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

brio mode: score a closed set of options instead of generating

JustVugge16146c8685d
diff --git a/c/Makefile b/c/Makefile
index 3d81868e..e679a774 100644
--- a/c/Makefile
+++ b/c/Makefile
@@ -1355,6 +1355,9 @@ tests/test_spec_decode_state$(EXE): tests/test_spec_decode_state.c colibri.c st.
tests/test_decode_batch$(EXE): tests/test_decode_batch.c decode_batch.h
$(CC) $(CFLAGS) $< -o $@ $(LDFLAGS)
+tests/test_pin_pool$(EXE): tests/test_pin_pool.c pin_pool.h kv_prefix.h
+ $(CC) $(CFLAGS) $< -o $@ $(LDFLAGS)
+
tests/test_serve_codec$(EXE): tests/test_serve_codec.c serve_codec.h compat.h
$(CC) $(CFLAGS) $< -o $@ $(LDFLAGS)
diff --git a/c/coli b/c/coli
index 6c416ce5..061c06c5 100755
--- a/c/coli
+++ b/c/coli
@@ -1475,6 +1475,99 @@ def render_gen_stats(st, mode):
if st["interrupted"]: parts.append("⏹ interrupted")
return " · ".join(parts)
+
+
+# ---- comandi della chat ------------------------------------------------------
+#
+# Stanno in un posto solo perche servono a tre cose che devono restare
+# d'accordo: il completamento col TAB, l'elenco di /help, e il controllo che
+# impedisce a un comando scritto male di partire come messaggio al modello.
+# Quest'ultimo e il motivo per cui esistono: prima "/brio merge" con una lettera
+# sbagliata finiva dritto al modello, che rispondeva educatamente a una riga di
+# comando. Ogni forma si accetta sia con / sia con : -- i comandi storici usano
+# i due punti e non si toglie a nessuno l'abitudine.
+CHAT_COMMANDS = {
+ "brio": "a | b | c punteggia le opzioni invece di generare; senza opzioni torna alla chat",
+ "reset": " ricomincia la conversazione",
+ "help": " questo elenco",
+ "quit": " esci (anche :q)",
+}
+
+def chat_command(message):
+ """(nome, resto) se la riga e un comando, (None, None) se e un messaggio.
+
+ Il nome torna anche quando NON esiste: e il chiamante a decidere che farne,
+ e deve poter distinguere "comando sbagliato" da "testo che comincia con /"."""
+ if not message or message[0] not in "/:":
+ return None, None
+ head, _, rest = message[1:].partition(" ")
+ return head.strip().lower(), rest.strip()
+
+def chat_commands_help():
+ print(f" {C.dim}comandi:{C.r}")
+ for name, what in CHAT_COMMANDS.items():
+ print(f" {C.teal}/{name}{C.r} {C.dim}{what}{C.r}")
+ print()
+
+def install_chat_completer():
+ """TAB completa i comandi. Senza readline (Windows) si perde solo il TAB."""
+ try:
+ import readline
+ except ImportError:
+ return
+ names = [p + n for n in CHAT_COMMANDS for p in ("/", ":")]
+ def complete(text, state):
+ hits = [n + " " for n in names if n.startswith(text)]
+ return hits[state] if state < len(hits) else None
+ readline.set_completer_delims(" \t\n")
+ readline.parse_and_bind("set show-all-if-ambiguous on") # un TAB solo li mostra tutti
+ readline.parse_and_bind("tab: complete")
+ readline.set_completer(complete)
+
+def chat_brio(a, base, model_id, msgs, question, options, w):
+ """Un giro di modalita brio dalla TUI: una richiesta, una distribuzione.
+
+ Il ciclo (fotografia del prefisso, una lettura per opzione, normalizzazione
+ per lunghezza) sta nel gateway, non qui: sono tre cose facili da sbagliare e
+ devono stare in un posto solo. Qui si manda la conversazione come contesto
+ e si disegnano le barre."""
+ import urllib.request, urllib.error
+ body=json.dumps({"model":model_id,"messages":msgs,"question":question,
+ "options":options}).encode()
+ req=urllib.request.Request(base.rstrip("/")+"/v1/brio", data=body,
+ headers={"Content-Type":"application/json"})
+ if a.api_key: req.add_header("Authorization", f"Bearer {a.api_key}")
+ print(f"\n {C.teal}◆ brio{C.r}")
+ sp=Spinner("scoring…"); sp.start(); t0=time.time()
+ try:
+ with urllib.request.urlopen(req) as r:
+ out=json.loads(r.read().decode("utf-8","replace"))
+ except urllib.error.HTTPError as e:
+ sp.stop()
+ try: detail=json.loads(e.read().decode("utf-8","replace")).get("error",{}).get("message","")
+ except Exception: detail=""
+ print(f" {C.yel}[il server ha rifiutato: HTTP {e.code}{' — '+detail if detail else ''}]{C.r}\n")
+ return
+ except OSError as e:
+ sp.stop(); print(f" {C.yel}[server irraggiungibile: {e}]{C.r}\n"); return
+ sp.stop()
+ bars=max(10, min(30, w-34))
+ for choice in out.get("choices", []):
+ p=choice.get("p",0.0); filled=int(round(p*bars))
+ colour=C.grn if choice["option"]==out.get("answer") else C.dgray
+ print(f" {colour}{choice['option'][:22]:<22}{C.r} {colour}{'█'*filled}{C.r}"
+ f"{C.dgray}{'░'*(bars-filled)}{C.r} {p*100:5.1f}%"
+ f" {C.dim}{choice.get('tokens',0)} tok{C.r}")
+ h=out.get("entropy",1.0)
+ # L'entropia e la parte che la generazione non sa dare: non "qual e la
+ # risposta" ma "quanto il modello sa di saperlo".
+ verdict=(f"{C.grn}certo{C.r}" if h<.4 else
+ f"{C.yel}incerto{C.r}" if h<.8 else f"{C.yel}NON SA{C.r}")
+ usage=out.get("usage",{})
+ print(f" {C.b}→ {out.get('answer','?')}{C.r} {C.dim}entropia {h:.3f}{C.r} ({verdict})")
+ print(f" {C.dim}{time.time()-t0:.2f}s · {usage.get('read_tokens',0)} token letti · "
+ f"{usage.get('completion_tokens',0)} generati{C.r}\n")
+
def chat_attached(a, base, model_id):
"""The chat REPL over HTTP against a running `coli serve`.
@@ -1487,8 +1580,11 @@ def chat_attached(a, base, model_id):
OpenAI SSE over localhost, stdlib only."""
import urllib.request, urllib.error
print(f" {C.grn}✦ attached{C.r} {C.dim}to {base} · model {model_id} · the engine stays warm after you quit{C.r}")
- print(f" {C.dim}type and press Enter · Ctrl-C stops the answer · :reset starts a new conversation · :q exits{C.r}\n")
+ print(f" {C.dim}type and press Enter · Ctrl-C stops the answer · :reset starts a new conversation · :q exits{C.r}")
+ print(f" {C.dim}/ per i comandi · TAB completa · /brio mette lo STESSO modello in modalita brio{C.r}\n")
+ install_chat_completer()
msgs=[]
+ brio_options=[] # non vuoto = modalita brio accesa
w=term_w()-4
while True:
if TTY:
@@ -1501,9 +1597,45 @@ def chat_attached(a, base, model_id):
try: msg=input()
except EOFError: break
msg=msg.strip("\r\n")
- if msg in (":q",":quit","exit"): break
+ if msg in (":q","/q","exit"): break
if not msg.strip(): continue
- if msg==":reset": msgs=[]; print(f" {C.dim}✦ new conversation{C.r}\n"); continue
+ # Una riga che comincia con / o : e un COMANDO, giusto o sbagliato che
+ # sia: non finisce mai al modello. Prima un refuso partiva come domanda.
+ name, rest = chat_command(msg)
+ if name is not None and name not in CHAT_COMMANDS:
+ print(f" {C.yel} comando sconosciuto: {msg.split()[0]}{C.r}")
+ chat_commands_help(); continue
+ if name in ("quit",): break
+ if name == "help": chat_commands_help(); continue
+ if name == "reset":
+ msgs=[]; brio_options=[]
+ print(f" {C.dim}✦ new conversation{C.r}\n"); continue
+ # ---- modalita brio -------------------------------------------------
+ # Lo stesso modello con cui stai chattando smette di generare e comincia
+ # a punteggiare: gli si danno le opzioni ammesse e lui dice quanto e
+ # probabile ciascuna. La conversazione fin qui FA da contesto, quindi
+ # /brio a meta chat continua il discorso invece di ricominciarlo.
+ if name == "brio":
+ spec=rest
+ if not spec:
+ if brio_options:
+ brio_options=[]
+ print(f" {C.dim}✦ chat{C.r}\n")
+ else:
+ print(f" {C.yel} /brio vuole le opzioni: /brio merge | request changes | close{C.r}\n")
+ continue
+ brio_options=[o.strip() for o in spec.split("|") if o.strip()]
+ if len(brio_options)<2:
+ brio_options=[]
+ print(f" {C.yel} servono almeno due opzioni, separate da |{C.r}\n")
+ continue
+ print(f" {C.grn}✦ brio{C.r} {C.dim}· {len(brio_options)} opzioni · "
+ f"il modello non genera piu, assegna probabilita · /brio per tornare alla chat{C.r}\n")
+ continue
+ if brio_options:
+ chat_brio(a, base, model_id, msgs, msg, brio_options, w)
+ continue
+ # --------------------------------------------------------------------
payload = message_with_images(msg)
if payload is None: continue # percorso sbagliato: gia' detto
msgs.append({"role":"user","content":payload})
diff --git a/c/colibri.c b/c/colibri.c
index d1779fed..348d4e1a 100644
--- a/c/colibri.c
+++ b/c/colibri.c
@@ -70,6 +70,7 @@
#include "abl.h" /* per-expert causal-ablation harness — inert unless g_abl.mode set (ABLATE_SCORE=<manifest>) */
#include "schema_gbnf.h" /* SCHEMA=: JSON-Schema -> GBNF for method F */
#include "decode_batch.h"
+#include "pin_pool.h" /* piu scatti annidati dello stato */
#include "route_trace.h" /* ROUTE_TRACE + .coli_usage, engine-agnostic (#700) */
#include "kv_fp8.h" /* KV8=1: cache latente in fp8 e4m3 + scala per-riga */
#include "kv_tq.h" /* KV_TQ=3|4: cache latente PolarQuant (rot+polare) */
@@ -8654,7 +8655,17 @@ static void repin_pass_limit(Model *m,int limit){
* append lascia nrec vecchio = file coerente. La riga KV del layer MTP non si salva:
* al resume kv_start=-1 e la finestra di draft riparte da sola. */
-typedef struct { KVState kv; int *hist, len, first; } ServeCtx;
+/* Scatti dello stato (modalita jev, SUBMIT pin=1), PER SLOT. Qui il
+ * riavvolgimento e gia nativo -- le righe KV sono indicizzate per posizione e
+ * lo slot le tiene -- ma mancava il predittore del PRIMO token fresco, che
+ * senza fotografia costringerebbe a rifare tutto il prompt.
+ *
+ * Sono piu di uno perche i prefissi utili sono annidati: le istruzioni,
+ * condivise da mille richieste, e istruzioni+domanda, condivise dalle
+ * alternative di una sola. Con uno scatto solo si e costretti a scegliere, e
+ * l'altro livello lo si ripaga ogni volta. Vedi pin_pool.h. */
+typedef struct { KVState kv; int *hist, len, first;
+ ColiPinPool pins; } ServeCtx;
static double kv_pool_bytes(Model *m, int max_ctx);
static void serve_ctx_init(Model *m, ServeCtx *s, const char *snap, int slot, int maxctx){
@@ -8679,6 +8690,7 @@ static void serve_ctx_free(Model *m, ServeCtx *s){
if(k->Ic) for(int i=0;i<m->c.n_layers;i++) free(k->Ic[i]);
free(k->Lc); free(k->Rc); free(k->Lc8); free(k->Rc8); free(k->Lsc); free(k->Rsc);
free(k->Ic); free(k->kv_start); free(s->hist);
+ coli_pin_pool_clear(&s->pins, NULL); /* questo motore non ha stato ricorrente */
}
typedef struct {
@@ -8768,22 +8780,28 @@ static void mux_echo(Tok *T, unsigned long long id, int pos, int token,
* needs logits at EVERY position, so this path takes no cached-prefix skip
* and no cross-slot KV adoption (KV rows [0,nt) are rewritten in full). */
static float *mux_prefill_echo(Model *m, Tok *T, unsigned long long id,
- const int *ids, int nt, int topk){
+ const int *ids, int nt, int topk,
+ int from, const float *pin_lo){
Cfg *c=&m->c; int D=c->hidden, V=c->vocab;
- float *x=falloc((int64_t)nt*D);
- for(int s=0;s<nt;s++) embed_row(m, ids[s], x+(int64_t)s*D);
- layers_forward(m,x,nt,0);
- if(m->hlast) memcpy(m->hlast, x+(int64_t)(nt-1)*D, D*sizeof(float));
- if(m->has_mtp && nt>=2 && g_draft>0) mtp_absorb(m, ids+1, x, nt-1, 0); /* same as step() */
+ if(from<0 || from>=nt) from=0;
+ int add=nt-from;
+ float *x=falloc((int64_t)add*D);
+ for(int s=0;s<add;s++) embed_row(m, ids[from+s], x+(int64_t)s*D);
+ layers_forward(m,x,add,from);
+ if(m->hlast) memcpy(m->hlast, x+(int64_t)(add-1)*D, D*sizeof(float));
+ if(m->has_mtp && add>=2 && g_draft>0) mtp_absorb(m, ids+from+1, x, add-1, from); /* same as step() */
float *lo=falloc(V), *row=falloc(D);
- mux_echo(T,id,0,ids[0],NULL,V,0);
+ /* La prima posizione emessa non ha un predittore fra le x appena calcolate:
+ * lo porta la fotografia. Senza (from==0, o nessun pin) resta " nan 0",
+ * esattamente come prima. */
+ mux_echo(T,id,from,ids[from], (from>0?pin_lo:NULL), V, (from>0&&pin_lo)?topk:0);
double th0=now_s();
- for(int pos=1; pos<nt; pos++){
- rmsnorm(row, x+(int64_t)(pos-1)*D, m->final_norm, D, c->eps);
+ for(int pos=from+1; pos<nt; pos++){
+ rmsnorm(row, x+(int64_t)(pos-1-from)*D, m->final_norm, D, c->eps);
matmul_qt(lo, row, &m->lm_head, 1);
mux_echo(T,id,pos,ids[pos],lo,V,topk);
}
- rmsnorm(row, x+(int64_t)(nt-1)*D, m->final_norm, D, c->eps);
+ rmsnorm(row, x+(int64_t)(add-1)*D, m->final_norm, D, c->eps);
matmul_qt(lo, row, &m->lm_head, 1);
m->t_head += now_s()-th0;
free(x); free(row);
@@ -9005,8 +9023,38 @@ static int mux_submit(Model *m, Tok *T, ServeCtx *ctx, ServeReq *req, GrDraft *g
* prompt re-prefills from position 0 -- no cached-prefix skip and no
* cross-slot adoption below (either would leave positions with no logits). */
int echo = sub.logprobs>0;
+ /* Il salto del prefisso nell'eco vale quando lo slot PORTA una fotografia,
+ * non quando questa richiesta la richiede: in un menu chiuso la foto la
+ * chiede la passata di riscaldamento e le opzioni che seguono non la
+ * ridichiarano. Legarlo a sub.pin faceva rifare il prompt intero a ogni
+ * opzione -- i numeri restavano giusti e il risparmio spariva, che e' il
+ * modo peggiore di sbagliare.
+ *
+ * Una fotografia esiste solo perche qualcuno l'ha chiesta su QUESTO slot,
+ * e uno slot e' una conversazione: un client OpenAI con echo=true che non
+ * ha mai chiesto niente non ne trova nessuna e rifa tutto da posizione 0,
+ * frame per frame, come prima. */
+ /* Lo scatto piu profondo che sia un prefisso di questo prompt. */
+ int pin_slot = echo ? coli_pin_best(&sc->pins, tmp, nt) : -1;
+ int pin_len = pin_slot >= 0 ? sc->pins.slot[pin_slot].len : 0;
+ const float *pin_lo = pin_slot >= 0 ? sc->pins.slot[pin_slot].logit : NULL;
+ int echo_pin = echo && pin_len > 0 && pin_lo;
int prefix=0;
- if(!echo) while(prefix<sc->len && prefix<nt && sc->hist[prefix]==tmp[prefix]) prefix++;
+ if(!echo || echo_pin) while(prefix<sc->len && prefix<nt && sc->hist[prefix]==tmp[prefix]) prefix++;
+ /* L'eco comincia ESATTAMENTE dove finisce la fotografia, non dove finisce
+ * il prefisso condiviso: i soli logit che abbiamo sono quelli della
+ * posizione fotografata, e sono il predittore del token che viene subito
+ * dopo. Se il prefisso condiviso va piu in la -- due opzioni di un menu
+ * condividono anche lo spazio che le precede, quindi capita sempre -- si
+ * torna indietro alla fotografia e si rifanno quei pochi token: si perde
+ * una posizione di riuso e si guadagna che ogni token dell'opzione ha il
+ * suo logprob. Pretendere che i due numeri combaciassero faceva ricadere
+ * ogni opzione dopo la prima sul ricalcolo completo: numeri giusti,
+ * risparmio zero. */
+ if(echo_pin){
+ if(pin_len>0 && pin_len<=prefix){ prefix=pin_len; coli_pin_touch(&sc->pins,pin_slot); }
+ else prefix=0;
+ }
if(prefix<sc->len){ sc->len=prefix; if(m->has_mtp) m->kv_start[m->c.n_layers]=-1;
kv_disk_truncate(m,sc->len); }
/* Cross-slot prefix adoption (COLI_KV_SHARE=1) — RadixAttention's benefit
@@ -9058,10 +9106,17 @@ static int mux_submit(Model *m, Tok *T, ServeCtx *ctx, ServeReq *req, GrDraft *g
if(add>0) memcpy(sc->hist+sc->len,tmp+sc->len,(size_t)add*sizeof(int));
fprintf(stderr,"[API] KV slot %d prefix %d/%d token, prefill %d\n",sub.slot,sc->len,nt,add);
free(tmp);
- float *logit = echo ? mux_prefill_echo(m,T,sub.id,sc->hist,nt,sub.logprobs)
+ float *logit = echo ? mux_prefill_echo(m,T,sub.id,sc->hist,nt,sub.logprobs,
+ echo_pin?prefix:0,
+ echo_pin?pin_lo:NULL)
: add>0 ? step(m,sc->hist+sc->len,add,sc->len)
: step(m,sc->hist+sc->len-1,1,sc->len-1);
sc->len+=add; sc->first=0;
+ if(sub.pin && logit){
+ coli_pin_pool_init(&sc->pins,m->c.vocab);
+ if(coli_pin_store(&sc->pins,sc->hist,nt,logit))
+ fprintf(stderr,"[PIN] slot %d: scatto a %d token\n",sub.slot,nt);
+ }
ServeReq *r=&req[sub.slot]; memset(r,0,sizeof(*r));
r->id=sub.id; r->maximum=sub.max_tokens; r->temp=sub.temperature; r->top_p=sub.top_p;
r->logprobs=sub.logprobs;
diff --git a/c/decode_batch.h b/c/decode_batch.h
index 80222489..7d1d45a8 100644
--- a/c/decode_batch.h
+++ b/c/decode_batch.h
@@ -27,6 +27,11 @@ static inline uint8_t *coli_kv_row8(uint8_t *base, int position, int width)
typedef struct {
unsigned long long id, bytes, gbytes;
int slot, max_tokens;
+ int pin; /* SUBMIT pin=1: fotografa lo stato dopo il prefill di questa
+ * richiesta, cosi le successive che cominciano con lo stesso
+ * prompt possono riavvolgersi invece di rifarlo. Serve a chi
+ * punteggia un menu chiuso: lo stato condiviso si calcola una
+ * volta e ogni opzione paga solo i propri token. */
float temperature, top_p;
int logprobs; /* requested per-token top-k count; 0 = channel off (opt-in) */
int tok_ids; /* 1 = payload is ASCII token ids, not raw prompt text */
@@ -52,7 +57,7 @@ typedef struct {
* undefined behavior (C11 7.21.6.2), so no sscanf ever touches the value. */
static inline int coli_submit_ext(const char *p, ColiSubmit *s)
{
- int seen = 0, seen_logprobs = 0, seen_ids = 0;
+ int seen = 0, seen_logprobs = 0, seen_ids = 0, seen_pin = 0;
while (*p == ' ' || *p == '\t') p++;
while (*p) {
char key[16];
@@ -77,6 +82,10 @@ static inline int coli_submit_ext(const char *p, ColiSubmit *s)
if (seen_ids || val > 1) return 0;
seen_ids = 1;
s->tok_ids = val;
+ } else if (!strcmp(key, "pin")) { /* fotografa lo stato dopo il prefill */
+ if (seen_pin || val > 1) return 0;
+ seen_pin = 1;
+ s->pin = val;
} else {
return 0; /* unknown key */
}
@@ -101,6 +110,7 @@ static inline int coli_submit_parse(const char *line, ColiSubmit *s)
s->gbytes = 0;
s->logprobs = 0;
s->tok_ids = 0;
+ s->pin = 0;
if (sscanf(line, "SUBMIT %llu %d %llu %d %f %f %llu %c", &s->id, &s->slot,
&s->bytes, &s->max_tokens, &s->temperature, &s->top_p,
&s->gbytes, &tail) == 7) ok = 1;
@@ -124,7 +134,9 @@ static inline int coli_submit_parse(const char *line, ColiSubmit *s)
}
if (!ok) return 0;
return s->id > 0 && s->bytes <= (16u << 20) && s->gbytes <= (1u << 20) &&
- s->slot >= 0 && s->max_tokens >= 1 &&
+ s->slot >= 0 &&
+ /* max_tokens=0: legittimo solo con logprobs>0 (vedi serve_codec.h) */
+ (s->max_tokens >= 1 || (s->max_tokens == 0 && s->logprobs > 0)) &&
isfinite(s->temperature) && isfinite(s->top_p) &&
s->temperature >= 0 && s->temperature <= 2 &&
s->top_p > 0 && s->top_p <= 1;
@@ -160,4 +172,47 @@ static inline int coli_ids_parse(const char *buf, size_t len, int *out,
return n;
}
+/* Coda numerica di un token: " <lp> <k> [tid tlp]*k", in log-softmax sul
+ * vocabolario intero. Vive qui, accanto a COLI_SUBMIT_TOPK_MAX e al parser
+ * delle chiavi, perche e l'altra meta dello stesso canale: chi lo legge e chi
+ * lo scrive devono concordare sul formato, e un formato concordato in due
+ * copie non e concordato. colibri.c ha la propria logprob_tail dal giorno in
+ * cui il canale e nato; questa ne e la versione condivisa per gli altri motori
+ * e produce gli stessi byte.
+ *
+ * lo==NULL, oppure un token fuori dal vocabolario, danno " nan 0": e il caso
+ * della posizione 0 di un echo, dove non c'e nulla su cui condizionare.
+ * Costo: O(V) per la normalizzazione e O(V*k) per la selezione, pagato solo
+ * dalle richieste che hanno chiesto il canale. */
+static inline int coli_logprob_tail(char *dst, size_t cap, const float *lo,
+ int V, int token, int topk)
+{
+ int tk_id[COLI_SUBMIT_TOPK_MAX];
+ float tk_val[COLI_SUBMIT_TOPK_MAX];
+ double se = 0, logZ;
+ float mx;
+ int w, i, k;
+ if (!dst || cap == 0) return 0;
+ if (!lo || token < 0 || token >= V || topk <= 0)
+ return snprintf(dst, cap, " nan 0");
+ if (topk > COLI_SUBMIT_TOPK_MAX) topk = COLI_SUBMIT_TOPK_MAX;
+ if (topk > V) topk = V;
+ mx = lo[0];
+ for (i = 1; i < V; i++) if (lo[i] > mx) mx = lo[i];
+ for (i = 0; i < V; i++) se += exp((double)lo[i] - mx);
+ logZ = (double)mx + log(se);
+ for (k = 0; k < topk; k++) { tk_id[k] = -1; tk_val[k] = -1e30f; }
+ for (i = 0; i < V; i++) {
+ float v = lo[i];
+ int mn = 0;
+ for (k = 1; k < topk; k++) if (tk_val[k] < tk_val[mn]) mn = k;
+ if (v > tk_val[mn]) { tk_val[mn] = v; tk_id[mn] = i; }
+ }
+ w = snprintf(dst, cap, " %.6f %d", (double)lo[token] - logZ, topk);
+ for (k = 0; k < topk && w > 0 && (size_t)w < cap; k++)
+ w += snprintf(dst + w, cap - (size_t)w, " %d %.6f",
+ tk_id[k], (double)tk_val[k] - logZ);
+ return w;
+}
+
#endif
diff --git a/c/deepseek_v41.c b/c/deepseek_v41.c
index f7da5616..e4f31b28 100644
--- a/c/deepseek_v41.c
+++ b/c/deepseek_v41.c
@@ -63,7 +63,8 @@
#include "quant.h"
#include "sparse_attn.h"
#include "omp_tune.h"
-#include "kv_prefix.h" /* riuso del prefisso tra turni (shared) */
+#include "kv_prefix.h"
+#include "pin_pool.h" /* riuso del prefisso tra turni (shared) */
#include <pthread.h> /* ehit_mark publishes the lazy HITS table under a lock */
#if defined(__AVX2__)
#include <immintrin.h>
@@ -2971,18 +2972,46 @@ static int spec_step(Model *m, int token, int start_pos, int main_rows,
return block;
}
-static void forward_full(Model *m, const int *ids, int n, float *logits, int all_logits,
+/* `spec_batch` dice che queste righe sono un lotto di verifica speculativa, e
+ * cambia il calcolo: schedule di pubblicazione per riga e buffer di rollback.
+ * `keep_rows` dice soltanto di TENERE i logit di ogni posizione invece della
+ * sola ultima, e non cambia niente altro. Erano lo stesso parametro, e usarlo
+ * per leggere il prefill faceva prendere a un prefill lo schedule del decode:
+ * righe diverse dell'indice, top-k diverso, numeri plausibili e sbagliati.
+ * Sul fixture minuscolo uscivano NaN, che e come si e visto. */
+static void forward_full(Model *m, const int *ids, int n, float *logits, int spec_batch,
const float *image_rows, int image_at, int image_h, int image_w,
- const uint8_t *image_mask);
+ const uint8_t *image_mask, int keep_rows);
+
+/* Fotografia dello stato e lettura del prefill, per il canale logprobs.
+ *
+ * Qui e piu semplice che su qwen36: questo motore e ad attenzione pura, quindi
+ * non c'e stato ricorrente da salvare. Riavvolgere vuol dire solo dichiarare
+ * che il prefisso tenuto e quello fotografato: le righe KV di quelle posizioni
+ * non sono state toccate da nessuno. Si salvano gli id e il vettore di logit
+ * finale, che e il predittore del primo token fresco. */
+static ColiPinPool g_pins; /* piu scatti annidati, vedi pin_pool.h */
+static const float *g_pin_logit = NULL;
+static int g_pin_use_logit = 0;
+
+static void v41_echo(const char *id, int pos, int token, const float *lo, int V, int k,
+ Tok *tokenizer) {
+ char tail[1024]; coli_logprob_tail(tail, sizeof tail, lo, V, token, k);
+ char piece[512]; int n = tok_decode(tokenizer, &token, 1, piece, (int)sizeof(piece));
+ if (n < 0) n = 0;
+ printf("ECHO %s %d %d%s\n", id, n, pos, tail);
+ if (n > 0) fwrite(piece, 1, (size_t)n, stdout);
+ fputc('\n', stdout); fflush(stdout);
+}
static void forward(Model *m, const int *ids, int n, float *logits) {
- forward_full(m, ids, n, logits, 0, NULL, -1, 0, 0, NULL);
+ forward_full(m, ids, n, logits, 0, NULL, -1, 0, 0, NULL, 0);
}
static void forward_with_image(Model *m, const int *ids, int n, float *logits,
const float *image_rows, int image_at, int image_h, int image_w,
const uint8_t *image_mask) {
- forward_full(m, ids, n, logits, 0, image_rows, image_at, image_h, image_w, image_mask);
+ forward_full(m, ids, n, logits, 0, image_rows, image_at, image_h, image_w, image_mask, 0);
}
/* Several positions past the prompt, with one row of logits each: what a speculative
@@ -2992,12 +3021,12 @@ static void forward_with_image(Model *m, const int *ids, int n, float *logits,
* tokens decoded one at a time, because a draft is only worth anything if accepting it
* is indistinguishable from having generated it. */
static void forward_batch(Model *m, const int *ids, int n, float *logits) {
- forward_full(m, ids, n, logits, 1, NULL, -1, 0, 0, NULL);
+ forward_full(m, ids, n, logits, 1, NULL, -1, 0, 0, NULL, 0);
}
-static void forward_full(Model *m, const int *ids, int n, float *logits, int all_logits,
+static void forward_full(Model *m, const int *ids, int n, float *logits, int spec_batch,
const float *image_rows, int image_at, int image_h, int image_w,
- const uint8_t *image_mask) {
+ const uint8_t *image_mask, int keep_rows) {
Cfg *c = &m->c;
int dim = c->dim, hc = c->hc_mult;
int start_pos = m->pos;
@@ -3009,7 +3038,7 @@ static void forward_full(Model *m, const int *ids, int n, float *logits, int all
m->pub_rows = 0;
/* Only the speculative verify batch is ever rolled back (spec_verify is its
* only caller), and only it may write the per-layer undo buffers. */
- m->rollback_save = all_logits;
+ m->rollback_save = spec_batch;
/* Several positions at once is either the speculative verify batch, which
* needs this per-row schedule because its rows are consecutive decode steps,
* or a prefill, which reads its index owner's keys for the whole chunk. The
@@ -3018,9 +3047,9 @@ static void forward_full(Model *m, const int *ids, int n, float *logits, int all
* resumes mid-sequence is many rows past position 0 and is still a prefill:
* given the decode schedule it reads a different layer's keys than the same
* positions read when they were prefilled cold, and picks a different
- * index top-k. `all_logits` is what actually distinguishes the two --
+ * index top-k. `spec_batch` is what actually distinguishes the two --
* spec_verify is its only caller. */
- if (n > 1 && all_logits) {
+ if (n > 1 && spec_batch) {
m->pub_layer = realloc(m->pub_layer, (size_t)n * sizeof(int));
if (!m->pub_layer) { fprintf(stderr, "OOM sizing the publish schedule\n"); exit(1); }
m->pub_rows = n;
@@ -3168,7 +3197,8 @@ static void forward_full(Model *m, const int *ids, int n, float *logits, int all
}
/* the last block's FFN mix collapses the stream one final time */
- for (int t = all_logits ? 0 : n - 1; t < n; t++) {
+ int rows_out = spec_batch || keep_rows;
+ for (int t = rows_out ? 0 : n - 1; t < n; t++) {
const float *mix = pre_mix + (size_t)t * hc;
for (int i = 0; i < dim; i++) {
float sum = 0.0f;
@@ -3178,9 +3208,9 @@ static void forward_full(Model *m, const int *ids, int n, float *logits, int all
}
if (t == n - 1) trace("final", -1, collapsed, dim);
rms_into(branch_in, collapsed, m->norm.w, dim, c->norm_eps);
- mvb(logits + (size_t)(all_logits ? t : 0) * c->vocab, &m->head, branch_in);
+ mvb(logits + (size_t)(rows_out ? t : 0) * c->vocab, &m->head, branch_in);
}
- trace("logits", -1, logits + (size_t)(all_logits ? n - 1 : 0) * c->vocab, c->vocab);
+ trace("logits", -1, logits + (size_t)(rows_out ? n - 1 : 0) * c->vocab, c->vocab);
m->pos += n;
/* Recorded where the tokens entered the state, and only for the MAIN stream:
@@ -3568,6 +3598,29 @@ static void serve_loop(Model *m, Tok *tokenizer, const char *snap) {
int reuse = 0;
if (n_prompt >= 1 && kv_prefix_on() && !pending_image)
reuse = kv_prefix_reuse(&m->kvp, ids, n_prompt);
+ /* La fotografia si prova sempre: copre anche il caso in cui lo stato
+ * vivo e gia il prompt, dove senza di essa il primo token fresco
+ * resterebbe senza predittore e quindi senza logprob. */
+ g_pin_use_logit = 0; g_pin_logit = NULL;
+ if (n_prompt >= 1 && !pending_image) {
+ /* Il piu profondo degli scatti valido: con due livelli annidati
+ * (istruzioni, istruzioni+domanda) vince il secondo, e se le sue
+ * righe non ci sono piu si ripiega sul primo. */
+ int ps = coli_pin_best(&g_pins, ids, n_prompt);
+ while (ps >= 0) {
+ ColiPin *k = &g_pins.slot[ps];
+ if (kv_prefix_holds(&m->kvp, k->ids, k->len)) {
+ kv_prefix_clear(&m->kvp);
+ kv_prefix_record(&m->kvp, k->ids, 0, k->len);
+ reuse = k->len;
+ g_pin_logit = k->logit; g_pin_use_logit = k->logit != NULL;
+ coli_pin_touch(&g_pins, ps);
+ break;
+ }
+ k->len = 0;
+ ps = coli_pin_best(&g_pins, ids, n_prompt);
+ }
+ }
if (getenv("COLI_PREFIX_LOG")) {
if (reuse)
fprintf(stderr, "[PREFIX] reusing %d of %d prompt tokens (%.0f%%)\n",
@@ -3585,7 +3638,12 @@ static void serve_loop(Model *m, Tok *tokenizer, const char *snap) {
coli_serve_write_error(stdout, command.id, "EMPTY_PROMPT");
coli_serve_command_dispose(&command); continue;
}
- int budget = command.max_tokens > 0 ? command.max_tokens : 256;
+ /* max_tokens=0 con logprobs>0 vuol dire "leggi e fermati": non e un
+ * valore mancante da rimpiazzare con un default, ed e' proprio il caso
+ * in cui un menu chiuso non vuole pagare un passo di decodifica per
+ * opzione. Senza logprobs 0 resta "non specificato" -> 256, come prima. */
+ int budget = command.max_tokens > 0 ? command.max_tokens
+ : (command.logprobs > 0 ? 0 : 256);
if (n_prompt + budget > c->max_positions) {
char message[128];
snprintf(message, sizeof(message), "CONTEXT_EXCEEDED %d %d",
@@ -3626,9 +3684,40 @@ static void serve_loop(Model *m, Tok *tokenizer, const char *snap) {
free(pending_image); pending_image = NULL;
/* `reuse` is the ABSOLUTE position of the first fresh token: every cache
* here is position-indexed, so this has to be the real offset. */
+ int nfresh = n_prompt - reuse;
+ float *all = NULL;
+ int echoed = 0; /* il prefill l'ha gia fatto il ramo della lettura */
+ if (command.logprobs > 0 && nfresh > 0 && !pending_image) {
+ all = (float *)malloc((size_t)nfresh * (size_t)c->vocab * sizeof(float));
+ if (all) {
+ /* un prefill normale (spec_batch=0) che tiene tutte le righe */
+ forward_full(m, ids + reuse, nfresh, all, 0, NULL, -1, 0, 0, NULL, 1);
+ /* La posizione p predice il token p+1; il primo token fresco e
+ * predetto dalla fotografia. Cosi ogni token dell'opzione ha il
+ * suo logprob, anche se non e fra i primi k di nessuna classifica. */
+ if (g_pin_use_logit && g_pin_logit)
+ v41_echo(command.id, reuse, ids[reuse], g_pin_logit, c->vocab,
+ command.logprobs, tokenizer);
+ for (int p = 0; p + 1 < nfresh; p++)
+ v41_echo(command.id, reuse + p + 1, ids[reuse + p + 1],
+ all + (size_t)p * c->vocab, c->vocab, command.logprobs, tokenizer);
+ memcpy(logits, all + (size_t)(nfresh - 1) * c->vocab,
+ (size_t)c->vocab * sizeof(float));
+ free(all);
+ echoed = 1;
+ }
+ }
+ if (!echoed)
forward_with_image(m, ids + reuse, n_prompt - reuse, logits, aligned,
image_at, image_h, image_w, image_mask);
free(aligned); free(image_mask);
+ if (command.pin) {
+ coli_pin_pool_init(&g_pins, c->vocab);
+ if (coli_pin_store(&g_pins, ids, n_prompt, logits)) {
+ fprintf(stderr, "[PIN] scatto a %d token\n", n_prompt);
+ fflush(stderr);
+ }
+ }
uint64_t prefill_bytes = m->expert_bytes - ebytes0;
double prefill_disk = m->t_disk - disk0;
double prefill_expert = m->t_expert - expert0, prefill_wall = now_s() - turn_started;
@@ -3647,7 +3736,15 @@ static void serve_loop(Model *m, Tok *tokenizer, const char *snap) {
for (int i = 0; i < n_eos; i++) if (token == eos_ids[i]) stop = 1;
if (stop) { limited = 0; break; }
int written = tok_decode(tokenizer, &token, 1, piece, (int)sizeof(piece));
- if (written > 0) coli_serve_write_data(stdout, command.id, piece, (size_t)written);
+ if (written > 0) {
+ if (command.logprobs > 0) {
+ /* La distribuzione da cui il token e stato estratto e ancora
+ * quella in `logits`: serve_sample non la modifica. */
+ char lp[1024];
+ coli_logprob_tail(lp, sizeof lp, logits, c->vocab, token, command.logprobs);
+ coli_serve_write_data_lp(stdout, command.id, piece, (size_t)written, lp);
+ } else coli_serve_write_data(stdout, command.id, piece, (size_t)written);
+ }
emitted++;
/* #1332: look at stdin once per token so a client that walked away stops
* paying for a turn nobody wants. A CANCEL aborts, a STOP ends it through
@@ -3689,7 +3786,13 @@ static void serve_loop(Model *m, Tok *tokenizer, const char *snap) {
for (int k = 0; k < n_eos; k++) if (drafted_token == eos_ids[k]) drafted_stop = 1;
if (drafted_stop) { limited = 0; done_early = 1; break; }
written = tok_decode(tokenizer, &drafted_token, 1, piece, (int)sizeof(piece));
- if (written > 0) coli_serve_write_data(stdout, command.id, piece, (size_t)written);
+ if (written > 0) {
+ if (command.logprobs > 0) {
+ char lp[1024];
+ coli_logprob_tail(lp, sizeof lp, logits, c->vocab, token, command.logprobs);
+ coli_serve_write_data_lp(stdout, command.id, piece, (size_t)written, lp);
+ } else coli_serve_write_data(stdout, command.id, piece, (size_t)written);
+ }
emitted++;
}
}
diff --git a/c/glm53.c b/c/glm53.c
index 64388463..98496070 100644
--- a/c/glm53.c
+++ b/c/glm53.c
@@ -91,6 +91,8 @@ static int g_vk_ready = 0;
#include "compat.h"
#include "serve_poll.h" /* CANCEL a meta' turno (#1332) */
#include "route_trace.h"
+#include "decode_batch.h" /* coli_submit_ext, coli_logprob_tail: canale logprobs */
+#include "pin_pool.h" /* piu scatti annidati dello stato */
#include <time.h>
#ifndef _WIN32
#include <sys/resource.h>
@@ -2462,6 +2464,34 @@ static void model_load(GModel *m, const char *dir) {
* `image_token_id`, quindi qui non c'e' nulla da inserire: si sostituisce la
* riga dell'embedding testuale con quella della torre e le posizioni restano
* quelle che sono. Prompt di solo testo passano vision=NULL, n_vision=0. */
+/* Canale logprobs (modalita jev). La lettura del prefill qui costa quasi
+ * niente: forward_span calcola gia i logit di OGNI posizione e forward_prefill
+ * li butta via tenendo solo l'ultima riga. Basta non buttarli.
+ *
+ * La fotografia invece serve davvero: 34 layer su 68 sono KDA e portano una
+ * ricorrenza che non si riavvolge, ed e esattamente quello che dice il
+ * commento degli slot piu sotto. Si salvano kda_state e kda_window di ogni
+ * layer KDA; le righe DSA non entrano nella foto perche sono indicizzate per
+ * posizione e restano dove sono finche la sessione vive. */
+static int g_echo_k = 0;
+static unsigned long long g_echo_id = 0;
+static Tok *g_echo_tok = NULL;
+static int g_echo_base = 0; /* posizione assoluta del primo token letto */
+static const float *g_echo_pin_logit = NULL;
+static float *g_echo_prev = NULL; /* ultima riga di logit del pezzo precedente: il
+ * prefill va a pezzi, e chi predice il primo token
+ * di un pezzo sta in quello prima */
+
+static void glm_echo(unsigned long long id, int pos, int token,
+ const float *lo, int V, int k){
+ char tail[1024]; coli_logprob_tail(tail, sizeof tail, lo, V, token, k);
+ char piece[512]; int n = g_echo_tok ? tok_decode(g_echo_tok, &token, 1, piece, (int)sizeof piece) : 0;
+ if(n<0) n=0;
+ printf("ECHO %llu %d %d%s\n", id, n, pos, tail);
+ if(n>0) fwrite(piece,1,(size_t)n,stdout);
+ putchar('\n'); fflush(stdout);
+}
+
static float *forward_span(GModel *m, GSession *s, const int *tokens, int n,
const float *vision, int n_vision) {
const Cfg *c = &m->c;
@@ -2584,6 +2614,24 @@ static float *forward_prefill(GModel *m, GSession *s, const int *tokens, int n,
(size_t)here * c->vocab * sizeof(float));
free(part);
} else {
+ /* La posizione p predice il token p+1: il predittore del token in
+ * `at+i` sta in `at+i-1`, che e la riga i-1 di questo pezzo, o
+ * l'ultima del pezzo prima, o la fotografia per il primissimo. */
+ if (g_echo_k > 0 && g_echo_id) {
+ for (int i = 0; i < here; i++) {
+ const float *pred;
+ if (at + i == 0) pred = g_echo_pin_logit;
+ else if (i == 0) pred = g_echo_prev;
+ else pred = part + (size_t)(i - 1) * c->vocab;
+ glm_echo(g_echo_id, g_echo_base + at + i, tokens[at + i],
+ pred, c->vocab, pred ? g_echo_k : 0);
+ }
+ if (!g_echo_prev)
+ g_echo_prev = malloc((size_t)c->vocab * sizeof(float));
+ if (g_echo_prev)
+ memcpy(g_echo_prev, part + (size_t)(here - 1) * c->vocab,
+ (size_t)c->vocab * sizeof(float));
+ }
free(last);
last = part;
if (here > 1) {
@@ -2743,8 +2791,19 @@ typedef struct {
GSession *session;
int *tokens; /* la sequenza che lo slot tiene */
int n, cap;
+ /* Scatti dello stato (SUBMIT pin=1): la ricorrenza KDA, gli id e i logit
+ * finali. Piu di uno perche i prefissi utili sono annidati: le istruzioni
+ * condivise da mille richieste e istruzioni+domanda condivise dalle
+ * alternative di una sola (pin_pool.h). La sessione ci sta dentro per
+ * identita: se lo slot ne ha aperta un'altra, le righe DSA di quelle
+ * posizioni non esistono piu e gli scatti non valgono niente. */
+ ColiPinPool pins;
+ GSession *pin_session;
} KVSlot;
+/* la ricorrenza KDA di uno scatto: stato e finestra di ogni strato lineare */
+typedef struct { float **state, **window; int n_layers; } Glm53PinState;
+
static KVSlot g_slots[GLM53_MAX_SLOTS];
static int g_n_slots = 0;
static int g_slot_context = 0;
@@ -2762,7 +2821,93 @@ static void slots_init(const GModel *m) {
(void)m;
}
+/* Uno scatto muore con la sessione che descrive. */
+static void glm53_pin_state_free(void *v) {
+ Glm53PinState *st = (Glm53PinState *)v;
+ if (!st) return;
+ for (int i = 0; i < st->n_layers; i++) {
+ if (st->state) free(st->state[i]);
+ if (st->window) free(st->window[i]);
+ }
+ free(st->state); free(st->window); free(st);
+}
+
+static void slot_pin_drop(const GModel *m, KVSlot *slot) {
+ (void)m;
+ coli_pin_pool_clear(&slot->pins, glm53_pin_state_free);
+ slot->pin_session = NULL;
+}
+
+static int slot_pin_save(const GModel *m, KVSlot *slot, const int *tokens, int n,
+ const float *logit) {
+ const Cfg *c = &m->c;
+ if (!slot->session || n < 1 || !logit) return 0;
+ /* Sessione nuova: gli scatti vecchi parlano di righe DSA che non esistono
+ * piu, e rimetterli risponderebbe da posizioni inventate, in silenzio. */
+ if (slot->pin_session != slot->session) slot_pin_drop(m, slot);
+ coli_pin_pool_init(&slot->pins, c->vocab);
+ ColiPin *k = coli_pin_store(&slot->pins, tokens, n, logit);
+ if (!k) return 0;
+ const size_t ns = (size_t)c->kda_heads * c->kda_hd * c->kda_hd;
+ const size_t nw = (size_t)3 * c->kda_proj * c->conv_k;
+ Glm53PinState *st = (Glm53PinState *)k->state;
+ if (st && st->n_layers != c->n_layers) { glm53_pin_state_free(st); st = NULL; }
+ if (!st) {
+ st = (Glm53PinState *)calloc(1, sizeof(*st));
+ if (!st) { k->len = 0; return 0; }
+ st->n_layers = c->n_layers;
+ st->state = (float **)calloc((size_t)c->n_layers, sizeof(float *));
+ st->window = (float **)calloc((size_t)c->n_layers, sizeof(float *));
+ if (!st->state || !st->window) { glm53_pin_state_free(st); k->len = 0; return 0; }
+ for (int i = 0; i < c->n_layers; i++) {
+ if (c->is_full[i] || !slot->session->layer[i].kda_state) continue;
+ st->state[i] = (float *)malloc(ns * sizeof(float));
+ st->window[i] = (float *)malloc(nw * sizeof(float));
+ if (!st->state[i] || !st->window[i]) { glm53_pin_state_free(st); k->len = 0; return 0; }
+ }
+ }
+ for (int i = 0; i < c->n_layers; i++) {
+ GLayerState *ls = &slot->session->layer[i];
+ if (c->is_full[i] || !ls->kda_state || !st->state[i]) continue;
+ memcpy(st->state[i], ls->kda_state, ns * sizeof(float));
+ memcpy(st->window[i], ls->kda_window, nw * sizeof(float));
+ }
+ k->state = st;
+ slot->pin_session = slot->session;
+ return 1;
+}
+
+/* Rimette lo scatto piu profondo che sia un prefisso stretto di questo prompt,
+ * se la sessione che l'ha prodotto e ancora quella dello slot. Torna quante
+ * posizioni sono gia' fatte, 0 se non si applica. */
+static int slot_pin_restore(const GModel *m, KVSlot *slot, const int *tokens, int n) {
+ const Cfg *c = &m->c;
+ if (!slot->session || slot->pin_session != slot->session) return 0;
+ const size_t ns = (size_t)c->kda_heads * c->kda_hd * c->kda_hd;
+ const size_t nw = (size_t)3 * c->kda_proj * c->conv_k;
+ int s = coli_pin_best(&slot->pins, tokens, n);
+ while (s >= 0) {
+ ColiPin *k = &slot->pins.slot[s];
+ Glm53PinState *st = (Glm53PinState *)k->state;
+ if (st && k->len <= slot->session->filled) {
+ for (int i = 0; i < c->n_layers; i++) {
+ GLayerState *ls = &slot->session->layer[i];
+ if (c->is_full[i] || !ls->kda_state || !st->state[i]) continue;
+ memcpy(ls->kda_state, st->state[i], ns * sizeof(float));
+ memcpy(ls->kda_window, st->window[i], nw * sizeof(float));
+ }
+ slot->session->filled = k->len;
+ coli_pin_touch(&slot->pins, s);
+ return k->len;
+ }
+ k->len = 0; /* lo scatto pretende posizioni che non ci sono */
+ s = coli_pin_best(&slot->pins, tokens, n);
+ }
+ return 0;
+}
+
static void slot_reset(const GModel *m, KVSlot *slot) {
+ slot_pin_drop(m, slot);
if (slot->session) session_close(m, slot->session);
slot->session = NULL;
slot->n = 0;
@@ -2813,6 +2958,7 @@ typedef struct {
float temp, top_p;
char *payload;
int plen;
+ int logprobs, pin; /* SUBMIT logprobs=k / pin=1 */
} ServeReq;
static int g_stop[16], g_nstop = 0;
@@ -2859,6 +3005,16 @@ static void serve_data(unsigned long long id, const char *text, int n) {
fflush(stdout);
}
+/* Come serve_data ma con la coda numerica del canale logprobs. Si usa solo se
+ * la richiesta l'ha chiesto: senza, il frame e quello di sempre. */
+static void serve_data_lp(unsigned long long id, const char *text, int n,
+ const char *tail) {
+ printf("DATA %llu %d%s\n", id, n, tail ? tail : "");
+ if (n > 0) fwrite(text, 1, (size_t)n, stdout);
+ putchar('\n');
+ fflush(stdout);
+}
+
/* Una richiesta intera, o 0 su EOF. Il payload si legge a byte contati, non a
* righe: puo' contenerne. */
static int serve_read_req(ServeReq *q, char *verb, size_t verb_size) {
@@ -2893,11 +3049,28 @@ static int serve_read_req(ServeReq *q, char *verb, size_t verb_size) {
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) {
+ int header_used = 0;
+ if (sscanf(header, "SUBMIT %llu %d %d %d %f %f%n", &q->id, &q->slot, &q->plen,
+ &q->max_tokens, &q->temp, &q->top_p, &header_used) != 6) {
strcpy(verb, "BAD_FRAME");
return 1;
}
+ /* Chiavi facoltative dopo i sei campi posizionali (logprobs=k, pin=1): le
+ * legge lo stesso parser degli altri motori, cosi la modalita jev si
+ * chiede allo stesso modo ovunque. Una richiesta che non ne porta resta
+ * identica a prima, byte per byte. */
+ q->logprobs = 0; q->pin = 0;
+ {
+ const char *rest = header + header_used;
+ while (*rest == ' ') rest++;
+ if (*rest && *rest != '\n') {
+ char tailbuf[256];
+ snprintf(tailbuf, sizeof tailbuf, "%s", rest);
+ for (char *w = tailbuf; *w; w++) if (*w == '\n' || *w == '\r') { *w = 0; break; }
+ ColiSubmit ext; memset(&ext, 0, sizeof ext);
+ if (coli_submit_ext(tailbuf, &ext)) { q->logprobs = ext.logprobs; q->pin = ext.pin; }
+ }
+ }
if (q->plen < 0 || q->plen > (1 << 24)) { strcpy(verb, "BAD_FRAME"); return 1; }
q->payload = malloc((size_t)q->plen + 1);
if (!q->payload) { strcpy(verb, "BAD_FRAME"); return 1; }
@@ -2909,6 +3082,18 @@ static int serve_read_req(ServeReq *q, char *verb, size_t verb_size) {
q->payload[q->plen] = 0;
int trailing = fgetc(stdin);
(void)trailing; /* il '\n' di chiusura del frame */
+ /* max_tokens=0 vale solo in modalita jev ("leggi e fermati"), e lo si sa
+ * solo dopo aver letto le chiavi. Il rifiuto sta DOPO che payload e '\n'
+ * sono stati consumati: rifiutare prima lascerebbe i byte del prompt nello
+ * stream e disallineerebbe ogni frame successivo, che e' esattamente il
+ * guaio che il commento di serve_cancel_pending descrive. Questo motore non
+ * passa dal parser condiviso, quindi la regola va ripetuta qui o resta
+ * l'unico ad accettare uno zero che per tutti gli altri e' malformato. */
+ if (q->max_tokens < 1 && !(q->max_tokens == 0 && q->logprobs > 0)) {
+ free(q->payload); q->payload = NULL; q->plen = 0;
+ strcpy(verb, "BAD_FRAME");
+ return 1;
+ }
return 1;
}
@@ -3021,7 +3206,11 @@ static int serve_one(GModel *m, Tok *tokenizer, ServeReq *q) {
const double s_attn = m->t_attn, s_ffn = m->t_ffn, s_disk = m->t_disk, s_head = m->t_head;
const uint64_t s_fw = m->forwards;
int emitted = 0, limited = 0;
- const int budget = q->max_tokens > 0 ? q->max_tokens : 256;
+ /* 0 con logprobs>0 = "leggi e fermati" (modalita jev), non un default da
+ * riempire: e' cosi che un menu chiuso non paga un passo di decodifica per
+ * ogni opzione. Senza logprobs il comportamento e quello di prima. */
+ const int budget = q->max_tokens > 0 ? q->max_tokens
+ : (q->logprobs > 0 ? 0 : 256);
/* Quanto di questo prompt e' gia' nella sessione.
*
@@ -3039,6 +3228,12 @@ static int serve_one(GModel *m, Tok *tokenizer, ServeReq *q) {
int shared = 0;
if (cached > 0 && cached < total && slot_shared(slot, sequence, total) >= cached)
shared = cached;
+ /* La fotografia si prova sempre, non solo quando il riuso in avanti
+ * fallisce: se lo stato vivo e gia il prompt condiviso, il riuso normale
+ * scatterebbe lo stesso ma il primo token fresco resterebbe senza
+ * predittore, e quindi senza logprob, proprio quello che serve. */
+ int pinned = slot_pin_restore(m, slot, sequence, total);
+ if (pinned > 0) shared = pinned;
if (shared <= 0) {
slot_reset(m, slot);
slot->session = session_open(m, room);
@@ -3070,8 +3265,21 @@ static int serve_one(GModel *m, Tok *tokenizer, ServeReq *q) {
}
const int reused = shared;
+ g_echo_k = q->logprobs; g_echo_id = q->logprobs > 0 ? q->id : 0;
+ g_echo_tok = tokenizer; g_echo_base = shared;
+ { /* i logit dello scatto rimesso: predicono il primo token fresco */
+ int ps = coli_pin_best(&slot->pins, sequence, total);
+ g_echo_pin_logit = (pinned > 0 && shared == pinned && ps >= 0)
+ ? slot->pins.slot[ps].logit : NULL;
+ }
float *logits = forward_prefill(m, slot->session, sequence + shared,
total - shared, vision, n_vision, 0);
+ g_echo_k = 0; g_echo_id = 0; /* la lettura riguarda il prefill, non la decodifica */
+ 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++) {
@@ -3091,7 +3299,11 @@ static int serve_one(GModel *m, Tok *tokenizer, ServeReq *q) {
if (!input_eof) ctl = serve_cancel_pending(q->id, &input_eof);
if (ctl != SERVE_CTL_NONE) break;
if (total >= room) { limited = 1; break; }
- int next = sample_token(logits + (size_t)(rows - 1) * m->c.vocab, m->c.vocab);
+ const float *row = logits + (size_t)(rows - 1) * m->c.vocab;
+ int next = sample_token(row, m->c.vocab);
+ char lptail[1024]; lptail[0] = 0;
+ if (q->logprobs > 0)
+ coli_logprob_tail(lptail, sizeof lptail, row, m->c.vocab, next, q->logprobs);
free(logits);
logits = NULL;
if (is_stop(next)) break;
@@ -3099,7 +3311,8 @@ static int serve_one(GModel *m, Tok *tokenizer, ServeReq *q) {
emitted++;
char piece[512];
int written = tok_decode(tokenizer, &next, 1, piece, sizeof(piece) - 1);
- serve_data(q->id, piece, written);
+ if (q->logprobs > 0) serve_data_lp(q->id, piece, written, lptail);
+ else serve_data(q->id, piece, written);
if (step + 1 == budget) { limited = 1; break; }
logits = forward_span(m, session, &next, 1, NULL, 0);
rows = 1;
diff --git a/c/inkling.c b/c/inkling.c
index 7d74b97e..d4ce20a7 100644
--- a/c/inkling.c
+++ b/c/inkling.c
@@ -40,7 +40,8 @@
#endif
#include "omp_tune.h"
#include "route_trace.h"
-#include "kv_prefix.h" /* KV prefix reuse (shared) */ /* shared routing telemetry (#700) */
+#include "kv_prefix.h"
+#include "pin_pool.h" /* KV prefix reuse (shared) */ /* shared routing telemetry (#700) */
#include "serve_codec.h"
#ifdef COLI_SEGMENT_ADAPTER
#include "segment_runtime.h"
@@ -1847,6 +1848,88 @@ static void inkling_layers_forward_range(Model *m, float *x, int S, int pos0,
* non-NULL also writes the per-position argmax (teacher-forcing check).
* dmel: u8 [naud, mel_bins] frames consumed left-to-right by the <|audio|>
* placeholder positions in ids (prefill only; decode steps pass NULL). */
+/* Canale logprobs: coda numerica per token, lettura del prefill, fotografia
+ * dello stato. Attenzione: questo motore NON e ad attenzione pura. Oltre alle
+ * righe K/V, che sono indicizzate per posizione e quindi si riavvolgono da
+ * sole, porta quattro stati di convoluzione corta per strato (cs[0..3], gli
+ * ingressi grezzi degli ultimi conv_k-1 passi). Quelli non si riavvolgono: se
+ * non li si fotografa, l'opzione successiva parte con la coda dell'opzione
+ * precedente dentro la convoluzione e i logprob sono sbagliati in modo
+ * silenzioso. Sono piccoli (tre passi per canale), quindi la fotografia costa
+ * poco. */
+static int g_echo_k = 0;
+static const char *g_echo_id = NULL;
+static ColiPinPool g_pins; /* piu scatti annidati, vedi pin_pool.h */
+static const float *g_pin_logit = NULL;
+static int g_pin_use_logit = 0;
+static Tok *g_echo_tok = NULL;
+
+/* Lo stato che questo motore deve fotografare oltre alle righe K/V: i quattro
+ * banchi di convoluzione corta per strato. Piccoli (conv_k-1 passi per canale)
+ * ma indispensabili: senza, l'alternativa successiva parte con la coda della
+ * precedente dentro la convoluzione. */
+typedef struct { float **cs[4]; int n_layers; } InkPinState;
+
+static void ink_echo(const char *id, int pos, int token, const float *lo, int V, int k){
+ char tail[1024]; coli_logprob_tail(tail, sizeof tail, lo, V, token, k);
+ char piece[512]; int n = g_echo_tok ? tok_decode(g_echo_tok, &token, 1, piece, (int)sizeof piece) : 0;
+ if (n < 0) n = 0;
+ printf("ECHO %s %d %d%s\n", id, n, pos, tail);
+ if (n > 0) fwrite(piece, 1, (size_t)n, stdout);
+ fputc('\n', stdout); fflush(stdout);
+}
+
+/* larghezza in float di uno stato di convoluzione, per strato e per banco */
+static int64_t ink_cs_cells(Cfg *c, int bank, int layer){
+ int kvdim = L_KV(c,layer) * L_HD(c,layer);
+ int C = (bank < 2) ? kvdim : c->hidden;
+ return (int64_t)C * (c->conv_k - 1);
+}
+
+static void ink_pin_state_free(void *v){
+ InkPinState *st = (InkPinState *)v;
+ if (!st) return;
+ for (int j = 0; j < 4; j++){
+ if (!st->cs[j]) continue;
+ for (int i = 0; i < st->n_layers; i++) free(st->cs[j][i]);
+ free(st->cs[j]);
+ }
+ free(st);
+}
+
+static InkPinState *ink_pin_state_save(Model *m, InkPinState *reuse){
+ Cfg *c = &m->c;
+ InkPinState *st = reuse;
+ if (st && st->n_layers != c->n_layers) { ink_pin_state_free(st); st = NULL; }
+ if (!st){
+ st = (InkPinState *)calloc(1, sizeof(*st));
+ if (!st) return NULL;
+ st->n_layers = c->n_layers;
+ for (int j = 0; j < 4; j++){
+ st->cs[j] = (float**)calloc((size_t)c->n_layers, sizeof(float*));
+ if (!st->cs[j]){ ink_pin_state_free(st); return NULL; }
+ for (int i = 0; i < c->n_layers; i++){
+ st->cs[j][i] = (float*)malloc((size_t)ink_cs_cells(c,j,i) * sizeof(float));
+ if (!st->cs[j][i]){ ink_pin_state_free(st); return NULL; }
+ }
+ }
+ }
+ for (int j = 0; j < 4; j++)
+ for (int i = 0; i < c->n_layers; i++)
+ memcpy(st->cs[j][i], m->cs[j][i],
+ (size_t)ink_cs_cells(c,j,i) * sizeof(float));
+ return st;
+}
+
+static void ink_pin_state_restore(Model *m, const InkPinState *st){
+ Cfg *c = &m->c;
+ if (!st) return;
+ for (int j = 0; j < 4; j++)
+ for (int i = 0; i < c->n_layers; i++)
+ memcpy(m->cs[j][i], st->cs[j][i],
+ (size_t)ink_cs_cells(c,j,i) * sizeof(float));
+}
+
static float *step_mm(Model *m, const int *ids, int S, int pos0, int *tf_out,
const uint8_t *dmel, int naud) {
Cfg *c = &m->c; int D = c->hidden;
@@ -1872,6 +1955,19 @@ static float *step_mm(Model *m, const int *ids, int S, int pos0, int *tf_out,
if (dmel && naud > 0) kv_prefix_taint(&m->kvp);
float *last = falloc(D);
float *logit = falloc(c->unpad_vocab);
+ /* Lettura del prefill: un passaggio di lm_head per posizione, pagato solo
+ * da chi ha chiesto il canale. La posizione p predice il token p+1; il
+ * primo token fresco e predetto dalla fotografia. */
+ if (g_echo_k > 0 && g_echo_id && S > 0) {
+ if (g_pin_use_logit && g_pin_logit)
+ ink_echo(g_echo_id, pos0, ids[0], g_pin_logit, c->unpad_vocab, g_echo_k);
+ for (int p = 0; p + 1 < S; p++) {
+ rmsnorm_row(last, x + (int64_t)p*D, m->final_norm, D, c->eps);
+ for (int d = 0; d < D; d++) last[d] /= c->mup;
+ matmul_w(logit, last, m->lm_head, 1, D, c->unpad_vocab);
+ ink_echo(g_echo_id, pos0 + p + 1, ids[p+1], logit, c->unpad_vocab, g_echo_k);
+ }
+ }
if (tf_out) {
for (int s = 0; s < S; s++) {
rmsnorm_row(last, x + (int64_t)s*D, m->final_norm, D, c->eps);
@@ -2118,7 +2214,8 @@ static const char *prompt_reject(int np, int want) {
}
typedef struct { char id[64]; int max_tok; float temp, top_p; char *payload; int plen;
- uint8_t *audio; int alen; } SReq; /* raw DMel bytes after the payload */
+ uint8_t *audio; int alen;
+ int logprobs, pin; } SReq; /* raw DMel bytes after the payload; SUBMIT logprobs=k / pin=1 */
#define SRV_QMAX 16
static SReq g_q[SRV_QMAX]; static int g_qn = 0;
static const ColiServeWireProfile inkling_wire = {
@@ -2186,6 +2283,7 @@ static int serve_read_cmd(FILE *input, FILE *output, const char *cur_id) {
SReq *q = &g_q[g_qn++];
snprintf(q->id, sizeof(q->id), "%s", command.id);
q->max_tok=command.max_tokens; q->temp=command.temperature;
+ q->logprobs=command.logprobs; q->pin=command.pin;
q->top_p=command.top_p; q->plen=(int)command.payload_bytes;
q->alen=(int)command.extension_bytes;
q->audio=coli_serve_command_extension(&command);
@@ -2258,6 +2356,32 @@ static int serve_one(Model *m, Tok *T, SReq *q) {
* brings its own audio must not match a text-only state either. */
if (naud > 0) kv_prefix_taint(&m->kvp);
int reuse = kv_prefix_reuse(&m->kvp, ids, np);
+ /* La fotografia si prova sempre, non solo quando il riuso vivo fallisce:
+ * altrimenti la prima opzione trova ancora lo stato del prompt, passa dal
+ * riuso normale e il suo primo token resta senza predittore. */
+ g_pin_use_logit = 0; g_pin_logit = NULL;
+ if (naud == 0) {
+ /* Il piu profondo degli scatti valido per questo prompt. Uno scatto le
+ * cui righe K/V non ci sono piu si butta e si riprova col precedente,
+ * invece di rinunciare e rifare tutto da zero. */
+ int s = coli_pin_best(&g_pins, ids, np);
+ while (s >= 0) {
+ ColiPin *k = &g_pins.slot[s];
+ if (kv_prefix_holds(&m->kvp, k->ids, k->len)) {
+ ink_pin_state_restore(m, (const InkPinState *)k->state);
+ kv_prefix_clear(&m->kvp);
+ kv_prefix_record(&m->kvp, k->ids, 0, k->len);
+ m->kv_len = k->len;
+ reuse = k->len;
+ g_pin_logit = k->logit; g_pin_use_logit = k->logit != NULL;
+ coli_pin_touch(&g_pins, s);
+ break;
+ }
+ k->len = 0;
+ s = coli_pin_best(&g_pins, ids, np);
+ }
+ }
+ g_echo_k = q->logprobs; g_echo_id = q->id; g_echo_tok = T;
if (getenv("INK_PREFIX_LOG")) {
/* Report the decision either way, with the reason when it is no. "It
* did not get faster" is otherwise indistinguishable from "reuse is not
@@ -2280,6 +2404,17 @@ static int serve_one(Model *m, Tok *T, SReq *q) {
/* `reuse` is the ABSOLUTE position of the first fresh token: attention and
* the KV slots are position-indexed, so this has to be the real offset. */
float *logit = step_mm(m, ids + reuse, np - reuse, reuse, NULL, q->audio, naud);
+ if (q->pin && logit && naud == 0) {
+ coli_pin_pool_init(&g_pins, c->unpad_vocab);
+ ColiPin *k = coli_pin_store(&g_pins, ids, np, logit);
+ if (k) {
+ InkPinState *st = ink_pin_state_save(m, (InkPinState *)k->state);
+ if (st) { k->state = st; fprintf(stderr, "[PIN] scatto a %d token\n", np); }
+ else { k->len = 0; } /* senza stato lo scatto e' una bugia */
+ fflush(stderr);
+ }
+ }
+ g_echo_k = 0; g_echo_id = NULL; /* la lettura riguarda il prefill, non la decodifica */
int forwards = 1; /* il prefill e' il primo forward */
int len = np, gen = 0, limited = 1, cancelled = 0;
char buf[512];
@@ -2290,12 +2425,15 @@ static int serve_one(Model *m, Tok *T, SReq *q) {
for (int s = 0; s < q->max_tok && !cancelled; s++) {
apply_rep_penalty(logit, c->unpad_vocab, hist, nhist, rep);
int tk = sample_logits(logit, c->unpad_vocab, q->temp, q->top_p);
+ char lptail[1024]; lptail[0] = 0;
+ if (q->logprobs > 0) coli_logprob_tail(lptail, sizeof lptail, logit, c->unpad_vocab, tk, q->logprobs);
free(logit); logit = NULL;
if (tk == c->eos) { limited = 0; break; }
if (nhist < 128) hist[nhist++] = tk;
else { memmove(hist, hist+1, 127*sizeof(int)); hist[127] = tk; }
int nb = tok_decode(T, &tk, 1, buf, sizeof(buf)-1);
- coli_serve_write_data(stdout,q->id,buf,(size_t)nb);
+ if (q->logprobs > 0) coli_serve_write_data_lp(stdout,q->id,buf,(size_t)nb,lptail);
+ else coli_serve_write_data(stdout,q->id,buf,(size_t)nb);
gen++; len++;
while (stdin_readable()) {
int r = serve_read_cmd(stdin, stdout, q->id);
diff --git a/c/kimi_k3.c b/c/kimi_k3.c
index 34ba89ef..4013ff26 100644
--- a/c/kimi_k3.c
+++ b/c/kimi_k3.c
@@ -114,6 +114,7 @@
#include "omp_tune.h"
#include "route_trace.h"
#include "kv_prefix.h"
+#include "pin_pool.h" /* coli_pin_slots_wanted: quanti scatti tenere */
#include "hybrid_split.h" /* KV prefix reuse (shared) */
#include "serve_codec.h"
#ifdef COLI_SEGMENT_ADAPTER
@@ -2185,6 +2186,30 @@ static int k3_layers_forward_range(Model *m, float *hidden, float *bres,
return cancelled&&*cancelled?-1:0;
}
+/* Canale logprobs (modalita jev). Anche qui la fotografia dello stato c'e
+ * gia: si chiama K3Ckpt e salva kstate piu le tre finestre di convoluzione di
+ * ogni strato KDA. Mancava la lettura del prefill e, alla fotografia, i logit
+ * finali: senza quelli il primo token fresco di ogni opzione resta senza
+ * predittore.
+ *
+ * Il prefill qui va a blocchi (K3_CHUNK), quindi la posizione che predice il
+ * primo token di un blocco sta nel blocco PRECEDENTE. Il riporto tiene quella
+ * riga di logit fra un blocco e l'altro; all'inizio lo riempie la fotografia. */
+static int g_echo_k = 0;
+static const char *g_echo_id = NULL;
+static Tok *g_echo_tok = NULL;
+static float *g_echo_carry = NULL; /* logit dell'ultima posizione gia fatta */
+static int g_echo_carry_ok = 0;
+
+static void k3_echo(const char *id, int pos, int token, const float *lo, int V, int k){
+ char tail[1024]; coli_logprob_tail(tail, sizeof tail, lo, V, token, k);
+ char piece[512]; int n = g_echo_tok ? tok_decode(g_echo_tok, &token, 1, piece, (int)sizeof piece) : 0;
+ if(n<0) n=0;
+ printf("ECHO %s %d %d%s\n", id, n, pos, tail);
+ if(n>0) fwrite(piece,1,(size_t)n,stdout);
+ fputc('\n', stdout); fflush(stdout);
+}
+
static float *step_chunk_ex(Model *m, const int *ids, int pos0, int C,
K3CancelPoll poll_cancel, void *cancel_context,
int *cancelled){
@@ -2220,11 +2245,13 @@ static float *step_chunk_ex(Model *m, const int *ids, int pos0, int C,
float *logits=NULL;
if((!cancelled||!*cancelled)&&m->has_head){
double t0=now_s();
+ int echo_on = g_echo_k>0 && g_echo_id;
for(int t=0;t<C;t++){
/* head only where needed: the chunk's last token (feeds sampling)
* and every position when K3_LOGITS dumps teacher-forced logits;
- * also all positions during Phase 10 validation */
- if(!g_lfp && !g_k3_val_lfp && t<C-1) continue;
+ * also all positions during Phase 10 validation; and every
+ * position when a request asked for the logprobs channel */
+ if(!g_lfp && !g_k3_val_lfp && !echo_on && t<C-1) continue;
res_mix(mix,hidden+(int64_t)t*D,bres+(int64_t)t*nbmax*D,nb,D,m->out_sw,c->eps);
rmsnorm_(mix,mix,m->final_norm,D,c->eps);
if(m->trace) fwrite(mix,sizeof(float),D,m->trace);
@@ -2232,6 +2259,15 @@ static float *step_chunk_ex(Model *m, const int *ids, int pos0, int C,
w_matmul(lo,mix,&m->lm_head,1);
if(g_lfp) fwrite(lo,sizeof(float),(size_t)c->vocab,g_lfp);
if(g_k3_val_lfp) fwrite(lo,sizeof(float),(size_t)c->vocab,g_k3_val_lfp);
+ if(echo_on){
+ if(t==0) k3_echo(g_echo_id,pos0,ids[0],
+ g_echo_carry_ok?g_echo_carry:NULL,c->vocab,g_echo_k);
+ if(t+1<C) k3_echo(g_echo_id,pos0+t+1,ids[t+1],lo,c->vocab,g_echo_k);
+ else if(g_echo_carry){
+ memcpy(g_echo_carry,lo,(size_t)c->vocab*sizeof(float));
+ g_echo_carry_ok=1;
+ }
+ }
if(t==C-1) logits=lo; else free(lo);
}
m->t_head+=now_s()-t0;
@@ -2577,6 +2613,7 @@ typedef struct {
float temp, top_p;
char *payload;
int plen;
+ int logprobs, pin; /* SUBMIT logprobs=k / pin=1 */
} ServeReq;
static const ColiServeWireProfile kimi_wire={
@@ -2654,8 +2691,16 @@ typedef struct {
int pos; /* state covers ids[0..pos-1] */
int *fed; /* own copy of those ids */
float *blob; /* packed kstate + cwq/cwk/cwv of every KDA layer */
+ float *logit; /* logit dell'ultima posizione coperta: predice il primo
+ * token fresco. Allocato solo per le foto chieste con
+ * SUBMIT pin=1, che sono le uniche a cui serve. */
+ int pinned; /* foto chiesta con pin=1: una foto ordinaria non la
+ * sfratta. Senza questo, con un solo slot la foto di
+ * fine risposta cancella quella del prompt e ogni
+ * opzione del menu rifa tutto da capo -- misurato. */
uint64_t used; /* LRU stamp */
} K3Ckpt;
+static const float *g_k3_restored_logit=NULL; /* logit della foto appena rimessa */
static K3Ckpt g_k3_ckpt[K3_CKPT_MAX];
static uint64_t g_k3_ckpt_clock=0;
@@ -2750,7 +2795,7 @@ static int k3_ckpt_slot_full(const K3Ckpt *k){
return g_k3_ckpt_dir ? k->pos>0 : k->blob!=NULL;
}
-static void k3_ckpt_save(Model *m){
+static void k3_ckpt_save(Model *m, const float *logit){
if(g_k3_ckpt_slots<1) return;
int pos=m->kvp.len;
if(pos<1||m->kvp.tainted||!m->kvp.fed) return;
@@ -2758,13 +2803,21 @@ static void k3_ckpt_save(Model *m){
K3Ckpt *k=&g_k3_ckpt[s];
if(k3_ckpt_slot_full(k)&&k->pos==pos&&
!memcmp(k->fed,m->kvp.fed,(size_t)pos*sizeof(int))){
+ if(logit){
+ if(!k->logit) k->logit=(float*)malloc((size_t)m->c.vocab*sizeof(float));
+ if(k->logit) memcpy(k->logit,logit,(size_t)m->c.vocab*sizeof(float));
+ k->pinned=1;
+ }
k->used=++g_k3_ckpt_clock; return; }
}
- int victim=0;
+ int victim=-1;
for(int s=0;s<g_k3_ckpt_slots;s++){
- if(!k3_ckpt_slot_full(&g_k3_ckpt[s])){ victim=s; break; }
- if(g_k3_ckpt[s].used<g_k3_ckpt[victim].used) victim=s;
+ K3Ckpt *cand=&g_k3_ckpt[s];
+ if(!logit&&cand->pinned) continue; /* una foto ordinaria non la tocca */
+ if(!k3_ckpt_slot_full(cand)){ victim=s; break; }
+ if(victim<0||cand->used<g_k3_ckpt[victim].used) victim=s;
}
+ if(victim<0) return; /* tutte chieste: la foto ordinaria si salta */
K3Ckpt *k=&g_k3_ckpt[victim];
if(!g_k3_ckpt_dir&&!k->blob){
k->blob=malloc(k3_ckpt_blob_floats(m)*sizeof(float));
@@ -2777,14 +2830,36 @@ static void k3_ckpt_save(Model *m){
if(g_k3_ckpt_dir){
if(!k3_ckpt_disk_write(m,victim,pos)){ k->pos=0; return; }
} else k3_ckpt_copy(k->blob,m,1);
+ if(logit){
+ if(!k->logit) k->logit=(float*)malloc((size_t)m->c.vocab*sizeof(float));
+ if(k->logit) memcpy(k->logit,logit,(size_t)m->c.vocab*sizeof(float));
+ } else { free(k->logit); k->logit=NULL; }
+ k->pinned = logit ? 1 : 0;
k->pos=pos; k->used=++g_k3_ckpt_clock;
if(getenv("K3_PREFIX_LOG"))
fprintf(stderr,"[K3-CKPT] saved pos=%d slot=%d\n",pos,victim);
}
+/* I logit di una foto che copre ESATTAMENTE `pos` token di questo prompt,
+ * senza rimettere niente. Serve quando il riuso vivo ha gia portato lo stato
+ * dove serve: la foto non va ripristinata, ma i suoi logit restano l'unico
+ * predittore del primo token fresco, e senza quelli la prima posizione
+ * dell'opzione esce senza logprob. */
+static const float *k3_ckpt_logit_at(const int *ids, int pos){
+ if(g_k3_ckpt_slots<1||pos<1) return NULL;
+ for(int s=0;s<g_k3_ckpt_slots;s++){
+ const K3Ckpt *k=&g_k3_ckpt[s];
+ if(!k3_ckpt_slot_full(k)||k->pos!=pos||!k->logit) continue;
+ if(memcmp(k->fed,ids,(size_t)pos*sizeof(int))) continue;
+ return k->logit;
+ }
+ return NULL;
+}
+
/* Deepest valid photo for this prompt; restores it and returns the covered
* positions (the caller prefills only ids[pos..np)), or 0 when none fits. */
static int k3_ckpt_restore_best(Model *m, const int *ids, int np){
+ g_k3_restored_logit=NULL;
if(g_k3_ckpt_slots<1||m->kvp.tainted||!m->kvp.fed) return 0;
int live=0, lim=m->kvp.len<np?m->kvp.len:np;
while(live<lim&&m->kvp.fed[live]==ids[live]) live++;
@@ -2796,12 +2871,19 @@ static int k3_ckpt_restore_best(Model *m, const int *ids, int np){
if(memcmp(k->fed,ids,(size_t)k->pos*sizeof(int))) continue;
if(best<0||k->pos>g_k3_ckpt[best].pos) best=s;
}
- if(best<0) return 0;
+ if(best<0){
+ /* Nessuna foto e servita a questo prompt: se ce n'era una chiesta, ha
+ * smesso di aiutare e si lascia andare, cosi la chat normale ritrova
+ * subito i suoi checkpoint. */
+ for(int s=0;s<g_k3_ckpt_slots;s++) g_k3_ckpt[s].pinned=0;
+ return 0;
+ }
K3Ckpt *k=&g_k3_ckpt[best];
if(g_k3_ckpt_dir){
if(!k3_ckpt_disk_read(m,best,k->pos)){ k->pos=0; return 0; }
} else k3_ckpt_copy(k->blob,m,0);
m->kvp.len=k->pos; /* the record truncates with the state it describes */
+ g_k3_restored_logit=k->logit;
k->used=++g_k3_ckpt_clock;
if(getenv("K3_PREFIX_LOG"))
fprintf(stderr,"[K3-CKPT] restored pos=%d of %d prompt tokens "
@@ -2857,6 +2939,7 @@ static int serve_read_req(FILE *in, FILE *out, ServeReq *q, const char *active){
}
snprintf(q->id,sizeof(q->id),"%s",command.id);
q->max_tok=command.max_tokens; q->temp=command.temperature; q->top_p=command.top_p;
+ q->logprobs=command.logprobs; q->pin=command.pin;
q->payload=(char*)coli_serve_command_take_payload(&command);
q->plen=(int)command.payload_bytes;
coli_serve_command_dispose(&command);
@@ -2893,6 +2976,16 @@ static void serve_data(const char *id, const char *p, int n){
coli_serve_write_data(stdout,id,p,(size_t)n);
}
+/* Coda del canale logprobs sul frame DATA. La riempie il ciclo di decodifica
+ * per il token appena campionato; resta vuota per chi non ha chiesto nulla,
+ * e allora il frame e quello di sempre, byte per byte. */
+static char g_lp_tail[1024];
+static void serve_data_maybe_lp(const char *id, const char *p, int n){
+ if(n<=0) return;
+ if(g_lp_tail[0]) coli_serve_write_data_lp(stdout,id,p,(size_t)n,g_lp_tail);
+ else coli_serve_write_data(stdout,id,p,(size_t)n);
+}
+
static void serve_tool(const char *id, const char *p, int n){
if(n<0) return;
coli_serve_write_tool(stdout,id,p,(size_t)n);
@@ -2983,7 +3076,38 @@ static int serve_one(Model *m, Tok *T, ServeReq *q){
* At least one new token is required, since the state cannot be rewound.
* Either the reused positions are token-identical or nothing is reused;
* the emitted tokens are unchanged in both cases. */
+ /* Una richiesta con pin=1 chiede la fotografia anche quando l'operatore non
+ * ha acceso COLI_K3_CKPT: senza almeno uno slot non c'e dove metterla e
+ * ogni opzione rifarebbe il prompt intero. Se la memoria non basta si
+ * resta senza: e un'ottimizzazione, mai il motivo di un errore. */
+ /* Gli scatti utili sono ANNIDATI: le istruzioni, condivise da mille
+ * richieste, e istruzioni+domanda, condivise dalle alternative di una
+ * sola. Con uno solo se ne perde sempre uno e la domanda viene riletta
+ * una volta per opzione. Questo motore il pool ce l'ha gia' (K3Ckpt tiene
+ * il piu' profondo valido); qui si apre solo con quanti slot, con lo
+ * stesso COLI_PIN_SLOTS degli altri. */
+ if(q->pin && g_k3_ckpt_slots<1){
+ int n=coli_pin_slots_wanted(); if(n<1) n=1;
+ if(n>K3_CKPT_MAX) n=K3_CKPT_MAX;
+ g_k3_ckpt_slots=n;
+ fprintf(stderr,"[PIN] %d scatti dello stato ricorrente accesi su richiesta (%.2f GB)\n",
+ n,k3_ckpt_reserve_gb(m,n));
+ }
int reuse=prepare_request_state(m,ids,np,np+q->max_tok+8);
+ /* Il riporto per il primo token fresco: i logit salvati con la foto che si
+ * e appena rimessa. Senza foto resta spento e la prima posizione esce con
+ * " nan 0", come deve. */
+ g_echo_k=q->logprobs; g_echo_id=q->id; g_echo_tok=T;
+ g_echo_carry_ok=0;
+ if(q->logprobs>0){
+ if(!g_echo_carry) g_echo_carry=(float*)malloc((size_t)m->c.vocab*sizeof(float));
+ const float *pred = g_k3_restored_logit;
+ if(!pred&&reuse>0) pred=k3_ckpt_logit_at(ids,reuse);
+ if(g_echo_carry&&pred&&reuse>0){
+ memcpy(g_echo_carry,pred,(size_t)m->c.vocab*sizeof(float));
+ g_echo_carry_ok=1;
+ }
+ }
if(getenv("K3_PREFIX_LOG")){
/* Report the decision either way, with the state behind a "no".
* "It did not get faster" is otherwise the same observation as
@@ -3019,13 +3143,17 @@ static int serve_one(Model *m, Tok *T, ServeReq *q){
}
/* Turn boundary: the state now covers exactly the prompt. A photo here is
* what an agentic edit of the NEXT request restores from. */
- k3_ckpt_save(m);
+ k3_ckpt_save(m, q->pin ? lo : NULL);
+ if(q->pin) fprintf(stderr,"[PIN] stato fotografato a %d token\n",np);
+ g_echo_k=0; g_echo_id=NULL; /* la lettura riguarda il prefill, non la decodifica */
int gen=0, limited=1, cancelled=0, xsup=0, xopen=0, xtl=0, xtool=0;
char buf[512], xtag[320]; /* tool-call open tags carry attributes: call tool="..." index="..." (#1143) */
double tg=now_s();
int forwards=1; /* the prefill; decode steps are counted where they run */
for(int s=0;s<q->max_tok&&!cancelled;s++){
int tk=sample_tok(lo,m->c.vocab,q->temp,q->top_p);
+ g_lp_tail[0]=0;
+ if(q->logprobs>0) coli_logprob_tail(g_lp_tail,sizeof g_lp_tail,lo,m->c.vocab,tk,q->logprobs);
free(lo); lo=NULL;
int eos=0; for(int i=0;i<m->c.n_eos;i++) if(tk==m->c.eos[i]) eos=1;
int show=!eos;
@@ -3057,7 +3185,7 @@ static int serve_one(Model *m, Tok *T, ServeReq *q){
if(show){
int nb=tok_decode(T,&tk,1,buf,sizeof(buf)-1);
if(xtool) serve_tool(q->id,buf,nb);
- else serve_data(q->id,buf,nb);
+ else serve_data_maybe_lp(q->id,buf,nb);
}
if(!eos) gen++;
while(serve_stdin_readable()){
@@ -3078,7 +3206,7 @@ static int serve_one(Model *m, Tok *T, ServeReq *q){
free(lo); free(ids);
/* End of the reply: the next turn's transcript extends THIS state, and an
* edited retry of this turn restores the prompt-boundary photo above. */
- k3_ckpt_save(m);
+ k3_ckpt_save(m, NULL);
double dt=now_s()-t0, decode=now_s()-tg;
uint64_t hits=m->hits-hit0, misses=m->miss-miss0, total=hits+misses;
ColiServeDone done={gen,decode>0?gen/decode:0.0,
diff --git a/c/kv_prefix.h b/c/kv_prefix.h
index 52667411..5636f160 100644
--- a/c/kv_prefix.h
+++ b/c/kv_prefix.h
@@ -127,4 +127,23 @@ static inline int kv_prefix_reuse(const kv_prefix *p, const int *ids, int n) {
return p->len;
}
+/* Il prefisso fotografato (modalita jev, SUBMIT pin=1) e ancora vivo?
+ *
+ * Una fotografia salva lo stato ricorrente e il vettore di logit finale, ma
+ * NON le righe K/V: quelle restano dove sono, indicizzate per posizione. Fra
+ * un'opzione e l'altra pero i banchi possono essere stati ributtati (prompt
+ * piu lungo -> kv_alloc), e allora quelle righe non descrivono piu niente.
+ *
+ * Confrontare la fotografia con la RICHIESTA non basta: direbbe di si anche
+ * quando le righe sono sparite. Il confronto va fatto con cio che lo stato
+ * dichiara di tenere, perche kv_prefix_alloc azzera len ogni volta che i
+ * banchi vengono buttati e kv_prefix_grow conserva solo le posizioni davvero
+ * copiate. Questo e l'unico controllo che distingue "le righe ci sono ancora"
+ * da "gli id si somigliano". */
+static inline int kv_prefix_holds(const kv_prefix *p, const int *pin, int pin_len) {
+ if (!p || !p->fed || !pin || pin_len <= 0) return 0;
+ if (p->tainted || p->len < pin_len || pin_len > p->cap) return 0;
+ return memcmp(p->fed, pin, (size_t)pin_len * sizeof(int)) == 0;
+}
+
#endif /* KV_PREFIX_H */
diff --git a/c/olmoe.c b/c/olmoe.c
index 0270f0de..be107b82 100644
--- a/c/olmoe.c
+++ b/c/olmoe.c
@@ -38,7 +38,8 @@
#endif
#include "omp_tune.h"
#include "route_trace.h" /* shared routing telemetry (#700) */
-#include "kv_prefix.h" /* riuso del prefisso tra turni (shared) */
+#include "kv_prefix.h"
+#include "pin_pool.h" /* piu scatti annidati */ /* riuso del prefisso tra turni (shared) */
#include "serve_codec.h"
#ifdef COLI_SEGMENT_ADAPTER
#include "segment_runtime.h"
@@ -992,6 +993,27 @@ static void layers_forward_range(Model *m, float *x, int S, int pos_base,
free(nrm); free(tmp);
}
+/* Canale logprobs: coda numerica per token, lettura del prefill, fotografia
+ * dello stato. Questo motore e ad attenzione pura, quindi riavvolgere vuol
+ * dire solo dichiarare che il prefisso tenuto e quello fotografato: le righe
+ * KV di quelle posizioni non le ha toccate nessuno. Si salvano gli id e il
+ * vettore di logit finale, che e il predittore del primo token fresco. */
+static int g_echo_k = 0;
+static const char *g_echo_id = NULL;
+static ColiPinPool g_pins; /* piu scatti annidati, vedi pin_pool.h */
+static const float *g_pin_logit = NULL; /* logit dello scatto rimesso, se c'e */
+static int g_pin_use_logit = 0;
+static Tok *g_echo_tok = NULL;
+
+static void olmoe_echo(const char *id, int pos, int token, const float *lo, int V, int k){
+ char tail[1024]; coli_logprob_tail(tail, sizeof tail, lo, V, token, k);
+ char piece[512]; int n = g_echo_tok ? tok_decode(g_echo_tok, &token, 1, piece, (int)sizeof piece) : 0;
+ if (n < 0) n = 0;
+ printf("ECHO %s %d %d%s\n", id, n, pos, tail);
+ if (n > 0) fwrite(piece, 1, (size_t)n, stdout);
+ fputc('\n', stdout); fflush(stdout);
+}
+
static float *step(Model *m, const int *ids, int S, int pos_base) {
Cfg *c = &m->c; int D = c->hidden;
if (g_pilot && m->token_count > 0) {
@@ -1018,6 +1040,21 @@ static float *step(Model *m, const int *ids, int S, int pos_base) {
* the ids those positions were built from, and that invariant is the
* whole safety argument for reusing them next turn. */
kv_prefix_record(&m->kvp, ids, pos_base, S);
+ /* Lettura del prefill: un passaggio di lm_head per posizione, pagato solo
+ * da chi ha chiesto il canale. La posizione p predice il token p+1; il
+ * primo token fresco e predetto dalla fotografia. Cosi ogni token di
+ * un'opzione ha il suo logprob, anche fuori dai primi k. */
+ if (g_echo_k > 0 && g_echo_id && S > 0) {
+ float *erow = falloc(D), *elog = falloc(c->vocab);
+ if (g_pin_use_logit && g_pin_logit)
+ olmoe_echo(g_echo_id, pos_base, ids[0], g_pin_logit, c->vocab, g_echo_k);
+ for (int p = 0; p + 1 < S; p++) {
+ rmsnorm_row(erow, x + (int64_t)p*D, m->final_norm, D, c->eps);
+ matmul(elog, erow, m->lm_head, 1, D, c->vocab);
+ olmoe_echo(g_echo_id, pos_base + p + 1, ids[p+1], elog, c->vocab, g_echo_k);
+ }
+ free(erow); free(elog);
+ }
float *last = falloc(D);
rmsnorm_row(last, x + (int64_t)(S-1)*D, m->final_norm, D, c->eps);
float *logit = falloc(c->vocab);
@@ -1404,7 +1441,8 @@ static void run_chat(Model *m, Tok *T, int ctx_cap) {
* never touched, the same invariant CHAT mode's /reset already relies on
* (it clears hist_len, not the K/V buffers themselves). */
-typedef struct { char id[64]; int max_tok; float temp, top_p; char *payload; int plen; } SReq;
+typedef struct { char id[64]; int max_tok; float temp, top_p; char *payload; int plen;
+ int logprobs, pin; } SReq; /* SUBMIT logprobs=k / pin=1 */
#define SRV_QMAX 16
static SReq g_q[SRV_QMAX]; static int g_qn = 0;
static const ColiServeWireProfile olmoe_wire = {
@@ -1441,6 +1479,8 @@ static int serve_read_cmd(FILE *in, FILE *out, const char *cur_id) {
SReq *q = &g_q[g_qn++];
snprintf(q->id, sizeof(q->id), "%s", command.id);
q->max_tok = command.max_tokens;
+ q->logprobs = command.logprobs;
+ q->pin = command.pin;
q->temp = command.temperature;
q->top_p = command.top_p;
q->payload = (char *)coli_serve_command_take_payload(&command);
@@ -1504,6 +1544,31 @@ static int serve_one(Model *m, Tok *T, SReq *q, int ctx_cap) {
* kv_prefix_record only ever grows the length, so the stale tail would
* claim coverage the cache no longer has. */
int reuse = kv_prefix_off() ? 0 : kv_prefix_reuse(&m->kvp, ids, np);
+ /* La fotografia si prova sempre, non solo quando il riuso vivo fallisce:
+ * altrimenti la prima opzione trova ancora lo stato del prompt, passa dal
+ * riuso normale e il suo primo token resta senza predittore. */
+ g_pin_use_logit = 0; g_pin_logit = NULL;
+ {
+ /* Il piu profondo degli scatti che sia un prefisso di questo prompt.
+ * Con due livelli (istruzioni, istruzioni+domanda) e il secondo a
+ * decidere; se e' morto si ripiega sul primo invece di rifare tutto. */
+ int s = coli_pin_best(&g_pins, ids, np);
+ while (s >= 0) {
+ ColiPin *k = &g_pins.slot[s];
+ if (kv_prefix_holds(&m->kvp, k->ids, k->len)) {
+ kv_prefix_clear(&m->kvp);
+ kv_prefix_record(&m->kvp, k->ids, 0, k->len);
+ m->kv_len = k->len;
+ reuse = k->len;
+ g_pin_logit = k->logit; g_pin_use_logit = k->logit != NULL;
+ coli_pin_touch(&g_pins, s);
+ break;
+ }
+ k->len = 0; /* le righe non ci sono piu: scatto orfano */
+ s = coli_pin_best(&g_pins, ids, np);
+ }
+ }
+ g_echo_k = q->logprobs; g_echo_id = q->id; g_echo_tok = T;
if (!reuse) kv_prefix_clear(&m->kvp);
if (getenv("COLI_PREFIX_LOG")) {
if (reuse)
@@ -1525,12 +1590,22 @@ static int serve_one(Model *m, Tok *T, SReq *q, int ctx_cap) {
float *logit = step(m, ids + reuse, np - reuse, reuse);
int hist_len = np, gen = 0, limited = 1, cancelled = 0;
char buf[512];
+ if (q->pin && logit) {
+ coli_pin_pool_init(&g_pins, c->vocab);
+ if (coli_pin_store(&g_pins, ids, np, logit)) {
+ fprintf(stderr, "[PIN] scatto a %d token\n", np); fflush(stderr);
+ }
+ }
+ g_echo_k = 0; g_echo_id = NULL; /* la lettura riguarda il prefill, non la decodifica */
for (int s = 0; s < q->max_tok && !cancelled; s++) {
int nt = pick_tok(logit, c->vocab, -1);
+ char lptail[1024]; lptail[0] = 0;
+ if (q->logprobs > 0) coli_logprob_tail(lptail, sizeof lptail, logit, c->vocab, nt, q->logprobs);
free(logit); logit = NULL;
if (is_stop(nt)) { limited = 0; break; }
int nb = tok_decode(T, &nt, 1, buf, sizeof(buf)-1);
- coli_serve_write_data(stdout, q->id, buf, (size_t)nb);
+ if (q->logprobs > 0) coli_serve_write_data_lp(stdout, q->id, buf, (size_t)nb, lptail);
+ else coli_serve_write_data(stdout, q->id, buf, (size_t)nb);
gen++; hist_len++;
while (coli_stdin_readable()) {
int r = serve_read_cmd(stdin, stdout, q->id);
diff --git a/c/openai_server.py b/c/openai_server.py
index 9f385390..252c453b 100644
--- a/c/openai_server.py
+++ b/c/openai_server.py
@@ -3088,16 +3088,28 @@ class Engine:
elif kind == "ECHO" and len(fields) >= 6:
# U7a prefill read-out: "ECHO <id> <n> <pos> <lp> <k>
# [tid tlp]*k" plus a DATA-framed payload (n bytes + LF).
- # Emitted only for opted-in requests; no current request
- # path opts in, so the frame is read (to keep the stream
- # in sync) and dropped -- U7b delivers it to the response
- # assembly when it wires the opt-in.
+ # Emitted only for opted-in requests. Questo e' U7b: il
+ # frame non si butta piu', va alla coda della richiesta che
+ # l'ha chiesto. Chi non ha chiesto logprobs non ne riceve
+ # nessuno, quindi il percorso della chat non cambia.
size = int(fields[2])
if not 0 <= size <= 65536:
raise RuntimeError("invalid engine DATA size")
- self._read_exact(size)
+ piece = self._read_exact(size)
if self._read_exact(1) != b"\n":
raise RuntimeError("invalid engine DATA terminator")
+ request_id = fields[1]
+ lp = fields[4]
+ with self.pending_lock:
+ events = self.pending.get(request_id)
+ if events is not None:
+ events.put(("echo", {
+ "pos": int(fields[3]),
+ # " nan 0" = niente su cui condizionare: la prima
+ # posizione assoluta non ha un predittore.
+ "logprob": None if lp in ("nan", "-nan") else float(lp),
+ "text": piece.decode("utf-8", "replace"),
+ }))
elif kind == "ACCEPT" and len(fields) >= 3:
# #597: the engine validated the submission (fits context) before prefill.
# Keep it pending — DATA/DONE still follow — and let generate() commit the
@@ -3160,7 +3172,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, image=None):
+ on_tool=None, image=None, logprobs=0, pin=False, on_echo=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")
@@ -3217,9 +3229,18 @@ class Engine:
default=0)
if cut > 0:
prefix_field = f" {len(xpayload)} {len(prompt[:cut].encode('utf-8'))}"
+ # Chiavi di estensione (decode_batch.h): logprobs=k accende la lettura
+ # del prefill, pin=1 fotografa lo stato a fine prompt. Una richiesta
+ # che non le manda produce un header identico a prima, byte per byte.
+ ext = ""
+ if logprobs:
+ ext += f" logprobs={int(logprobs)}"
+ if pin:
+ ext += " pin=1"
header = (f"SUBMIT {request_id} {cache_slot} {len(payload)} {max_tokens} "
f"{temperature:.8g} {top_p:.8g}"
+ (prefix_field if prefix_field else (f" {len(xpayload)}" if xpayload else ""))
+ + ext
+ "\n").encode()
try:
with self.write_lock:
@@ -3301,6 +3322,13 @@ class Engine:
with self.write_lock:
self.process.stdin.write(f"CANCEL {request_id}\n".encode())
self.process.stdin.flush()
+ elif kind == "echo":
+ # Lettura del prefill: arriva PRIMA di ogni DATA e non e' testo
+ # generato, quindi non passa da decode() e non entra nella
+ # risposta. La consuma chi ha chiesto il canale.
+ _accept({"prompt_tokens": None})
+ if on_echo is not None:
+ on_echo(value)
elif kind == "tool":
_accept({"prompt_tokens": None})
if not cancel_sent and not stop_sent:
@@ -3839,6 +3867,8 @@ class APIHandler(BaseHTTPRequestHandler):
self.chat_completion(body, request_id)
elif path == "/v1/completions":
self.completion(body, request_id)
+ elif path == "/v1/brio":
+ self.brio(body, request_id)
elif path == "/v1/messages":
self.anthropic_messages(body, request_id)
else:
@@ -3857,6 +3887,155 @@ class APIHandler(BaseHTTPRequestHandler):
except OSError:
pass
+
+ # ---------------------------------------------------------------- modalita brio
+ #
+ # Il modello non genera: si legge il logprob di ogni opzione ammessa e si
+ # normalizza sulle sole opzioni. Torna una distribuzione, non una stringa.
+ #
+ # PERCHE' IL CICLO STA QUI E NON NEL CLIENT. Servono tre cose facili da
+ # sbagliare: fotografare il prefisso condiviso (pin) cosi ogni opzione paga
+ # solo i propri token; NON mettere l'elenco delle opzioni nel prompt (su
+ # qwen36 erano 48 token su 123, meta del risparmio); e normalizzare per
+ # lunghezza, perche' sommare i logprob penalizza le opzioni da piu token --
+ # misurato, la somma diceva "merge" dove la generazione greedy dello stesso
+ # modello diceva "request changes". Un client che rifacesse questo ciclo
+ # sbaglierebbe una di queste tre, e il risultato resterebbe plausibile.
+ #
+ # COSA TORNA. Non solo il vincitore: la probabilita di OGNI opzione e
+ # l'entropia. E' la differenza con la generazione, che una risposta la da
+ # sempre e con la stessa faccia: qui "non lo so" e' un numero.
+ def brio(self, body, request_id):
+ options = body.get("options")
+ if not isinstance(options, list) or not options:
+ raise APIError(400, "`options` must be a non-empty array of strings.", "options")
+ if len(options) > 64:
+ raise APIError(400, "`options` accepts at most 64 entries.", "options")
+ seen = set()
+ for option in options:
+ if not isinstance(option, str) or not option.strip():
+ raise APIError(400, "Every option must be a non-empty string.", "options")
+ if option in seen:
+ raise APIError(400, f"Duplicate option: {option!r}.", "options")
+ seen.add(option)
+ question = body.get("question")
+ if question is not None and not isinstance(question, str):
+ raise APIError(400, "`question` must be a string.", "question")
+ state = body.get("state")
+ messages = body.get("messages")
+ if state is not None and not isinstance(state, str):
+ raise APIError(400, "`state` must be a string.", "state")
+ if state is None and isinstance(messages, list):
+ # La conversazione in corso FA da stato: e' quello che la TUI manda
+ # quando si scrive /brio a meta chat.
+ parts = []
+ for message in messages:
+ if not isinstance(message, dict):
+ raise APIError(400, "Every message must be an object.", "messages")
+ content = message.get("content")
+ if isinstance(content, list):
+ content = "".join(piece.get("text", "") for piece in content
+ if isinstance(piece, dict))
+ if content:
+ parts.append(f"{message.get('role', 'user')}: {content}")
+ state = "\n".join(parts)
+ if not state and not question:
+ raise APIError(400, "Provide `state`, `messages` or `question`.", "state")
+ normalize = body.get("normalize", "mean")
+ if normalize not in ("mean", "sum"):
+ raise APIError(400, "`normalize` must be \"mean\" or \"sum\".", "normalize")
+ # Lo slot si sceglie dallo STATO, non dalla domanda: mille domande
+ # diverse sullo stesso contesto devono cadere sullo stesso slot, o la
+ # fotografia del prefisso condiviso non le serve a niente. E' la stessa
+ # regola di conversation_cache_slot per la chat, con la chiave presa
+ # dalla parte che non cambia.
+ cache_slot = body.get("cache_slot")
+ if cache_slot is None:
+ cache_slot = conversation_cache_slot(
+ [{"role": "system", "content": state or ""}], self.server.kv_slots)
+ if isinstance(cache_slot, bool) or not isinstance(cache_slot, int) \
+ or not 0 <= cache_slot < self.server.kv_slots:
+ raise APIError(400, "Invalid cache slot.", "cache_slot")
+
+ prefix = ""
+ if state:
+ prefix += f"Context:\n{state}\n\n"
+ if question:
+ prefix += f"Question: {question}\n"
+ prefix += "Answer:"
+
+ started = time.time()
+ with self.server.scheduler.admit(self.client_disconnected, cache_slot) as admission:
+ queue_wait, cache_slot = admission
+
+ def score(text, pin):
+ """Un giro sul motore: niente generazione, solo la lettura.
+
+ max_tokens=0 vale solo con logprobs>0 e vuol dire "leggi il
+ prompt e fermati". Chiedere un token costerebbe un passo di
+ decodifica completo per opzione, buttato via."""
+ echoes = []
+ accepted = {}
+
+ def on_accept(value):
+ accepted.update(value)
+
+ self.server.engine.generate(
+ text, 0, 0.0, 1.0, lambda _chunk: None, cache_slot,
+ self.client_disconnected, logprobs=1, pin=pin,
+ on_echo=echoes.append, on_accept=on_accept)
+ return accepted.get("prompt_tokens"), echoes
+
+ # 1) il prefisso condiviso, fotografato una volta
+ n_prefix, echoes = score(prefix, True)
+ if n_prefix is None: # motore senza ACCEPT (olmoe)
+ n_prefix = max((e["pos"] for e in echoes), default=-1) + 1
+
+ # 2) un giro per opzione: paga solo i propri token
+ scored = []
+ for option in options:
+ # Il cliente se n'e andato: smettere subito invece di macinare
+ # le opzioni restanti per nessuno. Con una sola slot KV un menu
+ # lungo abbandonato la terrebbe occupata per minuti, e le
+ # richieste dietro andrebbero in coda fino al timeout -- e'
+ # cosi che sono usciti i primi 429.
+ if self.client_disconnected():
+ raise ClientCancelled()
+ _, tail = score(prefix + " " + option, False)
+ rows = [e for e in tail if e["pos"] >= n_prefix and e["logprob"] is not None]
+ total = sum(e["logprob"] for e in rows)
+ count = max(len(rows), 1)
+ scored.append({"option": option, "logprob": total, "tokens": len(rows),
+ "mean_logprob": total / count})
+
+ if not any(entry["tokens"] for entry in scored):
+ raise APIError(502, "The engine returned no log probabilities for the options.",
+ None, "engine_error", "server_error")
+ key = "mean_logprob" if normalize == "mean" else "logprob"
+ top = max(entry[key] for entry in scored)
+ weights = [math.exp(entry[key] - top) for entry in scored]
+ total_weight = sum(weights) or 1.0
+ for entry, weight in zip(scored, weights):
+ entry["p"] = weight / total_weight
+ scored.sort(key=lambda entry: -entry["p"])
+ entropy = -sum(e["p"] * math.log(max(e["p"], 1e-12)) for e in scored)
+ entropy /= math.log(max(len(scored), 2))
+
+ self.send_json(200, {
+ "id": "brio-" + uuid.uuid4().hex,
+ "object": "brio.choice",
+ "created": int(time.time()),
+ "model": self.server.model_id,
+ "answer": scored[0]["option"],
+ "entropy": round(entropy, 6),
+ "normalize": normalize,
+ "choices": scored,
+ "usage": {"prompt_tokens": n_prefix, "completion_tokens": 0,
+ "read_tokens": sum(e["tokens"] for e in scored),
+ "total_tokens": n_prefix + sum(e["tokens"] for e in scored)},
+ }, request_id, {"x-colibri-queue-wait-ms": str(round(queue_wait * 1000)),
+ "x-colibri-elapsed-ms": str(round((time.time() - started) * 1000))})
+
def _fail(self, error, request_id):
"""Report an error, unless the response is already on the wire. Once a streaming 200
is committed, a second status line would be framed as SSE body -- clients saw a whole
diff --git a/c/pin_pool.h b/c/pin_pool.h
new file mode 100644
index 00000000..3f6efb48
--- /dev/null
+++ b/c/pin_pool.h
@@ -0,0 +1,147 @@
+/* pin_pool.h — piu fotografie dello stato, non una sola.
+ *
+ * IL PROBLEMA. Una fotografia sola (SUBMIT pin=1) copre UN prefisso. Chi
+ * punteggia un insieme chiuso ne ha due annidati: le istruzioni, condivise da
+ * mille richieste, e istruzioni+domanda, condivise dalle alternative di quella
+ * richiesta. Con una sola si e' costretti a scegliere: o si tengono le
+ * istruzioni e ogni alternativa fa rileggere la domanda da capo, o si tiene la
+ * domanda e le istruzioni si rileggono a ogni item.
+ *
+ * Misurato su qwen36 (22 GB), 4 item, istruzioni da 121 token, 3 opzioni:
+ * con una fotografia sola jev macina 124 token per item invece di 46, cioe'
+ * tre volte la domanda, e passa da 126,6 s a item contro i 60,1 della
+ * generazione. Non e' un limite del metodo, e' questo pezzo che manca.
+ *
+ * LA FORMA. Un pugno di scatti; si rimette SEMPRE il piu' profondo che sia un
+ * prefisso stretto del prompt nuovo. Nessuna chiave nuova sul filo: il client
+ * manda pin=1 dove gli serve un punto di ritorno, e il motore li tiene tutti
+ * finche' c'e' posto. kimi_k3.c fa gia' cosi' con i suoi checkpoint (di li'
+ * viene l'idea di tenere il piu' profondo valido); qui la parte che non
+ * dipende dal motore sta in un posto solo.
+ *
+ * COSA C'E' DENTRO E COSA NO. Qui stanno gli id, i logit finali e la
+ * contabilita' degli slot. Lo stato ricorrente NO: e' diverso in ogni motore
+ * (DeltaNet, SSM, KDA, convoluzioni corte) e alcuni non ne hanno affatto. Ogni
+ * motore se lo attacca a `state` e se lo copia da se'.
+ *
+ * QUELLO CHE QUESTO FILE NON PUO' SAPERE. Che le righe K/V di quelle posizioni
+ * siano ancora vive. Non entrano nella fotografia, restano dove sono, e i
+ * banchi possono essere stati ributtati nel frattempo. Chi rimette uno scatto
+ * DEVE chiederlo a kv_prefix_holds() prima di fidarsi. */
+#ifndef COLI_PIN_POOL_H
+#define COLI_PIN_POOL_H
+
+#include <stdlib.h>
+#include <string.h>
+
+#ifndef COLI_PIN_SLOTS_MAX
+#define COLI_PIN_SLOTS_MAX 8
+#endif
+
+typedef struct {
+ int *ids; /* copia propria degli id che lo scatto copre */
+ int len; /* quante posizioni */
+ int cap; /* capienza di ids */
+ float *logit; /* logit dell'ultima posizione coperta: predice il primo token fresco */
+ void *state; /* blob del motore (stato ricorrente), opaco qui */
+ unsigned long long used; /* marca LRU */
+} ColiPin;
+
+typedef struct {
+ ColiPin slot[COLI_PIN_SLOTS_MAX];
+ int n; /* slot in uso, 0 = spento */
+ int vocab;
+ unsigned long long clock;
+} ColiPinPool;
+
+/* Quanti scatti tenere. Default 4: bastano istruzioni + domanda con margine.
+ * Su un motore con stato ricorrente grosso ogni scatto costa (qwen36: decine
+ * di MB), quindi si puo' abbassare senza toccare il codice. */
+static inline int coli_pin_slots_wanted(void) {
+ const char *e = getenv("COLI_PIN_SLOTS");
+ int n = e ? atoi(e) : 4;
+ if (n < 0) n = 0;
+ if (n > COLI_PIN_SLOTS_MAX) n = COLI_PIN_SLOTS_MAX;
+ return n;
+}
+
+static inline void coli_pin_pool_init(ColiPinPool *p, int vocab) {
+ if (!p || p->n) return;
+ memset(p, 0, sizeof(*p));
+ p->n = coli_pin_slots_wanted();
+ p->vocab = vocab;
+}
+
+/* Lo scatto piu' profondo che sia un prefisso STRETTO di questo prompt.
+ *
+ * Stretto perche' serve almeno un token nuovo: un prompt uguale allo scatto
+ * vorrebbe dire riavvolgere fino a se stesso e non lascerebbe niente da
+ * macinare, quindi nessun logit da cui ripartire. Torna l'indice o -1. */
+static inline int coli_pin_best(const ColiPinPool *p, const int *ids, int n) {
+ if (!p || !ids || n < 1) return -1;
+ int best = -1;
+ for (int s = 0; s < p->n; s++) {
+ const ColiPin *k = &p->slot[s];
+ if (k->len < 1 || !k->ids || k->len >= n) continue;
+ if (memcmp(k->ids, ids, (size_t)k->len * sizeof(int)) != 0) continue;
+ if (best < 0 || k->len > p->slot[best].len) best = s;
+ }
+ return best;
+}
+
+/* Dove mettere lo scatto nuovo: uno slot libero, oppure lo stesso prefisso se
+ * c'e' gia' (rinfrescarlo, non duplicarlo), oppure il meno usato di recente. */
+static inline int coli_pin_victim(ColiPinPool *p, const int *ids, int n) {
+ if (!p || p->n < 1) return -1;
+ for (int s = 0; s < p->n; s++)
+ if (p->slot[s].len == n && p->slot[s].ids &&
+ memcmp(p->slot[s].ids, ids, (size_t)n * sizeof(int)) == 0) return s;
+ for (int s = 0; s < p->n; s++) if (p->slot[s].len < 1) return s;
+ int lru = 0;
+ for (int s = 1; s < p->n; s++) if (p->slot[s].used < p->slot[lru].used) lru = s;
+ return lru;
+}
+
+/* Scrive id e logit nello slot. Torna lo slot, o NULL se non c'e' memoria: la
+ * fotografia e' un'ottimizzazione e non deve MAI essere il motivo di un
+ * errore, quindi chi chiama tira dritto. `state` non viene toccato: se lo
+ * slot ne portava uno, il chiamante lo riusa o lo libera lui. */
+static inline ColiPin *coli_pin_store(ColiPinPool *p, const int *ids, int n,
+ const float *logit) {
+ if (!p || p->n < 1 || !ids || n < 1) return NULL;
+ int s = coli_pin_victim(p, ids, n);
+ if (s < 0) return NULL;
+ ColiPin *k = &p->slot[s];
+ if (k->cap < n) {
+ int *grown = (int *)realloc(k->ids, (size_t)n * sizeof(int));
+ if (!grown) { k->len = 0; return NULL; }
+ k->ids = grown; k->cap = n;
+ }
+ if (logit && p->vocab > 0) {
+ if (!k->logit) k->logit = (float *)malloc((size_t)p->vocab * sizeof(float));
+ if (!k->logit) { k->len = 0; return NULL; }
+ memcpy(k->logit, logit, (size_t)p->vocab * sizeof(float));
+ }
+ memcpy(k->ids, ids, (size_t)n * sizeof(int));
+ k->len = n;
+ k->used = ++p->clock;
+ return k;
+}
+
+static inline void coli_pin_touch(ColiPinPool *p, int s) {
+ if (p && s >= 0 && s < p->n) p->slot[s].used = ++p->clock;
+}
+
+/* Butta ogni scatto. Si chiama quando lo stato che descrivono non esiste piu'
+ * (banchi K/V riallocati, sessione chiusa): uno scatto orfano rimesso a posto
+ * risponderebbe da posizioni che non ci sono, e lo farebbe in silenzio. */
+static inline void coli_pin_pool_clear(ColiPinPool *p, void (*free_state)(void *)) {
+ if (!p) return;
+ for (int s = 0; s < p->n; s++) {
+ if (free_state && p->slot[s].state) free_state(p->slot[s].state);
+ p->slot[s].state = NULL;
+ p->slot[s].len = 0;
+ }
+}
+
+#endif /* COLI_PIN_POOL_H */
diff --git a/c/qwen36.c b/c/qwen36.c
index 3a4eb071..9657dc9e 100644
--- a/c/qwen36.c
+++ b/c/qwen36.c
@@ -61,7 +61,9 @@ static int qwen36_max_ctx(void) {
#include "cli_args.h"
#include "st.h"
#include "omp_tune.h"
-#include "kv_prefix.h" /* riuso del prefisso tra turni (shared) */
+#include "kv_prefix.h"
+#include "pin_pool.h" /* riuso del prefisso tra turni (shared) */
+#include "decode_batch.h" /* ColiSubmit + coli_submit_ext: le chiavi key=value di SUBMIT */
#include "json.h" /* tokenizer.json parsing (reuse minimal parser) */
#include "qwen36_tier.h" /* optional CUDA VRAM expert tier */
#include "expert_ffn.h" /* routed experts: planar int4 kernel + layer runner */
@@ -2405,6 +2407,42 @@ static void layers_forward_range(Model *m, float *x, int S, int pos_base,
free(nrm); free(tmp);
}
+/* Fotografia dello stato dopo un prefill "pinnato" (SUBMIT pin=1).
+ *
+ * A cosa serve. Punteggiare un menu chiuso significa mandare N volte
+ * "prompt + opzione_i". Il prefisso condiviso e sempre lo stesso, ma
+ * kv_prefix.h e tutto-o-niente: dopo l'opzione 1 lo stato tenuto e
+ * "prompt + opzione_1", che NON e un prefisso di "prompt + opzione_2", e si
+ * ricomincia da capo. Misurato su qwen36: 0,90 s quando il riuso prende,
+ * 40 s quando non prende.
+ *
+ * Perche una fotografia e non il riuso parziale. Tenere il prefisso comune e
+ * ricalcolare dalla divergenza e corretto per l'attenzione, che guarda solo
+ * indietro, ma NON per gli strati ricorrenti: lo stato di una ricorrenza non
+ * si riavvolge a una posizione arbitraria. qwen36 ha 30 layer lineari su 40.
+ * Una fotografia invece funziona ovunque, perche riporta lo stato a un punto
+ * in cui c'e davvero stato.
+ *
+ * Cosa contiene. Le righe KV delle posizioni del prompt non si copiano: non
+ * sono state toccate, basta riportare indietro kv_len. Si copiano lo stato
+ * ricorrente (DN_rec + DN_conv, ~63 MB su questo modello) e il vettore di
+ * logit finale, cosi il predittore del primo token fresco esiste e la lettura
+ * del prefill copre anche quello. */
+static ColiPinPool g_pins; /* piu scatti annidati, vedi pin_pool.h */
+static const float *g_pin_logit = NULL; /* logit dello scatto rimesso */
+static int g_pin_use_logit = 0; /* 1 quando questa richiesta e ripartita dalla fotografia */
+
+/* Lo stato che questo motore deve fotografare oltre alle righe K/V: la
+ * ricorrenza e la finestra di convoluzione di ogni strato DeltaNet. Sono
+ * decine di MB per scatto, quindi COLI_PIN_SLOTS conta davvero qui. */
+typedef struct { float **rec, **conv; int n_layers; } Q36PinState;
+
+/* Stato della lettura del prefill: dichiarato qui perche step() lo consulta e
+ * step() viene prima del codice di servizio che lo accende. */
+static int g_echo_k = 0; /* 0 = spento */
+static const char *g_echo_id = NULL;
+static void serve_echo(const char *id, int pos, int token, const float *lo, int V, int k);
+
static float *step(Model *m, const int *ids, int S, int pos_base) {
Cfg *c = &m->c; int D = c->hidden;
if (m->resident_mode && m->first_step) m->resident_collecting = 1;
@@ -2438,6 +2476,27 @@ static float *step(Model *m, const int *ids, int S, int pos_base) {
m->token_count += S; m->freq_token_count += S;
if (!m->hot_pinned && m->hot_n > 0 && m->freq_token_count >= m->warmup_tokens) pin_hot_experts(m);
m->kv_len = pos_base + S;
+ /* Lettura del prefill: una passata di lm_head per posizione, pagata SOLO
+ * dalle richieste che hanno chiesto il canale. La posizione p predice il
+ * token p+1, quindi si copre l'intero blocco fresco tranne il suo primo
+ * token, il cui predittore sta nello stato precedente. Per questo il
+ * chiamante arretra di uno il riuso del prefisso quando la lettura e
+ * accesa: cosi il primo token dell'opzione ricade sempre qui dentro. */
+ if (g_echo_k > 0 && g_echo_id && S > 0) {
+ float *erow = falloc(D), *elog = falloc(c->vocab);
+ /* Il primo token fresco e predetto dallo stato PRECEDENTE, che dopo un
+ * riavvolgimento e proprio quello fotografato: senza questi logit
+ * l'opzione perderebbe il suo primo token, che spesso e l'unico. */
+ if (g_pin_use_logit && g_pin_logit)
+ serve_echo(g_echo_id, pos_base, ids[0], g_pin_logit, c->vocab, g_echo_k);
+ for (int p = 0; p + 1 < S; p++) {
+ rmsnorm_row(erow, x + (int64_t)p*D, m->final_norm, D, c->eps);
+ if (!qt_lmhead_matmul(elog, erow, D, c->vocab))
+ matmul_d(elog, erow, m->lm_head, 1, D, c->vocab);
+ serve_echo(g_echo_id, pos_base + p + 1, ids[p+1], elog, c->vocab, g_echo_k);
+ }
+ free(erow); free(elog);
+ }
float *last = falloc(D);
rmsnorm_row(last, x + (int64_t)(S-1)*D, m->final_norm, D, c->eps);
float *logit = falloc(c->vocab);
@@ -2572,6 +2631,96 @@ static float *g_last_logit = NULL;
/* Zero the DeltaNet recurrent state so a new request doesn't inherit the
* previous conversation's hidden state. Must be called at the start of every
* generation (the CLI runs once, so this is also correct there). */
+static void q36_pin_state_free(void *v){
+ Q36PinState *st = (Q36PinState *)v;
+ if (!st) return;
+ for (int i = 0; i < st->n_layers; i++){
+ if (st->rec) free(st->rec[i]);
+ if (st->conv) free(st->conv[i]);
+ }
+ free(st->rec); free(st->conv); free(st);
+}
+
+static void pin_drop(void){
+ coli_pin_pool_clear(&g_pins, q36_pin_state_free);
+ g_pin_logit = NULL; g_pin_use_logit = 0;
+}
+
+static Q36PinState *q36_pin_state_save(Model *m, Q36PinState *reuse){
+ Cfg *c = &m->c;
+ size_t nr = (size_t)c->dn_vheads * c->dn_kdim * c->dn_vdim;
+ size_t nc = (size_t)c->dn_conv_dim * (c->dn_convk - 1);
+ Q36PinState *st = reuse;
+ if (st && st->n_layers != c->n_layers) { q36_pin_state_free(st); st = NULL; }
+ if (!st){
+ st = (Q36PinState *)calloc(1, sizeof(*st));
+ if (!st) return NULL;
+ st->n_layers = c->n_layers;
+ st->rec = (float**)calloc((size_t)c->n_layers, sizeof(float*));
+ st->conv = (float**)calloc((size_t)c->n_layers, sizeof(float*));
+ if (!st->rec || !st->conv) { q36_pin_state_free(st); return NULL; }
+ for (int i = 0; i < c->n_layers; i++){
+ if (c->is_attn[i]) continue;
+ st->rec[i] = (float*)malloc(nr * sizeof(float));
+ st->conv[i] = (float*)malloc(nc * sizeof(float));
+ if (!st->rec[i] || !st->conv[i]) { q36_pin_state_free(st); return NULL; }
+ }
+ }
+ for (int i = 0; i < c->n_layers; i++){
+ if (c->is_attn[i]) continue;
+ if (m->DN_rec[i] && st->rec[i]) memcpy(st->rec[i], m->DN_rec[i], nr * sizeof(float));
+ if (m->DN_conv[i] && st->conv[i]) memcpy(st->conv[i], m->DN_conv[i], nc * sizeof(float));
+ }
+ return st;
+}
+
+static void pin_save(Model *m, const int *ids, int n, const float *logit){
+ Cfg *c = &m->c;
+ coli_pin_pool_init(&g_pins, c->vocab);
+ ColiPin *k = coli_pin_store(&g_pins, ids, n, logit);
+ if (!k) return; /* ottimizzazione, mai un errore */
+ Q36PinState *st = q36_pin_state_save(m, (Q36PinState *)k->state);
+ if (!st) { k->len = 0; return; } /* senza stato lo scatto sarebbe una bugia */
+ k->state = st;
+ fprintf(stderr, "[PIN] scatto a %d token\n", n); fflush(stderr);
+}
+
+/* Se la fotografia e un prefisso del nuovo prompt, la si rimette e si riparte
+ * da li. Restituisce quanti token sono gia fatti, 0 se non si applica. */
+static int pin_restore(Model *m, const int *ids, int n){
+ Cfg *c = &m->c;
+ size_t nr = (size_t)c->dn_vheads * c->dn_kdim * c->dn_vdim;
+ size_t nc = (size_t)c->dn_conv_dim * (c->dn_convk - 1);
+ g_pin_logit = NULL;
+ /* Il piu profondo degli scatti che sia un prefisso stretto di questo
+ * prompt. Gli strati di attenzione non stanno nella fotografia: le loro
+ * righe K/V restano dove sono, e se i banchi sono stati ributtati quelle
+ * righe non descrivono piu niente -- solo il registro del prefisso lo sa
+ * (kv_prefix_holds). Uno scatto orfano si butta e si riprova col
+ * precedente, invece di rinunciare e rifare tutto da zero. */
+ int s = coli_pin_best(&g_pins, ids, n);
+ while (s >= 0) {
+ ColiPin *k = &g_pins.slot[s];
+ Q36PinState *st = (Q36PinState *)k->state;
+ if (st && kv_prefix_holds(&m->kvp, k->ids, k->len)) {
+ for (int i = 0; i < c->n_layers; i++){
+ if (c->is_attn[i]) continue;
+ if (m->DN_rec[i] && st->rec[i]) memcpy(m->DN_rec[i], st->rec[i], nr * sizeof(float));
+ if (m->DN_conv[i] && st->conv[i]) memcpy(m->DN_conv[i], st->conv[i], nc * sizeof(float));
+ }
+ m->kv_len = k->len;
+ kv_prefix_clear(&m->kvp);
+ kv_prefix_record(&m->kvp, k->ids, 0, k->len);
+ g_pin_logit = k->logit;
+ coli_pin_touch(&g_pins, s);
+ return k->len;
+ }
+ k->len = 0;
+ s = coli_pin_best(&g_pins, ids, n);
+ }
+ return 0;
+}
+
static void reset_recurrent(Model *m){
Cfg *c = &m->c;
/* Paired with the record on purpose: whoever zeroes the state must also
@@ -2747,7 +2896,10 @@ static int *read_int_array(jval *o, const char *key, int *n_out) {
* session hangs forever (#748). compat.h's coli_serve_binary_mode (#749)
* carries that fix for every engine; see its comment for the full story. */
-typedef struct { char id[64]; int max_tok; float temp, top_p; char *payload; int plen; } ServeReq;
+typedef struct { char id[64]; int max_tok; float temp, top_p; char *payload; int plen;
+ int logprobs; /* SUBMIT logprobs=k: 0 = canale spento (opt-in) */
+ int pin; /* SUBMIT pin=1: fotografa lo stato dopo il prefill */
+ } ServeReq;
static int serve_read_req(ServeReq *q){
char line[512], cmd[16], id[64];
@@ -2757,10 +2909,46 @@ static int serve_read_req(ServeReq *q){
if(strcmp(cmd,"SUBMIT")) return 0;
int slot, plen, max_tok; float temp, top_p;
if(sscanf(line,"%*s %*s %d %d %d %f %f",&slot,&plen,&max_tok,&temp,&top_p)!=5 ||
- plen<0||plen>(1<<24)||max_tok<1){
+ plen<0||plen>(1<<24)||max_tok<0){ /* 0 = modalita jev, vedi sotto */
printf("ERROR %s bad submit header\n",id); fflush(stdout); return 0;
}
(void)slot;
+ /* Le chiavi key=value stanno dopo i campi fissi. Si riusa il parser
+ * condiviso di decode_batch.h invece di scriverne un secondo: e lo stesso
+ * namespace che colibri.c gia accetta, quindi i due motori non divergono.
+ * Un client vecchio non manda nessuna chiave e finisce a logprobs=0. */
+ q->logprobs = 0;
+ q->pin = 0;
+ {
+ /* Stessa tecnica di coli_submit_parse: %n da l'offset dopo i campi
+ * numerici, e la chiave deve essere separata da spazio (altrimenti
+ * "1logprobs=5" sarebbe un campo malformato, non un opt-in). Qui i
+ * campi fissi sono 6 e non 7, perche questo header non ha gbytes. */
+ int base = 0;
+ int sd, sp_, smt; float st, stp;
+ if (sscanf(line, "%*s %*s %d %d %d %f %f%n", &sd, &sp_, &smt, &st, &stp, &base) == 5 &&
+ base > 0 && (line[base] == ' ' || line[base] == '\t')) {
+ /* coli_submit_ext rifiuta qualunque byte non-spazio dopo il valore,
+ * e fgets lascia il '\n' in fondo: va tolto, o "logprobs=5\n" e
+ * un valore con spazzatura attaccata. Si lavora su una copia per
+ * non toccare la riga che il chiamante ha gia parsato. */
+ char ext_buf[256];
+ snprintf(ext_buf, sizeof ext_buf, "%s", line + base);
+ for (char *e = ext_buf; *e; e++) if (*e == '\n' || *e == '\r') { *e = 0; break; }
+ const char *tail = ext_buf;
+ while (*tail == ' ' || *tail == '\t') tail++;
+ if (*tail) {
+ ColiSubmit ext; memset(&ext, 0, sizeof ext);
+ if (coli_submit_ext(ext_buf, &ext)) { q->logprobs = ext.logprobs; q->pin = ext.pin; }
+ else { printf("ERROR %s bad submit extension\n", id); fflush(stdout); return 0; }
+ }
+ }
+ }
+ /* La convalida di max_tok si chiude QUI, non sopra: 0 e legittimo solo in
+ * modalita jev, e se logprobs c'e si sa solo dopo aver letto le chiavi. */
+ if(max_tok < 1 && !(max_tok == 0 && q->logprobs > 0)){
+ printf("ERROR %s bad submit header\n",id); fflush(stdout); return 0;
+ }
char *payload=malloc((size_t)plen+1);
if(!payload){ printf("ERROR %s out of memory\n",id); fflush(stdout); return 0; }
if(fread(payload,1,(size_t)plen,stdin)!=(size_t)plen){ free(payload); return -1; }
@@ -2771,6 +2959,36 @@ static int serve_read_req(ServeReq *q){
return 2;
}
+/* Coda numerica di un token, formato IDENTICO a logprob_tail di colibri.c:
+ * " <lp> <k> [tid tlp]*k", normalizzata in log-softmax sul vocabolario intero.
+ * Due motori che scrivono lo stesso canale devono scrivere lo stesso formato,
+ * altrimenti il client ne ha due da conoscere. lo==NULL da " nan 0". */
+
+/* Un token -> un frame, con la coda numerica. Si usa SOLO quando il client ha
+ * chiesto logprobs=k: quel client punteggia, non mostra testo, quindi il buffer
+ * UTF-8 (che accorpa i byte di piu token in un DATA) qui sarebbe di intralcio.
+ * Senza logprobs il percorso resta quello di prima, byte per byte. */
+static void serve_data_lp(const char *id, const char *p, int n, const char *tail){
+ printf("DATA %s %d%s\n",id,n,tail);
+ if(n>0) fwrite(p,1,(size_t)n,stdout);
+ fputc('\n',stdout); fflush(stdout);
+}
+
+/* Lettura del prefill (canale logprobs, opt-in). I logit alla posizione p
+ * predicono il token p+1, quindi scorrendo le posizioni fresche si ottiene il
+ * logprob di OGNI token del blocco, non solo dei primi k di una classifica:
+ * e cio che serve a punteggiare un'opzione che non e fra le piu probabili, e
+ * a punteggiarne una di piu token sommando i suoi pezzi.
+ * Vive in variabili globali e non nella firma di step() perche step() e la
+ * matematica: il protocollo non deve entrarci. */
+static void serve_echo(const char *id, int pos, int token, const float *lo, int V, int k){
+ char tail[1024]; coli_logprob_tail(tail,sizeof tail,lo,V,token,k);
+ unsigned char b[256]; int n=0; decode_id_to_bytes(token,b,&n);
+ printf("ECHO %s %d %d%s\n",id,n,pos,tail);
+ if(n>0) fwrite(b,1,(size_t)n,stdout);
+ fputc('\n',stdout); fflush(stdout);
+}
+
static void serve_data(const char *id, const char *p, int n){
if(n<=0) return;
printf("DATA %s %d\n",id,n);
@@ -2906,6 +3124,21 @@ static void serve_one(Model *m, ServeReq *q){
(m->kvp.len > 0 && m->kvp.len < np) ? " (diverged)" : "");
fflush(stderr);
}
+ /* Con la lettura accesa il riuso arretra di un token: il predittore del
+ * primo token fresco deve ricadere nel blocco che ricalcoliamo, altrimenti
+ * quel token resta senza logprob ed e proprio quello che al chiamante
+ * serve (il primo token dell'opzione). Costa una posizione. */
+ /* La fotografia si prova SEMPRE, non solo quando il riuso vivo fallisce.
+ * Altrimenti la prima opzione (che trova ancora lo stato del prompt e
+ * quindi passa dal riuso normale) resterebbe senza i logit salvati, e il
+ * suo primo token senza logprob: proprio il token che serve. Rimetterla
+ * quando lo stato e gia quello costa una memcpy, non un prefill. */
+ g_pin_use_logit = 0;
+ {
+ int pinned = pin_restore(m, ids, np);
+ if (pinned) { reuse = pinned; g_pin_use_logit = 1; }
+ }
+ g_echo_k = q->logprobs; g_echo_id = q->id;
if (!reuse) { reset_recurrent(m); m->kv_len = 0; }
/* Per-REQUEST state, not per-process: without this the server keeps the
* first request's prefill flag and expert-collection set forever, so
@@ -2919,19 +3152,28 @@ static void serve_one(Model *m, ServeReq *q){
/* `reuse` is the ABSOLUTE position of the first fresh token: attention and
* the KV rows are position-indexed, so this has to be the real offset. */
float *lo = step(m, ids + reuse, np - reuse, reuse);
+ if (q->pin) pin_save(m, ids, np, lo);
int gen=0, limited=1, forwards=1; /* il prefill e' il primo forward */
const double s_disk=m->t_disk, s_attn=tm_sum(0)+tm_sum(1), s_moe=tm_sum(2), s_head=tm_sum(5);
int eos_ids[4]; int n_eos=serve_eos_ids(eos_ids,4);
double t0=now_s();
unsigned char sbuf[16]; int sbn=0;
+ g_echo_k = 0; g_echo_id = NULL; /* la lettura riguarda il prefill, non la decodifica */
for(int s=0;s<q->max_tok;s++){
int tk = serve_sample(lo, m->c.vocab, q->temp, q->top_p);
+ /* La coda si calcola PRIMA della free: dopo, lo non c'e piu. */
+ char lptail[1024]; lptail[0]=0;
+ if(q->logprobs>0) coli_logprob_tail(lptail,sizeof lptail,lo,m->c.vocab,tk,q->logprobs);
free(lo); lo=NULL;
int is_eos=0; for(int e=0;e<n_eos;e++) if(tk==eos_ids[e]) is_eos=1;
if(is_eos){ limited=0; break; }
unsigned char tmp[256]; int tn=0; decode_id_to_bytes(tk, tmp, &tn);
- unsigned char chunk[256]; int cn=0; utf8_drain(sbuf,&sbn,tmp,tn,chunk,&cn);
- if(cn>0) serve_data(q->id,(char*)chunk,cn);
+ if(q->logprobs>0){
+ serve_data_lp(q->id,(char*)tmp,tn,lptail);
+ } else {
+ unsigned char chunk[256]; int cn=0; utf8_drain(sbuf,&sbn,tmp,tn,chunk,&cn);
+ if(cn>0) serve_data(q->id,(char*)chunk,cn);
+ }
gen++;
/* #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
@@ -2980,7 +3222,13 @@ static void serve_loop(Model *m){
ServeReq q={0}; int r;
do r=serve_read_req(&q); while(r==0);
if(r<0) return;
- if(r==2){ serve_one(m,&q); free(q.payload); }
+ /* La mappa degli esperti va rimandata DOPO ogni richiesta, non solo
+ * dopo READY: all'avvio la cache RAM e vuota, e quella fotografia a
+ * freddo restava l'unica che il cruscotto avesse mai visto -- tutto
+ * grigio, RAM 0, disco tutto, per sempre. hits_emit era gia per
+ * richiesta, ed e per questo che il lampeggio funzionava e il colore
+ * no. kimi_k3.c fa cosi da sempre (serve_emap dopo serve_one). */
+ if(r==2){ serve_one(m,&q); free(q.payload); emap_emit(m); }
}
}
diff --git a/c/qwen38.c b/c/qwen38.c
index e569cb3c..17ffc0b4 100644
--- a/c/qwen38.c
+++ b/c/qwen38.c
@@ -78,6 +78,7 @@ static int qwen38_max_ctx(void) {
#undef matmul_q
#include "route_trace.h" /* shared ROUTE_TRACE + .coli_usage contract */
#include "serve_codec.h" /* shared SUBMIT/STOP/CANCEL framing */
+#include "pin_pool.h" /* piu scatti annidati dello stato */
/* ---------- tokenizer (optional, for human-readable output) ---------- */
static char **g_tok = NULL; /* id -> piece string (strdup'd) */
static int g_tok_n = 0;
@@ -1129,6 +1130,7 @@ typedef struct {
float temp, top_p;
char *payload;
int plen;
+ int logprobs, pin; /* SUBMIT logprobs=k / pin=1 */
} ServeReq;
static const ColiServeWireProfile q38_wire = {
.max_header_bytes = 511,
@@ -1203,6 +1205,7 @@ static int serve_read_req(FILE *in,FILE *out,ServeReq *q,const char *active_id){
q->slot=command.slot;
q->max_tok=command.max_tokens;q->temp=command.temperature;q->top_p=command.top_p;
q->payload=(char*)coli_serve_command_take_payload(&command);q->plen=(int)command.payload_bytes;
+ q->logprobs=command.logprobs;q->pin=command.pin;
coli_serve_command_dispose(&command);return 2;
}
@@ -1212,6 +1215,16 @@ static void serve_data(const char *id, const char *p, int n){
fwrite(p,1,(size_t)n,stdout); fputc('\n',stdout); fflush(stdout);
}
+/* Come serve_data ma con la coda numerica del canale logprobs. Emette anche a
+ * n==0: un token che non chiude un carattere UTF-8 ha comunque il suo logprob,
+ * e perderlo bucherebbe la sequenza proprio dove il conto deve tornare. */
+static void serve_data_lp(const char *id, const char *p, int n, const char *tail){
+ if(n<0) n=0;
+ printf("DATA %s %d%s\n",id,n,tail?tail:"");
+ if(n>0) fwrite(p,1,(size_t)n,stdout);
+ fputc('\n',stdout); fflush(stdout);
+}
+
/* temperature + top-p sampler (ported from kimi_k3.c; vocab ~250k -> qsort O(V log V) per token) */
typedef struct { float p; int id; } SampleProb;
static int sample_prob_desc(const void *a, const void *b){
@@ -1280,6 +1293,12 @@ typedef struct {
int *ids;
int id_cap;
int len;
+ int pinned; /* fotografia chiesta con SUBMIT pin=1: la tengono le
+ * richieste che la estendono, invece di sovrascriverla.
+ * Senza questo la seconda opzione di un menu cancella la
+ * fotografia costruita dalla prima e ogni opzione rifa il
+ * prompt intero: il riuso ci sarebbe ma non scatterebbe
+ * mai. */
float *logits;
float **dn_rec;
float **dn_conv;
@@ -1290,6 +1309,79 @@ typedef struct {
static Q38PrefixCache g_q38_prefix;
+/* La cache automatica sopra resta quella della chat: una sola, riscritta a
+ * ogni prompt. Accanto sta un pool di scatti CHIESTI (SUBMIT pin=1), che non
+ * si sovrascrivono a vicenda: i prefissi utili a un insieme chiuso sono
+ * annidati (istruzioni, istruzioni+domanda) e con uno solo se ne perde sempre
+ * uno. Due meccanismi separati perche' hanno due politiche diverse: uno
+ * insegue l'ultimo prompt, l'altro tiene i punti di ritorno che il client ha
+ * dichiarato. Vedi pin_pool.h. */
+static int q38_prefix_geometry(const Model *m,size_t *rec_cells,
+ size_t *conv_cells,size_t *ple_cells);
+static ColiPinPool g_q38_pins;
+typedef struct { float **rec, **conv, *ple; int64_t ple_hist[2]; int ple_len; int n_layers; } Q38PinState;
+
+static void q38_pin_state_free(void *v){
+ Q38PinState *st = (Q38PinState *)v;
+ if (!st) return;
+ for (int i = 0; i < st->n_layers; i++){
+ if (st->rec) free(st->rec[i]);
+ if (st->conv) free(st->conv[i]);
+ }
+ free(st->rec); free(st->conv); free(st->ple); free(st);
+}
+
+/* Copia la ricorrenza DeltaNet (piu le righe PLE) fra motore e scatto. */
+static int q38_pin_state_copy(Model *m, Q38PinState **slot, int to_state){
+ const Cfg *c = &m->c;
+ size_t rec = 0, conv = 0, ple = 0;
+ if (!q38_prefix_geometry(m, &rec, &conv, &ple)) return 0;
+ Q38PinState *st = *slot;
+ if (st && st->n_layers != c->layers){ q38_pin_state_free(st); st = NULL; }
+ if (!st){
+ if (!to_state) return 0;
+ st = (Q38PinState *)calloc(1, sizeof(*st));
+ if (!st) return 0;
+ st->n_layers = c->layers;
+ st->rec = (float**)calloc((size_t)c->layers, sizeof(float*));
+ st->conv = (float**)calloc((size_t)c->layers, sizeof(float*));
+ if (!st->rec || !st->conv){ q38_pin_state_free(st); return 0; }
+ for (int i = 0; i < c->layers; i++){
+ if (c->is_attn[i]) continue;
+ st->rec[i] = (float*)malloc(rec * sizeof(float));
+ st->conv[i] = (float*)malloc(conv * sizeof(float));
+ if (!st->rec[i] || !st->conv[i]){ q38_pin_state_free(st); return 0; }
+ }
+ if (ple){
+ st->ple = (float*)malloc(ple * sizeof(float));
+ if (!st->ple){ q38_pin_state_free(st); return 0; }
+ }
+ *slot = st;
+ }
+ for (int i = 0; i < c->layers; i++){
+ if (c->is_attn[i] || !st->rec[i]) continue;
+ if (to_state){
+ memcpy(st->rec[i], m->DN_rec[i], rec * sizeof(float));
+ memcpy(st->conv[i], m->DN_conv[i], conv * sizeof(float));
+ } else {
+ memcpy(m->DN_rec[i], st->rec[i], rec * sizeof(float));
+ memcpy(m->DN_conv[i], st->conv[i], conv * sizeof(float));
+ }
+ }
+ if (ple && st->ple){
+ if (to_state){
+ memcpy(st->ple, m->PLE_conv_state, ple * sizeof(float));
+ st->ple_len = m->ple_history_len;
+ memcpy(st->ple_hist, m->ple_history, sizeof(st->ple_hist));
+ } else {
+ memcpy(m->PLE_conv_state, st->ple, ple * sizeof(float));
+ m->ple_history_len = st->ple_len;
+ memcpy(m->ple_history, st->ple_hist, sizeof(st->ple_hist));
+ }
+ }
+ return 1;
+}
+
static int q38_size_mul(size_t left,size_t right,size_t *out){
if(!out||(right&&left>SIZE_MAX/right))return 0;
*out=left*right;return 1;
@@ -1325,7 +1417,7 @@ static void q38_prefix_cache_dispose(Q38PrefixCache *cache){
}
static void q38_prefix_cache_invalidate(void){
- g_q38_prefix.valid=0;g_q38_prefix.len=0;
+ g_q38_prefix.valid=0;g_q38_prefix.len=0;g_q38_prefix.pinned=0;
}
static int q38_prefix_cache_layout(Model *m){
@@ -1405,12 +1497,14 @@ static void q38_prefix_copy_state(Model *m,int to_cache){
}
}
-static int q38_prefix_cache_save(Model *m,const int *ids,int len,const float *logits){
+static int q38_prefix_cache_save(Model *m,const int *ids,int len,const float *logits,
+ int pinned){
if(!m||!ids||len<1||!logits||!q38_prefix_cache_layout(m)||
!q38_prefix_ids_reserve(len))return 0;
memcpy(g_q38_prefix.ids,ids,(size_t)len*sizeof(int));
memcpy(g_q38_prefix.logits,logits,(size_t)m->c.vocab*sizeof(float));
- q38_prefix_copy_state(m,1);g_q38_prefix.len=len;g_q38_prefix.valid=1;return 1;
+ q38_prefix_copy_state(m,1);g_q38_prefix.len=len;g_q38_prefix.valid=1;
+ g_q38_prefix.pinned=pinned;return 1;
}
/* Restore only when the complete cached prompt is an exact prefix. A shorter
@@ -1524,7 +1618,9 @@ static int serve_one(Model *m, ServeReq *q){
q38_pending_image_clear();
}
int max_ctx=m->kv_cap;
- if(np<1 || np>max_ctx || q->max_tok<1 || q->max_tok>max_ctx-np){
+ /* max_tokens=0 in modalita jev: leggere il prompt e fermarsi (serve_codec.h) */
+ int tok_min = (q->logprobs > 0) ? 0 : 1;
+ if(np<1 || np>max_ctx || q->max_tok<tok_min || q->max_tok>max_ctx-np){
printf("ERROR %s CONTEXT_EXCEEDED prompt_tokens=%d requested=%d capacity=%d\n",q->id,np,q->max_tok,max_ctx);
fflush(stdout); free(ids); return 0;
}
@@ -1532,7 +1628,31 @@ static int serve_one(Model *m, ServeReq *q){
double request_started=now_s();
uint64_t hits_before=m->hits, misses_before=m->miss;
Q38Timers timers_before=m->timers;
- int reuse=q38_prefix_restore(m,ids,np);
+ /* Prima gli scatti CHIESTI, e il piu profondo: sono punti di ritorno che
+ * il client ha dichiarato, e battono la cache automatica, che insegue solo
+ * l'ultimo prompt. Se nessuno serve, si ricade su quella. */
+ int reuse=0; const float *pin_lo=NULL;
+ {
+ int ps=coli_pin_best(&g_q38_pins,ids,np);
+ while(ps>=0){
+ ColiPin *k=&g_q38_pins.slot[ps];
+ Q38PinState *st=(Q38PinState*)k->state;
+ if(st && q38_pin_state_copy(m,&st,0)){
+ m->kv_len=k->len; reuse=k->len; pin_lo=k->logit;
+ coli_pin_touch(&g_q38_pins,ps);
+ break;
+ }
+ k->len=0;
+ ps=coli_pin_best(&g_q38_pins,ids,np);
+ }
+ }
+ if(!reuse) reuse=q38_prefix_restore(m,ids,np);
+ /* L'eco vale per il prefill, e il predittore del primo token fresco sono i
+ * logit salvati con lo stato che si e appena rimesso. reuse==np e il caso
+ * "prompt identico": li non c'e nessun token fresco da leggere. */
+ g_echo_k=q->logprobs; g_echo_id=q->id;
+ g_echo_pin_logit=(reuse>0&&reuse<np)
+ ? (pin_lo?pin_lo:q38_prefix_cached_logits(m)) : NULL;
float *lo=NULL;
if(reuse==np){
const float *cached=q38_prefix_cached_logits(m);
@@ -1551,7 +1671,24 @@ static int serve_one(Model *m, ServeReq *q){
q38_prefix_cache_invalidate();reset_recurrent(m);m->kv_len=0;
lo=step(m,ids,np,0);
}
- if(reuse!=np&&!q38_prefix_cache_save(m,ids,np,lo)&&getenv("Q38_PREFIX_LOG"))
+ g_echo_k=0; g_echo_id=NULL; g_echo_pin_logit=NULL; /* la lettura e finita col prefill */
+ /* Una fotografia chiesta esplicitamente sopravvive alle richieste che la
+ * estendono; la si lascia andare solo quando non e servita a niente
+ * (reuse==0: il prompt nuovo non comincia piu con lei), cosi la chat
+ * normale ritrova subito il suo riuso di prefisso. */
+ /* Uno scatto chiesto va nel pool, dove nessun'altra richiesta lo
+ * sovrascrive; la cache automatica resta libera di inseguire la chat. */
+ if(q->pin&&lo){
+ coli_pin_pool_init(&g_q38_pins,m->c.vocab);
+ ColiPin *k=coli_pin_store(&g_q38_pins,ids,np,lo);
+ if(k){
+ Q38PinState *st=(Q38PinState*)k->state;
+ if(q38_pin_state_copy(m,&st,1)){ k->state=st; fprintf(stderr,"[PIN] scatto a %d token\n",np); }
+ else k->len=0; /* senza stato lo scatto e una bugia */
+ }
+ }
+ if(reuse!=np&&
+ !q38_prefix_cache_save(m,ids,np,lo,0)&&getenv("Q38_PREFIX_LOG"))
fprintf(stderr,"[qwen38 prefix] cache disabled for request %s (state snapshot unavailable)\n",q->id);
if(getenv("Q38_PREFIX_LOG"))
fprintf(stderr,"[qwen38 prefix] request=%s reused=%d/%d\n",q->id,reuse,np);
@@ -1568,6 +1705,8 @@ static int serve_one(Model *m, ServeReq *q){
}
if(cancelled||stopped)break;
int tk = serve_sample(lo, m->c.vocab, q->temp, q->top_p);
+ char lptail[1024]; lptail[0]=0;
+ if(q->logprobs>0) coli_logprob_tail(lptail,sizeof lptail,lo,m->c.vocab,tk,q->logprobs);
free(lo); lo=NULL;
int is_eos=0; for(int e=0;e<n_eos;e++) if(tk==eos_ids[e]) is_eos=1;
if(is_eos){ limited=0; break; }
@@ -1582,7 +1721,8 @@ static int serve_one(Model *m, ServeReq *q){
if(!chunk||utf8_drain(sbuf,&sbn,token,token_n,chunk,chunk_cap,&chunk_n)<0){
free(chunk);free(token);fprintf(stderr,"[decode] invalid output capacity\n");exit(1);
}
- if(chunk_n>0)serve_data(q->id,(char*)chunk,chunk_n);
+ if(q->logprobs>0) serve_data_lp(q->id,(char*)chunk,chunk_n,lptail);
+ else if(chunk_n>0) serve_data(q->id,(char*)chunk,chunk_n);
free(chunk);free(token);
gen++;
while(!input_eof&&coli_stdin_readable()){
diff --git a/c/qwen38_core.h b/c/qwen38_core.h
index 4ac743b5..30dcfdb2 100644
--- a/c/qwen38_core.h
+++ b/c/qwen38_core.h
@@ -2174,6 +2174,26 @@ static void q38_layers_forward_range(Model *m,float *hyper,const int *ids,
free(mixed); free(inject); free(block);
}
+/* Canale logprobs (modalita jev). Qui la fotografia dello stato NON si
+ * aggiunge: questo motore ce l'ha gia, si chiama Q38PrefixCache e salva stato
+ * ricorrente, id e logit finali dopo ogni prompt. Manca solo la lettura, cioe
+ * un passaggio di lm_head per posizione invece che solo sull'ultima, e il
+ * predittore del primo token fresco, che sono i logit gia salvati. */
+static int g_echo_k = 0;
+static const char *g_echo_id = NULL;
+static const float *g_echo_pin_logit = NULL; /* logit dell'ultima posizione riusata */
+
+static void q38_echo(const char *id, int pos, int token, const float *lo, int V, int k){
+ char tail[1024]; coli_logprob_tail(tail, sizeof tail, lo, V, token, k);
+ unsigned char *piece=NULL; int n=0;
+ if(decode_id_alloc(token,&piece,&n)) { piece=NULL; n=0; }
+ if(n<0) n=0;
+ printf("ECHO %s %d %d%s\n", id, n, pos, tail);
+ if(n>0) fwrite(piece,1,(size_t)n,stdout);
+ fputc('\n', stdout); fflush(stdout);
+ free(piece);
+}
+
static float *step(Model *m,const int *ids,int S,int pos_base) {
Cfg *c=&m->c;int H=c->hidden,W=c->hc_width,C=c->hc_count;
m->timers.forwards++;
@@ -2207,6 +2227,17 @@ static float *step(Model *m,const int *ids,int S,int pos_base) {
}
q38_gr_read(m,&m->final_gr,hyper,S,mixed,NULL);m->kv_len=pos_base+S;
float *logit=falloc(c->vocab);double phase_started=now_s();
+ /* Lettura del prefill: la posizione p predice il token p+1. Il primo token
+ * fresco lo predice la fotografia del prefisso, quando c'e. Pagata solo da
+ * chi ha chiesto il canale. */
+ if(g_echo_k>0&&g_echo_id&&S>0){
+ if(g_echo_pin_logit)
+ q38_echo(g_echo_id,pos_base,ids[0],g_echo_pin_logit,c->vocab,g_echo_k);
+ for(int p=0;p+1<S;p++){
+ q38_weight_matmul(logit,mixed+(int64_t)p*H,&m->lm_head,1,H,c->vocab);
+ q38_echo(g_echo_id,pos_base+p+1,ids[p+1],logit,c->vocab,g_echo_k);
+ }
+ }
q38_weight_matmul(logit,mixed+(int64_t)(S-1)*H,&m->lm_head,1,H,c->vocab);
q38_tm_add(m,Q38_TM_LM_HEAD,phase_started);
free(hyper);free(mixed);free(inject);free(block);return logit;
diff --git a/c/serve_codec.h b/c/serve_codec.h
index 9511730e..ae15a77b 100644
--- a/c/serve_codec.h
+++ b/c/serve_codec.h
@@ -3,6 +3,7 @@
#include <errno.h>
#include <math.h>
+#include "decode_batch.h" /* ColiSubmit, coli_submit_ext, coli_logprob_tail */
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
@@ -60,6 +61,11 @@ typedef struct {
/* IMAGE: la griglia di patch che accompagna il payload. Zero per ogni altro
* comando. */
int grid_h, grid_w;
+ /* SUBMIT logprobs=k: emissione top-k per token. 0 = canale spento.
+ * Le chiavi key=value stanno dopo i campi posizionali e usano lo
+ * stesso namespace di decode_batch.h, non un secondo dialetto. */
+ int logprobs;
+ int pin; /* SUBMIT pin=1, vedi decode_batch.h */
unsigned char *payload;
} ColiServeCommand;
@@ -262,9 +268,35 @@ static inline ColiServeReadResult coli_serve_read_command_alloc(
int minimum_fields = 7;
int maximum_fields = minimum_fields + !!profile->allow_extension_bytes +
!!profile->allow_prefix_hint;
- if (nfields < minimum_fields || nfields > maximum_fields ||
- (nfields >= 8 && !profile->allow_extension_bytes) ||
- (nfields >= 9 && (!profile->allow_prefix_hint ||
+ /* I token key=value vengono dopo i campi posizionali. Il primo campo che
+ * contiene '=' apre l'estensione: da li in poi il conteggio posizionale si
+ * ferma, e le regole (chiavi note, niente duplicati, valori in campo) sono
+ * quelle di coli_submit_ext, non una seconda copia scritta qui. */
+ int positional = nfields;
+ for (int f = minimum_fields; f < nfields; f++)
+ if (strchr(fields[f], '=')) { positional = f; break; }
+ command->logprobs = 0;
+ command->pin = 0;
+ if (positional < nfields) {
+ char ext[128]; size_t used = 0; ext[0] = 0;
+ for (int f = positional; f < nfields; f++) {
+ size_t need = strlen(fields[f]) + 1;
+ if (used + need + 1 >= sizeof ext) { free(line); return COLI_SERVE_READ_BAD_REQUEST; }
+ ext[used++] = ' ';
+ memcpy(ext + used, fields[f], need);
+ used += need - 1;
+ }
+ {
+ ColiSubmit tmp;
+ memset(&tmp, 0, sizeof tmp);
+ if (!coli_submit_ext(ext, &tmp)) { free(line); return COLI_SERVE_READ_BAD_REQUEST; }
+ command->logprobs = tmp.logprobs;
+ command->pin = tmp.pin;
+ }
+ }
+ if (positional < minimum_fields || positional > maximum_fields ||
+ (positional >= 8 && !profile->allow_extension_bytes) ||
+ (positional >= 9 && (!profile->allow_prefix_hint ||
!profile->allow_extension_bytes))) {
free(line);
return COLI_SERVE_READ_BAD_REQUEST;
@@ -276,12 +308,19 @@ static inline ColiServeReadResult coli_serve_read_command_alloc(
!coli_serve_parse_i32(fields[4], &command->max_tokens) ||
!coli_serve_parse_f32(fields[5], &command->temperature) ||
!coli_serve_parse_f32(fields[6], &command->top_p) ||
- (nfields >= 8 &&
+ (positional >= 8 &&
!coli_serve_parse_u64(fields[7], &command->extension_bytes)) ||
- (nfields >= 9 && !coli_serve_parse_i32(fields[8], &command->prefix_bytes)) ||
+ (positional >= 9 && !coli_serve_parse_i32(fields[8], &command->prefix_bytes)) ||
command->payload_bytes > profile->max_payload_bytes ||
command->extension_bytes > profile->max_extension_bytes ||
- command->max_tokens < 1 ||
+ /* max_tokens=0 vale SOLO in modalita jev (logprobs>0) e vuol dire
+ * "leggi il prompt e fermati", niente generazione. Senza, chi punteggia
+ * un menu chiuso deve chiedere almeno un token, e quel token lo paga:
+ * un passo di decodifica completo per opzione, buttato via. Misurato su
+ * qwen36: raddoppia il costo di un'opzione da un token. Una richiesta
+ * che non chiede logprobs continua a essere rifiutata a 0, come prima. */
+ (command->max_tokens < 1 &&
+ !(command->max_tokens == 0 && command->logprobs > 0)) ||
(profile->max_tokens && command->max_tokens > profile->max_tokens) ||
(profile->require_finite_sampling &&
(!isfinite(command->temperature) || !isfinite(command->top_p)))) {
@@ -343,6 +382,21 @@ static inline int coli_serve_write_data(
return fflush(output) == 0;
}
+/* Come coli_serve_write_data, ma con la coda numerica del canale logprobs
+ * appesa all'intestazione: "DATA <id> <n> <lp> <k> [tid tlp]*k". Un frame per
+ * token, perche un client che punteggia vuole i token, non il testo accorpato.
+ * Si usa SOLO quando la richiesta ha chiesto logprobs=k: senza, il frame resta
+ * quello legacy byte per byte, e un gateway vecchio non vede mai questa forma. */
+static inline int coli_serve_write_data_lp(
+ FILE *output, const char *id, const void *data, size_t bytes, const char *tail)
+{
+ if (fprintf(output, "DATA %s %zu%s\n", id, bytes, tail ? tail : "") < 0 ||
+ (bytes && fwrite(data, 1, bytes, output) != bytes) ||
+ fputc('\n', output) == EOF)
+ return 0;
+ return fflush(output) == 0;
+}
+
/* Engine-authenticated structured tool output. The payload is opaque to this
* transport; the gateway applies the active family parser. A zero-byte frame
* declares the sideband authoritative for the request, so ordinary DATA that
diff --git a/c/tests/test_brio_serve.py b/c/tests/test_brio_serve.py
new file mode 100644
index 00000000..233ac4e6
--- /dev/null
+++ b/c/tests/test_brio_serve.py
@@ -0,0 +1,215 @@
+"""Closed-set scoring over the serve protocol: exact, and invisible to chat.
+
+Two properties, and the whole feature rests on them.
+
+EXACTNESS. Rewinding to a snapshot must give the SAME log probabilities as
+recomputing the prompt from cold. If it does not, the engine is answering from
+a state that is not the one it claims to hold -- and the answer still looks
+plausible, so nothing else in the tree would catch it. The gate is a paired
+comparison: the same option scored through the snapshot and through a fresh
+engine must agree to the last digit printed.
+
+INVISIBILITY. A request that does not ask for the channel must produce the
+byte-identical frames it produced before the channel existed. Chat is the mode
+everyone uses; the scoring channel is opt-in and must stay that way. The check
+is a byte diff of the frames, not a reading of the text.
+
+Runs against the tiny olmoe fixture the oracle job already builds
+(tools/make_olmoe_tiny.py + convert_olmoe_merged.py), so it needs no
+checkpoint. Skipped when the fixture is absent, like the other serve tests.
+"""
+import json
+import os
+import subprocess
+import sys
+import unittest
+from pathlib import Path
+
+HERE = Path(__file__).resolve().parent.parent
+ENGINE = HERE / ("olmoe.exe" if sys.platform == "win32" else "olmoe")
+FIXTURE = Path(os.environ.get("OLMOE_TINY", HERE / "olmoe_tiny"))
+PROMPT = "Context: the release is late and the tests are red.\nQuestion: ship?\nAnswer:"
+OPTION = " no"
+
+
+class Engine:
+ """One serve-mode engine, driven over the wire the gateway uses."""
+
+ def __init__(self):
+ env = dict(os.environ, SNAP=str(FIXTURE), SERVE="1",
+ TOK=str(FIXTURE / "tokenizer.json"),
+ COLI_NO_OMP_TUNE="1", OMP_NUM_THREADS="2")
+ self.p = subprocess.Popen([str(ENGINE)], env=env, stdin=subprocess.PIPE,
+ stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,
+ bufsize=0)
+ while True:
+ line = self.readline()
+ if line is None:
+ raise AssertionError("engine died before READY")
+ if "READY" in line:
+ return
+
+ def readline(self):
+ out = b""
+ while True:
+ ch = self.p.stdout.read(1)
+ if not ch:
+ return None
+ if ch == b"\n":
+ return out.decode("utf-8", "replace").replace("\x01", "")
+ out += ch
+
+ def submit(self, rid, text, max_tokens, extension=""):
+ """Returns (frames, echoes). frames are raw lines, for byte comparison."""
+ payload = text.encode("utf-8")
+ self.p.stdin.write(
+ f"SUBMIT {rid} 0 {len(payload)} {max_tokens} 0 1{extension}\n".encode())
+ self.p.stdin.write(payload)
+ self.p.stdin.write(b"\n")
+ self.p.stdin.flush()
+ frames, echoes = [], {}
+ while True:
+ line = self.readline()
+ if line is None:
+ return frames, echoes
+ fields = line.split()
+ if not fields:
+ continue
+ if fields[0] in ("ECHO", "DATA"):
+ size = int(fields[2])
+ if size:
+ self.p.stdout.read(size)
+ self.p.stdout.read(1)
+ if fields[0] == "ECHO" and fields[4] not in ("nan", "-nan"):
+ echoes[int(fields[3])] = float(fields[4])
+ frames.append(line)
+ if fields[0] in ("DONE", "ERROR"):
+ return frames, echoes
+
+ def close(self):
+ try:
+ self.p.stdin.close()
+ except OSError:
+ pass
+ self.p.terminate()
+ self.p.wait(timeout=30)
+
+
+def strip_volatile(frames):
+ """Drop the lines that differ run to run whatever the request asked for:
+ timings, hardware, and the routing telemetry that accumulates on disk."""
+ return [f for f in frames
+ if not f.startswith(("STAT", "PROF", "DONE", "TIERS", "HWINFO", "EMAP", "HITS"))]
+
+
[email protected]((FIXTURE / "config.json").is_file(),
+ "tiny olmoe fixture is absent (tools/make_olmoe_tiny.py)")
[email protected](ENGINE.is_file(), "olmoe engine is not built")
+class BrioServe(unittest.TestCase):
+ def test_a_snapshot_scores_exactly_like_a_cold_recompute(self):
+ warm = Engine()
+ try:
+ _, prefix = warm.submit(1, PROMPT, 0, " logprobs=1 pin=1")
+ _, pinned = warm.submit(2, PROMPT + OPTION, 0, " logprobs=1")
+ finally:
+ warm.close()
+ self.assertTrue(prefix, "the warm pass read nothing")
+ tail_starts = max(prefix) + 1
+
+ cold = Engine()
+ try:
+ _, fresh = cold.submit(1, PROMPT + OPTION, 0, " logprobs=1")
+ finally:
+ cold.close()
+
+ wanted = {p for p in fresh if p >= tail_starts}
+ self.assertTrue(wanted, "the cold run read no tail position")
+
+ # SAME positions, not just the ones that happen to overlap. The first
+ # fresh token is predicted by the snapshot's own logits; if those go
+ # missing its ECHO carries "nan" and drops out, and comparing only the
+ # intersection would call that a pass. It is not: one option token
+ # would silently stop counting towards the score.
+ got = {p for p in pinned if p >= tail_starts}
+ self.assertEqual(got, wanted,
+ f"the snapshot scored positions {sorted(got)} where a cold "
+ f"recompute scored {sorted(wanted)} -- an option token lost "
+ f"its predictor")
+
+ for position in sorted(wanted):
+ self.assertEqual(
+ pinned[position], fresh[position],
+ f"position {position}: rewinding gave {pinned[position]}, "
+ f"recomputing gave {fresh[position]} -- the snapshot is not the "
+ f"state it claims to be")
+
+ def test_the_snapshot_only_reads_the_fresh_tail(self):
+ """The point of the snapshot: the shared prefix is not read again."""
+ engine = Engine()
+ try:
+ _, prefix = engine.submit(1, PROMPT, 0, " logprobs=1 pin=1")
+ _, tail = engine.submit(2, PROMPT + OPTION, 0, " logprobs=1")
+ finally:
+ engine.close()
+ self.assertTrue(prefix, "the warm pass read nothing")
+ self.assertTrue(tail, "the option read nothing")
+ self.assertGreater(min(tail), max(prefix) - 1,
+ "the option re-read positions the snapshot already held")
+
+ def test_a_request_without_the_keys_is_byte_identical(self):
+ """Chat must not be able to tell the channel exists.
+
+ Two fresh engines rather than two turns of one: the request id is part
+ of every frame, so the same id has to be reused, and a second turn on a
+ live engine would also start from a different cached state."""
+ def frames_for(extension):
+ engine = Engine()
+ try:
+ frames, _ = engine.submit(1, PROMPT, 4, extension)
+ finally:
+ engine.close()
+ return strip_volatile(frames)
+
+ plain = frames_for("")
+ off = frames_for(" logprobs=0 pin=0")
+ self.assertEqual(plain, off,
+ "the two ways of opting out disagree")
+
+ # And opting out must see NOTHING of the channel. Comparing the two
+ # opt-out spellings only proves they agree with each other: a defect
+ # that turned the read-out on for everybody would move both arms
+ # together and pass. These two assertions are the actual invariant.
+ for frames in (plain, off):
+ self.assertFalse([f for f in frames if f.startswith("ECHO")],
+ "a request that did not ask for the channel got ECHO frames")
+ for line in frames:
+ if line.startswith("DATA"):
+ self.assertEqual(
+ len(line.split()), 3,
+ f"a DATA frame carried the numeric tail unasked: {line!r}")
+
+ def test_read_only_generates_nothing(self):
+ """max_tokens=0 means read the prompt and stop: no DATA frame at all."""
+ engine = Engine()
+ try:
+ frames, _ = engine.submit(1, PROMPT, 0, " logprobs=1")
+ finally:
+ engine.close()
+ self.assertFalse([f for f in frames if f.startswith("DATA")],
+ "a read-only request still generated a token")
+ self.assertTrue([f for f in frames if f.startswith("ECHO")],
+ "a read-only request read nothing")
+
+ def test_read_only_needs_the_channel(self):
+ """max_tokens=0 without logprobs stays a malformed request."""
+ engine = Engine()
+ try:
+ frames, _ = engine.submit(1, PROMPT, 0)
+ finally:
+ engine.close()
+ self.assertTrue([f for f in frames if f.startswith("ERROR")],
+ "max_tokens=0 was accepted without the logprobs channel")
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/c/tests/test_decode_batch.c b/c/tests/test_decode_batch.c
index 386412e8..795c84fa 100644
--- a/c/tests/test_decode_batch.c
+++ b/c/tests/test_decode_batch.c
@@ -102,7 +102,19 @@ static void test_submit_extension_fields(void)
assert(!coli_submit_parse("SUBMIT 42 3 17 64 0.7 0.95 0 logprobs=1000", &sub));
/* an extended header still validates the base fields */
assert(!coli_submit_parse("SUBMIT 0 3 17 64 0.7 0.95 0 logprobs=5", &sub));
- assert(!coli_submit_parse("SUBMIT 42 3 17 0 0.7 0.95 0 logprobs=5", &sub));
+
+ /* max_tokens=0 = "leggi il prompt e fermati", e vale SOLO con logprobs>0.
+ * Chi punteggia un insieme chiuso non vuole generare niente: dover chiedere
+ * almeno un token costa un passo di decodifica completo per ogni opzione,
+ * buttato via. Senza logprobs lo zero resta una richiesta malformata, cosi
+ * un client che dimentica il campo continua a prendere un errore invece di
+ * una risposta vuota. */
+ assert(coli_submit_parse("SUBMIT 42 3 17 0 0.7 0.95 0 logprobs=5", &sub));
+ assert(sub.max_tokens == 0 && sub.logprobs == 5);
+ assert(!coli_submit_parse("SUBMIT 42 3 17 0 0.7 0.95", &sub));
+ assert(!coli_submit_parse("SUBMIT 42 3 17 0 0.7 0.95 0 logprobs=0", &sub));
+ assert(!coli_submit_parse("SUBMIT 42 3 17 0 0.7 0.95 0 pin=1", &sub));
+ assert(!coli_submit_parse("SUBMIT 42 3 17 -1 0.7 0.95 0 logprobs=5", &sub));
}
/* U7a token-ID intake: the ids the caller formatted are exactly the ids that
diff --git a/c/tests/test_pin_pool.c b/c/tests/test_pin_pool.c
new file mode 100644
index 00000000..5427ca12
--- /dev/null
+++ b/c/tests/test_pin_pool.c
@@ -0,0 +1,110 @@
+/* pin_pool.h: the nested-snapshot bookkeeping, without an engine.
+ *
+ * The pool is what makes closed-set scoring cheap: the shared instructions are
+ * photographed once, the instructions-plus-question a second time, and each
+ * option then costs only its own tokens. Everything that can go wrong here is
+ * silent -- a snapshot restored at the wrong length answers from a state that
+ * is not the one it claims, and the reply still reads plausibly. So the rules
+ * are pinned down by a test that needs no model. */
+#include <assert.h>
+#include <stdio.h>
+#include <string.h>
+#include <stdlib.h>
+#include "../pin_pool.h"
+#include "../kv_prefix.h"
+
+static void set_slots(int n) {
+ static char buf[32];
+ snprintf(buf, sizeof buf, "%d", n);
+#ifdef _WIN32
+ _putenv_s("COLI_PIN_SLOTS", buf);
+#else
+ setenv("COLI_PIN_SLOTS", buf, 1);
+#endif
+}
+
+int main(void) {
+ const int ids[8] = {10, 11, 12, 13, 14, 15, 16, 17};
+ float logit[4] = {1.f, 2.f, 3.f, 4.f};
+
+ /* --- the deepest snapshot wins ------------------------------------- */
+ set_slots(4);
+ ColiPinPool p; memset(&p, 0, sizeof p);
+ coli_pin_pool_init(&p, 4);
+ assert(p.n == 4);
+ assert(coli_pin_store(&p, ids, 2, logit));
+ assert(coli_pin_store(&p, ids, 5, logit));
+ int best = coli_pin_best(&p, ids, 8);
+ assert(best >= 0 && p.slot[best].len == 5);
+
+ /* --- a strict prefix only: equal length leaves nothing to prefill --- */
+ best = coli_pin_best(&p, ids, 5);
+ assert(best >= 0 && p.slot[best].len == 2);
+
+ /* --- a prompt that diverges falls back to the shallower snapshot ---- */
+ const int other[8] = {10, 11, 99, 99, 99, 99, 99, 99};
+ best = coli_pin_best(&p, other, 8);
+ assert(best >= 0 && p.slot[best].len == 2);
+
+ /* --- diverging at the first token matches nothing ------------------- */
+ const int alien[4] = {99, 98, 97, 96};
+ assert(coli_pin_best(&p, alien, 4) < 0);
+
+ /* --- the logits travel with the snapshot ---------------------------- */
+ best = coli_pin_best(&p, ids, 8);
+ assert(p.slot[best].logit && p.slot[best].logit[3] == 4.f);
+
+ /* --- storing the same prefix refreshes, it does not duplicate ------- */
+ int before = 0;
+ for (int s = 0; s < p.n; s++) if (p.slot[s].len > 0) before++;
+ assert(coli_pin_store(&p, ids, 5, logit));
+ int after = 0;
+ for (int s = 0; s < p.n; s++) if (p.slot[s].len > 0) after++;
+ assert(after == before);
+
+ /* --- with one slot the newer snapshot replaces the older ------------ */
+ ColiPinPool one; memset(&one, 0, sizeof one);
+ set_slots(1);
+ coli_pin_pool_init(&one, 4);
+ assert(one.n == 1);
+ assert(coli_pin_store(&one, ids, 2, logit));
+ assert(coli_pin_store(&one, ids, 5, logit));
+ best = coli_pin_best(&one, ids, 8);
+ assert(best >= 0 && one.slot[best].len == 5);
+ assert(coli_pin_best(&one, ids, 4) < 0); /* the 2-long one is gone */
+
+ /* --- zero slots: the pool is off and nothing is ever stored --------- */
+ ColiPinPool off; memset(&off, 0, sizeof off);
+ set_slots(0);
+ coli_pin_pool_init(&off, 4);
+ assert(off.n == 0);
+ assert(coli_pin_store(&off, ids, 2, logit) == NULL);
+ assert(coli_pin_best(&off, ids, 8) < 0);
+
+ /* --- clearing drops every snapshot, and frees engine state ---------- */
+ set_slots(4);
+ ColiPinPool q; memset(&q, 0, sizeof q);
+ coli_pin_pool_init(&q, 4);
+ ColiPin *k = coli_pin_store(&q, ids, 3, logit);
+ assert(k);
+ k->state = malloc(16); /* what an engine would attach */
+ assert(k->state);
+ coli_pin_pool_clear(&q, free);
+ assert(coli_pin_best(&q, ids, 8) < 0);
+ assert(q.slot[0].state == NULL);
+
+ /* --- kv_prefix_holds: the rows a snapshot needs must still be live -- */
+ kv_prefix record; memset(&record, 0, sizeof record);
+ assert(kv_prefix_alloc(&record, 8));
+ kv_prefix_record(&record, ids, 0, 5);
+ assert(kv_prefix_holds(&record, ids, 5));
+ assert(kv_prefix_holds(&record, ids, 3));
+ assert(!kv_prefix_holds(&record, ids, 6)); /* claims more than is held */
+ assert(!kv_prefix_holds(&record, other, 5)); /* same length, other tokens */
+ kv_prefix_clear(&record);
+ assert(!kv_prefix_holds(&record, ids, 1)); /* banks dropped: nothing holds */
+ kv_prefix_free(&record);
+
+ puts("pin_pool: deepest match, strict prefix, refresh, eviction, liveness: ok");
+ return 0;
+}
diff --git a/c/tests/test_qwen38_prefix.c b/c/tests/test_qwen38_prefix.c
index 91e00e4e..6baf9927 100644
--- a/c/tests/test_qwen38_prefix.c
+++ b/c/tests/test_qwen38_prefix.c
@@ -61,7 +61,7 @@ int main(void){
const int first[]={1,2,3};float first_logits[8];
for(int i=0;i<8;i++)first_logits[i]=(float)(100+i);
- fill_state(&m,7.f);CHECK(q38_prefix_cache_save(&m,first,3,first_logits));
+ fill_state(&m,7.f);CHECK(q38_prefix_cache_save(&m,first,3,first_logits,0));
fill_state(&m,99.f);m.kv_len=3;
const int extension[]={1,2,3,4};
CHECK(q38_prefix_restore(&m,extension,4)==3);CHECK(check_state(&m,7.f));
@@ -73,13 +73,28 @@ int main(void){
/* An exact prompt restores the recurrent state and its saved logits. */
fill_state(&m,55.f);CHECK(q38_prefix_restore(&m,first,3)==3);CHECK(check_state(&m,7.f));
fill_state(&m,56.f);CHECK(q38_prefix_restore(&m,extension,4)==3);CHECK(check_state(&m,7.f));
- CHECK(q38_prefix_cache_save(&m,extension,4,first_logits));
+ CHECK(q38_prefix_cache_save(&m,extension,4,first_logits,0));
fill_state(&m,88.f);CHECK(q38_prefix_restore(&m,extension,4)==4);CHECK(check_state(&m,7.f));
const float *cached=q38_prefix_cached_logits(&m);CHECK(cached&&cached[0]==100.f&&cached[7]==107.f);
+ /* La fotografia chiesta con pin=1 si riconosce, e invalidarla la spegne:
+ * e quel flag a decidere se una richiesta che estende il prefisso puo
+ * sovrascriverla, quindi deve sopravvivere al salvataggio e sparire con
+ * l'invalidazione. */
+ CHECK(q38_prefix_cache_save(&m,first,3,first_logits,1));
+ CHECK(g_q38_prefix.pinned&&g_q38_prefix.len==3);
+ CHECK(q38_prefix_restore(&m,extension,4)==3);
+ CHECK(q38_prefix_cache_save(&m,extension,4,first_logits,0));
+ CHECK(!g_q38_prefix.pinned&&g_q38_prefix.len==4);
+ CHECK(q38_prefix_cache_save(&m,extension,4,first_logits,1));
+ q38_prefix_cache_invalidate();
+ CHECK(!g_q38_prefix.pinned&&!g_q38_prefix.valid);
+ CHECK(q38_prefix_cache_save(&m,extension,4,first_logits,0));
+
/* A mismatch is never restored; the serve miss path invalidates then
* resets the live recurrent state before feeding the new prompt. */
const int shorter[]={1,2,3};CHECK(q38_prefix_restore(&m,shorter,3)==0);
+ CHECK(q38_prefix_restore(&m,extension,4)==4);
const int mismatch[]={1,2,4};CHECK(q38_prefix_restore(&m,mismatch,3)==0);
q38_prefix_cache_invalidate();reset_recurrent(&m);m.kv_len=0;
CHECK(!g_q38_prefix.valid&&m.kv_len==0&&m.ple_history_len==0);