forked from zhaoxlpku/HKU-DASC7606-A2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
eval_fewshot_multigpu.py
289 lines (232 loc) · 10.5 KB
/
eval_fewshot_multigpu.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
import argparse
import pprint
import os
import copy
from str2bool import str2bool
from typing import Dict, Sequence
from sentence_transformers import SentenceTransformer
IGNORE_INDEX = -100
parser = argparse.ArgumentParser()
parser.add_argument('--data_path', type=str, default="")
parser.add_argument('--device_id', type=str, default="")
parser.add_argument('--model', type=str, default='', help="")
parser.add_argument('--embedder', type=str, default="", help="")
parser.add_argument('--output_path', type=str, help="")
parser.add_argument('--start_index', type=int, default=0, help="")
parser.add_argument('--end_index', type=int, default=164, help="")
parser.add_argument('--N', type=int, default=8, help="")
parser.add_argument('--max_len', type=int, default=512, help="")
parser.add_argument('--overwrite', type=str2bool, default=False, help="")
parser.add_argument('--prompt_type', type=str, default="v1.0", help="")
parser.add_argument('--top_k', type=str2bool, default=False, help="")
parser.add_argument('--top_k_reverse', type=str2bool, default=False, help="")
args = parser.parse_args()
os.environ['CUDA_VISIBLE_DEVICES'] = str(args.device_id)
from tqdm import tqdm
import torch
import json
import transformers
from modeling_phi import PhiForCausalLM
from configuration_phi import PhiConfig
from tokenization_codegen import CodeGenTokenizer
from accelerate import init_empty_weights, infer_auto_device_map
if torch.cuda.is_available():
device = "cuda"
else:
device = "cpu"
def get_arc_problems(data_path="data/ARC-Easy-test.jsonl"):
dataset = []
with open(data_path, encoding="utf-8") as f:
for line in f.readlines():
json_obj = json.loads(line)
candidate_answers = " ".join([f"({label}) {text}" for text, label in zip(json_obj["choices"]["text"], json_obj["choices"]["label"])]).strip()
for text, label in zip(json_obj["choices"]["text"], json_obj["choices"]["label"]):
dataset.append({
"id": json_obj["id"],
"question": json_obj["question"],
"candidate_answers": candidate_answers,
"answer": text,
"label": label,
"answerKey": json_obj["answerKey"],
})
return dataset
def load_all_demonstrations(train_path="data/ARC-Challenge-train.jsonl"):
demonstrations = []
with open(train_path, encoding="utf-8") as f:
for line in f.readlines():
json_obj = json.loads(line)
demonstrations.append((json_obj["question"], json_obj["choices"]["text"], json_obj["choices"]["label"], json_obj["answerKey"]))
print(f"load {len(demonstrations)} demonstrations from {train_path}")
return demonstrations
def llm_embedder(llm, sentences, is_query=True):
INSTRUCTIONS = {
"qa": {
"query": "Represent this query for retrieving relevant documents: ",
"key": "Represent this document for retrieval: ",
},
"icl": {
"query": "Convert this example into vector to look for useful examples: ",
"key": "Convert this example into vector for retrieval: ",
},
"chat": {
"query": "Embed this dialogue to find useful historical dialogues: ",
"key": "Embed this historical dialogue for retrieval: ",
},
"lrlm": {
"query": "Embed this text chunk for finding useful historical chunks: ",
"key": "Embed this historical text chunk for retrieval: ",
},
"tool": {
"query": "Transform this user request for fetching helpful tool descriptions: ",
"key": "Transform this tool description for retrieval: "
},
"convsearch": {
"query": "Encode this query and context for searching relevant passages: ",
"key": "Encode this passage for retrieval: ",
},
}
instruction = INSTRUCTIONS["icl"]
if is_query:
sentences = [instruction["query"] + s for s in sentences]
else:
sentences = [instruction["key"] + s for s in sentences]
# Encode
sentence_embeddings = llm.encode(sentences)
return sentence_embeddings
def candidate_answers_formating(texts, labels):
candidate_answers = " ".join([f"({label}) {text}" for text, label in zip(texts, labels)]).strip()
return candidate_answers
# task 4
def example_formating(question, answer=None, candidate_answers=None, prompt_type="v2.0"):
if prompt_type == "v1.0":
if answer is not None:
prompt = f"Question: {question}\nCandidate answers: {candidate_answers}\nGold answer: {answer}"
else:
prompt = f"Question: {question}\nCandidate answers: {candidate_answers}\nGold answer:"
elif prompt_type == "v2.0":
if answer is not None:
prompt = "Write Your Code Here"
else:
prompt = "Write Your Code Here"
else:
raise NotImplementedError
return prompt
def generate_prompt(question, candidate_answers, prompt_type, N,
demonstrations, demonstration_embeddings, embedder,
top_k=False, top_k_reverse=False):
indices = list(range(len(demonstrations)))
if top_k: # task 5
question_embeddings = llm_embedder(embedder, [question], True) # [1, n_dim]
similarity = "Write Your Code Here" @ "Write Your Code Here" # [1, n_demo]
indices_sorted = sorted(list(range(len(demonstrations))), key=lambda x: similarity[0][x], reverse=True)
if top_k_reverse:
indices = indices_sorted[:N][::-1] + indices_sorted[N:]
else:
indices = indices_sorted
template = ""
for idx in indices[:N]:
demo = demonstrations[idx]
candidate = candidate_answers_formating(demo[1], demo[2])
gold = demo[1][demo[2].index(demo[3])]
template += f"\n\n{example_formating(demo[0], answer=gold, candidate_answers=candidate, prompt_type=prompt_type)}"
template += f"\n\n{example_formating(question, candidate_answers=candidate_answers, prompt_type=prompt_type)}"
return template.strip()
def get_model(
base_model: str = "bigcode/starcoder",
):
assert base_model, (
"Please specify a --base_model, e.g. --base_model='bigcode/starcoder'"
)
tokenizer = CodeGenTokenizer.from_pretrained(base_model)
tokenizer.pad_token_id = tokenizer.eos_token_id
tokenizer.pad_token = tokenizer.eos_token
n_gpus = torch.cuda.device_count()
memory = '4GiB' # adjust this value to ensure that the whole model could be loaded
no_split_module_classes = PhiForCausalLM._no_split_modules
max_memory = {int(cuda): memory for cuda in range(n_gpus)}
config = PhiConfig.from_pretrained(base_model)
with init_empty_weights():
model = PhiForCausalLM._from_config(config)
device_map = infer_auto_device_map(model, max_memory=max_memory, no_split_module_classes=no_split_module_classes)
model = PhiForCausalLM.from_pretrained(base_model, device_map=device_map)
model.config.pad_token_id = tokenizer.pad_token_id
model.eval()
return tokenizer, model
def _tokenize_fn(strings: Sequence[str], tokenizer: transformers.PreTrainedTokenizer) -> Dict:
"""Tokenize a list of strings."""
tokenized_list = [
tokenizer(
text,
return_tensors="pt",
padding="longest",
max_length=args.max_len,
truncation=True,
)
for text in strings
]
input_ids = labels = [tokenized.input_ids[0] for tokenized in tokenized_list]
input_ids_lens = labels_lens = [
tokenized.input_ids.ne(tokenizer.pad_token_id).sum().item() for tokenized in tokenized_list
]
return dict(
input_ids=input_ids,
labels=labels,
input_ids_lens=input_ids_lens,
labels_lens=labels_lens,
)
def preprocess(
sources: Sequence[str],
targets: Sequence[str],
tokenizer: transformers.PreTrainedTokenizer,
) -> Dict:
"""Preprocess the data by tokenizing."""
examples = [s + t for s, t in zip(sources, targets)]
examples_tokenized, sources_tokenized = [_tokenize_fn(strings, tokenizer) for strings in (examples, sources)]
input_ids = examples_tokenized["input_ids"]
labels = copy.deepcopy(input_ids)
for label, source_len in zip(labels, sources_tokenized["input_ids_lens"]):
label[:source_len] = IGNORE_INDEX
return dict(input_ids=torch.stack(input_ids).to(device), labels=torch.stack(labels).to(device))
def main():
argsdict = vars(args)
print(pprint.pformat(argsdict))
problems = get_arc_problems(args.data_path)[args.start_index: args.end_index]
num_samples = len(problems)
tokenizer, model = get_model(base_model=args.model)
print(f"Loaded {args.model}.")
embedder = SentenceTransformer(args.embedder, device=device)
print(f"loaded {args.embedder}.")
demonstrations = load_all_demonstrations(args.data_path.replace("test", "train").replace("validation", "train"))
demonstration_embeddings = llm_embedder(embedder, [d[0] for d in demonstrations], False) # ndarray: [n_demons, n_dim]
for i in tqdm(range(num_samples), ncols=0, total=num_samples):
output_file = args.output_path + '/{}.jsonl'.format(args.start_index + i)
if os.path.exists(output_file) and not args.overwrite:
print(f'Skip {output_file} as it already exists')
continue
question = problems[i]["question"]
answer = problems[i]["answer"]
candidate_answers = problems[i]["candidate_answers"]
source = generate_prompt(question, candidate_answers, args.prompt_type, args.N,
demonstrations, demonstration_embeddings, embedder,
top_k=args.top_k, top_k_reverse=args.top_k_reverse)
if i == 0:
print(f"prompt #{i}: {source}")
target = " {}".format(answer)
encoding = preprocess([source], [target], tokenizer)
with torch.no_grad():
# task 6
outputs = model("Write Your Code Here")
log_likelihood = "Write Your Code Here"
print("Saving results to {}".format(output_file))
with open(output_file, "w", encoding="utf-8") as f:
f.write(json.dumps({
"id": problems[i]["id"],
"log_likelihood": log_likelihood.tolist(),
"question": question,
"candidate_answers": candidate_answers,
"answer": answer,
"label": problems[i]["label"],
"answerKey": problems[i]["answerKey"],
}) + "\n")
if __name__ == '__main__':
main()