-
Notifications
You must be signed in to change notification settings - Fork 27
/
dataloader.py
336 lines (275 loc) · 16.7 KB
/
dataloader.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
import torch
from torch import nn
from transformers import Trainer
import torch.nn.functional as F
import copy, os
import deepspeed
from evaluate_util import get_dataloader, get_all_evals
import copy
import json
from pathlib import Path
from data_module import get_batch_loss
from utils import merge_dicts, interleave_eval_result_dict, get_forget_quality, get_model_utility
import numpy as np
from scipy.stats import ks_2samp, hmean
import csv
from transformers.integrations.deepspeed import deepspeed_init, deepspeed_load_checkpoint, is_deepspeed_available
def printll(name, inp):
#print list with 4 decimal for each item
print(name, [round(x, 4) for x in inp])
class CustomTrainer(Trainer):
def compute_loss(self, model, inputs, return_outputs=False):
input_ids, labels, attention_mask = inputs
# forward pass
outputs = model(input_ids,labels=labels, attention_mask=attention_mask)
# logits = outputs.get("logits")
loss = outputs.loss
# # compute custom loss (suppose one has 3 labels with different weights)
# loss_fct = nn.CrossEntropyLoss(weight=torch.tensor([1.0, 2.0, 3.0], device=model.device))
# loss = loss_fct(logits.view(-1, self.model.config.num_labels), labels.view(-1))
return (loss, outputs) if return_outputs else loss
def prediction_step(self, model, inputs, prediction_loss_only: bool, ignore_keys=None):
input_ids, labels, attention_mask = inputs
# forward pass
with torch.no_grad():
outputs = model(input_ids,labels=labels, attention_mask=attention_mask)
logits = outputs.logits
loss = outputs.loss
return (loss, logits, labels)
class CustomTrainerForgetting(Trainer):
def __init__(self, *args, **kwargs):
self.loss_type = kwargs.pop('forget_loss')
self.oracle_model = kwargs.pop('oracle_model')
self.eval_cfg = kwargs.pop('eval_cfg')
super(CustomTrainerForgetting, self).__init__(*args, **kwargs)
if self.loss_type == "KL":
self.oracle_model = self.e_prepare_deepspeed(self.oracle_model)
def e_prepare_deepspeed(self, model):
# Adapted from accelerate: https://github.com/huggingface/accelerate/blob/739b135f8367becb67ffaada12fe76e3aa60fefd/src/accelerate/accelerator.py#L1473
deepspeed_plugin = self.accelerator.state.deepspeed_plugin
config_kwargs = copy.deepcopy(deepspeed_plugin.deepspeed_config)
if model is not None:
if hasattr(model, "config"):
hidden_size = (
max(model.config.hidden_sizes)
if getattr(model.config, "hidden_sizes", None)
else getattr(model.config, "hidden_size", None)
)
if hidden_size is not None and config_kwargs["zero_optimization"]["stage"] == 3:
# Note that `stage3_prefetch_bucket_size` can produce DeepSpeed messages like: `Invalidate trace cache @ step 0: expected module 1, but got module 0`
# This is expected and is not an error, see: https://github.com/microsoft/DeepSpeed/discussions/4081
config_kwargs.update(
{
"zero_optimization.reduce_bucket_size": hidden_size * hidden_size,
"zero_optimization.stage3_param_persistence_threshold": 10 * hidden_size,
"zero_optimization.stage3_prefetch_bucket_size": 0.9 * hidden_size * hidden_size,
}
)
# If ZeRO-3 is used, we shard both the active and reference model.
# Otherwise, we assume the reference model fits in memory and is initialized on each device with ZeRO disabled (stage 0)
if config_kwargs["zero_optimization"]["stage"] != 3:
config_kwargs["zero_optimization"]["stage"] = 0
config_kwargs["optimizer"] = {"type": None}
model, *_ = deepspeed.initialize(model=model, config=config_kwargs)
model.eval()
#set the gradients to false for every parameter
for param in model.parameters():
param.requires_grad = False
return model
def compute_loss(self, model, inputs, return_outputs=False):
if self.loss_type == "grad_ascent":
forget_inputs, retain_inputs = inputs
input_ids, labels, attention_mask = forget_inputs
outputs = model(input_ids,labels=labels, attention_mask=attention_mask)
forget_loss = outputs.loss
forget_loss = forget_loss * -1
loss = forget_loss
elif self.loss_type == "grad_diff":
forget_inputs, retain_inputs = inputs
input_ids, labels, attention_mask = forget_inputs
outputs = model(input_ids,labels=labels, attention_mask=attention_mask)
forget_loss = outputs.loss
forget_loss = forget_loss * -1
retain_input_ids, retain_labels, retain_attention_mask = retain_inputs
retain_outputs = model(retain_input_ids,labels=retain_labels, attention_mask=retain_attention_mask)
retain_loss = retain_outputs.loss
loss = forget_loss + retain_loss
elif self.loss_type == "KL":
forget_inputs, retain_inputs = inputs
input_ids, labels, attention_mask = forget_inputs
outputs = model(input_ids,labels=labels, attention_mask=attention_mask)
forget_loss = outputs.loss
forget_loss = forget_loss * -1
retain_input_ids, retain_labels, retain_attention_mask = retain_inputs
with torch.no_grad():
retain_outputs = self.oracle_model(retain_input_ids,labels=retain_labels, attention_mask=retain_attention_mask)
retain_probs = F.log_softmax(retain_outputs.logits, dim=-1)
retain_probs = retain_probs.view(-1, retain_outputs.logits.shape[-1])
current_outputs = model(retain_input_ids,labels=retain_labels, attention_mask=retain_attention_mask)
current_probs = F.log_softmax(current_outputs.logits, dim=-1)
current_probs = current_probs.view(-1, current_outputs.logits.shape[-1])
#minimum KL divergence
retain_loss = nn.functional.kl_div(current_probs, retain_probs, reduction='batchmean', log_target=True)
loss = forget_loss + retain_loss
elif self.loss_type == "idk":
idk_inputs, retain_inputs = inputs
idk_input_ids, idk_labels, idk_attention_mask = idk_inputs
retain_input_ids, retain_labels, retain_attention_mask = retain_inputs
#concatenate the inputs. single forward pass is much more efficient
input_ids = torch.cat((idk_input_ids, retain_input_ids), dim=0)
labels = torch.cat((idk_labels, retain_labels), dim=0)
attention_mask = torch.cat((idk_attention_mask, retain_attention_mask), dim=0)
outputs = model(input_ids,labels=labels, attention_mask=attention_mask)
loss = outputs.loss
elif self.loss_type == "dpo":
idk_inputs, forget_inputs, retain_inputs = inputs
idk_input_ids, idk_labels, idk_attention_mask = idk_inputs
forget_input_ids, forget_labels, forget_attention_mask = forget_inputs
idk_outputs = model(idk_input_ids,labels=idk_labels, attention_mask=idk_attention_mask)
forget_outputs = model(forget_input_ids,labels=forget_labels, attention_mask=forget_attention_mask)
with torch.no_grad():
idk_outputs_oracle = self.oracle_model(idk_input_ids,labels=idk_labels, attention_mask=idk_attention_mask)
forget_outputs_oracle = self.oracle_model(forget_input_ids,labels=forget_labels, attention_mask=forget_attention_mask)
idk_logits_oracle = idk_outputs_oracle.logits
forget_logits_oracle = forget_outputs_oracle.logits
idk_loss_oracle = -1 * get_batch_loss(idk_logits_oracle, idk_labels)
forget_loss_oracle = -1 * get_batch_loss(forget_logits_oracle, labels)
idk_loss_current = -1 * get_batch_loss(idk_outputs.logits, idk_labels)
forget_loss_current = -1 * get_batch_loss(forget_outputs.logits, labels)
pi_logratios = idk_loss_current - forget_loss_current
ref_logratios = idk_loss_oracle - forget_loss_oracle
beta = 0.1
loss = -F.logsigmoid(beta * (pi_logratios - ref_logratios)).mean()
outputs = forget_outputs
return (loss, outputs) if return_outputs else loss
def prediction_step(self, model, inputs, prediction_loss_only: bool, ignore_keys=None):
input_ids, labels, attention_mask = inputs
# forward pass
with torch.no_grad():
outputs = model(input_ids,labels=labels, attention_mask=attention_mask)
logits = outputs.logits
loss = outputs.loss
return (loss, logits, labels)
def evaluate(
self,
eval_dataset = None,
ignore_keys = None,
metric_key_prefix = "eval",
):
# if eval is called w/o train, handle model prep here
if self.is_deepspeed_enabled and self.deepspeed is None:
_, _ = deepspeed_init(self, num_training_steps=0, inference=True)
args = self.args
model = self._wrap_model(self.model, training=False, dataloader=None)
print(self.is_in_train, args.device, model.dtype, self.args.dataloader_num_workers, self.eval_cfg.split_list, self.eval_cfg.split)
if len(self.accelerator._models) == 0 and model is self.model:
model = (
self.accelerator.prepare(model)
if self.is_deepspeed_enabled
else self.accelerator.prepare_model(model, evaluation_mode=True)
)
if self.is_fsdp_enabled:
self.model = model
# for the rest of this function `model` is the outside model, whether it was wrapped or not
if model is not self.model:
self.model_wrapped = model
# backward compatibility
if self.is_deepspeed_enabled:
self.deepspeed = self.model_wrapped
# if full fp16 or bf16 eval is wanted and this ``evaluation`` or ``predict`` isn't called
# while ``train`` is running, cast it to the right dtype first and then put on device
if not self.is_in_train:
if args.fp16_full_eval:
model = model.to(dtype=torch.float16, device=args.device)
elif args.bf16_full_eval:
model = model.to(dtype=torch.bfloat16, device=args.device)
model.eval()
curr_step = self.state.global_step
eval_cfg = self.eval_cfg
curr_save_dir = os.path.join(eval_cfg.save_dir, f"checkpoint-{curr_step}")
Path(curr_save_dir).mkdir(parents=True, exist_ok=True)
forget_rate = eval_cfg.split.split('_')[0]
with torch.no_grad():
for i, (folder, split, question_key, answer_key, eval_task, base_answer_key, perturbed_answer_key) in enumerate(zip(eval_cfg.data_path, eval_cfg.split_list, eval_cfg.question_key, eval_cfg.answer_key, eval_cfg.eval_task, eval_cfg.base_answer_key, eval_cfg.perturbed_answer_key)):
world_size = self.accelerator.num_processes
# For some reason, Hydra is not interprating the split correctly
if eval_task == 'eval_log_forget':
split = eval_cfg.split
print(f'Working on eval task {eval_task} with split {split}')
save_filename = os.path.join(curr_save_dir, f"{eval_task}.json")
save_filename = save_filename if world_size == 1 else os.path.join(curr_save_dir, f"{eval_task}_{self.accelerator.local_process_index}.json")
# print(save_filename)
if os.path.exists(save_filename) and not eval_cfg.overwrite:
print(f"Skipping {eval_task} because {save_filename} already exists")
continue
eval_dataloader, base_eval_dataloader, perturb_dataloader = get_dataloader(eval_cfg, eval_task, self.tokenizer, folder, split, question_key, answer_key, base_answer_key, perturbed_answer_key)
eval_dataloader = self.accelerator.prepare(eval_dataloader)
# print('dataset condition: ', len(eval_dataloader.dataset), self.accelerator.local_process_index)
base_eval_dataloader = self.accelerator.prepare(base_eval_dataloader)
perturb_dataloader = self.accelerator.prepare(perturb_dataloader)
normalize_gt = False
# if 'eval_log' not in eval_task:
# normalize_gt = True
eval_logs = get_all_evals(eval_cfg, model, self.tokenizer, eval_task, eval_dataloader, base_eval_dataloader, perturb_dataloader, normalize_gt=normalize_gt)
with open(save_filename, "w") as f:
# pretty write json to f
json.dump(eval_logs, f, indent=4)
#wait for all process to finish
self.accelerator.wait_for_everyone()
aggregated_eval_logs = {}
for eval_task in eval_cfg.eval_task:
#read the saved file as json and merge them using merge_dicts
if world_size > 1:
if self.accelerator.is_local_main_process:
eval_logs = json.load(open(os.path.join(curr_save_dir, f"{eval_task}_0.json")))
for i in range(1, world_size):
filename = os.path.join(curr_save_dir, f"{eval_task}_{i}.json")
eval_logs = merge_dicts(eval_logs, json.load(open(filename)))
aggregated_eval_logs[f'{eval_task}.json'] = eval_logs
new_save_filename = os.path.join(curr_save_dir, f"{eval_task}.json")
with open(new_save_filename, "w") as f:
# pretty write json to f
json.dump(eval_logs, f, indent=4)
#delete old files use shutil
for i in range(world_size):
filename = os.path.join(curr_save_dir, f"{eval_task}_{i}.json")
os.remove(filename)
if self.accelerator.is_local_main_process:
# aggregated_eval_logs = interleave_eval_result_dict(aggregated_eval_logs, forget_rate, large_bsz=eval_cfg.batch_size, num_processes=world_size)
aggregated_eval_log_filename = os.path.join(curr_save_dir, "eval_log_aggregated.json")
with open(aggregated_eval_log_filename, 'w') as f:
json.dump(aggregated_eval_logs, f, indent=4)
if eval_cfg.retain_result is not None:
model_utility = get_model_utility(aggregated_eval_logs)
retain_result = json.load(open(eval_cfg.retain_result, 'r'))
forget_quality = get_forget_quality(aggregated_eval_logs, retain_result)
aggregate_stat = {**model_utility, **forget_quality}
# save aggregate_stat as csv
with open(os.path.join(curr_save_dir, "aggregate_stat.csv"), 'w') as csvfile:
field_names = list(aggregate_stat.keys())
writer = csv.DictWriter(csvfile, fieldnames=field_names)
writer.writeheader()
writer.writerow(aggregate_stat)
def custom_data_collator_forget(samples):
forget_samples, retain_samples = [sample[0] for sample in samples], [sample[1] for sample in samples]
rets = []
for data_type in ["forget", "retain"]:
data = forget_samples if data_type == "forget" else retain_samples
input_ids = [s[0] for s in data]
labels = [s[1] for s in data]
attention_mask = [s[2] for s in data]
rets.append((torch.stack(input_ids), torch.stack(labels), torch.stack(attention_mask)))
return rets
def compute_metrics(pred):
logits, labels = torch.from_numpy(pred.predictions), torch.from_numpy(pred.label_ids)
preds = torch.from_numpy(pred.predictions.argmax(-1))
shifted_labels = labels[..., 1:].contiguous()
acc = torch.mean((preds[..., :-1] == shifted_labels).float())
loss = get_loss(logits, labels)
return {"eval accuracy": acc, "eval loss": loss.item()}
def get_loss(output, labels):
shifted_labels = labels[..., 1:].contiguous()
output = output[..., :-1, :].contiguous()
loss_function = nn.CrossEntropyLoss(ignore_index=-100)
loss = loss_function(output.view(-1, output.size(-1)), shifted_labels.view(-1))
return loss