XCLiu commited on
Commit
a18caf6
1 Parent(s): c1423bb

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +252 -0
app.py ADDED
@@ -0,0 +1,252 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import torch
3
+ from janus.janusflow.models import MultiModalityCausalLM, VLChatProcessor
4
+ from PIL import Image
5
+ from diffusers.models import AutoencoderKL
6
+ import numpy as np
7
+ import spaces # Import spaces for ZeroGPU compatibility
8
+
9
+ cuda_device = 'cuda' if torch.cuda.is_available() else 'cpu'
10
+
11
+ # Load model and processor
12
+ model_path = "deepseek-ai/JanusFlow-1.3B"
13
+ model_path = "/weka-jd/prod/jupyter/liuxingchao/notebooks/janus/final_converted_ckpt_ema"
14
+ vl_chat_processor = VLChatProcessor.from_pretrained(model_path)
15
+ tokenizer = vl_chat_processor.tokenizer
16
+
17
+ vl_gpt = MultiModalityCausalLM.from_pretrained(model_path)
18
+ vl_gpt = vl_gpt.to(torch.bfloat16).to(cuda_device).eval()
19
+
20
+ # remember to use bfloat16 dtype, this vae doesn't work with fp16
21
+ vae = AutoencoderKL.from_pretrained("stabilityai/sdxl-vae")
22
+ vae = vae.to(torch.bfloat16).to(cuda_device).eval()
23
+
24
+ # Multimodal Understanding function
25
+ @torch.inference_mode()
26
+ @spaces.GPU(duration=120)
27
+ # Multimodal Understanding function
28
+ def multimodal_understanding(image, question, seed, top_p, temperature):
29
+ # Clear CUDA cache before generating
30
+ torch.cuda.empty_cache()
31
+
32
+ # set seed
33
+ torch.manual_seed(seed)
34
+ np.random.seed(seed)
35
+ torch.cuda.manual_seed(seed)
36
+
37
+ conversation = [
38
+ {
39
+ "role": "User",
40
+ "content": f"<image_placeholder>\n{question}",
41
+ "images": [image],
42
+ },
43
+ {"role": "Assistant", "content": ""},
44
+ ]
45
+
46
+ pil_images = [Image.fromarray(image)]
47
+ prepare_inputs = vl_chat_processor(
48
+ conversations=conversation, images=pil_images, force_batchify=True
49
+ ).to(cuda_device, dtype=torch.bfloat16 if torch.cuda.is_available() else torch.float16)
50
+
51
+
52
+ inputs_embeds = vl_gpt.prepare_inputs_embeds(**prepare_inputs)
53
+
54
+ outputs = vl_gpt.language_model.generate(
55
+ inputs_embeds=inputs_embeds,
56
+ attention_mask=prepare_inputs.attention_mask,
57
+ pad_token_id=tokenizer.eos_token_id,
58
+ bos_token_id=tokenizer.bos_token_id,
59
+ eos_token_id=tokenizer.eos_token_id,
60
+ max_new_tokens=512,
61
+ do_sample=False if temperature == 0 else True,
62
+ use_cache=True,
63
+ temperature=temperature,
64
+ top_p=top_p,
65
+ )
66
+
67
+ answer = tokenizer.decode(outputs[0].cpu().tolist(), skip_special_tokens=True)
68
+
69
+ return answer
70
+
71
+
72
+ @torch.inference_mode()
73
+ @spaces.GPU(duration=120)
74
+ def generate(
75
+ input_ids,
76
+ cfg_weight: float = 2.0,
77
+ num_inference_steps: int = 30
78
+ ):
79
+ # we generate 5 images at a time, *2 for CFG
80
+ tokens = torch.stack([input_ids] * 10).cuda()
81
+ tokens[5:, 1:] = vl_chat_processor.pad_id
82
+ inputs_embeds = vl_gpt.language_model.get_input_embeddings()(tokens)
83
+ print(inputs_embeds.shape)
84
+
85
+ # we remove the last <bog> token and replace it with t_emb later
86
+ inputs_embeds = inputs_embeds[:, :-1, :]
87
+
88
+ # generate with rectified flow ode
89
+ # step 1: encode with vision_gen_enc
90
+ z = torch.randn((5, 4, 48, 48), dtype=torch.bfloat16).cuda()
91
+
92
+ dt = 1.0 / num_inference_steps
93
+ dt = torch.zeros_like(z).cuda().to(torch.bfloat16) + dt
94
+
95
+ # step 2: run ode
96
+ attention_mask = torch.ones((10, inputs_embeds.shape[1]+577)).to(vl_gpt.device)
97
+ attention_mask[5:, 1:inputs_embeds.shape[1]] = 0
98
+ attention_mask = attention_mask.int()
99
+ for step in range(num_inference_steps):
100
+ # prepare inputs for the llm
101
+ z_input = torch.cat([z, z], dim=0) # for cfg
102
+ t = step / num_inference_steps * 1000.
103
+ t = torch.tensor([t] * z_input.shape[0]).to(dt)
104
+ z_enc = vl_gpt.vision_gen_enc_model(z_input, t)
105
+ z_emb, t_emb, hs = z_enc[0], z_enc[1], z_enc[2]
106
+ z_emb = z_emb.view(z_emb.shape[0], z_emb.shape[1], -1).permute(0, 2, 1)
107
+ z_emb = vl_gpt.vision_gen_enc_aligner(z_emb)
108
+ llm_emb = torch.cat([inputs_embeds, t_emb.unsqueeze(1), z_emb], dim=1)
109
+
110
+ # input to the llm
111
+ # we apply attention mask for CFG: 1 for tokens that are not masked, 0 for tokens that are masked.
112
+ if step == 0:
113
+ outputs = vl_gpt.language_model.model(inputs_embeds=llm_emb,
114
+ use_cache=True,
115
+ attention_mask=attention_mask,
116
+ past_key_values=None)
117
+ past_key_values = []
118
+ for kv_cache in past_key_values:
119
+ k, v = kv_cache[0], kv_cache[1]
120
+ past_key_values.append((k[:, :, :inputs_embeds.shape[1], :], v[:, :, :inputs_embeds.shape[1], :]))
121
+ past_key_values = tuple(past_key_values)
122
+ else:
123
+ outputs = vl_gpt.language_model.model(inputs_embeds=llm_emb,
124
+ use_cache=True,
125
+ attention_mask=attention_mask,
126
+ past_key_values=past_key_values)
127
+ hidden_states = outputs.last_hidden_state
128
+
129
+ # transform hidden_states back to v
130
+ hidden_states = vl_gpt.vision_gen_dec_aligner(vl_gpt.vision_gen_dec_aligner_norm(hidden_states[:, -576:, :]))
131
+ hidden_states = hidden_states.reshape(z_emb.shape[0], 24, 24, 768).permute(0, 3, 1, 2)
132
+ v = vl_gpt.vision_gen_dec_model(hidden_states, hs, t_emb)
133
+ v_cond, v_uncond = torch.chunk(v, 2)
134
+ v = cfg_weight * v_cond - (cfg_weight-1.) * v_uncond
135
+ z = z + dt * v
136
+
137
+ # step 3: decode with vision_gen_dec and sdxl vae
138
+ decoded_image = vae.decode(z / vae.config.scaling_factor).sample
139
+
140
+ images = decoded_image.float().clip_(-1., 1.).permute(0,2,3,1).cpu().numpy()
141
+ images = ((images+1) / 2. * 255).astype(np.uint8)
142
+
143
+ return images
144
+
145
+ def unpack(dec, width, height, parallel_size=5):
146
+ dec = dec.to(torch.float32).cpu().numpy().transpose(0, 2, 3, 1)
147
+ dec = np.clip((dec + 1) / 2 * 255, 0, 255)
148
+
149
+ visual_img = np.zeros((parallel_size, width, height, 3), dtype=np.uint8)
150
+ visual_img[:, :, :] = dec
151
+
152
+ return visual_img
153
+
154
+
155
+ @torch.inference_mode()
156
+ @spaces.GPU(duration=120)
157
+ def generate_image(prompt,
158
+ seed=None,
159
+ guidance=5,
160
+ num_inference_steps=30):
161
+ # Clear CUDA cache and avoid tracking gradients
162
+ torch.cuda.empty_cache()
163
+ # Set the seed for reproducible results
164
+ if seed is not None:
165
+ torch.manual_seed(seed)
166
+ torch.cuda.manual_seed(seed)
167
+ np.random.seed(seed)
168
+
169
+ with torch.no_grad():
170
+ messages = [{'role': 'User', 'content': prompt},
171
+ {'role': 'Assistant', 'content': ''}]
172
+ text = vl_chat_processor.apply_sft_template_for_multi_turn_prompts(conversations=messages,
173
+ sft_format=vl_chat_processor.sft_format,
174
+ system_prompt='')
175
+ text = text + vl_chat_processor.image_start_tag
176
+ input_ids = torch.LongTensor(tokenizer.encode(text))
177
+ images = generate(input_ids,
178
+ cfg_weight=guidance,
179
+ num_inference_steps=num_inference_steps)
180
+ return [Image.fromarray(images[i]).resize((1024, 1024), Image.LANCZOS) for i in range(images.shape[0])]
181
+
182
+
183
+
184
+ # Gradio interface
185
+ with gr.Blocks() as demo:
186
+ gr.Markdown(value="# Multimodal Understanding")
187
+ # with gr.Row():
188
+ with gr.Row():
189
+ image_input = gr.Image()
190
+ with gr.Column():
191
+ question_input = gr.Textbox(label="Question")
192
+ und_seed_input = gr.Number(label="Seed", precision=0, value=42)
193
+ top_p = gr.Slider(minimum=0, maximum=1, value=0.95, step=0.05, label="top_p")
194
+ temperature = gr.Slider(minimum=0, maximum=1, value=0.1, step=0.05, label="temperature")
195
+
196
+ understanding_button = gr.Button("Chat")
197
+ understanding_output = gr.Textbox(label="Response")
198
+
199
+ examples_inpainting = gr.Examples(
200
+ label="Multimodal Understanding examples",
201
+ examples=[
202
+ [
203
+ "explain this meme",
204
+ "./images/doge.png",
205
+ ],
206
+ [
207
+ "Convert the formula into latex code.",
208
+ "./images/equation.png",
209
+ ],
210
+ ],
211
+ inputs=[question_input, image_input],
212
+ )
213
+
214
+
215
+ gr.Markdown(value="# Text-to-Image Generation")
216
+
217
+
218
+
219
+ with gr.Row():
220
+ cfg_weight_input = gr.Slider(minimum=1, maximum=10, value=2, step=0.5, label="CFG Weight")
221
+ step_input = gr.Slider(minimum=1, maximum=50, value=30, step=1, label="Number of Inference Steps")
222
+
223
+ prompt_input = gr.Textbox(label="Prompt")
224
+ seed_input = gr.Number(label="Seed (Optional)", precision=0, value=12345)
225
+
226
+ generation_button = gr.Button("Generate Images")
227
+
228
+ image_output = gr.Gallery(label="Generated Images", columns=2, rows=2, height=300)
229
+
230
+ examples_t2i = gr.Examples(
231
+ label="Text to image generation examples.",
232
+ examples=[
233
+ "Master shifu racoon wearing drip attire as a street gangster.",
234
+ "A cute and adorable baby fox with big brown eyes, autumn leaves in the background enchanting,immortal,fluffy, shiny mane,Petals,fairyism,unreal engine 5 and Octane Render,highly detailed, photorealistic, cinematic, natural colors.",
235
+ "The image features an intricately designed eye set against a circular backdrop adorned with ornate swirl patterns that evoke both realism and surrealism. At the center of attention is a strikingly vivid blue iris surrounded by delicate veins radiating outward from the pupil to create depth and intensity. The eyelashes are long and dark, casting subtle shadows on the skin around them which appears smooth yet slightly textured as if aged or weathered over time.\n\nAbove the eye, there's a stone-like structure resembling part of classical architecture, adding layers of mystery and timeless elegance to the composition. This architectural element contrasts sharply but harmoniously with the organic curves surrounding it. Below the eye lies another decorative motif reminiscent of baroque artistry, further enhancing the overall sense of eternity encapsulated within each meticulously crafted detail. \n\nOverall, the atmosphere exudes a mysterious aura intertwined seamlessly with elements suggesting timelessness, achieved through the juxtaposition of realistic textures and surreal artistic flourishes. Each component\u2014from the intricate designs framing the eye to the ancient-looking stone piece above\u2014contributes uniquely towards creating a visually captivating tableau imbued with enigmatic allure.",
236
+ ],
237
+ inputs=prompt_input,
238
+ )
239
+
240
+ understanding_button.click(
241
+ multimodal_understanding,
242
+ inputs=[image_input, question_input, und_seed_input, top_p, temperature],
243
+ outputs=understanding_output
244
+ )
245
+
246
+ generation_button.click(
247
+ fn=generate_image,
248
+ inputs=[prompt_input, seed_input, cfg_weight_input, step_input],
249
+ outputs=image_output
250
+ )
251
+
252
+ demo.launch(share=True)