Nicholas Bumgarner commited on
Commit
4aa8326
·
1 Parent(s): 26b395e

Fix Gradio 6.22 + remove torch dep: use tokenizers lib, gr.Timer API

Browse files
Files changed (2) hide show
  1. app.py +53 -46
  2. requirements.txt +1 -1
app.py CHANGED
@@ -5,7 +5,7 @@ Phox on Hugging Face Spaces — BQSM Wave-Rider Inference Engine.
5
  This app wraps the Phoenix Brain C inference binary in a Gradio interface.
6
  At Space startup it:
7
  1. Downloads the Gemma-4-12B ternary model from HF Hub
8
- 2. Downloads the Gemma 4 tokenizer
9
  3. Compiles phoenix_brain.c with AVX2 + OpenMP
10
  4. Starts phoenix in --chat mode with shared-memory ring buffers
11
  5. Provides a chat UI via Gradio
@@ -22,10 +22,9 @@ import mmap
22
  import struct
23
  import subprocess
24
  import threading
25
- import numpy as np
26
 
27
  import gradio as gr
28
- from transformers import AutoTokenizer
29
 
30
  # ── Config ──
31
  SPACE_DIR = os.path.dirname(os.path.abspath(__file__))
@@ -53,6 +52,7 @@ _state_lock = threading.Lock()
53
  _chat_messages = []
54
  _boot_status = {"ready": False, "phase": "idle", "message": "Not started"}
55
  _boot_thread = None
 
56
 
57
 
58
  def _update_boot(phase, message, ready=False):
@@ -63,12 +63,47 @@ def _update_boot(phase, message, ready=False):
63
  _boot_status["ready"] = ready
64
 
65
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
66
  def boot_phoenix():
67
  """Full startup sequence: download model, build binary, start phoenix."""
 
 
 
 
68
  # Phase 1: Download model
69
  _update_boot("download", "Downloading BQSM model from HF Hub...")
70
  try:
71
- from huggingface_hub import hf_hub_download
72
  os.makedirs(MODEL_SUBDIR, exist_ok=True)
73
  if not os.path.exists(MODEL_PATH):
74
  hf_hub_download(
@@ -77,7 +112,7 @@ def boot_phoenix():
77
  local_dir=MODEL_SUBDIR,
78
  local_dir_use_symlinks=False,
79
  )
80
- _update_boot("download", f"Model ready: {MODEL_PATH}")
81
  except Exception as e:
82
  _update_boot("download", f"Model download FAILED: {e}")
83
  return
@@ -114,20 +149,19 @@ def boot_phoenix():
114
  )
115
  _update_boot("start", f"Phoenix PID {_phoenix_proc.pid} — loading model (~40s)...")
116
 
117
- # Phase 4: Wait for model load by monitoring process
118
  time.sleep(2)
119
  for i in range(60):
120
  if _phoenix_proc.poll() is not None:
121
  _update_boot("error", f"Phoenix exited early (code {_phoenix_proc.returncode})")
122
  return
123
- # Check if it's past the model loading phase by checking daemon log
124
  try:
125
  with open(STATE_LOG, 'r') as f:
126
  log = f.read()
127
- if "Chat Mode" in log or "Loaded" in log:
128
  _update_boot("ready", "Phoenix ready — chat interface active!", ready=True)
129
  return
130
- except:
131
  pass
132
  time.sleep(1)
133
 
@@ -150,10 +184,10 @@ def init_ring_buffers():
150
  global _ring_in_fd, _ring_out_fd, _ring_in_mm, _ring_out_mm
151
  _ring_in_fd = os.open(RING_IN_PATH, os.O_RDWR)
152
  _ring_in_mm = mmap.mmap(_ring_in_fd, RING_BUF_SIZE,
153
- mmap.MAP_SHARED, mmap.PROT_READ | mmap.PROT_WRITE)
154
  _ring_out_fd = os.open(RING_OUT_PATH, os.O_RDWR)
155
  _ring_out_mm = mmap.mmap(_ring_out_fd, RING_BUF_SIZE,
156
- mmap.MAP_SHARED, mmap.PROT_READ | mmap.PROT_WRITE)
157
 
158
 
159
  def ring_push(mm, val):
@@ -228,11 +262,10 @@ def start_phoenix_manual():
228
  def stop_phoenix():
229
  global _phoenix_proc, _ring_in_mm, _ring_out_mm, _ring_in_fd, _ring_out_fd
230
  with _state_lock:
231
- # Send quit sentinel
232
  if _ring_in_mm:
233
  try:
234
  ring_push(_ring_in_mm, SENTINEL_QUIT)
235
- except:
236
  pass
237
  time.sleep(0.5)
238
 
@@ -273,11 +306,11 @@ def phox_chat(message, history):
273
  if _phoenix_proc is None or _phoenix_proc.poll() is not None:
274
  return "Phoenix is not running. Please click 'Start Engine' first."
275
 
276
- # Tokenize
277
  if _tokenizer is None:
