File size: 3,548 Bytes
2e208c6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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()