Skip to content

Run frontier MoE models on hardware you already own — pure C, zero deps, experts streamed from disk. Tiny engine, immense model. 🐦

C

feat(web): attach an image in the browser, and fix what the real model caught

JustVuggb719fea9623a
diff --git a/c/family_registry.py b/c/family_registry.py
index 2241c003..efa4242d 100644
--- a/c/family_registry.py
+++ b/c/family_registry.py
@@ -525,7 +525,10 @@ FAMILIES = (
planner_unsupported_reason="",
expert_inventory=_individual_expert_inventory(_GLM53_EXPERT),
config_section="text_config",
- limits=FamilyLimits(8192, 1048576, 1024, 1024, 1, 8, "GLM53_MAXT"),
+ # implicit_cap 0, non 8: questo motore dimensiona la cache degli
+ # esperti dalla RAM disponibile, quindi "nessuna scelta esplicita"
+ # deve arrivargli come 0 e non come otto slot per layer.
+ limits=FamilyLimits(8192, 1048576, 1024, 1024, 1, 0, "GLM53_MAXT"),
capabilities=COMMON_CAP,
has_gateway_adapter=True,
has_cli_adapter=True,
diff --git a/c/glm53 b/c/glm53
index 1d43ee36..d921b5e4 100644
Binary files a/c/glm53 and b/c/glm53 differ
diff --git a/c/glm53.c b/c/glm53.c
index ace25eca..72af76ea 100644
--- a/c/glm53.c
+++ b/c/glm53.c
@@ -1133,6 +1133,9 @@ static void mla_layer(const Cfg *c, const GLayer *l, const float *x, int tokens,
* in cui li vuole il calcolo. Le Mat che ne escono puntano dentro allo slot,
* cosi' il codice del MoE non sa da dove arrivi il peso e resta quello di
* prima. */
+/* Slot per layer chiesti dalla riga di comando; 0 = decide il budget misurato. */
+static int g_cap_override = 0;
+
#define GLM53_EXPERT_PIECES 6
typedef struct ERef {
@@ -1244,6 +1247,7 @@ static void expert_cache_init(GModel *m) {
int sparse = m->layer_end - from;
if (sparse < 0) sparse = 0;
int cap = (int)((budget * 1e9) / ((double)m->e_slot * (sparse > 0 ? sparse : 1)));
+ if (g_cap_override > 0) cap = g_cap_override; /* scelta esplicita: vince */
if (cap < 1) cap = 1;
if (cap > c->n_experts) cap = c->n_experts;
@@ -2521,11 +2525,14 @@ static void serve_one(GModel *m, Tok *tokenizer, ServeReq *q) {
* davvero macinato: prompt piu' quello che ha generato. */
slot_remember(slot, sequence, total);
const double elapsed = now_s() - started;
- /* Quanto prefisso lo slot ha risparmiato. La regola di compatibilita' del
- * protocollo dice che un server ignora le righe che non conosce, quindi
- * questa non rompe nessun client e da' a chi la vuole un modo di vedere se
- * il riuso sta funzionando davvero. */
- serve_line("REUSE %llu %d %d\n", q->id, reused, prompt_tokens);
+ /* Quanto prefisso lo slot ha risparmiato.
+ *
+ * Su STDERR, non nel protocollo. La specifica dice che un server ignora le
+ * righe che non conosce, ma questo progetto ha scelto il contrario apposta
+ * e lo mette per iscritto in un test: una riga sconosciuta uccide il
+ * dispatcher, cosi' un motore non puo' parlare a un server che non lo
+ * capisce. La regola vera e' quella del test, non quella del documento. */
+ fprintf(stderr, "REUSE %llu %d %d\n", q->id, reused, prompt_tokens);
serve_line("DONE %llu STAT %d %.2f %.1f %.1f %d %d\n", q->id, emitted,
elapsed > 0 ? emitted / elapsed : 0.0,
m->miss + m->hits ? 100.0 * m->hits / (double)(m->hits + m->miss) : 0.0,
@@ -2572,6 +2579,13 @@ int main(int argc, char **argv) {
else if (!strcmp(argv[i], "--patches") && i + 1 < argc) patch_file = argv[++i];
else if (!strcmp(argv[i], "--grid") && i + 1 < argc &&
sscanf(argv[++i], "%dx%d", &grid_h, &grid_w) == 2) continue;
+ else if (argv[i][0] >= '0' && argv[i][0] <= '9') {
+ /* Capienza posizionale: e' cosi' che il gateway lancia ogni motore
+ * (openai_server.py, Engine.__init__). Zero vuol dire "decidila
+ * tu", che qui e' il budget misurato dalla RAM disponibile. */
+ const int cap = atoi(argv[i]);
+ if (cap > 0) g_cap_override = cap;
+ }
else { fprintf(stderr, "argomento sconosciuto: %s\n", argv[i]); return 2; }
}
/* SERVE=1 e SNAP=<dir>: il motore non e' piu' una CLI ma il capo di una
diff --git a/c/tests/test_glm53_serve.py b/c/tests/test_glm53_serve.py
index ec426bcf..d8330fac 100644
--- a/c/tests/test_glm53_serve.py
+++ b/c/tests/test_glm53_serve.py
@@ -16,17 +16,33 @@ che nessuno ha fatto.
"""
import argparse
import os
+import tempfile
import subprocess
import sys
from pathlib import Path
+NOTES = tempfile.mktemp(suffix=".glm53.stderr")
+
+
+def reuse_reported():
+ """Quanti token di prefisso il motore dice di aver riusato."""
+ try:
+ text = open(NOTES, "r", errors="replace").read()
+ except OSError:
+ return 0
+ return sum(int(line.split()[2]) for line in text.splitlines()
+ if line.startswith("REUSE "))
+
+
def engine(binary, fixture, extra=None):
environment = {**os.environ, "SERVE": "1", "SERVE_BATCH": "1",
"SNAP": str(fixture), "GLM53_BITS": "32"}
environment.update(extra or {})
+ # stderr in un file: il riuso del prefisso si racconta li', perche' nel
+ # protocollo una riga in piu' farebbe cadere il gateway (di proposito).
return subprocess.Popen([binary], stdin=subprocess.PIPE, stdout=subprocess.PIPE,
- stderr=subprocess.DEVNULL, env=environment)
+ stderr=open(NOTES, "wb"), env=environment)
def read_line(stream):
@@ -61,19 +77,17 @@ def collect(process, request_id):
"""I DATA fino al DONE della richiesta, o l'ERROR che li sostituisce.
Restituisce anche quanto prefisso lo slot ha riusato, se il motore lo dice."""
- pieces, reused = [], None
+ pieces = []
while True:
line = read_line(process.stdout)
- if line.startswith("REUSE "):
- reused = int(line.split()[2])
- elif line.startswith("DATA "):
+ if line.startswith("DATA "):
_, got_id, count = line.split()
if int(got_id) != request_id:
raise AssertionError(f"DATA per {got_id}, atteso {request_id}")
payload = process.stdout.read(int(count) + 1) # payload piu' '\n'
pieces.append(payload[:int(count)])
elif line.startswith("DONE ") or line.startswith("ERROR "):
- return b"".join(pieces), line, reused
+ return b"".join(pieces), line, reuse_reported()
def cli_answer(binary, fixture, prompt, tokens):
diff --git a/c/tools/glm53_image.py b/c/tools/glm53_image.py
index 170d686a..304786d1 100644
--- a/c/tools/glm53_image.py
+++ b/c/tools/glm53_image.py
@@ -30,6 +30,7 @@ from __future__ import annotations
import argparse
import json
import math
+import os
import sys
from pathlib import Path
@@ -142,6 +143,16 @@ def preprocess(source, model_dir=None):
std = tuple(settings.get("image_std", STD))
min_tokens = settings.get("min_image_tokens", MIN_TOKENS)
max_tokens = settings.get("max_image_tokens", MAX_TOKENS)
+ # Il tetto del checkpoint e' 8000 token per immagine, che su una macchina
+ # che streamma gli esperti da disco vuol dire un prefill lunghissimo per
+ # una foto qualunque. GLM53_MAX_IMAGE_TOKENS lo abbassa: l'immagine viene
+ # rimpicciolita, non tagliata, quindi si perde dettaglio e non pezzi.
+ override = os.environ.get("GLM53_MAX_IMAGE_TOKENS")
+ if override:
+ try:
+ max_tokens = max(min_tokens, int(override))
+ except ValueError:
+ pass
patch = settings.get("patch_size", PATCH)
merge = settings.get("merge_size", MERGE)
temporal = settings.get("temporal_patch_size", TEMPORAL)
diff --git a/web/src/App.tsx b/web/src/App.tsx
index 1b137f80..14a51e5b 100644
--- a/web/src/App.tsx
+++ b/web/src/App.tsx
@@ -17,6 +17,7 @@ import {
Link2,
LoaderCircle,
MemoryStick,
+ ImagePlus,
MessageSquareText,
MonitorDot,
RefreshCw,
@@ -67,6 +68,29 @@ export default function App() {
const [healthError, setHealthError] = useState("")
const [lastRun, setLastRun] = useState<StreamChatResult | null>(null)
const [draft, setDraft] = useState("")
+ /* Immagini in attesa di partire col prossimo messaggio. Si tengono come
+ data: URI perche' e' quello che il server accetta e quello che il browser
+ puo' mostrare in anteprima senza inventarsi un percorso su disco. */
+ const [attachments, setAttachments] = useState<{ name: string; url: string }[]>([])
+ const fileInputRef = useRef<HTMLInputElement>(null)
+
+ const attachFiles = async (files: FileList | File[] | null) => {
+ if (!files) return
+ const images = Array.from(files).filter((file) => file.type.startsWith("image/"))
+ if (!images.length) return
+ const read = await Promise.all(
+ images.map(
+ (file) =>
+ new Promise<{ name: string; url: string }>((resolve, reject) => {
+ const reader = new FileReader()
+ reader.onload = () => resolve({ name: file.name, url: String(reader.result) })
+ reader.onerror = () => reject(reader.error)
+ reader.readAsDataURL(file)
+ }),
+ ),
+ )
+ setAttachments((current) => [...current, ...read])
+ }
const [loading, setLoading] = useState(false)
const [streamStart, setStreamStart] = useState<number | null>(null)
const [tokenCount, setTokenCount] = useState(0)
@@ -183,11 +207,15 @@ export default function App() {
const send = async () => {
const content = draft.trim()
- if (!content || loading) return
+ /* Un'immagine da sola e' una domanda valida: "questa cosa e'?" si puo'
+ chiedere anche senza scrivere niente. */
+ if ((!content && !attachments.length) || loading) return
const user = message("user", content)
+ if (attachments.length) user.images = attachments.map((item) => item.url)
const assistant = message("assistant", "")
const history = [...messages, user]
setDraft("")
+ setAttachments([])
setError("")
updateMessages([...history, assistant])
setLoading(true)
@@ -399,8 +427,22 @@ export default function App() {
<div className="composer-wrap">
{error && <div className="error-banner" role="alert">{t(error)}</div>}
<div className="composer">
- <Textarea value={draft} onChange={(event) => setDraft(event.target.value)} placeholder={t("chat.placeholder")} onKeyDown={(event) => { if (event.key === "Enter" && !event.shiftKey && !event.nativeEvent.isComposing) { event.preventDefault(); void send() } }} />
- <div className="composer-foot"><span><MessageSquareText className="size-3.5" /> {t("chat.inputHint")}</span>{loading ? <Button variant="destructive" size="icon" aria-label={t("chat.stop")} onClick={() => abortRef.current?.abort()}><CircleStop className="size-4" /></Button> : <Button size="icon" aria-label={t("chat.send")} disabled={!canSend} onClick={() => void send()}><ArrowUp className="size-4" /></Button>}</div>
+ <Textarea value={draft}
+ onPaste={(event) => { const files = Array.from(event.clipboardData.files); if (files.length) { event.preventDefault(); void attachFiles(files) } }}
+ onDragOver={(event) => event.preventDefault()}
+ onDrop={(event) => { if (event.dataTransfer.files.length) { event.preventDefault(); void attachFiles(event.dataTransfer.files) } }} onChange={(event) => setDraft(event.target.value)} placeholder={t("chat.placeholder")} onKeyDown={(event) => { if (event.key === "Enter" && !event.shiftKey && !event.nativeEvent.isComposing) { event.preventDefault(); void send() } }} />
+ {attachments.length > 0 && (
+ <div className="attachments">
+ {attachments.map((item, index) => (
+ <span key={item.url + index} className="attachment">
+ <img src={item.url} alt={item.name} />
+ <button type="button" aria-label={t("chat.removeImage")}
+ onClick={() => setAttachments((current) => current.filter((_, at) => at !== index))}>x</button>
+ </span>
+ ))}
+ </div>
+ )}
+ <div className="composer-foot"><span><MessageSquareText className="size-3.5" /> {t("chat.inputHint")}</span><input ref={fileInputRef} type="file" accept="image/*" multiple hidden onChange={(event) => { void attachFiles(event.target.files); event.target.value = "" }} /><Button variant="ghost" size="icon" aria-label={t("chat.attachImage")} onClick={() => fileInputRef.current?.click()}><ImagePlus className="size-4" /></Button>{loading ? <Button variant="destructive" size="icon" aria-label={t("chat.stop")} onClick={() => abortRef.current?.abort()}><CircleStop className="size-4" /></Button> : <Button size="icon" aria-label={t("chat.send")} disabled={!canSend} onClick={() => void send()}><ArrowUp className="size-4" /></Button>}</div>
</div>
</div>
</>}
diff --git a/web/src/i18n/de.ts b/web/src/i18n/de.ts
index d6095256..f7f3918f 100644
--- a/web/src/i18n/de.ts
+++ b/web/src/i18n/de.ts
@@ -72,6 +72,8 @@ const de: Record<string, string> = {
"chat.colibri": "colibrì",
"chat.placeholder": "Nachricht an colibrì…",
"chat.inputHint": "Eingabetaste zum Senden · Umschalt+Eingabetaste für Zeilenumbruch",
+ "chat.attachImage": "Bild anhängen",
+ "chat.removeImage": "Bild entfernen",
"chat.stop": "Generierung stoppen",
"chat.send": "Nachricht senden",
diff --git a/web/src/i18n/en.ts b/web/src/i18n/en.ts
index 158971d8..67782abb 100644
--- a/web/src/i18n/en.ts
+++ b/web/src/i18n/en.ts
@@ -72,6 +72,8 @@ const en: Record<string, string> = {
"chat.colibri": "colibrì",
"chat.placeholder": "Message colibrì…",
"chat.inputHint": "Enter to send · Shift+Enter for newline",
+ "chat.attachImage": "Attach an image",
+ "chat.removeImage": "Remove image",
"chat.stop": "Stop generation",
"chat.send": "Send message",
diff --git a/web/src/i18n/it.ts b/web/src/i18n/it.ts
index 7f73e1e9..57373ab8 100644
--- a/web/src/i18n/it.ts
+++ b/web/src/i18n/it.ts
@@ -63,6 +63,8 @@ const it: Record<string, string> = {
"chat.colibri": "colibrì",
"chat.placeholder": "Scrivi a colibrì…",
"chat.inputHint": "Invio per inviare · Shift+Invio per andare a capo",
+ "chat.attachImage": "Allega un'immagine",
+ "chat.removeImage": "Togli l'immagine",
"chat.stop": "Ferma la generazione",
"chat.send": "Invia messaggio",
diff --git a/web/src/i18n/zh-CN.ts b/web/src/i18n/zh-CN.ts
index 97de86af..c1d2b433 100644
--- a/web/src/i18n/zh-CN.ts
+++ b/web/src/i18n/zh-CN.ts
@@ -63,6 +63,8 @@ const zhCN: Record<string, string> = {
"chat.colibri": "colibrì",
"chat.placeholder": "给 colibrì 发消息…",
"chat.inputHint": "回车发送 · Shift+回车换行",
+ "chat.attachImage": "添加图片",
+ "chat.removeImage": "移除图片",
"chat.stop": "停止生成",
"chat.send": "发送消息",
diff --git a/web/src/i18n/zh-TW.ts b/web/src/i18n/zh-TW.ts
index c59fe94f..0fd2e245 100644
--- a/web/src/i18n/zh-TW.ts
+++ b/web/src/i18n/zh-TW.ts
@@ -63,6 +63,8 @@ const zhTW: Record<string, string> = {
"chat.colibri": "colibrì",
"chat.placeholder": "傳送訊息給 colibrì…",
"chat.inputHint": "Enter 傳送 · Shift+Enter 換行",
+ "chat.attachImage": "附加圖片",
+ "chat.removeImage": "移除圖片",
"chat.stop": "停止生成",
"chat.send": "傳送訊息",
diff --git a/web/src/index.css b/web/src/index.css
index 5cf70f62..0d0887d7 100644
--- a/web/src/index.css
+++ b/web/src/index.css
@@ -228,3 +228,19 @@ button:focus-visible, input:focus-visible, textarea:focus-visible, select:focus-
.tok-com { color: #6b7780; font-style: italic; }
.md-caret { display: inline-block; width: 7px; height: 13px; margin-left: 1px; background: var(--primary); opacity: .75; animation: md-blink 1s steps(2) infinite; vertical-align: text-bottom; }
@keyframes md-blink { 50% { opacity: 0; } }
+
+/* Anteprime delle immagini allegate al messaggio in scrittura. Piccole di
+ proposito: servono a ricordare cosa si sta mandando, non a guardarle. */
+.attachments { display: flex; flex-wrap: wrap; gap: .4rem; padding: .4rem .1rem 0; }
+.attachment { position: relative; display: inline-flex; }
+.attachment img {
+ width: 3rem; height: 3rem; object-fit: cover; border-radius: .375rem;
+ border: 1px solid hsl(var(--border));
+}
+.attachment button {
+ position: absolute; top: -.35rem; right: -.35rem; width: 1.15rem; height: 1.15rem;
+ line-height: 1; border-radius: 999px; border: 1px solid hsl(var(--border));
+ background: hsl(var(--background)); color: hsl(var(--muted-foreground));
+ font-size: .7rem; cursor: pointer;
+}
+.attachment button:hover { color: hsl(var(--foreground)); }
diff --git a/web/src/lib/api.ts b/web/src/lib/api.ts
index b793d6f2..b4169a46 100644
--- a/web/src/lib/api.ts
+++ b/web/src/lib/api.ts
@@ -4,6 +4,11 @@ export interface ChatMessage {
id: string
role: ChatRole
content: string
+ /* Immagini allegate al turno, come data: URI. Restano sul messaggio e non
+ dentro `content` perche' la cronologia le deve poter rimandare al server
+ insieme al testo: un secondo turno che parla della foto senza la foto
+ riceverebbe una risposta su niente. */
+ images?: string[]
/* Reasoning models stream their thinking on a separate delta field before
the answer. Kept apart from `content` so it can be rendered as its own
block and excluded from what is sent back as conversation history. */
@@ -160,7 +165,19 @@ export async function streamChat(options: StreamChatOptions): Promise<StreamChat
signal: options.signal,
body: JSON.stringify({
model: options.model,
- messages: options.messages.map(({ role, content }) => ({ role, content })),
+ /* Un turno con immagini viaggia nella forma a parti dell'API OpenAI;
+ senza, resta la stringa di sempre e nessun server vede una differenza. */
+ messages: options.messages.map(({ role, content, images }) =>
+ images && images.length
+ ? {
+ role,
+ content: [
+ ...(content ? [{ type: "text", text: content }] : []),
+ ...images.map((url) => ({ type: "image_url", image_url: { url } })),
+ ],
+ }
+ : { role, content },
+ ),
temperature: options.temperature,
max_completion_tokens: options.maxTokens,
enable_thinking: options.enableThinking,