278
  return "Tokenizer not loaded."
 
279
  try:
280
- token_ids = _tokenizer.encode(message, add_special_tokens=False)
281
  except Exception as e:
282
  return f"Tokenization error: {e}"
283
 
@@ -292,38 +325,10 @@ def phox_chat(message, history):
292
  if not pred_ids:
293
  return "No prediction received (timeout). Try again."
294
 
295
- if _tokenizer is None:
296
- return "Tokenizer not loaded."
297
  response = _tokenizer.decode(pred_ids, skip_special_tokens=True)
298
  return response.strip() if response else "[no output]"
299
 
300
 
301
- # ── Tokenizer ──
302
- # On HF Spaces, we always download from our model repo.
303
- # The tokenizer is stored under the "tokenizer/" subfolder.
304
- print("[Phox Space] Loading Gemma 4 tokenizer from Hub...")
305
- _tokenizer = None
306
- try:
307
- _tokenizer = AutoTokenizer.from_pretrained(
308
- MODEL_REPO, subfolder="tokenizer")
309
- print(f"[Phox Space] Tokenizer loaded (vocab={_tokenizer.vocab_size})")
310
- except Exception as e:
311
- print(f"[Phox Space] Tokenizer download failed: {e}")
312
- # Fallback: try local paths (for local testing)
313
- for tok_path in [
314
- os.path.join(MODEL_SUBDIR, "tokenizer"),
315
- "/home/compunerd/models/gemma4-tokenizer",
316
- ]:
317
- try:
318
- _tokenizer = AutoTokenizer.from_pretrained(tok_path)
319
- print(f"[Phox Space] Tokenizer loaded from {tok_path}")
320
- break
321
- except Exception:
322
- pass
323
- if _tokenizer is None:
324
- print("[Phox Space] WARNING: No tokenizer available — chat will not work")
325
-
326
-
327
  # ── Gradio interface ──
328
 
329
  with gr.Blocks(title="Phox — Wave-Rider Brain") as demo:
@@ -357,11 +362,13 @@ with gr.Blocks(title="Phox — Wave-Rider Brain") as demo:
357
  start_btn.click(fn=start_phoenix_manual, outputs=status_text)
358
  stop_btn.click(fn=stop_phoenix, outputs=status_text)
359
 
360
- # Auto-refresh boot status
361
  def tick():
362
  return f"Phase: {_boot_status['phase']} | {_boot_status['message']}"
363
- demo.load(fn=get_boot_status, outputs=status_json, every=3)
364
- demo.load(fn=tick, outputs=status_text, every=2)
 
 
365
 
366
 
367
  if __name__ == "__main__":
 
5
  This app wraps the Phoenix Brain C inference binary in a Gradio interface.
6
  At Space startup it:
7
  1. Downloads the Gemma-4-12B ternary model from HF Hub
8
+ 2. Downloads the Gemma 4 tokenizer (via tokenizers library, no PyTorch needed)
9
  3. Compiles phoenix_brain.c with AVX2 + OpenMP
10
  4. Starts phoenix in --chat mode with shared-memory ring buffers
11
  5. Provides a chat UI via Gradio
 
22
  import struct
23
  import subprocess
24
  import threading
 
25
 
26
  import gradio as gr
27
+ from huggingface_hub import hf_hub_download
28
 
29
  # ── Config ──
30
  SPACE_DIR = os.path.dirname(os.path.abspath(__file__))
 
52
  _chat_messages = []
53
  _boot_status = {"ready": False, "phase": "idle", "message": "Not started"}
54
  _boot_thread = None
55
+ _tokenizer = None
56
 
57
 
58
  def _update_boot(phase, message, ready=False):
 
63
  _boot_status["ready"] = ready
64
 
65
 
66
+ def load_tokenizer():
67
+ """Download and load the Gemma 4 tokenizer from HF Hub."""
68
+ global _tokenizer
69
+ print("[Phox Space] Loading Gemma 4 tokenizer from Hub...")
70
+ try:
71
+ tok_path = hf_hub_download(
72
+ repo_id=MODEL_REPO,
73
+ filename="tokenizer/tokenizer.json")
74
+ from tokenizers import Tokenizer
75
+ _tokenizer = Tokenizer.from_file(tok_path)
76
+ # Build a simple vocab-size attribute for compatibility
77
+ _tokenizer.vocab_size = len(_tokenizer.get_vocab(with_added=False))
78
+ print(f"[Phox Space] Tokenizer loaded (vocab={_tokenizer.vocab_size})")
79
+ except Exception as e:
80
+ print(f"[Phox Space] Tokenizer download failed: {e}")
81
+ # Fallback: try local paths
82
+ for tok_path in [
83
+ os.path.join(MODEL_SUBDIR, "tokenizer", "tokenizer.json"),
84
+ "/home/compunerd/models/gemma4-tokenizer/tokenizer.json",
85
+ ]:
86
+ try:
87
+ from tokenizers import Tokenizer
88
+ _tokenizer = Tokenizer.from_file(tok_path)
89
+ _tokenizer.vocab_size = len(_tokenizer.get_vocab(with_added=False))
90
+ print(f"[Phox Space] Tokenizer loaded from {tok_path}")
91
+ break
92
+ except Exception:
93
+ pass
94
+ if _tokenizer is None:
95
+ print("[Phox Space] WARNING: No tokenizer available — chat will not work")
96
+
97
+
98
  def boot_phoenix():
