benwtrent commented on code in PR #11860: URL: https://github.com/apache/lucene/pull/11860#discussion_r1025640458
########## lucene/core/src/java/org/apache/lucene/codecs/lucene95/Lucene95HnswVectorsWriter.java: ########## @@ -0,0 +1,751 @@ +/* + * 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 static org.apache.lucene.codecs.lucene95.Lucene95HnswVectorsFormat.DIRECT_MONOTONIC_BLOCK_SHIFT; +import static org.apache.lucene.search.DocIdSetIterator.NO_MORE_DOCS; + +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import org.apache.lucene.codecs.CodecUtil; +import org.apache.lucene.codecs.KnnFieldVectorsWriter; +import org.apache.lucene.codecs.KnnVectorsWriter; +import org.apache.lucene.codecs.lucene90.IndexedDISI; +import org.apache.lucene.index.*; +import org.apache.lucene.index.Sorter; +import org.apache.lucene.search.DocIdSetIterator; +import org.apache.lucene.store.IndexInput; +import org.apache.lucene.store.IndexOutput; +import org.apache.lucene.util.*; +import org.apache.lucene.util.hnsw.HnswGraph; +import org.apache.lucene.util.hnsw.HnswGraph.NodesIterator; +import org.apache.lucene.util.hnsw.HnswGraphBuilder; +import org.apache.lucene.util.hnsw.NeighborArray; +import org.apache.lucene.util.hnsw.OnHeapHnswGraph; +import org.apache.lucene.util.packed.DirectMonotonicWriter; + +/** + * Writes vector values and knn graphs to index segments. + * + * @lucene.experimental + */ +public final class Lucene95HnswVectorsWriter extends KnnVectorsWriter { + + private final SegmentWriteState segmentWriteState; + private final IndexOutput meta, vectorData, vectorIndex; + private final int M; + private final int beamWidth; + + private final List<FieldWriter<?>> fields = new ArrayList<>(); + private boolean finished; + + Lucene95HnswVectorsWriter(SegmentWriteState state, int M, int beamWidth) throws IOException { + this.M = M; + this.beamWidth = beamWidth; + segmentWriteState = state; + String metaFileName = + IndexFileNames.segmentFileName( + state.segmentInfo.name, state.segmentSuffix, Lucene95HnswVectorsFormat.META_EXTENSION); + + String vectorDataFileName = + IndexFileNames.segmentFileName( + state.segmentInfo.name, + state.segmentSuffix, + Lucene95HnswVectorsFormat.VECTOR_DATA_EXTENSION); + + String indexDataFileName = + IndexFileNames.segmentFileName( + state.segmentInfo.name, + state.segmentSuffix, + Lucene95HnswVectorsFormat.VECTOR_INDEX_EXTENSION); + boolean success = false; + try { + meta = state.directory.createOutput(metaFileName, state.context); + vectorData = state.directory.createOutput(vectorDataFileName, state.context); + vectorIndex = state.directory.createOutput(indexDataFileName, state.context); + + CodecUtil.writeIndexHeader( + meta, + Lucene95HnswVectorsFormat.META_CODEC_NAME, + Lucene95HnswVectorsFormat.VERSION_CURRENT, + state.segmentInfo.getId(), + state.segmentSuffix); + CodecUtil.writeIndexHeader( + vectorData, + Lucene95HnswVectorsFormat.VECTOR_DATA_CODEC_NAME, + Lucene95HnswVectorsFormat.VERSION_CURRENT, + state.segmentInfo.getId(), + state.segmentSuffix); + CodecUtil.writeIndexHeader( + vectorIndex, + Lucene95HnswVectorsFormat.VECTOR_INDEX_CODEC_NAME, + Lucene95HnswVectorsFormat.VERSION_CURRENT, + state.segmentInfo.getId(), + state.segmentSuffix); + success = true; + } finally { + if (success == false) { + IOUtils.closeWhileHandlingException(this); + } + } + } + + @Override + public KnnFieldVectorsWriter<?> addField(FieldInfo fieldInfo) throws IOException { + FieldWriter<?> newField = + FieldWriter.create(fieldInfo, M, beamWidth, segmentWriteState.infoStream); + fields.add(newField); + return newField; + } + + @Override + public void flush(int maxDoc, Sorter.DocMap sortMap) throws IOException { + for (FieldWriter<?> field : fields) { + if (sortMap == null) { + writeField(field, maxDoc); + } else { + writeSortingField(field, maxDoc, sortMap); + } + } + } + + @Override + public void finish() throws IOException { + if (finished) { + throw new IllegalStateException("already finished"); + } + finished = true; + + if (meta != null) { + // write end of fields marker + meta.writeInt(-1); + CodecUtil.writeFooter(meta); + } + if (vectorData != null) { + CodecUtil.writeFooter(vectorData); + CodecUtil.writeFooter(vectorIndex); + } + } + + @Override + public long ramBytesUsed() { + long total = 0; + for (FieldWriter<?> field : fields) { + total += field.ramBytesUsed(); + } + return total; + } + + private void writeField(FieldWriter<?> fieldData, int maxDoc) throws IOException { + // write vector values + long vectorDataOffset = vectorData.alignFilePointer(Float.BYTES); + switch (fieldData.fieldInfo.getVectorEncoding()) { + case BYTE -> writeByteVectors(fieldData); + case FLOAT32 -> writeFloat32Vectors(fieldData); + } + long vectorDataLength = vectorData.getFilePointer() - vectorDataOffset; + + // write graph + long vectorIndexOffset = vectorIndex.getFilePointer(); + OnHeapHnswGraph graph = fieldData.getGraph(); + int[][] graphLevelNodeOffsets = writeGraph(graph); + long vectorIndexLength = vectorIndex.getFilePointer() - vectorIndexOffset; + + writeMeta( + fieldData.fieldInfo, + maxDoc, + vectorDataOffset, + vectorDataLength, + vectorIndexOffset, + vectorIndexLength, + fieldData.docsWithField, + graph, + graphLevelNodeOffsets); + } + + private void writeFloat32Vectors(FieldWriter<?> fieldData) throws IOException { + final ByteBuffer buffer = + ByteBuffer.allocate(fieldData.dim * Float.BYTES).order(ByteOrder.LITTLE_ENDIAN); + final BytesRef binaryValue = new BytesRef(buffer.array()); + for (Object v : fieldData.vectors) { + buffer.asFloatBuffer().put((float[]) v); + vectorData.writeBytes(binaryValue.bytes, binaryValue.offset, binaryValue.length); + } + } + + private void writeByteVectors(FieldWriter<?> fieldData) throws IOException { + for (Object v : fieldData.vectors) { + BytesRef vector = (BytesRef) v; + vectorData.writeBytes(vector.bytes, vector.offset, vector.length); + } + } + + private void writeSortingField(FieldWriter<?> fieldData, int maxDoc, Sorter.DocMap sortMap) + throws IOException { + final int[] docIdOffsets = new int[sortMap.size()]; + int offset = 1; // 0 means no vector for this (field, document) + DocIdSetIterator iterator = fieldData.docsWithField.iterator(); + for (int docID = iterator.nextDoc(); + docID != DocIdSetIterator.NO_MORE_DOCS; + docID = iterator.nextDoc()) { + int newDocID = sortMap.oldToNew(docID); + docIdOffsets[newDocID] = offset++; + } + DocsWithFieldSet newDocsWithField = new DocsWithFieldSet(); + final int[] ordMap = new int[offset - 1]; // new ord to old ord + final int[] oldOrdMap = new int[offset - 1]; // old ord to new ord + int ord = 0; + int doc = 0; + for (int docIdOffset : docIdOffsets) { + if (docIdOffset != 0) { + ordMap[ord] = docIdOffset - 1; + oldOrdMap[docIdOffset - 1] = ord; + newDocsWithField.add(doc); + ord++; + } + doc++; + } + + // write vector values + long vectorDataOffset = + switch (fieldData.fieldInfo.getVectorEncoding()) { + case BYTE -> writeSortedByteVectors(fieldData, ordMap); + case FLOAT32 -> writeSortedFloat32Vectors(fieldData, ordMap); + }; + long vectorDataLength = vectorData.getFilePointer() - vectorDataOffset; + + // write graph + long vectorIndexOffset = vectorIndex.getFilePointer(); + OnHeapHnswGraph graph = fieldData.getGraph(); + int[][] graphLevelNodeOffsets = graph == null ? new int[0][] : new int[graph.numLevels()][]; + HnswGraph mockGraph = reconstructAndWriteGraph(graph, ordMap, oldOrdMap, graphLevelNodeOffsets); + long vectorIndexLength = vectorIndex.getFilePointer() - vectorIndexOffset; + + writeMeta( + fieldData.fieldInfo, + maxDoc, + vectorDataOffset, + vectorDataLength, + vectorIndexOffset, + vectorIndexLength, + newDocsWithField, + mockGraph, + graphLevelNodeOffsets); + } + + private long writeSortedFloat32Vectors(FieldWriter<?> fieldData, int[] ordMap) + throws IOException { + long vectorDataOffset = vectorData.alignFilePointer(Float.BYTES); + final ByteBuffer buffer = + ByteBuffer.allocate(fieldData.dim * Float.BYTES).order(ByteOrder.LITTLE_ENDIAN); + final BytesRef binaryValue = new BytesRef(buffer.array()); + for (int ordinal : ordMap) { + float[] vector = (float[]) fieldData.vectors.get(ordinal); + buffer.asFloatBuffer().put(vector); + vectorData.writeBytes(binaryValue.bytes, binaryValue.offset, binaryValue.length); + } + return vectorDataOffset; + } + + private long writeSortedByteVectors(FieldWriter<?> fieldData, int[] ordMap) throws IOException { + long vectorDataOffset = vectorData.alignFilePointer(Float.BYTES); + for (int ordinal : ordMap) { + BytesRef vector = (BytesRef) fieldData.vectors.get(ordinal); + vectorData.writeBytes(vector.bytes, vector.offset, vector.length); + } + return vectorDataOffset; + } + + /** + * Reconstructs the graph given the old and new node ids. + * + * <p>Additionally, the graph node connections are written to the vectorIndex. + * + * @param graph The current on heap graph + * @param newToOldMap the new node ids indexed to the old node ids + * @param oldToNewMap the old node ids indexed to the new node ids + * @param levelNodeOffsets where to place the new offsets for the nodes in the vector index. + * @return The graph + * @throws IOException if writing to vectorIndex fails + */ + private HnswGraph reconstructAndWriteGraph( + OnHeapHnswGraph graph, int[] newToOldMap, int[] oldToNewMap, int[][] levelNodeOffsets) + throws IOException { + if (graph == null) return null; + + List<int[]> nodesByLevel = new ArrayList<>(graph.numLevels()); + nodesByLevel.add(null); + + int maxOrd = graph.size(); + int maxConnOnLevel = M * 2; + NodesIterator nodesOnLevel0 = graph.getNodesOnLevel(0); + levelNodeOffsets[0] = new int[nodesOnLevel0.size()]; + while (nodesOnLevel0.hasNext()) { + int node = nodesOnLevel0.nextInt(); + NeighborArray neighbors = graph.getNeighbors(0, newToOldMap[node]); + long offset = vectorIndex.getFilePointer(); + reconstructAndWriteNeigbours(neighbors, oldToNewMap, maxConnOnLevel, maxOrd); + levelNodeOffsets[0][node] = Math.toIntExact(vectorIndex.getFilePointer() - offset); Review Comment: I am storing these offsets (non-cumulative) as `int`. This is mainly to reduce heap usage when writing a larger graph (with many nodes). For this to be larger than an `int` `M` would need to be close to `Integer.MAX_VALUE / 2`. This is an unrealistic, and I would think unsupported scenario. It effectively means that every node is directly connected to every node in the graph. I think they would run out of memory before getting to this point as we eagerly allocate `int[M]` for EVERY node already... ########## lucene/core/src/java/org/apache/lucene/codecs/lucene95/Lucene95HnswVectorsReader.java: ########## @@ -0,0 +1,497 @@ +/* + * 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 static org.apache.lucene.search.DocIdSetIterator.NO_MORE_DOCS; + +import java.io.IOException; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; +import org.apache.lucene.codecs.CodecUtil; +import org.apache.lucene.codecs.KnnVectorsReader; +import org.apache.lucene.index.*; +import org.apache.lucene.search.ScoreDoc; +import org.apache.lucene.search.TopDocs; +import org.apache.lucene.search.TotalHits; +import org.apache.lucene.store.ChecksumIndexInput; +import org.apache.lucene.store.DataInput; +import org.apache.lucene.store.IndexInput; +import org.apache.lucene.store.RandomAccessInput; +import org.apache.lucene.util.Bits; +import org.apache.lucene.util.IOUtils; +import org.apache.lucene.util.RamUsageEstimator; +import org.apache.lucene.util.hnsw.HnswGraph; +import org.apache.lucene.util.hnsw.HnswGraphSearcher; +import org.apache.lucene.util.hnsw.NeighborQueue; +import org.apache.lucene.util.packed.DirectMonotonicReader; + +/** + * Reads vectors from the index segments along with index data structures supporting KNN search. + * + * @lucene.experimental + */ +public final class Lucene95HnswVectorsReader extends KnnVectorsReader { + + private final FieldInfos fieldInfos; + private final Map<String, FieldEntry> fields = new HashMap<>(); + private final IndexInput vectorData; + private final IndexInput vectorIndex; + + Lucene95HnswVectorsReader(SegmentReadState state) throws IOException { + this.fieldInfos = state.fieldInfos; + int versionMeta = readMetadata(state); + boolean success = false; + try { + vectorData = + openDataInput( + state, + versionMeta, + Lucene95HnswVectorsFormat.VECTOR_DATA_EXTENSION, + Lucene95HnswVectorsFormat.VECTOR_DATA_CODEC_NAME); + vectorIndex = + openDataInput( + state, + versionMeta, + Lucene95HnswVectorsFormat.VECTOR_INDEX_EXTENSION, + Lucene95HnswVectorsFormat.VECTOR_INDEX_CODEC_NAME); + success = true; + } finally { + if (success == false) { + IOUtils.closeWhileHandlingException(this); + } + } + } + + private int readMetadata(SegmentReadState state) throws IOException { + String metaFileName = + IndexFileNames.segmentFileName( + state.segmentInfo.name, state.segmentSuffix, Lucene95HnswVectorsFormat.META_EXTENSION); + int versionMeta = -1; + try (ChecksumIndexInput meta = state.directory.openChecksumInput(metaFileName, state.context)) { + Throwable priorE = null; + try { + versionMeta = + CodecUtil.checkIndexHeader( + meta, + Lucene95HnswVectorsFormat.META_CODEC_NAME, + Lucene95HnswVectorsFormat.VERSION_START, + Lucene95HnswVectorsFormat.VERSION_CURRENT, + state.segmentInfo.getId(), + state.segmentSuffix); + readFields(meta, state.fieldInfos); + } catch (Throwable exception) { + priorE = exception; + } finally { + CodecUtil.checkFooter(meta, priorE); + } + } + return versionMeta; + } + + private static IndexInput openDataInput( + SegmentReadState state, int versionMeta, String fileExtension, String codecName) + throws IOException { + String fileName = + IndexFileNames.segmentFileName(state.segmentInfo.name, state.segmentSuffix, fileExtension); + IndexInput in = state.directory.openInput(fileName, state.context); + boolean success = false; + try { + int versionVectorData = + CodecUtil.checkIndexHeader( + in, + codecName, + Lucene95HnswVectorsFormat.VERSION_START, + Lucene95HnswVectorsFormat.VERSION_CURRENT, + state.segmentInfo.getId(), + state.segmentSuffix); + if (versionMeta != versionVectorData) { + throw new CorruptIndexException( + "Format versions mismatch: meta=" + + versionMeta + + ", " + + codecName + + "=" + + versionVectorData, + in); + } + CodecUtil.retrieveChecksum(in); + success = true; + return in; + } finally { + if (success == false) { + IOUtils.closeWhileHandlingException(in); + } + } + } + + private void readFields(ChecksumIndexInput meta, FieldInfos infos) throws IOException { + for (int fieldNumber = meta.readInt(); fieldNumber != -1; fieldNumber = meta.readInt()) { + FieldInfo info = infos.fieldInfo(fieldNumber); + if (info == null) { + throw new CorruptIndexException("Invalid field number: " + fieldNumber, meta); + } + FieldEntry fieldEntry = readField(meta); + validateFieldEntry(info, fieldEntry); + fields.put(info.name, fieldEntry); + } + } + + private void validateFieldEntry(FieldInfo info, FieldEntry fieldEntry) { + int dimension = info.getVectorDimension(); + if (dimension != fieldEntry.dimension) { + throw new IllegalStateException( + "Inconsistent vector dimension for field=\"" + + info.name + + "\"; " + + dimension + + " != " + + fieldEntry.dimension); + } + + int byteSize = + switch (info.getVectorEncoding()) { + case BYTE -> Byte.BYTES; + case FLOAT32 -> Float.BYTES; + }; + long vectorBytes = Math.multiplyExact((long) dimension, byteSize); + long numBytes = Math.multiplyExact(vectorBytes, fieldEntry.size); + if (numBytes != fieldEntry.vectorDataLength) { + throw new IllegalStateException( + "Vector data length " + + fieldEntry.vectorDataLength + + " not matching size=" + + fieldEntry.size + + " * dim=" + + dimension + + " * byteSize=" + + byteSize + + " = " + + numBytes); + } + } + + private VectorSimilarityFunction readSimilarityFunction(DataInput input) throws IOException { + int similarityFunctionId = input.readInt(); + if (similarityFunctionId < 0 + || similarityFunctionId >= VectorSimilarityFunction.values().length) { + throw new CorruptIndexException( + "Invalid similarity function id: " + similarityFunctionId, input); + } + return VectorSimilarityFunction.values()[similarityFunctionId]; + } + + private VectorEncoding readVectorEncoding(DataInput input) throws IOException { + int encodingId = input.readInt(); + if (encodingId < 0 || encodingId >= VectorEncoding.values().length) { + throw new CorruptIndexException("Invalid vector encoding id: " + encodingId, input); + } + return VectorEncoding.values()[encodingId]; + } + + private FieldEntry readField(IndexInput input) throws IOException { + VectorEncoding vectorEncoding = readVectorEncoding(input); + VectorSimilarityFunction similarityFunction = readSimilarityFunction(input); + return new FieldEntry(input, vectorEncoding, similarityFunction); + } + + @Override + public long ramBytesUsed() { + long totalBytes = RamUsageEstimator.shallowSizeOfInstance(Lucene95HnswVectorsFormat.class); + totalBytes += + RamUsageEstimator.sizeOfMap( + fields, RamUsageEstimator.shallowSizeOfInstance(FieldEntry.class)); + return totalBytes; + } + + @Override + public void checkIntegrity() throws IOException { + CodecUtil.checksumEntireFile(vectorData); + CodecUtil.checksumEntireFile(vectorIndex); + } + + @Override + public VectorValues getVectorValues(String field) throws IOException { + FieldEntry fieldEntry = fields.get(field); + VectorValues values = OffHeapVectorValues.load(fieldEntry, vectorData); + if (fieldEntry.vectorEncoding == VectorEncoding.BYTE) { + return new ExpandingVectorValues(values); + } else { + return values; + } + } + + @Override + public TopDocs search(String field, float[] target, int k, Bits acceptDocs, int visitedLimit) + throws IOException { + FieldEntry fieldEntry = fields.get(field); + + if (fieldEntry.size() == 0) { + return new TopDocs(new TotalHits(0, TotalHits.Relation.EQUAL_TO), new ScoreDoc[0]); + } + + // bound k by total number of vectors to prevent oversizing data structures + k = Math.min(k, fieldEntry.size()); + OffHeapVectorValues vectorValues = OffHeapVectorValues.load(fieldEntry, vectorData); + + NeighborQueue results = + HnswGraphSearcher.search( + target, + k, + vectorValues, + fieldEntry.vectorEncoding, + fieldEntry.similarityFunction, + getGraph(fieldEntry), + vectorValues.getAcceptOrds(acceptDocs), + visitedLimit); + + int i = 0; + ScoreDoc[] scoreDocs = new ScoreDoc[Math.min(results.size(), k)]; + while (results.size() > 0) { + int node = results.topNode(); + float score = results.topScore(); + results.pop(); + scoreDocs[scoreDocs.length - ++i] = new ScoreDoc(vectorValues.ordToDoc(node), score); + } + + TotalHits.Relation relation = + results.incomplete() + ? TotalHits.Relation.GREATER_THAN_OR_EQUAL_TO + : TotalHits.Relation.EQUAL_TO; + return new TopDocs(new TotalHits(results.visitedCount(), relation), scoreDocs); + } + + /** Get knn graph values; used for testing */ + public HnswGraph getGraph(String field) throws IOException { + FieldInfo info = fieldInfos.fieldInfo(field); + if (info == null) { + throw new IllegalArgumentException("No such field '" + field + "'"); + } + FieldEntry entry = fields.get(field); + if (entry != null && entry.vectorIndexLength > 0) { + return getGraph(entry); + } else { + return HnswGraph.EMPTY; + } + } + + private HnswGraph getGraph(FieldEntry entry) throws IOException { + return new OffHeapHnswGraph(entry, vectorIndex); + } + + @Override + public void close() throws IOException { + IOUtils.close(vectorData, vectorIndex); + } + + static class FieldEntry { + + final VectorSimilarityFunction similarityFunction; + final VectorEncoding vectorEncoding; + final long vectorDataOffset; + final long vectorDataLength; + final long vectorIndexOffset; + final long vectorIndexLength; + final int M; + final int numLevels; + final int dimension; + final int size; + final int[][] nodesByLevel; + // for each level the start offsets in vectorIndex file from where to read neighbours + final DirectMonotonicReader.Meta offsetsMeta; + final long offsetsOffset; + final int offsetsBlockShift; + final long offsetsLength; + + // the following four variables used to read docIds encoded by IndexDISI + // special values of docsWithFieldOffset are -1 and -2 + // -1 : dense + // -2 : empty + // other: sparse + final long docsWithFieldOffset; + final long docsWithFieldLength; + final short jumpTableEntryCount; + final byte denseRankPower; + + // the following four variables used to read ordToDoc encoded by DirectMonotonicWriter + // note that only spare case needs to store ordToDoc + final long addressesOffset; + final int blockShift; + final DirectMonotonicReader.Meta meta; + final long addressesLength; + + FieldEntry( + IndexInput input, + VectorEncoding vectorEncoding, + VectorSimilarityFunction similarityFunction) + throws IOException { + this.similarityFunction = similarityFunction; + this.vectorEncoding = vectorEncoding; + vectorDataOffset = input.readVLong(); + vectorDataLength = input.readVLong(); + vectorIndexOffset = input.readVLong(); + vectorIndexLength = input.readVLong(); + dimension = input.readVInt(); + size = input.readInt(); + + docsWithFieldOffset = input.readLong(); + docsWithFieldLength = input.readLong(); + jumpTableEntryCount = input.readShort(); + denseRankPower = input.readByte(); + + // dense or empty + if (docsWithFieldOffset == -1 || docsWithFieldOffset == -2) { + addressesOffset = 0; + blockShift = 0; + meta = null; + addressesLength = 0; + } else { + // sparse + addressesOffset = input.readLong(); + blockShift = input.readVInt(); + meta = DirectMonotonicReader.loadMeta(input, size, blockShift); + addressesLength = input.readLong(); + } + + // read nodes by level + M = input.readVInt(); + numLevels = input.readVInt(); + nodesByLevel = new int[numLevels][]; + long numberOfOffsets = 0; + for (int level = 0; level < numLevels; level++) { + if (level > 0) { + int numNodesOnLevel = input.readVInt(); + numberOfOffsets += numNodesOnLevel; + nodesByLevel[level] = new int[numNodesOnLevel]; + for (int i = 0; i < numNodesOnLevel; i++) { + nodesByLevel[level][i] = input.readInt(); + } + } else { + numberOfOffsets += size; + } + } + if (numberOfOffsets > 0) { + offsetsOffset = input.readLong(); + offsetsBlockShift = input.readVInt(); + offsetsMeta = DirectMonotonicReader.loadMeta(input, numberOfOffsets, offsetsBlockShift); + offsetsLength = input.readLong(); + } else { + offsetsOffset = 0; + offsetsBlockShift = 0; + offsetsMeta = null; + offsetsLength = 0; + } + } + + int size() { + return size; + } + } + + /** Read the nearest-neighbors graph from the index input */ + private static final class OffHeapHnswGraph extends HnswGraph { + + final IndexInput dataIn; + final int[][] nodesByLevel; + final int numLevels; + final int entryNode; + final int size; + int arcCount; + int arcUpTo; + int arc; + private final DirectMonotonicReader graphLevelNodeOffsets; + private final long[] graphLevelNodeIndexOffsets; + // Allocated to be M*2 to track the current neighbors being explored + private final int[] currentNeighborsBuffer; + + OffHeapHnswGraph(FieldEntry entry, IndexInput vectorIndex) throws IOException { + this.dataIn = + vectorIndex.slice("graph-data", entry.vectorIndexOffset, entry.vectorIndexLength); + this.nodesByLevel = entry.nodesByLevel; + this.numLevels = entry.numLevels; + this.entryNode = numLevels > 1 ? nodesByLevel[numLevels - 1][0] : 0; + this.size = entry.size(); + final RandomAccessInput addressesData = + vectorIndex.randomAccessSlice(entry.offsetsOffset, entry.offsetsLength); + this.graphLevelNodeOffsets = + DirectMonotonicReader.getInstance(entry.offsetsMeta, addressesData); + this.currentNeighborsBuffer = new int[entry.M * 2]; + graphLevelNodeIndexOffsets = new long[numLevels]; + graphLevelNodeIndexOffsets[0] = 0; + for (int i = 1; i < numLevels; i++) { + // nodesByLevel is `null` for the zeroth level as we know its the size + int nodeCount = nodesByLevel[i - 1] == null ? size : nodesByLevel[i - 1].length; + graphLevelNodeIndexOffsets[i] = graphLevelNodeIndexOffsets[i - 1] + nodeCount; + } Review Comment: This gives us a nice cumulative indexed offset to use later when grabbing a nodes memory offset for its connections. ########## lucene/core/src/java/org/apache/lucene/codecs/lucene95/Lucene95HnswVectorsReader.java: ########## @@ -0,0 +1,497 @@ +/* + * 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 static org.apache.lucene.search.DocIdSetIterator.NO_MORE_DOCS; + +import java.io.IOException; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; +import org.apache.lucene.codecs.CodecUtil; +import org.apache.lucene.codecs.KnnVectorsReader; +import org.apache.lucene.index.*; +import org.apache.lucene.search.ScoreDoc; +import org.apache.lucene.search.TopDocs; +import org.apache.lucene.search.TotalHits; +import org.apache.lucene.store.ChecksumIndexInput; +import org.apache.lucene.store.DataInput; +import org.apache.lucene.store.IndexInput; +import org.apache.lucene.store.RandomAccessInput; +import org.apache.lucene.util.Bits; +import org.apache.lucene.util.IOUtils; +import org.apache.lucene.util.RamUsageEstimator; +import org.apache.lucene.util.hnsw.HnswGraph; +import org.apache.lucene.util.hnsw.HnswGraphSearcher; +import org.apache.lucene.util.hnsw.NeighborQueue; +import org.apache.lucene.util.packed.DirectMonotonicReader; + +/** + * Reads vectors from the index segments along with index data structures supporting KNN search. + * + * @lucene.experimental + */ +public final class Lucene95HnswVectorsReader extends KnnVectorsReader { + + private final FieldInfos fieldInfos; + private final Map<String, FieldEntry> fields = new HashMap<>(); + private final IndexInput vectorData; + private final IndexInput vectorIndex; + + Lucene95HnswVectorsReader(SegmentReadState state) throws IOException { + this.fieldInfos = state.fieldInfos; + int versionMeta = readMetadata(state); + boolean success = false; + try { + vectorData = + openDataInput( + state, + versionMeta, + Lucene95HnswVectorsFormat.VECTOR_DATA_EXTENSION, + Lucene95HnswVectorsFormat.VECTOR_DATA_CODEC_NAME); + vectorIndex = + openDataInput( + state, + versionMeta, + Lucene95HnswVectorsFormat.VECTOR_INDEX_EXTENSION, + Lucene95HnswVectorsFormat.VECTOR_INDEX_CODEC_NAME); + success = true; + } finally { + if (success == false) { + IOUtils.closeWhileHandlingException(this); + } + } + } + + private int readMetadata(SegmentReadState state) throws IOException { + String metaFileName = + IndexFileNames.segmentFileName( + state.segmentInfo.name, state.segmentSuffix, Lucene95HnswVectorsFormat.META_EXTENSION); + int versionMeta = -1; + try (ChecksumIndexInput meta = state.directory.openChecksumInput(metaFileName, state.context)) { + Throwable priorE = null; + try { + versionMeta = + CodecUtil.checkIndexHeader( + meta, + Lucene95HnswVectorsFormat.META_CODEC_NAME, + Lucene95HnswVectorsFormat.VERSION_START, + Lucene95HnswVectorsFormat.VERSION_CURRENT, + state.segmentInfo.getId(), + state.segmentSuffix); + readFields(meta, state.fieldInfos); + } catch (Throwable exception) { + priorE = exception; + } finally { + CodecUtil.checkFooter(meta, priorE); + } + } + return versionMeta; + } + + private static IndexInput openDataInput( + SegmentReadState state, int versionMeta, String fileExtension, String codecName) + throws IOException { + String fileName = + IndexFileNames.segmentFileName(state.segmentInfo.name, state.segmentSuffix, fileExtension); + IndexInput in = state.directory.openInput(fileName, state.context); + boolean success = false; + try { + int versionVectorData = + CodecUtil.checkIndexHeader( + in, + codecName, + Lucene95HnswVectorsFormat.VERSION_START, + Lucene95HnswVectorsFormat.VERSION_CURRENT, + state.segmentInfo.getId(), + state.segmentSuffix); + if (versionMeta != versionVectorData) { + throw new CorruptIndexException( + "Format versions mismatch: meta=" + + versionMeta + + ", " + + codecName + + "=" + + versionVectorData, + in); + } + CodecUtil.retrieveChecksum(in); + success = true; + return in; + } finally { + if (success == false) { + IOUtils.closeWhileHandlingException(in); + } + } + } + + private void readFields(ChecksumIndexInput meta, FieldInfos infos) throws IOException { + for (int fieldNumber = meta.readInt(); fieldNumber != -1; fieldNumber = meta.readInt()) { + FieldInfo info = infos.fieldInfo(fieldNumber); + if (info == null) { + throw new CorruptIndexException("Invalid field number: " + fieldNumber, meta); + } + FieldEntry fieldEntry = readField(meta); + validateFieldEntry(info, fieldEntry); + fields.put(info.name, fieldEntry); + } + } + + private void validateFieldEntry(FieldInfo info, FieldEntry fieldEntry) { + int dimension = info.getVectorDimension(); + if (dimension != fieldEntry.dimension) { + throw new IllegalStateException( + "Inconsistent vector dimension for field=\"" + + info.name + + "\"; " + + dimension + + " != " + + fieldEntry.dimension); + } + + int byteSize = + switch (info.getVectorEncoding()) { + case BYTE -> Byte.BYTES; + case FLOAT32 -> Float.BYTES; + }; + long vectorBytes = Math.multiplyExact((long) dimension, byteSize); + long numBytes = Math.multiplyExact(vectorBytes, fieldEntry.size); + if (numBytes != fieldEntry.vectorDataLength) { + throw new IllegalStateException( + "Vector data length " + + fieldEntry.vectorDataLength + + " not matching size=" + + fieldEntry.size + + " * dim=" + + dimension + + " * byteSize=" + + byteSize + + " = " + + numBytes); + } + } + + private VectorSimilarityFunction readSimilarityFunction(DataInput input) throws IOException { + int similarityFunctionId = input.readInt(); + if (similarityFunctionId < 0 + || similarityFunctionId >= VectorSimilarityFunction.values().length) { + throw new CorruptIndexException( + "Invalid similarity function id: " + similarityFunctionId, input); + } + return VectorSimilarityFunction.values()[similarityFunctionId]; + } + + private VectorEncoding readVectorEncoding(DataInput input) throws IOException { + int encodingId = input.readInt(); + if (encodingId < 0 || encodingId >= VectorEncoding.values().length) { + throw new CorruptIndexException("Invalid vector encoding id: " + encodingId, input); + } + return VectorEncoding.values()[encodingId]; + } + + private FieldEntry readField(IndexInput input) throws IOException { + VectorEncoding vectorEncoding = readVectorEncoding(input); + VectorSimilarityFunction similarityFunction = readSimilarityFunction(input); + return new FieldEntry(input, vectorEncoding, similarityFunction); + } + + @Override + public long ramBytesUsed() { + long totalBytes = RamUsageEstimator.shallowSizeOfInstance(Lucene95HnswVectorsFormat.class); + totalBytes += + RamUsageEstimator.sizeOfMap( + fields, RamUsageEstimator.shallowSizeOfInstance(FieldEntry.class)); + return totalBytes; + } + + @Override + public void checkIntegrity() throws IOException { + CodecUtil.checksumEntireFile(vectorData); + CodecUtil.checksumEntireFile(vectorIndex); + } + + @Override + public VectorValues getVectorValues(String field) throws IOException { + FieldEntry fieldEntry = fields.get(field); + VectorValues values = OffHeapVectorValues.load(fieldEntry, vectorData); + if (fieldEntry.vectorEncoding == VectorEncoding.BYTE) { + return new ExpandingVectorValues(values); + } else { + return values; + } + } + + @Override + public TopDocs search(String field, float[] target, int k, Bits acceptDocs, int visitedLimit) + throws IOException { + FieldEntry fieldEntry = fields.get(field); + + if (fieldEntry.size() == 0) { + return new TopDocs(new TotalHits(0, TotalHits.Relation.EQUAL_TO), new ScoreDoc[0]); + } + + // bound k by total number of vectors to prevent oversizing data structures + k = Math.min(k, fieldEntry.size()); + OffHeapVectorValues vectorValues = OffHeapVectorValues.load(fieldEntry, vectorData); + + NeighborQueue results = + HnswGraphSearcher.search( + target, + k, + vectorValues, + fieldEntry.vectorEncoding, + fieldEntry.similarityFunction, + getGraph(fieldEntry), + vectorValues.getAcceptOrds(acceptDocs), + visitedLimit); + + int i = 0; + ScoreDoc[] scoreDocs = new ScoreDoc[Math.min(results.size(), k)]; + while (results.size() > 0) { + int node = results.topNode(); + float score = results.topScore(); + results.pop(); + scoreDocs[scoreDocs.length - ++i] = new ScoreDoc(vectorValues.ordToDoc(node), score); + } + + TotalHits.Relation relation = + results.incomplete() + ? TotalHits.Relation.GREATER_THAN_OR_EQUAL_TO + : TotalHits.Relation.EQUAL_TO; + return new TopDocs(new TotalHits(results.visitedCount(), relation), scoreDocs); + } + + /** Get knn graph values; used for testing */ + public HnswGraph getGraph(String field) throws IOException { + FieldInfo info = fieldInfos.fieldInfo(field); + if (info == null) { + throw new IllegalArgumentException("No such field '" + field + "'"); + } + FieldEntry entry = fields.get(field); + if (entry != null && entry.vectorIndexLength > 0) { + return getGraph(entry); + } else { + return HnswGraph.EMPTY; + } + } + + private HnswGraph getGraph(FieldEntry entry) throws IOException { + return new OffHeapHnswGraph(entry, vectorIndex); + } + + @Override + public void close() throws IOException { + IOUtils.close(vectorData, vectorIndex); + } + + static class FieldEntry { + + final VectorSimilarityFunction similarityFunction; + final VectorEncoding vectorEncoding; + final long vectorDataOffset; + final long vectorDataLength; + final long vectorIndexOffset; + final long vectorIndexLength; + final int M; + final int numLevels; + final int dimension; + final int size; + final int[][] nodesByLevel; + // for each level the start offsets in vectorIndex file from where to read neighbours + final DirectMonotonicReader.Meta offsetsMeta; + final long offsetsOffset; + final int offsetsBlockShift; + final long offsetsLength; + + // the following four variables used to read docIds encoded by IndexDISI + // special values of docsWithFieldOffset are -1 and -2 + // -1 : dense + // -2 : empty + // other: sparse + final long docsWithFieldOffset; + final long docsWithFieldLength; + final short jumpTableEntryCount; + final byte denseRankPower; + + // the following four variables used to read ordToDoc encoded by DirectMonotonicWriter + // note that only spare case needs to store ordToDoc + final long addressesOffset; + final int blockShift; + final DirectMonotonicReader.Meta meta; + final long addressesLength; + + FieldEntry( + IndexInput input, + VectorEncoding vectorEncoding, + VectorSimilarityFunction similarityFunction) + throws IOException { + this.similarityFunction = similarityFunction; + this.vectorEncoding = vectorEncoding; + vectorDataOffset = input.readVLong(); + vectorDataLength = input.readVLong(); + vectorIndexOffset = input.readVLong(); + vectorIndexLength = input.readVLong(); + dimension = input.readVInt(); + size = input.readInt(); + + docsWithFieldOffset = input.readLong(); + docsWithFieldLength = input.readLong(); + jumpTableEntryCount = input.readShort(); + denseRankPower = input.readByte(); + + // dense or empty + if (docsWithFieldOffset == -1 || docsWithFieldOffset == -2) { + addressesOffset = 0; + blockShift = 0; + meta = null; + addressesLength = 0; + } else { + // sparse + addressesOffset = input.readLong(); + blockShift = input.readVInt(); + meta = DirectMonotonicReader.loadMeta(input, size, blockShift); + addressesLength = input.readLong(); + } + + // read nodes by level + M = input.readVInt(); + numLevels = input.readVInt(); + nodesByLevel = new int[numLevels][]; + long numberOfOffsets = 0; + for (int level = 0; level < numLevels; level++) { + if (level > 0) { + int numNodesOnLevel = input.readVInt(); + numberOfOffsets += numNodesOnLevel; + nodesByLevel[level] = new int[numNodesOnLevel]; + for (int i = 0; i < numNodesOnLevel; i++) { + nodesByLevel[level][i] = input.readInt(); + } + } else { + numberOfOffsets += size; + } + } Review Comment: Here are some changes. Now on the Writer, we don't write the level 0 nodes at all. We never used that value anyways, so I chose not to write it (seemed wasteful). Additionally, `numLevels`, `M`, `numNodesOnLevel` are all `VInt`. Typically, graphs have "few" levels (<256 almost definitely < 65K). Additionally, as levels increase, teh number of nodes there decreases, so storing those as VInt made sense to me. I am tracking the offsets here as we need to know the offset for each node on each layer. Remember, a node can be on multiple layers ########## lucene/core/src/java/org/apache/lucene/codecs/lucene95/Lucene95HnswVectorsWriter.java: ########## @@ -0,0 +1,751 @@ +/* + * 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 static org.apache.lucene.codecs.lucene95.Lucene95HnswVectorsFormat.DIRECT_MONOTONIC_BLOCK_SHIFT; +import static org.apache.lucene.search.DocIdSetIterator.NO_MORE_DOCS; + +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import org.apache.lucene.codecs.CodecUtil; +import org.apache.lucene.codecs.KnnFieldVectorsWriter; +import org.apache.lucene.codecs.KnnVectorsWriter; +import org.apache.lucene.codecs.lucene90.IndexedDISI; +import org.apache.lucene.index.*; +import org.apache.lucene.index.Sorter; +import org.apache.lucene.search.DocIdSetIterator; +import org.apache.lucene.store.IndexInput; +import org.apache.lucene.store.IndexOutput; +import org.apache.lucene.util.*; +import org.apache.lucene.util.hnsw.HnswGraph; +import org.apache.lucene.util.hnsw.HnswGraph.NodesIterator; +import org.apache.lucene.util.hnsw.HnswGraphBuilder; +import org.apache.lucene.util.hnsw.NeighborArray; +import org.apache.lucene.util.hnsw.OnHeapHnswGraph; +import org.apache.lucene.util.packed.DirectMonotonicWriter; + +/** + * Writes vector values and knn graphs to index segments. + * + * @lucene.experimental + */ +public final class Lucene95HnswVectorsWriter extends KnnVectorsWriter { + + private final SegmentWriteState segmentWriteState; + private final IndexOutput meta, vectorData, vectorIndex; + private final int M; + private final int beamWidth; + + private final List<FieldWriter<?>> fields = new ArrayList<>(); + private boolean finished; + + Lucene95HnswVectorsWriter(SegmentWriteState state, int M, int beamWidth) throws IOException { + this.M = M; + this.beamWidth = beamWidth; + segmentWriteState = state; + String metaFileName = + IndexFileNames.segmentFileName( + state.segmentInfo.name, state.segmentSuffix, Lucene95HnswVectorsFormat.META_EXTENSION); + + String vectorDataFileName = + IndexFileNames.segmentFileName( + state.segmentInfo.name, + state.segmentSuffix, + Lucene95HnswVectorsFormat.VECTOR_DATA_EXTENSION); + + String indexDataFileName = + IndexFileNames.segmentFileName( + state.segmentInfo.name, + state.segmentSuffix, + Lucene95HnswVectorsFormat.VECTOR_INDEX_EXTENSION); + boolean success = false; + try { + meta = state.directory.createOutput(metaFileName, state.context); + vectorData = state.directory.createOutput(vectorDataFileName, state.context); + vectorIndex = state.directory.createOutput(indexDataFileName, state.context); + + CodecUtil.writeIndexHeader( + meta, + Lucene95HnswVectorsFormat.META_CODEC_NAME, + Lucene95HnswVectorsFormat.VERSION_CURRENT, + state.segmentInfo.getId(), + state.segmentSuffix); + CodecUtil.writeIndexHeader( + vectorData, + Lucene95HnswVectorsFormat.VECTOR_DATA_CODEC_NAME, + Lucene95HnswVectorsFormat.VERSION_CURRENT, + state.segmentInfo.getId(), + state.segmentSuffix); + CodecUtil.writeIndexHeader( + vectorIndex, + Lucene95HnswVectorsFormat.VECTOR_INDEX_CODEC_NAME, + Lucene95HnswVectorsFormat.VERSION_CURRENT, + state.segmentInfo.getId(), + state.segmentSuffix); + success = true; + } finally { + if (success == false) { + IOUtils.closeWhileHandlingException(this); + } + } + } + + @Override + public KnnFieldVectorsWriter<?> addField(FieldInfo fieldInfo) throws IOException { + FieldWriter<?> newField = + FieldWriter.create(fieldInfo, M, beamWidth, segmentWriteState.infoStream); + fields.add(newField); + return newField; + } + + @Override + public void flush(int maxDoc, Sorter.DocMap sortMap) throws IOException { + for (FieldWriter<?> field : fields) { + if (sortMap == null) { + writeField(field, maxDoc); + } else { + writeSortingField(field, maxDoc, sortMap); + } + } + } + + @Override + public void finish() throws IOException { + if (finished) { + throw new IllegalStateException("already finished"); + } + finished = true; + + if (meta != null) { + // write end of fields marker + meta.writeInt(-1); + CodecUtil.writeFooter(meta); + } + if (vectorData != null) { + CodecUtil.writeFooter(vectorData); + CodecUtil.writeFooter(vectorIndex); + } + } + + @Override + public long ramBytesUsed() { + long total = 0; + for (FieldWriter<?> field : fields) { + total += field.ramBytesUsed(); + } + return total; + } + + private void writeField(FieldWriter<?> fieldData, int maxDoc) throws IOException { + // write vector values + long vectorDataOffset = vectorData.alignFilePointer(Float.BYTES); + switch (fieldData.fieldInfo.getVectorEncoding()) { + case BYTE -> writeByteVectors(fieldData); + case FLOAT32 -> writeFloat32Vectors(fieldData); + } + long vectorDataLength = vectorData.getFilePointer() - vectorDataOffset; + + // write graph + long vectorIndexOffset = vectorIndex.getFilePointer(); + OnHeapHnswGraph graph = fieldData.getGraph(); + int[][] graphLevelNodeOffsets = writeGraph(graph); + long vectorIndexLength = vectorIndex.getFilePointer() - vectorIndexOffset; + + writeMeta( + fieldData.fieldInfo, + maxDoc, + vectorDataOffset, + vectorDataLength, + vectorIndexOffset, + vectorIndexLength, + fieldData.docsWithField, + graph, + graphLevelNodeOffsets); + } + + private void writeFloat32Vectors(FieldWriter<?> fieldData) throws IOException { + final ByteBuffer buffer = + ByteBuffer.allocate(fieldData.dim * Float.BYTES).order(ByteOrder.LITTLE_ENDIAN); + final BytesRef binaryValue = new BytesRef(buffer.array()); + for (Object v : fieldData.vectors) { + buffer.asFloatBuffer().put((float[]) v); + vectorData.writeBytes(binaryValue.bytes, binaryValue.offset, binaryValue.length); + } + } + + private void writeByteVectors(FieldWriter<?> fieldData) throws IOException { + for (Object v : fieldData.vectors) { + BytesRef vector = (BytesRef) v; + vectorData.writeBytes(vector.bytes, vector.offset, vector.length); + } + } + + private void writeSortingField(FieldWriter<?> fieldData, int maxDoc, Sorter.DocMap sortMap) + throws IOException { + final int[] docIdOffsets = new int[sortMap.size()]; + int offset = 1; // 0 means no vector for this (field, document) + DocIdSetIterator iterator = fieldData.docsWithField.iterator(); + for (int docID = iterator.nextDoc(); + docID != DocIdSetIterator.NO_MORE_DOCS; + docID = iterator.nextDoc()) { + int newDocID = sortMap.oldToNew(docID); + docIdOffsets[newDocID] = offset++; + } + DocsWithFieldSet newDocsWithField = new DocsWithFieldSet(); + final int[] ordMap = new int[offset - 1]; // new ord to old ord + final int[] oldOrdMap = new int[offset - 1]; // old ord to new ord + int ord = 0; + int doc = 0; + for (int docIdOffset : docIdOffsets) { + if (docIdOffset != 0) { + ordMap[ord] = docIdOffset - 1; + oldOrdMap[docIdOffset - 1] = ord; + newDocsWithField.add(doc); + ord++; + } + doc++; + } + + // write vector values + long vectorDataOffset = + switch (fieldData.fieldInfo.getVectorEncoding()) { + case BYTE -> writeSortedByteVectors(fieldData, ordMap); + case FLOAT32 -> writeSortedFloat32Vectors(fieldData, ordMap); + }; + long vectorDataLength = vectorData.getFilePointer() - vectorDataOffset; + + // write graph + long vectorIndexOffset = vectorIndex.getFilePointer(); + OnHeapHnswGraph graph = fieldData.getGraph(); + int[][] graphLevelNodeOffsets = graph == null ? new int[0][] : new int[graph.numLevels()][]; + HnswGraph mockGraph = reconstructAndWriteGraph(graph, ordMap, oldOrdMap, graphLevelNodeOffsets); + long vectorIndexLength = vectorIndex.getFilePointer() - vectorIndexOffset; + + writeMeta( + fieldData.fieldInfo, + maxDoc, + vectorDataOffset, + vectorDataLength, + vectorIndexOffset, + vectorIndexLength, + newDocsWithField, + mockGraph, + graphLevelNodeOffsets); + } + + private long writeSortedFloat32Vectors(FieldWriter<?> fieldData, int[] ordMap) + throws IOException { + long vectorDataOffset = vectorData.alignFilePointer(Float.BYTES); + final ByteBuffer buffer = + ByteBuffer.allocate(fieldData.dim * Float.BYTES).order(ByteOrder.LITTLE_ENDIAN); + final BytesRef binaryValue = new BytesRef(buffer.array()); + for (int ordinal : ordMap) { + float[] vector = (float[]) fieldData.vectors.get(ordinal); + buffer.asFloatBuffer().put(vector); + vectorData.writeBytes(binaryValue.bytes, binaryValue.offset, binaryValue.length); + } + return vectorDataOffset; + } + + private long writeSortedByteVectors(FieldWriter<?> fieldData, int[] ordMap) throws IOException { + long vectorDataOffset = vectorData.alignFilePointer(Float.BYTES); + for (int ordinal : ordMap) { + BytesRef vector = (BytesRef) fieldData.vectors.get(ordinal); + vectorData.writeBytes(vector.bytes, vector.offset, vector.length); + } + return vectorDataOffset; + } + + /** + * Reconstructs the graph given the old and new node ids. + * + * <p>Additionally, the graph node connections are written to the vectorIndex. + * + * @param graph The current on heap graph + * @param newToOldMap the new node ids indexed to the old node ids + * @param oldToNewMap the old node ids indexed to the new node ids + * @param levelNodeOffsets where to place the new offsets for the nodes in the vector index. + * @return The graph + * @throws IOException if writing to vectorIndex fails + */ + private HnswGraph reconstructAndWriteGraph( + OnHeapHnswGraph graph, int[] newToOldMap, int[] oldToNewMap, int[][] levelNodeOffsets) + throws IOException { + if (graph == null) return null; + + List<int[]> nodesByLevel = new ArrayList<>(graph.numLevels()); + nodesByLevel.add(null); + + int maxOrd = graph.size(); + int maxConnOnLevel = M * 2; + NodesIterator nodesOnLevel0 = graph.getNodesOnLevel(0); + levelNodeOffsets[0] = new int[nodesOnLevel0.size()]; + while (nodesOnLevel0.hasNext()) { + int node = nodesOnLevel0.nextInt(); + NeighborArray neighbors = graph.getNeighbors(0, newToOldMap[node]); + long offset = vectorIndex.getFilePointer(); + reconstructAndWriteNeigbours(neighbors, oldToNewMap, maxConnOnLevel, maxOrd); + levelNodeOffsets[0][node] = Math.toIntExact(vectorIndex.getFilePointer() - offset); + } + + maxConnOnLevel = M; + for (int level = 1; level < graph.numLevels(); level++) { + NodesIterator nodesOnLevel = graph.getNodesOnLevel(level); + int[] newNodes = new int[nodesOnLevel.size()]; + int n = 0; + while (nodesOnLevel.hasNext()) { + newNodes[n++] = oldToNewMap[nodesOnLevel.nextInt()]; + } + Arrays.sort(newNodes); + nodesByLevel.add(newNodes); + levelNodeOffsets[level] = new int[newNodes.length]; + int nodeOffsetIndex = 0; + for (int node : newNodes) { + NeighborArray neighbors = graph.getNeighbors(level, newToOldMap[node]); + long offset = vectorIndex.getFilePointer(); + reconstructAndWriteNeigbours(neighbors, oldToNewMap, maxConnOnLevel, maxOrd); + levelNodeOffsets[level][nodeOffsetIndex++] = + Math.toIntExact(vectorIndex.getFilePointer() - offset); + } + } + return new HnswGraph() { + @Override + public int nextNeighbor() { + throw new UnsupportedOperationException("Not supported on a mock graph"); + } + + @Override + public void seek(int level, int target) { + throw new UnsupportedOperationException("Not supported on a mock graph"); + } + + @Override + public int size() { + return graph.size(); + } + + @Override + public int numLevels() { + return graph.numLevels(); + } + + @Override + public int entryNode() { + throw new UnsupportedOperationException("Not supported on a mock graph"); + } + + @Override + public NodesIterator getNodesOnLevel(int level) { + if (level == 0) { + return graph.getNodesOnLevel(0); + } else { + return new NodesIterator(nodesByLevel.get(level), nodesByLevel.get(level).length); + } + } + }; + } + + private void reconstructAndWriteNeigbours( + NeighborArray neighbors, int[] oldToNewMap, int maxConnOnLevel, int maxOrd) + throws IOException { + int size = neighbors.size(); + vectorIndex.writeVInt(size); + + // Destructively modify; it's ok we are discarding it after this + int[] nnodes = neighbors.node(); + for (int i = 0; i < size; i++) { + nnodes[i] = oldToNewMap[nnodes[i]]; + } + Arrays.sort(nnodes, 0, size); + // Now that we have sorted, do delta encoding to minimize the required bits to store the + // information + for (int i = size - 1; i > 0; --i) { + assert nnodes[i] < maxOrd : "node too large: " + nnodes[i] + ">=" + maxOrd; + nnodes[i] -= nnodes[i - 1]; + } + for (int i = 0; i < size; i++) { + vectorIndex.writeVInt(nnodes[i]); + } + } + + @Override + public void mergeOneField(FieldInfo fieldInfo, MergeState mergeState) throws IOException { + long vectorDataOffset = vectorData.alignFilePointer(Float.BYTES); + VectorValues vectors = MergedVectorValues.mergeVectorValues(fieldInfo, mergeState); + + IndexOutput tempVectorData = + segmentWriteState.directory.createTempOutput( + vectorData.getName(), "temp", segmentWriteState.context); + IndexInput vectorDataInput = null; + boolean success = false; + try { + // write the vector data to a temporary file + DocsWithFieldSet docsWithField = + writeVectorData(tempVectorData, vectors, fieldInfo.getVectorEncoding().byteSize); + CodecUtil.writeFooter(tempVectorData); + IOUtils.close(tempVectorData); + + // copy the temporary file vectors to the actual data file + vectorDataInput = + segmentWriteState.directory.openInput( + tempVectorData.getName(), segmentWriteState.context); + vectorData.copyBytes(vectorDataInput, vectorDataInput.length() - CodecUtil.footerLength()); + CodecUtil.retrieveChecksum(vectorDataInput); + long vectorDataLength = vectorData.getFilePointer() - vectorDataOffset; + long vectorIndexOffset = vectorIndex.getFilePointer(); + // build the graph using the temporary vector data + // we use Lucene95HnswVectorsReader.DenseOffHeapVectorValues for the graph construction + // doesn't need to know docIds + // TODO: separate random access vector values from DocIdSetIterator? + int byteSize = vectors.dimension() * fieldInfo.getVectorEncoding().byteSize; + OffHeapVectorValues offHeapVectors = + new OffHeapVectorValues.DenseOffHeapVectorValues( + vectors.dimension(), docsWithField.cardinality(), vectorDataInput, byteSize); + OnHeapHnswGraph graph = null; + int[][] vectorIndexNodeOffsets = null; + if (offHeapVectors.size() != 0) { + // build graph + HnswGraphBuilder<?> hnswGraphBuilder = + HnswGraphBuilder.create( + offHeapVectors, + fieldInfo.getVectorEncoding(), + fieldInfo.getVectorSimilarityFunction(), + M, + beamWidth, + HnswGraphBuilder.randSeed); + hnswGraphBuilder.setInfoStream(segmentWriteState.infoStream); + graph = hnswGraphBuilder.build(offHeapVectors.copy()); + vectorIndexNodeOffsets = writeGraph(graph); + } + long vectorIndexLength = vectorIndex.getFilePointer() - vectorIndexOffset; + writeMeta( + fieldInfo, + segmentWriteState.segmentInfo.maxDoc(), + vectorDataOffset, + vectorDataLength, + vectorIndexOffset, + vectorIndexLength, + docsWithField, + graph, + vectorIndexNodeOffsets); + success = true; + } finally { + IOUtils.close(vectorDataInput); + if (success) { + segmentWriteState.directory.deleteFile(tempVectorData.getName()); + } else { + IOUtils.closeWhileHandlingException(tempVectorData); + IOUtils.deleteFilesIgnoringExceptions( + segmentWriteState.directory, tempVectorData.getName()); + } + } + } + + /** + * @param graph Write the graph in a compressed format + * @return The non-cumulative offsets for the nodes. Should be used to create cumulative offsets. + * @throws IOException if writing to vectorIndex fails + */ + private int[][] writeGraph(OnHeapHnswGraph graph) throws IOException { + if (graph == null) return new int[0][0]; + // write vectors' neighbours on each level into the vectorIndex file + int countOnLevel0 = graph.size(); + int[][] offsets = new int[graph.numLevels()][]; + for (int level = 0; level < graph.numLevels(); level++) { + NodesIterator nodesOnLevel = graph.getNodesOnLevel(level); + offsets[level] = new int[nodesOnLevel.size()]; + int nodeOffsetId = 0; + while (nodesOnLevel.hasNext()) { + int node = nodesOnLevel.nextInt(); + NeighborArray neighbors = graph.getNeighbors(level, node); + int size = neighbors.size(); + // Write size in VInt as the neighbors list is typically small + long offsetStart = vectorIndex.getFilePointer(); + vectorIndex.writeVInt(size); + // Destructively modify; it's ok we are discarding it after this + int[] nnodes = neighbors.node(); + Arrays.sort(nnodes, 0, size); + // Now that we have sorted, do delta encoding to minimize the required bits to store the + // information + for (int i = size - 1; i > 0; --i) { + assert nnodes[i] < countOnLevel0 : "node too large: " + nnodes[i] + ">=" + countOnLevel0; + nnodes[i] -= nnodes[i - 1]; + } + for (int i = 0; i < size; i++) { + vectorIndex.writeVInt(nnodes[i]); + } + offsets[level][nodeOffsetId++] = + Math.toIntExact(vectorIndex.getFilePointer() - offsetStart); + } + } + return offsets; + } + + private void writeMeta( + FieldInfo field, + int maxDoc, + long vectorDataOffset, + long vectorDataLength, + long vectorIndexOffset, + long vectorIndexLength, + DocsWithFieldSet docsWithField, + HnswGraph graph, + int[][] graphLevelNodeOffsets) Review Comment: I couldn't think of a better way to handle this as either: - We store the graphLevelNodeOffsets WHILE they are calculated, meaning they would be interleaved with the vectors (seems impossible to read again.) - Store the offsets in a completely new file. I am open to storing the offsets in new file, but it seemed OK to me to tack them on the end of the `vex` file. -- 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