Run frontier MoE models on hardware you already own — pure C, zero deps, experts streamed from disk. Tiny engine, immense model. 🐦
C
feat: integrate Kimi chat with TUI and Web
ZacharyZcR5450c27e4d1b
diff --git a/c/coli b/c/coliindex fdb7f7b2..d31f98ac 100755--- a/c/coli+++ b/c/coli@@ -152,13 +152,44 @@ def hline(w): return f"{C.dgray}{'─'*w}{C.r}"# ---------- util ----------def term_w(): return min(shutil.get_terminal_size((80,20)).columns, 100)-def need_model(model):+def model_arch(model):+ try:+ with open(os.path.join(model, "config.json"), encoding="utf-8") as f:+ model_type = (json.load(f).get("model_type") or "").lower()+ except (OSError, ValueError, TypeError):+ return "glm"+ if "inkling" in model_type:+ return "inkling"+ if "kimi" in model_type:+ return "kimi"+ return "glm"++def engine_for(model):+ arch = model_arch(model)+ if arch == "glm" or os.environ.get("COLI_ENGINE"):+ return GLM+ name = "inkling" if arch == "inkling" else "kimi_k3"+ local = os.path.join(HERE, name + _EXE)+ return local if os.path.exists(local) else os.path.join(_LIBEXEC, name + _EXE)++def need_model(model, engine=None):if not os.path.isdir(model):sys.exit(f"{C.yel}model not found:{C.r} {model}\n set COLI_MODEL or use --model")if not os.path.exists(os.path.join(model,"tokenizer.json")):sys.exit(f"{C.yel}tokenizer.json is missing from {model}{C.r}")- if not os.path.exists(GLM):- sys.exit(f"{C.yel}engine is not built.{C.r} Run: coli build")+ engine = engine or engine_for(model)+ if not os.path.exists(engine):+ arch = model_arch(model)+ target = "kimi_k3" if arch == "kimi" else "inkling" if arch == "inkling" else "colibri"+ sys.exit(f"{C.yel}{target} engine is not built.{C.r} Run: make -C c {target}")++def env_for_engine(a, arch):+ if arch == "glm":+ return env_for(a)+ env = os.environ.copy()+ if a.ngen: env["NGEN"] = str(a.ngen)+ if a.temp is not None: env["COLI_TEMP"] = str(a.temp)+ return envdef cuda_binary():if not os.path.exists(GLM): return False@@ -702,6 +733,34 @@ def cmd_chat(a):chat_attached(a, base, mid); returnif getattr(a,"attach",None):sys.exit(f"--attach: no coli serve answering at {base} (start one with: coli serve --model <dir>)")+ arch=model_arch(a.model)+ if arch!="glm":+ engine=engine_for(a.model)+ need_model(a.model,engine)+ model_id="kimi-k3-colibri" if arch=="kimi" else "inkling-colibri"+ banner(f"chat · {model_id} · local server")+ import openai_server+ cmd=[sys.executable,openai_server.__file__,"--model",a.model,+ "--engine",engine,"--arch",arch,"--model-id",model_id,+ "--host","127.0.0.1","--port","8000","--max-tokens",str(a.ngen)]+ if a.api_key: cmd+=["--api-key",a.api_key]+ p=subprocess.Popen(cmd,env=env_for_engine(a,arch))+ try:+ sp=Spinner(f"loading {model_id}…"); sp.start()+ for _ in range(1800):+ if p.poll() is not None:+ sp.stop(); sys.exit(f"{model_id} server exited while loading")+ if server_probe("http://127.0.0.1:8000",a.api_key,timeout=1.0):+ sp.stop()+ chat_attached(a,"http://127.0.0.1:8000",model_id)+ return+ time.sleep(1)+ sp.stop(); sys.exit(f"timed out loading {model_id}")+ finally:+ if p.poll() is None:+ p.terminate()+ try: p.wait(timeout=10)+ except subprocess.TimeoutExpired: p.kill()need_model(a.model)banner(f"chat · {os.path.basename(a.model)} · ram {a.ram or '-'}GB · topp {a.topp or 'off'}")kv_resume_notice(a.model)@@ -840,16 +899,23 @@ def cmd_chat(a):def serve_pidfile(port): return os.path.join(tempfile.gettempdir(), f"coli-serve-{port}.pid")def cmd_serve(a):- need_model(a.model)+ arch=model_arch(a.model)+ engine=engine_for(a.model)+ need_model(a.model,engine)+ if arch!="glm" and a.kv_slots!=1:+ sys.exit(f"{arch} currently supports exactly one KV slot")# pidfile: cosi' `coli stop` spegne tutto con un comando, senza pkill a mano.# EN: pidfile so `coli stop` can shut everything down without manual pkill.try:with open(serve_pidfile(a.port),"w") as f: f.write(f"{os.getpid()} {a.model}\n")except OSError: pass- from openai_server import serve+ import openai_server+ openai_server.ARCH=arch+ model_id=a.model_id or ("kimi-k3-colibri" if arch=="kimi" else+ "inkling-colibri" if arch=="inkling" else "glm-5.2-colibri")try:- serve(a.model, a.host, a.port, a.model_id, a.api_key,- a.cap,a.ngen,GLM,env_for(a),a.cors_origin,+ openai_server.serve(a.model,a.host,a.port,model_id,a.api_key,+ a.cap,a.ngen,engine,env_for_engine(a,arch),a.cors_origin,a.max_queue,a.queue_timeout,a.kv_slots,allowed_hosts=a.allowed_host)finally:try: os.unlink(serve_pidfile(a.port))@@ -878,7 +944,7 @@ def cmd_stop(a):if "coli" in cmd and " serve" in cmd and pid!=os.getpid():if not any(p==pid for p,_ in targets): targets.append((pid,"coli serve (cmdline)"))comm=open(f"/proc/{pd}/comm").read().strip()- if comm in ("colibri","glm","exe","olmoe"):+ if comm in ("colibri","glm","exe","olmoe","inkling","kimi_k3"):env=open(f"/proc/{pd}/environ","rb").read().replace(b"\0",b"\n").decode("utf-8","replace")if "SERVE=1" in env: targets.append((pid,f"engine `{comm}` (SERVE=1)"))except (OSError,PermissionError): continue@@ -1008,7 +1074,7 @@ def main():pc.add_argument("--api-key", default=os.environ.get("COLI_API_KEY"))ps=sub.add_parser("serve", parents=[common])ps.add_argument("--host",default="127.0.0.1"); ps.add_argument("--port",type=int,default=8000)- ps.add_argument("--model-id",default=os.environ.get("COLI_MODEL_ID","glm-5.2-colibri"))+ ps.add_argument("--model-id",default=os.environ.get("COLI_MODEL_ID"))ps.add_argument("--api-key",default=os.environ.get("COLI_API_KEY"))ps.add_argument("--cors-origin",action="append",default=None)ps.add_argument("--max-queue",type=int,default=int(os.environ.get("COLI_MAX_QUEUE","8")))@@ -1021,7 +1087,7 @@ def main():pst.add_argument("--port",type=int,default=8000); pst.add_argument("--dry-run",action="store_true")pw=sub.add_parser("web", parents=[common], help="serve + open the dashboard in a browser")for arg,kw in (("--host",dict(default="127.0.0.1")),("--port",dict(type=int,default=8000)),- ("--model-id",dict(default=os.environ.get("COLI_MODEL_ID","glm-5.2-colibri"))),+ ("--model-id",dict(default=os.environ.get("COLI_MODEL_ID"))),("--api-key",dict(default=os.environ.get("COLI_API_KEY"))),("--cors-origin",dict(action="append",default=None)),("--max-queue",dict(type=int,default=int(os.environ.get("COLI_MAX_QUEUE","8")))),diff --git a/c/kimi_k3.c b/c/kimi_k3.cindex 58cbac92..4ea1e288 100644--- a/c/kimi_k3.c+++ b/c/kimi_k3.c@@ -62,6 +62,7 @@#include <time.h>#if defined(__APPLE__) || defined(__linux__) || defined(__FreeBSD__)#include <sys/resource.h>+#include <sys/select.h>#include <unistd.h>#endif#include <pthread.h>@@ -1090,14 +1091,24 @@ static void kv_alloc(Model *m, int max_t){}}-static int sample_tok(const float *lo, int V, float temp){+typedef struct { float p; int id; } SampleProb;+static int sample_prob_desc(const void *a,const void *b){+ float d=((const SampleProb*)b)->p-((const SampleProb*)a)->p;+ return d>0?1:d<0?-1:0;+}+static int sample_tok(const float *lo, int V, float temp, float top_p){if(temp<=0.f){ int b=0; for(int i=1;i<V;i++) if(lo[i]>lo[b]) b=i; return b; }- float *p=falloc(V); float mx=lo[0];+ SampleProb *rank=malloc((size_t)V*sizeof(SampleProb)); float mx=lo[0];+ if(!rank){ fprintf(stderr,"OOM sampling\n"); exit(1); }for(int i=1;i<V;i++) if(lo[i]>mx) mx=lo[i];- double s=0; for(int i=0;i<V;i++){ p[i]=expf((lo[i]-mx)/temp); s+=p[i]; }- double r=((double)rand()/RAND_MAX)*s, acc=0; int pick=V-1;- for(int i=0;i<V;i++){ acc+=p[i]; if(acc>=r){ pick=i; break; } }- free(p); return pick;+ double sum=0;+ for(int i=0;i<V;i++){ float p=expf((lo[i]-mx)/temp); sum+=p; rank[i]=(SampleProb){p,i}; }+ qsort(rank,(size_t)V,sizeof(SampleProb),sample_prob_desc);+ double cut=(top_p>0.f&&top_p<1.f)?top_p*sum:sum, kept=0; int n=0;+ while(n<V&&kept<cut) kept+=rank[n++].p;+ double r=((double)rand()/RAND_MAX)*kept, acc=0; int pick=rank[0].id;+ for(int i=0;i<n;i++){ acc+=rank[i].p; if(acc>=r){ pick=rank[i].id; break; } }+ free(rank); return pick;}/* ---------- K3 XTML chat format (faithful to the shipped encoding_k3.py) --@@ -1155,20 +1166,259 @@ static int chat_build(Tok *T, const char *sys, const char *user, int thinking,return b.n;}+static void chat_message(ChatB *b, const char *role, const char *text, int assistant){+ cb_open(b,"message",role);+ if(assistant) cb_open(b,"response",NULL);+ cb_text(b,text);+ if(assistant) cb_close(b,"response");+ cb_close(b,"message");+ cb_special(b,b->sp_eom);+}++static void chat_assistant(ChatB *b, const char *reasoning, const char *text){+ cb_open(b,"message","assistant");+ cb_open(b,"think",NULL); cb_text(b,reasoning); cb_close(b,"think");+ cb_open(b,"response",NULL); cb_text(b,text); cb_close(b,"response");+ cb_close(b,"message"); cb_special(b,b->sp_eom);+}++/* Internal gateway payload. Length framing keeps arbitrary UTF-8/newlines in+ * message content while preserving the segment boundaries required by K3's+ * rank-BPE chat template:+ * K3CHAT1\n+ * M <role> <utf8-bytes>\n<content> ...+ * G <thinking>\n+ */+static int chat_build_wire(Tok *T, const char *wire, int nwire, int *thinking,+ int *ids, int cap, int *sp){+ ChatB b={T,ids,0,cap,+ chat_special(T,"<|open|>"), chat_special(T,"<|close|>"),+ chat_special(T,"<|sep|>"), chat_special(T,"<|end_of_msg|>")};+ if(b.sp_open<0||b.sp_close<0||b.sp_sep<0||b.sp_eom<0) return -1;+ sp[0]=b.sp_open; sp[1]=b.sp_close; sp[2]=b.sp_sep; sp[3]=b.sp_eom;+ const char *p=wire, *end=wire+nwire;+ if(nwire<8||memcmp(p,"K3CHAT1\n",8)) return -1;+ p+=8; *thinking=0;+ while(p<end){+ const char *nl=memchr(p,'\n',(size_t)(end-p));+ if(!nl) return -1;+ if(*p=='G'){+ int v=0;+ if(sscanf(p,"G %d",&v)!=1) return -1;+ *thinking=!!v; p=nl+1; break;+ }+ if(*p=='A'){+ int nr=-1, nt=-1;+ if(sscanf(p,"A %d %d",&nr,&nt)!=2||nr<0||nt<0||nl+1+nr+nt>end) return -1;+ char *reason=malloc((size_t)nr+1), *text=malloc((size_t)nt+1);+ if(!reason||!text){ fprintf(stderr,"OOM chat assistant\n"); exit(1); }+ memcpy(reason,nl+1,(size_t)nr); reason[nr]=0;+ memcpy(text,nl+1+nr,(size_t)nt); text[nt]=0;+ chat_assistant(&b,reason,text);+ free(reason); free(text); p=nl+1+nr+nt; continue;+ }+ char role[16]; int nb=-1;+ if(sscanf(p,"M %15s %d",role,&nb)!=2||nb<0||nl+1+nb>end) return -1;+ char *text=malloc((size_t)nb+1);+ if(!text){ fprintf(stderr,"OOM chat message\n"); exit(1); }+ memcpy(text,nl+1,(size_t)nb); text[nb]=0;+ const char *r=!strcmp(role,"developer")?"system":role;+ if(strcmp(r,"system")&&strcmp(r,"user")&&strcmp(r,"assistant")){ free(text); return -1; }+ chat_message(&b,r,text,!strcmp(r,"assistant"));+ free(text); p=nl+1+nb;+ }+ cb_open(&b,"message","assistant");+ cb_open(&b,*thinking?"think":"response",NULL);+ return b.n;+}++/* ---------- serve mode: shared openai_server.py protocol ---------- */+typedef struct {+ char id[64];+ int max_tok;+ float temp, top_p;+ char *payload;+ int plen;+} ServeReq;++static void model_state_reset(Model *m){+ Cfg *c=&m->c;+ for(int i=0;i<c->n_layers;i++){+ if(m->L[i].kda){+ memset(m->kstate[i],0,(size_t)c->kda_heads*c->kda_hd*c->kda_hd*sizeof(float));+ memset(m->cwq[i],0,(size_t)c->kda_proj*c->conv_k*sizeof(float));+ memset(m->cwk[i],0,(size_t)c->kda_proj*c->conv_k*sizeof(float));+ memset(m->cwv[i],0,(size_t)c->kda_proj*c->conv_k*sizeof(float));+ }+ if(m->Lc&&m->Lc[i]) free(m->Lc[i]);+ if(m->Rc&&m->Rc[i]) free(m->Rc[i]);+ }+ free(m->Lc); free(m->Rc);+ m->Lc=NULL; m->Rc=NULL; m->max_t=0;+}++static int serve_stdin_readable(void){+ fd_set r; struct timeval tv={0,0};+ FD_ZERO(&r); FD_SET(0,&r);+ return select(1,&r,NULL,NULL,&tv)>0;+}++static int serve_read_req(ServeReq *q, const char *active){+ char line[512], cmd[16], id[64];+ if(!fgets(line,sizeof(line),stdin)) return -1;+ if(sscanf(line,"%15s %63s",cmd,id)<2) return 0;+ if(!strcmp(cmd,"CANCEL")||!strcmp(cmd,"STOP")) return active&&!strcmp(active,id);+ 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){+ printf("ERROR %s bad submit header\n",id); fflush(stdout); return 0;+ }+ (void)slot;+ 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; }+ (void)fgetc(stdin); payload[plen]=0;+ snprintf(q->id,sizeof(q->id),"%s",id);+ q->max_tok=max_tok; q->temp=temp; q->top_p=top_p;+ q->payload=payload; q->plen=plen;+ return 2;+}++static void serve_data(const char *id, const char *p, int n){+ if(n<=0) return;+ printf("DATA %s %d\n",id,n);+ fwrite(p,1,(size_t)n,stdout); fputc('\n',stdout); fflush(stdout);+}++static void serve_one(Model *m, Tok *T, ServeReq *q){+ int cap=65536, *ids=malloc((size_t)cap*sizeof(int)), np=0;+ if(!ids){ printf("ERROR %s out of memory\n",q->id); fflush(stdout); return; }+ int sp[4]={-1,-1,-1,-1}, chat=0, thinking=0;+ if(m->c.bos>=0) ids[np++]=m->c.bos;+ if(q->plen>=8&&!memcmp(q->payload,"K3CHAT1\n",8)){+ int n=chat_build_wire(T,q->payload,q->plen,&thinking,ids+np,cap-np,sp);+ if(n<0){ printf("ERROR %s invalid K3 chat payload\n",q->id); fflush(stdout); free(ids); return; }+ np+=n; chat=1;+ } else {+ np+=tok_encode(T,q->payload,q->plen,ids+np,cap-np);+ }+ int max_ctx=getenv("K3_MAXT")?atoi(getenv("K3_MAXT")):8192;+ if(np<1||np+q->max_tok>max_ctx){+ 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;+ }+ printf("ACCEPT %s %d\n",q->id,np); fflush(stdout);+ model_state_reset(m);+ kv_alloc(m,np+q->max_tok+8);+ int chunk=getenv("K3_CHUNK")?atoi(getenv("K3_CHUNK")):32;+ if(chunk<1) chunk=1; if(chunk>512) chunk=512;+ double t0=now_s(), a0=m->t_attn, e0=m->t_moe, d0=m->t_eload, h0=m->t_head;+ uint64_t hit0=m->hits, miss0=m->miss;+ float *lo=NULL;+ for(int i=0;i<np;i+=chunk){+ int C=np-i<chunk?np-i:chunk;+ free(lo); lo=step_chunk(m,ids+i,i,C);+ }+ int gen=0, limited=1, cancelled=0, xsup=0, xopen=0, xtl=0;+ char buf[512], xtag[64];+ double tg=now_s();+ for(int s=0;s<q->max_tok&&!cancelled;s++){+ int tk=sample_tok(lo,m->c.vocab,q->temp,q->top_p);+ 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;+ if(chat&&sp[0]>=0){+ if(tk==sp[0]||tk==sp[1]){+ xsup=1; xopen=(tk==sp[0]); xtl=0; show=0;+ } else if(tk==sp[2]){+ if(xsup){+ xsup=0; xtag[xtl]=0;+ if(xopen&&!strcmp(xtag,"response")&&thinking)+ serve_data(q->id,"</think>",8);+ }+ show=0;+ } else if(xsup){+ int nb=tok_decode(T,&tk,1,buf,sizeof(buf)-1);+ if(xtl+nb<(int)sizeof(xtag)){ memcpy(xtag+xtl,buf,(size_t)nb); xtl+=nb; }+ show=0;+ } else if(tk==sp[3]) show=0;+ }+ if(show){+ int nb=tok_decode(T,&tk,1,buf,sizeof(buf)-1);+ serve_data(q->id,buf,nb);+ }+ if(!eos) gen++;+ while(serve_stdin_readable()){+ ServeReq queued={0};+ int r=serve_read_req(&queued,q->id);+ if(r<0){ cancelled=1; break; }+ if(r==1) cancelled=1;+ if(r==2){+ printf("ERROR %s engine busy\n",queued.id); fflush(stdout); free(queued.payload);+ }+ }+ if(cancelled){ limited=0; break; }+ if(eos){ limited=0; break; }+ if(s+1<q->max_tok) lo=step_chunk(m,&tk,np+s,1);+ }+ free(lo); free(ids);+ double dt=now_s()-t0, decode=now_s()-tg;+ uint64_t hits=m->hits-hit0, misses=m->miss-miss0, total=hits+misses;+ printf("DONE %s STAT %d %.3f %.1f %.2f %d %d\n",q->id,gen,+ decode>0?gen/decode:0.0,total?100.0*hits/total:0.0,rss_gb(),np,limited);+ double moe=m->t_moe-e0, disk=m->t_eload-d0;+ printf("PROF %.3f %d %d %.3f %.3f %.3f %.3f %.3f %d\n",+ dt,np,gen,disk,0.0,moe>disk?moe-disk:moe,m->t_attn-a0,m->t_head-h0,gen+1);+ fflush(stdout);+}++static void serve_loop(Model *m, Tok *T){+ setvbuf(stdin,NULL,_IONBF,0);+ fputs("\x01\x01READY\x01\x01\n",stdout);+ printf("STAT 0 0.0 0.0 %.2f 0 0\n",rss_gb());+ fflush(stdout);+ for(;;){+ ServeReq q={0}; int r;+ do r=serve_read_req(&q,NULL); while(r==0);+ if(r<0) return;+ if(r==2){ serve_one(m,T,&q); free(q.payload); }+ }+}+int main(int argc, char **argv){- if(argc<2){+ int serving=getenv("SERVE")&&getenv("SERVE")[0]=='1';+ if(!serving&&argc<2){fprintf(stderr,"usage: %s <model_dir> [prompt] [--ids \"1 2 3\"] [--ngen N]\n",argv[0]);return 1;}- const char *snap=argv[1], *prompt=NULL, *idstr=NULL, *sysmsg=NULL;+ const char *snap=serving?getenv("SNAP"):argv[1], *prompt=NULL, *idstr=NULL, *sysmsg=NULL, *wirepath=NULL;+ if(!snap||!*snap){ fprintf(stderr,"set SNAP=<Kimi K3 snapshot directory>\n"); return 1; }int ngen=32, chat=0;- for(int i=2;i<argc;i++){+ for(int i=serving?1:2;i<argc;i++){if(!strcmp(argv[i],"--ngen")&&i+1<argc) ngen=atoi(argv[++i]);else if(!strcmp(argv[i],"--ids")&&i+1<argc) idstr=argv[++i];else if(!strcmp(argv[i],"--chat")) chat=1;else if(!strcmp(argv[i],"--system")&&i+1<argc) sysmsg=argv[++i];+ else if(!strcmp(argv[i],"--wire-test")&&i+1<argc) wirepath=argv[++i];else if(!prompt) prompt=argv[i];}+ if(wirepath){+ char tp[2048]; snprintf(tp,sizeof(tp),"%s/tokenizer.json",snap);+ Tok wt; tok_load(&wt,tp);+ FILE *wf=fopen(wirepath,"rb"); if(!wf){ perror(wirepath); return 1; }+ fseek(wf,0,SEEK_END); long wn=ftell(wf); fseek(wf,0,SEEK_SET);+ if(wn<0||wn>(1<<24)){ fprintf(stderr,"wire payload too large\n"); fclose(wf); return 1; }+ char *wire=malloc((size_t)wn+1); int *wid=malloc(65536*sizeof(int));+ if(!wire||!wid){ fprintf(stderr,"OOM wire test\n"); return 1; }+ if(fread(wire,1,(size_t)wn,wf)!=(size_t)wn){ fprintf(stderr,"short wire read\n"); return 1; }+ fclose(wf); wire[wn]=0;+ int thinking=0, wsp[4], n=chat_build_wire(&wt,wire,(int)wn,&thinking,wid,65536,wsp);+ if(n<0){ fprintf(stderr,"invalid K3 chat wire payload\n"); return 1; }+ for(int i=0;i<n;i++) printf("%s%d",i?" ":"",wid[i]);+ printf("\n"); free(wire); free(wid); return 0;+ }float temp=getenv("COLI_TEMP")?(float)atof(getenv("COLI_TEMP")):0.f;int nlayers=getenv("K3_LAYERS")?atoi(getenv("K3_LAYERS")):0;Model m;@@ -1193,6 +1443,11 @@ int main(int argc, char **argv){{ char tp[2048]; snprintf(tp,sizeof(tp),"%s/tokenizer.json",snap);FILE *f=fopen(tp,"rb"); if(f){ fclose(f); tok_load(&T,tp); has_tok=1;fprintf(stderr,"[K3] tokenizer.json loaded (family=%s)\n",T.kimi?"kimi":(T.o200k?"o200k":"cl100k")); } }+ if(serving){+ if(!has_tok){ fprintf(stderr,"serve mode needs tokenizer.json\n"); return 1; }+ serve_loop(&m,&T);+ return 0;+ }int sp[4]={-1,-1,-1,-1};int think=getenv("K3_THINK")?atoi(getenv("K3_THINK")):1;if(idstr){@@ -1249,7 +1504,7 @@ int main(int argc, char **argv){int xsup=0, xopen=0; char xtag[64]; int xtl=0;if(chat&&think){ printf("[think] "); fflush(stdout); }for(int s=0;s<ngen;s++){- int t=sample_tok(lo,m.c.vocab,temp);+ int t=sample_tok(lo,m.c.vocab,temp,1.f);free(lo); lo=NULL;int is_eos=0; for(int e=0;e<m.c.n_eos;e++) if(t==m.c.eos[e]) is_eos=1;int show=1;diff --git a/c/openai_server.py b/c/openai_server.pyindex 8b4dfaab..0d5d69d6 100644--- a/c/openai_server.py+++ b/c/openai_server.py@@ -374,7 +374,7 @@ def parse_tool_calls(reply, tools=None):return text.strip(), calls-ARCH = "glm" # set in main(): "glm" | "inkling" (auto-detected from the model's config.json)+ARCH = "glm" # set in main(): "glm" | "inkling" | "kimi" (auto-detected)INK_THINK, INK_TEXT = "<|content_thinking|>", "<|content_text|>"@@ -457,6 +457,42 @@ def split_inkling(text):return _INK_MARKER.sub("", text), _INK_MARKER.sub("", "".join(reasoning))+def render_chat_kimi(messages, enable_thinking=False, reasoning_effort=None, tools=None,+ tool_choice=None):+ """Validated multi-turn K3 payload for the C engine.++ K3's rank-BPE makes ordinary-text segment boundaries part of the tokenizer+ contract. This private length-framed payload preserves roles, UTF-8 bytes,+ and message boundaries; kimi_k3.c constructs the native XTML tokens.+ """+ if not isinstance(messages, list) or not messages:+ raise APIError(400, "`messages` must be a non-empty array.", "messages")+ if tools or tool_choice not in (None, "none"):+ raise APIError(400, "Tool use is not wired up for the Kimi K3 engine yet.",+ "tools", "unsupported_parameter")+ parts = ["K3CHAT1\n"]+ for index, message in enumerate(messages):+ if not isinstance(message, dict):+ raise APIError(400, "Each message must be an object.", f"messages.{index}")+ role = message.get("role")+ if role not in ("system", "developer", "user", "assistant"):+ raise APIError(400, f"Unsupported role {role!r}.", f"messages.{index}.role")+ raw = message.get("content")+ text = content_text(raw, f"messages.{index}.content") if raw is not None else ""+ reasoning = message.get("reasoning_content") if role == "assistant" else None+ if reasoning is not None and not isinstance(reasoning, str):+ raise APIError(400, "`reasoning_content` must be a string.",+ f"messages.{index}.reasoning_content")+ if role == "assistant" and enable_thinking:+ reasoning = reasoning or ""+ parts.append(f"A {len(reasoning.encode('utf-8'))} {len(text.encode('utf-8'))}\n"+ f"{reasoning or ''}{text}")+ else:+ parts.append(f"M {role} {len(text.encode('utf-8'))}\n{text}")+ parts.append(f"G {1 if enable_thinking else 0}\n")+ return "".join(parts)++def render_chat_inkling(messages, enable_thinking=False, reasoning_effort=None, tools=None,tool_choice=None):"""Text-only subset of Inkling's chat_template.jinja: role tokens with@@ -1696,10 +1732,10 @@ class APIHandler(BaseHTTPRequestHandler):sys.stderr.flush()maximum, temperature, top_p, grammar, _requested_stop_sequences = generation_options(body, self.server.max_tokens)- if grammar is not None and ARCH == "inkling":- # inkling.c's serve loop speaks the 6-field SUBMIT header only; sending the+ if grammar is not None and ARCH in ("inkling", "kimi"):+ # sibling engines speak the 6-field SUBMIT header only; sending the# grammar payload extension would desync its stdin framing.- raise APIError(400, "`response_format` grammars are not supported by the Inkling "+ raise APIError(400, f"`response_format` grammars are not supported by the {ARCH} ""engine yet.", "response_format", "unsupported_parameter")stop_sequences, ignore_leading_stop = stop_policy(body, chat)# tools and tool_choice come from chat_completion() already processed/filtered@@ -1995,7 +2031,8 @@ class APIHandler(BaseHTTPRequestHandler):raise APIError(400, "`enable_thinking` must be a boolean.", "enable_thinking")tools = body.get("tools") or body.get("functions") or Nonetool_choice = body.get("tool_choice")- renderer = render_chat_inkling if ARCH == "inkling" else render_chat+ renderer = (render_chat_inkling if ARCH == "inkling" else+ render_chat_kimi if ARCH == "kimi" else render_chat)prompt = renderer(body.get("messages"), enable_thinking, reasoning_effort, tools,tool_choice)self.generation(body, prompt, request_id, True, tools, tool_choice,@@ -2267,6 +2304,8 @@ def serve(model, host="127.0.0.1", port=8000, model_id="glm-5.2-colibri", api_keraise ValueError("queue_timeout must be positive")if not 1 <= kv_slots <= 16:raise ValueError("kv_slots must be between 1 and 16")+ if ARCH in ("inkling", "kimi") and kv_slots != 1:+ raise ValueError(f"{ARCH} engine currently supports exactly one KV slot")if host not in ("127.0.0.1", "localhost", "::1") and not api_key:# (#SEC-6) Fail closed: an unauthenticated engine on a non-loopback bind exposes# a compute-heavy API to the network. Refuse unless explicitly overridden.@@ -2302,7 +2341,7 @@ def main():parser = argparse.ArgumentParser(description=__doc__)parser.add_argument("--model", default=os.environ.get("COLI_MODEL"), required=not os.environ.get("COLI_MODEL"))parser.add_argument("--engine", default=str(default_engine()))- parser.add_argument("--arch", choices=("auto", "glm", "inkling"), default="auto",+ parser.add_argument("--arch", choices=("auto", "glm", "inkling", "kimi"), default="auto",help="chat-template family; auto reads model_type from the model's config.json")parser.add_argument("--host", default="127.0.0.1")parser.add_argument("--port", type=int, default=8000)@@ -2327,11 +2366,14 @@ def main():if ARCH == "auto":try:with open(Path(args.model) / "config.json") as fh:- ARCH = "inkling" if "inkling" in (json.load(fh).get("model_type") or "") else "glm"+ model_type = (json.load(fh).get("model_type") or "").lower()+ ARCH = ("inkling" if "inkling" in model_type else+ "kimi" if "kimi" in model_type else "glm")except OSError:ARCH = "glm"if args.model_id is None:- args.model_id = "inkling-colibri" if ARCH == "inkling" else "glm-5.2-colibri"+ args.model_id = ("inkling-colibri" if ARCH == "inkling" else+ "kimi-k3-colibri" if ARCH == "kimi" else "glm-5.2-colibri")serve(args.model, args.host, args.port, args.model_id, args.api_key,args.cap,args.max_tokens,args.engine,cors_origins=args.cors_origin,max_queue=args.max_queue,queue_timeout=args.queue_timeout,kv_slots=args.kv_slots,diff --git a/c/tests/fixtures/kimi_chat_wire.txt b/c/tests/fixtures/kimi_chat_wire.txtnew file mode 100644index 00000000..dcb36fb1--- /dev/null+++ b/c/tests/fixtures/kimi_chat_wire.txt@@ -0,0 +1,7 @@+K3CHAT1+M system 11+Be precise.M user 11+你好+KimiA 7 9+because你好。M user 8+ContinueG 1diff --git a/c/tests/test_openai_server.py b/c/tests/test_openai_server.pyindex 2bda0cc7..68f883ff 100644--- a/c/tests/test_openai_server.py+++ b/c/tests/test_openai_server.py@@ -16,7 +16,8 @@ from openai_server import (APIError, APIHandler, APIServer, ClientCancelled,READY, Engine, InklingStreamSplit, StopFilter, ThinkingStreamSplit,_engine_error, conversation_cache_slot, generation_options,parse_tool_calls, read_engine_turn,- render_chat, serve, split_thinking_reply, stop_policy)+ render_chat, render_chat_kimi, serve,+ split_thinking_reply, stop_policy)class FakeEngine:@@ -79,6 +80,37 @@ class TemplateTest(unittest.TestCase):"[gMASK]<sop><|system|>Reasoning Effort: High<|user|>Hi<|assistant|><think>",)+ def test_kimi_payload_preserves_utf8_lengths_and_turns(self):+ prompt = render_chat_kimi([+ {"role": "system", "content": "Be precise."},+ {"role": "user", "content": "你好\nKimi"},+ {"role": "assistant", "content": "你好。"},+ {"role": "user", "content": "Continue"},+ ], enable_thinking=True)+ self.assertEqual(+ prompt,+ "K3CHAT1\n"+ "M system 11\nBe precise."+ "M user 11\n你好\nKimi"+ "A 0 9\n你好。"+ "M user 8\nContinue"+ "G 1\n",+ )++ def test_kimi_rejects_tools_and_unknown_roles(self):+ with self.assertRaisesRegex(APIError, "Tool use"):+ render_chat_kimi([{"role": "user", "content": "Hi"}],+ tools=[{"type": "function"}])+ with self.assertRaisesRegex(APIError, "Unsupported role"):+ render_chat_kimi([{"role": "tool", "content": "result"}])++ def test_kimi_preserves_prior_reasoning_channel(self):+ self.assertEqual(+ render_chat_kimi([{"role": "assistant", "reasoning_content": "why",+ "content": "answer"}], enable_thinking=True),+ "K3CHAT1\nA 3 6\nwhyanswerG 1\n",+ )+def test_validates_generation_limits(self):self.assertEqual(generation_options({"max_tokens": 4, "temperature": 0, "top_p": 1}, 8),(4, 0.0, 1.0, None, ()))@@ -638,6 +670,28 @@ class HTTPTest(unittest.TestCase):self.assertIn("<|user|>Hi<|assistant|><think></think>", self.engine.calls[-1][0])self.assertEqual(self.engine.calls[-1][4], 1)+ def test_kimi_chat_completion_uses_multiturn_wire_payload(self):+ with patch("openai_server.ARCH", "kimi"):+ with self.request("/v1/chat/completions", {+ "model": "test-model",+ "messages": [+ {"role": "user", "content": "你好"},+ {"role": "assistant", "content": "你好。"},+ {"role": "user", "content": "Continue"},+ ],+ "enable_thinking": False,+ }) as response:+ body = json.load(response)+ self.assertEqual(body["choices"][0]["message"]["content"], "Héllo")+ self.assertEqual(+ self.engine.calls[-1][0],+ "K3CHAT1\n"+ "M user 6\n你好"+ "M assistant 9\n你好。"+ "M user 8\nContinue"+ "G 0\n",+ )+def test_chat_completion_stops_across_engine_chunks(self):before = self.engine.stop_requestswith self.request("/v1/chat/completions", {diff --git a/docs/kimi_k3.md b/docs/kimi_k3.mdindex 5e5b948d..b9b9e831 100644--- a/docs/kimi_k3.md+++ b/docs/kimi_k3.md@@ -183,10 +183,16 @@ teacher-forced logit streams at C=32 vs C=1 match exactly). Measured prefill:~5.3 -> **2.0 s/token** at C=32. The KDA state-update sweeps are AVX2(scalar fallback for head dims not divisible by 8).-## Chat mode (`--chat`)+## Chat, API, and Web-```+```sh+# standalone one-turn diagnostic./kimi_k3 <model_dir> --chat "your question" [--system "..."] --ngen 300++# first-class multi-turn interfaces (config.json auto-detects Kimi K3)+COLI_MODEL=<model_dir> ./coli chat+COLI_MODEL=<model_dir> ./coli serve+COLI_MODEL=<model_dir> ./coli web```K3's chat format ("XTML", from the checkpoint's own `encoding_k3.py`) uses@@ -198,18 +204,28 @@ only four special tokens — `<|open|>`, `<|close|>`, `<|sep|>`,<|open|>message role="assistant"<|sep|><|open|>think<|sep|> <- generation prompt```-The assistant's thinking is a *structural* channel (preserved across turns in-multi-turn use); `K3_THINK=0` opens `<response>` directly instead. The C-builder mirrors the reference segment-for-segment (segment boundaries are-token boundaries) and was verified **token-exact** against `encoding_k3.py` +-tiktoken for system/no-system and thinking/non-thinking prompts. At decode-the CLI hides the XTML structure and prints `[think]` / `[response]` channel-banners; generation stops at `<|end_of_msg|>` (the eos).+The assistant's thinking is a *structural* channel and is preserved when an+OpenAI-compatible client sends prior `reasoning_content`; `enable_thinking=false`+opens `<response>` directly. The gateway does not flatten XTML into a string:+it sends length-framed messages to the C engine, which builds every structural+and ordinary-text segment at the tokenizer boundary required by K3's rank-BPE.+The multi-turn wire was compared against the official `encoding_k3.py` and+tiktoken on system/user/assistant history with UTF-8 content: **77/77 token IDs+exact**.++`coli chat` starts a private local server for Kimi and keeps the 2.8T model+loaded for the whole terminal session. `coli serve` exposes streaming and+non-streaming `/v1/chat/completions`; `coli web` uses that same API. Reasoning+is returned as `reasoning_content`, response text as `content`, and+`<|end_of_msg|>` remains the model-owned stop token. `STOP` and `CANCEL` are+honoured between generated tokens.## Current limitations- Decode is single-token (no speculative decoding — K3 has no MTP head).-- `--chat` renders a single system+user turn (no multi-turn CLI loop, no- tool-call rendering — the format supports both; see `encoding_k3.py`).-- CPU only (no CUDA/Metal/Vulkan tier), scalar KDA inner loops.-- No chat template handling; prompts are raw text after `[BOS]`.+- Tool declarations/calls and image content are not exposed through the shared+ gateway yet; unsupported requests fail explicitly.+- CPU only (no CUDA/Metal/Vulkan tier).+- The protocol, tokenizer, gateway, TUI, and Web client paths are locally+ testable without the 1.5 TB checkpoint. A release claim still requires one+ full-model multi-turn TUI/Web run on a host that owns the complete snapshot.