From b4ef48e941f398a2239765e0116f6a5575348f73 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Wed, 14 Oct 2026 00:46:16 +0200 Subject: [PATCH 1/8] qwen35: sessions, parallel requests (--batch N) and pictures (--vision, M-RoPE) in the Qwen3.6 engine One conversation state per session; --batch N keeps N of them and decodes one token of each in a single window (rows of several sessions in one forward, bit-equal to the solo rows), reads a prompt between the other slots' windows and takes a conversation over from the session that holds its start. GENI / BGENI pictures: the encoder's rows replace the embeddings of the <|image_pad|> cells, positions as llama.cpp's mtmd (interleaved M-RoPE 11/11/10, text after a picture continues at p + max(nx, ny)). tools/qwen35/q36_mtmd_dump.cpp is llama.cpp's side of the picture check. --- src/qwen35/q36_engine.cu | 915 +++++++++++++++++++++++++++++---- tools/qwen35/q36_mtmd_dump.cpp | 132 +++++ 2 files changed, 935 insertions(+), 112 deletions(-) create mode 100644 tools/qwen35/q36_mtmd_dump.cpp diff --git a/src/qwen35/q36_engine.cu b/src/qwen35/q36_engine.cu index c42aff35..05fbc9eb 100644 --- a/src/qwen35/q36_engine.cu +++ b/src/qwen35/q36_engine.cu @@ -54,6 +54,7 @@ #include #include #include +#include #include namespace { @@ -232,16 +233,36 @@ __global__ void k_gate_rows(float* sh, const float* gate, int n, int T) { sh[i] *= sigm(gate[i / n]); } +/// Batch rows (several sessions decoded in one window, one token each): row t reads and writes the cache of session +/// slot[t] at cell[t]; its rotary position is cell[t] + delta[t]. Every field null: one session, the rows are its +/// consecutive cells *pos0 + t (the prompt, a verify window, a decode step). +struct RowSel { + const int32_t* cell = nullptr; // device [T] + const int32_t* slot = nullptr; // device [T] + const int32_t* delta = nullptr; // device [T] + float* const* kc = nullptr; // device [n_sessions]: this layer's K / V base of each session + float* const* vc = nullptr; +}; + /// The attention layer's per-token preparation for T rows at positions *pos0 + t: q (from the [q | gate] pairs) and k /// RMS-normed per head with their weights, NEOX RoPE over the first n_rot dims, k / v into the cache, the gate kept. +/// Rotary position of a cell: the cell itself (text) plus *rdelta (what the pictures before a text run did not use +/// of their cells, see mrope), or, with `mtab` (a request's prompt cells, device int32 [cell][3] = t, h, w), the +/// interleaved M-RoPE position (llama.cpp's IMROPE with sections 11 / 11 / 10: pair p takes stream p % 3). /// grid (H + HKV, T), block 256 (HD <= 256). __global__ void k_attn_prep(const float* qg, const float* kx, const float* vx, const float* qw, const float* kw, float* q, float* gate, float* kc, float* vc, int H, int HKV, int HD, int n_rot, - const int32_t* pos0, int ctx, float base, float eps) { + const int32_t* pos0, int ctx, float base, float eps, const int32_t* rdelta, + const int32_t* mtab, RowSel rs) { __shared__ float sh[kThreads]; __shared__ float buf[256]; const int head = blockIdx.x, t = blockIdx.y; - const int pos = *pos0 + t; + const int pos = rs.cell ? rs.cell[t] : *pos0 + t; + const int dl = rs.delta ? rs.delta[t] : (rdelta ? *rdelta : 0); + if (rs.kc) { + kc = rs.kc[rs.slot[t]]; + vc = rs.vc[rs.slot[t]]; + } const bool isq = head < H; const float* src = isq ? qg + ((size_t) t * H + head) * 2 * HD : kx + ((size_t) t * HKV + head - H) * HD; const int i = threadIdx.x; @@ -255,7 +276,8 @@ __global__ void k_attn_prep(const float* qg, const float* kx, const float* vx, c const int half = n_rot / 2; if (i < n_rot) { const int p = i < half ? i : i - half; - const float theta = (float) pos * powf(base, -2.0f * (float) p / (float) n_rot); + const int rp = mtab ? __ldg(mtab + (size_t) pos * 3 + p % 3) : pos + dl; + const float theta = (float) rp * powf(base, -2.0f * (float) p / (float) n_rot); float sn, cs; sincosf(theta, &sn, &cs); v = i < half ? buf[i] * cs - buf[i + half] * sn : buf[i - half] * sn + buf[i] * cs; @@ -274,12 +296,16 @@ __global__ void k_attn_prep(const float* qg, const float* kx, const float* vx, c /// cells [0, *pos0 + t]. Writes the chunk's partial accumulator, max and sum; chunks past the query's cells write /// nothing (the merge stops before them). grid (n_chunk, n_rows), block 256, HD == 256. __global__ void k_attn_part(const float* q, const float* kc, const float* vc, const int32_t* pos0, int t0, int H, - int HKV, int ctx, float scale, int n_chunk, float* pacc, float* pm, float* pl) { + int HKV, int ctx, float scale, int n_chunk, float* pacc, float* pm, float* pl, RowSel rs) { constexpr int HD = 256; __shared__ float qs[HD], sc[kChunkCells], sh[kThreads]; const int c = blockIdx.x, row = blockIdx.y; const int t = t0 + row / H, h = row % H, kvh = h / (H / HKV); - const int npos = *pos0 + t + 1; + const int npos = (rs.cell ? rs.cell[t] : *pos0 + t) + 1; + if (rs.kc) { + kc = rs.kc[rs.slot[t]]; + vc = rs.vc[rs.slot[t]]; + } const int p0 = c * kChunkCells; if (p0 >= npos) return; const int j = threadIdx.x; @@ -310,10 +336,10 @@ __global__ void k_attn_part(const float* q, const float* kc, const float* vc, co } /// The chunks merged, times sigmoid(gate): grid (n_rows), block HD. __global__ void k_attn_merge(const float* pacc, const float* pm, const float* pl, const float* gate, - const int32_t* pos0, int t0, int H, int n_chunk, float* out) { + const int32_t* pos0, int t0, int H, int n_chunk, float* out, RowSel rs) { constexpr int HD = 256; const int row = blockIdx.x, t = t0 + row / H, h = row % H, d = threadIdx.x; - const int npos = *pos0 + t + 1; + const int npos = (rs.cell ? rs.cell[t] : *pos0 + t) + 1; const int nc = (npos + kChunkCells - 1) / kChunkCells; float M = -INFINITY; for (int c = 0; c < nc; ++c) M = fmaxf(M, pm[(size_t) row * n_chunk + c]); @@ -428,6 +454,15 @@ __global__ void k_gate_mul(float* att, const float* gate, int64_t n) { if (i < n) att[i] *= sigm(gate[i]); } +/// Picture rows over the embeddings of a chunk: x[r] = img[map[r]] for the rows with map[r] >= 0 (the rows of a picture's +/// <|image_pad|> cells). grid (T), block 256. +__global__ void k_put_rows(float* x, const float* img, const int32_t* map, int n) { + const int r = blockIdx.x; + const int m = map[r]; + if (m < 0) return; + for (int i = threadIdx.x; i < n; i += blockDim.x) x[(size_t) r * n + i] = img[(size_t) m * n + i]; +} + /// The prompt's routed entries sorted by expert for MMQ: bounds[x] .. bounds[x + 1] are expert x's rows; sorted row r /// holds entry dst[r] (= t * K + k, the row of the per-slot outputs) of token src[r]. The order inside an expert is the /// atomics' (no output depends on it: every row's products are its own). cnt / cur: n_expert ints of scratch. @@ -565,8 +600,14 @@ __global__ void k_to_f16(const float* x, __half* y, int64_t n) { /// 3-entry history carried in registers across the tokens and written back at the end; SiLU, then the L2 norm of the /// q/k heads (block < qk_heads) per token - fused_gdn_conv_l2's arithmetic, token after token. History [channel][3]. __global__ void __launch_bounds__(128) k_conv_seq(float* hist, const float* qkv, const float* w, float* h, int C, - int qk_heads, float eps, int T, bool write) { + int qk_heads, float eps, int T, bool write, + float* const* hist_tab = nullptr, const int32_t* slot_rows = nullptr) { __shared__ float part[4]; + if (hist_tab) { // batch rows (T = 1 each, grid y = row): row r's history is session slot_rows[r]'s + hist = hist_tab[slot_rows[blockIdx.y]]; + qkv += (size_t) blockIdx.y * C; + h += (size_t) blockIdx.y * C; + } const int c = blockIdx.x * 128 + threadIdx.x; float v0 = hist[c * 3], v1 = hist[c * 3 + 1], v2 = hist[c * 3 + 2]; const float w0 = w[c * 4], w1 = w[c * 4 + 1], w2 = w[c * 4 + 2], w3 = w[c * 4 + 3]; @@ -600,8 +641,18 @@ __global__ void __launch_bounds__(128) k_conv_seq(float* hist, const float* qkv, /// registers across the tokens. h (T, C) = q | k | v, gate / beta (T, HV), z / y (T, ZV). __global__ void __launch_bounds__(512) k_gdn_seq(float* state, const float* h, int C, const float* gate, const float* beta, const float* z, const float* gamma, float eps, - float* y, int h_k, int h_v, int T, bool write) { + float* y, int h_k, int h_v, int T, bool write, + float* const* state_tab = nullptr, const int32_t* slot_rows = nullptr) { constexpr int S = 128, RG = 4, RPG = 32; + if (state_tab) { // batch rows (T = 1 each, grid y = row): row r's state is session slot_rows[r]'s + const int r = blockIdx.y; + state = state_tab[slot_rows[r]]; + h += (size_t) r * C; + gate += (size_t) r * h_v; + beta += (size_t) r * h_v; + z += (size_t) r * h_v * S; + if (y) y += (size_t) r * h_v * S; + } __shared__ float sk[S], sq[S]; __shared__ float red_kv[RG][S]; __shared__ float red_o[RG][S]; @@ -1003,6 +1054,13 @@ template T* dalloc_t(size_t n) { return p; } +/// A picture in a prompt: its first cell, its rows, and the hash the conversation cache compares it by. +struct ImgKey { + int64_t cell = 0, n = 0; + uint64_t hash = 0; + bool operator==(const ImgKey& o) const { return cell == o.cell && n == o.n && hash == o.hash; } +}; + struct Engine { const Model* m = nullptr; cudaStream_t st = nullptr; @@ -1012,7 +1070,7 @@ struct Engine { float *x, *h, *y, *qkv, *hc, *z, *alpha, *beta, *gdn_y, *qg, *kx, *vx, *q, *gate, *att, *logits_r, *eparts, *moe_out, *sg, *su, *shh, *sy, *sgate, *ewts, *logits; float* hmain = nullptr; // [tmax][N] the main model's final normed hidden of each row (the MTP seeds) - float* hlast = nullptr; // [N] that of the last processed position (zeros before the first) + float* hlast = nullptr; // [N] that of the last processed position (zeros before the first): the current session's void *q8, *xq, *escr; int32_t *ids, *grp_start, *n_groups, *ent_dst, *ent_tok, *tok, *pos0, *pick; int32_t* hpin = nullptr; // pinned staging: [0] decode token, [1] position, [2..9] picks, [10] max rows, [16..] tokens @@ -1020,7 +1078,7 @@ struct Engine { float *pacc, *pm, *pl, *amv; int32_t* ami; int n_chunk = 0, att_rows = 0; // attention partials: att_rows query rows x n_chunk chunks - std::vector conv, S, kc, vc; // per layer; the MTP block's K / V at index n_layers + std::vector conv, S, kc, vc; // per layer; the MTP block's K / V at index n_layers: the CURRENT session's (select) // verify windows (T <= kVerify): the GDN inputs of every row per layer, kept for the commit static constexpr int kVerify = 8; std::vector v_qkv, v_hc, v_alpha, v_beta; @@ -1028,7 +1086,12 @@ struct Engine { float *mtp_cat = nullptr, *hmtp = nullptr, *logits_m = nullptr; int32_t *tok_m = nullptr, *pos0_m = nullptr, *pick_m = nullptr; // graphs: [0] the decode step, [T] a verify window of T rows, mtp1 the MTP draft step - cudaGraphExec_t g1 = nullptr, gv[kVerify + 1] = {}, gm1 = nullptr; + // (the graphs hold the current session's state pointers as kernel arguments: one set per session) + struct GSet { + cudaGraphExec_t g1 = nullptr, gv[kVerify + 1] = {}, gm1 = nullptr; + }; + std::vector gsets; + GSet& gs() { return gsets[(size_t) cur]; } strata::prefill::Gemm gemm; cublasHandle_t blas = nullptr; float* att_s = nullptr; // the prompt attention's scores / probabilities, kAttScoreFloats floats @@ -1047,6 +1110,42 @@ struct Engine { bool use_graph = true; int mtp_d = 0; // MTP drafts per speculative step (0: none; greedy requests only) + // ---- sessions: the conversation states. One for a single-request engine; --batch N keeps N, each with its own + // recurrent state and KV cache, so N requests run at once: their rows share one decode window (forward_rows). The + // members conv / S / kc / vc / pos / hlast above are the CURRENT session's (select() swaps them). + struct Sess { + std::vector conv, S, kc, vc; + float* hlast = nullptr; + int64_t pos = 0; + int32_t rdelta = 0; // rotary offset of the text after the last picture (see k_attn_prep) + std::vector live; // the tokens whose state it holds (cell i = live[i]) + std::vector imgs; // the pictures among them + bool active = false; // a batch slot is decoding in it + uint64_t used = 0; // when it was last used (the LRU pick) + }; + std::vector sess; + int n_sess = 1, cur = 0; + uint64_t use_clock = 0; + // device tables for batch rows: per state index (layer, then the MTP block) the session pointers + float **d_conv_tab = nullptr, **d_S_tab = nullptr, **d_kc_tab = nullptr, **d_vc_tab = nullptr; + int32_t *d_rcell = nullptr, *d_rslot = nullptr, *d_rdelta = nullptr; // [kVerify] the rows' cell / session / rotary offset + int32_t* hrow = nullptr; // pinned staging for the rows + cudaGraphExec_t gb[kVerify + 1] = {}; // a batch window of nb rows + bool rows_mode = false; // layer(): the rows are sessions' (not consecutive cells) + int64_t rows_pmax = 0; // (eager) the highest cell of the rows + // pictures (--vision): the request's rows replace the embeddings of its <|image_pad|> cells; M-RoPE + bool vision = false; + int32_t* d_mtab = nullptr; // [ctx][3] t, h, w of the current request's prompt cells (vision) + const int32_t* mtab_now = nullptr; // set for a forward over prompt cells that need it, else null + int32_t* d_delta = nullptr; // device scalar: the current session's rotary offset (decode graphs read it) + float* d_img = nullptr; // the request's picture rows [n][N] + size_t img_cap = 0; // floats + int32_t* d_map = nullptr; // [tmax] a chunk's row -> picture row (or -1) + int32_t* h_map = nullptr; // pinned + bool map_on = false; // this forward's embeddings take picture rows + std::vector img_map; // the request's cell -> picture row (-1: text) + int64_t img_prompt_cells = 0; // the request's prompt length: cells below it use the table + // ---- the hybrid mode (Model::hybrid): per state index (the layers, then the MTP block) the slot tables; a // batch of up to hybrid_t rows runs its VRAM-resident experts on the GPU and the others on the CPU pool, side by // side; a bigger prompt chunk streams each layer's experts into a staging buffer for MMQ (two, double-buffered) @@ -1104,15 +1203,66 @@ struct Engine { } } - void init(const Model& model, int ctx_, int tmax_) { + void alloc_session(Sess& ss) const { + const auto& g = m->g; + const size_t C = (size_t) g.ssm_conv_channels; + for (const Layer& L : m->layers) { + if (L.attn) { + ss.conv.push_back(nullptr); + ss.S.push_back(nullptr); + ss.kc.push_back(dalloc((size_t) g.n_head_kv * ctx * g.head_dim)); + ss.vc.push_back(dalloc((size_t) g.n_head_kv * ctx * g.head_dim)); + } else { + ss.conv.push_back(dalloc(C * (g.ssm_d_conv - 1))); + ss.S.push_back(dalloc((size_t) g.ssm_v_heads * g.ssm_state_size * g.ssm_state_size)); + ss.kc.push_back(nullptr); + ss.vc.push_back(nullptr); + } + } + if (m->has_mtp) { // the MTP block's own K / V (an attention layer at index n_layers) + ss.conv.push_back(nullptr); + ss.S.push_back(nullptr); + ss.kc.push_back(dalloc((size_t) g.n_head_kv * ctx * g.head_dim)); + ss.vc.push_back(dalloc((size_t) g.n_head_kv * ctx * g.head_dim)); + } + ss.hlast = dalloc((size_t) g.n_embd); + } + + /// The current session: `i`'s state, cache and position become the engine's (conv / S / kc / vc / pos / hlast). + void select(int i) { + if (i == cur) return; + sess[(size_t) cur].pos = pos; + cur = i; + load_cur(); + } + void load_cur() { + Sess& ss = sess[(size_t) cur]; + conv = ss.conv; S = ss.S; kc = ss.kc; vc = ss.vc; + hlast = ss.hlast; + pos = ss.pos; + ss.used = ++use_clock; + set_delta(ss.rdelta); + } + /// The rotary offset the decode graphs read (a device scalar), for the current session. + void set_delta(int32_t d) { + sess[(size_t) cur].rdelta = d; + if (!d_delta) return; + hpin[60] = d; + CK(cudaMemcpyAsync(d_delta, hpin + 60, 4, cudaMemcpyHostToDevice, st)); + CK(cudaStreamSynchronize(st)); // (the pinned word is reused) + } + + void init(const Model& model, int ctx_, int tmax_, int n_sessions = 1, bool vision_ = false) { m = &model; ctx = ctx_; + n_sess = std::max(1, std::min(n_sessions, kVerify)); + vision = vision_; tmax = std::max(tmax_, kVerify); const auto& g = m->g; const size_t T = (size_t) tmax, N = (size_t) g.n_embd, Kp = (size_t) m->top_k, FF = (size_t) g.n_ff; const size_t C = (size_t) g.ssm_conv_channels; CK(cudaStreamCreateWithFlags(&st, cudaStreamNonBlocking)); - x = dalloc(T * N); h = dalloc(T * N); y = dalloc(T * N); hmain = dalloc(T * N); hlast = dalloc(N); + x = dalloc(T * N); h = dalloc(T * N); y = dalloc(T * N); hmain = dalloc(T * N); qkv = dalloc(T * C); hc = dalloc(T * C); z = dalloc(T * g.ssm_value_dim); alpha = dalloc(T * g.ssm_v_heads); beta = dalloc(T * g.ssm_v_heads); gdn_y = dalloc(T * g.ssm_value_dim); qg = dalloc(T * 2 * g.n_head * g.head_dim); kx = dalloc(T * g.n_head_kv * g.head_dim); @@ -1195,29 +1345,17 @@ struct Engine { pacc = dalloc((size_t) att_rows * n_chunk * g.head_dim); pm = dalloc((size_t) att_rows * n_chunk); pl = dalloc((size_t) att_rows * n_chunk); - for (const Layer& L : m->layers) { + for (const Layer& L : m->layers) { // the verify windows' GDN inputs (one set, whichever session runs) if (L.attn) { - conv.push_back(nullptr); - S.push_back(nullptr); - kc.push_back(dalloc((size_t) g.n_head_kv * ctx * g.head_dim)); - vc.push_back(dalloc((size_t) g.n_head_kv * ctx * g.head_dim)); for (auto* v : {&v_qkv, &v_hc, &v_alpha, &v_beta}) v->push_back(nullptr); } else { - conv.push_back(dalloc(C * (g.ssm_d_conv - 1))); - S.push_back(dalloc((size_t) g.ssm_v_heads * g.ssm_state_size * g.ssm_state_size)); - kc.push_back(nullptr); - vc.push_back(nullptr); v_qkv.push_back(dalloc((size_t) kVerify * C)); v_hc.push_back(dalloc((size_t) kVerify * C)); v_alpha.push_back(dalloc((size_t) kVerify * g.ssm_v_heads)); v_beta.push_back(dalloc((size_t) kVerify * g.ssm_v_heads)); } } - if (m->has_mtp) { // the MTP block's own K / V (an attention layer at index n_layers) - conv.push_back(nullptr); - S.push_back(nullptr); - kc.push_back(dalloc((size_t) g.n_head_kv * ctx * g.head_dim)); - vc.push_back(dalloc((size_t) g.n_head_kv * ctx * g.head_dim)); + if (m->has_mtp) { mtp_cat = dalloc(T * 2 * N); hmtp = dalloc(T * N); logits_m = dalloc((size_t) g.n_vocab); @@ -1225,6 +1363,39 @@ struct Engine { pos0_m = dalloc_t(1); pick_m = dalloc_t(1); } + sess.resize((size_t) n_sess); + gsets.resize((size_t) n_sess); + for (Sess& ss : sess) alloc_session(ss); + if (n_sess > 1) { // the batch rows' tables: per state index the session pointers, on the device + const size_t ns = sess[0].conv.size(); + std::vector hc(ns * (size_t) n_sess), hs(hc), hk(hc), hv(hc); + for (size_t li = 0; li < ns; ++li) + for (int s_ = 0; s_ < n_sess; ++s_) { + hc[li * n_sess + s_] = sess[(size_t) s_].conv[li]; + hs[li * n_sess + s_] = sess[(size_t) s_].S[li]; + hk[li * n_sess + s_] = sess[(size_t) s_].kc[li]; + hv[li * n_sess + s_] = sess[(size_t) s_].vc[li]; + } + const std::pair*> tabs[4] = {{&d_conv_tab, &hc}, {&d_S_tab, &hs}, + {&d_kc_tab, &hk}, {&d_vc_tab, &hv}}; + for (const auto& tb : tabs) { + CK(cudaMalloc((void**) tb.first, tb.second->size() * sizeof(float*))); + CK(cudaMemcpy((void*) *tb.first, tb.second->data(), tb.second->size() * sizeof(float*), + cudaMemcpyHostToDevice)); + } + d_rcell = dalloc_t(kVerify); + d_rslot = dalloc_t(kVerify); + d_rdelta = dalloc_t(kVerify); + CK(cudaHostAlloc((void**) &hrow, 64 * sizeof(int32_t), cudaHostAllocDefault)); + } + if (vision) { + d_mtab = dalloc_t((size_t) ctx * 3); + d_map = dalloc_t(T); + CK(cudaHostAlloc((void**) &h_map, T * sizeof(int32_t), cudaHostAllocDefault)); + } + d_delta = dalloc_t(1); + cur = 0; + load_cur(); CK(cudaDeviceSynchronize()); // every legacy-stream cudaMemset of the buffers above is done size_t fr = 0, tot = 0; CK(cudaMemGetInfo(&fr, &tot)); @@ -1242,6 +1413,8 @@ struct Engine { CK(cudaMemsetAsync(hlast, 0, (size_t) g.n_embd * 4, st)); CK(cudaStreamSynchronize(st)); pos = 0; + sess[(size_t) cur].pos = 0; + set_delta(0); } /// y [T][n_out] = W x [T][n_in] on the native MMVQ, 8 columns per launch. @@ -1329,19 +1502,26 @@ struct Engine { f32mm(L.beta, h, be_b, N, HV, T); k_gdn_gb<<>>(al_b, L.dt, L.ssm_a, be_b, HV, T); } - // one token, a window or a chunk: the same kernels (every token in one launch each), so a decode step and a - // verify window compute bitwise the same rows and the MTP's greedy text is the plain greedy text. (Strata's - // fused single-token kernels are not used here: fused_gdn_conv_l2's 4-tap sum contracts into FMAs - // differently from k_conv_seq's, a 1-ulp difference in h that the Q8_1 activation rounding can turn into a - // flipped near-tie later; with them the KL is the same, 1.05x / 0.81x the floor, but MTP would not be exact.) - k_conv_seq<<>>(conv[li], qkv_b, L.conv, hc_b, C, 2 * HK, m->eps, T, !verify); - if (T > kGemmT && !verify) { // a prompt chunk: the column-split delta rule, then the norm - k_gdn_seq_cols<<>>(S[li], hc_b, C, al_b, - be_b, gdn_y, HK, HV, T); - k_gdn_norm<<>>(gdn_y, z, L.ssm_norm, m->eps, gdn_y, HV); - } else { // decode, verify windows and commits: one kernel, so a window's rows are a decode step's rows - k_gdn_seq<<>>(S[li], hc_b, C, al_b, be_b, z, L.ssm_norm, m->eps, gdn_y, HK, HV, - T, !verify); + if (rows_mode) { // batch rows: each row one token of its own session (grid y = row) + k_conv_seq<<>>(nullptr, qkv_b, L.conv, hc_b, C, 2 * HK, m->eps, 1, true, + d_conv_tab + li * n_sess, d_rslot); + k_gdn_seq<<>>(nullptr, hc_b, C, al_b, be_b, z, L.ssm_norm, m->eps, gdn_y, + HK, HV, 1, true, d_S_tab + li * n_sess, d_rslot); + } else { + // one token, a window or a chunk: the same kernels (every token in one launch each), so a decode step and a + // verify window compute bitwise the same rows and the MTP's greedy text is the plain greedy text. (Strata's + // fused single-token kernels are not used here: fused_gdn_conv_l2's 4-tap sum contracts into FMAs + // differently from k_conv_seq's, a 1-ulp difference in h that the Q8_1 activation rounding can turn into a + // flipped near-tie later; with them the KL is the same, 1.05x / 0.81x the floor, but MTP would not be exact.) + k_conv_seq<<>>(conv[li], qkv_b, L.conv, hc_b, C, 2 * HK, m->eps, T, !verify); + if (T > kGemmT && !verify) { // a prompt chunk: the column-split delta rule, then the norm + k_gdn_seq_cols<<>>(S[li], hc_b, C, al_b, + be_b, gdn_y, HK, HV, T); + k_gdn_norm<<>>(gdn_y, z, L.ssm_norm, m->eps, gdn_y, HV); + } else { // decode, verify windows and commits: one kernel, so a window's rows are a decode step's rows + k_gdn_seq<<>>(S[li], hc_b, C, al_b, be_b, z, L.ssm_norm, m->eps, gdn_y, HK, HV, + T, !verify); + } } mm(L.ssm_out, gdn_y, y, T); } else { @@ -1349,8 +1529,17 @@ struct Engine { apply(L.wq, xq, qg, T); apply(L.wk, xq, kx, T); apply(L.wv, xq, vx, T); - k_attn_prep<<>>(qg, kx, vx, L.q_norm, L.k_norm, q, gate, kc[li], vc[li], H, - HKV, HD, m->n_rot, dpos, ctx, m->rope_base, m->eps); + RowSel rs; + if (rows_mode) { + rs.cell = d_rcell; + rs.slot = d_rslot; + rs.delta = d_rdelta; + rs.kc = d_kc_tab + li * n_sess; + rs.vc = d_vc_tab + li * n_sess; + } + k_attn_prep<<>>(qg, kx, vx, L.q_norm, L.k_norm, q, gate, rows_mode ? nullptr : kc[li], + rows_mode ? nullptr : vc[li], H, HKV, HD, m->n_rot, dpos, ctx, + m->rope_base, m->eps, d_delta, mtab_now, rs); if (T > kGemmT) { // a prompt chunk: scores = Q K^T and out = P V as FP16 GEMMs (FP32 accumulation, FP32 scores) per KV // head (its query heads one strided batch over the shared K / V), the causal softmax in between writing @@ -1400,9 +1589,10 @@ struct Engine { const int nt = std::min(rows_per, T - t0); const int nc = graph_mode ? n_chunk : (int) std::min(n_chunk, (p0 + t0 + nt + kChunkCells - 1) / kChunkCells); - k_attn_part<<>>(q, kc[li], vc[li], dpos, t0, H, HKV, ctx, - 1.0f / sqrtf((float) HD), n_chunk, pacc, pm, pl); - k_attn_merge<<>>(pacc, pm, pl, gate, dpos, t0, H, n_chunk, att); + k_attn_part<<>>(q, rows_mode ? nullptr : kc[li], + rows_mode ? nullptr : vc[li], dpos, t0, H, HKV, ctx, + 1.0f / sqrtf((float) HD), n_chunk, pacc, pm, pl, rs); + k_attn_merge<<>>(pacc, pm, pl, gate, dpos, t0, H, n_chunk, att, rs); } } mm(L.wo, att, y, T); @@ -1489,6 +1679,7 @@ struct Engine { stream_begin(seq); } K::iq_embed_rows(m->embd_type, m->embd, m->embd_row, tok, T, N, x, st); + if (map_on) k_put_rows<<>>(x, d_img, d_map, N); // a picture's cells take its rows k_rms<<>>(x, m->layers[0].attn_norm, h, N, m->eps); // later layers: from k_moe_out for (size_t l = 0; l < m->layers.size(); ++l) { const bool last = l + 1 == m->layers.size(); @@ -1513,6 +1704,7 @@ struct Engine { const int N = (int) g.n_embd; if (main_hybrid && lhy(m->layers.size()) && T > hybrid_t && use_mmq) stream_begin({(int) m->layers.size()}); K::iq_embed_rows(m->embd_type, m->embd, m->embd_row, tok_m, T, N, y, st); + if (map_on) k_put_rows<<>>(y, d_img, d_map, N); k_rms_ld<<>>(y, N, m->mtp_enorm, mtp_cat, 2 * N, N, m->eps); // [e | ...] k_rms_ld<<>>(seeds, N, m->mtp_hnorm, mtp_cat + N, 2 * N, N, m->eps); // [... | h] mm(m->eh_proj, mtp_cat, x, T); @@ -1729,9 +1921,13 @@ struct Engine { CK(cudaDeviceSynchronize()); } void reset_graphs() { - for (cudaGraphExec_t* g : {&g1, &gm1}) - if (*g) { CK(cudaGraphExecDestroy(*g)); *g = nullptr; } - for (auto& g : gv) + for (GSet& gset : gsets) { + for (cudaGraphExec_t* g : {&gset.g1, &gset.gm1}) + if (*g) { CK(cudaGraphExecDestroy(*g)); *g = nullptr; } + for (auto& g : gset.gv) + if (g) { CK(cudaGraphExecDestroy(g)); g = nullptr; } + } + for (auto& g : gb) if (g) { CK(cudaGraphExecDestroy(g)); g = nullptr; } } @@ -1748,25 +1944,87 @@ struct Engine { CK(cudaGraphLaunch(gx, st)); } + // ---- pictures (--vision). A request with pictures hands the engine its rows (the encoder's, in prompt order), the + // cell -> row map of its <|image_pad|> cells and the M-RoPE table of its prompt cells; the cells below the prompt + // length take their rotary positions from the table, the text after it continues at cell + delta (what the pictures + // did not use of their cells: llama.cpp's mtmd advances the text position by max(nx, ny) per picture). + bool img_active = false; + void set_images(const std::vector& rows, const std::vector& cell_row, const std::vector& mrope, + int64_t n_prompt, int32_t delta) { + const size_t need = rows.size(); + if (need > img_cap) { + CK(cudaDeviceSynchronize()); + if (d_img) CK(cudaFree(d_img)); + CK(cudaMalloc((void**) &d_img, need * 4)); + img_cap = need; + } + CK(cudaMemcpy(d_img, rows.data(), need * 4, cudaMemcpyHostToDevice)); + CK(cudaMemcpy(d_mtab, mrope.data(), mrope.size() * 4, cudaMemcpyHostToDevice)); + img_map = cell_row; + img_prompt_cells = n_prompt; + img_active = true; + set_delta(delta); + } + void clear_images() { + img_map.clear(); + img_active = false; + img_prompt_cells = 0; + mtab_now = nullptr; + map_on = false; + set_delta(0); + } + /// A forward over the cells [c0, c0 + T): the picture rows of its cells, and the table when it is a prompt's. + void chunk_pictures(int64_t c0, int T) { + mtab_now = nullptr; + map_on = false; + if (!img_active) return; + if (c0 < img_prompt_cells) mtab_now = d_mtab; + bool any = false; + for (int j = 0; j < T; ++j) { + const int64_t c = c0 + j; + const int32_t v = c < (int64_t) img_map.size() ? img_map[(size_t) c] : -1; + h_map[j] = v; + any = any || v >= 0; + } + if (any) { + CK(cudaMemcpyAsync(d_map, h_map, (size_t) T * 4, cudaMemcpyHostToDevice, st)); + map_on = true; + } + } + /// The tokens at the current position: a prompt in chunks (eager), one token from the decode graph. The last /// token's logits stay in `logits` (its greedy pick in `pick`), hlast its normed hidden. With the MTP block the - /// prompt also runs through it (its K / V for every position: row q reads h_{q-1} and token q). - template void process(const int32_t* toks, int64_t n, F on_chunk) { + /// prompt also runs through it (its K / V for every position: row q reads h_{q-1} and token q). on_chunk(done) runs + /// after every chunk; false ends the read there (a cancelled request): the tokens processed are returned. + template int64_t process(const int32_t* toks, int64_t n, F on_chunk_) { const int N = (int) m->g.n_embd; + auto on_chunk = [&](int64_t done) -> bool { // a callback returning void never cancels + if constexpr (std::is_void_v) { + on_chunk_(done); + return true; + } else { + return on_chunk_(done); + } + }; if (n == 1) { CK(cudaStreamSynchronize(st)); // the pinned staging is free again hpin[0] = toks[0]; hpin[1] = (int32_t) pos; CK(cudaMemcpyAsync(tok, hpin, 4, cudaMemcpyHostToDevice, st)); CK(cudaMemcpyAsync(pos0, hpin + 1, 4, cudaMemcpyHostToDevice, st)); + chunk_pictures(pos, 1); rows_deferred = true; - graph_run(g1, [&] { forward(1, pos, 1, use_graph, false); }); + // a prompt cell of a picture request (its rotary position is in the table, its row a picture's) runs eagerly + if (mtab_now || map_on) forward(1, pos, 1, false, false); + else graph_run(gs().g1, [&] { forward(1, pos, 1, use_graph, false); }); + mtab_now = nullptr; + map_on = false; rows_deferred = false; CK(cudaMemcpyAsync(hlast, hmain, (size_t) N * 4, cudaMemcpyDeviceToDevice, st)); pos += 1; after_rows(1); on_chunk(1); - return; + return 1; } for (int64_t i = 0; i < n; i += tmax) { const int T = (int) std::min(tmax, n - i); @@ -1774,6 +2032,7 @@ struct Engine { hpin[1] = (int32_t) pos; CK(cudaMemcpyAsync(tok, toks + i, (size_t) T * 4, cudaMemcpyHostToDevice, st)); CK(cudaMemcpyAsync(pos0, hpin + 1, 4, cudaMemcpyHostToDevice, st)); + chunk_pictures(pos, T); forward(T, pos, i + T == n ? 1 : 0, false, false); if (m->has_mtp && mtp_d > 0) { // seeds: h_{q-1} for each row q: hlast, then this chunk's rows 0 .. T - 2 (in `y`, free here) @@ -1787,9 +2046,95 @@ struct Engine { CK(cudaMemcpyAsync(hlast, hmain + (size_t) (T - 1) * N, (size_t) N * 4, cudaMemcpyDeviceToDevice, st)); pos += T; CK(cudaStreamSynchronize(st)); - on_chunk(i + T); + mtab_now = nullptr; + map_on = false; + if (!on_chunk(i + T)) { + if (m->hybrid) rebalance(hybrid_swaps_after_prompt); + return i + T; + } } if (m->hybrid) rebalance(hybrid_swaps_after_prompt); + return n; + } + + // ---- batch rows: one decode window for the next token of several sessions + struct Row { int slot; int32_t tok; }; + long long win_count = 0; + /// One window over the rows (each the next token of its own session, at that session's position): the greedy picks + /// end up in rows_pick, every row's logits in `logits`. The sessions' positions advance. + int32_t rows_pick[kVerify] = {}; + void step_rows(const Row* rows, int nb) { + sess[(size_t) cur].pos = pos; + CK(cudaStreamSynchronize(st)); // the pinned staging is free again + int64_t pmax = 0; + for (int r = 0; r < nb; ++r) { + const Sess& ss = sess[(size_t) rows[r].slot]; + hrow[r] = rows[r].tok; + hrow[8 + r] = (int32_t) ss.pos; + hrow[16 + r] = rows[r].slot; + hrow[24 + r] = ss.rdelta; + pmax = std::max(pmax, ss.pos); + } + CK(cudaMemcpyAsync(tok, hrow, (size_t) nb * 4, cudaMemcpyHostToDevice, st)); + CK(cudaMemcpyAsync(d_rcell, hrow + 8, (size_t) nb * 4, cudaMemcpyHostToDevice, st)); + CK(cudaMemcpyAsync(d_rslot, hrow + 16, (size_t) nb * 4, cudaMemcpyHostToDevice, st)); + CK(cudaMemcpyAsync(d_rdelta, hrow + 24, (size_t) nb * 4, cudaMemcpyHostToDevice, st)); + mtab_now = nullptr; + map_on = false; + rows_mode = true; + rows_deferred = true; + graph_run(gb[nb], [&] { forward(nb, pmax, nb, use_graph, false); }); + rows_deferred = false; + rows_mode = false; + CK(cudaMemcpyAsync(hrow + 32, pick, (size_t) nb * 4, cudaMemcpyDeviceToHost, st)); + CK(cudaStreamSynchronize(st)); + for (int r = 0; r < nb; ++r) { + rows_pick[r] = hrow[32 + r]; + ++sess[(size_t) rows[r].slot].pos; + } + pos = sess[(size_t) cur].pos; + if (m->hybrid) { + count_rows(nb); + if (++win_count % kRebalanceEvery == 0) rebalance(8); + } + } + /// Row r's logits of the last step_rows, on the host. + void host_logits_row(int r, std::vector& out) { + out.resize((size_t) m->g.n_vocab); + CK(cudaMemcpyAsync(out.data(), logits + (size_t) r * m->g.n_vocab, out.size() * 4, cudaMemcpyDeviceToHost, st)); + CK(cudaStreamSynchronize(st)); + } + + /// Session dst takes session src's state: the recurrent state, the cache's first src.pos cells, the position, the + /// pictures' offset (for a conversation read in one session that continues in another). + void copy_session(int src, int dst) { + if (src == dst) return; + sess[(size_t) cur].pos = pos; + const auto& g = m->g; + const Sess& a = sess[(size_t) src]; + Sess& b = sess[(size_t) dst]; + const size_t C = (size_t) g.ssm_conv_channels; + const size_t row = (size_t) ctx * g.head_dim * 4; + for (size_t l = 0; l < a.conv.size(); ++l) { + if (a.conv[l]) { + CK(cudaMemcpyAsync(b.conv[l], a.conv[l], C * (g.ssm_d_conv - 1) * 4, cudaMemcpyDeviceToDevice, st)); + CK(cudaMemcpyAsync(b.S[l], a.S[l], (size_t) g.ssm_v_heads * g.ssm_state_size * g.ssm_state_size * 4, + cudaMemcpyDeviceToDevice, st)); + } + if (a.kc[l] && a.pos > 0) { + CK(cudaMemcpy2DAsync(b.kc[l], row, a.kc[l], row, (size_t) a.pos * g.head_dim * 4, (size_t) g.n_head_kv, + cudaMemcpyDeviceToDevice, st)); + CK(cudaMemcpy2DAsync(b.vc[l], row, a.vc[l], row, (size_t) a.pos * g.head_dim * 4, (size_t) g.n_head_kv, + cudaMemcpyDeviceToDevice, st)); + } + } + CK(cudaMemcpyAsync(b.hlast, a.hlast, (size_t) g.n_embd * 4, cudaMemcpyDeviceToDevice, st)); + CK(cudaStreamSynchronize(st)); + b.pos = a.pos; + b.rdelta = a.rdelta; + b.live = a.live; + b.imgs = a.imgs; + if (dst == cur) load_cur(); } int hybrid_swaps_after_prompt = 2048; /// the MTP seed rows of a prompt chunk: a buffer the block's own forward does not use (`moe_out`, [tmax][N]) @@ -1830,7 +2175,7 @@ struct Engine { CK(cudaMemcpyAsync(pos0_m, hpin + 1, 4, cudaMemcpyHostToDevice, st)); CK(cudaMemcpyAsync(seeds, hmtp + (size_t) last_row * N, (size_t) N * 4, cudaMemcpyDeviceToDevice, st)); last_row = 0; - if (mtp_graph) graph_run(gm1, [&] { forward_mtp(1, pos + d, seeds, true, use_graph); }); + if (mtp_graph) graph_run(gs().gm1, [&] { forward_mtp(1, pos + d, seeds, true, use_graph); }); else forward_mtp(1, pos + d, seeds, true, false); CK(cudaMemcpyAsync(hpin + 2, pick_m, 4, cudaMemcpyDeviceToHost, st)); CK(cudaStreamSynchronize(st)); @@ -1844,7 +2189,7 @@ struct Engine { CK(cudaMemcpyAsync(tok, hpin + 16, (size_t) T * 4, cudaMemcpyHostToDevice, st)); CK(cudaMemcpyAsync(pos0, hpin + 1, 4, cudaMemcpyHostToDevice, st)); rows_deferred = true; - graph_run(gv[T], [&] { forward(T, pos, T, use_graph, true); }); + graph_run(gs().gv[T], [&] { forward(T, pos, T, use_graph, true); }); rows_deferred = false; CK(cudaMemcpyAsync(hpin + 2, pick, (size_t) T * 4, cudaMemcpyDeviceToHost, st)); CK(cudaStreamSynchronize(st)); @@ -2164,49 +2509,226 @@ std::vector parse_ids(const char* s) { bool is_eos(int t) { return t == 248044 || t == 248046; } +// ------------------------------------------------------------------------------------------------ pictures +constexpr int32_t kImagePad = 248056; // <|image_pad|> + +uint64_t fnv1a(const void* p, size_t n, uint64_t h = 1469598103934665603ull) { + const uint8_t* b = (const uint8_t*) p; + for (size_t i = 0; i < n; ++i) h = (h ^ b[i]) * 1099511628211ull; + return h; +} + +/// A request's pictures: the encoder's rows in prompt order, each picture's cell run, and the positions. +struct ImgReq { + std::vector rows; + std::vector imgs; + std::vector cell_row; // per prompt cell: its row in `rows`, or -1 (text) + std::vector mrope; // [cell][3] t, h, w of every prompt cell (llama.cpp's mtmd positions) + int32_t delta = 0; // the text after the prompt: rotary position = cell + delta +}; + +/// Reads a strata-vision file (one or more records: int32 'SVE1', n, nx, ny, n_embd, then n x n_embd floats, in prompt +/// order) and lays the pictures over the prompt's <|image_pad|> runs. Positions as mtmd's: text counts up by one; a +/// picture's cells take (t, h, w) = (p, p + row, p + column) and the text after it continues at p + max(nx, ny). "" or +/// the error. `keys`: the server's key for each picture (img_keys=), else the embeddings' hash. +std::string build_images(const std::string& path, const std::vector& ids, int64_t n_embd, + const std::vector& keys, ImgReq& r) { + struct Img { int64_t n, nx, ny; size_t off; }; + std::vector imgs; + std::FILE* f = std::fopen(path.c_str(), "rb"); + if (!f) return "cannot open " + path; + std::string ve; + while (ve.empty()) { + int32_t hdr[5]; + const size_t got = std::fread(hdr, sizeof(int32_t), 5, f); + if (got == 0) break; + if (got != 5 || hdr[0] != 0x31455653 || hdr[1] < 1 || hdr[2] < 1 || hdr[3] < 1 || (int64_t) hdr[2] * hdr[3] != hdr[1] || + hdr[4] != (int32_t) n_embd) { + ve = "bad embeddings file (expected strata-vision records of width " + std::to_string((long long) n_embd) + ")"; + break; + } + const size_t off = r.rows.size(), cnt = (size_t) hdr[1] * (size_t) hdr[4]; + r.rows.resize(off + cnt); + if (std::fread(r.rows.data() + off, sizeof(float), cnt, f) != cnt) { ve = "short embeddings file"; break; } + imgs.push_back({hdr[1], hdr[2], hdr[3], off}); + } + std::fclose(f); + if (!ve.empty()) return ve; + const int64_t n = (int64_t) ids.size(); + r.cell_row.assign((size_t) n, -1); + r.mrope.assign((size_t) n * 3, 0); + auto put = [&](int64_t c, int64_t t, int64_t h, int64_t w) { + r.mrope[(size_t) c * 3] = (int32_t) t; + r.mrope[(size_t) c * 3 + 1] = (int32_t) h; + r.mrope[(size_t) c * 3 + 2] = (int32_t) w; + }; + int64_t p = 0, i = 0; + size_t k = 0; + while (i < n) { + if (ids[(size_t) i] != kImagePad) { put(i, p, p, p); ++p; ++i; continue; } + if (k >= imgs.size()) return "the prompt has more images than the embeddings file"; + const Img& im = imgs[k++]; + uint64_t h; + { // what the conversation cache compares: a picture is its grid and its key (or its embeddings) + const int64_t grid[3] = {im.n, im.nx, im.ny}; + h = fnv1a(grid, sizeof grid); + if (keys.size() == imgs.size()) h = fnv1a(&keys[k - 1], sizeof(uint64_t), h); + else h = fnv1a(r.rows.data() + im.off, (size_t) im.n * (size_t) n_embd * sizeof(float), h); + } + r.imgs.push_back({i, im.n, h}); + for (int64_t j = 0; j < im.n; ++j) + if (i + j >= n || ids[(size_t) (i + j)] != kImagePad) + return "image " + std::to_string(k) + " has " + std::to_string((long long) im.n) + + " rows but fewer <|image_pad|> tokens"; + for (int64_t j = 0; j < im.n; ++j) { + const int64_t y = j / im.nx, x = j % im.nx; + put(i + j, p, p + y, p + x); + r.cell_row[(size_t) (i + j)] = (int32_t) ((im.off / (size_t) n_embd) + (size_t) j); + } + i += im.n; + p += std::max(im.nx, im.ny); + } + if (k != imgs.size()) return "the embeddings file has more images than the prompt"; + if (n > 0 && ids[(size_t) (n - 1)] == kImagePad) return "the prompt cannot end in an image"; + r.delta = (int32_t) (p - n); + return ""; +} + // ------------------------------------------------------------------------------------------------ serve -int serve(Engine& E) { - std::printf("READY %d stop\n", E.ctx); - std::fflush(stdout); +/// A batch slot: a session decoding (its next token is `x`, not yet in the state). +struct Slot { + bool active = false, stop = false; + int32_t x = 0; + int64_t produced = 0, max_new = 0; + Sampling smp; + std::mt19937_64 rng; + std::vector hist; + Clock::time_point t0; +}; + +/// The engine protocol (serve/server.py). One request at a time on the control lines: GEN / GENI (alone: speculative +/// steps with the MTP block), or with --batch N BGEN / BGENI (the request's prompt is read into that slot's +/// session - the decode windows of the other slots go on between its chunks - then its tokens come as BT lines, one +/// window for every slot decoding, until BDONE). BSTOP ends a slot at its next window; STOP the request on the +/// control lines. +struct Serve { + Engine& E; std::mutex mu; std::condition_variable cv; std::deque lines; bool eof = false; std::atomic stop{false}; - std::thread reader([&] { - std::string l; - while (std::getline(std::cin, l)) { - if (!l.empty() && l.back() == '\r') l.pop_back(); - if (l == "STOP") { stop.store(true); continue; } - std::lock_guard lk(mu); - lines.push_back(l); - cv.notify_one(); - } - std::lock_guard lk(mu); - eof = true; - cv.notify_one(); - }); - reader.detach(); - std::vector live; // the tokens whose state the engine holds (cell i = live[i]) + std::vector slots; + int n_active = 0; std::vector lg; - for (;;) { - std::string line; - { - std::unique_lock lk(mu); - cv.wait(lk, [&] { return eof || !lines.empty(); }); - if (lines.empty()) return 0; - line = lines.front(); - lines.pop_front(); + + explicit Serve(Engine& e) : E(e), slots((size_t) e.n_sess) {} + + /// BSTOP / BYIELD lines among the queued ones: applied now (a window is a moment away at most). + void poll_control() { + std::lock_guard lk(mu); + for (auto it = lines.begin(); it != lines.end();) { + if (it->rfind("BSTOP ", 0) == 0) { + const int b = std::atoi(it->c_str() + 6); + if (b >= 0 && b < (int) slots.size()) slots[(size_t) b].stop = true; + it = lines.erase(it); + } else if (it->rfind("BYIELD", 0) == 0) { // (a read here does not give way: the server then goes on) + it = lines.erase(it); + } else { + ++it; + } } - if (line.empty()) continue; - if (line.rfind("GEN ", 0) != 0) { - std::printf("ERR expected: GEN [key=value ...] \n"); + } + + /// One decode window over every active slot: one token each. + void window() { + poll_control(); + std::vector rows; + for (int b = 0; b < E.n_sess; ++b) + if (slots[(size_t) b].active) rows.push_back({b, slots[(size_t) b].x}); + if (rows.empty()) return; + E.step_rows(rows.data(), (int) rows.size()); + for (size_t r = 0; r < rows.size(); ++r) { + const int b = rows[r].slot; + Slot& sl = slots[(size_t) b]; + Engine::Sess& ss = E.sess[(size_t) b]; + ss.live.push_back(sl.x); + int y; + if (sl.smp.needs_logits()) { + E.host_logits_row((int) r, lg); + y = sample(lg, sl.smp, sl.hist, sl.rng); + } else { + y = E.rows_pick[r]; + } + std::printf("BT %d %d\n", b, y); + ++sl.produced; + sl.hist.push_back(y); + const char* fin = is_eos(y) ? "stop" : sl.stop ? "cancel" : sl.produced >= sl.max_new ? "length" + : ss.pos + 1 > E.ctx ? "length" : nullptr; + if (fin) { + std::printf("BDONE %d %lld %s %.1f\n", b, (long long) sl.produced, fin, ms_since(sl.t0)); + sl.active = false; + ss.active = false; + --n_active; + } else { + sl.x = y; + } + } + std::fflush(stdout); + } + + /// The length of session ss's held tokens when they are a proper start of `ids` with the same pictures, else 0. + size_t match_len(const Engine::Sess& ss, const std::vector& ids, const std::vector& imgs) const { + const size_t L = ss.live.size(); + if (L == 0 || L >= ids.size() || !std::equal(ss.live.begin(), ss.live.end(), ids.begin())) return 0; + std::vector in_live; + for (const ImgKey& k : imgs) { + if (k.cell + k.n <= (int64_t) L) in_live.push_back(k); + else if (k.cell < (int64_t) L) return 0; // the held tokens end inside a picture + } + return in_live == ss.imgs ? L : 0; + } + + /// The session a request alone takes: the one holding the longest start of its prompt, else an empty one, else the + /// least recently used (never a decoding slot). + int pick_session(const std::vector& ids, const std::vector& imgs) const { + int best = -1, free_empty = -1, lru = -1; + size_t bl = 0; + for (int i = 0; i < E.n_sess; ++i) { + const Engine::Sess& ss = E.sess[(size_t) i]; + if (ss.active) continue; + const size_t l = match_len(ss, ids, imgs); + if (l > bl) { bl = l; best = i; } + if (ss.live.empty() && free_empty < 0) free_empty = i; + if (lru < 0 || ss.used < E.sess[(size_t) lru].used) lru = i; + } + return best >= 0 ? best : free_empty >= 0 ? free_empty : lru; + } + + void request(const std::string& line) { + const bool adm = line[0] == 'B'; + const bool geni = line.rfind(adm ? "BGENI " : "GENI ", 0) == 0; + if (!adm && !geni && line.rfind("GEN ", 0) != 0) { + std::printf("ERR expected: GEN [key=value ...] or GENI [keys] \n"); std::fflush(stdout); - continue; + return; } - char* p = nullptr; - const long long max_new = std::strtoll(line.c_str() + 4, &p, 10); + char* p = const_cast(line.c_str()) + (adm ? (geni ? 6 : 5) : (geni ? 5 : 4)); + int slot = -1; + if (adm) { + char* e1 = nullptr; + const long b = std::strtol(p, &e1, 10); + p = e1; + slot = (int) b; + if (e1 == line.c_str() || b < 0 || b >= (long) slots.size() || slots[(size_t) b].active || E.n_sess < 2) { + std::printf("ERR BGEN: no such free slot (--batch %d) or a bad max_new\n", E.n_sess < 2 ? 0 : E.n_sess); + std::fflush(stdout); + return; + } + } + const long long max_new = std::strtoll(p, &p, 10); Sampling smp; + std::vector img_keys; for (;;) { while (*p == ' ') ++p; const char* st0 = p; @@ -2225,49 +2747,150 @@ int serve(Engine& E) { else if (key == "penalty_freq") smp.freq = std::strtof(v, nullptr); else if (key == "penalty_present") smp.present = std::strtof(v, nullptr); else if (key == "seed") smp.seed = std::strtoull(v, nullptr, 10); + else if (key == "img_keys") { + const char* q = v; + img_keys.clear(); + while (*q) { + char* qe = nullptr; + const unsigned long long x = std::strtoull(q, &qe, 16); + if (qe == q) { img_keys.clear(); break; } + img_keys.push_back((uint64_t) x); + q = *qe == ',' ? qe + 1 : qe; + if (*qe != ',' && *qe != '\0') { img_keys.clear(); break; } + } + } + } + std::string emb; + if (geni) { + while (*p == ' ') ++p; + const char* e = p; + while (*e && *e != ' ') ++e; + emb.assign(p, (size_t) (e - p)); + p = const_cast(e); } const std::vector ids = parse_ids(p); - if (max_new < 1 || ids.empty()) { + if (max_new < 1 || ids.empty() || (geni && emb.empty())) { std::printf("ERR bad request: max_new or the ids\n"); std::fflush(stdout); - continue; + return; + } + if (geni && !E.vision) { + std::printf("ERR this engine was started without --vision\n"); + std::fflush(stdout); + return; } if ((int64_t) ids.size() + max_new > E.ctx) { std::printf("ERR prompt (%zu tokens) + max_new (%lld) exceeds the context (%d)\n", ids.size(), max_new, E.ctx); std::fflush(stdout); - continue; + return; } bool bad = false; for (int32_t t : ids) bad |= t < 0 || t >= (int32_t) E.m->g.n_vocab; - if (bad) { std::printf("ERR a token id is outside the vocabulary\n"); std::fflush(stdout); continue; } - stop.store(false); - // the held state continues when the request extends it (the recurrent state cannot step back) - size_t reuse = 0; - if (live.size() < ids.size() && std::equal(live.begin(), live.end(), ids.begin())) reuse = live.size(); - else { - E.reset(); - live.clear(); + if (bad) { std::printf("ERR a token id is outside the vocabulary\n"); std::fflush(stdout); return; } + ImgReq ir; + if (geni) { + const std::string ve = build_images(emb, ids, E.m->g.n_embd, img_keys, ir); + if (!ve.empty()) { std::printf("ERR %s\n", ve.c_str()); std::fflush(stdout); return; } } + stop.store(false); + // ---- the session: the held state continues when the request extends it (the recurrent state cannot step back) + const int s = adm ? slot : pick_session(ids, ir.imgs); + Engine::Sess& ss = E.sess[(size_t) s]; + size_t reuse = match_len(ss, ids, ir.imgs); + if (adm) { // another session holding more of this prompt (the conversation was read alone): copy its state + int src = -1; + size_t best = reuse; + for (int i = 0; i < E.n_sess; ++i) { + if (i == s || E.sess[(size_t) i].active) continue; + const size_t l = match_len(E.sess[(size_t) i], ids, ir.imgs); + if (l > best) { best = l; src = i; } + } + if (src >= 0) { + E.copy_session(src, s); + reuse = best; + } + } + E.select(s); + if (reuse == 0) { + E.reset(); + ss.live.clear(); + ss.imgs.clear(); + } + if (geni) E.set_images(ir.rows, ir.cell_row, ir.mrope, (int64_t) ids.size(), ir.delta); + else E.clear_images(); const auto t0 = Clock::now(); const int64_t fresh = (int64_t) (ids.size() - reuse); - E.process(ids.data() + reuse, fresh, [&](int64_t done) { + bool cancelled = false; + const int64_t got = E.process(ids.data() + reuse, fresh, [&](int64_t done) -> bool { std::printf("PP %lld %lld %.0f %.1f\n", (long long) done, (long long) fresh, ms_since(t0), (double) done / std::max(1e-9, ms_since(t0) / 1000.0)); std::fflush(stdout); + if (n_active > 0 && done < fresh) window(); // the slots decoding go on between a read's chunks (the + else poll_control(); // last chunk's logits must stay for the first token) + if (stop.load() && done < fresh) { cancelled = true; return false; } + return true; }); - live.insert(live.end(), ids.begin() + (long) reuse, ids.end()); + ss.live.insert(ss.live.end(), ids.begin() + (long) reuse, ids.begin() + (long) reuse + (long) got); + ss.imgs.clear(); + bool cut = false; + for (const ImgKey& k : ir.imgs) { + if (k.cell + k.n <= (int64_t) ss.live.size()) ss.imgs.push_back(k); + else if (k.cell < (int64_t) ss.live.size()) cut = true; + } + if (cancelled && cut) { // stopped inside a picture: the state cannot be continued, the next read starts over + ss.live.clear(); + ss.imgs.clear(); + } + E.sess[(size_t) E.cur].pos = E.pos; const double prompt_ms = ms_since(t0); + if (cancelled) { + std::printf("DONE 0 %zu %.1f 0.0 cancel 0 0 %zu 0 0 0 0 0.0 %lld 0\n", ids.size(), prompt_ms, reuse, (long long) got); + if (adm) std::printf("BADM %d 0\n", slot); + std::fflush(stdout); + return; + } std::mt19937_64 rng(smp.seed); std::vector hist = ids; const auto d0 = Clock::now(); long long produced = 0, offered = 0, accepted = 0; const char* finish = "length"; - // greedy requests with the MTP block: speculative steps of mtp_d drafts (verified, so the text is the greedy - // text); sampled ones one token at a time - const bool spec = E.mtp_d > 0 && !smp.needs_logits(); + // greedy requests alone with the MTP block: speculative steps of mtp_d drafts (verified, so the text is the greedy + // text); sampled ones, and requests beside others, one token at a time + const bool spec = E.mtp_d > 0 && !smp.needs_logits() && !adm; std::vector fix, drafts; int32_t picks[16]; int nx = smp.needs_logits() ? -1 : E.greedy(); + if (adm) { + if (smp.needs_logits()) { + E.host_logits(lg); + nx = sample(lg, smp, hist, rng); + } + std::printf("T %d\n", nx); + ++produced; + hist.push_back(nx); + const char* fin = is_eos(nx) ? "stop" : stop.load() ? "cancel" : max_new <= 1 ? "length" + : E.pos + 1 > E.ctx ? "length" : nullptr; + const bool cont = fin == nullptr; + std::printf("DONE %lld %zu %.1f %.1f %s 0 0 %zu 0 0 0 0 0.0 %lld 0\n", produced, ids.size(), prompt_ms, + ms_since(d0), cont ? "length" : fin, reuse, (long long) fresh); + if (cont) { + Slot& sl = slots[(size_t) slot]; + sl = Slot{}; + sl.active = true; + sl.x = nx; + sl.produced = 1; + sl.max_new = max_new; + sl.smp = smp; + sl.rng = rng; + sl.hist = hist; + sl.t0 = Clock::now(); + ss.active = true; + ++n_active; + } + std::printf("BADM %d %d\n", slot, cont ? 1 : 0); + std::fflush(stdout); + return; + } bool done = false; while (!done) { if (smp.needs_logits()) { @@ -2285,14 +2908,15 @@ int serve(Engine& E) { return true; }; if (!emit(nx)) break; - if (spec && E.pos + E.mtp_d + 1 <= E.ctx) { + if (n_active > 0) window(); + if (spec && n_active == 0 && E.pos + E.mtp_d + 1 <= E.ctx) { const int a = E.spec_step(nx, fix, E.mtp_d, drafts, picks); offered += E.mtp_d; accepted += a; - live.push_back(nx); + ss.live.push_back(nx); fix.assign(drafts.begin(), drafts.begin() + a); for (int i = 0; i < a; ++i) { - live.push_back(drafts[(size_t) i]); + ss.live.push_back(drafts[(size_t) i]); if (!emit(drafts[(size_t) i])) { done = true; break; } } nx = picks[a]; @@ -2301,26 +2925,81 @@ int serve(Engine& E) { if (E.pos + 1 > E.ctx) break; const int32_t one = nx; E.process(&one, 1, [](int64_t) {}); - live.push_back(nx); + ss.live.push_back(nx); fix.clear(); if (!smp.needs_logits()) nx = E.greedy(); } + E.sess[(size_t) E.cur].pos = E.pos; const double decode_ms = ms_since(d0); std::printf("DONE %lld %zu %.1f %.1f %s %lld %lld %zu 0 0 0 0 0.0 %lld 0\n", produced, ids.size(), prompt_ms, decode_ms, finish, accepted, offered, reuse, (long long) fresh); std::fflush(stdout); } + + int run() { + if (E.n_sess > 1) std::printf("INFO batch_slots=%d slot_cache=1\n", E.n_sess); + std::printf("READY %d stop\n", E.ctx); + std::fflush(stdout); + std::thread reader([&] { + std::string l; + while (std::getline(std::cin, l)) { + if (!l.empty() && l.back() == '\r') l.pop_back(); + if (l == "STOP") { stop.store(true); continue; } + std::lock_guard lk(mu); + lines.push_back(l); + cv.notify_one(); + } + std::lock_guard lk(mu); + eof = true; + cv.notify_one(); + }); + reader.detach(); + for (;;) { + std::string line; + bool have = false; + { + std::unique_lock lk(mu); + if (n_active == 0) cv.wait(lk, [&] { return eof || !lines.empty(); }); + if (!lines.empty()) { + line = lines.front(); + lines.pop_front(); + have = true; + } else if (n_active == 0) { + return 0; + } + } + if (!have) { window(); continue; } + if (line.empty()) continue; + if (line.rfind("BSTOP ", 0) == 0) { + const int b = std::atoi(line.c_str() + 6); + if (b >= 0 && b < (int) slots.size()) slots[(size_t) b].stop = true; + } else if (line.rfind("BYIELD", 0) == 0) { + // (a read that has ended) + } else if (line.rfind("GEN", 0) == 0 || line.rfind("BGEN", 0) == 0) { + request(line); + } else { + std::printf("ERR expected: GEN [key=value ...] \n"); + std::fflush(stdout); + } + if (n_active > 0) window(); + } + } +}; + +int serve(Engine& E) { + Serve sv(E); + return sv.run(); } } // namespace int strata::qwen35::run(int argc, char** argv) { - std::string model, tokens, force, dump_full; + std::string model, tokens, force, dump_full, emb_file; int ctx = 32768, chunk = 0, n_gen = 64, bench_pp = 0, bench_tg = 0, mtp_d = 0, cpu_threads = 0, hybrid_rows = 128; double expert_vram = -1.0; bool warm = true; - int expert_slots = 0; - bool serve_mode = false, graph = true; + int expert_slots = 0, batch = 0; + bool serve_mode = false, graph = true, vision = false; for (int i = 1; i < argc; ++i) { const std::string a = argv[i]; auto next = [&]() -> std::string { @@ -2340,6 +3019,7 @@ int strata::qwen35::run(int argc, char** argv) { else if (a == "--tokens") tokens = next(); else if (a == "--n") n_gen = std::atoi(next().c_str()); else if (a == "--force") force = next(); + else if (a == "--emb") emb_file = next(); // --tokens with pictures: a strata-vision file (the ids carry <|image_pad|> runs) else if (a == "--dump-full-logits") dump_full = next(); else if (a == "--bench-pp") bench_pp = std::atoi(next().c_str()); else if (a == "--bench-tg") bench_tg = std::atoi(next().c_str()); @@ -2352,6 +3032,8 @@ int strata::qwen35::run(int argc, char** argv) { else std::fprintf(stderr, "strata-q36: ignoring --mtp %s (this family's MTP is the GGUF's own block: --mtp N " "drafts)\n", v.c_str()); } + else if (a == "--vision") vision = true; // pictures (GENI): the encoder is strata-vision's + else if (a == "--batch" || a == "--slots") batch = std::atoi(next().c_str()); // sessions decoding together else if (a == "--expert-vram") expert_vram = std::atof(next().c_str()); // GiB for the routed experts else if (a == "--cpu-threads") cpu_threads = std::atoi(next().c_str()); else if (a == "--expert-slots") expert_slots = std::atoi(next().c_str()); @@ -2411,7 +3093,7 @@ int strata::qwen35::run(int argc, char** argv) { std::fprintf(stderr, "strata-q36: chunk rule: free %.2f GiB (with %.2f packed), main experts %.2f GiB\n", fr / 1073741824.0, packed / 1073741824.0, experts / 1073741824.0); } - E.init(m, ctx, chunk); + E.init(m, ctx, chunk, batch, vision); if (!place_experts(m, E, expert_vram, cpu_threads, hybrid_rows, expert_slots, err)) { std::fprintf(stderr, "strata-q36: %s\n", err.c_str()); return 1; @@ -2462,6 +3144,15 @@ int strata::qwen35::run(int argc, char** argv) { FILE* ff = dump_full.empty() ? nullptr : std::fopen(dump_full.c_str(), "wb"); std::vector lg; std::vector gen; + if (!emb_file.empty()) { + if (!vision) { std::fprintf(stderr, "strata-q36: --emb needs --vision\n"); return 2; } + ImgReq ir; + const std::string ve = build_images(emb_file, prompt, m.g.n_embd, {}, ir); + if (!ve.empty()) { std::fprintf(stderr, "strata-q36: %s\n", ve.c_str()); return 2; } + E.set_images(ir.rows, ir.cell_row, ir.mrope, (int64_t) prompt.size(), ir.delta); + std::fprintf(stderr, "strata-q36: %zu picture(s), %zu rows, text after them at cell + %d\n", ir.imgs.size(), + ir.rows.size() / (size_t) m.g.n_embd, (int) ir.delta); + } const auto t0 = Clock::now(); E.process(prompt.data(), (int64_t) prompt.size(), [](int64_t) {}); const double pp_ms = ms_since(t0); diff --git a/tools/qwen35/q36_mtmd_dump.cpp b/tools/qwen35/q36_mtmd_dump.cpp new file mode 100644 index 00000000..55519bc3 --- /dev/null +++ b/tools/qwen35/q36_mtmd_dump.cpp @@ -0,0 +1,132 @@ +// tools/qwen35/q36_mtmd_dump.cpp - llama.cpp's side of the Qwen3.6 PICTURE check: the same GGUF and mmproj, llama.cpp's own +// mtmd library and graph (the M-RoPE positions of mtmd_helper_eval_chunk_single, qwen35moe's IMROPE). Prints the prompt's +// chunks (the text ids, the picture's token count) and the greedy ids, and dumps every step's full logits (f32, +// [step][vocab]) so the first token's logits can be compared with strata-q36's (--dump-full-logits there). +// +// Built against a llama.cpp checkout with its mtmd library (not part of Strata's build): +// g++ -O2 -std=c++17 q36_mtmd_dump.cpp -I/include -I/ggml/include -I/tools/mtmd -L/build/bin +// -lllama -lmtmd -lggml -lggml-base -Wl,-rpath,/build/bin -o q36_mtmd_dump +// Usage: q36_mtmd_dump --model GGUF --mmproj F --image F --prompt TEXT [--n 32] [--ngl 99] [--max-tokens N] [--mm-cpu 1] +// [--dump-full-logits F] [--force ID,ID,...] +// TEXT holds one <__media__> marker where the picture goes (the chat template's user turn); it is tokenized with +// special tokens parsed and no BOS. --force feeds that continuation instead of the greedy ids (teacher forcing). +#include "llama.h" +#include "mtmd.h" +#include "mtmd-helper.h" + +#include +#include +#include +#include +#include + +static std::vector parse_ids(const std::string& s) { + std::vector v; + const char* p = s.c_str(); + while (*p) { + while (*p == ',' || *p == ' ') ++p; + if (!*p) break; + v.push_back(std::atoi(p)); + while (*p && *p != ',' && *p != ' ') ++p; + } + return v; +} + +int main(int argc, char** argv) { + std::string model, mmproj, image, prompt, dump_full, force; + int n_gen = 32, ngl = 99, max_tokens = 0, mm_cpu = 0; + for (int i = 1; i + 1 < argc; i += 2) { + const std::string a = argv[i], v = argv[i + 1]; + if (a == "--model") model = v; + else if (a == "--mmproj") mmproj = v; + else if (a == "--image") image = v; + else if (a == "--prompt") prompt = v; + else if (a == "--n") n_gen = std::atoi(v.c_str()); + else if (a == "--ngl") ngl = std::atoi(v.c_str()); + else if (a == "--max-tokens") max_tokens = std::atoi(v.c_str()); + else if (a == "--mm-cpu") mm_cpu = std::atoi(v.c_str()); // the encoder on the CPU (as strata-vision's default) + else if (a == "--dump-full-logits") dump_full = v; + else if (a == "--force") force = v; + else { std::fprintf(stderr, "unknown option %s\n", a.c_str()); return 2; } + } + llama_backend_init(); + llama_model_params mp = llama_model_default_params(); + mp.n_gpu_layers = ngl; + llama_model* mdl = llama_model_load_from_file(model.c_str(), mp); + if (!mdl) { std::fprintf(stderr, "cannot load %s\n", model.c_str()); return 1; } + const llama_vocab* vocab = llama_model_get_vocab(mdl); + llama_context_params cp = llama_context_default_params(); + cp.n_ctx = 8192; + cp.n_batch = cp.n_ubatch = 2048; + cp.op_offload = ngl > 0; + llama_context* ctx = llama_init_from_model(mdl, cp); + if (!ctx) { std::fprintf(stderr, "cannot create the context\n"); return 1; } + mtmd_context_params mcp = mtmd_context_params_default(); + mcp.use_gpu = ngl > 0 && !mm_cpu; + mcp.print_timings = false; + mcp.warmup = false; + if (max_tokens > 0) mcp.image_max_tokens = max_tokens; + mtmd_context* mctx = mtmd_init_from_file(mmproj.c_str(), mdl, mcp); + if (!mctx) { std::fprintf(stderr, "cannot load %s\n", mmproj.c_str()); return 1; } + mtmd_helper_bitmap_wrapper bw = mtmd_helper_bitmap_init_from_file(mctx, image.c_str(), false, mtmd_helper_init_opt_default()); + if (!bw.bitmap) { std::fprintf(stderr, "cannot read %s\n", image.c_str()); return 1; } + mtmd_input_chunks* chunks = mtmd_input_chunks_init(); + mtmd_input_text txt{prompt.c_str(), prompt.size(), false, true}; + const mtmd_bitmap* bms[1] = {bw.bitmap}; + if (mtmd_tokenize(mctx, chunks, &txt, bms, 1) != 0) { std::fprintf(stderr, "tokenize failed\n"); return 1; } + const size_t nc = mtmd_input_chunks_size(chunks); + llama_pos n_past = 0; + for (size_t c = 0; c < nc; ++c) { + const mtmd_input_chunk* ch = mtmd_input_chunks_get(chunks, c); + if (mtmd_input_chunk_get_type(ch) == MTMD_INPUT_CHUNK_TYPE_TEXT) { + size_t n = 0; + const llama_token* t = mtmd_input_chunk_get_tokens_text(ch, &n); + std::printf("text:"); + for (size_t i = 0; i < n; ++i) std::printf(" %d", (int) t[i]); + std::printf("\n"); + } else { + std::printf("image: %d tokens, %d positions\n", (int) mtmd_input_chunk_get_n_tokens(ch), + (int) mtmd_input_chunk_get_n_pos(ch)); + } + llama_pos np = n_past; + if (mtmd_helper_eval_chunk_single(mctx, ctx, ch, n_past, 0, (int32_t) cp.n_batch, c + 1 == nc, &np) != 0) { + std::fprintf(stderr, "eval failed at chunk %zu\n", c); + return 1; + } + n_past = np; + } + const std::vector forced = parse_ids(force); + if (!forced.empty()) n_gen = (int) forced.size() + 1; + const int V = llama_vocab_n_tokens(vocab); + FILE* ff = dump_full.empty() ? nullptr : std::fopen(dump_full.c_str(), "wb"); + std::vector gen; + for (int i = 0; i < n_gen; ++i) { + const float* lg = llama_get_logits_ith(ctx, -1); + int a = 0; + for (int j = 1; j < V; ++j) if (lg[j] > lg[a]) a = j; + if (i == 0) { + int b = -1; + for (int j = 0; j < V; ++j) if (j != a && (b < 0 || lg[j] > lg[b])) b = j; + std::printf("first: top1 %d (%.4f) top2 %d (%.4f)\n", a, lg[a], b, lg[b]); + } + gen.push_back(a); + if (ff) std::fwrite(lg, 4, V, ff); + if (i + 1 == n_gen) break; + llama_token t = i < (int) forced.size() ? forced[i] : a; + llama_pos pp = n_past++; // the text after a picture continues at n_past (max(nx, ny) past its first position) + llama_batch one = llama_batch_get_one(&t, 1); + one.pos = &pp; + if (llama_decode(ctx, one) != 0) { std::fprintf(stderr, "decode failed\n"); return 1; } + } + std::printf("gen:"); + for (int t : gen) std::printf(" %d", t); + std::printf("\n"); + if (ff) std::fclose(ff); + mtmd_input_chunks_free(chunks); + mtmd_bitmap_free(bw.bitmap); + mtmd_free(mctx); + llama_free(ctx); + llama_model_free(mdl); + llama_backend_free(); + return 0; +} From 7419037255f9c1e8004c007536d0d2c86ca07620 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Wed, 14 Oct 2026 01:11:11 +0200 Subject: [PATCH 2/8] qwen35: --batch-mtp (each slot verifies an MTP proposal in the batch window) and a clear refusal when the slots' caches cannot fit A slot's window carries its next token and, for the greedy slots that fit beside one row per slot, the proposal of its MTP block; the proposals for the next window come right after the window from its own hidden states (the first from the state the prompt left). Grouped GDN rows (a slot's rows in sequence on its own state), verify windows and their commit run per slot; every slot's tokens equal its solo run. The engine also says what the sessions take and stops with the numbers when they cannot fit. --- src/qwen35/q36_engine.cu | 380 ++++++++++++++++++++++++++++++++++----- 1 file changed, 340 insertions(+), 40 deletions(-) diff --git a/src/qwen35/q36_engine.cu b/src/qwen35/q36_engine.cu index 05fbc9eb..ff532355 100644 --- a/src/qwen35/q36_engine.cu +++ b/src/qwen35/q36_engine.cu @@ -46,6 +46,7 @@ #include #include #include +#include #include #include #include @@ -601,12 +602,16 @@ __global__ void k_to_f16(const float* x, __half* y, int64_t n) { /// q/k heads (block < qk_heads) per token - fused_gdn_conv_l2's arithmetic, token after token. History [channel][3]. __global__ void __launch_bounds__(128) k_conv_seq(float* hist, const float* qkv, const float* w, float* h, int C, int qk_heads, float eps, int T, bool write, - float* const* hist_tab = nullptr, const int32_t* slot_rows = nullptr) { + float* const* hist_tab = nullptr, const int32_t* slot_rows = nullptr, + const int32_t* grow0 = nullptr, const int32_t* gcnt = nullptr) { __shared__ float part[4]; - if (hist_tab) { // batch rows (T = 1 each, grid y = row): row r's history is session slot_rows[r]'s - hist = hist_tab[slot_rows[blockIdx.y]]; - qkv += (size_t) blockIdx.y * C; - h += (size_t) blockIdx.y * C; + if (hist_tab) { // batch rows, grid y = group: group g's history is session slot_rows[g]'s; its rows are + // grow0[g] .. + gcnt[g] - 1 (one row at row g when there are no group arrays) + const int g = blockIdx.y, r0 = grow0 ? grow0[g] : g; + hist = hist_tab[slot_rows[g]]; + if (gcnt) T = gcnt[g]; + qkv += (size_t) r0 * C; + h += (size_t) r0 * C; } const int c = blockIdx.x * 128 + threadIdx.x; float v0 = hist[c * 3], v1 = hist[c * 3 + 1], v2 = hist[c * 3 + 2]; @@ -642,11 +647,13 @@ __global__ void __launch_bounds__(128) k_conv_seq(float* hist, const float* qkv, __global__ void __launch_bounds__(512) k_gdn_seq(float* state, const float* h, int C, const float* gate, const float* beta, const float* z, const float* gamma, float eps, float* y, int h_k, int h_v, int T, bool write, - float* const* state_tab = nullptr, const int32_t* slot_rows = nullptr) { + float* const* state_tab = nullptr, const int32_t* slot_rows = nullptr, + const int32_t* grow0 = nullptr, const int32_t* gcnt = nullptr) { constexpr int S = 128, RG = 4, RPG = 32; - if (state_tab) { // batch rows (T = 1 each, grid y = row): row r's state is session slot_rows[r]'s - const int r = blockIdx.y; - state = state_tab[slot_rows[r]]; + if (state_tab) { // batch rows, grid y = group (see k_conv_seq) + const int g = blockIdx.y, r = grow0 ? grow0[g] : g; + state = state_tab[slot_rows[g]]; + if (gcnt) T = gcnt[g]; h += (size_t) r * C; gate += (size_t) r * h_v; beta += (size_t) r * h_v; @@ -1129,9 +1136,12 @@ struct Engine { // device tables for batch rows: per state index (layer, then the MTP block) the session pointers float **d_conv_tab = nullptr, **d_S_tab = nullptr, **d_kc_tab = nullptr, **d_vc_tab = nullptr; int32_t *d_rcell = nullptr, *d_rslot = nullptr, *d_rdelta = nullptr; // [kVerify] the rows' cell / session / rotary offset + // the GDN layers run a slot's rows in sequence: per group (a slot) its session, its first row and its row count + int32_t *d_gslot = nullptr, *d_grow0 = nullptr, *d_gcnt = nullptr; + int rows_G = 0; // groups of the rows being run int32_t* hrow = nullptr; // pinned staging for the rows - cudaGraphExec_t gb[kVerify + 1] = {}; // a batch window of nb rows bool rows_mode = false; // layer(): the rows are sessions' (not consecutive cells) + bool bmtp = false; // --batch-mtp: batch windows verify MTP proposals int64_t rows_pmax = 0; // (eager) the highest cell of the rows // pictures (--vision): the request's rows replace the embeddings of its <|image_pad|> cells; M-RoPE bool vision = false; @@ -1365,6 +1375,25 @@ struct Engine { } sess.resize((size_t) n_sess); gsets.resize((size_t) n_sess); + { // the sessions' caches: said before they fail (a slot's K / V at the context, fp32, for the attention layers and + // the MTP block, and its recurrent state) + size_t n_attn = m->has_mtp ? 1 : 0, n_gdn = 0; + for (const Layer& L : m->layers) (L.attn ? n_attn : n_gdn) += 1; + const size_t per = (size_t) (g.n_head_kv * g.head_dim * 2 * 4) * (size_t) ctx * n_attn + + (size_t) g.ssm_v_heads * g.ssm_state_size * g.ssm_state_size * 4 * n_gdn; + size_t fr0 = 0, tot0 = 0; + CK(cudaMemGetInfo(&fr0, &tot0)); + if (n_sess > 1) + std::fprintf(stderr, "strata-q36: %d sessions (--batch): %.2f GiB of VRAM each at a context of %d (%.2f GiB in " + "all), %.2f GiB free before them\n", n_sess, (double) per / (1 << 30), ctx, + (double) per * n_sess / (1 << 30), (double) fr0 / (1 << 30)); + if (n_sess > 1 && per * (size_t) n_sess + ((size_t) 1 << 30) > fr0) { + std::fprintf(stderr, "strata-q36: not enough VRAM for %d slots at a context of %d (%.2f GiB each, %.2f GiB " + "free): use fewer slots (\"parallel\" / --batch) or a shorter --max-context\n", n_sess, ctx, + (double) per / (1 << 30), (double) fr0 / (1 << 30)); + std::exit(1); + } + } for (Sess& ss : sess) alloc_session(ss); if (n_sess > 1) { // the batch rows' tables: per state index the session pointers, on the device const size_t ns = sess[0].conv.size(); @@ -1386,7 +1415,10 @@ struct Engine { d_rcell = dalloc_t(kVerify); d_rslot = dalloc_t(kVerify); d_rdelta = dalloc_t(kVerify); - CK(cudaHostAlloc((void**) &hrow, 64 * sizeof(int32_t), cudaHostAllocDefault)); + d_gslot = dalloc_t(kVerify); + d_grow0 = dalloc_t(kVerify); + d_gcnt = dalloc_t(kVerify); + CK(cudaHostAlloc((void**) &hrow, 128 * sizeof(int32_t), cudaHostAllocDefault)); } if (vision) { d_mtab = dalloc_t((size_t) ctx * 3); @@ -1502,11 +1534,12 @@ struct Engine { f32mm(L.beta, h, be_b, N, HV, T); k_gdn_gb<<>>(al_b, L.dt, L.ssm_a, be_b, HV, T); } - if (rows_mode) { // batch rows: each row one token of its own session (grid y = row) - k_conv_seq<<>>(nullptr, qkv_b, L.conv, hc_b, C, 2 * HK, m->eps, 1, true, - d_conv_tab + li * n_sess, d_rslot); - k_gdn_seq<<>>(nullptr, hc_b, C, al_b, be_b, z, L.ssm_norm, m->eps, gdn_y, - HK, HV, 1, true, d_S_tab + li * n_sess, d_rslot); + if (rows_mode) { // batch rows: a slot's rows (one, or a verify window's two) in sequence on its own state + k_conv_seq<<>>(nullptr, qkv_b, L.conv, hc_b, C, 2 * HK, m->eps, 1, + !verify, d_conv_tab + li * n_sess, d_gslot, d_grow0, d_gcnt); + k_gdn_seq<<>>(nullptr, hc_b, C, al_b, be_b, z, L.ssm_norm, m->eps, + gdn_y, HK, HV, 1, !verify, d_S_tab + li * n_sess, + d_gslot, d_grow0, d_gcnt); } else { // one token, a window or a chunk: the same kernels (every token in one launch each), so a decode step and a // verify window compute bitwise the same rows and the MTP's greedy text is the plain greedy text. (Strata's @@ -1927,8 +1960,9 @@ struct Engine { for (auto& g : gset.gv) if (g) { CK(cudaGraphExecDestroy(g)); g = nullptr; } } - for (auto& g : gb) - if (g) { CK(cudaGraphExecDestroy(g)); g = nullptr; } + for (auto& kv : row_graphs) + if (kv.second) CK(cudaGraphExecDestroy(kv.second)); + row_graphs.clear(); } template void graph_run(cudaGraphExec_t& gx, F body) { @@ -2060,44 +2094,151 @@ struct Engine { // ---- batch rows: one decode window for the next token of several sessions struct Row { int slot; int32_t tok; }; long long win_count = 0; - /// One window over the rows (each the next token of its own session, at that session's position): the greedy picks - /// end up in rows_pick, every row's logits in `logits`. The sessions' positions advance. + std::map row_graphs; // by (rows, groups, kind): graphs of the batch windows + /// A slot's rows of one window: `n` consecutive cells from the session's position (1: the next token; 2: also an MTP + /// proposal the window verifies). + struct Group { int slot; int n; int32_t tok[2]; }; int32_t rows_pick[kVerify] = {}; - void step_rows(const Row* rows, int nb) { + int rows_G_last = 0; // groups of the window run last (commit_rows takes their keep counts) + + void run_graph_key(int key, const std::function& body) { + if (!use_graph) { body(); return; } + graph_run(row_graphs[key], body); + } + + /// One window over the groups' rows. `verify`: a verify window - the GDN state is read, not written (commit_rows writes + /// it for the kept rows) and the sessions' positions stay. The greedy picks end up in rows_pick (one per row), every + /// row's logits in `logits`. Without verify the sessions' positions advance by their rows. + void run_rows(const Group* gr, int G, bool verify) { sess[(size_t) cur].pos = pos; CK(cudaStreamSynchronize(st)); // the pinned staging is free again int64_t pmax = 0; - for (int r = 0; r < nb; ++r) { - const Sess& ss = sess[(size_t) rows[r].slot]; - hrow[r] = rows[r].tok; - hrow[8 + r] = (int32_t) ss.pos; - hrow[16 + r] = rows[r].slot; - hrow[24 + r] = ss.rdelta; - pmax = std::max(pmax, ss.pos); + int T = 0; + for (int g = 0; g < G; ++g) { + const Sess& ss = sess[(size_t) gr[g].slot]; + hrow[40 + g] = gr[g].slot; + hrow[48 + g] = T; + hrow[56 + g] = gr[g].n; + for (int j = 0; j < gr[g].n; ++j) { + hrow[T] = gr[g].tok[j]; + hrow[8 + T] = (int32_t) (ss.pos + j); + hrow[16 + T] = gr[g].slot; + hrow[24 + T] = ss.rdelta; + ++T; + } + pmax = std::max(pmax, ss.pos + gr[g].n - 1); } - CK(cudaMemcpyAsync(tok, hrow, (size_t) nb * 4, cudaMemcpyHostToDevice, st)); - CK(cudaMemcpyAsync(d_rcell, hrow + 8, (size_t) nb * 4, cudaMemcpyHostToDevice, st)); - CK(cudaMemcpyAsync(d_rslot, hrow + 16, (size_t) nb * 4, cudaMemcpyHostToDevice, st)); - CK(cudaMemcpyAsync(d_rdelta, hrow + 24, (size_t) nb * 4, cudaMemcpyHostToDevice, st)); + CK(cudaMemcpyAsync(tok, hrow, (size_t) T * 4, cudaMemcpyHostToDevice, st)); + CK(cudaMemcpyAsync(d_rcell, hrow + 8, (size_t) T * 4, cudaMemcpyHostToDevice, st)); + CK(cudaMemcpyAsync(d_rslot, hrow + 16, (size_t) T * 4, cudaMemcpyHostToDevice, st)); + CK(cudaMemcpyAsync(d_rdelta, hrow + 24, (size_t) T * 4, cudaMemcpyHostToDevice, st)); + CK(cudaMemcpyAsync(d_gslot, hrow + 40, (size_t) G * 4, cudaMemcpyHostToDevice, st)); + CK(cudaMemcpyAsync(d_grow0, hrow + 48, (size_t) G * 4, cudaMemcpyHostToDevice, st)); + CK(cudaMemcpyAsync(d_gcnt, hrow + 56, (size_t) G * 4, cudaMemcpyHostToDevice, st)); mtab_now = nullptr; map_on = false; rows_mode = true; + rows_G = G; rows_deferred = true; - graph_run(gb[nb], [&] { forward(nb, pmax, nb, use_graph, false); }); + run_graph_key((verify ? 1000 : 0) + G * 10 + (T - G), [&] { forward(T, pmax, T, use_graph, verify); }); rows_deferred = false; rows_mode = false; - CK(cudaMemcpyAsync(hrow + 32, pick, (size_t) nb * 4, cudaMemcpyDeviceToHost, st)); + CK(cudaMemcpyAsync(hrow + 32, pick, (size_t) T * 4, cudaMemcpyDeviceToHost, st)); CK(cudaStreamSynchronize(st)); - for (int r = 0; r < nb; ++r) { - rows_pick[r] = hrow[32 + r]; - ++sess[(size_t) rows[r].slot].pos; - } + for (int r = 0; r < T; ++r) rows_pick[r] = hrow[32 + r]; + if (!verify) + for (int g = 0; g < G; ++g) sess[(size_t) gr[g].slot].pos += gr[g].n; pos = sess[(size_t) cur].pos; + rows_G_last = G; if (m->hybrid) { - count_rows(nb); + count_rows(T); if (++win_count % kRebalanceEvery == 0) rebalance(8); } } + /// One window for the next token of each of the rows' sessions (no proposals): the greedy picks in rows_pick. + void step_rows(const Row* rows, int nb) { + Group gr[kVerify]; + for (int r = 0; r < nb; ++r) gr[r] = {rows[r].slot, 1, {rows[r].tok, 0}}; + run_rows(gr, nb, false); + } + /// After run_rows(.., verify = true): the GDN state of group g takes its first keep[g] rows (the conv history and the + /// recurrence run again over the rows' kept inputs, as commit() does) and the session advances by keep[g]. + void commit_rows(const Group* gr, const int* keep, int G) { + const auto& g = m->g; + const int HK = (int) g.ssm_k_heads, HV = (int) g.ssm_v_heads, C = (int) g.ssm_conv_channels; + sess[(size_t) cur].pos = pos; + for (int i = 0; i < G; ++i) hrow[56 + i] = keep[i]; // (hrow's slot / first-row words are the window's, unchanged) + CK(cudaMemcpyAsync(d_gcnt, hrow + 56, (size_t) G * 4, cudaMemcpyHostToDevice, st)); + rows_mode = true; + rows_G = G; + run_graph_key(2000 + G, [&] { + for (size_t l = 0; l < m->layers.size(); ++l) { + const Layer& L = m->layers[l]; + if (L.attn) continue; + k_conv_seq<<>>(nullptr, v_qkv[l], L.conv, hc, C, 2 * HK, m->eps, 1, true, + d_conv_tab + l * n_sess, d_gslot, d_grow0, d_gcnt); + k_gdn_seq<<>>(nullptr, v_hc[l], C, v_alpha[l], v_beta[l], z, L.ssm_norm, + m->eps, nullptr, HK, HV, 1, true, d_S_tab + l * n_sess, + d_gslot, d_grow0, d_gcnt); + } + }); + rows_mode = false; + CK(cudaStreamSynchronize(st)); + for (int i = 0; i < G; ++i) sess[(size_t) gr[i].slot].pos += keep[i]; + pos = sess[(size_t) cur].pos; + } + + /// The MTP block over rows of several sessions: row r reads token tok at cell `cell` of session `slot` and the seed + /// hidden at `seed` (device, n_embd floats); its draft - the block's greedy pick after that row - ends up in + /// mtp_pick[r], and the block's K / V cells are written. + struct MtpRow { int slot; int32_t tok; int64_t cell; const float* seed; }; + int32_t mtp_pick[kVerify] = {}; + float* logits_mr = nullptr; + int32_t* pick_mr = nullptr; + void mtp_rows(const MtpRow* rows, int T) { + const auto& g = m->g; + const int N = (int) g.n_embd; + if (!logits_mr) { + logits_mr = dalloc((size_t) kVerify * g.n_vocab); + pick_mr = dalloc_t(kVerify); + } + sess[(size_t) cur].pos = pos; + CK(cudaStreamSynchronize(st)); + int64_t pmax = 0; + for (int r = 0; r < T; ++r) { + hrow[r] = rows[r].tok; + hrow[8 + r] = (int32_t) rows[r].cell; + hrow[16 + r] = rows[r].slot; + hrow[24 + r] = sess[(size_t) rows[r].slot].rdelta; + pmax = std::max(pmax, rows[r].cell); + CK(cudaMemcpyAsync(mtp_seed() + (size_t) r * N, rows[r].seed, (size_t) N * 4, cudaMemcpyDeviceToDevice, st)); + } + CK(cudaMemcpyAsync(tok_m, hrow, (size_t) T * 4, cudaMemcpyHostToDevice, st)); + CK(cudaMemcpyAsync(d_rcell, hrow + 8, (size_t) T * 4, cudaMemcpyHostToDevice, st)); + CK(cudaMemcpyAsync(d_rslot, hrow + 16, (size_t) T * 4, cudaMemcpyHostToDevice, st)); + CK(cudaMemcpyAsync(d_rdelta, hrow + 24, (size_t) T * 4, cudaMemcpyHostToDevice, st)); + mtab_now = nullptr; + map_on = false; + rows_mode = true; + rows_G = T; + rows_deferred = true; + run_graph_key(3000 + T, [&] { + K::iq_embed_rows(m->embd_type, m->embd, m->embd_row, tok_m, T, N, y, st); + k_rms_ld<<>>(y, N, m->mtp_enorm, mtp_cat, 2 * N, N, m->eps); // [e | ...] + k_rms_ld<<>>(mtp_seed(), N, m->mtp_hnorm, mtp_cat + N, 2 * N, N, m->eps); // [... | h] + mm(m->eh_proj, mtp_cat, x, T); + k_rms<<>>(x, m->mtp.attn_norm, h, N, m->eps); + layer(m->mtp, m->layers.size(), T, pmax, pos0_m, use_graph, false, m->mtp_shnorm, hmtp); + mm(m->head, hmtp, logits_mr, T); + k_argmax<<>>(logits_mr, (int) g.n_vocab, pick_mr, amv, ami, false); + k_argmax<<>>(logits_mr, kArgBlocks, pick_mr, amv, ami, true); + }); + rows_deferred = false; + rows_mode = false; + CK(cudaMemcpyAsync(hrow + 32, pick_mr, (size_t) T * 4, cudaMemcpyDeviceToHost, st)); + CK(cudaStreamSynchronize(st)); + for (int r = 0; r < T; ++r) mtp_pick[r] = hrow[32 + r]; + } /// Row r's logits of the last step_rows, on the host. void host_logits_row(int r, std::vector& out) { out.resize((size_t) m->g.n_vocab); @@ -2604,6 +2745,9 @@ struct Slot { std::mt19937_64 rng; std::vector hist; Clock::time_point t0; + int32_t draft = 0; // --batch-mtp: the MTP block's proposal for the token after `x` + bool draft_ready = false; + long long offered = 0, accepted = 0; }; /// The engine protocol (serve/server.py). One request at a time on the control lines: GEN / GENI (alone: speculative @@ -2640,18 +2784,171 @@ struct Serve { } } + /// One decode window with MTP proposals (--batch-mtp): every active slot's next token, and for up to kVerify - S of the + /// slots (the greedy ones, in turn) also the proposal its MTP block made: the window verifies both at once. A slot whose + /// proposal the main model confirms moves two tokens in the window. The proposals for the next window come right after + /// it, from the hidden states the window just produced (the first one of a slot from the state its prompt left). + int mtp_turn = 0; + void window_mtp() { + poll_control(); + const int N = (int) E.m->g.n_embd; + std::vector act; + for (int b = 0; b < E.n_sess; ++b) + if (slots[(size_t) b].active) act.push_back(b); + const int S = (int) act.size(); + if (S == 0) return; + // who verifies a proposal this window: the greedy slots in turn, as many as fit beside one row per slot + const int room = Engine::kVerify - S; + std::vector cand((size_t) S, 0); + int nc = 0; + for (int k = 0; k < S && nc < room; ++k) { + const int i = (mtp_turn + k) % S; + if (!slots[(size_t) act[(size_t) i]].smp.needs_logits()) { cand[(size_t) i] = 1; ++nc; } + } + ++mtp_turn; + // a candidate without a proposal gets its first one from the state its last row left + std::vector first; + std::vector first_of; + for (int i = 0; i < S; ++i) { + Slot& sl = slots[(size_t) act[(size_t) i]]; + if (cand[(size_t) i] && !sl.draft_ready) { + Engine::Sess& ss = E.sess[(size_t) act[(size_t) i]]; + first.push_back({act[(size_t) i], sl.x, ss.pos, ss.hlast}); + first_of.push_back(i); + } + } + if (!first.empty()) { + E.mtp_rows(first.data(), (int) first.size()); + for (size_t k = 0; k < first.size(); ++k) { + Slot& sl = slots[(size_t) act[(size_t) first_of[k]]]; + sl.draft = E.mtp_pick[k]; + sl.draft_ready = true; + } + } + std::vector gr((size_t) S); + std::vector row0((size_t) S); + int T = 0; + for (int i = 0; i < S; ++i) { + const Slot& sl = slots[(size_t) act[(size_t) i]]; + gr[(size_t) i] = {act[(size_t) i], cand[(size_t) i] ? 2 : 1, {sl.x, sl.draft}}; + row0[(size_t) i] = T; + T += gr[(size_t) i].n; + } + E.run_rows(gr.data(), S, true); + // the picks: emit, decide how many rows each slot keeps + std::vector keep((size_t) S, 1); + std::vector last((size_t) S, 0); + std::vector alive((size_t) S, 0); + for (int i = 0; i < S; ++i) { + const int b = act[(size_t) i]; + Slot& sl = slots[(size_t) b]; + Engine::Sess& ss = E.sess[(size_t) b]; + const int n = gr[(size_t) i].n, r0 = row0[(size_t) i]; + int y0 = E.rows_pick[r0]; + if (sl.smp.needs_logits()) { + E.host_logits_row(r0, lg); + y0 = sample(lg, sl.smp, sl.hist, sl.rng); + } + bool two = n == 2 && y0 == sl.draft && !is_eos(y0) && !sl.stop && sl.produced + 2 <= sl.max_new && + ss.pos + 3 <= E.ctx; // (ss.pos: the position of the slot's next token: the window did not move it) + if (n == 2) { ++sl.offered; if (two) ++sl.accepted; } + const int rows_kept = two ? 2 : 1; + keep[(size_t) i] = rows_kept; + const int32_t fed[2] = {sl.x, sl.draft}; + bool done = false; + int y = y0; + for (int j = 0; j < rows_kept; ++j) { + if (j == 1) y = E.rows_pick[r0 + 1]; + ss.live.push_back(fed[j]); + std::printf("BT %d %d\n", b, y); + ++sl.produced; + sl.hist.push_back(y); + const char* fin = is_eos(y) ? "stop" : sl.stop ? "cancel" : sl.produced >= sl.max_new ? "length" + : ss.pos + j + 2 > E.ctx ? "length" : nullptr; + if (fin) { + std::printf("BDONE %d %lld %s %.1f\n", b, (long long) sl.produced, fin, ms_since(sl.t0)); + if (sl.offered > 0) + std::fprintf(stderr, "strata batch: slot %d: %lld of %lld MTP proposals accepted\n", b, sl.accepted, + sl.offered); + sl.active = false; + ss.active = false; + --n_active; + done = true; + break; + } + } + last[(size_t) i] = y; + alive[(size_t) i] = !done; + if (!done) sl.x = y; + } + E.commit_rows(gr.data(), keep.data(), S); + // the hidden state after each slot's last kept row (the seed of a later first proposal), and the next proposals + std::vector nx; + std::vector nx_of, nx_last; + for (int i = 0; i < S; ++i) { + const int b = act[(size_t) i]; + Engine::Sess& ss = E.sess[(size_t) b]; + const int r0 = row0[(size_t) i]; + CK(cudaMemcpyAsync(ss.hlast, E.hmain + (size_t) (r0 + keep[(size_t) i] - 1) * N, (size_t) N * 4, + cudaMemcpyDeviceToDevice, E.st)); + Slot& sl = slots[(size_t) b]; + sl.draft_ready = false; + if (!alive[(size_t) i] || !cand[(size_t) i]) continue; + const int64_t p_new = ss.pos; // commit_rows moved it: the cell of the token the next window feeds + if (keep[(size_t) i] == 2) { + nx.push_back({b, sl.draft, p_new - 1, E.hmain + (size_t) r0 * N}); + nx.push_back({b, last[(size_t) i], p_new, E.hmain + (size_t) (r0 + 1) * N}); + nx_last.push_back((int) nx.size() - 1); + } else { + nx.push_back({b, last[(size_t) i], p_new, E.hmain + (size_t) r0 * N}); + nx_last.push_back((int) nx.size() - 1); + } + nx_of.push_back(i); + } + std::fflush(stdout); + if (!nx.empty()) { + // (more rows than the window holds: the proposals come in two calls) + for (size_t at = 0, k = 0; at < nx.size();) { + size_t take = std::min(nx.size() - at, Engine::kVerify); + while (take > 0 && at + take < nx.size() && nx[at + take].slot == nx[at + take - 1].slot) --take; // a slot's rows together + E.mtp_rows(nx.data() + at, (int) take); + for (; k < nx_last.size() && (size_t) nx_last[k] < at + take; ++k) { + Slot& sl = slots[(size_t) act[(size_t) nx_of[k]]]; + sl.draft = E.mtp_pick[(size_t) nx_last[k] - at]; + sl.draft_ready = true; + } + at += take; + } + } + } + /// One decode window over every active slot: one token each. void window() { poll_control(); + if (E.bmtp && E.mtp_d > 0) { // proposals need a row to spare and a slot that decodes greedily + int act = 0, greedy = 0; + for (const Slot& sl : slots) + if (sl.active) { ++act; greedy += !sl.smp.needs_logits(); } + if (greedy > 0 && Engine::kVerify - act > 0) { window_mtp(); return; } + } + window_plain(); + } + + /// One token of every active slot, no proposals. + void window_plain() { std::vector rows; for (int b = 0; b < E.n_sess; ++b) if (slots[(size_t) b].active) rows.push_back({b, slots[(size_t) b].x}); if (rows.empty()) return; E.step_rows(rows.data(), (int) rows.size()); + const size_t Nb = (size_t) E.m->g.n_embd * 4; for (size_t r = 0; r < rows.size(); ++r) { const int b = rows[r].slot; Slot& sl = slots[(size_t) b]; Engine::Sess& ss = E.sess[(size_t) b]; + if (E.bmtp) // (the hidden state a later first proposal starts from) + CK(cudaMemcpyAsync(ss.hlast, E.hmain + r * (size_t) E.m->g.n_embd, Nb, cudaMemcpyDeviceToDevice, E.st)); + sl.draft_ready = false; ss.live.push_back(sl.x); int y; if (sl.smp.needs_logits()) { @@ -2999,7 +3296,7 @@ int strata::qwen35::run(int argc, char** argv) { double expert_vram = -1.0; bool warm = true; int expert_slots = 0, batch = 0; - bool serve_mode = false, graph = true, vision = false; + bool serve_mode = false, graph = true, vision = false, batch_mtp = false; for (int i = 1; i < argc; ++i) { const std::string a = argv[i]; auto next = [&]() -> std::string { @@ -3034,6 +3331,7 @@ int strata::qwen35::run(int argc, char** argv) { } else if (a == "--vision") vision = true; // pictures (GENI): the encoder is strata-vision's else if (a == "--batch" || a == "--slots") batch = std::atoi(next().c_str()); // sessions decoding together + else if (a == "--batch-mtp") batch_mtp = true; // ... each verifying an MTP proposal else if (a == "--expert-vram") expert_vram = std::atof(next().c_str()); // GiB for the routed experts else if (a == "--cpu-threads") cpu_threads = std::atoi(next().c_str()); else if (a == "--expert-slots") expert_slots = std::atoi(next().c_str()); @@ -3110,6 +3408,8 @@ int strata::qwen35::run(int argc, char** argv) { } report{E}; E.reset(); E.mtp_d = m.has_mtp ? mtp_d : 0; + E.bmtp = (batch_mtp || (std::getenv("STRATA_BATCH_MTP") != nullptr && std::string(std::getenv("STRATA_BATCH_MTP")) != "0")) && E.n_sess > 1 && E.mtp_d > 0; + if (batch_mtp && !E.bmtp) std::fprintf(stderr, "strata-q36: --batch-mtp needs --batch N (2 or more) and --mtp N: ignored\n"); if (warm) E.warmup(); if (serve_mode) return serve(E); if (bench_pp > 0 || bench_tg > 0) { From a9adfa5dad37dafb5b0c4a49421ef66c759aba3d Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Wed, 14 Oct 2026 01:11:11 +0200 Subject: [PATCH 3/8] Qwen3.6-35B-A3B: setup asks for pictures and recommends parallel requests; docs Setup: the images question for qwen36 (GPU encoder on an NVIDIA card of 16 GB or more, the CPU encoder otherwise, AMD under Linux on the CPU; --vision gpu kept as asked with a note), the pinned mmproj (size and SHA-256) beside the GGUF, the vision section and --vision in the config; --parallel N is written as asked with what a slot costs, and the recommendation is said where every expert still fits. docs/QWEN36.md: pictures and several requests at once with the measurements. --- docs/BATCHING.md | 3 + docs/DETAILS.md | 2 + docs/QWEN36.md | 107 ++++++++++++++++++++++++++++ serve/test_q36_config.py | 48 +++++++++++++ setup.py | 140 +++++++++++++++++++++++++++++++++++-- tools/test_setup_qwen36.py | 82 ++++++++++++++++++++-- 6 files changed, 368 insertions(+), 14 deletions(-) create mode 100644 docs/QWEN36.md create mode 100644 serve/test_q36_config.py diff --git a/docs/BATCHING.md b/docs/BATCHING.md index 69e5e2f7..8ce4b45a 100644 --- a/docs/BATCHING.md +++ b/docs/BATCHING.md @@ -9,6 +9,9 @@ conversations at the same time instead of waiting for each other. It is opt-in and changes nothing when the options are absent (#465; the engine part is PR #559). +**Qwen3.6-35B-A3B** has the same option on its own engine path (`"parallel": N`, `--batch N`, `--batch-mtp`, up to 8 slots, the same +engine protocol and the same server): its numbers, what a slot costs and where setup recommends it are in [QWEN36.md](QWEN36.md). + ## Turning it on One GPU: add `"parallel": 2` to the model's config (`strata-.json`) and restart, or run setup with diff --git a/docs/DETAILS.md b/docs/DETAILS.md index ad64e20e..12a35f21 100644 --- a/docs/DETAILS.md +++ b/docs/DETAILS.md @@ -1463,6 +1463,8 @@ The config snippets for every client, the tool arguments and the safety rules ar ## Images (vision) +(Qwen3.6-35B-A3B reads pictures the same way, with its own `mmproj-F16.gguf`: [QWEN36.md](QWEN36.md).) + The model has a vision encoder: [`mmproj-Qwen3.8-Flash-Next-BF16.gguf`](https://huggingface.co/ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-GGUF) (0.9 GB, a 27-layer ViT plus the projector into the language model). It is **optional**: say yes when the setup asks "Images?", or run it again with `--vision gpu` (or `--vision cpu`). The setup downloads the encoder, builds a small diff --git a/docs/QWEN36.md b/docs/QWEN36.md new file mode 100644 index 00000000..76efb57d --- /dev/null +++ b/docs/QWEN36.md @@ -0,0 +1,107 @@ +# Qwen3.6-35B-A3B: pictures and several requests at once + +Strata runs [Qwen3.6-35B-A3B](https://huggingface.co/Qwen/Qwen3.6-35B-A3B) (35B mixture of experts, 3B active, 256 experts, top-8) from +[Unsloth's GGUFs with the MTP layer](https://huggingface.co/unsloth/Qwen3.6-35B-A3B-MTP-GGUF) (UD-Q4_K_XL, UD-Q6_K_XL, Q8_0) on its own +engine path (`src/qwen35`; `strata` switches to it from the file's architecture). Pick it in setup (`--family qwen36`). Besides text it +reads **pictures** and serves **several requests at once**, the same two options the Flash-Next models have. + +Measured on an AMD Radeon AI PRO R9700 32 GB (HIP, Linux, UD-Q4_K_XL, every expert in VRAM) and on an RTX 3060 12 GB (CUDA, 20 threads, +UD-Q4_K_XL in the hybrid mode: 22-37 of 256 experts per layer in VRAM, the rest on the CPU), llama.cpp 972b5fc on the same files. + +## Pictures + +The vision encoder is Unsloth's `mmproj-F16.gguf` (0.9 GB, pinned revision, SHA-256 checked by setup): a 27-layer ViT with a 2x2 merger, +the same projector family as the Flash-Next models' (`qwen3vl_merger`; only its output width differs: 2048 here, 2560 there). Strata runs +it with the same helper (`strata-vision`, llama.cpp's `mtmd`), so the encoder choices are the Flash-Next ones +([Images](DETAILS.md#images-vision)): **setup asks "Do you want images?"**, the default answer is yes on an NVIDIA card of 16 GB or more +(GPU encoder, ~1.2 GB of VRAM at up to 1,024 image tokens) and on AMD under Linux (CPU encoder, no VRAM); `--vision yes|no|gpu|cpu` +and `--vision-tokens N` work as there. A card under 16 GB is recommended the CPU encoder (the GPU one takes room from the experts); +`--vision gpu` is kept as asked, with a note. + +| Encoder | Time per picture (640x400 = 260 tokens / 800x450 = 350 tokens) | VRAM | +| --- | --- | --- | +| GPU, RTX 3060 | 0.10 s / 0.15 s | 1.18 GiB at up to 1,024 tokens (1.34 GiB at 2,048) | +| CPU, 32 threads (R9700 box) | 0.9 s / 1.1 s | none | +| CPU, 10 threads (3060 box) | 1.6 s / 2.1 s | none | + +A picture becomes up to 1,024 tokens of the context (the CPU default is 300). The engine puts the encoder's rows where the prompt has +`<|image_pad|>` tokens and gives every row its 2-D position, interleaved M-RoPE exactly as llama.cpp does for this model (rotary sections +11 / 11 / 10, a picture's rows at (t, h, w) = (p, p + row, p + column), the text after it continuing at p + max(columns, rows)). + +**Checked against llama.cpp** (its `mtmd` and its own graph, the encoder on the CPU on both sides, the same prompt ids, the answer +llama.cpp gives fed to both so the logits are compared step by step, 24 steps; the "floor" is llama.cpp's CPU backend against its own +HIP run, the noise two correct engines have on this model): + +| Picture and question | Prompt tokens | First token | Mean KL, llama.cpp HIP vs Strata | Floor (llama.cpp CPU vs HIP) | +| --- | ---: | --- | ---: | ---: | +| 640x400, text in the image | 288 | same | 0.029 | 0.056 | +| 640x400, list the shapes | 294 | same | 0.035 | 0.039 | +| 800x450, text in the image | 378 | same | 0.021 | 0.031 | +| 800x450, describe the shapes | 381 | same | 0.0005 | 0.0019 | + +The answers are the same text as llama.cpp's: `STRATA 42` (with llama.cpp's own spelling ` STRATA42`), `CODE 4217`, `Red circle / Blue square +/ Green triangle`, `A red square is positioned on the left ... A blue circle is positioned on the right ...`. With the picture options on, +a request without pictures gives the same tokens as without them (10 prompts x 128 greedy tokens, identical). + +Pictures work with several requests at once, with the MTP drafts and with the conversation cache: the same conversation sent again (a chat +app resends its pictures) continues from the held state when its pictures are the same (they are matched by the server's key for each +picture); a different picture starts that conversation again. + +## Several requests at once + +`"parallel": N` in the model's config (`strata-qwen36-.json`, or `--parallel N` at setup) makes the engine keep N conversations open +(`--batch N`, up to 8) and decode them together: every window carries one token of each conversation, so the dense weights, the head and +every routed expert two conversations share are read once for all of them. The server needs no change: it speaks the same engine protocol +as for Flash-Next ([BATCHING.md](BATCHING.md)). A request that arrives while another is read waits only for that read: the prompt of a +new request is read **between** the decode windows of the others (one window per prompt chunk), and a conversation continues in the slot +that holds its start (or the engine copies the longer held start from another slot). + +Aggregate decode speed, N requests at once, same prompts, greedy, 128 new tokens each, wall time from the first request to the last +answer, **R9700 32 GB, UD-Q4_K_XL, llama.cpp `llama-server -np N`** (5 interleaved pairs, median; Strata `--batch 8 --mtp 0`): + +| Requests at once | Strata | llama.cpp | Ratio | Pairs faster | +| ---: | ---: | ---: | ---: | ---: | +| 1 | 83.9 tok/s | 73.8 | 1.14 | 5/5 | +| 2 | 173.5 | 107.4 | 1.61 | 5/5 | +| 4 | 252.0 | 165.0 | 1.53 | 5/5 | +| 8 | 325.4 | 208.1 | 1.56 | 5/5 | + +Every slot's tokens equal the tokens of the same request alone (the base engine's), at 2, 4 and 8 slots, with a 2.5K-token prompt read beside +decoding slots, with slots reused for later requests, with pictures and with sampling (same seed). Through the server: four concurrent chat +requests give the texts of the same four one after the other. + +**MTP drafts.** A request that has the engine to itself keeps its MTP drafts (the server sends it alone while nothing else runs). With +several requests the batch window has no drafts unless `--batch-mtp` is in the config's `args` (opt-in): every slot's window then also +carries the proposal its MTP block made (one per slot, up to the rows to spare in the 8-row window) and a confirmed proposal moves two +tokens in the window. Same prompts, 5 interleaved pairs, R9700: + +| Requests at once | `--mtp 0` | `--mtp 2 --batch-mtp` | Ratio | Pairs faster | +| ---: | ---: | ---: | ---: | ---: | +| 1 | 83.7 tok/s | 134.0 | 1.60 | 5/5 | +| 2 | 173.1 | 207.0 | 1.20 | 5/5 | +| 4 | 251.0 | 275.0 | 1.10 | 5/5 | +| 8 | 324.0 | 320.5 | 0.99 | 0/5 (no row to spare: no proposals) | + +The text is the same with and without it (every slot equal to its solo tokens). + +**What a slot costs.** Each slot keeps its own cache in VRAM: 1.5 GB at a context of 32K (fp32 keys and values of the 10 attention layers +and the MTP block, 45 KB per token) and 0.07 GB of recurrent state. Setup writes the context for one conversation, so N slots take N times +that from the room the experts would have: on a card that does not hold every expert (12 and 16 GB, the hybrid mode) that is room the +expert slots lose, and a batch reads more distinct experts from RAM. Setup therefore **recommends `--parallel` only where every expert still +fits** (about 3 on a 32 GB card at 32K) and says why it leaves it at one otherwise; any number you give is kept. On the RTX 3060 12 GB with +`--batch 4` the engine kept 22 of 256 experts per layer (the sessions, the picture encoder and the MTP block took the rest) and four +requests at once ran 45 tok/s together against 42 one after the other: not worth it there. The engine says what the sessions take before it +allocates them and refuses (with the numbers) a count that cannot fit. + +In the hybrid mode the text of a request can differ a little between running alone and running beside others: the experts that sit on the +GPU or on the CPU change with the routing of all the requests, and the two compute with different rounding. With the slot tables fixed (`STRATA_Q36_FIXED_SLOTS=1`, a test setting) every slot equals its +solo run there too, with and without `--batch-mtp`. + +## Not done / limits + +- Eight slots at most (the window holds 8 rows); `--batch-mtp` shares those rows between slots and proposals. +- A sampling request in a batch decodes one token per window without proposals. `logit_bias` is not available on this engine path: the + server refuses a request that has it (as it does with `--batch` for Flash-Next). +- A slot that stopped being alone goes back to the solo path only through the server's own hand-over; the MTP block's cache has holes for + the tokens a slot decoded in batch windows (the drafts of a later solo stretch are a little worse; the text is not affected). +- Intel Arc (SYCL) does not run this family. diff --git a/serve/test_q36_config.py b/serve/test_q36_config.py new file mode 100644 index 00000000..981ae5f3 --- /dev/null +++ b/serve/test_q36_config.py @@ -0,0 +1,48 @@ +"""serve/test_q36_config.py - what the server hands the Qwen3.6-35B-A3B engine (arch qwen35moe): the config's pictures +("vision" section -> --vision) and parallel requests ("parallel": N -> --batch N), as for Flash-Next's engine. + + python -m unittest serve.test_q36_config +""" +from __future__ import annotations + +import unittest +from unittest import mock + +from serve.server import engine_args, parallel_args + + +def cfg(**kw): + base = {"arch": "qwen35moe", "exe": "strata", "args": ["--native", "/m/Qwen3.6-35B-A3B-UD-Q4_K_XL.gguf", + "--max-context", "32768", "--prefill", "auto", "--mtp", "2"]} + base.update(kw) + return base + + +class Q36Config(unittest.TestCase): + def test_parallel_becomes_batch(self): + a = engine_args(cfg(parallel=4)) + self.assertEqual(a[a.index("--batch") + 1], "4") + self.assertNotIn("--batch", engine_args(cfg())) + self.assertNotIn("--batch", engine_args(cfg(parallel=1))) + + def test_more_than_the_window_is_said(self): + with mock.patch("builtins.print") as pr: + a = engine_args(cfg(parallel=12)) + self.assertEqual(a[a.index("--batch") + 1], "12") # the engine caps it at 8 and says so + self.assertTrue(any("at most 8" in str(c) for c in pr.call_args_list)) + + def test_a_vision_section_starts_the_engine_with_pictures(self): + v = {"exe": "strata-vision", "mmproj": "/m/mmproj-F16.gguf", "model": "/m/Qwen3.6-35B-A3B-UD-Q4_K_XL.gguf", + "gpu": False, "max_tokens": 300} + self.assertIn("--vision", engine_args(cfg(vision=v))) + self.assertIn("--vision", engine_args(cfg(vision=v, args=cfg()["args"] + ["--vision"]))) + self.assertEqual(engine_args(cfg(vision=v, args=cfg()["args"] + ["--vision"])).count("--vision"), 1) + self.assertNotIn("--vision", engine_args(cfg())) + + def test_an_explicit_batch_in_the_args_wins(self): + c = cfg(parallel=4, args=cfg()["args"] + ["--batch", "2"]) + self.assertEqual(parallel_args(c, c["args"]), []) + + +if __name__ == "__main__": + unittest.main() diff --git a/setup.py b/setup.py index aac1bc1b..9d205980 100644 --- a/setup.py +++ b/setup.py @@ -453,7 +453,10 @@ OWN_PATH_FAMILIES = { # V in fp32 (strata-q36) "kv_bytes_per_token": 11 * 2 * 256 * 2 * 4, "mtp": 2, # drafts per step (greedy requests): measured best on the R9700 - "vision": False}, # the image encoder for this family is not wired up yet + # pictures: Unsloth's mmproj (the same projector family as Flash-Next's: qwen3vl_merger) through + # strata-vision; a parallel slot's session: its KV cache (kv_bytes_per_token) and the recurrent state of + # the 30 GDN layers (state_gb) + "vision": True, "state_gb": 0.07} } PREVIEW_FAMILIES = OWN_PATH_FAMILIES # the earlier name (tools and tests that import it) # EXPERIMENTAL, off by default (setup asks): a control vector shipped with the repository, see its README @@ -4555,8 +4558,9 @@ def choices_from_config(cfg_path: Path) -> dict: size = next((m for m in d["models"] if m.lower() == tag[len(d["tag"]):].lower()), None) a = cfg.get("args", []) ctx = a[a.index("--max-context") + 1] if "--max-context" in a and a.index("--max-context") + 1 < len(a) else None + vis = cfg.get("vision") return {"family": own, "model": size, "context": int(ctx) if ctx and ctx.isdigit() else None, "kv": None, - "vision": "none", "esp": "off", "host": cfg.get("host"), "api_key": cfg.get("api_key"), + "vision": ("gpu" if vis.get("gpu") else "cpu") if isinstance(vis, dict) else "none", "esp": "off", "host": cfg.get("host"), "api_key": cfg.get("api_key"), "port": cfg.get("port"), "gpu": cfg.get("gpu"), "layer_split": None, "cuda": 12 if config_toolkit(cfg) == 12 else None, "vram_reserve_mib": None} family = next((f for f, d in FAMILIES.items() if d["tag"] and tag.startswith(d["tag"])), "qwen") @@ -5507,6 +5511,89 @@ def own_path_size(fam: dict, ram: float) -> str: return max(fits, key=lambda m: fam["sha256"][fam["file"].format(q=m)][0]) if fits else next(iter(fam["models"])) +def own_path_vision(a, fam: dict, gpu: dict, hip: bool) -> str: + """The image encoder for an own-path family (Qwen3.6-35B-A3B): "gpu", "cpu" or "none". The Flash-Next families' rules: + --vision yes|no|gpu|cpu, else a question whose default answer is yes where the GPU encoder costs little - an NVIDIA + card of 16 GB or more (its ~1.4 GB is under a tenth of it) - and, on AMD under Linux, yes with the CPU encoder (it takes + no VRAM; there is no GPU encoder for AMD yet). A smaller NVIDIA card is recommended the CPU encoder (the GPU one takes + room from the experts); what is asked for with --vision gpu is kept, with a note (recommend, never force).""" + asked = a.vision + vram = float(gpu.get("vram_gb", 0.0)) + big = vram >= UNSLOTH_IMAGES_MIN_VRAM_GB + if asked in ("no", "none"): + return "none" + if asked is None: + say() + say(f" Images: {fam['title']} can also read pictures (screenshots, photos, scanned pages). This adds a " + f"{fam['sha256'][fam['mmproj']][0] / 1e9:.1f} GB download" + ( + "; the encoder runs on the CPU (no VRAM), a few seconds per picture." if hip else + " and the image encoder runs on the GPU (~1.4 GB of VRAM kept free, 0.1-0.5 s per picture)." if big else + "; the encoder runs on the CPU (a few seconds per picture), because the GPU encoder would take ~1.4 GB " + "of VRAM from the experts on this card.")) + default = "n" if (hip and WIN) else "y" if (big or hip) else "n" + if ask("Do you want images?", ["y", "n"], default, a.yes) != "y": + return "none" + asked = "cpu" if (hip or not big) else "gpu" + if hip: + if asked == "gpu": + say(" The AMD backend has no GPU image encoder yet: the encoder runs on the CPU.") + if WIN: + warn("images on the CPU with an AMD card are Linux-only for now (the ready-made Windows AMD engine has no " + "image encoder): images off") + return "none" + return "cpu" + if asked == "yes": + asked = "gpu" if big else "cpu" + if asked == "gpu" and not big and vram > 0: + warn(f"the GPU image encoder takes ~1.4 GB of VRAM, which on a {vram:.0f} GB card is room the experts would use: " + "--vision cpu reads pictures on the CPU instead (a few seconds each); kept as you chose") + return asked + + +def own_path_parallel_slot_gb(fam: dict, ctx: int) -> float: + """The VRAM one batch slot's session takes: its KV cache (fp32 K and V of the attention layers and the MTP block) and + the recurrent state of the GDN layers.""" + return ctx * fam["kv_bytes_per_token"] / 1e9 + fam["state_gb"] + + +def own_path_parallel_recommend(fam: dict, model: str, vram_gb: float, ctx: int) -> int: + """How many requests at once to recommend: 0 = one at a time. Only where every routed expert still fits in VRAM with + the slots' sessions (a batch then reads each expert once for all its rows); where some experts run on the CPU the + batch reads more distinct experts from RAM and every slot's VRAM is room the expert slots lose.""" + size = fam["sha256"][fam["file"].format(q=model)][0] / 1e9 + base = size * 0.93 + 4.5 # the routed experts + the dense weights and buffers (the file's 7% beyond them) + slot = own_path_parallel_slot_gb(fam, ctx) + best = 0 + for n in (2, 3, 4): + if base + (n + 1) * slot <= vram_gb: + best = n + return best + + +def own_path_parallel_note(a_parallel, fam: dict, model: str, vram_gb: float, ctx: int) -> list: + """What setup says about "parallel" for an own-path family: the recommendation, or how the asked count compares with + it (kept as asked: recommend, never force).""" + rec = own_path_parallel_recommend(fam, model, vram_gb, ctx) + slot = own_path_parallel_slot_gb(fam, ctx) + if a_parallel is None or a_parallel <= 1: + if not rec: + return ["Several requests at once: left at one at a time - this card does not hold every expert beside more " + "sessions, and the experts that run on the CPU make a batch read more of them (docs/BATCHING.md)."] + return [f"Several requests at once (opt-in): --parallel {rec} decodes up to {rec} together instead of one after " + f"the other (each takes ~{slot:.1f} GB of VRAM at this context; docs/BATCHING.md)."] + lines = [f"parallel requests: {a_parallel} at once (each takes ~{slot:.1f} GB of VRAM at this context, " + f"{a_parallel * slot:.1f} GB in all)"] + if a_parallel > PARALLEL_MAX: + lines.append(f"the engine runs at most {PARALLEL_MAX} at once; it will use {PARALLEL_MAX}") + if not rec: + lines.append("recommended for this card: one at a time - not every expert fits in VRAM beside more sessions; " + "kept as you chose") + elif a_parallel > rec: + lines.append(f"recommended for this card: {rec} - more slots leave fewer experts in VRAM, which can make every " + "request slower; kept as you chose") + return lines + + def install_own_path(a, family, gpu, hip, amd, cuda_tk, multi, port, ram, adopted): """Steps 2-7 for a family with its own engine path (OWN_PATH_FAMILIES: Qwen3.6-35B-A3B): the size, the context, the engine, the GGUF (pinned revision, size and SHA-256), the tokenizer from the GGUF, the config and the start @@ -5558,8 +5645,8 @@ def install_own_path(a, family, gpu, hip, amd, cuda_tk, multi, port, ram, adopte warn(f"{ctx // 1024}K is past {fam['title']}'s trained 262,144 positions and this engine path has no rope " "scaling yet: kept as you chose, but answers past 256K are untested") ok(f"context: {ctx} tokens") - if a.vision not in (None, "no", "none"): - warn(f"images are not available with {fam['title']} yet: off") + vision = own_path_vision(a, fam, gpu, hip) + ok("images: " + {"none": "off", "gpu": "on", "cpu": "on (encoder on the CPU)"}[vision]) if a.rope_scaling or a.rope_scale or a.kv or a.resident_budget_gib is not None or a.low_ram not in (None, "auto"): warn(f"--rope-scaling / --kv / --resident-budget-gib / --low-ram are Flash-Next settings: {fam['title']} " "does not use them") @@ -5576,7 +5663,10 @@ def install_own_path(a, family, gpu, hip, amd, cuda_tk, multi, port, ram, adopte "numpy, jinja2, regex, pyyaml, tqdm, requests, cmake, ninja, pillow, psutil") step(4, "the Strata engine") - llama, eng, meta, lib_dirs, gpu, _ = engine_step(a, gpu, hip, amd, cuda_tk, "none") + llama, eng, meta, lib_dirs, gpu, vision = engine_step(a, gpu, hip, amd, cuda_tk, vision) + if vision != "none" and not (eng / VEXE).exists(): + warn("this engine has no image encoder: images off (run setup again with --build to compile it)") + vision = "none" if fam["arch"] not in engine_families(eng): fail(f"this engine ({meta.get('version')}) does not run {fam['title']} yet", "update Strata, or compile the engine with --build, and run setup again") @@ -5591,6 +5681,16 @@ def install_own_path(a, family, gpu, hip, amd, cuda_tk, multi, port, ram, adopte download(fam["hf"] + gguf.name, gguf) verify_sha256(gguf, *fam["sha256"][gguf.name]) ok(f"model file: {gguf}") + mmproj = folder / fam["mmproj"] + if vision != "none": # the image encoder: Unsloth's mmproj, pinned, size + SHA-256 checked + if mmproj.exists() and done(mmproj): + ok(f"{mmproj.name} already downloaded") + else: + if a.gguf_dir: + fail(f"{mmproj} is missing", f"put {mmproj.name} in {folder}, or drop --gguf-dir to download it") + download(fam["mmproj_hf"] + mmproj.name, mmproj, "vision encoder") + verify_sha256(mmproj, *fam["sha256"][mmproj.name]) + ok(f"vision encoder: {mmproj}") step(6, "preparing the model for Strata") data, _ = data_folder(a.data_dir) @@ -5625,6 +5725,27 @@ def install_own_path(a, family, gpu, hip, amd, cuda_tk, multi, port, ram, adopte cfg["open_browser"] = a.browser cfg["args"] = recommend_pool_workers(cfg["args"]) # --pool-workers: this engine path's CPU expert threads too cfg_path = ROOT / f"strata-{tag.lower()}.json" + if vision != "none": + old_cfg = cfg_path if cfg_path.is_file() else adopted + vt = vision_tokens(getattr(a, "vision_tokens", None), vision, old_cfg) + cfg["args"].append("--vision") + cfg["vision"] = {"exe": str(eng / VEXE), "mmproj": str(mmproj), "model": str(gguf), "gpu": vision == "gpu", + "max_tokens": vt} # the text model, opened vocab-only + if vision == "cpu": + cfg["vision"]["threads"] = max(1, (os.cpu_count() or 8) // 2) + elif getattr(a, "vision_tokens", None) is not None: + warn("--vision-tokens: images are off, so it is not used") + # requests at once ("parallel", opt-in): written only when given; the recommendation is said once + vram_gb = float(gpu.get("vram_gb", 0.0)) + par = getattr(a, "parallel", None) + if par is not None: + if par >= 2: + cfg["parallel"] = par + for i, line in enumerate(own_path_parallel_note(par, fam, model, vram_gb, ctx)): + (ok if i == 0 else warn)(line) + else: + cfg["parallel"] = 1 + ok("parallel requests: one at a time (--parallel 1)") write_setup_config(cfg_path, cfg, adopted if adopted is not None and adopted.name == cfg_path.name else None) script = write_run_script(tag, cfg_path, port, cfg.get("open_browser") is not False) ok(f"start script: {script.name}") @@ -5633,6 +5754,11 @@ def install_own_path(a, family, gpu, hip, amd, cuda_tk, multi, port, ram, adopte say(f" API (OpenAI): http://127.0.0.1:{port}/v1 (any API key; model name: anything)") say(f" API (Anthropic): http://127.0.0.1:{port}/v1/messages") say(f" Next time: just run {'START-HERE.bat' if WIN else './setup.sh'} (or {script.name}) - it starts right away") + if vision != "none": + say(" Images: send them in the chat page, in chat.py (/image ) or over the API") + if par is None: # the opt-in, said once (nothing changes) + for line in own_path_parallel_note(None, fam, model, vram_gb, ctx): + say(" " + line) if a.no_start: return 0 return start(cfg_path, port) @@ -5687,8 +5813,8 @@ def main() -> int: return mac_setup(sys.argv[1:]) ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) ap.add_argument("--family", choices=list(FAMILIES) + list(PREVIEW_FAMILIES), - help="qwen = Qwen3.8-Flash-Next, swift = Swift 1.5 (qwen36 = Qwen3.6-35B-A3B: download only, the " - "engine does not run it yet)") + help="qwen = Qwen3.8-Flash-Next, swift = Swift 1.5, qwen36 = Qwen3.6-35B-A3B (pictures with --vision, " + "several requests at once with --parallel; docs/QWEN36.md)") ap.add_argument("--model", choices=list(dict.fromkeys([*MODELS, *(m for f in PREVIEW_FAMILIES.values() for m in f["models"])]))) ap.add_argument("--context", type=int) diff --git a/tools/test_setup_qwen36.py b/tools/test_setup_qwen36.py index 7358a3d8..3c76181c 100644 --- a/tools/test_setup_qwen36.py +++ b/tools/test_setup_qwen36.py @@ -93,6 +93,9 @@ class InstallOwnPath(unittest.TestCase): def engine_step(a, gpu, hip, amd, cuda_tk, vision): self.calls.append(("engine", vision)) + if vision != "none": # the image encoder beside the engine + eng.mkdir(parents=True, exist_ok=True) + (eng / setup.VEXE).write_text("x") return self.root / "llama", eng, {"version": "0.1.44"}, ["/libs"], gpu, vision def write_cfg(path, cfg, source=None): @@ -115,13 +118,13 @@ class InstallOwnPath(unittest.TestCase): p.start() self.addCleanup(p.stop) - def install(self, ram=64.0, vram=16.0, **kw): + def install(self, ram=64.0, vram=16.0, hip=False, **kw): gpu = {"index": 0, "count": 1, "vram_gb": vram, "name": "Test GPU"} - return run(setup.install_own_path, args(models_dir=str(self.root / "models"), **kw), "qwen36", gpu, False, [], + return run(setup.install_own_path, args(models_dir=str(self.root / "models"), **kw), "qwen36", gpu, hip, [], 13, [], 8080, ram, None) def test_installs_the_pinned_file_and_writes_the_config(self): - rc, out = self.install(model="UD-Q4_K_XL") + rc, out = self.install(model="UD-Q4_K_XL", vision="no") self.assertEqual(rc, 0, out) get = [c for c in self.calls if c[0] == "get"] self.assertEqual(len(get), 1) @@ -129,7 +132,9 @@ class InstallOwnPath(unittest.TestCase): self.assertEqual(get[0][1], setup.hf(REPO) + gguf.name) self.assertEqual(get[0][2], gguf) self.assertIn(("sha", gguf.name), self.calls) - self.assertIn(("engine", "none"), self.calls) # no image encoder for this family yet + self.assertIn(("engine", "none"), self.calls) # --vision no: no image encoder + self.assertNotIn("--vision", self.cfg["args"]) + self.assertNotIn("vision", self.cfg) tok = [c for c in self.calls if c[0] == "run"] self.assertTrue(tok and "strata_tokenizer.py" in str(tok[0][1])) a = self.cfg["args"] @@ -176,12 +181,74 @@ class InstallOwnPath(unittest.TestCase): self.assertEqual(rc, 1) self.assertIn("not enough free disk space", out) - def test_bigger_card_bigger_context_and_vision_said_off(self): - rc, out = self.install(model="UD-Q4_K_XL", vram=32.0, vision="yes") + def test_bigger_card_bigger_context(self): + rc, out = self.install(model="UD-Q4_K_XL", vram=32.0, vision="no") self.assertEqual(rc, 0, out) a = self.cfg["args"] self.assertEqual(a[a.index("--max-context") + 1], "131072") - self.assertIn("images are not available", out) + + def test_images_by_default_on_a_16gb_nvidia_card_use_the_gpu_encoder(self): + rc, out = self.install(model="UD-Q4_K_XL", vram=16.0) # --yes: the question's default answer + self.assertEqual(rc, 0, out) + self.assertIn(("engine", "gpu"), self.calls) + mm = self.root / "models" / "qwen36-UD-Q4_K_XL" / "mmproj-F16.gguf" + self.assertIn(("get", setup.hf(REPO) + "mmproj-F16.gguf", mm), self.calls) + self.assertIn(("sha", "mmproj-F16.gguf"), self.calls) # pinned: size + SHA-256 (899283584 bytes) + self.assertEqual(setup.OWN_PATH_FAMILIES["qwen36"]["sha256"]["mmproj-F16.gguf"][0], 899283584) + a = self.cfg["args"] + self.assertIn("--vision", a) + v = self.cfg["vision"] + self.assertTrue(v["gpu"]) + self.assertEqual(v["mmproj"], str(mm)) + self.assertTrue(v["model"].endswith("Qwen3.6-35B-A3B-UD-Q4_K_XL.gguf")) # the text model, opened vocab-only + self.assertEqual(Path(v["exe"]).name, setup.VEXE) + self.assertEqual(v["max_tokens"], 1024) + self.assertIn("images: on", out) + + def test_a_12gb_card_is_recommended_the_cpu_encoder_never_forced(self): + rc, out = self.install(model="UD-Q4_K_XL", vram=12.0) # the default answer is no + self.assertEqual(rc, 0, out) + self.assertNotIn("vision", self.cfg) + rc, out = self.install(model="UD-Q4_K_XL", vram=12.0, vision="yes") # yes: the CPU encoder, said why + self.assertEqual(rc, 0, out) + self.assertFalse(self.cfg["vision"]["gpu"]) + self.assertEqual(self.cfg["vision"]["max_tokens"], 300) + self.assertIn("threads", self.cfg["vision"]) + rc, out = self.install(model="UD-Q4_K_XL", vram=12.0, vision="gpu") # gpu asked for: kept, with a note + self.assertEqual(rc, 0, out) + self.assertTrue(self.cfg["vision"]["gpu"]) + self.assertIn("kept as you chose", out) + + def test_amd_reads_pictures_on_the_cpu(self): + with mock.patch.object(setup, "WIN", False): + rc, out = self.install(model="UD-Q4_K_XL", vram=32.0, hip=True, vision="yes") + self.assertEqual(rc, 0, out) + self.assertFalse(self.cfg["vision"]["gpu"]) + self.assertIn("--vision", self.cfg["args"]) + with mock.patch.object(setup, "WIN", True): + rc, out = self.install(model="UD-Q4_K_XL", vram=32.0, hip=True, vision="cpu") + self.assertNotIn("vision", self.cfg) + self.assertIn("Linux-only", out) + + def test_parallel_is_opt_in_and_recommended_where_the_experts_fit(self): + fam = setup.OWN_PATH_FAMILIES["qwen36"] + # nothing written without --parallel; the recommendation is said + rc, out = self.install(model="UD-Q4_K_XL", vram=32.0, vision="no", context=32768) + self.assertEqual(rc, 0, out) + self.assertNotIn("parallel", self.cfg) + self.assertIn("--parallel 3", out) + # a 12 GB card runs the hybrid mode: one at a time recommended, any asked number kept + self.assertEqual(setup.own_path_parallel_recommend(fam, "UD-Q4_K_XL", 12.0, 32768), 0) + rc, out = self.install(model="UD-Q4_K_XL", vram=12.0, vision="no", parallel=4) + self.assertEqual(self.cfg["parallel"], 4) + self.assertIn("recommended for this card: one at a time", out) + self.assertIn("kept as you chose", out) + rc, out = self.install(model="UD-Q4_K_XL", vram=12.0, vision="no", parallel=1) + self.assertEqual(self.cfg["parallel"], 1) + rc, out = self.install(model="UD-Q4_K_XL", vram=32.0, vision="no", parallel=12) + self.assertIn("at most 8", out) + self.assertEqual(self.cfg["parallel"], 12) # written as asked; the server and the engine cap it + self.assertGreater(setup.own_path_parallel_slot_gb(fam, 32768), 1.4) def test_config_read_back(self): self.install(model="UD-Q6_K_XL", context=65536) @@ -189,6 +256,7 @@ class InstallOwnPath(unittest.TestCase): p.write_text(json.dumps(self.cfg), encoding="utf-8") ch = setup.choices_from_config(p) self.assertEqual((ch["family"], ch["model"], ch["context"]), ("qwen36", "UD-Q6_K_XL", 65536)) + self.assertEqual(ch["vision"], "gpu") # 16 GB NVIDIA, the default answer self.assertTrue(setup.own_path_config(self.cfg)) self.assertEqual(setup.calibration_targets([p], None, None), []) # the tuning is Flash-Next's From cfc7686c0040bc692299e083231dd224ca59b8d6 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Wed, 14 Oct 2026 01:11:42 +0200 Subject: [PATCH 4/8] tools/qwen35: the Qwen3.6 pictures and parallel-requests gates (engine protocol harness, solo / batch identity, protocol edges, llama.cpp picture comparison, throughput A/B) --- tools/qwen35/parity_prompts.ids | 10 ++ tools/qwen35/pictures/code4217.png | Bin 0 -> 9774 bytes tools/qwen35/pictures/shapes.png | Bin 0 -> 7153 bytes tools/qwen35/q36_batch_gate.py | 115 +++++++++++++++++++++++ tools/qwen35/q36_cmp_gate.py | 13 +++ tools/qwen35/q36_harness.py | 143 +++++++++++++++++++++++++++++ tools/qwen35/q36_par_bench.py | 98 ++++++++++++++++++++ tools/qwen35/q36_proto_edge.py | 112 ++++++++++++++++++++++ tools/qwen35/q36_serve_par.py | 65 +++++++++++++ tools/qwen35/q36_solo_gate.py | 26 ++++++ tools/qwen35/q36_venc.py | 18 ++++ tools/qwen35/q36_vision_cmp.py | 131 ++++++++++++++++++++++++++ tools/qwen35/q36_vision_proto.py | 91 ++++++++++++++++++ tools/qwen35/q36_vision_serve.py | 20 ++++ 14 files changed, 842 insertions(+) create mode 100644 tools/qwen35/parity_prompts.ids create mode 100644 tools/qwen35/pictures/code4217.png create mode 100644 tools/qwen35/pictures/shapes.png create mode 100644 tools/qwen35/q36_batch_gate.py create mode 100644 tools/qwen35/q36_cmp_gate.py create mode 100644 tools/qwen35/q36_harness.py create mode 100644 tools/qwen35/q36_par_bench.py create mode 100644 tools/qwen35/q36_proto_edge.py create mode 100644 tools/qwen35/q36_serve_par.py create mode 100644 tools/qwen35/q36_solo_gate.py create mode 100644 tools/qwen35/q36_venc.py create mode 100644 tools/qwen35/q36_vision_cmp.py create mode 100644 tools/qwen35/q36_vision_proto.py create mode 100644 tools/qwen35/q36_vision_serve.py diff --git a/tools/qwen35/parity_prompts.ids b/tools/qwen35/parity_prompts.ids new file mode 100644 index 00000000..81968c47 --- /dev/null +++ b/tools/qwen35/parity_prompts.ids @@ -0,0 +1,10 @@ +248045,846,198,7734,264,2716,3255,883,264,324,55965,51624,852,13325,264,1876,303,264,16002,13,248046,198,248045,74455,198,248068,271,248069,271 +248045,846,198,60856,449,436,34810,6297,303,12654,440,615,321,2113,303,496,7,16,681,321,884,2250,4821,6813,13,248046,198,248045,74455,198,248068,271,248069,271 +248045,846,198,3710,369,220,16,22,348,220,17,18,478,220,16,19,19,593,220,16,17,30,6712,279,7123,13,248046,198,248045,74455,198,248068,271,248069,271 +248045,846,198,814,20139,1204,264,43447,4138,310,264,5600,4514,6086,13,248046,198,248045,74455,198,248068,271,248069,271 +248045,846,198,26583,1083,5753,25,561,5257,310,44663,10583,506,4139,3162,7840,11,5171,2943,13,248046,198,248045,74455,198,248068,271,248069,271 +248045,846,198,826,4097,11461,1881,25804,321,40986,13,248046,198,248045,74455,198,248068,271,248069,271 +248045,846,198,8917,5437,537,279,6868,314,67815,321,68613,303,2250,22157,13,248046,198,248045,74455,198,248068,271,248069,271 +248045,846,198,7734,264,4566,1576,21988,264,2236,440,2192,11,3049,11,1007,321,2250,9212,13,248046,198,248045,74455,198,248068,271,248069,271 +248045,846,198,2592,660,13805,3595,513,427,9510,536,321,660,427,9510,536,513,1147,10090,536,11,513,660,13805,3595,1147,10090,536,30,79091,13,248046,198,248045,74455,198,248068,271,248069,271 +248045,846,198,7734,264,6185,36974,883,40297,10849,383,264,3177,8329,13,248046,198,248045,74455,198,248068,271,248069,271 diff --git a/tools/qwen35/pictures/code4217.png b/tools/qwen35/pictures/code4217.png new file mode 100644 index 0000000000000000000000000000000000000000..1b1cefb8978b480074f61e4ab297dce1c03df001 GIT binary patch literal 9774 zcmd^lXHZmIw{2rW0Y#BuAQ%XeRg@f5Y%zk0KqE9DQ8I$WCJIPYkc=b+6eK4>Vgrig zoP`F-Ij06X+}Yl9>YcCN_o`mi{d4QyKV4mWuf6tKGmJULT-)!VqQYUCQ#1$!;_#i@ zHyrWhF7jTYIj1wOC753n>z6y+o_@;F#X{)@x zzj<{*_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Bu+5VpF{1FDwWiNsUCTIh|+&widIhb;lGVkKkLf(*QvKV9dF%UrhSi8tr8CZy`1AT zOGo!V3uo%#x%t;Q`0dg?QsUR&hcUHHQ7%!Y8=O4IjF?fmJ>_z{DDTF0!QZbiesYnT zvo0#{6~5{3OO(@f_m{kZHZuBJ>LfSozh3?4!2Q}&#!7Yeyi@@YTmL+RKU3x`hm{w) z&^V>^2V?%_M1EgHZ)8iba>MFoJ_P2!Im>qsUfoL5w^mknbxr)|+y0-&`~JiTT*{9;m;YB6X4>&)qi;XkBbZVqt;}TRUD~Y6#tH{`xlZuk0;AJK6AP8_a!>s9C^ll zPqh9Ka5gkc*YiPF2V{fOnS28ME-xBsgo-#8o z$A@z=Z5mzsYj<^Tt7YA{=mQ{t0@F6TWOg_U zu@JsH85i1}aekt;ZaV=fRNOKoiS5%W6$d!X%5QC9DeMvhQ#n?~OKtVvB2%D`10XCq zb4?JksO*_=e2iJ-5(CU~e0Nn-FJL|brf=;_nmRI&Cz+I6Q^+u9ee;&XSumGw7?4KQ-?X#xEpH<(EH)2I6BIsDDn?9kF-$@ zb+euY+`j<#qiHGk+r-f)md%q5VSV0r3_sy}-qBECUjJ#8R0PvoC>Ot38-68;`JaIS z$m@n&&Nc@j_8#8U@39y@`U-Z=$QI3&+3^6bCHsr!vwm$rfDs?zBQPDags_9{hviF4Q^6u+{1&PKBZgxSMG6_5sG5<6MPh&4+E2*ik_SkM1~7f z{-9qleE87Su(=O`pn3CG82u0XuIJw)!+)PIm{2G(wFIj1i`Kv< R<;yU{9i-yTtQ$J7{sTx$T?GID literal 0 HcmV?d00001 diff --git a/tools/qwen35/pictures/shapes.png b/tools/qwen35/pictures/shapes.png new file mode 100644 index 0000000000000000000000000000000000000000..4e5a72a320e88814d4820b7dbc432b3e517b8cbd GIT binary patch literal 7153 zcmds6X*`r|+rP$GLlRMzxTA#V&MwQSWXYD?wk#v0FqSN19WzmPB1lH<+`FD*Ru5mY=fWUImFHo)yE;5c13SKp3_Jnm;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UY6WL|IsTbx7D_PB8JJ3GxVZ*wC zO$zw&Tw7sr5EzajklpibJ?Cg^fiAN%5~52{s`^zq_sO#OsOl2&C88JHo|yitSlvg_ zf+~hdG8yFL7+}vswx<$34%F*`gZMD+ruFP(*L;3-_NPyK%|;=&ma?~3skJ+^IY~u2 zpoZL=d+S?Ko_Wdhn}+T{Tos2nf6zq{%2!|IKgQJU(# z_7osVxi(d0(--n zT|0stm#5$8#-Ee2t=`(2jOh?63N5-=$lUK>+8V(fVRyX@Hedy?(6T*v;JHJB>CMt zd+^a30V9|M solo tokens (and, with --golden, equal to the base engine's); +2. the first --slots prompts through BGEN, admitted one after the other, then decoding together -> every slot's tokens + must equal its solo tokens; the decode rate of the window phase; +3. --waves: the 10 prompts in waves of --slots (slot reuse: the cached state of a finished slot is taken over); +4. --long L: a prompt of about L tokens admitted into the last slot while the others decode (its prompt chunks run + between their windows); the others' tokens must still equal their solo tokens, and so must the long one's. +""" +from pathlib import Path +import argparse, json, shlex, sys, time +sys.path.insert(0, __file__.rsplit("/", 1)[0] if "/" in __file__ else ".") +from q36_harness import Eng, load_prompts + + +def same(a, b): + return a == b + + +ap = argparse.ArgumentParser() +ap.add_argument("--exe", required=True) +ap.add_argument("--args", default="") +ap.add_argument("--slots", type=int, default=4) +ap.add_argument("--n", type=int, default=128) +ap.add_argument("--prompts", default=str(Path(__file__).resolve().parent / "parity_prompts.ids")) +ap.add_argument("--golden", default=None) +ap.add_argument("--keys", default="") +ap.add_argument("--long", type=int, default=0) +ap.add_argument("--waves", action="store_true") +ap.add_argument("--skip-solo-bench", action="store_true") +ap.add_argument("--out", default=None) +ap.add_argument("--log", default=None) +ap.add_argument("--env", default="") +a = ap.parse_args() +env = dict(kv.split("=", 1) for kv in a.env.split() if "=" in kv) +eng = Eng(a.exe, shlex.split(a.args), env=env, log=a.log) +print("ready:", eng.ready, "info:", eng.info, "load %.1fs" % eng.load_s, flush=True) +prompts = load_prompts(a.prompts) +ok = True +res = {"args": a.args, "slots": a.slots} + +# 1. solo +solo, solo_rate = [], [] +for i, ids in enumerate(prompts): + toks, done, ttft, wall = eng.solo(ids, a.n, a.keys) + solo.append(toks) + solo_rate.append(len(toks) / max(1e-9, wall - (ttft or 0))) +print("solo: %d prompts, decode %.1f tok/s median" % (len(solo), sorted(solo_rate)[len(solo_rate) // 2]), flush=True) +if a.golden: + g = json.load(open(a.golden))["tokens"] + eq = [same(x, y) for x, y in zip(solo, g)] + print("solo vs golden (base engine):", "identical %d of %d" % (sum(eq), len(eq)), flush=True) + ok &= all(eq) +res["solo_tok_s_median"] = sorted(solo_rate)[len(solo_rate) // 2] + +# 2. batch +S = min(a.slots, len(prompts)) +reqs = [{"ids": prompts[i], "n": a.n, "slot": i, "keys": a.keys} for i in range(S)] +r = eng.batch(reqs) +eq = [same(r["tokens"][i], solo[i]) for i in range(S)] +print("batch %d: %d of %d slots identical to solo | wall %.2fs, window phase %d tokens in %.2fs = %.1f tok/s (aggregate)" + % (S, sum(eq), S, r["wall"], r["tail_tokens"], r["tail_s"], r["tail_tok_s"]), flush=True) +for i, e in enumerate(eq): + if not e: + x, y = r["tokens"][i], solo[i] + k = next((k for k in range(min(len(x), len(y))) if x[k] != y[k]), min(len(x), len(y))) + print(" slot %d differs at token %d (lens %d / %d)" % (i, k, len(x), len(y))) +ok &= all(eq) +res["batch"] = {"slots": S, "identical": sum(eq), "wall": r["wall"], "tail_tok_s": r["tail_tok_s"], "tail_tokens": r["tail_tokens"]} + +# 3. waves (slot reuse) +if a.waves: + wave_ok = True + for w0 in range(0, len(prompts), S): + idx = list(range(w0, min(w0 + S, len(prompts)))) + rq = [{"ids": prompts[i], "n": a.n, "slot": j, "keys": a.keys} for j, i in enumerate(idx)] + rr = eng.batch(rq) + for j, i in enumerate(idx): + if not same(rr["tokens"][j], solo[i]): + wave_ok = False + print(" wave %d prompt %d differs" % (w0 // S, i)) + print("waves of %d: %s" % (S, "all identical" if wave_ok else "DIFFERENT"), flush=True) + ok &= wave_ok + +# 4. a long prompt admitted while the others decode +if a.long and S >= 2: + base = prompts[0] + filler = [] + while len(filler) < a.long: + for p in prompts: + filler += p[3:-8] if len(p) > 12 else p + longids = filler[:a.long] + prompts[1][-8:] + toks, done, ttft, wall = eng.solo(longids, 48, a.keys) + reqs = [{"ids": prompts[i], "n": a.n * 2, "slot": i, "keys": a.keys} for i in range(S - 1)] + # the first S-1 are admitted first; then the long one is admitted while they decode + longreq = {"ids": longids, "n": 48, "slot": S - 1, "keys": a.keys} + solo2 = [] + for i in range(S - 1): + t2, _, _, _ = eng.solo(prompts[i], a.n * 2, a.keys) + solo2.append(t2) + rr = eng.batch(reqs + [longreq]) + eq = [same(rr["tokens"][i], solo2[i]) for i in range(S - 1)] + [same(rr["tokens"][S - 1], toks)] + print("long prompt (%d tokens) admitted beside %d decoding slots: %s | admission stamps %s" + % (len(longids), S - 1, "%d of %d identical" % (sum(eq), len(eq)), ["%.2f" % x for x in rr["admit_stamps"]]), flush=True) + ok &= all(eq) + +res["ok"] = ok +if a.out: + json.dump(res, open(a.out, "w")) +eng.close() +print("GATE", "PASS" if ok else "FAIL", flush=True) +sys.exit(0 if ok else 1) diff --git a/tools/qwen35/q36_cmp_gate.py b/tools/qwen35/q36_cmp_gate.py new file mode 100644 index 00000000..078f96a7 --- /dev/null +++ b/tools/qwen35/q36_cmp_gate.py @@ -0,0 +1,13 @@ +"""q36_cmp_gate.py A.json B.json : per prompt identical or the first differing index.""" +import json, sys +a, b = json.load(open(sys.argv[1]))["tokens"], json.load(open(sys.argv[2]))["tokens"] +same = 0 +for i, (x, y) in enumerate(zip(a, b)): + n = next((k for k in range(min(len(x), len(y))) if x[k] != y[k]), None) + if n is None and len(x) == len(y): + same += 1 + print("p%02d identical (%d tokens)" % (i, len(x))) + else: + print("p%02d DIFFERENT at %s (len %d vs %d)" % (i, n, len(x), len(y))) +print("identical: %d of %d" % (same, len(a))) +sys.exit(0 if same == len(a) else 1) diff --git a/tools/qwen35/q36_harness.py b/tools/qwen35/q36_harness.py new file mode 100644 index 00000000..48a6e4bd --- /dev/null +++ b/tools/qwen35/q36_harness.py @@ -0,0 +1,143 @@ +"""harness.py - drives strata-q36 / `strata` (qwen35moe) --serve over the engine protocol, for the q36-vp gates. + + Eng(exe, args) starts `exe --serve args`, waits for READY (INFO lines kept) + .solo(ids, n, keys, emb) GEN / GENI one request -> (tokens, DONE line) + .batch(reqs) reqs = [{"ids":[..], "n":N, "keys":"", "slot":b, "emb":path}] admitted one after the + other (BGEN, as the server does: one admission at a time), then every slot decodes + together -> dict(tokens=[..per req], wall, steady_tok_s, ...) +Run on the lent box; the box's lock / memory cap wrap the whole python call (see run.sh). +""" +import json, os, queue, subprocess, sys, threading, time + + +def load_prompts(path): + return [[int(x) for x in l.strip().split(",") if x] for l in open(path) if l.strip()] + + +class Eng: + def __init__(self, exe, args, env=None, log=None, quiet=False): + e = dict(os.environ) + e.update(env or {}) + self.logf = open(log, "w") if log else subprocess.DEVNULL + self.p = subprocess.Popen([exe, "--serve", *args], stdin=subprocess.PIPE, stdout=subprocess.PIPE, + stderr=self.logf, text=True, bufsize=1, env=e) + self.q = queue.Queue() + self.info = {} + threading.Thread(target=self._pump, daemon=True).start() + t0 = time.time() + while True: + l = self.line(600) + if l is None: + raise SystemExit("engine ended before READY (see %s)" % log) + if l.startswith("INFO "): + for kv in l.split()[1:]: + k, _, v = kv.partition("=") + self.info[k] = v + if l.startswith("READY"): + self.ready = l + break + self.load_s = time.time() - t0 + + def _pump(self): + for l in self.p.stdout: + self.q.put(l.rstrip("\n")) + self.q.put(None) + + def line(self, timeout=600): + try: + return self.q.get(timeout=timeout) + except queue.Empty: + raise SystemExit("engine silent for %ds" % timeout) + + def send(self, s): + self.p.stdin.write(s + "\n") + self.p.stdin.flush() + + def solo(self, ids, n, keys="", emb=None): + head = ("GENI %d" % n if emb else "GEN %d" % n) + (" " + keys if keys else "") + (" " + emb if emb else "") + t0 = time.time() + self.send(head + " " + ",".join(map(str, ids))) + toks, ttft, pp = [], None, [] + while True: + l = self.line() + if l is None: + raise SystemExit("engine died") + if l.startswith("T "): + if ttft is None: + ttft = time.time() - t0 + toks.append(int(l.split()[1])) + elif l.startswith("PP "): + pp.append(l) + elif l.startswith("DONE"): + return toks, l, ttft, time.time() - t0 + elif l.startswith("ERR"): + raise SystemExit("ERR: " + l) + + def batch(self, reqs, hold_s=0.0): + """Admit every request (BGEN) in order, then read until every slot is done.""" + toks = [[] for _ in reqs] + by_slot = {r["slot"]: i for i, r in enumerate(reqs)} + done = [False] * len(reqs) + t0 = time.time() + first_bt = None + admitted_at = None + stamps = [] + for i, r in enumerate(reqs): + head = ("BGENI %d %d" if r.get("emb") else "BGEN %d %d") % (r["slot"], r["n"]) + keys = r.get("keys", "") + self.send(head + (" " + keys if keys else "") + (" " + r["emb"] if r.get("emb") else "") + " " + + ",".join(map(str, r["ids"]))) + while True: + l = self.line() + if l is None: + raise SystemExit("engine died") + if l.startswith("T "): + toks[i].append(int(l.split()[1])) + elif l.startswith("BT "): + f = l.split() + j = by_slot[int(f[1])] + toks[j].append(int(f[2])) + if first_bt is None: + first_bt = time.time() + elif l.startswith("BDONE "): + done[by_slot[int(l.split()[1])]] = True + elif l.startswith("BADM "): + f = l.split() + if f[2] == "0": + done[i] = True + break + elif l.startswith("ERR"): + raise SystemExit("ERR: " + l) + stamps.append(time.time() - t0) + admitted_at = time.time() + n_at_admit = sum(len(t) for t in toks) + while not all(done): + l = self.line() + if l is None: + raise SystemExit("engine died") + if l.startswith("BT "): + f = l.split() + toks[by_slot[int(f[1])]].append(int(f[2])) + elif l.startswith("BDONE "): + done[by_slot[int(l.split()[1])]] = True + elif l.startswith("ERR"): + raise SystemExit("ERR: " + l) + t1 = time.time() + tot = sum(len(t) for t in toks) + return {"tokens": toks, "wall": t1 - t0, "admit_s": admitted_at - t0, "admit_stamps": stamps, + "tail_tokens": tot - n_at_admit, "tail_s": t1 - admitted_at, + "tail_tok_s": (tot - n_at_admit) / max(1e-9, t1 - admitted_at)} + + def close(self): + try: + self.send("STOP") + except Exception: + pass + try: + self.p.stdin.close() + except Exception: + pass + try: + self.p.wait(timeout=30) + except Exception: + self.p.kill() diff --git a/tools/qwen35/q36_par_bench.py b/tools/qwen35/q36_par_bench.py new file mode 100644 index 00000000..7d902d25 --- /dev/null +++ b/tools/qwen35/q36_par_bench.py @@ -0,0 +1,98 @@ +"""par_bench.py - aggregate decode throughput of N requests at once: strata-q36 (--batch) and llama.cpp (llama-server -np N), +same GGUF, same prompt ids, greedy, 128 new tokens each. One JSON line per (engine, N, round). + + python q36_par_bench.py strata --exe E --args "--model M --max-context 8192 --batch 8 --mtp 0" --ns 1,2,4,8 --rounds 3 --out F + python q36_par_bench.py llama --server BIN --model M --ns 1,2,4,8 --rounds 3 --out F [--port 8197] + +The strata wall time runs from the first BGEN to the last BDONE (admissions included); the llama one from the first request +sent to the last answer (prompt reading included); tok/s = tokens produced / wall. `tail_tok_s` (strata): the window phase +only, after the last admission.""" +from pathlib import Path +import argparse, json, os, shlex, subprocess, sys, threading, time, urllib.request +sys.path.insert(0, __file__.rsplit("/", 1)[0] if "/" in __file__ else ".") +from q36_harness import Eng, load_prompts + +ORDER = [0, 1, 2, 3, 5, 8, 0, 1] # the prompts that run the full 128 tokens, repeated to fill 8 slots + + +def strata(a): + prompts = load_prompts(a.prompts) + eng = Eng(a.exe, shlex.split(a.args), log=a.log) + out = open(a.out, "a") + for n in [int(x) for x in a.ns.split(",")]: + for rnd in range(a.rounds): + reqs = [{"ids": prompts[ORDER[i]], "n": a.n, "slot": i} for i in range(n)] + r = eng.batch(reqs) + tot = sum(len(t) for t in r["tokens"]) + row = {"engine": "strata", "n": n, "round": rnd, "tokens": tot, "wall": r["wall"], "tok_s": tot / r["wall"], + "tail_tok_s": r["tail_tok_s"]} + print(json.dumps(row), flush=True) + out.write(json.dumps(row) + "\n") + out.flush() + eng.close() + + +def post(port, body): + return json.loads(urllib.request.urlopen(urllib.request.Request(f"http://127.0.0.1:{port}/completion", json.dumps(body).encode(), + {"Content-Type": "application/json"}), timeout=900).read()) + + +def llama(a): + prompts = load_prompts(a.prompts) + out = open(a.out, "a") + for n in [int(x) for x in a.ns.split(",")]: + cmd = [a.server, "-m", a.model, "-ngl", "99", "-fa", "on", "-c", str(8192 * n), "-np", str(n), "--port", str(a.port), + "--no-webui", "-t", "16"] + shlex.split(a.llama_args) + log = open(a.log or os.devnull, "a") + p = subprocess.Popen(cmd, stdout=log, stderr=log) + try: + for _ in range(240): + try: + urllib.request.urlopen(f"http://127.0.0.1:{a.port}/health", timeout=2) + break + except Exception: # noqa: BLE001 + time.sleep(1) + for rnd in range(a.rounds + 1): # round 0: the warm-up + res = [None] * n + + def one(i): + res[i] = post(a.port, {"prompt": prompts[ORDER[i]], "n_predict": a.n, "temperature": 0, "top_k": 1, + "cache_prompt": False, "id_slot": i}) + ts = [threading.Thread(target=one, args=(i,)) for i in range(n)] + t0 = time.time() + for t in ts: + t.start() + for t in ts: + t.join() + wall = time.time() - t0 + tot = sum(r["tokens_predicted"] for r in res) + if rnd == 0: + continue + row = {"engine": "llama", "n": n, "round": rnd - 1, "tokens": tot, "wall": wall, "tok_s": tot / wall} + print(json.dumps(row), flush=True) + out.write(json.dumps(row) + "\n") + out.flush() + finally: + p.terminate() + try: + p.wait(timeout=60) + except subprocess.TimeoutExpired: + p.kill() + + +ap = argparse.ArgumentParser() +ap.add_argument("mode", choices=["strata", "llama"]) +ap.add_argument("--exe") +ap.add_argument("--args", default="") +ap.add_argument("--server") +ap.add_argument("--model") +ap.add_argument("--llama-args", default="") +ap.add_argument("--ns", default="1,2,4,8") +ap.add_argument("--rounds", type=int, default=3) +ap.add_argument("--n", type=int, default=128) +ap.add_argument("--prompts", default=str(Path(__file__).resolve().parent / "parity_prompts.ids")) +ap.add_argument("--port", type=int, default=8197) +ap.add_argument("--out", required=True) +ap.add_argument("--log", default=None) +a = ap.parse_args() +(strata if a.mode == "strata" else llama)(a) diff --git a/tools/qwen35/q36_proto_edge.py b/tools/qwen35/q36_proto_edge.py new file mode 100644 index 00000000..a7d623f1 --- /dev/null +++ b/tools/qwen35/q36_proto_edge.py @@ -0,0 +1,112 @@ +"""proto_edge.py - the protocol's edges for parallel requests (engine level): max_new 1, BSTOP, a busy slot, STOP during an +admission's prompt read, slot reuse (the held state), sampled requests in a batch against the same request alone, a +request that reaches the context's end.""" +from pathlib import Path +import argparse, shlex, sys, time +sys.path.insert(0, __file__.rsplit("/", 1)[0] if "/" in __file__ else ".") +from q36_harness import Eng, load_prompts + +ap = argparse.ArgumentParser() +ap.add_argument("--exe", required=True) +ap.add_argument("--args", default="") +ap.add_argument("--log", default=None) +a = ap.parse_args() +eng = Eng(a.exe, shlex.split(a.args), log=a.log) +P = load_prompts(str(Path(__file__).resolve().parent / "parity_prompts.ids")) +ok = True + + +def check(name, cond, extra=""): + global ok + ok &= bool(cond) + print(("PASS " if cond else "FAIL ") + name + (" - " + extra if extra else ""), flush=True) + + +def lines_until(pred, timeout=120): + out = [] + t0 = time.time() + while time.time() - t0 < timeout: + l = eng.line(timeout) + out.append(l) + if pred(l): + return out + return out + + +# 1. max_new 1: T, DONE, BADM slot 0 +eng.send("BGEN 0 1 " + ",".join(map(str, P[0]))) +r = lines_until(lambda l: l.startswith("BADM")) +check("BGEN max_new 1 ends at the admission", r[-1] == "BADM 0 0" and any(l.startswith("T ") for l in r), str(r[-3:])) + +# 2. a long answer, BSTOP after a few tokens, then a longer request on the held state +eng.send("BGEN 0 200 " + ",".join(map(str, P[1]))) +r = lines_until(lambda l: l.startswith("BADM")) +check("BGEN max_new 200 continues", r[-1] == "BADM 0 1", r[-1]) +bts = [] +while len(bts) < 5: + l = eng.line() + if l.startswith("BT 0"): + bts.append(int(l.split()[2])) +# the slot is busy: another BGEN for it is refused (BT lines of the running slot may come first) +eng.send("BGEN 0 5 " + ",".join(map(str, P[2]))) +seen = lines_until(lambda l: l.startswith("ERR") or l.startswith("BADM")) +for l in seen: + if l.startswith("BT 0"): + bts.append(int(l.split()[2])) +check("BGEN into a busy slot is refused", seen[-1].startswith("ERR BGEN"), seen[-1]) +eng.send("BSTOP 0") +done = lines_until(lambda l: l.startswith("BDONE 0")) +for l in done: + if l.startswith("BT 0"): + bts.append(int(l.split()[2])) +check("BSTOP ends the slot with cancel", done[-1].split()[3] == "cancel", done[-1]) +first = [int(l.split()[1]) for l in r if l.startswith("T ")] +# the slot holds the prompt and every token a window fed (all but the last one): a continuation extends exactly that +eng.send("BGEN 0 3 " + ",".join(map(str, P[1] + first + bts))) +r2 = lines_until(lambda l: l.startswith("BADM")) +dn = [l for l in r2 if l.startswith("DONE")][0].split() +check("a continuation reuses the slot's held state", int(dn[8]) == len(P[1]) + len(first) + len(bts) - 1, + "reused %s of %d" % (dn[8], len(P[1] + first + bts))) +lines_until(lambda l: l.startswith("BDONE 0")) + +# 3. STOP during an admission's prompt read +filler = [] +while len(filler) < 3000: + for p in P: + filler += p[3:-8] +filler = filler[:3000] +eng.send("BGEN 1 8 " + ",".join(map(str, filler))) +time.sleep(0.15) +eng.send("STOP") +r3 = lines_until(lambda l: l.startswith("BADM")) +dn = [l for l in r3 if l.startswith("DONE")][0].split() +pp = [l for l in r3 if l.startswith("PP ")] +check("STOP during the prompt read ends it with cancel", dn[5] == "cancel" and r3[-1] == "BADM 1 0", + "%d PP line(s), DONE %s" % (len(pp), " ".join(dn[:6]))) +# the engine is in step: a normal request on the same slot works +eng.send("BGEN 1 6 " + ",".join(map(str, P[3]))) +r4 = lines_until(lambda l: l.startswith("BADM")) +check("a request after the cancelled read works", r4[-1] == "BADM 1 1", r4[-1]) +lines_until(lambda l: l.startswith("BDONE 1")) + +# 4. sampled: batch against alone, same seed +keys = "temperature=0.8 top_k=40 top_p=0.95 seed=11" +toks, _, _, _ = eng.solo(P[4], 40, keys) +res = eng.batch([{"ids": P[4], "n": 40, "slot": 2, "keys": keys}, {"ids": P[5], "n": 40, "slot": 3, "keys": "temperature=0.5 seed=3"}]) +check("a sampled request in a batch equals the same request alone", res["tokens"][0] == toks, + "%d / %d tokens" % (len(res["tokens"][0]), len(toks))) + +# 5. the context's end: a prompt of ctx - 40 tokens and max_new 400 finishes with length +ctx = int(eng.ready.split()[1]) +long_prompt = (filler * 4)[:ctx - 60] +eng.send("BGEN 3 400 " + ",".join(map(str, long_prompt))) +r5 = lines_until(lambda l: l.startswith("ERR") or l.startswith("BADM")) +check("a request that cannot fit its answer is refused with the engine's message", r5[-1].startswith("ERR prompt"), r5[-1][:80]) +eng.send("BGEN 3 50 " + ",".join(map(str, long_prompt[:ctx - 80]))) +r6 = lines_until(lambda l: l.startswith("BADM")) +bd = lines_until(lambda l: l.startswith("BDONE 3")) +check("a request to the context's end finishes", bd[-1].split()[3] in ("length", "stop"), bd[-1]) + +eng.close() +print("GATE", "PASS" if ok else "FAIL") +sys.exit(0 if ok else 1) diff --git a/tools/qwen35/q36_serve_par.py b/tools/qwen35/q36_serve_par.py new file mode 100644 index 00000000..fe6f4a06 --- /dev/null +++ b/tools/qwen35/q36_serve_par.py @@ -0,0 +1,65 @@ +"""q36_serve_par.py PORT [--n 128] [--conc 4] [--img PATH] : N concurrent chat requests through the server (parallel: N), against +the same requests one after the other (the solo path). Greedy, thinking off: the texts must be equal. Prints the +aggregate rate of the concurrent round. With --img: half of the requests carry the picture (and ask about it).""" +import argparse, base64, json, sys, threading, time, urllib.request + +PROMPTS = json.load(open(sys.argv[0].rsplit("/", 1)[0] + "/parity_prompts.json")) if False else [ + "Write a short story about a lighthouse keeper who finds a message in a bottle.", + "Implement an LRU cache in Python with get and put in O(1), and add three unit tests.", + "What is 17 * 23 + 144 / 12? Show the steps.", + "Explain how a refrigerator works to a ten-year-old.", + "Translate into German: The train to Munich leaves at half past seven, platform four.", + "List five differences between TCP and UDP.", + "Summarize the plot of Romeo and Juliet in three sentences.", + "Write a JSON object describing a book with title, author, year and three tags.", +] + + +def ask(port, content, n, out, i, stream=False): + body = {"model": "x", "max_tokens": n, "temperature": 0, "chat_template_kwargs": {"enable_thinking": False}, + "messages": [{"role": "user", "content": content}]} + t0 = time.time() + try: + r = json.loads(urllib.request.urlopen(urllib.request.Request(f"http://127.0.0.1:{port}/v1/chat/completions", + json.dumps(body).encode(), {"Content-Type": "application/json"}), timeout=900).read()) + out[i] = (r["choices"][0]["message"]["content"], r["usage"]["completion_tokens"], time.time() - t0) + except Exception as e: # noqa: BLE001 + out[i] = ("ERROR %s" % e, 0, time.time() - t0) + + +ap = argparse.ArgumentParser() +ap.add_argument("port", type=int) +ap.add_argument("--n", type=int, default=128) +ap.add_argument("--conc", type=int, default=4) +ap.add_argument("--img", default=None) +a = ap.parse_args() +contents = [] +for i in range(a.conc): + p = PROMPTS[i % len(PROMPTS)] + if a.img and i % 2 == 1: + b64 = base64.b64encode(open(a.img, "rb").read()).decode() + contents.append([{"type": "image_url", "image_url": {"url": "data:image/png;base64," + b64}}, + {"type": "text", "text": "What text is written in the image? Answer with the text only."}]) + else: + contents.append(p) +solo = [None] * a.conc +for i, c in enumerate(contents): + ask(a.port, c, a.n, solo, i) +print("one after the other: %d requests, %d tokens, %.1fs" % (a.conc, sum(x[1] for x in solo), sum(x[2] for x in solo)), flush=True) +for rnd in range(2): + conc = [None] * a.conc + ts = [threading.Thread(target=ask, args=(a.port, c, a.n, conc, i)) for i, c in enumerate(contents)] + t0 = time.time() + for t in ts: + t.start() + for t in ts: + t.join() + wall = time.time() - t0 + tot = sum(x[1] for x in conc) + same = [conc[i][0] == solo[i][0] for i in range(a.conc)] + print("concurrent round %d: %d requests, %d tokens in %.1fs = %.1f tok/s aggregate; texts equal to the solo run: %s" + % (rnd, a.conc, tot, wall, tot / wall, same), flush=True) + for i, ok in enumerate(same): + if not ok: + print(" request %d: %r vs %r" % (i, conc[i][0][:80], solo[i][0][:80])) +sys.exit(0) diff --git a/tools/qwen35/q36_solo_gate.py b/tools/qwen35/q36_solo_gate.py new file mode 100644 index 00000000..09caadab --- /dev/null +++ b/tools/qwen35/q36_solo_gate.py @@ -0,0 +1,26 @@ +"""q36_solo_gate.py --exe E --args "..." --out F.json [--n 128] [--prompts F] [--keys K] : greedy tokens of the 10 parity +prompts, one request each through the serve protocol; the JSON is what two builds are compared on (cmp_gate.py).""" +from pathlib import Path +import argparse, json, shlex, sys, time +sys.path.insert(0, __file__.rsplit("/", 1)[0] if "/" in __file__ else ".") +from q36_harness import Eng, load_prompts + +ap = argparse.ArgumentParser() +ap.add_argument("--exe", required=True) +ap.add_argument("--args", default="") +ap.add_argument("--out", required=True) +ap.add_argument("--n", type=int, default=128) +ap.add_argument("--prompts", default=str(Path(__file__).resolve().parent / "parity_prompts.ids")) +ap.add_argument("--keys", default="") +ap.add_argument("--log", default=None) +a = ap.parse_args() +eng = Eng(a.exe, shlex.split(a.args), log=a.log) +print("ready", eng.ready, "info", eng.info, "load %.1fs" % eng.load_s, flush=True) +res = [] +for i, ids in enumerate(load_prompts(a.prompts)): + toks, done, ttft, wall = eng.solo(ids, a.n, a.keys) + dec = done.split() + print("p%02d %d tok %.1f tok/s %s" % (i, len(toks), len(toks) / max(1e-9, wall - (ttft or 0)), done[:70]), flush=True) + res.append(toks) +json.dump({"args": a.args, "tokens": res}, open(a.out, "w")) +eng.close() diff --git a/tools/qwen35/q36_venc.py b/tools/qwen35/q36_venc.py new file mode 100644 index 00000000..2520a03f --- /dev/null +++ b/tools/qwen35/q36_venc.py @@ -0,0 +1,18 @@ +"""q36_venc.py EXE MMPROJ MODEL IMG [IMG ...] : drive strata-vision (ENC protocol), print each picture's header + stats.""" +import subprocess, sys, struct, os, time +exe, mm, model, *imgs = sys.argv[1:] +args = [exe, "--mmproj", mm, "--model", model] + [a for a in os.environ.get("STRATA_VARGS", os.environ.get("VARGS", "")).split() if a] +p = subprocess.Popen(args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True) +print(p.stdout.readline().strip()) +for img in imgs: + out = img + ".sve" + p.stdin.write(f"ENC {img} {out}\n"); p.stdin.flush() + r = p.stdout.readline().strip() + print(img, r) + if r.startswith("OK"): + d = open(out, "rb").read() + magic, n, nx, ny, ne = struct.unpack("<5i", d[:20]) + import array + a = array.array("f"); a.frombytes(d[20:]) + print(" hdr", hex(magic), n, nx, ny, ne, "floats", len(a), "mean %.5f" % (sum(a) / len(a)), "first", [round(x, 4) for x in a[:6]]) +p.stdin.write("QUIT\n"); p.stdin.flush(); p.wait() diff --git a/tools/qwen35/q36_vision_cmp.py b/tools/qwen35/q36_vision_cmp.py new file mode 100644 index 00000000..2101f451 --- /dev/null +++ b/tools/qwen35/q36_vision_cmp.py @@ -0,0 +1,131 @@ +"""vcmp.py - the picture gate: strata-q36 against llama.cpp (mtmd) on the same GGUF + mmproj, same pictures. + +For each (picture, question): llama.cpp HIP (q36_mtmd_dump, encoder on the CPU like strata-vision's) gives the prompt's +chunks, its greedy answer and every step's full logits; the encoder file of strata-vision (venc.py) is laid over the same +ids; strata-q36 (--tokens ids --emb file --force llama's greedy ids) gives its logits on the same sequence. Reported: +the answer text agreement, the first token's logits (top-1/top-2 both, max |diff| over the top-5), the teacher-forced +mean KL(P_llama || Q_strata) and top-1 agreement over the steps, and - the floor - the same numbers for llama.cpp's CPU +backend against llama.cpp HIP. + + python q36_vision_cmp.py --dump BIN --q36 BIN --vision BIN --model GGUF --mmproj F --out DIR --pic shapes.png --pic code4217.png + [--lock "flock ..."] [--n 24] [--q36-args "--vision --max-context 4096"] +""" +from pathlib import Path +import argparse, json, os, shlex, struct, subprocess, sys +import numpy as np + +V = 248320 +QUESTIONS = { + "shapes.png": ["What text is written in the image? Answer with the text only.", + "List every shape in the image with its colour, from left to right. One short line each."], + "code4217.png": ["What text is written in the image? Answer with the text only.", + "Describe the shapes in the image with their colours and positions, one short line each."], +} +TEMPLATE = "<|im_start|>user\n<__media__>{q}<|im_end|>\n<|im_start|>assistant\n\n\n\n\n" +PAD = 248056 + + +def run(cmd, lock, log, env=None): + full = (shlex.split(lock) if lock else []) + cmd + e = dict(os.environ) + e.update(env or {}) + r = subprocess.run(full, capture_output=True, text=True, timeout=3600, env=e) + open(log, "w").write(r.stdout + "\n--- stderr ---\n" + r.stderr) + if r.returncode != 0: + raise SystemExit("%s failed (rc %d), see %s" % (cmd[0], r.returncode, log)) + return r.stdout + + +def parse_dump(out): + chunks, gen, first = [], [], None + for l in out.splitlines(): + if l.startswith("text:"): + chunks.append(("text", [int(x) for x in l.split(":", 1)[1].split()])) + elif l.startswith("image:"): + chunks.append(("image", int(l.split()[1]))) + elif l.startswith("gen:"): + gen = [int(x) for x in l.split(":", 1)[1].split()] + elif l.startswith("first:"): + first = l + return chunks, gen, first + + +def log_softmax(x): + x = x.astype(np.float64) + m = x.max(axis=1, keepdims=True) + return x - m - np.log(np.exp(x - m).sum(axis=1, keepdims=True)) + + +def kl_stats(p_logits, q_logits): + n = min(len(p_logits), len(q_logits)) + lp, lq = log_softmax(p_logits[:n]), log_softmax(q_logits[:n]) + kl = (np.exp(lp) * (lp - lq)).sum(axis=1) + top1 = (p_logits[:n].argmax(axis=1) == q_logits[:n].argmax(axis=1)) + return kl, top1 + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--dump", required=True) + ap.add_argument("--q36", required=True) + ap.add_argument("--vision", required=True) + ap.add_argument("--venc", default=str(Path(__file__).resolve().parent / "q36_venc.py")) + ap.add_argument("--model", required=True) + ap.add_argument("--mmproj", required=True) + ap.add_argument("--out", required=True) + ap.add_argument("--pic", action="append", required=True) + ap.add_argument("--lock", default="") + ap.add_argument("--n", type=int, default=24) + ap.add_argument("--q36-args", default="--vision --max-context 4096") + ap.add_argument("--floor", action="store_true", help="also llama.cpp CPU (ngl 0) vs HIP") + a = ap.parse_args() + os.makedirs(a.out, exist_ok=True) + rows = [] + for pic in a.pic: + name = os.path.basename(pic) + # the encoder's file (strata-vision, CPU) + run([sys.executable, a.venc, a.vision, a.mmproj, a.model, pic], "", os.path.join(a.out, name + ".venc.log")) + emb = pic + ".sve" + for qi, q in enumerate(QUESTIONS.get(name, ["Describe this image."])): + tag = "%s.q%d" % (name, qi) + prompt = TEMPLATE.format(q=q) + ref_log = os.path.join(a.out, tag + ".llama.log") + logit_f = os.path.join(a.out, tag + ".llama.logits") + out = run([a.dump, "--model", a.model, "--mmproj", a.mmproj, "--image", pic, "--prompt", prompt, "--n", str(a.n), + "--dump-full-logits", logit_f, "--mm-cpu", "1", "--max-tokens", "1024"], a.lock, ref_log) + chunks, gen, first = parse_dump(out) + ids = [] + for kind, v in chunks: + ids += v if kind == "text" else [PAD] * v + hdr = struct.unpack("<5i", open(emb, "rb").read(20)) + assert hdr[1] == sum(v for k, v in chunks if k == "image"), "the encoders disagree on the token count %s vs %s" % (hdr, chunks) + q_logit_f = os.path.join(a.out, tag + ".q36.logits") + qout = run([a.q36, "--model", a.model, "--tokens", ",".join(map(str, ids)), "--emb", emb, "--n", str(a.n), + "--force", ",".join(map(str, gen[:-1])), "--dump-full-logits", q_logit_f, *shlex.split(a.q36_args)], + a.lock, os.path.join(a.out, tag + ".q36.log")) + qgen = [int(x) for x in [l for l in qout.splitlines() if l.startswith("gen:")][0].split(":", 1)[1].split()] + P = np.fromfile(logit_f, dtype=np.float32).reshape(-1, V) + Q = np.fromfile(q_logit_f, dtype=np.float32).reshape(-1, V) + kl, top1 = kl_stats(P, Q) + d5 = np.abs(np.sort(P[0])[-5:] - np.sort(Q[0])[-5:]).max() + row = {"tag": tag, "prompt_tokens": len(ids), "llama_gen": gen, "strata_gen_forced": qgen, + "first_top1_same": bool(P[0].argmax() == Q[0].argmax()), "first_max_top5_diff": float(d5), + "kl_mean": float(kl.mean()), "kl_first": float(kl[0]), "top1": float(top1.mean()), "steps": int(len(kl))} + if a.floor: + fl = os.path.join(a.out, tag + ".cpu.logits") + run([a.dump, "--model", a.model, "--mmproj", a.mmproj, "--image", pic, "--prompt", prompt, "--n", str(a.n), + "--dump-full-logits", fl, "--mm-cpu", "1", "--max-tokens", "1024", "--ngl", "0", "--force", + ",".join(map(str, gen[:-1]))], "", os.path.join(a.out, tag + ".cpu.log")) + C = np.fromfile(fl, dtype=np.float32).reshape(-1, V) + klc, t1c = kl_stats(P, C) + row.update({"floor_kl_mean": float(klc.mean()), "floor_kl_first": float(klc[0]), "floor_top1": float(t1c.mean()), + "floor_first_max_top5_diff": float(np.abs(np.sort(P[0])[-5:] - np.sort(C[0])[-5:]).max())}) + rows.append(row) + print(json.dumps({k: v for k, v in row.items() if k not in ("llama_gen", "strata_gen_forced")}), flush=True) + print(" llama :", gen[:16], flush=True) + print(" strata :", qgen[:16], "(teacher-forced on llama's ids: its own greedy at each step)", flush=True) + json.dump(rows, open(os.path.join(a.out, "summary.json"), "w"), indent=1) + + +if __name__ == "__main__": + main() diff --git a/tools/qwen35/q36_vision_proto.py b/tools/qwen35/q36_vision_proto.py new file mode 100644 index 00000000..89624e71 --- /dev/null +++ b/tools/qwen35/q36_vision_proto.py @@ -0,0 +1,91 @@ +"""vision_proto.py - pictures over the engine protocol (GENI / BGENI), no server: the ids come from llama.cpp's own tokenizer +output (vc1/*.llama.log of vcmp.py), the rows from strata-vision (.sve). + + python q36_vision_proto.py --exe E --args "--model M --max-context 8192 --vision --batch 4" --vc DIR --pics DIR + +Checks: 1. a solo GENI answers like llama.cpp's greedy (the first 24 tokens); 2. two pictures and a text prompt decoding +together (BGENI / BGEN) give each the tokens of its solo run; 3. the conversation cache: the same request again and a +longer one (the first, its answer and more text) reuse the held state, a different picture does not; a text request after +a picture request is not disturbed (the rotary offset is back at 0).""" +from pathlib import Path +import argparse, json, os, shlex, sys +sys.path.insert(0, __file__.rsplit("/", 1)[0] if "/" in __file__ else ".") +from q36_harness import Eng, load_prompts + +PAD = 248056 + + +def case(vc, pics, name, q): + log = open(os.path.join(vc, "%s.q%d.llama.log" % (name, q))).read() + ids, gen = [], [] + for l in log.splitlines(): + if l.startswith("text:"): + ids += [int(x) for x in l.split(":", 1)[1].split()] + elif l.startswith("image:"): + ids += [PAD] * int(l.split()[1]) + elif l.startswith("gen:"): + gen = [int(x) for x in l.split(":", 1)[1].split()] + return ids, gen, os.path.join(pics, name + ".sve") + + +ap = argparse.ArgumentParser() +ap.add_argument("--exe", required=True) +ap.add_argument("--args", default="") +ap.add_argument("--vc", required=True) +ap.add_argument("--pics", required=True) +ap.add_argument("--n", type=int, default=24) +ap.add_argument("--log", default=None) +a = ap.parse_args() +eng = Eng(a.exe, shlex.split(a.args), log=a.log) +print("ready", eng.ready, eng.info, flush=True) +ok = True +S0, G0, E0 = case(a.vc, a.pics, "shapes.png", 0) +S1, G1, E1 = case(a.vc, a.pics, "shapes.png", 1) +C0, GC0, EC0 = case(a.vc, a.pics, "code4217.png", 0) +C1, GC1, EC1 = case(a.vc, a.pics, "code4217.png", 1) + +# 1. solo vs llama.cpp's greedy +solo = {} +for tag, (ids, gen, emb) in {"shapes.q0": (S0, G0, E0), "shapes.q1": (S1, G1, E1), "code.q0": (C0, GC0, EC0), + "code.q1": (C1, GC1, EC1)}.items(): + toks, done, ttft, wall = eng.solo(ids, a.n, emb=emb) + solo[tag] = toks + k = next((i for i in range(min(len(toks), len(gen))) if toks[i] != gen[i]), None) + print("solo %-10s %d tokens, vs llama.cpp greedy: %s | %s" % (tag, len(toks), "same %d tokens" % len(toks) if k is None else "first difference at %d" % k, done[:60]), flush=True) + +# 2. batch: two pictures + a text prompt +text = load_prompts(str(Path(__file__).resolve().parent / "parity_prompts.ids"))[0] +t_toks, _, _, _ = eng.solo(text, a.n) +reqs = [{"ids": S1, "n": a.n, "slot": 0, "emb": E1}, {"ids": C1, "n": a.n, "slot": 1, "emb": EC1}, + {"ids": text, "n": a.n, "slot": 2}] +r = eng.batch(reqs) +eq = [r["tokens"][0] == solo["shapes.q1"], r["tokens"][1] == solo["code.q1"], r["tokens"][2] == t_toks] +print("batch (2 pictures + 1 text): identical to solo %s" % eq, flush=True) +ok &= all(eq) +# slot reuse: the same again into other slots +r2 = eng.batch([{"ids": C1, "n": a.n, "slot": 3, "emb": EC1}, {"ids": S1, "n": a.n, "slot": 0, "emb": E1}]) +eq2 = [r2["tokens"][0] == solo["code.q1"], r2["tokens"][1] == solo["shapes.q1"]] +print("batch again (slot 3 new, slot 0 held): identical %s" % eq2, flush=True) +ok &= all(eq2) + +# 3. the conversation cache (solo path) +def reused(done): + return int(done.split()[8]) + +toks1, done1, _, _ = eng.solo(S0, 16, emb=E0) +toks1b, done1b, _, _ = eng.solo(S0, 16, emb=E0) +print("same request again (a state that has moved past the prompt cannot step back: no reuse): reused %d of %d, tokens %s" % (reused(done1b), len(S0), "same" if toks1b == toks1 else "DIFFERENT"), flush=True) +ok &= toks1b == toks1 +longer = S0 + toks1 + text[:12] +toks2, done2, _, _ = eng.solo(longer, 16, emb=E0) +print("longer request (picture + answer + more): reused %d of %d" % (reused(done2), len(longer)), flush=True) +ok &= reused(done2) >= len(S0) +toks3, done3, _, _ = eng.solo(C0, 16, emb=EC0) # a different picture +print("a different picture: reused %d" % reused(done3), "tokens vs its solo: %s" % ("same" if toks3 == solo["code.q0"][:16] else "DIFFERENT"), flush=True) +ok &= toks3 == solo["code.q0"][:16] +t2, done4, _, _ = eng.solo(text, a.n) +print("a text request after pictures: tokens vs the text solo: %s" % ("identical" if t2 == t_toks else "DIFFERENT"), flush=True) +ok &= t2 == t_toks +eng.close() +print("GATE", "PASS" if ok else "FAIL") +sys.exit(0 if ok else 1) diff --git a/tools/qwen35/q36_vision_serve.py b/tools/qwen35/q36_vision_serve.py new file mode 100644 index 00000000..5bb59c1e --- /dev/null +++ b/tools/qwen35/q36_vision_serve.py @@ -0,0 +1,20 @@ +"""vq.py PORT IMG [IMG2] : the picture questions through the server (chat completions, image_url data URL), greedy, +thinking off. Prints each answer and the usage.""" +import base64, json, sys, time, urllib.request +port, img = sys.argv[1], sys.argv[2] +QS = {"code4217.png": ["What text is written in the image? Answer with the text only.", + "Describe the shapes in the image with their colours and positions, one short line each."], + "shapes.png": ["What text is written in the image? Answer with the text only.", + "List every shape in the image with its colour, from left to right. One short line each."]} +name = img.rsplit("/", 1)[-1] +b64 = base64.b64encode(open(img, "rb").read()).decode() +for q in QS.get(name, ["Describe this image."]): + body = {"model": "x", "max_tokens": 120, "temperature": 0, "chat_template_kwargs": {"enable_thinking": False}, + "messages": [{"role": "user", "content": [{"type": "image_url", "image_url": {"url": "data:image/png;base64," + b64}}, + {"type": "text", "text": q}]}]} + t0 = time.time() + r = json.loads(urllib.request.urlopen(urllib.request.Request(f"http://127.0.0.1:{port}/v1/chat/completions", + json.dumps(body).encode(), {"Content-Type": "application/json"}), timeout=900).read()) + print("Q:", q) + print("A:", repr(r["choices"][0]["message"]["content"]), "%.1fs" % (time.time() - t0)) + print("usage", r.get("usage"), flush=True) From 3921f57eea8afea4c89dead8c244970568eed8b1 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Wed, 14 Oct 2026 01:47:11 +0200 Subject: [PATCH 5/8] qwen35: a conversation's held tokens match its state exactly (no drafts past the end of an answer or a stop), reads give the decoding slots windows, pictures x2 check spec_step takes no draft past an end-of-answer token or past the room max_new leaves, and a stop asked for before the state moves keeps only x: every token emitted but the last is in the state, so a conversation that continues from the held tokens (the server's solo -> slot -> solo hand-over, a chat's next turn) neither misses nor reads a token twice. Before, an answer ending inside accepted drafts left the state ahead of the held tokens (found by tools/qwen35/q36_serve_handoff.py: the first request's text now equals its run alone). STRATA_Q36_READ_WINDOWS sets the decode windows of the other slots between two chunks of a prompt read (default 1). The mtmd dump takes several pictures; the engine logs each request's reuse; a 1,024-token test picture. --- docs/QWEN36.md | 15 ++++- src/qwen35/q36_engine.cu | 52 ++++++++++++++---- tools/qwen35/make_big_picture.py | 27 +++++++++ tools/qwen35/pictures/big1024.png | Bin 0 -> 47955 bytes tools/qwen35/q36_interleave_probe.py | 79 +++++++++++++++++++++++++++ tools/qwen35/q36_mtmd_dump.cpp | 22 +++++--- tools/qwen35/q36_par_bench.py | 15 +++-- tools/qwen35/q36_serve_handoff.py | 46 ++++++++++++++++ tools/qwen35/q36_vision_cmp.py | 35 ++++++++---- 9 files changed, 256 insertions(+), 35 deletions(-) create mode 100644 tools/qwen35/make_big_picture.py create mode 100644 tools/qwen35/pictures/big1024.png create mode 100644 tools/qwen35/q36_interleave_probe.py create mode 100644 tools/qwen35/q36_serve_handoff.py diff --git a/docs/QWEN36.md b/docs/QWEN36.md index 76efb57d..607d08e3 100644 --- a/docs/QWEN36.md +++ b/docs/QWEN36.md @@ -20,7 +20,7 @@ and `--vision-tokens N` work as there. A card under 16 GB is recommended the CPU | Encoder | Time per picture (640x400 = 260 tokens / 800x450 = 350 tokens) | VRAM | | --- | --- | --- | -| GPU, RTX 3060 | 0.10 s / 0.15 s | 1.18 GiB at up to 1,024 tokens (1.34 GiB at 2,048) | +| GPU, RTX 3060 | 0.10 s / 0.15 s | 1,179 MiB at up to 1,024 tokens (1,337 MiB at 2,048), CUDA context included | | CPU, 32 threads (R9700 box) | 0.9 s / 1.1 s | none | | CPU, 10 threads (3060 box) | 1.6 s / 2.1 s | none | @@ -105,3 +105,16 @@ solo run there too, with and without `--batch-mtp`. - A slot that stopped being alone goes back to the solo path only through the server's own hand-over; the MTP block's cache has holes for the tokens a slot decoded in batch windows (the drafts of a later solo stretch are a little worse; the text is not affected). - Intel Arc (SYCL) does not run this family. + +## Testing + +The gates are in `tools/qwen35/` and talk to the engine through its serve protocol (no server needed); run them under the box's GPU lock: + +- `q36_solo_gate.py` + `q36_cmp_gate.py`: the 10 parity prompts x 128 greedy tokens through `GEN`, compared with another build's. +- `q36_batch_gate.py --slots N --waves --long 2500`: every slot's tokens equal its solo tokens, slots reused, a long prompt read beside + decoding slots. `q36_proto_edge.py`: `max_new` 1, `BSTOP`, a busy slot, `STOP` during a prompt read, held-state reuse, sampled requests, + the context's end. `q36_interleave_probe.py`: what the decoding slots see while a long prompt is read. +- `q36_vision_cmp.py` (with `q36_mtmd_dump.cpp` built against llama.cpp): the picture comparison above; `q36_vision_proto.py`: pictures through + `GENI` / `BGENI` (solo, in a batch, the conversation cache); `q36_vision_serve.py` and `q36_serve_par.py` / `q36_serve_handoff.py`: + the same through the server. +- `q36_par_bench.py`: the aggregate-throughput A/B against `llama-server -np N`. diff --git a/src/qwen35/q36_engine.cu b/src/qwen35/q36_engine.cu index ff532355..215f0194 100644 --- a/src/qwen35/q36_engine.cu +++ b/src/qwen35/q36_engine.cu @@ -2285,7 +2285,13 @@ struct Engine { /// tokens of the rows the block must redo first (the drafts the last window accepted, seeded by hmain rows /// 0 .. fix.size() - 1 of that window). Drafts d1 .. dD, then the window [x, d1 .. dD] through the main model; /// returns the accepted count a and writes the picks of rows 0 .. a (row a's pick is the token after them). - int spec_step(int x_tok, const std::vector& fix, int D, std::vector& drafts, int32_t* picks) { + /// `max_a`: at most that many drafts are taken (the answer has room for max_a + 1 more tokens, the last of which is + /// not fed, as in plain decoding); and no draft past an end-of-answer token is taken (that token is the next one the + /// caller emits). So the state ends exactly where plain decoding would leave it. + /// `cancel`: a stop asked for before the state moves keeps only x (the caller then emits no draft: every token emitted but + /// the last is in the state, so a conversation that continues from the held tokens loses and repeats nothing). + int spec_step(int x_tok, const std::vector& fix, int D, std::vector& drafts, int32_t* picks, + int max_a = 1 << 20, const std::atomic* cancel = nullptr) { const int N = (int) m->g.n_embd; if (main_hybrid) D = std::min(D, (int) (kRebalanceEvery - pos % kRebalanceEvery) - 1); const int T0 = (int) fix.size() + 1; // the redo rows and the row of x @@ -2336,6 +2342,10 @@ struct Engine { CK(cudaStreamSynchronize(st)); int a = 0; while (a < D && hpin[2 + a] == drafts[(size_t) a]) ++a; + a = std::min(a, max_a); + if (cancel != nullptr && cancel->load()) a = 0; + for (int i = 0; i < a; ++i) + if (drafts[(size_t) i] == 248044 || drafts[(size_t) i] == 248046) { a = i; break; } // (<|endoftext|>, <|im_end|>) for (int i = 0; i <= a; ++i) picks[i] = hpin[2 + i]; commit(a + 1); CK(cudaMemcpyAsync(hlast, hmain + (size_t) a * N, (size_t) N * 4, cudaMemcpyDeviceToDevice, st)); @@ -2765,8 +2775,13 @@ struct Serve { std::vector slots; int n_active = 0; std::vector lg; + // decode windows of the other slots between two chunks of a prompt read: STRATA_Q36_READ_WINDOWS (default 1; a chunk + // takes ~0.15 s at 512 tokens, a window ~0.012 s: more windows give the decoding slots more of the time a read takes) + int read_windows = 1; - explicit Serve(Engine& e) : E(e), slots((size_t) e.n_sess) {} + explicit Serve(Engine& e) : E(e), slots((size_t) e.n_sess) { + if (const char* v = std::getenv("STRATA_Q36_READ_WINDOWS")) read_windows = std::max(0, std::min(64, std::atoi(v))); + } /// BSTOP / BYIELD lines among the queued ones: applied now (a window is a moment away at most). void poll_control() { @@ -3122,8 +3137,13 @@ struct Serve { std::printf("PP %lld %lld %.0f %.1f\n", (long long) done, (long long) fresh, ms_since(t0), (double) done / std::max(1e-9, ms_since(t0) / 1000.0)); std::fflush(stdout); - if (n_active > 0 && done < fresh) window(); // the slots decoding go on between a read's chunks (the - else poll_control(); // last chunk's logits must stay for the first token) + if (n_active > 0 && done < fresh) { + poll_control(); + // the slots decoding go on between a read's chunks (the last chunk's + for (int w = 0; w < read_windows && n_active > 0; ++w) window(); // logits must stay for the first token) + } else { + poll_control(); + } if (stop.load() && done < fresh) { cancelled = true; return false; } return true; }); @@ -3186,10 +3206,12 @@ struct Serve { } std::printf("BADM %d %d\n", slot, cont ? 1 : 0); std::fflush(stdout); + std::fprintf(stderr, "strata batch: slot %d takes a prompt of %zu tokens = %zu reused + %lld read in %.0f ms (%.1f " + "tok/s)%s\n", slot, ids.size(), reuse, (long long) fresh, prompt_ms, + prompt_ms > 0 ? 1000.0 * (double) fresh / prompt_ms : 0.0, cont ? "" : ", done at once"); return; } - bool done = false; - while (!done) { + for (;;) { if (smp.needs_logits()) { E.host_logits(lg); nx = sample(lg, smp, hist, rng); @@ -3207,15 +3229,21 @@ struct Serve { if (!emit(nx)) break; if (n_active > 0) window(); if (spec && n_active == 0 && E.pos + E.mtp_d + 1 <= E.ctx) { - const int a = E.spec_step(nx, fix, E.mtp_d, drafts, picks); + const int a = E.spec_step(nx, fix, E.mtp_d, drafts, picks, (int) std::min(max_new - produced - 1, 1 << 20), &stop); offered += E.mtp_d; accepted += a; + // the state now holds x and the accepted drafts - spec_step took none past an end-of-answer token or past + // the room max_new leaves, so the state ends where plain decoding leaves it (the last token emitted is not + // fed) and a later request that continues this conversation neither misses nor reads a token twice ss.live.push_back(nx); + for (int i = 0; i < a; ++i) ss.live.push_back(drafts[(size_t) i]); fix.assign(drafts.begin(), drafts.begin() + a); - for (int i = 0; i < a; ++i) { - ss.live.push_back(drafts[(size_t) i]); - if (!emit(drafts[(size_t) i])) { done = true; break; } + for (int i = 0; i < a; ++i) { // (all of them: they are in the state; a stop is seen at the next token) + std::printf("T %d\n", drafts[(size_t) i]); + ++produced; + hist.push_back(drafts[(size_t) i]); } + std::fflush(stdout); nx = picks[a]; continue; } @@ -3231,6 +3259,10 @@ struct Serve { std::printf("DONE %lld %zu %.1f %.1f %s %lld %lld %zu 0 0 0 0 0.0 %lld 0\n", produced, ids.size(), prompt_ms, decode_ms, finish, accepted, offered, reuse, (long long) fresh); std::fflush(stdout); + std::fprintf(stderr, "strata serve: session %d: prompt %zu tokens = %zu reused + %lld read in %.0f ms (%.1f tok/s), " + "%lld generated in %.0f ms (%.1f tok/s), drafts accepted %lld of %lld (%s)\n", s, ids.size(), reuse, + (long long) fresh, prompt_ms, prompt_ms > 0 ? 1000.0 * (double) fresh / prompt_ms : 0.0, produced, + decode_ms, decode_ms > 0 ? 1000.0 * (double) produced / decode_ms : 0.0, accepted, offered, finish); } int run() { diff --git a/tools/qwen35/make_big_picture.py b/tools/qwen35/make_big_picture.py new file mode 100644 index 00000000..98ef33bf --- /dev/null +++ b/tools/qwen35/make_big_picture.py @@ -0,0 +1,27 @@ +"""make_big_picture.py OUT : a 1024x1024 test picture (about 1,024 image tokens, a prompt that spans several chunks): a heading, a +few lines of small text and coloured shapes on white.""" +import sys +from PIL import Image, ImageDraw, ImageFont + +im = Image.new("RGB", (1024, 1024), "white") +d = ImageDraw.Draw(im) + + +def font(size, bold=True): + for f in (("arialbd.ttf" if bold else "arial.ttf"), "C:/Windows/Fonts/arialbd.ttf", + "/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf", "/usr/share/fonts/truetype/liberation/LiberationSans-Bold.ttf"): + try: + return ImageFont.truetype(f, size) + except OSError: + pass + return ImageFont.load_default() + + +d.text((90, 60), "INVOICE 20261014", fill="black", font=font(96)) +d.text((90, 200), "Total due: 1337 EUR", fill=(20, 20, 160), font=font(64)) +for i, line in enumerate(["Item 1 widgets x 12", "Item 2 gears x 7", "Item 3 springs x 30"]): + d.text((90, 320 + 70 * i), line, fill="black", font=font(48, False)) +d.ellipse([560, 600, 960, 1000], fill=(30, 160, 60)) +d.rectangle([90, 640, 430, 980], fill=(220, 30, 30)) +im.save(sys.argv[1]) +print("wrote", sys.argv[1]) diff --git a/tools/qwen35/pictures/big1024.png b/tools/qwen35/pictures/big1024.png new file mode 100644 index 0000000000000000000000000000000000000000..b58d7023c31cc1a3fcea972ea584e5c96186935e GIT binary patch literal 47955 zcmeFZWmMH&*EN2?q*Pi$x|TF6mT3l;%*9M6 z`+3Lse|W#X-yVjSaydBX{Px~!%{Av-Yx_lBRvZVD6cd3!;7CfmP(&cE!?)KFx6$E` zZSUGa1fqsi^2KvymxT4nTgv#OWKSRG@&|k{;23cqE=L?xACwms)H!<} zOu09Od}lg9|LlYAbR*pv{Wy8D_R@6;r`>jdasHIg{lEwr&mYs?JYl*xwS>Bkj&=h+ z2!R-TEp%FBEI{pKz1)ic4D=5@6H{OLpVzdr&S@xS|W6%GIIgW-i7 zgytVhNlD32O5u>;;Na8V7!KVM_$n=Ru(wC;?gj@1b)2{M_xF#Ej<&S43=Nelq`kr+ zee!2`IIFC`(q>vzOl-Q&o%k|&Yr4Vol97>7TvxY2yULz{fx*eisj+EcWo2b!<4u*l zv127E0+F)*592zzW99n+9_xvtrDShp_G!rSy=@I1$c+Z z*@+tGLdUhg8AN29Ms4A=;!;9ei;G0W#Ns~+KY#wLS#GY-(Y&;4Wo4zLs3?J1`L>US zj_w8ZDLWI>kAvh}cPVPUFLgeV1_cF?@>nh}Ee*pH$8lRIk~*SyrW6%zA8d?g$t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ZQ{I?a{NpnCmfNtgUI5Yv_si z2wlZg(i*x7YZ`~-0AChFu% 1), default=0.0) +mx0 = max((max(gaps(v[-60:])) for v in base.values() if len(v) > 2), default=0.0) +print("a prompt of %d tokens read in %.2f s (%d chunks, %.0f tok/s) beside %d decoding slots" % (len(longids), read_s, len(pp), + len(longids) / read_s, a.slots)) +print("the %d decoding slots produced %d tokens during the read (%.1f tok/s together); longest pause between two tokens of a slot %.0f ms" + " (while only decoding: %.0f ms)" % (a.slots, n_during, n_during / read_s, 1000 * mx, 1000 * mx0)) +for s in range(a.slots): + eng.send("BSTOP %d" % s) +eng.send("BSTOP %d" % a.slots) +time.sleep(1.0) +eng.close() diff --git a/tools/qwen35/q36_mtmd_dump.cpp b/tools/qwen35/q36_mtmd_dump.cpp index 55519bc3..af208b27 100644 --- a/tools/qwen35/q36_mtmd_dump.cpp +++ b/tools/qwen35/q36_mtmd_dump.cpp @@ -6,7 +6,7 @@ // Built against a llama.cpp checkout with its mtmd library (not part of Strata's build): // g++ -O2 -std=c++17 q36_mtmd_dump.cpp -I/include -I/ggml/include -I/tools/mtmd -L/build/bin // -lllama -lmtmd -lggml -lggml-base -Wl,-rpath,/build/bin -o q36_mtmd_dump -// Usage: q36_mtmd_dump --model GGUF --mmproj F --image F --prompt TEXT [--n 32] [--ngl 99] [--max-tokens N] [--mm-cpu 1] +// Usage: q36_mtmd_dump --model GGUF --mmproj F --image F [--image F2 ...] --prompt TEXT [--n 32] [--ngl 99] [--max-tokens N] [--mm-cpu 1] // [--dump-full-logits F] [--force ID,ID,...] // TEXT holds one <__media__> marker where the picture goes (the chat template's user turn); it is tokenized with // special tokens parsed and no BOS. --force feeds that continuation instead of the greedy ids (teacher forcing). @@ -33,13 +33,14 @@ static std::vector parse_ids(const std::string& s) { } int main(int argc, char** argv) { - std::string model, mmproj, image, prompt, dump_full, force; + std::string model, mmproj, prompt, dump_full, force; + std::vector images; int n_gen = 32, ngl = 99, max_tokens = 0, mm_cpu = 0; for (int i = 1; i + 1 < argc; i += 2) { const std::string a = argv[i], v = argv[i + 1]; if (a == "--model") model = v; else if (a == "--mmproj") mmproj = v; - else if (a == "--image") image = v; + else if (a == "--image") images.push_back(v); // repeat for several pictures (one <__media__> each) else if (a == "--prompt") prompt = v; else if (a == "--n") n_gen = std::atoi(v.c_str()); else if (a == "--ngl") ngl = std::atoi(v.c_str()); @@ -68,12 +69,17 @@ int main(int argc, char** argv) { if (max_tokens > 0) mcp.image_max_tokens = max_tokens; mtmd_context* mctx = mtmd_init_from_file(mmproj.c_str(), mdl, mcp); if (!mctx) { std::fprintf(stderr, "cannot load %s\n", mmproj.c_str()); return 1; } - mtmd_helper_bitmap_wrapper bw = mtmd_helper_bitmap_init_from_file(mctx, image.c_str(), false, mtmd_helper_init_opt_default()); - if (!bw.bitmap) { std::fprintf(stderr, "cannot read %s\n", image.c_str()); return 1; } + std::vector bws; + std::vector bms; + for (const std::string& image : images) { + mtmd_helper_bitmap_wrapper bw = mtmd_helper_bitmap_init_from_file(mctx, image.c_str(), false, mtmd_helper_init_opt_default()); + if (!bw.bitmap) { std::fprintf(stderr, "cannot read %s\n", image.c_str()); return 1; } + bws.push_back(bw); + bms.push_back(bw.bitmap); + } mtmd_input_chunks* chunks = mtmd_input_chunks_init(); mtmd_input_text txt{prompt.c_str(), prompt.size(), false, true}; - const mtmd_bitmap* bms[1] = {bw.bitmap}; - if (mtmd_tokenize(mctx, chunks, &txt, bms, 1) != 0) { std::fprintf(stderr, "tokenize failed\n"); return 1; } + if (mtmd_tokenize(mctx, chunks, &txt, bms.data(), bms.size()) != 0) { std::fprintf(stderr, "tokenize failed\n"); return 1; } const size_t nc = mtmd_input_chunks_size(chunks); llama_pos n_past = 0; for (size_t c = 0; c < nc; ++c) { @@ -123,7 +129,7 @@ int main(int argc, char** argv) { std::printf("\n"); if (ff) std::fclose(ff); mtmd_input_chunks_free(chunks); - mtmd_bitmap_free(bw.bitmap); + for (auto& bw : bws) mtmd_bitmap_free(bw.bitmap); mtmd_free(mctx); llama_free(ctx); llama_model_free(mdl); diff --git a/tools/qwen35/q36_par_bench.py b/tools/qwen35/q36_par_bench.py index 7d902d25..f9718114 100644 --- a/tools/qwen35/q36_par_bench.py +++ b/tools/qwen35/q36_par_bench.py @@ -21,11 +21,16 @@ def strata(a): out = open(a.out, "a") for n in [int(x) for x in a.ns.split(",")]: for rnd in range(a.rounds): - reqs = [{"ids": prompts[ORDER[i]], "n": a.n, "slot": i} for i in range(n)] - r = eng.batch(reqs) - tot = sum(len(t) for t in r["tokens"]) - row = {"engine": "strata", "n": n, "round": rnd, "tokens": tot, "wall": r["wall"], "tok_s": tot / r["wall"], - "tail_tok_s": r["tail_tok_s"]} + if n == 1 and not eng.info.get("batch_slots"): # an engine without slots: the request alone (GEN) + toks, done, ttft, wall = eng.solo(prompts[ORDER[0]], a.n) + row = {"engine": "strata", "n": 1, "round": rnd, "tokens": len(toks), "wall": wall, + "tok_s": len(toks) / wall, "tail_tok_s": len(toks) / max(1e-9, wall - (ttft or 0))} + else: + reqs = [{"ids": prompts[ORDER[i]], "n": a.n, "slot": i} for i in range(n)] + r = eng.batch(reqs) + tot = sum(len(t) for t in r["tokens"]) + row = {"engine": "strata", "n": n, "round": rnd, "tokens": tot, "wall": r["wall"], "tok_s": tot / r["wall"], + "tail_tok_s": r["tail_tok_s"]} print(json.dumps(row), flush=True) out.write(json.dumps(row) + "\n") out.flush() diff --git a/tools/qwen35/q36_serve_handoff.py b/tools/qwen35/q36_serve_handoff.py new file mode 100644 index 00000000..96b60ce0 --- /dev/null +++ b/tools/qwen35/q36_serve_handoff.py @@ -0,0 +1,46 @@ +"""q36_serve_handoff.py PORT [--n 300] : a request that runs alone (the solo path, with MTP drafts), another one arrives while it +runs (the server stops it and continues it in a batch slot from its held state), the second one ends (the first is alone again and +goes back to the solo path): the first request's text must be the text of the same request run entirely alone. Greedy, thinking +off, every expert in VRAM (in the hybrid mode a different window mix can round differently: see docs/QWEN36.md). + + python tools/qwen35/q36_serve_handoff.py 8199 [--n 300] [--delay 1.0] +""" +import argparse, json, sys, threading, time, urllib.request + +A = "Write a long, detailed story about a lighthouse keeper who finds a message in a bottle and follows it across the sea." +B = "List the first twenty prime numbers and explain how you found them." + + +def ask(port, text, n, out, key): + body = {"model": "x", "max_tokens": n, "temperature": 0, "chat_template_kwargs": {"enable_thinking": False}, + "messages": [{"role": "user", "content": text}]} + t0 = time.time() + r = json.loads(urllib.request.urlopen(urllib.request.Request(f"http://127.0.0.1:{port}/v1/chat/completions", + json.dumps(body).encode(), {"Content-Type": "application/json"}), timeout=900).read()) + out[key] = (r["choices"][0]["message"]["content"], r["usage"]["completion_tokens"], time.time() - t0) + + +ap = argparse.ArgumentParser() +ap.add_argument("port", type=int) +ap.add_argument("--n", type=int, default=300) +ap.add_argument("--delay", type=float, default=1.0) +a = ap.parse_args() +alone = {} +ask(a.port, A, a.n, alone, "A") +ask(a.port, B, 60, alone, "B") +for rnd in range(2): + mix = {} + ta = threading.Thread(target=ask, args=(a.port, A, a.n, mix, "A")) + tb = threading.Thread(target=lambda: (time.sleep(a.delay), ask(a.port, B, 60, mix, "B"))) + ta.start() + tb.start() + ta.join() + tb.join() + ea, eb = mix["A"][0] == alone["A"][0], mix["B"][0] == alone["B"][0] + print("round %d: A %d tokens in %.1fs, B %d tokens in %.1fs; A equals its run alone: %s; B equals its run alone: %s" + % (rnd, mix["A"][1], mix["A"][2], mix["B"][1], mix["B"][2], ea, eb), flush=True) + if not (ea and eb): + x, y = mix["A"][0], alone["A"][0] + k = next((i for i in range(min(len(x), len(y))) if x[i] != y[i]), min(len(x), len(y))) + print(" A first differs from its run alone at character %d of %d: %r vs %r" % (k, len(y), x[max(0, k - 20):k + 30], + y[max(0, k - 20):k + 30])) diff --git a/tools/qwen35/q36_vision_cmp.py b/tools/qwen35/q36_vision_cmp.py index 2101f451..59c5a7e1 100644 --- a/tools/qwen35/q36_vision_cmp.py +++ b/tools/qwen35/q36_vision_cmp.py @@ -23,6 +23,9 @@ QUESTIONS = { } TEMPLATE = "<|im_start|>user\n<__media__>{q}<|im_end|>\n<|im_start|>assistant\n\n\n\n\n" PAD = 248056 +TEMPLATE_PAIR = ("<|im_start|>user\nPicture 1: <__media__>\nPicture 2: <__media__>\n{q}<|im_end|>\n<|im_start|>assistant\n" + "\n\n\n\n") +PAIR_QUESTIONS = ["What text is written in each of the two pictures? One short line for each."] def run(cmd, lock, log, env=None): @@ -73,7 +76,7 @@ def main(): ap.add_argument("--model", required=True) ap.add_argument("--mmproj", required=True) ap.add_argument("--out", required=True) - ap.add_argument("--pic", action="append", required=True) + ap.add_argument("--pic", action="append", required=True, help="a picture, or a+b for one request with two pictures") ap.add_argument("--lock", default="") ap.add_argument("--n", type=int, default=24) ap.add_argument("--q36-args", default="--vision --max-context 4096") @@ -81,24 +84,34 @@ def main(): a = ap.parse_args() os.makedirs(a.out, exist_ok=True) rows = [] - for pic in a.pic: - name = os.path.basename(pic) - # the encoder's file (strata-vision, CPU) - run([sys.executable, a.venc, a.vision, a.mmproj, a.model, pic], "", os.path.join(a.out, name + ".venc.log")) - emb = pic + ".sve" - for qi, q in enumerate(QUESTIONS.get(name, ["Describe this image."])): + for pic_spec in a.pic: + pics = pic_spec.split("+") # "a.png+b.png": one request with two pictures (one <__media__> each) + name = "+".join(os.path.basename(p) for p in pics) + # the encoder's file (strata-vision, CPU): one record per picture, in prompt order + run([sys.executable, a.venc, a.vision, a.mmproj, a.model, *pics], "", os.path.join(a.out, name + ".venc.log")) + emb = os.path.join(a.out, name + ".sve") + with open(emb, "wb") as f: + for p in pics: + f.write(open(p + ".sve", "rb").read()) + questions = QUESTIONS.get(name, ["Describe this image."] if len(pics) == 1 else PAIR_QUESTIONS) + for qi, q in enumerate(questions): tag = "%s.q%d" % (name, qi) - prompt = TEMPLATE.format(q=q) + prompt = TEMPLATE.format(q=q) if len(pics) == 1 else TEMPLATE_PAIR.format(q=q) ref_log = os.path.join(a.out, tag + ".llama.log") logit_f = os.path.join(a.out, tag + ".llama.logits") - out = run([a.dump, "--model", a.model, "--mmproj", a.mmproj, "--image", pic, "--prompt", prompt, "--n", str(a.n), + out = run([a.dump, "--model", a.model, "--mmproj", a.mmproj, *sum([["--image", p] for p in pics], []), + "--prompt", prompt, "--n", str(a.n), "--dump-full-logits", logit_f, "--mm-cpu", "1", "--max-tokens", "1024"], a.lock, ref_log) chunks, gen, first = parse_dump(out) ids = [] for kind, v in chunks: ids += v if kind == "text" else [PAD] * v - hdr = struct.unpack("<5i", open(emb, "rb").read(20)) - assert hdr[1] == sum(v for k, v in chunks if k == "image"), "the encoders disagree on the token count %s vs %s" % (hdr, chunks) + tot_rows, off, data = 0, 0, open(emb, "rb").read() + while off < len(data): # the records' row counts + h = struct.unpack("<5i", data[off:off + 20]) + tot_rows += h[1] + off += 20 + 4 * h[1] * h[4] + assert tot_rows == sum(v for k, v in chunks if k == "image"), "the encoders disagree on the token count %d vs %s" % (tot_rows, chunks) q_logit_f = os.path.join(a.out, tag + ".q36.logits") qout = run([a.q36, "--model", a.model, "--tokens", ",".join(map(str, ids)), "--emb", emb, "--n", str(a.n), "--force", ",".join(map(str, gen[:-1])), "--dump-full-logits", q_logit_f, *shlex.split(a.q36_args)], From a7027766ff7bf62ee6dc11bc55c70c4c6df2cf38 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Wed, 14 Oct 2026 01:54:21 +0200 Subject: [PATCH 6/8] docs/QWEN36.md: the long picture, two pictures, reads beside decoding slots, the hand-over; the picture comparison takes several pictures --- docs/QWEN36.md | 10 ++++++++-- tools/qwen35/q36_vision_cmp.py | 3 ++- 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/docs/QWEN36.md b/docs/QWEN36.md index 607d08e3..21bb641f 100644 --- a/docs/QWEN36.md +++ b/docs/QWEN36.md @@ -38,6 +38,8 @@ HIP run, the noise two correct engines have on this model): | 640x400, list the shapes | 294 | same | 0.035 | 0.039 | | 800x450, text in the image | 378 | same | 0.021 | 0.031 | | 800x450, describe the shapes | 381 | same | 0.0005 | 0.0019 | +| 1024x1024, the title (1,024 image tokens, read in 3 chunks) | 1,042 | same | 0.0022 | 0.0026 | +| two pictures in one request, the text in each | 655 | differs (a near tie: the floor's KL at this step is 0.16 too) | 0.014 | 0.022 | The answers are the same text as llama.cpp's: `STRATA 42` (with llama.cpp's own spelling ` STRATA42`), `CODE 4217`, `Red circle / Blue square / Green triangle`, `A red square is positioned on the left ... A blue circle is positioned on the right ...`. With the picture options on, @@ -53,8 +55,12 @@ picture); a different picture starts that conversation again. (`--batch N`, up to 8) and decode them together: every window carries one token of each conversation, so the dense weights, the head and every routed expert two conversations share are read once for all of them. The server needs no change: it speaks the same engine protocol as for Flash-Next ([BATCHING.md](BATCHING.md)). A request that arrives while another is read waits only for that read: the prompt of a -new request is read **between** the decode windows of the others (one window per prompt chunk), and a conversation continues in the slot -that holds its start (or the engine copies the longer held start from another slot). +new request is read **between** the decode windows of the others, and a conversation continues in the slot that holds its start (or the +engine copies the longer held start from another slot). A 3,008-token prompt read in 0.95 s (3,200 tok/s, 6 chunks) beside three decoding +slots: each of them paused at most 160 ms (one chunk) instead of the whole read, and produced 20 tokens meanwhile (one window per chunk, +the default); `STRATA_Q36_READ_WINDOWS=4` gives them 65 tokens during a 1.14 s read (more of the time, a slower read). +A request that runs alone (the solo path, with its MTP drafts) and is moved into a batch slot when another arrives, and back when it is +alone again, gives the text it gives running alone (the server's hand-over reuses the held state). Aggregate decode speed, N requests at once, same prompts, greedy, 128 new tokens each, wall time from the first request to the last answer, **R9700 32 GB, UD-Q4_K_XL, llama.cpp `llama-server -np N`** (5 interleaved pairs, median; Strata `--batch 8 --mtp 0`): diff --git a/tools/qwen35/q36_vision_cmp.py b/tools/qwen35/q36_vision_cmp.py index 59c5a7e1..370183eb 100644 --- a/tools/qwen35/q36_vision_cmp.py +++ b/tools/qwen35/q36_vision_cmp.py @@ -126,7 +126,8 @@ def main(): "kl_mean": float(kl.mean()), "kl_first": float(kl[0]), "top1": float(top1.mean()), "steps": int(len(kl))} if a.floor: fl = os.path.join(a.out, tag + ".cpu.logits") - run([a.dump, "--model", a.model, "--mmproj", a.mmproj, "--image", pic, "--prompt", prompt, "--n", str(a.n), + run([a.dump, "--model", a.model, "--mmproj", a.mmproj, *sum([["--image", p] for p in pics], []), + "--prompt", prompt, "--n", str(a.n), "--dump-full-logits", fl, "--mm-cpu", "1", "--max-tokens", "1024", "--ngl", "0", "--force", ",".join(map(str, gen[:-1]))], "", os.path.join(a.out, tag + ".cpu.log")) C = np.fromfile(fl, dtype=np.float32).reshape(-1, V) From 1e13cbc8a5d9b2cb8d8e8e283b534e150cfa80c2 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Wed, 14 Oct 2026 02:28:13 +0200 Subject: [PATCH 7/8] qwen35: keep the base engine's end-of-answer accounting (hybrid text identical), a stop keeps only x, the held tokens list every accepted draft An earlier commit capped the accepted drafts at the end of an answer; that is an exact state, but it moved the hybrid mode's expert-slot counts, so a sequence of requests with --mtp on a card that does not hold every expert differed from the base engine from the fourth request on (found by comparing the 10 parity prompts against the base goldens on the 12 GB card). Now the speculative step commits what the base engine committed; a stop seen before the state moves keeps only x (the server's hand-over of a stopped request to a batch slot then reuses the held state: its text equals the run alone), and the held tokens list x and every accepted draft, so a conversation that continues from them matches the state exactly. Setup says what parallel measured on the 12 GB card; docs/QWEN36.md updated. --- docs/QWEN36.md | 17 ++++++++++++++--- setup.py | 6 ++++-- src/qwen35/q36_engine.cu | 32 +++++++++++++------------------- 3 files changed, 31 insertions(+), 24 deletions(-) diff --git a/docs/QWEN36.md b/docs/QWEN36.md index 21bb641f..ae1d408a 100644 --- a/docs/QWEN36.md +++ b/docs/QWEN36.md @@ -72,6 +72,16 @@ answer, **R9700 32 GB, UD-Q4_K_XL, llama.cpp `llama-server -np N`** (5 interleav | 4 | 252.0 | 165.0 | 1.53 | 5/5 | | 8 | 325.4 | 208.1 | 1.56 | 5/5 | +**RTX 3060 12 GB, UD-Q4_K_XL in the hybrid mode** (each engine with the slots it needs: `--batch N` takes room from the expert slots; llama.cpp +`llama-server -np N -ncmoe 28 -t 8`, the best split of a sweep on this card; 5 interleaved pairs, medians; the box was shared with other +jobs between runs, never during one): + +| Requests at once | Strata | llama.cpp | Ratio | Pairs faster | +| ---: | ---: | ---: | ---: | ---: | +| 1 | 64.0 tok/s | 41.1 | 1.56 | 5/5 | +| 2 | 85.1 | 52.5 | 1.62 | 5/5 | +| 4 | 99.3 | 63.0 | 1.58 | 5/5 | + Every slot's tokens equal the tokens of the same request alone (the base engine's), at 2, 4 and 8 slots, with a 2.5K-token prompt read beside decoding slots, with slots reused for later requests, with pictures and with sampling (same seed). Through the server: four concurrent chat requests give the texts of the same four one after the other. @@ -94,9 +104,10 @@ The text is the same with and without it (every slot equal to its solo tokens). and the MTP block, 45 KB per token) and 0.07 GB of recurrent state. Setup writes the context for one conversation, so N slots take N times that from the room the experts would have: on a card that does not hold every expert (12 and 16 GB, the hybrid mode) that is room the expert slots lose, and a batch reads more distinct experts from RAM. Setup therefore **recommends `--parallel` only where every expert still -fits** (about 3 on a 32 GB card at 32K) and says why it leaves it at one otherwise; any number you give is kept. On the RTX 3060 12 GB with -`--batch 4` the engine kept 22 of 256 experts per layer (the sessions, the picture encoder and the MTP block took the rest) and four -requests at once ran 45 tok/s together against 42 one after the other: not worth it there. The engine says what the sessions take before it +fits** (about 3 on a 32 GB card at 32K) and says why it leaves it at one otherwise; any number you give is kept. It still pays on a card +that does not: on the RTX 3060 12 GB, `--batch 4` leaves 37 of 256 experts per layer in VRAM instead of 54, so a request alone decodes +64.7 tok/s instead of 68.3 (-5%, 3 interleaved runs each, medians of the 10 parity prompts), and four requests at once ran 99 tok/s together +against 64 for one (table above; each of them slower: ~25 tok/s). The engine says what the sessions take before it allocates them and refuses (with the numbers) a count that cannot fit. In the hybrid mode the text of a request can differ a little between running alone and running beside others: the experts that sit on the diff --git a/setup.py b/setup.py index 9d205980..91f3c159 100644 --- a/setup.py +++ b/setup.py @@ -5577,8 +5577,10 @@ def own_path_parallel_note(a_parallel, fam: dict, model: str, vram_gb: float, ct slot = own_path_parallel_slot_gb(fam, ctx) if a_parallel is None or a_parallel <= 1: if not rec: - return ["Several requests at once: left at one at a time - this card does not hold every expert beside more " - "sessions, and the experts that run on the CPU make a batch read more of them (docs/BATCHING.md)."] + return ["Several requests at once (opt-in, --parallel N): left at one at a time, because this card does not hold every " + "expert beside more sessions. Measured there (RTX 3060 12 GB), 4 requests together ran about 1.5x the speed " + "of one (99 against 64 tok/s) but each of them slower, and a request alone about 5% slower, as the " + "slots take VRAM from the expert cache (docs/QWEN36.md)."] return [f"Several requests at once (opt-in): --parallel {rec} decodes up to {rec} together instead of one after " f"the other (each takes ~{slot:.1f} GB of VRAM at this context; docs/BATCHING.md)."] lines = [f"parallel requests: {a_parallel} at once (each takes ~{slot:.1f} GB of VRAM at this context, " diff --git a/src/qwen35/q36_engine.cu b/src/qwen35/q36_engine.cu index 215f0194..04cbbe62 100644 --- a/src/qwen35/q36_engine.cu +++ b/src/qwen35/q36_engine.cu @@ -2285,13 +2285,11 @@ struct Engine { /// tokens of the rows the block must redo first (the drafts the last window accepted, seeded by hmain rows /// 0 .. fix.size() - 1 of that window). Drafts d1 .. dD, then the window [x, d1 .. dD] through the main model; /// returns the accepted count a and writes the picks of rows 0 .. a (row a's pick is the token after them). - /// `max_a`: at most that many drafts are taken (the answer has room for max_a + 1 more tokens, the last of which is - /// not fed, as in plain decoding); and no draft past an end-of-answer token is taken (that token is the next one the - /// caller emits). So the state ends exactly where plain decoding would leave it. - /// `cancel`: a stop asked for before the state moves keeps only x (the caller then emits no draft: every token emitted but - /// the last is in the state, so a conversation that continues from the held tokens loses and repeats nothing). + /// `cancel`: a stop asked for before the state moves keeps only x (the caller then emits no draft), so that a request + /// stopped mid-answer leaves the state at the tokens it has shown: a conversation that continues from them (the server's + /// hand-over of a stopped request to a batch slot) reuses it instead of reading them again. int spec_step(int x_tok, const std::vector& fix, int D, std::vector& drafts, int32_t* picks, - int max_a = 1 << 20, const std::atomic* cancel = nullptr) { + const std::atomic* cancel = nullptr) { const int N = (int) m->g.n_embd; if (main_hybrid) D = std::min(D, (int) (kRebalanceEvery - pos % kRebalanceEvery) - 1); const int T0 = (int) fix.size() + 1; // the redo rows and the row of x @@ -2342,10 +2340,7 @@ struct Engine { CK(cudaStreamSynchronize(st)); int a = 0; while (a < D && hpin[2 + a] == drafts[(size_t) a]) ++a; - a = std::min(a, max_a); if (cancel != nullptr && cancel->load()) a = 0; - for (int i = 0; i < a; ++i) - if (drafts[(size_t) i] == 248044 || drafts[(size_t) i] == 248046) { a = i; break; } // (<|endoftext|>, <|im_end|>) for (int i = 0; i <= a; ++i) picks[i] = hpin[2 + i]; commit(a + 1); CK(cudaMemcpyAsync(hlast, hmain + (size_t) a * N, (size_t) N * 4, cudaMemcpyDeviceToDevice, st)); @@ -3229,21 +3224,20 @@ struct Serve { if (!emit(nx)) break; if (n_active > 0) window(); if (spec && n_active == 0 && E.pos + E.mtp_d + 1 <= E.ctx) { - const int a = E.spec_step(nx, fix, E.mtp_d, drafts, picks, (int) std::min(max_new - produced - 1, 1 << 20), &stop); + const int a = E.spec_step(nx, fix, E.mtp_d, drafts, picks, &stop); offered += E.mtp_d; accepted += a; - // the state now holds x and the accepted drafts - spec_step took none past an end-of-answer token or past - // the room max_new leaves, so the state ends where plain decoding leaves it (the last token emitted is not - // fed) and a later request that continues this conversation neither misses nor reads a token twice + // the state now holds x and every accepted draft, whether or not the answer ends inside them (an end of + // answer, max_new): the held tokens say so, so a later request that continues this conversation matches them + // (a prompt that has the same tokens next reuses the state, any other reads from the start) and never reads + // a token twice ss.live.push_back(nx); for (int i = 0; i < a; ++i) ss.live.push_back(drafts[(size_t) i]); fix.assign(drafts.begin(), drafts.begin() + a); - for (int i = 0; i < a; ++i) { // (all of them: they are in the state; a stop is seen at the next token) - std::printf("T %d\n", drafts[(size_t) i]); - ++produced; - hist.push_back(drafts[(size_t) i]); - } - std::fflush(stdout); + bool ended = false; + for (int i = 0; i < a && !ended; ++i) + if (!emit(drafts[(size_t) i])) ended = true; + if (ended) break; nx = picks[a]; continue; } From 95eefd51f02751178ea77a329da2bcd030255842 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Wed, 14 Oct 2026 02:40:00 +0200 Subject: [PATCH 8/8] tools/qwen35: q36_vision_proto says to start the engine without --mtp for its cache check --- tools/qwen35/q36_vision_proto.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/tools/qwen35/q36_vision_proto.py b/tools/qwen35/q36_vision_proto.py index 89624e71..d64ccea2 100644 --- a/tools/qwen35/q36_vision_proto.py +++ b/tools/qwen35/q36_vision_proto.py @@ -6,7 +6,10 @@ output (vc1/*.llama.log of vcmp.py), the rows from strata-vision (.sve) Checks: 1. a solo GENI answers like llama.cpp's greedy (the first 24 tokens); 2. two pictures and a text prompt decoding together (BGENI / BGEN) give each the tokens of its solo run; 3. the conversation cache: the same request again and a longer one (the first, its answer and more text) reuse the held state, a different picture does not; a text request after -a picture request is not disturbed (the rotary offset is back at 0).""" +a picture request is not disturbed (the rotary offset is back at 0). + +Start the engine without --mtp for the cache check: the held tokens of a request that ran with drafts include the drafts accepted past +its last emitted token, so a prompt that does not repeat them reads from the start (correct, but the check wants the reuse).""" from pathlib import Path import argparse, json, os, shlex, sys sys.path.insert(0, __file__.rsplit("/", 1)[0] if "/" in __file__ else ".")