AbstractPhil commited on
Commit
bc1c4ce
·
verified ·
1 Parent(s): 570437f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +317 -216
app.py CHANGED
@@ -1,101 +1,118 @@
1
  """alephllm-chat — talk to Beatrix.
2
- A live window onto the AlephLLM training runs: loads the newest
3
- checkpoint from the training repo, serves streaming completion and a
4
- chat-format preview on ZeroGPU (with KV-cached decode and an A/B
5
- toggle), and — with clear disclosure — logs conversations to a PUBLIC
6
- research dataset. Code: https://github.com/AbstractEyes/alephllm
 
 
 
7
  """
 
8
  import json
9
  import os
10
  import re
11
- import threading
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
- try:
24
- import spaces
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
- HISTORY_REPO = "AbstractPhil/alephllm-chat-history"
38
- CHAT_HEADER = ("A conversation with Beatrix, a small byte-level "
39
- "language model still in pretraining.\n")
40
 
41
- _lock = threading.Lock()
42
- _state = {"model": None, "step": None, "manifest": None}
43
-
44
- # ---------------------------------------------------------------- history log
45
- _history_dir = Path("history")
 
46
  _boot_id = uuid.uuid4().hex[:8]
47
- _history_dir.mkdir(exist_ok=True)
48
- _scheduler = None
49
- if os.environ.get("HF_TOKEN"):
 
 
 
 
50
  try:
51
- from huggingface_hub import CommitScheduler
52
- _scheduler = CommitScheduler(
53
- repo_id=HISTORY_REPO, repo_type="dataset",
54
- folder_path=str(_history_dir), path_in_repo="data",
55
- every=5, token=os.environ["HF_TOKEN"], private=False)
56
- except Exception as e: # noqa: BLE001
57
- print(f"[history] logging disabled: {e}")
 
58
 
59
  LOG_NOTE = (
60
- f"🌐 **Public research log — read before typing.** Everything entered "
61
- f"here (prompts, chats, sampling settings, and Beatrix's replies) is "
62
- f"stored **publicly** in "
63
- f"[{HISTORY_REPO}](https://huggingface.co/datasets/{HISTORY_REPO}) "
64
- f"as JSON, tagged with an anonymous per-visit session id and the "
65
- f"checkpoint step. No accounts, names, IPs, or device data are "
66
- f"collected — but anything you type becomes public data, so **do not "
67
- f"enter personal information**."
68
- if _scheduler else
69
- "📴 Conversation logging is currently **disabled** (no storage token "
70
- "configured) — nothing you type here is recorded.")
71
-
72
-
73
- def _log(kind: str, session: str, payload: dict):
74
- if _scheduler is None:
 
75
  return
76
- payload = dict(payload, kind=kind, session=session,
77
- ts=datetime.now(timezone.utc).isoformat(),
78
- craft=CRAFT, checkpoint_step=_state["step"])
79
- day = datetime.now(timezone.utc).strftime("%Y-%m-%d")
80
- path = _history_dir / f"sessions-{day}-{_boot_id}.jsonl"
81
- with _scheduler.lock:
82
- with open(path, "a", encoding="utf-8", errors="replace") as f:
83
- f.write(json.dumps(payload, ensure_ascii=False) + "\n")
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: gr.Request | None) -> str:
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
- # ---------------------------------------------------------------- model load
108
- def _latest_checkpoint():
109
- files = HfApi().list_repo_files(REPO)
110
- cks = sorted(f for f in files
111
- if f.startswith(f"{CRAFT}/checkpoints/step_")
112
- and f.endswith(".safetensors") and "/fp8/" not in f)
113
- return cks[-1] if cks else None
 
 
 
 
 
 
 
 
114
 
115
 
116
- def _manifest():
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
117
  try:
118
- p = hf_hub_download(REPO, f"{CRAFT}/manifest.json",
119
- force_download=True)
120
- return json.load(open(p, encoding="utf-8"))
121
  except Exception:
122
- return None
 
 
 
 
 
 
123
 
124
 