99
  """Full startup sequence: download model, build binary, start phoenix."""
100
+ # Phase 0: Tokenizer
101
+ _update_boot("tokenizer", "Loading tokenizer from Hub...")
102
+ load_tokenizer()
103
+
104
  # Phase 1: Download model
105
  _update_boot("download", "Downloading BQSM model from HF Hub...")
106
  try:
 
107
  os.makedirs(MODEL_SUBDIR, exist_ok=True)
108
  if not os.path.exists(MODEL_PATH):
109
  hf_hub_download(
 
112
  local_dir=MODEL_SUBDIR,
113
  local_dir_use_symlinks=False,
114
  )
115
+ _update_boot("download", f"Model ready: {os.path.getsize(MODEL_PATH)} bytes")
116
  except Exception as e:
117
  _update_boot("download", f"Model download FAILED: {e}")
118
  return
 
149
  )
150
  _update_boot("start", f"Phoenix PID {_phoenix_proc.pid} — loading model (~40s)...")
151
 
152
+ # Phase 4: Wait for model load
153
  time.sleep(2)
154
  for i in range(60):
155
  if _phoenix_proc.poll() is not None:
156
  _update_boot("error", f"Phoenix exited early (code {_phoenix_proc.returncode})")
157
  return
 
158
  try:
159
  with open(STATE_LOG, 'r') as f:
160
  log = f.read()
161
+ if "Chat Mode" in log:
162
  _update_boot("ready", "Phoenix ready — chat interface active!", ready=True)
163
  return
164
+ except Exception:
165
  pass
166
  time.sleep(1)
167
 
 
184
  global _ring_in_fd, _ring_out_fd, _ring_in_mm, _ring_out_mm
185
  _ring_in_fd = os.open(RING_IN_PATH, os.O_RDWR)
186
  _ring_in_mm = mmap.mmap(_ring_in_fd, RING_BUF_SIZE,
187
+ mmap.MAP_SHARED, mmap.PROT_READ | mmap.PROT_WRITE)
188
  _ring_out_fd = os.open(RING_OUT_PATH, os.O_RDWR)
189
  _ring_out_mm = mmap.mmap(_ring_out_fd, RING_BUF_SIZE,
190
+ mmap.MAP_SHARED, mmap.PROT_READ | mmap.PROT_WRITE)
191
 
192
 
193
  def ring_push(mm, val):
 
262
  def stop_phoenix():
263
  global _phoenix_proc, _ring_in_mm, _ring_out_mm, _ring_in_fd, _ring_out_fd
264
  with _state_lock:
 
265
  if _ring_in_mm:
266
  try:
267
  ring_push(_ring_in_mm, SENTINEL_QUIT)
268
+ except Exception:
269
  pass
270
  time.sleep(0.5)
271
 
 
306
  if _phoenix_proc is None or _phoenix_proc.poll() is not None:
307
  return "Phoenix is not running. Please click 'Start Engine' first."
308
 
 
309
  if _tokenizer is None:
310
  return "Tokenizer not loaded."
311
+
312
  try:
313
+ token_ids = _tokenizer.encode(message).ids
314
  except Exception as e:
315
  return f"Tokenization error: {e}"
316
 
 
325
  if not pred_ids:
326
  return "No prediction received (timeout). Try again."
327
 
 
 
328
  response = _tokenizer.decode(pred_ids, skip_special_tokens=True)
329
  return response.strip() if response else "[no output]"
330
 
331
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
332
  # ── Gradio interface ──
333
 
334
  with gr.Blocks(title="Phox — Wave-Rider Brain") as demo:
 
362
  start_btn.click(fn=start_phoenix_manual, outputs=status_text)
363
  stop_btn.click(fn=stop_phoenix, outputs=status_text)
364
 
365
+ # Periodic status refresh using gr.Timer (Gradio 6.x API)
366
  def tick():
367
  return f"Phase: {_boot_status['phase']} | {_boot_status['message']}"
368
+ timer1 = gr.Timer(3, active=True)
369
+ timer1.tick(fn=get_boot_status, outputs=status_json)
370
+ timer2 = gr.Timer(2, active=True)
371
+ timer2.tick(fn=tick, outputs=status_text)
372
 
373
 
374
  if __name__ == "__main__":
requirements.txt CHANGED
@@ -1,4 +1,4 @@
1
  gradio>=6.0
2
- transformers>=4.46
3
  huggingface_hub>=0.20
4
  numpy
 
1
  gradio>=6.0
2
+ tokenizers>=0.15
3
  huggingface_hub>=0.20
4
  numpy