Skip to content

Apache Lucene open-source search software

Remove unused MultiLeafKnnCollector and BlockingFloatHeap (#15686)

Mayya Sharipova75d47f09c459
diff --git a/lucene/core/src/java/org/apache/lucene/search/knn/MultiLeafKnnCollector.java b/lucene/core/src/java/org/apache/lucene/search/knn/MultiLeafKnnCollector.java
deleted file mode 100644
index 6b5e398d708..00000000000
--- a/lucene/core/src/java/org/apache/lucene/search/knn/MultiLeafKnnCollector.java
+++ /dev/null
@@ -1,139 +0,0 @@
-/*
- * 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.search.knn;
-
-import org.apache.lucene.search.AbstractKnnCollector;
-import org.apache.lucene.search.KnnCollector;
-import org.apache.lucene.util.hnsw.BlockingFloatHeap;
-import org.apache.lucene.util.hnsw.FloatHeap;
-
-/**
- * MultiLeafKnnCollector is a specific KnnCollector that can exchange the top collected results
- * across segments through a shared global queue.
- *
- * @lucene.experimental
- */
-public final class MultiLeafKnnCollector extends KnnCollector.Decorator {
-
- // greediness of globally non-competitive search: (0,1]
- private static final float DEFAULT_GREEDINESS = 0.9f;
- private static final int DEFAULT_INTERVAL = 0xff;
- // the global queue of the highest similarities collected so far across all segments
- private final BlockingFloatHeap globalSimilarityQueue;
- // the local queue of the highest similarities if we are not competitive globally
- // the size of this queue is defined by greediness
- private final FloatHeap nonCompetitiveQueue;
- // the queue of the local similarities to periodically update with the global queue
- private final FloatHeap updatesQueue;
- private final float[] updatesScratch;
- // interval to synchronize the local and global queues, as a number of visited vectors
- private final int interval;
- private boolean kResultsCollected = false;
- private float cachedGlobalMinSim = Float.NEGATIVE_INFINITY;
- private final AbstractKnnCollector subCollector;
-
- /**
- * Create a new MultiLeafKnnCollector.
- *
- * @param k the number of neighbors to collect
- * @param globalSimilarityQueue the global queue of the highest similarities collected so far
- * across all segments
- * @param subCollector the local collector
- */
- public MultiLeafKnnCollector(
- int k, BlockingFloatHeap globalSimilarityQueue, AbstractKnnCollector subCollector) {
- this(k, DEFAULT_GREEDINESS, DEFAULT_INTERVAL, globalSimilarityQueue, subCollector);
- }
-
- /**
- * Create a new MultiLeafKnnCollector.
- *
- * @param k the number of neighbors to collect
- * @param greediness the greediness of the global search
- * @param interval (by number of collected values) the interval to synchronize the local and
- * global queues
- * @param globalSimilarityQueue the global queue of the highest similarities collected so far
- * @param subCollector the local collector
- */
- public MultiLeafKnnCollector(
- int k,
- float greediness,
- int interval,
- BlockingFloatHeap globalSimilarityQueue,
- AbstractKnnCollector subCollector) {
- super(subCollector);
- if (greediness < 0 || greediness > 1) {
- throw new IllegalArgumentException("greediness must be in [0,1]");
- }
- if (interval <= 0) {
- throw new IllegalArgumentException("interval must be positive");
- }
- this.interval = interval;
- this.subCollector = subCollector;
- this.globalSimilarityQueue = globalSimilarityQueue;
- this.nonCompetitiveQueue = new FloatHeap(Math.max(1, Math.round((1 - greediness) * k)));
- this.updatesQueue = new FloatHeap(k);
- this.updatesScratch = new float[k];
- }
-
- @Override
- public boolean collect(int docId, float similarity) {
- boolean localSimUpdated = subCollector.collect(docId, similarity);
- boolean firstKResultsCollected =
- (kResultsCollected == false && subCollector.numCollected() == k());
- if (firstKResultsCollected) {
- kResultsCollected = true;
- }
- updatesQueue.offer(similarity);
- boolean globalSimUpdated = nonCompetitiveQueue.offer(similarity);
-
- if (kResultsCollected) {
- // as we've collected k results, we can start do periodic updates with the global queue
- if (firstKResultsCollected || (subCollector.visitedCount() & interval) == 0) {
- // BlockingFloatHeap#offer requires input to be sorted in ascending order, so we can't
- // pass in the underlying updatesQueue array as-is since it is only partially ordered
- // (see GH#13462):
- int len = updatesQueue.size();
- if (len > 0) {
- for (int i = 0; i < len; i++) {
- updatesScratch[i] = updatesQueue.poll();
- }
- assert updatesQueue.size() == 0;
- cachedGlobalMinSim = globalSimilarityQueue.offer(updatesScratch, len);
- globalSimUpdated = true;
- }
- }
- }
- return localSimUpdated || globalSimUpdated;
- }
-
- @Override
- public float minCompetitiveSimilarity() {
- if (kResultsCollected == false) {
- return Float.NEGATIVE_INFINITY;
- }
- return Math.max(
- subCollector.minCompetitiveSimilarity(),
- Math.min(nonCompetitiveQueue.peek(), cachedGlobalMinSim));
- }
-
- @Override
- public String toString() {
- return "MultiLeafKnnCollector[subCollector=" + subCollector + "]";
- }
-}
diff --git a/lucene/core/src/java/org/apache/lucene/util/hnsw/BlockingFloatHeap.java b/lucene/core/src/java/org/apache/lucene/util/hnsw/BlockingFloatHeap.java
deleted file mode 100644
index 6bbf6fdb741..00000000000
--- a/lucene/core/src/java/org/apache/lucene/util/hnsw/BlockingFloatHeap.java
+++ /dev/null
@@ -1,193 +0,0 @@
-/*
- * 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 java.util.concurrent.locks.ReentrantLock;
-
-/**
- * A blocking bounded min heap that stores floats. The top element is the lowest value of the heap.
- *
- * <p>A primitive priority queue that maintains a partial ordering of its elements such that the
- * least element can always be found in constant time. Implementation is based on {@link
- * org.apache.lucene.util.LongHeap}
- *
- * @lucene.internal
- */
-public final class BlockingFloatHeap {
- private final int maxSize;
- private final float[] heap;
- private final ReentrantLock lock;
- private int size;
-
- public BlockingFloatHeap(int maxSize) {
- this.maxSize = maxSize;
- this.heap = new float[maxSize + 1];
- this.lock = new ReentrantLock();
- this.size = 0;
- }
-
- /**
- * Inserts a value into this heap.
- *
- * <p>If the number of values would exceed the heap's maxSize, the least value is discarded
- *
- * @param value the value to add
- * @return the new 'top' element in the queue.
- */
- public float offer(float value) {
- lock.lock();
- try {
- if (size < maxSize) {
- push(value);
- return heap[1];
- } else {
- if (value >= heap[1]) {
- updateTop(value);
- }
- return heap[1];
- }
- } finally {
- lock.unlock();
- }
- }
-
- /**
- * Inserts array of values into this heap.
- *
- * <p>Values must be sorted in ascending order.
- *
- * @param values a set of values to insert, must be sorted in ascending order
- * @param len number of values from the {@code values} array to insert
- * @return the new 'top' element in the queue.
- */
- public float offer(float[] values, int len) {
- lock.lock();
- try {
- for (int i = len - 1; i >= 0; i--) {
- if (size < maxSize) {
- push(values[i]);
- } else {
- if (values[i] >= heap[1]) {
- updateTop(values[i]);
- } else {
- break;
- }
- }
- }
- return heap[1];
- } finally {
- lock.unlock();
- }
- }
-
- /**
- * Removes and returns the head of the heap
- *
- * @return the head of the heap, the smallest value
- * @throws IllegalStateException if the heap is empty
- */
- public float poll() {
- if (size > 0) {
- float result;
-
- lock.lock();
- try {
- result = heap[1]; // save first value
- heap[1] = heap[size]; // move last to first
- size--;
- downHeap(1); // adjust heap
- } finally {
- lock.unlock();
- }
- return result;
- } else {
- throw new IllegalStateException("The heap is empty");
- }
- }
-
- /**
- * Retrieves, but does not remove, the head of this heap.
- *
- * @return the head of the heap, the smallest value
- */
- public float peek() {
- lock.lock();
- try {
- return heap[1];
- } finally {
- lock.unlock();
- }
- }
-
- /**
- * Returns the number of elements in this heap.
- *
- * @return the number of elements in this heap
- */
- public int size() {
- lock.lock();
- try {
- return size;
- } finally {
- lock.unlock();
- }
- }
-
- private void push(float element) {
- size++;
- heap[size] = element;
- upHeap(size);
- }
-
- private float updateTop(float value) {
- heap[1] = value;
- downHeap(1);
- return heap[1];
- }
-
- private void downHeap(int i) {
- float value = heap[i]; // save top value
- int j = i << 1; // find smaller child
- int k = j + 1;
- if (k <= size && heap[k] < heap[j]) {
- j = k;
- }
- while (j <= size && heap[j] < value) {
- heap[i] = heap[j]; // shift up child
- i = j;
- j = i << 1;
- k = j + 1;
- if (k <= size && heap[k] < heap[j]) {
- j = k;
- }
- }
- heap[i] = value; // install saved value
- }
-
- private void upHeap(int origPos) {
- int i = origPos;
- float value = heap[i]; // save bottom value
- int j = i >>> 1;
- while (j > 0 && value < heap[j]) {
- heap[i] = heap[j]; // shift parents down
- i = j;
- j = j >>> 1;
- }
- heap[i] = value; // install saved value
- }
-}
diff --git a/lucene/core/src/test/org/apache/lucene/search/knn/TestMultiLeafKnnCollector.java b/lucene/core/src/test/org/apache/lucene/search/knn/TestMultiLeafKnnCollector.java
deleted file mode 100644
index 8466293f61a..00000000000
--- a/lucene/core/src/test/org/apache/lucene/search/knn/TestMultiLeafKnnCollector.java
+++ /dev/null
@@ -1,62 +0,0 @@
-/*
- * 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.search.knn;
-
-import org.apache.lucene.search.TopKnnCollector;
-import org.apache.lucene.tests.util.LuceneTestCase;
-import org.apache.lucene.util.hnsw.BlockingFloatHeap;
-
-public class TestMultiLeafKnnCollector extends LuceneTestCase {
-
- /** Validates a fix for GH#13462 */
- public void testGlobalScoreCoordination() {
- int k = 7;
- BlockingFloatHeap globalHeap = new BlockingFloatHeap(k);
- MultiLeafKnnCollector collector1 =
- new MultiLeafKnnCollector(k, globalHeap, new TopKnnCollector(k, Integer.MAX_VALUE));
- MultiLeafKnnCollector collector2 =
- new MultiLeafKnnCollector(k, globalHeap, new TopKnnCollector(k, Integer.MAX_VALUE));
-
- // Collect k (7) hits in collector1 with scores [100, 106]:
- for (int i = 0; i < k; i++) {
- collector1.collect(0, 100f + i);
- }
-
- // The global heap should be updated since k hits were collected, and have a min score of
- // 100:
- assertEquals(100f, globalHeap.peek(), 0f);
- assertEquals(100f, collector1.minCompetitiveSimilarity(), 0f);
-
- // Collect k (7) hits in collector2 with only two that are competitive (200 and 300),
- // which also forces an update of the global heap with collector2's hits. This is a tricky
- // case where the heap will not be fully ordered, so it ensures global queue updates don't
- // incorrectly short-circuit (see GH#13462):
- collector2.collect(0, 10f);
- collector2.collect(0, 11f);
- collector2.collect(0, 12f);
- collector2.collect(0, 13f);
- collector2.collect(0, 200f);
- collector2.collect(0, 14f);
- collector2.collect(0, 300f);
-
- // At this point, our global heap should contain [102, 103, 104, 105, 106, 200, 300] since
- // values 200 and 300 from collector2 should have pushed out 100 and 101 from collector1.
- // The min value on the global heap should be 102:
- assertEquals(102f, globalHeap.peek(), 0f);
- assertEquals(102f, collector2.minCompetitiveSimilarity(), 0f);
- }
-}
diff --git a/lucene/core/src/test/org/apache/lucene/util/hnsw/TestBlockingFloatHeap.java b/lucene/core/src/test/org/apache/lucene/util/hnsw/TestBlockingFloatHeap.java
deleted file mode 100644
index 07df7b3044e..00000000000
--- a/lucene/core/src/test/org/apache/lucene/util/hnsw/TestBlockingFloatHeap.java
+++ /dev/null
@@ -1,100 +0,0 @@
-/*
- * 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 com.carrotsearch.randomizedtesting.RandomizedTest.randomIntBetween;
-
-import java.util.concurrent.CountDownLatch;
-import org.apache.lucene.tests.util.LuceneTestCase;
-import org.apache.lucene.util.SuppressForbidden;
-
-public class TestBlockingFloatHeap extends LuceneTestCase {
-
- public void testBasicOperations() {
- BlockingFloatHeap heap = new BlockingFloatHeap(3);
- heap.offer(2);
- heap.offer(4);
- heap.offer(1);
- heap.offer(3);
- assertEquals(3, heap.size());
- assertEquals(2, heap.peek(), 0);
-
- assertEquals(2, heap.poll(), 0);
- assertEquals(3, heap.poll(), 0);
- assertEquals(4, heap.poll(), 0);
- assertEquals(0, heap.size(), 0);
- }
-
- public void testBasicOperations2() {
- int size = atLeast(10);
- BlockingFloatHeap heap = new BlockingFloatHeap(size);
- double sum = 0, sum2 = 0;
-
- for (int i = 0; i < size; i++) {
- float next = random().nextFloat(100f);
- sum += next;
- heap.offer(next);
- }
-
- float last = Float.NEGATIVE_INFINITY;
- for (long i = 0; i < size; i++) {
- float next = heap.poll();
- assertTrue(next >= last);
- last = next;
- sum2 += last;
- }
- assertEquals(sum, sum2, 0.01);
- }
-
- @SuppressForbidden(reason = "Thread sleep")
- public void testMultipleThreads() throws Exception {
- Thread[] threads = new Thread[randomIntBetween(3, 20)];
- final CountDownLatch latch = new CountDownLatch(1);
- BlockingFloatHeap globalHeap = new BlockingFloatHeap(1);
-
- for (int i = 0; i < threads.length; i++) {
- threads[i] =
- new Thread(
- () -> {
- try {
- latch.await();
- int numIterations = randomIntBetween(10, 100);
- float bottomValue = 0;
-
- while (numIterations-- > 0) {
- bottomValue += randomIntBetween(0, 5);
- globalHeap.offer(bottomValue);
- Thread.sleep(randomIntBetween(0, 50));
-
- float globalBottomValue = globalHeap.peek();
- assertTrue(globalBottomValue >= bottomValue);
- bottomValue = globalBottomValue;
- }
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
- });
- threads[i].start();
- }
-
- latch.countDown();
- for (Thread t : threads) {
- t.join();
- }
- }
-}