-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.py
366 lines (324 loc) · 17.6 KB
/
utils.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
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
import pandas as pd
import torch
import copy
from transformers import T5Config
from datasets import Dataset, DatasetDict
from datasets import load_dataset
from transformers import AutoTokenizer, AutoModelForSeq2SeqLM, set_seed
import numpy
import numpy as np
from torch.utils.data import DataLoader
import pdb
import os
def log_info(logging, s):
logging.info(s)
def get_dataset(tokenizer, args, logging, model_name_or_path, data_file, source_max_length, target_max_length, batch_size):
# load dataset
import random
seed = 0
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
if args.datafile_path == "NicolaiSivesind/ChatGPT-Research-Abstracts": # max_length = 455
dataset = load_dataset("NicolaiSivesind/ChatGPT-Research-Abstracts")
# filter dataset with word count > 100
dataset_df = dataset["train"].to_pandas()
index = dataset_df.index
index = list(index)
total_num = len(dataset_df)
train_num = int(total_num * 0.8)
# split train and validation dataset
os.makedirs("./nlp_dataset/ChatGPT-Research-Abstracts", exist_ok=True)
if os.path.exists("./nlp_dataset/ChatGPT-Research-Abstracts/index_train.txt"):
with open("./nlp_dataset/ChatGPT-Research-Abstracts/index_train.txt", "r") as f:
index_train = f.read().split(",")
index_train = [int(i) for i in index_train]
index_val = list(set(index) - set(index_train))
dataset["train_tmp"] = dataset["train"].select(index_train)
dataset["validation"] = dataset["train"].select(index_val)
dataset["train"] = dataset["train_tmp"]
else:
index_train = random.sample(index, train_num)
index_val = list(set(index) - set(index_train))
dataset["train_tmp"] = dataset["train"].select(index_train)
dataset["validation"] = dataset["train"].select(index_val)
dataset["train"] = dataset["train_tmp"]
# save index_train to file
with open("./nlp_dataset/ChatGPT-Research-Abstracts/index_train.txt", "w") as f:
f.write(",".join([str(i) for i in index_train]))
text_column = "generated_abstract"
label_column = "generated_abstract"
if args.target_text_type == "human_machine":
label_column = "real_abstract"
elif args.target_text_type == "rephrase":
import csv
# read rephrase_text from csv file
rephrase_text = []
with open("./dataset_collect/rephrase_text.csv", "r") as f:
reader = csv.reader(f)
for row in reader:
rephrase_text = row
break
## add rephrase_text as a new column to dataset
# get rephrase list list(index) from rephrase_text
rephrase_text = [rephrase_text[i] for i in index]
dataset_df = dataset["train"].to_pandas()
dataset_df["rephrase_text"] = rephrase_text[:len(dataset_df)]
dataset["train"] = Dataset.from_pandas(dataset_df)
dataset_df = dataset["validation"].to_pandas()
dataset_df["rephrase_text"] = rephrase_text[len(dataset["train"]):]
dataset["validation"] = Dataset.from_pandas(dataset_df)
label_column = "rephrase_text"
elif args.target_text_type == "rephrase_multi":
import csv
# read rephrase_text from csv file
rephrase_text1 = []
with open("./dataset_collect/rephrase_text_full_0.csv", "r") as f:
reader = csv.reader(f)
for row in reader:
rephrase_text1 = row
break
rephrase_text2 = []
with open("./dataset_collect/rephrase_text_full_1.csv", "r") as f:
reader = csv.reader(f)
for row in reader:
rephrase_text2 = row
break
# rephrase_text is the concatenation of rephrase_text1 and rephrase_text2
rephrase_text = rephrase_text1 + rephrase_text2
column = ["rephrase1", "rephrase2", "rephrase3", "rephrase4", "rephrase5", "rephrase6", "rephrase7", "rephrase8", "rephrase9", "rephrase10"]
dataset_df_train = dataset["train"].to_pandas()
# dataset_df["rephrase_text"] = [rephrase_text[i:i+10] for i in range(0, 10*len(dataset_df), 10)]
# rephrase_text = [rephrase_text[i:i+10] for i in range(0, len(rephrase_text), 10)]
for i in range(len(column)):
final_list = []
for j in index_train:
final_list.append(rephrase_text[j*10+i])
dataset_df_train[column[i]] = final_list
dataset["train"] = Dataset.from_pandas(dataset_df_train)
dataset_df_val = dataset["validation"].to_pandas()
# dataset_df["rephrase_text"] = [rephrase_text[i:i+10] for i in range(len(dataset["train"])*10, (8000+2000)*10, 10)]
#for i in range(len(column)):
# dataset_df[column[i]] = rephrase_text[j+i] for j in range(len(dataset["train"])*10, (8000+2000)*10, 10)
for i in range(len(column)):
final_list = []
for j in index_val:
final_list.append(rephrase_text[j*10+i])
dataset_df_val[column[i]] = final_list
dataset["validation"] = Dataset.from_pandas(dataset_df_val)
label_column = "rephrase_text"
#pdb.set_trace()
elif args.datafile_path == "wikitext": # max_length = 699
dataset = load_dataset('wikitext', 'wikitext-2-v1')
dataset_df = dataset["train"].to_pandas()
dataset_df = dataset_df[dataset_df["text"].str.len() > 50]
dataset["train"] = Dataset.from_pandas(dataset_df)
dataset_df = dataset["validation"].to_pandas()
dataset_df = dataset_df[dataset_df["text"].str.len() > 50]
dataset["validation"] = Dataset.from_pandas(dataset_df)
text_column = "text"
label_column = "text"
elif args.datafile_path == "Hello-SimpleAI/HC3-gpt": # max_length = 639/ tokenn=650
dataset = load_dataset("Hello-SimpleAI/HC3", "all")
dataset_df = dataset["train"].to_pandas()
dataset_df['mask'] = dataset_df.apply(lambda x: len(x["chatgpt_answers"]) > 0, axis=1)
# remove dataset_df with mask = False
dataset_df = dataset_df[dataset_df['mask'] == True]
dataset_df = dataset_df.reset_index(drop=True)
dataset_df["chatgpt_answers"] = dataset_df["chatgpt_answers"].apply(lambda x: x[0])
print("dataset_df", dataset_df)
index = dataset_df.index
index = list(index)
total_num = len(dataset_df)
train_num = int(total_num * 0.8)
dataset = dataset_df
# convert dataset to DatasetDict
dataset = DatasetDict({"train": Dataset.from_pandas(dataset_df)})
# split train and validation dataset
os.makedirs("./nlp_dataset/HC3-gpt", exist_ok=True)
if os.path.exists("./nlp_dataset/HC3-gpt/index_train.txt"):
with open("./nlp_dataset/HC3-gpt/index_train.txt", "r") as f:
index_train = f.read().split(",")
index_train = [int(i) for i in index_train]
index_val = list(set(index) - set(index_train))
dataset["train_tmp"] = dataset["train"].select(index_train)
dataset["validation"] = dataset["train"].select(index_val)
dataset["train"] = dataset["train_tmp"]
else:
index_train = random.sample(index, train_num)
index_val = list(set(index) - set(index_train))
dataset["train_tmp"] = dataset["train"].select(index_train)
dataset["validation"] = dataset["train"].select(index_val)
dataset["train"] = dataset["train_tmp"]
# save index_train to file
with open("./nlp_dataset/HC3-gpt/index_train.txt", "w") as f:
f.write(",".join([str(i) for i in index_train]))
text_column = "chatgpt_answers"
label_column = "chatgpt_answers"
elif args.datafile_path == "NicolaiSivesind/ChatGPT-Research-Abstracts-human": # max=584/ token=590
dataset = load_dataset("NicolaiSivesind/ChatGPT-Research-Abstracts")
# filter dataset with word count > 100
dataset_df = dataset["train"].to_pandas()
index = dataset_df.index
index = list(index)
total_num = len(dataset_df)
train_num = int(total_num * 0.8)
# split train and validation dataset
os.makedirs("./nlp_dataset/ChatGPT-Research-Abstracts-human", exist_ok=True)
if os.path.exists("./nlp_dataset/ChatGPT-Research-Abstracts-human/index_train.txt"):
with open("./nlp_dataset/ChatGPT-Research-Abstracts-human/index_train.txt", "r") as f:
index_train = f.read().split(",")
index_train = [int(i) for i in index_train]
index_val = list(set(index) - set(index_train))
dataset["train_tmp"] = dataset["train"].select(index_train)
dataset["validation"] = dataset["train"].select(index_val)
dataset["train"] = dataset["train_tmp"]
else:
index_train = random.sample(index, train_num)
index_val = list(set(index) - set(index_train))
dataset["train_tmp"] = dataset["train"].select(index_train)
dataset["validation"] = dataset["train"].select(index_val)
dataset["train"] = dataset["train_tmp"]
# save index_train to file
with open("./nlp_dataset/ChatGPT-Research-Abstracts-human/index_train.txt", "w") as f:
f.write(",".join([str(i) for i in index_train]))
text_column = "real_abstract"
label_column = "real_abstract"
log_info(logging, f"Dataset length :{len(dataset['train'])}")
def preprocess_function(sample, padding="max_length"):
inputs = sample[text_column]
model_inputs = tokenizer(inputs, max_length=source_max_length, padding=padding, truncation=True)
if args.target_text_type == "original":
labels = tokenizer(text_target=sample[label_column], max_length=target_max_length, padding=padding, truncation=True)
if padding == "max_length":
labels["input_ids"] = [[(l if l != tokenizer.pad_token_id else -100) for l in label] for label in labels["input_ids"]]
elif args.target_text_type == "shift_token":
## shift tokens of sample[label_column]
labels = tokenizer(text_target=sample[label_column], max_length=target_max_length, padding=padding, truncation=True)
input_ids = labels["input_ids"]
input_ids = torch.tensor(input_ids)
input_ids = input_ids[:,1:]
input_ids = torch.cat([input_ids, torch.tensor([[tokenizer.pad_token_id]]).repeat(input_ids.shape[0], 1)], dim=1)
if padding == "max_length":
input_ids = [[(l if l != tokenizer.pad_token_id else -100) for l in label] for label in input_ids]
labels["input_ids"] = input_ids
elif args.target_text_type == "rephrase":
labels = tokenizer(text_target=sample[label_column], max_length=target_max_length, padding=padding, truncation=True)
if padding == "max_length":
labels["input_ids"] = [[(l if l != tokenizer.pad_token_id else -100) for l in label] for label in labels["input_ids"]]
elif args.target_text_type == "human_machine":
labels = tokenizer(text_target=sample[label_column], max_length=target_max_length, padding=padding, truncation=True)
if padding == "max_length":
labels["input_ids"] = [[(l if l != tokenizer.pad_token_id else -100) for l in label] for label in labels["input_ids"]]
elif args.target_text_type == "rephrase_multi":
column = ["rephrase1", "rephrase2", "rephrase3", "rephrase4", "rephrase5", "rephrase6", "rephrase7", "rephrase8", "rephrase9", "rephrase10"]
total_label = torch.tensor([])
for c in column:
labels = tokenizer(text_target=sample[c], max_length=target_max_length, padding=padding, truncation=True)
if padding == "max_length":
labels["input_ids"] = [[(l if l != tokenizer.pad_token_id else -100) for l in label] for label in labels["input_ids"]]
# concate labels["input_ids"] to total_label
total_label = torch.cat([total_label, torch.tensor(labels["input_ids"])], dim=1)
# convert total_label to torch Long
total_label = total_label.long()
if args.target_text_type == "rephrase_multi":
model_inputs["labels"] = total_label # [10000, 256]
else:
model_inputs["labels"] = labels["input_ids"]
attention_mask = model_inputs["attention_mask"]
attention_mask = torch.tensor(attention_mask)
message_all = torch.tensor(sample['message_all'])
model_inputs["message_all"] = message_all
model_inputs["message_base"] = sample['message_base']
return model_inputs
prev_mssage = numpy.random.randint(0, 2, size=(4))
prev_mssage = torch.tensor(prev_mssage, dtype=torch.float)
def str_convert(example):
if args.target_text_type == "rephrase_multi":
column = ["rephrase1", "rephrase2", "rephrase3", "rephrase4", "rephrase5", "rephrase6", "rephrase7", "rephrase8", "rephrase9", "rephrase10"]
for c in column:
example[c] = str(example[c])
else:
example[label_column] = str(example[label_column])
if args.figurepint:
message = numpy.random.randint(0, 2, size=(int(args.message_max_length-4)))
message = torch.tensor(message, dtype=torch.float)
# concate prev_message and message to message_all
message_all = torch.cat([prev_mssage, message], dim=0)
example['message_all'] = message_all.repeat(args.input_max_length, 1)
example['message_base'] = message_all
elif args.adaptive:
if example['generated_word_count'] > 400:
message = numpy.random.randint(0, 2, size=(16))
elif example['generated_word_count'] <= 400 and example['generated_word_count'] >200:
message = numpy.random.randint(0, 2, size=(12))
message = torch.tensor(message, dtype=torch.float)
example['message_all'] = message.repeat(args.input_max_length, 1)
example['message_base'] = message
else:
message = numpy.random.randint(0, 2, size=(args.message_max_length))
message = torch.tensor(message, dtype=torch.float)
example['message_all'] = message.repeat(args.input_max_length, 1)
example['message_base'] = message
return example
def collate_fn(examples):
return tokenizer.pad(examples, padding="longest", return_tensors="pt")
dataset['train'] = dataset['train'].map(str_convert)
print("current dataset length", len(dataset['train']))
train_dataset = dataset['train'].map(
preprocess_function,
batched=True,
num_proc=1,
remove_columns=dataset["train"].column_names,
load_from_cache_file=True,
desc="Running tokenizer on dataset")
train_dataloader = DataLoader(
train_dataset, shuffle=True, collate_fn=collate_fn,
batch_size=batch_size, pin_memory=True)
dataset['validation'] = dataset['validation'].map(str_convert)
val_dataset = dataset['validation'].map(
preprocess_function,
batched=True,
num_proc=1,
remove_columns=dataset["validation"].column_names,
load_from_cache_file=True,
desc="Running tokenizer on dataset",)
val_dataloader = DataLoader(
val_dataset, shuffle=True, collate_fn=collate_fn,
batch_size=batch_size, pin_memory=True)
return train_dataloader, val_dataloader
def modify_probe(probs, mode):
if mode == "delete":
# randomly set one token in the second dimension to 0
index = np.random.randint(0, probs.shape[1], probs.shape[0])
mask = torch.ones_like(probs)
mask[np.arange(probs.shape[0]), index] = 0
probs = probs * mask
return probs
elif mode == "replace":
# randomly set one token in the second dimension to 0
index = np.random.randint(0, probs.shape[1], probs.shape[0])
new_prob = torch.rand(probs.shape[0], probs.shape[2], device=probs.device)
new_prob = new_prob / new_prob.sum(axis=1, keepdims=True)
mask = torch.ones_like(probs)
mask[np.arange(probs.shape[0]), index] = 0
probs_copy = probs.clone()
probs_copy[np.arange(probs.shape[0]), index] = new_prob
probs = probs * mask + probs_copy * (1 - mask)
return probs
elif mode == "add":
index = np.random.randint(0, probs.shape[1], probs.shape[0])
new_prob = torch.rand(probs.shape[0], probs.shape[2], device=probs.device)
new_prob = new_prob / new_prob.sum(axis=1, keepdims=True)
result = torch.zeros_like(probs)
probs_copy = probs.clone()
for i in range(probs.shape[0]):
result[i] = torch.cat([probs_copy[i, :index[i]],
new_prob[i].unsqueeze(0),
probs_copy[i, index[i]:probs.shape[1]-1]])
mask = torch.ones_like(probs)
for i in range(probs.shape[0]):
mask[i, index[i]:] = 0
probs = probs * mask + result * (1 - mask)
return probs