-
Notifications
You must be signed in to change notification settings - Fork 0
/
test-fs-demos.py
254 lines (177 loc) · 7.14 KB
/
test-fs-demos.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
from typing import List, Optional
import fire
import os
from llama import Dialog, Llama
from datasets import load_dataset
import time
import json
def get_store(dir_name, file_name):
store_path = os.path.join(dir_name,file_name)
with open(store_path, 'r') as file:
store = json.load(file)
return store
def get_untested_prompts(prompt_store):
return [prompt for prompt in prompt_store if not prompt['tested']]
def extract_data(dataset_name,example):
if dataset_name=="snli-hard":
premise = example["sentence1"]
hypothesis = example["sentence2"]
else:
premise = example["premise"]
hypothesis = example["hypothesis"]
return premise, hypothesis
def prepare_demonstrations(dataset_name, dataset, demo_indexes):
normal_mappings = {0:"Entailment",1:"Neutral",2:"Contradiction"}
hans_mappings = {0:"Entailment",1:"Non-Entailment",2:"Non-Entailment"}
demos = []
for index in demo_indexes:
demos.append(dataset[index])
for demo in demos:
if dataset_name == "hans":
demo['label'] = hans_mappings[demo['label']]
else:
demo['label'] = normal_mappings[demo['label']]
return demos
def prepare_data(dataset, num_examples, system_prompt, dataset_name, demonstrations):
dialogs = []
few_shot_prompt = ""
for demo in demonstrations:
ex = f"Premise: {demo['premise']}\nHypothesis: {demo['hypothesis']}\nRelationship: {demo['label']}\n \n"
few_shot_prompt = few_shot_prompt + ex
for i, example in enumerate(dataset):
if dataset_name == "snli-hard":
if example['gold_label'] == -1:
continue
else:
if example['label'] == -1:
continue
premise, hypothesis = extract_data(dataset_name,example)
user_prompt = few_shot_prompt + f"Premise: {premise}\nHypothesis: {hypothesis}\nRelationship: "
dialog = [{"role": "system", "content": system_prompt},
{"role": "user", "content": user_prompt}]
dialogs.append(dialog)
# print(system_prompt)
# print(user_prompt)
if i != -1:
if i == num_examples-1:
break
return dialogs
def process_batches(generator, batch_size, dialogs, max_gen_len, temperature, top_p):
results = []
for i in range(0, len(dialogs), batch_size):
batch_dialogs = dialogs[i : i + batch_size]
batch_results = generator.chat_completion(batch_dialogs,
max_gen_len=max_gen_len,
temperature=temperature,
top_p=top_p)
results.extend(batch_results)
return results
def load_model(ckpt_dir, tokenizer_path, max_seq_len, max_batch_size):
generator = Llama.build(ckpt_dir=ckpt_dir,
tokenizer_path=tokenizer_path,
max_seq_len=max_seq_len,
max_batch_size=max_batch_size)
return generator
def main(
ckpt_dir: str,
tokenizer_path: str,
temperature: float = 0.6,
top_p: float = 0.9,
max_seq_len: int = 512,
max_batch_size: int = 4,
max_gen_len: Optional[int] = None,
):
"""
run different prompts and demos and save to file
"""
dataset_test_flags = {
"snli": True,
"snli-hard": True,
"mnli-mm": True,
"mnli-m": True,
"hans": True
}
test_set_paths = {
"snli": ["stanfordnlp/snli", "test"],
"snli-hard": ["au123/snli-hard", "test"],
"mnli-mm": ["nyu-mll/multi_nli", "validation_mismatched"],
"mnli-m": ["nyu-mll/multi_nli", "validation_matched"],
"hans": ["hans","validation"]
}
train_set_paths = {
"snli": ["stanfordnlp/snli", "train"],
"snli-hard": ["stanfordnlp/snli", "train"],
"mnli-mm": ["nyu-mll/multi_nli", "train"],
"mnli-m": ["nyu-mll/multi_nli", "train"],
"hans": ["nyu-mll/multi_nli", "train"]
}
to_test = []
test_sets = {}
train_sets = {}
for dataset_name in dataset_test_flags.keys():
if dataset_test_flags[dataset_name]:
to_test.append(dataset_name)
print("> Loading Test Sets...")
for dataset_name in to_test:
test_sets[dataset_name] = load_dataset(test_set_paths[dataset_name][0],split=test_set_paths[dataset_name][1])
print("> Loading Train Sets...")
for dataset_name in to_test:
train_sets[dataset_name] = load_dataset(train_set_paths[dataset_name][0],split=train_set_paths[dataset_name][1])
print("> Loading Prompts and Demos...")
# get prompts from file
prompt_store = get_store("fs_demos_outputs","fs-prompt-store.json")
untested_prompts = get_untested_prompts(prompt_store)
# get demo indexes from file
demo_store = get_store("fs_demos_outputs","fs-demo-store.json")
print("> Building LLaMA-3-8b-Instruct Model...")
generator = load_model(ckpt_dir, tokenizer_path, max_seq_len, max_batch_size)
print("> Preparing Data and Generating Responses...")
max_gen_len = 3
num_test_examples = -1
num_demonstrations = 3
#########
# final_demos = {
# "snli": 0,
# "snli-hard": 0,
# "mnli-mm": 1,
# "mnli-m": 1,
# "hans": 1
# }
#########
for dataset_name in to_test:
test_set = test_sets[dataset_name]
train_set = train_sets[dataset_name]
for prompt in untested_prompts:
#### CHANGES MADE HERE
# for demo_config in demo_store:
# print(prompt)
demo_config = demo_store[2]
demo_indexes = demo_config[dataset_name]
# if dataset_name == "hans":
# demo_indexes = [11,0,9]
# else:
# demo_indexes = [11,0,9]
#####
demonstrations = prepare_demonstrations(dataset_name, train_set, demo_indexes)
preds_file = demo_config["preds_file"]
preds_file = preds_file.replace('NAME',dataset_name)
preds_file = preds_file.replace('PROMPTNUM',str(prompt["prompt_num"]))
if dataset_name == "hans":
system_prompt = prompt["text_hans"]
else:
system_prompt = prompt["text"]
dialogs = prepare_data(test_set, num_test_examples, system_prompt, dataset_name, demonstrations)
######
dir_name = "fs_baselines"
######
output_path = os.path.join(dir_name,preds_file)
results = process_batches(generator, max_batch_size, dialogs, max_gen_len, temperature, top_p)
# results = [ {'generation':{'content': 'hello'}},{'generation':{'content': 'world'}} ]
with open(output_path, 'w') as file:
for result in results:
file.write(f"{result['generation']['content']}\n")
print("> Process Complete")
if __name__ == "__main__":
start_time = time.time()
fire.Fire(main)
print(f"Script completed in {time.time()-start_time} seconds.")