Nafiul Huda commited on
Commit
02cea10
·
verified ·
1 Parent(s): 72090d1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +68 -121
app.py CHANGED
@@ -1,15 +1,10 @@
1
  import gradio as gr
2
  import torch
3
- import time
4
- import re
5
  from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer
6
  from threading import Thread
7
 
8
-
9
  model_id = "unsloth/gemma-3-270m-it-GGUF"
10
- # model_id = "unsloth/Qwen3-0.6B-GGUF"
11
  gguf_filename = "gemma-3-270m-it-UD-IQ2_M.gguf"
12
- # gguf_filename = "Qwen3-0.6B-UD-Q8_K_XL.gguf"
13
 
14
  tokenizer = AutoTokenizer.from_pretrained(model_id, gguf_file=gguf_filename)
15
  model = AutoModelForCausalLM.from_pretrained(
@@ -24,25 +19,13 @@ def to_str(val):
24
  if isinstance(val, str):
25
  return val
26
  if isinstance(val, (list, tuple)):
27
- return " ".join(str(v.get("text", "")) if isinstance(v, dict) else str(v) for v in val)
 
 
 
28
  return str(val)
29
 
30
 
31
- def parse_thinking(val):
32
- if isinstance(val, bool):
33
- return val
34
- if isinstance(val, str):
35
- return val.lower() in ("true", "1", "yes")
36
- return bool(val)
37
-
38
-
39
- def strip_think(text):
40
- text = re.sub(r"<think>.*?</think>", "", text, flags=re.DOTALL)
41
- text = re.sub(r"<think>.*$", "", text, flags=re.DOTALL)
42
- text = re.sub(r"</think>", "", text)
43
- return text.strip()
44
-
45
-
46
  def user_submit(message, history):
47
  if not message or not message.strip():
48
  return "", history
@@ -52,14 +35,12 @@ def user_submit(message, history):
52
 
53
 
54
  @torch.no_grad()
55
- def bot_respond(history, system_prompt, max_tokens, temperature, top_p, top_k, enable_thinking):
56
  history = list(history) if history else []
57
  if not history or history[-1].get("role") != "user":
58
  yield history
59
  return
60
 
61
- thinking_on = parse_thinking(enable_thinking)
62
-
63
  messages = []
64
  sp = to_str(system_prompt).strip()
65
  if sp:
@@ -67,81 +48,38 @@ def bot_respond(history, system_prompt, max_tokens, temperature, top_p, top_k, e
67
  for turn in history:
68
  if not isinstance(turn, dict):
69
  continue
70
- if turn.get("metadata"):
71
- continue
72
  role = str(turn.get("role", ""))
73
  content = to_str(turn.get("content", ""))
74
  if role in ("user", "assistant") and content:
75
  messages.append({"role": role, "content": content})
76
 
77
- # Qwen3: append /no_think to last user message to disable thinking
78
- if not thinking_on and messages and messages[-1]["role"] == "user":
79
- messages[-1]["content"] = messages[-1]["content"] + " /no_think"
80
-
81
  try:
82
  text = tokenizer.apply_chat_template(
83
- messages, tokenize=False, add_generation_prompt=True,
84
- enable_thinking=thinking_on
85
  )
86
  inputs = tokenizer([text], return_tensors="pt").to("cpu")
87
  except Exception as e:
88
- history.append({"role": "assistant", "content": "Error: " + str(e)})
89
- yield history
90
  return
91
 
92
- streamer = TextIteratorStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True)
 
 
93
  thread = Thread(target=model.generate, kwargs=dict(
94
  **inputs, streamer=streamer,
95
- max_new_tokens=int(max_tokens), temperature=float(temperature),
96
- top_p=float(top_p), top_k=int(top_k), do_sample=True
 
 
 
97
  ))
98
  thread.start()
99
 
100
  raw = ""
101
- t0 = None
102
- t_elapsed = 0
103
- t_done = False
104
-
105
  try:
106
  for chunk in streamer:
107
  raw += str(chunk)
108
-
109
- # Thinking OFF — strip all think tags, just show answer
110
- if not thinking_on:
111
- clean = strip_think(raw)
112
- if clean:
113
- yield history + [{"role": "assistant", "content": clean}]
114
- continue
115
-
116
- # Thinking ON
117
- has_o = "<think>" in raw
118
- has_c = "</think>" in raw
119
-
120
- if has_o and t0 is None:
121
- t0 = time.time()
122
- if has_o and has_c and not t_done:
123
- t_done = True
124
- t_elapsed = time.time() - t0
125
-
126
- if not has_o:
127
- yield history + [{"role": "assistant", "content": raw.strip()}]
128
- elif not has_c:
129
- sec = time.time() - t0
130
- thought = raw[raw.find("<think>") + 7:].strip()
131
- yield history + [
132
- {"role": "assistant", "content": thought,
133
- "metadata": {"title": "💭 Thinking (" + str(round(sec, 1)) + "s)..."}}
134
- ]
135
- else:
136
- m = re.search(r"<think>(.*?)</think>", raw, flags=re.DOTALL)
137
- thought = m.group(1).strip() if m else ""
138
- answer = raw[raw.find("</think>") + 8:].strip()
139
- out = []
140
- out.append({"role": "assistant", "content": thought,
141
- "metadata": {"title": "💭 Thinking (" + str(round(t_elapsed, 1)) + "s)"}})
142
- if answer:
143
- out.append({"role": "assistant", "content": answer})
144
- yield history + out
145
  except Exception as e:
146
  yield history + [{"role": "assistant", "content": "Error: " + str(e)}]
147
  finally:
@@ -150,27 +88,24 @@ def bot_respond(history, system_prompt, max_tokens, temperature, top_p, top_k, e
150
 
151
 
152
  @torch.no_grad()
153
- def api_generate(message, system_prompt, max_tokens, temperature, top_p, top_k, enable_thinking):
 
 
 
154
  message = str(message) if message else ""
155
  system_prompt = str(system_prompt).strip() if system_prompt else ""
156
  max_tokens = int(float(max_tokens)) if max_tokens else 2048
157
  temperature = float(temperature) if temperature else 0.6
158
  top_p = float(top_p) if top_p else 0.95
159
  top_k = int(float(top_k)) if top_k else 20
160
- thinking_on = parse_thinking(enable_thinking)
161
 
162
  messages = []
163
  if system_prompt:
164
  messages.append({"role": "system", "content": system_prompt})
165
  messages.append({"role": "user", "content": message})
166
 
167
- # Qwen3: append /no_think to disable thinking
168
- if not thinking_on and messages[-1]["role"] == "user":
169
- messages[-1]["content"] = messages[-1]["content"] + " /no_think"
170
-
171
  text = tokenizer.apply_chat_template(
172
- messages, tokenize=False, add_generation_prompt=True,
173
- enable_thinking=thinking_on
174
  )
175
  inputs = tokenizer([text], return_tensors="pt").to("cpu")
176
  out = model.generate(
@@ -178,67 +113,79 @@ def api_generate(message, system_prompt, max_tokens, temperature, top_p, top_k,
178
  temperature=temperature, top_p=top_p,
179
  top_k=top_k, do_sample=True
180
  )
181
- decoded = tokenizer.decode(out[0][inputs.input_ids.shape[-1]:], skip_special_tokens=True)
 
 
182
  del inputs
183
 
184
- thinking = ""
185
- response = decoded
186
-
187
- if thinking_on:
188
- m = re.search(r"<think>(.*?)</think>", decoded, flags=re.DOTALL)
189
- if m:
190
- thinking = m.group(1).strip()
191
- response = decoded[decoded.find("</think>") + 8:].strip()
192
- else:
193
- response = strip_think(decoded)
194
-
195
- return {"thinking": thinking, "response": response}
196
 
197
 
198
- with gr.Blocks(title="Qwen3-0.6B") as demo:
199
 
200
  with gr.Tab("Chat"):
201
- gr.Markdown("# Qwen3-0.6B")
202
  chatbot = gr.Chatbot(height=500)
203
  with gr.Row():
204
- msg = gr.Textbox(placeholder="Type a message...", scale=4,
205
- container=False, show_label=False)
 
 
206
  send_btn = gr.Button("Send", variant="primary", scale=1)
207
  with gr.Accordion("Settings", open=False):
208
- system_prompt = gr.Textbox(label="System Prompt",
209
- placeholder="You are a helpful assistant.", lines=2)
210
- enable_thinking = gr.Checkbox(label="Enable Thinking", value=True)
 
 
211
  with gr.Row():
212
- max_tokens = gr.Slider(64, 4096, value=2048, step=64, label="Max Tokens")
213
- temperature = gr.Slider(0.05, 2.0, value=0.6, step=0.05, label="Temperature")
 
 
 
 
214
  with gr.Row():
215
- top_p = gr.Slider(0.1, 1.0, value=0.95, step=0.05, label="Top-P")
216
- top_k = gr.Slider(1, 100, value=20, step=1, label="Top-K")
 
 
 
 
217
  gr.ClearButton([msg, chatbot], value="Clear")
218
 
219
- params = [chatbot, system_prompt, max_tokens, temperature, top_p, top_k, enable_thinking]
220
- msg.submit(user_submit, [msg, chatbot], [msg, chatbot], queue=False).then(
221
- bot_respond, params, chatbot)
222
- send_btn.click(user_submit, [msg, chatbot], [msg, chatbot], queue=False).then(
223
- bot_respond, params, chatbot)
 
 
224
 
225
  with gr.Tab("API"):
226
  gr.Markdown("# API Endpoint")
227
  api_msg = gr.Textbox(label="Message")
228
  api_sys = gr.Textbox(label="System Prompt", value="")
229
  with gr.Row():
230
- api_max = gr.Slider(64, 4096, value=2048, step=64, label="Max Tokens")
231
- api_temp = gr.Slider(0.05, 2.0, value=0.6, step=0.05, label="Temperature")
 
 
 
 
232
  with gr.Row():
233
- api_topp = gr.Slider(0.1, 1.0, value=0.95, step=0.05, label="Top-P")
234
- api_topk = gr.Slider(1, 100, value=20, step=1, label="Top-K")
235
- api_think = gr.Checkbox(label="Enable Thinking", value=True)
 
 
 
236
  api_btn = gr.Button("Generate", variant="primary")
237
  api_out = gr.JSON(label="Response")
238
 
239
  api_btn.click(
240
  api_generate,
241
- inputs=[api_msg, api_sys, api_max, api_temp, api_topp, api_topk, api_think],
242
  outputs=api_out,
243
  api_name="generate"
244
  )
 
1
  import gradio as gr
2
  import torch
 
 
3
  from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer
4
  from threading import Thread
5
 
 
6
  model_id = "unsloth/gemma-3-270m-it-GGUF"
 
7
  gguf_filename = "gemma-3-270m-it-UD-IQ2_M.gguf"
 
8
 
9
  tokenizer = AutoTokenizer.from_pretrained(model_id, gguf_file=gguf_filename)
10
  model = AutoModelForCausalLM.from_pretrained(
 
19
  if isinstance(val, str):
20
  return val
21
  if isinstance(val, (list, tuple)):
22
+ return " ".join(
23
+ str(v.get("text", "")) if isinstance(v, dict) else str(v)
24
+ for v in val
25
+ )
26
  return str(val)
27
 
28
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29
  def user_submit(message, history):
30
  if not message or not message.strip():
31
  return "", history
 
35
 
36
 
37
  @torch.no_grad()
38
+ def bot_respond(history, system_prompt, max_tokens, temperature, top_p, top_k):
39
  history = list(history) if history else []
40
  if not history or history[-1].get("role") != "user":
41
  yield history
42
  return
43
 
 
 
44
  messages = []
45
  sp = to_str(system_prompt).strip()
46
  if sp:
 
48
  for turn in history:
49
  if not isinstance(turn, dict):
50
  continue
 
 
51
  role = str(turn.get("role", ""))
52
  content = to_str(turn.get("content", ""))
53
  if role in ("user", "assistant") and content:
54
  messages.append({"role": role, "content": content})
55
 
 
 
 
 
56
  try:
57
  text = tokenizer.apply_chat_template(
58
+ messages, tokenize=False, add_generation_prompt=True
 
59
  )
60
  inputs = tokenizer([text], return_tensors="pt").to("cpu")
61
  except Exception as e:
62
+ yield history + [{"role": "assistant", "content": "Error: " + str(e)}]
 
63
  return
64
 
65
+ streamer = TextIteratorStreamer(
66
+ tokenizer, skip_prompt=True, skip_special_tokens=True
67
+ )
68
  thread = Thread(target=model.generate, kwargs=dict(
69
  **inputs, streamer=streamer,
70
+ max_new_tokens=int(max_tokens),
71
+ temperature=float(temperature),
72
+ top_p=float(top_p),
73
+ top_k=int(top_k),
74
+ do_sample=True
75
  ))
76
  thread.start()
77
 
78
  raw = ""
 
 
 
 
79
  try:
80
  for chunk in streamer:
81
  raw += str(chunk)
82
+ yield history + [{"role": "assistant", "content": raw.strip()}]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
83
  except Exception as e:
84
  yield history + [{"role": "assistant", "content": "Error: " + str(e)}]
85
  finally:
 
88
 
89
 
90
  @torch.no_grad()
91
+ def api_generate(
92
+ message, system_prompt="", max_tokens=2048,
93
+ temperature=0.6, top_p=0.95, top_k=20
94
+ ):
95
  message = str(message) if message else ""
96
  system_prompt = str(system_prompt).strip() if system_prompt else ""
97
  max_tokens = int(float(max_tokens)) if max_tokens else 2048
98
  temperature = float(temperature) if temperature else 0.6
99
  top_p = float(top_p) if top_p else 0.95
100
  top_k = int(float(top_k)) if top_k else 20
 
101
 
102
  messages = []
103
  if system_prompt:
104
  messages.append({"role": "system", "content": system_prompt})
105
  messages.append({"role": "user", "content": message})
106
 
 
 
 
 
107
  text = tokenizer.apply_chat_template(
108
+ messages, tokenize=False, add_generation_prompt=True
 
109
  )
110
  inputs = tokenizer([text], return_tensors="pt").to("cpu")
111
  out = model.generate(
 
113
  temperature=temperature, top_p=top_p,
114
  top_k=top_k, do_sample=True
115
  )
116
+ decoded = tokenizer.decode(
117
+ out[0][inputs.input_ids.shape[-1]:], skip_special_tokens=True
118
+ )
119
  del inputs
120
 
121
+ return {"response": decoded.strip()}
 
 
 
 
 
 
 
 
 
 
 
122
 
123
 
124
+ with gr.Blocks(title="Gemma 3 270M") as demo:
125
 
126
  with gr.Tab("Chat"):
127
+ gr.Markdown("# Gemma 3 270M")
128
  chatbot = gr.Chatbot(height=500)
129
  with gr.Row():
130
+ msg = gr.Textbox(
131
+ placeholder="Type a message...", scale=4,
132
+ container=False, show_label=False
133
+ )
134
  send_btn = gr.Button("Send", variant="primary", scale=1)
135
  with gr.Accordion("Settings", open=False):
136
+ system_prompt = gr.Textbox(
137
+ label="System Prompt",
138
+ placeholder="You are a helpful assistant.",
139
+ lines=2
140
+ )
141
  with gr.Row():
142
+ max_tokens = gr.Slider(
143
+ 64, 4096, value=2048, step=64, label="Max Tokens"
144
+ )
145
+ temperature = gr.Slider(
146
+ 0.05, 2.0, value=0.6, step=0.05, label="Temperature"
147
+ )
148
  with gr.Row():
149
+ top_p = gr.Slider(
150
+ 0.1, 1.0, value=0.95, step=0.05, label="Top-P"
151
+ )
152
+ top_k = gr.Slider(
153
+ 1, 100, value=20, step=1, label="Top-K"
154
+ )
155
  gr.ClearButton([msg, chatbot], value="Clear")
156
 
157
+ params = [chatbot, system_prompt, max_tokens, temperature, top_p, top_k]
158
+ msg.submit(
159
+ user_submit, [msg, chatbot], [msg, chatbot], queue=False
160
+ ).then(bot_respond, params, chatbot)
161
+ send_btn.click(
162
+ user_submit, [msg, chatbot], [msg, chatbot], queue=False
163
+ ).then(bot_respond, params, chatbot)
164
 
165
  with gr.Tab("API"):
166
  gr.Markdown("# API Endpoint")
167
  api_msg = gr.Textbox(label="Message")
168
  api_sys = gr.Textbox(label="System Prompt", value="")
169
  with gr.Row():
170
+ api_max = gr.Slider(
171
+ 64, 4096, value=2048, step=64, label="Max Tokens"
172
+ )
173
+ api_temp = gr.Slider(
174
+ 0.05, 2.0, value=0.6, step=0.05, label="Temperature"
175
+ )
176
  with gr.Row():
177
+ api_topp = gr.Slider(
178
+ 0.1, 1.0, value=0.95, step=0.05, label="Top-P"
179
+ )
180
+ api_topk = gr.Slider(
181
+ 1, 100, value=20, step=1, label="Top-K"
182
+ )
183
  api_btn = gr.Button("Generate", variant="primary")
184
  api_out = gr.JSON(label="Response")
185
 
186
  api_btn.click(
187
  api_generate,
188
+ inputs=[api_msg, api_sys, api_max, api_temp, api_topp, api_topk],
189
  outputs=api_out,
190
  api_name="generate"
191
  )