Spaces:
Sleeping
Sleeping
Added the idefics3 model
Browse files
app.py
CHANGED
@@ -1,146 +1,352 @@
|
|
|
|
1 |
import gradio as gr
|
2 |
-
import
|
3 |
-
import
|
4 |
-
|
|
|
5 |
import torch
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
6 |
|
7 |
-
device = "cuda" if torch.cuda.is_available() else "cpu"
|
8 |
|
9 |
-
if torch.cuda.is_available():
|
10 |
-
torch.cuda.max_memory_allocated(device=device)
|
11 |
-
pipe = DiffusionPipeline.from_pretrained("stabilityai/sdxl-turbo", torch_dtype=torch.float16, variant="fp16", use_safetensors=True)
|
12 |
-
pipe.enable_xformers_memory_efficient_attention()
|
13 |
-
pipe = pipe.to(device)
|
14 |
-
else:
|
15 |
-
pipe = DiffusionPipeline.from_pretrained("stabilityai/sdxl-turbo", use_safetensors=True)
|
16 |
-
pipe = pipe.to(device)
|
17 |
|
18 |
-
MAX_SEED = np.iinfo(np.int32).max
|
19 |
-
MAX_IMAGE_SIZE = 1024
|
20 |
|
21 |
-
def infer(prompt, negative_prompt, seed, randomize_seed, width, height, guidance_scale, num_inference_steps):
|
22 |
|
23 |
-
|
24 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
25 |
|
26 |
-
|
27 |
|
28 |
-
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
|
36 |
-
|
37 |
|
38 |
-
|
39 |
-
|
40 |
-
examples = [
|
41 |
-
|
42 |
-
|
43 |
-
|
44 |
-
]
|
45 |
-
|
46 |
-
css="""
|
47 |
-
#col-container {
|
48 |
-
|
49 |
-
|
50 |
-
}
|
51 |
-
"""
|
52 |
-
|
53 |
-
if torch.cuda.is_available():
|
54 |
-
|
55 |
-
else:
|
56 |
-
|
57 |
-
|
58 |
-
with gr.Blocks(css=css) as demo:
|
59 |
|
60 |
-
|
61 |
-
|
62 |
-
|
63 |
-
|
64 |
-
|
65 |
|
66 |
-
|
67 |
|
68 |
-
|
69 |
-
|
70 |
-
|
71 |
-
|
72 |
-
|
73 |
-
|
74 |
-
|
75 |
|
76 |
-
|
77 |
|
78 |
-
|
79 |
|
80 |
-
|
81 |
|
82 |
-
|
83 |
-
|
84 |
-
|
85 |
-
|
86 |
-
|
87 |
-
|
88 |
|
89 |
-
|
90 |
-
|
91 |
-
|
92 |
-
|
93 |
-
|
94 |
-
|
95 |
-
|
96 |
|
97 |
-
|
98 |
|
99 |
-
|
100 |
|
101 |
-
|
102 |
-
|
103 |
-
|
104 |
-
|
105 |
-
|
106 |
-
|
107 |
-
|
108 |
|
109 |
-
|
110 |
-
|
111 |
-
|
112 |
-
|
113 |
-
|
114 |
-
|
115 |
-
|
116 |
|
117 |
-
|
118 |
|
119 |
-
|
120 |
-
|
121 |
-
|
122 |
-
|
123 |
-
|
124 |
-
|
125 |
-
|
126 |
|
127 |
-
|
128 |
-
|
129 |
-
|
130 |
-
|
131 |
-
|
132 |
-
|
133 |
-
|
134 |
|
135 |
-
|
136 |
-
|
137 |
-
|
138 |
-
|
139 |
|
140 |
-
|
141 |
-
|
142 |
-
|
143 |
-
|
144 |
-
|
145 |
|
146 |
-
demo.queue().launch()
|
|
|
1 |
+
|
2 |
import gradio as gr
|
3 |
+
from transformers import AutoProcessor, Idefics3ForConditionalGeneration
|
4 |
+
import re
|
5 |
+
import time
|
6 |
+
from PIL import Image
|
7 |
import torch
|
8 |
+
import spaces
|
9 |
+
import subprocess
|
10 |
+
subprocess.run('pip install flash-attn --no-build-isolation', env={'FLASH_ATTENTION_SKIP_CUDA_BUILD': "TRUE"}, shell=True)
|
11 |
+
|
12 |
+
|
13 |
+
processor = AutoProcessor.from_pretrained("HuggingFaceM4/Idefics3-8B-Llama3")
|
14 |
+
|
15 |
+
model = Idefics3ForConditionalGeneration.from_pretrained("HuggingFaceM4/Idefics3-8B-Llama3",
|
16 |
+
torch_dtype=torch.bfloat16,
|
17 |
+
#_attn_implementation="flash_attention_2",
|
18 |
+
trust_remote_code=True).to("cuda")
|
19 |
+
|
20 |
+
BAD_WORDS_IDS = processor.tokenizer(["<image>", "<fake_token_around_image>"], add_special_tokens=False).input_ids
|
21 |
+
EOS_WORDS_IDS = [processor.tokenizer.eos_token_id]
|
22 |
+
|
23 |
+
@spaces.GPU
|
24 |
+
def model_inference(
|
25 |
+
images, text, assistant_prefix, decoding_strategy, temperature, max_new_tokens,
|
26 |
+
repetition_penalty, top_p
|
27 |
+
):
|
28 |
+
if text == "" and not images:
|
29 |
+
gr.Error("Please input a query and optionally image(s).")
|
30 |
+
|
31 |
+
if text == "" and images:
|
32 |
+
gr.Error("Please input a text query along the image(s).")
|
33 |
+
|
34 |
+
if isinstance(images, Image.Image):
|
35 |
+
images = [images]
|
36 |
+
|
37 |
+
|
38 |
+
resulting_messages = [
|
39 |
+
{
|
40 |
+
"role": "user",
|
41 |
+
"content": [{"type": "image"}] + [
|
42 |
+
{"type": "text", "text": text}
|
43 |
+
]
|
44 |
+
}
|
45 |
+
]
|
46 |
+
|
47 |
+
if assistant_prefix:
|
48 |
+
text = f"{assistant_prefix} {text}"
|
49 |
+
|
50 |
+
|
51 |
+
prompt = processor.apply_chat_template(resulting_messages, add_generation_prompt=True)
|
52 |
+
inputs = processor(text=prompt, images=[images], return_tensors="pt")
|
53 |
+
inputs = {k: v.to("cuda") for k, v in inputs.items()}
|
54 |
+
|
55 |
+
generation_args = {
|
56 |
+
"max_new_tokens": max_new_tokens,
|
57 |
+
"repetition_penalty": repetition_penalty,
|
58 |
+
|
59 |
+
}
|
60 |
+
|
61 |
+
assert decoding_strategy in [
|
62 |
+
"Greedy",
|
63 |
+
"Top P Sampling",
|
64 |
+
]
|
65 |
+
if decoding_strategy == "Greedy":
|
66 |
+
generation_args["do_sample"] = False
|
67 |
+
elif decoding_strategy == "Top P Sampling":
|
68 |
+
generation_args["temperature"] = temperature
|
69 |
+
generation_args["do_sample"] = True
|
70 |
+
generation_args["top_p"] = top_p
|
71 |
+
|
72 |
+
|
73 |
+
generation_args.update(inputs)
|
74 |
+
|
75 |
+
# Generate
|
76 |
+
generated_ids = model.generate(**generation_args)
|
77 |
+
|
78 |
+
generated_texts = processor.batch_decode(generated_ids[:, generation_args["input_ids"].size(1):], skip_special_tokens=True)
|
79 |
+
return generated_texts[0]
|
80 |
+
|
81 |
+
|
82 |
+
with gr.Blocks(fill_height=True) as demo:
|
83 |
+
gr.Markdown("## IDEFICS3-Llama 🐶")
|
84 |
+
gr.Markdown("Play with [HuggingFaceM4/Idefics3-8B-Llama3](https://huggingface.co/HuggingFaceM4/Idefics3-8B-Llama3) in this demo. To get started, upload an image and text or try one of the examples.")
|
85 |
+
gr.Markdown("**Disclaimer:** Idefics3 does not include an RLHF alignment stage, so it may not consistently follow prompts or handle complex tasks. However, this doesn't mean it is incapable of doing so. Adding a prefix to the assistant's response, such as Let's think step for a reasoning question or `<html>` for HTML code generation, can significantly improve the output in practice. You could also play with the parameters such as the temperature in non-greedy mode.")
|
86 |
+
with gr.Column():
|
87 |
+
image_input = gr.Image(label="Upload your Image", type="pil", scale=1)
|
88 |
+
query_input = gr.Textbox(label="Prompt")
|
89 |
+
assistant_prefix = gr.Textbox(label="Assistant Prefix", placeholder="Let's think step by step.")
|
90 |
+
|
91 |
+
submit_btn = gr.Button("Submit")
|
92 |
+
output = gr.Textbox(label="Output")
|
93 |
+
|
94 |
+
with gr.Accordion(label="Example Inputs and Advanced Generation Parameters"):
|
95 |
+
examples=[
|
96 |
+
["example_images/mmmu_example.jpeg", "Chase wants to buy 4 kilograms of oval beads and 5 kilograms of star-shaped beads. How much will he spend?", "Let's think step by step.", "Greedy", 0.4, 512, 1.2, 0.8],
|
97 |
+
["example_images/rococo_1.jpg", "What art era is this?", None, "Greedy", 0.4, 512, 1.2, 0.8],
|
98 |
+
["example_images/paper_with_text.png", "Read what's written on the paper", None, "Greedy", 0.4, 512, 1.2, 0.8],
|
99 |
+
["example_images/dragons_playing.png","What's unusual about this image?",None, "Greedy", 0.4, 512, 1.2, 0.8],
|
100 |
+
["example_images/example_images_ai2d_example_2.jpeg", "What happens to fish if pelicans increase?", None, "Greedy", 0.4, 512, 1.2, 0.8],
|
101 |
+
["example_images/travel_tips.jpg", "I want to go somewhere similar to the one in the photo. Give me destinations and travel tips.", None, "Greedy", 0.4, 512, 1.2, 0.8],
|
102 |
+
["example_images/dummy_pdf.png", "How much percent is the order status?", None, "Greedy", 0.4, 512, 1.2, 0.8],
|
103 |
+
["example_images/art_critic.png", "As an art critic AI assistant, could you describe this painting in details and make a thorough critic?.",None, "Greedy", 0.4, 512, 1.2, 0.8],
|
104 |
+
["example_images/s2w_example.png", "What is this UI about?", None,"Greedy", 0.4, 512, 1.2, 0.8]]
|
105 |
+
|
106 |
+
# Hyper-parameters for generation
|
107 |
+
max_new_tokens = gr.Slider(
|
108 |
+
minimum=8,
|
109 |
+
maximum=1024,
|
110 |
+
value=512,
|
111 |
+
step=1,
|
112 |
+
interactive=True,
|
113 |
+
label="Maximum number of new tokens to generate",
|
114 |
+
)
|
115 |
+
repetition_penalty = gr.Slider(
|
116 |
+
minimum=0.01,
|
117 |
+
maximum=5.0,
|
118 |
+
value=1.2,
|
119 |
+
step=0.01,
|
120 |
+
interactive=True,
|
121 |
+
label="Repetition penalty",
|
122 |
+
info="1.0 is equivalent to no penalty",
|
123 |
+
)
|
124 |
+
temperature = gr.Slider(
|
125 |
+
minimum=0.0,
|
126 |
+
maximum=5.0,
|
127 |
+
value=0.4,
|
128 |
+
step=0.1,
|
129 |
+
interactive=True,
|
130 |
+
label="Sampling temperature",
|
131 |
+
info="Higher values will produce more diverse outputs.",
|
132 |
+
)
|
133 |
+
top_p = gr.Slider(
|
134 |
+
minimum=0.01,
|
135 |
+
maximum=0.99,
|
136 |
+
value=0.8,
|
137 |
+
step=0.01,
|
138 |
+
interactive=True,
|
139 |
+
label="Top P",
|
140 |
+
info="Higher values is equivalent to sampling more low-probability tokens.",
|
141 |
+
)
|
142 |
+
decoding_strategy = gr.Radio(
|
143 |
+
[
|
144 |
+
"Greedy",
|
145 |
+
"Top P Sampling",
|
146 |
+
],
|
147 |
+
value="Greedy",
|
148 |
+
label="Decoding strategy",
|
149 |
+
interactive=True,
|
150 |
+
info="Higher values is equivalent to sampling more low-probability tokens.",
|
151 |
+
)
|
152 |
+
decoding_strategy.change(
|
153 |
+
fn=lambda selection: gr.Slider(
|
154 |
+
visible=(
|
155 |
+
selection in ["contrastive_sampling", "beam_sampling", "Top P Sampling", "sampling_top_k"]
|
156 |
+
)
|
157 |
+
),
|
158 |
+
inputs=decoding_strategy,
|
159 |
+
outputs=temperature,
|
160 |
+
)
|
161 |
+
|
162 |
+
decoding_strategy.change(
|
163 |
+
fn=lambda selection: gr.Slider(
|
164 |
+
visible=(
|
165 |
+
selection in ["contrastive_sampling", "beam_sampling", "Top P Sampling", "sampling_top_k"]
|
166 |
+
)
|
167 |
+
),
|
168 |
+
inputs=decoding_strategy,
|
169 |
+
outputs=repetition_penalty,
|
170 |
+
)
|
171 |
+
decoding_strategy.change(
|
172 |
+
fn=lambda selection: gr.Slider(visible=(selection in ["Top P Sampling"])),
|
173 |
+
inputs=decoding_strategy,
|
174 |
+
outputs=top_p,
|
175 |
+
)
|
176 |
+
gr.Examples(
|
177 |
+
examples = examples,
|
178 |
+
inputs=[image_input, query_input, assistant_prefix, decoding_strategy, temperature,
|
179 |
+
max_new_tokens, repetition_penalty, top_p],
|
180 |
+
outputs=output,
|
181 |
+
fn=model_inference
|
182 |
+
)
|
183 |
+
|
184 |
+
submit_btn.click(model_inference, inputs = [image_input, query_input, assistant_prefix, decoding_strategy, temperature,
|
185 |
+
max_new_tokens, repetition_penalty, top_p], outputs=output)
|
186 |
+
|
187 |
+
|
188 |
+
demo.launch(debug=True)
|
189 |
+
|
190 |
+
|
191 |
+
|
192 |
+
|
193 |
+
|
194 |
+
|
195 |
+
|
196 |
+
|
197 |
+
|
198 |
|
|
|
199 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
200 |
|
|
|
|
|
201 |
|
|
|
202 |
|
203 |
+
|
204 |
+
|
205 |
+
|
206 |
+
# -----------------------------------------------------------------------------------------------------------------------------
|
207 |
+
# import gradio as gr
|
208 |
+
# import numpy as np
|
209 |
+
# import random
|
210 |
+
# from diffusers import DiffusionPipeline
|
211 |
+
# import torch
|
212 |
+
|
213 |
+
# device = "cuda" if torch.cuda.is_available() else "cpu"
|
214 |
+
|
215 |
+
# if torch.cuda.is_available():
|
216 |
+
# torch.cuda.max_memory_allocated(device=device)
|
217 |
+
# pipe = DiffusionPipeline.from_pretrained("stabilityai/sdxl-turbo", torch_dtype=torch.float16, variant="fp16", use_safetensors=True)
|
218 |
+
# pipe.enable_xformers_memory_efficient_attention()
|
219 |
+
# pipe = pipe.to(device)
|
220 |
+
# else:
|
221 |
+
# pipe = DiffusionPipeline.from_pretrained("stabilityai/sdxl-turbo", use_safetensors=True)
|
222 |
+
# pipe = pipe.to(device)
|
223 |
+
|
224 |
+
# MAX_SEED = np.iinfo(np.int32).max
|
225 |
+
# MAX_IMAGE_SIZE = 1024
|
226 |
+
|
227 |
+
# def infer(prompt, negative_prompt, seed, randomize_seed, width, height, guidance_scale, num_inference_steps):
|
228 |
+
|
229 |
+
# if randomize_seed:
|
230 |
+
# seed = random.randint(0, MAX_SEED)
|
231 |
|
232 |
+
# generator = torch.Generator().manual_seed(seed)
|
233 |
|
234 |
+
# image = pipe(
|
235 |
+
# prompt = prompt,
|
236 |
+
# negative_prompt = negative_prompt,
|
237 |
+
# guidance_scale = guidance_scale,
|
238 |
+
# num_inference_steps = num_inference_steps,
|
239 |
+
# width = width,
|
240 |
+
# height = height,
|
241 |
+
# generator = generator
|
242 |
+
# ).images[0]
|
243 |
|
244 |
+
# return image
|
245 |
+
|
246 |
+
# examples = [
|
247 |
+
# "Astronaut in a jungle, cold color palette, muted colors, detailed, 8k",
|
248 |
+
# "An astronaut riding a green horse",
|
249 |
+
# "A delicious ceviche cheesecake slice",
|
250 |
+
# ]
|
251 |
+
|
252 |
+
# css="""
|
253 |
+
# #col-container {
|
254 |
+
# margin: 0 auto;
|
255 |
+
# max-width: 520px;
|
256 |
+
# }
|
257 |
+
# """
|
258 |
+
|
259 |
+
# if torch.cuda.is_available():
|
260 |
+
# power_device = "GPU"
|
261 |
+
# else:
|
262 |
+
# power_device = "CPU"
|
263 |
+
|
264 |
+
# with gr.Blocks(css=css) as demo:
|
265 |
|
266 |
+
# with gr.Column(elem_id="col-container"):
|
267 |
+
# gr.Markdown(f"""
|
268 |
+
# # Text-to-Image Gradio Template
|
269 |
+
# Currently running on {power_device}.
|
270 |
+
# """)
|
271 |
|
272 |
+
# with gr.Row():
|
273 |
|
274 |
+
# prompt = gr.Text(
|
275 |
+
# label="Prompt",
|
276 |
+
# show_label=False,
|
277 |
+
# max_lines=1,
|
278 |
+
# placeholder="Enter your prompt",
|
279 |
+
# container=False,
|
280 |
+
# )
|
281 |
|
282 |
+
# run_button = gr.Button("Run", scale=0)
|
283 |
|
284 |
+
# result = gr.Image(label="Result", show_label=False)
|
285 |
|
286 |
+
# with gr.Accordion("Advanced Settings", open=False):
|
287 |
|
288 |
+
# negative_prompt = gr.Text(
|
289 |
+
# label="Negative prompt",
|
290 |
+
# max_lines=1,
|
291 |
+
# placeholder="Enter a negative prompt",
|
292 |
+
# visible=False,
|
293 |
+
# )
|
294 |
|
295 |
+
# seed = gr.Slider(
|
296 |
+
# label="Seed",
|
297 |
+
# minimum=0,
|
298 |
+
# maximum=MAX_SEED,
|
299 |
+
# step=1,
|
300 |
+
# value=0,
|
301 |
+
# )
|
302 |
|
303 |
+
# randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
|
304 |
|
305 |
+
# with gr.Row():
|
306 |
|
307 |
+
# width = gr.Slider(
|
308 |
+
# label="Width",
|
309 |
+
# minimum=256,
|
310 |
+
# maximum=MAX_IMAGE_SIZE,
|
311 |
+
# step=32,
|
312 |
+
# value=512,
|
313 |
+
# )
|
314 |
|
315 |
+
# height = gr.Slider(
|
316 |
+
# label="Height",
|
317 |
+
# minimum=256,
|
318 |
+
# maximum=MAX_IMAGE_SIZE,
|
319 |
+
# step=32,
|
320 |
+
# value=512,
|
321 |
+
# )
|
322 |
|
323 |
+
# with gr.Row():
|
324 |
|
325 |
+
# guidance_scale = gr.Slider(
|
326 |
+
# label="Guidance scale",
|
327 |
+
# minimum=0.0,
|
328 |
+
# maximum=10.0,
|
329 |
+
# step=0.1,
|
330 |
+
# value=0.0,
|
331 |
+
# )
|
332 |
|
333 |
+
# num_inference_steps = gr.Slider(
|
334 |
+
# label="Number of inference steps",
|
335 |
+
# minimum=1,
|
336 |
+
# maximum=12,
|
337 |
+
# step=1,
|
338 |
+
# value=2,
|
339 |
+
# )
|
340 |
|
341 |
+
# gr.Examples(
|
342 |
+
# examples = examples,
|
343 |
+
# inputs = [prompt]
|
344 |
+
# )
|
345 |
|
346 |
+
# run_button.click(
|
347 |
+
# fn = infer,
|
348 |
+
# inputs = [prompt, negative_prompt, seed, randomize_seed, width, height, guidance_scale, num_inference_steps],
|
349 |
+
# outputs = [result]
|
350 |
+
# )
|
351 |
|
352 |
+
# demo.queue().launch()
|