File size: 16,400 Bytes
550665c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
import numpy as np
from .constants import (
    QUESTION_COLUMN_NAME,
    CONTEXT_COLUMN_NAME,
    ANSWER_COLUMN_NAME,
    ANSWERABLE_COLUMN_NAME,
    ID_COLUMN_NAME
)

def get_sketch_features(

    tokenizer, 

    mode, 

    data_args

):
    """

    Get the features for sketch model.



    Args:

        tokenizer (Tokenizer): Tokenizer for tokenizing input examples.

        mode (str): Mode of operation ("train", "eval", or "test").

        data_args (dict): Additional arguments for data loading.



    Returns:

        tuple: A tuple containing the function for preparing features and a boolean value indicating if labels are required.

    """

    pad_on_right = tokenizer.padding_side == "right"
    max_seq_length = min(data_args.max_seq_length, tokenizer.model_max_length)
    
    def tokenize_fn(examples):
        """

        Tokenize input examples.



        Args:

            examples (dict): Input examples.



        Returns:

            dict: Tokenized examples.

        """
        # Tokenize the input examples using the provided tokenizer.
        # The tokenizer is configured to truncate sequences to a maximum length.
        # The tokenizer also returns the overflowing tokens, offsets mapping, and token type IDs.
        # The padding strategy is determined by the data_args.pad_to_max_length parameter.
        # tokenized_examples = tokenizer(
        #     examples[QUESTION_COLUMN_NAME if pad_on_right else CONTEXT_COLUMN_NAME],
        #     examples[CONTEXT_COLUMN_NAME if pad_on_right else QUESTION_COLUMN_NAME],
        #     truncation="only_second" if pad_on_right else "only_first",
        #     truncation=True,
        #     max_length=max_seq_length,
        #     stride=data_args.doc_stride,
        #     return_overflowing_tokens=True,
        #     return_offsets_mapping=False,
        #     return_token_type_ids=data_args.return_token_type_ids,
        #     padding="max_length" if data_args.pad_to_max_length else False,
        # )


        # Strip leading and trailing whitespaces from questions and contexts
        questions = [q.strip() for q in examples[QUESTION_COLUMN_NAME if pad_on_right else CONTEXT_COLUMN_NAME]]
        contexts = [c.strip() for c in examples[CONTEXT_COLUMN_NAME if pad_on_right else QUESTION_COLUMN_NAME]]

        # Now, apply the tokenizer
        tokenized_examples = tokenizer(
            questions,
            contexts,
            truncation="only_second" if pad_on_right else "only_first",
            max_length=max_seq_length,
            stride=data_args.doc_stride,
            return_overflowing_tokens=True,
            return_offsets_mapping=True,
            return_token_type_ids=data_args.return_token_type_ids,
            padding="max_length" if data_args.pad_to_max_length else False,
        )
        
        return tokenized_examples



    
    def prepare_train_features(examples):
        """

        Prepare training features by tokenizing the input examples and adding labels.



        Args:

            examples (dict): Input examples.



        Returns:

            dict: Tokenized and labeled examples.

        """
        # Tokenize the input examples using the provided tokenizer.
        tokenized_examples = tokenize_fn(examples)
        sample_mapping = tokenized_examples.pop("overflow_to_sample_mapping")
        
        # Add labels to the tokenized examples.
        # The label is 0 for answerable and 1 for not answerable.
        tokenized_examples["labels"] = []
        for i in range(len(tokenized_examples["input_ids"])):
            sample_index = sample_mapping[i]
            
            # Determine if the example is answerable or not.
            is_impossible = examples[ANSWERABLE_COLUMN_NAME][sample_index]
            tokenized_examples["labels"].append(1 if is_impossible else 0)
        
        return tokenized_examples

    
    def prepare_eval_features(examples):
        """

        Prepare evaluation features by tokenizing the input examples and adding labels.



        Args:

            examples (dict): Input examples.



        Returns:

            dict: Tokenized and labeled examples.



        """
        # Tokenize the input examples using the provided tokenizer.
        tokenized_examples = tokenize_fn(examples)
        sample_mapping = tokenized_examples.pop("overflow_to_sample_mapping")
        
        # Add example ids and labels to the tokenized examples.
        tokenized_examples["example_id"] = []
        tokenized_examples["labels"] = []
        
        for i in range(len(tokenized_examples["input_ids"])):
            # Determine the sample index.
            sample_index = sample_mapping[i]
            
            # Extract the example id.
            id_col = examples[ID_COLUMN_NAME][sample_index]
            tokenized_examples["example_id"].append(id_col)
            
            # Determine the label.
            # answerable: 0, not answerable: 1.
            is_impossible = examples[ANSWERABLE_COLUMN_NAME][sample_index]
            tokenized_examples["labels"].append(1 if is_impossible else 0)
        
        return tokenized_examples

    
    def prepare_test_features(examples):
        """

        Prepare test features by tokenizing the input examples and adding example ids.



        Args:

            examples (dict): Input examples.



        Returns:

            dict: Tokenized and labeled examples.



        """
        # Tokenize the input examples using the provided tokenizer.
        tokenized_examples = tokenize_fn(examples)
        sample_mapping = tokenized_examples.pop("overflow_to_sample_mapping")
        
        # Add example ids to the tokenized examples.
        tokenized_examples["example_id"] = []
        
        for i in range(len(tokenized_examples["input_ids"])):
            # Determine the sample index.
            sample_index = sample_mapping[i]
            
            # Extract the example id.
            id_col = examples[ID_COLUMN_NAME][sample_index]
            
            # Add the example id to the tokenized examples.
            tokenized_examples["example_id"].append(id_col)
        
        return tokenized_examples

    
    if mode == "train":
        get_features_fn = prepare_train_features
    elif mode == "eval":
        get_features_fn = prepare_eval_features
    elif mode == "test":
        get_features_fn = prepare_test_features
    
    return get_features_fn, True

