|
| 1 | +# Copyright (c) Facebook, Inc. and its 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 | + |
| 8 | +import torch |
| 9 | +import torch.distributed |
| 10 | + |
| 11 | +import faiss |
| 12 | + |
| 13 | +# did not manage to run it in fbcode, so graphted in github version with torchrun |
| 14 | +# |
| 15 | +# import new_contrib |
| 16 | +new_contrib=faiss.contrib |
| 17 | + |
| 18 | +import new_contrib.torch_utils |
| 19 | +from new_contrib.torch import clustering |
| 20 | +from new_contrib import datasets |
| 21 | + |
| 22 | + |
| 23 | +class DatasetAssignDistributedGPU(clustering.DatasetAssign): |
| 24 | + """ |
| 25 | + There is one instance per worker, each worker has a dataset shard. |
| 26 | + The non-master workers do not run through the k-means function, so some |
| 27 | + code has run it to keep the workers in sync. |
| 28 | + """ |
| 29 | + |
| 30 | + |
| 31 | + def __init__(self, res, x, rank, nproc): |
| 32 | + clustering.DatasetAssign.__init__(self, x) |
| 33 | + self.res = res |
| 34 | + self.rank = rank |
| 35 | + self.nproc = nproc |
| 36 | + self.device = x.device |
| 37 | + |
| 38 | + n = len(x) |
| 39 | + sizes = torch.zeros(nproc, device=self.device, dtype=torch.int64) |
| 40 | + sizes[rank] = n |
| 41 | + torch.distributed.all_gather([sizes[i:i+1] for i in range(nproc)], sizes[rank:rank+1]) |
| 42 | + self.sizes = sizes.cpu().numpy() |
| 43 | + |
| 44 | + # begin & end of each shard |
| 45 | + self.cs = np.zeros(nproc + 1, dtype='int64') |
| 46 | + self.cs[1:] = np.cumsum(self.sizes) |
| 47 | + |
| 48 | + def count(self): |
| 49 | + return int(self.sizes.sum()) |
| 50 | + |
| 51 | + def int_to_slaves(self, i): |
| 52 | + " broadcast an int to all workers " |
| 53 | + rank, nproc = self.rank, self.nproc |
| 54 | + tab = torch.zeros(1, device=self.device, dtype=torch.int64) |
| 55 | + if rank == 0: |
| 56 | + tab[0] = i |
| 57 | + else: |
| 58 | + assert i is None |
| 59 | + torch.distributed.broadcast(tab, 0) |
| 60 | + return tab.item() |
| 61 | + |
| 62 | + def get_subset(self, indices): |
| 63 | + rank, nproc = self.rank, self.nproc |
| 64 | + assert rank == 0 or indices is None |
| 65 | + |
| 66 | + len_indices = self.int_to_slaves(len(indices) if rank == 0 else None) |
| 67 | + |
| 68 | + if rank == 0: |
| 69 | + indices = torch.from_numpy(indices).to(self.device) |
| 70 | + else: |
| 71 | + indices = torch.zeros(len_indices, dtype=torch.int64, device=self.device) |
| 72 | + torch.distributed.broadcast(indices, 0) |
| 73 | + |
| 74 | + # select subset of indices |
| 75 | + |
| 76 | + i0, i1 = self.cs[rank], self.cs[rank + 1] |
| 77 | + |
| 78 | + mask = torch.logical_and(indices < i1, indices >= i0) |
| 79 | + output = torch.zeros(len_indices, self.x.shape[1], dtype=self.x.dtype, device=self.device) |
| 80 | + output[mask] = self.x[indices[mask] - i0] |
| 81 | + torch.distributed.reduce(output, 0) # sum |
| 82 | + if rank == 0: |
| 83 | + return output |
| 84 | + else: |
| 85 | + return None |
| 86 | + |
| 87 | + def perform_search(self, centroids): |
| 88 | + assert False, "shoudl not be called" |
| 89 | + |
| 90 | + def assign_to(self, centroids, weights=None): |
| 91 | + assert weights is None |
| 92 | + |
| 93 | + rank, nproc = self.rank, self.nproc |
| 94 | + assert rank == 0 or centroids is None |
| 95 | + nc = self.int_to_slaves(len(centroids) if rank == 0 else None) |
| 96 | + |
| 97 | + if rank != 0: |
| 98 | + centroids = torch.zeros(nc, self.x.shape[1], dtype=self.x.dtype, device=self.device) |
| 99 | + torch.distributed.broadcast(centroids, 0) |
| 100 | + |
| 101 | + # perform search |
| 102 | + D, I = faiss.knn_gpu(self.res, self.x, centroids, 1, device=self.device.index) |
| 103 | + |
| 104 | + I = I.ravel() |
| 105 | + D = D.ravel() |
| 106 | + |
| 107 | + sum_per_centroid = torch.zeros_like(centroids) |
| 108 | + if weights is None: |
| 109 | + sum_per_centroid.index_add_(0, I, self.x) |
| 110 | + else: |
| 111 | + sum_per_centroid.index_add_(0, I, self.x * weights[:, None]) |
| 112 | + |
| 113 | + torch.distributed.reduce(sum_per_centroid, 0) |
| 114 | + |
| 115 | + if rank == 0: |
| 116 | + # gather deos not support tensors of different sizes |
| 117 | + # should be implemented with point-to-point communication |
| 118 | + assert np.all(self.sizes == self.sizes[0]) |
| 119 | + all_I = torch.zeros(self.count(), dtype=I.dtype, device=self.device) |
| 120 | + all_D = torch.zeros(self.count(), dtype=D.dtype, device=self.device) |
| 121 | + torch.distributed.gather( |
| 122 | + I, [all_I[self.cs[r]:self.cs[r + 1]] for r in range(nproc)], |
| 123 | + dst=0, |
| 124 | + ) |
| 125 | + torch.distributed.gather( |
| 126 | + D, [all_D[self.cs[r]:self.cs[r + 1]] for r in range(nproc)], |
| 127 | + dst=0, |
| 128 | + ) |
| 129 | + return all_I.cpu().numpy(), all_D, sum_per_centroid |
| 130 | + else: |
| 131 | + torch.distributed.gather(I, None, dst=0) |
| 132 | + torch.distributed.gather(D, None, dst=0) |
| 133 | + return None |
| 134 | + |
| 135 | + |
| 136 | +if __name__ == "__main__": |
| 137 | + |
| 138 | + torch.distributed.init_process_group( |
| 139 | + backend="nccl", |
| 140 | + ) |
| 141 | + rank = torch.distributed.get_rank() |
| 142 | + nproc = torch.distributed.get_world_size() |
| 143 | + |
| 144 | + # current version does only support shards of the same size |
| 145 | + ds = datasets.SyntheticDataset(32, 10000, 0, 0, seed=1234 + rank) |
| 146 | + x = ds.get_train() |
| 147 | + |
| 148 | + device = torch.device(f"cuda:{rank}") |
| 149 | + |
| 150 | + torch.cuda.set_device(device) |
| 151 | + x = torch.from_numpy(x).to(device) |
| 152 | + res = faiss.StandardGpuResources() |
| 153 | + |
| 154 | + da = DatasetAssignDistributedGPU(res, x, rank, nproc) |
| 155 | + |
| 156 | + k = 1000 |
| 157 | + niter = 25 |
| 158 | + |
| 159 | + if rank == 0: |
| 160 | + print(f"sizes = {da.sizes}") |
| 161 | + centroids, iteration_stats = clustering.kmeans(k, da, niter=niter, return_stats=True) |
| 162 | + print("clusters:", centroids.cpu().numpy()) |
| 163 | + else: |
| 164 | + # make sure the iterations are aligned with master |
| 165 | + da.get_subset(None) |
| 166 | + |
| 167 | + for it in range(niter): |
| 168 | + da.assign_to(None) |
| 169 | + |
| 170 | + torch.distributed.barrier() |
| 171 | + print("Done") |
0 commit comments