hashed_index.py 17.4 KB
Newer Older
Neel Kant's avatar
Neel Kant committed
1
from collections import defaultdict
Neel Kant's avatar
Neel Kant committed
2
import os
Neel Kant's avatar
Neel Kant committed
3
import pickle
Neel Kant's avatar
Neel Kant committed
4
import shutil
Neel Kant's avatar
Neel Kant committed
5

Neel Kant's avatar
Neel Kant committed
6
7
8
9
10
11
12
13
14
15
16
import numpy as np
import torch
from torch.nn.parallel.distributed import DistributedDataParallel as torchDDP

from megatron import get_args
from megatron import mpu
from megatron.checkpointing import get_checkpoint_tracker_filename, get_checkpoint_name
from megatron.data.bert_dataset import get_indexed_dataset_
from megatron.data.ict_dataset import InverseClozeDataset
from megatron.data.samplers import DistributedBatchSampler
from megatron.initialize import initialize_megatron
Neel Kant's avatar
Neel Kant committed
17
from megatron.model import REALMRetriever
Neel Kant's avatar
Neel Kant committed
18
19
20
21
from megatron.training import get_model
from pretrain_bert_ict import get_batch, model_provider


22
23
24
25
def detach(tensor):
    return tensor.detach().cpu().numpy()


Neel Kant's avatar
Neel Kant committed
26
27
class HashedIndex(object):
    """Class for holding hashed data"""
Neel Kant's avatar
Neel Kant committed
28
    def __init__(self, embed_size, num_buckets, whiten=False, seed=0):
Neel Kant's avatar
Neel Kant committed
29
30
31
        np.random.seed(seed)
        self.block_data = defaultdict(list)
        self.hash_data = defaultdict(list)
Neel Kant's avatar
Neel Kant committed
32
        hash_matrix = 2 * np.random.rand(embed_size, int(num_buckets / 2)) - 1
Neel Kant's avatar
Neel Kant committed
33
        self.hash_matrix = hash_matrix / np.linalg.norm(hash_matrix, axis=0).reshape(1, -1)
Neel Kant's avatar
Neel Kant committed
34
35
36
        self.embed_mean = None
        self.embed_whitener = None
        self.whiten = whiten
Neel Kant's avatar
Neel Kant committed
37
38

        # alsh
Neel Kant's avatar
Neel Kant committed
39
        self.m = 5
Neel Kant's avatar
Neel Kant committed
40
41
        self.u = 0.99
        self.max_norm = None
Neel Kant's avatar
Neel Kant committed
42
        self.block_index = None
Neel Kant's avatar
Neel Kant committed
43
44
45
46
47

    def state(self):
        state = {
            'block_data': self.block_data,
            'hash_data': self.hash_data,
Neel Kant's avatar
Neel Kant committed
48
49
50
            'hash_matrix': self.hash_matrix,
            'embed_mean': self.embed_mean,
            'embed_whitener': self.embed_whitener,
Neel Kant's avatar
Neel Kant committed
51
52
53
54
55
56
57
58
59
60
61
        }
        return state

    def get_block_bucket(self, hash):
        return self.hash_data[hash]

    def get_block_embed(self, block_idx):
        return self.block_data[block_idx]

    def hash_embeds(self, embeds, block_data=None):
        """Hash a tensor of embeddings using a random projection matrix"""
Neel Kant's avatar
Neel Kant committed
62
        embed_scores_pos = torch.matmul(embeds, torch.cuda.FloatTensor(self.hash_matrix))
Neel Kant's avatar
Neel Kant committed
63
64
65
66
67
68
69
70
71
72
73
74
75
76
        embed_scores = torch.cat((embed_scores_pos, -embed_scores_pos), axis=1)
        embed_hashes = detach(torch.argmax(embed_scores, axis=1))

        if block_data is not None:
            for hash, indices in zip(embed_hashes, block_data):
                self.hash_data[hash].append(indices)

        return embed_hashes

    def assign_block_embeds(self, block_indices, block_embeds, allow_overwrite=False):
        """Assign the embeddings for each block index into a hash map"""
        for idx, embed in zip(block_indices, block_embeds):
            if not allow_overwrite and int(idx) in self.block_data:
                raise ValueError("Attempted to overwrite a read-only HashedIndex")
Neel Kant's avatar
Neel Kant committed
77
            self.block_data[int(idx)] = np.float16(embed)
