Spaces:
Running on Zero
Running on Zero
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,101 +1,118 @@
|
|
| 1 |
"""alephllm-chat — talk to Beatrix.
|
| 2 |
-
|
| 3 |
-
|
| 4 |
-
chat
|
| 5 |
-
|
| 6 |
-
|
|
|
|
|
|
|
|
|
|
| 7 |
"""
|
|
|
|
| 8 |
import json
|
| 9 |
import os
|
| 10 |
import re
|
| 11 |
-
import
|
| 12 |
import time
|
| 13 |
import uuid
|
| 14 |
from datetime import datetime, timezone
|
| 15 |
from pathlib import Path
|
| 16 |
|
| 17 |
import gradio as gr
|
|
|
|
| 18 |
import numpy as np
|
|
|
|
| 19 |
import torch
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 20 |
from huggingface_hub import HfApi, hf_hub_download
|
| 21 |
from safetensors.torch import load_file
|
| 22 |
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
GPU = spaces.GPU
|
| 26 |
-
except Exception: # local testing without the spaces runtime
|
| 27 |
-
def GPU(fn=None, **kw):
|
| 28 |
-
return fn if fn is not None else (lambda f: f)
|
| 29 |
-
|
| 30 |
-
import geolip.alephllm as _al
|
| 31 |
-
print(f"[boot] geolip.alephllm {_al.__version__}")
|
| 32 |
from geolip.alephllm.presets import PRESETS, AlephLMConfig
|
| 33 |
from geolip.alephllm.model.alephlm import AlephLM
|
|
|
|
| 34 |
|
| 35 |
REPO = "AbstractPhil/alephllm-mini-beatrix-training"
|
| 36 |
CRAFT = "mini-beatrix-1"
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
#
|
| 45 |
-
|
|
|
|
| 46 |
_boot_id = uuid.uuid4().hex[:8]
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
if os.environ.get("
|
|
|
|
|
|
|
|
|
|
|
|
|
| 50 |
try:
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
|
|
|
| 58 |
|
| 59 |
LOG_NOTE = (
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
|
|
|
| 75 |
return
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
def _text(content) -> str:
|
| 87 |
-
"""gradio 6 Chatbot delivers turn content as a list of content-block
|
| 88 |
-
dicts — normalize to plain text before the model or the public log
|
| 89 |
-
ever sees it."""
|
| 90 |
-
if isinstance(content, str):
|
| 91 |
-
return content
|
| 92 |
-
if isinstance(content, list):
|
| 93 |
-
return "".join(b.get("text", "") for b in content
|
| 94 |
-
if isinstance(b, dict) and b.get("type") == "text")
|
| 95 |
-
return str(content)
|
| 96 |
|
| 97 |
|
| 98 |
-
def _session(request
|
| 99 |
import hashlib
|
| 100 |
try:
|
| 101 |
raw = str(request.session_hash)
|
|
@@ -104,106 +121,165 @@ def _session(request: gr.Request | None) -> str:
|
|
| 104 |
return hashlib.sha256(raw.encode()).hexdigest()[:16]
|
| 105 |
|
| 106 |
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 114 |
|
| 115 |
|
| 116 |
-
def
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 117 |
try:
|
| 118 |
-
|
| 119 |
-
force_download=True)
|
| 120 |
-
return json.load(open(p, encoding="utf-8"))
|
| 121 |
except Exception:
|
| 122 |
-
return
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 123 |
|
| 124 |
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
if
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
if c.get("val_bpb")]
|
| 169 |
-
if bpbs:
|
| 170 |
-
lines.append(f"**Val bits-per-byte:** {bpbs[-1]:.3f}")
|
| 171 |
-
lines.append(f"**Params:** {_state['model'].param_count()/1e6:.1f}M · "
|
| 172 |
-
f"context {_state['model'].cfg.context} bytes")
|
| 173 |
-
return " \n".join(lines)
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
# ---------------------------------------------------------------- generation
|
| 177 |
-
@GPU
|
| 178 |
-
def _stream(prompt: str, max_new: int, temperature: float, top_p: float,
|
| 179 |
-
use_cache: bool, stop: str | None = None):
|
| 180 |
-
"""Yields (text_so_far, stats_line). KV-cached by default; the
|
| 181 |
-
uncached path recomputes the full context every byte for A/B timing."""
|
| 182 |
-
model = _state["model"]
|
| 183 |
-
if model is None:
|
| 184 |
-
yield "(no checkpoint loaded — press Reload)", ""
|
| 185 |
-
return
|
| 186 |
-
dev = next(model.parameters()).device
|
| 187 |
raw = np.frombuffer(prompt.encode("utf-8", errors="replace"),
|
| 188 |
dtype=np.uint8).astype(np.int64)
|
| 189 |
-
|
| 190 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 191 |
out, t0 = [], time.time()
|
|
|
|
| 192 |
with torch.no_grad():
|
| 193 |
-
cache = None
|
| 194 |
if use_cache:
|
| 195 |
with torch.autocast("cuda", dtype=torch.bfloat16,
|
| 196 |
enabled=dev.type == "cuda"):
|
| 197 |
logits, cache = model.prefill(ids)
|
| 198 |
prefill_s = time.time() - t0
|
| 199 |
t1 = time.time()
|
| 200 |
-
for
|
| 201 |
if use_cache:
|
| 202 |
nxt = model._sample(logits, temperature, top_p)
|
| 203 |
else:
|
| 204 |
with torch.autocast("cuda", dtype=torch.bfloat16,
|
| 205 |
enabled=dev.type == "cuda"):
|
| 206 |
-
fl, _ = model(ids[:, -
|
| 207 |
nxt = model._sample(fl, temperature, top_p)
|
| 208 |
ids = torch.cat([ids, nxt], dim=1)
|
| 209 |
out.append(int(nxt.item()))
|
|
@@ -213,16 +289,19 @@ def _stream(prompt: str, max_new: int, temperature: float, top_p: float,
|
|
| 213 |
logits = model.decode_step(nxt, cache)
|
| 214 |
text = bytes(out).decode("utf-8", errors="replace")
|
| 215 |
bps = len(out) / max(time.time() - t1, 1e-6)
|
| 216 |
-
stats = (f"kv-cache **on** · prefill
|
| 217 |
-
f"
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
|
|
|
|
|
|
|
|
|
|
| 221 |
return
|
| 222 |
yield text, stats
|
| 223 |
|
| 224 |
|
| 225 |
-
def complete(prompt, max_new, temperature, top_p, use_cache,
|
| 226 |
request: gr.Request):
|
| 227 |
if not prompt or not prompt.strip():
|
| 228 |
yield "(enter a prompt)", ""
|
|
@@ -230,105 +309,127 @@ def complete(prompt, max_new, temperature, top_p, use_cache,
|
|
| 230 |
text, done = "", False
|
| 231 |
try:
|
| 232 |
for text, stats in _stream(prompt, max_new, temperature, top_p,
|
| 233 |
-
use_cache):
|
| 234 |
yield prompt + text, stats
|
| 235 |
done = True
|
| 236 |
-
finally:
|
| 237 |
_log("completion", _session(request),
|
| 238 |
-
{"prompt": prompt, "output": text, "completed": done,
|
| 239 |
-
|
| 240 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 241 |
|
| 242 |
|
| 243 |
-
def chat(message, history, max_new, temperature, top_p, use_cache,
|
| 244 |
request: gr.Request):
|
| 245 |
if not message or not message.strip():
|
| 246 |
yield list(history or []), "", ""
|
| 247 |
return
|
| 248 |
-
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
who = "User" if turn["role"] == "user" else "Beatrix"
|
| 253 |
-
transcript += f"{who}: {turn['content']}\n"
|
| 254 |
-
transcript += f"User: {message}\nBeatrix:"
|
| 255 |
history = history + [{"role": "user", "content": message},
|
| 256 |
{"role": "assistant", "content": ""}]
|
|
|
|
|
|
|
| 257 |
done = False
|
| 258 |
try:
|
| 259 |
for text, stats in _stream(transcript, max_new, temperature, top_p,
|
| 260 |
-
use_cache, stop=
|
| 261 |
-
history[-1]["content"] =
|
| 262 |
yield history, "", stats
|
| 263 |
done = True
|
| 264 |
finally:
|
| 265 |
_log("chat", _session(request),
|
| 266 |
-
{"messages": history, "completed": done,
|
| 267 |
-
|
| 268 |
-
"top_p": top_p, "kv_cache": bool(use_cache)}})
|
| 269 |
|
| 270 |
|
| 271 |
DESCRIPTION = """
|
| 272 |
-
# Beatrix — a
|
| 273 |
-
|
| 274 |
-
|
| 275 |
-
|
| 276 |
-
|
| 277 |
-
|
| 278 |
-
|
| 279 |
-
|
| 280 |
-
|
| 281 |
-
|
| 282 |
-
|
| 283 |
-
|
| 284 |
-
|
| 285 |
-
|
| 286 |
-
|
| 287 |
-
|
| 288 |
-
|
| 289 |
-
|
| 290 |
-
|
| 291 |
-
|
| 292 |
-
|
| 293 |
-
|
| 294 |
-
**
|
| 295 |
-
|
| 296 |
-
|
| 297 |
-
|
| 298 |
-
|
| 299 |
-
*
|
|
|
|
|
|
|
|
|
|
|
|
|
| 300 |
[alephllm-mini-beatrix-training](https://huggingface.co/AbstractPhil/alephllm-mini-beatrix-training)
|
| 301 |
· *code:* [github.com/AbstractEyes/alephllm](https://github.com/AbstractEyes/alephllm)
|
|
|
|
| 302 |
"""
|
| 303 |
|
| 304 |
with gr.Blocks(title="Beatrix — AlephLLM chat") as demo:
|
| 305 |
gr.Markdown(DESCRIPTION)
|
| 306 |
gr.Markdown(LOG_NOTE)
|
|
|
|
| 307 |
with gr.Row():
|
| 308 |
-
|
| 309 |
-
|
| 310 |
-
|
| 311 |
-
|
| 312 |
-
temperature = gr.Slider(0.0, 1.5, value=0.
|
| 313 |
label="Temperature")
|
| 314 |
top_p = gr.Slider(0.1, 1.0, value=0.95, step=0.05, label="Top-p")
|
| 315 |
use_cache = gr.Checkbox(value=True, label="KV cache")
|
| 316 |
stats_md = gr.Markdown("")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 317 |
with gr.Tab("Completion"):
|
| 318 |
prompt = gr.Textbox(label="Prompt", lines=4,
|
| 319 |
value="The history of mathematics begins")
|
| 320 |
comp_out = gr.Textbox(label="Continuation (streams)", lines=12)
|
| 321 |
gr.Button("Complete", variant="primary").click(
|
| 322 |
-
complete,
|
|
|
|
| 323 |
[comp_out, stats_md])
|
| 324 |
-
with gr.Tab("Chat (preview — no chat training yet)"):
|
| 325 |
-
gr.Markdown(LOG_NOTE)
|
| 326 |
-
chatbot = gr.Chatbot(label="Beatrix", height=420)
|
| 327 |
-
msg = gr.Textbox(label="Message", placeholder="Say something to Beatrix…")
|
| 328 |
-
msg.submit(chat, [msg, chatbot, max_new, temperature, top_p, use_cache],
|
| 329 |
-
[chatbot, msg, stats_md])
|
| 330 |
-
gr.ClearButton([chatbot, msg])
|
| 331 |
-
reload_btn.click(load_model, None, status)
|
| 332 |
|
| 333 |
-
|
| 334 |
-
demo.launch()
|
|
|
|
| 1 |
"""alephllm-chat — talk to Beatrix.
|
| 2 |
+
|
| 3 |
+
Serves a provenance-matched pair: a locked mini-beatrix-1 core and the
|
| 4 |
+
chat arm trained on that exact core. The arm can be switched off at
|
| 5 |
+
runtime to reveal the untouched base model. Standard ZeroGPU Space shape:
|
| 6 |
+
model loaded at import, @spaces.GPU on the generator, demo.launch() at
|
| 7 |
+
the end. No framework patching.
|
| 8 |
+
|
| 9 |
+
Code: https://github.com/AbstractEyes/alephllm
|
| 10 |
"""
|
| 11 |
+
import asyncio
|
| 12 |
import json
|
| 13 |
import os
|
| 14 |
import re
|
| 15 |
+
import sys
|
| 16 |
import time
|
| 17 |
import uuid
|
| 18 |
from datetime import datetime, timezone
|
| 19 |
from pathlib import Path
|
| 20 |
|
| 21 |
import gradio as gr
|
| 22 |
+
import gradio.utils
|
| 23 |
import numpy as np
|
| 24 |
+
import spaces
|
| 25 |
import torch
|
| 26 |
+
|
| 27 |
+
# gradio.utils.safe_get_lock / safe_get_stop_event call get_running_loop(),
|
| 28 |
+
# which always raises during setup (nothing is running yet), so each call
|
| 29 |
+
# builds a throwaway event loop just to construct a Lock/Event and drops
|
| 30 |
+
# the previous one — measured on 6.23.1: 9 loops created, 7 orphaned per
|
| 31 |
+
# boot. Each orphan produces one
|
| 32 |
+
# ValueError: Invalid file descriptor: -1
|
| 33 |
+
# when the collector finalizes it (the socketpair can be freed before the
|
| 34 |
+
# loop object, so __del__ calls fileno() on a closed socket).
|
| 35 |
+
# On Python 3.10+ Lock()/Event() bind lazily to whichever loop first awaits
|
| 36 |
+
# them, so no loop is needed at construction. This REMOVES loop creation —
|
| 37 |
+
# it starts no loop, thread, process or coroutine of its own. Measured
|
| 38 |
+
# after: 1 loop, 0 orphans. gradio.queueing binds the NAMES rather than the
|
| 39 |
+
# module, so every holder is swept.
|
| 40 |
+
_orig_lock = gradio.utils.safe_get_lock
|
| 41 |
+
_orig_stop = gradio.utils.safe_get_stop_event
|
| 42 |
+
for _mod in list(sys.modules.values()):
|
| 43 |
+
if getattr(_mod, "safe_get_lock", None) is _orig_lock:
|
| 44 |
+
_mod.safe_get_lock = lambda: asyncio.Lock()
|
| 45 |
+
if getattr(_mod, "safe_get_stop_event", None) is _orig_stop:
|
| 46 |
+
_mod.safe_get_stop_event = lambda: asyncio.Event()
|
| 47 |
from huggingface_hub import HfApi, hf_hub_download
|
| 48 |
from safetensors.torch import load_file
|
| 49 |
|
| 50 |
+
import amoe
|
| 51 |
+
from amoe.io.checkpoint import load_anchor
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 52 |
from geolip.alephllm.presets import PRESETS, AlephLMConfig
|
| 53 |
from geolip.alephllm.model.alephlm import AlephLM
|
| 54 |
+
from geolip.alephllm.amoe_bridge import CHAT_HEADER, USER_TAG, ASSISTANT_TAG
|
| 55 |
|
| 56 |
REPO = "AbstractPhil/alephllm-mini-beatrix-training"
|
| 57 |
CRAFT = "mini-beatrix-1"
|
| 58 |
+
ARM_ON = "Chat arm (conditioned)"
|
| 59 |
+
ARM_OFF = "Core only (raw base model)"
|
| 60 |
+
MAX_NEW_CAP = 512
|
| 61 |
|
| 62 |
+
# --------------------------------------------------------------- logging
|
| 63 |
+
# The mounted bucket IS the store. Rows are appended to a file under
|
| 64 |
+
# /data — no token, no HfApi, no scheduler, no uploader, no thread. The
|
| 65 |
+
# only writes this app makes are plain appends inside the mount.
|
| 66 |
+
DATA_DIR = Path(os.environ.get("BEATRIX_DATA", "/data"))
|
| 67 |
+
HISTORY_DIR = DATA_DIR / "chat-history"
|
| 68 |
_boot_id = uuid.uuid4().hex[:8]
|
| 69 |
+
|
| 70 |
+
_log_on = False
|
| 71 |
+
if DATA_DIR.is_dir() and os.environ.get("BEATRIX_NO_LOG") != "1":
|
| 72 |
+
# The bucket is MOUNTED by the platform — never try to create /data
|
| 73 |
+
# itself (the app runs as a non-root user, so that raises
|
| 74 |
+
# PermissionError and reads like a failure when the real state is
|
| 75 |
+
# simply "no bucket attached"). Only the subdirectory is ours.
|
| 76 |
try:
|
| 77 |
+
HISTORY_DIR.mkdir(parents=True, exist_ok=True)
|
| 78 |
+
_log_on = True
|
| 79 |
+
except OSError as e:
|
| 80 |
+
print(f"[boot] {DATA_DIR} mounted but read-only ({type(e).__name__})"
|
| 81 |
+
" — conversation logging off", flush=True)
|
| 82 |
+
else:
|
| 83 |
+
print(f"[boot] no bucket mounted at {DATA_DIR} — conversation logging off",
|
| 84 |
+
flush=True)
|
| 85 |
|
| 86 |
LOG_NOTE = (
|
| 87 |
+
"🌐 **Public research log — read before typing.** Everything entered "
|
| 88 |
+
"here (prompts, chats, sampling settings, and Beatrix's replies) is "
|
| 89 |
+
"written as JSON into this Space's **public storage bucket**, tagged "
|
| 90 |
+
"with an anonymous per-visit session id and the checkpoint that "
|
| 91 |
+
"answered. No accounts, names, IP addresses or device data are "
|
| 92 |
+
"collected — but anything you type becomes public data, so **do not "
|
| 93 |
+
"enter personal information**."
|
| 94 |
+
if _log_on else
|
| 95 |
+
"📴 Conversation logging is **off** — nothing you type here is recorded.")
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def _log(kind, session, payload, prov):
|
| 99 |
+
"""One append into the mounted bucket. Called from inside the gradio
|
| 100 |
+
event handlers, so it runs in gradio's own worker — no thread, no
|
| 101 |
+
network, nothing to sync."""
|
| 102 |
+
if not _log_on:
|
| 103 |
return
|
| 104 |
+
try:
|
| 105 |
+
row = dict(payload, kind=kind, session=session, craft=CRAFT,
|
| 106 |
+
ts=datetime.now(timezone.utc).isoformat(), **prov)
|
| 107 |
+
day = datetime.now(timezone.utc).strftime("%Y-%m-%d")
|
| 108 |
+
with open(HISTORY_DIR / f"sessions-{day}-{_boot_id}.jsonl", "a",
|
| 109 |
+
encoding="utf-8", errors="replace") as f:
|
| 110 |
+
f.write(json.dumps(row, ensure_ascii=False) + "\n")
|
| 111 |
+
except Exception: # logging must never affect a conversation
|
| 112 |
+
pass
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 113 |
|
| 114 |
|
| 115 |
+
def _session(request):
|
| 116 |
import hashlib
|
| 117 |
try:
|
| 118 |
raw = str(request.session_hash)
|
|
|
|
| 121 |
return hashlib.sha256(raw.encode()).hexdigest()[:16]
|
| 122 |
|
| 123 |
|
| 124 |
+
def _text(content):
|
| 125 |
+
"""gradio hands chat content back as a list of content blocks."""
|
| 126 |
+
if isinstance(content, str):
|
| 127 |
+
return content
|
| 128 |
+
if isinstance(content, list):
|
| 129 |
+
return "".join(b.get("text", "") for b in content
|
| 130 |
+
if isinstance(b, dict) and b.get("type") == "text")
|
| 131 |
+
return str(content)
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
def _clean_turn(s):
|
| 135 |
+
"""A user message is data, not transcript syntax."""
|
| 136 |
+
s = " ".join(str(s).split())
|
| 137 |
+
return s.replace(USER_TAG.strip(), "User -").replace(ASSISTANT_TAG,
|
| 138 |
+
"Beatrix -")
|
| 139 |
|
| 140 |
|
| 141 |
+
def _finish_reply(text, stops):
|
| 142 |
+
"""Trim a trailing partial stop tag (budget ran out mid-tag) and any
|
| 143 |
+
replacement char from a truncated multi-byte tail."""
|
| 144 |
+
text = text.rstrip("�")
|
| 145 |
+
for s in stops:
|
| 146 |
+
for k in range(len(s), 0, -1):
|
| 147 |
+
if text.endswith(s[:k]):
|
| 148 |
+
text = text[:-k]
|
| 149 |
+
break
|
| 150 |
+
return text.strip()
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
# ----------------------------------------------------------- model load
|
| 154 |
+
def _step_of(path, pat):
|
| 155 |
+
m = re.search(pat, path)
|
| 156 |
+
return int(m.group(1)) if m else None
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
def choose_pair(files):
|
| 160 |
+
"""Newest core that HAS an arm trained on it. Numeric step compare —
|
| 161 |
+
substring matching would let '@step2000' match '@step20000'."""
|
| 162 |
+
cores = {s: f for f in files
|
| 163 |
+
if f.startswith(f"{CRAFT}/checkpoints/step_")
|
| 164 |
+
and f.endswith(".safetensors") and "/fp8/" not in f
|
| 165 |
+
for s in [_step_of(f, r"step_(\d+)\.safetensors$")] if s}
|
| 166 |
+
arms = {s: f for f in files
|
| 167 |
+
if f.startswith(f"{CRAFT}/arms/") and f.endswith(".anchor.pt")
|
| 168 |
+
for s in [_step_of(f, r"@step(\d+)\.anchor\.pt$")] if s}
|
| 169 |
+
if not cores:
|
| 170 |
+
return None, None, None, ""
|
| 171 |
+
newest = max(cores)
|
| 172 |
+
paired = sorted(s for s in cores if s in arms)
|
| 173 |
+
if not paired:
|
| 174 |
+
return newest, cores[newest], None, "no chat arm exists yet"
|
| 175 |
+
step = paired[-1]
|
| 176 |
+
note = ("" if step == newest else
|
| 177 |
+
f"a newer core (step {newest:,}) has no chat arm yet — serving "
|
| 178 |
+
f"the newest matched pair")
|
| 179 |
+
return step, cores[step], arms[step], note
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
def _verify_anchor(local_arm, step):
|
| 183 |
+
"""amoe's strict= check is inert for AlephLM (no model.config), so
|
| 184 |
+
provenance is asserted here from the anchor's own metadata."""
|
| 185 |
try:
|
| 186 |
+
got = load_anchor(local_arm).meta.get("base_model_id")
|
|
|
|
|
|
|
| 187 |
except Exception:
|
| 188 |
+
return False
|
| 189 |
+
want = f"alephllm/{CRAFT}@step{step}"
|
| 190 |
+
if got and got != want:
|
| 191 |
+
print(f"[boot] refusing arm: trained on {got}, core is {want}",
|
| 192 |
+
flush=True)
|
| 193 |
+
return False
|
| 194 |
+
return True
|
| 195 |
|
| 196 |
|
| 197 |
+
files = HfApi().list_repo_files(REPO)
|
| 198 |
+
STEP, CKPT, ARM_PATH, NOTE = choose_pair(files)
|
| 199 |
+
MANIFEST = json.load(open(hf_hub_download(REPO, f"{CRAFT}/manifest.json"),
|
| 200 |
+
encoding="utf-8"))
|
| 201 |
+
CFG = AlephLMConfig.from_dict(MANIFEST["model_config"])
|
| 202 |
+
|
| 203 |
+
model = AlephLM(CFG)
|
| 204 |
+
model.load_state_dict(load_file(hf_hub_download(REPO, CKPT)))
|
| 205 |
+
model.eval()
|
| 206 |
+
CORE_PARAMS = model.param_count()
|
| 207 |
+
|
| 208 |
+
ARM_NAME, WRAPPERS = None, []
|
| 209 |
+
if ARM_PATH:
|
| 210 |
+
_local_arm = hf_hub_download(REPO, ARM_PATH)
|
| 211 |
+
if _verify_anchor(_local_arm, STEP):
|
| 212 |
+
amoe.attach(model, _local_arm, strict=False)
|
| 213 |
+
WRAPPERS = [b for b in model.blocks if hasattr(b, "adapter")]
|
| 214 |
+
ARM_NAME = ARM_PATH.split("/")[-1]
|
| 215 |
+
print(f"[boot] arm attached: {ARM_NAME} ({len(WRAPPERS)} sites)",
|
| 216 |
+
flush=True)
|
| 217 |
+
ARM_PARAMS = model.param_count() - CORE_PARAMS
|
| 218 |
+
model.to("cuda") # ZeroGPU packs here (standard Space pattern)
|
| 219 |
+
|
| 220 |
+
|
| 221 |
+
STATUS = " \n".join(filter(None, [
|
| 222 |
+
f"**Core:** step {STEP:,}",
|
| 223 |
+
f"**Trained on:** {MANIFEST['tokens_seen']/1e9:.2f}B bytes",
|
| 224 |
+
"**Stage:** pretraining complete (core locked)",
|
| 225 |
+
(f"**Val bits-per-byte:** "
|
| 226 |
+
f"{[c['val_bpb'] for c in MANIFEST.get('checkpoints', []) if c.get('val_bpb')][-1]:.3f}"
|
| 227 |
+
if any(c.get("val_bpb") for c in MANIFEST.get("checkpoints", [])) else ""),
|
| 228 |
+
(f"**Chat arm:** `{ARM_NAME}` · {len(WRAPPERS)} sites · "
|
| 229 |
+
f"{ARM_PARAMS/1e6:.1f}M params · trained on THIS core"
|
| 230 |
+
if ARM_NAME else "**Chat arm:** none — core only"),
|
| 231 |
+
f"**Params:** {CORE_PARAMS/1e6:.1f}M core · context {CFG.context} bytes",
|
| 232 |
+
(f"ℹ️ {NOTE}" if NOTE else ""),
|
| 233 |
+
]))
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
# ------------------------------------------------------------ generation
|
| 237 |
+
def _fit(prompt, max_new, context):
|
| 238 |
+
"""Keep the whole prompt and shrink the generation budget instead of
|
| 239 |
+
amputating the transcript; cut on a UTF-8 boundary if we must."""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 240 |
raw = np.frombuffer(prompt.encode("utf-8", errors="replace"),
|
| 241 |
dtype=np.uint8).astype(np.int64)
|
| 242 |
+
if raw.size > context - 16:
|
| 243 |
+
cut = raw.size - (context - 16)
|
| 244 |
+
while cut < raw.size and 0x80 <= int(raw[cut]) < 0xC0:
|
| 245 |
+
cut += 1
|
| 246 |
+
raw = raw[cut:]
|
| 247 |
+
return raw, min(int(max_new), max(8, context - raw.size - 1))
|
| 248 |
+
|
| 249 |
+
|
| 250 |
+
@spaces.GPU(duration=120)
|
| 251 |
+
def _stream(prompt, max_new, temperature, top_p, use_cache, arm_mode,
|
| 252 |
+
stop=()):
|
| 253 |
+
"""Yields (text, stats).
|
| 254 |
+
|
| 255 |
+
Runs inside a ZeroGPU ForkProcess: this body executes in a forked
|
| 256 |
+
child with its own copy of memory, so the arm flags it sets are
|
| 257 |
+
private to this call and need no lock. A threading.Lock here would be
|
| 258 |
+
actively unsafe — a lock held by any parent thread at fork time is
|
| 259 |
+
inherited locked with no owner, and the child would block forever."""
|
| 260 |
+
want_arm = bool(WRAPPERS) and arm_mode == ARM_ON
|
| 261 |
+
for w in WRAPPERS:
|
| 262 |
+
w.enabled = want_arm
|
| 263 |
+
dev = next(model.parameters()).device
|
| 264 |
+
raw, max_new = _fit(prompt, max_new, CFG.context)
|
| 265 |
+
ids = torch.tensor([raw.tolist()], device=dev)
|
| 266 |
out, t0 = [], time.time()
|
| 267 |
+
label = "arm ON" if want_arm else "core only"
|
| 268 |
with torch.no_grad():
|
| 269 |
+
cache, prefill_s = None, 0.0
|
| 270 |
if use_cache:
|
| 271 |
with torch.autocast("cuda", dtype=torch.bfloat16,
|
| 272 |
enabled=dev.type == "cuda"):
|
| 273 |
logits, cache = model.prefill(ids)
|
| 274 |
prefill_s = time.time() - t0
|
| 275 |
t1 = time.time()
|
| 276 |
+
for _ in range(max_new):
|
| 277 |
if use_cache:
|
| 278 |
nxt = model._sample(logits, temperature, top_p)
|
| 279 |
else:
|
| 280 |
with torch.autocast("cuda", dtype=torch.bfloat16,
|
| 281 |
enabled=dev.type == "cuda"):
|
| 282 |
+
fl, _ = model(ids[:, -CFG.context:])
|
| 283 |
nxt = model._sample(fl, temperature, top_p)
|
| 284 |
ids = torch.cat([ids, nxt], dim=1)
|
| 285 |
out.append(int(nxt.item()))
|
|
|
|
| 289 |
logits = model.decode_step(nxt, cache)
|
| 290 |
text = bytes(out).decode("utf-8", errors="replace")
|
| 291 |
bps = len(out) / max(time.time() - t1, 1e-6)
|
| 292 |
+
stats = (f"{label} · kv-cache **on** · prefill "
|
| 293 |
+
f"{prefill_s*1000:.0f} ms · {bps:.0f} bytes/s"
|
| 294 |
+
if use_cache else
|
| 295 |
+
f"{label} · kv-cache **off** · {bps:.0f} bytes/s")
|
| 296 |
+
cut = min((text.index(s) for s in stop if s in text),
|
| 297 |
+
default=-1)
|
| 298 |
+
if cut >= 0:
|
| 299 |
+
yield text[:cut], stats
|
| 300 |
return
|
| 301 |
yield text, stats
|
| 302 |
|
| 303 |
|
| 304 |
+
def complete(prompt, max_new, temperature, top_p, use_cache, arm_mode,
|
| 305 |
request: gr.Request):
|
| 306 |
if not prompt or not prompt.strip():
|
| 307 |
yield "(enter a prompt)", ""
|
|
|
|
| 309 |
text, done = "", False
|
| 310 |
try:
|
| 311 |
for text, stats in _stream(prompt, max_new, temperature, top_p,
|
| 312 |
+
use_cache, arm_mode):
|
| 313 |
yield prompt + text, stats
|
| 314 |
done = True
|
| 315 |
+
finally:
|
| 316 |
_log("completion", _session(request),
|
| 317 |
+
{"prompt": prompt, "output": text, "completed": done},
|
| 318 |
+
{"checkpoint_step": STEP, "arm": ARM_NAME, "arm_mode": arm_mode})
|
| 319 |
+
|
| 320 |
+
|
| 321 |
+
def _transcript(history, message):
|
| 322 |
+
"""Header first, then as many recent turns as fit."""
|
| 323 |
+
head, tail = CHAT_HEADER, f"{USER_TAG}{message}\n{ASSISTANT_TAG}"
|
| 324 |
+
budget = CFG.context - 16 - len(head.encode()) - len(tail.encode())
|
| 325 |
+
turns = []
|
| 326 |
+
for t in reversed(history):
|
| 327 |
+
who = USER_TAG if t["role"] == "user" else ASSISTANT_TAG + " "
|
| 328 |
+
line = f"{who}{t['content']}\n"
|
| 329 |
+
if len(line.encode()) > budget:
|
| 330 |
+
break
|
| 331 |
+
budget -= len(line.encode())
|
| 332 |
+
turns.append(line)
|
| 333 |
+
return head + "".join(reversed(turns)) + tail
|
| 334 |
|
| 335 |
|
| 336 |
+
def chat(message, history, max_new, temperature, top_p, use_cache, arm_mode,
|
| 337 |
request: gr.Request):
|
| 338 |
if not message or not message.strip():
|
| 339 |
yield list(history or []), "", ""
|
| 340 |
return
|
| 341 |
+
message = _clean_turn(message)
|
| 342 |
+
history = [{"role": t["role"], "content": _clean_turn(_text(t["content"]))}
|
| 343 |
+
for t in (history or [])]
|
| 344 |
+
transcript = _transcript(history, message)
|
|
|
|
|
|
|
|
|
|
| 345 |
history = history + [{"role": "user", "content": message},
|
| 346 |
{"role": "assistant", "content": ""}]
|
| 347 |
+
stops = ("\n" + USER_TAG.strip(), "\n" + ASSISTANT_TAG,
|
| 348 |
+
USER_TAG.strip(), ASSISTANT_TAG)
|
| 349 |
done = False
|
| 350 |
try:
|
| 351 |
for text, stats in _stream(transcript, max_new, temperature, top_p,
|
| 352 |
+
use_cache, arm_mode, stop=stops):
|
| 353 |
+
history[-1]["content"] = _finish_reply(text, stops) or "…"
|
| 354 |
yield history, "", stats
|
| 355 |
done = True
|
| 356 |
finally:
|
| 357 |
_log("chat", _session(request),
|
| 358 |
+
{"messages": history, "completed": done},
|
| 359 |
+
{"checkpoint_step": STEP, "arm": ARM_NAME, "arm_mode": arm_mode})
|
|
|
|
| 360 |
|
| 361 |
|
| 362 |
DESCRIPTION = """
|
| 363 |
+
# Beatrix — a byte-level AlephLLM you can talk to
|
| 364 |
+
|
| 365 |
+
**mini-beatrix-1**: 112.5M parameters, no tokenizer, pretrained on 15.3
|
| 366 |
+
billion bytes and carrying her first **chat arm** — a 3.2M-parameter
|
| 367 |
+
adapter trained on this exact frozen core, which you can switch off
|
| 368 |
+
mid-session to hear the raw base model underneath.
|
| 369 |
+
|
| 370 |
+
**How she reads text.** Beatrix consumes raw UTF-8 bytes. Each position
|
| 371 |
+
composes the byte with its two predecessors (a trigram embedding with a
|
| 372 |
+
dedicated pad row), so "tokens" are learned inside the network rather
|
| 373 |
+
than fixed by a vocabulary.
|
| 374 |
+
|
| 375 |
+
**What's inside.** 16 pre-norm layers where routing uses *signed
|
| 376 |
+
geometric addresses* — dispatch weights `sinh(u_k)/Σcosh(u_j)` over
|
| 377 |
+
learned unit anchors, with no softmax-over-choices, no top-k, and
|
| 378 |
+
inhibition (negative weights) as a first-class citizen. Each layer holds
|
| 379 |
+
an anchored expert bank **born contributing exactly zero**; three
|
| 380 |
+
attention layers use a linear-cost address read instead of softmax
|
| 381 |
+
attention. Both elected themselves into load-bearing work during
|
| 382 |
+
training — removing the banks costs +2.1 bits per byte, removing the
|
| 383 |
+
aleph attention +3.0.
|
| 384 |
+
|
| 385 |
+
**The arm is detachable, exactly.** Switch to *Core only* and the model
|
| 386 |
+
is the pretrained base again, bit for bit. The space only ever serves an
|
| 387 |
+
arm trained on the core it is attached to — provenance is verified from
|
| 388 |
+
the adapter's own metadata at load.
|
| 389 |
+
|
| 390 |
+
**What to expect.** She is small and early: conversational in shape,
|
| 391 |
+
thin on knowledge, confidently wrong at times. Short exchanges suit her
|
| 392 |
+
best; longer answers drift.
|
| 393 |
+
|
| 394 |
+
*Training record:*
|
| 395 |
[alephllm-mini-beatrix-training](https://huggingface.co/AbstractPhil/alephllm-mini-beatrix-training)
|
| 396 |
· *code:* [github.com/AbstractEyes/alephllm](https://github.com/AbstractEyes/alephllm)
|
| 397 |
+
· *adapters:* [amoe-lora](https://github.com/AbstractEyes/amoe-lora)
|
| 398 |
"""
|
| 399 |
|
| 400 |
with gr.Blocks(title="Beatrix — AlephLLM chat") as demo:
|
| 401 |
gr.Markdown(DESCRIPTION)
|
| 402 |
gr.Markdown(LOG_NOTE)
|
| 403 |
+
gr.Markdown(STATUS)
|
| 404 |
with gr.Row():
|
| 405 |
+
arm_mode = gr.Radio([ARM_ON, ARM_OFF], value=ARM_ON, label="Model",
|
| 406 |
+
scale=2)
|
| 407 |
+
max_new = gr.Slider(16, MAX_NEW_CAP, value=192, step=16,
|
| 408 |
+
label="Max new bytes")
|
| 409 |
+
temperature = gr.Slider(0.0, 1.5, value=0.7, step=0.05,
|
| 410 |
label="Temperature")
|
| 411 |
top_p = gr.Slider(0.1, 1.0, value=0.95, step=0.05, label="Top-p")
|
| 412 |
use_cache = gr.Checkbox(value=True, label="KV cache")
|
| 413 |
stats_md = gr.Markdown("")
|
| 414 |
+
with gr.Tab("Chat"):
|
| 415 |
+
gr.Markdown(LOG_NOTE)
|
| 416 |
+
chatbot = gr.Chatbot(label="Beatrix", height=420)
|
| 417 |
+
msg = gr.Textbox(label="Message", placeholder="Say hello to Beatrix…")
|
| 418 |
+
gr.Examples([["Hello!"], ["Who are you?"], ["What can you do?"],
|
| 419 |
+
["How are you today?"], ["Tell me about books."]],
|
| 420 |
+
inputs=msg)
|
| 421 |
+
msg.submit(chat,
|
| 422 |
+
[msg, chatbot, max_new, temperature, top_p, use_cache,
|
| 423 |
+
arm_mode],
|
| 424 |
+
[chatbot, msg, stats_md])
|
| 425 |
+
gr.ClearButton([chatbot, msg])
|
| 426 |
with gr.Tab("Completion"):
|
| 427 |
prompt = gr.Textbox(label="Prompt", lines=4,
|
| 428 |
value="The history of mathematics begins")
|
| 429 |
comp_out = gr.Textbox(label="Continuation (streams)", lines=12)
|
| 430 |
gr.Button("Complete", variant="primary").click(
|
| 431 |
+
complete,
|
| 432 |
+
[prompt, max_new, temperature, top_p, use_cache, arm_mode],
|
| 433 |
[comp_out, stats_md])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 434 |
|
| 435 |
+
demo.launch()
|
|
|