Run frontier MoE models on hardware you already own — pure C, zero deps, experts streamed from disk. Tiny engine, immense model. 🐦
C
vk_tier: RAM and VRAM without the same experts when RAM is short (COLI_VK_TIER_EXCLUSIVE)
JustVugg7c84eeea8f07
diff --git a/c/colibri.c b/c/colibri.cindex 319d1b0a..a21f81d5 100644--- a/c/colibri.c+++ b/c/colibri.c@@ -110,6 +110,10 @@ static inline void omp_set_num_threads(int n){ (void)n; }#include "backend_vulkan.h"#include "vk_tier.h" /* the routed-expert tier the MoE engines share */#endif+#ifndef COLI_VULKAN /* exclusive RAM/VRAM (vk_tier.h) is the Vulkan build's: no device holds an expert */+static inline int vkt_ram_first(int layer, int eid) { (void)layer; (void)eid; return 0; }+static inline void vkt_ram_gave(void) {}+#endif#ifdef COLI_XDNA/* Optional AMD XDNA2 lane. This header pulls in no XRT: the engine owns the* prepared-host state, and XRT lives only behind an optional helper DLL. */@@ -451,17 +455,21 @@ static void eslots_release(ESlot **slots,int n){ for(int i=0;i<n;i++) eslot_rele* prenotazioni in volo (eid<-1) contano come vive: stanno per possederne uno.* EN: reusing a slab-less slot re-allocates, so it only counts as eviction* EN: while the row's live-slab count is under ecap; else pick a slab owner. */-static int eslot_lru_victim(ESlot *slots,int n,int ecap){- int lru=-1, empty=-1, live=0;+static int eslot_lru_victim(ESlot *slots,int n,int ecap,int layer){+ int lru=-1, empty=-1, live=0, dev=-1;for(int i=0;i<n;i++){ESlot *s=&slots[i];if(s->slab || s->eid<-1) live++;if(eslot_busy(s) || s->eid<-1) continue;if(!s->slab){ if(s->eid==-1 && empty<0) empty=i; continue; }if(s->eid==-1) return i; /* slot libero che possiede ancora lo slab */+ /* un expert che il tier Vulkan tiene gia' esce prima (vkt_ram_first: con poca RAM+ * la RAM e la VRAM non tengono gli stessi expert) */+ if(vkt_ram_first(layer,s->eid)){ if(dev<0 || s->used<slots[dev].used) dev=i; continue; }if(lru<0 || s->used<slots[lru].used) lru=i;}if(empty>=0 && live<ecap) return empty; /* sotto il tetto: meglio il vuoto che sfrattare */+ if(dev>=0){ vkt_ram_gave(); return dev; }return lru;}@@ -5465,7 +5473,7 @@ static void ecache_promote_ws(Model *m,int layer,int nmiss){int promo = nmiss<m->ecap ? nmiss : m->ecap;for(int a=0;a<promo;a++){ int q=nmiss-1-a; ESlot *dst;if(*nn<m->ecap) dst=&Sl[(*nn)++];- else { int lru=eslot_lru_victim(Sl,*nn,m->ecap);+ else { int lru=eslot_lru_victim(Sl,*nn,m->ecap,layer);if(lru<0){ static int warned;if(!warned){ warned=1; fprintf(stderr,"[CUDA] no reusable LRU expert slot (in flight or cap reached); skipping cache promotion\n"); }continue; }@@ -6925,7 +6933,7 @@ static void pilot_realload(Model *m, int layer, int eid){int slot,isnew=0;if(nn<m->ecap){ slot=nn; isnew=1; m->ecn[layer]=nn+1; } /* cresci: pubblica subito lo slot (marcato prenotato) */else {- slot=eslot_lru_victim(Sl,nn,m->ecap); /* riusa libero-con-slab, poi LRU; slot svuotati solo sotto ecap (#1034) */+ slot=eslot_lru_victim(Sl,nn,m->ecap,layer); /* riusa libero-con-slab, poi LRU; slot svuotati solo sotto ecap (#1034) */if(slot<0){ atomic_fetch_add_explicit(&g_pilot_drops,1,memory_order_relaxed);pthread_mutex_unlock(&g_pilot_mx); return; } /* tutti in volo, o cap raggiunto *//* LFRU eviction guard (#441, narrowed by #497 — folded into the SPMC selection):@@ -6933,7 +6941,7 @@ static void pilot_realload(Model *m, int layer, int eid){* hotter than the speculation by tier_pick_lfru's 25%+4-freq hysteresis; the* un-narrowed #474 test dropped ~all speculations on a full cache (#490).* Skips free slots (eid==-1). Cache placement only -> output unchanged. */- if(g_pilot_evict_guard && m->eheat && m->elast && Sl[slot].eid>=0){+ if(g_pilot_evict_guard && m->eheat && m->elast && Sl[slot].eid>=0 && !vkt_ram_first(layer,Sl[slot].eid)){int vid=Sl[slot].eid; uint32_t vh=m->eheat[layer][vid];if(vh>=2){uint64_t vs=tier_lfru_score(vh,m->elast[layer][vid],m->eaccess_clock);@@ -6999,11 +7007,11 @@ static void pilot_uring_batch(Model *m){if(found){ pthread_mutex_unlock(&g_pilot_mx); continue; }int slot;if(nn<m->ecap){ slot=nn; m->ecn[layer]=nn+1; }- else slot=eslot_lru_victim(Sl,nn,m->ecap); /* riusa libero-con-slab, poi LRU; slot svuotati solo sotto ecap (#1034) */+ else slot=eslot_lru_victim(Sl,nn,m->ecap,layer); /* riusa libero-con-slab, poi LRU; slot svuotati solo sotto ecap (#1034) */if(slot<0){ atomic_fetch_add_explicit(&g_pilot_drops,1,memory_order_relaxed); pthread_mutex_unlock(&g_pilot_mx); continue; }/* LFRU eviction guard (#441, narrowed by #497): protect only a genuinely WARM* resident (>=2 accesses) that is clearly hotter (see pilot_realload) */- if(g_pilot_evict_guard && m->eheat && m->elast && Sl[slot].eid>=0){+ if(g_pilot_evict_guard && m->eheat && m->elast && Sl[slot].eid>=0 && !vkt_ram_first(layer,Sl[slot].eid)){int vid=Sl[slot].eid; uint32_t vh=m->eheat[layer][vid];if(vh>=2){uint64_t vs=tier_lfru_score(vh,m->elast[layer][vid],m->eaccess_clock);diff --git a/c/deepseek_v4.c b/c/deepseek_v4.cindex dc3190c7..b5fef8de 100644--- a/c/deepseek_v4.c+++ b/c/deepseek_v4.c@@ -1636,6 +1636,12 @@ int coli_v4_expert_store_open_planned(int slots = (int)(cache_limit / per_slot);if (slots > plan.slots_per_layer) slots = plan.slots_per_layer;if (slots < options->experts_per_layer && slots < 6) slots = 6;+ { /* COLI_V4_EXPERT_SLOTS=n (tests): at most n experts a layer in RAM, never below the+ * store's minimum (6, or every expert of a smaller layer) */+ const char *e = getenv("COLI_V4_EXPERT_SLOTS");+ int n = e && *e ? atoi(e) : 0, least = options->experts_per_layer < 6 ? options->experts_per_layer : 6;+ if (n > 0 && n < slots) slots = n < least ? least : n;+ }plan.expert_cache_bytes = (uint64_t)slots * per_slot;runtime->target_expert_cache_bytes = plan.expert_cache_bytes;plan.projected_bytes = fixed + dense_bytes +@@ -8341,16 +8347,30 @@ static V4ExpertSlot *next_pooled_empty_slot(V4ExpertStoreState *state,/* 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. */+/* With coli_v4_expert_store_ram_first set (the Vulkan tier with exclusive RAM/VRAM), a+ * slot whose expert the device holds goes first: the oldest such one. */+static int hot_ram_first(const V4ExpertSlot *slot) {+ int (*first)(int, int) = coli_v4_expert_store_ram_first;+ return first && slot->owner_layer >= 0 && slot->expert >= 0 && first(slot->owner_layer, slot->expert);+}static V4ExpertSlot *oldest_unreferenced_slot(V4ExpertStoreState *state,int layer) {+ V4ExpertSlot *oldest = NULL;int index = state->lru_head[layer];while (index >= 0) {V4ExpertSlot *slot = &state->slots[index];V4_COUNT_VICTIM_PROBE();- if (!slot->references) return slot;+ if (!slot->references) {+ if (!coli_v4_expert_store_ram_first) return slot;+ if (hot_ram_first(slot)) {+ if (coli_v4_expert_store_ram_gave) coli_v4_expert_store_ram_gave();+ return slot;+ }+ if (!oldest) oldest = slot;+ }index = slot->lru_next;}- return NULL;+ return oldest;}/* All index helpers are called with state->mutex held. A single table entry@@ -9347,19 +9367,25 @@ static void hot_repin_locked(V4HotPolicy *policy, V4ExpertStoreState *state,* extra slot made possible by more RAM. */static V4ExpertSlot *hot_oldest_victim(V4ExpertStoreState *state,const V4HotPolicy *policy, int layer) {- V4ExpertSlot *fallback = NULL;+ V4ExpertSlot *fallback = NULL, *oldest = 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, slot->owner_layer, slot->expert))- return slot;+ if (!hot_is_pinned(policy, slot->owner_layer, slot->expert)) {+ if (!coli_v4_expert_store_ram_first) return slot;+ if (hot_ram_first(slot)) {+ if (coli_v4_expert_store_ram_gave) coli_v4_expert_store_ram_gave();+ return slot;+ }+ if (!oldest) oldest = slot;+ }}index = slot->lru_next;}- return fallback;+ return oldest ? oldest : fallback;}/* Pool-mode victim selection merges the heads of the physical-partition LRU@@ -9373,6 +9399,8 @@ static V4ExpertSlot *hot_oldest_pool_victim(V4ExpertSlot *reserved = NULL;V4ExpertSlot *pinned = NULL;V4ExpertSlot *last_resort = NULL;+ V4ExpertSlot *device = NULL; /* exclusive RAM/VRAM: the oldest lendable one the device holds */+ const int scan_all = coli_v4_expert_store_ram_first != NULL;for (int partition = 0; partition < state->layers; partition++) {int index = state->lru_head[partition];while (index >= 0) {@@ -9395,8 +9423,10 @@ static V4ExpertSlot *hot_oldest_pool_victim(if (!pinned || slot->used < pinned->used)pinned = slot;} else {+ if (scan_all && hot_ram_first(slot) && (!device || slot->used < device->used))+ device = slot;if (!best || slot->used < best->used) best = slot;- break;+ if (!scan_all) break;}}}@@ -9407,6 +9437,10 @@ static V4ExpertSlot *hot_oldest_pool_victim(* leases or an extremely small cache make that impossible, correctness* wins: relax the reserve before evicting a pin, then use the exact oldest* unreferenced slot as the final fallback. */+ if (device) {+ if (coli_v4_expert_store_ram_gave) coli_v4_expert_store_ram_gave();+ return device;+ }if (best) return best;if (reserved) return reserved;if (pinned) return pinned;@@ -9636,6 +9670,8 @@ void coli_v4_expert_store_prefill_pool(ColiExpertStore *store, int layer) {* routing's, whichever side computed it. The store's hit and miss counters are not* touched: they describe the RAM cache. */int (*coli_v4_expert_store_device_tier)(int layer, int expert);+int (*coli_v4_expert_store_ram_first)(int layer, int expert);+void (*coli_v4_expert_store_ram_gave)(void);void coli_v4_expert_store_note_routed(ColiExpertStore *store, ColiExpertKey key) {if (!store || !store->state) return;@@ -13044,6 +13080,8 @@ static void v4_vk_tier_start(const ColiV4Engine *engine) {}free(pl); free(pe);coli_v4_expert_store_device_tier = v4_vkt_device_tier;+ coli_v4_expert_store_ram_first = vkt_ram_first; /* exclusive RAM/VRAM (COLI_VK_TIER_EXCLUSIVE) */+ coli_v4_expert_store_ram_gave = vkt_ram_gave;coli_v4_vk_tier = &g_v4_vkt;}@@ -13273,6 +13311,8 @@ static void v4_vk_close(void) {v4_vk_tier_report("run", (unsigned long long)st.hits, (unsigned long long)st.misses);coli_v4_vk_tier = NULL;coli_v4_expert_store_device_tier = NULL;+ coli_v4_expert_store_ram_first = NULL;+ coli_v4_expert_store_ram_gave = NULL;}size_t bytes = 0, tensors = 0;coli_vk_mem_info(&bytes, &tensors);diff --git a/c/deepseek_v41.c b/c/deepseek_v41.cindex 7d1a11bb..60de2eca 100644--- a/c/deepseek_v41.c+++ b/c/deepseek_v41.c@@ -84,6 +84,10 @@/* 1 once COLI_VULKAN=1 opened a device, after the weights load (a VK=1 build). */static int g_vk_ready = 0;#endif+#ifndef COLI_VULKAN /* exclusive RAM/VRAM (vk_tier.h) is the Vulkan build's: no device holds an expert */+static inline int vkt_ram_first(int layer, int eid) { (void)layer; (void)eid; return 0; }+static inline void vkt_ram_gave(void) {}+#endif#define V41_MAX_LAYERS 64#define V41_MAX_ENGRAM 4@@ -1610,6 +1614,19 @@ static void ehit_mark(Model *m, int layer, int eid) {* DSpark stage: same slot shapes, same LRU, a different set of experts. Only the* backbone's routing reaches the dashboard's grid -- the draft head has its own,* smaller expert set, and a row of it would not line up with anything. */+/* The slot a full cache gives up: the least recently used, and before it (the+ * backbone's layers: the DSpark stages keep their experts on the CPU) the least+ * recently used of those whose expert the Vulkan tier holds (vkt_ram_first). */+static int v41_victim(const LCache *cache, const char *kind, int layer) {+ int oldest = 0, dev = -1, backbone = !strcmp(kind, "layers");+ for (int i = 1; i < cache->n; i++)+ if (cache->slot[i].used < cache->slot[oldest].used) oldest = i;+ for (int i = 0; backbone && i < cache->n; i++)+ if (cache->slot[i].eid >= 0 && vkt_ram_first(layer, cache->slot[i].eid) &&+ (dev < 0 || cache->slot[i].used < cache->slot[dev].used)) dev = i;+ if (dev >= 0) { vkt_ram_gave(); return dev; }+ return oldest;+}static Slot *expert_slot_at(Model *m, LCache *cache, const char *kind, int layer, int eid) {if (!strcmp(kind, "layers")) ehit_mark(m, layer, eid);for (int i = 0; i < cache->n; i++)@@ -1623,10 +1640,7 @@ static Slot *expert_slot_at(Model *m, LCache *cache, const char *kind, int layerif (cache->n < cache->cap) {victim = &cache->slot[cache->n++];} else {- int oldest = 0;- for (int i = 1; i < cache->n; i++)- if (cache->slot[i].used < cache->slot[oldest].used) oldest = i;- victim = &cache->slot[oldest];+ victim = &cache->slot[v41_victim(cache, kind, layer)];}victim->used = ++m->clock;expert_fetch(m, kind, layer, &victim, &eid, 1);@@ -1665,10 +1679,7 @@ static void expert_slots_at(Model *m, LCache *cache, const char *kind, int layerif (cache->n < cache->cap) {victim = &cache->slot[cache->n++];} else {- int oldest = 0;- for (int i = 1; i < cache->n; i++)- if (cache->slot[i].used < cache->slot[oldest].used) oldest = i;- victim = &cache->slot[oldest];+ victim = &cache->slot[v41_victim(cache, kind, layer)];}victim->used = ++m->clock;victim->eid = -1; /* not this expert yet: the read is still pending */diff --git a/c/deepseek_v4_internal.h b/c/deepseek_v4_internal.hindex 3321e2d7..9e8a1bb5 100644--- a/c/deepseek_v4_internal.h+++ b/c/deepseek_v4_internal.h@@ -720,6 +720,10 @@ uint64_t coli_v4_expert_store_record_bytes(ColiExpertStore *store);int coli_v4_expert_store_read_private(ColiExpertStore *store, ColiExpertKey key,unsigned char *buffer, ColiExpertView *view);extern int (*coli_v4_expert_store_device_tier)(int layer, int expert);+/* Exclusive RAM/VRAM (vk_tier.h's vkt_ram_first): when set, a full RAM cache gives up+ * first a slot whose expert the device holds, and reports it through ram_gave. */+extern int (*coli_v4_expert_store_ram_first)(int layer, int expert);+extern void (*coli_v4_expert_store_ram_gave)(void);/* The dense chain (deepseek_v4_chain.h, COLI_VK_CHAIN): a layer's attention state as its* units keep it, so the chain can mirror it on the device and write back what a forwarddiff --git a/c/glm53.c b/c/glm53.cindex 8a8a23c1..d3165e7d 100644--- a/c/glm53.c+++ b/c/glm53.c@@ -90,6 +90,10 @@ static uint64_t g_metal_moe_rows = 0;static int g_vk_ready = 0; /* COLI_VULKAN=1 and the device opened */static int g_vk_dense = 0; /* the resident matrices run there (coli_vk_dense_decide) */#endif+#ifndef COLI_VULKAN /* exclusive RAM/VRAM (vk_tier.h) is the Vulkan build's: no device holds an expert */+static inline int vkt_ram_first(int layer, int eid) { (void)layer; (void)eid; return 0; }+static inline void vkt_ram_gave(void) {}+#endif#include "compat.h"#include "serve_poll.h" /* CANCEL a meta' turno (#1332) */#include "route_trace.h"@@ -2006,10 +2010,14 @@ static void expert_block_read(GModel *m, int index, const int *ids, int here,if (hit) { slot_of[i] = (int)(hit - cache->s); continue; }Slot *victim;if (cache->n < cache->cap) victim = &cache->s[cache->n++];- else {- int lru = 0;+ else { /* il meno usato; prima ancora uno che il tier Vulkan tiene gia' (vkt_ram_first) */+ int lru = 0, dev = -1;for (int j = 1; j < cache->n; j++)if (cache->s[j].used < cache->s[lru].used) lru = j;+ for (int j = 0; j < cache->n; j++)+ if (cache->s[j].eid >= 0 && vkt_ram_first(index, cache->s[j].eid) &&+ (dev < 0 || cache->s[j].used < cache->s[dev].used)) dev = j;+ if (dev >= 0) { lru = dev; vkt_ram_gave(); }victim = &cache->s[lru];}/* prenotato subito: cosi' la scelta successiva non lo ripesca */diff --git a/c/inkling.c b/c/inkling.cindex 0b89b021..d35d4ab6 100644--- a/c/inkling.c+++ b/c/inkling.c@@ -82,6 +82,10 @@ static int g_vk_tier_try = 0; /* the device opened with the expert tier to bestatic int g_vk_chain = 0; /* COLI_VK_CHAIN decided on, and the chain's pipelines are up (inkling_chain.h) */static int g_ink_dho = 0; /* COLI_VK_DENSE_HOST: the dense matrices on the device only (ink_dho_place) */#endif+#ifndef COLI_VULKAN /* exclusive RAM/VRAM (vk_tier.h) is the Vulkan build's: no device holds an expert */+static inline int vkt_ram_first(int layer, int eid) { (void)layer; (void)eid; return 0; }+static inline void vkt_ram_gave(void) {}+#endif#if defined(__APPLE__)#include <mach/mach.h>#include <sys/sysctl.h>@@ -1511,9 +1515,16 @@ static Slot *slot_acquire(Model *m, int layer, int eid) {if (!s->q13 || !s->q2) { fprintf(stderr,"OOM expert slot\n"); exit(1); } }else { s->f13 = falloc(n13); s->f2 = falloc(n2); }} else {- int lru = -1;- for (int i = 0; i < lc->n; i++)- if (!lc->slots[i].pinned && (lru < 0 || lc->slots[i].used < lc->slots[lru].used)) lru = i;+ int lru = -1, dev = -1; /* an expert the Vulkan tier holds goes first (vkt_ram_first) */+ for (int i = 0; i < lc->n; i++) {+ if (lc->slots[i].pinned) continue;+ if (lc->slots[i].eid >= 0 && vkt_ram_first(layer, lc->slots[i].eid)) {+ if (dev < 0 || lc->slots[i].used < lc->slots[dev].used) dev = i;+ continue;+ }+ if (lru < 0 || lc->slots[i].used < lc->slots[lru].used) lru = i;+ }+ if (dev >= 0) { lru = dev; vkt_ram_gave(); }if (lru < 0) { fprintf(stderr, "layer %d: cache cap %d entirely pinned\n", layer, lc->cap); exit(1); }s = &lc->slots[lru];}diff --git a/c/kimi_k3.c b/c/kimi_k3.cindex ccb1cc34..3ca44c22 100644--- a/c/kimi_k3.c+++ b/c/kimi_k3.c@@ -1976,11 +1976,13 @@ static void experts_apply_union(Model *m, int li, int nu, const int *uids,/* LRU over the UNPINNED slots. pin_seed caps pinned at cap/2, so a* victim always exists; the -1 fallback is a belt-and-braces guard* against a future caller pinning everything and deadlocking here. */- int lru=-1;+ int lru=-1, dev=-1; /* an expert the Vulkan tier holds goes first (vkt_ram_first) */for(int i=0;i<lc->n;i++){if(lc->s[i].pinned) continue;+ if(lc->s[i].eid>=0 && vkt_ram_first(li,lc->s[i].eid)){ if(dev<0 || lc->s[i].used<lc->s[dev].used) dev=i; continue; }if(lru<0 || lc->s[i].used<lc->s[lru].used) lru=i;}+ if(dev>=0){ lru=dev; vkt_ram_gave(); }if(lru<0) break; /* every slot pinned: keep the read */dst=&lc->s[lru];}diff --git a/c/mimo.c b/c/mimo.cindex a3f6d773..978cbeae 100644--- a/c/mimo.c+++ b/c/mimo.c@@ -713,10 +713,16 @@ static void experts_ensure(Model *m, int li, const int *want, int n, Slot **out)for (int k = 0; k < nmiss; k++) {int best = -1;if (lc->n < lc->cap) best = lc->n++;- else {- uint64_t oldest = UINT64_MAX;- for (int s = 0; s < lc->n; s++)- if (lc->s[s].used < stamp && lc->s[s].used < oldest) { oldest = lc->s[s].used; best = s; }+ else { /* the least recently used, and before it one the Vulkan tier holds (vkt_ram_first) */+ uint64_t oldest = UINT64_MAX, dev_oldest = UINT64_MAX;+ int dev = -1;+ for (int s = 0; s < lc->n; s++) {+ if (lc->s[s].used >= stamp) continue;+ if (lc->s[s].eid >= 0 && vkt_ram_first(li, lc->s[s].eid)) {+ if (lc->s[s].used < dev_oldest) { dev_oldest = lc->s[s].used; dev = s; }+ } else if (lc->s[s].used < oldest) { oldest = lc->s[s].used; best = s; }+ }+ if (dev >= 0) { best = dev; vkt_ram_gave(); }}if (best < 0) { fprintf(stderr, "[mimo] expert cache smaller than one routing step\n"); exit(1); }Slot *s = &lc->s[best];diff --git a/c/olmoe.c b/c/olmoe.cindex cd3fb557..c73e3197 100644--- a/c/olmoe.c+++ b/c/olmoe.c@@ -70,6 +70,10 @@ static int g_vk_ready = 0;static int g_vk_chain = 0; /* COLI_VK_CHAIN decided on, and the chain's pipelines are up (olmoe_chain.h) */static int g_olc_fit_on; /* the partial chain's fit ran: the chain set itself up in model_init (olmoe_chain.h) */#endif+#ifndef COLI_VULKAN /* exclusive RAM/VRAM (vk_tier.h) is the Vulkan build's: no device holds an expert */+static inline int vkt_ram_first(int layer, int eid) { (void)layer; (void)eid; return 0; }+static inline void vkt_ram_gave(void) {}+#endif#ifdef _WIN32#include <windows.h>@@ -906,6 +910,18 @@ static void ehit_mark(Model *m, int layer, int eid) {if (layer >= 0 && layer < c->n_layers && eid >= 0 && eid < c->n_experts) m->ehit[layer][eid] = 1;}+/* The unpinned slot a full layer cache gives up (caller holds g_pilot_mx), never one+ * being loaded or read: the least recently used, or before it the least recently used+ * of those whose expert the Vulkan tier holds. -1 when there is none. */+static int olmoe_victim(const LCache *lc, int layer) {+ int lru = -1, dev = -1;+ for (int i = 0; i < lc->n; i++) {+ if (lc->slots[i].pinned || lc->slots[i].eid < 0 || lc->slots[i].busy) continue;+ if (vkt_ram_first(layer, lc->slots[i].eid)) { if (dev < 0 || lc->slots[i].used < lc->slots[dev].used) dev = i; continue; }+ if (lru < 0 || lc->slots[i].used < lc->slots[lru].used) lru = i;+ }+ return dev >= 0 ? dev : lru;+}static void expert_get(Model *m, int layer, int eid, Slot **out) {LCache *lc = &m->cache[layer];pthread_mutex_lock(&g_pilot_mx);@@ -931,12 +947,9 @@ static void expert_get(Model *m, int layer, int eid, Slot **out) {s = &lc->slots[lc->n++];slot_ensure_allocated(m, s);} else {- /* LRU eviction: skip pinned, in-flight (eid==-1) and busy slots */- int lru = -1;- for (int i = 0; i < lc->n; i++) {- if (lc->slots[i].pinned || lc->slots[i].eid < 0 || lc->slots[i].busy) continue;- if (lru < 0 || lc->slots[i].used < lc->slots[lru].used) lru = i;- }+ /* LRU eviction: skip pinned, in-flight (eid==-1) and busy slots; an expert the+ * Vulkan tier holds goes first (vkt_ram_first: no second copy when RAM is short) */+ int lru = olmoe_victim(lc, layer);if (lru < 0) {/* All slots are pinned, in-flight or busy; find oldest non-in-flight slot* (may be pinned, but never select one currently being loaded or read). */@@ -963,6 +976,7 @@ static void expert_get(Model *m, int layer, int eid, Slot **out) {}s = &lc->slots[lru];s->pinned = 0;+ if (vkt_ram_first(layer, s->eid)) vkt_ram_gave();}cache_reserve(m, layer, s, eid);s->used = ++m->clock;@@ -1594,12 +1608,9 @@ static void pilot_realload(Model *m, int layer, int eid) {s = &lc->slots[lc->n++];slot_ensure_allocated(m, s);} else {- /* LRU eviction: skip pinned, in-flight (eid==-1) and busy slots */- int lru = -1;- for (int i = 0; i < lc->n; i++) {- if (lc->slots[i].pinned || lc->slots[i].eid < 0 || lc->slots[i].busy) continue;- if (lru < 0 || lc->slots[i].used < lc->slots[lru].used) lru = i;- }+ /* LRU eviction: skip pinned, in-flight (eid==-1) and busy slots; an expert the+ * Vulkan tier holds goes first (vkt_ram_first: no second copy when RAM is short) */+ int lru = olmoe_victim(lc, layer);if (lru < 0) {m->is_queued[layer * c->n_experts + eid] = 0;pthread_mutex_unlock(&g_pilot_mx);@@ -1608,7 +1619,7 @@ static void pilot_realload(Model *m, int layer, int eid) {/* LFRU eviction guard: don't displace a warm resident expert with a speculation */if (g_pilot_evict_guard && m->freq && m->freq[layer] && m->last_access &&- lc->slots[lru].eid >= 0) {+ lc->slots[lru].eid >= 0 && !vkt_ram_first(layer, lc->slots[lru].eid)) {int vid = lc->slots[lru].eid;uint64_t vs = lfru_score(m->freq[layer][vid], m->last_access[layer * c->n_experts + vid], m->clock);uint64_t cs = lfru_score(m->freq[layer][eid], m->last_access[layer * c->n_experts + eid], m->clock);@@ -1620,6 +1631,7 @@ static void pilot_realload(Model *m, int layer, int eid) {}s = &lc->slots[lru]; s->pinned = 0;+ if (vkt_ram_first(layer, s->eid)) vkt_ram_gave();}cache_reserve(m, layer, s, eid); s->used = ++m->clock;pthread_mutex_unlock(&g_pilot_mx);diff --git a/c/qwen36.c b/c/qwen36.cindex 31fe7c95..b4af4f96 100644--- a/c/qwen36.c+++ b/c/qwen36.c@@ -1006,15 +1006,17 @@ static int slot_busy(const Slot *s) { return __atomic_load_n(&s->busy, __ATOMIC* recently used one that is neither being loaded (eid < 0) nor computed from* (busy), unpinned unless allow_pinned. -1 when there is none. The demand* path and the PILOT worker both pick here, so neither can evict an expert a- * moe run is still reading. */-static int slot_victim(const LCache *lc, int allow_pinned) {- int lru = -1;+ * moe run is still reading. One whose expert the Vulkan tier holds goes first+ * (vkt_ram_first: RAM and VRAM do not keep the same experts when RAM is short). */+static int slot_victim(const LCache *lc, int layer, int allow_pinned) {+ int lru = -1, dev = -1;for (int i = 0; i < lc->n; i++) {const Slot *s = &lc->slots[i];if (s->eid < 0 || slot_busy(s) || (s->pinned && !allow_pinned)) continue;+ if (vkt_ram_first(layer, s->eid)) { if (dev < 0 || s->used < lc->slots[dev].used) dev = i; continue; }if (lru < 0 || s->used < lc->slots[lru].used) lru = i;}- return lru;+ return dev >= 0 ? dev : lru;}static void ensure_pilot_worker_started(Model *m) {@@ -2693,8 +2695,8 @@ static void expert_fetch(Model *m, int layer, int eid, Slot **out, int hold) {else {/* LRU eviction: an unpinned slot first, else the oldest pinned one;* never one being loaded or computed from. */- int lru = slot_victim(lc, 0);- if (lru < 0) lru = slot_victim(lc, 1);+ int lru = slot_victim(lc, layer, 0);+ if (lru < 0) lru = slot_victim(lc, layer, 1);while (lru < 0) {/* Every slot is held or being loaded. Only this thread holds (the* PILOT worker never does) and a moe run holds fewer slots than@@ -2718,9 +2720,10 @@ static void expert_fetch(Model *m, int layer, int eid, Slot **out, int hold) {pthread_mutex_unlock(&g_pilot_mx);sleep_ms(1);pthread_mutex_lock(&g_pilot_mx);- lru = slot_victim(lc, 1);+ lru = slot_victim(lc, layer, 1);}s = &lc->slots[lru]; s->pinned = 0;+ if (vkt_ram_first(layer, s->eid)) vkt_ram_gave();}cache_hide(m, layer, s); s->used = ++m->clock;pthread_mutex_unlock(&g_pilot_mx);@@ -4103,9 +4106,10 @@ static void pilot_realload(Model *m, int layer, int eid) {Slot *s;if (lc->n < lc->cap) { s = &lc->slots[lc->n++]; slot_ensure_allocated(m, s); }else {- int lru = slot_victim(lc, 0);+ int lru = slot_victim(lc, layer, 0);if (lru < 0) { m->is_queued[layer*c->n_experts+eid]=0; pthread_mutex_unlock(&g_pilot_mx); return; }s = &lc->slots[lru]; s->pinned = 0;+ if (vkt_ram_first(layer, s->eid)) vkt_ram_gave();}cache_hide(m, layer, s); s->used = ++m->clock;pthread_mutex_unlock(&g_pilot_mx);@@ -4182,6 +4186,7 @@ static void pilot_prefetch(Model *m, int lnext, const float *x, int S) {* never fired (#1391). tier_offer_slot handles both formats. */tier_offer_slot(lnext, eid, ps);}+ if (!found && vkt_ram_first(lnext, eid)) found = 1; /* the device serves it: nothing to read */if (!found) {int gidx = lnext*E + eid;pthread_mutex_lock(&g_pilot_mx); int already_queued = m->is_queued[gidx];diff --git a/c/qwen38_core.h b/c/qwen38_core.hindex 6943489d..da36b99f 100644--- a/c/qwen38_core.h+++ b/c/qwen38_core.h@@ -1834,6 +1834,20 @@ static void q38_ehit_mark(Model *m,int layer,int eid) {}if(layer>=0&&layer<c->layers&&eid>=0&&eid<c->experts)ehit[layer][eid]=1;}+/* The slot a full layer cache gives up: the least recently used outside `protect`+ * (NULL: none protected), and before it the least recently used of those whose expert+ * the Vulkan tier holds (vkt_ram_first: no second copy in RAM when RAM is short).+ * -1 when every slot is protected. */+static int q38_victim(const LCache *lc,int layer,const uint8_t *protect){+ int lru=-1,dev=-1;+ for(int i=0;i<lc->n;i++){+ if(protect&&protect[i])continue;+ if(lc->slots[i].eid>=0&&vkt_ram_first(layer,lc->slots[i].eid)){if(dev<0||lc->slots[i].used<lc->slots[dev].used)dev=i;continue;}+ if(lru<0||lc->slots[i].used<lc->slots[lru].used)lru=i;+ }+ if(dev>=0){vkt_ram_gave();return dev;}+ return lru;+}static Slot *q38_expert_get(Model *m,int layer,int eid) {q38_ehit_mark(m,layer,eid);LCache *lc=&m->cache[layer]; int si=lc->by_expert[eid];@@ -1841,7 +1855,7 @@ static Slot *q38_expert_get(Model *m,int layer,int eid) {m->miss++; Slot *s;if(lc->n<lc->cap){s=&lc->slots[lc->n++];s->eid=-1;}else {- int victim=0;for(int i=1;i<lc->n;i++)if(lc->slots[i].used<lc->slots[victim].used)victim=i;+ int victim=q38_victim(lc,layer,NULL);s=&lc->slots[victim];if(s->eid>=0)lc->by_expert[s->eid]=-1;}s->eid=-1;q38_load_expert(m,layer,eid,s);s->eid=eid;s->used=++m->clock;lc->by_expert[eid]=(int)(s-lc->slots);return s;@@ -1942,11 +1956,7 @@ static int q38_expert_get_batch(Model *m,int layer,const int *experts,int count,if(cache->n<cache->cap){slot=&cache->slots[cache->n++];slot->eid=-1;}else{- int victim=-1;- for(int candidate=0;candidate<cache->n;candidate++)- if(!protected_slots[candidate]&&- (victim<0||cache->slots[candidate].used<cache->slots[victim].used))- victim=candidate;+ int victim=q38_victim(cache,layer,protected_slots);if(victim<0){fprintf(stderr,"Qwen3.8 expert demand set has no reservable cache slot\n");exit(1);diff --git a/c/vk_tier.c b/c/vk_tier.cindex 84d35d04..bb1a835e 100644--- a/c/vk_tier.c+++ b/c/vk_tier.c@@ -70,6 +70,12 @@ static struct {int nd2; int *d2_idx; int cd2; /* a big step's rows on it: their assignments */const float **d2_y; ColiVkExpert **d2_bex; int *d2_brows; const float **d2_bx; float *d2_bw; int d2_cap, d2_cexp;unsigned long long d2_served, d2_steps, d2_big, d2_uploads, d2_lost;+ /* exclusive RAM/VRAM (vkt_ram_first): on, and the RAM slots given up for it. routed[l*E+e]+ * is the issue (seq) that last routed the expert, layer_seq[l] the layer's last issue: an+ * expert routed in its layer's current step may be one the CPU is computing from its RAM+ * slot (handed back by the balance, past a batch's rows), so it is never offered */+ int excl; unsigned long long ram_gave;+ uint32_t *routed_at, *layer_seq, seq;double d2_ms;VSlot *s;uint32_t tick, decay_at; /* tokens seen (rows of the forward's first layer) */@@ -1144,6 +1150,12 @@ static int issue(int layer, const float *x, int S, int K, const int *idx, const}if (T.d2 && !coli_vk_xb_ready_dev(1)) d2_stop("the second device stopped answering");if (layer < T.last_layer || T.begin) { T.begin = 0; T.first_layer = layer; new_forward(); }+ if (T.routed_at) { /* this step's routing: its experts are not offered to the RAM cache's eviction */+ uint32_t q = ++T.seq;+ for (int i = 0; i < S * K; i++)+ if (idx[i] >= 0 && idx[i] < T.c.experts) __atomic_store_n(&T.routed_at[(size_t)layer * T.c.experts + idx[i]], q, __ATOMIC_RELAXED);+ __atomic_store_n(&T.layer_seq[layer], q, __ATOMIC_RELEASE);+ }if (layer == T.first_layer) { /* COLI_VK_TIER_RATE promotions per token of the forward */T.tick += (uint32_t)S;long cap = (long)T.promo_cap + (long)T.rate * S;@@ -1503,6 +1515,13 @@ int vkt_init(const VktConfig *cfg, uint32_t *const *heat) {if (fit + (T.st_ok ? T.st_slots : 0) >= all && fit_raw >= all + (T.st_ok ? T.st_slots : 0) &&need < lim && need <= coli_vk_block_bytes((size_t)256 << 20)) lim = need;coli_vk_tier_pool_limit(lim);+ const char *ex = getenv("COLI_VK_TIER_EXCLUSIVE");+ T.excl = !(ex && *ex == '0');+ if (T.excl) {+ T.routed_at = calloc((size_t)T.c.layers * T.c.experts, sizeof(uint32_t));+ T.layer_seq = calloc((size_t)T.c.layers, sizeof(uint32_t));+ if (!T.routed_at || !T.layer_seq) { free(T.routed_at); free(T.layer_seq); T.routed_at = T.layer_seq = NULL; T.excl = 0; }+ }const char *bal = getenv("COLI_VK_TIER_BALANCE");T.balance = T.c.in_ram != NULL && !(bal && *bal == '0');T.share = 1.f;@@ -1567,6 +1586,8 @@ void vkt_report(const char *scope, unsigned long long ram_hits, unsigned long lohuman((double)T.upload_bytes, hl, sizeof hl), T.warm, T.evictions, T.qfull, T.rated, T.failed,T.dev_ms, T.cpu_ms, T.wait_ms, T.dev_ms > 0 ? 100.0 * hidden / T.dev_ms : 0.0);if (T.balance) fprintf(stderr, " | balance: device share %.2f, %llu rows handed to the CPU", T.share, T.handed);+ if (T.excl) fprintf(stderr, " | exclusive: %llu RAM copies of device experts given up first",+ __atomic_load_n(&T.ram_gave, __ATOMIC_RELAXED));if (T.st_ok && T.st_steps) {char hs[32];fprintf(stderr, " | stream: %llu steps, %llu cold experts (%s, %.2f GB/s) and %llu rows streamed in %llu sub-batches, "@@ -1590,6 +1611,23 @@ void vkt_report(const char *scope, unsigned long long ram_hits, unsigned long lo}int vkt_devices(void) { return !T.on ? 0 : T.d2 ? 2 : 1; }+static VSlot *g_old_slots; /* the slot table of the tier shut down last (vkt_shutdown) */+static uint32_t *g_old_routed, *g_old_seq;++/* The engine's prefetch workers ask too, while the engine thread changes the slot table:+ * the state byte is read atomically (a stale answer costs one eviction order or one+ * read, never a wrong expert: the engine's own cache decides what its slots hold). */+int vkt_ram_first(int layer, int eid) {+ VSlot *s = __atomic_load_n(&T.s, __ATOMIC_ACQUIRE);+ uint32_t *routed = __atomic_load_n(&T.routed_at, __ATOMIC_ACQUIRE), *seq = __atomic_load_n(&T.layer_seq, __ATOMIC_ACQUIRE);+ int L = T.c.layers, E = T.c.experts;+ if (!__atomic_load_n(&T.on, __ATOMIC_RELAXED) || !T.excl || !s || !routed || !seq ||+ layer < 0 || layer >= L || eid < 0 || eid >= E) return 0;+ size_t i = (size_t)layer * E + eid;+ if (__atomic_load_n(&routed[i], __ATOMIC_RELAXED) == __atomic_load_n(&seq[layer], __ATOMIC_ACQUIRE)) return 0;+ return __atomic_load_n(&s[i].state, __ATOMIC_RELAXED) == VS_RESIDENT;+}+void vkt_ram_gave(void) { __atomic_add_fetch(&T.ram_gave, 1, __ATOMIC_RELAXED); }void vkt_shutdown(void) {if (!T.s) return;@@ -1612,7 +1650,12 @@ void vkt_shutdown(void) {for (int i = 0; T.st && i < T.st_n; i++) if (T.st[i].ex) coli_vk_xb_expert_free(T.st[i].ex);}pthread_mutex_destroy(&T.mx); pthread_cond_destroy(&T.cv); pthread_cond_destroy(&T.cv_room); pthread_cond_destroy(&T.cv_done);- free(T.s); free(T.grp); free(T.map); free(T.touched); free(T.bex); free(T.brows); free(T.bfirst);+ /* the slot table outlives the tier by one shutdown: a prefetch worker may be in+ * vkt_ram_first with the pointer it read before this */+ free(g_old_slots); g_old_slots = T.s;+ free(g_old_routed); g_old_routed = T.routed_at; /* the same for the routing marks */+ free(g_old_seq); g_old_seq = T.layer_seq;+ free(T.grp); free(T.map); free(T.touched); free(T.bex); free(T.brows); free(T.bfirst);free(T.bx); free(T.by); free(T.bw); free(T.evict); free(T.done);free(T.st); free(T.sy); free(T.bcnt); free(T.bofs); free(T.bcls); free(T.blist); free(T.pred); free(T.pred_ok);for (int h = 0; h < 2; h++) { free(T.hf[h].slot); free(T.hf[h].yout); }diff --git a/c/vk_tier.h b/c/vk_tier.hindex 5a9d42cc..586240da 100644--- a/c/vk_tier.h+++ b/c/vk_tier.h@@ -21,7 +21,12 @@* hottest on the primary device, the next ones on the second (its budget: its free* memory less COLI_VK_RESERVE2_GB, at most COLI_VK_EXPERTS2 experts when set), each* step one batch per device, both in flight at once. Nothing changes for the- * engine: the calls below are the same with one device or two.+ * engine: the calls below are the same with one device or two;+ * - keeps the RAM and the VRAM from holding the same experts when RAM is short+ * (COLI_VK_TIER_EXCLUSIVE, on unless 0): an engine's RAM expert cache that must+ * evict gives up first a slot whose expert the device holds (vkt_ram_first), and+ * the prefetchers that read experts into RAM skip what the device holds. With RAM+ * to spare nothing is evicted and nothing changes.* With COLI_VULKAN unset, COLI_VK_TIER=0, a CUDA tier active, or a build without* VK=1 (the inline stubs below), nothing here runs and the engine is unchanged.*@@ -237,6 +242,13 @@ int vkt_step_rows(int S, int block);int vkt_stream_prefetch(int layer, int S);/* How many devices hold experts: 0 (the tier is off), 1, or 2 (COLI_VK_DEV2's too). */int vkt_devices(void);+/* Exclusive RAM/VRAM: 1 when the device holds this expert and the tier wants the RAM+ * copy given up first (COLI_VK_TIER_EXCLUSIVE unset or not 0). An engine's RAM cache+ * asks it while it picks the slot to evict (prefer such a slot to its LRU choice) and+ * its prefetchers before reading an expert; vkt_ram_gave() counts a slot given up so.+ * Any thread (the prefetch workers too): it reads the slot table without the engine. */+int vkt_ram_first(int layer, int eid);+void vkt_ram_gave(void);#elsestatic inline int vkt_wanted(void){return 0;}static inline int vkt_init(const VktConfig *c, uint32_t *const *h){(void)c;(void)h;return 0;}@@ -257,6 +269,8 @@ static inline size_t vkt_expert_bytes(int h,int i,VktFmt a,VktFmt b){(void)h;(vostatic inline int vkt_step_rows(int S,int b){return S<b?S:b;}static inline int vkt_stream_prefetch(int l,int S){(void)l;(void)S;return 0;}static inline int vkt_devices(void){return 0;}+static inline int vkt_ram_first(int l,int e){(void)l;(void)e;return 0;}+static inline void vkt_ram_gave(void){}#endif#endif