Neel Kant's avatar
Neel Kant committed
78
79
80
81
82
83
84
85
86
87

    def save_shard(self, rank):
        dir_name = 'block_hash_data'
        if not os.path.isdir(dir_name):
            os.mkdir(dir_name)

        # save the data for each shard
        with open('{}/{}.pkl'.format(dir_name, rank), 'wb') as data_file:
            pickle.dump(self.state(), data_file)

Neel Kant's avatar
Neel Kant committed
88
    def consolidate_shards_and_save(self, ignore_shard=0):
Neel Kant's avatar
Neel Kant committed
89
90
91
92
93
94
        """Combine all the shards made using self.save_shard()"""
        dir_name = 'block_hash_data'
        fnames = os.listdir(dir_name)
        for fname in fnames:
            with open('{}/{}'.format(dir_name, fname), 'rb') as f:
                data = pickle.load(f)
Neel Kant's avatar
Neel Kant committed
95
                assert np.array_equal(data['hash_matrix'], self.hash_matrix)
Neel Kant's avatar
Neel Kant committed
96
97
98
99

                old_size = len(self.block_data)
                shard_size = len(data['block_data'])
                self.block_data.update(data['block_data'])
Neel Kant's avatar
Neel Kant committed
100
                assert (len(self.block_data) == old_size + shard_size) or (str(ignore_shard) in fname)
Neel Kant's avatar
Neel Kant committed
101

Neel Kant's avatar
Neel Kant committed
102
103
104
105
106
107
                if not self.whiten:
                    for bucket, items in data['hash_data'].items():
                        self.hash_data[bucket].extend(items)

        if self.whiten:
            self.whiten_block_embeds()
Neel Kant's avatar
Neel Kant committed
108

Neel Kant's avatar
Neel Kant committed
109
110
        args = get_args()
        with open(args.hash_data_path, 'wb') as final_file:
Neel Kant's avatar
Neel Kant committed
111
112
113
114
115
            pickle.dump(self.state(), final_file)
        shutil.rmtree(dir_name, ignore_errors=True)

    def clear(self):
        """Clear the data structures to save memory"""
Neel Kant's avatar
Neel Kant committed
116
117
118
119
120
121
122
123
124
125
126
127
128
        self.block_data = dict()
        self.hash_data = defaultdict(list)

    def whiten_block_embeds(self):
        """Transform all block embeds to have zero mean and unit covariance
        when treated as samples from a distribution"""
        block_idx, all_embeds = zip(*self.block_data.items())
        arr_embeds = np.transpose(np.array(all_embeds))

        mean = np.mean(arr_embeds, axis=1).reshape(-1, 1)
        centered = arr_embeds - mean
        inv_cov = np.linalg.inv(np.cov(arr_embeds))
        whitener = np.transpose(np.linalg.cholesky(inv_cov))
Neel Kant's avatar
Neel Kant committed
129
        whitened = np.float16(np.transpose(whitener.dot(centered)))
Neel Kant's avatar
Neel Kant committed
130
131
132
133

        self.embed_mean = mean.reshape(-1)
        self.embed_whitener = whitener
        self.block_data = dict(zip(block_idx, list(whitened)))
Neel Kant's avatar
Neel Kant committed
134
        self.hash_data = defaultdict(list)
Neel Kant's avatar
Neel Kant committed
135
136
137
        batch_size = 16384
        i = 0

Neel Kant's avatar
Neel Kant committed
138
        args = get_args()
Neel Kant's avatar
Neel Kant committed
139
140
141
        with torch.no_grad():
            hashing_tensor = torch.cuda.HalfTensor(self.hash_matrix)
            while True:
Neel Kant's avatar
Neel Kant committed
142
143
                if args.debug:
                    print(i, flush=True)
Neel Kant's avatar
Neel Kant committed
144
145
146
                batch_slice = slice(i * batch_size, (i + 1) * batch_size)
                batch_embed = torch.cuda.HalfTensor(whitened[batch_slice])
                batch_block_idx = block_idx[batch_slice]
Neel Kant's avatar
Neel Kant committed
147
                if len(batch_block_idx) == 0:
Neel Kant's avatar
Neel Kant committed
148
149
150
151
152
                    break

                hash_scores_pos = torch.matmul(batch_embed, hashing_tensor)
                embed_scores = torch.cat((hash_scores_pos, -hash_scores_pos), axis=1)
                embed_hashes = detach(torch.argmax(embed_scores, axis=1))
Neel Kant's avatar
Neel Kant committed
153
                for idx, hash in zip(batch_block_idx, list(embed_hashes)):
