-
Notifications
You must be signed in to change notification settings - Fork 0
/
evaluate_attack.py
149 lines (122 loc) · 5.33 KB
/
evaluate_attack.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
import os
import json
import sys
import argparse
import torch
import copy
from tqdm import tqdm
import config
import wandb
from utils.load_model import load_models
from utils.data_loader import GenericDataLoader
from utils.logging import LoggingHandler
import utils.utils as utils
from utils.utils import model_code_to_qmodel_name, model_code_to_cmodel_name
import utils.load_data as ld
def evaluate_recall(results, qrels, k_values=[10, 20, 50, 100, 500, 1000] ):
cnt = {k: 0 for k in k_values}
for q in results:
sims = list(results[q].items())
sims.sort(key=lambda x: x[1], reverse=True)
gt = qrels[q]
found = 0
for i, (c, _) in enumerate(sims[:max(k_values)]):
if c in gt:
found = 1
if (i + 1) in k_values:
cnt[i + 1] += found
# print(i, c, found)
recall = {}
for k in k_values:
recall[f"Recall@{k}"] = round(cnt[k] / len(results), 5)
return recall
def main():
args= config.parse()
print(args)
wandb.init(
project = "hotflip_attack_perfo",
# track hyperparameters and run metadata
config=vars(args),
)
# Create a subdirectory to store the test results of the attack results
sub_dir = 'results/attack_results/%s/%s-%s' % ( args.method, args.attack_dataset, args.attack_model_code)
# Here is the attack_model_code, record the attack dataset, and then go to the evaluation dataset
if not os.path.exists(sub_dir):
os.makedirs(sub_dir, exist_ok=True)
# Here filename is the file used to save the adversaival documents generated by the test
filename = '%s/%s-%s-k%d-seed%d-num_cand%d-num_iter%d-tokens%d.json'%(sub_dir, args.eval_dataset, args.eval_model_code, args.k, args.seed, args.num_cand, args.num_iter, args.num_adv_passage_tokens)
if os.path.isfile(filename):
return
url = "https://public.ukp.informatik.tu-darmstadt.de/thakur/BEIR/datasets/{}.zip".format(args.eval_dataset)
out_dir = os.path.join(os.getcwd(), "datasets")
data_path = os.path.join(out_dir, args.eval_dataset)
if not os.path.exists(data_path):
data_path = ld.download_and_unzip(url, out_dir)
print(data_path)
data = GenericDataLoader(data_path)
if '-train' in data_path:
args.split = 'train'
corpus, queries, qrels = data.load(split=args.split)
# Load the retrieval results of the beir dataset generated by the embedding_index.py file. Here are all eval_model_code
beir_result_file = f'{args.result_output}/{args.eval_dataset}/{args.eval_model_code}/beir.json'
with open(beir_result_file, 'r') as f:
results = json.load(f)
assert len(qrels) == len(results)
print('Total samples:', len(results))
# Load models
model, c_model, tokenizer,get_emb = load_models(args.eval_model_code)
model.eval()
model.cuda()
c_model.eval()
c_model.cuda()
def evaluate_adv(k, qrels, results):
'''
evaluate adversarial results
:param k: Here k = args.k
:param qrels:
:param results:
:return:
'''
# The first step is to load all attack results according to the parameters.
adv_ps = []
for s in range(k):
file_name = "results/%s-generate/%s/%s/k%d-s%d-seed%d-num_cand%d-num_iter%d-tokens%d-gold_init%s.json" % (
args.method, args.attack_dataset, args.attack_model_code, args.k, s, args.seed, # attack_dataset
args.num_cand,
args.num_iter, args.num_adv_passage_tokens, args.init_gold)
if not os.path.exists(file_name):
print(f"!!!!! {file_name} does not exist!")
continue
attack_results = []
with open(file_name, 'r') as f:
for line in f:
data = json.loads(line)
attack_results.append(data)
adv_ps.append(attack_results[-1])
print('# adversaria passages', len(adv_ps))
adv_results = copy.deepcopy(results)
adv_p_ids = [tokenizer.convert_tokens_to_ids(p["best_adv_text"]) for p in adv_ps]
adv_p_ids = torch.tensor(adv_p_ids).cuda()
adv_attention = torch.ones_like(adv_p_ids, device='cuda')
adv_token_type = torch.zeros_like(adv_p_ids, device='cuda')
adv_input = {'input_ids': adv_p_ids, 'attention_mask': adv_attention, 'token_type_ids': adv_token_type}
with torch.no_grad():
adv_embs = get_emb(c_model, adv_input)
adv_qrels = {q: {"adv%d" % (s): 1 for s in range(k)} for q in qrels}
for i, query_id in tqdm(enumerate(results)):
query_text = queries[query_id]
query_input = tokenizer(query_text, padding=True, truncation=True, return_tensors="pt")
query_input = {key: value.cuda() for key, value in query_input.items()}
with torch.no_grad():
query_emb = get_emb(model, query_input)
adv_sim = torch.mm(query_emb, adv_embs.T)
for s in range(len(adv_ps)):
adv_results[query_id]["adv%d" % (s)] = adv_sim[0][s].cpu().item()
adv_eval = evaluate_recall(adv_results, adv_qrels)
return adv_eval
final_res = evaluate_adv(args.k, qrels, results)
with open(filename, 'w') as f:
json.dump(final_res, f)
print(final_res)
if __name__ == "__main__":
main()