sagar007 commited on
Commit
bf55041
·
verified ·
1 Parent(s): c1e3d0c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +251 -162
app.py CHANGED
@@ -1,184 +1,273 @@
1
  import gradio as gr
2
  import torch
3
- from transformers import AutoModelForCausalLM, AutoTokenizer, AutoProcessor
4
  from PIL import Image
5
- import os
6
  import spaces
 
7
 
8
- # Initial setup without loading model to device
9
- print("Setting up the application...")
10
 
11
- # We'll load the model in the GPU functions to avoid CPU memory issues
12
- model = None
13
- tokenizer = AutoTokenizer.from_pretrained("sagar007/Lava_phi")
14
- processor = AutoProcessor.from_pretrained("openai/clip-vit-base-patch32")
15
-
16
- print("Tokenizer and processor loaded successfully!")
17
-
18
- # For text-only generation with GPU on demand
19
- @spaces.GPU
20
- def generate_text(prompt, max_length=128):
21
- try:
22
- global model
23
 
24
- # Load model if not already loaded
25
- if model is None:
26
- print("Loading model on first request...")
27
- model = AutoModelForCausalLM.from_pretrained(
28
- "sagar007/Lava_phi",
29
- torch_dtype=torch.float16, # Use float16 on GPU
30
- device_map="auto" # This will put the model on GPU automatically
31
- )
32
- print("Model loaded successfully!")
33
 
34
- inputs = tokenizer(f"human: {prompt}\ngpt:", return_tensors="pt").to(model.device)
 
 
 
 
 
 
35
 
36
- # Generate with GPU
37
- with torch.no_grad():
38
- outputs = model.generate(
39
- **inputs,
40
- max_new_tokens=max_length,
41
- do_sample=True,
42
- temperature=0.7,
43
- top_p=0.9,
 
 
 
 
 
 
 
44
  )
45
-
46
- generated_text = tokenizer.decode(outputs[0], skip_special_tokens=True)
47
-
48
- # Extract only the model's response
49
- if "gpt:" in generated_text:
50
- generated_text = generated_text.split("gpt:", 1)[1].strip()
51
 
52
- return generated_text
53
- except Exception as e:
54
- # Capture and return any errors
55
- return f"Error generating text: {str(e)}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
56
 
57
- # For image and text processing with GPU on demand
58
- @spaces.GPU
59
- def process_image_and_prompt(image, prompt, max_length=128):
60
  try:
61
- if image is None:
62
- return "No image provided. Please upload an image."
63
 
64
- global model
65
-
66
- # Load model if not already loaded
67
- if model is None:
68
- print("Loading model on first request...")
69
- model = AutoModelForCausalLM.from_pretrained(
70
- "sagar007/Lava_phi",
71
- torch_dtype=torch.float16, # Use float16 on GPU
72
- device_map="auto" # This will put the model on GPU automatically
73
  )
74
- print("Model loaded successfully!")
75
-
76
- # Process image
77
- image_tensor = processor(images=image, return_tensors="pt").pixel_values.to(model.device)
78
-
79
- # Tokenize input with image token
80
- inputs = tokenizer(f"human: <image>\n{prompt}\ngpt:", return_tensors="pt").to(model.device)
81
-
82
- # Generate with GPU
83
- with torch.no_grad():
84
- outputs = model.generate(
85
- input_ids=inputs["input_ids"],
86
- attention_mask=inputs["attention_mask"],
87
- images=image_tensor,
88
- max_new_tokens=max_length,
89
- do_sample=True,
90
- temperature=0.7,
91
- top_p=0.9,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
92
  )
93
-
94
- generated_text = tokenizer.decode(outputs[0], skip_special_tokens=True)
95
-
96
- # Extract only the model's response
97
- if "gpt:" in generated_text:
98
- generated_text = generated_text.split("gpt:", 1)[1].strip()
99
 
100
- return generated_text
101
  except Exception as e:
