GYX97 commited on
Commit
1835872
·
verified ·
1 Parent(s): 3aecece

Update README.md

Browse files
Files changed (1) hide show
  1. README.md +200 -3
README.md CHANGED
@@ -1,3 +1,200 @@
1
- ---
2
- license: apache-2.0
3
- ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🩺 ImageDoctor: Diagnosing Text-to-Image Generation via Grounded Image Reasoning
2
+
3
+ **ImageDoctor** is a unified **evaluation model** for **text-to-image (T2I) generation**, capable of producing both **multi-aspect scalar scores** and **spatially grounded heatmaps**.
4
+ It follows a **“look–think–predict”** reasoning paradigm that mimics human visual diagnosis — first localizing flaws, then reasoning about them, and finally producing an interpretable judgment.
5
+
6
+ ---
7
+
8
+ ## 🔍 Key Features
9
+
10
+ - **🧠 Multi-Aspect Scoring**
11
+ Predicts four fine-grained quality dimensions:
12
+ - *Plausibility*
13
+ - *Text–Image Alignment*
14
+ - *Aesthetics*
15
+ - *Overall Quality*
16
+
17
+ - **📍 Spatially Grounded Feedback**
18
+ Generates **heatmaps** highlighting potential artifacts and misalignments for more interpretable feedback.
19
+
20
+ - **🗣️ Grounded Image Reasoning**
21
+ Provides **step-by-step reasoning** explaining the evaluation — enhancing interpretability and trustworthiness.
22
+
23
+ - **⚙️ Reinforcement-Tuned with GRPO**
24
+ Trained with **Group Relative Policy Optimization (GRPO)** for richer, more stable preference alignment.
25
+
26
+ - **💡 Versatile Applications**
27
+ - As a **metric** for dense image–text evaluation
28
+ - As a **verifier** in test-time scaling setups
29
+ - As a **reward model** in reinforcement learning (e.g., DenseFlow-GRPO)
30
+
31
+ ## 🖼️ Quick Start
32
+
33
+ ```python
34
+ from transformers import AutoProcessor, AutoModelForCausalLM
35
+ from PIL import Image
36
+ import os
37
+ import math
38
+ from qwen_vl_utils import process_vision_info
39
+ import torch
40
+ import numpy as np
41
+
42
+ def build_messages(image, task_prompt):
43
+ return [{
44
+ "role": "user",
45
+ "content": [
46
+ {"type": "image", "image": image},
47
+ {
48
+ "type": "text",
49
+ "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}]"
50
+ }
51
+ ]
52
+ }]
53
+
54
+ checkpoint = "GYX97/ImageDoctor"
55
+ image_path = "path_to_image"
56
+ prompt = 'prompt_for_image_generation'
57
+ img = Image.open(image_path).convert("RGB")
58
+ r = math.sqrt(512*512 / (img.width * img.height))
59
+ new_size = (max(1, int(img.width * r)), max(1, int(img.height * r)))
60
+ img = img.resize(new_size, resample=Image.BICUBIC)
61
+
62
+
63
+ processor = AutoProcessor.from_pretrained(checkpoint, trust_remote_code=True)
64
+ model = AutoModelForCausalLM.from_pretrained(checkpoint, device_map="auto", trust_remote_code=True)
65
+
66
+ messages = build_messages(img, prompt)
67
+ text = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
68
+ image_inputs, video_inputs = process_vision_info(messages)
69
+ output_dir = 'path_to_save_heatmaps'
70
+
71
+ inputs = processor(
72
+ text=[text],
73
+ images=image_inputs,
74
+ videos=video_inputs,
75
+ padding=True,
76
+ return_tensors="pt"
77
+ ).to(model.device)
78
+
79
+ # 2) Generate
80
+ gen_kwargs = dict(
81
+ max_new_tokens=20000,
82
+ use_cache=True,
83
+ return_dict_in_generate=True,
84
+ output_hidden_states=True,
85
+ )
86
+ outputs = model.generate(**inputs, **gen_kwargs)
87
+
88
+ # Decode assistant output (strip prompt tokens)
89
+ generated_ids = outputs.sequences
90
+ trimmed = [out[len(inp):] for inp, out in zip(inputs.input_ids, generated_ids)]
91
+ decoded = processor.batch_decode(trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
92
+
93
+ print(decoded.strip())
94
+
95
+ has_tokens = all(
96
+ hasattr(model.config, a) for a in ["image_token_id", "misalignment_token_id", "artifact_token_id"]
97
+ )
98
+ has_heads = all(
99
+ hasattr(model, a) for a in ["text_hidden_fcs", "image_hidden_fcs", "prompt_encoder", "heatmap", "sigmoid"]
100
+ )
101
+ if has_tokens and has_heads and outputs.hidden_states is not None:
102
+ true_generated = generated_ids[:, inputs.input_ids.shape[1]:]
103
+
104
+ # Find special tokens
105
+ misalignment_mask = (true_generated[:, 1:] == model.config.misalignment_token_id)
106
+ artifact_mask = (true_generated[:, 1:] == model.config.artifact_token_id)
107
+
108
+ if misalignment_mask.any() or artifact_mask.any():
109
+ # Gather final-layer hidden states across decoding steps
110
+ step_states = []
111
+ for step in outputs.hidden_states[1:]: # skip encoder states at index 0
112
+ step_states.append(step[-1]) # last layer [B, 1, H]
113
+ all_gen_h = torch.cat(step_states, dim=1) # [B, T, H]
114
+
115
+ # Map text hidden → special token embeddings
116
+ last_hidden_state = model.text_hidden_fcs[0](all_gen_h) # [B, T, H’]
117
+ # Index by masks (flatten batch/time)
118
+ mis_tokens = last_hidden_state[misalignment_mask].unsqueeze(1) if misalignment_mask.any() else None
119
+ art_tokens = last_hidden_state[artifact_mask].unsqueeze(1) if artifact_mask.any() else None
120
+
121
+ # Visual embeddings (grid features)
122
+ image_embeds = model.visual(
123
+ inputs["pixel_values"].to(model.device),
124
+ grid_thw=inputs["image_grid_thw"].to(model.device)
125
+ )
126
+ img_hidden = model.image_hidden_fcs[0](image_embeds.unsqueeze(0)) # [1, L, C]
127
+ # reshape to low-res feature map (18x18 matches your original; change if your head differs)
128
+ img_hidden = img_hidden.transpose(1, 2).view(1, -1, 18, 18)
129
+
130
+ def run_heatmap(text_tokens):
131
+ sparse_embeddings, dense_embeddings = model.prompt_encoder(
132
+ points=None, boxes=None, masks=None, text_embeds=text_tokens
133
+ )
134
+ low_res = model.heatmap(
135
+ image_embeddings=img_hidden,
136
+ image_pe=model.prompt_encoder.get_dense_pe(),
137
+ sparse_prompt_embeddings=sparse_embeddings.to(img_hidden.dtype),
138
+ dense_prompt_embeddings=dense_embeddings,
139
+ multimask_output=False
140
+ )
141
+ return model.sigmoid(low_res) # [N, 1, H, W]
142
+
143
+ artifact_np_path = None
144
+ misalign_np_path = None
145
+
146
+ if output_dir:
147
+ os.makedirs( output_dir, exist_ok=True)
148
+
149
+ if mis_tokens is not None and art_tokens is not None:
150
+ fused = torch.cat([mis_tokens, art_tokens], dim=0)
151
+ pred = run_heatmap(fused)
152
+ mis_pred = pred[0:1, 0] # [1,H,W] pick first
153
+ art_pred = pred[1:2, 0] # [1,H,W] pick second
154
+
155
+ mis_np = mis_pred[0].detach().cpu().float().numpy()
156
+ art_np = art_pred[0].detach().cpu().float().numpy()
157
+
158
+ if output_dir:
159
+ misalign_np_path = os.path.join( output_dir, f"misalignment.npy")
160
+ artifact_np_path = os.path.join( output_dir, f"artifact.npy")
161
+ np.save(misalign_np_path, mis_np)
162
+ np.save(artifact_np_path, art_np)
163
+
164
+ elif art_tokens is not None:
165
+ pred = run_heatmap(art_tokens[:1])
166
+ art_np = pred[0, 0].detach().cpu().float().numpy()
167
+ if output_dir:
168
+ artifact_np_path = os.path.join( output_dir, f"artifact.npy")
169
+ np.save(artifact_np_path, art_np)
170
+
171
+ elif mis_tokens is not None:
172
+ pred = run_heatmap(mis_tokens[:1])
173
+ mis_np = pred[0, 0].detach().cpu().float().numpy()
174
+ if output_dir:
175
+ misalign_np_path = os.path.join( output_dir, f"misalignment.npy")
176
+ np.save(misalign_np_path, mis_np)
177
+
178
+
179
+ ```
180
+
181
+ ## 📚 Citation
182
+
183
+ If you use **ImageDoctor**, please cite:
184
+ ```bibtex
185
+
186
+ @misc{guo2025imagedoctordiagnosingtexttoimagegeneration,
187
+ author = {Yuxiang Guo, Jiang Liu, Ze Wang, Hao Chen, Ximeng Sun, Yang Zhao, Jialian Wu, Xiaodong Yu, Zicheng Liu and Emad Barsoum},
188
+ title = {ImageDoctor: Diagnosing Text-to-Image Generation via Grounded Image Reasoning},
189
+ eprint = {2510.01010},
190
+ archivePrefix={arXiv},
191
+ year = {2025},
192
+ url = {https://arxiv.org/abs/2510.01010},
193
+ '''
194
+ ---
195
+
196
+
197
+
198
+ ---
199
+ license: apache-2.0
200
+ ---