OrlandoHugBot commited on
Commit
e410c29
·
verified ·
1 Parent(s): 2593e69

Create README.md

Browse files
Files changed (1) hide show
  1. README.md +243 -0
README.md ADDED
@@ -0,0 +1,243 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ pipeline_tag: any-to-any
3
+ library_name: transformers
4
+ tags:
5
+ - text-to-image
6
+ - image-editing
7
+ - image-understanding
8
+ - vision-language
9
+ - multimodal
10
+ - autoregressive
11
+ - unified-model
12
+ license: mit
13
+ ---
14
+
15
+ ## 🌌 UniPic2-Metaquery-9B
16
+
17
+ <div align="center">
18
+ <img src="skywork-logo.png" alt="Skywork Logo" width="500">
19
+ </div>
20
+
21
+ <p align="center">
22
+ <a href="https://github.com/SkyworkAI/UniPic">
23
+ <img src="https://img.shields.io/badge/GitHub-UniPic-blue?logo=github" alt="GitHub Repo">
24
+ </a>
25
+ <a href="https://github.com/SkyworkAI/UniPic/stargazers">
26
+ <img src="https://img.shields.io/github/stars/SkyworkAI/UniPic?style=social" alt="GitHub Stars">
27
+ </a>
28
+ <a href="https://github.com/SkyworkAI/UniPic/network/members">
29
+ <img src="https://img.shields.io/github/forks/SkyworkAI/UniPic?style=social" alt="GitHub Forks">
30
+ </a>
31
+ </p>
32
+
33
+
34
+ ## 📖 Introduction
35
+
36
+ **UniPic2-Metaquery-GRPO-Flash** is a quantized variant of UniPic2-MetaQuery-GRPO, offering end-to-end image understanding, text-to-image (T2I) generation, and image editing. Optimized for efficiency, it runs smoothly on NVIDIA RTX 40-series GPUs with under 16 GB VRAM — without any performance degradation.
37
+ <div align="center"> <img src="teaser.png" alt="Model Teaser" width="720"> </div>
38
+ <div align="center"> <img src="understanding.png" alt="Model Teaser" width="720"> </div>
39
+
40
+
41
+ ## 📊 Benchmarks
42
+
43
+ <div align="center"> <img src="eval.png" alt="Model Eval" width="720"> </div>
44
+
45
+
46
+ ## 🧠 Usage
47
+
48
+ ### 1. Clone the Repository
49
+
50
+ ```bash
51
+ git clone https://github.com/SkyworkAI/UniPic
52
+ cd UniPic-2
53
+ ```
54
+
55
+ ### 2. Set Up the Environment
56
+ ```bash
57
+ conda create -n unipic python=3.10
58
+ conda activate unipic
59
+ pip install -r requirements.txt
60
+ ```
61
+
62
+
63
+ ### 3.Text-to-Image Generation
64
+ ```bash
65
+ import torch
66
+ from PIL import Image
67
+ from unipicv2.pipeline_stable_diffusion_3_kontext import StableDiffusion3KontextPipeline
68
+ from unipicv2.transformer_sd3_kontext import SD3Transformer2DKontextModel
69
+ from unipicv2.stable_diffusion_3_conditioner import StableDiffusion3Conditioner
70
+ from transformers import Qwen2_5_VLForConditionalGeneration, Qwen2_5_VLProcessor
71
+ from diffusers import FlowMatchEulerDiscreteScheduler, AutoencoderKL,BitsAndBytesConfig
72
+
73
+ # Load model components
74
+ pretrained_model_name_or_path = "/path/to/UniPic2-Metaquery-Flash/UniPic2-Metaquery"
75
+ vlm_path = "/path/to/UniPic2-Metaquery-Flash/Qwen2.5-VL-7B-Instruct-AWQ"
76
+
77
+ quant = "int4" # {"int4", "fp16"}
78
+
79
+ bnb4 = BitsAndBytesConfig(
80
+ load_in_4bit=True,
81
+ bnb_4bit_use_double_quant=True,
82
+ bnb_4bit_quant_type="nf4",
83
+ bnb_4bit_compute_dtype=torch.float16, # 与 LMM/Cond 对齐
84
+ )
85
+
86
+ if quant == "int4":
87
+ transformer = SD3Transformer2DKontextModel.from_pretrained(
88
+ pretrained_model_name_or_path, subfolder="transformer",
89
+ quantization_config=bnb4, device_map="auto", low_cpu_mem_usage=True
90
+ )
91
+ elif quant == "fp16":
92
+ transformer = SD3Transformer2DKontextModel.from_pretrained(
93
+ pretrained_model_name_or_path, subfolder="transformer",
94
+ torch_dtype=torch.float16, device_map="auto", low_cpu_mem_usage=True
95
+ )
96
+ else:
97
+ raise ValueError(f"Unsupported quant: {quant}")
98
+
99
+
100
+ vae = AutoencoderKL.from_pretrained(
101
+ pretrained_model_name_or_path, subfolder="vae",
102
+ torch_dtype=torch.float16, device_map="auto", low_cpu_mem_usage=True).cuda()
103
+
104
+ # Load Qwen2.5-VL model
105
+ lmm = Qwen2_5_VLForConditionalGeneration.from_pretrained(
106
+ vlm_path,
107
+ torch_dtype=torch.bfloat16,device_map="auto",
108
+ attn_implementation="flash_attention_2")
109
+
110
+ processor = Qwen2_5_VLProcessor.from_pretrained(vlm_path)
111
+ processor.chat_template = processor.chat_template.replace(
112
+ "{% if loop.first and message['role'] != 'system' %}<|im_start|>system\nYou are a helpful assistant.<|im_end|>\n{% endif %}",
113
+ "")
114
+
115
+ # 加上cuda
116
+ conditioner = StableDiffusion3Conditioner.from_pretrained(
117
+ pretrained_model_name_or_path, subfolder="conditioner", torch_dtype=torch.float16).cuda()
118
+
119
+ scheduler = FlowMatchEulerDiscreteScheduler.from_pretrained(pretrained_model_name_or_path, subfolder="scheduler")
120
+
121
+ # Create pipeline (note: text encoders set to None)
122
+ pipeline = StableDiffusion3KontextPipeline(
123
+ transformer=transformer, vae=vae,
124
+ text_encoder=None, tokenizer=None,
125
+ text_encoder_2=None, tokenizer_2=None,
126
+ text_encoder_3=None, tokenizer_3=None,
127
+ scheduler=scheduler)
128
+
129
+ # Prepare prompts
130
+ prompt = 'a pig with wings and a top hat flying over a happy futuristic scifi city'
131
+ negative_prompt = ''
132
+
133
+ messages = [[{"role": "user", "content": [{"type": "text", "text": f'Generate an image: {txt}'}]}]
134
+ for txt in [prompt, negative_prompt]]
135
+
136
+ texts = [processor.apply_chat_template(msg, tokenize=False, add_generation_prompt=True) for msg in messages]
137
+ inputs = processor(text=texts, images=None, videos=None, padding=True, return_tensors="pt").to("cuda")
138
+
139
+ # Process with Qwen2.5-VL
140
+ input_ids, attention_mask = inputs.input_ids, inputs.attention_mask
141
+ input_ids = torch.cat([input_ids, input_ids.new_zeros(2, conditioner.config.num_queries)], dim=1)
142
+ attention_mask = torch.cat([attention_mask, attention_mask.new_ones(2, conditioner.config.num_queries)], dim=1)
143
+ inputs_embeds = lmm.get_input_embeddings()(input_ids)
144
+ inputs_embeds[:, -conditioner.config.num_queries:] = conditioner.meta_queries[None].expand(2, -1, -1)
145
+
146
+ outputs = lmm.model(inputs_embeds=inputs_embeds, attention_mask=attention_mask, use_cache=False)
147
+ hidden_states = outputs.last_hidden_state[:, -conditioner.config.num_queries:]
148
+ prompt_embeds, pooled_prompt_embeds = conditioner(hidden_states)
149
+
150
+ # Generate image
151
+ image = pipeline(
152
+ prompt_embeds=prompt_embeds[:1],
153
+ pooled_prompt_embeds=pooled_prompt_embeds[:1],
154
+ negative_prompt_embeds=prompt_embeds[1:],
155
+ negative_pooled_prompt_embeds=pooled_prompt_embeds[1:],
156
+ height=512, width=384,
157
+ num_inference_steps=50,
158
+ guidance_scale=3.5,
159
+ generator=torch.Generator(device=transformer.device).manual_seed(42)
160
+ ).images[0]
161
+
162
+ image.save("text2image.png")
163
+ print(f"Image saved to text2image.png (quant={quant})")
164
+ ```
165
+
166
+
167
+ ### 4. Image Editing
168
+ ```bash
169
+ # Load image for editing
170
+ image = Image.open("text2image.png")
171
+ image = fix_longer_edge(image, image_size=512)
172
+
173
+ prompt = "remove the pig's hat"
174
+ negative_prompt = "blurry, low quality, low resolution, distorted, deformed, broken content, missing parts, damaged details, artifacts, glitch, noise, pixelated, grainy, compression artifacts, bad composition, wrong proportion, incomplete editing, unfinished, unedited areas."
175
+
176
+ # Prepare messages with image input
177
+ messages = [[{"role": "user", "content": [{"type": "image", "image": image}, {"type": "text", "text": txt}]}]
178
+ for txt in [prompt, negative_prompt]]
179
+
180
+ texts = [processor.apply_chat_template(msg, tokenize=False, add_generation_prompt=True) for msg in messages]
181
+
182
+ min_pixels = max_pixels = int(image.height * 28 / 32 * image.width * 28 / 32)
183
+ inputs = processor(
184
+ text=texts, images=[image]*2,
185
+ min_pixels=min_pixels, max_pixels=max_pixels,
186
+ videos=None, padding=True, return_tensors="pt").cuda()
187
+
188
+ # Process with vision understanding
189
+ input_ids, attention_mask, pixel_values, image_grid_thw = \
190
+ inputs.input_ids, inputs.attention_mask, inputs.pixel_values, inputs.image_grid_thw
191
+
192
+ input_ids = torch.cat([input_ids, input_ids.new_zeros(2, conditioner.config.num_queries)], dim=1)
193
+ attention_mask = torch.cat([attention_mask, attention_mask.new_ones(2, conditioner.config.num_queries)], dim=1)
194
+ inputs_embeds = lmm.get_input_embeddings()(input_ids)
195
+ inputs_embeds[:, -conditioner.config.num_queries:] = conditioner.meta_queries[None].expand(2, -1, -1)
196
+
197
+ image_embeds = lmm.visual(pixel_values, grid_thw=image_grid_thw)
198
+ image_token_id = processor.tokenizer.convert_tokens_to_ids('<|image_pad|>')
199
+ inputs_embeds[input_ids == image_token_id] = image_embeds
200
+
201
+ lmm.model.rope_deltas = None
202
+ outputs = lmm.model(inputs_embeds=inputs_embeds, attention_mask=attention_mask,
203
+ image_grid_thw=image_grid_thw, use_cache=False)
204
+
205
+ hidden_states = outputs.last_hidden_state[:, -conditioner.config.num_queries:]
206
+ prompt_embeds, pooled_prompt_embeds = conditioner(hidden_states)
207
+
208
+ # Generate edited image
209
+ edited_image = pipeline(
210
+ image=image,
211
+ prompt_embeds=prompt_embeds[:1],
212
+ pooled_prompt_embeds=pooled_prompt_embeds[:1],
213
+ negative_prompt_embeds=prompt_embeds[1:],
214
+ negative_pooled_prompt_embeds=pooled_prompt_embeds[1:],
215
+ height=image.height, width=image.width,
216
+ num_inference_steps=50,
217
+ guidance_scale=3.5,
218
+ generator=torch.Generator(device=transformer.device).manual_seed(42)
219
+ ).images[0]
220
+
221
+ edited_image.save("edited_image.png")
222
+ print(f"Image saved to edited_image.png (quant={quant})")
223
+
224
+ ```
225
+
226
+
227
+ ## 📄 License
228
+ This model is released under the MIT License.
229
+
230
+
231
+ ## Citation
232
+ If you use Skywork-UniPic in your research, please cite:
233
+ ```
234
+ @misc{wang2025skyworkunipicunifiedautoregressive,
235
+ title={Skywork UniPic: Unified Autoregressive Modeling for Visual Understanding and Generation},
236
+ author={Peiyu Wang and Yi Peng and Yimeng Gan and Liang Hu and Tianyidan Xie and Xiaokun Wang and Yichen Wei and Chuanxin Tang and Bo Zhu and Changshi Li and Hongyang Wei and Eric Li and Xuchen Song and Yang Liu and Yahui Zhou},
237
+ year={2025},
238
+ eprint={2508.03320},
239
+ archivePrefix={arXiv},
240
+ primaryClass={cs.CV},
241
+ url={https://arxiv.org/abs/2508.03320},
242
+ }
243
+ ```