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

qwen36: run dense checkpoints of the family (Qwen3.8-27B)

JustVuggd229c60971e5
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index ab191ac4..70d21228 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -506,6 +506,27 @@ jobs:
./qwen36 "$cap" 8 qwen38_2p4t_tiny/ref_full.json
echo "::endgroup::"
done
+ - name: "Qwen3.8-27B geometry: a dense checkpoint of the same architecture (#1757)"
+ run: |
+ cd c
+ # Qwen/Qwen3.8-27B is Qwen3_5ForConditionalGeneration: the hybrid
+ # DeltaNet + gated attention of this engine with one SwiGLU MLP per
+ # layer and no router. The converter has to write num_experts 0 and
+ # the MLP width, and the engine has to run that MLP as an ungated
+ # shared expert, token for token against Qwen3_5ForCausalLM.
+ python3 tools/make_qwen36_tiny.py --geometry qwen38-27b-dense \
+ --out qwen38_27b_tiny --ref-mode full \
+ --emit-ref qwen38_27b_tiny/ref_full.json
+ python3 tools/convert_qwen36.py --model qwen38_27b_tiny \
+ --out qwen38_27b_tiny_c --ebits 8
+ python3 -c "import json; m = json.load(open('qwen38_27b_tiny_c/qwen36_meta.json')); \
+ assert (m['num_experts'], m['topk'], m['shared_inter']) == (0, 0, 128), m"
+ for cap in 1 8; do
+ echo "::group::27B dense geometry cap=$cap"
+ COLI_DENSE_I8=0 SNAP=qwen38_27b_tiny_c \
+ ./qwen36 "$cap" 8 qwen38_27b_tiny/ref_full.json
+ echo "::endgroup::"
+ done
- name: Same run under ASan + UBSan
run: |
cd c
diff --git a/README.md b/README.md
index 3a0ad7d9..f3e75e4a 100644
--- a/README.md
+++ b/README.md
@@ -453,6 +453,7 @@ the model's `config.json`):
> | **Kimi K3** | ~1.6 TB | 32 GB+ | not needed |
> | **DeepSeek V4 Flash** | ~167 GB (REAP 150B: ~85 GB) | 16 GB min, 32 GB comfortable | optional; any NVIDIA card from the GTX 10 series up (Pascal/Turing via `CUDA_ARCH=portable-pre-ampere NO_TC=1`, best on RTX 50) makes prefill 5-10x and decode ~2.5x faster |
> | **Qwen3.8-Flash-Next** | ~185.5 GB (official FP8 checkpoint) | 16 GB min, 24 GB comfortable at the default context | optional; the CUDA VRAM expert tier with dense trunk quantized to int8 in VRAM |
+> | **Qwen3.8-27B** (dense) | ~51 GB converted (f16) | 20 GB with int4 dense weights, 30 GB in int8 | not used yet (CPU) |
> | **Qwen3.6-35B-A3B** | ~20 GB (int4-gs64 container) | 24 GB (needs full RAM residency) | optional; the CUDA VRAM expert tier measured **1.44 -> 10.05 tok/s (7.0x)** on two 8 GB cards, output bit-identical to CPU |
>
> A GPU only ever makes it faster. Speed is set by your disk, because the experts
diff --git a/c/coli b/c/coli
index abab0722..a91d23f1 100755
--- a/c/coli
+++ b/c/coli
@@ -1199,7 +1199,9 @@ def cmd_info(a):
experts=arch_c.get("n_routed_experts",arch_c.get("num_experts"))
row("model", a.model)
row("arch", f"hidden {arch_c.get('hidden_size')} · {arch_c.get('num_hidden_layers')} layer · "
- f"{experts} expert/layer · top-{arch_c.get('num_experts_per_tok')}")
+ + (f"{experts} expert/layer · top-{arch_c.get('num_experts_per_tok')}"
+ if experts is not None else
+ f"dense (MLP {arch_c.get('intermediate_size')}, no experts)"))
sts=[x for x in os.listdir(a.model) if x.endswith('.safetensors')]
sz=sum(os.path.getsize(os.path.join(a.model,x)) for x in sts)
row("shards", f"{len(sts)} files · {sz/1e9:.0f} GB on disk")
@@ -1870,14 +1872,15 @@ def cmd_chat(a):
if getattr(a,"attach",None):
sys.exit(f"--attach: no coli serve answering at {base} (start one with: coli serve --model <dir>)")
need_model(a.model)
- family=resolve_model(a.model).descriptor
+ resolved=resolve_model(a.model); family=resolved.descriptor
arch=family.id
if not family.has_gateway_adapter:
sys.exit(f"{family.display_name}: gateway adapter is not wired")
if arch!="glm":
engine=engine_for(a.model)
need_model(a.model,engine)
- model_id=family.default_model_id
+ from family_registry import default_model_id
+ model_id=default_model_id(resolved)
banner(f"chat · {model_id} · local server", model=a.model)
import openai_server
# --cap rides along so an explicit `coli chat --cap N` reaches the
diff --git a/c/family_registry.py b/c/family_registry.py
index d1fb3877..2ed2d0ee 100644
--- a/c/family_registry.py
+++ b/c/family_registry.py
@@ -59,6 +59,10 @@ class DisplayVariant:
geometry: tuple
display_name: str
display_scale: str
+ # The API model id for this checkpoint, when it must not borrow the family's:
+ # set only where no id was ever announced for it, so existing clients of the
+ # 35B and 2.4T keep the id they were configured with.
+ model_id: str = ""
@dataclass(frozen=True, slots=True)
@@ -67,6 +71,9 @@ class PlannerGeometry:
fixed_state_bytes: int
workspace_bytes: int
configured_experts: int
+ # A dense checkpoint (no expert count in its config): zero experts is its shape,
+ # not a broken MoE config, and the planner keeps every weight resident (#1757).
+ dense: bool = False
@dataclass(frozen=True, slots=True)
@@ -240,6 +247,10 @@ def _qwen36_geometry(config, context, _model_dir):
conv_dim = key_heads * key_dim * 2 + value_heads * value_dim
fixed = (layers - full) * (value_heads * key_dim * value_dim +
conv_dim * (conv_k - 1)) * 4
+ # A dense checkpoint of the family (Qwen3.8-27B, #1757) has no num_experts: nothing
+ # to cache, every weight resident.
+ if "num_experts" not in config:
+ return PlannerGeometry(kv, fixed, 0, 0, dense=True)
return PlannerGeometry(kv, fixed, 0, _required_int(config, "num_experts", "qwen36"))
@@ -1288,7 +1299,10 @@ FAMILIES = (
),
FamilyDescriptor(
id="qwen36",
- model_types=("qwen3_5_moe", "qwen3_5_moe_text"),
+ # qwen3_5 / qwen3_5_text: the dense checkpoints of the same architecture
+ # (Qwen3.8-27B, #1757). The engine loads their MLP as an ungated shared
+ # expert and routes nothing.
+ model_types=("qwen3_5_moe", "qwen3_5_moe_text", "qwen3_5", "qwen3_5_text"),
display_name="Qwen3.6-35B-A3B",
display_scale="35B",
# Both checkpoints declare qwen3_5_moe_text. Keyed on the three
@@ -1301,6 +1315,9 @@ FAMILIES = (
DisplayVariant((("num_hidden_layers", 92), ("num_experts", 512),
("hidden_size", 8192)),
"Qwen3.8-2.4T-A95B", "2.4T"),
+ DisplayVariant((("num_hidden_layers", 64), ("hidden_size", 5120),
+ ("intermediate_size", 17408)),
+ "Qwen3.8-27B", "27B", model_id="qwen3.8-27b-colibri"),
),
engine_artifact="qwen36",
engine_aliases=(),
@@ -1562,6 +1579,17 @@ def resolve_model(model_dir):
config, family_config, str(model))
+def default_model_id(resolved):
+ """The API model id for what was actually loaded: its display variant's, if it has
+ one of its own, else the family's."""
+ family = resolved.descriptor
+ config = resolved.family_config
+ for variant in family.display_variants:
+ if variant.model_id and all(config.get(key) == value for key, value in variant.geometry):
+ return variant.model_id
+ return family.default_model_id
+
+
def display_for(resolved):
"""(display_name, display_scale) for what was actually loaded.
@@ -1598,7 +1626,7 @@ def planner_geometry(resolved, context):
for value in (geometry.context_state_bytes, geometry.fixed_state_bytes,
geometry.workspace_bytes, geometry.configured_experts)):
raise RegistryError(f"invalid planner geometry for {resolved.descriptor.id}")
- if geometry.configured_experts < 1:
+ if geometry.configured_experts < 1 and not geometry.dense:
raise ValueError(f"{resolved.descriptor.id}: configured expert count is zero")
return geometry
diff --git a/c/openai_server.py b/c/openai_server.py
index 221427b3..c7928f8d 100644
--- a/c/openai_server.py
+++ b/c/openai_server.py
@@ -24,6 +24,7 @@ import v4_dsml # vendored DeepSeek V4 DSML reference primit
import v41_dsml # ...and V4.1's, whose tag names differ by a space
from family_registry import (FamilyConfigError, UnknownFamilyError, family_by_id,
family_ids, resolve_model)
+from family_registry import default_model_id as registry_default_model_id
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from urllib.parse import unquote, urlsplit
@@ -714,7 +715,7 @@ def parse_arch_tool_calls(reply, tools, tool_reply=None):
_sideband_text, calls = parse_k3_tool_calls(tool_reply, tools)
return reply.strip(), calls
return parse_k3_tool_calls(reply, tools) # compatibility with pre-#1147 engines
- if ARCH == "qwen38":
+ if chat_flavor() == "qwen38":
return parse_qwen38_tool_calls(reply, tools)
return parse_tool_calls(reply, tools)
@@ -749,6 +750,32 @@ def _tool_hold():
ARCH = "glm" # set in main(): a family id from family_registry (glm | inkling |
# kimi | olmoe | qwen36 | qwen38 | deepseek_v4)
+# The chat template the model was trained on, when it is not its engine family's (#1757):
+# Qwen3.8-27B is a dense Qwen3.5-architecture model, so the qwen36 engine runs it, but it
+# ships Qwen3.8's chat_template.jinja (the same file, sha256 c3cf9e34, that the qwen38
+# renderer is pinned to): xhigh reasoning by default, the XML tool-call form, history
+# that keeps its thinking. None means "the family's own", which is what every other
+# checkpoint is. Only rendering follows it; what the engine can do (images) stays ARCH's.
+CHAT_FLAVOR = None
+
+
+def chat_flavor():
+ return CHAT_FLAVOR or ARCH
+
+
+def detect_chat_flavor(family_id, model_dir):
+ """The template a checkpoint ships, when it differs from its family's (see CHAT_FLAVOR)."""
+ if family_id != "qwen36" or not model_dir:
+ return None
+ for name in ("chat_template.jinja", "tokenizer_config.json"):
+ try:
+ text = (Path(model_dir) / name).read_text(encoding="utf-8")
+ except (OSError, UnicodeDecodeError):
+ continue
+ # the line that makes a template Qwen3.8's: reasoning is on by default, at xhigh
+ if "reasoning_effort|default('xhigh')" in text:
+ return "qwen38"
+ return None
INK_THINK, INK_TEXT = "<|content_thinking|>", "<|content_text|>"
@@ -2621,7 +2648,7 @@ def render_chat_for_arch(messages, enable_thinking=False, reasoning_effort=None,
if ARCH == "glm53":
return render_chat_glm53(messages, enable_thinking, reasoning_effort, tools,
tool_choice, add_generation_prompt)
- if ARCH == "qwen38":
+ if chat_flavor() == "qwen38":
return render_chat_qwen38(messages, enable_thinking, reasoning_effort, tools,
tool_choice, add_generation_prompt)
if ARCH == "qwen36":
@@ -5227,7 +5254,7 @@ class APIHandler(BaseHTTPRequestHandler):
if reasoning_effort is None and "enable_thinking" not in body:
# Qwen3.8's official template defaults to enabled xhigh thinking;
# preserve the older opt-in default for the other families.
- if ARCH == "qwen38":
+ if chat_flavor() == "qwen38":
reasoning_effort = "xhigh"
elif os.environ.get("COLI_THINK", "0") == "1":
reasoning_effort = "high"
@@ -5312,7 +5339,7 @@ class APIHandler(BaseHTTPRequestHandler):
raise APIError(400, "`thinking` must be an object.", "thinking")
enable_thinking = bool(thinking and thinking.get("type") == "enabled")
if not enable_thinking and thinking is None:
- if ARCH == "qwen38":
+ if chat_flavor() == "qwen38":
enable_thinking = True
elif os.environ.get("COLI_THINK", "0") == "1":
enable_thinking = True
@@ -5330,7 +5357,7 @@ class APIHandler(BaseHTTPRequestHandler):
translated["tool_choice"] = tool_choice
if tool_choice == "none":
tools = None
- default_effort = "xhigh" if ARCH == "qwen38" and thinking is None else "high"
+ default_effort = "xhigh" if chat_flavor() == "qwen38" and thinking is None else "high"
add_generation_prompt = resolve_generation_prompt(messages, body)
prompt = render_chat_for_arch(messages, enable_thinking,
default_effort if enable_thinking else None,
@@ -5635,10 +5662,19 @@ def serve(model, host="127.0.0.1", port=8000, model_id=None, api_key=None,
previous_sigterm = signal.getsignal(signal.SIGTERM)
try:
family = pending_family or resolve_model(model).descriptor
- global ARCH
+ global ARCH, CHAT_FLAVOR
ARCH = family.id
+ CHAT_FLAVOR = detect_chat_flavor(family.id, model)
+ if CHAT_FLAVOR:
+ print(f"[gateway] {family.id} engine, {CHAT_FLAVOR} chat template "
+ "(from the checkpoint's chat_template.jinja)", file=sys.stderr)
engine = pending_engine or default_engine(family)
- model_id = pending_model_id or family.default_model_id
+ if not pending_model_id:
+ try:
+ pending_model_id = registry_default_model_id(resolve_model(model))
+ except Exception:
+ pending_model_id = family.default_model_id
+ model_id = pending_model_id
server.model_id = model_id
if kv_slots > family.limits.max_kv_slots:
raise ValueError(f"{family.id} engine supports at most "
@@ -5708,7 +5744,7 @@ def main():
if args.engine is None:
args.engine = str(default_engine(family))
if args.model_id is None:
- args.model_id = family.default_model_id
+ args.model_id = registry_default_model_id(resolved)
serve(args.model, args.host, args.port, args.model_id, args.api_key,
args.cap,args.max_tokens,args.engine,cors_origins=args.cors_origin,
max_queue=args.max_queue,queue_timeout=args.queue_timeout,kv_slots=args.kv_slots,
diff --git a/c/qwen36.c b/c/qwen36.c
index e7515014..7a4ffb2d 100644
--- a/c/qwen36.c
+++ b/c/qwen36.c
@@ -1208,6 +1208,21 @@ static int dense_int4_wanted(const char *tag){
* touch out->w -- the caller sets that (or leaves it, e.g. load_tq frees it
* right after). `tag` selects the int4 planar copy per dense_int4_wanted
* (NULL/COLI_DENSE_BITS!=4: skipped, out->q4 stays NULL). */
+/* Whether a matrix that got its int4 copy keeps the int8 one too. Only the CUDA
+ * placer reads it (it uploads int8 rows); on the CPU matmul_d takes the int4 copy
+ * whenever there is one, so keeping both doubled the trunk for nothing: measured on
+ * Qwen3.8-27B with COLI_DENSE_BITS=4, 42.4 GB resident against 29.1 in int8 (#1757).
+ * COLI_DENSE_KEEP_I8=1 keeps both. */
+static int dense_keep_i8(void){
+ static int v = -1;
+ if (v < 0) {
+ v = getenv("COLI_DENSE_KEEP_I8") && getenv("COLI_DENSE_KEEP_I8")[0] == '1';
+#ifdef COLI_CUDA
+ { const char *cu = getenv("COLI_CUDA"); if (cu && *cu == '1') v = 1; }
+#endif
+ }
+ return v;
+}
static void qw_quantize(const float *W, int I, int O, const char *tag, QW *out) {
int8_t *q = malloc((size_t)O*I); float *sc = malloc((size_t)O*sizeof(float));
if (!q || !sc) { fprintf(stderr, "OOM qw_quantize\n"); exit(1); }
@@ -1226,6 +1241,7 @@ static void qw_quantize(const float *W, int I, int O, const char *tag, QW *out)
if (q4 && sg) {
pack_int4_g64_planar(W, q4, sg, O, I);
out->q4 = q4; out->sg = sg; out->ng = I/64;
+ if (!dense_keep_i8()) { free(out->q); free(out->sc); out->q = NULL; out->sc = NULL; }
} else { free(q4); free(sg); }
}
}
@@ -1233,7 +1249,7 @@ 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
- if (w->q) {
+ if (w->q || w->q4) {
if (w->q4 || dense_idot_on()) {
/* integer dot: the activation rows to int8 once, then the K1b
* grouped kernel (int4 planar) or the per-row int8 kernel */
@@ -1250,6 +1266,7 @@ static void matmul_d(float *y, const float *x, const QW *w, int S, int I, int O)
return;
}
free(xq); free(sx); free(xsg); /* out of memory: the f32 path below */
+ if (!w->q) { fprintf(stderr, "OOM in the int4 dense GEMV (no int8 copy to fall back on)\n"); exit(1); }
}
if (S > 1 && dense_batch_on())
matmul_q_batch(y, x, w->q, w->sc, S, I, O);
@@ -1368,14 +1385,22 @@ static void validate_cfg(const Cfg *c, int n_layers_from_config) {
n_layers_from_config, c->n_layers);
CFG_NEED(c->hidden > 0 && c->hidden <= 65536, "hidden %d out of range", c->hidden);
CFG_NEED(c->vocab > 0, "vocab %d must be positive", c->vocab);
- CFG_NEED(c->n_experts > 0 && c->n_experts <= 1024,
- "num_experts %d out of range 1..1024 (keep[] in moe())", c->n_experts);
- CFG_NEED(c->topk > 0 && c->topk <= 256,
- "topk %d out of range 1..256 (idx[]/val[] in moe())", c->topk);
- CFG_NEED(c->topk <= c->n_experts, "topk %d exceeds num_experts %d",
- c->topk, c->n_experts);
- CFG_NEED(c->inter > 0 && c->shared_inter > 0,
- "moe_inter %d / shared_inter %d must be positive", c->inter, c->shared_inter);
+ if (c->n_experts == 0) {
+ /* A dense checkpoint of the same family (Qwen3.5 / Qwen3.8 27B, #1757): the
+ * layer's MLP is loaded as the shared expert, ungated, and nothing is routed. */
+ CFG_NEED(c->topk == 0, "a dense model (num_experts 0) routes nothing, but topk is %d",
+ c->topk);
+ CFG_NEED(c->shared_inter > 0, "dense MLP width %d must be positive", c->shared_inter);
+ } else {
+ CFG_NEED(c->n_experts > 0 && c->n_experts <= 1024,
+ "num_experts %d out of range 1..1024 (keep[] in moe())", c->n_experts);
+ CFG_NEED(c->topk > 0 && c->topk <= 256,
+ "topk %d out of range 1..256 (idx[]/val[] in moe())", c->topk);
+ CFG_NEED(c->topk <= c->n_experts, "topk %d exceeds num_experts %d",
+ c->topk, c->n_experts);
+ CFG_NEED(c->inter > 0 && c->shared_inter > 0,
+ "moe_inter %d / shared_inter %d must be positive", c->inter, c->shared_inter);
+ }
CFG_NEED(c->q_heads > 0 && c->kv_heads > 0 && c->head_dim > 0,
"attention dims q_heads=%d kv_heads=%d head_dim=%d must be positive",
c->q_heads, c->kv_heads, c->head_dim);
@@ -1552,7 +1577,7 @@ static void model_init_range(Model *m, const char *snap, int cap, int bits,
if (load_boundaries) {
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, "lmhead", &m->lm_head);
- if (m->lm_head.q) { qcount++; qfreed += (double)c->hidden * c->vocab * sizeof(float); }
+ if (m->lm_head.q || m->lm_head.q4) { 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));
@@ -1563,7 +1588,7 @@ static void model_init_range(Model *m, const char *snap, int cap, int bits,
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)
+ #define QCOUNT(field) do { if ((field).q || (field).q4) { 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];
@@ -1572,9 +1597,11 @@ static void model_init_range(Model *m, const char *snap, int cap, int bits,
LD(in_ln, "input_layernorm.weight", c->hidden);
LD(post_ln,"post_attention_layernorm.weight", 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, "router", &l->gate);
- QCOUNT(l->gate);
+ if (c->n_experts) {
+ snprintf(nm,sizeof(nm),"model.layers.%d.mlp.gate.weight", ai);
+ load_tq(m, nm, c->hidden, c->n_experts, quantize_dense, "router", &l->gate);
+ QCOUNT(l->gate);
+ } else l->gate = (QW){0};
/* 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);
@@ -1584,18 +1611,20 @@ static void model_init_range(Model *m, const char *snap, int cap, int bits,
} else { l->qn = NULL; l->kn = NULL; }
/* router correction bias (optional) */
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); }
+ if (c->n_experts && 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, int8-during-load) */
- snprintf(nm,sizeof(nm),"model.layers.%d.mlp.shared_expert.gate_proj.weight", ai);
+ /* shared expert (dense, int8-during-load). A dense model's MLP is the same
+ * SwiGLU under mlp.{gate,up,down}_proj, with no gate in front of it. */
+ const char *shp = c->n_experts ? "mlp.shared_expert." : "mlp.";
+ snprintf(nm,sizeof(nm),"model.layers.%d.%sgate_proj.weight", ai, shp);
load_tq(m, nm, c->hidden, c->shared_inter, quantize_dense, "shexp", &l->sh_g); QCOUNT(l->sh_g);
- snprintf(nm,sizeof(nm),"model.layers.%d.mlp.shared_expert.up_proj.weight", ai);
+ snprintf(nm,sizeof(nm),"model.layers.%d.%sup_proj.weight", ai, shp);
load_tq(m, nm, c->hidden, c->shared_inter, quantize_dense, "shexp", &l->sh_u); QCOUNT(l->sh_u);
- snprintf(nm,sizeof(nm),"model.layers.%d.mlp.shared_expert.down_proj.weight", ai);
+ snprintf(nm,sizeof(nm),"model.layers.%d.%sdown_proj.weight", ai, shp);
load_tq(m, nm, c->shared_inter, c->hidden, quantize_dense, "shexp", &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;
+ l->sh_gate = c->n_experts && st_has(&m->S, nm) ? load_t_n(m, nm, c->hidden) : NULL;
if (c->is_attn[i]) {
/* Gated Attention (full_attention) layer, dense projections int8-during-load */
snprintf(nm,sizeof(nm),"model.layers.%d.self_attn.q_proj.weight", ai);
@@ -2372,6 +2401,14 @@ static void route_footer(FILE *f, const Model *m) {
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;
+ if (E == 0) {
+ memset(out, 0, (int64_t)S*D*sizeof(float));
+ float *g = falloc(c->shared_inter), *u = falloc(c->shared_inter), *hh = falloc(D);
+ qwen_shared_experts_cpu(m, l, x, S, out, g, u, hh);
+ free(g); free(u); free(hh);
+ (void)layer;
+ return;
+ }
float *logits = falloc((int64_t)S*E);
double _tr = tm_now();
matmul_d(logits, x, &l->gate, S, D, E);
@@ -3012,7 +3049,7 @@ static void *pilot_worker(void *arg) {
}
static void pilot_prefetch(Model *m, int lnext, const float *x, int S) {
- if (lnext < 0 || lnext >= m->c.n_layers) return;
+ if (lnext < 0 || lnext >= m->c.n_layers || m->c.n_experts == 0) return;
Cfg *c = &m->c; int D = c->hidden, E = c->n_experts;
ensure_pilot_worker_started(m);
float *logits = falloc((int64_t)S * E);
@@ -3529,6 +3566,9 @@ static void dash_hex(const uint8_t *bytes,int n,char *hex){
}
static void emap_emit(Model *m){
const Cfg *c=&m->c; const int rows=c->n_layers, cols=c->n_experts;
+ /* A dense model has no expert grid. "EMAP 64 0 " would be a three-field line,
+ * and the gateway stops its dispatcher on a line it cannot parse (#1757). */
+ if(cols==0) return;
uint8_t *cells=calloc((size_t)rows*cols,1);
pthread_mutex_lock(&g_pilot_mx);
for(int i=0;i<rows;i++) for(int e=0;e<cols;e++)
@@ -3539,6 +3579,7 @@ static void emap_emit(Model *m){
}
static void hits_emit(Model *m){
const Cfg *c=&m->c; const int rows=c->n_layers, cols=c->n_experts, nb=(rows*cols+7)/8;
+ if(cols==0) return; /* see emap_emit */
if(!m->ehit) ehit_mark(m,-1,-1);
uint8_t *bm=calloc((size_t)nb,1); int bit=0;
for(int i=0;i<rows;i++) for(int e=0;e<cols;e++,bit++)
@@ -3909,7 +3950,8 @@ int main(int argc, char **argv) {
/* Una riga, sempre: e' l'unico modo di verificare il probe dall'esterno
* (CI sul container tiny int8, #1331) senza una scheda. */
fprintf(stderr, "[qwen36] expert format on disk: %s\n",
- expert_mixed ? "int4 gate/up + int8 down (mixed; CPU path, no VRAM tier yet)"
+ m.c.n_experts == 0 ? "none (dense model: every layer's MLP is resident)"
+ : expert_mixed ? "int4 gate/up + int8 down (mixed; CPU path, no VRAM tier yet)"
: expert_is_int4 ? "int4 packed (tier fmt=4)" : "int8 (tier fmt=1)");
g_expert_is_int4 = expert_is_int4;
g_expert_mixed = expert_mixed; g_expert_down_gs = expert_mixed ? m.c.expert_down_gs : 0;
@@ -3931,7 +3973,7 @@ int main(int argc, char **argv) {
}
if (expert_mixed && getenv("COLI_CUDA") && getenv("COLI_CUDA")[0] == '1')
fprintf(stderr, "[qwen36] COLI_CUDA=1 ignored: the VRAM expert tier does not take the mixed layout yet (one format per expert)\n");
- if (!expert_mixed &&
+ if (!expert_mixed && m.c.n_experts > 0 &&
qt_init(m.c.n_layers, m.c.n_experts, m.c.hidden, m.c.inter, cap, m.c.topk,
m.c.expert_gs, expert_is_int4)) {
fprintf(stderr, "[gpu] MoE experts -> CUDA VRAM tier\n");
diff --git a/c/resource_plan.py b/c/resource_plan.py
index 955f29a7..7ad1704b 100644
--- a/c/resource_plan.py
+++ b/c/resource_plan.py
@@ -1091,10 +1091,20 @@ def build_plan(model, ram_gb=0, context=4096, gpu_indices=None, vram_gb=0,
cap = int(cache_bytes // per_cap) if per_cap else 0
if configured_experts:
cap = min(cap, configured_experts)
+ if geometry.dense:
+ # Nothing to cache: the engine still takes a cache size, and one slot is
+ # the smallest it accepts; no slot is ever filled.
+ cap = 1
warm_bytes = min(max(0, info["expert_bytes"] - hot_bytes), cache_bytes)
cold_bytes = max(0, info["expert_bytes"] - hot_bytes - warm_bytes)
- if cap < 1:
+ if geometry.dense:
+ if info["dense_bytes"] + runtime_bytes > ram_budget:
+ warnings.append(
+ f"a dense model keeps every weight resident: {format_bytes(info['dense_bytes'])} "
+ f"of weights (as stored; the engine quantizes them at load) do not fit the "
+ f"RAM budget of {format_bytes(ram_budget)}")
+ elif cap < 1:
warnings.append("RAM budget cannot hold one expert slot per sparse layer")
if gpu_indices is not None and len(gpus) != len(set(gpu_indices)):
warnings.append("one or more requested GPUs were not detected")
@@ -1130,7 +1140,11 @@ def build_plan(model, ram_gb=0, context=4096, gpu_indices=None, vram_gb=0,
resident_expert = hot_bytes + warm_bytes
projected_hit = resident_expert / total_expert if total_expert else 1.0
- if cold_bytes:
+ if geometry.dense:
+ bottleneck = ("GPU compute (dense model, weights in VRAM)" if trunk_placed else
+ "RAM bandwidth (dense model: every weight is read for every token)")
+ bottleneck_class = "compute" if trunk_placed else "memory"
+ elif cold_bytes:
bottleneck = "disk expert misses"
bottleneck_class = "disk"
elif warm_bytes and planning_gpus:
@@ -1198,12 +1212,14 @@ def build_plan(model, ram_gb=0, context=4096, gpu_indices=None, vram_gb=0,
# Un motore solo-CPU non ha un tier VRAM: annunciarlo comunque fa
# scrivere al piano una riga che nessuno puo' eseguire.
"decisions": ([{"target": "VRAM", "reason": "dense trunk as int8 residents"}]
- if trunk_placed else []) +
- ([{"target": "VRAM", "reason": "profile-ranked hot experts"}]
- if resolved.descriptor.supports_accelerator else []) + [
- {"target": "RAM", "reason": "warm experts execute on CPU without quality loss"},
- {"target": "Disk", "reason": "immutable recovery source for cold experts"},
- ],
+ if trunk_placed else []) + (
+ [{"target": "RAM", "reason": "dense model: every weight resident, read every token"}]
+ if geometry.dense else
+ ([{"target": "VRAM", "reason": "profile-ranked hot experts"}]
+ if resolved.descriptor.supports_accelerator else []) + [
+ {"target": "RAM", "reason": "warm experts execute on CPU without quality loss"},
+ {"target": "Disk", "reason": "immutable recovery source for cold experts"},
+ ]),
"warnings": warnings,
# #379: read-only surfacing of the cached Metal-cache storage probe, if
# the engine has already measured this model dir. gbs is None unless
diff --git a/c/tests/test_family_registry.py b/c/tests/test_family_registry.py
index 4a3e95e2..0a2036e8 100644
--- a/c/tests/test_family_registry.py
+++ b/c/tests/test_family_registry.py
@@ -1563,7 +1563,9 @@ class DisplayVariantTest(unittest.TestCase):
def test_variants_are_public(self):
meta = public_metadata(next(f for f in FAMILIES if f.id == "qwen36"))
self.assertEqual([v["display_name"] for v in meta["display_variants"]],
- ["Qwen3.6-35B-A3B", "Qwen3.8-2.4T-A95B"])
+ ["Qwen3.6-35B-A3B", "Qwen3.8-2.4T-A95B", "Qwen3.8-27B"])
+ self.assertEqual(meta["display_variants"][2]["geometry"],
+ {"num_hidden_layers": 64, "hidden_size": 5120, "intermediate_size": 17408})
self.assertEqual(meta["display_variants"][1]["geometry"],
{"num_hidden_layers": 92, "num_experts": 512, "hidden_size": 8192})
for family in FAMILIES:
diff --git a/c/tests/test_openai_server.py b/c/tests/test_openai_server.py
index 28e49d37..7260640e 100644
--- a/c/tests/test_openai_server.py
+++ b/c/tests/test_openai_server.py
@@ -29,6 +29,7 @@ from openai_server import (APIError, APIHandler, APIServer, ClientCancelled,
render_chat_qwen38, render_chat_v4, render_chat_dsv41,
_dsv4_tool_calls, serve,
resolve_generation_prompt, split_thinking_reply,
+ detect_chat_flavor,
starts_in_reasoning,
stop_policy, tune_child_env)
@@ -230,6 +231,30 @@ class TemplateTest(unittest.TestCase):
self.assertIn("<|im_start|>assistant\nParis.<|im_end|>",
render_chat_qwen(first + [past, follow], enable_thinking=True))
+ def test_qwen38_template_on_the_qwen36_engine(self):
+ """#1757: Qwen3.8-27B is a dense model of Qwen3.5's architecture, so the qwen36
+ engine runs it, but it ships Qwen3.8's chat_template.jinja. The gateway renders
+ the template the checkpoint carries, not its engine family's."""
+ import tempfile
+ with tempfile.TemporaryDirectory() as d:
+ template = Path(d) / "chat_template.jinja"
+ template.write_text("{%- set resolved_reasoning_effort = "
+ "reasoning_effort|default('xhigh') %}", encoding="utf-8")
+ self.assertEqual(detect_chat_flavor("qwen36", d), "qwen38")
+ self.assertIsNone(detect_chat_flavor("glm53", d))
+ template.write_text("{%- if enable_thinking is defined %}", encoding="utf-8")
+ self.assertIsNone(detect_chat_flavor("qwen36", d))
+ template.unlink()
+ self.assertIsNone(detect_chat_flavor("qwen36", d))
+ history = [{"role": "user", "content": "Capital of France?"}]
+ with patch("openai_server.ARCH", "qwen36"), patch("openai_server.CHAT_FLAVOR", "qwen38"):
+ for thinking in (True, False):
+ self.assertEqual(render_chat_for_arch(history, thinking, "xhigh"),
+ render_chat_qwen38(history, thinking, "xhigh"))
+ with patch("openai_server.ARCH", "qwen36"):
+ self.assertNotEqual(render_chat_for_arch(history, True, "xhigh"),
+ render_chat_qwen38(history, True, "xhigh"))
+
def test_kimi_renders_tool_declaration_and_choice(self):
tools = [{"type": "function", "function": {
"name": "get_weather", "parameters": {"type": "object"}}}]
@@ -2160,6 +2185,16 @@ class HTTPTest(unittest.TestCase):
self.addCleanup(caught.exception.close)
self.assertEqual(caught.exception.code, 400)
+ def test_qwen38_template_defaults_to_xhigh_thinking_on_the_qwen36_engine(self):
+ """What the flavor changes over the wire: with no thinking field, a Qwen3.8
+ template reasons at xhigh by default, as the qwen38 family does."""
+ history = [{"role": "user", "content": "Capital of France?"}]
+ with patch("openai_server.ARCH", "qwen36"), patch("openai_server.CHAT_FLAVOR", "qwen38"):
+ with self.request("/v1/chat/completions", {
+ "model": "test-model", "messages": history}) as response:
+ self.assertEqual(response.status, 200)
+ self.assertEqual(self.engine.calls[-1][0], render_chat_qwen38(history, True, "xhigh"))
+
def test_a_well_formed_forced_tool_choice_still_runs(self):
"""The read above must not change the shape clients actually send."""
with self.request("/v1/chat/completions", {
diff --git a/c/tests/test_qwen36_tensor_kinds.py b/c/tests/test_qwen36_tensor_kinds.py
index 121daebb..eaa9276b 100644
--- a/c/tests/test_qwen36_tensor_kinds.py
+++ b/c/tests/test_qwen36_tensor_kinds.py
@@ -104,6 +104,59 @@ TINY_FIXTURE = tuple(
)
+# Qwen/Qwen3.8-27B, model.safetensors.index.json (1199 tensors, fetched 2026-09-27): the
+# DENSE checkpoint of the same architecture (#1757). No router, no experts: each layer
+# carries one SwiGLU MLP under mlp.{gate,up,down}_proj. 38 text/mtp names plus 21
+# model.visual.* kinds (three listed).
+# sha256 model.safetensors.index.json (Qwen/Qwen3.8-27B):
+# 77042094076611b69791a610065f28b7013b8c621795fa86ddccc8bac7d1b9df
+QWEN38_27B = (
+ "lm_head.weight",
+ "model.language_model.embed_tokens.weight",
+ "model.language_model.layers.N.input_layernorm.weight",
+ "model.language_model.layers.N.linear_attn.A_log",
+ "model.language_model.layers.N.linear_attn.conv1d.weight",
+ "model.language_model.layers.N.linear_attn.dt_bias",
+ "model.language_model.layers.N.linear_attn.in_proj_a.weight",
+ "model.language_model.layers.N.linear_attn.in_proj_b.weight",
+ "model.language_model.layers.N.linear_attn.in_proj_qkv.weight",
+ "model.language_model.layers.N.linear_attn.in_proj_z.weight",
+ "model.language_model.layers.N.linear_attn.norm.weight",
+ "model.language_model.layers.N.linear_attn.out_proj.weight",
+ "model.language_model.layers.N.mlp.down_proj.weight",
+ "model.language_model.layers.N.mlp.gate_proj.weight",
+ "model.language_model.layers.N.mlp.up_proj.weight",
+ "model.language_model.layers.N.post_attention_layernorm.weight",
+ "model.language_model.layers.N.self_attn.k_norm.weight",
+ "model.language_model.layers.N.self_attn.k_proj.weight",
+ "model.language_model.layers.N.self_attn.o_proj.weight",
+ "model.language_model.layers.N.self_attn.q_norm.weight",
+ "model.language_model.layers.N.self_attn.q_proj.weight",
+ "model.language_model.layers.N.self_attn.v_proj.weight",
+ "model.language_model.norm.weight",
+ "mtp.fc.weight",
+ "mtp.layers.N.input_layernorm.weight",
+ "mtp.layers.N.mlp.down_proj.weight",
+ "mtp.layers.N.mlp.gate_proj.weight",
+ "mtp.layers.N.mlp.up_proj.weight",
+ "mtp.layers.N.post_attention_layernorm.weight",
+ "mtp.layers.N.self_attn.k_norm.weight",
+ "mtp.layers.N.self_attn.k_proj.weight",
+ "mtp.layers.N.self_attn.o_proj.weight",
+ "mtp.layers.N.self_attn.q_norm.weight",
+ "mtp.layers.N.self_attn.q_proj.weight",
+ "mtp.layers.N.self_attn.v_proj.weight",
+ "mtp.norm.weight",
+ "mtp.pre_fc_norm_embedding.weight",
+ "mtp.pre_fc_norm_hidden.weight",
+ "model.visual.blocks.N.attn.proj.bias",
+ "model.visual.blocks.N.attn.proj.weight",
+ "model.visual.blocks.N.attn.qkv.bias",
+)
+
+DENSE_MLP_KINDS = {"mlp.gate_proj.weight", "mlp.up_proj.weight", "mlp.down_proj.weight"}
+
+
def _concrete(names):
return [n.replace("N", "7") for n in names]
@@ -160,7 +213,17 @@ class TensorKindsTest(unittest.TestCase):
self.assertEqual({p[1] for p in placed if p[0] == "skip"}, {"mtp"})
self.assertEqual({p[1] for p in placed if p[0] == "global"}, set(GLOBAL_KINDS))
self.assertEqual({p[2] for p in placed if p[0] == "layer"},
- set(LAYER_KINDS) - set())
+ set(LAYER_KINDS) - DENSE_MLP_KINDS)
+
+ def test_every_27b_tensor_is_placed(self):
+ """The dense checkpoint: the MoE kinds are absent, the dense MLP is placed, the
+ mtp head and the vision tower are skipped."""
+ prefix, placed = self._classify_all(_concrete(QWEN38_27B))
+ self.assertEqual(prefix, "model.language_model.")
+ self.assertEqual({p[1] for p in placed if p[0] == "skip"}, {"mtp", "visual"})
+ layer = {p[2] for p in placed if p[0] == "layer"}
+ self.assertTrue(DENSE_MLP_KINDS <= layer)
+ self.assertFalse({k for k in layer if k.startswith("mlp.") and k not in DENSE_MLP_KINDS})
def test_every_35b_tensor_is_placed(self):
prefix, placed = self._classify_all(_concrete(QWEN36_35B))
diff --git a/c/tests/test_resource_plan.py b/c/tests/test_resource_plan.py
index 539fb484..6307b1a5 100644
--- a/c/tests/test_resource_plan.py
+++ b/c/tests/test_resource_plan.py
@@ -250,6 +250,47 @@ class ResourcePlanTest(unittest.TestCase):
])
return model
+ def _qwen_dense_model(self, num_experts=None):
+ """Qwen3.8-27B's shape at toy size (#1757): the qwen3_5 architecture with one
+ dense MLP per layer and no expert count in the config."""
+ other = tempfile.TemporaryDirectory()
+ self.addCleanup(other.cleanup)
+ model = Path(other.name)
+ text = {
+ "model_type": "qwen3_5_text", "num_hidden_layers": 4, "hidden_size": 32,
+ "intermediate_size": 64, "num_key_value_heads": 1, "head_dim": 8,
+ "linear_num_key_heads": 2, "linear_key_head_dim": 8,
+ "linear_num_value_heads": 4, "linear_value_head_dim": 8,
+ "linear_conv_kernel_dim": 4,
+ "layer_types": ["linear_attention"] * 3 + ["full_attention"],
+ }
+ if num_experts is not None:
+ text["num_experts"] = num_experts
+ (model / "config.json").write_text(json.dumps(
+ {"model_type": "qwen3_5", "text_config": text}))
+ write_shard(model / "model.safetensors", [
+ ("model.language_model.embed_tokens.weight", 100),
+ ("model.language_model.layers.0.mlp.gate_proj.weight", 80),
+ ("model.language_model.layers.0.mlp.up_proj.weight", 80),
+ ("model.language_model.layers.0.mlp.down_proj.weight", 80),
+ ])
+ return model
+
+ def test_dense_qwen_model_keeps_every_weight_resident(self):
+ plan = build_plan(self._qwen_dense_model(), context=32, available_memory=32 * GB,
+ available_disk=100 * GB, gpus=[])
+ self.assertEqual(plan["model"]["family_id"], "qwen36")
+ self.assertEqual(plan["model"]["configured_experts"], 0)
+ self.assertEqual(plan["tiers"]["ram"]["cache_slots_per_layer"], 1)
+ self.assertIn("dense model", plan["expected_bottleneck"])
+ self.assertFalse([w for w in plan["warnings"] if "expert slot" in w])
+ self.assertEqual([d["target"] for d in plan["decisions"]], ["RAM"])
+
+ def test_zero_experts_declared_is_still_a_broken_config(self):
+ with self.assertRaisesRegex(ValueError, "num_experts|expert count is zero"):
+ build_plan(self._qwen_dense_model(num_experts=0), context=32,
+ available_memory=32 * GB, available_disk=100 * GB, gpus=[])
+
def _glm53_model(self):
other = tempfile.TemporaryDirectory()
self.addCleanup(other.cleanup)
diff --git a/c/tools/convert_qwen36.py b/c/tools/convert_qwen36.py
index d97d79f9..af2e5ce9 100644
--- a/c/tools/convert_qwen36.py
+++ b/c/tools/convert_qwen36.py
@@ -330,6 +330,18 @@ def main():
print("WARNING: tokenizer.json not found; the engine will need TOK=<path>")
except Exception as e:
print(f"WARNING: could not fetch tokenizer.json ({e}); the engine will need TOK=<path>")
+ # The chat template travels with the container: the gateway renders what the
+ # checkpoint was trained on, and a Qwen3.8 template on this engine (Qwen3.8-27B,
+ # #1757) is recognised from this file.
+ for extra in ("chat_template.jinja", "tokenizer_config.json", "generation_config.json"):
+ try:
+ extra_path = (hf_hub_download(args.repo, extra, token=token) if args.repo
+ else str(src_dir / extra))
+ except Exception:
+ continue
+ if Path(extra_path).is_file():
+ shutil.copy2(extra_path, out / extra)
+ print(f"{extra} -> {out / extra}")
# ---- build weight map (key -> shard file) ----
if idx_path:
@@ -571,10 +583,14 @@ def main():
"n_layers": int(mcfg["num_hidden_layers"]),
"n_active": len(all_idx),
"layer_types": layer_types,
- "num_experts": int(mcfg["num_experts"]),
- "topk": int(mcfg["num_experts_per_tok"]),
- "moe_inter": int(mcfg.get("moe_intermediate_size", mcfg.get("intermediate_size", 0) // 2)),
- "shared_inter": int(mcfg.get("shared_expert_intermediate_size", mcfg.get("moe_intermediate_size", 0))),
+ # A dense checkpoint of the family (no num_experts: Qwen3.5 / Qwen3.8 27B) routes
+ # nothing; the engine loads its MLP as an ungated shared expert of that width.
+ "num_experts": int(mcfg.get("num_experts", 0)),
+ "topk": int(mcfg.get("num_experts_per_tok", 0)) if mcfg.get("num_experts") else 0,
+ "moe_inter": (int(mcfg.get("moe_intermediate_size", mcfg.get("intermediate_size", 0) // 2))
+ if mcfg.get("num_experts") else 0),
+ "shared_inter": (int(mcfg.get("shared_expert_intermediate_size", mcfg.get("moe_intermediate_size", 0)))
+ if mcfg.get("num_experts") else int(mcfg["intermediate_size"])),
"rms_eps": float(mcfg.get("rms_norm_eps", 1e-6)),
"ebits": args.ebits,
"scoring_func": mcfg.get("scoring_func", "softmax"),
diff --git a/c/tools/make_qwen36_tiny.py b/c/tools/make_qwen36_tiny.py
index 23e22d65..3508d42a 100644
--- a/c/tools/make_qwen36_tiny.py
+++ b/c/tools/make_qwen36_tiny.py
@@ -47,7 +47,7 @@ except ImportError as exc:
sys.exit(f"Missing deps: {exc}. Run: pip install torch transformers")
-def get_classes():
+def get_classes(dense=False):
"""Resolve the Qwen3-MoE model/config classes across transformers versions.
Uses each model class's declared `config_class` (NOT a name guess): in
@@ -55,7 +55,7 @@ def get_classes():
same-named `Qwen3_5MoeConfig` is the vision-language wrapper and lacks the
text fields (vocab_size, head_dim, ...). Guessing by name picks the wrong one.
"""
- candidates = [
+ candidates = ["Qwen3_5ForCausalLM"] if dense else [
"Qwen3_5MoeForCausalLM",
"Qwen3MoeForCausalLM",
"Qwen3NextMoeForCausalLM",
@@ -67,7 +67,8 @@ def get_classes():
cc = getattr(mc, "config_class", None)
if cc is not None:
return mc, cc
- sys.exit("No Qwen3-MoE model class found in this transformers build. Upgrade transformers.")
+ sys.exit(f"No {'dense Qwen3.5' if dense else 'Qwen3-MoE'} model class found in this "
+ "transformers build. Upgrade transformers.")
class Zero(nn.Module):
@@ -92,6 +93,13 @@ GEOMETRIES = {
rope_dim=8, n_experts=512, topk=10, inter=16,
dn_key_heads=2, dn_value_heads=16,
fused_experts=True, mtp=True),
+ # Qwen/Qwen3.8-27B, config.json: Qwen3_5ForConditionalGeneration, a DENSE model of
+ # the same family -- 64 layers / full_attention_interval 4 / 24:4 attention heads /
+ # 16:48 DeltaNet heads / one SwiGLU MLP per layer, no router (#1757).
+ "qwen38-27b-dense": dict(hidden=64, n_layers=8, q_heads=6, kv_heads=1, head_dim=16,
+ rope_dim=8, n_experts=0, topk=0, inter=128,
+ dn_key_heads=2, dn_value_heads=6,
+ fused_experts=False, mtp=False, dense=True),
}
@@ -150,7 +158,7 @@ def build(out: Path, hidden=64, n_layers=8, q_heads=4, kv_heads=2,
vocab=320, max_new=16, prompt_ids=None, emit_ref=None,
ref_mode="attention_only", seed=20260817,
dn_key_heads=None, dn_value_heads=None,
- fused_experts=False, mtp=False):
+ fused_experts=False, mtp=False, dense=False):
if dn_key_heads is None:
dn_key_heads = q_heads
if dn_value_heads is None:
@@ -159,7 +167,7 @@ def build(out: Path, hidden=64, n_layers=8, q_heads=4, kv_heads=2,
# three local draws passed, one CI draw failed at 11/16, with identical
# code. A gate that reddens at random gets muted within a week.
torch.manual_seed(seed)
- ModelCls, ConfigCls = get_classes()
+ ModelCls, ConfigCls = get_classes(dense)
layer_types = ["full_attention" if i % 4 == 3 else "linear_attention"
for i in range(n_layers)]
base = dict(
@@ -176,6 +184,12 @@ def build(out: Path, hidden=64, n_layers=8, q_heads=4, kv_heads=2,
attention_bias=False, attention_dropout=0.0, use_cache=True,
rope_parameters={"rope_type": "default", "rope_theta": 10000.0},
)
+ if dense:
+ # the dense text config has no router: one MLP of intermediate_size per layer
+ for key in ("num_experts", "num_experts_per_tok", "moe_intermediate_size",
+ "shared_expert_intermediate_size"):
+ base.pop(key)
+ base["intermediate_size"] = inter
# Qwen3_5MoeConfig uses **kwargs, so pass everything; fall back to filtered
# only if a build rejects an unknown key.
try:
diff --git a/c/tools/qwen36_tensor_kinds.py b/c/tools/qwen36_tensor_kinds.py
index f926982d..3269184a 100644
--- a/c/tools/qwen36_tensor_kinds.py
+++ b/c/tools/qwen36_tensor_kinds.py
@@ -46,6 +46,10 @@ LAYER_KINDS = frozenset((
"mlp.shared_expert.up_proj.weight",
"mlp.shared_expert.down_proj.weight",
"mlp.shared_expert_gate.weight",
+ # dense checkpoints of the family (Qwen3.5 / Qwen3.8 27B): the whole MLP, no router
+ "mlp.gate_proj.weight",
+ "mlp.up_proj.weight",
+ "mlp.down_proj.weight",
# routed experts, fused layout (real checkpoints): one tensor per layer
"mlp.experts.gate_up_proj",
"mlp.experts.down_proj",
diff --git a/docs/ENVIRONMENT.md b/docs/ENVIRONMENT.md
index 8ff5aa31..85ca9a23 100644
--- a/docs/ENVIRONMENT.md
+++ b/docs/ENVIRONMENT.md
@@ -423,6 +423,7 @@ and the CPU/GPU execution split.
| `COLI_DENSE_IDOT` | `1` (on) | The dense trunk's GEMVs (DeltaNet projections and out_proj, attention q/k/v/o, shared expert, lm_head) quantize the activation to int8 once per call and run integer dot products (maddubs on AVX2, vpdpbusd on AVX-VNNI / AVX-512 VNNI) instead of converting every int8 weight to f32. Not bit-identical to the f32 path; measured +1.0% perplexity, lm_head 12.6 to 10.2 ms/token. `=0` restores the f32-activation kernel. |
| `QWEN_EXPERT_ACT` | `i8` | The routed experts' activation quantized to int8 once per row (expert_ffn.h mode 1). Measured +0.1% perplexity, expert compute 22.7 to 15.9 ms/token. `=f32` restores f32 activations and the bit-identical contract with the pair kernels. |
| `COLI_DENSE_BITS` | `8` | `=4` stores the dense trunk as int4 in blocks of 64 with one scale per block (the K1b planar layout, half the bytes), served by the grouped integer kernel; implies the integer dot. Opt-in: on the 35B it costs +10% perplexity on the whole trunk, +2.4% on lm_head alone (see `COLI_DENSE_INT4`). |
+| `COLI_DENSE_KEEP_I8` | `0` (off) | qwen36: a matrix that got its int4 copy (`COLI_DENSE_BITS=4`) frees its int8 copy, which only the CUDA placer reads; `=1` keeps both. With `COLI_CUDA=1` both are kept anyway. Measured on Qwen3.8-27B: 42.4 GB resident with both copies, 18.8 GB without. |
| `COLI_DENSE_INT4` | all components | With `COLI_DENSE_BITS=4`, a comma list of the components that take int4: `lmhead`, `dnproj`, `dnout`, `attn`, `shexp`, `router`. Measured on the 35B: `lmhead` +2.4% perplexity for 254 MB less per token; `lmhead,dnproj,dnout` +5.6%; everything +10%. |
| `QWEN_EXPERT_KERNEL` | `1` (on) | Routed experts run through the shared `expert_ffn.h` kernel: the int4 stays packed in RAM (planar layout, half the expert-cache RSS of the int8 unpack), gate+up are one pass, and a layer is two OpenMP regions over (expert, row-chunk) items instead of 3 x top-k GEMV regions. Takes effect on an int4 gs=64 container whose hidden and expert widths are multiples of 64, and not under the CUDA expert tier. `=0` restores the unpack-to-int8 path; the two produce the same tokens (1024-token decode on the real container byte-identical; pinned on the tiny int4 fixture in CI), only the f32 accumulation order inside a dot differs. Measured at cap 256 on the real container: 12.8 -> 15.7 tok/s, peak RSS 29 -> 17 GB. |
| `QWEN_DENSE_BATCH` | `1` (on) | On AVX2/FMA, reuse each dense-int8 weight decode across two prompt rows. `=0` restores one GEMV call per row. Decode `S=1` is unchanged. |
diff --git a/docs/qwen36.md b/docs/qwen36.md
index 98dd906e..4113f955 100644
--- a/docs/qwen36.md
+++ b/docs/qwen36.md
@@ -194,13 +194,14 @@ tier takes one format per expert and refuses a mixed container with a line
## Which checkpoints, and what the banner calls them
-Two Qwen checkpoints declare `model_type: qwen3_5_moe_text` and resolve to
-this engine:
+Three Qwen checkpoints resolve to this engine: two MoE ones that declare
+`model_type: qwen3_5_moe_text`, and a dense one that declares `qwen3_5`:
| checkpoint | layers | experts | hidden | banner |
|---|---|---|---|---|
| Qwen/Qwen3.6-35B-A3B | 40 (10 attention) | 256, top-8 | 2048 | `Qwen3.6-35B-A3B · 35B MoE` |
| Qwen/Qwen3.8-2.4T-A95B | 92 (23 attention) | 512, top-10 | 8192 | `Qwen3.8-2.4T-A95B · 2.4T MoE` |
+| Qwen/Qwen3.8-27B | 64 (16 attention) | none: one MLP of 17408 per layer | 5120 | `Qwen3.8-27B · 27B` |
The registry names a checkpoint by its geometry (`display_variants` on the
`qwen36` descriptor), so the banner says what is on disk. A config that
@@ -217,6 +218,48 @@ is hold the experts: the warmstart keeps every expert in RAM by design (see
disk-streaming design, not this one. The conversion and the geometry checks
are in place so that work starts from a verified shape, not from a guess.
+### The dense 27B
+
+Qwen3.8-27B (#1757) is `Qwen3_5ForConditionalGeneration`: the same Gated
+DeltaNet + gated attention layers, with one SwiGLU MLP per layer and no
+router. The engine loads that MLP as the shared expert, ungated, and routes
+nothing; the converter writes `num_experts: 0` and the MLP width into
+`qwen36_meta.json`. It ships Qwen3.8's `chat_template.jinja`, not Qwen3.6's
+(the same file the qwen38 renderer is pinned to): the converter copies it
+into the container, and the gateway recognises it and renders with the
+Qwen3.8 rules (reasoning on by default at `xhigh`, the XML tool-call form,
+history that keeps its thinking) while the engine stays qwen36. The API model
+id is `qwen3.8-27b-colibri`.
+
+```bash
+python3 tools/convert_qwen36.py --model <Qwen3.8-27B download> --out q27_c
+./coli chat --model q27_c --gpu none
+```
+
+The container keeps the weights in f16 (51 GB) and the engine quantizes
+them while loading. Every weight is read for every token, so speed is set by
+memory bandwidth, not by the disk. Measured on a 16-thread CPU server
+(8 OpenMP threads), perplexity over 1000 tokens of human-written text:
+
+| dense weights | RSS | scoring | perplexity, English | perplexity, Italian |
+|---|---|---|---|---|
+| int8 (default) | 29.1 GB | 2.25 tok/s | 4.85 | 11.19 |
+| `COLI_DENSE_BITS=4 COLI_DENSE_INT4=shexp,lmhead` | 21.6 GB | 3.15 tok/s | 4.94 (+1.8%) | 11.69 (+4.5%) |
+| `COLI_DENSE_BITS=4` (everything) | 18.8 GB | 3.72 tok/s | 5.02 (+3.5%) | 12.15 (+8.6%) |
+
+Through the gateway (`coli serve`), greedy decode ran at 2.1 tok/s in int8 and
+3.45 tok/s with everything in int4, after a load of 73 and 114 s; the answers
+to the same English, Italian and Turkish questions were the same but for a word.
+
+The MLP is 17 of the 27 billion parameters, so int4 on the MLP and the LM head
+keeps most of the saving at half the loss. With a matrix in int4 the engine
+no longer keeps its int8 copy (`COLI_DENSE_KEEP_I8=1` does); that is what
+brings the full int4 run from 42.4 to 18.8 GB.
+
+Not yet: the CUDA tier (a dense checkpoint runs on the CPU), the vision
+tower and the MTP head (both skipped by the converter), and an int4
+container on disk.
+
### The converter's tensor contract
Both checkpoints ship experts **fused** per layer (`mlp.experts.gate_up_proj`,