Inkling CUDA: the elastic expert pool for hybrid loads (the adaptive tier's slot pool lives in virtual memory) and router heat for the pool that gives experts up

Hybrid loads (the adaptive tier is on: part of the experts in slots on the card, every expert with a host copy): the slot pool is placed in the elastic
pool's virtual memory when STRATA_INK_ELASTIC_EXPERTS is on. When the global K/V needs more than the card has free, the slots at the top of the pool are
switched off (InkExpertPolicy::kill_slot: the expert goes back to its host copy, its table entry is rewritten, no round puts anything in the slot), the card
is synchronised and the chunks go to the K/V; when a conversation ends the K/V returns to its start size and the chunks map behind the pool again
(revive_slot: the slots come back empty and the next rounds fill them). No device-to-host copy is needed: the host copies exist already.
The K/V sizing branch of the runner takes this case too (the whole K/V stays on the card, no mapped host K/V).

Router heat for the d_sec4 pool (all-resident loads): k_ink_heat_add, one 128-thread block per decode / verify MoE visit after the router (prefill chunks,
M >= 16, are skipped), keeps a decayed pick count per expert on the card (a token decays a layer's row by 0.5^(1/32) in all, so the looped core is not
decayed three times). The experts that leave first are chosen by those counts (rate in picks per token, which is the cold hits per token an expert would
cost), the pack's order until about 128 tokens have been seen. STRATA_INK_ELASTIC_HEAT=0 keeps the order of the pack. The kit's tracker was never fed and
its score mixed a prior of 0.35..1 with a rate of 0..0.06; the score now has one unit.

InkElasticSec4Pool gets unmap_tail / map_tail for callers that manage the pool's contents themselves. Tests: ink_elastic_sec4_test (tail moves, set_recent),
ink_expert_policy_test (kill / revive).
This commit is contained in:
Niko1221 committed 2026-12-02 21:47:40 +01:00
1 parent 52954a6a09
commit 993666eef9
7 files changed
+277 -11

No files matched your search

@@ -52,6 +52,7 @@ public:
state_.assign((size_t)n_keys, kOut);
slot_of_.assign((size_t)n_keys, -1);
owner_ = slot_owner;
alive_.assign(owner_.size(), 1);
n_pinned_ = 0;
for (int k : pinned) {
if (k >= 0 && k < n_keys && state_[(size_t)k] == kOut) { state_[(size_t)k] = kPinned; ++n_pinned_; }
@@ -70,6 +71,26 @@ public:
return std::max(1, n);
}
// A slot whose memory the card gives up (the K/V grew into it) is switched off: its expert is out (the key is returned, -1 when it was
// empty) and no round puts anything there until revive_slot (the memory is back; the slot starts empty and the next rounds fill it).
int kill_slot(int s) {
if (s < 0 || s >= (int)owner_.size() || !alive_[(size_t)s]) return -1;
const int k = owner_[(size_t)s];
if (k >= 0) { state_[(size_t)k] = kOut; slot_of_[(size_t)k] = -1; }
owner_[(size_t)s] = -1;
alive_[(size_t)s] = 0;
return k;
}
void revive_slot(int s) {
if (s >= 0 && s < (int)owner_.size()) alive_[(size_t)s] = 1;
}
bool slot_alive(int s) const { return s >= 0 && s < (int)alive_.size() && alive_[(size_t)s]; }
int n_alive_slots() const {
int n = 0;
for (uint8_t a : alive_) n += a ? 1 : 0;
return n;
}
bool resident(int key) const { return key >= 0 && key < n_keys_ && state_[(size_t)key] != kOut; }
int slot_of(int key) const { return (key >= 0 && key < n_keys_) ? slot_of_[(size_t)key] : -1; }
int n_slots() const { return (int)owner_.size(); }
@@ -98,8 +119,8 @@ public:
if (state_[(size_t)k] == kOut && use_[(size_t)k] >= cfg_.usage_floor) cand.push_back(k);
std::stable_sort(cand.begin(), cand.end(), [&](int a, int b) { return use_[(size_t)a] > use_[(size_t)b]; });
// coldest movable slots first (empty slots count as usage -1: they take anything)
std::vector<int> slots((size_t)owner_.size());
for (int s = 0; s < (int)slots.size(); ++s) slots[(size_t)s] = s;
std::vector<int> slots;
for (int s = 0; s < (int)owner_.size(); ++s) if (alive_[(size_t)s]) slots.push_back(s);
auto slot_use = [&](int s) { const int k = owner_[(size_t)s]; return k < 0 ? -1.0f : use_[(size_t)k]; };
std::stable_sort(slots.begin(), slots.end(), [&](int a, int b) { return slot_use(a) < slot_use(b); });
size_t si = 0;
@@ -129,6 +150,7 @@ private:
std::vector<uint8_t> state_;
std::vector<int> slot_of_;
std::vector<int> owner_;
std::vector<uint8_t> alive_; // per slot: 0 = switched off (its memory is not on the card)
};
} // namespace strata::core
+71 -1
View File
@@ -18,6 +18,7 @@
#include "ink_cuda.cuh"
#include "ink_moe_cuda.cuh"
#include "../ink_cold_store.hpp"
#include "../ink_elastic_sec4.hpp"
#include "../ink_host_avx2.h"
#include "../ink_host_avx512.h"
#include "strata/platform/commit.hpp"
@@ -2630,9 +2631,21 @@ struct InkHybridEngine {
}
// Allocate the pool and the bookkeeping; call after start_workers() (needs d_use_cnt) and after the prefill staging buffers.
// Elastic expert pool: when tier_vmm is set before tier_alloc(), the slot pool lives in that pool's virtual memory instead of one cudaMalloc, and the
// global K/V can take chunks from its tail (tier_shrink) and give them back (tier_regrow). Every expert of the tier has a host copy, so a slot that
// goes away only has its table entry turned back to the host copy: nothing is copied off the card.
strata::ink::InkElasticSec4Pool* tier_vmm = nullptr;
bool tier_alloc() {
if (tclass.empty() || tier_pool_bytes == 0 || !active || !d_use_cnt) return false;
if (cudaMalloc(&d_promo_pool, tier_pool_bytes) != cudaSuccess) { (void)cudaGetLastError(); d_promo_pool = nullptr; return false; }
if (tier_vmm) {
if (tier_vmm->init_vmm(tier_pool_bytes, tier_pool_bytes, {})) {
d_promo_pool = tier_vmm->base();
} else {
std::fprintf(stderr, "[InkTier] the slot pool could not be placed in virtual memory: one allocation instead\n");
tier_vmm = nullptr;
}
}
if (!tier_vmm && cudaMalloc(&d_promo_pool, tier_pool_bytes) != cudaSuccess) { (void)cudaGetLastError(); d_promo_pool = nullptr; return false; }
key_to_slot.assign((size_t)n_layers * n_experts, -1);
// initial owners: the policy knows slot_of for every resident key
for (auto& tc : tclass)
@@ -2668,6 +2681,61 @@ struct InkHybridEngine {
return sl < 0 ? nullptr : d_promo_pool + tc.pool_off + (size_t)sl * tc.slot_bytes;
}
// The K/V needs `want` chunks: the slots in the top of the pool are switched off (their experts go back to the host copy, their table entries
// are rewritten), the card is synchronised, and the chunks go to the pool's donor list. Returns the chunks gained (the pool's floor may allow fewer).
// Called between tokens by the runner.
// layer_has_host[il] is set for every layer that lost an expert: the decode graph and the dispatch only look for cold experts in such layers.
int64_t tier_shrink(InkExpertDev* const d_experts[24], cudaStream_t st, int64_t want, bool* layer_has_host) {
if (!tier_on || !tier_vmm || !tier_vmm->active() || want <= 0) return 0;
INK_CK(cudaDeviceSynchronize()); // the swaps of the last round and the decode graph are done: nothing reads the slots
const uint64_t gran = tier_vmm->granularity();
const int64_t take = std::min<int64_t>(want, (int64_t)(tier_vmm->reclaimable_bytes() / gran)); // the pool keeps its floor
if (take <= 0) return 0;
const uint64_t new_bytes = (uint64_t)(tier_vmm->mapped_chunks() - take) * gran;
int demoted = 0;
for (int c = (int)tclass.size() - 1; c >= 0; --c) {
auto& tc = tclass[(size_t)c];
bool all_below = false;
for (int s = tc.n_slots - 1; s >= 0; --s) {
const uint64_t end = (uint64_t)tc.pool_off + (uint64_t)(s + 1) * tc.slot_bytes;
if (end <= new_bytes) { all_below = true; break; }
if (!tc.pol.slot_alive(s)) continue;
const int owner = tc.pol.kill_slot(s);
if (owner < 0) continue;
const int out_g = tc.keys[(size_t)owner];
const auto& om = host_meta[(size_t)out_g];
InkExpertDev dem{};
dem.body_off = orig_host_off[(size_t)out_g];
dem.dn_off = om.dn_off;
dem.gu_code = om.gu_code;
dem.dn_code = om.dn_code;
dem.tier = 2;
tier_flip(&d_experts[out_g / n_experts][out_g % n_experts], dem, st);
key_to_slot[(size_t)out_g] = -1;
++demoted;
if (layer_has_host) layer_has_host[out_g / n_experts] = true;
}
if (all_below) break;
}
INK_CK(cudaStreamSynchronize(st));
const int64_t got = tier_vmm->unmap_tail(take, /*release_to_os=*/false);
tier_demoted_total += (uint64_t)demoted;
return got;
}
// The K/V gave chunks back: they map behind the pool again and the slots they hold come back empty; the next rounds fill them with the experts
// the router asks for. Returns the chunks mapped.
int64_t tier_regrow(cudaStream_t st) {
if (!tier_on || !tier_vmm || !tier_vmm->active() || tier_vmm->donated_chunk_count() == 0) return 0;
INK_CK(cudaStreamSynchronize(st));
const int64_t got = tier_vmm->map_tail((int64_t)tier_vmm->donated_chunk_count(), /*allow_os_alloc=*/false);
const uint64_t bytes = tier_vmm->mapped_bytes();
for (auto& tc : tclass)
for (int s = 0; s < tc.n_slots; ++s)
if (!tc.pol.slot_alive(s) && (uint64_t)tc.pool_off + (uint64_t)(s + 1) * tc.slot_bytes <= bytes) tc.pol.revive_slot(s);
return got;
}
uint64_t tier_demoted_total = 0;
void tier_flip(InkExpertDev* d_entry, const InkExpertDev& v, cudaStream_t st) {
InkExpertDev* h = &h_flip[flip_idx++ & (kFlipCap - 1)];
*h = v;
@@ -2787,6 +2855,7 @@ struct InkHybridEngine {
}
auto fr = [](auto*& p) { if (p) { cudaFree(p); p = nullptr; } };
fr(d_seq); fr(d_cur_seq); fr(d_use_cnt); fr(d_want_keys); fr(d_n_want); fr(d_stat); fr(d_trace); fr(d_trace_n);
if (tier_vmm) d_promo_pool = nullptr; // the pool's virtual range belongs to the elastic pool, which the model releases
fr(d_promo_pool); fr(d_pf_stage[0]); fr(d_pf_stage[1]);
fr(d_pf_exp_tmp[0]); fr(d_pf_exp_tmp[1]);
fr(d_v_y); fr(d_v_p);
@@ -2877,6 +2946,7 @@ inline void launch_ink_moe_hybrid(
CUBLAS_GEMM_DEFAULT_TENSOR_OP));
}
k_ink_router_select_topk8<<<M, 32, 0, st>>>(ws.r_logits, gate_b, ws.topk_idx, ws.topk_w, route_scale, M, ink_tail_args_now(ws.y_pair, experts)); // opt-in tail skip: a dropped slot has id < 0
ink_heat_launch(st, ws.topk_idx, M);
if (M == 1 && hyb.exact_mode && hyb.exact_graph) {
// exact mode: the card copies the cold experts in and computes them itself (see k_ink_stage_plan)
+27
View File
@@ -4300,6 +4300,32 @@ inline InkTailArgs ink_tail_args_now(float* y_pair, const InkExpertDev* ex = nul
return ta;
}
// Routing heat for the elastic expert pool (ink_elastic_sec4.hpp): per expert a decayed count of how often the router picked it, kept on the card
// (3072 floats). One block per MoE visit after the router: the layer's row decays by `decay` (chosen so that a token, which visits a layer 1 or 3 times,
// decays it by 0.5^(1/32) in all) and every pick of the visit adds 1. Decode and verify steps only (the caller skips M >= 16, so a prompt does not
// pollute it). Off (dev == nullptr) unless the runner turned it on for an elastic pool.
struct InkHeatCfg {
float* dev = nullptr; // [24 * 128]
float decay[24] = {}; // per visit of the layer
};
inline InkHeatCfg& ink_heat_cfg() { static InkHeatCfg c; return c; }
__global__ void __launch_bounds__(kInkExperts) k_ink_heat_add(const int32_t* __restrict__ topk_idx, int M, int layer, float decay, float* __restrict__ heat) {
const int e = threadIdx.x;
float c = 0.0f;
for (int i = 0; i < M * kInkTopK; ++i) c += (topk_idx[i] == e) ? 1.0f : 0.0f;
float* h = heat + (size_t)layer * kInkExperts;
h[e] = h[e] * decay + c;
}
inline void ink_heat_launch(cudaStream_t st, const int32_t* topk_idx, int M) {
const InkHeatCfg& hc = ink_heat_cfg();
if (!hc.dev || M >= 16) return;
const int tv = ink_tail_cur_visit();
if (tv < 0 || tv >= kInkTailVisits) return;
const int ip = ink_visit_phys(tv);
k_ink_heat_add<<<1, kInkExperts, 0, st>>>(topk_idx, M, ip, hc.decay[ip], hc.dev);
}
// Calibration: after the dispatch, add the weighted outputs of the candidate slots (y_pair rows) to the layer's sums.
__global__ void k_ink_tail_calib(const float* __restrict__ y_pair, const int* __restrict__ mask, double* __restrict__ acc, unsigned long long* __restrict__ cnt, int M) {
const int tok = blockIdx.x;
@@ -4342,6 +4368,7 @@ inline void launch_ink_moe_router(
}
const InkTailArgs ta = tail_ok ? ink_tail_args_now(ws.y_pair, tail_ex) : InkTailArgs{}; // on = 0: the kernel runs as before
k_ink_router_select_topk8<<<M, 32, 0, st>>>(ws.r_logits, gate_b, ws.topk_idx, ws.topk_w, route_scale, M, ta);
ink_heat_launch(st, ws.topk_idx, M);
ink_moe_mark(0);
}
+41 -3
View File
@@ -310,6 +310,7 @@ struct InkCudaModel {
size_t elastic_max_body = 0;
int elastic_cpu_threads = 0;
bool elastic_armed = false;
bool elastic_tier = false; // the pool is the hybrid engine's slot pool (hybrid loads): experts leave by turning their slots off, the host copies exist already
uint64_t elastic_arena_plan = 0; // bytes of the host copy to reserve at the first eviction (set by the runner from max_ctx)
uint64_t elastic_arena_used = 0;
std::vector<int64_t> elastic_arena_off; // per key: its slot in the host arena (-1 = none yet); a slot stays with its key
@@ -1165,7 +1166,11 @@ struct InkCudaModel {
}
}
if (tier_mode) {
// the slot pool in the elastic pool's virtual memory: the global K/V can then take chunks from it (hybrid.tier_shrink)
const char* kv_vmm_env_t = std::getenv("STRATA_INK_KV_VMM");
if (InkElasticSec4Pool::env_enabled() && !(kv_vmm_env_t && kv_vmm_env_t[0] == '0') && strata::core::vmm_available()) hybrid.tier_vmm = &elastic_sec4;
if (hybrid.tier_alloc()) {
elastic_tier = hybrid.tier_vmm != nullptr;
const int E = man.c.n_experts;
size_t n_start = 0;
for (int di = 0; di < n_total; ++di) {
@@ -1346,6 +1351,7 @@ struct InkCudaModel {
const size_t rb = elastic_arm_vram_bytes();
if (rb > 0 && cudaMalloc(&d_elastic_reserve, rb) != cudaSuccess) { (void)cudaGetLastError(); d_elastic_reserve = nullptr; }
}
elastic_heat_on();
for (int il = 0; il < man.c.n_phys; ++il) {
d_experts[il] = dalloc<InkExpertDev>(man.c.n_experts);
INK_CK(cudaMemcpy(d_experts[il], h_exp.data() + (size_t)il * man.c.n_experts,
@@ -2579,6 +2585,34 @@ struct InkCudaModel {
}
uint8_t* d_elastic_reserve = nullptr;
// Routing heat (k_ink_heat_add): which experts to give up first is decided by how often the router picked them lately (a 32-token half-life),
// not only by their place in the pack's order. The slot pool of a hybrid load has its own usage policy, so this is for the d_sec4 pool only.
// STRATA_INK_ELASTIC_HEAT=0 keeps the order of the pack.
float* d_elastic_heat = nullptr;
void elastic_heat_on() {
if (!elastic_sec4.active() || elastic_tier) return;
const char* e = std::getenv("STRATA_INK_ELASTIC_HEAT");
if (e && e[0] == '0') return;
const size_t n = (size_t)man.c.n_phys * man.c.n_experts;
d_elastic_heat = dalloc<float>(n);
INK_CK(cudaMemset(d_elastic_heat, 0, n * sizeof(float)));
InkHeatCfg& hc = ink_heat_cfg();
hc.dev = d_elastic_heat;
for (int il = 0; il < man.c.n_phys && il < 24; ++il) {
const int visits = (il >= man.c.core_start && il < man.c.core_end) ? 3 : 1; // the looped core runs 3 times per token
hc.decay[il] = std::pow(InkExpertHeatTracker::kDecayPerToken, 1.0f / (float)visits);
}
}
void elastic_refresh_heat() {
if (!d_elastic_heat) return;
cudaSetDevice(primary_gpu);
const size_t n = (size_t)man.c.n_phys * man.c.n_experts;
std::vector<float> h(n);
cudaDeviceSynchronize(); // the counts of the decode steps in flight are in
if (cudaMemcpy(h.data(), d_elastic_heat, n * sizeof(float), cudaMemcpyDeviceToHost) != cudaSuccess) { (void)cudaGetLastError(); return; }
elastic_sec4.heat().set_recent(h.data(), (int)n);
}
// The first expert is about to leave the card: start the hybrid engine (CPU pool, doorbell, prefill staging), reserve the host copy and pick the lane.
// Lane: the exact one (the card copies a cold expert in and computes it with its own kernels: the same bits wherever the expert lives) whenever the host
// copy can be pinned; STRATA_INK_EXACT=0 forces the CPU lane. On a pageable arena the CPU lane stays (the copy lane would sync on every visit).
@@ -2622,6 +2656,7 @@ struct InkCudaModel {
// The K/V needs `want_chunks` more chunks than the card has free. Takes them from the coldest tail of d_sec4; they wait in the pool's donor list
// and the K/V's map takes them from there (no cuMemRelease / cuMemCreate in between). Returns the chunks gained.
int64_t reclaim_experts_for_kv(int64_t want_chunks, cudaStream_t sync_st) {
if (elastic_tier) return hybrid.tier_shrink(d_experts, sync_st, want_chunks, layer_has_host);
if (!elastic_sec4.active() || want_chunks <= 0 || h_exp_shadow.empty()) return 0;
const uint64_t gran = elastic_sec4.granularity();
if (gran == 0) return 0;
@@ -2684,11 +2719,13 @@ struct InkCudaModel {
cudaStreamSynchronize(sync_st);
hybrid.exact_flush_key_bytes(sync_st);
};
elastic_refresh_heat(); // who goes first: the router's own counts of the last tokens (the pack's order until there are enough)
return elastic_sec4.reclaim_chunks(take, /*release_to_os=*/false, sync_fn, d2d_swap_fn, publish_fn);
}
// Chunks the K/V gave back (a context that ended): they map behind the experts that left, which are read back from the host copy.
int64_t regrow_experts_from_donated(cudaStream_t sync_st) {
if (elastic_tier) return hybrid.tier_regrow(sync_st);
if (!elastic_sec4.active() || !elastic_armed || elastic_sec4.donated_chunk_count() == 0 || h_exp_shadow.empty()) return 0;
const int E = man.c.n_experts;
auto h2d_reload = [&](int key, uint64_t dst_off, uint32_t bytes) -> bool {
@@ -2768,9 +2805,10 @@ struct InkCudaModel {
stage_d_sec4[0] = nullptr;
ls_active = false; n_stages = 1;
if (d_elastic_reserve) { cudaFree(d_elastic_reserve); d_elastic_reserve = nullptr; }
if (d_elastic_heat) { ink_heat_cfg().dev = nullptr; cudaFree(d_elastic_heat); d_elastic_heat = nullptr; }
if (elastic_sec4.active()) { elastic_sec4.release(); d_sec4 = nullptr; }
h_exp_shadow.clear();
elastic_src.clear(); elastic_arena_off.clear(); elastic_armed = false; elastic_arena_used = 0;
elastic_src.clear(); elastic_arena_off.clear(); elastic_armed = false; elastic_tier = false; elastic_arena_used = 0;
if (d_sec4) { cudaFree(d_sec4); d_sec4 = nullptr; }
if (h_sec4_pinned) { cudaFreeHost(h_sec4_pinned); h_sec4_pinned = nullptr; }
if (h_embed_raw) { cudaFreeHost(h_embed_raw); h_embed_raw = nullptr; d_embed_mapped = nullptr; }
@@ -3339,7 +3377,7 @@ struct InkCudaRunner {
kv_dev_ctx = std::max(256, std::min(max_ctx, (max_slots == 1) ? c1_init_dev_cap : 4096));
kv_host_ctx = 0;
kv_alloc_ctx = kv_dev_ctx;
} else if (max_slots == 1 && !m.ls_active && !m.ep2_active && !m.all_sf4_vram && kv_offload_mode == 0 && m.elastic_sec4.active() && m.n_host_experts == 0 &&
} else if (max_slots == 1 && !m.ls_active && !m.ep2_active && !m.all_sf4_vram && kv_offload_mode == 0 && m.elastic_sec4.active() && (m.n_host_experts == 0 || m.elastic_tier) &&
strata::core::vmm_available() && elastic_fits_max_ctx(avail_glob, per_pos_glob, max_ctx)) {
// Elastic expert pool: the whole global K/V stays on the card (kv_host_ctx = 0). It starts small and grows through the K/V's virtual memory;
// what the card does not have free by then comes from the coldest tail of d_sec4 (reclaim_experts_for_kv), never from mapped host RAM.
@@ -3957,7 +3995,7 @@ struct InkCudaRunner {
// A conversation ended (the slot is reset) and experts are off the card: the K/V goes back to its start size and the chunks it frees take the experts back.
void kv_vmm_trim_and_regrow_experts(int keep_pos = 8192) {
if (!kv_vmm || max_slots != 1 || kv_host_ctx > 0 || !m.elastic_sec4.active() || !m.elastic_armed || m.n_host_experts == 0) return;
if (!kv_vmm || max_slots != 1 || kv_host_ctx > 0 || !m.elastic_sec4.active() || m.elastic_sec4.mapped_chunks() >= m.elastic_sec4.total_chunks()) return; // nothing left the card: nothing to give back
const int target = std::max(256, std::min(kv_dev_ctx, keep_pos));
if (target >= kv_dev_ctx) return;
const uint64_t g = strata::core::vmm_granularity();
+55 -5
View File
@@ -66,7 +66,9 @@ public:
return (il >= core_start_ && il < core_end_) ? 3.0f : 1.0f;
}
// Updates exponential moving average on decode/verify steps ONLY (frozen when M >= 16 prefill chunk!).
// `recent` is in picks per token (a looped layer's experts count once per visit, so the 3x is already in it): the cold hits per token an
// expert would cost if it left the card. It is fed either by record_step (host: one EMA bump per routed key of a decode / verify step; a
// prefill chunk, M >= 16, changes nothing) or by set_recent (the card's decayed counts, see k_ink_heat_add).
void record_step(const int32_t* routed_keys, int count, int batch_m) noexcept {
if (batch_m >= 16 || recent_.empty()) return;
const float decay = (batch_m <= 1) ? kDecayPerToken : std::pow(kDecayPerToken, (float)std::min(batch_m, 8));
@@ -74,18 +76,36 @@ public:
const float bump = 1.0f - kDecayPerToken;
for (int i = 0; i < count; ++i) {
const int k = routed_keys[i];
if (k >= 0 && (size_t)k < recent_.size()) {
recent_[(size_t)k] += bump;
}
if (k >= 0 && (size_t)k < recent_.size()) recent_[(size_t)k] += bump;
}
tokens_seen_ += (float)std::max(1, batch_m);
}
// counts[i] = the card's decayed pick count of key i (steady state: picks per token / (1 - gamma)). The number of tokens behind it is read off the
// total (8 picks x 48 visits per token): a few tokens of history do not outvote the prior.
void set_recent(const float* counts, int n) noexcept {
if (recent_.empty()) return;
double mass = 0.0;
for (int i = 0; i < n && (size_t)i < recent_.size(); ++i) {
recent_[(size_t)i] = counts[i] * (1.0f - kDecayPerToken);
mass += counts[i];
}
const double full = 8.0 * 48.0 / (1.0 - (double)kDecayPerToken);
const double fill = std::min(0.999, mass / full);
tokens_seen_ = (float)(std::log(1.0 - fill) / std::log((double)kDecayPerToken));
}
float tokens_seen() const noexcept { return tokens_seen_; }
// Residency score = expected cold hits per token that keeping the expert saves. Before anything has been seen it is the prior (the pack's own
// order: the position in vram_load_order, times the layer's visits, times a typical pick rate); with 128 tokens of history it is the measured rate.
float score(int key) const noexcept {
if (key < 0 || (size_t)key >= prior_.size()) return 0.0f;
const int il = n_experts_ > 0 ? (key / n_experts_) : 0;
return loop_weight(il) * (0.35f * prior_[(size_t)key] + 0.65f * recent_[(size_t)key]);
const float conf = std::min(1.0f, tokens_seen_ / 128.0f);
const float prior_rate = loop_weight(il) * 0.0625f * prior_[(size_t)key];
return (1.0f - conf) * prior_rate + conf * recent_[(size_t)key];
}
float static_density_score(int key, uint32_t body_bytes) const noexcept {
const float b = (float)std::max<uint32_t>(1u, body_bytes);
if (key < 0 || (size_t)key >= prior_.size()) return 0.0f;
@@ -100,6 +120,7 @@ private:
int core_end_ = 18;
std::vector<float> prior_;
std::vector<float> recent_;
float tokens_seen_ = 0.0f;
};
// ----------------------------------------------------------------------------
@@ -212,6 +233,35 @@ public:
size_t donated_chunk_count() const noexcept { return donor_chunks_.size(); }
// For a pool whose contents the caller manages itself (the hybrid engine's slot pool, no expert table here): the mapped part is a prefix of
// the range; these two move its end. The caller has moved or dropped whatever lived in the chunks it gives up (unmap_tail), and fills
// the chunks it gains (map_tail).
// Gives the top `take` mapped chunks (never below min_keep_bytes_) to the donor list, or back to the OS. Returns how many.
int64_t unmap_tail(int64_t take, bool release_to_os) {
if (!active_ || take <= 0) return 0;
const int64_t min_chunks = static_cast<int64_t>((min_keep_bytes_ + gran_ - 1) / gran_);
take = std::min(take, mapped_hi_ > min_chunks ? mapped_hi_ - min_chunks : 0);
int64_t n = 0;
for (int64_t c = mapped_hi_ - 1; n < take; --c, ++n) {
const strata::core::VmmChunk h = vmm_.unmap(c);
if (h != 0) {
if (release_to_os) strata::core::vmm_chunk_free(h);
else donor_chunks_.push_back(h);
}
}
mapped_hi_ -= n;
return n;
}
// Maps up to `add` chunks behind the mapped prefix: donated chunks first, new ones from the OS only when allowed. Returns how many.
int64_t map_tail(int64_t add, bool allow_os_alloc) {
if (!active_ || add <= 0 || mapped_hi_ >= vmm_.chunks()) return 0;
add = std::min(add, vmm_.chunks() - mapped_hi_);
if (!allow_os_alloc) add = std::min<int64_t>(add, static_cast<int64_t>(donor_chunks_.size()));
int64_t n = 0;
while (n < add && vmm_.map_range(mapped_hi_, mapped_hi_ + 1, [this] { return take_donated_chunk(); })) { ++mapped_hi_; ++n; }
return n;
}
template <class SyncFn, class D2DSwapFn, class PublishFn>
int64_t reclaim_chunks(int64_t need_chunks, bool release_to_os,
SyncFn&& sync_fn, D2DSwapFn&& d2d_swap_fn, PublishFn&& publish_fn) {
@@ -191,6 +191,22 @@ void test_elastic_pool_shrink_rescue_and_regrow() {
for (int step = 0; step < 40; ++step) pool.heat().record_step(&tail_hot_key, 1, /*batch_m=*/1);
CHECK(pool.heat().score(tail_hot_key) > pool.heat().score(0 * kExpPerLayer + 7));
// 3b. the card's decayed counts: the token count behind them is read off their total, and a measured rate outvotes the prior only as that grows
{
strata::ink::InkExpertHeatTracker t;
t.init(kLayers, kExpPerLayer, 6, 18, order);
const double full = 8.0 * 48.0 / (1.0 - (double)strata::ink::InkExpertHeatTracker::kDecayPerToken);
std::vector<float> counts((size_t)kTotal, 0.0f);
const int hot_key = order.back();
counts[(size_t)hot_key] = (float)(full * (1.0 - std::pow((double)strata::ink::InkExpertHeatTracker::kDecayPerToken, 64.0))); // all the mass on one expert
t.set_recent(counts.data(), kTotal);
CHECK(std::fabs(t.tokens_seen() - 64.0f) < 1.5f);
CHECK(t.score(hot_key) > t.score(order.front())); // 64 tokens of a single pick: it beats the prior of the best core expert
t.set_recent(std::vector<float>((size_t)kTotal, 0.0f).data(), kTotal);
CHECK(t.tokens_seen() < 0.5f); // nothing seen: back to the prior
CHECK(t.score(order.front()) > 2.5f * t.score(0));
}
// 4. reclaim 16 chunks (32 MiB) for the K/V: the hot tail expert is rescued into a safe chunk
std::vector<int> tier_of((size_t)kTotal, 0);
std::vector<uint64_t> dev_off((size_t)kTotal, 0);
@@ -265,6 +281,31 @@ void test_elastic_pool_shrink_rescue_and_regrow() {
std::printf("[PASS] InkElasticSec4Pool: 3x-loop order, prefill freeze, hot rescue, chunk hand-over and regrow, floor\n");
}
// A pool with no expert table (the hybrid engine's slot pool): the caller moves the end of the mapped prefix itself.
void test_tail_moves_for_a_caller_managed_pool() {
set_env("STRATA_INK_ELASTIC_MIN_EXP_MIB", "256"); // 128 chunks kept
strata::ink::InkElasticSec4Pool pool;
CHECK(pool.init_vmm(200 * kSimGran, 200 * kSimGran, {}));
CHECK(pool.active() && pool.mapped_chunks() == 200);
const size_t live0 = g_live_os_chunks;
CHECK(pool.unmap_tail(50, /*release_to_os=*/false) == 50); // 200 -> 150
CHECK(pool.mapped_chunks() == 150 && pool.donated_chunk_count() == 50 && g_live_os_chunks == live0);
CHECK(pool.unmap_tail(50, false) == 22); // the floor: 128 chunks stay
CHECK(pool.mapped_chunks() == 128 && pool.donated_chunk_count() == 72);
CHECK(pool.unmap_tail(1, false) == 0);
// the K/V takes 10 donated chunks and later gives them back; the pool maps what it is given first
std::vector<strata::core::VmmChunk> kv;
for (int i = 0; i < 10; ++i) kv.push_back(pool.take_donated_chunk());
CHECK(pool.donated_chunk_count() == 62);
CHECK(pool.map_tail(100, /*allow_os_alloc=*/false) == 62); // only donated chunks: 128 -> 190
CHECK(pool.mapped_chunks() == 190 && g_live_os_chunks == live0);
for (auto h : kv) pool.donate_chunk(h);
CHECK(pool.map_tail(100, false) == 10 && pool.mapped_chunks() == 200);
CHECK(pool.map_tail(1, true) == 0); // the range is full
CHECK(pool.unmap_tail(30, /*release_to_os=*/true) == 30 && g_live_os_chunks == live0 - 30);
std::printf("[PASS] InkElasticSec4Pool: unmap_tail / map_tail for a caller-managed pool\n");
}
void test_k8v4_and_k8v8_tc_attn_non_saturation() {
constexpr float kPScale = 32768.0f;
// value amplitudes amax in [0.01, 64] and probabilities p in [0.05, 1]
@@ -313,6 +354,7 @@ void test_k8v4_and_k8v8_tc_attn_non_saturation() {
int main() {
test_elastic_pool_shrink_rescue_and_regrow();
test_tail_moves_for_a_caller_managed_pool();
test_k8v4_and_k8v8_tc_attn_non_saturation();
if (g_failures) {
std::fprintf(stderr, "%d check(s) failed\n", g_failures);
@@ -105,6 +105,23 @@ int main() {
for (int k = 0; k < 10; ++k) CHECK(p.resident(k) && p.slot_of(k) < 0);
}
}
// 9. a slot the card gives up (the elastic K/V grew into its memory): its owner goes out, no round uses the slot, revive makes it empty and usable again
{
auto p = make(100, 0, 4); // keys 0..3 in slots 0..3
const int out = p.kill_slot(3);
CHECK(out == 3 && !p.resident(3) && p.slot_of(3) < 0 && !p.slot_alive(3) && p.n_alive_slots() == 3 && p.n_resident() == 3);
CHECK(p.kill_slot(3) == -1); // twice: nothing
for (int i = 0; i < 10; ++i) { p.add_use(50); p.add_use(51); p.add_use(52); p.add_use(53); p.add_use(54); }
auto sw = p.round();
for (const auto& s : sw) CHECK(s.slot != 3); // the dead slot is never handed out
p.revive_slot(3);
CHECK(p.slot_alive(3) && p.n_alive_slots() == 4 && !p.resident(3));
for (int i = 0; i < 10; ++i) p.add_use(60);
sw = p.round();
bool used3 = false;
for (const auto& s : sw) { if (s.slot == 3) { used3 = true; CHECK(s.out_key < 0 && s.in_key == 60); } }
CHECK(used3); // the empty revived slot takes the hot expert at once
}
// 8. pin_count: a quarter of the card, at least one
CHECK(InkExpertPolicy::pin_count(1000, 0.25f) == 250);
CHECK(InkExpertPolicy::pin_count(2, 0.25f) == 1);