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(v4): support Pro and decouple resident tiers

DrewZb09ab5df5567
diff --git a/c/deepseek_v4.c b/c/deepseek_v4.c
index 5ebebd27..de16212a 100644
--- a/c/deepseek_v4.c
+++ b/c/deepseek_v4.c
@@ -81,6 +81,10 @@ int coli_v4_layer_plan(ColiDeepSeekV4LayerPlan *plan,
const int64_t heads = config->num_attention_heads;
const int64_t head_dim = config->head_dim;
const int64_t q_rank = config->q_lora_rank;
+ if (config->o_groups < 1 || heads % config->o_groups != 0)
+ return set_error(error, error_size, "unsupported grouped-output attention dimensions");
+ const int64_t o_group_width =
+ (heads / config->o_groups) * head_dim;
const int64_t o_width = (int64_t)config->o_groups * config->o_lora_rank;
const int64_t experts = config->n_routed_experts;
const int64_t moe = config->moe_intermediate_size;
@@ -91,7 +95,7 @@ int coli_v4_layer_plan(ColiDeepSeekV4LayerPlan *plan,
ADD(add_1d(plan, COLI_ST_BF16, head_dim, "attn.kv_norm.weight", error, error_size));
ADD(add_1d(plan, COLI_ST_BF16, q_rank, "attn.q_norm.weight", error, error_size));
ADD(add_fp8(plan, head_dim, hidden, "attn.wkv", error, error_size));
- ADD(add_fp8(plan, o_width, hidden, "attn.wo_a", error, error_size));
+ ADD(add_fp8(plan, o_width, o_group_width, "attn.wo_a", error, error_size));
ADD(add_fp8(plan, hidden, o_width, "attn.wo_b", error, error_size));
ADD(add_fp8(plan, q_rank, hidden, "attn.wq_a", error, error_size));
ADD(add_fp8(plan, heads * head_dim, q_rank, "attn.wq_b", error, error_size));
@@ -414,6 +418,65 @@ int coli_v4_resource_plan_compute(
return plan_error(error, error_size, "V4 plan exceeds available RAM");
return 0;
}
+
+static int resident_tiers_fit(uint64_t available, uint64_t fixed,
+ uint64_t dense, uint64_t dspark,
+ uint64_t minimum_experts) {
+ uint64_t total;
+ return !add_u64(fixed, dense, &total) &&
+ !add_u64(total, dspark, &total) &&
+ !add_u64(total, minimum_experts, &total) && total <= available;
+}
+
+int coli_v4_resident_tier_plan(
+ ColiDeepSeekV4ResidentTierPlan *plan,
+ const ColiDeepSeekV4ResidentTierInputs *inputs,
+ char *error, size_t error_size) {
+ if (!plan || !inputs || !inputs->available_bytes ||
+ !inputs->dense_bytes || !inputs->minimum_expert_bytes ||
+ (inputs->has_dspark &&
+ (!inputs->dspark_streamed_bytes || !inputs->dspark_full_bytes ||
+ inputs->dspark_full_bytes < inputs->dspark_streamed_bytes)) ||
+ (!inputs->has_dspark &&
+ (inputs->dspark_streamed_bytes || inputs->dspark_full_bytes)))
+ return plan_error(error, error_size,
+ "invalid V4 resident-tier inputs");
+ memset(plan, 0, sizeof(*plan));
+
+ uint64_t streamed = inputs->has_dspark
+ ? inputs->dspark_streamed_bytes : 0;
+ if (!resident_tiers_fit(inputs->available_bytes, inputs->fixed_bytes,
+ 0, streamed, inputs->minimum_expert_bytes))
+ return plan_error(error, error_size,
+ "resident V4 tiers leave too little target cache");
+
+ if (inputs->has_dspark &&
+ resident_tiers_fit(inputs->available_bytes, inputs->fixed_bytes,
+ inputs->dense_bytes, inputs->dspark_full_bytes,
+ inputs->minimum_expert_bytes)) {
+ plan->dense_resident = 1;
+ plan->dspark_resident = 1;
+ plan->dense_bytes = inputs->dense_bytes;
+ plan->dspark_bytes = inputs->dspark_full_bytes;
+ } else if (resident_tiers_fit(
+ inputs->available_bytes, inputs->fixed_bytes,
+ inputs->dense_bytes, streamed,
+ inputs->minimum_expert_bytes)) {
+ plan->dense_resident = 1;
+ plan->dense_bytes = inputs->dense_bytes;
+ plan->dspark_bytes = streamed;
+ } else if (inputs->has_dspark &&
+ resident_tiers_fit(
+ inputs->available_bytes, inputs->fixed_bytes, 0,
+ inputs->dspark_full_bytes,
+ inputs->minimum_expert_bytes)) {
+ plan->dspark_resident = 1;
+ plan->dspark_bytes = inputs->dspark_full_bytes;
+ } else {
+ plan->dspark_bytes = streamed;
+ }
+ return 0;
+}
#endif /* COLI_V4_UNIT_RESOURCE_PLAN */
#ifdef COLI_V4_UNIT_HEAD_CACHE
@@ -664,21 +727,20 @@ int coli_v4_expert_store_open_planned(
}
uint64_t fixed = plan.system_reserve_bytes + plan.runtime_reserve_bytes;
- uint64_t full_required = fixed + head_bytes + dense_bytes +
- dspark_full_bytes + plan.minimum_expert_bytes;
- int full_resident = dspark_full_bytes &&
- full_required <= plan.planner_available_bytes;
- if (full_resident) {
- dspark_bytes = dspark_full_bytes;
- runtime->dense_resident = 1;
- runtime->dspark_resident = 1;
- runtime->dspark_expert_cache_bytes = dspark_full_experts;
- } else {
- dense_bytes = 0;
- runtime->dense_resident = 0;
- runtime->dspark_resident = 0;
- runtime->dspark_expert_cache_bytes = 0;
- }
+ int has_dspark = dspark_model && *dspark_model;
+ ColiDeepSeekV4ResidentTierPlan tiers;
+ ColiDeepSeekV4ResidentTierInputs tier_inputs = {
+ plan.planner_available_bytes, fixed, dense_bytes, dspark_bytes,
+ dspark_full_bytes, plan.minimum_expert_bytes, has_dspark,
+ };
+ if (coli_v4_resident_tier_plan(&tiers, &tier_inputs,
+ error, error_size)) return -1;
+ dense_bytes = tiers.dense_bytes;
+ dspark_bytes = tiers.dspark_bytes;
+ runtime->dense_resident = tiers.dense_resident;
+ runtime->dspark_resident = tiers.dspark_resident;
+ runtime->dspark_expert_cache_bytes = tiers.dspark_resident
+ ? dspark_full_experts : 0;
if (dspark_bytes + dense_bytes > plan.planner_available_bytes - fixed) {
snprintf(error, error_size, "resident V4 tiers exceed available RAM");
return -1;
@@ -708,13 +770,14 @@ int coli_v4_expert_store_open_planned(
if (resident_head && coli_v4_head_cache_load(
engine, options->model_dir, error, error_size)) return -1;
const char *dspark_tier = (dspark_model && *dspark_model)
- ? (full_resident ? "resident" : "streamed") : "disabled";
+ ? (tiers.dspark_resident ? "resident" : "streamed") : "disabled";
fprintf(stderr,
"ram_tiers available=%.2fGiB dense=%s(%.2fGiB) "
"dspark=%s(%.2fGiB) dspark_experts=%.2fGiB "
"target_slots=%d target_cache=%.2fGiB head=%s projected=%.2fGiB\n",
plan.planner_available_bytes / (double)GIB,
- full_resident ? "resident" : "streamed", dense_bytes / (double)GIB,
+ tiers.dense_resident ? "resident" : "streamed",
+ dense_bytes / (double)GIB,
dspark_tier, dspark_bytes / (double)GIB,
dspark_full_experts / (double)GIB, slots,
plan.expert_cache_bytes / (double)GIB,
@@ -1380,7 +1443,7 @@ static int attention_token_impl(float *output,
int heads_per_group = heads / groups;
int group_width = heads_per_group * head_dim;
- int scale_columns = (hidden + 127) / 128;
+ int scale_columns = (group_width + 127) / 128;
int scale_rows_per_group = (o_rank + 127) / 128;
for (int group = 0; !result && group < groups; group++) {
ColiTensorView group_view = wo_a;
@@ -1776,7 +1839,7 @@ static int attention_token_impl(float *output,
int heads_per_group = heads / groups;
int group_width = heads_per_group * head_dim;
- int scale_columns = (hidden + 127) / 128;
+ int scale_columns = (group_width + 127) / 128;
int scale_rows_per_group = (o_rank + 127) / 128;
for (int group = 0; !result && group < groups; group++) {
ColiTensorView group_view = wo_a;
@@ -2028,7 +2091,7 @@ int coli_v4_attention_window_batch_ref(
int heads_per_group = heads / groups;
int group_width = heads_per_group * head_dim;
- int scale_columns = (hidden + 127) / 128;
+ int scale_columns = (group_width + 127) / 128;
int scale_rows = (o_rank + 127) / 128;
float *group_inputs = malloc((size_t)batch * group_width * sizeof(*group_inputs));
float *group_outputs = malloc((size_t)batch * o_rank * sizeof(*group_outputs));
@@ -4547,7 +4610,7 @@ static int attention_token_impl(float *output,
int heads_per_group = heads / groups;
int group_width = heads_per_group * head_dim;
- int scale_columns = (hidden + 127) / 128;
+ int scale_columns = (group_width + 127) / 128;
int scale_rows_per_group = (o_rank + 127) / 128;
for (int group = 0; !result && group < groups; group++) {
ColiTensorView group_view = wo_a;
@@ -8376,6 +8439,10 @@ int coli_v4_layer_plan(ColiDeepSeekV4LayerPlan *plan,
const int64_t heads = config->num_attention_heads;
const int64_t head_dim = config->head_dim;
const int64_t q_rank = config->q_lora_rank;
+ if (config->o_groups < 1 || heads % config->o_groups != 0)
+ return set_error(error, error_size, "unsupported grouped-output attention dimensions");
+ const int64_t o_group_width =
+ (heads / config->o_groups) * head_dim;
const int64_t o_width = (int64_t)config->o_groups * config->o_lora_rank;
const int64_t experts = config->n_routed_experts;
const int64_t moe = config->moe_intermediate_size;
@@ -8386,7 +8453,7 @@ int coli_v4_layer_plan(ColiDeepSeekV4LayerPlan *plan,
ADD(add_1d(plan, COLI_ST_BF16, head_dim, "attn.kv_norm.weight", error, error_size));
ADD(add_1d(plan, COLI_ST_BF16, q_rank, "attn.q_norm.weight", error, error_size));
ADD(add_fp8(plan, head_dim, hidden, "attn.wkv", error, error_size));
- ADD(add_fp8(plan, o_width, hidden, "attn.wo_a", error, error_size));
+ ADD(add_fp8(plan, o_width, o_group_width, "attn.wo_a", error, error_size));
ADD(add_fp8(plan, hidden, o_width, "attn.wo_b", error, error_size));
ADD(add_fp8(plan, q_rank, hidden, "attn.wq_a", error, error_size));
ADD(add_fp8(plan, heads * head_dim, q_rank, "attn.wq_b", error, error_size));
diff --git a/c/deepseek_v4_dspark.c b/c/deepseek_v4_dspark.c
index 8ec92920..09b88b32 100644
--- a/c/deepseek_v4_dspark.c
+++ b/c/deepseek_v4_dspark.c
@@ -1407,7 +1407,7 @@ int coli_v4_dspark_attention_block(
}
int heads_per_group = heads / groups;
int group_width = heads_per_group * d;
- int scale_columns = (hidden + 127) / 128;
+ int scale_columns = (group_width + 127) / 128;
int scale_rows = (orank + 127) / 128;
float *group_inputs = malloc((size_t)batch * group_width * sizeof(float));
float *group_outputs = malloc((size_t)batch * orank * sizeof(float));
diff --git a/c/deepseek_v4_internal.h b/c/deepseek_v4_internal.h
index 69df5cf1..a9fa3434 100644
--- a/c/deepseek_v4_internal.h
+++ b/c/deepseek_v4_internal.h
@@ -507,11 +507,32 @@ typedef struct {
int slots_per_layer;
} ColiDeepSeekV4ResourcePlan;
+typedef struct {
+ uint64_t available_bytes;
+ uint64_t fixed_bytes;
+ uint64_t dense_bytes;
+ uint64_t dspark_streamed_bytes;
+ uint64_t dspark_full_bytes;
+ uint64_t minimum_expert_bytes;
+ int has_dspark;
+} ColiDeepSeekV4ResidentTierInputs;
+
+typedef struct {
+ uint64_t dense_bytes;
+ uint64_t dspark_bytes;
+ int dense_resident;
+ int dspark_resident;
+} ColiDeepSeekV4ResidentTierPlan;
+
uint64_t coli_v4_os_available_memory(void);
int coli_v4_resource_plan_compute(
ColiDeepSeekV4ResourcePlan *plan,
const ColiDeepSeekV4ResourceInputs *inputs,
char *error, size_t error_size);
+int coli_v4_resident_tier_plan(
+ ColiDeepSeekV4ResidentTierPlan *plan,
+ const ColiDeepSeekV4ResidentTierInputs *inputs,
+ char *error, size_t error_size);
/* ==== end deepseek_v4_resource_plan.h ==== */
/* ==== begin deepseek_v4_head_cache.h ==== */
diff --git a/c/tests/test_deepseek_v4.c b/c/tests/test_deepseek_v4.c
index 2a353b15..3b7efcdf 100644
--- a/c/tests/test_deepseek_v4.c
+++ b/c/tests/test_deepseek_v4.c
@@ -168,9 +168,18 @@ static int test_config(int argc, char **argv) {
fprintf(stderr, "%s\n", error);
return 1;
}
- if (config.hidden_size != 4096 || config.num_hidden_layers != 43 ||
- config.n_routed_experts != 256 || config.num_experts_per_tok != 6 ||
- config.compress_ratio_count != 44 || config.compress_ratios[2] != 4 ||
+ int flash = config.hidden_size == 4096 &&
+ config.num_hidden_layers == 43 &&
+ config.n_routed_experts == 256 &&
+ config.compress_ratio_count == 44 &&
+ config.compress_ratios[0] == 0;
+ int pro = config.hidden_size == 7168 &&
+ config.num_hidden_layers == 61 &&
+ config.n_routed_experts == 384 &&
+ config.compress_ratio_count == 62 &&
+ config.compress_ratios[0] == 128;
+ if ((!flash && !pro) || config.num_experts_per_tok != 6 ||
+ config.compress_ratios[2] != 4 ||
config.compress_ratios[3] != 128 || config.hc_mult != 4)
return 1;
}
@@ -446,6 +455,20 @@ static int test_layer(void) {
assert(ape && ape->shape[0] == 128 && ape->shape[1] == 512);
assert(find_spec(&plan, "ffn.gate.bias") != NULL);
+ /* V4 Pro no longer has hidden_size == one output-attention group's
+ input width. Keep the grouped wo_a layout derived from heads/groups. */
+ config.hidden_size = 7168;
+ config.num_attention_heads = 128;
+ config.o_groups = 16;
+ assert(coli_v4_layer_plan(&plan, &config, 0, error, sizeof(error)) == 0);
+ const ColiDeepSeekV4TensorSpec *wo_a =
+ find_spec(&plan, "attn.wo_a.weight");
+ const ColiDeepSeekV4TensorSpec *wo_a_scale =
+ find_spec(&plan, "attn.wo_a.scale");
+ assert(wo_a && wo_a->shape[0] == 16384 && wo_a->shape[1] == 4096);
+ assert(wo_a_scale && wo_a_scale->shape[0] == 128 &&
+ wo_a_scale->shape[1] == 32);
+
puts("deepseek_v4_layer tests passed");
return 0;
}
@@ -644,6 +667,49 @@ static int test_resource_plan(void) {
input = fixture(4 * GIB);
if (coli_v4_resource_plan_compute(&capped, &input, error, sizeof(error)) == 0)
return 1;
+
+ ColiDeepSeekV4ResidentTierPlan tiers;
+ ColiDeepSeekV4ResidentTierInputs target_only = {
+ 40 * GIB, 4 * GIB, 24 * GIB, 0, 0, 12 * GIB, 0,
+ };
+ if (coli_v4_resident_tier_plan(
+ &tiers, &target_only, error, sizeof(error)) ||
+ !tiers.dense_resident || tiers.dspark_resident ||
+ tiers.dense_bytes != 24 * GIB || tiers.dspark_bytes)
+ return 1;
+ target_only.available_bytes = 39 * GIB;
+ if (coli_v4_resident_tier_plan(
+ &tiers, &target_only, error, sizeof(error)) ||
+ tiers.dense_resident || tiers.dspark_resident || tiers.dense_bytes ||
+ tiers.dspark_bytes)
+ return 1;
+
+ ColiDeepSeekV4ResidentTierInputs with_dspark = {
+ 60 * GIB, 4 * GIB, 24 * GIB, 2 * GIB, 20 * GIB, 12 * GIB, 1,
+ };
+ if (coli_v4_resident_tier_plan(
+ &tiers, &with_dspark, error, sizeof(error)) ||
+ !tiers.dense_resident || !tiers.dspark_resident ||
+ tiers.dense_bytes != 24 * GIB || tiers.dspark_bytes != 20 * GIB)
+ return 1;
+ with_dspark.available_bytes = 48 * GIB;
+ if (coli_v4_resident_tier_plan(
+ &tiers, &with_dspark, error, sizeof(error)) ||
+ !tiers.dense_resident || tiers.dspark_resident ||
+ tiers.dense_bytes != 24 * GIB || tiers.dspark_bytes != 2 * GIB)
+ return 1;
+ with_dspark.available_bytes = 40 * GIB;
+ if (coli_v4_resident_tier_plan(
+ &tiers, &with_dspark, error, sizeof(error)) ||
+ tiers.dense_resident || !tiers.dspark_resident || tiers.dense_bytes ||
+ tiers.dspark_bytes != 20 * GIB)
+ return 1;
+ with_dspark.available_bytes = 32 * GIB;
+ if (coli_v4_resident_tier_plan(
+ &tiers, &with_dspark, error, sizeof(error)) ||
+ tiers.dense_resident || tiers.dspark_resident || tiers.dense_bytes ||
+ tiers.dspark_bytes != 2 * GIB)
+ return 1;
puts("DeepSeek V4 resource plan tests: ok");
return 0;
}
diff --git a/c/tests/test_v4_cli.py b/c/tests/test_v4_cli.py
index 16d9eb8f..629cfd72 100644
--- a/c/tests/test_v4_cli.py
+++ b/c/tests/test_v4_cli.py
@@ -81,12 +81,37 @@ class V4CliTest(unittest.TestCase):
def test_engine_command_prefers_prompt_file(self):
cli = load_cli()
- args = argparse.Namespace(model=str(HERE), ngen=32, ram=0, stop_sentence=False)
+ args = argparse.Namespace(
+ model=str(HERE), draft_model=None, ngen=32, ram=0,
+ stop_sentence=False,
+ )
command = cli.engine_command(args, raw=True, prompt_file=r"C:\tmp\prompt.txt")
self.assertIn("--prompt-file", command)
+ self.assertIn("--no-dspark", command)
self.assertIn(r"C:\tmp\prompt.txt", command)
self.assertNotIn("你好", command)
+ def test_engine_command_enables_explicit_dspark_model(self):
+ cli = load_cli()
+ args = argparse.Namespace(
+ model=str(HERE), draft_model=str(HERE / "draft"), ngen=1,
+ ram=0, stop_sentence=False,
+ )
+ command = cli.engine_command(args, prompt="hello")
+ self.assertIn("--draft-model", command)
+ self.assertIn(str((HERE / "draft").resolve()), command)
+ self.assertNotIn("--no-dspark", command)
+
+ def test_engine_command_keeps_combined_dspark_default(self):
+ cli = load_cli()
+ args = argparse.Namespace(
+ model=str(HERE), draft_model=None, model_has_dspark=True,
+ ngen=1, ram=0, stop_sentence=False,
+ )
+ command = cli.engine_command(args, prompt="hello")
+ self.assertNotIn("--no-dspark", command)
+ self.assertNotIn("--draft-model", command)
+
def test_write_prompt_file_is_utf8(self):
cli = load_cli()
path = cli.write_prompt_file("你好")
diff --git a/c/v4 b/c/v4
index b4f2f630..205aa979 100644
--- a/c/v4
+++ b/c/v4
@@ -18,6 +18,12 @@ BOS = "<\uff5cbegin\u2581of\u2581sentence\uff5c>"
USER = "<\uff5cUser\uff5c>"
ASSISTANT = "<\uff5cAssistant\uff5c>"
EOS = "<\uff5cend\u2581of\u2581sentence\uff5c>"
+DSPARK_CONFIG_FIELDS = (
+ "dspark_block_size",
+ "dspark_noise_token_id",
+ "dspark_markov_rank",
+ "dspark_target_layer_ids",
+)
def configure_stdio_utf8():
@@ -78,6 +84,11 @@ def validate_model(model):
)
if not is_v4:
raise SystemExit(f"model is not a DeepSeek V4 checkpoint: {model}")
+ return config
+
+
+def has_dspark_manifest(config):
+ return all(field in config for field in DSPARK_CONFIG_FIELDS)
def validate_engine():
@@ -113,6 +124,13 @@ def engine_command(args, prompt=None, raw=True, prompt_file=None):
command.append("--raw-prompt")
if args.ram:
command.extend(("--memory-gb", f"{args.ram:g}"))
+ draft_model = getattr(args, "draft_model", None)
+ if draft_model:
+ command.extend(("--draft-model", os.path.abspath(draft_model)))
+ elif not getattr(args, "model_has_dspark", False):
+ # Target-only checkpoints (including V4 Pro) do not carry the
+ # dspark_* manifest required by the native speculative runner.
+ command.append("--no-dspark")
if getattr(args, "stop_sentence", False):
command.append("--stop-sentence")
return command
@@ -181,7 +199,14 @@ def emit_bytes(chunk):
def generate(args, prompt, raw=True, stream=True):
- validate_model(args.model)
+ target_config = validate_model(args.model)
+ args.model_has_dspark = has_dspark_manifest(target_config)
+ if getattr(args, "draft_model", None):
+ draft_config = validate_model(args.draft_model)
+ if not has_dspark_manifest(draft_config):
+ raise SystemExit(
+ f"DSpark config fields are missing from {args.draft_model}"
+ )
validate_engine()
# Always pass the prompt through a UTF-8 file. Windows argv uses the ANSI
# code page for MinGW main(), which corrupts Chinese from PowerShell.
@@ -263,6 +288,8 @@ def cmd_chat(args):
def add_runtime_arguments(parser):
parser.add_argument("--model", required=True, help="DeepSeek V4 model directory")
+ parser.add_argument("--draft-model", metavar="PATH",
+ help="separate DSpark checkpoint; disabled when no manifest is present")
parser.add_argument("--ram", type=positive_float, default=0, metavar="GIB",
help="process RAM limit in GiB (default: auto)")
parser.add_argument("--ngen", type=positive_int, default=128, metavar="N",