FinMM-code / fin-mm /code /LLaVA-Plus /scripts /llava_plus /infer_fin_kline.py
GoldenGrapeGentleman1's picture
Upload fin-mm/code
2e208c6 verified
Raw History Blame Contribute Delete
3.55 kB
import json
from pathlib import Path
import torch
from tqdm import tqdm
from PIL import Image
from transformers import AutoTokenizer
from llava.model.builder import load_pretrained_model
from llava.mm_utils import process_images, tokenizer_image_token
DATA_JSON = Path("/workspace/data/finmultitime_hf/finmultitime_kline_llavaplus.json")
MODEL_PATH = Path("/workspace/models/llava-plus-fin-kline-v1.3-7b")
OUT_JSON = Path("/workspace/data/finmultitime_hf/finmultitime_kline_llavaplus_pred.json")
def load_model():
# 直接从 finetune 后的目录加载 tokenizer(全参微调时是完整模型)
tokenizer = AutoTokenizer.from_pretrained(
str(MODEL_PATH),
use_fast=False,
)
tokenizer2, model, image_processor, context_len = load_pretrained_model(
model_path=str(MODEL_PATH),
model_base=None, # 全参微调,这里不再需要 base
model_name="llava",
)
# 保证 tokenizer 与内部一致(一般相同,这里取模型返回的更保险)
tokenizer = tokenizer2
model = model.cuda().eval()
return tokenizer, model, image_processor
def get_image_path(obj):
if "images" in obj and obj["images"]:
p = Path(obj["images"][0])
if p.exists():
return p
if "image" in obj:
p = Path("/workspace/data/finmultitime_hf/image") / obj["image"]
if p.exists():
return p
raise FileNotFoundError(f"no valid image path for sample {obj.get('id')}")
@torch.no_grad()
def chat_once(tokenizer, model, image_processor, img_path, prompt, max_new_tokens=384):
image = Image.open(img_path).convert("RGB")
image_tensor = process_images([image], image_processor, model.config)
image_tensor = image_tensor.to(model.device, dtype=torch.float16)
conv = "<image>\n" + prompt
input_ids = tokenizer_image_token(
conv, tokenizer, return_tensors="pt"
).unsqueeze(0).to(model.device)
output_ids = model.generate(
input_ids,
images=image_tensor,
max_new_tokens=max_new_tokens,
do_sample=False,
temperature=0.0,
)
# 兜底:防止极端情况下 token id 越界
vocab_size = tokenizer.vocab_size
output_ids = output_ids.clamp_(0, vocab_size - 1)
out = tokenizer.decode(output_ids[0], skip_special_tokens=True)
if "<assistant>" in out:
out = out.split("<assistant>")[-1].strip()
return out.strip()
def main():
tokenizer, model, image_processor = load_model()
with DATA_JSON.open("r", encoding="utf-8") as f:
data = json.load(f)
results = []
for obj in tqdm(data, desc="Infer"):
try:
img_path = get_image_path(obj)
except Exception as e:
print(f"[WARN] skip {obj.get('id')} because {e}")
continue
human_turn = next(
(t for t in obj.get("conversations", []) if t.get("from") == "human"),
None,
)
if human_turn is None:
print(f"[WARN] no human turn in {obj.get('id')}, skip")
continue
prompt = human_turn["value"].replace("<image>", "").strip()
pred = chat_once(tokenizer, model, image_processor, img_path, prompt)
out_obj = dict(obj)
out_obj["model_answer"] = pred
results.append(out_obj)
with OUT_JSON.open("w", encoding="utf-8") as f:
json.dump(results, f, ensure_ascii=False, indent=2)
print(f"[OK] saved {len(results)} predictions to {OUT_JSON}")
if __name__ == "__main__":
main()