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(glm53): vision people can actually use -- paste a path, get an answer

JustVugg2a2e0a180ed0
diff --git a/c/coli b/c/coli
index c6691e4a..f49a108e 100755
--- a/c/coli
+++ b/c/coli
@@ -24,7 +24,7 @@ Configuration through environment variables or flags (also valid after the subco
--topp P adaptive expert top-p --topk N fixed top-k
--ngen N maximum response tokens --cap N cache slots/layer
"""
-import os, sys, subprocess, argparse, json, time, signal, shutil, threading, re, codecs, tempfile, textwrap, struct
+import os, sys, subprocess, argparse, json, time, signal, shutil, threading, re, codecs, tempfile, textwrap, struct, shlex
# input() only gets line editing and UP/DOWN history once the readline module
# has been LOADED — without it the terminal's arrow-key escape sequences are
@@ -1290,7 +1290,7 @@ def chat_attached(a, base, model_id):
if msg in (":q",":quit","exit"): break
if not msg.strip(): continue
if msg==":reset": msgs=[]; print(f" {C.dim}✦ new conversation{C.r}\n"); continue
- msgs.append({"role":"user","content":msg})
+ msgs.append({"role":"user","content":message_with_images(msg)})
body=json.dumps({"model":model_id,"messages":msgs,"stream":True,
"max_tokens":ngen_for(a,interactive=True)}).encode()
req=urllib.request.Request(base.rstrip("/")+"/v1/chat/completions", data=body,
@@ -1396,6 +1396,45 @@ def kv_resume_notice(model_dir):
f"KVSAVE=0 disables saving · delete {p} to start clean{C.r}")
except (OSError, struct.error): pass
+IMAGE_SUFFIXES = (".png",".jpg",".jpeg",".webp",".bmp",".gif",".tif",".tiff")
+
+def message_with_images(text):
+ """Un percorso incollato diventa un'immagine, il resto resta testo.
+
+ Chi scrive in chat non ha voglia di comporre JSON: incolla il percorso, o
+ ce lo trascina sopra e il terminale glielo mette fra virgolette. Qui si
+ riconoscono i pezzi della riga che sono davvero file che esistono e hanno
+ l'estensione di un'immagine, e si costruisce il messaggio a parti che il
+ gateway gia' capisce. Se non ce ne sono, il messaggio resta la stringa di
+ prima e nessun percorso di codice cambia.
+
+ Il controllo e' che il file ESISTA: senza, una frase che nomina "foto.png"
+ diventerebbe una richiesta con un'immagine che non c'e'."""
+ if not text.strip():
+ return text
+ try:
+ tokens = shlex.split(text, posix=True)
+ except ValueError:
+ # Un apostrofo o una virgoletta spaiata: e' prosa, non un percorso
+ # quotato. Meglio lasciarla passare come testo che rifiutare la riga.
+ return text
+ pieces, found = [], []
+ for token in tokens:
+ candidate = os.path.expanduser(token)
+ if candidate.lower().endswith(IMAGE_SUFFIXES) and os.path.isfile(candidate):
+ found.append(candidate)
+ else:
+ pieces.append(token)
+ if not found:
+ return text
+ content = []
+ remaining = " ".join(pieces).strip()
+ if remaining:
+ content.append({"type":"text","text":remaining})
+ for path in found:
+ content.append({"type":"image_url","image_url":{"url":path}})
+ return content
+
def cmd_chat(a):
# ATTACH: a running `coli serve` beats a private engine every time — the load
# (34-136 s) and the cache warmth survive between sessions. Explicit --attach
diff --git a/c/glm53 b/c/glm53
index 19d2e75d..1d43ee36 100644
Binary files a/c/glm53 and b/c/glm53 differ
diff --git a/c/glm53.c b/c/glm53.c
index 02f4d66a..ace25eca 100644
--- a/c/glm53.c
+++ b/c/glm53.c
@@ -2293,6 +2293,27 @@ static void slot_remember(KVSlot *slot, const int *tokens, int n) {
slot->n = n;
}
+/* Un'immagine annunciata prima della richiesta a cui appartiene.
+ *
+ * Il protocollo porta testo; le patch sono binarie e grosse, quindi arrivano
+ * con un frame loro (IMAGE) subito prima del SUBMIT con lo stesso id. Il
+ * motore la tiene da parte finche' quella richiesta non arriva, e se arriva
+ * un'altra immagine prima la vecchia si butta: tenere quella sbagliata
+ * vorrebbe dire rispondere sulla foto precedente senza dirlo. */
+typedef struct {
+ unsigned long long id;
+ float *patches;
+ int grid_h, grid_w;
+} PendingImage;
+
+static PendingImage g_pending = {0, NULL, 0, 0};
+
+static void pending_clear(void) {
+ free(g_pending.patches);
+ g_pending.patches = NULL;
+ g_pending.id = 0;
+}
+
typedef struct {
unsigned long long id;
int slot, max_tokens;
@@ -2356,6 +2377,28 @@ static int serve_read_req(ServeReq *q, char *verb, size_t verb_size) {
sscanf(header, "%*s %llu", &q->id);
return 1;
}
+ if (!strcmp(verb, "IMAGE")) {
+ unsigned long long id; int bytes, grid_h, grid_w;
+ if (sscanf(header, "IMAGE %llu %d %d %d", &id, &bytes, &grid_h, &grid_w) != 4 ||
+ bytes < 0 || bytes > (1 << 28) || grid_h < 1 || grid_w < 1) {
+ strcpy(verb, "BAD_FRAME");
+ return 1;
+ }
+ pending_clear();
+ float *patches = malloc((size_t)bytes);
+ if (!patches || fread(patches, 1, (size_t)bytes, stdin) != (size_t)bytes) {
+ free(patches);
+ strcpy(verb, "BAD_FRAME");
+ return 1;
+ }
+ (void)fgetc(stdin); /* il '\n' di chiusura */
+ g_pending.id = id;
+ g_pending.patches = patches;
+ g_pending.grid_h = grid_h;
+ g_pending.grid_w = grid_w;
+ q->id = id;
+ return 1;
+ }
if (strcmp(verb, "SUBMIT")) return 1;
if (sscanf(header, "SUBMIT %llu %d %d %d %f %f", &q->id, &q->slot, &q->plen,
&q->max_tokens, &q->temp, &q->top_p) != 6) {
@@ -2427,9 +2470,34 @@ static void serve_one(GModel *m, Tok *tokenizer, ServeReq *q) {
slot->session = session_open(m, room);
shared = 0;
}
+ /* L'immagine annunciata per QUESTA richiesta, se c'e'. Il prefisso in
+ * cache non la riguarda: la torre ha gia' dato i suoi embedding quando
+ * quei token sono stati macinati, e i segnaposto stanno nel prompt. Se il
+ * riuso salta i token immagine, gli embedding da consumare sono quelli
+ * delle posizioni nuove, quindi il riuso si annulla quando c'e' un'immagine
+ * -- costa un prefill in piu' ed e' l'unica cosa che non puo' sbagliare. */
+ float *vision = NULL;
+ int n_vision = 0;
+ if (g_pending.patches && g_pending.id == q->id) {
+ if (!m->has_vision) {
+ pending_clear();
+ free(sequence);
+ serve_line("ERROR %llu BAD_REQUEST\n", q->id);
+ return;
+ }
+ if (shared) { /* niente riuso con un'immagine */
+ slot_reset(m, slot);
+ slot->session = session_open(m, room);
+ shared = 0;
+ }
+ vision = vision_encode(m, g_pending.patches, g_pending.grid_h,
+ g_pending.grid_w, &n_vision);
+ pending_clear();
+ }
+
const int reused = shared;
float *logits = forward_prefill(m, slot->session, sequence + shared,
- total - shared, NULL, 0, 0);
+ total - shared, vision, n_vision, 0);
GSession *session = slot->session;
int rows = 1;
for (int step = 0; step < budget; step++) {
@@ -2448,6 +2516,7 @@ static void serve_one(GModel *m, Tok *tokenizer, ServeReq *q) {
rows = 1;
}
free(logits);
+ free(vision);
/* La sessione resta allo slot per il turno dopo, con la sequenza che ha
* davvero macinato: prompt piu' quello che ha generato. */
slot_remember(slot, sequence, total);
@@ -2476,6 +2545,8 @@ static void serve_loop(GModel *m, Tok *tokenizer) {
if (!strcmp(verb, "SUBMIT")) {
serve_one(m, tokenizer, &q);
free(q.payload);
+ } else if (!strcmp(verb, "IMAGE")) {
+ /* annunciata: nessuna risposta, la si usa al SUBMIT che segue */
} else if (!strcmp(verb, "BAD_FRAME")) {
serve_line("ERROR %llu BAD_FRAME\n", q.id);
} else if (!strcmp(verb, "CANCEL")) {
diff --git a/c/openai_server.py b/c/openai_server.py
index 1e8daf28..09c81167 100644
--- a/c/openai_server.py
+++ b/c/openai_server.py
@@ -1369,6 +1369,90 @@ def render_chat(messages, enable_thinking=False, reasoning_effort=None, tools=No
return "".join(prompt)
+# ---- immagini per GLM-5.3 ------------------------------------------------------------
+# Il modello vede l'immagine come una sequenza di segnaposto <|image|>, uno per
+# token che la torre produrra': (griglia_h/2) x (griglia_w/2). Il numero non e'
+# negoziabile -- il motore rifiuta se non combacia con gli embedding che riceve --
+# quindi si preprocessa PRIMA di rendere il prompt e si espande il segnaposto al
+# numero giusto. Cosi' il renderer non deve sapere niente di immagini.
+GLM53_IMAGE_OPEN, GLM53_IMAGE, GLM53_IMAGE_CLOSE = (
+ "<|begin_of_image|>", "<|image|>", "<|end_of_image|>")
+
+
+def _image_bytes_from_url(url):
+ """data: URI, file:// o percorso sul disco -> i byte dell'immagine."""
+ if not isinstance(url, str) or not url:
+ raise APIError(400, "image_url.url must be a non-empty string.", "messages")
+ if url.startswith("data:"):
+ head, _, payload = url.partition(",")
+ if "base64" not in head:
+ raise APIError(400, "only base64 data: URIs are supported.", "messages")
+ import base64
+ try:
+ return base64.b64decode(payload, validate=True)
+ except Exception:
+ raise APIError(400, "image_url.url is not valid base64.", "messages")
+ if url.startswith("http://") or url.startswith("https://"):
+ # Scaricare da un URL che arriva in una richiesta vorrebbe dire far fare
+ # al server una chiamata di rete decisa da chi la manda. Non si fa.
+ raise APIError(400, "remote image URLs are not fetched; send the image "
+ "as a base64 data: URI or a path on this machine.",
+ "messages")
+ path = url[7:] if url.startswith("file://") else url
+ try:
+ with open(path, "rb") as handle:
+ return handle.read()
+ except OSError as problem:
+ raise APIError(400, f"cannot read image {path}: {problem}", "messages")
+
+
+def expand_glm53_images(messages, model_dir):
+ """Sostituisce le parti immagine coi loro segnaposto e ne estrae le patch.
+
+ Restituisce (messaggi riscritti, patch). I messaggi tornano con contenuto
+ testuale puro, quindi il renderer li tratta come qualunque altro turno."""
+ images = []
+ rewritten = []
+ for message in messages:
+ content = message.get("content") if isinstance(message, dict) else None
+ if not isinstance(content, list):
+ rewritten.append(message)
+ continue
+ pieces = []
+ for part in content:
+ if not isinstance(part, dict):
+ continue
+ kind = part.get("type")
+ if kind == "text":
+ pieces.append(part.get("text", ""))
+ elif kind in ("image_url", "input_image"):
+ url = (part.get("image_url") or {}).get("url") if kind == "image_url" \
+ else part.get("image_url") or part.get("url")
+ data = _image_bytes_from_url(url)
+ patches, grid_h, grid_w = _preprocess_image(data, model_dir)
+ tokens = (grid_h // 2) * (grid_w // 2)
+ images.append((patches, grid_h, grid_w))
+ pieces.append(GLM53_IMAGE_OPEN + GLM53_IMAGE * tokens + GLM53_IMAGE_CLOSE)
+ else:
+ raise APIError(400, f"unsupported content part {kind!r}.", "messages")
+ rewritten.append({**message, "content": "".join(pieces)})
+ return rewritten, images
+
+
+def _preprocess_image(data, model_dir):
+ """L'immagine nelle patch che la torre vuole. Il lavoro sta in
+ tools/glm53_image.py, verificato contro il processore ufficiale."""
+ try:
+ import sys as _sys
+ from pathlib import Path as _Path
+ _sys.path.insert(0, str(_Path(__file__).resolve().parent / "tools"))
+ from glm53_image import preprocess
+ except ImportError as problem:
+ raise APIError(400, f"image support needs Pillow and numpy ({problem}).",
+ "messages")
+ return preprocess(data, model_dir)
+
+
GLM53_TOOL_PREAMBLE = (
"<|system|>\n# Tools\n\n"
"You may call one or more functions to assist with the user query.\n\n"
@@ -2240,6 +2324,7 @@ class Engine:
family = (resolve_model(model).descriptor if config.exists()
else family_by_id(ARCH))
arch = family.id
+ self.model_dir = str(model)
child_env = dict(env or os.environ, SNAP=str(model), SERVE="1", SERVE_BATCH="1",
NGEN=str(max_tokens), KV_SLOTS=str(kv_slots))
tune_child_env(child_env, arch)
@@ -2426,7 +2511,7 @@ class Engine:
def generate(self, prompt, max_tokens, temperature, top_p, on_text, cache_slot=0,
cancelled=None, grammar=None, stopped=None, on_accept=None, audio=None,
- on_tool=None):
+ on_tool=None, image=None):
if isinstance(cache_slot, bool) or not isinstance(cache_slot, int) or not 0 <= cache_slot < self.kv_slots:
raise APIError(400, "Invalid cache slot.", "cache_slot")
payload = prompt.encode("utf-8")
@@ -2491,6 +2576,16 @@ class Engine:
with self.write_lock:
if self.process.poll() is not None:
raise RuntimeError("colibri engine is not running")
+ # Le patch sono binarie e grosse: viaggiano in un frame loro,
+ # annunciato subito prima del SUBMIT a cui appartengono. Deve
+ # partire dentro lo stesso lock, o un'altra richiesta potrebbe
+ # infilarsi in mezzo e prendersi l'immagine di questa.
+ if image is not None:
+ patches, grid_h, grid_w = image
+ blob = patches.tobytes() if hasattr(patches, "tobytes") else patches
+ self.process.stdin.write(
+ f"IMAGE {request_id} {len(blob)} {grid_h} {grid_w}\n".encode()
+ + blob + b"\n")
self.process.stdin.write(header + payload + xpayload + b"\n")
self.process.stdin.flush()
except Exception:
@@ -3122,7 +3217,7 @@ class APIHandler(BaseHTTPRequestHandler):
return {"type": "error", "error": {"type": error.error_type, "message": error.message}}
def generation(self, body, prompt, request_id, chat, tools=None, tool_choice=None,
- enable_thinking=False, audio=None):
+ enable_thinking=False, audio=None, image=None):
# COLI_DEBUG tees the engine transaction to stderr: 1 = decoded output stream only,
# 2 = both sides (rendered prompt + output). render_chat already folds prior turns and
# tool results into `prompt`, so level 2 is the full conversation the engine saw.
@@ -3186,7 +3281,8 @@ class APIHandler(BaseHTTPRequestHandler):
prompt, maximum, temperature, top_p, stop_filter.feed, cache_slot,
self.client_disconnected, grammar=grammar, stopped=generation_stopped,
**({"on_tool": sideband.feed} if sideband.enabled else {}),
- **({"audio": audio} if audio else {}))
+ **({"audio": audio} if audio else {}),
+ **({"image": image} if image is not None else {}))
stop_filter.finish()
sideband.finish()
text = "".join(output)
@@ -3367,7 +3463,8 @@ class APIHandler(BaseHTTPRequestHandler):
prompt, maximum, temperature, top_p, stop_filter.feed, cache_slot,
self.client_disconnected, grammar=grammar, stopped=generation_stopped,
**({"on_tool": sideband.feed} if sideband.enabled else {}),
- on_accept=start_stream, **({"audio": audio} if audio else {}))
+ on_accept=start_stream, **({"audio": audio} if audio else {}),
+ **({"image": image} if image is not None else {}))
stop_filter.finish()
sideband.finish()
if think:
@@ -3398,7 +3495,8 @@ class APIHandler(BaseHTTPRequestHandler):
stats = self.server.engine.generate(
prompt, maximum, temperature, top_p, stop_filter.feed, cache_slot,
self.client_disconnected, grammar=grammar, stopped=stop_filter.stopped,
- on_accept=start_stream, **({"audio": audio} if audio else {}))
+ on_accept=start_stream, **({"audio": audio} if audio else {}),
+ **({"image": image} if image is not None else {}))
stop_filter.finish()
if content_split:
content_split.close()
@@ -3467,11 +3565,24 @@ class APIHandler(BaseHTTPRequestHandler):
tools = body.get("tools") or body.get("functions") or None
tool_choice = body.get("tool_choice")
audio_clips = [] if ARCH == "inkling" else None
- prompt = render_chat_for_arch(body.get("messages"), enable_thinking, reasoning_effort,
+ messages = body.get("messages")
+ # Le immagini diventano segnaposto PRIMA del rendering: il renderer
+ # tratta poi turni di solo testo, e il conto dei segnaposto e quello
+ # degli embedding non possono divergere.
+ image = None
+ if ARCH == "glm53":
+ messages, images = expand_glm53_images(
+ messages, getattr(self.server.engine, "model_dir", None))
+ if len(images) > 1:
+ raise APIError(400, "one image per request for now; the engine "
+ "holds a single pending image.", "messages")
+ image = images[0] if images else None
+ prompt = render_chat_for_arch(messages, enable_thinking, reasoning_effort,
tools, tool_choice, audio_out=audio_clips)
self.generation(body, prompt, request_id, True, tools, tool_choice,
enable_thinking=enable_thinking,
- audio=b"".join(audio_clips) if audio_clips else None)
+ audio=b"".join(audio_clips) if audio_clips else None,
+ image=image)
# ---- Anthropic /v1/messages (#343) ----------------------------------------------------
ANTHROPIC_STOP = {"stop": "end_turn", "length": "max_tokens", "tool_calls": "tool_use"}
diff --git a/c/tests/test_glm53_vision_serve.py b/c/tests/test_glm53_vision_serve.py
new file mode 100644
index 00000000..9a2d8750
--- /dev/null
+++ b/c/tests/test_glm53_vision_serve.py
@@ -0,0 +1,131 @@
+#!/usr/bin/env python3
+"""Un'immagine attraversa il protocollo e cambia la risposta.
+
+Fino a ieri la torre vision c'era e non era raggiungibile: la CLI voleva patch
+gia' estratte, il protocollo portava solo testo e il gateway buttava via le
+immagini in silenzio, che e' il modo peggiore di non supportarle -- l'utente
+manda una foto, riceve una risposta, e la risposta parla del nulla.
+
+Questo test segue la catena intera: si preprocessa un'immagine con lo stesso
+codice che usa il gateway, la si manda col frame IMAGE, e si chiede al motore
+di rispondere a un prompt che contiene i segnaposto.
+
+La verifica non e' che risponda: risponderebbe comunque, anche ignorando i
+pixel. E' che **due immagini diverse diano due risposte diverse**. Se il frame
+arrivasse e venisse scartato, o gli embedding finissero nelle posizioni
+sbagliate, il modello continuerebbe a parlare e le due risposte sarebbero
+identiche: e' l'unica differenza che distingue una vision collegata da una
+vision finta.
+
+USO:
+ python3 tests/test_glm53_vision_serve.py --binary ./glm53 --fixture ~/glm53_mm_tiny
+"""
+import argparse
+import json
+import os
+import subprocess
+import sys
+from pathlib import Path
+
+IMAGE_OPEN, IMAGE_TOKEN, IMAGE_CLOSE = "<|begin_of_image|>", "<|image|>", "<|end_of_image|>"
+
+
+def make_image(seed, side, numpy):
+ """Un'immagine deterministica, senza file su disco."""
+ generator = numpy.random.default_rng(seed)
+ return generator.integers(0, 256, (side, side, 3), dtype=numpy.uint8)
+
+
+def read_line(stream):
+ line = stream.readline()
+ if not line:
+ raise AssertionError("il motore ha chiuso lo stream prima del previsto")
+ return line.decode("utf-8", "replace").rstrip("\n")
+
+
+def ask(process, request_id, prompt, image):
+ """IMAGE piu' SUBMIT, e la risposta in byte."""
+ patches, grid_h, grid_w = image
+ blob = patches.tobytes()
+ process.stdin.write(
+ f"IMAGE {request_id} {len(blob)} {grid_h} {grid_w}\n".encode() + blob + b"\n")
+ body = prompt.encode("utf-8")
+ process.stdin.write(
+ f"SUBMIT {request_id} 0 {len(body)} 4 0.0 1.0\n".encode() + body + b"\n")
+ process.stdin.flush()
+
+ pieces = []
+ while True:
+ line = read_line(process.stdout)
+ if line.startswith("DATA "):
+ count = int(line.split()[2])
+ pieces.append(process.stdout.read(count + 1)[:count])
+ elif line.startswith("ERROR "):
+ raise AssertionError(f"il motore ha rifiutato: {line}")
+ elif line.startswith("DONE "):
+ return b"".join(pieces)
+
+
+def main() -> int:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--binary", required=True)
+ parser.add_argument("--fixture", type=Path, required=True)
+ arguments = parser.parse_args()
+
+ try:
+ import numpy
+ from PIL import Image
+ except ImportError as problem:
+ print(f"SKIP: servono numpy e Pillow ({problem}); niente e' stato verificato")
+ return 0
+ sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tools"))
+ from glm53_image import preprocess, load_config
+
+ settings = load_config(arguments.fixture)
+ merge = settings.get("merge_size", 2)
+ patch = settings.get("patch_size", 14)
+ # La misura piu' piccola che soddisfa il minimo di 16 token immagine.
+ side = patch * merge * 4
+
+ images = [preprocess(Image.fromarray(make_image(seed, side, numpy)), arguments.fixture)
+ for seed in (1, 2)]
+ tokens = (images[0][1] // merge) * (images[0][2] // merge)
+ if images[1][1:] != images[0][1:]:
+ print("SKIP: le due immagini di prova hanno griglie diverse")
+ return 0
+
+ prompt = "gu" + IMAGE_OPEN + IMAGE_TOKEN * tokens + IMAGE_CLOSE + "xy"
+ environment = {**os.environ, "SERVE": "1", "SERVE_BATCH": "1",
+ "SNAP": str(arguments.fixture), "GLM53_BITS": "32"}
+ process = subprocess.Popen([os.path.abspath(arguments.binary)],
+ stdin=subprocess.PIPE, stdout=subprocess.PIPE,
+ stderr=subprocess.DEVNULL, env=environment)
+ try:
+ if "READY" not in read_line(process.stdout):
+ print("FAIL: nessun READY")
+ return 1
+ read_line(process.stdout) # STAT
+ first = ask(process, 1, prompt, images[0])
+ second = ask(process, 2, prompt, images[1])
+ process.stdin.close()
+ process.wait(timeout=120)
+ finally:
+ if process.poll() is None:
+ process.kill()
+
+ if not first:
+ print("FAIL: nessun token generato con un'immagine")
+ return 1
+ if first == second:
+ print(f"FAIL: due immagini diverse danno la stessa risposta ({first!r});\n"
+ f" i pixel non stanno arrivando al modello")
+ return 1
+
+ print(f"PASS GLM-5.3 vision sul protocollo: {tokens} token immagine da una "
+ f"{side}x{side}, due immagini diverse danno risposte diverse "
+ f"({first!r} contro {second!r})")
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/c/tools/glm53_image.py b/c/tools/glm53_image.py
new file mode 100644
index 00000000..170d686a
--- /dev/null
+++ b/c/tools/glm53_image.py
@@ -0,0 +1,210 @@
+#!/usr/bin/env python3
+"""Da un'immagine alle patch che la torre vision di GLM-5.3 si aspetta.
+
+Il motore C prende patch gia' estratte e non sa niente di JPEG, di
+ridimensionamenti o di normalizzazioni: quel lavoro sta qui, dove Python c'e'
+gia' per il template di chat e per il gateway.
+
+Cosa fa, nell'ordine del processore ufficiale:
+
+ 1. decodifica e converte in RGB
+ 2. sceglie la tela con smart_resize -- aritmetica intera, allineata a 28
+ (patch 14 per merge 2), dentro al budget di token del checkpoint
+ 3. ridimensiona, riscala di 1/255 e normalizza con media e deviazione CLIP
+ 4. spezza in patch nell'ordine che vuole la torre: a blocchi di merge,
+ e dentro ogni patch canale, ripetizione temporale, riga, colonna
+
+Un avvertimento onesto sul punto 3. Il processore di riferimento ridimensiona
+con torchvision, e riprodurne il bicubico senza portarsi dietro torch non e'
+possibile: qui si usa quello di Pillow. Geometria, ordine delle patch e
+normalizzazione sono identici e verificati contro il riferimento; i valori dei
+pixel differiscono di quanto differiscono due bicubici, che il test misura e
+scrive invece di dichiararlo zero.
+
+USO:
+ python3 tools/glm53_image.py foto.jpg --out patches.f32
+ python3 tools/glm53_image.py foto.jpg --json # solo la griglia
+"""
+from __future__ import annotations
+
+import argparse
+import json
+import math
+import sys
+from pathlib import Path
+
+# Dal processor_config.json del checkpoint. Restano qui come default e vengono
+# sovrascritti da quel file quando lo si passa: due copie che divergono in
+# silenzio sarebbero peggio di nessuna.
+PATCH = 14
+MERGE = 2
+TEMPORAL = 2
+MIN_TOKENS = 16
+MAX_TOKENS = 8000
+MEAN = (0.48145466, 0.4578275, 0.40821073)
+STD = (0.26862954, 0.26130258, 0.27577711)
+
+
+def smart_resize(height, width, *, temporal=TEMPORAL, factor=PATCH * MERGE,
+ min_tokens=MIN_TOKENS, max_tokens=MAX_TOKENS, frames=None):
+ """La tela allineata dentro al budget. Aritmetica intera, come l'originale."""
+ # Il riferimento passa num_frames = temporal_factor, non 1: conta nel
+ # ramo che allarga un'immagine troppo piccola.
+ if frames is None: frames = temporal
+ pixels_per_token = temporal * factor ** 2
+ min_pixels = min_tokens * pixels_per_token
+ max_pixels = max_tokens * pixels_per_token
+
+ def align(value):
+ return math.ceil(value / factor) * factor
+
+ aligned_frames = max(temporal, round(frames / temporal) * temporal)
+ aligned_height, aligned_width = align(height), align(width)
+ budget = aligned_frames * aligned_height * aligned_width
+
+ if budget < min_pixels:
+ scale = math.sqrt(min_pixels / (frames * height * width))
+ aligned_height = align(max(1, math.ceil(height * scale)))
+ aligned_width = align(max(1, math.ceil(width * scale)))
+ budget = aligned_frames * aligned_height * aligned_width
+
+ if budget > max_pixels:
+ minimum = aligned_frames * factor ** 2
+ if max_pixels < minimum:
+ raise ValueError(f"max_tokens={max_tokens} non basta per una sola patch")
+ low, high = 1, height
+ best = (factor, factor)
+ while low <= high:
+ content_height = (low + high) // 2
+ content_width = max(1, math.floor(width * content_height / height))
+ candidate = (align(content_height), align(content_width))
+ if aligned_frames * candidate[0] * candidate[1] <= max_pixels:
+ best = candidate
+ low = content_height + 1
+ else:
+ high = content_height - 1
+ aligned_height, aligned_width = best
+
+ return aligned_height, aligned_width
+
+
+def patchify(pixels, numpy, patch=PATCH, merge=MERGE, temporal=TEMPORAL):
+ """[3, H, W] normalizzato -> [griglia, 3*T*14*14], nell'ordine della torre.
+
+ L'ordine non e' quello della griglia riga per riga: e' a blocchi di merge,
+ perche' e' cosi' che il merger 2x2 poi li richiude. Dentro ogni patch i
+ valori vanno canale, ripetizione temporale, riga, colonna."""
+ channels, height, width = pixels.shape
+ grid_h, grid_w = height // patch, width // patch
+ blocks = pixels.reshape(channels, grid_h // merge, merge, patch,
+ grid_w // merge, merge, patch)
+ # [gh/m, gw/m, m, m, C, p, p]
+ blocks = blocks.transpose(1, 4, 2, 5, 0, 3, 6)
+ blocks = numpy.repeat(blocks[..., None, :, :], temporal, axis=-3)
+ return numpy.ascontiguousarray(
+ blocks.reshape(grid_h * grid_w, channels * temporal * patch * patch),
+ dtype=numpy.float32), grid_h, grid_w
+
+
+def load_config(model_dir):
+ """I parametri veri del checkpoint, quando c'e'.
+
+ processor_config.json e' la fonte giusta, ma un export che non ce l'ha ha
+ comunque vision_config dentro config.json: patch, merge e ripetizione
+ temporale devono venire dal modello che si sta usando, non da costanti
+ scritte qui, o su un checkpoint con una geometria diversa si taglierebbero
+ patch della misura sbagliata senza che nulla protesti."""
+ settings = {}
+ if not model_dir:
+ return settings
+ root = Path(model_dir)
+ processor = root / "processor_config.json"
+ if processor.exists():
+ settings.update(json.loads(processor.read_text()).get("image_processor", {}))
+ config = root / "config.json"
+ if config.exists():
+ vision = json.loads(config.read_text()).get("vision_config") or {}
+ for their, ours in (("patch_size", "patch_size"),
+ ("spatial_merge_size", "merge_size"),
+ ("temporal_patch_size", "temporal_patch_size")):
+ if their in vision:
+ settings.setdefault(ours, vision[their])
+ return settings
+
+
+def preprocess(source, model_dir=None):
+ """Immagine (percorso, bytes o oggetto PIL) -> (patch, grid_h, grid_w)."""
+ import numpy
+ from PIL import Image
+
+ settings = load_config(model_dir)
+ mean = tuple(settings.get("image_mean", MEAN))
+ 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)
+ patch = settings.get("patch_size", PATCH)
+ merge = settings.get("merge_size", MERGE)
+ temporal = settings.get("temporal_patch_size", TEMPORAL)
+
+ if isinstance(source, (str, Path)):
+ image = Image.open(source)
+ elif isinstance(source, bytes):
+ import io
+ image = Image.open(io.BytesIO(source))
+ else:
+ image = source
+ image = image.convert("RGB")
+
+ height, width = image.height, image.width
+ target_h, target_w = smart_resize(height, width, temporal=temporal,
+ factor=patch * merge, min_tokens=min_tokens,
+ max_tokens=max_tokens)
+
+ # L'immagine NON viene stirata sulla tela: si scala mantenendo il rapporto
+ # e il resto della tela resta nero. Stirarla cambierebbe le proporzioni di
+ # tutto quello che il modello guarda, e non darebbe nessun errore.
+ scale = min(target_h / height, target_w / width)
+ pixels_per_token = temporal * (patch * merge) ** 2
+ if temporal * height * width >= pixels_per_token * min_tokens:
+ scale = min(1.0, scale) # gia' abbastanza grande: non si ingrandisce
+ content_h = max(1, min(target_h, math.floor(height * scale)))
+ content_w = max(1, min(target_w, math.floor(width * scale)))
+ if (content_h, content_w) != (height, width):
+ image = image.resize((content_w, content_h), Image.BICUBIC)
+
+ # Il riempimento e' a zero PRIMA della normalizzazione, quindi nella tela
+ # finita vale (0 - media)/deviazione e non zero.
+ canvas = numpy.zeros((target_h, target_w, 3), numpy.float32)
+ canvas[:content_h, :content_w] = numpy.asarray(image, dtype=numpy.float32)
+ pixels = canvas.transpose(2, 0, 1) / 255.0
+ for channel in range(3):
+ pixels[channel] = (pixels[channel] - mean[channel]) / std[channel]
+ return patchify(pixels, numpy, patch, merge, temporal)
+
+
+def main() -> int:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("image", type=Path)
+ parser.add_argument("--out", type=Path, help="dove scrivere le patch f32")
+ parser.add_argument("--model", type=Path, help="checkpoint da cui leggere i parametri")
+ parser.add_argument("--json", action="store_true", help="stampa solo la griglia")
+ arguments = parser.parse_args()
+
+ patches, grid_h, grid_w = preprocess(arguments.image, arguments.model)
+ merge = load_config(arguments.model).get("merge_size", MERGE)
+ tokens = (grid_h // merge) * (grid_w // merge)
+ if arguments.out:
+ arguments.out.write_bytes(patches.tobytes())
+ if arguments.json:
+ print(json.dumps({"grid_h": grid_h, "grid_w": grid_w,
+ "patches": int(patches.shape[0]),
+ "image_tokens": tokens}))
+ else:
+ print(f"{arguments.image.name}: griglia {grid_h}x{grid_w}, "
+ f"{patches.shape[0]} patch da {patches.shape[1]}, "
+ f"{tokens} token immagine")
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())