Neel Kant's avatar
Neel Kant committed
154
                    # [int] instead of [array<int>] since this is just for analysis rn
Neel Kant's avatar
Neel Kant committed
155
                    self.hash_data[hash].append(idx)
Neel Kant's avatar
Neel Kant committed
156
157
                i += 1

Neel Kant's avatar
Neel Kant committed
158

Neel Kant's avatar
Neel Kant committed
159
160
161
162
163
    def create_block_data_index(self):
        import faiss
        self.block_idx, block_embeds = zip(*self.block_data.items())
        block_embeds = np.array(block_embeds)

Neel Kant's avatar
Neel Kant committed
164
        alsh_preprocessed_blocks = self.alsh_block_preprocess_fn()
Neel Kant's avatar
Neel Kant committed
165
        index = faiss.IndexFlatL2(alsh_preprocessed_blocks.shape[1])
Neel Kant's avatar
Neel Kant committed
166
        index.add(alsh_preprocessed_blocks)
Neel Kant's avatar
Neel Kant committed
167
168
169
        print('Total blocks in index: ', index.ntotal)
        self.block_index = index

Neel Kant's avatar
Neel Kant committed
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
    def get_norm_powers_and_halves_array(self, embeds):
        norm = np.linalg.norm(embeds, axis=1)
        norm_powers = [np.multiply(norm, norm)]  # squared L2 norms of all
        for i in range(self.m - 1):
            norm_powers.append(np.multiply(norm_powers[-1], norm_powers[-1]))
        # [num_blocks x self.m]
        norm_powers = np.transpose(np.array(norm_powers))
        halves_array = 0.5 * np.ones(norm_powers.shape)

        return norm_powers, halves_array

    def alsh_block_preprocess_fn(self):
        block_idx, block_embeds = zip(*self.block_data.items())
        block_embeds = np.array(block_embeds)
        if self.max_norm is None:
            self.max_norm = max(np.linalg.norm(block_embeds, axis=1))
        if self.max_norm > 1:
            block_embeds = self.u / self.max_norm * block_embeds
        norm_powers, halves_array = self.get_norm_powers_and_halves_array(block_embeds)

        # P'(S(x)) for all x in block_embeds
Neel Kant's avatar
Neel Kant committed
191
        return np.float32(np.concatenate((block_embeds, norm_powers, halves_array), axis=1))
Neel Kant's avatar
Neel Kant committed
192
193

    def alsh_query_preprocess_fn(self, query_embeds):
Neel Kant's avatar
Neel Kant committed
194
        max_norm = max(np.linalg.norm(query_embeds, axis=1))
Neel Kant's avatar
Neel Kant committed
195
196
197
198
199
        if max_norm > 1:
            query_embeds = self.u / max_norm * query_embeds
        norm_powers, halves_array = self.get_norm_powers_and_halves_array(query_embeds)

        # Q'(S(x)) for all x in query_embeds
Neel Kant's avatar
Neel Kant committed
200
        return np.float32(np.concatenate((query_embeds, halves_array, norm_powers), axis=1))
Neel Kant's avatar
Neel Kant committed
201

Neel Kant's avatar
Neel Kant committed
202
    def exact_mips_equals(self, query_embeds, norm_blocks):
Neel Kant's avatar
Neel Kant committed
203
        """For each query, determine whether the mips block is in the correct hash bucket"""
Neel Kant's avatar
Neel Kant committed
204
205
206
        shuffled_block_idx, block_embeds = zip(*self.block_data.items())
        if norm_blocks:
            block_embeds = block_embeds / np.linalg.norm(block_embeds, axis=1).reshape(-1, 1)
Neel Kant's avatar
Neel Kant committed
207
208
209
210
211
212
213
214
215
216
        with torch.no_grad():
            # get hashes for the queries
            hash_scores_pos = torch.matmul(torch.cuda.HalfTensor(query_embeds), torch.cuda.HalfTensor(self.hash_matrix))
            hash_scores = torch.cat((hash_scores_pos, -hash_scores_pos), axis=1)
            query_hashes = detach(torch.argmax(hash_scores, axis=1))

            # [num_query x num_blocks]
            inner_products = torch.matmul(torch.cuda.HalfTensor(query_embeds),
                                          torch.cuda.HalfTensor(np.transpose(np.array(block_embeds))))
            max_inner_product_idxes = detach(torch.argmax(inner_products, axis=1))
Neel Kant's avatar
Neel Kant committed
217
            best_blocks = [self.block_data[shuffled_block_idx[idx]] for idx in max_inner_product_idxes]
