-
Notifications
You must be signed in to change notification settings - Fork 3.5k
/
torch_test_contrib_gpu.py
472 lines (374 loc) · 17 KB
/
torch_test_contrib_gpu.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import faiss
import torch
import unittest
import numpy as np
import faiss.contrib.torch_utils
def to_column_major_torch(x):
if hasattr(torch, 'contiguous_format'):
return x.t().clone(memory_format=torch.contiguous_format).t()
else:
# was default setting before memory_format was introduced
return x.t().clone().t()
def to_column_major_numpy(x):
return x.T.copy().T
class TestTorchUtilsGPU(unittest.TestCase):
# tests add, search
def test_lookup(self):
cpu_index = faiss.IndexFlatL2(128)
# Add to CPU index with np
xb_torch = torch.rand(10000, 128)
cpu_index.add(xb_torch.numpy())
# Add to CPU index with torch GPU (should fail)
xb_torch_gpu = torch.rand(10000, 128, device=torch.device('cuda', 0), dtype=torch.float32)
with self.assertRaises(AssertionError):
cpu_index.add(xb_torch_gpu)
# Add to GPU with torch GPU
res = faiss.StandardGpuResources()
gpu_index = faiss.GpuIndexFlatL2(res, 128)
gpu_index.add(xb_torch.cuda())
# Search with torch CPU
xq_torch_cpu = torch.rand(10, 128, dtype=torch.float32)
d_torch_cpu, i_torch_cpu = gpu_index.search(xq_torch_cpu, 10)
# Search with torch GPU
xq_torch_gpu = xq_torch_cpu.cuda()
d_torch_gpu, i_torch_gpu = gpu_index.search(xq_torch_gpu, 10)
self.assertTrue(d_torch_gpu.is_cuda)
self.assertTrue(i_torch_gpu.is_cuda)
# Should be equivalent
self.assertTrue(torch.equal(d_torch_cpu.cuda(), d_torch_gpu))
self.assertTrue(torch.equal(i_torch_cpu.cuda(), i_torch_gpu))
# Search with torch GPU using pre-allocated arrays
new_d_torch_gpu = torch.zeros(10, 10, device=torch.device('cuda', 0), dtype=torch.float32)
new_i_torch_gpu = torch.zeros(10, 10, device=torch.device('cuda', 0), dtype=torch.int64)
gpu_index.search(xq_torch_gpu, 10, new_d_torch_gpu, new_i_torch_gpu)
self.assertTrue(torch.equal(d_torch_cpu.cuda(), new_d_torch_gpu))
self.assertTrue(torch.equal(i_torch_cpu.cuda(), new_i_torch_gpu))
# Search with numpy CPU
xq_np_cpu = xq_torch_cpu.numpy()
d_np_cpu, i_np_cpu = gpu_index.search(xq_np_cpu, 10)
self.assertEqual(type(d_np_cpu), np.ndarray)
self.assertEqual(type(i_np_cpu), np.ndarray)
self.assertTrue(np.array_equal(d_torch_cpu.numpy(), d_np_cpu))
self.assertTrue(np.array_equal(i_torch_cpu.numpy(), i_np_cpu))
# tests train, add_with_ids
def test_train_add_with_ids(self):
d = 32
nlist = 5
res = faiss.StandardGpuResources()
res.noTempMemory()
index = faiss.GpuIndexIVFFlat(res, d, nlist, faiss.METRIC_L2)
xb = torch.rand(1000, d, device=torch.device('cuda', 0), dtype=torch.float32)
index.train(xb)
ids = torch.arange(1000, 1000 + xb.shape[0], device=torch.device('cuda', 0), dtype=torch.int64)
# Test add_with_ids with torch gpu
index.add_with_ids(xb, ids)
_, I = index.search(xb[10:20], 1)
self.assertTrue(torch.equal(I.view(10), ids[10:20]))
# Test add_with_ids with torch cpu
index.reset()
xb_cpu = xb.cpu()
ids_cpu = ids.cpu()
index.train(xb_cpu)
index.add_with_ids(xb_cpu, ids_cpu)
_, I = index.search(xb_cpu[10:20], 1)
self.assertTrue(torch.equal(I.view(10), ids_cpu[10:20]))
# Test add_with_ids with numpy
index.reset()
xb_np = xb.cpu().numpy()
ids_np = ids.cpu().numpy()
index.train(xb_np)
index.add_with_ids(xb_np, ids_np)
_, I = index.search(xb_np[10:20], 1)
self.assertTrue(np.array_equal(I.reshape(10), ids_np[10:20]))
# tests reconstruct, reconstruct_n
def test_flat_reconstruct(self):
d = 32
res = faiss.StandardGpuResources()
res.noTempMemory()
index = faiss.GpuIndexFlatL2(res, d)
xb = torch.rand(100, d, device=torch.device('cuda', 0), dtype=torch.float32)
index.add(xb)
# Test reconstruct with torch gpu (native return)
y = index.reconstruct(7)
self.assertTrue(y.is_cuda)
self.assertTrue(torch.equal(xb[7], y))
# Test reconstruct with numpy output provided
y = np.empty(d, dtype='float32')
index.reconstruct(11, y)
self.assertTrue(np.array_equal(xb.cpu().numpy()[11], y))
# Test reconstruct with torch cpu output providesd
y = torch.empty(d, dtype=torch.float32)
index.reconstruct(12, y)
self.assertTrue(torch.equal(xb[12].cpu(), y))
# Test reconstruct with torch gpu output providesd
y = torch.empty(d, device=torch.device('cuda', 0), dtype=torch.float32)
index.reconstruct(13, y)
self.assertTrue(torch.equal(xb[13], y))
# Test reconstruct_n with torch gpu (native return)
y = index.reconstruct_n(10, 10)
self.assertTrue(y.is_cuda)
self.assertTrue(torch.equal(xb[10:20], y))
# Test reconstruct with numpy output provided
y = np.empty((10, d), dtype='float32')
index.reconstruct_n(20, 10, y)
self.assertTrue(np.array_equal(xb.cpu().numpy()[20:30], y))
# Test reconstruct_n with torch cpu output provided
y = torch.empty(10, d, dtype=torch.float32)
index.reconstruct_n(40, 10, y)
self.assertTrue(torch.equal(xb[40:50].cpu(), y))
# Test reconstruct_n with torch gpu output provided
y = torch.empty(10, d, device=torch.device('cuda', 0), dtype=torch.float32)
index.reconstruct_n(50, 10, y)
self.assertTrue(torch.equal(xb[50:60], y))
def test_ivfflat_reconstruct(self):
d = 32
nlist = 5
res = faiss.StandardGpuResources()
res.noTempMemory()
config = faiss.GpuIndexIVFFlatConfig()
config.use_raft = False
index = faiss.GpuIndexIVFFlat(res, d, nlist, faiss.METRIC_L2, config)
xb = torch.rand(100, d, device=torch.device('cuda', 0), dtype=torch.float32)
index.train(xb)
index.add(xb)
# Test reconstruct_n with torch gpu (native return)
y = index.reconstruct_n(10, 10)
self.assertTrue(y.is_cuda)
self.assertTrue(torch.equal(xb[10:20], y))
# Test reconstruct with numpy output provided
y = np.empty((10, d), dtype='float32')
index.reconstruct_n(20, 10, y)
self.assertTrue(np.array_equal(xb.cpu().numpy()[20:30], y))
# Test reconstruct_n with torch cpu output provided
y = torch.empty(10, d, dtype=torch.float32)
index.reconstruct_n(40, 10, y)
self.assertTrue(torch.equal(xb[40:50].cpu(), y))
# Test reconstruct_n with torch gpu output provided
y = torch.empty(10, d, device=torch.device('cuda', 0), dtype=torch.float32)
index.reconstruct_n(50, 10, y)
self.assertTrue(torch.equal(xb[50:60], y))
# tests assign
def test_assign(self):
d = 32
res = faiss.StandardGpuResources()
res.noTempMemory()
index = faiss.GpuIndexFlatL2(res, d)
xb = torch.rand(10000, d, device=torch.device('cuda', 0), dtype=torch.float32)
index.add(xb)
index_cpu = faiss.IndexFlatL2(d)
index.copyTo(index_cpu)
# Test assign with native gpu output
# both input as gpu torch and input as cpu torch
xq = torch.rand(10, d, device=torch.device('cuda', 0), dtype=torch.float32)
labels = index.assign(xq, 5)
labels_cpu = index_cpu.assign(xq.cpu(), 5)
self.assertTrue(torch.equal(labels.cpu(), labels_cpu))
# Test assign with np input
labels = index.assign(xq.cpu().numpy(), 5)
labels_cpu = index_cpu.assign(xq.cpu().numpy(), 5)
self.assertTrue(np.array_equal(labels, labels_cpu))
# Test assign with numpy output provided
labels = np.empty((xq.shape[0], 5), dtype='int64')
index.assign(xq.cpu().numpy(), 5, labels)
self.assertTrue(np.array_equal(labels, labels_cpu))
# Test assign with torch cpu output provided
labels = torch.empty(xq.shape[0], 5, dtype=torch.int64)
index.assign(xq.cpu(), 5, labels)
labels_cpu = index_cpu.assign(xq.cpu(), 5)
self.assertTrue(torch.equal(labels, labels_cpu))
# tests remove_ids
def test_remove_ids(self):
# This is not currently implemented on GPU indices
return
# tests range_search
def test_range_search(self):
# This is not currently implemented on GPU indices
return
# tests search_and_reconstruct
def test_search_and_reconstruct(self):
# This is not currently implemented on GPU indices
return
# tests sa_encode, sa_decode
def test_sa_encode_decode(self):
# This is not currently implemented on GPU indices
return
class TestTorchUtilsKnnGpu(unittest.TestCase):
def test_knn_gpu(self, use_raft=False):
torch.manual_seed(10)
d = 32
nb = 1024
nq = 10
k = 10
res = faiss.StandardGpuResources()
# make GT on torch cpu and test using IndexFlatL2
xb = torch.rand(nb, d, dtype=torch.float32)
xq = torch.rand(nq, d, dtype=torch.float32)
index = faiss.IndexFlatL2(d)
index.add(xb)
gt_D, gt_I = index.search(xq, k)
# for the GPU, we'll use a non-default stream
s = torch.cuda.Stream()
with torch.cuda.stream(s):
# test numpy inputs
xb_np = xb.numpy()
xq_np = xq.numpy()
for xq_row_major in True, False:
for xb_row_major in True, False:
if not xq_row_major:
xq_c = to_column_major_numpy(xq_np)
assert not xq_c.flags.contiguous
else:
xq_c = xq_np
if not xb_row_major:
xb_c = to_column_major_numpy(xb_np)
assert not xb_c.flags.contiguous
else:
xb_c = xb_np
D, I = faiss.knn_gpu(res, xq_c, xb_c, k, use_raft=use_raft)
self.assertTrue(torch.equal(torch.from_numpy(I), gt_I))
self.assertLess((torch.from_numpy(D) - gt_D).abs().max(), 1e-4)
# test torch (cpu, gpu) inputs
for is_cuda in True, False:
for xq_row_major in True, False:
for xb_row_major in True, False:
if is_cuda:
xq_c = xq.cuda()
xb_c = xb.cuda()
else:
# also test torch cpu tensors
xq_c = xq
xb_c = xb
if not xq_row_major:
xq_c = to_column_major_torch(xq)
assert not xq_c.is_contiguous()
if not xb_row_major:
xb_c = to_column_major_torch(xb)
assert not xb_c.is_contiguous()
D, I = faiss.knn_gpu(res, xq_c, xb_c, k, use_raft=use_raft)
self.assertTrue(torch.equal(I.cpu(), gt_I))
self.assertLess((D.cpu() - gt_D).abs().max(), 1e-4)
# test on subset
try:
# This internally uses the current pytorch stream
D, I = faiss.knn_gpu(res, xq_c[6:8], xb_c, k, use_raft=use_raft)
except TypeError:
if not xq_row_major:
# then it is expected
continue
# otherwise it is an error
raise
self.assertTrue(torch.equal(I.cpu(), gt_I[6:8]))
self.assertLess((D.cpu() - gt_D[6:8]).abs().max(), 1e-4)
@unittest.skipUnless(
"RAFT" in faiss.get_compile_options(),
"only if RAFT is compiled in")
def test_knn_gpu_raft(self):
self.test_knn_gpu(use_raft=True)
def test_knn_gpu_datatypes(self, use_raft=False):
torch.manual_seed(10)
d = 10
nb = 1024
nq = 5
k = 10
res = faiss.StandardGpuResources()
# make GT on torch cpu and test using IndexFlatL2
xb = torch.rand(nb, d, dtype=torch.float32)
xq = torch.rand(nq, d, dtype=torch.float32)
index = faiss.IndexFlatL2(d)
index.add(xb)
gt_D, gt_I = index.search(xq, k)
xb_c = xb.cuda().half()
xq_c = xq.cuda().half()
# use i32 output indices
D = torch.zeros(nq, k, device=xb_c.device, dtype=torch.float32)
I = torch.zeros(nq, k, device=xb_c.device, dtype=torch.int32)
faiss.knn_gpu(res, xq_c, xb_c, k, D, I, use_raft=use_raft)
self.assertTrue(torch.equal(I.long().cpu(), gt_I))
self.assertLess((D.float().cpu() - gt_D).abs().max(), 1.5e-3)
# Test using numpy
D = np.zeros((nq, k), dtype=np.float32)
I = np.zeros((nq, k), dtype=np.int32)
xb_c = xb.half().numpy()
xq_c = xq.half().numpy()
faiss.knn_gpu(res, xq_c, xb_c, k, D, I, use_raft=use_raft)
self.assertTrue(torch.equal(torch.from_numpy(I).long(), gt_I))
self.assertLess((torch.from_numpy(D) - gt_D).abs().max(), 1.5e-3)
class TestTorchUtilsPairwiseDistanceGpu(unittest.TestCase):
def test_pairwise_distance_gpu(self):
torch.manual_seed(10)
d = 32
k = 100
# To compare against IndexFlat, use nb == k
nb = k
nq = 10
res = faiss.StandardGpuResources()
# make GT on torch cpu and test using IndexFlatL2
xb = torch.rand(nb, d, dtype=torch.float32)
xq = torch.rand(nq, d, dtype=torch.float32)
index = faiss.IndexFlatL2(d)
index.add(xb)
gt_D, _ = index.search(xq, k)
# for the GPU, we'll use a non-default stream
s = torch.cuda.Stream()
with torch.cuda.stream(s):
# test numpy inputs
xb_np = xb.numpy()
xq_np = xq.numpy()
for xq_row_major in True, False:
for xb_row_major in True, False:
if not xq_row_major:
xq_c = to_column_major_numpy(xq_np)
assert not xq_c.flags.contiguous
else:
xq_c = xq_np
if not xb_row_major:
xb_c = to_column_major_numpy(xb_np)
assert not xb_c.flags.contiguous
else:
xb_c = xb_np
D = faiss.pairwise_distance_gpu(res, xq_c, xb_c)
# IndexFlat will sort the results, so we need to
# do the same on our end
D = np.sort(D, axis=1)
self.assertLess((torch.from_numpy(D) - gt_D).abs().max(), 1e-4)
# test torch (cpu, gpu) inputs
for is_cuda in True, False:
for xq_row_major in True, False:
for xb_row_major in True, False:
if is_cuda:
xq_c = xq.cuda()
xb_c = xb.cuda()
else:
# also test torch cpu tensors
xq_c = xq
xb_c = xb
if not xq_row_major:
xq_c = to_column_major_torch(xq)
assert not xq_c.is_contiguous()
if not xb_row_major:
xb_c = to_column_major_torch(xb)
assert not xb_c.is_contiguous()
D = faiss.pairwise_distance_gpu(res, xq_c, xb_c)
# IndexFlat will sort the results, so we need to
# do the same on our end
D, _ = torch.sort(D, dim=1)
self.assertLess((D.cpu() - gt_D).abs().max(), 1e-4)
# test on subset
try:
# This internally uses the current pytorch stream
D = faiss.pairwise_distance_gpu(res, xq_c[4:8], xb_c)
except TypeError:
if not xq_row_major:
# then it is expected
continue
# otherwise it is an error
raise
# IndexFlat will sort the results, so we need to
# do the same on our end
print(D)
D, _ = torch.sort(D, dim=1)
self.assertLess((D.cpu() - gt_D[4:8]).abs().max(), 1e-4)