Skip to content

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

C
15.0 KB
Raw Blame
/* qwen36_tier.h -- optional CUDA VRAM expert tier for the qwen36 engine.
 *
 * Applies colibri's placement concept ("route -> place -> overlap -> learn")
 * one level up from the GLM disk tier: experts live in RAM, the *hot* ones
 * are promoted into DEVICE_LOCAL VRAM across one or more GPUs and computed
 * there via the existing CUDA backend (backend_cuda.cu, expert-group API).
 *
 *  - Every expert has one home device (eid % n_gpus), no duplicates.
 *  - Routing heat decides who earns VRAM (LFRU semantics from tier.h, with
 *    hysteresis); a warmstart pre-fills the budget before the first token,
 *    ordered by a persisted heat table (HEAT_FILE) when available.
 *  - Uploads run on a background thread through staging copies; decode never
 *    blocks on placement. A VRAM miss falls back to the CPU int8 path and
 *    overlaps with the in-flight GPU groups.
 *
 * Enable with COLI_CUDA=1 [COLI_GPUS=0,1] [CUDA_EXPERT_GB=<G>|auto]
 * [HEAT_FILE=<path>] [QT_NO_WARMSTART=1]. Compiled only when the build sets
 * -DCOLI_CUDA (CUDA=1); otherwise the inline stubs below keep the engine
 * CPU-only with zero overhead. */
#ifndef QWEN36_TIER_H
#define QWEN36_TIER_H
#include <stdint.h>

#ifdef COLI_CUDA

/* Init after model load. Returns 1 when the tier is active.
 * cap_experts_per_layer must equal n_experts (full RAM residency): the tier
 * stores raw pointers into the expert slots, which must never be evicted. */
/* expert_is_int4: 1 = pesi int4 impacchettati (fmt=4), 0 = int8 (fmt=1). Il
 * chiamante lo determina dalla TAGLIA SU DISCO, non da meta.ebits, che su
 * qualche container mente (cfr. il rilevamento in qwen36.c). */
/* R4 role split: park the dense-i8 lm_head on its own CUDA device
 * (COLI_LMHEAD_GPU=<dev>). One GEMV per token, at token end β€” outside the
 * per-layer latency chain β€” so a slower second card can host it without
 * pacing the expert stream. qt_init places no experts on that device. */
int  qt_lmhead_init(const int8_t *q, const float *sc, int I, int O);
int  qt_lmhead_matmul(float *y, const float *x, int I, int O);

/* ---- placement table (R4) ------------------------------------------------
 * Every movable piece of the forward pass can be pinned to the CPU or to a
 * specific CUDA device, so configurations can be A/B'd instead of argued
 * about. One variable, not one per component:
 *
 *   COLI_PLACE="experts=0,lmhead=0,dnproj=1,dnout=1,attnproj=cpu"
 *
 * Target is `cpu` or a CUDA ordinal. A component may also be split across
 * cards by layer count, joined with '+' so it cannot be confused with the
 * component separator:
 *
 *   COLI_PLACE="dnproj=0:15+1:15"   first 15 DeltaNet layers on dev 0, rest on 1
 *
 * Unnamed components keep their default (CPU; experts keep following
 * COLI_GPUS). Splitting matters because the DeltaNet projections hang
 * serially in the layer chain anyway -- a slower card delays only its own
 * layers, never the whole stream, which is what sank asymmetric EXPERT
 * placement. `layer` is the model layer index; pass 0 for whole-model
 * components like lmhead. */
#define QT_PLACE_CPU (-1)
int  qt_place_of(const char *component, int layer);
/* Automatic placement (COLI_PLACE unset or "auto"; "off" disables). The
 * engine offers each trunk component with its byte size BEFORE qt_init --
 * "lmhead" once (layer 0), "dnproj" per DeltaNet layer -- and qt_init decides
 * by bytes saved per token per byte of VRAM, pricing displaced experts by
 * heat. The decision is what qt_place_of() then returns, and the placed
 * bytes come out of that device's expert budget. Sizes only; the tensors
 * follow through qt_lmhead_init / qt_dnproj_init as before. */
