Upload inference.py with huggingface_hub
Browse files- inference.py +67 -0
inference.py
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 3 |
+
|
| 4 |
+
# 使用你本地的检查点路径
|
| 5 |
+
model_path = "/root/Qwen2.5-7B-Instruct-R1-forfinance/"
|
| 6 |
+
|
| 7 |
+
# 加载模型和分词器
|
| 8 |
+
print("正在加载模型...")
|
| 9 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 10 |
+
model_path,
|
| 11 |
+
torch_dtype=torch.bfloat16, # 根据config.json中的torch_dtype
|
| 12 |
+
device_map="auto",
|
| 13 |
+
trust_remote_code=True # 如果需要的话
|
| 14 |
+
)
|
| 15 |
+
|
| 16 |
+
tokenizer = AutoTokenizer.from_pretrained(
|
| 17 |
+
model_path,
|
| 18 |
+
trust_remote_code=True
|
| 19 |
+
)
|
| 20 |
+
|
| 21 |
+
print("模型加载完成!")
|
| 22 |
+
|
| 23 |
+
# 准备输入
|
| 24 |
+
prompt = "假设你是一位金融行业专家,请回答下列问题。\n在宏观分析中,描述在既定利率水平下产品市场达到均衡状态的曲线是什么?\n请一步步思考。"
|
| 25 |
+
|
| 26 |
+
messages = [
|
| 27 |
+
{"role": "system", "content": "You are Qwen, created by Alibaba Cloud. You are a helpful assistant."},
|
| 28 |
+
{"role": "user", "content": prompt}
|
| 29 |
+
]
|
| 30 |
+
|
| 31 |
+
# 应用聊天模板
|
| 32 |
+
text = tokenizer.apply_chat_template(
|
| 33 |
+
messages,
|
| 34 |
+
tokenize=False,
|
| 35 |
+
add_generation_prompt=True
|
| 36 |
+
)
|
| 37 |
+
|
| 38 |
+
print("输入文本:")
|
| 39 |
+
print(text)
|
| 40 |
+
print("\n" + "="*50 + "\n")
|
| 41 |
+
|
| 42 |
+
# 编码输入
|
| 43 |
+
model_inputs = tokenizer([text], return_tensors="pt").to(model.device)
|
| 44 |
+
|
| 45 |
+
# 生成回答
|
| 46 |
+
print("正在生成回答...")
|
| 47 |
+
with torch.no_grad(): # 节省显存
|
| 48 |
+
generated_ids = model.generate(
|
| 49 |
+
**model_inputs,
|
| 50 |
+
max_new_tokens=2048, # 适当减少避免太长
|
| 51 |
+
do_sample=True,
|
| 52 |
+
temperature=0.7,
|
| 53 |
+
top_p=0.8,
|
| 54 |
+
repetition_penalty=1.05,
|
| 55 |
+
pad_token_id=tokenizer.eos_token_id
|
| 56 |
+
)
|
| 57 |
+
|
| 58 |
+
# 解码生成的tokens
|
| 59 |
+
generated_ids = [
|
| 60 |
+
output_ids[len(input_ids):] for input_ids, output_ids in zip(model_inputs.input_ids, generated_ids)
|
| 61 |
+
]
|
| 62 |
+
|
| 63 |
+
response = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0]
|
| 64 |
+
|
| 65 |
+
# 输出结果
|
| 66 |
+
print("模型回答:")
|
| 67 |
+
print(response)
|