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

qwen38: several conversations at once (KV_SLOTS up to 16)

JustVugg948ad7422d9e
diff --git a/c/qwen38.c b/c/qwen38.c
index 846e14ec..2508e0c1 100644
--- a/c/qwen38.c
+++ b/c/qwen38.c
@@ -1252,6 +1252,24 @@ static void q38_pending_image_clear(void){
memset(&g_pending_image,0,sizeof g_pending_image);
}
+/* IMAGE: the patches wait for the SUBMIT they belong to. */
+static int q38_serve_take_image(FILE *out,ColiServeCommand *command){
+ if(!g_serve_model||!g_serve_model->vis_ready){
+ coli_serve_write_error(out,command->id,
+ "this engine has no vision tower; images are not supported");
+ coli_serve_command_dispose(command);return 0;
+ }
+ if(g_pending_image.present)
+ fprintf(stderr,"[qwen38] a second image arrived before its SUBMIT; dropping the first\n");
+ q38_pending_image_clear();
+ g_pending_image.patches=coli_serve_command_take_payload(command);
+ g_pending_image.bytes=command->payload_bytes;
+ g_pending_image.grid_h=command->grid_h;
+ g_pending_image.grid_w=command->grid_w;
+ g_pending_image.present=1;
+ coli_serve_command_dispose(command);return 0;
+}
+
static int serve_read_req(FILE *in,FILE *out,ServeReq *q,const char *active_id){
ColiServeCommand command;
ColiServeReadResult result=coli_serve_read_command(in,&q38_wire,&command);
@@ -1268,22 +1286,7 @@ static int serve_read_req(FILE *in,FILE *out,ServeReq *q,const char *active_id){
int control=active?(command.kind==COLI_SERVE_COMMAND_STOP?1:3):0;
coli_serve_command_dispose(&command);return control;
}
- if(command.kind==COLI_SERVE_COMMAND_IMAGE){
- if(!g_serve_model||!g_serve_model->vis_ready){
- coli_serve_write_error(out,command.id,
- "this engine has no vision tower; images are not supported");
- coli_serve_command_dispose(&command);return 0;
- }
- if(g_pending_image.present)
- fprintf(stderr,"[qwen38] a second image arrived before its SUBMIT; dropping the first\n");
- q38_pending_image_clear();
- g_pending_image.patches=coli_serve_command_take_payload(&command);
- g_pending_image.bytes=command.payload_bytes;
- g_pending_image.grid_h=command.grid_h;
- g_pending_image.grid_w=command.grid_w;
- g_pending_image.present=1;
- coli_serve_command_dispose(&command);return 0;
- }
+ if(command.kind==COLI_SERVE_COMMAND_IMAGE)return q38_serve_take_image(out,&command);
if(command.kind!=COLI_SERVE_COMMAND_SUBMIT){coli_serve_command_dispose(&command);return 0;}
if(active_id){
coli_serve_write_error(out,command.id,"engine busy");
@@ -1757,7 +1760,16 @@ static int q38_serve_budget(int np, int max_tok, int max_ctx, int read_only){
return max_tok > room ? room : max_tok;
}
-static int serve_one(Model *m, ServeReq *q){
+/* When a request was accepted, and the counters then: the DONE and PROF frames
+ * report the request's share from them. */
+typedef struct { double started; uint64_t hits, misses; Q38Timers timers; } Q38ReqClock;
+
+/* A request's prompt into the conversation the Model holds: its tokens and image,
+ * the budget, ACCEPT, the pins and the prefix cache, the prefill and its read-out.
+ * 1 with the prompt's ids and the logits after it; 0 when the request ended here,
+ * its ERROR frame written. serve_one and serve_mux start every request here. */
+static int q38_serve_start(Model *m, ServeReq *q, int **ids_out, int *np_out, float **lo_out,
+ Q38ReqClock *clk){
int *ids=NULL, np=0;
encode_text_n(q->payload,(size_t)q->plen,&ids,&np); /* byte-counted prompt; qwen38 adds no BOS */
if(g_pending_image.present){
@@ -1792,9 +1804,7 @@ static int serve_one(Model *m, ServeReq *q){
q->max_tok = budget;
}
printf("ACCEPT %s %d\n",q->id,np); fflush(stdout);
- double request_started=now_s();
- uint64_t hits_before=m->hits, misses_before=m->miss;
- Q38Timers timers_before=m->timers;
+ clk->started=now_s(); clk->hits=m->hits; clk->misses=m->miss; clk->timers=m->timers;
/* 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. */
@@ -1866,6 +1876,16 @@ static int serve_one(Model *m, ServeReq *q){
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);
+ *ids_out=ids; *np_out=np; *lo_out=lo;
+ return 1;
+}
+
+static int serve_one(Model *m, ServeReq *q){
+ int *ids=NULL, np=0; float *lo=NULL; Q38ReqClock clk;
+ if(!q38_serve_start(m,q,&ids,&np,&lo,&clk)) return 0;
+ double request_started=clk.started;
+ uint64_t hits_before=clk.hits, misses_before=clk.misses;
+ Q38Timers timers_before=clk.timers;
int gen=0, limited=1, cancelled=0, stopped=0, input_eof=0;
int eos_ids[4];int n_eos=serve_eos_ids(eos_ids,4,m->c.eos_id,m->c.vocab);
/* Q38_MTP=1: the head drafts and a verify forward checks it; every token
@@ -1951,6 +1971,207 @@ static int serve_one(Model *m, ServeReq *q){
return input_eof?-1:0;
}
+/* ---- several conversations at once (KV_SLOTS>1) -----------------------------
+ * The gateway's cache slots, each a conversation with a state of its own (Q38Seq,
+ * qwen38_core.h). A SUBMIT on a free slot starts its request at once: the prompt goes
+ * in through the same q38_serve_start as a lone request's, on that slot's state, with
+ * its pins and its own prefix cache. Then every step picks the next token of each
+ * active request from its logits and runs one forward over a row of each
+ * (q38_forward_rows): the matrices and the experts are read once for all of them. A
+ * request's frames are a lone request's; they interleave by id. Nothing drafts
+ * (speculation follows one conversation), and the slot keeps its state between turns,
+ * so a conversation's next turn reuses its prompt as a lone serve's does. */
+static int g_q38_mux_slots = 1;
+static Q38Seq *g_q38_mux_seq; /* [slots]: the conversations the Model does not hold */
+static Q38PrefixCache *g_q38_mux_prefix; /* [slots]: their prefix caches */
+static int g_q38_mux_cur; /* the slot the Model holds, -1 when every one is parked */
+
+typedef struct {
+ ServeReq q;
+ int active, stop, cancel, limited;
+ int *ids, np, gen;
+ float *lo; /* the logits the next pick reads */
+ Q38ReqClock clk;
+ double first_token_at, last_token_at;
+ unsigned char sbuf[16]; int sbn;
+} Q38MuxReq;
+
+static void q38_mux_bind(Model *m,int slot){
+ if(g_q38_mux_cur==slot)return;
+ for(int k=0;k<2;k++){ /* the held one back to its place, then the asked one in */
+ int x=k?slot:g_q38_mux_cur;
+ if(x<0)continue;
+ q38_seq_swap(m,&g_q38_mux_seq[x]);
+ Q38PrefixCache t=g_q38_prefix; g_q38_prefix=g_q38_mux_prefix[x]; g_q38_mux_prefix[x]=t;
+ }
+ g_q38_mux_cur=slot;
+}
+
+/* Slot 0 is the Model's own state; the others get theirs here. 0: out of memory. */
+static int q38_mux_alloc(Model *m){
+ int n=g_q38_mux_slots;
+ g_q38_mux_seq=(Q38Seq*)calloc((size_t)n,sizeof *g_q38_mux_seq);
+ g_q38_mux_prefix=(Q38PrefixCache*)calloc((size_t)n,sizeof *g_q38_mux_prefix);
+ if(!g_q38_mux_seq||!g_q38_mux_prefix)return 0;
+ for(int i=1;i<n;i++)if(!q38_seq_alloc(m,&g_q38_mux_seq[i]))return 0;
+ g_q38_mux_cur=0;
+ return 1;
+}
+static void q38_mux_free(Model *m){
+ if(!g_q38_mux_seq)return;
+ for(int i=0;i<g_q38_mux_slots;i++){q38_mux_bind(m,i);q38_prefix_cache_release(m);}
+ q38_mux_bind(m,0); /* the Model's own state back where q38_model_free looks */
+ for(int i=1;i<g_q38_mux_slots;i++)q38_seq_free(m,&g_q38_mux_seq[i]);
+ free(g_q38_mux_seq);free(g_q38_mux_prefix);g_q38_mux_seq=NULL;g_q38_mux_prefix=NULL;
+}
+
+/* A request's end, as serve_one ends one: the UTF-8 tail, DONE and PROF, or the
+ * ERROR of a cancel. */
+static void q38_mux_finish(Model *m,Q38MuxReq *r){
+ free(r->lo);r->lo=NULL;free(r->ids);r->ids=NULL;r->active=0;
+ if(r->cancel){coli_serve_write_error(stdout,r->q.id,"CANCELLED");return;}
+ if(r->stop)r->limited=0;
+ unsigned char tail[3];int tail_n=0;
+ if(utf8_finish(r->sbuf,&r->sbn,tail,sizeof tail,&tail_n)<0){
+ fprintf(stderr,"[decode] invalid UTF-8 finalization\n");exit(1);
+ }
+ if(tail_n)serve_data(r->q.id,(char*)tail,tail_n);
+ double wall_s=now_s()-r->clk.started;
+ double decode_s=r->gen>1?r->last_token_at-r->first_token_at:0.0;
+ uint64_t hits=m->hits-r->clk.hits,misses=m->miss-r->clk.misses;
+ Q38Timers timers=q38_tm_delta(&m->timers,&r->clk.timers);
+ ColiServeDone done={r->gen,q38_decode_rate(r->gen,decode_s),
+ q38_cache_hit_percent(hits,misses),rss_gb(),r->np,r->limited};
+ coli_serve_write_done(stdout,r->q.id,&done);
+ char profile[256];int profile_bytes=q38_format_prof(profile,sizeof profile,wall_s,r->np,r->gen,&timers);
+ if(profile_bytes>0)fwrite(profile,1,(size_t)profile_bytes,stdout);
+ else fprintf(stderr,"[qwen38] internal error: PROF frame overflow\n");
+ fflush(stdout);
+ serve_hits(m);
+ q38_tm_report_bank(&timers,"request");
+}
+
+/* The next token of an active request, as serve_one's loop picks and sends it: 1
+ * with the token when the request goes on, 0 when it ended. */
+static int q38_mux_pick(Model *m,Q38MuxReq *r,const int *eos_ids,int n_eos,int *tk_out){
+ if(r->cancel||r->stop||r->gen>=r->q.max_tok){q38_mux_finish(m,r);return 0;}
+ int tk=serve_sample(r->lo,m->c.vocab,r->q.temp,r->q.top_p);
+ char lptail[1024];lptail[0]=0;
+ if(r->q.logprobs>0)coli_logprob_tail(lptail,sizeof lptail,r->lo,m->c.vocab,tk,r->q.logprobs);
+ free(r->lo);r->lo=NULL;
+ for(int e=0;e<n_eos;e++)if(tk==eos_ids[e]){r->limited=0;q38_mux_finish(m,r);return 0;}
+ double token_at=now_s();
+ if(!r->gen)r->first_token_at=token_at;
+ r->last_token_at=token_at;
+ unsigned char *token=NULL;int token_n=0;
+ if(decode_id_alloc(tk,&token,&token_n)){fprintf(stderr,"[decode] out of memory\n");exit(1);}
+ if(token_n>(INT_MAX-3)/3){free(token);fprintf(stderr,"[decode] token is too large\n");exit(1);}
+ int chunk_cap=token_n*3+3;
+ unsigned char *chunk=(unsigned char*)malloc((size_t)chunk_cap);int chunk_n=0;
+ if(!chunk||utf8_drain(r->sbuf,&r->sbn,token,token_n,chunk,chunk_cap,&chunk_n)<0){
+ free(chunk);free(token);fprintf(stderr,"[decode] invalid output capacity\n");exit(1);
+ }
+ if(r->q.logprobs>0)serve_data_lp(r->q.id,(char*)chunk,chunk_n,lptail);
+ else if(chunk_n>0)serve_data(r->q.id,(char*)chunk,chunk_n);
+ free(chunk);free(token);
+ r->gen++;
+ /* the next logits are not needed after the last requested token (serve_one) */
+ if(r->gen>=r->q.max_tok){q38_mux_finish(m,r);return 0;}
+ *tk_out=tk;return 1;
+}
+
+/* One command: a SUBMIT on a free slot starts its request, STOP and CANCEL mark the
+ * request they name, IMAGE waits for its SUBMIT. -1 at the end of the input. */
+static int q38_serve_take_image(FILE *out,ColiServeCommand *command);
+static int q38_mux_read(Model *m,Q38MuxReq *rq,int n){
+ ColiServeCommand command;
+ ColiServeReadResult result=coli_serve_read_command(stdin,&q38_wire,&command);
+ if(result==COLI_SERVE_READ_EOF||result==COLI_SERVE_READ_BAD_FRAME)return -1;
+ if(result==COLI_SERVE_READ_NOMEM){coli_serve_write_error(stdout,command.id,"out of memory");return -1;}
+ if(result==COLI_SERVE_READ_BAD_REQUEST){
+ if(command.kind==COLI_SERVE_COMMAND_SUBMIT)
+ coli_serve_write_error(stdout,command.id,"bad submit header");
+ coli_serve_command_dispose(&command);return 0;
+ }
+ if(result!=COLI_SERVE_READ_OK)return 0;
+ if(command.kind==COLI_SERVE_COMMAND_STOP||command.kind==COLI_SERVE_COMMAND_CANCEL){
+ for(int i=0;i<n;i++)if(rq[i].active&&!strcmp(rq[i].q.id,command.id)){
+ if(command.kind==COLI_SERVE_COMMAND_STOP)rq[i].stop=1; else rq[i].cancel=1;
+ }
+ coli_serve_command_dispose(&command);return 0;
+ }
+ if(command.kind==COLI_SERVE_COMMAND_IMAGE)return q38_serve_take_image(stdout,&command);
+ if(command.kind!=COLI_SERVE_COMMAND_SUBMIT){coli_serve_command_dispose(&command);return 0;}
+ if(command.slot<0||command.slot>=n){
+ coli_serve_write_error(stdout,command.id,"invalid cache slot");
+ coli_serve_command_dispose(&command);return 0;
+ }
+ Q38MuxReq *r=&rq[command.slot];
+ if(r->active){
+ coli_serve_write_error(stdout,command.id,"cache slot busy");
+ coli_serve_command_dispose(&command);return 0;
+ }
+ memset(r,0,sizeof *r);
+ snprintf(r->q.id,sizeof(r->q.id),"%s",command.id);
+ r->q.slot=command.slot;
+ r->q.max_tok=command.max_tokens;r->q.temp=command.temperature;r->q.top_p=command.top_p;
+ r->q.payload=(char*)coli_serve_command_take_payload(&command);r->q.plen=(int)command.payload_bytes;
+ r->q.logprobs=command.logprobs;r->q.pin=command.pin;
+ coli_serve_command_dispose(&command);
+ q38_mux_bind(m,r->q.slot);
+ int ok=q38_serve_start(m,&r->q,&r->ids,&r->np,&r->lo,&r->clk);
+ free(r->q.payload);r->q.payload=NULL;
+ if(!ok)return 0;
+ q38_vision_detach(m); /* the image's rows are the prompt's: no decode row reads them */
+ r->active=1;r->limited=1;
+ return 1;
+}
+
+static void serve_mux(Model *m){
+ int n=g_q38_mux_slots,V=m->c.vocab,input_eof=0;
+ Q38MuxReq *rq=(Q38MuxReq*)calloc((size_t)n,sizeof *rq);
+ Q38Row *rows=(Q38Row*)malloc((size_t)n*sizeof *rows);
+ int *tok=(int*)malloc((size_t)n*sizeof(int)),*who=(int*)malloc((size_t)n*sizeof(int));
+ if(!rq||!rows||!tok||!who){fprintf(stderr,"[serve] out of memory\n");exit(1);}
+ int eos_ids[4];int n_eos=serve_eos_ids(eos_ids,4,m->c.eos_id,V);
+ unsigned long long steps=0,nrows=0;
+ fprintf(stderr,"[qwen38] serving %d conversations at once (KV_SLOTS)\n",n);
+ for(;;){
+ int active=0;for(int i=0;i<n;i++)active+=rq[i].active;
+ /* idle: wait for a command; decoding: take one only when one is there */
+ if(!input_eof&&(!active||coli_stdin_readable())&&q38_mux_read(m,rq,n)<0)input_eof=1;
+ active=0;for(int i=0;i<n;i++)active+=rq[i].active;
+ if(!active){if(input_eof)break;continue;}
+ int S=0,ended=0;
+ for(int i=0;i<n;i++)if(rq[i].active){
+ int tk;
+ if(!q38_mux_pick(m,&rq[i],eos_ids,n_eos,&tk)){ended=1;continue;}
+ rows[S]=(Q38Row){&g_q38_mux_seq[i],rq[i].np+rq[i].gen-1};tok[S]=tk;who[S]=i;S++;
+ }
+ if(S){
+ /* every conversation parked: the rows read theirs from g_q38_mux_seq */
+ q38_mux_bind(m,-1);
+ float *lo=q38_forward_rows(m,rows,tok,S);
+ steps++;nrows+=(unsigned long long)S;
+ for(int s=0;s<S;s++){
+ Q38MuxReq *r=&rq[who[s]];
+ r->lo=falloc(V);memcpy(r->lo,lo+(int64_t)s*V,(size_t)V*sizeof(float));
+ }
+ free(lo);
+ }
+ if(ended){
+#ifdef COLI_VULKAN
+ q38_vk_report();
+ vkt_report("turn", m->hits, m->miss);
+#endif
+ serve_emap(m);
+ }
+ }
+ fprintf(stderr,"[qwen38] KV_SLOTS=%d: %llu decode steps, %llu rows (%.2f a step)\n",n,steps,nrows,
+ steps?(double)nrows/(double)steps:0.0);
+ free(rq);free(rows);free(tok);free(who);
+}
+
static void serve_loop(Model *m){
g_serve_model=m;
coli_serve_binary_mode();
@@ -1960,6 +2181,9 @@ static void serve_loop(Model *m){
if(!q38_serve_ensure_kv(m,max_ctx)){
fprintf(stderr,"[serve] unable to allocate QSA state\n");return;
}
+ if(g_q38_mux_slots>1&&!q38_mux_alloc(m)){
+ fprintf(stderr,"[serve] unable to allocate the state of %d conversations (KV_SLOTS)\n",g_q38_mux_slots);return;
+ }
fputs("\x01\x01READY\x01\x01\n",stdout);
/* between READY and STAT: the gateway reads it in the handshake, so it knows
* the served modalities before the first request (docs/serve_protocol.md) */
@@ -1967,6 +2191,7 @@ static void serve_loop(Model *m){
printf("STAT 0 0.00 0.0 %.2f\n",rss_gb());
fflush(stdout);
serve_emap(m); /* after READY and STAT: the boot reader discards what precedes them */
+ if(g_q38_mux_slots>1){serve_mux(m);q38_mux_free(m);return;}
for(;;){
ServeReq q={0}; int r;
do r=serve_read_req(stdin,stdout,&q,NULL); while(r!=2&&r>=0);
@@ -2130,8 +2355,24 @@ int main(int argc, char **argv) {
Model m; model_init(&m, snap, cap, bits);
q38_expert_int4_attach(&m, snap); /* <snap>/experts-int4g64/ when present (Q38_EXPERT_INT4) */
- q38_mtp_attach(&m, cap); /* Q38_MTP=1: the checkpoint's MTP head drafts (qwen38_core.h) */
+ if (serve_mode) { /* KV_SLOTS: how many conversations the serve decodes at once */
+ const char *ks=getenv("KV_SLOTS");
+ if (ks && *ks) {
+ char *end=NULL; long v=strtol(ks,&end,10);
+ if (end==ks || *end || v<1 || v>16) { fprintf(stderr, "KV_SLOTS must be between 1 and 16\n"); return 2; }
+ g_q38_mux_slots=(int)v;
+ }
+ }
+ if (g_q38_mux_slots>1)
+ fprintf(stderr, "[qwen38] KV_SLOTS=%d: the MTP head stays unloaded and nothing drafts "
+ "(speculation follows one conversation)\n", g_q38_mux_slots);
+ else q38_mtp_attach(&m, cap); /* Q38_MTP=1: the checkpoint's MTP head drafts (qwen38_core.h) */
q38_tier_start(&m, cap); /* COLI_CUDA=1: hot experts stream to VRAM (qwen36_tier.c) */
+ if (g_q38_mux_slots>1 && m.dn_dev) {
+ m.dn_dev=0;
+ fprintf(stderr, "[qwen38] KV_SLOTS=%d: DeltaNet on the CPU (Q38_DN_GPU keeps one conversation's state on the card)\n",
+ g_q38_mux_slots);
+ }
q38_trunk_cpu_int8(&m); /* the trunk's int8 rows on the CPU, BF16 released (Q38_TRUNK_CPU_INT8=0 keeps BF16) */
q38_expert_report(&m, cap); /* expert format, bytes per expert, what the cache costs */
#ifdef COLI_VULKAN
@@ -2145,6 +2386,11 @@ int main(int argc, char **argv) {
* on an integrated GPU (docs/vulkan.md, "The dense chain") */
if(g_vk_ready&&!qt_ready())
g_vk_chain=coli_vk_chain_decide("qwen38",vkt_wanted()&&m.c.experts>0,COLI_VK_CHAIN_OFF);
+ if(g_vk_chain&&g_q38_mux_slots>1){
+ g_vk_chain=0;
+ fprintf(stderr,"[VK] qwen38: KV_SLOTS=%d: the dense chain is off (it keeps one conversation's state on the device); "
+ "the expert tier runs every conversation's experts\n",g_q38_mux_slots);
+ }
q38c_start(&m); /* the layers that fit the device, before anything of the chain goes up (a partial chain placed now; qwen38_chain.h) */
if(g_vk_chain&&!vkc_init())g_vk_chain=0;
q38_dho_start(&m); /* COLI_VK_DENSE_HOST: the trunk on the device only, before the tier sizes its budget */
diff --git a/c/qwen38_core.h b/c/qwen38_core.h
index 382d11ef..e8897f9b 100644
--- a/c/qwen38_core.h
+++ b/c/qwen38_core.h
@@ -160,6 +160,22 @@ typedef enum {
Q38_EXPERT_BATCH_FALLBACK_LAYOUT,
} Q38ExpertBatchFallback;
+/* One conversation's state for a multiplexed serve (KV_SLOTS>1, qwen38.c's
+ * serve_mux): everything a forward reads and writes that belongs to one token
+ * sequence. The Model holds the conversation being prefilled; the others wait
+ * here, and q38_seq_swap trades the two sets of pointers. A multiplexed decode
+ * step (q38_forward_rows) parks every conversation here and reads each row's
+ * from its Q38Row. */
+typedef struct Q38Seq {
+ float **K, **V, **IK, **DN_rec, **DN_conv;
+ int kv_len;
+ kv_prefix kvp;
+ int64_t *ple_history;
+ float *PLE_conv_state;
+ int ple_history_len;
+} Q38Seq;
+typedef struct { Q38Seq *seq; int pos; } Q38Row;
+
typedef struct {
Cfg c;
shards S;
@@ -234,6 +250,10 @@ typedef struct {
float **snap_rec[Q38_SPEC_SNAPS], **snap_conv[Q38_SPEC_SNAPS], *snap_ple[Q38_SPEC_SNAPS];
int64_t snap_ple_history[Q38_SPEC_SNAPS][2];
int snap_ple_history_len[Q38_SPEC_SNAPS];
+ /* A multiplexed decode step (q38_forward_rows): row s is the token at
+ * mux_rows[s].pos of mux_rows[s].seq, so the attention, DeltaNet and PLE
+ * read and write that conversation's state; NULL in every other forward. */
+ const Q38Row *mux_rows;
#ifdef COLI_VULKAN
void *vkchain; /* the dense chain's device state (qwen38_chain.h), NULL until it runs */
void *vkchain2; /* its layers on COLI_VK_DEV2's device, after the primary's (qwen38_chain.h) */
@@ -2072,9 +2092,14 @@ static void q38_ple_prefetch(Model *m,const int *ids,int S) {
/* 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;
+ int64_t history[2]={0,0};
+ int history_len=0;
+ if(!m->mux_rows){history[0]=m->ple_history[0];history[1]=m->ple_history[1];history_len=m->ple_history_len;}
for(int s=0;s<S;s++){
+ if(m->mux_rows){ /* a multiplexed step: every row is the next token of its own conversation */
+ const Q38Seq *q=m->mux_rows[s].seq;
+ history[0]=q->ple_history[0];history[1]=q->ple_history[1];history_len=q->ple_history_len;
+ }
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++){
@@ -2120,8 +2145,10 @@ static void q38_ple(Model *m,const int *ids,int S,const float *hyper,float *out)
int rows=S-base<B?S-base:B;
for(int r=0;r<rows;r++){
int s=base+r; float *emb=embs+(int64_t)r*E;
- 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;
+ int64_t *hist=m->ple_history; int *hlen=&m->ple_history_len;
+ if(m->mux_rows){hist=m->mux_rows[s].seq->ple_history;hlen=&m->mux_rows[s].seq->ple_history_len;}
+ int64_t p1=*hlen>=1?hist[*hlen-1]:c->eos_id;
+ int64_t p2=*hlen>=2?hist[*hlen-2]:c->eos_id;
if(m->ple_pref&&s<m->ple_pref_rows){
/* gia' in memoria: le ha portate q38_ple_prefetch mentre i primi
* layer calcolavano */
@@ -2131,10 +2158,10 @@ static void q38_ple(Model *m,const int *ids,int S,const float *hyper,float *out)
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);
}
- if(ids[s]==c->eos_id)m->ple_history_len=0;
- else if(m->ple_history_len==0){m->ple_history[0]=ids[s];m->ple_history_len=1;}
- else if(m->ple_history_len==1){m->ple_history[1]=ids[s];m->ple_history_len=2;}
- else {m->ple_history[0]=m->ple_history[1];m->ple_history[1]=ids[s];}
+ if(ids[s]==c->eos_id)*hlen=0;
+ else if(*hlen==0){hist[0]=ids[s];*hlen=1;}
+ else if(*hlen==1){hist[1]=ids[s];*hlen=2;}
+ else {hist[0]=hist[1];hist[1]=ids[s];}
if(s<m->snap_rows){ /* a verify: the history after this row (the ring below) */
memcpy(m->snap_ple_history[s],m->ple_history,sizeof(m->snap_ple_history[s]));
m->snap_ple_history_len[s]=m->ple_history_len;
@@ -2143,6 +2170,7 @@ static void q38_ple(Model *m,const int *ids,int S,const float *hyper,float *out)
q38_dense_matmul(m,keysb,embs,&l->ple_key,rows,E,W);q38_dense_matmul(m,valueb,embs,&l->ple_value,rows,E,H);
for(int r=0;r<rows;r++){
int s=base+r; const float *keys=keysb+(int64_t)r*W,*value=valueb+(int64_t)r*H;
+ if(m->mux_rows) ring=m->mux_rows[s].seq->PLE_conv_state;
for(int b=0;b<C;b++){
q38_rms0(kn+(int64_t)b*H,keys+(int64_t)b*H,l->ple_norm_key+(int64_t)b*H,H,c->eps);
q38_rms0(qn+(int64_t)b*H,hyper+(int64_t)s*W+(int64_t)b*H,l->ple_norm_query+(int64_t)b*H,H,c->eps);
@@ -2272,7 +2300,8 @@ static void q38_deltanet(Model *m,Layer *l,int layer,const float *x,int S,
float *conv=falloc(CD);
float *q=falloc((int64_t)VH*KD),*k=falloc((int64_t)VH*KD);
float *core=falloc(V);
- float *rec=m->DN_rec[layer],*ring=m->DN_conv[layer];
+ /* a multiplexed step parks every conversation: each row's state below */
+ float *rec=m->DN_rec?m->DN_rec[layer]:NULL,*ring=m->DN_conv?m->DN_conv[layer]:NULL;
/* Decode token with the layer on the card: the two gates on the CPU (b and
* a, 48 outputs each), everything else -- in_proj qkv and z, conv,
@@ -2306,6 +2335,7 @@ static void q38_deltanet(Model *m,Layer *l,int layer,const float *x,int S,
q38_dense_matmul(m,aa,chunk,&l->dn_a,rows,H,VH);
for(int s=0;s<rows;s++) {
+ if(m->mux_rows){rec=m->mux_rows[base+s].seq->DN_rec[layer];ring=m->mux_rows[base+s].seq->DN_conv[layer];}
float *qkv_row=qkv+(int64_t)s*CD;
float *z_row=z+(int64_t)s*V;
float *b_row=bb+(int64_t)s*VH;
@@ -2399,15 +2429,18 @@ static void q38_attention(Model *m,Layer *l,int layer,const float *x,int S,int p
* (each s writes only its own row) and must be complete before the
* ranking, which reads the whole IK[0..pos] prefix. Guarded on S>1 so
* decode keeps the serial path it has today. */
+ const Q38Row *mr=m->mux_rows; /* a multiplexed step: each row's own conversation and position */
#pragma omp parallel for schedule(static) if(S>1)
for(int s=0;s<S;s++){
- int pos=pos_base+s;
+ int pos=mr?mr[s].pos:pos_base+s;
+ float *Kl=mr?mr[s].seq->K[layer]:m->K[layer],*Vl=mr?mr[s].seq->V[layer]:m->V[layer];
+ float *IKl=mr?mr[s].seq->IK[layer]:m->IK[layer];
for(int h=0;h<KVH;h++){
float *kh=kp+(int64_t)s*KVH*D+(int64_t)h*D;q38_rms0(kh,kh,l->kn,D,c->eps);q38_rope(kh,D,c->rotary_dim,pos,theta);
- memcpy(m->K[layer]+((int64_t)h*m->kv_cap+pos)*D,kh,(size_t)D*sizeof(float));
- memcpy(m->V[layer]+((int64_t)h*m->kv_cap+pos)*D,vp+(int64_t)s*KVH*D+(int64_t)h*D,(size_t)D*sizeof(float));
+ memcpy(Kl+((int64_t)h*m->kv_cap+pos)*D,kh,(size_t)D*sizeof(float));
+ memcpy(Vl+((int64_t)h*m->kv_cap+pos)*D,vp+(int64_t)s*KVH*D+(int64_t)h*D,(size_t)D*sizeof(float));
}
- memcpy(m->IK[layer]+(int64_t)pos*ID,ip+(int64_t)s*(IQ+1)*ID+(int64_t)IQ*ID,(size_t)ID*sizeof(float));
+ memcpy(IKl+(int64_t)pos*ID,ip+(int64_t)s*(IQ+1)*ID+(int64_t)IQ*ID,(size_t)ID*sizeof(float));
}
float *heads=falloc((int64_t)S*QH*D);
/* Ranking and attention are independent per position: no shared writes
@@ -2426,7 +2459,9 @@ static void q38_attention(Model *m,Layer *l,int layer,const float *x,int S,int p
double qsa_wall_started=now_s();
#pragma omp parallel for schedule(dynamic,8) reduction(+:index_dt,attn_dt) if(S>1)
for(int s=0;s<S;s++){
- int pos=pos_base+s,visible=pos+1,blocks=visible/R,tail=blocks*R;
+ int pos=mr?mr[s].pos:pos_base+s,visible=pos+1,blocks=visible/R,tail=blocks*R;
+ const float *Kl=mr?mr[s].seq->K[layer]:m->K[layer],*Vl=mr?mr[s].seq->V[layer]:m->V[layer];
+ const float *IKl=mr?mr[s].seq->IK[layer]:m->IK[layer];
double phase_started=now_s();
float *qidx=falloc((int64_t)IQ*ID),*pool=falloc(ID);
int *selected=(int*)malloc((size_t)maxsel*sizeof(int));
@@ -2436,7 +2471,7 @@ static void q38_attention(Model *m,Layer *l,int layer,const float *x,int S,int p
Q38Block *rank=blocks?(Q38Block*)malloc((size_t)blocks*sizeof(Q38Block)):NULL;
if(blocks&&!rank){fprintf(stderr,"OOM QSA block ranking\n");exit(1);}
for(int b=0;b<blocks;b++){
- memset(pool,0,(size_t)ID*sizeof(float));for(int r=0;r<R;r++){const float *raw=m->IK[layer]+(int64_t)(b*R+r)*ID;for(int d=0;d<ID;d++)pool[d]+=raw[d]/R;}
+ memset(pool,0,(size_t)ID*sizeof(float));for(int r=0;r<R;r++){const float *raw=IKl+(int64_t)(b*R+r)*ID;for(int d=0;d<ID;d++)pool[d]+=raw[d]/R;}
q38_rms0(pool,pool,l->idx_kn,ID,c->eps);q38_rope(pool,ID,c->rotary_dim,b*R,theta);
float score=0.f;for(int h=0;h<IQ;h++){float a=0.f;for(int d=0;d<ID;d++)a+=qidx[(int64_t)h*ID+d]*pool[d];if(a>0.f)score+=a;}rank[b]=(Q38Block){score/sqrtf((float)ID),b};
}
@@ -2448,10 +2483,10 @@ static void q38_attention(Model *m,Layer *l,int layer,const float *x,int S,int p
float *qraw=qp+(int64_t)s*QH*2*D+(int64_t)h*2*D;
float *qh=falloc(D);memcpy(qh,qraw,(size_t)D*sizeof(float));q38_rms0(qh,qh,l->qn,D,c->eps);q38_rope(qh,D,c->rotary_dim,pos,theta);
float *score=falloc(nsel);float mx=-INFINITY;
- int khidx=h/(QH/KVH);for(int j=0;j<nsel;j++){const float *kh=m->K[layer]+((int64_t)khidx*m->kv_cap+selected[j])*D;float a=0.f;for(int d=0;d<D;d++)a+=qh[d]*kh[d];a/=sqrtf((float)D);score[j]=a;if(a>mx)mx=a;}
+ int khidx=h/(QH/KVH);for(int j=0;j<nsel;j++){const float *kh=Kl+((int64_t)khidx*m->kv_cap+selected[j])*D;float a=0.f;for(int d=0;d<D;d++)a+=qh[d]*kh[d];a/=sqrtf((float)D);score[j]=a;if(a>mx)mx=a;}
float den=0.f;for(int j=0;j<nsel;j++){score[j]=expf(score[j]-mx);den+=score[j];}
float *oh=heads+(int64_t)s*QH*D+(int64_t)h*D;memset(oh,0,(size_t)D*sizeof(float));
- for(int j=0;j<nsel;j++){float a=score[j]/den;const float *vh=m->V[layer]+((int64_t)khidx*m->kv_cap+selected[j])*D;for(int d=0;d<D;d++)oh[d]+=a*vh[d];}
+ for(int j=0;j<nsel;j++){float a=score[j]/den;const float *vh=Vl+((int64_t)khidx*m->kv_cap+selected[j])*D;for(int d=0;d<D;d++)oh[d]+=a*vh[d];}
for(int d=0;d<D;d++)oh[d]*=q38_sigmoid(qraw[D+d]);free(qh);free(score);
}
attn_dt+=now_s()-phase_started;
@@ -3366,6 +3401,101 @@ static float *q38_forward(Model *m,const int *ids,int S,int pos_base,int nlogits
free(mixed);free(inject);free(block);return logit;
}
+/* ---- several conversations at once (KV_SLOTS>1, qwen38.c's serve_mux) -------
+ * Each conversation owns a Q38Seq: its K, V and indexer rows, its DeltaNet state,
+ * its PLE history and ring, its record of the tokens its rows hold. The Model holds
+ * the conversation a prefill runs on (q38_seq_swap trades it for a parked one); a
+ * decode step parks them all and runs one forward over a row of each
+ * (q38_forward_rows). The MTP head stays unloaded and nothing drafts: speculation
+ * follows one sequence. */
+static void q38_seq_swap(Model *m,Q38Seq *q) {
+#define Q38_SEQ_SWAP(T,a,b) do{T t_=(a);(a)=(b);(b)=t_;}while(0)
+ Q38_SEQ_SWAP(float**,m->K,q->K); Q38_SEQ_SWAP(float**,m->V,q->V); Q38_SEQ_SWAP(float**,m->IK,q->IK);
+ Q38_SEQ_SWAP(float**,m->DN_rec,q->DN_rec); Q38_SEQ_SWAP(float**,m->DN_conv,q->DN_conv);
+ Q38_SEQ_SWAP(int,m->kv_len,q->kv_len); Q38_SEQ_SWAP(kv_prefix,m->kvp,q->kvp);
+ Q38_SEQ_SWAP(int64_t*,m->ple_history,q->ple_history);
+ Q38_SEQ_SWAP(float*,m->PLE_conv_state,q->PLE_conv_state);
+ Q38_SEQ_SWAP(int,m->ple_history_len,q->ple_history_len);
+#undef Q38_SEQ_SWAP
+}
+
+/* A conversation's state of its own, the shape the Model's has (q38_alloc_state,
+ * ensure_kv): 0 when out of memory, with what was allocated freed. */
+static void q38_seq_free(Model *m,Q38Seq *q);
+static int q38_seq_alloc(Model *m,Q38Seq *q) {
+ Cfg *c=&m->c; memset(q,0,sizeof *q);
+ q->K=(float**)calloc((size_t)c->layers+1,sizeof(float*)); q->V=(float**)calloc((size_t)c->layers+1,sizeof(float*));
+ q->IK=(float**)calloc((size_t)c->layers+1,sizeof(float*));
+ q->DN_rec=(float**)calloc((size_t)c->layers,sizeof(float*)); q->DN_conv=(float**)calloc((size_t)c->layers,sizeof(float*));
+ int ok=q->K&&q->V&&q->IK&&q->DN_rec&&q->DN_conv&&kv_prefix_alloc(&q->kvp,m->kv_cap);
+ for(int i=0;ok&&i<c->layers;i++){
+ if(c->is_attn[i]){
+ size_t kv=(size_t)c->kv_heads*m->kv_cap*c->head_dim;
+ q->K[i]=(float*)malloc(kv*sizeof(float)); q->V[i]=(float*)malloc(kv*sizeof(float));
+ q->IK[i]=(float*)malloc((size_t)m->kv_cap*c->idx_dim*sizeof(float));
+ ok=q->K[i]&&q->V[i]&&q->IK[i];
+ } else if(i>=m->range_begin&&i<m->range_end){
+ q->DN_rec[i]=(float*)calloc((size_t)c->dn_vheads*c->dn_kdim*c->dn_vdim,sizeof(float));
+ q->DN_conv[i]=(float*)calloc((size_t)c->dn_conv_dim*(c->dn_convk-1),sizeof(float));
+ ok=q->DN_rec[i]&&q->DN_conv[i];
+ }
+ }
+ if(ok&&c->ple_layer>=m->range_begin&&c->ple_layer<m->range_end){
+ q->ple_history=(int64_t*)calloc(2,sizeof(int64_t));
+ q->PLE_conv_state=(float*)calloc((size_t)c->hc_width*(c->ple_convk-1)*c->ngram_size,sizeof(float));
+ ok=q->ple_history&&q->PLE_conv_state;
+ }
+ if(!ok){q38_seq_free(m,q);return 0;}
+ return 1;
+}
+static void q38_seq_free(Model *m,Q38Seq *q) {
+ for(int i=0;i<m->c.layers;i++){
+ if(q->K)free(q->K[i]); if(q->V)free(q->V[i]); if(q->IK)free(q->IK[i]);
+ if(q->DN_rec)free(q->DN_rec[i]); if(q->DN_conv)free(q->DN_conv[i]);
+ }
+ free(q->K);free(q->V);free(q->IK);free(q->DN_rec);free(q->DN_conv);
+ kv_prefix_free(&q->kvp); free(q->ple_history); free(q->PLE_conv_state);
+ memset(q,0,sizeof *q);
+}
+
+/* One decode step of several conversations: row s is the token ids[s] at
+ * rows[s].pos of the conversation rows[s].seq, every conversation parked. The
+ * dense matrices, the routed experts, the residual reads and lm_head run once
+ * over the S rows; the attention, DeltaNet and PLE read and write each row's own
+ * conversation (m->mux_rows). The CPU kernels give a row the same bits whatever S
+ * is (as a verify's rows, below), so each conversation gets the logits it would
+ * alone. Decode rows are never an image's. S rows of logits come back. */
+static float *q38_forward_rows(Model *m,const Q38Row *rows,const int *ids,int S) {
+ Cfg *c=&m->c;int H=c->hidden,W=c->hc_width,C=c->hc_count;
+ m->timers.forwards++;
+ m->mux_rows=rows;
+ float *hyper=falloc((int64_t)S*W);
+ 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;
+ q38_weight_row(&m->embed,ids[s],e);
+ for(int b=1;b<C;b++)memcpy(e+(int64_t)b*H,e,(size_t)H*sizeof(float));
+ }
+ 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++)
+ q38_layer_forward(m,i,hyper,ids,S,0,mixed,inject,block);
+ q38_gr_read(m,&m->final_gr,hyper,S,mixed,NULL);
+ m->mux_rows=NULL;
+ for(int s=0;s<S;s++){
+ Q38Seq *q=rows[s].seq;
+ q->kv_len=rows[s].pos+1;
+ if(q->kvp.len>rows[s].pos)q->kvp.len=rows[s].pos;
+ kv_prefix_record(&q->kvp,ids+s,rows[s].pos,1);
+ }
+ float *logit=falloc((int64_t)S*c->vocab);
+ double phase_started=now_s();
+ q38_weight_matmul(logit,mixed,&m->lm_head,S,H,c->vocab);
+ q38_tm_add(m,Q38_TM_LM_HEAD,phase_started);
+ free(hyper);free(mixed);free(inject);free(block);
+ return logit;
+}
+
/* ---- the MTP head (Q38_MTP=1) ---------------------------------------------
* The checkpoint carries one more decoder layer under mtp.*, trained to read
* the model's state at position p together with the token at p+1 and to say
diff --git a/c/tests/serve_mux_check.py b/c/tests/serve_mux_check.py
new file mode 100644
index 00000000..56ff75b0
--- /dev/null
+++ b/c/tests/serve_mux_check.py
@@ -0,0 +1,185 @@
+#!/usr/bin/env python3
+"""Several conversations at once (KV_SLOTS=n): every request's frames against the same
+request served alone.
+
+The multiplexed session gets each wave of requests in one write, every request on its
+own cache slot, so the engine decodes them as one batch of rows at different positions
+that grows as requests come in and shrinks as they end. The second wave goes back to
+each slot: one turn extends its conversation, one goes back inside it, one starts over;
+one request of it is stopped and one cancelled after their first token. The reference
+serves each slot's requests in a session of its own with KV_SLOTS=1, one after the
+other, so each turn finds the prompt cache its conversation's turns left there. Greedy sampling throughout: every DATA frame, its text and its
+logprobs, must be the reference's, byte for byte (the CPU kernels give a row the same
+bits in a batch of any size), and the engine's report must show decode steps of more
+than one row.
+
+usage: serve_mux_check.py <engine> <snapshot> <slots> [KEY=VALUE ...] (extra environment)
+MUX_TOL: compare logprobs within this bound instead of byte for byte (an engine whose
+batched kernels sum in another order). MUX_IDS=numeric: request ids 1, 2, ... instead of
+r0, r1, ...; MUX_GBYTES=1: the grammar-bytes field (0) before the options (colibri).
+"""
+import os
+import re
+import subprocess
+import sys
+import threading
+
+READY = b"\x01\x01READY\x01\x01"
+
+
+def waves(n):
+ base = bytes(range(65, 65 + 23))
+ one = [(base[:7 + 3 * i] + bytes([97 + i]) * (i + 1), 4 + 2 * (i % 3), "logprobs=2" if i % 2 else "")
+ for i in range(n)]
+ two = []
+ for i, (prompt, _, _) in enumerate(one):
+ if i % 3 == 0:
+ two.append((prompt + b"xyz", 6, "")) # after the reply: the prompt and a new tail
+ elif i % 3 == 1:
+ two.append((prompt[:6] + b"QRS", 5, "logprobs=1")) # back inside the prompt
+ else:
+ two.append((b"zz" + prompt, 5, "")) # a new conversation on the slot
+ return [one, two]
+
+
+class Session:
+ def __init__(self, engine, snap, slots, extra):
+ env = dict(os.environ, SNAP=snap, SERVE="1", SERVE_BATCH="1", KV_SLOTS=str(slots), **extra)
+ self.p = subprocess.Popen([engine, "8", "8"], env=env, stdin=subprocess.PIPE,
+ stdout=subprocess.PIPE, stderr=subprocess.PIPE)
+ self.err = []
+ threading.Thread(target=lambda: [self.err.append(l) for l in iter(self.p.stderr.readline, b"")],
+ daemon=True).start()
+ while True:
+ line = self.p.stdout.readline()
+ if not line:
+ self.die("engine exited before READY")
+ if READY in line:
+ break
+ self.n = 0
+
+ def die(self, why):
+ sys.exit(why + ":\n" + b"".join(self.err).decode(errors="replace")[-4000:])
+
+ def rid(self):
+ self.n += 1
+ return str(self.n) if os.environ.get("MUX_IDS") == "numeric" else f"r{self.n}"
+
+ def header(self, rid, slot, prompt, max_tok, ext):
+ return (f"SUBMIT {rid} {slot} {len(prompt)} {max_tok} 0 1" +
+ (" 0" if os.environ.get("MUX_GBYTES") == "1" else "") +
+ (f" {ext}" if ext else "") + "\n").encode() + prompt + b"\n"
+
+ def collect(self, ids, out, controls=None):
+ """Frames until every request in ids is DONE or ERROR. controls: {id: b"STOP"
+ or b"CANCEL"}, sent after that request's first DATA frame."""
+ open_ids, sent = set(ids), set()
+ while open_ids:
+ line = self.p.stdout.readline()
+ if not line:
+ self.die("engine died")
+ parts = line.split()
+ kind = parts[0] if parts else b""
+ if kind in (b"DATA", b"ECHO"):
+ rid = parts[1].decode()
+ body = self.p.stdout.read(int(parts[2]))
+ self.p.stdout.readline()
+ out.setdefault(rid, []).append(line.rstrip() + b" " + body)
+ if controls and rid in controls and rid not in sent:
+ sent.add(rid)
+ self.p.stdin.write(controls[rid] + b" " + rid.encode() + b"\n")
+ self.p.stdin.flush()
+ elif kind == b"DONE":
+ rid = parts[1].decode()
+ out.setdefault(rid, []).append(b"DONE")
+ open_ids.discard(rid)
+ elif kind == b"ERROR":
+ rid = parts[1].decode()
+ out.setdefault(rid, []).append(b"ERROR " + b" ".join(parts[2:]))
+ open_ids.discard(rid)
+
+ def close(self):
+ self.p.stdin.close()
+ self.p.wait(timeout=600)
+ return b"".join(self.err).decode(errors="replace")
+
+
+def main():
+ engine, snap, slots = sys.argv[1], sys.argv[2], int(sys.argv[3])
+ extra = dict(a.split("=", 1) for a in sys.argv[4:])
+ plan = waves(slots)
+ # the reference: each slot's conversation alone, in a session of its own, so its
+ # turns find the prompt cache its turns left (what a slot keeps between turns)
+ want = [None] * sum(len(w) for w in plan)
+ for slot in range(slots):
+ ref = Session(engine, snap, 1, extra)
+ for w, wave in enumerate(plan):
+ prompt, max_tok, ext = wave[slot]
+ rid = ref.rid()
+ ref.p.stdin.write(ref.header(rid, 0, prompt, max_tok, ext))
+ ref.p.stdin.flush()
+ got = {}
+ ref.collect([rid], got)
+ want[w * slots + slot] = got[rid]
+ ref.close()
+ # the multiplexed session: a wave in one write
+ mux = Session(engine, snap, slots, extra)
+ got_all, order, controls = {}, [], {}
+ for w, wave in enumerate(plan):
+ blob, ids = b"", []
+ for slot, (prompt, max_tok, ext) in enumerate(wave):
+ rid = mux.rid()
+ ids.append(rid)
+ blob += mux.header(rid, slot, prompt, max_tok, ext)
+ order += ids
+ if w == 1 and len(ids) >= 3: # the second wave: one stopped, one cancelled after their first token
+ controls = {ids[0]: b"STOP", ids[2]: b"CANCEL"}
+ mux.p.stdin.write(blob)
+ mux.p.stdin.flush()
+ mux.collect(ids, got_all, controls)
+ err = mux.close()
+ tol = float(os.environ.get("MUX_TOL", "0"))
+ bad = []
+ def strip(frames): # the request id differs between the sessions
+ return [f.split(b" ", 2)[2] if f.startswith((b"DATA", b"ECHO")) else f for f in frames]
+ for k, rid in enumerate(order):
+ a, b = strip(want[k]), strip(got_all.get(rid, []))
+ if rid in controls:
+ # stopped or cancelled after its first token: what it sent is the start of the
+ # reference's, and it ends in DONE (a stop) or ERROR CANCELLED (a cancel), unless
+ # it was through before the command arrived
+ body, end = b[:-1], b[-1:]
+ full = b == a
+ ok = len(body) >= 1 and body == a[:len(body)] and (
+ full or end == ([b"DONE"] if controls[rid] == b"STOP" else [b"ERROR CANCELLED"]))
+ if not ok:
+ bad.append(f"{rid}: {controls[rid].decode()} after the first token gave {b}, the reference {a}")
+ continue
+ if tol and len(a) == len(b):
+ same = all(x == y or close(x, y, tol) for x, y in zip(a, b))
+ else:
+ same = a == b
+ if not same:
+ bad.append(f"{rid} (request {k}): {b} != {a}")
+ if bad:
+ print("\n".join(bad))
+ print(err[-3000:])
+ sys.exit(f"FAIL: {len(bad)} of {len(order)} requests differ from the same request served alone")
+ m = re.search(r"(\d+) decode steps, (\d+) rows", err)
+ if not m or int(m.group(2)) <= int(m.group(1)):
+ print(err[-3000:])
+ sys.exit("FAIL: no decode step of more than one row (the report says " +
+ (m.group(0) if m else "nothing") + ")")
+ print(f"OK {engine} KV_SLOTS={slots}: {len(order)} requests as they are alone, {m.group(0)}")
+
+
+def close(x, y, tol):
+ """Two DATA frames that differ only in the last digits of their logprobs."""
+ num = re.compile(rb"-?\d+\.\d+")
+ if num.sub(b"#", x) != num.sub(b"#", y):
+ return False
+ return all(abs(float(p) - float(q)) <= tol for p, q in zip(num.findall(x), num.findall(y)))
+
+
+if __name__ == "__main__":
+ main()