-
Notifications
You must be signed in to change notification settings - Fork 587
/
Copy pathSSDIndex.h
522 lines (441 loc) · 26.2 KB
/
SSDIndex.h
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
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#pragma once
#include <limits>
#include "inc/Core/Common.h"
#include "inc/Core/Common/DistanceUtils.h"
#include "inc/Core/Common/QueryResultSet.h"
#include "inc/Core/SPANN/Index.h"
#include "inc/Core/SPANN/ExtraFullGraphSearcher.h"
#include "inc/Helper/VectorSetReader.h"
#include "inc/Helper/StringConvert.h"
#include "inc/SSDServing/Utils.h"
namespace SPTAG {
namespace SSDServing {
namespace SSDIndex {
template <typename ValueType>
ErrorCode OutputResult(const std::string& p_output, std::vector<QueryResult>& p_results, int p_resultNum)
{
if (!p_output.empty())
{
auto ptr = f_createIO();
if (ptr == nullptr || !ptr->Initialize(p_output.c_str(), std::ios::binary | std::ios::out)) {
LOG(Helper::LogLevel::LL_Error, "Failed create file: %s\n", p_output.c_str());
return ErrorCode::FailedCreateFile;
}
int32_t i32Val = static_cast<int32_t>(p_results.size());
if (ptr->WriteBinary(sizeof(i32Val), reinterpret_cast<char*>(&i32Val)) != sizeof(i32Val)) {
LOG(Helper::LogLevel::LL_Error, "Fail to write result file!\n");
return ErrorCode::DiskIOFail;
}
i32Val = p_resultNum;
if (ptr->WriteBinary(sizeof(i32Val), reinterpret_cast<char*>(&i32Val)) != sizeof(i32Val)) {
LOG(Helper::LogLevel::LL_Error, "Fail to write result file!\n");
return ErrorCode::DiskIOFail;
}
float fVal = 0;
for (size_t i = 0; i < p_results.size(); ++i)
{
for (int j = 0; j < p_resultNum; ++j)
{
i32Val = p_results[i].GetResult(j)->VID;
if (ptr->WriteBinary(sizeof(i32Val), reinterpret_cast<char*>(&i32Val)) != sizeof(i32Val)) {
LOG(Helper::LogLevel::LL_Error, "Fail to write result file!\n");
return ErrorCode::DiskIOFail;
}
fVal = p_results[i].GetResult(j)->Dist;
if (ptr->WriteBinary(sizeof(fVal), reinterpret_cast<char*>(&fVal)) != sizeof(fVal)) {
LOG(Helper::LogLevel::LL_Error, "Fail to write result file!\n");
return ErrorCode::DiskIOFail;
}
}
}
}
return ErrorCode::Success;
}
template<typename T, typename V>
void PrintPercentiles(const std::vector<V>& p_values, std::function<T(const V&)> p_get, const char* p_format)
{
double sum = 0;
std::vector<T> collects;
collects.reserve(p_values.size());
for (const auto& v : p_values)
{
T tmp = p_get(v);
sum += tmp;
collects.push_back(tmp);
}
std::sort(collects.begin(), collects.end());
LOG(Helper::LogLevel::LL_Info, "Avg\t50tiles\t90tiles\t95tiles\t99tiles\t99.9tiles\tMax\n");
std::string formatStr("%.3lf");
for (int i = 1; i < 7; ++i)
{
formatStr += '\t';
formatStr += p_format;
}
formatStr += '\n';
LOG(Helper::LogLevel::LL_Info,
formatStr.c_str(),
sum / collects.size(),
collects[static_cast<size_t>(collects.size() * 0.50)],
collects[static_cast<size_t>(collects.size() * 0.90)],
collects[static_cast<size_t>(collects.size() * 0.95)],
collects[static_cast<size_t>(collects.size() * 0.99)],
collects[static_cast<size_t>(collects.size() * 0.999)],
collects[static_cast<size_t>(collects.size() - 1)]);
}
template <typename ValueType>
void SearchSequential(SPANN::Index<ValueType>* p_index,
int p_numThreads,
std::vector<QueryResult>& p_results,
std::vector<SPANN::SearchStats>& p_stats,
int p_maxQueryCount, int p_internalResultNum)
{
int numQueries = min(static_cast<int>(p_results.size()), p_maxQueryCount);
std::atomic_size_t queriesSent(0);
std::vector<std::thread> threads;
LOG(Helper::LogLevel::LL_Info, "Searching: numThread: %d, numQueries: %d.\n", p_numThreads, numQueries);
Utils::StopW sw;
auto func = [&]()
{
Utils::StopW threadws;
size_t index = 0;
while (true)
{
index = queriesSent.fetch_add(1);
if (index < numQueries)
{
if ((index & ((1 << 14) - 1)) == 0)
{
LOG(Helper::LogLevel::LL_Info, "Sent %.2lf%%...\n", index * 100.0 / numQueries);
}
double startTime = threadws.getElapsedMs();
p_index->GetMemoryIndex()->SearchIndex(p_results[index]);
double endTime = threadws.getElapsedMs();
p_index->SearchDiskIndex(p_results[index], &(p_stats[index]));
double exEndTime = threadws.getElapsedMs();
p_stats[index].m_exLatency = exEndTime - endTime;
p_stats[index].m_totalLatency = p_stats[index].m_totalSearchLatency = exEndTime - startTime;
}
else
{
return;
}
}
};
for (int i = 0; i < p_numThreads; i++) { threads.emplace_back(func); }
for (auto& thread : threads) { thread.join(); }
double sendingCost = sw.getElapsedSec();
LOG(Helper::LogLevel::LL_Info,
"Finish sending in %.3lf seconds, actuallQPS is %.2lf, query count %u.\n",
sendingCost,
numQueries / sendingCost,
static_cast<uint32_t>(numQueries));
for (int i = 0; i < numQueries; i++) { p_results[i].CleanQuantizedTarget(); }
}
template <typename ValueType>
void Search(SPANN::Index<ValueType>* p_index)
{
SPANN::Options& p_opts = *(p_index->GetOptions());
std::string outputFile = p_opts.m_searchResult;
std::string truthFile = p_opts.m_truthPath;
std::string warmupFile = p_opts.m_warmupPath;
if (p_index->m_pQuantizer)
{
p_index->m_pQuantizer->SetEnableADC(p_opts.m_enableADC);
}
if (!p_opts.m_logFile.empty())
{
GetLogger().reset(new Helper::FileLogger(Helper::LogLevel::LL_Info, p_opts.m_logFile.c_str()));
}
int numThreads = p_opts.m_iSSDNumberOfThreads;
int internalResultNum = p_opts.m_searchInternalResultNum;
int K = p_opts.m_resultNum;
int truthK = (p_opts.m_truthResultNum <= 0) ? K : p_opts.m_truthResultNum;
if (!warmupFile.empty())
{
LOG(Helper::LogLevel::LL_Info, "Start loading warmup query set...\n");
std::shared_ptr<Helper::ReaderOptions> queryOptions(new Helper::ReaderOptions(p_opts.m_valueType, p_opts.m_dim, p_opts.m_warmupType, p_opts.m_warmupDelimiter));
auto queryReader = Helper::VectorSetReader::CreateInstance(queryOptions);
if (ErrorCode::Success != queryReader->LoadFile(p_opts.m_warmupPath))
{
LOG(Helper::LogLevel::LL_Error, "Failed to read query file.\n");
exit(1);
}
auto warmupQuerySet = queryReader->GetVectorSet();
int warmupNumQueries = warmupQuerySet->Count();
std::vector<QueryResult> warmupResults(warmupNumQueries, QueryResult(NULL, max(K, internalResultNum), false));
std::vector<SPANN::SearchStats> warmpUpStats(warmupNumQueries);
for (int i = 0; i < warmupNumQueries; ++i)
{
(*((COMMON::QueryResultSet<ValueType>*)&warmupResults[i])).SetTarget(reinterpret_cast<ValueType*>(warmupQuerySet->GetVector(i)), p_index->m_pQuantizer);
warmupResults[i].Reset();
}
LOG(Helper::LogLevel::LL_Info, "Start warmup...\n");
SearchSequential(p_index, numThreads, warmupResults, warmpUpStats, p_opts.m_queryCountLimit, internalResultNum);
LOG(Helper::LogLevel::LL_Info, "\nFinish warmup...\n");
}
LOG(Helper::LogLevel::LL_Info, "Start loading QuerySet...\n");
std::shared_ptr<Helper::ReaderOptions> queryOptions(new Helper::ReaderOptions(p_opts.m_valueType, p_opts.m_dim, p_opts.m_queryType, p_opts.m_queryDelimiter));
auto queryReader = Helper::VectorSetReader::CreateInstance(queryOptions);
if (ErrorCode::Success != queryReader->LoadFile(p_opts.m_queryPath))
{
LOG(Helper::LogLevel::LL_Error, "Failed to read query file.\n");
exit(1);
}
auto querySet = queryReader->GetVectorSet();
int numQueries = querySet->Count();
std::vector<QueryResult> results(numQueries, QueryResult(NULL, max(K, internalResultNum), false));
std::vector<SPANN::SearchStats> stats(numQueries);
for (int i = 0; i < numQueries; ++i)
{
(*((COMMON::QueryResultSet<ValueType>*)&results[i])).SetTarget(reinterpret_cast<ValueType*>(querySet->GetVector(i)), p_index->m_pQuantizer);
results[i].Reset();
}
LOG(Helper::LogLevel::LL_Info, "Start ANN Search...\n");
SearchSequential(p_index, numThreads, results, stats, p_opts.m_queryCountLimit, internalResultNum);
LOG(Helper::LogLevel::LL_Info, "\nFinish ANN Search...\n");
std::shared_ptr<VectorSet> vectorSet;
if (!p_opts.m_vectorPath.empty() && fileexists(p_opts.m_vectorPath.c_str())) {
std::shared_ptr<Helper::ReaderOptions> vectorOptions(new Helper::ReaderOptions(p_opts.m_valueType, p_opts.m_dim, p_opts.m_vectorType, p_opts.m_vectorDelimiter));
auto vectorReader = Helper::VectorSetReader::CreateInstance(vectorOptions);
if (ErrorCode::Success == vectorReader->LoadFile(p_opts.m_vectorPath))
{
vectorSet = vectorReader->GetVectorSet();
if (p_opts.m_distCalcMethod == DistCalcMethod::Cosine) vectorSet->Normalize(numThreads);
LOG(Helper::LogLevel::LL_Info, "\nLoad VectorSet(%d,%d).\n", vectorSet->Count(), vectorSet->Dimension());
}
}
if (p_opts.m_rerank > 0 && vectorSet != nullptr) {
LOG(Helper::LogLevel::LL_Info, "\n Begin rerank...\n");
for (int i = 0; i < results.size(); i++)
{
for (int j = 0; j < K; j++)
{
if (results[i].GetResult(j)->VID < 0) continue;
results[i].GetResult(j)->Dist = COMMON::DistanceUtils::ComputeDistance((const ValueType*)querySet->GetVector(i),
(const ValueType*)vectorSet->GetVector(results[i].GetResult(j)->VID), querySet->Dimension(), p_opts.m_distCalcMethod);
}
BasicResult* re = results[i].GetResults();
std::sort(re, re + K, COMMON::Compare);
}
K = p_opts.m_rerank;
}
float recall = 0, MRR = 0;
std::vector<std::set<SizeType>> truth;
if (!truthFile.empty())
{
LOG(Helper::LogLevel::LL_Info, "Start loading TruthFile...\n");
auto ptr = f_createIO();
if (ptr == nullptr || !ptr->Initialize(truthFile.c_str(), std::ios::in | std::ios::binary)) {
LOG(Helper::LogLevel::LL_Error, "Failed open truth file: %s\n", truthFile.c_str());
exit(1);
}
int originalK = truthK;
COMMON::TruthSet::LoadTruth(ptr, truth, numQueries, originalK, truthK, p_opts.m_truthType);
char tmp[4];
if (ptr->ReadBinary(4, tmp) == 4) {
LOG(Helper::LogLevel::LL_Error, "Truth number is larger than query number(%d)!\n", numQueries);
}
recall = COMMON::TruthSet::CalculateRecall<ValueType>((p_index->GetMemoryIndex()).get(), results, truth, K, truthK, querySet, vectorSet, numQueries, nullptr, false, &MRR);
LOG(Helper::LogLevel::LL_Info, "Recall%d@%d: %f MRR@%d: %f\n", truthK, K, recall, K, MRR);
}
LOG(Helper::LogLevel::LL_Info, "\nEx Elements Count:\n");
PrintPercentiles<double, SPANN::SearchStats>(stats,
[](const SPANN::SearchStats& ss) -> double
{
return ss.m_totalListElementsCount;
},
"%.3lf");
LOG(Helper::LogLevel::LL_Info, "\nHead Latency Distribution:\n");
PrintPercentiles<double, SPANN::SearchStats>(stats,
[](const SPANN::SearchStats& ss) -> double
{
return ss.m_totalSearchLatency - ss.m_exLatency;
},
"%.3lf");
LOG(Helper::LogLevel::LL_Info, "\nEx Latency Distribution:\n");
PrintPercentiles<double, SPANN::SearchStats>(stats,
[](const SPANN::SearchStats& ss) -> double
{
return ss.m_exLatency;
},
"%.3lf");
LOG(Helper::LogLevel::LL_Info, "\nTotal Latency Distribution:\n");
PrintPercentiles<double, SPANN::SearchStats>(stats,
[](const SPANN::SearchStats& ss) -> double
{
return ss.m_totalSearchLatency;
},
"%.3lf");
LOG(Helper::LogLevel::LL_Info, "\nTotal Disk Page Access Distribution:\n");
PrintPercentiles<int, SPANN::SearchStats>(stats,
[](const SPANN::SearchStats& ss) -> int
{
return ss.m_diskAccessCount;
},
"%4d");
LOG(Helper::LogLevel::LL_Info, "\nTotal Disk IO Distribution:\n");
PrintPercentiles<int, SPANN::SearchStats>(stats,
[](const SPANN::SearchStats& ss) -> int
{
return ss.m_diskIOCount;
},
"%4d");
LOG(Helper::LogLevel::LL_Info, "\n");
if (!outputFile.empty())
{
LOG(Helper::LogLevel::LL_Info, "Start output to %s\n", outputFile.c_str());
OutputResult<ValueType>(outputFile, results, K);
}
LOG(Helper::LogLevel::LL_Info,
"Recall@%d: %f MRR@%d: %f\n", K, recall, K, MRR);
LOG(Helper::LogLevel::LL_Info, "\n");
if (p_opts.m_recall_analysis) {
LOG(Helper::LogLevel::LL_Info, "Start recall analysis...\n");
std::shared_ptr<VectorIndex> headIndex = p_index->GetMemoryIndex();
SizeType sampleSize = numQueries < 100 ? numQueries : 100;
SizeType sampleK = headIndex->GetNumSamples() < 1000 ? headIndex->GetNumSamples() : 1000;
float sampleE = 1e-6f;
std::vector<SizeType> samples(sampleSize, 0);
std::vector<float> queryHeadRecalls(sampleSize, 0);
std::vector<float> truthRecalls(sampleSize, 0);
std::vector<int> shouldSelect(sampleSize, 0);
std::vector<int> shouldSelectLong(sampleSize, 0);
std::vector<int> nearQueryHeads(sampleSize, 0);
std::vector<int> annNotFound(sampleSize, 0);
std::vector<int> rngRule(sampleSize, 0);
std::vector<int> postingCut(sampleSize, 0);
for (int i = 0; i < sampleSize; i++) samples[i] = COMMON::Utils::rand(numQueries);
#pragma omp parallel for schedule(dynamic)
for (int i = 0; i < sampleSize; i++)
{
COMMON::QueryResultSet<ValueType> queryANNHeads((const ValueType*)(querySet->GetVector(samples[i])), max(K, internalResultNum));
headIndex->SearchIndex(queryANNHeads);
float queryANNHeadsLongestDist = queryANNHeads.GetResult(internalResultNum - 1)->Dist;
COMMON::QueryResultSet<ValueType> queryBFHeads((const ValueType*)(querySet->GetVector(samples[i])), max(sampleK, internalResultNum));
for (SizeType y = 0; y < headIndex->GetNumSamples(); y++)
{
float dist = headIndex->ComputeDistance(queryBFHeads.GetQuantizedTarget(), headIndex->GetSample(y));
queryBFHeads.AddPoint(y, dist);
}
queryBFHeads.SortResult();
{
std::vector<bool> visited(internalResultNum, false);
for (SizeType y = 0; y < internalResultNum; y++)
{
for (SizeType z = 0; z < internalResultNum; z++)
{
if (visited[z]) continue;
if (fabs(queryANNHeads.GetResult(z)->Dist - queryBFHeads.GetResult(y)->Dist) < sampleE)
{
queryHeadRecalls[i] += 1;
visited[z] = true;
break;
}
}
}
}
std::map<int, std::set<int>> tmpFound; // headID->truths
p_index->DebugSearchDiskIndex(queryBFHeads, internalResultNum, sampleK, nullptr, &truth[samples[i]], &tmpFound);
for (SizeType z = 0; z < K; z++) {
truthRecalls[i] += truth[samples[i]].count(queryBFHeads.GetResult(z)->VID);
}
for (SizeType z = 0; z < K; z++) {
truth[samples[i]].erase(results[samples[i]].GetResult(z)->VID);
}
for (std::map<int, std::set<int>>::iterator it = tmpFound.begin(); it != tmpFound.end(); it++) {
float q2truthposting = headIndex->ComputeDistance(querySet->GetVector(samples[i]), headIndex->GetSample(it->first));
for (auto vid : it->second) {
if (!truth[samples[i]].count(vid)) continue;
if (q2truthposting < queryANNHeadsLongestDist) shouldSelect[i] += 1;
else {
shouldSelectLong[i] += 1;
std::set<int> nearQuerySelectedHeads;
float v2vhead = headIndex->ComputeDistance(vectorSet->GetVector(vid), headIndex->GetSample(it->first));
for (SizeType z = 0; z < internalResultNum; z++) {
if (queryANNHeads.GetResult(z)->VID < 0) break;
float v2qhead = headIndex->ComputeDistance(vectorSet->GetVector(vid), headIndex->GetSample(queryANNHeads.GetResult(z)->VID));
if (v2qhead < v2vhead) {
nearQuerySelectedHeads.insert(queryANNHeads.GetResult(z)->VID);
}
}
if (nearQuerySelectedHeads.size() == 0) continue;
nearQueryHeads[i] += 1;
COMMON::QueryResultSet<ValueType> annTruthHead((const ValueType*)(vectorSet->GetVector(vid)), p_opts.m_debugBuildInternalResultNum);
headIndex->SearchIndex(annTruthHead);
bool found = false;
for (SizeType z = 0; z < annTruthHead.GetResultNum(); z++) {
if (nearQuerySelectedHeads.count(annTruthHead.GetResult(z)->VID)) {
found = true;
break;
}
}
if (!found) {
annNotFound[i] += 1;
continue;
}
// RNG rule and posting cut
std::set<int> replicas;
for (SizeType z = 0; z < annTruthHead.GetResultNum() && replicas.size() < p_opts.m_replicaCount; z++) {
BasicResult* item = annTruthHead.GetResult(z);
if (item->VID < 0) break;
bool good = true;
for (auto r : replicas) {
if (p_opts.m_rngFactor * headIndex->ComputeDistance(headIndex->GetSample(r), headIndex->GetSample(item->VID)) < item->Dist) {
good = false;
break;
}
}
if (good) replicas.insert(item->VID);
}
found = false;
for (auto r : nearQuerySelectedHeads) {
if (replicas.count(r)) {
found = true;
break;
}
}
if (found) postingCut[i] += 1;
else rngRule[i] += 1;
}
}
}
}
float headacc = 0, truthacc = 0, shorter = 0, longer = 0, lost = 0, buildNearQueryHeads = 0, buildAnnNotFound = 0, buildRNGRule = 0, buildPostingCut = 0;
for (int i = 0; i < sampleSize; i++) {
headacc += queryHeadRecalls[i];
truthacc += truthRecalls[i];
lost += shouldSelect[i] + shouldSelectLong[i];
shorter += shouldSelect[i];
longer += shouldSelectLong[i];
buildNearQueryHeads += nearQueryHeads[i];
buildAnnNotFound += annNotFound[i];
buildRNGRule += rngRule[i];
buildPostingCut += postingCut[i];
}
LOG(Helper::LogLevel::LL_Info, "Query head recall @%d:%f.\n", internalResultNum, headacc / sampleSize / internalResultNum);
LOG(Helper::LogLevel::LL_Info, "BF top %d postings truth recall @%d:%f.\n", sampleK, truthK, truthacc / sampleSize / truthK);
LOG(Helper::LogLevel::LL_Info,
"Percent of truths in postings have shorter distance than query selected heads: %f percent\n",
shorter / lost * 100);
LOG(Helper::LogLevel::LL_Info,
"Percent of truths in postings have longer distance than query selected heads: %f percent\n",
longer / lost * 100);
LOG(Helper::LogLevel::LL_Info,
"\tPercent of truths no shorter distance in query selected heads: %f percent\n",
(longer - buildNearQueryHeads) / lost * 100);
LOG(Helper::LogLevel::LL_Info,
"\tPercent of truths exists shorter distance in query selected heads: %f percent\n",
buildNearQueryHeads / lost * 100);
LOG(Helper::LogLevel::LL_Info,
"\t\tRNG rule ANN search loss: %f percent\n", buildAnnNotFound / lost * 100);
LOG(Helper::LogLevel::LL_Info,
"\t\tPosting cut loss: %f percent\n", buildPostingCut / lost * 100);
LOG(Helper::LogLevel::LL_Info,
"\t\tRNG rule loss: %f percent\n", buildRNGRule / lost * 100);
}
}
}
}
}