102
- # Capture and return any errors
103
- return f"Error processing image: {str(e)}"
104
-
105
- # Create Gradio Interface
106
- with gr.Blocks(title="LLaVA-Phi: Vision-Language Model") as demo:
107
- gr.Markdown("# LLaVA-Phi: Vision-Language Model")
108
- gr.Markdown("This model uses ZeroGPU technology - GPU resources are allocated only when generating responses and released afterward.")
109
-
110
- with gr.Tab("Text Generation"):
111
- with gr.Row():
112
- with gr.Column():
113
- text_input = gr.Textbox(label="Enter your prompt", lines=3, placeholder="What is artificial intelligence?")
114
- text_max_length = gr.Slider(minimum=16, maximum=512, value=128, step=8, label="Maximum response length")
115
- text_button = gr.Button("Generate")
116
-
117
- with gr.Column():
118
- text_output = gr.Textbox(label="Generated response", lines=8)
119
- text_status = gr.Markdown("*Status: Ready*")
120
-
121
- def text_fn(prompt, max_length):
122
- text_status.update("*Status: Generating response...*")
123
- try:
124
- response = generate_text(prompt, max_length)
125
- text_status.update("*Status: Complete*")
126
- return response
127
- except Exception as e:
128
- text_status.update("*Status: Error*")
129
- return f"Error: {str(e)}"
130
-
131
- text_button.click(
132
- fn=text_fn,
133
- inputs=[text_input, text_max_length],
134
- outputs=text_output
135
- )
136
-
137
- with gr.Tab("Image + Text Analysis"):
138
- with gr.Row():
139
- with gr.Column():
140
- image_input = gr.Image(type="pil", label="Upload an image")
141
- image_text_input = gr.Textbox(label="Enter your prompt about the image",
142
- lines=2,
143
- placeholder="Describe this image in detail.")
144
- image_max_length = gr.Slider(minimum=16, maximum=512, value=128, step=8, label="Maximum response length")
145
- image_button = gr.Button("Analyze")
146
-
147
- with gr.Column():
148
- image_output = gr.Textbox(label="Model response", lines=8)
149
- image_status = gr.Markdown("*Status: Ready*")
150
-
151
- def image_fn(image, prompt, max_length):
152
- image_status.update("*Status: Analyzing image...*")
153
- try:
154
- response = process_image_and_prompt(image, prompt, max_length)
155
- image_status.update("*Status: Complete*")
156
- return response
157
- except Exception as e:
158
- image_status.update("*Status: Error*")
159
- return f"Error: {str(e)}"
160
-
161
- image_button.click(
162
- fn=image_fn,
163
- inputs=[image_input, image_text_input, image_max_length],
164
- outputs=image_output
165
- )
166
-
167
- # Example inputs for each tab
168
- gr.Examples(
169
- examples=["What is the advantage of vision-language models?",
170
- "Explain how multimodal AI models work.",
171
- "Tell me a short story about robots."],
172
- inputs=text_input
173
- )
174
-
175
- # Status indicator
176
- with gr.Row():
177
- gr.Markdown("*Note: When you click Generate or Analyze, a GPU will be temporarily allocated to process your request and then released. The first request may take longer as the model needs to be loaded.*")
178
 
179
- # Launch the app
180
  if __name__ == "__main__":
 
181
  demo.launch(
182
- enable_queue=True,
183
- show_error=True
 
184
  )
 
1
  import gradio as gr
2
  import torch
3
+ from transformers import AutoModelForCausalLM, AutoTokenizer, CLIPProcessor, CLIPModel
4
  from PIL import Image
5
+ import logging
6
  import spaces
7
+ import numpy
8
 
9
+ # Setup logging
10
+ logging.basicConfig(level=logging.INFO)
11
 
12
+ class LLaVAPhiModel:
13
+ def __init__(self, model_id="sagar007/Lava_phi"):
14
+ self.device = "cuda"
15
+ self.model_id = model_id
16
+ logging.info("Initializing LLaVA-Phi model...")
 
 
 
 
 
 
 
17
 
18
+ # Initialize tokenizer
19
+ self.tokenizer = AutoTokenizer.from_pretrained(model_id)
20
+ if self.tokenizer.pad_token is None:
21
+ self.tokenizer.pad_token = self.tokenizer.eos_token
 
 
 
 
 
22
 
23
+ try:
24
+ # Use CLIPProcessor directly instead of AutoProcessor
25
+ self.processor = CLIPProcessor.from_pretrained("openai/clip-vit-base-patch32")
26
+ logging.info("Successfully loaded CLIP processor")
27
+ except Exception as e:
28
+ logging.error(f"Failed to load CLIP processor: {str(e)}")
29
+ self.processor = None
30
 
