wangyiqun commited on
Commit
12971fd
·
verified ·
1 Parent(s): 2fc51c1

Create run.py

Browse files
Files changed (1) hide show
  1. run.py +79 -0
run.py ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from transformers import AutoModelForCausalLM, AutoTokenizer
3
+ from peft import PeftModel
4
+
5
+ # 检查是否有可用的 GPU
6
+ device = "cuda" if torch.cuda.is_available() else "cpu"
7
+
8
+ # 模型名称
9
+ model_name = "Qwen/Qwen2.5-3B-Instruct"
10
+
11
+ # 加载分词器
12
+ tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)
13
+
14
+ # 再次加载 LoRA 模型
15
+ base_model = AutoModelForCausalLM.from_pretrained(model_name, trust_remote_code=True).to(device)
16
+ lora_model = PeftModel.from_pretrained(base_model, "wangyiqun/qwen25_3b_instruct_lora_vulgarity_finetuned")
17
+
18
+ # 推理示例
19
+ input_text = "Hello"
20
+ input_ids = tokenizer(input_text, return_tensors="pt").input_ids.to(lora_model.device)
21
+ output = lora_model.generate(input_ids, max_new_tokens=50, do_sample=True, top_p=0.95, temperature=0.35)
22
+ output_text = tokenizer.decode(output[0], skip_special_tokens=True)
23
+ print(output_text)
24
+
25
+
26
+
27
+
28
+ #!pip install gradio
29
+ import gradio as gr
30
+
31
+ # 假设这些变量已经定义
32
+ # tokenizer, model
33
+
34
+ # 对话函数
35
+ def chatbot(input_text, history):
36
+ if history is None:
37
+ history = []
38
+ # 将当前输入添加到历史记录中
39
+ history.append({"role": "user", "content": input_text})
40
+ messages = [
41
+ {"role": "system", "content": "根据用户友好的打招呼,和用户对骂,注意上下文语义连贯"}
42
+ ] + history
43
+ text = tokenizer.apply_chat_template(
44
+ messages,
45
+ tokenize=False,
46
+ add_generation_prompt=True
47
+ )
48
+ global lora_model
49
+ model = lora_model
50
+ model_inputs = tokenizer([text], return_tensors="pt").to(model.device)
51
+
52
+ generated_ids = model.generate(
53
+ **model_inputs,
54
+ max_new_tokens=512
55
+ )
56
+ generated_ids = [
57
+ output_ids[len(input_ids):] for input_ids, output_ids in zip(model_inputs.input_ids, generated_ids)
58
+ ]
59
+
60
+ response = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0]
61
+ # 将模型回复添加到历史记录中
62
+ history.append({"role": "assistant", "content": response})
63
+ # 转换为 Gradio Chatbot 所需的格式
64
+ chat_history = [(msg["content"] if msg["role"] == "user" else None,
65
+ msg["content"] if msg["role"] == "assistant" else None) for msg in history if
66
+ msg["role"] in ["user", "assistant"]]
67
+ return chat_history, history
68
+
69
+
70
+ # Gradio 界面
71
+ iface = gr.Interface(
72
+ fn=chatbot,
73
+ inputs=[gr.Textbox(label="输入你的问题"), gr.State()],
74
+ outputs=[gr.Chatbot(label="聊天历史"), gr.State()],
75
+ title="Qwen2.5-finetune-骂人专家",
76
+ description="Qwen2.5-finetune-骂人专家"
77
+ )
78
+
79
+ iface.launch(share=True, inbrowser=False, debug=True)