andylizf commited on
Commit
6ccefc9
·
verified ·
1 Parent(s): 7a2f199

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. SPANN/AnnService/inc/Core/Common/BKTree.h +814 -0
  2. SPANN/AnnService/inc/Core/Common/DistanceUtils.h +167 -0
  3. SPANN/AnnService/inc/Core/Common/FineGrainedLock.h +44 -0
  4. SPANN/AnnService/inc/Core/Common/Heap.h +110 -0
  5. SPANN/AnnService/inc/Core/Common/IQuantizer.h +68 -0
  6. SPANN/AnnService/inc/Core/Common/InstructionUtils.h +59 -0
  7. SPANN/AnnService/inc/Core/Common/PQQuantizer.h +362 -0
  8. SPANN/AnnService/inc/Core/Common/QueryResultSet.h +124 -0
  9. SPANN/AnnService/inc/Core/Common/RelativeNeighborhoodGraph.h +86 -0
  10. SPANN/AnnService/inc/Core/Common/WorkSpace.h +324 -0
  11. SPANN/AnnService/inc/Core/CommonDataStructure.h +226 -0
  12. SPANN/AnnService/inc/Core/DefinitionList.h +142 -0
  13. SPANN/AnnService/inc/Core/MetadataSet.h +136 -0
  14. SPANN/AnnService/inc/Core/MultiIndexScan.h +80 -0
  15. SPANN/AnnService/inc/Core/SearchQuery.h +257 -0
  16. SPANN/AnnService/inc/Core/SearchResult.h +82 -0
  17. SPANN/AnnService/inc/Core/VectorSet.h +85 -0
  18. SPANN/AnnService/src/Aggregator/AggregatorContext.cpp +117 -0
  19. SPANN/AnnService/src/Aggregator/AggregatorExecutionContext.cpp +51 -0
  20. SPANN/AnnService/src/Aggregator/AggregatorService.cpp +413 -0
  21. SPANN/AnnService/src/Aggregator/AggregatorSettings.cpp +14 -0
  22. SPANN/AnnService/src/Aggregator/main.cpp +19 -0
  23. SPANN/AnnService/src/Helper/ArgumentsParser.cpp +86 -0
  24. SPANN/AnnService/src/Helper/AsyncFileReader.cpp +202 -0
  25. SPANN/AnnService/src/Helper/Base64Encode.cpp +240 -0
  26. SPANN/AnnService/src/Helper/CommonHelper.cpp +157 -0
  27. SPANN/AnnService/src/Helper/DynamicNeighbors.cpp +86 -0
  28. SPANN/AnnService/src/Helper/SimpleIniReader.cpp +235 -0
  29. SPANN/AnnService/src/Helper/VectorSetReader.cpp +56 -0
  30. SPANN/AnnService/src/Helper/VectorSetReaders/DefaultReader.cpp +85 -0
  31. SPANN/AnnService/src/Helper/VectorSetReaders/TxtReader.cpp +436 -0
  32. SPANN/AnnService/src/Helper/VectorSetReaders/XvecReader.cpp +119 -0
  33. SPANN/ThirdParty/zstd/.circleci/config.yml +124 -0
  34. SPANN/ThirdParty/zstd/.circleci/images/primary/Dockerfile +9 -0
  35. SPANN/ThirdParty/zstd/.cirrus.yml +11 -0
  36. SPANN/ThirdParty/zstd/.gitattributes +21 -0
  37. SPANN/ThirdParty/zstd/.gitignore +55 -0
  38. SPANN/ThirdParty/zstd/.travis.yml +128 -0
  39. SPANN/ThirdParty/zstd/CONTRIBUTING.md +489 -0
  40. SPANN/ThirdParty/zstd/Makefile +439 -0
  41. SPANN/ThirdParty/zstd/lib/BUCK +232 -0
  42. SPANN/ThirdParty/zstd/lib/README.md +217 -0
  43. SPANN/ThirdParty/zstd/lib/common/debug.c +24 -0
  44. SPANN/ThirdParty/zstd/lib/libzstd.mk +203 -0
  45. SPANN/ThirdParty/zstd/lib/libzstd.pc.in +16 -0
  46. SPANN/ThirdParty/zstd/lib/module.modulemap +25 -0
  47. SPANN/ThirdParty/zstd/lib/zstd_errors.h +95 -0
  48. SPANN/ThirdParty/zstd/zlibWrapper/.gitignore +28 -0
  49. SPANN/ThirdParty/zstd/zlibWrapper/BUCK +22 -0
  50. SPANN/ThirdParty/zstd/zlibWrapper/Makefile +119 -0
SPANN/AnnService/inc/Core/Common/BKTree.h ADDED
@@ -0,0 +1,814 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright (c) Microsoft Corporation. All rights reserved.
2
+ // Licensed under the MIT License.
3
+
4
+ #ifndef _SPTAG_COMMON_BKTREE_H_
5
+ #define _SPTAG_COMMON_BKTREE_H_
6
+
7
+ #include <stack>
8
+ #include <string>
9
+ #include <vector>
10
+ #include <mutex>
11
+ #include <shared_mutex>
12
+ #include "inc/Core/VectorIndex.h"
13
+
14
+ #include "CommonUtils.h"
15
+ #include "QueryResultSet.h"
16
+ #include "WorkSpace.h"
17
+ #include "Dataset.h"
18
+ #include "DistanceUtils.h"
19
+
20
+ namespace SPTAG
21
+ {
22
+ namespace COMMON
23
+ {
24
+ // node type for storing BKT
25
+ struct BKTNode
26
+ {
27
+ SizeType centerid;
28
+ SizeType childStart;
29
+ SizeType childEnd;
30
+
31
+ BKTNode(SizeType cid = -1) : centerid(cid), childStart(-1), childEnd(-1) {}
32
+ };
33
+
34
+ template <typename T>
35
+ struct KmeansArgs {
36
+ int _K;
37
+ int _DK;
38
+ DimensionType _D;
39
+ DimensionType _RD;
40
+ int _T;
41
+ DistCalcMethod _M;
42
+ T* centers;
43
+ T* newTCenters;
44
+ SizeType* counts;
45
+ float* newCenters;
46
+ SizeType* newCounts;
47
+ int* label;
48
+ SizeType* clusterIdx;
49
+ float* clusterDist;
50
+ float* weightedCounts;
51
+ float* newWeightedCounts;
52
+ std::function<float(const T*, const T*, DimensionType)> fComputeDistance;
53
+ const std::shared_ptr<IQuantizer>& m_pQuantizer;
54
+
55
+ KmeansArgs(int k, DimensionType dim, SizeType datasize, int threadnum, DistCalcMethod distMethod, const std::shared_ptr<IQuantizer>& quantizer = nullptr) : _K(k), _DK(k), _D(dim), _RD(dim), _T(threadnum), _M(distMethod), m_pQuantizer(quantizer){
56
+ if (m_pQuantizer) {
57
+ _RD = m_pQuantizer->ReconstructDim();
58
+ fComputeDistance = m_pQuantizer->DistanceCalcSelector<T>(distMethod);
59
+ }
60
+ else {
61
+ fComputeDistance = COMMON::DistanceCalcSelector<T>(distMethod);
62
+ }
63
+
64
+ centers = (T*)ALIGN_ALLOC(sizeof(T) * _K * _D);
65
+ newTCenters = (T*)ALIGN_ALLOC(sizeof(T) * _K * _D);
66
+ counts = new SizeType[_K];
67
+ newCenters = new float[_T * _K * _RD];
68
+ newCounts = new SizeType[_T * _K];
69
+ label = new int[datasize];
70
+ clusterIdx = new SizeType[_T * _K];
71
+ clusterDist = new float[_T * _K];
72
+ weightedCounts = new float[_K];
73
+ newWeightedCounts = new float[_T * _K];
74
+ }
75
+
76
+ ~KmeansArgs() {
77
+ ALIGN_FREE(centers);
78
+ ALIGN_FREE(newTCenters);
79
+ delete[] counts;
80
+ delete[] newCenters;
81
+ delete[] newCounts;
82
+ delete[] label;
83
+ delete[] clusterIdx;
84
+ delete[] clusterDist;
85
+ delete[] weightedCounts;
86
+ delete[] newWeightedCounts;
87
+ }
88
+
89
+ inline void ClearCounts() {
90
+ memset(newCounts, 0, sizeof(SizeType) * _T * _K);
91
+ memset(newWeightedCounts, 0, sizeof(float) * _T * _K);
92
+ }
93
+
94
+ inline void ClearCenters() {
95
+ memset(newCenters, 0, sizeof(float) * _T * _K * _RD);
96
+ }
97
+
98
+ inline void ClearDists(float dist) {
99
+ for (int i = 0; i < _T * _K; i++) {
100
+ clusterIdx[i] = -1;
101
+ clusterDist[i] = dist;
102
+ }
103
+ }
104
+
105
+ void Shuffle(std::vector<SizeType>& indices, SizeType first, SizeType last) {
106
+ SizeType* pos = new SizeType[_K];
107
+ pos[0] = first;
108
+ for (int k = 1; k < _K; k++) pos[k] = pos[k - 1] + newCounts[k - 1];
109
+
110
+ for (int k = 0; k < _K; k++) {
111
+ if (counts[k] == 0) continue;
112
+ SizeType i = pos[k];
113
+ while (newCounts[k] > 0) {
114
+ SizeType swapid = pos[label[i]] + newCounts[label[i]] - 1;
115
+ newCounts[label[i]]--;
116
+ std::swap(indices[i], indices[swapid]);
117
+ std::swap(label[i], label[swapid]);
118
+ }
119
+ while (indices[i] != clusterIdx[k]) i++;
120
+ std::swap(indices[i], indices[pos[k] + counts[k] - 1]);
121
+ }
122
+ delete[] pos;
123
+ }
124
+ };
125
+ template<typename T>
126
+ void RefineLambda(KmeansArgs<T>& args, float& lambda, int size)
127
+ {
128
+ int maxcluster = -1;
129
+ SizeType maxCount = 0;
130
+ for (int k = 0; k < args._DK; k++) {
131
+ if (args.counts[k] > maxCount && args.newCounts[k] > 0)
132
+ {
133
+ maxcluster = k;
134
+ maxCount = args.counts[k];
135
+ }
136
+ }
137
+
138
+ float avgDist = args.newWeightedCounts[maxcluster] / args.newCounts[maxcluster];
139
+ //lambda = avgDist / 10 / args.counts[maxcluster];
140
+ //lambda = (args.clusterDist[maxcluster] - avgDist) / args.newCounts[maxcluster];
141
+ lambda = (args.clusterDist[maxcluster] - avgDist) / size;
142
+ if (lambda < 0) lambda = 0;
143
+ }
144
+
145
+ template <typename T, typename R>
146
+ float RefineCenters(const Dataset<T>& data, KmeansArgs<T>& args)
147
+ {
148
+ int maxcluster = -1;
149
+ SizeType maxCount = 0;
150
+ for (int k = 0; k < args._DK; k++) {
151
+ if (args.counts[k] > maxCount && args.newCounts[k] > 0 && DistanceUtils::ComputeDistance((T*)data[args.clusterIdx[k]], args.centers + k * args._D, args._D, DistCalcMethod::L2) > 1e-6)
152
+ {
153
+ maxcluster = k;
154
+ maxCount = args.counts[k];
155
+ }
156
+ }
157
+
158
+ if (maxcluster != -1 && (args.clusterIdx[maxcluster] < 0 || args.clusterIdx[maxcluster] >= data.R()))
159
+ SPTAGLIB_LOG(Helper::LogLevel::LL_Debug, "maxcluster:%d(%d) Error dist:%f\n", maxcluster, args.newCounts[maxcluster], args.clusterDist[maxcluster]);
160
+
161
+ float diff = 0;
162
+ std::vector<R> reconstructVector(args._RD, 0);
163
+ for (int k = 0; k < args._DK; k++) {
164
+ T* TCenter = args.newTCenters + k * args._D;
165
+ if (args.counts[k] == 0) {
166
+ if (maxcluster != -1) {
167
+ //int nextid = Utils::rand_int(last, first);
168
+ //while (args.label[nextid] != maxcluster) nextid = Utils::rand_int(last, first);
169
+ SizeType nextid = args.clusterIdx[maxcluster];
170
+ std::memcpy(TCenter, data[nextid], sizeof(T)*args._D);
171
+ }
172
+ else {
173
+ std::memcpy(TCenter, args.centers + k * args._D, sizeof(T)*args._D);
174
+ }
175
+ }
176
+ else {
177
+ float* currCenters = args.newCenters + k * args._RD;
178
+ for (DimensionType j = 0; j < args._RD; j++) {
179
+ currCenters[j] /= args.counts[k];
180
+ }
181
+
182
+ if (args._M == DistCalcMethod::Cosine) {
183
+ COMMON::Utils::Normalize(currCenters, args._RD, COMMON::Utils::GetBase<T>());
184
+ }
185
+
186
+ if (args.m_pQuantizer) {
187
+ for (DimensionType j = 0; j < args._RD; j++) reconstructVector[j] = (R)(currCenters[j]);
188
+ args.m_pQuantizer->QuantizeVector(reconstructVector.data(), (uint8_t*)TCenter);
189
+ }
190
+ else {
191
+ for (DimensionType j = 0; j < args._D; j++) TCenter[j] = (T)(currCenters[j]);
192
+ }
193
+ }
194
+ diff += DistanceUtils::ComputeDistance(TCenter, args.centers + k * args._D, args._D, DistCalcMethod::L2);
195
+ }
196
+ return diff;
197
+ }
198
+
199
+ #if defined(NEWGPU)
200
+
201
+ #include "inc/Core/Common/cuda/Kmeans.hxx"
202
+
203
+ template <typename T, typename R>
204
+ inline float KmeansAssign(const Dataset<T>& data,
205
+ std::vector<SizeType>& indices,
206
+ const SizeType first, const SizeType last, KmeansArgs<T>& args,
207
+ const bool updateCenters, float lambda) {
208
+ float currDist = 0;
209
+ SizeType totalSize = last - first;
210
+
211
+ // TODO - compile-time options for MAX_DIM and metric
212
+ computeKmeansGPU<T, float, 100>(data, indices, first, last, args._K, args._D,
213
+ args._DK, lambda, args.centers, args.label, args.counts, args.newCounts, args.newCenters,
214
+ args.clusterIdx, args.clusterDist, args.weightedCounts, args.newWeightedCounts, 0, updateCenters);
215
+ }
216
+
217
+ #else
218
+
219
+ template <typename T, typename R>
220
+ inline float KmeansAssign(const Dataset<T>& data,
221
+ std::vector<SizeType>& indices,
222
+ const SizeType first, const SizeType last, KmeansArgs<T>& args,
223
+ const bool updateCenters, float lambda) {
224
+ float currDist = 0;
225
+ SizeType subsize = (last - first - 1) / args._T + 1;
226
+
227
+ #pragma omp parallel for num_threads(args._T) shared(data, indices) reduction(+:currDist)
228
+ for (int tid = 0; tid < args._T; tid++)
229
+ {
230
+ SizeType istart = first + tid * subsize;
231
+ SizeType iend = min(first + (tid + 1) * subsize, last);
232
+ SizeType *inewCounts = args.newCounts + tid * args._K;
233
+ float *inewCenters = args.newCenters + tid * args._K * args._RD;
234
+ SizeType * iclusterIdx = args.clusterIdx + tid * args._K;
235
+ float * iclusterDist = args.clusterDist + tid * args._K;
236
+ float * iweightedCounts = args.newWeightedCounts + tid * args._K;
237
+ float idist = 0;
238
+ R* reconstructVector = nullptr;
239
+ if (args.m_pQuantizer) reconstructVector = (R*)ALIGN_ALLOC(args.m_pQuantizer->ReconstructSize());
240
+
241
+ for (SizeType i = istart; i < iend; i++) {
242
+ int clusterid = 0;
243
+ float smallestDist = MaxDist;
244
+ for (int k = 0; k < args._DK; k++) {
245
+ float dist = args.fComputeDistance(data[indices[i]], args.centers + k*args._D, args._D) + lambda*args.counts[k];
246
+ if (dist > -MaxDist && dist < smallestDist) {
247
+ clusterid = k; smallestDist = dist;
248
+ }
249
+ }
250
+ args.label[i] = clusterid;
251
+ inewCounts[clusterid]++;
252
+ iweightedCounts[clusterid] += smallestDist;
253
+ idist += smallestDist;
254
+ if (updateCenters) {
255
+ if (args.m_pQuantizer) {
256
+ args.m_pQuantizer->ReconstructVector((const uint8_t*)data[indices[i]], reconstructVector);
257
+ }
258
+ else {
259
+ reconstructVector = (R*)data[indices[i]];
260
+ }
261
+ float* center = inewCenters + clusterid*args._RD;
262
+ for (DimensionType j = 0; j < args._RD; j++) center[j] += reconstructVector[j];
263
+
264
+ if (smallestDist > iclusterDist[clusterid]) {
265
+ iclusterDist[clusterid] = smallestDist;
266
+ iclusterIdx[clusterid] = indices[i];
267
+ }
268
+ }
269
+ else {
270
+ if (smallestDist <= iclusterDist[clusterid]) {
271
+ iclusterDist[clusterid] = smallestDist;
272
+ iclusterIdx[clusterid] = indices[i];
273
+ }
274
+ }
275
+ }
276
+ if (args.m_pQuantizer) ALIGN_FREE(reconstructVector);
277
+ currDist += idist;
278
+ }
279
+
280
+ for (int i = 1; i < args._T; i++) {
281
+ for (int k = 0; k < args._DK; k++) {
282
+ args.newCounts[k] += args.newCounts[i * args._K + k];
283
+ args.newWeightedCounts[k] += args.newWeightedCounts[i * args._K + k];
284
+ }
285
+ }
286
+
287
+ if (updateCenters) {
288
+ for (int i = 1; i < args._T; i++) {
289
+ float* currCenter = args.newCenters + i*args._K*args._RD;
290
+ for (size_t j = 0; j < ((size_t)args._DK) * args._RD; j++) args.newCenters[j] += currCenter[j];
291
+
292
+ for (int k = 0; k < args._DK; k++) {
293
+ if (args.clusterIdx[i*args._K + k] != -1 && args.clusterDist[i*args._K + k] > args.clusterDist[k]) {
294
+ args.clusterDist[k] = args.clusterDist[i*args._K + k];
295
+ args.clusterIdx[k] = args.clusterIdx[i*args._K + k];
296
+ }
297
+ }
298
+ }
299
+ }
300
+ else {
301
+ for (int i = 1; i < args._T; i++) {
302
+ for (int k = 0; k < args._DK; k++) {
303
+ if (args.clusterIdx[i*args._K + k] != -1 && args.clusterDist[i*args._K + k] <= args.clusterDist[k]) {
304
+ args.clusterDist[k] = args.clusterDist[i*args._K + k];
305
+ args.clusterIdx[k] = args.clusterIdx[i*args._K + k];
306
+ }
307
+ }
308
+ }
309
+ }
310
+ return currDist;
311
+ }
312
+
313
+ #endif
314
+
315
+
316
+ template <typename T, typename R>
317
+ inline float InitCenters(const Dataset<T>& data,
318
+ std::vector<SizeType>& indices, const SizeType first, const SizeType last,
319
+ KmeansArgs<T>& args, int samples, int tryIters) {
320
+ SizeType batchEnd = min(first + samples, last);
321
+ float lambda = 0, currDist, minClusterDist = MaxDist;
322
+ for (int numKmeans = 0; numKmeans < tryIters; numKmeans++) {
323
+ for (int k = 0; k < args._DK; k++) {
324
+ SizeType randid = COMMON::Utils::rand(last, first);
325
+ std::memcpy(args.centers + k*args._D, data[indices[randid]], sizeof(T)*args._D);
326
+ }
327
+ args.ClearCounts();
328
+ args.ClearDists(-MaxDist);
329
+ currDist = KmeansAssign<T, R>(data, indices, first, batchEnd, args, true, 0);
330
+ if (currDist < minClusterDist) {
331
+ minClusterDist = currDist;
332
+ memcpy(args.newTCenters, args.centers, sizeof(T)*args._K*args._D);
333
+ memcpy(args.counts, args.newCounts, sizeof(SizeType) * args._K);
334
+
335
+ RefineLambda(args, lambda, batchEnd - first);
336
+ }
337
+ }
338
+ return lambda;
339
+ }
340
+
341
+ template <typename T, typename R>
342
+ float TryClustering(const Dataset<T>& data,
343
+ std::vector<SizeType>& indices, const SizeType first, const SizeType last,
344
+ KmeansArgs<T>& args, int samples = 1000, float lambdaFactor = 100.0f, bool debug = false, IAbortOperation* abort = nullptr) {
345
+
346
+ float adjustedLambda = InitCenters<T, R>(data, indices, first, last, args, samples, 3);
347
+ if (abort && abort->ShouldAbort()) return 0;
348
+
349
+ SizeType batchEnd = min(first + samples, last);
350
+ float currDiff, currDist, minClusterDist = MaxDist;
351
+ int noImprovement = 0;
352
+ float originalLambda = COMMON::Utils::GetBase<T>() * COMMON::Utils::GetBase<T>() / lambdaFactor / (batchEnd - first);
353
+ for (int iter = 0; iter < 100; iter++) {
354
+ std::memcpy(args.centers, args.newTCenters, sizeof(T)*args._K*args._D);
355
+ std::shuffle(indices.begin() + first, indices.begin() + last, rg);
356
+
357
+ args.ClearCenters();
358
+ args.ClearCounts();
359
+ args.ClearDists(-MaxDist);
360
+ currDist = KmeansAssign<T, R>(data, indices, first, batchEnd, args, true, min(adjustedLambda, originalLambda));
361
+ std::memcpy(args.counts, args.newCounts, sizeof(SizeType) * args._K);
362
+
363
+ if (currDist < minClusterDist) {
364
+ noImprovement = 0;
365
+ minClusterDist = currDist;
366
+ }
367
+ else {
368
+ noImprovement++;
369
+ }
370
+
371
+ /*
372
+ if (debug) {
373
+ std::string log = "";
374
+ for (int k = 0; k < args._DK; k++) {
375
+ log += std::to_string(args.counts[k]) + " ";
376
+ }
377
+ SPTAGLIB_LOG(Helper::LogLevel::LL_Info, "iter %d dist:%f lambda:(%f,%f) counts:%s\n", iter, currDist, originalLambda, adjustedLambda, log.c_str());
378
+ }
379
+ */
380
+
381
+ currDiff = RefineCenters<T, R>(data, args);
382
+ //if (debug) SPTAGLIB_LOG(Helper::LogLevel::LL_Info, "iter %d dist:%f diff:%f\n", iter, currDist, currDiff);
383
+
384
+ if (abort && abort->ShouldAbort()) return 0;
385
+ if (currDiff < 1e-3 || noImprovement >= 5) break;
386
+ }
387
+
388
+ args.ClearCounts();
389
+ args.ClearDists(MaxDist);
390
+ currDist = KmeansAssign<T, R>(data, indices, first, last, args, false, 0);
391
+ for (int k = 0; k < args._DK; k++) {
392
+ if (args.clusterIdx[k] != -1) std::memcpy(args.centers + k * args._D, data[args.clusterIdx[k]], sizeof(T) * args._D);
393
+ }
394
+
395
+ args.ClearCounts();
396
+ args.ClearDists(MaxDist);
397
+ currDist = KmeansAssign<T, R>(data, indices, first, last, args, false, 0);
398
+ std::memcpy(args.counts, args.newCounts, sizeof(SizeType) * args._K);
399
+
400
+ SizeType maxCount = 0, minCount = (std::numeric_limits<SizeType>::max)(), availableClusters = 0;
401
+ float CountStd = 0.0, CountAvg = (last - first) * 1.0f / args._DK;
402
+ for (int i = 0; i < args._DK; i++) {
403
+ if (args.counts[i] > maxCount) maxCount = args.counts[i];
404
+ if (args.counts[i] < minCount) minCount = args.counts[i];
405
+ CountStd += (args.counts[i] - CountAvg) * (args.counts[i] - CountAvg);
406
+ if (args.counts[i] > 0) availableClusters++;
407
+ }
408
+ CountStd = sqrt(CountStd / args._DK) / CountAvg;
409
+ if (debug) SPTAGLIB_LOG(Helper::LogLevel::LL_Info, "Lambda:min(%g,%g) Max:%d Min:%d Avg:%f Std/Avg:%f Dist:%f NonZero/Total:%d/%d\n", originalLambda, adjustedLambda, maxCount, minCount, CountAvg, CountStd, currDist, availableClusters, args._DK);
410
+
411
+ return CountStd;
412
+ }
413
+
414
+ template <typename T>
415
+ float DynamicFactorSelect(const Dataset<T> & data,
416
+ std::vector<SizeType> & indices, const SizeType first, const SizeType last,
417
+ KmeansArgs<T> & args, int samples = 1000) {
418
+
419
+ float bestLambdaFactor = 100.0f, bestCountStd = (std::numeric_limits<float>::max)();
420
+ for (float lambdaFactor = 0.001f; lambdaFactor <= 1000.0f + 1e-3; lambdaFactor *= 10) {
421
+ float CountStd = 0.0;
422
+ if (args.m_pQuantizer)
423
+ {
424
+ switch (args.m_pQuantizer->GetReconstructType())
425
+ {
426
+ #define DefineVectorValueType(Name, Type) \
427
+ case VectorValueType::Name: \
428
+ CountStd = TryClustering<T, Type>(data, indices, first, last, args, samples, lambdaFactor, true); \
429
+ break;
430
+
431
+ #include "inc/Core/DefinitionList.h"
432
+ #undef DefineVectorValueType
433
+
434
+ default: break;
435
+ }
436
+ }
437
+ else
438
+ {
439
+ CountStd = TryClustering<T, T>(data, indices, first, last, args, samples, lambdaFactor, true);
440
+ }
441
+
442
+ if (CountStd < bestCountStd) {
443
+ bestLambdaFactor = lambdaFactor;
444
+ bestCountStd = CountStd;
445
+ }
446
+ }
447
+ /*
448
+ std::vector<float> tries(16, 0);
449
+ for (int i = 0; i < 8; i++) {
450
+ tries[i] = bestLambdaFactor * (i + 2) / 10;
451
+ tries[8 + i] = bestLambdaFactor * (i + 2);
452
+ }
453
+ for (float lambdaFactor : tries) {
454
+ float CountStd = TryClustering(data, indices, first, last, args, samples, lambdaFactor, true);
455
+ if (CountStd < bestCountStd) {
456
+ bestLambdaFactor = lambdaFactor;
457
+ bestCountStd = CountStd;
458
+ }
459
+ }
460
+ */
461
+ SPTAGLIB_LOG(Helper::LogLevel::LL_Info, "Best Lambda Factor:%f\n", bestLambdaFactor);
462
+ return bestLambdaFactor;
463
+ }
464
+
465
+ template <typename T>
466
+ int KmeansClustering(const Dataset<T>& data,
467
+ std::vector<SizeType>& indices, const SizeType first, const SizeType last,
468
+ KmeansArgs<T>& args, int samples = 1000, float lambdaFactor = 100.0f, bool debug = false, IAbortOperation* abort = nullptr) {
469
+
470
+ if (args.m_pQuantizer)
471
+ {
472
+ switch (args.m_pQuantizer->GetReconstructType())
473
+ {
474
+ #define DefineVectorValueType(Name, Type) \
475
+ case VectorValueType::Name: \
476
+ TryClustering<T, Type>(data, indices, first, last, args, samples, lambdaFactor, debug, abort); \
477
+ break;
478
+
479
+ #include "inc/Core/DefinitionList.h"
480
+ #undef DefineVectorValueType
481
+
482
+ default: break;
483
+ }
484
+ }
485
+ else
486
+ {
487
+ TryClustering<T, T>(data, indices, first, last, args, samples, lambdaFactor, debug, abort);
488
+ }
489
+
490
+ if (abort && abort->ShouldAbort()) return 1;
491
+
492
+ int numClusters = 0;
493
+ for (int i = 0; i < args._K; i++) if (args.counts[i] > 0) numClusters++;
494
+
495
+ if (numClusters <= 1) return numClusters;
496
+
497
+ args.Shuffle(indices, first, last);
498
+ return numClusters;
499
+ }
500
+
501
+ class BKTree
502
+ {
503
+ public:
504
+ BKTree(): m_iTreeNumber(1), m_iBKTKmeansK(32), m_iBKTLeafSize(8), m_iSamples(1000), m_fBalanceFactor(-1.0f), m_bfs(0), m_lock(new std::shared_timed_mutex), m_pQuantizer(nullptr) {}
505
+
506
+ BKTree(const BKTree& other): m_iTreeNumber(other.m_iTreeNumber),
507
+ m_iBKTKmeansK(other.m_iBKTKmeansK),
508
+ m_iBKTLeafSize(other.m_iBKTLeafSize),
509
+ m_iSamples(other.m_iSamples),
510
+ m_fBalanceFactor(other.m_fBalanceFactor),
511
+ m_lock(new std::shared_timed_mutex),
512
+ m_pQuantizer(other.m_pQuantizer) {}
513
+ ~BKTree() {}
514
+
515
+ inline const BKTNode& operator[](SizeType index) const { return m_pTreeRoots[index]; }
516
+ inline BKTNode& operator[](SizeType index) { return m_pTreeRoots[index]; }
517
+
518
+ inline SizeType size() const { return (SizeType)m_pTreeRoots.size(); }
519
+
520
+ inline SizeType sizePerTree() const {
521
+ std::shared_lock<std::shared_timed_mutex> lock(*m_lock);
522
+ return (SizeType)m_pTreeRoots.size() - m_pTreeStart.back();
523
+ }
524
+
525
+ inline const std::unordered_map<SizeType, SizeType>& GetSampleMap() const { return m_pSampleCenterMap; }
526
+
527
+ inline void SwapTree(BKTree& newTrees)
528
+ {
529
+ m_pTreeRoots.swap(newTrees.m_pTreeRoots);
530
+ m_pTreeStart.swap(newTrees.m_pTreeStart);
531
+ m_pSampleCenterMap.swap(newTrees.m_pSampleCenterMap);
532
+ }
533
+
534
+ template <typename T>
535
+ void Rebuild(const Dataset<T>& data, DistCalcMethod distMethod, IAbortOperation* abort)
536
+ {
537
+ BKTree newTrees(*this);
538
+ newTrees.BuildTrees<T>(data, distMethod, 1, nullptr, nullptr, false, abort);
539
+
540
+ std::unique_lock<std::shared_timed_mutex> lock(*m_lock);
541
+ m_pTreeRoots.swap(newTrees.m_pTreeRoots);
542
+ m_pTreeStart.swap(newTrees.m_pTreeStart);
543
+ m_pSampleCenterMap.swap(newTrees.m_pSampleCenterMap);
544
+ }
545
+
546
+ template <typename T>
547
+ void BuildTrees(const Dataset<T>& data, DistCalcMethod distMethod, int numOfThreads,
548
+ std::vector<SizeType>* indices = nullptr, std::vector<SizeType>* reverseIndices = nullptr,
549
+ bool dynamicK = false, IAbortOperation* abort = nullptr)
550
+ {
551
+ struct BKTStackItem {
552
+ SizeType index, first, last;
553
+ bool debug;
554
+ BKTStackItem(SizeType index_, SizeType first_, SizeType last_, bool debug_ = false) : index(index_), first(first_), last(last_), debug(debug_) {}
555
+ };
556
+ std::stack<BKTStackItem> ss;
557
+
558
+ std::vector<SizeType> localindices;
559
+ if (indices == nullptr) {
560
+ localindices.resize(data.R());
561
+ for (SizeType i = 0; i < localindices.size(); i++) localindices[i] = i;
562
+ }
563
+ else {
564
+ localindices.assign(indices->begin(), indices->end());
565
+ }
566
+ KmeansArgs<T> args(m_iBKTKmeansK, data.C(), (SizeType)localindices.size(), numOfThreads, distMethod, m_pQuantizer);
567
+
568
+ if (m_fBalanceFactor < 0) m_fBalanceFactor = DynamicFactorSelect(data, localindices, 0, (SizeType)localindices.size(), args, m_iSamples);
569
+
570
+ m_pSampleCenterMap.clear();
571
+ for (char i = 0; i < m_iTreeNumber; i++)
572
+ {
573
+ std::shuffle(localindices.begin(), localindices.end(), rg);
574
+
575
+ m_pTreeStart.push_back((SizeType)m_pTreeRoots.size());
576
+ m_pTreeRoots.emplace_back((SizeType)localindices.size());
577
+ SPTAGLIB_LOG(Helper::LogLevel::LL_Info, "Start to build BKTree %d\n", i + 1);
578
+
579
+ ss.push(BKTStackItem(m_pTreeStart[i], 0, (SizeType)localindices.size(), true));
580
+ while (!ss.empty()) {
581
+ if (abort && abort->ShouldAbort()) return;
582
+
583
+ BKTStackItem item = ss.top(); ss.pop();
584
+ m_pTreeRoots[item.index].childStart = (SizeType)m_pTreeRoots.size();
585
+ if (item.last - item.first <= m_iBKTLeafSize) {
586
+ for (SizeType j = item.first; j < item.last; j++) {
587
+ SizeType cid = (reverseIndices == nullptr)? localindices[j]: reverseIndices->at(localindices[j]);
588
+ m_pTreeRoots.emplace_back(cid);
589
+ }
590
+ }
591
+ else { // clustering the data into BKTKmeansK clusters
592
+ if (dynamicK) {
593
+ args._DK = std::min<int>((item.last - item.first) / m_iBKTLeafSize + 1, m_iBKTKmeansK);
594
+ args._DK = std::max<int>(args._DK, 2);
595
+ }
596
+
597
+ int numClusters = KmeansClustering(data, localindices, item.first, item.last, args, m_iSamples, m_fBalanceFactor, item.debug, abort);
598
+ if (numClusters <= 1) {
599
+ SizeType end = min(item.last + 1, (SizeType)localindices.size());
600
+ std::sort(localindices.begin() + item.first, localindices.begin() + end);
601
+ m_pTreeRoots[item.index].centerid = (reverseIndices == nullptr) ? localindices[item.first] : reverseIndices->at(localindices[item.first]);
602
+ m_pTreeRoots[item.index].childStart = -m_pTreeRoots[item.index].childStart;
603
+ for (SizeType j = item.first + 1; j < end; j++) {
604
+ SizeType cid = (reverseIndices == nullptr) ? localindices[j] : reverseIndices->at(localindices[j]);
605
+ m_pTreeRoots.emplace_back(cid);
606
+ m_pSampleCenterMap[cid] = m_pTreeRoots[item.index].centerid;
607
+ }
608
+ m_pSampleCenterMap[-1 - m_pTreeRoots[item.index].centerid] = item.index;
609
+ }
610
+ else {
611
+ SizeType maxCount = 0;
612
+ for (int k = 0; k < m_iBKTKmeansK; k++) if (args.counts[k] > maxCount) maxCount = args.counts[k];
613
+ for (int k = 0; k < m_iBKTKmeansK; k++) {
614
+ if (args.counts[k] == 0) continue;
615
+ SizeType cid = (reverseIndices == nullptr) ? localindices[item.first + args.counts[k] - 1] : reverseIndices->at(localindices[item.first + args.counts[k] - 1]);
616
+ m_pTreeRoots.emplace_back(cid);
617
+ if (args.counts[k] > 1) ss.push(BKTStackItem((SizeType)(m_pTreeRoots.size() - 1), item.first, item.first + args.counts[k] - 1, item.debug && (args.counts[k] == maxCount)));
618
+ item.first += args.counts[k];
619
+ }
620
+ }
621
+ }
622
+ m_pTreeRoots[item.index].childEnd = (SizeType)m_pTreeRoots.size();
623
+ }
624
+ m_pTreeRoots.emplace_back(-1);
625
+ SPTAGLIB_LOG(Helper::LogLevel::LL_Info, "%d BKTree built, %zu %zu\n", i + 1, m_pTreeRoots.size() - m_pTreeStart[i], localindices.size());
626
+ }
627
+ }
628
+
629
+ inline std::uint64_t BufferSize() const
630
+ {
631
+ return sizeof(int) + sizeof(SizeType) * m_iTreeNumber +
632
+ sizeof(SizeType) + sizeof(BKTNode) * m_pTreeRoots.size();
633
+ }
634
+
635
+ ErrorCode SaveTrees(std::shared_ptr<Helper::DiskIO> p_out) const
636
+ {
637
+ std::shared_lock<std::shared_timed_mutex> lock(*m_lock);
638
+ IOBINARY(p_out, WriteBinary, sizeof(m_iTreeNumber), (char*)&m_iTreeNumber);
639
+ IOBINARY(p_out, WriteBinary, sizeof(SizeType) * m_iTreeNumber, (char*)m_pTreeStart.data());
640
+ SizeType treeNodeSize = (SizeType)m_pTreeRoots.size();
641
+ IOBINARY(p_out, WriteBinary, sizeof(treeNodeSize), (char*)&treeNodeSize);
642
+ IOBINARY(p_out, WriteBinary, sizeof(BKTNode) * treeNodeSize, (char*)m_pTreeRoots.data());
643
+ SPTAGLIB_LOG(Helper::LogLevel::LL_Info, "Save BKT (%d,%d) Finish!\n", m_iTreeNumber, treeNodeSize);
644
+ return ErrorCode::Success;
645
+ }
646
+
647
+ ErrorCode SaveTrees(std::string sTreeFileName) const
648
+ {
649
+ SPTAGLIB_LOG(Helper::LogLevel::LL_Info, "Save BKT to %s\n", sTreeFileName.c_str());
650
+ auto ptr = f_createIO();
651
+ if (ptr == nullptr || !ptr->Initialize(sTreeFileName.c_str(), std::ios::binary | std::ios::out)) return ErrorCode::FailedCreateFile;
652
+ return SaveTrees(ptr);
653
+ }
654
+
655
+ ErrorCode LoadTrees(char* pBKTMemFile)
656
+ {
657
+ m_iTreeNumber = *((int*)pBKTMemFile);
658
+ pBKTMemFile += sizeof(int);
659
+ m_pTreeStart.resize(m_iTreeNumber);
660
+ memcpy(m_pTreeStart.data(), pBKTMemFile, sizeof(SizeType) * m_iTreeNumber);
661
+ pBKTMemFile += sizeof(SizeType)*m_iTreeNumber;
662
+
663
+ SizeType treeNodeSize = *((SizeType*)pBKTMemFile);
664
+ pBKTMemFile += sizeof(SizeType);
665
+ m_pTreeRoots.resize(treeNodeSize);
666
+ memcpy(m_pTreeRoots.data(), pBKTMemFile, sizeof(BKTNode) * treeNodeSize);
667
+ if (m_pTreeRoots.size() > 0 && m_pTreeRoots.back().centerid != -1) m_pTreeRoots.emplace_back(-1);
668
+ SPTAGLIB_LOG(Helper::LogLevel::LL_Info, "Load BKT (%d,%d) Finish!\n", m_iTreeNumber, treeNodeSize);
669
+ return ErrorCode::Success;
670
+ }
671
+
672
+ ErrorCode LoadTrees(std::shared_ptr<Helper::DiskIO> p_input)
673
+ {
674
+ IOBINARY(p_input, ReadBinary, sizeof(m_iTreeNumber), (char*)&m_iTreeNumber);
675
+ m_pTreeStart.resize(m_iTreeNumber);
676
+ IOBINARY(p_input, ReadBinary, sizeof(SizeType) * m_iTreeNumber, (char*)m_pTreeStart.data());
677
+
678
+ SizeType treeNodeSize;
679
+ IOBINARY(p_input, ReadBinary, sizeof(treeNodeSize), (char*)&treeNodeSize);
680
+ m_pTreeRoots.resize(treeNodeSize);
681
+ IOBINARY(p_input, ReadBinary, sizeof(BKTNode) * treeNodeSize, (char*)m_pTreeRoots.data());
682
+
683
+ if (m_pTreeRoots.size() > 0 && m_pTreeRoots.back().centerid != -1) m_pTreeRoots.emplace_back(-1);
684
+ SPTAGLIB_LOG(Helper::LogLevel::LL_Info, "Load BKT (%d,%d) Finish!\n", m_iTreeNumber, treeNodeSize);
685
+ return ErrorCode::Success;
686
+ }
687
+
688
+ ErrorCode LoadTrees(std::string sTreeFileName)
689
+ {
690
+ SPTAGLIB_LOG(Helper::LogLevel::LL_Info, "Load BKT From %s\n", sTreeFileName.c_str());
691
+ auto ptr = f_createIO();
692
+ if (ptr == nullptr || !ptr->Initialize(sTreeFileName.c_str(), std::ios::binary | std::ios::in)) return ErrorCode::FailedOpenFile;
693
+ return LoadTrees(ptr);
694
+ }
695
+
696
+ template <typename T>
697
+ void InitSearchTrees(const Dataset<T>& data, std::function<float(const T*, const T*, DimensionType)> fComputeDistance, COMMON::QueryResultSet<T> &p_query, COMMON::WorkSpace &p_space) const
698
+ {
699
+ for (char i = 0; i < m_iTreeNumber; i++) {
700
+ const BKTNode& node = m_pTreeRoots[m_pTreeStart[i]];
701
+ if (node.childStart < 0) {
702
+ p_space.m_SPTQueue.insert(NodeDistPair(m_pTreeStart[i], fComputeDistance(p_query.GetQuantizedTarget(), data[node.centerid], data.C())));
703
+ } else if (m_bfs) {
704
+ float FactorQ = 1.1f;
705
+ int MaxBFSNodes = 100;
706
+ p_space.m_currBSPTQueue.Resize(MaxBFSNodes); p_space.m_nextBSPTQueue.Resize(MaxBFSNodes);
707
+ Heap<NodeDistPair>* p_curr = &p_space.m_currBSPTQueue, * p_next = &p_space.m_nextBSPTQueue;
708
+ p_curr->Top().distance = 1e9;
709
+
710
+ for (SizeType begin = node.childStart; begin < node.childEnd; begin++) {
711
+ _mm_prefetch((const char*)(data[m_pTreeRoots[begin].centerid]), _MM_HINT_T0);
712
+ }
713
+
714
+ for (SizeType begin = node.childStart; begin < node.childEnd; begin++) {
715
+ SizeType index = m_pTreeRoots[begin].centerid;
716
+ float dist = fComputeDistance(p_query.GetQuantizedTarget(), data[index], data.C());
717
+ if (dist <= FactorQ * p_curr->Top().distance && p_curr->size() < MaxBFSNodes) {
718
+ p_curr->insert(NodeDistPair(begin, dist));
719
+ }
720
+ else {
721
+ p_space.m_SPTQueue.insert(NodeDistPair(begin, dist));
722
+ }
723
+ }
724
+
725
+ for (int level = 1; level <= m_bfs; level++) {
726
+ p_next->Top().distance = 1e9;
727
+ while (!p_curr->empty()) {
728
+ NodeDistPair tmp = p_curr->pop();
729
+ const BKTNode& tnode = m_pTreeRoots[tmp.node];
730
+ if (tnode.childStart < 0) {
731
+ p_space.m_SPTQueue.insert(tmp);
732
+ }
733
+ else {
734
+ for (SizeType begin = tnode.childStart; begin < tnode.childEnd; begin++) {
735
+ _mm_prefetch((const char*)(data[m_pTreeRoots[begin].centerid]), _MM_HINT_T0);
736
+ }
737
+ if (!p_space.CheckAndSet(tnode.centerid)) {
738
+ p_space.m_NGQueue.insert(NodeDistPair(tnode.centerid, tmp.distance));
739
+ }
740
+ for (SizeType begin = tnode.childStart; begin < tnode.childEnd; begin++) {
741
+ SizeType index = m_pTreeRoots[begin].centerid;
742
+ float dist = fComputeDistance(p_query.GetQuantizedTarget(), data[index], data.C());
743
+ if (dist <= FactorQ * p_next->Top().distance && p_next->size() < MaxBFSNodes) {
744
+ p_next->insert(NodeDistPair(begin, dist));
745
+ }
746
+ else {
747
+ p_space.m_SPTQueue.insert(NodeDistPair(begin, dist));
748
+ }
749
+ }
750
+ }
751
+ }
752
+ std::swap(p_curr, p_next);
753
+ }
754
+
755
+ while (!p_curr->empty()) {
756
+ p_space.m_SPTQueue.insert(p_curr->pop());
757
+ }
758
+ }
759
+ else {
760
+ for (SizeType begin = node.childStart; begin < node.childEnd; begin++) {
761
+ _mm_prefetch((const char*)(data[m_pTreeRoots[begin].centerid]), _MM_HINT_T0);
762
+ }
763
+ for (SizeType begin = node.childStart; begin < node.childEnd; begin++) {
764
+ SizeType index = m_pTreeRoots[begin].centerid;
765
+ p_space.m_SPTQueue.insert(NodeDistPair(begin, fComputeDistance(p_query.GetQuantizedTarget(), data[index], data.C())));
766
+ }
767
+ }
768
+ }
769
+ }
770
+
771
+ template <typename T>
772
+ void SearchTrees(const Dataset<T>& data, std::function<float(const T*, const T*, DimensionType)> fComputeDistance, COMMON::QueryResultSet<T> &p_query,
773
+ COMMON::WorkSpace &p_space, const int p_limits) const
774
+ {
775
+ while (!p_space.m_SPTQueue.empty())
776
+ {
777
+ NodeDistPair bcell = p_space.m_SPTQueue.pop();
778
+ const BKTNode& tnode = m_pTreeRoots[bcell.node];
779
+ if (tnode.childStart < 0) {
780
+ if (!p_space.CheckAndSet(tnode.centerid)) {
781
+ p_space.m_iNumberOfCheckedLeaves++;
782
+ p_space.m_NGQueue.insert(NodeDistPair(tnode.centerid, bcell.distance));
783
+ }
784
+ if (p_space.m_iNumberOfCheckedLeaves >= p_limits) break;
785
+ }
786
+ else {
787
+ for (SizeType begin = tnode.childStart; begin < tnode.childEnd; begin++) {
788
+ _mm_prefetch((const char*)(data[m_pTreeRoots[begin].centerid]), _MM_HINT_T0);
789
+ }
790
+ if (!p_space.CheckAndSet(tnode.centerid)) {
791
+ p_space.m_NGQueue.insert(NodeDistPair(tnode.centerid, bcell.distance));
792
+ }
793
+ for (SizeType begin = tnode.childStart; begin < tnode.childEnd; begin++) {
794
+ SizeType index = m_pTreeRoots[begin].centerid;
795
+ p_space.m_SPTQueue.insert(NodeDistPair(begin, fComputeDistance(p_query.GetQuantizedTarget(), data[index], data.C())));
796
+ }
797
+ }
798
+ }
799
+ }
800
+
801
+ private:
802
+ std::vector<SizeType> m_pTreeStart;
803
+ std::vector<BKTNode> m_pTreeRoots;
804
+ std::unordered_map<SizeType, SizeType> m_pSampleCenterMap;
805
+
806
+ public:
807
+ std::unique_ptr<std::shared_timed_mutex> m_lock;
808
+ int m_iTreeNumber, m_iBKTKmeansK, m_iBKTLeafSize, m_iSamples, m_bfs;
809
+ float m_fBalanceFactor;
810
+ std::shared_ptr<SPTAG::COMMON::IQuantizer> m_pQuantizer;
811
+ };
812
+ }
813
+ }
814
+ #endif
SPANN/AnnService/inc/Core/Common/DistanceUtils.h ADDED
@@ -0,0 +1,167 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright (c) Microsoft Corporation. All rights reserved.
2
+ // Licensed under the MIT License.
3
+
4
+ #ifndef _SPTAG_COMMON_DISTANCEUTILS_H_
5
+ #define _SPTAG_COMMON_DISTANCEUTILS_H_
6
+
7
+ #include <functional>
8
+ #include <iostream>
9
+
10
+ #include "CommonUtils.h"
11
+ #include "InstructionUtils.h"
12
+
13
+ namespace SPTAG
14
+ {
15
+ namespace COMMON
16
+ {
17
+ template <typename T>
18
+ using DistanceCalcReturn = float(*)(const T*, const T*, DimensionType);
19
+ template<typename T>
20
+ inline DistanceCalcReturn<T> DistanceCalcSelector(SPTAG::DistCalcMethod p_method);
21
+
22
+ class DistanceUtils
23
+ {
24
+ public:
25
+ template <typename T>
26
+ static float ComputeL2Distance(const T* pX, const T* pY, DimensionType length)
27
+ {
28
+ const T* pEnd4 = pX + ((length >> 2) << 2);
29
+ const T* pEnd1 = pX + length;
30
+
31
+ float diff = 0;
32
+
33
+ while (pX < pEnd4) {
34
+ float c1 = ((float)(*pX++) - (float)(*pY++)); diff += c1 * c1;
35
+ c1 = ((float)(*pX++) - (float)(*pY++)); diff += c1 * c1;
36
+ c1 = ((float)(*pX++) - (float)(*pY++)); diff += c1 * c1;
37
+ c1 = ((float)(*pX++) - (float)(*pY++)); diff += c1 * c1;
38
+ }
39
+ while (pX < pEnd1) {
40
+ float c1 = ((float)(*pX++) - (float)(*pY++)); diff += c1 * c1;
41
+ }
42
+ return diff;
43
+ }
44
+
45
+ static float ComputeL2Distance_SSE(const std::int8_t* pX, const std::int8_t* pY, DimensionType length);
46
+ static float ComputeL2Distance_AVX(const std::int8_t* pX, const std::int8_t* pY, DimensionType length);
47
+ static float ComputeL2Distance_AVX512(const std::int8_t* pX, const std::int8_t* pY, DimensionType length);
48
+
49
+ static float ComputeL2Distance_SSE(const std::uint8_t* pX, const std::uint8_t* pY, DimensionType length);
50
+ static float ComputeL2Distance_AVX(const std::uint8_t* pX, const std::uint8_t* pY, DimensionType length);
51
+ static float ComputeL2Distance_AVX512(const std::uint8_t* pX, const std::uint8_t* pY, DimensionType length);
52
+
53
+ static float ComputeL2Distance_SSE(const std::int16_t* pX, const std::int16_t* pY, DimensionType length);
54
+ static float ComputeL2Distance_AVX(const std::int16_t* pX, const std::int16_t* pY, DimensionType length);
55
+ static float ComputeL2Distance_AVX512(const std::int16_t* pX, const std::int16_t* pY, DimensionType length);
56
+
57
+ static float ComputeL2Distance_SSE(const float* pX, const float* pY, DimensionType length);
58
+ static float ComputeL2Distance_AVX(const float* pX, const float* pY, DimensionType length);
59
+ static float ComputeL2Distance_AVX512(const float* pX, const float* pY, DimensionType length);
60
+
61
+ template <typename T>
62
+ static float ComputeCosineDistance(const T* pX, const T* pY, DimensionType length)
63
+ {
64
+ const T* pEnd4 = pX + ((length >> 2) << 2);
65
+ const T* pEnd1 = pX + length;
66
+
67
+ float diff = 0;
68
+
69
+ while (pX < pEnd4)
70
+ {
71
+ float c1 = ((float)(*pX++) * (float)(*pY++)); diff += c1;
72
+ c1 = ((float)(*pX++) * (float)(*pY++)); diff += c1;
73
+ c1 = ((float)(*pX++) * (float)(*pY++)); diff += c1;
74
+ c1 = ((float)(*pX++) * (float)(*pY++)); diff += c1;
75
+ }
76
+ while (pX < pEnd1) diff += ((float)(*pX++) * (float)(*pY++));
77
+ int base = Utils::GetBase<T>();
78
+ return base * base - diff;
79
+ }
80
+
81
+ static float ComputeCosineDistance_SSE(const std::int8_t* pX, const std::int8_t* pY, DimensionType length);
82
+ static float ComputeCosineDistance_AVX(const std::int8_t* pX, const std::int8_t* pY, DimensionType length);
83
+ static float ComputeCosineDistance_AVX512(const std::int8_t* pX, const std::int8_t* pY, DimensionType length);
84
+
85
+ static float ComputeCosineDistance_SSE(const std::uint8_t* pX, const std::uint8_t* pY, DimensionType length);
86
+ static float ComputeCosineDistance_AVX(const std::uint8_t* pX, const std::uint8_t* pY, DimensionType length);
87
+ static float ComputeCosineDistance_AVX512(const std::uint8_t* pX, const std::uint8_t* pY, DimensionType length);
88
+
89
+ static float ComputeCosineDistance_SSE(const std::int16_t* pX, const std::int16_t* pY, DimensionType length);
90
+ static float ComputeCosineDistance_AVX(const std::int16_t* pX, const std::int16_t* pY, DimensionType length);
91
+ static float ComputeCosineDistance_AVX512(const std::int16_t* pX, const std::int16_t* pY, DimensionType length);
92
+
93
+ static float ComputeCosineDistance_SSE(const float* pX, const float* pY, DimensionType length);
94
+ static float ComputeCosineDistance_AVX(const float* pX, const float* pY, DimensionType length);
95
+ static float ComputeCosineDistance_AVX512(const float* pX, const float* pY, DimensionType length);
96
+
97
+
98
+ template<typename T>
99
+ static inline float ComputeDistance(const T* p1, const T* p2, DimensionType length, SPTAG::DistCalcMethod distCalcMethod)
100
+ {
101
+ auto func = DistanceCalcSelector<T>(distCalcMethod);
102
+ return func(p1, p2, length);
103
+ }
104
+
105
+ static inline float ConvertCosineSimilarityToDistance(float cs)
106
+ {
107
+ // Cosine similarity is in [-1, 1], the higher the value, the closer are the two vectors.
108
+ // However, the tree is built and searched based on "distance" between two vectors, that's >=0. The smaller the value, the closer are the two vectors.
109
+ // So we do a linear conversion from a cosine similarity to a distance value.
110
+ return 1 - cs; //[1, 3]
111
+ }
112
+
113
+ static inline float ConvertDistanceBackToCosineSimilarity(float d)
114
+ {
115
+ return 1 - d;
116
+ }
117
+ };
118
+ template<typename T>
119
+ inline DistanceCalcReturn<T> DistanceCalcSelector(SPTAG::DistCalcMethod p_method)
120
+ {
121
+ bool isSize4 = (sizeof(T) == 4);
122
+ switch (p_method)
123
+ {
124
+ case SPTAG::DistCalcMethod::InnerProduct:
125
+ case SPTAG::DistCalcMethod::Cosine:
126
+ if (InstructionSet::AVX512())
127
+ {
128
+ return &(DistanceUtils::ComputeCosineDistance_AVX512);
129
+ }
130
+ else if (InstructionSet::AVX2() || (isSize4 && InstructionSet::AVX()))
131
+ {
132
+ return &(DistanceUtils::ComputeCosineDistance_AVX);
133
+ }
134
+ else if (InstructionSet::SSE2() || (isSize4 && InstructionSet::SSE()))
135
+ {
136
+ return &(DistanceUtils::ComputeCosineDistance_SSE);
137
+ }
138
+ else {
139
+ return &(DistanceUtils::ComputeCosineDistance);
140
+ }
141
+
142
+ case SPTAG::DistCalcMethod::L2:
143
+ if (InstructionSet::AVX512())
144
+ {
145
+ return &(DistanceUtils::ComputeL2Distance_AVX512);
146
+ }
147
+ else if (InstructionSet::AVX2() || (isSize4 && InstructionSet::AVX()))
148
+ {
149
+ return &(DistanceUtils::ComputeL2Distance_AVX);
150
+ }
151
+ else if (InstructionSet::SSE2() || (isSize4 && InstructionSet::SSE()))
152
+ {
153
+ return &(DistanceUtils::ComputeL2Distance_SSE);
154
+ }
155
+ else {
156
+ return &(DistanceUtils::ComputeL2Distance);
157
+ }
158
+
159
+ default:
160
+ break;
161
+ }
162
+ return nullptr;
163
+ }
164
+ }
165
+ }
166
+
167
+ #endif // _SPTAG_COMMON_DISTANCEUTILS_H_
SPANN/AnnService/inc/Core/Common/FineGrainedLock.h ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright (c) Microsoft Corporation. All rights reserved.
2
+ // Licensed under the MIT License.
3
+
4
+ #ifndef _SPTAG_COMMON_FINEGRAINEDLOCK_H_
5
+ #define _SPTAG_COMMON_FINEGRAINEDLOCK_H_
6
+
7
+ #include <shared_mutex>
8
+ #include <vector>
9
+ #include <mutex>
10
+ #include <memory>
11
+
12
+ namespace SPTAG
13
+ {
14
+ namespace COMMON
15
+ {
16
+ class FineGrainedLock {
17
+ public:
18
+ FineGrainedLock() {
19
+ m_locks.reset(new std::mutex[PoolSize + 1]);
20
+ }
21
+ ~FineGrainedLock() {}
22
+
23
+ std::mutex& operator[](SizeType idx) {
24
+ unsigned index = hash_func((unsigned)idx);
25
+ return m_locks[index];
26
+ }
27
+
28
+ const std::mutex& operator[](SizeType idx) const {
29
+ unsigned index = hash_func((unsigned)idx);
30
+ return m_locks[index];
31
+ }
32
+ private:
33
+ static const int PoolSize = 32767;
34
+ std::unique_ptr<std::mutex[]> m_locks;
35
+
36
+ inline unsigned hash_func(unsigned idx) const
37
+ {
38
+ return ((unsigned)(idx * 99991) + _rotl(idx, 2) + 101) & PoolSize;
39
+ }
40
+ };
41
+ }
42
+ }
43
+
44
+ #endif // _SPTAG_COMMON_FINEGRAINEDLOCK_H_
SPANN/AnnService/inc/Core/Common/Heap.h ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright (c) Microsoft Corporation. All rights reserved.
2
+ // Licensed under the MIT License.
3
+
4
+ #ifndef _SPTAG_COMMON_HEAP_H_
5
+ #define _SPTAG_COMMON_HEAP_H_
6
+
7
+ namespace SPTAG
8
+ {
9
+ namespace COMMON
10
+ {
11
+
12
+ // priority queue
13
+ template <typename T>
14
+ class Heap {
15
+ public:
16
+ Heap() : heap(nullptr), length(0), count(0) {}
17
+
18
+ Heap(int size) { Resize(size); }
19
+
20
+ void Resize(int size)
21
+ {
22
+ length = size;
23
+ heap.reset(new T[length + 1]); // heap uses 1-based indexing
24
+ count = 0;
25
+ lastlevel = int(pow(2.0, floor(log2((float)size))));
26
+ }
27
+ ~Heap() {}
28
+ inline int size() { return count; }
29
+ inline bool empty() { return count == 0; }
30
+ inline void clear(int size)
31
+ {
32
+ if (size > length) Resize(size);
33
+ count = 0;
34
+ }
35
+
36
+ inline T& Top() { if (count == 0) return heap[0]; else return heap[1]; }
37
+
38
+ // Insert a new element in the heap.
39
+ void insert(const T& value)
40
+ {
41
+ /* If heap is full, then return without adding this element. */
42
+ int loc;
43
+ if (count == length) {
44
+ int maxi = lastlevel;
45
+ for (int i = lastlevel + 1; i <= length; i++)
46
+ if (heap[maxi] < heap[i]) maxi = i;
47
+ if (value > heap[maxi]) return;
48
+ loc = maxi;
49
+ }
50
+ else {
51
+ loc = ++(count); /* Remember 1-based indexing. */
52
+ }
53
+ /* Keep moving parents down until a place is found for this node. */
54
+ int par = (loc >> 1); /* Location of parent. */
55
+ while (par > 0 && value < heap[par]) {
56
+ heap[loc] = heap[par]; /* Move parent down to loc. */
57
+ loc = par;
58
+ par >>= 1;
59
+ }
60
+ /* Insert the element at the determined location. */
61
+ heap[loc] = value;
62
+ }
63
+ // Returns the node of minimum value from the heap (top of the heap).
64
+ bool pop(T& value)
65
+ {
66
+ if (count == 0) return false;
67
+ /* Switch first node with last. */
68
+ value = heap[1];
69
+ std::swap(heap[1], heap[count]);
70
+ count--;
71
+ heapify(); /* Move new node 1 to right position. */
72
+ return true; /* Return old last node. */
73
+ }
74
+ T& pop()
75
+ {
76
+ if (count == 0) return heap[0];
77
+ /* Switch first node with last. */
78
+ std::swap(heap[1], heap[count]);
79
+ count--;
80
+ heapify(); /* Move new node 1 to right position. */
81
+ return heap[count + 1]; /* Return old last node. */
82
+ }
83
+ private:
84
+ // Storage array for the heap.
85
+ // Type T must be comparable.
86
+ std::unique_ptr<T[]> heap;
87
+ int length;
88
+ int count; // Number of element in the heap
89
+ int lastlevel;
90
+ // Reorganizes the heap (a parent is smaller than its children) starting with a node.
91
+
92
+ void heapify()
93
+ {
94
+ int parent = 1, next = 2;
95
+ while (next < count) {
96
+ if (heap[next] > heap[next + 1]) next++;
97
+ if (heap[next] < heap[parent]) {
98
+ std::swap(heap[parent], heap[next]);
99
+ parent = next;
100
+ next <<= 1;
101
+ }
102
+ else break;
103
+ }
104
+ if (next == count && heap[next] < heap[parent]) std::swap(heap[parent], heap[next]);
105
+ }
106
+ };
107
+ }
108
+ }
109
+
110
+ #endif // _SPTAG_COMMON_HEAP_H_
SPANN/AnnService/inc/Core/Common/IQuantizer.h ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright (c) Microsoft Corporation. All rights reserved.
2
+ // Licensed under the MIT License.
3
+
4
+ #ifndef _SPTAG_COMMON_QUANTIZER_H_
5
+ #define _SPTAG_COMMON_QUANTIZER_H_
6
+
7
+ #include "inc/Core/Common.h"
8
+ #include <cstdint>
9
+ #include "inc/Core/CommonDataStructure.h"
10
+ #include "DistanceUtils.h"
11
+
12
+ namespace SPTAG
13
+ {
14
+ namespace COMMON
15
+ {
16
+ class IQuantizer
17
+ {
18
+ public:
19
+ virtual float L2Distance(const std::uint8_t* pX, const std::uint8_t* pY) const = 0;
20
+
21
+ virtual float CosineDistance(const std::uint8_t* pX, const std::uint8_t* pY) const = 0;
22
+
23
+ template <typename T>
24
+ std::function<float(const T*, const T*, SizeType)> DistanceCalcSelector(SPTAG::DistCalcMethod p_method) const;
25
+
26
+ virtual void QuantizeVector(const void* vec, std::uint8_t* vecout, bool ADC = true) const = 0;
27
+
28
+ virtual SizeType QuantizeSize() const = 0;
29
+
30
+ virtual void ReconstructVector(const std::uint8_t* qvec, void* vecout) const = 0;
31
+
32
+ virtual SizeType ReconstructSize() const = 0;
33
+
34
+ virtual DimensionType ReconstructDim() const = 0;
35
+
36
+ virtual std::uint64_t BufferSize() const = 0;
37
+
38
+ virtual ErrorCode SaveQuantizer(std::shared_ptr<Helper::DiskIO> p_out) const = 0;
39
+
40
+ virtual ErrorCode LoadQuantizer(std::shared_ptr<Helper::DiskIO> p_in) = 0;
41
+
42
+ virtual ErrorCode LoadQuantizer(uint8_t* raw_bytes) = 0;
43
+
44
+ static std::shared_ptr<IQuantizer> LoadIQuantizer(std::shared_ptr<Helper::DiskIO> p_in);
45
+
46
+ static std::shared_ptr<IQuantizer> LoadIQuantizer(SPTAG::ByteArray bytes);
47
+
48
+ virtual bool GetEnableADC() const = 0;
49
+
50
+ virtual void SetEnableADC(bool enableADC) = 0;
51
+
52
+ virtual QuantizerType GetQuantizerType() const = 0;
53
+
54
+ virtual VectorValueType GetReconstructType() const = 0;
55
+
56
+ virtual DimensionType GetNumSubvectors() const = 0;
57
+
58
+ virtual int GetBase() const = 0;
59
+
60
+ virtual float* GetL2DistanceTables() = 0;
61
+
62
+ template<typename T>
63
+ T* GetCodebooks();
64
+ };
65
+ }
66
+ }
67
+
68
+ #endif // _SPTAG_COMMON_QUANTIZER_H_
SPANN/AnnService/inc/Core/Common/InstructionUtils.h ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #ifndef _SPTAG_COMMON_INSTRUCTIONUTILS_H_
2
+ #define _SPTAG_COMMON_INSTRUCTIONUTILS_H_
3
+
4
+ #include <string>
5
+ #include <vector>
6
+ #include <bitset>
7
+ #include <array>
8
+
9
+ #ifndef GPU
10
+
11
+ #ifndef _MSC_VER
12
+ #include <cpuid.h>
13
+ #include <xmmintrin.h>
14
+ #include <immintrin.h>
15
+
16
+ void cpuid(int info[4], int InfoType);
17
+
18
+ #else
19
+ #include <intrin.h>
20
+ #define cpuid(info, x) __cpuidex(info, x, 0)
21
+ #endif
22
+
23
+ #endif
24
+
25
+ namespace SPTAG {
26
+ namespace COMMON {
27
+
28
+ class InstructionSet
29
+ {
30
+ // forward declarations
31
+ class InstructionSet_Internal;
32
+
33
+ public:
34
+ // getters
35
+ static bool AVX(void);
36
+ static bool SSE(void);
37
+ static bool SSE2(void);
38
+ static bool AVX2(void);
39
+ static bool AVX512(void);
40
+ static void PrintInstructionSet(void);
41
+
42
+ private:
43
+ static const InstructionSet_Internal CPU_Rep;
44
+
45
+ class InstructionSet_Internal
46
+ {
47
+ public:
48
+ InstructionSet_Internal();
49
+ bool HW_SSE;
50
+ bool HW_SSE2;
51
+ bool HW_AVX;
52
+ bool HW_AVX2;
53
+ bool HW_AVX512;
54
+ };
55
+ };
56
+ }
57
+ }
58
+
59
+ #endif
SPANN/AnnService/inc/Core/Common/PQQuantizer.h ADDED
@@ -0,0 +1,362 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright (c) Microsoft Corporation. All rights reserved.
2
+ // Licensed under the MIT License.
3
+
4
+ #ifndef _SPTAG_COMMON_PQQUANTIZER_H_
5
+ #define _SPTAG_COMMON_PQQUANTIZER_H_
6
+
7
+ #include "CommonUtils.h"
8
+ #include "DistanceUtils.h"
9
+ #include "IQuantizer.h"
10
+ #include <iostream>
11
+ #include <fstream>
12
+ #include <limits>
13
+ #include <memory>
14
+ #include <cassert>
15
+ #include <cstring>
16
+
17
+
18
+ namespace SPTAG
19
+ {
20
+ namespace COMMON
21
+ {
22
+ template <typename T>
23
+ class PQQuantizer : public IQuantizer
24
+ {
25
+ public:
26
+ PQQuantizer();
27
+
28
+ PQQuantizer(DimensionType NumSubvectors, SizeType KsPerSubvector, DimensionType DimPerSubvector, bool EnableADC, std::unique_ptr<T[]>&& Codebooks);
29
+
30
+ ~PQQuantizer();
31
+
32
+ virtual float L2Distance(const std::uint8_t* pX, const std::uint8_t* pY) const;
33
+
34
+ virtual float CosineDistance(const std::uint8_t* pX, const std::uint8_t* pY) const;
35
+
36
+ virtual void QuantizeVector(const void* vec, std::uint8_t* vecout, bool ADC = true) const;
37
+
38
+ virtual SizeType QuantizeSize() const;
39
+
40
+ void ReconstructVector(const std::uint8_t* qvec, void* vecout) const;
41
+
42
+ virtual SizeType ReconstructSize() const;
43
+
44
+ virtual DimensionType ReconstructDim() const;
45
+
46
+ virtual std::uint64_t BufferSize() const;
47
+
48
+ virtual ErrorCode SaveQuantizer(std::shared_ptr<Helper::DiskIO> p_out) const;
49
+
50
+ virtual ErrorCode LoadQuantizer(std::shared_ptr<Helper::DiskIO> p_in);
51
+
52
+ virtual ErrorCode LoadQuantizer(std::uint8_t* raw_bytes);
53
+
54
+ virtual DimensionType GetNumSubvectors() const;
55
+
56
+ virtual int GetBase() const;
57
+
58
+ SizeType GetKsPerSubvector() const;
59
+
60
+ SizeType GetBlockSize() const;
61
+
62
+ DimensionType GetDimPerSubvector() const;
63
+
64
+ virtual bool GetEnableADC() const;
65
+
66
+ virtual void SetEnableADC(bool enableADC);
67
+
68
+ VectorValueType GetReconstructType() const
69
+ {
70
+ return GetEnumValueType<T>();
71
+ }
72
+
73
+ QuantizerType GetQuantizerType() const {
74
+ return QuantizerType::PQQuantizer;
75
+ }
76
+
77
+ float* GetL2DistanceTables();
78
+
79
+ T* GetCodebooks();
80
+
81
+ protected:
82
+ DimensionType m_NumSubvectors;
83
+ SizeType m_KsPerSubvector;
84
+ DimensionType m_DimPerSubvector;
85
+ SizeType m_BlockSize;
86
+ bool m_EnableADC;
87
+
88
+ inline SizeType m_DistIndexCalc(SizeType i, SizeType j, SizeType k) const;
89
+ void InitializeDistanceTables();
90
+
91
+ std::unique_ptr<T[]> m_codebooks;
92
+ std::unique_ptr<const float[]> m_L2DistanceTables;
93
+ };
94
+
95
+ template <typename T>
96
+ PQQuantizer<T>::PQQuantizer() : m_NumSubvectors(0), m_KsPerSubvector(0), m_DimPerSubvector(0), m_BlockSize(0), m_EnableADC(false)
97
+ {
98
+ }
99
+
100
+ template <typename T>
101
+ PQQuantizer<T>::PQQuantizer(DimensionType NumSubvectors, SizeType KsPerSubvector, DimensionType DimPerSubvector, bool EnableADC, std::unique_ptr<T[]>&& Codebooks) : m_NumSubvectors(NumSubvectors), m_KsPerSubvector(KsPerSubvector), m_DimPerSubvector(DimPerSubvector), m_BlockSize(KsPerSubvector* KsPerSubvector), m_codebooks(std::move(Codebooks)), m_EnableADC(EnableADC)
102
+ {
103
+ InitializeDistanceTables();
104
+ }
105
+
106
+ template <typename T>
107
+ PQQuantizer<T>::~PQQuantizer()
108
+ {}
109
+
110
+ template <typename T>
111
+ float PQQuantizer<T>::L2Distance(const std::uint8_t* pX, const std::uint8_t* pY) const
112
+ // pX must be query distance table for ADC
113
+ {
114
+ float out = 0;
115
+ if (GetEnableADC()) {
116
+ float* ptr = (float*)pX;
117
+ for (int i = 0; i < m_NumSubvectors; i++) {
118
+ out += ptr[pY[i]];
119
+ ptr += m_KsPerSubvector;
120
+ }
121
+ }
122
+ else {
123
+ for (int i = 0; i < m_NumSubvectors; i++) {
124
+ out += m_L2DistanceTables[m_DistIndexCalc(i, pX[i], pY[i])];
125
+ }
126
+ }
127
+ return out;
128
+ }
129
+
130
+ template <typename T>
131
+ float PQQuantizer<T>::CosineDistance(const std::uint8_t* pX, const std::uint8_t* pY) const
132
+ // pX must be query distance table for ADC
133
+ {
134
+ SPTAGLIB_LOG(Helper::LogLevel::LL_Error, "Quantizer does not support CosineDistance!\n");
135
+ return 0;
136
+ }
137
+
138
+ template <typename T>
139
+ void PQQuantizer<T>::QuantizeVector(const void* vec, std::uint8_t* vecout, bool ADC) const
140
+ {
141
+ if (ADC && GetEnableADC())
142
+ {
143
+ auto distCalc = DistanceCalcSelector<T>(DistCalcMethod::L2);
144
+ float* ADCtable = (float*) vecout;
145
+ T* subcodebooks = m_codebooks.get();
146
+ T* subvec = (T*)vec;
147
+ for (int i = 0; i < m_NumSubvectors; i++)
148
+ {
149
+ for (int j = 0; j < m_KsPerSubvector; j++)
150
+ {
151
+ (*ADCtable) = distCalc(subvec, subcodebooks, m_DimPerSubvector);
152
+ ADCtable++;
153
+ subcodebooks += m_DimPerSubvector;
154
+ }
155
+ subvec += m_DimPerSubvector;
156
+ }
157
+ }
158
+ else
159
+ {
160
+ auto distCalc = DistanceCalcSelector<T>(DistCalcMethod::L2);
161
+ T* subvec = (T*)vec;
162
+ T* subcodebooks = m_codebooks.get();
163
+ for (int i = 0; i < m_NumSubvectors; i++) {
164
+ int bestIndex = -1;
165
+ float minDist = std::numeric_limits<float>::infinity();
166
+
167
+ for (int j = 0; j < m_KsPerSubvector; j++) {
168
+ float dist = distCalc(subvec, subcodebooks, m_DimPerSubvector);
169
+ if (dist < minDist) {
170
+ bestIndex = j;
171
+ minDist = dist;
172
+ }
173
+ subcodebooks += m_DimPerSubvector;
174
+ }
175
+ assert(bestIndex != -1);
176
+ vecout[i] = (std::uint8_t)bestIndex;
177
+ subvec += m_DimPerSubvector;
178
+ }
179
+ }
180
+ }
181
+
182
+ template <typename T>
183
+ SizeType PQQuantizer<T>::QuantizeSize() const
184
+ {
185
+ if (GetEnableADC())
186
+ {
187
+ return sizeof(float) * m_NumSubvectors * m_KsPerSubvector;
188
+ }
189
+ else
190
+ {
191
+ return m_NumSubvectors;
192
+ }
193
+ }
194
+
195
+ template <typename T>
196
+ void PQQuantizer<T>::ReconstructVector(const std::uint8_t* qvec, void* vecout) const
197
+ {
198
+ T* sub_vecout = (T*)vecout;
199
+ T* subcodebooks = m_codebooks.get();
200
+ for (int i = 0; i < m_NumSubvectors; i++) {
201
+ memcpy(sub_vecout, subcodebooks + qvec[i] * m_DimPerSubvector, sizeof(T) * m_DimPerSubvector);
202
+ sub_vecout += m_DimPerSubvector;
203
+ subcodebooks += m_KsPerSubvector * m_DimPerSubvector;
204
+ }
205
+ }
206
+
207
+ template <typename T>
208
+ SizeType PQQuantizer<T>::ReconstructSize() const
209
+ {
210
+ return sizeof(T) * ReconstructDim();
211
+ }
212
+
213
+ template <typename T>
214
+ DimensionType PQQuantizer<T>::ReconstructDim() const
215
+ {
216
+ return m_DimPerSubvector * m_NumSubvectors;
217
+ }
218
+
219
+ template <typename T>
220
+ std::uint64_t PQQuantizer<T>::BufferSize() const
221
+ {
222
+ return sizeof(T) * m_NumSubvectors * m_KsPerSubvector * m_DimPerSubvector +
223
+ sizeof(DimensionType) + sizeof(SizeType) + sizeof(DimensionType) + sizeof(VectorValueType) + sizeof(QuantizerType);
224
+ }
225
+
226
+ template <typename T>
227
+ ErrorCode PQQuantizer<T>::SaveQuantizer(std::shared_ptr<Helper::DiskIO> p_out) const
228
+ {
229
+ QuantizerType qtype = QuantizerType::PQQuantizer;
230
+ VectorValueType rtype = GetEnumValueType<T>();
231
+ IOBINARY(p_out, WriteBinary, sizeof(QuantizerType), (char*)&qtype);
232
+ IOBINARY(p_out, WriteBinary, sizeof(VectorValueType), (char*)&rtype);
233
+ IOBINARY(p_out, WriteBinary, sizeof(DimensionType), (char*)&m_NumSubvectors);
234
+ IOBINARY(p_out, WriteBinary, sizeof(SizeType), (char*)&m_KsPerSubvector);
235
+ IOBINARY(p_out, WriteBinary, sizeof(DimensionType), (char*)&m_DimPerSubvector);
236
+ IOBINARY(p_out, WriteBinary, sizeof(T) * m_NumSubvectors * m_KsPerSubvector * m_DimPerSubvector, (char*)m_codebooks.get());
237
+ SPTAGLIB_LOG(Helper::LogLevel::LL_Info, "Saving quantizer: Subvectors:%d KsPerSubvector:%d DimPerSubvector:%d\n", m_NumSubvectors, m_KsPerSubvector, m_DimPerSubvector);
238
+ return ErrorCode::Success;
239
+ }
240
+
241
+ template <typename T>
242
+ ErrorCode PQQuantizer<T>::LoadQuantizer(std::shared_ptr<Helper::DiskIO> p_in)
243
+ {
244
+ SPTAGLIB_LOG(Helper::LogLevel::LL_Info, "Loading Quantizer.\n");
245
+ IOBINARY(p_in, ReadBinary, sizeof(DimensionType), (char*)&m_NumSubvectors);
246
+ SPTAGLIB_LOG(Helper::LogLevel::LL_Info, "After read subvecs: %s.\n", std::to_string(m_NumSubvectors).c_str());
247
+ IOBINARY(p_in, ReadBinary, sizeof(SizeType), (char*)&m_KsPerSubvector);
248
+ SPTAGLIB_LOG(Helper::LogLevel::LL_Info, "After read ks: %s.\n", std::to_string(m_KsPerSubvector).c_str());
249
+ IOBINARY(p_in, ReadBinary, sizeof(DimensionType), (char*)&m_DimPerSubvector);
250
+ SPTAGLIB_LOG(Helper::LogLevel::LL_Info, "After read dim: %s.\n", std::to_string(m_DimPerSubvector).c_str());
251
+ m_codebooks = std::make_unique<T[]>(m_NumSubvectors * m_KsPerSubvector * m_DimPerSubvector);
252
+ SPTAGLIB_LOG(Helper::LogLevel::LL_Info, "sizeof(T): %s.\n", std::to_string(sizeof(T)).c_str());
253
+ IOBINARY(p_in, ReadBinary, sizeof(T) * m_NumSubvectors * m_KsPerSubvector * m_DimPerSubvector, (char*)m_codebooks.get());
254
+ SPTAGLIB_LOG(Helper::LogLevel::LL_Info, "After read codebooks.\n");
255
+
256
+ m_BlockSize = m_KsPerSubvector * m_KsPerSubvector;
257
+ InitializeDistanceTables();
258
+ SPTAGLIB_LOG(Helper::LogLevel::LL_Info, "Loaded quantizer: Subvectors:%d KsPerSubvector:%d DimPerSubvector:%d\n", m_NumSubvectors, m_KsPerSubvector, m_DimPerSubvector);
259
+ return ErrorCode::Success;
260
+ }
261
+
262
+ template <typename T>
263
+ ErrorCode PQQuantizer<T>::LoadQuantizer(std::uint8_t* raw_bytes)
264
+ {
265
+ SPTAGLIB_LOG(Helper::LogLevel::LL_Info, "Loading Quantizer.\n");
266
+ m_NumSubvectors = *(DimensionType*)raw_bytes;
267
+ raw_bytes += sizeof(DimensionType);
268
+ SPTAGLIB_LOG(Helper::LogLevel::LL_Info, "After read subvecs: %s.\n", std::to_string(m_NumSubvectors).c_str());
269
+ m_KsPerSubvector = *(SizeType*)raw_bytes;
270
+ raw_bytes += sizeof(SizeType);
271
+ SPTAGLIB_LOG(Helper::LogLevel::LL_Info, "After read ks: %s.\n", std::to_string(m_KsPerSubvector).c_str());
272
+ m_DimPerSubvector = *(DimensionType*)raw_bytes;
273
+ raw_bytes += sizeof(DimensionType);
274
+ SPTAGLIB_LOG(Helper::LogLevel::LL_Info, "After read dim: %s.\n", std::to_string(m_DimPerSubvector).c_str());
275
+ m_codebooks = std::make_unique<T[]>(m_NumSubvectors * m_KsPerSubvector * m_DimPerSubvector);
276
+ SPTAGLIB_LOG(Helper::LogLevel::LL_Info, "sizeof(T): %s.\n", std::to_string(sizeof(T)).c_str());
277
+ std::memcpy(m_codebooks.get(), raw_bytes, sizeof(T) * m_NumSubvectors * m_KsPerSubvector * m_DimPerSubvector);
278
+ SPTAGLIB_LOG(Helper::LogLevel::LL_Info, "After read codebooks.\n");
279
+
280
+ m_BlockSize = m_KsPerSubvector * m_KsPerSubvector;
281
+ InitializeDistanceTables();
282
+ SPTAGLIB_LOG(Helper::LogLevel::LL_Info, "Loaded quantizer: Subvectors:%d KsPerSubvector:%d DimPerSubvector:%d\n", m_NumSubvectors, m_KsPerSubvector, m_DimPerSubvector);
283
+ return ErrorCode::Success;
284
+ }
285
+
286
+ template <typename T>
287
+ int PQQuantizer<T>::GetBase() const
288
+ {
289
+ return COMMON::Utils::GetBase<T>();
290
+ }
291
+
292
+ template <typename T>
293
+ DimensionType PQQuantizer<T>::GetNumSubvectors() const
294
+ {
295
+ return m_NumSubvectors;
296
+ }
297
+
298
+ template <typename T>
299
+ SizeType PQQuantizer<T>::GetKsPerSubvector() const
300
+ {
301
+ return m_KsPerSubvector;
302
+ }
303
+
304
+ template <typename T>
305
+ SizeType PQQuantizer<T>::GetBlockSize() const
306
+ {
307
+ return m_BlockSize;
308
+ }
309
+
310
+ template <typename T>
311
+ DimensionType PQQuantizer<T>::GetDimPerSubvector() const
312
+ {
313
+ return m_DimPerSubvector;
314
+ }
315
+
316
+ template <typename T>
317
+ bool PQQuantizer<T>::GetEnableADC() const
318
+ {
319
+ return m_EnableADC;
320
+ }
321
+
322
+ template <typename T>
323
+ void PQQuantizer<T>::SetEnableADC(bool enableADC)
324
+ {
325
+ m_EnableADC = enableADC;
326
+ }
327
+
328
+ template <typename T>
329
+ inline SizeType PQQuantizer<T>::m_DistIndexCalc(SizeType i, SizeType j, SizeType k) const {
330
+ return m_BlockSize * i + j * m_KsPerSubvector + k;
331
+ }
332
+
333
+ template <typename T>
334
+ void PQQuantizer<T>::InitializeDistanceTables()
335
+ {
336
+ auto temp_m_L2DistanceTables = std::make_unique<float[]>(m_BlockSize * m_NumSubvectors);
337
+ auto L2Dist = DistanceCalcSelector<T>(DistCalcMethod::L2);
338
+
339
+ for (int i = 0; i < m_NumSubvectors; i++) {
340
+ SizeType baseIdx = i * m_KsPerSubvector * m_DimPerSubvector;
341
+ for (int j = 0; j < m_KsPerSubvector; j++) {
342
+ for (int k = 0; k < m_KsPerSubvector; k++) {
343
+ temp_m_L2DistanceTables[m_DistIndexCalc(i, j, k)] = L2Dist(&m_codebooks[baseIdx + j * m_DimPerSubvector], &m_codebooks[baseIdx + k * m_DimPerSubvector], m_DimPerSubvector);
344
+ }
345
+ }
346
+ }
347
+ m_L2DistanceTables = std::move(temp_m_L2DistanceTables);
348
+ }
349
+
350
+ template <typename T>
351
+ float* PQQuantizer<T>::GetL2DistanceTables() {
352
+ return (float*)(m_L2DistanceTables.get());
353
+ }
354
+
355
+ template<typename T>
356
+ T* PQQuantizer<T>::GetCodebooks() {
357
+ return (T*)(m_codebooks.get());
358
+ }
359
+ }
360
+ }
361
+
362
+ #endif // _SPTAG_COMMON_PQQUANTIZER_H_
SPANN/AnnService/inc/Core/Common/QueryResultSet.h ADDED
@@ -0,0 +1,124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright (c) Microsoft Corporation. All rights reserved.
2
+ // Licensed under the MIT License.
3
+
4
+ #ifndef _SPTAG_COMMON_QUERYRESULTSET_H_
5
+ #define _SPTAG_COMMON_QUERYRESULTSET_H_
6
+
7
+ #include "inc/Core/SearchQuery.h"
8
+ #include "DistanceUtils.h"
9
+ #include <algorithm>
10
+ #include "IQuantizer.h"
11
+
12
+ namespace SPTAG
13
+ {
14
+ namespace COMMON
15
+ {
16
+
17
+ inline bool operator < (const BasicResult& lhs, const BasicResult& rhs)
18
+ {
19
+ return ((lhs.Dist < rhs.Dist) || ((lhs.Dist == rhs.Dist) && (lhs.VID < rhs.VID)));
20
+ }
21
+
22
+
23
+ inline bool Compare(const BasicResult& lhs, const BasicResult& rhs)
24
+ {
25
+ return ((lhs.Dist < rhs.Dist) || ((lhs.Dist == rhs.Dist) && (lhs.VID < rhs.VID)));
26
+ }
27
+
28
+
29
+ // Space to save temporary answer, similar with TopKCache
30
+ template<typename T>
31
+ class QueryResultSet : public QueryResult
32
+ {
33
+ public:
34
+ QueryResultSet(const T* _target, int _K) : QueryResult(_target, _K, false)
35
+ {
36
+ }
37
+
38
+ QueryResultSet(const QueryResultSet& other) : QueryResult(other)
39
+ {
40
+ }
41
+
42
+ ~QueryResultSet()
43
+ {
44
+ }
45
+
46
+ inline void SetTarget(const T* p_target, const std::shared_ptr<IQuantizer>& quantizer)
47
+ {
48
+ if (quantizer == nullptr) QueryResult::SetTarget((const void*)p_target);
49
+ else
50
+ {
51
+ if (m_target == m_quantizedTarget || (m_quantizedSize != quantizer->QuantizeSize()))
52
+ {
53
+ if (m_target != m_quantizedTarget) ALIGN_FREE(m_quantizedTarget);
54
+ m_quantizedTarget = ALIGN_ALLOC(quantizer->QuantizeSize());
55
+ m_quantizedSize = quantizer->QuantizeSize();
56
+ }
57
+ m_target = p_target;
58
+ quantizer->QuantizeVector((void*)p_target, (uint8_t*)m_quantizedTarget);
59
+ }
60
+ }
61
+
62
+ inline const T* GetTarget() const
63
+ {
64
+ return reinterpret_cast<const T*>(m_target);
65
+ }
66
+
67
+ T* GetQuantizedTarget()
68
+ {
69
+ return reinterpret_cast<T*>(m_quantizedTarget);
70
+ }
71
+
72
+ inline float worstDist() const
73
+ {
74
+ return m_results[0].Dist;
75
+ }
76
+
77
+ bool AddPoint(const SizeType index, float dist)
78
+ {
79
+ if (dist < m_results[0].Dist || (dist == m_results[0].Dist && index < m_results[0].VID))
80
+ {
81
+ m_results[0].VID = index;
82
+ m_results[0].Dist = dist;
83
+ Heapify(m_resultNum);
84
+ return true;
85
+ }
86
+ return false;
87
+ }
88
+
89
+ inline void SortResult()
90
+ {
91
+ for (int i = m_resultNum - 1; i >= 0; i--)
92
+ {
93
+ std::swap(m_results[0], m_results[i]);
94
+ Heapify(i);
95
+ }
96
+ }
97
+
98
+ void Reverse()
99
+ {
100
+ std::reverse(m_results.Data(), m_results.Data() + m_resultNum);
101
+ }
102
+
103
+ private:
104
+ void Heapify(int count)
105
+ {
106
+ int parent = 0, next = 1, maxidx = count - 1;
107
+ while (next < maxidx)
108
+ {
109
+ if (m_results[next] < m_results[next + 1]) next++;
110
+ if (m_results[parent] < m_results[next])
111
+ {
112
+ std::swap(m_results[next], m_results[parent]);
113
+ parent = next;
114
+ next = (parent << 1) + 1;
115
+ }
116
+ else break;
117
+ }
118
+ if (next == maxidx && m_results[parent] < m_results[next]) std::swap(m_results[parent], m_results[next]);
119
+ }
120
+ };
121
+ }
122
+ }
123
+
124
+ #endif // _SPTAG_COMMON_QUERYRESULTSET_H_
SPANN/AnnService/inc/Core/Common/RelativeNeighborhoodGraph.h ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright (c) Microsoft Corporation. All rights reserved.
2
+ // Licensed under the MIT License.
3
+
4
+ #ifndef _SPTAG_COMMON_RNG_H_
5
+ #define _SPTAG_COMMON_RNG_H_
6
+
7
+ #include "NeighborhoodGraph.h"
8
+
9
+ namespace SPTAG
10
+ {
11
+ namespace COMMON
12
+ {
13
+ class RelativeNeighborhoodGraph: public NeighborhoodGraph
14
+ {
15
+ public:
16
+ RelativeNeighborhoodGraph() { m_pNeighborhoodGraph.SetName("RNG"); }
17
+
18
+ void RebuildNeighbors(VectorIndex* index, const SizeType node, SizeType* nodes, const BasicResult* queryResults, const int numResults) {
19
+ DimensionType count = 0;
20
+ for (int j = 0; j < numResults && count < m_iNeighborhoodSize; j++) {
21
+ const BasicResult& item = queryResults[j];
22
+ if (item.VID < 0) break;
23
+ if (item.VID == node) continue;
24
+
25
+ bool good = true;
26
+ for (DimensionType k = 0; k < count; k++) {
27
+ if (m_fRNGFactor * index->ComputeDistance(index->GetSample(nodes[k]), index->GetSample(item.VID)) < item.Dist) {
28
+ good = false;
29
+ break;
30
+ }
31
+ }
32
+ if (good) nodes[count++] = item.VID;
33
+ }
34
+ for (DimensionType j = count; j < m_iNeighborhoodSize; j++) nodes[j] = -1;
35
+ }
36
+
37
+ void InsertNeighbors(VectorIndex* index, const SizeType node, SizeType insertNode, float insertDist)
38
+ {
39
+ SizeType* nodes = m_pNeighborhoodGraph[node];
40
+ const void* nodeVec = index->GetSample(node);
41
+ const void* insertVec = index->GetSample(insertNode);
42
+
43
+ std::lock_guard<std::mutex> lock(m_dataUpdateLock[node]);
44
+
45
+ _mm_prefetch((const char*)nodes, _MM_HINT_T0);
46
+ _mm_prefetch((const char*)(nodeVec), _MM_HINT_T0);
47
+ _mm_prefetch((const char*)(insertVec), _MM_HINT_T0);
48
+ for (DimensionType i = 0; i < m_iNeighborhoodSize; i++) {
49
+ auto futureNode = nodes[i];
50
+ if (futureNode < 0) break;
51
+ _mm_prefetch((const char*)(index->GetSample(futureNode)), _MM_HINT_T0);
52
+ }
53
+
54
+ SizeType tmpNode;
55
+ float tmpDist;
56
+ const void* tmpVec;
57
+ int checkNeighborhoodSize = (nodes[m_iNeighborhoodSize - 1] < -1) ? m_iNeighborhoodSize - 1 : m_iNeighborhoodSize;
58
+ for (DimensionType k = 0; k < checkNeighborhoodSize; k++)
59
+ {
60
+ tmpNode = nodes[k];
61
+ if (tmpNode < 0) {
62
+ nodes[k] = insertNode;
63
+ break;
64
+ }
65
+
66
+ tmpVec = index->GetSample(tmpNode);
67
+ tmpDist = index->ComputeDistance(tmpVec, nodeVec);
68
+ if (tmpDist > insertDist || (insertDist == tmpDist && insertNode < tmpNode))
69
+ {
70
+ nodes[k] = insertNode;
71
+ while (++k < checkNeighborhoodSize && index->ComputeDistance(tmpVec, nodeVec) <= index->ComputeDistance(tmpVec, insertVec)) {
72
+ std::swap(tmpNode, nodes[k]);
73
+ if (tmpNode < 0) return;
74
+ tmpVec = index->GetSample(tmpNode);
75
+ }
76
+ break;
77
+ }
78
+ else if (index->ComputeDistance(tmpVec, insertVec) < insertDist) {
79
+ break;
80
+ }
81
+ }
82
+ }
83
+ };
84
+ }
85
+ }
86
+ #endif
SPANN/AnnService/inc/Core/Common/WorkSpace.h ADDED
@@ -0,0 +1,324 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright (c) Microsoft Corporation. All rights reserved.
2
+ // Licensed under the MIT License.
3
+
4
+ #ifndef _SPTAG_COMMON_WORKSPACE_H_
5
+ #define _SPTAG_COMMON_WORKSPACE_H_
6
+
7
+ #include "inc/Core/SearchResult.h"
8
+ #include "CommonUtils.h"
9
+ #include "Heap.h"
10
+
11
+ #include <stdarg.h>
12
+
13
+ namespace SPTAG
14
+ {
15
+ namespace COMMON
16
+ {
17
+ template <typename WorkSpaceType>
18
+ class IWorkSpaceFactory
19
+ {
20
+ public:
21
+ virtual std::unique_ptr<WorkSpaceType> GetWorkSpace() = 0;
22
+ virtual void ReturnWorkSpace(std::unique_ptr<WorkSpaceType> ws) = 0;
23
+ };
24
+
25
+ template <typename WorkSpaceType>
26
+ class ThreadLocalWorkSpaceFactory : public IWorkSpaceFactory<WorkSpaceType>
27
+ {
28
+ public:
29
+ static thread_local std::unique_ptr<WorkSpaceType> m_workspace;
30
+
31
+ virtual std::unique_ptr< WorkSpaceType> GetWorkSpace() override
32
+ {
33
+ return std::move(m_workspace);
34
+ }
35
+
36
+ virtual void ReturnWorkSpace(std::unique_ptr<WorkSpaceType> ws) override
37
+ {
38
+ m_workspace = std::move(ws);
39
+ }
40
+
41
+ };
42
+
43
+ class OptHashPosVector
44
+ {
45
+ protected:
46
+ // Max loop number in one hash block.
47
+ static const int m_maxLoop = 8;
48
+
49
+ // Could we use the second hash block.
50
+ bool m_secondHash;
51
+
52
+ int m_exp;
53
+
54
+ // Max pool size.
55
+ int m_poolSize;
56
+
57
+ // Record 2 hash tables.
58
+ // [0~m_poolSize + 1) is the first block.
59
+ // [m_poolSize + 1, 2*(m_poolSize + 1)) is the second block;
60
+ std::unique_ptr<SizeType[]> m_hashTable;
61
+
62
+
63
+ inline unsigned hash_func2(unsigned idx, int poolSize, int loop)
64
+ {
65
+ return (idx + loop) & poolSize;
66
+ }
67
+
68
+
69
+ inline unsigned hash_func(unsigned idx, int poolSize)
70
+ {
71
+ return ((unsigned)(idx * 99991) + _rotl(idx, 2) + 101) & poolSize;
72
+ }
73
+
74
+ public:
75
+ OptHashPosVector(): m_secondHash(false), m_exp(2), m_poolSize(8191) {}
76
+
77
+ ~OptHashPosVector() {}
78
+
79
+
80
+ void Init(SizeType size, int exp)
81
+ {
82
+ int ex = 0;
83
+ while (size != 0) {
84
+ ex++;
85
+ size >>= 1;
86
+ }
87
+ m_secondHash = true;
88
+ m_exp = exp;
89
+ m_poolSize = (1 << (ex + exp)) - 1;
90
+ m_hashTable.reset(new SizeType[(m_poolSize + 1) * 2]);
91
+ clear();
92
+ }
93
+
94
+ void clear()
95
+ {
96
+ if (!m_secondHash)
97
+ {
98
+ // Clear first block.
99
+ memset(m_hashTable.get(), 0, sizeof(SizeType) * (m_poolSize + 1));
100
+ }
101
+ else
102
+ {
103
+ // Clear all blocks.
104
+ m_secondHash = false;
105
+ memset(m_hashTable.get(), 0, 2 * sizeof(SizeType) * (m_poolSize + 1));
106
+ }
107
+ }
108
+
109
+ inline int HashTableExponent() const { return m_exp; }
110
+
111
+ inline int MaxCheck() const { return (1 << (int)(log2(m_poolSize + 1) - m_exp)); }
112
+
113
+ inline bool CheckAndSet(SizeType idx)
114
+ {
115
+ // Inner Index is begin from 1
116
+ return _CheckAndSet(m_hashTable.get(), m_poolSize, true, idx + 1) == 0;
117
+ }
118
+
119
+ inline void DoubleSize()
120
+ {
121
+ int new_poolSize = ((m_poolSize + 1) << 1) - 1;
122
+ SizeType* new_hashTable = new SizeType[(new_poolSize + 1) * 2];
123
+ memset(new_hashTable, 0, sizeof(SizeType) * (new_poolSize + 1) * 2);
124
+
125
+ m_secondHash = false;
126
+ for (int i = 0; i <= new_poolSize; i++)
127
+ if (m_hashTable[i]) _CheckAndSet(new_hashTable, new_poolSize, true, m_hashTable[i]);
128
+
129
+ m_exp++;
130
+ m_poolSize = new_poolSize;
131
+ m_hashTable.reset(new_hashTable);
132
+ }
133
+
134
+ inline int _CheckAndSet(SizeType* hashTable, int poolSize, bool isFirstTable, SizeType idx)
135
+ {
136
+ unsigned index = hash_func((unsigned)idx, poolSize);
137
+ for (int loop = 0; loop < m_maxLoop; ++loop)
138
+ {
139
+ if (!hashTable[index])
140
+ {
141
+ // index first match and record it.
142
+ hashTable[index] = idx;
143
+ return 1;
144
+ }
145
+ if (hashTable[index] == idx)
146
+ {
147
+ // Hit this item in hash table.
148
+ return 0;
149
+ }
150
+ // Get next hash position.
151
+ index = hash_func2(index, poolSize, loop);
152
+ }
153
+
154
+ if (isFirstTable)
155
+ {
156
+ // Use second hash block.
157
+ m_secondHash = true;
158
+ return _CheckAndSet(hashTable + poolSize + 1, poolSize, false, idx);
159
+ }
160
+
161
+ DoubleSize();
162
+ SPTAGLIB_LOG(Helper::LogLevel::LL_Error, "Hash table is full! Set HashTableExponent to larger value (default is 2). NewHashTableExponent=%d NewPoolSize=%d\n", m_exp, m_poolSize);
163
+ return _CheckAndSet(m_hashTable.get(), m_poolSize, true, idx);
164
+ }
165
+ };
166
+
167
+ class DistPriorityQueue {
168
+ int m_size;
169
+ std::unique_ptr<float[]> m_data;
170
+ int m_length;
171
+ int m_count;
172
+
173
+ public:
174
+ DistPriorityQueue(): m_size(0), m_length(0), m_count(0) {}
175
+
176
+ void Resize(int size_) {
177
+ m_size = size_;
178
+ m_data.reset(new float[size_ + 1]);
179
+
180
+ m_data[1] = MaxDist;
181
+ m_length = 1;
182
+ m_count = size_;
183
+ }
184
+ void clear(int count_) {
185
+ if (count_ > m_size) {
186
+ m_size = count_;
187
+ m_data.reset(new float[count_ + 1]);
188
+ }
189
+ m_data[1] = MaxDist;
190
+ m_length = 1;
191
+ m_count = count_;
192
+
193
+ }
194
+ bool insert(float dist) {
195
+ if (dist > m_data[1]) return false;
196
+
197
+ if (m_length == m_count) {
198
+ m_data[1] = dist;
199
+ int parent = 1, next = 2;
200
+ while (next < m_length) {
201
+ if (m_data[next] < m_data[next + 1]) next++;
202
+ if (m_data[next] > m_data[parent]) {
203
+ std::swap(m_data[parent], m_data[next]);
204
+ parent = next;
205
+ next <<= 1;
206
+ }
207
+ else break;
208
+ }
209
+ if (next == m_length && m_data[next] > m_data[parent]) std::swap(m_data[parent], m_data[next]);
210
+ }
211
+ else {
212
+ int next = ++(m_length), parent = (next >> 1);
213
+ while (parent > 0 && dist > m_data[parent]) {
214
+ m_data[next] = m_data[parent];
215
+ next = parent;
216
+ parent >>= 1;
217
+ }
218
+ m_data[next] = dist;
219
+ }
220
+ return true;
221
+ }
222
+ inline float worst() {
223
+ return m_data[1];
224
+ }
225
+ };
226
+
227
+ class IWorkSpace {};
228
+
229
+ // Variables for each single NN search
230
+ struct WorkSpace : public IWorkSpace
231
+ {
232
+ WorkSpace() {}
233
+
234
+ WorkSpace(WorkSpace& other)
235
+ {
236
+ Initialize(other.m_iMaxCheck, other.nodeCheckStatus.HashTableExponent());
237
+ }
238
+
239
+ ~WorkSpace() {
240
+ SPTAGLIB_LOG(Helper::LogLevel::LL_Info, "Delete workspace happens!\n");
241
+ }
242
+
243
+ void Initialize(int maxCheck, int hashExp)
244
+ {
245
+ nodeCheckStatus.Init(maxCheck, hashExp);
246
+ m_SPTQueue.Resize(maxCheck * 10);
247
+ m_NGQueue.Resize(maxCheck * 30);
248
+ m_Results.Resize(maxCheck / 16);
249
+
250
+ m_iNumOfContinuousNoBetterPropagation = 0;
251
+ //m_iContinuousLimit = maxCheck / 64;
252
+ m_iNumberOfTreeCheckedLeaves = 0;
253
+ m_iNumberOfCheckedLeaves = 0;
254
+ m_iMaxCheck = maxCheck;
255
+ m_relaxedMono = false;
256
+ }
257
+
258
+ void Initialize(va_list& arg)
259
+ {
260
+ int maxCheck = va_arg(arg, int);
261
+ int hashExp = va_arg(arg, int);
262
+ Initialize(maxCheck, hashExp);
263
+ }
264
+
265
+ void Reset(int maxCheck, int resultNum)
266
+ {
267
+ nodeCheckStatus.clear();
268
+ m_SPTQueue.clear(maxCheck * 10);
269
+ m_NGQueue.clear(maxCheck * 30);
270
+ m_Results.clear(max(maxCheck / 16, resultNum));
271
+
272
+ m_iNumOfContinuousNoBetterPropagation = 0;
273
+ //m_iContinuousLimit = maxCheck / 64;
274
+ m_iNumberOfTreeCheckedLeaves = 0;
275
+ m_iNumberOfCheckedLeaves = 0;
276
+ m_iMaxCheck = maxCheck;
277
+ m_relaxedMono = false;
278
+ }
279
+
280
+ void ResetResult(int maxCheck, int resultNum)
281
+ {
282
+ m_Results.clear(max(maxCheck / 16, resultNum));
283
+ m_iNumOfContinuousNoBetterPropagation = 0;
284
+ m_iNumberOfTreeCheckedLeaves = 0;
285
+ m_iNumberOfCheckedLeaves = 0;
286
+ }
287
+
288
+ inline bool CheckAndSet(SizeType idx)
289
+ {
290
+ return nodeCheckStatus.CheckAndSet(idx);
291
+ }
292
+
293
+ inline int HashTableExponent() const
294
+ {
295
+ return nodeCheckStatus.HashTableExponent();
296
+ }
297
+
298
+ static void Reset() {}
299
+
300
+ OptHashPosVector nodeCheckStatus;
301
+
302
+ // counter for dynamic pivoting
303
+ int m_iNumOfContinuousNoBetterPropagation;
304
+ int m_iContinuousLimit;
305
+ int m_iNumberOfTreeCheckedLeaves;
306
+ int m_iNumberOfCheckedLeaves;
307
+ int m_iMaxCheck;
308
+ bool m_relaxedMono;
309
+
310
+ // Prioriy queue used for neighborhood graph
311
+ Heap<NodeDistPair> m_NGQueue;
312
+
313
+ // Priority queue Used for Tree
314
+ Heap<NodeDistPair> m_SPTQueue;
315
+ // Priority queue Used for Tree BFS
316
+ Heap<NodeDistPair> m_currBSPTQueue;
317
+ Heap<NodeDistPair> m_nextBSPTQueue;
318
+
319
+ DistPriorityQueue m_Results;
320
+ };
321
+ }
322
+ }
323
+
324
+ #endif // _SPTAG_COMMON_WORKSPACE_H_
SPANN/AnnService/inc/Core/CommonDataStructure.h ADDED
@@ -0,0 +1,226 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright (c) Microsoft Corporation. All rights reserved.
2
+ // Licensed under the MIT License.
3
+
4
+ #ifndef _SPTAG_COMMONDATASTRUCTURE_H_
5
+ #define _SPTAG_COMMONDATASTRUCTURE_H_
6
+
7
+ #include "inc/Core/Common.h"
8
+
9
+ namespace SPTAG
10
+ {
11
+
12
+ template<typename T>
13
+ class Array
14
+ {
15
+ public:
16
+ Array();
17
+
18
+ Array(T* p_array, std::size_t p_length, bool p_transferOwnership);
19
+
20
+ Array(T* p_array, std::size_t p_length, std::shared_ptr<T> p_dataHolder);
21
+
22
+ Array(Array<T>&& p_right);
23
+
24
+ Array(const Array<T>& p_right);
25
+
26
+ Array<T>& operator= (Array<T>&& p_right);
27
+
28
+ Array<T>& operator= (const Array<T>& p_right);
29
+
30
+ T& operator[] (std::size_t p_index);
31
+
32
+ const T& operator[] (std::size_t p_index) const;
33
+
34
+ ~Array();
35
+
36
+ T* Data() const;
37
+
38
+ std::size_t Length() const;
39
+
40
+ std::shared_ptr<T> DataHolder() const;
41
+
42
+ void Set(T* p_array, std::size_t p_length, bool p_transferOwnership);
43
+
44
+ void Clear();
45
+
46
+ static Array<T> Alloc(std::size_t p_length);
47
+
48
+ const static Array<T> c_empty;
49
+
50
+ private:
51
+ T* m_data;
52
+
53
+ std::size_t m_length;
54
+
55
+ // Notice this is holding an array. Set correct deleter for this.
56
+ std::shared_ptr<T> m_dataHolder;
57
+ };
58
+
59
+ template<typename T>
60
+ const Array<T> Array<T>::c_empty;
61
+
62
+
63
+ template<typename T>
64
+ Array<T>::Array()
65
+ : m_data(nullptr),
66
+ m_length(0)
67
+ {
68
+ }
69
+
70
+ template<typename T>
71
+ Array<T>::Array(T* p_array, std::size_t p_length, bool p_transferOnwership)
72
+
73
+ : m_data(p_array),
74
+ m_length(p_length)
75
+ {
76
+ if (p_transferOnwership)
77
+ {
78
+ m_dataHolder.reset(m_data, std::default_delete<T[]>());
79
+ }
80
+ }
81
+
82
+
83
+ template<typename T>
84
+ Array<T>::Array(T* p_array, std::size_t p_length, std::shared_ptr<T> p_dataHolder)
85
+ : m_data(p_array),
86
+ m_length(p_length),
87
+ m_dataHolder(std::move(p_dataHolder))
88
+ {
89
+ }
90
+
91
+
92
+ template<typename T>
93
+ Array<T>::Array(Array<T>&& p_right)
94
+ : m_data(p_right.m_data),
95
+ m_length(p_right.m_length),
96
+ m_dataHolder(std::move(p_right.m_dataHolder))
97
+ {
98
+ }
99
+
100
+
101
+ template<typename T>
102
+ Array<T>::Array(const Array<T>& p_right)
103
+ : m_data(p_right.m_data),
104
+ m_length(p_right.m_length),
105
+ m_dataHolder(p_right.m_dataHolder)
106
+ {
107
+ }
108
+
109
+
110
+ template<typename T>
111
+ Array<T>&
112
+ Array<T>::operator= (Array<T>&& p_right)
113
+ {
114
+ m_data = p_right.m_data;
115
+ m_length = p_right.m_length;
116
+ m_dataHolder = std::move(p_right.m_dataHolder);
117
+
118
+ return *this;
119
+ }
120
+
121
+
122
+ template<typename T>
123
+ Array<T>&
124
+ Array<T>::operator= (const Array<T>& p_right)
125
+ {
126
+ m_data = p_right.m_data;
127
+ m_length = p_right.m_length;
128
+ m_dataHolder = p_right.m_dataHolder;
129
+
130
+ return *this;
131
+ }
132
+
133
+
134
+ template<typename T>
135
+ T&
136
+ Array<T>::operator[] (std::size_t p_index)
137
+ {
138
+ return m_data[p_index];
139
+ }
140
+
141
+
142
+ template<typename T>
143
+ const T&
144
+ Array<T>::operator[] (std::size_t p_index) const
145
+ {
146
+ return m_data[p_index];
147
+ }
148
+
149
+
150
+ template<typename T>
151
+ Array<T>::~Array()
152
+ {
153
+ }
154
+
155
+
156
+ template<typename T>
157
+ T*
158
+ Array<T>::Data() const
159
+ {
160
+ return m_data;
161
+ }
162
+
163
+
164
+ template<typename T>
165
+ std::size_t
166
+ Array<T>::Length() const
167
+ {
168
+ return m_length;
169
+ }
170
+
171
+
172
+ template<typename T>
173
+ std::shared_ptr<T>
174
+ Array<T>::DataHolder() const
175
+ {
176
+ return m_dataHolder;
177
+ }
178
+
179
+
180
+ template<typename T>
181
+ void
182
+ Array<T>::Set(T* p_array, std::size_t p_length, bool p_transferOwnership)
183
+ {
184
+ m_data = p_array;
185
+ m_length = p_length;
186
+
187
+ if (p_transferOwnership)
188
+ {
189
+ m_dataHolder.reset(m_data, std::default_delete<T[]>());
190
+ }
191
+ }
192
+
193
+
194
+ template<typename T>
195
+ void
196
+ Array<T>::Clear()
197
+ {
198
+ m_data = nullptr;
199
+ m_length = 0;
200
+ m_dataHolder.reset();
201
+ }
202
+
203
+
204
+ template<typename T>
205
+ Array<T>
206
+ Array<T>::Alloc(std::size_t p_length)
207
+ {
208
+ Array<T> arr;
209
+ if (0 == p_length)
210
+ {
211
+ return arr;
212
+ }
213
+
214
+ arr.m_dataHolder.reset(new T[p_length], std::default_delete<T[]>());
215
+
216
+ arr.m_length = p_length;
217
+ arr.m_data = arr.m_dataHolder.get();
218
+ return arr;
219
+ }
220
+
221
+
222
+ typedef Array<std::uint8_t> ByteArray;
223
+
224
+ } // namespace SPTAG
225
+
226
+ #endif // _SPTAG_COMMONDATASTRUCTURE_H_
SPANN/AnnService/inc/Core/DefinitionList.h ADDED
@@ -0,0 +1,142 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright (c) Microsoft Corporation. All rights reserved.
2
+ // Licensed under the MIT License.
3
+
4
+ #ifdef DefineVectorValueType
5
+
6
+ DefineVectorValueType(Int8, std::int8_t)
7
+ DefineVectorValueType(UInt8, std::uint8_t)
8
+ DefineVectorValueType(Int16, std::int16_t)
9
+ DefineVectorValueType(Float, float)
10
+
11
+ #endif // DefineVectorValueType
12
+
13
+ #ifdef DefineVectorValueType2
14
+
15
+ DefineVectorValueType2(Int8, Int8, std::int8_t, std::int8_t)
16
+ DefineVectorValueType2(Int8, UInt8, std::int8_t, std::uint8_t)
17
+ DefineVectorValueType2(Int8, Int16, std::int8_t, std::int16_t)
18
+ DefineVectorValueType2(Int8, Float, std::int8_t, float)
19
+ DefineVectorValueType2(UInt8, Int8, std::uint8_t, std::int8_t)
20
+ DefineVectorValueType2(UInt8, UInt8, std::uint8_t, std::uint8_t)
21
+ DefineVectorValueType2(UInt8, Int16, std::uint8_t, std::int16_t)
22
+ DefineVectorValueType2(UInt8, Float, std::uint8_t, float)
23
+ DefineVectorValueType2(Int16, Int8, std::int16_t, std::int8_t)
24
+ DefineVectorValueType2(Int16, UInt8, std::int16_t, std::uint8_t)
25
+ DefineVectorValueType2(Int16, Int16, std::int16_t, std::int16_t)
26
+ DefineVectorValueType2(Int16, Float, std::int16_t, float)
27
+ DefineVectorValueType2(Float, Int8, float, std::int8_t)
28
+ DefineVectorValueType2(Float, UInt8, float, std::uint8_t)
29
+ DefineVectorValueType2(Float, Int16, float, std::int16_t)
30
+ DefineVectorValueType2(Float, Float, float, float)
31
+
32
+ #endif // DefineVectorValueType2
33
+
34
+ #ifdef DefineDistCalcMethod
35
+
36
+ DefineDistCalcMethod(L2)
37
+ DefineDistCalcMethod(Cosine)
38
+ DefineDistCalcMethod(InnerProduct)
39
+
40
+ #endif // DefineDistCalcMethod
41
+
42
+ #ifdef DefineQuantizerType
43
+
44
+ DefineQuantizerType(None, std::shared_ptr<void>)
45
+ DefineQuantizerType(PQQuantizer, std::shared_ptr<SPTAG::COMMON::PQQuantizer>)
46
+ DefineQuantizerType(OPQQuantizer, std::shared_ptr<SPTAG::COMMON::OPQQuantizer>)
47
+
48
+ #endif // DefineQuantizerType
49
+
50
+
51
+ #ifdef DefineErrorCode
52
+
53
+ // 0x0000 ~ 0x0FFF General Status
54
+ DefineErrorCode(Success, 0x0000)
55
+ DefineErrorCode(Fail, 0x0001)
56
+ DefineErrorCode(FailedOpenFile, 0x0002)
57
+ DefineErrorCode(FailedCreateFile, 0x0003)
58
+ DefineErrorCode(ParamNotFound, 0x0010)
59
+ DefineErrorCode(FailedParseValue, 0x0011)
60
+ DefineErrorCode(MemoryOverFlow, 0x0012)
61
+ DefineErrorCode(LackOfInputs, 0x0013)
62
+ DefineErrorCode(VectorNotFound, 0x0014)
63
+ DefineErrorCode(EmptyIndex, 0x0015)
64
+ DefineErrorCode(EmptyData, 0x0016)
65
+ DefineErrorCode(DimensionSizeMismatch, 0x0017)
66
+ DefineErrorCode(ExternalAbort, 0x0018)
67
+ DefineErrorCode(EmptyDiskIO, 0x0019)
68
+ DefineErrorCode(DiskIOFail, 0x0020)
69
+
70
+ // 0x1000 ~ 0x1FFF Index Build Status
71
+
72
+ // 0x2000 ~ 0x2FFF Index Serve Status
73
+
74
+ // 0x3000 ~ 0x3FFF Helper Function Status
75
+ DefineErrorCode(ReadIni_FailedParseSection, 0x3000)
76
+ DefineErrorCode(ReadIni_FailedParseParam, 0x3001)
77
+ DefineErrorCode(ReadIni_DuplicatedSection, 0x3002)
78
+ DefineErrorCode(ReadIni_DuplicatedParam, 0x3003)
79
+
80
+
81
+ // 0x4000 ~ 0x4FFF Socket Library Status
82
+ DefineErrorCode(Socket_FailedResolveEndPoint, 0x4000)
83
+ DefineErrorCode(Socket_FailedConnectToEndPoint, 0x4001)
84
+
85
+
86
+ #endif // DefineErrorCode
87
+
88
+
89
+
90
+ #ifdef DefineIndexAlgo
91
+
92
+ DefineIndexAlgo(BKT)
93
+ DefineIndexAlgo(KDT)
94
+ DefineIndexAlgo(SPANN)
95
+
96
+ #endif // DefineIndexAlgo
97
+
98
+ // target vectors and queries
99
+ #ifdef DefineVectorFileType
100
+
101
+ // number of vectors(int32_t), dimension(int32_t)
102
+ // 1st vector
103
+ // 2nd vector
104
+ // ..
105
+ DefineVectorFileType(DEFAULT)
106
+ // dimension of 1st vector(int32_t), 1st vector
107
+ // dimension of 2nd vector(int32_t), 2nd vector
108
+ // ...
109
+ DefineVectorFileType(XVEC)
110
+ // vectors that have names and are viewable
111
+ DefineVectorFileType(TXT)
112
+
113
+ #endif // DefineVectorFileType
114
+
115
+ #ifdef DefineTruthFileType
116
+
117
+ // 1st nn id(int32_t), SPACE, 2nd nn id, SPACE, 3rd nn id,...
118
+ // 1st nn id, SPACE, 2nd nn id, SPACE, 3rd nn id,...
119
+ // ...
120
+ DefineTruthFileType(TXT)
121
+ // K of 1st vector(int32_t), 1st nn id(int32_t), SPACE, 2nd nn id, SPACE, 3rd nn id,...
122
+ // K of 2nd vector(int32_t), 1st nn id, SPACE, 2nd nn id, SPACE, 3rd nn id,...
123
+ // ...
124
+ DefineTruthFileType(XVEC)
125
+ // row(int32_t), column(int32_t), data...
126
+ DefineTruthFileType(DEFAULT)
127
+
128
+ #endif // DefineTruthFileType
129
+
130
+ #ifdef DefineNumaStrategy
131
+
132
+ DefineNumaStrategy(LOCAL)
133
+ DefineNumaStrategy(SCATTER)
134
+
135
+ #endif // DefineNumaStrategy
136
+
137
+ #ifdef DefineOrderStrategy
138
+
139
+ DefineOrderStrategy(ASC)
140
+ DefineOrderStrategy(DESC)
141
+
142
+ #endif // DefineOrderStrategy
SPANN/AnnService/inc/Core/MetadataSet.h ADDED
@@ -0,0 +1,136 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright (c) Microsoft Corporation. All rights reserved.
2
+ // Licensed under the MIT License.
3
+
4
+ #ifndef _SPTAG_METADATASET_H_
5
+ #define _SPTAG_METADATASET_H_
6
+
7
+ #include "CommonDataStructure.h"
8
+
9
+ namespace SPTAG
10
+ {
11
+
12
+ class MetadataSet
13
+ {
14
+ public:
15
+ MetadataSet();
16
+
17
+ virtual ~MetadataSet();
18
+
19
+ virtual ByteArray GetMetadata(SizeType p_vectorID) const = 0;
20
+
21
+ virtual ByteArray GetMetadataCopy(SizeType p_vectorID) const = 0;
22
+
23
+ virtual SizeType Count() const = 0;
24
+
25
+ virtual bool Available() const = 0;
26
+
27
+ virtual std::pair<std::uint64_t, std::uint64_t> BufferSize() const = 0;
28
+
29
+ virtual void Add(const ByteArray& data) = 0;
30
+
31
+ virtual ErrorCode SaveMetadata(std::shared_ptr<Helper::DiskIO> p_metaOut, std::shared_ptr<Helper::DiskIO> p_metaIndexOut) = 0;
32
+
33
+ virtual ErrorCode SaveMetadata(const std::string& p_metaFile, const std::string& p_metaindexFile) = 0;
34
+
35
+ virtual void AddBatch(MetadataSet& data);
36
+
37
+ virtual ErrorCode RefineMetadata(std::vector<SizeType>& indices, std::shared_ptr<MetadataSet>& p_newMetadata, std::uint64_t p_blockSize, std::uint64_t p_capacity, std::uint64_t p_metaSize) const;
38
+
39
+ virtual ErrorCode RefineMetadata(std::vector<SizeType>& indices, std::shared_ptr<Helper::DiskIO> p_metaOut, std::shared_ptr<Helper::DiskIO> p_metaIndexOut) const;
40
+
41
+ virtual ErrorCode RefineMetadata(std::vector<SizeType>& indices, const std::string& p_metaFile, const std::string& p_metaindexFile) const;
42
+
43
+ static bool GetMetadataOffsets(const std::uint8_t* p_meta, const std::uint64_t p_metaLength, std::uint64_t* p_offsets, std::uint64_t p_offsetLength, char p_delimiter = '\n');
44
+ };
45
+
46
+
47
+ class FileMetadataSet : public MetadataSet
48
+ {
49
+ public:
50
+ FileMetadataSet(const std::string& p_metaFile, const std::string& p_metaindexFile,
51
+ std::uint64_t p_blockSize = 1024 * 1024, std::uint64_t p_capacity = MaxSize, std::uint64_t p_metaSize = 10);
52
+
53
+ ~FileMetadataSet();
54
+
55
+ ByteArray GetMetadata(SizeType p_vectorID) const;
56
+
57
+ ByteArray GetMetadataCopy(SizeType p_vectorID) const;
58
+
59
+ SizeType Count() const;
60
+
61
+ bool Available() const;
62
+
63
+ std::pair<std::uint64_t, std::uint64_t> BufferSize() const;
64
+
65
+ void Add(const ByteArray& data);
66
+
67
+ ErrorCode SaveMetadata(std::shared_ptr<Helper::DiskIO> p_metaOut, std::shared_ptr<Helper::DiskIO> p_metaIndexOut);
68
+
69
+ ErrorCode SaveMetadata(const std::string& p_metaFile, const std::string& p_metaindexFile);
70
+
71
+ private:
72
+ std::shared_ptr<void> m_lock;
73
+
74
+ std::vector<std::uint64_t> m_offsets;
75
+
76
+ SizeType m_count;
77
+
78
+ std::shared_ptr<Helper::DiskIO> m_fp = nullptr;
79
+
80
+ std::vector<std::uint8_t> m_newdata;
81
+ };
82
+
83
+
84
+ class MemMetadataSet : public MetadataSet
85
+ {
86
+ public:
87
+ MemMetadataSet(std::uint64_t p_blockSize, std::uint64_t p_capacity, std::uint64_t p_metaSize);
88
+
89
+ MemMetadataSet(ByteArray p_metadata, ByteArray p_offsets, SizeType p_count);
90
+
91
+ MemMetadataSet(ByteArray p_metadata, ByteArray p_offsets, SizeType p_count,
92
+ std::uint64_t p_blockSize, std::uint64_t p_capacity, std::uint64_t p_metaSize);
93
+
94
+ MemMetadataSet(const std::string& p_metafile, const std::string& p_metaindexfile,
95
+ std::uint64_t p_blockSize, std::uint64_t p_capacity, std::uint64_t p_metaSize);
96
+
97
+ MemMetadataSet(std::shared_ptr<Helper::DiskIO> p_metain, std::shared_ptr<Helper::DiskIO> p_metaindexin,
98
+ std::uint64_t p_blockSize, std::uint64_t p_capacity, std::uint64_t p_metaSize);
99
+
100
+ ~MemMetadataSet();
101
+
102
+ ByteArray GetMetadata(SizeType p_vectorID) const;
103
+
104
+ ByteArray GetMetadataCopy(SizeType p_vectorID) const;
105
+
106
+ SizeType Count() const;
107
+
108
+ bool Available() const;
109
+
110
+ std::pair<std::uint64_t, std::uint64_t> BufferSize() const;
111
+
112
+ void Add(const ByteArray& data);
113
+
114
+ ErrorCode SaveMetadata(std::shared_ptr<Helper::DiskIO> p_metaOut, std::shared_ptr<Helper::DiskIO> p_metaIndexOut);
115
+
116
+ ErrorCode SaveMetadata(const std::string& p_metaFile, const std::string& p_metaindexFile);
117
+
118
+ private:
119
+ ErrorCode Init(std::shared_ptr<Helper::DiskIO> p_metain, std::shared_ptr<Helper::DiskIO> p_metaindexin,
120
+ std::uint64_t p_blockSize, std::uint64_t p_capacity, std::uint64_t p_metaSize);
121
+
122
+ std::shared_ptr<void> m_lock;
123
+
124
+ std::shared_ptr<void> m_pOffsets;
125
+
126
+ SizeType m_count;
127
+
128
+ ByteArray m_metadataHolder;
129
+
130
+ std::vector<std::uint8_t> m_newdata;
131
+ };
132
+
133
+
134
+ } // namespace SPTAG
135
+
136
+ #endif // _SPTAG_METADATASET_H_
SPANN/AnnService/inc/Core/MultiIndexScan.h ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright (c) Microsoft Corporation. All rights reserved.
2
+ // Licensed under the MIT License.
3
+
4
+ #ifndef _SPTAG_MULTI_INDEX_SCAN_H
5
+ #define _SPTAG_MULTI_INDEX_SCAN_H
6
+
7
+ #include <memory>
8
+
9
+ #include <vector>
10
+ #include <utility>
11
+ #include <unordered_set>
12
+ #include <queue>
13
+ #include <stack>
14
+ #include <chrono>
15
+
16
+ #include "ResultIterator.h"
17
+ #include "VectorIndex.h"
18
+ #include <numeric>
19
+ namespace SPTAG
20
+ {
21
+ class MultiIndexScan
22
+ {
23
+ public:
24
+ MultiIndexScan();
25
+ MultiIndexScan(std::vector<std::shared_ptr<VectorIndex>> vecIndices,
26
+ std::vector<void*> p_targets,
27
+ unsigned int k,
28
+ float (*rankFunction)(std::vector<float>),
29
+ bool useTimer,
30
+ int termCondVal,
31
+ int searchLimit
32
+ );
33
+ ~MultiIndexScan();
34
+ void Init(std::vector<std::shared_ptr<VectorIndex>> vecIndices,
35
+ std::vector<ByteArray> p_targets,
36
+ std::vector<float> weight,
37
+ unsigned int k,
38
+ bool useTimer,
39
+ int termCondVal,
40
+ int searchLimit);
41
+ bool Next(BasicResult& result);
42
+ void Close();
43
+
44
+ private:
45
+ std::vector<std::shared_ptr<ResultIterator>> indexIters;
46
+ std::vector<std::shared_ptr<VectorIndex>> fwdLUTs;
47
+ std::unordered_set<SizeType> seenSet;
48
+ std::vector<SPTAG::ByteArray> p_data_array;
49
+ std::vector<float> weight;
50
+
51
+ unsigned int k;
52
+
53
+
54
+
55
+ bool useTimer;
56
+ unsigned int termCondVal;
57
+ int searchLimit;
58
+ std::chrono::time_point<std::chrono::high_resolution_clock> t_start;
59
+
60
+ float (*func)(std::vector<float>);
61
+
62
+ unsigned int consecutive_drops;
63
+
64
+ bool terminate;
65
+ using pq_item = std::pair<float, SizeType>;
66
+ class pq_item_compare
67
+ {
68
+ public:
69
+ bool operator()(const pq_item& lhs, const pq_item& rhs)
70
+ {
71
+ return lhs.first < rhs.first;
72
+ }
73
+ };
74
+ std::priority_queue<pq_item, std::vector<pq_item>, pq_item_compare> pq;
75
+ std::stack<pq_item> outputStk;
76
+ float WeightedRankFunc(std::vector<float>);
77
+
78
+ };
79
+ } // namespace SPTAG
80
+ #endif
SPANN/AnnService/inc/Core/SearchQuery.h ADDED
@@ -0,0 +1,257 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright (c) Microsoft Corporation. All rights reserved.
2
+ // Licensed under the MIT License.
3
+
4
+ #ifndef _SPTAG_SEARCHQUERY_H_
5
+ #define _SPTAG_SEARCHQUERY_H_
6
+
7
+ #include "SearchResult.h"
8
+
9
+ #include <cstring>
10
+
11
+ namespace SPTAG
12
+ {
13
+
14
+ // Space to save temporary answer, similar with TopKCache
15
+ class QueryResult
16
+ {
17
+ public:
18
+ typedef BasicResult* iterator;
19
+ typedef const BasicResult* const_iterator;
20
+
21
+ QueryResult()
22
+ : m_target(nullptr),
23
+ m_resultNum(0),
24
+ m_withMeta(false),
25
+ m_quantizedTarget(nullptr),
26
+ m_quantizedSize(0)
27
+ {
28
+ }
29
+
30
+ QueryResult(int p_resultNum)
31
+ {
32
+ Init(nullptr, p_resultNum, true);
33
+ }
34
+
35
+ QueryResult(const void* p_target, int p_resultNum, bool p_withMeta)
36
+ {
37
+ Init(p_target, p_resultNum, p_withMeta);
38
+ }
39
+
40
+
41
+ QueryResult(const void* p_target, int p_resultNum, bool p_withMeta, BasicResult* p_results)
42
+ : m_target(p_target),
43
+ m_resultNum(p_resultNum),
44
+ m_withMeta(p_withMeta),
45
+ m_quantizedTarget((void*)p_target),
46
+ m_quantizedSize(0)
47
+ {
48
+ m_results.Set(p_results, p_resultNum, false);
49
+ }
50
+
51
+
52
+ QueryResult(const QueryResult& p_other)
53
+ {
54
+ Init(p_other.m_target, p_other.m_resultNum, p_other.m_withMeta);
55
+ if (m_resultNum > 0)
56
+ {
57
+ std::copy(p_other.m_results.Data(), p_other.m_results.Data() + m_resultNum, m_results.Data());
58
+ }
59
+ if (p_other.m_target != p_other.m_quantizedTarget)
60
+ {
61
+ m_quantizedSize = p_other.m_quantizedSize;
62
+ m_quantizedTarget = ALIGN_ALLOC(m_quantizedSize);
63
+ std::copy(reinterpret_cast<std::uint8_t*>(p_other.m_quantizedTarget), reinterpret_cast<std::uint8_t*>(p_other.m_quantizedTarget) + m_quantizedSize, reinterpret_cast<std::uint8_t*>(m_quantizedTarget));
64
+ }
65
+ }
66
+
67
+
68
+ QueryResult& operator=(const QueryResult& p_other)
69
+ {
70
+ if (m_target != m_quantizedTarget) ALIGN_FREE(m_quantizedTarget);
71
+
72
+ Init(p_other.m_target, p_other.m_resultNum, p_other.m_withMeta);
73
+ if (m_resultNum > 0)
74
+ {
75
+ std::copy(p_other.m_results.Data(), p_other.m_results.Data() + m_resultNum, m_results.Data());
76
+ }
77
+ if (p_other.m_target != p_other.m_quantizedTarget)
78
+ {
79
+ m_quantizedSize = p_other.m_quantizedSize;
80
+ m_quantizedTarget = ALIGN_ALLOC(m_quantizedSize);
81
+ std::copy(reinterpret_cast<std::uint8_t*>(p_other.m_quantizedTarget), reinterpret_cast<std::uint8_t*>(p_other.m_quantizedTarget) + m_quantizedSize, reinterpret_cast<std::uint8_t*>(m_quantizedTarget));
82
+ }
83
+ return *this;
84
+ }
85
+
86
+
87
+ ~QueryResult()
88
+ {
89
+ if (m_target != m_quantizedTarget)
90
+ {
91
+ ALIGN_FREE(m_quantizedTarget);
92
+ }
93
+ }
94
+
95
+
96
+ inline void Init(const void* p_target, int p_resultNum, bool p_withMeta)
97
+ {
98
+ m_target = p_target;
99
+ m_resultNum = p_resultNum;
100
+ m_withMeta = p_withMeta;
101
+ m_quantizedTarget = (void*)p_target;
102
+ m_quantizedSize = 0;
103
+
104
+ m_results = Array<BasicResult>::Alloc(p_resultNum);
105
+ }
106
+
107
+
108
+ inline int GetResultNum() const
109
+ {
110
+ return m_resultNum;
111
+ }
112
+
113
+
114
+ inline void SetResultNum(int p_resultNum)
115
+ {
116
+ m_resultNum = p_resultNum;
117
+ }
118
+
119
+
120
+ inline const void* GetTarget()
121
+ {
122
+ return m_target;
123
+ }
124
+
125
+
126
+ inline const void* GetQuantizedTarget()
127
+ {
128
+ return m_quantizedTarget;
129
+ }
130
+
131
+
132
+ inline void SetTarget(const void* p_target)
133
+ {
134
+ if (m_target != m_quantizedTarget)
135
+ {
136
+ ALIGN_FREE(m_quantizedTarget);
137
+ }
138
+ m_target = p_target;
139
+ m_quantizedTarget = (void*)p_target;
140
+ m_quantizedSize = 0;
141
+ }
142
+
143
+
144
+ inline bool HasQuantizedTarget()
145
+ {
146
+ return m_target != m_quantizedTarget;
147
+ }
148
+
149
+
150
+ inline void CleanQuantizedTarget()
151
+ {
152
+ if (m_target != m_quantizedTarget) {
153
+ ALIGN_FREE(m_quantizedTarget);
154
+ m_quantizedTarget = (void*)m_target;
155
+ }
156
+ }
157
+
158
+
159
+ inline BasicResult* GetResult(int i) const
160
+ {
161
+ return i < m_resultNum ? m_results.Data() + i : nullptr;
162
+ }
163
+
164
+
165
+ inline void SetResult(int p_index, SizeType p_VID, float p_dist)
166
+ {
167
+ if (p_index < m_resultNum)
168
+ {
169
+ m_results[p_index].VID = p_VID;
170
+ m_results[p_index].Dist = p_dist;
171
+ }
172
+ }
173
+
174
+
175
+ inline BasicResult* GetResults() const
176
+ {
177
+ return m_results.Data();
178
+ }
179
+
180
+
181
+ inline bool WithMeta() const
182
+ {
183
+ return m_withMeta;
184
+ }
185
+
186
+
187
+ inline const ByteArray& GetMetadata(int p_index) const
188
+ {
189
+ if (p_index < m_resultNum && m_withMeta)
190
+ {
191
+ return m_results[p_index].Meta;
192
+ }
193
+
194
+ return ByteArray::c_empty;
195
+ }
196
+
197
+
198
+ inline void SetMetadata(int p_index, ByteArray p_metadata)
199
+ {
200
+ if (p_index < m_resultNum && m_withMeta)
201
+ {
202
+ m_results[p_index].Meta = std::move(p_metadata);
203
+ }
204
+ }
205
+
206
+
207
+ inline void Reset()
208
+ {
209
+ for (int i = 0; i < m_resultNum; i++)
210
+ {
211
+ m_results[i].VID = -1;
212
+ m_results[i].Dist = MaxDist;
213
+ m_results[i].Meta.Clear();
214
+ }
215
+ }
216
+
217
+
218
+ iterator begin()
219
+ {
220
+ return m_results.Data();
221
+ }
222
+
223
+
224
+ iterator end()
225
+ {
226
+ return m_results.Data() + m_resultNum;
227
+ }
228
+
229
+
230
+ const_iterator begin() const
231
+ {
232
+ return m_results.Data();
233
+ }
234
+
235
+
236
+ const_iterator end() const
237
+ {
238
+ return m_results.Data() + m_resultNum;
239
+ }
240
+
241
+
242
+ protected:
243
+ const void* m_target;
244
+
245
+ void* m_quantizedTarget;
246
+
247
+ SizeType m_quantizedSize;
248
+
249
+ int m_resultNum;
250
+
251
+ bool m_withMeta;
252
+
253
+ Array<BasicResult> m_results;
254
+ };
255
+ } // namespace SPTAG
256
+
257
+ #endif // _SPTAG_SEARCHQUERY_H_
SPANN/AnnService/inc/Core/SearchResult.h ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright (c) Microsoft Corporation. All rights reserved.
2
+ // Licensed under the MIT License.
3
+
4
+ #ifndef _SPTAG_SEARCHRESULT_H_
5
+ #define _SPTAG_SEARCHRESULT_H_
6
+
7
+ #include "CommonDataStructure.h"
8
+
9
+ namespace SPTAG
10
+ {
11
+ struct NodeDistPair
12
+ {
13
+ SizeType node;
14
+ float distance;
15
+
16
+ NodeDistPair(SizeType _node = -1, float _distance = MaxDist) : node(_node), distance(_distance) {}
17
+
18
+ inline bool operator < (const NodeDistPair& rhs) const
19
+ {
20
+ return distance < rhs.distance;
21
+ }
22
+
23
+ inline bool operator > (const NodeDistPair& rhs) const
24
+ {
25
+ return distance > rhs.distance;
26
+ }
27
+ };
28
+
29
+ struct Edge
30
+ {
31
+ SizeType node;
32
+ float distance;
33
+ SizeType tonode;
34
+ Edge() : node(MaxSize), distance(MaxDist), tonode(MaxSize) {}
35
+ };
36
+
37
+ struct EdgeCompare
38
+ {
39
+ inline bool operator()(const Edge& a, int b) const
40
+ {
41
+ return a.node < b;
42
+ };
43
+
44
+ inline bool operator()(int a, const Edge& b) const
45
+ {
46
+ return a < b.node;
47
+ };
48
+
49
+ inline bool operator()(const Edge& a, const Edge& b) const
50
+ {
51
+ if (a.node == b.node)
52
+ {
53
+ if (a.distance == b.distance)
54
+ {
55
+ return a.tonode < b.tonode;
56
+ }
57
+
58
+ return a.distance < b.distance;
59
+ }
60
+
61
+ return a.node < b.node;
62
+ };
63
+ };
64
+
65
+ struct BasicResult
66
+ {
67
+ SizeType VID;
68
+ float Dist;
69
+ ByteArray Meta;
70
+ bool RelaxedMono;
71
+
72
+ BasicResult() : VID(-1), Dist(MaxDist), RelaxedMono(false) {}
73
+
74
+ BasicResult(SizeType p_vid, float p_dist) : VID(p_vid), Dist(p_dist), RelaxedMono(false) {}
75
+
76
+ BasicResult(SizeType p_vid, float p_dist, ByteArray p_meta) : VID(p_vid), Dist(p_dist), Meta(p_meta), RelaxedMono(false) {}
77
+ BasicResult(SizeType p_vid, float p_dist, ByteArray p_meta, bool p_relaxedMono) : VID(p_vid), Dist(p_dist), Meta(p_meta), RelaxedMono(p_relaxedMono) {}
78
+ };
79
+
80
+ } // namespace SPTAG
81
+
82
+ #endif // _SPTAG_SEARCHRESULT_H_
SPANN/AnnService/inc/Core/VectorSet.h ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright (c) Microsoft Corporation. All rights reserved.
2
+ // Licensed under the MIT License.
3
+
4
+ #ifndef _SPTAG_VECTORSET_H_
5
+ #define _SPTAG_VECTORSET_H_
6
+
7
+ #include "CommonDataStructure.h"
8
+
9
+ namespace SPTAG
10
+ {
11
+
12
+ class VectorSet
13
+ {
14
+ public:
15
+ VectorSet();
16
+
17
+ virtual ~VectorSet();
18
+
19
+ virtual VectorValueType GetValueType() const = 0;
20
+
21
+ virtual void* GetVector(SizeType p_vectorID) const = 0;
22
+
23
+ virtual void* GetData() const = 0;
24
+
25
+ virtual DimensionType Dimension() const = 0;
26
+
27
+ virtual SizeType Count() const = 0;
28
+
29
+ virtual bool Available() const = 0;
30
+
31
+ virtual ErrorCode Save(const std::string& p_vectorFile) const = 0;
32
+
33
+ virtual ErrorCode AppendSave(const std::string& p_vectorFile) const = 0;
34
+
35
+ virtual SizeType PerVectorDataSize() const = 0;
36
+
37
+ virtual void Normalize(int p_threads) = 0;
38
+ };
39
+
40
+
41
+ class BasicVectorSet : public VectorSet
42
+ {
43
+ public:
44
+ BasicVectorSet(const ByteArray& p_bytesArray,
45
+ VectorValueType p_valueType,
46
+ DimensionType p_dimension,
47
+ SizeType p_vectorCount);
48
+
49
+ virtual ~BasicVectorSet();
50
+
51
+ virtual VectorValueType GetValueType() const;
52
+
53
+ virtual void* GetVector(SizeType p_vectorID) const;
54
+
55
+ virtual void* GetData() const;
56
+
57
+ virtual DimensionType Dimension() const;
58
+
59
+ virtual SizeType Count() const;
60
+
61
+ virtual bool Available() const;
62
+
63
+ virtual ErrorCode Save(const std::string& p_vectorFile) const;
64
+
65
+ virtual ErrorCode AppendSave(const std::string& p_vectorFile) const;
66
+
67
+ virtual SizeType PerVectorDataSize() const;
68
+
69
+ virtual void Normalize(int p_threads);
70
+
71
+ private:
72
+ ByteArray m_data;
73
+
74
+ VectorValueType m_valueType;
75
+
76
+ DimensionType m_dimension;
77
+
78
+ SizeType m_vectorCount;
79
+
80
+ size_t m_perVectorDataSize;
81
+ };
82
+
83
+ } // namespace SPTAG
84
+
85
+ #endif // _SPTAG_VECTORSET_H_
SPANN/AnnService/src/Aggregator/AggregatorContext.cpp ADDED
@@ -0,0 +1,117 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright (c) Microsoft Corporation. All rights reserved.
2
+ // Licensed under the MIT License.
3
+
4
+ #include "inc/Aggregator/AggregatorContext.h"
5
+ #include "inc/Helper/SimpleIniReader.h"
6
+
7
+ #include <fstream>
8
+
9
+ using namespace SPTAG;
10
+ using namespace SPTAG::Aggregator;
11
+
12
+ RemoteMachine::RemoteMachine()
13
+ : m_connectionID(Socket::c_invalidConnectionID),
14
+ m_status(RemoteMachineStatus::Disconnected)
15
+ {
16
+ }
17
+
18
+
19
+ AggregatorContext::AggregatorContext(const std::string& p_filePath)
20
+ : m_initialized(false)
21
+ {
22
+ Helper::IniReader iniReader;
23
+ if (ErrorCode::Success != iniReader.LoadIniFile(p_filePath))
24
+ {
25
+ return;
26
+ }
27
+
28
+ m_settings.reset(new AggregatorSettings);
29
+
30
+ m_settings->m_listenAddr = iniReader.GetParameter("Service", "ListenAddr", std::string("0.0.0.0"));
31
+ m_settings->m_listenPort = iniReader.GetParameter("Service", "ListenPort", std::string("8100"));
32
+ m_settings->m_threadNum = iniReader.GetParameter("Service", "ThreadNumber", static_cast<std::uint32_t>(8));
33
+ m_settings->m_socketThreadNum = iniReader.GetParameter("Service", "SocketThreadNumber", static_cast<std::uint32_t>(8));
34
+ m_settings->m_centers = iniReader.GetParameter("Service", "Centers", std::string("centers"));
35
+ m_settings->m_valueType = iniReader.GetParameter("Service", "ValueType", VectorValueType::Float);
36
+ m_settings->m_topK = iniReader.GetParameter("Service", "TopK", static_cast<SizeType>(-1));
37
+ m_settings->m_distMethod = iniReader.GetParameter("Service", "DistCalcMethod", DistCalcMethod::L2);
38
+ const std::string emptyStr;
39
+
40
+ SizeType serverNum = iniReader.GetParameter("Servers", "Number", static_cast<SizeType>(0));
41
+
42
+ for (SizeType i = 0; i < serverNum; ++i)
43
+ {
44
+ std::string sectionName("Server_");
45
+ sectionName += std::to_string(i);
46
+ if (!iniReader.DoesSectionExist(sectionName))
47
+ {
48
+ continue;
49
+ }
50
+
51
+ std::shared_ptr<RemoteMachine> remoteMachine(new RemoteMachine);
52
+
53
+ remoteMachine->m_address = iniReader.GetParameter(sectionName, "Address", emptyStr);
54
+ remoteMachine->m_port = iniReader.GetParameter(sectionName, "Port", emptyStr);
55
+
56
+ if (remoteMachine->m_address.empty() || remoteMachine->m_port.empty())
57
+ {
58
+ continue;
59
+ }
60
+
61
+ m_remoteServers.push_back(std::move(remoteMachine));
62
+ }
63
+
64
+ if (m_settings->m_topK > 0) {
65
+ std::ifstream inputStream(m_settings->m_centers, std::ifstream::binary);
66
+ if (!inputStream.is_open()) {
67
+ SPTAGLIB_LOG(Helper::LogLevel::LL_Error, "Failed to read file %s.\n", m_settings->m_centers.c_str());
68
+ exit(1);
69
+ }
70
+
71
+ SizeType row;
72
+ DimensionType col;
73
+ inputStream.read((char*)&row, sizeof(SizeType));
74
+ inputStream.read((char*)&col, sizeof(DimensionType));
75
+ if (row > serverNum) row = serverNum;
76
+ std::uint64_t totalRecordVectorBytes = ((std::uint64_t)GetValueTypeSize(m_settings->m_valueType)) * row * col;
77
+ ByteArray vectorSet = ByteArray::Alloc(totalRecordVectorBytes);
78
+ char* vecBuf = reinterpret_cast<char*>(vectorSet.Data());
79
+ inputStream.read(vecBuf, totalRecordVectorBytes);
80
+ inputStream.close();
81
+
82
+ m_centers.reset(new BasicVectorSet(vectorSet, m_settings->m_valueType, col, row));
83
+ }
84
+ m_initialized = true;
85
+ }
86
+
87
+
88
+ AggregatorContext::~AggregatorContext()
89
+ {
90
+ }
91
+
92
+
93
+ bool
94
+ AggregatorContext::IsInitialized() const
95
+ {
96
+ return m_initialized;
97
+ }
98
+
99
+
100
+ const std::vector<std::shared_ptr<RemoteMachine>>&
101
+ AggregatorContext::GetRemoteServers() const
102
+ {
103
+ return m_remoteServers;
104
+ }
105
+
106
+
107
+ const std::shared_ptr<AggregatorSettings>&
108
+ AggregatorContext::GetSettings() const
109
+ {
110
+ return m_settings;
111
+ }
112
+
113
+ const std::shared_ptr<VectorSet>&
114
+ AggregatorContext::GetCenters() const
115
+ {
116
+ return m_centers;
117
+ }
SPANN/AnnService/src/Aggregator/AggregatorExecutionContext.cpp ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright (c) Microsoft Corporation. All rights reserved.
2
+ // Licensed under the MIT License.
3
+
4
+ #include "inc/Aggregator/AggregatorExecutionContext.h"
5
+
6
+ using namespace SPTAG;
7
+ using namespace SPTAG::Aggregator;
8
+
9
+ AggregatorExecutionContext::AggregatorExecutionContext(std::size_t p_totalServerNumber,
10
+ Socket::PacketHeader p_requestHeader)
11
+ : m_requestHeader(std::move(p_requestHeader))
12
+ {
13
+ m_results.clear();
14
+ m_results.resize(p_totalServerNumber);
15
+
16
+ m_unfinishedCount = static_cast<std::uint32_t>(p_totalServerNumber);
17
+ }
18
+
19
+
20
+ AggregatorExecutionContext::~AggregatorExecutionContext()
21
+ {
22
+ }
23
+
24
+
25
+ std::size_t
26
+ AggregatorExecutionContext::GetServerNumber() const
27
+ {
28
+ return m_results.size();
29
+ }
30
+
31
+
32
+ AggregatorResult&
33
+ AggregatorExecutionContext::GetResult(std::size_t p_num)
34
+ {
35
+ return m_results[p_num];
36
+ }
37
+
38
+
39
+ const Socket::PacketHeader&
40
+ AggregatorExecutionContext::GetRequestHeader() const
41
+ {
42
+ return m_requestHeader;
43
+ }
44
+
45
+
46
+ bool
47
+ AggregatorExecutionContext::IsCompletedAfterFinsh(std::uint32_t p_finishedCount)
48
+ {
49
+ auto lastCount = m_unfinishedCount.fetch_sub(p_finishedCount);
50
+ return lastCount <= p_finishedCount;
51
+ }
SPANN/AnnService/src/Aggregator/AggregatorService.cpp ADDED
@@ -0,0 +1,413 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright (c) Microsoft Corporation. All rights reserved.
2
+ // Licensed under the MIT License.
3
+
4
+ #include "inc/Aggregator/AggregatorService.h"
5
+ #include "inc/Server/QueryParser.h"
6
+ #include "inc/Core/Common/DistanceUtils.h"
7
+ #include "inc/Helper/Base64Encode.h"
8
+
9
+ using namespace SPTAG;
10
+ using namespace SPTAG::Aggregator;
11
+
12
+ AggregatorService::AggregatorService()
13
+ : m_shutdownSignals(m_ioContext),
14
+ m_pendingConnectServersTimer(m_ioContext)
15
+ {
16
+ }
17
+
18
+
19
+ AggregatorService::~AggregatorService()
20
+ {
21
+ }
22
+
23
+
24
+ bool
25
+ AggregatorService::Initialize()
26
+ {
27
+ std::string configFilePath = "Aggregator.ini";
28
+ m_aggregatorContext.reset(new AggregatorContext(configFilePath));
29
+
30
+ m_initalized = m_aggregatorContext->IsInitialized();
31
+
32
+ return m_initalized;
33
+ }
34
+
35
+
36
+ void
37
+ AggregatorService::Run()
38
+ {
39
+ auto threadNum = max((SPTAG::SizeType)1, GetContext()->GetSettings()->m_threadNum);
40
+ m_threadPool.reset(new boost::asio::thread_pool(threadNum));
41
+
42
+ StartClient();
43
+ StartListen();
44
+ WaitForShutdown();
45
+ }
46
+
47
+
48
+ void
49
+ AggregatorService::StartClient()
50
+ {
51
+ auto context = GetContext();
52
+ Socket::PacketHandlerMapPtr handlerMap(new Socket::PacketHandlerMap);
53
+ handlerMap->emplace(Socket::PacketType::SearchResponse,
54
+ [this](Socket::ConnectionID p_srcID, Socket::Packet p_packet)
55
+ {
56
+ boost::asio::post(*m_threadPool,
57
+ std::bind(&AggregatorService::SearchResponseHanlder,
58
+ this,
59
+ p_srcID,
60
+ std::move(p_packet)));
61
+ });
62
+
63
+
64
+ m_socketClient.reset(new Socket::Client(handlerMap,
65
+ context->GetSettings()->m_socketThreadNum,
66
+ 30));
67
+
68
+ m_socketClient->SetEventOnConnectionClose([this](Socket::ConnectionID p_cid)
69
+ {
70
+ auto context = this->GetContext();
71
+ for (const auto& server : context->GetRemoteServers())
72
+ {
73
+ if (nullptr != server && p_cid == server->m_connectionID)
74
+ {
75
+ server->m_status = RemoteMachineStatus::Disconnected;
76
+ this->AddToPendingServers(server);
77
+ }
78
+ }
79
+ });
80
+
81
+ {
82
+ std::lock_guard<std::mutex> guard(m_pendingConnectServersMutex);
83
+ m_pendingConnectServers = context->GetRemoteServers();
84
+ }
85
+
86
+ ConnectToPendingServers();
87
+ }
88
+
89
+
90
+ void
91
+ AggregatorService::StartListen()
92
+ {
93
+ auto context = GetContext();
94
+ Socket::PacketHandlerMapPtr handlerMap(new Socket::PacketHandlerMap);
95
+ handlerMap->emplace(Socket::PacketType::SearchRequest,
96
+ [this](Socket::ConnectionID p_srcID, Socket::Packet p_packet)
97
+ {
98
+ boost::asio::post(*m_threadPool,
99
+ std::bind(&AggregatorService::SearchRequestHanlder,
100
+ this,
101
+ p_srcID,
102
+ std::move(p_packet)));
103
+ });
104
+
105
+ m_socketServer.reset(new Socket::Server(context->GetSettings()->m_listenAddr,
106
+ context->GetSettings()->m_listenPort,
107
+ handlerMap,
108
+ context->GetSettings()->m_socketThreadNum));
109
+
110
+ SPTAGLIB_LOG(Helper::LogLevel::LL_Info,
111
+ "Start to listen %s:%s ...\n",
112
+ context->GetSettings()->m_listenAddr.c_str(),
113
+ context->GetSettings()->m_listenPort.c_str());
114
+ }
115
+
116
+
117
+ void
118
+ AggregatorService::WaitForShutdown()
119
+ {
120
+ m_shutdownSignals.add(SIGINT);
121
+ m_shutdownSignals.add(SIGTERM);
122
+ #ifdef SIGQUIT
123
+ m_shutdownSignals.add(SIGQUIT);
124
+ #endif
125
+
126
+ m_shutdownSignals.async_wait([this](boost::system::error_code p_ec, int p_signal)
127
+ {
128
+ SPTAGLIB_LOG(Helper::LogLevel::LL_Info, "Received shutdown signals.\n");
129
+ m_pendingConnectServersTimer.cancel();
130
+ });
131
+
132
+ m_ioContext.run();
133
+ SPTAGLIB_LOG(Helper::LogLevel::LL_Info, "Start shutdown procedure.\n");
134
+
135
+ m_socketServer.reset();
136
+ m_threadPool->stop();
137
+ m_threadPool->join();
138
+ }
139
+
140
+
141
+ void
142
+ AggregatorService::ConnectToPendingServers()
143
+ {
144
+ auto context = GetContext();
145
+ std::vector<std::shared_ptr<RemoteMachine>> pendingList;
146
+ pendingList.reserve(context->GetRemoteServers().size());
147
+
148
+ {
149
+ std::lock_guard<std::mutex> guard(m_pendingConnectServersMutex);
150
+ pendingList.swap(m_pendingConnectServers);
151
+ }
152
+
153
+ for (auto& pendingServer : pendingList)
154
+ {
155
+ if (pendingServer->m_status != RemoteMachineStatus::Disconnected)
156
+ {
157
+ continue;
158
+ }
159
+
160
+ pendingServer->m_status = RemoteMachineStatus::Connecting;
161
+ std::shared_ptr<RemoteMachine> server = pendingServer;
162
+ auto runner = [server, this]()
163
+ {
164
+ ErrorCode errCode;
165
+ auto cid = m_socketClient->ConnectToServer(server->m_address, server->m_port, errCode);
166
+ if (Socket::c_invalidConnectionID == cid)
167
+ {
168
+ if (ErrorCode::Socket_FailedResolveEndPoint == errCode)
169
+ {
170
+ SPTAGLIB_LOG(Helper::LogLevel::LL_Error,
171
+ "[Error] Failed to resolve %s %s.\n",
172
+ server->m_address.c_str(),
173
+ server->m_port.c_str());
174
+ }
175
+ else
176
+ {
177
+ this->AddToPendingServers(std::move(server));
178
+ }
179
+ }
180
+ else
181
+ {
182
+ server->m_connectionID = cid;
183
+ server->m_status = RemoteMachineStatus::Connected;
184
+ }
185
+ };
186
+ boost::asio::post(*m_threadPool, std::move(runner));
187
+ }
188
+
189
+ m_pendingConnectServersTimer.expires_from_now(boost::posix_time::seconds(30));
190
+ m_pendingConnectServersTimer.async_wait([this](const boost::system::error_code& p_ec)
191
+ {
192
+ if (boost::asio::error::operation_aborted != p_ec)
193
+ {
194
+ ConnectToPendingServers();
195
+ }
196
+ });
197
+ }
198
+
199
+
200
+ void
201
+ AggregatorService::AddToPendingServers(std::shared_ptr<RemoteMachine> p_remoteServer)
202
+ {
203
+ std::lock_guard<std::mutex> guard(m_pendingConnectServersMutex);
204
+ m_pendingConnectServers.emplace_back(std::move(p_remoteServer));
205
+ }
206
+
207
+
208
+ void
209
+ AggregatorService::SearchRequestHanlder(Socket::ConnectionID p_localConnectionID, Socket::Packet p_packet)
210
+ {
211
+ auto context = GetContext();
212
+ std::vector<Socket::ConnectionID> remoteServers;
213
+ remoteServers.reserve(context->GetRemoteServers().size());
214
+
215
+ if (context->GetSettings()->m_topK > 0 && context->GetRemoteServers().size() == context->GetCenters()->Count()) {
216
+ Socket::RemoteQuery remoteQuery;
217
+ remoteQuery.Read(p_packet.Body());
218
+
219
+ Service::QueryParser queryParser;
220
+ queryParser.Parse(remoteQuery.m_queryString, "|");
221
+ ByteArray vector;
222
+ size_t vectorSize;
223
+ SizeType vectorDimension = 0;
224
+ std::vector<BasicResult> servers;
225
+ switch (context->GetSettings()->m_valueType)
226
+ {
227
+ #define DefineVectorValueType(Name, Type) \
228
+ case VectorValueType::Name: \
229
+ if (!queryParser.GetVectorElements().empty()) { \
230
+ Service::ConvertVectorFromString<Type>(queryParser.GetVectorElements(), vector, vectorDimension); \
231
+ } else if (queryParser.GetVectorBase64() != nullptr && queryParser.GetVectorBase64Length() != 0) { \
232
+ vector = ByteArray::Alloc(Helper::Base64::CapacityForDecode(queryParser.GetVectorBase64Length())); \
233
+ Helper::Base64::Decode(queryParser.GetVectorBase64(), queryParser.GetVectorBase64Length(), vector.Data(), vectorSize); \
234
+ vectorDimension = (SizeType)(vectorSize / GetValueTypeSize(context->GetSettings()->m_valueType)); \
235
+ } \
236
+ for (int i = 0; i < context->GetCenters()->Count(); i++) { \
237
+ servers.push_back(BasicResult(i, COMMON::DistanceUtils::ComputeDistance((Type*)vector.Data(), \
238
+ (Type*)context->GetCenters()->GetVector(i), vectorDimension, context->GetSettings()->m_distMethod))); \
239
+ } \
240
+ break; \
241
+
242
+ #include "inc/Core/DefinitionList.h"
243
+ #undef DefineVectorValueType
244
+
245
+ default:
246
+ break;
247
+ }
248
+ std::sort(servers.begin(), servers.end(), [](const BasicResult& a, const BasicResult& b) { return a.Dist < b.Dist; });
249
+ for (int i = 0; i < context->GetSettings()->m_topK; i++) {
250
+ auto& server = context->GetRemoteServers().at(servers[i].VID);
251
+ if (RemoteMachineStatus::Connected != server->m_status)
252
+ {
253
+ continue;
254
+ }
255
+ remoteServers.push_back(server->m_connectionID);
256
+ }
257
+ }
258
+ else {
259
+ for (const auto& server : context->GetRemoteServers())
260
+ {
261
+ if (RemoteMachineStatus::Connected != server->m_status)
262
+ {
263
+ continue;
264
+ }
265
+
266
+ remoteServers.push_back(server->m_connectionID);
267
+ }
268
+ }
269
+ Socket::PacketHeader requestHeader = p_packet.Header();
270
+ if (Socket::c_invalidConnectionID == requestHeader.m_connectionID)
271
+ {
272
+ requestHeader.m_connectionID = p_localConnectionID;
273
+ }
274
+
275
+ std::shared_ptr<AggregatorExecutionContext> executionContext(
276
+ new AggregatorExecutionContext(remoteServers.size(), requestHeader));
277
+
278
+ for (std::uint32_t i = 0; i < remoteServers.size(); ++i)
279
+ {
280
+ AggregatorCallback callback = [this, executionContext, i](Socket::RemoteSearchResult p_result)
281
+ {
282
+ executionContext->GetResult(i).reset(new Socket::RemoteSearchResult(std::move(p_result)));
283
+ if (executionContext->IsCompletedAfterFinsh(1))
284
+ {
285
+ this->AggregateResults(std::move(executionContext));
286
+ }
287
+ };
288
+
289
+ auto timeoutCallback = [](std::shared_ptr<AggregatorCallback> p_callback)
290
+ {
291
+ if (nullptr != p_callback)
292
+ {
293
+ Socket::RemoteSearchResult result;
294
+ result.m_status = Socket::RemoteSearchResult::ResultStatus::Timeout;
295
+
296
+ (*p_callback)(std::move(result));
297
+ }
298
+ };
299
+
300
+ auto connectCallback = [callback](bool p_connectSucc)
301
+ {
302
+ if (!p_connectSucc)
303
+ {
304
+ Socket::RemoteSearchResult result;
305
+ result.m_status = Socket::RemoteSearchResult::ResultStatus::FailedNetwork;
306
+
307
+ callback(std::move(result));
308
+ }
309
+ };
310
+
311
+ Socket::Packet packet;
312
+ packet.Header().m_packetType = Socket::PacketType::SearchRequest;
313
+ packet.Header().m_processStatus = Socket::PacketProcessStatus::Ok;
314
+ packet.Header().m_bodyLength = p_packet.Header().m_bodyLength;
315
+ packet.Header().m_connectionID = Socket::c_invalidConnectionID;
316
+ packet.Header().m_resourceID = m_aggregatorCallbackManager.Add(std::make_shared<AggregatorCallback>(std::move(callback)),
317
+ context->GetSettings()->m_searchTimeout,
318
+ std::move(timeoutCallback));
319
+
320
+ packet.AllocateBuffer(packet.Header().m_bodyLength);
321
+ packet.Header().WriteBuffer(packet.HeaderBuffer());
322
+ memcpy(packet.Body(), p_packet.Body(), packet.Header().m_bodyLength);
323
+
324
+ m_socketClient->SendPacket(remoteServers[i], std::move(packet), connectCallback);
325
+ }
326
+ }
327
+
328
+
329
+ void
330
+ AggregatorService::SearchResponseHanlder(Socket::ConnectionID p_localConnectionID, Socket::Packet p_packet)
331
+ {
332
+ auto callback = m_aggregatorCallbackManager.GetAndRemove(p_packet.Header().m_resourceID);
333
+ if (nullptr == callback)
334
+ {
335
+ return;
336
+ }
337
+
338
+ if (p_packet.Header().m_processStatus != Socket::PacketProcessStatus::Ok || 0 == p_packet.Header().m_bodyLength)
339
+ {
340
+ Socket::RemoteSearchResult result;
341
+ result.m_status = Socket::RemoteSearchResult::ResultStatus::FailedExecute;
342
+
343
+ (*callback)(std::move(result));
344
+ }
345
+ else
346
+ {
347
+ Socket::RemoteSearchResult result;
348
+ result.Read(p_packet.Body());
349
+ (*callback)(std::move(result));
350
+ }
351
+ }
352
+
353
+
354
+ std::shared_ptr<AggregatorContext>
355
+ AggregatorService::GetContext()
356
+ {
357
+ // Add mutex if necessary.
358
+ return m_aggregatorContext;
359
+ }
360
+
361
+
362
+ void
363
+ AggregatorService::AggregateResults(std::shared_ptr<AggregatorExecutionContext> p_exectionContext)
364
+ {
365
+ if (nullptr == p_exectionContext)
366
+ {
367
+ return;
368
+ }
369
+
370
+ Socket::Packet packet;
371
+ packet.Header().m_packetType = Socket::PacketType::SearchResponse;
372
+ packet.Header().m_processStatus = Socket::PacketProcessStatus::Ok;
373
+ packet.Header().m_resourceID = p_exectionContext->GetRequestHeader().m_resourceID;
374
+
375
+ Socket::RemoteSearchResult remoteResult;
376
+ remoteResult.m_status = Socket::RemoteSearchResult::ResultStatus::Success;
377
+
378
+ std::size_t resultNum = 0;
379
+ for (std::size_t i = 0; i < p_exectionContext->GetServerNumber(); ++i)
380
+ {
381
+ const auto& result = p_exectionContext->GetResult(i);
382
+ if (nullptr == result)
383
+ {
384
+ continue;
385
+ }
386
+
387
+ resultNum += result->m_allIndexResults.size();
388
+ }
389
+
390
+ remoteResult.m_allIndexResults.reserve(resultNum);
391
+ for (std::size_t i = 0; i < p_exectionContext->GetServerNumber(); ++i)
392
+ {
393
+ const auto& result = p_exectionContext->GetResult(i);
394
+ if (nullptr == result)
395
+ {
396
+ continue;
397
+ }
398
+
399
+ for (auto& indexRes : result->m_allIndexResults)
400
+ {
401
+ remoteResult.m_allIndexResults.emplace_back(std::move(indexRes));
402
+ }
403
+ }
404
+
405
+ std::uint32_t cap = static_cast<std::uint32_t>(remoteResult.EstimateBufferSize());
406
+ packet.AllocateBuffer(cap);
407
+ packet.Header().m_bodyLength = static_cast<std::uint32_t>(remoteResult.Write(packet.Body()) - packet.Body());
408
+ packet.Header().WriteBuffer(packet.HeaderBuffer());
409
+
410
+ m_socketServer->SendPacket(p_exectionContext->GetRequestHeader().m_connectionID,
411
+ std::move(packet),
412
+ nullptr);
413
+ }
SPANN/AnnService/src/Aggregator/AggregatorSettings.cpp ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright (c) Microsoft Corporation. All rights reserved.
2
+ // Licensed under the MIT License.
3
+
4
+ #include "inc/Aggregator/AggregatorSettings.h"
5
+
6
+ using namespace SPTAG;
7
+ using namespace SPTAG::Aggregator;
8
+
9
+ AggregatorSettings::AggregatorSettings()
10
+ : m_searchTimeout(100),
11
+ m_threadNum(8),
12
+ m_socketThreadNum(8)
13
+ {
14
+ }
SPANN/AnnService/src/Aggregator/main.cpp ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright (c) Microsoft Corporation. All rights reserved.
2
+ // Licensed under the MIT License.
3
+
4
+ #include "inc/Aggregator/AggregatorService.h"
5
+
6
+ SPTAG::Aggregator::AggregatorService g_service;
7
+
8
+ int main(int argc, char* argv[])
9
+ {
10
+ if (!g_service.Initialize())
11
+ {
12
+ return 1;
13
+ }
14
+
15
+ g_service.Run();
16
+
17
+ return 0;
18
+ }
19
+
SPANN/AnnService/src/Helper/ArgumentsParser.cpp ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright (c) Microsoft Corporation. All rights reserved.
2
+ // Licensed under the MIT License.
3
+
4
+ #include "inc/Helper/ArgumentsParser.h"
5
+
6
+ using namespace SPTAG::Helper;
7
+
8
+
9
+ ArgumentsParser::IArgument::IArgument()
10
+ {
11
+ }
12
+
13
+
14
+ ArgumentsParser::IArgument::~IArgument()
15
+ {
16
+ }
17
+
18
+
19
+ ArgumentsParser::ArgumentsParser()
20
+ {
21
+ }
22
+
23
+
24
+ ArgumentsParser::~ArgumentsParser()
25
+ {
26
+ }
27
+
28
+
29
+ bool
30
+ ArgumentsParser::Parse(int p_argc, char** p_args)
31
+ {
32
+ while (p_argc > 0)
33
+ {
34
+ int last = p_argc;
35
+ for (auto& option : m_arguments)
36
+ {
37
+ if (!option->ParseValue(p_argc, p_args))
38
+ {
39
+ SPTAGLIB_LOG(Helper::LogLevel::LL_Empty, "Failed to parse args around \"%s\"\n", *p_args);
40
+ PrintHelp();
41
+ return false;
42
+ }
43
+ }
44
+
45
+ if (last == p_argc)
46
+ {
47
+ p_argc -= 1;
48
+ p_args += 1;
49
+ }
50
+ }
51
+
52
+ bool isValid = true;
53
+ for (auto& option : m_arguments)
54
+ {
55
+ if (option->IsRequiredButNotSet())
56
+ {
57
+ SPTAGLIB_LOG(Helper::LogLevel::LL_Empty, "Required option not set:\n ");
58
+ option->PrintDescription();
59
+ SPTAGLIB_LOG(Helper::LogLevel::LL_Empty, "\n");
60
+ isValid = false;
61
+ }
62
+ }
63
+
64
+ if (!isValid)
65
+ {
66
+ SPTAGLIB_LOG(Helper::LogLevel::LL_Empty, "\n");
67
+ PrintHelp();
68
+ return false;
69
+ }
70
+
71
+ return true;
72
+ }
73
+
74
+
75
+ void
76
+ ArgumentsParser::PrintHelp()
77
+ {
78
+ SPTAGLIB_LOG(Helper::LogLevel::LL_Empty, "Usage: ");
79
+ for (auto& option : m_arguments)
80
+ {
81
+ SPTAGLIB_LOG(Helper::LogLevel::LL_Empty, "\n ");
82
+ option->PrintDescription();
83
+ }
84
+
85
+ SPTAGLIB_LOG(Helper::LogLevel::LL_Empty, "\n\n");
86
+ }
SPANN/AnnService/src/Helper/AsyncFileReader.cpp ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright (c) Microsoft Corporation. All rights reserved.
2
+ // Licensed under the MIT License.
3
+
4
+ #include "inc/Helper/AsyncFileReader.h"
5
+
6
+ namespace SPTAG {
7
+ namespace Helper {
8
+ #ifndef _MSC_VER
9
+ void SetThreadAffinity(int threadID, std::thread& thread, NumaStrategy socketStrategy, OrderStrategy idStrategy)
10
+ {
11
+ #ifdef NUMA
12
+ int numGroups = numa_num_task_nodes();
13
+ int numCpus = numa_num_task_cpus() / numGroups;
14
+
15
+ int group = threadID / numCpus;
16
+ int cpuid = threadID % numCpus;
17
+ if (socketStrategy == NumaStrategy::SCATTER) {
18
+ group = threadID % numGroups;
19
+ cpuid = (threadID / numGroups) % numCpus;
20
+ }
21
+
22
+ struct bitmask* cpumask = numa_allocate_cpumask();
23
+ if (!numa_node_to_cpus(group, cpumask)) {
24
+ unsigned int nodecpu = 0;
25
+ for (unsigned int i = 0; i < cpumask->size; i++) {
26
+ if (numa_bitmask_isbitset(cpumask, i)) {
27
+ if (cpuid == nodecpu) {
28
+ cpu_set_t cpuset;
29
+ CPU_ZERO(&cpuset);
30
+ CPU_SET(i, &cpuset);
31
+ int rc = pthread_setaffinity_np(thread.native_handle(), sizeof(cpu_set_t), &cpuset);
32
+ if (rc != 0) {
33
+ SPTAGLIB_LOG(Helper::LogLevel::LL_Error, "Error calling pthread_setaffinity_np for thread %d: %d\n", threadID, rc);
34
+ }
35
+ break;
36
+ }
37
+ nodecpu++;
38
+ }
39
+ }
40
+ }
41
+ #else
42
+ cpu_set_t cpuset;
43
+ CPU_ZERO(&cpuset);
44
+ CPU_SET(threadID, &cpuset);
45
+ int rc = pthread_setaffinity_np(thread.native_handle(), sizeof(cpu_set_t), &cpuset);
46
+ if (rc != 0) {
47
+ SPTAGLIB_LOG(Helper::LogLevel::LL_Error, "Error calling pthread_setaffinity_np for thread %d: %d\n", threadID, rc);
48
+ }
49
+ #endif
50
+ }
51
+
52
+ struct timespec AIOTimeout {0, 30000};
53
+ void BatchReadFileAsync(std::vector<std::shared_ptr<Helper::DiskIO>>& handlers, AsyncReadRequest* readRequests, int num)
54
+ {
55
+ std::vector<struct iocb> myiocbs(num);
56
+ std::vector<std::vector<struct iocb*>> iocbs(handlers.size());
57
+ std::vector<int> submitted(handlers.size(), 0);
58
+ std::vector<int> done(handlers.size(), 0);
59
+ int totalToSubmit = 0, channel = 0;
60
+
61
+ memset(myiocbs.data(), 0, num * sizeof(struct iocb));
62
+ for (int i = 0; i < num; i++) {
63
+ AsyncReadRequest* readRequest = &(readRequests[i]);
64
+
65
+ channel = readRequest->m_status & 0xffff;
66
+ int fileid = (readRequest->m_status >> 16);
67
+
68
+ struct iocb* myiocb = &(myiocbs[totalToSubmit++]);
69
+ myiocb->aio_data = reinterpret_cast<uintptr_t>(readRequest);
70
+ myiocb->aio_lio_opcode = IOCB_CMD_PREAD;
71
+ myiocb->aio_fildes = ((AsyncFileIO*)(handlers[fileid].get()))->GetFileHandler();
72
+ myiocb->aio_buf = (std::uint64_t)(readRequest->m_buffer);
73
+ myiocb->aio_nbytes = readRequest->m_readSize;
74
+ myiocb->aio_offset = static_cast<std::int64_t>(readRequest->m_offset);
75
+
76
+ iocbs[fileid].emplace_back(myiocb);
77
+ }
78
+ std::vector<struct io_event> events(totalToSubmit);
79
+ int totalDone = 0, totalSubmitted = 0, totalQueued = 0;
80
+ while (totalDone < totalToSubmit) {
81
+ if (totalSubmitted < totalToSubmit) {
82
+ for (int i = 0; i < handlers.size(); i++) {
83
+ if (submitted[i] < iocbs[i].size()) {
84
+ AsyncFileIO* handler = (AsyncFileIO*)(handlers[i].get());
85
+ int s = syscall(__NR_io_submit, handler->GetIOCP(channel), iocbs[i].size() - submitted[i], iocbs[i].data() + submitted[i]);
86
+ if (s > 0) {
87
+ submitted[i] += s;
88
+ totalSubmitted += s;
89
+ }
90
+ else {
91
+ SPTAGLIB_LOG(Helper::LogLevel::LL_Error, "fid:%d channel %d, to submit:%d, submitted:%s\n", i, channel, iocbs[i].size() - submitted[i], strerror(-s));
92
+ }
93
+ }
94
+ }
95
+ }
96
+
97
+ for (int i = totalQueued; i < totalDone; i++) {
98
+ AsyncReadRequest* req = reinterpret_cast<AsyncReadRequest*>((events[i].data));
99
+ if (nullptr != req)
100
+ {
101
+ req->m_callback(true);
102
+ }
103
+ }
104
+ totalQueued = totalDone;
105
+
106
+ for (int i = 0; i < handlers.size(); i++) {
107
+ if (done[i] < submitted[i]) {
108
+ int wait = submitted[i] - done[i];
109
+ AsyncFileIO* handler = (AsyncFileIO*)(handlers[i].get());
110
+ auto d = syscall(__NR_io_getevents, handler->GetIOCP(channel), wait, wait, events.data() + totalDone, &AIOTimeout);
111
+ done[i] += d;
112
+ totalDone += d;
113
+ }
114
+ }
115
+ }
116
+
117
+ for (int i = totalQueued; i < totalDone; i++) {
118
+ AsyncReadRequest* req = reinterpret_cast<AsyncReadRequest*>((events[i].data));
119
+ if (nullptr != req)
120
+ {
121
+ req->m_callback(true);
122
+ }
123
+ }
124
+ }
125
+ #else
126
+ ULONGLONG GetCpuMasks(WORD group, DWORD numCpus)
127
+ {
128
+ ULONGLONG masks = 0, mask = 1;
129
+ for (DWORD i = 0; i < numCpus; ++i)
130
+ {
131
+ masks |= mask;
132
+ mask <<= 1;
133
+ }
134
+
135
+ return masks;
136
+ }
137
+
138
+ void SetThreadAffinity(int threadID, std::thread& thread, NumaStrategy socketStrategy, OrderStrategy idStrategy)
139
+ {
140
+ WORD numGroups = GetActiveProcessorGroupCount();
141
+ DWORD numCpus = GetActiveProcessorCount(0);
142
+
143
+ GROUP_AFFINITY ga;
144
+ memset(&ga, 0, sizeof(ga));
145
+ PROCESSOR_NUMBER pn;
146
+ memset(&pn, 0, sizeof(pn));
147
+
148
+ WORD group = (WORD)(threadID / numCpus);
149
+ pn.Number = (BYTE)(threadID % numCpus);
150
+ if (socketStrategy == NumaStrategy::SCATTER) {
151
+ group = (WORD)(threadID % numGroups);
152
+ pn.Number = (BYTE)((threadID / numGroups) % numCpus);
153
+ }
154
+
155
+ ga.Group = group;
156
+ ga.Mask = GetCpuMasks(group, numCpus);
157
+ BOOL res = SetThreadGroupAffinity(GetCurrentThread(), &ga, NULL);
158
+ if (!res)
159
+ {
160
+ SPTAGLIB_LOG(Helper::LogLevel::LL_Error, "Failed SetThreadGroupAffinity for group %d and mask %I64x for thread %d.\n", ga.Group, ga.Mask, threadID);
161
+ return;
162
+ }
163
+ pn.Group = group;
164
+ if (idStrategy == OrderStrategy::DESC) {
165
+ pn.Number = (BYTE)(numCpus - 1 - pn.Number);
166
+ }
167
+ res = SetThreadIdealProcessorEx(GetCurrentThread(), &pn, NULL);
168
+ if (!res)
169
+ {
170
+ SPTAGLIB_LOG(Helper::LogLevel::LL_Error, "Unable to set ideal processor for thread %d.\n", threadID);
171
+ return;
172
+ }
173
+
174
+ //SPTAGLIB_LOG(Helper::LogLevel::LL_Info, "numGroup:%d numCPUs:%d threadID:%d group:%d cpuid:%d\n", (int)(numGroups), (int)numCpus, threadID, (int)(group), (int)(pn.Number));
175
+ YieldProcessor();
176
+ }
177
+
178
+ void BatchReadFileAsync(std::vector<std::shared_ptr<Helper::DiskIO>>& handlers, AsyncReadRequest* readRequests, int num)
179
+ {
180
+ if (handlers.size() == 1) {
181
+ handlers[0]->BatchReadFile(readRequests, num);
182
+ }
183
+ else {
184
+ int currFileId = 0, currReqStart = 0;
185
+ for (int i = 0; i < num; i++) {
186
+ AsyncReadRequest* readRequest = &(readRequests[i]);
187
+
188
+ int fileid = (readRequest->m_status >> 16);
189
+ if (fileid != currFileId) {
190
+ handlers[currFileId]->BatchReadFile(readRequests + currReqStart, i - currReqStart);
191
+ currFileId = fileid;
192
+ currReqStart = i;
193
+ }
194
+ }
195
+ if (currReqStart < num) {
196
+ handlers[currFileId]->BatchReadFile(readRequests + currReqStart, num - currReqStart);
197
+ }
198
+ }
199
+ }
200
+ #endif
201
+ }
202
+ }
SPANN/AnnService/src/Helper/Base64Encode.cpp ADDED
@@ -0,0 +1,240 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright (c) Microsoft Corporation. All rights reserved.
2
+ // Licensed under the MIT License.
3
+
4
+ #include "inc/Helper/Base64Encode.h"
5
+
6
+ using namespace SPTAG;
7
+ using namespace SPTAG::Helper;
8
+
9
+ namespace
10
+ {
11
+ namespace Local
12
+ {
13
+ const char c_encTable[] =
14
+ {
15
+ 'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z',
16
+ 'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z',
17
+ '0','1','2','3','4','5','6','7','8','9','+','/'
18
+ };
19
+
20
+
21
+ const std::uint8_t c_decTable[] =
22
+ {
23
+ 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, // 0x00 - 0x0f
24
+ 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, // 0x10 - 0x1f
25
+ 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 62, 64, 64, 64, 63, // 0x20 - 0x2f
26
+ 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 64, 64, 64, 64, 64, 64, // 0x30 - 0x3f
27
+ 64, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, // 0x40 - 0x4f
28
+ 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 64, 64, 64, 64, 64, // 0x50 - 0x5f
29
+ 64, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, // 0x60 - 0x6f
30
+ 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 64, 64, 64, 64, 64, // 0x70 - 0x7f
31
+ 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, // 0x80 - 0x8f
32
+ 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, // 0x90 - 0x9f
33
+ 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, // 0xa0 - 0xaf
34
+ 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, // 0xb0 - 0xbf
35
+ 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, // 0xc0 - 0xcf
36
+ 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, // 0xd0 - 0xdf
37
+ 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, // 0xe0 - 0xef
38
+ 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, // 0xf0 - 0xff
39
+ };
40
+
41
+
42
+ const char c_paddingChar = '=';
43
+ }
44
+ }
45
+
46
+
47
+ bool
48
+ Base64::Encode(const std::uint8_t* p_in, std::size_t p_inLen, char* p_out, std::size_t& p_outLen)
49
+ {
50
+ using namespace Local;
51
+
52
+ p_outLen = 0;
53
+ while (p_inLen >= 3)
54
+ {
55
+ p_out[0] = c_encTable[p_in[0] >> 2];
56
+ p_out[1] = c_encTable[((p_in[0] & 0x03) << 4) | ((p_in[1] & 0xf0) >> 4)];
57
+ p_out[2] = c_encTable[((p_in[1] & 0x0f) << 2) | ((p_in[2] & 0xc0) >> 6)];
58
+ p_out[3] = c_encTable[p_in[2] & 0x3f];
59
+
60
+ p_in += 3;
61
+ p_inLen -= 3;
62
+ p_out += 4;
63
+ p_outLen += 4;
64
+ }
65
+
66
+ switch (p_inLen)
67
+ {
68
+ case 1:
69
+ p_out[0] = c_encTable[p_in[0] >> 2];
70
+ p_out[1] = c_encTable[(p_in[0] & 0x03) << 4];
71
+ p_out[2] = c_paddingChar;
72
+ p_out[3] = c_paddingChar;
73
+
74
+ p_outLen += 4;
75
+ break;
76
+
77
+ case 2:
78
+ p_out[0] = c_encTable[p_in[0] >> 2];
79
+ p_out[1] = c_encTable[((p_in[0] & 0x03) << 4) | ((p_in[1] & 0xf0) >> 4)];
80
+ p_out[2] = c_encTable[(p_in[1] & 0x0f) << 2];
81
+ p_out[3] = c_paddingChar;
82
+
83
+ p_outLen += 4;
84
+ break;
85
+ }
86
+
87
+ return true;
88
+ }
89
+
90
+
91
+ bool
92
+ Base64::Encode(const std::uint8_t* p_in, std::size_t p_inLen, std::ostream& p_out, std::size_t& p_outLen)
93
+ {
94
+ using namespace Local;
95
+
96
+ p_outLen = 0;
97
+ while (p_inLen >= 3)
98
+ {
99
+ p_out << c_encTable[p_in[0] >> 2];
100
+ p_out << c_encTable[((p_in[0] & 0x03) << 4) | ((p_in[1] & 0xf0) >> 4)];
101
+ p_out << c_encTable[((p_in[1] & 0x0f) << 2) | ((p_in[2] & 0xc0) >> 6)];
102
+ p_out << c_encTable[p_in[2] & 0x3f];
103
+
104
+ p_in += 3;
105
+ p_inLen -= 3;
106
+ p_outLen += 4;
107
+ }
108
+
109
+ switch (p_inLen)
110
+ {
111
+ case 1:
112
+ p_out << c_encTable[p_in[0] >> 2];
113
+ p_out << c_encTable[(p_in[0] & 0x03) << 4];
114
+ p_out << c_paddingChar;
115
+ p_out << c_paddingChar;
116
+
117
+ p_outLen += 4;
118
+ break;
119
+
120
+ case 2:
121
+ p_out << c_encTable[p_in[0] >> 2];
122
+ p_out << c_encTable[((p_in[0] & 0x03) << 4) | ((p_in[1] & 0xf0) >> 4)];
123
+ p_out << c_encTable[(p_in[1] & 0x0f) << 2];
124
+ p_out << c_paddingChar;
125
+
126
+ p_outLen += 4;
127
+ break;
128
+
129
+ default:
130
+ break;
131
+ }
132
+
133
+ return true;
134
+ }
135
+
136
+
137
+ bool
138
+ Base64::Decode(const char* p_in, std::size_t p_inLen, std::uint8_t* p_out, std::size_t& p_outLen)
139
+ {
140
+ using namespace Local;
141
+
142
+ // Should always be padding.
143
+ if ((p_inLen & 0x03) != 0)
144
+ {
145
+ return false;
146
+ }
147
+
148
+ std::uint8_t u0 = 0;
149
+ std::uint8_t u1 = 0;
150
+ std::uint8_t u2 = 0;
151
+ std::uint8_t u3 = 0;
152
+
153
+ p_outLen = 0;
154
+ while (p_inLen > 4)
155
+ {
156
+ u0 = c_decTable[static_cast<std::size_t>(p_in[0])];
157
+ u1 = c_decTable[static_cast<std::size_t>(p_in[1])];
158
+ u2 = c_decTable[static_cast<std::size_t>(p_in[2])];
159
+ u3 = c_decTable[static_cast<std::size_t>(p_in[3])];
160
+
161
+ if (u0 > 63 || u1 > 63 || u2 > 63 || u3 > 63)
162
+ {
163
+ return false;
164
+ }
165
+
166
+ p_out[0] = (u0 << 2) | (u1 >> 4);
167
+ p_out[1] = (u1 << 4) | (u2 >> 2);
168
+ p_out[2] = (u2 << 6) | u3;
169
+
170
+ p_inLen -= 4;
171
+ p_in += 4;
172
+ p_out += 3;
173
+ p_outLen += 3;
174
+ }
175
+
176
+ u0 = c_decTable[static_cast<std::size_t>(p_in[0])];
177
+ u1 = c_decTable[static_cast<std::size_t>(p_in[1])];
178
+ u2 = c_decTable[static_cast<std::size_t>(p_in[2])];
179
+ u3 = c_decTable[static_cast<std::size_t>(p_in[3])];
180
+
181
+ if (u0 > 63 || u1 > 63 || (c_paddingChar == p_in[2] && c_paddingChar != p_in[3]))
182
+ {
183
+ return false;
184
+ }
185
+
186
+ if (u2 > 63 && c_paddingChar != p_in[2])
187
+ {
188
+ return false;
189
+ }
190
+
191
+ if (u3 > 63 && c_paddingChar != p_in[3])
192
+ {
193
+ return false;
194
+ }
195
+
196
+
197
+ p_out[0] = (u0 << 2) | (u1 >> 4);
198
+ ++p_outLen;
199
+ if (c_paddingChar == p_in[2])
200
+ {
201
+ if ((u1 & 0x0F) != 0)
202
+ {
203
+ return false;
204
+ }
205
+ }
206
+ else
207
+ {
208
+ p_out[1] = (u1 << 4) | (u2 >> 2);
209
+ ++p_outLen;
210
+ if (c_paddingChar == p_in[3])
211
+ {
212
+ if ((u3 & 0x03) != 0)
213
+ {
214
+ return false;
215
+ }
216
+ }
217
+ else
218
+ {
219
+ p_out[2] = (u2 << 6) | u3;
220
+ ++p_outLen;
221
+ }
222
+ }
223
+
224
+ return true;
225
+ }
226
+
227
+
228
+ std::size_t
229
+ Base64::CapacityForEncode(std::size_t p_inLen)
230
+ {
231
+ return ((p_inLen + 2) / 3) * 4;
232
+ }
233
+
234
+
235
+ std::size_t
236
+ Base64::CapacityForDecode(std::size_t p_inLen)
237
+ {
238
+ return (p_inLen / 4) * 3 + ((p_inLen % 4) * 2) / 3;
239
+ }
240
+
SPANN/AnnService/src/Helper/CommonHelper.cpp ADDED
@@ -0,0 +1,157 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright (c) Microsoft Corporation. All rights reserved.
2
+ // Licensed under the MIT License.
3
+
4
+ #include "inc/Helper/CommonHelper.h"
5
+
6
+ #include <cctype>
7
+ #include <functional>
8
+
9
+ using namespace SPTAG;
10
+ using namespace SPTAG::Helper;
11
+
12
+ void
13
+ StrUtils::ToLowerInPlace(std::string& p_str)
14
+ {
15
+ for (char& ch : p_str)
16
+ {
17
+ if (std::isupper(ch))
18
+ {
19
+ ch = ch | 0x20;
20
+ }
21
+ }
22
+ }
23
+
24
+
25
+ std::vector<std::string>
26
+ StrUtils::SplitString(const std::string& p_str, const std::string& p_separator)
27
+ {
28
+ std::vector<std::string> ret;
29
+
30
+ std::size_t begin = p_str.find_first_not_of(p_separator);
31
+ while (std::string::npos != begin)
32
+ {
33
+ std::size_t end = p_str.find_first_of(p_separator, begin);
34
+ if (std::string::npos == end)
35
+ {
36
+ ret.emplace_back(p_str.substr(begin, p_str.size() - begin));
37
+ break;
38
+ }
39
+ else
40
+ {
41
+ ret.emplace_back(p_str.substr(begin, end - begin));
42
+ }
43
+
44
+ begin = p_str.find_first_not_of(p_separator, end);
45
+ }
46
+
47
+ return ret;
48
+ }
49
+
50
+
51
+ std::pair<const char*, const char*>
52
+ StrUtils::FindTrimmedSegment(const char* p_begin,
53
+ const char* p_end,
54
+ const std::function<bool(char)>& p_isSkippedChar)
55
+ {
56
+ while (p_begin < p_end)
57
+ {
58
+ if (!p_isSkippedChar(*p_begin))
59
+ {
60
+ break;
61
+ }
62
+
63
+ ++p_begin;
64
+ }
65
+
66
+ while (p_end > p_begin)
67
+ {
68
+ if (!p_isSkippedChar(*(p_end - 1)))
69
+ {
70
+ break;
71
+ }
72
+
73
+ --p_end;
74
+ }
75
+
76
+ return std::make_pair(p_begin, p_end);
77
+ }
78
+
79
+
80
+ bool
81
+ StrUtils::StartsWith(const char* p_str, const char* p_prefix)
82
+ {
83
+ if (nullptr == p_prefix)
84
+ {
85
+ return true;
86
+ }
87
+
88
+ if (nullptr == p_str)
89
+ {
90
+ return false;
91
+ }
92
+
93
+ while ('\0' != (*p_prefix) && '\0' != (*p_str))
94
+ {
95
+ if (*p_prefix != *p_str)
96
+ {
97
+ return false;
98
+ }
99
+ ++p_prefix;
100
+ ++p_str;
101
+ }
102
+
103
+ return '\0' == *p_prefix;
104
+ }
105
+
106
+
107
+ bool
108
+ StrUtils::StrEqualIgnoreCase(const char* p_left, const char* p_right)
109
+ {
110
+ if (p_left == p_right)
111
+ {
112
+ return true;
113
+ }
114
+
115
+ if (p_left == nullptr || p_right == nullptr)
116
+ {
117
+ return false;
118
+ }
119
+
120
+ auto tryConv = [](char p_ch) -> char
121
+ {
122
+ if ('a' <= p_ch && p_ch <= 'z')
123
+ {
124
+ return p_ch - 32;
125
+ }
126
+
127
+ return p_ch;
128
+ };
129
+
130
+ while (*p_left != '\0' && *p_right != '\0')
131
+ {
132
+ if (tryConv(*p_left) != tryConv(*p_right))
133
+ {
134
+ return false;
135
+ }
136
+
137
+ ++p_left;
138
+ ++p_right;
139
+ }
140
+
141
+ return *p_left == *p_right;
142
+ }
143
+
144
+
145
+ std::string
146
+ StrUtils::ReplaceAll(const std::string& orig, const std::string& from, const std::string& to)
147
+ {
148
+ std::string ret = orig;
149
+ if (from.empty()) return ret;
150
+
151
+ size_t pos = 0;
152
+ while ((pos = ret.find(from, pos)) != std::string::npos) {
153
+ ret.replace(pos, from.length(), to);
154
+ pos += to.length();
155
+ }
156
+ return ret;
157
+ }
SPANN/AnnService/src/Helper/DynamicNeighbors.cpp ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include "inc/Helper/DynamicNeighbors.h"
2
+ #include "inc/Core/Common.h"
3
+
4
+ using namespace SPTAG::Helper;
5
+
6
+ DynamicNeighbors::DynamicNeighbors(const int* p_data, const int p_length)
7
+ : c_data(p_data),
8
+ c_length(p_length)
9
+ {
10
+ }
11
+
12
+
13
+ DynamicNeighbors:: ~DynamicNeighbors()
14
+ {
15
+ }
16
+
17
+
18
+ int
19
+ DynamicNeighbors::operator[](const int p_id) const
20
+ {
21
+ if (p_id < c_length && p_id >= 0)
22
+ {
23
+ return c_data[p_id];
24
+ }
25
+
26
+ return -1;
27
+ }
28
+
29
+
30
+ int
31
+ DynamicNeighbors::Size() const
32
+ {
33
+ return c_length;
34
+ }
35
+
36
+
37
+ DynamicNeighborsSet::DynamicNeighborsSet(const char* p_filePath)
38
+ {
39
+ auto fp = f_createIO();
40
+ if (fp == nullptr || !fp->Initialize(p_filePath, std::ios::binary | std::ios::in)) {
41
+ SPTAGLIB_LOG(Helper::LogLevel::LL_Error, "Failed open graph file: %s\n", p_filePath);
42
+ throw std::runtime_error("Opening graph file failed");
43
+ }
44
+
45
+ if (fp->ReadBinary(sizeof(m_vectorCount), (char*)&m_vectorCount) != sizeof(m_vectorCount)) {
46
+ SPTAGLIB_LOG(Helper::LogLevel::LL_Error, "Failed to read DynamicNeighborsSet!\n");
47
+ throw std::runtime_error("reading DynamicNeighborsSet failed");
48
+ }
49
+
50
+ m_neighborOffset.reset(new int[m_vectorCount + 1]);
51
+ m_neighborOffset[0] = 0;
52
+ if (fp->ReadBinary(m_vectorCount * sizeof(int), (char*)(m_neighborOffset.get() + 1)) != m_vectorCount * sizeof(int)) {
53
+ SPTAGLIB_LOG(Helper::LogLevel::LL_Error, "Failed to read DynamicNeighborsSet!\n");
54
+ throw std::runtime_error("reading DynamicNeighborsSet failed");
55
+ }
56
+
57
+ size_t graphSize = static_cast<size_t>(m_neighborOffset[m_vectorCount]);
58
+ SPTAGLIB_LOG(Helper::LogLevel::LL_Error, "Vector count: %d, Graph size: %zu\n", m_vectorCount, graphSize);
59
+
60
+ m_data.reset(new int[graphSize]);
61
+ auto readSize = fp->ReadBinary(graphSize * sizeof(int), (char*)(m_data.get()));
62
+ if (readSize != graphSize * sizeof(int)) {
63
+ SPTAGLIB_LOG(Helper::LogLevel::LL_Error,
64
+ "Failed read graph: size not match, expected %zu, actually %zu\n",
65
+ static_cast<size_t>(graphSize * sizeof(int)),
66
+ static_cast<size_t>(readSize));
67
+ throw std::runtime_error("Graph size doesn't match expected");
68
+ }
69
+ }
70
+
71
+
72
+ DynamicNeighborsSet::~DynamicNeighborsSet()
73
+ {
74
+ }
75
+
76
+
77
+ DynamicNeighbors DynamicNeighborsSet::operator[](const int p_id) const
78
+ {
79
+ if (p_id >= m_vectorCount)
80
+ {
81
+ return DynamicNeighbors(nullptr, 0);
82
+ }
83
+
84
+ return DynamicNeighbors(m_data.get() + static_cast<uint64_t>(m_neighborOffset[p_id]),
85
+ m_neighborOffset[p_id + 1] - m_neighborOffset[p_id]);
86
+ }
SPANN/AnnService/src/Helper/SimpleIniReader.cpp ADDED
@@ -0,0 +1,235 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright (c) Microsoft Corporation. All rights reserved.
2
+ // Licensed under the MIT License.
3
+
4
+ #include "inc/Helper/SimpleIniReader.h"
5
+ #include "inc/Helper/CommonHelper.h"
6
+
7
+ #include <cctype>
8
+ #include <functional>
9
+
10
+ using namespace SPTAG;
11
+ using namespace SPTAG::Helper;
12
+
13
+ const IniReader::ParameterValueMap IniReader::c_emptyParameters;
14
+
15
+
16
+ IniReader::IniReader()
17
+ {
18
+ }
19
+
20
+
21
+ IniReader::~IniReader()
22
+ {
23
+ }
24
+
25
+
26
+ ErrorCode IniReader::LoadIni(std::shared_ptr<Helper::DiskIO> p_input)
27
+ {
28
+ std::uint64_t c_bufferSize = 1 << 16;
29
+
30
+ std::unique_ptr<char[]> line(new char[c_bufferSize]);
31
+
32
+ std::string currSection;
33
+ std::shared_ptr<ParameterValueMap> currParamMap(new ParameterValueMap);
34
+
35
+ if (m_parameters.count(currSection) == 0)
36
+ {
37
+ m_parameters.emplace(currSection, currParamMap);
38
+ }
39
+
40
+ auto isSpace = [](char p_ch) -> bool
41
+ {
42
+ return std::isspace(p_ch) != 0;
43
+ };
44
+
45
+ while (true)
46
+ {
47
+ if (!p_input->ReadString(c_bufferSize, line)) break;
48
+
49
+ std::uint64_t len = 0;
50
+ while (len < c_bufferSize && line[len] != '\0')
51
+ {
52
+ ++len;
53
+ }
54
+
55
+ auto nonSpaceSeg = StrUtils::FindTrimmedSegment(line.get(), line.get() + len, isSpace);
56
+
57
+ if (nonSpaceSeg.second <= nonSpaceSeg.first)
58
+ {
59
+ // Blank line.
60
+ continue;
61
+ }
62
+
63
+ if (';' == *nonSpaceSeg.first)
64
+ {
65
+ // Comments.
66
+ continue;
67
+ }
68
+ else if ('[' == *nonSpaceSeg.first)
69
+ {
70
+ // Parse Section
71
+ if (']' != *(nonSpaceSeg.second - 1))
72
+ {
73
+ return ErrorCode::ReadIni_FailedParseSection;
74
+ }
75
+
76
+ auto sectionSeg = StrUtils::FindTrimmedSegment(nonSpaceSeg.first + 1, nonSpaceSeg.second - 1, isSpace);
77
+
78
+ if (sectionSeg.second <= sectionSeg.first)
79
+ {
80
+ // Empty section name.
81
+ return ErrorCode::ReadIni_FailedParseSection;
82
+ }
83
+
84
+ currSection.assign(sectionSeg.first, sectionSeg.second);
85
+ StrUtils::ToLowerInPlace(currSection);
86
+
87
+ if (m_parameters.count(currSection) == 0)
88
+ {
89
+ currParamMap.reset(new ParameterValueMap);
90
+ m_parameters.emplace(currSection, currParamMap);
91
+ }
92
+ else
93
+ {
94
+ return ErrorCode::ReadIni_DuplicatedSection;
95
+ }
96
+ }
97
+ else
98
+ {
99
+ // Parameter Value Pair.
100
+ const char* equalSignLoc = nonSpaceSeg.first;
101
+ while (equalSignLoc < nonSpaceSeg.second && '=' != *equalSignLoc)
102
+ {
103
+ ++equalSignLoc;
104
+ }
105
+
106
+ if (equalSignLoc >= nonSpaceSeg.second)
107
+ {
108
+ return ErrorCode::ReadIni_FailedParseParam;
109
+ }
110
+
111
+ auto paramSeg = StrUtils::FindTrimmedSegment(nonSpaceSeg.first, equalSignLoc, isSpace);
112
+
113
+ if (paramSeg.second <= paramSeg.first)
114
+ {
115
+ // Empty parameter name.
116
+ return ErrorCode::ReadIni_FailedParseParam;
117
+ }
118
+
119
+ std::string paramName(paramSeg.first, paramSeg.second);
120
+ StrUtils::ToLowerInPlace(paramName);
121
+
122
+ if (currParamMap->count(paramName) == 0)
123
+ {
124
+ currParamMap->emplace(std::move(paramName), std::string(equalSignLoc + 1, nonSpaceSeg.second));
125
+ }
126
+ else
127
+ {
128
+ return ErrorCode::ReadIni_DuplicatedParam;
129
+ }
130
+ }
131
+ }
132
+ return ErrorCode::Success;
133
+ }
134
+
135
+
136
+ ErrorCode
137
+ IniReader::LoadIniFile(const std::string& p_iniFilePath)
138
+ {
139
+ auto ptr = f_createIO();
140
+ if (ptr == nullptr || !ptr->Initialize(p_iniFilePath.c_str(), std::ios::in)) return ErrorCode::FailedOpenFile;
141
+ return LoadIni(ptr);
142
+ }
143
+
144
+
145
+ bool
146
+ IniReader::DoesSectionExist(const std::string& p_section) const
147
+ {
148
+ std::string section(p_section);
149
+ StrUtils::ToLowerInPlace(section);
150
+ return m_parameters.count(section) != 0;
151
+ }
152
+
153
+
154
+ bool
155
+ IniReader::DoesParameterExist(const std::string& p_section, const std::string& p_param) const
156
+ {
157
+ std::string name(p_section);
158
+ StrUtils::ToLowerInPlace(name);
159
+ auto iter = m_parameters.find(name);
160
+ if (iter == m_parameters.cend())
161
+ {
162
+ return false;
163
+ }
164
+
165
+ const auto& paramMap = iter->second;
166
+ if (paramMap == nullptr)
167
+ {
168
+ return false;
169
+ }
170
+
171
+ name = p_param;
172
+ StrUtils::ToLowerInPlace(name);
173
+ return paramMap->count(name) != 0;
174
+ }
175
+
176
+
177
+ bool
178
+ IniReader::GetRawValue(const std::string& p_section, const std::string& p_param, std::string& p_value) const
179
+ {
180
+ std::string name(p_section);
181
+ StrUtils::ToLowerInPlace(name);
182
+ auto sectionIter = m_parameters.find(name);
183
+ if (sectionIter == m_parameters.cend())
184
+ {
185
+ return false;
186
+ }
187
+
188
+ const auto& paramMap = sectionIter->second;
189
+ if (paramMap == nullptr)
190
+ {
191
+ return false;
192
+ }
193
+
194
+ name = p_param;
195
+ StrUtils::ToLowerInPlace(name);
196
+ auto paramIter = paramMap->find(name);
197
+ if (paramIter == paramMap->cend())
198
+ {
199
+ return false;
200
+ }
201
+
202
+ p_value = paramIter->second;
203
+ return true;
204
+ }
205
+
206
+
207
+ const IniReader::ParameterValueMap&
208
+ IniReader::GetParameters(const std::string& p_section) const
209
+ {
210
+ std::string name(p_section);
211
+ StrUtils::ToLowerInPlace(name);
212
+ auto sectionIter = m_parameters.find(name);
213
+ if (sectionIter == m_parameters.cend() || nullptr == sectionIter->second)
214
+ {
215
+ return c_emptyParameters;
216
+ }
217
+
218
+ return *(sectionIter->second);
219
+ }
220
+
221
+ void
222
+ IniReader::SetParameter(const std::string& p_section, const std::string& p_param, const std::string& p_val)
223
+ {
224
+ std::string name(p_section);
225
+ StrUtils::ToLowerInPlace(name);
226
+ auto sectionIter = m_parameters.find(name);
227
+ if (sectionIter == m_parameters.cend() || sectionIter->second == nullptr)
228
+ {
229
+ m_parameters[name] = std::shared_ptr<ParameterValueMap>(new ParameterValueMap);
230
+ }
231
+
232
+ std::string param(p_param);
233
+ StrUtils::ToLowerInPlace(param);
234
+ (*m_parameters[name])[param] = p_val;
235
+ }
SPANN/AnnService/src/Helper/VectorSetReader.cpp ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright (c) Microsoft Corporation. All rights reserved.
2
+ // Licensed under the MIT License.
3
+
4
+ #include "inc/Helper/VectorSetReader.h"
5
+ #include "inc/Helper/VectorSetReaders/DefaultReader.h"
6
+ #include "inc/Helper/VectorSetReaders/TxtReader.h"
7
+ #include "inc/Helper/VectorSetReaders/XvecReader.h"
8
+
9
+ using namespace SPTAG;
10
+ using namespace SPTAG::Helper;
11
+
12
+
13
+ ReaderOptions::ReaderOptions(VectorValueType p_valueType, DimensionType p_dimension, VectorFileType p_fileType, std::string p_vectorDelimiter, std::uint32_t p_threadNum, bool p_normalized)
14
+ : m_inputValueType(p_valueType), m_dimension(p_dimension), m_inputFileType(p_fileType), m_vectorDelimiter(p_vectorDelimiter), m_threadNum(p_threadNum), m_normalized(p_normalized)
15
+ {
16
+ AddOptionalOption(m_threadNum, "-t", "--thread", "Thread Number.");
17
+ AddOptionalOption(m_vectorDelimiter, "-dl", "--delimiter", "Vector delimiter.");
18
+ AddOptionalOption(m_normalized, "-norm", "--normalized", "Vector is normalized.");
19
+ AddRequiredOption(m_dimension, "-d", "--dimension", "Dimension of vector.");
20
+ AddRequiredOption(m_inputValueType, "-v", "--vectortype", "Input vector data type. Default is float.");
21
+ AddRequiredOption(m_inputFileType, "-f", "--filetype", "Input file type (DEFAULT, TXT, XVEC). Default is DEFAULT.");
22
+ }
23
+
24
+
25
+ ReaderOptions::~ReaderOptions()
26
+ {
27
+ }
28
+
29
+
30
+ VectorSetReader::VectorSetReader(std::shared_ptr<ReaderOptions> p_options)
31
+ : m_options(p_options)
32
+ {
33
+ }
34
+
35
+
36
+ VectorSetReader:: ~VectorSetReader()
37
+ {
38
+ }
39
+
40
+
41
+ std::shared_ptr<VectorSetReader>
42
+ VectorSetReader::CreateInstance(std::shared_ptr<ReaderOptions> p_options)
43
+ {
44
+ if (p_options->m_inputFileType == VectorFileType::DEFAULT) {
45
+ return std::make_shared<DefaultVectorReader>(p_options);
46
+ }
47
+ else if (p_options->m_inputFileType == VectorFileType::TXT) {
48
+ return std::make_shared<TxtVectorReader>(p_options);
49
+ }
50
+ else if (p_options->m_inputFileType == VectorFileType::XVEC) {
51
+ return std::make_shared<XvecVectorReader>(p_options);
52
+ }
53
+ return nullptr;
54
+ }
55
+
56
+
SPANN/AnnService/src/Helper/VectorSetReaders/DefaultReader.cpp ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright (c) Microsoft Corporation. All rights reserved.
2
+ // Licensed under the MIT License.
3
+
4
+ #include "inc/Helper/VectorSetReaders/DefaultReader.h"
5
+ #include "inc/Helper/CommonHelper.h"
6
+
7
+ using namespace SPTAG;
8
+ using namespace SPTAG::Helper;
9
+
10
+ DefaultVectorReader::DefaultVectorReader(std::shared_ptr<ReaderOptions> p_options)
11
+ : VectorSetReader(p_options)
12
+ {
13
+ m_vectorOutput = "";
14
+ m_metadataConentOutput = "";
15
+ m_metadataIndexOutput = "";
16
+ }
17
+
18
+
19
+ DefaultVectorReader::~DefaultVectorReader()
20
+ {
21
+ }
22
+
23
+
24
+ ErrorCode
25
+ DefaultVectorReader::LoadFile(const std::string& p_filePaths)
26
+ {
27
+ const auto& files = SPTAG::Helper::StrUtils::SplitString(p_filePaths, ",");
28
+ m_vectorOutput = files[0];
29
+ if (files.size() >= 3) {
30
+ m_metadataConentOutput = files[1];
31
+ m_metadataIndexOutput = files[2];
32
+ }
33
+ return ErrorCode::Success;
34
+ }
35
+
36
+
37
+ std::shared_ptr<VectorSet>
38
+ DefaultVectorReader::GetVectorSet(SizeType start, SizeType end) const
39
+ {
40
+ auto ptr = f_createIO();
41
+ if (ptr == nullptr || !ptr->Initialize(m_vectorOutput.c_str(), std::ios::binary | std::ios::in)) {
42
+ SPTAGLIB_LOG(Helper::LogLevel::LL_Error, "Failed to read file %s.\n", m_vectorOutput.c_str());
43
+ throw std::runtime_error("Failed read file");
44
+ }
45
+
46
+ SizeType row;
47
+ DimensionType col;
48
+ if (ptr->ReadBinary(sizeof(SizeType), (char*)&row) != sizeof(SizeType)) {
49
+ SPTAGLIB_LOG(Helper::LogLevel::LL_Error, "Failed to read VectorSet!\n");
50
+ throw std::runtime_error("Failed read file");
51
+ }
52
+ if (ptr->ReadBinary(sizeof(DimensionType), (char*)&col) != sizeof(DimensionType)) {
53
+ SPTAGLIB_LOG(Helper::LogLevel::LL_Error, "Failed to read VectorSet!\n");
54
+ throw std::runtime_error("Failed read file");
55
+ }
56
+
57
+ if (start > row) start = row;
58
+ if (end < 0 || end > row) end = row;
59
+ std::uint64_t totalRecordVectorBytes = ((std::uint64_t)GetValueTypeSize(m_options->m_inputValueType)) * (end - start) * col;
60
+ ByteArray vectorSet;
61
+ if (totalRecordVectorBytes > 0) {
62
+ vectorSet = ByteArray::Alloc(totalRecordVectorBytes);
63
+ char* vecBuf = reinterpret_cast<char*>(vectorSet.Data());
64
+ std::uint64_t offset = ((std::uint64_t)GetValueTypeSize(m_options->m_inputValueType)) * start * col + sizeof(SizeType) + sizeof(DimensionType);
65
+ if (ptr->ReadBinary(totalRecordVectorBytes, vecBuf, offset) != totalRecordVectorBytes) {
66
+ SPTAGLIB_LOG(Helper::LogLevel::LL_Error, "Failed to read VectorSet!\n");
67
+ throw std::runtime_error("Failed read file");
68
+ }
69
+ }
70
+
71
+ SPTAGLIB_LOG(Helper::LogLevel::LL_Info, "Load Vector(%d,%d)\n", end - start, col);
72
+ return std::make_shared<BasicVectorSet>(vectorSet,
73
+ m_options->m_inputValueType,
74
+ col,
75
+ end - start);
76
+ }
77
+
78
+
79
+ std::shared_ptr<MetadataSet>
80
+ DefaultVectorReader::GetMetadataSet() const
81
+ {
82
+ if (fileexists(m_metadataIndexOutput.c_str()) && fileexists(m_metadataConentOutput.c_str()))
83
+ return std::shared_ptr<MetadataSet>(new FileMetadataSet(m_metadataConentOutput, m_metadataIndexOutput));
84
+ return nullptr;
85
+ }
SPANN/AnnService/src/Helper/VectorSetReaders/TxtReader.cpp ADDED
@@ -0,0 +1,436 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright (c) Microsoft Corporation. All rights reserved.
2
+ // Licensed under the MIT License.
3
+
4
+ #include "inc/Helper/VectorSetReaders/TxtReader.h"
5
+ #include "inc/Helper/StringConvert.h"
6
+ #include "inc/Helper/CommonHelper.h"
7
+
8
+ #include <omp.h>
9
+
10
+ using namespace SPTAG;
11
+ using namespace SPTAG::Helper;
12
+
13
+ TxtVectorReader::TxtVectorReader(std::shared_ptr<ReaderOptions> p_options)
14
+ : VectorSetReader(p_options),
15
+ m_subTaskBlocksize(0)
16
+ {
17
+ omp_set_num_threads(m_options->m_threadNum);
18
+
19
+ std::string tempFolder("tempfolder");
20
+ if (!direxists(tempFolder.c_str()))
21
+ {
22
+ mkdir(tempFolder.c_str());
23
+ }
24
+
25
+ tempFolder += FolderSep;
26
+ std::srand(clock());
27
+ std::string randstr = std::to_string(std::rand());
28
+ m_vectorOutput = tempFolder + "vectorset.bin." + randstr;
29
+ m_metadataConentOutput = tempFolder + "metadata.bin." + randstr;
30
+ m_metadataIndexOutput = tempFolder + "metadataindex.bin." + randstr;
31
+ }
32
+
33
+
34
+ TxtVectorReader::~TxtVectorReader()
35
+ {
36
+ if (fileexists(m_vectorOutput.c_str()))
37
+ {
38
+ remove(m_vectorOutput.c_str());
39
+ }
40
+
41
+ if (fileexists(m_metadataIndexOutput.c_str()))
42
+ {
43
+ remove(m_metadataIndexOutput.c_str());
44
+ }
45
+
46
+ if (fileexists(m_metadataConentOutput.c_str()))
47
+ {
48
+ remove(m_metadataConentOutput.c_str());
49
+ }
50
+ }
51
+
52
+
53
+ ErrorCode
54
+ TxtVectorReader::LoadFile(const std::string& p_filePaths)
55
+ {
56
+ const auto& files = GetFileSizes(p_filePaths);
57
+ std::vector<std::function<ErrorCode()>> subWorks;
58
+ subWorks.reserve(files.size() * m_options->m_threadNum);
59
+
60
+ m_subTaskCount = 0;
61
+ for (const auto& fileInfo : files)
62
+ {
63
+ if (fileInfo.second == (std::numeric_limits<std::size_t>::max)())
64
+ {
65
+ SPTAGLIB_LOG(Helper::LogLevel::LL_Error, "File %s not exists or can't access.\n", fileInfo.first.c_str());
66
+ return ErrorCode::FailedOpenFile;
67
+ }
68
+
69
+ std::uint32_t fileTaskCount = 0;
70
+ std::size_t blockSize = m_subTaskBlocksize;
71
+ if (0 == blockSize)
72
+ {
73
+ fileTaskCount = m_options->m_threadNum;
74
+ if(fileTaskCount == 0) fileTaskCount = 1;
75
+ blockSize = (fileInfo.second + fileTaskCount - 1) / fileTaskCount;
76
+ }
77
+ else
78
+ {
79
+ fileTaskCount = static_cast<std::uint32_t>((fileInfo.second + blockSize - 1) / blockSize);
80
+ }
81
+
82
+ for (std::uint32_t i = 0; i < fileTaskCount; ++i)
83
+ {
84
+ subWorks.emplace_back(std::bind(&TxtVectorReader::LoadFileInternal,
85
+ this,
86
+ fileInfo.first,
87
+ m_subTaskCount++,
88
+ i,
89
+ blockSize));
90
+ }
91
+ }
92
+
93
+ m_totalRecordCount = 0;
94
+ m_totalRecordVectorBytes = 0;
95
+ m_subTaskRecordCount.clear();
96
+ m_subTaskRecordCount.resize(m_subTaskCount, 0);
97
+
98
+ m_waitSignal.Reset(m_subTaskCount);
99
+
100
+ #pragma omp parallel for schedule(dynamic)
101
+ for (int64_t i = 0; i < (int64_t)subWorks.size(); i++)
102
+ {
103
+ ErrorCode code = subWorks[i]();
104
+ if (ErrorCode::Success != code)
105
+ {
106
+ throw std::runtime_error("LoadFileInternal failed");
107
+ }
108
+
109
+ }
110
+
111
+ m_waitSignal.Wait();
112
+
113
+ return MergeData();
114
+ }
115
+
116
+
117
+ std::shared_ptr<VectorSet>
118
+ TxtVectorReader::GetVectorSet(SizeType start, SizeType end) const
119
+ {
120
+ auto ptr = f_createIO();
121
+ if (ptr == nullptr || !ptr->Initialize(m_vectorOutput.c_str(), std::ios::binary | std::ios::in)) {
122
+ SPTAGLIB_LOG(Helper::LogLevel::LL_Error, "Failed to read file %s.\n", m_vectorOutput.c_str());
123
+ throw std::runtime_error("Failed to read vectorset file");
124
+ }
125
+
126
+ SizeType row;
127
+ DimensionType col;
128
+ if (ptr->ReadBinary(sizeof(SizeType), (char*)&row) != sizeof(SizeType)) {
129
+ SPTAGLIB_LOG(Helper::LogLevel::LL_Error, "Failed to read VectorSet!\n");
130
+ throw std::runtime_error("Failed to read vectorset file");
131
+ }
132
+ if (ptr->ReadBinary(sizeof(DimensionType), (char*)&col) != sizeof(DimensionType)) {
133
+ SPTAGLIB_LOG(Helper::LogLevel::LL_Error, "Failed to read VectorSet!\n");
134
+ throw std::runtime_error("Failed to read vectorset file");
135
+ }
136
+
137
+ if (start > row) start = row;
138
+ if (end < 0 || end > row) end = row;
139
+ std::uint64_t totalRecordVectorBytes = ((std::uint64_t)GetValueTypeSize(m_options->m_inputValueType)) * (end - start) * col;
140
+ ByteArray vectorSet;
141
+ if (totalRecordVectorBytes > 0) {
142
+ vectorSet = ByteArray::Alloc(totalRecordVectorBytes);
143
+ char* vecBuf = reinterpret_cast<char*>(vectorSet.Data());
144
+ std::uint64_t offset = ((std::uint64_t)GetValueTypeSize(m_options->m_inputValueType)) * start * col + +sizeof(SizeType) + sizeof(DimensionType);
145
+ if (ptr->ReadBinary(totalRecordVectorBytes, vecBuf, offset) != totalRecordVectorBytes) {
146
+ SPTAGLIB_LOG(Helper::LogLevel::LL_Error, "Failed to read VectorSet!\n");
147
+ throw std::runtime_error("Failed to read vectorset file");
148
+ }
149
+ }
150
+ return std::shared_ptr<VectorSet>(new BasicVectorSet(vectorSet,
151
+ m_options->m_inputValueType,
152
+ col,
153
+ end - start));
154
+ }
155
+
156
+
157
+ std::shared_ptr<MetadataSet>
158
+ TxtVectorReader::GetMetadataSet() const
159
+ {
160
+ if (fileexists(m_metadataIndexOutput.c_str()) && fileexists(m_metadataConentOutput.c_str()))
161
+ return std::shared_ptr<MetadataSet>(new FileMetadataSet(m_metadataConentOutput, m_metadataIndexOutput));
162
+ return nullptr;
163
+ }
164
+
165
+
166
+ ErrorCode
167
+ TxtVectorReader::LoadFileInternal(const std::string& p_filePath,
168
+ std::uint32_t p_subTaskID,
169
+ std::uint32_t p_fileBlockID,
170
+ std::size_t p_fileBlockSize)
171
+ {
172
+ std::uint64_t lineBufferSize = 1 << 16;
173
+ std::unique_ptr<char[]> currentLine(new char[lineBufferSize]);
174
+
175
+ SizeType recordCount = 0;
176
+ std::uint64_t metaOffset = 0;
177
+ std::size_t totalRead = 0;
178
+ std::streamoff startpos = p_fileBlockID * p_fileBlockSize;
179
+
180
+ std::shared_ptr<Helper::DiskIO> input = f_createIO(), output = f_createIO(), meta = f_createIO(), metaIndex = f_createIO();
181
+ if (input == nullptr || !input->Initialize(p_filePath.c_str(), std::ios::in | std::ios::binary))
182
+ {
183
+ SPTAGLIB_LOG(Helper::LogLevel::LL_Error, "Unable to open file: %s\n",p_filePath.c_str());
184
+ return ErrorCode::FailedOpenFile;
185
+ }
186
+
187
+ SPTAGLIB_LOG(Helper::LogLevel::LL_Info, "Begin Subtask: %u, start offset position: %lld\n", p_subTaskID, startpos);
188
+
189
+ std::string subFileSuffix("_");
190
+ subFileSuffix += std::to_string(p_subTaskID);
191
+ subFileSuffix += ".tmp";
192
+
193
+ if (output == nullptr || !output->Initialize((m_vectorOutput + subFileSuffix).c_str(), std::ios::binary | std::ios::out) ||
194
+ meta == nullptr || !meta->Initialize((m_metadataConentOutput + subFileSuffix).c_str(), std::ios::binary | std::ios::out) ||
195
+ metaIndex == nullptr || !metaIndex->Initialize((m_metadataIndexOutput + subFileSuffix).c_str(), std::ios::binary | std::ios::out))
196
+ {
197
+ SPTAGLIB_LOG(Helper::LogLevel::LL_Error, "Unable to create files: %s %s %s\n", (m_vectorOutput + subFileSuffix).c_str(), (m_metadataConentOutput + subFileSuffix).c_str(), (m_metadataIndexOutput + subFileSuffix).c_str());
198
+ return ErrorCode::FailedCreateFile;
199
+ }
200
+
201
+ if (p_fileBlockID != 0)
202
+ {
203
+ totalRead += input->ReadString(lineBufferSize, currentLine, '\n', startpos);
204
+ }
205
+
206
+ std::size_t vectorByteSize = GetValueTypeSize(m_options->m_inputValueType) * m_options->m_dimension;
207
+ std::unique_ptr<std::uint8_t[]> vector;
208
+ vector.reset(new std::uint8_t[vectorByteSize]);
209
+
210
+ while (totalRead <= p_fileBlockSize)
211
+ {
212
+ std::uint64_t lineLength = input->ReadString(lineBufferSize, currentLine);
213
+ if (lineLength == 0) break;
214
+ totalRead += lineLength;
215
+
216
+ std::size_t tabIndex = lineLength - 1;
217
+ while (tabIndex > 0 && currentLine[tabIndex] != '\t')
218
+ {
219
+ --tabIndex;
220
+ }
221
+
222
+ if (0 == tabIndex && currentLine[tabIndex] != '\t')
223
+ {
224
+ SPTAGLIB_LOG(Helper::LogLevel::LL_Error, "Subtask: %u cannot parsing line:%s\n", p_subTaskID, currentLine.get());
225
+ return ErrorCode::FailedParseValue;
226
+ }
227
+
228
+ bool parseSuccess = false;
229
+ switch (m_options->m_inputValueType)
230
+ {
231
+ #define DefineVectorValueType(Name, Type) \
232
+ case VectorValueType::Name: \
233
+ parseSuccess = TranslateVector(currentLine.get() + tabIndex + 1, reinterpret_cast<Type*>(vector.get())); \
234
+ break; \
235
+
236
+ #include "inc/Core/DefinitionList.h"
237
+ #undef DefineVectorValueType
238
+
239
+ default:
240
+ parseSuccess = false;
241
+ break;
242
+ }
243
+
244
+ if (!parseSuccess)
245
+ {
246
+ SPTAGLIB_LOG(Helper::LogLevel::LL_Error, "Subtask: %u cannot parsing vector:%s\n", p_subTaskID, currentLine.get());
247
+ return ErrorCode::FailedParseValue;
248
+ }
249
+
250
+ ++recordCount;
251
+ if (output->WriteBinary(vectorByteSize, (char*)vector.get()) != vectorByteSize ||
252
+ meta->WriteBinary(tabIndex, currentLine.get()) != tabIndex ||
253
+ metaIndex->WriteBinary(sizeof(metaOffset), (const char*)&metaOffset) != sizeof(metaOffset)) {
254
+ SPTAGLIB_LOG(Helper::LogLevel::LL_Error, "Subtask: %u cannot write line:%s\n", p_subTaskID, currentLine.get());
255
+ return ErrorCode::DiskIOFail;
256
+ }
257
+ metaOffset += tabIndex;
258
+ }
259
+ if (metaIndex->WriteBinary(sizeof(metaOffset), (const char*)&metaOffset) != sizeof(metaOffset)) {
260
+ SPTAGLIB_LOG(Helper::LogLevel::LL_Error, "Subtask: %u cannot write final offset!\n", p_subTaskID);
261
+ return ErrorCode::DiskIOFail;
262
+ }
263
+
264
+ m_totalRecordCount += recordCount;
265
+ m_subTaskRecordCount[p_subTaskID] = recordCount;
266
+ m_totalRecordVectorBytes += recordCount * vectorByteSize;
267
+
268
+ m_waitSignal.FinishOne();
269
+ return ErrorCode::Success;
270
+ }
271
+
272
+
273
+ ErrorCode
274
+ TxtVectorReader::MergeData()
275
+ {
276
+ const std::size_t bufferSize = 1 << 30;
277
+ const std::size_t bufferSizeTrim64 = (bufferSize / sizeof(std::uint64_t)) * sizeof(std::uint64_t);
278
+
279
+ std::shared_ptr<Helper::DiskIO> input = f_createIO(), output = f_createIO(), meta = f_createIO(), metaIndex = f_createIO();
280
+
281
+ if (output == nullptr || !output->Initialize(m_vectorOutput.c_str(), std::ios::binary | std::ios::out) ||
282
+ meta == nullptr || !meta->Initialize(m_metadataConentOutput.c_str(), std::ios::binary | std::ios::out) ||
283
+ metaIndex == nullptr || !metaIndex->Initialize(m_metadataIndexOutput.c_str(), std::ios::binary | std::ios::out))
284
+ {
285
+ SPTAGLIB_LOG(Helper::LogLevel::LL_Error, "Unable to create files: %s %s %s\n", m_vectorOutput.c_str(), m_metadataConentOutput.c_str(), m_metadataIndexOutput.c_str());
286
+ return ErrorCode::FailedCreateFile;
287
+ }
288
+
289
+ std::unique_ptr<char[]> bufferHolder(new char[bufferSize]);
290
+ char* buf = bufferHolder.get();
291
+
292
+ SizeType totalRecordCount = m_totalRecordCount;
293
+ if (output->WriteBinary(sizeof(totalRecordCount), (char*)(&totalRecordCount)) != sizeof(totalRecordCount)) {
294
+ SPTAGLIB_LOG(Helper::LogLevel::LL_Error, "Unable to write file: %s\n", m_vectorOutput.c_str());
295
+ return ErrorCode::DiskIOFail;
296
+ }
297
+ if (output->WriteBinary(sizeof(m_options->m_dimension), (char*)&(m_options->m_dimension)) != sizeof(m_options->m_dimension)) {
298
+ SPTAGLIB_LOG(Helper::LogLevel::LL_Error, "Unable to write file: %s\n", m_vectorOutput.c_str());
299
+ return ErrorCode::DiskIOFail;
300
+ }
301
+
302
+ for (std::uint32_t i = 0; i < m_subTaskCount; ++i)
303
+ {
304
+ std::string file = m_vectorOutput;
305
+ file += "_";
306
+ file += std::to_string(i);
307
+ file += ".tmp";
308
+
309
+ if (input == nullptr || !input->Initialize(file.c_str(), std::ios::binary | std::ios::in))
310
+ {
311
+ SPTAGLIB_LOG(Helper::LogLevel::LL_Error, "Unable to open file: %s\n", file.c_str());
312
+ return ErrorCode::FailedOpenFile;
313
+ }
314
+
315
+ std::uint64_t readSize = input->ReadBinary(bufferSize, bufferHolder.get());
316
+ while (readSize != 0) {
317
+ if (output->WriteBinary(readSize, bufferHolder.get()) != readSize) {
318
+ SPTAGLIB_LOG(Helper::LogLevel::LL_Error, "Unable to write file: %s\n", m_vectorOutput.c_str());
319
+ return ErrorCode::DiskIOFail;
320
+ }
321
+ readSize = input->ReadBinary(bufferSize, bufferHolder.get());
322
+ }
323
+ input->ShutDown();
324
+ remove(file.c_str());
325
+ }
326
+
327
+ for (std::uint32_t i = 0; i < m_subTaskCount; ++i)
328
+ {
329
+ std::string file = m_metadataConentOutput;
330
+ file += "_";
331
+ file += std::to_string(i);
332
+ file += ".tmp";
333
+
334
+ if (input == nullptr || !input->Initialize(file.c_str(), std::ios::binary | std::ios::in))
335
+ {
336
+ SPTAGLIB_LOG(Helper::LogLevel::LL_Error, "Unable to open file: %s\n", file.c_str());
337
+ return ErrorCode::FailedOpenFile;
338
+ }
339
+
340
+ std::uint64_t readSize = input->ReadBinary(bufferSize, bufferHolder.get());
341
+ while ( readSize != 0 ) {
342
+ if (meta->WriteBinary(readSize, bufferHolder.get()) != readSize) {
343
+ SPTAGLIB_LOG(Helper::LogLevel::LL_Error, "Unable to write file: %s\n", m_metadataConentOutput.c_str());
344
+ return ErrorCode::DiskIOFail;
345
+ }
346
+ readSize = input->ReadBinary(bufferSize, bufferHolder.get());
347
+ }
348
+ input->ShutDown();
349
+ remove(file.c_str());
350
+ }
351
+
352
+ if (metaIndex->WriteBinary(sizeof(totalRecordCount), (char*)(&totalRecordCount)) != sizeof(totalRecordCount)) {
353
+ SPTAGLIB_LOG(Helper::LogLevel::LL_Error, "Unable to write file: %s\n", m_metadataIndexOutput.c_str());
354
+ return ErrorCode::DiskIOFail;
355
+ }
356
+
357
+ std::uint64_t totalOffset = 0;
358
+ for (std::uint32_t i = 0; i < m_subTaskCount; ++i)
359
+ {
360
+ std::string file = m_metadataIndexOutput;
361
+ file += "_";
362
+ file += std::to_string(i);
363
+ file += ".tmp";
364
+
365
+ if (input == nullptr || !input->Initialize(file.c_str(), std::ios::binary | std::ios::in))
366
+ {
367
+ SPTAGLIB_LOG(Helper::LogLevel::LL_Error, "Unable to open file: %s\n", file.c_str());
368
+ return ErrorCode::FailedOpenFile;
369
+ }
370
+
371
+ for (SizeType remains = m_subTaskRecordCount[i]; remains > 0;)
372
+ {
373
+ std::size_t readBytesCount = min(remains * sizeof(std::uint64_t), bufferSizeTrim64);
374
+ if (input->ReadBinary(readBytesCount, buf) != readBytesCount) {
375
+ SPTAGLIB_LOG(Helper::LogLevel::LL_Error, "Unable to read file: %s\n", file.c_str());
376
+ return ErrorCode::DiskIOFail;
377
+ }
378
+ std::uint64_t* offset = reinterpret_cast<std::uint64_t*>(buf);
379
+ for (std::uint64_t j = 0; j < readBytesCount / sizeof(std::uint64_t); ++j)
380
+ {
381
+ offset[j] += totalOffset;
382
+ }
383
+
384
+ if (metaIndex->WriteBinary(readBytesCount, buf) != readBytesCount) {
385
+ SPTAGLIB_LOG(Helper::LogLevel::LL_Error, "Unable to write file: %s\n", m_metadataIndexOutput.c_str());
386
+ return ErrorCode::DiskIOFail;
387
+ }
388
+ remains -= static_cast<SizeType>(readBytesCount / sizeof(std::uint64_t));
389
+ }
390
+ if (input->ReadBinary(sizeof(std::uint64_t), buf) != sizeof(std::uint64_t)) {
391
+ SPTAGLIB_LOG(Helper::LogLevel::LL_Error, "Unable to read file: %s\n", file.c_str());
392
+ return ErrorCode::DiskIOFail;
393
+ }
394
+ totalOffset += *(reinterpret_cast<std::uint64_t*>(buf));
395
+
396
+ input->ShutDown();
397
+ remove(file.c_str());
398
+ }
399
+
400
+ if (metaIndex->WriteBinary(sizeof(totalOffset), (char*)&totalOffset) != sizeof(totalOffset)) {
401
+ SPTAGLIB_LOG(Helper::LogLevel::LL_Error, "Unable to write file: %s\n", m_metadataIndexOutput.c_str());
402
+ return ErrorCode::DiskIOFail;
403
+ }
404
+ return ErrorCode::Success;
405
+ }
406
+
407
+
408
+ std::vector<TxtVectorReader::FileInfoPair>
409
+ TxtVectorReader::GetFileSizes(const std::string& p_filePaths)
410
+ {
411
+ const auto& files = Helper::StrUtils::SplitString(p_filePaths, ",");
412
+ std::vector<TxtVectorReader::FileInfoPair> res;
413
+ res.reserve(files.size());
414
+
415
+ for (const auto& filePath : files)
416
+ {
417
+ if (!fileexists(filePath.c_str()))
418
+ {
419
+ res.emplace_back(filePath, (std::numeric_limits<std::size_t>::max)());
420
+ continue;
421
+ }
422
+ #ifndef _MSC_VER
423
+ struct stat stat_buf;
424
+ stat(filePath.c_str(), &stat_buf);
425
+ #else
426
+ struct _stat64 stat_buf;
427
+ _stat64(filePath.c_str(), &stat_buf);
428
+ #endif
429
+ std::size_t fileSize = stat_buf.st_size;
430
+ res.emplace_back(filePath, static_cast<std::size_t>(fileSize));
431
+ }
432
+
433
+ return res;
434
+ }
435
+
436
+
SPANN/AnnService/src/Helper/VectorSetReaders/XvecReader.cpp ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright (c) Microsoft Corporation. All rights reserved.
2
+ // Licensed under the MIT License.
3
+
4
+ #include "inc/Helper/VectorSetReaders/XvecReader.h"
5
+ #include "inc/Helper/CommonHelper.h"
6
+
7
+ #include <time.h>
8
+
9
+ using namespace SPTAG;
10
+ using namespace SPTAG::Helper;
11
+
12
+ XvecVectorReader::XvecVectorReader(std::shared_ptr<ReaderOptions> p_options)
13
+ : VectorSetReader(p_options)
14
+ {
15
+ std::string tempFolder("tempfolder");
16
+ if (!direxists(tempFolder.c_str()))
17
+ {
18
+ mkdir(tempFolder.c_str());
19
+ }
20
+ std::srand(clock());
21
+ m_vectorOutput = tempFolder + FolderSep + "vectorset.bin." + std::to_string(std::rand());
22
+ }
23
+
24
+
25
+ XvecVectorReader::~XvecVectorReader()
26
+ {
27
+ if (fileexists(m_vectorOutput.c_str()))
28
+ {
29
+ remove(m_vectorOutput.c_str());
30
+ }
31
+ }
32
+
33
+
34
+ ErrorCode
35
+ XvecVectorReader::LoadFile(const std::string& p_filePaths)
36
+ {
37
+ const auto& files = Helper::StrUtils::SplitString(p_filePaths, ",");
38
+ auto fp = f_createIO();
39
+ if (fp == nullptr || !fp->Initialize(m_vectorOutput.c_str(), std::ios::binary | std::ios::out)) {
40
+ SPTAGLIB_LOG(Helper::LogLevel::LL_Error, "Failed to write file: %s \n", m_vectorOutput.c_str());
41
+ return ErrorCode::FailedCreateFile;
42
+ }
43
+ SizeType vectorCount = 0;
44
+ IOBINARY(fp, WriteBinary, sizeof(vectorCount), (char*)&vectorCount);
45
+ IOBINARY(fp, WriteBinary, sizeof(m_options->m_dimension), (char*)&(m_options->m_dimension));
46
+
47
+ size_t vectorDataSize = GetValueTypeSize(m_options->m_inputValueType) * m_options->m_dimension;
48
+ std::unique_ptr<char[]> buffer(new char[vectorDataSize]);
49
+ for (std::string file : files)
50
+ {
51
+ auto ptr = f_createIO();
52
+ if (ptr == nullptr || !ptr->Initialize(file.c_str(), std::ios::binary | std::ios::in)) {
53
+ SPTAGLIB_LOG(Helper::LogLevel::LL_Error, "Failed to read file: %s \n", file.c_str());
54
+ return ErrorCode::FailedOpenFile;
55
+ }
56
+ while (true)
57
+ {
58
+ DimensionType dim;
59
+ if (ptr->ReadBinary(sizeof(DimensionType), (char*)&dim) == 0) break;
60
+
61
+ if (dim != m_options->m_dimension) {
62
+ SPTAGLIB_LOG(Helper::LogLevel::LL_Error, "Xvec file %s has No.%d vector whose dims are not as many as expected. Expected: %d, Fact: %d\n", file.c_str(), vectorCount, m_options->m_dimension, dim);
63
+ return ErrorCode::DimensionSizeMismatch;
64
+ }
65
+ IOBINARY(ptr, ReadBinary, vectorDataSize, buffer.get());
66
+ IOBINARY(fp, WriteBinary, vectorDataSize, buffer.get());
67
+ vectorCount++;
68
+ }
69
+ }
70
+ IOBINARY(fp, WriteBinary, sizeof(vectorCount), (char*)&vectorCount, 0);
71
+ return ErrorCode::Success;
72
+ }
73
+
74
+
75
+ std::shared_ptr<VectorSet>
76
+ XvecVectorReader::GetVectorSet(SizeType start, SizeType end) const
77
+ {
78
+ auto ptr = f_createIO();
79
+ if (ptr == nullptr || !ptr->Initialize(m_vectorOutput.c_str(), std::ios::binary | std::ios::in)) {
80
+ SPTAGLIB_LOG(Helper::LogLevel::LL_Error, "Failed to read file %s.\n", m_vectorOutput.c_str());
81
+ throw std::runtime_error("Failed read file");
82
+ }
83
+
84
+ SizeType row;
85
+ DimensionType col;
86
+ if (ptr->ReadBinary(sizeof(SizeType), (char*)&row) != sizeof(SizeType)) {
87
+ SPTAGLIB_LOG(Helper::LogLevel::LL_Error, "Failed to read VectorSet!\n");
88
+ throw std::runtime_error("Failed read file");
89
+ }
90
+ if (ptr->ReadBinary(sizeof(DimensionType), (char*)&col) != sizeof(DimensionType)) {
91
+ SPTAGLIB_LOG(Helper::LogLevel::LL_Error, "Failed to read VectorSet!\n");
92
+ throw std::runtime_error("Failed read file");
93
+ }
94
+
95
+ if (start > row) start = row;
96
+ if (end < 0 || end > row) end = row;
97
+ std::uint64_t totalRecordVectorBytes = ((std::uint64_t)GetValueTypeSize(m_options->m_inputValueType)) * (end - start) * col;
98
+ ByteArray vectorSet;
99
+ if (totalRecordVectorBytes > 0) {
100
+ vectorSet = ByteArray::Alloc(totalRecordVectorBytes);
101
+ char* vecBuf = reinterpret_cast<char*>(vectorSet.Data());
102
+ std::uint64_t offset = ((std::uint64_t)GetValueTypeSize(m_options->m_inputValueType)) * start * col + +sizeof(SizeType) + sizeof(DimensionType);
103
+ if (ptr->ReadBinary(totalRecordVectorBytes, vecBuf, offset) != totalRecordVectorBytes) {
104
+ SPTAGLIB_LOG(Helper::LogLevel::LL_Error, "Failed to read VectorSet!\n");
105
+ throw std::runtime_error("Failed read file");
106
+ }
107
+ }
108
+ return std::shared_ptr<VectorSet>(new BasicVectorSet(vectorSet,
109
+ m_options->m_inputValueType,
110
+ col,
111
+ end - start));
112
+ }
113
+
114
+
115
+ std::shared_ptr<MetadataSet>
116
+ XvecVectorReader::GetMetadataSet() const
117
+ {
118
+ return nullptr;
119
+ }
SPANN/ThirdParty/zstd/.circleci/config.yml ADDED
@@ -0,0 +1,124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ version: 2
2
+
3
+ jobs:
4
+ # the first half of the jobs are in this test
5
+ short-tests-0:
6
+ # TODO: Create a small custom docker image with all the dependencies we need
7
+ # preinstalled to reduce installation time.
8
+ docker:
9
+ - image: fbopensource/zstd-circleci-primary:0.0.1
10
+ # TODO: Re-enable aarch64 build:
11
+ # make aarch64build && make clean
12
+ steps:
13
+ - checkout
14
+ - run:
15
+ name: Test
16
+ command: |
17
+ ./tests/test-license.py
18
+ cc -v
19
+ CFLAGS="-O0 -Werror -pedantic" make allmost; make clean
20
+ make c99build; make clean
21
+ make c11build; make clean
22
+ make -j regressiontest; make clean
23
+ make shortest; make clean
24
+ make cxxtest; make clean
25
+ # the second half of the jobs are in this test
26
+ short-tests-1:
27
+ docker:
28
+ - image: fbopensource/zstd-circleci-primary:0.0.1
29
+ steps:
30
+ - checkout
31
+ - run:
32
+ name: Test
33
+ command: |
34
+ make gnu90build; make clean
35
+ make gnu99build; make clean
36
+ make ppc64build V=1; make clean
37
+ make ppcbuild V=1; make clean
38
+ make armbuild V=1; make clean
39
+ make -C tests test-legacy test-longmatch; make clean
40
+ make -C lib libzstd-nomt; make clean
41
+ # This step should only be run in a cron job
42
+ regression-test:
43
+ docker:
44
+ - image: fbopensource/zstd-circleci-primary:0.0.1
45
+ environment:
46
+ CIRCLE_ARTIFACTS: /tmp/circleci-artifacts
47
+ steps:
48
+ - checkout
49
+ # Restore the cached resources.
50
+ - restore_cache:
51
+ # We try our best to bust the cache when the data changes by hashing
52
+ # data.c. If that doesn't work, simply update the version number here
53
+ # and below. If we fail to bust the cache, the regression testing will
54
+ # still work, since it has its own stamp, but will need to redownload
55
+ # everything.
56
+ keys:
57
+ - regression-cache-{{ checksum "tests/regression/data.c" }}-v0
58
+ - run:
59
+ name: Regression Test
60
+ command: |
61
+ make -C programs zstd
62
+ make -C tests/regression test
63
+ mkdir -p $CIRCLE_ARTIFACTS
64
+ ./tests/regression/test \
65
+ --cache tests/regression/cache \
66
+ --output $CIRCLE_ARTIFACTS/results.csv \
67
+ --zstd programs/zstd
68
+ echo "NOTE: The new results.csv is uploaded as an artifact to this job"
69
+ echo " If this fails, go to the Artifacts pane in CircleCI, "
70
+ echo " download /tmp/circleci-artifacts/results.csv, and if they "
71
+ echo " are still good, copy it into the repo and commit it."
72
+ echo "> diff tests/regression/results.csv $CIRCLE_ARTIFACTS/results.csv"
73
+ diff tests/regression/results.csv $CIRCLE_ARTIFACTS/results.csv
74
+ # Only save the cache on success (default), since if the failure happened
75
+ # before we stamp the data cache, we will have a bad cache for this key.
76
+ - save_cache:
77
+ key: regression-cache-{{ checksum "tests/regression/data.c" }}-v0
78
+ paths:
79
+ - tests/regression/cache
80
+ - store_artifacts:
81
+ path: /tmp/circleci-artifacts
82
+
83
+
84
+ workflows:
85
+ version: 2
86
+ commit:
87
+ jobs:
88
+ # Run the tests in parallel
89
+ - short-tests-0
90
+ - short-tests-1
91
+ - regression-test
92
+
93
+ nightly:
94
+ triggers:
95
+ - schedule:
96
+ cron: "0 0 * * *"
97
+ filters:
98
+ branches:
99
+ only:
100
+ - release
101
+ - dev
102
+ - master
103
+ jobs:
104
+ # Run daily regression tests
105
+ - regression-test
106
+
107
+
108
+
109
+ # Longer tests
110
+ #- make -C tests test-zstd-nolegacy && make clean
111
+ #- pyenv global 3.4.4; make -C tests versionsTest && make clean
112
+ #- make zlibwrapper && make clean
113
+ #- gcc -v; make -C tests test32 MOREFLAGS="-I/usr/include/x86_64-linux-gnu" && make clean
114
+ #- make uasan && make clean
115
+ #- make asan32 && make clean
116
+ #- make -C tests test32 CC=clang MOREFLAGS="-g -fsanitize=address -I/usr/include/x86_64-linux-gnu"
117
+ # Valgrind tests
118
+ #- CFLAGS="-O1 -g" make -C zlibWrapper valgrindTest && make clean
119
+ #- make -C tests valgrindTest && make clean
120
+ # ARM, AArch64, PowerPC, PowerPC64 tests
121
+ #- make ppctest && make clean
122
+ #- make ppc64test && make clean
123
+ #- make armtest && make clean
124
+ #- make aarch64test && make clean
SPANN/ThirdParty/zstd/.circleci/images/primary/Dockerfile ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ FROM circleci/buildpack-deps:bionic
2
+
3
+ RUN sudo dpkg --add-architecture i386
4
+ RUN sudo apt-get -y -qq update
5
+ RUN sudo apt-get -y install \
6
+ gcc-multilib-powerpc-linux-gnu gcc-arm-linux-gnueabi \
7
+ libc6-dev-armel-cross gcc-aarch64-linux-gnu libc6-dev-arm64-cross \
8
+ libc6-dev-ppc64-powerpc-cross zstd gzip coreutils \
9
+ libcurl4-openssl-dev
SPANN/ThirdParty/zstd/.cirrus.yml ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ task:
2
+ name: FreeBSD (shortest)
3
+ freebsd_instance:
4
+ matrix:
5
+ image_family: freebsd-12-2
6
+ # The stable 11.3 image causes "Agent is not responding" so use a snapshot
7
+ image_family: freebsd-11-3-snap
8
+ install_script: pkg install -y gmake coreutils
9
+ script: |
10
+ MOREFLAGS="-Werror" gmake -j all
11
+ gmake shortest
SPANN/ThirdParty/zstd/.gitattributes ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Set the default behavior
2
+ * text eol=lf
3
+
4
+ # Explicitly declare source files
5
+ *.c text eol=lf
6
+ *.h text eol=lf
7
+
8
+ # Denote files that should not be modified.
9
+ *.odt binary
10
+ *.png binary
11
+
12
+ # Visual Studio
13
+ *.sln text eol=crlf
14
+ *.vcxproj* text eol=crlf
15
+ *.vcproj* text eol=crlf
16
+ *.suo binary
17
+ *.rc text eol=crlf
18
+
19
+ # Windows
20
+ *.bat text eol=crlf
21
+ *.cmd text eol=crlf
SPANN/ThirdParty/zstd/.gitignore ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Object files
2
+ *.o
3
+ *.ko
4
+ *.dSYM
5
+
6
+ # Libraries
7
+ *.lib
8
+ *.a
9
+
10
+ # Shared objects (inc. Windows DLLs)
11
+ *.dll
12
+ *.so
13
+ *.so.*
14
+ *.dylib
15
+
16
+ # Executables
17
+ /zstd
18
+ zstdmt
19
+ *.exe
20
+ *.out
21
+ *.app
22
+
23
+ # Test artefacts
24
+ tmp*
25
+ *.zst
26
+ *.zstd
27
+ dictionary.
28
+ dictionary
29
+ NUL
30
+
31
+ # Build artefacts
32
+ contrib/linux-kernel/linux/
33
+ projects/
34
+ bin/
35
+ .buckd/
36
+ buck-out/
37
+ build-*
38
+ *.gcda
39
+
40
+ # Other files
41
+ .directory
42
+ _codelite/
43
+ _zstdbench/
44
+ .clang_complete
45
+ *.idea
46
+ *.swp
47
+ .DS_Store
48
+ googletest/
49
+ *.d
50
+ *.vscode
51
+ *.code-workspace
52
+ compile_commands.json
53
+ .clangd
54
+ perf.data
55
+ perf.data.old
SPANN/ThirdParty/zstd/.travis.yml ADDED
@@ -0,0 +1,128 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Travis CI is used to test platforms that github-actions currently doesn't support
2
+ # without either self-hosting or some finnicky work-around. Also, some tests
3
+ # are troublesome to migrate since GH Actions runs tests not in a tty.
4
+ language: c
5
+
6
+ git:
7
+ depth: 1
8
+
9
+ branches:
10
+ only:
11
+ - dev
12
+ - release
13
+ - master
14
+ - travisTest
15
+
16
+ addons:
17
+ apt:
18
+ update: true
19
+
20
+ env:
21
+ global:
22
+ - FUZZERTEST=-T1mn
23
+ ZSTREAM_TESTTIME=-T1mn
24
+ DECODECORPUS_TESTTIME=-T1mn
25
+
26
+ matrix:
27
+ fast_finish: true
28
+ include:
29
+ - name: S390X (big endian) + Fuzz test
30
+ dist: trusty
31
+ arch: s390x
32
+ script:
33
+ - FUZZER_FLAGS=--no-big-tests make -C tests fuzztest
34
+
35
+ - name: S390X (big endian) + Fuzz test + no intrinsics
36
+ dist: trusty
37
+ arch: s390x
38
+ script:
39
+ - MOREFLAGS="-DZSTD_NO_INTRINSICS" FUZZER_FLAGS=--no-big-tests make -C tests fuzztest
40
+
41
+ - name: arm64 # ~2.5 mn
42
+ os: linux
43
+ arch: arm64
44
+ script:
45
+ - make check
46
+
47
+ - name: arm64fuzz
48
+ os: linux
49
+ arch: arm64
50
+ script:
51
+ - make -C tests fuzztest
52
+
53
+ # TODO: migrate to GH Actions once newest clang staticanalyze warnings are fixed
54
+ - name: static analyzer scanbuild # ~8mn
55
+ dist: trusty # note : it's important to pin down a version of static analyzer, since different versions report different false positives
56
+ script:
57
+ - make staticAnalyze
58
+
59
+ # GH actions can't run this command on OS-X, non-tty issues
60
+ - name: OS-X make all lib
61
+ os: osx
62
+ script:
63
+ - make -C lib all
64
+
65
+ # Introduced to check compat with old toolchains, to prevent e.g. #1872
66
+ - name: ARM Build Test (on Trusty)
67
+ dist: trusty
68
+ script:
69
+ - make arminstall
70
+ - make armbuild
71
+
72
+ # check release number (release/new tag only)
73
+ - name: Tag-Specific Test
74
+ if: tag =~ ^v[0-9]\.[0-9]
75
+ script:
76
+ - make -C tests checkTag
77
+ - tests/checkTag "$TRAVIS_BRANCH"
78
+
79
+ - name: PPC64LE + Fuzz test # ~13mn
80
+ arch: ppc64le
81
+ env:
82
+ - FUZZER_FLAGS=--no-big-tests
83
+ - MOREFLAGS="-static"
84
+ script:
85
+ - cat /proc/cpuinfo
86
+ - make -C tests fuzztest
87
+
88
+ # This test currently fails on GA specifically, for no obvious reason
89
+ # (it works fine on travisCI, and on local test platforms).
90
+ - name: Versions Compatibility Test # ~6mn
91
+ script:
92
+ - make -C tests versionsTest
93
+
94
+ # meson dedicated test
95
+ - name: Xenial (Meson + clang) # ~15mn
96
+ dist: bionic
97
+ language: cpp
98
+ compiler: clang
99
+ install:
100
+ - sudo apt-get install -qq liblz4-dev valgrind tree
101
+ - |
102
+ travis_retry curl -o ~/ninja.zip -L 'https://github.com/ninja-build/ninja/releases/download/v1.9.0/ninja-linux.zip' &&
103
+ unzip ~/ninja.zip -d ~/.local/bin
104
+ - |
105
+ travis_retry curl -o ~/get-pip.py -L 'https://bootstrap.pypa.io/get-pip.py' &&
106
+ python3 ~/get-pip.py --user &&
107
+ pip3 install --user meson
108
+ script:
109
+ - |
110
+ meson setup \
111
+ --buildtype=debugoptimized \
112
+ -Db_lundef=false \
113
+ -Dauto_features=enabled \
114
+ -Dbin_programs=true \
115
+ -Dbin_tests=true \
116
+ -Dbin_contrib=true \
117
+ -Ddefault_library=both \
118
+ build/meson builddir
119
+ - pushd builddir
120
+ - ninja
121
+ - meson test --verbose --no-rebuild
122
+ - DESTDIR=./staging ninja install
123
+ - tree ./staging
124
+ after_failure:
125
+ - cat "$TRAVIS_BUILD_DIR"/builddir/meson-logs/testlog.txt
126
+
127
+ allow_failures:
128
+ - env: ALLOW_FAILURES=true
SPANN/ThirdParty/zstd/CONTRIBUTING.md ADDED
@@ -0,0 +1,489 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Contributing to Zstandard
2
+ We want to make contributing to this project as easy and transparent as
3
+ possible.
4
+
5
+ ## Our Development Process
6
+ New versions are being developed in the "dev" branch,
7
+ or in their own feature branch.
8
+ When they are deemed ready for a release, they are merged into "release".
9
+
10
+ As a consequences, all contributions must stage first through "dev"
11
+ or their own feature branch.
12
+
13
+ ## Pull Requests
14
+ We actively welcome your pull requests.
15
+
16
+ 1. Fork the repo and create your branch from `dev`.
17
+ 2. If you've added code that should be tested, add tests.
18
+ 3. If you've changed APIs, update the documentation.
19
+ 4. Ensure the test suite passes.
20
+ 5. Make sure your code lints.
21
+ 6. If you haven't already, complete the Contributor License Agreement ("CLA").
22
+
23
+ ## Contributor License Agreement ("CLA")
24
+ In order to accept your pull request, we need you to submit a CLA. You only need
25
+ to do this once to work on any of Facebook's open source projects.
26
+
27
+ Complete your CLA here: <https://code.facebook.com/cla>
28
+
29
+ ## Workflow
30
+ Zstd uses a branch-based workflow for making changes to the codebase. Typically, zstd
31
+ will use a new branch per sizable topic. For smaller changes, it is okay to lump multiple
32
+ related changes into a branch.
33
+
34
+ Our contribution process works in three main stages:
35
+ 1. Local development
36
+ * Update:
37
+ * Checkout your fork of zstd if you have not already
38
+ ```
39
+ git checkout https://github.com/<username>/zstd
40
+ cd zstd
41
+ ```
42
+ * Update your local dev branch
43
+ ```
44
+ git pull https://github.com/facebook/zstd dev
45
+ git push origin dev
46
+ ```
47
+ * Topic and development:
48
+ * Make a new branch on your fork about the topic you're developing for
49
+ ```
50
+ # branch names should be concise but sufficiently informative
51
+ git checkout -b <branch-name>
52
+ git push origin <branch-name>
53
+ ```
54
+ * Make commits and push
55
+ ```
56
+ # make some changes =
57
+ git add -u && git commit -m <message>
58
+ git push origin <branch-name>
59
+ ```
60
+ * Note: run local tests to ensure that your changes didn't break existing functionality
61
+ * Quick check
62
+ ```
63
+ make shortest
64
+ ```
65
+ * Longer check
66
+ ```
67
+ make test
68
+ ```
69
+ 2. Code Review and CI tests
70
+ * Ensure CI tests pass:
71
+ * Before sharing anything to the community, create a pull request in your own fork against the dev branch
72
+ and make sure that all GitHub Actions CI tests pass. See the Continuous Integration section below for more information.
73
+ * Ensure that static analysis passes on your development machine. See the Static Analysis section
74
+ below to see how to do this.
75
+ * Create a pull request:
76
+ * When you are ready to share you changes to the community, create a pull request from your branch
77
+ to facebook:dev. You can do this very easily by clicking 'Create Pull Request' on your fork's home
78
+ page.
79
+ * From there, select the branch where you made changes as your source branch and facebook:dev
80
+ as the destination.
81
+ * Examine the diff presented between the two branches to make sure there is nothing unexpected.
82
+ * Write a good pull request description:
83
+ * While there is no strict template that our contributors follow, we would like them to
84
+ sufficiently summarize and motivate the changes they are proposing. We recommend all pull requests,
85
+ at least indirectly, address the following points.
86
+ * Is this pull request important and why?
87
+ * Is it addressing an issue? If so, what issue? (provide links for convenience please)
88
+ * Is this a new feature? If so, why is it useful and/or necessary?
89
+ * Are there background references and documents that reviewers should be aware of to properly assess this change?
90
+ * Note: make sure to point out any design and architectural decisions that you made and the rationale behind them.
91
+ * Note: if you have been working with a specific user and would like them to review your work, make sure you mention them using (@<username>)
92
+ * Submit the pull request and iterate with feedback.
93
+ 3. Merge and Release
94
+ * Getting approval:
95
+ * You will have to iterate on your changes with feedback from other collaborators to reach a point
96
+ where your pull request can be safely merged.
97
+ * To avoid too many comments on style and convention, make sure that you have a
98
+ look at our style section below before creating a pull request.
99
+ * Eventually, someone from the zstd team will approve your pull request and not long after merge it into
100
+ the dev branch.
101
+ * Housekeeping:
102
+ * Most PRs are linked with one or more Github issues. If this is the case for your PR, make sure
103
+ the corresponding issue is mentioned. If your change 'fixes' or completely addresses the
104
+ issue at hand, then please indicate this by requesting that an issue be closed by commenting.
105
+ * Just because your changes have been merged does not mean the topic or larger issue is complete. Remember
106
+ that the change must make it to an official zstd release for it to be meaningful. We recommend
107
+ that contributors track the activity on their pull request and corresponding issue(s) page(s) until
108
+ their change makes it to the next release of zstd. Users will often discover bugs in your code or
109
+ suggest ways to refine and improve your initial changes even after the pull request is merged.
110
+
111
+ ## Static Analysis
112
+ Static analysis is a process for examining the correctness or validity of a program without actually
113
+ executing it. It usually helps us find many simple bugs. Zstd uses clang's `scan-build` tool for
114
+ static analysis. You can install it by following the instructions for your OS on https://clang-analyzer.llvm.org/scan-build.
115
+
116
+ Once installed, you can ensure that our static analysis tests pass on your local development machine
117
+ by running:
118
+ ```
119
+ make staticAnalyze
120
+ ```
121
+
122
+ In general, you can use `scan-build` to static analyze any build script. For example, to static analyze
123
+ just `contrib/largeNbDicts` and nothing else, you can run:
124
+
125
+ ```
126
+ scan-build make -C contrib/largeNbDicts largeNbDicts
127
+ ```
128
+
129
+ ### Pitfalls of static analysis
130
+ `scan-build` is part of our regular CI suite. Other static analyzers are not.
131
+
132
+ It can be useful to look at additional static analyzers once in a while (and we do), but it's not a good idea to multiply the nb of analyzers run continuously at each commit and PR. The reasons are :
133
+
134
+ - Static analyzers are full of false positive. The signal to noise ratio is actually pretty low.
135
+ - A good CI policy is "zero-warning tolerance". That means that all issues must be solved, including false positives. This quickly becomes a tedious workload.
136
+ - Multiple static analyzers will feature multiple kind of false positives, sometimes applying to the same code but in different ways leading to :
137
+ + torteous code, trying to please multiple constraints, hurting readability and therefore maintenance. Sometimes, such complexity introduce other more subtle bugs, that are just out of scope of the analyzers.
138
+ + sometimes, these constraints are mutually exclusive : if one try to solve one, the other static analyzer will complain, they can't be both happy at the same time.
139
+ - As if that was not enough, the list of false positives change with each version. It's hard enough to follow one static analyzer, but multiple ones with their own update agenda, this quickly becomes a massive velocity reducer.
140
+
141
+ This is different from running a static analyzer once in a while, looking at the output, and __cherry picking__ a few warnings that seem helpful, either because they detected a genuine risk of bug, or because it helps expressing the code in a way which is more readable or more difficult to misuse. These kind of reports can be useful, and are accepted.
142
+
143
+ ## Continuous Integration
144
+ CI tests run every time a pull request (PR) is created or updated. The exact tests
145
+ that get run will depend on the destination branch you specify. Some tests take
146
+ longer to run than others. Currently, our CI is set up to run a short
147
+ series of tests when creating a PR to the dev branch and a longer series of tests
148
+ when creating a PR to the release branch. You can look in the configuration files
149
+ of the respective CI platform for more information on what gets run when.
150
+
151
+ Most people will just want to create a PR with the destination set to their local dev
152
+ branch of zstd. You can then find the status of the tests on the PR's page. You can also
153
+ re-run tests and cancel running tests from the PR page or from the respective CI's dashboard.
154
+
155
+ Almost all of zstd's CI runs on GitHub Actions (configured at `.github/workflows`), which will automatically run on PRs to your
156
+ own fork. A small number of tests run on other services (e.g. Travis CI, Circle CI, Appveyor).
157
+ These require work to set up on your local fork, and (at least for Travis CI) cost money.
158
+ Therefore, if the PR on your local fork passes GitHub Actions, feel free to submit a PR
159
+ against the main repo.
160
+
161
+ ### Third-party CI
162
+ A small number of tests cannot run on GitHub Actions, or have yet to be migrated.
163
+ For these, we use a variety of third-party services (listed below). It is not necessary to set
164
+ these up on your fork in order to contribute to zstd; however, we do link to instructions for those
165
+ who want earlier signal.
166
+
167
+ | Service | Purpose | Setup Links | Config Path |
168
+ |-----------|------------------------------------------------------------------------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------|------------------------|
169
+ | Travis CI | Used for testing on non-x86 architectures such as PowerPC | https://docs.travis-ci.com/user/tutorial/#to-get-started-with-travis-ci-using-github <br> https://github.com/marketplace/travis-ci | `.travis.yml` |
170
+ | AppVeyor | Used for some Windows testing (e.g. cygwin, mingw) | https://www.appveyor.com/blog/2018/10/02/github-apps-integration/ <br> https://github.com/marketplace/appveyor | `appveyor.yml` |
171
+ | Cirrus CI | Used for testing on FreeBSD | https://github.com/marketplace/cirrus-ci/ | `.cirrus.yml` |
172
+ | Circle CI | Historically was used to provide faster signal,<br/> but we may be able to migrate these to Github Actions | https://circleci.com/docs/2.0/getting-started/#setting-up-circleci <br> https://youtu.be/Js3hMUsSZ2c <br> https://circleci.com/docs/2.0/enable-checks/ | `.circleci/config.yml` |
173
+
174
+ Note: the instructions linked above mostly cover how to set up a repository with CI from scratch.
175
+ The general idea should be the same for setting up CI on your fork of zstd, but you may have to
176
+ follow slightly different steps. In particular, please ignore any instructions related to setting up
177
+ config files (since zstd already has configs for each of these services).
178
+
179
+ ## Performance
180
+ Performance is extremely important for zstd and we only merge pull requests whose performance
181
+ landscape and corresponding trade-offs have been adequately analyzed, reproduced, and presented.
182
+ This high bar for performance means that every PR which has the potential to
183
+ impact performance takes a very long time for us to properly review. That being said, we
184
+ always welcome contributions to improve performance (or worsen performance for the trade-off of
185
+ something else). Please keep the following in mind before submitting a performance related PR:
186
+
187
+ 1. Zstd isn't as old as gzip but it has been around for time now and its evolution is
188
+ very well documented via past Github issues and pull requests. It may be the case that your
189
+ particular performance optimization has already been considered in the past. Please take some
190
+ time to search through old issues and pull requests using keywords specific to your
191
+ would-be PR. Of course, just because a topic has already been discussed (and perhaps rejected
192
+ on some grounds) in the past, doesn't mean it isn't worth bringing up again. But even in that case,
193
+ it will be helpful for you to have context from that topic's history before contributing.
194
+ 2. The distinction between noise and actual performance gains can unfortunately be very subtle
195
+ especially when microbenchmarking extremely small wins or losses. The only remedy to getting
196
+ something subtle merged is extensive benchmarking. You will be doing us a great favor if you
197
+ take the time to run extensive, long-duration, and potentially cross-(os, platform, process, etc)
198
+ benchmarks on your end before submitting a PR. Of course, you will not be able to benchmark
199
+ your changes on every single processor and os out there (and neither will we) but do that best
200
+ you can:) We've adding some things to think about when benchmarking below in the Benchmarking
201
+ Performance section which might be helpful for you.
202
+ 3. Optimizing performance for a certain OS, processor vendor, compiler, or network system is a perfectly
203
+ legitimate thing to do as long as it does not harm the overall performance health of Zstd.
204
+ This is a hard balance to strike but please keep in mind other aspects of Zstd when
205
+ submitting changes that are clang-specific, windows-specific, etc.
206
+
207
+ ## Benchmarking Performance
208
+ Performance microbenchmarking is a tricky subject but also essential for Zstd. We value empirical
209
+ testing over theoretical speculation. This guide it not perfect but for most scenarios, it
210
+ is a good place to start.
211
+
212
+ ### Stability
213
+ Unfortunately, the most important aspect in being able to benchmark reliably is to have a stable
214
+ benchmarking machine. A virtual machine, a machine with shared resources, or your laptop
215
+ will typically not be stable enough to obtain reliable benchmark results. If you can get your
216
+ hands on a desktop, this is usually a better scenario.
217
+
218
+ Of course, benchmarking can be done on non-hyper-stable machines as well. You will just have to
219
+ do a little more work to ensure that you are in fact measuring the changes you've made not and
220
+ noise. Here are some things you can do to make your benchmarks more stable:
221
+
222
+ 1. The most simple thing you can do to drastically improve the stability of your benchmark is
223
+ to run it multiple times and then aggregate the results of those runs. As a general rule of
224
+ thumb, the smaller the change you are trying to measure, the more samples of benchmark runs
225
+ you will have to aggregate over to get reliable results. Here are some additional things to keep in
226
+ mind when running multiple trials:
227
+ * How you aggregate your samples are important. You might be tempted to use the mean of your
228
+ results. While this is certainly going to be a more stable number than a raw single sample
229
+ benchmark number, you might have more luck by taking the median. The mean is not robust to
230
+ outliers whereas the median is. Better still, you could simply take the fastest speed your
231
+ benchmark achieved on each run since that is likely the fastest your process will be
232
+ capable of running your code. In our experience, this (aggregating by just taking the sample
233
+ with the fastest running time) has been the most stable approach.
234
+ * The more samples you have, the more stable your benchmarks should be. You can verify
235
+ your improved stability by looking at the size of your confidence intervals as you
236
+ increase your sample count. These should get smaller and smaller. Eventually hopefully
237
+ smaller than the performance win you are expecting.
238
+ * Most processors will take some time to get `hot` when running anything. The observations
239
+ you collect during that time period will very different from the true performance number. Having
240
+ a very large number of sample will help alleviate this problem slightly but you can also
241
+ address is directly by simply not including the first `n` iterations of your benchmark in
242
+ your aggregations. You can determine `n` by simply looking at the results from each iteration
243
+ and then hand picking a good threshold after which the variance in results seems to stabilize.
244
+ 2. You cannot really get reliable benchmarks if your host machine is simultaneously running
245
+ another cpu/memory-intensive application in the background. If you are running benchmarks on your
246
+ personal laptop for instance, you should close all applications (including your code editor and
247
+ browser) before running your benchmarks. You might also have invisible background applications
248
+ running. You can see what these are by looking at either Activity Monitor on Mac or Task Manager
249
+ on Windows. You will get more stable benchmark results of you end those processes as well.
250
+ * If you have multiple cores, you can even run your benchmark on a reserved core to prevent
251
+ pollution from other OS and user processes. There are a number of ways to do this depending
252
+ on your OS:
253
+ * On linux boxes, you have use https://github.com/lpechacek/cpuset.
254
+ * On Windows, you can "Set Processor Affinity" using https://www.thewindowsclub.com/processor-affinity-windows
255
+ * On Mac, you can try to use their dedicated affinity API https://developer.apple.com/library/archive/releasenotes/Performance/RN-AffinityAPI/#//apple_ref/doc/uid/TP40006635-CH1-DontLinkElementID_2
256
+ 3. To benchmark, you will likely end up writing a separate c/c++ program that will link libzstd.
257
+ Dynamically linking your library will introduce some added variation (not a large amount but
258
+ definitely some). Statically linking libzstd will be more stable. Static libraries should
259
+ be enabled by default when building zstd.
260
+ 4. Use a profiler with a good high resolution timer. See the section below on profiling for
261
+ details on this.
262
+ 5. Disable frequency scaling, turbo boost and address space randomization (this will vary by OS)
263
+ 6. Try to avoid storage. On some systems you can use tmpfs. Putting the program, inputs and outputs on
264
+ tmpfs avoids touching a real storage system, which can have a pretty big variability.
265
+
266
+ Also check our LLVM's guide on benchmarking here: https://llvm.org/docs/Benchmarking.html
267
+
268
+ ### Zstd benchmark
269
+ The fastest signal you can get regarding your performance changes is via the in-build zstd cli
270
+ bench option. You can run Zstd as you typically would for your scenario using some set of options
271
+ and then additionally also specify the `-b#` option. Doing this will run our benchmarking pipeline
272
+ for that options you have just provided. If you want to look at the internals of how this
273
+ benchmarking script works, you can check out programs/benchzstd.c
274
+
275
+ For example: say you have made a change that you believe improves the speed of zstd level 1. The
276
+ very first thing you should use to asses whether you actually achieved any sort of improvement
277
+ is `zstd -b`. You might try to do something like this. Note: you can use the `-i` option to
278
+ specify a running time for your benchmark in seconds (default is 3 seconds).
279
+ Usually, the longer the running time, the more stable your results will be.
280
+
281
+ ```
282
+ $ git checkout <commit-before-your-change>
283
+ $ make && cp zstd zstd-old
284
+ $ git checkout <commit-after-your-change>
285
+ $ make && cp zstd zstd-new
286
+ $ zstd-old -i5 -b1 <your-test-data>
287
+ 1<your-test-data> : 8990 -> 3992 (2.252), 302.6 MB/s , 626.4 MB/s
288
+ $ zstd-new -i5 -b1 <your-test-data>
289
+ 1<your-test-data> : 8990 -> 3992 (2.252), 302.8 MB/s , 628.4 MB/s
290
+ ```
291
+
292
+ Unless your performance win is large enough to be visible despite the intrinsic noise
293
+ on your computer, benchzstd alone will likely not be enough to validate the impact of your
294
+ changes. For example, the results of the example above indicate that effectively nothing
295
+ changed but there could be a small <3% improvement that the noise on the host machine
296
+ obscured. So unless you see a large performance win (10-15% consistently) using just
297
+ this method of evaluation will not be sufficient.
298
+
299
+ ### Profiling
300
+ There are a number of great profilers out there. We're going to briefly mention how you can
301
+ profile your code using `instruments` on mac, `perf` on linux and `visual studio profiler`
302
+ on windows.
303
+
304
+ Say you have an idea for a change that you think will provide some good performance gains
305
+ for level 1 compression on Zstd. Typically this means, you have identified a section of
306
+ code that you think can be made to run faster.
307
+
308
+ The first thing you will want to do is make sure that the piece of code is actually taking up
309
+ a notable amount of time to run. It is usually not worth optimizing something which accounts for less than
310
+ 0.0001% of the total running time. Luckily, there are tools to help with this.
311
+ Profilers will let you see how much time your code spends inside a particular function.
312
+ If your target code snippet is only part of a function, it might be worth trying to
313
+ isolate that snippet by moving it to its own function (this is usually not necessary but
314
+ might be).
315
+
316
+ Most profilers (including the profilers discussed below) will generate a call graph of
317
+ functions for you. Your goal will be to find your function of interest in this call graph
318
+ and then inspect the time spent inside of it. You might also want to to look at the
319
+ annotated assembly which most profilers will provide you with.
320
+
321
+ #### Instruments
322
+ We will once again consider the scenario where you think you've identified a piece of code
323
+ whose performance can be improved upon. Follow these steps to profile your code using
324
+ Instruments.
325
+
326
+ 1. Open Instruments
327
+ 2. Select `Time Profiler` from the list of standard templates
328
+ 3. Close all other applications except for your instruments window and your terminal
329
+ 4. Run your benchmarking script from your terminal window
330
+ * You will want a benchmark that runs for at least a few seconds (5 seconds will
331
+ usually be long enough). This way the profiler will have something to work with
332
+ and you will have ample time to attach your profiler to this process:)
333
+ * I will just use benchzstd as my bencharmking script for this example:
334
+ ```
335
+ $ zstd -b1 -i5 <my-data> # this will run for 5 seconds
336
+ ```
337
+ 5. Once you run your benchmarking script, switch back over to instruments and attach your
338
+ process to the time profiler. You can do this by:
339
+ * Clicking on the `All Processes` drop down in the top left of the toolbar.
340
+ * Selecting your process from the dropdown. In my case, it is just going to be labeled
341
+ `zstd`
342
+ * Hitting the bright red record circle button on the top left of the toolbar
343
+ 6. You profiler will now start collecting metrics from your benchmarking script. Once
344
+ you think you have collected enough samples (usually this is the case after 3 seconds of
345
+ recording), stop your profiler.
346
+ 7. Make sure that in toolbar of the bottom window, `profile` is selected.
347
+ 8. You should be able to see your call graph.
348
+ * If you don't see the call graph or an incomplete call graph, make sure you have compiled
349
+ zstd and your benchmarking script using debug flags. On mac and linux, this just means
350
+ you will have to supply the `-g` flag alone with your build script. You might also
351
+ have to provide the `-fno-omit-frame-pointer` flag
352
+ 9. Dig down the graph to find your function call and then inspect it by double clicking
353
+ the list item. You will be able to see the annotated source code and the assembly side by
354
+ side.
355
+
356
+ #### Perf
357
+
358
+ This wiki has a pretty detailed tutorial on getting started working with perf so we'll
359
+ leave you to check that out of you're getting started:
360
+
361
+ https://perf.wiki.kernel.org/index.php/Tutorial
362
+
363
+ Some general notes on perf:
364
+ * Use `perf stat -r # <bench-program>` to quickly get some relevant timing and
365
+ counter statistics. Perf uses a high resolution timer and this is likely one
366
+ of the first things your team will run when assessing your PR.
367
+ * Perf has a long list of hardware counters that can be viewed with `perf --list`.
368
+ When measuring optimizations, something worth trying is to make sure the hardware
369
+ counters you expect to be impacted by your change are in fact being so. For example,
370
+ if you expect the L1 cache misses to decrease with your change, you can look at the
371
+ counter `L1-dcache-load-misses`
372
+ * Perf hardware counters will not work on a virtual machine.
373
+
374
+ #### Visual Studio
375
+
376
+ TODO
377
+
378
+ ## Issues
379
+ We use GitHub issues to track public bugs. Please ensure your description is
380
+ clear and has sufficient instructions to be able to reproduce the issue.
381
+
382
+ Facebook has a [bounty program](https://www.facebook.com/whitehat/) for the safe
383
+ disclosure of security bugs. In those cases, please go through the process
384
+ outlined on that page and do not file a public issue.
385
+
386
+ ## Coding Style
387
+ It's a pretty long topic, which is difficult to summarize in a single paragraph.
388
+ As a rule of thumbs, try to imitate the coding style of
389
+ similar lines of codes around your contribution.
390
+ The following is a non-exhaustive list of rules employed in zstd code base:
391
+
392
+ ### C90
393
+ This code base is following strict C90 standard,
394
+ with 2 extensions : 64-bit `long long` types, and variadic macros.
395
+ This rule is applied strictly to code within `lib/` and `programs/`.
396
+ Sub-project in `contrib/` are allowed to use other conventions.
397
+
398
+ ### C++ direct compatibility : symbol mangling
399
+ All public symbol declarations must be wrapped in `extern “C” { … }`,
400
+ so that this project can be compiled as C++98 code,
401
+ and linked into C++ applications.
402
+
403
+ ### Minimal Frugal
404
+ This design requirement is fundamental to preserve the portability of the code base.
405
+ #### Dependencies
406
+ - Reduce dependencies to the minimum possible level.
407
+ Any dependency should be considered “bad” by default,
408
+ and only tolerated because it provides a service in a better way than can be achieved locally.
409
+ The only external dependencies this repository tolerates are
410
+ standard C libraries, and in rare cases, system level headers.
411
+ - Within `lib/`, this policy is even more drastic.
412
+ The only external dependencies allowed are `<assert.h>`, `<stdlib.h>`, `<string.h>`,
413
+ and even then, not directly.
414
+ In particular, no function shall ever allocate on heap directly,
415
+ and must use instead `ZSTD_malloc()` and equivalent.
416
+ Other accepted non-symbol headers are `<stddef.h>` and `<limits.h>`.
417
+ - Within the project, there is a strict hierarchy of dependencies that must be respected.
418
+ `programs/` is allowed to depend on `lib/`, but only its public API.
419
+ Within `lib/`, `lib/common` doesn't depend on any other directory.
420
+ `lib/compress` and `lib/decompress` shall not depend on each other.
421
+ `lib/dictBuilder` can depend on `lib/common` and `lib/compress`, but not `lib/decompress`.
422
+ #### Resources
423
+ - Functions in `lib/` must use very little stack space,
424
+ several dozens of bytes max.
425
+ Everything larger must use the heap allocator,
426
+ or require a scratch buffer to be emplaced manually.
427
+
428
+ ### Naming
429
+ * All public symbols are prefixed with `ZSTD_`
430
+ + private symbols, with a scope limited to their own unit, are free of this restriction.
431
+ However, since `libzstd` source code can be amalgamated,
432
+ each symbol name must attempt to be (and remain) unique.
433
+ Avoid too generic names that could become ground for future collisions.
434
+ This generally implies usage of some form of prefix.
435
+ * For symbols (functions and variables), naming convention is `PREFIX_camelCase`.
436
+ + In some advanced cases, one can also find :
437
+ - `PREFIX_prefix2_camelCase`
438
+ - `PREFIX_camelCase_extendedQualifier`
439
+ * Multi-words names generally consist of an action followed by object:
440
+ - for example : `ZSTD_createCCtx()`
441
+ * Prefer positive actions
442
+ - `goBackward` rather than `notGoForward`
443
+ * Type names (`struct`, etc.) follow similar convention,
444
+ except that they are allowed and even invited to start by an Uppercase letter.
445
+ Example : `ZSTD_CCtx`, `ZSTD_CDict`
446
+ * Macro names are all Capital letters.
447
+ The same composition rules (`PREFIX_NAME_QUALIFIER`) apply.
448
+ * File names are all lowercase letters.
449
+ The convention is `snake_case`.
450
+ File names **must** be unique across the entire code base,
451
+ even when they stand in clearly separated directories.
452
+
453
+ ### Qualifiers
454
+ * This code base is `const` friendly, if not `const` fanatical.
455
+ Any variable that can be `const` (aka. read-only) **must** be `const`.
456
+ Any pointer which content will not be modified must be `const`.
457
+ This property is then controlled at compiler level.
458
+ `const` variables are an important signal to readers that this variable isn’t modified.
459
+ Conversely, non-const variables are a signal to readers to watch out for modifications later on in the function.
460
+ * If a function must be inlined, mention it explicitly,
461
+ using project's own portable macros, such as `FORCE_INLINE_ATTR`,
462
+ defined in `lib/common/compiler.h`.
463
+
464
+ ### Debugging
465
+ * **Assertions** are welcome, and should be used very liberally,
466
+ to control any condition the code expects for its correct execution.
467
+ These assertion checks will be run in debug builds, and disabled in production.
468
+ * For traces, this project provides its own debug macros,
469
+ in particular `DEBUGLOG(level, ...)`, defined in `lib/common/debug.h`.
470
+
471
+ ### Code documentation
472
+ * Avoid code documentation that merely repeats what the code is already stating.
473
+ Whenever applicable, prefer employing the code as the primary way to convey explanations.
474
+ Example 1 : `int nbTokens = n;` instead of `int i = n; /* i is a nb of tokens *./`.
475
+ Example 2 : `assert(size > 0);` instead of `/* here, size should be positive */`.
476
+ * At declaration level, the documentation explains how to use the function or variable
477
+ and when applicable why it's needed, of the scenarios where it can be useful.
478
+ * At implementation level, the documentation explains the general outline of the algorithm employed,
479
+ and when applicable why this specific choice was preferred.
480
+
481
+ ### General layout
482
+ * 4 spaces for indentation rather than tabs
483
+ * Code documentation shall directly precede function declaration or implementation
484
+ * Function implementations and its code documentation should be preceded and followed by an empty line
485
+
486
+
487
+ ## License
488
+ By contributing to Zstandard, you agree that your contributions will be licensed
489
+ under both the [LICENSE](LICENSE) file and the [COPYING](COPYING) file in the root directory of this source tree.
SPANN/ThirdParty/zstd/Makefile ADDED
@@ -0,0 +1,439 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ################################################################
2
+ # Copyright (c) 2015-2021, Yann Collet, Facebook, Inc.
3
+ # All rights reserved.
4
+ #
5
+ # This source code is licensed under both the BSD-style license (found in the
6
+ # LICENSE file in the root directory of this source tree) and the GPLv2 (found
7
+ # in the COPYING file in the root directory of this source tree).
8
+ # You may select, at your option, one of the above-listed licenses.
9
+ # ################################################################
10
+
11
+ # verbose mode (print commands) on V=1 or VERBOSE=1
12
+ Q = $(if $(filter 1,$(V) $(VERBOSE)),,@)
13
+
14
+ PRGDIR = programs
15
+ ZSTDDIR = lib
16
+ BUILDIR = build
17
+ ZWRAPDIR = zlibWrapper
18
+ TESTDIR = tests
19
+ FUZZDIR = $(TESTDIR)/fuzz
20
+
21
+ # Define nul output
22
+ VOID = /dev/null
23
+
24
+ # When cross-compiling from linux to windows, you might
25
+ # need to specify this as "Windows." Fedora build fails
26
+ # without it.
27
+ #
28
+ # Note: mingw-w64 build from linux to windows does not
29
+ # fail on other tested distros (ubuntu, debian) even
30
+ # without manually specifying the TARGET_SYSTEM.
31
+ TARGET_SYSTEM ?= $(OS)
32
+ CP ?= cp
33
+
34
+ ifneq (,$(filter Windows%,$(TARGET_SYSTEM)))
35
+ EXT =.exe
36
+ else
37
+ EXT =
38
+ endif
39
+
40
+ ## default: Build lib-release and zstd-release
41
+ .PHONY: default
42
+ default: lib-release zstd-release
43
+
44
+ .PHONY: all
45
+ all: allmost examples manual contrib
46
+
47
+ .PHONY: allmost
48
+ allmost: allzstd zlibwrapper
49
+
50
+ # skip zwrapper, can't build that on alternate architectures without the proper zlib installed
51
+ .PHONY: allzstd
52
+ allzstd: lib
53
+ $(Q)$(MAKE) -C $(PRGDIR) all
54
+ $(Q)$(MAKE) -C $(TESTDIR) all
55
+
56
+ .PHONY: all32
57
+ all32:
58
+ $(MAKE) -C $(PRGDIR) zstd32
59
+ $(MAKE) -C $(TESTDIR) all32
60
+
61
+ .PHONY: lib lib-release lib-mt lib-nomt
62
+ lib lib-release lib-mt lib-nomt:
63
+ $(Q)$(MAKE) -C $(ZSTDDIR) $@
64
+
65
+ .PHONY: zstd zstd-release
66
+ zstd zstd-release:
67
+ $(Q)$(MAKE) -C $(PRGDIR) $@
68
+ $(Q)ln -sf $(PRGDIR)/zstd$(EXT) zstd$(EXT)
69
+
70
+ .PHONY: zstdmt
71
+ zstdmt:
72
+ $(Q)$(MAKE) -C $(PRGDIR) $@
73
+ $(Q)$(CP) $(PRGDIR)/zstd$(EXT) ./zstdmt$(EXT)
74
+
75
+ .PHONY: zlibwrapper
76
+ zlibwrapper: lib
77
+ $(MAKE) -C $(ZWRAPDIR) all
78
+
79
+ ## test: run long-duration tests
80
+ .PHONY: test
81
+ DEBUGLEVEL ?= 1
82
+ test: MOREFLAGS += -g -Werror
83
+ test:
84
+ DEBUGLEVEL=$(DEBUGLEVEL) MOREFLAGS="$(MOREFLAGS)" $(MAKE) -j -C $(PRGDIR) allVariants
85
+ $(MAKE) -C $(TESTDIR) $@
86
+ ZSTD=../../programs/zstd $(MAKE) -C doc/educational_decoder $@
87
+
88
+ ## shortest: same as `make check`
89
+ .PHONY: shortest
90
+ shortest:
91
+ $(Q)$(MAKE) -C $(TESTDIR) $@
92
+
93
+ ## check: run basic tests for `zstd` cli
94
+ .PHONY: check
95
+ check: shortest
96
+
97
+ .PHONY: automated_benchmarking
98
+ automated_benchmarking:
99
+ $(MAKE) -C $(TESTDIR) $@
100
+
101
+ .PHONY: benchmarking
102
+ benchmarking: automated_benchmarking
103
+
104
+ ## examples: build all examples in `examples/` directory
105
+ .PHONY: examples
106
+ examples: lib
107
+ $(MAKE) -C examples all
108
+
109
+ ## manual: generate API documentation in html format
110
+ .PHONY: manual
111
+ manual:
112
+ $(MAKE) -C contrib/gen_html $@
113
+
114
+ ## man: generate man page
115
+ .PHONY: man
116
+ man:
117
+ $(MAKE) -C programs $@
118
+
119
+ ## contrib: build all supported projects in `/contrib` directory
120
+ .PHONY: contrib
121
+ contrib: lib
122
+ $(MAKE) -C contrib/pzstd all
123
+ $(MAKE) -C contrib/seekable_format/examples all
124
+ $(MAKE) -C contrib/seekable_format/tests test
125
+ $(MAKE) -C contrib/largeNbDicts all
126
+ cd build/single_file_libs/ ; ./build_decoder_test.sh
127
+ cd build/single_file_libs/ ; ./build_library_test.sh
128
+
129
+ .PHONY: cleanTabs
130
+ cleanTabs:
131
+ cd contrib; ./cleanTabs
132
+
133
+ .PHONY: clean
134
+ clean:
135
+ $(Q)$(MAKE) -C $(ZSTDDIR) $@ > $(VOID)
136
+ $(Q)$(MAKE) -C $(PRGDIR) $@ > $(VOID)
137
+ $(Q)$(MAKE) -C $(TESTDIR) $@ > $(VOID)
138
+ $(Q)$(MAKE) -C $(ZWRAPDIR) $@ > $(VOID)
139
+ $(Q)$(MAKE) -C examples/ $@ > $(VOID)
140
+ $(Q)$(MAKE) -C contrib/gen_html $@ > $(VOID)
141
+ $(Q)$(MAKE) -C contrib/pzstd $@ > $(VOID)
142
+ $(Q)$(MAKE) -C contrib/seekable_format/examples $@ > $(VOID)
143
+ $(Q)$(MAKE) -C contrib/seekable_format/tests $@ > $(VOID)
144
+ $(Q)$(MAKE) -C contrib/largeNbDicts $@ > $(VOID)
145
+ $(Q)$(RM) zstd$(EXT) zstdmt$(EXT) tmp*
146
+ $(Q)$(RM) -r lz4
147
+ @echo Cleaning completed
148
+
149
+ #------------------------------------------------------------------------------
150
+ # make install is validated only for Linux, macOS, Hurd and some BSD targets
151
+ #------------------------------------------------------------------------------
152
+ ifneq (,$(filter $(shell uname),Linux Darwin GNU/kFreeBSD GNU OpenBSD FreeBSD DragonFly NetBSD MSYS_NT Haiku AIX))
153
+
154
+ HOST_OS = POSIX
155
+
156
+ MKDIR ?= mkdir -p
157
+
158
+ HAVE_COLORNEVER = $(shell echo a | egrep --color=never a > /dev/null 2> /dev/null && echo 1 || echo 0)
159
+ EGREP_OPTIONS ?=
160
+ ifeq ($HAVE_COLORNEVER, 1)
161
+ EGREP_OPTIONS += --color=never
162
+ endif
163
+ EGREP = egrep $(EGREP_OPTIONS)
164
+
165
+ # Print a two column output of targets and their description. To add a target description, put a
166
+ # comment in the Makefile with the format "## <TARGET>: <DESCRIPTION>". For example:
167
+ #
168
+ ## list: Print all targets and their descriptions (if provided)
169
+ .PHONY: list
170
+ list:
171
+ $(Q)TARGETS=$$($(MAKE) -pRrq -f $(lastword $(MAKEFILE_LIST)) : 2>/dev/null \
172
+ | awk -v RS= -F: '/^# File/,/^# Finished Make data base/ {if ($$1 !~ "^[#.]") {print $$1}}' \
173
+ | $(EGREP) -v -e '^[^[:alnum:]]' | sort); \
174
+ { \
175
+ printf "Target Name\tDescription\n"; \
176
+ printf "%0.s-" {1..16}; printf "\t"; printf "%0.s-" {1..40}; printf "\n"; \
177
+ for target in $$TARGETS; do \
178
+ line=$$($(EGREP) "^##[[:space:]]+$$target:" $(lastword $(MAKEFILE_LIST))); \
179
+ description=$$(echo $$line | awk '{i=index($$0,":"); print substr($$0,i+1)}' | xargs); \
180
+ printf "$$target\t$$description\n"; \
181
+ done \
182
+ } | column -t -s $$'\t'
183
+
184
+ .PHONY: install armtest usan asan uasan msan asan32
185
+ install:
186
+ $(Q)$(MAKE) -C $(ZSTDDIR) $@
187
+ $(Q)$(MAKE) -C $(PRGDIR) $@
188
+
189
+ .PHONY: uninstall
190
+ uninstall:
191
+ $(Q)$(MAKE) -C $(ZSTDDIR) $@
192
+ $(Q)$(MAKE) -C $(PRGDIR) $@
193
+
194
+ .PHONY: travis-install
195
+ travis-install:
196
+ $(MAKE) install PREFIX=~/install_test_dir
197
+
198
+ .PHONY: gcc5build gcc6build gcc7build clangbuild m32build armbuild aarch64build ppcbuild ppc64build
199
+ gcc5build: clean
200
+ gcc-5 -v
201
+ CC=gcc-5 $(MAKE) all MOREFLAGS="-Werror"
202
+
203
+ gcc6build: clean
204
+ gcc-6 -v
205
+ CC=gcc-6 $(MAKE) all MOREFLAGS="-Werror"
206
+
207
+ gcc7build: clean
208
+ gcc-7 -v
209
+ CC=gcc-7 $(MAKE) all MOREFLAGS="-Werror"
210
+
211
+ clangbuild: clean
212
+ clang -v
213
+ CXX=clang++ CC=clang CFLAGS="-Werror -Wconversion -Wno-sign-conversion -Wdocumentation" $(MAKE) all
214
+
215
+ m32build: clean
216
+ gcc -v
217
+ $(MAKE) all32
218
+
219
+ armbuild: clean
220
+ CC=arm-linux-gnueabi-gcc CFLAGS="-Werror" $(MAKE) allzstd
221
+
222
+ aarch64build: clean
223
+ CC=aarch64-linux-gnu-gcc CFLAGS="-Werror -O0" $(MAKE) allzstd
224
+
225
+ ppcbuild: clean
226
+ CC=powerpc-linux-gnu-gcc CFLAGS="-m32 -Wno-attributes -Werror" $(MAKE) -j allzstd
227
+
228
+ ppc64build: clean
229
+ CC=powerpc-linux-gnu-gcc CFLAGS="-m64 -Werror" $(MAKE) -j allzstd
230
+
231
+ .PHONY: armfuzz aarch64fuzz ppcfuzz ppc64fuzz
232
+ armfuzz: clean
233
+ CC=arm-linux-gnueabi-gcc QEMU_SYS=qemu-arm-static MOREFLAGS="-static" FUZZER_FLAGS=--no-big-tests $(MAKE) -C $(TESTDIR) fuzztest
234
+
235
+ aarch64fuzz: clean
236
+ ld -v
237
+ CC=aarch64-linux-gnu-gcc QEMU_SYS=qemu-aarch64-static MOREFLAGS="-static" FUZZER_FLAGS=--no-big-tests $(MAKE) -C $(TESTDIR) fuzztest
238
+
239
+ ppcfuzz: clean
240
+ CC=powerpc-linux-gnu-gcc QEMU_SYS=qemu-ppc-static MOREFLAGS="-static" FUZZER_FLAGS=--no-big-tests $(MAKE) -C $(TESTDIR) fuzztest
241
+
242
+ ppc64fuzz: clean
243
+ CC=powerpc-linux-gnu-gcc QEMU_SYS=qemu-ppc64-static MOREFLAGS="-m64 -static" FUZZER_FLAGS=--no-big-tests $(MAKE) -C $(TESTDIR) fuzztest
244
+
245
+ .PHONY: cxxtest gcc5test gcc6test armtest aarch64test ppctest ppc64test
246
+ cxxtest: CXXFLAGS += -Wall -Wextra -Wundef -Wshadow -Wcast-align -Werror
247
+ cxxtest: clean
248
+ $(MAKE) -C $(PRGDIR) all CC="$(CXX) -Wno-deprecated" CFLAGS="$(CXXFLAGS)" # adding -Wno-deprecated to avoid clang++ warning on dealing with C files directly
249
+
250
+ gcc5test: clean
251
+ gcc-5 -v
252
+ $(MAKE) all CC=gcc-5 MOREFLAGS="-Werror"
253
+
254
+ gcc6test: clean
255
+ gcc-6 -v
256
+ $(MAKE) all CC=gcc-6 MOREFLAGS="-Werror"
257
+
258
+ armtest: clean
259
+ $(MAKE) -C $(TESTDIR) datagen # use native, faster
260
+ $(MAKE) -C $(TESTDIR) test CC=arm-linux-gnueabi-gcc QEMU_SYS=qemu-arm-static ZSTDRTTEST= MOREFLAGS="-Werror -static" FUZZER_FLAGS=--no-big-tests
261
+
262
+ aarch64test:
263
+ $(MAKE) -C $(TESTDIR) datagen # use native, faster
264
+ $(MAKE) -C $(TESTDIR) test CC=aarch64-linux-gnu-gcc QEMU_SYS=qemu-aarch64-static ZSTDRTTEST= MOREFLAGS="-Werror -static" FUZZER_FLAGS=--no-big-tests
265
+
266
+ ppctest: clean
267
+ $(MAKE) -C $(TESTDIR) datagen # use native, faster
268
+ $(MAKE) -C $(TESTDIR) test CC=powerpc-linux-gnu-gcc QEMU_SYS=qemu-ppc-static ZSTDRTTEST= MOREFLAGS="-Werror -Wno-attributes -static" FUZZER_FLAGS=--no-big-tests
269
+
270
+ ppc64test: clean
271
+ $(MAKE) -C $(TESTDIR) datagen # use native, faster
272
+ $(MAKE) -C $(TESTDIR) test CC=powerpc-linux-gnu-gcc QEMU_SYS=qemu-ppc64-static ZSTDRTTEST= MOREFLAGS="-m64 -static" FUZZER_FLAGS=--no-big-tests
273
+
274
+ .PHONY: arm-ppc-compilation
275
+ arm-ppc-compilation:
276
+ $(MAKE) -C $(PRGDIR) clean zstd CC=arm-linux-gnueabi-gcc QEMU_SYS=qemu-arm-static ZSTDRTTEST= MOREFLAGS="-Werror -static"
277
+ $(MAKE) -C $(PRGDIR) clean zstd CC=aarch64-linux-gnu-gcc QEMU_SYS=qemu-aarch64-static ZSTDRTTEST= MOREFLAGS="-Werror -static"
278
+ $(MAKE) -C $(PRGDIR) clean zstd CC=powerpc-linux-gnu-gcc QEMU_SYS=qemu-ppc-static ZSTDRTTEST= MOREFLAGS="-Werror -Wno-attributes -static"
279
+ $(MAKE) -C $(PRGDIR) clean zstd CC=powerpc-linux-gnu-gcc QEMU_SYS=qemu-ppc64-static ZSTDRTTEST= MOREFLAGS="-m64 -static"
280
+
281
+ regressiontest:
282
+ $(MAKE) -C $(FUZZDIR) regressiontest
283
+
284
+ uasanregressiontest:
285
+ $(MAKE) -C $(FUZZDIR) regressiontest CC=clang CXX=clang++ CFLAGS="-O3 -fsanitize=address,undefined" CXXFLAGS="-O3 -fsanitize=address,undefined"
286
+
287
+ msanregressiontest:
288
+ $(MAKE) -C $(FUZZDIR) regressiontest CC=clang CXX=clang++ CFLAGS="-O3 -fsanitize=memory" CXXFLAGS="-O3 -fsanitize=memory"
289
+
290
+ update_regressionResults : REGRESS_RESULTS_DIR := /tmp/regress_results_dir/
291
+ update_regressionResults:
292
+ $(MAKE) -C programs zstd
293
+ $(MAKE) -C tests/regression test
294
+ $(RM) -rf $(REGRESS_RESULTS_DIR)
295
+ $(MKDIR) $(REGRESS_RESULTS_DIR)
296
+ ./tests/regression/test \
297
+ --cache tests/regression/cache \
298
+ --output $(REGRESS_RESULTS_DIR)/results.csv \
299
+ --zstd programs/zstd
300
+ echo "Showing results differences"
301
+ ! diff tests/regression/results.csv $(REGRESS_RESULTS_DIR)/results.csv
302
+ echo "Updating results.csv"
303
+ $(CP) $(REGRESS_RESULTS_DIR)/results.csv tests/regression/results.csv
304
+
305
+
306
+ # run UBsan with -fsanitize-recover=pointer-overflow
307
+ # this only works with recent compilers such as gcc 8+
308
+ usan: clean
309
+ $(MAKE) test CC=clang MOREFLAGS="-g -fno-sanitize-recover=all -fsanitize-recover=pointer-overflow -fsanitize=undefined -Werror"
310
+
311
+ asan: clean
312
+ $(MAKE) test CC=clang MOREFLAGS="-g -fsanitize=address -Werror"
313
+
314
+ asan-%: clean
315
+ LDFLAGS=-fuse-ld=gold MOREFLAGS="-g -fno-sanitize-recover=all -fsanitize=address -Werror" $(MAKE) -C $(TESTDIR) $*
316
+
317
+ msan: clean
318
+ $(MAKE) test CC=clang MOREFLAGS="-g -fsanitize=memory -fno-omit-frame-pointer -Werror" HAVE_LZMA=0 # datagen.c fails this test for no obvious reason
319
+
320
+ msan-%: clean
321
+ LDFLAGS=-fuse-ld=gold MOREFLAGS="-g -fno-sanitize-recover=all -fsanitize=memory -fno-omit-frame-pointer -Werror" FUZZER_FLAGS=--no-big-tests $(MAKE) -C $(TESTDIR) HAVE_LZMA=0 $*
322
+
323
+ asan32: clean
324
+ $(MAKE) -C $(TESTDIR) test32 CC=clang MOREFLAGS="-g -fsanitize=address"
325
+
326
+ uasan: clean
327
+ $(MAKE) test CC=clang MOREFLAGS="-g -fno-sanitize-recover=all -fsanitize-recover=pointer-overflow -fsanitize=address,undefined -Werror"
328
+
329
+ uasan-%: clean
330
+ LDFLAGS=-fuse-ld=gold MOREFLAGS="-g -fno-sanitize-recover=all -fsanitize-recover=pointer-overflow -fsanitize=address,undefined -Werror" $(MAKE) -C $(TESTDIR) $*
331
+
332
+ tsan-%: clean
333
+ LDFLAGS=-fuse-ld=gold MOREFLAGS="-g -fno-sanitize-recover=all -fsanitize=thread -Werror" $(MAKE) -C $(TESTDIR) $* FUZZER_FLAGS=--no-big-tests
334
+
335
+ .PHONY: apt-install
336
+ apt-install:
337
+ sudo apt-get -yq --no-install-suggests --no-install-recommends --force-yes install $(APT_PACKAGES)
338
+
339
+ .PHONY: apt-add-repo
340
+ apt-add-repo:
341
+ sudo add-apt-repository -y ppa:ubuntu-toolchain-r/test
342
+ sudo apt-get update -y -qq
343
+
344
+ .PHONY: ppcinstall arminstall valgrindinstall libc6install gcc6install gcc7install gcc8install gpp6install clang38install lz4install
345
+ ppcinstall:
346
+ APT_PACKAGES="qemu-system-ppc qemu-user-static gcc-powerpc-linux-gnu" $(MAKE) apt-install
347
+
348
+ arminstall:
349
+ APT_PACKAGES="qemu-system-arm qemu-user-static gcc-arm-linux-gnueabi libc6-dev-armel-cross gcc-aarch64-linux-gnu libc6-dev-arm64-cross" $(MAKE) apt-install
350
+
351
+ valgrindinstall:
352
+ APT_PACKAGES="valgrind" $(MAKE) apt-install
353
+
354
+ libc6install:
355
+ APT_PACKAGES="libc6-dev-i386 gcc-multilib" $(MAKE) apt-install
356
+
357
+ gcc6install: apt-add-repo
358
+ APT_PACKAGES="libc6-dev-i386 gcc-multilib gcc-6 gcc-6-multilib" $(MAKE) apt-install
359
+
360
+ gcc7install: apt-add-repo
361
+ APT_PACKAGES="libc6-dev-i386 gcc-multilib gcc-7 gcc-7-multilib" $(MAKE) apt-install
362
+
363
+ gcc8install: apt-add-repo
364
+ APT_PACKAGES="libc6-dev-i386 gcc-multilib gcc-8 gcc-8-multilib" $(MAKE) apt-install
365
+
366
+ gpp6install: apt-add-repo
367
+ APT_PACKAGES="libc6-dev-i386 g++-multilib gcc-6 g++-6 g++-6-multilib" $(MAKE) apt-install
368
+
369
+ clang38install:
370
+ APT_PACKAGES="clang-3.8" $(MAKE) apt-install
371
+
372
+ # Ubuntu 14.04 ships a too-old lz4
373
+ lz4install:
374
+ [ -e lz4 ] || git clone https://github.com/lz4/lz4 && sudo $(MAKE) -C lz4 install
375
+
376
+ endif
377
+
378
+
379
+ CMAKE_PARAMS = -DZSTD_BUILD_CONTRIB:BOOL=ON -DZSTD_BUILD_STATIC:BOOL=ON -DZSTD_BUILD_TESTS:BOOL=ON -DZSTD_ZLIB_SUPPORT:BOOL=ON -DZSTD_LZMA_SUPPORT:BOOL=ON -DCMAKE_BUILD_TYPE=Release
380
+
381
+ ifneq (,$(filter MSYS%,$(shell uname)))
382
+ HOST_OS = MSYS
383
+ CMAKE_PARAMS = -G"MSYS Makefiles" -DCMAKE_BUILD_TYPE=Debug -DZSTD_MULTITHREAD_SUPPORT:BOOL=OFF -DZSTD_BUILD_STATIC:BOOL=ON -DZSTD_BUILD_TESTS:BOOL=ON
384
+ endif
385
+
386
+ #------------------------------------------------------------------------
387
+ # target specific tests
388
+ #------------------------------------------------------------------------
389
+ ifneq (,$(filter $(HOST_OS),MSYS POSIX))
390
+ .PHONY: cmakebuild c89build gnu90build c99build gnu99build c11build bmix64build bmix32build bmi32build staticAnalyze
391
+ cmakebuild:
392
+ cmake --version
393
+ $(RM) -r $(BUILDIR)/cmake/build
394
+ $(MKDIR) $(BUILDIR)/cmake/build
395
+ cd $(BUILDIR)/cmake/build; cmake -DCMAKE_INSTALL_PREFIX:PATH=~/install_test_dir $(CMAKE_PARAMS) ..
396
+ $(MAKE) -C $(BUILDIR)/cmake/build -j4;
397
+ $(MAKE) -C $(BUILDIR)/cmake/build install;
398
+ $(MAKE) -C $(BUILDIR)/cmake/build uninstall;
399
+ cd $(BUILDIR)/cmake/build; ctest -V -L Medium
400
+
401
+ c89build: clean
402
+ $(CC) -v
403
+ CFLAGS="-std=c89 -Werror -O0" $(MAKE) allmost # will fail, due to missing support for `long long`
404
+
405
+ gnu90build: clean
406
+ $(CC) -v
407
+ CFLAGS="-std=gnu90 -Werror -O0" $(MAKE) allmost
408
+
409
+ c99build: clean
410
+ $(CC) -v
411
+ CFLAGS="-std=c99 -Werror -O0" $(MAKE) allmost
412
+
413
+ gnu99build: clean
414
+ $(CC) -v
415
+ CFLAGS="-std=gnu99 -Werror -O0" $(MAKE) allmost
416
+
417
+ c11build: clean
418
+ $(CC) -v
419
+ CFLAGS="-std=c11 -Werror -O0" $(MAKE) allmost
420
+
421
+ bmix64build: clean
422
+ $(CC) -v
423
+ CFLAGS="-O3 -mbmi -Werror" $(MAKE) -C $(TESTDIR) test
424
+
425
+ bmix32build: clean
426
+ $(CC) -v
427
+ CFLAGS="-O3 -mbmi -mx32 -Werror" $(MAKE) -C $(TESTDIR) test
428
+
429
+ bmi32build: clean
430
+ $(CC) -v
431
+ CFLAGS="-O3 -mbmi -m32 -Werror" $(MAKE) -C $(TESTDIR) test
432
+
433
+ # static analyzer test uses clang's scan-build
434
+ # does not analyze zlibWrapper, due to detected issues in zlib source code
435
+ staticAnalyze: SCANBUILD ?= scan-build
436
+ staticAnalyze:
437
+ $(CC) -v
438
+ CC=$(CC) CPPFLAGS=-g $(SCANBUILD) --status-bugs -v $(MAKE) zstd
439
+ endif
SPANN/ThirdParty/zstd/lib/BUCK ADDED
@@ -0,0 +1,232 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ cxx_library(
2
+ name='zstd',
3
+ header_namespace='',
4
+ exported_headers=['zstd.h'],
5
+ visibility=['PUBLIC'],
6
+ deps=[
7
+ ':common',
8
+ ':compress',
9
+ ':decompress',
10
+ ':deprecated',
11
+ ],
12
+ )
13
+
14
+ cxx_library(
15
+ name='compress',
16
+ header_namespace='',
17
+ visibility=['PUBLIC'],
18
+ exported_headers=subdir_glob([
19
+ ('compress', 'zstd*.h'),
20
+ ]),
21
+ srcs=glob(['compress/zstd*.c', 'compress/hist.c']),
22
+ deps=[':common'],
23
+ )
24
+
25
+ cxx_library(
26
+ name='decompress',
27
+ header_namespace='',
28
+ visibility=['PUBLIC'],
29
+ headers=subdir_glob([
30
+ ('decompress', '*_impl.h'),
31
+ ]),
32
+ srcs=glob(['decompress/zstd*.c']),
33
+ deps=[
34
+ ':common',
35
+ ':legacy',
36
+ ],
37
+ )
38
+
39
+ cxx_library(
40
+ name='deprecated',
41
+ header_namespace='',
42
+ visibility=['PUBLIC'],
43
+ exported_headers=subdir_glob([
44
+ ('deprecated', '*.h'),
45
+ ]),
46
+ srcs=glob(['deprecated/*.c']),
47
+ deps=[':common'],
48
+ )
49
+
50
+ cxx_library(
51
+ name='legacy',
52
+ header_namespace='',
53
+ visibility=['PUBLIC'],
54
+ exported_headers=subdir_glob([
55
+ ('legacy', '*.h'),
56
+ ]),
57
+ srcs=glob(['legacy/*.c']),
58
+ deps=[':common'],
59
+ exported_preprocessor_flags=[
60
+ '-DZSTD_LEGACY_SUPPORT=4',
61
+ ],
62
+ )
63
+
64
+ cxx_library(
65
+ name='zdict',
66
+ header_namespace='',
67
+ visibility=['PUBLIC'],
68
+ exported_headers=['zdict.h'],
69
+ headers=subdir_glob([
70
+ ('dictBuilder', 'divsufsort.h'),
71
+ ('dictBuilder', 'cover.h'),
72
+ ]),
73
+ srcs=glob(['dictBuilder/*.c']),
74
+ deps=[':common'],
75
+ )
76
+
77
+ cxx_library(
78
+ name='compiler',
79
+ header_namespace='',
80
+ visibility=['PUBLIC'],
81
+ exported_headers=subdir_glob([
82
+ ('common', 'compiler.h'),
83
+ ]),
84
+ )
85
+
86
+ cxx_library(
87
+ name='cpu',
88
+ header_namespace='',
89
+ visibility=['PUBLIC'],
90
+ exported_headers=subdir_glob([
91
+ ('common', 'cpu.h'),
92
+ ]),
93
+ )
94
+
95
+ cxx_library(
96
+ name='bitstream',
97
+ header_namespace='',
98
+ visibility=['PUBLIC'],
99
+ exported_headers=subdir_glob([
100
+ ('common', 'bitstream.h'),
101
+ ]),
102
+ )
103
+
104
+ cxx_library(
105
+ name='entropy',
106
+ header_namespace='',
107
+ visibility=['PUBLIC'],
108
+ exported_headers=subdir_glob([
109
+ ('common', 'fse.h'),
110
+ ('common', 'huf.h'),
111
+ ]),
112
+ srcs=[
113
+ 'common/entropy_common.c',
114
+ 'common/fse_decompress.c',
115
+ 'compress/fse_compress.c',
116
+ 'compress/huf_compress.c',
117
+ 'decompress/huf_decompress.c',
118
+ ],
119
+ deps=[
120
+ ':debug',
121
+ ':bitstream',
122
+ ':compiler',
123
+ ':errors',
124
+ ':mem',
125
+ ],
126
+ )
127
+
128
+ cxx_library(
129
+ name='errors',
130
+ header_namespace='',
131
+ visibility=['PUBLIC'],
132
+ exported_headers=[
133
+ 'zstd_errors.h',
134
+ 'common/error_private.h',
135
+ ]
136
+ srcs=['common/error_private.c'],
137
+ )
138
+
139
+ cxx_library(
140
+ name='mem',
141
+ header_namespace='',
142
+ visibility=['PUBLIC'],
143
+ exported_headers=subdir_glob([
144
+ ('common', 'mem.h'),
145
+ ]),
146
+ )
147
+
148
+ cxx_library(
149
+ name='pool',
150
+ header_namespace='',
151
+ visibility=['PUBLIC'],
152
+ exported_headers=subdir_glob([
153
+ ('common', 'pool.h'),
154
+ ]),
155
+ srcs=['common/pool.c'],
156
+ deps=[
157
+ ':threading',
158
+ ':zstd_common',
159
+ ],
160
+ )
161
+
162
+ cxx_library(
163
+ name='threading',
164
+ header_namespace='',
165
+ visibility=['PUBLIC'],
166
+ exported_headers=subdir_glob([
167
+ ('common', 'threading.h'),
168
+ ]),
169
+ srcs=['common/threading.c'],
170
+ exported_preprocessor_flags=[
171
+ '-DZSTD_MULTITHREAD',
172
+ ],
173
+ exported_linker_flags=[
174
+ '-pthread',
175
+ ],
176
+ )
177
+
178
+ cxx_library(
179
+ name='xxhash',
180
+ header_namespace='',
181
+ visibility=['PUBLIC'],
182
+ exported_headers=subdir_glob([
183
+ ('common', 'xxhash.h'),
184
+ ]),
185
+ srcs=['common/xxhash.c'],
186
+ exported_preprocessor_flags=[
187
+ '-DXXH_NAMESPACE=ZSTD_',
188
+ ],
189
+ )
190
+
191
+ cxx_library(
192
+ name='zstd_common',
193
+ header_namespace='',
194
+ visibility=['PUBLIC'],
195
+ exported_headers=subdir_glob([
196
+ ('', 'zstd.h'),
197
+ ('common', 'zstd_internal.h'),
198
+ ]),
199
+ srcs=['common/zstd_common.c'],
200
+ deps=[
201
+ ':compiler',
202
+ ':errors',
203
+ ':mem',
204
+ ],
205
+ )
206
+
207
+ cxx_library(
208
+ name='debug',
209
+ header_namespace='',
210
+ visibility=['PUBLIC'],
211
+ exported_headers=subdir_glob([
212
+ ('common', 'debug.h'),
213
+ ]),
214
+ srcs=['common/debug.c'],
215
+ )
216
+
217
+ cxx_library(
218
+ name='common',
219
+ deps=[
220
+ ':debug',
221
+ ':bitstream',
222
+ ':compiler',
223
+ ':cpu',
224
+ ':entropy',
225
+ ':errors',
226
+ ':mem',
227
+ ':pool',
228
+ ':threading',
229
+ ':xxhash',
230
+ ':zstd_common',
231
+ ]
232
+ )
SPANN/ThirdParty/zstd/lib/README.md ADDED
@@ -0,0 +1,217 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Zstandard library files
2
+ ================================
3
+
4
+ The __lib__ directory is split into several sub-directories,
5
+ in order to make it easier to select or exclude features.
6
+
7
+
8
+ #### Building
9
+
10
+ `Makefile` script is provided, supporting [Makefile conventions](https://www.gnu.org/prep/standards/html_node/Makefile-Conventions.html#Makefile-Conventions),
11
+ including commands variables, staged install, directory variables and standard targets.
12
+ - `make` : generates both static and dynamic libraries
13
+ - `make install` : install libraries and headers in target system directories
14
+
15
+ `libzstd` default scope is pretty large, including compression, decompression, dictionary builder,
16
+ and support for decoding legacy formats >= v0.5.0.
17
+ The scope can be reduced on demand (see paragraph _modular build_).
18
+
19
+
20
+ #### Multithreading support
21
+
22
+ When building with `make`, by default the dynamic library is multithreaded and static library is single-threaded (for compatibility reasons).
23
+
24
+ Enabling multithreading requires 2 conditions :
25
+ - set build macro `ZSTD_MULTITHREAD` (`-DZSTD_MULTITHREAD` for `gcc`)
26
+ - for POSIX systems : compile with pthread (`-pthread` compilation flag for `gcc`)
27
+
28
+ For convenience, we provide a build target to generate multi and single threaded libraries:
29
+ - Force enable multithreading on both dynamic and static libraries by appending `-mt` to the target, e.g. `make lib-mt`.
30
+ - Force disable multithreading on both dynamic and static libraries by appending `-nomt` to the target, e.g. `make lib-nomt`.
31
+ - By default, as mentioned before, dynamic library is multithreaded, and static library is single-threaded, e.g. `make lib`.
32
+
33
+ When linking a POSIX program with a multithreaded version of `libzstd`,
34
+ note that it's necessary to invoke the `-pthread` flag during link stage.
35
+
36
+ Multithreading capabilities are exposed
37
+ via the [advanced API defined in `lib/zstd.h`](https://github.com/facebook/zstd/blob/v1.4.3/lib/zstd.h#L351).
38
+
39
+
40
+ #### API
41
+
42
+ Zstandard's stable API is exposed within [lib/zstd.h](zstd.h).
43
+
44
+
45
+ #### Advanced API
46
+
47
+ Optional advanced features are exposed via :
48
+
49
+ - `lib/zstd_errors.h` : translates `size_t` function results
50
+ into a `ZSTD_ErrorCode`, for accurate error handling.
51
+
52
+ - `ZSTD_STATIC_LINKING_ONLY` : if this macro is defined _before_ including `zstd.h`,
53
+ it unlocks access to the experimental API,
54
+ exposed in the second part of `zstd.h`.
55
+ All definitions in the experimental APIs are unstable,
56
+ they may still change in the future, or even be removed.
57
+ As a consequence, experimental definitions shall ___never be used with dynamic library___ !
58
+ Only static linking is allowed.
59
+
60
+
61
+ #### Modular build
62
+
63
+ It's possible to compile only a limited set of features within `libzstd`.
64
+ The file structure is designed to make this selection manually achievable for any build system :
65
+
66
+ - Directory `lib/common` is always required, for all variants.
67
+
68
+ - Compression source code lies in `lib/compress`
69
+
70
+ - Decompression source code lies in `lib/decompress`
71
+
72
+ - It's possible to include only `compress` or only `decompress`, they don't depend on each other.
73
+
74
+ - `lib/dictBuilder` : makes it possible to generate dictionaries from a set of samples.
75
+ The API is exposed in `lib/dictBuilder/zdict.h`.
76
+ This module depends on both `lib/common` and `lib/compress` .
77
+
78
+ - `lib/legacy` : makes it possible to decompress legacy zstd formats, starting from `v0.1.0`.
79
+ This module depends on `lib/common` and `lib/decompress`.
80
+ To enable this feature, define `ZSTD_LEGACY_SUPPORT` during compilation.
81
+ Specifying a number limits versions supported to that version onward.
82
+ For example, `ZSTD_LEGACY_SUPPORT=2` means : "support legacy formats >= v0.2.0".
83
+ Conversely, `ZSTD_LEGACY_SUPPORT=0` means "do __not__ support legacy formats".
84
+ By default, this build macro is set as `ZSTD_LEGACY_SUPPORT=5`.
85
+ Decoding supported legacy format is a transparent capability triggered within decompression functions.
86
+ It's also allowed to invoke legacy API directly, exposed in `lib/legacy/zstd_legacy.h`.
87
+ Each version does also provide its own set of advanced API.
88
+ For example, advanced API for version `v0.4` is exposed in `lib/legacy/zstd_v04.h` .
89
+
90
+ - While invoking `make libzstd`, it's possible to define build macros
91
+ `ZSTD_LIB_COMPRESSION, ZSTD_LIB_DECOMPRESSION`, `ZSTD_LIB_DICTBUILDER`,
92
+ and `ZSTD_LIB_DEPRECATED` as `0` to forgo compilation of the
93
+ corresponding features. This will also disable compilation of all
94
+ dependencies (eg. `ZSTD_LIB_COMPRESSION=0` will also disable
95
+ dictBuilder).
96
+
97
+ - There are a number of options that can help minimize the binary size of
98
+ `libzstd`.
99
+
100
+ The first step is to select the components needed (using the above-described
101
+ `ZSTD_LIB_COMPRESSION` etc.).
102
+
103
+ The next step is to set `ZSTD_LIB_MINIFY` to `1` when invoking `make`. This
104
+ disables various optional components and changes the compilation flags to
105
+ prioritize space-saving.
106
+
107
+ Detailed options: Zstandard's code and build environment is set up by default
108
+ to optimize above all else for performance. In pursuit of this goal, Zstandard
109
+ makes significant trade-offs in code size. For example, Zstandard often has
110
+ more than one implementation of a particular component, with each
111
+ implementation optimized for different scenarios. For example, the Huffman
112
+ decoder has complementary implementations that decode the stream one symbol at
113
+ a time or two symbols at a time. Zstd normally includes both (and dispatches
114
+ between them at runtime), but by defining `HUF_FORCE_DECOMPRESS_X1` or
115
+ `HUF_FORCE_DECOMPRESS_X2`, you can force the use of one or the other, avoiding
116
+ compilation of the other. Similarly, `ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT`
117
+ and `ZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG` force the compilation and use of
118
+ only one or the other of two decompression implementations. The smallest
119
+ binary is achieved by using `HUF_FORCE_DECOMPRESS_X1` and
120
+ `ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT` (implied by `ZSTD_LIB_MINIFY`).
121
+
122
+ For squeezing the last ounce of size out, you can also define
123
+ `ZSTD_NO_INLINE`, which disables inlining, and `ZSTD_STRIP_ERROR_STRINGS`,
124
+ which removes the error messages that are otherwise returned by
125
+ `ZSTD_getErrorName` (implied by `ZSTD_LIB_MINIFY`).
126
+
127
+ Finally, when integrating into your application, make sure you're doing link-
128
+ time optimization and unused symbol garbage collection (via some combination of,
129
+ e.g., `-flto`, `-ffat-lto-objects`, `-fuse-linker-plugin`,
130
+ `-ffunction-sections`, `-fdata-sections`, `-fmerge-all-constants`,
131
+ `-Wl,--gc-sections`, `-Wl,-z,norelro`, and an archiver that understands
132
+ the compiler's intermediate representation, e.g., `AR=gcc-ar`). Consult your
133
+ compiler's documentation.
134
+
135
+ - While invoking `make libzstd`, the build macro `ZSTD_LEGACY_MULTITHREADED_API=1`
136
+ will expose the deprecated `ZSTDMT` API exposed by `zstdmt_compress.h` in
137
+ the shared library, which is now hidden by default.
138
+
139
+ - The build macro `DYNAMIC_BMI2` can be set to 1 or 0 in order to generate binaries
140
+ which can detect at runtime the presence of BMI2 instructions, and use them only if present.
141
+ These instructions contribute to better performance, notably on the decoder side.
142
+ By default, this feature is automatically enabled on detecting
143
+ the right instruction set (x64) and compiler (clang or gcc >= 5).
144
+ It's obviously disabled for different cpus,
145
+ or when BMI2 instruction set is _required_ by the compiler command line
146
+ (in this case, only the BMI2 code path is generated).
147
+ Setting this macro will either force to generate the BMI2 dispatcher (1)
148
+ or prevent it (0). It overrides automatic detection.
149
+
150
+ - The build macro `ZSTD_NO_UNUSED_FUNCTIONS` can be defined to hide the definitions of functions
151
+ that zstd does not use. Not all unused functions are hidden, but they can be if needed.
152
+ Currently, this macro will hide function definitions in FSE and HUF that use an excessive
153
+ amount of stack space.
154
+
155
+ - The build macro `ZSTD_NO_INTRINSICS` can be defined to disable all explicit intrinsics.
156
+ Compiler builtins are still used.
157
+
158
+ - The build macro `ZSTD_DECODER_INTERNAL_BUFFER` can be set to control
159
+ the amount of extra memory used during decompression to store literals.
160
+ This defaults to 64kB. Reducing this value reduces the memory footprint of
161
+ `ZSTD_DCtx` decompression contexts,
162
+ but might also result in a small decompression speed cost.
163
+
164
+
165
+ #### Windows : using MinGW+MSYS to create DLL
166
+
167
+ DLL can be created using MinGW+MSYS with the `make libzstd` command.
168
+ This command creates `dll\libzstd.dll` and the import library `dll\libzstd.lib`.
169
+ The import library is only required with Visual C++.
170
+ The header file `zstd.h` and the dynamic library `dll\libzstd.dll` are required to
171
+ compile a project using gcc/MinGW.
172
+ The dynamic library has to be added to linking options.
173
+ It means that if a project that uses ZSTD consists of a single `test-dll.c`
174
+ file it should be linked with `dll\libzstd.dll`. For example:
175
+ ```
176
+ gcc $(CFLAGS) -Iinclude/ test-dll.c -o test-dll dll\libzstd.dll
177
+ ```
178
+ The compiled executable will require ZSTD DLL which is available at `dll\libzstd.dll`.
179
+
180
+
181
+ #### Advanced Build options
182
+
183
+ The build system requires a hash function in order to
184
+ separate object files created with different compilation flags.
185
+ By default, it tries to use `md5sum` or equivalent.
186
+ The hash function can be manually switched by setting the `HASH` variable.
187
+ For example : `make HASH=xxhsum`
188
+ The hash function needs to generate at least 64-bit using hexadecimal format.
189
+ When no hash function is found,
190
+ the Makefile just generates all object files into the same default directory,
191
+ irrespective of compilation flags.
192
+ This functionality only matters if `libzstd` is compiled multiple times
193
+ with different build flags.
194
+
195
+ The build directory, where object files are stored
196
+ can also be manually controlled using variable `BUILD_DIR`,
197
+ for example `make BUILD_DIR=objectDir/v1`.
198
+ In which case, the hash function doesn't matter.
199
+
200
+
201
+ #### Deprecated API
202
+
203
+ Obsolete API on their way out are stored in directory `lib/deprecated`.
204
+ At this stage, it contains older streaming prototypes, in `lib/deprecated/zbuff.h`.
205
+ These prototypes will be removed in some future version.
206
+ Consider migrating code towards supported streaming API exposed in `zstd.h`.
207
+
208
+
209
+ #### Miscellaneous
210
+
211
+ The other files are not source code. There are :
212
+
213
+ - `BUCK` : support for `buck` build system (https://buckbuild.com/)
214
+ - `Makefile` : `make` script to build and install zstd library (static and dynamic)
215
+ - `README.md` : this file
216
+ - `dll/` : resources directory for Windows compilation
217
+ - `libzstd.pc.in` : script for `pkg-config` (used in `make install`)
SPANN/ThirdParty/zstd/lib/common/debug.c ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* ******************************************************************
2
+ * debug
3
+ * Part of FSE library
4
+ * Copyright (c) Yann Collet, Facebook, Inc.
5
+ *
6
+ * You can contact the author at :
7
+ * - Source repository : https://github.com/Cyan4973/FiniteStateEntropy
8
+ *
9
+ * This source code is licensed under both the BSD-style license (found in the
10
+ * LICENSE file in the root directory of this source tree) and the GPLv2 (found
11
+ * in the COPYING file in the root directory of this source tree).
12
+ * You may select, at your option, one of the above-listed licenses.
13
+ ****************************************************************** */
14
+
15
+
16
+ /*
17
+ * This module only hosts one global variable
18
+ * which can be used to dynamically influence the verbosity of traces,
19
+ * such as DEBUGLOG and RAWLOG
20
+ */
21
+
22
+ #include "debug.h"
23
+
24
+ int g_debuglevel = DEBUGLEVEL;
SPANN/ThirdParty/zstd/lib/libzstd.mk ADDED
@@ -0,0 +1,203 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ################################################################
2
+ # Copyright (c) Yann Collet, Facebook, Inc.
3
+ # All rights reserved.
4
+ #
5
+ # This source code is licensed under both the BSD-style license (found in the
6
+ # LICENSE file in the root directory of this source tree) and the GPLv2 (found
7
+ # in the COPYING file in the root directory of this source tree).
8
+ # You may select, at your option, one of the above-listed licenses.
9
+ # ################################################################
10
+
11
+ ##################################################################
12
+ # Input Variables
13
+ ##################################################################
14
+
15
+ # Zstd lib directory
16
+ LIBZSTD ?= ./
17
+
18
+ # Legacy support
19
+ ZSTD_LEGACY_SUPPORT ?= 5
20
+ ZSTD_LEGACY_MULTITHREADED_API ?= 0
21
+
22
+ # Build size optimizations
23
+ HUF_FORCE_DECOMPRESS_X1 ?= 0
24
+ HUF_FORCE_DECOMPRESS_X2 ?= 0
25
+ ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT ?= 0
26
+ ZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG ?= 0
27
+ ZSTD_NO_INLINE ?= 0
28
+ ZSTD_STRIP_ERROR_STRINGS ?= 0
29
+
30
+ # Assembly support
31
+ ZSTD_NO_ASM ?= 0
32
+
33
+ ##################################################################
34
+ # libzstd helpers
35
+ ##################################################################
36
+
37
+ VOID ?= /dev/null
38
+
39
+ # Make 4.3 doesn't support '\#' anymore (https://lwn.net/Articles/810071/)
40
+ NUM_SYMBOL := \#
41
+
42
+ # define silent mode as default (verbose mode with V=1 or VERBOSE=1)
43
+ $(V)$(VERBOSE).SILENT:
44
+
45
+ # When cross-compiling from linux to windows,
46
+ # one might need to specify TARGET_SYSTEM as "Windows."
47
+ # Building from Fedora fails without it.
48
+ # (but Ubuntu and Debian don't need to set anything)
49
+ TARGET_SYSTEM ?= $(OS)
50
+
51
+ # Version numbers
52
+ LIBVER_SRC := $(LIBZSTD)/zstd.h
53
+ LIBVER_MAJOR_SCRIPT:=`sed -n '/define ZSTD_VERSION_MAJOR/s/.*[[:blank:]]\([0-9][0-9]*\).*/\1/p' < $(LIBVER_SRC)`
54
+ LIBVER_MINOR_SCRIPT:=`sed -n '/define ZSTD_VERSION_MINOR/s/.*[[:blank:]]\([0-9][0-9]*\).*/\1/p' < $(LIBVER_SRC)`
55
+ LIBVER_PATCH_SCRIPT:=`sed -n '/define ZSTD_VERSION_RELEASE/s/.*[[:blank:]]\([0-9][0-9]*\).*/\1/p' < $(LIBVER_SRC)`
56
+ LIBVER_SCRIPT:= $(LIBVER_MAJOR_SCRIPT).$(LIBVER_MINOR_SCRIPT).$(LIBVER_PATCH_SCRIPT)
57
+ LIBVER_MAJOR := $(shell echo $(LIBVER_MAJOR_SCRIPT))
58
+ LIBVER_MINOR := $(shell echo $(LIBVER_MINOR_SCRIPT))
59
+ LIBVER_PATCH := $(shell echo $(LIBVER_PATCH_SCRIPT))
60
+ LIBVER := $(shell echo $(LIBVER_SCRIPT))
61
+ CCVER := $(shell $(CC) --version)
62
+ ZSTD_VERSION?= $(LIBVER)
63
+
64
+ # ZSTD_LIB_MINIFY is a helper variable that
65
+ # configures a bunch of other variables to space-optimized defaults.
66
+ ZSTD_LIB_MINIFY ?= 0
67
+ ifneq ($(ZSTD_LIB_MINIFY), 0)
68
+ HAVE_CC_OZ ?= $(shell echo "" | $(CC) -Oz -x c -c - -o /dev/null 2> /dev/null && echo 1 || echo 0)
69
+ ZSTD_LEGACY_SUPPORT ?= 0
70
+ ZSTD_LIB_DEPRECATED ?= 0
71
+ HUF_FORCE_DECOMPRESS_X1 ?= 1
72
+ ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT ?= 1
73
+ ZSTD_NO_INLINE ?= 1
74
+ ZSTD_STRIP_ERROR_STRINGS ?= 1
75
+ ifneq ($(HAVE_CC_OZ), 0)
76
+ # Some compilers (clang) support an even more space-optimized setting.
77
+ CFLAGS += -Oz
78
+ else
79
+ CFLAGS += -Os
80
+ endif
81
+ CFLAGS += -fno-stack-protector -fomit-frame-pointer -fno-ident \
82
+ -DDYNAMIC_BMI2=0 -DNDEBUG
83
+ else
84
+ CFLAGS ?= -O3
85
+ endif
86
+
87
+ DEBUGLEVEL ?= 0
88
+ CPPFLAGS += -DXXH_NAMESPACE=ZSTD_ -DDEBUGLEVEL=$(DEBUGLEVEL)
89
+ ifeq ($(TARGET_SYSTEM),Windows_NT) # MinGW assumed
90
+ CPPFLAGS += -D__USE_MINGW_ANSI_STDIO # compatibility with %zu formatting
91
+ endif
92
+ DEBUGFLAGS= -Wall -Wextra -Wcast-qual -Wcast-align -Wshadow \
93
+ -Wstrict-aliasing=1 -Wswitch-enum -Wdeclaration-after-statement \
94
+ -Wstrict-prototypes -Wundef -Wpointer-arith \
95
+ -Wvla -Wformat=2 -Winit-self -Wfloat-equal -Wwrite-strings \
96
+ -Wredundant-decls -Wmissing-prototypes -Wc++-compat
97
+ CFLAGS += $(DEBUGFLAGS) $(MOREFLAGS)
98
+ ASFLAGS += $(DEBUGFLAGS) $(MOREFLAGS) $(CFLAGS)
99
+ LDFLAGS += $(MOREFLAGS)
100
+ FLAGS = $(CPPFLAGS) $(CFLAGS) $(ASFLAGS) $(LDFLAGS)
101
+
102
+ ifndef ALREADY_APPENDED_NOEXECSTACK
103
+ export ALREADY_APPENDED_NOEXECSTACK := 1
104
+ ifeq ($(shell echo "int main(int argc, char* argv[]) { (void)argc; (void)argv; return 0; }" | $(CC) $(FLAGS) -z noexecstack -x c -Werror - -o $(VOID) 2>$(VOID) && echo 1 || echo 0),1)
105
+ LDFLAGS += -z noexecstack
106
+ endif
107
+ ifeq ($(shell echo | $(CC) $(FLAGS) -Wa,--noexecstack -x assembler -Werror -c - -o $(VOID) 2>$(VOID) && echo 1 || echo 0),1)
108
+ CFLAGS += -Wa,--noexecstack
109
+ # CFLAGS are also added to ASFLAGS
110
+ else ifeq ($(shell echo | $(CC) $(FLAGS) -Qunused-arguments -Wa,--noexecstack -x assembler -Werror -c - -o $(VOID) 2>$(VOID) && echo 1 || echo 0),1)
111
+ # See e.g.: https://github.com/android/ndk/issues/171
112
+ CFLAGS += -Qunused-arguments -Wa,--noexecstack
113
+ # CFLAGS are also added to ASFLAGS
114
+ endif
115
+ endif
116
+
117
+ HAVE_COLORNEVER = $(shell echo a | grep --color=never a > /dev/null 2> /dev/null && echo 1 || echo 0)
118
+ GREP_OPTIONS ?=
119
+ ifeq ($HAVE_COLORNEVER, 1)
120
+ GREP_OPTIONS += --color=never
121
+ endif
122
+ GREP = grep $(GREP_OPTIONS)
123
+ SED_ERE_OPT ?= -E
124
+
125
+ ZSTD_COMMON_FILES := $(sort $(wildcard $(LIBZSTD)/common/*.c))
126
+ ZSTD_COMPRESS_FILES := $(sort $(wildcard $(LIBZSTD)/compress/*.c))
127
+ ZSTD_DECOMPRESS_FILES := $(sort $(wildcard $(LIBZSTD)/decompress/*.c))
128
+ ZSTD_DICTBUILDER_FILES := $(sort $(wildcard $(LIBZSTD)/dictBuilder/*.c))
129
+ ZSTD_DEPRECATED_FILES := $(sort $(wildcard $(LIBZSTD)/deprecated/*.c))
130
+ ZSTD_LEGACY_FILES :=
131
+
132
+ ZSTD_DECOMPRESS_AMD64_ASM_FILES := $(sort $(wildcard $(LIBZSTD)/decompress/*_amd64.S))
133
+
134
+ ifneq ($(ZSTD_NO_ASM), 0)
135
+ CPPFLAGS += -DZSTD_DISABLE_ASM
136
+ else
137
+ # Unconditionally add the ASM files they are disabled by
138
+ # macros in the .S file.
139
+ ZSTD_DECOMPRESS_FILES += $(ZSTD_DECOMPRESS_AMD64_ASM_FILES)
140
+ endif
141
+
142
+ ifneq ($(HUF_FORCE_DECOMPRESS_X1), 0)
143
+ CFLAGS += -DHUF_FORCE_DECOMPRESS_X1
144
+ endif
145
+
146
+ ifneq ($(HUF_FORCE_DECOMPRESS_X2), 0)
147
+ CFLAGS += -DHUF_FORCE_DECOMPRESS_X2
148
+ endif
149
+
150
+ ifneq ($(ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT), 0)
151
+ CFLAGS += -DZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT
152
+ endif
153
+
154
+ ifneq ($(ZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG), 0)
155
+ CFLAGS += -DZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG
156
+ endif
157
+
158
+ ifneq ($(ZSTD_NO_INLINE), 0)
159
+ CFLAGS += -DZSTD_NO_INLINE
160
+ endif
161
+
162
+ ifneq ($(ZSTD_STRIP_ERROR_STRINGS), 0)
163
+ CFLAGS += -DZSTD_STRIP_ERROR_STRINGS
164
+ endif
165
+
166
+ ifneq ($(ZSTD_LEGACY_MULTITHREADED_API), 0)
167
+ CFLAGS += -DZSTD_LEGACY_MULTITHREADED_API
168
+ endif
169
+
170
+ ifneq ($(ZSTD_LEGACY_SUPPORT), 0)
171
+ ifeq ($(shell test $(ZSTD_LEGACY_SUPPORT) -lt 8; echo $$?), 0)
172
+ ZSTD_LEGACY_FILES += $(shell ls $(LIBZSTD)/legacy/*.c | $(GREP) 'v0[$(ZSTD_LEGACY_SUPPORT)-7]')
173
+ endif
174
+ endif
175
+ CPPFLAGS += -DZSTD_LEGACY_SUPPORT=$(ZSTD_LEGACY_SUPPORT)
176
+
177
+ UNAME := $(shell uname)
178
+
179
+ ifndef BUILD_DIR
180
+ ifeq ($(UNAME), Darwin)
181
+ ifeq ($(shell md5 < /dev/null > /dev/null; echo $$?), 0)
182
+ HASH ?= md5
183
+ endif
184
+ else ifeq ($(UNAME), FreeBSD)
185
+ HASH ?= gmd5sum
186
+ else ifeq ($(UNAME), NetBSD)
187
+ HASH ?= md5 -n
188
+ else ifeq ($(UNAME), OpenBSD)
189
+ HASH ?= md5
190
+ endif
191
+ HASH ?= md5sum
192
+
193
+ HASH_DIR = conf_$(shell echo $(CC) $(CPPFLAGS) $(CFLAGS) $(LDFLAGS) $(ZSTD_FILES) | $(HASH) | cut -f 1 -d " " )
194
+ HAVE_HASH :=$(shell echo 1 | $(HASH) > /dev/null && echo 1 || echo 0)
195
+ ifeq ($(HAVE_HASH),0)
196
+ $(info warning : could not find HASH ($(HASH)), needed to differentiate builds using different flags)
197
+ BUILD_DIR := obj/generic_noconf
198
+ endif
199
+ endif # BUILD_DIR
200
+
201
+ ZSTD_SUBDIR := $(LIBZSTD)/common $(LIBZSTD)/compress $(LIBZSTD)/decompress $(LIBZSTD)/dictBuilder $(LIBZSTD)/legacy $(LIBZSTD)/deprecated
202
+ vpath %.c $(ZSTD_SUBDIR)
203
+ vpath %.S $(ZSTD_SUBDIR)
SPANN/ThirdParty/zstd/lib/libzstd.pc.in ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ZSTD - standard compression algorithm
2
+ # Copyright (C) 2014-2016, Yann Collet, Facebook
3
+ # BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php)
4
+
5
+ prefix=@PREFIX@
6
+ exec_prefix=@EXEC_PREFIX@
7
+ includedir=@INCLUDEDIR@
8
+ libdir=@LIBDIR@
9
+
10
+ Name: zstd
11
+ Description: fast lossless compression algorithm library
12
+ URL: http://www.zstd.net/
13
+ Version: @VERSION@
14
+ Libs: -L${libdir} -lzstd
15
+ Libs.private: @LIBS_PRIVATE@
16
+ Cflags: -I${includedir}
SPANN/ThirdParty/zstd/lib/module.modulemap ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ module libzstd [extern_c] {
2
+ header "zstd.h"
3
+ export *
4
+ config_macros [exhaustive] /* zstd.h */ \
5
+ ZSTD_STATIC_LINKING_ONLY, \
6
+ ZSTDLIB_VISIBLE, \
7
+ ZSTD_DLL_EXPORT, \
8
+ ZSTDLIB_STATIC_API, \
9
+ ZSTD_DISABLE_DEPRECATE_WARNINGS, \
10
+ ZSTD_CLEVEL_DEFAULT, \
11
+ /* zdict.h */ ZDICT_STATIC_LINKING_ONLY, \
12
+ ZDICTLIB_VISIBILITY, \
13
+ ZDICT_DISABLE_DEPRECATE_WARNINGS, \
14
+ /* zstd_errors.h */ ZSTDERRORLIB_VISIBILITY
15
+
16
+ module dictbuilder [extern_c] {
17
+ header "zdict.h"
18
+ export *
19
+ }
20
+
21
+ module errors [extern_c] {
22
+ header "zstd_errors.h"
23
+ export *
24
+ }
25
+ }
SPANN/ThirdParty/zstd/lib/zstd_errors.h ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * Copyright (c) Yann Collet, Facebook, Inc.
3
+ * All rights reserved.
4
+ *
5
+ * This source code is licensed under both the BSD-style license (found in the
6
+ * LICENSE file in the root directory of this source tree) and the GPLv2 (found
7
+ * in the COPYING file in the root directory of this source tree).
8
+ * You may select, at your option, one of the above-listed licenses.
9
+ */
10
+
11
+ #ifndef ZSTD_ERRORS_H_398273423
12
+ #define ZSTD_ERRORS_H_398273423
13
+
14
+ #if defined (__cplusplus)
15
+ extern "C" {
16
+ #endif
17
+
18
+ /*===== dependency =====*/
19
+ #include <stddef.h> /* size_t */
20
+
21
+
22
+ /* ===== ZSTDERRORLIB_API : control library symbols visibility ===== */
23
+ #ifndef ZSTDERRORLIB_VISIBILITY
24
+ # if defined(__GNUC__) && (__GNUC__ >= 4)
25
+ # define ZSTDERRORLIB_VISIBILITY __attribute__ ((visibility ("default")))
26
+ # else
27
+ # define ZSTDERRORLIB_VISIBILITY
28
+ # endif
29
+ #endif
30
+ #if defined(ZSTD_DLL_EXPORT) && (ZSTD_DLL_EXPORT==1)
31
+ # define ZSTDERRORLIB_API __declspec(dllexport) ZSTDERRORLIB_VISIBILITY
32
+ #elif defined(ZSTD_DLL_IMPORT) && (ZSTD_DLL_IMPORT==1)
33
+ # define ZSTDERRORLIB_API __declspec(dllimport) ZSTDERRORLIB_VISIBILITY /* It isn't required but allows to generate better code, saving a function pointer load from the IAT and an indirect jump.*/
34
+ #else
35
+ # define ZSTDERRORLIB_API ZSTDERRORLIB_VISIBILITY
36
+ #endif
37
+
38
+ /*-*********************************************
39
+ * Error codes list
40
+ *-*********************************************
41
+ * Error codes _values_ are pinned down since v1.3.1 only.
42
+ * Therefore, don't rely on values if you may link to any version < v1.3.1.
43
+ *
44
+ * Only values < 100 are considered stable.
45
+ *
46
+ * note 1 : this API shall be used with static linking only.
47
+ * dynamic linking is not yet officially supported.
48
+ * note 2 : Prefer relying on the enum than on its value whenever possible
49
+ * This is the only supported way to use the error list < v1.3.1
50
+ * note 3 : ZSTD_isError() is always correct, whatever the library version.
51
+ **********************************************/
52
+ typedef enum {
53
+ ZSTD_error_no_error = 0,
54
+ ZSTD_error_GENERIC = 1,
55
+ ZSTD_error_prefix_unknown = 10,
56
+ ZSTD_error_version_unsupported = 12,
57
+ ZSTD_error_frameParameter_unsupported = 14,
58
+ ZSTD_error_frameParameter_windowTooLarge = 16,
59
+ ZSTD_error_corruption_detected = 20,
60
+ ZSTD_error_checksum_wrong = 22,
61
+ ZSTD_error_dictionary_corrupted = 30,
62
+ ZSTD_error_dictionary_wrong = 32,
63
+ ZSTD_error_dictionaryCreation_failed = 34,
64
+ ZSTD_error_parameter_unsupported = 40,
65
+ ZSTD_error_parameter_outOfBound = 42,
66
+ ZSTD_error_tableLog_tooLarge = 44,
67
+ ZSTD_error_maxSymbolValue_tooLarge = 46,
68
+ ZSTD_error_maxSymbolValue_tooSmall = 48,
69
+ ZSTD_error_stage_wrong = 60,
70
+ ZSTD_error_init_missing = 62,
71
+ ZSTD_error_memory_allocation = 64,
72
+ ZSTD_error_workSpace_tooSmall= 66,
73
+ ZSTD_error_dstSize_tooSmall = 70,
74
+ ZSTD_error_srcSize_wrong = 72,
75
+ ZSTD_error_dstBuffer_null = 74,
76
+ /* following error codes are __NOT STABLE__, they can be removed or changed in future versions */
77
+ ZSTD_error_frameIndex_tooLarge = 100,
78
+ ZSTD_error_seekableIO = 102,
79
+ ZSTD_error_dstBuffer_wrong = 104,
80
+ ZSTD_error_srcBuffer_wrong = 105,
81
+ ZSTD_error_maxCode = 120 /* never EVER use this value directly, it can change in future versions! Use ZSTD_isError() instead */
82
+ } ZSTD_ErrorCode;
83
+
84
+ /*! ZSTD_getErrorCode() :
85
+ convert a `size_t` function result into a `ZSTD_ErrorCode` enum type,
86
+ which can be used to compare with enum list published above */
87
+ ZSTDERRORLIB_API ZSTD_ErrorCode ZSTD_getErrorCode(size_t functionResult);
88
+ ZSTDERRORLIB_API const char* ZSTD_getErrorString(ZSTD_ErrorCode code); /**< Same as ZSTD_getErrorName, but using a `ZSTD_ErrorCode` enum argument */
89
+
90
+
91
+ #if defined (__cplusplus)
92
+ }
93
+ #endif
94
+
95
+ #endif /* ZSTD_ERRORS_H_398273423 */
SPANN/ThirdParty/zstd/zlibWrapper/.gitignore ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # object artifacts
2
+ *.o
3
+
4
+ # Default result files
5
+ _*
6
+ example
7
+ example_zstd.*
8
+ example_gz.*
9
+ fitblk
10
+ fitblk_zstd.*
11
+ zwrapbench
12
+ foo.gz
13
+
14
+ minigzip
15
+ minigzip_zstd
16
+ example
17
+ example_zstd
18
+ fitblk
19
+ fitblk_zstd
20
+ zwrapbench
21
+
22
+ # Misc files
23
+ *.bat
24
+ *.zip
25
+ *.txt
26
+
27
+ # Directories
28
+ minizip/
SPANN/ThirdParty/zstd/zlibWrapper/BUCK ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ cxx_library(
2
+ name='zlib_wrapper',
3
+ visibility=['PUBLIC'],
4
+ exported_linker_flags=['-lz'],
5
+ header_namespace='',
6
+ exported_headers=['zstd_zlibwrapper.h'],
7
+ headers=[
8
+ 'gzcompatibility.h',
9
+ 'gzguts.h',
10
+ ],
11
+ srcs=glob(['*.c']),
12
+ deps=[
13
+ '//lib:zstd',
14
+ '//lib:zstd_common',
15
+ ],
16
+ )
17
+
18
+ cxx_binary(
19
+ name='minigzip',
20
+ srcs=['examples/minigzip.c'],
21
+ deps=[':zlib_wrapper'],
22
+ )
SPANN/ThirdParty/zstd/zlibWrapper/Makefile ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Makefile for example of using zstd wrapper for zlib
2
+ #
3
+ # make - compiles examples
4
+ # make MOREFLAGS=-DZWRAP_USE_ZSTD=1 - compiles examples with zstd compression turned on
5
+ # make test - runs examples
6
+
7
+
8
+ # Paths to static and dynamic zlib and zstd libraries
9
+ # Use "make ZLIB_PATH=path/to/zlib ZLIB_LIBRARY=path/to/libz.so" to select a path to library
10
+ ZLIB_LIBRARY ?= -lz
11
+ ZLIB_PATH ?= .
12
+
13
+ ZSTDLIBDIR = ../lib
14
+ ZSTDLIBRARY = $(ZSTDLIBDIR)/libzstd.a
15
+ ZLIBWRAPPER_PATH = .
16
+ GZFILES = gzclose.o gzlib.o gzread.o gzwrite.o
17
+ EXAMPLE_PATH = examples
18
+ PROGRAMS_PATH = ../programs
19
+ TEST_FILE = ../doc/zstd_compression_format.md
20
+
21
+ vpath %.c $(PROGRAMS_PATH) $(EXAMPLE_PATH) $(ZLIBWRAPPER_PATH)
22
+
23
+
24
+ CPPFLAGS += -DXXH_NAMESPACE=ZSTD_ -I$(ZLIB_PATH) -I$(PROGRAMS_PATH) \
25
+ -I$(ZSTDLIBDIR) -I$(ZSTDLIBDIR)/common -I$(ZLIBWRAPPER_PATH)
26
+ STDFLAGS = -std=c89 -pedantic -Wno-long-long -Wno-variadic-macros -Wc++-compat \
27
+ -DNO_snprintf -DNO_vsnprintf # strict ANSI C89 is missing these prototypes
28
+ DEBUGFLAGS= -Wall -Wextra -Wcast-qual -Wcast-align -Wshadow -Wswitch-enum \
29
+ -Wdeclaration-after-statement -Wstrict-prototypes -Wundef \
30
+ -Wstrict-aliasing=1
31
+ CFLAGS ?= -O3
32
+ CFLAGS += $(STDFLAGS) $(DEBUGFLAGS)
33
+ CPPFLAGS += $(MOREFLAGS)
34
+ LDLIBS += $(ZLIB_LIBRARY)
35
+
36
+ # Define *.exe as extension for Windows systems
37
+ ifneq (,$(filter Windows%,$(OS)))
38
+ EXT =.exe
39
+ else
40
+ EXT =
41
+ endif
42
+
43
+ default : release
44
+
45
+ release : STDFLAGS =
46
+ release : DEBUGFLAGS =
47
+ release : all
48
+
49
+ all: fitblk example zwrapbench minigzip
50
+
51
+ test: example fitblk example_zstd fitblk_zstd zwrapbench minigzip minigzip_zstd
52
+ ./example
53
+ ./example_zstd
54
+ ./fitblk 10240 <$(TEST_FILE)
55
+ ./fitblk 40960 <$(TEST_FILE)
56
+ ./fitblk_zstd 10240 <$(TEST_FILE)
57
+ ./fitblk_zstd 40960 <$(TEST_FILE)
58
+ @echo ---- minigzip start ----
59
+ ./minigzip_zstd example$(EXT)
60
+ #cp example$(EXT).gz example$(EXT)_zstd.gz
61
+ ./minigzip_zstd -d example$(EXT).gz
62
+ ./minigzip example$(EXT)
63
+ #cp example$(EXT).gz example$(EXT)_gz.gz
64
+ ./minigzip_zstd -d example$(EXT).gz
65
+ @echo ---- minigzip end ----
66
+ ./zwrapbench -qi1b3B1K $(TEST_FILE)
67
+ ./zwrapbench -rqi1b1e3 ../lib
68
+
69
+ #valgrindTest: ZSTDLIBRARY = $(ZSTDLIBDIR)/libzstd.so
70
+ valgrindTest: VALGRIND = LD_LIBRARY_PATH=$(ZSTDLIBDIR) valgrind --track-origins=yes --leak-check=full --error-exitcode=1
71
+ valgrindTest: clean example fitblk example_zstd fitblk_zstd zwrapbench
72
+ @echo "\n ---- valgrind tests ----"
73
+ $(VALGRIND) ./example
74
+ $(VALGRIND) ./example_zstd
75
+ $(VALGRIND) ./fitblk 10240 <$(TEST_FILE)
76
+ $(VALGRIND) ./fitblk 40960 <$(TEST_FILE)
77
+ $(VALGRIND) ./fitblk_zstd 10240 <$(TEST_FILE)
78
+ $(VALGRIND) ./fitblk_zstd 40960 <$(TEST_FILE)
79
+ $(VALGRIND) ./zwrapbench -qi1b3B1K $(TEST_FILE)
80
+ $(VALGRIND) ./zwrapbench -rqi1b1e5 ../lib ../programs ../tests
81
+
82
+ #.c.o:
83
+ # $(CC) $(CFLAGS) $(CPPFLAGS) -c $< -o $@
84
+
85
+ minigzip: minigzip.o zstd_zlibwrapper.o $(GZFILES) $(ZSTDLIBRARY)
86
+
87
+ minigzip_zstd: minigzip.o zstdTurnedOn_zlibwrapper.o $(GZFILES) $(ZSTDLIBRARY)
88
+ $(LINK.o) $^ $(LDLIBS) $(OUTPUT_OPTION)
89
+
90
+ example: example.o zstd_zlibwrapper.o $(GZFILES) $(ZSTDLIBRARY)
91
+
92
+ example_zstd: example.o zstdTurnedOn_zlibwrapper.o $(GZFILES) $(ZSTDLIBRARY)
93
+ $(LINK.o) $^ $(LDLIBS) $(OUTPUT_OPTION)
94
+
95
+ fitblk: fitblk.o zstd_zlibwrapper.o $(ZSTDLIBRARY)
96
+
97
+ fitblk_zstd: fitblk.o zstdTurnedOn_zlibwrapper.o $(ZSTDLIBRARY)
98
+ $(LINK.o) $^ $(LDLIBS) $(OUTPUT_OPTION)
99
+
100
+ zwrapbench: zwrapbench.o zstd_zlibwrapper.o util.o timefn.o datagen.o $(ZSTDLIBRARY)
101
+
102
+
103
+ zstd_zlibwrapper.o: zstd_zlibwrapper.h
104
+
105
+ zstdTurnedOn_zlibwrapper.o: CPPFLAGS += -DZWRAP_USE_ZSTD=1
106
+ zstdTurnedOn_zlibwrapper.o: zstd_zlibwrapper.c zstd_zlibwrapper.h
107
+ $(COMPILE.c) $< $(OUTPUT_OPTION)
108
+
109
+
110
+ $(ZSTDLIBRARY):
111
+ $(MAKE) -C $(ZSTDLIBDIR) libzstd.a
112
+
113
+ $(ZSTDLIBDIR)/libzstd.so:
114
+ $(MAKE) -C $(ZSTDLIBDIR) libzstd
115
+
116
+
117
+ clean:
118
+ -$(RM) $(ZLIBWRAPPER_PATH)/*.o $(EXAMPLE_PATH)/*.o *.o foo.gz example$(EXT) example_zstd$(EXT) fitblk$(EXT) fitblk_zstd$(EXT) zwrapbench$(EXT) minigzip$(EXT) minigzip_zstd$(EXT)
119
+ @echo Cleaning completed