31
+ self.history = []
32
+ self.model = None
33
+ self.clip = None
34
+
35
+ @spaces.GPU
36
+ def ensure_models_loaded(self):
37
+ """Ensure models are loaded in GPU context"""
38
+ if self.model is None:
39
+ # Load main model with updated quantization config
40
+ from transformers import BitsAndBytesConfig
41
+ quantization_config = BitsAndBytesConfig(
42
+ load_in_4bit=True,
43
+ bnb_4bit_compute_dtype=torch.float16,
44
+ bnb_4bit_use_double_quant=True,
45
+ bnb_4bit_quant_type="nf4"
46
  )
 
 
 
 
 
 
47
 
48
+ try:
49
+ self.model = AutoModelForCausalLM.from_pretrained(
50
+ self.model_id,
51
+ quantization_config=quantization_config,
52
+ device_map="auto",
53
+ torch_dtype=torch.bfloat16,
54
+ trust_remote_code=True
55
+ )
56
+ self.model.config.pad_token_id = self.tokenizer.eos_token_id
57
+ logging.info("Successfully loaded main model")
58
+ except Exception as e:
59
+ logging.error(f"Failed to load main model: {str(e)}")
60
+ raise
61
+
62
+ if self.clip is None:
63
+ try:
64
+ # Use CLIPModel directly instead of AutoModel
65
+ self.clip = CLIPModel.from_pretrained("openai/clip-vit-base-patch32").to(self.device)
66
+ logging.info("Successfully loaded CLIP model")
67
+ except Exception as e:
68
+ logging.error(f"Failed to load CLIP model: {str(e)}")
69
+ self.clip = None
70
+
71
+ @spaces.GPU
72
+ def process_image(self, image):
73
+ """Process image through CLIP if available"""
74
+ try:
75
+ self.ensure_models_loaded()
76
+
77
+ if self.clip is None or self.processor is None:
78
+ logging.warning("CLIP model or processor not available")
79
+ return None
80
+
81
+ # Convert image to correct format
82
+ if isinstance(image, str):
83
+ image = Image.open(image)
84
+ elif isinstance(image, numpy.ndarray):
85
+ image = Image.fromarray(image)
86
+
87
+ # Ensure image is in RGB mode
88
+ if image.mode != 'RGB':
89
+ image = image.convert('RGB')
90
+
91
+ with torch.no_grad():
92
+ try:
93
+ # Process image with error handling
94
+ image_inputs = self.processor(images=image, return_tensors="pt")
95
+ image_features = self.clip.get_image_features(
96
+ pixel_values=image_inputs.pixel_values.to(self.device)
97
+ )
98
+ logging.info("Successfully processed image through CLIP")
99
+ return image_features
100
+ except Exception as e:
101
+ logging.error(f"Error during image processing: {str(e)}")
102
+ return None
103
+ except Exception as e:
104
+ logging.error(f"Error in process_image: {str(e)}")
105
+ return None
106
+
107
+ @spaces.GPU(duration=120)
108
+ def generate_response(self, message, image=None):
109
+ try:
110
+ self.ensure_models_loaded()
111
+
112
+ if image is not None:
113
+ image_features = self.process_image(image)
114
+ has_image = image_features is not None
115
+ if not has_image:
116
+ message = "Note: Image processing is not available - continuing with text only.\n" + message
117
+
118
+ prompt = f"human: {'<image>' if has_image else ''}\n{message}\ngpt:"
119
+ context = ""
120
+ for turn in self.history[-3:]:
121
+ context += f"human: {turn[0]}\ngpt: {turn[1]}\n"
122
+
123
+ full_prompt = context + prompt
124
+ inputs = self.tokenizer(
125
+ full_prompt,
126
+ return_tensors="pt",
127
+ padding=True,
128
+ truncation=True,
129
+ max_length=512
130
+ )
131
+ inputs = {k: v.to(self.device) for k, v in inputs.items()}
132
+
133
+ if has_image:
134
+ inputs["image_features"] = image_features
135
+
136
+ with torch.no_grad():
137
+ outputs = self.model.generate(
138
+ **inputs,
139
+ max_new_tokens=256,
140
+ min_length=20,
141
+ temperature=0.7,
142
+ do_sample=True,
143
+ top_p=0.9,
144
+ top_k=40,
145
+ repetition_penalty=1.5,
146
+ no_repeat_ngram_size=3,
147
+ use_cache=True,
148
+ pad_token_id=self.tokenizer.pad_token_id,
149
+ eos_token_id=self.tokenizer.eos_token_id
150
+ )
151
+ else:
152
+ prompt = f"human: {message}\ngpt:"
153
+ context = ""
154
+ for turn in self.history[-3:]:
155
+ context += f"human: {turn[0]}\ngpt: {turn[1]}\n"
156
+
157
+ full_prompt = context + prompt
158
+ inputs = self.tokenizer(
159
+ full_prompt,
160
+ return_tensors="pt",
161
+ padding=True,
162
+ truncation=True,
163
+ max_length=512
164
+ )
165
+ inputs = {k: v.to(self.device) for k, v in inputs.items()}
166
+
167
+ with torch.no_grad():
168
+ outputs = self.model.generate(
169
+ **inputs,
170
+ max_new_tokens=150,
171
+ min_length=20,
172
+ temperature=0.6,
173
+ do_sample=True,
174
+ top_p=0.85,
175
+ top_k=30,
176
+ repetition_penalty=1.8,
177
+ no_repeat_ngram_size=4,
178
+ use_cache=True,
179
+ pad_token_id=self.tokenizer.pad_token_id,
180
+ eos_token_id=self.tokenizer.eos_token_id
181
+ )
182
+
183
+ response = self.tokenizer.decode(outputs[0], skip_special_tokens=True)
184
+
185
+ # Clean up response
186
+ if "gpt:" in response:
187
+ response = response.split("gpt:")[-1].strip()
188
+ if "human:" in response:
189
+ response = response.split("human:")[0].strip()
190
+ if "<image>" in response:
191
+ response = response.replace("<image>", "").strip()
192
+
193
+ self.history.append((message, response))
194
+ return response
195
+
196
+ except Exception as e:
197
+ logging.error(f"Error generating response: {str(e)}")
198
+ logging.error(f"Full traceback:", exc_info=True)
199
+ return f"Error: {str(e)}"
200
+
201
+ def clear_history(self):
202
+ self.history = []
203
+ return None
204
 
