File size: 13,688 Bytes
7f7285f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
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
116
117
118
119
120
121
122
123
124
125
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
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
# -*- coding: utf-8 -*-

"""
@Author             : Bao
@Date               : 2020/4/14
@Desc               :
@Last modified by   : Bao
@Last modified date : 2020/8/12
"""

import os
import copy
import logging
import ujson as json
import torch
from tqdm import tqdm
from torch.utils.data import TensorDataset
import tensorflow as tf
import cjjpy as cjj
import sys

try:
    from ...mrc_client.answer_generator import assemble_answers_to_one
except:
    sys.path.append(cjj.AbsParentDir(__file__, '...'))
    from mrc_client.answer_generator import assemble_answers_to_one

logger = logging.getLogger(__name__)


class InputExample(object):
    def __init__(self, guid, claim, evidences, questions, answers,
                 evidential, label=None, nli_labels=None):
        self.guid = guid
        self.claim = claim
        self.evidences = evidences
        self.questions = questions
        self.answers = answers
        self.evidential = evidential
        self.label = label
        self.nli_labels = nli_labels

    def __repr__(self):
        return str(self.to_json_string())

    def to_dict(self):
        """Serializes this instance to a Python dictionary."""
        output = copy.deepcopy(self.__dict__)
        return output

    def to_json_string(self):
        """Serializes this instance to a JSON string."""
        return json.dumps(self.to_dict(), indent=2, sort_keys=True) + "\n"


class InputFeatures(object):
    def __init__(
            self,
            guid,
            c_input_ids,
            c_attention_mask,
            c_token_type_ids,
            q_input_ids_list,
            q_attention_mask_list,
            q_token_type_ids_list,
            nli_labels=None,
            label=None,
    ):
        self.guid = guid
        self.c_input_ids = c_input_ids
        self.c_attention_mask = c_attention_mask
        self.c_token_type_ids = c_token_type_ids
        self.q_input_ids_list = q_input_ids_list
        self.q_attention_mask_list = q_attention_mask_list
        self.q_token_type_ids_list = q_token_type_ids_list
        self.nli_labels = nli_labels
        self.label = label

    def __repr__(self):
        return str(self.to_json_string())

    def to_dict(self):
        """Serializes this instance to a Python dictionary."""
        output = copy.deepcopy(self.__dict__)
        return output

    def to_json_string(self):
        """Serializes this instance to a JSON string."""
        return json.dumps(self.to_dict(), indent=2, sort_keys=True) + "\n"


def _create_input_ids_from_token_ids(token_ids_a, token_ids_b, tokenizer, max_seq_length):
    pair = len(token_ids_b) != 0

    # Truncate sequences.
    num_special_tokens_to_add = tokenizer.num_special_tokens_to_add(pair=pair)
    while len(token_ids_a) + len(token_ids_b) > max_seq_length - num_special_tokens_to_add:
        if len(token_ids_b) > 0:
            token_ids_b = token_ids_b[:-1]
        else:
            token_ids_a = token_ids_a[:-1]

    # Add special tokens to input_ids.
    input_ids = tokenizer.build_inputs_with_special_tokens(token_ids_a, token_ids_b if pair else None)

    # The mask has 1 for real tokens and 0 for padding tokens. Only real tokens are attended to.
    attention_mask = [1] * len(input_ids)

    # Create token_type_ids.
    token_type_ids = tokenizer.create_token_type_ids_from_sequences(token_ids_a, token_ids_b if pair else None)

    # Pad up to the sequence length.
    padding_length = max_seq_length - len(input_ids)
    if tokenizer.padding_side == "right":
        input_ids = input_ids + ([tokenizer.pad_token_id] * padding_length)
        attention_mask = attention_mask + ([0] * padding_length)
        token_type_ids = token_type_ids + ([tokenizer.pad_token_type_id] * padding_length)
    else:
        input_ids = ([tokenizer.pad_token_id] * padding_length) + input_ids
        attention_mask = ([0] * padding_length) + attention_mask
        token_type_ids = ([tokenizer.pad_token_type_id] * padding_length) + token_type_ids

    assert len(input_ids) == max_seq_length
    assert len(attention_mask) == max_seq_length
    assert len(token_type_ids) == max_seq_length

    return input_ids, attention_mask, token_type_ids