def get_intensive_features(

    tokenizer, 

    mode, 

    data_args

):
    """

    Generate intensive features for training, evaluation, or testing.



    Args:

        tokenizer (Tokenizer): The tokenizer used to tokenize the input examples.

        mode (str): The mode of operation. Must be one of "train", "eval", or "test".

        data_args (DataArguments): The data arguments containing the configuration for tokenization.



    Returns:

        tuple: A tuple containing the function to prepare the features and a boolean indicating if the tokenizer is beam-based.



    Raises:

        ValueError: If the mode is not one of "train", "eval", or "test".



    """
    pad_on_right = tokenizer.padding_side == "right"
    max_seq_length = min(data_args.max_seq_length, tokenizer.model_max_length)
    beam_based = data_args.intensive_model_type in ["xlnet", "xlm"]
    
    def tokenize_fn(examples):
        """

        Tokenize input examples.



        Args:

            examples (dict): Input examples.



        Returns:

            dict: Tokenized examples.

        """
        # Tokenize the input examples using the provided tokenizer.
        # The tokenizer is configured to truncate sequences to a maximum length.
        # The tokenizer also returns the overflowing tokens, offsets mapping, and token type IDs.
        # The padding strategy is determined by the data_args.pad_to_max_length parameter.
        tokenized_examples = tokenizer(
            examples[QUESTION_COLUMN_NAME if pad_on_right else CONTEXT_COLUMN_NAME],
            examples[CONTEXT_COLUMN_NAME if pad_on_right else QUESTION_COLUMN_NAME],
            truncation="only_second" if pad_on_right else "only_first",
            max_length=max_seq_length,
            stride=data_args.doc_stride,
            return_overflowing_tokens=True,
            return_offsets_mapping=True,
            return_token_type_ids=data_args.return_token_type_ids,
            padding="max_length" if data_args.pad_to_max_length else False,
        )
        
        return tokenized_examples
    
    def prepare_train_features(examples):
        """

        Prepare training features by tokenizing the input examples and adding labels.



        Args:

            examples (dict): Input examples.



        Returns:

            dict: Tokenized and labeled examples.

        """
        # Tokenize the input examples using the provided tokenizer.
        tokenized_examples = tokenize_fn(examples)
        sample_mapping = tokenized_examples.pop("overflow_to_sample_mapping")
        offset_mapping = tokenized_examples.pop("offset_mapping")
        
        # Add start positions, end positions, and is_impossibles to the tokenized examples.
        tokenized_examples["start_positions"] = []
        tokenized_examples["end_positions"] = []
        tokenized_examples["is_impossibles"] = []
        
        if beam_based:
            # Add cls_index and p_mask to the tokenized examples if beam_based.
            tokenized_examples["cls_index"] = []
            tokenized_examples["p_mask"] = []
        
        for i, offsets in enumerate(offset_mapping):
            # We will label impossible answers with the index of the CLS token.
            # Get the input_ids and cls_index for the current example.
            input_ids = tokenized_examples["input_ids"][i]
            cls_index = input_ids.index(tokenizer.cls_token_id)
            
            # Get the sequence_ids for the current example.
            sequence_ids = tokenized_examples.sequence_ids(i)
            context_index = 1 if pad_on_right else 0
            
            # Build the p_mask: non special tokens and context gets 0.0, the others get 1.0.
            # The cls token gets 0.0 too (for predictions of empty answers).
            # Inspired by XLNet.
            if beam_based:
                tokenized_examples["cls_index"].append(cls_index)
                tokenized_examples["p_mask"].append(
                    [
                    0.0 if s == context_index or k == cls_index else 1.0
                    for s, k in enumerate(sequence_ids)
                    ]
                )
            
            # Get the sample_index, answers, and is_impossible for the current example.
            sample_index = sample_mapping[i]
            answers = examples[ANSWER_COLUMN_NAME][sample_index]
            is_impossible = examples[ANSWERABLE_COLUMN_NAME][sample_index]
            
            # If no answers are given, set the cls_index as answer.
            if is_impossible or len(answers["answer_start"]) == 0:
                tokenized_examples["start_positions"].append(cls_index)
                tokenized_examples["end_positions"].append(cls_index)
                tokenized_examples["is_impossibles"].append(1.0) # unanswerable
            else:
                # Start and end token index of the current span in the text.
                start_char = answers["answer_start"][0]
                end_char = start_char + len(answers["text"][0])
                
                # sequence_ids: 0 for question, 1 for context, None for others
                
                # Start token index of the current span in the tokenized context.
                token_start_index = 0
                while sequence_ids[token_start_index] != context_index:
                    token_start_index += 1
                    
                # End token index of the current span in the tokenized context.
                token_end_index = len(input_ids) - 1
                while sequence_ids[token_end_index] != context_index:
                    token_end_index -= 1
                
                # Detect if the answer is out of the span (in which case this feature is labeled with the CLS index).
                if not (offsets[token_start_index][0] <= start_char and 
                        offsets[token_end_index][1] >= end_char
                ):
                    tokenized_examples["start_positions"].append(cls_index)
                    tokenized_examples["end_positions"].append(cls_index)
                    tokenized_examples["is_impossibles"].append(1.0) # answerable
                else:
                    # Otherwise move the token_start_index and token_end_index to the two ends of the answer.
                    # Note: we could go after the last offset if the answer is the last word (edge case).
                    while (token_start_index < len(offsets) and 
                           offsets[token_start_index][0] <= start_char):
                        token_start_index += 1
                    tokenized_examples["start_positions"].append(token_start_index - 1)

                    while offsets[token_end_index][1] >= end_char:
                        token_end_index -= 1
                    tokenized_examples["end_positions"].append(token_end_index + 1)
                    tokenized_examples["is_impossibles"].append(0.0) # answerable
                    
        return tokenized_examples            
    

    def prepare_eval_features(examples):
        """

        Prepare evaluation features by tokenizing the input examples and adding labels.



        Args:

            examples (dict): Input examples.



        Returns:

            dict: Tokenized and labeled examples.

        """
        # Tokenize the input examples using the provided tokenizer.
        tokenized_examples = tokenize_fn(examples)
        sample_mapping = tokenized_examples.pop("overflow_to_sample_mapping")
        
        # Add example ids to the tokenized examples.
        tokenized_examples["example_id"] = []
        
        if beam_based:
            # Add cls_index and p_mask to the tokenized examples if beam_based.
            tokenized_examples["cls_index"] = []
            tokenized_examples["p_mask"] = []
        
        for i, input_ids in enumerate(tokenized_examples["input_ids"]):
            # Find the CLS index in the input_ids.
            cls_index = input_ids.index(tokenizer.cls_token_id)
            
            sequence_ids = tokenized_examples.sequence_ids(i)
            context_index = 1 if pad_on_right else 0
            
            if beam_based:
                # Build the p_mask: non special tokens and context gets 0.0, the others get 1.0.
                # The cls token gets 0.0 too (for predictions of empty answers).
                # Inspired by XLNet.
                tokenized_examples["cls_index"].append(cls_index)
                tokenized_examples["p_mask"].append(
                    [
                    0.0 if s == context_index or k == cls_index else 1.0
                    for s, k in enumerate(sequence_ids)
                    ]
                )
            
            sample_index = sample_mapping[i]
            id_col = examples[ID_COLUMN_NAME][sample_index]
            tokenized_examples["example_id"].append(id_col)
            
            # Set to None the offset mapping that are not part of the context
            # so it's easy to determine if a token position is part of the context or not.
            tokenized_examples["offset_mapping"][i] = [
                (o if sequence_ids[k] == context_index else None)
                for k, o in enumerate(tokenized_examples["offset_mapping"][i])
            ]
        
        return tokenized_examples
    
    if mode == "train":
        get_features_fn = prepare_train_features
    elif mode == "eval":
        get_features_fn = prepare_eval_features
    elif mode == "test":
        get_features_fn = prepare_eval_features
        
    return get_features_fn, True