kaivalnp commented on code in PR #15979: URL: https://github.com/apache/lucene/pull/15979#discussion_r3647733932
########## lucene/core/src/java/org/apache/lucene/codecs/lucene106/dedup/DedupMergeContext.java: ########## @@ -0,0 +1,357 @@ +/* + * 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.lucene106.dedup; + +import static java.nio.ByteOrder.LITTLE_ENDIAN; +import static org.apache.lucene.codecs.lucene106.dedup.DedupUtil.ORD_UNKNOWN; +import static org.apache.lucene.codecs.lucene106.dedup.DedupUtil.alignBytes; +import static org.apache.lucene.codecs.lucene106.dedup.DedupUtil.hashBytes; +import static org.apache.lucene.codecs.lucene106.dedup.DedupUtil.writeEndOfFields; +import static org.apache.lucene.codecs.lucene106.dedup.DedupUtil.writeEndOfGroups; +import static org.apache.lucene.codecs.lucene106.dedup.DedupUtil.writeFieldInfo; +import static org.apache.lucene.codecs.lucene106.dedup.DedupUtil.writeGroupInfo; + +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.FloatBuffer; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; +import org.apache.lucene.codecs.lucene106.dedup.DedupUtil.DedupVectorValues; +import org.apache.lucene.codecs.lucene106.dedup.DedupUtil.GroupInfo; +import org.apache.lucene.codecs.lucene106.dedup.DedupUtil.GroupKey; +import org.apache.lucene.codecs.lucene106.dedup.DedupUtil.OrdToVecOrd; +import org.apache.lucene.codecs.lucene106.dedup.DedupUtil.OrdToVecOrdArrayList; +import org.apache.lucene.codecs.lucene106.dedup.DedupUtil.WriteFieldInfo; +import org.apache.lucene.index.ByteVectorValues; +import org.apache.lucene.index.DocIDMerger; +import org.apache.lucene.index.DocsWithFieldSet; +import org.apache.lucene.index.FieldInfo; +import org.apache.lucene.index.FloatVectorValues; +import org.apache.lucene.index.KnnVectorValues; +import org.apache.lucene.index.MergeState; +import org.apache.lucene.index.VectorEncoding; +import org.apache.lucene.internal.hppc.IntArrayList; +import org.apache.lucene.internal.hppc.ObjectCursor; +import org.apache.lucene.store.IndexOutput; +import org.apache.lucene.util.Accountable; +import org.apache.lucene.util.IOSupplier; +import org.apache.lucene.util.RamUsageEstimator; + +/** + * Merges de-duplicated flat vectors from several segments. Fields sharing a {@link + * DedupUtil.GroupKey} are merged into one group: their vectors are streamed in merged doc order + * through a {@link DedupGroup}, so a vector is written the first time it is seen and later + * occurrences (within or across fields) reuse that group ordinal. Vectors originating from a dedup + * source are compared by ordinal to avoid reading them back. + * + * @lucene.experimental + */ +final class DedupMergeContext implements Accountable { + private static final long SHALLOW_SIZE = + RamUsageEstimator.shallowSizeOfInstance(DedupMergeContext.class); + private final List<FieldData> fieldDataList; + + DedupMergeContext() { + this.fieldDataList = new ArrayList<>(); + } + + @Override + public long ramBytesUsed() { + return SHALLOW_SIZE + fieldDataList.size() * FieldData.SHALLOW_SIZE; + } + + void addField(FieldInfo fieldInfo, MergeState mergeState) throws IOException { + fieldDataList.add( + new FieldData( + fieldInfo, + new GroupKey(fieldInfo), + new DocsWithFieldSet(), + new IntArrayList(), + getVectorMerger(fieldInfo, mergeState), + mergeState.segmentInfo.maxDoc())); + } + + void finish(IndexOutput meta, IndexOutput vectorData) throws IOException { + + // Evaluate compatible fields together for correct de-duplication + Map<GroupKey, List<FieldData>> fieldGroups = + fieldDataList.stream().collect(Collectors.groupingBy(FieldData::groupKey)); + + Map<GroupKey, Integer> groupOrds = new HashMap<>(); + int groupOrd = 0; + for (Map.Entry<GroupKey, List<FieldData>> entry : fieldGroups.entrySet()) { + GroupKey groupKey = entry.getKey(); + long vectorDataOffset = alignBytes(vectorData, groupKey.encoding()); + + DedupMergeGroup<?, ?> mergeGroup = + switch (groupKey.encoding()) { + case BYTE -> new ByteGroup(); + case FLOAT32 -> new FloatGroup(groupKey.dimension()); + }; + + for (FieldData fieldData : entry.getValue()) { + mergeGroup.processField(fieldData, vectorData); + } + + int dimension = groupKey.dimension(); + VectorEncoding encoding = groupKey.encoding(); + int groupSize = mergeGroup.size(); + long vectorDataSize = vectorData.getFilePointer() - vectorDataOffset; + + GroupInfo groupInfo = + new GroupInfo(groupOrd, dimension, encoding, groupSize, vectorDataOffset, vectorDataSize); + writeGroupInfo(meta, groupInfo); + + groupOrds.put(groupKey, groupOrd); + groupOrd++; + } + + writeEndOfGroups(meta); + + for (FieldData fieldData : fieldDataList) { + WriteFieldInfo fieldInfo = + new WriteFieldInfo( + fieldData.fieldInfo.number, + fieldData.fieldInfo.getVectorSimilarityFunction(), + fieldData.fieldInfo.getVectorDimension(), + fieldData.fieldInfo.getVectorEncoding(), + groupOrds.get(fieldData.groupKey), + fieldData.ordToVecOrd.elementsCount, + fieldData.maxDoc, + fieldData.docsWithFieldSet, + new OrdToVecOrdArrayList(fieldData.ordToVecOrd)); + writeFieldInfo(meta, vectorData, fieldInfo); + } + + writeEndOfFields(meta); + } + + abstract static sealed class DedupMergeGroup<T, U extends KnnVectorValues> extends DedupGroup<T> { + abstract T vectorFrom(Sub<U> sub); + + void processField(FieldData fieldData, IndexOutput vectorData) throws IOException { + @SuppressWarnings("unchecked") + DocIDMerger<Sub<U>> merger = (DocIDMerger<Sub<U>>) fieldData.merger; + + // iterate merged docs one-by-one + for (Sub<U> next = merger.next(); next != null; next = merger.next()) { + T vector = vectorFrom(next); + int groupSize = size(); + + // add vector to group + ObjectCursor<T> cursor = super.addUnique(vector); + if (cursor.index == groupSize) { // new addition + // already on-heap, write immediately to avoid another IO read Review Comment: All vectors are loaded onto heap **one-by-one** inside the [`addUnique`](https://github.com/kaivalnp/lucene/blob/91936b9b43d7244b2663de254ef1c0715c59d754/lucene/core/src/java/org/apache/lucene/codecs/lucene106/dedup/DedupMergeContext.java#L160) call (internally by the [hash function](https://github.com/kaivalnp/lucene/blob/91936b9b43d7244b2663de254ef1c0715c59d754/lucene/core/src/java/org/apache/lucene/codecs/lucene106/dedup/DedupMergeContext.java#L259-L266)). For the actual on-heap storage in the group -- we only retain the `[Byte|Float]VectorValues values, int index` tuple on-heap (and not the entire vector) -- allowing us to keep context about all vectors being merged (even if their raw size is greater than heap). Now if we were to defer all writes to the end (once the group is complete), we would need to re-read the vectors from disk, causing wasted IO. However, I discovered that since we _just_ loaded a vector onto heap inside `addUnique`, we could [immediately write it to disk](https://github.com/kaivalnp/lucene/blob/91936b9b43d7244b2663de254ef1c0715c59d754/lucene/core/src/java/org/apache/lucene/codecs/lucene106/dedup/DedupMergeContext.java#L162-L163) to the new segment, because a [subsequent `vectorValue` call with the same `ord` would not cause more IO](https://github.com/kaivalnp/lucene/blob/91936b9b43d7244b2663de254ef1c0715c59d754/lucene/core/src/java/org/apache/lucene/codecs/lucene95/OffHeapFloatVectorValues.java#L77-L86). -- 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: [email protected] For queries about this service, please contact Infrastructure at: [email protected] --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
