Nicholas Bumgarner commited on
Commit
a2124e2
·
1 Parent(s): 850c7dc

Convert to Gradio: Phox wave-rider inference engine

Browse files

- Replaced static HTML with Gradio chat interface
- Added phoenix_brain.c (BQSM v8 harmonic inference engine)
- Space downloads model from compunerd/emerging-systems-models
- Compiles C binary at startup with AVX2 + OpenMP
- Shared-memory ring buffer I/O between Python and C
- Tokenizes via Gemma 4 tokenizer from HF Hub

Files changed (6) hide show
  1. README.md +13 -5
  2. app.py +386 -0
  3. index.html +0 -19
  4. phoenix_brain.c +0 -0
  5. requirements.txt +4 -0
  6. style.css +0 -28
README.md CHANGED
@@ -1,11 +1,19 @@
1
  ---
2
- title: Emerging.systems
3
- emoji: 🐢
4
  colorFrom: gray
5
  colorTo: purple
6
- sdk: static
7
  pinned: false
8
- short_description: Exploring the extreme blending of many merging domains
9
  ---
 
10
 
11
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
1
  ---
2
+ title: Phox — Wave-Rider Brain
3
+ emoji: 🌀
4
  colorFrom: gray
5
  colorTo: purple
6
+ sdk: gradio
7
  pinned: false
8
+ short_description: Chat with a Kuramoto oscillator interference engine running on Gemma-4-12B ternary weights
9
  ---
10
+ # Phox — Wave-Rider Inference Engine
11
 
