Spaces:
Running

robertnetwork commited on
Commit
89ddab3
·
verified ·
1 Parent(s): 9a834d9

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +23 -133
app.py CHANGED
@@ -1,151 +1,41 @@
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,
45
- top_p,
46
- ):
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(
63
- messages,
64
- tokenize=False,
65
- add_generation_prompt=True
66
  )
67
- except:
68
- # Fallback formatting if chat template is not available
69
- formatted_prompt = system_message + "\n\n"
70
- for msg in history:
71
- if msg["role"] == "user":
72
- formatted_prompt += f"User: {msg['content']}\n"
73
- elif msg["role"] == "assistant":
74
- formatted_prompt += f"Assistant: {msg['content']}\n"
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:
93
- sorted_logits, sorted_indices = torch.sort(logits, descending=True)
94
- cumulative_probs = torch.cumsum(torch.softmax(sorted_logits, dim=-1), dim=-1)
95
-
96
- # Remove tokens with cumulative probability above the threshold
97
- sorted_indices_to_remove = cumulative_probs > top_p
98
- sorted_indices_to_remove[1:] = sorted_indices_to_remove[:-1].clone()
99
- sorted_indices_to_remove[0] = 0
100
-
101
- indices_to_remove = sorted_indices[sorted_indices_to_remove]
102
- logits[indices_to_remove] = float('-inf')
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()
125
-
126
-
127
- # Create the interface
128
- demo = gr.ChatInterface(
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,
136
- maximum=1.0,
137
- value=0.95,
138
- step=0.05,
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()
 
1
  import gradio as gr
2
  import torch
3
+ from transformers import AutoTokenizer, AutoModelForCausalLM
4
+ from peft import PeftModel
 
5
  import gc
6
 
 
 
 
7
  # Global variables to store model and tokenizer
8
  model = None
9
  tokenizer = None
10
 
11
  def load_model():
12
+ """Load the base model and LoRA adapter using PEFT"""
13
  global model, tokenizer
14
 
15
  if model is None or tokenizer is None:
16
+ print("Loading base model and LoRA adapter...")
17
 
18
+ # Load tokenizer
19
+ tokenizer = AutoTokenizer.from_pretrained("unsloth/Meta-Llama-3.1-8B-Instruct")
 
 
 
 
 
 
20
 
21
+ if tokenizer.pad_token is None:
22
+ tokenizer.pad_token = tokenizer.eos_token
23
 
24
+ # Load base model
25
+ base_model = AutoModelForCausalLM.from_pretrained(
26
+ "unsloth/Meta-Llama-3.1-8B-Instruct",
27
+ torch_dtype=torch.float32,
28
+ device_map="cpu",
29
+ low_cpu_mem_usage=True
30
+ )
31
+
32
+ # Load LoRA adapter
33
+ model = PeftModel.from_pretrained(
34
+ base_model,
35
+ "robertnetwork/strudel-medium",
36
+ torch_dtype=torch.float32
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
37
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38
 
39
+ print("Base model and LoRA adapter loaded successfully!")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
40
 
41
+ return model, tokenizer