lm_seqs_dataset.py 5.99 KB
Newer Older
VictorSanh's avatar
VictorSanh committed
1
# coding=utf-8
thomwolf's avatar
thomwolf committed
2
# Copyright 2019-present, the HuggingFace Inc. team and Facebook, Inc.
VictorSanh's avatar
VictorSanh committed
3
4
5
6
7
8
9
10
11
12
13
14
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
VictorSanh's avatar
VictorSanh committed
15
""" Dataset to distilled models
thomwolf's avatar
thomwolf committed
16
    adapted in part from Facebook, Inc XLM model (https://github.com/facebookresearch/XLM)
VictorSanh's avatar
VictorSanh committed
17
"""
Aymeric Augustin's avatar
Aymeric Augustin committed
18
import numpy as np
VictorSanh's avatar
VictorSanh committed
19
import torch
VictorSanh's avatar
VictorSanh committed
20
from torch.utils.data import Dataset
VictorSanh's avatar
VictorSanh committed
21
22
23

from utils import logger

24

VictorSanh's avatar
VictorSanh committed
25
26
27
28
29
30
31
32
33
34
35
class LmSeqsDataset(Dataset):
    """Custom Dataset wrapping language modeling sequences.

    Each sample will be retrieved by indexing the list of token_ids and their corresponding lengths.

    Input:
    ------
        params: `NameSpace` parameters
        data: `List[np.array[int]]
    """

36
    def __init__(self, params, data):
VictorSanh's avatar
VictorSanh committed
37
38
39
        self.params = params

        self.token_ids = np.array(data)
VictorSanh's avatar
VictorSanh committed
40
        self.lengths = np.array([len(t) for t in data])
VictorSanh's avatar
VictorSanh committed
41
42
43
44

        self.check()
        self.remove_long_sequences()
        self.remove_empty_sequences()
45
        self.remove_unknown_sequences()
VictorSanh's avatar
VictorSanh committed
46
47
48
        self.check()
        self.print_statistics()

VictorSanh's avatar
VictorSanh committed
49
50
51
    def __getitem__(self, index):
        return (self.token_ids[index], self.lengths[index])

VictorSanh's avatar
VictorSanh committed
52
53
54
55
56
57
58
59
    def __len__(self):
        return len(self.lengths)

    def check(self):
        """
        Some sanity checks
        """
        assert len(self.token_ids) == len(self.lengths)
60
        assert all(self.lengths[i] == len(self.token_ids[i]) for i in range(len(self.lengths)))
VictorSanh's avatar
VictorSanh committed
61
62
63

    def remove_long_sequences(self):
        """
VictorSanh's avatar
VictorSanh committed
64
        Sequences that are too long are splitted by chunk of max_model_input_size.
VictorSanh's avatar
VictorSanh committed
65
        """
VictorSanh's avatar
VictorSanh committed
66
67
        max_len = self.params.max_model_input_size
        indices = self.lengths > max_len
68
        logger.info(f"Splitting {sum(indices)} too long sequences.")
VictorSanh's avatar
VictorSanh committed
69
70

        def divide_chunks(l, n):
71
            return [l[i : i + n] for i in range(0, len(l), n)]
VictorSanh's avatar
VictorSanh committed
72
73
74

        new_tok_ids = []
        new_lengths = []
VictorSanh's avatar
VictorSanh committed
75
        if self.params.mlm:
76
            cls_id, sep_id = self.params.special_tok_ids["cls_token"], self.params.special_tok_ids["sep_token"]
VictorSanh's avatar
VictorSanh committed
77
        else:
78
            cls_id, sep_id = self.params.special_tok_ids["bos_token"], self.params.special_tok_ids["eos_token"]
VictorSanh's avatar
VictorSanh committed
79
80

        for seq_, len_ in zip(self.token_ids, self.lengths):
VictorSanh's avatar
VictorSanh committed
81
            assert (seq_[0] == cls_id) and (seq_[-1] == sep_id), seq_
VictorSanh's avatar
VictorSanh committed
82
83
84
85
86
            if len_ <= max_len:
                new_tok_ids.append(seq_)
                new_lengths.append(len_)
            else:
                sub_seqs = []
87
                for sub_s in divide_chunks(seq_, max_len - 2):
VictorSanh's avatar
VictorSanh committed
88
89
90
                    if sub_s[0] != cls_id:
                        sub_s = np.insert(sub_s, 0, cls_id)
                    if sub_s[-1] != sep_id:
