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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
2 |
{answer}"""
|
3 |
else:
|
4 |
formatted_response = answer
|
@@ -38,7 +335,6 @@
|
|
38 |
submit_btn: gr.update(interactive=True, value="Send")
|
39 |
}
|
40 |
|
41 |
-
# --- CORRECTED FUNCTION ---
|
42 |
def retry_last(display_history: list, model_history: list, system_prompt_text: str,
|
43 |
temp: float, top_p_val: float, top_k_val: int,
|
44 |
min_p_val: float, max_tokens: int):
|
@@ -57,16 +353,16 @@
|
|
57 |
return
|
58 |
|
59 |
# Correctly remove the last turn (assistant response + user query)
|
60 |
-
model_history.pop() # Remove assistant's message
|
61 |
-
display_history.pop() # Remove assistant's message from display
|
62 |
|
63 |
# Get the last user message to resubmit it, then remove it
|
64 |
last_user_entry = model_history.pop()
|
65 |
last_user_msg = last_user_entry["content"]
|
66 |
|
67 |
# We also pop the user message from the display history because
|
68 |
-
# handle_user_message will add it back.
|
69 |
-
if display_history:
|
70 |
display_history.pop()
|
71 |
|
72 |
# Use 'yield from' to properly call the generator and pass its updates
|
@@ -123,4 +419,5 @@
|
|
123 |
)
|
124 |
|
125 |
if __name__ == "__main__":
|
126 |
-
demo.launch(debug=True, share=False)
|
|
|
|
1 |
+
import os
|
2 |
+
import torch
|
3 |
+
import gradio as gr
|
4 |
+
import spaces
|
5 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
6 |
+
|
7 |
+
# -------------------------------------------------
|
8 |
+
# Model setup (loaded once at startup)
|
9 |
+
# -------------------------------------------------
|
10 |
+
model_name = "gr0010/Art-0-8B-development"
|
11 |
+
|
12 |
+
# Load model and tokenizer globally
|
13 |
+
print("Loading model and tokenizer...")
|
14 |
+
tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)
|
15 |
+
|
16 |
+
# Load model in CPU first, will move to GPU when needed
|
17 |
+
model = AutoModelForCausalLM.from_pretrained(
|
18 |
+
model_name,
|
19 |
+
torch_dtype=torch.bfloat16,
|
20 |
+
device_map="cuda", # Direct CUDA loading for ZeroGPU
|
21 |
+
trust_remote_code=True,
|
22 |
+
)
|
23 |
+
print("Model loaded successfully!")
|
24 |
+
|
25 |
+
# -------------------------------------------------
|
26 |
+
# Core generation and parsing logic with Zero GPU
|
27 |
+
# -------------------------------------------------
|
28 |
+
@spaces.GPU(duration=120) # Request GPU for up to 120 seconds
|
29 |
+
def generate_and_parse(messages: list, temperature: float = 0.6,
|
30 |
+
top_p: float = 0.95, top_k: int = 20,
|
31 |
+
min_p: float = 0.0, max_new_tokens: int = 32768):
|
32 |
+
"""
|
33 |
+
Takes a clean list of messages, generates a response,
|
34 |
+
and parses it into thinking and answer parts.
|
35 |
+
Decorated with @spaces.GPU for Zero GPU allocation.
|
36 |
+
"""
|
37 |
+
# Apply chat template with enable_thinking=True for Qwen3
|
38 |
+
prompt_text = tokenizer.apply_chat_template(
|
39 |
+
messages,
|
40 |
+
tokenize=False,
|
41 |
+
add_generation_prompt=True,
|
42 |
+
enable_thinking=True # Explicitly enable thinking mode
|
43 |
+
)
|
44 |
+
|
45 |
+
# --- CONSOLE DEBUG OUTPUT ---
|
46 |
+
print("\n" + "="*50)
|
47 |
+
print("--- RAW PROMPT SENT TO MODEL ---")
|
48 |
+
print(prompt_text[:500] + "..." if len(prompt_text) > 500 else prompt_text)
|
49 |
+
print("="*50 + "\n")
|
50 |
+
|
51 |
+
model_inputs = tokenizer([prompt_text], return_tensors="pt").to("cuda")
|
52 |
+
|
53 |
+
with torch.no_grad():
|
54 |
+
generated_ids = model.generate(
|
55 |
+
**model_inputs,
|
56 |
+
max_new_tokens=max_new_tokens,
|
57 |
+
do_sample=True,
|
58 |
+
temperature=temperature,
|
59 |
+
top_p=top_p,
|
60 |
+
top_k=top_k,
|
61 |
+
min_p=min_p,
|
62 |
+
pad_token_id=tokenizer.eos_token_id,
|
63 |
+
)
|
64 |
+
|
65 |
+
output_token_ids = generated_ids[0][len(model_inputs.input_ids[0]):].tolist()
|
66 |
+
|
67 |
+
thinking = ""
|
68 |
+
answer = ""
|
69 |
+
try:
|
70 |
+
# Find the </think> token to separate thinking from answer
|
71 |
+
end_think_token_id = 151668 # </think>
|
72 |
+
if end_think_token_id in output_token_ids:
|
73 |
+
end_think_idx = output_token_ids.index(end_think_token_id) + 1
|
74 |
+
thinking_tokens = output_token_ids[:end_think_idx]
|
75 |
+
answer_tokens = output_token_ids[end_think_idx:]
|
76 |
+
|
77 |
+
thinking = tokenizer.decode(thinking_tokens, skip_special_tokens=True).strip()
|
78 |
+
# Remove <think> and </think> tags from thinking
|
79 |
+
thinking = thinking.replace("<think>", "").replace("</think>", "").strip()
|
80 |
+
|
81 |
+
answer = tokenizer.decode(answer_tokens, skip_special_tokens=True).strip()
|
82 |
+
else:
|
83 |
+
# If no </think> token found, treat everything as answer
|
84 |
+
answer = tokenizer.decode(output_token_ids, skip_special_tokens=True).strip()
|
85 |
+
# Remove any stray <think> tags
|
86 |
+
answer = answer.replace("<think>", "").replace("</think>", "")
|
87 |
+
except (ValueError, IndexError):
|
88 |
+
answer = tokenizer.decode(output_token_ids, skip_special_tokens=True).strip()
|
89 |
+
answer = answer.replace("<think>", "").replace("</think>", "")
|
90 |
+
|
91 |
+
return thinking, answer
|
92 |
+
|
93 |
+
# -------------------------------------------------
|
94 |
+
# Gradio UI Logic
|
95 |
+
# -------------------------------------------------
|
96 |
+
|
97 |
+
# Custom CSS for better styling
|
98 |
+
custom_css = """
|
99 |
+
.model-info {
|
100 |
+
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
101 |
+
padding: 1rem;
|
102 |
+
border-radius: 10px;
|
103 |
+
margin-bottom: 1rem;
|
104 |
+
color: white;
|
105 |
+
}
|
106 |
+
.model-info a {
|
107 |
+
color: #fff;
|
108 |
+
text-decoration: underline;
|
109 |
+
font-weight: bold;
|
110 |
+
}
|
111 |
+
"""
|
112 |
+
|
113 |
+
with gr.Blocks(theme=gr.themes.Soft(), fill_height=True, css=custom_css) as demo:
|
114 |
+
# Separate states for display and model context
|
115 |
+
display_history_state = gr.State([]) # For Gradio chatbot display
|
116 |
+
model_history_state = gr.State([]) # Clean history for model
|
117 |
+
is_generating_state = gr.State(False) # To prevent multiple submissions
|
118 |
+
|
119 |
+
# Model info and CTA section
|
120 |
+
gr.HTML("""
|
121 |
+
<div class="model-info">
|
122 |
+
<h1 style="margin: 0; font-size: 2em;">π¨ Art-0 8B Thinking Chatbot</h1>
|
123 |
+
<p style="margin: 0.5rem 0;">
|
124 |
+
Powered by <a href="https://huggingface.co/gr0010/Art-0-8B-development" target="_blank">Art-0-8B-development</a>
|
125 |
+
- A fine-tuned Qwen3-8B model with advanced reasoning capabilities
|
126 |
+
</p>
|
127 |
+
</div>
|
128 |
+
""")
|
129 |
+
|
130 |
+
gr.Markdown(
|
131 |
+
"""
|
132 |
+
Chat with Art-0-8B, featuring transparent reasoning display and custom personality instructions.
|
133 |
+
The model shows its internal thought process when solving problems.
|
134 |
+
"""
|
135 |
+
)
|
136 |
+
|
137 |
+
# System prompt at the top (main feature)
|
138 |
+
with gr.Group():
|
139 |
+
gr.Markdown("### π System Prompt (Personality & Behavior)")
|
140 |
+
system_prompt = gr.Textbox(
|
141 |
+
value="""Personality Instructions:
|
142 |
+
You are an AI assistant named Art developed by AGI-0.
|
143 |
+
Reasoning Instructions:
|
144 |
+
Think using bullet points and short sentences to simulate thoughts and emoticons to simulate emotions""",
|
145 |
+
label="System Prompt",
|
146 |
+
info="Define the model's personality and reasoning style",
|
147 |
+
lines=5,
|
148 |
+
interactive=True
|
149 |
+
)
|
150 |
+
|
151 |
+
# Main chat interface
|
152 |
+
chatbot = gr.Chatbot(
|
153 |
+
label="Conversation",
|
154 |
+
elem_id="chatbot",
|
155 |
+
bubble_full_width=False,
|
156 |
+
height=500,
|
157 |
+
show_copy_button=True,
|
158 |
+
type="messages"
|
159 |
+
)
|
160 |
+
|
161 |
+
with gr.Row():
|
162 |
+
user_input = gr.Textbox(
|
163 |
+
show_label=False,
|
164 |
+
placeholder="Type your message here...",
|
165 |
+
scale=4,
|
166 |
+
container=False,
|
167 |
+
interactive=True
|
168 |
+
)
|
169 |
+
submit_btn = gr.Button(
|
170 |
+
"Send",
|
171 |
+
variant="primary",
|
172 |
+
scale=1,
|
173 |
+
interactive=True
|
174 |
+
)
|
175 |
+
|
176 |
+
with gr.Row():
|
177 |
+
clear_btn = gr.Button("ποΈ Clear History", variant="secondary")
|
178 |
+
retry_btn = gr.Button("π Retry Last", variant="secondary")
|
179 |
+
|
180 |
+
# Example prompts
|
181 |
+
gr.Examples(
|
182 |
+
examples=[
|
183 |
+
["Give me a short introduction to large language models."],
|
184 |
+
["What are the benefits of using transformers in AI?"],
|
185 |
+
["There are 5 birds on a branch. A hunter shoots one. How many birds are left?"],
|
186 |
+
["Explain quantum computing step by step."],
|
187 |
+
["Write a Python function to calculate the factorial of a number."],
|
188 |
+
["What makes Art-0 different from other AI models?"],
|
189 |
+
],
|
190 |
+
inputs=user_input,
|
191 |
+
label="π‘ Example Prompts"
|
192 |
+
)
|
193 |
+
|
194 |
+
# Advanced settings at the bottom
|
195 |
+
with gr.Accordion("βοΈ Advanced Generation Settings", open=False):
|
196 |
+
with gr.Row():
|
197 |
+
temperature = gr.Slider(
|
198 |
+
minimum=0.1,
|
199 |
+
maximum=2.0,
|
200 |
+
value=0.6,
|
201 |
+
step=0.1,
|
202 |
+
label="Temperature",
|
203 |
+
info="Controls randomness (higher = more creative)"
|
204 |
+
)
|
205 |
+
top_p = gr.Slider(
|
206 |
+
minimum=0.1,
|
207 |
+
maximum=1.0,
|
208 |
+
value=0.95,
|
209 |
+
step=0.05,
|
210 |
+
label="Top-p",
|
211 |
+
info="Nucleus sampling threshold"
|
212 |
+
)
|
213 |
+
with gr.Row():
|
214 |
+
top_k = gr.Slider(
|
215 |
+
minimum=1,
|
216 |
+
maximum=100,
|
217 |
+
value=20,
|
218 |
+
step=1,
|
219 |
+
label="Top-k",
|
220 |
+
info="Number of top tokens to consider"
|
221 |
+
)
|
222 |
+
min_p = gr.Slider(
|
223 |
+
minimum=0.0,
|
224 |
+
maximum=1.0,
|
225 |
+
value=0.0,
|
226 |
+
step=0.01,
|
227 |
+
label="Min-p",
|
228 |
+
info="Minimum probability threshold for token sampling"
|
229 |
+
)
|
230 |
+
with gr.Row():
|
231 |
+
max_new_tokens = gr.Slider(
|
232 |
+
minimum=128,
|
233 |
+
maximum=32768,
|
234 |
+
value=32768,
|
235 |
+
step=128,
|
236 |
+
label="Max New Tokens",
|
237 |
+
info="Maximum response length"
|
238 |
+
)
|
239 |
+
|
240 |
+
def handle_user_message(user_message: str, display_history: list, model_history: list,
|
241 |
+
system_prompt_text: str, is_generating: bool,
|
242 |
+
temp: float, top_p_val: float, top_k_val: int,
|
243 |
+
min_p_val: float, max_tokens: int):
|
244 |
+
"""
|
245 |
+
Handles user input, updates histories, and generates the model's response.
|
246 |
+
"""
|
247 |
+
# Prevent multiple submissions
|
248 |
+
if is_generating or not user_message.strip():
|
249 |
+
return {
|
250 |
+
chatbot: display_history,
|
251 |
+
display_history_state: display_history,
|
252 |
+
model_history_state: model_history,
|
253 |
+
is_generating_state: is_generating,
|
254 |
+
user_input: user_message,
|
255 |
+
submit_btn: gr.update(interactive=not is_generating)
|
256 |
+
}
|
257 |
+
|
258 |
+
# Set generating state
|
259 |
+
is_generating = True
|
260 |
+
|
261 |
+
# Update model history (clean format for model)
|
262 |
+
model_history.append({"role": "user", "content": user_message.strip()})
|
263 |
+
|
264 |
+
# Update display history (for Gradio chatbot)
|
265 |
+
display_history.append([user_message.strip(), None])
|
266 |
+
|
267 |
+
# Yield intermediate state to show user message and disable input
|
268 |
+
yield {
|
269 |
+
chatbot: display_history,
|
270 |
+
display_history_state: display_history,
|
271 |
+
model_history_state: model_history,
|
272 |
+
is_generating_state: is_generating,
|
273 |
+
user_input: "",
|
274 |
+
submit_btn: gr.update(interactive=False, value="π Generating...")
|
275 |
+
}
|
276 |
+
|
277 |
+
# Prepare messages for model (include system prompt)
|
278 |
+
messages_for_model = []
|
279 |
+
if system_prompt_text.strip():
|
280 |
+
messages_for_model.append({"role": "system", "content": system_prompt_text.strip()})
|
281 |
+
messages_for_model.extend(model_history)
|
282 |
+
|
283 |
+
try:
|
284 |
+
# Generate response with hyperparameters
|
285 |
+
thinking, answer = generate_and_parse(
|
286 |
+
messages_for_model,
|
287 |
+
temperature=temp,
|
288 |
+
top_p=top_p_val,
|
289 |
+
top_k=top_k_val,
|
290 |
+
min_p=min_p_val,
|
291 |
+
max_new_tokens=max_tokens
|
292 |
+
)
|
293 |
+
|
294 |
+
# Format response for display
|
295 |
+
if thinking and thinking.strip():
|
296 |
+
formatted_response = f"""<details>
|
297 |
+
<summary><b>π€ Show Reasoning Process</b></summary>
|
298 |
+
{thinking} code Codedownloadcontent_copyexpand_lessIGNORE_WHEN_COPYING_STARTIGNORE_WHEN_COPYING_END </details>
|
299 |
{answer}"""
|
300 |
else:
|
301 |
formatted_response = answer
|
|
|
335 |
submit_btn: gr.update(interactive=True, value="Send")
|
336 |
}
|
337 |
|
|
|
338 |
def retry_last(display_history: list, model_history: list, system_prompt_text: str,
|
339 |
temp: float, top_p_val: float, top_k_val: int,
|
340 |
min_p_val: float, max_tokens: int):
|
|
|
353 |
return
|
354 |
|
355 |
# Correctly remove the last turn (assistant response + user query)
|
356 |
+
model_history.pop() # Remove assistant's message from model history
|
357 |
+
display_history.pop() # Remove assistant's message from display history
|
358 |
|
359 |
# Get the last user message to resubmit it, then remove it
|
360 |
last_user_entry = model_history.pop()
|
361 |
last_user_msg = last_user_entry["content"]
|
362 |
|
363 |
# We also pop the user message from the display history because
|
364 |
+
# handle_user_message will add it back when it processes the retry.
|
365 |
+
if display_history: # Ensure display_history is not empty before popping
|
366 |
display_history.pop()
|
367 |
|
368 |
# Use 'yield from' to properly call the generator and pass its updates
|
|
|
419 |
)
|
420 |
|
421 |
if __name__ == "__main__":
|
422 |
+
demo.launch(debug=True, share=False)
|
423 |
+
|