You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@lucene.apache.org by to...@apache.org on 2020/01/12 06:11:43 UTC

[lucene-solr] 08/10: Mocobeta/lucene 9004 2 (#3)

This is an automated email from the ASF dual-hosted git repository.

tomoko pushed a commit to branch jira/lucene-9004-aknn-2
in repository https://gitbox.apache.org/repos/asf/lucene-solr.git

commit b4a8979e5cb338a17a798525b05eb7ab06cbd613
Author: Michael Sokolov <so...@falutin.net>
AuthorDate: Fri Jan 10 10:52:16 2020 -0500

    Mocobeta/lucene 9004 2 (#3)
    
    * Added KnnGraphTester; fixed some small bugs and measured recall
    
    * use FloatBuffer for encode/decode of vector values. Share a single float[] when fetching values. 25% latency reduction
    
    * Don't try to precompute nearest neighbors when generating test data in KnnGraphTester
    
    * added visitedCounter for debugging/optimization
    restored shrinking to limit fanout of graph
    fixed an upside-down priority queue
    
    * don't terminate exploration of graph until we have a full result queue
    
    * fixing up some small bugs I had introduced in earlier push
---
 .../codecs/lucene90/Lucene90KnnGraphReader.java    |  27 +++-
 .../java/org/apache/lucene/index/VectorValues.java |  12 +-
 .../org/apache/lucene/search/KnnGraphQuery.java    |  25 +++-
 .../org/apache/lucene/search/KnnScoreWeight.java   |  12 ++
 .../org/apache/lucene/util/hnsw/HNSWGraph.java     |  27 ++--
 .../apache/lucene/util/hnsw/HNSWGraphReader.java   |  17 ++-
 .../apache/lucene/util/hnsw/HNSWGraphWriter.java   |  12 +-
 .../apache/lucene/util/hnsw/KnnGraphTester.java    | 165 +++++++++++++++++----
 8 files changed, 220 insertions(+), 77 deletions(-)

diff --git a/lucene/core/src/java/org/apache/lucene/codecs/lucene90/Lucene90KnnGraphReader.java b/lucene/core/src/java/org/apache/lucene/codecs/lucene90/Lucene90KnnGraphReader.java
index 1083fd4..c7e615e 100644
--- a/lucene/core/src/java/org/apache/lucene/codecs/lucene90/Lucene90KnnGraphReader.java
+++ b/lucene/core/src/java/org/apache/lucene/codecs/lucene90/Lucene90KnnGraphReader.java
@@ -18,6 +18,8 @@
 package org.apache.lucene.codecs.lucene90;
 
 import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.nio.FloatBuffer;
 import java.util.HashMap;
 import java.util.Map;
 
@@ -258,18 +260,29 @@ public final class Lucene90KnnGraphReader extends KnnGraphReader {
 
     final int maxDoc;
     final int numDims;
+    final int byteSize;
     final KnnGraphEntry entry;
     final IndexInput dataIn;
+    final BytesRef binaryValue;
+    final ByteBuffer byteBuffer;
+    final FloatBuffer floatBuffer;
+    final float[] value;
 
     int doc = -1;
-    BytesRef binaryValue;
 
     RandomAccessVectorValuesReader(int maxDoc, int numDims, KnnGraphEntry entry, IndexInput dataIn) {
       this.maxDoc = maxDoc;
       this.numDims = numDims;
       this.entry = entry;
       this.dataIn = dataIn;
-      this.binaryValue = new BytesRef(new byte[Float.BYTES * numDims]);
+      // TODO: if we had more direct access to file system (a FileChannel) we could use a
+      // MappedByteBuffer here. EG if we know that dataIn is a ByteBufferIndexInput, we could get a
+      // FloatBuffer from that and provide access to it
+      byteSize = Float.BYTES * numDims;
+      byteBuffer = ByteBuffer.allocate(byteSize);
+      floatBuffer = byteBuffer.asFloatBuffer();
+      value = new float[numDims];
+      binaryValue = new BytesRef(byteBuffer.array(), byteBuffer.arrayOffset(), byteSize);
     }
 
     @Override
@@ -277,7 +290,10 @@ public final class Lucene90KnnGraphReader extends KnnGraphReader {
       if (doc == NO_MORE_DOCS) {
         return null;
       }
-      return VectorValues.decode(binaryValue, numDims);
+      // return VectorValues.decode(binaryValue, numDims);
+      floatBuffer.position(0);
+      floatBuffer.get(value, 0, numDims);
+      return value;
     }
 
     @Override
@@ -296,10 +312,11 @@ public final class Lucene90KnnGraphReader extends KnnGraphReader {
       if (ord == null) {
         return false;
       }
-      int offset = Float.BYTES * numDims * ord;
+      int offset = ord * byteSize;
       assert offset >= 0;
       dataIn.seek(offset);
-      dataIn.readBytes(binaryValue.bytes, binaryValue.offset, binaryValue.length);
+      //dataIn.readBytes(binaryValue.bytes, binaryValue.offset, binaryValue.length);
+      dataIn.readBytes(byteBuffer.array(), byteBuffer.arrayOffset(), byteSize);
       return true;
     }
 
diff --git a/lucene/core/src/java/org/apache/lucene/index/VectorValues.java b/lucene/core/src/java/org/apache/lucene/index/VectorValues.java
index e83d174..9e0ce1d 100644
--- a/lucene/core/src/java/org/apache/lucene/index/VectorValues.java
+++ b/lucene/core/src/java/org/apache/lucene/index/VectorValues.java
@@ -73,15 +73,9 @@ public abstract class VectorValues extends DocIdSetIterator {
    * Encodes float array to byte array.
    */
   public static BytesRef encode(float[] value) {
-    byte[] bytes = new byte[Float.BYTES * value.length];
-    for (int i = 0; i < value.length; i++) {
-      int bits = Float.floatToIntBits(value[i]);
-      bytes[i * Float.BYTES] = (byte)(bits >> 24);
-      bytes[i * Float.BYTES + 1] = (byte)(bits >> 16);
-      bytes[i * Float.BYTES + 2] = (byte)(bits >> 8);
-      bytes[i * Float.BYTES + 3] = (byte)(bits);
-    }
-    return new BytesRef(bytes);
+    ByteBuffer buffer = ByteBuffer.allocate(Float.BYTES * value.length);
+    buffer.asFloatBuffer().put(value);
+    return new BytesRef(buffer.array());
   }
 
   public static boolean verifyNumDimensions(int numBytes, int numDims) {
diff --git a/lucene/core/src/java/org/apache/lucene/search/KnnGraphQuery.java b/lucene/core/src/java/org/apache/lucene/search/KnnGraphQuery.java
index b1c14f6..0f30037 100644
--- a/lucene/core/src/java/org/apache/lucene/search/KnnGraphQuery.java
+++ b/lucene/core/src/java/org/apache/lucene/search/KnnGraphQuery.java
@@ -21,6 +21,7 @@ import java.io.IOException;
 import java.util.Arrays;
 import java.util.Objects;
 import java.util.Set;
+import java.util.concurrent.atomic.AtomicLong;
 
 import org.apache.lucene.document.Document;
 import org.apache.lucene.index.FieldInfo;
@@ -44,8 +45,8 @@ public class KnnGraphQuery extends Query implements Accountable {
   private final String field;
   private final float[] queryVector;
   private final int ef;
-
-  private long bytesUsed = 0L;
+  private final long bytesUsed;
+  private final AtomicLong visitedCounter;
 
   /**
    * Creates an nearest neighbor search query with default {@code ef} parameter (={@link #DEFAULT_EF}).
@@ -54,7 +55,6 @@ public class KnnGraphQuery extends Query implements Accountable {
    */
   public KnnGraphQuery(String field, float[] queryVector) {
     this(field, queryVector, DEFAULT_EF);
-    this.bytesUsed = RamUsageEstimator.shallowSizeOfInstance(getClass());
   }
 
   /**
@@ -68,7 +68,8 @@ public class KnnGraphQuery extends Query implements Accountable {
     this.field = field;
     this.queryVector = queryVector;
     this.ef = ef;
-    this.bytesUsed = RamUsageEstimator.shallowSizeOfInstance(getClass());
+    visitedCounter = new AtomicLong();
+    bytesUsed = RamUsageEstimator.shallowSizeOfInstance(getClass());
   }
 
   /**
@@ -85,8 +86,11 @@ public class KnnGraphQuery extends Query implements Accountable {
     this.field = field;
     this.queryVector = queryVector;
     this.ef = ef;
+    visitedCounter = new AtomicLong();
     if (reader != null) {
-      this.bytesUsed = HNSWGraphReader.loadGraphs(field, reader, forceReload);
+      bytesUsed = HNSWGraphReader.loadGraphs(field, reader, forceReload);
+    } else {
+      bytesUsed = 0;
     }
   }
 
@@ -106,7 +110,9 @@ public class KnnGraphQuery extends Query implements Accountable {
 
   @Override
   public Weight createWeight(IndexSearcher searcher, ScoreMode scoreMode, float boost) throws IOException {
-    return new KnnScoreWeight(this, boost, scoreMode, field, queryVector, ef);
+    KnnScoreWeight weight = new KnnScoreWeight(this, boost, scoreMode, field, queryVector, ef);
+    weight.setVisitedCounter(visitedCounter);
+    return weight;
   }
 
   @Override
@@ -143,4 +149,11 @@ public class KnnGraphQuery extends Query implements Accountable {
   public long ramBytesUsed() {
     return bytesUsed;
   }
+
+  /**
+   * @return this total the number of documents visited by this query
+   */
+  public long getVisitedCount() {
+    return visitedCounter.get();
+  }
 }
diff --git a/lucene/core/src/java/org/apache/lucene/search/KnnScoreWeight.java b/lucene/core/src/java/org/apache/lucene/search/KnnScoreWeight.java
index 02b6a5c..a3847ad 100644
--- a/lucene/core/src/java/org/apache/lucene/search/KnnScoreWeight.java
+++ b/lucene/core/src/java/org/apache/lucene/search/KnnScoreWeight.java
@@ -18,6 +18,7 @@
 package org.apache.lucene.search;
 
 import java.io.IOException;
+import java.util.concurrent.atomic.AtomicLong;
 
 import org.apache.lucene.index.FieldInfo;
 import org.apache.lucene.index.LeafReaderContext;
@@ -32,6 +33,7 @@ class KnnScoreWeight extends ConstantScoreWeight {
   private final ScoreMode scoreMode;
   private final float[] queryVector;
   private final int ef;
+  private AtomicLong visitedCounter;
 
   KnnScoreWeight(Query query, float score, ScoreMode scoreMode, String field, float[] queryVector, int ef) {
     super(query, score);
@@ -70,6 +72,7 @@ class KnnScoreWeight extends ConstantScoreWeight {
       @Override
       public Scorer get(long leadCost) throws IOException {
         Neighbors neighbors = hnswReader.searchNeighbors(queryVector, ef, vectorValues);
+        visitedCounter.addAndGet(hnswReader.getVisitedCount());
         return new Scorer(weight) {
 
           int doc = -1;
@@ -110,6 +113,7 @@ class KnnScoreWeight extends ConstantScoreWeight {
                     switch (fi.getVectorDistFunc()) {
                       case MANHATTAN:
                       case EUCLIDEAN:
+                        // is it necessary to normalize these scores?
                         score = 1.0f / (next.distance() / numDimensions + 0.01f);
                         break;
                       case COSINE:
@@ -158,4 +162,12 @@ class KnnScoreWeight extends ConstantScoreWeight {
   public boolean isCacheable(LeafReaderContext ctx) {
     return true;
   }
+
+  public void setVisitedCounter(AtomicLong counter) {
+    visitedCounter = counter;
+  }
+
+  public long getVisitedCount() {
+    return visitedCounter.get();
+  }
 }
diff --git a/lucene/core/src/java/org/apache/lucene/util/hnsw/HNSWGraph.java b/lucene/core/src/java/org/apache/lucene/util/hnsw/HNSWGraph.java
index c4d8332..37c7338 100644
--- a/lucene/core/src/java/org/apache/lucene/util/hnsw/HNSWGraph.java
+++ b/lucene/core/src/java/org/apache/lucene/util/hnsw/HNSWGraph.java
@@ -55,29 +55,27 @@ public final class HNSWGraph implements Accountable {
    * @param ef the number of nodes to be searched
    * @param level graph level
    * @param vectorValues vector values
-   * @return nearest neighbors
+   * @return number of candidates visited
    */
-  void searchLayer(float[] query, FurthestNeighbors results, int ef, int level, VectorValues vectorValues) throws IOException {
+  int searchLayer(float[] query, FurthestNeighbors results, int ef, int level, VectorValues vectorValues) throws IOException {
     if (level >= layers.size()) {
       throw new IllegalArgumentException("layer does not exist for the level: " + level);
     }
 
     Layer layer = layers.get(level);
     TreeSet<Neighbor> candidates = new TreeSet<>();
+    // set of docids that have been visited by search on this layer, used to avoid backtracking
+    Set<Integer> visited = new HashSet<>();
     for (Neighbor n : results) {
-      // TODO: candidates should get neighbors of neighbors
       candidates.add(n);
+      visited.add(n.docId());
     }
-    // set of docids that have been visited by search on this layer, used to avoid backtracking
-    Set<Integer> visited = new HashSet<>();
-    // We want to efficiently pop the best (nearest, least distance) candidate, so use NearestNeighbors,
-    // but we don't want to overflow the heap and lose the best candidate!
+    Neighbor f = results.top();
     while (candidates.size() > 0) {
       Neighbor c = candidates.pollFirst();
-      Neighbor f = results.top();
       assert c.isDeferred() == false;
       assert f.isDeferred() == false;
-      if (c.distance() > f.distance()) {
+      if (c.distance() > f.distance() && results.size() >= ef) {
         break;
       }
       for (Neighbor e : layer.getFriends(c.docId())) {
@@ -85,21 +83,19 @@ public final class HNSWGraph implements Accountable {
           continue;
         }
         visited.add(e.docId());
-        assert f.isDeferred() == false;
         float dist = distance(query, e.docId(), vectorValues);
         if (dist < f.distance() || results.size() < ef) {
           Neighbor n = new ImmutableNeighbor(e.docId(), dist);
           candidates.add(n);
-          Neighbor popped = results.insertWithOverflow(n);
-          if (popped != null && popped != n) {
-            f = results.top();
-          }
+          results.insertWithOverflow(n);
+          f = results.top();
         }
       }
     }
 
     //System.out.println("level=" + level + ", visited nodes=" + visited.size());
     //return pickNearestNeighbor(results);
+    return visited.size();
   }
 
   private float distance(float[] query, int docId, VectorValues vectorValues) throws IOException {
@@ -216,13 +212,10 @@ public final class HNSWGraph implements Accountable {
       throw new IllegalArgumentException("layer does not exist for level: " + level);
     }
     layer.connectNodes(node1, node2, dist);
-    /*
     // ensure friends size <= maxConnections
-    //
     if (maxConnections > 0) {
       layer.shrink(node2, maxConnections);
     }
-    */
   }
 
   /** Connects two nodes; this is supposed to be called when searching */
diff --git a/lucene/core/src/java/org/apache/lucene/util/hnsw/HNSWGraphReader.java b/lucene/core/src/java/org/apache/lucene/util/hnsw/HNSWGraphReader.java
index ef11386..28abd8e 100644
--- a/lucene/core/src/java/org/apache/lucene/util/hnsw/HNSWGraphReader.java
+++ b/lucene/core/src/java/org/apache/lucene/util/hnsw/HNSWGraphReader.java
@@ -35,12 +35,16 @@ import org.apache.lucene.search.DocIdSetIterator;
  * This also caches built {@link HNSWGraph}s for repeated use. */
 public final class HNSWGraphReader {
 
+  // TODO: evict from this cache when a reader's segment is merged. Probably should hold the cache
+  // somewhere that has a similar lifecycle, like Lucene90KnnGraphReader
   private static final Map<GraphKey, HNSWGraph> cache = new ConcurrentHashMap<>();
 
   private final String field;
   private final LeafReaderContext context;
   private final VectorValues.DistanceFunction distFunc;
 
+  private long visitedCount;
+
   public HNSWGraphReader(String field, LeafReaderContext context) {
     this.field = field;
     this.context = context;
@@ -58,9 +62,9 @@ public final class HNSWGraphReader {
     Neighbor ep = new ImmutableNeighbor(enterPoint, VectorValues.distance(query, vectorValues.vectorValue(), distFunc));
     FurthestNeighbors neighbors = new FurthestNeighbors(ef, ep);
     for (int l = hnsw.topLevel(); l > 0; l--) {
-      hnsw.searchLayer(query, neighbors, 1, l, vectorValues);
+      visitedCount += hnsw.searchLayer(query, neighbors, 1, l, vectorValues);
     }
-    hnsw.searchLayer(query, neighbors, ef, 0, vectorValues);
+    visitedCount += hnsw.searchLayer(query, neighbors, ef, 0, vectorValues);
     return neighbors;
   }
 
@@ -122,6 +126,15 @@ public final class HNSWGraphReader {
     return hnsw;
   }
 
+  /**
+   * @return the number of documents visited by this reader. For each visited document, the reader
+   * computed the distance to a target vector.  This count accumulates over the lifetime of the
+   * reader.
+   */
+  public long getVisitedCount() {
+    return visitedCount;
+  }
+
   private static class GraphKey {
     final String field;
     final Object readerId;
diff --git a/lucene/core/src/java/org/apache/lucene/util/hnsw/HNSWGraphWriter.java b/lucene/core/src/java/org/apache/lucene/util/hnsw/HNSWGraphWriter.java
index 2760481..a00cfd3 100644
--- a/lucene/core/src/java/org/apache/lucene/util/hnsw/HNSWGraphWriter.java
+++ b/lucene/core/src/java/org/apache/lucene/util/hnsw/HNSWGraphWriter.java
@@ -64,7 +64,7 @@ public final class HNSWGraphWriter implements Accountable {
   }
 
   /** Full constructor */
-  public HNSWGraphWriter(int maxConn, int maxConn0, int efConst, long seed, int numDimensions, VectorValues.DistanceFunction distFunc) {
+  HNSWGraphWriter(int maxConn, int maxConn0, int efConst, long seed, int numDimensions, VectorValues.DistanceFunction distFunc) {
     this.maxConn = maxConn;
     this.maxConn0 = maxConn0;
     this.efConst = efConst;
@@ -115,7 +115,7 @@ public final class HNSWGraphWriter implements Accountable {
     FurthestNeighbors results = new FurthestNeighbors(efConst, ep);
     // down to the level from the hnsw's top level
     for (int l = hnsw.topLevel(); l > level; l--) {
-      hnsw.searchLayer(value, results, efConst, l, vectorValues);
+      hnsw.searchLayer(value, results, 1, l, vectorValues);
     }
 
     // down to level 0 with placing the doc to each layer
@@ -128,12 +128,10 @@ public final class HNSWGraphWriter implements Accountable {
 
       hnsw.searchLayer(value, results, efConst, l, vectorValues);
       int maxConnections = l == 0 ? maxConn0 : maxConn;
-      NearestNeighbors neighbors = new NearestNeighbors(maxConnections, results.top());
-      for (Neighbor n : results) {
-        neighbors.insertWithOverflow(n);
+      while (results.size() > maxConnections) {
+        results.pop();
       }
-      for (Neighbor n : neighbors) {
-        // TODO: limit *total* num connections by pruning (shrinking)
+      for (Neighbor n : results) {
         hnsw.connectNodes(l, docId, n.docId(), n.distance(), maxConnections);
       }
     }
diff --git a/lucene/core/src/test/org/apache/lucene/util/hnsw/KnnGraphTester.java b/lucene/core/src/test/org/apache/lucene/util/hnsw/KnnGraphTester.java
index ad21eca..f731d15 100644
--- a/lucene/core/src/test/org/apache/lucene/util/hnsw/KnnGraphTester.java
+++ b/lucene/core/src/test/org/apache/lucene/util/hnsw/KnnGraphTester.java
@@ -46,6 +46,8 @@ import org.apache.lucene.index.IndexWriterConfig;
 import org.apache.lucene.index.LeafReader;
 import org.apache.lucene.index.LeafReaderContext;
 import org.apache.lucene.index.KnnGraphValues;
+import org.apache.lucene.index.NoMergePolicy;
+import org.apache.lucene.index.ReaderUtil;
 import org.apache.lucene.index.VectorValues;
 import org.apache.lucene.search.IndexSearcher;
 import org.apache.lucene.search.KnnGraphQuery;
@@ -53,6 +55,7 @@ import org.apache.lucene.search.ScoreDoc;
 import org.apache.lucene.search.TopDocs;
 import org.apache.lucene.store.Directory;
 import org.apache.lucene.store.FSDirectory;
+import org.apache.lucene.util.IntsRef;
 import org.apache.lucene.util.PriorityQueue;
 
 /** For testing indexing and search performance of a knn-graph using random vectors */
@@ -65,51 +68,93 @@ public class KnnGraphTester {
   private int numDocs;
   private int dim;
   private int topK;
-  private int numProbe;
+  private int fanout;
   private float[] vectors;
   private int[] nabors;
+  private Path indexPath;
+
 
   public KnnGraphTester() {
     // set defaults
     numDocs = 10_000;
     dim = 256;
     topK = 10;
-    numProbe = 500;
+    fanout = 50;
     random = new Random();
+    indexPath = Paths.get("knn_test_index");
   }
 
   public static void main(String... args) throws Exception {
-    if (args.length != 2) {
+    new KnnGraphTester().run(args);
+  }
+
+  private void run(String... args) throws Exception {
+    String operation = null, path = null;
+    for (int iarg = 0; iarg < args.length; iarg++) {
+      String arg = args[iarg];
+      switch(arg) {
+        case "-generate":
+        case "-search":
+        case "-check":
+        case "-stats":
+          if (operation != null) {
+            throw new IllegalArgumentException("Specify only one operation, not both " + arg + " and " + operation);
+          }
+          if (iarg == args.length - 1) {
+            throw new IllegalArgumentException("Operation " + arg + " requires a following pathname");
+          }
+          operation = arg;
+          path = args[++iarg];
+          break;
+        case "-fanout":
+          if (iarg == args.length - 1) {
+            throw new IllegalArgumentException("-fanout requires a following number");
+          }
+          fanout = Integer.parseInt(args[++iarg]);
+          break;
+        case "-ndoc":
+          if (iarg == args.length - 1) {
+            throw new IllegalArgumentException("-ndoc requires a following number");
+          }
+          numDocs = Integer.parseInt(args[++iarg]);
+          break;
+        default:
+          usage();
+      }
+    }
+    if (operation == null || path == null) {
       usage();
     }
-    switch (args[0]) {
+    switch (operation) {
       case "-generate":
-        new KnnGraphTester().create(args[1]);
+        create(path);
         break;
       case "-search":
-        new KnnGraphTester().search(args[1]);
+        search(path);
+        break;
+      case "-check":
+        check(path);
         break;
       case "-stats":
-        new KnnGraphTester().stats(args[1]);
+        stats(path);
         break;
-      default:
-        usage();
     }
   }
 
   private void search(String dataFile) throws IOException {
     readDataFile(dataFile);
-    Path indexPath = Paths.get("knn_test_index");
     createIndex(indexPath);
-    // topK = 25;
     testSearch(indexPath, 1000);
-    //GraphSearch.VERBOSE = true;
-    //testSearch(indexPath, 1);
+  }
+
+  private void check(String dataFile) throws IOException {
+    readDataFile(dataFile);
+    createIndex(indexPath);
+    checkIndex(indexPath, 1000);
   }
 
   private void stats(String dataFile) throws IOException {
     readDataFile(dataFile);
-    Path indexPath = Paths.get("knn_test_index");
     createIndex(indexPath);
     printFanoutHist(indexPath);
   }
@@ -176,6 +221,45 @@ public class KnnGraphTester {
     System.out.println("");
   }
 
+  private void checkIndex(Path indexPath, int numIters) throws IOException {
+    float[][] targets = new float[numIters][];
+    TopDocs[] results = new TopDocs[numIters];
+    System.out.println("checking " + numIters + " documents");
+    long start = System.nanoTime();
+    long minVisited = Long.MAX_VALUE, maxVisited = 0, totalVisited = 0;
+    try (Directory dir = FSDirectory.open(indexPath);
+         DirectoryReader reader = DirectoryReader.open(dir)) {
+      int leafCount = reader.leaves().size();
+      for (int i = 0; i < numIters; i++) {
+        targets[i] = new float[dim];
+        int docid = random.nextInt(reader.maxDoc());
+        int readerOrd = ReaderUtil.subIndex(docid, reader.leaves());
+        LeafReaderContext leafReaderContext = reader.leaves().get(readerOrd);
+        int leafDocid = docid - leafReaderContext.docBase;
+        KnnGraphValues graphValues = leafReaderContext.reader().getKnnGraphValues(KNN_FIELD);
+        VectorValues vectorValues = leafReaderContext.reader().getVectorValues(KNN_FIELD);
+        boolean ok = graphValues.advanceExact(leafDocid);
+        if (ok == false) {
+          throw new IllegalStateException("KnnGraphValues failed to advance to docid=" + docid);
+        }
+        IntsRef friends = graphValues.getFriends(0);
+        // check all the supposed friends for overlap with the true list of closest documents
+        int advanced = vectorValues.advance(leafDocid);
+        if (advanced != leafDocid) {
+          throw new IllegalStateException("VectorValues failed to advance to docid=" + docid
+                                          + "; in leaf=" + readerOrd + " having maxDoc=" + leafReaderContext.reader().maxDoc()
+                                          + ", advance(" + leafDocid + ") returned " + advanced);
+        }
+        System.arraycopy(vectorValues.vectorValue(), 0, targets[i], 0, dim);
+        results[i] = new TopDocs(null, new ScoreDoc[friends.length]);
+        for (int j = 0; j < friends.length; j++) {
+          results[i].scoreDocs[j] = new ScoreDoc(leafReaderContext.docBase + friends.ints[friends.offset + j], 0);
+        }
+      }
+    }
+    checkResults(targets, results);
+  }
+
   private void testSearch(Path indexPath, int numIters) throws IOException {
     float[][] targets = new float[numIters][];
     TopDocs[] results = new TopDocs[numIters];
@@ -183,15 +267,19 @@ public class KnnGraphTester {
       targets[i] = new float[dim];
       randomVector(targets[i]);
     }
-    System.out.println("running " + numIters + " targets; topK=" + topK + ", numProbe=" + numProbe);
+    System.out.println("running " + numIters + " targets; topK=" + topK + ", fanout=" + fanout);
     long start = System.nanoTime();
+    long minVisited = Long.MAX_VALUE, maxVisited = 0, totalVisited = 0;
     try (Directory dir = FSDirectory.open(indexPath);
          DirectoryReader reader = DirectoryReader.open(dir)) {
       IndexSearcher searcher = new IndexSearcher(reader);
-      int result = 0;
       for (int i = 0; i < numIters; i++) {
-        KnnGraphQuery query = new KnnGraphQuery(KNN_FIELD, targets[i], numProbe);
+        KnnGraphQuery query = new KnnGraphQuery(KNN_FIELD, targets[i], fanout);
         results[i] = searcher.search(query, topK);
+        long numVisited = query.getVisitedCount();
+        minVisited = Math.min(minVisited, numVisited);
+        maxVisited = Math.max(maxVisited, numVisited);
+        totalVisited += numVisited;
         for (ScoreDoc scoreDoc : results[i].scoreDocs) {
           int id = searcher.doc(scoreDoc.doc).getFields().get(0).numericValue().intValue();
           scoreDoc.doc = id;
@@ -200,6 +288,7 @@ public class KnnGraphTester {
     }
     long elapsed = (System.nanoTime() - start) / 1_000_000; // ns -> ms
     System.out.println("completed " + numIters + " searches in " + elapsed + " ms: " + (1000 * numIters / elapsed) + " QPS");
+    System.out.println(" visited documents avg=" + (totalVisited / 1000) + " min=" + minVisited + " max=" + maxVisited);
     System.out.println("checking results");
     checkResults(targets, results);
   }
@@ -207,21 +296,28 @@ public class KnnGraphTester {
   private void checkResults(float[][] targets, TopDocs[] results) {
     int[] expected = new int[topK];
     int totalMatches = 0;
+    int totalResults = 0;
     for (int i = 0; i < results.length; i++) {
+      /*
       if (results[i].scoreDocs.length != topK) {
         System.err.println("search " + i + " got " + results[i].scoreDocs.length + " results, expecting " + topK);
       }
-      getActualNN(targets[i], 0, expected, 0);
+      */
+      int n = results[i].scoreDocs.length;
+      totalResults += n;
+      if (expected.length < n) {
+        expected = new int[n];
+      }
+      getActualNN(targets[i], 0, expected, 0, n);
       int matched = compareNN(expected, results[i]);
       totalMatches += matched;
     }
-    System.out.println("total matches = " + totalMatches);
-    System.out.println("Average overlap = " + (100.0 * totalMatches / (results.length * topK)) + "%");
+    System.out.println("total matches = " + totalMatches + " out of " + totalResults);
+    System.out.printf("Average overlap = %.2f%%\n", ((100.0 * totalMatches) / totalResults));
   }
 
   int compareNN(int[] expected, TopDocs results) {
     int matched = 0;
-    int i = 0;
     /*
     System.out.print("expected=");
     for (int j = 0; j < expected.length; j++) {
@@ -236,8 +332,8 @@ public class KnnGraphTester {
     System.out.print('\n');
     */
     Set<Integer> expectedSet = new HashSet<>();
-    for (int doc : expected) {
-      expectedSet.add(doc);
+    for (int i = 0; i < results.scoreDocs.length; i++) {
+      expectedSet.add(expected[i]);
     }
     for (ScoreDoc scoreDoc : results.scoreDocs) {
       if (expectedSet.contains(scoreDoc.doc)) {
@@ -253,10 +349,11 @@ public class KnnGraphTester {
    * @param targetOffset offset of the target vector in the target parameter
    * @param nn an array in which to write the resulting nearest neighbor vector indexes
    * @param nnOfset the offset in the nearest neighbor array at which to start writing
+   * @param n how many results to find
    */
-  void getActualNN(float[] targetArray, int targetOffset, int[] nn, int nnOffset) {
-      final ScoreDocQueue queue = new ScoreDocQueue(topK);
-      assert queue.size() == topK : " queue.size()=" + queue.size();
+  void getActualNN(float[] targetArray, int targetOffset, int[] nn, int nnOffset, int n) {
+      final ScoreDocQueue queue = new ScoreDocQueue(n);
+      assert queue.size() == n : " queue.size()=" + queue.size();
       int vectorOffset = 0;
       ScoreDoc bottom = queue.top();
       for (int j = 0; j < numDocs; j++) {
@@ -273,8 +370,9 @@ public class KnnGraphTester {
         vectorOffset += dim;
       }
       assert queue.size() == topK;
-      nnOffset += topK;
-      for (int k = 1; k <= topK; k++) {
+      nnOffset += n;
+      for (int k = 1; k <= n; k++) {
+        // we don't really need these in score order, but we might?
         ScoreDoc scoreDoc = queue.pop();
         //System.out.println("" + scoreDoc.doc + ":" + scoreDoc.score);
         nn[nnOffset - k] = scoreDoc.doc;
@@ -290,6 +388,7 @@ public class KnnGraphTester {
   private void createIndex(Path indexPath) throws IOException {
     IndexWriterConfig iwc = new IndexWriterConfig()
       .setOpenMode(IndexWriterConfig.OpenMode.CREATE);
+    // iwc.setMergePolicy(NoMergePolicy.INSTANCE);
     System.out.println("creating index in " + indexPath);
     long start = System.nanoTime();
     try (FSDirectory dir = FSDirectory.open(indexPath);
@@ -310,7 +409,7 @@ public class KnnGraphTester {
   private void create(String dataFile) throws IOException {
     generateRandomVectors(dim * numDocs);
     System.out.println("Generated " + numDocs + " random vectors");
-    computeNearest();
+    //computeNearest();
     writeDataFile(dataFile);
   }
 
@@ -326,9 +425,11 @@ public class KnnGraphTester {
         vectors[i] = din.readFloat();
       }
       nabors = new int[numDocs * topK];
+      /*
       for (int i = 0; i < nabors.length; i++) {
         nabors[i] = din.readInt();
       }
+      */
     }
   }
 
@@ -342,9 +443,11 @@ public class KnnGraphTester {
       for (int i = 0; i < vectors.length; i++) {
         dout.writeFloat(vectors[i]);
       }
+      /*
       for (int i = 0; i < nabors.length; i++) {
         dout.writeInt(nabors[i]);
       }
+      */
     }
   }
 
@@ -361,7 +464,7 @@ public class KnnGraphTester {
       if (i % 1000 == 1) {
         System.out.println("  " + (i - 1));
       }
-      getActualNN(vectors, i * dim, nabors, i * topK);
+      getActualNN(vectors, i * dim, nabors, i * topK, topK);
     }
   }
 
@@ -379,7 +482,7 @@ public class KnnGraphTester {
   }
 
   private static void usage() {
-    String error = "Usage: TestKnnGraph -generate|-search {datafile}";
+    String error = "Usage: TestKnnGraph -generate|-search|-stats|-check {datafile} [-fanout N]";
     System.err.println(error);
     System.exit(1);
   }