void qt_trunk_offer(const char *component, int layer, size_t bytes);
/* The automatic placement is a prediction; the engine measures it at startup
 * (one GEMV both ways, qwen36.c trunk_probe_gpu_wins) and withdraws the whole
 * trunk when the GPU loses, giving the bytes back to the expert budget. Only
 * the automatic placement can be withdrawn; a COLI_PLACE list stands. */
int  qt_place_is_auto(void);
void qt_trunk_withdraw(const char *why);

/* DeltaNet input projections, qkv ++ z fused into one resident tensor per
 * layer: one GEMV instead of two, and the engine's qkv/z buffers are laid out
 * contiguously so the result needs no split copy. */
int  qt_dnproj_init(int layer, const int8_t *q, const float *sc,
                    int I, int O, int device);
int  qt_dnproj_matmul(int layer, float *y, const float *x, int I, int O);
int  qt_dnproj_ready(int layer);
int  qt_dnproj_matmul_batch(int layer, float *y, const float *x, int S, int I, int O);

/* The whole DeltaNet layer on the device (backend coli_cuda_dn_*): after the
 * input projection (qt_dnproj_init) and the out_proj (a qt_dense handle) have
 * both landed on the same device, qt_dn_gpu_init puts the layer's conv ring,
 * recurrent state and norm/conv weights there too; qt_dn_gpu_step then runs a
 * decode token end to end on the card, host in, host out. The host copy of
 * the state stays the engine's, moved with qt_dn_gpu_set/get_state whenever
 * the CPU path (prefill, snapshot, reset) needs it. A failing step turns the
 * layer off, like every other GPU path here, and the engine continues on the
 * CPU from the state it can still get back. */
int  qt_dn_gpu_init(int layer, int vh, int vk, int kdim, int vdim, int conv_dim, int convk, int hidden,
                    const float *conv_w, const float *norm_w, float eps, int dnout_handle_plus1);
int  qt_dn_gpu_ready(int layer);
/* the same from three dense handles (in_proj qkv, in_proj z, out_proj), all on one
 * device -- qwen38's trunk items; gate_sigmoid: the gated norm's gate (1 = sigmoid(z)) */
int  qt_dn_gpu_init_dense(int layer, int vh, int vk, int kdim, int vdim, int conv_dim, int convk, int hidden,
                          const float *conv_w, const float *norm_w, float eps, int gate_sigmoid,
                          int proj_handle_plus1, int projz_handle_plus1, int dnout_handle_plus1);
int  qt_dn_gpu_set_state(int layer, const float *ring, const float *rec);   /* NULL = zero */
int  qt_dn_gpu_get_state(int layer, float *ring, float *rec);
int  qt_dn_gpu_step(int layer, const float *x, float *out, const float *egh, const float *beta);
/* Generic resident dense matrix (int8 per-row, one GEMV per call), addressed
 * by a handle: the Qwen3.8 trunk uses this for every matrix it places. Offer
 * the size with qt_trunk_offer(name, layer, bytes) before qt_init, ask
 * qt_place_of(name, layer) after it, then hand the quantized bytes here.
 * Returns the handle (>= 0) or -1 (stays on the CPU). */
int  qt_dense_init(const int8_t *q, const float *sc, int I, int O, int device);
int  qt_dense_matmul(int handle, float *y, const float *x, int I, int O);
/* Row-major x[S,I] -> y[S,O], using the same resident int8 tensor. */
int  qt_dense_matmul_batch(int handle, float *y, const float *x, int S, int I, int O);
int  qt_dense_count(void);

/* fp8 streaming mode (Qwen3.8): experts arrive as e4m3 bytes with 128x128
 * block scales and do NOT all fit in RAM. cap may be smaller than n_experts;
 * the tier copies what it uploads inside the qt_note call and keeps no
 * pointer into the engine's slot. e4m3_lut is quant.h's E4M3_LUT, published
 * to the backend so fmt=8 uploads are accepted. */
/* Init returns 0 without changing an active tier. Shut down before reinit;
 * callers must serialize init/shutdown with new work. */
int  qt_init_fp8(int n_layers, int n_experts, int hidden, int inter,
                 int cap_experts_per_layer, int topk, const float *e4m3_lut);
int  qt_init(int n_layers, int n_experts, int hidden, int inter,
             int cap_experts_per_layer, int topk, int expert_gs,
             int expert_is_int4);
int  qt_ready(void);
int  qt_is_resident(int layer, int eid);
void qt_shutdown(void);

