jonaschua commited on
Commit
537b454
·
verified ·
1 Parent(s): 7966586

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +91 -125
app.py CHANGED
@@ -1,135 +1,101 @@
1
- import gradio as gr
2
- from huggingface_hub import InferenceClient
3
- import spaces #0.32.0
4
- import torch
5
- import os
6
- import platform
7
- import requests
8
  from PIL import Image
 
 
 
 
 
 
 
 
 
 
 
9
 
10
 
11
- model = ""
12
- duration = None
13
- token = os.getenv('deepseekv2')
14
- provider = None #'fal-ai' #None #replicate # sambanova
15
- mode = "text-to-text"
16
-
17
- print(f"Is CUDA available: {torch.cuda.is_available()}")
18
- print(f"CUDA device: {torch.cuda.get_device_name(torch.cuda.current_device())}")
19
- print(f"CUDA version: {torch.version.cuda}")
20
- print(f"Python version: {platform.python_version()}")
21
- print(f"Pytorch version: {torch.__version__}")
22
- print(f"Gradio version: {gr. __version__}")
23
- # print(f"HFhub version: {huggingface_hub.__version__}")
24
-
25
-
26
- """
27
- Packages ::::::::::
28
- Is CUDA available: True
29
- CUDA device: NVIDIA A100-SXM4-80GB MIG 3g.40gb
30
- CUDA version: 12.1
31
- Python version: 3.10.13
32
- Pytorch version: 2.4.0+cu121
33
- Gradio version: 5.0.1
34
- """
35
-
36
-
37
- def choose_model(model_name):
38
- if model_name == "DeepSeek-R1-Distill-Qwen-1.5B":
39
- model = "deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B"
40
-
41
- elif model_name == "DeepSeek-R1-Distill-Qwen-32B":
42
- model = "deepseek-ai/DeepSeek-R1-Distill-Qwen-32B"
43
-
44
- elif model_name == "Llama3-8b-Instruct":
45
- model = "meta-llama/Meta-Llama-3-8B-Instruct"
46
-
47
- elif model_name == "Llama3.1-8b-Instruct":
48
- model = "meta-llama/Llama-3.1-8B-Instruct"
49
-
50
- elif model_name == "Llama2-13b-chat":
51
- model = "meta-llama/Llama-2-13b-chat-hf"
52
-
53
- elif model_name == "Llama-3.2-11B-Vision-Instruct":
54
- model = "meta-llama/Llama-3.2-11B-Vision-Instruct"
55
- mode = "image-to-text"
56
- return model
57
-
58
- elif model_name == "Gemma-2-2b":
59
- model = "google/gemma-2-2b-it"
60
-
61
- elif model_name == "Gemma-7b":
62
- model = "google/gemma-7b"
63
 
64
- elif model_name == "Mixtral-8x7B-Instruct":
65
- model = "mistralai/Mixtral-8x7B-Instruct-v0.1"
66
-
67
- elif model_name == "Microsoft-phi-2":
68
- model = "microsoft/phi-2"
69
-
70
- elif model_name == "Qwen2.5-Coder-32B-Instruct":
71
- model = "Qwen/Qwen2.5-Coder-32B-Instruct"
72
-
73
- else: # default to zephyr if no model chosen
74
- model = "HuggingFaceH4/zephyr-7b-beta"
75
-
76
- mode = "text-to-text"
77
- return model
78
 
79
-
80
- @spaces.GPU(duration=duration)
81
- def respond(message, history: list[tuple[str, str]], image=None, model, system_message, max_tokens, temperature, top_p):
82
-
83
- print(model)
84
- model_name = choose_model(model)
85
-
86
- client = InferenceClient(model_name, provider=provider, token=os.getenv('deepseekv2'))
87
 
88
- messages = [{"role": "system", "content": system_message}]
89
-
90
- for val in history:
91
- if val[0]:
92
- messages.append({"role": "user", "content": val[0]})
93
- if val[1]:
94
- messages.append({"role": "assistant", "content": val[1]})
95
-
96
- messages.append({"role": "user", "content": message})
97
-
98
- response = ""
99
-
100
- for message in client.chat_completion(messages, max_tokens=max_tokens, stream=True, temperature=temperature, top_p=top_p):
101
- token = message.choices[0].delta.content
102
-
103
- response += token
104
- yield response
105
 
106
- # else:
107
- # url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/0052a70beed5bf71b92610a43a52df6d286cd5f3/diffusers/rabbit.jpg"
108
- # image = Image.open(requests.get(url, stream=True).raw)
109
-
110
-
111
- demo = gr.ChatInterface(
112
-
113
- respond,
114
- input_components=[gr.Textbox(label="Message"), gr.Image(label="image", type="pil")],
115
- multimodal=True,
116
- stop_btn = "Stop generation",
117
- # multimodal = True,
118
- title="Ask me anything",
119
- description="Hi there! I am your friendly AI chatbot. Choose from different language models under the Additional Inputs tab below.",
120
- examples=[["Explain quantum computing"], ["Explain forex trading"], ["What is the capital of China?"], ["Make a poem about nature"]],
121
- additional_inputs=[
122
- gr.Dropdown(["DeepSeek-R1-Distill-Qwen-1.5B", "DeepSeek-R1-Distill-Qwen-32B", "Gemma-2-2b", "Gemma-7b", "Llama2-13b-chat", "Llama3-8b-Instruct", "Llama3.1-8b-Instruct", "Llama-3.2-11B-Vision-Instruct", "Microsoft-phi-2", "Mixtral-8x7B-Instruct", "Qwen2.5-Coder-32B-Instruct", "Zephyr-7b-beta"], label="Select Model"),
123
- gr.Textbox(value="You are a friendly and helpful Chatbot, be concise and straight to the point, avoid excessive reasoning.", label="System message"),
124
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
125
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
126
- gr.Slider(minimum=0.1, maximum=1.0, value=0.95, step=0.05, label="Top-p (nucleus sampling)")
127
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
128
  ],
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
129
 
130
-
131
- )
132
-
133
-
134
- if __name__ == "__main__":
135
- demo.launch(share=True)
 
