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

perf(dsv4): bound expert miss selection cost

JustVugg45fb8b2ac295
diff --git a/c/deepseek_v4.c b/c/deepseek_v4.c
index c0a6f1b1..4842b918 100644
--- a/c/deepseek_v4.c
+++ b/c/deepseek_v4.c
@@ -7025,6 +7025,9 @@ typedef struct {
uint64_t used;
unsigned char *slab;
int aligned_slab;
+ int lru_previous;
+ int lru_next;
+ unsigned char in_lru;
} V4ExpertSlot;
typedef struct {
@@ -7037,6 +7040,9 @@ typedef struct {
V4ExpertSlot *slots;
int *slot_by_expert; /* resident/in-flight slot; every StoreOps variant that
* mutates slot identity must maintain this index */
+ int *allocated_per_layer;
+ int *lru_head;
+ int *lru_tail;
uint64_t clock;
unsigned active_leases;
ColiExpertStoreStats stats;
@@ -7135,6 +7141,74 @@ static V4ExpertSlot *layer_slots(V4ExpertStoreState *state, int layer) {
return state->slots + (size_t)layer * state->slots_per_layer;
}
+#ifdef COLI_V4_TEST_HOOKS
+uint64_t coli_v4_test_expert_victim_probes;
+#define V4_COUNT_VICTIM_PROBE() (coli_v4_test_expert_victim_probes++)
+#else
+#define V4_COUNT_VICTIM_PROBE() ((void)0)
+#endif
+
+/* All LRU helpers are called with state->mutex held. Slabs are allocated in
+ * slot order and never freed before store destruction, so the next empty slot
+ * is O(1). Allocated slots form one exact LRU list per layer: moving a slot to
+ * the tail is equivalent to assigning the old monotonically increasing used
+ * timestamp, without searching the whole cache for its minimum on a miss. */
+static void touch_lru_slot(V4ExpertStoreState *state, int layer,
+ V4ExpertSlot *slot) {
+ int index = (int)(slot - state->slots);
+ int layer_begin = layer * state->slots_per_layer;
+ int layer_end = layer_begin + state->slots_per_layer;
+ assert(index >= layer_begin && index < layer_end);
+ if (slot->in_lru) {
+ if (slot->lru_previous >= 0)
+ state->slots[slot->lru_previous].lru_next = slot->lru_next;
+ else
+ state->lru_head[layer] = slot->lru_next;
+ if (slot->lru_next >= 0)
+ state->slots[slot->lru_next].lru_previous = slot->lru_previous;
+ else
+ state->lru_tail[layer] = slot->lru_previous;
+ } else {
+ slot->in_lru = 1;
+ }
+ slot->lru_previous = state->lru_tail[layer];
+ slot->lru_next = -1;
+ if (state->lru_tail[layer] >= 0)
+ state->slots[state->lru_tail[layer]].lru_next = index;
+ else
+ state->lru_head[layer] = index;
+ state->lru_tail[layer] = index;
+}
+
+static V4ExpertSlot *next_empty_slot(V4ExpertStoreState *state, int layer) {
+ int next = state->allocated_per_layer[layer];
+ if (next >= state->slots_per_layer) return NULL;
+ return layer_slots(state, layer) + next;
+}
+
+static void mark_slot_allocated(V4ExpertStoreState *state, int layer,
+ V4ExpertSlot *slot) {
+ assert(slot == layer_slots(state, layer) +
+ state->allocated_per_layer[layer]);
+ state->allocated_per_layer[layer]++;
+ touch_lru_slot(state, layer, slot);
+}
+
+/* Only referenced (in-use/in-flight) slots can precede the victim. Therefore
+ * passive cache capacity -- and consequently configured RAM -- does not add
+ * work to an ordinary miss. */
+static V4ExpertSlot *oldest_unreferenced_slot(V4ExpertStoreState *state,
+ int layer) {
+ int index = state->lru_head[layer];
+ while (index >= 0) {
+ V4ExpertSlot *slot = &state->slots[index];
+ V4_COUNT_VICTIM_PROBE();
+ if (!slot->references) return slot;
+ index = slot->lru_next;
+ }
+ return NULL;
+}
+
/* All index helpers are called with state->mutex held. A single table entry
* covers both a published expert and its in-flight reservation, so the hot
* path and the single-flight path are O(1) in cache capacity. */
@@ -7209,18 +7283,14 @@ static int lookup(ColiExpertStore *store, ColiExpertKey key,
}
pthread_mutex_lock(&state->mutex);
state->stats.requests++;
- V4ExpertSlot *slots = layer_slots(state, key.layer);
V4ExpertSlot *slot = indexed_expert_slot(state, key);
if (slot && slot->slab && slot->expert == key.expert)
state->stats.hits++;
else
slot = NULL;
if (!slot) {
- for (int i = 0; i < state->slots_per_layer; i++) {
- if (!slots[i].references && (!slot || !slots[i].slab ||
- (slot->slab && slots[i].used < slot->used)))
- slot = &slots[i];
- }
+ slot = next_empty_slot(state, key.layer);
+ if (!slot) slot = oldest_unreferenced_slot(state, key.layer);
if (!slot) {
pthread_mutex_unlock(&state->mutex);
memset(view, 0, sizeof(*view));
@@ -7233,6 +7303,7 @@ static int lookup(ColiExpertStore *store, ColiExpertKey key,
memset(view, 0, sizeof(*view));
return -1;
}
+ mark_slot_allocated(state, key.layer, slot);
state->stats.resident_bytes += state->record_bytes;
}
/* A short read must never expose a partially overwritten old slot. */
@@ -7273,6 +7344,7 @@ static int lookup(ColiExpertStore *store, ColiExpertKey key,
slot->references++;
state->active_leases++;
slot->used = ++state->clock;
+ touch_lru_slot(state, key.layer, slot);
if (state->ehit) {
size_t expert_index =
(size_t)key.layer * state->experts_per_layer + key.expert;
@@ -7384,6 +7456,9 @@ static void destroy(ColiExpertStore *store) {
free(state->records);
free(state->slots);
free(state->slot_by_expert);
+ free(state->allocated_per_layer);
+ free(state->lru_head);
+ free(state->lru_tail);
free(state->ehit);
free(state->eheat);
free(state);
@@ -7461,13 +7536,24 @@ int coli_deepseek_v4_expert_store_open(
state->slots_per_layer = state->experts_per_layer;
state->slots = calloc((size_t)state->layers * state->slots_per_layer,
sizeof(*state->slots));
- if (!state->slots) {
+ state->allocated_per_layer = calloc(
+ (size_t)state->layers, sizeof(*state->allocated_per_layer));
+ state->lru_head = malloc((size_t)state->layers * sizeof(*state->lru_head));
+ state->lru_tail = malloc((size_t)state->layers * sizeof(*state->lru_tail));
+ if (!state->slots || !state->allocated_per_layer || !state->lru_head ||
+ !state->lru_tail) {
set_error(error, error_size, "out of memory creating expert cache slots");
goto fail;
}
+ for (int layer = 0; layer < state->layers; layer++) {
+ state->lru_head[layer] = -1;
+ state->lru_tail[layer] = -1;
+ }
for (int i = 0; i < state->layers * state->slots_per_layer; i++) {
state->slots[i].expert = -1;
state->slots[i].loading_expert = -1;
+ state->slots[i].lru_previous = -1;
+ state->slots[i].lru_next = -1;
}
size_t telemetry_cells =
(size_t)state->layers * state->experts_per_layer;
@@ -7492,6 +7578,9 @@ fail:
if (state->slots) free(state->slots);
free(state->records);
free(state->slot_by_expert);
+ free(state->allocated_per_layer);
+ free(state->lru_head);
+ free(state->lru_tail);
free(state->ehit);
free(state->eheat);
coli_st_index_close(state->index);
@@ -7907,8 +7996,10 @@ static void hot_repin_locked(V4HotPolicy *policy, V4ExpertStoreState *state,
if (expert < 0) continue;
V4ExpertSlot *slot = indexed_expert_slot(
state, (ColiExpertKey){layer, expert});
- if (slot && slot->slab && slot->expert == expert)
+ if (slot && slot->slab && slot->expert == expert) {
slot->used = ++state->clock;
+ touch_lru_slot(state, layer, slot);
+ }
}
uint64_t decay_interval = policy->repin_interval * 64;
if (decay_interval && policy->layer_requests[layer] &&
@@ -7917,6 +8008,27 @@ static void hot_repin_locked(V4HotPolicy *policy, V4ExpertStoreState *state,
usage[expert] = (usage[expert] + 1) / 2;
}
+/* Return the exact oldest unreferenced, non-pinned slot. The fallback is the
+ * exact oldest unreferenced slot, matching the previous three-scan policy when
+ * every available slot is pinned. Each skipped node is either an active
+ * lease/in-flight load or one of the small bounded pin set -- never merely an
+ * extra slot made possible by more RAM. */
+static V4ExpertSlot *hot_oldest_victim(V4ExpertStoreState *state,
+ const V4HotPolicy *policy, int layer) {
+ V4ExpertSlot *fallback = NULL;
+ int index = state->lru_head[layer];
+ while (index >= 0) {
+ V4ExpertSlot *slot = &state->slots[index];
+ V4_COUNT_VICTIM_PROBE();
+ if (!slot->references) {
+ if (!fallback) fallback = slot;
+ if (!hot_is_pinned(policy, layer, slot->expert)) return slot;
+ }
+ index = slot->lru_next;
+ }
+ return fallback;
+}
+
static int lookup_hot(ColiExpertStore *store, ColiExpertKey key,
ColiExpertView *view) {
if (!store || !store->state || !view) {
@@ -7946,7 +8058,6 @@ static int lookup_hot(ColiExpertStore *store, ColiExpertKey key,
layer_requests % policy->repin_interval == 0)
hot_repin_locked(policy, state, key.layer);
- V4ExpertSlot *slots = layer_slots(state, key.layer);
V4ExpertSlot *slot;
retry_lookup:
slot = indexed_expert_slot(state, key);
@@ -7954,6 +8065,7 @@ retry_lookup:
slot->references++;
state->active_leases++;
slot->used = ++state->clock; state->stats.hits++;
+ touch_lru_slot(state, key.layer, slot);
if (hot_is_pinned(policy, key.layer, key.expert) && !store->gpu)
hot_pack_slot_locked(policy, state, record, slot);
memset(view, 0, sizeof(*view)); view->key = key;
@@ -7979,17 +8091,8 @@ retry_lookup:
}
goto retry_lookup;
}
- for (int i = 0; i < state->slots_per_layer; i++)
- if (!slots[i].references && !slots[i].slab) { slot = &slots[i]; break; }
- if (!slot)
- for (int i = 0; i < state->slots_per_layer; i++)
- if (!slots[i].references &&
- !hot_is_pinned(policy, key.layer, slots[i].expert) &&
- (!slot || slots[i].used < slot->used)) slot = &slots[i];
- if (!slot)
- for (int i = 0; i < state->slots_per_layer; i++)
- if (!slots[i].references && (!slot || slots[i].used < slot->used))
- slot = &slots[i];
+ slot = next_empty_slot(state, key.layer);
+ if (!slot) slot = hot_oldest_victim(state, policy, key.layer);
if (!slot) {
pthread_mutex_unlock(&state->mutex);
memset(view, 0, sizeof(*view));
@@ -8004,6 +8107,7 @@ retry_lookup:
return -1;
}
slot->aligned_slab = 1;
+ mark_slot_allocated(state, key.layer, slot);
state->stats.resident_bytes += state->record_bytes;
}
policy->packed[hot_slot_index(state, slot)] = 0;
@@ -8013,6 +8117,7 @@ retry_lookup:
slot->references = 1;
state->active_leases++;
slot->used = ++state->clock;
+ touch_lru_slot(state, key.layer, slot);
pthread_mutex_unlock(&state->mutex);
int rep = coli_st_expert_route(key.layer, key.expert);
struct timespec disk_t0;
@@ -8050,6 +8155,7 @@ retry_lookup:
}
slot->expert = key.expert; slot->loading_expert = -1;
slot->used = ++state->clock;
+ touch_lru_slot(state, key.layer, slot);
state->stats.misses++; state->stats.bytes_read += record->record_bytes;
hot_pack_slot_commit(policy, state, record, slot, v4_pack_buf);
v4_pack_buf = NULL;
diff --git a/c/deepseek_v4_internal.h b/c/deepseek_v4_internal.h
index 029892c2..f5c70087 100644
--- a/c/deepseek_v4_internal.h
+++ b/c/deepseek_v4_internal.h
@@ -966,6 +966,7 @@ extern int coli_v4_test_closed_owned_index;
extern void (*coli_v4_test_expert_read_hook)(ColiExpertKey key);
extern void (*coli_v4_test_expert_wait_hook)(ColiExpertKey key);
extern uint64_t coli_v4_test_fp4_batch_calls;
+extern uint64_t coli_v4_test_expert_victim_probes;
int coli_v4_test_expert_slot_index(ColiExpertStore *store, ColiExpertKey key);
ColiV4Session *coli_v4_test_session_bare_create(ColiV4Engine *engine);
diff --git a/c/tests/test_deepseek_v4.c b/c/tests/test_deepseek_v4.c
index 8c85992e..fa4f8a04 100644
--- a/c/tests/test_deepseek_v4.c
+++ b/c/tests/test_deepseek_v4.c
@@ -384,54 +384,77 @@ static int write_all(int fd, const void *data, size_t length) {
return 0;
}
-static int write_fixture(const char *path) {
+static int write_fixture_experts(const char *path, int expert_count) {
static const char *matrix_names[3] = {"w1", "w2", "w3"};
- char header[16384];
+ if (expert_count < 1 || (size_t)expert_count > SIZE_MAX / 1024) return -1;
+ size_t header_capacity = 256 + (size_t)expert_count * 1024;
+ char *header = malloc(header_capacity);
+ size_t payload_size = 4 + (size_t)expert_count * 51;
+ unsigned char *payload = malloc(payload_size);
+ if (!header || !payload) {
+ free(payload);
+ free(header);
+ return -1;
+ }
size_t used = (size_t)snprintf(
- header, sizeof(header),
+ header, header_capacity,
"{\"resident\":{\"dtype\":\"F32\",\"shape\":[1],"
"\"data_offsets\":[3,7]}");
- for (int expert = 0; expert < 7; expert++) {
- int scale = expert ? 4 + expert * 51 : 0;
- int weight = scale + 3 + (expert ? 0 : 4);
+ for (int expert = 0; expert < expert_count; expert++) {
+ size_t scale = expert ? 4 + (size_t)expert * 51 : 0;
+ size_t weight = scale + 3 + (expert ? 0 : 4);
for (int matrix = 0; matrix < 3; matrix++) {
int count = snprintf(
- header + used, sizeof(header) - used,
+ header + used, header_capacity - used,
",\"layers.0.ffn.experts.%d.%s.scale\":{"
"\"dtype\":\"F8_E8M0\",\"shape\":[1,1],"
- "\"data_offsets\":[%d,%d]}",
+ "\"data_offsets\":[%zu,%zu]}",
expert, matrix_names[matrix], scale + matrix,
scale + matrix + 1);
- if (count < 0 || (size_t)count >= sizeof(header) - used) return -1;
+ if (count < 0 || (size_t)count >= header_capacity - used) {
+ free(payload); free(header); return -1;
+ }
used += (size_t)count;
}
for (int matrix = 0; matrix < 3; matrix++) {
int count = snprintf(
- header + used, sizeof(header) - used,
+ header + used, header_capacity - used,
",\"layers.0.ffn.experts.%d.%s.weight\":{"
"\"dtype\":\"I8\",\"shape\":[1,16],"
- "\"data_offsets\":[%d,%d]}",
+ "\"data_offsets\":[%zu,%zu]}",
expert, matrix_names[matrix], weight + matrix * 16,
weight + (matrix + 1) * 16);
- if (count < 0 || (size_t)count >= sizeof(header) - used) return -1;
+ if (count < 0 || (size_t)count >= header_capacity - used) {
+ free(payload); free(header); return -1;
+ }
used += (size_t)count;
}
}
- if (used + 1 >= sizeof(header)) return -1;
+ if (used + 1 >= header_capacity) {
+ free(payload); free(header); return -1;
+ }
header[used++] = '}';
header[used] = '\0';
- unsigned char payload[361];
- for (int i = 0; i < 361; i++) payload[i] = (unsigned char)i;
+ for (size_t i = 0; i < payload_size; i++)
+ payload[i] = (unsigned char)i;
uint64_t header_length = used;
int fd = open(path, O_CREAT | O_TRUNC | O_WRONLY | COMPAT_O_BINARY, 0600);
- if (fd < 0) return -1;
+ if (fd < 0) {
+ free(payload); free(header); return -1;
+ }
int result = write_all(fd, &header_length, sizeof(header_length)) ||
write_all(fd, header, (size_t)header_length) ||
- write_all(fd, payload, sizeof(payload));
+ write_all(fd, payload, payload_size);
close(fd);
+ free(payload);
+ free(header);
return result ? -1 : 0;
}
+static int write_fixture(const char *path) {
+ return write_fixture_experts(path, 7);
+}
+
static int expect_fixture_expert(const ColiExpertView *view, int expert) {
int scale = expert ? 4 + expert * 51 : 0;
int weight = scale + 3 + (expert ? 0 : 4);
@@ -732,6 +755,92 @@ static int test_expert_store(void) {
puts("DeepSeek-V4 ExpertStore tests: ok");
return 0;
}
+
+static int run_expert_miss_scaling_case(const char *directory, int experts,
+ int slots) {
+ char error[256];
+ ColiDeepSeekV4ExpertStoreOptions options = {
+ directory, 1, experts, (uint64_t)slots * 51, -1, UINT64_MAX
+ };
+ ColiExpertStore *store = NULL;
+ if (coli_deepseek_v4_expert_store_open(&options, &store,
+ error, sizeof(error))) {
+ fprintf(stderr, "scaling store open failed: slots=%d error=%s\n",
+ slots, error);
+ return 1;
+ }
+ coli_v4_test_expert_victim_probes = 0;
+ for (int expert = 0; expert < slots; expert++) {
+ ColiExpertView view;
+ if (coli_expert_lookup(store, (ColiExpertKey){0, expert}, &view)) {
+ fprintf(stderr, "scaling fill failed: slots=%d expert=%d\n",
+ slots, expert);
+ store->ops->destroy(store);
+ return 1;
+ }
+ coli_expert_release(store, &view);
+ }
+ if (coli_v4_test_expert_victim_probes != 0) {
+ fprintf(stderr,
+ "empty-slot fill searched residents: slots=%d probes=%llu\n",
+ slots, (unsigned long long)coli_v4_test_expert_victim_probes);
+ store->ops->destroy(store);
+ return 1;
+ }
+
+ coli_v4_test_expert_victim_probes = 0;
+ ColiExpertView view;
+ if (coli_expert_lookup(store, (ColiExpertKey){0, experts - 1}, &view)) {
+ fprintf(stderr, "scaling eviction failed: slots=%d\n", slots);
+ store->ops->destroy(store);
+ return 1;
+ }
+ uint64_t probes = coli_v4_test_expert_victim_probes;
+ coli_expert_release(store, &view);
+ ColiExpertStoreStats stats;
+ store->ops->stats(store, &stats);
+ int failed = probes != 1 || stats.requests != (uint64_t)slots + 1 ||
+ stats.hits != 0 || stats.misses != (uint64_t)slots + 1 ||
+ stats.bytes_read != ((uint64_t)slots + 1) * 51 ||
+ stats.resident_bytes != (uint64_t)slots * 51 ||
+ stats.capacity_bytes != (uint64_t)slots * 51;
+ if (failed)
+ fprintf(stderr,
+ "miss scaling mismatch: slots=%d probes=%llu requests=%llu "
+ "hits=%llu misses=%llu bytes=%llu resident=%llu capacity=%llu\n",
+ slots, (unsigned long long)probes,
+ (unsigned long long)stats.requests,
+ (unsigned long long)stats.hits,
+ (unsigned long long)stats.misses,
+ (unsigned long long)stats.bytes_read,
+ (unsigned long long)stats.resident_bytes,
+ (unsigned long long)stats.capacity_bytes);
+ store->ops->destroy(store);
+ return failed;
+}
+
+static int test_expert_store_miss_scaling(void) {
+ char directory[] = "colibri-v4-scaling-XXXXXX";
+ char path[256];
+ setenv("COLI_V4_AUTOPIN", "0", 1);
+ setenv("COLI_V4_SAVE_USAGE", "0", 1);
+ setenv("COLI_V4_ROWS16", "0", 1);
+ if (!mkdtemp(directory)) { perror("mkdtemp scaling"); return 1; }
+ snprintf(path, sizeof(path), "%s/model.safetensors", directory);
+ if (write_fixture_experts(path, 256)) {
+ perror("write scaling fixture");
+ rmdir(directory);
+ return 1;
+ }
+ int result = run_expert_miss_scaling_case(directory, 256, 44) ||
+ run_expert_miss_scaling_case(directory, 256, 219);
+ unlink(path);
+ rmdir(directory);
+ if (result) return 1;
+ puts("DeepSeek-V4 ExpertStore miss scaling: ok "
+ "(44 slots=1 probe, 219 slots=1 probe)");
+ return 0;
+}
/* ==== end test_deepseek_v4_expert_store.c ==== */
/* ==== begin test_deepseek_v4_kv_cache.c ==== */
@@ -1192,6 +1301,10 @@ int main(int argc, char **argv) {
fprintf(stderr, "FAIL: test_expert_store\n");
return 1;
}
+ if (test_expert_store_miss_scaling() != 0) {
+ fprintf(stderr, "FAIL: test_expert_store_miss_scaling\n");
+ return 1;
+ }
if (test_kv_cache() != 0) {
fprintf(stderr, "FAIL: test_kv_cache\n");
return 1;