12
+ **BQSM v8 + Phoenix Brain**: A Kuramoto oscillator interference engine running on Gemma-4-12B ternary weights. No matmul — the ring IS the computation.
13
+
14
+ - AVX2 + OpenMP C inference binary compiled at Space startup
15
+ - 48-layer wave-rider physics with traveling wave activation
16
+ - Self-tuning via gradient lens profiles
17
+ - Shared-memory ring buffer I/O between Python and C
18
+
19
+ Check out the code at [github.com/compunerd/basin-quotient-machine](https://github.com/compunerd/basin-quotient-machine)
app.py ADDED
@@ -0,0 +1,386 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Phox on Hugging Face Spaces — BQSM Wave-Rider Inference Engine.
4
+
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
12
+
13
+ The phoenix binary runs on CPU (AVX2) — the wave-rider physics engine
14
+ doesn't use PyTorch, so ZeroGPU doesn't accelerate it directly.
15
+ But the Space provides a free public endpoint to chat with Phox.
16
+ """
17
+ import os
18
+ import sys
19
+ import time
20
+ import json
21
+ 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__))
32
+ MODEL_REPO = "compunerd/emerging-systems-models"
33
+ MODEL_FILENAME = "gemma4-12b-ternary-normed.bqsm"
34
+ MODEL_SUBDIR = os.path.join(SPACE_DIR, "models")
35
+ MODEL_PATH = os.path.join(MODEL_SUBDIR, MODEL_FILENAME)
36
+ STATE_FILE = "/tmp/phoenix_state.jsonl"
37
+ STATE_LOG = "/tmp/phoenix_daemon.log"
38
+ RING_IN_PATH = "/tmp/phoenix_ring_in"
39
+ RING_OUT_PATH = "/tmp/phoenix_ring_out"
40
+ RING_CAPACITY = 4096
41
+ RING_BUF_SIZE = RING_CAPACITY * 4 + 16
42
+ PHOENIX_BIN = os.path.join(SPACE_DIR, "phoenix")
43
+ CHAT_TIMEOUT_S = 30
44
+ SENTINEL_QUIT = 0xFFFFFFFE
45
+
46
+ # ── Global state ──
47
+ _phoenix_proc = None
48
+ _ring_in_mm = None
49
+ _ring_out_mm = None
50
+ _ring_in_fd = None
51
+ _ring_out_fd = None
52
+ _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):
59
+ """Update boot status (thread-safe)."""
60
+ with _state_lock:
61
+ _boot_status["phase"] = phase
62
+ _boot_status["message"] = message
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(
75
+ repo_id=MODEL_REPO,
76
+ filename=MODEL_FILENAME,
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
84
+
85
+ # Phase 2: Build binary
86
+ _update_boot("build", "Compiling phoenix_brain.c (AVX2 + OpenMP)...")
87
+ src_path = os.path.join(SPACE_DIR, "phoenix_brain.c")
88
+ if os.path.exists(src_path):
89
+ cc = os.environ.get("CC", "cc")
90
+ cmd = [cc, "-O3", "-std=c11", "-march=native", "-fopenmp",
91
+ src_path, "-o", PHOENIX_BIN, "-lm"]
92
+ result = subprocess.run(cmd, capture_output=True, text=True)
93
+ if result.returncode != 0:
94
+ _update_boot("build", f"Build FAILED: {result.stderr[:500]}")
95
+ return
96
+ elif not os.path.exists(PHOENIX_BIN):
97
+ _update_boot("build", "No phoenix_brain.c or pre-built binary found!")
98
+ return
99
+
100
+ # Phase 3: Start phoenix
101
+ _update_boot("start", "Starting phoenix in chat mode...")
102
+ global _phoenix_proc
103
+ with _state_lock:
104
+ if _phoenix_proc and _phoenix_proc.poll() is None:
105
+ _update_boot("start", "Already running", ready=True)
106
+ return
107
+
108
+ init_ring_buffers()
109
+
110
+ _phoenix_proc = subprocess.Popen(
111
+ [PHOENIX_BIN, MODEL_PATH, "--chat"],
112
+ stdout=open(STATE_LOG, 'a'),
113
+ stderr=subprocess.STDOUT,
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
+
134
+ _update_boot("ready", "Phoenix likely loaded (timeout) — try chatting!", ready=True)
135
+
136
+
137
+ def init_ring_buffers():
138
+ """Create ring buffer files with initialized headers."""
139
+ for path in [RING_IN_PATH, RING_OUT_PATH]:
140
+ try:
141
+ os.unlink(path)
142
+ except FileNotFoundError:
143
+ pass
144
+ fd = os.open(path, os.O_CREAT | os.O_RDWR, 0o666)
145
+ os.write(fd, b'\x00' * RING_BUF_SIZE)
146
+ os.lseek(fd, 0, 0)
147
+ os.write(fd, struct.pack('<IIII', 0, 0, 0, RING_CAPACITY))
148
+ os.close(fd)
149
+
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):
160
+ head = struct.unpack_from('<I', mm, 0)[0]
161
+ tail = struct.unpack_from('<I', mm, 4)[0]
162
+ sz = struct.unpack_from('<I', mm, 8)[0]
163
+ next_tail = (tail + 1) % RING_CAPACITY
164
+ if next_tail == head:
165
+ return False
166
+ struct.pack_into('<I', mm, 16 + tail * 4, val)
167
+ struct.pack_into('<I', mm, 4, next_tail)
168
+ struct.pack_into('<I', mm, 8, sz + 1)
169
+ return True
170
+
171
+
172
+ def ring_pop(mm):
173
+ head = struct.unpack_from('<I', mm, 0)[0]
174
+ tail = struct.unpack_from('<I', mm, 4)[0]
175
+ sz = struct.unpack_from('<I', mm, 8)[0]
176
+ if sz == 0:
177
+ return None
178
+ val = struct.unpack_from('<I', mm, 16 + head * 4)[0]
179
+ next_head = (head + 1) % RING_CAPACITY
180
+ struct.pack_into('<I', mm, 0, next_head)
181
+ struct.pack_into('<I', mm, 8, sz - 1)
182
+ return val
183
+
184
+
185
+ def send_tokens_to_phoenix(token_ids):
186
+ if not _ring_in_mm:
187
+ return 0
188
+ pushed = 0
189
+ for tid in token_ids:
190
+ if ring_push(_ring_in_mm, tid):
191
+ pushed += 1
192
+ return pushed
193
+
194
+
195
+ def poll_predictions(timeout_s=CHAT_TIMEOUT_S):
196
+ results = []
197
+ start = time.time()
198
+ while time.time() - start < timeout_s:
199
+ tok = ring_pop(_ring_out_mm)
200
+ if tok is not None:
201
+ if tok == SENTINEL_QUIT:
202
+ break
203
+ results.append(tok)
204
+ else:
205
+ time.sleep(0.05)
206
+ return results
207
+
208
+
209
+ def start_phoenix_manual():
210
+ """Start phoenix if not running (for the Start button)."""
211
+ global _phoenix_proc
212
+ with _state_lock:
213
+ if _phoenix_proc and _phoenix_proc.poll() is None:
214
+ return "Already running"
215
+ if not os.path.exists(PHOENIX_BIN):
216
+ return "Binary not built yet"
217
+ if not os.path.exists(MODEL_PATH):
218
+ return "Model not downloaded yet"
219
+ init_ring_buffers()
220
+ _phoenix_proc = subprocess.Popen(
221
+ [PHOENIX_BIN, MODEL_PATH, "--chat"],
222
+ stdout=open(STATE_LOG, 'a'),
223
+ stderr=subprocess.STDOUT,
224
+ )
225
+ return f"Started (PID {_phoenix_proc.pid})"
226
+
227
+
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
+
239
+ if _phoenix_proc and _phoenix_proc.poll() is None:
240
+ _phoenix_proc.terminate()
241
+ try:
242
+ _phoenix_proc.wait(timeout=10)
243
+ except subprocess.TimeoutExpired:
244
+ _phoenix_proc.kill()
245
+
246
+ if _ring_in_mm:
247
+ _ring_in_mm.close()
248
+ _ring_in_mm = None
249
+ if _ring_out_mm:
250
+ _ring_out_mm.close()
251
+ _ring_out_mm = None
252
+ if _ring_in_fd is not None:
253
+ os.close(_ring_in_fd)
254
+ _ring_in_fd = None
255
+ if _ring_out_fd is not None:
256
+ os.close(_ring_out_fd)
257
+ _ring_out_fd = None
258
+ return "Stopped"
259
+
260
+
261
+ def get_boot_status():
262
+ """Return current boot status for the UI."""
263
+ with _state_lock:
264
+ return dict(_boot_status)
265
+
266
+
267
+ def phox_chat(message, history):
268
+ """Main chat function."""
269
+ if not _ring_in_mm or not _ring_out_mm:
270
+ return "Engine not initialized. Please wait for startup."
271
+
272
+ with _state_lock:
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
+
284
+ if not token_ids:
285
+ return "Empty input."
286
+
287
+ pushed = send_tokens_to_phoenix(token_ids)
288
+ if pushed == 0:
289
+ return "Ring buffer full. Try again."
290
+
291
+ pred_ids = poll_predictions()
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
+ print("[Phox Space] Loading tokenizer...")
303
+ _tokenizer = None
304
+ for tok_path in [
305
+ os.path.join(MODEL_SUBDIR, "tokenizer"),
306
+ "/home/compunerd/models/gemma4-tokenizer",
307
+ MODEL_REPO + "/resolve/main/tokenizer",
308
+ ]:
309
+ try:
310
+ _tokenizer = AutoTokenizer.from_pretrained(tok_path)
311
+ print(f"[Phox Space] Tokenizer loaded from {tok_path} (vocab={_tokenizer.vocab_size})")
312
+ break
313
+ except Exception as e:
314
+ print(f"[Phox Space] Tokenizer load from {tok_path}: {e}")
315
+
316
+ if _tokenizer is None:
317
+ # Fallback: try downloading from our model repo
318
+ try:
319
+ _tokenizer = AutoTokenizer.from_pretrained(
320
+ MODEL_REPO, subfolder="tokenizer",
321
+ use_auth_token=os.environ.get("HF_TOKEN"))
322
+ print(f"[Phox Space] Tokenizer downloaded from Hub (vocab={_tokenizer.vocab_size})")
323
+ except Exception as e:
324
+ print(f"[Phox Space] FALLBACK: Tokenizer unavailable: {e}")
325
+ _tokenizer = None
326
+
327
+
328
+ # ── Gradio interface ──
329
+ css = """
330
+ .phox-header { background: #070b13; }
331
+ """
332
+
333
+ with gr.Blocks(css=css, title="Phox — Wave-Rider Brain") as demo:
334
+ gr.Markdown("""
335
+ # 🌀 Phox — Wave-Rider Inference Engine
336
+
337
+ **BQSM v8 + Phoenix Brain**: A Kuramoto oscillator interference engine
338
+ running on Gemma-4-12B ternary weights (80% sparse, 2-bit). No matmul —
339
+ the ring IS the computation.
340
+
341
+ Chat with Phox below. The wave-rider carries your tokens through 48 layers
342
+ of traveling wave activation. Self-tuning via gradient lens profiles.
343
+ """)
344
+
345
+ with gr.Row():
346
+ with gr.Column(scale=3):
347
+ chatbot = gr.ChatInterface(
348
+ fn=phox_chat,
349
+ title="Talk to Phox",
350
+ description="Type a message and watch the oscillators work.",
351
+ )
352
+ with gr.Column(scale=1):
353
+ gr.Markdown("### Engine Status")
354
+ status_json = gr.JSON(label="Boot Status", interactive=False)
355
+ gr.Markdown("### Controls")
356
+ with gr.Row():
357
+ start_btn = gr.Button("Start Engine", variant="primary")
358
+ stop_btn = gr.Button("Stop Engine", variant="secondary")
359
+ status_text = gr.Textbox(label="Engine Output", interactive=False)
360
+
361
+ start_btn.click(fn=start_phoenix_manual, outputs=status_text)
362
+ stop_btn.click(fn=stop_phoenix, outputs=status_text)
363
+
364
+ # Auto-refresh boot status
365
+ demo.load(fn=get_boot_status, outputs=status_json, every=3)
366
+
367
+ # Status text refresh
368
+ status_refresh = gr.State(value=0)
369
+ def tick():
370
+ global status_refresh
371
+ status_refresh.value += 1
372
+ return f"Phase: {_boot_status['phase']} | {_boot_status['message']}"
373
+ status_refresh_timer = demo.load(fn=tick, outputs=status_text, every=2)
374
+
375
+
376
+ if __name__ == "__main__":
377
+ # Start boot sequence in background thread
378
+ _boot_thread = threading.Thread(target=boot_phoenix, daemon=True)
379
+ _boot_thread.start()
380
+
381
+ app = demo.queue()
382
+ app.launch(
383
+ server_name="0.0.0.0",
384
+ server_port=int(os.environ.get("PORT", 7860)),
385
+ share=False,
386
+ )
index.html DELETED
@@ -1,19 +0,0 @@
1
- <!doctype html>
2
- <html>
3
- <head>
4
- <meta charset="utf-8" />
5
- <meta name="viewport" content="width=device-width" />
6
- <title>My static Space</title>
7
- <link rel="stylesheet" href="style.css" />
8
- </head>
9
- <body>
10
- <div class="card">
11
- <h1>Welcome to your static Space!</h1>
12
- <p>You can modify this app directly by editing <i>index.html</i> in the Files and versions tab.</p>
13
- <p>
14
- Also don't forget to check the
15
- <a href="https://huggingface.co/docs/hub/spaces" target="_blank">Spaces documentation</a>.
16
- </p>
17
- </div>
18
- </body>
19
- </html>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
phoenix_brain.c ADDED
The diff for this file is too large to render. See raw diff
 
requirements.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ gradio>=4.0
2
+ transformers>=4.30
3
+ huggingface_hub>=0.20
4
+ numpy
style.css DELETED
@@ -1,28 +0,0 @@
1
- body {
2
- padding: 2rem;
3
- font-family: -apple-system, BlinkMacSystemFont, "Arial", sans-serif;
4
- }
5
-
6
- h1 {
7
- font-size: 16px;
8
- margin-top: 0;
9
- }
10
-
11
- p {
12
- color: rgb(107, 114, 128);
13
- font-size: 15px;
14
- margin-bottom: 10px;
15
- margin-top: 5px;
16
- }
17
-
18
- .card {
19
- max-width: 620px;
20
- margin: 0 auto;
21
- padding: 16px;
22
- border: 1px solid lightgray;
23
- border-radius: 16px;
24
- }
25
-
26
- .card p:last-child {
27
- margin-bottom: 0;
28
- }