ict_dataset.py 6.98 KB
Newer Older
1
import itertools
2
import random
3
4
import os
import time
5
6

import numpy as np
7
import torch
8
9
10
from torch.utils.data import Dataset

from megatron import get_tokenizer
11
12
13
from megatron import print_rank_0
from megatron import mpu
from megatron.data import helpers
14

15

16
class InverseClozeDataset(Dataset):
17
    """Dataset containing sentences and their blocks for an inverse cloze task."""
Neel Kant's avatar
Neel Kant committed
18
    def __init__(self, name, block_dataset, title_dataset, data_prefix,
19
20
21
22
23
                 num_epochs, max_num_samples, max_seq_length,
                 short_seq_prob, seed):
        self.name = name
        self.seed = seed
        self.max_seq_length = max_seq_length
Neel Kant's avatar
Neel Kant committed
24
25
        self.block_dataset = block_dataset
        self.title_dataset = title_dataset
26
        self.short_seq_prob = short_seq_prob
27
28
        self.rng = random.Random(self.seed)

Neel Kant's avatar
Neel Kant committed
29
30
        self.samples_mapping = get_samples_mapping(self.block_dataset,
                                                   self.title_dataset,
31
32
33
34
35
36
                                                   data_prefix,
                                                   num_epochs,
                                                   max_num_samples,
                                                   self.max_seq_length,
                                                   self.seed,
                                                   self.name)
37
38
39
40
41
42
43
44
45
        tokenizer = get_tokenizer()
        self.vocab_id_list = list(tokenizer.inv_vocab.keys())
        self.vocab_id_to_token_list = tokenizer.inv_vocab
        self.cls_id = tokenizer.cls
        self.sep_id = tokenizer.sep
        self.mask_id = tokenizer.mask
        self.pad_id = tokenizer.pad

    def __len__(self):
46
        return self.samples_mapping.shape[0]
47
48

    def __getitem__(self, idx):
Neel Kant's avatar
Neel Kant committed
49
50
51
52
        start_idx, end_idx, doc_idx, block_idx = self.samples_mapping[idx]
        title = list(self.title_dataset[int(doc_idx)])
        block = [list(self.block_dataset[i]) for i in range(start_idx, end_idx)]
        assert len(block) > 1
53

54
        # avoid selecting the first or last sentence to be the query.
Neel Kant's avatar
Neel Kant committed
55
        if len(block) == 2:
56
57
            rand_sent_idx = int(self.rng.random() > 0.5)
        else:
Neel Kant's avatar
Neel Kant committed
58
            rand_sent_idx = self.rng.randint(1, len(block) - 2)
59

Neel Kant's avatar
Neel Kant committed
60
        # keep the query in the block 10% of the time.
61
        if self.rng.random() < 0.1:
Neel Kant's avatar
Neel Kant committed
62
            query = block[rand_sent_idx].copy()
63
        else:
Neel Kant's avatar
Neel Kant committed
64
            query = block.pop(rand_sent_idx)
65

Neel Kant's avatar
Neel Kant committed
66
        # still need to truncate because blocks are concluded when
67
        # the sentence lengths have exceeded max_seq_length.
Neel Kant's avatar
Neel Kant committed
68
69
        query = query[:self.max_seq_length - 2]
        block = list(itertools.chain(*block))[:self.max_seq_length - (3 + len(title))]
70

Neel Kant's avatar
Neel Kant committed
71
72
        query_tokens, query_token_types, query_pad_mask = self.concat_and_pad_tokens(query)
        block_tokens, block_token_types, block_pad_mask = self.concat_and_pad_tokens(block, title)
73
74

        sample = {
Neel Kant's avatar
Neel Kant committed
75
76
77
78
79
80
            'query_tokens': np.array(query_tokens),
            'query_types': np.array(query_token_types),
            'query_pad_mask': np.array(query_pad_mask),
            'block_tokens': np.array(block_tokens),
            'block_types': np.array(block_token_types),
            'block_pad_mask': np.array(block_pad_mask)
81
82
83
84
        }

        return sample

