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

fix(deepseek-v4): the MoE step says why it failed, instead of "failed in MoE"

JustVugg849f43f6a71b
diff --git a/c/deepseek_v4.c b/c/deepseek_v4.c
index 4052ed8d..040c7261 100644
--- a/c/deepseek_v4.c
+++ b/c/deepseek_v4.c
@@ -4165,6 +4165,30 @@ int coli_v4_sparse_attention_ref(float *output, const float *queries,
#endif /* COLI_V4_UNIT_SPARSE_ATTENTION */
#ifdef COLI_V4_UNIT_BLOCK_HYBRID
+
+/* Why the MoE step failed, for the block to put in its error string.
+ *
+ * moe_token_pipeline and v4_moe_batch_union can fail in some thirty places
+ * -- an expert that would not read, an upload that would not land, a GPU
+ * expert group that refused, a routing table missing, a plain malloc -- and
+ * every one of them used to return a bare -1. The block then reported
+ * "hybrid batched block failed in MoE", which is true and useless: #1464
+ * spent a day trying flags against a message that could not tell an out-of-
+ * VRAM card from a bad read over /mnt/c. The reason is thread-local because
+ * the pipeline may be driven from more than one thread; it is cleared on
+ * entry so a stale one cannot outlive the call that set it. */
+#include <stdarg.h> /* this unit has no other variadic helper; set_error lives in another */
+#include <stdio.h>
+static __thread char v4_moe_reason[192];
+static void moe_reason_clear(void) { v4_moe_reason[0] = 0; }
+static const char *moe_reason(void) { return v4_moe_reason; }
+static int moe_fail(const char *format, ...) {
+ va_list arguments;
+ va_start(arguments, format);
+ vsnprintf(v4_moe_reason, sizeof v4_moe_reason, format, arguments);
+ va_end(arguments);
+ return -1;
+}
/* ######## deepseek_v4_block_hybrid.c ######## */
/* Accepted decode pipeline plus batched causal attention for prompt prefill. */
/* ---- begin include deepseek_v4_block_pipeline.c ---- */
@@ -4409,7 +4433,11 @@ static int block_token_impl(float *output_hc,
free(comb); free(post); free(branch); free(normalized);
free(reduced); free(state); free(residual);
- return result ? set_error(error, error_size, "block computation failed") : 0;
+ if (!result) return 0;
+ if (moe_reason()[0])
+ return set_error(error, error_size, "block computation failed in MoE: %s",
+ moe_reason());
+ return set_error(error, error_size, "block computation failed");
}
int coli_v4_block_token_ref(float *output_hc,
@@ -4865,7 +4893,8 @@ static int moe_token_pipeline(float *output,
!expert_output || !shared_output) {
free(shared_output); free(expert_output); free(expert_weights);
free(expert_ids); free(indices); free(route_weights); free(gate);
- return -1;
+ return moe_fail("layer %d: out of memory for the routing scratch",
+ weights->plan.layer);
}
#ifdef COLI_V4_DISABLE_BF16_ROUTE
#ifdef COLI_V4_EXPERIMENTAL_BLOCK_OTHER_PROFILE
@@ -4879,8 +4908,13 @@ static int moe_token_pipeline(float *output,
#endif
const int64_t *table = value(weights, "ffn.gate.tid2eid", NULL);
const float *bias = value(weights, "ffn.gate.bias", NULL);
+ moe_reason_clear();
int result = token < 0 || token >= config->vocab_size;
- if (!result && weights->plan.uses_hash_router && !table) result = -1;
+ if (result) moe_fail("layer %d: token %d is outside the vocabulary of %d",
+ weights->plan.layer, token, config->vocab_size);
+ if (!result && weights->plan.uses_hash_router && !table)
+ result = moe_fail("layer %d: the hash router table ffn.gate.tid2eid is missing",
+ weights->plan.layer);
if (!result && weights->plan.uses_hash_router)
for (int i = 0; i < topk; i++)
indices[i] = (int)table[(size_t)token * topk + i];
@@ -4916,7 +4950,9 @@ static int moe_token_pipeline(float *output,
}
}
}
- if (!result && selected != topk) result = -1;
+ if (!result && selected != topk)
+ result = moe_fail("layer %d: routing selected %d experts, wanted %d",
+ weights->plan.layer, selected, topk);
#ifdef COLI_V4_EXPERIMENTAL_PREFETCH
if (!result && expert_prefetch_enabled() && store->ops->prefetch) {
@@ -4943,7 +4979,8 @@ static int moe_token_pipeline(float *output,
jobs[i].key = (ColiExpertKey){weights->plan.layer, expert_ids[i]};
jobs[i].result = -1;
if (profiled_expert_load_start(&loaders[i], &jobs[i]) != 0) {
- result = -1;
+ result = moe_fail("layer %d: could not start reading expert %d",
+ weights->plan.layer, expert_ids[i]);
break;
}
loader_active[i] = 1;
@@ -4958,7 +4995,8 @@ static int moe_token_pipeline(float *output,
job.key = (ColiExpertKey){weights->plan.layer, expert_ids[0]};
job.result = -1;
if (profiled_expert_load_start(&loader, &job) != 0)
- result = -1;
+ result = moe_fail("layer %d: could not start reading expert %d",
+ weights->plan.layer, expert_ids[0]);
else
loader_active = 1;
}
@@ -4966,7 +5004,9 @@ static int moe_token_pipeline(float *output,
ColiTensorView w1, w2, w3;
if (!result && (fp8_view(&w1, weights, "ffn.shared_experts.w1") ||
fp8_view(&w2, weights, "ffn.shared_experts.w2") ||
- fp8_view(&w3, weights, "ffn.shared_experts.w3"))) result = -1;
+ fp8_view(&w3, weights, "ffn.shared_experts.w3")))
+ result = moe_fail("layer %d: the shared expert's fp8 tensors are missing",
+ weights->plan.layer);
if (!result) result = coli_v4_shared_expert_forward_ref(
shared_output, &w1, &w2, &w3, input, config->swiglu_limit);
if (!result) memset(output, 0, (size_t)d * sizeof(*output));
@@ -4976,7 +5016,8 @@ static int moe_token_pipeline(float *output,
#ifdef COLI_V4_GPU_TIER
int gpu_compute = 0;
#endif
- if (!views) result = -1;
+ if (!views) result = moe_fail("layer %d: out of memory for %d expert views",
+ weights->plan.layer, selected);
if (!result) {
memset(views, 0, (size_t)selected * sizeof(*views));
#ifdef COLI_V4_GPU_TIER
@@ -4986,10 +5027,16 @@ static int moe_token_pipeline(float *output,
int slot = current % dual_loader_lanes();
if (!loader_active[slot] ||
profiled_expert_load_finish(&loaders[slot]) != 0) {
- result = -1; break;
+ result = moe_fail("layer %d: the read of expert %d did not complete",
+ weights->plan.layer, jobs[slot].key.expert);
+ break;
}
loader_active[slot] = 0;
- if (jobs[slot].result) { result = -1; break; }
+ if (jobs[slot].result) {
+ result = moe_fail("layer %d: reading expert %d from the expert store failed",
+ weights->plan.layer, jobs[slot].key.expert);
+ break;
+ }
views[current] = jobs[slot].view;
#ifdef COLI_V4_GPU_TIER
if (store->gpu) {
@@ -5016,7 +5063,8 @@ static int moe_token_pipeline(float *output,
jobs[slot].result = -1;
if (profiled_expert_load_start(&loaders[slot],
&jobs[slot]) != 0)
- result = -1;
+ result = moe_fail("layer %d: could not start reading expert %d",
+ weights->plan.layer, expert_ids[next]);
else
loader_active[slot] = 1;
}
@@ -5095,7 +5143,9 @@ static int moe_token_pipeline(float *output,
void **gates = malloc((size_t)selected * sizeof(*gates));
void **ups = malloc((size_t)selected * sizeof(*ups));
void **downs = malloc((size_t)selected * sizeof(*downs));
- if (!gates || !ups || !downs) result = -1;
+ if (!gates || !ups || !downs)
+ result = moe_fail("layer %d: out of memory for the GPU expert group of %d",
+ weights->plan.layer, selected);
if (!result) {
for (int i = 0; i < selected; i++) {
gates[i] = views[i].gate.gpu;
@@ -5119,7 +5169,11 @@ static int moe_token_pipeline(float *output,
float *y, const float *x);
if (!dsv4_cuda_expert_group(gates, ups, downs,
expert_weights, selected, config->swiglu_limit,
- expert_output, input)) result = -1;
+ expert_output, input))
+ result = moe_fail("layer %d: the GPU expert group of %d experts "
+ "refused (a CUDA allocation or launch failed; "
+ "check nvidia-smi for free VRAM)",
+ weights->plan.layer, selected);
if (!result)
for (int i = 0; i < d; i++)
expert_output[i] += shared_output[i];
@@ -5261,10 +5315,16 @@ static int moe_token_pipeline(float *output,
#else
for (int current = 0; current < selected && loader_active; current++) {
if (profiled_expert_load_finish(&loader) != 0) {
- result = -1; loader_active = 0; break;
+ result = moe_fail("layer %d: the read of expert %d did not complete",
+ weights->plan.layer, job.key.expert);
+ loader_active = 0; break;
}
loader_active = 0;
- if (job.result) { result = -1; break; }
+ if (job.result) {
+ result = moe_fail("layer %d: reading expert %d from the expert store failed",
+ weights->plan.layer, job.key.expert);
+ break;
+ }
ColiExpertView expert = job.view;
#ifdef COLI_V4_GPU_TIER
if (store->gpu) coli_v4_gpu_expert_attach(store, &expert);
@@ -5277,7 +5337,8 @@ static int moe_token_pipeline(float *output,
expert_ids[current + 1]};
job.result = -1;
if (profiled_expert_load_start(&loader, &job) != 0)
- result = -1;
+ result = moe_fail("layer %d: could not start reading expert %d",
+ weights->plan.layer, expert_ids[current + 1]);
else
loader_active = 1;
}
@@ -5373,7 +5434,11 @@ static int block_token_pipeline(float *output_hc,
#undef DP_MARK
free(comb); free(post); free(branch); free(normalized);
free(reduced); free(state); free(residual);
- return result ? set_error(error, error_size, "block computation failed") : 0;
+ if (!result) return 0;
+ if (moe_reason()[0])
+ return set_error(error, error_size, "block computation failed in MoE: %s",
+ moe_reason());
+ return set_error(error, error_size, "block computation failed");
}
int coli_v4_block_token_ref(float *output_hc,
@@ -5543,6 +5608,7 @@ static int v4_moe_batch_union(
float *outputs, const ColiDeepSeekV4LayerWeights *weights,
const ColiDeepSeekV4Config *config, ColiExpertStore *store,
const float *inputs, const int *tokens, int batch) {
+ moe_reason_clear();
int d = config->hidden_size;
int n = config->n_routed_experts;
int topk = config->num_experts_per_tok;
@@ -5577,7 +5643,8 @@ static int v4_moe_batch_union(
free(keys); free(used); free(expert_items); free(expert_weights);
free(expert_outputs); free(expert_inputs); free(shared);
free(indices); free(route_weights); free(gate);
- return -1;
+ return moe_fail("layer %d: out of memory for the prefill expert union",
+ weights->plan.layer);
}
#ifdef COLI_V4_DISABLE_BF16_ROUTE
decode_bf16(gate, value(weights, "ffn.gate.weight", NULL), gate_count);
@@ -5610,7 +5677,8 @@ static int v4_moe_batch_union(
if (item_indices[rank] >= 0 && item_indices[rank] < n)
used[item_indices[rank]] = 1;
else
- result = -1;
+ result = moe_fail("layer %d: routing returned an expert outside "
+ "the table", weights->plan.layer);
}
}
@@ -5619,7 +5687,8 @@ static int v4_moe_batch_union(
(fp8_view(&w1, weights, "ffn.shared_experts.w1") ||
fp8_view(&w2, weights, "ffn.shared_experts.w2") ||
fp8_view(&w3, weights, "ffn.shared_experts.w3")))
- result = -1;
+ result = moe_fail("layer %d: the shared expert's fp8 tensors are missing",
+ weights->plan.layer);
if (!result && batch > 1 && v4_shared_batch_enabled())
result = v4_shared_expert_forward_batch_ref(
shared, &w1, &w2, &w3, inputs, batch, config->swiglu_limit);
@@ -5649,7 +5718,8 @@ static int v4_moe_batch_union(
jobs[current].key = keys[current];
jobs[current].result = -1;
if (profiled_expert_load_start(&loaders[current], &jobs[current]))
- result = -1;
+ result = moe_fail("layer %d: could not start reading expert %d",
+ weights->plan.layer, keys[current].expert);
else
active[current] = 1;
}
@@ -5657,7 +5727,8 @@ static int v4_moe_batch_union(
int slot = current % dual_loader_lanes();
if (!active[slot] || profiled_expert_load_finish(&loaders[slot]) ||
jobs[slot].result) {
- result = -1;
+ result = moe_fail("layer %d: reading expert %d from the expert store failed",
+ weights->plan.layer, jobs[slot].key.expert);
break;
}
active[slot] = 0;
@@ -5669,7 +5740,8 @@ static int v4_moe_batch_union(
jobs[slot].key = keys[next];
jobs[slot].result = -1;
if (profiled_expert_load_start(&loaders[slot], &jobs[slot]))
- result = -1;
+ result = moe_fail("layer %d: could not start reading expert %d",
+ weights->plan.layer, keys[next].expert);
else
active[slot] = 1;
}
@@ -5690,7 +5762,8 @@ static int v4_moe_batch_union(
for (int current = 0; !result && current < key_count; current++) {
ColiExpertView view;
if (coli_expert_lookup(store, keys[current], &view)) {
- result = -1;
+ result = moe_fail("layer %d: expert %d is not in the expert store",
+ weights->plan.layer, keys[current].expert);
break;
}
result = v4_apply_expert_batch(
@@ -5881,6 +5954,9 @@ int coli_v4_block_window_batch_ref(
free(normalized); free(states);
if (!result) return 0;
if (error && error_size && error[0]) return -1;
+ if (moe_reason()[0])
+ return set_error(error, error_size, "hybrid batched block failed in %s: %s",
+ phase, moe_reason());
return set_error(error, error_size, "hybrid batched block failed in %s", phase);
}
#endif /* COLI_V4_UNIT_BLOCK_HYBRID */
diff --git a/c/tests/test_v4_moe_reason_source.py b/c/tests/test_v4_moe_reason_source.py
new file mode 100644
index 00000000..d60f6b52
--- /dev/null
+++ b/c/tests/test_v4_moe_reason_source.py
@@ -0,0 +1,51 @@
+"""The V4 MoE step must say why it failed.
+
+moe_token_pipeline and v4_moe_batch_union used to fail in some thirty places
+with a bare -1, and the block reported "hybrid batched block failed in MoE"
+for all of them (#1464). Every failure site now records a reason through
+moe_fail(), and both block tails append it. This pins that shape at source
+level: the only `result = -1` left in those two functions are the job markers
+(`jobs[i].result = -1`, "not finished yet"), and the block tails read
+moe_reason(). A silent exit reintroduced by a later change fails here.
+"""
+import re
+import unittest
+from pathlib import Path
+
+SOURCE = Path(__file__).resolve().parent.parent / "deepseek_v4.c"
+
+
+def function_body(text, signature):
+ start = text.index(signature)
+ end = text.index("\n}\n", start)
+ return text[start:end]
+
+
+class V4MoeReasonSourceTest(unittest.TestCase):
+ def setUp(self):
+ self.text = SOURCE.read_text(encoding="utf-8")
+
+ def test_no_silent_failure_in_the_two_moe_functions(self):
+ for signature in ("static int moe_token_pipeline(",
+ "static int v4_moe_batch_union("):
+ body = function_body(self.text, signature)
+ for line in body.splitlines():
+ stripped = line.strip()
+ if re.search(r"(^|[^.\w])result\s*=\s*-1;|^return -1;", stripped):
+ self.assertRegex(
+ stripped, r"^jobs?\[\w+\]\.result = -1;$|^job\.result = -1;$",
+ f"silent failure in {signature}: {stripped!r}")
+
+ def test_both_functions_clear_the_reason_on_entry(self):
+ for signature in ("static int moe_token_pipeline(",
+ "static int v4_moe_batch_union("):
+ self.assertIn("moe_reason_clear();", function_body(self.text, signature))
+
+ def test_block_tails_append_the_reason(self):
+ self.assertIn('"hybrid batched block failed in %s: %s"', self.text)
+ self.assertIn('"block computation failed in MoE: %s"', self.text)
+ self.assertGreaterEqual(self.text.count("moe_reason()[0]"), 3)
+
+
+if __name__ == "__main__":
+ unittest.main()