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

fix(registry): a reasoning family needs more room than one answer

JustVuggb2330bf6811b
diff --git a/c/Makefile b/c/Makefile
index 7d715f6a..5dd1b757 100644
--- a/c/Makefile
+++ b/c/Makefile
@@ -1032,6 +1032,20 @@ qwen38$(EXE): qwen38.c qwen38_core.h qwen38_nfc.h qwen38_nfc_tables.h st.h json.
qwen38-tiny-generate:
$(PYTHON) tools/make_qwen38_tiny.py --out ./qwen38_tiny
+# Il prefetch PLE e' un riordino, non un cambio di calcolo: le stesse righe,
+# lette prima e in parallelo. Quindi acceso e spento devono dare gli STESSI
+# token, e questo lo pretende invece di fidarsi. Se un giorno divergono, il
+# prefetch ha smesso di essere un riordino e va guardato, non spento.
+.PHONY: qwen38-ple-prefetch-check
+qwen38-ple-prefetch-check: qwen38-tiny-generate qwen38$(EXE)
+ @fail=0; for cap in 1 2 4 8; do for pb in 0 1; do for bf in 0 1; do \
+ on=$$(Q38_PREFILL_BATCH=$$pb Q38_NATIVE_BF16=$$bf OMP_NUM_THREADS=2 SNAP=./qwen38_tiny ./qwen38$(EXE) $$cap 8 ./qwen38_tiny/ref.json 2>/dev/null | grep '^C engine'); \
+ off=$$(Q38_PLE_PREFETCH=0 Q38_PREFILL_BATCH=$$pb Q38_NATIVE_BF16=$$bf OMP_NUM_THREADS=2 SNAP=./qwen38_tiny ./qwen38$(EXE) $$cap 8 ./qwen38_tiny/ref.json 2>/dev/null | grep '^C engine'); \
+ if [ -z "$$on" ]; then echo "FAIL cap=$$cap batch=$$pb bf16=$$bf: no output"; fail=1; \
+ elif [ "$$on" != "$$off" ]; then echo "FAIL cap=$$cap batch=$$pb bf16=$$bf: prefetch changes the tokens"; fail=1; fi; \
+ done; done; done; \
+ [ $$fail -eq 0 ] && echo "PLE prefetch: identical tokens on and off, 16 configurations" || exit 1
+
qwen38-tiny-check: qwen38-tiny-generate qwen38$(EXE)
@for batch in 0 1; do for bf16 in 0 1; do for cap in 1 4; do \
Q38_PREFILL_BATCH=$$batch Q38_NATIVE_BF16=$$bf16 OMP_NUM_THREADS=2 SNAP=./qwen38_tiny ./qwen38$(EXE) $$cap 8 ./qwen38_tiny/ref.json || exit $$?; \
diff --git a/c/family_registry.py b/c/family_registry.py
index 9b86e030..7ab26a48 100644
--- a/c/family_registry.py
+++ b/c/family_registry.py
@@ -907,7 +907,13 @@ FAMILIES = (
# implicit_cap 0, non 8: questo motore dimensiona la cache degli
# esperti dalla RAM disponibile, quindi "nessuna scelta esplicita"
# deve arrivargli come 0 e non come otto slot per layer.
- limits=FamilyLimits(8192, 1048576, 1024, 1024, 1, 0, "GLM53_MAXT"),
+ # L'interattivo era 1024, uguale al default non interattivo: l'unica
+ # famiglia che ragiona a cui non era stato alzato. Su un modello che
+ # riflette prima di rispondere quel tetto non e' una rete di sicurezza,
+ # e' una ghigliottina che cade DENTRO al blocco di pensiero e chiude il
+ # turno senza risposta (#1278). 16384 e' il valore che hanno gia' tutte
+ # le famiglie con lo stesso contesto massimo di 1048576.
+ limits=FamilyLimits(8192, 1048576, 1024, 16384, 1, 0, "GLM53_MAXT"),
# tools=True: this family DOES render and parse tool calls. It used to
# share COMMON_CAP, which says otherwise -- the flag is descriptive
# (it only feeds the capability dict) so nothing broke, but a client
@@ -963,7 +969,13 @@ FAMILIES = (
planner_unsupported_reason="",
expert_inventory=_inkling_expert_inventory,
config_section="text_config",
- limits=FamilyLimits(8192, 1048576, 1024, 1024, 1, 8, "CTX_MAX"),
+ # L'interattivo era 1024, uguale al default non interattivo: l'unica
+ # famiglia che ragiona a cui non era stato alzato. Su un modello che
+ # riflette prima di rispondere quel tetto non e' una rete di sicurezza,
+ # e' una ghigliottina che cade DENTRO al blocco di pensiero e chiude il
+ # turno senza risposta (#1278). 16384 e' il valore che hanno gia' tutte
+ # le famiglie con lo stesso contesto massimo di 1048576.
+ limits=FamilyLimits(8192, 1048576, 1024, 16384, 1, 8, "CTX_MAX"),
capabilities=FamilyCapabilities(False, False, True, True),
has_gateway_adapter=True,
tune_prompt_template="<|user|>{prompt}<|assistant|>",
@@ -991,7 +1003,13 @@ FAMILIES = (
planner_unsupported_reason="",
expert_inventory=_individual_expert_inventory(_KIMI_EXPERT),
config_section="text_config",
- limits=FamilyLimits(8192, 1048576, 1024, 1024, 1, 8, "K3_MAXT"),
+ # L'interattivo era 1024, uguale al default non interattivo: l'unica
+ # famiglia che ragiona a cui non era stato alzato. Su un modello che
+ # riflette prima di rispondere quel tetto non e' una rete di sicurezza,
+ # e' una ghigliottina che cade DENTRO al blocco di pensiero e chiude il
+ # turno senza risposta (#1278). 16384 e' il valore che hanno gia' tutte
+ # le famiglie con lo stesso contesto massimo di 1048576.
+ limits=FamilyLimits(8192, 1048576, 1024, 16384, 1, 8, "K3_MAXT"),
# tools=True: this family DOES render and parse tool calls. It used to
# share COMMON_CAP, which says otherwise -- the flag is descriptive
# (it only feeds the capability dict) so nothing broke, but a client
diff --git a/c/qwen38_core.h b/c/qwen38_core.h
index 03a41e8f..2e1ac904 100644
--- a/c/qwen38_core.h
+++ b/c/qwen38_core.h
@@ -140,6 +140,8 @@ typedef struct {
* `vis_rows`, oppure -1. Assoluta e non relativa al chunk: il prefill arriva
* a pezzi, e un indice relativo darebbe l'immagine sbagliata al secondo
* pezzo senza che niente protesti. */
+ /* PLE prefetto: le righe gia' lette per il chunk in corso, o NULL. */
+ float *ple_pref; int ple_pref_rows;
Q38Vision vis;
int vis_ready;
float *vis_rows;
@@ -1346,6 +1348,69 @@ static int64_t q38_hash_row(Model *m,int head,int ngram,int64_t cur,int64_t p1,i
return m->ple_head_offset[head]+r;
}
+
+/* Anticipa le letture PLE all'inizio del forward invece di emetterle inline al
+ * layer che le usa.
+ *
+ * Perche' si puo' fare, e perche' NON si puo' fare con gli esperti: gli indici
+ * delle righe PLE sono funzione pura degli id dei token e della finestra di due
+ * token che li precede -- q38_hash_row non guarda nessuno stato nascosto. Sono
+ * quindi noti PRIMA che parta un solo calcolo. Gli esperti no: quelli dipendono
+ * dal router del layer precedente, e per questo la loro finestra di anticipo e'
+ * di un layer e non di tutto il forward.
+ *
+ * Il PLE cade sul layer 2 di 48, quindi fra l'emissione e l'uso ci sono due
+ * layer interi di calcolo -- con il loro streaming di esperti, che su questo
+ * motore e' la parte lenta. E' abbondantemente il tempo di far arrivare 16
+ * righe da 160 byte.
+ *
+ * Sono anche letture PARALLELE invece che in fila: prima erano 16 pread seriali
+ * a queue depth 1 per token, che in prefill diventano lunghezza-del-prompt per
+ * 16, una alla volta.
+ *
+ * Riordino puro: stessi byte, letti prima. I token non cambiano, e il test lo
+ * pretende invece di darlo per scontato. */
+static void q38_ple_prefetch(Model *m,const int *ids,int S) {
+ Cfg *c=&m->c;
+ free(m->ple_pref); m->ple_pref=NULL; m->ple_pref_rows=0;
+ if(c->ple_layer<0||S<1||c->ngram_heads<1||c->ngram_head_dim<1) return;
+ if(!q38_env_bool("Q38_PLE_PREFETCH",1)) return;
+
+ int64_t per_row=c->ngram_head_dim, per_pos=(int64_t)c->ngram_heads*per_row;
+ if(S>INT_MAX/c->ngram_heads) return;
+ float *buffer=(float*)malloc((size_t)S*per_pos*sizeof(float));
+ int64_t *rows=(int64_t*)malloc((size_t)S*c->ngram_heads*sizeof(int64_t));
+ if(!buffer||!rows){free(buffer);free(rows);return;} /* niente prefetch: si legge inline */
+
+ /* La finestra di due token viene SIMULATA, non mutata: q38_ple la aggiorna
+ * per conto suo mentre gira, e toccarla qui la farebbe avanzare due volte. */
+ int64_t history[2]={m->ple_history[0],m->ple_history[1]};
+ int history_len=m->ple_history_len;
+ for(int s=0;s<S;s++){
+ int64_t p1=history_len>=1?history[history_len-1]:c->eos_id;
+ int64_t p2=history_len>=2?history[history_len-2]:c->eos_id;
+ for(int h=0;h<c->ngram_heads;h++){
+ int ng=h<c->heads_per_ngram?2:3;
+ rows[(int64_t)s*c->ngram_heads+h]=q38_hash_row(m,h,ng,ids[s],p1,p2);
+ }
+ if(ids[s]==c->eos_id) history_len=0;
+ else if(history_len==0){history[0]=ids[s];history_len=1;}
+ else if(history_len==1){history[1]=ids[s];history_len=2;}
+ else {history[0]=history[1];history[1]=ids[s];}
+ }
+
+ int64_t total=(int64_t)S*c->ngram_heads;
+ volatile int failed=0;
+ #pragma omp parallel for schedule(static)
+ for(int64_t i=0;i<total;i++){
+ if(failed) continue;
+ q38_ple_row(m,rows[i],buffer+i*per_row);
+ }
+ free(rows);
+ if(failed){free(buffer);return;}
+ m->ple_pref=buffer; m->ple_pref_rows=S;
+}
+
static void q38_ple(Model *m,const int *ids,int S,const float *hyper,float *out) {
double phase_started=now_s();
Cfg *c=&m->c; Layer *l=&m->L[c->ple_layer]; int H=c->hidden,C=c->hc_count,W=c->hc_width,E=c->ple_dim;
@@ -1354,7 +1419,12 @@ static void q38_ple(Model *m,const int *ids,int S,const float *hyper,float *out)
for(int s=0;s<S;s++){
int64_t p1=m->ple_history_len>=1?m->ple_history[m->ple_history_len-1]:c->eos_id;
int64_t p2=m->ple_history_len>=2?m->ple_history[m->ple_history_len-2]:c->eos_id;
- for(int h=0;h<c->ngram_heads;h++){
+ if(m->ple_pref&&s<m->ple_pref_rows){
+ /* gia' in memoria: le ha portate q38_ple_prefetch mentre i primi
+ * layer calcolavano */
+ memcpy(emb,m->ple_pref+(int64_t)s*c->ngram_heads*c->ngram_head_dim,
+ (size_t)c->ngram_heads*c->ngram_head_dim*sizeof(float));
+ } else for(int h=0;h<c->ngram_heads;h++){
int ng=h<c->heads_per_ngram?2:3; int64_t row=q38_hash_row(m,h,ng,ids[s],p1,p2);
q38_ple_row(m,row,emb+(int64_t)h*c->ngram_head_dim);
}
@@ -1871,6 +1941,10 @@ 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++;
float *hyper=falloc((int64_t)S*W);
+ /* Le righe PLE partono ADESSO, non al layer 2 dove servono: sono note dagli
+ * id dei token soltanto, e i due layer che le precedono danno il tempo di
+ * farle arrivare dal disco. */
+ q38_ple_prefetch(m,ids,S);
for(int s=0;s<S;s++){
if(ids[s]<0||ids[s]>=c->vocab){fprintf(stderr,"token id %d outside vocabulary\n",ids[s]);exit(1);}
float *e=hyper+(int64_t)s*W;
@@ -1884,7 +1958,11 @@ static float *step(Model *m,const int *ids,int S,int pos_base) {
float *mixed=falloc((int64_t)S*H),*inject=falloc((int64_t)S*C),*block=falloc((int64_t)S*H);
for(int i=0;i<c->layers;i++){
Layer *l=&m->L[i];
- if(i==c->ple_layer){float *ple=falloc((int64_t)S*W);q38_ple(m,ids,S,hyper,ple);for(int64_t z=0;z<(int64_t)S*W;z++)hyper[z]+=ple[z];free(ple);}
+ if(i==c->ple_layer){float *ple=falloc((int64_t)S*W);q38_ple(m,ids,S,hyper,ple);for(int64_t z=0;z<(int64_t)S*W;z++)hyper[z]+=ple[z];free(ple);
+ /* consumate: il chunk successivo ha altri token, e riusare queste
+ * righe darebbe gli embedding del chunk precedente combaciando in
+ * silenzio invece di dare errore. */
+ free(m->ple_pref); m->ple_pref=NULL; m->ple_pref_rows=0;}
q38_gr_read(m,&l->attn_gr,hyper,S,mixed,inject);
if(c->is_attn[i])q38_attention(m,l,i,mixed,S,pos_base,block);else q38_deltanet(m,l,i,mixed,S,block);
q38_gr_apply(c,hyper,block,inject,S);
diff --git a/c/tests/test_family_registry.py b/c/tests/test_family_registry.py
index 00d4c984..c56e1b4d 100644
--- a/c/tests/test_family_registry.py
+++ b/c/tests/test_family_registry.py
@@ -1097,6 +1097,29 @@ class FamilyRegistryTest(unittest.TestCase):
f"{family.id}: registry says tools={family.capabilities.tools} but the "
f"renderer {'refuses' if refused else 'accepts'} them")
+ def test_a_reasoning_family_gets_more_room_than_a_single_answer(self):
+ """Chi ragiona deve avere un budget interattivo piu' largo del default.
+
+ Il tetto sui token e' una rete di sicurezza: la fine vera la decidono
+ gli stop token. Ma su un modello che riflette prima di rispondere, un
+ tetto stretto non ti prende DOPO la risposta, ti prende DENTRO al
+ pensiero, e il turno finisce senza che l'utente veda niente (#1278).
+
+ glm53, inkling e kimi erano rimaste all'interattivo uguale al default,
+ mentre ogni altra famiglia che ragiona lo aveva gia' alzato. Nessuno se
+ n'e' accorto perche' il registro accetta qualsiasi valore >= 1: questo
+ controllo esiste perche' la prossima non passi allo stesso modo.
+ """
+ for family in FAMILIES:
+ if not family.capabilities.thinking:
+ continue # senza ragionamento il default e' la risposta intera
+ self.assertGreater(
+ family.limits.interactive_max_output, family.limits.default_max_output,
+ f"{family.id}: reasons, but its interactive budget "
+ f"({family.limits.interactive_max_output}) is no larger than the "
+ f"non-interactive default ({family.limits.default_max_output}) -- "
+ f"reasoning can consume it before the answer starts")
+
def test_build_install_ci_and_release_cover_registered_engines(self):
repo = Path(__file__).resolve().parents[2]
makefile = (repo / "c" / "Makefile").read_text(encoding="utf-8")