-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
146 lines (131 loc) · 4.74 KB
/
main.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
import argparse
import json
import os
import time
import torch
from transformers import (AutoConfig, AutoModelForMaskedLM, AutoModelForSequenceClassification,
AutoTokenizer)
from utils.dataprocessor import DataProcessor, YNATProcessor, NSMCProcessor
from utils import attack
from utils.attack import run_attack
from utils.attack_original import run_attack as original_run_attack
def dump_features(args, features, output_dir):
output_file = f"{args.output_file}.json"
outputs = []
for feature in features:
outputs.append(
{
"success_indication": feature.success_indication,
"target_sequence": feature.first_seq,
"num_tokens": len(feature.first_seq.split(" ")),
"original_label": feature.label_id,
"change_label": feature.final_label if feature.final_label else feature.label_id ,
"query_length": feature.query_length,
"num_changes": feature.num_changes,
"changes": feature.changes,
"attacked_text": feature.final_text,
}
)
json.dump(
outputs,
open(os.path.join(output_dir, output_file), "w"),
indent=4,
ensure_ascii=False,
)
print("Finished dump")
def calculate_accuracy(features):
total = len(features)
cnt_pred_fail = 0
cnt_success = 0
for feature in features:
if feature.success_indication == "Predict fail":
cnt_pred_fail += 1
if feature.success_indication == "Attack success":
cnt_success += 1
orig_acc = (1 - cnt_pred_fail / total) * 100
attack_acc = orig_acc - (cnt_success / total * 100)
print(f'original accuarcy : {orig_acc}')
print(f'attacked accuarcy : {attack_acc}')
def add_general_args(
parser: argparse.ArgumentParser, root_dir: str
) -> argparse.ArgumentParser:
# Required parameters
parser.add_argument(
"--input-dir",
default=None,
type=str,
required=True,
help="The input data path. Should contain the .json files (or other data files) for the task.",
)
parser.add_argument(
"--output-dir",
default=None,
type=str,
required=True,
help="The output directory where the model predictions and checkpoints will be written.",
)
parser.add_argument(
"--output-file",
type=str,
required=True,
help="File name for output result",
)
parser.add_argument(
"--finetuned-model-path",
type=str,
required=True,
help="Path for finetnued model",
)
parser.add_argument(
"--dataset",
default="YNAT",
type=str,
help="Target dataset name",
)
parser.add_argument(
"--run-wordwise-legacy",
action='store_true',
help="If True then Attack with white space wise otherwise Attack with subword wise",
)
return parser
def main():
parser = argparse.ArgumentParser()
parser = add_general_args(parser, os.getcwd())
parser = DataProcessor.add_specific_args(parser, os.getcwd())
parser = attack.add_specific_args(parser, os.getcwd())
args = parser.parse_args()
model_name = "klue/bert-base"
tokenizer = AutoTokenizer.from_pretrained(model_name)
if args.dataset == "NSMC" or args.dataset == "nsmc":
processor = NSMCProcessor(args, tokenizer)
else:
processor = YNATProcessor(args, tokenizer)
target_examples = processor.get_dev_data(args.input_dir)
target_features = processor.get_features(target_examples)
num_labels = len(processor.get_labels())
pretrained_config = AutoConfig.from_pretrained(model_name)
pretrained_model = AutoModelForMaskedLM.from_pretrained(
model_name, config=pretrained_config
)
pretrained_model.to("cuda")
finetuned_model = AutoModelForSequenceClassification.from_pretrained(model_name,num_labels=num_labels)
finetuned_model.to("cuda")
model_state, _ = torch.load(args.finetuned_model_path)
finetuned_model.load_state_dict(model_state, strict=False)
start = time.time()
output_features = []
for example, feature in zip(target_examples, target_features):
if args.run_wordwise_legacy:
output = original_run_attack(
args, processor, example, feature, pretrained_model, finetuned_model
)
else:
output = run_attack(
args, processor, example, feature, pretrained_model, finetuned_model
)
output_features.append(output)
print('Total execution time : ', time.time()-start)
calculate_accuracy(output_features)
dump_features(args, output_features, args.output_dir)
if __name__ == "__main__":
main()