/
SiftSmall.java
338 lines (304 loc) · 18.7 KB
/
SiftSmall.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
/*
* Copyright DataStax, Inc.
*
* Licensed 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 io.github.jbellis.jvector.example;
import io.github.jbellis.jvector.disk.RandomAccessReader;
import io.github.jbellis.jvector.disk.ReaderSupplier;
import io.github.jbellis.jvector.disk.SimpleMappedReader;
import io.github.jbellis.jvector.disk.SimpleMappedReaderSupplier;
import io.github.jbellis.jvector.example.util.MMapReaderSupplier;
import io.github.jbellis.jvector.example.util.SiftLoader;
import io.github.jbellis.jvector.graph.GraphIndex;
import io.github.jbellis.jvector.graph.GraphIndexBuilder;
import io.github.jbellis.jvector.graph.GraphSearcher;
import io.github.jbellis.jvector.graph.ListRandomAccessVectorValues;
import io.github.jbellis.jvector.graph.OnHeapGraphIndex;
import io.github.jbellis.jvector.graph.RandomAccessVectorValues;
import io.github.jbellis.jvector.graph.SearchResult;
import io.github.jbellis.jvector.graph.disk.Feature;
import io.github.jbellis.jvector.graph.disk.FeatureId;
import io.github.jbellis.jvector.graph.disk.InlineVectorValues;
import io.github.jbellis.jvector.graph.disk.InlineVectors;
import io.github.jbellis.jvector.graph.disk.OnDiskGraphIndex;
import io.github.jbellis.jvector.graph.disk.OnDiskGraphIndexWriter;
import io.github.jbellis.jvector.graph.similarity.BuildScoreProvider;
import io.github.jbellis.jvector.graph.similarity.ScoreFunction.ApproximateScoreFunction;
import io.github.jbellis.jvector.graph.similarity.ScoreFunction.Reranker;
import io.github.jbellis.jvector.graph.similarity.SearchScoreProvider;
import io.github.jbellis.jvector.pq.PQVectors;
import io.github.jbellis.jvector.pq.ProductQuantization;
import io.github.jbellis.jvector.util.Bits;
import io.github.jbellis.jvector.util.ExceptionUtils;
import io.github.jbellis.jvector.util.ExplicitThreadLocal;
import io.github.jbellis.jvector.vector.VectorSimilarityFunction;
import io.github.jbellis.jvector.vector.VectorUtil;
import io.github.jbellis.jvector.vector.VectorizationProvider;
import io.github.jbellis.jvector.vector.types.ByteSequence;
import io.github.jbellis.jvector.vector.types.VectorFloat;
import io.github.jbellis.jvector.vector.types.VectorTypeSupport;
import java.io.BufferedOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Function;
import java.util.stream.IntStream;
import static java.lang.Math.min;
// this class uses explicit typing instead of `var` for easier reading when excerpted for instructional use
public class SiftSmall {
private static final VectorTypeSupport vts = VectorizationProvider.getInstance().getVectorTypeSupport();
// hello world
public static void siftInMemory(ArrayList<VectorFloat<?>> baseVectors) throws IOException {
// infer the dimensionality from the first vector
int originalDimension = baseVectors.get(0).length();
// wrap the raw vectors in a RandomAccessVectorValues
RandomAccessVectorValues ravv = new ListRandomAccessVectorValues(baseVectors, originalDimension);
// score provider using the raw, in-memory vectors
BuildScoreProvider bsp = BuildScoreProvider.randomAccessScoreProvider(ravv, VectorSimilarityFunction.EUCLIDEAN);
try (GraphIndexBuilder builder = new GraphIndexBuilder(bsp,
ravv.dimension(),
16, // graph degree
100, // construction search depth
1.2f, // allow degree overflow during construction by this factor
1.2f)) // relax neighbor diversity requirement by this factor
{
// build the index (in memory)
OnHeapGraphIndex index = builder.build(ravv);
// search for a random vector
VectorFloat<?> q = randomVector(originalDimension);
SearchResult sr = GraphSearcher.search(q,
10, // number of results
ravv, // vectors we're searching, used for scoring
VectorSimilarityFunction.EUCLIDEAN, // how to score
index,
Bits.ALL); // valid ordinals to consider
for (SearchResult.NodeScore ns : sr.getNodes()) {
System.out.println(ns);
}
}
}
// show how to use explicit GraphSearcher objects
public static void siftInMemoryWithSearcher(ArrayList<VectorFloat<?>> baseVectors) throws IOException {
int originalDimension = baseVectors.get(0).length();
RandomAccessVectorValues ravv = new ListRandomAccessVectorValues(baseVectors, originalDimension);
BuildScoreProvider bsp = BuildScoreProvider.randomAccessScoreProvider(ravv, VectorSimilarityFunction.EUCLIDEAN);
try (GraphIndexBuilder builder = new GraphIndexBuilder(bsp, ravv.dimension(), 16, 100, 1.2f, 1.2f)) {
OnHeapGraphIndex index = builder.build(ravv);
// search for a random vector using a GraphSearcher and SearchScoreProvider
VectorFloat<?> q = randomVector(originalDimension);
try (GraphSearcher searcher = new GraphSearcher(index)) {
SearchScoreProvider ssp = SearchScoreProvider.exact(q, VectorSimilarityFunction.EUCLIDEAN, ravv);
SearchResult sr = searcher.search(ssp, 10, Bits.ALL);
for (SearchResult.NodeScore ns : sr.getNodes()) {
System.out.println(ns);
}
}
}
}
// call out to testRecall instead of doing manual searches
public static void siftInMemoryWithRecall(List<VectorFloat<?>> baseVectors, List<VectorFloat<?>> queryVectors, List<Set<Integer>> groundTruth) throws IOException {
int originalDimension = baseVectors.get(0).length();
RandomAccessVectorValues ravv = new ListRandomAccessVectorValues(baseVectors, originalDimension);
BuildScoreProvider bsp = BuildScoreProvider.randomAccessScoreProvider(ravv, VectorSimilarityFunction.EUCLIDEAN);
try (GraphIndexBuilder builder = new GraphIndexBuilder(bsp, ravv.dimension(), 16, 100, 1.2f, 1.2f)) {
OnHeapGraphIndex index = builder.build(ravv);
// measure our recall against the (exactly computed) ground truth
Function<VectorFloat<?>, SearchScoreProvider> sspFactory = q -> SearchScoreProvider.exact(q, VectorSimilarityFunction.EUCLIDEAN, ravv);
testRecall(index, queryVectors, groundTruth, sspFactory);
}
}
// write and load index to and from disk
public static void siftPersisted(List<VectorFloat<?>> baseVectors, List<VectorFloat<?>> queryVectors, List<Set<Integer>> groundTruth) throws IOException {
int originalDimension = baseVectors.get(0).length();
RandomAccessVectorValues ravv = new ListRandomAccessVectorValues(baseVectors, originalDimension);
BuildScoreProvider bsp = BuildScoreProvider.randomAccessScoreProvider(ravv, VectorSimilarityFunction.EUCLIDEAN);
Path indexPath = Files.createTempFile("siftsmall", ".inline");
try (GraphIndexBuilder builder = new GraphIndexBuilder(bsp, ravv.dimension(), 16, 100, 1.2f, 1.2f)) {
// build the index (in memory)
OnHeapGraphIndex index = builder.build(ravv);
// write the index to disk with default options
OnDiskGraphIndex.write(index, ravv, indexPath);
}
// on-disk indexes require a ReaderSupplier (not just a Reader) because we will want it to
// open additional readers for searching
ReaderSupplier rs = new SimpleMappedReaderSupplier(indexPath);
OnDiskGraphIndex index = OnDiskGraphIndex.load(rs);
// measure our recall against the (exactly computed) ground truth
Function<VectorFloat<?>, SearchScoreProvider> sspFactory = q -> SearchScoreProvider.exact(q, VectorSimilarityFunction.EUCLIDEAN, ravv);
testRecall(index, queryVectors, groundTruth, sspFactory);
}
// diskann-style index with PQ
public static void siftDiskAnn(List<VectorFloat<?>> baseVectors, List<VectorFloat<?>> queryVectors, List<Set<Integer>> groundTruth) throws IOException {
int originalDimension = baseVectors.get(0).length();
RandomAccessVectorValues ravv = new ListRandomAccessVectorValues(baseVectors, originalDimension);
BuildScoreProvider bsp = BuildScoreProvider.randomAccessScoreProvider(ravv, VectorSimilarityFunction.EUCLIDEAN);
Path indexPath = Files.createTempFile("siftsmall", ".inline");
try (GraphIndexBuilder builder = new GraphIndexBuilder(bsp, ravv.dimension(), 16, 100, 1.2f, 1.2f)) {
OnHeapGraphIndex index = builder.build(ravv);
OnDiskGraphIndex.write(index, ravv, indexPath);
}
// compute and write compressed vectors to disk
Path pqPath = Files.createTempFile("siftsmall", ".pq");
try (DataOutputStream out = new DataOutputStream(new BufferedOutputStream(Files.newOutputStream(pqPath)))) {
// Compress the original vectors using PQ. this represents a compression ratio of 128 * 4 / 16 = 32x
ProductQuantization pq = ProductQuantization.compute(ravv,
16, // number of subspaces
256, // number of centroids per subspace
true); // center the dataset
ByteSequence<?>[] compressed = pq.encodeAll(ravv);
// write the compressed vectors to disk
PQVectors pqv = new PQVectors(pq, compressed);
pqv.write(out);
}
ReaderSupplier rs = new MMapReaderSupplier(indexPath);
OnDiskGraphIndex index = OnDiskGraphIndex.load(rs);
// load the PQVectors that we just wrote to disk
try (RandomAccessReader in = new SimpleMappedReader(pqPath)) {
PQVectors pqv = PQVectors.load(in);
// SearchScoreProvider that does a first pass with the loaded-in-memory PQVectors,
// then reranks with the exact vectors that are stored on disk in the index
Function<VectorFloat<?>, SearchScoreProvider> sspFactory = q -> {
ApproximateScoreFunction asf = pqv.precomputedScoreFunctionFor(q, VectorSimilarityFunction.EUCLIDEAN);
Reranker reranker = index.getView().rerankerFor(q, VectorSimilarityFunction.EUCLIDEAN);
return new SearchScoreProvider(asf, reranker);
};
// measure our recall against the (exactly computed) ground truth
testRecall(index, queryVectors, groundTruth, sspFactory);
}
}
public static void siftDiskAnnLTM(List<VectorFloat<?>> baseVectors, List<VectorFloat<?>> queryVectors, List<Set<Integer>> groundTruth) throws IOException {
int originalDimension = baseVectors.get(0).length();
RandomAccessVectorValues ravv = new ListRandomAccessVectorValues(baseVectors, originalDimension);
// compute the codebook, but don't encode any vectors yet
ProductQuantization pq = ProductQuantization.compute(ravv, 16, 256, true);
Path indexPath = Files.createTempFile("siftsmall", ".inline");
Path pqPath = Files.createTempFile("siftsmall", ".pq");
// Builder creation looks mostly the same, but we need to set the BuildScoreProvider after the PQVectors are created
try (GraphIndexBuilder builder = new GraphIndexBuilder(null,
ravv.dimension(), 16, 100, 1.2f, 1.2f);
// explicit Writer for the first time, this is what's behind OnDiskGraphIndex.write
OnDiskGraphIndexWriter writer = new OnDiskGraphIndexWriter.Builder(builder.getGraph(), indexPath)
.with(new InlineVectors(ravv.dimension()))
.withMapper(new OnDiskGraphIndexWriter.IdentityMapper())
.build();
// you can use the partially written index as a source of the vectors written so far
InlineVectorValues ivv = new InlineVectorValues(ravv.dimension(), writer);
// output for the compressed vectors
DataOutputStream pqOut = new DataOutputStream(new BufferedOutputStream(Files.newOutputStream(pqPath))))
{
// as we build the index we'll compress the new vectors and add them to this List backing a PQVectors
List<ByteSequence<?>> incrementallyCompressedVectors = new ArrayList<>();
PQVectors pqv = new PQVectors(pq, incrementallyCompressedVectors);
// now we can create the actual BuildScoreProvider based on PQ + reranking
BuildScoreProvider bsp = BuildScoreProvider.pqBuildScoreProvider(VectorSimilarityFunction.EUCLIDEAN, ivv, pqv);
builder.setBuildScoreProvider(bsp);
// build the index vector-at-a-time (on disk)
for (VectorFloat<?> v : baseVectors) {
// compress the new vector and add it to the PQVectors (via incrementallyCompressedVectors)
int ordinal = incrementallyCompressedVectors.size();
incrementallyCompressedVectors.add(pq.encode(v));
// write the full vector to disk
writer.writeInline(ordinal, Feature.singleState(FeatureId.INLINE_VECTORS, new InlineVectors.State(v)));
// now add it to the graph -- the previous steps must be completed first since the PQVectors
// and InlineVectorValues are both used during the search that runs as part of addGraphNode construction
builder.addGraphNode(ordinal, v);
}
// cleanup does a final enforcement of maxDegree and handles other scenarios like deleted nodes
// that we don't need to worry about here
builder.cleanup();
// finish writing the index (by filling in the edge lists) and write our completed PQVectors
writer.write(Map.of());
pqv.write(pqOut);
}
// searching the index does not change
ReaderSupplier rs = new MMapReaderSupplier(indexPath);
OnDiskGraphIndex index = OnDiskGraphIndex.load(rs);
try (RandomAccessReader in = new SimpleMappedReader(pqPath)) {
PQVectors pqv = PQVectors.load(in);
Function<VectorFloat<?>, SearchScoreProvider> sspFactory = q -> {
ApproximateScoreFunction asf = pqv.precomputedScoreFunctionFor(q, VectorSimilarityFunction.EUCLIDEAN);
Reranker reranker = index.getView().rerankerFor(q, VectorSimilarityFunction.EUCLIDEAN);
return new SearchScoreProvider(asf, reranker);
};
testRecall(index, queryVectors, groundTruth, sspFactory);
}
}
//
// Utilities and main() harness
//
public static VectorFloat<?> randomVector(int dim) {
Random R = ThreadLocalRandom.current();
VectorFloat<?> vec = vts.createFloatVector(dim);
for (int i = 0; i < dim; i++) {
vec.set(i, R.nextFloat());
if (R.nextBoolean()) {
vec.set(i, -vec.get(i));
}
}
VectorUtil.l2normalize(vec);
return vec;
}
private static void testRecall(GraphIndex graph,
List<VectorFloat<?>> queryVectors,
List<Set<Integer>> groundTruth,
Function<VectorFloat<?>,
SearchScoreProvider> sspFactory)
throws IOException
{
AtomicInteger topKfound = new AtomicInteger(0);
int topK = 100;
String graphType = graph.getClass().getSimpleName();
try (ExplicitThreadLocal<GraphSearcher> searchers = ExplicitThreadLocal.withInitial(() -> new GraphSearcher(graph))) {
IntStream.range(0, queryVectors.size()).parallel().forEach(i -> {
VectorFloat<?> queryVector = queryVectors.get(i);
try (GraphSearcher searcher = searchers.get()) {
SearchScoreProvider ssp = sspFactory.apply(queryVector);
int rerankK = ssp.scoreFunction().isExact() ? topK : 2 * topK; // hardcoded overquery factor of 2x when reranking
SearchResult.NodeScore[] nn = searcher.search(ssp, rerankK, Bits.ALL).getNodes();
Set<Integer> gt = groundTruth.get(i);
long n = IntStream.range(0, min(topK, nn.length)).filter(j -> gt.contains(nn[j].node)).count();
topKfound.addAndGet((int) n);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
});
} catch (Exception e) {
ExceptionUtils.throwIoException(e);
}
System.out.printf("(%s) Recall: %.4f%n", graphType, (double) topKfound.get() / (queryVectors.size() * topK));
}
public static void main(String[] args) throws IOException {
var siftPath = "siftsmall";
var baseVectors = SiftLoader.readFvecs(String.format("%s/siftsmall_base.fvecs", siftPath));
var queryVectors = SiftLoader.readFvecs(String.format("%s/siftsmall_query.fvecs", siftPath));
var groundTruth = SiftLoader.readIvecs(String.format("%s/siftsmall_groundtruth.ivecs", siftPath));
System.out.format("%d base and %d query vectors loaded, dimensions %d%n",
baseVectors.size(), queryVectors.size(), baseVectors.get(0).length());
siftInMemory(baseVectors);
siftInMemoryWithSearcher(baseVectors);
siftInMemoryWithRecall(baseVectors, queryVectors, groundTruth);
siftPersisted(baseVectors, queryVectors, groundTruth);
siftDiskAnn(baseVectors, queryVectors, groundTruth);
siftDiskAnnLTM(baseVectors, queryVectors, groundTruth);
}
}