Spaces:
Running
on
Zero
Running
on
Zero
Upload app (12).py
Browse files- app (12).py +64 -0
app (12).py
ADDED
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
import spaces
|
3 |
+
from transformers import AutoModelForCausalLM, AutoProcessor
|
4 |
+
import torch
|
5 |
+
from PIL import Image
|
6 |
+
import subprocess
|
7 |
+
subprocess.run('pip install flash-attn --no-build-isolation', env={'FLASH_ATTENTION_SKIP_CUDA_BUILD': "TRUE"}, shell=True)
|
8 |
+
|
9 |
+
models = {
|
10 |
+
"microsoft/Phi-3.5-vision-instruct": AutoModelForCausalLM.from_pretrained("microsoft/Phi-3.5-vision-instruct", trust_remote_code=True, torch_dtype="auto", _attn_implementation="flash_attention_2").cuda().eval()
|
11 |
+
|
12 |
+
}
|
13 |
+
|
14 |
+
processors = {
|
15 |
+
"microsoft/Phi-3.5-vision-instruct": AutoProcessor.from_pretrained("microsoft/Phi-3.5-vision-instruct", trust_remote_code=True)
|
16 |
+
}
|
17 |
+
|
18 |
+
|
19 |
+
kwargs = {}
|
20 |
+
kwargs['torch_dtype'] = torch.bfloat16
|
21 |
+
|
22 |
+
user_prompt = '<|user|>\n'
|
23 |
+
assistant_prompt = '<|assistant|>\n'
|
24 |
+
prompt_suffix = "<|end|>\n"
|
25 |
+
|
26 |
+
@spaces.GPU
|
27 |
+
def run_example(image, text_input=None, model_id="microsoft/Phi-3.5-vision-instruct"):
|
28 |
+
model = models[model_id]
|
29 |
+
processor = processors[model_id]
|
30 |
+
|
31 |
+
prompt = f"{user_prompt}<|image_1|>\n{text_input}{prompt_suffix}{assistant_prompt}"
|
32 |
+
image = Image.fromarray(image).convert("RGB")
|
33 |
+
|
34 |
+
inputs = processor(prompt, image, return_tensors="pt").to("cuda:0")
|
35 |
+
generate_ids = model.generate(**inputs,
|
36 |
+
max_new_tokens=1000,
|
37 |
+
eos_token_id=processor.tokenizer.eos_token_id,
|
38 |
+
)
|
39 |
+
generate_ids = generate_ids[:, inputs['input_ids'].shape[1]:]
|
40 |
+
response = processor.batch_decode(generate_ids,
|
41 |
+
skip_special_tokens=True,
|
42 |
+
clean_up_tokenization_spaces=False)[0]
|
43 |
+
return response
|
44 |
+
|
45 |
+
css = """
|
46 |
+
footer {
|
47 |
+
visibility: hidden;
|
48 |
+
}
|
49 |
+
"""
|
50 |
+
|
51 |
+
with gr.Blocks(theme="Nymbo/Nymbo_Theme", css=css) as demo:
|
52 |
+
with gr.Tab(label="Phi-3.5 Input"):
|
53 |
+
with gr.Row():
|
54 |
+
with gr.Column():
|
55 |
+
input_img = gr.Image(label="Input Picture")
|
56 |
+
model_selector = gr.Dropdown(choices=list(models.keys()), label="Model", value="microsoft/Phi-3.5-vision-instruct")
|
57 |
+
text_input = gr.Textbox(label="Question")
|
58 |
+
submit_btn = gr.Button(value="Submit")
|
59 |
+
with gr.Column():
|
60 |
+
output_text = gr.Textbox(label="Output Text")
|
61 |
+
|
62 |
+
submit_btn.click(run_example, [input_img, text_input, model_selector], [output_text])
|
63 |
+
|
64 |
+
demo.launch(debug=True)
|