def convert_examples_to_features(
        examples,
        tokenizer,
        max_seq1_length=256,
        max_seq2_length=128,
        verbose=True
):
    features = []
    iter = tqdm(examples, desc="Converting Examples") if verbose else examples
    for (ex_index, example) in enumerate(iter):
        encoded_outputs = {"guid": example.guid, 'label': example.label,
                           'nli_labels': example.nli_labels}

        # ****** for sequence 1 ******* #
        token_ids_a, token_ids_b = [], []

        # text a in sequence 1
        token_ids = tokenizer.encode(example.claim, add_special_tokens=False)  # encode claim
        token_ids_a.extend(token_ids)

        # text b in sequence 1
        for i, evidence in enumerate(example.evidences):
            token_ids = tokenizer.encode(evidence, add_special_tokens=False)  # encode evidence
            token_ids_b.extend(token_ids + [tokenizer.sep_token_id])
        # Remove last sep token in token_ids_b.
        token_ids_b = token_ids_b[:-1]
        token_ids_b = token_ids_b[:max_seq1_length - len(token_ids_a) - 4]  # magic number for special tokens

        # premise </s> </s> hypothesis
        input_ids, attention_mask, token_type_ids = _create_input_ids_from_token_ids(
            token_ids_b,
            token_ids_a,
            tokenizer,
            max_seq1_length,
        )

        encoded_outputs["c_input_ids"] = input_ids
        encoded_outputs["c_attention_mask"] = attention_mask
        encoded_outputs["c_token_type_ids"] = token_type_ids

        # ****** for sequence 2 ******* #
        encoded_outputs["q_input_ids_list"] = []  # m x L
        encoded_outputs["q_attention_mask_list"] = []
        encoded_outputs["q_token_type_ids_list"] = []

        for candidate in example.evidential:
            # text a in sequence 2
            token_ids_a = tokenizer.encode(example.claim, add_special_tokens=False)  # encode claim
            # text b in sequence 2
            token_ids_b = tokenizer.encode(candidate, add_special_tokens=False)  # encode candidate answer
            # premise </s> </s> hypothesis
            input_ids, attention_mask, token_type_ids = _create_input_ids_from_token_ids(
                token_ids_b,
                token_ids_a,
                tokenizer,
                max_seq2_length,
            )

            encoded_outputs["q_input_ids_list"].append(input_ids)
            encoded_outputs["q_attention_mask_list"].append(attention_mask)
            encoded_outputs["q_token_type_ids_list"].append(token_type_ids)

        features.append(InputFeatures(**encoded_outputs))

        if ex_index < 5 and verbose:
            logger.info("*** Example ***")
            logger.info("guid: {}".format(example.guid))
            logger.info("c_input_ids: {}".format(encoded_outputs["c_input_ids"]))
            for input_ids in encoded_outputs['q_input_ids_list']:
                logger.info('q_input_ids: {}'.format(input_ids))
            logger.info("label: {}".format(example.label))
            logger.info("nli_labels: {}".format(example.nli_labels))

    return features


