hashed_index.py 6.69 KB
Newer Older
Neel Kant's avatar
Neel Kant committed
1
2
3
4
5
6
7
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_
8
9
from megatron.data.realm_dataset import InverseClozeDataset
from megatron.data.realm_index import BlockData, RandProjectionLSHIndex
Neel Kant's avatar
Neel Kant committed
10
11
from megatron.data.samplers import DistributedBatchSampler
from megatron.initialize import initialize_megatron
Neel Kant's avatar
Neel Kant committed
12
from megatron.model import REALMRetriever
Neel Kant's avatar
Neel Kant committed
13
14
15
16
from megatron.training import get_model
from pretrain_bert_ict import get_batch, model_provider


17
18
19
20
def detach(tensor):
    return tensor.detach().cpu().numpy()


Neel Kant's avatar
Neel Kant committed
21
22
23
def test_retriever():
    initialize_megatron(extra_args_provider=None,
                        args_defaults={'tokenizer_type': 'BertWordPieceLowerCase'})
Neel Kant's avatar
Neel Kant committed
24
    args = get_args()
Neel Kant's avatar
Neel Kant committed
25
    model = load_ict_checkpoint(only_block_model=True)
Neel Kant's avatar
Neel Kant committed
26
    model.eval()
Neel Kant's avatar
Neel Kant committed
27
    dataset = get_ict_dataset()
Neel Kant's avatar
Neel Kant committed
28
    hashed_index = HashedIndex.load_from_file(args.hash_data_path)
Neel Kant's avatar
Neel Kant committed
29
    retriever = REALMRetriever(model, dataset, hashed_index)
Neel Kant's avatar
Neel Kant committed
30
31
32
33
34
35
36
37
38
39

    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
40
41


Neel Kant's avatar
Neel Kant committed
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
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
58
59
60
    # 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
61
62
63
    initialize_megatron(extra_args_provider=None,
                        args_defaults={'tokenizer_type': 'BertWordPieceLowerCase'})
    args = get_args()
Neel Kant's avatar
Neel Kant committed
64
    model = load_ict_checkpoint(only_block_model=True, no_grad=True)
Neel Kant's avatar
Neel Kant committed
65
    model.eval()
Neel Kant's avatar
Neel Kant committed
66
    dataset = get_ict_dataset()
Neel Kant's avatar
Neel Kant committed
67
    data_iter = iter(get_one_epoch_dataloader(dataset))
68
69
    all_block_data = BlockData()
    hashed_index = RandProjectionLSHIndex(embed_size=128, num_buckets=32, whiten=True)
Neel Kant's avatar
Neel Kant committed
70

Neel Kant's avatar
Neel Kant committed
71
72
    i = 1
    total = 0
Neel Kant's avatar
Neel Kant committed
73
74
    while True:
        try:
Neel Kant's avatar
Neel Kant committed
75
            query_tokens, query_pad_mask, \
76
            block_tokens, block_pad_mask, block_index_data = get_batch(data_iter)
77
        except:
Neel Kant's avatar
Neel Kant committed
78
            break
79

80
81
82
        block_index_data = detach(block_index_data)
        block_indices = block_index_data[:, 3]
        block_meta = block_index_data[:, :3]
Neel Kant's avatar
Neel Kant committed
83

84
85
        block_logits = model(None, None, block_tokens, block_pad_mask, only_block=True)
        all_block_data.add_block_data(block_indices, block_logits, block_meta)
Neel Kant's avatar
Neel Kant committed
86

87
        total += block_indices.size
88
        i += 1
Neel Kant's avatar
Neel Kant committed
89
90
91
92
        if i % 20 == 0:
            print('Batch {:10d} | Total {:10d}'.format(i, total), flush=True)
            if args.debug:
                break
93

94
    all_block_data.save_shard(args.rank)
Neel Kant's avatar
Neel Kant committed
95
    torch.distributed.barrier()
96
97
    del model

Neel Kant's avatar
Neel Kant committed
98
    if args.rank == 0:
99
100
101
        all_block_data.consolidate_shards_and_save()
        hashed_index.hash_whitened_block_embeds(all_block_data)
        hashed_index.save_to_file()
Neel Kant's avatar
Neel Kant committed
102
    else:
103
        all_block_data.clear()
Neel Kant's avatar
Neel Kant committed
104
105


Neel Kant's avatar
Neel Kant committed
106
def load_ict_checkpoint(only_query_model=False, only_block_model=False, no_grad=False):
Neel Kant's avatar
Neel Kant committed
107
    args = get_args()
Neel Kant's avatar
Neel Kant committed
108
    model = get_model(lambda: model_provider(only_query_model, only_block_model))
Neel Kant's avatar
Neel Kant committed
109
110
111

    if isinstance(model, torchDDP):
        model = model.module
Neel Kant's avatar
Neel Kant committed
112
    tracker_filename = get_checkpoint_tracker_filename(args.ict_load)
Neel Kant's avatar
Neel Kant committed
113
114
115
116
    with open(tracker_filename, 'r') as f:
        iteration = int(f.read().strip())

    assert iteration > 0
Neel Kant's avatar
Neel Kant committed
117
    checkpoint_name = get_checkpoint_name(args.ict_load, iteration, False)
Neel Kant's avatar
Neel Kant committed
118
119
120
121
122
    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
123
124
125
126
127
128
129
130
131
    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
132
133
134
135
136
137
138
139
    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
140
def get_ict_dataset():
Neel Kant's avatar
Neel Kant committed
141
    args = get_args()
Neel Kant's avatar
Neel Kant committed
142
    block_dataset = get_indexed_dataset_(args.data_path, 'mmap', True)
Neel Kant's avatar
Neel Kant committed
143
    titles_dataset = get_indexed_dataset_(args.titles_data_path, 'mmap', True)
Neel Kant's avatar
Neel Kant committed
144
145
146

    kwargs = dict(
        name='full',
Neel Kant's avatar
Neel Kant committed
147
148
        block_dataset=block_dataset,
        title_dataset=titles_dataset,
Neel Kant's avatar
Neel Kant committed
149
        data_prefix=args.data_path,
Neel Kant's avatar
Neel Kant committed
150
151
        num_epochs=1,
        max_num_samples=None,
Neel Kant's avatar
Neel Kant committed
152
153
154
155
156
157
158
159
        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
160
def get_one_epoch_dataloader(dataset):
Neel Kant's avatar
Neel Kant committed
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
    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
182
    main()