Neel Kant's avatar
Neel Kant committed
218
219
            best_blocks_tensor = torch.cuda.HalfTensor(np.array(best_blocks))
            # bb = best_blocks
Neel Kant's avatar
Neel Kant committed
220
            bb_hash_scores_pos = torch.matmul(best_blocks_tensor, torch.cuda.HalfTensor(self.hash_matrix))
Neel Kant's avatar
Neel Kant committed
221
222
            bb_hash_scores = torch.cat((bb_hash_scores_pos, -bb_hash_scores_pos), axis=1)
            best_block_hashes = detach(torch.argmax(bb_hash_scores, axis=1))
Neel Kant's avatar
Neel Kant committed
223
224
225

            print('Query hashes: ', query_hashes)
            print('Block hashes: ', best_block_hashes)
Neel Kant's avatar
Neel Kant committed
226
227
228
229
230
            equal_arr = np.equal(query_hashes, best_block_hashes).astype(int)

            # array of zeros and ones which can be used for counting success
            return equal_arr

Neel Kant's avatar
Neel Kant committed
231
    def exact_mips_test(self, num_queries, whitened, norm_blocks, alsh):
Neel Kant's avatar
Neel Kant committed
232
233
234
        if whitened:
            if self.embed_mean is None:
                self.whiten_block_embeds()
Neel Kant's avatar
Neel Kant committed
235
            query_embeds = np.random.multivariate_normal(np.zeros(128), np.eye(128), num_queries)
Neel Kant's avatar
Neel Kant committed
236
            query_embeds = query_embeds / np.linalg.norm(query_embeds, axis=1).reshape(-1, 1)
Neel Kant's avatar
Neel Kant committed
237
            if alsh:
Neel Kant's avatar
Neel Kant committed
238
239
                if self.block_index is None:
                    self.create_block_data_index()
Neel Kant's avatar
Neel Kant committed
240
                alsh_queries = self.alsh_query_preprocess_fn(query_embeds)
Neel Kant's avatar
Neel Kant committed
241
                neighbor_ids, distances = self.block_index.search(alsh_queries, 5)
Neel Kant's avatar
Neel Kant committed
242
243
                print('DONE')
                return
Neel Kant's avatar
Neel Kant committed
244
245
246
247
248
249
        else:
            block_idx, all_embeds = zip(*self.block_data.items())
            arr_embeds = np.transpose(np.array(all_embeds))

            mean = np.mean(arr_embeds, axis=1).reshape(-1, 1)
            cov = np.cov(arr_embeds)
Neel Kant's avatar
Neel Kant committed
250
            query_embeds = np.random.multivariate_normal(mean, cov, num_queries)
Neel Kant's avatar
Neel Kant committed
251

Neel Kant's avatar
Neel Kant committed
252
        equal_arr = self.exact_mips_equals(query_embeds, norm_blocks)
Neel Kant's avatar
Neel Kant committed
253
        print("Num correct: ", sum(equal_arr), " Fraction correct: ", sum(equal_arr) / equal_arr.size)
Neel Kant's avatar
Neel Kant committed
254
        print(equal_arr)
Neel Kant's avatar
Neel Kant committed
255

Neel Kant's avatar
Neel Kant committed
256
257
    @classmethod
    def load_from_file(cls, fname):
Neel Kant's avatar
Neel Kant committed
258
        print(" > Unpickling block hash data")
Neel Kant's avatar
Neel Kant committed
259
        state_dict = pickle.load(open(fname, 'rb'))
Neel Kant's avatar
Neel Kant committed
260
        print(" > Finished unpickling")
Neel Kant's avatar
Neel Kant committed
261
262
263
264
265
        hash_matrix = state_dict['hash_matrix']

        new_index = HashedIndex(hash_matrix.shape[0], hash_matrix.shape[1] * 2)
        new_index.block_data = state_dict['block_data']
        new_index.hash_data = state_dict['hash_data']
Neel Kant's avatar
Neel Kant committed
266
267
        new_index.embed_mean = state_dict.get('embed_mean')
        new_index.embed_whitener = state_dict.get('embed_whitener')
Neel Kant's avatar
Neel Kant committed
268
        new_index.hash_matrix = hash_matrix
Neel Kant's avatar
Neel Kant committed
269

Neel Kant's avatar
Neel Kant committed
270
271
        return new_index

Neel Kant's avatar
Neel Kant committed
272

