Skip to content

Run frontier MoE models on hardware you already own — pure C, zero deps, experts streamed from disk. Tiny engine, immense model. 🐦

C

feat(qwen38): images end to end -- frame, tower, embeddings

JustVugg2355ed323d9f
diff --git a/.gitignore b/.gitignore
index b4b1d57d..0fe3c15b 100644
--- a/.gitignore
+++ b/.gitignore
@@ -145,3 +145,4 @@ c/*.obj
c/kimi_k3_tiny/.vendor_kimi_k3/
c/kimi_k3_tiny/.coli_usage
c/qwen38_vision_tiny/
+c/qwen38_mm_tiny/
diff --git a/c/Makefile b/c/Makefile
index 48c64986..7d715f6a 100644
--- a/c/Makefile
+++ b/c/Makefile
@@ -1151,6 +1151,15 @@ qwen38-vision-check: tests/test_qwen38_vision$(EXE)
$(PYTHON) tools/make_qwen38_vision_tiny.py --out ./qwen38_vision_tiny
./tests/test_qwen38_vision$(EXE) ./qwen38_vision_tiny
+# Il percorso completo: frame IMAGE, torre, sostituzione degli embedding,
+# generazione. Prova che due immagini diverse danno risposte diverse, che e'
+# l'unica domanda a cui una fixture con pesi casuali sa rispondere onestamente.
+.PHONY: qwen38-vision-serve-check
+qwen38-vision-serve-check: qwen38$(EXE)
+ $(PYTHON) tools/make_qwen38_multimodal_tiny.py --out ./qwen38_mm_tiny
+ $(PYTHON) tools/make_edge_tiny_tokenizer.py --vocab-size 64 ./qwen38_mm_tiny
+ $(PYTHON) tests/test_qwen38_vision_serve.py --binary ./qwen38$(EXE) --fixture ./qwen38_mm_tiny
+
tests/test_qwen38_prefix$(EXE): tests/test_qwen38_prefix.c qwen38.c qwen38_core.h qwen38_nfc.h qwen38_nfc_tables.h st.h json.h compat.h quant.h route_trace.h serve_codec.h tok_unicode.h tok_unicode_o200k.h
$(CC) $(NOCUDA_CFLAGS) $< -o $@ $(NOCUDA_LDFLAGS)
diff --git a/c/openai_server.py b/c/openai_server.py
index 5997022d..074489ca 100644
--- a/c/openai_server.py
+++ b/c/openai_server.py
@@ -1480,6 +1480,62 @@ def _image_bytes_from_url(url):
raise APIError(400, f"cannot read image {path}: {problem}", "messages")
+# Qwen3.8 splices images as <|vision_start|> + N x <|image_pad|> + <|vision_end|>,
+# and N is not a constant: the resolution is dynamic, so it comes from the grid
+# the preprocessor chose. Hardcoding it would put the right vectors in the wrong
+# number of slots, which the engine refuses rather than guesses about.
+QWEN38_VISION_START = "<|vision_start|>"
+QWEN38_IMAGE_PAD = "<|image_pad|>"
+QWEN38_VISION_END = "<|vision_end|>"
+
+
+def _preprocess_qwen38_image(data, model_dir, max_tokens=None):
+ try:
+ import sys as _sys
+ from pathlib import Path as _Path
+ _sys.path.insert(0, str(_Path(__file__).resolve().parent / "tools"))
+ from qwen38_image import preprocess
+ except ImportError as problem:
+ raise APIError(400, f"image support needs Pillow and numpy ({problem}).",
+ "messages")
+ return preprocess(data, model_dir, max_tokens)
+
+
+def expand_qwen38_images(messages, model_dir, max_tokens=None):
+ """Replace image parts with their placeholders and pull out the patches.
+
+ Returns (rewritten messages, images). The messages come back as plain text,
+ so the renderer treats them like any other turn."""
+ images = []
+ rewritten = []
+ for message in messages:
+ content = message.get("content") if isinstance(message, dict) else None
+ if not isinstance(content, list):
+ rewritten.append(message)
+ continue
+ pieces = []
+ for part in content:
+ if not isinstance(part, dict):
+ continue
+ kind = part.get("type")
+ if kind == "text":
+ pieces.append(part.get("text", ""))
+ elif kind in ("image_url", "input_image"):
+ url = (part.get("image_url") or {}).get("url") if kind == "image_url" \
+ else part.get("image_url") or part.get("url")
+ data = _image_bytes_from_url(url)
+ patches, grid_h, grid_w = _preprocess_qwen38_image(
+ data, model_dir, max_tokens)
+ tokens = (grid_h // 2) * (grid_w // 2)
+ images.append((patches, grid_h, grid_w))
+ pieces.append(QWEN38_VISION_START + QWEN38_IMAGE_PAD * tokens
+ + QWEN38_VISION_END)
+ else:
+ raise APIError(400, f"unsupported content part {kind!r}.", "messages")
+ rewritten.append({**message, "content": "".join(pieces)})
+ return rewritten, images
+
+
def expand_glm53_images(messages, model_dir):
"""Sostituisce le parti immagine coi loro segnaposto e ne estrae le patch.
@@ -3684,6 +3740,15 @@ class APIHandler(BaseHTTPRequestHandler):
raise APIError(400, "one image per request for now; the engine "
"holds a single pending image.", "messages")
image = images[0] if images else None
+ elif ARCH == "qwen38":
+ ceiling = os.environ.get("Q38_MAX_IMAGE_TOKENS")
+ messages, images = expand_qwen38_images(
+ messages, getattr(self.server.engine, "model_dir", None),
+ int(ceiling) if ceiling else None)
+ if len(images) > 1:
+ raise APIError(400, "one image per request for now; the engine "
+ "holds a single pending image.", "messages")
+ image = images[0] if images else None
prompt = render_chat_for_arch(messages, enable_thinking, reasoning_effort,
tools, tool_choice, audio_out=audio_clips)
self.generation(body, prompt, request_id, True, tools, tool_choice,
diff --git a/c/qwen38.c b/c/qwen38.c
index 599a353f..991ff129 100644
--- a/c/qwen38.c
+++ b/c/qwen38.c
@@ -60,6 +60,7 @@ static int qwen38_max_ctx(void) {
#include <unistd.h>
#endif
#include "st.h"
+#include "qwen38_vision.h"
#include "json.h" /* tokenizer.json parsing (reuse minimal parser) */
#include "tok_unicode.h"
#include "tok_unicode_o200k.h"
@@ -1137,6 +1138,19 @@ static const ColiServeWireProfile q38_wire = {
/* Returns 2=SUBMIT, 1=STOP(active), 3=CANCEL(active), 0=ignored, -1=EOF/fatal.
* A SUBMIT encountered during a synchronous turn is consumed and rejected so
* its payload cannot desynchronize the following control frame. */
+/* Un'immagine in attesa del SUBMIT che la usa. Se ne arriva una seconda prima
+ * del SUBMIT, la prima viene buttata e lo si dice: rispondere sulla foto
+ * precedente senza avvisare sarebbe peggio di rifiutare. */
+static struct { unsigned char *patches; uint64_t bytes; int grid_h, grid_w; int present; } g_pending_image;
+/* Il modello del turno in corso, per poter rifiutare un'immagine gia' alla
+ * lettura del frame invece che dopo averla accettata. */
+static Model *g_serve_model;
+
+static void q38_pending_image_clear(void){
+ free(g_pending_image.patches);
+ memset(&g_pending_image,0,sizeof g_pending_image);
+}
+
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);
@@ -1153,6 +1167,22 @@ 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_SUBMIT){coli_serve_command_dispose(&command);return 0;}
if(active_id){
coli_serve_write_error(out,command.id,"engine busy");
@@ -1437,6 +1467,25 @@ static int q38_format_prof(char *out,size_t capacity,double wall_s,int prompt_to
static int serve_one(Model *m, ServeReq *q){
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){
+ /* Le patch arrivano gia' float32 dal gateway: qui si controlla solo che
+ * ce ne sia un numero intero e che la griglia le giustifichi, perche' un
+ * conteggio storto darebbe una torre alimentata con byte disallineati. */
+ Cfg *vc=&m->c;
+ int features=vc->vis_in_ch*vc->vis_temporal*vc->vis_patch*vc->vis_patch;
+ uint64_t want=(uint64_t)g_pending_image.grid_h*g_pending_image.grid_w*features*sizeof(float);
+ if(!m->vis_ready||g_pending_image.bytes!=want){
+ printf("ERROR %s BAD_IMAGE bytes=%llu expected=%llu\n",q->id,
+ (unsigned long long)g_pending_image.bytes,(unsigned long long)want);
+ fflush(stdout); q38_pending_image_clear(); free(ids); return 0;
+ }
+ if(q38_vision_attach(m,(const float*)g_pending_image.patches,
+ g_pending_image.grid_h,g_pending_image.grid_w,ids,np)<0){
+ printf("ERROR %s BAD_IMAGE the prompt and the grid disagree\n",q->id);
+ fflush(stdout); q38_pending_image_clear(); free(ids); return 0;
+ }
+ 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){
printf("ERROR %s CONTEXT_EXCEEDED prompt_tokens=%d requested=%d capacity=%d\n",q->id,np,q->max_tok,max_ctx);
@@ -1513,6 +1562,11 @@ static int serve_one(Model *m, ServeReq *q){
if(s == q->max_tok - 1) break;
lo = step(m, &tk, 1, np+s);
}
+ /* I vettori dell'immagine valgono per QUESTO turno soltanto: lasciarli
+ * agganciati farebbe rispondere la richiesta successiva sulla foto
+ * precedente, e la mappa e' per posizione assoluta, quindi combacerebbe
+ * silenziosamente invece di dare errore. */
+ q38_vision_detach(m);
free(lo); free(ids);
if(cancelled){coli_serve_write_error(stdout,q->id,"CANCELLED");return input_eof?-1:0;}
if(stopped)limited=0;
@@ -1540,6 +1594,7 @@ static int serve_one(Model *m, ServeReq *q){
}
static void serve_loop(Model *m){
+ g_serve_model=m;
coli_serve_binary_mode();
setvbuf(stdin,NULL,_IONBF,0);
int max_ctx=qwen38_max_ctx();
diff --git a/c/qwen38_core.h b/c/qwen38_core.h
index 3a594fe1..03a41e8f 100644
--- a/c/qwen38_core.h
+++ b/c/qwen38_core.h
@@ -27,6 +27,10 @@ typedef struct {
int ple_layer, ple_dim, ple_convk, ngram_size, heads_per_ngram;
int ngram_heads, ngram_head_dim, ngram_parts;
uint8_t *is_attn;
+ /* vision: 0 = checkpoint di solo testo, o torre non caricata */
+ int image_token;
+ int vis_depth, vis_hidden, vis_heads, vis_inter, vis_patch;
+ int vis_merge, vis_temporal, vis_in_ch, vis_out_hidden, vis_num_pos;
} Cfg;
typedef enum {
@@ -132,6 +136,14 @@ typedef struct {
int prefill_batch;
uint64_t resident_weight_bytes;
double dense_load_s;
+ /* vision. `vis_map` mappa la posizione ASSOLUTA nella sequenza alla riga di
+ * `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. */
+ Q38Vision vis;
+ int vis_ready;
+ float *vis_rows;
+ int *vis_map, vis_map_len, vis_rows_n;
Q38Timers timers;
} Model;
@@ -476,12 +488,46 @@ static void q38_load_cfg(Cfg *c,const char *snap) {
else if(!strcmp(s,"full_attention")||!strcmp(s,"qwen_sparse_attention")) c->is_attn[i]=1;
else {fprintf(stderr,"unsupported layer type %s\n",s);exit(1);}
}
+ /* Vision: opzionale. Un checkpoint di solo testo non ha vision_config, e in
+ * quel caso la torre resta spenta invece di rifiutare il modello. La
+ * geometria viene dal file, non da costanti qui: una torre di misura diversa
+ * deve fallire dicendo cosa non torna, non leggere pesi della misura
+ * sbagliata. */
+ {
+ jval *vc = q38_obj(root, "vision_config");
+ if (vc) {
+ c->vis_depth = q38_num_int(vc,"depth",0,1,1,1024);
+ c->vis_hidden = q38_num_int(vc,"hidden_size",0,1,1,65536);
+ c->vis_heads = q38_num_int(vc,"num_heads",0,1,1,1024);
+ c->vis_inter = q38_num_int(vc,"intermediate_size",0,1,1,262144);
+ c->vis_patch = q38_num_int(vc,"patch_size",16,0,1,512);
+ c->vis_merge = q38_num_int(vc,"spatial_merge_size",2,0,1,8);
+ c->vis_temporal = q38_num_int(vc,"temporal_patch_size",2,0,1,8);
+ c->vis_in_ch = q38_num_int(vc,"in_channels",3,0,1,8);
+ c->vis_out_hidden = q38_num_int(vc,"out_hidden_size",c->hidden,0,1,65536);
+ c->vis_num_pos = q38_num_int(vc,"num_position_embeddings",0,1,1,1<<20);
+ c->image_token = q38_num_int(root,"image_token_id",-1,0,0,INT_MAX);
+ }
+ }
json_free(root); free(buf); free(arena);
}
#define Q38_NEED(x,...) do{if(!(x)){fprintf(stderr,"[qwen38 config] ");fprintf(stderr,__VA_ARGS__);fprintf(stderr," -- refusing\n");exit(1);}}while(0)
static void q38_validate_cfg(const Cfg *c) {
Q38_NEED(c->hidden>0&&c->hidden<=65536,"hidden_size=%d",c->hidden);
+ if (c->vis_depth) {
+ /* La torre proietta direttamente nello spazio del testo: se le due
+ * dimensioni non coincidono i token immagine finirebbero nel posto
+ * giusto con i numeri sbagliati, che e' peggio di un rifiuto. */
+ Q38_NEED(c->vis_out_hidden==c->hidden,
+ "vision out_hidden_size=%d but text hidden_size=%d",
+ c->vis_out_hidden,c->hidden);
+ Q38_NEED(c->vis_hidden%c->vis_heads==0,
+ "vision hidden_size=%d not divisible by num_heads=%d",
+ c->vis_hidden,c->vis_heads);
+ Q38_NEED(c->image_token>=0&&c->image_token<c->vocab,
+ "image_token_id=%d outside vocabulary",c->image_token);
+ }
Q38_NEED(c->layers>0&&c->layers<=Q38_MAX_LAYERS,"layers=%d",c->layers);
Q38_NEED(c->vocab>0&&c->max_positions>0&&
c->max_positions<=QWEN38_ATTN_MAX_CTX,"vocab/context invalid");
@@ -641,6 +687,127 @@ static void q38_alloc_state(Model *m) {
}
}
+/* ---- vision ------------------------------------------------------------- */
+
+/* La torre e' in F32 residente: 27 blocchi da 1152 sono ~0.6 GB, che accanto ai
+ * 9.2 GiB dei pesi densi non cambia la classe di macchina. Gli esperti restano
+ * su disco; la torre no, perche' si usa una volta per immagine e non per token. */
+static const float *q38_vis_tensor(Model *m,const char *suffix,int64_t expect) {
+ char nm[512];
+ snprintf(nm,sizeof nm,"%s.visual.%s",m->prefix,suffix);
+ if(!st_has(&m->S,nm)){
+ snprintf(nm,sizeof nm,"model.visual.%s",suffix);
+ if(!st_has(&m->S,nm)){fprintf(stderr,"vision tensor missing: %s\n",suffix);exit(1);}
+ }
+ st_tensor *t=st_find(&m->S,nm);
+ if(expect>0&&t->numel!=expect){
+ fprintf(stderr,"vision tensor %s has %lld values, expected %lld -- refusing\n",
+ nm,(long long)t->numel,(long long)expect);exit(1);
+ }
+ float *buf=(float*)malloc((size_t)t->numel*sizeof(float));
+ if(!buf){fprintf(stderr,"OOM loading %s\n",nm);exit(1);}
+ st_read_f32(&m->S,nm,buf,t->numel);
+ m->resident_weight_bytes+=(uint64_t)t->numel*sizeof(float);
+ return buf;
+}
+
+static void q38_vis_linear(Model *m,Q38Linear *l,const char *stem,int out,int in) {
+ char nm[512];
+ snprintf(nm,sizeof nm,"%s.weight",stem); l->w=q38_vis_tensor(m,nm,(int64_t)out*in);
+ snprintf(nm,sizeof nm,"%s.bias",stem); l->b=q38_vis_tensor(m,nm,out);
+ l->out=out; l->in=in;
+}
+
+static void q38_vis_norm(Model *m,Q38Norm *n,const char *stem,int width) {
+ char nm[512];
+ snprintf(nm,sizeof nm,"%s.weight",stem); n->w=q38_vis_tensor(m,nm,width);
+ snprintf(nm,sizeof nm,"%s.bias",stem); n->b=q38_vis_tensor(m,nm,width);
+}
+
+static void q38_load_vision(Model *m) {
+ Cfg *c=&m->c;
+ if(!c->vis_depth) return;
+ char probe[512];
+ snprintf(probe,sizeof probe,"%s.visual.pos_embed.weight",m->prefix);
+ if(!st_has(&m->S,probe)&&!st_has(&m->S,"model.visual.pos_embed.weight")){
+ /* config multimodale ma pesi assenti: e' un export solo-testo di un
+ * checkpoint multimodale. Spegnere la torre e dirlo e' meglio che
+ * rifiutare un modello che per il testo funziona benissimo. */
+ fprintf(stderr,"[qwen38] vision_config present but no visual weights; text only\n");
+ c->vis_depth=0; return;
+ }
+ Q38Vision *v=&m->vis;
+ memset(v,0,sizeof *v);
+ v->depth=c->vis_depth; v->hidden=c->vis_hidden; v->heads=c->vis_heads;
+ v->head_dim=c->vis_hidden/c->vis_heads; v->inter=c->vis_inter;
+ v->patch=c->vis_patch; v->merge=c->vis_merge; v->temporal=c->vis_temporal;
+ v->in_ch=c->vis_in_ch; v->out_hidden=c->vis_out_hidden;
+ v->num_pos=c->vis_num_pos; v->side=(int)(sqrt((double)c->vis_num_pos)+0.5);
+ v->eps=1e-6f;
+ if(v->side*v->side!=v->num_pos){
+ fprintf(stderr,"[qwen38] num_position_embeddings=%d is not a square grid -- refusing\n",
+ v->num_pos);exit(1);
+ }
+ int features=v->in_ch*v->temporal*v->patch*v->patch;
+ q38_vis_linear(m,&v->patch_embed,"patch_embed.proj",v->hidden,features);
+ v->pos_embed=q38_vis_tensor(m,"pos_embed.weight",(int64_t)v->num_pos*v->hidden);
+ v->blocks=(Q38VBlock*)calloc((size_t)v->depth,sizeof(Q38VBlock));
+ if(!v->blocks){fprintf(stderr,"OOM vision blocks\n");exit(1);}
+ for(int i=0;i<v->depth;i++){
+ char stem[160];
+ snprintf(stem,sizeof stem,"blocks.%d.norm1",i); q38_vis_norm(m,&v->blocks[i].norm1,stem,v->hidden);
+ snprintf(stem,sizeof stem,"blocks.%d.norm2",i); q38_vis_norm(m,&v->blocks[i].norm2,stem,v->hidden);
+ snprintf(stem,sizeof stem,"blocks.%d.attn.qkv",i); q38_vis_linear(m,&v->blocks[i].qkv,stem,3*v->hidden,v->hidden);
+ snprintf(stem,sizeof stem,"blocks.%d.attn.proj",i); q38_vis_linear(m,&v->blocks[i].proj,stem,v->hidden,v->hidden);
+ snprintf(stem,sizeof stem,"blocks.%d.mlp.linear_fc1",i); q38_vis_linear(m,&v->blocks[i].fc1,stem,v->inter,v->hidden);
+ snprintf(stem,sizeof stem,"blocks.%d.mlp.linear_fc2",i); q38_vis_linear(m,&v->blocks[i].fc2,stem,v->hidden,v->inter);
+ }
+ int wide=v->hidden*v->merge*v->merge;
+ q38_vis_norm(m,&v->merger_norm,"merger.norm",v->hidden);
+ q38_vis_linear(m,&v->merger_fc1,"merger.linear_fc1",wide,wide);
+ q38_vis_linear(m,&v->merger_fc2,"merger.linear_fc2",v->out_hidden,wide);
+ m->vis_ready=1;
+ fprintf(stderr,"[qwen38] vision tower: %d blocks, hidden %d, %d heads, patch %d, merge %d\n",
+ v->depth,v->hidden,v->heads,v->patch,v->merge);
+}
+
+/* Esegue la torre su un'immagine gia' preprocessata e prepara la mappa
+ * posizione->riga. `ids`/`n` sono i token del prompt: le righe vengono
+ * assegnate ai token immagine nell'ordine in cui compaiono. */
+static int q38_vision_attach(Model *m,const float *patches,int grid_h,int grid_w,
+ const int *ids,int n) {
+ Cfg *c=&m->c;
+ if(!m->vis_ready) return -1;
+ int tokens=(grid_h*grid_w)/(c->vis_merge*c->vis_merge);
+ int slots=0;
+ for(int i=0;i<n;i++) if(ids[i]==c->image_token) slots++;
+ if(slots!=tokens){
+ /* Il numero di segnaposto nel prompt DEVE essere quello che la griglia
+ * produce. Se non lo e', il template e il preprocessing hanno visto due
+ * immagini diverse, e proseguire vorrebbe dire mettere i vettori giusti
+ * nelle posizioni sbagliate. */
+ fprintf(stderr,"[qwen38] prompt has %d image placeholders but the grid gives %d tokens\n",
+ slots,tokens);
+ return -1;
+ }
+ free(m->vis_rows); free(m->vis_map);
+ m->vis_rows=(float*)calloc((size_t)tokens*c->hidden,sizeof(float));
+ m->vis_map=(int*)malloc((size_t)n*sizeof(int));
+ if(!m->vis_rows||!m->vis_map){free(m->vis_rows);free(m->vis_map);
+ m->vis_rows=NULL;m->vis_map=NULL;return -1;}
+ if(q38_vision_forward(&m->vis,patches,grid_h,grid_w,m->vis_rows)!=tokens){
+ free(m->vis_rows);free(m->vis_map);m->vis_rows=NULL;m->vis_map=NULL;return -1;}
+ int next=0;
+ for(int i=0;i<n;i++) m->vis_map[i]=(ids[i]==c->image_token)?next++:-1;
+ m->vis_map_len=n; m->vis_rows_n=tokens;
+ return tokens;
+}
+
+static void q38_vision_detach(Model *m) {
+ free(m->vis_rows); free(m->vis_map);
+ m->vis_rows=NULL; m->vis_map=NULL; m->vis_map_len=0; m->vis_rows_n=0;
+}
+
static void model_init_range(Model *m,const char *snap,int cap,int bits,
int layer_begin,int layer_end,int load_boundaries,
int allocate_state) {
@@ -702,6 +869,10 @@ static void model_init_range(Model *m,const char *snap,int cap,int bits,
if(!lc->slots||!lc->by_expert){fprintf(stderr,"OOM expert cache\n");exit(1);} for(int e=0;e<c->experts;e++)lc->by_expert[e]=-1;
}
if(c->ple_layer>=layer_begin&&c->ple_layer<layer_end) q38_load_ple(m,&m->L[c->ple_layer]);
+ /* La torre solo quando il motore possiede la sequenza intera: uno shard che
+ * ospita solo alcuni layer non ha da fare niente con le immagini, e
+ * caricarla la' sarebbe mezzo giga per nulla. */
+ if(load_boundaries&&q38_env_bool("Q38_VISION",1)) q38_load_vision(m);
if(allocate_state) q38_alloc_state(m);
m->dense_load_s=now_s()-t0;
fprintf(stderr,"[qwen38] native text weights: prefix=%s, %d layers, PLE=%d, cache=%d/layer, "
@@ -1702,7 +1873,12 @@ static float *step(Model *m,const int *ids,int S,int pos_base) {
float *hyper=falloc((int64_t)S*W);
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);
+ float *e=hyper+(int64_t)s*W;
+ int abs_pos=pos_base+s, vis_row=-1;
+ if(m->vis_map&&abs_pos>=0&&abs_pos<m->vis_map_len) vis_row=m->vis_map[abs_pos];
+ if(vis_row>=0&&vis_row<m->vis_rows_n)
+ memcpy(e,m->vis_rows+(int64_t)vis_row*H,(size_t)H*sizeof(float));
+ else 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);
diff --git a/c/serve_codec.h b/c/serve_codec.h
index 85ac05d6..9511730e 100644
--- a/c/serve_codec.h
+++ b/c/serve_codec.h
@@ -20,6 +20,11 @@ typedef enum {
COLI_SERVE_COMMAND_SUBMIT,
COLI_SERVE_COMMAND_STOP,
COLI_SERVE_COMMAND_CANCEL,
+ /* IMAGE <id> <bytes> <grid_h> <grid_w>\n<payload>\n, annunciato subito prima
+ * del SUBMIT a cui appartiene. Un motore di solo testo che non lo gestisce lo
+ * vede come un comando che non sa trattare e lo rifiuta, che e' la risposta
+ * giusta: meglio dire di no che accettare una foto e ignorarla. */
+ COLI_SERVE_COMMAND_IMAGE,
} ColiServeCommandKind;
typedef enum {
@@ -52,6 +57,9 @@ typedef struct {
float top_p;
uint64_t extension_bytes;
int prefix_bytes;
+ /* IMAGE: la griglia di patch che accompagna il payload. Zero per ogni altro
+ * comando. */
+ int grid_h, grid_w;
unsigned char *payload;
} ColiServeCommand;
@@ -134,6 +142,8 @@ static inline void coli_serve_classify_line(
command->kind = COLI_SERVE_COMMAND_STOP;
else if (name_size == 6 && !memcmp(name, "CANCEL", 6))
command->kind = COLI_SERVE_COMMAND_CANCEL;
+ else if (name_size == 5 && !memcmp(name, "IMAGE", 5))
+ command->kind = COLI_SERVE_COMMAND_IMAGE;
else
return;
while (*cursor == ' ' || *cursor == '\t') cursor++;
@@ -200,6 +210,7 @@ static inline ColiServeReadResult coli_serve_read_command_alloc(
if (!strcmp(fields[0], "SUBMIT")) command->kind = COLI_SERVE_COMMAND_SUBMIT;
else if (!strcmp(fields[0], "STOP")) command->kind = COLI_SERVE_COMMAND_STOP;
else if (!strcmp(fields[0], "CANCEL")) command->kind = COLI_SERVE_COMMAND_CANCEL;
+ else if (!strcmp(fields[0], "IMAGE")) command->kind = COLI_SERVE_COMMAND_IMAGE;
else {
free(line);
return COLI_SERVE_READ_IGNORED;
@@ -215,6 +226,39 @@ static inline ColiServeReadResult coli_serve_read_command_alloc(
free(line);
return COLI_SERVE_READ_OK;
}
+ if (command->kind == COLI_SERVE_COMMAND_IMAGE) {
+ /* IMAGE <id> <bytes> <grid_h> <grid_w>\n<payload>\n
+ *
+ * Il payload va consumato SEMPRE, anche quando il motore non sa cosa
+ * farsene: lasciarlo nello stream sposterebbe il frame successivo di
+ * qualche megabyte e il gateway leggerebbe pixel come se fossero
+ * un'intestazione. Per questo il rifiuto vive nel chiamante, non qui. */
+ if (nfields != 5 ||
+ !coli_serve_parse_u64(fields[2], &command->payload_bytes) ||
+ !coli_serve_parse_i32(fields[3], &command->grid_h) ||
+ !coli_serve_parse_i32(fields[4], &command->grid_w) ||
+ command->payload_bytes > profile->max_payload_bytes ||
+ command->grid_h < 1 || command->grid_w < 1) {
+ free(line);
+ return COLI_SERVE_READ_BAD_REQUEST;
+ }
+ free(line);
+ command->payload = (unsigned char *)allocate((size_t)command->payload_bytes + 1);
+ if (!command->payload) return COLI_SERVE_READ_NOMEM;
+ if (command->payload_bytes &&
+ fread(command->payload, 1, (size_t)command->payload_bytes, input)
+ != (size_t)command->payload_bytes) {
+ coli_serve_command_dispose(command);
+ return COLI_SERVE_READ_BAD_FRAME;
+ }
+ command->payload[command->payload_bytes] = 0;
+ int terminator = fgetc(input);
+ if (terminator != '\n' && !(terminator == '\r' && fgetc(input) == '\n')) {
+ coli_serve_command_dispose(command);
+ return COLI_SERVE_READ_BAD_FRAME;
+ }
+ return COLI_SERVE_READ_OK;
+ }
int minimum_fields = 7;
int maximum_fields = minimum_fields + !!profile->allow_extension_bytes +
!!profile->allow_prefix_hint;
diff --git a/c/tests/test_qwen38_vision_serve.py b/c/tests/test_qwen38_vision_serve.py
new file mode 100644
index 00000000..376f7ff5
--- /dev/null
+++ b/c/tests/test_qwen38_vision_serve.py
@@ -0,0 +1,159 @@
+#!/usr/bin/env python3
+"""Il percorso completo delle immagini in Qwen3.8: frame IMAGE, torre, generazione.
+
+Non verifica che il modello RISPONDA: con pesi casuali risponderebbe comunque, e
+risponderebbe identico anche ignorando del tutto l'immagine. Verifica che **due
+immagini diverse diano due risposte diverse**, che e' l'unica domanda a cui una
+fixture casuale sa rispondere onestamente, ed e' anche quella che smaschera il
+difetto piu' probabile: patch caricate, torre eseguita, e poi il risultato
+buttato via da qualche parte fra il merger e gli embedding.
+
+Poi controlla i rifiuti, perche' accettare un'immagine sbagliata e' peggio che
+rifiutarla: un conteggio di byte che non corrisponde alla griglia, e un prompt in
+cui i segnaposto non sono quanti la griglia ne produce.
+
+USO:
+ python3 tests/test_qwen38_vision_serve.py --binary ./qwen38 --fixture ./qwen38_mm_tiny
+"""
+import argparse
+import json
+import struct
+import subprocess
+import sys
+from pathlib import Path
+
+
+def read_until(process, prefixes, limit=400):
+ """Legge righe finche' non ne arriva una che comincia per uno dei prefissi."""
+ for _ in range(limit):
+ line = process.stdout.readline()
+ if not line:
+ return None
+ # Le righe di controllo del mux sono racchiuse da \x01: senza toglierli
+ # un confronto per prefisso non trova mai nulla e il test aspetta per sempre.
+ text = line.decode("utf-8", "replace").strip("\r\n\x01")
+ for prefix in prefixes:
+ if text.startswith(prefix):
+ return text
+ return None
+
+
+def turn(process, request_id, prompt_ids, patches, grid_h, grid_w, image_token):
+ """Manda IMAGE + SUBMIT e restituisce (verdetto, testo raccolto)."""
+ payload = bytes(bytearray([min(t, 255) for t in prompt_ids]))
+ if patches is not None:
+ blob = struct.pack(f"<{len(patches)}f", *patches)
+ process.stdin.write(
+ f"IMAGE {request_id} {len(blob)} {grid_h} {grid_w}\n".encode() + blob + b"\n")
+ header = f"SUBMIT {request_id} 0 {len(payload)} 4 0.0 1.0\n".encode()
+ process.stdin.write(header + payload + b"\n")
+ process.stdin.flush()
+ first = read_until(process, ("ACCEPT", "ERROR"))
+ if first is None or first.startswith("ERROR"):
+ return (first or "nessuna risposta"), ""
+ collected = []
+ for _ in range(200):
+ line = process.stdout.readline()
+ if not line:
+ break
+ text = line.decode("utf-8", "replace").strip("\r\n\x01")
+ if text.startswith("DATA"):
+ collected.append(text)
+ if text.startswith("DONE") or text.startswith("ERROR"):
+ return text, "\n".join(collected)
+ return "senza DONE", "\n".join(collected)
+
+
+def main() -> int:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--binary", type=Path, required=True)
+ parser.add_argument("--fixture", type=Path, required=True)
+ arguments = parser.parse_args()
+
+ meta_path = arguments.fixture / "vision_meta.json"
+ if not arguments.binary.exists() or not meta_path.exists():
+ print(f"SKIP: serve {arguments.binary} e la fixture; generala con "
+ f"tools/make_qwen38_multimodal_tiny.py")
+ return 0
+ meta = json.loads(meta_path.read_text())
+ grid_h, grid_w = meta["grid_h"], meta["grid_w"]
+ features, image_token = meta["features"], meta["image_token"]
+ tokens = meta["tokens"]
+ count = grid_h * grid_w * features
+
+ environment = {"SNAP": str(arguments.fixture), "SERVE": "1", "SERVE_BATCH": "1",
+ "OMP_NUM_THREADS": "2", "PATH": "/usr/bin:/bin"}
+ process = subprocess.Popen([str(arguments.binary.resolve()), "1", "4"],
+ stdin=subprocess.PIPE, stdout=subprocess.PIPE,
+ stderr=subprocess.DEVNULL, env=environment)
+ failures = 0
+ try:
+ if read_until(process, ("READY",)) is None:
+ print("FAIL il motore non ha mai detto READY")
+ return 1
+ print("ok il motore e' pronto")
+
+ prompt = [image_token] * tokens + [3, 4]
+
+ # Due immagini deliberatamente diverse: una a gradiente crescente, una a
+ # gradiente opposto. Se il risultato della torre non arrivasse agli
+ # embedding, le due risposte sarebbero identiche.
+ first = [((i % 97) / 97.0) for i in range(count)]
+ second = [1.0 - value for value in first]
+
+ verdict_a, text_a = turn(process, "a1", prompt, first, grid_h, grid_w, image_token)
+ verdict_b, text_b = turn(process, "b1", prompt, second, grid_h, grid_w, image_token)
+ for label, verdict in (("prima immagine", verdict_a), ("seconda immagine", verdict_b)):
+ if not verdict.startswith("DONE"):
+ print(f"FAIL {label}: {verdict}")
+ failures += 1
+ if not failures:
+ if text_a and text_b and text_a != text_b:
+ print("ok due immagini diverse danno due risposte diverse")
+ else:
+ print("FAIL le due immagini hanno dato la stessa risposta: la torre "
+ "gira ma il suo risultato non arriva agli embedding")
+ failures += 1
+
+ # Byte che non corrispondono alla griglia: va rifiutato, non arrotondato.
+ verdict, _ = turn(process, "c1", prompt, first[:-features], grid_h, grid_w, image_token)
+ if verdict.startswith("ERROR"):
+ print("ok un conteggio di byte incoerente con la griglia e' rifiutato")
+ else:
+ print(f"FAIL byte incoerenti accettati: {verdict}")
+ failures += 1
+
+ # Segnaposto in numero sbagliato: il prompt e la griglia devono concordare.
+ verdict, _ = turn(process, "d1", [image_token] * (tokens - 1) + [3],
+ first, grid_h, grid_w, image_token)
+ if verdict.startswith("ERROR"):
+ print("ok un prompt con troppi pochi segnaposto e' rifiutato")
+ else:
+ print(f"FAIL segnaposto mancanti accettati: {verdict}")
+ failures += 1
+
+ # Senza immagine il motore deve continuare a funzionare come prima.
+ verdict, _ = turn(process, "e1", [3, 4, 5], None, 0, 0, image_token)
+ if verdict.startswith("DONE"):
+ print("ok una richiesta di solo testo funziona ancora")
+ else:
+ print(f"FAIL il solo testo si e' rotto: {verdict}")
+ failures += 1
+ finally:
+ try:
+ process.stdin.close()
+ except Exception:
+ pass
+ process.terminate()
+ process.wait(timeout=10)
+
+ print()
+ if failures:
+ print(f"TEST FAIL ({failures} casi)")
+ return 1
+ print("percorso immagini Qwen3.8: frame, torre e generazione collegati")
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/c/tools/make_qwen38_multimodal_tiny.py b/c/tools/make_qwen38_multimodal_tiny.py
new file mode 100644
index 00000000..b47f9bc8
--- /dev/null
+++ b/c/tools/make_qwen38_multimodal_tiny.py
@@ -0,0 +1,97 @@
+#!/usr/bin/env python3
+"""Fixture multimodale tiny per Qwen3.8: testo piu' torre vision, in un modello solo.
+
+Unisce quello che gia' sanno fare make_qwen38_tiny.py (il modello di testo) e
+make_qwen38_vision_tiny.py (la torre) in un checkpoint che il motore carica
+davvero, cosi' il percorso completo -- frame IMAGE, torre, sostituzione degli
+embedding, generazione -- si puo' provare senza i 185 GB.
+
+Il test che ci gira sopra non verifica che il modello risponda: con pesi casuali
+risponderebbe comunque, e risponderebbe anche ignorando del tutto l'immagine.
+Verifica che DUE IMMAGINI DIVERSE DIANO DUE RISPOSTE DIVERSE, che e' l'unica
+domanda a cui una fixture casuale sa rispondere onestamente.
+
+USO:
+ python3 tools/make_qwen38_multimodal_tiny.py --out ./qwen38_mm_tiny
+"""
+from __future__ import annotations
+
+import argparse
+import json
+from pathlib import Path
+
+SEED = 20260830
+
+
+def build(out: Path, *, grid_h=4, grid_w=4, seed=SEED):
+ import torch
+ from safetensors.torch import save_file
+ from transformers.models.qwen4_exp.configuration_qwen4_exp import Qwen4ExpVisionConfig
+ from transformers.models.qwen4_exp.modeling_qwen4_exp import Qwen4ExpVisionModel
+
+ import make_qwen38_tiny
+
+ out.mkdir(parents=True, exist_ok=True)
+ text_dir = out / "_text"
+ make_qwen38_tiny.build(text_dir, emit_ref=False)
+ text_config = json.loads((text_dir / "config.json").read_text())
+
+ vocab = text_config.get("vocab_size") or text_config["text_config"]["vocab_size"]
+ hidden = text_config.get("hidden_size") or text_config["text_config"]["hidden_size"]
+ # Il segnaposto immagine deve stare nel vocabolario del modello di testo, o
+ # il motore rifiuterebbe il token prima ancora di arrivare alla torre.
+ image_token = vocab - 1
+
+ vision = Qwen4ExpVisionConfig(
+ depth=2, hidden_size=64, num_heads=4, intermediate_size=128,
+ patch_size=16, spatial_merge_size=2, temporal_patch_size=2,
+ in_channels=3, out_hidden_size=hidden, num_position_embeddings=64,
+ hidden_act="gelu_pytorch_tanh",
+ )
+ torch.manual_seed(seed)
+ tower = Qwen4ExpVisionModel(vision).eval()
+ with torch.no_grad():
+ for parameter in tower.parameters():
+ parameter.copy_(torch.randn_like(parameter) * 0.6)
+
+ from safetensors.torch import load_file
+ tensors = dict(load_file(str(text_dir / "model.safetensors")))
+ for name, value in tower.state_dict().items():
+ tensors[f"model.visual.{name}"] = value.detach().contiguous()
+ save_file(tensors, str(out / "model.safetensors"))
+
+ merged = dict(text_config)
+ merged["vision_config"] = vision.to_dict()
+ merged["image_token_id"] = image_token
+ (out / "config.json").write_text(json.dumps(merged, indent=2))
+ for extra in ("generation_config.json",):
+ source = text_dir / extra
+ if source.exists():
+ (out / extra).write_text(source.read_text())
+
+ features = vision.in_channels * vision.temporal_patch_size * vision.patch_size ** 2
+ tokens = (grid_h * grid_w) // (vision.spatial_merge_size ** 2)
+ (out / "vision_meta.json").write_text(json.dumps({
+ "grid_h": grid_h, "grid_w": grid_w, "features": features,
+ "image_token": image_token, "tokens": tokens,
+ }))
+ print(f" fixture multimodale: vocab {vocab}, hidden {hidden}, "
+ f"segnaposto immagine {image_token}, {tokens} token per immagine")
+ print(f" scritta in {out}")
+
+
+def main() -> int:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--out", type=Path, required=True)
+ arguments = parser.parse_args()
+ import sys
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
+ try:
+ build(arguments.out)
+ except ImportError as exc:
+ raise SystemExit(f"serve transformers e safetensors: {exc}")
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/docs/qwen38.md b/docs/qwen38.md
index e1f93b41..d374c683 100644
--- a/docs/qwen38.md
+++ b/docs/qwen38.md
@@ -247,6 +247,34 @@ itself in float64 by 1.83e-4 on these activations, so a gap of that order is the
arithmetic rather than a defect, and the threshold sits between it and the
4.6e-3 the real bug produced.
-The prompt side is settled by the template, which splices images as
-`<|vision_start|><|image_pad|><|vision_end|>`. Wiring the tower into the engine's
-sequence, and accepting images at the gateway, is the remaining step.
+### Wired up
+
+Images work end to end. Send an OpenAI `image_url` part with a base64 data URI or
+a local path; the gateway preprocesses it, replaces the part with
+`<|vision_start|>` + N x `<|image_pad|>` + `<|vision_end|>`, and hands the patches
+to the engine in an `IMAGE` frame ahead of the `SUBMIT` they belong to. The engine
+runs the tower once and substitutes its output for the embedding of each
+placeholder.
+
+N is not a constant. The resolution is dynamic, so the placeholder count comes
+from the grid the preprocessor chose, and the engine **refuses** a request where
+the prompt and the grid disagree rather than guessing which vectors go where.
+`Q38_MAX_IMAGE_TOKENS` caps it; a 1080p photo is 2040 tokens without one.
+
+```
+make -C c qwen38-vision-serve-check
+```
+
+That gate does not check the model answers -- with random weights it would answer
+regardless, and would answer identically while ignoring the picture entirely. It
+checks that **two different images produce two different answers**, which is the
+only question a random fixture can answer honestly, and the one that catches the
+likeliest defect: patches loaded, tower run, result dropped somewhere between the
+merger and the embeddings. It also checks the refusals, since accepting a wrong
+image is worse than refusing it.
+
+Remote URLs are refused rather than fetched, as elsewhere: a request should not
+make the server open a connection of the sender's choosing.
+
+One image per request for now -- the engine holds a single pending image, and a
+second arriving before its `SUBMIT` drops the first and says so.