Views
No views yet
transformers:1from transformers import AutoTokenizer, AutoModel, AutoConfig
2path = "Salesforce/cogalign-internvl2_5-mpo-1b"
3model = AutoModel.from_pretrained(
4 path,
5 torch_dtype=torch.bfloat16,
6 low_cpu_mem_usage=True,
7 use_flash_attn=True,
8 trust_remote_code=True).eval().cuda()
9tokenizer = AutoTokenizer.from_pretrained(path, trust_remote_code=True, use_fast=False)1# Adapted from https://huggingface.co/OpenGVLab/InternVL2_5-1B-MPO
2import copy
3import pandas as pd
4from datasets import load_dataset
5import requests
6import numpy as np
7import torch
8import torchvision.transforms as T
9from decord import VideoReader, cpu
10from PIL import Image
11from torchvision.transforms.functional import InterpolationMode
12
13# Taken from InternVL's code
14IMAGENET_MEAN = (0.485, 0.456, 0.406)
15IMAGENET_STD = (0.229, 0.224, 0.225)
16
17def build_transform(input_size):
18 MEAN, STD = IMAGENET_MEAN, IMAGENET_STD
19 transform = T.Compose([
20 T.Lambda(lambda img: img.convert('RGB') if img.mode != 'RGB' else img),
21 T.Resize((input_size, input_size), interpolation=InterpolationMode.BICUBIC),
22 T.ToTensor(),
23 T.Normalize(mean=MEAN, std=STD)
24 ])
25 return transform
26
27def find_closest_aspect_ratio(aspect_ratio, target_ratios, width, height, image_size):
28 best_ratio_diff = float('inf')
29 best_ratio = (1, 1)
30 area = width * height
31 for ratio in target_ratios:
32 target_aspect_ratio = ratio[0] / ratio[1]
33 ratio_diff = abs(aspect_ratio - target_aspect_ratio)
34 if ratio_diff < best_ratio_diff:
35 best_ratio_diff = ratio_diff
36 best_ratio = ratio
37 elif ratio_diff == best_ratio_diff:
38 if area > 0.5 * image_size * image_size * ratio[0] * ratio[1]:
39 best_ratio = ratio
40 return best_ratio
41
42def dynamic_preprocess(image, min_num=1, max_num=12, image_size=448, use_thumbnail=False):
43 orig_width, orig_height = image.size
44 aspect_ratio = orig_width / orig_height
45
46 # calculate the existing image aspect ratio
47 target_ratios = set(
48 (i, j) for n in range(min_num, max_num + 1) for i in range(1, n + 1) for j in range(1, n + 1) if
49 i * j <= max_num and i * j >= min_num)
50 target_ratios = sorted(target_ratios, key=lambda x: x[0] * x[1])
51
52 # find the closest aspect ratio to the target
53 target_aspect_ratio = find_closest_aspect_ratio(
54 aspect_ratio, target_ratios, orig_width, orig_height, image_size)
55
56 # calculate the target width and height
57 target_width = image_size * target_aspect_ratio[0]
58 target_height = image_size * target_aspect_ratio[1]
59 blocks = target_aspect_ratio[0] * target_aspect_ratio[1]
60
61 # resize the image
62 resized_img = image.resize((target_width, target_height))
63 processed_images = []
64 for i in range(blocks):
65 box = (
66 (i % (target_width // image_size)) * image_size,
67 (i // (target_width // image_size)) * image_size,
68 ((i % (target_width // image_size)) + 1) * image_size,
69 ((i // (target_width // image_size)) + 1) * image_size
70 )
71 # split the image
72 split_img = resized_img.crop(box)
73 processed_images.append(split_img)
74 assert len(processed_images) == blocks
75 if use_thumbnail and len(processed_images) != 1:
76 thumbnail_img = image.resize((image_size, image_size))
77 processed_images.append(thumbnail_img)
78 return processed_images
79
80def load_image(image_file, input_size=448, max_num=12, is_url=False):
81 if is_url:
82 image = Image.open(requests.get(image_file, stream=True).raw)
83 else:
84 image = Image.open(image_file).convert('RGB')
85 transform = build_transform(input_size=input_size)
86 images = dynamic_preprocess(image, image_size=input_size, use_thumbnail=True, max_num=max_num)
87 pixel_values = [transform(image) for image in images]
88 pixel_values = torch.stack(pixel_values)
89 return pixel_values1chocolate = load_dataset("khhuang/CHOCOLATE")["test"]
2chocolate_df = pd.DataFrame(chocolate)
3chocolate_df_lvlm = chocolate_df.loc[chocolate_df.split=="LVLM",:]
4
5instance = chocolate_df_lvlm.iloc[2]
6caption = ' '.join(instance.sentences)
7
8url = instance.image_path
9pixel_values = load_image(url, max_num=12, is_url=True).to(torch.bfloat16).cuda()
10generation_config = dict(max_new_tokens=1024, do_sample=True)
11
12prompt = f"""
13You are given a chart and a caption, you are tasked to detect whether the caption is factually
14consistent with the chart. A caption is factually consistent with the chart if it describes the datapoints within the charts without factual errors (e.g. wrong label, value, trends).
15[Start of Caption]
16{caption}
17[End of Caption]
18For the above caption, you should respond 'Answer: Yes' if it is factually consistent with the chart. Otherwise, respond 'Answer: No'. Do not provide explanation or other thing.
19"""
20question = f'<image>\n{prompt}'
21response = model.chat(tokenizer, pixel_values, question, generation_config)
22print(f'User: {question}\nAssistant: {response}')@misc{huang-etal-2025-cogalign,
title = "Why Vision Language Models Struggle with Visual Arithmetic? Towards Enhanced Chart and Geometry Understanding",
author = "Huang, Kung-Hsiang and
Qin, Can and
Qiu, Haoyi and
Laban, Philippe and
Joty, Shafiq and
Xiong, Caiming and
Wu, Chien-Sheng",
year = "2025",
eprint={2502.11492},
archivePrefix = "arXiv",
primaryClass={cs.AI}
}