VictorSanh's avatar
VictorSanh committed
91
                        sub_s = np.insert(sub_s, len(sub_s), sep_id)
VictorSanh's avatar
VictorSanh committed
92
                    assert len(sub_s) <= max_len
VictorSanh's avatar
VictorSanh committed
93
                    assert (sub_s[0] == cls_id) and (sub_s[-1] == sep_id), sub_s
VictorSanh's avatar
VictorSanh committed
94
95
96
97
98
99
100
101
102
103
104
105
106
                    sub_seqs.append(sub_s)

                new_tok_ids.extend(sub_seqs)
                new_lengths.extend([len(l) for l in sub_seqs])

        self.token_ids = np.array(new_tok_ids)
        self.lengths = np.array(new_lengths)

    def remove_empty_sequences(self):
        """
        Too short sequences are simply removed. This could be tunedd.
        """
        init_size = len(self)
107
        indices = self.lengths > 11
VictorSanh's avatar
VictorSanh committed
108
109
110
        self.token_ids = self.token_ids[indices]
        self.lengths = self.lengths[indices]
        new_size = len(self)
111
        logger.info(f"Remove {init_size - new_size} too short (<=11 tokens) sequences.")
VictorSanh's avatar
VictorSanh committed
112

113
114
115
116
    def remove_unknown_sequences(self):
        """
        Remove sequences with a (too) high level of unknown tokens.
        """
117
        if "unk_token" not in self.params.special_tok_ids:
118
119
            return
        else:
120
            unk_token_id = self.params.special_tok_ids["unk_token"]
121
122
        init_size = len(self)
        unk_occs = np.array([np.count_nonzero(a == unk_token_id) for a in self.token_ids])
123
        indices = (unk_occs / self.lengths) < 0.5
124
125
126
        self.token_ids = self.token_ids[indices]
        self.lengths = self.lengths[indices]
        new_size = len(self)
127
        logger.info(f"Remove {init_size - new_size} sequences with a high level of unknown tokens (50%).")
128

VictorSanh's avatar
VictorSanh committed
129
130
131
132
133
134
    def print_statistics(self):
        """
        Print some statistics on the corpus. Only the master process.
        """
        if not self.params.is_master:
            return
135
        logger.info(f"{len(self)} sequences")
VictorSanh's avatar
VictorSanh committed
136
137
138
139
140
141
142
143
        # data_len = sum(self.lengths)
        # nb_unique_tokens = len(Counter(list(chain(*self.token_ids))))
        # logger.info(f'{data_len} tokens ({nb_unique_tokens} unique)')

        # unk_idx = self.params.special_tok_ids['unk_token']
        # nb_unkown = sum([(t==unk_idx).sum() for t in self.token_ids])
        # logger.info(f'{nb_unkown} unknown tokens (covering {100*nb_unkown/data_len:.2f}% of the data)')

144
    def batch_sequences(self, batch):
VictorSanh's avatar
VictorSanh committed
145
146
147
        """
        Do the padding and transform into torch.tensor.
        """
VictorSanh's avatar
VictorSanh committed
148
149
        token_ids = [t[0] for t in batch]
        lengths = [t[1] for t in batch]
VictorSanh's avatar
VictorSanh committed
150
151
152
153
154
155
        assert len(token_ids) == len(lengths)

        # Max for paddings
        max_seq_len_ = max(lengths)

        # Pad token ids
VictorSanh's avatar
VictorSanh committed
156
        if self.params.mlm:
157
            pad_idx = self.params.special_tok_ids["pad_token"]
VictorSanh's avatar
VictorSanh committed
158
        else:
159
160
            pad_idx = self.params.special_tok_ids["unk_token"]
        tk_ = [list(t.astype(int)) + [pad_idx] * (max_seq_len_ - len(t)) for t in token_ids]
VictorSanh's avatar
VictorSanh committed
161
162
163
        assert len(tk_) == len(token_ids)
        assert all(len(t) == max_seq_len_ for t in tk_)

164
        tk_t = torch.tensor(tk_)  # (bs, max_seq_len_)
VictorSanh's avatar
VictorSanh committed
165
        lg_t = torch.tensor(lengths)  # (bs)
VictorSanh's avatar
VictorSanh committed
166
        return tk_t, lg_t