mirror of
https://github.com/Niko1221/Strata.git
synced 2026-12-05 07:48:45 +00:00
ling32: scratch regrow, the prefill scratch exists only while a prompt is prefilled and the pool regrows for decode (tier B / C, opt-in)
- engine: every row-dependent buffer (activations, logits, KDA chunk scratch, MLA workspaces, grouped-MoE work, lookahead snapshots) lives in a ScratchSet; a small `dec` set (decode_rows = 64 rows) is always resident, a `big` set of the prompt chunk is allocated by the first prefill-sized forward (the existing allocation retry makes the tier store release chunks of pool slots when the card has no room) and freed by the first decode-sized forward, which also frees the span rows and tells the store to take the memory back - store: ExpertProvider::grow_bytes / ExpertStore::grow_bytes re-allocate released chunks of small dynamic slots (empty, lowest chunk first, keeping 192 MiB free: STRATA_L32_REGROW_RESERVE_MB) - planner / main: --regrow on|off (or STRATA_L32_REGROW=1; default off), --decode-rows N; with regrow the plan counts decode_rows rows of scratch instead of the chunk (tier A and runs without lazy KV keep the full chunk); a speculative request (MTP, not plain) keeps its sets and does not regrow - test: ling32_regrow_regress (same dump and ids with regrow on and off: tier B, two prompts, injected allocation failure, tier C, MTP speculation; STRATA_L32_KV_FORCE_RELEASE=1 makes the big set take one chunk even where the card has room)
This commit is contained in:
1 parent
99a6309aa3
commit
418f142af4
7 files changed
+304
-51
No files matched your search
@@ -210,6 +210,8 @@ if(LING32_CUDA OR LING32_HIP)
|
||||
set_tests_properties(ling32_mtp_auto_regress PROPERTIES FIXTURES_REQUIRED ling32_wide_mtp TIMEOUT 600)
|
||||
add_test(NAME ling32_kv_grow_regress COMMAND ${Python3_EXECUTABLE} -I ${_tests_dir}/ling32_kv_grow_test.py $<TARGET_FILE:strata-ling32> ${_wide} ${_wide_mtp} ${CMAKE_BINARY_DIR}/kv_grow_work)
|
||||
set_tests_properties(ling32_kv_grow_regress PROPERTIES FIXTURES_REQUIRED ling32_wide_mtp TIMEOUT 900)
|
||||
add_test(NAME ling32_regrow_regress COMMAND ${Python3_EXECUTABLE} -I ${_tests_dir}/ling32_regrow_test.py $<TARGET_FILE:strata-ling32> ${_wide} ${_wide_mtp} ${CMAKE_BINARY_DIR}/regrow_work)
|
||||
set_tests_properties(ling32_regrow_regress PROPERTIES FIXTURES_REQUIRED ling32_wide_mtp TIMEOUT 900)
|
||||
endif()
|
||||
if(Python3_FOUND)
|
||||
set_tests_properties(ling32_kernel_test ling32_model_test PROPERTIES FIXTURES_REQUIRED ling32_fixture)
|
||||
|
||||
@@ -408,20 +408,143 @@ struct Ling32Engine::StageCtx {
|
||||
|
||||
StageCtx(Ling32Engine& e, GpuModel& mm, int dev, int lf, int ll) : E(e), m(mm), c(mm.cfg), device(dev), layer_first(lf), layer_last(ll), has_embed(lf == 0), has_head(ll == mm.cfg.n_layers) {}
|
||||
|
||||
template <class T> bool alloc(T*& p, size_t n, std::string& err) {
|
||||
if (std::getenv("STRATA_L32_TRACE")) std::fprintf(stderr, "ling32: alloc %.1f MiB\n", n * sizeof(T) / 1048576.0);
|
||||
// ---- scratch regrow (EngineOptions::scratch_regrow, tier B / C with lazy KV). Every buffer whose size follows the number of rows lives in a ScratchSet. The `dec` set (decode_rows rows) is always resident;
|
||||
// the `big` set (rows of the prompt chunk, up to max_tokens) exists only while a prompt is prefilled: a decode-sized forward frees it and the store regrows its dynamic pool into the memory
|
||||
// (trim_scratch), the next prompt allocates it again (ensure_rows; a failed allocation makes the store release pool chunks, see alloc_bytes). The members x, h, ... always mirror the ACTIVE set (scr_bind).
|
||||
#define L32_SCR_PTRS(X) X(x) X(h) X(cur) X(proj) X(qn) X(kn) X(vc) X(ko) X(beta) X(q) X(ckv) X(qabs) X(ctx) X(av) X(gate) X(g) X(u) X(a) X(rlog) X(rw) X(gu) X(ye) X(logits) X(ysh) X(kscr) \
|
||||
X(ridx) X(ids) X(actp) X(q8[0]) X(q8[1]) X(fa[0]) X(fa[1]) X(mla_ws) X(mla_exp_ws) X(hx_ws) X(la_u) X(la_logits) X(la_f) X(la_q8) X(snap[0]) X(snap[1]) X(snap[2]) X(snap[3]) X(snap[4]) X(snap[5])
|
||||
struct ScratchSet {
|
||||
void* p[48] = {};
|
||||
int rows = 0, lrows = 0;
|
||||
size_t kscr_floats = 0, mla_ws_bytes = 0, mla_exp_ws_bytes = 0, hx_ws_bytes = 0;
|
||||
gpu::MoeTcWork tcw;
|
||||
};
|
||||
ScratchSet dec_set, big_set;
|
||||
int rows_cur = 0; // rows of the active set
|
||||
int lrows_full = 0; // the logits rows the options ask for at max_tokens rows (the active set may hold fewer)
|
||||
bool regrow_on = false; // two sets in use
|
||||
bool big_valid = false; // the big set is allocated
|
||||
void scr_save(ScratchSet& s) const {
|
||||
static_assert(kRing == 6, "L32_SCR_PTRS lists the six snapshot buffers");
|
||||
int i = 0;
|
||||
#define X(m) s.p[i++] = static_cast<void*>(m);
|
||||
L32_SCR_PTRS(X)
|
||||
#undef X
|
||||
s.rows = rows_cur; s.lrows = lrows; s.kscr_floats = kscr_floats; s.mla_ws_bytes = mla_ws_bytes; s.mla_exp_ws_bytes = mla_exp_ws_bytes; s.hx_ws_bytes = hx_ws_bytes; s.tcw = tcw;
|
||||
}
|
||||
void scr_bind(const ScratchSet& s) {
|
||||
int i = 0;
|
||||
#define X(m) m = static_cast<std::remove_reference_t<decltype(m)>>(s.p[i++]);
|
||||
L32_SCR_PTRS(X)
|
||||
#undef X
|
||||
rows_cur = s.rows; lrows = s.lrows; kscr_floats = s.kscr_floats; mla_ws_bytes = s.mla_ws_bytes; mla_exp_ws_bytes = s.mla_exp_ws_bytes; hx_ws_bytes = s.hx_ws_bytes; tcw = s.tcw;
|
||||
}
|
||||
void scr_free(ScratchSet& s) {
|
||||
for (void*& q : s.p) if (q) { cudaFree(q); q = nullptr; }
|
||||
gpu::moe_tc_free(s.tcw);
|
||||
s = ScratchSet{};
|
||||
}
|
||||
// a new set of `rows` rows; the active members are left as they were
|
||||
bool scratch_make(int rows, ScratchSet& out, std::string& err) {
|
||||
ScratchSet prev;
|
||||
scr_save(prev);
|
||||
scr_bind(ScratchSet{});
|
||||
const bool ok = scratch_body(static_cast<size_t>(rows), err);
|
||||
if (ok) scr_save(out);
|
||||
else { ScratchSet part; scr_save(part); scr_free(part); }
|
||||
scr_bind(prev);
|
||||
return ok;
|
||||
}
|
||||
void sync_streams() { cudaStreamSynchronize(st); cudaStreamSynchronize(la); cudaStreamSynchronize(st2); }
|
||||
// the active set must hold `n` rows (a prefill-sized forward): allocate / enlarge the big set
|
||||
bool ensure_rows(int n, std::string& err) {
|
||||
if (!regrow_on || n <= rows_cur) return true;
|
||||
const int want = std::min(Nmax, ((n + 127) / 128) * 128);
|
||||
sync_streams();
|
||||
static const bool force_release = [] { const char* f = std::getenv("STRATA_L32_KV_FORCE_RELEASE"); return f && f[0] == '1'; }(); // tests: the big set always takes at least one chunk of pool slots
|
||||
if (force_release && E.provider_) E.provider_->release_bytes(1);
|
||||
if (big_valid) { scr_bind(dec_set); scr_free(big_set); big_valid = false; }
|
||||
if (!scratch_make(want, big_set, err)) return false;
|
||||
scr_bind(big_set);
|
||||
big_valid = true;
|
||||
return true;
|
||||
}
|
||||
// a decode-sized forward is coming: back to the small set, free the big one and the span rows, let the store take the memory
|
||||
void trim_scratch() {
|
||||
if (!regrow_on || !big_valid) return;
|
||||
sync_streams();
|
||||
scr_bind(dec_set);
|
||||
scr_free(big_set);
|
||||
big_valid = false;
|
||||
if (xs) { cudaFree(xs); xs = nullptr; }
|
||||
if (ids_sp) { cudaFree(ids_sp); ids_sp = nullptr; }
|
||||
xs_rows = 0;
|
||||
h_ready = false;
|
||||
if (E.provider_) E.provider_->grow_bytes(~static_cast<size_t>(0));
|
||||
}
|
||||
|
||||
// one cudaMalloc; with a tier store attached (lazy KV / scratch regrow) a failure makes the store release whole chunks of pool slots and the allocation is tried again
|
||||
bool alloc_bytes(void** pp, size_t bytes, const char* what, std::string& err) {
|
||||
if (std::getenv("STRATA_L32_TRACE")) std::fprintf(stderr, "ling32: alloc %.1f MiB\n", bytes / 1048576.0);
|
||||
static const bool inject = [] { const char* f = std::getenv("STRATA_L32_LAZY_OOM"); return f && f[0] == '1'; }(); // test hook: the first allocation after the store is attached fails once, so the release-and-retry path runs
|
||||
cudaError_t e = cudaSuccess;
|
||||
if (inject && E.provider_ && E.opt.kv_init_ctx > 0 && !oom_injected) { oom_injected = true; e = cudaErrorMemoryAllocation; }
|
||||
else e = cudaMalloc(reinterpret_cast<void**>(&p), n * sizeof(T));
|
||||
// lazy latent KV: the tier store gave all the room the cache did not need to its pool; a later allocation (the prompt span's buffers, ...) takes chunks of pool slots back instead of failing
|
||||
else e = cudaMalloc(pp, bytes);
|
||||
// lazy latent KV: the tier store gave all the room the cache did not need to its pool; a later allocation (the prompt span's buffers, the prefill scratch, ...) takes chunks of pool slots back instead of failing
|
||||
for (int t = 0; e == cudaErrorMemoryAllocation && E.provider_ && E.opt.kv_init_ctx > 0 && t < 64; ++t) {
|
||||
(void)cudaGetLastError();
|
||||
if (E.provider_->release_bytes(n * sizeof(T)) == 0) break;
|
||||
e = cudaMalloc(reinterpret_cast<void**>(&p), n * sizeof(T));
|
||||
if (E.provider_->release_bytes(bytes) == 0) break;
|
||||
e = cudaMalloc(pp, bytes);
|
||||
}
|
||||
return cu(e, "cudaMalloc", err);
|
||||
return cu(e, what, err);
|
||||
}
|
||||
template <class T> bool alloc(T*& p, size_t n, std::string& err) { return alloc_bytes(reinterpret_cast<void**>(&p), n * sizeof(T), "cudaMalloc", err); }
|
||||
|
||||
// the row-dependent buffers of N rows (into the members; scratch_make / init save them into a set)
|
||||
bool scratch_body(size_t N, std::string& err) {
|
||||
const EngineOptions& o = E.opt;
|
||||
rows_cur = static_cast<int>(N);
|
||||
lrows = o.logits_rows > 0 ? std::min<int>(o.logits_rows, static_cast<int>(N)) : static_cast<int>(N);
|
||||
bool ok = alloc(x, N * D, err) && alloc(h, N * D, err) && alloc(cur, N * D, err) && alloc(proj, N * 5 * C, err) && alloc(qn, N * C, err) && alloc(kn, N * C, err) &&
|
||||
alloc(vc, N * C, err) && alloc(ko, N * C, err) && alloc(beta, N * c.H, err) && alloc(q, N * c.mla_q_dim(), err) && alloc(ckv, N * c.mla_latent_vals(), err) &&
|
||||
alloc(qabs, N * c.H * c.kv_lora, err) && alloc(ctx, N * c.H * c.kv_lora, err) && alloc(av, N * c.H * c.vhead, err) && alloc(gate, N * c.H, err) &&
|
||||
alloc(g, N * std::max(c.I_dense, c.I_shared), err) && alloc(u, N * std::max(c.I_dense, c.I_shared), err) && alloc(a, N * std::max(c.I_dense, c.I_shared), err) &&
|
||||
alloc(rlog, N * c.n_exp, err) && alloc(ridx, N * c.top_k, err) && alloc(rw, N * c.top_k, err) && alloc(gu, N * c.top_k * 2 * c.I_moe, err) &&
|
||||
alloc(ye, N * c.top_k * D, err) && alloc(logits, static_cast<size_t>(lrows) * c.V, err) && alloc(ids, N, err);
|
||||
if (!ok) return false;
|
||||
if (o.kda_par && o.kda_chunked && static_cast<int>(N) > o.kda_seq_max_n) {
|
||||
kscr_floats = gpu::kda_chunk_scratch_floats(static_cast<int>(N), c.H, c.hd);
|
||||
if (!alloc_bytes(reinterpret_cast<void**>(&kscr), kscr_floats * sizeof(float), "cudaMalloc (KDA chunk scratch)", err)) return false;
|
||||
}
|
||||
if (!alloc_bytes(&actp, N * c.top_k * c.I_moe * sizeof(float), "cudaMalloc", err)) return false;
|
||||
for (int s = 0; s < 2; ++s)
|
||||
if (!alloc_bytes(reinterpret_cast<void**>(&q8[s]), N * Kmax / 64 * sizeof(gpu::Q8Blk), "cudaMalloc", err) || !alloc(fa[s], N * Kmax, err)) return false;
|
||||
if (o.mla_kernel > 0) {
|
||||
mla_ws_bytes = gpu::mla_attn_fast_workspace(static_cast<int>(N), c.H, c.nope, c.rope, c.kv_lora, o.max_ctx, o.latent, o.mla_kernel);
|
||||
if (o.mla_prefill_kernel > 0) mla_ws_bytes = std::max(mla_ws_bytes, gpu::mla_attn_fast_workspace(static_cast<int>(N), c.H, c.nope, c.rope, c.kv_lora, o.max_ctx, o.latent, o.mla_prefill_kernel));
|
||||
if (mla_ws_bytes && !alloc_bytes(&mla_ws, mla_ws_bytes, "cudaMalloc (MLA split-K scratch)", err)) return false;
|
||||
}
|
||||
#if defined(STRATA_USE_HIP)
|
||||
if (o.mla_hipx && (o.latent == LatentFmt::F32 || o.latent == LatentFmt::F16X2) && gpu::mla_exph_ok(c.nope, c.rope, c.vhead, c.kv_lora)) {
|
||||
hx_ws_bytes = gpu::mla_exph_workspace_bytes(static_cast<int>(N), c.H, o.mla_hipx_slab);
|
||||
if (!alloc_bytes(&hx_ws, hx_ws_bytes, "cudaMalloc (expanded MLA workspace)", err)) return false;
|
||||
}
|
||||
#else
|
||||
if (o.mla_expanded && o.latent == LatentFmt::F32 && o.age_recent == 0 && gpu::mla_exp_ok(c.nope, c.rope, c.vhead, c.kv_lora)) {
|
||||
mla_exp_ws_bytes = gpu::mla_exp_workspace_bytes(static_cast<int>(N), c.H, o.mla_exp_slab);
|
||||
if (!alloc_bytes(&mla_exp_ws, mla_exp_ws_bytes, "cudaMalloc (expanded MLA workspace)", err)) return false;
|
||||
}
|
||||
#endif
|
||||
if (!alloc(ysh, N * D, err)) return false;
|
||||
if (o.tc_moe_min_n > 0 && !gpu::moe_tc_alloc(tcw, static_cast<int>(N) * c.top_k, c.n_exp)) { err = "cudaMalloc (grouped MoE work)"; return false; }
|
||||
if (o.lookahead) {
|
||||
for (int r = 0; r < kRing; ++r)
|
||||
if (!alloc(snap[r], N * D, err)) return false;
|
||||
if (!alloc(la_u, N * D, err) || !alloc(la_logits, N * c.n_exp, err) || !alloc(la_f, N * D, err) || !alloc_bytes(reinterpret_cast<void**>(&la_q8), N * D / 64 * sizeof(gpu::Q8Blk), "cudaMalloc", err)) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
bool init(std::string& err) {
|
||||
const EngineOptions& o = E.opt;
|
||||
@@ -433,43 +556,19 @@ struct Ling32Engine::StageCtx {
|
||||
cu(cudaEventCreateWithFlags(&ev_join, cudaEventDisableTiming), "event", err);
|
||||
cu(cudaEventCreateWithFlags(&ev_sh, cudaEventDisableTiming), "event", err);
|
||||
Nmax = o.max_tokens;
|
||||
lrows_full = o.logits_rows > 0 ? std::min<int>(o.logits_rows, Nmax) : Nmax;
|
||||
D = c.D;
|
||||
C = c.kda_channels();
|
||||
Kmax = std::max({D, C, c.I_dense, c.I_shared, c.H * c.vhead});
|
||||
const size_t N = Nmax;
|
||||
lrows = o.logits_rows > 0 ? std::min<int>(o.logits_rows, static_cast<int>(N)) : static_cast<int>(N);
|
||||
bool ok = alloc(x, N * D, err) && alloc(h, N * D, err) && alloc(cur, N * D, err) && alloc(proj, N * 5 * C, err) && alloc(qn, N * C, err) && alloc(kn, N * C, err) &&
|
||||
alloc(vc, N * C, err) && alloc(ko, N * C, err) && alloc(beta, N * c.H, err) && alloc(q, N * c.mla_q_dim(), err) && alloc(ckv, N * c.mla_latent_vals(), err) &&
|
||||
alloc(qabs, N * c.H * c.kv_lora, err) && alloc(ctx, N * c.H * c.kv_lora, err) && alloc(av, N * c.H * c.vhead, err) && alloc(gate, N * c.H, err) &&
|
||||
alloc(g, N * std::max(c.I_dense, c.I_shared), err) && alloc(u, N * std::max(c.I_dense, c.I_shared), err) && alloc(a, N * std::max(c.I_dense, c.I_shared), err) &&
|
||||
alloc(rlog, N * c.n_exp, err) && alloc(ridx, N * c.top_k, err) && alloc(rw, N * c.top_k, err) && alloc(gu, N * c.top_k * 2 * c.I_moe, err) &&
|
||||
alloc(ye, N * c.top_k * D, err) && alloc(logits, static_cast<size_t>(lrows) * c.V, err) && alloc(ids, N, err);
|
||||
if (!ok) return false;
|
||||
if (!cu(cudaMalloc(reinterpret_cast<void**>(&ecnt), 32 * sizeof(int)), "cudaMalloc", err) || !cu(cudaMemset(ecnt, 0, 32 * sizeof(int)), "cudaMemset", err)) return false;
|
||||
if (E.opt.kda_par && E.opt.kda_chunked && Nmax > E.opt.kda_seq_max_n) {
|
||||
kscr_floats = gpu::kda_chunk_scratch_floats(static_cast<int>(Nmax), c.H, c.hd);
|
||||
if (!cu(cudaMalloc(reinterpret_cast<void**>(&kscr), kscr_floats * sizeof(float)), "cudaMalloc (KDA chunk scratch)", err)) return false;
|
||||
}
|
||||
ok = cu(cudaMalloc(reinterpret_cast<void**>(&rcnt), 16 * sizeof(unsigned int)), "cudaMalloc", err) && cu(cudaMemset(rcnt, 0, 16 * sizeof(unsigned int)), "cudaMemset", err);
|
||||
if (!ok) return false;
|
||||
ok = cu(cudaMalloc(&actp, N * c.top_k * c.I_moe * sizeof(float)), "cudaMalloc", err);
|
||||
for (int s = 0; ok && s < 2; ++s) {
|
||||
ok = cu(cudaMalloc(reinterpret_cast<void**>(&q8[s]), N * Kmax / 64 * sizeof(gpu::Q8Blk)), "cudaMalloc", err) && alloc(fa[s], N * Kmax, err);
|
||||
}
|
||||
bool ok = cu(cudaMalloc(reinterpret_cast<void**>(&rcnt), 16 * sizeof(unsigned int)), "cudaMalloc", err) && cu(cudaMemset(rcnt, 0, 16 * sizeof(unsigned int)), "cudaMemset", err);
|
||||
if (!ok) return false;
|
||||
if ((o.latent == LatentFmt::Q8 || o.latent == LatentFmt::F16X2) && o.mla_kernel <= 0) { err = "the Q8 / f16x2 latent caches need the shared MLA kernel (--mla-kernel simt|tc), not the original attention kernel"; return false; }
|
||||
#if !defined(STRATA_USE_HIP)
|
||||
if (o.latent == LatentFmt::F16X2) { err = "--latent f16x2 is the AMD WMMA kernel's cache format (gfx11 / gfx12 builds only)"; return false; }
|
||||
#endif
|
||||
if (o.mla_kernel > 0) {
|
||||
mla_ws_bytes = gpu::mla_attn_fast_workspace(static_cast<int>(N), c.H, c.nope, c.rope, c.kv_lora, o.max_ctx, o.latent, o.mla_kernel);
|
||||
if (o.mla_prefill_kernel > 0) mla_ws_bytes = std::max(mla_ws_bytes, gpu::mla_attn_fast_workspace(static_cast<int>(N), c.H, c.nope, c.rope, c.kv_lora, o.max_ctx, o.latent, o.mla_prefill_kernel));
|
||||
if (mla_ws_bytes && !cu(cudaMalloc(&mla_ws, mla_ws_bytes), "cudaMalloc (MLA split-K scratch)", err)) return false;
|
||||
}
|
||||
#if defined(STRATA_USE_HIP)
|
||||
if (o.mla_hipx && (o.latent == LatentFmt::F32 || o.latent == LatentFmt::F16X2) && gpu::mla_exph_ok(c.nope, c.rope, c.vhead, c.kv_lora)) {
|
||||
hx_ws_bytes = gpu::mla_exph_workspace_bytes(static_cast<int>(N), c.H, o.mla_hipx_slab);
|
||||
if (!cu(cudaMalloc(&hx_ws, hx_ws_bytes), "cudaMalloc (expanded MLA workspace)", err)) return false;
|
||||
hx_wk.assign(c.n_layers + 1, nullptr); // + the MTP layer (index n_layers): its prefill chunks take the expanded form too (the NVIDIA build_mla_expanded does the same)
|
||||
hx_wv.assign(c.n_layers + 1, nullptr);
|
||||
const size_t nw = static_cast<size_t>(c.H) * c.nope * c.kv_lora, nv = static_cast<size_t>(c.H) * c.vhead * c.kv_lora;
|
||||
@@ -487,14 +586,13 @@ struct Ling32Engine::StageCtx {
|
||||
cudaStreamSynchronize(st);
|
||||
}
|
||||
#else
|
||||
if (o.mla_expanded && o.latent == LatentFmt::F32 && o.age_recent == 0 && gpu::mla_exp_ok(c.nope, c.rope, c.vhead, c.kv_lora)) {
|
||||
mla_exp_ws_bytes = gpu::mla_exp_workspace_bytes(static_cast<int>(N), c.H, o.mla_exp_slab);
|
||||
if (!cu(cudaMalloc(&mla_exp_ws, mla_exp_ws_bytes), "cudaMalloc (expanded MLA workspace)", err)) return false;
|
||||
}
|
||||
#endif
|
||||
if (!alloc(ysh, N * D, err) || !alloc(d_pos, 1, err) || !alloc(d_rdelta, 1, err) || !cu(cudaMallocHost(reinterpret_cast<void**>(&h_pos), sizeof(int)), "pinned", err)) return false;
|
||||
if (!alloc(d_pos, 1, err) || !alloc(d_rdelta, 1, err) || !cu(cudaMallocHost(reinterpret_cast<void**>(&h_pos), sizeof(int)), "pinned", err)) return false;
|
||||
cudaMemset(d_rdelta, 0, sizeof(int));
|
||||
if (o.tc_moe_min_n > 0 && !gpu::moe_tc_alloc(tcw, static_cast<int>(N) * c.top_k, c.n_exp)) { err = "cudaMalloc (grouped MoE work)"; return false; }
|
||||
// the row-dependent scratch (see ScratchSet): decode_rows rows while scratch_regrow keeps a second, big set for the prompts, else max_tokens rows
|
||||
regrow_on = o.scratch_regrow && o.decode_rows >= 1 && o.decode_rows < Nmax;
|
||||
if (!scratch_body(static_cast<size_t>(regrow_on ? o.decode_rows : Nmax), err)) return false;
|
||||
scr_save(dec_set);
|
||||
// state
|
||||
S_sz = static_cast<size_t>(c.H) * c.hd * c.hd;
|
||||
hist_sz = static_cast<size_t>(3) * C * 3;
|
||||
@@ -535,18 +633,15 @@ struct Ling32Engine::StageCtx {
|
||||
if (o.lookahead) {
|
||||
E.stats_.init(c.n_layers);
|
||||
for (int r = 0; r < kRing; ++r) {
|
||||
if (!alloc(snap[r], N * D, err) || !cu(cudaEventCreateWithFlags(&snap_ready[r], cudaEventDisableTiming), "event", err) ||
|
||||
if (!cu(cudaEventCreateWithFlags(&snap_ready[r], cudaEventDisableTiming), "event", err) ||
|
||||
!cu(cudaEventCreateWithFlags(&snap_done[r], cudaEventDisableTiming), "event", err))
|
||||
return false;
|
||||
}
|
||||
if (!alloc(la_u, N * D, err) || !alloc(la_logits, N * c.n_exp, err) || !alloc(la_f, N * D, err) ||
|
||||
!cu(cudaMalloc(reinterpret_cast<void**>(&la_q8), N * D / 64 * sizeof(gpu::Q8Blk)), "cudaMalloc", err))
|
||||
return false;
|
||||
if (o.lookahead_k1) {
|
||||
d_pred1.assign(c.n_layers, nullptr);
|
||||
h_pred1.assign(c.n_layers, nullptr);
|
||||
for (int il = c.first_k_dense; il < c.n_layers; ++il)
|
||||
if (!alloc(d_pred1[il], N * kLookaheadTopN, err) || !cu(cudaMallocHost(reinterpret_cast<void**>(&h_pred1[il]), N * kLookaheadTopN * sizeof(int)), "pinned", err)) return false;
|
||||
if (!alloc(d_pred1[il], static_cast<size_t>(Nmax) * kLookaheadTopN, err) || !cu(cudaMallocHost(reinterpret_cast<void**>(&h_pred1[il]), static_cast<size_t>(Nmax) * kLookaheadTopN * sizeof(int)), "pinned", err)) return false;
|
||||
}
|
||||
for (int ki = 0; ki < 2; ++ki) {
|
||||
d_pred[ki].assign(c.n_layers, nullptr);
|
||||
@@ -555,7 +650,7 @@ struct Ling32Engine::StageCtx {
|
||||
la_targets[ki].assign(c.n_layers, {});
|
||||
if (!((o.lookahead_ks >> ki) & 1)) continue; // this predictor is not wanted (the tiers use one: k = 2 for Mode B, k = 4 for Mode C)
|
||||
for (int il = c.first_k_dense; il < c.n_layers; ++il) {
|
||||
if (!alloc(d_pred[ki][il], N * kLookaheadTopN, err) || !cu(cudaMallocHost(reinterpret_cast<void**>(&h_pred[ki][il]), N * kLookaheadTopN * sizeof(int)), "pinned", err))
|
||||
if (!alloc(d_pred[ki][il], static_cast<size_t>(Nmax) * kLookaheadTopN, err) || !cu(cudaMallocHost(reinterpret_cast<void**>(&h_pred[ki][il]), static_cast<size_t>(Nmax) * kLookaheadTopN * sizeof(int)), "pinned", err))
|
||||
return false;
|
||||
if (hp_dev[ki].empty()) hp_dev[ki].assign(c.n_layers, nullptr);
|
||||
{
|
||||
@@ -570,8 +665,8 @@ struct Ling32Engine::StageCtx {
|
||||
}
|
||||
if (o.lookahead_stats || o.capture) // the routing capture is only read by the statistics and the capture mode: two small D2H copies per MoE layer are not free
|
||||
for (int il = c.first_k_dense; il < c.n_layers; ++il) {
|
||||
if (!cu(cudaMallocHost(reinterpret_cast<void**>(&h_ridx[il]), N * c.top_k * sizeof(int)), "pinned", err) ||
|
||||
!cu(cudaMallocHost(reinterpret_cast<void**>(&h_rw[il]), N * c.top_k * sizeof(float)), "pinned", err))
|
||||
if (!cu(cudaMallocHost(reinterpret_cast<void**>(&h_ridx[il]), static_cast<size_t>(Nmax) * c.top_k * sizeof(int)), "pinned", err) ||
|
||||
!cu(cudaMallocHost(reinterpret_cast<void**>(&h_rw[il]), static_cast<size_t>(Nmax) * c.top_k * sizeof(float)), "pinned", err))
|
||||
return false;
|
||||
}
|
||||
reset();
|
||||
@@ -639,6 +734,9 @@ struct Ling32Engine::StageCtx {
|
||||
|
||||
void destroy() {
|
||||
auto f = [](auto*& p) { if (p) { cudaFree(p); p = nullptr; } };
|
||||
if (big_valid) { scr_bind(dec_set); scr_free(big_set); big_valid = false; } // scratch regrow: the members below are the small set again
|
||||
f(mla_ws);
|
||||
for (auto*& p : snap) f(p);
|
||||
f(x); f(h); f(cur); f(proj); f(qn); f(kn); f(vc); f(ko); f(beta); f(q); f(ckv); f(qabs); f(ctx); f(av); f(gate); f(g); f(u); f(a); f(rlog); f(rw); f(gu); f(ye); f(logits);
|
||||
f(mla_exp_ws); f(ridx); f(rcnt); f(ecnt); f(kscr); f(ids); f(actp); f(q8[0]); f(q8[1]); f(fa[0]); f(fa[1]); f(S_pool); f(hist_pool); f(S_ck); f(hist_ck); f(la_u); f(la_logits); f(la_f); f(la_q8);
|
||||
for (auto*& p : cache) if (p) { cudaFree(p); p = nullptr; }
|
||||
@@ -1257,6 +1355,10 @@ bool Ling32Engine::forward_mm(const int* ids, int N, int n_logits, std::vector<f
|
||||
if (N < 1 || N > opt.max_tokens) { err = "forward: N must be 1.." + std::to_string(opt.max_tokens); return false; }
|
||||
if (pos_ + N > opt.max_ctx) { err = "context full: position " + std::to_string(pos_ + N) + " > max_ctx " + std::to_string(opt.max_ctx); return false; }
|
||||
if (pos_ + N + kKvMargin > I.kv_cap && !I.grow_kv(pos_ + N + kKvMargin, err)) return false; // lazy latent KV
|
||||
if (I.regrow_on) { // scratch regrow: a prefill-sized forward needs the big scratch set, a decode-sized one gives it back to the pool (not while a speculative request is active: its cycles keep the sets)
|
||||
if (N > I.rows_cur) { if (!I.ensure_rows(N, err)) return false; }
|
||||
else if (N <= opt.decode_rows && I.big_valid && !(spec_on_ && !plain_on_)) I.trim_scratch();
|
||||
}
|
||||
if (n_logits > N) n_logits = N;
|
||||
if (n_logits > I.lrows) { err = "forward: " + std::to_string(n_logits) + " logits rows asked for, the buffer holds " + std::to_string(I.lrows) + " (EngineOptions::logits_rows)"; return false; }
|
||||
const auto t0 = std::chrono::steady_clock::now();
|
||||
@@ -1327,7 +1429,7 @@ bool Ling32Engine::forward_mm(const int* ids, int N, int n_logits, std::vector<f
|
||||
bool Ling32Engine::forward_span(const int* ids, int N, int n_logits, std::vector<float>* logits, std::string& err) {
|
||||
if (N < 1) { err = "forward_span: N must be >= 1"; return false; }
|
||||
if (n_logits > N) n_logits = N;
|
||||
if (n_logits > p_->stages.front()->lrows) { err = "forward_span: " + std::to_string(n_logits) + " logits rows asked for, the buffer holds " + std::to_string(p_->stages.front()->lrows) + " (EngineOptions::logits_rows)"; return false; }
|
||||
if (n_logits > p_->stages.front()->lrows_full) { err = "forward_span: " + std::to_string(n_logits) + " logits rows asked for, the buffer holds " + std::to_string(p_->stages.front()->lrows_full) + " (EngineOptions::logits_rows)"; return false; }
|
||||
const int sub = opt.max_tokens;
|
||||
const bool carry = (!spec_on_ || span_spec_) && !opt.capture && n_logits <= sub && (N > sub || (provider_ && N >= 128)); // one chunk with a tier store also runs layer-major: the next-layer hint then applies
|
||||
if (!carry) { // the chunk loop of the caller
|
||||
@@ -1344,6 +1446,7 @@ bool Ling32Engine::forward_span(const int* ids, int N, int n_logits, std::vector
|
||||
const Cfg& c = m_->cfg;
|
||||
if (pos_ + N > opt.max_ctx) { err = "context full: position " + std::to_string(pos_ + N) + " > max_ctx " + std::to_string(opt.max_ctx); return false; }
|
||||
if (pos_ + N + kKvMargin > I.kv_cap && !I.grow_kv(pos_ + N + kKvMargin, err)) return false; // lazy latent KV
|
||||
if (I.regrow_on && std::min(N, sub) > I.rows_cur && !I.ensure_rows(std::min(N, sub), err)) return false; // scratch regrow: the sub-chunks of the span need the big set
|
||||
const auto t0c = std::chrono::steady_clock::now();
|
||||
if (provider_) provider_->begin_forward(N);
|
||||
I.la_enabled = false; // no lookahead predictions in a span: they are made per sub-chunk for later layers of the same sub-chunk, and the span runs layer-major
|
||||
@@ -1371,6 +1474,7 @@ bool Ling32Engine::run_layer(int il, const float* x_in, int N, std::vector<float
|
||||
StageCtx& I = p_->stage_of(il);
|
||||
gpu::DeviceGuard dg(I.device);
|
||||
const Cfg& c = m_->cfg;
|
||||
if (I.regrow_on && N > I.rows_cur && !I.ensure_rows(N, err)) return false;
|
||||
I.set_pos(pos0);
|
||||
cudaMemcpyAsync(I.x, x_in, static_cast<size_t>(N) * c.D * 4, cudaMemcpyHostToDevice, I.st);
|
||||
I.h_ready = false; // a single layer on its own input: no pending input norm of a previous layer
|
||||
@@ -1501,6 +1605,7 @@ bool Ling32Engine::spec_init(const SpecParams& p, std::string& err) {
|
||||
I.sB = std::max(1, std::min(p.block, 8));
|
||||
if (I.Nmax < I.sB + 1) { err = "--chunk must be at least block + 1 for speculative decoding"; return false; }
|
||||
if (I.lrows < I.sB + 1) { err = "the logits buffer (" + std::to_string(I.lrows) + " rows) is smaller than a verify batch (block + 1)"; return false; }
|
||||
if (I.regrow_on && I.dec_set.rows < I.sB + 1) { err = "scratch regrow: decode_rows (" + std::to_string(I.dec_set.rows) + ") is smaller than a verify batch (block + 1)"; return false; }
|
||||
if (opt.capture) { err = "speculative decoding is not combined with layer capture"; return false; }
|
||||
I.snap_slots = I.sB;
|
||||
I.ext_len = 3 + I.sB + 1;
|
||||
|
||||
@@ -34,6 +34,8 @@ struct EngineOptions {
|
||||
int max_ctx = 8192; // MLA latent cache rows per MLA layer (fp16, 576 values each)
|
||||
int kv_init_ctx = 0; // lazy latent KV (tier B / C): the cache starts with this many rows per MLA layer (the planner counted only these) and doubles when the position gets close; the tier store gives pool slots back when the card has no room. 0 = max_ctx rows up front
|
||||
int max_tokens = 256; // tokens per forward() call
|
||||
bool scratch_regrow = false; // tier B / C with lazy KV: the activation scratch of a chunk exists only while a prompt is prefilled (a second, small set of decode_rows rows serves decode); when the prompt is done the big set is freed and the store regrows its dynamic pool into the memory (STRATA_L32_REGROW)
|
||||
int decode_rows = 64; // rows of the always-resident scratch set of scratch_regrow (decode steps, verify batches of a speculative cycle)
|
||||
int logits_rows = 0; // rows of the logits buffer (V floats each): 0 = max_tokens (every row of a chunk can be asked for); a chat / serve run asks for at most the verify rows of a speculative cycle, so the engine sets 32 there and the 0.6 GiB of a 1024-token chunk stay free for expert slots
|
||||
int tc_min_n = 0; // trunk projections with float activations and at least this many tokens: tensor-core GEMM (fp16 tiles, fp32 accumulate); 0 = always the float GEMV
|
||||
int tc_moe_min_n = 0; // routed experts of batches with at least this many tokens (float activations): grouped by expert, tensor-core tiles; 0 = per-pair kernels
|
||||
@@ -159,6 +161,7 @@ public:
|
||||
// the store also serves the MTP layer's experts (the sidecar's Section 4 in pinned RAM, GpuModel::mtp_pool): the engine then calls prepare() for il = n_layers as for a trunk layer
|
||||
virtual bool serves_mtp() { return false; }
|
||||
virtual size_t release_bytes(size_t /*need*/) { return 0; } // lazy KV: free at least this many bytes of the provider's card memory (dynamic expert slots, whole chunks); returns the bytes freed (0: nothing left to give)
|
||||
virtual size_t grow_bytes(size_t /*max_bytes*/) { return 0; } // scratch regrow: hand back up to this many bytes of the card to the provider (dynamic expert slots of chunks that release_bytes freed); returns the bytes taken
|
||||
// called right before prepare(): the device routing weights [N * top_k] and the pair rows of ye [N * top_k, D] of this layer (--turbo-ssd renormalises the weights and clears skipped rows)
|
||||
virtual void set_route_buffers(float* /*d_rw*/, float* /*d_ye*/) {}
|
||||
virtual const uint8_t* const* next_pass(int /*j*/, void* /*stream*/) { return nullptr; }
|
||||
|
||||
@@ -209,6 +209,14 @@ struct RunOpts {
|
||||
int logits_rows_opt = -1; // --logits-rows N: rows of the engine's logits buffer (0 = a whole chunk; -1 = 32 for --serve / --genjobs, which ask for few rows, else a whole chunk: the teacher-forced modes dump every row)
|
||||
int kv_init_opt = -1; // --kv-init N: lazy latent KV, initial capacity in rows (0 = reserve the whole context up front; -1 = 16384 in tier B / C, the cache then grows with the conversation and the tier store gives pool slots back); STRATA_L32_LAZY_KV=0 also switches it off
|
||||
int kv_plan_rows = 0; // set by make_plan: the rows make_sizes counts for the latent cache (0 = o.ctx)
|
||||
int regrow_opt = -1; // --regrow on|off: scratch regrow (the activation scratch of a chunk only while a prompt is prefilled, the memory goes back to the expert pool for decode); -1 = STRATA_L32_REGROW (default off), tier B / C with lazy KV only
|
||||
int decode_rows_opt = 64; // --decode-rows N: rows of the always-resident scratch set of scratch regrow
|
||||
bool regrow_plan = false; // set by make_plan: make_sizes counts decode_rows_opt rows of activation scratch instead of the chunk
|
||||
bool regrow() const {
|
||||
if (regrow_opt >= 0) return regrow_opt > 0 && kv_init_rows() > 0 && chunk > decode_rows_opt;
|
||||
const char* e = std::getenv("STRATA_L32_REGROW");
|
||||
return e && e[0] == '1' && kv_init_rows() > 0 && chunk > decode_rows_opt;
|
||||
}
|
||||
int kv_init_rows() const {
|
||||
const char* e = std::getenv("STRATA_L32_LAZY_KV");
|
||||
if (e && e[0] == '0') return 0;
|
||||
@@ -366,8 +374,8 @@ TierSizes make_sizes(const Ling32File& f, const RunOpts& o) {
|
||||
if (o.spec_mtp || !o.mtp_file.empty()) ++n_mla;
|
||||
sz.latent_bytes = static_cast<uint64_t>(n_mla) * latent_layer_bytes(o.latent, o.kv_plan_rows > 0 ? o.kv_plan_rows : o.ctx, f.cfg().kv_lora, f.cfg().rope);
|
||||
}
|
||||
sz.chunk = o.chunk;
|
||||
sz.logits_rows = o.logits_rows() > 0 ? std::min(o.logits_rows(), o.chunk) : o.chunk;
|
||||
sz.chunk = o.regrow_plan ? std::min(o.chunk, o.decode_rows_opt) : o.chunk; // scratch regrow: the plan counts the decode set only; a prompt takes pool chunks back while it is prefilled
|
||||
sz.logits_rows = o.logits_rows() > 0 ? std::min(o.logits_rows(), static_cast<int>(sz.chunk)) : static_cast<int>(sz.chunk);
|
||||
sz.vocab = f.cfg().V;
|
||||
sz.hidden = f.cfg().D;
|
||||
return sz;
|
||||
@@ -382,8 +390,9 @@ bool make_plan(const Ling32File& f, const RunOpts& o, uint64_t vram_free, uint64
|
||||
// lazy latent KV: the planner counts the initial capacity only; a plan that keeps everything on the card (tier A: CUDA graphs capture the cache) is made again with the whole context
|
||||
RunOpts po = o;
|
||||
po.kv_plan_rows = o.kv_init_rows();
|
||||
po.regrow_plan = o.regrow();
|
||||
plan = plan_tier(hw, make_request(o), rt, make_sizes(f, po));
|
||||
if (plan.ok && plan.mode == TierMode::A && po.kv_plan_rows > 0) { po.kv_plan_rows = 0; plan = plan_tier(hw, make_request(o), rt, make_sizes(f, po)); }
|
||||
if (plan.ok && plan.mode == TierMode::A && po.kv_plan_rows > 0) { po.kv_plan_rows = 0; po.regrow_plan = false; plan = plan_tier(hw, make_request(o), rt, make_sizes(f, po)); } // tier A keeps everything (and the CUDA graphs): no regrow
|
||||
if (!plan.ok) { err = plan.error; return false; }
|
||||
plan.kv_rows = po.kv_plan_rows;
|
||||
if (o.force_vram_ranks >= 0 || o.force_ram_ranks >= 0 || o.force_dyn >= 0 || o.force_ring >= 0) { // tests and experiments: choose the split by hand
|
||||
@@ -838,6 +847,7 @@ int cmd_run(const RunOpts& o_in) {
|
||||
eo.max_tokens = o.chunk;
|
||||
eo.logits_rows = o.logits_rows();
|
||||
if (tiered && plan.kv_rows > 0) eo.kv_init_ctx = plan.kv_rows; // lazy latent KV (the plan counted only this)
|
||||
if (tiered && plan.kv_rows > 0 && o.regrow()) { eo.scratch_regrow = true; eo.decode_rows = o.decode_rows_opt; } // the plan counted decode_rows rows of scratch only
|
||||
eo.lookahead = o.lookahead || o.coverage || (tiered && plan.prefetch);
|
||||
if (tiered) { eo.lookahead_ks = (o.lookahead || o.coverage) ? 3 : (plan.lookahead_k == 4 ? 2 : 1); eo.lookahead_stats = o.lookahead; }
|
||||
eo.lookahead_group_mask = !o.la_nomask;
|
||||
@@ -1620,6 +1630,8 @@ int main(int argc, char** argv) {
|
||||
else if (a == "--chunk") o.chunk = std::atoi(nx().c_str());
|
||||
else if (a == "--logits-rows") o.logits_rows_opt = std::atoi(nx().c_str());
|
||||
else if (a == "--kv-init") o.kv_init_opt = std::atoi(nx().c_str());
|
||||
else if (a == "--regrow") { const std::string v = nx(); o.regrow_opt = (v == "on" || v == "1") ? 1 : 0; }
|
||||
else if (a == "--decode-rows") o.decode_rows_opt = std::max(1, std::atoi(nx().c_str()));
|
||||
else if (a == "--device") o.device = std::atoi(nx().c_str());
|
||||
else if (a == "--topk") o.topk = std::atoi(nx().c_str());
|
||||
else if (a == "--act") o.act_q8 = nx() == "q8";
|
||||
|
||||
@@ -737,6 +737,33 @@ struct ExpertStore::Impl {
|
||||
return freed;
|
||||
}
|
||||
|
||||
// scratch regrow (the engine freed the activation scratch of a prompt): take chunks of small dynamic slots that release_bytes freed back, lowest chunk first, as long as the card keeps `reserve` bytes free
|
||||
// and at most MAX_BYTES. The new slots start empty (state 0: the prefetch and the demand copies fill them). Called between forwards, like release_bytes.
|
||||
size_t grow_bytes(size_t max_bytes) {
|
||||
if (dyn_dead == 0 || slot_small == 0 || dyn_chunks.empty()) return 0;
|
||||
static const size_t reserve = [] { const char* e = std::getenv("STRATA_L32_REGROW_RESERVE_MB"); return static_cast<size_t>(e && e[0] ? std::atoi(e) : 192) * 1048576ull; }();
|
||||
std::unique_lock<std::mutex> lk(mu);
|
||||
size_t taken = 0;
|
||||
int slots = 0;
|
||||
for (int ci = 0; ci < static_cast<int>(dyn_chunks.size()) && taken < max_bytes; ++ci) {
|
||||
if (dyn_chunks[static_cast<size_t>(ci)]) continue;
|
||||
const int s0 = ci * kDynChunk, s1 = std::min(n_small, s0 + kDynChunk);
|
||||
const size_t cb = static_cast<size_t>(s1 - s0) * slot_small;
|
||||
size_t fr = 0, tot = 0;
|
||||
if (cudaMemGetInfo(&fr, &tot) != cudaSuccess || fr < cb + reserve) { (void)cudaGetLastError(); break; }
|
||||
uint8_t* cp = nullptr;
|
||||
if (cudaMalloc(reinterpret_cast<void**>(&cp), cb) != cudaSuccess) { (void)cudaGetLastError(); break; }
|
||||
dyn_chunks[static_cast<size_t>(ci)] = cp;
|
||||
for (int sl = s0; sl < s1; ++sl) dyn[static_cast<size_t>(sl)].state = 0;
|
||||
dyn_dead -= s1 - s0;
|
||||
gpu_alloc += cb;
|
||||
taken += cb;
|
||||
slots += s1 - s0;
|
||||
}
|
||||
if (taken) std::printf("tier store: scratch regrow took %d dynamic slots (%.0f MiB) back, %d of %d small slots live\n", slots, taken / 1048576.0, n_small - dyn_dead, n_small);
|
||||
return taken;
|
||||
}
|
||||
|
||||
// A dynamic slot to fill. demand: may take slots of the current layer's earlier passes and slots a prefetch filled for later layers; prefetch: only slots whose last user finished.
|
||||
int alloc_dyn(bool demand, int pass, cudaEvent_t* old_ev = nullptr, uint64_t need = 0, int evict_below = 1 << 30) {
|
||||
int best = -1;
|
||||
@@ -1848,6 +1875,7 @@ const uint8_t* const* ExpertStore::prepare(int il, int n_tokens, const int* d_ri
|
||||
int ExpertStore::passes() { return p_->passes(); }
|
||||
bool ExpertStore::serves_mtp() { return p_->serves_mtp(); }
|
||||
size_t ExpertStore::release_bytes(size_t need) { return p_->release_bytes(need); }
|
||||
size_t ExpertStore::grow_bytes(size_t max_bytes) { return p_->grow_bytes(max_bytes); }
|
||||
bool ExpertStore::cpu_pending() { return p_->cpu_pending(); }
|
||||
void ExpertStore::cpu_begin(int, int, const float* d_ah, float* d_gu, float* d_actp, float* d_ye, void*) { p_->cpu_begin(d_ah, d_gu, d_actp, d_ye); }
|
||||
void ExpertStore::cpu_after_gu(void* stream) { p_->cpu_after_gu(static_cast<cudaStream_t>(stream)); }
|
||||
|
||||
@@ -43,6 +43,7 @@ public:
|
||||
const uint8_t* const* prepare(int il, int n_tokens, const int* d_ridx, int top_k, void* stream) override;
|
||||
int passes() override;
|
||||
size_t release_bytes(size_t need) override; // lazy latent KV: frees whole tail chunks of dynamic slots (>= need bytes if possible)
|
||||
size_t grow_bytes(size_t max_bytes) override; // scratch regrow: re-allocates released chunks of dynamic slots (empty) after the engine freed its prefill scratch
|
||||
bool serves_mtp() override; // the MTP layer's experts (GpuModel::mtp_pool) are served here as slots of the pool
|
||||
const uint8_t* const* next_pass(int j, void* stream) override;
|
||||
bool cpu_pending() override;
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
#!/usr/bin/env python3
|
||||
"""ling32_regrow_test.py - scratch regrow (tier B / C): the activation scratch of a chunk exists only while a prompt is prefilled, the memory goes back to the expert pool for decode.
|
||||
(STRATA_L32_KV_FORCE_RELEASE=1 makes the big set take one chunk of pool slots even where the card has room, so the legs exercise the release and the regrow.)
|
||||
|
||||
python ling32_regrow_test.py STRATA_LING32_EXE WIDE_FIXTURE WIDE_MTP_FIXTURE WORKDIR
|
||||
|
||||
Where the scratch lives changes nothing the kernels compute: every leg with --regrow on must give the same bytes as the same leg with --regrow off (the teacher-forced dump of a 1200-token
|
||||
prompt at --chunk 128, and the generated ids). The legs also check that the machinery ran: the big scratch set was allocated while the prompt ran (the store released pool chunks for it)
|
||||
and the store took them back for decode ("scratch regrow took N dynamic slots").
|
||||
|
||||
tier B, plain regrow on vs off (dump, ids)
|
||||
tier B, a second prompt in the same process (the jobs run twice: the next prompt takes the memory back, the pool regrows again)
|
||||
tier B, STRATA_L32_LAZY_OOM=1 the first allocation after the store is attached fails once (the release-and-retry path of the big set)
|
||||
tier C (card + RAM + SSD) regrow on vs off
|
||||
tier B, MTP sidecar speculative decoding (greedy: exact) regrow on vs the plain run: the same ids (the speculative request keeps its scratch sets, no regrow)
|
||||
|
||||
Exit code 0 = pass.
|
||||
"""
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import random
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
|
||||
def run(exe, model, work, name, jobs, extra, env_extra=None, mode="jobs"):
|
||||
out = os.path.join(work, name)
|
||||
os.makedirs(out, exist_ok=True)
|
||||
env = dict(os.environ)
|
||||
for k in ("STRATA_L32_LAZY_KV", "STRATA_L32_KV_FORCE_RELEASE", "STRATA_L32_LAZY_OOM", "STRATA_L32_REGROW"):
|
||||
env.pop(k, None)
|
||||
if env_extra:
|
||||
env.update(env_extra)
|
||||
cmd = [exe, "--model", model, "--" + mode, jobs, "--out", out, "--ctx", "4000", "--chunk", "128", "--no-selfcheck", "--stop", "999999", "--kv-init", "64"] + extra
|
||||
p = subprocess.run(cmd, capture_output=True, text=True, errors="replace", env=env)
|
||||
txt = p.stdout + p.stderr
|
||||
dump = os.path.join(out, "g1200.tf.bin")
|
||||
gj = os.path.join(out, "g1200.gen.json")
|
||||
if p.returncode != 0 or (mode == "genjobs" and not os.path.exists(gj)) or (mode == "jobs" and not os.path.exists(dump)):
|
||||
return None, "exit %d: %s" % (p.returncode, " | ".join(txt.strip().splitlines()[-3:]))
|
||||
ids = json.load(open(gj)).get("gen_ids") if os.path.exists(gj) else []
|
||||
h = hashlib.sha256(open(dump, "rb").read()).hexdigest()[:16] if os.path.exists(dump) else "-"
|
||||
gave = len(re.findall(r"lazy KV gave", txt))
|
||||
took = len(re.findall(r"scratch regrow took", txt))
|
||||
return (h, ids, gave, took), ""
|
||||
|
||||
|
||||
def main():
|
||||
exe, wide, mtp, work = sys.argv[1:5]
|
||||
os.makedirs(work, exist_ok=True)
|
||||
rnd = random.Random(20261204)
|
||||
ids = [rnd.randrange(1, 500) for _ in range(1200)]
|
||||
jobs = os.path.join(work, "jobs.jsonl")
|
||||
with open(jobs, "w") as f:
|
||||
f.write('{"id":"g1200","prompt_ids":[' + ",".join(map(str, ids)) + '],"cont_ids":[10],"gen":40,"tf":0}\n')
|
||||
gen = os.path.join(work, "genjobs.jsonl")
|
||||
with open(gen, "w") as f:
|
||||
for k in range(2): # two prompts: the second one takes the pool memory back for its prefill and gives it again
|
||||
f.write('{"id":"g1200","prompt_ids":[' + ",".join(map(str, ids[k * 5:] + ids[:k * 5])) + '],"gen":40}\n')
|
||||
tier_b = ["--tier", "hybrid", "--vram-budget-gib", "3", "--ram-budget-gib", "4"]
|
||||
tier_c = ["--tier", "nvme", "--vram-budget-gib", "0.001", "--ram-budget-gib", "0.001"]
|
||||
legs = [
|
||||
# name, mode, args, env, regrow expected to run (needs "took" > 0)
|
||||
("ref_b", "jobs", tier_b + ["--regrow", "off"], None, False),
|
||||
("rg_b", "jobs", tier_b + ["--regrow", "on"], {"STRATA_L32_KV_FORCE_RELEASE": "1"}, True),
|
||||
("ref_gen", "genjobs", tier_b + ["--regrow", "off"], None, False),
|
||||
("rg_gen", "genjobs", tier_b + ["--regrow", "on"], {"STRATA_L32_KV_FORCE_RELEASE": "1"}, True),
|
||||
("rg_gen_oom", "genjobs", tier_b + ["--regrow", "on"], {"STRATA_L32_LAZY_OOM": "1"}, True), # the first allocation after the store is attached fails once: the release-and-retry path (the big set), then the regrow
|
||||
("ref_c", "jobs", tier_c + ["--regrow", "off"], None, False),
|
||||
("rg_c", "jobs", tier_c + ["--regrow", "on"], {"STRATA_L32_KV_FORCE_RELEASE": "1"}, None), # tier C at 0.001 GiB has no pool to release: the two scratch sets run, the pool does not move
|
||||
("rg_spec_gen", "genjobs", tier_b + ["--regrow", "on", "--mtp", mtp, "--spec", "mtp", "--spec-adaptive"], {"STRATA_L32_KV_FORCE_RELEASE": "1"}, None),
|
||||
]
|
||||
res = {}
|
||||
for name, mode, extra, env, want in legs:
|
||||
r, err = run(exe, wide, work, name, gen if mode == "genjobs" else jobs, extra, env, mode)
|
||||
if r is None:
|
||||
print("FAIL: %s: %s" % (name, err))
|
||||
return 1
|
||||
res[name] = r
|
||||
print("%-12s dump %s, %d ids, %d slot releases, %d regrows" % (name, r[0], len(r[1]), r[2], r[3]))
|
||||
if want is True and r[3] < 1:
|
||||
print("FAIL: %s: the pool did not regrow (the test does not exercise the machinery)" % name)
|
||||
return 1
|
||||
if want is False and r[3] != 0:
|
||||
print("FAIL: %s: the run without regrow printed a regrow message" % name)
|
||||
return 1
|
||||
for a, b in (("ref_b", "rg_b"), ("ref_c", "rg_c")):
|
||||
if res[a][0] != res[b][0] or res[a][1] != res[b][1]:
|
||||
print("FAIL: %s differs from %s (dump %s vs %s)" % (b, a, res[b][0], res[a][0]))
|
||||
return 1
|
||||
for b in ("rg_gen", "rg_gen_oom", "rg_spec_gen"):
|
||||
if res["ref_gen"][1] != res[b][1]:
|
||||
print("FAIL: %s gives other ids than the run without regrow" % b)
|
||||
return 1
|
||||
print("PASS: the same dump and ids with the prefill scratch freed for decode and the pool regrown (tier B, two prompts, injected OOM, tier C, MTP speculation)")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
Reference in new issue
Block a user