Spaces:
Paused
Paused
Update app.py
Browse files
app.py
CHANGED
@@ -1,50 +1,49 @@
|
|
1 |
-
import os
|
2 |
import torch
|
|
|
|
|
3 |
import gradio as gr
|
4 |
-
|
5 |
-
|
6 |
-
|
7 |
-
|
8 |
-
|
9 |
-
|
10 |
-
|
11 |
-
model =
|
12 |
-
|
13 |
-
|
14 |
-
|
15 |
-
|
16 |
-
|
17 |
-
|
18 |
-
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
|
36 |
-
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
-
|
41 |
-
|
42 |
-
|
43 |
-
|
44 |
-
|
45 |
-
|
46 |
-
|
47 |
-
|
48 |
-
|
49 |
-
# Launch the interface on Hugging Face Spaces
|
50 |
-
iface.launch(share=True) # To create a public link, set share=True
|
|
|
|
|
1 |
import torch
|
2 |
+
from transformers import AutoProcessor, AutoModelForImageTextToText, TextStreamer
|
3 |
+
from peft import PeftModel
|
4 |
import gradio as gr
|
5 |
+
|
6 |
+
# Load base model and processor
|
7 |
+
base_model_id = "unsloth/gemma-3-12b-it-unsloth-bnb-4bit"
|
8 |
+
adapter_model_id = "adarsh3601/my_gemma_pt3"
|
9 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
10 |
+
|
11 |
+
processor = AutoProcessor.from_pretrained(base_model_id)
|
12 |
+
model = AutoModelForImageTextToText.from_pretrained(base_model_id, torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32, device_map="auto")
|
13 |
+
|
14 |
+
# Apply adapter (LoRA)
|
15 |
+
model = PeftModel.from_pretrained(model, adapter_model_id)
|
16 |
+
model.eval()
|
17 |
+
|
18 |
+
streamer = TextStreamer(processor.tokenizer, skip_prompt=True, skip_special_tokens=True)
|
19 |
+
|
20 |
+
# Helper to format messages using the chat template
|
21 |
+
def format_chat(messages):
|
22 |
+
formatted = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
|
23 |
+
return formatted
|
24 |
+
|
25 |
+
# Chat function
|
26 |
+
def chat(message, history):
|
27 |
+
messages = []
|
28 |
+
|
29 |
+
# Format history into messages
|
30 |
+
for user_msg, bot_msg in history:
|
31 |
+
messages.append({"role": "user", "content": user_msg})
|
32 |
+
messages.append({"role": "assistant", "content": bot_msg})
|
33 |
+
|
34 |
+
messages.append({"role": "user", "content": message})
|
35 |
+
prompt = format_chat(messages)
|
36 |
+
|
37 |
+
inputs = processor(prompt, return_tensors="pt").to(device)
|
38 |
+
|
39 |
+
with torch.no_grad():
|
40 |
+
outputs = model.generate(**inputs, max_new_tokens=512, streamer=streamer)
|
41 |
+
|
42 |
+
decoded = processor.batch_decode(outputs, skip_special_tokens=True)[0]
|
43 |
+
response = decoded.split("<end_of_turn>")[0].strip().split("<start_of_turn>model")[-1].strip()
|
44 |
+
return response
|
45 |
+
|
46 |
+
# Gradio interface
|
47 |
+
gui = gr.ChatInterface(fn=chat, title="Gemma-3 Chatbot", description="Fine-tuned on adarsh3601/my_gemma_pt3")
|
48 |
+
|
49 |
+
gui.launch()
|
|
|
|