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): handle cancellation during prompt processing

eni105e78f46722
diff --git a/c/glm53.c b/c/glm53.c
index 7071863a..ff19690f 100644
--- a/c/glm53.c
+++ b/c/glm53.c
@@ -2721,9 +2721,15 @@ static float *forward_span(GModel *m, GSession *s, const int *tokens, int n,
*
* Con `keep_all` si tengono i logit di ogni posizione, che serve solo al
* confronto con l'oracolo; altrimenti si tiene l'ultima riga, che e' l'unica
- * che decide il token successivo. */
+ * che decide il token successivo.
+ *
+ * `halt`, se c'e', si chiede prima di ogni pezzo: un client che se n'e' andato
+ * a meta' di un prompt lungo non deve tenere il motore occupato fino in fondo.
+ * Se dice di fermarsi si torna NULL a un confine di pezzo, dove ogni layer e'
+ * avanzato e `filled` dice esattamente quanti token la sessione ha macinato. */
static float *forward_prefill(GModel *m, GSession *s, const int *tokens, int n,
- const float *vision, int n_vision, int keep_all) {
+ const float *vision, int n_vision, int keep_all,
+ int (*halt)(void *), void *halt_arg) {
const Cfg *c = &m->c;
const char *setting = getenv("GLM53_PREFILL_CHUNK");
int chunk = setting ? atoi(setting) : 128;
@@ -2736,6 +2742,11 @@ static float *forward_prefill(GModel *m, GSession *s, const int *tokens, int n,
int used_vision = 0;
for (int at = 0; at < n; at += chunk) {
+ if (halt && halt(halt_arg)) {
+ free(all);
+ free(last);
+ return NULL;
+ }
const int here = at + chunk <= n ? chunk : n - at;
/* Gli embedding dell'immagine vanno divisi come i token: a ogni pezzo
* quelli dei segnaposto che contiene, altrimenti il conto non torna e
@@ -3075,7 +3086,7 @@ static void slot_remember(KVSlot *slot, const int *tokens, int n) {
if (!slot->tokens) { fprintf(stderr, "OOM allocating slot history\n"); exit(1); }
slot->cap = n;
}
- memcpy(slot->tokens, tokens, (size_t)n * sizeof(int));
+ if (n > 0) memcpy(slot->tokens, tokens, (size_t)n * sizeof(int));
slot->n = n;
}
@@ -3316,6 +3327,24 @@ static int serve_cancel_pending(unsigned long long id, int *input_eof) {
return stopped ? SERVE_CTL_STOP : SERVE_CTL_NONE;
}
+/* La stessa guardata, fra un pezzo di prefill e l'altro.
+ *
+ * Senza, un client che se ne va a meta' di un prompt lungo lascia il motore a
+ * macinarlo fino in fondo per nessuno: misurato su una macchina di prova, un
+ * prompt di 281 token disconnesso a 20 s ha tenuto il motore fino a 211.7 s.
+ * Si ferma solo un CANCEL. Uno STOP si ricorda e decide al primo passo di
+ * decodifica, come avrebbe fatto arrivando li'; un CANCEL dopo vince lo
+ * stesso. EOF non ferma niente, e da li' non si legge piu'. */
+typedef struct { unsigned long long id; int *ctl, *input_eof; } PrefillWatch;
+
+static int prefill_should_halt(void *arg) {
+ PrefillWatch *w = (PrefillWatch *)arg;
+ if (*w->input_eof) return 0;
+ const int seen = serve_cancel_pending(w->id, w->input_eof);
+ if (seen != SERVE_CTL_NONE && *w->ctl != SERVE_CTL_CANCEL) *w->ctl = seen;
+ return *w->ctl == SERVE_CTL_CANCEL;
+}
+
/* Genera per una richiesta e chiude col suo DONE.
*
* Ritorna -1 se stdin ha raggiunto EOF durante il turno, 0 altrimenti: il turno
@@ -3430,16 +3459,25 @@ static int serve_one(GModel *m, Tok *tokenizer, ServeReq *q) {
g_echo_pin_logit = (pinned > 0 && shared == pinned && ps >= 0)
? slot->pins.slot[ps].logit : NULL;
}
+ int rows = 1, ctl = SERVE_CTL_NONE, input_eof = 0;
+ PrefillWatch watch = { q->id, &ctl, &input_eof };
float *logits = forward_prefill(m, slot->session, sequence + shared,
- total - shared, vision, n_vision, 0);
+ total - shared, vision, n_vision, 0,
+ prefill_should_halt, &watch);
g_echo_k = 0; g_echo_id = 0; /* la lettura riguarda il prefill, non la decodifica */
- if (q->pin && logits &&
+ /* Interrotto a meta' prefill: la sessione ha macinato solo `filled` token,
+ * e da qui in poi `total` dice quello, cosi' la storia che slot_remember
+ * scrive sotto e la riga CANCEL descrivono la cache vera. Un nuovo tentativo
+ * dello stesso prompt ne e' allora un'estensione stretta e riusa il pezzo
+ * gia' fatto. Il ciclo sotto esce al primo giro, senza toccare `logits`. */
+ if (ctl == SERVE_CTL_CANCEL)
+ total = slot->session->filled; /* e niente fotografia di un prompt a meta' */
+ else if (q->pin && logits &&
!slot_pin_save(m, slot, sequence, total, logits) && getenv("GLM53_VERBOSE"))
fprintf(stderr, "[PIN] fotografia non riuscita, si riparte da capo ogni volta\n");
else if (q->pin)
fprintf(stderr, "[PIN] stato fotografato a %d token\n", total);
GSession *session = slot->session;
- int rows = 1, ctl = SERVE_CTL_NONE, input_eof = 0;
for (int step = 0; step < budget; step++) {
/* #1332: una guardata a stdin per token. Il costo e' una select con
* timeout zero; il guadagno e' che il gateway smette di aspettare un
@@ -3454,7 +3492,14 @@ static int serve_one(GModel *m, Tok *tokenizer, ServeReq *q) {
* pagherebbe una select e una fgets a vuoto. Il turno finisce qui sotto
* e il DONE parte lo stesso; e' serve_one a dire a serve_loop, col
* valore di ritorno, che dopo non c'e' piu' nessuno. */
- if (!input_eof) ctl = serve_cancel_pending(q->id, &input_eof);
+ /* Un CANCEL visto durante il prefill decide qui senza guardare di
+ * nuovo. Uno STOP invece si guarda lo stesso: un CANCEL arrivato dopo
+ * l'ultima guardata del prefill deve vincere, come vinceva quando
+ * arrivavano insieme a questo punto. */
+ if (ctl != SERVE_CTL_CANCEL && !input_eof) {
+ const int seen = serve_cancel_pending(q->id, &input_eof);
+ if (seen != SERVE_CTL_NONE) ctl = seen;
+ }
if (ctl != SERVE_CTL_NONE) break;
if (total >= room) { limited = 1; break; }
const float *row = logits + (size_t)(rows - 1) * m->c.vocab;
@@ -3517,13 +3562,18 @@ static int serve_one(GModel *m, Tok *tokenizer, ServeReq *q) {
* un client che ha cambiato idea. */
if (ctl == SERVE_CTL_CANCEL) {
/* Fin dove e' arrivato il motore: il client ne ha ricevuti al massimo
- * `emitted`, e quanti ne mancano si legge solo dal suo lato. `filled`
- * sta accanto perche' un Continue riusa solo se ha piu' token di
- * quelli in cache: oggi filled == prompt + emitted, quindi anche un
- * client che ha ricevuto tutto rifa' il prefill da capo. */
+ * `emitted`, e quanti ne mancano si legge solo dal suo lato. Durante il
+ * prefill `filled` conta solo il prefisso completato; durante la decodifica
+ * filled == prompt + emitted. Un nuovo tentativo riusa la cache solo se
+ * il prompt ne contiene tutto il prefisso e almeno un token in piu'. */
if (getenv("GLM53_VERBOSE"))
fprintf(stderr, "CANCEL %llu %d %d %d\n", q->id, prompt_tokens,
emitted, session->filled);
+ /* Un turno con un'immagine interrotto a meta' prefill lascerebbe nella
+ * storia solo gli id dei segnaposto, e gli id non dicono quale
+ * immagine: una richiesta dopo con gli stessi id e senza IMAGE
+ * riuserebbe righe fatte da embedding che non ha mandato. Si butta. */
+ if (n_vision > 0) slot_reset(m, slot);
serve_line("ERROR %llu CANCELLED\n", q->id);
free(sequence);
return input_eof ? -1 : 0;
@@ -3808,7 +3858,8 @@ int main(int argc, char **argv) {
* volta e ogni token dopo costa un token, non tutto il prefisso. */
GSession *session = session_open(&model, count + (greedy > 0 ? greedy : 0) + 1);
const double prefill_start = now_s();
- float *logits = forward_prefill(&model, session, tokens, count, vision, n_vision, 1);
+ float *logits = forward_prefill(&model, session, tokens, count, vision, n_vision, 1,
+ NULL, NULL);
if (getenv("GLM53_VERBOSE")) {
fprintf(stderr, "load %.1fs, prefill %d tokens in %.1fs\n",
load_seconds, count, now_s() - prefill_start);
diff --git a/c/tests/glm53_serve_harness.py b/c/tests/glm53_serve_harness.py
index 91b7bc1f..abab16ce 100644
--- a/c/tests/glm53_serve_harness.py
+++ b/c/tests/glm53_serve_harness.py
@@ -452,6 +452,92 @@ def main() -> int:
f" da sessione pulita: {clean!r}")
return 1
+ # --- CANCEL durante il prefill ---
+ #
+ # Il CANCEL si guarda anche fra un pezzo di prefill e l'altro: prima un
+ # client che se ne andava a meta' di un prompt lungo lasciava il motore a
+ # macinarlo fino in fondo per nessuno. Il motore si ferma a un confine di
+ # pezzo, risponde CANCELLED senza DATA, e tiene quello che ha fatto: un
+ # nuovo tentativo dello stesso prompt ne e' un'estensione stretta e lo
+ # riusa, con la stessa risposta di una sessione pulita.
+ #
+ # Deterministico, non una corsa: il turno 29 mette in cache i primi 10
+ # token, e il CANCEL del turno 30 parte nella stessa scrittura del SUBMIT,
+ # quindi la guardata prima del primo pezzo lo trova gia' li'.
+ long_prompt = prompt + "abcdefghijklmnopqrstuvwxyz0123"
+ chunked = {"GLM53_PREFILL_CHUNK": "1"}
+ halted = engine(binary, arguments.fixture, chunked)
+ try:
+ handshake(halted)
+ submit(halted, 29, long_prompt[:10], max_tokens=1)
+ _, done29, _ = collect(halted, 29)
+ if not done29.startswith("DONE 29 "):
+ print(f"FAIL: turno che prepara la cache -> {done29!r}")
+ return 1
+ body = long_prompt.encode()
+ halted.stdin.write(f"SUBMIT 30 0 {len(body)} 4 0.0 1.0\n".encode() + body
+ + b"\nCANCEL 30\n")
+ halted.stdin.flush()
+ prefill_data, done30, _ = collect(halted, 30)
+ if done30 != "ERROR 30 CANCELLED" or prefill_data:
+ print(f"FAIL: CANCEL durante il prefill -> {done30!r} con "
+ f"{len(prefill_data)} byte di DATA, atteso ERROR 30 CANCELLED "
+ f"senza DATA")
+ return 1
+ notes = open(NOTES, "r", errors="replace").read().splitlines()
+ halted_line = [line.split() for line in notes if line.startswith("CANCEL 30 ")]
+ if halted_line != [["CANCEL", "30", str(len(body)), "0", "10"]]:
+ print(f"FAIL: CANCEL durante il prefill doveva fermarsi ai 10 token "
+ f"gia' in cache su {len(body)}: {halted_line!r}")
+ return 1
+ submit(halted, 31, long_prompt, max_tokens=4)
+ retried, done31, _ = collect(halted, 31)
+ if not done31.startswith("DONE 31 "):
+ print(f"FAIL: nuovo tentativo dopo il CANCEL -> {done31!r}")
+ return 1
+ if reuse_line(31)[2:4] != ["10", str(len(body))] or reuse_line(31)[-1] != "extend":
+ print(f"FAIL: il nuovo tentativo doveva riusare i 10 token del prefill "
+ f"interrotto: {reuse_line(31)!r}")
+ return 1
+ halted.stdin.close()
+ halted.wait(timeout=60)
+ finally:
+ if halted.poll() is None:
+ halted.kill()
+ clean_engine = engine(binary, arguments.fixture, chunked)
+ try:
+ handshake(clean_engine)
+ # Lo stesso CANCEL su uno slot vuoto: si ferma prima di macinare
+ # qualsiasi cosa, e la storia che resta ha zero token. Il motore deve
+ # rispondere CANCELLED e poi servire il turno dopo da freddo.
+ clean_engine.stdin.write(f"SUBMIT 33 0 {len(body)} 4 0.0 1.0\n".encode()
+ + body + b"\nCANCEL 33\n")
+ clean_engine.stdin.flush()
+ _, done33, _ = collect(clean_engine, 33)
+ empty_line = [line.split() for line in
+ open(NOTES, "r", errors="replace").read().splitlines()
+ if line.startswith("CANCEL 33 ")]
+ if done33 != "ERROR 33 CANCELLED" or \
+ empty_line != [["CANCEL", "33", str(len(body)), "0", "0"]]:
+ print(f"FAIL: CANCEL prima del primo pezzo su uno slot vuoto -> "
+ f"{done33!r}, {empty_line!r}")
+ return 1
+ submit(clean_engine, 32, long_prompt, max_tokens=4)
+ from_clean, done32, _ = collect(clean_engine, 32)
+ clean_engine.stdin.close()
+ clean_engine.wait(timeout=60)
+ finally:
+ if clean_engine.poll() is None:
+ clean_engine.kill()
+ if reuse_line(32)[-1:] != ["cold"]:
+ print(f"FAIL: dopo un CANCEL a zero token il turno doveva partire da "
+ f"freddo: {reuse_line(32)!r}")
+ return 1
+ if not done32.startswith("DONE 32 ") or retried != from_clean:
+ print(f"FAIL: dopo un prefill interrotto la risposta cambia\n"
+ f" riusando: {retried!r}\n da pulito: {from_clean!r} ({done32!r})")
+ return 1
+
# La CLI stampa la risposta e poi un a capo; quello che conta e' che i byte
# della risposta siano gli stessi.
from_cli = cli_answer(binary, arguments.fixture, prompt, tokens)
@@ -466,6 +552,8 @@ def main() -> int:
f"al secondo turno con la stessa risposta di una sessione pulita, "
f"CANCEL onorato a meta' turno dopo {emitted_before} token su {budget}, "
f"STOP chiuso col DONE dopo {emitted_stop} token su {stop_budget}, "
+ f"CANCEL durante il prefill fermo a 10 token su {len(body)} e riusato "
+ f"dal nuovo tentativo, "
f"SUBMIT a slot occupato rifiutato con SLOT_BUSY, "
f"{emitted_eof} token portati a termine con la pipa gia' chiusa")
return 0
diff --git a/docs/ENVIRONMENT.md b/docs/ENVIRONMENT.md
index 7c0ab378..044a4498 100644
--- a/docs/ENVIRONMENT.md
+++ b/docs/ENVIRONMENT.md
@@ -357,7 +357,7 @@ See `docs/glm53-flash.md`.
| `GLM53_BITS` | `4` | Precision of the resident dense weights: 4, 8 or 32. Routed experts are not affected — they arrive already quantized in the container and are never requantized. |
| `GLM53_EXPERT_GB` | measured | RAM budget (GB) for the expert LRU cache; per-layer slots are derived from it. Unset, it is taken from reclaimable physical memory after the weights are loaded (Linux `MemAvailable`, Windows available physical memory, macOS free+inactive+purgeable pages), minus a 3 GB margin. A fixed number is wrong in both directions: too small on a large machine leaves memory idle while the disk does all the work. |
| `GLM53_MAXT` | `8192` | KV state capacity in tokens, and the session size in serve mode. |
-| `GLM53_PREFILL_CHUNK` | `128` | Prefill chunk size in tokens. Smaller keeps the workspace smaller; too small re-reads experts once per chunk per layer instead of amortizing them. |
+| `GLM53_PREFILL_CHUNK` | `128` | Prefill chunk size in tokens. Smaller keeps the workspace smaller; too small re-reads experts once per chunk per layer instead of amortizing them. In serve mode, CANCEL is checked before each prefill chunk. Cancellation waits for any chunk already running to finish. |
| `GLM53_MAX_IMAGE_TOKENS` | checkpoint's (8000) | Ceiling on tokens per image. Each covers 28×28 pixels, so 256 keeps ordinary text legible and 64 keeps shapes and colours. The image is shrunk, not cropped. Lower it: 8000 is 2691 tokens for a 1080p photo, i.e. a prefill nobody will sit through. |
| `GLM53_VERBOSE` | unset | Print the parsed geometry, the expert budget and the per-token cache cost to stderr. |
| `GLM53_DUMP_INDEX` | unset | Print the rows the sparse indexer selected. The first place to look when the engine diverges only at certain lengths. |