-
Notifications
You must be signed in to change notification settings - Fork 0
/
dataset.py
215 lines (180 loc) · 8.11 KB
/
dataset.py
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
import numpy as np
import random
import torch
from transformers import AutoTokenizer
from torch.utils.data import TensorDataset, Dataset
class BiEncoder_Dataset_Original(Dataset):
"""
If the question and passage are tokenized,
simply cut them into max_length and input them.
ex) Q: 김연아는 어느나라 사람이니?
P: 김연아는 대한민국의 대표로서 올림픽에서 당당히 금메달을 차지했다.
-> Q김연아는 어느나라 사람이니? / P(김연아는 대한민국의 대표로서)
"""
def __init__(self, queries, passages, tokenizer):
self.queries = queries
self.passages = passages
self.tokenizer = tokenizer
def __len__(self):
return len(self.queries)
def _return_train_dataset(self):
q_seqs = self.tokenizer(
self.queries, padding="max_length", truncation=True, return_tensors="pt"
)
p_seqs = self.tokenizer(
self.passages, padding="max_length", truncation=True, return_tensors="pt"
)
train_dataset = TensorDataset(
p_seqs["input_ids"],
p_seqs["attention_mask"],
p_seqs["token_type_ids"],
q_seqs["input_ids"],
q_seqs["attention_mask"],
q_seqs["token_type_ids"],
)
return train_dataset
class BiEncoder_Dataset_Overflow(Dataset):
"""
When the question and passage are tokenized,
additional data is generated for sentences that are truncated with max_length,
question and the cut passage is made into q-p pairs
ex) Q: 김연아는 어느나라 사람이니?
P: 김연아는 대한민국의 대표로서 올림픽에서 당당히 금메달을 차지했다.
-> Q김연아는 어느나라 사람이니? / P(김연아는 대한민국의 대표로서)
-> Q김연아는 어느나라 사람이니? / P(대표로서 올림픽에서 당당히 금메달을)
-> Q김연아는 어느나라 사람이니? / P(금메달을 차지했다. Pad Pad Pad)
In the case of Korean corpus, this code was used
because there are many losses of information
if the passage is tokenized and most of the tokenized passage length exceeds max_length.
Return:
Dataset format
"""
def __init__(self, queries, passages, tokenizer):
self.queries = queries
self.passages = passages
self.tokenizer = tokenizer
def __len__(self):
return len(self.queries)
def _return_train_dataset(self):
for i in range(len(self.queries)):
if i == 0:
q_seqs = self.tokenizer(
self.queries[i],
padding="max_length",
truncation=True,
return_tensors="pt",
)
p_seqs = self.tokenizer(
self.passages[i],
truncation=True,
stride=128,
padding="max_length",
return_overflowing_tokens=True,
return_offsets_mapping=True,
return_tensors="pt",
)
p_seqs.pop("overflow_to_sample_mapping")
p_seqs.pop("offset_mapping")
for k in q_seqs.keys():
q_seqs[k] = q_seqs[k].tolist()
p_seqs[k] = p_seqs[k].tolist()
initial_p_seqs_length = len(p_seqs['input_ids'])
for j in range(len(p_seqs['input_ids'])):
q_seqs['input_ids'].append(q_seqs['input_ids'][0])
q_seqs['token_type_ids'].append(
q_seqs['token_type_ids'][0])
q_seqs['attention_mask'].append(
q_seqs['attention_mask'][0])
p_seqs['input_ids'].append(p_seqs['input_ids'][j])
p_seqs['token_type_ids'].append(
p_seqs['token_type_ids'][j])
p_seqs['attention_mask'].append(
p_seqs['attention_mask'][j])
q_seqs['input_ids'] = q_seqs['input_ids'][1:]
q_seqs['token_type_ids'] = q_seqs['token_type_ids'][1:]
q_seqs['attention_mask'] = q_seqs['attention_mask'][1:]
p_seqs['input_ids'] = p_seqs['input_ids'][initial_p_seqs_length:]
p_seqs['token_type_ids'] = p_seqs['token_type_ids'][initial_p_seqs_length:]
p_seqs['attention_mask'] = p_seqs['attention_mask'][initial_p_seqs_length:]
else:
tmp_q_seq = self.tokenizer(
self.queries[i],
padding="max_length",
truncation=True,
return_tensors="pt",
)
tmp_p_seq = self.tokenizer(
self.passages[i],
truncation=True,
stride=128,
padding="max_length",
return_overflowing_tokens=True,
return_offsets_mapping=True,
return_tensors="pt",
)
tmp_p_seq.pop("overflow_to_sample_mapping")
tmp_p_seq.pop("offset_mapping")
for k in tmp_p_seq.keys():
tmp_p_seq[k] = tmp_p_seq[k].tolist()
tmp_q_seq[k] = tmp_q_seq[k].tolist()
for j in range(len(tmp_p_seq["input_ids"])):
q_seqs["input_ids"].append(tmp_q_seq["input_ids"][0])
q_seqs["token_type_ids"].append(
tmp_q_seq["token_type_ids"][0])
q_seqs["attention_mask"].append(
tmp_q_seq["attention_mask"][0])
p_seqs["input_ids"].append(tmp_p_seq["input_ids"][j])
p_seqs["token_type_ids"].append(
tmp_p_seq["token_type_ids"][j])
p_seqs["attention_mask"].append(
tmp_p_seq["attention_mask"][j])
for k in q_seqs.keys():
q_seqs[k] = torch.tensor(q_seqs[k])
p_seqs[k] = torch.tensor(p_seqs[k])
train_dataset = TensorDataset(
p_seqs["input_ids"],
p_seqs["attention_mask"],
# If you use the roberta model, annotate 'token_type_ids'.
p_seqs["token_type_ids"],
q_seqs["input_ids"],
q_seqs["attention_mask"],
# If you use the roberta model, annotate 'token_type_ids'.
q_seqs["token_type_ids"],
)
return train_dataset
class CrossEncoder_Dataset(Dataset):
"""
The question and Passage are grouped and overflowed to form an input form of CrossEncoder.
ex) Q: 김연아는 어느나라 사람이니?
P: 김연아는 대한민국의 대표로서 올림픽에서 당당히 금메달을 차지했다.
-> [CLS] 김연아는 어느나라 사람이니? [SEP] 김연아는 대한민국의 대표로서
-> [CLS] 김연아는 어느나라 사람이니? [SEP] 대표로서 올림픽에서 당당히 금메달을
-> [CLS] 김연아는 어느나라 사람이니? [SEP] 금메달을 차지했다. [SEP] [PAD] ..
"""
def __init__(self, queries, passages, tokenizer):
self.queries = queries
self.passages = passages
self.tokenizer = tokenizer
def __len__(self):
return len(self.queries)
def _return_train_dataset(self):
tokenized_examples = self.tokenizer(
self.queries,
self.passages,
truncation="only_second",
max_length=512,
strid=128,
return_overflowing_tokens=True,
return_offsets_mapping=True,
# return_token_type_ids=False, # if you want to use roberta tokenizer, you release this code
padding="max_length",
return_tensors="pt",
)
train_dataset = TensorDataset(
tokenized_examples["input_ids"],
tokenized_examples["attention_mask"],
tokenized_examples[
"token_type_ids"
], # When you use RoBertaModel, annotate it
)
return train_dataset