forked from zjunlp/EasyEdit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsafety.py
230 lines (193 loc) · 7.52 KB
/
safety.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
import json
from pathlib import Path
import torch
from torch.utils.data import Dataset
import typing
import transformers
from transformers import GPT2Tokenizer, GPT2TokenizerFast, LlamaTokenizer
from ..util.globals import *
from ..trainer.utils import dict_to
class SafetyDataset(Dataset):
"""
Dataset of SafeEdit
"""
def __init__(self, data_dir: str, size: typing.Optional[int] = None, config=None, *args, **kwargs):
data_dir = Path(data_dir)
unsafety_loc = data_dir
if(config is not None):
self.config = config
if(config is not None and hasattr(config, 'max_length')):
self.max_length = config.max_length
else:
self.max_length = 1000
if(config is not None and hasattr(config, 'tokenizer_name')):
tok_name = (
config.tokenizer_name
if config.tokenizer_name is not None
else config.model.name
)
tokenizer = getattr(transformers, config.tokenizer_class).from_pretrained(
tok_name
)
if isinstance(tokenizer, GPT2Tokenizer) or isinstance(tokenizer, GPT2TokenizerFast):
tokenizer.pad_token_id = tokenizer.eos_token_id
tokenizer.padding_side = 'left'
print('GPTTokenizer Detected, Set pad token id and left padding!!!')
elif isinstance(tokenizer, LlamaTokenizer):
tokenizer.pad_token_id = tokenizer.eos_token_id
tokenizer.padding_side = 'left'
print('LlamaTokenizer Detected, Set pad token id and left padding!!!')
self.tok = tokenizer
with open(unsafety_loc, "r") as f:
raw = json.load(f)
data = []
for i, record in enumerate(raw):
data.append(
{
"case_id": record["id"],
"category": record["unsafety category"],
"question": record["question"],
"prompt": record["adversarial prompt"],
"target_new": record["safe generation"],
"ground_truth": record["unsafe generation"],
"locality_prompt": record["knowledge constrain"]["prompt"],
"locality_ground_truth": record["knowledge constrain"]["answer"],
"cond": "{} >> {} || {}".format(
record["unsafe generation"],
record["safe generation"],
record["adversarial prompt"],
),
}
)
if "generalization test" in record.keys():
data[-1]["general_prompt"] = [
record["generalization test"]["test input of only harmful question"],
record["generalization test"]["test input of other attack prompt input"],
record["generalization test"]["test input of other question input"],
record["generalization test"]["test input of other questions and attack prompts"],
]
if size is not None:
data = data[:size]
self._data = data
def __getitem__(self, item):
return self._data[item]
def __len__(self):
return len(self._data)
def get_edit_labels(self, labels):
return labels.masked_fill(labels == self.tok.pad_token_id, -100)
def collate_fn(self, batch):
src = [b["prompt"] for b in batch]
trg = [b["target_new"] for b in batch]
cond = [b["cond"] for b in batch]
loc = [b["locality_prompt"] for b in batch]
loc_ans = [b["locality_ground_truth"] for b in batch]
src = [src_ + trg_ for src_, trg_ in zip(src, trg)]
loc = [loc_ + loc_ans_ for loc_, loc_ans_ in zip(loc, loc_ans)]
batches = {
f"{k1}_{k2}": v2
for k1, v1 in {
"src": src,
"trg": trg,
"cond": cond,
}.items()
for k2, v2 in self.tok(
v1,
return_tensors="pt",
padding=True,
max_length=self.max_length,
truncation=True,
).items()
}
# edit_inner
edit_inner = {}
edit_inner["input_ids"] = batches["src_input_ids"]
edit_inner["attention_mask"] = batches["src_attention_mask"]
edit_labels = self.get_edit_labels(batches["trg_input_ids"])
edit_inner["labels"] = edit_labels
# loc
loc = dict(
self.tok(
loc,
return_tensors="pt",
padding=True,
max_length=self.max_length,
truncation=True,
)
)
loc_ans = dict(
self.tok(
loc_ans,
return_tensors="pt",
padding=True,
max_length=self.max_length,
truncation=True,
)
)
loc["decoder_attention_mask"] = loc_ans["attention_mask"]
loc["labels"] = self.get_edit_labels(loc_ans["input_ids"])
# portability TODO
cond = {k[5:]: v for k, v in batches.items() if k.startswith("cond")}
batch = {
"edit_inner": edit_inner,
"loc": loc,
"cond": cond,
"raw": batch,
}
return dict_to(batch, self.config.device)
def collate_gpt_fn(self, batch):
src = [b["prompt"] for b in batch]
trg = [b["target_new"] for b in batch]
cond = [b["cond"] for b in batch]
loc = [b["locality_prompt"] for b in batch]
loc_ans = [b["locality_ground_truth"] for b in batch]
src = [src_ + trg_ for src_, trg_ in zip(src, trg)]
loc = [loc_ + loc_ans_ for loc_, loc_ans_ in zip(loc, loc_ans)]
batches = {
f"{k1}_{k2}": v2
for k1, v1 in {
"src": src,
"trg": trg,
"cond": cond,
}.items()
for k2, v2 in self.tok(
v1,
return_tensors="pt",
padding=True,
max_length=self.max_length,
truncation=True,
).items()
}
# edit_inner
edit_inner = {}
edit_inner["input_ids"] = batches["src_input_ids"]
edit_inner["attention_mask"] = batches["src_attention_mask"]
edit_labels = self.get_edit_labels(batches["trg_input_ids"])
edit_inner["labels"] = edit_labels
# loc
loc = dict(
self.tok(
loc,
return_tensors="pt",
padding=True,
max_length=self.max_length,
truncation=True,
)
)
loc_ans = dict(
self.tok(
loc_ans,
return_tensors="pt",
padding=True,
max_length=self.max_length,
truncation=True,
)
)
loc["decoder_attention_mask"] = loc_ans["attention_mask"]
loc["labels"] = self.get_edit_labels(loc_ans["input_ids"])
# portability TODO
cond = {k[5:]: v for k, v in batches.items() if k.startswith("cond")}
batch = {
"edit_inner": edit_inner,
"loc": loc,
}
return dict_to(batch, self.config.device)