Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -1,28 +1,28 @@
|
|
1 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
2 |
MODEL_ID = "deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B"
|
3 |
QUANT = "Q5_K_M"
|
4 |
|
5 |
-
|
6 |
def run_command(command, cwd=None):
|
7 |
-
"""
|
8 |
result = subprocess.run(command, shell=True, cwd=cwd, text=True, capture_output=True)
|
9 |
if result.returncode != 0:
|
10 |
-
print(f"
|
11 |
-
print(f"
|
12 |
exit(result.returncode)
|
13 |
else:
|
14 |
-
print(f"
|
15 |
print(result.stdout)
|
16 |
|
17 |
-
run_command('pip install llama-cpp-python')
|
18 |
-
|
19 |
-
import gradio as gr
|
20 |
-
import os
|
21 |
-
from llama_cpp import Llama
|
22 |
-
from huggingface_hub import snapshot_download
|
23 |
-
|
24 |
def setup_llama_cpp():
|
25 |
-
"""
|
26 |
if not os.path.exists('llama.cpp'):
|
27 |
run_command('git clone https://github.com/ggml-org/llama.cpp.git')
|
28 |
os.chdir('llama.cpp')
|
@@ -32,7 +32,7 @@ def setup_llama_cpp():
|
|
32 |
os.chdir('..')
|
33 |
|
34 |
def setup_model(model_id):
|
35 |
-
"""
|
36 |
local_dir = model_id.split('/')[-1]
|
37 |
if not os.path.exists(local_dir):
|
38 |
snapshot_download(repo_id=model_id, local_dir=local_dir)
|
@@ -44,49 +44,217 @@ def setup_model(model_id):
|
|
44 |
run_command(f'./llama.cpp/build/bin/llama-quantize ./{gguf_path} {quantized_path} {QUANT}')
|
45 |
return quantized_path
|
46 |
|
47 |
-
def
|
48 |
-
"""
|
49 |
-
|
50 |
-
|
51 |
-
|
52 |
-
|
53 |
-
|
54 |
-
|
55 |
-
|
56 |
-
|
57 |
-
|
58 |
-
|
59 |
-
|
60 |
-
|
61 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
62 |
)
|
63 |
-
|
64 |
-
|
65 |
-
|
66 |
-
|
67 |
-
|
68 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
69 |
|
70 |
if __name__ == "__main__":
|
|
|
|
|
71 |
setup_llama_cpp()
|
72 |
MODEL_PATH = setup_model(MODEL_ID)
|
73 |
-
|
74 |
-
|
75 |
-
|
76 |
-
|
77 |
-
|
78 |
-
|
79 |
-
|
80 |
-
|
81 |
-
|
82 |
-
|
83 |
-
description="使用Llama GGUF量化模型进行推理",
|
84 |
-
additional_inputs_accordion=gr.Accordion(label="⚙️ 参数设置", open=False),
|
85 |
-
additional_inputs=[
|
86 |
-
gr.Textbox("You are a helpful assistant.", label="System Prompt"),
|
87 |
-
gr.Slider(0, 1, 0.6, label="Temperature"),
|
88 |
-
gr.Slider(100, 4096, 1000, label="Max Tokens"),
|
89 |
-
gr.Slider(1, 100, 40, label="Top K"),
|
90 |
-
gr.Slider(0, 1, 0.85, label="Top P"),
|
91 |
-
],
|
92 |
-
).queue().launch()
|
|
|
1 |
+
import time
|
2 |
+
import gradio as gr
|
3 |
+
from openai import OpenAI
|
4 |
+
import os
|
5 |
+
import subprocess
|
6 |
+
from huggingface_hub import snapshot_download
|
7 |
+
|
8 |
+
# Model configuration
|
9 |
MODEL_ID = "deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B"
|
10 |
QUANT = "Q5_K_M"
|
11 |
|
12 |
+
# Utility functions
|
13 |
def run_command(command, cwd=None):
|
14 |
+
"""Run a system command."""
|
15 |
result = subprocess.run(command, shell=True, cwd=cwd, text=True, capture_output=True)
|
16 |
if result.returncode != 0:
|
17 |
+
print(f"Command failed: {command}")
|
18 |
+
print(f"Error: {result.stderr}")
|
19 |
exit(result.returncode)
|
20 |
else:
|
21 |
+
print(f"Command succeeded: {command}")
|
22 |
print(result.stdout)
|
23 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
24 |
def setup_llama_cpp():
|
25 |
+
"""Clone and compile llama.cpp repository."""
|
26 |
if not os.path.exists('llama.cpp'):
|
27 |
run_command('git clone https://github.com/ggml-org/llama.cpp.git')
|
28 |
os.chdir('llama.cpp')
|
|
|
32 |
os.chdir('..')
|
33 |
|
34 |
def setup_model(model_id):
|
35 |
+
"""Download and convert model to GGUF format, return quantized model path."""
|
36 |
local_dir = model_id.split('/')[-1]
|
37 |
if not os.path.exists(local_dir):
|
38 |
snapshot_download(repo_id=model_id, local_dir=local_dir)
|
|
|
44 |
run_command(f'./llama.cpp/build/bin/llama-quantize ./{gguf_path} {quantized_path} {QUANT}')
|
45 |
return quantized_path
|
46 |
|
47 |
+
def start_llama_server(model_path):
|
48 |
+
"""Start llama-server in the background."""
|
49 |
+
cmd = f'./llama.cpp/build/bin/llama-server --host 0.0.0.0 --port 8080 --model {model_path} --ctx-size 32768'
|
50 |
+
process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
51 |
+
# Give the server a moment to start
|
52 |
+
time.sleep(5)
|
53 |
+
return process
|
54 |
+
|
55 |
+
# GUI-specific utilities (unchanged from your original)
|
56 |
+
def format_time(seconds_float):
|
57 |
+
total_seconds = int(round(seconds_float))
|
58 |
+
hours = total_seconds // 3600
|
59 |
+
remaining_seconds = total_seconds % 3600
|
60 |
+
minutes = remaining_seconds // 60
|
61 |
+
seconds = remaining_seconds % 60
|
62 |
+
if hours > 0:
|
63 |
+
return f"{hours}h {minutes}m {seconds}s"
|
64 |
+
elif minutes > 0:
|
65 |
+
return f"{minutes}m {seconds}s"
|
66 |
+
else:
|
67 |
+
return f"{seconds}s"
|
68 |
+
|
69 |
+
DESCRIPTION = '''
|
70 |
+
# Duplicate the space for free private inference.
|
71 |
+
## DeepSeek-R1 Distill Qwen-1.5B Demo
|
72 |
+
A reasoning model trained using RL (Reinforcement Learning) that demonstrates structured reasoning capabilities.
|
73 |
+
'''
|
74 |
+
|
75 |
+
CSS = """
|
76 |
+
.spinner { animation: spin 1s linear infinite; display: inline-block; margin-right: 8px; }
|
77 |
+
@keyframes spin { from { transform: rotate(0deg); } to { transform: rotate(360deg); } }
|
78 |
+
.thinking-summary { cursor: pointer; padding: 8px; background: #f5f5f5; border-radius: 4px; margin: 4px 0; }
|
79 |
+
.thought-content { padding: 10px; background: #f8f9fa; border-radius: 4px; margin: 5px 0; }
|
80 |
+
.thinking-container { border-left: 3px solid #facc15; padding-left: 10px; margin: 8px 0; background: #210c29; }
|
81 |
+
details:not([open]) .thinking-container { border-left-color: #290c15; }
|
82 |
+
details { border: 1px solid #e0e0e0 !important; border-radius: 8px !important; padding: 12px !important; margin: 8px 0 !important; transition: border-color 0.2s; }
|
83 |
+
"""
|
84 |
+
|
85 |
+
client = OpenAI(base_url="http://localhost:8080/v1", api_key="no-key-required")
|
86 |
+
|
87 |
+
def user(message, history):
|
88 |
+
return "", history + [[message, None]]
|
89 |
+
|
90 |
+
class ParserState:
|
91 |
+
__slots__ = ['answer', 'thought', 'in_think', 'start_time', 'last_pos', 'total_think_time']
|
92 |
+
def __init__(self):
|
93 |
+
self.answer = ""
|
94 |
+
self.thought = ""
|
95 |
+
self.in_think = False
|
96 |
+
self.start_time = 0
|
97 |
+
self.last_pos = 0
|
98 |
+
self.total_think_time = 0.0
|
99 |
+
|
100 |
+
def parse_response(text, state):
|
101 |
+
buffer = text[state.last_pos:]
|
102 |
+
state.last_pos = len(text)
|
103 |
+
while buffer:
|
104 |
+
if not state.in_think:
|
105 |
+
think_start = buffer.find('<think>')
|
106 |
+
if think_start != -1:
|
107 |
+
state.answer += buffer[:think_start]
|
108 |
+
state.in_think = True
|
109 |
+
state.start_time = time.perf_counter()
|
110 |
+
buffer = buffer[think_start + 7:]
|
111 |
+
else:
|
112 |
+
state.answer += buffer
|
113 |
+
break
|
114 |
+
else:
|
115 |
+
think_end = buffer.find('</think>')
|
116 |
+
if think_end != -1:
|
117 |
+
state.thought += buffer[:think_end]
|
118 |
+
duration = time.perf_counter() - state.start_time
|
119 |
+
state.total_think_time += duration
|
120 |
+
state.in_think = False
|
121 |
+
buffer = buffer[think_end + 8:]
|
122 |
+
else:
|
123 |
+
state.thought += buffer
|
124 |
+
break
|
125 |
+
elapsed = time.perf_counter() - state.start_time if state.in_think else 0
|
126 |
+
return state, elapsed
|
127 |
+
|
128 |
+
def format_response(state, elapsed):
|
129 |
+
answer_part = state.answer.replace('<think>', '').replace('</think>', '')
|
130 |
+
collapsible = []
|
131 |
+
collapsed = "<details open>"
|
132 |
+
if state.thought or state.in_think:
|
133 |
+
if state.in_think:
|
134 |
+
total_elapsed = state.total_think_time + elapsed
|
135 |
+
formatted_time = format_time(total_elapsed)
|
136 |
+
status = f"🌀 Thinking for {formatted_time}"
|
137 |
+
else:
|
138 |
+
formatted_time = format_time(state.total_think_time)
|
139 |
+
status = f"✅ Thought for {formatted_time}"
|
140 |
+
collapsed = "<details>"
|
141 |
+
collapsible.append(
|
142 |
+
f"{collapsed}<summary>{status}</summary>\n\n<div class='thinking-container'>\n{state.thought}\n</div>\n</details>"
|
143 |
+
)
|
144 |
+
return collapsible, answer_part
|
145 |
+
|
146 |
+
def generate_response(history, temperature, top_p, max_tokens, active_gen):
|
147 |
+
messages = [
|
148 |
+
{"role": "system", "content": "You are a helpful assistant."},
|
149 |
+
*[{"role": "user" if i % 2 == 0 else "assistant", "content": msg or ""}
|
150 |
+
for i, (user_msg, assistant_msg) in enumerate(history[:-1])],
|
151 |
+
{"role": "user", "content": history[-1][0]}
|
152 |
+
]
|
153 |
+
full_response = ""
|
154 |
+
state = ParserState()
|
155 |
+
try:
|
156 |
+
stream = client.chat.completions.create(
|
157 |
+
model="", # Model name not needed with llama-server
|
158 |
+
messages=messages,
|
159 |
+
temperature=temperature,
|
160 |
+
top_p=top_p,
|
161 |
+
max_tokens=max_tokens,
|
162 |
+
stream=True
|
163 |
+
)
|
164 |
+
for chunk in stream:
|
165 |
+
if not active_gen[0]:
|
166 |
+
break
|
167 |
+
if chunk.choices[0].delta.content:
|
168 |
+
full_response += chunk.choices[0].delta.content
|
169 |
+
state, elapsed = parse_response(full_response, state)
|
170 |
+
collapsible, answer_part = format_response(state, elapsed)
|
171 |
+
history[-1][1] = "\n\n".join(collapsible + [answer_part])
|
172 |
+
yield history
|
173 |
+
state, elapsed = parse_response(full_response, state)
|
174 |
+
collapsible, answer_part = format_response(state, elapsed)
|
175 |
+
history[-1][1] = "\n\n".join(collapsible + [answer_part])
|
176 |
+
yield history
|
177 |
+
except Exception as e:
|
178 |
+
history[-1][1] = f"Error: {str(e)}"
|
179 |
+
yield history
|
180 |
+
finally:
|
181 |
+
active_gen[0] = False
|
182 |
+
|
183 |
+
# GUI setup
|
184 |
+
with gr.Blocks(css=CSS) as demo:
|
185 |
+
gr.Markdown(DESCRIPTION)
|
186 |
+
active_gen = gr.State([False])
|
187 |
+
|
188 |
+
chatbot = gr.Chatbot(
|
189 |
+
elem_id="chatbot",
|
190 |
+
height=500,
|
191 |
+
show_label=False,
|
192 |
+
render_markdown=True
|
193 |
)
|
194 |
+
|
195 |
+
with gr.Row():
|
196 |
+
msg = gr.Textbox(
|
197 |
+
label="Message",
|
198 |
+
placeholder="Type your message...",
|
199 |
+
container=False,
|
200 |
+
scale=4
|
201 |
+
)
|
202 |
+
submit_btn = gr.Button("Send", variant='primary', scale=1)
|
203 |
+
|
204 |
+
with gr.Column(scale=2):
|
205 |
+
with gr.Row():
|
206 |
+
clear_btn = gr.Button("Clear", variant='secondary')
|
207 |
+
stop_btn = gr.Button("Stop", variant='stop')
|
208 |
+
|
209 |
+
with gr.Accordion("Parameters", open=False):
|
210 |
+
temperature = gr.Slider(minimum=0.1, maximum=1.5, value=0.6, label="Temperature")
|
211 |
+
top_p = gr.Slider(minimum=0.1, maximum=1.0, value=0.95, label="Top-p")
|
212 |
+
max_tokens = gr.Slider(minimum=2048, maximum=32768, value=4096, step=64, label="Max Tokens")
|
213 |
+
|
214 |
+
gr.Examples(
|
215 |
+
examples=[
|
216 |
+
["How many r's are in the word strawberry?"],
|
217 |
+
["Write 10 funny sentences that end in a fruit!"],
|
218 |
+
["Let’s play word chains! I’ll start: PIZZA. Your turn! Next word must start with… A!"]
|
219 |
+
],
|
220 |
+
inputs=msg,
|
221 |
+
label="Example Prompts"
|
222 |
+
)
|
223 |
+
|
224 |
+
submit_event = submit_btn.click(
|
225 |
+
user, [msg, chatbot], [msg, chatbot], queue=False
|
226 |
+
).then(
|
227 |
+
lambda: [True], outputs=active_gen
|
228 |
+
).then(
|
229 |
+
generate_response, [chatbot, temperature, top_p, max_tokens, active_gen], chatbot
|
230 |
+
)
|
231 |
+
|
232 |
+
msg.submit(
|
233 |
+
user, [msg, chatbot], [msg, chatbot], queue=False
|
234 |
+
).then(
|
235 |
+
lambda: [True], outputs=active_gen
|
236 |
+
).then(
|
237 |
+
generate_response, [chatbot, temperature, top_p, max_tokens, active_gen], chatbot
|
238 |
+
)
|
239 |
+
|
240 |
+
stop_btn.click(
|
241 |
+
lambda: [False], None, active_gen, cancels=[submit_event]
|
242 |
+
)
|
243 |
+
|
244 |
+
clear_btn.click(lambda: None, None, chatbot, queue=False)
|
245 |
|
246 |
if __name__ == "__main__":
|
247 |
+
# Install dependencies
|
248 |
+
run_command('pip install llama-cpp-python openai')
|
249 |
setup_llama_cpp()
|
250 |
MODEL_PATH = setup_model(MODEL_ID)
|
251 |
+
|
252 |
+
# Start llama-server
|
253 |
+
server_process = start_llama_server(MODEL_PATH)
|
254 |
+
try:
|
255 |
+
# Launch GUI
|
256 |
+
demo.launch(server_name="0.0.0.0", server_port=7860)
|
257 |
+
finally:
|
258 |
+
# Cleanup: terminate the server process when the GUI is closed
|
259 |
+
server_process.terminate()
|
260 |
+
server_process.wait()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|