Skip to content

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

C

feat(qwen36): group-scaled int4 (gs64) containers — converter flag + CPU read path

kreuzzelg5a0715e744da
diff --git a/c/qwen36.c b/c/qwen36.c
index 99da321c..567a2042 100644
--- a/c/qwen36.c
+++ b/c/qwen36.c
@@ -543,6 +543,7 @@ typedef struct {
uint8_t *is_attn; /* [n_layers] 1 if Gated Attention layer, 0 if DeltaNet */
/* Gated DeltaNet (linear_attention) dims, read from qwen36_meta.json. */
int dn_vheads, dn_kheads, dn_kdim, dn_vdim, dn_convk, dn_conv_dim;
+ int expert_gs; /* expert scale group size along input dim; 0 = per-row */
} Cfg;
/* ---------- per-layer dense weights ---------- */
@@ -748,6 +749,58 @@ static void matmul_q(float *y, const float *x, const int8_t *q, const float *sca
#endif
}
+/* Group-scaled int8 GEMV: one f32 scale per `gs` input elements per row
+ * (gs64 expert containers). Row layout of `scale`: [O][I/gs] row-major. */
+static int g_expert_gs = 0; /* set from qwen36_meta.json (expert_gs) at load */
+static void matmul_q_gs(float *y, const float *x, const int8_t *q, const float *scale,
+ int I, int O, int gs) {
+ int ng = (I + gs - 1) / gs;
+#if defined(__AVX2__) && defined(__FMA__)
+ if ((gs & 31) == 0) {
+ #pragma omp parallel for schedule(static) if(O >= 256)
+ for (int o = 0; o < O; o++) {
+ const int8_t *w = q + (int64_t)o * I;
+ const float *sc = scale + (int64_t)o * ng;
+ float acc = 0.f;
+ for (int gi = 0; gi < ng; gi++) {
+ __m256 a0 = _mm256_setzero_ps(), a1 = _mm256_setzero_ps();
+ int base = gi * gs, end = base + gs; if (end > I) end = I;
+ for (int i = base; i + 16 <= end; i += 16) {
+ __m128i b0 = _mm_loadu_si128((const __m128i*)(w + i));
+ a0 = _mm256_fmadd_ps(_mm256_loadu_ps(x+i), _mm256_cvtepi32_ps(_mm256_cvtepi8_epi32(b0)), a0);
+ a1 = _mm256_fmadd_ps(_mm256_loadu_ps(x+i+8), _mm256_cvtepi32_ps(_mm256_cvtepi8_epi32(_mm_srli_si128(b0,8))), a1);
+ }
+ a0 = _mm256_add_ps(a0, a1);
+ __m128 s = _mm_add_ps(_mm256_castps256_ps128(a0), _mm256_extractf128_ps(a0,1));
+ s = _mm_add_ps(s, _mm_movehl_ps(s,s));
+ s = _mm_add_ss(s, _mm_shuffle_ps(s,s,1));
+ acc += _mm_cvtss_f32(s) * sc[gi];
+ }
+ y[o] = acc;
+ }
+ return;
+ }
+#endif
+ #pragma omp parallel for schedule(static) if(O >= 256)
+ for (int o = 0; o < O; o++) {
+ const int8_t *w = q + (int64_t)o * I;
+ const float *sc = scale + (int64_t)o * ng;
+ float acc = 0.f;
+ for (int gi = 0; gi < ng; gi++) {
+ int base = gi * gs, end = base + gs; if (end > I) end = I;
+ float part = 0.f;
+ for (int i = base; i < end; i++) part += x[i] * (float)w[i];
+ acc += part * sc[gi];
+ }
+ y[o] = acc;
+ }
+}
+/* Expert-GEMV dispatch: per-row scales (classic) or grouped (gs64 container). */
+static void matmul_qe(float *y, const float *x, const int8_t *q, const float *scale, int I, int O) {
+ if (g_expert_gs) matmul_q_gs(y, x, q, scale, I, O, g_expert_gs);
+ else matmul_q(y, x, q, scale, I, O);
+}
+
/* ---- 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. */
@@ -852,6 +905,7 @@ static void load_meta(Cfg *c, const char *snap) {
G("q_heads", q_heads); G("kv_heads", kv_heads); G("head_dim", head_dim);
G("q_head_dim", q_head_dim); G("k_head_dim", k_head_dim); G("v_head_dim", v_head_dim);
G("o_in", o_in); G("rope_dim", rope_dim); G("qk_rope_head_dim", rope_dim);
+ G("expert_gs", expert_gs);
G("num_experts", n_experts); G("topk", topk);
G("moe_inter", inter); G("shared_inter", shared_inter);
G("n_group", n_group); G("topk_group", topk_group);
@@ -1007,6 +1061,10 @@ static void model_init(Model *m, const char *snap, int cap, int bits) {
m->dense_load_s = now_s() - t0;
}
+/* scale counts per expert matrix: per-row (gs=0) or grouped along input dim */
+static int64_t scale_count_gu(const Cfg *c){ return c->expert_gs ? (int64_t)c->inter * ((c->hidden + c->expert_gs - 1) / c->expert_gs) : c->inter; }
+static int64_t scale_count_d (const Cfg *c){ return c->expert_gs ? (int64_t)c->hidden * ((c->inter + c->expert_gs - 1) / c->expert_gs) : c->hidden; }
+
static void slot_ensure_allocated(Model *m, Slot *s) {
if (s->g) return;
Cfg *c = &m->c;
@@ -1017,10 +1075,10 @@ static void slot_ensure_allocated(Model *m, Slot *s) {
s->g = w_block;
s->u = w_block + ng;
s->d = w_block + ng + ng;
- float *s_block = falloc(c->inter + c->inter + c->hidden);
+ float *s_block = falloc(2*scale_count_gu(c) + scale_count_d(c));
s->gs = s_block;
- s->us = s_block + c->inter;
- s->ds = s_block + c->inter + c->inter;
+ s->us = s_block + scale_count_gu(c);
+ s->ds = s_block + 2*scale_count_gu(c);
s->pinned = 0;
s->is_int4 = 0;
s->g4 = s->u4 = s->d4 = NULL; /* packed int4 (allocated on int4 load if GPU int4 active) */
@@ -1034,7 +1092,7 @@ static void load_expert_merged(Model *m, int layer, int eid, Slot *s) {
Cfg *cc = &m->c;
int64_t ng = (int64_t)cc->inter * cc->hidden, nd = (int64_t)cc->hidden * cc->inter;
int64_t want_w = ng + ng + nd;
- int64_t want_s = (int64_t)cc->inter + cc->inter + cc->hidden;
+ int64_t want_s = 2*scale_count_gu(cc) + scale_count_d(cc);
st_tensor *tw = st_find(&m->S, nm), *ts = st_find(&m->S, qsnm);
if (!tw || (tw->nbytes != want_w && tw->nbytes != want_w / 2)) {
fprintf(stderr, "%s: expert weight is %lld bytes — expected %lld (int8) or %lld (int4)\n",
@@ -1389,10 +1447,10 @@ static void moe(Model *m, Layer *l, int layer, float *x, int S, float *out) {
{
for (int kk = 0; kk < K; kk++) {
Slot *e; expert_get(m, layer, idx[kk], &e);
- matmul_q(g, xs, e->g, e->gs, D, I);
- matmul_q(u, xs, e->u, e->us, D, I);
+ matmul_qe(g, xs, e->g, e->gs, D, I);
+ matmul_qe(u, xs, e->u, e->us, D, I);
for (int i = 0; i < I; i++) { float gv = g[i]; g[i] = (gv / (1.f + expf(-gv))) * u[i]; }
- matmul_q(hh, g, e->d, e->ds, I, D);
+ matmul_qe(hh, g, e->d, e->ds, I, D);
float w = val[kk];
float *os = out + (int64_t)s*D;
for (int d = 0; d < D; d++) os[d] += w * hh[d];
@@ -2016,6 +2074,8 @@ int main(int argc, char **argv) {
}
Model m; model_init(&m, snap, cap, bits);
+ 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()) {
diff --git a/c/tools/convert_qwen36.py b/c/tools/convert_qwen36.py
index c5126c00..a694080d 100644
--- a/c/tools/convert_qwen36.py
+++ b/c/tools/convert_qwen36.py
@@ -84,7 +84,25 @@ def pack_int4(q: "torch.Tensor") -> "torch.Tensor":
return (lo | hi).contiguous()
-def make_merged(gate, up, down, ebits):
+def quantize_row_grouped(w: "torch.Tensor", bits: int, gs: int):
+ """Group-wise symmetric quantization: one f32 scale per `gs` input elements
+ per row (like GLM's gs64 containers). Returns (q int8 [O,I], scales f32
+ [O, ceil(I/gs)] flattened row-major)."""
+ qmax = (1 << (bits - 1)) - 1
+ O, I = w.shape[0], w.reshape(w.shape[0], -1).shape[1]
+ w_f32 = w.reshape(O, -1).float()
+ pad = (-I) % gs
+ if pad:
+ w_f32 = torch.nn.functional.pad(w_f32, (0, pad))
+ ng = w_f32.shape[1] // gs
+ g = w_f32.view(O, ng, gs)
+ scales = g.abs().amax(dim=2, keepdim=True).clamp(min=1e-12) / qmax
+ q = (g / scales).round().clamp(-qmax - 1, qmax).to(torch.int8).view(O, -1)[:, :I]
+ return q, scales.view(O, ng)
+
+
+def make_merged(gate, up, down, ebits, gs=0):
+ gsz = gs # local `gs` is rebound to the gate scales below -- keep the group size safe
"""gate/up: [inter, H]; down: [H, inter] (torch, any fp).
-> (merged_weight, qs f32 1D).
@@ -96,6 +114,9 @@ def make_merged(gate, up, down, ebits):
qs (per-row f32 scales) is identical in both cases.
"""
def q(t):
+ if gsz:
+ qt, s = quantize_row_grouped(t, ebits, gsz) # [O, ng] scales
+ return qt, s.reshape(-1)
qt, s = quantize_row(t.reshape(t.shape[0], -1), ebits) # rows along dim0
return qt, s
gq, gs = q(gate)
@@ -189,6 +210,9 @@ def main():
src.add_argument("--model", help="Local HF checkpoint directory")
ap.add_argument("--out", required=False, help="Output container directory")
ap.add_argument("--ebits", type=int, default=4, help="Expert quant bits (2..8, default 4)")
+ ap.add_argument("--gs", type=int, default=0,
+ help="Group size for expert scales (e.g. 64). 0 = per-row (default). "
+ "Group-scaled containers need engine support (expert_gs in meta).")
ap.add_argument("--upload-repo", help="Push the finished container to this HF repo ID")
ap.add_argument("--hf-token", help="HF token (defaults to HF_TOKEN env / cached login)")
ap.add_argument("--low-disk", action="store_true",
@@ -430,7 +454,7 @@ def main():
dk = k.replace("gate_up_proj", "down_proj")
down = get_tensor(dk).float() # [E, H, inter]
for e in range(E):
- mw, qs = make_merged(gate[e], up[e], down[e], args.ebits)
+ mw, qs = make_merged(gate[e], up[e], down[e], args.ebits, gs=args.gs)
tens[f"model.layers.{a}.mlp.experts.{e}.merged_weight"] = mw
tens[f"model.layers.{a}.mlp.experts.{e}.qs"] = qs
continue
@@ -442,7 +466,7 @@ def main():
for e in sorted(sep):
d = sep[e]
if "gate_proj" in d and "up_proj" in d and "down_proj" in d:
- mw, qs = make_merged(d["gate_proj"], d["up_proj"], d["down_proj"], args.ebits)
+ mw, qs = make_merged(d["gate_proj"], d["up_proj"], d["down_proj"], args.ebits, gs=args.gs)
tens[f"model.layers.{a}.mlp.experts.{e}.merged_weight"] = mw
tens[f"model.layers.{a}.mlp.experts.{e}.qs"] = qs
else:
@@ -513,6 +537,7 @@ def main():
meta["o_in"] = op[1]
if qn is not None:
meta["qk_rope_head_dim"] = qn[0]
+ meta["expert_gs"] = args.gs # 0 = per-row scales; >0 = group size along input dim
meta["head_dim"] = meta.get("k_head_dim", meta.get("q_head_dim", 256))
meta["rope_dim"] = meta.get("qk_rope_head_dim", meta["head_dim"] // 4)
# ---- DeltaNet (linear_attention) dims. From config (authoritative for dn; unlike the