redhairedshanks1 commited on
Commit
1612fe8
·
verified ·
1 Parent(s): 893d9ce

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +339 -42
app.py CHANGED
@@ -1,36 +1,194 @@
1
  import os
2
  import re
 
 
3
  import gradio as gr
 
 
 
 
 
 
 
4
  from llama_cpp import Llama
5
- from huggingface_hub import login
6
  from transformers import AutoTokenizer
7
 
8
- # If your model/quant repo is gated, add an HF token as a Space secret named HF_TOKEN
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
  HF_TOKEN = os.getenv("HF_TOKEN")
10
  if HF_TOKEN:
11
- login(HF_TOKEN)
12
-
13
- # Choose a base model ID (for tokenizer/chat template) and a GGUF file to load
14
- # Defaults target the Llama 8B distill. You can change these three vars.
15
- MODEL_ID = os.getenv("MODEL_ID", "deepseek-ai/DeepSeek-R1-Distill-Llama-8B")
16
- GGUF_REPO = os.getenv("GGUF_REPO", "TheBloke/DeepSeek-R1-Distill-Llama-8B-GGUF")
17
- GGUF_FILE = os.getenv("GGUF_FILE", "deepseek-r1-distill-llama-8b.Q4_K_M.gguf")
18
-
19
- # Load tokenizer (to apply chat template correctly)
20
- tokenizer = AutoTokenizer.from_pretrained(MODEL_ID, trust_remote_code=True)
21
-
22
- # Load the quantized model via llama.cpp (downloads just the selected file)
23
- llm = Llama.from_pretrained(
24
- repo_id=GGUF_REPO,
25
- filename=GGUF_FILE,
26
- n_ctx=4096,
27
- n_threads=max(1, (os.cpu_count() or 2) // 2),
28
- n_batch=128,
29
- verbose=False,
30
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
31
 
32
- def apply_template(history, message):
33
- # history is list of [user, assistant]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34
  msgs = []
35
  for u, a in history:
36
  if u:
@@ -42,25 +200,164 @@ def apply_template(history, message):
42
  msgs, tokenize=False, add_generation_prompt=True
43
  )
44
 
45
- def strip_reasoning(text):
46
- # Hide DeepSeek-style reasoning tokens if desired
47
- return re.sub(r"<\|begin_of_thought\|>.*?<\|end_of_thought\|>", "", text, flags=re.DOTALL)
48
 
49
- def chat_fn(message, history, max_new_tokens, temperature, top_p, show_reasoning):
50
- prompt = apply_template(history, message)
51
- stream = llm(
52
- prompt,
53
- max_tokens=int(max_new_tokens),
54
- temperature=float(temperature),
55
- top_p=float(top_p),
56
- stop=[tokenizer.eos_token or "", "<|eot_id|>"],
57
- stream=True,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
58
  )
59
- raw = ""
60
- for part in stream:
61
- delta = part["choices"][0]["text"]
62
- raw += delta
63
- yield raw if show_reasoning else strip_reasoning(raw)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
64
 
65
  demo = gr.ChatInterface(
66
  fn=chat_fn,
@@ -71,7 +368,7 @@ demo = gr.ChatInterface(
71
  gr.Checkbox(label="Show reasoning", value=False),
72
  ],
73
  title="DeepSeek R1 Distill (CPU, GGUF)",
74
- description="Running a distilled DeepSeek R1 on free-tier CPU. Expect slow generation.",
75
  examples=[
76
  "Prove that the sum of two even numbers is even.",
77
  "A train leaves at 3 PM at 60 km/h. Another at 4 PM at 80 km/h. When will the second catch up?",
 
1
  import os
2
  import re
3
+ import sys
4
+ import traceback
5
  import gradio as gr
6
+
7
+ from huggingface_hub import (
8
+ login,
9
+ HfApi,
10
+ hf_hub_download,
11
+ whoami,
12
+ )
13
  from llama_cpp import Llama
 
14
  from transformers import AutoTokenizer
15
 
16
+ """
17
+ Environment variables you can set in your Space (Settings -> Variables & secrets):
18
+
19
+ Required (pick one of these approaches):
20
+ - GGUF_REPO: The Hugging Face repo that contains your .gguf files
21
+ - GGUF_FILE: The specific .gguf filename to load from that repo
22
+
23
+ Optional (recommended):
24
+ - MODEL_ID: Base model repo to pull the tokenizer/chat template from.
25
+ Use the matching family for your quant:
26
+ - Qwen family: deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B or -Qwen-7B
27
+ - Llama family: deepseek-ai/DeepSeek-R1-Distill-Llama-8B
28
+
29
+ If MODEL_ID is not set, we will attempt to guess it from GGUF_REPO.
30
+
31
+ Other optional env vars:
32
+ - HF_TOKEN: If your repo is gated/private, add this as a Space secret (read scope).
33
+ - PREFER_FAMILY: "qwen" or "llama" (only used if we need to guess MODEL_ID). Default: qwen
34
+ - PREFER_SIZE: "1.5b", "7b", or "8b" (only used if we need to guess MODEL_ID). Default: 1.5b
35
+ - N_CTX: context window (default 4096)
36
+ - N_THREADS: CPU threads (default: half your CPU cores, at least 1)
37
+ - N_BATCH: batch size (default 128)
38
+ """
39
+
40
+ # --------------------
41
+ # Auth (optional)
42
+ # --------------------
43
  HF_TOKEN = os.getenv("HF_TOKEN")
44
  if HF_TOKEN:
45
+ try:
46
+ login(HF_TOKEN)
47
+ try:
48
+ user = whoami().get("name", "ok")
49
+ print(f"[auth] Logged into Hugging Face as: {user}")
50
+ except Exception:
51
+ print("[auth] Logged in (could not fetch user name).")
52
+ except Exception as e:
53
+ print(f"[auth] Failed to login with HF_TOKEN: {e}")
54
+
55
+ # --------------------
56
+ # Config / Defaults
57
+ # --------------------
58
+ GGUF_REPO = os.getenv("GGUF_REPO", "").strip()
59
+ GGUF_FILE = os.getenv("GGUF_FILE", "").strip()
60
+
61
+ PREFER_FAMILY = os.getenv("PREFER_FAMILY", "qwen").lower()
62
+ PREFER_SIZE = os.getenv("PREFER_SIZE", "1.5b").lower()
63
+
64
+ # Runtime knobs
65
+ def _default_threads():
66
+ try:
67
+ cores = os.cpu_count() or 2
68
+ return max(1, cores // 2) # be gentle on free CPU
69
+ except Exception:
70
+ return 1
71
+
72
+ N_CTX = int(os.getenv("N_CTX", "4096"))
73
+ N_THREADS = int(os.getenv("N_THREADS", str(_default_threads())))
74
+ N_BATCH = int(os.getenv("N_BATCH", "128"))
75
+
76
+ # --------------------
77
+ # Helpers
78
+ # --------------------
79
+ api = HfApi()
80
+
81
+
82
+ def repo_exists(repo_id: str) -> bool:
83
+ try:
84
+ api.model_info(repo_id)
85
+ return True
86
+ except Exception:
87
+ return False
88
+
89
+
90
+ def pick_q4_file(repo_id: str) -> str:
91
+ """Choose a reasonable 4-bit GGUF from a repo (prefer Q4_K_M, then Q4_0)."""
92
+ info = api.model_info(repo_id)
93
+ ggufs = [s.rfilename for s in info.siblings if s.rfilename.lower().endswith(".gguf")]
94
+
95
+ # Prefer Q4_K_M, then any Q4, then Q3 as last resort
96
+ priority = []
97
+ for f in ggufs:
98
+ fl = f.lower()
99
+ score = 0
100
+ if "q4_k_m" in fl:
101
+ score = 100
102
+ elif "q4_k_s" in fl or "q4_k_l" in fl or "q4_k" in fl:
103
+ score = 95
104
+ elif "q4_0" in fl or "q4" in fl:
105
+ score = 90
106
+ elif "q3_k_m" in fl or "q3" in fl:
107
+ score = 70
108
+ else:
109
+ score = 10
110
+ priority.append((score, f))
111
+
112
+ if not priority:
113
+ raise FileNotFoundError(f"No .gguf files found in {repo_id}")
114
+
115
+ priority.sort(reverse=True, key=lambda x: x[0])
116
+ chosen = priority[0][1]
117
+ return chosen
118
+
119
+
120
+ def guess_model_id_from_repo(repo_id: str) -> str:
121
+ """Guess a matching tokenizer/chat-template model based on the GGUF repo name."""
122
+ rid = repo_id.lower()
123
+ # Family
124
+ if "qwen" in rid or PREFER_FAMILY == "qwen":
125
+ # Size
126
+ if "1.5" in rid or "1_5" in rid or PREFER_SIZE == "1.5b":
127
+ return "deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B"
128
+ elif "7b" in rid or PREFER_SIZE == "7b":
129
+ return "deepseek-ai/DeepSeek-R1-Distill-Qwen-7B"
130
+ else:
131
+ return "deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B"
132
+ # Llama family
133
+ if "llama" in rid or PREFER_FAMILY == "llama":
134
+ return "deepseek-ai/DeepSeek-R1-Distill-Llama-8B"
135
+ # Fallback
136
+ return "deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B"
137
 
138
+
139
+ def ensure_model_source(repo_id: str | None, filename: str | None) -> tuple[str, str]:
140
+ """
141
+ Ensure we have a valid GGUF repo + file.
142
+ - If both provided, verify they exist.
143
+ - If only repo provided, pick a reasonable Q4 file.
144
+ - If none provided, raise with a helpful message.
145
+ """
146
+ if repo_id and filename:
147
+ try:
148
+ api.model_info(repo_id) # raises if missing or no access
149
+ except Exception as e:
150
+ raise FileNotFoundError(
151
+ f"Repo not accessible: {repo_id}\n{e}\n"
152
+ "Check the repo id spelling, your HF token, and license access."
153
+ )
154
+ # Now check the file exists in the repo
155
+ info = api.model_info(repo_id)
156
+ files = {s.rfilename for s in info.siblings}
157
+ if filename not in files:
158
+ # Try case-insensitive match
159
+ lower_map = {s.rfilename.lower(): s.rfilename for s in info.siblings}
160
+ if filename.lower() in lower_map:
161
+ filename = lower_map[filename.lower()]
162
+ else:
163
+ raise FileNotFoundError(
164
+ f"File not found in repo: {filename}\n"
165
+ f"Available gguf files: {[f for f in files if f.lower().endswith('.gguf')]}"
166
+ )
167
+ return repo_id, filename
168
+
169
+ if repo_id and not filename:
170
+ return repo_id, pick_q4_file(repo_id)
171
+
172
+ raise ValueError(
173
+ "No GGUF_REPO/GGUF_FILE provided. Set them in your Space Variables.\n"
174
+ "Examples you can try (you must verify these exist and accept access if gated):\n"
175
+ " - GGUF_REPO = TheBloke/DeepSeek-R1-Distill-Qwen-7B-GGUF\n"
176
+ " GGUF_FILE = deepseek-r1-distill-qwen-7b.Q4_K_M.gguf\n"
177
+ " - GGUF_REPO = bartowski/DeepSeek-R1-Distill-Qwen-1.5B-GGUF\n"
178
+ " GGUF_FILE = deepseek-r1-distill-qwen-1.5b.Q4_K_M.gguf\n"
179
+ " - GGUF_REPO = MaziyarPanahi/DeepSeek-R1-Distill-Llama-8B-GGUF\n"
180
+ " GGUF_FILE = deepseek-r1-distill-llama-8b.Q4_K_M.gguf\n"
181
+ )
182
+
183
+
184
+ def build_tokenizer(model_id: str) -> AutoTokenizer:
185
+ print(f"[tokenizer] Loading tokenizer/chat template from {model_id}")
186
+ tok = AutoTokenizer.from_pretrained(model_id, trust_remote_code=True)
187
+ return tok
188
+
189
+
190
+ def apply_template(tokenizer: AutoTokenizer, history, message: str) -> str:
191
+ # history: list of [user, assistant]
192
  msgs = []
193
  for u, a in history:
194
  if u:
 
200
  msgs, tokenize=False, add_generation_prompt=True
201
  )
202
 
 
 
 
203
 
204
+ def strip_reasoning(text: str) -> str:
205
+ # Hide DeepSeek-style reasoning tags if present
206
+ return re.sub(
207
+ r"<\|begin_of_thought\|>.*?<\|end_of_thought\|>",
208
+ "",
209
+ text,
210
+ flags=re.DOTALL,
211
+ )
212
+
213
+
214
+ # --------------------
215
+ # Resolve model + file
216
+ # --------------------
217
+ try:
218
+ GGUF_REPO, GGUF_FILE = ensure_model_source(GGUF_REPO, GGUF_FILE)
219
+ print(f"[gguf] Using repo: {GGUF_REPO}")
220
+ print(f"[gguf] Using file: {GGUF_FILE}")
221
+ except Exception as e:
222
+ # Fail fast with a clear error; Gradio will show logs
223
+ print("[startup] Failed to resolve GGUF model source:")
224
+ print(e)
225
+ traceback.print_exc()
226
+ # Provide a minimal dummy UI to show the error instead of crashing Space build
227
+ def _error_ui():
228
+ return gr.Markdown(
229
+ f"Cannot start: {e}\n\n"
230
+ "Go to Settings → Variables and set GGUF_REPO and GGUF_FILE to a valid GGUF."
231
+ )
232
+ with gr.Blocks() as demo:
233
+ gr.Markdown("# DeepSeek R1 Distill (CPU, GGUF)")
234
+ _error_ui()
235
+ if __name__ == "__main__":
236
+ demo.launch()
237
+ sys.exit(0)
238
+
239
+ # Guess MODEL_ID if not provided
240
+ MODEL_ID = os.getenv("MODEL_ID", "").strip()
241
+ if not MODEL_ID:
242
+ MODEL_ID = guess_model_id_from_repo(GGUF_REPO)
243
+
244
+ # --------------------
245
+ # Download and load
246
+ # --------------------
247
+ try:
248
+ # Download exact file; raises if not found or no access
249
+ print(f"[download] Fetching {GGUF_FILE} from {GGUF_REPO} ...")
250
+ model_path = hf_hub_download(repo_id=GGUF_REPO, filename=GGUF_FILE)
251
+ print(f"[download] File ready at: {model_path}")
252
+ except Exception as e:
253
+ print("[download] Failed to download the GGUF file:")
254
+ print(e)
255
+ traceback.print_exc()
256
+ # Same graceful error UI
257
+ def _error_ui():
258
+ return gr.Markdown(
259
+ f"Download failed: {e}\n\n"
260
+ "Check that GGUF_REPO and GGUF_FILE are correct and your HF_TOKEN has access."
261
+ )
262
+ with gr.Blocks() as demo:
263
+ gr.Markdown("# DeepSeek R1 Distill (CPU, GGUF)")
264
+ _error_ui()
265
+ if __name__ == "__main__":
266
+ demo.launch()
267
+ sys.exit(0)
268
+
269
+ # Load tokenizer for chat template
270
+ try:
271
+ tokenizer = build_tokenizer(MODEL_ID)
272
+ except Exception as e:
273
+ print("[tokenizer] Failed to load tokenizer/chat template:")
274
+ print(e)
275
+ traceback.print_exc()
276
+ # Still try to continue with a naive prompt if tokenizer fails
277
+ tokenizer = None
278
+ def naive_template(history, message):
279
+ # Simple ChatML-like format
280
+ parts = []
281
+ for u, a in history:
282
+ if u:
283
+ parts.append(f"<|im_start|>user\n{u}\n<|im_end|>")
284
+ if a:
285
+ parts.append(f"<|im_start|>assistant\n{a}\n<|im_end|>")
286
+ parts.append(f"<|im_start|>user\n{message}\n<|im_end|>\n<|im_start|>assistant\n")
287
+ return "\n".join(parts)
288
+
289
+ def make_prompt(history, message):
290
+ if tokenizer is not None:
291
+ return apply_template(tokenizer, history, message)
292
+ return naive_template(history, message) # type: ignore[name-defined]
293
+
294
+ # Load llama.cpp
295
+ try:
296
+ llm = Llama(
297
+ model_path=model_path,
298
+ n_ctx=N_CTX,
299
+ n_threads=N_THREADS,
300
+ n_batch=N_BATCH,
301
+ n_gpu_layers=0, # CPU Space
302
+ verbose=False,
303
  )
304
+ print("[llama] Model loaded.")
305
+ except Exception as e:
306
+ print("[llama] Failed to load llama.cpp with the downloaded GGUF:")
307
+ print(e)
308
+ traceback.print_exc()
309
+ def _error_ui():
310
+ return gr.Markdown(f"Failed to load model: {e}")
311
+ with gr.Blocks() as demo:
312
+ gr.Markdown("# DeepSeek R1 Distill (CPU, GGUF)")
313
+ _error_ui()
314
+ if __name__ == "__main__":
315
+ demo.launch()
316
+ sys.exit(0)
317
+
318
+ # --------------------
319
+ # Gradio app
320
+ # --------------------
321
+ def chat_fn(message, history, max_new_tokens, temperature, top_p, show_reasoning):
322
+ try:
323
+ prompt = make_prompt(history, message)
324
+ # Common stop markers; eos from tokenizer if available
325
+ stops = ["<|eot_id|>", "<|im_end|>", "<|end_of_text|>"]
326
+ try:
327
+ if tokenizer is not None and getattr(tokenizer, "eos_token", None):
328
+ eos = tokenizer.eos_token
329
+ if eos and eos not in stops:
330
+ stops.append(eos)
331
+ except Exception:
332
+ pass
333
+
334
+ stream = llm(
335
+ prompt,
336
+ max_tokens=int(max_new_tokens),
337
+ temperature=float(temperature),
338
+ top_p=float(top_p),
339
+ stop=stops,
340
+ stream=True,
341
+ )
342
+ raw = ""
343
+ for part in stream:
344
+ delta = part["choices"][0]["text"]
345
+ raw += delta
346
+ yield raw if show_reasoning else strip_reasoning(raw)
347
+ except Exception as e:
348
+ err = f"[error] {type(e).__name__}: {e}"
349
+ yield err
350
+
351
+ header_md = f"""
352
+ ### DeepSeek R1 Distill (CPU, GGUF)
353
+ Loaded:
354
+ - GGUF_REPO: `{GGUF_REPO}`
355
+ - GGUF_FILE: `{GGUF_FILE}`
356
+ - Chat template from: `{MODEL_ID}`
357
+ - n_ctx={N_CTX}, n_threads={N_THREADS}, n_batch={N_BATCH}
358
+
359
+ Tip: If you see a 404/403 at startup, set GGUF_REPO/GGUF_FILE correctly and ensure HF_TOKEN has access.
360
+ """
361
 
362
  demo = gr.ChatInterface(
363
  fn=chat_fn,
 
368
  gr.Checkbox(label="Show reasoning", value=False),
369
  ],
370
  title="DeepSeek R1 Distill (CPU, GGUF)",
371
+ description=header_md,
372
  examples=[
373
  "Prove that the sum of two even numbers is even.",
374
  "A train leaves at 3 PM at 60 km/h. Another at 4 PM at 80 km/h. When will the second catch up?",