VideoUFO commited on
Commit
b554a07
·
verified ·
1 Parent(s): 368c22e

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. ScaleDF_rebuttal/python_dedup_pkgs/faiss/contrib/big_batch_search.py +515 -0
  2. ScaleDF_rebuttal/python_dedup_pkgs/faiss/contrib/client_server.py +91 -0
  3. ScaleDF_rebuttal/python_dedup_pkgs/faiss/contrib/clustering.py +502 -0
  4. ScaleDF_rebuttal/python_dedup_pkgs/faiss/contrib/datasets.py +465 -0
  5. ScaleDF_rebuttal/python_dedup_pkgs/faiss/contrib/evaluation.py +498 -0
  6. ScaleDF_rebuttal/python_dedup_pkgs/faiss/contrib/exhaustive_search.py +368 -0
  7. ScaleDF_rebuttal/python_dedup_pkgs/faiss/contrib/factory_tools.py +156 -0
  8. ScaleDF_rebuttal/python_dedup_pkgs/faiss/contrib/inspect_tools.py +117 -0
  9. ScaleDF_rebuttal/python_dedup_pkgs/faiss/contrib/ivf_tools.py +148 -0
  10. ScaleDF_rebuttal/python_dedup_pkgs/faiss/contrib/ondisk.py +59 -0
  11. ScaleDF_rebuttal/python_dedup_pkgs/faiss/contrib/rpc.py +261 -0
  12. ScaleDF_rebuttal/python_dedup_pkgs/faiss/contrib/torch/README.md +6 -0
  13. ScaleDF_rebuttal/python_dedup_pkgs/faiss/contrib/torch/__init__.py +0 -0
  14. ScaleDF_rebuttal/python_dedup_pkgs/faiss/contrib/torch/clustering.py +61 -0
  15. ScaleDF_rebuttal/python_dedup_pkgs/faiss/contrib/torch/quantization.py +96 -0
  16. ScaleDF_rebuttal/python_dedup_pkgs/faiss/contrib/torch_utils.py +839 -0
  17. ScaleDF_rebuttal/python_dedup_pkgs/faiss/contrib/vecs_io.py +178 -0
  18. ScaleDF_rebuttal/python_dedup_pkgs/faiss_cpu-1.14.3.dist-info/INSTALLER +1 -0
  19. ScaleDF_rebuttal/python_dedup_pkgs/faiss_cpu-1.14.3.dist-info/METADATA +124 -0
  20. ScaleDF_rebuttal/python_dedup_pkgs/faiss_cpu-1.14.3.dist-info/RECORD +39 -0
  21. ScaleDF_rebuttal/python_dedup_pkgs/faiss_cpu-1.14.3.dist-info/REQUESTED +0 -0
  22. ScaleDF_rebuttal/python_dedup_pkgs/faiss_cpu-1.14.3.dist-info/WHEEL +6 -0
  23. ScaleDF_rebuttal/python_dedup_pkgs/faiss_cpu-1.14.3.dist-info/licenses/LICENSE +21 -0
  24. ScaleDF_rebuttal/python_dedup_pkgs/faiss_cpu-1.14.3.dist-info/licenses/THIRD_PARTY_NOTICES +410 -0
  25. ScaleDF_rebuttal/python_dedup_pkgs/faiss_cpu-1.14.3.dist-info/sboms/auditwheel.cdx.json +1 -0
  26. ScaleDF_rebuttal/python_dedup_pkgs/flatbuffers-25.12.19.dist-info/INSTALLER +1 -0
  27. ScaleDF_rebuttal/python_dedup_pkgs/flatbuffers-25.12.19.dist-info/METADATA +27 -0
  28. ScaleDF_rebuttal/python_dedup_pkgs/flatbuffers-25.12.19.dist-info/RECORD +26 -0
  29. ScaleDF_rebuttal/python_dedup_pkgs/flatbuffers-25.12.19.dist-info/REQUESTED +0 -0
  30. ScaleDF_rebuttal/python_dedup_pkgs/flatbuffers-25.12.19.dist-info/WHEEL +6 -0
  31. ScaleDF_rebuttal/python_dedup_pkgs/flatbuffers-25.12.19.dist-info/top_level.txt +1 -0
  32. ScaleDF_rebuttal/python_dedup_pkgs/flatbuffers/__init__.py +19 -0
  33. ScaleDF_rebuttal/python_dedup_pkgs/flatbuffers/_version.py +17 -0
  34. ScaleDF_rebuttal/python_dedup_pkgs/flatbuffers/builder.py +858 -0
  35. ScaleDF_rebuttal/python_dedup_pkgs/flatbuffers/compat.py +91 -0
  36. ScaleDF_rebuttal/python_dedup_pkgs/flatbuffers/encode.py +45 -0
  37. ScaleDF_rebuttal/python_dedup_pkgs/flatbuffers/flexbuffers.py +1592 -0
  38. ScaleDF_rebuttal/python_dedup_pkgs/flatbuffers/number_types.py +182 -0
  39. ScaleDF_rebuttal/python_dedup_pkgs/flatbuffers/packer.py +41 -0
  40. ScaleDF_rebuttal/python_dedup_pkgs/flatbuffers/table.py +148 -0
  41. ScaleDF_rebuttal/python_dedup_pkgs/flatbuffers/util.py +47 -0
  42. ScaleDF_rebuttal/python_dedup_pkgs/google/protobuf/__init__.py +10 -0
  43. ScaleDF_rebuttal/python_dedup_pkgs/google/protobuf/any.py +53 -0
  44. ScaleDF_rebuttal/python_dedup_pkgs/google/protobuf/any_pb2.py +37 -0
  45. ScaleDF_rebuttal/python_dedup_pkgs/google/protobuf/api_pb2.py +47 -0
  46. ScaleDF_rebuttal/python_dedup_pkgs/google/protobuf/compiler/__init__.py +0 -0
  47. ScaleDF_rebuttal/python_dedup_pkgs/google/protobuf/compiler/plugin_pb2.py +46 -0
  48. ScaleDF_rebuttal/python_dedup_pkgs/google/protobuf/descriptor.py +1665 -0
  49. ScaleDF_rebuttal/python_dedup_pkgs/google/protobuf/descriptor_database.py +185 -0
  50. ScaleDF_rebuttal/python_dedup_pkgs/google/protobuf/descriptor_pb2.py +0 -0
ScaleDF_rebuttal/python_dedup_pkgs/faiss/contrib/big_batch_search.py ADDED
@@ -0,0 +1,515 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ #
3
+ # This source code is licensed under the MIT license found in the
4
+ # LICENSE file in the root directory of this source tree.
5
+
6
+ import time
7
+ import pickle
8
+ import os
9
+ import logging
10
+ from multiprocessing.pool import ThreadPool
11
+ import threading
12
+ import _thread
13
+ from queue import Queue
14
+ import traceback
15
+ import datetime
16
+
17
+ import numpy as np
18
+ import faiss
19
+
20
+ from faiss.contrib.inspect_tools import get_invlist
21
+
22
+
23
+ class BigBatchSearcher:
24
+ """
25
+ Object that manages all the data related to the computation
26
+ except the actual within-bucket matching and the organization of the
27
+ computation (parallel or not)
28
+ """
29
+
30
+ def __init__(
31
+ self,
32
+ index, xq, k,
33
+ verbose=0,
34
+ use_float16=False):
35
+
36
+ # verbosity
37
+ self.verbose = verbose
38
+ self.tictoc = []
39
+
40
+ self.xq = xq
41
+ self.index = index
42
+ self.use_float16 = use_float16
43
+ keep_max = faiss.is_similarity_metric(index.metric_type)
44
+ self.rh = faiss.ResultHeap(len(xq), k, keep_max=keep_max)
45
+ self.t_accu = [0] * 6
46
+ self.t_display = self.t0 = time.time()
47
+
48
+ def start_t_accu(self):
49
+ self.t_accu_t0 = time.time()
50
+
51
+ def stop_t_accu(self, n):
52
+ self.t_accu[n] += time.time() - self.t_accu_t0
53
+
54
+ def tic(self, name):
55
+ self.tictoc = (name, time.time())
56
+ if self.verbose > 0:
57
+ print(name, end="\r", flush=True)
58
+
59
+ def toc(self):
60
+ name, t0 = self.tictoc
61
+ dt = time.time() - t0
62
+ if self.verbose > 0:
63
+ print(f"{name}: {dt:.3f} s")
64
+ return dt
65
+
66
+ def report(self, l):
67
+ if self.verbose == 1 or (
68
+ self.verbose == 2 and (
69
+ l > 1000 and time.time() < self.t_display + 1.0
70
+ )
71
+ ):
72
+ return
73
+ t = time.time() - self.t0
74
+ print(
75
+ f"[{t:.1f} s] list {l}/{self.index.nlist} "
76
+ f"times prep q {self.t_accu[0]:.3f} prep b {self.t_accu[1]:.3f} "
77
+ f"comp {self.t_accu[2]:.3f} res {self.t_accu[3]:.3f} "
78
+ f"wait in {self.t_accu[4]:.3f} "
79
+ f"wait out {self.t_accu[5]:.3f} "
80
+ f"eta {datetime.timedelta(seconds=t*self.index.nlist/(l+1)-t)} "
81
+ f"mem {faiss.get_mem_usage_kb()}",
82
+ end="\r" if self.verbose <= 2 else "\n",
83
+ flush=True,
84
+ )
85
+ self.t_display = time.time()
86
+
87
+ def coarse_quantization(self):
88
+ self.tic("coarse quantization")
89
+ bs = 65536
90
+ nq = len(self.xq)
91
+ q_assign = np.empty((nq, self.index.nprobe), dtype='int32')
92
+ for i0 in range(0, nq, bs):
93
+ i1 = min(nq, i0 + bs)
94
+ q_dis_i, q_assign_i = self.index.quantizer.search(
95
+ self.xq[i0:i1], self.index.nprobe)
96
+ # q_dis[i0:i1] = q_dis_i
97
+ q_assign[i0:i1] = q_assign_i
98
+ self.toc()
99
+ self.q_assign = q_assign
100
+
101
+ def reorder_assign(self):
102
+ self.tic("bucket sort")
103
+ q_assign = self.q_assign
104
+ q_assign += 1 # move -1 -> 0
105
+ self.bucket_lims = faiss.matrix_bucket_sort_inplace(
106
+ self.q_assign, nbucket=self.index.nlist + 1, nt=16)
107
+ self.query_ids = self.q_assign.ravel()
108
+ if self.verbose > 0:
109
+ print(' number of -1s:', self.bucket_lims[1])
110
+ self.bucket_lims = self.bucket_lims[1:] # shift back to ignore -1s
111
+ del self.q_assign # inplace so let's forget about the old version...
112
+ self.toc()
113
+
114
+ def prepare_bucket(self, l):
115
+ """ prepare the queries and database items for bucket l"""
116
+ t0 = time.time()
117
+ index = self.index
118
+ # prepare queries
119
+ i0, i1 = self.bucket_lims[l], self.bucket_lims[l + 1]
120
+ q_subset = self.query_ids[i0:i1]
121
+ xq_l = self.xq[q_subset]
122
+ if self.by_residual:
123
+ xq_l = xq_l - index.quantizer.reconstruct(l)
124
+ t1 = time.time()
125
+ # prepare database side
126
+ list_ids, xb_l = get_invlist(index.invlists, l)
127
+
128
+ if self.decode_func is None:
129
+ xb_l = xb_l.ravel()
130
+ else:
131
+ xb_l = self.decode_func(xb_l)
132
+
133
+ if self.use_float16:
134
+ xb_l = xb_l.astype('float16')
135
+ xq_l = xq_l.astype('float16')
136
+
137
+ t2 = time.time()
138
+ self.t_accu[0] += t1 - t0
139
+ self.t_accu[1] += t2 - t1
140
+ return q_subset, xq_l, list_ids, xb_l
141
+
142
+ def add_results_to_heap(self, q_subset, D, list_ids, I):
143
+ """add the bucket results to the heap structure"""
144
+ if D is None:
145
+ return
146
+ t0 = time.time()
147
+ if I is None:
148
+ I = list_ids
149
+ else:
150
+ I = list_ids[I]
151
+ self.rh.add_result_subset(q_subset, D, I)
152
+ self.t_accu[3] += time.time() - t0
153
+
154
+ def sizes_in_checkpoint(self):
155
+ return (self.xq.shape, self.index.nprobe, self.index.nlist)
156
+
157
+ def write_checkpoint(self, fname, completed):
158
+ # write to temp file then move to final file
159
+ tmpname = fname + ".tmp"
160
+ with open(tmpname, "wb") as f:
161
+ pickle.dump(
162
+ {
163
+ "sizes": self.sizes_in_checkpoint(),
164
+ "completed": completed,
165
+ "rh": (self.rh.D, self.rh.I),
166
+ }, f, -1)
167
+ os.replace(tmpname, fname)
168
+
169
+ def read_checkpoint(self, fname):
170
+ with open(fname, "rb") as f:
171
+ ckp = pickle.load(f)
172
+ assert ckp["sizes"] == self.sizes_in_checkpoint()
173
+ self.rh.D[:] = ckp["rh"][0]
174
+ self.rh.I[:] = ckp["rh"][1]
175
+ return ckp["completed"]
176
+
177
+
178
+ class BlockComputer:
179
+ """ computation within one bucket """
180
+
181
+ def __init__(
182
+ self,
183
+ index,
184
+ method="knn_function",
185
+ pairwise_distances=faiss.pairwise_distances,
186
+ knn=faiss.knn):
187
+
188
+ self.index = index
189
+ if index.__class__ == faiss.IndexIVFFlat:
190
+ index_help = faiss.IndexFlat(index.d, index.metric_type)
191
+ decode_func = lambda x: x.view("float32")
192
+ by_residual = False
193
+ elif index.__class__ == faiss.IndexIVFPQ:
194
+ index_help = faiss.IndexPQ(
195
+ index.d, index.pq.M, index.pq.nbits, index.metric_type)
196
+ index_help.pq = index.pq
197
+ decode_func = index_help.pq.decode
198
+ index_help.is_trained = True
199
+ by_residual = index.by_residual
200
+ elif index.__class__ == faiss.IndexIVFScalarQuantizer:
201
+ index_help = faiss.IndexScalarQuantizer(
202
+ index.d, index.sq.qtype, index.metric_type)
203
+ index_help.sq = index.sq
204
+ decode_func = index_help.sq.decode
205
+ index_help.is_trained = True
206
+ by_residual = index.by_residual
207
+ else:
208
+ raise RuntimeError(f"index type {index.__class__} not supported")
209
+ self.index_help = index_help
210
+ self.decode_func = None if method == "index" else decode_func
211
+ self.by_residual = by_residual
212
+ self.method = method
213
+ self.pairwise_distances = pairwise_distances
214
+ self.knn = knn
215
+
216
+ def block_search(self, xq_l, xb_l, list_ids, k, **extra_args):
217
+ metric_type = self.index.metric_type
218
+ if xq_l.size == 0 or xb_l.size == 0:
219
+ D = I = None
220
+ elif self.method == "index":
221
+ faiss.copy_array_to_vector(xb_l, self.index_help.codes)
222
+ self.index_help.ntotal = len(list_ids)
223
+ D, I = self.index_help.search(xq_l, k)
224
+ elif self.method == "pairwise_distances":
225
+ # TODO implement blockwise to avoid mem blowup
226
+ D = self.pairwise_distances(xq_l, xb_l, metric=metric_type)
227
+ I = None
228
+ elif self.method == "knn_function":
229
+ D, I = self.knn(xq_l, xb_l, k, metric=metric_type, **extra_args)
230
+
231
+ return D, I
232
+
233
+
234
+ def big_batch_search(
235
+ index, xq, k,
236
+ method="knn_function",
237
+ pairwise_distances=faiss.pairwise_distances,
238
+ knn=faiss.knn,
239
+ verbose=0,
240
+ threaded=0,
241
+ use_float16=False,
242
+ prefetch_threads=1,
243
+ computation_threads=1,
244
+ q_assign=None,
245
+ checkpoint=None,
246
+ checkpoint_freq=7200,
247
+ start_list=0,
248
+ end_list=None,
249
+ crash_at=-1
250
+ ):
251
+ """
252
+ Search queries xq in the IVF index, with a search function that collects
253
+ batches of query vectors per inverted list. This can be faster than the
254
+ regular search indexes.
255
+ Supports IVFFlat, IVFPQ and IVFScalarQuantizer.
256
+
257
+ Supports three computation methods:
258
+ method = "index":
259
+ build a flat index and populate it separately for each index
260
+ method = "pairwise_distances":
261
+ decompress codes and compute all pairwise distances for the queries
262
+ and index and add result to heap
263
+ method = "knn_function":
264
+ decompress codes and compute knn results for the queries
265
+
266
+ threaded=0: sequential execution
267
+ threaded=1: prefetch next bucket while computing the current one
268
+ threaded=2: prefetch prefetch_threads buckets at a time.
269
+
270
+ compute_threads>1: the knn function will get an additional thread_no that
271
+ tells which worker should handle this.
272
+
273
+ In threaded mode, the computation is tiled with the bucket preparation and
274
+ the writeback of results (useful to maximize GPU utilization).
275
+
276
+ use_float16: convert all matrices to float16 (faster for GPU gemm)
277
+
278
+ q_assign: override coarse assignment, should be a matrix of size nq * nprobe
279
+
280
+ checkpointing (only for threaded > 1):
281
+ checkpoint: file where the checkpoints are stored
282
+ checkpoint_freq: when to perform checkpointing. Should be a multiple of threaded
283
+
284
+ start_list, end_list: process only a subset of invlists
285
+ """
286
+ nprobe = index.nprobe
287
+
288
+ assert method in ("index", "pairwise_distances", "knn_function")
289
+
290
+ mem_queries = xq.nbytes
291
+ mem_assign = len(xq) * nprobe * np.dtype('int32').itemsize
292
+ mem_res = len(xq) * k * (
293
+ np.dtype('int64').itemsize
294
+ + np.dtype('float32').itemsize
295
+ )
296
+ mem_tot = mem_queries + mem_assign + mem_res
297
+ if verbose > 0:
298
+ logging.info(
299
+ f"memory: queries {mem_queries} assign {mem_assign} "
300
+ f"result {mem_res} total {mem_tot} = {mem_tot / (1<<30):.3f} GiB"
301
+ )
302
+
303
+ bbs = BigBatchSearcher(
304
+ index, xq, k,
305
+ verbose=verbose,
306
+ use_float16=use_float16
307
+ )
308
+
309
+ comp = BlockComputer(
310
+ index,
311
+ method=method,
312
+ pairwise_distances=pairwise_distances,
313
+ knn=knn
314
+ )
315
+
316
+ bbs.decode_func = comp.decode_func
317
+
318
+ bbs.by_residual = comp.by_residual
319
+ if q_assign is None:
320
+ bbs.coarse_quantization()
321
+ else:
322
+ bbs.q_assign = q_assign
323
+ bbs.reorder_assign()
324
+
325
+ if end_list is None:
326
+ end_list = index.nlist
327
+
328
+ completed = set()
329
+ if checkpoint is not None:
330
+ assert (start_list, end_list) == (0, index.nlist)
331
+ if os.path.exists(checkpoint):
332
+ logging.info(f"recovering checkpoint: {checkpoint}")
333
+ completed = bbs.read_checkpoint(checkpoint)
334
+ logging.info(f" already completed: {len(completed)}")
335
+ else:
336
+ logging.info("no checkpoint: starting from scratch")
337
+
338
+ if threaded == 0:
339
+ # simple sequential version
340
+
341
+ for l in range(start_list, end_list):
342
+ bbs.report(l)
343
+ q_subset, xq_l, list_ids, xb_l = bbs.prepare_bucket(l)
344
+ t0i = time.time()
345
+ D, I = comp.block_search(xq_l, xb_l, list_ids, k)
346
+ bbs.t_accu[2] += time.time() - t0i
347
+ bbs.add_results_to_heap(q_subset, D, list_ids, I)
348
+
349
+ elif threaded == 1:
350
+
351
+ # parallel version with granularity 1
352
+
353
+ def add_results_and_prefetch(to_add, l):
354
+ """ perform the addition for the previous bucket and
355
+ prefetch the next (if applicable) """
356
+ if to_add is not None:
357
+ bbs.add_results_to_heap(*to_add)
358
+ if l < index.nlist:
359
+ return bbs.prepare_bucket(l)
360
+
361
+ prefetched_bucket = bbs.prepare_bucket(start_list)
362
+ to_add = None
363
+ pool = ThreadPool(1)
364
+
365
+ for l in range(start_list, end_list):
366
+ bbs.report(l)
367
+ prefetched_bucket_a = pool.apply_async(
368
+ add_results_and_prefetch, (to_add, l + 1))
369
+ q_subset, xq_l, list_ids, xb_l = prefetched_bucket
370
+ bbs.start_t_accu()
371
+ D, I = comp.block_search(xq_l, xb_l, list_ids, k)
372
+ bbs.stop_t_accu(2)
373
+ to_add = q_subset, D, list_ids, I
374
+ bbs.start_t_accu()
375
+ prefetched_bucket = prefetched_bucket_a.get()
376
+ bbs.stop_t_accu(4)
377
+
378
+ bbs.add_results_to_heap(*to_add)
379
+ pool.close()
380
+ else:
381
+
382
+ def task_manager_thread(
383
+ task,
384
+ pool_size,
385
+ start_task,
386
+ end_task,
387
+ completed,
388
+ output_queue,
389
+ input_queue,
390
+ ):
391
+ try:
392
+ with ThreadPool(pool_size) as pool:
393
+ res = [pool.apply_async(
394
+ task,
395
+ args=(i, output_queue, input_queue))
396
+ for i in range(start_task, end_task)
397
+ if i not in completed]
398
+ for r in res:
399
+ r.get()
400
+ pool.close()
401
+ pool.join()
402
+ output_queue.put(None)
403
+ except:
404
+ traceback.print_exc()
405
+ _thread.interrupt_main()
406
+ raise
407
+
408
+ def task_manager(*args):
409
+ task_manager = threading.Thread(
410
+ target=task_manager_thread,
411
+ args=args,
412
+ )
413
+ task_manager.daemon = True
414
+ task_manager.start()
415
+ return task_manager
416
+
417
+ def prepare_task(task_id, output_queue, input_queue=None):
418
+ try:
419
+ logging.info(f"Prepare start: {task_id}")
420
+ q_subset, xq_l, list_ids, xb_l = bbs.prepare_bucket(task_id)
421
+ output_queue.put((task_id, q_subset, xq_l, list_ids, xb_l))
422
+ logging.info(f"Prepare end: {task_id}")
423
+ except:
424
+ traceback.print_exc()
425
+ _thread.interrupt_main()
426
+ raise
427
+
428
+ def compute_task(task_id, output_queue, input_queue):
429
+ try:
430
+ logging.info(f"Compute start: {task_id}")
431
+ t_wait_out = 0
432
+ while True:
433
+ t0 = time.time()
434
+ logging.info(f'Compute input: task {task_id}')
435
+ input_value = input_queue.get()
436
+ t_wait_in = time.time() - t0
437
+ if input_value is None:
438
+ # signal for other compute tasks
439
+ input_queue.put(None)
440
+ break
441
+ centroid, q_subset, xq_l, list_ids, xb_l = input_value
442
+ logging.info(f'Compute work: task {task_id}, centroid {centroid}')
443
+ t0 = time.time()
444
+ if computation_threads > 1:
445
+ D, I = comp.block_search(
446
+ xq_l, xb_l, list_ids, k, thread_id=task_id
447
+ )
448
+ else:
449
+ D, I = comp.block_search(xq_l, xb_l, list_ids, k)
450
+ t_compute = time.time() - t0
451
+ logging.info(f'Compute output: task {task_id}, centroid {centroid}')
452
+ t0 = time.time()
453
+ output_queue.put(
454
+ (centroid, t_wait_in, t_wait_out, t_compute, q_subset, D, list_ids, I)
455
+ )
456
+ t_wait_out = time.time() - t0
457
+ logging.info(f"Compute end: {task_id}")
458
+ except:
459
+ traceback.print_exc()
460
+ _thread.interrupt_main()
461
+ raise
462
+
463
+ prepare_to_compute_queue = Queue(2)
464
+ compute_to_main_queue = Queue(2)
465
+ compute_task_manager = task_manager(
466
+ compute_task,
467
+ computation_threads,
468
+ 0,
469
+ computation_threads,
470
+ set(),
471
+ compute_to_main_queue,
472
+ prepare_to_compute_queue,
473
+ )
474
+ prepare_task_manager = task_manager(
475
+ prepare_task,
476
+ prefetch_threads,
477
+ start_list,
478
+ end_list,
479
+ completed,
480
+ prepare_to_compute_queue,
481
+ None,
482
+ )
483
+
484
+ t_checkpoint = time.time()
485
+ while True:
486
+ logging.info("Waiting for result")
487
+ value = compute_to_main_queue.get()
488
+ if not value:
489
+ break
490
+ centroid, t_wait_in, t_wait_out, t_compute, q_subset, D, list_ids, I = value
491
+ # to test checkpointing
492
+ if centroid == crash_at:
493
+ 1 / 0
494
+ bbs.t_accu[2] += t_compute
495
+ bbs.t_accu[4] += t_wait_in
496
+ bbs.t_accu[5] += t_wait_out
497
+ logging.info(f"Adding to heap start: centroid {centroid}")
498
+ bbs.add_results_to_heap(q_subset, D, list_ids, I)
499
+ logging.info(f"Adding to heap end: centroid {centroid}")
500
+ completed.add(centroid)
501
+ bbs.report(centroid)
502
+ if checkpoint is not None:
503
+ if time.time() - t_checkpoint > checkpoint_freq:
504
+ logging.info("writing checkpoint")
505
+ bbs.write_checkpoint(checkpoint, completed)
506
+ t_checkpoint = time.time()
507
+
508
+ prepare_task_manager.join()
509
+ compute_task_manager.join()
510
+
511
+ bbs.tic("finalize heap")
512
+ bbs.rh.finalize()
513
+ bbs.toc()
514
+
515
+ return bbs.rh.D, bbs.rh.I
ScaleDF_rebuttal/python_dedup_pkgs/faiss/contrib/client_server.py ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ #
3
+ # This source code is licensed under the MIT license found in the
4
+ # LICENSE file in the root directory of this source tree.
5
+
6
+ from multiprocessing.pool import ThreadPool
7
+ import faiss
8
+ from typing import List, Tuple
9
+
10
+ from . import rpc
11
+
12
+ ############################################################
13
+ # Server implementation
14
+ ############################################################
15
+
16
+
17
+ class SearchServer(rpc.Server):
18
+ """ Assign version that can be exposed via RPC """
19
+
20
+ def __init__(self, s: int, index: faiss.Index):
21
+ rpc.Server.__init__(self, s)
22
+ self.index = index
23
+ self.index_ivf = faiss.extract_index_ivf(index)
24
+
25
+ def set_nprobe(self, nprobe: int) -> int:
26
+ """ set nprobe field """
27
+ self.index_ivf.nprobe = nprobe
28
+
29
+ def get_ntotal(self) -> int:
30
+ return self.index.ntotal
31
+
32
+ def __getattr__(self, f):
33
+ # all other functions get forwarded to the index
34
+ return getattr(self.index, f)
35
+
36
+
37
+ def run_index_server(index: faiss.Index, port: int, v6: bool = False):
38
+ """ serve requests for that index forever """
39
+ rpc.run_server(
40
+ lambda s: SearchServer(s, index),
41
+ port, v6=v6)
42
+
43
+
44
+ ############################################################
45
+ # Client implementation
46
+ ############################################################
47
+
48
+ class ClientIndex:
49
+ """manages a set of distance sub-indexes. The sub_indexes search a
50
+ subset of the inverted lists. Searches are merged afterwards
51
+ """
52
+
53
+ def __init__(self, machine_ports: List[Tuple[str, int]], v6: bool = False):
54
+ """ connect to a series of (host, port) pairs """
55
+ self.sub_indexes = []
56
+ for machine, port in machine_ports:
57
+ self.sub_indexes.append(rpc.Client(machine, port, v6))
58
+
59
+ self.ni = len(self.sub_indexes)
60
+ # pool of threads. Each thread manages one sub-index.
61
+ self.pool = ThreadPool(self.ni)
62
+ # test connection...
63
+ self.ntotal = self.get_ntotal()
64
+ self.verbose = False
65
+
66
+ def set_nprobe(self, nprobe: int) -> None:
67
+ self.pool.map(
68
+ lambda idx: idx.set_nprobe(nprobe),
69
+ self.sub_indexes
70
+ )
71
+
72
+ def set_omp_num_threads(self, nt: int) -> None:
73
+ self.pool.map(
74
+ lambda idx: idx.set_omp_num_threads(nt),
75
+ self.sub_indexes
76
+ )
77
+
78
+ def get_ntotal(self) -> None:
79
+ return sum(self.pool.map(
80
+ lambda idx: idx.get_ntotal(),
81
+ self.sub_indexes
82
+ ))
83
+
84
+ def search(self, x, k: int):
85
+
86
+ rh = faiss.ResultHeap(x.shape[0], k)
87
+
88
+ for Di, Ii in self.pool.imap(lambda idx: idx.search(x, k), self.sub_indexes):
89
+ rh.add_result(Di, Ii)
90
+ rh.finalize()
91
+ return rh.D, rh.I
ScaleDF_rebuttal/python_dedup_pkgs/faiss/contrib/clustering.py ADDED
@@ -0,0 +1,502 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ #
3
+ # This source code is licensed under the MIT license found in the
4
+ # LICENSE file in the root directory of this source tree.
5
+
6
+ """
7
+ This contrib module contains a few routines useful to do clustering variants.
8
+ """
9
+
10
+ import numpy as np
11
+ import faiss
12
+ import time
13
+ from multiprocessing.pool import ThreadPool
14
+
15
+
16
+ try:
17
+ import scipy.sparse
18
+ except ImportError:
19
+ print("scipy not accessible, Python k-means will not work")
20
+
21
+
22
+ def print_nop(*arg, **kwargs):
23
+ pass
24
+
25
+
26
+ def two_level_clustering(xt, nc1, nc2, rebalance=True, clustering_niter=25, **args):
27
+ """
28
+ perform 2-level clustering on a training set xt
29
+ nc1 and nc2 are the number of clusters at each level, the final number of
30
+ clusters is nc2. Additional arguments are passed to the Kmeans object.
31
+
32
+ Rebalance allocates the number of sub-clusters depending on the number of
33
+ first-level assignment.
34
+ """
35
+ d = xt.shape[1]
36
+
37
+ verbose = args.get("verbose", False)
38
+
39
+ log = print if verbose else print_nop
40
+
41
+ log(f"2-level clustering of {xt.shape} nb 1st level clusters = {nc1} total {nc2}")
42
+ log("perform coarse training")
43
+
44
+ km = faiss.Kmeans(
45
+ d, nc1, niter=clustering_niter,
46
+ max_points_per_centroid=2000,
47
+ **args
48
+ )
49
+ km.train(xt)
50
+
51
+ iteration_stats = [km.iteration_stats]
52
+ log()
53
+
54
+ # coarse centroids
55
+ centroids1 = km.centroids
56
+
57
+ log("assigning the training set")
58
+ t0 = time.time()
59
+ _, assign1 = km.assign(xt)
60
+ bc = np.bincount(assign1, minlength=nc1)
61
+ log(f"done in {time.time() - t0:.2f} s. Sizes of clusters {min(bc)}-{max(bc)}")
62
+ o = assign1.argsort()
63
+ del km
64
+
65
+ if not rebalance:
66
+ # make sure the sub-clusters sum up to exactly nc2
67
+ cc = np.arange(nc1 + 1) * nc2 // nc1
68
+ all_nc2 = cc[1:] - cc[:-1]
69
+ else:
70
+ bc_sum = np.cumsum(bc)
71
+ all_nc2 = bc_sum * nc2 // bc_sum[-1]
72
+ all_nc2[1:] -= all_nc2[:-1]
73
+ assert sum(all_nc2) == nc2
74
+ log(f"nb 2nd-level centroids {min(all_nc2)}-{max(all_nc2)}")
75
+
76
+ # train sub-clusters
77
+ i0 = 0
78
+ c2 = []
79
+ t0 = time.time()
80
+ for c1 in range(nc1):
81
+ nc2 = int(all_nc2[c1])
82
+ log(f"[{time.time() - t0:.2f} s] training sub-cluster {c1}/{nc1} nc2={nc2}\r", end="", flush=True)
83
+ i1 = i0 + bc[c1]
84
+ subset = o[i0:i1]
85
+ assert np.all(assign1[subset] == c1)
86
+ km = faiss.Kmeans(d, nc2, **args)
87
+ xtsub = xt[subset]
88
+ km.train(xtsub)
89
+ iteration_stats.append(km.iteration_stats)
90
+ c2.append(km.centroids)
91
+ del km
92
+ i0 = i1
93
+ log(f"done in {time.time() - t0:.2f} s")
94
+ return np.vstack(c2), iteration_stats
95
+
96
+
97
+ def train_ivf_index_with_2level(index, xt, **args):
98
+ """
99
+ Applies 2-level clustering to an index_ivf embedded in an index.
100
+ """
101
+ # handle PreTransforms
102
+ index = faiss.downcast_index(index)
103
+ if isinstance(index, faiss.IndexPreTransform):
104
+ for i in range(index.chain.size()):
105
+ vt = index.chain.at(i)
106
+ vt.train(xt)
107
+ xt = vt.apply(xt)
108
+ train_ivf_index_with_2level(index.index, xt, **args)
109
+ index.is_trained = True
110
+ return
111
+ assert isinstance(index, faiss.IndexIVF)
112
+ assert index.metric_type == faiss.METRIC_L2
113
+ # now do 2-level clustering
114
+ nc1 = int(np.sqrt(index.nlist))
115
+ print("REBALANCE=", args)
116
+
117
+ centroids, _ = two_level_clustering(xt, nc1, index.nlist, **args)
118
+ index.quantizer.train(centroids)
119
+ index.quantizer.add(centroids)
120
+ # finish training
121
+ index.train(xt)
122
+
123
+
124
+ def balanced_assignment_with_penalties(x, centroids, alpha = 0.03, num_iter = 20, maxk = 100):
125
+ """
126
+ Assign vectors x to centroids with a balance constraint.
127
+
128
+ Iteratively adjusts per-cluster penalties so that oversized clusters
129
+ become less attractive. At each iteration the penalized distance for
130
+ cluster c is ``d(x, c)^2 + penalty_c^2`` and the penalty is updated as
131
+ ``penalty_c *= (binsize_c / n_opt) ** alpha`` where ``n_opt = n / nc``.
132
+
133
+ A single kNN call (with *maxk* neighbors) is done upfront; subsequent
134
+ iterations only re-weight among those candidates, making the routine
135
+ fast even for large datasets.
136
+
137
+ Reference: "Balancing clusters to reduce response time variability in
138
+ large scale image search", Tavenard et al., CBMI 2011.
139
+ https://inria.hal.science/inria-00576886/document
140
+ See also notebook N10159950.
141
+
142
+ Args:
143
+ x: (n, d) float32 array of vectors to assign.
144
+ centroids: (nc, d) float32 array of cluster centroids.
145
+ alpha: exponent that controls how aggressively penalties grow.
146
+ Higher values yield more balanced clusters at the cost
147
+ of higher MSE. Typical range: 0.01 – 0.1.
148
+ num_iter: number of penalty-update iterations.
149
+ maxk: number of nearest centroids to consider per vector.
150
+ Must be <= nc.
151
+
152
+ Returns:
153
+ assign: (n,) int64 array of centroid indices.
154
+ stats: dict with keys
155
+
156
+ - *imf*: imbalance factor (1.0 = perfectly balanced)
157
+ - *mse*: mean squared error of the assignment
158
+ - *binsize_min*, *binsize_max*: smallest / largest cluster
159
+ - *penalty_min*, *penalty_max*: penalty value range
160
+ - *alpha*: the alpha value used
161
+ """
162
+
163
+ nc = len(centroids)
164
+ n = len(x)
165
+ nopt = n / nc # targed bin sizes
166
+
167
+ # we assign to the top-maxk clusters. The final assignment will pick among these clusters.
168
+ full_d2, full_assign = faiss.knn(x, centroids, maxk)
169
+
170
+ # scalar penalty for each cluster
171
+ penalties = np.ones(nc, dtype=np.float32)
172
+
173
+ for it in range(num_iter):
174
+ # compute penalized assignment
175
+ penalties2 = penalties ** 2
176
+ full_d2_penalized = full_d2 + penalties2[full_assign]
177
+ a0 = full_d2_penalized.argmin(axis=1)
178
+ assign = np.take_along_axis(full_assign, a0[:, None], axis=1).ravel()
179
+ binsizes = np.bincount(assign, minlength=nc)
180
+ # print(imbalance_factor(nc, assign), mse, int(binsizes.min()), int(binsizes.max()))
181
+ penalties *= (binsizes / nopt) ** alpha
182
+
183
+ stats = dict(
184
+ alpha=alpha,
185
+ imf=imbalance_factor(nc, assign),
186
+ mse = ((x - centroids[assign]) ** 2).sum(1).mean(), # recompute MSE
187
+ binsize_min=int(binsizes.min()),
188
+ binsize_max=int(binsizes.max()),
189
+ penalty_min=penalties.min(),
190
+ penalty_max=penalties.max(),
191
+ )
192
+
193
+ return assign, stats
194
+
195
+
196
+ ###############################################################################
197
+ # K-means implementation in Python
198
+ #
199
+ # It relies on DatasetAssign, an abstraction of the training vectors that offers
200
+ # the minimal set of operations to perform k-means clustering.
201
+ ###############################################################################
202
+
203
+
204
+ class DatasetAssign:
205
+ """Wrapper for a matrix that offers a function to assign the vectors
206
+ to centroids. All other implementations offer the same interface"""
207
+
208
+ def __init__(self, x):
209
+ self.x = np.ascontiguousarray(x, dtype='float32')
210
+
211
+ def count(self):
212
+ return self.x.shape[0]
213
+
214
+ def dim(self):
215
+ return self.x.shape[1]
216
+
217
+ def get_subset(self, indices):
218
+ return self.x[indices]
219
+
220
+ def perform_search(self, centroids):
221
+ return faiss.knn(self.x, centroids, 1)
222
+
223
+ def assign_to(self, centroids, weights=None):
224
+ D, I = self.perform_search(centroids)
225
+
226
+ I = I.ravel()
227
+ D = D.ravel()
228
+ nc, d = centroids.shape
229
+ sum_per_centroid = np.zeros((nc, d), dtype='float32')
230
+ if weights is None:
231
+ np.add.at(sum_per_centroid, I, self.x)
232
+ else:
233
+ np.add.at(sum_per_centroid, I, weights[:, np.newaxis] * self.x)
234
+
235
+ return I, D, sum_per_centroid
236
+
237
+
238
+ class DatasetAssignGPU(DatasetAssign):
239
+ """ GPU version of the previous """
240
+
241
+ def __init__(self, x, gpu_id, verbose=False):
242
+ DatasetAssign.__init__(self, x)
243
+ index = faiss.IndexFlatL2(x.shape[1])
244
+ if gpu_id >= 0:
245
+ self.index = faiss.index_cpu_to_gpu(
246
+ faiss.StandardGpuResources(),
247
+ gpu_id, index)
248
+ else:
249
+ # -1 -> assign to all GPUs
250
+ self.index = faiss.index_cpu_to_all_gpus(index)
251
+
252
+ def perform_search(self, centroids):
253
+ self.index.reset()
254
+ self.index.add(centroids)
255
+ return self.index.search(self.x, 1)
256
+
257
+
258
+ def sparse_assign_to_dense(xq, xb, xq_norms=None, xb_norms=None):
259
+ """ assignment function for xq is sparse, xb is dense
260
+ uses a matrix multiplication. The squared norms can be provided if
261
+ available.
262
+ """
263
+ nq = xq.shape[0]
264
+ nb = xb.shape[0]
265
+ if xb_norms is None:
266
+ xb_norms = (xb ** 2).sum(1)
267
+ if xq_norms is None:
268
+ xq_norms = np.array(xq.power(2).sum(1))
269
+ d2 = xb_norms - 2 * xq @ xb.T
270
+ I = d2.argmin(axis=1)
271
+ D = d2.ravel()[I + np.arange(nq) * nb] + xq_norms.ravel()
272
+ return D, I
273
+
274
+
275
+ def sparse_assign_to_dense_blocks(
276
+ xq, xb, xq_norms=None, xb_norms=None, qbs=16384, bbs=16384, nt=None):
277
+ """
278
+ decomposes the sparse_assign_to_dense function into blocks to avoid a
279
+ possible memory blow up. Can be run in multithreaded mode, because scipy's
280
+ sparse-dense matrix multiplication is single-threaded.
281
+ """
282
+ nq = xq.shape[0]
283
+ nb = xb.shape[0]
284
+ D = np.empty(nq, dtype="float32")
285
+ D.fill(np.inf)
286
+ I = -np.ones(nq, dtype=int)
287
+
288
+ if xb_norms is None:
289
+ xb_norms = (xb ** 2).sum(1)
290
+
291
+ def handle_query_block(i):
292
+ xq_block = xq[i : i + qbs]
293
+ Iblock = I[i : i + qbs]
294
+ Dblock = D[i : i + qbs]
295
+ if xq_norms is None:
296
+ xq_norms_block = np.array(xq_block.power(2).sum(1))
297
+ else:
298
+ xq_norms_block = xq_norms[i : i + qbs]
299
+ for j in range(0, nb, bbs):
300
+ Di, Ii = sparse_assign_to_dense(
301
+ xq_block,
302
+ xb[j : j + bbs],
303
+ xq_norms=xq_norms_block,
304
+ xb_norms=xb_norms[j : j + bbs],
305
+ )
306
+ if j == 0:
307
+ Iblock[:] = Ii
308
+ Dblock[:] = Di
309
+ else:
310
+ mask = Di < Dblock
311
+ Iblock[mask] = Ii[mask] + j
312
+ Dblock[mask] = Di[mask]
313
+
314
+ if nt == 0 or nt == 1 or nq <= qbs:
315
+ list(map(handle_query_block, range(0, nq, qbs)))
316
+ else:
317
+ pool = ThreadPool(nt)
318
+ pool.map(handle_query_block, range(0, nq, qbs))
319
+
320
+ return D, I
321
+
322
+
323
+ class DatasetAssignSparse(DatasetAssign):
324
+ """Wrapper for a matrix that offers a function to assign the vectors
325
+ to centroids. All other implementations offer the same interface"""
326
+
327
+ def __init__(self, x):
328
+ assert x.__class__ == scipy.sparse.csr_matrix
329
+ self.x = x
330
+ self.squared_norms = np.array(x.power(2).sum(1))
331
+
332
+ def get_subset(self, indices):
333
+ return np.array(self.x[indices].todense())
334
+
335
+ def perform_search(self, centroids):
336
+ return sparse_assign_to_dense_blocks(
337
+ self.x, centroids, xq_norms=self.squared_norms)
338
+
339
+ def assign_to(self, centroids, weights=None):
340
+ D, I = self.perform_search(centroids)
341
+
342
+ I = I.ravel()
343
+ D = D.ravel()
344
+ n = self.x.shape[0]
345
+ if weights is None:
346
+ weights = np.ones(n, dtype='float32')
347
+ nc = len(centroids)
348
+
349
+ m = scipy.sparse.csc_matrix(
350
+ (weights, I, np.arange(n + 1)),
351
+ shape=(nc, n))
352
+ sum_per_centroid = np.array((m * self.x).todense())
353
+
354
+ return I, D, sum_per_centroid
355
+
356
+
357
+ def imbalance_factor(k, assign):
358
+ assign = np.ascontiguousarray(assign, dtype='int64')
359
+ return faiss.imbalance_factor(len(assign), k, faiss.swig_ptr(assign))
360
+
361
+
362
+ def check_if_torch(x):
363
+ if x.__class__ == np.ndarray:
364
+ return False
365
+ import torch
366
+ if isinstance(x, torch.Tensor):
367
+ return True
368
+ raise NotImplementedError(f"Unknown tensor type {type(x)}")
369
+
370
+
371
+ def reassign_centroids(hassign, centroids, rs=None):
372
+ """ reassign centroids when some of them collapse """
373
+ if rs is None:
374
+ rs = np.random
375
+ k, d = centroids.shape
376
+ nsplit = 0
377
+ is_torch = check_if_torch(centroids)
378
+
379
+ empty_cents = np.where(hassign == 0)[0]
380
+
381
+ if len(empty_cents) == 0:
382
+ return 0
383
+
384
+ if is_torch:
385
+ import torch
386
+ fac = torch.ones_like(centroids[0])
387
+ else:
388
+ fac = np.ones_like(centroids[0])
389
+ fac[::2] += 1 / 1024.
390
+ fac[1::2] -= 1 / 1024.
391
+
392
+ # this is a single pass unless there are more than k/2
393
+ # empty centroids
394
+ while len(empty_cents) > 0:
395
+ # choose which centroids to split (numpy)
396
+ probas = hassign.astype('float') - 1
397
+ probas[probas < 0] = 0
398
+ probas /= probas.sum()
399
+ nnz = (probas > 0).sum()
400
+
401
+ nreplace = min(nnz, empty_cents.size)
402
+ cjs = rs.choice(k, size=nreplace, p=probas)
403
+
404
+ for ci, cj in zip(empty_cents[:nreplace], cjs):
405
+
406
+ c = centroids[cj]
407
+ centroids[ci] = c * fac
408
+ centroids[cj] = c / fac
409
+
410
+ hassign[ci] = hassign[cj] // 2
411
+ hassign[cj] -= hassign[ci]
412
+ nsplit += 1
413
+
414
+ empty_cents = empty_cents[nreplace:]
415
+
416
+ return nsplit
417
+
418
+
419
+
420
+ def kmeans(k, data, niter=25, seed=1234, checkpoint=None, verbose=True,
421
+ return_stats=False):
422
+ """Pure python kmeans implementation. Follows the Faiss C++ version
423
+ quite closely, but takes a DatasetAssign instead of a training data
424
+ matrix. Also redo is not implemented.
425
+
426
+ For the torch implementation, the centroids are tensors (possibly on GPU),
427
+ but the indices remain numpy on CPU.
428
+ """
429
+ n, d = data.count(), data.dim()
430
+ log = print if verbose else print_nop
431
+
432
+ log(("Clustering %d points in %dD to %d clusters, " +
433
+ "%d iterations seed %d") % (n, d, k, niter, seed))
434
+
435
+ rs = np.random.RandomState(seed)
436
+ print("preproc...")
437
+ t0 = time.time()
438
+ # initialization
439
+ perm = rs.choice(n, size=k, replace=False)
440
+ centroids = data.get_subset(perm)
441
+ is_torch = check_if_torch(centroids)
442
+
443
+ iteration_stats = []
444
+
445
+ log(" done")
446
+ t_search_tot = 0
447
+ obj = []
448
+ for i in range(niter):
449
+ t0s = time.time()
450
+
451
+ log('assigning', end='\r', flush=True)
452
+ assign, D, sums = data.assign_to(centroids)
453
+
454
+ log('compute centroids', end='\r', flush=True)
455
+
456
+ t_search_tot += time.time() - t0s
457
+
458
+ err = D.sum()
459
+ if is_torch:
460
+ err = err.item()
461
+ obj.append(err)
462
+
463
+ hassign = np.bincount(assign, minlength=k)
464
+
465
+ fac = hassign.reshape(-1, 1).astype('float32')
466
+ fac[fac == 0] = 1 # quiet warning
467
+ if is_torch:
468
+ import torch
469
+ fac = torch.from_numpy(fac).to(sums.device)
470
+
471
+ centroids = sums / fac
472
+
473
+ nsplit = reassign_centroids(hassign, centroids, rs)
474
+
475
+ s = {
476
+ "obj": err,
477
+ "time": (time.time() - t0),
478
+ "time_search": t_search_tot,
479
+ "imbalance_factor": imbalance_factor(k, assign),
480
+ "nsplit": nsplit
481
+ }
482
+
483
+ log((" Iteration %d (%.2f s, search %.2f s): "
484
+ "objective=%g imbalance=%.3f nsplit=%d") % (
485
+ i, s["time"], s["time_search"],
486
+ err, s["imbalance_factor"],
487
+ nsplit)
488
+ )
489
+ iteration_stats.append(s)
490
+
491
+ if checkpoint is not None:
492
+ log('storing centroids in', checkpoint)
493
+ if is_torch:
494
+ import torch
495
+ torch.save(centroids, checkpoint)
496
+ else:
497
+ np.save(checkpoint, centroids)
498
+
499
+ if return_stats:
500
+ return centroids, iteration_stats
501
+ else:
502
+ return centroids
ScaleDF_rebuttal/python_dedup_pkgs/faiss/contrib/datasets.py ADDED
@@ -0,0 +1,465 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ #
3
+ # This source code is licensed under the MIT license found in the
4
+ # LICENSE file in the root directory of this source tree.
5
+
6
+ import os
7
+ import numpy as np
8
+ import faiss
9
+ import getpass
10
+
11
+
12
+ from .vecs_io import fvecs_read, ivecs_read, bvecs_mmap, fvecs_mmap, bvecs_iter, bvecs_iter_chunked
13
+ from .exhaustive_search import knn
14
+
15
+
16
+ class Dataset:
17
+ """ Generic abstract class for a test dataset """
18
+
19
+ def __init__(self):
20
+ """ the constructor should set the following fields: """
21
+ self.d = -1
22
+ self.metric = 'L2' # or IP
23
+ self.nq = -1
24
+ self.nb = -1
25
+ self.nt = -1
26
+
27
+ def get_queries(self):
28
+ """ return the queries as a (nq, d) array """
29
+ raise NotImplementedError()
30
+
31
+ def get_train(self, maxtrain=None):
32
+ """ return the queries as a (nt, d) array """
33
+ raise NotImplementedError()
34
+
35
+ def get_database(self):
36
+ """ return the queries as a (nb, d) array """
37
+ raise NotImplementedError()
38
+
39
+ def database_iterator(self, bs=128, split=(1, 0)):
40
+ """returns an iterator on database vectors.
41
+ bs is the number of vectors per batch
42
+ split = (nsplit, rank) means the dataset is split in nsplit
43
+ shards and we want shard number rank
44
+ The default implementation just iterates over the full matrix
45
+ returned by get_dataset.
46
+ """
47
+ xb = self.get_database()
48
+ nsplit, rank = split
49
+ i0, i1 = self.nb * rank // nsplit, self.nb * (rank + 1) // nsplit
50
+ for j0 in range(i0, i1, bs):
51
+ yield xb[j0: min(j0 + bs, i1)]
52
+
53
+ def get_groundtruth(self, k=None):
54
+ """ return the ground truth for k-nearest neighbor search """
55
+ raise NotImplementedError()
56
+
57
+ def get_groundtruth_range(self, thresh=None):
58
+ """ return the ground truth for range search """
59
+ raise NotImplementedError()
60
+
61
+ def __str__(self):
62
+ return (f"dataset in dimension {self.d}, with metric {self.metric}, "
63
+ f"size: Q {self.nq} B {self.nb} T {self.nt}")
64
+
65
+ def check_sizes(self):
66
+ """ runs the previous and checks the sizes of the matrices """
67
+ assert self.get_queries().shape == (self.nq, self.d)
68
+ if self.nt > 0:
69
+ xt = self.get_train(maxtrain=123)
70
+ assert xt.shape == (123, self.d), "shape=%s" % (xt.shape, )
71
+ assert self.get_database().shape == (self.nb, self.d)
72
+ assert self.get_groundtruth(k=13).shape == (self.nq, 13)
73
+
74
+
75
+ class SyntheticDataset(Dataset):
76
+ """A dataset that is not completely random but still challenging to
77
+ index
78
+ """
79
+
80
+ def __init__(self, d, nt, nb, nq, metric='L2', seed=1338):
81
+ Dataset.__init__(self)
82
+ self.d, self.nt, self.nb, self.nq = d, nt, nb, nq
83
+ d1 = 10 # intrinsic dimension (more or less)
84
+ n = nb + nt + nq
85
+ rs = np.random.RandomState(seed)
86
+ x = rs.normal(size=(n, d1))
87
+ x = np.dot(x, rs.rand(d1, d))
88
+ # now we have a d1-dim ellipsoid in d-dimensional space
89
+ # higher factor (>4) -> higher frequency -> less linear
90
+ x = x * (rs.rand(d) * 4 + 0.1)
91
+ x = np.sin(x)
92
+ x = x.astype('float32')
93
+ self.metric = metric
94
+ self.xt = x[:nt]
95
+ self.xb = x[nt:nt + nb]
96
+ self.xq = x[nt + nb:]
97
+
98
+ def get_queries(self):
99
+ return self.xq
100
+
101
+ def get_train(self, maxtrain=None):
102
+ maxtrain = maxtrain if maxtrain is not None else self.nt
103
+ return self.xt[:maxtrain]
104
+
105
+ def get_database(self):
106
+ return self.xb
107
+
108
+ def get_groundtruth(self, k=100):
109
+ return knn(
110
+ self.xq, self.xb, k,
111
+ faiss.METRIC_L2 if self.metric == 'L2' else faiss.METRIC_INNER_PRODUCT
112
+ )[1]
113
+
114
+
115
+ ############################################################################
116
+ # The following datasets are a few standard open-source datasets
117
+ # they should be stored in a directory, and we start by guessing where
118
+ # that directory is
119
+ ############################################################################
120
+
121
+ username = getpass.getuser()
122
+
123
+ for dataset_basedir in (
124
+ '/datasets01/simsearch/041218/',
125
+ '/mnt/vol/gfsai-flash3-east/ai-group/datasets/simsearch/',
126
+ f'/home/{username}/simsearch/data/'):
127
+ if os.path.exists(dataset_basedir):
128
+ break
129
+ else:
130
+ # users can link their data directory to `./data`
131
+ dataset_basedir = 'data/'
132
+
133
+
134
+ def set_dataset_basedir(path):
135
+ global dataset_basedir
136
+ dataset_basedir = path
137
+
138
+
139
+ class DatasetSIFT1M(Dataset):
140
+ """
141
+ The original dataset is available at: http://corpus-texmex.irisa.fr/
142
+ (ANN_SIFT1M)
143
+ """
144
+
145
+ def __init__(self):
146
+ Dataset.__init__(self)
147
+ self.d, self.nt, self.nb, self.nq = 128, 100000, 1000000, 10000
148
+ self.basedir = dataset_basedir + 'sift1M/'
149
+
150
+ def get_queries(self):
151
+ return fvecs_read(self.basedir + "sift_query.fvecs")
152
+
153
+ def get_train(self, maxtrain=None):
154
+ maxtrain = maxtrain if maxtrain is not None else self.nt
155
+ return fvecs_read(self.basedir + "sift_learn.fvecs")[:maxtrain]
156
+
157
+ def get_database(self):
158
+ return fvecs_read(self.basedir + "sift_base.fvecs")
159
+
160
+ def get_groundtruth(self, k=None):
161
+ gt = ivecs_read(self.basedir + "sift_groundtruth.ivecs")
162
+ if k is not None:
163
+ assert k <= 100
164
+ gt = gt[:, :k]
165
+ return gt
166
+
167
+
168
+ def sanitize(x):
169
+ return np.ascontiguousarray(x, dtype='float32')
170
+
171
+
172
+ class DatasetBigANN(Dataset):
173
+ """
174
+ The original dataset is available at: http://corpus-texmex.irisa.fr/
175
+ (ANN_SIFT1B)
176
+ """
177
+
178
+ def __init__(self, nb_M=1000):
179
+ Dataset.__init__(self)
180
+ assert nb_M in (1, 2, 5, 10, 20, 50, 100, 200, 500, 1000)
181
+ self.nb_M = nb_M
182
+ nb = nb_M * 10**6
183
+ self.d, self.nt, self.nb, self.nq = 128, 10**8, nb, 10000
184
+ self.basedir = dataset_basedir + 'bigann/'
185
+
186
+ def get_queries(self):
187
+ return sanitize(bvecs_mmap(self.basedir + 'bigann_query.bvecs')[:])
188
+
189
+ def get_train(self, maxtrain=None):
190
+ maxtrain = maxtrain if maxtrain is not None else self.nt
191
+ return sanitize(bvecs_mmap(self.basedir + 'bigann_learn.bvecs')[:maxtrain])
192
+
193
+ def get_groundtruth(self, k=None):
194
+ gt = ivecs_read(self.basedir + 'gnd/idx_%dM.ivecs' % self.nb_M)
195
+ if k is not None:
196
+ assert k <= 100
197
+ gt = gt[:, :k]
198
+ return gt
199
+
200
+ def get_database(self):
201
+ assert self.nb_M < 100, "dataset too large, use iterator"
202
+ return sanitize(bvecs_mmap(self.basedir + 'bigann_base.bvecs')[:self.nb])
203
+
204
+ def database_iterator(self, bs=128, split=(1, 0)):
205
+ xb = bvecs_mmap(self.basedir + 'bigann_base.bvecs')
206
+ nsplit, rank = split
207
+ i0, i1 = self.nb * rank // nsplit, self.nb * (rank + 1) // nsplit
208
+ for j0 in range(i0, i1, bs):
209
+ yield sanitize(xb[j0: min(j0 + bs, i1)])
210
+
211
+
212
+ class DatasetDeep1B(Dataset):
213
+ """
214
+ See
215
+ https://github.com/facebookresearch/faiss/tree/main/benchs#getting-deep1b
216
+ on how to get the data
217
+ """
218
+
219
+ def __init__(self, nb=10**9):
220
+ Dataset.__init__(self)
221
+ nb_to_name = {
222
+ 10**5: '100k',
223
+ 10**6: '1M',
224
+ 10**7: '10M',
225
+ 10**8: '100M',
226
+ 10**9: '1B'
227
+ }
228
+ assert nb in nb_to_name
229
+ self.d, self.nt, self.nb, self.nq = 96, 358480000, nb, 10000
230
+ self.basedir = dataset_basedir + 'deep1b/'
231
+ self.gt_fname = "%sdeep%s_groundtruth.ivecs" % (
232
+ self.basedir, nb_to_name[self.nb])
233
+
234
+ def get_queries(self):
235
+ return sanitize(fvecs_read(self.basedir + "deep1B_queries.fvecs"))
236
+
237
+ def get_train(self, maxtrain=None):
238
+ maxtrain = maxtrain if maxtrain is not None else self.nt
239
+ return sanitize(fvecs_mmap(self.basedir + "learn.fvecs")[:maxtrain])
240
+
241
+ def get_groundtruth(self, k=None):
242
+ gt = ivecs_read(self.gt_fname)
243
+ if k is not None:
244
+ assert k <= 100
245
+ gt = gt[:, :k]
246
+ return gt
247
+
248
+ def get_database(self):
249
+ assert self.nb <= 10**8, "dataset too large, use iterator"
250
+ return sanitize(fvecs_mmap(self.basedir + "base.fvecs")[:self.nb])
251
+
252
+ def database_iterator(self, bs=128, split=(1, 0)):
253
+ xb = fvecs_mmap(self.basedir + "base.fvecs")
254
+ nsplit, rank = split
255
+ i0, i1 = self.nb * rank // nsplit, self.nb * (rank + 1) // nsplit
256
+ for j0 in range(i0, i1, bs):
257
+ yield sanitize(xb[j0: min(j0 + bs, i1)])
258
+
259
+
260
+ class DatasetGlove(Dataset):
261
+ """
262
+ Data from http://ann-benchmarks.com/glove-100-angular.hdf5
263
+ """
264
+
265
+ def __init__(self, loc=None, download=False):
266
+ import h5py
267
+ assert not download, "not implemented"
268
+ if not loc:
269
+ loc = dataset_basedir + 'glove/glove-100-angular.hdf5'
270
+ self.glove_h5py = h5py.File(loc, 'r')
271
+ # IP and L2 are equivalent in this case, but it is traditionally seen as an IP dataset
272
+ self.metric = 'IP'
273
+ self.d, self.nt = 100, 0
274
+ self.nb = self.glove_h5py['train'].shape[0]
275
+ self.nq = self.glove_h5py['test'].shape[0]
276
+
277
+ def get_queries(self):
278
+ xq = np.array(self.glove_h5py['test'])
279
+ faiss.normalize_L2(xq)
280
+ return xq
281
+
282
+ def get_database(self):
283
+ xb = np.array(self.glove_h5py['train'])
284
+ faiss.normalize_L2(xb)
285
+ return xb
286
+
287
+ def get_groundtruth(self, k=None):
288
+ gt = self.glove_h5py['neighbors']
289
+ if k is not None:
290
+ assert k <= 100
291
+ gt = gt[:, :k]
292
+ return gt
293
+
294
+
295
+ class DatasetMusic100(Dataset):
296
+ """
297
+ get dataset from
298
+ https://github.com/stanis-morozov/ip-nsw#dataset
299
+ """
300
+
301
+ def __init__(self):
302
+ Dataset.__init__(self)
303
+ self.d, self.nt, self.nb, self.nq = 100, 0, 10**6, 10000
304
+ self.metric = 'IP'
305
+ self.basedir = dataset_basedir + 'music-100/'
306
+
307
+ def get_queries(self):
308
+ xq = np.fromfile(self.basedir + 'query_music100.bin', dtype='float32')
309
+ xq = xq.reshape(-1, 100)
310
+ return xq
311
+
312
+ def get_database(self):
313
+ xb = np.fromfile(self.basedir + 'database_music100.bin', dtype='float32')
314
+ xb = xb.reshape(-1, 100)
315
+ return xb
316
+
317
+ def get_groundtruth(self, k=None):
318
+ gt = np.load(self.basedir + 'gt.npy')
319
+ if k is not None:
320
+ assert k <= 100
321
+ gt = gt[:, :k]
322
+ return gt
323
+
324
+
325
+ class DatasetGIST1M(Dataset):
326
+ """
327
+ The original dataset is available at: http://corpus-texmex.irisa.fr/
328
+ (ANN_GIST1M)
329
+ """
330
+
331
+ def __init__(self):
332
+ Dataset.__init__(self)
333
+ self.d, self.nt, self.nb, self.nq = 960, 100000, 1000000, 10000
334
+ self.basedir = dataset_basedir + 'gist1M/'
335
+
336
+ def get_queries(self):
337
+ return fvecs_read(self.basedir + "gist_query.fvecs")
338
+
339
+ def get_train(self, maxtrain=None):
340
+ maxtrain = maxtrain if maxtrain is not None else self.nt
341
+ return fvecs_read(self.basedir + "gist_learn.fvecs")[:maxtrain]
342
+
343
+ def get_database(self):
344
+ return fvecs_read(self.basedir + "gist_base.fvecs")
345
+
346
+ def get_groundtruth(self, k=None):
347
+ gt = ivecs_read(self.basedir + "gist_groundtruth.ivecs")
348
+ if k is not None:
349
+ assert k <= 100
350
+ gt = gt[:, :k]
351
+ return gt
352
+
353
+ class DatasetDINO10B(Dataset):
354
+ """
355
+ Data from https://dl.fbaipublicfiles.com/large_objects/dino_vitl_10B/
356
+ The dataset contains 10 billion 1024-d vectors extracted from image patches from the YFCC100M dataset, using a Dino-ViT-L 16 model (facebook/dinov3-vitl16-pretrain-lvd1689m).
357
+ The dataset is sharded in multiple chunked .bvecs files. Downloading instructions can be obtained with "wget https://dl.fbaipublicfiles.com/large_objects/dino_vitl_10B/README.md".
358
+ Supported sizes : 100k 200k 500k 1M ... 5B 10B listed in supported_nbs (see __init__).
359
+ """
360
+ def __init__(self, nb, ignore_supported = False):
361
+ Dataset.__init__(self)
362
+ supported_nbs = [100_000, 200_000, 500_000, 1_000_000, 2_000_000, 5_000_000, 10_000_000, 20_000_000, 50_000_000, 100_000_000, 200_000_000, 500_000_000, 1_000_000_000, 2_000_000_000, 5_000_000_000, 10_000_000_000]
363
+ if nb not in supported_nbs and not ignore_supported:
364
+ raise ValueError(f"Unsupported dataset size: {nb}, supported values are: {supported_nbs}")
365
+ if not os.path.exists(dataset_basedir):
366
+ raise ValueError(f"Provided dataset base directory does not exist: {dataset_basedir}")
367
+ self.basedir = dataset_basedir + "dino_vitl_10B/"
368
+ self.indexdir = self.basedir + "chunked_base_10B"
369
+ assert os.path.exists(self.indexdir), f"Index path should exist, check your dataset path: {self.indexdir}"
370
+ self.queriesdir = self.basedir + "queries_clean.bvecs"
371
+ assert os.path.exists(self.queriesdir), f"Queries path should exist as dataset size {nb} is supported: {self.queriesdir}"
372
+ self.gtsdir = self.basedir + "gts/" + "gts_dino_patch_" + str(nb) + "_" + "k10.npy"
373
+ self.train_queriesdir = self.basedir + "train_queries_99M.bvecs"
374
+ self.nb = nb
375
+ self.d = 1024
376
+ self.nq = 100_000
377
+ self.nt = 99_000_000
378
+ self.metric = "L2"
379
+
380
+
381
+ def get_queries(self):
382
+ """Get all vectors as a single array"""
383
+ queries = bvecs_mmap(self.queriesdir)
384
+ return sanitize(queries)
385
+
386
+ def get_train(self, maxtrain = None):
387
+ """Get training query vectors as a single array"""
388
+ if maxtrain is None or maxtrain > 10_000_000:
389
+ raise NotImplementedError("The training set is potentially too large to fit in RAM (400 GB of data). Please use train_iterator or use maxtrain parameter below 10_000_000 to get the first maxtrain training vectors.")
390
+ return sanitize(bvecs_mmap(self.train_queriesdir)[:maxtrain])
391
+
392
+ def get_database(self):
393
+ """Get all database vectors as a single array"""
394
+ if self.nb > 10_000_000:
395
+ raise NotImplementedError("The dataset is potentially too large to fit in RAM. Please use database_iterator or use a dataset size equal to or below 10_000_000.")
396
+ else:
397
+ return sanitize(bvecs_iter_chunked(self.indexdir, batch_size=self.nb).__next__())
398
+
399
+ def database_iterator(self, bs=10_000):
400
+ """Iterator over the database of size nb, corresponding to the first nb vectors in the .bvecs file"""
401
+ total_read = 0
402
+ for batch in bvecs_iter_chunked(self.indexdir, batch_size=bs):
403
+ if total_read + batch.shape[0] > self.nb:
404
+ batch = batch[:self.nb - total_read]
405
+ yield sanitize(batch)
406
+ total_read += batch.shape[0]
407
+ if total_read >= self.nb:
408
+ break
409
+
410
+ def train_iterator(self, bs=10_000):
411
+ """Iterator over all training query vectors in the .bvecs file"""
412
+ for batch in bvecs_iter(self.train_queriesdir, batch_size=bs):
413
+ yield sanitize(batch)
414
+
415
+ def get_groundtruth(self, k = 10):
416
+ """Get ground truth from .npy file"""
417
+ if k > 10:
418
+ raise NotImplementedError("Ground truth files only available for k<=10")
419
+ gts = np.load(self.gtsdir)
420
+ gts = gts[:, :k]
421
+ return gts
422
+
423
+ def distance(self):
424
+ return "euclidean"
425
+
426
+ def dataset_from_name(dataset='deep1M', download=False):
427
+ """ converts a string describing a dataset to a Dataset object
428
+ Supports sift1M, bigann1M..bigann1B, deep1M..deep1B, music-100 and glove
429
+ """
430
+
431
+ if dataset == 'sift1M':
432
+ return DatasetSIFT1M()
433
+
434
+ elif dataset == 'gist1M':
435
+ return DatasetGIST1M()
436
+
437
+ elif dataset.startswith('bigann'):
438
+ dbsize = 1000 if dataset == "bigann1B" else int(dataset[6:-1])
439
+ return DatasetBigANN(nb_M=dbsize)
440
+
441
+ elif dataset.startswith("deep"):
442
+
443
+ szsuf = dataset[4:]
444
+ if szsuf[-1] == 'M':
445
+ dbsize = 10 ** 6 * int(szsuf[:-1])
446
+ elif szsuf == '1B':
447
+ dbsize = 10 ** 9
448
+ elif szsuf[-1] == 'k':
449
+ dbsize = 1000 * int(szsuf[:-1])
450
+ else:
451
+ assert False, "did not recognize suffix " + szsuf
452
+ return DatasetDeep1B(nb=dbsize)
453
+
454
+ elif dataset == "music-100":
455
+ return DatasetMusic100()
456
+
457
+ elif dataset == "glove":
458
+ return DatasetGlove(download=download)
459
+
460
+ elif dataset.startswith("dino"):
461
+ dbsize = 10_000_000_000 if dataset == "dino10B" else int(dataset[4:])
462
+ return DatasetDINO10B(nb=dbsize)
463
+
464
+ else:
465
+ raise RuntimeError("unknown dataset " + dataset)
ScaleDF_rebuttal/python_dedup_pkgs/faiss/contrib/evaluation.py ADDED
@@ -0,0 +1,498 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ #
3
+ # This source code is licensed under the MIT license found in the
4
+ # LICENSE file in the root directory of this source tree.
5
+
6
+ import numpy as np
7
+ import unittest
8
+ import time
9
+ import faiss
10
+
11
+ from multiprocessing.pool import ThreadPool
12
+
13
+ ###############################################################
14
+ # Simple functions to evaluate knn results
15
+
16
+
17
+ def knn_intersection_measure(I1, I2):
18
+ """ computes the intersection measure of two result tables
19
+ """
20
+ nq, rank = I1.shape
21
+ assert I2.shape == (nq, rank)
22
+ ninter = sum(
23
+ np.intersect1d(I1[i], I2[i]).size
24
+ for i in range(nq)
25
+ )
26
+ return ninter / I1.size
27
+
28
+ ###############################################################
29
+ # Range search results can be compared with Precision-Recall
30
+
31
+
32
+ def filter_range_results(lims, D, I, thresh):
33
+ """ select a set of results """
34
+ nq = lims.size - 1
35
+ mask = D < thresh
36
+ new_lims = np.zeros_like(lims)
37
+ for i in range(nq):
38
+ new_lims[i + 1] = new_lims[i] + mask[lims[i] : lims[i + 1]].sum()
39
+ return new_lims, D[mask], I[mask]
40
+
41
+
42
+ def range_PR(lims_ref, Iref, lims_new, Inew, mode="overall"):
43
+ """compute the precision and recall of range search results. The
44
+ function does not take the distances into account. """
45
+
46
+ def ref_result_for(i):
47
+ return Iref[lims_ref[i]:lims_ref[i + 1]]
48
+
49
+ def new_result_for(i):
50
+ return Inew[lims_new[i]:lims_new[i + 1]]
51
+
52
+ nq = lims_ref.size - 1
53
+ assert lims_new.size - 1 == nq
54
+
55
+ ninter = np.zeros(nq, dtype="int64")
56
+
57
+ def compute_PR_for(q):
58
+
59
+ # ground truth results for this query
60
+ gt_ids = ref_result_for(q)
61
+
62
+ # results for this query
63
+ new_ids = new_result_for(q)
64
+
65
+ # there are no set functions in numpy so let's do this
66
+ inter = np.intersect1d(gt_ids, new_ids)
67
+
68
+ ninter[q] = len(inter)
69
+
70
+ # run in a thread pool, which helps in spite of the GIL
71
+ pool = ThreadPool(20)
72
+ pool.map(compute_PR_for, range(nq))
73
+
74
+ return counts_to_PR(
75
+ lims_ref[1:] - lims_ref[:-1],
76
+ lims_new[1:] - lims_new[:-1],
77
+ ninter,
78
+ mode=mode
79
+ )
80
+
81
+
82
+ def counts_to_PR(ngt, nres, ninter, mode="overall"):
83
+ """ computes a precision-recall for a set of queries.
84
+ ngt = nb of GT results per query
85
+ nres = nb of found results per query
86
+ ninter = nb of correct results per query (smaller than nres of course)
87
+ """
88
+
89
+ if mode == "overall":
90
+ ngt, nres, ninter = ngt.sum(), nres.sum(), ninter.sum()
91
+
92
+ if nres > 0:
93
+ precision = ninter / nres
94
+ else:
95
+ precision = 1.0
96
+
97
+ if ngt > 0:
98
+ recall = ninter / ngt
99
+ elif nres == 0:
100
+ recall = 1.0
101
+ else:
102
+ recall = 0.0
103
+
104
+ return precision, recall
105
+
106
+ elif mode == "average":
107
+ # average precision and recall over queries
108
+
109
+ mask = ngt == 0
110
+ ngt[mask] = 1
111
+
112
+ recalls = ninter / ngt
113
+ recalls[mask] = (nres[mask] == 0).astype(float)
114
+
115
+ # avoid division by 0
116
+ mask = nres == 0
117
+ assert np.all(ninter[mask] == 0)
118
+ ninter[mask] = 1
119
+ nres[mask] = 1
120
+
121
+ precisions = ninter / nres
122
+
123
+ return precisions.mean(), recalls.mean()
124
+
125
+ else:
126
+ raise AssertionError()
127
+
128
+
129
+ def sort_range_res_2(lims, D, I):
130
+ """ sort 2 arrays using the first as key """
131
+ I2 = np.empty_like(I)
132
+ D2 = np.empty_like(D)
133
+ nq = len(lims) - 1
134
+ for i in range(nq):
135
+ l0, l1 = lims[i], lims[i + 1]
136
+ ii = I[l0:l1]
137
+ di = D[l0:l1]
138
+ o = di.argsort()
139
+ I2[l0:l1] = ii[o]
140
+ D2[l0:l1] = di[o]
141
+ return I2, D2
142
+
143
+
144
+ def sort_range_res_1(lims, I):
145
+ I2 = np.empty_like(I)
146
+ nq = len(lims) - 1
147
+ for i in range(nq):
148
+ l0, l1 = lims[i], lims[i + 1]
149
+ I2[l0:l1] = I[l0:l1]
150
+ I2[l0:l1].sort()
151
+ return I2
152
+
153
+
154
+ def range_PR_multiple_thresholds(
155
+ lims_ref, Iref,
156
+ lims_new, Dnew, Inew,
157
+ thresholds,
158
+ mode="overall", do_sort="ref,new"
159
+ ):
160
+ """ compute precision-recall values for range search results
161
+ for several thresholds on the "new" results.
162
+ This is to plot PR curves
163
+ """
164
+ # ref should be sorted by ids
165
+ if "ref" in do_sort:
166
+ Iref = sort_range_res_1(lims_ref, Iref)
167
+
168
+ # new should be sorted by distances
169
+ if "new" in do_sort:
170
+ Inew, Dnew = sort_range_res_2(lims_new, Dnew, Inew)
171
+
172
+ def ref_result_for(i):
173
+ return Iref[lims_ref[i]:lims_ref[i + 1]]
174
+
175
+ def new_result_for(i):
176
+ l0, l1 = lims_new[i], lims_new[i + 1]
177
+ return Inew[l0:l1], Dnew[l0:l1]
178
+
179
+ nq = lims_ref.size - 1
180
+ assert lims_new.size - 1 == nq
181
+
182
+ nt = len(thresholds)
183
+ counts = np.zeros((nq, nt, 3), dtype="int64")
184
+
185
+ def compute_PR_for(q):
186
+ gt_ids = ref_result_for(q)
187
+ res_ids, res_dis = new_result_for(q)
188
+
189
+ counts[q, :, 0] = len(gt_ids)
190
+
191
+ if res_dis.size == 0:
192
+ # the rest remains at 0
193
+ return
194
+
195
+ # which offsets we are interested in
196
+ nres= np.searchsorted(res_dis, thresholds)
197
+ counts[q, :, 1] = nres
198
+
199
+ if gt_ids.size == 0:
200
+ return
201
+
202
+ # find number of TPs at each stage in the result list
203
+ ii = np.searchsorted(gt_ids, res_ids)
204
+ ii[ii == len(gt_ids)] = -1
205
+ n_ok = np.cumsum(gt_ids[ii] == res_ids)
206
+
207
+ # focus on threshold points
208
+ n_ok = np.hstack(([0], n_ok))
209
+ counts[q, :, 2] = n_ok[nres]
210
+
211
+ pool = ThreadPool(20)
212
+ pool.map(compute_PR_for, range(nq))
213
+ # print(counts.transpose(2, 1, 0))
214
+
215
+ precisions = np.zeros(nt)
216
+ recalls = np.zeros(nt)
217
+ for t in range(nt):
218
+ p, r = counts_to_PR(
219
+ counts[:, t, 0], counts[:, t, 1], counts[:, t, 2],
220
+ mode=mode
221
+ )
222
+ precisions[t] = p
223
+ recalls[t] = r
224
+
225
+ return precisions, recalls
226
+
227
+
228
+ ###############################################################
229
+ # Functions that compare search results with a reference result.
230
+ # They are intended for use in tests
231
+
232
+ def _cluster_tables_with_tolerance(tab1, tab2, thr):
233
+ """ for two tables, cluster them by merging values closer than thr.
234
+ Returns the cluster ids for each table element """
235
+ tab = np.hstack([tab1, tab2])
236
+ tab.sort()
237
+ n = len(tab)
238
+ diffs = np.ones(n)
239
+ diffs[1:] = tab[1:] - tab[:-1]
240
+ unique_vals = tab[diffs > thr]
241
+ idx1 = np.searchsorted(unique_vals, tab1, side='right') - 1
242
+ idx2 = np.searchsorted(unique_vals, tab2, side='right') - 1
243
+ return idx1, idx2
244
+
245
+
246
+ def check_ref_knn_with_draws(Dref, Iref, Dnew, Inew, rtol=1e-5):
247
+ """ test that knn search results are identical, with possible ties.
248
+ Raise if not. """
249
+ np.testing.assert_allclose(Dref, Dnew, rtol=rtol)
250
+ # here we have to be careful because of draws
251
+ testcase = unittest.TestCase() # because it makes nice error messages
252
+ for i in range(len(Iref)):
253
+ if np.all(Iref[i] == Inew[i]): # easy case
254
+ continue
255
+
256
+ # otherwise collect elements per distance
257
+ r = rtol * Dref[i].max()
258
+
259
+ DrefC, DnewC = _cluster_tables_with_tolerance(Dref[i], Dnew[i], r)
260
+
261
+ for dis in np.unique(DrefC):
262
+ if dis == DrefC[-1]:
263
+ continue
264
+ mask = DrefC == dis
265
+ testcase.assertEqual(set(Iref[i, mask]), set(Inew[i, mask]))
266
+
267
+
268
+ def check_ref_range_results(Lref, Dref, Iref,
269
+ Lnew, Dnew, Inew):
270
+ """ compare range search results wrt. a reference result,
271
+ throw if it fails """
272
+ np.testing.assert_array_equal(Lref, Lnew)
273
+ nq = len(Lref) - 1
274
+ for i in range(nq):
275
+ l0, l1 = Lref[i], Lref[i + 1]
276
+ Ii_ref = Iref[l0:l1]
277
+ Ii_new = Inew[l0:l1]
278
+ Di_ref = Dref[l0:l1]
279
+ Di_new = Dnew[l0:l1]
280
+ if np.all(Ii_ref == Ii_new): # easy
281
+ pass
282
+ else:
283
+ def sort_by_ids(I, D):
284
+ o = I.argsort()
285
+ return I[o], D[o]
286
+ # sort both
287
+ (Ii_ref, Di_ref) = sort_by_ids(Ii_ref, Di_ref)
288
+ (Ii_new, Di_new) = sort_by_ids(Ii_new, Di_new)
289
+ np.testing.assert_array_equal(Ii_ref, Ii_new)
290
+ np.testing.assert_array_almost_equal(Di_ref, Di_new, decimal=5)
291
+
292
+
293
+ ###############################################################
294
+ # OperatingPoints functions
295
+ # this is the Python version of the AutoTune object in C++
296
+
297
+
298
+ class OperatingPoints:
299
+ """
300
+ Manages a set of search parameters with associated performance and time.
301
+ Keeps the Pareto optimal points.
302
+ """
303
+
304
+ def __init__(self):
305
+ # list of (key, perf, t)
306
+ self.operating_points = [
307
+ # (self.do_nothing_key(), 0.0, 0.0)
308
+ ]
309
+ self.suboptimal_points = []
310
+
311
+ def compare_keys(self, k1, k2):
312
+ """ return -1 if k1 > k2, 1 if k2 > k1, 0 otherwise """
313
+ raise NotImplemented
314
+
315
+ def do_nothing_key(self):
316
+ """ parameters to say we do nothing, takes 0 time and has 0 performance"""
317
+ raise NotImplemented
318
+
319
+ def is_pareto_optimal(self, perf_new, t_new):
320
+ for _, perf, t in self.operating_points:
321
+ if perf >= perf_new and t <= t_new:
322
+ return False
323
+ return True
324
+
325
+ def predict_bounds(self, key):
326
+ """ predicts the bound on time and performance """
327
+ min_time = 0.0
328
+ max_perf = 1.0
329
+ for key2, perf, t in self.operating_points + self.suboptimal_points:
330
+ cmp = self.compare_keys(key, key2)
331
+ if cmp > 0: # key2 > key
332
+ if t > min_time:
333
+ min_time = t
334
+ if cmp < 0: # key2 < key
335
+ if perf < max_perf:
336
+ max_perf = perf
337
+ return max_perf, min_time
338
+
339
+ def should_run_experiment(self, key):
340
+ (max_perf, min_time) = self.predict_bounds(key)
341
+ return self.is_pareto_optimal(max_perf, min_time)
342
+
343
+ def add_operating_point(self, key, perf, t):
344
+ if self.is_pareto_optimal(perf, t):
345
+ i = 0
346
+ # maybe it shadows some other operating point completely?
347
+ while i < len(self.operating_points):
348
+ op_Ls, perf2, t2 = self.operating_points[i]
349
+ if perf >= perf2 and t < t2:
350
+ self.suboptimal_points.append(
351
+ self.operating_points.pop(i))
352
+ else:
353
+ i += 1
354
+ self.operating_points.append((key, perf, t))
355
+ return True
356
+ else:
357
+ self.suboptimal_points.append((key, perf, t))
358
+ return False
359
+
360
+
361
+ class OperatingPointsWithRanges(OperatingPoints):
362
+ """
363
+ Set of parameters that are each picked from a discrete range of values.
364
+ An increase of each parameter is assumed to make the operation slower
365
+ and more accurate.
366
+ A key = int array of indices in the ordered set of parameters.
367
+ """
368
+
369
+ def __init__(self):
370
+ OperatingPoints.__init__(self)
371
+ # list of (name, values)
372
+ self.ranges = []
373
+
374
+ def add_range(self, name, values):
375
+ self.ranges.append((name, values))
376
+
377
+ def compare_keys(self, k1, k2):
378
+ if np.all(k1 >= k2):
379
+ return 1
380
+ if np.all(k2 >= k1):
381
+ return -1
382
+ return 0
383
+
384
+ def do_nothing_key(self):
385
+ return np.zeros(len(self.ranges), dtype=int)
386
+
387
+ def num_experiments(self):
388
+ return int(np.prod([len(values) for name, values in self.ranges]))
389
+
390
+ def sample_experiments(self, n_autotune, rs=np.random):
391
+ """ sample a set of experiments of max size n_autotune
392
+ (run all experiments in random order if n_autotune is 0)
393
+ """
394
+ assert n_autotune == 0 or n_autotune >= 2
395
+ totex = self.num_experiments()
396
+ rs = np.random.RandomState(123)
397
+ if n_autotune == 0 or totex < n_autotune:
398
+ experiments = rs.permutation(totex - 2)
399
+ else:
400
+ experiments = rs.choice(
401
+ totex - 2, size=n_autotune - 2, replace=False)
402
+
403
+ experiments = [0, totex - 1] + [int(cno) + 1 for cno in experiments]
404
+ return experiments
405
+
406
+ def cno_to_key(self, cno):
407
+ """Convert a sequential experiment number to a key"""
408
+ k = np.zeros(len(self.ranges), dtype=int)
409
+ for i, (name, values) in enumerate(self.ranges):
410
+ k[i] = cno % len(values)
411
+ cno //= len(values)
412
+ assert cno == 0
413
+ return k
414
+
415
+ def get_parameters(self, k):
416
+ """Convert a key to a dictionary with parameter values"""
417
+ return {
418
+ name: values[k[i]]
419
+ for i, (name, values) in enumerate(self.ranges)
420
+ }
421
+
422
+ def restrict_range(self, name, max_val):
423
+ """ remove too large values from a range"""
424
+ for name2, values in self.ranges:
425
+ if name == name2:
426
+ val2 = [v for v in values if v < max_val]
427
+ values[:] = val2
428
+ return
429
+ raise RuntimeError(f"parameter {name} not found")
430
+
431
+
432
+ ###############################################################
433
+ # Timer object
434
+
435
+
436
+ class TimerIter:
437
+ def __init__(self, timer):
438
+ self.ts = []
439
+ self.runs = timer.runs
440
+ self.timer = timer
441
+ if timer.nt >= 0:
442
+ faiss.omp_set_num_threads(timer.nt)
443
+
444
+ def __next__(self):
445
+ timer = self.timer
446
+ self.runs -= 1
447
+ self.ts.append(time.time())
448
+ total_time = self.ts[-1] - self.ts[0] if len(self.ts) >= 2 else 0
449
+ if self.runs == -1 or total_time > timer.max_secs:
450
+ if timer.nt >= 0:
451
+ faiss.omp_set_num_threads(timer.remember_nt)
452
+ ts = np.array(self.ts)
453
+ times = ts[1:] - ts[:-1]
454
+ if len(times) == timer.runs:
455
+ timer.times = times[timer.warmup :]
456
+ else:
457
+ # if timeout, we use all the runs
458
+ timer.times = times[:]
459
+ raise StopIteration
460
+
461
+
462
+ class RepeatTimer:
463
+ """
464
+ This is yet another timer object. It is adapted to Faiss by
465
+ taking a number of openmp threads to set on input. It should be called
466
+ in an explicit loop as:
467
+
468
+ timer = RepeatTimer(warmup=1, nt=1, runs=6)
469
+
470
+ for _ in timer:
471
+ # perform operation
472
+
473
+ print(f"time={timer.get_ms():.1f} ± {timer.get_ms_std():.1f} ms")
474
+
475
+ the same timer can be re-used. In that case it is reset each time it
476
+ enters a loop. It focuses on ms-scale times because for second scale
477
+ it's usually less relevant to repeat the operation.
478
+ """
479
+ def __init__(self, warmup=0, nt=-1, runs=1, max_secs=np.inf):
480
+ assert warmup < runs
481
+ self.warmup = warmup
482
+ self.nt = nt
483
+ self.runs = runs
484
+ self.max_secs = max_secs
485
+ self.remember_nt = faiss.omp_get_max_threads()
486
+
487
+ def __iter__(self):
488
+ return TimerIter(self)
489
+
490
+ def ms(self):
491
+ return np.mean(self.times) * 1000
492
+
493
+ def ms_std(self):
494
+ return np.std(self.times) * 1000 if len(self.times) > 1 else 0.0
495
+
496
+ def nruns(self):
497
+ """ effective number of runs (may be lower than runs - warmup due to timeout)"""
498
+ return len(self.times)
ScaleDF_rebuttal/python_dedup_pkgs/faiss/contrib/exhaustive_search.py ADDED
@@ -0,0 +1,368 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ #
3
+ # This source code is licensed under the MIT license found in the
4
+ # LICENSE file in the root directory of this source tree.
5
+
6
+ import faiss
7
+ import time
8
+ import numpy as np
9
+
10
+ import logging
11
+
12
+ LOG = logging.getLogger(__name__)
13
+
14
+
15
+ def knn_ground_truth(xq, db_iterator, k, metric_type=faiss.METRIC_L2, shard=False, ngpu=-1):
16
+ """Computes the exact KNN search results for a dataset that possibly
17
+ does not fit in RAM but for which we have an iterator that
18
+ returns it block by block.
19
+ """
20
+ LOG.info("knn_ground_truth queries size %s k=%d" % (xq.shape, k))
21
+ t0 = time.time()
22
+ nq, d = xq.shape
23
+ keep_max = faiss.is_similarity_metric(metric_type)
24
+ rh = faiss.ResultHeap(nq, k, keep_max=keep_max)
25
+
26
+ index = faiss.IndexFlat(d, metric_type)
27
+ if ngpu == -1:
28
+ ngpu = faiss.get_num_gpus()
29
+
30
+ if ngpu:
31
+ LOG.info('running on %d GPUs' % ngpu)
32
+ co = faiss.GpuMultipleClonerOptions()
33
+ co.shard = shard
34
+ index = faiss.index_cpu_to_all_gpus(index, co=co, ngpu=ngpu)
35
+
36
+ # compute ground-truth by blocks, and add to heaps
37
+ i0 = 0
38
+ for xbi in db_iterator:
39
+ ni = xbi.shape[0]
40
+ index.add(xbi)
41
+ D, I = index.search(xq, k)
42
+ I += i0
43
+ rh.add_result(D, I)
44
+ index.reset()
45
+ i0 += ni
46
+ LOG.info("%d db elements, %.3f s" % (i0, time.time() - t0))
47
+
48
+ rh.finalize()
49
+ LOG.info("GT time: %.3f s (%d vectors)" % (time.time() - t0, i0))
50
+
51
+ return rh.D, rh.I
52
+
53
+ # knn function used to be here
54
+ knn = faiss.knn
55
+
56
+
57
+
58
+
59
+ def range_search_gpu(xq, r2, index_gpu, index_cpu, gpu_k=1024):
60
+ """GPU does not support range search, so we emulate it with
61
+ knn search + fallback to CPU index.
62
+
63
+ The index_cpu can either be:
64
+ - a CPU index that supports range search
65
+ - a numpy table, that will be used to construct a Flat index if needed.
66
+ - None. In that case, at most gpu_k results will be returned
67
+ """
68
+ nq, d = xq.shape
69
+ is_binary_index = isinstance(index_gpu, faiss.IndexBinary)
70
+ keep_max = faiss.is_similarity_metric(index_gpu.metric_type)
71
+ r2 = int(r2) if is_binary_index else float(r2)
72
+ k = min(index_gpu.ntotal, gpu_k)
73
+ LOG.debug(
74
+ f"GPU search {nq} queries with {k=:} {is_binary_index=:} {keep_max=:}")
75
+ t0 = time.time()
76
+ D, I = index_gpu.search(xq, k)
77
+ t1 = time.time() - t0
78
+ if is_binary_index:
79
+ assert d * 8 < 32768 # let's compact the distance matrix
80
+ D = D.astype('int16')
81
+ t2 = 0
82
+ lim_remain = None
83
+ if index_cpu is not None:
84
+ if not keep_max:
85
+ mask = D[:, k - 1] < r2
86
+ else:
87
+ mask = D[:, k - 1] > r2
88
+ if mask.sum() > 0:
89
+ LOG.debug("CPU search remain %d" % mask.sum())
90
+ t0 = time.time()
91
+ if isinstance(index_cpu, np.ndarray):
92
+ # then it in fact an array that we have to make flat
93
+ xb = index_cpu
94
+ if is_binary_index:
95
+ index_cpu = faiss.IndexBinaryFlat(d * 8)
96
+ else:
97
+ index_cpu = faiss.IndexFlat(d, index_gpu.metric_type)
98
+ index_cpu.add(xb)
99
+ lim_remain, D_remain, I_remain = index_cpu.range_search(xq[mask], r2)
100
+ if is_binary_index:
101
+ D_remain = D_remain.astype('int16')
102
+ t2 = time.time() - t0
103
+ LOG.debug("combine")
104
+ t0 = time.time()
105
+
106
+ CombinerRangeKNN = (
107
+ faiss.CombinerRangeKNNint16 if is_binary_index else
108
+ faiss.CombinerRangeKNNfloat
109
+ )
110
+
111
+ combiner = CombinerRangeKNN(nq, k, r2, keep_max)
112
+ if True:
113
+ sp = faiss.swig_ptr
114
+ combiner.I = sp(I)
115
+ combiner.D = sp(D)
116
+ # combiner.set_knn_result(sp(I), sp(D))
117
+ if lim_remain is not None:
118
+ combiner.mask = sp(mask)
119
+ combiner.D_remain = sp(D_remain)
120
+ combiner.lim_remain = sp(lim_remain.view("int64"))
121
+ combiner.I_remain = sp(I_remain)
122
+ # combiner.set_range_result(sp(mask), sp(lim_remain.view("int64")), sp(D_remain), sp(I_remain))
123
+ L_res = np.empty(nq + 1, dtype='int64')
124
+ combiner.compute_sizes(sp(L_res))
125
+ nres = L_res[-1]
126
+ D_res = np.empty(nres, dtype=D.dtype)
127
+ I_res = np.empty(nres, dtype='int64')
128
+ combiner.write_result(sp(D_res), sp(I_res))
129
+ else:
130
+ D_res, I_res = [], []
131
+ nr = 0
132
+ for i in range(nq):
133
+ if not mask[i]:
134
+ if index_gpu.metric_type == faiss.METRIC_L2:
135
+ nv = (D[i, :] < r2).sum()
136
+ else:
137
+ nv = (D[i, :] > r2).sum()
138
+ D_res.append(D[i, :nv])
139
+ I_res.append(I[i, :nv])
140
+ else:
141
+ l0, l1 = lim_remain[nr], lim_remain[nr + 1]
142
+ D_res.append(D_remain[l0:l1])
143
+ I_res.append(I_remain[l0:l1])
144
+ nr += 1
145
+ L_res = np.cumsum([0] + [len(di) for di in D_res])
146
+ D_res = np.hstack(D_res)
147
+ I_res = np.hstack(I_res)
148
+ t3 = time.time() - t0
149
+ LOG.debug(f"times {t1:.3f}s {t2:.3f}s {t3:.3f}s")
150
+ return L_res, D_res, I_res
151
+
152
+
153
+ def range_ground_truth(xq, db_iterator, threshold, metric_type=faiss.METRIC_L2,
154
+ shard=False, ngpu=-1):
155
+ """Computes the range-search search results for a dataset that possibly
156
+ does not fit in RAM but for which we have an iterator that
157
+ returns it block by block.
158
+ """
159
+ nq, d = xq.shape
160
+ t0 = time.time()
161
+ xq = np.ascontiguousarray(xq, dtype='float32')
162
+
163
+ index = faiss.IndexFlat(d, metric_type)
164
+ if ngpu == -1:
165
+ ngpu = faiss.get_num_gpus()
166
+ if ngpu:
167
+ LOG.info('running on %d GPUs' % ngpu)
168
+ co = faiss.GpuMultipleClonerOptions()
169
+ co.shard = shard
170
+ index_gpu = faiss.index_cpu_to_all_gpus(index, co=co, ngpu=ngpu)
171
+
172
+ # compute ground-truth by blocks
173
+ i0 = 0
174
+ D = [[] for _i in range(nq)]
175
+ I = [[] for _i in range(nq)]
176
+ for xbi in db_iterator:
177
+ ni = xbi.shape[0]
178
+ if ngpu > 0:
179
+ index_gpu.add(xbi)
180
+ lims_i, Di, Ii = range_search_gpu(xq, threshold, index_gpu, xbi)
181
+ index_gpu.reset()
182
+ else:
183
+ index.add(xbi)
184
+ lims_i, Di, Ii = index.range_search(xq, threshold)
185
+ index.reset()
186
+ Ii += i0
187
+ for j in range(nq):
188
+ l0, l1 = lims_i[j], lims_i[j + 1]
189
+ if l1 > l0:
190
+ D[j].append(Di[l0:l1])
191
+ I[j].append(Ii[l0:l1])
192
+ i0 += ni
193
+ LOG.info("%d db elements, %.3f s" % (i0, time.time() - t0))
194
+
195
+ empty_I = np.zeros(0, dtype='int64')
196
+ empty_D = np.zeros(0, dtype='float32')
197
+ # import pdb; pdb.set_trace()
198
+ D = [(np.hstack(i) if i != [] else empty_D) for i in D]
199
+ I = [(np.hstack(i) if i != [] else empty_I) for i in I]
200
+ sizes = [len(i) for i in I]
201
+ assert len(sizes) == nq
202
+ lims = np.zeros(nq + 1, dtype="uint64")
203
+ lims[1:] = np.cumsum(sizes)
204
+ return lims, np.hstack(D), np.hstack(I)
205
+
206
+
207
+ def threshold_radius_nres(nres, dis, ids, thresh, keep_max=False):
208
+ """ select a set of results """
209
+ if keep_max:
210
+ mask = dis > thresh
211
+ else:
212
+ mask = dis < thresh
213
+ new_nres = np.zeros_like(nres)
214
+ o = 0
215
+ for i, nr in enumerate(nres):
216
+ nr = int(nr) # avoid issues with int64 + uint64
217
+ new_nres[i] = mask[o:o + nr].sum()
218
+ o += nr
219
+ return new_nres, dis[mask], ids[mask]
220
+
221
+
222
+ def threshold_radius(lims, dis, ids, thresh, keep_max=False):
223
+ """ restrict range-search results to those below a given radius """
224
+ if keep_max:
225
+ mask = dis > thresh
226
+ else:
227
+ mask = dis < thresh
228
+ new_lims = np.zeros_like(lims)
229
+ n = len(lims) - 1
230
+ for i in range(n):
231
+ l0, l1 = lims[i], lims[i + 1]
232
+ new_lims[i + 1] = new_lims[i] + mask[l0:l1].sum()
233
+ return new_lims, dis[mask], ids[mask]
234
+
235
+
236
+ def apply_maxres(res_batches, target_nres, keep_max=False):
237
+ """find radius that reduces number of results to target_nres, and
238
+ applies it in-place to the result batches used in
239
+ range_search_max_results"""
240
+ alldis = np.hstack([dis for _, dis, _ in res_batches])
241
+ assert len(alldis) > target_nres
242
+ if keep_max:
243
+ alldis.partition(len(alldis) - target_nres - 1)
244
+ radius = alldis[-1 - target_nres]
245
+ else:
246
+ alldis.partition(target_nres)
247
+ radius = alldis[target_nres]
248
+
249
+ if alldis.dtype == 'float32':
250
+ radius = float(radius)
251
+ else:
252
+ radius = int(radius)
253
+ LOG.debug(' setting radius to %s' % radius)
254
+ totres = 0
255
+ for i, (nres, dis, ids) in enumerate(res_batches):
256
+ nres, dis, ids = threshold_radius_nres(
257
+ nres, dis, ids, radius, keep_max=keep_max)
258
+ totres += len(dis)
259
+ res_batches[i] = nres, dis, ids
260
+ LOG.debug(' updated previous results, new nb results %d' % totres)
261
+ return radius, totres
262
+
263
+
264
+ def range_search_max_results(index, query_iterator, radius,
265
+ max_results=None, min_results=None,
266
+ shard=False, ngpu=0, clip_to_min=False):
267
+ """Performs a range search with many queries (given by an iterator)
268
+ and adjusts the threshold on-the-fly so that the total results
269
+ table does not grow larger than max_results.
270
+
271
+ If ngpu != 0, the function moves the index to this many GPUs to
272
+ speed up search.
273
+ """
274
+ # TODO: all result manipulations are in python, should move to C++ if perf
275
+ # critical
276
+ is_binary_index = isinstance(index, faiss.IndexBinary)
277
+
278
+ if min_results is None:
279
+ assert max_results is not None
280
+ min_results = int(0.8 * max_results)
281
+
282
+ if max_results is None:
283
+ assert min_results is not None
284
+ max_results = int(min_results * 1.5)
285
+
286
+ if ngpu == -1:
287
+ ngpu = faiss.get_num_gpus()
288
+
289
+ if ngpu:
290
+ LOG.info('running on %d GPUs' % ngpu)
291
+ co = faiss.GpuMultipleClonerOptions()
292
+ co.shard = shard
293
+ index_gpu = faiss.index_cpu_to_all_gpus(index, co=co, ngpu=ngpu)
294
+ else:
295
+ index_gpu = None
296
+
297
+ t_start = time.time()
298
+ t_search = t_post_process = 0
299
+ qtot = totres = raw_totres = 0
300
+ res_batches = []
301
+
302
+ for xqi in query_iterator:
303
+ t0 = time.time()
304
+ LOG.debug(f"searching {len(xqi)} vectors")
305
+ if index_gpu:
306
+ lims_i, Di, Ii = range_search_gpu(xqi, radius, index_gpu, index)
307
+ else:
308
+ lims_i, Di, Ii = index.range_search(xqi, radius)
309
+
310
+ nres_i = lims_i[1:] - lims_i[:-1]
311
+ raw_totres += len(Di)
312
+ qtot += len(xqi)
313
+
314
+ t1 = time.time()
315
+ if is_binary_index:
316
+ # weird Faiss quirk that returns floats for Hamming distances
317
+ Di = Di.astype('int16')
318
+
319
+ totres += len(Di)
320
+ res_batches.append((nres_i, Di, Ii))
321
+
322
+ if max_results is not None and totres > max_results:
323
+ LOG.info('too many results %d > %d, scaling back radius' %
324
+ (totres, max_results))
325
+ radius, totres = apply_maxres(
326
+ res_batches, min_results,
327
+ keep_max=index.metric_type == faiss.METRIC_INNER_PRODUCT
328
+ )
329
+ t2 = time.time()
330
+ t_search += t1 - t0
331
+ t_post_process += t2 - t1
332
+ LOG.debug(' [%.3f s] %d queries done, %d results' % (
333
+ time.time() - t_start, qtot, totres))
334
+
335
+ LOG.info(
336
+ 'search done in %.3f s + %.3f s, total %d results, end threshold %g' % (
337
+ t_search, t_post_process, totres, radius)
338
+ )
339
+
340
+ if clip_to_min and totres > min_results:
341
+ radius, totres = apply_maxres(
342
+ res_batches, min_results,
343
+ keep_max=index.metric_type == faiss.METRIC_INNER_PRODUCT
344
+ )
345
+
346
+ nres = np.hstack([nres_i for nres_i, dis_i, ids_i in res_batches])
347
+ dis = np.hstack([dis_i for nres_i, dis_i, ids_i in res_batches])
348
+ ids = np.hstack([ids_i for nres_i, dis_i, ids_i in res_batches])
349
+
350
+ lims = np.zeros(len(nres) + 1, dtype='uint64')
351
+ lims[1:] = np.cumsum(nres)
352
+
353
+ return radius, lims, dis, ids
354
+
355
+
356
+ def exponential_query_iterator(xq, start_bs=32, max_bs=20000):
357
+ """ produces batches of progressively increasing sizes. This is useful to
358
+ adjust the search radius progressively without overflowing with
359
+ intermediate results """
360
+ nq = len(xq)
361
+ bs = start_bs
362
+ i = 0
363
+ while i < nq:
364
+ xqi = xq[i:i + bs]
365
+ yield xqi
366
+ if bs < max_bs:
367
+ bs *= 2
368
+ i += len(xqi)
ScaleDF_rebuttal/python_dedup_pkgs/faiss/contrib/factory_tools.py ADDED
@@ -0,0 +1,156 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ #
3
+ # This source code is licensed under the MIT license found in the
4
+ # LICENSE file in the root directory of this source tree.
5
+
6
+ import faiss
7
+ import re
8
+
9
+
10
+ def get_code_size(d, indexkey):
11
+ """ size of one vector in an index in dimension d
12
+ constructed with factory string indexkey"""
13
+
14
+ if indexkey == "Flat":
15
+ return d * 4
16
+
17
+ if indexkey.endswith(",RFlat"):
18
+ return d * 4 + get_code_size(d, indexkey[:-len(",RFlat")])
19
+
20
+ mo = re.match("IVF\\d+(_HNSW32)?,(.*)$", indexkey)
21
+ if mo:
22
+ return get_code_size(d, mo.group(2))
23
+
24
+ mo = re.match("IVF\\d+\\(.*\\)?,(.*)$", indexkey)
25
+ if mo:
26
+ return get_code_size(d, mo.group(1))
27
+
28
+ mo = re.match("IMI\\d+x2,(.*)$", indexkey)
29
+ if mo:
30
+ return get_code_size(d, mo.group(1))
31
+
32
+ mo = re.match("(.*),Refine\\((.*)\\)$", indexkey)
33
+ if mo:
34
+ return get_code_size(d, mo.group(1)) + get_code_size(d, mo.group(2))
35
+
36
+ mo = re.match('PQ(\\d+)x(\\d+)(fs|fsr)?$', indexkey)
37
+ if mo:
38
+ return (int(mo.group(1)) * int(mo.group(2)) + 7) // 8
39
+
40
+ mo = re.match('PQ(\\d+)\\+(\\d+)$', indexkey)
41
+ if mo:
42
+ return (int(mo.group(1)) + int(mo.group(2)))
43
+
44
+ mo = re.match('PQ(\\d+)$', indexkey)
45
+ if mo:
46
+ return int(mo.group(1))
47
+
48
+ if indexkey == "HNSW32" or indexkey == "HNSW32,Flat":
49
+ return d * 4 + 64 * 4 # roughly
50
+
51
+ if indexkey == 'SQ8':
52
+ return d
53
+ elif indexkey == 'SQ4':
54
+ return (d + 1) // 2
55
+ elif indexkey == 'SQ6':
56
+ return (d * 6 + 7) // 8
57
+ elif indexkey == 'SQfp16':
58
+ return d * 2
59
+ elif indexkey == 'SQbf16':
60
+ return d * 2
61
+
62
+ mo = re.match('PCAR?(\\d+),(.*)$', indexkey)
63
+ if mo:
64
+ return get_code_size(int(mo.group(1)), mo.group(2))
65
+ mo = re.match('OPQ\\d+_(\\d+),(.*)$', indexkey)
66
+ if mo:
67
+ return get_code_size(int(mo.group(1)), mo.group(2))
68
+ mo = re.match('OPQ\\d+,(.*)$', indexkey)
69
+ if mo:
70
+ return get_code_size(d, mo.group(1))
71
+ mo = re.match('RR(\\d+),(.*)$', indexkey)
72
+ if mo:
73
+ return get_code_size(int(mo.group(1)), mo.group(2))
74
+ raise RuntimeError("cannot parse " + indexkey)
75
+
76
+
77
+ def get_hnsw_M(index):
78
+ return index.hnsw.cum_nneighbor_per_level.at(1) // 2
79
+
80
+
81
+ def reverse_index_factory(index):
82
+ """
83
+ attempts to get the factory string the index was built with
84
+ """
85
+ index = faiss.downcast_index(index)
86
+ if isinstance(index, faiss.IndexFlat):
87
+ return "Flat"
88
+ elif isinstance(index, faiss.IndexIVF):
89
+ quantizer = faiss.downcast_index(index.quantizer)
90
+
91
+ if isinstance(quantizer, faiss.IndexFlat):
92
+ prefix = f"IVF{index.nlist}"
93
+ elif isinstance(quantizer, faiss.MultiIndexQuantizer):
94
+ prefix = f"IMI{quantizer.pq.M}x{quantizer.pq.nbits}"
95
+ elif isinstance(quantizer, faiss.IndexHNSW):
96
+ prefix = f"IVF{index.nlist}_HNSW{get_hnsw_M(quantizer)}"
97
+ else:
98
+ prefix = f"IVF{index.nlist}({reverse_index_factory(quantizer)})"
99
+
100
+ if isinstance(index, faiss.IndexIVFFlat):
101
+ return prefix + ",Flat"
102
+ if isinstance(index, faiss.IndexIVFScalarQuantizer):
103
+ return prefix + ",SQ8"
104
+ if isinstance(index, faiss.IndexIVFPQ):
105
+ return prefix + f",PQ{index.pq.M}x{index.pq.nbits}"
106
+ if isinstance(index, faiss.IndexIVFPQFastScan):
107
+ return prefix + f",PQ{index.pq.M}x{index.pq.nbits}fs"
108
+
109
+ elif isinstance(index, faiss.IndexPreTransform):
110
+ if index.chain.size() != 1:
111
+ raise NotImplementedError()
112
+ vt = faiss.downcast_VectorTransform(index.chain.at(0))
113
+ if isinstance(vt, faiss.OPQMatrix):
114
+ prefix = f"OPQ{vt.M}_{vt.d_out}"
115
+ elif isinstance(vt, faiss.ITQTransform):
116
+ prefix = f"ITQ{vt.itq.d_out}"
117
+ elif isinstance(vt, faiss.PCAMatrix):
118
+ assert vt.eigen_power == 0
119
+ prefix = "PCA" + ("R" if vt.random_rotation else "") + str(vt.d_out)
120
+ else:
121
+ raise NotImplementedError()
122
+ return f"{prefix},{reverse_index_factory(index.index)}"
123
+
124
+ elif isinstance(index, faiss.IndexHNSW):
125
+ return f"HNSW{get_hnsw_M(index)}"
126
+
127
+ elif isinstance(index, faiss.IndexRefine):
128
+ return f"{reverse_index_factory(index.base_index)},Refine({reverse_index_factory(index.refine_index)})"
129
+
130
+ elif isinstance(index, faiss.IndexPQFastScan):
131
+ return f"PQ{index.pq.M}x{index.pq.nbits}fs"
132
+
133
+ elif isinstance(index, faiss.IndexPQ):
134
+ return f"PQ{index.pq.M}x{index.pq.nbits}"
135
+
136
+ elif isinstance(index, faiss.IndexLSH):
137
+ return "LSH" + ("r" if index.rotate_data else "") + ("t" if index.train_thresholds else "")
138
+
139
+ elif isinstance(index, faiss.IndexScalarQuantizer):
140
+ sqtypes = {
141
+ faiss.ScalarQuantizer.QT_8bit: "8",
142
+ faiss.ScalarQuantizer.QT_4bit: "4",
143
+ faiss.ScalarQuantizer.QT_6bit: "6",
144
+ faiss.ScalarQuantizer.QT_fp16: "fp16",
145
+ faiss.ScalarQuantizer.QT_bf16: "bf16",
146
+ }
147
+ return f"SQ{sqtypes[index.sq.qtype]}"
148
+
149
+ # IndexIDMap2 is a subclass of IndexIDMap, so it must be checked first.
150
+ elif isinstance(index, faiss.IndexIDMap2):
151
+ return f"IDMap2,{reverse_index_factory(index.index)}"
152
+
153
+ elif isinstance(index, faiss.IndexIDMap):
154
+ return f"IDMap,{reverse_index_factory(index.index)}"
155
+
156
+ raise NotImplementedError()
ScaleDF_rebuttal/python_dedup_pkgs/faiss/contrib/inspect_tools.py ADDED
@@ -0,0 +1,117 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ #
3
+ # This source code is licensed under the MIT license found in the
4
+ # LICENSE file in the root directory of this source tree.
5
+
6
+ import numpy as np
7
+ import faiss
8
+
9
+
10
+ def get_invlist(invlists, l):
11
+ """ returns the inverted lists content as a pair of (list_ids, list_codes).
12
+ The codes are reshaped to a proper size
13
+ """
14
+ invlists = faiss.downcast_InvertedLists(invlists)
15
+ ls = invlists.list_size(l)
16
+ list_ids = np.zeros(ls, dtype='int64')
17
+ ids = codes = None
18
+ try:
19
+ ids = invlists.get_ids(l)
20
+ if ls > 0:
21
+ faiss.memcpy(faiss.swig_ptr(list_ids), ids, list_ids.nbytes)
22
+ codes = invlists.get_codes(l)
23
+ if invlists.code_size != faiss.InvertedLists.INVALID_CODE_SIZE:
24
+ list_codes = np.zeros((ls, invlists.code_size), dtype='uint8')
25
+ else:
26
+ # it's a BlockInvertedLists
27
+ npb = invlists.n_per_block
28
+ bs = invlists.block_size
29
+ ls_round = (ls + npb - 1) // npb
30
+ list_codes = np.zeros((ls_round, bs // npb, npb), dtype='uint8')
31
+ if ls > 0:
32
+ faiss.memcpy(faiss.swig_ptr(list_codes), codes, list_codes.nbytes)
33
+ finally:
34
+ if ids is not None:
35
+ invlists.release_ids(l, ids)
36
+ if codes is not None:
37
+ invlists.release_codes(l, codes)
38
+ return list_ids, list_codes
39
+
40
+
41
+ def get_invlist_sizes(invlists):
42
+ """ return the array of sizes of the inverted lists """
43
+ return np.array([
44
+ invlists.list_size(i)
45
+ for i in range(invlists.nlist)
46
+ ], dtype='int64')
47
+
48
+
49
+ def print_object_fields(obj):
50
+ """ list values all fields of an object known to SWIG """
51
+
52
+ for name in obj.__class__.__swig_getmethods__:
53
+ print(f"{name} = {getattr(obj, name)}")
54
+
55
+
56
+ def get_pq_centroids(pq):
57
+ """ return the PQ centroids as an array """
58
+ cen = faiss.vector_to_array(pq.centroids)
59
+ return cen.reshape(pq.M, pq.ksub, pq.dsub)
60
+
61
+
62
+ def get_LinearTransform_matrix(pca):
63
+ """ extract matrix + bias from the PCA object
64
+ works for any linear transform (OPQ, random rotation, etc.)
65
+ """
66
+ b = faiss.vector_to_array(pca.b)
67
+ A = faiss.vector_to_array(pca.A).reshape(pca.d_out, pca.d_in)
68
+ return A, b
69
+
70
+
71
+ def make_LinearTransform_matrix(A, b=None):
72
+ """ make a linear transform from a matrix and a bias term (optional)"""
73
+ d_out, d_in = A.shape
74
+ if b is not None:
75
+ assert b.shape == (d_out, )
76
+ lt = faiss.LinearTransform(d_in, d_out, b is not None)
77
+ faiss.copy_array_to_vector(A.ravel(), lt.A)
78
+ if b is not None:
79
+ faiss.copy_array_to_vector(b, lt.b)
80
+ lt.is_trained = True
81
+ lt.set_is_orthonormal()
82
+ return lt
83
+
84
+
85
+ def get_additive_quantizer_codebooks(aq):
86
+ """ return to codebooks of an additive quantizer """
87
+ codebooks = faiss.vector_to_array(aq.codebooks).reshape(-1, aq.d)
88
+ co = faiss.vector_to_array(aq.codebook_offsets)
89
+ return [
90
+ codebooks[co[i]:co[i + 1]]
91
+ for i in range(aq.M)
92
+ ]
93
+
94
+
95
+ def get_flat_data(index):
96
+ """ copy and return the data matrix in an IndexFlat """
97
+ xb = faiss.vector_to_array(index.codes).view("float32")
98
+ return xb.reshape(index.ntotal, index.d)
99
+
100
+
101
+ def get_flat_codes(index_flat):
102
+ """ get the codes from an indexFlatCodes as an array """
103
+ return faiss.vector_to_array(index_flat.codes).reshape(
104
+ index_flat.ntotal, index_flat.code_size)
105
+
106
+
107
+ def get_NSG_neighbors(nsg):
108
+ """ get the neighbor list for the vectors stored in the NSG structure, as
109
+ a N-by-K matrix of indices """
110
+ graph = nsg.get_final_graph()
111
+ neighbors = np.zeros((graph.N, graph.K), dtype='int32')
112
+ faiss.memcpy(
113
+ faiss.swig_ptr(neighbors),
114
+ graph.data,
115
+ neighbors.nbytes
116
+ )
117
+ return neighbors
ScaleDF_rebuttal/python_dedup_pkgs/faiss/contrib/ivf_tools.py ADDED
@@ -0,0 +1,148 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ #
3
+ # This source code is licensed under the MIT license found in the
4
+ # LICENSE file in the root directory of this source tree.
5
+
6
+ import numpy as np
7
+ import faiss
8
+
9
+ from faiss.contrib.inspect_tools import get_invlist_sizes
10
+
11
+
12
+ def add_preassigned(index_ivf, x, a, ids=None):
13
+ """
14
+ Add elements to an IVF index, where the assignment is already computed
15
+ """
16
+ n, d = x.shape
17
+ assert a.shape == (n, )
18
+ if isinstance(index_ivf, faiss.IndexBinaryIVF):
19
+ d *= 8
20
+ assert d == index_ivf.d
21
+ if ids is not None:
22
+ assert ids.shape == (n, )
23
+ ids = faiss.swig_ptr(ids)
24
+ index_ivf.add_core(
25
+ n, faiss.swig_ptr(x), ids, faiss.swig_ptr(a)
26
+ )
27
+
28
+
29
+ def search_preassigned(index_ivf, xq, k, list_nos, coarse_dis=None):
30
+ """
31
+ Perform a search in the IVF index, with predefined lists to search into.
32
+ Supports indexes with pretransforms (as opposed to the
33
+ IndexIVF.search_preassigned, that cannot be applied with pretransform).
34
+ """
35
+ if isinstance(index_ivf, faiss.IndexPreTransform):
36
+ assert index_ivf.chain.size() == 1, "chain must have only one component"
37
+ transform = faiss.downcast_VectorTransform(index_ivf.chain.at(0))
38
+ xq = transform.apply(xq)
39
+ index_ivf = faiss.downcast_index(index_ivf.index)
40
+ n, d = xq.shape
41
+ if isinstance(index_ivf, faiss.IndexBinaryIVF):
42
+ d *= 8
43
+ dis_type = "int32"
44
+ else:
45
+ dis_type = "float32"
46
+
47
+ assert d == index_ivf.d
48
+ assert list_nos.shape == (n, index_ivf.nprobe)
49
+
50
+ # the coarse distances are used in IVFPQ with L2 distance and
51
+ # by_residual=True otherwise we provide dummy coarse_dis
52
+ if coarse_dis is None:
53
+ coarse_dis = np.zeros((n, index_ivf.nprobe), dtype=dis_type)
54
+ else:
55
+ assert coarse_dis.shape == (n, index_ivf.nprobe)
56
+
57
+ return index_ivf.search_preassigned(xq, k, list_nos, coarse_dis)
58
+
59
+
60
+ def range_search_preassigned(index_ivf, x, radius, list_nos, coarse_dis=None):
61
+ """
62
+ Perform a range search in the IVF index, with predefined lists to
63
+ search into
64
+ """
65
+ n, d = x.shape
66
+ if isinstance(index_ivf, faiss.IndexBinaryIVF):
67
+ d *= 8
68
+ dis_type = "int32"
69
+ else:
70
+ dis_type = "float32"
71
+
72
+ # the coarse distances are used in IVFPQ with L2 distance and
73
+ # by_residual=True otherwise we provide dummy coarse_dis
74
+ if coarse_dis is None:
75
+ coarse_dis = np.zeros((n, index_ivf.nprobe), dtype=dis_type)
76
+ else:
77
+ assert coarse_dis.shape == (n, index_ivf.nprobe)
78
+
79
+ assert d == index_ivf.d
80
+ assert list_nos.shape == (n, index_ivf.nprobe)
81
+
82
+ res = faiss.RangeSearchResult(n)
83
+ sp = faiss.swig_ptr
84
+
85
+ index_ivf.range_search_preassigned_c(
86
+ n, sp(x), radius,
87
+ sp(list_nos), sp(coarse_dis),
88
+ res
89
+ )
90
+ # get pointers and copy them
91
+ lims = faiss.rev_swig_ptr(res.lims, n + 1).copy()
92
+ num_results = int(lims[-1])
93
+ dist = faiss.rev_swig_ptr(res.distances, num_results).copy()
94
+ indices = faiss.rev_swig_ptr(res.labels, num_results).copy()
95
+ return lims, dist, indices
96
+
97
+
98
+ def replace_ivf_quantizer(index_ivf, new_quantizer):
99
+ """ replace the IVF quantizer with a flat quantizer and return the
100
+ old quantizer"""
101
+ if new_quantizer.ntotal == 0:
102
+ centroids = index_ivf.quantizer.reconstruct_n()
103
+ new_quantizer.train(centroids)
104
+ new_quantizer.add(centroids)
105
+ else:
106
+ assert new_quantizer.ntotal == index_ivf.nlist
107
+
108
+ # cleanly dealloc old quantizer
109
+ old_own = index_ivf.own_fields
110
+ index_ivf.own_fields = False
111
+ old_quantizer = faiss.downcast_index(index_ivf.quantizer)
112
+ old_quantizer.this.own(old_own)
113
+ index_ivf.quantizer = new_quantizer
114
+
115
+ if hasattr(index_ivf, "referenced_objects"):
116
+ index_ivf.referenced_objects.append(new_quantizer)
117
+ else:
118
+ index_ivf.referenced_objects = [new_quantizer]
119
+ return old_quantizer
120
+
121
+
122
+ def permute_invlists(index_ivf, perm):
123
+ """ Apply some permutation to the inverted lists, and modify the quantizer
124
+ entries accordingly.
125
+ Perm is an array of size nlist, where old_index = perm[new_index]
126
+ """
127
+ nlist, = perm.shape
128
+ assert index_ivf.nlist == nlist
129
+ quantizer = faiss.downcast_index(index_ivf.quantizer)
130
+ assert quantizer.ntotal == index_ivf.nlist
131
+ perm = np.ascontiguousarray(perm, dtype='int64')
132
+
133
+ # just make sure it's a permutation...
134
+ bc = np.bincount(perm, minlength=nlist)
135
+ assert np.all(bc == np.ones(nlist, dtype=int))
136
+
137
+ # handle quantizer
138
+ quantizer.permute_entries(perm)
139
+
140
+ # handle inverted lists
141
+ invlists = faiss.downcast_InvertedLists(index_ivf.invlists)
142
+ invlists.permute_invlists(faiss.swig_ptr(perm))
143
+
144
+
145
+ def sort_invlists_by_size(index_ivf):
146
+ invlist_sizes = get_invlist_sizes(index_ivf.invlists)
147
+ perm = np.argsort(invlist_sizes)
148
+ permute_invlists(index_ivf, perm)
ScaleDF_rebuttal/python_dedup_pkgs/faiss/contrib/ondisk.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ #
3
+ # This source code is licensed under the MIT license found in the
4
+ # LICENSE file in the root directory of this source tree.
5
+
6
+ from typing import List
7
+ import faiss
8
+ import logging
9
+
10
+ LOG = logging.getLogger(__name__)
11
+
12
+
13
+ def merge_ondisk(
14
+ trained_index: faiss.Index, shard_fnames: List[str], ivfdata_fname: str, shift_ids=False
15
+ ) -> None:
16
+ """Add the contents of the indexes stored in shard_fnames into the index
17
+ trained_index. The on-disk data is stored in ivfdata_fname"""
18
+ assert not isinstance(
19
+ trained_index, faiss.IndexIVFPQR
20
+ ), "IndexIVFPQR is not supported as an on disk index."
21
+ # merge the images into an on-disk index
22
+ # first load the inverted lists
23
+ ivfs = []
24
+ for fname in shard_fnames:
25
+ # the IO_FLAG_MMAP is to avoid actually loading the data thus
26
+ # the total size of the inverted lists can exceed the
27
+ # available RAM
28
+ LOG.info("read " + fname)
29
+ index = faiss.read_index(fname, faiss.IO_FLAG_MMAP)
30
+ index_ivf = faiss.extract_index_ivf(index)
31
+ ivfs.append(index_ivf.invlists)
32
+
33
+ # avoid that the invlists get deallocated with the index
34
+ index_ivf.own_invlists = False
35
+
36
+ # construct the output index
37
+ index = trained_index
38
+ index_ivf = faiss.extract_index_ivf(index)
39
+
40
+ assert index.ntotal == 0, "works only on empty index"
41
+
42
+ # prepare the output inverted lists. They will be written
43
+ # to merged_index.ivfdata
44
+ invlists = faiss.OnDiskInvertedLists(
45
+ index_ivf.nlist, index_ivf.code_size, ivfdata_fname
46
+ )
47
+
48
+ # merge all the inverted lists
49
+ ivf_vector = faiss.InvertedListsPtrVector()
50
+ for ivf in ivfs:
51
+ ivf_vector.push_back(ivf)
52
+
53
+ LOG.info("merge %d inverted lists " % ivf_vector.size())
54
+ ntotal = invlists.merge_from_multiple(ivf_vector.data(), ivf_vector.size(), shift_ids)
55
+
56
+ # now replace the inverted lists in the output index
57
+ index.ntotal = index_ivf.ntotal = ntotal
58
+ index_ivf.replace_invlists(invlists, True)
59
+ invlists.this.disown()
ScaleDF_rebuttal/python_dedup_pkgs/faiss/contrib/rpc.py ADDED
@@ -0,0 +1,261 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ #
3
+ # This source code is licensed under the MIT license found in the
4
+ # LICENSE file in the root directory of this source tree.
5
+
6
+ """
7
+ Simplistic RPC implementation.
8
+ Exposes all functions of a Server object.
9
+
10
+ This code is for demonstration purposes only, and does not include certain
11
+ security protections. It is not meant to be run on an untrusted network or
12
+ in a production environment.
13
+ """
14
+
15
+ import importlib
16
+ import os
17
+ import pickle
18
+ import sys
19
+ import _thread
20
+ import traceback
21
+ import socket
22
+ import logging
23
+
24
+ LOG = logging.getLogger(__name__)
25
+
26
+ # default
27
+ PORT = 12032
28
+
29
+ safe_modules = {
30
+ 'numpy',
31
+ 'numpy.core.multiarray',
32
+ }
33
+
34
+
35
+ class RestrictedUnpickler(pickle.Unpickler):
36
+
37
+ def find_class(self, module, name):
38
+ # Only allow safe modules.
39
+ if module in safe_modules:
40
+ return getattr(importlib.import_module(module), name)
41
+ # Forbid everything else.
42
+ raise pickle.UnpicklingError("global '%s.%s' is forbidden" %
43
+ (module, name))
44
+
45
+
46
+ class FileSock:
47
+ " wraps a socket so that it is usable by pickle/cPickle "
48
+
49
+ def __init__(self,sock):
50
+ self.sock = sock
51
+ self.nr=0
52
+
53
+ def write(self, buf):
54
+ # print("sending %d bytes"%len(buf))
55
+ #self.sock.sendall(buf)
56
+ # print("...done")
57
+ bs = 512 * 1024
58
+ ns = 0
59
+ while ns < len(buf):
60
+ sent = self.sock.send(buf[ns:ns + bs])
61
+ ns += sent
62
+
63
+ def read(self,bs=512*1024):
64
+ #if self.nr==10000: pdb.set_trace()
65
+ self.nr+=1
66
+ # print("read bs=%d"%bs)
67
+ b = []
68
+ nb = 0
69
+ while len(b)<bs:
70
+ # print(' loop')
71
+ rb = self.sock.recv(bs - nb)
72
+ if not rb: break
73
+ b.append(rb)
74
+ nb += len(rb)
75
+ return b''.join(b)
76
+
77
+ def readline(self):
78
+ # print("readline!")
79
+ """may be optimized..."""
80
+ s=bytes()
81
+ while True:
82
+ c=self.read(1)
83
+ s+=c
84
+ if len(c)==0 or chr(c[0])=='\n':
85
+ return s
86
+
87
+
88
+ class ClientExit(Exception):
89
+ pass
90
+
91
+
92
+ class ServerException(Exception):
93
+ pass
94
+
95
+
96
+ class Server:
97
+ """
98
+ server protocol. Methods from classes that subclass Server can be called
99
+ transparently from a client
100
+ """
101
+
102
+ def __init__(self, s, logf=sys.stderr, log_prefix=''):
103
+ self.logf = logf
104
+ self.log_prefix = log_prefix
105
+
106
+ # connection
107
+
108
+ self.conn = s
109
+ self.fs = FileSock(s)
110
+
111
+
112
+ def log(self, s):
113
+ self.logf.write("Server log %s: %s\n" % (self.log_prefix, s))
114
+
115
+ def one_function(self):
116
+ """
117
+ Executes a single function with associated I/O.
118
+ Protocol:
119
+ - the arguments and results are serialized with the pickle protocol
120
+ - client sends : (fname,args)
121
+ fname = method name to call
122
+ args = tuple of arguments
123
+ - server sends result: (rid,st,ret)
124
+ rid = request id
125
+ st = None, or exception if there was during execution
126
+ ret = return value or None if st!=None
127
+ """
128
+
129
+ try:
130
+ (fname, args) = RestrictedUnpickler(self.fs).load()
131
+ except EOFError:
132
+ raise ClientExit("read args")
133
+ self.log("executing method %s"%(fname))
134
+ st = None
135
+ ret = None
136
+ try:
137
+ f=getattr(self,fname)
138
+ except AttributeError:
139
+ st = AttributeError("unknown method "+fname)
140
+ self.log("unknown method")
141
+
142
+ try:
143
+ ret = f(*args)
144
+ except Exception as e:
145
+ # due to a bug (in mod_python?), ServerException cannot be
146
+ # unpickled, so send the string and make the exception on the client side
147
+
148
+ #st=ServerException(
149
+ # "".join(traceback.format_tb(sys.exc_info()[2]))+
150
+ # str(e))
151
+ st="".join(traceback.format_tb(sys.exc_info()[2]))+str(e)
152
+ self.log("exception in method")
153
+ traceback.print_exc(50,self.logf)
154
+ self.logf.flush()
155
+
156
+ LOG.info("return")
157
+ try:
158
+ pickle.dump((st ,ret), self.fs, protocol=4)
159
+ except EOFError:
160
+ raise ClientExit("function return")
161
+
162
+ def exec_loop(self):
163
+ """ main execution loop. Loops and handles exit states"""
164
+
165
+ self.log("in exec_loop")
166
+ try:
167
+ while True:
168
+ self.one_function()
169
+ except ClientExit as e:
170
+ self.log("ClientExit %s"%e)
171
+ except socket.error as e:
172
+ self.log("socket error %s"%e)
173
+ traceback.print_exc(50,self.logf)
174
+ except EOFError:
175
+ self.log("EOF during communication")
176
+ traceback.print_exc(50,self.logf)
177
+ except BaseException:
178
+ # unexpected
179
+ traceback.print_exc(50,sys.stderr)
180
+ sys.exit(1)
181
+
182
+ LOG.info("exit server")
183
+
184
+ def exec_loop_cleanup(self):
185
+ pass
186
+
187
+ ###################################################################
188
+ # spying stuff
189
+
190
+ def get_ps_stats(self):
191
+ ret=''
192
+ f=os.popen("echo ============ `hostname` uptime:; uptime;"+
193
+ "echo ============ self:; "+
194
+ "ps -p %d -o pid,vsize,rss,%%cpu,nlwp,psr; "%os.getpid()+
195
+ "echo ============ run queue:;"+
196
+ "ps ar -o user,pid,%cpu,%mem,ni,nlwp,psr,vsz,rss,cputime,command")
197
+ for l in f:
198
+ ret+=l
199
+ return ret
200
+
201
+
202
+ class Client:
203
+ """
204
+ Methods of the server object can be called transparently. Exceptions are
205
+ re-raised.
206
+ """
207
+ def __init__(self, HOST, port=PORT, v6=False):
208
+ socktype = socket.AF_INET6 if v6 else socket.AF_INET
209
+
210
+ sock = socket.socket(socktype, socket.SOCK_STREAM)
211
+ LOG.info("connecting to %s:%d, socket type: %s", HOST, port, socktype)
212
+ sock.connect((HOST, port))
213
+ self.sock = sock
214
+ self.fs = FileSock(sock)
215
+
216
+ def generic_fun(self, fname, args):
217
+ # int "gen fun",fname
218
+ pickle.dump((fname, args), self.fs, protocol=4)
219
+ return self.get_result()
220
+
221
+ def get_result(self):
222
+ (st, ret) = RestrictedUnpickler(self.fs).load()
223
+ if st!=None:
224
+ raise ServerException(st)
225
+ else:
226
+ return ret
227
+
228
+ def __getattr__(self,name):
229
+ return lambda *x: self.generic_fun(name,x)
230
+
231
+
232
+ def run_server(new_handler, port=PORT, report_to_file=None, v6=False):
233
+
234
+ HOST = '' # Symbolic name meaning the local host
235
+ socktype = socket.AF_INET6 if v6 else socket.AF_INET
236
+ s = socket.socket(socktype, socket.SOCK_STREAM)
237
+ s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
238
+
239
+ LOG.info("bind %s:%d", HOST, port)
240
+ s.bind((HOST, port))
241
+ s.listen(5)
242
+
243
+ LOG.info("accepting connections")
244
+ if report_to_file is not None:
245
+ LOG.info('storing host+port in %s', report_to_file)
246
+ open(report_to_file, 'w').write('%s:%d ' % (socket.gethostname(), port))
247
+
248
+ while True:
249
+ try:
250
+ conn, addr = s.accept()
251
+ except socket.error as e:
252
+ if e[1]=='Interrupted system call': continue
253
+ raise
254
+
255
+ LOG.info('Connected to %s', addr)
256
+
257
+ ibs = new_handler(conn)
258
+
259
+ tid = _thread.start_new_thread(ibs.exec_loop,())
260
+
261
+ LOG.debug("Thread ID: %d", tid)
ScaleDF_rebuttal/python_dedup_pkgs/faiss/contrib/torch/README.md ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ # The Torch contrib
2
+
3
+ This contrib directory contains a few Pytorch routines that
4
+ are useful for similarity search. They do not necessarily depend on Faiss.
5
+
6
+ The code is designed to work with CPU and GPU tensors.
ScaleDF_rebuttal/python_dedup_pkgs/faiss/contrib/torch/__init__.py ADDED
File without changes
ScaleDF_rebuttal/python_dedup_pkgs/faiss/contrib/torch/clustering.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ #
3
+ # This source code is licensed under the MIT license found in the
4
+ # LICENSE file in the root directory of this source tree.
5
+
6
+ """
7
+ This contrib module contains Pytorch code for k-means clustering
8
+ """
9
+ import faiss
10
+ import faiss.contrib.torch_utils
11
+ import torch
12
+
13
+ # the kmeans can produce both torch and numpy centroids
14
+ from faiss.contrib.clustering import kmeans # noqa: F401 some libraries import kmeans from here
15
+
16
+
17
+
18
+ class DatasetAssign:
19
+ """Wrapper for a tensor that offers a function to assign the vectors
20
+ to centroids. All other implementations offer the same interface"""
21
+
22
+ def __init__(self, x):
23
+ self.x = x
24
+
25
+ def count(self):
26
+ return self.x.shape[0]
27
+
28
+ def dim(self):
29
+ return self.x.shape[1]
30
+
31
+ def get_subset(self, indices):
32
+ return self.x[indices]
33
+
34
+ def perform_search(self, centroids):
35
+ return faiss.knn(self.x, centroids, 1)
36
+
37
+ def assign_to(self, centroids, weights=None):
38
+ D, I = self.perform_search(centroids)
39
+
40
+ I = I.ravel()
41
+ D = D.ravel()
42
+ nc, d = centroids.shape
43
+
44
+ sum_per_centroid = torch.zeros_like(centroids)
45
+ if weights is None:
46
+ sum_per_centroid.index_add_(0, I, self.x)
47
+ else:
48
+ sum_per_centroid.index_add_(0, I, self.x * weights[:, None])
49
+
50
+ # the indices are still in numpy.
51
+ return I.cpu().numpy(), D, sum_per_centroid
52
+
53
+
54
+ class DatasetAssignGPU(DatasetAssign):
55
+
56
+ def __init__(self, res, x):
57
+ DatasetAssign.__init__(self, x)
58
+ self.res = res
59
+
60
+ def perform_search(self, centroids):
61
+ return faiss.knn_gpu(self.res, self.x, centroids, 1)
ScaleDF_rebuttal/python_dedup_pkgs/faiss/contrib/torch/quantization.py ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ #
3
+ # This source code is licensed under the MIT license found in the
4
+ # LICENSE file in the root directory of this source tree.
5
+
6
+ """
7
+ This contrib module contains Pytorch code for quantization.
8
+ """
9
+
10
+ import torch
11
+ import faiss
12
+ import math
13
+ from faiss.contrib.torch import clustering
14
+ # the kmeans can produce both torch and numpy centroids
15
+
16
+
17
+ class Quantizer:
18
+
19
+ def __init__(self, d, code_size):
20
+ """
21
+ d: dimension of vectors
22
+ code_size: nb of bytes of the code (per vector)
23
+ """
24
+ self.d = d
25
+ self.code_size = code_size
26
+
27
+ def train(self, x):
28
+ """
29
+ takes a n-by-d array and performs training
30
+ """
31
+ pass
32
+
33
+ def encode(self, x):
34
+ """
35
+ takes a n-by-d float array, encodes to an n-by-code_size uint8 array
36
+ """
37
+ pass
38
+
39
+ def decode(self, codes):
40
+ """
41
+ takes a n-by-code_size uint8 array, returns a n-by-d array
42
+ """
43
+ pass
44
+
45
+
46
+ class VectorQuantizer(Quantizer):
47
+
48
+ def __init__(self, d, k):
49
+
50
+ code_size = int(math.ceil(torch.log2(k) / 8))
51
+ Quantizer.__init__(d, code_size)
52
+ self.k = k
53
+
54
+ def train(self, x):
55
+ pass
56
+
57
+
58
+ class ProductQuantizer(Quantizer):
59
+ def __init__(self, d, M, nbits):
60
+ """ M: number of subvectors, d%M == 0
61
+ nbits: number of bits that each vector is encoded into
62
+ """
63
+ assert d % M == 0
64
+ assert nbits == 8 # todo: implement other nbits values
65
+ code_size = int(math.ceil(M * nbits / 8))
66
+ Quantizer.__init__(self, d, code_size)
67
+ self.M = M
68
+ self.nbits = nbits
69
+ self.code_size = code_size
70
+
71
+ def train(self, x):
72
+ nc = 2 ** self.nbits
73
+ sd = self.d // self.M
74
+ dev = x.device
75
+ dtype = x.dtype
76
+ self.codebook = torch.zeros((self.M, nc, sd), device=dev, dtype=dtype)
77
+ for m in range(self.M):
78
+ xsub = x[:, m * self.d // self.M: (m + 1) * self.d // self.M]
79
+ data = clustering.DatasetAssign(xsub.contiguous())
80
+ self.codebook[m] = clustering.kmeans(2 ** self.nbits, data)
81
+
82
+ def encode(self, x):
83
+ codes = torch.zeros((x.shape[0], self.code_size), dtype=torch.uint8)
84
+ for m in range(self.M):
85
+ xsub = x[:, m * self.d // self.M:(m + 1) * self.d // self.M]
86
+ _, I = faiss.knn(xsub.contiguous(), self.codebook[m], 1)
87
+ codes[:, m] = I.ravel()
88
+ return codes
89
+
90
+ def decode(self, codes):
91
+ idxs = [codes[:, m].long() for m in range(self.M)]
92
+ vectors = [self.codebook[m, idxs[m], :] for m in range(self.M)]
93
+ stacked_vectors = torch.stack(vectors, dim=1)
94
+ cbd = self.codebook.shape[-1]
95
+ x_rec = stacked_vectors.reshape(-1, cbd * self.M)
96
+ return x_rec
ScaleDF_rebuttal/python_dedup_pkgs/faiss/contrib/torch_utils.py ADDED
@@ -0,0 +1,839 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ #
3
+ # This source code is licensed under the MIT license found in the
4
+ # LICENSE file in the root directory of this source tree.
5
+
6
+ """
7
+
8
+ This is a set of function wrappers that override the default numpy versions.
9
+
10
+ Interoperability functions for pytorch and Faiss: Importing this will allow
11
+ pytorch Tensors (CPU or GPU) to be used as arguments to Faiss indexes and
12
+ other functions. Torch GPU tensors can only be used with Faiss GPU indexes.
13
+ If this is imported with a package that supports Faiss GPU, the necessary
14
+ stream synchronization with the current pytorch stream will be automatically
15
+ performed.
16
+
17
+ Numpy ndarrays can continue to be used in the Faiss python interface after
18
+ importing this file. All arguments must be uniformly either numpy ndarrays
19
+ or Torch tensors; no mixing is allowed.
20
+
21
+ """
22
+
23
+
24
+ import faiss
25
+ import torch
26
+ import contextlib
27
+ import inspect
28
+ import sys
29
+ import numpy as np
30
+
31
+ ##################################################################
32
+ # Equivalent of swig_ptr for Torch tensors
33
+ ##################################################################
34
+
35
+
36
+ def swig_ptr_from_UInt8Tensor(x):
37
+ """ gets a Faiss SWIG pointer from a pytorch tensor (on CPU or GPU) """
38
+ assert x.is_contiguous()
39
+ assert x.dtype == torch.uint8
40
+ return faiss.cast_integer_to_uint8_ptr(
41
+ x.untyped_storage().data_ptr() + x.storage_offset())
42
+
43
+
44
+ def swig_ptr_from_HalfTensor(x):
45
+ """ gets a Faiss SWIG pointer from a pytorch tensor (on CPU or GPU) """
46
+ assert x.is_contiguous()
47
+ assert x.dtype == torch.float16
48
+ # no canonical half type in C/C++
49
+ return faiss.cast_integer_to_void_ptr(
50
+ x.untyped_storage().data_ptr() + x.storage_offset() * 2)
51
+
52
+
53
+ def swig_ptr_from_FloatTensor(x):
54
+ """ gets a Faiss SWIG pointer from a pytorch tensor (on CPU or GPU) """
55
+ assert x.is_contiguous()
56
+ assert x.dtype == torch.float32
57
+ return faiss.cast_integer_to_float_ptr(
58
+ x.untyped_storage().data_ptr() + x.storage_offset() * 4)
59
+
60
+
61
+ def swig_ptr_from_BFloat16Tensor(x):
62
+ """ gets a Faiss SWIG pointer from a pytorch tensor (on CPU or GPU) """
63
+ assert x.is_contiguous()
64
+ assert x.dtype == torch.bfloat16
65
+ return faiss.cast_integer_to_void_ptr(
66
+ x.untyped_storage().data_ptr() + x.storage_offset() * 2)
67
+
68
+
69
+ def swig_ptr_from_IntTensor(x):
70
+ """ gets a Faiss SWIG pointer from a pytorch tensor (on CPU or GPU) """
71
+ assert x.is_contiguous()
72
+ assert x.dtype == torch.int32, 'dtype=%s' % x.dtype
73
+ return faiss.cast_integer_to_int_ptr(
74
+ x.untyped_storage().data_ptr() + x.storage_offset() * 4)
75
+
76
+
77
+ def swig_ptr_from_IndicesTensor(x):
78
+ """ gets a Faiss SWIG pointer from a pytorch tensor (on CPU or GPU) """
79
+ assert x.is_contiguous()
80
+ assert x.dtype == torch.int64, 'dtype=%s' % x.dtype
81
+ return faiss.cast_integer_to_idx_t_ptr(
82
+ x.untyped_storage().data_ptr() + x.storage_offset() * 8)
83
+
84
+ ##################################################################
85
+ # utilities
86
+ ##################################################################
87
+
88
+
89
+ @contextlib.contextmanager
90
+ def using_stream(res, pytorch_stream=None):
91
+ """ Creates a scoping object to make Faiss GPU use the same stream
92
+ as pytorch, based on torch.cuda.current_stream().
93
+ Or, a specific pytorch stream can be passed in as a second
94
+ argument, in which case we will use that stream.
95
+ """
96
+
97
+ if pytorch_stream is None:
98
+ pytorch_stream = torch.cuda.current_stream()
99
+
100
+ # This is the cudaStream_t that we wish to use
101
+ cuda_stream_s = faiss.cast_integer_to_cudastream_t(
102
+ pytorch_stream.cuda_stream)
103
+
104
+ # So we can revert GpuResources stream state upon exit
105
+ prior_dev = torch.cuda.current_device()
106
+ prior_stream = res.getDefaultStream(torch.cuda.current_device())
107
+
108
+ res.setDefaultStream(torch.cuda.current_device(), cuda_stream_s)
109
+
110
+ # Do the user work
111
+ try:
112
+ yield
113
+ finally:
114
+ res.setDefaultStream(prior_dev, prior_stream)
115
+
116
+
117
+ def torch_replace_method(the_class, name, replacement,
118
+ ignore_missing=False, ignore_no_base=False):
119
+ try:
120
+ orig_method = getattr(the_class, name)
121
+ except AttributeError:
122
+ if ignore_missing:
123
+ return
124
+ raise
125
+ if orig_method.__name__ == 'torch_replacement_' + name:
126
+ # replacement was done in parent class
127
+ return
128
+
129
+ # We should already have the numpy replacement methods patched
130
+ assert ignore_no_base or (orig_method.__name__ == 'replacement_' + name)
131
+ setattr(the_class, name + '_numpy', orig_method)
132
+ setattr(the_class, name, replacement)
133
+
134
+ ##################################################################
135
+ # Setup wrappers
136
+ ##################################################################
137
+
138
+
139
+ def handle_torch_Index(the_class):
140
+ def torch_replacement_add(self, x, numeric_type=faiss.Float32):
141
+ if type(x) is np.ndarray:
142
+ # forward to faiss __init__.py base method
143
+ return self.add_numpy(x)
144
+
145
+ assert type(x) is torch.Tensor
146
+ n, d = x.shape
147
+ assert d == self.d
148
+ if numeric_type == faiss.Float32:
149
+ x_ptr = swig_ptr_from_FloatTensor(x)
150
+ elif numeric_type == faiss.Float16:
151
+ x_ptr = swig_ptr_from_HalfTensor(x)
152
+ else:
153
+ raise ValueError(
154
+ "numeric type must be either faiss.Float32 or faiss.Float16"
155
+ )
156
+
157
+ if x.is_cuda:
158
+ assert hasattr(self, 'getDevice'), \
159
+ 'GPU tensor on CPU index not allowed'
160
+
161
+ # On the GPU, use proper stream ordering
162
+ with using_stream(self.getResources()):
163
+ self.add_ex(n, x_ptr, numeric_type)
164
+ else:
165
+ # CPU torch
166
+ self.add_ex(n, x_ptr, numeric_type)
167
+
168
+ def torch_replacement_add_with_ids(self, x, ids,
169
+ numeric_type=faiss.Float32):
170
+ if type(x) is np.ndarray:
171
+ # forward to faiss __init__.py base method
172
+ return self.add_with_ids_numpy(x, ids)
173
+
174
+ assert type(x) is torch.Tensor
175
+ n, d = x.shape
176
+ assert d == self.d
177
+ if numeric_type == faiss.Float32:
178
+ x_ptr = swig_ptr_from_FloatTensor(x)
179
+ elif numeric_type == faiss.Float16:
180
+ x_ptr = swig_ptr_from_HalfTensor(x)
181
+ else:
182
+ raise ValueError(
183
+ "numeric type must be either faiss.Float32 or faiss.Float16"
184
+ )
185
+
186
+ assert type(ids) is torch.Tensor
187
+ assert ids.shape == (n, ), 'not same number of vectors as ids'
188
+ ids_ptr = swig_ptr_from_IndicesTensor(ids)
189
+
190
+ if x.is_cuda:
191
+ assert hasattr(self, 'getDevice'), \
192
+ 'GPU tensor on CPU index not allowed'
193
+
194
+ # On the GPU, use proper stream ordering
195
+ with using_stream(self.getResources()):
196
+ self.add_with_ids_ex(n, x_ptr, numeric_type, ids_ptr)
197
+ else:
198
+ # CPU torch
199
+ self.add_with_ids_ex(n, x_ptr, numeric_type, ids_ptr)
200
+
201
+ def torch_replacement_assign(self, x, k, labels=None):
202
+ if type(x) is np.ndarray:
203
+ # forward to faiss __init__.py base method
204
+ return self.assign_numpy(x, k, labels)
205
+
206
+ assert type(x) is torch.Tensor
207
+ n, d = x.shape
208
+ assert d == self.d
209
+ x_ptr = swig_ptr_from_FloatTensor(x)
210
+
211
+ if labels is None:
212
+ labels = torch.empty(n, k, device=x.device, dtype=torch.int64)
213
+ else:
214
+ assert type(labels) is torch.Tensor
215
+ assert labels.shape == (n, k)
216
+ L_ptr = swig_ptr_from_IndicesTensor(labels)
217
+
218
+ if x.is_cuda:
219
+ assert hasattr(self, 'getDevice'), \
220
+ 'GPU tensor on CPU index not allowed'
221
+
222
+ # On the GPU, use proper stream ordering
223
+ with using_stream(self.getResources()):
224
+ self.assign_c(n, x_ptr, L_ptr, k)
225
+ else:
226
+ # CPU torch
227
+ self.assign_c(n, x_ptr, L_ptr, k)
228
+
229
+ return labels
230
+
231
+ def torch_replacement_train(self, x, numeric_type=faiss.Float32):
232
+ if type(x) is np.ndarray:
233
+ # forward to faiss __init__.py base method
234
+ return self.train_numpy(x)
235
+
236
+ assert type(x) is torch.Tensor
237
+ n, d = x.shape
238
+ assert d == self.d
239
+ if numeric_type == faiss.Float32:
240
+ x_ptr = swig_ptr_from_FloatTensor(x)
241
+ elif numeric_type == faiss.Float16:
242
+ x_ptr = swig_ptr_from_HalfTensor(x)
243
+ else:
244
+ raise ValueError(
245
+ "numeric type must be either faiss.Float32 or faiss.Float16"
246
+ )
247
+
248
+ if x.is_cuda:
249
+ assert hasattr(self, 'getDevice'), \
250
+ 'GPU tensor on CPU index not allowed'
251
+
252
+ # On the GPU, use proper stream ordering
253
+ with using_stream(self.getResources()):
254
+ self.train_ex(n, x_ptr, numeric_type)
255
+ else:
256
+ # CPU torch
257
+ self.train_ex(n, x_ptr, numeric_type)
258
+
259
+ def search_methods_common(x, k, D, I, numeric_type=faiss.Float32):
260
+ n, d = x.shape
261
+ if numeric_type == faiss.Float32:
262
+ x_ptr = swig_ptr_from_FloatTensor(x)
263
+ elif numeric_type == faiss.Float16:
264
+ x_ptr = swig_ptr_from_HalfTensor(x)
265
+ else:
266
+ raise ValueError(
267
+ "numeric type must be either faiss.Float32 or faiss.Float16"
268
+ )
269
+
270
+ if D is None:
271
+ D = torch.empty(n, k, device=x.device, dtype=torch.float32)
272
+ else:
273
+ assert type(D) is torch.Tensor
274
+ assert D.shape == (n, k)
275
+ D_ptr = swig_ptr_from_FloatTensor(D)
276
+
277
+ if I is None:
278
+ I = torch.empty(n, k, device=x.device, dtype=torch.int64)
279
+ else:
280
+ assert type(I) is torch.Tensor
281
+ assert I.shape == (n, k)
282
+ I_ptr = swig_ptr_from_IndicesTensor(I)
283
+
284
+ return x_ptr, D_ptr, I_ptr, D, I
285
+
286
+ def torch_replacement_search(self, x, k, D=None, I=None,
287
+ numeric_type=faiss.Float32):
288
+ if type(x) is np.ndarray:
289
+ # forward to faiss __init__.py base method
290
+ return self.search_numpy(x, k, D=D, I=I)
291
+
292
+ assert type(x) is torch.Tensor
293
+ n, d = x.shape
294
+ assert d == self.d
295
+
296
+ x_ptr, D_ptr, I_ptr, D, I = search_methods_common(x, k, D, I)
297
+
298
+ if x.is_cuda:
299
+ assert hasattr(self, 'getDevice'), \
300
+ 'GPU tensor on CPU index not allowed'
301
+
302
+ # On the GPU, use proper stream ordering
303
+ with using_stream(self.getResources()):
304
+ self.search_ex(n, x_ptr, numeric_type, k, D_ptr, I_ptr)
305
+ else:
306
+ # CPU torch
307
+ self.search_ex(n, x_ptr, numeric_type, k, D_ptr, I_ptr)
308
+
309
+ return D, I
310
+
311
+ def torch_replacement_search_and_reconstruct(self, x, k, D=None, I=None,
312
+ R=None):
313
+ if type(x) is np.ndarray:
314
+ # Forward to faiss __init__.py base method
315
+ return self.search_and_reconstruct_numpy(x, k, D=D, I=I, R=R)
316
+
317
+ assert type(x) is torch.Tensor
318
+ n, d = x.shape
319
+ assert d == self.d
320
+
321
+ x_ptr, D_ptr, I_ptr, D, I = search_methods_common(x, k, D, I)
322
+
323
+ if R is None:
324
+ R = torch.empty(n, k, d, device=x.device, dtype=torch.float32)
325
+ else:
326
+ assert type(R) is torch.Tensor
327
+ assert R.shape == (n, k, d)
328
+ R_ptr = swig_ptr_from_FloatTensor(R)
329
+
330
+ if x.is_cuda:
331
+ assert hasattr(self, 'getDevice'), \
332
+ 'GPU tensor on CPU index not allowed'
333
+
334
+ # On the GPU, use proper stream ordering
335
+ with using_stream(self.getResources()):
336
+ self.search_and_reconstruct_c(n, x_ptr, k, D_ptr, I_ptr, R_ptr)
337
+ else:
338
+ # CPU torch
339
+ self.search_and_reconstruct_c(n, x_ptr, k, D_ptr, I_ptr,
340
+ R_ptr)
341
+
342
+ return D, I, R
343
+
344
+ def torch_replacement_search_preassigned(self, x, k, Iq, Dq, *,
345
+ D=None, I=None):
346
+ if type(x) is np.ndarray:
347
+ # forward to faiss __init__.py base method
348
+ return self.search_preassigned_numpy(x, k, Iq, Dq, D=D, I=I)
349
+
350
+ assert type(x) is torch.Tensor
351
+ n, d = x.shape
352
+ assert d == self.d
353
+
354
+ x_ptr, D_ptr, I_ptr, D, I = search_methods_common(x, k, D, I)
355
+
356
+ assert Iq.shape == (n, self.nprobe)
357
+ Iq = Iq.contiguous()
358
+ Iq_ptr = swig_ptr_from_IndicesTensor(Iq)
359
+
360
+ if Dq is not None:
361
+ Dq = Dq.contiguous()
362
+ assert Dq.shape == Iq.shape
363
+ Dq_ptr = swig_ptr_from_FloatTensor(Dq)
364
+ else:
365
+ Dq_ptr = None
366
+
367
+ if x.is_cuda:
368
+ assert hasattr(self, 'getDevice'), \
369
+ 'GPU tensor on CPU index not allowed'
370
+
371
+ # On the GPU, use proper stream ordering
372
+ with using_stream(self.getResources()):
373
+ self.search_preassigned_c(n, x_ptr, k, Iq_ptr, Dq_ptr,
374
+ D_ptr, I_ptr, False)
375
+ else:
376
+ # CPU torch
377
+ self.search_preassigned_c(n, x_ptr, k, Iq_ptr, Dq_ptr,
378
+ D_ptr, I_ptr, False)
379
+
380
+ return D, I
381
+
382
+ def torch_replacement_remove_ids(self, x):
383
+ # Not yet implemented
384
+ assert type(x) is not torch.Tensor, \
385
+ 'remove_ids not yet implemented for torch'
386
+ return self.remove_ids_numpy(x)
387
+
388
+ def torch_replacement_reconstruct(self, key, x=None):
389
+ # No tensor inputs are required, but with importing this module, we
390
+ # assume that the default should be torch tensors. If we are passed a
391
+ # numpy array, however, assume that the user is overriding this default
392
+ if (x is not None) and (type(x) is np.ndarray):
393
+ # Forward to faiss __init__.py base method
394
+ return self.reconstruct_numpy(key, x)
395
+
396
+ # If the index is a CPU index, the default device is CPU, otherwise we
397
+ # produce a GPU tensor
398
+ device = torch.device('cpu')
399
+ if hasattr(self, 'getDevice'):
400
+ # same device as the index
401
+ device = torch.device('cuda', self.getDevice())
402
+
403
+ if x is None:
404
+ x = torch.empty(self.d, device=device, dtype=torch.float32)
405
+ else:
406
+ assert type(x) is torch.Tensor
407
+ assert x.shape == (self.d, )
408
+ x_ptr = swig_ptr_from_FloatTensor(x)
409
+
410
+ if x.is_cuda:
411
+ assert hasattr(self, 'getDevice'), \
412
+ 'GPU tensor on CPU index not allowed'
413
+
414
+ # On the GPU, use proper stream ordering
415
+ with using_stream(self.getResources()):
416
+ self.reconstruct_c(key, x_ptr)
417
+ else:
418
+ # CPU torch
419
+ self.reconstruct_c(key, x_ptr)
420
+
421
+ return x
422
+
423
+ def torch_replacement_reconstruct_n(self, n0=0, ni=-1, x=None):
424
+ if ni == -1:
425
+ ni = self.ntotal
426
+
427
+ # No tensor inputs are required, but with importing this module, we
428
+ # assume that the default should be torch tensors. If we are passed a
429
+ # numpy array, however, assume that the user is overriding this default
430
+ if (x is not None) and (type(x) is np.ndarray):
431
+ # Forward to faiss __init__.py base method
432
+ return self.reconstruct_n_numpy(n0, ni, x)
433
+
434
+ # If the index is a CPU index, the default device is CPU, otherwise we
435
+ # produce a GPU tensor
436
+ device = torch.device('cpu')
437
+ if hasattr(self, 'getDevice'):
438
+ # same device as the index
439
+ device = torch.device('cuda', self.getDevice())
440
+
441
+ if x is None:
442
+ x = torch.empty(ni, self.d, device=device, dtype=torch.float32)
443
+ else:
444
+ assert type(x) is torch.Tensor
445
+ assert x.shape == (ni, self.d)
446
+ x_ptr = swig_ptr_from_FloatTensor(x)
447
+
448
+ if x.is_cuda:
449
+ assert hasattr(self, 'getDevice'), \
450
+ 'GPU tensor on CPU index not allowed'
451
+
452
+ # On the GPU, use proper stream ordering
453
+ with using_stream(self.getResources()):
454
+ self.reconstruct_n_c(n0, ni, x_ptr)
455
+ else:
456
+ # CPU torch
457
+ self.reconstruct_n_c(n0, ni, x_ptr)
458
+
459
+ return x
460
+
461
+ def torch_replacement_update_vectors(self, keys, x):
462
+ if type(keys) is np.ndarray:
463
+ # Forward to faiss __init__.py base method
464
+ return self.update_vectors_numpy(keys, x)
465
+
466
+ assert type(keys) is torch.Tensor
467
+ (n, ) = keys.shape
468
+ keys_ptr = swig_ptr_from_IndicesTensor(keys)
469
+
470
+ assert type(x) is torch.Tensor
471
+ assert x.shape == (n, self.d)
472
+ x_ptr = swig_ptr_from_FloatTensor(x)
473
+
474
+ if x.is_cuda:
475
+ assert hasattr(self, 'getDevice'), \
476
+ 'GPU tensor on CPU index not allowed'
477
+
478
+ # On the GPU, use proper stream ordering
479
+ with using_stream(self.getResources()):
480
+ self.update_vectors_c(n, keys_ptr, x_ptr)
481
+ else:
482
+ # CPU torch
483
+ self.update_vectors_c(n, keys_ptr, x_ptr)
484
+
485
+ # Until the GPU version is implemented, we do not support pre-allocated
486
+ # output buffers
487
+ def torch_replacement_range_search(self, x, thresh):
488
+ if type(x) is np.ndarray:
489
+ # Forward to faiss __init__.py base method
490
+ return self.range_search_numpy(x, thresh)
491
+
492
+ assert type(x) is torch.Tensor
493
+ n, d = x.shape
494
+ assert d == self.d
495
+ x_ptr = swig_ptr_from_FloatTensor(x)
496
+
497
+ assert not x.is_cuda, \
498
+ 'Range search using GPU tensor not yet implemented'
499
+ assert not hasattr(self, 'getDevice'), \
500
+ 'Range search on GPU index not yet implemented'
501
+
502
+ res = faiss.RangeSearchResult(n)
503
+ self.range_search_c(n, x_ptr, thresh, res)
504
+
505
+ # get pointers and copy them
506
+ # FIXME: no rev_swig_ptr equivalent for torch.Tensor, just convert
507
+ # np to torch
508
+ # NOTE: torch does not support np.uint64, just np.int64
509
+ lims = torch.from_numpy(
510
+ faiss.rev_swig_ptr(res.lims, n + 1).copy().astype('int64'))
511
+ nd = int(lims[-1])
512
+ D = torch.from_numpy(faiss.rev_swig_ptr(res.distances, nd).copy())
513
+ I = torch.from_numpy(faiss.rev_swig_ptr(res.labels, nd).copy())
514
+
515
+ return lims, D, I
516
+
517
+ def torch_replacement_sa_encode(self, x, codes=None):
518
+ if type(x) is np.ndarray:
519
+ # Forward to faiss __init__.py base method
520
+ return self.sa_encode_numpy(x, codes)
521
+
522
+ assert type(x) is torch.Tensor
523
+ n, d = x.shape
524
+ assert d == self.d
525
+ x_ptr = swig_ptr_from_FloatTensor(x)
526
+
527
+ if codes is None:
528
+ codes = torch.empty(n, self.sa_code_size(), dtype=torch.uint8)
529
+ else:
530
+ assert codes.shape == (n, self.sa_code_size())
531
+ codes_ptr = swig_ptr_from_UInt8Tensor(codes)
532
+
533
+ if x.is_cuda:
534
+ assert hasattr(self, 'getDevice'), \
535
+ 'GPU tensor on CPU index not allowed'
536
+
537
+ # On the GPU, use proper stream ordering
538
+ with using_stream(self.getResources()):
539
+ self.sa_encode_c(n, x_ptr, codes_ptr)
540
+ else:
541
+ # CPU torch
542
+ self.sa_encode_c(n, x_ptr, codes_ptr)
543
+
544
+ return codes
545
+
546
+ def torch_replacement_sa_decode(self, codes, x=None):
547
+ if type(codes) is np.ndarray:
548
+ # Forward to faiss __init__.py base method
549
+ return self.sa_decode_numpy(codes, x)
550
+
551
+ assert type(codes) is torch.Tensor
552
+ n, cs = codes.shape
553
+ assert cs == self.sa_code_size()
554
+ codes_ptr = swig_ptr_from_UInt8Tensor(codes)
555
+
556
+ if x is None:
557
+ x = torch.empty(n, self.d, dtype=torch.float32)
558
+ else:
559
+ assert type(x) is torch.Tensor
560
+ assert x.shape == (n, self.d)
561
+ x_ptr = swig_ptr_from_FloatTensor(x)
562
+
563
+ if codes.is_cuda:
564
+ assert hasattr(self, 'getDevice'), \
565
+ 'GPU tensor on CPU index not allowed'
566
+
567
+ # On the GPU, use proper stream ordering
568
+ with using_stream(self.getResources()):
569
+ self.sa_decode_c(n, codes_ptr, x_ptr)
570
+ else:
571
+ # CPU torch
572
+ self.sa_decode_c(n, codes_ptr, x_ptr)
573
+
574
+ return x
575
+
576
+ torch_replace_method(the_class, 'add', torch_replacement_add)
577
+ torch_replace_method(the_class, 'add_with_ids',
578
+ torch_replacement_add_with_ids)
579
+ torch_replace_method(the_class, 'assign', torch_replacement_assign)
580
+ torch_replace_method(the_class, 'train', torch_replacement_train)
581
+ torch_replace_method(the_class, 'search', torch_replacement_search)
582
+ torch_replace_method(the_class, 'remove_ids',
583
+ torch_replacement_remove_ids)
584
+ torch_replace_method(the_class, 'reconstruct',
585
+ torch_replacement_reconstruct)
586
+ torch_replace_method(the_class, 'reconstruct_n',
587
+ torch_replacement_reconstruct_n)
588
+ torch_replace_method(the_class, 'range_search',
589
+ torch_replacement_range_search)
590
+ torch_replace_method(the_class, 'update_vectors',
591
+ torch_replacement_update_vectors,
592
+ ignore_missing=True)
593
+ torch_replace_method(the_class, 'search_and_reconstruct',
594
+ torch_replacement_search_and_reconstruct,
595
+ ignore_missing=True)
596
+ torch_replace_method(the_class, 'search_preassigned',
597
+ torch_replacement_search_preassigned,
598
+ ignore_missing=True)
599
+ torch_replace_method(the_class, 'sa_encode', torch_replacement_sa_encode)
600
+ torch_replace_method(the_class, 'sa_decode', torch_replacement_sa_decode)
601
+
602
+
603
+ faiss_module = sys.modules['faiss']
604
+
605
+ # Re-patch anything that inherits from faiss.Index to add the torch bindings
606
+ for symbol in dir(faiss_module):
607
+ obj = getattr(faiss_module, symbol)
608
+ if inspect.isclass(obj):
609
+ the_class = obj
610
+ if issubclass(the_class, faiss.Index):
611
+ handle_torch_Index(the_class)
612
+
613
+
614
+ # allows torch tensor usage with knn
615
+ def torch_replacement_knn(xq, xb, k, metric=faiss.METRIC_L2, metric_arg=0):
616
+ if type(xb) is np.ndarray:
617
+ # Forward to faiss __init__.py base method
618
+ return faiss.knn_numpy(xq, xb, k, metric=metric,
619
+ metric_arg=metric_arg)
620
+
621
+ nb, d = xb.size()
622
+ assert xb.is_contiguous()
623
+ assert xb.dtype == torch.float32
624
+ assert not xb.is_cuda, "use knn_gpu for GPU tensors"
625
+
626
+ nq, d2 = xq.size()
627
+ assert d2 == d
628
+ assert xq.is_contiguous()
629
+ assert xq.dtype == torch.float32
630
+ assert not xq.is_cuda, "use knn_gpu for GPU tensors"
631
+
632
+ D = torch.empty(nq, k, device=xb.device, dtype=torch.float32)
633
+ I = torch.empty(nq, k, device=xb.device, dtype=torch.int64)
634
+ I_ptr = swig_ptr_from_IndicesTensor(I)
635
+ D_ptr = swig_ptr_from_FloatTensor(D)
636
+ xb_ptr = swig_ptr_from_FloatTensor(xb)
637
+ xq_ptr = swig_ptr_from_FloatTensor(xq)
638
+
639
+ if metric == faiss.METRIC_L2:
640
+ faiss.knn_L2sqr(
641
+ xq_ptr, xb_ptr,
642
+ d, nq, nb, k, D_ptr, I_ptr
643
+ )
644
+ elif metric == faiss.METRIC_INNER_PRODUCT:
645
+ faiss.knn_inner_product(
646
+ xq_ptr, xb_ptr,
647
+ d, nq, nb, k, D_ptr, I_ptr
648
+ )
649
+ else:
650
+ faiss.knn_extra_metrics(
651
+ xq_ptr, xb_ptr,
652
+ d, nq, nb, metric, metric_arg, k, D_ptr, I_ptr
653
+ )
654
+
655
+ return D, I
656
+
657
+
658
+ torch_replace_method(faiss_module, 'knn', torch_replacement_knn, True, True)
659
+
660
+
661
+ # allows torch tensor usage with bfKnn
662
+ def torch_replacement_knn_gpu(res, xq, xb, k, D=None, I=None,
663
+ metric=faiss.METRIC_L2, device=-1,
664
+ use_cuvs=False):
665
+ if type(xb) is np.ndarray:
666
+ # Forward to faiss __init__.py base method
667
+ return faiss.knn_gpu_numpy(res, xq, xb, k, D, I, metric, device)
668
+
669
+ nb, d = xb.size()
670
+ if xb.is_contiguous():
671
+ xb_row_major = True
672
+ elif xb.t().is_contiguous():
673
+ xb = xb.t()
674
+ xb_row_major = False
675
+ else:
676
+ raise TypeError('matrix should be row or column-major')
677
+
678
+ if xb.dtype == torch.float32:
679
+ xb_type = faiss.DistanceDataType_F32
680
+ xb_ptr = swig_ptr_from_FloatTensor(xb)
681
+ elif xb.dtype == torch.float16:
682
+ xb_type = faiss.DistanceDataType_F16
683
+ xb_ptr = swig_ptr_from_HalfTensor(xb)
684
+ elif xb.dtype == torch.bfloat16:
685
+ xb_type = faiss.DistanceDataType_BF16
686
+ xb_ptr = swig_ptr_from_BFloat16Tensor(xb)
687
+ else:
688
+ raise TypeError('xq must be float32, float16 or bfloat16')
689
+
690
+ nq, d2 = xq.size()
691
+ assert d2 == d
692
+ if xq.is_contiguous():
693
+ xq_row_major = True
694
+ elif xq.t().is_contiguous():
695
+ xq = xq.t()
696
+ xq_row_major = False
697
+ else:
698
+ raise TypeError('matrix should be row or column-major')
699
+
700
+ if xq.dtype == torch.float32:
701
+ xq_type = faiss.DistanceDataType_F32
702
+ xq_ptr = swig_ptr_from_FloatTensor(xq)
703
+ elif xq.dtype == torch.float16:
704
+ xq_type = faiss.DistanceDataType_F16
705
+ xq_ptr = swig_ptr_from_HalfTensor(xq)
706
+ elif xq.dtype == torch.bfloat16:
707
+ xq_type = faiss.DistanceDataType_BF16
708
+ xq_ptr = swig_ptr_from_BFloat16Tensor(xq)
709
+ else:
710
+ raise TypeError('xq must be float32, float16 or bfloat16')
711
+
712
+ if D is None:
713
+ D = torch.empty(nq, k, device=xb.device, dtype=torch.float32)
714
+ else:
715
+ assert D.shape == (nq, k)
716
+ # interface takes void*, we need to check this
717
+ assert (D.dtype == torch.float32)
718
+
719
+ if I is None:
720
+ I = torch.empty(nq, k, device=xb.device, dtype=torch.int64)
721
+ else:
722
+ assert I.shape == (nq, k)
723
+
724
+ if I.dtype == torch.int64:
725
+ I_type = faiss.IndicesDataType_I64
726
+ I_ptr = swig_ptr_from_IndicesTensor(I)
727
+ elif I.dtype == I.dtype == torch.int32:
728
+ I_type = faiss.IndicesDataType_I32
729
+ I_ptr = swig_ptr_from_IntTensor(I)
730
+ else:
731
+ raise TypeError('I must be i64 or i32')
732
+
733
+ D_ptr = swig_ptr_from_FloatTensor(D)
734
+
735
+ args = faiss.GpuDistanceParams()
736
+ args.metric = metric
737
+ args.k = k
738
+ args.dims = d
739
+ args.vectors = xb_ptr
740
+ args.vectorsRowMajor = xb_row_major
741
+ args.vectorType = xb_type
742
+ args.numVectors = nb
743
+ args.queries = xq_ptr
744
+ args.queriesRowMajor = xq_row_major
745
+ args.queryType = xq_type
746
+ args.numQueries = nq
747
+ args.outDistances = D_ptr
748
+ args.outIndices = I_ptr
749
+ args.outIndicesType = I_type
750
+ args.device = device
751
+ args.use_cuvs = use_cuvs
752
+
753
+ with using_stream(res):
754
+ faiss.bfKnn(res, args)
755
+
756
+ return D, I
757
+
758
+
759
+ torch_replace_method(faiss_module, 'knn_gpu', torch_replacement_knn_gpu,
760
+ True, True)
761
+
762
+
763
+ # allows torch tensor usage with bfKnn for all pairwise distances
764
+ def torch_replacement_pairwise_distance_gpu(res, xq, xb, D=None,
765
+ metric=faiss.METRIC_L2,
766
+ device=-1):
767
+ if type(xb) is np.ndarray:
768
+ # Forward to faiss __init__.py base method
769
+ return faiss.pairwise_distance_gpu_numpy(res, xq, xb, D, metric)
770
+
771
+ nb, d = xb.size()
772
+ if xb.is_contiguous():
773
+ xb_row_major = True
774
+ elif xb.t().is_contiguous():
775
+ xb = xb.t()
776
+ xb_row_major = False
777
+ else:
778
+ raise TypeError('xb matrix should be row or column-major')
779
+
780
+ if xb.dtype == torch.float32:
781
+ xb_type = faiss.DistanceDataType_F32
782
+ xb_ptr = swig_ptr_from_FloatTensor(xb)
783
+ elif xb.dtype == torch.float16:
784
+ xb_type = faiss.DistanceDataType_F16
785
+ xb_ptr = swig_ptr_from_HalfTensor(xb)
786
+ else:
787
+ raise TypeError('xb must be float32 or float16')
788
+
789
+ nq, d2 = xq.size()
790
+ assert d2 == d
791
+ if xq.is_contiguous():
792
+ xq_row_major = True
793
+ elif xq.t().is_contiguous():
794
+ xq = xq.t()
795
+ xq_row_major = False
796
+ else:
797
+ raise TypeError('xq matrix should be row or column-major')
798
+
799
+ if xq.dtype == torch.float32:
800
+ xq_type = faiss.DistanceDataType_F32
801
+ xq_ptr = swig_ptr_from_FloatTensor(xq)
802
+ elif xq.dtype == torch.float16:
803
+ xq_type = faiss.DistanceDataType_F16
804
+ xq_ptr = swig_ptr_from_HalfTensor(xq)
805
+ else:
806
+ raise TypeError('xq must be float32 or float16')
807
+
808
+ if D is None:
809
+ D = torch.empty(nq, nb, device=xb.device, dtype=torch.float32)
810
+ else:
811
+ assert D.shape == (nq, nb)
812
+ # interface takes void*, we need to check this
813
+ assert (D.dtype == torch.float32)
814
+
815
+ D_ptr = swig_ptr_from_FloatTensor(D)
816
+
817
+ args = faiss.GpuDistanceParams()
818
+ args.metric = metric
819
+ args.k = -1 # selects all pairwise distance
820
+ args.dims = d
821
+ args.vectors = xb_ptr
822
+ args.vectorsRowMajor = xb_row_major
823
+ args.vectorType = xb_type
824
+ args.numVectors = nb
825
+ args.queries = xq_ptr
826
+ args.queriesRowMajor = xq_row_major
827
+ args.queryType = xq_type
828
+ args.numQueries = nq
829
+ args.outDistances = D_ptr
830
+ args.device = device
831
+
832
+ with using_stream(res):
833
+ faiss.bfKnn(res, args)
834
+
835
+ return D
836
+
837
+
838
+ torch_replace_method(faiss_module, 'pairwise_distance_gpu',
839
+ torch_replacement_pairwise_distance_gpu, True, True)
ScaleDF_rebuttal/python_dedup_pkgs/faiss/contrib/vecs_io.py ADDED
@@ -0,0 +1,178 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ #
3
+ # This source code is licensed under the MIT license found in the
4
+ # LICENSE file in the root directory of this source tree.
5
+
6
+ import sys
7
+ import numpy as np
8
+ import os
9
+
10
+ """
11
+ I/O functions in fvecs, bvecs, ivecs formats
12
+ definition of the formats here: http://corpus-texmex.irisa.fr/
13
+ """
14
+
15
+
16
+ def ivecs_read(fname):
17
+ a = np.fromfile(fname, dtype='int32')
18
+ if sys.byteorder == 'big':
19
+ a.byteswap(inplace=True)
20
+ d = a[0]
21
+ return a.reshape(-1, d + 1)[:, 1:].copy()
22
+
23
+
24
+ def fvecs_read(fname):
25
+ return ivecs_read(fname).view('float32')
26
+
27
+
28
+ def ivecs_mmap(fname):
29
+ assert sys.byteorder != 'big'
30
+ a = np.memmap(fname, dtype='int32', mode='r')
31
+ d = a[0]
32
+ return a.reshape(-1, d + 1)[:, 1:]
33
+
34
+
35
+ def fvecs_mmap(fname):
36
+ return ivecs_mmap(fname).view('float32')
37
+
38
+
39
+ def bvecs_mmap(fname):
40
+ x = np.memmap(fname, dtype='uint8', mode='r')
41
+ if sys.byteorder == 'big':
42
+ da = x[:4][::-1].copy()
43
+ d = da.view('int32')[0]
44
+ else:
45
+ d = x[:4].view('int32')[0]
46
+ return x.reshape(-1, d + 4)[:, 4:]
47
+
48
+
49
+ def ivecs_write(fname, m):
50
+ n, d = m.shape
51
+ m1 = np.empty((n, d + 1), dtype='int32')
52
+ m1[:, 0] = d
53
+ m1[:, 1:] = m
54
+ if sys.byteorder == 'big':
55
+ m1.byteswap(inplace=True)
56
+ m1.tofile(fname)
57
+
58
+
59
+ def fvecs_write(fname, m):
60
+ m = m.astype('float32')
61
+ ivecs_write(fname, m.view('int32'))
62
+
63
+ def bvecs_iter(filepath, batch_size=100_000):
64
+ """
65
+ Memory-mapped iterator - only loads requested slices into RAM
66
+ """
67
+
68
+ file_size = os.path.getsize(filepath)
69
+ with open(filepath, 'rb') as f:
70
+ dim = np.frombuffer(f.read(4), dtype='<i4')[0]
71
+
72
+ bytes_per_vec = 4 + dim
73
+ n_vectors = file_size // bytes_per_vec
74
+
75
+ mm = np.memmap(filepath, mode='r', dtype=np.uint8)
76
+ records = mm.reshape(n_vectors, bytes_per_vec)
77
+
78
+ for start in range(0, n_vectors, batch_size):
79
+ end = np.min([start + batch_size, n_vectors])
80
+ yield records[start:end, 4:]
81
+
82
+ def bvecs_iter_chunked(chunk_folder, batch_size=100_000):
83
+ """
84
+ Memory-mapped iterator over chunked .bvecs files.
85
+ Iterates through all chunk files in order (chunk_0000.bvecs, chunk_0001.bvecs, etc.)
86
+ and yields batches of vectors, handling cases where batches span multiple files.
87
+
88
+ Args:
89
+ chunk_folder: path to folder containing chunk_XXXX.bvecs files
90
+ batch_size: number of vectors to yield per batch
91
+
92
+ Yields:
93
+ numpy array of shape (batch_size, d) or smaller for last batch
94
+
95
+ Raises:
96
+ ValueError: if there are gaps in the chunk sequence
97
+ """
98
+
99
+ # Find all chunk files and sort them
100
+ chunk_files = []
101
+ for entry in os.scandir(chunk_folder):
102
+ if entry.is_file() and entry.name.startswith("chunk_") and entry.name.endswith(".bvecs"):
103
+ chunk_files.append(entry.path)
104
+ chunk_files.sort()
105
+
106
+ if not chunk_files:
107
+ raise ValueError(f"No chunk files found in {chunk_folder}")
108
+
109
+ # Extract chunk numbers and verify no gaps
110
+ chunk_numbers = []
111
+ for path in chunk_files:
112
+ basename = os.path.basename(path)
113
+ try:
114
+ num_str = basename.split('_')[1].split('.')[0]
115
+ chunk_numbers.append(int(num_str))
116
+ except (IndexError, ValueError):
117
+ raise ValueError(f"Invalid chunk filename format: {basename}")
118
+
119
+ # Check for gaps in sequence
120
+ expected_chunks = list(range(len(chunk_numbers)))
121
+ if sorted(chunk_numbers) != expected_chunks:
122
+ missing = set(expected_chunks) - set(chunk_numbers)
123
+ raise ValueError(
124
+ f"Gap detected in chunk sequence! Missing chunks: {sorted(missing)}\n"
125
+ f"Found chunks: {sorted(chunk_numbers)}\n"
126
+ f"Expected continuous sequence from 0 to {len(chunk_numbers)-1}"
127
+ )
128
+
129
+ # Get dimension from first chunk
130
+ with open(chunk_files[0], 'rb') as f:
131
+ dim = np.frombuffer(f.read(4), dtype='<i4')[0]
132
+
133
+ bytes_per_vec = 4 + dim
134
+
135
+ # Buffer to accumulate vectors across chunk boundaries
136
+ buffer = None
137
+ buffer_size = 0
138
+
139
+ # Iterate through each chunk file
140
+ for chunk_path in chunk_files:
141
+ file_size = os.path.getsize(chunk_path)
142
+ n_vectors = file_size // bytes_per_vec
143
+
144
+ # Memory-map this chunk
145
+ mm = np.memmap(chunk_path, mode='r', dtype=np.uint8)
146
+ records = mm.reshape(n_vectors, bytes_per_vec)
147
+ vectors = records[:, 4:] # Skip dimension prefix
148
+
149
+ start = 0
150
+
151
+ # First, handle any buffered data from previous chunk
152
+ if buffer is not None:
153
+ needed = batch_size - buffer_size
154
+ if needed <= n_vectors:
155
+ # Can complete the buffered batch with this chunk
156
+ batch = np.vstack([buffer, vectors[:needed]])
157
+ yield batch
158
+ buffer = None
159
+ buffer_size = 0
160
+ start = needed
161
+ else:
162
+ # Still not enough, accumulate and continue to next chunk
163
+ buffer = np.vstack([buffer, vectors])
164
+ buffer_size += n_vectors
165
+ continue
166
+
167
+ # Now process complete batches from this chunk
168
+ while start + batch_size <= n_vectors:
169
+ yield vectors[start:start + batch_size]
170
+ start += batch_size
171
+
172
+ remainder = n_vectors - start
173
+ if remainder > 0:
174
+ buffer = vectors[start:].copy()
175
+ buffer_size = remainder
176
+
177
+ if buffer is not None:
178
+ yield buffer
ScaleDF_rebuttal/python_dedup_pkgs/faiss_cpu-1.14.3.dist-info/INSTALLER ADDED
@@ -0,0 +1 @@
 
 
1
+ pip
ScaleDF_rebuttal/python_dedup_pkgs/faiss_cpu-1.14.3.dist-info/METADATA ADDED
@@ -0,0 +1,124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Metadata-Version: 2.4
2
+ Name: faiss-cpu
3
+ Version: 1.14.3
4
+ Summary: A library for efficient similarity search and clustering of dense vectors.
5
+ Keywords: search,nearest-neighbors,clustering,vectors,similarity
6
+ Author: Meta AI Research
7
+ License-Expression: MIT
8
+ License-File: LICENSE
9
+ License-File: THIRD_PARTY_NOTICES
10
+ Classifier: Development Status :: 5 - Production/Stable
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: Intended Audience :: Science/Research
13
+ Classifier: Operating System :: MacOS :: MacOS X
14
+ Classifier: Operating System :: Microsoft :: Windows
15
+ Classifier: Operating System :: POSIX :: Linux
16
+ Classifier: Programming Language :: C++
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Programming Language :: Python :: 3.10
19
+ Classifier: Programming Language :: Python :: 3.11
20
+ Classifier: Programming Language :: Python :: 3.12
21
+ Classifier: Programming Language :: Python :: 3.13
22
+ Classifier: Programming Language :: Python :: 3.14
23
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
24
+ Project-URL: Homepage, https://github.com/facebookresearch/faiss
25
+ Project-URL: Documentation, https://github.com/facebookresearch/faiss/wiki
26
+ Project-URL: Repository, https://github.com/facebookresearch/faiss
27
+ Project-URL: Issues, https://github.com/facebookresearch/faiss/issues
28
+ Requires-Python: >=3.10
29
+ Requires-Dist: numpy>=1.25
30
+ Requires-Dist: packaging
31
+ Description-Content-Type: text/markdown
32
+
33
+ # Faiss
34
+
35
+ Faiss is a library for efficient similarity search and clustering of dense vectors. It contains algorithms that search in sets of vectors of any size, up to ones that possibly do not fit in RAM. It also contains supporting code for evaluation and parameter tuning. Faiss is written in C++ with complete wrappers for Python/numpy. Some of the most useful algorithms are implemented on the GPU. It is developed primarily at Meta's [Fundamental AI Research](https://ai.facebook.com/) group.
36
+
37
+ ## News
38
+
39
+ See [CHANGELOG.md](CHANGELOG.md) for detailed information about latest features.
40
+
41
+ ## Introduction
42
+
43
+ Faiss contains several methods for similarity search. It assumes that the instances are represented as vectors and are identified by an integer, and that the vectors can be compared with L2 (Euclidean) distances or dot products. Vectors that are similar to a query vector are those that have the lowest L2 distance or the highest dot product with the query vector. It also supports cosine similarity, since this is a dot product on normalized vectors.
44
+
45
+ Some of the methods, like those based on binary vectors and compact quantization codes, solely use a compressed representation of the vectors and do not require to keep the original vectors. This generally comes at the cost of a less precise search but these methods can scale to billions of vectors in main memory on a single server. Other methods, like HNSW and NSG add an indexing structure on top of the raw vectors to make searching more efficient.
46
+
47
+ The GPU implementation can accept input from either CPU or GPU memory. On a server with GPUs, the GPU indexes can be used a drop-in replacement for the CPU indexes (e.g., replace `IndexFlatL2` with `GpuIndexFlatL2`) and copies to/from GPU memory are handled automatically. Results will be faster however if both input and output remain resident on the GPU. Both single and multi-GPU usage is supported.
48
+
49
+ ## Installing
50
+
51
+ Faiss comes with precompiled libraries for Anaconda in Python, see [faiss-cpu](https://anaconda.org/pytorch/faiss-cpu), [faiss-gpu](https://anaconda.org/pytorch/faiss-gpu) and [faiss-gpu-cuvs](https://anaconda.org/pytorch/faiss-gpu-cuvs). The library is mostly implemented in C++, the only dependency is a [BLAS](https://en.wikipedia.org/wiki/Basic_Linear_Algebra_Subprograms) implementation. Optional GPU support is provided via CUDA or AMD ROCm, and the Python interface is also optional. The backend GPU implementations of NVIDIA [cuVS](https://github.com/rapidsai/cuvs) can also be enabled optionally. It compiles with cmake. See [INSTALL.md](INSTALL.md) for details.
52
+
53
+ ## How Faiss works
54
+
55
+ Faiss is built around an index type that stores a set of vectors, and provides a function to search in them with L2 and/or dot product vector comparison. Some index types are simple baselines, such as exact search. Most of the available indexing structures correspond to various trade-offs with respect to
56
+
57
+ - search time
58
+ - search quality
59
+ - memory used per index vector
60
+ - training time
61
+ - adding time
62
+ - need for external data for unsupervised training
63
+
64
+ The optional GPU implementation provides what is likely (as of March 2017) the fastest exact and approximate (compressed-domain) nearest neighbor search implementation for high-dimensional vectors, fastest Lloyd's k-means, and fastest small k-selection algorithm known. [The implementation is detailed here](https://arxiv.org/abs/1702.08734).
65
+
66
+ ## Full documentation of Faiss
67
+
68
+ The following are entry points for documentation:
69
+
70
+ - the full documentation can be found on the [wiki page](https://github.com/facebookresearch/faiss/wiki), including a [tutorial](https://github.com/facebookresearch/faiss/wiki/Getting-started), a [FAQ](https://github.com/facebookresearch/faiss/wiki/FAQ) and a [troubleshooting section](https://github.com/facebookresearch/faiss/wiki/Troubleshooting)
71
+ - the [doxygen documentation](https://faiss.ai/) gives per-class information extracted from code comments
72
+ - to reproduce results from our research papers, [Polysemous codes](https://arxiv.org/abs/1609.01882) and [Billion-scale similarity search with GPUs](https://arxiv.org/abs/1702.08734), refer to the [benchmarks README](benchs/README.md). For [
73
+ Link and code: Fast indexing with graphs and compact regression codes](https://arxiv.org/abs/1804.09996), see the [link_and_code README](benchs/link_and_code)
74
+
75
+ ## Authors
76
+
77
+ The main authors of Faiss are:
78
+ - [Hervé Jégou](https://github.com/jegou) initiated the Faiss project and wrote its first implementation
79
+ - [Matthijs Douze](https://github.com/mdouze) implemented most of the CPU Faiss
80
+ - [Jeff Johnson](https://github.com/wickedfoo) implemented all of the GPU Faiss
81
+ - [Lucas Hosseini](https://github.com/beauby) implemented the binary indexes and the build system
82
+ - [Chengqi Deng](https://github.com/KinglittleQ) implemented NSG, NNdescent and much of the additive quantization code.
83
+ - [Alexandr Guzhva](https://github.com/alexanderguzhva) many optimizations: SIMD, memory allocation and layout, fast decoding kernels for vector codecs, etc.
84
+ - [Gergely Szilvasy](https://github.com/algoriddle) build system, benchmarking framework.
85
+
86
+ ## Reference
87
+
88
+ References to cite when you use Faiss in a research paper:
89
+ ```
90
+ @article{douze2024faiss,
91
+ title={The Faiss library},
92
+ author={Matthijs Douze and Alexandr Guzhva and Chengqi Deng and Jeff Johnson and Gergely Szilvasy and Pierre-Emmanuel Mazaré and Maria Lomeli and Lucas Hosseini and Hervé Jégou},
93
+ year={2024},
94
+ eprint={2401.08281},
95
+ archivePrefix={arXiv},
96
+ primaryClass={cs.LG}
97
+ }
98
+ ```
99
+ For the GPU version of Faiss, please cite:
100
+ ```
101
+ @article{johnson2019billion,
102
+ title={Billion-scale similarity search with {GPUs}},
103
+ author={Johnson, Jeff and Douze, Matthijs and J{\'e}gou, Herv{\'e}},
104
+ journal={IEEE Transactions on Big Data},
105
+ volume={7},
106
+ number={3},
107
+ pages={535--547},
108
+ year={2019},
109
+ publisher={IEEE}
110
+ }
111
+ ```
112
+
113
+ ## Join the Faiss community
114
+
115
+ For public discussion of Faiss or for questions, visit https://github.com/facebookresearch/faiss/discussions.
116
+
117
+ We monitor the [issues page](https://github.com/facebookresearch/faiss/issues) of the repository.
118
+ You can report bugs, ask questions, etc.
119
+
120
+ ## Legal
121
+
122
+ Faiss is MIT-licensed, refer to the [LICENSE file](https://github.com/facebookresearch/faiss/blob/main/LICENSE) in the top level directory.
123
+
124
+ Copyright © Meta Platforms, Inc.
ScaleDF_rebuttal/python_dedup_pkgs/faiss_cpu-1.14.3.dist-info/RECORD ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ faiss/__init__.py,sha256=b00ZjZQxoVaB7xSs7F-LGsdjjpKoNf-6TsebbVdb2eg,15852
2
+ faiss/__init__.pyi,sha256=Qa7WJ9DBTMqTbEGT6Q_ApUJvA5IjOtNv9e0L3Wk5XJk,141474
3
+ faiss/_swigfaiss.abi3.so,sha256=c3Fu7gF59JHuTlypqXQKitDt_GN4jqSEnUUdkR45hVo,6343033
4
+ faiss/array_conversions.py,sha256=R2aNQIs0QXl8c4QBokiHqQYSFLHyAnJUjKHJOT2-JaQ,5779
5
+ faiss/class_wrappers.py,sha256=06l2Oj2PCRMRq6vsIf-TK4s59ZxgpJPjBAz9kVMSTVg,54471
6
+ faiss/extra_wrappers.py,sha256=LdmUnKqOIxK89l3fZV-9xKm0QV5aKKvcIpB5GhaOZyk,23168
7
+ faiss/gpu_wrappers.py,sha256=r2XcE_WO_URnFVq01zPgHbyKhfRHFvlw7nlX6-eObc8,9196
8
+ faiss/libfaiss.so,sha256=_M_GSE9kRb5W7XeuoTTflfnOXkziJVGg93MCKEJGn6w,15322617
9
+ faiss/loader.py,sha256=aruLX7CmBXVYo_f-gfIOmXB0cI8s7PQwENS1dQik0z8,8035
10
+ faiss/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
11
+ faiss/swigfaiss.py,sha256=dRj4m2PtNonWhEus0TuoGDXj4y5b8aKxrXnRNlubeu4,650107
12
+ faiss/contrib/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
13
+ faiss/contrib/big_batch_search.py,sha256=Z8jiHtXx_ZjZEd9_0AImuPC2RT_SEjuYv_-0SoQ9FJE,17640
14
+ faiss/contrib/client_server.py,sha256=kuqPNWADtVbR-0U_1Yf1YaJFZaDUaIM71Cb1PszEWSE,2773
15
+ faiss/contrib/clustering.py,sha256=gOh1qLvHeg9sCpj560xf9pDHmjT6kxXNffKi4xFtCSU,15679
16
+ faiss/contrib/datasets.py,sha256=-Y-bgYXkyFCOar-YI3hJYnK0EuLVd3lTCaD8XU9p5Kc,16414
17
+ faiss/contrib/evaluation.py,sha256=lcMt-xWrqjSMFpc7obmI9NAFu0fl1vEsvpUU0tCSsk0,15002
18
+ faiss/contrib/exhaustive_search.py,sha256=aZ9tgA3WswNcu0ORCl_Yj_RcN2qxgWbtc9W8_SyWKvM,12381
19
+ faiss/contrib/factory_tools.py,sha256=s3psIASX0ssAEs4POdkna-1i8eFXakvn8zLLHJTnOJg,5379
20
+ faiss/contrib/inspect_tools.py,sha256=adznxU6EFhVrBXuyyol5M-j5baUVlhJCOoz7cFDFVdQ,3749
21
+ faiss/contrib/ivf_tools.py,sha256=L8zIjlLqjE630RGxv-iGmS9Map4ZarFmoP4mUCnAJBE,4874
22
+ faiss/contrib/ondisk.py,sha256=o75LX2UDSVb0WaKWHKVwfVoXXmIGt-qblIMaVP3VRYQ,2069
23
+ faiss/contrib/rpc.py,sha256=2uTBaGGf6dueh7yTbb1L30UoJMNC0zVXPFV2liiwUfE,7310
24
+ faiss/contrib/torch_utils.py,sha256=Ni6cI29oEfW1ntjnIa-HG6CXwu8rhEO_FQ4sbEh4j58,29177
25
+ faiss/contrib/vecs_io.py,sha256=hp1_SwLOEOZAWr2igEa6qJyVm2ZXuIf_gx6DTd5muSM,5439
26
+ faiss/contrib/torch/README.md,sha256=cSZmWcQwJOW9UNYrLAUwW3QoIFwqlLTpVK_HL-Aekr8,212
27
+ faiss/contrib/torch/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
28
+ faiss/contrib/torch/clustering.py,sha256=CtM1XCSTgexM4-iCD1GXw9AWmZR1WWzMLWOy2tobz_4,1676
29
+ faiss/contrib/torch/quantization.py,sha256=eAzTe4Dg4njItfe7VfKvtCwtfO5_Jfo_HS9RpE0DC74,2797
30
+ faiss_cpu.libs/libgfortran-83c28eba.so.5.0.0,sha256=5VSHn-5-2oAFW2yhQHpU0ABQh0-DDMhrK_P1DfXHuys,2714697
31
+ faiss_cpu.libs/libgomp-e985bcbb.so.1.0.0,sha256=pDkE5PopcwHUZA3BuzyKNIC0BvmeSY66mxkUtoqrYEo,253289
32
+ faiss_cpu.libs/libopenblaso-r0-d77a1985.3.15.so,sha256=ODWntDKwTBPEY68sZaphbuv3_ALK3KJa1SJ9yvhG0uw,38700273
33
+ faiss_cpu.libs/libquadmath-2284e583.so.0.0.0,sha256=qTB7uqNTYj-gFOi2gtUMRin15cfWHaqahlL30WXNQho,272193
34
+ faiss_cpu-1.14.3.dist-info/METADATA,sha256=5o0tgI7S2gtoacVv52c5bKF3UN9RhU2jkxnDJ5lY9Fs,7785
35
+ faiss_cpu-1.14.3.dist-info/WHEEL,sha256=hg7z7Me-dEZ0SHvjjdyugRyBrl5j-HfyAzvrIFMX014,155
36
+ faiss_cpu-1.14.3.dist-info/RECORD,,
37
+ faiss_cpu-1.14.3.dist-info/licenses/LICENSE,sha256=UkEte8fOQVfqYou6rLiCngqcs8WPV_mRdhJryM8r_IU,1086
38
+ faiss_cpu-1.14.3.dist-info/licenses/THIRD_PARTY_NOTICES,sha256=sHUkrWqCLt2GvR1HA6vIz9_pNBiGcNn1wslmdvVU5As,21831
39
+ faiss_cpu-1.14.3.dist-info/sboms/auditwheel.cdx.json,sha256=fdent5LcjB8z3IpmKXMP5atwaxuOABYIbnobNwLX7Bk,3003
ScaleDF_rebuttal/python_dedup_pkgs/faiss_cpu-1.14.3.dist-info/REQUESTED ADDED
File without changes
ScaleDF_rebuttal/python_dedup_pkgs/faiss_cpu-1.14.3.dist-info/WHEEL ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ Wheel-Version: 1.0
2
+ Generator: scikit-build-core 0.12.2
3
+ Root-Is-Purelib: false
4
+ Tag: cp310-abi3-manylinux_2_27_x86_64
5
+ Tag: cp310-abi3-manylinux_2_28_x86_64
6
+
ScaleDF_rebuttal/python_dedup_pkgs/faiss_cpu-1.14.3.dist-info/licenses/LICENSE ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) Facebook, Inc. and its affiliates.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
ScaleDF_rebuttal/python_dedup_pkgs/faiss_cpu-1.14.3.dist-info/licenses/THIRD_PARTY_NOTICES ADDED
@@ -0,0 +1,410 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Third-Party Notices for faiss pip wheels
2
+ ========================================
3
+
4
+ The faiss pip wheels bundle the following third-party libraries as binary
5
+ dependencies. Their licenses are reproduced below.
6
+
7
+
8
+ 1. OpenBLAS (Linux, Windows wheels)
9
+ -------------------------------------------
10
+
11
+ Copyright (c) 2011-2014, The OpenBLAS Project
12
+ All rights reserved.
13
+
14
+ Redistribution and use in source and binary forms, with or without
15
+ modification, are permitted provided that the following conditions are
16
+ met:
17
+
18
+ 1. Redistributions of source code must retain the above copyright
19
+ notice, this list of conditions and the following disclaimer.
20
+
21
+ 2. Redistributions in binary form must reproduce the above copyright
22
+ notice, this list of conditions and the following disclaimer in
23
+ the documentation and/or other materials provided with the
24
+ distribution.
25
+ 3. Neither the name of the OpenBLAS project nor the names of
26
+ its contributors may be used to endorse or promote products
27
+ derived from this software without specific prior written
28
+ permission.
29
+
30
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
31
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
32
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
33
+ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
34
+ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
35
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
36
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
37
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
38
+ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
39
+ USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
40
+
41
+ License: BSD-3-Clause
42
+ Source: https://github.com/OpenMathLib/OpenBLAS
43
+
44
+
45
+ 2. LLVM OpenMP Runtime (libomp) (macOS wheels)
46
+ -----------------------------------------------
47
+
48
+ ==============================================================================
49
+ The LLVM Project is under the Apache License v2.0 with LLVM Exceptions:
50
+ ==============================================================================
51
+
52
+ Apache License
53
+ Version 2.0, January 2004
54
+ http://www.apache.org/licenses/
55
+
56
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
57
+
58
+ 1. Definitions.
59
+
60
+ "License" shall mean the terms and conditions for use, reproduction,
61
+ and distribution as defined by Sections 1 through 9 of this document.
62
+
63
+ "Licensor" shall mean the copyright owner or entity authorized by
64
+ the copyright owner that is granting the License.
65
+
66
+ "Legal Entity" shall mean the union of the acting entity and all
67
+ other entities that control, are controlled by, or are under common
68
+ control with that entity. For the purposes of this definition,
69
+ "control" means (i) the power, direct or indirect, to cause the
70
+ direction or management of such entity, whether by contract or
71
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
72
+ outstanding shares, or (iii) beneficial ownership of such entity.
73
+
74
+ "You" (or "Your") shall mean an individual or Legal Entity
75
+ exercising permissions granted by this License.
76
+
77
+ "Source" form shall mean the preferred form for making modifications,
78
+ including but not limited to software source code, documentation
79
+ source, and configuration files.
80
+
81
+ "Object" form shall mean any form resulting from mechanical
82
+ transformation or translation of a Source form, including but
83
+ not limited to compiled object code, generated documentation,
84
+ and conversions to other media types.
85
+
86
+ "Work" shall mean the work of authorship, whether in Source or
87
+ Object form, made available under the License, as indicated by a
88
+ copyright notice that is included in or attached to the work
89
+ (an example is provided in the Appendix below).
90
+
91
+ "Derivative Works" shall mean any work, whether in Source or Object
92
+ form, that is based on (or derived from) the Work and for which the
93
+ editorial revisions, annotations, elaborations, or other modifications
94
+ represent, as a whole, an original work of authorship. For the purposes
95
+ of this License, Derivative Works shall not include works that remain
96
+ separable from, or merely link (or bind by name) to the interfaces of,
97
+ the Work and Derivative Works thereof.
98
+
99
+ "Contribution" shall mean any work of authorship, including
100
+ the original version of the Work and any modifications or additions
101
+ to that Work or Derivative Works thereof, that is intentionally
102
+ submitted to Licensor for inclusion in the Work by the copyright owner
103
+ or by an individual or Legal Entity authorized to submit on behalf of
104
+ the copyright owner. For the purposes of this definition, "submitted"
105
+ means any form of electronic, verbal, or written communication sent
106
+ to the Licensor or its representatives, including but not limited to
107
+ communication on electronic mailing lists, source code control systems,
108
+ and issue tracking systems that are managed by, or on behalf of, the
109
+ Licensor for the purpose of discussing and improving the Work, but
110
+ excluding communication that is conspicuously marked or otherwise
111
+ designated in writing by the copyright owner as "Not a Contribution."
112
+
113
+ "Contributor" shall mean Licensor and any individual or Legal Entity
114
+ on behalf of whom a Contribution has been received by Licensor and
115
+ subsequently incorporated within the Work.
116
+
117
+ 2. Grant of Copyright License. Subject to the terms and conditions of
118
+ this License, each Contributor hereby grants to You a perpetual,
119
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
120
+ copyright license to reproduce, prepare Derivative Works of,
121
+ publicly display, publicly perform, sublicense, and distribute the
122
+ Work and such Derivative Works in Source or Object form.
123
+
124
+ 3. Grant of Patent License. Subject to the terms and conditions of
125
+ this License, each Contributor hereby grants to You a perpetual,
126
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
127
+ (except as stated in this section) patent license to make, have made,
128
+ use, offer to sell, sell, import, and otherwise transfer the Work,
129
+ where such license applies only to those patent claims licensable
130
+ by such Contributor that are necessarily infringed by their
131
+ Contribution(s) alone or by combination of their Contribution(s)
132
+ with the Work to which such Contribution(s) was submitted. If You
133
+ institute patent litigation against any entity (including a
134
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
135
+ or a Contribution incorporated within the Work constitutes direct
136
+ or contributory patent infringement, then any patent licenses
137
+ granted to You under this License for that Work shall terminate
138
+ as of the date such litigation is filed.
139
+
140
+ 4. Redistribution. You may reproduce and distribute copies of the
141
+ Work or Derivative Works thereof in any medium, with or without
142
+ modifications, and in Source or Object form, provided that You
143
+ meet the following conditions:
144
+
145
+ (a) You must give any other recipients of the Work or
146
+ Derivative Works a copy of this License; and
147
+
148
+ (b) You must cause any modified files to carry prominent notices
149
+ stating that You changed the files; and
150
+
151
+ (c) You must retain, in the Source form of any Derivative Works
152
+ that You distribute, all copyright, patent, trademark, and
153
+ attribution notices from the Source form of the Work,
154
+ excluding those notices that do not pertain to any part of
155
+ the Derivative Works; and
156
+
157
+ (d) If the Work includes a "NOTICE" text file as part of its
158
+ distribution, then any Derivative Works that You distribute must
159
+ include a readable copy of the attribution notices contained
160
+ within such NOTICE file, excluding those notices that do not
161
+ pertain to any part of the Derivative Works, in at least one
162
+ of the following places: within a NOTICE text file distributed
163
+ as part of the Derivative Works; within the Source form or
164
+ documentation, if provided along with the Derivative Works; or,
165
+ within a display generated by the Derivative Works, if and
166
+ wherever such third-party notices normally appear. The contents
167
+ of the NOTICE file are for informational purposes only and
168
+ do not modify the License. You may add Your own attribution
169
+ notices within Derivative Works that You distribute, alongside
170
+ or as an addendum to the NOTICE text from the Work, provided
171
+ that such additional attribution notices cannot be construed
172
+ as modifying the License.
173
+
174
+ You may add Your own copyright statement to Your modifications and
175
+ may provide additional or different license terms and conditions
176
+ for use, reproduction, or distribution of Your modifications, or
177
+ for any such Derivative Works as a whole, provided Your use,
178
+ reproduction, and distribution of the Work otherwise complies with
179
+ the conditions stated in this License.
180
+
181
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
182
+ any Contribution intentionally submitted for inclusion in the Work
183
+ by You to the Licensor shall be under the terms and conditions of
184
+ this License, without any additional terms or conditions.
185
+ Notwithstanding the above, nothing herein shall supersede or modify
186
+ the terms of any separate license agreement you may have executed
187
+ with Licensor regarding such Contributions.
188
+
189
+ 6. Trademarks. This License does not grant permission to use the trade
190
+ names, trademarks, service marks, or product names of the Licensor,
191
+ except as required for reasonable and customary use in describing the
192
+ origin of the Work and reproducing the content of the NOTICE file.
193
+
194
+ 7. Disclaimer of Warranty. Unless required by applicable law or
195
+ agreed to in writing, Licensor provides the Work (and each
196
+ Contributor provides its Contributions) on an "AS IS" BASIS,
197
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
198
+ implied, including, without limitation, any warranties or conditions
199
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
200
+ PARTICULAR PURPOSE. You are solely responsible for determining the
201
+ appropriateness of using or redistributing the Work and assume any
202
+ risks associated with Your exercise of permissions under this License.
203
+
204
+ 8. Limitation of Liability. In no event and under no legal theory,
205
+ whether in tort (including negligence), contract, or otherwise,
206
+ unless required by applicable law (such as deliberate and grossly
207
+ negligent acts) or agreed to in writing, shall any Contributor be
208
+ liable to You for damages, including any direct, indirect, special,
209
+ incidental, or consequential damages of any character arising as a
210
+ result of this License or out of the use or inability to use the
211
+ Work (including but not limited to damages for loss of goodwill,
212
+ work stoppage, computer failure or malfunction, or any and all
213
+ other commercial damages or losses), even if such Contributor
214
+ has been advised of the possibility of such damages.
215
+
216
+ 9. Accepting Warranty or Additional Liability. While redistributing
217
+ the Work or Derivative Works thereof, You may choose to offer,
218
+ and charge a fee for, acceptance of support, warranty, indemnity,
219
+ or other liability obligations and/or rights consistent with this
220
+ License. However, in accepting such obligations, You may act only
221
+ on Your own behalf and on Your sole responsibility, not on behalf
222
+ of any other Contributor, and only if You agree to indemnify,
223
+ defend, and hold each Contributor harmless for any liability
224
+ incurred by, or claims asserted against, such Contributor by reason
225
+ of your accepting any such warranty or additional liability.
226
+
227
+ END OF TERMS AND CONDITIONS
228
+
229
+ APPENDIX: How to apply the Apache License to your work.
230
+
231
+ To apply the Apache License to your work, attach the following
232
+ boilerplate notice, with the fields enclosed by brackets "[]"
233
+ replaced with your own identifying information. (Don't include
234
+ the brackets!) The text should be enclosed in the appropriate
235
+ comment syntax for the file format. We also recommend that a
236
+ file or class name and description of purpose be included on the
237
+ same "printed page" as the copyright notice for easier
238
+ identification within third-party archives.
239
+
240
+ Copyright [yyyy] [name of copyright owner]
241
+
242
+ Licensed under the Apache License, Version 2.0 (the "License");
243
+ you may not use this file except in compliance with the License.
244
+ You may obtain a copy of the License at
245
+
246
+ http://www.apache.org/licenses/LICENSE-2.0
247
+
248
+ Unless required by applicable law or agreed to in writing, software
249
+ distributed under the License is distributed on an "AS IS" BASIS,
250
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
251
+ See the License for the specific language governing permissions and
252
+ limitations under the License.
253
+
254
+
255
+ ---- LLVM Exceptions to the Apache 2.0 License ----
256
+
257
+ As an exception, if, as a result of your compiling your source code, portions
258
+ of this Software are embedded into an Object form of such source code, you
259
+ may redistribute such embedded portions in such Object form without complying
260
+ with the conditions of Sections 4(a), 4(b) and 4(d) of the License.
261
+
262
+ In addition, if you combine or link compiled forms of this Software with
263
+ software that is licensed under the GPLv2 ("Combined Software") and if a
264
+ court of competent jurisdiction determines that the patent provision (Section
265
+ 3), the indemnity provision (Section 9) or other Section of the License
266
+ conflicts with the conditions of the GPLv2, you may retroactively and
267
+ prospectively choose to deem waived or otherwise exclude such Section(s) of
268
+ the License, but only in their entirety and only with respect to the Combined
269
+ Software.
270
+
271
+ ==============================================================================
272
+ Software from third parties included in the LLVM Project:
273
+ ==============================================================================
274
+ The LLVM Project contains third party software which is under different license
275
+ terms. All such code will be identified clearly using at least one of two
276
+ mechanisms:
277
+ 1) It will be in a separate directory tree with its own `LICENSE.txt` or
278
+ `LICENSE` file at the top containing the specific license and restrictions
279
+ which apply to that software, or
280
+ 2) It will contain specific license and restriction terms at the top of every
281
+ file.
282
+
283
+ ==============================================================================
284
+ Legacy LLVM License (https://llvm.org/docs/DeveloperPolicy.html#legacy):
285
+ ==============================================================================
286
+
287
+ The software contained in this directory tree is dual licensed under both the
288
+ University of Illinois "BSD-Like" license and the MIT license. As a user of
289
+ this code you may choose to use it under either license. As a contributor,
290
+ you agree to allow your code to be used under both. The full text of the
291
+ relevant licenses is included below.
292
+
293
+ In addition, a license agreement from the copyright/patent holders of the
294
+ software contained in this directory tree is included below.
295
+
296
+ ==============================================================================
297
+
298
+ University of Illinois/NCSA
299
+ Open Source License
300
+
301
+ Copyright (c) 1997-2019 Intel Corporation
302
+
303
+ All rights reserved.
304
+
305
+ Developed by:
306
+ OpenMP Runtime Team
307
+ Intel Corporation
308
+ http://www.openmprtl.org
309
+
310
+ Permission is hereby granted, free of charge, to any person obtaining a copy of
311
+ this software and associated documentation files (the "Software"), to deal with
312
+ the Software without restriction, including without limitation the rights to
313
+ use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
314
+ of the Software, and to permit persons to whom the Software is furnished to do
315
+ so, subject to the following conditions:
316
+
317
+ * Redistributions of source code must retain the above copyright notice,
318
+ this list of conditions and the following disclaimers.
319
+
320
+ * Redistributions in binary form must reproduce the above copyright notice,
321
+ this list of conditions and the following disclaimers in the
322
+ documentation and/or other materials provided with the distribution.
323
+
324
+ * Neither the names of Intel Corporation OpenMP Runtime Team nor the
325
+ names of its contributors may be used to endorse or promote products
326
+ derived from this Software without specific prior written permission.
327
+
328
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
329
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
330
+ FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
331
+ CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
332
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
333
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS WITH THE
334
+ SOFTWARE.
335
+
336
+ ==============================================================================
337
+
338
+ Copyright (c) 1997-2019 Intel Corporation
339
+
340
+ Permission is hereby granted, free of charge, to any person obtaining a copy
341
+ of this software and associated documentation files (the "Software"), to deal
342
+ in the Software without restriction, including without limitation the rights
343
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
344
+ copies of the Software, and to permit persons to whom the Software is
345
+ furnished to do so, subject to the following conditions:
346
+
347
+ The above copyright notice and this permission notice shall be included in
348
+ all copies or substantial portions of the Software.
349
+
350
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
351
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
352
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
353
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
354
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
355
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
356
+ THE SOFTWARE.
357
+
358
+ ==============================================================================
359
+
360
+ Intel Corporation
361
+
362
+ Software Grant License Agreement ("Agreement")
363
+
364
+ Except for the license granted herein to you, Intel Corporation ("Intel") reserves
365
+ all right, title, and interest in and to the Software (defined below).
366
+
367
+ Definition
368
+
369
+ "Software" means the code and documentation as well as any original work of
370
+ authorship, including any modifications or additions to an existing work, that
371
+ is intentionally submitted by Intel to llvm.org (http://llvm.org) ("LLVM") for
372
+ inclusion in, or documentation of, any of the products owned or managed by LLVM
373
+ (the "Work"). For the purposes of this definition, "submitted" means any form of
374
+ electronic, verbal, or written communication sent to LLVM or its
375
+ representatives, including but not limited to communication on electronic
376
+ mailing lists, source code control systems, and issue tracking systems that are
377
+ managed by, or on behalf of, LLVM for the purpose of discussing and improving
378
+ the Work, but excluding communication that is conspicuously marked otherwise.
379
+
380
+ 1. Grant of Copyright License. Subject to the terms and conditions of this
381
+ Agreement, Intel hereby grants to you and to recipients of the Software
382
+ distributed by LLVM a perpetual, worldwide, non-exclusive, no-charge,
383
+ royalty-free, irrevocable copyright license to reproduce, prepare derivative
384
+ works of, publicly display, publicly perform, sublicense, and distribute the
385
+ Software and such derivative works.
386
+
387
+ 2. Grant of Patent License. Subject to the terms and conditions of this
388
+ Agreement, Intel hereby grants you and to recipients of the Software
389
+ distributed by LLVM a perpetual, worldwide, non-exclusive, no-charge,
390
+ royalty-free, irrevocable (except as stated in this section) patent license
391
+ to make, have made, use, offer to sell, sell, import, and otherwise transfer
392
+ the Work, where such license applies only to those patent claims licensable
393
+ by Intel that are necessarily infringed by Intel's Software alone or by
394
+ combination of the Software with the Work to which such Software was
395
+ submitted. If any entity institutes patent litigation against Intel or any
396
+ other entity (including a cross-claim or counterclaim in a lawsuit) alleging
397
+ that Intel's Software, or the Work to which Intel has contributed constitutes
398
+ direct or contributory patent infringement, then any patent licenses granted
399
+ to that entity under this Agreement for the Software or Work shall terminate
400
+ as of the date such litigation is filed.
401
+
402
+ Unless required by applicable law or agreed to in writing, the software is
403
+ provided on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
404
+ either express or implied, including, without limitation, any warranties or
405
+ conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
406
+ PARTICULAR PURPOSE.
407
+
408
+ ==============================================================================
409
+ License: Apache-2.0 WITH LLVM-exception
410
+ Source: https://github.com/llvm/llvm-project
ScaleDF_rebuttal/python_dedup_pkgs/faiss_cpu-1.14.3.dist-info/sboms/auditwheel.cdx.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"bomFormat": "CycloneDX", "specVersion": "1.4", "version": 1, "metadata": {"component": {"type": "library", "bom-ref": "pkg:pypi/faiss_cpu@1.14.3?file_name=faiss_cpu-1.14.3-cp310-abi3-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", "name": "faiss_cpu", "version": "1.14.3", "purl": "pkg:pypi/faiss_cpu@1.14.3?file_name=faiss_cpu-1.14.3-cp310-abi3-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl"}, "tools": [{"name": "auditwheel", "version": "6.6.0"}]}, "components": [{"type": "library", "bom-ref": "pkg:pypi/faiss_cpu@1.14.3?file_name=faiss_cpu-1.14.3-cp310-abi3-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", "name": "faiss_cpu", "version": "1.14.3", "purl": "pkg:pypi/faiss_cpu@1.14.3?file_name=faiss_cpu-1.14.3-cp310-abi3-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl"}, {"type": "library", "bom-ref": "pkg:rpm/almalinux/openblas-openmp@0.3.15-6.el8#413963a9629ce91dfc39c185fd83d1ea744ee2c043ab84d9d1b89deecc051ed4", "name": "openblas-openmp", "version": "0.3.15-6.el8", "purl": "pkg:rpm/almalinux/openblas-openmp@0.3.15-6.el8"}, {"type": "library", "bom-ref": "pkg:rpm/almalinux/libgomp@8.5.0-28.el8_10.alma.1#c61017c9a24eb6e1e1a3cdc9becd004a6419cbda3d54b4848b98f240a4829571", "name": "libgomp", "version": "8.5.0-28.el8_10.alma.1", "purl": "pkg:rpm/almalinux/libgomp@8.5.0-28.el8_10.alma.1"}, {"type": "library", "bom-ref": "pkg:rpm/almalinux/libquadmath@8.5.0-28.el8_10.alma.1#97b91febe2a1c7927c6482d6bd6567b83be3467f33c9d2764df1283f7ac9a5fa", "name": "libquadmath", "version": "8.5.0-28.el8_10.alma.1", "purl": "pkg:rpm/almalinux/libquadmath@8.5.0-28.el8_10.alma.1"}, {"type": "library", "bom-ref": "pkg:rpm/almalinux/libgfortran@8.5.0-28.el8_10.alma.1#3362720ce454cc402813e3cfe54f0eb4efaedcd690fa35129ddc4b3de40e0650", "name": "libgfortran", "version": "8.5.0-28.el8_10.alma.1", "purl": "pkg:rpm/almalinux/libgfortran@8.5.0-28.el8_10.alma.1"}], "dependencies": [{"ref": "pkg:pypi/faiss_cpu@1.14.3?file_name=faiss_cpu-1.14.3-cp310-abi3-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", "dependsOn": ["pkg:rpm/almalinux/openblas-openmp@0.3.15-6.el8#413963a9629ce91dfc39c185fd83d1ea744ee2c043ab84d9d1b89deecc051ed4", "pkg:rpm/almalinux/libgomp@8.5.0-28.el8_10.alma.1#c61017c9a24eb6e1e1a3cdc9becd004a6419cbda3d54b4848b98f240a4829571", "pkg:rpm/almalinux/libquadmath@8.5.0-28.el8_10.alma.1#97b91febe2a1c7927c6482d6bd6567b83be3467f33c9d2764df1283f7ac9a5fa", "pkg:rpm/almalinux/libgfortran@8.5.0-28.el8_10.alma.1#3362720ce454cc402813e3cfe54f0eb4efaedcd690fa35129ddc4b3de40e0650"]}, {"ref": "pkg:rpm/almalinux/openblas-openmp@0.3.15-6.el8#413963a9629ce91dfc39c185fd83d1ea744ee2c043ab84d9d1b89deecc051ed4"}, {"ref": "pkg:rpm/almalinux/libgomp@8.5.0-28.el8_10.alma.1#c61017c9a24eb6e1e1a3cdc9becd004a6419cbda3d54b4848b98f240a4829571"}, {"ref": "pkg:rpm/almalinux/libquadmath@8.5.0-28.el8_10.alma.1#97b91febe2a1c7927c6482d6bd6567b83be3467f33c9d2764df1283f7ac9a5fa"}, {"ref": "pkg:rpm/almalinux/libgfortran@8.5.0-28.el8_10.alma.1#3362720ce454cc402813e3cfe54f0eb4efaedcd690fa35129ddc4b3de40e0650"}]}
ScaleDF_rebuttal/python_dedup_pkgs/flatbuffers-25.12.19.dist-info/INSTALLER ADDED
@@ -0,0 +1 @@
 
 
1
+ pip
ScaleDF_rebuttal/python_dedup_pkgs/flatbuffers-25.12.19.dist-info/METADATA ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Metadata-Version: 2.4
2
+ Name: flatbuffers
3
+ Version: 25.12.19
4
+ Summary: The FlatBuffers serialization format for Python
5
+ Home-page: https://google.github.io/flatbuffers/
6
+ Author: Derek Bailey
7
+ Author-email: derekbailey@google.com
8
+ License: Apache 2.0
9
+ Project-URL: Documentation, https://google.github.io/flatbuffers/
10
+ Project-URL: Source, https://github.com/google/flatbuffers
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: License :: OSI Approved :: Apache Software License
13
+ Classifier: Operating System :: OS Independent
14
+ Classifier: Programming Language :: Python
15
+ Classifier: Programming Language :: Python :: 2
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
18
+ Dynamic: author
19
+ Dynamic: author-email
20
+ Dynamic: classifier
21
+ Dynamic: description
22
+ Dynamic: home-page
23
+ Dynamic: license
24
+ Dynamic: project-url
25
+ Dynamic: summary
26
+
27
+ Python runtime library for use with the `Flatbuffers <https://google.github.io/flatbuffers/>`_ serialization format.
ScaleDF_rebuttal/python_dedup_pkgs/flatbuffers-25.12.19.dist-info/RECORD ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ flatbuffers-25.12.19.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
2
+ flatbuffers-25.12.19.dist-info/METADATA,sha256=nzgjn5b6ohUipqratpEuHlYHCLvpyfaWoGeclAP6CJ4,1004
3
+ flatbuffers-25.12.19.dist-info/RECORD,,
4
+ flatbuffers-25.12.19.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
5
+ flatbuffers-25.12.19.dist-info/WHEEL,sha256=JNWh1Fm1UdwIQV075glCn4MVuCRs0sotJIq-J6rbxCU,109
6
+ flatbuffers-25.12.19.dist-info/top_level.txt,sha256=UXVWLA8ys6HeqTz6rfKesocUq6ln-ZL8mhZC_cq5BEc,12
7
+ flatbuffers/__init__.py,sha256=vJZrqZOOTKdBNMa_iTKUA6WJG_c_NzKGpFXOe1Igtiw,751
8
+ flatbuffers/__pycache__/__init__.cpython-311.pyc,,
9
+ flatbuffers/__pycache__/_version.cpython-311.pyc,,
10
+ flatbuffers/__pycache__/builder.cpython-311.pyc,,
11
+ flatbuffers/__pycache__/compat.cpython-311.pyc,,
12
+ flatbuffers/__pycache__/encode.cpython-311.pyc,,
13
+ flatbuffers/__pycache__/flexbuffers.cpython-311.pyc,,
14
+ flatbuffers/__pycache__/number_types.cpython-311.pyc,,
15
+ flatbuffers/__pycache__/packer.cpython-311.pyc,,
16
+ flatbuffers/__pycache__/table.cpython-311.pyc,,
17
+ flatbuffers/__pycache__/util.cpython-311.pyc,,
18
+ flatbuffers/_version.py,sha256=sk31rbYWDseoJxI9YQ1fYR-MMxRATyqsntKAEv7D7pI,696
19
+ flatbuffers/builder.py,sha256=HrG5KJ9rasiSTrMGeatkSdDs7fXV5fy_927Dsgakp4A,24567
20
+ flatbuffers/compat.py,sha256=ihBSpWDCSL-vgLSyZtcu8LX3ZI3wz9LhtqItY2GQZgg,2373
21
+ flatbuffers/encode.py,sha256=2Or3mgWRAkJiWg-GgYasDU4zIHpQU3W06fmIhwbz5uM,1550
22
+ flatbuffers/flexbuffers.py,sha256=yF8Wr4Lo8WJb-pj9NNaIYxLwzlHHyTroM0iO8fyDwbU,44454
23
+ flatbuffers/number_types.py,sha256=ijO0QcJiuxlQegoBOed0v9m0DdzTZHWxpTBZUqzsWHA,3762
24
+ flatbuffers/packer.py,sha256=LNWym8YgFRqHjcPeGpYY3inCGWH6XnbkQKtAPtFEVas,1164
25
+ flatbuffers/table.py,sha256=ciYTmq_CzAuYpb3KAVnl75M84ieChfbyKne-dFHzwwU,4818
26
+ flatbuffers/util.py,sha256=mRVQ1VoHp0MJMNtRTUGVzALwN4T_C-U14tMbj99py2A,1608
ScaleDF_rebuttal/python_dedup_pkgs/flatbuffers-25.12.19.dist-info/REQUESTED ADDED
File without changes
ScaleDF_rebuttal/python_dedup_pkgs/flatbuffers-25.12.19.dist-info/WHEEL ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (80.9.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py2-none-any
5
+ Tag: py3-none-any
6
+
ScaleDF_rebuttal/python_dedup_pkgs/flatbuffers-25.12.19.dist-info/top_level.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ flatbuffers
ScaleDF_rebuttal/python_dedup_pkgs/flatbuffers/__init__.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2014 Google Inc. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from . import util
16
+ from ._version import __version__
17
+ from .builder import Builder
18
+ from .compat import range_func as compat_range
19
+ from .table import Table
ScaleDF_rebuttal/python_dedup_pkgs/flatbuffers/_version.py ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2019 Google Inc. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ # Placeholder, to be updated during the release process
16
+ # by the setup.py
17
+ __version__ = "25.12.19"
ScaleDF_rebuttal/python_dedup_pkgs/flatbuffers/builder.py ADDED
@@ -0,0 +1,858 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2014 Google Inc. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import warnings
16
+
17
+ from . import compat
18
+ from . import encode
19
+ from . import number_types as N
20
+ from . import packer
21
+ from .compat import memoryview_type
22
+ from .compat import NumpyRequiredForThisFeature, import_numpy
23
+ from .compat import range_func
24
+ from .number_types import (SOffsetTFlags, UOffsetTFlags, VOffsetTFlags)
25
+
26
+ np = import_numpy()
27
+ ## @file
28
+ ## @addtogroup flatbuffers_python_api
29
+ ## @{
30
+
31
+
32
+ ## @cond FLATBUFFERS_INTERNAL
33
+ class OffsetArithmeticError(RuntimeError):
34
+ """Error caused by an Offset arithmetic error.
35
+
36
+ Probably caused by bad writing of fields. This is considered an unreachable
37
+ situation in normal circumstances.
38
+ """
39
+
40
+ pass
41
+
42
+
43
+ class IsNotNestedError(RuntimeError):
44
+ """Error caused by using a Builder to write Object data when not inside
45
+
46
+ an Object.
47
+ """
48
+
49
+ pass
50
+
51
+
52
+ class IsNestedError(RuntimeError):
53
+ """Error caused by using a Builder to begin an Object when an Object is
54
+
55
+ already being built.
56
+ """
57
+
58
+ pass
59
+
60
+
61
+ class StructIsNotInlineError(RuntimeError):
62
+ """Error caused by using a Builder to write a Struct at a location that
63
+
64
+ is not the current Offset.
65
+ """
66
+
67
+ pass
68
+
69
+
70
+ class BuilderSizeError(RuntimeError):
71
+ """Error caused by causing a Builder to exceed the hardcoded limit of 2
72
+
73
+ gigabytes.
74
+ """
75
+
76
+ pass
77
+
78
+
79
+ class BuilderNotFinishedError(RuntimeError):
80
+ """Error caused by not calling `Finish` before calling `Output`."""
81
+
82
+ pass
83
+
84
+
85
+ class EndVectorLengthMismatched(RuntimeError):
86
+ """The number of elements passed to EndVector does not match the number
87
+
88
+ specified in StartVector.
89
+ """
90
+
91
+ pass
92
+
93
+
94
+ # VtableMetadataFields is the count of metadata fields in each vtable.
95
+ VtableMetadataFields = 2
96
+ ## @endcond
97
+
98
+
99
+ class Builder(object):
100
+ """A Builder is used to construct one or more FlatBuffers.
101
+
102
+ Typically, Builder objects will be used from code generated by the `flatc`
103
+ compiler.
104
+
105
+ A Builder constructs byte buffers in a last-first manner for simplicity and
106
+ performance during reading.
107
+
108
+ Internally, a Builder is a state machine for creating FlatBuffer objects.
109
+
110
+ It holds the following internal state:
111
+ - Bytes: an array of bytes.
112
+ - current_vtable: a list of integers.
113
+ - vtables: a hash of vtable entries.
114
+
115
+ Attributes:
116
+ Bytes: The internal `bytearray` for the Builder.
117
+ finished: A boolean determining if the Builder has been finalized.
118
+ """
119
+
120
+ ## @cond FLATBUFFERS_INTENRAL
121
+ __slots__ = (
122
+ "Bytes",
123
+ "current_vtable",
124
+ "head",
125
+ "minalign",
126
+ "objectEnd",
127
+ "vtables",
128
+ "nested",
129
+ "forceDefaults",
130
+ "finished",
131
+ "vectorNumElems",
132
+ "sharedStrings",
133
+ )
134
+
135
+ """Maximum buffer size constant, in bytes.
136
+
137
+ Builder will never allow it's buffer grow over this size.
138
+ Currently equals 2Gb.
139
+ """
140
+ MAX_BUFFER_SIZE = 2**31
141
+ ## @endcond
142
+
143
+ def __init__(self, initialSize=1024):
144
+ """Initializes a Builder of size `initial_size`.
145
+
146
+ The internal buffer is grown as needed.
147
+ """
148
+
149
+ if not (0 <= initialSize <= Builder.MAX_BUFFER_SIZE):
150
+ msg = "flatbuffers: Cannot create Builder larger than 2 gigabytes."
151
+ raise BuilderSizeError(msg)
152
+
153
+ self.Bytes = bytearray(initialSize)
154
+ ## @cond FLATBUFFERS_INTERNAL
155
+ self.current_vtable = None
156
+ self.head = UOffsetTFlags.py_type(initialSize)
157
+ self.minalign = 1
158
+ self.objectEnd = None
159
+ self.vtables = {}
160
+ self.nested = False
161
+ self.forceDefaults = False
162
+ self.sharedStrings = None
163
+ ## @endcond
164
+ self.finished = False
165
+
166
+ def Clear(self):
167
+ ## @cond FLATBUFFERS_INTERNAL
168
+ self.current_vtable = None
169
+ self.head = len(self.Bytes)
170
+ self.minalign = 1
171
+ self.objectEnd = None
172
+ self.vtables = {}
173
+ self.nested = False
174
+ self.forceDefaults = False
175
+ self.sharedStrings = None
176
+ self.vectorNumElems = None
177
+ ## @endcond
178
+ self.finished = False
179
+
180
+ def Output(self):
181
+ """Return the portion of the buffer that has been used for writing data.
182
+
183
+ This is the typical way to access the FlatBuffer data inside the
184
+ builder. If you try to access `Builder.Bytes` directly, you would need
185
+ to manually index it with `Head()`, since the buffer is constructed
186
+ backwards.
187
+
188
+ It raises BuilderNotFinishedError if the buffer has not been finished
189
+ with `Finish`.
190
+ """
191
+
192
+ if not self.finished:
193
+ raise BuilderNotFinishedError()
194
+
195
+ return self.Bytes[self.head :]
196
+
197
+ ## @cond FLATBUFFERS_INTERNAL
198
+ def StartObject(self, numfields):
199
+ """StartObject initializes bookkeeping for writing a new object."""
200
+
201
+ self.assertNotNested()
202
+
203
+ # use 32-bit offsets so that arithmetic doesn't overflow.
204
+ self.current_vtable = [0] * numfields
205
+ self.objectEnd = self.Offset()
206
+ self.nested = True
207
+
208
+ def WriteVtable(self):
209
+ """WriteVtable serializes the vtable for the current object, if needed.
210
+
211
+ Before writing out the vtable, this checks pre-existing vtables for
212
+ equality to this one. If an equal vtable is found, point the object to
213
+ the existing vtable and return.
214
+
215
+ Because vtable values are sensitive to alignment of object data, not
216
+ all logically-equal vtables will be deduplicated.
217
+
218
+ A vtable has the following format:
219
+ <VOffsetT: size of the vtable in bytes, including this value>
220
+ <VOffsetT: size of the object in bytes, including the vtable offset>
221
+ <VOffsetT: offset for a field> * N, where N is the number of fields
222
+ in the schema for this type. Includes deprecated fields.
223
+ Thus, a vtable is made of 2 + N elements, each VOffsetT bytes wide.
224
+
225
+ An object has the following format:
226
+ <SOffsetT: offset to this object's vtable (may be negative)>
227
+ <byte: data>+
228
+ """
229
+
230
+ # Prepend a zero scalar to the object. Later in this function we'll
231
+ # write an offset here that points to the object's vtable:
232
+ self.PrependSOffsetTRelative(0)
233
+
234
+ objectOffset = self.Offset()
235
+
236
+ vtKey = []
237
+ trim = True
238
+ for elem in reversed(self.current_vtable):
239
+ if elem == 0:
240
+ if trim:
241
+ continue
242
+ else:
243
+ elem = objectOffset - elem
244
+ trim = False
245
+
246
+ vtKey.append(elem)
247
+
248
+ objectSize = UOffsetTFlags.py_type(objectOffset - self.objectEnd)
249
+ vtKey.append(objectSize)
250
+ vtKey = tuple(vtKey)
251
+ # calculate the size of the object
252
+ vt2Offset = self.vtables.get(vtKey)
253
+ if vt2Offset is None:
254
+ # Did not find a vtable, so write this one to the buffer.
255
+
256
+ # Write out the current vtable in reverse , because
257
+ # serialization occurs in last-first order:
258
+ i = len(self.current_vtable) - 1
259
+ trailing = 0
260
+ trim = True
261
+ while i >= 0:
262
+ off = 0
263
+ elem = self.current_vtable[i]
264
+ i -= 1
265
+
266
+ if elem == 0:
267
+ if trim:
268
+ trailing += 1
269
+ continue
270
+ else:
271
+ # Forward reference to field;
272
+ # use 32bit number to ensure no overflow:
273
+ off = objectOffset - elem
274
+ trim = False
275
+
276
+ self.PrependVOffsetT(off)
277
+
278
+ # The two metadata fields are written last.
279
+
280
+ # First, store the object bytesize:
281
+ self.PrependVOffsetT(VOffsetTFlags.py_type(objectSize))
282
+
283
+ # Second, store the vtable bytesize:
284
+ vBytes = len(self.current_vtable) - trailing + VtableMetadataFields
285
+ vBytes *= N.VOffsetTFlags.bytewidth
286
+ self.PrependVOffsetT(VOffsetTFlags.py_type(vBytes))
287
+
288
+ # Next, write the offset to the new vtable in the
289
+ # already-allocated SOffsetT at the beginning of this object:
290
+ objectStart = SOffsetTFlags.py_type(len(self.Bytes) - objectOffset)
291
+ encode.Write(
292
+ packer.soffset,
293
+ self.Bytes,
294
+ objectStart,
295
+ SOffsetTFlags.py_type(self.Offset() - objectOffset),
296
+ )
297
+
298
+ # Finally, store this vtable in memory for future
299
+ # deduplication:
300
+ self.vtables[vtKey] = self.Offset()
301
+ else:
302
+ # Found a duplicate vtable.
303
+ objectStart = SOffsetTFlags.py_type(len(self.Bytes) - objectOffset)
304
+ self.head = UOffsetTFlags.py_type(objectStart)
305
+
306
+ # Write the offset to the found vtable in the
307
+ # already-allocated SOffsetT at the beginning of this object:
308
+ encode.Write(
309
+ packer.soffset,
310
+ self.Bytes,
311
+ self.Head(),
312
+ SOffsetTFlags.py_type(vt2Offset - objectOffset),
313
+ )
314
+
315
+ self.current_vtable = None
316
+ return objectOffset
317
+
318
+ def EndObject(self):
319
+ """EndObject writes data necessary to finish object construction."""
320
+ self.assertNested()
321
+ self.nested = False
322
+ return self.WriteVtable()
323
+
324
+ def GrowByteBuffer(self):
325
+ """Doubles the size of the byteslice, and copies the old data towards
326
+
327
+ the end of the new buffer (since we build the buffer backwards).
328
+ """
329
+ if len(self.Bytes) == Builder.MAX_BUFFER_SIZE:
330
+ msg = "flatbuffers: cannot grow buffer beyond 2 gigabytes"
331
+ raise BuilderSizeError(msg)
332
+
333
+ newSize = min(len(self.Bytes) * 2, Builder.MAX_BUFFER_SIZE)
334
+ if newSize == 0:
335
+ newSize = 1
336
+ bytes2 = bytearray(newSize)
337
+ bytes2[newSize - len(self.Bytes) :] = self.Bytes
338
+ self.Bytes = bytes2
339
+
340
+ ## @endcond
341
+
342
+ def Head(self):
343
+ """Get the start of useful data in the underlying byte buffer.
344
+
345
+ Note: unlike other functions, this value is interpreted as from the
346
+ left.
347
+ """
348
+ ## @cond FLATBUFFERS_INTERNAL
349
+ return self.head
350
+ ## @endcond
351
+
352
+ ## @cond FLATBUFFERS_INTERNAL
353
+ def Offset(self):
354
+ """Offset relative to the end of the buffer."""
355
+ return len(self.Bytes) - self.head
356
+
357
+ def Pad(self, n):
358
+ """Pad places zeros at the current offset."""
359
+ if n <= 0:
360
+ return
361
+ new_head = self.head - n
362
+ self.Bytes[new_head : self.head] = b"\x00" * n
363
+ self.head = new_head
364
+
365
+ def Prep(self, size, additionalBytes):
366
+ """Prep prepares to write an element of `size` after `additional_bytes`
367
+
368
+ have been written, e.g. if you write a string, you need to align
369
+ such the int length field is aligned to SizeInt32, and the string
370
+ data follows it directly.
371
+ If all you need to do is align, `additionalBytes` will be 0.
372
+ """
373
+
374
+ # Track the biggest thing we've ever aligned to.
375
+ if size > self.minalign:
376
+ self.minalign = size
377
+
378
+ # Find the amount of alignment needed such that `size` is properly
379
+ # aligned after `additionalBytes`:
380
+ head = self.head
381
+ buf_len = len(self.Bytes)
382
+ alignSize = (~(buf_len - head + additionalBytes)) + 1
383
+ alignSize &= size - 1
384
+
385
+ # Reallocate the buffer if needed:
386
+ needed = alignSize + size + additionalBytes
387
+ while head < needed:
388
+ oldBufSize = buf_len
389
+ self.GrowByteBuffer()
390
+ buf_len = len(self.Bytes)
391
+ head += buf_len - oldBufSize
392
+ self.head = head
393
+ self.Pad(alignSize)
394
+
395
+ def PrependSOffsetTRelative(self, off):
396
+ """PrependSOffsetTRelative prepends an SOffsetT, relative to where it
397
+
398
+ will be written.
399
+ """
400
+
401
+ # Ensure alignment is already done:
402
+ self.Prep(N.SOffsetTFlags.bytewidth, 0)
403
+ if not (off <= self.Offset()):
404
+ msg = "flatbuffers: Offset arithmetic error."
405
+ raise OffsetArithmeticError(msg)
406
+ off2 = self.Offset() - off + N.SOffsetTFlags.bytewidth
407
+ self.PlaceSOffsetT(off2)
408
+
409
+ ## @endcond
410
+
411
+ def PrependUOffsetTRelative(self, off):
412
+ """Prepends an unsigned offset into vector data, relative to where it
413
+
414
+ will be written.
415
+ """
416
+
417
+ # Ensure alignment is already done:
418
+ self.Prep(N.UOffsetTFlags.bytewidth, 0)
419
+ if not (off <= self.Offset()):
420
+ msg = "flatbuffers: Offset arithmetic error."
421
+ raise OffsetArithmeticError(msg)
422
+ off2 = self.Offset() - off + N.UOffsetTFlags.bytewidth
423
+ self.PlaceUOffsetT(off2)
424
+
425
+ ## @cond FLATBUFFERS_INTERNAL
426
+ def StartVector(self, elemSize, numElems, alignment):
427
+ """StartVector initializes bookkeeping for writing a new vector.
428
+
429
+ A vector has the following format:
430
+ - <UOffsetT: number of elements in this vector>
431
+ - <T: data>+, where T is the type of elements of this vector.
432
+ """
433
+
434
+ self.assertNotNested()
435
+ self.nested = True
436
+ self.vectorNumElems = numElems
437
+ self.Prep(N.Uint32Flags.bytewidth, elemSize * numElems)
438
+ self.Prep(alignment, elemSize * numElems) # In case alignment > int.
439
+ return self.Offset()
440
+
441
+ ## @endcond
442
+
443
+ def EndVector(self, numElems=None):
444
+ """EndVector writes data necessary to finish vector construction."""
445
+
446
+ self.assertNested()
447
+ ## @cond FLATBUFFERS_INTERNAL
448
+ self.nested = False
449
+ ## @endcond
450
+
451
+ if numElems:
452
+ warnings.warn("numElems is deprecated.", DeprecationWarning, stacklevel=2)
453
+ if numElems != self.vectorNumElems:
454
+ raise EndVectorLengthMismatched()
455
+
456
+ # we already made space for this, so write without PrependUint32
457
+ self.PlaceUOffsetT(self.vectorNumElems)
458
+ self.vectorNumElems = None
459
+ return self.Offset()
460
+
461
+ def CreateSharedString(self, s, encoding="utf-8", errors="strict"):
462
+ """CreateSharedString checks if the string is already written to the buffer
463
+
464
+ before calling CreateString.
465
+ """
466
+
467
+ if not self.sharedStrings:
468
+ self.sharedStrings = {}
469
+ elif s in self.sharedStrings:
470
+ return self.sharedStrings[s]
471
+
472
+ off = self.CreateString(s, encoding, errors)
473
+ self.sharedStrings[s] = off
474
+
475
+ return off
476
+
477
+ def CreateString(self, s, encoding="utf-8", errors="strict"):
478
+ """CreateString writes a null-terminated byte string as a vector."""
479
+
480
+ self.assertNotNested()
481
+ ## @cond FLATBUFFERS_INTERNAL
482
+ self.nested = True
483
+ ## @endcond
484
+
485
+ if isinstance(s, compat.string_types):
486
+ x = s.encode(encoding, errors)
487
+ elif isinstance(s, compat.binary_types):
488
+ x = s
489
+ else:
490
+ raise TypeError("non-string passed to CreateString")
491
+
492
+ payload_len = len(x)
493
+ self.Prep(N.UOffsetTFlags.bytewidth, (payload_len + 1) * N.Uint8Flags.bytewidth)
494
+ self.Place(0, N.Uint8Flags)
495
+
496
+ new_head = self.head - payload_len
497
+ self.head = new_head
498
+ self.Bytes[new_head : new_head + payload_len] = x
499
+
500
+ self.vectorNumElems = payload_len
501
+ return self.EndVector()
502
+
503
+ def CreateByteVector(self, x):
504
+ """CreateString writes a byte vector."""
505
+
506
+ self.assertNotNested()
507
+ ## @cond FLATBUFFERS_INTERNAL
508
+ self.nested = True
509
+ ## @endcond
510
+
511
+ if not isinstance(x, compat.binary_types):
512
+ raise TypeError("non-byte vector passed to CreateByteVector")
513
+
514
+ data_len = len(x)
515
+ self.Prep(N.UOffsetTFlags.bytewidth, data_len * N.Uint8Flags.bytewidth)
516
+ new_head = self.head - data_len
517
+ self.head = new_head
518
+ self.Bytes[new_head : new_head + data_len] = x
519
+
520
+ self.vectorNumElems = data_len
521
+ return self.EndVector()
522
+
523
+ def CreateNumpyVector(self, x):
524
+ """CreateNumpyVector writes a numpy array into the buffer."""
525
+
526
+ if np is None:
527
+ # Numpy is required for this feature
528
+ raise NumpyRequiredForThisFeature("Numpy was not found.")
529
+
530
+ if not isinstance(x, np.ndarray):
531
+ raise TypeError("non-numpy-ndarray passed to CreateNumpyVector")
532
+
533
+ if x.dtype.kind not in ["b", "i", "u", "f"]:
534
+ raise TypeError("numpy-ndarray holds elements of unsupported datatype")
535
+
536
+ if x.ndim > 1:
537
+ raise TypeError("multidimensional-ndarray passed to CreateNumpyVector")
538
+
539
+ self.StartVector(x.itemsize, x.size, x.dtype.alignment)
540
+
541
+ # Ensure little endian byte ordering
542
+ if x.dtype.str[0] == "<":
543
+ x_lend = x
544
+ else:
545
+ x_lend = x.byteswap(inplace=False)
546
+
547
+ # tobytes ensures c_contiguous ordering
548
+ payload = x_lend.tobytes(order="C")
549
+
550
+ # Calculate total length
551
+ payload_len = len(payload)
552
+ new_head = self.head - payload_len
553
+ self.head = new_head
554
+ self.Bytes[new_head : new_head + payload_len] = payload
555
+
556
+ self.vectorNumElems = x.size
557
+ return self.EndVector()
558
+
559
+ ## @cond FLATBUFFERS_INTERNAL
560
+ def assertNested(self):
561
+ """Check that we are in the process of building an object."""
562
+
563
+ if not self.nested:
564
+ raise IsNotNestedError()
565
+
566
+ def assertNotNested(self):
567
+ """Check that no other objects are being built while making this object.
568
+
569
+ If not, raise an exception.
570
+ """
571
+
572
+ if self.nested:
573
+ raise IsNestedError()
574
+
575
+ def assertStructIsInline(self, obj):
576
+ """Structs are always stored inline, so need to be created right
577
+
578
+ where they are used. You'll get this error if you created it
579
+ elsewhere.
580
+ """
581
+
582
+ N.enforce_number(obj, N.UOffsetTFlags)
583
+ if obj != self.Offset():
584
+ msg = (
585
+ "flatbuffers: Tried to write a Struct at an Offset that "
586
+ "is different from the current Offset of the Builder."
587
+ )
588
+ raise StructIsNotInlineError(msg)
589
+
590
+ def Slot(self, slotnum):
591
+ """Slot sets the vtable key `voffset` to the current location in the
592
+
593
+ buffer.
594
+ """
595
+ self.assertNested()
596
+ self.current_vtable[slotnum] = self.Offset()
597
+
598
+ ## @endcond
599
+
600
+ def __Finish(self, rootTable, sizePrefix, file_identifier=None):
601
+ """Finish finalizes a buffer, pointing to the given `rootTable`."""
602
+ N.enforce_number(rootTable, N.UOffsetTFlags)
603
+
604
+ prepSize = N.UOffsetTFlags.bytewidth
605
+ if file_identifier is not None:
606
+ prepSize += N.Int32Flags.bytewidth
607
+ if sizePrefix:
608
+ prepSize += N.Int32Flags.bytewidth
609
+ self.Prep(self.minalign, prepSize)
610
+
611
+ if file_identifier is not None:
612
+ self.Prep(N.UOffsetTFlags.bytewidth, encode.FILE_IDENTIFIER_LENGTH)
613
+
614
+ # Convert bytes object file_identifier to an array of 4 8-bit integers,
615
+ # and use big-endian to enforce size compliance.
616
+ # https://docs.python.org/2/library/struct.html#format-characters
617
+ file_identifier = N.struct.unpack(">BBBB", file_identifier)
618
+ for i in range(encode.FILE_IDENTIFIER_LENGTH - 1, -1, -1):
619
+ # Place the bytes of the file_identifer in reverse order:
620
+ self.Place(file_identifier[i], N.Uint8Flags)
621
+
622
+ self.PrependUOffsetTRelative(rootTable)
623
+ if sizePrefix:
624
+ size = len(self.Bytes) - self.head
625
+ N.enforce_number(size, N.Int32Flags)
626
+ self.PrependInt32(size)
627
+ self.finished = True
628
+ return self.head
629
+
630
+ def Finish(self, rootTable, file_identifier=None):
631
+ """Finish finalizes a buffer, pointing to the given `rootTable`."""
632
+ return self.__Finish(rootTable, False, file_identifier=file_identifier)
633
+
634
+ def FinishSizePrefixed(self, rootTable, file_identifier=None):
635
+ """Finish finalizes a buffer, pointing to the given `rootTable`,
636
+
637
+ with the size prefixed.
638
+ """
639
+ return self.__Finish(rootTable, True, file_identifier=file_identifier)
640
+
641
+ ## @cond FLATBUFFERS_INTERNAL
642
+ def Prepend(self, flags, off):
643
+ self.Prep(flags.bytewidth, 0)
644
+ self.Place(off, flags)
645
+
646
+ def PrependSlot(self, flags, o, x, d):
647
+ if x is not None:
648
+ N.enforce_number(x, flags)
649
+ if d is not None:
650
+ N.enforce_number(d, flags)
651
+ if x != d or (self.forceDefaults and d is not None):
652
+ self.Prepend(flags, x)
653
+ self.Slot(o)
654
+
655
+ def PrependBoolSlot(self, *args):
656
+ self.PrependSlot(N.BoolFlags, *args)
657
+
658
+ def PrependByteSlot(self, *args):
659
+ self.PrependSlot(N.Uint8Flags, *args)
660
+
661
+ def PrependUint8Slot(self, *args):
662
+ self.PrependSlot(N.Uint8Flags, *args)
663
+
664
+ def PrependUint16Slot(self, *args):
665
+ self.PrependSlot(N.Uint16Flags, *args)
666
+
667
+ def PrependUint32Slot(self, *args):
668
+ self.PrependSlot(N.Uint32Flags, *args)
669
+
670
+ def PrependUint64Slot(self, *args):
671
+ self.PrependSlot(N.Uint64Flags, *args)
672
+
673
+ def PrependInt8Slot(self, *args):
674
+ self.PrependSlot(N.Int8Flags, *args)
675
+
676
+ def PrependInt16Slot(self, *args):
677
+ self.PrependSlot(N.Int16Flags, *args)
678
+
679
+ def PrependInt32Slot(self, *args):
680
+ self.PrependSlot(N.Int32Flags, *args)
681
+
682
+ def PrependInt64Slot(self, *args):
683
+ self.PrependSlot(N.Int64Flags, *args)
684
+
685
+ def PrependFloat32Slot(self, *args):
686
+ self.PrependSlot(N.Float32Flags, *args)
687
+
688
+ def PrependFloat64Slot(self, *args):
689
+ self.PrependSlot(N.Float64Flags, *args)
690
+
691
+ def PrependUOffsetTRelativeSlot(self, o, x, d):
692
+ """PrependUOffsetTRelativeSlot prepends an UOffsetT onto the object at
693
+
694
+ vtable slot `o`. If value `x` equals default `d`, then the slot will
695
+ be set to zero and no other data will be written.
696
+ """
697
+
698
+ if x != d or self.forceDefaults:
699
+ self.PrependUOffsetTRelative(x)
700
+ self.Slot(o)
701
+
702
+ def PrependStructSlot(self, v, x, d):
703
+ """PrependStructSlot prepends a struct onto the object at vtable slot `o`.
704
+
705
+ Structs are stored inline, so nothing additional is being added. In
706
+ generated code, `d` is always 0.
707
+ """
708
+
709
+ N.enforce_number(d, N.UOffsetTFlags)
710
+ if x != d:
711
+ self.assertStructIsInline(x)
712
+ self.Slot(v)
713
+
714
+ ## @endcond
715
+
716
+ def PrependBool(self, x):
717
+ """Prepend a `bool` to the Builder buffer.
718
+
719
+ Note: aligns and checks for space.
720
+ """
721
+ self.Prepend(N.BoolFlags, x)
722
+
723
+ def PrependByte(self, x):
724
+ """Prepend a `byte` to the Builder buffer.
725
+
726
+ Note: aligns and checks for space.
727
+ """
728
+ self.Prepend(N.Uint8Flags, x)
729
+
730
+ def PrependUint8(self, x):
731
+ """Prepend an `uint8` to the Builder buffer.
732
+
733
+ Note: aligns and checks for space.
734
+ """
735
+ self.Prepend(N.Uint8Flags, x)
736
+
737
+ def PrependUint16(self, x):
738
+ """Prepend an `uint16` to the Builder buffer.
739
+
740
+ Note: aligns and checks for space.
741
+ """
742
+ self.Prepend(N.Uint16Flags, x)
743
+
744
+ def PrependUint32(self, x):
745
+ """Prepend an `uint32` to the Builder buffer.
746
+
747
+ Note: aligns and checks for space.
748
+ """
749
+ self.Prepend(N.Uint32Flags, x)
750
+
751
+ def PrependUint64(self, x):
752
+ """Prepend an `uint64` to the Builder buffer.
753
+
754
+ Note: aligns and checks for space.
755
+ """
756
+ self.Prepend(N.Uint64Flags, x)
757
+
758
+ def PrependInt8(self, x):
759
+ """Prepend an `int8` to the Builder buffer.
760
+
761
+ Note: aligns and checks for space.
762
+ """
763
+ self.Prepend(N.Int8Flags, x)
764
+
765
+ def PrependInt16(self, x):
766
+ """Prepend an `int16` to the Builder buffer.
767
+
768
+ Note: aligns and checks for space.
769
+ """
770
+ self.Prepend(N.Int16Flags, x)
771
+
772
+ def PrependInt32(self, x):
773
+ """Prepend an `int32` to the Builder buffer.
774
+
775
+ Note: aligns and checks for space.
776
+ """
777
+ self.Prepend(N.Int32Flags, x)
778
+
779
+ def PrependInt64(self, x):
780
+ """Prepend an `int64` to the Builder buffer.
781
+
782
+ Note: aligns and checks for space.
783
+ """
784
+ self.Prepend(N.Int64Flags, x)
785
+
786
+ def PrependFloat32(self, x):
787
+ """Prepend a `float32` to the Builder buffer.
788
+
789
+ Note: aligns and checks for space.
790
+ """
791
+ self.Prepend(N.Float32Flags, x)
792
+
793
+ def PrependFloat64(self, x):
794
+ """Prepend a `float64` to the Builder buffer.
795
+
796
+ Note: aligns and checks for space.
797
+ """
798
+ self.Prepend(N.Float64Flags, x)
799
+
800
+ def ForceDefaults(self, forceDefaults):
801
+ """In order to save space, fields that are set to their default value
802
+
803
+ don't get serialized into the buffer. Forcing defaults provides a
804
+ way to manually disable this optimization. When set to `True`, will
805
+ always serialize default values.
806
+ """
807
+ self.forceDefaults = forceDefaults
808
+
809
+ ##############################################################
810
+
811
+ ## @cond FLATBUFFERS_INTERNAL
812
+ def PrependVOffsetT(self, x):
813
+ self.Prepend(N.VOffsetTFlags, x)
814
+
815
+ def Place(self, x, flags):
816
+ """Place prepends a value specified by `flags` to the Builder,
817
+
818
+ without checking for available space.
819
+ """
820
+
821
+ N.enforce_number(x, flags)
822
+ new_head = self.head - flags.bytewidth
823
+ self.head = new_head
824
+ encode.Write(flags.packer_type, self.Bytes, new_head, x)
825
+
826
+ def PlaceVOffsetT(self, x):
827
+ """PlaceVOffsetT prepends a VOffsetT to the Builder, without checking
828
+
829
+ for space.
830
+ """
831
+ N.enforce_number(x, N.VOffsetTFlags)
832
+ new_head = self.head - N.VOffsetTFlags.bytewidth
833
+ self.head = new_head
834
+ encode.Write(packer.voffset, self.Bytes, new_head, x)
835
+
836
+ def PlaceSOffsetT(self, x):
837
+ """PlaceSOffsetT prepends a SOffsetT to the Builder, without checking
838
+
839
+ for space.
840
+ """
841
+ N.enforce_number(x, N.SOffsetTFlags)
842
+ new_head = self.head - N.SOffsetTFlags.bytewidth
843
+ self.head = new_head
844
+ encode.Write(packer.soffset, self.Bytes, new_head, x)
845
+
846
+ def PlaceUOffsetT(self, x):
847
+ """PlaceUOffsetT prepends a UOffsetT to the Builder, without checking
848
+
849
+ for space.
850
+ """
851
+ N.enforce_number(x, N.UOffsetTFlags)
852
+ new_head = self.head - N.UOffsetTFlags.bytewidth
853
+ self.head = new_head
854
+ encode.Write(packer.uoffset, self.Bytes, new_head, x)
855
+
856
+ ## @endcond
857
+
858
+ ## @}
ScaleDF_rebuttal/python_dedup_pkgs/flatbuffers/compat.py ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2016 Google Inc. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """A tiny version of `six` to help with backwards compability.
16
+
17
+ Also includes compatibility helpers for numpy.
18
+ """
19
+
20
+ import sys
21
+
22
+ PY2 = sys.version_info[0] == 2
23
+ PY26 = sys.version_info[0:2] == (2, 6)
24
+ PY27 = sys.version_info[0:2] == (2, 7)
25
+ PY275 = sys.version_info[0:3] >= (2, 7, 5)
26
+ PY3 = sys.version_info[0] == 3
27
+ PY34 = sys.version_info[0:2] >= (3, 4)
28
+
29
+ if PY3:
30
+ import importlib.machinery
31
+
32
+ string_types = (str,)
33
+ binary_types = (bytes, bytearray)
34
+ range_func = range
35
+ memoryview_type = memoryview
36
+ struct_bool_decl = "?"
37
+ else:
38
+ import imp
39
+
40
+ string_types = (unicode,)
41
+ if PY26 or PY27:
42
+ binary_types = (str, bytearray)
43
+ else:
44
+ binary_types = (str,)
45
+ range_func = xrange
46
+ if PY26 or (PY27 and not PY275):
47
+ memoryview_type = buffer
48
+ struct_bool_decl = "<b"
49
+ else:
50
+ memoryview_type = memoryview
51
+ struct_bool_decl = "?"
52
+
53
+ # Helper functions to facilitate making numpy optional instead of required
54
+
55
+
56
+ def import_numpy():
57
+ """Returns the numpy module if it exists on the system,
58
+
59
+ otherwise returns None.
60
+ """
61
+ if PY3:
62
+ numpy_exists = importlib.machinery.PathFinder.find_spec("numpy") is not None
63
+ else:
64
+ try:
65
+ imp.find_module("numpy")
66
+ numpy_exists = True
67
+ except ImportError:
68
+ numpy_exists = False
69
+
70
+ if numpy_exists:
71
+ # We do this outside of try/except block in case numpy exists
72
+ # but is not installed correctly. We do not want to catch an
73
+ # incorrect installation which would manifest as an
74
+ # ImportError.
75
+ import numpy as np
76
+ else:
77
+ np = None
78
+
79
+ return np
80
+
81
+
82
+ class NumpyRequiredForThisFeature(RuntimeError):
83
+ """Error raised when user tries to use a feature that
84
+
85
+ requires numpy without having numpy installed.
86
+ """
87
+
88
+ pass
89
+
90
+
91
+ # NOTE: Future Jython support may require code here (look at `six`).
ScaleDF_rebuttal/python_dedup_pkgs/flatbuffers/encode.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2014 Google Inc. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from . import number_types as N
16
+ from . import packer
17
+ from .compat import memoryview_type
18
+ from .compat import NumpyRequiredForThisFeature, import_numpy
19
+
20
+ np = import_numpy()
21
+
22
+ FILE_IDENTIFIER_LENGTH = 4
23
+
24
+
25
+ def Get(packer_type, buf, head):
26
+ """Get decodes a value at buf[head] using `packer_type`."""
27
+ return packer_type.unpack_from(memoryview_type(buf), head)[0]
28
+
29
+
30
+ def GetVectorAsNumpy(numpy_type, buf, count, offset):
31
+ """GetVecAsNumpy decodes values starting at buf[head] as
32
+
33
+ `numpy_type`, where `numpy_type` is a numpy dtype.
34
+ """
35
+ if np is not None:
36
+ # TODO: could set .flags.writeable = False to make users jump through
37
+ # hoops before modifying...
38
+ return np.frombuffer(buf, dtype=numpy_type, count=count, offset=offset)
39
+ else:
40
+ raise NumpyRequiredForThisFeature('Numpy was not found.')
41
+
42
+
43
+ def Write(packer_type, buf, head, n):
44
+ """Write encodes `n` at buf[head] using `packer_type`."""
45
+ packer_type.pack_into(buf, head, n)
ScaleDF_rebuttal/python_dedup_pkgs/flatbuffers/flexbuffers.py ADDED
@@ -0,0 +1,1592 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Lint as: python3
2
+ # Copyright 2020 Google Inc. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """Implementation of FlexBuffers binary format.
16
+
17
+ For more info check https://google.github.io/flatbuffers/flexbuffers.html and
18
+ corresponding C++ implementation at
19
+ https://github.com/google/flatbuffers/blob/master/include/flatbuffers/flexbuffers.h
20
+ """
21
+
22
+ # pylint: disable=invalid-name
23
+ # TODO(dkovalev): Add type hints everywhere, so tools like pytypes could work.
24
+
25
+ import array
26
+ import contextlib
27
+ import enum
28
+ import struct
29
+
30
+ __all__ = ('Type', 'Builder', 'GetRoot', 'Dumps', 'Loads')
31
+
32
+
33
+ class BitWidth(enum.IntEnum):
34
+ """Supported bit widths of value types.
35
+
36
+ These are used in the lower 2 bits of a type field to determine the size of
37
+ the elements (and or size field) of the item pointed to (e.g. vector).
38
+ """
39
+
40
+ W8 = 0 # 2^0 = 1 byte
41
+ W16 = 1 # 2^1 = 2 bytes
42
+ W32 = 2 # 2^2 = 4 bytes
43
+ W64 = 3 # 2^3 = 8 bytes
44
+
45
+ @staticmethod
46
+ def U(value):
47
+ """Returns the minimum `BitWidth` to encode unsigned integer value."""
48
+ assert value >= 0
49
+
50
+ if value < (1 << 8):
51
+ return BitWidth.W8
52
+ elif value < (1 << 16):
53
+ return BitWidth.W16
54
+ elif value < (1 << 32):
55
+ return BitWidth.W32
56
+ elif value < (1 << 64):
57
+ return BitWidth.W64
58
+ else:
59
+ raise ValueError('value is too big to encode: %s' % value)
60
+
61
+ @staticmethod
62
+ def I(value):
63
+ """Returns the minimum `BitWidth` to encode signed integer value."""
64
+ # -2^(n-1) <= value < 2^(n-1)
65
+ # -2^n <= 2 * value < 2^n
66
+ # 2 * value < 2^n, when value >= 0 or 2 * (-value) <= 2^n, when value < 0
67
+ # 2 * value < 2^n, when value >= 0 or 2 * (-value) - 1 < 2^n, when value < 0
68
+ #
69
+ # if value >= 0:
70
+ # return BitWidth.U(2 * value)
71
+ # else:
72
+ # return BitWidth.U(2 * (-value) - 1) # ~x = -x - 1
73
+ value *= 2
74
+ return BitWidth.U(value if value >= 0 else ~value)
75
+
76
+ @staticmethod
77
+ def F(value):
78
+ """Returns the `BitWidth` to encode floating point value."""
79
+ if struct.unpack('<f', struct.pack('<f', value))[0] == value:
80
+ return BitWidth.W32
81
+ return BitWidth.W64
82
+
83
+ @staticmethod
84
+ def B(byte_width):
85
+ return {1: BitWidth.W8, 2: BitWidth.W16, 4: BitWidth.W32, 8: BitWidth.W64}[
86
+ byte_width
87
+ ]
88
+
89
+
90
+ I = {1: 'b', 2: 'h', 4: 'i', 8: 'q'} # Integer formats
91
+ U = {1: 'B', 2: 'H', 4: 'I', 8: 'Q'} # Unsigned integer formats
92
+ F = {4: 'f', 8: 'd'} # Floating point formats
93
+
94
+
95
+ def _Unpack(fmt, buf):
96
+ return struct.unpack('<%s' % fmt[len(buf)], buf)[0]
97
+
98
+
99
+ def _UnpackVector(fmt, buf, length):
100
+ byte_width = len(buf) // length
101
+ return struct.unpack('<%d%s' % (length, fmt[byte_width]), buf)
102
+
103
+
104
+ def _Pack(fmt, value, byte_width):
105
+ return struct.pack('<%s' % fmt[byte_width], value)
106
+
107
+
108
+ def _PackVector(fmt, values, byte_width):
109
+ return struct.pack('<%d%s' % (len(values), fmt[byte_width]), *values)
110
+
111
+
112
+ def _Mutate(fmt, buf, value, byte_width, value_bit_width):
113
+ if (1 << value_bit_width) <= byte_width:
114
+ buf[:byte_width] = _Pack(fmt, value, byte_width)
115
+ return True
116
+ return False
117
+
118
+
119
+ # Computes how many bytes you'd have to pad to be able to write an
120
+ # "scalar_size" scalar if the buffer had grown to "buf_size",
121
+ # "scalar_size" is a power of two.
122
+ def _PaddingBytes(buf_size, scalar_size):
123
+ # ((buf_size + (scalar_size - 1)) // scalar_size) * scalar_size - buf_size
124
+ return -buf_size & (scalar_size - 1)
125
+
126
+
127
+ def _ShiftSlice(s, offset, length):
128
+ start = offset + (0 if s.start is None else s.start)
129
+ stop = offset + (length if s.stop is None else s.stop)
130
+ return slice(start, stop, s.step)
131
+
132
+
133
+ # https://en.cppreference.com/w/cpp/algorithm/lower_bound
134
+ def _LowerBound(values, value, pred):
135
+ """Implementation of C++ std::lower_bound() algorithm."""
136
+ first, last = 0, len(values)
137
+ count = last - first
138
+ while count > 0:
139
+ i = first
140
+ step = count // 2
141
+ i += step
142
+ if pred(values[i], value):
143
+ i += 1
144
+ first = i
145
+ count -= step + 1
146
+ else:
147
+ count = step
148
+ return first
149
+
150
+
151
+ # https://en.cppreference.com/w/cpp/algorithm/binary_search
152
+ def _BinarySearch(values, value, pred=lambda x, y: x < y):
153
+ """Implementation of C++ std::binary_search() algorithm."""
154
+ index = _LowerBound(values, value, pred)
155
+ if index != len(values) and not pred(value, values[index]):
156
+ return index
157
+ return -1
158
+
159
+
160
+ class Type(enum.IntEnum):
161
+ """Supported types of encoded data.
162
+
163
+ These are used as the upper 6 bits of a type field to indicate the actual
164
+ type.
165
+ """
166
+
167
+ NULL = 0
168
+ INT = 1
169
+ UINT = 2
170
+ FLOAT = 3
171
+ # Types above stored inline, types below store an offset.
172
+ KEY = 4
173
+ STRING = 5
174
+ INDIRECT_INT = 6
175
+ INDIRECT_UINT = 7
176
+ INDIRECT_FLOAT = 8
177
+ MAP = 9
178
+ VECTOR = 10 # Untyped.
179
+
180
+ VECTOR_INT = 11 # Typed any size (stores no type table).
181
+ VECTOR_UINT = 12
182
+ VECTOR_FLOAT = 13
183
+ VECTOR_KEY = 14
184
+ # DEPRECATED, use VECTOR or VECTOR_KEY instead.
185
+ # Read test.cpp/FlexBuffersDeprecatedTest() for details on why.
186
+ VECTOR_STRING_DEPRECATED = 15
187
+
188
+ VECTOR_INT2 = 16 # Typed tuple (no type table, no size field).
189
+ VECTOR_UINT2 = 17
190
+ VECTOR_FLOAT2 = 18
191
+ VECTOR_INT3 = 19 # Typed triple (no type table, no size field).
192
+ VECTOR_UINT3 = 20
193
+ VECTOR_FLOAT3 = 21
194
+ VECTOR_INT4 = 22 # Typed quad (no type table, no size field).
195
+ VECTOR_UINT4 = 23
196
+ VECTOR_FLOAT4 = 24
197
+
198
+ BLOB = 25
199
+ BOOL = 26
200
+ VECTOR_BOOL = 36 # To do the same type of conversion of type to vector type
201
+
202
+ @staticmethod
203
+ def Pack(type_, bit_width):
204
+ return (int(type_) << 2) | bit_width
205
+
206
+ @staticmethod
207
+ def Unpack(packed_type):
208
+ return 1 << (packed_type & 0b11), Type(packed_type >> 2)
209
+
210
+ @staticmethod
211
+ def IsInline(type_):
212
+ return type_ <= Type.FLOAT or type_ == Type.BOOL
213
+
214
+ @staticmethod
215
+ def IsTypedVector(type_):
216
+ return (
217
+ Type.VECTOR_INT <= type_ <= Type.VECTOR_STRING_DEPRECATED
218
+ or type_ == Type.VECTOR_BOOL
219
+ )
220
+
221
+ @staticmethod
222
+ def IsTypedVectorElementType(type_):
223
+ return Type.INT <= type_ <= Type.STRING or type_ == Type.BOOL
224
+
225
+ @staticmethod
226
+ def ToTypedVectorElementType(type_):
227
+ if not Type.IsTypedVector(type_):
228
+ raise ValueError('must be typed vector type')
229
+
230
+ return Type(type_ - Type.VECTOR_INT + Type.INT)
231
+
232
+ @staticmethod
233
+ def IsFixedTypedVector(type_):
234
+ return Type.VECTOR_INT2 <= type_ <= Type.VECTOR_FLOAT4
235
+
236
+ @staticmethod
237
+ def IsFixedTypedVectorElementType(type_):
238
+ return Type.INT <= type_ <= Type.FLOAT
239
+
240
+ @staticmethod
241
+ def ToFixedTypedVectorElementType(type_):
242
+ if not Type.IsFixedTypedVector(type_):
243
+ raise ValueError('must be fixed typed vector type')
244
+
245
+ # 3 types each, starting from length 2.
246
+ fixed_type = type_ - Type.VECTOR_INT2
247
+ return Type(fixed_type % 3 + Type.INT), fixed_type // 3 + 2
248
+
249
+ @staticmethod
250
+ def ToTypedVector(element_type, fixed_len=0):
251
+ """Converts element type to corresponding vector type.
252
+
253
+ Args:
254
+ element_type: vector element type
255
+ fixed_len: number of elements: 0 for typed vector; 2, 3, or 4 for fixed
256
+ typed vector.
257
+
258
+ Returns:
259
+ Typed vector type or fixed typed vector type.
260
+ """
261
+ if fixed_len == 0:
262
+ if not Type.IsTypedVectorElementType(element_type):
263
+ raise ValueError('must be typed vector element type')
264
+ else:
265
+ if not Type.IsFixedTypedVectorElementType(element_type):
266
+ raise ValueError('must be fixed typed vector element type')
267
+
268
+ offset = element_type - Type.INT
269
+ if fixed_len == 0:
270
+ return Type(offset + Type.VECTOR_INT) # TypedVector
271
+ elif fixed_len == 2:
272
+ return Type(offset + Type.VECTOR_INT2) # FixedTypedVector
273
+ elif fixed_len == 3:
274
+ return Type(offset + Type.VECTOR_INT3) # FixedTypedVector
275
+ elif fixed_len == 4:
276
+ return Type(offset + Type.VECTOR_INT4) # FixedTypedVector
277
+ else:
278
+ raise ValueError('unsupported fixed_len: %s' % fixed_len)
279
+
280
+
281
+ class Buf:
282
+ """Class to access underlying buffer object starting from the given offset."""
283
+
284
+ def __init__(self, buf, offset):
285
+ self._buf = buf
286
+ self._offset = offset if offset >= 0 else len(buf) + offset
287
+ self._length = len(buf) - self._offset
288
+
289
+ def __getitem__(self, key):
290
+ if isinstance(key, slice):
291
+ return self._buf[_ShiftSlice(key, self._offset, self._length)]
292
+ elif isinstance(key, int):
293
+ return self._buf[self._offset + key]
294
+ else:
295
+ raise TypeError('invalid key type')
296
+
297
+ def __setitem__(self, key, value):
298
+ if isinstance(key, slice):
299
+ self._buf[_ShiftSlice(key, self._offset, self._length)] = value
300
+ elif isinstance(key, int):
301
+ self._buf[self._offset + key] = key
302
+ else:
303
+ raise TypeError('invalid key type')
304
+
305
+ def __repr__(self):
306
+ return 'buf[%d:]' % self._offset
307
+
308
+ def Find(self, sub):
309
+ """Returns the lowest index where the sub subsequence is found."""
310
+ return self._buf[self._offset :].find(sub)
311
+
312
+ def Slice(self, offset):
313
+ """Returns new `Buf` which starts from the given offset."""
314
+ return Buf(self._buf, self._offset + offset)
315
+
316
+ def Indirect(self, offset, byte_width):
317
+ """Return new `Buf` based on the encoded offset (indirect encoding)."""
318
+ return self.Slice(offset - _Unpack(U, self[offset : offset + byte_width]))
319
+
320
+
321
+ class Object:
322
+ """Base class for all non-trivial data accessors."""
323
+
324
+ __slots__ = '_buf', '_byte_width'
325
+
326
+ def __init__(self, buf, byte_width):
327
+ self._buf = buf
328
+ self._byte_width = byte_width
329
+
330
+ @property
331
+ def ByteWidth(self):
332
+ return self._byte_width
333
+
334
+
335
+ class Sized(Object):
336
+ """Base class for all data accessors which need to read encoded size."""
337
+
338
+ __slots__ = ('_size',)
339
+
340
+ def __init__(self, buf, byte_width, size=0):
341
+ super().__init__(buf, byte_width)
342
+ if size == 0:
343
+ self._size = _Unpack(U, self.SizeBytes)
344
+ else:
345
+ self._size = size
346
+
347
+ @property
348
+ def SizeBytes(self):
349
+ return self._buf[-self._byte_width : 0]
350
+
351
+ def __len__(self):
352
+ return self._size
353
+
354
+
355
+ class Blob(Sized):
356
+ """Data accessor for the encoded blob bytes."""
357
+
358
+ __slots__ = ()
359
+
360
+ @property
361
+ def Bytes(self):
362
+ return self._buf[0 : len(self)]
363
+
364
+ def __repr__(self):
365
+ return 'Blob(%s, size=%d)' % (self._buf, len(self))
366
+
367
+
368
+ class String(Sized):
369
+ """Data accessor for the encoded string bytes."""
370
+
371
+ __slots__ = ()
372
+
373
+ @property
374
+ def Bytes(self):
375
+ return self._buf[0 : len(self)]
376
+
377
+ def Mutate(self, value):
378
+ """Mutates underlying string bytes in place.
379
+
380
+ Args:
381
+ value: New string to replace the existing one. New string must have less
382
+ or equal UTF-8-encoded bytes than the existing one to successfully
383
+ mutate underlying byte buffer.
384
+
385
+ Returns:
386
+ Whether the value was mutated or not.
387
+ """
388
+ encoded = value.encode('utf-8')
389
+ n = len(encoded)
390
+ if n <= len(self):
391
+ self._buf[-self._byte_width : 0] = _Pack(U, n, self._byte_width)
392
+ self._buf[0:n] = encoded
393
+ self._buf[n : len(self)] = bytearray(len(self) - n)
394
+ return True
395
+ return False
396
+
397
+ def __str__(self):
398
+ return self.Bytes.decode('utf-8')
399
+
400
+ def __repr__(self):
401
+ return 'String(%s, size=%d)' % (self._buf, len(self))
402
+
403
+
404
+ class Key(Object):
405
+ """Data accessor for the encoded key bytes."""
406
+
407
+ __slots__ = ()
408
+
409
+ def __init__(self, buf, byte_width):
410
+ assert byte_width == 1
411
+ super().__init__(buf, byte_width)
412
+
413
+ @property
414
+ def Bytes(self):
415
+ return self._buf[0 : len(self)]
416
+
417
+ def __len__(self):
418
+ return self._buf.Find(0)
419
+
420
+ def __str__(self):
421
+ return self.Bytes.decode('ascii')
422
+
423
+ def __repr__(self):
424
+ return 'Key(%s, size=%d)' % (self._buf, len(self))
425
+
426
+
427
+ class Vector(Sized):
428
+ """Data accessor for the encoded vector bytes."""
429
+
430
+ __slots__ = ()
431
+
432
+ def __getitem__(self, index):
433
+ if index < 0 or index >= len(self):
434
+ raise IndexError(
435
+ 'vector index %s is out of [0, %d) range' % (index, len(self))
436
+ )
437
+
438
+ packed_type = self._buf[len(self) * self._byte_width + index]
439
+ buf = self._buf.Slice(index * self._byte_width)
440
+ return Ref.PackedType(buf, self._byte_width, packed_type)
441
+
442
+ @property
443
+ def Value(self):
444
+ """Returns the underlying encoded data as a list object."""
445
+ return [e.Value for e in self]
446
+
447
+ def __repr__(self):
448
+ return 'Vector(%s, byte_width=%d, size=%d)' % (
449
+ self._buf,
450
+ self._byte_width,
451
+ self._size,
452
+ )
453
+
454
+
455
+ class TypedVector(Sized):
456
+ """Data accessor for the encoded typed vector or fixed typed vector bytes."""
457
+
458
+ __slots__ = '_element_type', '_size'
459
+
460
+ def __init__(self, buf, byte_width, element_type, size=0):
461
+ super().__init__(buf, byte_width, size)
462
+
463
+ if element_type == Type.STRING:
464
+ # These can't be accessed as strings, since we don't know the bit-width
465
+ # of the size field, see the declaration of
466
+ # FBT_VECTOR_STRING_DEPRECATED above for details.
467
+ # We change the type here to be keys, which are a subtype of strings,
468
+ # and will ignore the size field. This will truncate strings with
469
+ # embedded nulls.
470
+ element_type = Type.KEY
471
+
472
+ self._element_type = element_type
473
+
474
+ @property
475
+ def Bytes(self):
476
+ return self._buf[: self._byte_width * len(self)]
477
+
478
+ @property
479
+ def ElementType(self):
480
+ return self._element_type
481
+
482
+ def __getitem__(self, index):
483
+ if index < 0 or index >= len(self):
484
+ raise IndexError(
485
+ 'vector index %s is out of [0, %d) range' % (index, len(self))
486
+ )
487
+
488
+ buf = self._buf.Slice(index * self._byte_width)
489
+ return Ref(buf, self._byte_width, 1, self._element_type)
490
+
491
+ @property
492
+ def Value(self):
493
+ """Returns underlying data as list object."""
494
+ if not self:
495
+ return []
496
+
497
+ if self._element_type is Type.BOOL:
498
+ return [bool(e) for e in _UnpackVector(U, self.Bytes, len(self))]
499
+ elif self._element_type is Type.INT:
500
+ return list(_UnpackVector(I, self.Bytes, len(self)))
501
+ elif self._element_type is Type.UINT:
502
+ return list(_UnpackVector(U, self.Bytes, len(self)))
503
+ elif self._element_type is Type.FLOAT:
504
+ return list(_UnpackVector(F, self.Bytes, len(self)))
505
+ elif self._element_type is Type.KEY:
506
+ return [e.AsKey for e in self]
507
+ elif self._element_type is Type.STRING:
508
+ return [e.AsString for e in self]
509
+ else:
510
+ raise TypeError('unsupported element_type: %s' % self._element_type)
511
+
512
+ def __repr__(self):
513
+ return 'TypedVector(%s, byte_width=%d, element_type=%s, size=%d)' % (
514
+ self._buf,
515
+ self._byte_width,
516
+ self._element_type,
517
+ self._size,
518
+ )
519
+
520
+
521
+ class Map(Vector):
522
+ """Data accessor for the encoded map bytes."""
523
+
524
+ @staticmethod
525
+ def CompareKeys(a, b):
526
+ if isinstance(a, Ref):
527
+ a = a.AsKeyBytes
528
+ if isinstance(b, Ref):
529
+ b = b.AsKeyBytes
530
+ return a < b
531
+
532
+ def __getitem__(self, key):
533
+ if isinstance(key, int):
534
+ return super().__getitem__(key)
535
+
536
+ index = _BinarySearch(self.Keys, key.encode('ascii'), self.CompareKeys)
537
+ if index != -1:
538
+ return super().__getitem__(index)
539
+
540
+ raise KeyError(key)
541
+
542
+ @property
543
+ def Keys(self):
544
+ byte_width = _Unpack(
545
+ U, self._buf[-2 * self._byte_width : -self._byte_width]
546
+ )
547
+ buf = self._buf.Indirect(-3 * self._byte_width, self._byte_width)
548
+ return TypedVector(buf, byte_width, Type.KEY)
549
+
550
+ @property
551
+ def Values(self):
552
+ return Vector(self._buf, self._byte_width)
553
+
554
+ @property
555
+ def Value(self):
556
+ return {k.Value: v.Value for k, v in zip(self.Keys, self.Values)}
557
+
558
+ def __repr__(self):
559
+ return 'Map(%s, size=%d)' % (self._buf, len(self))
560
+
561
+
562
+ class Ref:
563
+ """Data accessor for the encoded data bytes."""
564
+
565
+ __slots__ = '_buf', '_parent_width', '_byte_width', '_type'
566
+
567
+ @staticmethod
568
+ def PackedType(buf, parent_width, packed_type):
569
+ byte_width, type_ = Type.Unpack(packed_type)
570
+ return Ref(buf, parent_width, byte_width, type_)
571
+
572
+ def __init__(self, buf, parent_width, byte_width, type_):
573
+ self._buf = buf
574
+ self._parent_width = parent_width
575
+ self._byte_width = byte_width
576
+ self._type = type_
577
+
578
+ def __repr__(self):
579
+ return 'Ref(%s, parent_width=%d, byte_width=%d, type_=%s)' % (
580
+ self._buf,
581
+ self._parent_width,
582
+ self._byte_width,
583
+ self._type,
584
+ )
585
+
586
+ @property
587
+ def _Bytes(self):
588
+ return self._buf[: self._parent_width]
589
+
590
+ def _ConvertError(self, target_type):
591
+ raise TypeError('cannot convert %s to %s' % (self._type, target_type))
592
+
593
+ def _Indirect(self):
594
+ return self._buf.Indirect(0, self._parent_width)
595
+
596
+ @property
597
+ def IsNull(self):
598
+ return self._type is Type.NULL
599
+
600
+ @property
601
+ def IsBool(self):
602
+ return self._type is Type.BOOL
603
+
604
+ @property
605
+ def AsBool(self):
606
+ if self._type is Type.BOOL:
607
+ return bool(_Unpack(U, self._Bytes))
608
+ else:
609
+ return self.AsInt != 0
610
+
611
+ def MutateBool(self, value):
612
+ """Mutates underlying boolean value bytes in place.
613
+
614
+ Args:
615
+ value: New boolean value.
616
+
617
+ Returns:
618
+ Whether the value was mutated or not.
619
+ """
620
+ return self.IsBool and _Mutate(
621
+ U, self._buf, value, self._parent_width, BitWidth.W8
622
+ )
623
+
624
+ @property
625
+ def IsNumeric(self):
626
+ return self.IsInt or self.IsFloat
627
+
628
+ @property
629
+ def IsInt(self):
630
+ return self._type in (
631
+ Type.INT,
632
+ Type.INDIRECT_INT,
633
+ Type.UINT,
634
+ Type.INDIRECT_UINT,
635
+ )
636
+
637
+ @property
638
+ def AsInt(self):
639
+ """Returns current reference as integer value."""
640
+ if self.IsNull:
641
+ return 0
642
+ elif self.IsBool:
643
+ return int(self.AsBool)
644
+ elif self._type is Type.INT:
645
+ return _Unpack(I, self._Bytes)
646
+ elif self._type is Type.INDIRECT_INT:
647
+ return _Unpack(I, self._Indirect()[: self._byte_width])
648
+ if self._type is Type.UINT:
649
+ return _Unpack(U, self._Bytes)
650
+ elif self._type is Type.INDIRECT_UINT:
651
+ return _Unpack(U, self._Indirect()[: self._byte_width])
652
+ elif self.IsString:
653
+ return len(self.AsString)
654
+ elif self.IsKey:
655
+ return len(self.AsKey)
656
+ elif self.IsBlob:
657
+ return len(self.AsBlob)
658
+ elif self.IsVector:
659
+ return len(self.AsVector)
660
+ elif self.IsTypedVector:
661
+ return len(self.AsTypedVector)
662
+ elif self.IsFixedTypedVector:
663
+ return len(self.AsFixedTypedVector)
664
+ else:
665
+ raise self._ConvertError(Type.INT)
666
+
667
+ def MutateInt(self, value):
668
+ """Mutates underlying integer value bytes in place.
669
+
670
+ Args:
671
+ value: New integer value. It must fit to the byte size of the existing
672
+ encoded value.
673
+
674
+ Returns:
675
+ Whether the value was mutated or not.
676
+ """
677
+ if self._type is Type.INT:
678
+ return _Mutate(I, self._buf, value, self._parent_width, BitWidth.I(value))
679
+ elif self._type is Type.INDIRECT_INT:
680
+ return _Mutate(
681
+ I, self._Indirect(), value, self._byte_width, BitWidth.I(value)
682
+ )
683
+ elif self._type is Type.UINT:
684
+ return _Mutate(U, self._buf, value, self._parent_width, BitWidth.U(value))
685
+ elif self._type is Type.INDIRECT_UINT:
686
+ return _Mutate(
687
+ U, self._Indirect(), value, self._byte_width, BitWidth.U(value)
688
+ )
689
+ else:
690
+ return False
691
+
692
+ @property
693
+ def IsFloat(self):
694
+ return self._type in (Type.FLOAT, Type.INDIRECT_FLOAT)
695
+
696
+ @property
697
+ def AsFloat(self):
698
+ """Returns current reference as floating point value."""
699
+ if self.IsNull:
700
+ return 0.0
701
+ elif self.IsBool:
702
+ return float(self.AsBool)
703
+ elif self.IsInt:
704
+ return float(self.AsInt)
705
+ elif self._type is Type.FLOAT:
706
+ return _Unpack(F, self._Bytes)
707
+ elif self._type is Type.INDIRECT_FLOAT:
708
+ return _Unpack(F, self._Indirect()[: self._byte_width])
709
+ elif self.IsString:
710
+ return float(self.AsString)
711
+ elif self.IsVector:
712
+ return float(len(self.AsVector))
713
+ elif self.IsTypedVector():
714
+ return float(len(self.AsTypedVector))
715
+ elif self.IsFixedTypedVector():
716
+ return float(len(self.FixedTypedVector))
717
+ else:
718
+ raise self._ConvertError(Type.FLOAT)
719
+
720
+ def MutateFloat(self, value):
721
+ """Mutates underlying floating point value bytes in place.
722
+
723
+ Args:
724
+ value: New float value. It must fit to the byte size of the existing
725
+ encoded value.
726
+
727
+ Returns:
728
+ Whether the value was mutated or not.
729
+ """
730
+ if self._type is Type.FLOAT:
731
+ return _Mutate(
732
+ F,
733
+ self._buf,
734
+ value,
735
+ self._parent_width,
736
+ BitWidth.B(self._parent_width),
737
+ )
738
+ elif self._type is Type.INDIRECT_FLOAT:
739
+ return _Mutate(
740
+ F,
741
+ self._Indirect(),
742
+ value,
743
+ self._byte_width,
744
+ BitWidth.B(self._byte_width),
745
+ )
746
+ else:
747
+ return False
748
+
749
+ @property
750
+ def IsKey(self):
751
+ return self._type is Type.KEY
752
+
753
+ @property
754
+ def AsKeyBytes(self):
755
+ if self.IsKey:
756
+ return Key(self._Indirect(), self._byte_width).Bytes
757
+ else:
758
+ raise self._ConvertError(Type.KEY)
759
+
760
+ @property
761
+ def AsKey(self):
762
+ if self.IsKey:
763
+ return str(Key(self._Indirect(), self._byte_width))
764
+ else:
765
+ raise self._ConvertError(Type.KEY)
766
+
767
+ @property
768
+ def IsString(self):
769
+ return self._type is Type.STRING
770
+
771
+ @property
772
+ def AsStringBytes(self):
773
+ if self.IsString:
774
+ return String(self._Indirect(), self._byte_width).Bytes
775
+ elif self.IsKey:
776
+ return self.AsKeyBytes
777
+ else:
778
+ raise self._ConvertError(Type.STRING)
779
+
780
+ @property
781
+ def AsString(self):
782
+ if self.IsString:
783
+ return str(String(self._Indirect(), self._byte_width))
784
+ elif self.IsKey:
785
+ return self.AsKey
786
+ else:
787
+ raise self._ConvertError(Type.STRING)
788
+
789
+ def MutateString(self, value):
790
+ return String(self._Indirect(), self._byte_width).Mutate(value)
791
+
792
+ @property
793
+ def IsBlob(self):
794
+ return self._type is Type.BLOB
795
+
796
+ @property
797
+ def AsBlob(self):
798
+ if self.IsBlob:
799
+ return Blob(self._Indirect(), self._byte_width).Bytes
800
+ else:
801
+ raise self._ConvertError(Type.BLOB)
802
+
803
+ @property
804
+ def IsAnyVector(self):
805
+ return self.IsVector or self.IsTypedVector or self.IsFixedTypedVector()
806
+
807
+ @property
808
+ def IsVector(self):
809
+ return self._type in (Type.VECTOR, Type.MAP)
810
+
811
+ @property
812
+ def AsVector(self):
813
+ if self.IsVector:
814
+ return Vector(self._Indirect(), self._byte_width)
815
+ else:
816
+ raise self._ConvertError(Type.VECTOR)
817
+
818
+ @property
819
+ def IsTypedVector(self):
820
+ return Type.IsTypedVector(self._type)
821
+
822
+ @property
823
+ def AsTypedVector(self):
824
+ if self.IsTypedVector:
825
+ return TypedVector(
826
+ self._Indirect(),
827
+ self._byte_width,
828
+ Type.ToTypedVectorElementType(self._type),
829
+ )
830
+ else:
831
+ raise self._ConvertError('TYPED_VECTOR')
832
+
833
+ @property
834
+ def IsFixedTypedVector(self):
835
+ return Type.IsFixedTypedVector(self._type)
836
+
837
+ @property
838
+ def AsFixedTypedVector(self):
839
+ if self.IsFixedTypedVector:
840
+ element_type, size = Type.ToFixedTypedVectorElementType(self._type)
841
+ return TypedVector(self._Indirect(), self._byte_width, element_type, size)
842
+ else:
843
+ raise self._ConvertError('FIXED_TYPED_VECTOR')
844
+
845
+ @property
846
+ def IsMap(self):
847
+ return self._type is Type.MAP
848
+
849
+ @property
850
+ def AsMap(self):
851
+ if self.IsMap:
852
+ return Map(self._Indirect(), self._byte_width)
853
+ else:
854
+ raise self._ConvertError(Type.MAP)
855
+
856
+ @property
857
+ def Value(self):
858
+ """Converts current reference to value of corresponding type.
859
+
860
+ This is equivalent to calling `AsInt` for integer values, `AsFloat` for
861
+ floating point values, etc.
862
+
863
+ Returns:
864
+ Value of corresponding type.
865
+ """
866
+ if self.IsNull:
867
+ return None
868
+ elif self.IsBool:
869
+ return self.AsBool
870
+ elif self.IsInt:
871
+ return self.AsInt
872
+ elif self.IsFloat:
873
+ return self.AsFloat
874
+ elif self.IsString:
875
+ return self.AsString
876
+ elif self.IsKey:
877
+ return self.AsKey
878
+ elif self.IsBlob:
879
+ return self.AsBlob
880
+ elif self.IsMap:
881
+ return self.AsMap.Value
882
+ elif self.IsVector:
883
+ return self.AsVector.Value
884
+ elif self.IsTypedVector:
885
+ return self.AsTypedVector.Value
886
+ elif self.IsFixedTypedVector:
887
+ return self.AsFixedTypedVector.Value
888
+ else:
889
+ raise TypeError('cannot convert %r to value' % self)
890
+
891
+
892
+ def _IsIterable(obj):
893
+ try:
894
+ iter(obj)
895
+ return True
896
+ except TypeError:
897
+ return False
898
+
899
+
900
+ class Value:
901
+ """Class to represent given value during the encoding process."""
902
+
903
+ @staticmethod
904
+ def Null():
905
+ return Value(0, Type.NULL, BitWidth.W8)
906
+
907
+ @staticmethod
908
+ def Bool(value):
909
+ return Value(value, Type.BOOL, BitWidth.W8)
910
+
911
+ @staticmethod
912
+ def Int(value, bit_width):
913
+ return Value(value, Type.INT, bit_width)
914
+
915
+ @staticmethod
916
+ def UInt(value, bit_width):
917
+ return Value(value, Type.UINT, bit_width)
918
+
919
+ @staticmethod
920
+ def Float(value, bit_width):
921
+ return Value(value, Type.FLOAT, bit_width)
922
+
923
+ @staticmethod
924
+ def Key(offset):
925
+ return Value(offset, Type.KEY, BitWidth.W8)
926
+
927
+ def __init__(self, value, type_, min_bit_width):
928
+ self._value = value
929
+ self._type = type_
930
+
931
+ # For scalars: of itself, for vector: of its elements, for string: length.
932
+ self._min_bit_width = min_bit_width
933
+
934
+ @property
935
+ def Value(self):
936
+ return self._value
937
+
938
+ @property
939
+ def Type(self):
940
+ return self._type
941
+
942
+ @property
943
+ def MinBitWidth(self):
944
+ return self._min_bit_width
945
+
946
+ def StoredPackedType(self, parent_bit_width=BitWidth.W8):
947
+ return Type.Pack(self._type, self.StoredWidth(parent_bit_width))
948
+
949
+ # We have an absolute offset, but want to store a relative offset
950
+ # elem_index elements beyond the current buffer end. Since whether
951
+ # the relative offset fits in a certain byte_width depends on
952
+ # the size of the elements before it (and their alignment), we have
953
+ # to test for each size in turn.
954
+ def ElemWidth(self, buf_size, elem_index=0):
955
+ if Type.IsInline(self._type):
956
+ return self._min_bit_width
957
+ for byte_width in 1, 2, 4, 8:
958
+ offset_loc = (
959
+ buf_size
960
+ + _PaddingBytes(buf_size, byte_width)
961
+ + elem_index * byte_width
962
+ )
963
+ bit_width = BitWidth.U(offset_loc - self._value)
964
+ if byte_width == (1 << bit_width):
965
+ return bit_width
966
+ raise ValueError('relative offset is too big')
967
+
968
+ def StoredWidth(self, parent_bit_width=BitWidth.W8):
969
+ if Type.IsInline(self._type):
970
+ return max(self._min_bit_width, parent_bit_width)
971
+ return self._min_bit_width
972
+
973
+ def __repr__(self):
974
+ return 'Value(%s, %s, %s)' % (self._value, self._type, self._min_bit_width)
975
+
976
+ def __str__(self):
977
+ return str(self._value)
978
+
979
+
980
+ def InMap(func):
981
+ def wrapper(self, *args, **kwargs):
982
+ if isinstance(args[0], str):
983
+ self.Key(args[0])
984
+ func(self, *args[1:], **kwargs)
985
+ else:
986
+ func(self, *args, **kwargs)
987
+
988
+ return wrapper
989
+
990
+
991
+ def InMapForString(func):
992
+ def wrapper(self, *args):
993
+ if len(args) == 1:
994
+ func(self, args[0])
995
+ elif len(args) == 2:
996
+ self.Key(args[0])
997
+ func(self, args[1])
998
+ else:
999
+ raise ValueError('invalid number of arguments')
1000
+
1001
+ return wrapper
1002
+
1003
+
1004
+ class Pool:
1005
+ """Collection of (data, offset) pairs sorted by data for quick access."""
1006
+
1007
+ def __init__(self):
1008
+ self._pool = [] # sorted list of (data, offset) tuples
1009
+
1010
+ def FindOrInsert(self, data, offset):
1011
+ do = data, offset
1012
+ index = _BinarySearch(self._pool, do, lambda a, b: a[0] < b[0])
1013
+ if index != -1:
1014
+ _, offset = self._pool[index]
1015
+ return offset
1016
+ self._pool.insert(index, do)
1017
+ return None
1018
+
1019
+ def Clear(self):
1020
+ self._pool = []
1021
+
1022
+ @property
1023
+ def Elements(self):
1024
+ return [data for data, _ in self._pool]
1025
+
1026
+
1027
+ class Builder:
1028
+ """Helper class to encode structural data into flexbuffers format."""
1029
+
1030
+ def __init__(
1031
+ self,
1032
+ share_strings=False,
1033
+ share_keys=True,
1034
+ force_min_bit_width=BitWidth.W8,
1035
+ ):
1036
+ self._share_strings = share_strings
1037
+ self._share_keys = share_keys
1038
+ self._force_min_bit_width = force_min_bit_width
1039
+
1040
+ self._string_pool = Pool()
1041
+ self._key_pool = Pool()
1042
+
1043
+ self._finished = False
1044
+ self._buf = bytearray()
1045
+ self._stack = []
1046
+
1047
+ def __len__(self):
1048
+ return len(self._buf)
1049
+
1050
+ @property
1051
+ def StringPool(self):
1052
+ return self._string_pool
1053
+
1054
+ @property
1055
+ def KeyPool(self):
1056
+ return self._key_pool
1057
+
1058
+ def Clear(self):
1059
+ self._string_pool.Clear()
1060
+ self._key_pool.Clear()
1061
+ self._finished = False
1062
+ self._buf = bytearray()
1063
+ self._stack = []
1064
+
1065
+ def Finish(self):
1066
+ """Finishes encoding process and returns underlying buffer."""
1067
+ if self._finished:
1068
+ raise RuntimeError('builder has been already finished')
1069
+
1070
+ # If you hit this exception, you likely have objects that were never
1071
+ # included in a parent. You need to have exactly one root to finish a
1072
+ # buffer. Check your Start/End calls are matched, and all objects are inside
1073
+ # some other object.
1074
+ if len(self._stack) != 1:
1075
+ raise RuntimeError('internal stack size must be one')
1076
+
1077
+ value = self._stack[0]
1078
+ byte_width = self._Align(value.ElemWidth(len(self._buf)))
1079
+ self._WriteAny(value, byte_width=byte_width) # Root value
1080
+ self._Write(U, value.StoredPackedType(), byte_width=1) # Root type
1081
+ self._Write(U, byte_width, byte_width=1) # Root size
1082
+
1083
+ self.finished = True
1084
+ return self._buf
1085
+
1086
+ def _ReadKey(self, offset):
1087
+ key = self._buf[offset:]
1088
+ return key[: key.find(0)]
1089
+
1090
+ def _Align(self, alignment):
1091
+ byte_width = 1 << alignment
1092
+ self._buf.extend(b'\x00' * _PaddingBytes(len(self._buf), byte_width))
1093
+ return byte_width
1094
+
1095
+ def _Write(self, fmt, value, byte_width):
1096
+ self._buf.extend(_Pack(fmt, value, byte_width))
1097
+
1098
+ def _WriteVector(self, fmt, values, byte_width):
1099
+ self._buf.extend(_PackVector(fmt, values, byte_width))
1100
+
1101
+ def _WriteOffset(self, offset, byte_width):
1102
+ relative_offset = len(self._buf) - offset
1103
+ assert byte_width == 8 or relative_offset < (1 << (8 * byte_width))
1104
+ self._Write(U, relative_offset, byte_width)
1105
+
1106
+ def _WriteAny(self, value, byte_width):
1107
+ fmt = {
1108
+ Type.NULL: U,
1109
+ Type.BOOL: U,
1110
+ Type.INT: I,
1111
+ Type.UINT: U,
1112
+ Type.FLOAT: F,
1113
+ }.get(value.Type)
1114
+ if fmt:
1115
+ self._Write(fmt, value.Value, byte_width)
1116
+ else:
1117
+ self._WriteOffset(value.Value, byte_width)
1118
+
1119
+ def _WriteBlob(self, data, append_zero, type_):
1120
+ bit_width = BitWidth.U(len(data))
1121
+ byte_width = self._Align(bit_width)
1122
+ self._Write(U, len(data), byte_width)
1123
+ loc = len(self._buf)
1124
+ self._buf.extend(data)
1125
+ if append_zero:
1126
+ self._buf.append(0)
1127
+ self._stack.append(Value(loc, type_, bit_width))
1128
+ return loc
1129
+
1130
+ def _WriteScalarVector(self, element_type, byte_width, elements, fixed):
1131
+ """Writes scalar vector elements to the underlying buffer."""
1132
+ bit_width = BitWidth.B(byte_width)
1133
+ # If you get this exception, you're trying to write a vector with a size
1134
+ # field that is bigger than the scalars you're trying to write (e.g. a
1135
+ # byte vector > 255 elements). For such types, write a "blob" instead.
1136
+ if BitWidth.U(len(elements)) > bit_width:
1137
+ raise ValueError('too many elements for the given byte_width')
1138
+
1139
+ self._Align(bit_width)
1140
+ if not fixed:
1141
+ self._Write(U, len(elements), byte_width)
1142
+
1143
+ loc = len(self._buf)
1144
+
1145
+ fmt = {Type.INT: I, Type.UINT: U, Type.FLOAT: F}.get(element_type)
1146
+ if not fmt:
1147
+ raise TypeError('unsupported element_type')
1148
+ self._WriteVector(fmt, elements, byte_width)
1149
+
1150
+ type_ = Type.ToTypedVector(element_type, len(elements) if fixed else 0)
1151
+ self._stack.append(Value(loc, type_, bit_width))
1152
+ return loc
1153
+
1154
+ def _CreateVector(self, elements, typed, fixed, keys=None):
1155
+ """Writes vector elements to the underlying buffer."""
1156
+ length = len(elements)
1157
+
1158
+ if fixed and not typed:
1159
+ raise ValueError('fixed vector must be typed')
1160
+
1161
+ # Figure out smallest bit width we can store this vector with.
1162
+ bit_width = max(self._force_min_bit_width, BitWidth.U(length))
1163
+ prefix_elems = 1 # Vector size
1164
+ if keys:
1165
+ bit_width = max(bit_width, keys.ElemWidth(len(self._buf)))
1166
+ prefix_elems += 2 # Offset to the keys vector and its byte width.
1167
+
1168
+ vector_type = Type.KEY
1169
+ # Check bit widths and types for all elements.
1170
+ for i, e in enumerate(elements):
1171
+ bit_width = max(bit_width, e.ElemWidth(len(self._buf), prefix_elems + i))
1172
+
1173
+ if typed:
1174
+ if i == 0:
1175
+ vector_type = e.Type
1176
+ else:
1177
+ if vector_type != e.Type:
1178
+ raise RuntimeError('typed vector elements must be of the same type')
1179
+
1180
+ if fixed and not Type.IsFixedTypedVectorElementType(vector_type):
1181
+ raise RuntimeError('must be fixed typed vector element type')
1182
+
1183
+ byte_width = self._Align(bit_width)
1184
+ # Write vector. First the keys width/offset if available, and size.
1185
+ if keys:
1186
+ self._WriteOffset(keys.Value, byte_width)
1187
+ self._Write(U, 1 << keys.MinBitWidth, byte_width)
1188
+
1189
+ if not fixed:
1190
+ self._Write(U, length, byte_width)
1191
+
1192
+ # Then the actual data.
1193
+ loc = len(self._buf)
1194
+ for e in elements:
1195
+ self._WriteAny(e, byte_width)
1196
+
1197
+ # Then the types.
1198
+ if not typed:
1199
+ for e in elements:
1200
+ self._buf.append(e.StoredPackedType(bit_width))
1201
+
1202
+ if keys:
1203
+ type_ = Type.MAP
1204
+ else:
1205
+ if typed:
1206
+ type_ = Type.ToTypedVector(vector_type, length if fixed else 0)
1207
+ else:
1208
+ type_ = Type.VECTOR
1209
+
1210
+ return Value(loc, type_, bit_width)
1211
+
1212
+ def _PushIndirect(self, value, type_, bit_width):
1213
+ byte_width = self._Align(bit_width)
1214
+ loc = len(self._buf)
1215
+ fmt = {Type.INDIRECT_INT: I, Type.INDIRECT_UINT: U, Type.INDIRECT_FLOAT: F}[
1216
+ type_
1217
+ ]
1218
+ self._Write(fmt, value, byte_width)
1219
+ self._stack.append(Value(loc, type_, bit_width))
1220
+
1221
+ @InMapForString
1222
+ def String(self, value):
1223
+ """Encodes string value."""
1224
+ reset_to = len(self._buf)
1225
+ encoded = value.encode('utf-8')
1226
+ loc = self._WriteBlob(encoded, append_zero=True, type_=Type.STRING)
1227
+ if self._share_strings:
1228
+ prev_loc = self._string_pool.FindOrInsert(encoded, loc)
1229
+ if prev_loc is not None:
1230
+ del self._buf[reset_to:]
1231
+ self._stack[-1]._value = loc = prev_loc # pylint: disable=protected-access
1232
+
1233
+ return loc
1234
+
1235
+ @InMap
1236
+ def Blob(self, value):
1237
+ """Encodes binary blob value.
1238
+
1239
+ Args:
1240
+ value: A byte/bytearray value to encode
1241
+
1242
+ Returns:
1243
+ Offset of the encoded value in underlying the byte buffer.
1244
+ """
1245
+ return self._WriteBlob(value, append_zero=False, type_=Type.BLOB)
1246
+
1247
+ def Key(self, value):
1248
+ """Encodes key value.
1249
+
1250
+ Args:
1251
+ value: A byte/bytearray/str value to encode. Byte object must not contain
1252
+ zero bytes. String object must be convertible to ASCII.
1253
+
1254
+ Returns:
1255
+ Offset of the encoded value in the underlying byte buffer.
1256
+ """
1257
+ if isinstance(value, (bytes, bytearray)):
1258
+ encoded = value
1259
+ else:
1260
+ encoded = value.encode('ascii')
1261
+
1262
+ if 0 in encoded:
1263
+ raise ValueError('key contains zero byte')
1264
+
1265
+ loc = len(self._buf)
1266
+ self._buf.extend(encoded)
1267
+ self._buf.append(0)
1268
+ if self._share_keys:
1269
+ prev_loc = self._key_pool.FindOrInsert(encoded, loc)
1270
+ if prev_loc is not None:
1271
+ del self._buf[loc:]
1272
+ loc = prev_loc
1273
+
1274
+ self._stack.append(Value.Key(loc))
1275
+ return loc
1276
+
1277
+ def Null(self, key=None):
1278
+ """Encodes None value."""
1279
+ if key:
1280
+ self.Key(key)
1281
+ self._stack.append(Value.Null())
1282
+
1283
+ @InMap
1284
+ def Bool(self, value):
1285
+ """Encodes boolean value.
1286
+
1287
+ Args:
1288
+ value: A boolean value.
1289
+ """
1290
+ self._stack.append(Value.Bool(value))
1291
+
1292
+ @InMap
1293
+ def Int(self, value, byte_width=0):
1294
+ """Encodes signed integer value.
1295
+
1296
+ Args:
1297
+ value: A signed integer value.
1298
+ byte_width: Number of bytes to use: 1, 2, 4, or 8.
1299
+ """
1300
+ bit_width = BitWidth.I(value) if byte_width == 0 else BitWidth.B(byte_width)
1301
+ self._stack.append(Value.Int(value, bit_width))
1302
+
1303
+ @InMap
1304
+ def IndirectInt(self, value, byte_width=0):
1305
+ """Encodes signed integer value indirectly.
1306
+
1307
+ Args:
1308
+ value: A signed integer value.
1309
+ byte_width: Number of bytes to use: 1, 2, 4, or 8.
1310
+ """
1311
+ bit_width = BitWidth.I(value) if byte_width == 0 else BitWidth.B(byte_width)
1312
+ self._PushIndirect(value, Type.INDIRECT_INT, bit_width)
1313
+
1314
+ @InMap
1315
+ def UInt(self, value, byte_width=0):
1316
+ """Encodes unsigned integer value.
1317
+
1318
+ Args:
1319
+ value: An unsigned integer value.
1320
+ byte_width: Number of bytes to use: 1, 2, 4, or 8.
1321
+ """
1322
+ bit_width = BitWidth.U(value) if byte_width == 0 else BitWidth.B(byte_width)
1323
+ self._stack.append(Value.UInt(value, bit_width))
1324
+
1325
+ @InMap
1326
+ def IndirectUInt(self, value, byte_width=0):
1327
+ """Encodes unsigned integer value indirectly.
1328
+
1329
+ Args:
1330
+ value: An unsigned integer value.
1331
+ byte_width: Number of bytes to use: 1, 2, 4, or 8.
1332
+ """
1333
+ bit_width = BitWidth.U(value) if byte_width == 0 else BitWidth.B(byte_width)
1334
+ self._PushIndirect(value, Type.INDIRECT_UINT, bit_width)
1335
+
1336
+ @InMap
1337
+ def Float(self, value, byte_width=0):
1338
+ """Encodes floating point value.
1339
+
1340
+ Args:
1341
+ value: A floating point value.
1342
+ byte_width: Number of bytes to use: 4 or 8.
1343
+ """
1344
+ bit_width = BitWidth.F(value) if byte_width == 0 else BitWidth.B(byte_width)
1345
+ self._stack.append(Value.Float(value, bit_width))
1346
+
1347
+ @InMap
1348
+ def IndirectFloat(self, value, byte_width=0):
1349
+ """Encodes floating point value indirectly.
1350
+
1351
+ Args:
1352
+ value: A floating point value.
1353
+ byte_width: Number of bytes to use: 4 or 8.
1354
+ """
1355
+ bit_width = BitWidth.F(value) if byte_width == 0 else BitWidth.B(byte_width)
1356
+ self._PushIndirect(value, Type.INDIRECT_FLOAT, bit_width)
1357
+
1358
+ def _StartVector(self):
1359
+ """Starts vector construction."""
1360
+ return len(self._stack)
1361
+
1362
+ def _EndVector(self, start, typed, fixed):
1363
+ """Finishes vector construction by encodung its elements."""
1364
+ vec = self._CreateVector(self._stack[start:], typed, fixed)
1365
+ del self._stack[start:]
1366
+ self._stack.append(vec)
1367
+ return vec.Value
1368
+
1369
+ @contextlib.contextmanager
1370
+ def Vector(self, key=None):
1371
+ if key:
1372
+ self.Key(key)
1373
+
1374
+ try:
1375
+ start = self._StartVector()
1376
+ yield self
1377
+ finally:
1378
+ self._EndVector(start, typed=False, fixed=False)
1379
+
1380
+ @InMap
1381
+ def VectorFromElements(self, elements):
1382
+ """Encodes sequence of any elements as a vector.
1383
+
1384
+ Args:
1385
+ elements: sequence of elements, they may have different types.
1386
+ """
1387
+ with self.Vector():
1388
+ for e in elements:
1389
+ self.Add(e)
1390
+
1391
+ @contextlib.contextmanager
1392
+ def TypedVector(self, key=None):
1393
+ if key:
1394
+ self.Key(key)
1395
+
1396
+ try:
1397
+ start = self._StartVector()
1398
+ yield self
1399
+ finally:
1400
+ self._EndVector(start, typed=True, fixed=False)
1401
+
1402
+ @InMap
1403
+ def TypedVectorFromElements(self, elements, element_type=None):
1404
+ """Encodes sequence of elements of the same type as typed vector.
1405
+
1406
+ Args:
1407
+ elements: Sequence of elements, they must be of the same type.
1408
+ element_type: Suggested element type. Setting it to None means determining
1409
+ correct value automatically based on the given elements.
1410
+ """
1411
+ if isinstance(elements, array.array):
1412
+ if elements.typecode == 'f':
1413
+ self._WriteScalarVector(Type.FLOAT, 4, elements, fixed=False)
1414
+ elif elements.typecode == 'd':
1415
+ self._WriteScalarVector(Type.FLOAT, 8, elements, fixed=False)
1416
+ elif elements.typecode in ('b', 'h', 'i', 'l', 'q'):
1417
+ self._WriteScalarVector(
1418
+ Type.INT, elements.itemsize, elements, fixed=False
1419
+ )
1420
+ elif elements.typecode in ('B', 'H', 'I', 'L', 'Q'):
1421
+ self._WriteScalarVector(
1422
+ Type.UINT, elements.itemsize, elements, fixed=False
1423
+ )
1424
+ else:
1425
+ raise ValueError('unsupported array typecode: %s' % elements.typecode)
1426
+ else:
1427
+ add = self.Add if element_type is None else self.Adder(element_type)
1428
+ with self.TypedVector():
1429
+ for e in elements:
1430
+ add(e)
1431
+
1432
+ @InMap
1433
+ def FixedTypedVectorFromElements(
1434
+ self, elements, element_type=None, byte_width=0
1435
+ ):
1436
+ """Encodes sequence of elements of the same type as fixed typed vector.
1437
+
1438
+ Args:
1439
+ elements: Sequence of elements, they must be of the same type. Allowed
1440
+ types are `Type.INT`, `Type.UINT`, `Type.FLOAT`. Allowed number of
1441
+ elements are 2, 3, or 4.
1442
+ element_type: Suggested element type. Setting it to None means determining
1443
+ correct value automatically based on the given elements.
1444
+ byte_width: Number of bytes to use per element. For `Type.INT` and
1445
+ `Type.UINT`: 1, 2, 4, or 8. For `Type.FLOAT`: 4 or 8. Setting it to 0
1446
+ means determining correct value automatically based on the given
1447
+ elements.
1448
+ """
1449
+ if not 2 <= len(elements) <= 4:
1450
+ raise ValueError('only 2, 3, or 4 elements are supported')
1451
+
1452
+ types = {type(e) for e in elements}
1453
+ if len(types) != 1:
1454
+ raise TypeError('all elements must be of the same type')
1455
+
1456
+ (type_,) = types
1457
+
1458
+ if element_type is None:
1459
+ element_type = {int: Type.INT, float: Type.FLOAT}.get(type_)
1460
+ if not element_type:
1461
+ raise TypeError('unsupported element_type: %s' % type_)
1462
+
1463
+ if byte_width == 0:
1464
+ width = {
1465
+ Type.UINT: BitWidth.U,
1466
+ Type.INT: BitWidth.I,
1467
+ Type.FLOAT: BitWidth.F,
1468
+ }[element_type]
1469
+ byte_width = 1 << max(width(e) for e in elements)
1470
+
1471
+ self._WriteScalarVector(element_type, byte_width, elements, fixed=True)
1472
+
1473
+ def _StartMap(self):
1474
+ """Starts map construction."""
1475
+ return len(self._stack)
1476
+
1477
+ def _EndMap(self, start):
1478
+ """Finishes map construction by encodung its elements."""
1479
+ # Interleaved keys and values on the stack.
1480
+ stack = self._stack[start:]
1481
+
1482
+ if len(stack) % 2 != 0:
1483
+ raise RuntimeError('must be even number of keys and values')
1484
+
1485
+ for key in stack[::2]:
1486
+ if key.Type is not Type.KEY:
1487
+ raise RuntimeError('all map keys must be of %s type' % Type.KEY)
1488
+
1489
+ pairs = zip(stack[::2], stack[1::2]) # [(key, value), ...]
1490
+ pairs = sorted(pairs, key=lambda pair: self._ReadKey(pair[0].Value))
1491
+
1492
+ del self._stack[start:]
1493
+ for pair in pairs:
1494
+ self._stack.extend(pair)
1495
+
1496
+ keys = self._CreateVector(self._stack[start::2], typed=True, fixed=False)
1497
+ values = self._CreateVector(
1498
+ self._stack[start + 1 :: 2], typed=False, fixed=False, keys=keys
1499
+ )
1500
+
1501
+ del self._stack[start:]
1502
+ self._stack.append(values)
1503
+ return values.Value
1504
+
1505
+ @contextlib.contextmanager
1506
+ def Map(self, key=None):
1507
+ if key:
1508
+ self.Key(key)
1509
+
1510
+ try:
1511
+ start = self._StartMap()
1512
+ yield self
1513
+ finally:
1514
+ self._EndMap(start)
1515
+
1516
+ def MapFromElements(self, elements):
1517
+ start = self._StartMap()
1518
+ for k, v in elements.items():
1519
+ self.Key(k)
1520
+ self.Add(v)
1521
+ self._EndMap(start)
1522
+
1523
+ def Adder(self, type_):
1524
+ return {
1525
+ Type.BOOL: self.Bool,
1526
+ Type.INT: self.Int,
1527
+ Type.INDIRECT_INT: self.IndirectInt,
1528
+ Type.UINT: self.UInt,
1529
+ Type.INDIRECT_UINT: self.IndirectUInt,
1530
+ Type.FLOAT: self.Float,
1531
+ Type.INDIRECT_FLOAT: self.IndirectFloat,
1532
+ Type.KEY: self.Key,
1533
+ Type.BLOB: self.Blob,
1534
+ Type.STRING: self.String,
1535
+ }[type_]
1536
+
1537
+ @InMapForString
1538
+ def Add(self, value):
1539
+ """Encodes value of any supported type."""
1540
+ if value is None:
1541
+ self.Null()
1542
+ elif isinstance(value, bool):
1543
+ self.Bool(value)
1544
+ elif isinstance(value, int):
1545
+ self.Int(value)
1546
+ elif isinstance(value, float):
1547
+ self.Float(value)
1548
+ elif isinstance(value, str):
1549
+ self.String(value)
1550
+ elif isinstance(value, (bytes, bytearray)):
1551
+ self.Blob(value)
1552
+ elif isinstance(value, dict):
1553
+ with self.Map():
1554
+ for k, v in value.items():
1555
+ self.Key(k)
1556
+ self.Add(v)
1557
+ elif isinstance(value, array.array):
1558
+ self.TypedVectorFromElements(value)
1559
+ elif _IsIterable(value):
1560
+ self.VectorFromElements(value)
1561
+ else:
1562
+ raise TypeError('unsupported python type: %s' % type(value))
1563
+
1564
+ @property
1565
+ def LastValue(self):
1566
+ return self._stack[-1]
1567
+
1568
+ @InMap
1569
+ def ReuseValue(self, value):
1570
+ self._stack.append(value)
1571
+
1572
+
1573
+ def GetRoot(buf):
1574
+ """Returns root `Ref` object for the given buffer."""
1575
+ if len(buf) < 3:
1576
+ raise ValueError('buffer is too small')
1577
+ byte_width = buf[-1]
1578
+ return Ref.PackedType(
1579
+ Buf(buf, -(2 + byte_width)), byte_width, packed_type=buf[-2]
1580
+ )
1581
+
1582
+
1583
+ def Dumps(obj):
1584
+ """Returns bytearray with the encoded python object."""
1585
+ fbb = Builder()
1586
+ fbb.Add(obj)
1587
+ return fbb.Finish()
1588
+
1589
+
1590
+ def Loads(buf):
1591
+ """Returns python object decoded from the buffer."""
1592
+ return GetRoot(buf).Value
ScaleDF_rebuttal/python_dedup_pkgs/flatbuffers/number_types.py ADDED
@@ -0,0 +1,182 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2014 Google Inc. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import collections
16
+ import struct
17
+
18
+ from . import packer
19
+ from .compat import NumpyRequiredForThisFeature, import_numpy
20
+
21
+ np = import_numpy()
22
+
23
+ # For reference, see:
24
+ # https://docs.python.org/2/library/ctypes.html#ctypes-fundamental-data-types-2
25
+
26
+ # These classes could be collections.namedtuple instances, but those are new
27
+ # in 2.6 and we want to work towards 2.5 compatability.
28
+
29
+
30
+ class BoolFlags(object):
31
+ bytewidth = 1
32
+ min_val = False
33
+ max_val = True
34
+ py_type = bool
35
+ name = "bool"
36
+ packer_type = packer.boolean
37
+
38
+
39
+ class Uint8Flags(object):
40
+ bytewidth = 1
41
+ min_val = 0
42
+ max_val = (2**8) - 1
43
+ py_type = int
44
+ name = "uint8"
45
+ packer_type = packer.uint8
46
+
47
+
48
+ class Uint16Flags(object):
49
+ bytewidth = 2
50
+ min_val = 0
51
+ max_val = (2**16) - 1
52
+ py_type = int
53
+ name = "uint16"
54
+ packer_type = packer.uint16
55
+
56
+
57
+ class Uint32Flags(object):
58
+ bytewidth = 4
59
+ min_val = 0
60
+ max_val = (2**32) - 1
61
+ py_type = int
62
+ name = "uint32"
63
+ packer_type = packer.uint32
64
+
65
+
66
+ class Uint64Flags(object):
67
+ bytewidth = 8
68
+ min_val = 0
69
+ max_val = (2**64) - 1
70
+ py_type = int
71
+ name = "uint64"
72
+ packer_type = packer.uint64
73
+
74
+
75
+ class Int8Flags(object):
76
+ bytewidth = 1
77
+ min_val = -(2**7)
78
+ max_val = (2**7) - 1
79
+ py_type = int
80
+ name = "int8"
81
+ packer_type = packer.int8
82
+
83
+
84
+ class Int16Flags(object):
85
+ bytewidth = 2
86
+ min_val = -(2**15)
87
+ max_val = (2**15) - 1
88
+ py_type = int
89
+ name = "int16"
90
+ packer_type = packer.int16
91
+
92
+
93
+ class Int32Flags(object):
94
+ bytewidth = 4
95
+ min_val = -(2**31)
96
+ max_val = (2**31) - 1
97
+ py_type = int
98
+ name = "int32"
99
+ packer_type = packer.int32
100
+
101
+
102
+ class Int64Flags(object):
103
+ bytewidth = 8
104
+ min_val = -(2**63)
105
+ max_val = (2**63) - 1
106
+ py_type = int
107
+ name = "int64"
108
+ packer_type = packer.int64
109
+
110
+
111
+ class Float32Flags(object):
112
+ bytewidth = 4
113
+ min_val = None
114
+ max_val = None
115
+ py_type = float
116
+ name = "float32"
117
+ packer_type = packer.float32
118
+
119
+
120
+ class Float64Flags(object):
121
+ bytewidth = 8
122
+ min_val = None
123
+ max_val = None
124
+ py_type = float
125
+ name = "float64"
126
+ packer_type = packer.float64
127
+
128
+
129
+ class SOffsetTFlags(Int32Flags):
130
+ pass
131
+
132
+
133
+ class UOffsetTFlags(Uint32Flags):
134
+ pass
135
+
136
+
137
+ class VOffsetTFlags(Uint16Flags):
138
+ pass
139
+
140
+
141
+ def valid_number(n, flags):
142
+ if flags.min_val is None and flags.max_val is None:
143
+ return True
144
+ return flags.min_val <= n <= flags.max_val
145
+
146
+
147
+ def enforce_number(n, flags):
148
+ if flags.min_val is None and flags.max_val is None:
149
+ return
150
+ if not flags.min_val <= n <= flags.max_val:
151
+ raise TypeError("bad number %s for type %s" % (str(n), flags.name))
152
+
153
+
154
+ def float32_to_uint32(n):
155
+ packed = struct.pack("<1f", n)
156
+ (converted,) = struct.unpack("<1L", packed)
157
+ return converted
158
+
159
+
160
+ def uint32_to_float32(n):
161
+ packed = struct.pack("<1L", n)
162
+ (unpacked,) = struct.unpack("<1f", packed)
163
+ return unpacked
164
+
165
+
166
+ def float64_to_uint64(n):
167
+ packed = struct.pack("<1d", n)
168
+ (converted,) = struct.unpack("<1Q", packed)
169
+ return converted
170
+
171
+
172
+ def uint64_to_float64(n):
173
+ packed = struct.pack("<1Q", n)
174
+ (unpacked,) = struct.unpack("<1d", packed)
175
+ return unpacked
176
+
177
+
178
+ def to_numpy_type(number_type):
179
+ if np is not None:
180
+ return np.dtype(number_type.name).newbyteorder("<")
181
+ else:
182
+ raise NumpyRequiredForThisFeature("Numpy was not found.")
ScaleDF_rebuttal/python_dedup_pkgs/flatbuffers/packer.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2016 Google Inc. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """Provide pre-compiled struct packers for encoding and decoding.
16
+
17
+ See: https://docs.python.org/2/library/struct.html#format-characters
18
+ """
19
+
20
+ import struct
21
+ from . import compat
22
+
23
+
24
+ boolean = struct.Struct(compat.struct_bool_decl)
25
+
26
+ uint8 = struct.Struct("<B")
27
+ uint16 = struct.Struct("<H")
28
+ uint32 = struct.Struct("<I")
29
+ uint64 = struct.Struct("<Q")
30
+
31
+ int8 = struct.Struct("<b")
32
+ int16 = struct.Struct("<h")
33
+ int32 = struct.Struct("<i")
34
+ int64 = struct.Struct("<q")
35
+
36
+ float32 = struct.Struct("<f")
37
+ float64 = struct.Struct("<d")
38
+
39
+ uoffset = uint32
40
+ soffset = int32
41
+ voffset = uint16
ScaleDF_rebuttal/python_dedup_pkgs/flatbuffers/table.py ADDED
@@ -0,0 +1,148 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2014 Google Inc. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from . import encode
16
+ from . import number_types as N
17
+
18
+
19
+ class Table(object):
20
+ """Table wraps a byte slice and provides read access to its data.
21
+
22
+ The variable `Pos` indicates the root of the FlatBuffers object therein.
23
+ """
24
+
25
+ __slots__ = ("Bytes", "Pos")
26
+
27
+ def __init__(self, buf, pos):
28
+ N.enforce_number(pos, N.UOffsetTFlags)
29
+
30
+ self.Bytes = buf
31
+ self.Pos = pos
32
+
33
+ def Offset(self, vtableOffset):
34
+ """Offset provides access into the Table's vtable.
35
+
36
+ Deprecated fields are ignored by checking the vtable's length.
37
+ """
38
+
39
+ vtable = self.Pos - self.Get(N.SOffsetTFlags, self.Pos)
40
+ vtableEnd = self.Get(N.VOffsetTFlags, vtable)
41
+ if vtableOffset < vtableEnd:
42
+ return self.Get(N.VOffsetTFlags, vtable + vtableOffset)
43
+ return 0
44
+
45
+ def Indirect(self, off):
46
+ """Indirect retrieves the relative offset stored at `offset`."""
47
+ N.enforce_number(off, N.UOffsetTFlags)
48
+ return off + encode.Get(N.UOffsetTFlags.packer_type, self.Bytes, off)
49
+
50
+ def String(self, off):
51
+ """String gets a string from data stored inside the flatbuffer."""
52
+ N.enforce_number(off, N.UOffsetTFlags)
53
+ off += encode.Get(N.UOffsetTFlags.packer_type, self.Bytes, off)
54
+ start = off + N.UOffsetTFlags.bytewidth
55
+ length = encode.Get(N.UOffsetTFlags.packer_type, self.Bytes, off)
56
+ return bytes(self.Bytes[start : start + length])
57
+
58
+ def VectorLen(self, off):
59
+ """VectorLen retrieves the length of the vector whose offset is stored
60
+
61
+ at "off" in this object.
62
+ """
63
+ N.enforce_number(off, N.UOffsetTFlags)
64
+
65
+ off += self.Pos
66
+ off += encode.Get(N.UOffsetTFlags.packer_type, self.Bytes, off)
67
+ ret = encode.Get(N.UOffsetTFlags.packer_type, self.Bytes, off)
68
+ return ret
69
+
70
+ def Vector(self, off):
71
+ """Vector retrieves the start of data of the vector whose offset is
72
+
73
+ stored at "off" in this object.
74
+ """
75
+ N.enforce_number(off, N.UOffsetTFlags)
76
+
77
+ off += self.Pos
78
+ x = off + self.Get(N.UOffsetTFlags, off)
79
+ # data starts after metadata containing the vector length
80
+ x += N.UOffsetTFlags.bytewidth
81
+ return x
82
+
83
+ def Union(self, t2, off):
84
+ """Union initializes any Table-derived type to point to the union at
85
+
86
+ the given offset.
87
+ """
88
+ assert type(t2) is Table
89
+ N.enforce_number(off, N.UOffsetTFlags)
90
+
91
+ off += self.Pos
92
+ t2.Pos = off + self.Get(N.UOffsetTFlags, off)
93
+ t2.Bytes = self.Bytes
94
+
95
+ def Get(self, flags, off):
96
+ """Get retrieves a value of the type specified by `flags` at the
97
+
98
+ given offset.
99
+ """
100
+ N.enforce_number(off, N.UOffsetTFlags)
101
+ return flags.py_type(encode.Get(flags.packer_type, self.Bytes, off))
102
+
103
+ def GetSlot(self, slot, d, validator_flags):
104
+ N.enforce_number(slot, N.VOffsetTFlags)
105
+ if validator_flags is not None:
106
+ N.enforce_number(d, validator_flags)
107
+ off = self.Offset(slot)
108
+ if off == 0:
109
+ return d
110
+ return self.Get(validator_flags, self.Pos + off)
111
+
112
+ def GetVectorAsNumpy(self, flags, off):
113
+ """GetVectorAsNumpy returns the vector that starts at `Vector(off)`
114
+
115
+ as a numpy array with the type specified by `flags`. The array is
116
+ a `view` into Bytes, so modifying the returned array will
117
+ modify Bytes in place.
118
+ """
119
+ offset = self.Vector(off)
120
+ length = self.VectorLen(off) # TODO: length accounts for bytewidth, right?
121
+ numpy_dtype = N.to_numpy_type(flags)
122
+ return encode.GetVectorAsNumpy(numpy_dtype, self.Bytes, length, offset)
123
+
124
+ def GetArrayAsNumpy(self, flags, off, length):
125
+ """GetArrayAsNumpy returns the array with fixed width that starts at `Vector(offset)`
126
+
127
+ with length `length` as a numpy array with the type specified by `flags`.
128
+ The
129
+ array is a `view` into Bytes so modifying the returned will modify Bytes in
130
+ place.
131
+ """
132
+ numpy_dtype = N.to_numpy_type(flags)
133
+ return encode.GetVectorAsNumpy(numpy_dtype, self.Bytes, length, off)
134
+
135
+ def GetVOffsetTSlot(self, slot, d):
136
+ """GetVOffsetTSlot retrieves the VOffsetT that the given vtable location
137
+
138
+ points to. If the vtable value is zero, the default value `d`
139
+ will be returned.
140
+ """
141
+
142
+ N.enforce_number(slot, N.VOffsetTFlags)
143
+ N.enforce_number(d, N.VOffsetTFlags)
144
+
145
+ off = self.Offset(slot)
146
+ if off == 0:
147
+ return d
148
+ return off
ScaleDF_rebuttal/python_dedup_pkgs/flatbuffers/util.py ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2017 Google Inc. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from . import encode
16
+ from . import number_types
17
+ from . import packer
18
+
19
+
20
+ def GetSizePrefix(buf, offset):
21
+ """Extract the size prefix from a buffer."""
22
+ return encode.Get(packer.int32, buf, offset)
23
+
24
+
25
+ def GetBufferIdentifier(buf, offset, size_prefixed=False):
26
+ """Extract the file_identifier from a buffer"""
27
+ if size_prefixed:
28
+ # increase offset by size of UOffsetTFlags
29
+ offset += number_types.UOffsetTFlags.bytewidth
30
+ # increase offset by size of root table pointer
31
+ offset += number_types.UOffsetTFlags.bytewidth
32
+ # end of FILE_IDENTIFIER
33
+ end = offset + encode.FILE_IDENTIFIER_LENGTH
34
+ return buf[offset:end]
35
+
36
+
37
+ def BufferHasIdentifier(buf, offset, file_identifier, size_prefixed=False):
38
+ got = GetBufferIdentifier(buf, offset, size_prefixed=size_prefixed)
39
+ return got == file_identifier
40
+
41
+
42
+ def RemoveSizePrefix(buf, offset):
43
+ """Create a slice of a size-prefixed buffer that has
44
+
45
+ its position advanced just past the size prefix.
46
+ """
47
+ return buf, offset + number_types.Int32Flags.bytewidth
ScaleDF_rebuttal/python_dedup_pkgs/google/protobuf/__init__.py ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ # Protocol Buffers - Google's data interchange format
2
+ # Copyright 2008 Google Inc. All rights reserved.
3
+ #
4
+ # Use of this source code is governed by a BSD-style
5
+ # license that can be found in the LICENSE file or at
6
+ # https://developers.google.com/open-source/licenses/bsd
7
+
8
+ # Copyright 2007 Google Inc. All Rights Reserved.
9
+
10
+ __version__ = '7.35.1'
ScaleDF_rebuttal/python_dedup_pkgs/google/protobuf/any.py ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Protocol Buffers - Google's data interchange format
2
+ # Copyright 2008 Google Inc. All rights reserved.
3
+ #
4
+ # Use of this source code is governed by a BSD-style
5
+ # license that can be found in the LICENSE file or at
6
+ # https://developers.google.com/open-source/licenses/bsd
7
+
8
+ """Contains the Any helper APIs."""
9
+
10
+ from typing import Optional, TypeVar
11
+
12
+ from google.protobuf import descriptor
13
+ from google.protobuf.message import Message
14
+
15
+ from google.protobuf.any_pb2 import Any
16
+
17
+
18
+ _MessageT = TypeVar('_MessageT', bound=Message)
19
+
20
+
21
+ def pack(
22
+ msg: Message,
23
+ type_url_prefix: Optional[str] = 'type.googleapis.com/',
24
+ deterministic: Optional[bool] = None,
25
+ ) -> Any:
26
+ any_msg = Any()
27
+ any_msg.Pack(
28
+ msg=msg, type_url_prefix=type_url_prefix, deterministic=deterministic
29
+ )
30
+ return any_msg
31
+
32
+
33
+ def unpack(any_msg: Any, msg: Message) -> bool:
34
+ return any_msg.Unpack(msg=msg)
35
+
36
+
37
+ def unpack_as(any_msg: Any, message_type: type[_MessageT]) -> _MessageT:
38
+ unpacked = message_type()
39
+ if unpack(any_msg, unpacked):
40
+ return unpacked
41
+ else:
42
+ raise TypeError(
43
+ f'Attempted to unpack {type_name(any_msg)} to'
44
+ f' {message_type.__qualname__}'
45
+ )
46
+
47
+
48
+ def type_name(any_msg: Any) -> str:
49
+ return any_msg.TypeName()
50
+
51
+
52
+ def is_type(any_msg: Any, des: descriptor.Descriptor) -> bool:
53
+ return any_msg.Is(des)
ScaleDF_rebuttal/python_dedup_pkgs/google/protobuf/any_pb2.py ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ # Generated by the protocol buffer compiler. DO NOT EDIT!
3
+ # NO CHECKED-IN PROTOBUF GENCODE
4
+ # source: google/protobuf/any.proto
5
+ # Protobuf Python Version: 7.35.1
6
+ """Generated protocol buffer code."""
7
+ from google.protobuf import descriptor as _descriptor
8
+ from google.protobuf import descriptor_pool as _descriptor_pool
9
+ from google.protobuf import runtime_version as _runtime_version
10
+ from google.protobuf import symbol_database as _symbol_database
11
+ from google.protobuf.internal import builder as _builder
12
+ _runtime_version.ValidateProtobufRuntimeVersion(
13
+ _runtime_version.Domain.PUBLIC,
14
+ 7,
15
+ 35,
16
+ 1,
17
+ '',
18
+ 'google/protobuf/any.proto'
19
+ )
20
+ # @@protoc_insertion_point(imports)
21
+
22
+ _sym_db = _symbol_database.Default()
23
+
24
+
25
+
26
+
27
+ DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x19google/protobuf/any.proto\x12\x0fgoogle.protobuf\"6\n\x03\x41ny\x12\x19\n\x08type_url\x18\x01 \x01(\tR\x07typeUrl\x12\x14\n\x05value\x18\x02 \x01(\x0cR\x05valueBv\n\x13\x63om.google.protobufB\x08\x41nyProtoP\x01Z,google.golang.org/protobuf/types/known/anypb\xa2\x02\x03GPB\xaa\x02\x1eGoogle.Protobuf.WellKnownTypesb\x06proto3')
28
+
29
+ _globals = globals()
30
+ _builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals)
31
+ _builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'google.protobuf.any_pb2', _globals)
32
+ if not _descriptor._USE_C_DESCRIPTORS:
33
+ _globals['DESCRIPTOR']._loaded_options = None
34
+ _globals['DESCRIPTOR']._serialized_options = b'\n\023com.google.protobufB\010AnyProtoP\001Z,google.golang.org/protobuf/types/known/anypb\242\002\003GPB\252\002\036Google.Protobuf.WellKnownTypes'
35
+ _globals['_ANY']._serialized_start=46
36
+ _globals['_ANY']._serialized_end=100
37
+ # @@protoc_insertion_point(module_scope)
ScaleDF_rebuttal/python_dedup_pkgs/google/protobuf/api_pb2.py ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ # Generated by the protocol buffer compiler. DO NOT EDIT!
3
+ # NO CHECKED-IN PROTOBUF GENCODE
4
+ # source: google/protobuf/api.proto
5
+ # Protobuf Python Version: 7.35.1
6
+ """Generated protocol buffer code."""
7
+ from google.protobuf import descriptor as _descriptor
8
+ from google.protobuf import descriptor_pool as _descriptor_pool
9
+ from google.protobuf import runtime_version as _runtime_version
10
+ from google.protobuf import symbol_database as _symbol_database
11
+ from google.protobuf.internal import builder as _builder
12
+ _runtime_version.ValidateProtobufRuntimeVersion(
13
+ _runtime_version.Domain.PUBLIC,
14
+ 7,
15
+ 35,
16
+ 1,
17
+ '',
18
+ 'google/protobuf/api.proto'
19
+ )
20
+ # @@protoc_insertion_point(imports)
21
+
22
+ _sym_db = _symbol_database.Default()
23
+
24
+
25
+ from google.protobuf import source_context_pb2 as google_dot_protobuf_dot_source__context__pb2
26
+ from google.protobuf import type_pb2 as google_dot_protobuf_dot_type__pb2
27
+
28
+
29
+ DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x19google/protobuf/api.proto\x12\x0fgoogle.protobuf\x1a$google/protobuf/source_context.proto\x1a\x1agoogle/protobuf/type.proto\"\xdb\x02\n\x03\x41pi\x12\x12\n\x04name\x18\x01 \x01(\tR\x04name\x12\x31\n\x07methods\x18\x02 \x03(\x0b\x32\x17.google.protobuf.MethodR\x07methods\x12\x31\n\x07options\x18\x03 \x03(\x0b\x32\x17.google.protobuf.OptionR\x07options\x12\x18\n\x07version\x18\x04 \x01(\tR\x07version\x12\x45\n\x0esource_context\x18\x05 \x01(\x0b\x32\x1e.google.protobuf.SourceContextR\rsourceContext\x12.\n\x06mixins\x18\x06 \x03(\x0b\x32\x16.google.protobuf.MixinR\x06mixins\x12/\n\x06syntax\x18\x07 \x01(\x0e\x32\x17.google.protobuf.SyntaxR\x06syntax\x12\x18\n\x07\x65\x64ition\x18\x08 \x01(\tR\x07\x65\x64ition\"\xd4\x02\n\x06Method\x12\x12\n\x04name\x18\x01 \x01(\tR\x04name\x12(\n\x10request_type_url\x18\x02 \x01(\tR\x0erequestTypeUrl\x12+\n\x11request_streaming\x18\x03 \x01(\x08R\x10requestStreaming\x12*\n\x11response_type_url\x18\x04 \x01(\tR\x0fresponseTypeUrl\x12-\n\x12response_streaming\x18\x05 \x01(\x08R\x11responseStreaming\x12\x31\n\x07options\x18\x06 \x03(\x0b\x32\x17.google.protobuf.OptionR\x07options\x12\x33\n\x06syntax\x18\x07 \x01(\x0e\x32\x17.google.protobuf.SyntaxB\x02\x18\x01R\x06syntax\x12\x1c\n\x07\x65\x64ition\x18\x08 \x01(\tB\x02\x18\x01R\x07\x65\x64ition\"/\n\x05Mixin\x12\x12\n\x04name\x18\x01 \x01(\tR\x04name\x12\x12\n\x04root\x18\x02 \x01(\tR\x04rootBv\n\x13\x63om.google.protobufB\x08\x41piProtoP\x01Z,google.golang.org/protobuf/types/known/apipb\xa2\x02\x03GPB\xaa\x02\x1eGoogle.Protobuf.WellKnownTypesb\x06proto3')
30
+
31
+ _globals = globals()
32
+ _builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals)
33
+ _builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'google.protobuf.api_pb2', _globals)
34
+ if not _descriptor._USE_C_DESCRIPTORS:
35
+ _globals['DESCRIPTOR']._loaded_options = None
36
+ _globals['DESCRIPTOR']._serialized_options = b'\n\023com.google.protobufB\010ApiProtoP\001Z,google.golang.org/protobuf/types/known/apipb\242\002\003GPB\252\002\036Google.Protobuf.WellKnownTypes'
37
+ _globals['_METHOD'].fields_by_name['syntax']._loaded_options = None
38
+ _globals['_METHOD'].fields_by_name['syntax']._serialized_options = b'\030\001'
39
+ _globals['_METHOD'].fields_by_name['edition']._loaded_options = None
40
+ _globals['_METHOD'].fields_by_name['edition']._serialized_options = b'\030\001'
41
+ _globals['_API']._serialized_start=113
42
+ _globals['_API']._serialized_end=460
43
+ _globals['_METHOD']._serialized_start=463
44
+ _globals['_METHOD']._serialized_end=803
45
+ _globals['_MIXIN']._serialized_start=805
46
+ _globals['_MIXIN']._serialized_end=852
47
+ # @@protoc_insertion_point(module_scope)
ScaleDF_rebuttal/python_dedup_pkgs/google/protobuf/compiler/__init__.py ADDED
File without changes
ScaleDF_rebuttal/python_dedup_pkgs/google/protobuf/compiler/plugin_pb2.py ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ # Generated by the protocol buffer compiler. DO NOT EDIT!
3
+ # NO CHECKED-IN PROTOBUF GENCODE
4
+ # source: google/protobuf/compiler/plugin.proto
5
+ # Protobuf Python Version: 7.35.1
6
+ """Generated protocol buffer code."""
7
+ from google.protobuf import descriptor as _descriptor
8
+ from google.protobuf import descriptor_pool as _descriptor_pool
9
+ from google.protobuf import runtime_version as _runtime_version
10
+ from google.protobuf import symbol_database as _symbol_database
11
+ from google.protobuf.internal import builder as _builder
12
+ _runtime_version.ValidateProtobufRuntimeVersion(
13
+ _runtime_version.Domain.PUBLIC,
14
+ 7,
15
+ 35,
16
+ 1,
17
+ '',
18
+ 'google/protobuf/compiler/plugin.proto'
19
+ )
20
+ # @@protoc_insertion_point(imports)
21
+
22
+ _sym_db = _symbol_database.Default()
23
+
24
+
25
+ from google.protobuf import descriptor_pb2 as google_dot_protobuf_dot_descriptor__pb2
26
+
27
+
28
+ DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n%google/protobuf/compiler/plugin.proto\x12\x18google.protobuf.compiler\x1a google/protobuf/descriptor.proto\"c\n\x07Version\x12\x14\n\x05major\x18\x01 \x01(\x05R\x05major\x12\x14\n\x05minor\x18\x02 \x01(\x05R\x05minor\x12\x14\n\x05patch\x18\x03 \x01(\x05R\x05patch\x12\x16\n\x06suffix\x18\x04 \x01(\tR\x06suffix\"\xcf\x02\n\x14\x43odeGeneratorRequest\x12(\n\x10\x66ile_to_generate\x18\x01 \x03(\tR\x0e\x66ileToGenerate\x12\x1c\n\tparameter\x18\x02 \x01(\tR\tparameter\x12\x43\n\nproto_file\x18\x0f \x03(\x0b\x32$.google.protobuf.FileDescriptorProtoR\tprotoFile\x12\\\n\x17source_file_descriptors\x18\x11 \x03(\x0b\x32$.google.protobuf.FileDescriptorProtoR\x15sourceFileDescriptors\x12L\n\x10\x63ompiler_version\x18\x03 \x01(\x0b\x32!.google.protobuf.compiler.VersionR\x0f\x63ompilerVersion\"\x85\x04\n\x15\x43odeGeneratorResponse\x12\x14\n\x05\x65rror\x18\x01 \x01(\tR\x05\x65rror\x12-\n\x12supported_features\x18\x02 \x01(\x04R\x11supportedFeatures\x12\'\n\x0fminimum_edition\x18\x03 \x01(\x05R\x0eminimumEdition\x12\'\n\x0fmaximum_edition\x18\x04 \x01(\x05R\x0emaximumEdition\x12H\n\x04\x66ile\x18\x0f \x03(\x0b\x32\x34.google.protobuf.compiler.CodeGeneratorResponse.FileR\x04\x66ile\x1a\xb1\x01\n\x04\x46ile\x12\x12\n\x04name\x18\x01 \x01(\tR\x04name\x12\'\n\x0finsertion_point\x18\x02 \x01(\tR\x0einsertionPoint\x12\x18\n\x07\x63ontent\x18\x0f \x01(\tR\x07\x63ontent\x12R\n\x13generated_code_info\x18\x10 \x01(\x0b\x32\".google.protobuf.GeneratedCodeInfoR\x11generatedCodeInfo\"W\n\x07\x46\x65\x61ture\x12\x10\n\x0c\x46\x45\x41TURE_NONE\x10\x00\x12\x1b\n\x17\x46\x45\x41TURE_PROTO3_OPTIONAL\x10\x01\x12\x1d\n\x19\x46\x45\x41TURE_SUPPORTS_EDITIONS\x10\x02\x42r\n\x1c\x63om.google.protobuf.compilerB\x0cPluginProtosZ)google.golang.org/protobuf/types/pluginpb\xaa\x02\x18Google.Protobuf.Compiler')
29
+
30
+ _globals = globals()
31
+ _builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals)
32
+ _builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'google.protobuf.compiler.plugin_pb2', _globals)
33
+ if not _descriptor._USE_C_DESCRIPTORS:
34
+ _globals['DESCRIPTOR']._loaded_options = None
35
+ _globals['DESCRIPTOR']._serialized_options = b'\n\034com.google.protobuf.compilerB\014PluginProtosZ)google.golang.org/protobuf/types/pluginpb\252\002\030Google.Protobuf.Compiler'
36
+ _globals['_VERSION']._serialized_start=101
37
+ _globals['_VERSION']._serialized_end=200
38
+ _globals['_CODEGENERATORREQUEST']._serialized_start=203
39
+ _globals['_CODEGENERATORREQUEST']._serialized_end=538
40
+ _globals['_CODEGENERATORRESPONSE']._serialized_start=541
41
+ _globals['_CODEGENERATORRESPONSE']._serialized_end=1058
42
+ _globals['_CODEGENERATORRESPONSE_FILE']._serialized_start=792
43
+ _globals['_CODEGENERATORRESPONSE_FILE']._serialized_end=969
44
+ _globals['_CODEGENERATORRESPONSE_FEATURE']._serialized_start=971
45
+ _globals['_CODEGENERATORRESPONSE_FEATURE']._serialized_end=1058
46
+ # @@protoc_insertion_point(module_scope)
ScaleDF_rebuttal/python_dedup_pkgs/google/protobuf/descriptor.py ADDED
@@ -0,0 +1,1665 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Protocol Buffers - Google's data interchange format
2
+ # Copyright 2008 Google Inc. All rights reserved.
3
+ #
4
+ # Use of this source code is governed by a BSD-style
5
+ # license that can be found in the LICENSE file or at
6
+ # https://developers.google.com/open-source/licenses/bsd
7
+
8
+ """Descriptors essentially contain exactly the information found in a .proto
9
+
10
+ file, in types that make this information accessible in Python.
11
+ """
12
+
13
+ __author__ = 'robinson@google.com (Will Robinson)'
14
+
15
+ import abc
16
+ import binascii
17
+ import os
18
+ import threading
19
+ import warnings
20
+
21
+ from google.protobuf.internal import api_implementation
22
+
23
+ _USE_C_DESCRIPTORS = False
24
+ if api_implementation.Type() != 'python':
25
+ # pylint: disable=protected-access
26
+ _message = api_implementation._c_module
27
+ # TODO: Remove this import after fix api_implementation
28
+ if _message is None:
29
+ from google.protobuf.pyext import _message
30
+ _USE_C_DESCRIPTORS = True
31
+
32
+
33
+ class Error(Exception):
34
+ """Base error for this module."""
35
+
36
+
37
+ class TypeTransformationError(Error):
38
+ """Error transforming between python proto type and corresponding C++ type."""
39
+
40
+
41
+ if _USE_C_DESCRIPTORS:
42
+ # This metaclass allows to override the behavior of code like
43
+ # isinstance(my_descriptor, FieldDescriptor)
44
+ # and make it return True when the descriptor is an instance of the extension
45
+ # type written in C++.
46
+ class DescriptorMetaclass(type):
47
+
48
+ def __instancecheck__(cls, obj):
49
+ if super(DescriptorMetaclass, cls).__instancecheck__(obj):
50
+ return True
51
+ if isinstance(obj, cls._C_DESCRIPTOR_CLASS):
52
+ return True
53
+ return False
54
+
55
+ else:
56
+ # The standard metaclass; nothing changes.
57
+ DescriptorMetaclass = abc.ABCMeta
58
+
59
+
60
+ class _Lock(object):
61
+ """Wrapper class of threading.Lock(), which is allowed by 'with'."""
62
+
63
+ def __new__(cls):
64
+ self = object.__new__(cls)
65
+ self._lock = threading.Lock() # pylint: disable=protected-access
66
+ return self
67
+
68
+ def __enter__(self):
69
+ self._lock.acquire()
70
+
71
+ def __exit__(self, exc_type, exc_value, exc_tb):
72
+ self._lock.release()
73
+
74
+
75
+ _lock = threading.Lock()
76
+
77
+
78
+ def _Deprecated(
79
+ name,
80
+ alternative='get/find descriptors from generated code or query the descriptor_pool',
81
+ ):
82
+ if _Deprecated.count > 0:
83
+ _Deprecated.count -= 1
84
+ warnings.warn(
85
+ 'Call to deprecated %s, use %s instead.' % (name, alternative),
86
+ category=DeprecationWarning,
87
+ stacklevel=3,
88
+ )
89
+
90
+
91
+ # These must match the values in descriptor.proto, but we can't use them
92
+ # directly because we sometimes need to reference them in feature helpers
93
+ # below *during* the build of descriptor.proto.
94
+ _FEATURESET_MESSAGE_ENCODING_DELIMITED = 2
95
+ _FEATURESET_FIELD_PRESENCE_IMPLICIT = 2
96
+ _FEATURESET_FIELD_PRESENCE_LEGACY_REQUIRED = 3
97
+ _FEATURESET_REPEATED_FIELD_ENCODING_PACKED = 1
98
+ _FEATURESET_ENUM_TYPE_CLOSED = 2
99
+
100
+ # Deprecated warnings will print 100 times at most which should be enough for
101
+ # users to notice and do not cause timeout.
102
+ _Deprecated.count = 100
103
+
104
+
105
+ _internal_create_key = object()
106
+
107
+
108
+ class DescriptorBase(metaclass=DescriptorMetaclass):
109
+ """Descriptors base class.
110
+
111
+ This class is the base of all descriptor classes. It provides common options
112
+ related functionality.
113
+
114
+ Attributes:
115
+ has_options: True if the descriptor has non-default options. Usually it is
116
+ not necessary to read this -- just call GetOptions() which will happily
117
+ return the default instance. However, it's sometimes useful for
118
+ efficiency, and also useful inside the protobuf implementation to avoid
119
+ some bootstrapping issues.
120
+ file (FileDescriptor): Reference to file info.
121
+ """
122
+
123
+ if _USE_C_DESCRIPTORS:
124
+ # The class, or tuple of classes, that are considered as "virtual
125
+ # subclasses" of this descriptor class.
126
+ _C_DESCRIPTOR_CLASS = ()
127
+
128
+ def __init__(self, file, options, serialized_options, options_class_name):
129
+ """Initialize the descriptor given its options message and the name of the
130
+
131
+ class of the options message. The name of the class is required in case
132
+ the options message is None and has to be created.
133
+ """
134
+ self._features = None
135
+ self.file = file
136
+ self._original_options = options
137
+ # These two fields are duplicated as a compatibility shim for old gencode
138
+ # that resets them. In 26.x (cl/580304039) we renamed _options to,
139
+ # _loaded_options breaking backwards compatibility.
140
+ self._options = self._loaded_options = None
141
+ self._options_class_name = options_class_name
142
+ self._serialized_options = serialized_options
143
+
144
+ # Does this descriptor have non-default options?
145
+ self.has_options = (self._original_options is not None) or (
146
+ self._serialized_options is not None
147
+ )
148
+
149
+ @property
150
+ @abc.abstractmethod
151
+ def _parent(self):
152
+ pass
153
+
154
+ def _InferLegacyFeatures(self, edition, options, features):
155
+ """Infers features from proto2/proto3 syntax so that editions logic can be used everywhere.
156
+
157
+ Args:
158
+ edition: The edition to infer features for.
159
+ options: The options for this descriptor that are being processed.
160
+ features: The feature set object to modify with inferred features.
161
+ """
162
+ pass
163
+
164
+ def _GetFeatures(self):
165
+ if not self._features:
166
+ self._LazyLoadOptions()
167
+ return self._features
168
+
169
+ def _ResolveFeatures(self, edition, raw_options):
170
+ """Resolves features from the raw options of this descriptor.
171
+
172
+ Args:
173
+ edition: The edition to use for feature defaults.
174
+ raw_options: The options for this descriptor that are being processed.
175
+
176
+ Returns:
177
+ A fully resolved feature set for making runtime decisions.
178
+ """
179
+ # pylint: disable=g-import-not-at-top
180
+ from google.protobuf import descriptor_pb2
181
+
182
+ if self._parent:
183
+ features = descriptor_pb2.FeatureSet()
184
+ features.CopyFrom(self._parent._GetFeatures())
185
+ else:
186
+ features = self.file.pool._CreateDefaultFeatures(edition)
187
+ unresolved = descriptor_pb2.FeatureSet()
188
+ unresolved.CopyFrom(raw_options.features)
189
+ self._InferLegacyFeatures(edition, raw_options, unresolved)
190
+ features.MergeFrom(unresolved)
191
+
192
+ # Use the feature cache to reduce memory bloat.
193
+ return self.file.pool._InternFeatures(features)
194
+
195
+ def _LazyLoadOptions(self):
196
+ """Lazily initializes descriptor options towards the end of the build."""
197
+ if self._options and self._loaded_options == self._options:
198
+ # If neither has been reset by gencode, use the cache.
199
+ return
200
+
201
+ # pylint: disable=g-import-not-at-top
202
+ from google.protobuf import descriptor_pb2
203
+
204
+ if not hasattr(descriptor_pb2, self._options_class_name):
205
+ raise RuntimeError(
206
+ 'Unknown options class name %s!' % self._options_class_name
207
+ )
208
+ options_class = getattr(descriptor_pb2, self._options_class_name)
209
+ features = None
210
+ edition = self.file._edition
211
+
212
+ if not self.has_options:
213
+ if not self._features:
214
+ features = self._ResolveFeatures(
215
+ descriptor_pb2.Edition.Value(edition), options_class()
216
+ )
217
+ with _lock:
218
+ self._options = self._loaded_options = options_class()
219
+ if not self._features:
220
+ self._features = features
221
+ else:
222
+ if not self._serialized_options:
223
+ options = self._original_options
224
+ else:
225
+ options = _ParseOptions(options_class(), self._serialized_options)
226
+
227
+ if not self._features:
228
+ features = self._ResolveFeatures(
229
+ descriptor_pb2.Edition.Value(edition), options
230
+ )
231
+ with _lock:
232
+ self._options = self._loaded_options = options
233
+ if not self._features:
234
+ self._features = features
235
+ if options.HasField('features'):
236
+ options.ClearField('features')
237
+ if not options.SerializeToString():
238
+ self._options = self._loaded_options = options_class()
239
+ self.has_options = False
240
+
241
+ def GetOptions(self):
242
+ """Retrieves descriptor options.
243
+
244
+ Returns:
245
+ The options set on this descriptor.
246
+ """
247
+ # If either has been reset by gencode, reload options.
248
+ if not self._options or not self._loaded_options:
249
+ self._LazyLoadOptions()
250
+ return self._options
251
+
252
+
253
+ class _NestedDescriptorBase(DescriptorBase):
254
+ """Common class for descriptors that can be nested."""
255
+
256
+ def __init__(
257
+ self,
258
+ options,
259
+ options_class_name,
260
+ name,
261
+ full_name,
262
+ file,
263
+ containing_type,
264
+ serialized_start=None,
265
+ serialized_end=None,
266
+ serialized_options=None,
267
+ ):
268
+ """Constructor.
269
+
270
+ Args:
271
+ options: Protocol message options or None to use default message options.
272
+ options_class_name (str): The class name of the above options.
273
+ name (str): Name of this protocol message type.
274
+ full_name (str): Fully-qualified name of this protocol message type, which
275
+ will include protocol "package" name and the name of any enclosing
276
+ types.
277
+ containing_type: if provided, this is a nested descriptor, with this
278
+ descriptor as parent, otherwise None.
279
+ serialized_start: The start index (inclusive) in block in the
280
+ file.serialized_pb that describes this descriptor.
281
+ serialized_end: The end index (exclusive) in block in the
282
+ file.serialized_pb that describes this descriptor.
283
+ serialized_options: Protocol message serialized options or None.
284
+ """
285
+ super(_NestedDescriptorBase, self).__init__(
286
+ file, options, serialized_options, options_class_name
287
+ )
288
+
289
+ self.name = name
290
+ # TODO: Add function to calculate full_name instead of having it in
291
+ # memory?
292
+ self.full_name = full_name
293
+ self.containing_type = containing_type
294
+
295
+ self._serialized_start = serialized_start
296
+ self._serialized_end = serialized_end
297
+
298
+ def CopyToProto(self, proto):
299
+ """Copies this to the matching proto in descriptor_pb2.
300
+
301
+ Args:
302
+ proto: An empty proto instance from descriptor_pb2.
303
+
304
+ Raises:
305
+ Error: If self couldn't be serialized, due to to few constructor
306
+ arguments.
307
+ """
308
+ if (
309
+ self.file is not None
310
+ and self._serialized_start is not None
311
+ and self._serialized_end is not None
312
+ ):
313
+ proto.ParseFromString(
314
+ self.file.serialized_pb[self._serialized_start : self._serialized_end]
315
+ )
316
+ else:
317
+ raise Error('Descriptor does not contain serialization.')
318
+
319
+
320
+ class Descriptor(_NestedDescriptorBase):
321
+ """Descriptor for a protocol message type.
322
+
323
+ Attributes:
324
+ name (str): Name of this protocol message type.
325
+ full_name (str): Fully-qualified name of this protocol message type, which
326
+ will include protocol "package" name and the name of any enclosing
327
+ types.
328
+ containing_type (Descriptor): Reference to the descriptor of the type
329
+ containing us, or None if this is top-level.
330
+ fields (list[FieldDescriptor]): Field descriptors for all fields in this
331
+ type.
332
+ fields_by_number (dict(int, FieldDescriptor)): Same
333
+ :class:`FieldDescriptor` objects as in :attr:`fields`, but indexed by
334
+ "number" attribute in each FieldDescriptor.
335
+ fields_by_name (dict(str, FieldDescriptor)): Same :class:`FieldDescriptor`
336
+ objects as in :attr:`fields`, but indexed by "name" attribute in each
337
+ :class:`FieldDescriptor`.
338
+ nested_types (list[Descriptor]): Descriptor references for all protocol
339
+ message types nested within this one.
340
+ nested_types_by_name (dict(str, Descriptor)): Same Descriptor objects as
341
+ in :attr:`nested_types`, but indexed by "name" attribute in each
342
+ Descriptor.
343
+ enum_types (list[EnumDescriptor]): :class:`EnumDescriptor` references for
344
+ all enums contained within this type.
345
+ enum_types_by_name (dict(str, EnumDescriptor)): Same
346
+ :class:`EnumDescriptor` objects as in :attr:`enum_types`, but indexed by
347
+ "name" attribute in each EnumDescriptor.
348
+ enum_values_by_name (dict(str, EnumValueDescriptor)): Dict mapping from
349
+ enum value name to :class:`EnumValueDescriptor` for that value.
350
+ extensions (list[FieldDescriptor]): All extensions defined directly within
351
+ this message type (NOT within a nested type).
352
+ extensions_by_name (dict(str, FieldDescriptor)): Same FieldDescriptor
353
+ objects as :attr:`extensions`, but indexed by "name" attribute of each
354
+ FieldDescriptor.
355
+ is_extendable (bool): Does this type define any extension ranges?
356
+ oneofs (list[OneofDescriptor]): The list of descriptors for oneof fields
357
+ in this message.
358
+ oneofs_by_name (dict(str, OneofDescriptor)): Same objects as in
359
+ :attr:`oneofs`, but indexed by "name" attribute.
360
+ file (FileDescriptor): Reference to file descriptor.
361
+ is_map_entry: If the message type is a map entry.
362
+ """
363
+
364
+ if _USE_C_DESCRIPTORS:
365
+ _C_DESCRIPTOR_CLASS = _message.Descriptor
366
+
367
+ def __new__(
368
+ cls,
369
+ name=None,
370
+ full_name=None,
371
+ filename=None,
372
+ containing_type=None,
373
+ fields=None,
374
+ nested_types=None,
375
+ enum_types=None,
376
+ extensions=None,
377
+ options=None,
378
+ serialized_options=None,
379
+ is_extendable=True,
380
+ extension_ranges=None,
381
+ oneofs=None,
382
+ file=None, # pylint: disable=redefined-builtin
383
+ serialized_start=None,
384
+ serialized_end=None,
385
+ syntax=None,
386
+ is_map_entry=False,
387
+ create_key=None,
388
+ ):
389
+ _message.Message._CheckCalledFromGeneratedFile()
390
+ return _message.default_pool.FindMessageTypeByName(full_name)
391
+
392
+ # NOTE: The file argument redefining a builtin is nothing we can
393
+ # fix right now since we don't know how many clients already rely on the
394
+ # name of the argument.
395
+ def __init__(
396
+ self,
397
+ name,
398
+ full_name,
399
+ filename,
400
+ containing_type,
401
+ fields,
402
+ nested_types,
403
+ enum_types,
404
+ extensions,
405
+ options=None,
406
+ serialized_options=None,
407
+ is_extendable=True,
408
+ extension_ranges=None,
409
+ oneofs=None,
410
+ file=None,
411
+ serialized_start=None,
412
+ serialized_end=None, # pylint: disable=redefined-builtin
413
+ syntax=None,
414
+ is_map_entry=False,
415
+ create_key=None,
416
+ ):
417
+ """Arguments to __init__() are as described in the description
418
+
419
+ of Descriptor fields above.
420
+
421
+ Note that filename is an obsolete argument, that is not used anymore.
422
+ Please use file.name to access this as an attribute.
423
+ """
424
+ if create_key is not _internal_create_key:
425
+ _Deprecated('create function Descriptor()')
426
+
427
+ super(Descriptor, self).__init__(
428
+ options,
429
+ 'MessageOptions',
430
+ name,
431
+ full_name,
432
+ file,
433
+ containing_type,
434
+ serialized_start=serialized_start,
435
+ serialized_end=serialized_end,
436
+ serialized_options=serialized_options,
437
+ )
438
+
439
+ # We have fields in addition to fields_by_name and fields_by_number,
440
+ # so that:
441
+ # 1. Clients can index fields by "order in which they're listed."
442
+ # 2. Clients can easily iterate over all fields with the terse
443
+ # syntax: for f in descriptor.fields: ...
444
+ self.fields = fields
445
+ for field in self.fields:
446
+ field.containing_type = self
447
+ field.file = file
448
+ self.fields_by_number = dict((f.number, f) for f in fields)
449
+ self.fields_by_name = dict((f.name, f) for f in fields)
450
+ self._fields_by_camelcase_name = None
451
+
452
+ self.nested_types = nested_types
453
+ for nested_type in nested_types:
454
+ nested_type.containing_type = self
455
+ self.nested_types_by_name = dict((t.name, t) for t in nested_types)
456
+
457
+ self.enum_types = enum_types
458
+ for enum_type in self.enum_types:
459
+ enum_type.containing_type = self
460
+ self.enum_types_by_name = dict((t.name, t) for t in enum_types)
461
+ self.enum_values_by_name = dict(
462
+ (v.name, v) for t in enum_types for v in t.values
463
+ )
464
+
465
+ self.extensions = extensions
466
+ for extension in self.extensions:
467
+ extension.extension_scope = self
468
+ self.extensions_by_name = dict((f.name, f) for f in extensions)
469
+ self.is_extendable = is_extendable
470
+ self.extension_ranges = extension_ranges
471
+ self.oneofs = oneofs if oneofs is not None else []
472
+ self.oneofs_by_name = dict((o.name, o) for o in self.oneofs)
473
+ for oneof in self.oneofs:
474
+ oneof.containing_type = self
475
+ oneof.file = file
476
+ self._is_map_entry = is_map_entry
477
+
478
+ @property
479
+ def _parent(self):
480
+ return self.containing_type or self.file
481
+
482
+ @property
483
+ def fields_by_camelcase_name(self):
484
+ """Same FieldDescriptor objects as in :attr:`fields`, but indexed by
485
+
486
+ :attr:`FieldDescriptor.camelcase_name`.
487
+ """
488
+ if self._fields_by_camelcase_name is None:
489
+ self._fields_by_camelcase_name = dict(
490
+ (f.camelcase_name, f) for f in self.fields
491
+ )
492
+ return self._fields_by_camelcase_name
493
+
494
+ def EnumValueName(self, enum, value):
495
+ """Returns the string name of an enum value.
496
+
497
+ This is just a small helper method to simplify a common operation.
498
+
499
+ Args:
500
+ enum: string name of the Enum.
501
+ value: int, value of the enum.
502
+
503
+ Returns:
504
+ string name of the enum value.
505
+
506
+ Raises:
507
+ KeyError if either the Enum doesn't exist or the value is not a valid
508
+ value for the enum.
509
+ """
510
+ return self.enum_types_by_name[enum].values_by_number[value].name
511
+
512
+ def CopyToProto(self, proto):
513
+ """Copies this to a descriptor_pb2.DescriptorProto.
514
+
515
+ Args:
516
+ proto: An empty descriptor_pb2.DescriptorProto.
517
+ """
518
+ # This function is overridden to give a better doc comment.
519
+ super(Descriptor, self).CopyToProto(proto)
520
+
521
+
522
+ # TODO: We should have aggressive checking here,
523
+ # for example:
524
+ # * If you specify a repeated field, you should not be allowed
525
+ # to specify a default value.
526
+ # * [Other examples here as needed].
527
+ #
528
+ # TODO: for this and other *Descriptor classes, we
529
+ # might also want to lock things down aggressively (e.g.,
530
+ # prevent clients from setting the attributes). Having
531
+ # stronger invariants here in general will reduce the number
532
+ # of runtime checks we must do in reflection.py...
533
+ class FieldDescriptor(DescriptorBase):
534
+ """Descriptor for a single field in a .proto file.
535
+
536
+ Attributes:
537
+ name (str): Name of this field, exactly as it appears in .proto.
538
+ full_name (str): Name of this field, including containing scope. This is
539
+ particularly relevant for extensions.
540
+ index (int): Dense, 0-indexed index giving the order that this field
541
+ textually appears within its message in the .proto file.
542
+ number (int): Tag number declared for this field in the .proto file.
543
+ type (int): (One of the TYPE_* constants below) Declared type.
544
+ cpp_type (int): (One of the CPPTYPE_* constants below) C++ type used to
545
+ represent this field.
546
+ label (int): (One of the LABEL_* constants below) Tells whether this field
547
+ is optional, required, or repeated.
548
+ has_default_value (bool): True if this field has a default value defined,
549
+ otherwise false.
550
+ default_value (Varies): Default value of this field. Only meaningful for
551
+ non-repeated scalar fields. Repeated fields should always set this to [],
552
+ and non-repeated composite fields should always set this to None.
553
+ containing_type (Descriptor): Descriptor of the protocol message type that
554
+ contains this field. Set by the Descriptor constructor if we're passed
555
+ into one. Somewhat confusingly, for extension fields, this is the
556
+ descriptor of the EXTENDED message, not the descriptor of the message
557
+ containing this field. (See is_extension and extension_scope below).
558
+ message_type (Descriptor): If a composite field, a descriptor of the message
559
+ type contained in this field. Otherwise, this is None.
560
+ enum_type (EnumDescriptor): If this field contains an enum, a descriptor of
561
+ that enum. Otherwise, this is None.
562
+ is_extension: True iff this describes an extension field.
563
+ extension_scope (Descriptor): Only meaningful if is_extension is True. Gives
564
+ the message that immediately contains this extension field. Will be None
565
+ iff we're a top-level (file-level) extension field.
566
+ options (descriptor_pb2.FieldOptions): Protocol message field options or
567
+ None to use default field options.
568
+ containing_oneof (OneofDescriptor): If the field is a member of a oneof
569
+ union, contains its descriptor. Otherwise, None.
570
+ file (FileDescriptor): Reference to file descriptor.
571
+ """
572
+
573
+ # Must be consistent with C++ FieldDescriptor::Type enum in
574
+ # descriptor.h.
575
+ #
576
+ # TODO: Find a way to eliminate this repetition.
577
+ TYPE_DOUBLE = 1
578
+ TYPE_FLOAT = 2
579
+ TYPE_INT64 = 3
580
+ TYPE_UINT64 = 4
581
+ TYPE_INT32 = 5
582
+ TYPE_FIXED64 = 6
583
+ TYPE_FIXED32 = 7
584
+ TYPE_BOOL = 8
585
+ TYPE_STRING = 9
586
+ TYPE_GROUP = 10
587
+ TYPE_MESSAGE = 11
588
+ TYPE_BYTES = 12
589
+ TYPE_UINT32 = 13
590
+ TYPE_ENUM = 14
591
+ TYPE_SFIXED32 = 15
592
+ TYPE_SFIXED64 = 16
593
+ TYPE_SINT32 = 17
594
+ TYPE_SINT64 = 18
595
+ MAX_TYPE = 18
596
+
597
+ # Must be consistent with C++ FieldDescriptor::CppType enum in
598
+ # descriptor.h.
599
+ #
600
+ # TODO: Find a way to eliminate this repetition.
601
+ CPPTYPE_INT32 = 1
602
+ CPPTYPE_INT64 = 2
603
+ CPPTYPE_UINT32 = 3
604
+ CPPTYPE_UINT64 = 4
605
+ CPPTYPE_DOUBLE = 5
606
+ CPPTYPE_FLOAT = 6
607
+ CPPTYPE_BOOL = 7
608
+ CPPTYPE_ENUM = 8
609
+ CPPTYPE_STRING = 9
610
+ CPPTYPE_MESSAGE = 10
611
+ MAX_CPPTYPE = 10
612
+
613
+ _PYTHON_TO_CPP_PROTO_TYPE_MAP = {
614
+ TYPE_DOUBLE: CPPTYPE_DOUBLE,
615
+ TYPE_FLOAT: CPPTYPE_FLOAT,
616
+ TYPE_ENUM: CPPTYPE_ENUM,
617
+ TYPE_INT64: CPPTYPE_INT64,
618
+ TYPE_SINT64: CPPTYPE_INT64,
619
+ TYPE_SFIXED64: CPPTYPE_INT64,
620
+ TYPE_UINT64: CPPTYPE_UINT64,
621
+ TYPE_FIXED64: CPPTYPE_UINT64,
622
+ TYPE_INT32: CPPTYPE_INT32,
623
+ TYPE_SFIXED32: CPPTYPE_INT32,
624
+ TYPE_SINT32: CPPTYPE_INT32,
625
+ TYPE_UINT32: CPPTYPE_UINT32,
626
+ TYPE_FIXED32: CPPTYPE_UINT32,
627
+ TYPE_BYTES: CPPTYPE_STRING,
628
+ TYPE_STRING: CPPTYPE_STRING,
629
+ TYPE_BOOL: CPPTYPE_BOOL,
630
+ TYPE_MESSAGE: CPPTYPE_MESSAGE,
631
+ TYPE_GROUP: CPPTYPE_MESSAGE,
632
+ }
633
+
634
+ # Must be consistent with C++ FieldDescriptor::Label enum in
635
+ # descriptor.h.
636
+ #
637
+ # TODO: Find a way to eliminate this repetition.
638
+ LABEL_OPTIONAL = 1
639
+ LABEL_REQUIRED = 2
640
+ LABEL_REPEATED = 3
641
+ MAX_LABEL = 3
642
+
643
+ # Must be consistent with C++ constants kMaxNumber, kFirstReservedNumber,
644
+ # and kLastReservedNumber in descriptor.h
645
+ MAX_FIELD_NUMBER = (1 << 29) - 1
646
+ FIRST_RESERVED_FIELD_NUMBER = 19000
647
+ LAST_RESERVED_FIELD_NUMBER = 19999
648
+
649
+ if _USE_C_DESCRIPTORS:
650
+ _C_DESCRIPTOR_CLASS = _message.FieldDescriptor
651
+
652
+ def __new__(
653
+ cls,
654
+ name,
655
+ full_name,
656
+ index,
657
+ number,
658
+ type,
659
+ cpp_type,
660
+ label,
661
+ default_value,
662
+ message_type,
663
+ enum_type,
664
+ containing_type,
665
+ is_extension,
666
+ extension_scope,
667
+ options=None,
668
+ serialized_options=None,
669
+ has_default_value=True,
670
+ containing_oneof=None,
671
+ json_name=None,
672
+ file=None,
673
+ create_key=None,
674
+ ): # pylint: disable=redefined-builtin
675
+ _message.Message._CheckCalledFromGeneratedFile()
676
+ if is_extension:
677
+ return _message.default_pool.FindExtensionByName(full_name)
678
+ else:
679
+ return _message.default_pool.FindFieldByName(full_name)
680
+
681
+ def __init__(
682
+ self,
683
+ name,
684
+ full_name,
685
+ index,
686
+ number,
687
+ type,
688
+ cpp_type,
689
+ label,
690
+ default_value,
691
+ message_type,
692
+ enum_type,
693
+ containing_type,
694
+ is_extension,
695
+ extension_scope,
696
+ options=None,
697
+ serialized_options=None,
698
+ has_default_value=True,
699
+ containing_oneof=None,
700
+ json_name=None,
701
+ file=None,
702
+ create_key=None,
703
+ ): # pylint: disable=redefined-builtin
704
+ """The arguments are as described in the description of FieldDescriptor
705
+
706
+ attributes above.
707
+
708
+ Note that containing_type may be None, and may be set later if necessary
709
+ (to deal with circular references between message types, for example).
710
+ Likewise for extension_scope.
711
+ """
712
+ if create_key is not _internal_create_key:
713
+ _Deprecated('create function FieldDescriptor()')
714
+
715
+ super(FieldDescriptor, self).__init__(
716
+ file, options, serialized_options, 'FieldOptions'
717
+ )
718
+ self.name = name
719
+ self.full_name = full_name
720
+ self._camelcase_name = None
721
+ if json_name is None:
722
+ self.json_name = _ToJsonName(name)
723
+ else:
724
+ self.json_name = json_name
725
+ self.index = index
726
+ self.number = number
727
+ self._type = type
728
+ self.cpp_type = cpp_type
729
+ self._label = label
730
+ self.has_default_value = has_default_value
731
+ self.default_value = default_value
732
+ self.containing_type = containing_type
733
+ self.message_type = message_type
734
+ self.enum_type = enum_type
735
+ self.is_extension = is_extension
736
+ self.extension_scope = extension_scope
737
+ self.containing_oneof = containing_oneof
738
+ if api_implementation.Type() == 'python':
739
+ self._cdescriptor = None
740
+ else:
741
+ if is_extension:
742
+ self._cdescriptor = _message.default_pool.FindExtensionByName(full_name)
743
+ else:
744
+ self._cdescriptor = _message.default_pool.FindFieldByName(full_name)
745
+
746
+ @property
747
+ def _parent(self):
748
+ if self.containing_oneof:
749
+ return self.containing_oneof
750
+ if self.is_extension:
751
+ return self.extension_scope or self.file
752
+ return self.containing_type
753
+
754
+ def _InferLegacyFeatures(self, edition, options, features):
755
+ # pylint: disable=g-import-not-at-top
756
+ from google.protobuf import descriptor_pb2
757
+
758
+ if edition >= descriptor_pb2.Edition.EDITION_2023:
759
+ return
760
+
761
+ if self._label == FieldDescriptor.LABEL_REQUIRED:
762
+ features.field_presence = (
763
+ descriptor_pb2.FeatureSet.FieldPresence.LEGACY_REQUIRED
764
+ )
765
+
766
+ if self._type == FieldDescriptor.TYPE_GROUP:
767
+ features.message_encoding = (
768
+ descriptor_pb2.FeatureSet.MessageEncoding.DELIMITED
769
+ )
770
+
771
+ if options.HasField('packed'):
772
+ features.repeated_field_encoding = (
773
+ descriptor_pb2.FeatureSet.RepeatedFieldEncoding.PACKED
774
+ if options.packed
775
+ else descriptor_pb2.FeatureSet.RepeatedFieldEncoding.EXPANDED
776
+ )
777
+
778
+ @property
779
+ def type(self):
780
+ if (
781
+ self._GetFeatures().message_encoding
782
+ == _FEATURESET_MESSAGE_ENCODING_DELIMITED
783
+ and self.message_type
784
+ and not self.message_type.GetOptions().map_entry
785
+ and not self.containing_type.GetOptions().map_entry
786
+ ):
787
+ return FieldDescriptor.TYPE_GROUP
788
+ return self._type
789
+
790
+ @type.setter
791
+ def type(self, val):
792
+ self._type = val
793
+
794
+ @property
795
+ def is_required(self):
796
+ """Returns if the field is required."""
797
+ return (
798
+ self._GetFeatures().field_presence
799
+ == _FEATURESET_FIELD_PRESENCE_LEGACY_REQUIRED
800
+ )
801
+
802
+ @property
803
+ def is_repeated(self):
804
+ """Returns if the field is repeated."""
805
+ return self._label == FieldDescriptor.LABEL_REPEATED
806
+
807
+ @property
808
+ def camelcase_name(self):
809
+ """Camelcase name of this field.
810
+
811
+ Returns:
812
+ str: the name in CamelCase.
813
+ """
814
+ if self._camelcase_name is None:
815
+ self._camelcase_name = _ToCamelCase(self.name)
816
+ return self._camelcase_name
817
+
818
+ @property
819
+ def has_presence(self):
820
+ """Whether the field distinguishes between unpopulated and default values.
821
+
822
+ Raises:
823
+ RuntimeError: singular field that is not linked with message nor file.
824
+ """
825
+ if self.is_repeated:
826
+ return False
827
+ if (
828
+ self.cpp_type == FieldDescriptor.CPPTYPE_MESSAGE
829
+ or self.is_extension
830
+ or self.containing_oneof
831
+ ):
832
+ return True
833
+
834
+ return (
835
+ self._GetFeatures().field_presence
836
+ != _FEATURESET_FIELD_PRESENCE_IMPLICIT
837
+ )
838
+
839
+ @property
840
+ def is_packed(self):
841
+ """Returns if the field is packed."""
842
+ if not self.is_repeated:
843
+ return False
844
+ field_type = self.type
845
+ if (
846
+ field_type == FieldDescriptor.TYPE_STRING
847
+ or field_type == FieldDescriptor.TYPE_GROUP
848
+ or field_type == FieldDescriptor.TYPE_MESSAGE
849
+ or field_type == FieldDescriptor.TYPE_BYTES
850
+ ):
851
+ return False
852
+
853
+ return (
854
+ self._GetFeatures().repeated_field_encoding
855
+ == _FEATURESET_REPEATED_FIELD_ENCODING_PACKED
856
+ )
857
+
858
+ @staticmethod
859
+ def ProtoTypeToCppProtoType(proto_type):
860
+ """Converts from a Python proto type to a C++ Proto Type.
861
+
862
+ The Python ProtocolBuffer classes specify both the 'Python' datatype and the
863
+ 'C++' datatype - and they're not the same. This helper method should
864
+ translate from one to another.
865
+
866
+ Args:
867
+ proto_type: the Python proto type (descriptor.FieldDescriptor.TYPE_*)
868
+
869
+ Returns:
870
+ int: descriptor.FieldDescriptor.CPPTYPE_*, the C++ type.
871
+ Raises:
872
+ TypeTransformationError: when the Python proto type isn't known.
873
+ """
874
+ try:
875
+ return FieldDescriptor._PYTHON_TO_CPP_PROTO_TYPE_MAP[proto_type]
876
+ except KeyError:
877
+ raise TypeTransformationError('Unknown proto_type: %s' % proto_type)
878
+
879
+
880
+ class EnumDescriptor(_NestedDescriptorBase):
881
+ """Descriptor for an enum defined in a .proto file.
882
+
883
+ Attributes:
884
+ name (str): Name of the enum type.
885
+ full_name (str): Full name of the type, including package name and any
886
+ enclosing type(s).
887
+ values (list[EnumValueDescriptor]): List of the values in this enum.
888
+ values_by_name (dict(str, EnumValueDescriptor)): Same as :attr:`values`, but
889
+ indexed by the "name" field of each EnumValueDescriptor.
890
+ values_by_number (dict(int, EnumValueDescriptor)): Same as :attr:`values`,
891
+ but indexed by the "number" field of each EnumValueDescriptor.
892
+ containing_type (Descriptor): Descriptor of the immediate containing type of
893
+ this enum, or None if this is an enum defined at the top level in a .proto
894
+ file. Set by Descriptor's constructor if we're passed into one.
895
+ file (FileDescriptor): Reference to file descriptor.
896
+ options (descriptor_pb2.EnumOptions): Enum options message or None to use
897
+ default enum options.
898
+ """
899
+
900
+ if _USE_C_DESCRIPTORS:
901
+ _C_DESCRIPTOR_CLASS = _message.EnumDescriptor
902
+
903
+ def __new__(
904
+ cls,
905
+ name,
906
+ full_name,
907
+ filename,
908
+ values,
909
+ containing_type=None,
910
+ options=None,
911
+ serialized_options=None,
912
+ file=None, # pylint: disable=redefined-builtin
913
+ serialized_start=None,
914
+ serialized_end=None,
915
+ create_key=None,
916
+ ):
917
+ _message.Message._CheckCalledFromGeneratedFile()
918
+ return _message.default_pool.FindEnumTypeByName(full_name)
919
+
920
+ def __init__(
921
+ self,
922
+ name,
923
+ full_name,
924
+ filename,
925
+ values,
926
+ containing_type=None,
927
+ options=None,
928
+ serialized_options=None,
929
+ file=None, # pylint: disable=redefined-builtin
930
+ serialized_start=None,
931
+ serialized_end=None,
932
+ create_key=None,
933
+ ):
934
+ """Arguments are as described in the attribute description above.
935
+
936
+ Note that filename is an obsolete argument, that is not used anymore.
937
+ Please use file.name to access this as an attribute.
938
+ """
939
+ if create_key is not _internal_create_key:
940
+ _Deprecated('create function EnumDescriptor()')
941
+
942
+ super(EnumDescriptor, self).__init__(
943
+ options,
944
+ 'EnumOptions',
945
+ name,
946
+ full_name,
947
+ file,
948
+ containing_type,
949
+ serialized_start=serialized_start,
950
+ serialized_end=serialized_end,
951
+ serialized_options=serialized_options,
952
+ )
953
+
954
+ self.values = values
955
+ for value in self.values:
956
+ value.file = file
957
+ value.type = self
958
+ self.values_by_name = dict((v.name, v) for v in values)
959
+ # Values are reversed to ensure that the first alias is retained.
960
+ self.values_by_number = dict((v.number, v) for v in reversed(values))
961
+
962
+ @property
963
+ def _parent(self):
964
+ return self.containing_type or self.file
965
+
966
+ @property
967
+ def is_closed(self):
968
+ """Returns true whether this is a "closed" enum.
969
+
970
+ This means that it:
971
+ - Has a fixed set of values, rather than being equivalent to an int32.
972
+ - Encountering values not in this set causes them to be treated as unknown
973
+ fields.
974
+ - The first value (i.e., the default) may be nonzero.
975
+
976
+ WARNING: Some runtimes currently have a quirk where non-closed enums are
977
+ treated as closed when used as the type of fields defined in a
978
+ `syntax = proto2;` file. This quirk is not present in all runtimes; as of
979
+ writing, we know that:
980
+
981
+ - C++, Java, and C++-based Python share this quirk.
982
+ - UPB and UPB-based Python do not.
983
+ - PHP and Ruby treat all enums as open regardless of declaration.
984
+
985
+ Care should be taken when using this function to respect the target
986
+ runtime's enum handling quirks.
987
+ """
988
+ return self._GetFeatures().enum_type == _FEATURESET_ENUM_TYPE_CLOSED
989
+
990
+ def CopyToProto(self, proto):
991
+ """Copies this to a descriptor_pb2.EnumDescriptorProto.
992
+
993
+ Args:
994
+ proto (descriptor_pb2.EnumDescriptorProto): An empty descriptor proto.
995
+ """
996
+ # This function is overridden to give a better doc comment.
997
+ super(EnumDescriptor, self).CopyToProto(proto)
998
+
999
+
1000
+ class EnumValueDescriptor(DescriptorBase):
1001
+ """Descriptor for a single value within an enum.
1002
+
1003
+ Attributes:
1004
+ name (str): Name of this value.
1005
+ index (int): Dense, 0-indexed index giving the order that this value appears
1006
+ textually within its enum in the .proto file.
1007
+ number (int): Actual number assigned to this enum value.
1008
+ type (EnumDescriptor): :class:`EnumDescriptor` to which this value belongs.
1009
+ Set by :class:`EnumDescriptor`'s constructor if we're passed into one.
1010
+ options (descriptor_pb2.EnumValueOptions): Enum value options message or
1011
+ None to use default enum value options options.
1012
+ """
1013
+
1014
+ if _USE_C_DESCRIPTORS:
1015
+ _C_DESCRIPTOR_CLASS = _message.EnumValueDescriptor
1016
+
1017
+ def __new__(
1018
+ cls,
1019
+ name,
1020
+ index,
1021
+ number,
1022
+ type=None, # pylint: disable=redefined-builtin
1023
+ options=None,
1024
+ serialized_options=None,
1025
+ create_key=None,
1026
+ ):
1027
+ _message.Message._CheckCalledFromGeneratedFile()
1028
+ # There is no way we can build a complete EnumValueDescriptor with the
1029
+ # given parameters (the name of the Enum is not known, for example).
1030
+ # Fortunately generated files just pass it to the EnumDescriptor()
1031
+ # constructor, which will ignore it, so returning None is good enough.
1032
+ return None
1033
+
1034
+ def __init__(
1035
+ self,
1036
+ name,
1037
+ index,
1038
+ number,
1039
+ type=None, # pylint: disable=redefined-builtin
1040
+ options=None,
1041
+ serialized_options=None,
1042
+ create_key=None,
1043
+ ):
1044
+ """Arguments are as described in the attribute description above."""
1045
+ if create_key is not _internal_create_key:
1046
+ _Deprecated('create function EnumValueDescriptor()')
1047
+
1048
+ super(EnumValueDescriptor, self).__init__(
1049
+ type.file if type else None,
1050
+ options,
1051
+ serialized_options,
1052
+ 'EnumValueOptions',
1053
+ )
1054
+ self.name = name
1055
+ self.index = index
1056
+ self.number = number
1057
+ self.type = type
1058
+
1059
+ @property
1060
+ def _parent(self):
1061
+ return self.type
1062
+
1063
+
1064
+ class OneofDescriptor(DescriptorBase):
1065
+ """Descriptor for a oneof field.
1066
+
1067
+ Attributes:
1068
+ name (str): Name of the oneof field.
1069
+ full_name (str): Full name of the oneof field, including package name.
1070
+ index (int): 0-based index giving the order of the oneof field inside its
1071
+ containing type.
1072
+ containing_type (Descriptor): :class:`Descriptor` of the protocol message
1073
+ type that contains this field. Set by the :class:`Descriptor` constructor
1074
+ if we're passed into one.
1075
+ fields (list[FieldDescriptor]): The list of field descriptors this oneof can
1076
+ contain.
1077
+ """
1078
+
1079
+ if _USE_C_DESCRIPTORS:
1080
+ _C_DESCRIPTOR_CLASS = _message.OneofDescriptor
1081
+
1082
+ def __new__(
1083
+ cls,
1084
+ name,
1085
+ full_name,
1086
+ index,
1087
+ containing_type,
1088
+ fields,
1089
+ options=None,
1090
+ serialized_options=None,
1091
+ create_key=None,
1092
+ ):
1093
+ _message.Message._CheckCalledFromGeneratedFile()
1094
+ return _message.default_pool.FindOneofByName(full_name)
1095
+
1096
+ def __init__(
1097
+ self,
1098
+ name,
1099
+ full_name,
1100
+ index,
1101
+ containing_type,
1102
+ fields,
1103
+ options=None,
1104
+ serialized_options=None,
1105
+ create_key=None,
1106
+ ):
1107
+ """Arguments are as described in the attribute description above."""
1108
+ if create_key is not _internal_create_key:
1109
+ _Deprecated('create function OneofDescriptor()')
1110
+
1111
+ super(OneofDescriptor, self).__init__(
1112
+ containing_type.file if containing_type else None,
1113
+ options,
1114
+ serialized_options,
1115
+ 'OneofOptions',
1116
+ )
1117
+ self.name = name
1118
+ self.full_name = full_name
1119
+ self.index = index
1120
+ self.containing_type = containing_type
1121
+ self.fields = fields
1122
+
1123
+ @property
1124
+ def _parent(self):
1125
+ return self.containing_type
1126
+
1127
+
1128
+ class ServiceDescriptor(_NestedDescriptorBase):
1129
+ """Descriptor for a service.
1130
+
1131
+ Attributes:
1132
+ name (str): Name of the service.
1133
+ full_name (str): Full name of the service, including package name.
1134
+ index (int): 0-indexed index giving the order that this services definition
1135
+ appears within the .proto file.
1136
+ methods (list[MethodDescriptor]): List of methods provided by this service.
1137
+ methods_by_name (dict(str, MethodDescriptor)): Same
1138
+ :class:`MethodDescriptor` objects as in :attr:`methods_by_name`, but
1139
+ indexed by "name" attribute in each :class:`MethodDescriptor`.
1140
+ options (descriptor_pb2.ServiceOptions): Service options message or None to
1141
+ use default service options.
1142
+ file (FileDescriptor): Reference to file info.
1143
+ """
1144
+
1145
+ if _USE_C_DESCRIPTORS:
1146
+ _C_DESCRIPTOR_CLASS = _message.ServiceDescriptor
1147
+
1148
+ def __new__(
1149
+ cls,
1150
+ name=None,
1151
+ full_name=None,
1152
+ index=None,
1153
+ methods=None,
1154
+ options=None,
1155
+ serialized_options=None,
1156
+ file=None, # pylint: disable=redefined-builtin
1157
+ serialized_start=None,
1158
+ serialized_end=None,
1159
+ create_key=None,
1160
+ ):
1161
+ _message.Message._CheckCalledFromGeneratedFile() # pylint: disable=protected-access
1162
+ return _message.default_pool.FindServiceByName(full_name)
1163
+
1164
+ def __init__(
1165
+ self,
1166
+ name,
1167
+ full_name,
1168
+ index,
1169
+ methods,
1170
+ options=None,
1171
+ serialized_options=None,
1172
+ file=None, # pylint: disable=redefined-builtin
1173
+ serialized_start=None,
1174
+ serialized_end=None,
1175
+ create_key=None,
1176
+ ):
1177
+ if create_key is not _internal_create_key:
1178
+ _Deprecated('create function ServiceDescriptor()')
1179
+
1180
+ super(ServiceDescriptor, self).__init__(
1181
+ options,
1182
+ 'ServiceOptions',
1183
+ name,
1184
+ full_name,
1185
+ file,
1186
+ None,
1187
+ serialized_start=serialized_start,
1188
+ serialized_end=serialized_end,
1189
+ serialized_options=serialized_options,
1190
+ )
1191
+ self.index = index
1192
+ self.methods = methods
1193
+ self.methods_by_name = dict((m.name, m) for m in methods)
1194
+ # Set the containing service for each method in this service.
1195
+ for method in self.methods:
1196
+ method.file = self.file
1197
+ method.containing_service = self
1198
+
1199
+ @property
1200
+ def _parent(self):
1201
+ return self.file
1202
+
1203
+ def FindMethodByName(self, name):
1204
+ """Searches for the specified method, and returns its descriptor.
1205
+
1206
+ Args:
1207
+ name (str): Name of the method.
1208
+
1209
+ Returns:
1210
+ MethodDescriptor: The descriptor for the requested method.
1211
+
1212
+ Raises:
1213
+ KeyError: if the method cannot be found in the service.
1214
+ """
1215
+ return self.methods_by_name[name]
1216
+
1217
+ def CopyToProto(self, proto):
1218
+ """Copies this to a descriptor_pb2.ServiceDescriptorProto.
1219
+
1220
+ Args:
1221
+ proto (descriptor_pb2.ServiceDescriptorProto): An empty descriptor proto.
1222
+ """
1223
+ # This function is overridden to give a better doc comment.
1224
+ super(ServiceDescriptor, self).CopyToProto(proto)
1225
+
1226
+
1227
+ class MethodDescriptor(DescriptorBase):
1228
+ """Descriptor for a method in a service.
1229
+
1230
+ Attributes:
1231
+ name (str): Name of the method within the service.
1232
+ full_name (str): Full name of method.
1233
+ index (int): 0-indexed index of the method inside the service.
1234
+ containing_service (ServiceDescriptor): The service that contains this
1235
+ method.
1236
+ input_type (Descriptor): The descriptor of the message that this method
1237
+ accepts.
1238
+ output_type (Descriptor): The descriptor of the message that this method
1239
+ returns.
1240
+ client_streaming (bool): Whether this method uses client streaming.
1241
+ server_streaming (bool): Whether this method uses server streaming.
1242
+ options (descriptor_pb2.MethodOptions or None): Method options message, or
1243
+ None to use default method options.
1244
+ """
1245
+
1246
+ if _USE_C_DESCRIPTORS:
1247
+ _C_DESCRIPTOR_CLASS = _message.MethodDescriptor
1248
+
1249
+ def __new__(
1250
+ cls,
1251
+ name,
1252
+ full_name,
1253
+ index,
1254
+ containing_service,
1255
+ input_type,
1256
+ output_type,
1257
+ client_streaming=False,
1258
+ server_streaming=False,
1259
+ options=None,
1260
+ serialized_options=None,
1261
+ create_key=None,
1262
+ ):
1263
+ _message.Message._CheckCalledFromGeneratedFile() # pylint: disable=protected-access
1264
+ return _message.default_pool.FindMethodByName(full_name)
1265
+
1266
+ def __init__(
1267
+ self,
1268
+ name,
1269
+ full_name,
1270
+ index,
1271
+ containing_service,
1272
+ input_type,
1273
+ output_type,
1274
+ client_streaming=False,
1275
+ server_streaming=False,
1276
+ options=None,
1277
+ serialized_options=None,
1278
+ create_key=None,
1279
+ ):
1280
+ """The arguments are as described in the description of MethodDescriptor
1281
+
1282
+ attributes above.
1283
+
1284
+ Note that containing_service may be None, and may be set later if necessary.
1285
+ """
1286
+ if create_key is not _internal_create_key:
1287
+ _Deprecated('create function MethodDescriptor()')
1288
+
1289
+ super(MethodDescriptor, self).__init__(
1290
+ containing_service.file if containing_service else None,
1291
+ options,
1292
+ serialized_options,
1293
+ 'MethodOptions',
1294
+ )
1295
+ self.name = name
1296
+ self.full_name = full_name
1297
+ self.index = index
1298
+ self.containing_service = containing_service
1299
+ self.input_type = input_type
1300
+ self.output_type = output_type
1301
+ self.client_streaming = client_streaming
1302
+ self.server_streaming = server_streaming
1303
+
1304
+ @property
1305
+ def _parent(self):
1306
+ return self.containing_service
1307
+
1308
+ def CopyToProto(self, proto):
1309
+ """Copies this to a descriptor_pb2.MethodDescriptorProto.
1310
+
1311
+ Args:
1312
+ proto (descriptor_pb2.MethodDescriptorProto): An empty descriptor proto.
1313
+
1314
+ Raises:
1315
+ Error: If self couldn't be serialized, due to too few constructor
1316
+ arguments.
1317
+ """
1318
+ if self.containing_service is not None:
1319
+ from google.protobuf import descriptor_pb2
1320
+
1321
+ service_proto = descriptor_pb2.ServiceDescriptorProto()
1322
+ self.containing_service.CopyToProto(service_proto)
1323
+ proto.CopyFrom(service_proto.method[self.index])
1324
+ else:
1325
+ raise Error('Descriptor does not contain a service.')
1326
+
1327
+
1328
+ class FileDescriptor(DescriptorBase):
1329
+ """Descriptor for a file. Mimics the descriptor_pb2.FileDescriptorProto.
1330
+
1331
+ Note that :attr:`enum_types_by_name`, :attr:`extensions_by_name`, and
1332
+ :attr:`dependencies` fields are only set by the
1333
+ :py:mod:`google.protobuf.message_factory` module, and not by the generated
1334
+ proto code.
1335
+
1336
+ Attributes:
1337
+ name (str): Name of file, relative to root of source tree.
1338
+ package (str): Name of the package
1339
+ edition (Edition): Enum value indicating edition of the file
1340
+ serialized_pb (bytes): Byte string of serialized
1341
+ :class:`descriptor_pb2.FileDescriptorProto`.
1342
+ dependencies (list[FileDescriptor]): List of other :class:`FileDescriptor`
1343
+ objects this :class:`FileDescriptor` depends on.
1344
+ public_dependencies (list[FileDescriptor]): A subset of
1345
+ :attr:`dependencies`, which were declared as "public".
1346
+ message_types_by_name (dict(str, Descriptor)): Mapping from message names to
1347
+ their :class:`Descriptor`.
1348
+ enum_types_by_name (dict(str, EnumDescriptor)): Mapping from enum names to
1349
+ their :class:`EnumDescriptor`.
1350
+ extensions_by_name (dict(str, FieldDescriptor)): Mapping from extension
1351
+ names declared at file scope to their :class:`FieldDescriptor`.
1352
+ services_by_name (dict(str, ServiceDescriptor)): Mapping from services'
1353
+ names to their :class:`ServiceDescriptor`.
1354
+ pool (DescriptorPool): The pool this descriptor belongs to. When not passed
1355
+ to the constructor, the global default pool is used.
1356
+ """
1357
+
1358
+ if _USE_C_DESCRIPTORS:
1359
+ _C_DESCRIPTOR_CLASS = _message.FileDescriptor
1360
+
1361
+ def __new__(
1362
+ cls,
1363
+ name,
1364
+ package,
1365
+ options=None,
1366
+ serialized_options=None,
1367
+ serialized_pb=None,
1368
+ dependencies=None,
1369
+ public_dependencies=None,
1370
+ syntax=None,
1371
+ edition=None,
1372
+ pool=None,
1373
+ create_key=None,
1374
+ ):
1375
+ # FileDescriptor() is called from various places, not only from generated
1376
+ # files, to register dynamic proto files and messages.
1377
+ # pylint: disable=g-explicit-bool-comparison
1378
+ if serialized_pb:
1379
+ return _message.default_pool.AddSerializedFile(serialized_pb)
1380
+ else:
1381
+ return super(FileDescriptor, cls).__new__(cls)
1382
+
1383
+ def __init__(
1384
+ self,
1385
+ name,
1386
+ package,
1387
+ options=None,
1388
+ serialized_options=None,
1389
+ serialized_pb=None,
1390
+ dependencies=None,
1391
+ public_dependencies=None,
1392
+ syntax=None,
1393
+ edition=None,
1394
+ pool=None,
1395
+ create_key=None,
1396
+ ):
1397
+ """Constructor."""
1398
+ if create_key is not _internal_create_key:
1399
+ _Deprecated('create function FileDescriptor()')
1400
+
1401
+ super(FileDescriptor, self).__init__(
1402
+ self, options, serialized_options, 'FileOptions'
1403
+ )
1404
+
1405
+ if edition and edition != 'EDITION_UNKNOWN':
1406
+ self._edition = edition
1407
+ elif syntax == 'proto3':
1408
+ self._edition = 'EDITION_PROTO3'
1409
+ else:
1410
+ self._edition = 'EDITION_PROTO2'
1411
+
1412
+ if pool is None:
1413
+ from google.protobuf import descriptor_pool
1414
+
1415
+ pool = descriptor_pool.Default()
1416
+ self.pool = pool
1417
+ self.message_types_by_name = {}
1418
+ self.name = name
1419
+ self.package = package
1420
+ self.serialized_pb = serialized_pb
1421
+
1422
+ self.enum_types_by_name = {}
1423
+ self.extensions_by_name = {}
1424
+ self.services_by_name = {}
1425
+ self.dependencies = dependencies or []
1426
+ self.public_dependencies = public_dependencies or []
1427
+
1428
+ def CopyToProto(self, proto):
1429
+ """Copies this to a descriptor_pb2.FileDescriptorProto.
1430
+
1431
+ Args:
1432
+ proto: An empty descriptor_pb2.FileDescriptorProto.
1433
+ """
1434
+ proto.ParseFromString(self.serialized_pb)
1435
+
1436
+ @property
1437
+ def _parent(self):
1438
+ return None
1439
+
1440
+
1441
+ def _ParseOptions(message, string):
1442
+ """Parses serialized options.
1443
+
1444
+ This helper function is used to parse serialized options in generated
1445
+ proto2 files. It must not be used outside proto2.
1446
+ """
1447
+ message.ParseFromString(string)
1448
+ return message
1449
+
1450
+
1451
+ def _ToCamelCase(name):
1452
+ """Converts name to camel-case and returns it."""
1453
+ capitalize_next = False
1454
+ result = []
1455
+
1456
+ for c in name:
1457
+ if c == '_':
1458
+ if result:
1459
+ capitalize_next = True
1460
+ elif capitalize_next:
1461
+ result.append(c.upper())
1462
+ capitalize_next = False
1463
+ else:
1464
+ result += c
1465
+
1466
+ # Lower-case the first letter.
1467
+ if result and result[0].isupper():
1468
+ result[0] = result[0].lower()
1469
+ return ''.join(result)
1470
+
1471
+
1472
+ def _OptionsOrNone(descriptor_proto):
1473
+ """Returns the value of the field `options`, or None if it is not set."""
1474
+ if descriptor_proto.HasField('options'):
1475
+ return descriptor_proto.options
1476
+ else:
1477
+ return None
1478
+
1479
+
1480
+ def _ToJsonName(name):
1481
+ """Converts name to Json name and returns it."""
1482
+ capitalize_next = False
1483
+ result = []
1484
+
1485
+ for c in name:
1486
+ if c == '_':
1487
+ capitalize_next = True
1488
+ elif capitalize_next:
1489
+ result.append(c.upper())
1490
+ capitalize_next = False
1491
+ else:
1492
+ result += c
1493
+
1494
+ return ''.join(result)
1495
+
1496
+
1497
+ def MakeDescriptor(
1498
+ desc_proto,
1499
+ package='',
1500
+ build_file_if_cpp=True,
1501
+ syntax=None,
1502
+ edition=None,
1503
+ file_desc=None,
1504
+ ):
1505
+ """Make a protobuf Descriptor given a DescriptorProto protobuf.
1506
+
1507
+ Handles nested descriptors. Note that this is limited to the scope of defining
1508
+ a message inside of another message. Composite fields can currently only be
1509
+ resolved if the message is defined in the same scope as the field.
1510
+
1511
+ Args:
1512
+ desc_proto: The descriptor_pb2.DescriptorProto protobuf message.
1513
+ package: Optional package name for the new message Descriptor (string).
1514
+ build_file_if_cpp: Update the C++ descriptor pool if api matches. Set to
1515
+ False on recursion, so no duplicates are created.
1516
+ syntax: The syntax/semantics that should be used. Set to "proto3" to get
1517
+ proto3 field presence semantics.
1518
+ edition: The edition that should be used if syntax is "edition".
1519
+ file_desc: A FileDescriptor to place this descriptor into.
1520
+
1521
+ Returns:
1522
+ A Descriptor for protobuf messages.
1523
+ """
1524
+ # pylint: disable=g-import-not-at-top
1525
+ from google.protobuf import descriptor_pb2
1526
+
1527
+ # Generate a random name for this proto file to prevent conflicts with any
1528
+ # imported ones. We need to specify a file name so the descriptor pool
1529
+ # accepts our FileDescriptorProto, but it is not important what that file
1530
+ # name is actually set to.
1531
+ proto_name = binascii.hexlify(os.urandom(16)).decode('ascii')
1532
+
1533
+ if package:
1534
+ file_name = os.path.join(package.replace('.', '/'), proto_name + '.proto')
1535
+ else:
1536
+ file_name = proto_name + '.proto'
1537
+
1538
+ if api_implementation.Type() != 'python' and build_file_if_cpp:
1539
+ # The C++ implementation requires all descriptors to be backed by the same
1540
+ # definition in the C++ descriptor pool. To do this, we build a
1541
+ # FileDescriptorProto with the same definition as this descriptor and build
1542
+ # it into the pool.
1543
+ file_descriptor_proto = descriptor_pb2.FileDescriptorProto()
1544
+ file_descriptor_proto.message_type.add().MergeFrom(desc_proto)
1545
+
1546
+ if package:
1547
+ file_descriptor_proto.package = package
1548
+ file_descriptor_proto.name = file_name
1549
+
1550
+ _message.default_pool.Add(file_descriptor_proto)
1551
+ result = _message.default_pool.FindFileByName(file_descriptor_proto.name)
1552
+
1553
+ if _USE_C_DESCRIPTORS:
1554
+ return result.message_types_by_name[desc_proto.name]
1555
+
1556
+ if file_desc is None:
1557
+ file_desc = FileDescriptor(
1558
+ pool=None,
1559
+ name=file_name,
1560
+ package=package,
1561
+ syntax=syntax,
1562
+ edition=edition,
1563
+ options=None,
1564
+ serialized_pb='',
1565
+ dependencies=[],
1566
+ public_dependencies=[],
1567
+ create_key=_internal_create_key,
1568
+ )
1569
+ full_message_name = [desc_proto.name]
1570
+ if package:
1571
+ full_message_name.insert(0, package)
1572
+
1573
+ # Create Descriptors for enum types
1574
+ enum_types = {}
1575
+ for enum_proto in desc_proto.enum_type:
1576
+ full_name = '.'.join(full_message_name + [enum_proto.name])
1577
+ enum_desc = EnumDescriptor(
1578
+ enum_proto.name,
1579
+ full_name,
1580
+ None,
1581
+ [
1582
+ EnumValueDescriptor(
1583
+ enum_val.name,
1584
+ ii,
1585
+ enum_val.number,
1586
+ create_key=_internal_create_key,
1587
+ )
1588
+ for ii, enum_val in enumerate(enum_proto.value)
1589
+ ],
1590
+ file=file_desc,
1591
+ create_key=_internal_create_key,
1592
+ )
1593
+ enum_types[full_name] = enum_desc
1594
+
1595
+ # Create Descriptors for nested types
1596
+ nested_types = {}
1597
+ for nested_proto in desc_proto.nested_type:
1598
+ full_name = '.'.join(full_message_name + [nested_proto.name])
1599
+ # Nested types are just those defined inside of the message, not all types
1600
+ # used by fields in the message, so no loops are possible here.
1601
+ nested_desc = MakeDescriptor(
1602
+ nested_proto,
1603
+ package='.'.join(full_message_name),
1604
+ build_file_if_cpp=False,
1605
+ syntax=syntax,
1606
+ edition=edition,
1607
+ file_desc=file_desc,
1608
+ )
1609
+ nested_types[full_name] = nested_desc
1610
+
1611
+ fields = []
1612
+ for field_proto in desc_proto.field:
1613
+ full_name = '.'.join(full_message_name + [field_proto.name])
1614
+ enum_desc = None
1615
+ nested_desc = None
1616
+ if field_proto.json_name:
1617
+ json_name = field_proto.json_name
1618
+ else:
1619
+ json_name = None
1620
+ if field_proto.HasField('type_name'):
1621
+ type_name = field_proto.type_name
1622
+ full_type_name = '.'.join(
1623
+ full_message_name + [type_name[type_name.rfind('.') + 1 :]]
1624
+ )
1625
+ if full_type_name in nested_types:
1626
+ nested_desc = nested_types[full_type_name]
1627
+ elif full_type_name in enum_types:
1628
+ enum_desc = enum_types[full_type_name]
1629
+ # Else type_name references a non-local type, which isn't implemented
1630
+ field = FieldDescriptor(
1631
+ field_proto.name,
1632
+ full_name,
1633
+ field_proto.number - 1,
1634
+ field_proto.number,
1635
+ field_proto.type,
1636
+ FieldDescriptor.ProtoTypeToCppProtoType(field_proto.type),
1637
+ field_proto.label,
1638
+ None,
1639
+ nested_desc,
1640
+ enum_desc,
1641
+ None,
1642
+ False,
1643
+ None,
1644
+ options=_OptionsOrNone(field_proto),
1645
+ has_default_value=False,
1646
+ json_name=json_name,
1647
+ file=file_desc,
1648
+ create_key=_internal_create_key,
1649
+ )
1650
+ fields.append(field)
1651
+
1652
+ desc_name = '.'.join(full_message_name)
1653
+ return Descriptor(
1654
+ desc_proto.name,
1655
+ desc_name,
1656
+ None,
1657
+ None,
1658
+ fields,
1659
+ list(nested_types.values()),
1660
+ list(enum_types.values()),
1661
+ [],
1662
+ options=_OptionsOrNone(desc_proto),
1663
+ file=file_desc,
1664
+ create_key=_internal_create_key,
1665
+ )
ScaleDF_rebuttal/python_dedup_pkgs/google/protobuf/descriptor_database.py ADDED
@@ -0,0 +1,185 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Protocol Buffers - Google's data interchange format
2
+ # Copyright 2008 Google Inc. All rights reserved.
3
+ #
4
+ # Use of this source code is governed by a BSD-style
5
+ # license that can be found in the LICENSE file or at
6
+ # https://developers.google.com/open-source/licenses/bsd
7
+
8
+ """Provides a container for DescriptorProtos."""
9
+
10
+ __author__ = 'matthewtoia@google.com (Matt Toia)'
11
+
12
+ from typing import Dict, Iterator, Optional
13
+ import warnings
14
+
15
+
16
+ class Error(Exception):
17
+ pass
18
+
19
+
20
+ class DescriptorDatabaseConflictingDefinitionError(Error):
21
+ """Raised when a proto is added with the same name & different descriptor."""
22
+
23
+
24
+ class DescriptorDatabase(object):
25
+ """A container accepting FileDescriptorProtos and maps DescriptorProtos."""
26
+
27
+ def __init__(self) -> None:
28
+ self._file_desc_protos_by_file: Dict[
29
+ str, 'descriptor_pb2.FileDescriptorProto'
30
+ ] = {}
31
+ self._file_desc_protos_by_symbol: Dict[
32
+ str, 'descriptor_pb2.FileDescriptorProto'
33
+ ] = {}
34
+
35
+ def Add(self, file_desc_proto: 'descriptor_pb2.FileDescriptorProto') -> None:
36
+ """Adds the FileDescriptorProto and its types to this database.
37
+
38
+ Args:
39
+ file_desc_proto: The FileDescriptorProto to add.
40
+ Raises:
41
+ DescriptorDatabaseConflictingDefinitionError: if an attempt is made to
42
+ add a proto with the same name but different definition than an
43
+ existing proto in the database.
44
+ """
45
+ proto_name = file_desc_proto.name
46
+ if proto_name not in self._file_desc_protos_by_file:
47
+ self._file_desc_protos_by_file[proto_name] = file_desc_proto
48
+ elif self._file_desc_protos_by_file[proto_name] != file_desc_proto:
49
+ raise DescriptorDatabaseConflictingDefinitionError(
50
+ '%s already added, but with different descriptor.' % proto_name)
51
+ else:
52
+ return
53
+
54
+ # Add all the top-level descriptors to the index.
55
+ package = file_desc_proto.package
56
+ for message in file_desc_proto.message_type:
57
+ for name in _ExtractSymbols(message, package):
58
+ self._AddSymbol(name, file_desc_proto)
59
+ for enum in file_desc_proto.enum_type:
60
+ self._AddSymbol(
61
+ ('.'.join((package, enum.name)) if package else enum.name),
62
+ file_desc_proto,
63
+ )
64
+ for enum_value in enum.value:
65
+ self._file_desc_protos_by_symbol[
66
+ '.'.join((package, enum_value.name)) if package else enum_value.name
67
+ ] = file_desc_proto
68
+ for extension in file_desc_proto.extension:
69
+ self._AddSymbol(
70
+ ('.'.join((package, extension.name)) if package else extension.name),
71
+ file_desc_proto,
72
+ )
73
+ for service in file_desc_proto.service:
74
+ self._AddSymbol(
75
+ ('.'.join((package, service.name)) if package else service.name),
76
+ file_desc_proto,
77
+ )
78
+
79
+ def FindFileByName(self, name: str) -> 'descriptor_pb2.FileDescriptorProto':
80
+ """Finds the file descriptor proto by file name.
81
+
82
+ Typically the file name is a relative path ending to a .proto file. The
83
+ proto with the given name will have to have been added to this database
84
+ using the Add method or else an error will be raised.
85
+
86
+ Args:
87
+ name: The file name to find.
88
+
89
+ Returns:
90
+ The file descriptor proto matching the name.
91
+
92
+ Raises:
93
+ KeyError if no file by the given name was added.
94
+ """
95
+
96
+ return self._file_desc_protos_by_file[name]
97
+
98
+ def FindFileContainingSymbol(
99
+ self, symbol: str
100
+ ) -> 'descriptor_pb2.FileDescriptorProto':
101
+ """Finds the file descriptor proto containing the specified symbol.
102
+
103
+ The symbol should be a fully qualified name including the file descriptor's
104
+ package and any containing messages. Some examples:
105
+
106
+ 'some.package.name.Message'
107
+ 'some.package.name.Message.NestedEnum'
108
+ 'some.package.name.Message.some_field'
109
+
110
+ The file descriptor proto containing the specified symbol must be added to
111
+ this database using the Add method or else an error will be raised.
112
+
113
+ Args:
114
+ symbol: The fully qualified symbol name.
115
+
116
+ Returns:
117
+ The file descriptor proto containing the symbol.
118
+
119
+ Raises:
120
+ KeyError if no file contains the specified symbol.
121
+ """
122
+ if symbol.count('.') == 1 and symbol[0] == '.':
123
+ symbol = symbol.lstrip('.')
124
+ warnings.warn(
125
+ 'Please remove the leading "." when '
126
+ 'FindFileContainingSymbol, this will turn to error '
127
+ 'in 2026 Jan.',
128
+ RuntimeWarning,
129
+ )
130
+ try:
131
+ return self._file_desc_protos_by_symbol[symbol]
132
+ except KeyError:
133
+ # Fields, enum values, and nested extensions are not in
134
+ # _file_desc_protos_by_symbol. Try to find the top level
135
+ # descriptor. Non-existent nested symbol under a valid top level
136
+ # descriptor can also be found. The behavior is the same with
137
+ # protobuf C++.
138
+ top_level, _, _ = symbol.rpartition('.')
139
+ try:
140
+ return self._file_desc_protos_by_symbol[top_level]
141
+ except KeyError:
142
+ # Raise the original symbol as a KeyError for better diagnostics.
143
+ raise KeyError(symbol)
144
+
145
+ def FindFileContainingExtension(
146
+ self, extendee_name: str, extension_number: int # pylint: disable=unused-argument
147
+ ) -> Optional['descriptor_pb2.FileDescriptorProto']:
148
+ # TODO: implement this API.
149
+ return None
150
+
151
+ def FindAllExtensionNumbers(self, extendee_name: str) -> list[int]: # pylint: disable=unused-argument
152
+ # TODO: implement this API.
153
+ return []
154
+
155
+ def _AddSymbol(
156
+ self, name: str, file_desc_proto: 'descriptor_pb2.FileDescriptorProto'
157
+ ) -> None:
158
+ if name in self._file_desc_protos_by_symbol:
159
+ warn_msg = ('Conflict register for file "' + file_desc_proto.name +
160
+ '": ' + name +
161
+ ' is already defined in file "' +
162
+ self._file_desc_protos_by_symbol[name].name + '"')
163
+ warnings.warn(warn_msg, RuntimeWarning)
164
+ self._file_desc_protos_by_symbol[name] = file_desc_proto
165
+
166
+
167
+ def _ExtractSymbols(
168
+ desc_proto: 'descriptor_pb2.DescriptorProto', package: str
169
+ ) -> Iterator[str]:
170
+ """Pulls out all the symbols from a descriptor proto.
171
+
172
+ Args:
173
+ desc_proto: The proto to extract symbols from.
174
+ package: The package containing the descriptor type.
175
+
176
+ Yields:
177
+ The fully qualified name found in the descriptor.
178
+ """
179
+ message_name = package + '.' + desc_proto.name if package else desc_proto.name
180
+ yield message_name
181
+ for nested_type in desc_proto.nested_type:
182
+ for symbol in _ExtractSymbols(nested_type, message_name):
183
+ yield symbol
184
+ for enum_type in desc_proto.enum_type:
185
+ yield '.'.join((message_name, enum_type.name))
ScaleDF_rebuttal/python_dedup_pkgs/google/protobuf/descriptor_pb2.py ADDED
The diff for this file is too large to render. See raw diff