125
- def load_model():
126
- """Never raises (a transient hub error at boot must not crash-loop the
127
- space); downloads happen OUTSIDE the lock (a reload mid-generation must
128
- not block streams); the device move happens HERE once — under ZeroGPU
129
- the module-level .to('cuda') is the documented supported pattern."""
130
- try:
131
- ck = _latest_checkpoint()
132
- if ck is None:
133
- return "No checkpoint on the hub yet — the run has not reached its first save."
134
- step = int(re.search(r"step_(\d+)", ck).group(1))
135
- if _state["step"] == step and _state["model"] is not None:
136
- _state["manifest"] = _manifest() or _state["manifest"]
137
- return _status_md()
138
- man = _manifest()
139
- cfg = (AlephLMConfig.from_dict(man["model_config"])
140
- if man and man.get("model_config") else PRESETS[CRAFT].model)
141
- model = AlephLM(cfg)
142
- sd = load_file(hf_hub_download(REPO, ck))
143
- model.load_state_dict(sd)
144
- model.eval()
145
- if torch.cuda.is_available():
146
- model.to("cuda")
147
- with _lock:
148
- _state.update(model=model, step=step, manifest=man)
149
- return _status_md()
150
- except Exception as e: # noqa: BLE001
151
- return (f"**Status:** hub unreachable ({type(e).__name__}) — "
152
- "press *Reload newest checkpoint* to retry.")
153
-
154
-
155
- def _status_md():
156
- man, step = _state["manifest"], _state["step"]
157
- if _state["model"] is None:
158
- return "**Status:** no checkpoint loaded — press *Reload newest checkpoint*."
159
- lines = [f"**Checkpoint:** step {step:,}"]
160
- if man:
161
- lines.append(f"**Tokens trained:** {man['tokens_seen']/1e9:.3f}B")
162
- ph = next((p for p in man["phases"] if p["status"] == "active"), None)
163
- if ph:
164
- lines.append(f"**Phase:** {ph['name']} ({ph['dataset']}), "
165
- f"{ph.get('tokens_done', 0)/1e9:.2f}"
166
- f"/{ph['planned_tokens']/1e9:.1f}B")
167
- bpbs = [c.get("val_bpb") for c in man.get("checkpoints", [])
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
- keep = model.cfg.context - int(max_new) - 1
190
- ids = torch.tensor([raw[-keep:].tolist()], device=dev)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 i in range(int(max_new)):
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[:, -model.cfg.context:])
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 {prefill_s*1000:.0f} ms · "
217
- f"decode {bps:.0f} bytes/s" if use_cache else
218
- f"kv-cache **off** (full recompute) · decode {bps:.0f} bytes/s")
219
- if stop and stop in text:
220
- yield text.split(stop)[0], stats
 
 
 
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: # disconnects/cancels still reach the public log, flagged
237
  _log("completion", _session(request),
238
- {"prompt": prompt, "output": text, "completed": done,
239
- "params": {"max_new": int(max_new), "temperature": temperature,
240
- "top_p": top_p, "kv_cache": bool(use_cache)}})
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
- history = [{"role": turn["role"], "content": _text(turn["content"])}
249
- for turn in (history or [])]
250
- transcript = CHAT_HEADER
251
- for turn in history:
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="\nUser:"):
261
- history[-1]["content"] = text.strip() or "…"
262
  yield history, "", stats
263
  done = True
264
  finally:
265
  _log("chat", _session(request),
266
- {"messages": history, "completed": done,
267
- "params": {"max_new": int(max_new), "temperature": temperature,
268
- "top_p": top_p, "kv_cache": bool(use_cache)}})
269
 
270
 
271
  DESCRIPTION = """
272
- # Beatrix — a live AlephLLM training run
273
- You are talking to **mini-beatrix-1** (112.5M parameters), an experimental
274
- byte-level language model **currently in pretraining**. This space always
275
- serves the newest checkpoint uploaded by the training run — she gets
276
- smarter as you revisit.
277
- **How she reads text.** No tokenizer: Beatrix consumes raw UTF-8 bytes.
278
- Each position's embedding composes the byte with its two predecessors
279
- (a trigram embedding, with a dedicated pad row for sequence starts), so
280
- "tokens" are learned inside the network rather than fixed by a vocabulary.
281
- **What's inside.** A 16-layer transformer where routing is done by
282
- *signed geometric addresses* (the aleph mechanism): dispatch weights are
283
- `sinh(u_k)/Σcosh(u_j)` over learned unit anchors — no softmax-over-choices,
284
- no top-k, and negative (inhibitory) weights are first-class. Each layer
285
- carries an anchored expert bank **born contributing exactly zero** (it must
286
- earn its way in by gradient), three attention layers use a linear-cost
287
- address read instead of softmax attention, and the output head carries a
288
- second, address-based read behind a gate that also starts at zero.
289
- **KV-cached decode.** Generation runs incrementally: the standard layers
290
- keep a K/V cache, and the aleph attention layers keep a **constant-size
291
- prefix state** regardless of context length — a structural property of the
292
- address read. The toggle below lets you A/B cached vs full-recompute
293
- decoding and watch the bytes/s difference live.
294
- **What to expect right now.** Early-stage: under a billion tokens seen and
295
- **no chat training yet** — the Chat tab wraps your words in a transcript
296
- she continues, so expect drifty text, echoes, and format mimicry rather
297
- than conversation. A chat-tuned stage will replace this preview once base
298
- pretraining completes.
299
- *Training logs, checkpoints and manifests:*
 
 
 
 
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
- status = gr.Markdown(load_model())
309
- reload_btn = gr.Button("Reload newest checkpoint", scale=0)
310
- with gr.Row():
311
- max_new = gr.Slider(16, 1024, value=256, step=16, label="Max new bytes")
312
- temperature = gr.Slider(0.0, 1.5, value=0.8, step=0.05,
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, [prompt, max_new, temperature, top_p, use_cache],
 
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
- if __name__ == "__main__":
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()