1
+ from transformers import MllamaForConditionalGeneration, AutoProcessor, TextIteratorStreamer
 
 
 
 
 
 
2
  from PIL import Image
3
+ import requests
4
+ import torch
5
+ from threading import Thread
6
+ import gradio as gr
7
+ from gradio import FileData
8
+ import time
9
+ import spaces
10
+ ckpt = "meta-llama/Llama-3.2-11B-Vision-Instruct"
11
+ model = MllamaForConditionalGeneration.from_pretrained(ckpt,
12
+ torch_dtype=torch.bfloat16).to("cuda")
13
+ processor = AutoProcessor.from_pretrained(ckpt)
14
 
15
 
16
+ @spaces.GPU
17
+ def bot_streaming(message, history, max_new_tokens=250):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18
 
19
+ txt = message["text"]
20
+ ext_buffer = f"{txt}"
 
 
 
 
 
 
 
 
 
 
 
 
21
 
22
+ messages= []
23
+ images = []
 
 
 
 
 
 
24
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25
 
26
+ for i, msg in enumerate(history):
27
+ if isinstance(msg[0], tuple):
28
+ messages.append({"role": "user", "content": [{"type": "text", "text": history[i+1][0]}, {"type": "image"}]})
29
+ messages.append({"role": "assistant", "content": [{"type": "text", "text": history[i+1][1]}]})
30
+ images.append(Image.open(msg[0][0]).convert("RGB"))
31
+ elif isinstance(history[i-1], tuple) and isinstance(msg[0], str):
32
+ # messages are already handled
33
+ pass
34
+ elif isinstance(history[i-1][0], str) and isinstance(msg[0], str): # text only turn
35
+ messages.append({"role": "user", "content": [{"type": "text", "text": msg[0]}]})
36
+ messages.append({"role": "assistant", "content": [{"type": "text", "text": msg[1]}]})
37
+
38
+ # add current message
39
+ if len(message["files"]) == 1:
 
 
 
 
 
 
 
40
 
41
+ if isinstance(message["files"][0], str): # examples
42
+ image = Image.open(message["files"][0]).convert("RGB")
43
+ else: # regular input
44
+ image = Image.open(message["files"][0]["path"]).convert("RGB")
45
+ images.append(image)
46
+ messages.append({"role": "user", "content": [{"type": "text", "text": txt}, {"type": "image"}]})
47
+ else:
48
+ messages.append({"role": "user", "content": [{"type": "text", "text": txt}]})
49
+
50
+
51
+ texts = processor.apply_chat_template(messages, add_generation_prompt=True)
52
+
53
+ if images == []:
54
+ inputs = processor(text=texts, return_tensors="pt").to("cuda")
55
+ else:
56
+ inputs = processor(text=texts, images=images, return_tensors="pt").to("cuda")
57
+ streamer = TextIteratorStreamer(processor, skip_special_tokens=True, skip_prompt=True)
58
+
59
+ generation_kwargs = dict(inputs, streamer=streamer, max_new_tokens=max_new_tokens)
60
+ generated_text = ""
61
+
62
+ thread = Thread(target=model.generate, kwargs=generation_kwargs)
63
+ thread.start()
64
+ buffer = ""
65
+
66
+ for new_text in streamer:
67
+ buffer += new_text
68
+ generated_text_without_prompt = buffer
69
+ time.sleep(0.01)
70
+ yield buffer
71
+
72
+
73
+ demo = gr.ChatInterface(fn=bot_streaming, title="Multimodal Llama", examples=[
74
+ [{"text": "Which era does this piece belong to? Give details about the era.", "files":["./examples/rococo.jpg"]},
75
+ 200],
76
+ [{"text": "Where do the droughts happen according to this diagram?", "files":["./examples/weather_events.png"]},
77
+ 250],
78
+ [{"text": "What happens when you take out white cat from this chain?", "files":["./examples/ai2d_test.jpg"]},
79
+ 250],
80
+ [{"text": "How long does it take from invoice date to due date? Be short and concise.", "files":["./examples/invoice.png"]},
81
+ 250],
82
+ [{"text": "Where to find this monument? Can you give me other recommendations around the area?", "files":["./examples/wat_arun.jpg"]},
83
+ 250],
84
  ],
85
+ textbox=gr.MultimodalTextbox(),
86
+ additional_inputs = [gr.Slider(
87
+ minimum=10,
88
+ maximum=500,
89
+ value=250,
90
+ step=10,
91
+ label="Maximum number of new tokens to generate",
92
+ )
93
+ ],
94
+ cache_examples=False,
95
+ description="Try Multimodal Llama by Meta with transformers in this demo. Upload an image, and start chatting about it, or simply try one of the examples below. To learn more about Llama Vision, visit [our blog post](https://huggingface.co/blog/llama32). ",
96
+ stop_btn="Stop Generation",
97
+ fill_height=True,
98
+ multimodal=True)
99
+
100
+ demo.launch(debug=True)
101