File size: 6,829 Bytes
43235e7 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 | """
模型推理脚本:使用训练好的 LLaVA 模型对 test 集进行推理
生成预测结果供 LLM 评分使用
"""
import os
# 强制使用单 GPU,避免多GPU设备错误
os.environ["CUDA_VISIBLE_DEVICES"] = "0"
import json
import torch
from pathlib import Path
from PIL import Image
from tqdm import tqdm
from datetime import datetime
from llava.mm_utils import process_images, tokenizer_image_token
from llava.model.builder import load_pretrained_model
from llava.conversation import conv_templates
from llava.constants import DEFAULT_IMAGE_TOKEN
# ========= 配置 =========
# 训练好的模型路径 (使用 train split 训练的 v3 版本)
MODEL_PATH = "/workspace/models/llava-plus-fin-kline-v1.5-7b-kimi-v3"
# 数据路径
TEST_DATA_PATH = Path("/workspace/data/finmultitime_hf/finmultitime_kline_llavaplus_kimi_k2_test.json")
OUTPUT_PATH = Path("/workspace/output/model_predictions_v3.json")
# 推理参数
MAX_NEW_TOKENS = 1024
TEMPERATURE = 0.0
DO_SAMPLE = False
def load_model():
"""加载 LLaVA 模型"""
print(f"[MODEL] Loading from {MODEL_PATH}...")
tokenizer, model, image_processor, _ = load_pretrained_model(
model_path=MODEL_PATH,
model_base=None,
model_name="llava",
)
model = model.cuda().eval()
print("[MODEL] Loaded successfully.")
return tokenizer, model, image_processor
def inference_single(
tokenizer,
model,
image_processor,
prompt: str,
image_path: str
) -> str:
"""对单个样本进行推理(使用v1对话模板)"""
# 加载图像
if image_path and Path(image_path).exists():
image = Image.open(image_path).convert("RGB")
img_tensor = process_images([image], image_processor, model.config)
img_tensor = img_tensor.to(model.device, dtype=torch.float16)
else:
img_tensor = None
# 使用 v1 对话模板(与训练时一致)
conv = conv_templates["v1"].copy()
inp = prompt.replace("<image>\n", "").replace("<image>", "").strip()
if img_tensor is not None:
conv.append_message(conv.roles[0], DEFAULT_IMAGE_TOKEN + "\n" + inp)
else:
conv.append_message(conv.roles[0], inp)
conv.append_message(conv.roles[1], None)
full_prompt = conv.get_prompt()
# Tokenize
input_ids = tokenizer_image_token(
full_prompt, tokenizer, return_tensors="pt"
).unsqueeze(0).to(model.device)
# 推理
with torch.inference_mode():
output_ids = model.generate(
input_ids,
images=img_tensor,
max_new_tokens=MAX_NEW_TOKENS,
do_sample=DO_SAMPLE,
temperature=TEMPERATURE,
)
# 限制 vocab range
vocab_size = tokenizer.vocab_size
output_ids = output_ids.clone().clamp_(0, vocab_size - 1)
# 只解码新生成的 token
new_tokens = output_ids[0][input_ids.shape[1]:]
text = tokenizer.decode(new_tokens, skip_special_tokens=True).strip()
return text
def run_inference(tokenizer, model, image_processor, test_data: list, resume_from: dict = None):
"""运行推理"""
import time
predictions = resume_from if resume_from else {}
pending = [s for s in test_data if s["id"] not in predictions]
total = len(test_data)
done = len(predictions)
print(f"\n{'='*60}")
print(f"📊 推理进度: {done}/{total} ({done*100/total:.1f}%)")
print(f"⏳ 待推理: {len(pending)}")
print(f"{'='*60}\n")
start_time = time.time()
for i, sample in enumerate(pending):
sample_id = sample["id"]
sample_start = time.time()
# 获取问题和图像路径
question = sample["conversations"][0]["value"]
image_paths = sample.get("images", [])
image_path = image_paths[0] if image_paths else None
try:
prediction = inference_single(
tokenizer, model, image_processor,
question, image_path
)
predictions[sample_id] = prediction
status = "✅"
except Exception as e:
print(f"\n ❌ Error on {sample_id}: {e}")
predictions[sample_id] = f"[ERROR] {str(e)}"
status = "❌"
# 计算时间
sample_time = time.time() - sample_start
elapsed = time.time() - start_time
completed = i + 1
avg_time = elapsed / completed
remaining = avg_time * (len(pending) - completed)
# 每个样本都打印进度
current_done = done + completed
print(f"[{current_done}/{total}] {status} {sample_id} | 耗时: {sample_time:.1f}s | "
f"平均: {avg_time:.1f}s | 剩余: {remaining/60:.1f}min | "
f"预测长度: {len(prediction) if status=='✅' else 0}")
# 每5个样本保存一次
if completed % 5 == 0:
save_predictions(predictions)
print(f" 💾 已保存 {current_done} 条预测结果")
save_predictions(predictions)
total_time = time.time() - start_time
print(f"\n{'='*60}")
print(f"🎉 推理完成! 总耗时: {total_time/60:.1f} 分钟")
print(f"{'='*60}")
return predictions
def save_predictions(predictions: dict):
"""保存预测结果"""
OUTPUT_PATH.parent.mkdir(parents=True, exist_ok=True)
with open(OUTPUT_PATH, "w", encoding="utf-8") as f:
json.dump(predictions, f, ensure_ascii=False, indent=2)
def main():
print("=" * 60)
print("🚀 模型推理脚本启动")
print(f"⏰ 时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
print(f"📦 模型: {MODEL_PATH}")
print("=" * 60)
# 1. 加载模型
tokenizer, model, image_processor = load_model()
# 2. 加载测试数据
print(f"\n📂 加载测试数据: {TEST_DATA_PATH}")
with open(TEST_DATA_PATH, "r", encoding="utf-8") as f:
test_data = json.load(f)
print(f" 测试样本数: {len(test_data)}")
# 3. 断点续跑
resume_from = None
if OUTPUT_PATH.exists():
with open(OUTPUT_PATH, "r", encoding="utf-8") as f:
resume_from = json.load(f)
print(f"\n📂 发现已有预测结果: {len(resume_from)} 条")
# 4. 运行推理
print("\n🔄 开始推理...")
predictions = run_inference(tokenizer, model, image_processor, test_data, resume_from)
print(f"\n✅ 推理完成!共 {len(predictions)} 条预测")
print(f"📂 结果已保存到: {OUTPUT_PATH}")
# 5. 展示样例
print("\n📋 预测样例:")
for i, (sample_id, pred) in enumerate(list(predictions.items())[:2]):
print(f"\n [{sample_id}]")
print(f" 预测: {pred[:200]}...")
if __name__ == "__main__":
main()
|