/* Call once per routed expert per token (pointers to the RAM slot: packed
 * int4 or, on an int8 container, the live int8 weights -- tier fmt=1 is
 * accepted since #1334; see also #1391 for the decode-path offer). Updates
 * heat and may enqueue a background upload. */
void qt_note(int layer, int eid,
             const uint8_t *g4, const uint8_t *u4, const uint8_t *d4,
             const float *gs, const float *us, const float *ds);

/* Launch the GPU groups for the resident subset of the K selected experts
 * (async, all devices in parallel). Returns a bitmask of the k handled by
 * the GPU. Compute the misses on the CPU, then call qt_take(). */
uint32_t qt_issue(int layer, const int *eids, int K, const float *x);

/* Collect all GPU results and accumulate val[k]*y_k into out[hidden].
 * Returns 0 on collection failure, leaving out unchanged. The caller must
 * stop inference: experts selected by qt_issue were not computed on CPU. */
int qt_take(uint32_t mask, const float *val, int K, float *out);

/* Warmstart: plan the full fill set (heat order, budget reserved), then any
 * number of loader threads may call qt_note_planned per planned expert. */
int  qt_plan_fill(int *layers, int *eids, int max);
void qt_note_planned(int layer, int eid,
             const uint8_t *g4, const uint8_t *u4, const uint8_t *d4,
             const float *gs, const float *us, const float *ds);
int  qt_fill_next(int *layer, int *eid);
void qt_note_block(int layer, int eid,
             const uint8_t *g4, const uint8_t *u4, const uint8_t *d4,
             const float *gs, const float *us, const float *ds);
void qt_fill_wait(void);   /* blocks until every enqueued upload is resident (not merely dequeued) */

/* Re-plan the resident set from the prompt's own routing. counts[] are this
 * prompt's routing counts per expert: for layer >= 0 one layer's ne counts
 * (the engine calls this after each prefill layer's routing, so the swaps of
 * layer L upload while layers L+1.. still compute), for layer < 0 the whole
 * nl*ne table. Residents the prompt never routed to are swapped, budget-
 * neutral, for the prompt's most-routed non-residents of the same layer (or
 * device, for the whole-table form), through the victim-first swap the LFRU
 * tick uses, while the newcomer's count strictly exceeds the victim's. As
 * many swaps as the upload queue takes start at once, the rest are pending
 * and drain on later calls and, a few per token, on the decode ticks: nothing
 * blocks. Returns the pairs planned by this call. */
int  qt_replan(int layer, const uint32_t *counts, int max_swaps);
/* Experts the tier evicted since the last call (LFRU and re-plan swaps), as
 * (layer, eid) pairs, oldest first; the engine rebuilds their CPU copies ahead
 * of the miss path. Bounded ring: what overflows is simply not reported, the
 * miss path rebuilds lazily as before. Returns the count written. */
int  qt_evicted_take(int *layers, int *eids, int max);
/* Snapshot the hit/miss counters; qt_stats then also reports the hit rate
 * from this point on (the engine marks the prefill/decode boundary). */
void qt_stats_mark(void);

/* One telemetry block on stderr: residency, hits/misses, uploads per device. */
void qt_stats(void);

#else /* !COLI_CUDA: inline stubs, engine stays CPU-only */