class DataProcessor:
    def __init__(
            self,
            model_name_or_path,
            max_seq1_length,
            max_seq2_length,
            max_num_questions,
            cand_k,
            data_dir='',
            cache_dir_name='cache_check',
            overwrite_cache=False,
            mask_rate=0.
    ):
        self.model_name_or_path = model_name_or_path
        self.max_seq1_length = max_seq1_length
        self.max_seq2_length = max_seq2_length
        self.max_num_questions = max_num_questions
        self.k = cand_k
        self.mask_rate = mask_rate

        self.data_dir = data_dir
        self.cached_data_dir = os.path.join(data_dir, cache_dir_name)
        self.overwrite_cache = overwrite_cache

        self.label2id = {"SUPPORTS": 2, "REFUTES": 0, 'NOT ENOUGH INFO': 1}

    def _format_file(self, role):
        return os.path.join(self.data_dir, "{}.json".format(role))

    def load_and_cache_data(self, role, tokenizer, data_tag):
        tf.io.gfile.makedirs(self.cached_data_dir)
        cached_file = os.path.join(
            self.cached_data_dir,
            "cached_features_{}_{}_{}_{}_{}_{}".format(
                role,
                list(filter(None, self.model_name_or_path.split("/"))).pop(),
                str(self.max_seq1_length),
                str(self.max_seq2_length),
                str(self.k),
                data_tag
            ),
        )
        if os.path.exists(cached_file) and not self.overwrite_cache:
            logger.info("Loading features from cached file {}".format(cached_file))
            features = torch.load(cached_file)
        else:
            examples = []
            with tf.io.gfile.GFile(self._format_file(role)) as f:
                data = f.readlines()
                for line in tqdm(data):
                    sample = self._load_line(line)
                    examples.append(InputExample(**sample))
            features = convert_examples_to_features(examples, tokenizer,
                                                    self.max_seq1_length, self.max_seq2_length)
            if 'train' in role or 'eval' in role:
                logger.info("Saving features into cached file {}".format(cached_file))
                torch.save(features, cached_file)

        return self._create_tensor_dataset(features, tokenizer)

    def convert_inputs_to_dataset(self, inputs, tokenizer, verbose=True):
        examples = []
        for line in inputs:
            sample = self._load_line(line)
            examples.append(InputExample(**sample))
        features = convert_examples_to_features(examples, tokenizer,
                                                self.max_seq1_length, self.max_seq2_length, verbose)

        return self._create_tensor_dataset(features, tokenizer, do_predict=True)

    def _create_tensor_dataset(self, features, tokenizer, do_predict=False):
        all_c_input_ids = torch.tensor([f.c_input_ids for f in features], dtype=torch.long)
        all_c_attention_mask = torch.tensor([f.c_attention_mask for f in features], dtype=torch.long)
        all_c_token_type_ids = torch.tensor([f.c_token_type_ids for f in features], dtype=torch.long)

        all_q_input_ids_list = []
        all_q_attention_mask_list = []
        all_q_token_type_ids_list = []

        def _trunc_agg(self, feature, pad_token):
            # feature: m x L
            _input_list = [v for v in feature[:self.max_num_questions]]
            while len(_input_list) < self.max_num_questions:
                _input_list.append([pad_token] * self.max_seq2_length)
            return _input_list

        for f in features:  # N x m x L
            all_q_input_ids_list.append(_trunc_agg(self, f.q_input_ids_list, tokenizer.pad_token_id))
            all_q_attention_mask_list.append(_trunc_agg(self, f.q_attention_mask_list, 0))
            all_q_token_type_ids_list.append(_trunc_agg(self, f.q_token_type_ids_list, tokenizer.pad_token_type_id))

        all_q_input_ids_list = torch.tensor(all_q_input_ids_list, dtype=torch.long)
        all_q_attention_mask_list = torch.tensor(all_q_attention_mask_list, dtype=torch.long)
        all_q_token_type_ids_list = torch.tensor(all_q_token_type_ids_list, dtype=torch.long)

        all_nli_labels_list = []
        for f in features:
            all_nli_labels_list.append(f.nli_labels[:self.max_num_questions]
                                       + max(0, (self.max_num_questions - len(f.nli_labels))) * [[0., 0., 0.]])
        all_nli_labels = torch.tensor(all_nli_labels_list, dtype=torch.float)

        if not do_predict:
            all_labels = torch.tensor([f.label for f in features], dtype=torch.long)
            dataset = TensorDataset(
                all_c_input_ids, all_c_attention_mask, all_c_token_type_ids,
                all_q_input_ids_list, all_q_attention_mask_list, all_q_token_type_ids_list,
                all_nli_labels, all_labels,
            )
        else:
            dataset = TensorDataset(
                all_c_input_ids, all_c_attention_mask, all_c_token_type_ids,
                all_q_input_ids_list, all_q_attention_mask_list, all_q_token_type_ids_list,
                all_nli_labels,
            )

        return dataset

    def _load_line(self, line):
        if isinstance(line, str):
            line = json.loads(line)
        guid = line["id"]
        claim = line["claim"]

        # TODO: hack no evidence situation
        evidences = line["evidence"] if len(line['evidence']) > 0 else ['no idea'] * 5
        questions = line["questions"]
        answers = line["answers"]
        evidential = assemble_answers_to_one(line, self.k, mask_rate=self.mask_rate)['evidential_assembled']
        label = line.get("label", None)
        nli_labels = line.get('nli_labels', [[0., 0., 0.]] * len(questions))

        for i, e in enumerate(evidential):
            if '<mask>' in e:
                nli_labels[i] = [0., 0., 0.]

        answers = [v[0] for v in answers]  # k = 1
        label = self.label2id.get(label)

        sample = {
            "guid": guid,
            "claim": claim,
            "evidences": evidences,
            "questions": questions,
            "answers": answers,
            "evidential": evidential,  # already assembled.
            "label": label,
            'nli_labels': nli_labels
        }
        return sample