hashed_index.py 5.32 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
4
import pickle

Neel Kant's avatar
Neel Kant committed
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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
from megatron.training import get_model
from pretrain_bert_ict import get_batch, model_provider


Neel Kant's avatar
Neel Kant committed
20
def embed_docs():
Neel Kant's avatar
Neel Kant committed
21
22
23
24
25
26
27
28
    initialize_megatron(extra_args_provider=None,
                        args_defaults={'tokenizer_type': 'BertWordPieceLowerCase'})
    args = get_args()
    model = load_checkpoint()
    model.eval()
    dataset = get_dataset()
    data_iter = iter(get_dataloader(dataset))

Neel Kant's avatar
Neel Kant committed
29
    hash_data = defaultdict(list)
Neel Kant's avatar
Neel Kant committed
30
    hash_matrix = torch.cuda.HalfTensor(np.random.rand(128, 1024))
Neel Kant's avatar
Neel Kant committed
31
    hash_data['matrix'] = hash_matrix
Neel Kant's avatar
Neel Kant committed
32

33
    block_data = defaultdict(list)
Neel Kant's avatar
Neel Kant committed
34
    i = 0
Neel Kant's avatar
Neel Kant committed
35
36
37
38
    while True:
        try:
            input_tokens, input_types, input_pad_mask, \
            block_tokens, block_token_types, block_pad_mask, block_indices = get_batch(data_iter)
39
        except:
Neel Kant's avatar
Neel Kant committed
40
            break
41
42

        # TODO: make sure input is still in block
Neel Kant's avatar
Neel Kant committed
43
        input_logits, block_logits, _ = model.module.module.forward(
Neel Kant's avatar
Neel Kant committed
44
            input_tokens, input_types, input_pad_mask, block_tokens, block_pad_mask, block_token_types, return_logits=True)
Neel Kant's avatar
Neel Kant committed
45

Neel Kant's avatar
Neel Kant committed
46
        block_hash_pos = torch.matmul(block_logits, hash_matrix)
Neel Kant's avatar
Neel Kant committed
47
48
        block_hash_full = torch.cat((block_hash_pos, -block_hash_pos), axis=1)
        block_hashes = torch.argmax(block_hash_full, axis=1).detach().cpu().numpy()
49
        for hash, indices_array in zip(block_hashes, block_indices):
Neel Kant's avatar
Neel Kant committed
50
            hash_data[int(hash)].append(indices_array.detach().cpu().numpy())
Neel Kant's avatar
Neel Kant committed
51

52
53
54
        block_logits = block_logits.detach().cpu().numpy()
        block_indices = block_indices.detach().cpu().numpy()[:, 3]
        for logits, idx in zip(block_logits, block_indices):
Neel Kant's avatar
Neel Kant committed
55
            block_data[int(idx)] = logits
Neel Kant's avatar
Neel Kant committed
56

Neel Kant's avatar
Neel Kant committed
57
58
        if i % 100 == 0:
            print(i, flush=True)
59
60
        i += 1

Neel Kant's avatar
Neel Kant committed
61
62
63
    dir_name = 'block_hash_data'
    if not os.path.isdir(dir_name):
        os.mkdir(dir_name)
64

Neel Kant's avatar
Neel Kant committed
65
66
67
    with open('{}/{}.pkl'.format(dir_name, args.rank), 'wb') as data_file:
        all_data = {'block_data': block_data, 'hash_data': hash_data}
        pickle.dump(all_data, data_file)
68

Neel Kant's avatar
Neel Kant committed
69
    torch.distributed.barrier()
Neel Kant's avatar
Neel Kant committed
70

Neel Kant's avatar
Neel Kant committed
71
72
73
74
75
76
77
78
79
    if mpu.get_data_parallel_rank() == 0:
        all_block_data = defaultdict(dict)
        dir_name = 'block_hash_data'
        fnames = os.listdir(dir_name)
        for fname in fnames:
            with open(fname, 'rb') as f:
                data = pickle.load(f)
                all_block_data['hash_data'].update(data['hash_data'])
                all_block_data['block_data'].update(data['block_data'])
Neel Kant's avatar
Neel Kant committed
80

Neel Kant's avatar
Neel Kant committed
81
82
83
84
85
        with open('block_hash_data.pkl', 'wb') as final_file:
            pickle.dump(all_block_data, final_file)

        os.rmdir(dir_name)
    return
Neel Kant's avatar
Neel Kant committed
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


def load_checkpoint():
    args = get_args()
    model = get_model(model_provider)

    if isinstance(model, torchDDP):
        model = model.module
    tracker_filename = get_checkpoint_tracker_filename(args.load)
    with open(tracker_filename, 'r') as f:
        iteration = int(f.read().strip())

    assert iteration > 0
    checkpoint_name = get_checkpoint_name(args.load, iteration, False)
    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')
    model.load_state_dict(state_dict['model'])
    torch.distributed.barrier()

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

    return model


def get_dataset():
    args = get_args()
Neel Kant's avatar
Neel Kant committed
116
117
    block_dataset = get_indexed_dataset_(args.data_path, 'mmap', True)
    titles_dataset = get_indexed_dataset_(args.data_path + '-titles', 'mmap', True)
Neel Kant's avatar
Neel Kant committed
118
119
120

    kwargs = dict(
        name='full',
Neel Kant's avatar
Neel Kant committed
121
122
        context_dataset=block_dataset,
        titles_dataset=titles_dataset,
Neel Kant's avatar
Neel Kant committed
123
        data_prefix=args.data_path,
Neel Kant's avatar
Neel Kant committed
124
125
        num_epochs=1,
        max_num_samples=None,
Neel Kant's avatar
Neel Kant committed
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
        max_seq_length=288,  # doesn't matter
        short_seq_prob=0.0001,  # doesn't matter
        seed=1
    )
    dataset = InverseClozeDataset(**kwargs)
    return dataset


def get_dataloader(dataset):
    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
156
    embed_docs()