henry
commited on
Commit
·
da64fee
1
Parent(s):
e928f20
hi
Browse files- Run_Model.py +62 -0
- requirements.txt +3 -0
- run_webUI.py +245 -0
Run_Model.py
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 2 |
+
import torch
|
| 3 |
+
import os
|
| 4 |
+
|
| 5 |
+
# 可调参数,建议在文本生成时设置为较高值
|
| 6 |
+
TOP_P = 0.9 # Top-p (nucleus sampling),范围0到1
|
| 7 |
+
TOP_K = 80 # Top-k 采样的K值
|
| 8 |
+
TEMPERATURE = 0.3 # 温度参数,控制生成文本的随机性
|
| 9 |
+
|
| 10 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 11 |
+
|
| 12 |
+
# 获取当前脚本目录,亦可改为绝对路径
|
| 13 |
+
current_directory = os.path.dirname(os.path.abspath(__file__))
|
| 14 |
+
|
| 15 |
+
# 加载模型和分词器
|
| 16 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 17 |
+
current_directory,
|
| 18 |
+
torch_dtype="auto",
|
| 19 |
+
device_map="auto"
|
| 20 |
+
)
|
| 21 |
+
tokenizer = AutoTokenizer.from_pretrained(current_directory)
|
| 22 |
+
|
| 23 |
+
# 系统指令(建议为空)
|
| 24 |
+
messages = [
|
| 25 |
+
{"role": "system", "content": ""}
|
| 26 |
+
]
|
| 27 |
+
|
| 28 |
+
while True:
|
| 29 |
+
# 获取用户输入
|
| 30 |
+
user_input = input("User: ").strip()
|
| 31 |
+
|
| 32 |
+
# 添加用户输入到对话
|
| 33 |
+
messages.append({"role": "user", "content": user_input})
|
| 34 |
+
|
| 35 |
+
# 准备输入文本
|
| 36 |
+
text = tokenizer.apply_chat_template(
|
| 37 |
+
messages,
|
| 38 |
+
tokenize=False,
|
| 39 |
+
add_generation_prompt=True
|
| 40 |
+
)
|
| 41 |
+
model_inputs = tokenizer([text], return_tensors="pt").to(device)
|
| 42 |
+
|
| 43 |
+
# 生成响应
|
| 44 |
+
generated_ids = model.generate(
|
| 45 |
+
model_inputs.input_ids,
|
| 46 |
+
max_new_tokens=512,
|
| 47 |
+
top_p=TOP_P,
|
| 48 |
+
top_k=TOP_K,
|
| 49 |
+
temperature=TEMPERATURE,
|
| 50 |
+
do_sample=True,
|
| 51 |
+
pad_token_id=tokenizer.eos_token_id # 避免警告
|
| 52 |
+
)
|
| 53 |
+
generated_ids = [
|
| 54 |
+
output_ids[len(input_ids):] for input_ids, output_ids in zip(model_inputs.input_ids, generated_ids)
|
| 55 |
+
]
|
| 56 |
+
|
| 57 |
+
# 解码并打印响应
|
| 58 |
+
response = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0]
|
| 59 |
+
print(f"Assistant: {response}")
|
| 60 |
+
|
| 61 |
+
# 将生成的响应添加到对话中
|
| 62 |
+
messages.append({"role": "assistant", "content": response})
|
requirements.txt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
torch
|
| 2 |
+
transformers>=4.44.2
|
| 3 |
+
gradio>=4.44.0
|
run_webUI.py
ADDED
|
@@ -0,0 +1,245 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer
|
| 3 |
+
from transformers.trainer_utils import set_seed
|
| 4 |
+
from threading import Thread
|
| 5 |
+
import random
|
| 6 |
+
import os
|
| 7 |
+
import gradio as gr
|
| 8 |
+
|
| 9 |
+
# 默认参数
|
| 10 |
+
DEFAULT_TOP_P = 0.9 # Top-p (nucleus sampling) 范围在0到1之间
|
| 11 |
+
DEFAULT_TOP_K = 80 # Top-k 采样的K值
|
| 12 |
+
DEFAULT_TEMPERATURE = 0.3 # 温度参数,控制生成文本的随机性
|
| 13 |
+
DEFAULT_MAX_NEW_TOKENS = 512 # 生成的最大新令牌数
|
| 14 |
+
DEFAULT_SYSTEM_MESSAGE = "" # 默认系统消息
|
| 15 |
+
|
| 16 |
+
# 检查是否有可用的 GPU,默认使用 GPU,如果不可用则使用 CPU
|
| 17 |
+
if torch.cuda.is_available():
|
| 18 |
+
DEVICE = "cuda"
|
| 19 |
+
cpu_only = False
|
| 20 |
+
print("检测到 GPU,使用 GPU 进行推理。")
|
| 21 |
+
else:
|
| 22 |
+
DEVICE = "cpu"
|
| 23 |
+
cpu_only = True
|
| 24 |
+
print("未检测到 GPU,使用 CPU 进行推理。")
|
| 25 |
+
|
| 26 |
+
DEFAULT_CKPT_PATH = os.path.dirname(os.path.abspath(__file__))
|
| 27 |
+
|
| 28 |
+
def _load_model_tokenizer(checkpoint_path, cpu_only):
|
| 29 |
+
tokenizer = AutoTokenizer.from_pretrained(checkpoint_path, resume_download=True)
|
| 30 |
+
|
| 31 |
+
device_map = "cpu" if cpu_only else "auto"
|
| 32 |
+
|
| 33 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 34 |
+
checkpoint_path,
|
| 35 |
+
torch_dtype=torch.float16 if not cpu_only else torch.float32, # 使用更低的精度以节省显存
|
| 36 |
+
device_map=device_map,
|
| 37 |
+
resume_download=True,
|
| 38 |
+
).eval()
|
| 39 |
+
|
| 40 |
+
# 如果使用 GPU,确保模型使用半精度以节省显存(如果模型支持)
|
| 41 |
+
if not cpu_only and torch.cuda.is_available():
|
| 42 |
+
try:
|
| 43 |
+
model.half()
|
| 44 |
+
print("模型已切换为半精度(float16)。")
|
| 45 |
+
except:
|
| 46 |
+
print("无法切换模型为半精度,继续使用默认精度。")
|
| 47 |
+
|
| 48 |
+
model.generation_config.max_new_tokens = DEFAULT_MAX_NEW_TOKENS # 设置生成的最大新令牌数
|
| 49 |
+
|
| 50 |
+
return model, tokenizer
|
| 51 |
+
|
| 52 |
+
def _chat_stream(model, tokenizer, query, history, system_message, top_p, top_k, temperature, max_new_tokens):
|
| 53 |
+
conversation = [
|
| 54 |
+
{'role': 'system', 'content': system_message},
|
| 55 |
+
]
|
| 56 |
+
for query_h, response_h in history:
|
| 57 |
+
conversation.append({'role': 'user', 'content': query_h})
|
| 58 |
+
conversation.append({'role': 'assistant', 'content': response_h})
|
| 59 |
+
conversation.append({'role': 'user', 'content': query})
|
| 60 |
+
|
| 61 |
+
# 准备输入
|
| 62 |
+
try:
|
| 63 |
+
# 尝试使用 apply_chat_template 方法
|
| 64 |
+
text = tokenizer.apply_chat_template(
|
| 65 |
+
conversation,
|
| 66 |
+
tokenize=False, # 确保返回的是字符串
|
| 67 |
+
add_generation_prompt=True
|
| 68 |
+
)
|
| 69 |
+
except AttributeError:
|
| 70 |
+
# 如果没有 apply_chat_template 方法,使用标准方法构建对话
|
| 71 |
+
print("[WARNING] `apply_chat_template` 方法不存在,使用标准对话格式。")
|
| 72 |
+
text = "\n".join([f"{msg['role'].capitalize()}: {msg['content']}" for msg in conversation])
|
| 73 |
+
text += "\nAssistant:"
|
| 74 |
+
|
| 75 |
+
# 确保 text 是字符串
|
| 76 |
+
if not isinstance(text, str):
|
| 77 |
+
raise ValueError("apply_chat_template 应返回字符串类型的文本。")
|
| 78 |
+
|
| 79 |
+
# Tokenize 输入
|
| 80 |
+
inputs = tokenizer(text, return_tensors="pt").to(DEVICE)
|
| 81 |
+
|
| 82 |
+
streamer = TextIteratorStreamer(tokenizer=tokenizer, skip_prompt=True, timeout=60.0, skip_special_tokens=True)
|
| 83 |
+
|
| 84 |
+
# 生成参数
|
| 85 |
+
generation_kwargs = dict(
|
| 86 |
+
input_ids=inputs["input_ids"],
|
| 87 |
+
max_new_tokens=max_new_tokens,
|
| 88 |
+
top_p=top_p,
|
| 89 |
+
top_k=top_k,
|
| 90 |
+
temperature=temperature,
|
| 91 |
+
do_sample=True, # 确保使用采样方法
|
| 92 |
+
pad_token_id=tokenizer.eos_token_id, # 避免警告
|
| 93 |
+
streamer=streamer,
|
| 94 |
+
)
|
| 95 |
+
|
| 96 |
+
thread = Thread(target=model.generate, kwargs=generation_kwargs)
|
| 97 |
+
thread.start()
|
| 98 |
+
|
| 99 |
+
generated_text = ""
|
| 100 |
+
for new_text in streamer:
|
| 101 |
+
generated_text += new_text
|
| 102 |
+
yield new_text
|
| 103 |
+
return generated_text
|
| 104 |
+
|
| 105 |
+
def initialize_model():
|
| 106 |
+
checkpoint_path = DEFAULT_CKPT_PATH
|
| 107 |
+
seed = random.randint(0, 2**32 - 1) # 随机生成一个种子
|
| 108 |
+
set_seed(seed) # 设置随机种子
|
| 109 |
+
|
| 110 |
+
model, tokenizer = _load_model_tokenizer(checkpoint_path, cpu_only)
|
| 111 |
+
|
| 112 |
+
return model, tokenizer
|
| 113 |
+
|
| 114 |
+
# 初始化模型和分词器
|
| 115 |
+
model, tokenizer = initialize_model()
|
| 116 |
+
|
| 117 |
+
def chat_interface(user_input, history, system_message, top_p, top_k, temperature, max_new_tokens):
|
| 118 |
+
if user_input.strip() == "":
|
| 119 |
+
yield history, history, system_message, ""
|
| 120 |
+
return
|
| 121 |
+
|
| 122 |
+
# 创建一个新的助手回复条目,初始为空
|
| 123 |
+
history.append((user_input, ""))
|
| 124 |
+
yield history, history, system_message, "" # 更新 Chatbot 组件和状态
|
| 125 |
+
|
| 126 |
+
# 获取模型生成的回复
|
| 127 |
+
generator = _chat_stream(model, tokenizer, user_input, history[:-1], system_message, top_p, top_k, temperature, max_new_tokens)
|
| 128 |
+
assistant_reply = ""
|
| 129 |
+
for new_text in generator:
|
| 130 |
+
assistant_reply += new_text
|
| 131 |
+
# 更新最后一条助手回复
|
| 132 |
+
updated_history = history.copy()
|
| 133 |
+
updated_history[-1] = (user_input, assistant_reply)
|
| 134 |
+
yield updated_history, updated_history, system_message, "" # 更新 Chatbot 组件和状态
|
| 135 |
+
|
| 136 |
+
def clear_history():
|
| 137 |
+
return [], [], DEFAULT_SYSTEM_MESSAGE, ""
|
| 138 |
+
|
| 139 |
+
# Gradio 接口
|
| 140 |
+
with gr.Blocks() as demo:
|
| 141 |
+
# CSS
|
| 142 |
+
gr.HTML("""
|
| 143 |
+
<style>
|
| 144 |
+
#chat-container {
|
| 145 |
+
height: 500px;
|
| 146 |
+
overflow-y: auto;
|
| 147 |
+
}
|
| 148 |
+
.settings-column {
|
| 149 |
+
padding-left: 20px;
|
| 150 |
+
border-left: 1px solid #ddd;
|
| 151 |
+
}
|
| 152 |
+
.send-button {
|
| 153 |
+
margin-top: 10px;
|
| 154 |
+
width: 100%;
|
| 155 |
+
}
|
| 156 |
+
</style>
|
| 157 |
+
""")
|
| 158 |
+
|
| 159 |
+
gr.Markdown("# Qwen2.5 Sex")
|
| 160 |
+
|
| 161 |
+
with gr.Row():
|
| 162 |
+
# 左侧栏:聊天记录和用户输入
|
| 163 |
+
with gr.Column(scale=3):
|
| 164 |
+
chatbot = gr.Chatbot(elem_id="chat-container")
|
| 165 |
+
user_input = gr.Textbox(
|
| 166 |
+
show_label=False,
|
| 167 |
+
placeholder="输入你的问题...",
|
| 168 |
+
lines=2,
|
| 169 |
+
interactive=True
|
| 170 |
+
)
|
| 171 |
+
send_btn = gr.Button("发送", elem_classes=["send-button"])
|
| 172 |
+
|
| 173 |
+
# 右侧栏:清空历史按钮、系统消息输入框和生成参数滑块
|
| 174 |
+
with gr.Column(scale=1, elem_classes=["settings-column"]):
|
| 175 |
+
gr.Markdown("### 设置")
|
| 176 |
+
clear_btn = gr.Button("清空历史")
|
| 177 |
+
gr.Markdown("#### 系统消息")
|
| 178 |
+
system_message = gr.Textbox(
|
| 179 |
+
label="系统消息",
|
| 180 |
+
value=DEFAULT_SYSTEM_MESSAGE,
|
| 181 |
+
placeholder="输入系统消息...",
|
| 182 |
+
lines=2
|
| 183 |
+
)
|
| 184 |
+
gr.Markdown("#### 生成参数")
|
| 185 |
+
top_p_slider = gr.Slider(
|
| 186 |
+
minimum=0.1, maximum=1.0, value=DEFAULT_TOP_P, step=0.05,
|
| 187 |
+
label="Top-p (nucleus sampling)"
|
| 188 |
+
)
|
| 189 |
+
top_k_slider = gr.Slider(
|
| 190 |
+
minimum=0, maximum=100, value=DEFAULT_TOP_K, step=1,
|
| 191 |
+
label="Top-k"
|
| 192 |
+
)
|
| 193 |
+
temperature_slider = gr.Slider(
|
| 194 |
+
minimum=0.1, maximum=1.5, value=DEFAULT_TEMPERATURE, step=0.05,
|
| 195 |
+
label="Temperature"
|
| 196 |
+
)
|
| 197 |
+
max_new_tokens_slider = gr.Slider(
|
| 198 |
+
minimum=50, maximum=2048, value=DEFAULT_MAX_NEW_TOKENS, step=2,
|
| 199 |
+
label="Max New Tokens"
|
| 200 |
+
)
|
| 201 |
+
|
| 202 |
+
# 状态管理
|
| 203 |
+
state = gr.State([])
|
| 204 |
+
|
| 205 |
+
# 绑定事件
|
| 206 |
+
# 回车chat_interface
|
| 207 |
+
user_input.submit(
|
| 208 |
+
chat_interface,
|
| 209 |
+
inputs=[user_input, state, system_message, top_p_slider, top_k_slider, temperature_slider, max_new_tokens_slider],
|
| 210 |
+
outputs=[chatbot, state, system_message, user_input],
|
| 211 |
+
queue=True
|
| 212 |
+
)
|
| 213 |
+
# 发送chat_interface
|
| 214 |
+
send_btn.click(
|
| 215 |
+
chat_interface,
|
| 216 |
+
inputs=[user_input, state, system_message, top_p_slider, top_k_slider, temperature_slider, max_new_tokens_slider],
|
| 217 |
+
outputs=[chatbot, state, system_message, user_input],
|
| 218 |
+
queue=True
|
| 219 |
+
)
|
| 220 |
+
clear_btn.click(
|
| 221 |
+
clear_history,
|
| 222 |
+
inputs=None,
|
| 223 |
+
outputs=[chatbot, state, system_message, user_input],
|
| 224 |
+
queue=True
|
| 225 |
+
)
|
| 226 |
+
|
| 227 |
+
# JS
|
| 228 |
+
gr.HTML("""
|
| 229 |
+
<script>
|
| 230 |
+
function scrollChat() {
|
| 231 |
+
const chatContainer = document.getElementById('chat-container');
|
| 232 |
+
if(chatContainer) {
|
| 233 |
+
chatContainer.scrollTop = chatContainer.scrollHeight;
|
| 234 |
+
}
|
| 235 |
+
}
|
| 236 |
+
|
| 237 |
+
const observer = new MutationObserver(scrollChat);
|
| 238 |
+
const chatContainer = document.getElementById('chat-container');
|
| 239 |
+
if(chatContainer) {
|
| 240 |
+
observer.observe(chatContainer, { childList: true, subtree: true });
|
| 241 |
+
}
|
| 242 |
+
</script>
|
| 243 |
+
""")
|
| 244 |
+
|
| 245 |
+
demo.launch()
|