Views
No views yet
1from transformers import AutoModelForCausalLM, AutoTokenizer
2from peft import PeftModel
3
4# 加载tokenizer
5tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen2.5-32B-Instruct", trust_remote_code=True)
6
7# 加载基础模型
8base_model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2.5-32B-Instruct", trust_remote_code=True)
9
10# 加载LoRA适配器
11model = PeftModel.from_pretrained(base_model, "aigc-x/Qwen2.5-32B-novel-writting").merge_and_unload()
12
13# 模型推理
14prompt = "Below is an instruction that describes a task, paired with an input that provides further context. Write a response that appropriately completes the request."
15messages = [
16 {"role": "system", "content": "You are Qwen, created by Alibaba Cloud. You are a helpful assistant."},
17 {"role": "user", "content": prompt}
18]
19text = tokenizer.apply_chat_template(
20 messages,
21 tokenize=False,
22 add_generation_prompt=True
23)
24model_inputs = tokenizer([text], return_tensors="pt").to(model.device)
25
26generated_ids = model.generate(
27 **model_inputs,
28 max_new_tokens=4096
29)
30generated_ids = [
31 output_ids[len(input_ids):] for input_ids, output_ids in zip(model_inputs.input_ids, generated_ids)
32]
33
34response = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0]