Elastic K/V (--kv-grow): the K/V takes VRAM as the context grows, the expert cache holds the rest

At --max-context 262144 the K/V is allocated whole at start (3.35 GiB at int8 with the drafter's) and the expert
cache is sized around it. With --kv-grow (or STRATA_KV_GROW=1) the K/V pools and the cache arena are CUDA VMM ranges
(core/vmm.hpp; the driver calls through the runtime's entry-point query, nothing links the driver library). The K/V
maps 2 MiB chunks for the cells the requests reach (16384 at start); when a request needs more, slots just below the
prompt path's loan give theirs up, a hotter expert in them first moving into the slot of the coldest one in the loan
region. A short request after a long one hands the chunks back and the slots refill from the profile. No address
moves, so no graph is captured again, and --max-context cells always fit.

- serve: grows at a request (its prompt, and a parked conversation before its restore) and in the decode rounds;
  trims once the outgoing session is parked
- generate: grows once for the prompt and max_new, before the loan
- one GPU with a profile, the whole K/V in VRAM (no --kv-resident), every expert in RAM (not the low-RAM tier);
  STRATA_KV_GROW_INIT / _STEP / _FLOOR for tests. Off by default: more slots move experts between GPU and CPU.
- tests/core/vmm_test: map, a chunk moved between ranges keeps its bytes, release

IQ2_XS, RTX 5090, 262K, fixed cache: first-token logits and 64 tokens bit-identical to 0.1.31 off, mapped whole,
grown into new VRAM, and grown by giving up 266 slots. Cache auto: 15,119-15,207 -> 17,300-17,503 slots, short chat
15.06-15.33 -> 14.71-14.83 ms a round; an emulated 16 GB card: 3,396 -> 5,719 slots, short chat 100 -> 115 tok/s,
a 32K prompt 7.44 -> 6.36 s and 24.6 -> 22.2 ms a round after it.
This commit is contained in:
sergiywith authored and Niko1221 committed 2026-10-05 19:57:35 +02:00
1 parent 91cc8149b0
commit 9e3dbfe74a
9 files changed
+758 -5

No files matched your search

+5 -1
View File
@@ -427,7 +427,7 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP)
src/core/remote_expert_opt.cu
src/core/expert_cache.cpp src/core/native_head.cpp src/core/native_dense.cpp src/core/verify.cpp src/core/mtp.cpp
src/core/conversation_snapshot.cpp src/core/conversation_state.cpp src/core/conversation_memory.cpp src/core/peer_experts.cpp
src/core/arch_defaults.cpp)
src/core/arch_defaults.cpp src/core/vmm.cpp)
target_include_directories(strata_engine PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include)
target_link_libraries(strata_engine PUBLIC strata_core strata_kernels strata_kernels_cpu ${_strata_gpu_runtime_target})
if(STRATA_BUILD_TESTS AND EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/tests/core/exchange_storage_test.cpp")
@@ -444,6 +444,10 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP)
target_link_libraries(file_expert_source_test PRIVATE strata_engine)
add_test(NAME file_expert_source_test COMMAND file_expert_source_test)
set_tests_properties(file_expert_source_test PROPERTIES TIMEOUT 60)
add_executable(vmm_test tests/core/vmm_test.cpp)
target_link_libraries(vmm_test PRIVATE strata_engine)
add_test(NAME vmm_test COMMAND vmm_test)
set_tests_properties(vmm_test PROPERTIES TIMEOUT 60)
endif()
# #477: the learned expert profile (--expert-profile-save): its order and make_profile.py's file format (CPU only)
if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/tests/core/expert_profile_save_test.cpp")
+12
View File
@@ -24,9 +24,12 @@
#include <cstddef>
#include <cstdint>
#include <memory>
#include <string>
#include <vector>
#include "strata/core/vmm.hpp"
namespace strata::core {
/// Where one expert's VRAM lives, or -1. `int32_t` and not a bool because the slot index is what the kernel
@@ -198,6 +201,14 @@ public:
/// Slots filled so far, for the startup report.
int64_t fills() const { return fills_; }
/// The elastic K/V (--kv-grow): the arena in a VMM range (vmm.hpp) instead of one cudaMalloc, so the K/V can take
/// single chunks of it and give them back. Applies to the next `open`; ignored where VMM is not available.
static void set_vmm(bool enabled);
/// The arena's range (null: one cudaMalloc).
VmmRange* vmm_range() { return vmm_.get(); }
/// Byte offset of slot `s` in the arena (s == slots(): the end).
uint64_t slot_offset(int64_t s) const { return off_.empty() ? (uint64_t) s * (uint64_t) blob_ : off_[(size_t) s]; }
private:
#if defined(STRATA_USE_HIP)
bool ensure_blocking_staging(std::size_t bytes, std::string& err);
@@ -215,6 +226,7 @@ private:
std::vector<unsigned long long> segs_; ///< #533: each segment's physical handle (0: unmapped)
std::vector<int64_t> seg_size_; ///< #533: each segment's size (the last one may be shorter)
int64_t mapped_segs_ = 0; ///< #533: segments [0, mapped_segs_) are backed
std::unique_ptr<VmmRange> vmm_; ///< the arena's range when it is in VMM (set_vmm)
std::vector<int32_t> residency_; ///< [n_layers * n_expert] -> slot or kNotResident
int64_t slots_ = 0;
int64_t n_layers_ = 0;
+24
View File
@@ -41,6 +41,9 @@
#include "strata/kernels/ple.hpp"
#include <cstdio>
#include <functional>
#include "strata/core/vmm.hpp"
#include <cstdlib>
#include <cstdint>
#include <string>
@@ -233,6 +236,9 @@ struct QsaState {
/// pages at `block % n_slots`, with the host copy for a resume. The pool pointers above point at the slots.
int kv_mode = 0;
int64_t n_slots = 0;
/// The elastic K/V (qsa_set_kv_elastic): this state's pools are in a VMM range mapped only as far as the
/// context needs - its index in layer.cpp's registry; -1: carved from the arena as before.
int32_t kv_elastic = -1;
strata::kernels::KvHostPools host;
strata::kernels::KvStreamMap map;
int64_t idx_pooled_rows = 0; ///< rows of `idx_pooled` (a ring, which has no indexer, keeps 2)
@@ -276,6 +282,24 @@ uint64_t qsa_state_bytes(const ModelGeometry& g, int64_t max_cells, bool with_ro
/// Also puts the MTP drafter's K/V in a ring of its window (`ring_cells` of qsa_state_bytes/init; -1 forces a fully
/// resident state).
void qsa_set_kv_resident(int64_t cells);
/// THE ELASTIC K/V (--kv-grow; vmm.hpp). A mode-0 state's K/V pools get addresses for every cell of the context but
/// physical memory only for the first `init_cells`; `qsa_kv_elastic_grow` maps more as the context grows (from
/// chunks the expert cache gives up) and `qsa_kv_elastic_shrink` hands them back. The addresses never move, so the
/// captured graphs stay valid. Set before sizing and initializing the session and the drafter.
void qsa_set_kv_elastic(bool enabled, int64_t init_cells);
bool qsa_kv_elastic();
/// Cells every elastic state can hold now (INT64_MAX when none is elastic).
int64_t qsa_kv_elastic_cells();
/// Chunks still to map for every elastic state to hold `cells` cells.
int64_t qsa_kv_elastic_need(int64_t cells);
/// Maps them, each from `take()` (0: a new chunk), the new memory zeroed. Synchronous; nothing may be running on
/// the device. false: out of memory.
bool qsa_kv_elastic_grow(int64_t cells, const std::function<VmmChunk()>& take);
/// Unmaps the chunks past `cells` cells, each handed to `give`. Returns how many.
int64_t qsa_kv_elastic_shrink(int64_t cells, const std::function<void(VmmChunk)>& give);
/// Physical bytes the elastic pools hold, and what all of them would at the full context.
uint64_t qsa_kv_elastic_mapped_bytes();
uint64_t qsa_kv_elastic_full_bytes();
int64_t qsa_kv_resident();
/// The fewest resident cells a streamed layer may have: one verify window's selections (8 queries x 2,051 cells
/// in whole blocks) must fit at once, with room to spare.
+73
View File
@@ -0,0 +1,73 @@
#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.
#include <cstdint>
#include <vector>
namespace strata::core {
/// A physical chunk: the driver's allocation handle (CUmemGenericAllocationHandle); 0 = none.
using VmmChunk = unsigned long long;
/// The current device supports it and the entry points resolved.
bool vmm_available();
/// The chunk size (0 when not available).
uint64_t vmm_granularity();
/// A new physical chunk on the current device (0: out of memory), and its release.
VmmChunk vmm_chunk_new();
void vmm_chunk_free(VmmChunk h);
class VmmRange {
public:
VmmRange() = default;
~VmmRange() { release(); }
VmmRange(const VmmRange&) = delete;
VmmRange& operator=(const VmmRange&) = delete;
/// Reserves `bytes` (rounded up to whole chunks) of addresses, nothing mapped.
bool reserve(uint64_t bytes);
/// Unmaps and frees every chunk, then the addresses.
void release();
uint8_t* base() const { return (uint8_t*) (uintptr_t) base_; }
int64_t chunks() const { return (int64_t) h_.size(); }
bool mapped(int64_t i) const { return i >= 0 && i < chunks() && h_[(size_t) i] != 0; }
int64_t mapped_count() const;
/// 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);
/// Unmaps chunk i and hands back its physical chunk (0 when it was not mapped).
VmmChunk unmap(int64_t i);
private:
bool map_one(int64_t i, VmmChunk h);
bool set_access(int64_t lo, int64_t hi);
unsigned long long base_ = 0;
std::vector<VmmChunk> h_; // per chunk: its physical chunk, 0 = unmapped
};
template <class Take> bool VmmRange::map_range(int64_t lo, int64_t hi, Take take) {
lo = lo < 0 ? 0 : lo;
hi = hi > chunks() ? chunks() : hi;
int64_t run = -1; // access is set once per run of newly mapped chunks (it costs as much as the map)
for (int64_t i = lo; i < hi; ++i) {
if (mapped(i)) {
if (run >= 0 && !set_access(run, i)) return false;
run = -1;
continue;
}
VmmChunk h = take();
if (h == 0) h = vmm_chunk_new();
if (h == 0 || !map_one(i, h)) {
if (h != 0) vmm_chunk_free(h);
if (run >= 0) set_access(run, i);
return false;
}
if (run < 0) run = i;
}
return run < 0 || set_access(run, hi);
}
} // namespace strata::core
+21
View File
@@ -449,6 +449,12 @@ bool ExpertCache::ensure_blocking_staging(std::size_t bytes, std::string& err) {
}
#endif
namespace {
bool g_cache_vmm = false; // set_vmm
} // namespace
void ExpertCache::set_vmm(bool enabled) { g_cache_vmm = enabled; }
bool ExpertCache::open(int64_t n_slots, int64_t n_layers, int64_t n_expert, int64_t blob_bytes,
std::string& err) {
close();
@@ -487,6 +493,18 @@ bool ExpertCache::open(int64_t n_slots, int64_t n_layers, int64_t n_expert, int6
if (seg_req_ > 0) { // #533: --vram-elastic: physical segments behind one address range (zeroed below)
if (!open_segmented(want, err)) return false;
} else if (g_cache_vmm && vmm_available()) {
// the elastic K/V: every chunk mapped now; the K/V may later take some of them (and give them back)
auto r = std::make_unique<VmmRange>();
if (!r->reserve(want) || !r->map_range(0, r->chunks(), [] { return (VmmChunk) 0; })) {
char buf[256];
std::snprintf(buf, sizeof buf, "ExpertCache: mapping %.2f GiB of VRAM failed: out of memory",
(double) want / 1073741824.0);
err = buf;
return false;
}
base_ = r->base();
vmm_ = std::move(r);
} else if (cudaMalloc((void**) &base_, (size_t) want) != cudaSuccess) {
base_ = nullptr;
char buf[256];
@@ -571,6 +589,9 @@ void ExpertCache::close() {
off_.clear();
if (!segs_.empty()) {
release_segmented();
} else if (vmm_) {
vmm_.reset(); // unmaps and frees every chunk it still holds
base_ = nullptr;
} else if (base_ != nullptr) {
cudaFree(base_);
base_ = nullptr;
+154 -4
View File
@@ -37,6 +37,8 @@
#include <cmath>
#include <cstdio>
#include <cstring>
#include <limits>
#include <memory>
#include <vector>
namespace strata::core {
namespace { bool g_shared_early = true; bool g_fused_gr = false; bool g_fast_attn = true; bool g_publish_kernel = true; bool g_fused_gdn = true; bool g_fast_select = true; }
@@ -515,6 +517,115 @@ namespace {
int64_t g_kv_resident = 0;
uint64_t g_kv_host_bytes = 0;
// ---- the elastic K/V (--kv-grow): one VMM range per state, each pool array at a chunk boundary in it
bool g_kv_elastic = false;
int64_t g_kv_elastic_init = 16384;
struct ElasticPool {
strata::core::VmmRange range;
std::vector<uint64_t> off, per_slot; // each array's offset in the range (whole chunks) and bytes per page slot
int64_t n_slots = 0, page_size = 0;
};
std::vector<std::unique_ptr<ElasticPool>> g_pools;
int64_t pool_chunks(const ElasticPool& p, size_t a, int64_t slots) {
const uint64_t G = strata::core::vmm_granularity();
return (int64_t) (((uint64_t) slots * p.per_slot[a] + G - 1) / G);
}
int64_t pool_slots(const ElasticPool& p, int64_t cells) {
return std::min<int64_t>(p.n_slots, std::max<int64_t>((cells + p.page_size - 1) / p.page_size, 1));
}
/// Whole page slots every array of the pool has mapped.
int64_t pool_slots_mapped(const ElasticPool& p) {
const uint64_t G = strata::core::vmm_granularity();
int64_t slots = p.n_slots;
for (size_t a = 0; a < p.off.size(); ++a) {
const int64_t c0 = (int64_t) (p.off[a] / G);
const int64_t end = a + 1 < p.off.size() ? (int64_t) (p.off[a + 1] / G) : p.range.chunks();
int64_t c = 0;
while (c0 + c < end && p.range.mapped(c0 + c)) ++c;
slots = std::min<int64_t>(slots, (int64_t) ((uint64_t) c * G / p.per_slot[a]));
}
return slots;
}
bool pool_grow(ElasticPool& p, int64_t cells, const std::function<strata::core::VmmChunk()>& take) {
const uint64_t G = strata::core::vmm_granularity();
const int64_t slots = pool_slots(p, cells);
for (size_t a = 0; a < p.off.size(); ++a) {
const int64_t c0 = (int64_t) (p.off[a] / G), c1 = c0 + pool_chunks(p, a, slots);
std::vector<int64_t> fresh;
for (int64_t c = c0; c < c1; ++c)
if (!p.range.mapped(c)) fresh.push_back(c);
if (fresh.empty()) continue;
if (!p.range.map_range(c0, c1, take)) {
std::fprintf(stderr, "strata: the elastic K/V could not map %zu chunks (the driver has no VRAM left)\n",
fresh.size());
return false;
}
// what the chunk held before (another pool's cells, an expert) is not K/V: zeroed, as a new session is
for (const int64_t c : fresh)
if (cudaMemset(p.range.base() + (uint64_t) c * G, 0, (size_t) G) != cudaSuccess) {
std::fprintf(stderr, "strata: the elastic K/V could not clear a chunk: %s\n",
cudaGetErrorString(cudaGetLastError()));
return false;
}
}
return true;
}
} // namespace
void qsa_set_kv_elastic(bool enabled, int64_t init_cells) {
g_kv_elastic = enabled && strata::core::vmm_available();
if (init_cells > 0) g_kv_elastic_init = init_cells;
}
bool qsa_kv_elastic() { return g_kv_elastic; }
int64_t qsa_kv_elastic_cells() {
int64_t cells = std::numeric_limits<int64_t>::max();
for (const auto& p : g_pools) cells = std::min<int64_t>(cells, pool_slots_mapped(*p) * p->page_size);
return cells;
}
int64_t qsa_kv_elastic_need(int64_t cells) {
const uint64_t G = strata::core::vmm_granularity();
int64_t n = 0;
for (const auto& p : g_pools) {
const int64_t slots = pool_slots(*p, cells);
for (size_t a = 0; a < p->off.size(); ++a) {
const int64_t c0 = (int64_t) (p->off[a] / G), c1 = c0 + pool_chunks(*p, a, slots);
for (int64_t c = c0; c < c1; ++c) n += !p->range.mapped(c);
}
}
return n;
}
bool qsa_kv_elastic_grow(int64_t cells, const std::function<strata::core::VmmChunk()>& take) {
for (auto& p : g_pools)
if (!pool_grow(*p, cells, take)) return false;
return cudaDeviceSynchronize() == cudaSuccess;
}
int64_t qsa_kv_elastic_shrink(int64_t cells, const std::function<void(strata::core::VmmChunk)>& give) {
const uint64_t G = strata::core::vmm_granularity();
int64_t n = 0;
for (auto& p : g_pools) {
const int64_t slots = pool_slots(*p, cells);
for (size_t a = 0; a < p->off.size(); ++a) {
const int64_t c0 = (int64_t) (p->off[a] / G), c1 = c0 + pool_chunks(*p, a, slots);
const int64_t end = a + 1 < p->off.size() ? (int64_t) (p->off[a + 1] / G) : p->range.chunks();
for (int64_t c = c1; c < end; ++c)
if (const strata::core::VmmChunk h = p->range.unmap(c)) { give(h); ++n; }
}
}
return n;
}
uint64_t qsa_kv_elastic_mapped_bytes() {
uint64_t n = 0;
for (const auto& p : g_pools) n += (uint64_t) p->range.mapped_count() * strata::core::vmm_granularity();
return n;
}
uint64_t qsa_kv_elastic_full_bytes() {
uint64_t n = 0;
for (const auto& p : g_pools) n += (uint64_t) p->range.chunks() * strata::core::vmm_granularity();
return n;
}
namespace {
/// How one state holds its K/V: `mode` as in QsaState::kv_mode, `slots` VRAM pages of `pages` logical ones.
struct KvPlan {
int mode = 0;
@@ -560,8 +671,9 @@ uint64_t qsa_state_bytes(const ModelGeometry& g, int64_t max_cells, bool with_ro
const QsaShapes s = qsa_shapes(g);
const KvPlan p = kv_plan(s, max_cells, ring_cells);
uint64_t n = 0;
n += kv_pool_bytes(s, p.slots, g_kv_hybrid && ring_cells <= 0,
g_kv_int8 || g_kv_hybrid) + 4 * 16; // K/V pools (the VRAM slots)
if (!(g_kv_elastic && p.mode == 0)) // the elastic K/V's pools are in their own VMM range
n += kv_pool_bytes(s, p.slots, g_kv_hybrid && ring_cells <= 0,
g_kv_int8 || g_kv_hybrid) + 4 * 16; // K/V pools (the VRAM slots)
n += (uint64_t) p.pages * 4; // page_table
if (p.mode == 1) n += strata::kernels::kv_stream_map_bytes(p.slots) + 6 * 16; // the residency map
n += (uint64_t) (s.idx_block - 1) * s.idx_dim * 4; // tail
@@ -594,7 +706,43 @@ uint64_t qsa_state_init(const ModelGeometry& g, int64_t max_cells, void* base, Q
st.n_slots = p.slots;
const uint64_t rows = (uint64_t) p.slots * s.n_head_kv * s.page_size; // VRAM rows: the slots
const uint64_t q4_row = strata::kernels::kv_q4_bytes_per_head((int) s.head_dim);
if (st.kv_hybrid) {
st.kv_elastic = -1;
if (g_kv_elastic && p.mode == 0) {
// the elastic K/V: each array at a chunk boundary of the state's own range, the first cells mapped
const uint64_t slot_rows = (uint64_t) s.n_head_kv * s.page_size;
const uint64_t scale_row = (uint64_t) (s.head_dim / strata::kernels::KV_Q8_GROUP) * 2;
std::vector<uint64_t> per; // bytes per page slot of each array, in the order they are assigned below
if (st.kv_hybrid) per = {slot_rows * s.head_dim, slot_rows * scale_row, slot_rows * q4_row};
else if (st.kv_q4) per = {slot_rows * q4_row, slot_rows * q4_row};
else if (st.kv_int8) per = {slot_rows * s.head_dim, slot_rows * s.head_dim, slot_rows * scale_row, slot_rows * scale_row};
else per = {slot_rows * s.head_dim * 2, slot_rows * s.head_dim * 2};
auto pool = std::make_unique<ElasticPool>();
const uint64_t G = strata::core::vmm_granularity();
uint64_t at = 0;
for (const uint64_t b : per) {
pool->off.push_back(at);
at += ((uint64_t) p.slots * b + G - 1) / G * G;
}
pool->per_slot = per;
pool->n_slots = p.slots;
pool->page_size = s.page_size;
if (!pool->range.reserve(at) || !pool_grow(*pool, g_kv_elastic_init, [] { return (strata::core::VmmChunk) 0; })) {
std::fprintf(stderr, "strata: the elastic K/V could not reserve or map its pools\n");
return 0;
}
uint8_t* b = pool->range.base();
const uint64_t* o = pool->off.data();
if (st.kv_hybrid) { st.k_q = (int8_t*) (b + o[0]); st.k_scale = (uint16_t*) (b + o[1]); st.v_q4 = b + o[2]; }
else if (st.kv_q4) { st.k_q4 = b + o[0]; st.v_q4 = b + o[1]; }
else if (st.kv_int8) {
st.k_q = (int8_t*) (b + o[0]);
st.v_q = (int8_t*) (b + o[1]);
st.k_scale = (uint16_t*) (b + o[2]);
st.v_scale = (uint16_t*) (b + o[3]);
} else { st.k_pool = (uint16_t*) (b + o[0]); st.v_pool = (uint16_t*) (b + o[1]); }
st.kv_elastic = (int32_t) g_pools.size();
g_pools.push_back(std::move(pool));
} else if (st.kv_hybrid) {
st.k_q = c.take<int8_t>(rows * s.head_dim);
st.k_scale = c.take<uint16_t>(rows * (s.head_dim / strata::kernels::KV_Q8_GROUP));
st.v_q4 = c.take<uint8_t>(rows * q4_row);
@@ -715,7 +863,9 @@ uint64_t qsa_state_init(const ModelGeometry& g, int64_t max_cells, void* base, Q
void qsa_state_zero(const QsaState& st, const ModelGeometry& g, void* stream) {
const QsaShapes s = qsa_shapes(g);
cudaStream_t cs = (cudaStream_t) stream;
const size_t rows = (size_t) st.n_slots * s.n_head_kv * s.page_size;
// an elastic state zeroes what is mapped (the rest is zeroed when it is mapped)
const int64_t live_slots = st.kv_elastic >= 0 ? pool_slots_mapped(*g_pools[(size_t) st.kv_elastic]) : st.n_slots;
const size_t rows = (size_t) live_slots * s.n_head_kv * s.page_size;
if (st.kv_hybrid) {
cudaMemsetAsync(st.k_q, 0, rows * s.head_dim, cs);
cudaMemsetAsync(st.k_scale, 0, rows * (s.head_dim / strata::kernels::KV_Q8_GROUP) * 2, cs);
+157
View File
@@ -0,0 +1,157 @@
#include "strata/core/vmm.hpp"
#if !defined(STRATA_USE_HIP)
#include <cuda.h>
#include <cuda_runtime.h>
#include <mutex>
namespace strata::core {
namespace {
struct Api {
bool ok = false;
uint64_t gran = 0;
int dev = -1;
decltype(&cuMemAddressReserve) reserve = nullptr;
decltype(&cuMemAddressFree) free_va = nullptr;
decltype(&cuMemCreate) create = nullptr;
decltype(&cuMemRelease) release = nullptr;
decltype(&cuMemMap) map = nullptr;
decltype(&cuMemUnmap) unmap = nullptr;
decltype(&cuMemSetAccess) access = nullptr;
};
template <class F> bool resolve(const char* name, F& f) {
cudaDriverEntryPointQueryResult q{};
void* p = nullptr;
if (cudaGetDriverEntryPointByVersion(name, &p, 12000, cudaEnableDefault, &q) != cudaSuccess ||
q != cudaDriverEntryPointSuccess || p == nullptr)
return false;
f = (F) p;
return true;
}
// never destroyed: the K/V pools and the cache release their chunks from static destructors at exit
const Api& api() {
static Api& a = *new Api;
static std::once_flag once;
std::call_once(once, [] {
decltype(&cuDeviceGetAttribute) attr = nullptr;
decltype(&cuMemGetAllocationGranularity) granularity = nullptr;
if (cudaGetDevice(&a.dev) != cudaSuccess) return;
if (!resolve("cuDeviceGetAttribute", attr) || !resolve("cuMemGetAllocationGranularity", granularity) ||
!resolve("cuMemAddressReserve", a.reserve) || !resolve("cuMemAddressFree", a.free_va) ||
!resolve("cuMemCreate", a.create) || !resolve("cuMemRelease", a.release) || !resolve("cuMemMap", a.map) ||
!resolve("cuMemUnmap", a.unmap) || !resolve("cuMemSetAccess", a.access))
return;
int vmm = 0;
if (attr(&vmm, CU_DEVICE_ATTRIBUTE_VIRTUAL_MEMORY_MANAGEMENT_SUPPORTED, (CUdevice) a.dev) != CUDA_SUCCESS || !vmm)
return;
CUmemAllocationProp prop{};
prop.type = CU_MEM_ALLOCATION_TYPE_PINNED;
prop.location.type = CU_MEM_LOCATION_TYPE_DEVICE;
prop.location.id = a.dev;
size_t g = 0;
if (granularity(&g, &prop, CU_MEM_ALLOC_GRANULARITY_MINIMUM) != CUDA_SUCCESS || g == 0) return;
a.gran = g;
a.ok = true;
});
return a;
}
} // namespace
bool vmm_available() { return api().ok; }
uint64_t vmm_granularity() { return api().ok ? api().gran : 0; }
VmmChunk vmm_chunk_new() {
const Api& a = api();
if (!a.ok) return 0;
CUmemAllocationProp prop{};
prop.type = CU_MEM_ALLOCATION_TYPE_PINNED;
prop.location.type = CU_MEM_LOCATION_TYPE_DEVICE;
prop.location.id = a.dev;
CUmemGenericAllocationHandle h = 0;
if (a.create(&h, (size_t) a.gran, &prop, 0) != CUDA_SUCCESS) return 0;
return (VmmChunk) h;
}
void vmm_chunk_free(VmmChunk h) {
if (h != 0 && api().ok) api().release((CUmemGenericAllocationHandle) h);
}
bool VmmRange::reserve(uint64_t bytes) {
release();
const Api& a = api();
if (!a.ok || bytes == 0) return false;
const uint64_t n = (bytes + a.gran - 1) / a.gran;
CUdeviceptr p = 0;
if (a.reserve(&p, (size_t) (n * a.gran), 0, 0, 0) != CUDA_SUCCESS) return false;
base_ = (unsigned long long) p;
h_.assign((size_t) n, 0);
return true;
}
void VmmRange::release() {
if (base_ == 0) return;
const Api& a = api();
for (int64_t i = 0; i < chunks(); ++i) vmm_chunk_free(unmap(i));
a.free_va((CUdeviceptr) base_, (size_t) ((uint64_t) h_.size() * a.gran));
base_ = 0;
h_.clear();
}
int64_t VmmRange::mapped_count() const {
int64_t n = 0;
for (const VmmChunk h : h_) n += h != 0;
return n;
}
bool VmmRange::map_one(int64_t i, VmmChunk h) {
const Api& a = api();
if (a.map((CUdeviceptr) (base_ + (uint64_t) i * a.gran), (size_t) a.gran, 0, (CUmemGenericAllocationHandle) h, 0) !=
CUDA_SUCCESS)
return false;
h_[(size_t) i] = h;
return true;
}
bool VmmRange::set_access(int64_t lo, int64_t hi) {
if (hi <= lo) return true;
const Api& a = api();
CUmemAccessDesc d{};
d.location.type = CU_MEM_LOCATION_TYPE_DEVICE;
d.location.id = a.dev;
d.flags = CU_MEM_ACCESS_FLAGS_PROT_READWRITE;
return a.access((CUdeviceptr) (base_ + (uint64_t) lo * a.gran), (size_t) ((uint64_t) (hi - lo) * a.gran), &d, 1) ==
CUDA_SUCCESS;
}
VmmChunk VmmRange::unmap(int64_t i) {
if (!mapped(i)) return 0;
const Api& a = api();
const VmmChunk h = h_[(size_t) i];
if (a.unmap((CUdeviceptr) (base_ + (uint64_t) i * a.gran), (size_t) a.gran) != CUDA_SUCCESS) return 0;
h_[(size_t) i] = 0;
return h;
}
} // namespace strata::core
#else // HIP: no virtual memory here; the elastic K/V stays off
namespace strata::core {
bool vmm_available() { return false; }
uint64_t vmm_granularity() { return 0; }
VmmChunk vmm_chunk_new() { return 0; }
void vmm_chunk_free(VmmChunk) {}
bool VmmRange::reserve(uint64_t) { return false; }
void VmmRange::release() {}
int64_t VmmRange::mapped_count() const { return 0; }
bool VmmRange::map_one(int64_t, VmmChunk) { return false; }
bool VmmRange::set_access(int64_t, int64_t) { return false; }
VmmChunk VmmRange::unmap(int64_t) { return 0; }
} // namespace strata::core
#endif
+250
View File
@@ -374,6 +374,7 @@ struct Options {
bool ple_sync_submit = false; ///< A/B arm: submit reads on the token thread, no I/O worker
std::string kv = "fp16"; ///< plan v0.3 P7: KV storage, fp16 (default) or int8 (half the VRAM)
int64_t kv_resident = 0; ///< KV streaming: resident cells per QSA layer (0: all in VRAM)
bool kv_grow = false; ///< the elastic K/V (--kv-grow, STRATA_KV_GROW=1; kvg_ensure)
std::string dump_residual;
/// The head input, `bb.mixed`. It exists so the head can be SPLIT: steps 1-4 (the per-stream norm, the two
/// bf16 projections and the stream mean) recompute cheaply in Python, and only the 794 MB GEMV does not.
@@ -652,6 +653,10 @@ void usage() {
" --kv-resident N KV streaming: keep N cells of each QSA layer in VRAM (min 20480) and the\n"
" whole K/V in pinned RAM; the freed VRAM goes to expert slots. 0 (default):\n"
" all of it in VRAM. A context of N cells or fewer is not streamed\n"
" --kv-grow the K/V takes VRAM only for the cells the requests reach and the expert\n"
" cache holds the rest, giving slots back as the context grows (one GPU, with\n"
" --expert-profile; STRATA_KV_GROW=1/0 also). Default: the whole --max-context\n"
" allocated at start\n"
" --stream-token enqueue token work on the session stream (experimental)\n"
" --check-logits copy and check all logits in the stream-token path\n"
" --gr-fp32-activations experimental CUDA-oracle GR activation precision\n"
@@ -1546,6 +1551,8 @@ int main(int argc, char** argv) {
else if (a == "--ple-sync-submit") o.ple_sync_submit = true;
else if (a == "--kv") o.kv = next("--kv");
else if (a == "--kv-resident") o.kv_resident = std::atoll(next("--kv-resident"));
else if (a == "--kv-grow") o.kv_grow = true;
else if (a == "--no-kv-grow") o.kv_grow = false;
else if (a == "--stream-token") o.stream_token = true;
else if (a == "--check-logits") o.check_logits = true;
else if (a == "--gr-fp32-activations") o.gr_fp32_activations = true;
@@ -3214,6 +3221,20 @@ int main(int argc, char** argv) {
{
const strata::core::OnDevice on0(0);
const int64_t hi0 = multi_gpu ? split_at[0] : -1;
// the elastic K/V (--kv-grow, see kvg_ensure): one GPU, the whole K/V in VRAM (no streaming), a profiled cache
// that can give slots up, and every expert in RAM for the CPU to compute the ones it gives up
{
const char* ev = std::getenv("STRATA_KV_GROW");
bool remote = false;
for (const int r : o.expert_cache_remote) remote = remote || r > 0;
const bool asked = ev != nullptr && ev[0] != '\0' ? ev[0] != '0' : o.kv_grow;
const bool on = asked && !multi_gpu && o.kv_resident <= 0 &&
!o.expert_profile.empty() && !o.resident_cpu_experts && o.expert_cache != 0 && !remote &&
strata::core::vmm_available();
const char* iv = std::getenv("STRATA_KV_GROW_INIT");
strata::core::qsa_set_kv_elastic(on, iv != nullptr && std::atoll(iv) > 0 ? std::atoll(iv) : 16384);
strata::core::ExpertCache::set_vmm(on);
}
if (cudaMalloc(&sbuf, strata::core::session_bytes(g, o.max_context, K, 0, hi0)) != cudaSuccess) {
std::fprintf(stderr, "strata generate: session state allocation failed\n");
return 1;
@@ -4983,6 +5004,190 @@ int main(int argc, char** argv) {
}
return 0;
};
// ---- THE ELASTIC K/V (--kv-grow; vmm.hpp). Allocated for the whole --max-context up front, the K/V of a 262K
// context (3.35 GiB with the drafter's at int8) takes VRAM the expert cache could hold more experts in. Now the K/V pools hold physical memory only for the cells
// the requests reach. When a request needs more, slots just below the prompt path's loan give up their experts
// (the CPU computes those from RAM, like any miss) and their whole chunks are mapped into the K/V; a later short
// request hands them back and the slots are refilled with the profile's hottest experts. Neither side's
// addresses move, so every captured graph stays valid. The context is never smaller: --max-context cells always
// fit, the cache simply holds fewer experts while a long one is live.
struct KvGrow {
bool on = false;
int64_t top = 0, lo = 0; // slots [lo, top) hold no expert; their whole chunks may be with the K/V
int64_t floor = 128; // the cache keeps at least these slots
int64_t step = 8192; // the K/V grows in whole steps of cells
int64_t cells = 0; // what every K/V pool holds now
std::vector<strata::core::VmmChunk> spare; // out of the cache, not (yet) in the K/V
int64_t grows = 0, trims = 0, fresh = 0, evicted = 0, refilled = 0;
} kvg;
auto kvg_start = [&](int64_t top) {
kvg.on = strata::core::qsa_kv_elastic() && xcache.vmm_range() != nullptr && d_res != nullptr &&
!host_res.empty() && srcp != nullptr && top > kvg.floor;
if (!kvg.on) return;
kvg.top = kvg.lo = top;
kvg.cells = strata::core::qsa_kv_elastic_cells();
if (const char* v = std::getenv("STRATA_KV_GROW_STEP"); v != nullptr && std::atoll(v) > 0) kvg.step = std::atoll(v);
// tests: the cache keeps this many slots (its size: the K/V grows into new VRAM only)
if (const char* v = std::getenv("STRATA_KV_GROW_FLOOR"); v != nullptr && std::atoll(v) > 0) kvg.floor = std::atoll(v);
std::fprintf(stderr, "strata generate: elastic K/V: %lld of %lld cells in VRAM (%.2f of %.2f GiB); the expert "
"cache (%lld slots) gives the K/V room below slot %lld as the context grows\n",
(long long) kvg.cells, (long long) o.max_context,
(double) strata::core::qsa_kv_elastic_mapped_bytes() / 1073741824.0,
(double) strata::core::qsa_kv_elastic_full_bytes() / 1073741824.0, (long long) xcache.slots(),
(long long) top);
};
// Room for `cells` cells (rounded up to a step). `quiesce` must leave nothing running on the device and land
// the adaptive tier's swaps (a swap in flight could still be writing a slot given up here).
auto kvg_ensure = [&](int64_t cells, const std::function<void()>& quiesce) -> bool {
if (!kvg.on || cells <= kvg.cells) return true;
const int64_t target = std::min<int64_t>(o.max_context, (cells + kvg.step - 1) / kvg.step * kvg.step);
const int64_t need = strata::core::qsa_kv_elastic_need(target);
if (need == 0) { kvg.cells = strata::core::qsa_kv_elastic_cells(); return true; }
quiesce();
strata::core::VmmRange& r = *xcache.vmm_range();
const uint64_t G = strata::core::vmm_granularity();
std::vector<int32_t> owner; // slot -> residency index
// The slots given up are the ones just below the prompt path's loan, and the loan is most of the cache: they
// hold experts of middling heat. So an expert there that is hotter than the coldest one in the loan region
// moves into that one's slot (a device copy), and the coldest is given up instead - the cache then holds what
// a smaller cache would. Heat: the adaptive tier's routing counts, then the profile's rank.
std::vector<int32_t> rank;
std::vector<std::pair<float, int32_t>> cold; // the loan region's residents, hottest first
auto heat = [&](int32_t i) -> float {
const float u = drive.d.usage.empty() ? 0.0f : drive.d.usage[(size_t) i];
return u * 1048576.0f - (float) rank[(size_t) i];
};
const auto& lay = strata::kernels::cpu::expert_layout();
int64_t gave = 0, moved = 0;
auto freeable = [&]() -> int64_t { // mapped chunks wholly inside [lo, top): a chunk a live slot shares stays
const int64_t c0 = (int64_t) ((xcache.slot_offset(kvg.lo) + G - 1) / G);
const int64_t c1 = (int64_t) (xcache.slot_offset(kvg.top) / G);
int64_t k = 0;
for (int64_t c = c0; c < c1; ++c) k += r.mapped(c) ? 1 : 0;
return k;
};
while ((int64_t) kvg.spare.size() + freeable() < need && kvg.lo > kvg.floor) {
if (owner.empty()) {
owner.assign((size_t) xcache.slots(), -1);
for (size_t i = 0; i < host_res.size(); ++i)
if (host_res[i] >= 0 && host_res[i] < xcache.slots()) owner[(size_t) host_res[i]] = (int32_t) i;
rank.assign(host_res.size(), (int32_t) profile.size());
for (size_t r = 0; r < profile.size(); ++r)
rank[(size_t) profile[r].first * (size_t) g.n_expert + (size_t) profile[r].second] = (int32_t) r;
for (size_t i = 0; i < host_res.size(); ++i)
if (host_res[i] >= kvg.top) cold.emplace_back(heat((int32_t) i), (int32_t) i);
std::sort(cold.begin(), cold.end(), [](const auto& a, const auto& b) { return a.first > b.first; });
}
--kvg.lo;
++gave;
if (const int32_t oi = owner[(size_t) kvg.lo]; oi >= 0) {
const int64_t layer = oi / g.n_expert;
int32_t vi = -1;
if (!cold.empty() && cold.back().first < heat(oi)) {
vi = cold.back().second;
const int32_t vs = host_res[(size_t) vi];
if (xcache.slot_offset(vs + 1) - xcache.slot_offset(vs) < lay.blob_bytes(layer) ||
cudaMemcpy(xcache.device_slot(vs), xcache.device_slot((int32_t) kvg.lo),
(size_t) lay.blob_bytes(layer), cudaMemcpyDeviceToDevice) != cudaSuccess)
vi = -1;
else {
cold.pop_back();
host_res[(size_t) oi] = vs;
host_res[(size_t) vi] = strata::core::kNotResident;
++moved;
}
}
if (vi < 0) host_res[(size_t) oi] = strata::core::kNotResident;
++kvg.evicted;
}
}
// a device-to-device cudaMemcpy does not wait for the copy: the moves still read the slots given up, and a
// chunk unmapped under a copy faults it (the error then sticks to whatever runs next)
if (gave > 0 && cudaDeviceSynchronize() != cudaSuccess) {
std::fprintf(stderr, "strata: moving experts for the K/V failed: %s\n", cudaGetErrorString(cudaGetLastError()));
return false;
}
{
const int64_t c0 = (int64_t) ((xcache.slot_offset(kvg.lo) + G - 1) / G);
const int64_t c1 = (int64_t) (xcache.slot_offset(kvg.top) / G);
for (int64_t c = c0; c < c1; ++c)
if (r.mapped(c))
if (const strata::core::VmmChunk h = r.unmap(c)) kvg.spare.push_back(h);
}
if (gave > 0) cudaMemcpy(d_res, host_res.data(), host_res.size() * sizeof(int32_t), cudaMemcpyHostToDevice);
int64_t fresh = 0;
const bool ok = strata::core::qsa_kv_elastic_grow(target, [&]() -> strata::core::VmmChunk {
if (kvg.spare.empty()) { ++fresh; return 0; } // the cache is at its floor: new memory
const strata::core::VmmChunk h = kvg.spare.back();
kvg.spare.pop_back();
return h;
});
kvg.fresh += fresh;
kvg.cells = strata::core::qsa_kv_elastic_cells();
++kvg.grows;
std::fprintf(stderr, "strata: K/V grown to %lld cells (%.2f GiB); the expert cache gave %lld slots for it, "
"%lld hotter experts moved to colder ones' slots (%lld of %lld slots hold experts)%s\n",
(long long) kvg.cells, (double) strata::core::qsa_kv_elastic_mapped_bytes() / 1073741824.0,
(long long) gave, (long long) moved, (long long) (kvg.lo + (xcache.slots() - kvg.top)),
(long long) xcache.slots(),
fresh > 0 ? " - and new VRAM, the cache being at its floor" : "");
if (!ok)
std::fprintf(stderr, "strata: the K/V could not grow to %lld cells (%s)\n", (long long) target,
cudaGetErrorString(cudaGetLastError()));
return ok;
};
// A request that needs far fewer cells than the K/V holds gives the rest back: the slots refill with the
// profile's hottest experts the GPU does not hold. Run on a quiet device (as kvg_ensure's `quiesce`).
auto kvg_trim = [&](int64_t cells) {
if (!kvg.on) return;
const int64_t target = std::max<int64_t>(kvg.step, (cells + kvg.step - 1) / kvg.step * kvg.step);
if (kvg.cells < target + 2 * kvg.step || kvg.lo >= kvg.top) return;
strata::core::qsa_kv_elastic_shrink(target, [&](strata::core::VmmChunk h) { kvg.spare.push_back(h); });
kvg.cells = strata::core::qsa_kv_elastic_cells();
strata::core::VmmRange& r = *xcache.vmm_range();
const uint64_t G = strata::core::vmm_granularity();
const int64_t c1 = (int64_t) (xcache.slot_offset(kvg.top) / G);
for (int64_t c = (int64_t) (xcache.slot_offset(kvg.lo) / G); c < c1 && !kvg.spare.empty(); ++c) {
if (r.mapped(c)) continue;
const strata::core::VmmChunk h = kvg.spare.back();
kvg.spare.pop_back();
if (!r.map_range(c, c + 1, [h] { return h; })) break; // map_range frees h when it fails
}
const int64_t lo0 = kvg.lo;
while (kvg.lo < kvg.top) { // a slot whose chunks are all mapped again holds an expert again
const int64_t a = (int64_t) (xcache.slot_offset(kvg.lo) / G);
const int64_t b = (int64_t) ((xcache.slot_offset(kvg.lo + 1) + G - 1) / G);
bool all = true;
for (int64_t c = a; c < b && all; ++c) all = r.mapped(c);
if (!all) break;
++kvg.lo;
}
const auto& lay = strata::kernels::cpu::expert_layout();
size_t pi = 0;
for (int64_t s = lo0; s < kvg.lo; ++s) {
const uint64_t room = xcache.slot_offset(s + 1) - xcache.slot_offset(s);
for (; pi < profile.size(); ++pi) {
const int32_t l = profile[pi].first, e = profile[pi].second;
const size_t i = (size_t) l * (size_t) g.n_expert + (size_t) e;
if (host_res[i] >= 0 || lay.blob_bytes(l) > room) continue;
const uint8_t* b = srcp->blob(l, e);
if (b == nullptr || cudaMemcpy(xcache.device_slot((int32_t) s), b, (size_t) lay.blob_bytes(l),
cudaMemcpyHostToDevice) != cudaSuccess)
continue;
host_res[i] = (int32_t) s;
++kvg.refilled;
++pi;
break;
}
}
cudaMemcpy(d_res, host_res.data(), host_res.size() * sizeof(int32_t), cudaMemcpyHostToDevice);
cudaDeviceSynchronize();
for (const strata::core::VmmChunk h : kvg.spare) strata::core::vmm_chunk_free(h); // new ones, if any
kvg.spare.clear();
++kvg.trims;
std::fprintf(stderr, "strata: K/V trimmed to %lld cells; %lld slots back to the expert cache, refilled from "
"the profile\n", (long long) kvg.cells, (long long) (kvg.lo - lo0));
};
// ---- the resident RAM mode (--resident-experts / --resident-cpu-experts): the experts the GPU cache does not
// hold are copied from experts.bin into RAM once, so no decode or prompt step reads the file (the plain mmap
// mode reads them through the OS file cache, which a small-RAM PC keeps giving back to the SSD). Built here,
@@ -5541,6 +5746,7 @@ int main(int argc, char** argv) {
}
}
}
kvg_start(borrow != nullptr ? (int64_t) lend_first : xcache.slots());
// the penalty-history buffer: one row per verify-window row (`penalty_rows`), each the last
// `penalty_last_n` tokens that row's pick follows, -1 padded in front. Allocated once at the cap for
// the widest window; a request without penalties gets a null buffer and takes the byte-for-byte
@@ -7451,6 +7657,14 @@ int main(int argc, char** argv) {
std::printf("ERR %s\n", err.c_str());
return 1;
}
auto kv_quiesce = [&] { cudaDeviceSynchronize(); apply_pending(true); };
if (kvg.on) { // the elastic K/V: this prompt's cells (it gives back what it does not need below)
if (!kvg_ensure(n + 256, kv_quiesce)) {
std::printf("ERR the K/V cannot grow to this prompt: no VRAM is left\n");
std::fflush(stdout);
continue;
}
}
int64_t resume = 0;
bool from_live = false;
if (o.prompt_cache > 0 && want_cvec == cvec_cached) {
@@ -7553,6 +7767,11 @@ int main(int argc, char** argv) {
std::chrono::duration<double, std::milli>(Clock::now() - t0).count());
}
}
// the elastic K/V: a parked conversation is restored whole, and it may be longer than this prompt
if (incoming && !kvg_ensure((int64_t) incoming->live.ids.size() + 256, kv_quiesce)) {
std::printf("ERR the K/V cannot grow to the parked conversation: no VRAM is left\n");
return 1;
}
if (incoming) {
const auto t0 = Clock::now();
if (strata::core::conversation_snapshot_restore(*incoming, ss, g,
@@ -7624,6 +7843,12 @@ int main(int argc, char** argv) {
return (int64_t) c.ids.size() > resume || !starts_with(c.ids, c.imgs);
}), checks.end());
live_ok = false; // until this request has finished, the session is in between
// the elastic K/V: the outgoing session is parked and this request rewrites every cell from `resume` on,
// so cells past this prompt's are no longer anyone's - far more than it needs go back to the cache
if (kvg.on) {
kv_quiesce();
kvg_trim(n + 256);
}
int64_t reread_to = -1; // STRATA_CKPT_REREAD only: read [0, reread_to) again instead of restoring
if (resume == 0) {
strata::core::session_zero(ss, g, nullptr, main_cs);
@@ -8913,6 +9138,12 @@ int main(int argc, char** argv) {
cudaMemcpy(d_hist, hist_stage.data(), (size_t) T * (size_t) hist_n * sizeof(int32_t),
cudaMemcpyHostToDevice);
}
// the elastic K/V: the window's cells and the drafter's beyond them
if (kvg.on && p + T + 64 > kvg.cells &&
!kvg_ensure(p + T + 64, [&] { cudaDeviceSynchronize(); apply_pending(true); })) {
std::printf("ERR the K/V cannot grow: no VRAM is left\n");
return 1;
}
tr("window", p, T);
const Clock::time_point tw0 = Clock::now();
if (!ver.run(T, window.data(), p, win_pool_fn, win_pool_user, outv.data(), err) || drive.d.failed) {
@@ -9306,6 +9537,7 @@ int main(int argc, char** argv) {
int64_t pos_start = 0;
int64_t spec_pos = 0; // plan v0.3 P6: where the speculative loop starts (0 = not used)
strata::prefill::Prefill prefill;
bool kvg_started = false; // the elastic K/V took this run's cells
double prefill_batched_ms = 0;
std::FILE* final_r = o.dump_final_r.empty() ? nullptr : std::fopen(o.dump_final_r.c_str(), "wb");
std::vector<float> final_r_host(final_r ? (size_t) (g.hc * g.n_embd) : 0);
@@ -9333,6 +9565,10 @@ int main(int argc, char** argv) {
const int64_t blob = (int64_t) strata::kernels::cpu::expert_layout().max_blob;
if (k > 0) { // the lent slots are refilled after the prompt
const int32_t first = (int32_t) (xcache.slots() - k);
// the elastic K/V first: its hot experts move into slots of the loan, which are refilled after it
kvg_started = true;
kvg_start(first);
if (!kvg_ensure(n_prompt + o.max_new + 64, [] { cudaDeviceSynchronize(); })) return 1;
for (size_t i = 0; i < host_res.size(); ++i)
if (host_res[i] >= first) {
lent.emplace_back((int32_t) i, host_res[i]);
@@ -9367,6 +9603,11 @@ int main(int argc, char** argv) {
return e.empty() && mtp.prefill(R_rows, nxt.data(), T, p0, e);
};
}
if (!kvg_started) { // the elastic K/V: every cell this run can reach (no loan)
kvg_started = true;
kvg_start(xcache.slots());
if (!kvg_ensure(n_prompt + o.max_new + 64, [] { cudaDeviceSynchronize(); })) return 1;
}
const Clock::time_point tp0 = Clock::now();
if (!prefill.run(o.tokens.data(), n_batched, 0, err)) {
std::fprintf(stderr, "strata generate: %s\n", err.c_str());
@@ -9412,6 +9653,11 @@ int main(int argc, char** argv) {
(long long) ps.experts_dma, ps.ms_experts_host, (long long) ps.experts_resident, ps.ms_ple);
}
if (!kvg_started) { // the elastic K/V of a prompt that was not read in batches
kvg_started = true;
kvg_start(xcache.slots());
if (!kvg_ensure(n_prompt + o.max_new + 64, [] { cudaDeviceSynchronize(); })) return 1;
}
for (int64_t pos = pos_start;; ++pos) {
// plan v0.3 P6: a native pack's last prompt token is the first verify window (T = 1)
if (native_pack) { spec_pos = pos; break; }
@@ -10188,6 +10434,10 @@ int main(int argc, char** argv) {
? (double) xcache.resident() / (double) xcache.slots()
: 0.0));
}
if (kvg.on)
std::printf("%-24s %lld cells in VRAM, %lld grows, %lld trims, %lld experts given up, %lld refilled\n",
" elastic K/V", (long long) kvg.cells, (long long) kvg.grows, (long long) kvg.trims,
(long long) kvg.evicted, (long long) kvg.refilled);
if (tgraph.captured && tgraph.calls > 0) {
const double per = (double) tgraph.calls;
std::printf("%-24s wait for rings %.3f pool %.3f ms/token (%lld flushes over %lld positions)\n",
+62
View File
@@ -0,0 +1,62 @@
// The elastic K/V's VMM ranges (vmm.hpp): chunks map readable and writable, a chunk unmapped from one range and mapped
// into another keeps its bytes (what the expert cache hands the K/V), and a range releases what it holds.
#include "strata/core/vmm.hpp"
#include <cuda_runtime.h>
#include <cstdio>
#include <vector>
using strata::core::VmmChunk;
using strata::core::VmmRange;
static int fails = 0;
#define CHECK(c) do { if (!(c)) { std::fprintf(stderr, "FAIL %s:%d: %s\n", __FILE__, __LINE__, #c); ++fails; } } while (0)
int main() {
if (cudaFree(nullptr) != cudaSuccess || !strata::core::vmm_available()) {
std::printf("vmm_test: no CUDA device with virtual memory - skipped\n");
return 0;
}
const uint64_t G = strata::core::vmm_granularity();
CHECK(G >= 4096);
VmmRange a, b;
CHECK(a.reserve(8 * G + 1)); // rounds up
CHECK(a.chunks() == 9);
CHECK(b.reserve(4 * G));
CHECK(a.mapped_count() == 0);
CHECK(a.map_range(0, 6, [] { return (VmmChunk) 0; }));
CHECK(a.mapped_count() == 6 && a.mapped(5) && !a.mapped(6));
std::vector<uint8_t> h(6 * G), back(6 * G);
for (size_t i = 0; i < h.size(); ++i) h[i] = (uint8_t) (i * 2654435761u >> 13);
CHECK(cudaMemcpy(a.base(), h.data(), h.size(), cudaMemcpyHostToDevice) == cudaSuccess);
// chunks 4 and 5 move to b's chunks 1 and 0
const VmmChunk c4 = a.unmap(4), c5 = a.unmap(5);
CHECK(c4 != 0 && c5 != 0 && !a.mapped(4) && a.unmap(4) == 0);
std::vector<VmmChunk> give = {c4, c5}; // map_range takes them from the back: chunk 0 <- c5, chunk 1 <- c4
CHECK(b.map_range(0, 2, [&] { VmmChunk x = give.back(); give.pop_back(); return x; }));
CHECK(cudaMemcpy(back.data(), b.base(), G, cudaMemcpyDeviceToHost) == cudaSuccess);
bool same = true;
for (uint64_t i = 0; i < G; ++i) same = same && back[i] == h[5 * G + i];
CHECK(same);
CHECK(cudaMemcpy(back.data(), b.base() + G, G, cudaMemcpyDeviceToHost) == cudaSuccess);
same = true;
for (uint64_t i = 0; i < G; ++i) same = same && back[i] == h[4 * G + i];
CHECK(same);
// a's first chunks are untouched, and map_range fills a hole with new memory, skipping mapped chunks
CHECK(cudaMemcpy(back.data(), a.base(), 4 * G, cudaMemcpyDeviceToHost) == cudaSuccess);
same = true;
for (uint64_t i = 0; i < 4 * G; ++i) same = same && back[i] == h[i];
CHECK(same);
CHECK(a.map_range(3, 7, [] { return (VmmChunk) 0; }) && a.mapped_count() == 7);
CHECK(cudaMemset(a.base() + 4 * G, 7, 3 * G) == cudaSuccess && cudaDeviceSynchronize() == cudaSuccess);
size_t f0 = 0, f1 = 0, t = 0;
cudaMemGetInfo(&f0, &t);
a.release();
b.release();
cudaMemGetInfo(&f1, &t);
CHECK(f1 >= f0 + 8 * G); // 7 + 2 chunks went back (the driver may round)
CHECK(cudaGetLastError() == cudaSuccess);
std::printf("vmm_test: %s\n", fails ? "FAILED" : "ok");
return fails ? 1 : 0;
}