1: import os
2: from datasets import load_dataset
3: import torch
4: import json
5: from transformers import AutoTokenizer, LlamaTokenizer, LlamaForCausalLM, AutoModelForCausalLM
6: from tqdm import tqdm
7: import numpy as np
8: import random
9: import argparse
10: import torch.distributed as dist
11: import torch.multiprocessing as mp
12: from flexible_quant.flexible_quantized_cache import FlexibleQuantizedCacheConfig, FlexibleHQQQuantizedCache, FlexibleVanillaQuantizedCache
13: 
14: dataset2prompt = {
15:     "narrativeqa": "You are given a story, which can be either a novel or a movie script, and a question. Answer the question asconcisely as you can, using a single phrase if possible. Do not provide any explanation.\n\nStory: {context}\n\nNow, answer the question based on the story asconcisely as you can, using a single phrase if possible. Do not provide any explanation.\n\nQuestion: {input}\n\nAnswer:",
16:     "qasper": "You are given a scientific article and a question. Answer the question as concisely as you can, using a single phrase or sentence if possible. If the question cannot be answered based on the information in the article, write \"unanswerable\". If the question is a yes/no question, answer \"yes\", \"no\", or \"unanswerable\". Do not provide any explanation.\n\nArticle: {context}\n\n Answer the question based on the above article as concisely as you can, using a single phrase or sentence if possible. If the question cannot be answered based on the information in the article, write \"unanswerable\". If the question is a yes/no question, answer \"yes\", \"no\", or \"unanswerable\". Do not provide any explanation.\n\nQuestion: {input}\n\nAnswer:",
17:     "multifieldqa_en": "Read the following text and answer briefly.\n\n{context}\n\nNow, answer the following question based on the above text, only give me the answer and do not output any other words.\n\nQuestion: {input}\nAnswer:",
18:     "multifieldqa_zh": "阅读以下文字并用中文简短回答：\n\n{context}\n\n现在请基于上面的文章回答下面的问题，只告诉我答案，不要输出任何其他字词。\n\n问题：{input}\n回答：",
19:     "hotpotqa": "Answer the question based on the given passages. Only give me the answer and do not output any other words.\n\nThe following are given passages.\n{context}\n\nAnswer the question based on the given passages. Only give me the answer and do not output any other words.\n\nQuestion: {input}\nAnswer:",
20:     "2wikimqa": "Answer the question based on the given passages. Only give me the answer and do not output any other words.\n\nThe following are given passages.\n{context}\n\nAnswer the question based on the given passages. Only give me the answer and do not output any other words.\n\nQuestion: {input}\nAnswer:",
21:     "musique": "Answer the question based on the given passages. Only give me the answer and do not output any other words.\n\nThe following are given passages.\n{context}\n\nAnswer the question based on the given passages. Only give me the answer and do not output any other words.\n\nQuestion: {input}\nAnswer:",
22:     "dureader": "请基于给定的文章回答下述问题。\n\n文章：{context}\n\n请基于上述文章回答下面的问题。\n\n问题：{input}\n回答：",
23:     "gov_report": "You are given a report by a government agency. Write a one-page summary of the report.\n\nReport:\n{context}\n\nNow, write a one-page summary of the report.\n\nSummary:",
24:     "qmsum": "You are given a meeting transcript and a query containing a question or instruction. Answer the query in one or more sentences.\n\nTranscript:\n{context}\n\nNow, answer the query based on the above meeting transcript in one or more sentences.\n\nQuery: {input}\nAnswer:",
25:     "multi_news": "You are given several news passages. Write a one-page summary of all news. \n\nNews:\n{context}\n\nNow, write a one-page summary of all the news.\n\nSummary:",
26:     "vcsum": "下面有一段会议记录，请你阅读后，写一段总结，总结会议的内容。\n会议记录：\n{context}\n\n会议总结：",
27:     "trec": "Please determine the type of the question below. Here are some examples of questions.\n\n{context}\n{input}",
28:     "triviaqa": "Answer the question based on the given passage. Only give me the answer and do not output any other words. The following are some examples.\n\n{context}\n\n{input}",
29:     "samsum": "Summarize the dialogue into a few short sentences. The following are some examples.\n\n{context}\n\n{input}",
30:     "lsht": "请判断给定新闻的类别，下面是一些例子。\n\n{context}\n{input}",
31:     "passage_count": "There are some paragraphs below sourced from Wikipedia. Some of them may be duplicates. Please carefully read these paragraphs and determine how many unique paragraphs there are after removing duplicates. In other words, how many non-repeating paragraphs are there in total?\n\n{context}\n\nPlease enter the final count of unique paragraphs after removing duplicates. The output format should only contain the number, such as 1, 2, 3, and so on.\n\nThe final answer is: ",
32:     "passage_retrieval_en": "Here are 30 paragraphs from Wikipedia, along with an abstract. Please determine which paragraph the abstract is from.\n\n{context}\n\nThe following is an abstract.\n\n{input}\n\nPlease enter the number of the paragraph that the abstract is from. The answer format must be like \"Paragraph 1\", \"Paragraph 2\", etc.\n\nThe answer is: ",
33:     "passage_retrieval_zh": "以下是若干段落文字，以及其中一个段落的摘要。请确定给定的摘要出自哪一段。\n\n{context}\n\n下面是一个摘要\n\n{input}\n\n请输入摘要所属段落的编号。答案格式必须是\"段落1\"，\"段落2\"等格式\n\n答案是：",
34:     "lcc": "Please complete the code given below. \n{context}Next line of code:\n",
35:     "repobench-p": "Please complete the code given below. \n{context}{input}Next line of code:\n"
36: }
37: 
38: dataset2maxlen = {
39:     "narrativeqa": 128,
40:     "qasper": 128,
41:     "multifieldqa_en": 64,
42:     "multifieldqa_zh": 64,
43:     "hotpotqa": 32,
44:     "2wikimqa": 32,
45:     "musique": 32,
46:     "dureader": 128,
47:     "gov_report": 512,
48:     "qmsum": 512,
49:     "multi_news": 512,
50:     "vcsum": 512,
51:     "trec": 64,
52:     "triviaqa": 32,
53:     "samsum": 128,
54:     "lsht": 64,
55:     "passage_count": 32,
56:     "passage_retrieval_en": 32,
57:     "passage_retrieval_zh": 32,
58:     "lcc": 64,
59:     "repobench-p": 64
60: }
61: 
62: CACHE_DIR = "./models_storage"
63: 
64: def parse_args(args=None):
65:     parser = argparse.ArgumentParser()
66:     # parser.add_argument('--model', type=str, default=None, choices=["llama2-7b-chat-4k", "longchat-v1.5-7b-32k", "xgen-7b-8k", "internlm-7b-8k", "chatglm2-6b", "chatglm2-6b-32k", "chatglm3-6b-32k", "vicuna-v1.5-7b-16k"])
67:     # parser.add_argument('--model', type=str, default="Qwen/Qwen2.5-3B-Instruct-AWQ")
68:     parser.add_argument('--model', type=str, default="Qwen/Qwen2.5-7B-Instruct")
69:     parser.add_argument('--e', action='store_true', help="Evaluate on LongBench-E")
70:     parser.add_argument('--k_bits', type=int, default=8)
71:     parser.add_argument('--v_bits', type=int, default=8)
72:     parser.add_argument('--residual_length', type=int, default=128)
73:     parser.add_argument('--group_size', type=int, default=64)
74:     parser.add_argument('--asym', type=bool, default=True)
75:     # in HQQ, 0 for per-channel, 1 for per-token
76:     parser.add_argument('--axis_key', type=int, default=0)
77:     parser.add_argument('--axis_value', type=int, default=1)
78:     parser.add_argument('--max_length', type=int, default=7500)
79:     return parser.parse_args(args)
80: 
81: # This is the customized building prompt for chat models
82: def build_chat(tokenizer, prompt, model_name):
83:     # if "chatglm3" in model_name:
84:     #     prompt = tokenizer.build_chat_input(prompt)
85:     # elif "chatglm" in model_name:
86:     #     prompt = tokenizer.build_prompt(prompt)
87:     # elif "longchat" in model_name or "vicuna" in model_name:
88:     #     from fastchat.model import get_conversation_template
89:     #     conv = get_conversation_template("vicuna")
90:     #     conv.append_message(conv.roles[0], prompt)
91:     #     conv.append_message(conv.roles[1], None)
92:     #     prompt = conv.get_prompt()
93:     # elif "llama2" in model_name:
94:     #     prompt = f"[INST]{prompt}[/INST]"
95:     # elif "xgen" in model_name:
96:     #     header = (
97:     #         "A chat between a curious human and an artificial intelligence assistant. "
98:     #         "The assistant gives helpful, detailed, and polite answers to the human's questions.\n\n"
99:     #     )
100:     #     prompt = header + f" ### Human: {prompt}\n###"
101:     # elif "internlm" in model_name:
102:     #     prompt = f"<|User|>:{prompt}<eoh>\n<|Bot|>:"
103:     return prompt
104: 
105: def post_process(response, model_name):
106:     # if "xgen" in model_name:
107:     #     response = response.strip().replace("Assistant:", "")
108:     # elif "internlm" in model_name:
109:     #     response = response.split("<eoa>")[0]
110:     return response
111: 
112: def get_pred(rank, world_size, data, max_length, max_gen, prompt_format, dataset, device, model_name, out_path, cache_config):
113:     device = torch.device(f'cuda:{rank}')
114:     model, tokenizer = load_model_and_tokenizer(model_name, device)
115:     for json_obj in tqdm(data):
116:         prompt = prompt_format.format(**json_obj)
117:         # truncate to fit max_length (we suggest truncate in the middle, since the left and right side may contain crucial instructions)
118:         tokenized_prompt = tokenizer(prompt, truncation=False, return_tensors="pt").input_ids[0]
119:         # if "chatglm3" in model_name:
120:         #     tokenized_prompt = tokenizer(prompt, truncation=False, return_tensors="pt", add_special_tokens=False).input_ids[0]
121:         # if len(tokenized_prompt) > max_length:
122:         #     half = int(max_length/2)
123:         #     prompt = tokenizer.decode(tokenized_prompt[:half], skip_special_tokens=True)+tokenizer.decode(tokenized_prompt[-half:], skip_special_tokens=True)
124:         # if dataset not in ["trec", "triviaqa", "samsum", "lsht", "lcc", "repobench-p"]: # chat models are better off without build prompts on these tasks
125:         #     prompt = build_chat(tokenizer, prompt, model_name)
126:         # if "chatglm3" in model_name:
127:         #     if dataset in ["trec", "triviaqa", "samsum", "lsht", "lcc", "repobench-p"]:
128:         #         input = tokenizer(prompt, truncation=False, return_tensors="pt").to(device)
129:         #     else:
130:         #         input = prompt.to(device)
131:         # else:
132:         input = tokenizer(prompt, truncation=False, return_tensors="pt").to(device)
133:         context_length = input.input_ids.shape[-1]
134:         past_key_values = FlexibleVanillaQuantizedCache(cache_config=cache_config)
135:         if dataset == "samsum": # prevent illegal output on samsum (model endlessly repeat "\nDialogue"), might be a prompting issue
136:             output = model.generate(
137:                 **input,
138:                 max_new_tokens=max_gen,
139:                 # num_beams=1,
140:                 # do_sample=False,
141:                 # temperature=1.0,
142:                 min_length=context_length+1,
143:                 eos_token_id=[tokenizer.eos_token_id, tokenizer.encode("\n", add_special_tokens=False)[-1]],
144:                 past_key_values=past_key_values,
145:                 use_cache=True
146:             )[0]
147:         else:
148:             output = model.generate(
149:                 **input,
150:                 max_new_tokens=max_gen,
151:                 # num_beams=1,
152:                 # do_sample=False,
153:                 # temperature=1.0,
154:                 past_key_values=past_key_values,
155:                 use_cache=True
156:             )[0]
157:         pred = tokenizer.decode(output[context_length:], skip_special_tokens=True)
158:         pred = post_process(pred, model_name)
159:         with open(out_path, "a", encoding="utf-8") as f:
160:             json.dump({"pred": pred, "answers": json_obj["answers"], "all_classes": json_obj["all_classes"], "length": json_obj["length"]}, f, ensure_ascii=False)
161:             f.write('\n')
162:     # dist.destroy_process_group()
163: 
164: def seed_everything(seed):
165:     torch.manual_seed(seed)
166:     torch.cuda.manual_seed(seed)
167:     np.random.seed(seed)
168:     random.seed(seed)
169:     torch.backends.cudnn.benchmark = False
170:     torch.backends.cudnn.deterministic = True
171:     torch.cuda.manual_seed_all(seed)
172: 
173: def load_model_and_tokenizer(model_name, device):
174:     # if "chatglm" in model_name or "internlm" in model_name or "xgen" in model_name:
175:     #     tokenizer = AutoTokenizer.from_pretrained(path, trust_remote_code=True)
176:     #     model = AutoModelForCausalLM.from_pretrained(path, trust_remote_code=True, torch_dtype=torch.bfloat16).to(device)
177:     # elif "llama2" in model_name:
178:     #     replace_llama_attn_with_flash_attn()
179:     #     tokenizer = LlamaTokenizer.from_pretrained(path)
180:     #     model = LlamaForCausalLM.from_pretrained(path, torch_dtype=torch.bfloat16).to(device)
181:     # elif "longchat" in model_name or "vicuna" in model_name:
182:     #     from fastchat.model import load_model
183:     #     replace_llama_attn_with_flash_attn()
184:     #     model, _ = load_model(
185:     #         path,
186:     #         device='cpu',
187:     #         num_gpus=0,
188:     #         load_8bit=False,
189:     #         cpu_offloading=False,
190:     #         debug=False,
191:     #     )
192:     #     model = model.to(device)
193:     #     model = model.bfloat16()
194:     #     tokenizer = AutoTokenizer.from_pretrained(path, trust_remote_code=True, use_fast=False)
195:     tokenizer = AutoTokenizer.from_pretrained(model_name, use_fast=False, trust_remote_code=True)
196:     model = AutoModelForCausalLM.from_pretrained(model_name, cache_dir=CACHE_DIR, torch_dtype=torch.float16).to(device)
197:     model = model.eval()
198:     return model, tokenizer
199: 
200: if __name__ == '__main__':
201:     seed_everything(42)
202:     args = parse_args()
203:     cache_config = FlexibleQuantizedCacheConfig(nbits_key=args.k_bits, nbits_value=args.v_bits, residual_length=args.residual_length, q_group_size=args.group_size,
204:                                                 asym=args.asym, axis_key=args.axis_key, axis_value=args.axis_value, device='cuda')
205:     world_size = torch.cuda.device_count()
206:     mp.set_start_method('spawn', force=True)
207: 
208:     # model2path = json.load(open("config/model2path.json", "r"))
209:     # model2maxlen = json.load(open("config/model2maxlen.json", "r"))
210:     device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
211:     model_name = args.model
212:     # define your model
213:     # max_length = model2maxlen[model_name]
214:     max_length = args.max_length
215:     if args.e:
216:         datasets = ["qasper", "multifieldqa_en", "hotpotqa", "2wikimqa", "gov_report", "multi_news", \
217:             "trec", "triviaqa", "samsum", "passage_count", "passage_retrieval_en", "lcc", "repobench-p"]
218:     else:
219:         datasets = ["narrativeqa", "qasper", "multifieldqa_en", "multifieldqa_zh", "hotpotqa", "2wikimqa", "musique", \
220:                     "dureader", "gov_report", "qmsum", "multi_news", "vcsum", "trec", "triviaqa", "samsum", "lsht", \
221:                     "passage_count", "passage_retrieval_en", "passage_retrieval_zh", "lcc", "repobench-p"]
222:     # we design specific prompt format and max generation length for each task, feel free to modify them to optimize model output
223:     # dataset2prompt = json.load(open("config/dataset2prompt.json", "r"))
224:     # dataset2maxlen = json.load(open("config/dataset2maxlen.json", "r"))
225:     # predict on each dataset
226:     for dataset in datasets:
227:         if args.e:
228:             data = load_dataset('THUDM/LongBench', f"{dataset}_e", split='test')
229:             if not os.path.exists("pred_e"):
230:                 os.makedirs("pred_e")
231:             if not os.path.exists(f"pred_e/{model_name}"):
232:                 os.makedirs(f"pred_e/{model_name}")
233:             out_path = f"pred_e/{model_name}/{dataset}.jsonl"
234:         else:
235:             data = load_dataset('THUDM/LongBench', dataset, split='test')
236:             if not os.path.exists("pred"):
237:                 os.makedirs("pred")
238:             if not os.path.exists(f"pred/{model_name}"):
239:                 os.makedirs(f"pred/{model_name}")
240:             out_path = f"pred/{model_name}/{dataset}.jsonl"
241:         prompt_format = dataset2prompt[dataset]
242:         max_gen = dataset2maxlen[dataset]
243:         data_all = [data_sample for data_sample in data]
244:         data_subsets = [data_all[i::world_size] for i in range(world_size)]
245:         assert world_size == 1
246:         get_pred(0, world_size, data_subsets[0], max_length, max_gen, prompt_format, dataset, device, model_name, out_path, cache_config)
247:         # processes = []
248:         # for rank in range(world_size):
249:         #     p = mp.Process(target=get_pred, args=(rank, world_size, data_subsets[rank], max_length, \
250:         #                 max_gen, prompt_format, dataset, device, model_name, model2path, out_path))
251:         #     p.start()
252:         #     processes.append(p)
253:         # for p in processes:
254:         #     p.join()