205
+ def create_demo():
 
 
206
  try:
207
+ model = LLaVAPhiModel()
 
208
 
209
+ with gr.Blocks(css="footer {visibility: hidden}") as demo:
210
+ gr.Markdown(
211
+ """
212
+ # LLaVA-Phi Demo (ZeroGPU)
213
+ Chat with a vision-language model that can understand both text and images.
214
+ """
 
 
 
215
  )
216
+
217
+ chatbot = gr.Chatbot(height=400)
218
+ with gr.Row():
219
+ with gr.Column(scale=0.7):
220
+ msg = gr.Textbox(
221
+ show_label=False,
222
+ placeholder="Enter text and/or upload an image",
223
+ container=False
224
+ )
225
+ with gr.Column(scale=0.15, min_width=0):
226
+ clear = gr.Button("Clear")
227
+ with gr.Column(scale=0.15, min_width=0):
228
+ submit = gr.Button("Submit", variant="primary")
229
+
230
+ image = gr.Image(type="pil", label="Upload Image (Optional)")
231
+
232
+ def respond(message, chat_history, image):
233
+ if not message and image is None:
234
+ return chat_history
235
+
236
+ response = model.generate_response(message, image)
237
+ chat_history.append((message, response))
238
+ return "", chat_history
239
+
240
+ def clear_chat():
241
+ model.clear_history()
242
+ return None, None
243
+
244
+ submit.click(
245
+ respond,
246
+ [msg, chatbot, image],
247
+ [msg, chatbot],
248
+ )
249
+
250
+ clear.click(
251
+ clear_chat,
252
+ None,
253
+ [chatbot, image],
254
+ )
255
+
256
+ msg.submit(
257
+ respond,
258
+ [msg, chatbot, image],
259
+ [msg, chatbot],
260
  )
 
 
 
 
 
 
261
 
262
+ return demo
263
  except Exception as e:
264
+ logging.error(f"Error creating demo: {str(e)}")
265
+ raise
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
266
 
 
267
  if __name__ == "__main__":
268
+ demo = create_demo()
269
  demo.launch(
270
+ server_name="0.0.0.0",
271
+ server_port=7860,
272
+ share=True
273
  )