Neel Kant's avatar
Neel Kant committed
273
274
275
def test_retriever():
    initialize_megatron(extra_args_provider=None,
                        args_defaults={'tokenizer_type': 'BertWordPieceLowerCase'})
Neel Kant's avatar
Neel Kant committed
276
    args = get_args()
Neel Kant's avatar
Neel Kant committed
277
    model = load_ict_checkpoint(only_block_model=True)
Neel Kant's avatar
Neel Kant committed
278
    model.eval()
Neel Kant's avatar
Neel Kant committed
279
    dataset = get_ict_dataset()
Neel Kant's avatar
Neel Kant committed
280
    hashed_index = HashedIndex.load_from_file(args.hash_data_path)
Neel Kant's avatar
Neel Kant committed
281
    retriever = REALMRetriever(model, dataset, hashed_index)
Neel Kant's avatar
Neel Kant committed
282
283
284
285
286
287
288
289
290
291

    strs = [
        "The last monarch from the house of windsor",
        "married to Elvis Presley",
        "tallest building in the world today",
        "who makes graphics cards"
    ]

    for s in strs:
        retriever.retrieve_evidence_blocks_text(s)
Neel Kant's avatar
Neel Kant committed
292
293


Neel Kant's avatar
Neel Kant committed
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
def main():

    # TODO
    # consider broadcasting/all-reducing all in memory rather than using the filesystem
    # create a different process group in the same nccl world - don't have to use chkpts on disc or transfer things on disc
    # torch distributed new group, constains a list of rank, gives back a group which I can hand to the collective operations
    # create a training process group, indexing process group
    # pass the training group to the distributed DDP, instead of the large world process group
    # use indexing process group for the shard-combining
    # communication group between process "8" and process "0" which tells training group that there's a new index
    # also, process 0 sends process 8 the new model

    # if i want to launch a separate process for indexing, may have to work with environment variables to
    # allocate the resources well. Have to subsequently assign the correct gpus to the indexing job
    # consider initializing everything in a single group and break off processes based on the ranks

Neel Kant's avatar
Neel Kant committed
310
311
312
    # for debugging purposes, make it so that the training process group checks every some number of intervals
    # and if it isn't ready, then wait so that it's consistent. Start with using the filesystem

Neel Kant's avatar
Neel Kant committed
313
314
315
    initialize_megatron(extra_args_provider=None,
                        args_defaults={'tokenizer_type': 'BertWordPieceLowerCase'})
    args = get_args()
Neel Kant's avatar
Neel Kant committed
316
    model = load_ict_checkpoint(only_block_model=True, no_grad=True)
Neel Kant's avatar
Neel Kant committed
317
    model.eval()
Neel Kant's avatar
Neel Kant committed
318
    dataset = get_ict_dataset()
Neel Kant's avatar
Neel Kant committed
319
    data_iter = iter(get_one_epoch_dataloader(dataset))
Neel Kant's avatar
Neel Kant committed
320
    hashed_index = HashedIndex(embed_size=128, num_buckets=32, whiten=True)
Neel Kant's avatar
Neel Kant committed
321

Neel Kant's avatar
Neel Kant committed
322
323
324
    i = 1
    total = 0
    whiten = False
Neel Kant's avatar
Neel Kant committed
325
326
    while True:
        try:
Neel Kant's avatar
Neel Kant committed
327
328
            query_tokens, query_pad_mask, \
            block_tokens, block_pad_mask, block_indices = get_batch(data_iter)
329
        except:
Neel Kant's avatar
Neel Kant committed
330
            break
331

Neel Kant's avatar
Neel Kant committed
332
        block_indices = detach(block_indices)
Neel Kant's avatar
Neel Kant committed
333
        block_logits = model(None, None, block_tokens, block_pad_mask, only_block=True)
Neel Kant's avatar
Neel Kant committed
334

Neel Kant's avatar
Neel Kant committed
335
        # If whitened, then hashing needs to be done after whitening the block embeds
Neel Kant's avatar
Neel Kant committed
336
337
338
339
340
        # which is done in consolidate_shards_and_save()
        if not whiten:
            hashed_index.hash_embeds(block_logits, block_indices)
        hashed_index.assign_block_embeds(block_indices[:, 3], detach(block_logits))

Neel Kant's avatar
Neel Kant committed
341
        total += block_indices.shape[0]
342
        i += 1
Neel Kant's avatar
Neel Kant committed
343
344
345
346
        if i % 20 == 0:
            print('Batch {:10d} | Total {:10d}'.format(i, total), flush=True)
            if args.debug:
                break
