File size: 4,135 Bytes
7e7196e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os
import torch
from PIL import Image
import matplotlib.pyplot as plt
from datasets import load_dataset
from transformers import AutoProcessor, Qwen2VLForConditionalGeneration, BitsAndBytesConfig
from peft import PeftModel
from evaluate import load

# =========================
# CONFIG
# =========================
MODEL_NAME = "Qwen/Qwen2-VL-2B-Instruct"
CHECKPOINT_PATH = "./qlora-vlm"
JSONL_PATH = "0508_clean.jsonl"

NUM_SAMPLES = 3
IMAGE_SIZE = 512
MAX_NEW_TOKENS = 1024

# =========================
# LOAD PROCESSOR
# =========================
processor = AutoProcessor.from_pretrained(MODEL_NAME)

# =========================
# LOAD 4-BIT CONFIG
# =========================
bnb_config = BitsAndBytesConfig(
    load_in_4bit=True,
    bnb_4bit_compute_dtype=torch.float16,
    bnb_4bit_use_double_quant=True,
    bnb_4bit_quant_type="nf4"
)

# =========================
# LOAD ZERO-SHOT MODEL
# =========================
print("Loading zero-shot model...")
base_model_zero = Qwen2VLForConditionalGeneration.from_pretrained(
    MODEL_NAME,
    quantization_config=bnb_config,
    device_map="auto",
)
base_model_zero.eval()

# =========================
# LOAD FINE-TUNED MODEL
# =========================
print("Loading fine-tuned model...")
base_model = Qwen2VLForConditionalGeneration.from_pretrained(
    MODEL_NAME,
    quantization_config=bnb_config,
    device_map="auto",
)

model = PeftModel.from_pretrained(base_model, CHECKPOINT_PATH)
model.eval()

# =========================
# LOAD DATASET
# =========================
dataset = load_dataset("json", data_files=JSONL_PATH)["train"]

# =========================
# HELPER: GENERATION
# =========================
def build_inputs(image):
    prompt = "Convert this document image into structured Markdown."

    messages = [
        {
            "role": "user",
            "content": [
                {"type": "image"},
                {"type": "text", "text": prompt}
            ]
        }
    ]

    text = processor.apply_chat_template(
        messages,
        tokenize=False,
        add_generation_prompt=True
    )

    inputs = processor(
        text=text,
        images=image,
        return_tensors="pt"
    )

    return inputs

def generate(model_obj, image_path):
    image = Image.open(image_path).convert("RGB").resize((IMAGE_SIZE, IMAGE_SIZE))
    inputs = build_inputs(image).to(model_obj.device)

    with torch.no_grad():
        output = model_obj.generate(
            **inputs,
            max_new_tokens=MAX_NEW_TOKENS,
            do_sample=False
        )

    return processor.decode(output[0], skip_special_tokens=True)

# =========================
# OPTIONAL: METRIC
# =========================
def compute_rouge(pred, gt):
    rouge = load("rouge")
    score = rouge.compute(predictions=[pred], references=[gt])
    return score


# =========================
# VISUALIZATION
# =========================
def visualize(sample, title="Sample", save=False):
    image_path = sample["image"]
    gt = sample["markdown"]

    pred_zero = generate(base_model_zero, image_path)
    pred_ft = generate(model, image_path)

    image = Image.open(image_path).convert("RGB")

    # show image
    plt.figure(figsize=(8, 5))
    plt.imshow(image)
    plt.axis("off")
    plt.title(title)
    if save:
        plt.savefig(f"{title.replace(' ', '_')}.png")
    plt.show()

    print("\n" + "="*100)
    print("๐Ÿ“Œ GROUND TRUTH:\n")
    print(gt[:1500])

    print("\n" + "-"*100)
    print("๐Ÿค– ZERO-SHOT OUTPUT:\n")
    print(pred_zero[:1500])

    print("\n" + "-"*100)
    print("๐Ÿš€ FINE-TUNED OUTPUT:\n")
    print(pred_ft[:1500])

    # optional metric
    rouge_scores = compute_rouge(pred_ft, gt)
    print("\n๐Ÿ“Š ROUGE (Fine-tuned):", rouge_scores)

    print("="*100)

# =========================
# RUN: TRAIN SAMPLES
# =========================
print("\n===== TRAIN SAMPLES =====\n")
for i in range(NUM_SAMPLES):
    visualize(dataset[i], title=f"Train Sample {i+1}")