85
    def concat_and_pad_tokens(self, tokens, title=None):
86
87
        """concat with special tokens and pad sequence to self.max_seq_length"""
        tokens = [self.cls_id] + tokens + [self.sep_id]
88
89
        if title is not None:
            tokens += title + [self.sep_id]
90
        assert len(tokens) <= self.max_seq_length, len(tokens)
91
92

        num_pad = self.max_seq_length - len(tokens)
93
94
        pad_mask = [0] * len(tokens) + [1] * num_pad
        tokens += [self.pad_id] * num_pad
95
        token_types = [0] * self.max_seq_length
96
97
        return tokens, token_types, pad_mask

98

Neel Kant's avatar
Neel Kant committed
99
def get_samples_mapping(block_dataset,
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
                        titles_dataset,
                        data_prefix,
                        num_epochs,
                        max_num_samples,
                        max_seq_length,
                        seed,
                        name):
    if not num_epochs:
        if not max_num_samples:
            raise ValueError("Need to specify either max_num_samples "
                             "or num_epochs")
        num_epochs = np.iinfo(np.int32).max - 1
    if not max_num_samples:
        max_num_samples = np.iinfo(np.int64).max - 1

    # Filename of the index mapping
    indexmap_filename = data_prefix
    indexmap_filename += '_{}_indexmap'.format(name)
    if num_epochs != (np.iinfo(np.int32).max - 1):
        indexmap_filename += '_{}ep'.format(num_epochs)
    if max_num_samples != (np.iinfo(np.int64).max - 1):
        indexmap_filename += '_{}mns'.format(max_num_samples)
    indexmap_filename += '_{}msl'.format(max_seq_length)
    indexmap_filename += '_{}s'.format(seed)
    indexmap_filename += '.npy'

    # Build the indexed mapping if not exist.
    if torch.distributed.get_rank() == 0 and \
            not os.path.isfile(indexmap_filename):
        print(' > WARNING: could not find index map file {}, building '
              'the indices on rank 0 ...'.format(indexmap_filename))

        # Make sure the types match the helpers input types.
Neel Kant's avatar
Neel Kant committed
133
134
        assert block_dataset.doc_idx.dtype == np.int64
        assert block_dataset.sizes.dtype == np.int32
135
136
137
138
139
140
141

        # Build samples mapping
        verbose = torch.distributed.get_rank() == 0
        start_time = time.time()
        print_rank_0(' > building samples index mapping for {} ...'.format(
            name))
        samples_mapping = helpers.build_blocks_mapping(
Neel Kant's avatar
Neel Kant committed
142
143
            block_dataset.doc_idx,
            block_dataset.sizes,
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
            titles_dataset.sizes,
            num_epochs,
            max_num_samples,
            max_seq_length-3,  # account for added tokens
            seed,
            verbose)
        print_rank_0(' > done building samples index mapping')
        np.save(indexmap_filename, samples_mapping, allow_pickle=True)
        print_rank_0(' > saved the index mapping in {}'.format(
            indexmap_filename))
        # Make sure all the ranks have built the mapping
        print_rank_0(' > elapsed time to build and save samples mapping '
                     '(seconds): {:4f}'.format(
            time.time() - start_time))
    # This should be a barrier but nccl barrier assumes
    # device_index=rank which is not the case for model
    # parallel case
    counts = torch.cuda.LongTensor([1])
    torch.distributed.all_reduce(counts, group=mpu.get_data_parallel_group())
    assert counts[0].item() == torch.distributed.get_world_size(
        group=mpu.get_data_parallel_group())

    # Load indexed dataset.
    print_rank_0(' > loading indexed mapping from {}'.format(
        indexmap_filename))
    start_time = time.time()
    samples_mapping = np.load(indexmap_filename, allow_pickle=True)
    print_rank_0('    loaded indexed file in {:3.3f} seconds'.format(
        time.time() - start_time))
    print_rank_0('    total number of samples: {}'.format(
        samples_mapping.shape[0]))

    return samples_mapping