Inkling CUDA: elastic expert pool, the global K/V grows on the card and takes 2 MiB chunks from the coldest experts instead of spilling to host RAM

Port of PR 1 of the owner's Inkling 2 Mini elastic VMM kit onto int-0225, reworked after review (see notes-ink-evmm.md).

When every expert fits at load (the non-COMPACT all-resident branch), d_sec4 is now one VmmRange packed in descending heat order (the 3x-looped
core layers first, the 1x prelude / coda layers last). The K/V no longer reserves its full size up front: the planner keeps the whole K/V on the
card (kv_host_ctx = 0) when the free memory plus what the pool may give up holds max_ctx, and the K/V grows through its own virtual memory. When
it needs more than the card has free (256 MiB floor kept), whole chunks from the tail of d_sec4 go to it directly (no cuMemRelease / cuMemCreate).

An expert that leaves the card is copied device-to-host into a pinned arena first, its table entry becomes tier 2, and the hybrid engine (not
started until then) serves it. The lane is the exact one (the card copies the expert in and computes it with its own kernels: same bits
wherever the expert lives), staged inside the CUDA graph for decode; STRATA_INK_EXACT=0 forces the CPU lane. What arming needs on the card
(prefill staging pair, staging slots) is set aside at load and handed back at the first eviction. When the conversation ends (reset_slot) with
experts off the card, the K/V returns to its start size and the freed chunks map behind the experts, which are copied back.

Switches: STRATA_INK_ELASTIC_EXPERTS=0 (one cudaMalloc as before), STRATA_INK_ELASTIC_MIN_EXP_MIB (floor of resident experts, default 1536).
Changes to the kit: init_vmm closed the file view it was given (removed with the view: the host copy is a D2H copy now, valid for any layout);
the hybrid engine is armed lazily with its VRAM reserved at load; resident experts keep host_meta.body null (the prefill streamer treats a
non-null body as cold); the K/V sizing branch is guarded for COMPACT / ls / ep2; the D2D swap uses the prefill staging buffer, not d_w_scratch.

Tests: engine CTest ink_elastic_sec4_test (host, simulated chunks; asserts are real checks, not assert()).
This commit is contained in:
Niko1221 committed 2026-12-02 20:57:41 +01:00
1 parent 951a4af886
commit 52954a6a09
6 files changed
+1087 -18

No files matched your search

