| 45 | raise ValueError() |
| 46 | |
| 47 | class KNNWrapperMulti(object): |
| 48 | def __init__(self, val_file, index_file, dimension, |
| 49 | knn_sim_func=None, knn_keytype=None, knn_gpu=True, |
| 50 | k=1024, lmbda=0.25, knn_temp=1.0, probe=8, local_process_index=None): |
| 51 | self.val_file = val_file |
| 52 | self.index_file = index_file |
| 53 | self.dimension = dimension |
| 54 | self.lmbda = lmbda |
| 55 | self.k = k |
| 56 | self.knn_temperature = knn_temp |
| 57 | self.probe = probe |
| 58 | self.knn_sim_func = DIST.l2 |
| 59 | self.knn_keytype = KEY_TYPE.last_ffn_input |
| 60 | self.knn_gpu = knn_gpu and torch.cuda.is_available() and torch.cuda.device_count() > 0 |
| 61 | self.local_process_index = local_process_index |
| 62 | |
| 63 | self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') |
| 64 | self.model = None |
| 65 | self.vocab_size = None |
| 66 | self.activation_capturer = None |
| 67 | self.is_encoder_decoder = None |
| 68 | self.hook_handles = [] |
| 69 | |
| 70 | dist_type_to_dist_func = { |
| 71 | DIST.l2: KNNWrapperMulti.l2, |
| 72 | DIST.dot: KNNWrapperMulti.dotprod, |
| 73 | } |
| 74 | self.dist_func = dist_type_to_dist_func[self.knn_sim_func] # l2 or dot product function |
| 75 | |
| 76 | def setup_faiss(self): |
| 77 | if not self.val_file: |
| 78 | raise ValueError('Cannot build a datastore without the data.') |
| 79 | |
| 80 | start = time.time() |
| 81 | cpu_index = faiss.read_index(self.index_file, faiss.IO_FLAG_ONDISK_SAME_DIR) |
| 82 | logger.info(f'Reading datastore took {time.time() - start} s') |
| 83 | cpu_index.nprobe = self.probe |
| 84 | |
| 85 | if self.knn_gpu: |
| 86 | start = time.time() |
| 87 | # 1. Set maximum GPU memory allocation |
| 88 | res = faiss.StandardGpuResources() |
| 89 | res.setTempMemory(40 * 1024 * 1024 * 1024) |
| 90 | |
| 91 | # 2. Create a more memory-efficient cloner |
| 92 | co = faiss.GpuClonerOptions() |
| 93 | co.useFloat16 = True # Use half precision |
| 94 | co.verbose = True # See what's happening |
| 95 | |
| 96 | gpu_index = faiss.index_cpu_to_gpu(res, self.local_process_index, cpu_index, co) |
| 97 | |
| 98 | logger.info(f'Moving index to GPU took {time.time() - start} s') |
| 99 | else: |
| 100 | gpu_index = cpu_index |
| 101 | |
| 102 | # make_direct_map() allows calling reconstruct(n), |
| 103 | # and reconstructing key vectors given their ids |
| 104 | # currently, this is implemented only for CPU indexes: |