static inline int  qt_init(int a,int b,int c,int d,int e,int f,int g,int h){(void)h;(void)a;(void)b;(void)c;(void)d;(void)e;(void)f;(void)g;return 0;}
static inline int  qt_init_fp8(int a,int b,int c,int d,int e,int f,const float*g){(void)a;(void)b;(void)c;(void)d;(void)e;(void)f;(void)g;return 0;}
static inline int  qt_lmhead_init(const int8_t*a,const float*b,int c,int d){(void)a;(void)b;(void)c;(void)d;return 0;}
static inline int  qt_lmhead_matmul(float*a,const float*b,int c,int d){(void)a;(void)b;(void)c;(void)d;return 0;}
#define QT_PLACE_CPU (-1)
static inline int  qt_place_of(const char*a,int b){(void)a;(void)b;return QT_PLACE_CPU;}
static inline void qt_trunk_offer(const char*a,int b,size_t c){(void)a;(void)b;(void)c;}
static inline int  qt_place_is_auto(void){return 0;}
static inline void qt_trunk_withdraw(const char*a){(void)a;}
static inline int  qt_dnproj_init(int a,const int8_t*b,const float*c,int d,int e,int f){(void)a;(void)b;(void)c;(void)d;(void)e;(void)f;return 0;}
static inline int  qt_dnproj_matmul(int a,float*b,const float*c,int d,int e){(void)a;(void)b;(void)c;(void)d;(void)e;return 0;}
static inline int  qt_dnproj_ready(int a){(void)a;return 0;}
static inline int  qt_dnproj_matmul_batch(int a,float*b,const float*c,int d,int e,int f){(void)a;(void)b;(void)c;(void)d;(void)e;(void)f;return 0;}
static inline int  qt_dn_gpu_init(int a,int b,int c,int d,int e,int f,int g,int i,const float*j,const float*k,float l,int m){(void)a;(void)b;(void)c;(void)d;(void)e;(void)f;(void)g;(void)i;(void)j;(void)k;(void)l;(void)m;return 0;}
static inline int  qt_dn_gpu_ready(int a){(void)a;return 0;}
static inline int  qt_dn_gpu_init_dense(int a,int b,int c,int d,int e,int f,int g,int i,const float*j,const float*k,float l,int m,int n,int o,int p){(void)a;(void)b;(void)c;(void)d;(void)e;(void)f;(void)g;(void)i;(void)j;(void)k;(void)l;(void)m;(void)n;(void)o;(void)p;return 0;}
static inline int  qt_dn_gpu_set_state(int a,const float*b,const float*c){(void)a;(void)b;(void)c;return 0;}
static inline int  qt_dn_gpu_get_state(int a,float*b,float*c){(void)a;(void)b;(void)c;return 0;}
static inline int  qt_dn_gpu_step(int a,const float*b,float*c,const float*d,const float*e){(void)a;(void)b;(void)c;(void)d;(void)e;return 0;}
static inline int  qt_dense_init(const int8_t*a,const float*b,int c,int d,int e){(void)a;(void)b;(void)c;(void)d;(void)e;return -1;}
static inline int  qt_dense_matmul(int a,float*b,const float*c,int d,int e){(void)a;(void)b;(void)c;(void)d;(void)e;return 0;}
static inline int  qt_dense_matmul_batch(int a,float*b,const float*c,int d,int e,int f){(void)a;(void)b;(void)c;(void)d;(void)e;(void)f;return 0;}
static inline int  qt_dense_count(void){return 0;}
static inline int  qt_ready(void){return 0;}
static inline int  qt_is_resident(int a,int b){(void)a;(void)b;return 0;}
static inline void qt_shutdown(void){}
static inline void qt_note(int a,int b,const uint8_t*c,const uint8_t*d,const uint8_t*e,const float*f,const float*g,const float*h){(void)a;(void)b;(void)c;(void)d;(void)e;(void)f;(void)g;(void)h;}
static inline uint32_t qt_issue(int a,const int*b,int c,const float*d){(void)a;(void)b;(void)c;(void)d;return 0;}
static inline int qt_take(uint32_t a,const float*b,int c,float*d){(void)b;(void)c;(void)d;return a==0;}
static inline int  qt_plan_fill(int*a,int*b,int c){(void)a;(void)b;(void)c;return 0;}
static inline void qt_note_planned(int a,int b,const uint8_t*c,const uint8_t*d,const uint8_t*e,const float*f,const float*g,const float*h){(void)a;(void)b;(void)c;(void)d;(void)e;(void)f;(void)g;(void)h;}
static inline int  qt_fill_next(int*a,int*b){(void)a;(void)b;return 0;}
static inline void qt_note_block(int a,int b,const uint8_t*c,const uint8_t*d,const uint8_t*e,const float*f,const float*g,const float*h){(void)a;(void)b;(void)c;(void)d;(void)e;(void)f;(void)g;(void)h;}
static inline void qt_fill_wait(void){}
static inline int  qt_replan(int l,const uint32_t*a,int b){(void)l;(void)a;(void)b;return 0;}
static inline int  qt_evicted_take(int*a,int*b,int c){(void)a;(void)b;(void)c;return 0;}
static inline void qt_stats_mark(void){}
static inline void qt_stats(void){}

#endif /* COLI_CUDA */
#endif /* QWEN36_TIER_H */