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

Merge branch 'dev' into sse41-tier-upstream-next-v2

Jaapjan Tinbergen5023e3e9a346
diff --git a/c/Makefile b/c/Makefile
index edc703f6..b3bd50f6 100644
--- a/c/Makefile
+++ b/c/Makefile
@@ -503,13 +503,13 @@ TEST_RULES := $(shell sed -n 's|^tests/\(test_[a-z0-9_]*\)\$$(EXE):.*|\1|p' $(f
TEST_EXCLUDE = test_uring test_deepseek_v4 test_v4_ownership test_v4_serve_framing \
test_segment_adapters_registration test_segment_adapters_real \
test_edge_adapters_registration test_edge_adapters_real \
- test_gsgemv_sse41 test_qgemv_sse41 test_olmoe_dot_i8_16_sse41 test_qwen38_tier_engine
+ test_gsgemv_sse41 test_qgemv_sse41 test_olmoe_dot_i8_16_sse41 test_st_f16_bf16_simd_sse41 test_qwen38_tier_engine
TEST_BINS = $(addprefix tests/,$(addsuffix $(EXE),$(filter-out $(TEST_EXCLUDE),$(TEST_RULES))))
ifneq (,$(LINUX))
TEST_BINS += tests/test_uring$(EXE)
endif
ifneq (,$(X86_64))
-TEST_BINS += tests/test_gsgemv_sse41$(EXE) tests/test_qgemv_sse41$(EXE) tests/test_olmoe_dot_i8_16_sse41$(EXE)
+TEST_BINS += tests/test_gsgemv_sse41$(EXE) tests/test_qgemv_sse41$(EXE) tests/test_olmoe_dot_i8_16_sse41$(EXE) tests/test_st_f16_bf16_simd_sse41$(EXE)
endif
ifeq ($(COLI_V4_SUPPORTED),1)
TEST_BINS += tests/test_v4_hybrid_policy$(EXE) tests/test_k3_fill_budget$(EXE) tests/test_v4_bank_pair$(EXE)
@@ -1197,6 +1197,11 @@ tests/test_qwen36_tok_truncated$(EXE): tests/test_qwen36_tok_truncated.c qwen36.
tests/test_qwen36_encode_oom$(EXE): tests/test_qwen36_encode_oom.c qwen36.c expert_ffn.h qwen36_tier.h st.h json.h compat.h $(QWEN36_TIER_SRC) $(CUDA_OBJ)
$(CC) $(QWEN36_CFLAGS) $< $(QWEN36_TIER_SRC) $(CUDA_OBJ) -o $@ $(QWEN36_LDFLAGS)
+# slot_ensure_int8's wiring onto #1271's unpack_int4_to_int8: regression check
+# that its output matches the old separate scalar nibble-unpack loop it replaced.
+tests/test_qwen36_slot_int8$(EXE): tests/test_qwen36_slot_int8.c qwen36.c qwen36_tier.h st.h json.h compat.h $(QWEN36_TIER_SRC) $(CUDA_OBJ)
+ $(CC) $(QWEN36_CFLAGS) $< $(QWEN36_TIER_SRC) $(CUDA_OBJ) -o $@ $(QWEN36_LDFLAGS)
+
# Reproducible local timing evidence; intentionally not a noisy CI perf gate.
tests/bench_qwen36_dense_batch$(EXE): tests/bench_qwen36_dense_batch.c qwen36.c qwen36_tier.h st.h json.h compat.h $(QWEN36_TIER_SRC) $(CUDA_OBJ)
$(CC) $(QWEN36_CFLAGS) $< $(QWEN36_TIER_SRC) $(CUDA_OBJ) -o $@ $(QWEN36_LDFLAGS)
@@ -1321,6 +1326,28 @@ tests/test_dup_name_refusal$(EXE): tests/test_dup_name_refusal.c st.h json.h com
tests/test_st_shape$(EXE): tests/test_st_shape.c st.h json.h compat.h
$(CC) $(CFLAGS) $< -o $@ $(LDFLAGS)
+# Exhaustive bit-exact gate for st.h's bf16_to_f32_bulk/f16_to_f32_bulk AVX2 tier
+# (all 65536 patterns per format -- see the file for why no tolerance applies).
+tests/test_st_f16_bf16_simd$(EXE): tests/test_st_f16_bf16_simd.c st.h json.h compat.h
+ $(CC) $(CFLAGS) $< -o $@ $(LDFLAGS)
+
+# Same gate, forced onto the SSE4.1 tier: overrides the host's default -march
+# so the SSE4.1 body in st.h is actually exercised even on a devbox that
+# would otherwise always pick the AVX2 tier.
+tests/test_st_f16_bf16_simd_sse41$(EXE): tests/test_st_f16_bf16_simd.c st.h json.h compat.h
+ $(CC) $(CFLAGS) -msse4.1 -mno-avx2 -mno-fma $< -o $@ $(LDFLAGS)
+
+# bf16_to_f32_bulk/f16_to_f32_bulk vs the scalar per-element reference, NOT a
+# test gate. Build on demand: make tests/bench_st_f16_bf16_simd ARCH=native
+tests/bench_st_f16_bf16_simd$(EXE): tests/bench_st_f16_bf16_simd.c st.h json.h compat.h
+ $(CC) $(CFLAGS) $< -o $@ $(LDFLAGS)
+
+# Synthetic peak-RSS proxy for qwen36.c's dense-int8-during-load change
+# (load_tq vs the old post-hoc qdw_register pass), NOT a test gate. Build on
+# demand: make tests/bench_load_tq_peak_rss
+tests/bench_load_tq_peak_rss$(EXE): tests/bench_load_tq_peak_rss.c
+ $(CC) -O3 -march=native $< -o $@ -lm
+
tests/test_st$(EXE): tests/test_st.c st.h json.h compat.h
$(CC) $(CFLAGS) $< -o $@ $(LDFLAGS)
diff --git a/c/qwen36.c b/c/qwen36.c
index bcf91996..a0f13882 100644
--- a/c/qwen36.c
+++ b/c/qwen36.c
@@ -629,16 +629,28 @@ typedef struct {
int expert_gs; /* expert scale group size along input dim; 0 = per-row */
} Cfg;
+/* ---- Dense int8: a dense matrix that is quantized to int8 during load
+ * (load_tq, below matmul_d) instead of loaded as f32 and quantized in a
+ * separate pass afterward -- so the f32 staging buffer for THIS matrix alone
+ * is what's briefly resident, not every dense matrix in the model at once.
+ * `w` is the f32 copy: kept (and `q`/`sc` left NULL) when COLI_DENSE_I8=0,
+ * the reference/parity path; freed once `q`/`sc` are populated otherwise
+ * (COLI_KEEP_F32=1 keeps it alongside them, for debugging). matmul_d
+ * dispatches on q!=NULL directly -- no pointer-keyed scan. */
+typedef struct { const float *w; int8_t *q; float *sc; int I, O; } QW;
+static void qw_free(QW *w) { free((void*)w->w); free(w->q); free(w->sc); w->w = NULL; w->q = NULL; w->sc = NULL; }
+
/* ---------- per-layer dense weights ---------- */
typedef struct {
- float *in_ln, *post_ln, *q, *k, *v, *o, *qn, *kn, *gate, *gate_bias;
- float *sh_g, *sh_u, *sh_d, *sh_gate; /* shared expert (dense f32) + shared_expert_gate */
+ float *in_ln, *post_ln, *qn, *kn, *gate_bias;
+ QW q, k, v, o, gate;
+ QW sh_g, sh_u, sh_d; float *sh_gate; /* shared expert (dense, int8-during-load) + shared_expert_gate */
/* Gated DeltaNet (linear_attention) dense weights (f16->f32 via st_read_f32). */
- float *dn_qkv, *dn_z, *dn_b, *dn_a; /* in_proj_qkv/z/b/a */
+ QW dn_qkv, dn_z; float *dn_b, *dn_a; /* in_proj_qkv/z (int8-during-load), b/a (not dense-matmul'd) */
float *dn_conv; /* conv1d.weight [conv_dim, convk] (groups=conv_dim) */
float *dn_dtbias, *dn_alog; /* dt_bias[vh], A_log[vh] */
float *dn_norm; /* RMSNormGated weight [vdim] */
- float *dn_out; /* out_proj [hidden, value_dim] */
+ QW dn_out; /* out_proj [hidden, value_dim] */
} Layer;
/* ---------- LRU expert cache (int8 weights + per-row float scales) ---------- */
@@ -664,7 +676,8 @@ typedef struct {
Cfg c;
shards S;
int quant_bits;
- float *embed, *lm_head, *final_norm;
+ float *embed, *final_norm;
+ QW lm_head;
Layer *L;
LCache *cache; /* [n_layers] */
int *active_of; /* [n_layers] original->active idx (Phase 2: identity for all layers) */
@@ -997,11 +1010,9 @@ static void matmul_qe(float *y, const float *x, const int8_t *q, const float *sc
}
/* ---- Dense int8: per-row quantized copies of the large f32 matrices.
- * matmul_d dispatches via pointer lookup to matmul_q; COLI_DENSE_I8=0 falls
- * back to f32 (reference path for parity tests). ~4x less memory traffic. */
-#define QDW_MAX 1024
-static struct { const float *w; int8_t *q; float *sc; int I, O; } g_qdw[QDW_MAX];
-static int g_qdw_n = 0;
+ * matmul_d dispatches directly off QW.q (no pointer-keyed scan -- see QW,
+ * above Layer); COLI_DENSE_I8=0 falls back to f32 (QW.w, reference path for
+ * parity tests). ~4x less memory traffic. */
#ifdef COLI_QWEN_BATCH_TEST
static uint64_t g_qwen_matmul_d_calls;
#endif
@@ -1011,10 +1022,15 @@ static int dense_i8_on(void){ static int v=-1; if(v<0){ const char *e=getenv("CO
* the time. */
static int kv_prefix_off(void){ const char *e=getenv("COLI_KV_PREFIX"); return e && *e=='0'; }
static int dense_batch_on(void){ const char *e=getenv("QWEN_DENSE_BATCH"); return !(e&&*e=='0'); }
-static void qdw_register(const float *W, int I, int O){
- if (!W || !dense_i8_on() || g_qdw_n >= QDW_MAX) return;
+/* Per-row max-abs / round-clamp int8 quantization of an in-memory f32 matrix
+ * W [O][I] row-major -- same math load_tq used to run post-hoc via qdw_register,
+ * factored out so it can also run on a caller-owned buffer directly (tests
+ * that synthesize weights in memory, without a shard file to load from). Does
+ * not touch out->w -- the caller sets that (or leaves it, e.g. load_tq frees
+ * it right after). */
+static void qw_quantize(const float *W, int I, int O, QW *out) {
int8_t *q = malloc((size_t)O*I); float *sc = malloc((size_t)O*sizeof(float));
- if (!q || !sc) { free(q); free(sc); return; }
+ if (!q || !sc) { fprintf(stderr, "OOM qw_quantize\n"); exit(1); }
#pragma omp parallel for schedule(static)
for (int o = 0; o < O; o++) {
const float *r = W + (int64_t)o*I; float am = 0.f;
@@ -1023,20 +1039,20 @@ static void qdw_register(const float *W, int I, int O){
int8_t *d = q + (int64_t)o*I;
for (int i = 0; i < I; i++) { int v = (int)lrintf(r[i]*inv); if (v>127) v=127; if (v<-127) v=-127; d[i] = (int8_t)v; }
}
- g_qdw[g_qdw_n].w=W; g_qdw[g_qdw_n].q=q; g_qdw[g_qdw_n].sc=sc; g_qdw[g_qdw_n].I=I; g_qdw[g_qdw_n].O=O; g_qdw_n++;
+ out->q = q; out->sc = sc; out->I = I; out->O = O;
}
-static void matmul_d(float *y, const float *x, const float *W, int S, int I, int O){
+static void matmul_d(float *y, const float *x, const QW *w, int S, int I, int O){
#ifdef COLI_QWEN_BATCH_TEST
g_qwen_matmul_d_calls++;
#endif
- for (int i = 0; i < g_qdw_n; i++) if (g_qdw[i].w == W && g_qdw[i].I == I) {
+ if (w->q) {
if (S > 1 && dense_batch_on())
- matmul_q_batch(y, x, g_qdw[i].q, g_qdw[i].sc, S, I, O);
+ matmul_q_batch(y, x, w->q, w->sc, S, I, O);
else
- for (int s = 0; s < S; s++) matmul_q(y+(int64_t)s*O, x+(int64_t)s*I, g_qdw[i].q, g_qdw[i].sc, I, O);
+ for (int s = 0; s < S; s++) matmul_q(y+(int64_t)s*O, x+(int64_t)s*I, w->q, w->sc, I, O);
return;
}
- matmul(y, x, W, S, I, O);
+ matmul(y, x, w->w, S, I, O);
}
/* rmsnorm over a row of length D (in-place capable: out may == x).
@@ -1254,6 +1270,24 @@ static float *load_t_n(Model *m, const char *name, int64_t want) {
return p;
}
+/* Dense matrix load, quantized to int8 DURING loading rather than in a
+ * separate pass over the whole model afterward (see QW, above Layer):
+ * reads `name` (I*O elements, same size discipline as load_t_n), and when
+ * `quantize` && COLI_DENSE_I8 is on, quantizes it via qw_quantize and frees
+ * the f32 staging buffer right away -- so at most one dense matrix's f32 copy
+ * is ever resident at a time, not the whole model's. `quantize` is false for
+ * loaders that never ran through the old post-hoc qdw_register pass either
+ * (the Segment/Edge adapters build partial or auxiliary models straight off
+ * model_init_range/load_t_n, never main()'s dense-i8 block) -- passing it
+ * through keeps their f32-only behavior exactly as it was. */
+static void load_tq(Model *m, const char *name, int I, int O, int quantize, QW *out) {
+ float *p = load_t_n(m, name, (int64_t)I * O);
+ out->w = p; out->q = NULL; out->sc = NULL; out->I = I; out->O = O;
+ if (!quantize || !dense_i8_on()) return;
+ qw_quantize(p, I, O, out);
+ if (getenv("COLI_KEEP_F32")) out->w = p; else { free(p); out->w = NULL; }
+}
+
static void model_init_range(Model *m, const char *snap, int cap, int bits,
int layer_begin, int layer_end,
int load_boundaries, int allocate_state) {
@@ -1279,9 +1313,17 @@ static void model_init_range(Model *m, const char *snap, int cap, int bits,
exit(1);
}
double t0 = now_s();
+ /* Quantize during load only for the full-model path (main()'s static Model,
+ * load_boundaries=1): the Segment/Edge adapters build partial or auxiliary
+ * models straight off this same loop and never ran the old post-hoc
+ * qdw_register pass either, so gating on load_boundaries keeps their
+ * f32-only numerics exactly as they were. */
+ int quantize_dense = load_boundaries && dense_i8_on();
+ int qcount = 0; double qfreed = 0;
if (load_boundaries) {
- m->embed = load_t_n(m, "model.embed_tokens.weight", (int64_t)c->vocab * c->hidden);
- m->lm_head = load_t_n(m, "lm_head.weight", (int64_t)c->vocab * c->hidden);
+ m->embed = load_t_n(m, "model.embed_tokens.weight", (int64_t)c->vocab * c->hidden);
+ load_tq(m, "lm_head.weight", c->hidden, c->vocab, quantize_dense, &m->lm_head);
+ if (m->lm_head.q) { qcount++; qfreed += (double)c->hidden * c->vocab * sizeof(float); }
m->final_norm = load_t_n(m, "model.norm.weight", c->hidden);
}
m->L = calloc((size_t)c->n_layers, sizeof(Layer));
@@ -1291,15 +1333,19 @@ static void model_init_range(Model *m, const char *snap, int cap, int bits,
m->active_of = malloc((size_t)c->n_layers * sizeof(int));
for (int i = 0; i < c->n_layers; i++) m->active_of[i] = i;
char nm[256];
+ int q_out = c->q_heads * c->q_head_dim, kv_out = c->kv_heads * c->k_head_dim;
+ #define QCOUNT(field) do { if ((field).q) { qcount++; qfreed += (double)(field).I * (field).O * sizeof(float); } } while (0)
for (int i = layer_begin; i < layer_end; i++) {
int ai = m->active_of[i]; /* == i for Phase 2 */
Layer *l = &m->L[i];
- /* input/post layernorms + MoE exist for every layer */
+ /* input/post layernorms exist for every layer */
#define LD(field, suffix, want) snprintf(nm,sizeof(nm),"model.layers.%d." suffix,ai); l->field = load_t_n(m,nm,(want))
LD(in_ln, "input_layernorm.weight", c->hidden);
LD(post_ln,"post_attention_layernorm.weight", c->hidden);
- LD(gate, "mlp.gate.weight", (int64_t)c->n_experts * c->hidden);
#undef LD
+ snprintf(nm,sizeof(nm),"model.layers.%d.mlp.gate.weight", ai);
+ load_tq(m, nm, c->hidden, c->n_experts, quantize_dense, &l->gate);
+ QCOUNT(l->gate);
/* q/k norms are per-head [head_dim]; only on attention layers, load if present */
if (c->has_qk_norm) {
snprintf(nm,sizeof(nm),"model.layers.%d.self_attn.q_norm.weight", ai);
@@ -1311,42 +1357,51 @@ static void model_init_range(Model *m, const char *snap, int cap, int bits,
snprintf(nm,sizeof(nm),"model.layers.%d.mlp.gate.e_score_correction_bias", ai);
if (st_has(&m->S, nm)) { l->gate_bias = falloc(c->n_experts); st_read_f32(&m->S, nm, l->gate_bias, 0); }
else l->gate_bias = NULL;
- /* shared expert (dense f32) */
- #define LD2(field, suffix, want) snprintf(nm,sizeof(nm),"model.layers.%d.mlp.shared_expert." suffix,ai); l->field = load_t_n(m,nm,(want))
- LD2(sh_g, "gate_proj.weight", (int64_t)c->shared_inter * c->hidden);
- LD2(sh_u, "up_proj.weight", (int64_t)c->shared_inter * c->hidden);
- LD2(sh_d, "down_proj.weight", (int64_t)c->hidden * c->shared_inter);
- #undef LD2
+ /* shared expert (dense, int8-during-load) */
+ snprintf(nm,sizeof(nm),"model.layers.%d.mlp.shared_expert.gate_proj.weight", ai);
+ load_tq(m, nm, c->hidden, c->shared_inter, quantize_dense, &l->sh_g); QCOUNT(l->sh_g);
+ snprintf(nm,sizeof(nm),"model.layers.%d.mlp.shared_expert.up_proj.weight", ai);
+ load_tq(m, nm, c->hidden, c->shared_inter, quantize_dense, &l->sh_u); QCOUNT(l->sh_u);
+ snprintf(nm,sizeof(nm),"model.layers.%d.mlp.shared_expert.down_proj.weight", ai);
+ load_tq(m, nm, c->shared_inter, c->hidden, quantize_dense, &l->sh_d); QCOUNT(l->sh_d);
/* shared_expert_gate: Linear(hidden -> 1), sigmoid-gated shared expert */
snprintf(nm,sizeof(nm),"model.layers.%d.mlp.shared_expert_gate.weight", ai);
l->sh_gate = st_has(&m->S, nm) ? load_t_n(m, nm, c->hidden) : NULL;
if (c->is_attn[i]) {
- /* Gated Attention (full_attention) layer */
- #define LD3(field, suffix, want) snprintf(nm,sizeof(nm),"model.layers.%d.self_attn." suffix,ai); l->field = load_t_n(m,nm,(want))
- LD3(q, "q_proj.weight", (int64_t)c->q_heads * c->q_head_dim * c->hidden);
- LD3(k, "k_proj.weight", (int64_t)c->kv_heads * c->k_head_dim * c->hidden);
- LD3(v, "v_proj.weight", (int64_t)c->kv_heads * c->v_head_dim * c->hidden);
- LD3(o, "o_proj.weight", (int64_t)c->hidden * c->o_in);
- #undef LD3
- l->dn_qkv=l->dn_z=l->dn_b=l->dn_a=l->dn_conv=NULL;
- l->dn_dtbias=l->dn_alog=l->dn_norm=l->dn_out=NULL;
+ /* Gated Attention (full_attention) layer, dense projections int8-during-load */
+ snprintf(nm,sizeof(nm),"model.layers.%d.self_attn.q_proj.weight", ai);
+ load_tq(m, nm, c->hidden, q_out, quantize_dense, &l->q); QCOUNT(l->q);
+ snprintf(nm,sizeof(nm),"model.layers.%d.self_attn.k_proj.weight", ai);
+ load_tq(m, nm, c->hidden, kv_out, quantize_dense, &l->k); QCOUNT(l->k);
+ snprintf(nm,sizeof(nm),"model.layers.%d.self_attn.v_proj.weight", ai);
+ load_tq(m, nm, c->hidden, kv_out, quantize_dense, &l->v); QCOUNT(l->v);
+ snprintf(nm,sizeof(nm),"model.layers.%d.self_attn.o_proj.weight", ai);
+ load_tq(m, nm, c->o_in, c->hidden, quantize_dense, &l->o); QCOUNT(l->o);
+ l->dn_qkv=l->dn_z=(QW){0}; l->dn_b=l->dn_a=l->dn_conv=NULL;
+ l->dn_dtbias=l->dn_alog=l->dn_norm=NULL; l->dn_out=(QW){0};
} else {
/* Gated DeltaNet (linear_attention) layer */
- l->q=l->k=l->v=l->o=NULL;
+ l->q=l->k=l->v=l->o=(QW){0};
#define LD4(field, suffix, want) snprintf(nm,sizeof(nm),"model.layers.%d.linear_attn." suffix,ai); l->field = load_t_n(m,nm,(want))
int64_t vdim_tot = (int64_t)c->dn_vheads * c->dn_vdim;
- LD4(dn_qkv, "in_proj_qkv.weight", (int64_t)c->dn_conv_dim * c->hidden);
- LD4(dn_z, "in_proj_z.weight", vdim_tot * c->hidden);
+ snprintf(nm,sizeof(nm),"model.layers.%d.linear_attn.in_proj_qkv.weight", ai);
+ load_tq(m, nm, c->hidden, c->dn_conv_dim, quantize_dense, &l->dn_qkv); QCOUNT(l->dn_qkv);
+ snprintf(nm,sizeof(nm),"model.layers.%d.linear_attn.in_proj_z.weight", ai);
+ load_tq(m, nm, c->hidden, (int)vdim_tot, quantize_dense, &l->dn_z); QCOUNT(l->dn_z);
LD4(dn_b, "in_proj_b.weight", (int64_t)c->dn_vheads * c->hidden);
LD4(dn_a, "in_proj_a.weight", (int64_t)c->dn_vheads * c->hidden);
LD4(dn_conv,"conv1d.weight", (int64_t)c->dn_conv_dim * c->dn_convk);
LD4(dn_dtbias, "dt_bias", c->dn_vheads);
LD4(dn_alog,"A_log", c->dn_vheads);
LD4(dn_norm, "norm.weight", c->dn_vdim);
- LD4(dn_out, "out_proj.weight", (int64_t)c->hidden * vdim_tot);
#undef LD4
+ snprintf(nm,sizeof(nm),"model.layers.%d.linear_attn.out_proj.weight", ai);
+ load_tq(m, nm, (int)vdim_tot, c->hidden, quantize_dense, &l->dn_out); QCOUNT(l->dn_out);
}
}
+ #undef QCOUNT
+ if (quantize_dense)
+ fprintf(stderr, "[dense-i8] %d matrices quantized during load, %.1f GB f32 freed\n", qcount, qfreed/1073741824.0);
m->cache = calloc((size_t)c->n_layers, sizeof(LCache));
for (int i = layer_begin; i < layer_end; i++) {
m->cache[i].cap = cap;
@@ -1573,19 +1628,15 @@ static void slot_ensure_int8(Model *m, Slot *s) {
int64_t ng = (int64_t)c->inter * c->hidden, nd = (int64_t)c->hidden * c->inter;
int8_t *w = malloc((size_t)(ng + ng + nd));
if (!w) { fprintf(stderr, "OOM slot_ensure_int8\n"); exit(1); }
- const uint8_t *src4[3] = { s->g4, s->u4, s->d4 };
- int64_t lens[3] = { ng, ng, nd };
- int8_t *dst = w;
- for (int t = 0; t < 3; t++) {
- const uint8_t *p = src4[t];
- for (int64_t i = 0; i < lens[t]; i += 2) {
- uint8_t b = p[i >> 1];
- int8_t lo = (int8_t)(b & 0xF); if (lo & 8) lo -= 16;
- int8_t hi = (int8_t)((b >> 4) & 0xF); if (hi & 8) hi -= 16;
- dst[i] = lo; dst[i + 1] = hi;
- }
- dst += lens[t];
- }
+ /* #1271's unpack_int4_to_int8 (branchless, AVX2/NEON/scalar -- see its
+ * definition above load_expert_merged, which already uses it for the
+ * container's int4 read) instead of this function's own separate scalar
+ * copy of the same nibble-unpack math. g4/u4/d4 are three independently
+ * malloc'd packed buffers here (unlike load_expert_merged's single
+ * contiguous `raw`), so one call per segment. */
+ unpack_int4_to_int8(w, s->g4, ng);
+ unpack_int4_to_int8(w + ng, s->u4, ng);
+ unpack_int4_to_int8(w + ng + ng, s->d4, nd);
s->g = w; s->u = w + ng; s->d = w + ng + ng;
}
@@ -1796,9 +1847,9 @@ static void attention(Model *m, Layer *l, int layer, float *x, int S, int pos_ba
float *q = falloc((int64_t)S*q_out);
float *k = falloc((int64_t)S*kv_out);
float *vv= falloc((int64_t)S*kv_out);
- matmul_d(q, x, l->q, S, D, q_out);
- matmul_d(k, x, l->k, S, D, kv_out);
- matmul_d(vv, x, l->v, S, D, kv_out);
+ matmul_d(q, x, &l->q, S, D, q_out);
+ matmul_d(k, x, &l->k, S, D, kv_out);
+ matmul_d(vv, x, &l->v, S, D, kv_out);
/* split q into query (first hd) and gate (next gate_dim), both per head */
float *query = falloc((int64_t)S*H*hd);
float *gate = falloc((int64_t)S*H*gate_dim);
@@ -1860,7 +1911,7 @@ static void attention(Model *m, Layer *l, int layer, float *x, int S, int pos_ba
float g = gate_dim ? gate[o] : 0.f;
ag[o] = ctx[o] * (1.f / (1.f + expf(-g)));
}
- matmul_d(out, ag, l->o, S, H*hd, D);
+ matmul_d(out, ag, &l->o, S, H*hd, D);
free(q); free(k); free(vv); free(query); free(gate); free(ctx); free(ag);
}
@@ -1893,10 +1944,10 @@ static void qwen_shared_experts_cpu(Model *m, Layer *l, const float *x, int S,
if (B == 1) {
for (int s=0;s<S;s++) {
const float *xs=x+(int64_t)s*D;
- matmul_d(g,xs,l->sh_g,1,D,I);
- matmul_d(u,xs,l->sh_u,1,D,I);
+ matmul_d(g,xs,&l->sh_g,1,D,I);
+ matmul_d(u,xs,&l->sh_u,1,D,I);
for(int i=0;i<I;i++){float sv=g[i];g[i]=(sv/(1.f+expf(-sv)))*u[i];}
- matmul_d(hh,g,l->sh_d,1,I,D);
+ matmul_d(hh,g,&l->sh_d,1,I,D);
float sgate=1.f;
if(l->sh_gate){float sg=0.f;for(int i=0;i<D;i++)sg+=xs[i]*l->sh_gate[i];sgate=1.f/(1.f+expf(-sg));}
float *os=out+(int64_t)s*D;
@@ -1907,10 +1958,10 @@ static void qwen_shared_experts_cpu(Model *m, Layer *l, const float *x, int S,
float *bh=falloc((int64_t)B*D);
for(int base=0;base<S;base+=B){
int rows=S-base<B?S-base:B;
- matmul_d(bg,x+(int64_t)base*D,l->sh_g,rows,D,I);
- matmul_d(bu,x+(int64_t)base*D,l->sh_u,rows,D,I);
+ matmul_d(bg,x+(int64_t)base*D,&l->sh_g,rows,D,I);
+ matmul_d(bu,x+(int64_t)base*D,&l->sh_u,rows,D,I);
for(int64_t q=0;q<(int64_t)rows*I;q++){float sv=bg[q];bg[q]=(sv/(1.f+expf(-sv)))*bu[q];}
- matmul_d(bh,bg,l->sh_d,rows,I,D);
+ matmul_d(bh,bg,&l->sh_d,rows,I,D);
for(int s=0;s<rows;s++){
const float *xs=x+(int64_t)(base+s)*D;
float sgate=1.f;
@@ -2073,7 +2124,7 @@ static void moe(Model *m, Layer *l, int layer, float *x, int S, float *out) {
Cfg *c = &m->c; int D = c->hidden, E = c->n_experts, K = c->topk, I = c->inter;
float *logits = falloc((int64_t)S*E);
double _tr = tm_now();
- matmul_d(logits, x, l->gate, S, D, E);
+ matmul_d(logits, x, &l->gate, S, D, E);
tm_add(S, 4, tm_now()-_tr);
if (c->has_bias && l->gate_bias) {
for (int s = 0; s < S; s++) { float *pr = logits + (int64_t)s*E; for (int e = 0; e < E; e++) pr[e] += l->gate_bias[e]; }
@@ -2178,10 +2229,10 @@ static void moe(Model *m, Layer *l, int layer, float *x, int S, float *out) {
{
double _ts2 = tm_now();
int Ish = c->shared_inter;
- matmul_d(sh, xs, l->sh_g, 1, D, Ish);
- matmul_d(shu, xs, l->sh_u, 1, D, Ish);
+ matmul_d(sh, xs, &l->sh_g, 1, D, Ish);
+ matmul_d(shu, xs, &l->sh_u, 1, D, Ish);
for (int i = 0; i < Ish; i++) { float sv = sh[i]; sh[i] = (sv / (1.f + expf(-sv))) * shu[i]; }
- matmul_d(shd, sh, l->sh_d, 1, Ish, D);
+ matmul_d(shd, sh, &l->sh_d, 1, Ish, D);
float sgate = 1.f;
if (l->sh_gate) {
float sg = 0.f; const float *wg = l->sh_gate;
@@ -2271,8 +2322,8 @@ static void deltanet(Model *m, Layer *l, int layer, float *x, int S, int pos_bas
/* projections (single-token matmuls). One fused GEMV when this layer's
* dnproj is placed on a GPU, the two CPU matmuls otherwise. */
if (!qt_dnproj_matmul(layer, qkvz, xs, H, conv_dim + value_dim)) {
- matmul_d(qkv, xs, l->dn_qkv, 1, H, conv_dim);
- matmul_d(z, xs, l->dn_z, 1, H, value_dim);
+ matmul_d(qkv, xs, &l->dn_qkv, 1, H, conv_dim);
+ matmul_d(z, xs, &l->dn_z, 1, H, value_dim);
}
matmul(b, xs, l->dn_b, 1, H, vh);
matmul(a, xs, l->dn_a, 1, H, vh);
@@ -2370,7 +2421,7 @@ static void deltanet(Model *m, Layer *l, int layer, float *x, int S, int pos_bas
outr[(int64_t)h * vdim + d] = val * zr[d] / (1.f + expf(-zr[d]));
}
}
- matmul_d(out + (int64_t)s * H, outr, l->dn_out, 1, value_dim, H);
+ matmul_d(out + (int64_t)s * H, outr, &l->dn_out, 1, value_dim, H);
if (tm_on() && S==1){ g_dn_sub[3]+=tm_now()-_d0; }
if (layer == 0 && s == 0 && getenv("DN_DBG")) {
FILE *dbg = fopen(getenv("DN_DBG"), "wb");
@@ -2515,7 +2566,7 @@ static float *step(Model *m, const int *ids, int S, int pos_base) {
for (int p = 0; p + 1 < S; p++) {
rmsnorm_row(erow, x + (int64_t)p*D, m->final_norm, D, c->eps);
if (!qt_lmhead_matmul(elog, erow, D, c->vocab))
- matmul_d(elog, erow, m->lm_head, 1, D, c->vocab);
+ matmul_d(elog, erow, &m->lm_head, 1, D, c->vocab);
serve_echo(g_echo_id, pos_base + p + 1, ids[p+1], elog, c->vocab, g_echo_k);
}
free(erow); free(elog);
@@ -2525,7 +2576,7 @@ static float *step(Model *m, const int *ids, int S, int pos_base) {
float *logit = falloc(c->vocab);
double _th = tm_now();
if (!qt_lmhead_matmul(logit, last, D, c->vocab))
- matmul_d(logit, last, m->lm_head, 1, D, c->vocab);
+ matmul_d(logit, last, &m->lm_head, 1, D, c->vocab);
if (tm_on()) { tm_add(S, 5, tm_now()-_th); if (S==1) g_tm_dec_tokens++; else g_tm_pre_tokens += S; }
free(x); free(last);
if (lf) fclose(lf);
@@ -2586,7 +2637,7 @@ static void pilot_prefetch(Model *m, int lnext, const float *x, int S) {
Layer *l = &m->L[lnext];
float *nrm_x = falloc((int64_t)S * D);
for (int s = 0; s < S; s++) rmsnorm_row(nrm_x + (int64_t)s*D, x + (int64_t)s*D, l->post_ln, D, c->eps);
- matmul_d(logits, nrm_x, l->gate, S, D, E); /* int8 copy (f32 may be freed) */
+ matmul_d(logits, nrm_x, &l->gate, S, D, E); /* int8 copy (f32 may be freed) */
free(nrm_x);
for (int s = 0; s < S; s++) {
float *pr = logits + (int64_t)s*E;
@@ -3426,36 +3477,8 @@ int main(int argc, char **argv) {
g_expert_gs = m.c.expert_gs;
if (g_expert_gs) fprintf(stderr, "[qwen36] group-scaled experts: gs=%d\n", g_expert_gs);
fprintf(stderr, "resident weights loaded in %.1fs | RSS after load: %.2f GB\n", m.dense_load_s, rss_gb());
- /* quantize the large dense matrices to int8 (COLI_DENSE_I8=0 disables) */
- if (dense_i8_on()) {
- double tq = now_s();
- Cfg *qc = &m.c; int D2 = qc->hidden;
- int q_out = qc->q_heads * qc->q_head_dim, kv_out = qc->kv_heads * qc->k_head_dim;
- for (int i = 0; i < qc->n_layers; i++) {
- Layer *l = &m.L[i];
- qdw_register(l->q, D2, q_out); qdw_register(l->k, D2, kv_out);
- qdw_register(l->v, D2, kv_out); qdw_register(l->o, qc->o_in, D2);
- qdw_register(l->gate, D2, qc->n_experts);
- qdw_register(l->sh_g, D2, qc->shared_inter); qdw_register(l->sh_u, D2, qc->shared_inter);
- qdw_register(l->sh_d, qc->shared_inter, D2);
- qdw_register(l->dn_qkv, D2, qc->dn_conv_dim);
- qdw_register(l->dn_z, D2, qc->dn_vheads * qc->dn_vdim);
- qdw_register(l->dn_out, qc->dn_vheads * qc->dn_vdim, D2);
- }
- qdw_register(m.lm_head, D2, qc->vocab);
- /* Free the f32 originals -- the pointers only serve as lookup keys in
- * matmul_d from here on (never dereferenced again).
- * COLI_KEEP_F32=1 keeps them (debug). */
- double freed = 0;
- if (!getenv("COLI_KEEP_F32")) {
- for (int i = 0; i < g_qdw_n; i++) {
- freed += (double)g_qdw[i].I * g_qdw[i].O * sizeof(float);
- free((void*)g_qdw[i].w);
- }
- }
- fprintf(stderr, "[dense-i8] %d matrices quantized in %.1f s, %.1f GB f32 freed\n",
- g_qdw_n, now_s()-tq, freed/1073741824.0);
- }
+ /* dense matrices are quantized to int8 during model_init above (COLI_DENSE_I8=0
+ * disables it) -- see load_tq/QW; model_init_range already logged the count. */
/* Optional CUDA VRAM expert tier (COLI_CUDA=1): hot experts live in
* DEVICE_LOCAL memory across the configured GPUs, misses fall back to the
@@ -3485,15 +3508,11 @@ int main(int argc, char **argv) {
* No entry (dense-i8 off) means nothing to offer, and the CPU path stands. */
{
int O_qkv = m.c.dn_conv_dim, O_z = m.c.dn_vheads * m.c.dn_vdim;
- for (int i = 0; i < g_qdw_n; i++)
- if (g_qdw[i].w == m.lm_head)
- qt_trunk_offer("lmhead", 0, (size_t)g_qdw[i].I * g_qdw[i].O + (size_t)g_qdw[i].O * sizeof(float));
+ if (m.lm_head.q)
+ qt_trunk_offer("lmhead", 0, (size_t)m.lm_head.I * m.lm_head.O + (size_t)m.lm_head.O * sizeof(float));
for (int i = 0; i < m.c.n_layers; i++) {
if (m.c.is_attn[i]) continue;
- int have = 0;
- for (int j = 0; j < g_qdw_n; j++)
- if (g_qdw[j].w == m.L[i].dn_qkv || g_qdw[j].w == m.L[i].dn_z) have++;
- if (have == 2)
+ if (m.L[i].dn_qkv.q && m.L[i].dn_z.q)
qt_trunk_offer("dnproj", i, (size_t)(O_qkv + O_z) * m.c.hidden + (size_t)(O_qkv + O_z) * sizeof(float));
}
}
@@ -3504,11 +3523,8 @@ int main(int argc, char **argv) {
/* R4 role split: park the dense-i8 lm_head on COLI_LMHEAD_GPU. The
* qdw entry keyed by m.lm_head holds the int8 rows + per-row scales
* the CPU path uses; the GPU applies the identical semantics. */
- for (int i = 0; i < g_qdw_n; i++)
- if (g_qdw[i].w == m.lm_head) {
- qt_lmhead_init(g_qdw[i].q, g_qdw[i].sc, g_qdw[i].I, g_qdw[i].O);
- break;
- }
+ if (m.lm_head.q)
+ qt_lmhead_init(m.lm_head.q, m.lm_head.sc, m.lm_head.I, m.lm_head.O);
/* R4 step 2: DeltaNet input projections, per layer, wherever
* COLI_PLACE puts them. qkv and z are both [O_x, hidden] int8 with
* per-row scales, so fusing them is a concatenation along O -- two
@@ -3522,11 +3538,8 @@ int main(int argc, char **argv) {
if (m.c.is_attn[i]) continue;
int dev = qt_place_of("dnproj", i);
if (dev == QT_PLACE_CPU) continue;
- const int8_t *q1 = NULL, *q2 = NULL; const float *s1 = NULL, *s2 = NULL;
- for (int j = 0; j < g_qdw_n; j++) {
- if (g_qdw[j].w == m.L[i].dn_qkv) { q1 = g_qdw[j].q; s1 = g_qdw[j].sc; }
- if (g_qdw[j].w == m.L[i].dn_z) { q2 = g_qdw[j].q; s2 = g_qdw[j].sc; }
- }
+ const int8_t *q1 = m.L[i].dn_qkv.q, *q2 = m.L[i].dn_z.q;
+ const float *s1 = m.L[i].dn_qkv.sc, *s2 = m.L[i].dn_z.sc;
if (!q1 || !q2) continue; /* dense-i8 off: CPU path stands */
int8_t *qf = malloc((size_t)Of * Hd);
float *sf = malloc((size_t)Of * sizeof(float));
@@ -3663,12 +3676,12 @@ typedef struct {
static void qwen36_segment_layer_free(Layer *layer) {
free(layer->in_ln); free(layer->post_ln);
- free(layer->q); free(layer->k); free(layer->v); free(layer->o);
- free(layer->qn); free(layer->kn); free(layer->gate); free(layer->gate_bias);
- free(layer->sh_g); free(layer->sh_u); free(layer->sh_d); free(layer->sh_gate);
- free(layer->dn_qkv); free(layer->dn_z); free(layer->dn_b); free(layer->dn_a);
+ qw_free(&layer->q); qw_free(&layer->k); qw_free(&layer->v); qw_free(&layer->o);
+ free(layer->qn); free(layer->kn); qw_free(&layer->gate); free(layer->gate_bias);
+ qw_free(&layer->sh_g); qw_free(&layer->sh_u); qw_free(&layer->sh_d); free(layer->sh_gate);
+ qw_free(&layer->dn_qkv); qw_free(&layer->dn_z); free(layer->dn_b); free(layer->dn_a);
free(layer->dn_conv); free(layer->dn_dtbias); free(layer->dn_alog);
- free(layer->dn_norm); free(layer->dn_out);
+ free(layer->dn_norm); qw_free(&layer->dn_out);
}
static void qwen36_segment_model_destroy(Qwen36SegmentEngine *engine) {
@@ -4056,7 +4069,7 @@ static void qwen36_edge_engine_destroy(void *engine_impl) {
Qwen36EdgeEngine *engine = (Qwen36EdgeEngine *)engine_impl;
if (!engine) return;
free(engine->model.embed);
- free(engine->model.lm_head);
+ qw_free(&engine->model.lm_head);
free(engine->model.final_norm);
free(engine->model.c.is_attn);
st_destroy(&engine->model.S);
@@ -4095,9 +4108,10 @@ static int qwen36_edge_engine_open(
engine->model.embed = load_t_n(
&engine->model, "model.embed_tokens.weight",
(int64_t)config->vocab * config->hidden);
- engine->model.lm_head = load_t_n(
- &engine->model, "lm_head.weight",
- (int64_t)config->vocab * config->hidden);
+ /* quantize=0: this engine never ran the old post-hoc qdw_register pass
+ * either (only main()'s static Model did), so lm_head stays f32-only here,
+ * exactly as before. */
+ load_tq(&engine->model, "lm_head.weight", config->hidden, config->vocab, 0, &engine->model.lm_head);
engine->model.final_norm = load_t_n(
&engine->model, "model.norm.weight", config->hidden);
engine->model.quant_bits = container_layer_is_int4(&engine->model, 0) ? 4 : 8;
@@ -4245,7 +4259,7 @@ static int qwen36_edge_select(void *engine_impl,
}
rmsnorm_row(normalized, input + (size_t)row * config->hidden,
engine->model.final_norm, config->hidden, config->eps);
- matmul_d(logits, normalized, engine->model.lm_head,
+ matmul_d(logits, normalized, &engine->model.lm_head,
1, config->hidden, config->vocab);
if (coli_edge_argmax(logits, (uint32_t)config->vocab,
&request->token_ids[row],
@@ -4276,7 +4290,7 @@ static int qwen36_edge_logits(void *engine_impl,
rmsnorm_row(normalized, input + (size_t)row * config->hidden,
engine->model.final_norm, config->hidden, config->eps);
matmul_d(request->logits + (size_t)row * config->vocab,
- normalized, engine->model.lm_head,
+ normalized, &engine->model.lm_head,
1, config->hidden, config->vocab);
}
free(normalized);
diff --git a/c/st.h b/c/st.h
index 8ad5ffd3..e5cd84ad 100644
--- a/c/st.h
+++ b/c/st.h
@@ -138,6 +138,121 @@ static inline float f16_to_f32(uint16_t h) {
float f; memcpy(&f, &u, 4); return f;
}
+/* ---- bulk BF16/F16 -> F32, AVX2/SSE4.1/scalar tiers --------------------
+ * st_read_f32/st_read_slice_f32 convert whole tensors (up to the embed/
+ * lm_head matrix, vocab*hidden elements) through bf16_to_f32/f16_to_f32 one
+ * halfword at a time; that loop is pure overhead once the read syscall is
+ * off the critical path. The tiers below batch it, same idea and layering
+ * as gsgemv.h's AVX2/SSE4.1 kernels (immintrin.h only under the ISA guard,
+ * sse41_kernels.h not needed here -- no FMA, no shared load helper to reuse).
+ *
+ * BF16 -> F32 is an exact zero-pad widening for every bit pattern (BF16
+ * shares F32's 8-bit exponent field, so there is no special-casing --
+ * zero, normal, subnormal, inf, NaN all take the same `<<16`), so the
+ * vectorized tiers cannot disagree with the scalar reference.
+ *
+ * F16 -> F32's zero/normal/inf-NaN classes are each the same closed-form
+ * bit algebra as the scalar reference above, just run on several lanes at
+ * once -- no reassociation, nothing to round, so still bit-exact. True
+ * subnormals (exp==0, man!=0) need the scalar reference's shift-to-normalize
+ * loop, which does not vectorize; those (rare in real model weights) fall
+ * back to f16_to_f32 per element. Exhaustive verification (all 65536
+ * patterns per format) lives in tests/test_st_f16_bf16_simd.c. */
+#if defined(__AVX2__) || defined(__SSE4_1__)
+#include <immintrin.h>
+#endif
+
+#if defined(__AVX2__)
+static void bf16_to_f32_bulk(const uint16_t *src, float *dst, int64_t n) {
+ int64_t i = 0;
+ for (; i + 8 <= n; i += 8) {
+ __m128i h = _mm_loadu_si128((const __m128i*)(src + i));
+ __m256i w = _mm256_slli_epi32(_mm256_cvtepu16_epi32(h), 16);
+ _mm256_storeu_ps(dst + i, _mm256_castsi256_ps(w));
+ }
+ for (; i < n; i++) dst[i] = bf16_to_f32(src[i]);
+}
+static void f16_to_f32_bulk(const uint16_t *src, float *dst, int64_t n) {
+ int64_t i = 0;
+ const __m256i vsign_mask = _mm256_set1_epi32(0x8000);
+ const __m256i vexp_mask = _mm256_set1_epi32(0x1F);
+ const __m256i vman_mask = _mm256_set1_epi32(0x3FF);
+ const __m256i v112 = _mm256_set1_epi32(112);
+ const __m256i vinfnan_e = _mm256_set1_epi32(0x7F800000);
+ const __m256i vzero = _mm256_setzero_si256();
+ const __m256i v31 = _mm256_set1_epi32(31);
+ for (; i + 8 <= n; i += 8) {
+ __m128i h16 = _mm_loadu_si128((const __m128i*)(src + i));
+ __m256i h = _mm256_cvtepu16_epi32(h16);
+ __m256i sign = _mm256_slli_epi32(_mm256_and_si256(h, vsign_mask), 16);
+ __m256i exp = _mm256_and_si256(_mm256_srli_epi32(h, 10), vexp_mask);
+ __m256i man = _mm256_and_si256(h, vman_mask);
+ __m256i normal_u = _mm256_or_si256(sign, _mm256_or_si256(
+ _mm256_slli_epi32(_mm256_add_epi32(exp, v112), 23), _mm256_slli_epi32(man, 13)));
+ __m256i infnan_u = _mm256_or_si256(sign, _mm256_or_si256(vinfnan_e, _mm256_slli_epi32(man, 13)));
+ __m256i exp_is_zero = _mm256_cmpeq_epi32(exp, vzero);
+ __m256i man_is_zero = _mm256_cmpeq_epi32(man, vzero);
+ __m256i is_zero = _mm256_and_si256(exp_is_zero, man_is_zero);
+ __m256i is_subnorm = _mm256_andnot_si256(man_is_zero, exp_is_zero);
+ __m256i is_infnan = _mm256_cmpeq_epi32(exp, v31);
+ __m256i result = _mm256_blendv_epi8(normal_u, sign, is_zero);
+ result = _mm256_blendv_epi8(result, infnan_u, is_infnan);
+ _mm256_storeu_ps(dst + i, _mm256_castsi256_ps(result));
+ int m = _mm256_movemask_ps(_mm256_castsi256_ps(is_subnorm));
+ if (m) for (int k = 0; k < 8; k++) if ((m >> k) & 1) dst[i+k] = f16_to_f32(src[i+k]);
+ }
+ for (; i < n; i++) dst[i] = f16_to_f32(src[i]);
+}
+#elif defined(__SSE4_1__)
+static void bf16_to_f32_bulk(const uint16_t *src, float *dst, int64_t n) {
+ int64_t i = 0;
+ for (; i + 4 <= n; i += 4) {
+ __m128i h = _mm_loadl_epi64((const __m128i*)(src + i));
+ __m128i w = _mm_slli_epi32(_mm_cvtepu16_epi32(h), 16);
+ _mm_storeu_ps(dst + i, _mm_castsi128_ps(w));
+ }
+ for (; i < n; i++) dst[i] = bf16_to_f32(src[i]);
+}
+static void f16_to_f32_bulk(const uint16_t *src, float *dst, int64_t n) {
+ int64_t i = 0;
+ const __m128i vsign_mask = _mm_set1_epi32(0x8000);
+ const __m128i vexp_mask = _mm_set1_epi32(0x1F);
+ const __m128i vman_mask = _mm_set1_epi32(0x3FF);
+ const __m128i v112 = _mm_set1_epi32(112);
+ const __m128i vinfnan_e = _mm_set1_epi32(0x7F800000);
+ const __m128i vzero = _mm_setzero_si128();
+ const __m128i v31 = _mm_set1_epi32(31);
+ for (; i + 4 <= n; i += 4) {
+ __m128i h16 = _mm_loadl_epi64((const __m128i*)(src + i));
+ __m128i h = _mm_cvtepu16_epi32(h16);
+ __m128i sign = _mm_slli_epi32(_mm_and_si128(h, vsign_mask), 16);
+ __m128i exp = _mm_and_si128(_mm_srli_epi32(h, 10), vexp_mask);
+ __m128i man = _mm_and_si128(h, vman_mask);
+ __m128i normal_u = _mm_or_si128(sign, _mm_or_si128(
+ _mm_slli_epi32(_mm_add_epi32(exp, v112), 23), _mm_slli_epi32(man, 13)));
+ __m128i infnan_u = _mm_or_si128(sign, _mm_or_si128(vinfnan_e, _mm_slli_epi32(man, 13)));
+ __m128i exp_is_zero = _mm_cmpeq_epi32(exp, vzero);
+ __m128i man_is_zero = _mm_cmpeq_epi32(man, vzero);
+ __m128i is_zero = _mm_and_si128(exp_is_zero, man_is_zero);
+ __m128i is_subnorm = _mm_andnot_si128(man_is_zero, exp_is_zero);
+ __m128i is_infnan = _mm_cmpeq_epi32(exp, v31);
+ __m128i result = _mm_blendv_epi8(normal_u, sign, is_zero);
+ result = _mm_blendv_epi8(result, infnan_u, is_infnan);
+ _mm_storeu_ps(dst + i, _mm_castsi128_ps(result));
+ int m = _mm_movemask_ps(_mm_castsi128_ps(is_subnorm));
+ if (m) for (int k = 0; k < 4; k++) if ((m >> k) & 1) dst[i+k] = f16_to_f32(src[i+k]);
+ }
+ for (; i < n; i++) dst[i] = f16_to_f32(src[i]);
+}
+#else
+static void bf16_to_f32_bulk(const uint16_t *src, float *dst, int64_t n) {
+ for (int64_t i = 0; i < n; i++) dst[i] = bf16_to_f32(src[i]);
+}
+static void f16_to_f32_bulk(const uint16_t *src, float *dst, int64_t n) {
+ for (int64_t i = 0; i < n; i++) dst[i] = f16_to_f32(src[i]);
+}
+#endif
+
static int st_open_fd(shards *S, const char *path) {
for (int i = 0; i < S->nfd; i++) if (!strcmp(S->paths[i], path)) return S->fds[i];
int fd = open(path, COMPAT_O_RDONLY);
@@ -954,9 +1069,9 @@ static int64_t st_read_f32(shards *S, const char *name, float *out, int drop) {
if (t->dtype == 2) {
memcpy(out, raw, t->nbytes);
} else if (t->dtype == 0) {
- uint16_t *p = (uint16_t *)raw; for (int64_t i = 0; i < t->numel; i++) out[i] = bf16_to_f32(p[i]);
+ bf16_to_f32_bulk((uint16_t *)raw, out, t->numel);
} else {
- uint16_t *p = (uint16_t *)raw; for (int64_t i = 0; i < t->numel; i++) out[i] = f16_to_f32(p[i]);
+ f16_to_f32_bulk((uint16_t *)raw, out, t->numel);
}
free(raw);
if (drop) posix_fadvise(t->fd, t->off, t->nbytes, POSIX_FADV_DONTNEED);
@@ -1342,8 +1457,8 @@ static void st_read_slice_f32(shards *S, const char *name, int64_t elem_off, int
if (nb) st_pread_full(t->fd, raw, nb, boff, "pread slice"); /* dev #331: chunked + EINTR + honest short-read */
if (nb) {
if (t->dtype == 2) memcpy(out, raw, (size_t)nb);
- else if (t->dtype == 0) { uint16_t *p = raw; for (int64_t i = 0; i < n_elems; i++) out[i] = bf16_to_f32(p[i]); }
- else { uint16_t *p = raw; for (int64_t i = 0; i < n_elems; i++) out[i] = f16_to_f32(p[i]); }
+ else if (t->dtype == 0) bf16_to_f32_bulk((uint16_t *)raw, out, n_elems);
+ else f16_to_f32_bulk((uint16_t *)raw, out, n_elems);
}
free(raw);
if (drop && nb) posix_fadvise(t->fd, boff, nb, POSIX_FADV_DONTNEED);
diff --git a/c/tests/bench_qwen36_dense_batch.c b/c/tests/bench_qwen36_dense_batch.c
index 63f0fc22..7e29d5b3 100644
--- a/c/tests/bench_qwen36_dense_batch.c
+++ b/c/tests/bench_qwen36_dense_batch.c
@@ -39,13 +39,13 @@ static double shared_run(Model *m,Layer *l,const float *x,const float *seed,
static int shared_benchmark(void) {
Model m;memset(&m,0,sizeof(m));m.c.hidden=I;m.c.shared_inter=O;
Layer l;memset(&l,0,sizeof(l));
- l.sh_g=falloc((int64_t)O*I);l.sh_u=falloc((int64_t)O*I);
- l.sh_d=falloc((int64_t)I*O);l.sh_gate=falloc(I);
- for(int64_t i=0;i<(int64_t)O*I;i++){l.sh_g[i]=value(i,2);l.sh_u[i]=value(i,3);}
- for(int64_t i=0;i<(int64_t)I*O;i++)l.sh_d[i]=value(i,4);
+ l.sh_g.w=falloc((int64_t)O*I);l.sh_u.w=falloc((int64_t)O*I);
+ l.sh_d.w=falloc((int64_t)I*O);l.sh_gate=falloc(I);
+ for(int64_t i=0;i<(int64_t)O*I;i++){((float*)l.sh_g.w)[i]=value(i,2);((float*)l.sh_u.w)[i]=value(i,3);}
+ for(int64_t i=0;i<(int64_t)I*O;i++)((float*)l.sh_d.w)[i]=value(i,4);
for(int i=0;i<I;i++)l.sh_gate[i]=value(i,5);
- qdw_register(l.sh_g,I,O);qdw_register(l.sh_u,I,O);qdw_register(l.sh_d,O,I);
- if(g_qdw_n!=3){fprintf(stderr,"FAIL: expected three dense-int8 copies, got %d\n",g_qdw_n);return 1;}
+ qw_quantize(l.sh_g.w,I,O,&l.sh_g);qw_quantize(l.sh_u.w,I,O,&l.sh_u);qw_quantize(l.sh_d.w,O,I,&l.sh_d);
+ if(!l.sh_g.q||!l.sh_u.q||!l.sh_d.q){fprintf(stderr,"FAIL: expected three dense-int8 copies\n");return 1;}
float *x=falloc((int64_t)S*I),*seed=falloc((int64_t)S*I);
float *a=falloc((int64_t)S*I),*b=falloc((int64_t)S*I);
for(int64_t i=0;i<(int64_t)S*I;i++){x[i]=value(i,6);seed[i]=value(i,7);}
@@ -60,8 +60,7 @@ static int shared_benchmark(void) {
printf("qwen shared int8: S=%d D=%d I=%d weights=%.1f MiB\n",S,I,O,
3.0*I*O/1048576.0);
printf("scalar %.6f s batch %.6f s speedup %.2fx calls %d -> 3\n",ts,tb,ts/tb,S*3);
- for(int i=0;i<g_qdw_n;i++){free(g_qdw[i].q);free(g_qdw[i].sc);}g_qdw_n=0;
- free(l.sh_g);free(l.sh_u);free(l.sh_d);free(l.sh_gate);
+ qw_free(&l.sh_g);qw_free(&l.sh_u);qw_free(&l.sh_d);free(l.sh_gate);
free(x);free(seed);free(a);free(b);unsetenv("QWEN_SHARED_BATCH");unsetenv("QWEN_DENSE_BATCH");
return 0;
}
diff --git a/c/tests/test_qwen36_dense_batch.c b/c/tests/test_qwen36_dense_batch.c
index 69288725..8f7807d6 100644
--- a/c/tests/test_qwen36_dense_batch.c
+++ b/c/tests/test_qwen36_dense_batch.c
@@ -48,21 +48,34 @@ static void one_shape(int S, int I, int O) {
free(x);free(q);free(sc);free(ref);free(got);
}
-static void clear_qdw(void) {
- for(int i=0;i<g_qdw_n;i++){free(g_qdw[i].q);free(g_qdw[i].sc);}
- g_qdw_n=0;
+static void env_set(const char *name,const char *value) {
+#ifdef _WIN32
+ _putenv_s(name,value);
+#else
+ setenv(name,value,1);
+#endif
}
+static void env_unset(const char *name) {
+#ifdef _WIN32
+ _putenv_s(name,"");
+#else
+ unsetenv(name);
+#endif
+}
+
+static void clear_qw(Layer *l) { qw_free(&l->sh_g); qw_free(&l->sh_u); qw_free(&l->sh_d); }
static void shared_case(const char *format,int quantized) {
enum { S=12,D=64,I=32 };
Model m;memset(&m,0,sizeof(m));m.c.hidden=D;m.c.shared_inter=I;
Layer l;memset(&l,0,sizeof(l));
- l.sh_g=falloc((int64_t)I*D);l.sh_u=falloc((int64_t)I*D);
- l.sh_d=falloc((int64_t)D*I);l.sh_gate=falloc(D);
- for(int64_t i=0;i<(int64_t)I*D;i++){l.sh_g[i]=input_value(i,2);l.sh_u[i]=input_value(i,3);}
- for(int64_t i=0;i<(int64_t)D*I;i++)l.sh_d[i]=input_value(i,4);
+ l.sh_g.w=falloc((int64_t)I*D);l.sh_u.w=falloc((int64_t)I*D);
+ l.sh_d.w=falloc((int64_t)D*I);l.sh_gate=falloc(D);
+ l.sh_g.I=D;l.sh_g.O=I; l.sh_u.I=D;l.sh_u.O=I; l.sh_d.I=I;l.sh_d.O=D;
+ for(int64_t i=0;i<(int64_t)I*D;i++){((float*)l.sh_g.w)[i]=input_value(i,2);((float*)l.sh_u.w)[i]=input_value(i,3);}
+ for(int64_t i=0;i<(int64_t)D*I;i++)((float*)l.sh_d.w)[i]=input_value(i,4);
for(int i=0;i<D;i++)l.sh_gate[i]=input_value(i,5);
- if(quantized){qdw_register(l.sh_g,D,I);qdw_register(l.sh_u,D,I);qdw_register(l.sh_d,I,D);}
+ if(quantized){qw_quantize(l.sh_g.w,D,I,&l.sh_g);qw_quantize(l.sh_u.w,D,I,&l.sh_u);qw_quantize(l.sh_d.w,I,D,&l.sh_d);}
float *x=falloc((int64_t)S*D),*seed=falloc((int64_t)S*D);
float *ref=falloc((int64_t)S*D),*got=falloc((int64_t)S*D);
float *g=falloc(I),*u=falloc(I),*hh=falloc(D);
@@ -88,7 +101,7 @@ static void shared_case(const char *format,int quantized) {
(unsigned long long)g_qwen_matmul_d_calls);
printf("qwen shared batch exact: format=%s S=%d calls=%d -> 3\n",format,S,S*3);
- clear_qdw();free(l.sh_g);free(l.sh_u);free(l.sh_d);free(l.sh_gate);
+ clear_qw(&l);free(l.sh_gate);
free(x);free(seed);free(ref);free(got);free(g);free(u);free(hh);
}