347

Neel Kant's avatar
Neel Kant committed
348
    hashed_index.save_shard(args.rank)
Neel Kant's avatar
Neel Kant committed
349
    torch.distributed.barrier()
350
351
    del model

Neel Kant's avatar
Neel Kant committed
352
    if args.rank == 0:
Neel Kant's avatar
Neel Kant committed
353
354
355
        hashed_index.consolidate_shards_and_save()
    else:
        hashed_index.clear()
Neel Kant's avatar
Neel Kant committed
356
357


Neel Kant's avatar
Neel Kant committed
358
def load_ict_checkpoint(only_query_model=False, only_block_model=False, no_grad=False):
Neel Kant's avatar
Neel Kant committed
359
    args = get_args()
Neel Kant's avatar
Neel Kant committed
360
    model = get_model(lambda: model_provider(only_query_model, only_block_model))
Neel Kant's avatar
Neel Kant committed
361
362
363

    if isinstance(model, torchDDP):
        model = model.module
Neel Kant's avatar
Neel Kant committed
364
    tracker_filename = get_checkpoint_tracker_filename(args.ict_load)
Neel Kant's avatar
Neel Kant committed
365
366
367
368
    with open(tracker_filename, 'r') as f:
        iteration = int(f.read().strip())

    assert iteration > 0
Neel Kant's avatar
Neel Kant committed
369
    checkpoint_name = get_checkpoint_name(args.ict_load, iteration, False)
Neel Kant's avatar
Neel Kant committed
370
371
372
373
374
    if mpu.get_data_parallel_rank() == 0:
        print('global rank {} is loading checkpoint {}'.format(
            torch.distributed.get_rank(), checkpoint_name))

    state_dict = torch.load(checkpoint_name, map_location='cpu')
Neel Kant's avatar
Neel Kant committed
375
376
377
378
379
380
381
382
383
    if only_query_model:
        state_dict['model'].pop('context_model')
    if only_block_model:
        state_dict['model'].pop('question_model')
    if no_grad:
        with torch.no_grad():
            model.load_state_dict(state_dict['model'])
    else:
        model.load_state_dict(state_dict['model'])
Neel Kant's avatar
Neel Kant committed
384
385
386
387
388
389
390
391
    torch.distributed.barrier()

    if mpu.get_data_parallel_rank() == 0:
        print(' successfully loaded {}'.format(checkpoint_name))

    return model


Neel Kant's avatar
Neel Kant committed
392
def get_ict_dataset():
Neel Kant's avatar
Neel Kant committed
393
    args = get_args()
Neel Kant's avatar
Neel Kant committed
394
    block_dataset = get_indexed_dataset_(args.data_path, 'mmap', True)
Neel Kant's avatar
Neel Kant committed
395
    titles_dataset = get_indexed_dataset_(args.titles_data_path, 'mmap', True)
Neel Kant's avatar
Neel Kant committed
396
397
398

    kwargs = dict(
        name='full',
Neel Kant's avatar
Neel Kant committed
399
400
        block_dataset=block_dataset,
        title_dataset=titles_dataset,
Neel Kant's avatar
Neel Kant committed
401
        data_prefix=args.data_path,
Neel Kant's avatar
Neel Kant committed
402
403
        num_epochs=1,
        max_num_samples=None,
Neel Kant's avatar
Neel Kant committed
404
405
406
407
408
409
410
411
        max_seq_length=288,  # doesn't matter
        short_seq_prob=0.0001,  # doesn't matter
        seed=1
    )
    dataset = InverseClozeDataset(**kwargs)
    return dataset


Neel Kant's avatar
Neel Kant committed
412
def get_one_epoch_dataloader(dataset):
Neel Kant's avatar
Neel Kant committed
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
    args = get_args()

    world_size = mpu.get_data_parallel_world_size()
    rank = mpu.get_data_parallel_rank()
    global_batch_size = args.batch_size * world_size
    num_workers = args.num_workers

    sampler = torch.utils.data.SequentialSampler(dataset)
    batch_sampler = DistributedBatchSampler(sampler,
                                            batch_size=global_batch_size,
                                            drop_last=True,
                                            rank=rank,
                                            world_size=world_size)

    return torch.utils.data.DataLoader(dataset,
                                       batch_sampler=batch_sampler,
                                       num_workers=num_workers,
                                       pin_memory=True)


if __name__ == "__main__":
Neel Kant's avatar
Neel Kant committed
434
    main()