-
Notifications
You must be signed in to change notification settings - Fork 2
/
data.py
346 lines (248 loc) · 10.4 KB
/
data.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
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
import itertools
import json
import linecache
import os
import pickle
import re
import socket
import string
from collections import Counter
from logging import getLogger
from pathlib import Path
from typing import Callable, Dict, Iterable, List
import torch
from torch.utils.data import Dataset
import jsonlines
class TextDataset(Dataset):
def __init__(
self,
tokenizer,
data_dir,
max_length,
):
super().__init__()
self.src_file = Path(data_dir)
self.src_lens = self.get_char_lens(self.src_file)
self.max_source_length = max_length
self.tokenizer = tokenizer
self.tokenizer.padding_side = "left"
def __len__(self):
return len(self.src_lens)
def __getitem__(self, index):
index = index + 1 # linecache starts at 1
source_line = linecache.getline(str(self.src_file), index).rstrip("\n") #+self.tokenizer.bos_token
source_line = source_line.replace("xxx", '')
res_input = self.tokenizer.encode_plus(source_line, max_length=self.max_source_length, return_tensors="pt", truncation=True, padding="max_length")
return [res_input["input_ids"], res_input["attention_mask"]]
@staticmethod
def get_char_lens(data_file):
return [len(x) for x in Path(data_file).open().readlines()]
class ToxicPrompt(Dataset):
def __init__(
self,
tokenizer,
data_dir,
max_length,
n_obs=None,
prefix="",
):
super().__init__()
self.src_file = data_dir
self.prompts = []
with open(str(self.src_file), "r+", encoding="utf8") as f:
for item in jsonlines.Reader(f):
prompt = item["prompt"]["text"]
self.prompts.append(prompt)
self.tokenizer = tokenizer
self.max_lens = max_length
self.tokenizer.padding_side = "left"
def __len__(self):
return len(self.prompts)
def __getitem__(self, index):
index = index # linecache starts at 1
source_line = self.prompts[index].rstrip("\n")
source_line = source_line.replace("xxx", '')
res=self.tokenizer.encode_plus(source_line, max_length=self.max_lens, return_tensors="pt",truncation=True, padding="max_length")
return (res["input_ids"], res["attention_mask"])
@staticmethod
def get_char_lens(data_file):
return [len(x) for x in Path(data_file).open().readlines()]
class SentimentPrompt(Dataset):
def __init__(
self,
tokenizer,
data_dir,
max_length,
prompt_type="negative",
n_obs=None,
prefix="",
):
super().__init__()
self.src_file = data_dir + "/" + str(prompt_type) + '_prompts.jsonl'
self.prompts = []
with open(str(self.src_file), "r+", encoding="utf8") as f:
for item in jsonlines.Reader(f):
prompt = item["prompt"]["text"]
self.prompts.append(prompt)
self.tokenizer = tokenizer
self.max_lens = max_length
self.tokenizer.padding_side = "left"
def __len__(self):
return len(self.prompts)
def __getitem__(self, index):
index = index # linecache starts at 1
source_line = self.prompts[index].rstrip("\n")
source_line = source_line.replace("xxx", '')
assert source_line, f"empty source line for index {index}"
res=self.tokenizer.encode_plus(source_line, max_length=self.max_lens, return_tensors="pt",truncation=True, padding="max_length")
return (res["input_ids"], res["attention_mask"])
@staticmethod
def get_char_lens(data_file):
return [len(x) for x in Path(data_file).open().readlines()]
class DetoxicDataset(Dataset):
def __init__(
self,
tokenizer,
data_dir,
max_length,
type_path="train",
n_obs=None,
src_lang=None,
tgt_lang=None,
prefix="",
label_token = {}
):
super().__init__()
self.src_file = Path(data_dir).joinpath(type_path + ".src")
self.tgt_file = Path(data_dir).joinpath(type_path + ".tgt")
self.src_lens = self.get_char_lens(self.src_file)
self.max_source_length = max_length
self.max_target_length = max_length
self.label_token = label_token
assert min(self.src_lens) > 0, f"found empty line in {self.src_file}"
self.tokenizer = tokenizer
self.prefix = prefix
if n_obs is not None:
self.src_lens = self.src_lens[:n_obs]
self.src_lang = src_lang
self.tgt_lang = tgt_lang
self.tokenizer.padding_side = "left"
def token_wrapper(args, token):
if 'roberta' in args.model_name or 'gpt' in args.model_name or 'megatron' in args.model_name:
return 'Ġ' + token
else:
return token
def __len__(self):
return len(self.src_lens)
def __getitem__(self, index):
index = index + 1 # linecache starts at 1
source_line = self.prefix + linecache.getline(str(self.src_file), index).rstrip("\n") #+self.tokenizer.bos_token
source_line = source_line.replace("xxx", '')
tgt_line = linecache.getline(str(self.tgt_file), index).rstrip("\n")
tgt_line = str(tgt_line)
if "1" in tgt_line:
tgt_line = torch.tensor(self.tokenizer.encode(self.label_token['positive']))
else:
tgt_line = torch.tensor(self.tokenizer.encode(self.label_token['negative']))
assert source_line, f"empty source line for index {index}"
assert tgt_line, f"empty tgt line for index {index}"
res_input = self.tokenizer.encode_plus(source_line, max_length=self.max_source_length, return_tensors="pt", truncation=True, padding="max_length")
return [res_input["input_ids"], res_input["attention_mask"], tgt_line]
@staticmethod
def get_char_lens(data_file):
return [len(x) for x in Path(data_file).open().readlines()]
class Classification_Dataset(Dataset):
def __init__(
self,
tokenizer,
data_dir,
max_length,
type_path="train",
n_obs=None,
src_lang=None,
tgt_lang=None,
prefix="",
label_token = {}
):
super().__init__()
self.src_file = Path(data_dir).joinpath(type_path + ".src")
self.tgt_file = Path(data_dir).joinpath(type_path + ".tgt")
self.src_lens = self.get_char_lens(self.src_file)
self.max_source_length = max_length
self.max_target_length = max_length
self.label_token = label_token
assert min(self.src_lens) > 0, f"found empty line in {self.src_file}"
self.tokenizer = tokenizer
self.prefix = prefix
if n_obs is not None:
self.src_lens = self.src_lens[:n_obs]
self.src_lang = src_lang
self.tgt_lang = tgt_lang
self.tokenizer.padding_side = "left"
def token_wrapper(args, token):
if 'roberta' in args.model_name or 'gpt' in args.model_name or 'megatron' in args.model_name:
return 'Ġ' + token
else:
return token
def __len__(self):
return len(self.src_lens)
def __getitem__(self, index):
index = index + 1 # linecache starts at 1
source_line = self.prefix + linecache.getline(str(self.src_file), index).rstrip("\n") #+self.tokenizer.bos_token
tgt_line = linecache.getline(str(self.tgt_file), index).rstrip("\n")
if "positive" in tgt_line:
tgt_line = torch.tensor(self.tokenizer.encode(self.label_token['positive']))
else:
tgt_line = torch.tensor(self.tokenizer.encode(self.label_token['negative']))
assert source_line, f"empty source line for index {index}"
# assert tgt_line, f"empty tgt line for index {index}"
res_input = self.tokenizer.encode_plus(source_line, max_length=self.max_source_length, return_tensors="pt", truncation=True, padding="max_length")
return [res_input["input_ids"], res_input["attention_mask"], tgt_line]
@staticmethod
def get_char_lens(data_file):
return [len(x) for x in Path(data_file).open().readlines()]
class Sentiment_Suffix(Dataset):
def __init__(
self,
tokenizer,
data_dir,
max_length,
task_type="positive",
n_obs=None,
src_lang=None,
tgt_lang=None,
prefix="",
label_token = {}
):
super().__init__()
self.src_file = data_dir
self.src_lens = self.get_char_lens(self.src_file)
self.max_source_length = max_length
self.label_token = label_token
self.task_type = task_type
assert min(self.src_lens) > 0, f"found empty line in {self.src_file}"
self.tokenizer = tokenizer
self.prefix = prefix
if n_obs is not None:
self.src_lens = self.src_lens[:n_obs]
self.src_lang = src_lang
self.tgt_lang = tgt_lang
self.tokenizer.padding_side = "left"
def token_wrapper(args, token):
if 'roberta' in args.model_name or 'gpt' in args.model_name or 'megatron' in args.model_name:
return 'Ġ' + token
else:
return token
def __len__(self):
return len(self.src_lens)
def __getitem__(self, index):
index = index + 1 # linecache starts at 1
source_line = self.prefix + linecache.getline(str(self.src_file), index).rstrip("\n") #+self.tokenizer.bos_token
tgt_line = torch.tensor(self.tokenizer.encode(self.label_token[self.task_type]))
if len(source_line)<2:
source_line = "Hello world! Today is nice!"
res_input = self.tokenizer.encode_plus(source_line, max_length=self.max_source_length, return_tensors="pt", truncation=True, padding="max_length")
return [res_input["input_ids"], res_input["attention_mask"], tgt_line]
@staticmethod
def get_char_lens(data_file):
return [len(x) for x in Path(data_file).open().readlines()]