benchaplin commented on code in PR #14160: URL: https://github.com/apache/lucene/pull/14160#discussion_r1927620854
########## lucene/core/src/java/org/apache/lucene/util/hnsw/FilteredHnswGraphSearcher.java: ########## @@ -0,0 +1,332 @@ +/* + * 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.util.hnsw; + +import static org.apache.lucene.search.DocIdSetIterator.NO_MORE_DOCS; + +import java.io.IOException; +import org.apache.lucene.search.KnnCollector; +import org.apache.lucene.util.BitSet; +import org.apache.lucene.util.Bits; +import org.apache.lucene.util.FixedBitSet; +import org.apache.lucene.util.SparseFixedBitSet; + +/** + * Searches an HNSW graph to find nearest neighbors to a query vector. This particular + * implementation is optimized for a filtered search, inspired by the ACORN-1 algorithm. + * https://arxiv.org/abs/2403.04871 However, this implementation is augmented in some ways, mainly: + * + * <ul> + * <li>It dynamically determines when the optimized filter step should occur based on some + * filtered lambda. This is done per small world + * <li>The graph searcher doesn't always explore all the extended neighborhood and the number of + * additional candidates is predicated on the original candidate's filtered percentage. + * </ul> + */ +public class FilteredHnswGraphSearcher { + // How many filtered candidates must be found to consider N-hop neighbors + private static final float EXPANDED_EXPLORATION_LAMBDA = 0.10f; + + /** + * Scratch data structures that are used in each {@link #searchBaseLevel} call. These can be + * expensive to allocate, so they're cleared and reused across calls. + */ + private final NeighborQueue candidates; + + private final BitSet visited; + private final BitSet explorationVisited; + private final HnswGraph graph; + + /** + * Creates a new graph searcher. + * + * @param candidates max heap that will track the candidate nodes to explore + * @param visited bit set that will track nodes that have already been visited + */ + private FilteredHnswGraphSearcher( + NeighborQueue candidates, BitSet explorationVisited, BitSet visited, HnswGraph graph) { + assert graph.maxConn() > 0 : "graph must have known max connections"; + this.candidates = candidates; + this.visited = visited; + this.explorationVisited = explorationVisited; + this.graph = graph; + } + + /** + * Searches HNSW graph for the nearest neighbors of a query vector. + * + * @param scorer the scorer to compare the query with the nodes + * @param knnCollector a collector of top knn results to be returned + * @param graph the graph values. May represent the entire graph, or a level in a hierarchical + * graph. + * @param acceptOrds {@link Bits} that represents the allowed document ordinals to match, or + * {@code null} if they are all allowed to match. + */ + public static void search( + RandomVectorScorer scorer, + KnnCollector knnCollector, + HnswGraph graph, + int filterSize, + Bits acceptOrds) + throws IOException { + if (acceptOrds == null) { + throw new IllegalArgumentException("acceptOrds must not be null to used filtered search"); + } + FilteredHnswGraphSearcher graphSearcher = + new FilteredHnswGraphSearcher( + new NeighborQueue(knnCollector.k(), true), + bitSet(filterSize, getGraphSize(graph), knnCollector.k()), + new SparseFixedBitSet(getGraphSize(graph)), + graph); + int ep = graphSearcher.findBestEntryPoint(scorer, knnCollector); + int maxExplorationMultiplier = Math.min(graph.size() / filterSize, 8); + if (ep != -1) { + graphSearcher.searchBaseLevel(knnCollector, scorer, ep, maxExplorationMultiplier, acceptOrds); + } + } + + private static BitSet bitSet(long filterSize, int graphSize, int topk) { + float percentFiltered = (float) filterSize / graphSize; + assert percentFiltered > 0.0f && percentFiltered < 1.0f; + double totalOps = Math.log(graphSize) * topk; + int approximateVisitation = (int) (totalOps / percentFiltered); + return bitSet(approximateVisitation, graphSize); + } + + private static BitSet bitSet(int expectedBits, int totalBits) { + if (expectedBits < (totalBits >>> 7)) { + return new SparseFixedBitSet(totalBits); + } else { + return new FixedBitSet(totalBits); + } + } + + /** + * Function to find the best entry point from which to search the zeroth graph layer. + * + * @param scorer the scorer to compare the query with the nodes + * @param collector the knn result collector + * @return the best entry point, `-1` indicates graph entry node not set, or visitation limit + * exceeded + * @throws IOException When accessing the vector fails + */ + private int findBestEntryPoint(RandomVectorScorer scorer, KnnCollector collector) Review Comment: Thoughts on abstracting this since it's identical (minus source of `graph`) to `HnswGraphSearcher::findBestEntryPoint`? I suppose we might want to investigate multiple entry points in the future so maybe the duplicate code will be gone soon. -- 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