Spaces:
Running
on
Zero
Running
on
Zero
Update app.py
Browse files
app.py
CHANGED
@@ -7,11 +7,12 @@ from PIL import Image
|
|
7 |
|
8 |
import numpy as np
|
9 |
import os
|
10 |
-
import
|
|
|
11 |
|
12 |
|
13 |
# Load model and processor
|
14 |
-
model_path = "deepseek-ai/Janus-
|
15 |
config = AutoConfig.from_pretrained(model_path)
|
16 |
language_config = config.language_config
|
17 |
language_config._attn_implementation = 'eager'
|
@@ -26,9 +27,9 @@ else:
|
|
26 |
vl_chat_processor = VLChatProcessor.from_pretrained(model_path)
|
27 |
tokenizer = vl_chat_processor.tokenizer
|
28 |
cuda_device = 'cuda' if torch.cuda.is_available() else 'cpu'
|
29 |
-
|
30 |
@torch.inference_mode()
|
31 |
-
@spaces.GPU(duration=120)
|
32 |
# Multimodal Understanding function
|
33 |
def multimodal_understanding(image, question, seed, top_p, temperature):
|
34 |
# Clear CUDA cache before generating
|
@@ -41,11 +42,11 @@ def multimodal_understanding(image, question, seed, top_p, temperature):
|
|
41 |
|
42 |
conversation = [
|
43 |
{
|
44 |
-
"role": "User",
|
45 |
"content": f"<image_placeholder>\n{question}",
|
46 |
"images": [image],
|
47 |
},
|
48 |
-
{"role": "Assistant", "content": ""},
|
49 |
]
|
50 |
|
51 |
pil_images = [Image.fromarray(image)]
|
@@ -94,21 +95,26 @@ def generate(input_ids,
|
|
94 |
|
95 |
pkv = None
|
96 |
for i in range(image_token_num_per_image):
|
97 |
-
|
98 |
-
|
99 |
-
|
100 |
-
|
101 |
-
|
102 |
-
|
103 |
-
|
104 |
-
|
105 |
-
|
106 |
-
|
107 |
-
|
108 |
-
|
109 |
-
|
110 |
-
|
111 |
-
|
|
|
|
|
|
|
|
|
|
|
112 |
patches = vl_gpt.gen_vision_model.decode_code(generated_tokens.to(dtype=torch.int),
|
113 |
shape=[parallel_size, 8, width // patch_size, height // patch_size])
|
114 |
|
@@ -126,10 +132,11 @@ def unpack(dec, width, height, parallel_size=5):
|
|
126 |
|
127 |
|
128 |
@torch.inference_mode()
|
129 |
-
@spaces.GPU(duration=120) # Specify a duration to avoid timeout
|
130 |
def generate_image(prompt,
|
131 |
seed=None,
|
132 |
-
guidance=5
|
|
|
133 |
# Clear CUDA cache and avoid tracking gradients
|
134 |
torch.cuda.empty_cache()
|
135 |
# Set the seed for reproducible results
|
@@ -142,30 +149,31 @@ def generate_image(prompt,
|
|
142 |
parallel_size = 5
|
143 |
|
144 |
with torch.no_grad():
|
145 |
-
messages = [{'role': 'User', 'content': prompt},
|
146 |
-
{'role': 'Assistant', 'content': ''}]
|
147 |
text = vl_chat_processor.apply_sft_template_for_multi_turn_prompts(conversations=messages,
|
148 |
sft_format=vl_chat_processor.sft_format,
|
149 |
system_prompt='')
|
150 |
text = text + vl_chat_processor.image_start_tag
|
|
|
151 |
input_ids = torch.LongTensor(tokenizer.encode(text))
|
152 |
output, patches = generate(input_ids,
|
153 |
width // 16 * 16,
|
154 |
height // 16 * 16,
|
155 |
cfg_weight=guidance,
|
156 |
-
parallel_size=parallel_size
|
|
|
157 |
images = unpack(patches,
|
158 |
width // 16 * 16,
|
159 |
-
height // 16 * 16
|
160 |
-
|
161 |
-
return [Image.fromarray(images[i]).resize((1024, 1024), Image.LANCZOS) for i in range(parallel_size)]
|
162 |
|
|
|
163 |
|
164 |
|
165 |
# Gradio interface
|
166 |
with gr.Blocks() as demo:
|
167 |
gr.Markdown(value="# Multimodal Understanding")
|
168 |
-
# with gr.Row():
|
169 |
with gr.Row():
|
170 |
image_input = gr.Image()
|
171 |
with gr.Column():
|
@@ -182,11 +190,11 @@ with gr.Blocks() as demo:
|
|
182 |
examples=[
|
183 |
[
|
184 |
"explain this meme",
|
185 |
-
"doge.png",
|
186 |
],
|
187 |
[
|
188 |
"Convert the formula into latex code.",
|
189 |
-
"equation.png",
|
190 |
],
|
191 |
],
|
192 |
inputs=[question_input, image_input],
|
@@ -199,8 +207,9 @@ with gr.Blocks() as demo:
|
|
199 |
|
200 |
with gr.Row():
|
201 |
cfg_weight_input = gr.Slider(minimum=1, maximum=10, value=5, step=0.5, label="CFG Weight")
|
|
|
202 |
|
203 |
-
prompt_input = gr.Textbox(label="Prompt")
|
204 |
seed_input = gr.Number(label="Seed (Optional)", precision=0, value=12345)
|
205 |
|
206 |
generation_button = gr.Button("Generate Images")
|
@@ -208,9 +217,12 @@ with gr.Blocks() as demo:
|
|
208 |
image_output = gr.Gallery(label="Generated Images", columns=2, rows=2, height=300)
|
209 |
|
210 |
examples_t2i = gr.Examples(
|
211 |
-
label="Text to image generation examples.
|
212 |
examples=[
|
213 |
"Master shifu racoon wearing drip attire as a street gangster.",
|
|
|
|
|
|
|
214 |
"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.",
|
215 |
"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.",
|
216 |
],
|
@@ -225,8 +237,9 @@ with gr.Blocks() as demo:
|
|
225 |
|
226 |
generation_button.click(
|
227 |
fn=generate_image,
|
228 |
-
inputs=[prompt_input, seed_input, cfg_weight_input],
|
229 |
outputs=image_output
|
230 |
)
|
231 |
|
232 |
-
demo.launch(share=True)
|
|
|
|
7 |
|
8 |
import numpy as np
|
9 |
import os
|
10 |
+
import time
|
11 |
+
# import spaces # Import spaces for ZeroGPU compatibility
|
12 |
|
13 |
|
14 |
# Load model and processor
|
15 |
+
model_path = "deepseek-ai/Janus-Pro-7B"
|
16 |
config = AutoConfig.from_pretrained(model_path)
|
17 |
language_config = config.language_config
|
18 |
language_config._attn_implementation = 'eager'
|
|
|
27 |
vl_chat_processor = VLChatProcessor.from_pretrained(model_path)
|
28 |
tokenizer = vl_chat_processor.tokenizer
|
29 |
cuda_device = 'cuda' if torch.cuda.is_available() else 'cpu'
|
30 |
+
|
31 |
@torch.inference_mode()
|
32 |
+
# @spaces.GPU(duration=120)
|
33 |
# Multimodal Understanding function
|
34 |
def multimodal_understanding(image, question, seed, top_p, temperature):
|
35 |
# Clear CUDA cache before generating
|
|
|
42 |
|
43 |
conversation = [
|
44 |
{
|
45 |
+
"role": "<|User|>",
|
46 |
"content": f"<image_placeholder>\n{question}",
|
47 |
"images": [image],
|
48 |
},
|
49 |
+
{"role": "<|Assistant|>", "content": ""},
|
50 |
]
|
51 |
|
52 |
pil_images = [Image.fromarray(image)]
|
|
|
95 |
|
96 |
pkv = None
|
97 |
for i in range(image_token_num_per_image):
|
98 |
+
with torch.no_grad():
|
99 |
+
outputs = vl_gpt.language_model.model(inputs_embeds=inputs_embeds,
|
100 |
+
use_cache=True,
|
101 |
+
past_key_values=pkv)
|
102 |
+
pkv = outputs.past_key_values
|
103 |
+
hidden_states = outputs.last_hidden_state
|
104 |
+
logits = vl_gpt.gen_head(hidden_states[:, -1, :])
|
105 |
+
logit_cond = logits[0::2, :]
|
106 |
+
logit_uncond = logits[1::2, :]
|
107 |
+
logits = logit_uncond + cfg_weight * (logit_cond - logit_uncond)
|
108 |
+
probs = torch.softmax(logits / temperature, dim=-1)
|
109 |
+
next_token = torch.multinomial(probs, num_samples=1)
|
110 |
+
generated_tokens[:, i] = next_token.squeeze(dim=-1)
|
111 |
+
next_token = torch.cat([next_token.unsqueeze(dim=1), next_token.unsqueeze(dim=1)], dim=1).view(-1)
|
112 |
+
|
113 |
+
img_embeds = vl_gpt.prepare_gen_img_embeds(next_token)
|
114 |
+
inputs_embeds = img_embeds.unsqueeze(dim=1)
|
115 |
+
|
116 |
+
|
117 |
+
|
118 |
patches = vl_gpt.gen_vision_model.decode_code(generated_tokens.to(dtype=torch.int),
|
119 |
shape=[parallel_size, 8, width // patch_size, height // patch_size])
|
120 |
|
|
|
132 |
|
133 |
|
134 |
@torch.inference_mode()
|
135 |
+
# @spaces.GPU(duration=120) # Specify a duration to avoid timeout
|
136 |
def generate_image(prompt,
|
137 |
seed=None,
|
138 |
+
guidance=5,
|
139 |
+
t2i_temperature=1.0):
|
140 |
# Clear CUDA cache and avoid tracking gradients
|
141 |
torch.cuda.empty_cache()
|
142 |
# Set the seed for reproducible results
|
|
|
149 |
parallel_size = 5
|
150 |
|
151 |
with torch.no_grad():
|
152 |
+
messages = [{'role': '<|User|>', 'content': prompt},
|
153 |
+
{'role': '<|Assistant|>', 'content': ''}]
|
154 |
text = vl_chat_processor.apply_sft_template_for_multi_turn_prompts(conversations=messages,
|
155 |
sft_format=vl_chat_processor.sft_format,
|
156 |
system_prompt='')
|
157 |
text = text + vl_chat_processor.image_start_tag
|
158 |
+
|
159 |
input_ids = torch.LongTensor(tokenizer.encode(text))
|
160 |
output, patches = generate(input_ids,
|
161 |
width // 16 * 16,
|
162 |
height // 16 * 16,
|
163 |
cfg_weight=guidance,
|
164 |
+
parallel_size=parallel_size,
|
165 |
+
temperature=t2i_temperature)
|
166 |
images = unpack(patches,
|
167 |
width // 16 * 16,
|
168 |
+
height // 16 * 16,
|
169 |
+
parallel_size=parallel_size)
|
|
|
170 |
|
171 |
+
return [Image.fromarray(images[i]).resize((768, 768), Image.LANCZOS) for i in range(parallel_size)]
|
172 |
|
173 |
|
174 |
# Gradio interface
|
175 |
with gr.Blocks() as demo:
|
176 |
gr.Markdown(value="# Multimodal Understanding")
|
|
|
177 |
with gr.Row():
|
178 |
image_input = gr.Image()
|
179 |
with gr.Column():
|
|
|
190 |
examples=[
|
191 |
[
|
192 |
"explain this meme",
|
193 |
+
"images/doge.png",
|
194 |
],
|
195 |
[
|
196 |
"Convert the formula into latex code.",
|
197 |
+
"images/equation.png",
|
198 |
],
|
199 |
],
|
200 |
inputs=[question_input, image_input],
|
|
|
207 |
|
208 |
with gr.Row():
|
209 |
cfg_weight_input = gr.Slider(minimum=1, maximum=10, value=5, step=0.5, label="CFG Weight")
|
210 |
+
t2i_temperature = gr.Slider(minimum=0, maximum=1, value=1.0, step=0.05, label="temperature")
|
211 |
|
212 |
+
prompt_input = gr.Textbox(label="Prompt. (Prompt in more detail can help produce better images!)")
|
213 |
seed_input = gr.Number(label="Seed (Optional)", precision=0, value=12345)
|
214 |
|
215 |
generation_button = gr.Button("Generate Images")
|
|
|
217 |
image_output = gr.Gallery(label="Generated Images", columns=2, rows=2, height=300)
|
218 |
|
219 |
examples_t2i = gr.Examples(
|
220 |
+
label="Text to image generation examples.",
|
221 |
examples=[
|
222 |
"Master shifu racoon wearing drip attire as a street gangster.",
|
223 |
+
"The face of a beautiful girl",
|
224 |
+
"Astronaut in a jungle, cold color palette, muted colors, detailed, 8k",
|
225 |
+
"A glass of red wine on a reflective surface.",
|
226 |
"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.",
|
227 |
"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.",
|
228 |
],
|
|
|
237 |
|
238 |
generation_button.click(
|
239 |
fn=generate_image,
|
240 |
+
inputs=[prompt_input, seed_input, cfg_weight_input, t2i_temperature],
|
241 |
outputs=image_output
|
242 |
)
|
243 |
|
244 |
+
demo.launch(share=True)
|
245 |
+
# demo.queue(concurrency_count=1, max_size=10).launch(server_name="0.0.0.0", server_port=37906, root_path="/path")
|