+5
View File
@@ -323,6 +323,11 @@ if(STRATA_BUILD_TESTS)
add_executable(ink_batch_budget_test tests/core/ink_batch_budget_test.cpp)
target_include_directories(ink_batch_budget_test PRIVATE src/inkling2)
add_test(NAME ink_batch_budget_test COMMAND ink_batch_budget_test)
# the elastic expert pool of strata-inkling (the K/V takes 2 MiB chunks from the coldest experts) and the FP16 scaling of the K8V8 / K8V4 tensor-core attention: simulated chunks, no GPU
add_executable(ink_elastic_sec4_test tests/core/ink_elastic_sec4_test.cpp)
target_include_directories(ink_elastic_sec4_test PRIVATE include src/inkling2)
add_test(NAME ink_elastic_sec4_test COMMAND ink_elastic_sec4_test)
set_tests_properties(ink_elastic_sec4_test PROPERTIES TIMEOUT 60)
# #6770 / #6755: when strata-inkling's CUDA global K/V may grow in VRAM (net growth, not the whole new K/V; no GPU)
add_executable(ink_cold_lane_test tests/core/ink_cold_lane_test.cpp)
target_include_directories(ink_cold_lane_test PRIVATE include)
+5 -4
View File
@@ -1,8 +1,8 @@
#pragma once
// CUDA virtual memory (the elastic K/V, --kv-grow): an address range reserved once, whose physical memory is mapped and
// unmapped in chunks of the device's granularity (2 MiB). The K/V pools grow with the context by taking chunks the
// expert cache gives up, and neither moves: every captured graph and stored pointer stays valid. The driver calls
// are reached through the runtime's entry-point query, so nothing links the driver library. Not under HIP.
// CUDA & ROCm 6+ HIP virtual memory (the elastic K/V & expert pool): an address range reserved once, whose physical memory
// is mapped and unmapped in chunks of the device's granularity (2 MiB). The K/V pools grow with the context by taking chunks
// the expert cache gives up, and neither moves: every captured graph and stored pointer stays valid. The driver calls are
// reached through the runtime's entry-point query on CUDA (and hipMemMap on ROCm 6+ HIP), so nothing links libcuda directly.
#include <cstddef>
#include <cstdint>
@@ -36,6 +36,7 @@ public:
int64_t chunks() const { return (int64_t) h_.size(); }
bool mapped(int64_t i) const { return i >= 0 && i < chunks() && h_[(std::size_t) i] != 0; }
int64_t mapped_count() const;
uint64_t mapped_bytes() const { return (uint64_t) mapped_count() * vmm_granularity(); }
/// Maps chunks [lo, hi) that are not mapped yet, each to `take()` or, when that returns 0, to a new chunk.
/// Readable and writable when it returns; false: out of memory (what was mapped stays mapped).
template <class Take> bool map_range(int64_t lo, int64_t hi, Take take);
+33
View File
@@ -1525,6 +1525,37 @@ struct InkHybridEngine {
stage_ready = true;
exact_graph = exact_mode;
}
// Elastic expert pool (ink_elastic_sec4.hpp): the same in-graph staging as exact_prepare, but sized for any expert of the pack (which experts will be
// cold is not known yet) and with a key-bytes table the pool rewrites whenever an expert leaves the card or returns (exact_set_key_bytes / _flush).
// d_stage may already exist (the pool reserved it at load). false: no pinned arena, so the cold experts are not staged inside the graph.
std::vector<uint32_t> key_bytes_host;
bool key_bytes_dirty = false;
bool exact_prepare_elastic(size_t max_body, size_t n_keys) {
if (stage_ready) return true;
if (lane_pref == 2 || !active || ssd_only || !sec4_is_pinned || !h_sec4_pinned || max_body == 0) return false;
if (const char* e = std::getenv("STRATA_INK_EXACT_GRAPH")) if (e[0] == '0') return false;
stage_slot_bytes = (max_body + 255ull) & ~255ull;
if (!d_stage && cudaMalloc(&d_stage, stage_slot_bytes * kInkTopK) != cudaSuccess) { (void)cudaGetLastError(); d_stage = nullptr; return false; }
key_bytes_host.assign(n_keys, 0u);
d_key_bytes = dalloc<uint32_t>(n_keys);
INK_CK(cudaMemset(d_key_bytes, 0, n_keys * 4));
d_stage_state = dalloc<InkStageState>(1);
INK_CK(cudaMemset(d_stage_state, 0, sizeof(InkStageState)));
stage_ready = true;
exact_graph = exact_mode;
return true;
}
void exact_set_key_bytes(int key, uint32_t bytes) {
if (key < 0 || (size_t)key >= key_bytes_host.size() || key_bytes_host[(size_t)key] == bytes) return;
key_bytes_host[(size_t)key] = bytes;
key_bytes_dirty = true;
}
void exact_flush_key_bytes(cudaStream_t st) {
if (!key_bytes_dirty || !d_key_bytes) return;
INK_CK(cudaMemcpyAsync(d_key_bytes, key_bytes_host.data(), key_bytes_host.size() * 4, cudaMemcpyHostToDevice, st));
INK_CK(cudaStreamSynchronize(st)); // key_bytes_host may change again before the copy would read it
key_bytes_dirty = false;
}
uint32_t promo_step = 0; // cadence counter so step_promote does NOT sync every single token!
// Expert-cache statistics of the batched path (M <= 16, i.e. decode): every routed expert counted, and those that were not in the card
// (host RAM or SSD) counted as misses; STATS reports the hit rate (the share of routed experts served from the card).
@@ -2759,6 +2790,8 @@ struct InkHybridEngine {
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);
fr(d_stage); fr(d_key_bytes); fr(d_stage_state);
stage_ready = false; exact_graph = false;
for (int b = 0; b < 2; ++b) {
if (h_pf_exp_pin[b]) { cudaFreeHost(h_pf_exp_pin[b]); h_pf_exp_pin[b] = nullptr; }
if (h_pf_bounce[b]) { cudaFreeHost(h_pf_bounce[b]); h_pf_bounce[b] = nullptr; }
+357 -14
View File
@@ -11,6 +11,7 @@
#include "ink_cuda.cuh"
#include "ink_dflash2_path.cuh"
#include "ink_hybrid.cuh"
#include "../ink_elastic_sec4.hpp"
#include "ink_elastic_kv_ssd.cuh"
#include "ink_rtx5060ti_opt.cuh"
#include "ink_5060ti_fp8.cuh"
@@ -301,6 +302,18 @@ struct InkCudaModel {
bool layer_has_host[24] = {};
bool layer_has_peer[24] = {};
InkHybridEngine hybrid;
// Elastic expert pool (ink_elastic_sec4.hpp): d_sec4 in virtual memory, the coldest tail goes to the K/V when it grows. The hybrid engine
// is not started until the first expert leaves the card (elastic_arm); until then the card holds all 3072 experts exactly as before.
InkElasticSec4Pool elastic_sec4;
std::vector<InkExpertDev> h_exp_shadow; // the host copy of d_experts[] (a leaving or returning expert rewrites its layer's table)
std::vector<InkHostExpertMeta> elastic_src; // per key: layout facts of the expert (size, codes, down offset); its host copy is made when it leaves the card
size_t elastic_max_body = 0;
int elastic_cpu_threads = 0;
bool elastic_armed = false;
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
uint64_t elastic_evicted_total = 0; // experts that left the card, over the session (for the log)
// Exact 2-stage unembed screening index (for BF16 unembed in SQ-20)
UnembedScreenIndex unembed_screen;
@@ -931,21 +944,93 @@ struct InkCudaModel {
n_vram_experts, (size_t)n_total,
(double)sec4_bytes / 1073741824.0, n_transcoded, (double)vf_after / 1048576.0);
} else if (!ssd_experts && vfree > sec4_bytes + reserve && sec4_bytes <= user_vram_cap) {
// 100% VRAM resident! Single sequential streaming DMA!
INK_CK(cudaMalloc(&d_sec4, sec4_bytes));
const size_t CH = 64ull << 20;
uint8_t* hbuf = halloc_pinned<uint8_t>(std::min(CH, sec4_bytes));
size_t done = 0;
while (done < sec4_bytes) {
size_t want = std::min(CH, sec4_bytes - done);
if (!rd.read_at(hdr.sections[4].file_offset + done, hbuf, want, err)) {
cudaFreeHost(hbuf);
return false;
// 100% VRAM resident at startup. With virtual memory the experts are packed in descending heat order (the 3x-looped core layers first,
// the 1x prelude / coda layers last) into one address range (InkElasticSec4Pool): when the global K/V later grows past what the card has
// free, whole 2 MiB chunks of the coldest tail go to the K/V instead of the K/V going to mapped host RAM (the experts that lose their
// chunk are served by the hybrid engine from a host copy, see elastic_arm). STRATA_INK_ELASTIC_EXPERTS=0 keeps one cudaMalloc.
bool used_elastic_vmm = false;
const char* kv_vmm_env_ld = std::getenv("STRATA_INK_KV_VMM");
if (InkElasticSec4Pool::env_enabled() && !(kv_vmm_env_ld && kv_vmm_env_ld[0] == '0') && strata::core::vmm_available()) {
const auto& vorder = rd.vram_load_order();
std::vector<uint16_t> order;
if ((int)vorder.size() == n_total) {
order = vorder;
} else {
order.reserve(n_total);
for (int il = man.c.core_start; il < man.c.core_end; ++il)
for (int r = 0; r < man.c.n_experts; ++r) order.push_back((uint16_t)(il * man.c.n_experts + r));
for (int il = 0; il < man.c.core_start; ++il)
for (int r = 0; r < man.c.n_experts; ++r) order.push_back((uint16_t)(il * man.c.n_experts + r));
for (int il = man.c.core_end; il < man.c.n_phys; ++il)
for (int r = 0; r < man.c.n_experts; ++r) order.push_back((uint16_t)(il * man.c.n_experts + r));
}
std::vector<uint16_t> key_order;
key_order.reserve(order.size());
std::vector<InkElasticSlot> eslots;
eslots.reserve(order.size());
uint64_t pack_off = 0;
for (uint16_t di : order) {
const auto& e = dir[di];
const int il = di / man.c.n_experts;
const int key = il * man.c.n_experts + e.expert_id;
key_order.push_back((uint16_t)key);
InkElasticSlot s{};
s.key = key;
s.body_off = pack_off;
s.body_bytes = e.body_bytes;
s.gu_code = e.gu_code_id;
s.dn_code = e.dn_code_id;
s.resident = true;
eslots.push_back(s);
pack_off += e.body_bytes;
}
elastic_sec4.heat().init(man.c.n_phys, man.c.n_experts, man.c.core_start, man.c.core_end, key_order);
if (elastic_sec4.init_vmm(pack_off, pack_off, eslots)) {
d_sec4 = elastic_sec4.base();
sec4_bytes = (size_t)pack_off;
elastic_src.assign((size_t)n_total, {});
for (int di = 0; di < n_total; ++di) {
const auto& e = dir[di];
const int il = di / man.c.n_experts;
const int key = il * man.c.n_experts + e.expert_id;
elastic_src[key].body_bytes = e.body_bytes; // the layout facts of the expert (no host copy yet: it is made when the expert leaves the card)
elastic_src[key].dn_off = e.dn_offset;
elastic_src[key].gu_code = e.gu_code_id;
elastic_src[key].dn_code = e.dn_code_id;
elastic_max_body = std::max<size_t>(elastic_max_body, e.body_bytes);
}
uint8_t* h_one = halloc_pinned<uint8_t>(elastic_max_body);
const auto& placed = elastic_sec4.slots(); // placed[i] is the expert of directory entry order[i]
for (size_t i = 0; i < placed.size(); ++i) {
const auto& s = placed[i];
const auto& de = dir[order[i]];
if (!rd.read_at(hdr.sections[4].file_offset + de.body_offset, h_one, s.body_bytes, err)) { cudaFreeHost(h_one); return false; }
INK_CK(cudaMemcpy(d_sec4 + s.body_off, h_one, s.body_bytes, cudaMemcpyHostToDevice));
h_exp[s.key].body_off = s.body_off;
h_exp[s.key].tier = 0;
}
INK_CK(cudaFreeHost(h_one));
used_elastic_vmm = true;
} else {
elastic_sec4.release();
}
INK_CK(cudaMemcpy(d_sec4 + done, hbuf, want, cudaMemcpyHostToDevice));
done += want;
}
INK_CK(cudaFreeHost(hbuf));
if (!used_elastic_vmm) {
INK_CK(cudaMalloc(&d_sec4, sec4_bytes));
const size_t CH = 64ull << 20;
uint8_t* hbuf = halloc_pinned<uint8_t>(std::min(CH, sec4_bytes));
size_t done = 0;
while (done < sec4_bytes) {
size_t want = std::min(CH, sec4_bytes - done);
if (!rd.read_at(hdr.sections[4].file_offset + done, hbuf, want, err)) {
cudaFreeHost(hbuf);
return false;
}
INK_CK(cudaMemcpy(d_sec4 + done, hbuf, want, cudaMemcpyHostToDevice));
done += want;
}
INK_CK(cudaFreeHost(hbuf));
}
n_vram_experts = n_total;
n_host_experts = 0;
} else {
@@ -1255,6 +1340,12 @@ struct InkCudaModel {
}
double t_exp = now_s() - t1;
h_exp_shadow = h_exp;
elastic_cpu_threads = cpu_threads;
if (elastic_sec4.active()) { // set aside what arming will need (see elastic_arm); a failed reserve only means arming may fail later
const size_t rb = elastic_arm_vram_bytes();
if (rb > 0 && cudaMalloc(&d_elastic_reserve, rb) != cudaSuccess) { (void)cudaGetLastError(); d_elastic_reserve = nullptr; }
}
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,
@@ -2478,6 +2569,162 @@ struct InkCudaModel {
return true;
}
// ---- Elastic expert pool (see ink_elastic_sec4.hpp) ----
// What arming needs on the card (the prefill staging pair, the exact lane's staging slots, the hybrid engine's small buffers): set aside at load
// as one block (d_elastic_reserve) and handed back right before the allocations, so the first eviction never needs memory the card no longer has.
size_t elastic_arm_vram_bytes() const {
if (elastic_max_body == 0) return 0;
const size_t stage = ((elastic_max_body + 255ull) & ~255ull) * kInkTopK;
return 2 * InkHybridEngine::pf_stage_size(elastic_max_body) + stage + (8ull << 20);
}
uint8_t* d_elastic_reserve = nullptr;
// 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).
bool elastic_arm() {
if (elastic_armed) return true;
if (!elastic_sec4.active() || elastic_max_body == 0) return false;
cudaSetDevice(primary_gpu);
cudaDeviceSynchronize();
if (d_elastic_reserve) { cudaFree(d_elastic_reserve); d_elastic_reserve = nullptr; }
const size_t n_total = (size_t)man.c.n_phys * man.c.n_experts;
hybrid.host_meta.assign(n_total, {});
hybrid.orig_host_off.assign(n_total, 0);
hybrid.start_workers(elastic_cpu_threads);
if (!hybrid.alloc_pf_stage(elastic_max_body)) {
std::fprintf(stderr, "[InkElastic] cannot allocate the prefill staging buffers: no expert leaves the card\n");
return false;
}
const uint64_t arena_bytes = std::max<uint64_t>(elastic_arena_plan, (uint64_t)elastic_max_body * 64ull);
uint8_t* arena = hybrid.alloc_host_arena((size_t)arena_bytes);
if (!arena) {
std::fprintf(stderr, "[InkElastic] cannot allocate the host copy (%.2f GiB): no expert leaves the card\n", (double)arena_bytes / 1073741824.0);
return false;
}
elastic_arena_off.assign(n_total, -1);
elastic_arena_used = 0;
hybrid.alloc_staging(elastic_max_body, 0); // the pinned bounce pair when the arena is pageable (no VRAM is requested with 0 available)
if (hybrid.lane_pref != 2 && (hybrid.lane_pref == 1 || hybrid.sec4_is_pinned)) {
hybrid.set_lane(true);
const bool graph = hybrid.exact_prepare_elastic(elastic_max_body, n_total);
std::fprintf(stderr, "[InkElastic] cold experts: copied into the card and computed by its kernels (exact, identical answers)%s\n",
graph ? ", staged inside the CUDA graph" : ", eager (no pinned host copy)");
} else {
std::fprintf(stderr, "[InkElastic] cold experts: computed on the CPU where they are (%s; the answer can differ in rounding)\n",
hybrid.lane_pref == 2 ? "STRATA_INK_EXACT=0" : "the host copy is not pinned");
}
elastic_armed = true;
std::fprintf(stderr, "[InkElastic] armed: host copy %.2f GiB (%s)\n", (double)arena_bytes / 1073741824.0, hybrid.sec4_is_pinned ? "pinned" : "pageable");
return true;
}
// 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_sec4.active() || want_chunks <= 0 || h_exp_shadow.empty()) return 0;
const uint64_t gran = elastic_sec4.granularity();
if (gran == 0) return 0;
if (!elastic_armed && !elastic_arm()) return 0;
const int E = man.c.n_experts;
// the host copy holds the experts that left; a chunk takes at most gran bytes of them plus one straddling expert
const uint64_t arena_total = hybrid.h_sec4_bytes;
const uint64_t arena_free = arena_total > elastic_arena_used ? arena_total - elastic_arena_used : 0;
const int64_t arena_chunks = arena_free > elastic_max_body ? (int64_t)((arena_free - elastic_max_body) / gran) : 0;
const int64_t take = std::min<int64_t>(want_chunks, arena_chunks);
if (take <= 0) return 0;
auto sync_fn = [&]() {
cudaSetDevice(primary_gpu);
cudaDeviceSynchronize(); // an eviction is rare: nothing may still read the tail
};
auto d2d_swap_fn = [&](uint64_t off_a, uint64_t off_b, uint32_t bytes) -> bool {
if (!hybrid.d_pf_stage[0] || hybrid.pf_stage_bytes < bytes) return false;
uint8_t* scratch = hybrid.d_pf_stage[0];
cudaMemcpyAsync(scratch, d_sec4 + off_a, bytes, cudaMemcpyDeviceToDevice, sync_st);
cudaMemcpyAsync(d_sec4 + off_a, d_sec4 + off_b, bytes, cudaMemcpyDeviceToDevice, sync_st);
cudaMemcpyAsync(d_sec4 + off_b, scratch, bytes, cudaMemcpyDeviceToDevice, sync_st);
return true;
};
auto publish_fn = [&](const std::vector<int>& evicted, const std::vector<std::pair<int, uint64_t>>& moved) {
bool dirty_layer[24] = {};
for (const auto& mv : moved) {
h_exp_shadow[(size_t)mv.first].body_off = mv.second;
dirty_layer[mv.first / E] = true;
}
for (int key : evicted) {
const int il = key / E;
const auto& src = elastic_src[(size_t)key];
int64_t off = elastic_arena_off[(size_t)key];
if (off < 0) {
off = (int64_t)elastic_arena_used;
elastic_arena_used += (src.body_bytes + 63ull) & ~63ull;
elastic_arena_off[(size_t)key] = off;
}
uint8_t* dst = const_cast<uint8_t*>(hybrid.sec4_is_pinned ? hybrid.h_sec4_pinned : hybrid.h_sec4_pageable) + off;
// the host copy is what is on the card now (a rescued or swapped expert sits at its new offset, h_exp_shadow has it): bytes as they are, any layout
cudaMemcpyAsync(dst, d_sec4 + h_exp_shadow[(size_t)key].body_off, src.body_bytes, cudaMemcpyDeviceToHost, sync_st);
auto& hm = hybrid.host_meta[(size_t)key];
hm.body = dst; hm.body_bytes = src.body_bytes; hm.dn_off = src.dn_off; hm.gu_code = src.gu_code; hm.dn_code = src.dn_code; hm.cold_ssd = false;
hybrid.orig_host_off[(size_t)key] = (uint64_t)off;
hybrid.exact_set_key_bytes(key, src.body_bytes);
h_exp_shadow[(size_t)key].body_off = (uint64_t)off;
h_exp_shadow[(size_t)key].tier = 2;
layer_has_host[il] = true;
dirty_layer[il] = true;
if (n_vram_experts > 0) --n_vram_experts;
++n_host_experts;
++elastic_evicted_total;
}
for (int il = 0; il < man.c.n_phys; ++il) {
if (dirty_layer[il] && d_experts[il]) {
cudaMemcpyAsync(d_experts[il], h_exp_shadow.data() + (size_t)il * E, (size_t)E * sizeof(InkExpertDev), cudaMemcpyHostToDevice, sync_st);
}
}
cudaStreamSynchronize(sync_st);
hybrid.exact_flush_key_bytes(sync_st);
};
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_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 {
if ((size_t)key >= hybrid.host_meta.size() || !hybrid.host_meta[(size_t)key].body) return false;
return cudaMemcpyAsync(d_sec4 + dst_off, hybrid.host_meta[(size_t)key].body, bytes, cudaMemcpyHostToDevice, sync_st) == cudaSuccess;
};
auto sync_fn = [&]() {
cudaSetDevice(primary_gpu);
cudaStreamSynchronize(sync_st);
};
auto restore_pub = [&](const std::vector<std::pair<int, uint64_t>>& restored) {
bool dirty_layer[24] = {};
for (const auto& r : restored) {
const int key = r.first;
const int il = key / E;
h_exp_shadow[(size_t)key].body_off = r.second;
h_exp_shadow[(size_t)key].tier = 0;
hybrid.host_meta[(size_t)key].body = nullptr; // on the card again: the prefill streamer and the doorbell must not treat it as cold
dirty_layer[il] = true;
++n_vram_experts;
if (n_host_experts > 0) --n_host_experts;
}
for (int il = 0; il < man.c.n_phys; ++il) {
if (!dirty_layer[il]) continue;
bool any_host = false;
for (int e = 0; e < E; ++e) if (h_exp_shadow[(size_t)il * E + e].tier != 0) { any_host = true; break; }
layer_has_host[il] = any_host;
if (d_experts[il]) {
cudaMemcpyAsync(d_experts[il], h_exp_shadow.data() + (size_t)il * E, (size_t)E * sizeof(InkExpertDev), cudaMemcpyHostToDevice, sync_st);
}
}
cudaStreamSynchronize(sync_st);
};
return elastic_sec4.regrow_chunks((int64_t)elastic_sec4.donated_chunk_count(), /*allow_os_alloc=*/false, h2d_reload, sync_fn, restore_pub);
}
void free_all() {
if (ep2_active && peer_gpu >= 0) {
cudaSetDevice(peer_gpu);
@@ -2520,6 +2767,10 @@ struct InkCudaModel {
cudaSetDevice(primary_gpu);
stage_d_sec4[0] = nullptr;
ls_active = false; n_stages = 1;
if (d_elastic_reserve) { cudaFree(d_elastic_reserve); d_elastic_reserve = 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;
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; }
@@ -3088,6 +3339,18 @@ 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 &&
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.
kv_dev_ctx = std::max(256, std::min(max_ctx, c1_init_dev_cap));
kv_host_ctx = 0;
kv_alloc_ctx = kv_dev_ctx;
const size_t room = elastic_free_room(avail_glob);
const size_t need_evict = (size_t)max_ctx * per_pos_glob > room ? (size_t)max_ctx * per_pos_glob - room : 0;
m.elastic_arena_plan = std::min<uint64_t>(m.elastic_sec4.reclaimable_bytes(), (uint64_t)need_evict + need_evict / 8 + (96ull << 20));
std::fprintf(stderr, "[InkCUDA] Elastic expert pool (kv_fmt=%d): K/V starts at %d tokens on the card and grows to %d with no host K/V; at most %.2f GiB of the coldest experts leave the card for it (%.2f GiB may)\n",
(int)kv_dtype, kv_dev_ctx, max_ctx, (double)need_evict / 1073741824.0, (double)m.elastic_sec4.reclaimable_bytes() / 1073741824.0);
} else if (kv_offload_mode == 0 && host_fit_ctx >= 256) {
int dev_part = (vram_fit_ctx >= 1024) ? ((vram_fit_ctx * 3 / 4) & ~255) : 0;
int host_part = std::min(max_ctx - dev_part, host_fit_ctx);
@@ -3608,7 +3871,8 @@ struct InkCudaRunner {
if (g == 0) return false;
for (int b = 0; b < kv_vmm_nbuf(); ++b) {
const uint64_t bytes = (uint64_t)upto_pos * kv_vmm_buf[v][b].bpp;
if (!kv_vmm_buf[v][b].r.map_range(0, (int64_t)((bytes + g - 1) / g), [] { return (strata::core::VmmChunk)0; })) return false;
if (!kv_vmm_buf[v][b].r.map_range(0, (int64_t)((bytes + g - 1) / g),
[this] { return m.elastic_sec4.take_donated_chunk(); })) return false;
}
return true;
}
@@ -3632,9 +3896,55 @@ struct InkCudaRunner {
kv_dev_ctx = cap;
kv_alloc_ctx = cap;
}
// ---- elastic expert pool: room for the global K/V ----
static constexpr size_t kElasticGrowFloor = 256ull << 20; // free memory the card keeps (the floor the copying K/V growth keeps too)
static size_t elastic_free_room(size_t avail_glob) { return avail_glob > kElasticGrowFloor ? avail_glob - kElasticGrowFloor : 0; }
// Does a K/V of `ctx` positions fit on the card when the experts the pool may give up are given up?
bool elastic_fits_max_ctx(size_t avail_glob, size_t per_pos_glob, int ctx) const {
const uint64_t have = (uint64_t)elastic_free_room(avail_glob) + m.elastic_sec4.reclaimable_bytes();
return have / std::max<size_t>(1, per_pos_glob) >= (uint64_t)ctx;
}
// chunks the global K/V still has to map to hold `pos` positions
int64_t kv_vmm_missing_chunks(int pos) const {
const uint64_t g = strata::core::vmm_granularity();
int64_t missing = 0;
if (g == 0) return 0;
for (int v = 0; v < kInkVisits; ++v) {
if (kv_desc[v].is_swa) continue;
for (int b = 0; b < kv_vmm_nbuf(); ++b) {
const int64_t want_c = (int64_t)(((uint64_t)pos * kv_vmm_buf[v][b].bpp + g - 1) / g);
const int64_t cur_c = kv_vmm_buf[v][b].r.mapped_count();
if (want_c > cur_c) missing += want_c - cur_c;
}
}
return missing;
}
// Room for `pos` positions: the chunks the K/V gave back and what the card has free above the floor first, then the coldest experts. false: not enough.
bool elastic_make_room(int pos) {
if (!m.elastic_sec4.active()) return true;
const uint64_t g = strata::core::vmm_granularity();
if (g == 0) return false;
int64_t need = kv_vmm_missing_chunks(pos) - (int64_t)m.elastic_sec4.donated_chunk_count();
if (need <= 0) return true;
size_t vf = 0, vt = 0;
if (ink_cuda_mem_info(&vf, &vt, m.primary_gpu) == cudaSuccess && vf > kElasticGrowFloor) need -= (int64_t)((vf - kElasticGrowFloor) / g);
if (need <= 0) return true;
const int64_t got = m.reclaim_experts_for_kv(need, st);
if (got > 0) {
drop_all_graphs(); // the table of experts and which layers have cold ones changed: the graphs are captured again
std::fprintf(stderr, "[InkElastic] %lld chunks (%.1f MiB) of the coldest experts went to the K/V: %zu of %d experts stay on the card, %zu on the host\n",
(long long)got, (double)(got * (int64_t)g) / 1048576.0, m.n_vram_experts, m.man.c.n_phys * m.man.c.n_experts, m.n_host_experts);
}
return got >= need;
}
// growth without a copy: map more physical memory behind the same addresses. When even the request itself does not fit the tail goes to host RAM (kv_spill_tail), as before.
bool kv_vmm_grow(int old_cap, int new_cap, int needed_pos) {
int target = new_cap;
const bool elastic = m.elastic_sec4.active();
if (elastic && !elastic_make_room(target)) {
const int tight = std::min(max_ctx, ((needed_pos + 255) & ~255));
if (tight > old_cap && tight < target && elastic_make_room(tight)) target = tight;
}
if (!kv_vmm_map_all(target)) {
const int tight = std::min(max_ctx, ((needed_pos + 255) & ~255));
if (tight > old_cap && tight < target && kv_vmm_map_all(tight)) target = tight;
@@ -3644,10 +3954,40 @@ struct InkCudaRunner {
std::fprintf(stderr, "[InkCUDA] Elastic global KV grown (virtual memory, no copy): %d -> %d tokens (max_ctx=%d)\n", old_cap, target, max_ctx);
return true;
}
// 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;
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();
if (g == 0) return;
cudaSetDevice(m.primary_gpu);
cudaDeviceSynchronize();
int64_t returned = 0;
for (int v = 0; v < kInkVisits; ++v) {
if (kv_desc[v].is_swa) continue;
for (int b = 0; b < kv_vmm_nbuf(); ++b) {
const int64_t keep_c = (int64_t)(((uint64_t)target * kv_vmm_buf[v][b].bpp + g - 1) / g);
for (int64_t c = kv_vmm_buf[v][b].r.chunks() - 1; c >= keep_c; --c) {
const strata::core::VmmChunk h = kv_vmm_buf[v][b].r.unmap(c);
if (h != 0) { m.elastic_sec4.donate_chunk(h); ++returned; }
}
}
}
kv_vmm_publish(target);
if (returned > 0) {
const int64_t regrown = m.regrow_experts_from_donated(st);
drop_all_graphs();
std::fprintf(stderr, "[InkElastic] context ended: K/V back to %d tokens, %lld chunks went back to the experts (%zu on the card, %zu on the host)\n",
target, (long long)regrown, m.n_vram_experts, m.n_host_experts);
}
}
// STRATA_INK_KV_PREALLOC=1 (--kv-prealloc): the whole max_ctx is mapped now, so nothing grows at run time and the start-up says whether the context fits. false: it does not.
bool kv_prealloc_all() {
if (!kv_vmm || kv_alloc_ctx >= max_ctx) return kv_vmm;
const int old_cap = kv_alloc_ctx;
if (!elastic_make_room(max_ctx)) return false;
if (!kv_vmm_map_all(max_ctx)) return false;
kv_vmm_publish(max_ctx);
std::fprintf(stderr, "[InkCUDA] kv-prealloc: global K/V mapped for the whole context: %d -> %d tokens\n", old_cap, max_ctx);
@@ -3839,6 +4179,9 @@ struct InkCudaRunner {
void reset_slot(int slot) {
elastic_kv.reset_slot(slot);
if (slot == 0 && max_slots == 1 && kv_vmm && m.elastic_sec4.active() && kv_dev_ctx > 8192) {
kv_vmm_trim_and_regrow_experts(8192);
}
constexpr int c_off[4] = {0, kInkKVDim, 2 * kInkKVDim, 2 * kInkKVDim + kInkHidden};
constexpr int c_len[4] = {kInkKVDim, kInkKVDim, kInkHidden, kInkHidden};
for (int v = 0; v < kInkVisits; ++v) {
+364
View File
@@ -0,0 +1,364 @@
// engine/src/inkling2/ink_elastic_sec4.hpp - Elastic VMM Expert Pool & 32-Token Heat Tracker
//
// MIT License
// Copyright (c) 2026 Niko1221 and the Strata contributors
//
// Connects `strata::core::VmmRange` (CUDA & ROCm 6+ HIP 2 MiB virtual memory) to Inkling-2-Mini's Section 4 expert
// pool (`d_sec4`) so that:
// 1. `d_sec4 = vmm_.base()` never moves across the lifetime of the model (all CUDA/HIP graphs stay valid).
// 2. Experts are packed in descending `(loop_multiplicity * routing_prior) / body_bytes` order (3x-looped L6..17
// core experts at offset 0; coldest 1x prelude/coda experts in the top 2 MiB chunks).
// 3. An expert that leaves the card is copied to the host first (the caller does that in the publish callback of reclaim_chunks), so the
// host copy exists only for experts that have left and is exactly the bytes that were on the card, whatever their layout.
// 4. Growing Global KV (`kv_vmm_buf`) reclaims 2 MiB `VmmChunk` handles directly from the coldest tail of `d_sec4`
// (rescuing any runtime-hot expert via in-VRAM D2D swap before unmapping) rather than spilling KV to PCIe RAM.
// 5. When long requests finish or reset, unmapped KV chunks return to `d_sec4` and refill asynchronously from host.
#pragma once
#include "strata/core/vmm.hpp"
#include <algorithm>
#include <cmath>
#include <cstddef>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
#include <utility>
#include <vector>
namespace strata::ink {
// ----------------------------------------------------------------------------
// 32-Token Half-Life Routing Heat Tracker (Prefill-Frozen)
// ----------------------------------------------------------------------------
class InkExpertHeatTracker {
public:
static constexpr float kHalfLifeTokens = 32.0f;
static constexpr float kDecayPerToken = 0.97857206f; // 2^(-1/32)
void init(int n_phys, int n_experts, int core_start, int core_end,
const std::vector<uint16_t>& vram_order,
const float* optional_prior = nullptr) {
n_phys_ = n_phys;
n_experts_ = n_experts;
core_start_ = core_start;
core_end_ = core_end;
const int total = n_phys * n_experts;
prior_.assign((size_t)total, 0.5f);
recent_.assign((size_t)total, 0.0f);
if (optional_prior) {
for (int k = 0; k < total; ++k) prior_[(size_t)k] = std::max(1e-4f, optional_prior[k]);
} else if ((int)vram_order.size() == total) {
for (int rank = 0; rank < total; ++rank) {
const uint16_t key = vram_order[(size_t)rank];
if (key < (uint16_t)total) {
const float frac = (float)rank / (float)std::max(1, total - 1);
prior_[key] = 1.0f - 0.65f * frac;
}
}
}
}
float loop_weight(int il) const noexcept {
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!).
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));
for (float& r : recent_) r *= decay;
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;
}
}
}
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]);
}
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;
const int il = n_experts_ > 0 ? (key / n_experts_) : 0;
return (loop_weight(il) * prior_[(size_t)key]) / b;
}
private:
int n_phys_ = 24;
int n_experts_ = 128;
int core_start_ = 6;
int core_end_ = 18;
std::vector<float> prior_;
std::vector<float> recent_;
};
// ----------------------------------------------------------------------------
// Elastic VMM Section-4 Expert Pool (Backend-Neutral via DeviceOps callbacks)
// ----------------------------------------------------------------------------
struct InkElasticSlot {
int key = -1; // il * n_experts + expert_id
uint64_t body_off = 0; // byte offset inside sec4_vmm [0, total_bytes_)
uint32_t body_bytes = 0;
uint8_t gu_code = 0;
uint8_t dn_code = 0;
bool resident = false; // true -> tier 0 in VRAM; false -> tier 2 in Host/Hybrid
};
class InkElasticSec4Pool {
public:
InkElasticSec4Pool() = default;
~InkElasticSec4Pool() { release(); }
InkElasticSec4Pool(const InkElasticSec4Pool&) = delete;
InkElasticSec4Pool& operator=(const InkElasticSec4Pool&) = delete;
static bool env_enabled() noexcept {
const char* e = std::getenv("STRATA_INK_ELASTIC_EXPERTS");
return !(e && e[0] == '0');
}
static uint64_t env_min_expert_bytes() noexcept {
if (const char* e = std::getenv("STRATA_INK_ELASTIC_MIN_EXP_MIB")) {
const long mib = std::strtol(e, nullptr, 10);
if (mib >= 256 && mib <= 32768) return static_cast<uint64_t>(mib) << 20;
}
return 1536ull << 20; // 1.5 GiB default floor (~512 hot 3x-looped core experts)
}
bool active() const noexcept { return active_; }
uint8_t* base() const noexcept { return vmm_.base(); }
uint64_t granularity() const noexcept { return gran_; }
int64_t total_chunks() const noexcept { return vmm_.chunks(); }
int64_t mapped_chunks() const noexcept { return mapped_hi_; }
uint64_t mapped_bytes() const noexcept { return static_cast<uint64_t>(mapped_hi_) * gran_; }
uint64_t total_bytes() const noexcept { return total_bytes_; }
size_t resident_count() const noexcept { return n_resident_; }
uint64_t reclaimable_bytes() const noexcept {
if (!active_) return 0;
const uint64_t cur = mapped_bytes();
return cur > min_keep_bytes_ ? (cur - min_keep_bytes_) : 0ull;
}
InkExpertHeatTracker& heat() noexcept { return heat_; }
const InkExpertHeatTracker& heat() const noexcept { return heat_; }
const std::vector<InkElasticSlot>& slots() const noexcept { return slots_; }
bool init_vmm(uint64_t total_sec4_bytes, uint64_t init_vram_bytes,
const std::vector<InkElasticSlot>& ordered_slots) {
release_pool();
if (!env_enabled() || !strata::core::vmm_available() || total_sec4_bytes == 0) return false;
gran_ = strata::core::vmm_granularity();
if (gran_ == 0) return false;
if (!vmm_.reserve(total_sec4_bytes)) return false;
total_bytes_ = total_sec4_bytes;
min_keep_bytes_ = std::min(total_sec4_bytes, env_min_expert_bytes());
slots_ = ordered_slots;
key_to_slot_.assign(slots_.size(), -1);
for (size_t i = 0; i < slots_.size(); ++i) {
if (slots_[i].key >= 0 && (size_t)slots_[i].key < key_to_slot_.size()) {
key_to_slot_[(size_t)slots_[i].key] = (int)i;
}
}
const uint64_t clamped_init = std::min(total_sec4_bytes, init_vram_bytes);
const int64_t want_chunks = static_cast<int64_t>((clamped_init + gran_ - 1) / gran_);
if (want_chunks > 0 && !vmm_.map_range(0, want_chunks, [this] { return take_donated_chunk(); })) {
vmm_.release();
return false;
}
mapped_hi_ = want_chunks;
active_ = true;
refresh_residency_counts();
return true;
}
// release_pool() frees the chunks and the address range; release() is the same (kept for the callers that mean "all of it")
void release_pool() {
for (strata::core::VmmChunk h : donor_chunks_) {
strata::core::vmm_chunk_free(h);
}
donor_chunks_.clear();
vmm_.release();
slots_.clear();
key_to_slot_.clear();
mapped_hi_ = 0;
total_bytes_ = 0;
n_resident_ = 0;
active_ = false;
}
void release() { release_pool(); }
void donate_chunk(strata::core::VmmChunk h) {
if (h != 0) donor_chunks_.push_back(h);
}
strata::core::VmmChunk take_donated_chunk() {
if (donor_chunks_.empty()) return 0;
const strata::core::VmmChunk h = donor_chunks_.back();
donor_chunks_.pop_back();
return h;
}
size_t donated_chunk_count() const noexcept { return donor_chunks_.size(); }
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) {
if (!active_ || need_chunks <= 0) return 0;
const int64_t min_chunks = static_cast<int64_t>((min_keep_bytes_ + gran_ - 1) / gran_);
const int64_t avail = mapped_hi_ > min_chunks ? (mapped_hi_ - min_chunks) : 0;
const int64_t take = std::min(need_chunks, avail);
if (take <= 0) return 0;
sync_fn();
const int64_t new_hi = mapped_hi_ - take;
const uint64_t cut_off = static_cast<uint64_t>(new_hi) * gran_;
std::vector<size_t> victims;
for (size_t i = 0; i < slots_.size(); ++i) {
if (slots_[i].resident && slots_[i].body_off + slots_[i].body_bytes > cut_off) {
victims.push_back(i);
}
}
std::sort(victims.begin(), victims.end(), [&](size_t a, size_t b) {
return heat_.score(slots_[a].key) > heat_.score(slots_[b].key);
});
std::vector<std::pair<int, uint64_t>> moved_keys;
constexpr int kMaxSwapsPerReclaim = 32;
int swaps_done = 0;
for (size_t vi : victims) {
if (swaps_done >= kMaxSwapsPerReclaim) break;
const float v_score = heat_.score(slots_[vi].key);
ptrdiff_t best_ci = -1;
float best_c_score = v_score * 0.90f;
for (ptrdiff_t ci = static_cast<ptrdiff_t>(slots_.size()) - 1; ci >= 0; --ci) {
const auto& cand = slots_[(size_t)ci];
if (!cand.resident || cand.body_off + cand.body_bytes > cut_off) continue;
if (cand.body_bytes != slots_[vi].body_bytes ||
cand.gu_code != slots_[vi].gu_code ||
cand.dn_code != slots_[vi].dn_code) continue;
const float cs = heat_.score(cand.key);
if (cs < best_c_score) {
best_c_score = cs;
best_ci = ci;
if (best_c_score <= 0.01f) break;
}
}
if (best_ci >= 0) {
auto& hot_s = slots_[vi];
auto& cold_s = slots_[(size_t)best_ci];
if (d2d_swap_fn(hot_s.body_off, cold_s.body_off, hot_s.body_bytes)) {
std::swap(hot_s.key, cold_s.key);
key_to_slot_[(size_t)hot_s.key] = (int)vi;
key_to_slot_[(size_t)cold_s.key] = (int)best_ci;
moved_keys.emplace_back(hot_s.key, hot_s.body_off);
moved_keys.emplace_back(cold_s.key, cold_s.body_off);
++swaps_done;
}
}
}
std::vector<int> evicted_keys;
evicted_keys.reserve(victims.size());
for (auto& s : slots_) {
if (s.resident && s.body_off + s.body_bytes > cut_off) {
s.resident = false;
--n_resident_;
evicted_keys.push_back(s.key);
}
}
publish_fn(evicted_keys, moved_keys);
sync_fn();
int64_t unmapped = 0;
for (int64_t c = mapped_hi_ - 1; c >= new_hi; --c) {
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);
++unmapped;
}
}
mapped_hi_ = new_hi;
return unmapped;
}
template <class H2DReloadFn, class SyncFn, class RestorePublishFn>
int64_t regrow_chunks(int64_t add_chunks, bool allow_os_alloc,
H2DReloadFn&& h2d_reload_fn, SyncFn&& sync_fn, RestorePublishFn&& restore_publish_fn) {
if (!active_ || add_chunks <= 0 || mapped_hi_ >= vmm_.chunks()) return 0;
const int64_t max_add = vmm_.chunks() - mapped_hi_;
int64_t target_add = std::min(add_chunks, max_add);
if (!allow_os_alloc) {
target_add = std::min<int64_t>(target_add, static_cast<int64_t>(donor_chunks_.size()));
}
if (target_add <= 0) return 0;
const int64_t old_hi = mapped_hi_;
int64_t cur_hi = old_hi;
while (cur_hi < old_hi + target_add) {
if (!vmm_.map_range(cur_hi, cur_hi + 1, [this] { return take_donated_chunk(); })) break;
++cur_hi;
}
if (cur_hi == old_hi) return 0;
mapped_hi_ = cur_hi;
const uint64_t new_cap_bytes = mapped_bytes();
std::vector<std::pair<int, uint64_t>> restored;
for (auto& s : slots_) {
if (!s.resident && s.body_off + s.body_bytes <= new_cap_bytes) {
if (h2d_reload_fn(s.key, s.body_off, s.body_bytes)) {
s.resident = true;
++n_resident_;
restored.emplace_back(s.key, s.body_off);
}
}
}
sync_fn();
if (!restored.empty()) {
restore_publish_fn(restored);
sync_fn();
}
return cur_hi - old_hi;
}
private:
void refresh_residency_counts() noexcept {
const uint64_t cap = mapped_bytes();
n_resident_ = 0;
for (auto& s : slots_) {
s.resident = (s.body_off + s.body_bytes <= cap);
if (s.resident) ++n_resident_;
}
}
strata::core::VmmRange vmm_;
std::vector<strata::core::VmmChunk> donor_chunks_;
std::vector<InkElasticSlot> slots_;
std::vector<int> key_to_slot_;
InkExpertHeatTracker heat_;
uint64_t gran_ = 0;
uint64_t total_bytes_ = 0;
uint64_t min_keep_bytes_ = 1536ull << 20;
int64_t mapped_hi_ = 0;
size_t n_resident_ = 0;
bool active_ = false;
};
} // namespace strata::ink
+323
View File
@@ -0,0 +1,323 @@
// ink_elastic_sec4_test.cpp - host test of InkElasticSec4Pool (the elastic expert pool of strata-inkling) and of the FP16 scaling TC_ATTN uses for K8V8 / K8V4
//
// MIT License
// Copyright (c) 2026 Niko1221 and the Strata contributors
//
// Self-contained: no GPU. `strata::core::VmmRange` is replaced by a stub over simulated 2 MiB pages (so this test does not link strata_engine), then
// 1. the packing order: the 3x-looped core experts outscore the 1x prelude / coda experts,
// 2. reclaim_chunks(): a hot expert in the tail is rescued by a swap with a colder one below the cut and its bytes arrive intact,
// 3. the heat: a prefill chunk (M >= 16) does not change it, decode steps do,
// 4. the chunks move from the pool to the K/V and back without a new physical chunk (no driver release / create),
// 5. regrow_chunks(): the experts that left come back,
// 6. a reclaim that would go under the floor takes nothing,
// 7. K8V4 / K8V8 pre-scaling: every value is exact in FP16 and the P*V product never reaches 65504.
// (The kit's version of this test used assert(), which is compiled out in a Release build; CHECK below is not.)
#include <algorithm>
#include <cmath>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <unordered_map>
#include <vector>
#include "strata/core/vmm.hpp"
namespace {
constexpr uint64_t kSimGran = 2ull << 20; // 2 MiB
uint64_t g_next_handle = 1;
size_t g_live_os_chunks = 0;
std::unordered_map<strata::core::VmmChunk, std::vector<uint8_t>> g_phys_pages;
std::unordered_map<unsigned long long, std::vector<uint8_t>*> g_backing;
int g_failures = 0;
#define CHECK(cond) \
do { \
if (!(cond)) { \
std::fprintf(stderr, "CHECK failed: %s (%s:%d)\n", #cond, __FILE__, __LINE__); \
++g_failures; \
} \
} while (0)
void set_env(const char* k, const char* v) {
#ifdef _WIN32
_putenv_s(k, v);
#else
setenv(k, v, 1);
#endif
}
} // namespace
namespace strata::core {
bool vmm_available() { return true; }
uint64_t vmm_granularity() { return kSimGran; }
VmmChunk vmm_chunk_new() {
const VmmChunk h = g_next_handle++;
g_phys_pages[h].assign(kSimGran, 0);
++g_live_os_chunks;
return h;
}
void vmm_chunk_free(VmmChunk h) {
if (h != 0 && g_phys_pages.erase(h) > 0) --g_live_os_chunks;
}
bool VmmRange::reserve(uint64_t bytes) {
release();
const uint64_t n = (bytes + kSimGran - 1) / kSimGran;
auto* backing = new std::vector<uint8_t>(n * kSimGran, 0);
base_ = reinterpret_cast<unsigned long long>(backing->data());
g_backing[base_] = backing;
h_.assign((size_t)n, 0);
return true;
}
void VmmRange::release() {
if (base_ == 0) return;
for (int64_t i = 0; i < chunks(); ++i) vmm_chunk_free(unmap(i));
auto it = g_backing.find(base_);
if (it != g_backing.end()) { delete it->second; g_backing.erase(it); }
base_ = 0;
h_.clear();
}
int64_t VmmRange::mapped_count() const {
int64_t n = 0;
for (VmmChunk h : h_) n += (h != 0);
return n;
}
bool VmmRange::map_one(int64_t i, VmmChunk h) {
h_[(size_t)i] = h;
return true;
}
bool VmmRange::set_access(int64_t, int64_t) { return true; }
bool VmmRange::commit_run(int64_t lo, int64_t hi) { return set_access(lo, hi); }
VmmChunk VmmRange::unmap(int64_t i) {
if (!mapped(i)) return 0;
const VmmChunk h = h_[(size_t)i];
h_[(size_t)i] = 0;
return h;
}
} // namespace strata::core
#include "ink_elastic_sec4.hpp"
namespace {
// IEEE-754 FP16 round-to-nearest-even software reference (matches CUDA `__float2half_rn`)
uint16_t f32_to_f16_rn(float f) {
uint32_t x;
std::memcpy(&x, &f, 4);
const uint32_t sign = (x >> 16) & 0x8000u;
int exp = (int)((x >> 23) & 0xFFu) - 127 + 15;
uint32_t mant = x & 0x007FFFFFu;
if (exp <= 0) {
if (exp < -10) return (uint16_t)sign;
mant |= 0x00800000u;
const int shift = 14 - exp;
const uint32_t half_bit = 1u << (shift - 1);
const uint32_t rem = mant & ((1u << shift) - 1u);
uint32_t h = mant >> shift;
if (rem > half_bit || (rem == half_bit && (h & 1u))) ++h;
return (uint16_t)(sign | h);
}
if (exp >= 31) return (uint16_t)(sign | 0x7BFFu);
const uint32_t rem = mant & 0x1FFFu;
uint32_t h = (uint32_t)(exp << 10) | (mant >> 13);
if (rem > 0x1000u || (rem == 0x1000u && (h & 1u))) ++h;
return (uint16_t)(sign | h);
}
float f16_to_f32(uint16_t h) {
const uint32_t s = (uint32_t)(h & 0x8000u) << 16;
const uint32_t e = (h >> 10) & 0x1Fu;
const uint32_t m = h & 0x03FFu;
uint32_t f = (e == 0) ? s : (s | ((e + 112u) << 23) | (m << 13));
float out;
std::memcpy(&out, &f, 4);
return out;
}
void test_elastic_pool_shrink_rescue_and_regrow() {
set_env("STRATA_INK_ELASTIC_MIN_EXP_MIB", "256"); // 256 MiB floor for the compact test (384 MiB pool)
strata::ink::InkElasticSec4Pool pool;
constexpr int kLayers = 24;
constexpr int kExpPerLayer = 8; // 192 experts * 2 MiB = 384 MiB
constexpr int kTotal = kLayers * kExpPerLayer;
constexpr uint32_t kBodyBytes = 2u << 20;
std::vector<uint16_t> order;
for (int il = 6; il < 18; ++il)
for (int e = 0; e < kExpPerLayer; ++e) order.push_back((uint16_t)(il * kExpPerLayer + e));
for (int il = 0; il < 6; ++il)
for (int e = 0; e < kExpPerLayer; ++e) order.push_back((uint16_t)(il * kExpPerLayer + e));
for (int il = 18; il < 24; ++il)
for (int e = 0; e < kExpPerLayer; ++e) order.push_back((uint16_t)(il * kExpPerLayer + e));
pool.heat().init(kLayers, kExpPerLayer, 6, 18, order);
// 1. the 3x-looped core experts strictly outscore the 1x prelude / coda experts at start-up
CHECK(pool.heat().score(6 * kExpPerLayer + 0) > 2.5f * pool.heat().score(0 * kExpPerLayer + 0));
std::vector<strata::ink::InkElasticSlot> slots;
std::vector<uint32_t> host_sig((size_t)kTotal, 0);
uint64_t off = 0;
for (uint16_t key : order) {
strata::ink::InkElasticSlot s{};
s.key = key;
s.body_off = off;
s.body_bytes = kBodyBytes;
s.gu_code = 1;
s.dn_code = 1;
s.resident = true;
slots.push_back(s);
host_sig[key] = 0xA5000000u | (uint32_t)key;
off += kBodyBytes;
}
const bool ok = pool.init_vmm(off, off, slots);
CHECK(ok && pool.resident_count() == (size_t)kTotal);
if (!ok) return;
const size_t os_chunks_at_load = g_live_os_chunks;
CHECK(os_chunks_at_load == (size_t)kTotal);
for (const auto& s : pool.slots()) std::memcpy(pool.base() + s.body_off, &host_sig[(size_t)s.key], 4);
// 2. a prefill chunk (M = 128) does not change the heat
const int tail_hot_key = order.back(); // the very last tail expert (coda, layer 23)
const float pre_pf = pool.heat().score(tail_hot_key);
for (int step = 0; step < 20; ++step) pool.heat().record_step(&tail_hot_key, 1, /*batch_m=*/128);
CHECK(std::fabs(pool.heat().score(tail_hot_key) - pre_pf) < 1e-7f);
// 3. decode steps do: 40 consecutive hits make the tail expert hotter than a prelude expert
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));
// 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);
for (const auto& s : pool.slots()) dev_off[(size_t)s.key] = s.body_off;
const int64_t reclaimed = pool.reclaim_chunks(
16, /*release_to_os=*/false,
[]() {},
[&](uint64_t a, uint64_t b, uint32_t bytes) {
std::vector<uint8_t> tmp(bytes);
std::memcpy(tmp.data(), pool.base() + a, bytes);
std::memcpy(pool.base() + a, pool.base() + b, bytes);
std::memcpy(pool.base() + b, tmp.data(), bytes);
return true;
},
[&](const std::vector<int>& evicted, const std::vector<std::pair<int, uint64_t>>& moved) {
for (const auto& mv : moved) dev_off[(size_t)mv.first] = mv.second;
for (int k : evicted) tier_of[(size_t)k] = 2;
});
CHECK(reclaimed == 16);
CHECK(pool.donated_chunk_count() == 16);
CHECK(g_live_os_chunks == os_chunks_at_load); // no driver release / create
CHECK(tier_of[(size_t)tail_hot_key] == 0); // the rescued expert stayed on the card
{
uint32_t check_sig = 0;
std::memcpy(&check_sig, pool.base() + dev_off[(size_t)tail_hot_key], 4);
CHECK(check_sig == host_sig[(size_t)tail_hot_key]); // its bytes arrived intact
}
size_t evicted_n = 0;
for (int k = 0; k < kTotal; ++k) evicted_n += (tier_of[(size_t)k] == 2);
CHECK(evicted_n == (size_t)(kTotal - pool.resident_count()));
// 5. the K/V takes the 16 chunks and gives them back, then the experts return
std::vector<strata::core::VmmChunk> kv_held;
while (pool.donated_chunk_count() > 0) kv_held.push_back(pool.take_donated_chunk());
CHECK(kv_held.size() == 16);
for (auto h : kv_held) pool.donate_chunk(h);
const int64_t regrown = pool.regrow_chunks(
16, /*allow_os_alloc=*/false,
[&](int key, uint64_t dst_off, uint32_t /*bytes*/) {
std::memcpy(pool.base() + dst_off, &host_sig[(size_t)key], 4);
return true;
},
[]() {},
[&](const std::vector<std::pair<int, uint64_t>>& restored) {
for (const auto& r : restored) {
tier_of[(size_t)r.first] = 0;
dev_off[(size_t)r.first] = r.second;
}
});
CHECK(regrown == 16);
CHECK(pool.resident_count() == (size_t)kTotal);
for (int k = 0; k < kTotal; ++k) {
CHECK(tier_of[(size_t)k] == 0);
uint32_t sig = 0;
std::memcpy(&sig, pool.base() + dev_off[(size_t)k], 4);
CHECK(sig == host_sig[(size_t)k]);
}
// 6. the floor: with 256 MiB kept (128 chunks) of 192 chunks mapped, at most 64 chunks can go, however many are asked for
const int64_t big = pool.reclaim_chunks(
1000, /*allow=*/false, []() {}, [](uint64_t, uint64_t, uint32_t) { return false; },
[&](const std::vector<int>& evicted, const std::vector<std::pair<int, uint64_t>>&) { for (int k : evicted) tier_of[(size_t)k] = 2; });
CHECK(big == 64);
CHECK(pool.mapped_chunks() == 128);
CHECK(pool.reclaim_chunks(1, false, []() {}, [](uint64_t, uint64_t, uint32_t) { return false; },
[](const std::vector<int>&, const std::vector<std::pair<int, uint64_t>>&) {}) == 0);
std::printf("[PASS] InkElasticSec4Pool: 3x-loop order, prefill freeze, hot rescue, chunk hand-over and regrow, floor\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]
const float amaxes[] = {0.01f, 0.5f, 2.0f, 16.0f, 32.0f, 64.0f};
const float probs[] = {0.05f, 0.25f, 0.75f, 1.0f};
for (float am : amaxes) {
// K8V4: nib - 8 in [-7, 7], stored scale amax / 7; the kernel stores V * 64 and the scale / 64 (= amax / 448, the FP8 range)
const float v_sc_k8v4 = am / 7.0f;
const float svs_tc4 = v_sc_k8v4 * 0.015625f;
for (int qv = -7; qv <= 7; ++qv) {
const float ref_v = (float)qv * v_sc_k8v4;
const float smem_v = f16_to_f32(f32_to_f16_rn((float)qv * 64.0f));
CHECK(smem_v == (float)qv * 64.0f); // exact in FP16
for (float p : probs) {
CHECK(p * svs_tc4 * kPScale < 65504.0f); // never saturates, even at amax = 64 and p = 1
const float p_scaled_f16 = f16_to_f32(f32_to_f16_rn(std::min(p * svs_tc4 * kPScale, 65504.0f)));
const float tc_prod = (p_scaled_f16 * smem_v) * (1.0f / kPScale);
const float ref_prod = p * ref_v;
CHECK(std::fabs(tc_prod - ref_prod) <= 1.5e-3f * std::fabs(ref_prod) + 1e-9f);
}
}
// the unscaled form saturates above amax 14 for K8V4: the reason for the pre-scaling
if (am > 14.5f) CHECK(1.0f * v_sc_k8v4 * kPScale > 65504.0f);
// K8V8: int8 in [-127, 127], stored scale amax / 127; V * 4 and the scale / 4
const float v_sc_k8v8 = am / 127.0f;
const float svs_tc8 = v_sc_k8v8 * 0.25f;
for (int qv : {-127, -63, -1, 0, 1, 63, 127}) {
const float ref_v = (float)qv * v_sc_k8v8;
const float smem_v = f16_to_f32(f32_to_f16_rn((float)qv * 4.0f));
CHECK(smem_v == (float)qv * 4.0f);
for (float p : probs) {
CHECK(p * svs_tc8 * kPScale < 65504.0f);
const float p_scaled_f16 = f16_to_f32(f32_to_f16_rn(std::min(p * svs_tc8 * kPScale, 65504.0f)));
const float tc_prod = (p_scaled_f16 * smem_v) * (1.0f / kPScale);
const float ref_prod = p * ref_v;
CHECK(std::fabs(tc_prod - ref_prod) <= 1.5e-3f * std::fabs(ref_prod) + 1e-9f);
}
}
}
std::printf("[PASS] K8V4 and K8V8 TC_ATTN scaling: exact FP16 values and no 65504 saturation up to amax 64\n");
}
} // namespace
int main() {
test_elastic_pool_shrink_rescue_and_regrow();
test_k8v4_and_k8v8_tc_attn_non_saturation();
if (g_failures) {
std::fprintf(stderr, "%d check(s) failed\n", g_failures);
return 1;
}
std::printf("ALL TESTS PASSED.\n");
return 0;
}