codebyam commited on
Commit
1cf4072
·
verified ·
1 Parent(s): 9e5af0d

Upload 3 files

Browse files
Files changed (3) hide show
  1. Dockerfile +53 -0
  2. app.py +237 -0
  3. start.sh +21 -0
Dockerfile ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM ubuntu:22.04
2
+
3
+ # Install system dependencies
4
+ RUN apt-get update && \
5
+ apt-get install -y \
6
+ build-essential \
7
+ libssl-dev \
8
+ zlib1g-dev \
9
+ libboost-math-dev \
10
+ libboost-python-dev \
11
+ libboost-timer-dev \
12
+ libboost-thread-dev \
13
+ libboost-system-dev \
14
+ libboost-filesystem-dev \
15
+ libopenblas-dev \
16
+ libomp-dev \
17
+ cmake \
18
+ pkg-config \
19
+ git \
20
+ python3-pip \
21
+ curl \
22
+ libcurl4-openssl-dev \
23
+ wget && \
24
+ rm -rf /var/lib/apt/lists/*
25
+
26
+ # Install Python dependencies
27
+ RUN pip3 install huggingface-hub openai gradio
28
+
29
+ # Build llama.cpp with OpenBLAS
30
+ RUN git clone https://github.com/ggerganov/llama.cpp && \
31
+ cd llama.cpp && \
32
+ cmake -B build -S . \
33
+ -DLLAMA_BUILD_SERVER=ON \
34
+ -DLLAMA_BUILD_EXAMPLES=ON \
35
+ -DGGML_BLAS=ON \
36
+ -DGGML_BLAS_VENDOR=OpenBLAS \
37
+ -DCMAKE_BUILD_TYPE=Release && \
38
+ cmake --build build --config Release --target llama-server -j $(nproc)
39
+
40
+ # Download model
41
+ RUN mkdir -p /models && \
42
+ wget -O /models/model.q8_0.gguf https://huggingface.co/unsloth/DeepSeek-R1-Distill-Qwen-1.5B-GGUF/resolve/main/DeepSeek-R1-Distill-Qwen-1.5B-Q8_0.gguf
43
+
44
+ # Copy app and startup script
45
+ COPY app.py /app.py
46
+ COPY start.sh /start.sh
47
+ RUN chmod +x /start.sh
48
+
49
+ # Expose ports
50
+ EXPOSE 7860 8080
51
+
52
+ # Start services
53
+ CMD ["/start.sh"]
app.py ADDED
@@ -0,0 +1,237 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import time
2
+ import gradio as gr
3
+ from openai import OpenAI
4
+
5
+ def format_time(seconds_float):
6
+ total_seconds = int(round(seconds_float))
7
+ hours = total_seconds // 3600
8
+ remaining_seconds = total_seconds % 3600
9
+ minutes = remaining_seconds // 60
10
+ seconds = remaining_seconds % 60
11
+
12
+ if hours > 0:
13
+ return f"{hours}h {minutes}m {seconds}s"
14
+ elif minutes > 0:
15
+ return f"{minutes}m {seconds}s"
16
+ else:
17
+ return f"{seconds}s"
18
+
19
+ DESCRIPTION = '''
20
+ # Duplicate the space for free private inference.
21
+ ## DeepSeek-R1 Distill Qwen-7B Demo
22
+ A reasoning model trained using RL (Reinforcement Learning) that demonstrates structured reasoning capabilities.
23
+ '''
24
+
25
+ CSS = """
26
+ .spinner {
27
+ animation: spin 1s linear infinite;
28
+ display: inline-block;
29
+ margin-right: 8px;
30
+ }
31
+ @keyframes spin {
32
+ from { transform: rotate(0deg); }
33
+ to { transform: rotate(360deg); }
34
+ }
35
+ .thinking-summary {
36
+ cursor: pointer;
37
+ padding: 8px;
38
+ background: #f5f5f5;
39
+ border-radius: 4px;
40
+ margin: 4px 0;
41
+ }
42
+ .thought-content {
43
+ padding: 10px;
44
+ background: #f8f9fa;
45
+ border-radius: 4px;
46
+ margin: 5px 0;
47
+ }
48
+ .thinking-container {
49
+ border-left: 3px solid #facc15;
50
+ padding-left: 10px;
51
+ margin: 8px 0;
52
+ background: #210c29;
53
+ }
54
+ details:not([open]) .thinking-container {
55
+ border-left-color: #290c15;
56
+ }
57
+ details {
58
+ border: 1px solid #e0e0e0 !important;
59
+ border-radius: 8px !important;
60
+ padding: 12px !important;
61
+ margin: 8px 0 !important;
62
+ transition: border-color 0.2s;
63
+ }
64
+ """
65
+
66
+ client = OpenAI(base_url="http://localhost:8080/v1", api_key="no-key-required")
67
+
68
+ def user(message, history):
69
+ return "", history + [[message, None]]
70
+
71
+ class ParserState:
72
+ __slots__ = ['answer', 'thought', 'in_think', 'start_time', 'last_pos', 'total_think_time']
73
+ def __init__(self):
74
+ self.answer = ""
75
+ self.thought = ""
76
+ self.in_think = False
77
+ self.start_time = 0
78
+ self.last_pos = 0
79
+ self.total_think_time = 0.0
80
+
81
+ def parse_response(text, state):
82
+ buffer = text[state.last_pos:]
83
+ state.last_pos = len(text)
84
+
85
+ while buffer:
86
+ if not state.in_think:
87
+ think_start = buffer.find('<think>')
88
+ if think_start != -1:
89
+ state.answer += buffer[:think_start]
90
+ state.in_think = True
91
+ state.start_time = time.perf_counter()
92
+ buffer = buffer[think_start + 7:]
93
+ else:
94
+ state.answer += buffer
95
+ break
96
+ else:
97
+ think_end = buffer.find('</think>')
98
+ if think_end != -1:
99
+ state.thought += buffer[:think_end]
100
+ # Calculate duration and accumulate
101
+ duration = time.perf_counter() - state.start_time
102
+ state.total_think_time += duration
103
+ state.in_think = False
104
+ buffer = buffer[think_end + 8:]
105
+ else:
106
+ state.thought += buffer
107
+ break
108
+
109
+ elapsed = time.perf_counter() - state.start_time if state.in_think else 0
110
+ return state, elapsed
111
+
112
+ def format_response(state, elapsed):
113
+ answer_part = state.answer.replace('<think>', '').replace('</think>', '')
114
+ collapsible = []
115
+ collapsed = "<details open>"
116
+
117
+ if state.thought or state.in_think:
118
+ if state.in_think:
119
+ # Ongoing think: total time = accumulated + current elapsed
120
+ total_elapsed = state.total_think_time + elapsed
121
+ formatted_time = format_time(total_elapsed)
122
+ status = f"🌀 Thinking for {formatted_time}"
123
+ else:
124
+ # Finished: show total accumulated time
125
+ formatted_time = format_time(state.total_think_time)
126
+ status = f"✅ Thought for {formatted_time}"
127
+ collapsed = "<details>"
128
+ collapsible.append(
129
+ f"{collapsed}<summary>{status}</summary>\n\n<div class='thinking-container'>\n{state.thought}\n</div>\n</details>"
130
+ )
131
+
132
+ return collapsible, answer_part
133
+
134
+ def generate_response(history, temperature, top_p, max_tokens, active_gen):
135
+ messages = [{"role": "user", "content": history[-1][0]}]
136
+ full_response = ""
137
+ state = ParserState()
138
+ last_update = 0
139
+
140
+ try:
141
+ stream = client.chat.completions.create(
142
+ model="",
143
+ messages=messages,
144
+ temperature=temperature,
145
+ top_p=top_p,
146
+ max_tokens=max_tokens,
147
+ stream=True
148
+ )
149
+
150
+ for chunk in stream:
151
+ if not active_gen[0]:
152
+ break
153
+
154
+ if chunk.choices[0].delta.content:
155
+ full_response += chunk.choices[0].delta.content
156
+ state, elapsed = parse_response(full_response, state)
157
+
158
+ collapsible, answer_part = format_response(state, elapsed)
159
+ history[-1][1] = "\n\n".join(collapsible + [answer_part])
160
+ yield history
161
+
162
+ # Final update to ensure all content is parsed
163
+ state, elapsed = parse_response(full_response, state)
164
+ collapsible, answer_part = format_response(state, elapsed)
165
+ history[-1][1] = "\n\n".join(collapsible + [answer_part])
166
+ yield history
167
+
168
+ except Exception as e:
169
+ history[-1][1] = f"Error: {str(e)}"
170
+ yield history
171
+ finally:
172
+ active_gen[0] = False
173
+
174
+ with gr.Blocks(css=CSS) as demo:
175
+ gr.Markdown(DESCRIPTION)
176
+ active_gen = gr.State([False])
177
+
178
+ chatbot = gr.Chatbot(
179
+ elem_id="chatbot",
180
+ height=500,
181
+ show_label=False,
182
+ render_markdown=True
183
+ )
184
+
185
+ with gr.Row():
186
+ msg = gr.Textbox(
187
+ label="Message",
188
+ placeholder="Type your message...",
189
+ container=False,
190
+ scale=4
191
+ )
192
+ submit_btn = gr.Button("Send", variant='primary', scale=1)
193
+
194
+ with gr.Column(scale=2):
195
+ with gr.Row():
196
+ clear_btn = gr.Button("Clear", variant='secondary')
197
+ stop_btn = gr.Button("Stop", variant='stop')
198
+
199
+ with gr.Accordion("Parameters", open=False):
200
+ temperature = gr.Slider(minimum=0.1, maximum=1.5, value=0.6, label="Temperature")
201
+ top_p = gr.Slider(minimum=0.1, maximum=1.0, value=0.95, label="Top-p")
202
+ max_tokens = gr.Slider(minimum=2048, maximum=32768, value=4096, step=64, label="Max Tokens")
203
+
204
+ gr.Examples(
205
+ examples=[
206
+ ["How many r's are in the word strawberry?"],
207
+ ["Write 10 funny sentences that end in a fruit!"],
208
+ ["Let’s play word chains! I’ll start: PIZZA. Your turn! Next word must start with… A!"]
209
+ ],
210
+ inputs=msg,
211
+ label="Example Prompts"
212
+ )
213
+
214
+ submit_event = submit_btn.click(
215
+ user, [msg, chatbot], [msg, chatbot], queue=False
216
+ ).then(
217
+ lambda: [True], outputs=active_gen
218
+ ).then(
219
+ generate_response, [chatbot, temperature, top_p, max_tokens, active_gen], chatbot
220
+ )
221
+
222
+ msg.submit(
223
+ user, [msg, chatbot], [msg, chatbot], queue=False
224
+ ).then(
225
+ lambda: [True], outputs=active_gen
226
+ ).then(
227
+ generate_response, [chatbot, temperature, top_p, max_tokens, active_gen], chatbot
228
+ )
229
+
230
+ stop_btn.click(
231
+ lambda: [False], None, active_gen, cancels=[submit_event]
232
+ )
233
+
234
+ clear_btn.click(lambda: None, None, chatbot, queue=False)
235
+
236
+ if __name__ == "__main__":
237
+ demo.launch(server_name="0.0.0.0", server_port=7860)
start.sh ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+
3
+ # Start llama-server in background
4
+ cd /llama.cpp/build
5
+ ./bin/llama-bench --model /models/model.q8_0.gguf &
6
+
7
+ # Start llama-server in background
8
+ cd /llama.cpp/build
9
+ ./bin/llama-server --host 0.0.0.0 --port 8080 --model /models/model.q8_0.gguf --ctx-size 32768 --threads 2 &
10
+
11
+ # Wait for server to initialize
12
+ echo "Waiting for server to start..."
13
+ until curl -s "http://localhost:8080/v1/models" >/dev/null; do
14
+ sleep 1
15
+ done
16
+
17
+ echo "Server is ready. Starting Gradio app."
18
+
19
+ # Start Gradio UI
20
+ cd /
21
+ python3 app.py