Baichuan-7B-Instruction 为 Baichuan-7B 系列模型进行指令微调后的版本,预训练模型可见
Baichuan-7B。
1import gradio as gr
2from transformers import AutoTokenizer, AutoModelForCausalLM
3
4tokenizer = AutoTokenizer.from_pretrained("AlpachinoNLP/Baichuan-7B-Instruction",trust_remote_code=True,use_fast=False)
5model = AutoModelForCausalLM.from_pretrained("AlpachinoNLP/Baichuan-7B-Instruction",trust_remote_code=True ).half()
6model.cuda()
7
8def generate(histories, max_new_tokens=2048, do_sample = True, top_p = 0.95, temperature = 0.35, repetition_penalty=1.1):
9 prompt = ""
10 for history in histories:
11 history_with_identity = "\nHuman:" + history[0] + "\n\nAssistant:" + history[1]
12 prompt += history_with_identity
13 input_ids = tokenizer(prompt, return_tensors="pt").input_ids.to(model.device)
14 outputs = model.generate(
15 input_ids = input_ids,
16 max_new_tokens=max_new_tokens,
17 early_stopping=True,
18 do_sample=do_sample,
19 top_p=top_p,
20 temperature=temperature,
21 repetition_penalty=repetition_penalty,
22 )
23 rets = tokenizer.batch_decode(outputs, skip_special_tokens=True)
24 generate_text = rets[0].replace(prompt, "")
25 return generate_text
26
27with gr.Blocks() as demo:
28 chatbot = gr.Chatbot()
29 msg = gr.Textbox()
30 clear = gr.Button("clear")
31
32 def user(user_message, history):
33 return "", history + [[user_message, ""]]
34
35 def bot(history):
36 print(history)
37 bot_message = generate(history)
38 history[-1][1] = bot_message
39 return history
40
41 msg.submit(user, [msg, chatbot], [msg, chatbot], queue=False).then(
42 bot, chatbot, chatbot
43 )
44 clear.click(lambda: None, None, chatbot, queue=False)
45
46if __name__ == "__main__":
47 demo.launch(server_name="0.0.0.0")
48
49
50
Baichuan-7B 支持 int8 和 int4 量化,用户只需在推理代码中简单修改两行即可实现。请注意,如果是为了节省显存而进行量化,应加载原始精度模型到 CPU 后再开始量化;避免在 from_pretrained 时添加 device_map='auto' 或者其它会导致把原始精度模型直接加载到 GPU 的行为的参数。
1model = AutoModelForCausalLM.from_pretrained("AlpachinoNLP/Baichuan-7B-Instruction", torch_dtype=torch.float16, trust_remote_code=True)
2model = model.quantize(8).cuda()
1model = AutoModelForCausalLM.from_pretrained("AlpachinoNLP/Baichuan-7B-Instruction", torch_dtype=torch.float16, trust_remote_code=True)
2model = model.quantize(4).cuda()
MMLU 是一个包含了57种任务的英文评测数据集。
我们采用了开源的
评测方案 , 评测结果如下: