Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,54 +1,44 @@
|
|
| 1 |
import gradio as gr
|
| 2 |
import torch
|
| 3 |
-
from
|
|
|
|
|
|
|
| 4 |
import gc
|
| 5 |
|
|
|
|
|
|
|
|
|
|
| 6 |
# Global variables to store model and tokenizer
|
| 7 |
model = None
|
| 8 |
tokenizer = None
|
| 9 |
|
| 10 |
def load_model():
|
| 11 |
-
"""Load the model and tokenizer
|
| 12 |
global model, tokenizer
|
| 13 |
|
| 14 |
if model is None or tokenizer is None:
|
| 15 |
-
print("Loading model and tokenizer...")
|
| 16 |
-
|
| 17 |
-
try:
|
| 18 |
-
# First try to load tokenizer from your model (Unsloth usually includes it)
|
| 19 |
-
tokenizer = AutoTokenizer.from_pretrained("robertnetwork/strudel-medium")
|
| 20 |
-
print("Loaded tokenizer from your model repository")
|
| 21 |
-
except:
|
| 22 |
-
try:
|
| 23 |
-
# Fallback to base Llama 3.1 8B tokenizer
|
| 24 |
-
tokenizer = AutoTokenizer.from_pretrained("unsloth/Meta-Llama-3.1-8B-Instruct")
|
| 25 |
-
print("Loaded tokenizer from unsloth/Meta-Llama-3.1-8B-Instruct")
|
| 26 |
-
except:
|
| 27 |
-
# Final fallback to original Meta tokenizer (requires HF login)
|
| 28 |
-
tokenizer = AutoTokenizer.from_pretrained("meta-llama/Meta-Llama-3.1-8B-Instruct")
|
| 29 |
-
print("Loaded tokenizer from meta-llama/Meta-Llama-3.1-8B-Instruct")
|
| 30 |
-
|
| 31 |
-
# Set pad token if not already set
|
| 32 |
-
if tokenizer.pad_token is None:
|
| 33 |
-
tokenizer.pad_token = tokenizer.eos_token
|
| 34 |
|
| 35 |
-
# Load
|
| 36 |
-
model =
|
| 37 |
-
"robertnetwork/strudel-medium",
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
)
|
| 43 |
|
| 44 |
-
|
|
|
|
|
|
|
|
|
|
| 45 |
|
| 46 |
return model, tokenizer
|
| 47 |
|
| 48 |
|
| 49 |
def respond(
|
| 50 |
message,
|
| 51 |
-
history: list[dict],
|
| 52 |
system_message,
|
| 53 |
max_tokens,
|
| 54 |
temperature,
|
|
@@ -57,16 +47,16 @@ def respond(
|
|
| 57 |
# Load model if not already loaded
|
| 58 |
model, tokenizer = load_model()
|
| 59 |
|
| 60 |
-
# Build conversation history
|
| 61 |
messages = [{"role": "system", "content": system_message}]
|
| 62 |
|
| 63 |
-
# Add history messages
|
| 64 |
messages.extend(history)
|
| 65 |
|
| 66 |
# Add current user message
|
| 67 |
messages.append({"role": "user", "content": message})
|
| 68 |
|
| 69 |
-
# Format messages for the model
|
| 70 |
try:
|
| 71 |
# Try to use the model's chat template if available
|
| 72 |
formatted_prompt = tokenizer.apply_chat_template(
|
|
@@ -85,24 +75,18 @@ def respond(
|
|
| 85 |
formatted_prompt += f"User: {message}\nAssistant: "
|
| 86 |
|
| 87 |
# Tokenize input
|
| 88 |
-
inputs = tokenizer
|
| 89 |
|
| 90 |
-
# Generate response
|
|
|
|
| 91 |
with torch.no_grad():
|
| 92 |
-
# Generate tokens
|
| 93 |
-
|
| 94 |
|
| 95 |
for _ in range(max_tokens):
|
| 96 |
-
# Get current input
|
| 97 |
-
current_input = torch.tensor([generated_ids]).to(model.device)
|
| 98 |
-
|
| 99 |
# Generate next token
|
| 100 |
-
outputs = model(
|
| 101 |
-
logits = outputs.logits[0, -1, :]
|
| 102 |
-
|
| 103 |
-
# Apply temperature
|
| 104 |
-
if temperature != 1.0:
|
| 105 |
-
logits = logits / temperature
|
| 106 |
|
| 107 |
# Apply top-p sampling
|
| 108 |
if top_p < 1.0:
|
|
@@ -119,22 +103,22 @@ def respond(
|
|
| 119 |
|
| 120 |
# Sample next token
|
| 121 |
probs = torch.softmax(logits, dim=-1)
|
| 122 |
-
next_token = torch.multinomial(probs, num_samples=1)
|
| 123 |
|
| 124 |
# Check for end of sequence
|
| 125 |
-
if next_token == tokenizer.eos_token_id:
|
| 126 |
break
|
| 127 |
|
| 128 |
-
|
|
|
|
| 129 |
|
| 130 |
# Decode and yield current response
|
| 131 |
-
|
|
|
|
| 132 |
yield response
|
| 133 |
|
| 134 |
-
#
|
| 135 |
-
del
|
| 136 |
-
if torch.cuda.is_available():
|
| 137 |
-
torch.cuda.empty_cache()
|
| 138 |
|
| 139 |
# Final cleanup
|
| 140 |
gc.collect()
|
|
@@ -145,7 +129,7 @@ demo = gr.ChatInterface(
|
|
| 145 |
respond,
|
| 146 |
additional_inputs=[
|
| 147 |
gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
|
| 148 |
-
gr.Slider(minimum=1, maximum=
|
| 149 |
gr.Slider(minimum=0.1, maximum=2.0, value=0.7, step=0.1, label="Temperature"),
|
| 150 |
gr.Slider(
|
| 151 |
minimum=0.1,
|
|
@@ -155,13 +139,13 @@ demo = gr.ChatInterface(
|
|
| 155 |
label="Top-p (nucleus sampling)",
|
| 156 |
),
|
| 157 |
],
|
| 158 |
-
title="Strudel-Medium Chat (CPU)",
|
| 159 |
-
description="Chat with your fine-tuned
|
| 160 |
-
type="messages"
|
| 161 |
)
|
| 162 |
|
| 163 |
if __name__ == "__main__":
|
| 164 |
# Pre-load the model when the app starts
|
| 165 |
-
print("Starting application and loading model...")
|
| 166 |
load_model()
|
| 167 |
demo.launch()
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
import torch
|
| 3 |
+
from unsloth import FastLanguageModel
|
| 4 |
+
from transformers import TextStreamer
|
| 5 |
+
import locale
|
| 6 |
import gc
|
| 7 |
|
| 8 |
+
# Set UTF-8 locale to avoid encoding issues
|
| 9 |
+
locale.getpreferredencoding = lambda: "UTF-8"
|
| 10 |
+
|
| 11 |
# Global variables to store model and tokenizer
|
| 12 |
model = None
|
| 13 |
tokenizer = None
|
| 14 |
|
| 15 |
def load_model():
|
| 16 |
+
"""Load the LoRA model and tokenizer using Unsloth"""
|
| 17 |
global model, tokenizer
|
| 18 |
|
| 19 |
if model is None or tokenizer is None:
|
| 20 |
+
print("Loading LoRA model and tokenizer with Unsloth...")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 21 |
|
| 22 |
+
# Load the LoRA model using Unsloth
|
| 23 |
+
model, tokenizer = FastLanguageModel.from_pretrained(
|
| 24 |
+
model_name="robertnetwork/strudel-medium", # Your LoRA adapter
|
| 25 |
+
max_seq_length=2048, # Adjust based on your needs
|
| 26 |
+
dtype=None, # Auto-detect
|
| 27 |
+
load_in_4bit=False, # Set to False for CPU usage
|
| 28 |
+
device_map="cpu"
|
| 29 |
)
|
| 30 |
|
| 31 |
+
# Enable faster inference
|
| 32 |
+
FastLanguageModel.for_inference(model)
|
| 33 |
+
|
| 34 |
+
print("LoRA model loaded successfully!")
|
| 35 |
|
| 36 |
return model, tokenizer
|
| 37 |
|
| 38 |
|
| 39 |
def respond(
|
| 40 |
message,
|
| 41 |
+
history: list[dict],
|
| 42 |
system_message,
|
| 43 |
max_tokens,
|
| 44 |
temperature,
|
|
|
|
| 47 |
# Load model if not already loaded
|
| 48 |
model, tokenizer = load_model()
|
| 49 |
|
| 50 |
+
# Build conversation history
|
| 51 |
messages = [{"role": "system", "content": system_message}]
|
| 52 |
|
| 53 |
+
# Add history messages
|
| 54 |
messages.extend(history)
|
| 55 |
|
| 56 |
# Add current user message
|
| 57 |
messages.append({"role": "user", "content": message})
|
| 58 |
|
| 59 |
+
# Format messages for the model
|
| 60 |
try:
|
| 61 |
# Try to use the model's chat template if available
|
| 62 |
formatted_prompt = tokenizer.apply_chat_template(
|
|
|
|
| 75 |
formatted_prompt += f"User: {message}\nAssistant: "
|
| 76 |
|
| 77 |
# Tokenize input
|
| 78 |
+
inputs = tokenizer(formatted_prompt, return_tensors="pt", truncate=True)
|
| 79 |
|
| 80 |
+
# Generate response with streaming
|
| 81 |
+
response = ""
|
| 82 |
with torch.no_grad():
|
| 83 |
+
# Generate tokens iteratively for streaming effect
|
| 84 |
+
input_ids = inputs["input_ids"]
|
| 85 |
|
| 86 |
for _ in range(max_tokens):
|
|
|
|
|
|
|
|
|
|
| 87 |
# Generate next token
|
| 88 |
+
outputs = model(input_ids)
|
| 89 |
+
logits = outputs.logits[0, -1, :] / temperature
|
|
|
|
|
|
|
|
|
|
|
|
|
| 90 |
|
| 91 |
# Apply top-p sampling
|
| 92 |
if top_p < 1.0:
|
|
|
|
| 103 |
|
| 104 |
# Sample next token
|
| 105 |
probs = torch.softmax(logits, dim=-1)
|
| 106 |
+
next_token = torch.multinomial(probs, num_samples=1)
|
| 107 |
|
| 108 |
# Check for end of sequence
|
| 109 |
+
if next_token.item() == tokenizer.eos_token_id:
|
| 110 |
break
|
| 111 |
|
| 112 |
+
# Append to input for next iteration
|
| 113 |
+
input_ids = torch.cat([input_ids, next_token.unsqueeze(0)], dim=-1)
|
| 114 |
|
| 115 |
# Decode and yield current response
|
| 116 |
+
new_text = tokenizer.decode(next_token, skip_special_tokens=True)
|
| 117 |
+
response += new_text
|
| 118 |
yield response
|
| 119 |
|
| 120 |
+
# Cleanup
|
| 121 |
+
del outputs, logits, probs
|
|
|
|
|
|
|
| 122 |
|
| 123 |
# Final cleanup
|
| 124 |
gc.collect()
|
|
|
|
| 129 |
respond,
|
| 130 |
additional_inputs=[
|
| 131 |
gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
|
| 132 |
+
gr.Slider(minimum=1, maximum=256, value=128, step=1, label="Max new tokens"),
|
| 133 |
gr.Slider(minimum=0.1, maximum=2.0, value=0.7, step=0.1, label="Temperature"),
|
| 134 |
gr.Slider(
|
| 135 |
minimum=0.1,
|
|
|
|
| 139 |
label="Top-p (nucleus sampling)",
|
| 140 |
),
|
| 141 |
],
|
| 142 |
+
title="Strudel-Medium LoRA Chat (CPU)",
|
| 143 |
+
description="Chat with your Unsloth fine-tuned LoRA model running on CPU",
|
| 144 |
+
type="messages"
|
| 145 |
)
|
| 146 |
|
| 147 |
if __name__ == "__main__":
|
| 148 |
# Pre-load the model when the app starts
|
| 149 |
+
print("Starting application and loading LoRA model...")
|
| 150 |
load_model()
|
| 151 |
demo.launch()
|