Views
No views yet
1 from transformers import AutoProcessor, AutoModelForCausalLM
2 from PIL import Image
3 import os
4 import math
5 from qwen_vl_utils import process_vision_info
6 import torch
7 import numpy as np
8
9 def build_messages(image, task_prompt):
10 return [{
11 "role": "user",
12 "content": [
13 {"type": "image", "image": image},
14 {
15 "type": "text",
16 "text": f"Given a caption and an image generated based on this caption, please analyze the provided image in detail. Evaluate it on various dimensions including Semantic Alignment (How well the image content corresponds to the caption), Aesthetics (composition, color usage, and overall artistic quality), Plausibility (realism and attention to detail), and Overall Impression (General subjective assessment of the image's quality). For each evaluation dimension, provide a score between 0-1 and provide a concise rationale for the score. Use a chain-of-thought process to detail your reasoning steps, and enclose all potential important areas and detailed reasoning within <think> and </think> tags. The important areas are represented in following format: \” I need to focus on the bounding box area. Proposed regions (xyxy): ..., which is an enumerated list in the exact format:1.[x1,y1,x2,y2];\n2.[x1,y1,x2,y2];\n3.[x1,y1,x2,y2]… Here, x1,y1 is the top-left corner, and x2,y2 is the bottom-right corner. Then, within the <answer> and </answer> tags, summarize your assessment in the following format: \"Semantic Alignment score: ... \nMisalignment Locations: ...\nAesthetic score: ...\nPlausibility score: ... nArtifact Locations: ...\nOverall Impression score: ...\". No additional text is allowed in the answer section.\n\n Your actual evaluation should be based on the quality of the provided image.**\n\nYour task is provided as follows:\nText Caption: [{task_prompt}]"
17 }
18 ]
19 }]
20
21 checkpoint = "GYX97/ImageDoctor"
22 image_path = "path_to_image"
23 prompt = 'prompt_for_image_generation'
24 img = Image.open(image_path).convert("RGB")
25 r = math.sqrt(512*512 / (img.width * img.height))
26 new_size = (max(1, int(img.width * r)), max(1, int(img.height * r)))
27 img = img.resize(new_size, resample=Image.BICUBIC)
28
29
30 processor = AutoProcessor.from_pretrained(checkpoint, trust_remote_code=True)
31 model = AutoModelForCausalLM.from_pretrained(checkpoint, device_map="auto", trust_remote_code=True)
32
33 messages = build_messages(img, prompt)
34 text = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
35 image_inputs, video_inputs = process_vision_info(messages)
36 output_dir = 'path_to_save_heatmaps'
37
38 inputs = processor(
39 text=[text],
40 images=image_inputs,
41 videos=video_inputs,
42 padding=True,
43 return_tensors="pt"
44 ).to(model.device)
45
46 # 2) Generate
47 gen_kwargs = dict(
48 max_new_tokens=20000,
49 use_cache=True,
50 return_dict_in_generate=True,
51 output_hidden_states=True,
52 )
53 outputs = model.generate(**inputs, **gen_kwargs)
54
55 # Decode assistant output (strip prompt tokens)
56 generated_ids = outputs.sequences
57 trimmed = [out[len(inp):] for inp, out in zip(inputs.input_ids, generated_ids)]
58 decoded = processor.batch_decode(trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
59
60 print(decoded.strip())
61
62 has_tokens = all(
63 hasattr(model.config, a) for a in ["image_token_id", "misalignment_token_id", "artifact_token_id"]
64 )
65 has_heads = all(
66 hasattr(model, a) for a in ["text_hidden_fcs", "image_hidden_fcs", "prompt_encoder", "heatmap", "sigmoid"]
67 )
68 if has_tokens and has_heads and outputs.hidden_states is not None:
69 true_generated = generated_ids[:, inputs.input_ids.shape[1]:]
70
71 # Find special tokens
72 misalignment_mask = (true_generated[:, 1:] == model.config.misalignment_token_id)
73 artifact_mask = (true_generated[:, 1:] == model.config.artifact_token_id)
74
75 if misalignment_mask.any() or artifact_mask.any():
76 # Gather final-layer hidden states across decoding steps
77 step_states = []
78 for step in outputs.hidden_states[1:]: # skip encoder states at index 0
79 step_states.append(step[-1]) # last layer [B, 1, H]
80 all_gen_h = torch.cat(step_states, dim=1) # [B, T, H]
81
82 # Map text hidden → special token embeddings
83 last_hidden_state = model.text_hidden_fcs[0](all_gen_h) # [B, T, H’]
84 # Index by masks (flatten batch/time)
85 mis_tokens = last_hidden_state[misalignment_mask].unsqueeze(1) if misalignment_mask.any() else None
86 art_tokens = last_hidden_state[artifact_mask].unsqueeze(1) if artifact_mask.any() else None
87
88 # Visual embeddings (grid features)
89 image_embeds = model.visual(
90 inputs["pixel_values"].to(model.device),
91 grid_thw=inputs["image_grid_thw"].to(model.device)
92 )
93 img_hidden = model.image_hidden_fcs[0](image_embeds.unsqueeze(0)) # [1, L, C]
94 # reshape to low-res feature map (18x18 matches your original; change if your head differs)
95 img_hidden = img_hidden.transpose(1, 2).view(1, -1, 18, 18)
96
97 def run_heatmap(text_tokens):
98 sparse_embeddings, dense_embeddings = model.prompt_encoder(
99 points=None, boxes=None, masks=None, text_embeds=text_tokens
100 )
101 low_res = model.heatmap(
102 image_embeddings=img_hidden,
103 image_pe=model.prompt_encoder.get_dense_pe(),
104 sparse_prompt_embeddings=sparse_embeddings.to(img_hidden.dtype),
105 dense_prompt_embeddings=dense_embeddings,
106 multimask_output=False
107 )
108 return model.sigmoid(low_res) # [N, 1, H, W]
109
110 artifact_np_path = None
111 misalign_np_path = None
112
113 if output_dir:
114 os.makedirs( output_dir, exist_ok=True)
115
116 if mis_tokens is not None and art_tokens is not None:
117 fused = torch.cat([mis_tokens, art_tokens], dim=0)
118 pred = run_heatmap(fused)
119 mis_pred = pred[0:1, 0] # [1,H,W] pick first
120 art_pred = pred[1:2, 0] # [1,H,W] pick second
121
122 mis_np = mis_pred[0].detach().cpu().float().numpy()
123 art_np = art_pred[0].detach().cpu().float().numpy()
124
125 if output_dir:
126 misalign_np_path = os.path.join( output_dir, f"misalignment.npy")
127 artifact_np_path = os.path.join( output_dir, f"artifact.npy")
128 np.save(misalign_np_path, mis_np)
129 np.save(artifact_np_path, art_np)
130
131 elif art_tokens is not None:
132 pred = run_heatmap(art_tokens[:1])
133 art_np = pred[0, 0].detach().cpu().float().numpy()
134 if output_dir:
135 artifact_np_path = os.path.join( output_dir, f"artifact.npy")
136 np.save(artifact_np_path, art_np)
137
138 elif mis_tokens is not None:
139 pred = run_heatmap(mis_tokens[:1])
140 mis_np = pred[0, 0].detach().cpu().float().numpy()
141 if output_dir:
142 misalign_np_path = os.path.join( output_dir, f"misalignment.npy")
143 np.save(misalign_np_path, mis_np)
144
1451
2@misc{guo2025imagedoctordiagnosingtexttoimagegeneration,
3 author = {Yuxiang Guo, Jiang Liu, Ze Wang, Hao Chen, Ximeng Sun, Yang Zhao, Jialian Wu, Xiaodong Yu, Zicheng Liu and Emad Barsoum},
4 title = {ImageDoctor: Diagnosing Text-to-Image Generation via Grounded Image Reasoning},
5 eprint = {2510.01010},
6 archivePrefix={arXiv},
7 year = {2025},
8 url = {https://arxiv.org/abs/2510.01010},
9'''