#include "strata/core/logit_bias.hpp" #include "strata/core/latent_share.hpp" // src/program/generate.cpp - P2.S6: `strata generate`. // // THE DRIVER, and the first program in this project that answers a question. Everything below it is a // component; this is the thing that composes them into a token: // // embed_row(token) -> 48 captured layer graphs (the CPU expert pool behind the doorbell) -> // lm_head(R) -> sample -> embed_row(next) -> ... // // WHAT IT IS NOT. There is no tokenizer here. `pack/full/tokenizer/` and `tools/strata_tokenizer.py` exist, // and a C++ BPE is Phase 1's deliverable rather than this program's, so the prompt arrives as IDS via // `--tokens`. That is not a placeholder: it is exactly what Gate C1 needs, because C1 compares logits against // llama.cpp on the SAME ids, and a tokenizer on only one side of that comparison is a second variable. // // AND IT IS PHASE 2, so hit rate is `h = 0` and the number it prints is slow on purpose // (`phase-2-correct-engine.md:5-9`). What it is FOR is the honest tok/s figure and the logit dump. #include "strata/platform/memory.hpp" #include "strata/platform/io_priority.hpp" #include "strata/core/adapt_async_default.hpp" #include "strata/core/arch_defaults.hpp" #include "strata/core/reader_room.hpp" #include "strata/core/residency_trim.hpp" #include "strata/core/kfd_settle.hpp" #include "strata/core/kfd_quiet.hpp" #if defined(STRATA_USE_HIP) && defined(__linux__) #include "strata/kernels/fused_gr.hpp" // fused_gr_check, called early on an integrated gfx11 (kfd_quiet.hpp, LOAD) #endif #include "strata/core/page_cache_drop.hpp" #include "strata/core/gfx12_chunk.hpp" #include "strata/core/nv_chunk.hpp" #include "strata/core/nv_defaults.hpp" #include "strata/kernels/gfx_arch.hpp" #include "strata/core/batch_telemetry.hpp" #include "strata/core/dma_batch.hpp" #include "strata/program/adaptive_range.hpp" #include "strata/core/run_manifest.hpp" #include "strata/core/device.hpp" #include "strata/core/remote_expert_opt.hpp" #include "strata/core/expert_cache.hpp" #include "strata/core/expert_nibble.hpp" #include "strata/core/conversation_snapshot.hpp" #include "strata/core/lookup_default.hpp" #include "strata/core/serve_stop_bound.hpp" #include "strata/core/conversation_disk.hpp" #include "strata/core/conversation_file.hpp" #include "strata/core/session_save_reclaim.hpp" #include "strata/core/conversation_memory.hpp" #include "strata/core/park_pool_policy.hpp" #include "strata/core/auto_cache.hpp" #include "strata/core/ple_residency.hpp" #include "strata/core/resident_ram_copy.hpp" #include "strata/core/defaults_026.hpp" #include "strata/core/coupled_draft.hpp" #include "strata/core/expert_source.hpp" #include "strata/core/foresight_swap.hpp" #include "strata/core/pinned.hpp" #include "strata/core/pin_budget.hpp" #include "strata/core/uma_cache.hpp" #include "strata/core/remote_experts.hpp" #include "strata/core/on_device.hpp" #include "strata/core/peer_experts.hpp" #include "strata/core/layer.hpp" #include "strata/core/kv_grow_rules.hpp" #include "strata/core/layout.hpp" #include "strata/core/session.hpp" #include "strata/core/weights.hpp" #include "strata/kernels/gfx_arch.hpp" #include "strata/kernels/cpu/expert.hpp" #include "strata/kernels/cpu/pool.hpp" #include "strata/kernels/cpu/card_node.hpp" #include "strata/kernels/cpu/numa_pool.hpp" #include "strata/platform/home_cpus.hpp" #include "strata/platform/aux_cpus.hpp" #include "strata/kernels/cpu/expert_layout.hpp" #include "strata/kernels/cpu/hadamard.hpp" #include "strata/kernels/ngram.hpp" #include "strata/kernels/iq_kernels.hpp" #include "strata/kernels/s2_expert_grouped.hpp" #include "strata/kernels/sampler.hpp" #include "strata/kernels/verify_kernels.hpp" #include "strata/kernels/elementwise.hpp" #include "strata/kernels/shared_expert.hpp" #include "strata/kernels/native_moe.hpp" #include "strata/kernels/native_gdn.hpp" #include "strata/kernels/native_router.hpp" #include "strata/kernels/native_qsa.hpp" #include "strata/kernels/native_qsa_indexer.hpp" #include "strata/kernels/native_rope.hpp" #include "strata/kernels/mrope.hpp" #include "strata/kernels/kv_q4.hpp" #include "strata/kernels/qsa.hpp" #include "strata/core/native_head.hpp" #include "strata/core/spill_gate.hpp" #include "strata/core/pcie_share_rule.hpp" #include "strata/core/verify.hpp" #include "strata/core/latent_dense.hpp" #include "strata/core/mtp.hpp" #include "strata/core/gated_proposal.hpp" #if defined(STRATA_HAVE_DFLASH2) #include "strata/core/dflash2.hpp" #include "strata/core/draft_cap.hpp" #endif #include "strata/prefill/gemm.hpp" #include "strata/prefill/kva.hpp" #include "strata/prefill/kva_floor.hpp" #include "strata/prefill/prefill.hpp" #include "strata/prefill/pf_fused_override.hpp" #include "strata/prefill/own_only_switches.hpp" #include "strata/prefill/gp100_prompt_default.hpp" #include "strata/core/sm120_series.hpp" #if defined(STRATA_PREFILL_MMQ) #include "strata/prefill/moe_mmq.hpp" #endif #include "strata/core/native_dense.hpp" #include "strata/program/adapt_decay.hpp" #include "strata/program/batch_read.hpp" #include "strata/program/logits_selection.hpp" #include "strata/program/conv_cache.hpp" #include "strata/program/split_rules.hpp" #include "strata/program/stage_reserve.hpp" #include "strata/program/split_walk.hpp" #include "strata/program/gpu_report.hpp" #include "strata/prefill/loan_rules.hpp" #if defined(STRATA_PREFILL_FUSED) && !defined(STRATA_PREFILL_MMQ) #include "strata/prefill/equal_cut_rule.hpp" #include "strata/prefill/fit_out_rule.hpp" #endif #include "strata/prefill/share_rules.hpp" #include "strata/platform/host_limits.hpp" #include "strata/program/split_ring.hpp" #include "strata/program/prefill_plan.hpp" #include "strata/program/draft_kv_plan.hpp" #include "strata/program/message_boundary.hpp" #include "strata/program/reply_branch.hpp" #include "strata/spec/draft_policy.hpp" #include "strata/spec/draft_vocab.hpp" #include "strata/spec/window_rule.hpp" #include "strata/spec/draft_source.hpp" #include "strata/spec/suffix_drafter.hpp" #include "strata/spec/spec_start.hpp" #include "strata/program/batch_groups.hpp" #include "strata/program/par_counters.hpp" #if defined(__linux__) #include #include #include #include #endif #include "strata/program/pipe_probe.hpp" #include "strata/kernels/cvec.hpp" #include "strata/core/progress.hpp" #include "strata/core/stream_watch.hpp" #include "strata/core/gpu_pause_time.hpp" #include "strata/core/scr.hpp" #include "strata/kernels/scr_move.hpp" #include "strata/core/device.hpp" #include "strata/core/emulate.hpp" #ifndef NOMINMAX #define NOMINMAX // gguf_reader.hpp includes windows.h #endif #include "strata/artifact/gguf_reader.hpp" #include "strata/core/family_layout.hpp" #if defined(STRATA_HAVE_QWEN35) #include "strata/qwen35/engine.hpp" #endif #if defined(_WIN32) #include #include #include #include #include #else #include #include #include #if !defined(__APPLE__) // major() / minor(): on macOS #include #endif #endif #include #if defined(STRATA_GPU_METAL) namespace strata::metal_engine { void set_model_shard(const char* shard1); // metal/src/engine/window.cpp void set_batch_slots(int n); // metal/src/engine/window.cpp: how many --batch slots the window keeps state for // batch slot b <-> the main sequence: the running state (unless kv_only) and the first `upto` cells of K/V bool window_slot_copy_main(bool into_slot, int slot, int64_t upto, bool kv_only, std::string& err); std::string draft_vocab_default(); // metal/src/engine/window.cpp: the packaged default draft subset (data/draft_vocab.bin) bool draft_vocab_whole_head(); // STRATA_METAL_DRAFT_VOCAB=full } #endif #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include // STRATA_DF2_TAP_DUMP=FILE (research, off by default): every prompt tap batch the DFlash2 context takes is appended to FILE as // int64 pos0, int64 rows, then rows x floats_per_row float32 (the tap rows [rows][taps][n_embd]), for the layer-major / chunk-major // equivalence test (DF-08). Nothing runs without the variable. static void df2_tap_dump(const float* dev, int64_t rows, int64_t pos0, int64_t floats_per_row) { static const char* path = std::getenv("STRATA_DF2_TAP_DUMP"); if (path == nullptr || path[0] == '\0' || rows <= 0) return; std::vector h((size_t) (rows * floats_per_row)); if (cudaMemcpy(h.data(), dev, h.size() * sizeof(float), cudaMemcpyDeviceToHost) != cudaSuccess) return; if (std::FILE* f = std::fopen(path, "ab")) { std::fwrite(&pos0, 8, 1, f); std::fwrite(&rows, 8, 1, f); std::fwrite(h.data(), sizeof(float), h.size(), f); std::fclose(f); } } // logprobs=K / allowed=...: one `LP` line for the token just emitted, from `ver`'s head // logits for the window row it came from (before sampling, penalties and temperature). // Format matches the SYCL port's LP line so one server-side reader serves both. // Called only when the request asked (`req_logprobs >= 0`): a request without logprobs never reaches it, so the // default path does no work for this and prints exactly what it printed before. static void emit_lp_line(const strata::core::Verifier& ver, int t, int32_t token, int k, const std::vector& allowed) { if (k < 0) return; static std::vector row; row.resize((size_t) ver.vocab()); if (!ver.copy_logits(t, row.data()) || token < 0 || (size_t) token >= row.size()) { std::printf("LP nan\n"); return; } float mx = -INFINITY; for (const float v : row) mx = std::max(mx, v); double se = 0.0; for (const float v : row) se += std::exp((double) v - (double) mx); const double lse = (double) mx + std::log(se); std::printf("LP %.6f", (double) row[(size_t) token] - lse); if (!allowed.empty()) { // Only the ids the caller named; the server renormalises over them, which is what allowed_token_ids means. // The server refuses an id past the vocabulary with a 400 only when it can read the vocabulary size from the // tokenizer. The engine's own vocab() is the authority: an id past it is left off the line, so the logits // are never read out of bounds. for (const int32_t id : allowed) { if (id == token || id < 0 || (int64_t) id >= ver.vocab()) continue; std::printf(" %d:%.6f", (int) id, (double) row[(size_t) id] - lse); } std::printf("\n"); return; } if (k > 0) { static std::vector ord; ord.resize(row.size()); for (size_t v = 0; v < row.size(); ++v) ord[v] = (int32_t) v; const int kk = std::min(k, (int) row.size()); std::partial_sort(ord.begin(), ord.begin() + kk, ord.end(), [&](int32_t a, int32_t b) { return row[(size_t) a] > row[(size_t) b]; }); for (int j = 0; j < kk; ++j) std::printf(" %d:%.6f", ord[(size_t) j], (double) row[(size_t) ord[(size_t) j]] - lse); } std::printf("\n"); } namespace { namespace nib = strata::core::nibble; // llama.cpp's MMQ prompt kernels are in this build (STRATA_PREFILL_MMQ, defined on strata_prefill only): the start-up lines that name them ask #if defined(STRATA_PREFILL_MMQ) [[maybe_unused]] constexpr bool kMmqBuilt = true; #else [[maybe_unused]] constexpr bool kMmqBuilt = false; #endif // Uploads each device's latent D/U tables before its expert cache is sized. // Prefill and verify share these copies; non-latent packs allocate nothing. struct LatentTab { strata::core::LatentDense dense; std::vector labels; // (n_layers * E) group labels, read from labels.bin beside the A pack int64_t lat_H = 0, lat_ELL = 0, lat_I = 0; int lat_G = 8, lat_E = 0; bool latent = false; bool load(const strata::core::ModelGeometry& g, std::string& err, int64_t lb = 0, int64_t le = -1) { int device = 0; if (cudaGetDevice(&device) != cudaSuccess) { err = "latent dense: no current device"; return false; } auto& shared = strata::core::latent_shared(); if (shared.d != nullptr) { if (shared.u == nullptr || (le >= 0 && (lb < shared.first_layer || le > (shared.end_layer < 0 ? g.n_layers : shared.end_layer)))) { err = "latent dense: the shared tables do not cover the requested layer range"; return false; } return true; } if (le < 0) le = g.n_layers; if (lb < 0 || lb >= le || le > g.n_layers) { err = "latent dense: invalid layer range"; return false; } const auto& lay0 = strata::kernels::cpu::expert_layout(); if (!(lay0.native && !lay0.fmt.empty() && lay0.fmt[0].n_embd != (int64_t) g.n_embd)) return true; latent = true; lat_H = (int64_t) g.n_embd; lat_ELL = lay0.fmt[0].n_embd; lat_I = lay0.fmt[0].n_ff; lat_E = (int) g.n_expert; const char* f = std::getenv("STRATA_LATENT_DENSE"); if (f == nullptr || f[0] == 0) { err = "the latent layout needs STRATA_LATENT_DENSE="; return false; } if (!dense.open(f, g.n_layers, 8, (int64_t) g.n_embd, lay0.fmt[0].n_embd, err)) { err = "latent dense: " + err; return false; } { // labels.bin beside the A pack (STRATA_LATENT_A): one int32 group label per (layer, expert) const char* apack = std::getenv("STRATA_LATENT_A"); if (apack == nullptr || apack[0] == 0) { err = "latent dense: STRATA_LATENT_A is required"; return false; } std::string lp = apack; const size_t slash = lp.find_last_of('/'); lp = slash == std::string::npos ? std::string("labels.bin") : lp.substr(0, slash + 1) + "labels.bin"; std::FILE* lf = std::fopen(lp.c_str(), "rb"); if (lf == nullptr) { err = "latent dense: " + lp + " missing"; return false; } labels.resize((size_t) g.n_layers * (size_t) g.n_expert); const size_t got = std::fread(labels.data(), sizeof(int32_t), labels.size(), lf); std::fclose(lf); if (got != labels.size()) { err = "latent dense: " + lp + " is too small"; return false; } } const uint64_t db = (uint64_t) (le - lb) * dense.d_bytes(), ub = (uint64_t) (le - lb) * dense.u_bytes(); uint8_t *d = nullptr, *u = nullptr; if (cudaMalloc((void**) &d, db) != cudaSuccess || cudaMalloc((void**) &u, ub) != cudaSuccess) { const cudaError_t ce = cudaGetLastError(); if (d) { cudaFree(d); d = nullptr; } if (u) { cudaFree(u); u = nullptr; } err = std::string("the latent D/U device buffers could not be had (") + cudaGetErrorString(ce) + ")"; return false; } for (int64_t l = lb; l < le; ++l) if (cudaMemcpy(d + (size_t) (l - lb) * dense.d_bytes(), dense.d(l), dense.d_bytes(), cudaMemcpyHostToDevice) != cudaSuccess || cudaMemcpy(u + (size_t) (l - lb) * dense.u_bytes(), dense.u(l), dense.u_bytes(), cudaMemcpyHostToDevice) != cudaSuccess) { cudaFree(d); cudaFree(u); err = "the latent D/U upload failed at layer " + std::to_string(l); return false; } shared = {d, u, lb, le}; std::fprintf(stderr, "strata generate: CUDA%d latent D/U layers %lld-%lld: %llu MiB\n", device, (long long) lb, (long long) le - 1, (unsigned long long) ((db + ub) >> 20)); return true; } } lat_tab; // Windows' WDDM driver model: native Windows, or WSL2 (its GPU goes through /dev/dxg to the Windows driver). There, // pinning a large arena into two CUDA contexts leaves WDDM refusing every later allocation (the 5080 + 3090 rig); // a Linux driver has no such limit (#253: the 8 GiB cap cost a 4090 + 3060 split 3x of its prompt speed). bool under_wddm() { #ifdef _WIN32 return true; #else static const bool dxg = std::filesystem::exists("/dev/dxg"); return dxg; #endif } // #620 #486: " (N MiB of M MiB VRAM free on this GPU)" for an allocation's failure message (clears the error first) // How many cache slots a prompt-path loan leaves behind (128 on a card with room; a card too short for that lends against 16, see the cache sizing). static int64_t g_lend_keep = 128; // May a start short of VRAM be moved off the GPU (strata/core/spill_gate.hpp)? A discrete card only: not Metal, not an integrated GPU (Strix Halo and the other APUs share the host's RAM). static bool spill_discrete_gpu() { #if defined(STRATA_GPU_METAL) return strata::spill_allowed(true, false); #else static const bool ok = [] { int d = 0; cudaDeviceProp pr{}; if (cudaGetDevice(&d) != cudaSuccess || cudaGetDeviceProperties(&pr, d) != cudaSuccess) { (void) cudaGetLastError(); return false; } return strata::spill_allowed(false, pr.integrated != 0); }(); return ok; #endif } std::string vram_free_note() { (void) cudaGetLastError(); size_t free_b = 0, total_b = 0; if (cudaMemGetInfo(&free_b, &total_b) != cudaSuccess) { (void) cudaGetLastError(); return {}; } char buf[96]; std::snprintf(buf, sizeof buf, " (%llu MiB of %llu MiB VRAM free on this GPU)", (unsigned long long) (free_b >> 20), (unsigned long long) (total_b >> 20)); return buf; } // The plain reason for an out-of-memory in the loads that follow the request slots' sessions (the draft layer, the native head): with --batch N // those N sessions came out of the card before the cache was sized, and a card that is short for them has nothing left for these. std::string vram_batch_hint(const std::string& err, int batch) { if (batch < 2 || err.find("out of memory") == std::string::npos) return {}; char buf[320]; std::snprintf(buf, sizeof buf, "; this start keeps %d request slots (--batch %d), each a session of its own, so the card is too small for them at this context: " "use a smaller --max-context or fewer --batch slots", batch, batch); return buf; } #if defined(__linux__) // STRATA_CRASH_BT=1 (research): a fatal signal prints the call stack to stderr (the addresses go through addr2line -e ) namespace { char g_crash_path[512] = ""; void crash_bt_handler(int sig) { void* frames[48]; const int n = backtrace(frames, 48); const char msg[] = "strata: fatal signal, call stack:\n"; int fd = 2; if (g_crash_path[0] != '\0') { const int f = open(g_crash_path, O_WRONLY | O_CREAT | O_APPEND, 0644); if (f >= 0) fd = f; } (void) !write(fd, msg, sizeof msg - 1); backtrace_symbols_fd(frames, n, fd); signal(sig, SIG_DFL); raise(sig); } const bool crash_bt_installed = [] { const char* v = std::getenv("STRATA_CRASH_BT"); if (v == nullptr || v[0] == '\0' || v[0] == '0') return false; if (v[0] != '1' || v[1] != '\0') std::snprintf(g_crash_path, sizeof g_crash_path, "%s", v); for (int sg : {SIGFPE, SIGSEGV, SIGBUS, SIGABRT}) signal(sg, crash_bt_handler); return true; }(); } // namespace #endif #if defined(STRATA_USE_HIP) && defined(__linux__) // EXIT (kfd_quiet.hpp), integrated gfx11 under Linux only: SIGTERM / SIGINT / SIGHUP no longer end the process with kernels in flight // and the arena registered (the kernel's exit then evicts busy queues: reset 45 on p2006). The handler only writes the signal's // number into a pipe; a thread of its own stops the request, releases the verify windows' GPU waits, waits at most 3 s for the // device, drops the arena's registration only when the device finished, and then ends the process by the same signal (the same // wait status as before). Installed only once the card is known to be of that class, only for a signal whose action is still the // default (nohup's ignored SIGHUP stays ignored); no signal mask is changed. A second signal during the stop ends it at once. namespace kfdq_exit { std::atomic*> g_stop{nullptr}; // the serve loop's STOP flag while it exists int g_pipe[2] = {-1, -1}; volatile sig_atomic_t g_count = 0; int g_dev = 0; void handler(int sig) { if (strata::core::kfd_quiet::on_signal((int) g_count) == strata::core::kfd_quiet::OnSignal::DefaultAction) { signal(sig, SIG_DFL); raise(sig); return; } g_count = g_count + 1; const unsigned char b = (unsigned char) sig; (void) !write(g_pipe[1], &b, 1); } [[noreturn]] void stop_and_end(int sig) { using clk = std::chrono::steady_clock; const clk::time_point base = clk::now(); auto now = [&] { return std::chrono::duration(clk::now() - base).count(); }; auto stop = [] { if (std::atomic* f = g_stop.load()) f->store(true); }; auto release = [](int ms) { return strata::core::release_gpu_waits_within(ms); }; auto drain = [](int ms) { struct Shared { std::mutex mu; std::condition_variable cv; bool done = false, ok = false; }; auto sh = std::make_shared(); std::thread([sh] { // may never return on a GPU that hangs: the wait below is bounded, the process ends anyway (void) cudaSetDevice(g_dev); const bool ok = cudaDeviceSynchronize() == cudaSuccess; std::lock_guard lk(sh->mu); sh->done = true; sh->ok = ok; sh->cv.notify_all(); }).detach(); std::unique_lock lk(sh->mu); sh->cv.wait_for(lk, std::chrono::milliseconds(ms), [&] { return sh->done; }); return sh->done && sh->ok; }; int ranges = 0; auto unreg = [&] { ranges = strata::core::unregister_arena_ranges(); }; const strata::core::kfd_quiet::TeardownResult r = strata::core::kfd_quiet::teardown(stop, release, drain, unreg, now, strata::core::kfd_quiet::kExitBoundS); if (std::getenv("STRATA_TRACE") != nullptr) std::fprintf(stderr, "strata trace: kfd quiet: signal %d: waits released %s, device drained %s, %d arena ranges unregistered, %.0f ms\n", sig, r.released ? "yes" : "no", r.drained ? "yes" : "no", ranges, now() * 1000.0); std::fflush(stdout); std::fflush(stderr); signal(sig, SIG_DFL); raise(sig); _exit(128 + sig); } void install(int dev) { g_dev = dev; if (pipe2(g_pipe, O_CLOEXEC) != 0) return; std::thread([] { strata::platform::name_this_thread("strata-stop"); unsigned char b = 0; for (;;) { const ssize_t n = read(g_pipe[0], &b, 1); if (n == 1) stop_and_end((int) b); if (n < 0 && errno == EINTR) continue; if (n <= 0) return; } }).detach(); for (int sig : {SIGTERM, SIGINT, SIGHUP}) { struct sigaction old{}; if (sigaction(sig, nullptr, &old) != 0 || (old.sa_flags & SA_SIGINFO) || old.sa_handler != SIG_DFL) continue; struct sigaction sa{}; sa.sa_handler = handler; sigemptyset(&sa.sa_mask); sa.sa_flags = SA_RESTART; (void) sigaction(sig, &sa, nullptr); } } } // namespace kfdq_exit #endif // STRATA_PIPE_BYIELD_NODRAIN=1 (read once; off by default): with the pipelined groups, a BYIELD that reaches the main // loop is dropped without draining the groups first. A pipelined read never gives way (batch_read_piece), so the // BYIELD is for a read that has ended, and the drain (and the refill after it) did nothing for it bool pipe_byield_nodrain_env() { static const bool on = [] { const char* v = std::getenv("STRATA_PIPE_BYIELD_NODRAIN"); return v && v[0] != '0'; }(); return on; } // STRATA_ADMIT_MERGE_FIRST=1 (read once; off by default): a batch admission reads the last prompt tokens of its last // windowed part (up to a window's max_t, the last prompt token included) and its first token in ONE window instead of // the part's last windows and a window of the last token alone. A row computes what it computes in any window while // every expert is in VRAM, and row T-1 is the first window's position with its history and its Philox draw, so the // token and the state are the same; the rows before it commit as the prompt windows commit them bool admit_merge_first_env() { static const bool on = [] { const char* v = std::getenv("STRATA_ADMIT_MERGE_FIRST"); return v && v[0] != '0'; }(); return on; } // STRATA_CKPT_POOL=1 (read once; off by default): the serve loop keeps the running-state vectors of the conversation // checkpoints it drops (evicted, pruned, a batch slot's old one) and saves the next checkpoint into them, so a save // resizes nothing (no zero-fill of ~118 MB of fresh vectors) and a slot's copy reuses their pages. Every byte is // overwritten by the copy, so the checkpoints are the same bool park_async_env() { // STRATA_PARK_ASYNC (strata/core/conversation_snapshot.hpp) static const bool on = [] { const char* v = std::getenv("STRATA_PARK_ASYNC"); return v != nullptr && v[0] == '1'; }(); return on; } // STRATA_CKPT_POOL: unset = the engine's default (on in a single-stage serve with a conversation cache: park_pool_plan), 0 = off, any // other value = on. -1 unset, 0 off, 1 on (read once) int ckpt_pool_env_state() { static const int state = [] { const char* v = std::getenv("STRATA_CKPT_POOL"); return v ? (v[0] != '0' ? 1 : 0) : -1; }(); return state; } bool ckpt_pool_env() { return ckpt_pool_env_state() == 1; } // STRATA_CKPT_POOL_READY=N (opt-in, N = 1..16, read once; only with the pool on, STRATA_CKPT_POOL): the pool keeps N ready // checkpoints, each a running-state image with its pages in (~118 MB on Qwen3.8-Flash-Next), allocated on a background // thread after any take. Unset: the pool holds the dropped checkpoints only, as with STRATA_CKPT_POOL=1 before - that // variable alone allocates nothing ahead of time and its value is not a count. // The engine's own count when STRATA_CKPT_POOL_READY is unset (park_pool_plan, set once at the start of a serve with a cache) std::atomic& ckpt_pool_ready_default() { static std::atomic n{0}; return n; } size_t ckpt_pool_ready_env() { static const long env = [] { const char* v = std::getenv("STRATA_CKPT_POOL_READY"); return v ? std::atol(v) : -1L; }(); if (env < 0) return ckpt_pool_ready_default().load(); return env >= 1 ? (size_t) std::min(16L, env) : (size_t) 0; } // how many dropped checkpoints the pool keeps (a batch admission drops and takes about two): 2, or more when STRATA_CKPT_POOL_READY asks size_t ckpt_pool_cap_env() { return std::max(2, ckpt_pool_ready_env()); } // STRATA_PARK_SEGPOOL_MIB=N (read once; Linux only, inert where the OS layer is not written - Windows, macOS): the host buffers of parked // conversations (K/V segments of 512 KiB and more) come from one arena of N MiB (at most a quarter of the conversation cache) that a // background thread makes resident, so a park's first touch of fresh pages is paid once at start instead of at every park (include/ // strata/core/conversation_segment_pool.hpp). Unset: the engine's default, min(2 GiB, a quarter of the cache) in 64 MiB steps // (park_pool_policy.hpp); 0: off (a diagnostic switch). Its idle bytes count against --conversation-cache-mib and are given back // before any parked conversation is evicted and before the RAM floor is reached. Every byte a park writes is the same; only where // the buffers live differs. -1: unset. long long park_segpool_env_mib() { static const long long mib = [] { const char* v = std::getenv("STRATA_PARK_SEGPOOL_MIB"); if (v == nullptr) return -1LL; const long long n = std::atoll(v); return n > 0 ? n : 0LL; }(); return mib; } // STRATA_CKPT_THREADS=1 (read once; off by default): a layer split's checkpoint saves every stage's part at once, the // first on the calling thread and each later stage's on a thread of its own device (kept for the process: the copies' // private streams are per thread), instead of one stage after the other. Each part is the same copy of the same state bool ckpt_threads_env() { static const bool on = [] { const char* v = std::getenv("STRATA_CKPT_THREADS"); return v && v[0] != '0'; }(); return on; } // STRATA_SLOT_CKPT_MOVE=1 (read once; off by default): a batch admission MOVES its own turn checkpoint into the slot // instead of copying it (~112 MB of host vectors). The main session's chain no longer holds it, so the request path // looks for it in the slots' checkpoints too: while the main session's cells still hold its tokens it is restored there // as before (no K/V copy), else an active slot holding it gives it back like an idle one (a second request with the // same history). The same bytes are restored from another container, so the tokens are the same. It keeps the // dropped checkpoints' storage as STRATA_CKPT_POOL does (the slot's old checkpoint is the next save's) bool slot_ckpt_move_env() { static const bool on = [] { const char* v = std::getenv("STRATA_SLOT_CKPT_MOVE"); return v && v[0] != '0'; }(); return on; } // STRATA_SLOT_COPY_BATCHSYNC=1 (read once; off by default): the direct slot copy (STRATA_SLOT_COPY_DIRECT) only queues // its copies on each device's private copy stream and synchronizes every device once at the end, instead of waiting // for each of its ~116 copies. A streamed K/V state's residency refresh waits for its copies through an event. The // same copies in the same order on one stream, so the slot holds the same bytes bool slot_copy_batchsync_env() { static const bool on = [] { const char* v = std::getenv("STRATA_SLOT_COPY_BATCHSYNC"); return v && v[0] != '0'; }(); return on; } // perf-review D-4: the lent slots are refilled with queued copies and one wait; STRATA_REFILL_BLOCKING=1 waits on each // A file-backed arena on AMD (STRATA_ARENA_MMAP; the engine raises ROCclr's pin-in-place threshold, see main): an // adaptive swap copies one expert straight from the mapped file. Through ROCclr's staging that copy blocks the host // (decode windows of 150+ ms); instead the batch's pages are locked here for the async copies and unlocked when they // have landed (unpin_blobs), so the release that follows can hand them back. Neighbouring experts share a page and // a copy from a range only PART of which is registered fails ("invalid argument"), so the page ranges are merged // first and each merged span is registered once. A span that does not register is copied through the staging // path. Portable: a layer split copies to either card. // Whether pin_blobs locks anything (AMD on Linux with STRATA_ARENA_MMAP=1): the callers only gather the swaps' spans // then - `blob()` is not free (it counts reads, and the file tier may assemble the blob), so the default runs skip it. bool pin_blobs_on() { #if (defined(STRATA_USE_HIP) || defined(STRATA_HIP_GFX906)) && !defined(_WIN32) static const bool on = std::getenv("STRATA_ARENA_MMAP") && std::getenv("STRATA_ARENA_MMAP")[0] == '1'; return on; #else return false; #endif } // #884 (HIP, opt-in STRATA_HIP_ADAPT_KERNEL_COPY=1): an adaptive swap's host-to-device copy as a kernel on the refill stream // instead of a copy-engine (SDMA) memcpy. 2x RX 6900 XT hung after a long prompt only with the MMQ prompt path, adaptive swaps // AND SDMA together (any one off avoids it; the barrier packet that never passes is a ROCm-side problem, #884). This keeps // the swaps off SDMA without turning SDMA off for the prompt read (HSA_ENABLE_SDMA=0 costs 10-24% of it). Needs the source to // be mapped, 16-byte aligned memory (the registered arena); anything else takes the normal cudaMemcpyAsync. cudaError_t adapt_copy_h2d(void* dst, const void* src, size_t bytes, cudaStream_t st) { #if defined(STRATA_USE_HIP) static const bool kernel = [] { const char* e = std::getenv("STRATA_HIP_ADAPT_KERNEL_COPY"); const bool on = e != nullptr && e[0] == '1'; if (on) std::fprintf(stderr, "strata: STRATA_HIP_ADAPT_KERNEL_COPY=1: adaptive swaps copy with a kernel, not SDMA (#884)\n"); return on; }(); if (kernel && bytes % 16 == 0 && ((uintptr_t) src & 15) == 0 && ((uintptr_t) dst & 15) == 0) { void* dsrc = nullptr; if (cudaHostGetDevicePointer(&dsrc, const_cast(src), 0) == cudaSuccess && dsrc != nullptr) { strata::kernels::copy_from_mapped((float*) dst, (const float*) dsrc, (int64_t) (bytes / 4), (void*) st); return cudaGetLastError(); } (void) cudaGetLastError(); // not registered / not mapped: the ordinary copy } #endif return cudaMemcpyAsync(dst, src, bytes, cudaMemcpyHostToDevice, st); } int pin_blobs(std::vector> r, std::vector& live) { int failed = 0; // ranges left pageable (a copy from them still works, through the driver's staging) #if (defined(STRATA_USE_HIP) || defined(STRATA_HIP_GFX906)) && !defined(_WIN32) if (!pin_blobs_on() || r.empty()) return 0; for (auto& [a, e] : r) { a &= ~(uintptr_t) 4095; e = (e + 4095) & ~(uintptr_t) 4095; } std::sort(r.begin(), r.end()); size_t k = 0; for (size_t i = 1; i < r.size(); ++i) { if (r[i].first <= r[k].second) r[k].second = std::max(r[k].second, r[i].second); else r[++k] = r[i]; } r.resize(k + 1); for (const auto& [a, e] : r) { if (cudaHostRegister((void*) a, (size_t) (e - a), cudaHostRegisterReadOnly | cudaHostRegisterPortable) == cudaSuccess) live.push_back((void*) a); else { (void) cudaGetLastError(); ++failed; } } #else (void) r; (void) live; #endif return failed; } void unpin_blobs(std::vector& v) { for (void* p : v) (void) cudaHostUnregister(p); (void) cudaGetLastError(); v.clear(); } // STRATA_RSS_TRACE=1: the process's mapped file pages (the arena) at a startup step - who reads the arena back void rss_probe(const char* where) { static const bool on = std::getenv("STRATA_RSS_TRACE") != nullptr; if (!on) return; FILE* f = std::fopen("/proc/self/status", "r"); if (!f) return; char line[256]; long long kb = -1; while (std::fgets(line, sizeof line, f)) if (std::strncmp(line, "RssFile:", 8) == 0) { kb = std::atoll(line + 8); break; } std::fclose(f); std::fprintf(stderr, "strata rss: %s: RssFile %.2f GiB\n", where, (double) kb / (1024.0 * 1024.0)); std::fflush(stderr); } bool refill_blocking() { static const bool v = std::getenv("STRATA_REFILL_BLOCKING") != nullptr; return v; } using Clock = std::chrono::steady_clock; // --pipeline-windows: every STRATA_PIPELINE_* test and tuning variable (THETA, FORCE_MISS, SWITCH, LOG, TRACE, DOOM_SKIP, // LOOKUP_PON, PRESTAGE, AGREE, SNAP_OVERLAP, SPEC_DEPTH) is read only with STRATA_PIPELINE_DEBUG=1; without it the // defaults apply. static const char* pipe_dbg_env(const char* name) { static const bool on = [] { const char* v = std::getenv("STRATA_PIPELINE_DEBUG"); return v != nullptr && v[0] != 0 && v[0] != '0'; }(); return on ? std::getenv(name) : nullptr; } // The resident RAM mode and the adaptive tier. A swap copies `in` (held in RAM) into the slot of `out` (held only // by that slot). Before the slot is overwritten, `out`'s bytes are copied back from it into an exchange buffer, so // the CPU computes `out` from RAM while the swap is in flight; when the swap has landed, `commit_exchanges` moves // them into `in`'s place in RAM. The RAM copy then again holds exactly the experts no core slot does, and no swap // reads the file. Swaps that need no exchange (`out` in the lend region is held in RAM already; or `in` is not) go // on as before; ones beyond the buffers' room wait for a later round. Runs on the adaptive tier's thread while the // GPU commits and drafts: the copies back are on its stream, and waited for before the refills are queued. // // With a layer split, `host_res` holds slot numbers of WHICHEVER cache owns the layer, so the copy back must read the // owning card's cache on that card's stream: `locate(layer)` names them (cache, stream, device; -1 = CUDA0). Reading // a later stage's slot number out of CUDA0's cache copied another expert's bytes into RAM - the resident mode with a // split then computed some experts from the wrong weights after the first adaptive swaps (garbage output). struct SwapHome { strata::core::ExpertCache* cache; cudaStream_t stream; int dev; }; template bool resident_stage_swaps(strata::core::FileExpertSource& src, const std::vector& host_res, int64_t n_expert, std::vector& swaps, Locate locate) { if (!src.complement_ready() || swaps.empty()) return true; struct Staged { int32_t layer, in, out; int64_t q; }; std::vector staged; std::vector used; std::vector kept; kept.reserve(swaps.size()); for (const Swap& s : swaps) { if (!src.has_resident(s.layer, s.in) || src.has_resident(s.layer, s.out)) { kept.push_back(s); continue; } const int64_t q = (int64_t) staged.size(); if (q >= src.exchange_capacity()) continue; const int32_t slot = host_res[(size_t) s.layer * (size_t) n_expert + (size_t) s.out]; if (slot < 0) continue; const SwapHome home = locate(s.layer); const strata::core::OnDevice on(home.dev); nib::guard_raw(s.layer, "the adaptive tier's copy back (resident_stage_swaps)"); if (const cudaError_t e = cudaMemcpyAsync(src.exchange_buffer(q, s.layer), home.cache->device_slot(slot), (size_t) strata::kernels::cpu::expert_layout().blob_bytes(s.layer), cudaMemcpyDeviceToHost, home.stream); e != cudaSuccess) { std::fprintf(stderr, "strata: copy back of layer %d slot %d (device %d) failed: %s\n", (int) s.layer, (int) slot, home.dev, cudaGetErrorString(e)); return false; } bool seen = false; for (const SwapHome& u : used) seen = seen || u.stream == home.stream; if (!seen) used.push_back(home); staged.push_back({s.layer, s.in, s.out, q}); kept.push_back(s); } if (!staged.empty()) { for (const SwapHome& u : used) { const strata::core::OnDevice on(u.dev); if (const cudaError_t e = cudaStreamSynchronize(u.stream); e != cudaSuccess) { std::fprintf(stderr, "strata: copy back sync (device %d) failed: %s\n", u.dev, cudaGetErrorString(e)); return false; } } for (const Staged& x : staged) if (!src.stage_exchange(x.layer, x.in, x.out, x.q)) { std::fprintf(stderr, "strata: stage_exchange refused layer %d in %d out %d\n", (int) x.layer, (int) x.in, (int) x.out); return false; } } swaps.swap(kept); return true; } struct Options { std::string pack = "pack/full"; std::vector tokens; // the prompt, PRE-TOKENIZED int64_t max_new = 16; int64_t max_context = 4096; bool greedy = true; uint64_t seed = 0; int top_k = 20; float top_p = 0.95f; float temperature = 1.0f; std::string dump_logits; // one line of logits per generated position int64_t logits_stride = 1; // storage selection; all prompt tokens remain conditioned /// **THE RESIDUAL, SO THE HEAD CAN BE CHECKED WITHOUT THE LAYERS.** /// /// C1 fails (LEDGER L116) and the pipeline is `embed -> 48 layers -> head`. Dumping `R` splits it in half: /// the head is one norm, two bf16 projections and one 794 MB GEMV, all of which can be recomputed in Python /// from the manifest. If Python agrees with the engine on the same `R`, the head is right and the layers /// are wrong; if it disagrees, the head is wrong. Nothing else in the engine can be split that cheaply. std::string ple_gguf; // the ORIGINAL second GGUF shard: the PLE table is not in the pack bool no_ple = false; // explicit diagnostic ablation; never a normal inference default bool stream_token = false; // R2.6 experiment: ordered work on the session stream bool check_logits = false; // optional full-vocabulary finite scan bool gr_fp32_activations = false; // pinned CUDA single-token BF16 activation contract bool gr_native_mmvf = false; // pinned projection reduction tree as well as FP32 inputs bool native_bf16 = false; // SSM gates, router and indexer projections only bool native_bf16_extra = false; // PLE value and shared expert scalar gate bool native_ple_key = false; // unchanged Q2_0 key and CUDA Q8_1 activations bool native_moe_combine = false; // pinned fused CUDA weighted reduction bool native_gdn = false; // pinned CUDA recurrence and preprocessing bool native_flash_attn_short = false; // diagnostic pinned attention, context <=256 bool native_qsa_indexer = false; // pinned F16 key cache and F32 pooling bool native_qsa = false; // pinned F32 QSA norms and gate /// THE CONTEXT EXTENSION (rope scaling, rope_scaling.hpp). These knobs resolve to ONE process config, /// set once before `session_init` builds the rope table and the graphs capture the kernels. There is /// deliberately no per-request form: K sits in the cache POST-RoPE, so one cache must never mix two /// scalings. Precedence: an EXPLICIT flag over the model file's rope keys over the struct defaults - /// `none` and `1` are explicit values (the opt-outs), the absent flag is not. std::string rope_scaling; ///< --rope-scaling none|linear|yarn (llama.cpp's names); empty = the flag is absent double rope_scale = 0; ///< --rope-scale F: the extension factor; 0 = the flag is absent (the model file's, else 1 = off) double rope_freq_base = 0; ///< --rope-freq-base N: 0 = the model's (1e7) double rope_freq_scale = 0; ///< --rope-freq-scale F: the raw ggml knob; 0 = 1/--rope-scale double yarn_orig_ctx = 0; ///< --yarn-orig-ctx N: 0 = the model's, else 262144 double yarn_ext_factor = -1.0; ///< --yarn-ext-factor F: <0 = auto (1 for yarn, 0 otherwise) double yarn_attn_factor = 1.0; ///< --yarn-attn-factor F double yarn_beta_fast = 32.0; ///< --yarn-beta-fast F double yarn_beta_slow = 1.0; ///< --yarn-beta-slow F bool native_rope = false; // pinned text-only CUDA rotary arithmetic bool native_ple_postops = false; // pinned PLE postprojection arithmetic bool native_router = false; // pinned fused 512-expert top-10 router bool cpu_oracle_q8_0 = false; // pinned x86 activation scales/codes at both expert stages std::string native_head_gguf; // native output.weight experiment; same model shard as the pack std::vector native_dense_gguf; // repeat for native GDN/QSA projection shards /// Every shard of --native's model (strata::gguf_split_paths: the metadata shard first; a missing shard is an /// error) and of --native-head-gguf's (the same list unless that names another model). std::vector native_shards, native_head_shards; /// Plan v0.3 P1: the whole native arithmetic set as ONE switch (model shard 1). It enables exactly the /// combination recorded in bench/results/2026-09-23-attention-ple plus the native indexer, and never the /// <=256-token attention adapter. It becomes the default once P0 shows it is not slower. std::string native_preset; /// The token embedding from this GGUF instead of --native's (tools/embd_bf16_pack.py: BF16 as shipped) std::string embd_gguf; /// Plan v0.3 P2: how the n-gram table is read. Direct (default) = unbuffered SSD reads, table never in RAM. std::string ple_io = "direct"; bool ple_io_explicit = false; ///< --ple-io was given: the engine only warns when direct measures slow int64_t ple_row_cache = 1 << 20; ///< bounded row cache (rows of 90 B); 0 disables int ple_inflight = 256; // the prompt path reads a chunk's rows at once: 64 left the SSD half idle (32K: 303 -> 189 ms) double ple_delay_us = 0; ///< fault injection: every row read completes no earlier than this 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. std::string dump_mixed; /// One residual snapshot per layer per position: `n_layers * hc * n_embd` floats per position, appended in /// position order. This is the C1 BISECTION LADDER - it is what `llama-debug --tensor-filter l_last` prints /// for the reference, so the first layer whose `sum` diverges is the layer that holds the bug. It needs the /// captured path (the expert pool only exists there), so it is refused with `--no-capture`. std::string dump_layers; /// `2 * n_embd + 2 * hc` floats per layer per position: the attention half's block output, the MoE half's, /// and the two injection vectors. It separates `linear_attn_out-` from `ffn_out-`, which the residual /// ladder cannot. **CAPTURED INTO THE LAYER GRAPHS**, so it must be armed before `session_capture`. std::string dump_halves; /// P0.S8's routing trace, and a prerequisite the Phase 3 plan names explicitly. One record per layer per /// position: `int32 layer, int32 k, k int32 ids, k float weights`. It is what a hit-rate curve for a /// candidate VRAM expert cache is computed from, and it needs no new kernels - the doorbell already /// publishes exactly this much to pinned memory. std::string dump_routing; bool no_capture = false; // run the layers directly instead of replaying graphs bool no_pool = false; // skip the CPU expert pool: the GPU-only floor bool sync_every_layer = false; /// Per-stage CUDA-event timings inside the layer halves. `--no-capture` only: an event recorded inside a /// stream capture is silently dropped, so the captured path cannot carry this. bool stage_timing = false; /// Launch the 48 captured `pre` graphs back to back with no host work between them and report the pure GPU /// time per token. This is the only measurement that separates host-bound from GPU-bound, because the /// stage events include every gap where the GPU waited for the host. bool graph_only = false; bool gpu_only_full = false; ///< R0.3: pre + post + head, the true per-token GPU floor int pool_workers = 0; ///< R2.2: 0 = "all physical cores minus the host's"; >0 overrides int pool_tasks = 0; ///< Batched CPU expert tasks per phase; 0 keeps the existing policy /// #272: the pool's core layout; `all` (the default) is the layout it always had, auto / p-cores are opt-in strata::kernels::cpu::PoolAffinity pool_affinity = strata::kernels::cpu::PoolAffinity::All; /// --pool-affinity measure (opt-in, hybrid CPUs, native packs): `all` and `p-cores` are timed on this pack's /// own experts at start and the faster layout is taken (measure_pool_affinity) bool pool_measure = false; /// --host-core first|last|sibling (STRATA_HOST_CORE): the host thread's core (see HostCore in pool.hpp) std::string host_core; /// --pool-cores LIST (STRATA_POOL_CORES; experimental, off by default): the logical processors the pool's workers are pinned to std::string pool_cores; /// --aux-cpus off|auto|LIST (STRATA_AUX_CPUS): where the non-pool, non-host threads run (strata/platform/aux_cpus.hpp) std::string aux_cpus; /// R2.2's first half, as an A/B arm. **ON by default**, because the measurement that justifies it is the /// pool's own drain: 33.7 GB/s against 5/6 x 44.14 = 36.8 for five workers, on a machine whose sixth core /// is reserved for a host thread that has nothing to do while the drain runs. bool no_host_worker = false; bool coupled_draft = strata::core::coupled_draft_env(); ///< Coupled draft sampling for MTP drafter under sampling bool mmap_experts = false; ///< R2.1: opt OUT of the resident arena, back to MapViewOfFile std::string shared_expert_arena; ///< Linux: optional file backing for the resident arena shared by processes bool resident_cpu_experts = false; ///< mmap-backed static-cache misses copied into ordinary RAM /// `--resident-experts` (the low-RAM PC's resident mode, chosen by setup): `--resident-cpu-experts` with the copy /// page-locked when the driver allows (else locked in the working set), 4 GiB of RAM headroom, and plain mmap /// (with a warning) when even the experts no slot holds do not fit. bool resident_pin = false; uint64_t resident_headroom = 8ull << 30; /// `--ram-keep-gib W` (or STRATA_RAM_KEEP_GIB): the RAM, in bytes, the person wants left free for their own work (0: none). The expert /// arena is used only if this much stays available after it; the RAM copy that replaces it, and the explicit RAM modes, leave /// max(this, their own headroom) free. STRATA_RESIDENT_HEADROOM_GIB, when set, still decides the headroom. ple_residency.hpp. uint64_t ram_keep = 0; bool resident_soft = false; bool resident_cpu_explicit = false; ///< #384: --resident-cpu-experts given by itself (not only implied) /// CS-T `--resident-budget-gib N`: the resident mode with a RAM budget - the N GiB of experts the GPU cache does /// not hold that the expert profile ranks hottest are copied into RAM, the rest are read from the files in place /// (the GGUF shards when the pack has no experts.bin). 0 = the whole complement (--resident-experts). uint64_t resident_budget = 0; /// R4: slots of VRAM-resident experts. **0 = off, and off is the default.** /// **THE COMMENT THAT USED TO BE HERE WAS FALSE AND ROUND 328 MEASURED IT.** It said "the cache has no /// consumer yet - `moe_hit_grouped_s2` does not exist - so switching it on costs the fill traffic and /// saves nothing". The kernel exists (`src/kernels/cuda/s2_expert_grouped.cu`), it is wired at line ~660 /// via `expert_hit_run`, and switching the cache on **does** move work off the CPU pool: the drain fell /// **19.076 -> 10.312 ms/token** at 4096 per-layer slots, for **-2.7 ms/token** end to end. What was /// true is that the ADMISSION POLICY gave every slot to the first position, which is why the earlier /// measurement found nothing - see `expert_cache_per_layer`. int expert_cache = 0; std::array expert_cache_remote{}; ///< CUDA1..3 slots; CUDA0 keeps dense/state/MTP std::array expert_cache_remote_auto{}; bool remote_expert_opt = false; ///< optional optimization of the existing remote-expert decode path std::string expert_cache_remote_placement = "stripe"; ///< stripe experts or assign complete layers to CUDA1..3 bool expert_cache_cpu_order = false; /// **R4.2g. ROUND 328 MEASURED THAT THE GLOBAL ADMISSION POLICY CANNOT WORK, AND THIS IS THE FIX.** /// The default policy hands out slots in arrival order from one counter shared by all 48 layers, so the /// first `n_slots` distinct pairs - about 26 LAYERS OF POSITION 0 - take every slot and hits are confined /// to them. Measured at 256 slots: **1781 of 60000 = 2.97%**, against **21.4%** for 8 slots per layer and /// **70.4%** for 64, from `Memory/cache_allocation.py` on the same run's routing. Off by default. bool expert_cache_per_layer = false; /// Multi-GPU: a second expert tier on CUDA device `peer_device` (-1 = off), `peer_reserve_mib` left free /// there, `peer_slots` caps its size (0 = as many as fit), `peer_adapt_swaps` per adaptive round /// (-1 = adapt_swaps). int peer_device = -1; int peer_reserve_mib = 600; int64_t peer_slots = 0; int peer_adapt_swaps = -1; /// the prompt path's rows per layer the peer computes: -1 = half of chunk x top-k, 0 = the prompt path stays on /// the primary int64_t peer_prefill_rows = -1; /// The PLE gather's prefetch, as an A/B arm. The gather measured 2.10-2.61 ms/token because its sixteen /// row reads are sixteen SEPARATE page faults into a 26.8 GB mapping; see `ple_prefetch_enable`. bool no_ple_prefetch = false; /// R4.2e: a `profile.bin` from `tools/make_profile.py`. **When given, it decides residency instead of the /// compulsory-miss policy**, which is the whole point: a profile ranked by routing frequency over a whole /// trace is what the plan's `h = 0.6447` refers to, and compulsory-miss measured 0.4864 because it fills /// with whatever the prompt touched FIRST. Empty means no profile. std::string expert_profile; /// #477 (--serve, opt-in): where to save what the adaptive tier learned, as a profile `--expert-profile` reads /// (the resident experts first, then the routing counted since the start); on QUIT and every /// `expert_profile_save_min` minutes between requests. Empty (the default): nothing is counted or written. std::string expert_profile_save; double expert_profile_save_min = 10.0; /// --serve, --draft-costs FILE (the server passes it; empty = off, the policy measures as before): the draft policy's window costs are /// a table learned once on this machine and then fixed, so the same request gives the same answer on every start. A file learned /// under another key (card, driver, engine, model, settings; draft_costs_key()) or a missing / broken one: this run learns a new one /// with today's adaptive policy and writes it once the stretch is long enough (strata/spec/draft_policy.hpp, CostLearner). /// --draft-costs-key TEXT: more of the key from the server (the engine file's identity, say). std::string draft_costs, draft_costs_key; /// R4.2d: **ON by default**, because the measurement is unambiguous and the alternative is known-broken. /// Without it, 17 of 10,562 layers had the hit work done when the pool returned; with it, 9,190. The /// A/B arm is `--no-hit-poke`. bool no_hit_poke = false; /// R0.9: capture each layer as THREE graphs and time them from outside the capture, which is the only /// valid way to get a per-stage table on the real graph. Prints and exits; it is a measurement, not a run. bool gpu_stages = false; bool stats = false; bool shared_late = false; ///< plan v0.3 P3 A/B: shared expert inside post[l] (old order) bool keep_canonical = false; ///< plan v0.3 P1 A/B: load canonical copies of natively served tensors bool no_token_graph = false; ///< plan v0.3 P3 A/B: two graphs per layer instead of one per token bool no_fused_gr = false; ///< plan v0.3 P3 A/B: the six-kernel native gr_read + separate gr_write bool no_fast_attn = false; ///< plan v0.3 P3 A/B: gather + one-block-per-head QSA attention bool no_publish_kernel = false; ///< plan v0.3 P3 A/B: memcpy nodes for the doorbell and QSA step bool no_fused_gdn = false; ///< plan v0.3 P3 A/B: llama.cpp-layout GDN step + separate out norm bool no_fast_select = false; ///< plan v0.3 P7 A/B: FP64 row scores + bit-serial cell top-k /// Plan v0.3 P4: `--expert-cache auto` sizes the VRAM tier from what is free after the weights, the session /// and the KV state, minus this reserve for the graphs, the hit scratch and the head. int vram_reserve_mib = 700; bool vram_reserve_given = false; ///< --vram-reserve-mib on the command line (#496: no smaller automatic reserve) /// #533 (opt-in): the expert cache in physical segments (CUDA virtual memory management), so the serve loop's /// `VRAM ` command can give part of it back to other programs and take it again. Off: one cudaMalloc. bool vram_elastic = false; int64_t vram_segment_mib = 512; /// `--vram-reserve-later-mib N`: the reserve on a layer split's later cards (default: the same as the first). /// A card that drives no display needs less than the one the monitors are on. int vram_reserve_later_mib = -1; /// Plan v0.3 P5: batched prompt processing in chunks of this many tokens (0 = the token path). int64_t prefill_chunk = 0; /// `--prefill auto`: the largest chunk (up to 8192) whose buffers the expert cache can lend. A chunk of /// stream_all_min tokens or more (1024 by default) streams every expert the GPU does not hold once, routed or not /// (a smaller one only the experts it routes to), so a bigger chunk streams fewer bytes per token (the "ubatch" /// effect). bool prefill_auto = false; /// #282, opt-in: the largest chunk `--prefill auto` may take - 8192 by default; `--prefill auto:16384` or /// `auto:32768` (or STRATA_PREFILL_AUTO_MAX) lets it go further, never past the context int64_t prefill_auto_max = 8192; /// #1630: a bare `--prefill auto` stops here on a Windows HIP build (0: no cap). A chunk the user names is not capped. int64_t prefill_auto_cap = 0; /// a bare `--prefill auto` (no ":N", no STRATA_PREFILL_AUTO_MAX): the gfx12 Linux rule below may raise its ceiling bool prefill_auto_bare = false; /// 0.2.8 (Strix Halo on Windows): the prompt path keeps its own buffers by default (no lending), so `--prefill auto` /// must not fall back to 2048 ("reserved buffers, keep them small") - the gfx1151 rule above has already chosen a /// chunk that fits this box's carve-out. bool prefill_own_keep_chunk = false; /// #1630's warning for a chunk the user named (8192 or more on a Windows HIP build), held until the device is known: it was printed at argument /// parsing, so it also appeared on the Strix Halo (gfx1151), where 8192 and 16384 are the measured default and a bare auto no longer stops at 6144. std::string prefill_cap_warn; bool prefill_cap_warn_skip = false; ///< set by the gfx1151 rule below: that card is not the 7900 XTX of #1630 bool prefill_gfx12_16k = false; ///< a default (gfx12 Linux: 32768, 0.2.10.1; NVIDIA cc 8.0+: 32768, round 0212) raised the auto chunk ceiling (a layer split takes 8192 back, 0.1.44) const char* prefill_raise_who = "gfx12"; ///< who raised it, for the log lines ("gfx12" or "NVIDIA") /// --prefill-pipe (opt-in): a layer split's prompt chunks sized for its pipeline (Prefill::pipeline_chunk): 0 off, /// 1 today's chunk count evened out, a number > 1 the rig's b/a in tokens (setup's --calibrate measures it). /// < 0: not given - STRATA_PREFILL_PIPE, else off. double prefill_pipe = -1.0; bool no_split_rows = false; ///< plan v0.3 P4 A/B: one whole expert per pool thread /// Plan v0.3 P5: the prompt path borrows the top expert-cache slots for its buffers and refills them after /// the prompt (default); `--no-prefill-borrow` reserves the buffers' VRAM for the whole session instead. bool no_prefill_borrow = false; /// Plan v0.3 P5 validation: batch only positions [0, P) and run the rest of the prompt through the token path /// (teacher-forced), so the logits of positions >= P - which depend on the batched state - can be scored /// against the oracle at many positions. 0 = the whole prompt but the last position. int64_t prefill_until = 0; /// Plan v0.3 P6: after every processed position, append the residual after the last layer (hc x n_embd /// floats, the MTP draft head's input) to this file. Token path only. std::string dump_final_r; /// Plan v0.3 P6: speculative decoding with a verify window of this many tokens (the last accepted token and /// spec-1 drafts); 0 = plain decode. `spec_oracle` drafts from a token file (the expected continuation, for /// the exactness test); `spec_corrupt` N > 0 replaces every Nth draft with a wrong token. #if defined(STRATA_GPU_METAL) int spec = 2; // Metal: a window of 2 by default (measured best on the M5 Max; an explicit --spec wins) #else int spec = 0; #endif /// --serve runs up to this many sequences at once, one token each per batch window (0 = off). A request /// sent as `BGEN ...` reads its prompt and its first token through the usual path, then /// continues in slot of the batch windows (`BT ` lines, then `BDONE ...`). int batch = 0; /// The --batch slots in this many groups pipelined through the stages of a layer split (stage k /// runs one group while stage k+1 runs another). 1 = every slot in one window, stage after stage. int batch_groups = 1; bool batch_groups_set = false; ///< --batch-groups was given (a number or auto): no default then bool batch_groups_auto = false; ///< --batch-groups auto (#417 stage 1): one group per stage of a layer split, if it divides --batch bool batch_mtp = false; ///< --batch-mtp / STRATA_BATCH_MTP=1 (opt-in): one MTP proposal per batch slot std::string spec_oracle; int spec_corrupt = 0; /// Benchmarks and A/B checks (eddoursul's fork, F19): the run emits this continuation (token ids) instead of /// the window's argmax, and a draft is accepted when it matches it, so runs with different speculation /// settings process the same text. std::string spec_follow; /// Per verify window: a line with its size, a hash of its final residual rows and its argmaxes. std::string window_hashes; /// Plan v0.3 P6: the MTP draft layer's runtime directory (tools/mtp_rt.py); drafts come from it. std::string mtp; int64_t mtp_window = 32768; ///< the draft layer attends to the last N cells (0 = every cell) /// Plan v0.3 P6: the share (0..1) of each layer's distinct missed experts the GPU reads over PCIe from the /// pinned arena while the CPU computes the rest (verify windows). double pcie_frac = -1.0; ///< < 0: the model's default (0.2 direct for the Q2_0 pack, 0.55 DMA for native packs) bool pcie_frac_auto = false; ///< single-GPU serve (CUDA + HIP/gfx1100), no --pcie-frac: the share is refined in the first decode windows (PcieAuto) double pcie_probe_gbps = 0.0; ///< the start-up probe's reading (for PcieAuto) std::string pcie_mode = "auto"; ///< auto | dma | kernel | direct /// Plan v0.3 P6: every `adapt_every` rounds, swap up to `adapt_swaps` of the most-routed missing experts into /// the VRAM tier in place of the least-routed resident ones (decayed counts). 0 = static residency. int adapt_every = 4; bool adapt_every_given = false; ///< --adapt-every was on the command line (the per-card warm-up interval below does not override it) int adapt_warm_every = 0; ///< dflash2-kern: > 0: the interval for the first adapt_warm_rounds verify rounds of a speculative run int64_t adapt_warm_rounds = 0; int adapt_iv(int64_t rounds) const { return adapt_warm_every > 0 && rounds < adapt_warm_rounds ? adapt_warm_every : adapt_every; } ///< the interval in force at verify round `rounds` float adapt_decay = 0.7f; ///< the usage counts are multiplied by this after each adaptation (--adapt-decay) /// --ram-adapt N: the RAM tier follows the decode's routing without the GPU tier (STRATA_RAM_ADAPT's swaps, up to N /// of them read from the file a window); --ram-adapt-decay F multiplies the counts each window (default 1: none) int ram_adapt = 0; float ram_adapt_decay = 1.0f; /// --ram-profile FILE: the RAM tier's own ranking (a --ram-profile-save file); the GPU cache keeps --expert-profile. /// --ram-profile-save FILE: before each request and at exit, the RAM copy's experts first, then the rest by /// --ram-adapt's routing counts std::string ram_profile, ram_profile_save; /// an expert is swapped into the VRAM tier only when its decayed routing count beats the one it replaces by more than /// this (--adapt-min-gain; both the blocking and the asynchronous tier) float adapt_min_gain = 1.5f; /// --adapt-async 1 (--serve with the resident RAM mode; opt-in): the adaptive tier's rounds advance between verify /// windows on a helper thread instead of one window waiting for a whole round (see the tier in the --serve block). /// Not bit-exact run to run. 0 = the blocking tier. int adapt_async = 0; int adapt_async_given = -1; ///< --adapt-async on the command line (-1: not given; then the engine may decide, adapt_async_default.hpp) bool adapt_async_self = false; ///< the engine measures and chooses the asynchronous tier during the session (adapt_async_default.hpp) /// Plan v0.3 P6: a draft enters the verify window only while every draft before it (and itself) has at least /// this probability under the draft layer; 0 = always --spec-1 drafts. double spec_min_p = 0.0; /// Stop when the model emits an end-of-turn token (<|endoftext|> 248044, <|im_end|> 248046, or --eos-ids). bool stop_eos = false; std::vector eos_ids = {248044, 248046}; bool spec_split = false; ///< opt-in split verify window (the overlap study: ~7% slower; not bit-exact against no-split, the batch shape of its windows differs) /// --serve, multi-GPU layer split: "K" or "K1,K2,.." (the first layer of each later stage) or "auto" (placed /// from each GPU's free VRAM); empty = one GPU std::string layer_split; /// the later stages' devices "D1,D2,.." (default: the next visible GPUs; "0" with one K: both stages on this /// GPU, sharing everything - the bit-exact A/B of the hand-off) std::string split_device; /// --split-skip-if-fits (opt-in; the server passes it for a config's "split_skip_if_fits"): with /// --layer-split auto, run on CUDA0 alone when it holds every profiled expert pair plus the whole session (KV), /// the drafter and the reserve - a split then only adds hand-offs (two RDNA4 cards: 1,384 vs 1,794 tok/s at 4K) bool split_skip_if_fits = false; /// Plan v0.3 P8: stay resident and take requests on stdin (see the --serve block in main). bool serve = false; /// The vision path: keep a per-cell (t, h, w) rotary position table so --serve can take GENI requests. bool vision = false; int adapt_swaps = 96; /// --serve: how many conversation checkpoints to keep between requests (0 = every request reads its whole /// prompt again, the v0.1.2 behaviour). One is the GDN recurrence of the 36 layers, the QSA indexer tails and /// the PLE history (~118 MB of host RAM); the KV cache itself is positional and stays where it is. int prompt_cache = 6; int64_t conversation_cache_mib = -1; // host RAM for independent conversations; -1: not given, --serve sizes it from the free RAM (#3493), 0: off int conversation_cache_slots = 4; int64_t conversation_cache_min_free_mib = 2560; /// --serve: park only conversations of at least this many tokens. Every parked conversation costs one of /// conversation_cache_slots whatever its length, so without it a client that interleaves short side requests /// with one long conversation evicts the long one (oldest first). 0 = park every conversation. int64_t conversation_cache_min_tokens = 0; /// --serve: park only after the conversation has advanced this many tokens past the copy it would supersede. /// A conversation that moved a few hundred tokens writes a full snapshot again, and the turn after that drops it /// (drop_superseded) after writing the same bytes once more, so on a long single conversation every turn pays a /// whole-snapshot copy for nothing. 0 = park every turn, as before. int64_t conversation_cache_park_gain = 0; /// --serve: the NVMe tier. Parked conversations the RAM budget evicts are written to this folder as session files /// (with --conversation-disk-gib above 0) and read back when a request continues one of them. std::string conversation_disk; int64_t conversation_disk_gib = 0; /// --memory-limit-mib N / STRATA_MEMORY_LIMIT_MIB: the total RAM this engine's container or cgroup may use, for a /// container that cannot see its real limit (0 or unset = none; the flag wins over the variable) int64_t memory_limit_mib = -1; /// --serve SAVE: disk space a session file must leave free where it is written (MiB; 0 = no check) int64_t session_min_free_mib = 4096; bool session_save_reclaim = false; /// --serve: also keep a checkpoint every N freshly read prompt tokens (0 = only at the last turn boundary) int64_t prompt_cache_every = 16384; bool prompt_cache_tail = false; // optional extra checkpoint at an existing near-tail chunk boundary bool prompt_cache_spread = false; ///< --prompt-cache-spread: keep checkpoints spread back from the end, not the latest /// --serve: a prompt read from token 0 is also checkpointed at its first turn boundary - the end of the system /// prompt, which every chat of the same client shares - when that is at least N tokens (0 = never) int64_t prompt_cache_root = 2048; /// --serve: the token that opens a chat turn (<|im_start|>). The last one in a prompt is where the chat's /// history ends and the new assistant turn begins, which is the checkpoint the next request can reuse. int64_t turn_token = 248045; /// --serve (#458, opt-in): the role token of a short turn the server puts right before the new assistant turn /// (the "system" of a trailing reasoning-effort turn). When the turn before the last <|im_start|> opens with it, /// the checkpoint goes in front of that turn instead, so it holds the conversation and not the effort text. /// -1 = off (the checkpoint at the last <|im_start|>, as before). int64_t tail_role_token = -1; /// --serve: a text part of the prompt of at most N tokens (a chat message, the assistant header, a short tool /// result) goes through the verify windows, S tokens at a time, instead of the batched prompt path (0 = always /// the batched path) int64_t short_read = 64; bool short_read_set = false; // --short-read given: the class default (Prefill::short_read_default) does not apply bool prefill_head_alias = false; // lend the native output head's VRAM to prompt buffers between request phases /// --pipeline-windows N (--serve, a layer split on exactly two GPUs; opt-in): 1 = a prompt's short reads through /// the verify windows run with the stages overlapped (stage 0 reads window K+1 while stage 1 reads window K); /// 2 = the decode windows too: stage 0 runs window K+1 speculatively while stage 1 verifies window K (rolled back /// when K is not accepted as guessed). 0 = off (the stages take turns). /// -1 (not asked for) = 2 on gfx12 (HIP) layer splits of 3 or more stages, else 0; --pipeline-windows N asks for it. int pipeline_windows = -1; /// A layer split: each card keeps the dense weights of its own layers only (the rest of the model's are another /// card's), and the VRAM this frees goes to its expert cache. --no-trim-stage-weights: every card keeps them all. bool trim_stage_weights = true; /// 1 = --trim-stage-weights was given, 0 = --no-trim-stage-weights, -1 = neither (the default trim is on). int trim_stage_flag = -1; /// The suffix drafter (prompt lookup): when the text being written repeats an earlier stretch of the context (code /// edits, quoted input, tool-call JSON) by at least this many tokens, the window may be filled with what followed /// it there instead of the MTP's drafts, where the MTP's own first guess agrees and the draft policy expects it to /// pay (strata/spec/draft_policy.hpp). On by default; 0 = MTP only. int suffix_draft = 3; /// The MTP's own window cap (0 = --spec): with --spec 6 --mtp-max-t 4 the long windows come from suffix matches. int mtp_max_t = 0; /// --lookup-chain K (opt-in, 0 = off): prompt lookup CHAINED after the MTP's proposal. The suffix drafter matches /// the context followed by the MTP's drafts and appends up to K of the tokens that followed that match to the same /// verify window (the window grows to at most 8). Greedy verification keeps the output; its own counts are kept. int lookup_chain = 0; int lookup_chain_min = 3; ///< --lookup-chain-min M: the shortest match (in tokens, drafts included) it extends on /// --lookup-max-t N (-1 = not given: 12 on a build whose windows hold 8 rows, one GPU, no batch / DFlash2 / lookup chain, owner decision /// 11-01 for #4040; 0 = off, the --spec + 2 rule): prompt-lookup windows up to N tokens (<= kVerifyLongT) while /// the MTP keeps its --spec windows. A copy-heavy turn (an edit that rewrites a file) accepts nearly every lookup /// draft, so its decode is bound by the window length. Each window size is a graph of its own (~20-35 MiB of /// VRAM), so only --lookup-sizes get one past the MTP's sizes; a size whose graph finds no VRAM is dropped. int lookup_max_t = -1; /// --lookup-sizes A,B,.. : the lookup window sizes above the MTP's (default with --lookup-max-t N: MTP+1, MTP+2, N) std::string lookup_sizes; /// --mtp-hnorm stream (opt-in): the draft layer's pre_fc_norm_hidden normalizes each hyper-connection stream on /// its own (llama.cpp's qwen4exp MTP graph) instead of one RMS over all four (the default, tools/mtp_probe.py). bool mtp_hnorm_stream = false; /// --mtp-q4 (opt-in): the draft layer's projections and draft head from 4-bit copies (fewer bytes per draft step) std::string mtp_q4; ///< "" (off), all, proj (the projections only) or head (the draft head only) /// --mtp-draft-vocab FILE (opt-in): the draft head's token subset from FILE instead of /draft_vocab.bin std::string mtp_draft_vocab; /// --draft dflash2 --draft-model PACK (opt-in, CUDA / HIP): the DFlash2 block drafter for Qwen3.8-Flash-Next (tools/dflash2_pack.py) drafts instead /// of the MTP layer, which is not loaded (--draft-fallback mtp loads it too, as the fallback). Needs --mtp DIR (its draft_vocab.bin), --spec, --draft-model and a native pack; DFlash2 that cannot start is an error unless the fallback is mtp. std::string draft, draft_model; /// --draft-fallback mtp|none (with --draft dflash2): none = the MTP layer is NOT loaded, DFlash2 is the only drafter (the draft vocabulary still comes /// from /draft_vocab.bin). A DFlash2 that cannot start then ends the start with an error: nothing drafts instead. A per-run choice, not a per-round one. /// Unset: `--draft dflash2` means none (the owner's order: the DFlash2 and the MTP layer are never loaded together unless asked); `--draft auto` needs both. std::string draft_fallback; double draft_conf = 0.0; ///< --draft-conf P: with --draft dflash2 the window ends where the product of the selector's probabilities falls below P (replaces --spec-min-p) /// --draft auto (serve): both drafters stay current and each request picks one (its key draft=mtp|dflash2, else draft_rule); the CLI treats auto as dflash2 bool draft_auto = false; std::string draft_rule = "df2"; ///< --draft-rule df2|mtp|learn: what a request without a draft= key gets int draft_mtp_spec = 4; ///< --draft-mtp-spec N: the widest window of a request that drafts with the MTP layer under --draft auto bool draft_mtp_spec_set = false; ///< --draft-mtp-spec was given: it is also the window the MTP runs when --draft dflash2 falls back to it (the wider --spec was for DFlash2) double draft_mtp_min_p = -1.0; ///< --draft-mtp-min-p P: the MTP requests' --spec-min-p under --draft auto (-1 = --spec-min-p) int draft_cap = 0; ///< --draft-cap N: the widest verify window with --draft dflash2 (0 = by card class, see where the drafter loads) /// A control vector on the residual stream (strata/kernels/cvec.hpp), with llama.cpp's flags: the /// `experimental-speed-projection` profile passes `--control-vector-scaled FILE:1.0 --control-vector-layer-range /// 4 44 --cvec-mode project --cvec-dir per-layer`. None by default; --serve switches a loaded one per request. std::vector> cvec_files; int cvec_first = -1, cvec_last = -1; ///< llama.cpp's defaults: 1 .. the last layer int cvec_mode = 1; ///< 0 = project, 1 = add (llama.cpp's default) int cvec_single = -1; ///< --cvec-dir single:L (project mode): layer L's direction everywhere }; void usage() { std::fprintf(stderr, "strata generate --pack DIR --tokens \"1,2,3\" [options]\n" "\n" " --pack DIR the pack directory (default pack/full)\n" " --tokens LIST the prompt as comma-separated token IDS (required)\n" " --tokens-file PATH pretokenized prompt, commas or whitespace (alternative to --tokens)\n" " --gpu LIST run on these GPUs, comma-separated nvidia-smi/PCI indices (default: every\n" " visible one); sets CUDA_VISIBLE_DEVICES/CUDA_DEVICE_ORDER inside the engine,\n" " so a caller never has to export environment variables\n" " --ple-gguf PATH required PLE table (original second GGUF shard); with --native, the model's\n" " shard that holds per_layer_token_embd.weight when not given\n" " --no-ple explicit diagnostic ablation of the PLE layer\n" " --ple-io direct|mmap|ram n-gram table reads (plan v0.3 P2). direct (default): unbuffered SSD\n" " reads, the table never enters RAM or the file cache; mmap: A/B arm;\n" " ram: the whole table locked in RAM at start (VirtualLock on Windows,\n" " mlock elsewhere), so no SSD read sits on the prompt or token path\n" " --ple-row-cache N bounded cache of fetched rows, 90 B each (default 1048576; 0 = off)\n" " --ple-inflight N outstanding SSD reads (default 256)\n" " --ple-delay-us U fault injection: each row read completes no earlier than U us\n" " --ple-sync-submit A/B arm: submit table reads on the token thread (default: an I/O thread)\n" " --kv fp16|int8 KV storage (plan v0.3 P7): int8 codes + fp16 scale per 64 values, half the\n" " VRAM; default fp16 until gate G-C accepts int8\n" " --kv q4_0 4-bit K/V after a Hadamard rotation (PR #21): half of int8's memory,\n" " slightly lower precision (see bench/results/2026-09-27-kv-q4)\n" " --kv k8v4 hybrid: INT8 K (exact attention scores) + rotated Q4_0 V, 816 B/cell\n" " (vs int8's 1,056); streams with --kv-resident too\n" " --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" " --gr-native-mmvf experimental pinned GR norm/projections; implies FP32 activations\n" " --native-bf16 experimental CUDA-oracle SSM/router/indexer BF16 projections\n" " --native-bf16-extra experimental CUDA-oracle PLE/shared gate BF16 projections\n" " --native-ple-key experimental native PLE key; requires --native-dense-gguf\n" " --native-moe-combine experimental pinned CUDA routed/shared combination\n" " --native-gdn experimental pinned CUDA GDN norms/gates/recurrence\n" " --native-flash-attn-short diagnostic pinned vector attention; --max-context <=256\n" " --native-qsa-indexer experimental pinned indexer key cache and pooling\n" " --native-qsa experimental pinned QSA normalization and output gate\n" " --native-rope experimental pinned text-only CUDA rotary arithmetic\n" " --native-ple-postops experimental pinned PLE postprojection arithmetic\n" " --native-router experimental pinned CUDA 512-expert top-10 routing\n" " --cpu-oracle-q8-0 experimental pinned CPU expert quantization and dot reduction\n" " --native SHARD1 every full-context native path at once (plan v0.3 P1): stream-token,\n" " GR MMVF, BF16, head, dense + PLE key, MoE combine, GDN, router, QSA,\n" " indexer, RoPE, PLE postops, and the CPU q8_0 contract unless the\n" " expert cache is on. Individual --native-* flags stay for A/B.\n" " --native-head-gguf PATH native Q5_K head from model shard 1; requires --stream-token\n" " --embd-gguf PATH the token embedding from this GGUF instead of --native's (tools/embd_bf16_pack.py:\n" " BF16 as the checkpoint ships it; mapped host memory, no VRAM)\n" " --native-dense-gguf PATH native GDN/QSA/shared projections; repeat for each source model shard\n" " --expert-cache-cpu-order experimental GPU expert reduction matching CPU order\n" " --max-new N tokens to generate (default 16)\n" " --max-context N KV/state capacity (default 4096)\n" " --rope-scaling T extend the context past the trained one: none, linear\n" " (position interpolation) or yarn - llama.cpp's types and names.\n" " Default: the model file's rope keys, else none. Fixed at startup:\n" " K in the cache is post-RoPE, so one run one scaling\n" " --rope-scale F the extension factor for linear/yarn (default: the model file's\n" " factor, else 1 = off)\n" " --rope-freq-base N the raw ggml knobs: the frequency base (0 = the model's 1e7) and\n" " --rope-freq-scale F the angle shrink (0 = 1/--rope-scale)\n" " --yarn-orig-ctx N the trained context the correction targets (0 = 262144)\n" " --yarn-ext-factor F --yarn-attn-factor F --yarn-beta-fast F --yarn-beta-slow F\n" " YaRN's knobs; defaults: -1 (auto: 1 for yarn), 1, 32, 1\n" " --greedy argmax (the default)\n" " --seed S enable sampling with this Philox seed\n" " --top-k N --top-p F --temperature F\n" " --dump-logits PATH write one line of raw logits per position\n" " --logits-stride N store every Nth row plus final input (default 1); N>1 requires --max-new 1\n" " --dump-residual PATH write the final R (hc x n_embd, f32) for head bisection\n" " --dump-layers PATH write R after EVERY layer, per position: the C1 bisection ladder\n" " --dump-halves PATH write both halves' block_out and inject per layer: the half bisection\n" " --dump-routing PATH write the routed expert ids and weights per layer per position (P0.S8)\n" " --no-capture run the layers directly instead of replaying graphs\n" " --shared-late A/B: shared expert after the CPU pool (default: overlapped with it)\n" " --keep-canonical A/B: also load canonical copies of natively served tensors (more VRAM)\n" " --vision --serve takes images too (GENI requests; embeddings from strata-vision)\n" " --prompt-cache N --serve: keep N conversation checkpoints between requests (default 6, ~118 MB\n" " of RAM each; 0 = read every prompt from the start)\n" " --conversation-cache-mib N --serve: RAM budget for parked conversations (default: sized from the free RAM, up to 8192; 0 = off)\n" " --conversation-cache-slots N --serve: at most N parked conversations (default 4)\n" " --conversation-cache-min-free-mib N --serve: RAM floor (under MemAvailable, the cgroup limits and\n" " --memory-limit-mib) when parking, saving or restoring a session (default 2560)\n" " --memory-limit-mib N --serve: the total RAM (MiB) this engine's container or cgroup may use, when\n" " the container cannot see its real limit (also STRATA_MEMORY_LIMIT_MIB; the flag\n" " wins; 0 = none). Parking and session save/restore keep their floor under it\n" " --conversation-cache-min-tokens N --serve: park only conversations of at least N tokens, so\n" " short side requests do not take the slots a long one needs (default 0 = park any)\n" " --conversation-cache-park-gain N --serve: park only after the conversation advanced N tokens past\n" " the copy it would supersede, so a turn that grew by a few hundred tokens does not\n" " write a whole snapshot that the next turn drops (default 0 = park every turn)\n" " --conversation-disk DIR --serve: write the parked conversations the RAM budget evicts to DIR and\n" " read them back when a request continues one (needs --conversation-disk-gib)\n" " --conversation-disk-gib N --serve: disk budget of --conversation-disk, least recently written out\n" " first (default 0 = off)\n" " --session-min-free-mib N --serve: disk space a SAVE must leave free (default 4096; 0 = no check)\n" " --session-save-reclaim --serve: reclaim unpinned host caches if SAVE needs RAM (opt-in)\n" " --vram-elastic --serve (#533, opt-in, NVIDIA): the expert cache in segments (--vram-segment-mib,\n" " default 512), so the command `VRAM ` (the server's POST /v1/vram) can\n" " give VRAM back to other programs between requests and take it back later\n" " --batch N / --slots N --serve (opt-in): up to N requests decode together in batch slots (2..8\n" " normally; --batch-mtp waves more through eight-row windows),\n" " each slot with its own session (VRAM like the main one); docs/BATCHING.md\n" " --batch-mtp --batch (opt-in, needs --mtp and --spec): each slot also verifies one MTP proposal per\n" " window (STRATA_BATCH_MTP=1 does the same); works on one GPU and on a layer split (the\n" " slot drafters sit on the last stage's GPU; not with --batch-groups); needs VRAM per slot\n" " --batch-groups G --batch with a layer split: the slots in G groups pipelined through the GPUs\n" " --pipeline-windows N --serve with a layer split on two GPUs (on by default for 2+ stages on AMD gfx12;\n" " STRATA_PIPELINE_AUTO=0 or N=0 turns it off): one conversation's verify windows\n" " with the GPUs overlapped - 1 = the prompt's short reads, 2 = decode as well\n" " (stage 0 runs the next window while stage 1 verifies this one); docs/MULTI_GPU.md\n" " --trim-stage-weights a layer split (the default): each GPU loads only its own layers' dense weights\n" " --prompt-cache-every N --serve: also checkpoint every N fresh prompt tokens (default 16384, 0 = off)\n" " --prompt-cache-tail --serve, single GPU: one extra checkpoint near the prompt's end, at an existing\n" " chunk boundary (default off; requires --prompt-cache and --prompt-cache-every > 0)\n" " --prompt-cache-spread --serve: keep the checkpoints spread back from the conversation's end (dense\n" " near it, thinner further back) instead of the most recently used: a client that\n" " rewrites its history N tokens back reads about N again, not the whole conversation\n" " --turn-token ID --serve: the token that opens a chat turn (default 248045, <|im_start|>)\n" " --tail-role-token ID --serve: a turn of this role right before the last turn is left out of\n" " the conversation checkpoint (a trailing effort turn; default -1 = off)\n" " --short-read N --serve: read at most N fresh text tokens through the decode windows instead\n" " of the batched prompt path (default 64, or 24 on Windows Strix Halo with a\n" " UD-Q4_K_XL set, where the batched path is quicker from 26 tokens; 0 = off)\n" " --prefill-head-alias --serve: unload the native output head while each fresh prompt is read,\n" " then release prompt buffers and reload it before decode\n" " --suffix-draft N prompt lookup: draft from an earlier repeat of the last N+ tokens of context\n" " when it pays (default 3; 0 = MTP only)\n" " --mtp-max-t M cap the MTP's windows at M tokens (0 = --spec; longer ones come from suffixes)\n" " --lookup-max-t N prompt-lookup windows up to N (<= 16) tokens (default 12 on one GPU in the 8-row CUDA build, not Metal; 0 = off);\n" " copy-heavy edits gain, each extra window size costs a graph (~20-35 MiB of VRAM)\n" " --lookup-sizes A,B the lookup window sizes past the MTP's (default: MTP+1, MTP+2 and N)\n" " --spec N the MTP drafter's verify window: how many tokens it proposes per check (setup\n" " writes 4; --suffix-draft lets it grow by 2, up to 8, where a repeat is likely)\n" " --spec-min-p P how sure the draft layer must be to extend a verify window by another guess\n" " (setup writes 0.5; --calibrate measures it on this PC, see docs/DETAILS.md)\n" " --lookup-chain K opt-in: after the MTP's drafts, add up to K prompt-lookup drafts that continue\n" " them (the window grows to at most 8; default 0 = off)\n" " --lookup-chain-min M the shortest context match --lookup-chain extends on (default 3)\n" " --mtp-hnorm pooled|stream the draft layer's hidden-input norm: one RMS over all four streams\n" " (default) or one per stream (llama.cpp's MTP graph)\n" " --mtp-q4 all|proj|head opt-in: the draft layer's projections and/or draft head as 4-bit copies\n" " --mtp-draft-vocab FILE opt-in: the draft head's token subset (default /draft_vocab.bin)\n" " --draft mtp|dflash2 the draft source (default mtp); dflash2 needs --draft-model PACK (tools/dflash2_pack.py)\n" " and loads no MTP layer (--draft-fallback mtp keeps it as the fallback) (opt-in, Flash-Next, CUDA / HIP)\n" " --draft-fallback mtp|none with --draft dflash2 (default none): none = the MTP layer is not loaded at all, DFlash2 is the only drafter and a DFlash2 that cannot start is an error;\n" " mtp = load both, the MTP drafts if DFlash2 cannot start (--draft auto always loads both)\n" " (the MTP layer's ~0.9 GiB of VRAM goes to the expert cache; --mtp DIR is still needed for DIR/draft_vocab.bin)\n" " --draft-conf P with --draft dflash2: end the window where the product of the selector's probabilities falls below P (default 0 = --spec-min-p)\n" " --draft auto (serve) both drafters stay current; a request picks one: draft=mtp|dflash2, else --draft-rule df2|mtp|learn;\n" " MTP requests use --draft-mtp-spec N (default 4) and --draft-mtp-min-p P\n" " --draft-cap N the widest verify window with --draft dflash2 (default by card: 8 on Strix Halo / iGPU and on Blackwell cc 12.0 with 48 GB or more, 6 on other Blackwell, --spec as given elsewhere)\n" " --control-vector-scaled FILE:SCALE[,...] a control vector GGUF on the residual stream (llama.cpp's\n" " format; --control-vector FILE = scale 1). --serve: requests switch it (cvec=0|1)\n" " --control-vector-layer-range A B the layers it follows (inclusive; default 1 .. the last)\n" " --cvec-mode add|project h += s v (default) or h -= s (h.v) v with v unit\n" " --cvec-dir per-layer|single:L each layer's own direction (default) or layer L's everywhere (project)\n" " --no-token-graph A/B: two graphs per layer (the host launches each) instead of one per token\n" " --no-fused-gr A/B: the six-kernel hyper-connection read and a separate write (native)\n" " --prefill CHUNK batched prompt processing in chunks of CHUNK tokens (needs --native); auto =\n" " the largest chunk up to 8192 whose buffers the expert cache can lend;\n" " auto:16384 / auto:32768 (or STRATA_PREFILL_AUTO_MAX) allow bigger ones\n" " --prefill-pipe R opt-in, a layer split: prompt chunks sized so the stages read at once - R is\n" " this PC's b/a in tokens (setup's --calibrate measures it); 1 only evens out\n" " the buffers' chunk count (STRATA_PREFILL_EQUAL's rule); 0 off (default; or\n" " STRATA_PREFILL_PIPE)\n" " --no-pool skip the CPU expert pool (the GPU-only floor)\n" " --sync-every-layer debug: synchronise after every layer\n" " --ple-gguf PATH the n-gram/PLE shard. WITHOUT IT LAYER 1's PLE IS SILENTLY SKIPPED,\n" " which changes every number downstream - pass it for any real run\n" " --dump-mixed PATH write the post-attention residual (n_embd, f32)\n" " --stage-timing per-stage KERNEL-COUNT shares. NOT a time profile: an uncaptured\n" " event interval includes host gaps, so run with --gpu-only-full first\n" " --graph-only MEASURE: replay the 48 `pre` graphs only. OMITS the 48 `post` graphs\n" " and the LM head, so it is NOT the GPU floor (R0.3, Memory/ERRORS.md A4)\n" " --gpu-only-full MEASURE: replay pre+post for all 48 layers plus the LM head, no pool.\n" " THE TRUE PER-TOKEN GPU FLOOR. Quote this one, not --graph-only.\n" " --stats print the per-stage breakdown\n" " --spec-follow PATH benchmarks: emit this continuation (token ids) instead of the argmax and\n" " accept the drafts that match it, so speculation settings compare on the\n" " same text (with --spec; not --serve)\n" " --window-hashes PATH per verify window, a line with its index, position, size, a 64-bit hash of\n" " its final residual rows and its argmaxes: two builds that do the same\n" " arithmetic write the same file (use with --spec-follow, --adapt-every 0)\n" " --gpu-stages R0.9: capture the layer as three graphs (mixer / ffn+router / post)\n" " and time them from OUTSIDE the capture. The per-stage table on the\n" " real graph that --stage-timing cannot give. Prints and exits.\n" " --expert-profile P R4.2e: pre-load the VRAM tier from a `profile.bin` (see\n" " tools/make_profile.py) instead of admitting on first use.\n" " --expert-profile-save P --serve, #477: save what the adaptive tier learned (the experts in\n" " VRAM, then the routing counted since the start) as a profile at P, on\n" " QUIT and every --expert-profile-save-every MIN minutes (default 10;\n" " 0 = on QUIT only) between requests; start from it with --expert-profile P\n" " --no-hit-poke R4.2d's A/B arm. The hit path pokes the driver once right after its\n" " launch so the GPU starts while the CPU pool runs; without it the work\n" " waits for the next driver entry and does not overlap at all.\n" " --no-ple-prefetch A/B arm: read the PLE table's sixteen rows one at a time, instead of\n" " issuing them in one PrefetchVirtualMemory call.\n" " --expert-cache N R4: keep N expert blobs resident in VRAM and compute their rows on the\n" " GPU via `moe_hit_grouped_s2`. DEFAULT 0. Measured at 4096 slots\n" " with --expert-cache-per-layer: 54.4%% hits, CPU pool drain 19.1 -> 10.3\n" " ms/token, -2.7 ms/token end to end.\n" " --expert-cache-device1 N|auto fill CUDA1 with N experts or as many as fit\n" " --expert-cache-device2 N|auto fill CUDA2 with more experts\n" " --expert-cache-device3 N|auto fill CUDA3 with more experts\n" " --remote-expert-opt enable remote-expert decode optimizations (serve mode)\n" " --expert-cache-remote-placement stripe|layer distribute expert ranks or whole\n" " layers across CUDA1..3 (default: stripe)\n" " --peer-device N a second GPU as an adaptive expert-cache tier (rows over P2P; it also\n" " computes its experts' prompt rows). Not with --layer-split or\n" " --expert-cache-device1..3. Default output unchanged without it.\n" " --peer-reserve-mib N VRAM the peer tier leaves free on its card (default 600)\n" " --peer-slots N expert slots on the peer (default: what fits)\n" " --peer-adapt-swaps N peer cache swaps per adaptation step (default: --adapt-swaps)\n" " --peer-prefill-rows N prompt rows per layer the peer computes (default half of chunk x top-k;\n" " 0 = the prompt path stays on the primary)\n" " --expert-cache-per-layer R4.2g: give each layer its OWN slots instead of letting the first\n" " position take all of them. The default policy fills in arrival order\n" " from one shared counter, so 256 slots went to ~26 layers of position 0\n" " and measured **2.97%%**. Per-layer, the same routing gives 21.4%% at 8\n" " slots/layer and 70.4%% at 64. On a native pack, N is still the budget of N\n" " largest blobs; each layer's slots are that layer's own blob.\n" " --no-host-worker R2.2: the A/B arm. By default the HOST THREAD joins the drain, so the\n" " pool is six threads on six cores instead of five plus an idle core;\n" " this flag restores the five-worker form for comparison on `pool phases`.\n" " --pool-workers N R2.2: CPU expert pool worker count. Default 0 = every physical core\n" " except the one the host loop spins on (with --pool-affinity auto or\n" " p-cores on a hybrid CPU: P-cores minus 1). A sweep is how the pool's\n" " deviation from `cpu_s2` is attributed.\n" " --pool-tasks N Batched CPU expert tasks per GU/Down phase (0..4096). Default 0 =\n" " 3 per participating thread; positive counts are capped by row count.\n" " --host-core WHERE The host thread's core: first (the default: the first physical core, as always) or\n" " last (the last physical core, the workers on the others). Windows sends a GPU's\n" " interrupts to one logical processor, usually the first, and every copy that lands\n" " raises one: a spinning host there waits for them. Moves threads only, never a\n" " result. Not on hybrid CPUs. sibling: the first core's other hardware thread\n" " (SMT), so the interrupts keep the first logical processor and the workers keep\n" " every core; hybrid CPUs too, first without SMT (STRATA_HOST_CORE sets it too).\n" " --pool-cores LIST Experimental, off by default: pin the CPU workers to exactly these logical\n" " processors (0,2,4,6 or 2-14:2; the numbers Task Manager and lscpu show). The\n" " default is one worker per physical core, which the start-up line names. Two\n" " entries on one core, or the host's own, are kept with a warning; processors the\n" " process may not use are left out. The worker count is the list's length unless\n" " --pool-workers says otherwise. Moves threads only, never a result.\n" " STRATA_POOL_CORES sets it too.\n" " --aux-cpus SET Where the threads that are neither pool workers nor the host thread run (the\n" " adaptive tier's job thread, the prefill helpers, the CUDA driver's threads, ...):\n" " off (the default: wherever they were created), auto (the SMT siblings of the host's\n" " core, then physical cores with no worker; never a CPU that shares a core with a\n" " worker; nothing is done when none is spare) or a CPU list such as 24,26 (Linux; the\n" " host's and the workers' CPUs are dropped from it). Moves threads only, never a\n" " result. STRATA_AUX_CPUS sets it too; a request's strata_tune aux_cpus=0|1 beats it.\n" " --no-trim-stage-weights a layer split: every card keeps the dense weights of all the layers,\n" " as before. By default each card keeps only those of the layers it runs\n" " and the VRAM this frees goes to its expert cache.\n" " --pool-affinity MODE Worker CPU affinity: all (default: one worker per physical core, as\n" " always), auto (hybrid CPUs: P-cores first, then their SMT siblings,\n" " then E-cores) or p-cores (P-cores and their siblings only). measure (opt-in,\n" " hybrid CPUs, native packs): all and p-cores are timed on the pack's own experts\n" " at start (about a second) and the faster one is taken\n" " --coupled-draft enable coupled draft sampling for MTP drafter under sampling (STRATA_SPEC_COUPLED)\n" " --no-coupled-draft disable coupled draft sampling (propose argmax drafts)\n" " --mmap-experts R2.1: opt OUT of the resident expert arena, back to MapViewOfFile.\n" " The A/B arm: the mmap's rate depends on the OS page cache holding\n" " 34 GB, and measured 71.97 vs 34.78 ms/token cold vs warm.\n" " --shared-expert-arena FILE Linux: back the resident arena with one MAP_SHARED file.\n" " Put this file on /dev/shm, not ordinary SSD storage.\n" " A small header binds an existing backing file to the same pack.\n" " --resident-cpu-experts with mmap and a static profile, keep the experts the GPU cache does not\n" " hold resident in ordinary RAM (and the prompt path's lend region as far as\n" " RAM allows); adaptive swaps exchange them, so none is read from the file again.\n" " --resident-experts the low-RAM PC's resident mode (setup): --mmap-experts --resident-cpu-experts\n" " with the copy page-locked when possible, 4 GiB headroom, plain mmap if it\n" " does not fit. Same answers as --mmap-experts for the same placement.\n" " --ram-keep-gib W RAM to leave free for your own work, in GiB (default 0; STRATA_RAM_KEEP_GIB is the\n" " same). The expert arena is used only if W GiB stay available after it; otherwise\n" " the hottest experts are kept in a RAM copy that leaves max(W, 8 GiB on Windows /\n" " 4 GiB elsewhere) free and the rest are read from the files. 0 = the arena whenever\n" " it fits. STRATA_RESIDENT_HEADROOM_GIB, when set, decides the headroom instead.\n" " --adapt-min-gain F the adaptive tier swaps an expert in only when its decayed routing count beats\n" " the one it replaces by more than F (default 1.5; higher = fewer, surer swaps)\n" " --adapt-async 0|1 --serve with the resident RAM mode or the arena (one GPU): the adaptive\n" " tier's swaps advance between verify windows instead of a window waiting for a\n" " whole round (the arena: copy-in only). Not bit-exact run to run. Without the flag,\n" " the expert arena on one CUDA GPU (no --batch) starts blocking and tries it for a\n" " while when the swaps hold the windows up, keeping it only if it is faster; 0 = the\n" " blocking tier always (also STRATA_ADAPT_ASYNC=0); 1 = always on.\n"); } // --lookup-chain: the context's last tokens for the draft sources (at most 64), the MTP's pending drafts last // The window sizes the draft policy may give a lookup or chained window: every size up to --spec, unless // --lookup-max-t is on - then the MTP's own sizes and --lookup-sizes (default MTP+1, MTP+2 and --spec). unsigned lookup_size_mask(const Options& o) { if (o.lookup_max_t <= 0) return ~0u; const int s_mtp = o.mtp_max_t > 0 ? std::min(o.mtp_max_t, o.spec) : o.spec; unsigned m = 0; for (int t = 1; t <= s_mtp; ++t) m |= 1u << t; if (o.lookup_sizes.empty()) { for (int t : {s_mtp + 1, s_mtp + 2, o.spec}) if (t <= o.spec) m |= 1u << t; } else { size_t at = 0; while (at < o.lookup_sizes.size()) { const int t = std::atoi(o.lookup_sizes.c_str() + at); if (t >= 2 && t <= o.spec) m |= 1u << t; const size_t c = o.lookup_sizes.find(',', at); if (c == std::string::npos) break; at = c + 1; } } return m; } std::string size_list(unsigned m, int max_t) { std::string r; for (int t = 1; t <= max_t; ++t) if ((m >> t) & 1u) r += (r.empty() ? "" : ",") + std::to_string(t); return r; } int chain_tail(const strata::spec::SuffixDrafter& sfx, const int32_t* pending, int n_pending, std::vector& tail) { const std::vector& h = sfx.history(); const int keep = std::max(0, std::min((int) h.size(), 64 - n_pending)); tail.assign(h.end() - keep, h.end()); tail.insert(tail.end(), pending, pending + n_pending); return (int) tail.size(); } // --lookup-chain: the registered extra draft sources (strata/spec/draft_source.hpp) see the committed context too void extra_sources_reset() { for (auto& src : strata::spec::extra_draft_sources()) src->reset(); } void extra_sources_append(const int32_t* t, size_t n) { for (auto& src : strata::spec::extra_draft_sources()) src->append(t, n); } bool parse_i64_list(const char* s, std::vector& out, std::string& err) { out.clear(); // ids separated by commas or whitespace, read in place (an 80K-token prompt is half a megabyte of text) auto sep = [](char c) { return c == ',' || std::isspace((unsigned char) c); }; for (const char* p = s; *p != '\0';) { if (sep(*p)) { ++p; continue; } const char* end = p; while (*end != '\0' && !sep(*end)) ++end; int32_t id = 0; const auto parsed = std::from_chars(p, end, id); if (parsed.ec != std::errc{} || parsed.ptr != end || id < 0) { err = "invalid token id: expected an integer in [0, 2147483647]"; out.clear(); return false; } out.push_back(id); p = end; } if (out.empty()) { err = "token list was empty"; return false; } return true; } /// The pool's adapter plus the wall-clock it spent, so the report can say how much of the token was the CPU. struct Drive { strata::core::ExpertDispatch d; double cpu_ms = 0; int64_t calls = 0; /// THE ROUTING TRACE, which is P0.S8 and a stated prerequisite of Phase 3. `drive_pool` is called once /// per layer from the main loop - the workers live inside `expert_pool_dispatch` - so a single FILE* here /// needs no locking. `d.layers` is the CURRENT layer on entry (the adapter increments it as it walks the /// blob), which is why the layer index comes from there rather than from a counter of our own. std::FILE* routing = nullptr; }; void drive_pool(void* user, const float* x_f, const int32_t* ids, const float* weights, int64_t n_embd, int64_t k, float* out) { Drive* t = (Drive*) user; const Clock::time_point a = Clock::now(); strata::core::expert_pool_dispatch(&t->d, x_f, ids, weights, n_embd, k, out); t->cpu_ms += std::chrono::duration(Clock::now() - a).count(); ++t->calls; // THE ROUTING TRACE. Written AFTER the dispatch so the layer index is still this layer's: `d.layers` is // advanced by the adapter as it consumes the blob, and reading it after the call is the same value the // dispatch used. Record = int32 layer, int32 k, k int32 ids, k float weights. if (t->routing != nullptr) { // **`d.layers` HAS ALREADY BEEN ADVANCED BY THE TIME THIS RUNS, AND THE FIRST TRACE WAS OFF BY ONE // BECAUSE OF IT.** The adapter walks the blob by incrementing `d.layers` as it consumes each layer's // experts, so after the dispatch it holds the NEXT layer's index. `tools/make_profile.py` caught it // with a bounds check when the trace turned out to span 1..48 instead of 0..47. The hit-rate CURVE was // unaffected - it is a per-layer split, and shifting every layer by one preserves both metrics - but // anything keyed on the layer index, which is exactly what a cache profile is, would have been wrong. const int32_t layer_idx = (int32_t) (t->d.layers - 1); if (layer_idx < 0 || layer_idx >= strata::core::kCompiledGeometry.n_layers) { std::fprintf(stderr, "strata generate: the routing trace saw layer %d, outside 0..47\n", layer_idx); return; } const int32_t rec[2] = {layer_idx, (int32_t) k}; std::fwrite(rec, sizeof rec, 1, t->routing); std::fwrite(ids, sizeof(int32_t), (size_t) k, t->routing); std::fwrite(weights, sizeof(float), (size_t) k, t->routing); } } /// Plan v0.3 P6: the pool for a verify window. void drive_pool_multi_impl(void* user, const float* x_f, const int32_t* ids, int64_t n_tok, int64_t k, float* out, int64_t layer, strata::kernels::cpu::NativeArithmetic arithmetic) { Drive* t = (Drive*) user; t->d.layers = layer; const Clock::time_point a = Clock::now(); strata::core::expert_pool_dispatch_multi(t->d, x_f, ids, n_tok, k, out, arithmetic); t->cpu_ms += std::chrono::duration(Clock::now() - a).count(); ++t->calls; // the routing trace for the serve path: the same record format drive_pool writes (layer, k, ids, weights), // one record per token. The multi dispatch fuses the router weights into the kernel and does not surface // them, so records carry unit weights: tools/make_profile.py ranks pairs by routed frequency, which is the // signal that matters; a one-shot --dump-routing run records true weights if a weighted ranking is wanted. if (t->routing != nullptr && layer >= 0 && layer < strata::core::kCompiledGeometry.n_layers) { for (int64_t tok = 0; tok < n_tok; ++tok) { const int32_t rec[2] = {(int32_t) layer, (int32_t) k}; std::fwrite(rec, sizeof rec, 1, t->routing); std::fwrite(ids + tok * k, sizeof(int32_t), (size_t) k, t->routing); static const float one[64] = {}; // k <= 64 in a verify window; zeros read as unit weights std::fwrite(one, sizeof(float), (size_t) k, t->routing); } } } /// The verify window's pool as every decode has always run it (Default arithmetic), and the same with the window-invariant native /// arithmetic that a probabilistic (STRATA_SPEC_PROB) decode uses, so a row's target distribution does not depend on the window. void drive_pool_multi(void* u, const float* x, const int32_t* ids, int64_t n, int64_t k, float* out, int64_t l) { drive_pool_multi_impl(u, x, ids, n, k, out, l, strata::kernels::cpu::NativeArithmetic::Default); } void drive_pool_multi_invariant(void* u, const float* x, const int32_t* ids, int64_t n, int64_t k, float* out, int64_t l) { drive_pool_multi_impl(u, x, ids, n, k, out, l, strata::kernels::cpu::NativeArithmetic::WindowInvariant); } /// Layer split: every verify stage shares one Drive (its counters, usage and failure flags); the GPU plan, the expert /// cache and the PCIe share the pool uses for a layer are those of the stage that runs it. struct SplitDrive { static constexpr int kMax = 8; Drive* base = nullptr; int n = 0; ///< stages int64_t end[kMax] = {}; ///< stage i runs the layers from end[i - 1] (0) below end[i] strata::core::GpuPlanSink* plan[kMax] = {}; const uint8_t* cache_base[kMax] = {}; const uint64_t* cache_slot_off[kMax] = {}; int pcie_num[kMax] = {}; }; void drive_pool_split_impl(void* user, const float* x_f, const int32_t* ids, int64_t n_tok, int64_t k, float* out, int64_t layer, strata::kernels::cpu::NativeArithmetic arithmetic) { SplitDrive* s = (SplitDrive*) user; int st = 0; while (st + 1 < s->n && layer >= s->end[st]) ++st; Drive& d = *s->base; d.d.plan = s->plan[st]; d.d.cache_base = s->cache_base[st]; d.d.cache_slot_off = s->cache_slot_off[st]; d.d.pcie_num = s->pcie_num[st]; drive_pool_multi_impl(s->base, x_f, ids, n_tok, k, out, layer, arithmetic); } void drive_pool_split(void* u, const float* x, const int32_t* ids, int64_t n, int64_t k, float* out, int64_t l) { drive_pool_split_impl(u, x, ids, n, k, out, l, strata::kernels::cpu::NativeArithmetic::Default); } void drive_pool_split_invariant(void* u, const float* x, const int32_t* ids, int64_t n, int64_t k, float* out, int64_t l) { drive_pool_split_impl(u, x, ids, n, k, out, l, strata::kernels::cpu::NativeArithmetic::WindowInvariant); } /// Layer split across GPUs: a later stage on its own device, with its own copy of the dense weights, a session, an /// expert cache for its layers, a verify window and a prompt path; the last one also holds the head (the drafter /// lives on its device too). struct GpuStage { int dev = 0; int64_t lb = 0, le = 0; double pcie_frac = 0.0; double link_gbps = 0.0; ///< this card's probed host->device bandwidth (PcieAuto's per-stage share) void* arena = nullptr; ///< its dense weights (`wt`) uint64_t arena_bytes = 0; strata::core::WeightTable wt; strata::core::NativeDense dense; strata::core::NativeHead head; strata::core::SessionState ss; cudaStream_t stream = nullptr; strata::core::ExpertCache cache; std::vector> profile; ///< its layers' share of the profile, hottest first int32_t* d_res = nullptr; ///< the residency table on its device strata::core::Verifier ver; strata::core::Verifier ver_b; ///< --pipeline-windows: the odd windows' verifier strata::prefill::Prefill sp; cudaStream_t adapt_stream = nullptr; cudaEvent_t adapt_ev = nullptr; bool adapt_live = false; ///< swaps of this request are in flight on it int32_t* mrope = nullptr; ///< --vision: the image-position table on its device }; // what a refusal on the RAM guard says it had: "900 MiB available, source cgroup" (the smallest of MemAvailable, the // cgroup limits above the engine and --memory-limit-mib; see strata/core/conversation_memory.hpp) static std::string ram_note(const std::optional& mem) { if (!mem) return "RAM telemetry unavailable"; return std::to_string(mem->available >> 20) + " MiB available, source " + strata::core::memory_source_name(mem->source); } // ---- issue #31: what the watchdog prints before it stops a stalled engine struct MemSample { unsigned long long faults = 0, rss_mib = 0, avail_mib = 0, commit_mib = 0; // faults: hard (Linux) / all (Windows) }; MemSample mem_sample() { MemSample m; #if defined(_WIN32) PROCESS_MEMORY_COUNTERS pmc{}; if (K32GetProcessMemoryInfo(GetCurrentProcess(), &pmc, sizeof pmc)) { m.faults = pmc.PageFaultCount; m.rss_mib = pmc.WorkingSetSize >> 20; m.commit_mib = pmc.PagefileUsage >> 20; } MEMORYSTATUSEX ms{}; ms.dwLength = sizeof ms; if (GlobalMemoryStatusEx(&ms)) m.avail_mib = ms.ullAvailPhys >> 20; #else if (std::FILE* f = std::fopen("/proc/self/stat", "r")) { char buf[4096]; const size_t n = std::fread(buf, 1, sizeof buf - 1, f); buf[n] = 0; std::fclose(f); const char* s = std::strrchr(buf, ')'); // fields after the command name: 3 state ... 12 majflt for (int field = 2; s && field < 12; ++field) s = std::strchr(s + 1, ' '); if (s) m.faults = std::strtoull(s + 1, nullptr, 10); } auto kb = [](const char* path, const char* key) -> unsigned long long { unsigned long long v = 0; if (std::FILE* f = std::fopen(path, "r")) { char line[256]; const size_t kl = std::strlen(key); while (std::fgets(line, sizeof line, f)) if (std::strncmp(line, key, kl) == 0) { v = std::strtoull(line + kl, nullptr, 10); break; } std::fclose(f); } return v; }; m.rss_mib = kb("/proc/self/status", "VmRSS:") >> 10; m.commit_mib = kb("/proc/self/status", "VmSwap:") >> 10; m.avail_mib = kb("/proc/meminfo", "MemAvailable:") >> 10; #endif return m; } // the stage the watchdog names: " ", and the prompt chunk a batched read is in (#251) // #1407: the file tier's activity as the OS counts it (Linux: major page faults and bytes read from storage). The #29 // watchdog treats a growing count as "the step is slow, not stuck": a prompt layer whose experts are re-read from the // pack (low RAM, mmap experts) can take minutes while the heartbeat stands still. Zero where unavailable. static uint64_t file_tier_activity() { #if defined(__linux__) uint64_t total = 0; if (FILE* f = std::fopen("/proc/self/stat", "r")) { char buf[1024] = {}; const size_t n = std::fread(buf, 1, sizeof(buf) - 1, f); std::fclose(f); const char* p = std::strrchr(buf, ')'); if (p != nullptr && n > 0) { // after "(comm)": state ppid pgrp session tty tpgid flags minflt cminflt majflt unsigned long long majflt = 0; if (std::sscanf(p + 2, "%*c %*d %*d %*d %*d %*d %*u %*u %*u %llu", &majflt) == 1) total += majflt; } } if (FILE* f = std::fopen("/proc/self/io", "r")) { char line[256]; while (std::fgets(line, sizeof(line), f) != nullptr) { unsigned long long v = 0; if (std::sscanf(line, "read_bytes: %llu", &v) == 1) total += v >> 20; // MiB } std::fclose(f); } return total; #elif defined(_WIN32) // #1984 #1971: Windows had no measure here, so a prompt waiting on mapped-file page-ins never got the I/O allowance. // Bytes read (MiB) plus page faults / 8 (Windows counts soft faults too; a stuck engine makes almost none). uint64_t total = 0; IO_COUNTERS io{}; if (GetProcessIoCounters(GetCurrentProcess(), &io)) total += io.ReadTransferCount >> 20; PROCESS_MEMORY_COUNTERS pmc{}; // >> 3, not >> 6: a host that pages hard reads from the pagefile at ~200 faults a second (#2049: 190/s, one // thread waiting on one page at a time), which at >> 6 is 3 a second and never counted as busy if (K32GetProcessMemoryInfo(GetCurrentProcess(), &pmc, sizeof pmc)) total += pmc.PageFaultCount >> 3; return total; #else return 0; #endif } std::string stage_text() { const strata::core::Progress& p = strata::core::progress(); std::string s = std::string(p.where.load()) + " " + std::to_string((long long) p.detail.load()); if (const int64_t c = p.chunk.load(); c >= 0) s += " of the prompt chunk from token " + std::to_string((long long) c); return s; } #if !defined(_WIN32) // #605: whether `path` is on a rotational disk (1), not (0) or unknown (-1), from sysfs; `dev` is the disk's name int on_rotational_disk(const std::string& path, std::string& dev) { struct stat st{}; if (::stat(path.c_str(), &st) != 0) return -1; char sys[64]; std::snprintf(sys, sizeof sys, "/sys/dev/block/%u:%u", (unsigned) major(st.st_dev), (unsigned) minor(st.st_dev)); std::error_code ec; std::filesystem::path p = std::filesystem::canonical(sys, ec); for (int up = 0; !ec && up < 2; ++up, p = p.parent_path()) { // a partition has its disk's queue std::ifstream q(p / "queue" / "rotational"); int r = -1; if (q >> r) { dev = p.filename().string(); return r; } } return -1; } // #605: the engine's threads in uninterruptible sleep (state D - almost always waiting for the disk), and where // (wchan): 16 threads in blk_io_schedule is a disk that cannot keep up, not a deadlock in the engine void disk_wait_threads(std::FILE* f) { std::map where; int waiting = 0, threads = 0; std::error_code ec; for (const auto& e : std::filesystem::directory_iterator("/proc/self/task", ec)) { ++threads; std::ifstream st(e.path() / "stat"); std::string line; std::getline(st, line); const size_t rp = line.rfind(')'); if (rp == std::string::npos || rp + 2 >= line.size() || line[rp + 2] != 'D') continue; ++waiting; std::ifstream w(e.path() / "wchan"); std::string wc; std::getline(w, wc); ++where[wc.empty() || wc == "0" ? "?" : wc]; } if (threads == 0) return; std::string list; for (const auto& [name, n] : where) list += (list.empty() ? " (" : ", ") + name + " x" + std::to_string(n); if (!list.empty()) list += ")"; std::fprintf(f, " threads waiting on the disk (state D): %d of %d%s%s\n", waiting, threads, list.c_str(), waiting > 0 ? " - the engine is waiting for the drive: a rotational or failing disk with --ple-io " "direct (#605: --ple-io ram), or a drive too slow for the reads asked of it" : ""); } #endif // #2824: what the drive under `path` reads at, GB/s, for the prompt planner (it prices the file set a chunk re-reads). Linux: // rotational disk 0.15, NVMe 2.5, other 0.45 (SATA); elsewhere 1.5. STRATA_SSD_GBPS overrides. `why` says where it came from. double drive_read_gbps(const std::string& path, std::string& why) { if (const char* e = std::getenv("STRATA_SSD_GBPS"); e != nullptr && std::atof(e) > 0.0) { why = "STRATA_SSD_GBPS"; return std::atof(e); } #if !defined(_WIN32) std::string dev; const int rot = on_rotational_disk(path, dev); if (rot == 1) { why = dev + " is a rotational disk"; return 0.15; } if (rot == 0 && dev.rfind("nvme", 0) == 0) { why = dev + " is NVMe"; return 2.5; } if (rot == 0) { why = dev + " is a SATA-class SSD (assumed)"; return 0.45; } #endif why = "assumed"; return 1.5; } // --pipeline-windows: what the watchdog prints about the pipelined decode loop (set while it runs) struct PlDiag { strata::core::Verifier* v[2][2] = {}; std::atomic a_seq{0}, a_bits{0}, b_bits{0}, d_bits{0}, chain_kind{0}, doomed{0}, ending{0}, chain_live{0}; std::atomic iters{0}; }; PlDiag g_pl_diag; void pl_diag_print(std::FILE* f) { PlDiag& d = g_pl_diag; auto bits = [](int b, char* o) { std::snprintf(o, 16, "%c%c%c%c%c%c", b & 1 ? 'R' : '-', b & 2 ? 'L' : '-', b & 4 ? 'F' : '-', b & 8 ? 'C' : '-', b & 16 ? 'S' : '-', b & 32 ? 'V' : '-'); return (const char*) o; }; char ba[16], bb[16], bd[16]; std::fprintf(f, " pipelined loop: %lld iterations; A seq %d [%s] B [%s] D [%s] (Ready Launched Finished Committed " "S1-launched S1-done); chain kind %d live %d; doomed %d ending %d\n", d.iters.load(), d.a_seq.load(), bits(d.a_bits.load(), ba), bits(d.b_bits.load(), bb), bits(d.d_bits.load(), bd), d.chain_kind.load(), d.chain_live.load(), d.doomed.load(), d.ending.load()); const char* names[2][2] = {{"stage 0 even", "stage 0 odd"}, {"stage 1 even", "stage 1 odd"}}; for (int st = 0; st < 2; ++st) for (int par = 0; par < 2; ++par) if (d.v[st][par] != nullptr) d.v[st][par]->diag_pipelined(f, names[st][par]); } // #1341 #964: CUDA_LAUNCH_BLOCKING=1 in the environment. A verify window's graph waits on the GPU for flags the host // raises once cudaGraphLaunch has returned, and a blocking launch returns only when the graph has finished, so the // first window never ends (the batched prompt path has no such wait and runs). HIP's own switches are not checked. bool launch_blocking() { #if defined(STRATA_USE_HIP) || defined(STRATA_HIP_GFX906) return false; #else const char* v = std::getenv("CUDA_LAUNCH_BLOCKING"); return v != nullptr && std::atoi(v) != 0; #endif } /// #2065: the VRAM free when the current request began (-1 before the first); the stall report prints it, because a /// card this full is the one measured cause of a window that never finishes (the driver pages GPU memory). std::atomic g_req_vram_free_mib{-1}; /// AMD on Linux: the driver's paused-GPU counter (ms, strata/core/gpu_pause_time.hpp) when the current request began; /// -1 before the first request, when not available, and in every other build. Read once per request, never per step. std::atomic g_req_gpu_pause_ms{-1}; static int64_t gpu_pause_now() { #if defined(STRATA_USE_HIP) && defined(__linux__) return strata::core::gpu_pause_ms_self(); #else return -1; #endif } /// The same counter when the engine last went idle (READY, then the end of every request): the next request's begin reports a pause that /// happened in between. Only the request loop's thread touches it. static strata::core::GpuPauseIdle g_gpu_pause_idle; constexpr int64_t kVramSafeMib = #ifdef _WIN32 1024; // WDDM pages instead of failing (docs/DETAILS.md, the sysmem fallback): the line #2065 fell below #else 512; #endif /// Round 0216 (STRIX-NEXT): true on an integrated GPU (a Strix Halo) whose expert complement is page-locked in RAM. There the free figure the /// serve checks read counts that pinned memory about twice (the figure is the driver's hipMemGetInfo, src/core/device.cu only lowers it by the DXGI /// budget gap: 12,244 MiB after the cache, then 2.0 x the complement + 691 MiB less once it is pinned; RESULTS-STRIX2.md), so it reads 0 on a start /// that works and a larger --vram-reserve-mib only moves experts from the cache into the complement. The checks say so instead of advising a reserve. std::atomic g_uma_pinned_complement{false}; #if defined(_WIN32) // STRATA_STALL_STACKS=1: the call stack of every other thread, in the stall report. The other threads are suspended while // their stacks are unwound with the unwind tables (RtlLookupFunctionEntry / RtlVirtualUnwind: no heap, no loader lock, no // stdio), into static storage; the threads run again before anything is looked up or printed. Frames in strata.exe are then // named from its PDB (dbghelp, when the PDB is beside the exe); other modules are printed as module+offset. namespace stall_stacks { constexpr int kMaxThreads = 256, kMaxFrames = 32, kMaxMods = 128; struct Mod { uint64_t base; uint64_t size; char name[64]; }; struct Stack { DWORD tid; int n; uint64_t pc[kMaxFrames]; }; static Mod g_mods[kMaxMods]; static Stack g_stacks[kMaxThreads]; static int g_nmods = 0, g_nstacks = 0; static void collect() { g_nmods = g_nstacks = 0; HMODULE hm[kMaxMods]; DWORD need = 0; if (K32EnumProcessModules(GetCurrentProcess(), hm, sizeof hm, &need)) { const int n = std::min(kMaxMods, (int) (need / sizeof(HMODULE))); for (int i = 0; i < n; ++i) { MODULEINFO mi{}; char path[MAX_PATH] = {}; if (!K32GetModuleInformation(GetCurrentProcess(), hm[i], &mi, sizeof mi)) continue; K32GetModuleFileNameExA(GetCurrentProcess(), hm[i], path, MAX_PATH); const char* base = path; for (const char* p = path; *p; ++p) if (*p == '\\' || *p == '/') base = p + 1; Mod& m = g_mods[g_nmods++]; m.base = (uint64_t) (uintptr_t) mi.lpBaseOfDll; m.size = mi.SizeOfImage; std::snprintf(m.name, sizeof m.name, "%s", base); } } const DWORD me = GetCurrentThreadId(), pid = GetCurrentProcessId(); HANDLE snap = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0); if (snap == INVALID_HANDLE_VALUE) return; THREADENTRY32 te{}; te.dwSize = sizeof te; static DWORD tids[kMaxThreads]; int nt = 0; if (Thread32First(snap, &te)) { do { if (te.th32OwnerProcessID == pid && te.th32ThreadID != me && nt < kMaxThreads) tids[nt++] = te.th32ThreadID; } while (Thread32Next(snap, &te)); } CloseHandle(snap); for (int i = 0; i < nt; ++i) { HANDLE th = OpenThread(THREAD_SUSPEND_RESUME | THREAD_GET_CONTEXT | THREAD_QUERY_INFORMATION, FALSE, tids[i]); if (th == nullptr) continue; if (SuspendThread(th) == (DWORD) -1) { CloseHandle(th); continue; } Stack& s = g_stacks[g_nstacks]; s.tid = tids[i]; s.n = 0; alignas(16) CONTEXT ctx; std::memset(&ctx, 0, sizeof ctx); ctx.ContextFlags = CONTEXT_FULL; if (GetThreadContext(th, &ctx)) { for (int k = 0; k < kMaxFrames && ctx.Rip != 0; ++k) { s.pc[s.n++] = ctx.Rip; DWORD64 base = 0; RUNTIME_FUNCTION* fe = RtlLookupFunctionEntry(ctx.Rip, &base, nullptr); if (fe == nullptr) { // a leaf: the return address is at the stack pointer if (ctx.Rsp == 0) break; ctx.Rip = *(const DWORD64*) ctx.Rsp; ctx.Rsp += 8; } else { PVOID hd = nullptr; DWORD64 est = 0; RtlVirtualUnwind(UNW_FLAG_NHANDLER, base, ctx.Rip, fe, &ctx, &hd, &est, nullptr); } } ++g_nstacks; } ResumeThread(th); CloseHandle(th); } } static void print(std::FILE* f) { using SymInitializeFn = BOOL(WINAPI*)(HANDLE, const char*, BOOL); using SymFromAddrFn = BOOL(WINAPI*)(HANDLE, DWORD64, DWORD64*, SYMBOL_INFO*); using SymSetOptionsFn = DWORD(WINAPI*)(DWORD); SymFromAddrFn sym_from = nullptr; if (HMODULE dbg = LoadLibraryA("dbghelp.dll")) { auto init = (SymInitializeFn) GetProcAddress(dbg, "SymInitialize"); auto setopt = (SymSetOptionsFn) GetProcAddress(dbg, "SymSetOptions"); sym_from = (SymFromAddrFn) GetProcAddress(dbg, "SymFromAddr"); if (setopt) setopt(0x2 /*SYMOPT_UNDNAME*/ | 0x10 /*SYMOPT_DEFERRED_LOADS*/ | 0x20000 /*SYMOPT_NO_PROMPTS*/); if (init == nullptr || !init(GetCurrentProcess(), nullptr, TRUE)) sym_from = nullptr; } std::fprintf(f, " thread stacks (STRATA_STALL_STACKS=1; innermost first; strata.exe frames named from its PDB when it is beside the exe):\n"); for (int i = 0; i < g_nstacks; ++i) { const Stack& s = g_stacks[i]; std::fprintf(f, " thread %lu:\n", (unsigned long) s.tid); for (int k = 0; k < s.n; ++k) { const uint64_t pc = s.pc[k]; const Mod* m = nullptr; for (int j = 0; j < g_nmods; ++j) if (pc >= g_mods[j].base && pc < g_mods[j].base + g_mods[j].size) { m = &g_mods[j]; break; } char nm[200] = {}; if (m != nullptr && sym_from != nullptr && std::strcmp(m->name, "strata.exe") == 0) { alignas(8) char buf[sizeof(SYMBOL_INFO) + 160] = {}; SYMBOL_INFO* si = (SYMBOL_INFO*) buf; si->SizeOfStruct = sizeof(SYMBOL_INFO); si->MaxNameLen = 160; DWORD64 disp = 0; if (sym_from(GetCurrentProcess(), pc, &disp, si)) std::snprintf(nm, sizeof nm, " %s+0x%llx", si->Name, (unsigned long long) disp); } if (m != nullptr) std::fprintf(f, " %s+0x%llx%s\n", m->name, (unsigned long long) (pc - m->base), nm); else std::fprintf(f, " 0x%llx\n", (unsigned long long) pc); } } } } // namespace stall_stacks #endif void stall_report(std::FILE* f, uint64_t layers_during) { #if defined(_WIN32) const bool want_stacks = [] { const char* e = std::getenv("STRATA_STALL_STACKS"); return e != nullptr && e[0] == '1'; }(); if (want_stacks) stall_stacks::collect(); // first: the stacks as they were when the stall was noticed #endif strata::core::Progress& p = strata::core::progress(); std::fprintf(f, "strata serve: stall report (engine %s): stage \"%s\" for %lld s; %llu layers served since the " "last finished step (0 = stopped, more = slow)\n", STRATA_VERSION, stage_text().c_str(), (long long) ((strata::core::progress_now_ms() - p.since_ms.load()) / 1000), (unsigned long long) layers_during); if (const int64_t vf = g_req_vram_free_mib.load(); vf >= 0) { std::fprintf(f, " VRAM free when this request began: %lld MiB%s\n", (long long) vf, vf >= kVramSafeMib ? "" : " - LOW: a card this full can page GPU memory to system RAM (decode " "falls to a few tok/s, then a window never finishes, #2065); a larger --vram-reserve-mib, a " "smaller --max-context, or 'Prefer No Sysmem Fallback' for the engine in the NVIDIA control panel " "(docs/DETAILS.md) leaves room"); } #if defined(_WIN32) if (want_stacks) stall_stacks::print(f); #endif int64_t pause_before = -1; // the GPU pause counter at the first pass, for the change over the 2 s for (int pass = 0; pass < 2; ++pass) { if (pass == 1) { std::this_thread::sleep_for(std::chrono::seconds(2)); std::fprintf(f, " 2 s later:\n"); } // #5718 follow-up: the streams a host may be blocked on (the prompt path's), asked without blocking - before the // release below, so "finished" here means the GPU was done and the waiting host was not woken strata::core::stream_watch().report(f, [](void* s, int dev, std::string& why) { const strata::core::OnDevice on(dev); const cudaError_t e = cudaStreamQuery((cudaStream_t) s); if (e == cudaSuccess) return strata::core::StreamState::finished; if (e == cudaErrorNotReady) return strata::core::StreamState::working; why = cudaGetErrorString(e); (void) cudaGetLastError(); return strata::core::StreamState::failed; }); if (auto fn = strata::core::diag_pool_fn().load()) fn(f); if (auto fn = strata::core::diag_verify_fn().load()) fn(f); if (auto fn = strata::core::diag_pipeline_fn().load()) fn(f); #if !defined(_WIN32) disk_wait_threads(f); #endif const MemSample m = mem_sample(); std::fprintf(f, " memory: %llu MiB resident, %llu MiB %s, %llu MiB RAM available; %llu %s\n", m.rss_mib, m.commit_mib, #if defined(_WIN32) "committed", m.avail_mib, m.faults, "page faults so far" #else "in swap", m.avail_mib, m.faults, "major page faults so far" #endif ); // AMD on Linux: how long the driver kept the GPU work paused (no line where the counter cannot be read) const int64_t pause_now = gpu_pause_now(); const std::string pause_line = strata::core::gpu_pause_stall_line(pause_now, g_req_gpu_pause_ms.load(), pass == 1 ? pause_before : -1); if (!pause_line.empty()) std::fprintf(f, "%s\n", pause_line.c_str()); pause_before = pause_now; std::fflush(f); } #if defined(_WIN32) // every thread's stack, to read against this build's PDB: a few MB beside the engine's working directory if (HMODULE dbg = LoadLibraryA("dbghelp.dll")) { using Fn = BOOL(WINAPI*)(HANDLE, DWORD, HANDLE, int, void*, void*, void*); if (auto write = (Fn) GetProcAddress(dbg, "MiniDumpWriteDump")) { char path[64]; std::snprintf(path, sizeof path, "strata-stall-%lu.dmp", (unsigned long) GetCurrentProcessId()); HANDLE h = CreateFileA(path, GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); if (h != INVALID_HANDLE_VALUE) { const int kThreadInfo = 0x1000 | 0x100 | 0x4 | 0x800 | 0x40; // ThreadInfo, ProcessThreadData, HandleData, FullMemoryInfo, IndirectlyReferencedMemory; MiniDumpNormal = 0 const BOOL ok = write(GetCurrentProcess(), GetCurrentProcessId(), h, kThreadInfo, nullptr, nullptr, nullptr); CloseHandle(h); char full[MAX_PATH]; if (!GetFullPathNameA(path, MAX_PATH, full, nullptr)) std::snprintf(full, sizeof full, "%s", path); std::fprintf(f, " %s the thread stacks to %s (attach it to the issue)\n", ok ? "wrote" : "could not write", full); } } } #endif } /// One more launch with the prompt path's buffers in place: a 64 MiB allocation, a stream, a fill and a wait. On an integrated GPU whose pool is full the driver cannot /// build the command buffer ("PAL failed to submit CMD") and every later launch fails with "unspecified launch failure"; this finds it before the prompt is read. #if defined(STRATA_USE_HIP) static bool uma_launch_probe(std::string& why) { (void) cudaGetLastError(); void* p = nullptr; if (cudaMalloc(&p, 64ull << 20) != cudaSuccess) { why = "a 64 MiB allocation failed"; (void) cudaGetLastError(); return false; } cudaStream_t st = nullptr; bool ok = cudaStreamCreateWithFlags(&st, cudaStreamNonBlocking) == cudaSuccess; if (!ok) why = "a stream could not be created"; if (ok) ok = cudaMemsetAsync(p, 0, 64ull << 20, st) == cudaSuccess && cudaStreamSynchronize(st) == cudaSuccess && cudaGetLastError() == cudaSuccess; if (!ok && why.empty()) why = "a launch failed"; if (st != nullptr) cudaStreamDestroy(st); cudaFree(p); if (!ok) (void) cudaGetLastError(); return ok; } #endif /// Integrated GPU (Strix Halo), the prompt path's own buffers, a chunk above the 16384 default that the person or the environment named: the unified pool reads 0 MiB free /// on a start that works, so how much room is left cannot be read, and 32768 on a UD-Q4_K_XL cache that fills the pool takes the last of it (the driver then cannot create a /// stream, and the context is unusable from then on: HIP 719 at the first launch, after the prompt was read). So once the buffers are in place one stream, fill and wait are /// tried; if they fail the engine says so in one line and ends, before any prompt is read, instead of dying after the prefill. It cannot step down in the same process (the /// failed context aborts on the first call that touches it). Never for the 16384 default, a chunk that borrows cache slots, or a discrete GPU. STRATA_PF_OWN_PROBE_OFF=1 skips it. static void uma_refuse_chunk_if_full(int64_t chunk, bool borrows, double cache_gib) { #if !defined(STRATA_USE_HIP) (void) chunk; (void) borrows; (void) cache_gib; // observed on the Strix Halo (HIP) only: CUDA and Metal builds are untouched return; #else if (borrows || chunk <= 16384 || spill_discrete_gpu() || std::getenv("STRATA_PF_OWN_PROBE_OFF") != nullptr) return; std::string why; if (uma_launch_probe(why)) { if (std::getenv("STRATA_TRACE") != nullptr) std::fprintf(stderr, "strata trace: the launch probe passed with a %lld-token chunk\n", (long long) chunk); return; } const int64_t next = strata::core::gfx12_chunk_step_down(chunk); std::fprintf(stderr, "strata generate: a %lld-token prompt chunk does not fit beside the %.1f GiB expert cache on this GPU (%s): use --prefill auto:%lld, or a smaller --expert-cache\n", (long long) chunk, cache_gib, why.c_str(), (long long) next); std::fflush(stderr); std::_Exit(2); #endif } /// STRATA_TRACE=1: the VRAM left at a step of the startup (finds what fills the card after the cache is sized) void mem_mark(const char* where) { static const char* const env = std::getenv("STRATA_TRACE"); if (env == nullptr) return; size_t free_b = 0, total_b = 0; cudaMemGetInfo(&free_b, &total_b); std::fprintf(stderr, "strata trace: %lld MiB free after %s\n", (long long) (free_b >> 20), where); // STRATA_TRACE=2: also wait for the device here and name the first step after which it reports an error. A // "sticky" failure (#2013: unspecified launch failure surfacing in a later, unrelated call) is then pinned to // the step that ran the faulting work. Only a diagnostic: it adds a synchronisation per mark. if (env[0] == '2') { const cudaError_t sync_e = cudaDeviceSynchronize(); const cudaError_t last_e = cudaGetLastError(); std::fprintf(stderr, "strata trace: device %s after %s (sync: %s, last error: %s)\n", sync_e == cudaSuccess && last_e == cudaSuccess ? "ok" : "ERROR", where, cudaGetErrorString(sync_e), cudaGetErrorString(last_e)); } } /// #463's A/B: STRATA_ADAPT_NOWAIT=1 lets a verify window start before the adaptive tier's copies have landed (0.1.37) bool adapt_nowait() { static const bool v = [] { const char* e = std::getenv("STRATA_ADAPT_NOWAIT"); return e && e[0] == '1'; }(); return v; } /// #463 without the stall: a verify window takes the adaptive tier's previous swaps only once they are this many windows /// old, and then waits for their copies (which have landed by then). The window that first computes a swapped-in expert on /// the GPU depends only on the window count, as with #463's wait, so the answers are as reproducible. Default 1 = #463 and /// 0.1.39 (the very next window waits for the copies: ~4.6 ms per window on an RTX 2060 SUPER over PCIe 3.0 x8); lag 2 is /// opt-in (STRATA_ADAPT_LAG=2). The batch paths, --pipeline-windows and the peer tier are not lagged. (#764) int adapt_lag() { static const int v = [] { const char* e = std::getenv("STRATA_ADAPT_LAG"); return e ? std::max(1, std::atoi(e)) : 1; }(); return v; } /// STRATA_ADAPT_OVERLAP=1: the adaptive tier's copies land while the next decode window already runs. The window /// sees the swapped-in experts as resident from its first layer, exactly as after #463's wait (so the tokens are the same /// ones); what changes is only when the bytes arrive: the copies go in layer order and the verify window holds a layer's /// plan back until that layer's copies have landed (AdaptGate in strata/core/verify.hpp). The ~10 ms a 96-swap round /// took at the next window's start (PCIe 3.0 x16, Q2_0) is then hidden behind the window. Opt-in on every backend /// (=1 turns it on); the startup log names the state, and why when it cannot run. bool adapt_overlap() { static const bool v = [] { const char* e = std::getenv("STRATA_ADAPT_OVERLAP"); // Opt-in on every backend (#2010). Windows CUDA since 0.1.43: an RTX 5070 decoded Q2_0 2.6% slower with it // (story decode, -2.1% code), IQ3_XXS no faster. Linux CUDA was on by default from 0.1.43 (same tokens, +5.5..8.3% // decode on an A4000, +4.4% on a P100) until an RTX 5090 Laptop (WSL2, Core Ultra 9 275HX, native IQ3_XXS pack, // --expert-cache-per-layer) decoded 21% slower with it: 84.6 vs 106.6 tok/s medians of 5 generations of 256 // tokens from one build, the slowest of the fast run above the fastest of the slow one. return e && e[0] == '1'; }(); return v; } /// --draft-costs: what a learned draft cost table is valid for. The engine version and backend, every visible card (name, compute /// capability, memory), the driver and runtime versions, the adaptive tier's timing switches and the cost-aware window, and the /// engine's own command line (a file argument by its name and size, so a moved install keeps its table and another model file does /// not), without the table's own flags. Any change re-learns the table once; nothing in it changes from start to start. std::string draft_costs_key(int argc, char** argv, const std::string& extra, bool spec_cost) { std::string k = "engine " STRATA_VERSION; #if defined(STRATA_GPU_METAL) k += "|metal"; #elif defined(STRATA_USE_HIP) k += "|hip"; #else k += "|cuda"; #endif int n = 0; if (cudaGetDeviceCount(&n) != cudaSuccess) { n = 0; (void) cudaGetLastError(); } k += "|cards " + std::to_string(n); for (int d = 0; d < n; ++d) { cudaDeviceProp prop{}; if (cudaGetDeviceProperties(&prop, d) != cudaSuccess) { (void) cudaGetLastError(); continue; } k += std::string("|") + prop.name + " cc " + std::to_string(prop.major) + "." + std::to_string(prop.minor) + " " + std::to_string((unsigned long long) (prop.totalGlobalMem >> 20)) + " MiB"; } #if !defined(STRATA_HIP_GFX906) && !defined(STRATA_GPU_METAL) int drv = 0, rt = 0; if (cudaDriverGetVersion(&drv) != cudaSuccess) { drv = 0; (void) cudaGetLastError(); } if (cudaRuntimeGetVersion(&rt) != cudaSuccess) { rt = 0; (void) cudaGetLastError(); } k += "|driver " + std::to_string(drv) + " runtime " + std::to_string(rt); #endif k += std::string("|nowait ") + (adapt_nowait() ? "1" : "0") + " lag " + std::to_string(adapt_lag()) + " spec_cost " + (spec_cost ? "1" : "0"); k += "|args"; for (int i = 1; i < argc; ++i) { const std::string a = argv[i]; if (a == "--draft-costs" || a == "--draft-costs-key") { ++i; continue; } std::error_code ec; const std::filesystem::path p(std::u8string(a.begin(), a.end())); const size_t cut = a.find_last_of("/\\"); std::string base = cut == std::string::npos ? a : a.substr(cut + 1); if (base.empty() && cut != std::string::npos) base = a; // a path ending in a separator: keep it whole if (a.size() > 1 && a[0] != '-' && std::filesystem::is_regular_file(p, ec)) { const auto sz = std::filesystem::file_size(p, ec); k += " " + base + ":" + std::to_string(ec ? 0ull : (unsigned long long) sz); } else if (a.size() > 1 && a[0] != '-' && std::filesystem::is_directory(p, ec)) { k += " " + base + "/"; } else { k += " " + a; } } if (!extra.empty()) k += "|server " + extra; return k; } /// STRATA_ADAPT_FETCH (opt-in): 1 = the PCIe share also admits into the VRAM tier (ExpertDispatch::fetch_admit), beside /// the tier's own copies from RAM; 2 = instead of them (the tier's counts still decay). STRATA_ADAPT_FETCH_MIN and /// STRATA_ADAPT_FETCH_MARGIN: the admission's thresholds (default 1 and 0.5). int adapt_fetch() { static const int v = [] { const char* e = std::getenv("STRATA_ADAPT_FETCH"); return e ? std::max(0, std::min(2, std::atoi(e))) : 0; }(); return v; } /// ExpertDispatch::evict_sync where the tier does not wait for its copies; STRATA_ADAPT_EVICT_SYNC=0 turns it off. bool adapt_evict_sync() { static const bool v = [] { const char* e = std::getenv("STRATA_ADAPT_EVICT_SYNC"); return e == nullptr || std::atoi(e) != 0; }(); return v; } /// STRATA_ADAPT_CHECKRES=1: before a verify window, the device's residency table read back into `back` and /// compared with the host's (the pool's plan); the mismatched entries, the first ones reported. int64_t res_check(const int32_t* d_res, const std::vector& host_res, std::vector& back, int64_t n_expert, int64_t window) { if (cudaMemcpy(back.data(), d_res, host_res.size() * sizeof(int32_t), cudaMemcpyDeviceToHost) != cudaSuccess) { std::fprintf(stderr, "strata: res check: the read-back failed: %s\n", cudaGetErrorString(cudaGetLastError())); return 0; } static int printed = 0; int64_t bad = 0; for (size_t i = 0; i < host_res.size(); ++i) if (back[i] != host_res[i]) { ++bad; if (printed < 20) { ++printed; std::fprintf(stderr, "strata: res check: window %lld layer %lld expert %lld: host %d, device %d\n", (long long) window, (long long) (i / (size_t) n_expert), (long long) (i % (size_t) n_expert), (int) host_res[i], (int) back[i]); } } return bad; } /// #3797: when the engine cannot start for lack of GPU memory, the cards' free and total memory and the largest other /// programs that hold some, as a warning added to the message that says it (program/gpu_report.hpp). Best effort: a /// card that cannot be asked, or a driver that does not list its programs, is left out or said so; it never changes the /// failure and never throws. `devices`: the CUDA ordinals to report (duplicates are skipped). static void print_startup_gpu_report(const std::vector& devices) { namespace gr = strata::program::gpu_report; std::vector cards; int count = 0, prev = 0; if (cudaGetDeviceCount(&count) != cudaSuccess) { (void) cudaGetLastError(); return; } if (cudaGetDevice(&prev) != cudaSuccess) { (void) cudaGetLastError(); prev = 0; } std::vector seen; for (const int d : devices) { if (d < 0 || d >= count || std::find(seen.begin(), seen.end(), d) != seen.end()) continue; seen.push_back(d); if (cudaSetDevice(d) != cudaSuccess) { (void) cudaGetLastError(); continue; } // no context fits there either size_t free_b = 0, total_b = 0; if (cudaMemGetInfo(&free_b, &total_b) != cudaSuccess) { (void) cudaGetLastError(); continue; } gr::Card c; c.index = d; c.free_mib = (uint64_t) (free_b >> 20); c.total_mib = (uint64_t) (total_b >> 20); cudaDeviceProp prop{}; if (cudaGetDeviceProperties(&prop, d) == cudaSuccess) c.name = prop.name; else (void) cudaGetLastError(); #if !defined(STRATA_USE_HIP) && !defined(STRATA_HIP_GFX906) && !defined(STRATA_GPU_METAL) char bus[64] = {}; if (cudaDeviceGetPCIBusId(bus, (int) sizeof bus, d) == cudaSuccess) c.processes_known = gr::query_other_processes(bus, c.processes); else (void) cudaGetLastError(); #endif cards.push_back(std::move(c)); } if (prev >= 0 && prev < count) (void) cudaSetDevice(prev); (void) cudaGetLastError(); if (cards.empty()) return; #if defined(_WIN32) const uint32_t self = (uint32_t) GetCurrentProcessId(); #else const uint32_t self = (uint32_t) getpid(); #endif std::fprintf(stderr, "strata generate: GPU memory right now (best effort):\n%s\n", gr::format_gpu_memory_report(cards, self).c_str()); } /// The pre-launch hook's patch: the changed entries of the host's residency table (`idx`) as (index, entry) pairs into /// the mapped `pairs` (room for `cap`); their count, or -1 when they do not fit (then the whole table goes up). int64_t res_patch_pairs(const std::vector& idx, const std::vector& host_res, int32_t* pairs, size_t cap) { if (pairs == nullptr || idx.size() > cap) return -1; for (size_t k = 0; k < idx.size(); ++k) { pairs[2 * k] = idx[k]; pairs[2 * k + 1] = host_res[(size_t) idx[k]]; } std::atomic_thread_fence(std::memory_order_seq_cst); return (int64_t) idx.size(); } /// Mapped host memory for res_patch_pairs (portable: every card of a layer split reads it), or null. The kernels read /// it at the host's address: each of `devs` (-1: the current device) must map it there, else the whole table goes up. int32_t* res_pairs_alloc(size_t cap, const std::vector& devs) { void* p = nullptr; if (cudaHostAlloc(&p, cap * 2 * sizeof(int32_t), cudaHostAllocMapped | cudaHostAllocPortable) != cudaSuccess) { (void) cudaGetLastError(); return nullptr; } for (int dev : devs) { const strata::core::OnDevice on(dev); void* d = nullptr; if (cudaHostGetDevicePointer(&d, p, 0) != cudaSuccess || d != p) { (void) cudaGetLastError(); cudaFreeHost(p); return nullptr; } } return (int32_t*) p; } /// --adapt-async: one background job at a time (the asynchronous adaptive tier's copies and memcpys). `post` hands /// it over, `idle` says whether it has finished; the owner never posts while a job runs. class JobThread { public: JobThread() : th_([this] { loop(); }) {} ~JobThread() { { std::lock_guard lk(mu_); quit_ = true; } cv_.notify_one(); th_.join(); } JobThread(const JobThread&) = delete; JobThread& operator=(const JobThread&) = delete; void post(std::function f) { { std::lock_guard lk(mu_); job_ = std::move(f); has_ = true; done_.store(false, std::memory_order_release); } cv_.notify_one(); } bool idle() const { return done_.load(std::memory_order_acquire); } void wait() const { while (!idle()) std::this_thread::yield(); } private: // The second logical processor of the last physical core that has two: an SMT sibling no pool worker or host loop // is pinned to (the pool takes the first of every core but the first, the host the first core), or -1. static int smt_spare_cpu() { #if defined(_WIN32) DWORD len = 0; GetLogicalProcessorInformationEx(RelationProcessorCore, nullptr, &len); if (len == 0) return -1; std::vector buf(len); if (!GetLogicalProcessorInformationEx(RelationProcessorCore, (PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX) buf.data(), &len)) return -1; int best = -1, core = 0; for (const char* p = buf.data(); p < buf.data() + len; p += ((const SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX*) p)->Size, ++core) { const auto* e = (const SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX*) p; const GROUP_AFFINITY& ga = e->Processor.GroupMask[0]; int seen = 0; for (int bit = 0; bit < 64; ++bit) if ((ga.Mask & (1ull << bit)) && ++seen == 2 && core > 0) best = ga.Group * 64 + bit; } return best; #else return -1; #endif } void loop() { // the job's memcpys stay off the host's core and the pool's: by default the spare SMT sibling of the last // two-thread core (Windows); STRATA_ADAPT_JOB_CPU=, or -1 for no pinning. Without either, --aux-cpus // (off by default) puts the thread on the spare CPUs; an explicit STRATA_ADAPT_JOB_CPU is the user's word over it. strata::platform::name_this_thread("strata-adapt-job"); const char* c = std::getenv("STRATA_ADAPT_JOB_CPU"); const int cpu = c != nullptr ? std::atoi(c) : smt_spare_cpu(); if (cpu >= 0) (void) strata::kernels::cpu::pin_current_thread(cpu); if (c != nullptr) strata::aux_cpus::note_owned_thread(); else if (cpu < 0) strata::aux_cpus::pin_current_thread(); for (;;) { std::function f; { std::unique_lock lk(mu_); cv_.wait(lk, [&] { return has_ || quit_; }); if (!has_) return; f = std::move(job_); has_ = false; } f(); done_.store(true, std::memory_order_release); } } std::mutex mu_; std::condition_variable cv_; std::function job_; bool has_ = false, quit_ = false; std::atomic done_{true}; std::thread th_; // last: started once the members above exist }; // ---- --serve's conversation cache. A chat or an agent sends the whole conversation again with every request, and // reading it again is what made a long session wait minutes for every turn. What a sequence leaves behind splits in // two, and only one half needs copying: // * POSITIONAL state - the KV cache of the 12 QSA layers and their pooled indexer keys, the draft layer's KV. A // cell is written once for its position and read only by later positions (the block scores take `dead` for the // block being filled, never its pooled row), so rewinding to a position just means writing from there again. // * RUNNING state - the 36 GDN recurrences and conv histories, each QSA layer's indexer tail (the unfinished // block's raw keys) and the PLE's normalized history. Each describes "everything so far" and cannot be // rewound, so a checkpoint is a copy of exactly these: ~118 MB, the same set the verifier snapshots to roll // back rejected drafts. // A checkpoint is only valid while the positional cells below it still hold ITS tokens, so the serve loop keeps // just the checkpoints that are prefixes of the tokens the session holds now. using ImgKey = strata::core::ConversationImageKey; using ConvCheckpoint = strata::core::ConversationCheckpoint; uint64_t fnv1a(const void* data, size_t n, uint64_t h = 1469598103934665603ull) { const uint8_t* p = (const uint8_t*) data; for (size_t i = 0; i < n; ++i) { h ^= p[i]; h *= 1099511628211ull; } return h; } using ConvStateSizes = strata::core::ConversationStateSizes; ConvStateSizes conv_state_sizes(const strata::core::ModelGeometry& g, const strata::core::SessionState& ss) { ConvStateSizes z; std::string error; // a split stage's session owns only its layer range's state (see SessionState's carve note); the geometry // and the carve have already passed engine validation strata::core::conversation_session_sizes(g, ss, z, error); return z; } /// Copies the running state out (this session's carve only). The caller has synchronized the device. bool checkpoint_save(ConvCheckpoint& c, const strata::core::SessionState& ss, const strata::core::ModelGeometry& g) { std::string error; if (strata::core::conversation_checkpoint_save(c, ss, g, error)) return true; std::fprintf(stderr, "strata serve: checkpoint save: %s\n", error.c_str()); // the caller's ERR has no reason return false; } /// #3350: a conversation checkpoint is an optimization, like parking. After a failed save: true when the failure was /// only the copy's memory (a host or driver allocation, which does not stick), so the caller goes on without that /// checkpoint; false when the GPU itself is unwell (a sticky error comes back from the synchronize), which still ends /// the request as before. bool checkpoint_failure_is_survivable() { (void) cudaGetLastError(); // clears a failed allocation; a sticky error is not cleared and is returned again below return cudaDeviceSynchronize() == cudaSuccess; } /// Puts a checkpoint's running state back; the positional cells below it are the caller's to guarantee. bool checkpoint_restore(const ConvCheckpoint& c, strata::core::SessionState& ss, const strata::core::ModelGeometry& g) { std::string error; if (strata::core::conversation_checkpoint_restore(c, ss, g, error)) return true; std::fprintf(stderr, "strata serve: checkpoint restore: %s\n", error.c_str()); return false; } /// STRATA_CKPT_POOL: the storage of dropped checkpoints, for the next save or slot copy to reuse. `give` keeps a /// checkpoint's vectors (its tokens, pictures and marks cleared), `take` hands one back (an empty checkpoint when none /// is kept). At most `cap` are kept (a batch admission drops and takes about two; STRATA_CKPT_POOL=N), the rest are /// freed as before. class CheckpointPool { public: explicit CheckpointPool(bool on, size_t cap = 2) : on_(on), cap_(cap) {} /// Sets the switch and the cap once the serve loop knows its cache (before the first give or take, on the host thread) void configure(bool on, size_t cap) { std::lock_guard lk(mu_); on_ = on; cap_ = cap; } bool on() const { return on_; } size_t cap() const { return cap_; } size_t held() { std::lock_guard lk(mu_); return free_.size(); } /// The bytes of the kept checkpoints (idle memory), and giving them back to the system, newest first size_t idle_bytes() const { std::lock_guard lk(mu_); size_t n = 0; for (const ConvCheckpoint& c : free_) n += c.bytes(); return n; } size_t shrink(size_t want) { std::vector out; // freed outside the lock size_t given = 0; { std::lock_guard lk(mu_); while (!free_.empty() && given < want) { given += free_.back().bytes(); out.push_back(std::move(free_.back())); free_.pop_back(); } } return given; } void give(ConvCheckpoint&& c) { if (!on_ || c.gdn.empty()) return; strata::core::conversation_checkpoint_join(c.gdn.data()); clear_marks(c); std::lock_guard lk(mu_); if (free_.size() < cap_) free_.push_back(std::move(c)); } ConvCheckpoint take() { std::lock_guard lk(mu_); if (!on_ || free_.empty()) return ConvCheckpoint{}; ConvCheckpoint c = std::move(free_.back()); free_.pop_back(); return c; } /// v.erase(remove_if(v, drop)) with the dropped ones given to the pool (the kept ones keep their order) template void erase_if(std::vector& v, Drop drop) { size_t w = 0; for (size_t i = 0; i < v.size(); ++i) { if (drop(static_cast(v[i]))) { give(std::move(v[i])); continue; } if (w != i) v[w] = std::move(v[i]); ++w; } v.erase(v.begin() + (std::ptrdiff_t) w, v.end()); } private: static void clear_marks(ConvCheckpoint& c) { c.ids.clear(); c.imgs.clear(); c.used = 0; c.pinned = false; c.dev_tag = 0; for (ConvCheckpoint& part : c.stage_parts) clear_marks(part); } bool on_; size_t cap_; mutable std::mutex mu_; std::vector free_; }; /// What the conversation cache counts as the park pools' idle memory (ConversationCache::set_pool): the segment pool's resident /// bytes that no image uses, and the checkpoint pool's kept checkpoints. Giving back takes the arena first (it is the cheaper to /// top up again), then the checkpoints. class ParkPoolsBudget final : public strata::core::SegmentPoolBudget { public: ParkPoolsBudget(strata::core::SegmentPool* seg, CheckpointPool* ck) : seg_(seg), ck_(ck) {} size_t idle_bytes() const override { return (seg_ ? seg_->idle_bytes() : 0) + (ck_ ? ck_->idle_bytes() : 0); } size_t shrink(size_t want) override { size_t given = seg_ ? seg_->shrink(want) : 0; if (given < want && ck_) given += ck_->shrink(want - given); return given; } private: strata::core::SegmentPool* seg_; CheckpointPool* ck_; }; /// STRATA_CKPT_THREADS: runs job(0) on the calling thread and job(k), k = 1..n-1, on persistent thread k at the same /// time, and returns when all have. The threads live as long as this object: a short-lived thread would leave its /// private copy stream behind on every device it used (conversation_detail::copy_nonblocking). A thread inherits the /// host thread's one CPU (aux_cpus.hpp), where the copies would only take turns, so each first goes to the aux CPUs /// (--aux-cpus) or else to every CPU the process may use. One caller at a time; a job does not throw. class StageThreads { public: StageThreads() = default; StageThreads(const StageThreads&) = delete; StageThreads& operator=(const StageThreads&) = delete; ~StageThreads() { { std::lock_guard lk(mu_); stop_ = true; } go_.notify_all(); for (std::thread& t : threads_) t.join(); } void run(size_t n, const std::function& job) { if (n == 0) return; { std::lock_guard lk(mu_); while (threads_.size() + 1 < n) { const size_t k = threads_.size() + 1; threads_.emplace_back([this, k] { loop(k); }); } job_ = &job; n_ = n; pending_ = n - 1; ++round_; } go_.notify_all(); job(0); std::unique_lock lk(mu_); done_.wait(lk, [&] { return pending_ == 0; }); job_ = nullptr; } static void spread_current_thread() { #if defined(__linux__) // wide first: the mask the aux placement keeps as this thread's own is the one restore() puts back (a request // with aux_cpus=0), and the host's one CPU must not be it; wide = the process's CPU set from the start-up // (strata/platform/home_cpus.hpp) strata::platform::widen_to_home(); // the kernel keeps the CPUs the cgroup allows strata::aux_cpus::pin_current_thread(); // (a no-op while the feature is off) #endif } private: void loop(size_t k) { strata::platform::name_this_thread("strata-ckpt", (int) k); spread_current_thread(); uint64_t seen = 0; std::unique_lock lk(mu_); for (;;) { go_.wait(lk, [&] { return stop_ || round_ != seen; }); if (stop_) return; seen = round_; if (k >= n_) continue; // a round with fewer jobs than threads const std::function* job = job_; lk.unlock(); (*job)(k); lk.lock(); if (--pending_ == 0) done_.notify_all(); } } std::mutex mu_; std::condition_variable go_, done_; std::vector threads_; const std::function* job_ = nullptr; size_t n_ = 0, pending_ = 0; uint64_t round_ = 0; bool stop_ = false; }; // --control-vector-scaled: llama.cpp's `common_control_vector_load` (every file's `direction.` times its scale, // summed; layer 0 has none) and `llama_adapter_cvec::apply` with the projection-mode patch (project: the unit // direction and its norm as the scale), into the tables `cvec_upload` takes. `summary` is what INFO reports; // `digest` identifies the uploaded tables, mode and range exactly (a session file is bound to it). bool load_control_vectors(const Options& o, const strata::core::ModelGeometry& g, std::string& summary, uint64_t& digest, std::string& err) { const int64_t L = g.n_layers, N = g.n_embd; std::vector data((size_t) (L * N), 0.0f); std::vector have((size_t) L, false); for (const auto& [path, scale] : o.cvec_files) { try { strata::GgufFile f(path); const strata::MetaValue* arch = f.get("general.architecture"); if (arch == nullptr || arch->s != "controlvector") { err = path + ": not a control vector GGUF (general.architecture is not 'controlvector')"; return false; } const strata::MetaValue* hint = f.get("controlvector.model_hint"); if (hint != nullptr && hint->s != "qwen4exp") std::fprintf(stderr, "strata generate: %s was made for '%s', not qwen4exp\n", path.c_str(), hint->s.c_str()); int found = 0; for (const strata::TensorInfo& t : f.tensors()) { if (t.name.rfind("direction.", 0) != 0) continue; const long l = std::strtol(t.name.c_str() + 10, nullptr, 10); if (l < 1 || l >= L) continue; // layer 0 has no vector; past the model is ignored, as in llama.cpp if (t.type != 0 || t.elements() != (uint64_t) N) { err = path + ": " + t.name + " must be " + std::to_string((long long) N) + " f32"; return false; } const float* src = reinterpret_cast(f.tensor_data(t)); for (int64_t j = 0; j < N; ++j) data[(size_t) (l * N + j)] += scale * src[j]; have[(size_t) l] = true; ++found; } if (found == 0) { err = path + ": no direction. tensors"; return false; } } catch (const std::exception& e) { err = e.what(); return false; } } const int first = o.cvec_first <= 0 ? 1 : o.cvec_first; const int last = (o.cvec_last <= 0 || o.cvec_last >= L) ? (int) L - 1 : o.cvec_last; const int single = o.cvec_mode == 0 ? o.cvec_single : -1; if (single >= 0 && (single >= L || !have[(size_t) single])) { err = "--cvec-dir single:" + std::to_string(single) + ": the vector has no direction for that layer"; return false; } std::vector dir((size_t) (L * N), 0.0f), s((size_t) L, 0.0f); int steered = 0; for (int64_t l = first; l <= last; ++l) { const int64_t src = single >= 0 ? single : l; if (!have[(size_t) src]) continue; const float* d = data.data() + (size_t) (src * N); if (o.cvec_mode == 0) { double nrm = 0.0; for (int64_t j = 0; j < N; ++j) nrm += (double) d[j] * d[j]; nrm = std::sqrt(nrm); if (nrm <= 0.0) continue; s[(size_t) l] = (float) nrm; for (int64_t j = 0; j < N; ++j) dir[(size_t) (l * N + j)] = (float) (d[j] / nrm); } else { s[(size_t) l] = 1.0f; std::copy(d, d + N, dir.begin() + (size_t) (l * N)); } ++steered; } if (steered == 0) { err = "the control vector has no direction in layers " + std::to_string(first) + ".." + std::to_string(last); return false; } if (!strata::kernels::cvec_upload(dir, s, o.cvec_mode, first, last, N, g.hc, err)) return false; { strata::core::SessionIdentityBuilder b(0x43564543ull); // "CVEC" b.i64("mode", o.cvec_mode); b.i64("first", first); b.i64("last", last); b.i64("single", single); b.bytes("dir", dir.data(), dir.size() * sizeof(float)); b.bytes("scale", s.data(), s.size() * sizeof(float)); digest = b.digest(); if (digest == 0) digest = 1; // 0 means "none loaded" } summary = std::string(o.cvec_mode == 0 ? "project" : "add") + ":" + std::to_string(first) + "-" + std::to_string(last) + (single >= 0 ? ":single" + std::to_string(single) : ""); // the line llama.cpp's patched build prints, so a log shows the same thing std::fprintf(stderr, "strata generate: control vector mode = %s, dir = %s, layers %d..%d (%d steered)\n", o.cvec_mode == 0 ? "project" : "add", single >= 0 ? "single" : "per-layer", first, last, steered); return true; } /// 0.1.43: PcieAuto also refines a layer split's shares, each stage by its own probed link. 0.2.10.1: on by default for a discrete CUDA card /// (strata/core/pcie_share_rule.hpp), STRATA_PCIE_AUTO_SPLIT=0 restores the fixed probe share; HIP stays opt-in (=1), as does an integrated GPU. static bool pcie_auto_split_ok() { static const bool on = [] { #if defined(STRATA_USE_HIP) const bool hip = true; #else const bool hip = false; #endif return strata::pcie_auto_split_default(hip, spill_discrete_gpu(), strata::qwen_defaults_026(), std::getenv("STRATA_PCIE_AUTO_SPLIT")); }(); return on; } // 0.1.43: the HIP defaults of the decode speed push (route tail skip, measured PCIe share) were measured on gfx1201 (Radeon AI PRO // R9700) and apply on gfx1200 / gfx1201 only; every other AMD part (gfx11, gfx906, ...) keeps its earlier behaviour. CUDA: always true. [[maybe_unused]] static bool decode_defaults_arch_ok() { #if defined(STRATA_USE_HIP) int dev = 0; cudaDeviceProp p{}; return cudaGetDevice(&dev) == cudaSuccess && cudaGetDeviceProperties(&p, dev) == cudaSuccess && strata::kernels::gfx_arch_is_gfx12_wmma(p.gcnArchName); #else return true; #endif } /// 0.1.44: the pipelined decode puts the drafter on the first stage's card by default where it was measured (gfx12; the HIP builds /// only). STRATA_MTP_STAGE0=0 / 1 decides either way. [[maybe_unused]] static bool mtp_first_default_on() { #if defined(STRATA_USE_HIP) return decode_defaults_arch_ok(); #else return false; #endif } /// 0.2.7: gfx12 native packs start their decode miss split at 0.15 instead of the x16 share 0.55. Measured on an R9700 /// (p620, IQ3_S, 24576 expert pairs of which 13207 resident): --pcie-frac 0.15 decodes 94.6 tok/s at 8K against 86.1 and /// 84.4 against 67.2 at 32K (rotated pairs; at 64K the window is attention-bound and it is +4.7%); under serve/server.py a /// short chat decodes 93.2 against 84.4. The CPU lane rounds a missing expert's FP32 rows differently from the GPU lane, /// so this changes bits; the first-token KL of 0.0 against 0.55 is 0.0013 mean with the same top-1 in 12 of 12 prompts /// (below the engine's own implementation-noise scale). An explicit --pcie-frac always wins, and /// STRATA_PCIE_FRAC_DEFAULT=old restores the old share; the HIP-only gate keeps every CUDA build on its own measured /// values. [[maybe_unused]] static bool pcie_share_gfx12_default() { #if defined(STRATA_USE_HIP) return decode_defaults_arch_ok(); #else return false; #endif } // HIP outside gfx12: the same refinement, opt-in with STRATA_PCIE_FRAC_DEFAULT=auto (#2224). Its author gate-measured it on an // RX 7900 XTX (gfx1100) as "no regression" only (4 alternating starts at 64K, prefill 2189 base vs 2180 with it, decode 65.4 vs // 65.4; under serve the share refines 0.55 -> 0.25 from the pool's 42-45 us/missed expert and the probed 28.4-28.5 GB/s link); // a second report (2x RX 7900 GRE) found it never engages there (95-98% of the experts cached). The gain is measured only on // gfx1201 (where it is the default, decode_defaults_arch_ok), so the other parts keep the fixed share unless asked. [[maybe_unused]] static bool pcie_auto_fork_arch_ok() { #if defined(STRATA_USE_HIP) const char* pfd = std::getenv("STRATA_PCIE_FRAC_DEFAULT"); return pfd != nullptr && std::strcmp(pfd, "auto") == 0; #else return false; #endif } // The effective host->device bandwidth of the PCIe link: copies from pinned host memory, as the expert arena's // reads are. The native default share (0.55) was measured on x16 links (~26-28 GB/s); a x8 card in a x8 slot // carries about half of that. Returns < 0 when the probe cannot run (then the caller keeps the default). // // #485: a single timed burst read an x16 PCIe 4 link (RTX A3000 laptop) at 18.5, 6.9 and 5.8 GB/s in three starts - // a link still in a low-power state, other DMA, a context not yet up to speed - and the low reading set the share. // Such a disturbance only ever slows a copy: nothing makes a correctly timed copy faster than the link carries. So // the same 1 GiB is now copied as four bursts of 256 MiB, timed one by one, and the fastest is the link's figure (the // median would still follow a disturbance that lasts through half the bursts). Each burst takes ~10 ms on an x16 // PCIe 4 link, so the probe takes no longer than the one 1 GiB burst did. `samples`, when given, gets every // burst's reading for the log. double g_last_h2d_gbps = -1.0; // the last probe's reading, for the prompt planner (#2824) double probe_pcie_h2d_gbps(std::string* samples = nullptr) { constexpr size_t kBytes = 256ull << 20; constexpr int kBursts = 4; void* h = nullptr; void* d = nullptr; if (cudaMallocHost(&h, kBytes) != cudaSuccess) return -1.0; if (cudaMalloc(&d, kBytes) != cudaSuccess) { cudaFreeHost(h); return -1.0; } std::memset(h, 0, kBytes); // fault the pages in before timing cudaMemcpyAsync(d, h, kBytes, cudaMemcpyHostToDevice); // warmup: context up, copy engine primed float ms[kBursts] = {}; #if defined(STRATA_USE_HIP) && defined(_WIN32) // Windows HIP: the events do not bracket the copies there (an RX 6800 read 3,300-26,000 GB/s, so every link kept // the x16 share), so each burst is timed on the host between two synchronizes: 256 MiB takes ~10 ms, so the // synchronize around it hardly matters bool ok = cudaDeviceSynchronize() == cudaSuccess; for (int b = 0; b < kBursts && ok; ++b) { const Clock::time_point t0 = Clock::now(); cudaMemcpyAsync(d, h, kBytes, cudaMemcpyHostToDevice); ok = cudaDeviceSynchronize() == cudaSuccess; ms[b] = (float) std::chrono::duration(Clock::now() - t0).count(); } #else // the bursts run back to back on the stream, an event between each two cudaEvent_t ev[kBursts + 1]; int n_ev = 0; while (n_ev <= kBursts && cudaEventCreate(&ev[n_ev]) == cudaSuccess) ++n_ev; bool ok = n_ev == kBursts + 1; if (ok) { cudaEventRecord(ev[0]); for (int b = 0; b < kBursts; ++b) { cudaMemcpyAsync(d, h, kBytes, cudaMemcpyHostToDevice); cudaEventRecord(ev[b + 1]); } ok = cudaEventSynchronize(ev[kBursts]) == cudaSuccess; for (int b = 0; b < kBursts && ok; ++b) ok = cudaEventElapsedTime(&ms[b], ev[b], ev[b + 1]) == cudaSuccess; } for (int i = 0; i < n_ev; ++i) cudaEventDestroy(ev[i]); #endif double bw = -1.0; if (samples != nullptr) samples->clear(); for (int b = 0; b < kBursts && ok; ++b) { const double s = ms[b] > 0.01f ? (double) kBytes / (ms[b] * 1e-3) / 1e9 : -1.0; bw = std::max(bw, s); if (samples != nullptr) { char buf[32]; std::snprintf(buf, sizeof(buf), "%s%.1f", b == 0 ? "" : " ", s); *samples += buf; } } if (!ok) (void) cudaGetLastError(); cudaFree(d); cudaFreeHost(h); if (bw > 0.0) g_last_h2d_gbps = bw; return bw; } // The PCIe share of the missed experts for a link measured at `gbps`: `base` (the share measured on x16 links) from // 20 GB/s up, and below that in proportion to the bandwidth, so the time the link spends on its share stays about // what the x16 share costs. Continuous (#485): before, 19.9 GB/s gave 0.42 and 20.0 the full 0.55 (and 4.0 GB/s // gave 0.08, 3.9 none), so a reading near either edge moved the share by a quarter of its range. From 20 GB/s up // (an x16 PCIe 4/5 link: ~26-28 GB/s) the share is unchanged. double pcie_frac_for_gbps(double gbps, double base) { return gbps <= 0.0 ? base : base * std::min(1.0, gbps / 20.0); } // --pool-affinity measure: `all` against `p-cores` on a hybrid CPU, timed on this pack's own experts. // // The pool's default layout puts a worker on every physical core, and a layer's experts are done when the slowest // worker is. Measured on a Core i7-13700K (8 P + 8 E), IQ3_XXS, RTX 5090, same prompt and build: `all` (15 workers) // spent 6.7 ms per verify window in the pool and decoded 148 tok/s, `p-cores` (7 workers) 2.2 ms and 188-191 tok/s; // in an earlier run of the same day `all` took 2.4 ms, so the difference is not constant. Hence a measurement at // start and not a rule. // // What is timed is the decode's own call: two missed experts of four tokens per layer (run_split_multi_native on // blobs from the arena), every layer in turn, with the host spinning ~150 us between two layers as it does on the // GPU's flags. The two layouts take turns in kBlocks blocks and the medians are compared; `p-cores` is taken // unless `all` is more than 10% faster (fewer threads wait on fewer cores when the two are close). The layout // changes no result, only where threads run. It is one reading at start and is not repeated: on the same PC one // server start in four read `all` as the faster layout (6.6 ms against 8.6), where the others read it 2.4 to 4 times // slower. strata::kernels::cpu::PoolAffinity measure_pool_affinity(strata::core::ExpertSource* src, int workers, bool host_works, int tasks) { namespace cpu = strata::kernels::cpu; using Clock = std::chrono::steady_clock; const cpu::ExpertLayout& lay = cpu::expert_layout(); const cpu::CpuTopology topo = cpu::detect_cpu_topology(true, cpu::PoolAffinity::PCores); if (!topo.is_hybrid) { std::fprintf(stderr, "strata generate: --pool-affinity measure: this CPU is not a hybrid one; the layout stays all\n"); return cpu::PoolAffinity::All; } constexpr int kExperts = 2, kTok = 4, kRounds = 10, kBlocks = 3; const int64_t nl = lay.n_layers; std::vector blobs((size_t) nl * kExperts, nullptr); bool have = src != nullptr && lay.native && (int64_t) lay.fmt.size() >= nl && nl > 0; uint32_t seed = 12345u; for (int64_t l = 0; have && l < nl; ++l) for (int j = 0; j < kExperts; ++j) { seed = seed * 1664525u + 1013904223u; const uint8_t* b = src->blob(l, (int64_t) ((seed >> 8) % (uint32_t) lay.n_expert)); if (b == nullptr) { have = false; break; } blobs[(size_t) l * kExperts + (size_t) j] = b; } if (!have) { std::fprintf(stderr, "strata generate: --pool-affinity measure needs a native pack with its experts in RAM; " "the layout stays all\n"); return cpu::PoolAffinity::All; } std::vector nact((size_t) nl * kTok * cpu::kNativeActBytes); std::vector qact((size_t) nl * kTok); std::vector x((size_t) cpu::H), out((size_t) kExperts * kTok * cpu::H); for (int64_t l = 0; l < nl; ++l) for (int t = 0; t < kTok; ++t) { for (int i = 0; i < cpu::H; ++i) x[(size_t) i] = std::sin((float) (i + 13 * t + 7 * (int) l) * 0.031f); const size_t at = (size_t) l * kTok + (size_t) t; if (cpu::q2_native_kernels(lay.fmt[(size_t) l].gu_type)) cpu::act_quant_any(x.data(), cpu::H, qact[at]); else cpu::native_quant_act(lay.fmt[(size_t) l], x.data(), nact.data() + at * cpu::kNativeActBytes); } int n_workers[2] = {0, 0}; auto block = [&](cpu::PoolAffinity aff, int which) -> double { cpu::ExpertPool pool(workers, /*pin=*/true, host_works, aff, tasks); n_workers[which] = pool.workers(); const int host = cpu::planned_host_core(aff); cpu::ThreadAffinity prev; if (host >= 0) prev = cpu::pin_current_thread(host); cpu::ExpertJobMulti jobs[kExperts]; double ms = 0.0; for (int r = -1; r < kRounds; ++r) // round -1 is not timed: the workers start and the rows are touched for (int64_t l = 0; l < nl; ++l) { for (int j = 0; j < kExperts; ++j) { jobs[j].blob = blobs[(size_t) l * kExperts + (size_t) j]; jobs[j].nt = kTok; for (int t = 0; t < kTok; ++t) { const size_t at = (size_t) l * kTok + (size_t) t; jobs[j].act[t] = &qact[at]; jobs[j].nact[t] = nact.data() + at * cpu::kNativeActBytes; jobs[j].out[t] = out.data() + ((size_t) j * kTok + (size_t) t) * cpu::H; } } const Clock::time_point t0 = Clock::now(); pool.run_split_multi_native(lay.fmt[(size_t) l], jobs, kExperts); const Clock::time_point t1 = Clock::now(); if (r >= 0) ms += std::chrono::duration(t1 - t0).count(); while (std::chrono::duration(Clock::now() - t1).count() < 150.0) {} } if (host >= 0) cpu::restore_thread_affinity(prev); return ms / kRounds; }; double all_ms[kBlocks], p_ms[kBlocks]; for (int b = 0; b < kBlocks; ++b) { all_ms[b] = block(cpu::PoolAffinity::All, 0); p_ms[b] = block(cpu::PoolAffinity::PCores, 1); } std::sort(all_ms, all_ms + kBlocks); std::sort(p_ms, p_ms + kBlocks); const double a = all_ms[kBlocks / 2], p = p_ms[kBlocks / 2]; const bool take_p = p <= a * 1.10; std::fprintf(stderr, "strata generate: --pool-affinity measure: %d experts x %d tokens per layer over %lld layers: " "all (%d workers) %.2f ms, p-cores (%d workers) %.2f ms (medians of %d) -> %s\n", kExperts, kTok, (long long) nl, n_workers[0], a, n_workers[1], p, kBlocks, take_p ? "p-cores" : "all"); return take_p ? cpu::PoolAffinity::PCores : cpu::PoolAffinity::All; } // HIP: the thread that warms hipBLAS's libraries while the expert arena loads (see warm_gemm_libraries); joined at exit. std::thread g_warm_thr; struct WarmJoin { ~WarmJoin() { if (g_warm_thr.joinable()) g_warm_thr.join(); } } g_warm_join; /// The ceiling of the CPU/PCIe miss share the auto rules use (PcieAuto, its start value and the later stages of a layer split) and the pool factor k /// of the rule (strata/core/pcie_share_rule.hpp). 0.2.10.1 defaults on a discrete card: ceiling 0.95 and k falling with the pool rate (2 workers /// 31 -> 63 tok/s, 4 workers 56 -> 79, a strong pool unchanged: k is 1.85 from 30 GB/s of expert bytes and the shares stay below 0.60); an integrated /// GPU (Strix Halo and the other APUs, whose "link" is the shared memory) and STRATA_DEFAULTS=026 keep 0.60 and 1.85. STRATA_PCIE_SHARE_MAX / /// STRATA_PCIE_K_RULE=0 or 1 set either by hand. static double pcie_share_max() { static const double v = strata::pcie_share_ceiling(spill_discrete_gpu(), strata::qwen_defaults_026(), std::getenv("STRATA_PCIE_SHARE_MAX")); return v; } static double pcie_pool_k(double r) { static const bool on = strata::pcie_k_rule_default(spill_discrete_gpu(), strata::qwen_defaults_026(), std::getenv("STRATA_PCIE_K_RULE")); return strata::pcie_pool_k(r, on); } // 0.1.42, CUDA single-GPU serve, no --pcie-frac: the share refined from what the CPU pool measures in the first decode // windows. The balance share of the missed experts is link / (link + CPU rate). The link is the start-up probe; the CPU // rate is the expert bytes over the pool's wall time per missed expert (ExpertDispatch::ms_run / multi_misses), which the // engine already times. The best shares measured with the route tail skip on (RTX 3060 0.15-0.20, Tesla P100 0.20, RTX // A4000 flat from 0.15 to 0.40; the 0.1.41 rule gave 0.55, 0.29, 0.30) lie within one 0.05 step of link / (link + 1.85 x pool rate). // Three updates at most (after 48, then 96 and 96 more windows), each rounded to 0.05, so a noisy window cannot move // the share by less than a step and it stops moving after the third. STRATA_PCIE_FRAC_DEFAULT=old keeps the 0.1.41 rule. struct PcieAuto { static constexpr double kPoolFactor = 1.85; bool on = false; double link_gbps = 0.0, blob_bytes = 0.0; double mark_ms = 0.0; int64_t mark_jobs = 0; double acc_ms = 0.0; int64_t acc_jobs = 0; int acc_win = 0, updates = 0; void mark(double ms_run, int64_t jobs) { mark_ms = ms_run; mark_jobs = jobs; } /// After a decode window: the new share, or -1 while there is nothing to change. `tc_us`/`rate` get the reading. double window(double ms_run, int64_t jobs, double cur, double* tc_us, double* rate) { if (!on) return -1.0; acc_ms += ms_run - mark_ms; acc_jobs += jobs - mark_jobs; mark(ms_run, jobs); ++acc_win; if (acc_win < (updates == 0 ? 48 : 96)) return -1.0; if (acc_jobs < 300) { // too few missed experts to read the pool's speed (everything hits): look again if (acc_win >= 2000) on = false; return -1.0; } const double tc = acc_ms * 1000.0 / (double) acc_jobs; acc_ms = 0.0; acc_jobs = 0; acc_win = 0; if (++updates >= 3) on = false; if (!(tc > 1.0) || !(blob_bytes > 0.0) || !(link_gbps > 0.0)) return -1.0; const double r = blob_bytes / (tc * 1e-6) / 1e9; const double f = std::min(pcie_share_max(), std::max(0.10, std::round(link_gbps / (link_gbps + pcie_pool_k(r) * r) * 20.0) / 20.0)); *tc_us = tc; *rate = r; return std::fabs(f - cur) < 0.025 ? -1.0 : f; } }; // ---- STRATA_EXPERT_NIBBLE=1 (strata/core/expert_nibble.hpp): the gate/up experts of IQ2_S / IQ3_XXS / IQ3_S layers as // 4-bit codes in their VRAM slots. Everything below runs only with the switch on. /// The largest slot an expert cache can hold for this pack: the GGUF `max_blob`, or a converted layer's 4-bit slot when /// that is larger (the sizings that count slots of the largest blob would otherwise come out short of a full cache and /// leave converted experts out of VRAM, which the switch refuses). `max_blob` exactly with the switch off. uint64_t nibble_max_slot_bytes() { const auto& lay = strata::kernels::cpu::expert_layout(); uint64_t m = lay.max_blob; if (nib::any_on()) for (int64_t l = 0; l < lay.n_layers; ++l) m = std::max(m, nib::slot_bytes(l)); return m; } #if STRATA_EXPERT_NIBBLE_BUILT /// One expert cache's converted slots. The startup fill hands a converted layer's pairs to `add` instead of /// `fill_slot_blocking`; per layer, `kBatch` GGUF blobs at a time go H2D into one staging buffer (the bytes /// fill_slot_blocking would copy, from the source's `blob_stable`, which stays valid) and, per batch, the /// transcoder writes the codes, scales and d into the slots and round-trips every item, the GGUF down rows are copied /// behind them, the GGUF blocks are rebuilt from every slot and compared with the blob (both count against the layer /// in `d_bad`), and each slot's hash is recorded for STRATA_EXPERT_NIBBLE_RECHECK. One stream, so the staging /// buffer's reuse is ordered without events. The device arrays live as long as the process (RECHECK reads them); /// `finish` frees the staging buffer. struct NibbleCache { static constexpr int64_t kBatch = 64; struct Pending { int32_t expert, slot; const uint8_t* blob; }; struct Batch { int32_t layer; int64_t at, n; }; strata::core::ExpertCache* cache = nullptr; int dev = 0; ///< the cache's device std::vector> pending; ///< per layer: queued, at most kBatch std::vector batches; ///< what was transcoded and hashed, in that order std::vector> pairs; ///< (layer, expert) of each converted slot, in that order std::vector slots; ///< and its slot unsigned long long* h_ptrs = nullptr; ///< pinned: the slots' device addresses, in that order unsigned long long* d_ptrs = nullptr; ///< the same on the device (the transcoder's and hash's input) unsigned long long* d_ref = nullptr; ///< each slot's hash as loaded unsigned long long* d_now = nullptr; ///< RECHECK's unsigned long long* d_bad = nullptr; ///< per layer: items that did not round-trip, words that differ uint8_t* staging = nullptr; uint64_t raw_max = 0; cudaStream_t stream = nullptr; int64_t cap = 0, n = 0; double seconds = 0; bool active() const { return cache != nullptr; } static std::string cuda_fail(const char* what, cudaError_t e) { return std::string(what) + ": " + cudaGetErrorString(e); } /// For `c` on the current device, `want` converted pairs at most. bool begin(strata::core::ExpertCache& c, int64_t want, std::string& err) { if (cudaGetDevice(&dev) != cudaSuccess) dev = 0; cache = &c; cap = want > 0 ? want : 1; const auto& lay = strata::kernels::cpu::expert_layout(); pending.assign((size_t) lay.n_layers, {}); for (int64_t l = 0; l < lay.n_layers; ++l) if (nib::layer(l).on) raw_max = std::max(raw_max, nib::layer(l).raw_bytes); cudaError_t e = cudaStreamCreateWithFlags(&stream, cudaStreamNonBlocking); if (e == cudaSuccess) e = cudaMallocHost((void**) &h_ptrs, (size_t) cap * 8); if (e == cudaSuccess) e = cudaMalloc((void**) &d_ptrs, (size_t) cap * 8); if (e == cudaSuccess) e = cudaMalloc((void**) &d_ref, (size_t) cap * 8); if (e == cudaSuccess) e = cudaMalloc((void**) &d_now, (size_t) cap * 8); if (e == cudaSuccess) e = cudaMalloc((void**) &d_bad, (size_t) lay.n_layers * 8); if (e == cudaSuccess) e = cudaMemsetAsync(d_bad, 0, (size_t) lay.n_layers * 8, stream); if (e == cudaSuccess) e = cudaMalloc((void**) &staging, (size_t) ((uint64_t) kBatch * raw_max)); if (e != cudaSuccess) { err = cuda_fail("the 4-bit fill's buffers", e); return false; } if (const int rc = nib::prepare((void*) stream); rc != 0) { err = std::string("the 4-bit fill's GGUF codebooks: ") + (rc == (int) cudaErrorInvalidValue ? "a grid entry is not unique" : cudaGetErrorString((cudaError_t) rc)); return false; } return true; } bool add(int32_t layer, int32_t expert, int32_t slot, const uint8_t* blob, std::string& err) { auto& q = pending[(size_t) layer]; q.push_back({expert, slot, blob}); return (int64_t) q.size() < kBatch || flush(layer, err); } bool flush(int32_t layer, std::string& err) { auto& q = pending[(size_t) layer]; if (q.empty()) return true; const auto t0 = std::chrono::steady_clock::now(); const nib::LayerVram& L = nib::layer(layer); const int64_t k = (int64_t) q.size(); if (n + k > cap) { err = "the 4-bit fill was given more converted pairs than it counted"; return false; } cudaError_t e = cudaSuccess; for (int64_t i = 0; i < k && e == cudaSuccess; ++i) { uint8_t* dst = cache->device_slot(q[(size_t) i].slot); if (dst == nullptr || cache->slot_room(q[(size_t) i].slot) < L.hashed) { // a slot sized for the GGUF blob err = "the 4-bit fill: slot " + std::to_string(q[(size_t) i].slot) + (dst == nullptr ? " is outside the cache" : " is smaller than a 4-bit slot"); return false; } h_ptrs[n + i] = (unsigned long long) (uintptr_t) dst; e = cudaMemcpyAsync(staging + (uint64_t) i * L.raw_bytes, q[(size_t) i].blob, (size_t) L.raw_bytes, cudaMemcpyHostToDevice, stream); } if (e == cudaSuccess) e = cudaMemcpyAsync(d_ptrs + n, h_ptrs + n, (size_t) k * 8, cudaMemcpyHostToDevice, stream); if (e != cudaSuccess) { err = cuda_fail("the 4-bit fill's copies in", e); return false; } auto m2 = [&](const char* what, int rc) -> bool { // iq_kernels.cu's: a CUDA error code if (rc == 0) return true; err = std::string("the 4-bit ") + what + ": " + cudaGetErrorString((cudaError_t) rc); return false; }; if (!m2("transcoder", nib::transcode(L, staging, k, d_ptrs + n, d_bad + layer, (void*) stream))) return false; for (int64_t i = 0; i < k && e == cudaSuccess; ++i) e = cudaMemcpyAsync((uint8_t*) (uintptr_t) h_ptrs[n + i] + nib::kDownOff, staging + (uint64_t) i * L.raw_bytes + L.raw_down_off, (size_t) L.down_bytes, cudaMemcpyDeviceToDevice, stream); if (e != cudaSuccess) { err = cuda_fail("the 4-bit fill's down rows", e); return false; } if (!m2("GGUF check", nib::check_gguf(L, staging, k, d_ptrs + n, d_bad + layer, (void*) stream))) return false; if (!m2("slot hash", nib::hash_slots(L, d_ptrs + n, k, d_ref + n, (void*) stream))) return false; // the next batch's copies in land in the same staging bytes: they wait for this batch's kernels (one stream) for (const Pending& p : q) { pairs.emplace_back(layer, p.expert); slots.push_back(p.slot); } batches.push_back({layer, n, k}); n += k; q.clear(); seconds += std::chrono::duration(std::chrono::steady_clock::now() - t0).count(); return true; } /// The rest of the queue, then waits: false (with `err` naming every layer) when an item did not round-trip or a /// rebuilt GGUF block differs from its blob. bool finish(std::string& err) { for (int32_t l = 0; l < (int32_t) pending.size(); ++l) if (!flush(l, err)) return false; const auto t0 = std::chrono::steady_clock::now(); cudaError_t e = cudaStreamSynchronize(stream); std::vector bad(pending.size(), 0); if (e == cudaSuccess) e = cudaMemcpy(bad.data(), d_bad, bad.size() * 8, cudaMemcpyDeviceToHost); if (staging != nullptr) (void) cudaFree(staging); staging = nullptr; seconds += std::chrono::duration(std::chrono::steady_clock::now() - t0).count(); if (e != cudaSuccess) { err = cuda_fail("the 4-bit fill", e); return false; } for (size_t l = 0; l < bad.size(); ++l) if (bad[l] != 0) { char b[192]; std::snprintf(b, sizeof b, "%slayer %zu (%s): %llu items or words do not round-trip", err.empty() ? "" : "; ", l, nib::fmt_name(nib::layer((int64_t) l).gu_type), bad[l]); err += b; } if (!err.empty()) { err += " - the 4-bit code does not hold these weights (STRATA_EXPERT_NIBBLE_SKIP= keeps a layer's " "GGUF blocks)"; return false; } return true; } /// The end-to-end check of the fill as it is wired, on converted pair (layer, expert) with `raw` its GGUF blob: the /// slot read back, its hash against expert_nibble.hpp's host reference of what the device recorded, its down rows /// against the blob's. (Every item and every GGUF block of every slot was checked on the device by `finish`.) bool check(int32_t layer, int32_t expert, const uint8_t* raw, std::string& err) const { int64_t at = -1; for (size_t i = 0; i < pairs.size() && at < 0; ++i) if (pairs[i].first == layer && pairs[i].second == expert) at = (int64_t) i; if (at < 0 || raw == nullptr) { err = "the 4-bit check: no converted slot or no GGUF blob for layer " + std::to_string(layer) + " expert " + std::to_string(expert); return false; } const nib::LayerVram& L = nib::layer(layer); std::vector got((size_t) L.hashed); unsigned long long h = 0; cudaError_t e = cudaMemcpy(got.data(), cache->device_slot(slots[(size_t) at]), got.size(), cudaMemcpyDeviceToHost); if (e == cudaSuccess) e = cudaMemcpy(&h, d_ref + at, 8, cudaMemcpyDeviceToHost); if (e != cudaSuccess) { err = cuda_fail("the 4-bit check's read back", e); return false; } const char* why = nib::hash_host(got.data(), L.hashed) != h ? "the device slot hash differs from the host reference" : std::memcmp(got.data() + nib::kDownOff, raw + L.raw_down_off, (size_t) L.down_bytes) != 0 ? "the down rows differ from the GGUF blob's" : nullptr; if (why != nullptr) { err = "layer " + std::to_string(layer) + " expert " + std::to_string(expert) + " (" + nib::fmt_name(L.gu_type) + "): " + why; return false; } return true; } /// STRATA_EXPERT_NIBBLE_RECHECK: every converted slot's hash again, on the device, against the one recorded at load. /// False with the first slot that differs (or a CUDA error) in `err`; `bad_layer` its layer (-1: an error). bool recheck(std::string& err, int64_t& bad_layer) { bad_layer = -1; if (n == 0) return true; const strata::core::OnDevice on(dev); for (const Batch& b : batches) { const int rc = nib::hash_slots(nib::layer(b.layer), d_ptrs + b.at, b.n, d_now + b.at, (void*) stream); if (rc != 0) { err = cuda_fail("the slot hash", (cudaError_t) rc); return false; } } std::vector ref((size_t) n), now((size_t) n); cudaError_t e = cudaStreamSynchronize(stream); if (e == cudaSuccess) e = cudaMemcpy(ref.data(), d_ref, (size_t) n * 8, cudaMemcpyDeviceToHost); if (e == cudaSuccess) e = cudaMemcpy(now.data(), d_now, (size_t) n * 8, cudaMemcpyDeviceToHost); if (e != cudaSuccess) { err = cuda_fail("the slot hash read back", e); return false; } for (int64_t i = 0; i < n; ++i) if (ref[(size_t) i] != now[(size_t) i]) { char b[224]; std::snprintf(b, sizeof b, "CUDA%d: layer %d expert %d (slot %d) hashes %016llx, %016llx at load", dev, (int) pairs[(size_t) i].first, (int) pairs[(size_t) i].second, (int) slots[(size_t) i], now[(size_t) i], ref[(size_t) i]); err = b; bad_layer = pairs[(size_t) i].first; return false; } return true; } }; #else // A build without the 4-bit kernels (STRATA_EXPERT_NIBBLE_BUILT 0: HIP, Metal, a CUDA build without // STRATA_EXPERIMENTAL_SM60): nibble_refusal refuses the switch, so no cache is ever converted and none of this is entered. struct NibbleCache { int64_t n = 0; double seconds = 0; std::vector> pairs; bool active() const { return false; } bool begin(strata::core::ExpertCache&, int64_t, std::string& err) { err = "the 4-bit slots are not in this build"; return false; } bool add(int32_t, int32_t, int32_t, const uint8_t*, std::string& err) { err = "the 4-bit slots are not in this build"; return false; } bool finish(std::string&) { return true; } bool check(int32_t, int32_t, const uint8_t*, std::string& err) const { err = "the 4-bit slots are not in this build"; return false; } bool recheck(std::string&, int64_t& bad_layer) { bad_layer = -1; return true; } }; #endif /// With STRATA_EXPERT_NIBBLE=1, why this start cannot have 4-bit slots (empty: nothing here stops it): what the build, /// the GPUs, the environment and the options decide, before anything is allocated. The full residency, the loans and /// the prompt chunk are checked where they are known. std::string nibble_refusal(const Options& o) { const nib::Config& c = nib::config(); if (!c.error.empty()) return c.error; #if !STRATA_EXPERT_NIBBLE_BUILT || !defined(STRATA_NATIVE_EXPERTS) (void) o; return "the 4-bit slots and their kernels are in the CUDA build with STRATA_EXPERIMENTAL_SM60 and native experts only"; #else int count = 0; if (cudaGetDeviceCount(&count) != cudaSuccess || count <= 0) { (void) cudaGetLastError(); return "no CUDA device"; } for (int d = 0; d < count; ++d) { cudaDeviceProp p{}; if (cudaGetDeviceProperties(&p, d) != cudaSuccess) { (void) cudaGetLastError(); return "cannot read CUDA" + std::to_string(d) + "'s properties"; } if (p.major != 6 || p.minor != 0) return "CUDA" + std::to_string(d) + " (" + p.name + ") is compute capability " + std::to_string(p.major) + "." + std::to_string(p.minor) + ": the 4-bit slots are for compute capability 6.0 (GP100) only"; } if (std::string e = nib::env_conflicts(); !e.empty()) return e; if (o.peer_device >= 1) return "--peer-device (its cache holds GGUF blobs)"; for (size_t r = 0; r < o.expert_cache_remote.size(); ++r) if (o.expert_cache_remote[r] > 0 || o.expert_cache_remote_auto[r]) return "remote expert caches (--expert-cache-device1..3 hold GGUF blobs)"; if (o.kv_grow) return "--kv-grow (the elastic K/V moves slots at their GGUF size)"; if (o.vram_elastic) return "--vram-elastic (it refills slots with GGUF blobs)"; if (o.expert_profile.empty()) return "no --expert-profile (every expert must be VRAM-resident from the profile fill)"; if (o.expert_cache == 0) return "--expert-cache 0 (no VRAM slots to convert)"; return {}; #endif } } // namespace // #1425 #1549 #1629: --ple-io direct (the default) does unbuffered random reads of the n-gram table; on some drives // (DRAM-less NVMe, Windows unbuffered I/O) they run at 34 MB/s or 4-8 tok/s and a prompt reads layer 1 for minutes. // Rows per second of a short cold probe: a few batches of random rows through the same batched reader a prompt chunk // uses, stopped after ~0.6 s. Returns <= 0 when nothing could be measured. static double ple_direct_rows_per_s(strata::kernels::PleTable& t) { const uint64_t n = t.rows(); if (n < 4096) return -1.0; constexpr size_t kTok = 4; // 64 rows a batch std::vector rows(kTok * 16); // one token's PLE rows are PLE_N_HEADS x PLE_HEAD_DIM floats = the compiled hidden size (2560 for Flash-Next, 4096 for q4_big): a // buffer of 2560 floats a token was a heap overflow of 24 KB at hidden 4096 (found by an ASan run; on Metal it landed in Apple's // shader-cache objects and the first pipeline of the first window died in MTLCompilerFSCache::getElementImpl) std::vector out(kTok * (size_t) strata::kernels::PLE_N_HEADS * (size_t) strata::kernels::PLE_HEAD_DIM); uint64_t x = 0x9E3779B97F4A7C15ull ^ n; const auto t0 = std::chrono::steady_clock::now(); uint64_t done = 0; double el = 0; for (int b = 0; b < 64; ++b) { for (auto& r : rows) { x ^= x << 13; x ^= x >> 7; x ^= x << 17; r = (uint32_t) (x % n); } std::string e; if (!t.gather_batch(rows.data(), kTok, out.data(), e)) return -1.0; done += rows.size(); el = std::chrono::duration(std::chrono::steady_clock::now() - t0).count(); if (el > 0.6) break; } return el > 0 ? (double) done / el : -1.0; } #if defined(STRATA_USE_HIP) && !defined(STRATA_HIP_GFX906) // The R9700 / RX 9000 "bimodal prompt speed" (0.2.0 known limit). The runtime opens the process's hardware queues // lazily, as the first stream of each kind is used, and the kernel's scheduler (MES) puts a queue on one of the // card's compute pipes when the queue first gets work. The loader threads reach their streams in a different order // every start, so in about half of the starts the prompt path's two busy queues (the compute stream and the expert // staging stream) landed on the SAME pipe: every one of the ~30,000 hand-offs of a prompt then waits for the pipe to // switch queues, and a 4K prompt reads 13% slower (p620, 1,980 vs 2,290 tok/s). Opening the queues here, one after // the other on the main thread and before any other thread exists, makes the placement the same in every start (and // it is the fast one). Streams are destroyed again; the runtime keeps the queues. // Two queues are enough (R9700, "nn": 0 slow of 32 fresh starts, unprimed 10 of 32); five (nnnnh) fixed the starts too but cost // decode 2 to 3.6% and two expert slots, four normal ones did not even fix the starts. // STRATA_HIP_QUEUE_PRIME unset: gfx1200 / gfx1201 on Linux only, "nn" (not when GPU_MAX_HW_QUEUES is 1 or 2, #3480); "0": off; any other string is a spec // ('n' = a stream at the default priority, 'h' = at the highest) for experiments on other cards. static void prime_hw_queues() { const char* env = std::getenv("STRATA_HIP_QUEUE_PRIME"); if (env != nullptr && std::strcmp(env, "0") == 0) return; const char* pv = std::getenv("STRATA_PRIMARY_DEVICE"); const int dev = pv != nullptr && std::atoi(pv) > 0 ? std::atoi(pv) : 0; int n_dev = 0; if (cudaGetDeviceCount(&n_dev) != cudaSuccess || dev >= n_dev) { (void) cudaGetLastError(); return; } const char* spec = env != nullptr && env[0] != 0 ? env : nullptr; if (spec == nullptr) { #if defined(_WIN32) return; #else cudaDeviceProp prop{}; if (cudaGetDeviceProperties(&prop, dev) != cudaSuccess || !strata::kernels::gfx_arch_is_gfx12(prop.gcnArchName)) { (void) cudaGetLastError(); return; } // #3480: with the runtime capped to two hardware queues (GPU_MAX_HW_QUEUES=1 or 2, the user's own setting) the two // primed queues are all of them: the high-priority draft stream and the side stream share them and a 4K prompt // reads 39% slower (RX 9060 XT, 681-753 against 1188-1238 tok/s). Not primed then; a spec in // STRATA_HIP_QUEUE_PRIME still is. const char* cap = std::getenv("GPU_MAX_HW_QUEUES"); if (cap != nullptr && std::atoi(cap) >= 1 && std::atoi(cap) <= 2) { std::fprintf(stderr, "strata generate: GPU queues not primed: GPU_MAX_HW_QUEUES=%s leaves none for the draft stream " "(STRATA_HIP_QUEUE_PRIME=nn primes them anyway)\n", cap); return; } spec = "nn"; #endif } if (dev != 0 && cudaSetDevice(dev) != cudaSuccess) { (void) cudaGetLastError(); return; } void* buf = nullptr; if (cudaMalloc(&buf, 256) != cudaSuccess) { (void) cudaGetLastError(); return; } int lo = 0, hi = 0; const bool have_prio = hipDeviceGetStreamPriorityRange(&lo, &hi) == hipSuccess; std::vector ss; for (const char* c = spec; *c != 0; ++c) { cudaStream_t s = nullptr; const bool ok = (*c == 'h' && have_prio) ? hipStreamCreateWithPriority(&s, hipStreamNonBlocking, hi) == hipSuccess : cudaStreamCreateWithFlags(&s, cudaStreamNonBlocking) == cudaSuccess; if (!ok) continue; cudaMemsetAsync(buf, 0, 256, s); cudaStreamSynchronize(s); ss.push_back(s); } for (cudaStream_t s : ss) cudaStreamDestroy(s); cudaFree(buf); (void) cudaGetLastError(); std::fprintf(stderr, "strata generate: opened %zu GPU queues in a fixed order (STRATA_HIP_QUEUE_PRIME=0 turns it off)\n", ss.size()); } #endif // STRATA_SPEC_PROB=1 with the default (pick) gate: a draft that fails the confidence gate is still a proposal attempt, and the // verifier gets the gated measure (core/gated_proposal.hpp). That is exact only where the window choice cannot see a draw or a // timing that the next rounds draw again. Where it cannot be kept, say why and return false: the caller keeps the older rule // (a warning, not a refusal). static bool gated_proposal_usable(bool serial_single_device, int lookup_chain, int adapt_swaps, bool pcie_share, bool own_window_rule, int window, double min_p) { const char* why = nullptr; #if defined(STRATA_GPU_METAL) why = "the Metal engine has no gated verifier"; #endif if (why == nullptr && !serial_single_device) why = "it needs serial decode on one device"; if (why == nullptr && (lookup_chain != 0 || adapt_swaps != 0 || pcie_share)) why = "it needs --lookup-chain 0, --adapt-swaps 0 and --pcie-frac 0"; if (why == nullptr && own_window_rule) why = "STRATA_SPEC_COST, STRATA_SPEC_T_CYCLE, DFlash2 and --spec-corrupt change the window by their own rule"; if (why == nullptr && window > strata::core::gated::kRows) why = "the window is wider than 8 rows"; if (why == nullptr && (!std::isfinite(min_p) || min_p < 0.0)) why = "--spec-min-p must be a finite number >= 0"; if (why == nullptr) return true; static bool warned = false; if (!warned) { warned = true; std::fprintf(stderr, "strata: STRATA_SPEC_PROB=1 keeps the older acceptance rule in this run (%s). That rule's output " "distribution is off when the confidence gate fails; STRATA_SPEC_PROB_GATE=top is exact here.\n", why); } return false; } // A draft at MTP cell c is sampled at counter c+1. The next target starts // there and needs one final cell for its bonus. Cap BEFORE any proposal draw; // a zero budget therefore means no attempt, never a discarded failed NULL. class GatedDraftLimit { public: GatedDraftLimit(strata::core::MtpDrafter& mtp, bool active, int configured_mtp, int64_t next_target_pos, int64_t context_end) : mtp_(mtp), active_(active), configured_(configured_mtp - 1) { if (active_) { const int64_t room = std::max(0, context_end - next_target_pos); mtp_.set_max_drafts((int) std::min(configured_, std::max(0, room - 1))); } } ~GatedDraftLimit() { if (active_) mtp_.set_max_drafts(configured_); } GatedDraftLimit(const GatedDraftLimit&) = delete; GatedDraftLimit& operator=(const GatedDraftLimit&) = delete; private: strata::core::MtpDrafter& mtp_; bool active_; int configured_; }; // Prepare one gated window from the last successful producer result. Context room // is fixed before consulting D; the producer was already capped before drawing. // No max_new/output-cap shortening: the ordinary emission loop owns that limit. static bool prepare_gated_window(strata::core::gated::Packet& packet, const strata::core::MtpDrafter::DraftResult& generation, strata::spec::SuffixDrafter& suffix, const strata::spec::DraftPolicy& policy, bool suffix_enabled, bool initial, int room, int configured_mtp, int vocab, float threshold, const int32_t* q, const int32_t* drafts, const float* scores, int32_t* suffix_tokens, int& match, std::string& err) { if (room < 1 || generation.budget < 0 || generation.generated < 0 || generation.generated > generation.budget || generation.budget >= room) { err = "gated proposal: invalid context room or producer result"; return false; } strata::core::gated::RootChoice root; match = 0; if (suffix_enabled && !initial && room > 1) { const int k = suffix.propose(room - 1, suffix_tokens); match = suffix.last_match(); if (k > 0) { // Prefix/configuration only: never inspect a draw or its gated width. const auto pick = policy.choose(std::min(configured_mtp, room), k, match); root.eligible = pick.lookup; root.rescue_id = suffix_tokens[0]; root.window = pick.t; } } if (!strata::core::gated::make_packet(packet, q, drafts, scores, generation.generated, generation.budget, room, vocab, threshold, initial, root)) { err = std::string("gated proposal: ") + packet.error; return false; } return true; } // #4350: after a fatal GPU error (an illegal memory access, a launch failure) the device context cannot be used again, and unwinding the // destructors on it can hang until the stall watchdog (#224). A failed decode window / commit therefore ends the engine at once when the // runtime holds a sticky error, with "ERR fatal GPU error: ..." as its last stdout line: the server fails the request in flight with a 503 // and starts the engine again on the next request, like any engine death. // STRATA_INJECT_FATAL=N (a test hook, off when unset): the Nth decode window fails with the text of a real fatal error, the same way. [[noreturn]] static void exit_gpu_fatal(const std::string& what) { std::fprintf(stderr, "strata serve: fatal GPU error (%s): the engine ends so that the server can start it again\n", what.c_str()); std::fflush(stderr); std::printf("ERR fatal GPU error: %s\n", what.c_str()); std::fflush(stdout); std::_Exit(3); } static void exit_if_gpu_fatal(const std::string& err) { static const long inject = [] { const char* v = std::getenv("STRATA_INJECT_FATAL"); return v != nullptr ? std::atol(v) : 0L; }(); static long windows = 0; if (inject > 0 && ++windows == inject) { // STRATA_INJECT_FATAL_ONCE=: fires once across restarts (the file is made when it fires; while it exists nothing is injected) const char* once = std::getenv("STRATA_INJECT_FATAL_ONCE"); bool fire = true; if (once != nullptr && *once) { if (std::FILE* t = std::fopen(once, "rb")) { std::fclose(t); fire = false; } else if (std::FILE* t2 = std::fopen(once, "wb")) std::fclose(t2); } if (fire) exit_gpu_fatal("injected (STRATA_INJECT_FATAL): an illegal memory access was encountered"); } const cudaError_t sticky = cudaPeekAtLastError(); if (sticky != cudaSuccess) { // (by the runtime's own text, so that CUDA, HIP and SYCL builds read it the same way) const std::string text = cudaGetErrorString(sticky); static const char* const gone[] = {"illegal memory access", "illegal address", "unspecified launch failure", "launch failure", "hardware exception", "illegal instruction", "misaligned address", "uncorrectable", "launch timed out", "device-side assert"}; bool context_gone = false; for (const char* w : gone) if (text.find(w) != std::string::npos) context_gone = true; if (context_gone) exit_gpu_fatal(err.empty() ? std::string(cudaGetErrorString(sticky)) : err); } } #if defined(STRATA_USE_HIP) && defined(_WIN32) static int engine_main(int argc, char** argv) { // main() is at the end of this file (#3431) #else int main(int argc, char** argv) { #endif // **UNBUFFERED, BECAUSE THE INTERESTING OUTPUT IS THE OUTPUT BEFORE A CRASH.** `stdout` redirected to a // pipe or a file is block-buffered, so a program that dies loses every line it had already printed - which // turns "it crashed at step 7" into "it crashed somewhere", and the difference is a debugging session. std::setvbuf(stdout, nullptr, _IONBF, 0); strata::platform::restore_normal_io_priority(); // #4733: not the low disk priority of the program that started this one #if defined(STRATA_USE_HIP) && defined(_WIN32) { // 0.2.1.2: hipblas / libhipblaslt / rocblas are delay-loaded (CMakeLists.txt) and live in \rocm\bin, which only the // launcher puts on PATH; make the folder part of this process's DLL search, so `strata.exe --version` run straight from the // package folder works. The HIP runtime and the C++ runtime sit beside the exe and are found without it. wchar_t exe[MAX_PATH * 2] = {}; const DWORD n = GetModuleFileNameW(nullptr, exe, (DWORD) (sizeof(exe) / sizeof(exe[0]))); if (n > 0 && n < sizeof(exe) / sizeof(exe[0])) { std::wstring dir(exe, n); const size_t cut = dir.find_last_of(L"\\/"); if (cut != std::wstring::npos) { dir.resize(cut); dir += L"\\rocm\\bin"; if (GetFileAttributesW(dir.c_str()) != INVALID_FILE_ATTRIBUTES) SetDllDirectoryW(dir.c_str()); } } } #endif // `strata --version` / `-V` (also `strata generate --version`): the version and nothing else, before any GPU is touched for (int i = 1; i < argc && i < 3; ++i) { if (std::strcmp(argv[i], "--version") == 0 || std::strcmp(argv[i], "-V") == 0) { std::printf("strata %s\n", STRATA_VERSION); return 0; } // `strata --families`: the GGUF architectures this build runs (setup asks before it installs one) if (std::strcmp(argv[i], "--families") == 0) { #if defined(STRATA_HAVE_QWEN35) std::printf("qwen4exp qwen35moe\n"); #else std::printf("qwen4exp\n"); #endif return 0; } // `strata --geometry`: the name of the model shape the kernels are compiled for (the geometry header's kGeometryName: flash_next for the default build); // Control checks it against the shape of the package's signed manifest (strata_control/shape_engine.py) if (std::strcmp(argv[i], "--geometry") == 0) { std::printf("%s\n", strata::core::kGeometryName); return 0; } } #if (defined(STRATA_USE_HIP) || defined(STRATA_HIP_GFX906)) && !defined(_WIN32) // AMD, a file-backed arena (STRATA_ARENA_MMAP): ROCclr copies a pageable source of 1 MiB or more by locking its // pages in place (a GPU userptr), and keeps them - so every expert the VRAM fill copied from the mapped // experts.bin stayed resident, the release of the VRAM-held ones was undone by the driver at once, and a // 32 GB PC ran with ~0.3 GB free: the kernel swapped, and a turn's checkpoint took 25-80 s. Above this size // ROCclr stages through its own pinned buffers instead; decode is unchanged (49.06 vs 49.16 ms/window). if (std::getenv("STRATA_ARENA_MMAP") && std::getenv("STRATA_ARENA_MMAP")[0] == '1') setenv("GPU_PINNED_MIN_XFER_SIZE", "1000000", 0); // MiB; an explicit setting wins #endif #if defined(STRATA_USE_HIP) && defined(__linux__) // XFER (kfd_quiet.hpp): on an integrated gfx11 (every GPU node of the KFD topology a gfx1103 / gfx1150 / gfx1151: the class is // read from the topology files, since the device properties need HIP up) the same setting by default, so that no pageable // source of a copy (the check's vectors at load, the lent refill's blobs without a registered arena) becomes a userptr the // kernel can move under a running dispatch. A value the caller set wins; STRATA_KFD_QUIET(_XFER)=0 sets nothing. { const bool cls = strata::core::kfd_quiet::nodes_in_class(strata::core::kfd_quiet::read_topology("/sys/class/kfd/kfd/topology/nodes")); if (const char* v = strata::core::kfd_quiet::xfer_value(cls, std::getenv("STRATA_KFD_QUIET"), std::getenv("STRATA_KFD_QUIET_XFER"), std::getenv("GPU_PINNED_MIN_XFER_SIZE"))) { setenv("GPU_PINNED_MIN_XFER_SIZE", v, 0); if (std::getenv("STRATA_TRACE") != nullptr) std::fprintf(stderr, "strata trace: kfd quiet: GPU_PINNED_MIN_XFER_SIZE=%s (pageable copies staged by the runtime)\n", v); } } #endif // Load every CUDA kernel when the context is created, before the expert cache takes the free VRAM. With the // default lazy loading, a kernel first used mid-prompt (MMQ for IQ3_XXS at 64K+ on a 12 GB card) found no VRAM // left for its code and the engine ended ("out of memory: cudaFuncSetAttribute"). Costs ~30 MB of VRAM. if (std::getenv("CUDA_MODULE_LOADING") == nullptr) { #if defined(_WIN32) _putenv_s("CUDA_MODULE_LOADING", "EAGER"); #else setenv("CUDA_MODULE_LOADING", "EAGER", 0); #endif } if (launch_blocking()) std::fprintf(stderr, "warning: CUDA_LAUNCH_BLOCKING=1: the verify windows cannot run with blocking launches, so " "the first one after a prompt hangs until the watchdog ends the engine (#1341). Unset it; " "STRATA_PF_STEP_SYNC=1 narrows down a failing prompt step without it\n"); // --gpu LIST pins the visible GPUs (nvidia-smi/PCI order) from the command line instead of the caller's // environment: CUDA_VISIBLE_DEVICES is read at the first CUDA call, so this has to happen here, before // anything else. The value itself is consumed again by the option loop below. for (int i = 1; i + 1 < argc; ++i) { if (std::string(argv[i]) != "--gpu") continue; // The caller's own environment is overridden, so say so (a stale CUDA_VISIBLE_DEVICES from a launcher // would otherwise silently lose to the flag). const char* envname = "CUDA_VISIBLE_DEVICES"; #if defined(STRATA_USE_HIP) || defined(STRATA_HIP_GFX906) envname = "HIP_VISIBLE_DEVICES"; // the AMD runtime ignores CUDA_VISIBLE_DEVICES (serve/server.py sets this one) #endif const char* prev = std::getenv(envname); if (prev && prev[0] && std::string(prev) != argv[i + 1]) std::fprintf(stderr, "warning: --gpu %s overrides %s=%s from the environment\n", argv[i + 1], envname, prev); #if defined(_WIN32) _putenv_s("CUDA_DEVICE_ORDER", "PCI_BUS_ID"); _putenv_s(envname, argv[i + 1]); #else setenv("CUDA_DEVICE_ORDER", "PCI_BUS_ID", 1); setenv(envname, argv[i + 1], 1); #endif break; } #if defined(STRATA_HAVE_QWEN35) // **THE FAMILY SWITCH.** A Qwen3.6-35B-A3B file (GGUF architecture qwen35moe) runs on its own engine path // (src/qwen35), decided here from the file's header before any of this engine's state exists; every other file // goes on below exactly as before. Only the architecture string is read (the header of --native's shard). for (int i = 1; i + 1 < argc; ++i) { if (std::strcmp(argv[i], "--native") != 0 && std::strcmp(argv[i], "--model") != 0) continue; bool qwen35 = false; try { const strata::GgufFile meta(strata::gguf_split_paths(argv[i + 1]).front()); qwen35 = strata::model_family(meta) == strata::ModelFamily::Qwen35Moe; } catch (const std::exception&) { // not readable here: the normal path below reports it } if (qwen35) return strata::qwen35::run(argc, argv); break; } #endif #if defined(STRATA_USE_HIP) && !defined(STRATA_HIP_GFX906) prime_hw_queues(); #endif Options o; bool have_tokens = false; bool have_logits_stride = false; bool ram_keep_by_flag = false; for (int i = 1; i < argc; ++i) { const std::string a = argv[i]; auto next = [&](const char* what) -> const char* { if (i + 1 >= argc) { std::fprintf(stderr, "%s needs a value\n", what); std::exit(2); } return argv[++i]; }; bool parsed = true; if (a == "--help" || a == "-h") { usage(); return 0; } else if (a == "--gpu") { (void) next("--gpu"); } // applied at startup, before any CUDA call else if (a == "--pack") o.pack = next("--pack"); else if (a == "--tokens") { if (have_tokens) { std::fprintf(stderr, "supply one token input only\n"); return 2; } std::string e; if (!parse_i64_list(next("--tokens"), o.tokens, e)) { std::fprintf(stderr, "%s\n", e.c_str()); return 2; } have_tokens = true; } else if (a == "--tokens-file") { if (have_tokens) { std::fprintf(stderr, "supply one token input only\n"); return 2; } std::ifstream input(next("--tokens-file")); if (!input) { std::fprintf(stderr, "cannot open token file\n"); return 2; } std::string text((std::istreambuf_iterator(input)), std::istreambuf_iterator()); if (input.bad()) { std::fprintf(stderr, "cannot read token file\n"); return 2; } std::string error; if (text.find('\0') != std::string::npos || !parse_i64_list(text.c_str(), o.tokens, error)) { std::fprintf(stderr, "malformed token file: %s\n", error.c_str()); return 2; } have_tokens = true; } else if (a == "--max-new") o.max_new = std::atoll(next("--max-new")); else if (a == "--max-context") o.max_context = std::atoll(next("--max-context")); else if (a == "--rope-scaling") o.rope_scaling = next("--rope-scaling"); else if (a == "--rope-scale") o.rope_scale = std::atof(next("--rope-scale")); else if (a == "--rope-freq-base") o.rope_freq_base = std::atof(next("--rope-freq-base")); else if (a == "--rope-freq-scale") o.rope_freq_scale = std::atof(next("--rope-freq-scale")); else if (a == "--yarn-orig-ctx") o.yarn_orig_ctx = std::atof(next("--yarn-orig-ctx")); else if (a == "--yarn-ext-factor") o.yarn_ext_factor = std::atof(next("--yarn-ext-factor")); else if (a == "--yarn-attn-factor") o.yarn_attn_factor = std::atof(next("--yarn-attn-factor")); else if (a == "--yarn-beta-fast") o.yarn_beta_fast = std::atof(next("--yarn-beta-fast")); else if (a == "--yarn-beta-slow") o.yarn_beta_slow = std::atof(next("--yarn-beta-slow")); else if (a == "--greedy") o.greedy = true; else if (a == "--seed") { o.seed = (uint64_t) std::atoll(next("--seed")); o.greedy = false; } else if (a == "--top-k") o.top_k = std::atoi(next("--top-k")); else if (a == "--top-p") o.top_p = (float) std::atof(next("--top-p")); else if (a == "--temperature") o.temperature = (float) std::atof(next("--temperature")); else if (a == "--dump-logits") o.dump_logits = next("--dump-logits"); else if (a == "--logits-stride") { if (have_logits_stride) { std::fprintf(stderr, "--logits-stride must be supplied only once\n"); return 2; } if (!strata::program::logits_selection::parse_stride(next("--logits-stride"), o.logits_stride)) { std::fprintf(stderr, "--logits-stride requires a positive decimal int64\n"); return 2; } have_logits_stride = true; } else if (a == "--dump-residual") o.dump_residual = next("--dump-residual"); else if (a == "--dump-mixed") o.dump_mixed = next("--dump-mixed"); else if (a == "--dump-layers") o.dump_layers = next("--dump-layers"); else if (a == "--dump-halves") o.dump_halves = next("--dump-halves"); else if (a == "--dump-routing") o.dump_routing = next("--dump-routing"); else if (a == "--ple-gguf") o.ple_gguf = next("--ple-gguf"); else if (a == "--no-ple") o.no_ple = true; else if (a == "--ple-io") { o.ple_io = next("--ple-io"); o.ple_io_explicit = true; } else if (a == "--ple-row-cache") o.ple_row_cache = std::atoll(next("--ple-row-cache")); else if (a == "--ple-inflight") o.ple_inflight = std::atoi(next("--ple-inflight")); else if (a == "--ple-delay-us") o.ple_delay_us = std::atof(next("--ple-delay-us")); 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; else if (a == "--gr-native-mmvf") o.gr_native_mmvf = true; else if (a == "--native-bf16") o.native_bf16 = true; else if (a == "--native-bf16-extra") o.native_bf16_extra = true; else if (a == "--native-ple-key") o.native_ple_key = true; else if (a == "--native-moe-combine") o.native_moe_combine = true; else if (a == "--native-gdn") o.native_gdn = true; else if (a == "--native-flash-attn-short") o.native_flash_attn_short = true; else if (a == "--native-qsa-indexer") o.native_qsa_indexer = true; else if (a == "--native-qsa") o.native_qsa = true; else if (a == "--native-rope") o.native_rope = true; else if (a == "--native-ple-postops") o.native_ple_postops = true; else if (a == "--native-router") o.native_router = true; else if (a == "--cpu-oracle-q8-0") o.cpu_oracle_q8_0 = true; else if (a == "--native") o.native_preset = next("--native"); else if (a == "--native-head-gguf") o.native_head_gguf = next("--native-head-gguf"); else if (a == "--embd-gguf") o.embd_gguf = next("--embd-gguf"); else if (a == "--native-dense-gguf") o.native_dense_gguf.push_back(next("--native-dense-gguf")); else if (a == "--no-capture") o.no_capture = true; else if (a == "--no-pool") o.no_pool = true; else if (a == "--sync-every-layer") o.sync_every_layer = true; else if (a == "--stage-timing") o.stage_timing = true; else if (a == "--graph-only") o.graph_only = true; else if (a == "--gpu-only-full") o.gpu_only_full = true; else if (a == "--pool-workers") o.pool_workers = std::atoi(next("--pool-workers")); else if (a == "--pool-tasks") { const char* v = next("--pool-tasks"); char* end = nullptr; const long tasks = std::strtol(v, &end, 10); if (end == v || *end != '\0' || tasks < 0 || tasks > strata::kernels::cpu::ExpertPool::kMaxTasks) { std::fprintf(stderr, "strata generate: --pool-tasks expects an integer in 0..4096 (0 = automatic)\n"); return 2; } o.pool_tasks = (int) tasks; } else if (a == "--host-core") { o.host_core = next("--host-core"); if (o.host_core != "first" && o.host_core != "last" && o.host_core != "sibling") { std::fprintf(stderr, "strata generate: unknown --host-core value '%s' (expected first, last or sibling)\n", o.host_core.c_str()); return 2; } } else if (a == "--pool-cores") o.pool_cores = next("--pool-cores"); else if (a == "--aux-cpus") { o.aux_cpus = next("--aux-cpus"); std::string aerr; strata::aux_cpus::Config acfg; if (!strata::aux_cpus::parse_spec(o.aux_cpus, acfg, aerr)) { std::fprintf(stderr, "strata generate: %s\n", aerr.c_str()); return 2; } } else if (a == "--pool-affinity") { const std::string v = next("--pool-affinity"); if (v == "auto") o.pool_affinity = strata::kernels::cpu::PoolAffinity::Auto; else if (v == "p-cores" || v == "pcores") o.pool_affinity = strata::kernels::cpu::PoolAffinity::PCores; else if (v == "all") o.pool_affinity = strata::kernels::cpu::PoolAffinity::All; else if (v == "measure") o.pool_measure = true; else { std::fprintf(stderr, "strata generate: unknown --pool-affinity value '%s' (expected auto, p-cores, all or measure)\n", v.c_str()); return 2; } } else if (a == "--no-host-worker") o.no_host_worker = true; else if (a == "--no-ple-prefetch") o.no_ple_prefetch = true; else if (a == "--coupled-draft") o.coupled_draft = true; else if (a == "--no-coupled-draft") o.coupled_draft = false; else parsed = false; // The chain continues here in a second statement: one chain of 120+ `else if` passed MSVC's limit of 128 // nested blocks (C1061). The order of the tests and what each does are unchanged. if (!parsed) { if (a == "--expert-cache") { const std::string v = next("--expert-cache"); o.expert_cache = (v == "auto") ? -1 : std::atoi(v.c_str()); } else if (a == "--expert-cache-device1" || a == "--expert-cache-device2" || a == "--expert-cache-device3") { const size_t r = (size_t) (a.back() - '1'); const std::string v = next(a.c_str()); o.expert_cache_remote_auto[r] = v == "auto"; o.expert_cache_remote[r] = v == "auto" ? std::numeric_limits::max() : std::atoi(v.c_str()); } else if (a == "--remote-expert-opt") o.remote_expert_opt = true; else if (a == "--expert-cache-remote-placement") o.expert_cache_remote_placement = next("--expert-cache-remote-placement"); else if (a == "--vram-reserve-mib") { o.vram_reserve_mib = std::atoi(next("--vram-reserve-mib")); o.vram_reserve_given = true; } else if (a == "--vram-reserve-later-mib") o.vram_reserve_later_mib = std::atoi(next("--vram-reserve-later-mib")); else if (a == "--prefill") { const std::string v = next("--prefill"); o.prefill_auto = v == "auto" || v.rfind("auto:", 0) == 0; // #282: auto:N (N = 16384 or 32768) or STRATA_PREFILL_AUTO_MAX lets auto take chunks above 8192 const char* env_max = std::getenv("STRATA_PREFILL_AUTO_MAX"); const long long want_max = v.rfind("auto:", 0) == 0 ? std::atoll(v.c_str() + 5) : (o.prefill_auto && env_max != nullptr ? std::atoll(env_max) : 8192); o.prefill_auto_max = want_max >= 32768 ? 32768 : want_max >= 16384 ? 16384 : 8192; o.prefill_chunk = o.prefill_auto ? o.prefill_auto_max : std::atoll(v.c_str()); { // #1630: Windows HIP, RX 7900 XTX: a first long prompt at 8192-token chunks charged ~70 GB of commit and // killed the engine; 7500 and below were flat. A bare auto stops at 6144; a chunk the user names stays. #if defined(STRATA_USE_HIP) && defined(_WIN32) constexpr bool win_hip = true; #else constexpr bool win_hip = false; #endif const bool bare_auto = v == "auto" && !(o.prefill_auto && env_max != nullptr); o.prefill_auto_bare = bare_auto && o.prefill_auto; o.prefill_auto_cap = strata::platform::host_limits::auto_chunk_cap(win_hip, bare_auto && o.prefill_auto); if (o.prefill_auto_cap > 0) o.prefill_chunk = std::min(o.prefill_chunk, o.prefill_auto_cap); if (strata::platform::host_limits::warn_user_chunk(win_hip, bare_auto, o.prefill_chunk)) o.prefill_cap_warn = v; // printed once the device is known (gfx1151 does not print it) } } else if (a == "--prefill-pipe") o.prefill_pipe = std::max(0.0, std::atof(next("--prefill-pipe"))); else if (a == "--no-split-rows") o.no_split_rows = true; else if (a == "--no-prefill-borrow") o.no_prefill_borrow = true; else if (a == "--vram-elastic") o.vram_elastic = true; else if (a == "--vram-segment-mib") o.vram_segment_mib = std::atoll(next("--vram-segment-mib")); else if (a == "--prefill-until") o.prefill_until = std::atoll(next("--prefill-until")); else if (a == "--dump-final-r") o.dump_final_r = next("--dump-final-r"); else if (a == "--spec") o.spec = std::atoi(next("--spec")); else if (a == "--batch") o.batch = std::atoi(next("--batch")); else if (a == "--slots") o.batch = std::atoi(next("--slots")); // the same as --batch else if (a == "--trim-stage-weights") { o.trim_stage_weights = true; o.trim_stage_flag = 1; } else if (a == "--batch-groups") { const char* bgv = next("--batch-groups"); o.batch_groups_set = true; if (std::strcmp(bgv, "auto") == 0) o.batch_groups_auto = true; else o.batch_groups = std::atoi(bgv); } else if (a == "--batch-mtp") o.batch_mtp = true; else if (a == "--spec-oracle") o.spec_oracle = next("--spec-oracle"); else if (a == "--spec-corrupt") o.spec_corrupt = std::atoi(next("--spec-corrupt")); else if (a == "--spec-follow") o.spec_follow = next("--spec-follow"); else if (a == "--window-hashes") o.window_hashes = next("--window-hashes"); else if (a == "--mtp") o.mtp = next("--mtp"); else if (a == "--mtp-window") o.mtp_window = std::atoll(next("--mtp-window")); else if (a == "--pcie-frac") o.pcie_frac = std::atof(next("--pcie-frac")); else if (a == "--adapt-every") { o.adapt_every = std::atoi(next("--adapt-every")); o.adapt_every_given = true; } else if (a == "--ram-profile") o.ram_profile = next("--ram-profile"); else if (a == "--ram-profile-save") o.ram_profile_save = next("--ram-profile-save"); else if (a == "--ram-adapt") o.ram_adapt = std::max(0, std::atoi(next("--ram-adapt"))); else if (a == "--ram-adapt-decay") o.ram_adapt_decay = std::clamp((float) std::atof(next("--ram-adapt-decay")), 0.0f, 1.0f); else if (a == "--adapt-decay") o.adapt_decay = strata::program::adapt_decay_checked(std::atof(next("--adapt-decay"))); // #1284: outside 0..1 -> 0.7, said else if (a == "--adapt-min-gain") o.adapt_min_gain = (float) std::atof(next("--adapt-min-gain")); else if (a == "--adapt-async") { o.adapt_async = std::atoi(next("--adapt-async")) != 0 ? 1 : 0; o.adapt_async_given = o.adapt_async; } else if (a == "--spec-min-p") o.spec_min_p = std::atof(next("--spec-min-p")); else if (a == "--stop-eos") o.stop_eos = true; else if (a == "--spec-split") o.spec_split = true; else if (a == "--layer-split") o.layer_split = next("--layer-split"); else if (a == "--split-device") o.split_device = next("--split-device"); else if (a == "--split-skip-if-fits") o.split_skip_if_fits = true; else if (a == "--pcie-mode") o.pcie_mode = next("--pcie-mode"); else if (a == "--serve") o.serve = true; else if (a == "--vision") o.vision = true; else if (a == "--session-save-reclaim") o.session_save_reclaim = true; else if (a == "--prompt-cache") o.prompt_cache = std::max(0, std::atoi(next("--prompt-cache"))); else if (a == "--conversation-cache-mib" || a == "--conversation-cache-slots" || a == "--conversation-cache-min-free-mib" || a == "--conversation-cache-min-tokens" || a == "--conversation-cache-park-gain" || a == "--session-min-free-mib" || a == "--memory-limit-mib") { const std::string value = next(a.c_str()); int64_t number = 0; const auto result = std::from_chars(value.data(), value.data() + value.size(), number); const int64_t limit = (a == "--conversation-cache-slots" || a == "--conversation-cache-min-tokens" || a == "--conversation-cache-park-gain") ? INT32_MAX : INT64_MAX / (1024 * 1024); if (result.ec != std::errc{} || result.ptr != value.data() + value.size() || number < 0 || number > limit) { std::fprintf(stderr, "%s needs a nonnegative integer within range\n", a.c_str()); return 2; } if (a == "--conversation-cache-mib") o.conversation_cache_mib = number; else if (a == "--conversation-cache-min-free-mib") o.conversation_cache_min_free_mib = number; else if (a == "--conversation-cache-min-tokens") o.conversation_cache_min_tokens = number; else if (a == "--conversation-cache-park-gain") o.conversation_cache_park_gain = number; else if (a == "--session-min-free-mib") o.session_min_free_mib = number; else if (a == "--memory-limit-mib") o.memory_limit_mib = number; else o.conversation_cache_slots = (int) number; } else if (a == "--conversation-disk") o.conversation_disk = next("--conversation-disk"); else if (a == "--conversation-disk-gib") o.conversation_disk_gib = std::max(0LL, std::atoll(next("--conversation-disk-gib"))); else if (a == "--prompt-cache-tail") o.prompt_cache_tail = true; else if (a == "--prompt-cache-spread") o.prompt_cache_spread = true; else if (a == "--prompt-cache-every") o.prompt_cache_every = std::max(0LL, std::atoll(next("--prompt-cache-every"))); else if (a == "--prompt-cache-root") o.prompt_cache_root = std::max(0LL, std::atoll(next("--prompt-cache-root"))); else if (a == "--turn-token") o.turn_token = std::atoll(next("--turn-token")); else if (a == "--tail-role-token") o.tail_role_token = std::atoll(next("--tail-role-token")); else if (a == "--short-read") { o.short_read = std::max(0LL, std::atoll(next("--short-read"))); o.short_read_set = true; } else if (a == "--prefill-head-alias") o.prefill_head_alias = true; else if (a == "--pipeline-windows") o.pipeline_windows = std::max(0, std::min(2, std::atoi(next("--pipeline-windows")))); else if (a == "--no-trim-stage-weights") { o.trim_stage_weights = false; o.trim_stage_flag = 0; } else if (a == "--suffix-draft") o.suffix_draft = std::max(0, std::atoi(next("--suffix-draft"))); else if (a == "--mtp-max-t") o.mtp_max_t = std::max(0, std::atoi(next("--mtp-max-t"))); else if (a == "--lookup-max-t") o.lookup_max_t = std::max(0, std::atoi(next("--lookup-max-t"))); else if (a == "--lookup-sizes") o.lookup_sizes = next("--lookup-sizes"); else if (a == "--lookup-chain") o.lookup_chain = std::clamp(std::atoi(next("--lookup-chain")), 0, 7); else if (a == "--lookup-chain-min") o.lookup_chain_min = std::max(3, std::atoi(next("--lookup-chain-min"))); else if (a == "--mtp-hnorm") { const std::string v = next("--mtp-hnorm"); if (v != "pooled" && v != "stream") { std::fprintf(stderr, "strata generate: --mtp-hnorm takes pooled or stream\n"); return 2; } o.mtp_hnorm_stream = v == "stream"; } else if (a == "--mtp-q4") { o.mtp_q4 = next("--mtp-q4"); if (o.mtp_q4 != "all" && o.mtp_q4 != "proj" && o.mtp_q4 != "head") { std::fprintf(stderr, "strata generate: --mtp-q4 takes all, proj or head\n"); return 2; } } else if (a == "--mtp-draft-vocab") o.mtp_draft_vocab = next("--mtp-draft-vocab"); else if (a == "--draft") { o.draft = next("--draft"); if (o.draft == "auto") { o.draft = "dflash2"; o.draft_auto = true; } if (o.draft != "dflash2" && o.draft != "mtp") { std::fprintf(stderr, "strata generate: --draft takes mtp, dflash2 or auto\n"); std::exit(2); } } else if (a == "--draft-rule") o.draft_rule = next("--draft-rule"); else if (a == "--draft-mtp-spec") { o.draft_mtp_spec = std::max(2, std::atoi(next("--draft-mtp-spec"))); o.draft_mtp_spec_set = true; } else if (a == "--draft-mtp-min-p") o.draft_mtp_min_p = std::clamp(std::atof(next("--draft-mtp-min-p")), 0.0, 1.0); else if (a == "--draft-model") o.draft_model = next("--draft-model"); else if (a == "--draft-fallback") { o.draft_fallback = next("--draft-fallback"); if (o.draft_fallback != "mtp" && o.draft_fallback != "none") { std::fprintf(stderr, "strata generate: --draft-fallback takes mtp or none\n"); std::exit(2); } } else if (a == "--draft-conf") o.draft_conf = std::clamp(std::atof(next("--draft-conf")), 0.0, 1.0); else if (a == "--draft-cap") o.draft_cap = std::max(0, std::atoi(next("--draft-cap"))); else if (a == "--control-vector") o.cvec_files.push_back({next("--control-vector"), 1.0f}); else if (a == "--control-vector-scaled") { // FILE:SCALE, comma-separated; the LAST colon splits, so a Windows path (C:\...) keeps its drive std::stringstream list(next("--control-vector-scaled")); std::string item; while (std::getline(list, item, ',')) { const size_t colon = item.rfind(':'); char* end = nullptr; const float sc = colon == std::string::npos ? 0.0f : std::strtof(item.c_str() + colon + 1, &end); if (colon == std::string::npos || colon == 0 || end == item.c_str() + colon + 1 || *end != '\0') { std::fprintf(stderr, "--control-vector-scaled: expected FILE:SCALE, got '%s'\n", item.c_str()); return 2; } o.cvec_files.push_back({item.substr(0, colon), sc}); } } else if (a == "--control-vector-layer-range") { o.cvec_first = std::atoi(next("--control-vector-layer-range")); o.cvec_last = std::atoi(next("--control-vector-layer-range")); } else if (a == "--cvec-mode") { const std::string m = next("--cvec-mode"); if (m == "project") o.cvec_mode = 0; else if (m == "add") o.cvec_mode = 1; else { std::fprintf(stderr, "--cvec-mode: add or project, got '%s'\n", m.c_str()); return 2; } } else if (a == "--cvec-dir") { const std::string d = next("--cvec-dir"); if (d == "per-layer") o.cvec_single = -1; else if (d.rfind("single:", 0) == 0) o.cvec_single = std::atoi(d.c_str() + 7); else { std::fprintf(stderr, "--cvec-dir: per-layer or single:L, got '%s'\n", d.c_str()); return 2; } } else if (a == "--no-spec-split") o.spec_split = false; else if (a == "--eos-ids") { std::string e; if (!parse_i64_list(next("--eos-ids"), o.eos_ids, e)) { std::fprintf(stderr, "--eos-ids: %s\n", e.c_str()); return 2; } o.stop_eos = true; } else if (a == "--adapt-swaps") o.adapt_swaps = std::atoi(next("--adapt-swaps")); else if (a == "--expert-cache-cpu-order") o.expert_cache_cpu_order = true; else if (a == "--expert-cache-per-layer") o.expert_cache_per_layer = true; else if (a == "--peer-device") o.peer_device = std::atoi(next("--peer-device")); else if (a == "--peer-reserve-mib") o.peer_reserve_mib = std::atoi(next("--peer-reserve-mib")); else if (a == "--peer-slots") o.peer_slots = std::atoll(next("--peer-slots")); else if (a == "--peer-adapt-swaps") o.peer_adapt_swaps = std::atoi(next("--peer-adapt-swaps")); else if (a == "--peer-prefill-rows") o.peer_prefill_rows = std::atoll(next("--peer-prefill-rows")); else if (a == "--no-hit-poke") o.no_hit_poke = true; else if (a == "--expert-profile") o.expert_profile = next("--expert-profile"); else if (a == "--expert-profile-save") o.expert_profile_save = next("--expert-profile-save"); else if (a == "--draft-costs") o.draft_costs = next("--draft-costs"); else if (a == "--draft-costs-key") o.draft_costs_key = next("--draft-costs-key"); else if (a == "--expert-profile-save-every") o.expert_profile_save_min = std::atof(next("--expert-profile-save-every")); else if (a == "--gpu-stages") o.gpu_stages = true; else if (a == "--mmap-experts") o.mmap_experts = true; else if (a == "--shared-expert-arena") o.shared_expert_arena = next("--shared-expert-arena"); else if (a == "--resident-cpu-experts") o.resident_cpu_experts = o.resident_cpu_explicit = true; else if (a == "--resident-experts") { o.mmap_experts = o.resident_cpu_experts = o.resident_pin = o.resident_soft = true; o.resident_headroom = 4ull << 30; // A/B arms: STRATA_RESIDENT_PIN=0 keeps the copy pageable (the --resident-cpu-experts form); // STRATA_RESIDENT_HEADROOM_GIB=N leaves N GiB of the available RAM free instead of 4 o.resident_pin = strata::core::resident_pin_from_env(std::getenv("STRATA_RESIDENT_PIN")); if (const char* v = std::getenv("STRATA_RESIDENT_HEADROOM_GIB"); v != nullptr && std::atof(v) >= 0.0) o.resident_headroom = (uint64_t) (std::atof(v) * 1073741824.0); } else if (a == "--ram-keep-gib") { const double gib = std::atof(next("--ram-keep-gib")); if (!(gib >= 0.0)) { std::fprintf(stderr, "strata generate: --ram-keep-gib needs N >= 0\n"); return 2; } o.ram_keep = strata::core::ram_keep_from_gib(gib); ram_keep_by_flag = true; } else if (a == "--resident-budget-gib") { const double gib = std::atof(next("--resident-budget-gib")); if (!(gib > 0.0)) { std::fprintf(stderr, "strata generate: --resident-budget-gib needs N > 0\n"); return 2; } o.resident_budget = (uint64_t) (gib * 1073741824.0); o.mmap_experts = o.resident_cpu_experts = true; o.resident_pin = strata::core::resident_pin_from_env(std::getenv("STRATA_RESIDENT_PIN")); o.resident_headroom = 4ull << 30; if (const char* v = std::getenv("STRATA_RESIDENT_HEADROOM_GIB"); v != nullptr && std::atof(v) >= 0.0) o.resident_headroom = (uint64_t) (std::atof(v) * 1073741824.0); } else if (a == "--stats") o.stats = true; else if (a == "--shared-late") o.shared_late = true; else if (a == "--keep-canonical") o.keep_canonical = true; else if (a == "--no-token-graph") o.no_token_graph = true; else if (a == "--no-fused-gr") o.no_fused_gr = true; else if (a == "--no-fast-attn") o.no_fast_attn = true; else if (a == "--no-publish-kernel") o.no_publish_kernel = true; else if (a == "--no-fused-gdn") o.no_fused_gdn = true; else if (a == "--no-fast-select") o.no_fast_select = true; else { // An unknown flag is an ERROR and not a warning: a typo'd `--max-neww` that silently generated 16 // tokens would look like a working run. std::fprintf(stderr, "unknown argument: %s\n", a.c_str()); usage(); return 2; } } } { // --ram-keep-gib W (or STRATA_RAM_KEEP_GIB, for a program that cannot pass the flag; the flag wins): the RAM to leave free. It also // raises the headroom of the explicit RAM modes (--resident-budget-gib, --resident-experts) to at least W, unless // STRATA_RESIDENT_HEADROOM_GIB is set (that value wins). if (!ram_keep_by_flag) if (const char* v = std::getenv("STRATA_RAM_KEEP_GIB"); v != nullptr && v[0] != '\0' && std::atof(v) > 0.0) o.ram_keep = strata::core::ram_keep_from_gib(std::atof(v)); const char* hv = std::getenv("STRATA_RESIDENT_HEADROOM_GIB"); if (o.ram_keep > 0 && !(hv != nullptr && std::atof(hv) >= 0.0) && o.resident_headroom < o.ram_keep) o.resident_headroom = o.ram_keep; } #if defined(STRATA_USE_HIP) { // gfx1151 (Strix Halo): the switches that are exact there are on by default (strata/core/arch_defaults.hpp); before // any engine code reads its switches (they are read at first use), and the user's own settings are kept cudaDeviceProp ad{}; if (cudaGetDeviceProperties(&ad, 0) == cudaSuccess) { // an integrated Radeon (UMA / APU: the device property, not the name): the matrix-core prompt set is on by // default. Only when EVERY visible GPU is integrated and of the same architecture, so a box that also holds a // discrete card (whichever the engine ends up using) keeps the old defaults. bool all_igpu = ad.integrated != 0; int ndev = 0; if (all_igpu && cudaGetDeviceCount(&ndev) == cudaSuccess) { for (int d = 1; d < ndev && d < 64; ++d) { cudaDeviceProp od{}; if (cudaGetDeviceProperties(&od, d) != cudaSuccess || od.integrated == 0 || std::strncmp(od.gcnArchName, ad.gcnArchName, 7) != 0) { all_igpu = false; (void) cudaGetLastError(); break; } } } { // Linux, every visible card gfx12: the chunked GDN scan from the first chunk (owner yes 2026-11-07; was the launcher's GDN_STACK_GFX12). // Before apply_arch_defaults, so its "30,000+ tokens" line is not printed when the variable is set. bool all_gfx12 = true; int nd12 = 0; if (cudaGetDeviceCount(&nd12) != cudaSuccess || nd12 < 1) all_gfx12 = false; for (int d = 0; all_gfx12 && d < nd12 && d < 64; ++d) { cudaDeviceProp od{}; if (cudaGetDeviceProperties(&od, d) != cudaSuccess || !strata::kernels::gfx_arch_is_gfx12(od.gcnArchName)) all_gfx12 = false; } (void) cudaGetLastError(); #if defined(_WIN32) strata::core::apply_gdn_chunked_default(false, all_gfx12); #else strata::core::apply_gdn_chunked_default(true, all_gfx12); #endif } strata::core::apply_arch_defaults(ad.gcnArchName, all_igpu, o.batch, kMmqBuilt); #if defined(_WIN32) const bool win_host = true; #else const bool win_host = false; #endif // UMA mode (021-minipc): the Radeon 780M's firmware (gc 11.0.1 MES) resets the GPU when the kernel evicts the queues of a // process that has a dispatch in a barrier loop, and a registered host arena is what gets it evicted (notes-021-minipc.md). // So its expert arena stays unregistered. STRATA_UMA_REGISTER=1 (or STRATA_ARENA_PIN_GIB=0) registers it as before. if (strata::core::igpu_uma_arena_default(ad.gcnArchName, all_igpu, win_host)) strata::core::arena_uma_no_register_flag().store(true); // and on Linux the arena asks for no transparent huge pages there (arch_defaults.hpp, igpu_arena_no_thp_default) if (strata::core::igpu_arena_no_thp_default(ad.gcnArchName, all_igpu, win_host)) strata::core::arena_no_thp_flag().store(true); // and before READY it waits until its own KFD eviction counter has been quiet for 2 s (kfd_settle.hpp) if (strata::core::igpu_kfd_settle_default(ad.gcnArchName, all_igpu, win_host)) strata::core::kfd_settle_flag().store(true); #if defined(STRATA_USE_HIP) && defined(__linux__) // and the KFD is not provoked while our queues are busy (kfd_quiet.hpp): the same device class, HIP under Linux only if (strata::core::igpu_kfd_settle_default(ad.gcnArchName, all_igpu, win_host)) { strata::core::kfd_quiet::class_flag().store(true); // NOREG: the expert arena takes the unregistered path above (UMA mode) by default on the Radeon 780M class only (every // GPU node gfx1103, kfd_quiet.hpp nodes_in_noreg_class), without mlock: with the arena registered, the first request reset // the 780M on its first start (p2006, 11-15, three fixes in); unregistered, 12 of 12 starts ran clean. gfx1150 and gfx1151 // keep the registered arena. STRATA_ARENA_PIN_GIB set by the user (or STRATA_UMA_REGISTER=1) wins; STRATA_KFD_QUIET_NOREG=0 // registers. const bool noreg_cls = strata::core::kfd_quiet::nodes_in_noreg_class(strata::core::kfd_quiet::read_topology("/sys/class/kfd/kfd/topology/nodes")); if (strata::core::kfd_quiet::noreg_default(noreg_cls, std::getenv("STRATA_KFD_QUIET"), std::getenv("STRATA_KFD_QUIET_NOREG"), std::getenv("STRATA_UMA_REGISTER"))) { strata::core::arena_uma_no_register_flag().store(true); strata::core::kfd_quiet::noreg_flag().store(true); if (std::getenv("STRATA_TRACE") != nullptr) std::fprintf(stderr, "strata trace: kfd quiet: expert arena not registered with the driver, no mlock (%s)\n", strata::core::arena_no_register() ? "in effect" : "STRATA_ARENA_PIN_GIB set: registered as it says"); } if (std::getenv("STRATA_TRACE") != nullptr && strata::core::kfd_quiet::on(strata::core::kfd_quiet::Fix::Load)) std::fprintf(stderr, "strata trace: kfd quiet: load order active (check first, settle after the expert cache, first prompt's buffers at init)\n"); if (strata::core::kfd_quiet::on(strata::core::kfd_quiet::Fix::Exit)) { int cur = 0; if (cudaGetDevice(&cur) != cudaSuccess) { cur = 0; (void) cudaGetLastError(); } kfdq_exit::install(cur); if (std::getenv("STRATA_TRACE") != nullptr) std::fprintf(stderr, "strata trace: kfd quiet: stop on SIGTERM / SIGINT / SIGHUP drains the GPU first (at most 3 s)\n"); } } #endif // and the file cache of the model files is given back while the expert arena is read and after it (page_cache_drop.hpp): // the little free memory left beside the arena, the GPU's buffers and that cache is what makes the kernel's proactive compaction run if (strata::core::igpu_cache_drop_default(ad.gcnArchName, all_igpu, win_host)) strata::core::arena_cache_drop_flag().store(true); // gfx1151 on Windows (#1630 capped a bare `--prefill auto` at 6144 for a 7900 XTX's commit charge): the Strix Halo has its // 8192 chunk back. IQ3_S, 8K prompt: 691 -> 787 tok/s (one chunk streams 1,785 experts instead of 2,782), 64K 713 -> 748; // 4K is one chunk already. STRATA_GFX1151_CHUNK=0 (or STRATA_GFX1151_DEFAULTS=0) keeps 6144. if (win_host && all_igpu && std::strncmp(ad.gcnArchName, "gfx1151", 7) == 0) { // #1630 was a discrete RX 7900 XTX: no warning about a named chunk here const char* c1w = std::getenv("STRATA_GFX1151_CHUNK"); const char* d1w = std::getenv("STRATA_GFX1151_DEFAULTS"); if (!(c1w != nullptr && c1w[0] == '0') && !(d1w != nullptr && d1w[0] == '0')) o.prefill_cap_warn_skip = true; } if (win_host && all_igpu && o.prefill_auto_bare && o.prefill_auto_cap > 0 && std::strncmp(ad.gcnArchName, "gfx1151", 7) == 0) { const char* c1 = std::getenv("STRATA_GFX1151_CHUNK"); const char* d1 = std::getenv("STRATA_GFX1151_DEFAULTS"); if (!(c1 != nullptr && c1[0] == '0') && !(d1 != nullptr && d1[0] == '0')) { o.prefill_auto_cap = 0; // 0.2.8: 16,384 rather than 8,192. The prompt reads every expert once per chunk, so a bigger chunk // reads them fewer times: measured on strix (engine 0.1.52, own prompt buffers, IQ3_S) 32K 1,260.0 -> // 1,307.9 tok/s and 64K 1,191.0 -> 1,238.2 (+3.8% / +4.0%); at 4K and 8K the chunk is the prompt, so // nothing changes there. The buffers' reserve grows to ~10.9 GiB and the cache keeps all 24,576 slots // (the box reports 84.7 GiB free at a 64K context). STRATA_GFX1151_CHUNK=0 keeps 6,144. o.prefill_chunk = std::max(o.prefill_chunk, 16384); } } // 0.2.8: the Strix Halo prompt path keeps its own buffers instead of lending cache slots. A lent slot's expert // is re-read from the host arena during every chunk, and on this box that copy runs at ~0.5 GB/s (the arena is // unregistered in UMA mode): measured on strix, engine 0.1.52, IQ3_S, 2026-10-27 - 823 slots = 2.75 s of a // 3.3 s 4K prompt, 1,408 slots = 5.5 s of a 6.1 s 8K prompt. Without lending every expert stays in the cache // (24,576 slots) and the prompt reads VRAM only; the buffers' VRAM is reserved up front instead (the cache // still fits: 46.84 GiB of experts against a 63.6 GB carve-out). STRATA_PREFILL_BORROW=1 keeps 0.2.7's // lending, STRATA_GFX1151_DEFAULTS=0 turns the whole gfx1151 block off. if (win_host && all_igpu && std::strncmp(ad.gcnArchName, "gfx1151", 7) == 0) { const char* pb = std::getenv("STRATA_PREFILL_BORROW"); const char* pd = std::getenv("STRATA_GFX1151_DEFAULTS"); if (!(pb != nullptr && pb[0] == '1') && !(pd != nullptr && pd[0] == '0')) { o.no_prefill_borrow = true; o.prefill_own_keep_chunk = true; } } } else (void) cudaGetLastError(); } #endif #if !defined(STRATA_USE_HIP) && !defined(STRATA_HIP_GFX906) && !defined(STRATA_GPU_METAL) && !defined(_WIN32) // Linux CUDA, 2 or more batch slots: the exact parallel-request stack is the engine's own default (QUAL-PAR bit-exact; it was the launcher's // PARALLEL_STACK_ENV). Each switch keeps =0 as its off switch and a value the user set is kept. Before any engine code reads them. strata::core::apply_parallel_defaults_cuda(true, o.batch); strata::core::apply_gdn_defaults_cuda(true); // STRATA_GDN_TC=1, STRATA_GDN_CONVL2=2 (owner yes 2026-11-07; was the launcher's GDN_STACK_CUDA) #endif if (!o.prefill_cap_warn.empty() && !o.prefill_cap_warn_skip) std::fprintf(stderr, "strata: WARNING --prefill %s: prompt chunks of 8192 tokens or more crashed the engine " "on Windows HIP (RX 7900 XTX: the commit charge jumped ~70 GB, exit code 0xC0000409, " "#1630); 7500 and below were stable. Kept as asked; a bare --prefill auto stops at %lld\n", o.prefill_cap_warn.c_str(), (long long) strata::platform::host_limits::kWinHipAutoChunkCap); #if !defined(STRATA_USE_HIP) && !defined(STRATA_GPU_METAL) // the start-up line about K-quant experts: the default is set here (before any engine code reads its switches), the line is printed once the expert layout is // loaded and only when the loaded set has K-quant experts (strata::core::nv_kq_line_wanted), so a model without them says nothing untrue bool kq_line_pending = false, kq_line_fused = false; { // CUDA sm_86 / sm_60: the switches that are exact AND faster there are on by default (strata/core/nv_defaults.hpp), when every // visible card has that one compute capability; before any engine code reads its switches, the user's own settings are kept int nd = 0; if (cudaGetDeviceCount(&nd) == cudaSuccess && nd > 0) { int m0 = 0, n0 = 0; bool same = cudaDeviceGetAttribute(&m0, cudaDevAttrComputeCapabilityMajor, 0) == cudaSuccess && cudaDeviceGetAttribute(&n0, cudaDevAttrComputeCapabilityMinor, 0) == cudaSuccess; for (int d = 1; same && d < nd; ++d) { int m = 0, n = 0; same = cudaDeviceGetAttribute(&m, cudaDevAttrComputeCapabilityMajor, d) == cudaSuccess && cudaDeviceGetAttribute(&n, cudaDevAttrComputeCapabilityMinor, d) == cudaSuccess && m == m0 && n == n0; } if (same) { strata::core::apply_nv_defaults(m0, n0); strata::core::apply_spec_adapt_default(m0, n0); } { // round 0212: the K-quant MMQ prompt kernels, on by default for compute capability 8.0+ (STRATA_MMQ_KQ=0 or STRATA_NV_KQ_DEFAULT=0 turns them off); the lowest compute capability decides int lo_m = m0, lo_n = n0; for (int d = 1; d < nd; ++d) { int m = 0, n = 0; if (cudaDeviceGetAttribute(&m, cudaDevAttrComputeCapabilityMajor, d) == cudaSuccess && cudaDeviceGetAttribute(&n, cudaDevAttrComputeCapabilityMinor, d) == cudaSuccess && (m < lo_m || (m == lo_m && n < lo_n))) { lo_m = m; lo_n = n; } } // does Strata's own fused kernel read the K-quant experts on a visible card (the line says so then; strata::core::nv_kq_fused_here) bool kq_fused_here = false; for (int d = 0; d < nd; ++d) { int m = 0, n = 0, sms = 0; if (cudaDeviceGetAttribute(&m, cudaDevAttrComputeCapabilityMajor, d) == cudaSuccess && cudaDeviceGetAttribute(&n, cudaDevAttrComputeCapabilityMinor, d) == cudaSuccess && cudaDeviceGetAttribute(&sms, cudaDevAttrMultiProcessorCount, d) == cudaSuccess && strata::core::nv_kq_fused_here(m, n, sms)) kq_fused_here = true; } kq_line_pending = !strata::core::apply_nv_kq_default(lo_m, lo_n, kq_fused_here, false).empty(); kq_line_fused = kq_fused_here; } } (void) cudaGetLastError(); } #endif #if !defined(STRATA_USE_HIP) && !defined(STRATA_GPU_METAL) if (o.prefill_auto_bare && o.prefill_auto_cap == 0) { // NVIDIA, compute capability 8.0 and up, and 7.0 (Volta, lane 10, one V100: 20K +134%, 32K +111%, see nv_chunk.hpp); Turing and Pascal keep 8192 // (round 0212, owner 11-03 "after the full test suite passes on it"): a bare `--prefill auto` may reach // 32768 instead of 8192, by the gfx12 rule below. The fit scan still picks a smaller chunk when the expert cache cannot lend the buffers, and // the RAM guard further down steps 32768 -> 16384 -> 8192 when the RAM available does not cover the extra loan. An explicit --prefill N, // auto:N or STRATA_PREFILL_AUTO_MAX is never touched (prefill_auto_bare is false then). STRATA_NV_CHUNK=0 or STRATA_DEFAULTS=026 keeps 8192, // STRATA_NV_CHUNK=16 keeps 16384. A layer split takes 8192 back (like gfx12; STRATA_SPLIT_CHUNK16K=1 keeps the raised ceiling). // A6000 UD-Q4_K_XL (13.1K of 24.6K experts in VRAM): 20K +43.4%, 32K +22.5%, 64K +21.3%, 8K 0.0%; cards that hold every expert: flat. const int64_t top = strata::core::nv_chunk_ceiling(std::getenv("STRATA_NV_CHUNK"), strata::qwen_defaults_026()); int nd = 0, lo_major = 99, lo_minor = 99; // the lowest compute capability of the visible cards if (top > 0 && cudaGetDeviceCount(&nd) == cudaSuccess && nd > 0) { for (int d = 0; d < nd; ++d) { int m = 0, n = 0; if (cudaDeviceGetAttribute(&m, cudaDevAttrComputeCapabilityMajor, d) != cudaSuccess || cudaDeviceGetAttribute(&n, cudaDevAttrComputeCapabilityMinor, d) != cudaSuccess) { lo_major = 0; break; } const int mj = (int) strata::cc_major_of(m), mn = (int) strata::cc_minor_of(n); if (mj < lo_major || (mj == lo_major && mn < lo_minor)) { lo_major = mj; lo_minor = mn; } } if (strata::core::nv_chunk_card_ok(lo_major, lo_minor)) { o.prefill_auto_max = top; o.prefill_chunk = top; o.prefill_gfx12_16k = true; o.prefill_raise_who = "NVIDIA"; std::fprintf(stderr, "strata generate: NVIDIA: --prefill auto may take chunks up to %lld (STRATA_NV_CHUNK=0 keeps 8192, =16 keeps 16384)\n", (long long) top); } } (void) cudaGetLastError(); } #endif #if defined(STRATA_USE_HIP) && !defined(_WIN32) if (o.prefill_auto_bare && o.prefill_auto_cap == 0) { // gfx1200 / gfx1201 (RDNA4, Linux): a bare `--prefill auto` may reach 16384 instead of 8192 (R9700, IQ3_S / Q2_0, 16K / 32K / // 64K prompts: +0.5 .. +5.8%, residuals identical to 8192). The fit scan still picks a smaller chunk when the expert cache cannot lend // the buffers. An explicit --prefill N, auto:N or STRATA_PREFILL_AUTO_MAX is never touched (prefill_auto_bare is false then). // STRATA_GFX12_DEFAULTS=0 or STRATA_GFX12_CHUNK=0 keeps 8192. // 0.2.10.1 (owner 11-03, "do all 5"): the ceiling is 32768, not 16384. A 16384 chunk leaves a 20K prompt as 16384 + a 3.6K tail, and every // chunk of 1,024 tokens or more streams all the experts the card does not hold. R9700 (p620, IQ3_S, 3 rounds interleaved): 20K +12.1%, 32K +1.3%, // 64K +2.6%, 8K +0.9%; UD-Q4_K_XL 20K +26%; first-token KL against 16384 at most 5e-5 (3 of 6 prompts bitwise). The loan is only taken for // what a prompt needs, and the RAM guard below steps 32768 -> 16384 -> 8192. STRATA_GFX12_CHUNK=16 keeps 16384. const char* c0 = std::getenv("STRATA_GFX12_CHUNK"); const char* d0 = std::getenv("STRATA_GFX12_DEFAULTS"); cudaDeviceProp cp{}; if (strata::core::gfx12_chunk_ceiling(c0) > 0 && !(d0 != nullptr && d0[0] == '0') && cudaGetDeviceProperties(&cp, 0) == cudaSuccess && strata::kernels::gfx_arch_is_gfx12(cp.gcnArchName)) { const int64_t top = strata::core::gfx12_chunk_ceiling(c0); o.prefill_auto_max = top; o.prefill_chunk = top; o.prefill_gfx12_16k = true; std::fprintf(stderr, "strata generate: gfx12: --prefill auto may take chunks up to %lld (STRATA_GFX12_CHUNK=16 keeps 16384, =0 keeps 8192)\n", (long long) top); } (void) cudaGetLastError(); } #endif #if defined(STRATA_HIP_GFX906) { // #1728: the gfx906 build's kernels assume 64-lane waves; on a wave32 card they would fault or give wrong // numbers, so say so before the first launch (the ready-made wave32 engine is the one for those cards) int n_dev = 0; if (cudaGetDeviceCount(&n_dev) == cudaSuccess) { for (int d = 0; d < n_dev; ++d) { cudaDeviceProp wp{}; if (cudaGetDeviceProperties(&wp, d) == cudaSuccess && wp.warpSize != 64) { std::fprintf(stderr, "strata generate: this engine was built for gfx906 (wave64, STRATA_HIP_GFX906), but GPU %d " "(%s) has %d-lane waves: use the ready-made engine for that card, or hide it " "(HIP_VISIBLE_DEVICES)\n", d, wp.name, wp.warpSize); return 2; } } } else (void) cudaGetLastError(); } #endif strata::core::set_coupled_draft(o.coupled_draft); #if defined(__linux__) && !defined(STRATA_GPU_METAL) { // THE CARD'S NUMA NODE (strata/kernels/cpu/card_node.hpp): on a machine with two or more memory nodes the process // restricts itself to the CPUs of the card's node, here, before the pool, the host thread and the stagers exist // and before the first large allocation, so every thread and the pinned memory they touch first follow. One node, // STRATA_NUMA_CARD=0, or any case decide_card_node leaves as it is: nothing changes. namespace kc = strata::kernels::cpu; kc::CardNodeInput ci; ci.switch_off = kc::card_node_switch_off(std::getenv("STRATA_NUMA_CARD")); const std::map> node_cpus = ci.switch_off ? std::map>{} : kc::card_node_node_cpus("/sys"); ci.nodes_with_cpus = ci.switch_off ? 1 : (std::max)(1, (int) node_cpus.size()); std::string cards_text; if (!ci.switch_off && ci.nodes_with_cpus >= 2) { ci.mask = kc::card_node_describe("/sys", kc::card_node_thread_cpus(), node_cpus); std::string status; if (kc::card_node_read_file("/proc/self/status", status)) ci.mems_known = kc::card_node_mems_allowed(status, ci.mems_allowed); // the cards the run uses: the primary one; with a layer split, helper caches or a peer card, every visible one const char* pv = std::getenv("STRATA_PRIMARY_DEVICE"); const int primary = pv != nullptr && std::atoi(pv) > 0 ? std::atoi(pv) : 0; bool several = !o.layer_split.empty() || o.peer_device >= 1; for (int r = 0; r < 3; ++r) several = several || o.expert_cache_remote[(size_t) r] > 0 || o.expert_cache_remote_auto[(size_t) r]; int n_dev = 0; if (cudaGetDeviceCount(&n_dev) != cudaSuccess) n_dev = 0; (void) cudaGetLastError(); for (int d = several ? 0 : primary; d < n_dev && (several || d == primary); ++d) { cudaDeviceProp p{}; int node = -1; std::string bdf = "?"; if (cudaGetDeviceProperties(&p, d) == cudaSuccess) { bdf = kc::card_node_bdf((unsigned) p.pciDomainID, (unsigned) p.pciBusID, (unsigned) p.pciDeviceID); node = kc::card_node_pci_node("/sys", bdf); } else { (void) cudaGetLastError(); } ci.card_nodes.push_back(node); cards_text += (cards_text.empty() ? "" : ", ") + std::string("CUDA") + std::to_string(d) + " " + bdf + " node " + std::to_string(node); } if (ci.card_nodes.empty() && primary >= n_dev) ci.card_nodes.push_back(-1); // the primary is not visible: unknown if (!ci.card_nodes.empty()) ci.card_node_free_bytes = kc::card_node_free_bytes("/sys", ci.card_nodes.front()); ci.pinned_need_bytes = kc::card_node_pinned_need(o.max_context); // the person placed the threads: their placement stays std::string pc = o.pool_cores, ac = o.aux_cpus; if (pc.empty()) if (const char* e = std::getenv("STRATA_POOL_CORES")) pc = e; if (ac.empty()) if (const char* e = std::getenv("STRATA_AUX_CPUS")) ac = e; const char* split_env = std::getenv("STRATA_NUMA_SPLIT"); if (!pc.empty()) ci.user_placed = "--pool-cores is set"; else if (split_env != nullptr && *split_env != '\0') ci.user_placed = "STRATA_NUMA_SPLIT is set"; else if (!ac.empty() && ac != "auto" && ac != "off") ci.user_placed = "an --aux-cpus list is set"; // the pool's worker count without the rule, as ExpertPool picks it (the span plan when the per-node split may run) const kc::CpuTopology topo = kc::detect_cpu_topology(true, o.pool_affinity); ci.hybrid = topo.is_hybrid; ci.cpu_quota = topo.cpu_quota; ci.user_workers = o.pool_workers > 0 ? o.pool_workers : 0; kc::PoolPlanInput pin = kc::pool_plan_input(topo); pin.span_packages = kc::pick_numa_pool(std::getenv("STRATA_NUMA_POOL"), split_env, ci.nodes_with_cpus).choice == kc::NumaPoolChoice::Auto; ci.today_workers = ci.user_workers > 0 ? ci.user_workers : (std::min)(kc::plan_pool_workers(pin).workers, (std::max)(1, (int) topo.worker_cores.size())); } const kc::CardNodeDecision cd = kc::decide_card_node(ci); int moved = 0, refused = 0; if (cd.on) moved = kc::restrict_process_cpus(cd.cpus, refused); // the threads that widen their mask later (background copies, checkpoint helpers) widen to the process's CPU set // as it is now: the card's node, or the set the process was started with (a taskset is kept); the switch off: // every CPU, as before if (!ci.switch_off) strata::platform::set_home_cpus(kc::card_node_thread_cpus()); if (std::getenv("STRATA_TRACE") != nullptr) { std::string cpus; for (size_t i = 0; i < cd.cpus.size(); ++i) cpus += (i ? "," : "") + std::to_string(cd.cpus[i]); std::fprintf(stderr, "strata trace: card node: %d nodes with CPUs; cards: %s; card node free %lld MiB, pinned need %llu MiB; " "pool workers now %d, on the card's node %d (%d cores); %s%s (%d threads changed, %d refused)\n", ci.nodes_with_cpus, cards_text.empty() ? "not read" : cards_text.c_str(), (long long) (ci.card_node_free_bytes < 0 ? -1 : ci.card_node_free_bytes >> 20), (unsigned long long) (ci.pinned_need_bytes >> 20), ci.today_workers, cd.node_workers, cd.node_cores, cd.on ? "restricted to CPUs " : "left as is: ", cd.on ? cpus.c_str() : cd.why.c_str(), moved, refused); } } #endif { // --host-core / STRATA_HOST_CORE, before the pool and the session pin any thread std::string hc = o.host_core; if (hc.empty()) if (const char* e = std::getenv("STRATA_HOST_CORE")) hc = e; if (hc == "last") strata::kernels::cpu::set_host_core(strata::kernels::cpu::HostCore::Last); if (hc == "sibling") strata::kernels::cpu::set_host_core(strata::kernels::cpu::HostCore::Sibling); } { // --pool-cores / STRATA_POOL_CORES (experimental, off by default), before the pool is built. A list that cannot be read is // said and left out: the pool keeps its default placement (recommend, never force). std::string pc = o.pool_cores; if (pc.empty()) if (const char* e = std::getenv("STRATA_POOL_CORES")) pc = e; if (!pc.empty()) { std::vector cpus; std::string perr; if (strata::kernels::cpu::parse_pool_cores(pc, cpus, perr)) strata::kernels::cpu::set_pool_cores(cpus); else std::fprintf(stderr, "strata generate: --pool-cores: %s; the pool uses its default placement\n", perr.c_str()); } } { // --aux-cpus / STRATA_AUX_CPUS: read the CPUs this process may use now, before any thread is pinned; the plan // follows once the pool exists (it needs the workers' CPUs) std::string ac = o.aux_cpus; if (ac.empty()) if (const char* e = std::getenv("STRATA_AUX_CPUS")) ac = e; std::string aerr; if (!strata::aux_cpus::configure(ac, aerr)) { std::fprintf(stderr, "strata generate: STRATA_AUX_CPUS: %s\n", aerr.c_str()); return 2; } } strata::core::set_peer_portable(o.peer_device >= 1); // multi-GPU: the Portable flag on mapped host buffers only with a peer device (before any allocation) // Tesla P100: the prompt peer computes on MMQ only, so with --peer-device the GP100 FP16-path default stands aside (gp100_prompt_default.hpp) strata::prefill::peer_device_requested().store(o.peer_device >= 1); { // the RAM guard (parking, session save/restore): --memory-limit-mib, else STRATA_MEMORY_LIMIT_MIB, else none int64_t mib = o.memory_limit_mib; if (mib < 0) { const char* env = std::getenv("STRATA_MEMORY_LIMIT_MIB"); if (env != nullptr && env[0] != '\0') { const size_t len = std::strlen(env); const auto parsed = std::from_chars(env, env + len, mib); if (parsed.ec != std::errc{} || parsed.ptr != env + len || mib < 0 || mib > INT64_MAX / (1024 * 1024)) { std::fprintf(stderr, "STRATA_MEMORY_LIMIT_MIB needs a nonnegative integer within range (got \"%s\")\n", env); return 2; } } else mib = 0; } strata::core::set_memory_limit_bytes((uint64_t) mib << 20); if (o.serve || mib > 0) { constexpr double GiB = 1073741824.0; const auto mem = strata::core::sample_host_memory(); if (!mem) { std::fprintf(stderr, "strata generate: memory guard: the available RAM cannot be read; parking and session " "save/restore are refused\n"); } else { std::fprintf(stderr, "strata generate: memory guard: limit %.1f GiB (source: %s), current %.1f GiB, " "reclaimable cache credited %.1f GiB; available %.1f GiB (MemAvailable %.1f GiB%s), " "floor %lld MiB\n", (double) mem->limit / GiB, strata::core::memory_source_name(mem->source), (double) mem->current / GiB, (double) mem->credit / GiB, (double) mem->available / GiB, (double) mem->mem_available / GiB, mib > 0 ? (", --memory-limit-mib " + std::to_string((long long) mib)).c_str() : "", (long long) o.conversation_cache_min_free_mib); } } } if (o.serve && o.conversation_cache_mib > 0 && (o.prompt_cache == 0 || o.conversation_cache_slots == 0)) std::fprintf(stderr, "strata serve: warning: conversation caching is disabled by %s\n", o.prompt_cache == 0 ? "--prompt-cache 0" : "--conversation-cache-slots 0"); // STRATA_PRIMARY_DEVICE: which VISIBLE device the engine's own session runs on. The Windows HIP runtime // enumerates the cards in a fixed order no HIP_VISIBLE_DEVICES list can change (it only filters), so with a // slower card first a run could only put the model on it (RX 6600 before RX 6800). 0 (unset) is upstream's // behavior; the helper caches and the peer tier follow it, a layer split still assumes device 0 (see below). const int primary_device = [] { const char* v = std::getenv("STRATA_PRIMARY_DEVICE"); const int n = v != nullptr ? std::atoi(v) : 0; return n > 0 ? n : 0; }(); strata::core::set_primary_device(primary_device); // parking with --layer-split saves every stage (SavedConversation::stage_images) // Layer split (multi-GPU): the later stages run layers [K_i, K_i+1) on their own GPUs (--split-device, default // the next visible ones); "auto" places the K from each GPU's free VRAM once the weights are in (below). KV // streaming and images (the server's GPU encoder) run across a split, also with parking and --batch. Across // GPUs, not yet: control vectors, the helper caches (--expert-cache-remote), and lending cache slots to the // prompt path (each stage's prompt path has its own buffers). // --pcie-frac given: that one share is every stage's (the stages' own link probes are skipped), so a split over // a fast and a slow link cannot set the two apart from the command line (#485) const bool pcie_given = o.pcie_frac >= 0.0; std::vector split_at; std::vector split_devs; bool split_auto = false, split_same = false; if (!o.layer_split.empty()) { int n_dev = 1; if (cudaGetDeviceCount(&n_dev) != cudaSuccess || n_dev < 1) n_dev = 1; cudaGetLastError(); auto ints = [](const std::string& str, auto& out) -> bool { using V = typename std::decay_t::value_type; size_t a = 0; while (a < str.size()) { size_t b = str.find(',', a); if (b == std::string::npos) b = str.size(); const std::string t = str.substr(a, b - a); if (t.empty() || t.find_first_not_of("0123456789") != std::string::npos) return false; out.push_back((V) std::atoll(t.c_str())); a = b + 1; } return !out.empty(); }; split_auto = o.layer_split == "auto"; bool ok = o.serve && (split_auto || ints(o.layer_split, split_at)); if (ok && !o.split_device.empty()) ok = ints(o.split_device, split_devs); else if (ok) for (int d = 1; d < n_dev && (split_auto || split_devs.size() < split_at.size()); ++d) split_devs.push_back(d); if (ok && !split_auto && split_devs.empty() && split_at.size() == 1) split_devs.push_back(0); // one GPU split_same = ok && split_devs.size() == 1 && split_devs[0] == 0 && !split_auto; if (split_same && o.conversation_cache_mib > 0 && o.conversation_cache_slots > 0 && o.prompt_cache > 0) { std::fprintf(stderr, "strata serve: conversation parking does not support a layer split on one GPU " "(--split-device 0); disable parking with --conversation-cache-mib 0\n"); return 2; } // THE LAYER SPLIT'S SPILL WALK, STEP 6: FEWER CARDS. Under `auto`, a later card with too little free memory to hold even a trimmed share (a card another program fills) is left out // of the split, said plainly; with none left the start is the single card's, with its own walk and the rest of the experts in RAM. Only the cards the engine would have picked. if (ok && split_auto && !split_devs.empty() && std::getenv("STRATA_SPILL_OFF") == nullptr && spill_discrete_gpu()) { std::vector kept; for (const int d : split_devs) { size_t fb_c = 0, tb_c = 0; bool usable = true; { const strata::core::OnDevice on_c(d); usable = cudaMemGetInfo(&fb_c, &tb_c) != cudaSuccess || strata::program::split_walk::card_usable((int64_t) (fb_c >> 20)); (void) cudaGetLastError(); } if (usable) { kept.push_back(d); continue; } std::fprintf(stderr, "strata generate: short of GPU memory: CUDA%d has only %.2f GiB free, too little to hold a share of the model beside its context, a working cache " "and the prompt buffers (%.1f GiB at least): the layer split runs without it\n", d, (double) fb_c / 1073741824.0, (double) strata::program::split_walk::kMinCardMib / 1024.0); } if (kept.empty()) std::fprintf(stderr, "strata generate: short of GPU memory: no other card has room, so the model runs on CUDA0 alone with the experts that do not fit in RAM\n"); split_devs = kept; } if (ok && split_auto && split_devs.empty()) { std::fprintf(stderr, "strata generate: --layer-split auto: one GPU visible, so no split\n"); o.layer_split.clear(); split_auto = false; } else if (ok) { ok = (split_auto || split_at.size() == split_devs.size()) && split_devs.size() < (size_t) SplitDrive::kMax; for (size_t i = 0; ok && i < split_at.size(); ++i) ok = split_at[i] >= 2 && (i == 0 || split_at[i] > split_at[i - 1]); for (size_t i = 0; ok && !split_same && i < split_devs.size(); ++i) { ok = split_devs[i] > 0 && split_devs[i] < n_dev; for (size_t j = 0; ok && j < i; ++j) ok = split_devs[i] != split_devs[j]; } } if (!ok) { std::fprintf(stderr, "strata generate: --layer-split K[,K2..]|auto needs --serve, rising K from 2, and one " "distinct GPU per K in --split-device (1..%d; or 0 with one K: the same GPU). K is the " "FIRST LAYER of each later GPU, not a count of layers per card: \"24,36,42\" for 4 " "GPUs, not \"24,12,6,6\" (got \"%s\")\n", n_dev - 1, o.layer_split.c_str()); return 2; } } bool multi_gpu = !split_devs.empty() && !split_same; // cleared by --split-skip-if-fits before any stage loads // STRATA_PRIMARY_DEVICE: a later stage's list (`--split-device` values must be > 0) still assumes the // primary is device 0 - refuse the combination rather than mis-place a stage. The peer tier takes the // primary into account (peer_experts.cpp). if (primary_device != 0 && !o.layer_split.empty()) { std::fprintf(stderr, "strata generate: STRATA_PRIMARY_DEVICE %d is not supported with a layer split yet\n", primary_device); return 2; } bool split_own_auto = false; // #340: the split keeps own prompt buffers by its rule (not --no-prefill-borrow) if (o.mmap_experts && !o.shared_expert_arena.empty()) { std::fprintf(stderr, "strata generate: --shared-expert-arena backs the resident arena and cannot be used with --mmap-experts\n"); return 2; } if (o.resident_cpu_experts && (!o.mmap_experts || o.expert_profile.empty())) { std::fprintf(stderr, "strata generate: --resident-cpu-experts requires --mmap-experts and a static --expert-profile\n"); return 2; } const bool remote_caches = o.expert_cache_remote[0] > 0 || o.expert_cache_remote[1] > 0 || o.expert_cache_remote[2] > 0; // A layer split keeps the resident RAM mode: every stage's GPU cache is left out of the RAM copy, and an adaptive // swap copies an evicted expert back from the card that owns its layer (resident_stage_swaps). // The helper-GPU caches are allowed beside the resident RAM mode too: their experts are left out of the RAM copy // like a stage's (below), the helpers' refills read through the source (the RAM copy when it holds the bytes), // and the two adaptive tiers already keep each other's experts out (helper_holds in the primary's candidates, // RemoteExpertOpt::adapt's resident table). Measured on RX 6800 + RX 6600, Windows (docs/SECOND_GPU.md). // the helper-GPU expert caches (--expert-cache-remote, docs/SECOND_GPU.md): CUDA1..3 on one GPU; with a layer // split, the visible GPUs no stage runs on, in order int remote_dev[3] = {1, 2, 3}; if (primary_device != 0) { // STRATA_PRIMARY_DEVICE: the helpers are the visible devices except the primary, in order int n_vis = 1; if (cudaGetDeviceCount(&n_vis) != cudaSuccess || n_vis < 1) n_vis = 1; cudaGetLastError(); int k = 0; for (int d = 0; d < n_vis && k < 3; ++d) if (d != primary_device) remote_dev[k++] = d; for (; k < 3; ++k) remote_dev[k] = -1; } if (multi_gpu) { if (o.expert_profile.empty()) { std::fprintf(stderr, "strata generate: a layer split across GPUs needs --expert-profile\n"); return 2; } // A STAGE'S PROMPT PATH BORROWS FROM THAT STAGE'S OWN EXPERT CACHE. This used to set // `no_prefill_borrow = true` - "each stage's prompt path has its own buffers" - which is true, but it is // a reason to give each stage its own LOAN, not a reason to make every stage withhold a chunk-sized // reserve from its cache for the whole session. Forced on, it also collapsed `--prefill auto` to 2048 // (below) and skipped the lend arm, so a stage paid for its prompt buffers twice over: once in VRAM it // never got back, once in the smaller chunk. At `--prefill 5524` that reserve is 3.8 GiB per stage, // more than either 8 GB card had - which is how adding two GPUs to the two 12 GB ones lost 260K. // The loan is the tail of the stage's own cache (see `PfPart` in the serve block); outside the prompt // that tail is expert cache, so a large chunk costs a stage nothing permanent. // #340 - BUT A LOAN IS NOT FREE PER REQUEST: every stage streams the lent experts during the prompt and // copies them back after it, so on cards that hold (nearly) every expert of their layers a 2K prompt read // 37% slower than 0.1.29's own buffers (2x RX 9070 XT / R9700: 1570 -> 990 tok/s; 2x A5000 in #340: -35%). // So a split keeps 0.1.29's own buffers (2048-token chunks, priced into the split search) when they are a // small part of every card - at most 12% of its VRAM (16 GB and larger cards) - and borrows on smaller cards, // where the reserve would cost the cache (and the context) the paragraph above is about. Measured with own // buffers on the 9070 XT + R9700: 2K 1588 tok/s, 16K 2006 (0.1.29 1568 / 1935, 0.1.31 993 / 1852). // OPT-IN (the owner's choice for 0.1.32): own buffers change which experts a full card keeps resident, so the // split's output differs from 0.1.31's; the default borrows as 0.1.31 did - with the concurrent refill and the // 96-blob split ring that alone gave 2K +27%, 16K +5% over 0.1.31, decode unchanged, output identical. // STRATA_SPLIT_OWN=auto: the 12% rule above; 1: own buffers on any cards; unset/0: borrow. // --split-skip-if-fits keeps the loans (it can fall back to one GPU, which must stay as it is). const char* own_env = std::getenv("STRATA_SPLIT_OWN"); if (!o.no_prefill_borrow && !o.split_skip_if_fits && own_env != nullptr && own_env[0] != '0') { const char* v = std::string(own_env) == "auto" ? nullptr : own_env; bool own = v ? v[0] == '1' : true; // the buffers of a 2048-token chunk (or the --prefill one) + a 96-blob ring (as split_pf_mib prices them) const int64_t own_chunk = o.prefill_auto || o.prefill_chunk <= 0 ? 2048 : o.prefill_chunk; const int64_t reserve_mib = 160 + (own_chunk * 680) / 1024 + 96 * 4; std::string why; if (!v) { std::vector devs = {0}; for (const int d : split_devs) devs.push_back(d); for (const int d : devs) { cudaDeviceProp prop{}; if (cudaGetDeviceProperties(&prop, d) != cudaSuccess) { cudaGetLastError(); own = false; break; } const int64_t total_mib = (int64_t) (prop.totalGlobalMem >> 20); if (reserve_mib * 100 > 12 * total_mib) { own = false; why = "CUDA" + std::to_string(d) + " has " + std::to_string(total_mib) + " MiB"; break; } } } if (own) { o.no_prefill_borrow = true; split_own_auto = true; std::fprintf(stderr, "strata generate: layer split: every stage keeps its own prompt buffers (~%lld MiB " "each, %lld-token chunks)%s\n", (long long) reserve_mib, (long long) own_chunk, v ? " (STRATA_SPLIT_OWN=1)" : ""); } else if (!why.empty()) { std::fprintf(stderr, "strata generate: layer split: the prompt paths borrow from the caches (%s)\n", why.c_str()); } } int n_vis = 1; if (cudaGetDeviceCount(&n_vis) != cudaSuccess || n_vis < 1) n_vis = 1; cudaGetLastError(); int next_free = 1; for (int r = 0; r < 3; ++r) { if (o.expert_cache_remote[(size_t) r] <= 0) continue; while (next_free < n_vis && std::find(split_devs.begin(), split_devs.end(), next_free) != split_devs.end()) ++next_free; if (next_free >= n_vis) { std::fprintf(stderr, "strata generate: --expert-cache-remote with a layer split needs a GPU that runs no " "stage (%d visible, %zu used by the split)\n", n_vis, split_devs.size() + 1); return 2; } remote_dev[r] = next_free++; } std::string devs; for (const int d : split_devs) devs += (devs.empty() ? "" : ",") + std::to_string(d); std::fprintf(stderr, "strata generate: layer split across %zu GPUs: CUDA0, then CUDA%s (split %s)\n", split_devs.size() + 1, devs.c_str(), o.layer_split.c_str()); } #if defined(STRATA_USE_HIP) { // every GPU this run uses must be an architecture the binary has code for (a gfx1100 build on a gfx1201 // card would otherwise fail later with "invalid device function") std::vector used{primary_device}; // STRATA_PRIMARY_DEVICE: the primary is not always 0 if (multi_gpu) used.insert(used.end(), split_devs.begin(), split_devs.end()); for (int r = 0; r < 3; ++r) if (o.expert_cache_remote[(size_t) r] > 0) used.push_back(remote_dev[r]); for (const int d : used) { if (const std::string why = strata::core::gpu_arch_problem(d); !why.empty()) { std::fprintf(stderr, "strata generate: %s\n", why.c_str()); return 1; } } } #endif if (o.prefill_auto && (o.no_prefill_borrow || o.expert_profile.empty())) { o.prefill_auto = false; // nothing to lend from: the buffers are reserved for the session, so keep them small // 0.2.8 Strix Halo: the gfx1151 rule above chose a chunk that fits this box; the "keep them small" 2048 would throw // the whole 8K prompt back into 4 chunks (measured: 2048 against 8192 costs ~26% of an 8K prompt on this box). o.prefill_chunk = o.prefill_own_keep_chunk ? o.prefill_chunk : 2048; } if (!have_tokens && o.serve) { // plan v0.3 P8: requests bring their own tokens o.tokens = {248045}; o.max_new = 1; have_tokens = true; o.stop_eos = true; } if (!have_tokens) { std::fprintf(stderr, "strata generate: --tokens is required (this build has no tokenizer; see the " "header of src/program/generate.cpp)\n"); usage(); return 2; } if ((o.ple_io != "direct" && o.ple_io != "mmap" && o.ple_io != "ram") || o.ple_row_cache < 0 || o.ple_inflight < 1 || o.ple_inflight > 1024 || !(o.ple_delay_us >= 0)) { std::fprintf(stderr, "strata generate: invalid --ple-io/--ple-row-cache/--ple-inflight/--ple-delay-us\n"); return 2; } if (o.kv == "q4") o.kv = "q4_0"; if (o.kv != "fp16" && o.kv != "int8" && o.kv != "q4_0" && o.kv != "k8v4") { std::fprintf(stderr, "strata generate: --kv must be fp16, int8, q4_0 or k8v4\n"); return 2; } strata::core::qsa_set_kv_int8(o.kv == "int8"); strata::core::qsa_set_kv_q4(o.kv == "q4_0"); // PR #21: 4-bit codes after a Hadamard rotation (kv_q4.hpp) // STRATA_KV_ROT=1: INT8 K/V through the Hadamard rotation --kv q4_0 already uses. Opt-in: first-token KL to // fp16 K/V improved on an NVFP4 pack (0.0066 -> 0.0051) but not on IQ2_XS (0.0022 -> 0.0054) const char* kv_rot = std::getenv("STRATA_KV_ROT"); strata::core::qsa_set_kv_int8_rotate(kv_rot != nullptr && kv_rot[0] == '1'); if (kv_rot != nullptr && kv_rot[0] == '1' && o.kv == "int8") std::fprintf(stderr, "strata generate: STRATA_KV_ROT=1: INT8 K/V through the Hadamard rotation (opt-in)\n"); strata::core::qsa_set_kv_hybrid(o.kv == "k8v4"); // K8V4: INT8 K + rotated Q4_0 V, 816 B/cell if (o.kv_resident < 0) { std::fprintf(stderr, "strata generate: --kv-resident must be >= 0\n"); return 2; } strata::core::qsa_set_kv_resident(o.kv_resident); // Prompt lookup (the suffix drafter, on by default): the MTP keeps its --spec windows and a lookup window may be // up to 2 tokens longer; the draft policy (strata/spec/draft_policy.hpp) takes one only where it pays. Code // edits +6-11%, ordinary text unchanged (bench/results/2026-09-27-spec). --suffix-draft 0 turns it off. if (o.suffix_draft > 0 && o.spec >= 2 && o.mtp_max_t == 0) { o.mtp_max_t = o.spec; o.spec = std::min(o.spec + 2, 8); // kVerifyMaxT } // --lookup-max-t N: lookup windows up to N tokens, the MTP's stay at --spec. Not given: 12 where the pr-nv2 runs measured it (serve, one GPU, the 8-row // build: rewrites and agent edit turns +11..14%, prose and code within noise); --lookup-max-t 0 or STRATA_LOOKUP_MAX_T=0 turns it off. The wide // builds (HIP, 16 rows), a layer split, --batch, DFlash2 and --lookup-chain keep the old windows. if (o.lookup_max_t < 0) { const char* lme = std::getenv("STRATA_LOOKUP_MAX_T"); const bool env_off = lme != nullptr && lme[0] == '0'; const bool narrow = strata::kernels::kVerifyMaxT == strata::kernels::kVerifyNarrowT; strata::core::LookupDefaultIn ld; ld.env_off = env_off, ld.narrow_window = narrow, ld.serve = o.serve, ld.multi_gpu = multi_gpu; ld.layer_split = !o.layer_split.empty(), ld.batch = o.batch > 1, ld.dflash2 = o.draft == "dflash2"; ld.lookup_chain = o.lookup_chain > 0, ld.suffix_draft = o.suffix_draft > 0, ld.spec_at_least_2 = o.spec >= 2; #if defined(STRATA_GPU_METAL) ld.metal_build = true; // (Metal's windows hold 8 rows and it has no 12-row window: "metal window: window size out of range") #endif o.lookup_max_t = strata::core::default_lookup_max_t(ld); } if (o.lookup_max_t > 0 && o.suffix_draft > 0 && o.spec >= 2) { if (o.mtp_max_t == 0) o.mtp_max_t = o.spec; o.spec = std::max(o.spec, std::min(o.lookup_max_t, strata::kernels::kVerifyLongT)); } // --lookup-chain (opt-in): the MTP keeps its windows; a lookup chained after its drafts may lengthen one by up to K. // Sized from the cap actually in force: the suffix block above may already have raised --spec to --spec+2, so sizing // from mtp_max_t left K=1 and K=2 with a window identical to not passing the flag at all. if (o.lookup_chain > 0 && o.spec >= 2) { if (o.mtp_max_t == 0) o.mtp_max_t = o.spec; const int chain_base = o.spec; o.spec = std::max(chain_base, std::min(std::max(chain_base, o.mtp_max_t) + o.lookup_chain, 8)); // kVerifyNarrowT } // A speculative (solo) window holds at most kVerifyNarrowT rows: the hand-offs, the penalty history and the drafters' // buffers are sized for that. Only a plain --batch forms the wider windows of a build with kVerifyMaxT > 8. // (--lookup-max-t: a prompt-lookup window may be longer, up to kVerifyLongT; the MTP drafts stay at mtp_max_t) const int spec_cap = o.lookup_max_t > 0 && o.suffix_draft > 0 ? (int) strata::kernels::kVerifyLongT : (int) strata::kernels::kVerifyNarrowT; if (o.spec > spec_cap) { std::fprintf(stderr, "strata generate: --spec %d: a speculative window holds 2..%d tokens\n", o.spec, spec_cap); return 1; } // dflash2-kern: right after the start the resident experts are the profile's, not this text's; a speculative round carries // 2-5 tokens, so the adaptive tier (one swap round per adapt_every VERIFY rounds) learned the text 2-5 times slower per // token. For the first STRATA_SPEC_ADAPT_WARM rounds it swaps every STRATA_SPEC_ADAPT_EVERY rounds (set per card by // nv_defaults, where measured); later the normal interval. An explicit --adapt-every is kept as it is. if (!o.adapt_every_given && o.spec >= 2 && o.adapt_every > 0) { const char* e = std::getenv("STRATA_SPEC_ADAPT_EVERY"); const char* w = std::getenv("STRATA_SPEC_ADAPT_WARM"); const int n = e ? std::atoi(e) : 0; const long long wr = w ? std::atoll(w) : 0; if (n > 0 && n < o.adapt_every && wr > 0) { o.adapt_warm_every = n; o.adapt_warm_rounds = wr; } } strata::core::layer_set_shared_early(!o.shared_late); if (!o.native_preset.empty()) { try { // every shard of the model (-0000N-of-0000M.gguf beside --native). A missing shard is an error // here: it used to be skipped, leaving a model with some tensors absent and a later error, or none. o.native_shards = strata::gguf_split_paths(o.native_preset); // a model family Strata recognises but has no engine path for yet (Qwen3.6-35B-A3B) is refused here, // with a message that says so, before anything else about the file is judged { const strata::GgufFile meta(o.native_shards.front()); const std::string why = strata::model_family_not_supported(strata::model_family(meta)); if (strata::model_family(meta) != strata::ModelFamily::Unknown && !why.empty()) { std::fprintf(stderr, "strata generate: --native %s: %s\n", o.native_preset.c_str(), why.c_str()); return 2; } } // --ple-gguf defaults to the shard that holds the PLE table, found by name: shard 2 of the ISTA files // and of Unsloth's UD-Q4_K_XL, shard 1 of Swift's if (o.ple_gguf.empty() && !o.no_ple) { const strata::GgufModel model(o.native_shards); size_t at = 0; if (model.find("per_layer_token_embd.weight", &at) != nullptr) o.ple_gguf = o.native_shards[at]; } } catch (const std::exception& e) { std::fprintf(stderr, "strata generate: --native %s: %s\n", o.native_preset.c_str(), e.what()); return 2; } if (o.no_ple || o.ple_gguf.empty()) { std::fprintf(stderr, "strata generate: --native requires --ple-gguf (the PLE key is native too), and no " "shard of the model holds per_layer_token_embd.weight\n"); return 2; } o.stream_token = true; o.gr_native_mmvf = true; o.native_bf16 = o.native_bf16_extra = true; o.native_ple_key = o.native_moe_combine = o.native_gdn = o.native_router = true; o.native_qsa = o.native_qsa_indexer = o.native_rope = o.native_ple_postops = true; if (o.native_head_gguf.empty()) o.native_head_gguf = o.native_preset; if (o.native_dense_gguf.empty()) { // every shard of the model (-0000N-of-0000M.gguf beside --native), then the PLE shard: a split // may put any layer in any shard (Swift's GGUFs: layers 13-47 in shard 2, the PLE table in shard 1) o.native_dense_gguf = o.native_shards; // a PLE-only table (tools/ple_fp8_pack.py: architecture strata-ple) holds no projections bool ple_only = false; try { strata::GgufFile pg(o.ple_gguf); if (const strata::MetaValue* v = pg.get("general.architecture")) ple_only = v->s == "strata-ple"; } catch (const std::exception&) {} if (!ple_only && std::find(o.native_dense_gguf.begin(), o.native_dense_gguf.end(), o.ple_gguf) == o.native_dense_gguf.end()) o.native_dense_gguf.push_back(o.ple_gguf); } #if !defined(STRATA_USE_HIP) && !defined(STRATA_HIP_GFX906) && !defined(STRATA_GPU_METAL) // CUDA, a file that carries the hyper-connection projections as Q8_0 (Unsloth's UD-* files): the Q8_0 read is on by default (owner yes // 2026-11-07; was setup's unsloth_default_env, "closer to the file and faster"). The GSQ-RCO packs keep them BF16 and stay as they were. // STRATA_HC_Q8=0 turns it off; a value the user set is kept. Before the first read of the switch (the dense load below). strata::core::NativeDense::apply_hc_q8_default(o.native_dense_gguf); #endif // Plan v0.3 (24 Sep): the CPU experts stay on the VNNI kernel. The llama.cpp-CPU-exact q8_0 contract // cost 27.0 vs 17.2 ms/token of pool time and G-C does not need it; `--cpu-oracle-q8-0` still selects it. } if (o.logits_stride > 1 && (o.max_new != 1 || o.dump_logits.empty())) { std::fprintf(stderr, "strata generate: --logits-stride > 1 requires --max-new 1 and --dump-logits\n"); return 2; } if (o.no_ple && !o.ple_gguf.empty()) { std::fprintf(stderr, "strata generate: --no-ple and --ple-gguf are mutually exclusive\n"); return 2; } if (o.native_ple_postops && o.no_ple) { std::fprintf(stderr, "strata generate: --native-ple-postops requires PLE enabled\n"); return 2; } if (!o.no_ple && o.ple_gguf.empty()) { std::fprintf(stderr, "strata generate: --ple-gguf is required; --no-ple explicitly enables a diagnostic ablation\n"); return 2; } // P7 audit: positions, cells and pooled-block indices are cast to int32 on the device path. if (o.max_context > 2147483647LL - 8) { std::fprintf(stderr, "strata generate: --max-context must be below 2^31\n"); return 2; } if (o.max_new <= 0 || o.max_context <= 0 || o.max_new > o.max_context || o.tokens.size() > (size_t) (o.max_context - o.max_new)) { std::fprintf(stderr, "strata generate: positive --max-new and --max-context must fit the prompt and generation\n"); return 2; } // THE ROPE KNOBS (rope_scaling.hpp). Anything invalid dies here, at second zero, rather than becoming a // NaN angle inside one of the twelve QSA layers. Only the RANGES are checked - the config itself is // resolved after the model file has had its say, right before session_init. strata::kernels::RopeScaling rope_cfg; // type filled here; the rest at the resolution below { using RST = strata::kernels::RopeScalingType; // an absent --rope-scaling (the empty default) leaves the type to the model file's rope keys, // resolved below; anything present must be one of the three names if (o.rope_scaling == "none") rope_cfg.type = RST::None; else if (o.rope_scaling == "linear") rope_cfg.type = RST::Linear; else if (o.rope_scaling == "yarn") rope_cfg.type = RST::YaRN; else if (!o.rope_scaling.empty()) { std::fprintf(stderr, "strata generate: --rope-scaling must be none, linear or yarn (got '%s')\n", o.rope_scaling.c_str()); return 2; } // every knob FINITE first: `atof("nan")` is NaN, and a NaN passes every range comparison below for (const double v : {o.rope_scale, o.rope_freq_base, o.rope_freq_scale, o.yarn_orig_ctx, o.yarn_ext_factor, o.yarn_attn_factor, o.yarn_beta_fast, o.yarn_beta_slow}) if (!std::isfinite(v)) { std::fprintf(stderr, "strata generate: a rope scaling knob is not a finite number (%g)\n", v); return 2; } // 0 is the absent default; an explicit factor must extend, not shrink if (o.rope_scale != 0 && o.rope_scale < 1.0) { std::fprintf(stderr, "strata generate: --rope-scale %g must be >= 1 (it extends the context, not shrinks it)\n", o.rope_scale); return 2; } if (o.rope_freq_base != 0 && o.rope_freq_base <= 1.0) { std::fprintf(stderr, "strata generate: --rope-freq-base must be a base above 1 (0 = the model's)\n"); return 2; } if (o.rope_freq_scale < 0 || o.yarn_orig_ctx < 0 || o.yarn_ext_factor < -1.0 || o.yarn_attn_factor <= 0 || o.yarn_beta_fast <= 0 || o.yarn_beta_slow <= 0) { std::fprintf(stderr, "strata generate: invalid rope scaling knob (see usage: --yarn-ext-factor <0 = auto, " "--yarn-orig-ctx 0 = default, the rest positive)\n"); return 2; } } if (!std::isfinite(o.temperature) || o.temperature < 0 || !std::isfinite(o.top_p) || o.top_p <= 0 || o.top_p > 1 || o.top_k < 0 || o.expert_cache < -1 || o.pool_workers < 0 || std::any_of(o.expert_cache_remote.begin(), o.expert_cache_remote.end(), [](int slots) { return slots < 0; }) || (o.expert_cache_remote[1] > 0 && o.expert_cache_remote[0] == 0) || (o.expert_cache_remote[2] > 0 && o.expert_cache_remote[1] == 0)) { std::fprintf(stderr, "strata generate: invalid sampling or resource parameter\n"); return 2; } if (o.expert_cache_remote_placement != "stripe" && o.expert_cache_remote_placement != "layer") { std::fprintf(stderr, "strata generate: --expert-cache-remote-placement must be stripe or layer\n"); return 2; } if (o.remote_expert_opt && !o.serve) { std::fprintf(stderr, "strata generate: --remote-expert-opt requires --serve\n"); return 2; } // the peer tier is the second card's only user: a layer split or a remote expert cache would put a second engine // part (and a second copy of the same experts) on it if (o.peer_device >= 1 && (!o.layer_split.empty() || o.expert_cache_remote[0] > 0)) { std::fprintf(stderr, "strata generate: --peer-device cannot be combined with %s\n", !o.layer_split.empty() ? "--layer-split (use one or the other)" : "--expert-cache-device1..3 (the peer tier already caches experts there)"); return 2; } if (o.native_flash_attn_short && o.max_context > 256) { std::fprintf(stderr, "strata generate: --native-flash-attn-short requires --max-context <=256\n"); return 2; } if (o.native_flash_attn_short && (o.gpu_only_full || o.graph_only || o.gpu_stages)) { std::fprintf(stderr, "strata generate: --native-flash-attn-short requires the normal decode loop for status validation\n"); return 2; } // The whole-model graph measurements replay every layer through CUDA0's session, which a layer split carves to // CUDA0's own range - the answer would read another stage's state. Refused here rather than at the call, so // the reason is visible before 55 GB is loaded. if (multi_gpu && (o.gpu_only_full || o.gpu_stages)) { std::fprintf(stderr, "strata generate: --gpu-only-full and --gpu-stages replay the whole model through one " "session, which a layer split does not have; run them without --layer-split\n"); return 2; } if (!o.native_head_gguf.empty()) { try { o.native_head_shards = o.native_head_gguf == o.native_preset ? o.native_shards : strata::gguf_split_paths(o.native_head_gguf); } catch (const std::exception& e) { std::fprintf(stderr, "strata generate: --native-head-gguf %s: %s\n", o.native_head_gguf.c_str(), e.what()); return 2; } } if (o.native_ple_key && (o.native_dense_gguf.empty() || o.no_ple)) { std::fprintf(stderr, "strata generate: --native-ple-key requires PLE and --native-dense-gguf\n"); return 2; } if (o.cpu_oracle_q8_0 && (o.expert_cache != 0 || !o.expert_profile.empty())) { std::fprintf(stderr, "strata generate: --cpu-oracle-q8-0 cannot be combined with --expert-cache or --expert-profile until the GPU expert contract matches\n"); return 2; } // **BEFORE ANYTHING ELSE.** The CPU expert kernel is AVX-512 (VNNI + VBMI) and its translation unit is // compiled `/arch:AVX512`, so on a CPU without those features it does not fail - it executes an illegal // instruction at some unpredictable token. Refusing at second zero is the whole point of P2.S3's check. strata::kernels::cpu::expert_set_oracle_q8_0(o.cpu_oracle_q8_0); #if defined(__x86_64__) || defined(_M_X64) || defined(__i386__) || defined(_M_IX86) || defined(STRATA_GPU_METAL) // ... and nothing runs on a CPU without AVX2: every CPU expert kernel is AVX2 at least (the AVX-512 ones are // chosen above it), and so is ggml-cpu in the release build, which the native pack's layout load initializes // next. Refused here, by name, rather than an illegal instruction in the first expert. // The experimental older-CPU build (STRATA_ISA_FLOOR=avx|none, compiled on that PC; #394 #595 #623) has ggml-cpu // for that floor, so a native pack's experts run there on ggml-cpu (every AVX2 kernel is behind cpu_avx2_ok). const char* isa_floor = strata::kernels::cpu::isa_floor_build(); #if defined(STRATA_GPU_METAL) // Apple Silicon: every expert is on the GPU; ggml-cpu (NEON) is the only CPU expert code strata::metal_engine::set_model_shard(o.native_preset.c_str()); // the decode window reads the model GGUF itself strata::metal_engine::set_batch_slots(o.batch); o.mmap_experts = true; // ... experts included: no resident copy of them (the GGUF shards in place) if (false) { #else if (!strata::kernels::cpu::cpu_avx2_ok() && isa_floor[0] == '\0') { #endif std::fprintf(stderr, "strata generate: this CPU (%s) does not support AVX2 with FMA and F16C, which this engine's " "CPU expert kernels need; Strata runs on Intel Haswell (2013), AMD Zen (2017) or newer. " "Older CPUs are EXPERIMENTAL and slow: setup compiles an engine for them on this PC " "(STRATA_ISA_FLOOR, see \"Older CPUs\" in docs/INSTALL.md)\n", strata::kernels::cpu::cpu_name().c_str()); return 2; } if (isa_floor[0] != '\0') { const bool avx_floor = std::strcmp(isa_floor, "avx") == 0; if (avx_floor ? !strata::kernels::cpu::cpu_avx1_ok() : !strata::kernels::cpu::cpu_sse42_ok()) { std::fprintf(stderr, "strata generate: this engine is the older-CPU build for %s, which this CPU (%s) does " "not have%s\n", avx_floor ? "AVX" : "SSE4.2 with POPCNT", strata::kernels::cpu::cpu_name().c_str(), avx_floor ? "; compile it with STRATA_ISA_FLOOR=none" : ""); return 2; } if (!strata::kernels::cpu::cpu_avx2_ok()) std::fprintf(stderr, "strata generate: EXPERIMENTAL older-CPU build (ggml-cpu for %s): this CPU has no AVX2, " "so the CPU's experts run on ggml-cpu's kernels - expect it to be slow\n", isa_floor); else std::fprintf(stderr, "strata generate: this is the older-CPU build (ggml-cpu for %s); this CPU has AVX2, " "and the normal build is faster on it\n", isa_floor); } #else if (o.cpu_oracle_q8_0) { std::fprintf(stderr, "strata generate: --cpu-oracle-q8-0 is the x86 Q8_0 activation contract; this CPU uses the " "scalar quantizer\n"); return 2; } #endif std::string err; if (!o.native_head_gguf.empty() && !o.stream_token) { std::fprintf(stderr, "--native-head-gguf requires --stream-token\n"); return 2; } // Plan v0.3 P6: where the experts live. A native pack (tools/iq_pack.py: the IQ2_XS / IQ3_XXS files) keeps // every quantized tensor in its GGUF form, so it needs --native (the dense projections, head and embedding // come from the model file) and runs its experts in verify windows only (--spec). { const strata::core::ModelGeometry& g0 = strata::core::kCompiledGeometry; if (!strata::kernels::cpu::expert_layout_load(o.pack, g0.n_layers, g0.n_expert, err)) { std::fprintf(stderr, "strata generate: %s\n", err.c_str()); return 1; } // Every layer's formats must have GPU expert kernels and a prompt-path dequantizer, checked here, before // anything is allocated: an unsupported down type used to exit from inside the first verify window, and // an unsupported dequant type left the prompt path's fp16 buffer unwritten. const auto& lay = strata::kernels::cpu::expert_layout(); for (int64_t l = 0; lay.native && l < (int64_t) lay.fmt.size(); ++l) { const auto& f = lay.fmt[(size_t) l]; if (!strata::kernels::native_expert_supported(f.gu_type, f.d_type, f.n_embd, f.n_ff)) { std::fprintf(stderr, "strata generate: layer %lld's experts are %s/%s (ggml types %d/%d), which this " "engine has no GPU kernels for\n", (long long) l, strata::ggml_type_name((uint32_t) f.gu_type), strata::ggml_type_name((uint32_t) f.d_type), f.gu_type, f.d_type); return 1; } #if defined(STRATA_PREFILL_MMQ) // MODEL-UPDATE Phase 1: the K-quants' prompt kernels (STRATA_MMQ_KQ=1) are a library of their own on CUDA // (strata_kq): asking for the formats opens it now, before the expert cache takes the free VRAM (void) strata::prefill::mmq::supported(f.gu_type); (void) strata::prefill::mmq::supported(f.d_type); #endif } #if !defined(STRATA_USE_HIP) && !defined(STRATA_GPU_METAL) if (kq_line_pending && lay.native) { std::vector> kq_types; kq_types.reserve(lay.fmt.size()); for (const auto& f : lay.fmt) kq_types.emplace_back(f.gu_type, f.d_type); if (strata::core::nv_kq_line_wanted(kq_types)) std::fprintf(stderr, "%s\n", strata::core::nv_kq_default_line(kq_line_fused, kMmqBuilt).c_str()); } #endif // APR (prism.hadamard) packs: every expert path rotates its activations (CPU pool: native_quant_act / _h; // GPU verify, remote GPUs, prompt FP16 path: hadamard_rows). Validated end to end on CUDA (sm_86, sm_89 with // a two-GPU layer split and peer decode, sm_120) and on HIP gfx1151 and gfx1201 (R9700: Gyro-S speed gate and // forced-token KL against the FP16 path, 11-13). Other HIP architectures run the same // kernels but have not been run end to end with such a pack: said here, not refused (the P2P prompt peer // says the same in Prefill::set_peer). The former opt-in STRATA_APR is no longer read. if (strata::kernels::cpu::hadamard_spec().any()) { std::fprintf(stderr, "strata generate: APR pack: Hadamard-folded experts (block %d)\n", strata::kernels::cpu::hadamard_spec().block); #if defined(STRATA_USE_HIP) || defined(STRATA_HIP_GFX906) int dev = 0; cudaDeviceProp p{}; if (cudaGetDevice(&dev) == cudaSuccess && cudaGetDeviceProperties(&p, dev) == cudaSuccess) { std::string arch(p.gcnArchName); if (const size_t colon = arch.find(':'); colon != std::string::npos) arch.resize(colon); if (arch != "gfx1151" && arch != "gfx1201") std::fprintf(stderr, "strata generate: warning: Hadamard-folded experts are validated end to end " "on gfx1151 and gfx1201 among AMD GPUs, not yet on %s\n", arch.c_str()); } else { (void) cudaGetLastError(); } #endif } } const bool native_pack = strata::kernels::cpu::expert_layout().native; // STRATA_MMQ_DIRECT: the room each sized expert slot keeps after its blob (0 unless it is on: the slot costs and // the arena are then today's, byte for byte) const int64_t slot_guard = native_pack ? (int64_t) strata::prefill::Prefill::slot_guard_bytes() : 0; // STRATA_PRIMARY_DEVICE: switch the engine's own thread to the chosen card BEFORE any GPU // context or allocation exists below (the helper preflights, the PCIe probe, the weights and the // arena all follow it). Every other device switch in the engine saves and restores the current // device, so this single call is where the primary is picked. if (primary_device != 0) { int n_vis = 0; if (cudaGetDeviceCount(&n_vis) != cudaSuccess || primary_device >= n_vis) { cudaGetLastError(); std::fprintf(stderr, "strata generate: STRATA_PRIMARY_DEVICE=%d: no such visible device (%d visible)\n", primary_device, n_vis); return 2; } if (cudaSetDevice(primary_device) != cudaSuccess) { std::fprintf(stderr, "strata generate: STRATA_PRIMARY_DEVICE=%d: cudaSetDevice failed: %s\n", primary_device, cudaGetErrorString(cudaGetLastError())); return 1; } std::fprintf(stderr, "strata generate: primary device from STRATA_PRIMARY_DEVICE: CUDA%d\n", primary_device); } // ---- STRATA_EXPERT_NIBBLE=1 keeps the gate/up experts of IQ2_S / IQ3_XXS / IQ3_S layers as 4-bit codes in their VRAM // slots (strata/core/expert_nibble.hpp). Unset or 0: nothing here runs, no table is set, and every slot size below is // the GGUF blob's, as before. On: if anything would read a converted slot as GGUF blocks or write GGUF bytes into // one, the switch is ignored for this start with a warning (before anything is allocated); else the per-layer table // is set before the first slot estimate and the adaptive tier is off (it swaps GGUF blobs in and out of slots). // The residency, the loans and the prompt chunk are checked where they are known (those refuse the start). const bool nib_asked = nib::config().on || nib::config().error.rfind("STRATA_EXPERT_NIBBLE=", 0) == 0; const int64_t nib_chunk_asked = o.prefill_chunk; // an explicit --prefill N must stay N (the chunking is in the bits) if (nib_asked) { std::string why = nibble_refusal(o); if (why.empty()) { nib::set_layers(nib::plan_layers(strata::kernels::cpu::expert_layout(), why)); if (why.empty() && !nib::any_on()) why = "no layer of this pack is IQ2_S / IQ3_XXS / IQ3_S at 2560 x 640 among STRATA_EXPERT_NIBBLE_FMTS " "and outside STRATA_EXPERT_NIBBLE_SKIP"; if (why.empty()) (void) strata::prefill::Prefill::nibble_prompt_check(why); } if (!why.empty()) { // a warning, not a refusal: this start goes on as it would without the switch (the usual GGUF slots) std::fprintf(stderr, "strata generate: WARNING: STRATA_EXPERT_NIBBLE is off for this start: %s; the expert slots " "stay GGUF blocks\n", why.c_str()); nib::set_layers({}); } else { o.adapt_swaps = 0; o.peer_adapt_swaps = 0; const auto& lay = strata::kernels::cpu::expert_layout(); int64_t n_on = 0, by_fmt[3] = {0, 0, 0}; uint64_t more = 0; for (int64_t l = 0; l < lay.n_layers; ++l) { const nib::LayerVram& v = nib::layer(l); if (!v.on) continue; ++n_on; ++by_fmt[v.gu_type == nib::kIQ2_S ? 0 : v.gu_type == nib::kIQ3_XXS ? 1 : 2]; more += (v.slot_bytes - (v.raw_bytes + 255) / 256 * 256) * (uint64_t) lay.n_expert; } std::fprintf(stderr, "strata generate: STRATA_EXPERT_NIBBLE: %lld of %lld layers keep their gate/up experts as 4-bit " "codes in VRAM (IQ2_S %lld, IQ3_XXS %lld, IQ3_S %lld), %.2f GiB more VRAM than their GGUF " "blobs for all %lld experts of each; the adaptive tier is off (--adapt-swaps 0)%s\n", (long long) n_on, (long long) lay.n_layers, (long long) by_fmt[0], (long long) by_fmt[1], (long long) by_fmt[2], (double) more / 1073741824.0, (long long) lay.n_expert, nib::config().recheck ? "; STRATA_EXPERT_NIBBLE_RECHECK: every slot's hash after each request" : ""); } } // STRATA_EARLY_REMOTE_CONTEXTS=1: create EVERY secondary context here, like CUDA1's. Under WSL2 the driver's // pinned/mapped host budget (dxg gpadl, ~1 GiB) is spent by CUDA0's weights and MTP before the later loop runs, // and a new context then fails with cudaErrorMemoryAllocation (CUDA2: "cudaSetDevice(2) failed: out of memory"). const char* early_env = std::getenv("STRATA_EARLY_REMOTE_CONTEXTS"); const bool early_remote = early_env && early_env[0] == '1'; for (int r = 0; r < 3; ++r) if (o.expert_cache_remote[(size_t) r] > 0 && (r == 0 || early_remote)) { // Keep CUDA1's proven startup order: initialise its context before // allocating GPU0 weights or mapping the large host expert arena. double free_gib = 0; if (!strata::core::RemoteExperts::preflight(remote_dev[r], free_gib, err)) { std::fprintf(stderr, "strata generate: %s\n", err.c_str()); return 1; } std::fprintf(stderr, "strata generate: CUDA%d context ready, %.2f GiB free before expert arena registration\n", remote_dev[r], free_gib); } // plan v0.3 P6: the PCIe share of the missed experts, measured per kind of pack (the paper, finding on PCIe). // PR #44: a x8 link carries half of what the native default assumes - the GPU's SMs read that share over the // link (the copy kernel, since 0.1.14), so on a slower link it must shrink or the window waits for it. The // real H2D bandwidth is probed once; from 20 GB/s up (x16 PCIe 4/5) the measured default stays. The canonical // pack keeps 0.2 as its start value (0.1.43: PcieAuto refines it on CUDA). `--calibrate` measures it outright. // NVFP4 packs: 0.25. Their 2.76 MB experts cross the link twice as long as the i-quants' the 0.55 was // measured on, and that copy sits on the GPU's critical path while the CPU pool runs beside it: decode // 103 -> 117 tok/s short, 105 -> 124 at 32K (RTX 5090, PCIe 5 x16, 9950X3D; 0.10 and 0.40 both slower). if (o.pcie_frac < 0.0) { const auto& lay0 = strata::kernels::cpu::expert_layout(); const bool nvfp4_pack = native_pack && !lay0.fmt.empty() && lay0.fmt[0].gu_type == 40; const char* pfd = std::getenv("STRATA_PCIE_FRAC_DEFAULT"); const bool pf_old = pfd != nullptr && std::strcmp(pfd, "old") == 0; // 0.2.7: gfx12 native packs start at 0.15 (see pcie_share_gfx12_default above); other cards and // STRATA_PCIE_FRAC_DEFAULT=old keep the x16 share measured for them. const double base = strata::pcie_start_frac(nvfp4_pack, native_pack, pcie_share_gfx12_default(), pf_old, strata::qwen_defaults_026()); std::string bursts; #if !defined(STRATA_USE_HIP) && defined(_WIN32) // Windows: opt-in (STRATA_PCIE_AUTO_CANON=1); an RTX 5070 decoded a short Q2_0 answer 3% slower with it, code 2.5% faster const char* pac = std::getenv("STRATA_PCIE_AUTO_CANON"); const bool pf_old_canon = pf_old || !(pac != nullptr && pac[0] == '1'); #elif !defined(STRATA_USE_HIP) const bool pf_old_canon = pf_old; #else const bool pf_old_canon = true; // the canonical pack's PcieAuto is CUDA only #endif // the canonical pack keeps its 0.2 as the START value, but is probed too (CUDA, unless // STRATA_PCIE_FRAC_DEFAULT=old) so that PcieAuto can refine the share from the CPU pool's speed const double bw = (native_pack || !pf_old_canon) ? probe_pcie_h2d_gbps(&bursts) : -1.0; if (!native_pack && !(bw > 0.0)) { o.pcie_frac = base; } else if (!native_pack) { o.pcie_frac = base; std::fprintf(stderr, "strata generate: PCIe probe: %.1f GB/s host->device (best of %s); the canonical pack " "starts at pcie_frac %.2f and refines it from the CPU pool's speed\n", bw, bursts.c_str(), base); #if !defined(STRATA_USE_HIP) o.pcie_frac_auto = o.layer_split.empty(); o.pcie_probe_gbps = bw; #endif } else if (bw > 0.0) { o.pcie_frac = pcie_frac_for_gbps(bw, base); std::fprintf(stderr, "strata generate: PCIe probe: %.1f GB/s host->device (best of %s) -> pcie_frac %.2f " "(default %.2f)\n", bw, bursts.c_str(), o.pcie_frac, base); // 0.1.43: split opt-in + gfx12 default-on (decode_defaults_arch_ok). Other HIP parts: STRATA_PCIE_FRAC_DEFAULT=auto // turns the refinement on (pcie_auto_fork_arch_ok); the pool timings and miss counts it reads are engine-generic. // STRATA_PCIE_FRAC_DEFAULT=old keeps the start-up rule everywhere. o.pcie_frac_auto = (o.layer_split.empty() || pcie_auto_split_ok()) && !pf_old && (decode_defaults_arch_ok() || pcie_auto_fork_arch_ok()); o.pcie_probe_gbps = bw; } else { o.pcie_frac = base; std::fprintf(stderr, "strata generate: PCIe probe failed -> pcie_frac default %.2f\n", base); } } // STRATA_PCIE_BALANCE=1 (opt-in): each verify layer's PCIe count from measured costs (Verifier::set_pcie_balance) // instead of the probe's fixed share above - the CPU's speed sets the right share as much as the link's. IQ2_XS, // one AVX2 pool worker (emulated on an RTX 5090 + 9950X3D): 16.8-17.2 -> 12.8-13.0 ms a round; the 9950X3D's own // 16 workers: 12.2 either way. One GPU, no batch slots, no --pcie-frac. auto pcie_balance = [&]() { const char* e = std::getenv("STRATA_PCIE_BALANCE"); return !pcie_given && native_pack && !multi_gpu && o.batch <= 0 && e != nullptr && std::strcmp(e, "1") == 0; }; // the canonical Q2_0 pack's CPU kernels are AVX-512 only; a native pack runs on AVX2 CPUs as well if (!native_pack) { // #2347: an NVFP4 / i-quant / Unsloth pack IS a native pack and runs on an AVX2 CPU (its rows have AVX2 // kernels). This refusal is the canonical Q2_0 pack's, reached when the --pack folder has no // native_experts.txt - a hand-written config pointing --pack at the wrong folder reads as "this CPU is too // old". Say so before the refusal, and where the file is when it sits one level down (a pack/ subfolder). if (!strata::kernels::cpu::cpu_features().usable()) { std::error_code ec; const std::filesystem::path pk(o.pack); std::fprintf(stderr, "strata generate: %s has no native_experts.txt, so it is read as the canonical Q2_0 " "pack, whose CPU kernel needs AVX-512.\n" " An NVFP4, i-quant or Unsloth pack has that file in the folder given as --pack " "and runs on an AVX2 CPU as well;\n", o.pack.c_str()); if (std::filesystem::exists(pk / "pack" / "native_experts.txt", ec)) std::fprintf(stderr, " it is in %s: use that folder as --pack.\n", (pk / "pack").generic_string().c_str()); else std::fprintf(stderr, " if this is one of those packs, the folder is incomplete or the wrong one " "(setup writes it; run setup again).\n"); } strata::kernels::cpu::cpu_require_expert_support(); } else if (!strata::kernels::cpu::cpu_vnni_ok()) #if defined(__aarch64__) // arm64: every x86 test above is false, so say which expert pool this build links std::fprintf(stderr, "strata generate: CPU expert kernels: %s\n", #if defined(STRATA_OWN_CPU_QUANT) "the Strata quant layer (NEON)"); #else "ggml-cpu (NEON)"); #endif #else std::fprintf(stderr, "strata generate: CPU expert kernels: %s\n", !strata::kernels::cpu::cpu_avx2_ok() ? (strata::kernels::cpu::cpu_avx1_ok() && std::getenv("STRATA_NO_IQ128") == nullptr ? "AVX1 (older-CPU build)" : "ggml-cpu (older-CPU build)") : std::getenv("STRATA_NO_IQ256") == nullptr ? "AVX-2" : "ggml-cpu (STRATA_NO_IQ256 set)"); #endif // the compiled shape; a native model's file replaces it below with its own metadata (read_geometry), which a // pruned variant (GSQ-RCO Coder, fewer than 512 experts) differs from strata::core::ModelGeometry g = strata::core::kCompiledGeometry; strata::kernels::PleConsts ple_consts_run = strata::kernels::ple_artifact_consts(); // the model file's PLE hash constants when it has them int64_t K = g.n_expert_used; // THE ROPE CONFIG RESOLVES HERE, BEFORE ANY WEIGHT MOVES - the CLI and the model file have both spoken, // and `session_init` below builds the rope table from it and captures the kernels reading its constants // (rope_scaling.hpp); the only hard constraint is "set before that", and dying on a bad rope key beats // scanning gigabytes of shards first. Precedence: an EXPLICIT flag over the model file's rope keys over // the struct defaults. The empty --rope-scaling and the 0 --rope-scale mean the flag is absent, so the // model file decides; an explicit value - `none` and `1` included, the opt-outs - wins over the model file. { // The model file's rope keys (llama.cpp's names under the arch prefix), when it carries any - the // artifact today ships none, so this is a no-op defaults channel for future fine-tunes. std::string gguf_rope_type; double gguf_rope_base = 0, gguf_rope_factor = 0, gguf_rope_orig_ctx = 0; if (!o.native_preset.empty()) { // The geometry is the model file's (core::geometry_from_gguf: every ".*" shape key), checked // against the shapes this engine's kernels are built for. The expert count and top-k are run-time // sizes: a pruned variant (GSQ-RCO Coder) ships fewer experts than the canonical 512x10. try { strata::GgufFile model_gguf(o.native_shards.front()); // the metadata shard std::string gerr; if (!strata::core::geometry_from_gguf(model_gguf, g, K, gerr)) { std::fprintf(stderr, "strata generate: %s\n", gerr.c_str()); return 1; } const std::string mismatch = strata::core::compiled_geometry_mismatch(g); if (!mismatch.empty()) { std::fprintf(stderr, "strata generate: %s: %s\n", o.native_preset.c_str(), mismatch.c_str()); return 1; } const std::string p = std::string(strata::model_family_arch(g.family)) + "."; if (const strata::MetaValue* v = model_gguf.get(p + "rope.freq_base")) gguf_rope_base = v->num(); if (const strata::MetaValue* v = model_gguf.get(p + "rope.scaling.type")) gguf_rope_type = v->s; if (const strata::MetaValue* v = model_gguf.get(p + "rope.scaling.factor")) gguf_rope_factor = v->num(); if (const strata::MetaValue* v = model_gguf.get(p + "rope.scaling.original_context_length")) gguf_rope_orig_ctx = v->num(); // The PLE hash constants (multipliers, head sizes, head offsets) when the file carries them; the artifact's // own values stay the default for a file that does not. { auto arr = [&](const char* k, std::vector& out) { const strata::MetaValue* v = model_gguf.get(p + k); if (v == nullptr || v->type != strata::MetaType::ARRAY) return false; for (const strata::MetaValue& e : v->items) out.push_back(e.u); return true; }; std::vector pm, pv, po; const bool a1 = arr("ple.layer_multipliers", pm), a2 = arr("ple.head_vocab_sizes", pv), a3 = arr("ple.head_offsets", po); if (a1 || a2 || a3) { std::string perr; if (!(a1 && a2 && a3) || !strata::kernels::ple_consts_from_arrays(pm, pv, po, 0, ple_consts_run, perr)) { std::fprintf(stderr, "strata generate: %s: the PLE hash constants in the model file are not usable: %s\n", o.native_preset.c_str(), (a1 && a2 && a3) ? perr.c_str() : "one of the three arrays is missing"); return 1; } } } } catch (const std::exception& e) { std::fprintf(stderr, "strata generate: reading the model's geometry from %s: %s\n", o.native_preset.c_str(), e.what()); return 1; } } using RST = strata::kernels::RopeScalingType; if (!o.rope_scaling.empty()) { // the early validation pinned the spelling; `none` here is the CLI opting OUT of the model file's keys if (o.rope_scaling == "linear") rope_cfg.type = RST::Linear; else if (o.rope_scaling == "yarn") rope_cfg.type = RST::YaRN; else rope_cfg.type = RST::None; } else if (!gguf_rope_type.empty()) { if (gguf_rope_type == "linear") rope_cfg.type = RST::Linear; else if (gguf_rope_type == "yarn") rope_cfg.type = RST::YaRN; else if (gguf_rope_type != "none") { std::fprintf(stderr, "strata generate: %s carries rope.scaling.type '%s' - none, linear or yarn only\n", o.native_preset.c_str(), gguf_rope_type.c_str()); return 2; } } if (o.rope_scale > 0) rope_cfg.factor = o.rope_scale; // an explicit factor, 1 included else if (gguf_rope_factor > 1.0) rope_cfg.factor = gguf_rope_factor; if (o.rope_freq_base > 0) rope_cfg.freq_base = o.rope_freq_base; else if (gguf_rope_base > 1.0) rope_cfg.freq_base = gguf_rope_base; if (o.yarn_orig_ctx > 0) rope_cfg.orig_ctx = o.yarn_orig_ctx; else if (gguf_rope_orig_ctx >= 1) rope_cfg.orig_ctx = gguf_rope_orig_ctx; rope_cfg.freq_scale_in = o.rope_freq_scale; rope_cfg.ext_factor = o.yarn_ext_factor >= 0 ? o.yarn_ext_factor : (rope_cfg.type == RST::YaRN ? 1.0 : 0.0); rope_cfg.attn_factor = o.yarn_attn_factor; rope_cfg.beta_fast = o.yarn_beta_fast; rope_cfg.beta_slow = o.yarn_beta_slow; if (rope_cfg.type == RST::None) { // none is the trained rotation, exactly: the scaling knobs are inert (the table builder and // `kernel_args` ignore them), and resetting them keeps the logged/queried config honest. Only the // frequency base survives - it is the rotation itself, not a scaling knob. const bool knobs = o.rope_scale > 1.0 || o.rope_freq_scale > 0 || o.yarn_ext_factor > 0 || o.yarn_attn_factor != 1.0; const double base = rope_cfg.freq_base; rope_cfg = strata::kernels::RopeScaling{}; rope_cfg.freq_base = base; if (knobs) std::fprintf(stderr, "strata generate: note: no rope scaling is active (none), so --rope-scale, " "--rope-freq-scale and the --yarn-* knobs have no effect\n"); } // THE RESOLVED CONFIG IS VALIDATED AS A WHOLE, with the one rule every rotation site also applies // (rope_scaling.hpp): the CLI ranges above cannot see a model-file value, nor a combination such as a // --rope-freq-scale that turns the resolved factor non-finite. if (const char* why = strata::kernels::rope_scaling_invalid(rope_cfg)) { std::fprintf(stderr, "strata generate: invalid rope scaling configuration: %s (type %s, factor %g, " "freq_scale %g, base %g, original context %g)\n", why, rope_cfg.type == RST::YaRN ? "yarn" : rope_cfg.type == RST::Linear ? "linear" : "none", rope_cfg.factor, rope_cfg.freq_scale(), rope_cfg.freq_base, rope_cfg.orig_ctx); return 2; } strata::kernels::rope_scaling_set(rope_cfg); if (rope_cfg.type != RST::None) { const char* tn = rope_cfg.type == RST::YaRN ? "yarn" : "linear"; std::fprintf(stderr, "strata generate: rope scaling %s, factor %.6g (freq_scale %.6g, base %.6g, mscale %.6f), " "--max-context %lld against a trained context of %.0f\n", tn, rope_cfg.factor, rope_cfg.freq_scale(), rope_cfg.freq_base, rope_cfg.mscale(), (long long) o.max_context, rope_cfg.orig_ctx); if ((double) o.max_context <= rope_cfg.orig_ctx) std::fprintf(stderr, "strata generate: note: the context is within the trained %.0f - no position needs the " "extension, and the resolved scaling still applies to every angle\n", rope_cfg.orig_ctx); // only when there IS a magnitude correction: YaRN's log term (ext_factor != 0) or an explicit // --yarn-attn-factor; plain linear (mscale 1) has none, and saying otherwise was TODO 22 if (rope_cfg.mscale() != 1.0) std::fprintf(stderr, "strata generate: note: the %s magnitude correction scales cos and sin by %.6f " "at every position\n", rope_cfg.type == RST::YaRN ? "YaRN" : "--yarn-attn-factor", rope_cfg.mscale()); } } strata::core::NativeEmbed native_embed; if (native_pack) { if (o.native_preset.empty() || o.spec < 2 || o.keep_canonical || (o.prefill_chunk <= 0 && o.tokens.size() > 1)) { std::fprintf(stderr, "strata generate: %s is a native (IQ) pack: it needs --native SHARD1, --spec T (T >= 2) " "and --prefill CHUNK\n", o.pack.c_str()); return 2; } const auto embed_t0 = std::chrono::steady_clock::now(); if (!native_embed.load(o.embd_gguf.empty() ? o.native_shards : std::vector{o.embd_gguf}, g.n_embd, g.n_vocab, err)) { std::fprintf(stderr, "strata generate: %s\n", err.c_str()); return 1; } strata::core::set_native_embed(&native_embed); std::fprintf(stderr, "strata generate: native pack: %s experts (largest blob %.2f MB), token embedding " "%s %s (%.0f MiB, %.1f s)\n", o.pack.c_str(), (double) strata::kernels::cpu::expert_layout().max_blob / 1e6, strata::ggml_type_name((uint32_t) native_embed.type()), native_embed.in_vram() ? "in VRAM" : "in mapped host memory", (double) native_embed.bytes() / 1048576.0, std::chrono::duration(std::chrono::steady_clock::now() - embed_t0).count()); } // Plan v0.3 P1: tensors served in native form are not also loaded in canonical form (~2.7 GB of VRAM back // to the expert cache with --native). `--keep-canonical` loads both, as before. std::set skip; if (!o.keep_canonical) { if (!o.native_dense_gguf.empty() && !strata::core::NativeDense::served_names(o.native_dense_gguf, o.native_ple_key, skip, err)) { std::fprintf(stderr, "strata generate: %s\n", err.c_str()); return 1; } if (!o.native_head_gguf.empty()) skip.insert("output.weight"); // the PLE module validates its canonical key at construction (8 MB); a native pack has none to load if (!native_pack) skip.erase("blk.1.ple_key.weight"); // #326: a --compat-bf16 pack (OrcaRouter IQ3_XXS) keeps its BF16 key in the arena if (native_pack && !strata::core::NativeDense::keep_unquantized_ple_key(o.pack, skip, err)) { std::fprintf(stderr, "strata generate: %s\n", err.c_str()); return 1; } if (native_pack) skip.insert("token_embd.weight"); // STRATA_HC_Q8=1 (single GPU): the layers' hyper-connection down / up projections live only as Q8_0 (NativeDense // quantizes them from the pack file), so their bf16 copy is not loaded if (!o.native_dense_gguf.empty() && !multi_gpu && strata::core::NativeDense::hc_q8_requested()) strata::core::NativeDense::add_hc_skip(o.pack, skip); } // Layer split: every GPU holds only the dense weights of ITS layers (the PLE tensors stay everywhere). // Without this each card keeps a full copy (~3.4 GB for the Coder) that its stage never reads - VRAM the // expert cache wants. Opt-in, STRATA_STAGE_TRIM=1, on HIP and CUDA alike: measured on 2x MI50 (PR #639), // and the default waits for its author's re-run of the release branch on his cards. const std::set skip_base = skip; // --trim-stage-weights (PR #559) is the same switch as STRATA_STAGE_TRIM=1 (PR #639) // The trim is on by default with a split (PR #4522). STRATA_STAGE_TRIM=0 and --no-trim-stage-weights turn it off (a given // --trim-stage-weights beats STRATA_STAGE_TRIM=0, as before); the spill walk below keeps its own rule, which is // that the user ASKED for the trim (flag or STRATA_STAGE_TRIM=1), not that the trim is on. const char* const stage_trim_env = std::getenv("STRATA_STAGE_TRIM"); const bool trim_env_on = stage_trim_env != nullptr && stage_trim_env[0] != 0 && std::string(stage_trim_env) != "0"; const bool trim_env_off = stage_trim_env != nullptr && std::string(stage_trim_env) == "0"; const bool trim_off = o.trim_stage_flag == 0 || (trim_env_off && o.trim_stage_flag != 1); const bool trim_user_asked = !trim_off && (o.trim_stage_flag == 1 || trim_env_on); o.trim_stage_weights = !trim_off; bool trim_asked = !trim_off; // ---- THE LAYER SPLIT'S SPILL WALK, STEP 1 (include/strata/program/split_walk.hpp), EARLY: THE TRIM FOR EVERY CARD, CUDA0 TOO. Under `--layer-split auto` CUDA0's weights load before the // search has chosen the split, so it could not be trimmed. When the cards in the split are short (two 8 GB cards: every card would carry a 3.5 GiB copy of the dense set beside its // session, head, drafter, a working cache and the prompt buffers, and 6 of 6 starts failed in 0.2.10), the split is chosen here, before anything is loaded, from what each card has // free once its fixed costs are paid, so every layer gets the same cache bytes on every card; it then runs as an explicit split with every card trimmed. The dense set's size is // estimated from the pack (the native projections at the ratio the IQ3_S pack has); the check after CUDA0's load decides again from the exact figure. Never reached by cards with // room; STRATA_STAGE_TRIM=0, STRATA_SPLIT_EARLY_OFF=1 or STRATA_SPILL_OFF=1 keeps the old path. if (multi_gpu && split_auto && !trim_user_asked && !split_devs.empty() && std::getenv("STRATA_SPILL_OFF") == nullptr && !(std::getenv("STRATA_STAGE_TRIM") != nullptr && std::string(std::getenv("STRATA_STAGE_TRIM")) == "0") && std::getenv("STRATA_SPLIT_EARLY_OFF") == nullptr && spill_discrete_gpu()) { namespace sw = strata::program::split_walk; sw::Model wm; uint64_t pool_est = 0; std::string perr; if (strata::core::WeightTable::pool_bytes(o.pack, pool_est, perr, skip.empty() ? nullptr : &skip)) { wm.dense_mib = (int64_t) ((pool_est + (o.native_dense_gguf.empty() ? 0 : pool_est * 138 / 100)) >> 20); std::vector devs{primary_device}; devs.insert(devs.end(), split_devs.begin(), split_devs.end()); const int nd = (int) devs.size(); wm.session_mib = (int64_t) (strata::core::session_bytes(g, o.max_context, K, 0, (g.n_layers + nd - 1) / nd) >> 20); if (!o.native_head_gguf.empty()) wm.head_mib = 410; // the Q5_K head of this model family (0.41 GiB); the exact figure is read once the head loads wm.drafter_mib = (!o.mtp.empty() || o.draft == "dflash2") ? strata::program::stage_reserve::kDrafterMib : 0; wm.slot_mib = 3; const int64_t later_reserve = (o.vram_reserve_later_mib >= 0 ? o.vram_reserve_later_mib : o.vram_reserve_mib) + strata::program::stage_reserve::kWindowMib; wm.reserve_mib = later_reserve; std::vector free_mib((size_t) nd, 0), room_mib((size_t) nd, 0); bool short_any = false; int short_dev = 0; int64_t short_free = 0; for (int i = 0; i < nd; ++i) { const strata::core::OnDevice on_e(devs[(size_t) i]); size_t fb_e = 0, tb_e = 0; if (cudaMemGetInfo(&fb_e, &tb_e) != cudaSuccess) { (void) cudaGetLastError(); fb_e = 0; } free_mib[(size_t) i] = (int64_t) (fb_e >> 20); const bool last_e = i + 1 == nd; if (!short_any && sw::trim_needed(free_mib[(size_t) i], wm, last_e)) { short_any = true; short_dev = devs[(size_t) i]; short_free = free_mib[(size_t) i]; } room_mib[(size_t) i] = free_mib[(size_t) i] - sw::kContextMib - (i == 0 ? (int64_t) o.vram_reserve_mib : later_reserve) - sw::kStageLateAllocMib - (last_e ? wm.head_mib + wm.drafter_mib : 0); } // FEWER CARDS (step 6): when even the whole walk (the drafter and the head moved off) does not pay for every layer on these cards, the card with the least room is left // out, one at a time, said plainly; with only CUDA0 left the start is the single card's, with its own walk and the rest of the experts in RAM. const int64_t per_layer_f = (wm.dense_mib + (int64_t) (strata::core::session_bytes(g, o.max_context, K, 0, g.n_layers) >> 20)) / std::max(g.n_layers, 1); auto base_room_of = [&](int i) { return free_mib[(size_t) i] - sw::kContextMib - (i == 0 ? (int64_t) o.vram_reserve_mib : later_reserve) - sw::kStageLateAllocMib; }; while (short_any && devs.size() >= 2) { const int ndl = (int) devs.size(); std::vector base_room((size_t) ndl); int64_t sum_room = 0; for (int i = 0; i < ndl; ++i) { base_room[(size_t) i] = base_room_of(i); sum_room += base_room[(size_t) i]; } if (sw::split_feasible(base_room.data(), ndl, g.n_layers, per_layer_f, wm.head_mib + wm.drafter_mib)) break; int worst = 1; for (int i = 2; i < ndl; ++i) if (base_room[(size_t) i] < base_room[(size_t) worst]) worst = i; std::fprintf(stderr, "strata generate: short of GPU memory: even with the drafter and the head moved off, %d cards with %.2f GiB of room in all cannot hold the %lld layers " "(%.2f GiB): the layer split runs without CUDA%d\n", ndl, (double) sum_room / 1024.0, (long long) g.n_layers, (double) (per_layer_f * g.n_layers) / 1024.0, devs[(size_t) worst]); devs.erase(devs.begin() + worst); free_mib.erase(free_mib.begin() + worst); } if (short_any && devs.size() == 1) { std::fprintf(stderr, "strata generate: short of GPU memory: no other card has room, so the model runs on CUDA%d alone with the experts that do not fit in RAM\n", devs[0]); multi_gpu = false; split_auto = false; split_devs.clear(); split_at.clear(); o.layer_split.clear(); short_any = false; } if (short_any) { const int nd = (int) devs.size(); split_devs.assign(devs.begin() + 1, devs.end()); // each remaining card's room; the last carries the head, and the drafter unless the room does not pay for it (the drafter step drops it then) room_mib.assign((size_t) nd, 0); int64_t sum_room = 0; for (int i = 0; i < nd; ++i) { room_mib[(size_t) i] = base_room_of(i); sum_room += room_mib[(size_t) i]; } room_mib[(size_t) nd - 1] -= wm.head_mib + (sum_room - wm.head_mib >= per_layer_f * g.n_layers + wm.drafter_mib ? wm.drafter_mib : 0); std::vector share((size_t) nd, 0); sw::proportional_layers(room_mib.data(), nd, g.n_layers, share.data()); bool share_ok = true; for (const int64_t s : share) share_ok = share_ok && s >= 2; if (share_ok) { std::vector at; std::string ks; int64_t run = 0; for (int i = 0; i + 1 < nd; ++i) { run += share[(size_t) i]; at.push_back(run); ks += (ks.empty() ? "" : ",") + std::to_string(run); } std::fprintf(stderr, "strata generate: short of GPU memory: CUDA%d has %.2f GiB free and a layer split card needs about %.2f GiB beside a full copy of the dense weights " "(%.2f GiB): the split is chosen from what each card has free (--layer-split %s) and every card loads only the dense weights of its own layers " "(STRATA_STAGE_TRIM=0 keeps the copies)\n", short_dev, (double) short_free / 1024.0, (double) sw::untrimmed_need_mib(wm, true) / 1024.0, (double) wm.dense_mib / 1024.0, ks.c_str()); split_at = at; split_auto = false; trim_asked = true; o.layer_split = ks; } } } } // CUDA0'S ARENA IS BUILT BEFORE THE SPLIT IS KNOWN. The prompt path's PLE tables are read out of it, here, // and `auto` does not choose its split points until 590 lines below - so CUDA0 can still only trim an // explicit --layer-split. It is also the cheapest card to leave alone: it runs layers 0..split_at[0] on // the device with the most room, and on the 4-way IQ3_S rig the trim buys it 4598 -> 4608 slots. The VRAM // is on the later cards (CUDA2 1241 -> 2485, CUDA3 533 -> 1772), and THEIR weights load after the search, // so they trim under `auto` too - see the block past it. const bool stage_trim = trim_asked && multi_gpu && !split_auto && !split_at.empty(); const bool latent_trim = stage_trim && [] { const char* v = std::getenv("STRATA_LATENT_TRIM"); return v == nullptr || std::string(v) != "0"; }(); if (o.trim_stage_flag == 1 && !multi_gpu) std::fprintf(stderr, "strata generate: --trim-stage-weights needs a layer split across GPUs (ignored)\n"); // Only `--layer-split auto` WITH the trim asked loads the later stages' weights after the split search (they can // only be trimmed once the split is known). Every other run keeps the 0.1.39 order: weights first, then the // search - so without the trim nothing about a split moves. bool late_weights = trim_asked && multi_gpu && split_auto; // THE LAYER SPLIT'S SPILL WALK, STEP 1 (include/strata/program/split_walk.hpp): a card too short for the whole dense set loads only its own layers' weights. Decided below, // once the dense set's size is known and before any later stage loads; `walk_trim` is that decision, `later_trim` the stages' trim (asked for, or the walk's). bool walk_trim = false; // keep_routers: CUDA0 with --mmap-experts keeps every layer's router (ffn_gate_inp, ~2.5 MiB a layer) - the file // tier's routing-aware prefetch (RouterLookahead, below) copies all of them from CUDA0's arena, and would // otherwise turn itself off auto add_foreign = [&](int64_t lb, int64_t le, std::set& out, bool keep_routers) { std::FILE* f = std::fopen((o.pack + "/index.txt").c_str(), "rb"); if (!f) return; char line[1024], name[256]; while (std::fgets(line, sizeof line, f)) { if (line[0] == '#' || std::sscanf(line, "%255s", name) != 1) continue; const std::string n = name; if (n.rfind("blk.", 0) != 0 || n.find("ple") != std::string::npos) continue; if (keep_routers && n.ends_with(".ffn_gate_inp.weight")) continue; const int64_t l = std::atoll(name + 4); if (l < lb || l >= le) out.insert(n); } std::fclose(f); }; if (stage_trim) { add_foreign(0, split_at[0], skip, o.mmap_experts); strata::core::NativeDense::set_layer_range(0, (int) split_at[0]); std::fprintf(stderr, "strata generate: layer split: CUDA0 loads the dense weights of layers 0-%lld only\n", (long long) split_at[0] - 1); } // STRATA_HC_REQ8=1 (opt-in, changes the output): the hyper-connection projections are not loaded as BF16; // load_hc_q8 below requantizes them to int8 + an fp32 scale per 32 values (~0.56x the bytes), and the freed VRAM // goes to the expert cache like any other. (Upstream's STRATA_HC_Q8 is a different thing: the GGUF's Q8_0 bytes.) const bool hc_req8_env = std::getenv("STRATA_HC_REQ8") != nullptr && std::atoi(std::getenv("STRATA_HC_REQ8")) != 0; if (hc_req8_env && multi_gpu) std::fprintf(stderr, "strata generate: WARNING: STRATA_HC_REQ8 does not support a layer split yet - the BF16 " "projections are used\n"); const bool hc_q8 = hc_req8_env && !multi_gpu; if (hc_q8) strata::core::WeightTable::hc_q8_names(g.n_layers, skip); uint64_t pool_bytes = 0; if (!strata::core::WeightTable::pool_bytes(o.pack, pool_bytes, err, skip.empty() ? nullptr : &skip)) { std::fprintf(stderr, "strata generate: %s\n", err.c_str()); return 1; } void* arena = nullptr; if (const cudaError_t ce = cudaMalloc(&arena, pool_bytes); ce != cudaSuccess) { // #486: the arena is the first large allocation and its size does not depend on the context, so what is // missing is held by something else: say how much was free cudaGetLastError(); #if (defined(STRATA_USE_HIP) || defined(STRATA_HIP_GFX906)) && !defined(_WIN32) // HIP sees no device at all and /dev/kfd exists but this user cannot open it: the missing render / video group, // not another program holding the memory (0 MiB of 0 MiB would blame the wrong thing) { int n_hip = 0; if ((cudaGetDeviceCount(&n_hip) != cudaSuccess || n_hip < 1) && ::access("/dev/kfd", F_OK) == 0 && ::access("/dev/kfd", R_OK | W_OK) != 0) { cudaGetLastError(); std::fprintf(stderr, "strata generate: no GPU is visible (%s) and this user cannot open /dev/kfd " "(permission denied): it is not another program holding the GPU. Add your user to " "the render and video groups - sudo usermod -aG render,video $USER - then log out " "and in again\n", cudaGetErrorString(ce)); return 1; } } #endif size_t free_b = 0, total_b = 0; cudaMemGetInfo(&free_b, &total_b); std::fprintf(stderr, "strata generate: cudaMalloc(%llu) for the weight arena failed (%s): %llu MiB of %llu " "MiB VRAM free on this GPU. The arena is allocated first, before the KV and expert " "caches: another program (or an engine that is still exiting) holds the rest - " "nvidia-smi / rocm-smi lists them\n", (unsigned long long) pool_bytes, cudaGetErrorString(ce), (unsigned long long) (free_b >> 20), (unsigned long long) (total_b >> 20)); { // #3797: every card of the run, and who else is on it std::vector report_devs; int cur = 0; if (cudaGetDevice(&cur) == cudaSuccess) report_devs.push_back(cur); else (void) cudaGetLastError(); for (const int d : split_devs) report_devs.push_back(d); print_startup_gpu_report(report_devs); } return 1; } mem_mark("the CUDA context and the weight arena"); auto load_t0 = std::chrono::steady_clock::now(); auto load_s = [&] { const auto t = std::chrono::steady_clock::now(); const double s = std::chrono::duration(t - load_t0).count(); load_t0 = t; return s; }; strata::core::WeightTable wt; if (!wt.load(o.pack, arena, pool_bytes, err, skip.empty() ? nullptr : &skip)) { std::fprintf(stderr, "strata generate: %s\n", err.c_str()); return 1; } if (hc_q8) { uint64_t qb = 0; if (!wt.load_hc_q8(o.pack, qb, err)) { std::fprintf(stderr, "strata generate: %s\n", err.c_str()); return 1; } std::fprintf(stderr, "strata generate: STRATA_HC_REQ8: hyper-connection projections as int8 + fp32/32 scales, " "%llu MiB\n", (unsigned long long) (qb >> 20)); } std::fprintf(stderr, "strata generate: %llu MiB of weights loaded from %s in %.1f s (%zu canonical tensors " "skipped: served natively)\n", (unsigned long long) (pool_bytes >> 20), o.pack.c_str(), load_s(), skip.size()); mem_mark("the pack weights"); strata::core::NativeDense native_dense; if (!o.native_dense_gguf.empty()) { if (!native_dense.load(o.native_dense_gguf, wt, err, o.native_ple_key)) { std::fprintf(stderr, "strata generate: native dense projections: %s\n", err.c_str()); return 1; } std::fprintf(stderr, "strata generate: %zu native projection matrices, %.2f MiB of weights, in %.1f s\n", native_dense.tensor_count(), (double) native_dense.weight_bytes() / (1024.0 * 1024.0), load_s()); } // ---- THE LAYER SPLIT'S SPILL WALK, STEP 1: THE TRIM. CUDA0 holds the whole dense set now; every later card is about to load a copy of it (3.5 GiB for IQ3_S), which on a // card that is short (two 8 GB cards: 6 of 6 starts failed in 0.2.10) is what leaves its expert cache and its prompt path no room. A card that cannot afford the copy // beside its session, its head, its drafter and a working cache loads only the dense weights of its own layers instead (--trim-stage-weights, bit-exact in itself: // the cache just gets the room). A card with room never reaches this; STRATA_STAGE_TRIM=0 or STRATA_SPILL_OFF=1 keeps the old copy. CUDA0 stays whole under // `--layer-split auto` (its weights load before the split is known); it runs the card's share of layers the search gives it. if (multi_gpu && !trim_user_asked && !split_devs.empty() && std::getenv("STRATA_SPILL_OFF") == nullptr && !(std::getenv("STRATA_STAGE_TRIM") != nullptr && std::string(std::getenv("STRATA_STAGE_TRIM")) == "0") && spill_discrete_gpu()) { strata::program::split_walk::Model wm; wm.dense_mib = (int64_t) ((pool_bytes + (o.native_dense_gguf.empty() ? 0 : native_dense.weight_bytes())) >> 20); const int ns_w = (int) split_devs.size() + 1; wm.session_mib = (int64_t) (strata::core::session_bytes(g, o.max_context, K, 0, (g.n_layers + ns_w - 1) / ns_w) >> 20); if (const strata::core::WeightRef* wo_w = wt.find("output.weight"); wo_w != nullptr && !o.native_head_gguf.empty()) wm.head_mib = (int64_t) (((uint64_t) wo_w->ne1 * (uint64_t) (g.n_embd / 256) * 176ull) >> 20); // Q5_K: 176 bytes per 256 values wm.drafter_mib = (!o.mtp.empty() || o.draft == "dflash2") ? strata::program::stage_reserve::kDrafterMib : 0; wm.slot_mib = std::max(1, (int64_t) ((strata::kernels::cpu::expert_layout().max_blob + (1u << 20) - 1) >> 20)); wm.reserve_mib = (o.vram_reserve_later_mib >= 0 ? o.vram_reserve_later_mib : o.vram_reserve_mib) + strata::program::stage_reserve::kWindowMib; for (size_t i = 0; i < split_devs.size(); ++i) { const strata::core::OnDevice on_w(split_devs[i]); size_t fb_w = 0, tb_w = 0; if (cudaMemGetInfo(&fb_w, &tb_w) != cudaSuccess) { (void) cudaGetLastError(); continue; } const bool last_w = i + 1 == split_devs.size(); if (strata::program::split_walk::trim_needed((int64_t) (fb_w >> 20), wm, last_w)) { std::fprintf(stderr, "strata generate: short of GPU memory: CUDA%d has %.2f GiB free and a layer split card needs about %.2f GiB beside a full copy of the dense weights " "(%.2f GiB): each later card loads only the dense weights of its own layers (STRATA_STAGE_TRIM=0 keeps the copy)\n", split_devs[i], (double) fb_w / 1073741824.0, (double) strata::program::split_walk::untrimmed_need_mib(wm, last_w) / 1024.0, (double) wm.dense_mib / 1024.0); walk_trim = true; break; } } if (walk_trim && split_auto) late_weights = true; } // the stages' dense weights are trimmed to their own layers: asked for (an explicit split), or by the walk; under `auto` they load after the split search (late_weights) const bool later_trim = stage_trim || (walk_trim && !split_auto && !split_at.empty()); strata::kernels::gr_set_fp32_activations(o.gr_fp32_activations); strata::kernels::gr_set_native_mmvf(o.gr_native_mmvf); // Plan v0.3 P3: the fused hyper-connection read rides the native (FP32-activation) contract; the per-stage // and dump measurements need the unfused layout of R, so they keep the old kernels. strata::core::layer_set_fast_attn(!o.no_fast_attn); strata::core::layer_set_publish_kernel(!o.no_publish_kernel); strata::core::layer_set_fused_gdn(!o.no_fused_gdn); strata::core::layer_set_fast_select(!o.no_fast_select); strata::core::layer_set_fused_gr(o.gr_native_mmvf && !o.no_fused_gr && !o.gpu_stages && o.dump_layers.empty() && o.dump_halves.empty() && !o.stage_timing); strata::core::layer_set_native_bf16(o.native_bf16); strata::core::layer_set_native_flash_attn_short(o.native_flash_attn_short); strata::kernels::ple_set_native_bf16(o.native_bf16_extra); strata::kernels::shared_expert_set_native_bf16(o.native_bf16_extra); strata::kernels::native_moe_combine_set_enabled(o.native_moe_combine); strata::kernels::native_gdn_set_enabled(o.native_gdn); strata::kernels::native_router_set_enabled(o.native_router); strata::kernels::native_qsa_set_enabled(o.native_qsa); strata::kernels::native_qsa_indexer_set_enabled(o.native_qsa_indexer); strata::kernels::native_rope_set_enabled(o.native_rope); // The vision path: every rope kernel reads a cell's (t, h, w) from this table (strata/kernels/mrope.hpp). It is // the identity until an image request, and it is set here, before any CUDA graph captures a rope kernel. int32_t* d_mrope = nullptr; std::vector mrope_host; if (o.vision) { const int64_t cells = o.max_context + 64; mrope_host.resize((size_t) cells * 3); for (int64_t c = 0; c < cells; ++c) mrope_host[(size_t) c * 3] = mrope_host[(size_t) c * 3 + 1] = mrope_host[(size_t) c * 3 + 2] = (int32_t) c; if (cudaMalloc(&d_mrope, mrope_host.size() * sizeof(int32_t)) != cudaSuccess || cudaMemcpy(d_mrope, mrope_host.data(), mrope_host.size() * sizeof(int32_t), cudaMemcpyHostToDevice) != cudaSuccess) { std::fprintf(stderr, "strata generate: cannot allocate the image position table\n"); return 1; } strata::kernels::mrope_table_set(d_mrope); } strata::kernels::ple_set_native_postops(o.native_ple_postops); // before session_init: every graph captured from here on has the vector's kernels where it applies std::string cvec_summary = "0"; uint64_t cvec_digest = 0; // a session file is bound to the loaded vector (0: none) if (!o.cvec_files.empty()) { std::string ce; if (!load_control_vectors(o, g, cvec_summary, cvec_digest, ce)) { std::fprintf(stderr, "strata generate: control vector: %s\n", ce.c_str()); return 2; } } if (o.max_context < (int64_t) o.tokens.size() + o.max_new) { std::fprintf(stderr, "strata generate: --max-context %lld cannot hold %zu prompt + %lld new tokens\n", (long long) o.max_context, o.tokens.size(), (long long) o.max_new); return 2; } strata::core::SessionState ss; void* sbuf = nullptr; // allocated after the layer-split search, sized to CUDA0's own layer range (the carve) // **THE ENGINE RAN ON THE LEGACY DEFAULT STREAM, WHICH ON WDDM IS THE SLOW PATH.** All four session // calls - `session_capture`, `session_replay`, `session_token` and `session_loop` - were handed `nullptr`, // i.e. stream 0. `bench/micro/kernel_costs.cu` measures what that costs: EVERY kernel it launches through // a wrapper comes back at 28-31 us REGARDLESS OF SIZE, `scale_inplace` on 2,048 floats and `silu_inplace` // on 10,240 floats being indistinguishable, which is a fixed per-launch cost and not execution. // `bench/micro/graph_node_cost.cu` measures the same kernels on a real stream at 3.63 us ungrapped and // 0.805 us inside a graph. **That is an ~8x penalty on every launch in the engine.** cudaStream_t main_stream = nullptr; if (cudaStreamCreateWithFlags(&main_stream, cudaStreamNonBlocking) != cudaSuccess) { std::fprintf(stderr, "strata generate: cannot create the main stream\n"); return 1; } void* const main_cs = (void*) main_stream; // ---- **THE HALF-LEVEL DUMP HAS TO BE ARMED BEFORE `session_capture`, AND THE LADDER MUST NOT BE.** The // half copies are issued from inside `block_layer_pre`/`block_layer_post`, so they are only ever enqueued // while a graph is being CAPTURED - arming `ss.block.dump` afterwards would produce a file of zeros that // reads exactly like a wrong answer. The ladder is the opposite: `session_loop` enqueues it per token on // the replay stream, so it must be armed after capture to stay out of the graph. const uint64_t half_stride = (uint64_t) 2 * g.n_embd + (uint64_t) 2 * g.hc + (uint64_t) g.n_head * g.head_dim + (uint64_t) 5 * g.n_head_kv * g.head_dim + 8; std::FILE* half_dump = nullptr; float* half_stage = nullptr; if (!o.dump_halves.empty()) { half_dump = std::fopen(o.dump_halves.c_str(), "wb"); if (half_dump == nullptr) { std::fprintf(stderr, "strata generate: cannot write %s\n", o.dump_halves.c_str()); return 1; } const size_t n = (size_t) g.n_layers * (size_t) half_stride; if (cudaHostAlloc((void**) &half_stage, n * sizeof(float), cudaHostAllocDefault) != cudaSuccess) { std::fprintf(stderr, "strata generate: cannot pin the half-dump staging buffer\n"); return 1; } ss.block.dump = half_stage; } strata::core::Doorbell db; if (strata::core::doorbell_init(g, K, db) == 0) { std::fprintf(stderr, "strata generate: doorbell_init failed\n"); return 1; } ss.db = &db; // ================================ THE PLE ================================ // // **ITS ABSENCE IS WHY GATE C1 FAILED** (LEDGER L123): layer 1 carries six `blk.1.ple_*` tensors, the whole // module was built and parity-tested, and nothing called it. Everything below is construction - the table // is a mapping of the ORIGINAL second GGUF shard, the six weights are already loaded in the arena, and the // three buffers are the only allocation. // the six layer-1 weights the PLE reads, from CUDA0's table (again after a trimmed split reloads it) auto wire_ple = [&](const strata::core::WeightTable& t) -> bool { const strata::core::WeightRef* wk = t.find("blk.1.ple_key.weight"); const strata::core::WeightRef* wv = t.find("blk.1.ple_value.weight"); const strata::core::WeightRef* wnk = t.find("blk.1.ple_norm_key.weight"); const strata::core::WeightRef* wnq = t.find("blk.1.ple_norm_query.weight"); const strata::core::WeightRef* wnc = t.find("blk.1.ple_norm_conv.weight"); const strata::core::WeightRef* wc = t.find("blk.1.ple_conv1d.weight"); if (!wk || !wv || !wnk || !wnq || !wnc || !wc) { std::fprintf(stderr, "strata generate: the pack has no blk.1.ple_* tensors, so the PLE cannot be " "wired - and running without it is a DIFFERENT MODEL (LEDGER L123)\n"); return false; } // `ple_key` is S2 and the loader has already widened its scales to f32, so the two planes are located // by the sizes the `WeightRef` records rather than re-derived - the same rule `plane_ptrs` follows. if (!wk->quantized()) { // plan v0.3 P6: the IQ model files' BF16 key (the pack's extra.bin, raw BF16) ss.ple.w.key_bf16 = (const uint16_t*) wk->data; } else if (wk->data != nullptr) { ss.ple.w.key_codes = (const uint8_t*) wk->data; ss.ple.w.key_scales = (const float*) ((const uint8_t*) wk->data + wk->codes_bytes); } if (o.native_ple_key && wk->quantized()) { if (!wk->native_data || (wk->native_type != 42 && wk->native_type != 18 && wk->native_type != 23 && wk->native_type != 8) || !wk->native_q8_1) { std::fprintf(stderr, "strata generate: native PLE key is absent or incompatible\n"); return false; } ss.ple.w.key_native_data = wk->native_data; ss.ple.w.key_native_type = wk->native_type; ss.ple.w.key_native_q8_1 = wk->native_q8_1; } ss.ple.w.value_bf16 = (const uint16_t*) wv->data; ss.ple.w.norm_key = (const float*) wnk->data; ss.ple.w.norm_query = (const float*) wnq->data; ss.ple.w.norm_conv = (const float*) wnc->data; // The conv1d kernel reads F16, so this cast is a claim about the pack's storage. A checkpoint that keeps // the tensor F32 (Q8_0, UD-Q4_K_XL) would hand the kernel the low halves of the f32 words - not an error, // a plausible wrong layer-1 routing. tools/iq_pack.py narrows it (index kind 3); a pack that did not is // refused here (#255, gopinath87607). F16 is index kind 5 or 3 (F16InF32) in a native pack and kind 0 // (verbatim 2-byte F16) in the canonical Q2_0 pack; BF16 (kind 4) has the same size and is not F16. const bool f16 = wc->kind == strata::core::WeightKind::F16InF32 || (wc->kind == strata::core::WeightKind::Verbatim && wc->code_bits == 0); if (!f16 || wc->bytes != (uint64_t) wc->elements * 2) { std::fprintf(stderr, "strata generate: blk.1.ple_conv1d.weight is not stored as F16 (pack index kind %d, " "%llu B for %lld values); the PLE conv1d kernel reads F16 - repack with " "tools/iq_pack.py\n", (int) wc->kind, (unsigned long long) wc->bytes, (long long) wc->elements); return false; } ss.ple.w.conv1d_f16 = (const uint16_t*) wc->data; return true; }; strata::kernels::PleTable ple_table; bool ple_lock_by_policy = false; // the table was locked in RAM by the residency policy (not by --ple-io ram): #4518 may give the lock back std::vector ple_emb_host((size_t) strata::kernels::NG_N_EMBD); float* ple_emb_dev = nullptr; float* ple_scratch = nullptr; if (!o.ple_gguf.empty()) { strata::kernels::PleIoOptions pio; pio.mode = o.ple_io == "mmap" || o.ple_io == "ram" ? strata::kernels::PleIo::Mmap : strata::kernels::PleIo::Direct; pio.lock = o.ple_io == "ram"; const auto tpl = Clock::now(); pio.max_inflight = (uint32_t) o.ple_inflight; pio.cache_rows = (uint64_t) o.ple_row_cache; pio.io_thread = !o.ple_sync_submit; // Keep the SSD awake while rows are being asked for (PleReader::set_keepalive): some SSDs stall the first // reads 50-150 ms after ~250 ms without a command. STRATA_SSD_KEEPALIVE = ms without a read before one // page is read anyway (default 100, 0 = off), STRATA_SSD_KEEPALIVE_WINDOW = seconds after the last row // request that this goes on (default 60; then the SSD may sleep until the next request). { const char* ka = std::getenv("STRATA_SSD_KEEPALIVE"); const char* kw = std::getenv("STRATA_SSD_KEEPALIVE_WINDOW"); pio.keepalive_ms = ka != nullptr && *ka ? std::clamp(std::atof(ka), 0.0, 10000.0) : 100.0; pio.keepalive_window_s = kw != nullptr && *kw ? std::clamp(std::atof(kw), 1.0, 86400.0) : 60.0; if (pio.mode != strata::kernels::PleIo::Direct || !pio.io_thread) pio.keepalive_ms = 0; } if (!ple_table.open(o.ple_gguf, err, pio)) { std::fprintf(stderr, "strata generate: %s\n", err.c_str()); return 1; } // 0.2.7 (R9700 measurement): keep the table resident in RAM when the PC can afford it. The rows of a // prompt token are random 90 B reads in a 28.8 GB table, so even a cached direct read pays ~100 us a // token and a mapped read pays a minor fault a row. Measured on p620 (R9700, IQ3_S, 8K prompt, 24576 // expert pairs of which 13207 resident): PLE block 845 ms direct / 451 ms mmap / 132 ms resident, // prompt 2125 / 2368 / 2611 tok/s, and the answer md5 was identical in all three. The RAM cost is the // table itself; the policy needs 8 GiB of headroom on top of it (available_host_bytes accounts for // cgroups and --memory-limit-mib), an explicit --ple-io always wins, and STRATA_PLE_AUTO_RAM=0 turns it off. // The expert arena is filled AFTER this point and wants its own RAM (51 GiB for IQ3_S), so the table is admitted // only when RAM holds table + arena + headroom (strata/core/ple_residency.hpp). Measured on the 64 GB RTX 5070 PC // (2026-10-26): table + 8 GiB alone admitted it, the table's lock took the lockable memory and the expert load // died with error 1453 (ERROR_WORKING_SET_QUOTA). bool ple_auto_ram = false; if (pio.mode == strata::kernels::PleIo::Direct && !o.ple_io_explicit) { const strata::kernels::PleIoOptions direct_pio = pio; const char* auto_ram = std::getenv("STRATA_PLE_AUTO_RAM"); bool allowed = strata::core::ple_auto_ram_allowed(auto_ram, strata::qwen_defaults_026()); #if defined(__APPLE__) // Not on the Mac unless asked (STRATA_PLE_AUTO_RAM=1): unified memory with the experts mapped from the file cache. M5 Max, // IQ3_S, 3 interleaved pairs: with the 26.8 GiB table locked, a cold 4K prompt after decode work is 10.6% slower (-10.7 -10.6 // -10.0) than the same build with direct reads, the footprint is 42 GB against 15 and free memory dips to 19 GB against 46; // decode is the same (+0.2..0.6% median, inside the spread). The Mac had direct reads until sample_host_memory learned // to read macOS RAM (the conversation cache fix), which let this policy fire there. if (!(auto_ram && std::string(auto_ram) == "1")) allowed = false; #endif const uint64_t need = ple_table.table_bytes(); const auto available = strata::core::available_host_bytes(); uint64_t experts_ram = 0; // every routed expert's blob, the arena the engine copies into RAM at start { const auto& elay = strata::kernels::cpu::expert_layout(); for (int64_t l = 0; l < elay.n_layers; ++l) experts_ram += elay.blob_bytes(l) * (uint64_t) elay.n_expert; } if (allowed && need > 0 && strata::core::ple_resident_admit(available, need, experts_ram, 8ull << 30)) { ple_table.close(); pio.mode = strata::kernels::PleIo::Mmap; pio.lock = true; pio.keepalive_ms = 0; std::string ram_err; if (ple_table.open(o.ple_gguf, ram_err, pio)) { ple_auto_ram = true; ple_lock_by_policy = ple_table.locked(); std::fprintf(stderr, "strata generate: --ple-io ram chosen by the residency policy (the table is " "%.1f GiB, the expert arena still to fill %.1f GiB and %.1f GiB of RAM is available; " "STRATA_PLE_AUTO_RAM=0 keeps the direct reads, --ple-io direct forces them)\n", (double) need / (1ull << 30), (double) experts_ram / (1ull << 30), (double) *available / (1ull << 30)); } else { // Back to what was asked for; a table that cannot be mapped must not stop the engine. std::fprintf(stderr, "strata generate: resident PLE table failed (%s); keeping direct reads\n", ram_err.c_str()); pio = direct_pio; if (!ple_table.open(o.ple_gguf, err, pio)) { std::fprintf(stderr, "strata generate: %s\n", err.c_str()); return 1; } } } } // Recommend, never force: when the default direct reads measure slow, switch to the mapped reads (40-100x // faster on the reporters' drives); an explicit --ple-io direct is kept and only warned about. if (pio.mode == strata::kernels::PleIo::Direct && std::getenv("STRATA_PLE_PROBE") == nullptr) { constexpr double kSlowRowsPerS = 15000.0; // ~60 MB/s of 4 KiB pages; a healthy NVMe is >100k const double rps = ple_direct_rows_per_s(ple_table); if (rps >= kSlowRowsPerS) std::fprintf(stderr, "strata generate: PLE direct read probe: %.0f rows/s (fine)\n", rps); if (rps > 0 && rps < kSlowRowsPerS) { // #1984 #1971 #2040: on no platform is the switch made on its own. Windows: the mapped reads stalled prompts (the first chunk waits for 16 serial page faults // a token from a cold table with no progress mark). Linux SATA SSD: the 15K rows/s bar is NVMe-calibrated, a SATA SSD // tops out at 10-14K with direct's 16 reads in flight and mapped reads were 7x slower. The switch is only made when asked for // (STRATA_PLE_AUTO_MMAP=1, the 0.1.42 behaviour); otherwise the slow probe warns and direct is kept. bool auto_mmap = !o.ple_io_explicit; if (const char* am = std::getenv("STRATA_PLE_AUTO_MMAP"); am == nullptr || std::atoi(am) == 0) auto_mmap = false; if (auto_mmap) { std::fprintf(stderr, "strata generate: --ple-io direct measures slow here (%.0f rows/s, about %.0f MB/s of " "random 4 KiB reads): using --ple-io mmap instead (the OS file cache holds the pages; " "--ple-io direct forces the old mode, --ple-io ram keeps the table in RAM)\n", rps, rps * 4096.0 / 1e6); ple_table.close(); pio.mode = strata::kernels::PleIo::Mmap; pio.keepalive_ms = 0; if (!ple_table.open(o.ple_gguf, err, pio)) { std::fprintf(stderr, "strata generate: %s\n", err.c_str()); return 1; } } else { std::fprintf(stderr, "strata generate: WARNING: --ple-io direct measures slow here (%.0f rows/s, about %.0f " "MB/s of random 4 KiB reads): a prompt can spend minutes reading layer 1 and trip the " "stall watchdog (#1425, #1629). --ple-io mmap was 40-100x faster on some DRAM-less NVMe drives but 7x slower on a SATA SSD (#2040), so it is not chosen for you; " "--ple-io ram needs the RAM for the table%s\n", rps, rps * 4096.0 / 1e6, o.ple_io_explicit ? "" : " (kept direct: pass --ple-io mmap or --ple-io ram to change it; in a config file's \"args\" they are two entries: \"--ple-io\", \"mmap\")"); } } } #if !defined(_WIN32) if (pio.mode == strata::kernels::PleIo::Direct) { // #605: --ple-io direct's random reads (up to --ple-inflight at once) are for SSDs; a rotational disk // can take longer than the stall watchdog's 60 s for one prompt chunk's rows. Recommended, not forced. std::string dev; if (!under_wddm() && on_rotational_disk(o.ple_gguf, dev) == 1) // (WSL's virtual disk says rotational) std::fprintf(stderr, "strata generate: WARNING: the n-gram table (%s) is on a rotational disk (%s): " "--ple-io direct reads it at random and can stall a prompt for minutes (#605). " "--ple-io ram (it then needs RAM for the table) or the model on an SSD is " "recommended\n", o.ple_gguf.c_str(), dev.c_str()); } #endif // the memory guard credits the process's own mapped file pages back only when they are not locked (conversation_memory.hpp) strata::core::set_locked_own_file_bytes(ple_table.locked() ? ple_table.table_bytes() : 0); if (pio.lock) std::fprintf(stderr, "strata generate: PLE table %s (%s) in %.1f s\n", ple_table.locked() ? "locked in RAM" : "loaded (not locked)", ple_auto_ram ? "--ple-io ram chosen by the residency policy" : "--ple-io ram", std::chrono::duration(Clock::now() - tpl).count()); if (pio.keepalive_ms > 0) std::fprintf(stderr, "strata generate: the SSD is kept awake while rows are read: one page of the table after " "%.0f ms without a read, until %.0f s after the last request " "(STRATA_SSD_KEEPALIVE=0 turns it off)\n", pio.keepalive_ms, pio.keepalive_window_s); else if (pio.mode == strata::kernels::PleIo::Direct) std::fprintf(stderr, "strata generate: SSD keep-alive off: the SSD may fall asleep between reads\n"); if (!wire_ple(wt)) return 1; ss.ple.consts = ple_consts_run; for (int h = 0; h < strata::kernels::PLE_N_HEADS; ++h) { // the hash may only reach rows the table has if (ple_consts_run.offset[h] + ple_consts_run.vocab[h] > ple_table.rows()) { std::fprintf(stderr, "strata generate: PLE head %d reaches row %llu but the table has %llu rows (the model file's hash constants do not fit its PLE table)\n", h, (unsigned long long) (ple_consts_run.offset[h] + ple_consts_run.vocab[h]), (unsigned long long) ple_table.rows()); return 1; } } if (o.ple_delay_us > 0) ple_table.set_injected_delay_us(o.ple_delay_us); ss.ple.table = &ple_table; ss.ple.token = &ss.ple_token; ss.ple.prev = ss.ple_prev; // `ss.ple.hist` and the ready() check wait for `session_init`, which carves the history - the session is // now allocated after the layer-split search (see the carve), and the wiring lands there ss.ple.emb_host = ple_emb_host.data(); if (cudaMalloc((void**) &ple_emb_dev, (size_t) strata::kernels::NG_N_EMBD * 4) != cudaSuccess || cudaMalloc((void**) &ple_scratch, strata::core::ple_run_scratch_bytes()) != cudaSuccess) { std::fprintf(stderr, "strata generate: the PLE buffers failed\n"); return 1; } ss.ple.emb_dev = ple_emb_dev; ss.ple.scratch = ple_scratch; } else { std::fprintf(stderr, "strata generate: PLE OFF by explicit --no-ple diagnostic request.\n" " The tokens below are NOT this model's; this is only useful for A/B measurement.\n"); } float* d_parts = nullptr; if (cudaMalloc(&d_parts, (size_t) K * g.n_embd * 4) != cudaSuccess || cudaMemset(d_parts, 0, (size_t) K * g.n_embd * 4) != cudaSuccess) { std::fprintf(stderr, "strata generate: the parts buffer failed\n"); return 1; } // ---- --split-skip-if-fits: before any later stage loads, does CUDA0 alone hold every profiled pair? What it // still has to allocate on one GPU is the whole session (the KV of every layer), the drafter and the head // (kDrafterMib below), the verify windows and the reserve; the prompt path borrows from the cache. If the // profile's pairs fit in what is left, a split would only add the hand-offs: run on CUDA0 alone. if (multi_gpu && split_auto && o.split_skip_if_fits) { std::vector> prof; int64_t pslots = 0; std::string perr; const bool remote = o.expert_cache_remote[0] > 0 || o.expert_cache_remote[1] > 0 || o.expert_cache_remote[2] > 0; if (remote || o.expert_profile.empty() || !strata::core::read_expert_profile(o.expert_profile, g.n_layers, g.n_expert, prof, pslots, perr)) { std::fprintf(stderr, "strata generate: --split-skip-if-fits: %s; the split stays\n", remote ? "remote expert caches are in use" : perr.empty() ? "no expert profile" : perr.c_str()); } else { const auto& lay = strata::kernels::cpu::expert_layout(); int64_t pairs_bytes = 0; for (const auto& pr : prof) pairs_bytes += native_pack ? strata::core::ExpertCache::slot_stride((int64_t) nib::slot_bytes(pr.first), slot_guard) : (int64_t) lay.max_blob; size_t fb = 0, tb = 0; cudaMemGetInfo(&fb, &tb); const int64_t session = (int64_t) strata::core::session_bytes(g, o.max_context, K, 0, g.n_layers); const int64_t held_back = session + (((int64_t) o.vram_reserve_mib + 1000 + 96) << 20); // + drafter/head, windows const int64_t room = (int64_t) fb - held_back; cudaDeviceProp dp{}; cudaGetDeviceProperties(&dp, 0); if (pairs_bytes <= room) { std::fprintf(stderr, "strata generate: layer split skipped (--split-skip-if-fits): CUDA0 (%s) holds all " "%zu profiled pairs (%.2f GiB) with the session (%.2f GiB, %lld-token context), " "the drafter and the reserve: %.2f GiB free, %.2f GiB to spare - one GPU\n", dp.name, prof.size(), (double) pairs_bytes / 1073741824.0, (double) session / 1073741824.0, (long long) o.max_context, (double) fb / 1073741824.0, (double) (room - pairs_bytes) / 1073741824.0); multi_gpu = false; split_auto = false; split_devs.clear(); split_at.clear(); o.layer_split.clear(); } else { std::fprintf(stderr, "strata generate: --split-skip-if-fits: CUDA0 (%s) would hold only %.2f of the " "profile's %.2f GiB (%.2f GiB free, %.2f GiB for the session, drafter and " "reserve): the split stays\n", dp.name, (double) std::max(room, 0) / 1073741824.0, (double) pairs_bytes / 1073741824.0, (double) fb / 1073741824.0, (double) held_back / 1073741824.0); } } } strata::core::Verifier::set_commit_async(!multi_gpu); // see Verifier::set_commit_async // --draft-fallback none: the MTP layer is not loaded and every "is there an MTP" test below sees --mtp as absent; DFlash2 drafts alone. The draft // vocabulary file is taken from the --mtp directory first. Anything DFlash2 cannot do here is an error at start (below), never a silent MTP. bool df2_solo = false; std::string df2_vocab_file; auto df2_vocab_path = [&]() -> std::string { // the draft vocabulary file DFlash2 binds its head from return df2_solo ? df2_vocab_file : o.mtp_draft_vocab.empty() ? o.mtp + "/draft_vocab.bin" : o.mtp_draft_vocab; }; if (o.draft == "dflash2" && o.draft_auto && o.draft_fallback == "none") { std::fprintf(stderr, "strata generate: --draft auto keeps both drafters (a request picks one); --draft-fallback none is for --draft dflash2\n"); return 2; } if (o.draft == "dflash2" && !o.draft_auto && o.draft_fallback != "mtp") { // (unset or none) if ((o.mtp.empty() && o.mtp_draft_vocab.empty()) || o.spec < 2 || o.draft_model.empty()) { // --mtp-draft-vocab FILE alone is enough: no MTP folder is needed std::fprintf(stderr, "strata generate: --draft dflash2 drafts without the MTP layer (--draft-fallback mtp loads it too) and needs --draft-model PACK, --spec 2 or more and --mtp-draft-vocab FILE (or --mtp DIR, for DIR/draft_vocab.bin)\n"); return 2; } if (!strata::core::Dflash2Drafter::head_native()) { // without the vocabulary subset the DFlash2 would run its head over all of the target's rows (+0.7 ms a round measured on Metal) without a word. // Metal alone has a packaged default subset to fall back to (the Mac's MTP folder is empty by design); everywhere else a missing file is the error. std::string packaged; bool whole_head_ok = false; #if defined(STRATA_GPU_METAL) packaged = strata::metal_engine::draft_vocab_default(); whole_head_ok = strata::metal_engine::draft_vocab_whole_head(); #endif const strata::spec::Df2Vocab dv = strata::spec::df2_vocab_resolve(o.mtp, o.mtp_draft_vocab, packaged, whole_head_ok, [](const std::string& p) { std::error_code vec; return std::filesystem::exists(p, vec); }); if (!dv.ok) { std::fprintf(stderr, "strata generate: %s\n", dv.why.c_str()); return 2; } if (dv.packaged) std::fprintf(stderr, "strata generate: --draft dflash2: no draft vocabulary in the MTP folder: using the packaged default subset %s\n", dv.path.c_str()); df2_vocab_file = dv.path; } o.mtp.clear(); df2_solo = true; } // --pipeline-windows (opt-in): one conversation's windows with the two stages of a layer split overlapped. Decided // here, before any stage sizes its expert cache (the second verifier per stage and the snapshots are allocated // after the caches, so their room is kept out of them). What it does not support turns it off, said once. // 0.1.43: not asked for (-1) = on (2) for gfx12 layer splits of three or more stages, where it was measured (4x R9700); // with two stages it loses (the drafter's chain shares the last card with its window). STRATA_PIPELINE_AUTO=0 keeps // it off, --pipeline-windows N asks for it as before. Anything it does not support leaves it off, said nothing. // 0.1.44: the drafter can sit on the first stage's card (see mtp_first below) when its draft head is the subset file: the main head // stays on the last card and only the subset's rows are copied over once const bool mtp_first_ok = [&] { if (o.mtp.empty() || o.spec < 2) return false; if (const char* fh = std::getenv("STRATA_MTP_FULL_HEAD"); fh != nullptr && fh[0] == '1') return false; std::error_code ec; return o.mtp_draft_vocab.empty() ? std::filesystem::exists(std::filesystem::path(o.mtp) / "draft_vocab.bin", ec) : std::filesystem::exists(o.mtp_draft_vocab, ec); }(); // --batch with the solo path pipelined (opt-in, STRATA_PW_WITH_BATCH=1). With slots, a request that is alone runs the solo // path (GEN, with drafts; serve/server.py goes back to it when a slot is left alone, #857), and that path can keep // --pipeline-windows: both parities' verifiers share the stage's session (ver_b.init(.., gs.ss, ..)), so when the solo // request is STOPped for a newcomer, copy_to_slot reads a whole state from `ss` after the pipeline has drained. Batch // windows never use the second verifiers. With --batch-mtp the slot drafters go where the solo drafter is: the first // stage's card when mtp_first (they share its weights and draft head, and copy the last stage's rows over as it does). // Without this, --batch turns --pipeline-windows off and a request alone loses its overlap (2x RX 6900 XT, IQ3_S, 0.1.45: // 75 -> 66.5 tok/s at 32K with "parallel": 2). const bool pw_with_batch = [] { const char* e = std::getenv("STRATA_PW_WITH_BATCH"); return e != nullptr && e[0] == '1'; }(); const bool batch_blocks_pw = o.batch != 0 && !pw_with_batch; const bool pw_auto = o.pipeline_windows < 0; if (pw_auto) { static const char* ae = std::getenv("STRATA_PIPELINE_AUTO"); static const char* am = std::getenv("STRATA_PIPELINE_AUTO_MIN_STAGES"); // two stages pay off only with the drafter on the first card (0.1.44, mtp_first): its chain no longer shares the last card with the window const size_t min_st = am != nullptr ? (size_t) std::max(2, std::atoi(am)) : (mtp_first_ok && mtp_first_default_on() ? 2 : 3); bool on = o.serve && multi_gpu && !split_same && split_devs.size() + 1 >= min_st && !(ae != nullptr && std::atoi(ae) == 0); #if defined(STRATA_USE_HIP) on = on && decode_defaults_arch_ok(); #else on = false; #endif const bool helpers_a = o.expert_cache_remote[0] > 0 || o.expert_cache_remote[1] > 0 || o.expert_cache_remote[2] > 0; if (on && o.draft == "dflash2" && !o.draft_auto && o.draft_fallback != "mtp") std::fprintf(stderr, "strata generate: --pipeline-windows is off by default here: DFlash2 drafts from the finished window's taps on " "every stage (--draft mtp keeps the pipeline)\n"); on = on && !o.mtp.empty() && o.spec >= 2 && !batch_blocks_pw && o.peer_device < 0 && !helpers_a && !o.adapt_async && !(o.draft == "dflash2" && !o.draft_auto && o.draft_fallback != "mtp"); o.pipeline_windows = on ? 2 : 0; if (on) std::fprintf(stderr, "strata generate: --pipeline-windows 2 is on by default for a layer split of %zu stages " "(--pipeline-windows 0 or STRATA_PIPELINE_AUTO=0 turns it off)\n", split_devs.size() + 1); } if (o.pipeline_windows > 0) { const bool helpers = o.expert_cache_remote[0] > 0 || o.expert_cache_remote[1] > 0 || o.expert_cache_remote[2] > 0; const char* off = !o.serve ? "it needs --serve" : split_same ? "it needs each stage of the layer split on its own GPU" : !multi_gpu ? "it needs a layer split on two GPUs" : split_devs.empty() ? "it needs a layer split into two or more stages" : split_devs.size() > 1 && o.pipeline_windows == 1 ? "--pipeline-windows 1 needs exactly two stages" : split_devs.size() > 1 && o.adapt_async ? "not with --adapt-async on three or more stages" : o.draft == "dflash2" && !o.draft_auto && o.draft_fallback != "mtp" ? "DFlash2 drafts from the finished window's taps on every stage, so the next window's drafts cannot exist while this one still runs (the speculative window the MTP's chain makes has no DFlash2 counterpart; see RESULTS-DF2MGPU.md)" : o.mtp.empty() || o.spec < 2 ? "it needs the MTP drafter (--mtp, --spec)" : batch_blocks_pw ? "not with --batch slots (STRATA_PW_WITH_BATCH=1 keeps it for the solo path)" : o.peer_device >= 1 ? "not with --peer-device" : helpers ? "not with the helper caches (--expert-cache-device1..3, --remote-expert-opt)" : nullptr; if (off != nullptr) { std::fprintf(stderr, "strata generate: --pipeline-windows %d is off: %s\n", o.pipeline_windows, off); o.pipeline_windows = 0; } else if (o.batch != 0) { std::fprintf(stderr, "strata generate: --pipeline-windows %d stays on for the solo path beside %d batch slots " "(STRATA_PW_WITH_BATCH=1); batch windows run without it\n", o.pipeline_windows, o.batch); } else if (!pw_auto && o.pipeline_windows >= 2 && split_devs.size() == 1) { // #2637: the default (above) takes two stages only with the draft layer on the first card (mtp_first); asked for by // hand it was taken without a word. Recommend, never force: it stays on as asked, and the line says what it costs. const char* e0 = std::getenv("STRATA_MTP_STAGE0"); const bool first_card = mtp_first_ok && (e0 != nullptr ? std::atoi(e0) != 0 : mtp_first_default_on()); if (!first_card) std::fprintf(stderr, "strata generate: note: --pipeline-windows %d on a layer split of two stages without the draft layer " "on the first card (%s): the draft chain then shares the last card with its window and the " "pipeline lost to the serial loop on 2x R9700 before 0.1.44 (docs/MULTI_GPU.md); kept as asked, " "--pipeline-windows 0 turns it off\n", o.pipeline_windows, !mtp_first_ok ? "it needs --mtp with --spec 2 or more and the draft head's subset file (draft_vocab.bin)" : "STRATA_MTP_STAGE0=1 asks for it"); } } // ---- layer split across GPUs: each later stage's own copy of the dense weights, its session and (the last) the // head, made on its device before the host arena is mapped (as the drafter below, for the same WDDM reason) std::vector> stages; // One stage's dense weights on its device (the caller has made it current): `trim` = only layers [lb, le). auto load_stage_weights = [&](GpuStage& st, int64_t lb, int64_t le, bool trim) -> bool { std::set skip_s = skip_base; uint64_t pool_s = pool_bytes; if (trim) { add_foreign(lb, le, skip_s, false); strata::core::NativeDense::set_layer_range((int) lb, (int) le); if (!strata::core::WeightTable::pool_bytes(o.pack, pool_s, err, &skip_s)) { std::fprintf(stderr, "strata generate: %s\n", err.c_str()); return false; } std::fprintf(stderr, "strata generate: layer split: CUDA%d loads the dense weights of layers %lld-%lld only\n", st.dev, (long long) lb, (long long) le - 1); } else { skip_s = skip; } void* arena_s = nullptr; if (cudaMalloc(&arena_s, pool_s) != cudaSuccess || !st.wt.load(o.pack, arena_s, pool_s, err, skip_s.empty() ? nullptr : &skip_s)) { cudaGetLastError(); size_t free_b = 0, total_b = 0; // #486: what that card had free cudaMemGetInfo(&free_b, &total_b); std::fprintf(stderr, "strata generate: layer split, CUDA%d weights: %s (%llu MiB needed, %llu MiB of %llu " "MiB free on that card)\n", st.dev, err.empty() ? "the weight arena does not fit" : err.c_str(), (unsigned long long) (pool_s >> 20), (unsigned long long) (free_b >> 20), (unsigned long long) (total_b >> 20)); { // #3797: every card of the run, and who else is on it std::vector report_devs; int cur = 0; if (cudaGetDevice(&cur) == cudaSuccess) report_devs.push_back(cur); else (void) cudaGetLastError(); for (const int d : split_devs) report_devs.push_back(d); print_startup_gpu_report(report_devs); } return false; } st.arena = arena_s; st.arena_bytes = pool_bytes; if (!lat_tab.load(g, err, latent_trim ? lb : 0, latent_trim ? le : g.n_layers)) { std::fprintf(stderr, "strata generate: layer split, CUDA%d latent dense: %s\n", st.dev, err.c_str()); return false; } if (!o.native_dense_gguf.empty() && !st.dense.load(o.native_dense_gguf, st.wt, err, o.native_ple_key)) { std::fprintf(stderr, "strata generate: layer split, CUDA%d native dense projections: %s\n", st.dev, err.c_str()); return false; } return true; }; for (size_t i = 0; multi_gpu && i < split_devs.size(); ++i) { stages.push_back(std::make_unique()); GpuStage& st = *stages.back(); st.dev = split_devs[i]; double free_gib = 0; if (!strata::core::RemoteExperts::preflight(st.dev, free_gib, err)) { std::fprintf(stderr, "strata generate: %s\n", err.c_str()); return 1; } const strata::core::OnDevice on(st.dev); // Later stages' weights load here (0.1.39), except `--layer-split auto` with the trim asked: those load after // the split search (see late_weights), so `auto` can trim them too. if (!late_weights) { const int64_t lb = later_trim ? split_at[i] : 0; const int64_t le = later_trim ? (i + 1 < split_at.size() ? split_at[i + 1] : g.n_layers) : 0; if (!load_stage_weights(st, lb, le, later_trim)) return 1; } // THE SESSION AND THE HEAD WAIT FOR THE SPLIT SEARCH. `session_bytes` prices a stage's session by its // LAYER RANGE (the carve - every stage used to hold all 48 layers' state whatever it ran), so the // sessions are allocated after the search below has set `st.lb`/`st.le`; the last stage's head follows. if (cudaStreamCreateWithFlags(&st.stream, cudaStreamNonBlocking) != cudaSuccess || cudaStreamCreateWithFlags(&st.adapt_stream, cudaStreamNonBlocking) != cudaSuccess || cudaEventCreateWithFlags(&st.adapt_ev, cudaEventDisableTiming) != cudaSuccess) { std::fprintf(stderr, "strata generate: layer split, CUDA%d: its streams failed\n", st.dev); return 1; } // a control vector (the speed projection): its tables on this device too - the stage's layers apply it here if (!strata::kernels::cvec_replicate(err)) { std::fprintf(stderr, "strata generate: layer split, CUDA%d: %s\n", st.dev, err.c_str()); return 1; } // --vision: this device's image-position table (the identity until a picture request), read by every rope // kernel its stage runs - set before any of its graphs is captured if (o.vision) { if (cudaMalloc(&st.mrope, mrope_host.size() * sizeof(int32_t)) != cudaSuccess || cudaMemcpy(st.mrope, mrope_host.data(), mrope_host.size() * sizeof(int32_t), cudaMemcpyHostToDevice) != cudaSuccess) { std::fprintf(stderr, "strata generate: layer split, CUDA%d: the image position table failed\n", st.dev); return 1; } strata::kernels::mrope_table_set(st.mrope); } // its own PCIe share of the missed experts (the same rule as CUDA0's above: its link is probed). A given // --pcie-frac is every stage's share and skips these probes (pcie_given); there is no per-stage setting yet. st.pcie_frac = o.pcie_frac; if (!pcie_given && native_pack) { std::string bursts; const double bw = probe_pcie_h2d_gbps(&bursts); if (bw > 0.0) st.pcie_frac = pcie_frac_for_gbps(bw, 0.55); st.link_gbps = bw; std::fprintf(stderr, "strata generate: layer split: CUDA%d PCIe probe %.1f GB/s (best of %s) -> pcie_frac " "%.2f\n", st.dev, bw, bursts.c_str(), st.pcie_frac); } if (!late_weights) { size_t fb = 0, tb = 0; cudaMemGetInfo(&fb, &tb); std::fprintf(stderr, "strata generate: layer split: CUDA%d holds its weights; %.2f GiB free (its session " "follows the split search)\n", st.dev, (double) fb / 1073741824.0); } } GpuStage* const last_st = stages.empty() ? nullptr : stages.back().get(); // 0.1.44: the drafter on the FIRST stage's card, for a two-stage pipelined decode. Its chain then runs while that card is idle // (stage 0 has finished the window the chain follows), not beside the last stage's window on the last card, where the two // streams share the card and each takes ~2x as long (stage-1 window 11 -> 25 ms, chain 7 -> 21 ms, 2x R9700). The chain's // source rows are copied over once per chain (stage_source_R), the draft head's rows once at load. const bool mtp_first = [&] { if (!mtp_first_ok || o.pipeline_windows < 2 || stages.empty() || batch_blocks_pw) return false; const char* e = std::getenv("STRATA_MTP_STAGE0"); if (e != nullptr) return std::atoi(e) != 0; // 0 keeps the drafter on the last card, 1 asks for the first return mtp_first_default_on(); }(); // DFlash2 on a layer split: its card is the LAST stage's by default (the head rows, the embedding path and the Main role are there; only the // earlier stages' taps cross, a few KB a window), or the FIRST stage's with STRATA_DF2_STAGE=first (a measurement seam, not a default). const bool df2_first = [&] { if (!multi_gpu || stages.empty() || o.draft != "dflash2" || o.draft_auto) return false; const char* e = std::getenv("STRATA_DF2_STAGE"); return e != nullptr && std::string(e) == "first"; }(); std::vector> profile; if (!o.expert_profile.empty()) { int64_t pslots = 0; if (!strata::core::read_expert_profile(o.expert_profile, g.n_layers, g.n_expert, profile, pslots, err)) { std::fprintf(stderr, "strata generate: %s\n", err.c_str()); return 1; } // An explicit number truncates the ranked list ("what would 2,000 slots give" without rebuilding the // file). `--expert-cache 0` used to take the count the profile was built for; the profile now ranks // every pair (issue #46: a card that holds more than the old 8,000 used to stop there), so it means auto. if (o.expert_cache == 0) o.expert_cache = -1; // Multi-GPU: STRATA_PEER_HOT= gives the peer card a share f of the HOT pairs, so both cards // compute routed experts every layer (the primary alone did ~25 of ~30 per layer-window). Of the first // STRATA_PEER_HOT_AT (default 8700, ~ the primary's slots) ranks, every pair with floor((r+1)f) > floor(rf) // moves to just after that point: the primary fills past them, the peer (which takes what the primary does // not hold, in order) gets them first. if (o.peer_device >= 1) { // default 0.45 (measured: 0.3-0.6 all better than 0; 0 = off, e.g. for the gate) const char* ph = std::getenv("STRATA_PEER_HOT"); const double f = ph ? std::atof(ph) : 0.45; const char* pa = std::getenv("STRATA_PEER_HOT_AT"); const size_t at = std::min(profile.size(), (size_t) (pa ? std::atoll(pa) : 8700)); if (f > 0.0 && f < 1.0 && at > 0) { std::vector> keep, moved; for (size_t r = 0; r < at; ++r) { const bool to_peer = (int64_t) ((double) (r + 1) * f) > (int64_t) ((double) r * f); (to_peer ? moved : keep).push_back(profile[r]); } const size_t n_moved = moved.size(); // the primary's share continues with the ranks after `at` until it is full; then the moved ones std::vector> out; out.reserve(profile.size()); out.insert(out.end(), keep.begin(), keep.end()); const size_t fill = std::min(profile.size(), at + n_moved); // what the primary still takes out.insert(out.end(), profile.begin() + (long) at, profile.begin() + (long) fill); out.insert(out.end(), moved.begin(), moved.end()); out.insert(out.end(), profile.begin() + (long) fill, profile.end()); profile.swap(out); std::fprintf(stderr, "strata generate: STRATA_PEER_HOT %.2f: %zu of the first %zu ranked pairs moved " "behind rank %zu (the peer's)\n", f, n_moved, at, fill); } } std::fprintf(stderr, "strata generate: profile %s: %zu ranked pairs, built for %lld slots\n", o.expert_profile.c_str(), profile.size(), (long long) pslots); } // #477: the whole ranking as loaded, the prior of --expert-profile-save's order (a layer split keeps only // CUDA0's pairs in `profile` below). Empty without --expert-profile-save. std::vector> profile_loaded; if (!o.expert_profile_save.empty()) profile_loaded = profile; std::vector> ram_rank; // --ram-profile if (!o.ram_profile.empty()) { int64_t ram_slots = 0; if (!strata::core::read_expert_profile(o.ram_profile, g.n_layers, g.n_expert, ram_rank, ram_slots, err)) { std::fprintf(stderr, "strata generate: --ram-profile: %s\n", err.c_str()); return 1; } std::fprintf(stderr, "strata generate: the RAM tier is ranked by %s (%zu pairs); the GPU cache by --expert-profile\n", o.ram_profile.c_str(), ram_rank.size()); } // ---- layer split across GPUs: "auto" places the split points by a cost model of one decode window, measured on // the 5080 + 3090 rig (bench/results/2026-09-29-layer-split): // - every layer costs its GPU a time inversely proportional to SMs x clock (0.33 ms on an RTX 5080, 0.50 on a // 3090: the per-layer round trip and kernels, not the bytes - both cards have ~950 GB/s); // - an expert no cache holds costs ~190 ms per unit of routed mass: the CPU pool in decode and the PCIe stream // in prompts (fitted: the sweep's best K, 26-28, is where one more layer on the faster card stops paying // for the ~0.1% of the mass it pushes out of its cache); // SCALED PER STAGE BY ITS PROBED LINK against the 20 GB/s x16 reference (pcie_frac_for_gbps' rule): the // prompt path fetches a missed expert over ITS stage's link, so a stage on a narrow link pays // proportionally more per missed unit. Without this the search is blind to asymmetric cards: // 2026-10-04, 2x 4090 D with CUDA1 on a physical x1 link (1.6 GB/s), auto chose K=22 and read prompts // at ~350 tok/s; with the scale (x12 on CUDA1) it chooses the fit-in-cache boundary K=38: ~1400 tok/s. // With every scale 1.0 the objective is the formula the 190 ms was fitted with (unchanged). // - which experts a cache holds: its layers' profiled pairs, hottest first, until its free VRAM (less the // reserve, the prompt path's buffers and, on a later GPU, 1 GiB for its windows and the drafter) is used; // the routed mass a cache holds follows the COVERAGE CURVE below, not the (r+1)^-1.2 this used to use. // Up to 4 GPUs every placement is tried; beyond, the layers are shared in proportion to speed. // A FOUR-WAY PLACEMENT USED TO BE THE PROPORTIONAL GUESS AND NOTHING ELSE. That formula reads only // `layer_ms`, so on four GPUs the free VRAM a placement leaves for expert caches - the whole point of // the search - never entered it. It does now; see the ns == 4 branch below. // STRATA_SPLIT_MISS_MS tunes the miss cost (a slower CPU: higher). // THE PROMPT PATH'S BUFFERS ARE BORROWED FROM THE CACHE, NOT WITHHELD BESIDE IT. With borrowing the cache // is sized first and at full size, and the prompt path is laid out in the tail of it (`Prefill::relayout`), // so it withholds no VRAM of its own and this reserve is zero. Only without borrowing - no profile to fill // a cache from, or --no-prefill-borrow - do the buffers take a reserve, and then this estimate stands in // for buffers that cannot be priced exactly yet because the sessions do not exist. `plan_lend` uses the // exact `Prefill::bytes_needed` as soon as it can. bool pf_borrow = !o.no_prefill_borrow && !o.expert_profile.empty(); // (0.2.10: the auto cache sizing below can clear it, see AUTO NO-BORROW) // (#340: the estimate predates the streamed ring: from 1024-token chunks the prompt path also holds a ring of // whole expert blobs, which a split without borrowing sizes at 96 (Prefill::set_ring_override below) and books // here - without it a `--no-prefill-borrow` split filled the cards and the draft head no longer fit) const int64_t split_ring_mib = (multi_gpu && !pf_borrow && o.prefill_chunk >= strata::prefill::Prefill::stream_all_min_tokens()) ? (int64_t) ((96ull * (uint64_t) strata::kernels::cpu::expert_layout().max_blob + (1ull << 20) - 1) >> 20) : 0; if (split_ring_mib > 0) strata::prefill::Prefill::set_ring_override(96); if (o.prefill_pipe >= 0.0) strata::prefill::Prefill::set_pipe(o.prefill_pipe); const int64_t split_pf_mib = (o.prefill_chunk > 0 && !pf_borrow) ? 160 + (o.prefill_chunk * 680) / 1024 + split_ring_mib : 0; // ---- WHAT A STAGE RESERVES, AND ON WHICH STAGE. The flat 1 GiB this used to withhold from EVERY stage // after the first was booked "for its windows and the drafter", but the windows measure 75 MiB ("window up // to 6 tokens, 74.1 MiB of device buffers", on every boot) and the drafter is loaded on ONE stage - the // last one, which is also the only one that holds the head. On the two identical 8 GB cards that GiB was // the entire difference between CUDA0's cache and CUDA1's: 814 slots against 188, 2026-09-30. Both of // those allocations are already made before a stage's cache is sized, so what has to be held back here is // the windows and - only on the stage that carries them - the drafter and the head. // (the arithmetic is program/stage_reserve.hpp's: 96 MiB for the verify windows - 75 MiB measured, rounded up - // and 1000 MiB for the MTP drafter and the head on the last stage only; pinned by tests/program/stage_reserve_test.cpp) // --pipeline-windows: a second verifier on every stage (its arena alone is 70-75 MiB and its graphs come on top: // 64 MiB left two RTX 5070 Ti under Linux short of it) and, with the decode pipelined, two copies of the first // stage's GDN state (sized from its session where the first card's cache is sized; this is the split search's // estimate). Allocated after the caches, so kept out of them. const int64_t kPipeWindowMib = o.pipeline_windows > 0 ? 160 : 0; const int64_t kPipeSnapMib = o.pipeline_windows >= 2 ? 96 : 0; // ~3 MiB per GDN layer, twice, ~15 layers auto gdn_snapshot_bytes = [&](const strata::core::SessionState& s0) -> size_t { return (size_t) s0.gdn_alloc * ((size_t) g.ssm_state_size * g.ssm_v_heads * g.ssm_state_size + (size_t) g.ssm_conv_channels * (g.ssm_d_conv - 1)) * sizeof(float); }; // #340: with the own prompt buffers chosen by the split's rule (not asked for with --no-prefill-borrow) the // boundary is searched as the borrowing configuration would (no reserve): the reserve then only makes the caches // smaller, which measured cost no decode (K=28 on 9070 XT + R9700: 58.4 tok/s own vs 58.5 borrowing), while a // search with the reserve moved the boundary to K=32 and decode to 54.8. STRATA_SPLIT_OWN_PLACE=reserve: the // search sees the reserve. // ---- `--layer-split auto` with the trim asked: a later stage's weights load after this search, so they are not in // `cudaMemGetInfo` yet and are priced from the pack for each candidate range [lb, le): `pool_bytes` of the trimmed // arena (reads the index, allocates nothing) and `NativeDense::weight_bytes_for` for the projections, which `load` // makes one cudaMalloc each (a 2 MiB granule per matrix of a MiB or more). Priced as the full copy and without the // projections, a small card was over-credited and `auto` gave it layers it could not hold: P40 24 GB + RTX 3070 // 8 GB picked K=2 where K=16 is right (#1238, #880). Every other run has its weights loaded already, so its // `cap` is net of them and this is 0 (nothing about those placements moves); CUDA0's are loaded too. bool carve_ok = true; std::map, uint64_t> carve_memo, carve_dense_memo; // the second: the projections' share of the first auto carve_bytes = [&](int64_t lb, int64_t le) -> uint64_t { if (!late_weights) return 0; const std::pair key(lb, le); if (const auto it = carve_memo.find(key); it != carve_memo.end()) return it->second; std::set sk = skip_base; add_foreign(lb, le, sk, false); uint64_t total = 0; if (!strata::core::WeightTable::pool_bytes(o.pack, total, err, sk.empty() ? nullptr : &sk)) { carve_ok = false; return 0; } if (!o.native_dense_gguf.empty()) { uint64_t dense = 0; if (!strata::core::NativeDense::weight_bytes_for(o.native_dense_gguf, wt, o.native_ple_key, lb, le, dense, err)) { carve_ok = false; return 0; } total += dense; carve_dense_memo.emplace(key, dense); } carve_memo.emplace(key, total); return total; }; static const bool place_with_reserve = [] { const char* v = std::getenv("STRATA_SPLIT_OWN_PLACE"); return v != nullptr && std::string(v) == "reserve"; }(); auto stage_room = [&](int dev, bool later, bool drafter, bool search = false) -> int64_t { const strata::core::OnDevice on(dev); size_t fb = 0, tb = 0; if (const cudaError_t e = cudaMemGetInfo(&fb, &tb); e != cudaSuccess) std::fprintf(stderr, "strata generate: layer split: CUDA%d free memory: %s\n", dev < 0 ? 0 : dev, cudaGetErrorString(e)); const int64_t pf = search && split_own_auto && !place_with_reserve ? 0 : split_pf_mib; // what a later stage allocates after its cache and nothing prices (cuBLAS, the modules and the MMQ pool the prompt path warms up, ~250 MiB measured): the single card prices // it (kLateAllocMib, #4474); a stage did not, and two 16 GB cards ended a start with 131 MiB free and ran out of memory in the first long prompt. Not under STRATA_DEFAULTS=026. const int64_t late_alloc = later && !strata::qwen_defaults_026() ? strata::program::split_walk::kStageLateAllocMib : 0; const int64_t base_reserve = (later && o.vram_reserve_later_mib >= 0 ? o.vram_reserve_later_mib : o.vram_reserve_mib) + late_alloc; strata::program::stage_reserve::Inputs rin; rin.base_reserve_mib = base_reserve; rin.prompt_buffers_mib = pf; rin.later = later; rin.drafter = drafter; rin.pipe_window_mib = kPipeWindowMib; rin.pipe_snap_mib = kPipeSnapMib; return strata::program::stage_reserve::room_bytes((int64_t) fb, rin); }; // ---- TRIMMED STAGE WEIGHTS (the default with a split, --no-trim-stage-weights: off). Every card has just // loaded the dense weights of all the layers and runs only its own: once the split is known each one reloads // its own layers' (below), and the search counts what that frees towards the card's expert cache. On a 4060 // Ti + 5080 with Swift 1.5 IQ3_XXS at K=20 that was 1.9 + 1.3 GiB, 2,174 more cached experts and none left to // read from the files: 98 -> 131 tok/s on code at a 32K context, its prompt 1,006 -> 1,978 tok/s. const bool trim = o.trim_stage_weights && multi_gpu && !stages.empty(); std::vector> layer_rows((size_t) g.n_layers); // the arena's blk.. rows std::vector trim_prefix((size_t) g.n_layers + 1, 0); // the bytes of layers [0, l) if (trim) { if (std::FILE* f = std::fopen((o.pack + "/index.txt").c_str(), "rb")) { char line[1024], name[256]; while (std::fgets(line, sizeof line, f)) if (line[0] != '#' && std::sscanf(line, "%255s", name) == 1 && std::strncmp(name, "blk.", 4) == 0 && !skip.count(name) && std::strstr(name, "ple") == nullptr) { // the PLE rows stay on every card (add_foreign keeps them too) const long l = std::strtol(name + 4, nullptr, 10); if (l >= 0 && l < g.n_layers) layer_rows[(size_t) l].push_back(name); } std::fclose(f); } for (int64_t l = 0; l < g.n_layers; ++l) { std::set without = skip; without.insert(layer_rows[(size_t) l].begin(), layer_rows[(size_t) l].end()); uint64_t rest = pool_bytes; if (!strata::core::WeightTable::pool_bytes(o.pack, rest, err, &without)) { std::fprintf(stderr, "strata generate: %s\n", err.c_str()); return 1; } trim_prefix[(size_t) l + 1] = trim_prefix[(size_t) l] + (int64_t) (pool_bytes - rest) + (int64_t) native_dense.bytes_in(l, l + 1); } } // what a stage that runs [lb, le) frees by trimming (until then every card holds every layer) auto trim_frees = [&](int64_t lb, int64_t le) -> int64_t { return trim ? trim_prefix[(size_t) g.n_layers] - (trim_prefix[(size_t) le] - trim_prefix[(size_t) lb]) : 0; }; if (multi_gpu && split_auto) { const auto& lay = strata::kernels::cpu::expert_layout(); const int ns = (int) stages.size() + 1; std::vector cap((size_t) ns), used((size_t) ns); // what stage i has left for experts if it runs [lb, le): its room, minus its session and (a later stage) its weights auto stage_left = [&](int i, int64_t lb, int64_t le) -> int64_t { return cap[(size_t) i] - (int64_t) strata::core::session_bytes(g, o.max_context, K, lb, le) - (i == 0 ? 0 : (int64_t) carve_bytes(lb, le)); }; std::vector layer_ms((size_t) ns); for (int i = 0; i < ns; ++i) { const int dev = i == 0 ? 0 : stages[(size_t) i - 1]->dev; cap[(size_t) i] = stage_room(i == 0 ? -1 : dev, i > 0, (mtp_first || df2_first) ? i == 0 : i + 1 == ns, true); int sms = 0, khz = 0; cudaDeviceGetAttribute(&sms, cudaDevAttrMultiProcessorCount, dev); if (cudaDeviceGetAttribute(&khz, cudaDevAttrClockRate, dev) != cudaSuccess || khz <= 0) khz = 1800000; cudaGetLastError(); double speed = std::max(1.0, (double) sms * (double) khz / 1e6); // SMs x GHz // STRATA_SPLIT_SPEED_SCALE="1,0.55": each stage's speed times this factor (a test seam: an unequal pair, e.g. the // 4060 Ti + 3060 of #2644, on two equal cards); unset = nothing changes. if (const char* sc = std::getenv("STRATA_SPLIT_SPEED_SCALE"); sc != nullptr && *sc) { const char* p = sc; for (int k = 0; k < i && p != nullptr; ++k) { p = std::strchr(p, ','); if (p) ++p; } const double f = p != nullptr ? std::atof(p) : 0.0; if (f > 0.0) speed = std::max(1.0, speed * f); } layer_ms[(size_t) i] = 0.33 * (84.0 * 2.617) / speed; std::fprintf(stderr, "strata generate: layer split auto: CUDA%d %d SMs at %.2f GHz -> %.2f ms per layer, " "%.2f GiB free before its session carve\n", dev, sms, khz / 1e6, layer_ms[(size_t) i], (double) cap[(size_t) i] / 1073741824.0); } // The per-stage link, measured here (the stage-setup probes are skipped when --pcie-frac is given, and the // search needs the reading either way). std::vector link_gbps((size_t) ns, -1.0); for (int i = 0; i < ns; ++i) { const int dev = i == 0 ? 0 : stages[(size_t) i - 1]->dev; const strata::core::OnDevice on(dev); std::string bursts; link_gbps[(size_t) i] = native_pack ? probe_pcie_h2d_gbps(&bursts) : -1.0; } // #2007: relative to the fastest stage's link and only from a 4x gap on (split_rules::link_miss_scale): a // symmetric rig, or a moderate gap, keeps the fitted formula. STRATA_SPLIT_LINK_ABS=1: 0.1.41's 20 GB/s rule. // STRATA_SPLIT_UNIFORM=1: no per-link scaling at all (the pre-0.1.41 uniform miss cost), for A/B on links // where any scaling moves auto off the balanced placement. static const bool link_abs = [] { const char* v = std::getenv("STRATA_SPLIT_LINK_ABS"); return v && v[0] == '1'; }(); static const bool split_uniform = [] { const char* v = std::getenv("STRATA_SPLIT_UNIFORM"); return v && v[0] == '1'; }(); std::vector link_scale = strata::program::split_rules::link_miss_scale(link_gbps); for (int i = 0; i < ns; ++i) { const double bw = link_gbps[(size_t) i]; if (split_uniform) link_scale[(size_t) i] = 1.0; else if (link_abs) link_scale[(size_t) i] = bw > 0.0 ? std::clamp(20.0 / bw, 1.0, 64.0) : 1.0; std::fprintf(stderr, "strata generate: layer split auto: CUDA%d link %.1f GB/s -> miss cost x%.2f\n", i == 0 ? 0 : stages[(size_t) i - 1]->dev, bw, link_scale[(size_t) i]); } const double miss_ms = std::getenv("STRATA_SPLIT_MISS_MS") ? std::atof(std::getenv("STRATA_SPLIT_MISS_MS")) : 190.0; // ---- THE COVERAGE CURVE: HOW MUCH ROUTED MASS A CACHE HOLDS, AND WHY IT IS NO LONGER A POWER LAW. // // `mass[r]` used to be (r+1)^-1.2, fitted to the 5080+3090 sweep. That fit is still right ON THE RIG IT // WAS FITTED TO - at 20,000 pairs held it predicts 99.35% of the routed mass and that rig measured 99.4%. // It is wrong on the IQ3_S 4-way rig, badly: it claims the top 5,805 pairs hold 94.9% of the mass, and // that rig measures 69.2% (four boots, 14.9M decode lookups). No exponent reconciles them, because the // curve is a property of the MODEL'S ROUTING, not a universal constant - and the profile file carries // only a RANKING, with no counts, so it cannot be read off the data either. (tools/make_profile.py has // the frequencies, and drops them; see the note there.) // // What the two rigs do agree on is that the hit rate follows the HELD COUNT and almost nothing else: two // different splits held 14,541 and 14,384 pairs and measured 92.2% and 89.8% of the routed mass. So the // curve is taken over the held FRACTION f, as H(f) = 1 - (1 - f)^b, and each rank's mass is that curve's // increment, which makes any prefix of N pairs sum to exactly H(N/total) while a cache holding // colder-than-prefix pairs still scores below it. // // b = 3 IS CHOSEN TO LEAVE THE PREVIOUSLY VALIDATED REGIME WHERE IT WAS. At 20,000 held (f = 0.8138) it // gives 99.35%, against the old fit's 99.35% and that rig's measured 99.4% - the 2-GPU placement is // untouched. At f = 0.59 it gives 93.2% against 92.2% measured. Below f ~ 0.5 the two curves diverge, // and that is the whole point: it is exactly the regime where the old one was wrong, and where it told // the search that stranding a card's VRAM costs almost nothing. // // THE CURVE IS A FIT TO ONE MODEL'S TRAFFIC. STRATA_SPLIT_COVER_B overrides b for a model whose routing // is sharper or flatter, and STRATA_SPLIT_MISS_MS still scales the miss cost it feeds. const size_t n_ranked = profile.size(); const double cover_b = std::getenv("STRATA_SPLIT_COVER_B") ? std::atof(std::getenv("STRATA_SPLIT_COVER_B")) : 3.0; std::vector mass(n_ranked); double total_mass = 0; // Up to 3 GPUs the 0.1.39 curve (r+1)^-1.2 is kept, so 2- and 3-GPU placements do not move (the new curve is a // fit to a 4-way rig and was not measured on them); STRATA_SPLIT_COVER_B asks for the coverage curve at any // GPU count. const bool coverage_curve = ns >= 4 || std::getenv("STRATA_SPLIT_COVER_B") != nullptr; for (size_t r = 0; r < n_ranked; ++r) { if (!coverage_curve) { total_mass += (mass[r] = std::pow((double) r + 1.0, -1.2)); continue; } const double hi = std::pow(1.0 - (double) r / (double) n_ranked, cover_b); const double lo = std::pow(1.0 - (double) (r + 1) / (double) n_ranked, cover_b); total_mass += (mass[r] = hi - lo); } auto cost = [&](int64_t l) -> int64_t { return native_pack ? strata::core::ExpertCache::slot_stride((int64_t) nib::slot_bytes(l), slot_guard) : (int64_t) lay.max_blob; }; // the predicted window time (ms) of a placement, and the routed mass its caches hold std::vector held_cnt((size_t) ns, 0); // per-stage fill count, for the startability gate const int64_t kAutoLendPct = [] { const char* v = std::getenv("STRATA_PREFILL_LEND_PCT"); return v ? (int64_t) std::atoi(v) : g_lend_keep != 128 ? (int64_t) 100 // a card too short for the usual loan (see the cache sizing) lends what it must: the cap is for cards with room : (int64_t) (strata::prefill::Prefill::pinned_share() >= 0.9 ? 90 : 85); }(); auto predict = [&](const std::vector& at, double& held_mass, int64_t& held) -> double { // THE CARVE, PRICED: a placement gives stage i the layers [lb, le), and that range's session is a // real cost on its device - subtracted here so the search knows what it leaves for experts. This // is why the sessions are allocated after the search: `session_bytes` is pure arithmetic. std::vector capr((size_t) ns); for (int i = 0; i < ns; ++i) { const int64_t lb = i == 0 ? 0 : at[(size_t) i - 1]; const int64_t le = i + 1 < ns ? at[(size_t) i] : g.n_layers; capr[(size_t) i] = stage_left(i, lb, le) + strata::program::split_rules::trim_credit(i, trim_frees(lb, le)); } std::fill(used.begin(), used.end(), 0); std::fill(held_cnt.begin(), held_cnt.end(), 0); held_mass = 0; held = 0; std::vector mass_i((size_t) ns, 0.0), held_i((size_t) ns, 0.0); std::vector full((size_t) ns, false); for (size_t r = 0; r < profile.size(); ++r) { const int64_t l = profile[r].first; int st = 0; while (st + 1 < ns && l >= at[(size_t) st]) ++st; mass_i[(size_t) st] += mass[r]; if (full[(size_t) st]) continue; if (used[(size_t) st] + cost(l) > capr[(size_t) st]) { full[(size_t) st] = true; continue; } // as the fill used[(size_t) st] += cost(l); held_mass += mass[r]; held_i[(size_t) st] += mass[r]; ++held; ++held_cnt[(size_t) st]; } held_mass /= std::max(total_mass, 1e-9); // Each stage's misses on its own link (link_scale; 1.0 everywhere = the fitted single-constant formula). double ms = 0.0; for (int i = 0; i < ns; ++i) ms += miss_ms * link_scale[(size_t) i] * std::max(0.0, mass_i[(size_t) i] - held_i[(size_t) i]) / std::max(total_mass, 1e-9); for (int i = 0; i < ns; ++i) { const int64_t lb = i == 0 ? 0 : at[(size_t) i - 1], le = i + 1 < ns ? at[(size_t) i] : g.n_layers; ms += (double) (le - lb) * layer_ms[(size_t) i]; } return ms; }; std::vector best, at((size_t) ns - 1); double best_ms = 1e30, best_mass = 0; int64_t best_held = 0, tried = 0; // TIES GO TO THE BALANCED PLACEMENT. When every placement holds the whole profile (the model fits the cards, // as IQ3_S does on two or more 32 GB cards) the predicted decode window is the same for all of them - the // layers' times just add - and which one "won" was floating-point noise in the sum: 3 layers on the first // card, 30 on the second. A prompt flows through the stages as a pipeline, so its speed is the slowest stage's: // measured on 4x R9700 with --trim-stage-weights, 6,36,41 read a 32K prompt at 1,750 tok/s and 12,24,36 at 2,780, // same decode speed, same tokens. Among placements whose window time agrees to 1e-6 ms the one with the // smallest slowest stage (layers x ms per layer) is kept; an earlier one stays on a second tie. double best_max = 1e30; auto stage_max = [&](const std::vector& cuts) { double m = 0; for (int i = 0; i < ns; ++i) { const int64_t lb = i == 0 ? 0 : cuts[(size_t) i - 1], le = i + 1 < ns ? cuts[(size_t) i] : g.n_layers; m = std::max(m, (double) (le - lb) * layer_ms[(size_t) i]); } return m; }; const double tie_eps = 1e-6; // ---- LAYER SPLIT STARTABILITY GATE (LAYER 1). The search must not price placements only by decode time: // a split is usable only if the prompt path can start, which requires (serve, `fits_one` 5625-5636 + own_fits // 5855-5869): every participant must lend a chunk, or else afford its own prompt buffers with the serve-time // 512 MiB headroom. Here we check it for the last-resort chunk (512 tokens, bottom of kStepChunks 5849), // which is necessary and sufficient by monotonicity (both the slot test and `bytes_needed` grow with c). // // chunk_bytes uses a no-alloc fake SessionState. qsa_state_init is NOT used: with base=nullptr it would // cudaMemcpy a null page table and kv_stream_reset a null map (CUDA "invalid argument") on a streamed // state. bytes_needed only reads max_cells and kv_mode/n_pages/kv_int8/kv_q4/kv_hybrid, so we set those // fields directly, replicating kv_plan's arithmetic (layer.cpp:634) with the public getters. auto chunk_bytes = [&](int64_t lb, int64_t c) -> uint64_t { strata::core::qsa_set_kv_resident(o.kv_resident); const strata::kernels::QsaShapes s = strata::core::qsa_shapes(g); const int64_t pages = (o.max_context + s.page_size - 1) / s.page_size; int mode = 0; const int64_t kv_res = strata::core::qsa_kv_resident(); if (kv_res > 0) { const int64_t r = (std::max(kv_res, strata::core::qsa_kv_resident_min()) + s.page_size - 1) / s.page_size; if (r < pages) mode = 1; } const bool q4 = strata::core::qsa_kv_q4(); const bool hyb = strata::core::qsa_kv_hybrid(); const bool i8 = strata::core::qsa_kv_int8() && !q4; std::vector qs((size_t) g.n_qsa_layers()); for (int64_t j = 0; j < g.n_qsa_layers(); ++j) { qs[(size_t) j].max_cells = o.max_context; qs[(size_t) j].kv_mode = mode; qs[(size_t) j].n_pages = pages; qs[(size_t) j].kv_int8 = i8; qs[(size_t) j].kv_q4 = q4; qs[(size_t) j].kv_hybrid = hyb; } strata::core::SessionState ss{}; ss.max_cells = o.max_context; ss.qsa_states = qs.data(); const int64_t I = std::max(g.qsa_interval, 1); ss.qsa_ord0 = (int) (lb / I); // no_ring: serve sizes the streamed ring to what the rig affords (scan's ring_room), so the gate's // discriminator is the MOE set against each cache's slots - the ring is a separate budget, not a // reason a stage cannot lend. bytes_needed's default ring (384 slots) would inflate a 2-layer // stage's need past its cache and reject a split serve accepts. return strata::prefill::Prefill::bytes_needed_no_ring(g, ss, c); }; struct PartStat { int64_t lb, le; int64_t used; int64_t cnt; int64_t cap; }; auto can_start = [&](const std::vector& parts) -> bool { const int64_t kMaxBlob = (int64_t) nibble_max_slot_bytes(); // max_blob (or a larger 4-bit slot) auto slots_est_of = [&](int i, uint64_t cn) -> int64_t { if (parts[i].cnt <= 0) return -1; const uint64_t avg = (parts[i].used > 0) ? (uint64_t) parts[i].used / (uint64_t) parts[i].cnt : (uint64_t) kMaxBlob; return (int64_t) ((cn + avg - 1) / avg); }; auto fit_one = [&](int i, int64_t c, bool cap) -> bool { // mirrors fits_one (5820-5824) const int64_t k = slots_est_of(i, chunk_bytes(parts[i].lb, c)); if (k <= 0 || k + g_lend_keep > parts[i].cnt) return false; return !(cap && k * 100 > kAutoLendPct * parts[i].cnt); }; auto all_fit = [&](int64_t c, bool cap) -> bool { for (int i = 0; i < ns; ++i) if (!fit_one(i, c, cap)) return false; return true; }; // the chunk serve picks: the largest the WHOLE rig can lend (scan(nullptr), 5876-5895). A stage // whose cache is smaller than its layers' chunk (CUDA1's 512 slots for one layer) lends nothing, so // the bisection returns 0 and the loan is off - the host then has to afford its own buffers. int64_t chunk = 0; if (o.prefill_auto) { int64_t lo = 1, hi = 8192 / 256, best = 0; while (lo <= hi) { const int64_t mid = lo + (hi - lo) / 2; if (all_fit(mid * 256, true)) { best = mid * 256; lo = mid + 1; } else hi = mid - 1; } chunk = best; } else { for (int64_t c = o.prefill_chunk; c >= 256; c /= 2) if (all_fit(c, false)) { chunk = c; break; } } auto room_mib = [&](int i) -> int64_t { return (int64_t) ((parts[i].cap - parts[i].used) >> 20); }; static const bool gate_dbg = std::getenv("STRATA_LAYER_SPLIT_GATE") != nullptr; if (gate_dbg) { std::fprintf(stderr, "gate: K=%lld chunk=%lld", (long long) (ns == 2 ? parts[1].lb : 0), (long long) chunk); for (int i = 0; i < ns; ++i) { const uint64_t cn = chunk_bytes(parts[i].lb, chunk > 0 ? chunk : 256); std::fprintf(stderr, " | CUDA%d lb=%lld cnt=%lld used=%lldMiB cap=%lldMiB room=%lldMiB need=%lldMiB slots=%lld", i == 0 ? 0 : (int) stages[(size_t) i - 1]->dev, (long long) parts[i].lb, (long long) parts[i].cnt, (long long) (parts[i].used >> 20), (long long) (parts[i].cap >> 20), (long long) room_mib(i), (long long) (cn >> 20), (long long) slots_est_of(i, cn)); } std::fprintf(stderr, "\n"); } if (chunk == 0) { // no loan: every participant must afford its own buffers (serve 5960-5975) for (int i = 0; i < ns; ++i) if (room_mib(i) < (int64_t) (chunk_bytes(parts[i].lb, 256) >> 20) + 1536) return false; return true; } for (int i = 0; i < ns; ++i) { const uint64_t cn = chunk_bytes(parts[i].lb, chunk); const int64_t k = slots_est_of(i, cn); const bool lends = k > 0 && k + g_lend_keep <= parts[i].cnt && k * 100 <= kAutoLendPct * parts[i].cnt; if (lends) continue; if (room_mib(i) >= (int64_t) (cn >> 20) + 1536) continue; // affords its own buffers return false; } return true; }; // participant stats for a candidate, from the fill `predict` just computed (ns==2/3 + proportional) auto parts_of = [&](const std::vector& at) { std::vector parts((size_t) ns); for (int i = 0; i < ns; ++i) { parts[i].lb = i == 0 ? 0 : at[i - 1]; parts[i].le = i + 1 < ns ? at[i] : g.n_layers; parts[i].used = used[i]; parts[i].cnt = held_cnt[i]; parts[i].cap = stage_left(i, parts[i].lb, parts[i].le); } return parts; }; bool gate_on = true; // off only when no placement can start (below): then the best one is kept and a warning said int64_t min_stage_layers = 1; // #1616: 3 in the second pass below, when the first pick has a one- or two-layer stage std::vector stage_floors; // #2644: each stage's share of the room, in the share pass below (empty: off) // #1428: 2 and 3 GPUs - every placement priced, kept (a few hundred) so the near-tie warning below can name the // best placement that is really a different one (not the neighbour one layer over) std::vector>> priced; auto consider = [&]() { if (min_stage_layers > 1 && strata::program::split_rules::smallest_stage(at, g.n_layers) < min_stage_layers) return; if (!stage_floors.empty() && strata::program::split_rules::below_floors(at, g.n_layers, stage_floors)) return; double hm = 0; int64_t held = 0; const double ms = predict(at, hm, held); ++tried; if (ns <= 3) priced.emplace_back(ms, at); const double mx = stage_max(at); if (ms < best_ms - tie_eps || (ms <= best_ms + tie_eps && mx < best_max - tie_eps)) { // feasibility gate: mirrors the serve path (`fits_one` + own_fits) for the 512-token last resort; // a placement the prompt path cannot start is not chosen (#1094) - unless nothing can start, below if (gate_on && !can_start(parts_of(at))) return; best = at; best_ms = std::min(ms, best_ms); best_mass = hm; best_held = held; best_max = mx; } }; const int64_t L = g.n_layers; // share the layers in proportion to speed: the fallback beyond four GPUs, and the only placement a // model too small to hold four stages has (see the ns == 4 branch). auto proportional = [&]() { double total = 0; for (const double c : layer_ms) total += 1.0 / c; double acc = 0; for (int i = 0; i + 1 < ns; ++i) { acc += 1.0 / layer_ms[(size_t) i]; at[(size_t) i] = std::clamp((int64_t) std::llround(acc / total * (double) L), i == 0 ? 2 : at[(size_t) i - 1] + 1, L - (ns - 1 - i)); } consider(); }; auto search = [&]() { priced.clear(); if (ns == 2) { for (int64_t k = 2; k < L; ++k) { at[0] = k; consider(); } // a model with fewer than three layers enumerates nothing: keep the proportional guess rather than // leave `best` empty (an empty split would read split_at[i] out of bounds at the stage lb/le loop) if (best.empty()) proportional(); } else if (ns == 3) { for (int64_t k1 = 2; k1 + 1 < L; ++k1) for (int64_t k2 = k1 + 1; k2 < L; ++k2) { at[0] = k1; at[1] = k2; consider(); } if (best.empty()) proportional(); } else if (ns == 4) { // ---- EVERY FOUR-WAY PLACEMENT IS TRIED. This branch used to share the layers in proportion to // speed and score that ONE candidate, and that formula reads only `layer_ms` - never the free VRAM. // So on a four-GPU rig cache capacity did not influence the placement AT ALL, and the card with // the most room left could be handed the fewest layers: on the 3060/3060/5060/5060 box CUDA1 ended // up with 1,841 MiB no cache could use while CUDA2 ran 15 layers it could only hold a third of. // All C(L-3,3) placements - 15,180 at 48 layers - are now scored. // // A STAGE'S FILL DEPENDS ONLY ON ITS OWN RANGE AND ITS OWN FREE VRAM. `predict` hands each ranked // pair to the one stage that owns its layer and each stage stops at its first pair that does not // fit, so the four fills are independent and a placement's held mass is a SUM over its four // ranges. That is what makes this affordable: each distinct range is walked once and memoised, // 1,121 walks instead of 15,180 - measured at 14 ms against 740 ms, for the same answer. // `le` runs to L inclusive, so a row is L+1 wide - keying on a stride of L would put the last // stage's [lb, L) one past the end of the vector. // // NOTE: on v0.1.39 the search only runs under `--layer-split auto`, where every card still holds // the whole model's dense weights, so `cap[i]` is already net of them and the stage's room is what // `predict` subtracts - the session. (On the branch this came from the carve reached `auto` too, // and each stage's own weight bytes were taken off here as well.) const size_t stride = (size_t) L + 1; std::vector held_mass_at((size_t) ns * (size_t) L * stride, -1.0); std::vector held_at(held_mass_at.size(), 0); std::vector used_at(held_mass_at.size(), 0); // the fill's byte total, for the startability gate auto range_hold = [&](int i, int64_t lb, int64_t le) -> size_t { const size_t key = ((size_t) i * (size_t) L + (size_t) lb) * stride + (size_t) le; if (held_mass_at[key] < 0.0) { // one stage's own carve, exactly as `predict` prices it const int64_t room = stage_left(i, lb, le); double hm = 0; int64_t used = 0, cnt = 0; for (size_t r = 0; r < profile.size(); ++r) { const int64_t l = profile[r].first; if (l < lb || l >= le) continue; if (used + cost(l) > room) break; // the fill stops exactly where predict's does used += cost(l); hm += mass[r]; ++cnt; } held_mass_at[key] = hm; held_at[key] = cnt; used_at[key] = used; } return key; }; const double denom = std::max(total_mass, 1e-9); for (int64_t k1 = 2; k1 + 2 < L; ++k1) for (int64_t k2 = k1 + 1; k2 + 1 < L; ++k2) for (int64_t k3 = k2 + 1; k3 < L; ++k3) { const size_t a = range_hold(0, 0, k1), b = range_hold(1, k1, k2); const size_t c = range_hold(2, k2, k3), d = range_hold(3, k3, L); const double hm = held_mass_at[a] + held_mass_at[b] + held_mass_at[c] + held_mass_at[d]; const double ms = miss_ms * (1.0 - hm / denom) + (double) k1 * layer_ms[0] + (double) (k2 - k1) * layer_ms[1] + (double) (k3 - k2) * layer_ms[2] + (double) (L - k3) * layer_ms[3]; if (min_stage_layers > 1 && strata::program::split_rules::smallest_stage({k1, k2, k3}, L) < min_stage_layers) continue; if (!stage_floors.empty() && strata::program::split_rules::below_floors({k1, k2, k3}, L, stage_floors)) continue; ++tried; const double mx = stage_max({k1, k2, k3}); if (!(ms < best_ms - tie_eps || (ms <= best_ms + tie_eps && mx < best_max - tie_eps))) continue; if (gate_on) { // the same startability gate as `consider`, over the memoised fills const int64_t lbs[4] = {0, k1, k2, k3}; const int64_t les[4] = {k1, k2, k3, L}; std::vector parts((size_t) ns); for (int i = 0; i < ns; ++i) { const size_t key = i == 0 ? a : i == 1 ? b : i == 2 ? c : d; parts[i].lb = lbs[i]; parts[i].le = les[i]; parts[i].used = used_at[key]; parts[i].cnt = held_at[key]; parts[i].cap = stage_left(i, lbs[i], les[i]); } if (!can_start(parts)) continue; } best = {k1, k2, k3}; best_ms = std::min(ms, best_ms); best_max = mx; best_mass = hm / denom; best_held = held_at[a] + held_at[b] + held_at[c] + held_at[d]; } // Four stages into fewer than five layers: nothing was enumerated, so keep the old guess rather // than leave `best` empty - an empty split would leave every stage's lb/le unset. if (best.empty()) proportional(); } else { // Beyond four GPUs the placements outnumber any budget worth spending at startup (C(46,4) is // 163,185 at five). Nothing on this rig reaches it. proportional(); } }; search(); // ---- #1616: a stage with one or two layers holds a handful of expert slots (a 12 GB 3060: 512), and the // prompt chunk of every card is clamped to what the smallest cache can lend. When the pick has such a // stage, look again among placements that give every stage at least kMinStageLayers layers; keep the new // pick if there is one, and say so. Recommend, never force: with none startable the first pick stays. if (!best.empty() && strata::program::split_rules::restriction_possible(g.n_layers, ns) && strata::program::split_rules::has_tiny_stage(best, g.n_layers)) { const std::vector first = best; const double first_ms = best_ms; auto fmt = [](const std::vector& v) { std::string s; for (const int64_t k : v) s += (s.empty() ? "" : ",") + std::to_string(k); return s; }; // ---- #2644 (two GPUs): first a placement in which each stage owns at least its share of the layers by its room for // experts. The three-layer rule below lands on its own edge when the card that is predicted slower has little // room (4060 Ti 16 GB + 3060 12 GB: K=3, the 3060 idle, -44% prefill). The rooms are read at the even split // (a session and a later stage's weights depend on the range). bool share_pick = false; if (ns == 2) { std::vector rooms((size_t) ns); for (int i = 0; i < ns; ++i) rooms[(size_t) i] = stage_left(i, g.n_layers * i / ns, g.n_layers * (i + 1) / ns); const std::vector floors = strata::program::split_rules::share_floors(rooms, g.n_layers); if (strata::program::split_rules::floors_exceed_minimum(floors)) { best.clear(); best_ms = 1e30; best_max = 1e30; best_mass = 0; best_held = 0; stage_floors = floors; search(); stage_floors.clear(); share_pick = !best.empty(); if (share_pick) std::fprintf(stderr, "strata generate: layer split auto: K=%s would give a stage fewer than %lld layers " "(a tiny expert cache there clamps the prompt chunk of every card, #1616) and " "leave that card idle; chose K=%s instead, which gives each card at least its " "share of the layers by its room for experts (%.1f ms per decode window, not %.1f; " "--layer-split N sets it by hand, #2644)\n", fmt(first).c_str(), (long long) strata::program::split_rules::kMinStageLayers, fmt(best).c_str(), best_ms, first_ms); } } if (!share_pick) { best.clear(); best_ms = 1e30; best_max = 1e30; best_mass = 0; best_held = 0; min_stage_layers = strata::program::split_rules::kMinStageLayers; search(); min_stage_layers = 1; if (best.empty()) { best = first; best_ms = first_ms; std::fprintf(stderr, "strata generate: layer split auto: K=%s gives a stage fewer than %lld layers (a " "tiny expert cache clamps the prompt chunk, #1616), but no placement with at least " "that many layers can start; keeping it\n", fmt(first).c_str(), (long long) strata::program::split_rules::kMinStageLayers); } else { std::fprintf(stderr, "strata generate: layer split auto: K=%s would give a stage fewer than %lld layers " "(a tiny expert cache there clamps the prompt chunk of every card, #1616); chose " "K=%s instead (%.1f ms per decode window, not %.1f)\n", fmt(first).c_str(), (long long) strata::program::split_rules::kMinStageLayers, fmt(best).c_str(), best_ms, first_ms); } } } // ---- no startable placement: fall back to proportional, and if that too is impossible, say what is short auto split_diagnosis = [&](const std::vector& at) { const int64_t c = 512; for (int i = 0; i < ns; ++i) { const int dev = i == 0 ? 0 : stages[(size_t) i - 1]->dev; const int64_t lb = i == 0 ? 0 : at[(size_t) i - 1]; const int64_t le = i + 1 < ns ? at[(size_t) i] : g.n_layers; const uint64_t cn = chunk_bytes(lb, c); const int64_t room_mib = (int64_t) (stage_left(i, lb, le) >> 20); std::fprintf(stderr, "strata generate: CUDA%d: a 512-token prompt needs %lld MiB of its own buffers " "(+512 MiB headroom); %lld MiB is left for them after its session and cache\n", dev, (long long) (cn >> 20), (long long) room_mib); } std::fprintf(stderr, "strata generate: to make room: a smaller --max-context, --prefill 512, a smaller " "--vram-reserve-mib, an explicit --layer-split, or close other programs using the GPU\n"); }; // THE LAYER SPLIT'S SPILL WALK, STEP 2: THE KV WINDOW DOWN. No placement can start the prompt path with the window asked for: the sessions of the cards are smaller with a // smaller one (the rest of the K/V streams from pinned RAM), so the search runs again at 20480, 8192, 4096 cells a layer (the engine's smallest) and keeps the first window // that has a startable placement. The context and the number of requests are not touched. Never reached by a start that has a placement. if (best.empty() && std::getenv("STRATA_SPILL_OFF") == nullptr && spill_discrete_gpu()) { const int64_t kv_asked = o.kv_resident; for (int64_t w; (w = strata::program::split_walk::next_kv_window(o.kv_resident, o.max_context, strata::core::qsa_kv_resident_min())) > 0;) { o.kv_resident = w; strata::core::qsa_set_kv_resident(w); search(); if (!best.empty()) { std::fprintf(stderr, "strata generate: short of GPU memory: the KV window is %lld cells a layer in VRAM instead of %s, the rest is read from RAM: the context " "(%lld tokens) is unchanged\n", (long long) w, kv_asked > 0 ? std::to_string((long long) kv_asked).c_str() : "the whole context", (long long) o.max_context); break; } } if (best.empty()) { o.kv_resident = kv_asked; strata::core::qsa_set_kv_resident(kv_asked); } } if (best.empty()) { // recommend, never force: with nothing startable on paper the search runs again without the gate, so the // run is as it was before the gate, and what is short is said std::fprintf(stderr, "strata generate: layer split auto: no placement can start the prompt path on the " "figures here; choosing by decode speed alone\n"); gate_on = false; search(); if (!best.empty()) split_diagnosis(best); } if (best.empty()) { std::fprintf(stderr, "strata generate: --layer-split auto: no valid split for %d GPUs (this model has %lld layers)\n", ns, (long long) g.n_layers); return 2; } if (!carve_ok) { // `carve_bytes` reports through `err`; it is called from the search, which cannot return std::fprintf(stderr, "strata generate: %s\n", err.c_str()); return 1; } split_at = best; std::string ks; for (const int64_t k : split_at) ks += (ks.empty() ? "" : ",") + std::to_string(k); std::fprintf(stderr, "strata generate: layer split auto: K=%s - predicted %.1f ms per decode window; the caches " "hold %lld of %zu profiled pairs (~%.1f%% of the routed mass), best of %lld placements\n", ks.c_str(), best_ms, (long long) best_held, profile.size(), 100.0 * best_mass, (long long) tried); // #1428: a near tie on a mixed pair. The model prices a decode window only (the prompt path is not in it), and on // cards of different speed or link the winner can flip within a few percent of error: say which other split is // almost as good, so the user can try it. Recommend, never force: this only prints. { const double lo = *std::min_element(layer_ms.begin(), layer_ms.end()); const double hi = *std::max_element(layer_ms.begin(), layer_ms.end()); const double llo = *std::min_element(link_scale.begin(), link_scale.end()); const double lhi = *std::max_element(link_scale.begin(), link_scale.end()); const bool mixed = hi > lo * 1.10 || lhi > llo * 1.10; const double near_pct = std::getenv("STRATA_SPLIT_NEAR_TIE_PCT") ? std::atof(std::getenv("STRATA_SPLIT_NEAR_TIE_PCT")) : 4.0; if (mixed && near_pct > 0 && ns <= 3 && best_ms > 0 && !priced.empty()) { const std::vector* alt = nullptr; double alt_ms = 1e30; for (const auto& pc : priced) { if (pc.first > best_ms * (1.0 + near_pct / 100.0) || pc.first >= alt_ms) continue; int64_t dist = 0; // how far the other split's boundaries lie from the chosen one's for (size_t i = 0; i < pc.second.size() && i < best.size(); ++i) dist = std::max(dist, std::llabs(pc.second[i] - best[i])); if (dist < 3) continue; // the neighbour one layer over is not a different split if (gate_on && !can_start(parts_of(pc.second))) continue; alt = &pc.second; alt_ms = pc.first; } if (alt != nullptr) { std::string as; for (const int64_t k : *alt) as += (as.empty() ? "" : ",") + std::to_string(k); std::fprintf(stderr, "strata generate: layer split auto: NEAR TIE - K=%s is predicted %.1f ms per decode " "window, within %.1f%% of K=%s (%.1f ms); the cards differ, so the prediction may not " "rank them (it prices decode, not the prompt). To try the other: --layer-split %s\n", as.c_str(), alt_ms, 100.0 * (alt_ms / best_ms - 1.0), ks.c_str(), best_ms, as.c_str()); } } } } for (size_t i = 0; i < split_at.size(); ++i) if (split_at[i] >= g.n_layers) { std::fprintf(stderr, "strata generate: --layer-split: layer %lld is past the last (%lld)\n", (long long) split_at[i], (long long) (g.n_layers - 1)); return 2; } // ---- the trimmed stage weights (see above): each card reloads only its own layers' dense weights. Nothing // holds a pointer into the old copies yet but the PLE's six layer-1 weights, which are wired again. if (trim) { auto reload = [&](int dev, int64_t lo, int64_t hi, void*& base, uint64_t& base_bytes, strata::core::WeightTable& table, strata::core::NativeDense& dense) -> bool { const strata::core::OnDevice on(dev); std::set sk = skip; for (int64_t l = 0; l < g.n_layers; ++l) if (l < lo || l >= hi) sk.insert(layer_rows[(size_t) l].begin(), layer_rows[(size_t) l].end()); uint64_t bytes = 0; if (!strata::core::WeightTable::pool_bytes(o.pack, bytes, err, &sk)) return false; dense.release(); // the process-wide range that `load` also reads may be stale from an earlier stage's // set_layer_range (an explicit split loads its later stages eagerly): reset it to ours strata::core::NativeDense::set_layer_range((int) lo, (int) hi); table = strata::core::WeightTable{}; cudaFree(base); base = nullptr; if (cudaMalloc(&base, bytes) != cudaSuccess) { cudaGetLastError(); err = "the trimmed weight arena could not be allocated"; return false; } base_bytes = bytes; return table.load(o.pack, base, bytes, err, &sk) && (o.native_dense_gguf.empty() || dense.load(o.native_dense_gguf, table, err, o.native_ple_key, lo, hi)); }; const int64_t before = trim_prefix[(size_t) g.n_layers]; std::string kept; // CUDA0 only: the later stages' trimmed weights are loaded by upstream's `late_weights` loop below // (which also verifies the split search's pricing), and this block runs before it - reloading them // here too would leave `native dense: already loaded`. { const int64_t lo = 0, hi = split_at.empty() ? g.n_layers : split_at[0]; const bool ok = reload(0, lo, hi, arena, pool_bytes, wt, native_dense) && (o.ple_gguf.empty() || wire_ple(wt)); if (!ok) { std::fprintf(stderr, "strata generate: layer split, CUDA0: its own layers' weights: %s\n", err.c_str()); return 1; } kept += std::string("CUDA0 ") + std::to_string(lo) + "-" + std::to_string(hi - 1) + " (" + std::to_string(trim_frees(lo, hi) >> 20) + " MiB freed)"; } std::fprintf(stderr, "strata generate: layer split: CUDA0 keeps only its own layers' dense weights " "(%.2f GiB in all): %s (the later cards trim in late_weights)\n", (double) before / 1073741824.0, kept.c_str()); } // the stage that runs a layer (0: CUDA0's) auto stage_of = [&](int64_t l) -> int { int st = 0; while (st < (int) split_at.size() && l >= split_at[(size_t) st]) ++st; return st; }; // the whole ranking, hottest first, before each stage takes its own layers' share: the resident RAM copy ranks // the experts no GPU holds over ALL the layers (with CUDA0's share alone, a copy that did not fit kept only layers // 0..K-1's experts and read every later layer's from the files) std::vector> profile_all; if (multi_gpu) { profile_all = profile; std::vector> mine; for (const auto& pr : profile) { const int st = stage_of(pr.first); (st == 0 ? mine : stages[(size_t) st - 1]->profile).push_back(pr); } profile.swap(mine); for (size_t i = 0; i < stages.size(); ++i) { stages[i]->lb = split_at[i]; stages[i]->le = i + 1 < stages.size() ? split_at[i + 1] : g.n_layers; } } // ---- `--layer-split auto` with the trim asked: THE STAGES' WEIGHTS, NOW THAT THE SPLIT IS KNOWN. Each later card // loads the dense weights of the layers it runs and nothing else (before this they loaded in the loop above, a // full copy per card: on the 4-way IQ3_S rig CUDA1 3650 expert slots, CUDA2 1241, CUDA3 533 and a 768-token prompt // chunk; carved 4608 / 2485 / 1772 and 6144). The search priced these arenas from the pack index (`stage_pool`). if (late_weights) for (size_t i = 0; i < stages.size(); ++i) { GpuStage& st = *stages[i]; const strata::core::OnDevice on(st.dev); size_t before = 0, total_b = 0; // what this stage's load really costs, against what the search priced cudaMemGetInfo(&before, &total_b); if (!load_stage_weights(st, st.lb, st.le, true)) return 1; size_t fb = 0, tb = 0; cudaMemGetInfo(&fb, &tb); { // under-pricing (past a few MiB of rounding) is what put layers on a card that could not hold them (#1238); a little over-pricing is // by design (a granule per matrix runs ~0.8% high). Past 5% the pricing has drifted from the loading. const uint64_t took = before > fb ? (uint64_t) (before - fb) : 0; const uint64_t priced = carve_bytes(st.lb, st.le); if (priced + (8ull << 20) < took || (priced > took && priced - took > took / 20)) { // 8 MiB: the card reports its free memory in 2 MiB steps std::fprintf(stderr, "strata generate: layer split, CUDA%d: WARNING the split search priced this " "stage's weights at %llu MiB, it took %llu MiB\n", st.dev, (unsigned long long) (priced >> 20), (unsigned long long) (took >> 20)); // which part drifted: the projections (priced next to what `load` allocated) or the rest const auto dm = carve_dense_memo.find(std::make_pair(st.lb, st.le)); const uint64_t dense_priced = dm != carve_dense_memo.end() ? dm->second : 0; std::fprintf(stderr, "strata generate: layer split, CUDA%d: projections priced %llu MiB, loaded %llu MiB; " "the rest priced %llu MiB, took %llu MiB\n", st.dev, (unsigned long long) (dense_priced >> 20), (unsigned long long) (st.dense.allocated_bytes() >> 20), (unsigned long long) ((priced - std::min(priced, dense_priced)) >> 20), (unsigned long long) ((took - std::min(took, (uint64_t) st.dense.allocated_bytes())) >> 20)); } } std::fprintf(stderr, "strata generate: layer split: CUDA%d holds its weights; %.2f GiB free (its session " "follows)\n", st.dev, (double) fb / 1073741824.0); } // ---- CUDA0's session, and the stages' sessions: sized to each device's own layer range (the carve). A // stage that runs [lb, le) carves only those layers' GDN rows and QSA pools - before the carve every stage // held all 48 layers' state whatever layers it ran, which is the same disease the chunked-QSA-prefill PR // fixed in llama.cpp: allocation sized by the whole model instead of the device's own work. { const strata::core::OnDevice on0(primary_device); // STRATA_PRIMARY_DEVICE (upstream: a literal 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; // STRATA_KV_GROW_ANY=1: also beside a resident RAM copy (the experts the cache gives up are read from the // file, as any expert outside the RAM budget) and beside helper caches (they hold other experts) const char* av = std::getenv("STRATA_KV_GROW_ANY"); const bool any = av != nullptr && av[0] == '1'; const bool on = asked && !multi_gpu && o.kv_resident <= 0 && !o.expert_profile.empty() && (any || (!o.resident_cpu_experts && !remote)) && o.expert_cache != 0 && strata::core::vmm_available() && // the batch slots carve their own K/V and --vram-elastic's cache is not one VMM range o.batch == 0 && !o.vram_elastic && o.peer_device < 0; if (asked && !on) std::fprintf(stderr, "strata generate: --kv-grow is off (one GPU, a profile, the whole K/V in VRAM, " "every expert in RAM, no --batch, --vram-elastic or --peer-device)\n"); 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; } if (strata::core::session_init(g, o.max_context, K, sbuf, ss, 0, hi0) == 0) { std::fprintf(stderr, "strata generate: session_init failed\n"); return 1; } if (g.n_qsa_layers() > 0 && ss.qsa_states[ss.qsa_primary()].kv_mode == 1) std::fprintf(stderr, "strata generate: KV streaming: %lld of %lld cells per QSA layer in VRAM, the K/V in " "%.2f GiB of pinned RAM\n", (long long) (ss.qsa_states[ss.qsa_primary()].n_slots * 4), (long long) o.max_context, (double) strata::core::qsa_kv_host_bytes() / 1073741824.0); // the PLE block above built everything but the history, which session_init has just carved ss.ple.hist = ss.ple_hist; // (#167) generate mode starts from an empty sequence, and nothing else zeroes this state before the prompt // path or the verifier reads it (--serve zeroes it per request when nothing is reused) strata::core::session_zero(ss, g, nullptr, main_cs); if (cudaDeviceSynchronize() != cudaSuccess) { std::fprintf(stderr, "strata generate: zeroing the session state failed\n"); return 1; } if (!o.ple_gguf.empty()) { if (!ss.ple.ready()) { std::fprintf(stderr, "strata generate: the PLE run is not ready after construction\n"); return 1; } std::fprintf(stderr, "strata generate: PLE on, table %llu rows of %s\n", (unsigned long long) ple_table.rows(), o.ple_gguf.c_str()); } } mem_mark("the session (KV, GDN state, PLE history)"); for (size_t i = 0; i < stages.size(); ++i) { GpuStage& st = *stages[i]; const strata::core::OnDevice on(st.dev); void* sbuf_s = nullptr; if (cudaMalloc(&sbuf_s, strata::core::session_bytes(g, o.max_context, K, st.lb, st.le)) != cudaSuccess || strata::core::session_init(g, o.max_context, K, sbuf_s, st.ss, st.lb, st.le) == 0) { std::fprintf(stderr, "strata generate: layer split, CUDA%d: the session state failed\n", st.dev); return 1; } const bool last = i + 1 == stages.size(); const strata::core::WeightRef* wo_s = st.wt.find("output.weight"); if (wo_s == nullptr || (last && !o.native_head_gguf.empty() && !st.head.load(o.native_head_shards, g.n_embd, wo_s->ne1, err))) { std::fprintf(stderr, "strata generate: layer split, CUDA%d head: %s%s\n", st.dev, wo_s == nullptr ? "output.weight is missing" : err.c_str(), wo_s == nullptr ? "" : vram_free_note().c_str()); return 1; } size_t fb = 0, tb = 0; cudaMemGetInfo(&fb, &tb); std::fprintf(stderr, "strata generate: layer split: CUDA%d holds its weights, session [%lld, %lld)%s; " "%.2f GiB free\n", st.dev, (long long) st.lb, (long long) st.le, last ? " and the head" : "", (double) fb / 1073741824.0); } // STRATA_PREFILL_SHORT_MAX= (per-length schedule, opt-in): a prompt read from position 0 with at most that // many tokens runs every layer on the last stage's GPU (Prefill::read_short), layers [0, split_at[0]) against a // scratch session there; that session's state is then restored into the first stage's session (short_read below). // Needs a two-way split whose last GPU holds every layer's dense weights (no --trim-stage-weights). const int64_t short_max = [] { const char* e = std::getenv("STRATA_PREFILL_SHORT_MAX"); return e ? (int64_t) std::atoll(e) : (int64_t) 0; }(); // STRATA_PREFILL_SHORT_MIN (default 1024): a smaller prompt keeps the split read (one GPU would stream every layer's experts) const int64_t short_min = [] { const char* e = std::getenv("STRATA_PREFILL_SHORT_MIN"); return e ? (int64_t) std::atoll(e) : (int64_t) 1024; }(); strata::core::SessionState short_ss; bool short_on = false; if (short_max > 0 && stages.size() == 1 && split_at.size() == 1) { GpuStage& st = *stages.back(); const strata::core::OnDevice on(st.dev); const int64_t cap = std::min(short_max, o.max_context); void* buf = nullptr; const strata::core::WeightRef* wk = st.wt.find("blk.1.ple_key.weight"); const strata::core::WeightRef* wv = st.wt.find("blk.1.ple_value.weight"); const strata::core::WeightRef* wnk = st.wt.find("blk.1.ple_norm_key.weight"); const strata::core::WeightRef* wnq = st.wt.find("blk.1.ple_norm_query.weight"); const strata::core::WeightRef* wnc = st.wt.find("blk.1.ple_norm_conv.weight"); const strata::core::WeightRef* wc = st.wt.find("blk.1.ple_conv1d.weight"); float* emb_dev = nullptr; float* scratch = nullptr; if (ss.ple.ready() && (!wk || !wv || !wnk || !wnq || !wnc || !wc)) { std::fprintf(stderr, "strata generate: STRATA_PREFILL_SHORT_MAX: CUDA%d has no PLE run to read layer 1 with (off)\n", st.dev); } else if (cudaMalloc(&buf, strata::core::session_bytes(g, cap, K, 0, split_at[0])) != cudaSuccess || strata::core::session_init(g, cap, K, buf, short_ss, 0, split_at[0]) == 0 || cudaMalloc((void**) &emb_dev, (size_t) strata::kernels::NG_N_EMBD * 4) != cudaSuccess || cudaMalloc((void**) &scratch, strata::core::ple_run_scratch_bytes()) != cudaSuccess) { (void) cudaGetLastError(); std::fprintf(stderr, "strata generate: STRATA_PREFILL_SHORT_MAX: no VRAM on CUDA%d for the scratch session (off)\n", st.dev); } else if (!ss.ple.ready()) { // (--no-ple: no PLE run on either side) strata::core::session_zero(short_ss, g, nullptr, nullptr); short_on = cudaDeviceSynchronize() == cudaSuccess; } else { short_ss.ple = ss.ple; // the table, the constants and the host row buffer are shared; the weights are this GPU's strata::kernels::PleWeights& w = short_ss.ple.w; if (!wk->quantized()) { w.key_bf16 = (const uint16_t*) wk->data; } else if (wk->data != nullptr) { w.key_codes = (const uint8_t*) wk->data; w.key_scales = (const float*) ((const uint8_t*) wk->data + wk->codes_bytes); } if (ss.ple.w.key_native_data != nullptr) { w.key_native_data = wk->native_data; w.key_native_type = wk->native_type; w.key_native_q8_1 = wk->native_q8_1; } w.value_bf16 = (const uint16_t*) wv->data; w.norm_key = (const float*) wnk->data; w.norm_query = (const float*) wnq->data; w.norm_conv = (const float*) wnc->data; w.conv1d_f16 = (const uint16_t*) wc->data; short_ss.ple.token = &short_ss.ple_token; short_ss.ple.prev = short_ss.ple_prev; short_ss.ple.hist = short_ss.ple_hist; short_ss.ple.emb_dev = emb_dev; short_ss.ple.scratch = scratch; strata::core::session_zero(short_ss, g, nullptr, nullptr); short_on = cudaDeviceSynchronize() == cudaSuccess; } if (short_on) { // the two weight slots read_short streams the first stage's layers through, held from here on const uint64_t sb = strata::prefill::Prefill::short_slot_bytes(st.wt, wt, split_at[0], lat_tab.latent ? lat_tab.dense.d_bytes() : 0, lat_tab.latent ? lat_tab.dense.u_bytes() : 0); void* slots[2] = {}; std::string se; if (sb == 0 || cudaMalloc(&slots[0], sb) != cudaSuccess || cudaMalloc(&slots[1], sb) != cudaSuccess || !st.sp.set_short_slots(slots[0], slots[1], sb, se)) { (void) cudaGetLastError(); short_on = false; std::fprintf(stderr, "strata generate: STRATA_PREFILL_SHORT_MAX: no weight slots on CUDA%d (%s) (off)\n", st.dev, sb == 0 ? "the first stage's weights cannot be streamed" : se.empty() ? "no VRAM" : se.c_str()); } else { std::fprintf(stderr, "strata generate: short prompts stream layers 0-%lld's weights through two slots of %.0f MiB on CUDA%d\n", (long long) split_at[0] - 1, (double) sb / 1048576.0, st.dev); } if (short_on) std::fprintf(stderr, "strata generate: short prompts (<= %lld tokens from position 0) read every layer on CUDA%d " "(STRATA_PREFILL_SHORT_MAX), layers 0-%lld in a scratch session of %lld cells\n", (long long) short_max, st.dev, (long long) split_at[0] - 1, (long long) cap); } } // --batch: every stage carves o.batch more sessions like its own (same layer range and context), one per // slot of the batch windows. Before the expert cache is sized, so `--expert-cache auto` leaves them room. // Recommend, never force: a count the engine cannot run is said and adjusted (or batching left off) - the // engine still starts and serves one request at a time. // --batch-mtp / STRATA_BATCH_MTP=1 (opt-in): a slot also verifies one MTP proposal per window. Recommend, never // force: when it cannot run it is said and left off (plain batching still starts); default off = exactly 0.1.39. // With a layer split the slots' drafters live on the LAST stage's GPU (where the solo drafter, the head and the final // residual rows are); the windows are the ones --batch runs, two rows per slot, through every stage. // --batch-groups: given as a number or auto, or (0.1.41) auto by default for a layer split with --batch >= 2. The // pipelined slot groups run neither --batch-mtp's drafts nor the batch adaptive tier (--adapt-async 1), so when one of // them is asked for and the groups were not given, the default is one group (batch_groups.hpp). Evaluated again // once the slots that fit are known, and BEFORE the --batch-mtp gate below, which must see the resolved number. auto batch_groups_for = [&](bool mtp_on) { strata::program::batch_groups::Input bin; bin.set = o.batch_groups_set; bin.auto_given = o.batch_groups_auto; bin.given = o.batch_groups; bin.batch = o.batch; bin.later_stages = (int) stages.size(); bin.batch_mtp = mtp_on; bin.adapt_async = o.adapt_async != 0; { const char* ms = std::getenv("STRATA_BATCH_MTP_SERIAL"); bin.mtp_serial = ms != nullptr && ms[0] != '\0' && ms[0] != '0'; } #if !defined(STRATA_USE_HIP) // NVIDIA, 2 cards: the pipelined groups by default (0.2.7); one serial group, the 0.2.1-0.2.6 default, with // STRATA_BATCH_GROUPS_NV_SERIAL=1 or STRATA_DEFAULTS=026 (batch_groups.hpp nv_serial_wanted) bin.nv_serial_faster = strata::program::batch_groups::nv_serial_wanted(std::getenv("STRATA_BATCH_GROUPS_NV_SERIAL"), strata::qwen_defaults_026()); #endif { const char* mp = std::getenv("STRATA_PIPED_MTP"); bin.mtp_piped = mp != nullptr && mp[0] != '\0' && mp[0] != '0'; } return strata::program::batch_groups::resolve(bin); }; // DFlash2 slot drafts (the default for --draft dflash2 with --batch; STRATA_BATCH_DF2=0 turns them off): every batch slot gets its own drafter (the pack, // embedding and draft head shared, its own K/V ring and buffers). A window carries each slot's token plus drafts only in the rows the active slots leave // spare, and a round with no spare row does no drafter work (the committed rows wait on the host and are replayed when spare rows return). Measured on 2x // A6000 (RESULTS-DF2MGPU.md section 3): +25% / +9% over no drafts at 2 / 3 active slots, level at 4, within 1.5% at 8 and with users joining and leaving. // They run through the serial windows (one group); a layer split whose slots would be pipelined in groups by default keeps its groups and its undrafted // slots (the pipelined groups carry no drafts), and so does an explicit --batch-groups above 1. One card: on with the explicit pair (STRATA_BATCH_DF2=1 forces them on). const bool batch_df2_wanted = [&] { const char* e = std::getenv("STRATA_BATCH_DF2"); const bool off = e != nullptr && e[0] == '0'; const bool forced = e != nullptr && e[0] != '0' && e[0] != '\0'; #if defined(STRATA_GPU_METAL) return false; // (no per-slot drafters on Metal: one card, and the Metal drafter has no clones) #endif if (off || !(o.draft == "dflash2" && !o.draft_auto && o.batch >= 2 && o.serve && !split_same)) return false; if (forced) return true; // an explicit --draft dflash2 with --batch N turns the slots' drafts on (the launcher sends that pair only when the user picks DFlash2; --draft auto and the MTP // draft layer are unchanged). On one card that is all; on a layer split only where the slots would run as one group (the pipelined groups carry no drafts) return stages.empty() || batch_groups_for(false).groups <= 1; }(); const char* batch_mtp_env = std::getenv("STRATA_BATCH_MTP"); bool batch_mtp = o.batch_mtp || (batch_mtp_env != nullptr && batch_mtp_env[0] != '\0' && batch_mtp_env[0] != '0') || batch_df2_wanted; if (batch_mtp) { // (--pipeline-windows is already off with --batch slots) const char* why = o.batch < 2 ? "it needs --batch 2 or more" : o.mtp.empty() && !batch_df2_wanted ? "it needs --mtp" : o.spec < 2 ? "it needs --spec T (T >= 2)" : split_same ? "it needs each stage of a layer split on its own GPU" : !o.serve ? "it needs --serve" : nullptr; // the groups it would run with (the default gives way to it: one group; a number or auto given pipelines; // STRATA_PIPED_MTP with one slot per group: the pipelined groups draft) if (why == nullptr && !stages.empty() && batch_groups_for(true).groups > 1 && !batch_groups_for(true).mtp_piped) why = batch_groups_for(true).mtp_dropped ? "a layer split with --batch pipelines the slots in groups by default and the pipelined groups run no slot " "drafts (4 streams on 2 GPUs: 25-30% faster than the serial MTP windows); --batch-groups 1 or " "STRATA_BATCH_MTP_SERIAL=1 keeps --batch-mtp with serial windows (fewer streams, or when prompts arrive " "rarely, it can be the faster choice)" : "it does not combine with --batch-groups (pipelined slot groups) yet"; // (a layer split with helper-GPU expert caches has not been run with slot drafters. --remote-expert-opt alone does // not count: its object is only made with a helper cache on CUDA0 (`remote_opt` below), so without one it does nothing) if (why == nullptr && !stages.empty() && remote_caches) why = "it is not run with helper expert caches on a layer split"; if (why != nullptr) { std::fprintf(stderr, "strata generate: WARNING: %s is off: %s\n", batch_df2_wanted ? "STRATA_BATCH_DF2 (the slots' DFlash2 drafts)" : "--batch-mtp", why); batch_mtp = false; } } // STRATA_PIPED_MTP (opt-in): --batch-mtp's proposals in the pipelined groups of a layer split, one slot per group; // each stage commits a group's window once the last stage has judged its proposals // (Verifier::batch_launch_rows / batch_commit_rows) bool piped_mtp = batch_mtp && !stages.empty() && batch_groups_for(true).mtp_piped; // (final once the slots that fit are known, below) // STRATA_PIPED_MTP=N: up to N proposals per slot and window (at most --spec - 1); the first always, each further // one while the draft layer is at least --spec-min-p sure of it, as the solo path extends its windows int pm_drafts = 0; if (piped_mtp) { pm_drafts = std::clamp(std::atoi(std::getenv("STRATA_PIPED_MTP")), 1, std::max(1, std::min(o.spec - 1, (int) strata::kernels::kVerifyNarrowT - 1))); } // The verifiers' window: the solo path's drafts (--spec rows), the plain batch windows (the slots) and, with // STRATA_PIPED_MTP, a group's rows: its slots, each its token and its proposals ((slots) * (1 + proposals), one slot // per group = at most --spec rows). A function, not a number: --batch (the slots that fit) and the groups are final // only after this point, at the verifiers' init, and the plain value must stay what it was there. auto batch_max_t = [&]() -> int { // (--batch-mtp and STRATA_PIPED_MTP draft with the draft layer's kernels, built for the narrow window: their windows // stay at most kVerifyNarrowT rows; only the plain batch windows are wide) if (batch_mtp && !piped_mtp) return (int) strata::kernels::kVerifyNarrowT; const int plain = std::max(o.spec, std::min(o.batch, (int) strata::kernels::kVerifyMaxT)); const int group_rows = (piped_mtp && o.batch_groups > 1 && o.batch > 0) ? std::min(strata::kernels::kVerifyNarrowT, (o.batch / o.batch_groups) * (1 + pm_drafts)) : 0; return std::max(plain, group_rows); }; // The most slots, up to n, whose windows hold at most kVerifyMaxT rows each: n itself up to that, more only as // pipelined groups on a layer split - the groups as resolved below (a number given, auto, or the default's one // group for --adapt-async 1), dividing the slots, each at most kVerifyMaxT, all at most one group's worth per // stage. (--batch-mtp: n, as before.) auto slots_in_windows = [&](int n) { const int cap = strata::kernels::kVerifyMaxT; if (batch_mtp || n <= cap) return n; const int asked = o.batch; for (; n > cap; --n) { o.batch = n; const int gr = batch_groups_for(batch_mtp).groups; if (!stages.empty() && gr > 1 && n % gr == 0 && n / gr <= cap && n <= cap * ((int) stages.size() + 1)) break; } o.batch = asked; return n; }; std::vector>> bslot_ss; if (o.batch != 0) { const int cap = strata::kernels::kVerifyMaxT; const char* off = !o.serve ? "it needs --serve" : o.batch < 2 ? "it needs 2 or more slots" : split_same ? "it needs each stage of a layer split on its own GPU" : nullptr; if (off != nullptr) { std::fprintf(stderr, "strata generate: WARNING: --batch %d is off: %s\n", o.batch, off); o.batch = 0; } else if (o.batch > cap && !batch_mtp) { const int n = slots_in_windows(o.batch); if (n < o.batch) { std::fprintf(stderr, "strata generate: WARNING: --batch %d: a batch window holds at most %d rows, so %d " "slots\n", o.batch, cap, n); o.batch = n; } } } // --batch-groups auto: the pipeline needs one group per GPU stage to keep every card busy (4 x R9700, 8 clients: // 90 tok/s in one group, 136 in 2, 166 in 4). The most groups, at most one per stage, that divide the slots. // The default (0.1.41: a layer split with --batch pipelines one group per stage; --batch-groups 1 opts out) gives // way to --batch-mtp and --adapt-async 1, which need the serial windows: one group, said once. int groups_said = 0; auto resolve_groups_auto = [&] { const auto r = batch_groups_for(batch_mtp); if (!r.from_auto) return; o.batch_groups = r.groups; if (groups_said == r.groups) return; // (the second call, once the slots that fit are known, says nothing new) groups_said = r.groups; if (r.serial == strata::program::batch_groups::Serial::TwoCardsSerialFaster) std::fprintf(stderr, "strata generate: --batch-groups auto: 1 group of %d slot%s - %s; --batch-groups %d asks for the " "pipelined groups\n", o.batch, o.batch == 1 ? "" : "s", strata::program::batch_groups::serial_what(r.serial), r.would_be); else if (r.serial != strata::program::batch_groups::Serial::None) std::fprintf(stderr, "strata generate: --batch-groups auto: 1 group of %d slot%s - %s does not run in pipelined " "groups; --batch-groups %d would pipeline them and turn it off\n", o.batch, o.batch == 1 ? "" : "s", strata::program::batch_groups::serial_what(r.serial), r.would_be); else std::fprintf(stderr, "strata generate: --batch-groups auto: %d group%s of %d slot%s\n", r.groups, r.groups == 1 ? "" : "s", o.batch / r.groups, o.batch / r.groups == 1 ? "" : "s"); }; if (o.batch > 0) resolve_groups_auto(); if (o.batch > 0 && o.batch_groups > 1 && (stages.empty() || o.batch % o.batch_groups != 0)) { std::fprintf(stderr, "strata generate: WARNING: --batch-groups %d needs a layer split and to divide --batch %d; " "one group\n", o.batch_groups, o.batch); o.batch_groups = 1; } if (o.batch > 0) { bslot_ss.resize(1 + stages.size()); int fit = o.batch; // the slots every stage could carve uint64_t bytes0 = 0; for (size_t k = 0; k < bslot_ss.size(); ++k) { const int dev = k == 0 ? 0 : stages[k - 1]->dev; const int64_t lo = k == 0 ? 0 : stages[k - 1]->lb; const int64_t hi = k == 0 ? (multi_gpu ? split_at[0] : -1) : stages[k - 1]->le; const strata::core::OnDevice on_k(dev); const uint64_t bytes = strata::core::session_bytes(g, o.max_context, K, lo, hi); if (k == 0) bytes0 = bytes; for (int b = 0; b < fit; ++b) { auto u = std::make_unique(); void* buf = nullptr; if (cudaMalloc(&buf, bytes) != cudaSuccess || strata::core::session_init(g, o.max_context, K, buf, *u, lo, hi) == 0) { cudaGetLastError(); if (buf != nullptr) cudaFree(buf); size_t fb = 0, tb = 0; cudaMemGetInfo(&fb, &tb); std::fprintf(stderr, "strata generate: WARNING: --batch %d: slot %d's session does not fit on CUDA%d " "(%.2f GiB each, %.2f GiB free); %d slot%s\n", o.batch, b, dev, (double) bytes / 1073741824.0, (double) fb / 1073741824.0, b, b == 1 ? "" : "s"); fit = b; break; } strata::core::session_zero(*u, g, nullptr, nullptr); bslot_ss[k].push_back(std::move(u)); } cudaDeviceSynchronize(); size_t fb = 0, tb = 0; cudaMemGetInfo(&fb, &tb); std::fprintf(stderr, "strata generate: --batch: %d slot sessions on CUDA%d (%.2f GiB each); %.2f GiB free\n", (int) bslot_ss[k].size(), dev, (double) bytes / 1073741824.0, (double) fb / 1073741824.0); } for (auto& v : bslot_ss) if ((int) v.size() > fit) v.resize((size_t) fit); // the same count on every stage if (fit < 2) { std::fprintf(stderr, "strata generate: WARNING: --batch is off: not two slot sessions fit (a smaller " "--max-context or KV streaming, --kv-resident, makes them smaller)\n"); bslot_ss.clear(); o.batch = 0; } else { const int n = slots_in_windows(fit); // (the slots that fit are held to kVerifyMaxT rows per group too) if (n < fit) { std::fprintf(stderr, "strata generate: WARNING: --batch: %d slot sessions fit, and a batch window holds " "at most %d rows, so %d slots\n", fit, (int) strata::kernels::kVerifyMaxT, n); for (auto& v : bslot_ss) v.resize((size_t) n); fit = n; } o.batch = fit; resolve_groups_auto(); // (the slots that fit may not be the ones asked for) if (o.batch_groups > 1 && o.batch % o.batch_groups != 0) o.batch_groups = 1; // the sessions' VRAM is the expert cache's: say what it costs (docs/BATCHING.md has the measured trade) std::fprintf(stderr, "strata generate: --batch %d: the slot sessions take %.2f GiB of VRAM on CUDA0 that the " "expert cache would otherwise hold\n", o.batch, (double) bytes0 * o.batch / 1073741824.0); } } // STRATA_PIPED_MTP is decided again now that the slots that fit and the groups are final. Recommend, never force: when // it cannot run it is said and left off, and --batch-mtp goes on as it would without it. if (piped_mtp) { const char* why = nullptr; char buf[160]; const char* sc = std::getenv("STRATA_BATCH_SELF_COMMIT"); if (o.batch < 2 || o.batch_groups <= 1) { std::snprintf(buf, sizeof buf, "it needs 2 or more pipelined groups and %d slot%s in %d group%s are left", o.batch, o.batch == 1 ? "" : "s", o.batch_groups, o.batch_groups == 1 ? "" : "s"); why = buf; } else if (sc != nullptr && sc[0] != '\0' && sc[0] != '0') { why = "it does not combine with STRATA_BATCH_SELF_COMMIT (the window would keep its rows itself)"; } else if ((o.batch / o.batch_groups) * (1 + pm_drafts) > (int) strata::kernels::kVerifyNarrowT) { std::snprintf(buf, sizeof buf, "a group's window would hold %d rows (%d slots x %d), more than %d", (o.batch / o.batch_groups) * (1 + pm_drafts), o.batch / o.batch_groups, 1 + pm_drafts, (int) strata::kernels::kVerifyNarrowT); why = buf; } if (why != nullptr) { std::fprintf(stderr, "strata generate: WARNING: STRATA_PIPED_MTP is off: %s\n", why); piped_mtp = false; } else { std::fprintf(stderr, "strata generate: STRATA_PIPED_MTP: %d pipelined group%s of %d slot%s draft up to %d MTP " "proposal%s per slot each window\n", o.batch_groups, o.batch_groups == 1 ? "" : "s", o.batch / o.batch_groups, o.batch / o.batch_groups == 1 ? "" : "s", pm_drafts, pm_drafts > 1 ? "s" : ""); } } // Secure MTP's CUDA0 allocations before the large host arena is registered with both CUDA contexts. // In particular WDDM can refuse the draft weights after mapping tens of GiB of host pages. strata::core::MtpDrafter mtp; #if defined(STRATA_HAVE_DFLASH2) strata::core::Dflash2Drafter df2; // --draft dflash2 bool use_df2 = false; std::vector> slot_df2; // STRATA_BATCH_DF2: one drafter per batch slot (shared pack, own ring) bool batch_df2 = false; // the slots draft with DFlash2 (set once the slot drafters are allocated) #else constexpr bool use_df2 = false; constexpr bool batch_df2 = false; #endif // the draft layer's geometry (the canonical model's MTP head), `static` because MtpDrafter keeps a reference; the batch // slots' draft-KV copies use this one too static const strata::core::ModelGeometry draft_geometry = strata::core::kCompiledGeometry; std::vector> slot_mtp; // KVA (0.2.7: opt-in with STRATA_KVA=1; unset is the exact 0.2.6 path): what only the engine knows. A layer split and // the batch slots read their prompts in pieces and in stages, which the one-device, one-cold-read rule of the // approximate prompt read cannot follow, so they stay on the exact path (and say so here, once). The draft layer // (MTP) keeps its window, whatever it is: a session KVA approximated tells it the first cell built from a real row // (the cell floor, set per request below) and every session KVA did not approximate attends exactly as with // STRATA_KVA=0. { const strata::prefill::KvaConfig& kc = strata::prefill::kva_config(); strata::prefill::KvaEngine& ke = strata::prefill::kva_engine(); if (kc.explicit_on && !strata::prefill::kKvaBackend) std::fprintf(stderr, "strata generate: STRATA_KVA is set, but this build has no state-only late-layer path; " "every prompt is read exactly\n"); if (kc.on) { if (multi_gpu) ke.blocked = "a layer split across GPUs"; else if (o.batch > 0) ke.blocked = "batch slots (--batch)"; else if (o.peer_device >= 0) ke.blocked = "a peer device (--peer-device)"; if (!ke.blocked.empty()) { if (kc.explicit_on) std::fprintf(stderr, "strata generate: KVA (the approximate late-layer prompt read) is off here: %s\n", ke.blocked.c_str()); } mtp.enable_cell_floor(kc.wants_cell_floor(ke, !o.mtp.empty() && o.spec >= 2)); } } // SHORT OF VRAM: THE DRAFT LAYER IS THE LAST THING TO GO. The layer (about 0.9 GiB), the native head, the draft head and a working cache beside the // prompt path's buffers must all fit after the slot sessions; on a card that cannot hold them (8 GB NVIDIA, 128K, 2 requests: 1.4 GiB free after // the sessions) the start used to stop at "no VRAM is left for the expert cache" or run out of memory in the head upload. Without the layer // the model still answers (the verify window drafts from the prompt alone): slower decode, a start that works. Not with DFlash2 (its own // block decides), a split, or STRATA_MTP_KEEP=1. // A LAYER SPLIT WALKS THE SAME STEP ON THE CARD THAT HOLDS THE DRAFTER (the last stage's, or CUDA0 with the drafter first): its free memory is read there, after its weights, session // and head are in. DFlash2 (its pack, its ring and buffers, its draft head) is dropped by the same rule on that card; the single card keeps it as before (its own block decides). { const bool split_walk_drafter = multi_gpu && !stages.empty() && std::getenv("STRATA_SPILL_OFF") == nullptr; if (!o.mtp.empty() && !use_df2 && (split_walk_drafter || (!multi_gpu && stages.empty())) && std::getenv("STRATA_MTP_KEEP") == nullptr && spill_discrete_gpu()) { std::error_code fec1, fec2; const uint64_t layer_b = (uint64_t) std::filesystem::file_size(std::filesystem::path(o.mtp) / "dense.bin", fec1) + (uint64_t) std::filesystem::file_size(std::filesystem::path(o.mtp) / "experts.bin", fec2); const strata::core::WeightRef* wo_mtp = wt.find("output.weight"); const uint64_t head_b = (!o.native_head_gguf.empty() && wo_mtp != nullptr) ? (uint64_t) wo_mtp->ne1 * (uint64_t) (g.n_embd / 256) * 176ull : 0; // Q5_K: 176 bytes per 256 values const int draft_dev = split_walk_drafter ? (last_st && !mtp_first ? last_st->dev : -1) : -1; uint64_t free_now = 0; { const strata::core::OnDevice on_draft(draft_dev); free_now = (uint64_t) strata::core::device_free_bytes(); } const uint64_t need = strata::program::split_walk::draft_layer_need_bytes(layer_b, head_b); // + the cache the loan needs (214 slots, 543 MiB) + what is allocated after it and the drafter beyond DFlash2 (measured: DFlash2 alone ends 391 MiB free, MTP 41 at the same cache) if (!fec1 && !fec2 && strata::program::split_walk::draft_layer_short(free_now, layer_b, head_b)) { const std::string card = split_walk_drafter ? "CUDA" + std::to_string(draft_dev < 0 ? 0 : draft_dev) + ": " : std::string(); std::fprintf(stderr, "strata generate: short of GPU memory: %s%.2f GiB is free, and the draft layer (%.2f GiB), the head (%.2f GiB) and a working cache " "need about %.2f GiB: this start runs without the draft layer (decode is slower; STRATA_MTP_KEEP=1 keeps it)\n", card.c_str(), (double) free_now / 1073741824.0, (double) layer_b / 1073741824.0, (double) head_b / 1073741824.0, (double) need / 1073741824.0); o.mtp.clear(); } } // DFlash2 alone (--draft-fallback none, what Auto passes) on a stage that cannot hold it: no drafter, said in one line, instead of a start that ends if (split_walk_drafter && df2_solo && !use_df2 && std::getenv("STRATA_MTP_KEEP") == nullptr && spill_discrete_gpu()) { std::error_code fec3; const uint64_t pack_b = (uint64_t) std::filesystem::file_size(o.draft_model, fec3); const strata::core::WeightRef* wo_df = wt.find("output.weight"); const uint64_t head_b = (!o.native_head_gguf.empty() && wo_df != nullptr) ? (uint64_t) wo_df->ne1 * (uint64_t) (g.n_embd / 256) * 176ull : 0; const int dev_df = last_st && !df2_first ? last_st->dev : -1; uint64_t free_df = 0; { const strata::core::OnDevice on_df(dev_df); free_df = (uint64_t) strata::core::device_free_bytes(); } const uint64_t need_df = strata::program::split_walk::dflash2_need_bytes(pack_b, head_b / 2); if (!fec3 && free_df > 0 && free_df < need_df) { std::fprintf(stderr, "strata generate: short of GPU memory: CUDA%d: %.2f GiB is free, and DFlash2 (%.2f GiB with its buffers and draft head) and a working cache need about " "%.2f GiB: this start runs without a drafter (decode is slower; STRATA_MTP_KEEP=1 keeps it)\n", dev_df < 0 ? 0 : dev_df, (double) free_df / 1073741824.0, (double) pack_b / 1073741824.0 + 0.45, (double) need_df / 1073741824.0); df2_solo = false; o.draft.clear(); o.draft_model.clear(); } } } if (!o.mtp.empty() || df2_solo) { // (df2_solo: o.mtp is empty and no MTP layer is loaded; only the DFlash2 block below runs) if (o.spec < 2) { std::fprintf(stderr, "strata generate: --mtp is ignored without --spec T (T >= 2)\n"); o.mtp.clear(); } if (!o.mtp.empty()) mtp.set_prompt_len((int64_t) o.tokens.size()); if (!o.mtp.empty()) { mtp.set_hnorm_per_stream(o.mtp_hnorm_stream); // --mtp-hnorm stream (opt-in), before any capture mtp.set_q4(o.mtp_q4 == "all" || o.mtp_q4 == "proj", o.mtp_q4 == "all" || o.mtp_q4 == "head"); // before load if (!o.mtp_draft_vocab.empty()) mtp.set_draft_vocab(o.mtp_draft_vocab); } // the draft layer is the canonical model's MTP head (512 experts) even when the target is pruned, // so it always sees the canonical geometry; `static` because MtpDrafter keeps a reference // with a layer split across GPUs the drafter reads the last stage's residual: it lives on that device const strata::core::OnDevice on_mtp(last_st && !mtp_first ? last_st->dev : -1); // --pipeline-windows 2: 8 rows (the chain runs on past the window in flight: its drafts, its bonus token and // the next window's drafts), and the round/step graphs carry the forcing kernel // (--lookup-max-t past kVerifyNarrowT: the drafter keeps kVerifyNarrowT rows, MtpDrafter::draft_long catches a // longer window up in parts) const int mtp_t = o.pipeline_windows >= 2 ? strata::kernels::kVerifyNarrowT : std::min(o.spec, (int) strata::kernels::kVerifyNarrowT); if (o.pipeline_windows >= 2) mtp.set_force_capture(true); if (!o.mtp.empty() && !mtp.load(o.mtp, draft_geometry, last_st && !mtp_first ? last_st->ss : ss, mtp_t, err, o.mtp_window)) { std::fprintf(stderr, "strata generate: %s%s%s\n", err.c_str(), vram_free_note().c_str(), vram_batch_hint(err, o.batch).c_str()); return 1; } if (!o.mtp.empty()) mtp.set_ple_session(&ss); #if defined(STRATA_HAVE_DFLASH2) if (o.draft == "dflash2") { const char* why = o.mtp.empty() && !df2_solo ? "it needs --mtp (the fallback) and --spec 2 or more" : !native_pack ? "it needs a native pack" : o.draft_auto && (!split_devs.empty() || o.batch > 0) ? "--draft auto (both drafters) is for one card and one request at a time; --draft dflash2 runs on a layer split" : o.pipeline_windows > 0 ? "it does not run beside --pipeline-windows (the MTP's speculative next window has no DFlash2 counterpart); --pipeline-windows 0" : o.draft_model.empty() ? "it needs --draft-model PACK (tools/dflash2_pack.py)" : nullptr; if (why == nullptr) { if (df2.load(o.draft_model, multi_gpu && last_st != nullptr && !df2_first ? last_st->dev : 0, err)) { use_df2 = true; // Per card class, from the measured A/Bs (notes-dflash2-p1.md, RESULTS-CONF.md 11-08; the numbers are in core/draft_cap.hpp): Strix Halo 8, Blackwell cc 12.0 with // at least 48 GB 8, other Blackwell 6; a 12 GB NVIDIA card is slower with DFlash2 than with the MTP at every cap but code, which only the user can know. // Recommend, never force: the window is capped for the card unless --draft-cap says otherwise, and a small NVIDIA card gets one plain line. cudaDeviceProp dp{}; if (cudaGetDeviceProperties(&dp, df2.device()) == cudaSuccess) { #if defined(STRATA_USE_HIP) const bool uma = strata::kernels::gfx_arch_is_gfx1151(dp.gcnArchName); #else const bool uma = false; #endif #if defined(STRATA_USE_HIP) const int cc_major = 0; #else const int cc_major = dp.major; #endif #if defined(STRATA_USE_HIP) const int cc_minor = 0; const size_t card_bytes = 0; #else const int cc_minor = dp.minor; const size_t card_bytes = dp.totalGlobalMem; #endif const int cap = o.draft_cap > 0 ? o.draft_cap : strata::core::dflash2_auto_cap(uma, cc_major, cc_minor, card_bytes); if (cap > 0 && o.spec > cap) { std::fprintf(stderr, "strata generate: --draft dflash2: windows capped at %d tokens (%s; --draft-cap N changes it)\n", cap, o.draft_cap > 0 ? "as asked" : "the width measured best on this card"); o.spec = cap; } #if !defined(STRATA_USE_HIP) if (o.draft_cap == 0 && strata::core::dflash2_small_nvidia(true, dp.totalGlobalMem)) std::fprintf(stderr, "strata generate: --draft dflash2: on a 12 GB NVIDIA card the MTP drafter was faster in most measurements " "(code prompts at a window of 6 gained 3%%); continuing as asked\n"); #endif } } else if (df2_solo) { std::fprintf(stderr, "strata generate: --draft dflash2 --draft-fallback none: %s. DFlash2 needs about 1.2 GiB of VRAM; there is no MTP to draft instead, so the start ends here%s\n", err.c_str(), vram_free_note().c_str()); return 1; } else { std::fprintf(stderr, "strata generate: --draft dflash2: %s. DFlash2 needs about 1.2 GiB of VRAM (the pack 0.76 GiB, its buffers and K/V ring " "0.25 GiB, a draft head 0.2 GiB); start with --vram-reserve-mib 1900 to keep it (the expert cache then gives up about 2.5%% " "of its experts to the CPU), or a smaller --max-context. The MTP drafts instead.\n", err.c_str()); } } else if (df2_solo) { std::fprintf(stderr, "strata generate: --draft dflash2 --draft-fallback none: DFlash2 is off here: %s; there is no MTP to draft instead, so the start ends here\n", why); return 1; } else { std::fprintf(stderr, "strata generate: --draft dflash2 is off: %s; the MTP drafts instead\n", why); } // DFlash2 did not start: the MTP drafts, with its own window (the wider --spec was DFlash2's), when --draft-mtp-spec names it if (!use_df2 && o.draft_mtp_spec_set && o.spec > o.draft_mtp_spec) o.spec = o.draft_mtp_spec; } if (batch_df2_wanted && batch_mtp) { // the slots' DFlash2 drafters: streams and buffers now (the cache is sized around them); the head binds later if (use_df2) { std::string e2; for (int b = 0; b < o.batch; ++b) { auto d = std::make_unique(); if (!d->clone_alloc(df2, e2)) { std::fprintf(stderr, "strata generate: STRATA_BATCH_DF2: slot %d drafter: %s%s\n", b, e2.c_str(), vram_free_note().c_str()); return 1; } slot_df2.push_back(std::move(d)); } batch_df2 = true; size_t fb = 0, tb = 0; cudaMemGetInfo(&fb, &tb); std::fprintf(stderr, "strata generate: STRATA_BATCH_DF2: %d slot drafters on CUDA%d (%.0f MiB of private K/V ring and buffers each, sharing the " "solo drafter's pack); %.2f GiB free there\n", (int) slot_df2.size(), df2.device(), (double) slot_df2.front()->vram_bytes() / 1048576.0, (double) fb / 1073741824.0); } else { std::fprintf(stderr, "strata generate: WARNING: STRATA_BATCH_DF2 is off: DFlash2 is not running\n"); batch_mtp = false; } } #endif if (batch_mtp && !batch_df2_wanted) { // Slot b's drafter lives where the solo drafter does (the guard above: the last stage's GPU), carved from the // LAST stage's slot-b session (bslot_ss.back(): stage 0's on one GPU): it borrows that session's context // length and RoPE table, which are on that device. Its PLE history is the first stage's slot session: PLE // runs on the first stage, as for the solo drafter (`mtp.set_ple_session(&ss)` above). for (int b = 0; b < o.batch; ++b) { auto d = std::make_unique(); // STRATA_PIPED_MTP: the slot's proposal is drafted as an asynchronous chain (chain_launch), so the // pipeline goes on while it runs: the chain graphs carry the forcing kernel (a no-op here) if (piped_mtp) d->set_force_capture(true); // (mtp_first: the solo drafter is on the first stage's card, so slot b's is carved from its first-stage session) strata::core::SessionState& slot_s = mtp_first ? *bslot_ss[0][(size_t) b] : *bslot_ss.back()[(size_t) b]; if (!d->load(o.mtp, draft_geometry, slot_s, o.spec, err, o.mtp_window, &mtp)) { std::fprintf(stderr, "strata generate: batch MTP slot %d: %s%s\n", b, err.c_str(), vram_free_note().c_str()); return 1; } d->set_max_drafts(piped_mtp ? pm_drafts : 1); // the serial windows verify one proposal per slot d->set_ple_session(bslot_ss[0][(size_t) b].get()); slot_mtp.push_back(std::move(d)); } if (!slot_mtp.empty()) { size_t fb = 0, tb = 0; cudaMemGetInfo(&fb, &tb); std::fprintf(stderr, "strata generate: --batch-mtp: %d slot drafters on CUDA%d (%.0f MiB of private K/V " "state and buffers each, sharing the solo drafter's weights); %.2f GiB free there\n", (int) slot_mtp.size(), mtp.device(), (double) slot_mtp.front()->vram_bytes() / 1048576.0, (double) fb / 1073741824.0); } } } // THE HEAD BEFORE THE CACHE, AND BEFORE THE ARENA. The expert cache takes what is free minus the reserve, so // everything allocated after it comes out of the reserve. The native head (~0.5 GB with IQ3_S) was loaded after // it and ate most of the 700 MiB: 128K IQ3_S ended with 30 MiB free, the driver paged, and a request stalled for // good at its first verify window. Loaded first, the cache is sized around it. #620: and before the expert // arena registers tens of GiB of host pages, like the drafter above - WDDM then refused the head's cudaMalloc on // a 16 GB card with the desktop on the iGPU ("native head upload: out of memory" with GiBs free). const strata::core::WeightRef* wo = wt.find("output.weight"); if (wo == nullptr) { std::fprintf(stderr, "strata generate: output.weight is missing\n"); return 1; } const int64_t n_vocab = wo->ne1; strata::core::NativeHead native_head; if (!o.native_head_gguf.empty() && !multi_gpu) { // a layer split's head is on its last stage const auto head_t0 = std::chrono::steady_clock::now(); if (!native_head.load(o.native_head_shards, g.n_embd, n_vocab, err)) { std::fprintf(stderr, "strata generate: %s%s%s\n", err.c_str(), vram_free_note().c_str(), vram_batch_hint(err, o.batch).c_str()); return 1; } std::fprintf(stderr, "strata generate: experimental native Q5_K head, %llu bytes, in %.1f s\n", (unsigned long long) native_head.weight_bytes(), std::chrono::duration(std::chrono::steady_clock::now() - head_t0).count()); } std::vector logits((size_t) n_vocab); mem_mark("the native head"); // what DFlash2's own draft head and logits will take when it binds (the MTP drafter's own bind_bytes when it is loaded; without the MTP // (--draft-fallback none) the same formula from the vocabulary file, which that drafter never read) // DF-05: with the MTP loaded and the same draft-head subset (the plain gather: no --mtp-q4 head, no repack) the DFlash2 shares the MTP's copy at bind // (STRATA_DF2_SHARE_HEAD_OFF=1: its own copy, the A/B), and the cache is sized without that second copy const bool df2_expect_share = !df2_solo && !strata::core::Dflash2Drafter::head_native() && !o.mtp.empty() && std::getenv("STRATA_DF2_SHARE_HEAD_OFF") == nullptr && o.mtp_q4 != "all" && o.mtp_q4 != "head" && std::getenv("STRATA_MTP_FULL_HEAD") == nullptr && std::getenv("STRATA_Q6_PACKED") == nullptr && std::getenv("STRATA_MTP_Q8_SM60") == nullptr && std::filesystem::exists(df2_vocab_path()); auto df2_offer_head = [&]() { // after mtp.bind, before df2.bind #if defined(STRATA_HAVE_DFLASH2) strata::core::MtpDrafter::DraftHeadView hv; if (!o.mtp.empty() && mtp.draft_head_view(&native_head, df2_vocab_path(), hv)) { strata::core::Dflash2Drafter::SharedHead sh; sh.rows = hv.rows; sh.vocab_dev = hv.vocab_dev; sh.vocab_host = hv.vocab_host; sh.n = hv.n; sh.type = hv.type; df2.share_head(sh); } #endif }; auto df2_head_bytes = [&]() -> int64_t { if (df2_expect_share) return 0; // (its logits are in the 48 MiB the callers add) if (strata::core::Dflash2Drafter::head_native()) return (int64_t) 7 * n_vocab * (int64_t) sizeof(float); // STRATA_DF2_HEAD=native: no pruned copy, the logits of every row if (!df2_solo) return (int64_t) mtp.bind_bytes(native_head.row_bytes(), n_vocab); int64_t bytes = (int64_t) std::min(o.spec, (int) strata::kernels::kVerifyNarrowT) * n_vocab * (int64_t) sizeof(float); if (FILE* f = std::fopen(df2_vocab_path().c_str(), "rb")) { std::fseek(f, 0, SEEK_END); const long size = std::ftell(f); std::fclose(f); if (size >= 4 && size % 4 == 0) bytes += (int64_t) (size / 4) * (int64_t) native_head.row_bytes() + (int64_t) size; } return bytes; }; float* d_logits = nullptr; if (cudaMalloc(&d_logits, (size_t) n_vocab * 4) != cudaSuccess) { (void) cudaGetLastError(); std::fprintf(stderr, "strata generate: the logits buffer failed%s\n", vram_free_note().c_str()); return 1; } bool prefill_head_alias_bound = false; const void* prefill_head_alias_at = nullptr; // where the head came back the first time if (o.prefill_head_alias) { const char* why = !o.serve ? "it needs --serve" : multi_gpu || !stages.empty() ? "it supports one GPU only" : o.batch > 0 ? "it does not support --batch" : o.pipeline_windows > 0 ? "it does not support --pipeline-windows" : o.short_read > 0 ? "it needs --short-read 0" : o.expert_cache != 1 && o.expert_cache >= 0 ? "it needs --expert-cache 1 or auto" : o.mtp.empty() ? "it needs --mtp" : !native_head.loaded() ? "it needs the native output head" : nullptr; if (why != nullptr) { std::fprintf(stderr, "strata generate: --prefill-head-alias is unavailable: %s\n", why); return 2; } if (!mtp.bind(wt, &native_head, nullptr, err)) { std::fprintf(stderr, "strata generate: --prefill-head-alias: %s\n", err.c_str()); return 1; } native_head.unload(); prefill_head_alias_bound = true; std::fprintf(stderr, "strata generate: --prefill-head-alias: the %llu-byte output head is prompt workspace\n", (unsigned long long) native_head.weight_bytes()); } // Create the additional contexts after MTP has secured CUDA0 memory, but // before the host arena maps its expert pages into their address spaces. for (int r = 1; r < 3; ++r) if (o.expert_cache_remote[(size_t) r] > 0 && !early_remote) { double free_gib = 0; if (!strata::core::RemoteExperts::preflight(remote_dev[r], free_gib, err)) { std::fprintf(stderr, "strata generate: %s\n", err.c_str()); return 1; } std::fprintf(stderr, "strata generate: CUDA%d context ready, %.2f GiB free before expert arena registration\n", remote_dev[r], free_gib); } // ---- the CPU expert pool // // R2.1: the experts are loaded into a RESIDENT ARENA by default. The mmap path is kept behind // `--mmap-experts` because it is the A/B arm, not because it is competitive. // // The reasoning is the review's C1 and it is now measured on both sides. `FileExpertSource` maps the 34 GB // file, and mapped file pages are the first thing the OS reclaims; the engine's rate then depends on whether // the standby list happens to hold `experts.bin`, which is why two consecutive runs of the SAME BINARY with // the SAME FLAGS measured 71.97 and 34.78 ms/token in the pool (7.54 vs 12.18 tok/s). The arena is // anonymous memory the engine owns, and the pool runs at 19.41 ms/token - 1.79x better than the warm mmap // and 3.7x better than the cold one. // // IT IS NOT PINNED, and that is reported rather than hidden: `cudaHostRegister` on 31.64 GiB fails with // "out of memory" (you cannot pin 34 of 63 GB) and the arena falls back to 4 KB anonymous pages. That is // fine for the CPU pool - which is all that exists today - and NOT fine for Phase 3, whose cache fills and // CPU/PCIe miss split need the GPU to DMA out of this arena. Read `note()` when that lands. // // The earlier "the arena does not fit" conclusion was WRONG and is worth recording: the failure was a stale // CUDA error left set by the failed `cudaHostRegister` and read later by `gr_read`'s launch check. See the // note in `pinned.cu`. strata::core::FileExpertSource src; bool io_pf_by_default = false; // the Linux file-tier defaults turned io prefetch on (no STRATA_IO_PREFETCH given) { // the card, and whether this build has code for it (a binary built for other GPUs fails at its first kernel // otherwise, after the whole expert arena has loaded) - before the arena starts loading int dev = 0; cudaDeviceProp p{}; const bool named = cudaGetDevice(&dev) == cudaSuccess && cudaGetDeviceProperties(&p, dev) == cudaSuccess; if (!named) cudaGetLastError(); const char* name = named && p.name[0] ? p.name : "(an unnamed GPU)"; #if defined(STRATA_USE_HIP) std::fprintf(stderr, "strata generate: GPU %d: %s (%s)\n", dev, name, named ? p.gcnArchName : "?"); #if defined(__linux__) // integrated gfx11 (kfd_quiet.hpp, LOAD): the hyper-connection check now, before the expert arena exists and before the warm // thread starts, instead of in Verifier::init after the 7.7 GiB expert cache was allocated (it then finds it done). Its // result depends on the card and STRATA_HC_SPLIT only (random weights, compared bit for bit), so it is the same here. if (named && strata::core::kfd_quiet::load_moves().hc_check_early) strata::kernels::fused_gr_check(); #endif // the first prompt's one-time hipBLAS library loads (about 2.5 s), done on a thread while the expert arena loads if (named) g_warm_thr = std::thread([dev] { strata::prefill::warm_gemm_libraries(dev); }); // (RDNA4's matrix-core prompt attention is the default since 148-amd: the engine says so once, at its first prompt; // STRATA_HIP_WMMA=0 turns it off.) #if defined(_WIN32) // #468 #461: which HIP runtime was loaded - the bundled one beside the exe, or an AMD driver's System32 copy if (HMODULE h = GetModuleHandleA("amdhip64_7.dll")) { char path[MAX_PATH] = {}; if (GetModuleFileNameA(h, path, MAX_PATH) > 0) { std::fprintf(stderr, "strata generate: HIP runtime %s\n", path); // #1261: the bundled runtime sits beside the exe, but Windows bound the import to another copy (the AMD // driver's, in System32, was seen with a different build): kernels of this engine can then fail // (hipErrorInvalidDeviceFunction in the prompt GEMMs). Said, not changed - the import is bound before main. char exe[MAX_PATH] = {}; if (GetModuleFileNameA(nullptr, exe, MAX_PATH) > 0) { std::string beside(exe); const size_t cut = beside.find_last_of("\\/"); beside = (cut == std::string::npos ? std::string() : beside.substr(0, cut + 1)) + "amdhip64_7.dll"; if (GetFileAttributesA(beside.c_str()) != INVALID_FILE_ATTRIBUTES && _stricmp(beside.c_str(), path) != 0) { std::fprintf(stderr, "strata generate: WARNING: the HIP runtime in use is not the bundled one beside " "the engine (%s): if prompts fail with hipErrorInvalidDeviceFunction, tell the " "maintainers with this log (#1261)\n", beside.c_str()); // #461: why the bundled one lost. Its imports (rocm_kpack.dll and the C++ runtime) must be beside the // exe too; LoadLibraryEx on it with the search limited to its own folder says what is missing (126 = // a dependency). A diagnostic only: the copy it loads is released at once and nothing is forced. SetLastError(0); HMODULE probe = LoadLibraryExA(beside.c_str(), nullptr, LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR | LOAD_LIBRARY_SEARCH_DEFAULT_DIRS); const DWORD le = probe != nullptr ? 0 : GetLastError(); if (probe != nullptr) FreeLibrary(probe); std::fprintf(stderr, "strata generate: the bundled runtime beside the engine %s (GetLastError %lu)%s\n", probe != nullptr ? "loads on its own" : "does NOT load", (unsigned long) le, le == 126 ? ": a DLL it imports is missing from the engine's folder (rocm_kpack.dll, " "msvcp140.dll, vcruntime140.dll, vcruntime140_1.dll); run START-HERE.bat " "again (0.1.40.3 and later copy them)" : ""); } } } } #endif #else std::fprintf(stderr, "strata generate: GPU %d: %s, compute capability %d.%d%s\n", dev, name, strata::cc_major_of(p.major), strata::cc_minor_of(p.minor), strata::emulated_cc() ? " (STRATA_EMULATE_CC: a test mode, the card is emulated)" : ""); #if !defined(STRATA_HIP_GFX906) && !defined(STRATA_GPU_METAL) // a CUDA toolkit mismatch; the gfx906 HIP build has no CUDART_VERSION { // #542: a build whose libcudart is older than its headers (a CUDA 13 kit with a dangling libcudart.so that // CMake resolved to the system's CUDA 12 one) reads cudaDeviceProp shifted - silently, and slowly int rt = 0; if (cudaRuntimeGetVersion(&rt) == cudaSuccess && rt / 1000 != CUDART_VERSION / 1000) std::fprintf(stderr, "strata generate: WARNING: this engine was compiled with CUDA %d.%d headers but " "loaded a CUDA %d.%d runtime (libcudart): GPU properties can read wrong and some " "kernels go unused. Rebuild it against one toolkit (cmake -DCUDAToolkit_ROOT=, with its libcudart.so present) (#542)\n", CUDART_VERSION / 1000, CUDART_VERSION % 1000 / 10, rt / 1000, rt % 1000 / 10); } #endif #endif const std::string e = strata::core::device_code_error(); if (!e.empty()) { std::fprintf(stderr, "strata generate: this engine has no code for %s (sm_%d%d): %s - rebuild it for this " "card (setup does: START-HERE.bat --setup)\n", name, p.major, p.minor, e.c_str()); return 1; } } strata::core::ArenaExpertSource arena_src; strata::core::ExpertSource* srcp = nullptr; // #4846 (owner 11-01): the arena first, and when the RAM is still short after the wait and the give-back, the --mmap-experts source // for this run (o.mmap_experts is set here, before anything below sizes the experts' tier from it; nothing was sized for the arena // by now: the PLE table's lock, priced against it, was just given back). A hand-set `--ple-io ram` and a shared arena file are kept // as asked (warn only), STRATA_ARENA_RAM_FALLBACK=0 is the old behaviour. Two passes at most; the second only after the first chose // the file, and if the file cannot be opened the arena is tried again the old way (a start never ends in a refusal for this). const bool ram_fallback_ok = strata::core::arena_ram_fallback_allowed( std::getenv("STRATA_ARENA_RAM_FALLBACK"), o.ple_io_explicit && o.ple_io == "ram", !o.shared_expert_arena.empty()); bool ram_fallback_taken = false, ram_fallback_failed = false, ram_fallback_resident = false; const bool ram_fallback_resident_off = [] { const char* v = std::getenv("STRATA_ARENA_FALLBACK_RESIDENT"); return v != nullptr && v[0] == '0'; }(); // The RAM-copy fallback leaves max(--ram-keep-gib, the safety headroom: 8 GiB on Windows, where the page trim of the copy needs the // room, 4 GiB elsewhere) free; STRATA_RESIDENT_HEADROOM_GIB, when set, decides instead. ple_residency.hpp. #if defined(_WIN32) constexpr bool kWindowsHost = true; #else constexpr bool kWindowsHost = false; #endif const uint64_t ram_fallback_headroom = [&] { std::optional env_headroom; if (const char* v = std::getenv("STRATA_RESIDENT_HEADROOM_GIB"); v != nullptr && std::atof(v) >= 0.0) env_headroom = (uint64_t) (std::atof(v) * 1073741824.0); return strata::core::fallback_headroom(env_headroom, o.ram_keep, strata::core::fallback_safety_headroom(kWindowsHost)); }(); for (bool again = true; again;) { again = false; if (o.mmap_experts) { // FileExpertSource maps the pack's experts.bin: a canonical pack has it; a native (IQ) pack has it when // built with `tools/iq_pack.py --experts-bin` (the per-layer blob sizes of its layout, PR #121). The low-RAM // mode: the experts come from the file through the OS cache instead of a pinned copy in RAM, for a PC whose // GPU holds most of them but whose RAM cannot hold them all. // CS-T: a native pack without experts.bin maps the model's GGUF shards instead (native_experts.txt's spans, // checked against the files first) - no 30-77 GB copy of the experts on the disk src.set_gguf(o.native_preset); if (const char* v = std::getenv("STRATA_FETCH_THREADS"); v != nullptr && std::atoi(v) > 0) src.set_fetch_threads(std::atoi(v)); if (!src.open(o.pack, g.n_layers, g.n_expert, err)) { if (ram_fallback_taken) { // #4846: the file cannot be opened either; the arena, loaded the old way, is what is left std::fprintf(stderr, "strata generate: the experts cannot be read from the file either (%s): loading the expert arena " "as before, short of RAM\n", err.c_str()); o.mmap_experts = false; if (ram_fallback_resident) { o.resident_cpu_experts = o.resident_pin = o.resident_soft = ram_fallback_resident = false; o.resident_budget = 0; } ram_fallback_taken = false; ram_fallback_failed = true; again = true; continue; } std::fprintf(stderr, "strata generate: %s\n", err.c_str()); return 1; } std::fprintf(stderr, "strata generate: experts via mmap (%s; %s)\n", ram_fallback_taken ? "not enough RAM for the expert arena: the same source as --mmap-experts" : "--mmap-experts", src.gguf_mode() ? "the GGUF shards in place, no experts.bin" : "the A/B arm of R2.1"); // #286: with a RAM budget the hottest experts live in it, and the rest are read from the drive unbuffered // when the file cache could not keep them beside the budget anyway (a 32 GB PC) - the mapped reads' page // faults are small requests on the critical path, and their pages take the RAM the budget was sized for // #773: without a RAM budget there is no RAM copy and the file cache IS the expert tier (measured on a // 32 GB, 2 x 16 GB rig: forcing unbuffered reads there re-read 163-629 GB from the drive and halved the // speed), so STRATA_UNBUFFERED_LOAD=1 is not honoured in that mode if (o.resident_budget > 0) { std::string why; const bool ub = src.set_unbuffered(o.resident_budget, why); std::fprintf(stderr, "strata generate: the file tier reads %s (%s)\n", ub ? "unbuffered" : "through the file cache", why.c_str()); } else if (const char* env = std::getenv("STRATA_UNBUFFERED_LOAD"); env != nullptr && env[0] != '\0' && env[0] != '0') { std::fprintf(stderr, "strata generate: the file tier reads through the file cache (STRATA_UNBUFFERED_LOAD=%s " "ignored: without --resident-budget-gib the file cache holds the experts)\n", env); } #if defined(_WIN32) // the GPU cache's fill and the RAM copy read unbuffered even so: through the mapping their pages sat in the // working set beside the copy (end_startup_unbuffered below, once the copy is built). Windows, experts.bin if (o.resident_cpu_experts && !src.unbuffered()) { std::string why; if (src.begin_startup_unbuffered(why)) std::fprintf(stderr, "strata generate: the GPU cache's fill and the RAM copy read unbuffered (%s)\n", why.c_str()); else if (why.find("STRATA_STARTUP_UNBUFFERED") == std::string::npos) std::fprintf(stderr, "strata generate: the GPU cache's fill and the RAM copy read through the mapping " "(%s)\n", why.c_str()); } #endif // Linux I/O path: whole-blob preads instead of page faults, and the predicted experts of the next layers read // ahead on I/O threads while the current layer computes (see FileExpertSource::set_io_prefetch). 0.2.0: on by // default on Linux, with the decode gate (STRATA_IO_PF_GATE) and zero-copy page-cached experts // (STRATA_COLD_OVERLAP=4); STRATA_IO_PREFETCH=0 / STRATA_IO_PF_GATE=0 / STRATA_COLD_OVERLAP=0 turn them off. // io prefetch + the gate: the GGUF read in place and (0.2.1) an experts.bin pack; zero-copy only for the GGUF in place const char* io_pf_env = std::getenv("STRATA_IO_PREFETCH"); const bool io_pf_default = (io_pf_env == nullptr || io_pf_env[0] == '\0') && src.linux_io_defaults(); #if defined(__linux__) if ((io_pf_env == nullptr || io_pf_env[0] == '\0') && !io_pf_default && !src.linux_file_defaults() && !src.unbuffered()) std::fprintf(stderr, "strata generate: file tier (experts.bin): io prefetch stays off by default here: the page cache has room " "for %.0f%% of the experts (it helps from 55%%: 32 GB-class RAM, decode +20..34%% measured); " "STRATA_IO_PREFETCH=1 turns it on anyway\n", src.cache_room_ratio() * 100.0); #endif if (io_pf_default || (io_pf_env != nullptr && std::atoi(io_pf_env) != 0)) { const char* th = std::getenv("STRATA_IO_PF_THREADS"); src.set_io_prefetch(true, th != nullptr ? std::atoi(th) : 0); io_pf_by_default = io_pf_default && src.io_prefetch(); if (src.io_prefetch() && io_pf_default) { const char* cv = std::getenv("STRATA_COLD_OVERLAP"); std::fprintf(stderr, "strata generate: file tier (Linux defaults, %s): page-cached experts " "computed from the mapping (STRATA_COLD_OVERLAP=%s), io prefetch with whole-blob preads on %s I/O threads, " "the decode's read-ahead %s; off: STRATA_COLD_OVERLAP=0, STRATA_IO_PREFETCH=0, " "STRATA_IO_PF_GATE=0\n", src.linux_file_defaults() ? "the GGUF read in place" : "experts.bin: its pages are read from the mapping as they are", cv != nullptr && cv[0] != '\0' ? cv : (src.linux_file_defaults() ? "4" : "0"), th != nullptr ? th : "8", src.gate_on() ? "only while the page cache has room for it and it pays (STRATA_IO_PF_GATE=1)" : "always (STRATA_IO_PF_GATE=0)"); } else if (src.io_prefetch()) std::fprintf(stderr, "strata generate: file tier io prefetch ON (STRATA_IO_PREFETCH=1): whole-blob preads, " "the layer's uncached experts and the predicted ones read by %s I/O threads (STRATA_IO_PF_THREADS, default 8)%s\n", th != nullptr ? th : "8", src.gate_on() ? "; the decode's read-ahead gated (STRATA_IO_PF_GATE=0: always)" : ""); if (src.io_prefetch() && src.io_sched()) std::fprintf(stderr, "strata generate: io prefetch scheduling ON (STRATA_IO_PF_SCHED=1): a deadline per read, " "confidence admission (STRATA_IO_PF_MINCONF), a per-window byte budget (STRATA_IO_PF_BUDGET_MB / _FRAC)\n"); if (!src.io_prefetch() && !io_pf_default) std::fprintf(stderr, "strata generate: STRATA_IO_PREFETCH=1 is not available here (Linux mapped file tier " "only, not with unbuffered reads); the file tier reads as before\n"); if (src.io_prefetch()) { // recommend, never force: the engine runs as asked const char* st = std::getenv("STRATA_IO_PF_STAGE"); if (st != nullptr && std::atoi(st) != 0) std::fprintf(stderr, "strata generate: note: STRATA_IO_PF_STAGE=1 (staging) measured faster only on a 32 GB-class " "box (+25%% on an RTX 3060, 32 GB); it was slower at 16 GB and on an iGPU (docs/DETAILS.md, file tier I/O)\n"); #if defined(STRATA_USE_HIP) int igpu_dev = 0; cudaDeviceProp igpu_p{}; if (cudaGetDevice(&igpu_dev) == cudaSuccess && cudaGetDeviceProperties(&igpu_p, igpu_dev) == cudaSuccess && igpu_p.integrated != 0 && o.adapt_every > 0 && o.adapt_swaps > 0) std::fprintf(stderr, "strata generate: WARNING: STRATA_IO_PREFETCH=1 with the adaptive tier on an AMD iGPU (%s): " "GPU resets were seen with this combination under memory pressure (Radeon 780M); " "--adapt-every 100000 avoided them. Continuing as asked.\n", igpu_p.gcnArchName); else (void) cudaGetLastError(); #endif } } else if (const char* sv = std::getenv("STRATA_IO_STATS"); sv != nullptr && std::atoi(sv) != 0) { src.set_io_stats(true); } srcp = &src; } else { arena_src.set_gguf(o.native_preset); // plan v0.3 P6: a native pack may take its experts from shard 1 // Under WDDM (Windows, WSL2), a multi-GPU run (a layer split, or remote experts) starts with at most 8 GiB of // mapped host pages: pinning all of it into two contexts leaves WDDM refusing every later allocation - // measured on the 5080 + 3090 rig: cudaMemGetInfo and the next cudaMalloc fail. Unregistered layers remain // in the resident arena; their streamed experts go through the pinned staging ring. A Linux driver has no // such limit, so there the whole arena is pinned (#253). STRATA_ARENA_PIN_GIB overrides both ways. const int pin_env = strata::core::arena_pin_cap_gib(); // -1 unset, -2 "auto" (#243, Windows sliced pin) const bool pin_wddm_cap = pin_env < 0 && (o.expert_cache_remote[0] > 0 || multi_gpu) && under_wddm(); const uint64_t pin_limit = pin_env >= 0 ? (uint64_t) pin_env << 30 : pin_wddm_cap ? (8ull << 30) : 0; if (pin_env >= 0) std::fprintf(stderr, "strata generate: STRATA_ARENA_PIN_GIB=%d: %s\n", pin_env, pin_env == 0 ? "the whole expert arena is pinned" : "the expert arena's pinning is capped"); else if (pin_wddm_cap) std::fprintf(stderr, "strata generate: multi-GPU under WDDM: at most 8 GiB of the expert arena is pinned " "(STRATA_ARENA_PIN_GIB changes it)\n"); // ---- STRATA_PIN_BY_NEED=1 (default off: the prefix pinning above, byte-identical). WDDM does not let the // pin grow past ~RAM/2, and the prefix spends it on layers 0-31 whatever the GPU holds: layers 32-47 stay 100 % // CPU while ~10 GiB of pinned blobs sit in GPU-resident experts no DMA ever reads. Pinning is registered // BEFORE the arena's pages are touched (pinned.cu), so the set must be chosen here, before arena_src.open: the // profile is already read, and the GPU cache's size - opened much later - is ESTIMATED from the same free-VRAM // reading its auto sizing uses (the weights, session and drafter are loaded by now, host registration takes no // VRAM): the first R ranked pairs are taken as GPU-resident, and the rest (then the unranked pairs, in layer // order) are what the arena pins, hottest first, until the driver refuses. R is under-estimated a little // (x0.98): a resident pair pinned by mistake costs a few MiB, a hot non-resident one skipped costs DMA. // STRATA_PIN_BY_NEED_SKIP= forces R. Single GPU, profile given, no helper caches only. std::vector> pin_cand; // the non-resident estimate, by decreasing rank, then the resident one size_t pin_nonres = 0; // (how many of them are the non-resident estimate) if (const char* pn = std::getenv("STRATA_PIN_BY_NEED"); pn != nullptr && pn[0] != '\0' && pn[0] != '0') { const char* off_why = profile.empty() ? "it needs --expert-profile (the ranking)" : multi_gpu || o.peer_device >= 1 ? "not with a layer split or a peer GPU" : std::any_of(o.expert_cache_remote.begin(), o.expert_cache_remote.end(), [](int n) { return n > 0; }) ? "not with helper caches on other GPUs" : nullptr; if (off_why != nullptr) { std::fprintf(stderr, "strata generate: pin by need: off (%s); the prefix pinning stays\n", off_why); } else { const auto& pl = strata::kernels::cpu::expert_layout(); size_t skip = profile.size(); if (const char* sk = std::getenv("STRATA_PIN_BY_NEED_SKIP"); sk != nullptr && sk[0] != '\0') { skip = std::min(profile.size(), (size_t) std::max(std::atoll(sk), 0)); } else { // the bytes the GPU cache will hold: --expert-cache N slots of the largest blob, or what auto sizing // finds free (the same reserve terms as "expert cache auto" below, without its small-card rescue, // which only ever grants MORE slots) uint64_t cap_bytes; if (o.expert_cache > 0) { cap_bytes = (uint64_t) o.expert_cache * nibble_max_slot_bytes(); } else { const int64_t pf_mib = (o.prefill_chunk > 0 && !pf_borrow) ? 160 + (o.prefill_chunk * 680) / 1024 : 0; int64_t mtp_b = (!o.mtp.empty() && native_head.loaded()) ? (int64_t) mtp.bind_bytes(native_head.row_bytes(), n_vocab) : 0; #if defined(STRATA_HAVE_DFLASH2) if (use_df2 && native_head.loaded()) mtp_b += df2_head_bytes() + (48 << 20) + (o.serve ? (112 << 20) : 0); // DFlash2's own draft head and logits (serve: and the prompt staging) #endif if (stages.empty()) for (const auto& d : slot_mtp) mtp_b += (int64_t) d->bind_bytes(native_head.row_bytes(), n_vocab); const int64_t pipe_b = o.pipeline_windows <= 0 ? 0 : (kPipeWindowMib << 20) + (o.pipeline_windows >= 2 ? 2 * (int64_t) gdn_snapshot_bytes(ss) : 0); const int64_t room = (int64_t) strata::core::device_free_bytes() - ((((int64_t) o.vram_reserve_mib + pf_mib) << 20) + mtp_b + pipe_b); cap_bytes = room > 0 ? (uint64_t) room : 0; } cap_bytes = cap_bytes / 100 * 98; uint64_t used = 0; skip = 0; for (const auto& pr : profile) { const uint64_t b = pl.native ? (nib::slot_bytes(pr.first) + 255) / 256 * 256 : (uint64_t) pl.max_blob; if (used + b > cap_bytes) break; used += b; ++skip; } } std::vector seen((size_t) (g.n_layers * g.n_expert), 0); for (const auto& pr : profile) if (pr.first >= 0 && pr.first < g.n_layers && pr.second >= 0 && pr.second < g.n_expert) seen[(size_t) (pr.first * g.n_expert + pr.second)] = 1; pin_cand.assign(profile.begin() + (long) skip, profile.end()); for (int64_t l = 0; l < g.n_layers; ++l) for (int64_t e = 0; e < g.n_expert; ++e) if (!seen[(size_t) (l * g.n_expert + e)]) pin_cand.emplace_back((int32_t) l, (int32_t) e); pin_nonres = pin_cand.size(); // (the report counts these) // what the cap leaves over goes to the pairs taken as GPU-resident (last in line): the adaptive tier // swaps them out as the conversation moves, and the prompt read streams whatever is not resident then pin_cand.insert(pin_cand.end(), profile.begin(), profile.begin() + (long) skip); std::fprintf(stderr, "strata generate: pin by need: %zu of the %zu ranked pairs taken as GPU-resident " "(STRATA_PIN_BY_NEED_SKIP= sets it), %zu candidates to pin\n", skip, profile.size(), pin_nonres); arena_src.set_pin_priority(pin_cand, pin_nonres); } } // The arena pins until the OS refuses; on Windows that leaves no page-locked memory for the small buffers the // engine allocates after it (the verify window's staging: "mapped staging allocation failed", exit 1). Keep a // reserve while the arena pins and hand it back after (pin_budget.hpp). if (ple_lock_by_policy) // #4846: the residency policy priced the table against the arena before the rest of the start took its RAM arena_src.give_back_ram = [&]() -> uint64_t { if (!ple_table.locked()) return 0; const uint64_t held = ple_table.table_bytes(); if (!ple_table.unlock()) return 0; strata::core::set_locked_own_file_bytes(0); ple_lock_by_policy = false; // (given back: the conversation cache's give-back has nothing left to do) return held; }; strata::core::pin_reserve_take(); arena_src.fall_back_when_ram_short = ram_fallback_ok && !ram_fallback_failed; arena_src.notices_on_stdout = o.serve; // #5327: the RAM notices also on stdout in --serve mode only arena_src.ram_keep_bytes = o.ram_keep; arena_src.hard_limit_headroom_bytes = ram_fallback_headroom; if (o.ram_keep > 0) std::fprintf(stderr, "strata generate: --ram-keep-gib %.2f: the expert arena is used only if %.2f GiB of RAM stay available after it; " "otherwise the RAM copy of the hottest experts leaves %.2f GiB free (the larger of that and the %.0f GiB safety headroom, " "STRATA_RESIDENT_HEADROOM_GIB decides when set)\n", (double) o.ram_keep / 1073741824.0, (double) o.ram_keep / 1073741824.0, (double) ram_fallback_headroom / 1073741824.0, (double) strata::core::fallback_safety_headroom(kWindowsHost) / 1073741824.0); const bool arena_ok = arena_src.open(o.pack, g.n_layers, g.n_expert, /*threads=*/6, err, pin_limit, o.shared_expert_arena); strata::core::pin_note_arena(arena_src.pinned_arena_bytes()); strata::core::pin_sim_report("after the expert arena"); strata::core::pin_reserve_release_soft(); if (!arena_ok && arena_src.ram_short()) { // one plain line, one next step; the numbers are in err. With --serve STDOUT TOO, not only stderr: a service // setup (llama-swap and its like) keeps the engine's stdout in its log and never shows the stderr this line // lived on, so the 2.4x decode loss this fallback costs was invisible until it was measured (#5327). A plain // generate run keeps its stdout (the token stream) clean: stderr only, as before. std::fprintf(stderr, "strata generate: not enough RAM for the expert arena (%s): this run reads the experts from the " "file, like --mmap-experts (slower; the answers are the same). To get the arena back, free that RAM " "and start again\n", err.c_str()); if (o.serve) { std::printf("strata generate: not enough RAM for the expert arena (%s): this run reads the experts from the " "file, like --mmap-experts (slower; the answers are the same). To get the arena back, free that RAM " "and start again\n", err.c_str()); std::fflush(stdout); } o.mmap_experts = true; ram_fallback_taken = true; // R5070: the plain file source has no RAM copy at all, and on the owner's 5070 PC (63.1 GB, 44.6 GiB available for a // 46.84 GiB arena) it decodes at 9-10 tok/s where a RAM copy of the hottest experts gives 27-28. The fallback // takes the --resident-experts form instead (the hottest experts by the profile in RAM as far as the available // RAM allows, the rest read from the files); needs the static expert profile, STRATA_ARENA_FALLBACK_RESIDENT=0 // keeps the plain file source. STRATA_RESIDENT_PIN=0 keeps the copy pageable, read as for the flags (it was not // read here before: the copy was page-locked whatever the variable said). if (!o.expert_profile.empty() && !o.resident_cpu_experts && !ram_fallback_resident_off) { const auto mode = strata::core::auto_ram_copy_mode(std::getenv("STRATA_RESIDENT_PIN")); o.resident_cpu_experts = mode.resident_cpu_experts; o.resident_pin = mode.pin; o.resident_soft = mode.soft; o.resident_headroom = ram_fallback_headroom; // the budget form (as --resident-budget-gib): the hottest experts in what is available minus the headroom, and the rest // read unbuffered, not through the mapped view (whose pages grow the working set until available RAM is near zero) if (const auto hm = strata::core::sample_host_memory(); hm) o.resident_budget = strata::core::fallback_budget(hm->available, o.resident_headroom); ram_fallback_resident = true; } again = true; continue; } if (!arena_ok) { std::fprintf(stderr, "strata generate: %s\n", err.c_str()); return 1; } if (!pin_cand.empty()) { const auto& pl = strata::kernels::cpu::expert_layout(); uint64_t cand_b = 0, pin_b = 0; for (size_t ci = 0; ci < pin_nonres; ++ci) { const auto& pr = pin_cand[ci]; const uint64_t b = pl.blob_bytes(pr.first); cand_b += b; if (arena_src.pinned(pr.first, pr.second)) pin_b += b; } int64_t pcie_layers = 0; for (int64_t l = 0; l < g.n_layers; ++l) pcie_layers += arena_src.pcie_layer(l) ? 1 : 0; std::fprintf(stderr, "strata generate: pin by need: %zu ranges, %.2f GiB pinned, %.1f %% of the non-resident " "experts (%lld of %lld layers have a PCIe share)\n", arena_src.pin_ranges(), (double) pin_b / 1073741824.0, cand_b > 0 ? 100.0 * (double) pin_b / (double) cand_b : 0.0, (long long) pcie_layers, (long long) g.n_layers); } if (!arena_src.ram_warning().empty()) // #633: said before the load's numbers, which it explains std::fprintf(stderr, "strata generate: WARNING: %s\n", arena_src.ram_warning().c_str()); std::fprintf(stderr, "strata generate: expert arena: %s\n", arena_src.note().c_str()); std::fprintf(stderr, "strata generate: loaded %.2f GiB at %.2f GiB/s\n", (double) strata::kernels::cpu::expert_layout().total / (1024.0 * 1024 * 1024), arena_src.load_gib_per_second()); #if defined(__linux__) // integrated gfx11 under Linux: the experts are in the arena now; the model files' cached pages are a second copy. The reads of // experts.bin gave theirs back as they went (drop behind); this is the call after it, for every file the start read: the arena's expert files, // the pack's dense.bin and embd.bin, the GGUF shards of --native (not the PLE table's: its rows are read directly). The weights, the native // projections and the head were loaded before the arena (engine log order); the PLE table is read from the drive on request. Advice only. if (strata::core::page_cache_drop::enabled()) { std::vector cached_files; for (const auto& kv : arena_src.model_inputs()) cached_files.push_back(kv.second); if (!o.pack.empty()) for (const char* n : {"dense.bin", "embd.bin"}) cached_files.push_back(o.pack + "/" + n); for (const std::string& s : o.native_shards) if (s != o.ple_gguf) cached_files.push_back(s); const auto outcome = strata::core::page_cache_drop::give_back(cached_files); const std::string line = strata::core::page_cache_drop::draft_line(outcome); if (!line.empty()) std::fprintf(stderr, "strata generate: %s\n", line.c_str()); } #endif // A rate under ~0.2 GiB/s is not the hardware. Task Scheduler / service contexts throttle this // read+fill about 24x (measured 0.05 vs 1.42 GiB/s for the same binary, args and cache state; the // scheduler's defaults - Below normal priority and a least-privilege token - were the only // difference between the runs). Say so instead of letting the user blame the disk; see // docs/DETAILS.md, "Running it at startup (Task Scheduler)". #ifdef _WIN32 // a Windows launch context; elsewhere a load this slow is the disk if (arena_src.load_gib_per_second() > 0.0 && arena_src.load_gib_per_second() < 0.2) { std::fprintf(stderr, "strata generate: hint: ~24x below what this hardware streams from a normal " "launch. If Strata is started by Task Scheduler or a service, register the task " "with Priority 4 (Normal) and 'Run with highest privileges' - the scheduler's " "defaults (Below normal + a least-privilege token) throttle the load. See " "docs/DETAILS.md ('Running it at startup').\n"); } #endif srcp = &arena_src; } } // the arena / file pass loop (#4846) // The picture reader's room in the resident RAM mode (strata/core/reader_room.hpp): there the cache refuses the server's VRAM // command, so an on-demand reader keeps its room in the reserve, as before the reader went on demand. Decided here, once, before // the cache is sized; the mode is not entered later. if (const int keep = strata::core::reader_room_reserve_mib(o.vram_reserve_mib, o.vision, o.vram_elastic && o.serve, o.resident_cpu_experts); keep != o.vram_reserve_mib) { std::fprintf(stderr, "strata generate: the resident RAM mode cannot resize the expert cache, so the picture reader's %d MiB " "stay in the reserve (%d MiB asked)\n", keep, o.vram_reserve_mib); o.vram_reserve_mib = keep; } #if defined(__linux__) // 0.1.43.1: on by default (STRATA_ADAPT_CALLBACK_WARMUP=0 turns it off). Linux threads inherit the creator's CPU mask, and // the host pins itself to one CPU later; a callback thread the driver creates lazily after that would run on the // host's CPU and fight the host's spin-wait (985 us instead of 4 us per callback, #1964 #1975). Windows CPU Sets are // per thread and not inherited. if (const char* e = std::getenv("STRATA_ADAPT_CALLBACK_WARMUP"); !(e && e[0] == '0')) { // The driver creates its host-callback thread lazily. Create it before ExpertPool pins this thread. if (cudaLaunchHostFunc(nullptr, [](void*) {}, nullptr) != cudaSuccess || cudaStreamSynchronize(nullptr) != cudaSuccess) { (void) cudaGetLastError(); std::fprintf(stderr, "strata generate: could not warm up the GPU host-callback thread (continuing)\n"); } else { std::fprintf(stderr, "strata generate: GPU host-callback thread started before host-core pinning\n"); } } #endif if (o.pool_measure) o.pool_affinity = measure_pool_affinity(srcp, o.pool_workers, !o.no_host_worker, o.pool_tasks); strata::kernels::cpu::ExpertPool pool(o.pool_workers, /*pin=*/true, /*host_works=*/!o.no_host_worker, o.pool_affinity, o.pool_tasks); std::fprintf(stderr, "strata generate: CPU pool tasks/phase: %d%s, participating threads: %d\n", o.pool_tasks ? o.pool_tasks : 3 * (pool.workers() + (pool.host_works() ? 1 : 0)), o.pool_tasks ? " (capped by rows)" : " (automatic)", pool.workers() + (pool.host_works() ? 1 : 0)); if (pool.plan_limit()[0] != '\0' && !pool.explicit_cores()) // the default count: what it was bounded by (a configured count is never changed; --pool-cores has its own line below) std::fprintf(stderr, "strata generate: CPU pool: %d workers by default (%d physical cores, %d logical processors; bounded by %s)\n", pool.workers(), pool.plan_cores(), pool.plan_logical(), pool.plan_limit()); if (srcp == &arena_src && strata::kernels::cpu::active_numa_split().on && !strata::kernels::cpu::active_numa_split().test) std::fprintf(stderr, "strata generate: NUMA split on, but this model's experts come from the arena path: memory is " "not placed per node (known limitation)\n"); if (pool.is_hybrid() && pool.affinity() != strata::kernels::cpu::PoolAffinity::All) { const char* aff_str = pool.affinity() == strata::kernels::cpu::PoolAffinity::PCores ? "p-cores" : pool.affinity() == strata::kernels::cpu::PoolAffinity::All ? "all" : "auto"; std::fprintf(stderr, "strata generate: hybrid CPU detected (%d P-cores / %d threads, %d E-cores), pool workers: %d, affinity: %s\n", pool.p_cores(), pool.p_threads(), pool.e_cores(), pool.workers(), aff_str); } { // where the threads run (--host-core) const strata::kernels::cpu::CpuTopology ht = strata::kernels::cpu::detect_cpu_topology(true, o.pool_affinity); // the pool's own order, not a fresh detection's: STRATA_NUMA_SPLIT interleaves the sockets const std::vector& wc = pool.worker_cores(); std::string on; for (int i = 0; i < pool.workers() && i < (int) wc.size(); ++i) on += (i > 0 ? "," : "") + std::to_string(wc[(size_t) i]); std::fprintf(stderr, "strata generate: %d pool workers on logical processors %s, the host thread on %d%s " "(--host-core %s)\n", pool.workers(), on.c_str(), ht.host_core, pool.host_works() ? " (draining too)" : "", strata::kernels::cpu::host_core_setting() == strata::kernels::cpu::HostCore::Last ? "last" : strata::kernels::cpu::host_core_setting() == strata::kernels::cpu::HostCore::Sibling ? "sibling" : "first"); // the same facts in plain words, and whether each worker has a physical core of its own std::fprintf(stderr, "strata generate: %s\n", pool.placement_line().c_str()); // --aux-cpus: the plan, now the workers' CPUs are known; the threads that exist already (the CUDA driver's) move // now when it is on, the ones created later pin themselves (strata/platform/aux_cpus.hpp) const size_t nw = std::min((size_t) pool.workers(), wc.size()); std::fprintf(stderr, "%s\n", strata::aux_cpus::set_topology(ht.host_core, std::vector(wc.begin(), wc.begin() + (long) nw)).c_str()); } if (o.no_ple_prefetch) strata::kernels::ple_prefetch_enable(false); // ---- R4's slot storage. Allocated AFTER the weights and the session, so `cudaMemGetInfo` inside `open` // sees the memory this process actually has left rather than the card's idle figure - and refuses with both // numbers if the slots do not fit, instead of handing back a cache smaller than it was asked for. mem_mark("the weights, the session and the drafter"); strata::core::ExpertCache xcache; // THE HEAD BEFORE THE CACHE: the native head and the logits are allocated above, before the expert arena (#620) const bool auto_cache = o.expert_cache < 0; bool reserve_adapted = false; // #496: the auto sizing lowered the reserve so a small card's cache fits // --pipeline-windows: what it allocates on CUDA0 after the cache (see kPipeWindowMib) const int64_t pipe_first = o.pipeline_windows <= 0 ? 0 : (kPipeWindowMib << 20) + (o.pipeline_windows >= 2 ? 2 * (int64_t) gdn_snapshot_bytes(ss) : 0); if (pipe_first > 0) std::fprintf(stderr, "strata generate: --pipeline-windows %d: %lld MiB of CUDA0 kept out of the expert cache " "(the second verifier%s)\n", o.pipeline_windows, (long long) (pipe_first >> 20), o.pipeline_windows >= 2 ? ", the GDN snapshots" : ""); // The MiB the prompt path's OWN buffers (no loan) take, which the cache sizing leaves out. 0.1.39's rule is // 160 + chunk * 680 / 1024 (~16 GiB at 24576 against ~2.4 GiB really allocated); STRATA_OWNED_PRICE=exact prices the // real allocation instead (Prefill::bytes_needed_owned: 2 MiB pages, the ring in one piece, as PR #796 measured) // and gives that cache the difference. A recommendation to try, so it is not the default. auto owned_prefill_mib = [&]() -> int64_t { if (!(o.prefill_chunk > 0 && !pf_borrow)) return 0; static const bool exact = [] { const char* v = std::getenv("STRATA_OWNED_PRICE"); return v != nullptr && std::string(v) == "exact"; }(); if (!exact) return 160 + (o.prefill_chunk * 680) / 1024; const int64_t mib = ((int64_t) strata::prefill::Prefill::bytes_needed_owned(g, ss, o.prefill_chunk, srcp != nullptr) + (1 << 20) - 1) >> 20; std::fprintf(stderr, "strata generate: STRATA_OWNED_PRICE=exact: the prompt path's own buffers for a %lld-token chunk: %lld MiB (the 0.1.39 rule: %lld MiB)\n", (long long) o.prefill_chunk, (long long) mib, (long long) (160 + (o.prefill_chunk * 680) / 1024)); return mib + 64; // a margin for the allocator }; // The prompt and verify paths share this pair, including with an explicit cache size. { std::string le; if (!lat_tab.load(g, le, 0, latent_trim ? split_at[0] : g.n_layers)) { std::fprintf(stderr, "strata generate: %s\n", le.c_str()); return 1; } } if (o.expert_cache < 0) { size_t free_b = 0, total_b = 0; free_b = strata::core::device_free_bytes(); (void) total_b; if (free_b == 0 && o.prefill_head_alias) { (void) cudaGetLastError(); free_b = strata::core::device_free_bytes(); } #if defined(STRATA_USE_HIP) && !defined(_WIN32) { // An integrated GPU's "free VRAM" is system RAM (the BIOS carve-out plus the GTT pool, nearly all of the RAM when the kernel was told // ttm.pages_limit), and the cache copies experts into that same RAM on top of the arena: sized from the pool alone it can ask for // more than the OS has left, and the OOM killer takes the engine or the desktop. So the AUTO size counts that RAM once: the // cache gets at most what the OS reports available less a reserve for the desktop (include/strata/core/uma_cache.hpp). // A recommendation: --expert-cache N is kept as asked, STRATA_UMA_RESERVE_GIB=0 gives the old sizing. cudaDeviceProp up{}; int ud = 0; strata::core::detail::HostMemory uh{}; if (cudaGetDevice(&ud) == cudaSuccess && cudaGetDeviceProperties(&up, ud) == cudaSuccess && up.integrated && strata::core::detail::host_available_memory(uh)) { const uint64_t reserve = strata::core::uma_desktop_reserve_bytes(strata::platform::total_physical_memory()); const uint64_t room = strata::core::uma_cache_room_bytes((uint64_t) uh.available, reserve); if (reserve > 0 && room < (uint64_t) free_b) { std::fprintf(stderr, "strata generate: expert cache auto: this GPU shares system RAM: %.2f GiB free on the GPU, but the OS has " "%.2f GiB available; %.2f GiB stay for the desktop, so the cache is sized from %.2f GiB " "(STRATA_UMA_RESERVE_GIB changes the reserve, --expert-cache N sets the cache)\n", (double) free_b / 1073741824.0, (double) uh.available / 1073741824.0, (double) reserve / 1073741824.0, (double) room / 1073741824.0); free_b = (size_t) room; } } else { (void) cudaGetLastError(); } } #endif // Plan v0.3 P5: the batched prompt path's chunk buffers are allocated later, so they are reserved here - // under WDDM an over-subscribed allocation does not fail, it pages to system memory and crawls. // (with borrowing - the default with a profile - the prompt path lends cache slots instead; `pf_borrow` is // the predicate a local `borrow` was here, hoisted above so both cache-size branches read the same one) // #1376: under WDDM the free figure read here runs high, and what is allocated after the cache (the verify // windows, the prompt path) comes out of the reserve. 0.1.40 ended a 20 GB RX 7900 XT with 2,170 MiB free // (its write-back check cut the cache); 0.1.40.2 passed that check with the default 700 MiB and ended with // 323 MiB, where Windows paged and decode fell from 52 to 21-25 tok/s. --vram-reserve-mib 2600 fixed it. So on // Windows HIP an auto cache on a card of 16 GB (15 GiB and up, #1709) keeps a floor of kWddmAutoReserveMib. CUDA on Windows is // left as it was: the same 0.1.40 / 0.1.40.2 pair on an RTX 5070 ended with the same slots and free VRAM, and a // floor there would only cost 16 GB+ NVIDIA cards ~1.8 GiB of cache. A reserve given on the command line is // kept as it is; a smaller card keeps its own sizing (#496 lowers the reserve further when the cache would not // fit); and this is said, never silent. The cache size changes no output bit. constexpr int kWddmAutoReserveMib = 2560; if (!o.vram_reserve_given && o.vram_reserve_mib < kWddmAutoReserveMib) { #if defined(_WIN32) && defined(STRATA_USE_HIP) size_t fb_now = 0, tb_now = 0; // #1709: a 16 GB card (RX 9070 XT, 7800 XT) reports 15.9 GiB, just under 16: the floor is for 15 GiB and up // G16: and for a DISCRETE card only. An integrated GPU (the device property, as the UMA sizing above reads it) shares the RAM with the budget's // page-locked complement, which takes the freed room straight back: on a Strix Halo the floor left UD-Q4_K_XL no room for the prompt path (wddm_auto_reserve_mib) cudaDeviceProp fl_prop{}; int fl_dev = 0; const bool fl_integrated = cudaGetDevice(&fl_dev) == cudaSuccess && cudaGetDeviceProperties(&fl_prop, fl_dev) == cudaSuccess && fl_prop.integrated != 0; if (cudaMemGetInfo(&fb_now, &tb_now) == cudaSuccess && strata::core::wddm_auto_reserve_mib(fl_integrated, (uint64_t) tb_now, o.vram_reserve_mib, kWddmAutoReserveMib) == kWddmAutoReserveMib) { std::fprintf(stderr, "strata generate: expert cache auto: Windows keeps %d MiB free after the cache on a card " "this size (the default %d MiB left 323 MiB on a 20 GB card and Windows paged, #1376); " "--vram-reserve-mib N sets it\n", kWddmAutoReserveMib, o.vram_reserve_mib); o.vram_reserve_mib = kWddmAutoReserveMib; } #endif } const int64_t prefill_mib = owned_prefill_mib(); // the draft layer's head and logits are allocated when it binds, after this: 0.1.27's CJK subset made them // ~110-180 MiB larger, and out of the reserve they left 16 GB cards below the stall line (#199) int64_t mtp_bind = (!o.mtp.empty() && native_head.loaded()) ? (int64_t) mtp.bind_bytes(native_head.row_bytes(), n_vocab) : (mtp_first && last_st->head.loaded()) ? (int64_t) mtp.bind_bytes(last_st->head.row_bytes(), n_vocab) : 0; // (with a layer split the slot drafters bind on the last stage, whose cache is sized from what is free there) if (stages.empty()) for (const auto& d : slot_mtp) mtp_bind += (int64_t) d->bind_bytes(native_head.row_bytes(), n_vocab); #if defined(STRATA_HAVE_DFLASH2) if (use_df2 && native_head.loaded()) mtp_bind += df2_head_bytes() + (48 << 20) + (o.serve ? (112 << 20) : 0); // DFlash2's own draft head and logits (serve: and the prompt staging), bound after this #endif const int64_t reserve = (((int64_t) o.vram_reserve_mib + prefill_mib) << 20) + mtp_bind + pipe_first; const int64_t blob = (int64_t) nibble_max_slot_bytes(); // max_blob (STRATA_EXPERT_NIBBLE: or a larger 4-bit slot) // #496: the least a working cache needs (the verify window cannot start without one, #174): a cache too small to lend the prompt path a // 256-token chunk's buffers (plus the 128 slots a loan leaves; one slot without --prefill) makes it allocate its own on top int64_t min_slots = (o.prefill_chunk > 0 && pf_borrow) ? ((int64_t) strata::prefill::Prefill::bytes_needed(g, ss, 256) + blob - 1) / blob + g_lend_keep : 1; // #4474: what the load allocates after the cache that no setting prices (cuBLAS and the lazily loaded modules the prompt path and the // verifier warm up, ~245 MiB on every card measured) came out of the reserve, so a card ended 240 MiB under the reserve it was asked to // keep (459 MiB free at --vram-reserve-mib 700: under the 512 MiB line the serve check warns about, #2065). The cache now leaves it too. // Not on a card that could not keep min_slots after it, and not under STRATA_DEFAULTS=026 (the v0.2.6 sizing). strata::core::AutoCacheSlots auto_slots = strata::core::auto_cache_slots( (int64_t) free_b, reserve, blob, min_slots, strata::qwen_defaults_026() ? 0 : strata::core::kLateAllocMib); int64_t slots = auto_slots.slots; if (!profile.empty()) slots = std::min(slots, (int64_t) profile.size()); #if defined(STRATA_GPU_METAL) // Metal: the decode window reads its experts from its own arena (metal/src/engine/window.cpp), and the device copies the shared host // code makes - this cache included - are given back before the arena is sized. An auto cache of everything that is "free" (14.56 GiB on // a 32 GB Mac) only held the memory the arena and the prompt buffers need, left 85 MiB free at the first request, and was touched // again after it was given back. 1500 slots is the cache the identity gates run with; --expert-cache N sets another. constexpr int64_t kMetalAutoCacheSlots = 1500; if (slots > kMetalAutoCacheSlots) { std::fprintf(stderr, "strata generate: expert cache auto: %d slots, not %lld: on a Mac the engine reads its experts from its own arena and " "this cache would only hold memory the arena and the prompt buffers need (--expert-cache N sets it)\n", (int) kMetalAutoCacheSlots, (long long) slots); slots = kMetalAutoCacheSlots; } #endif o.expert_cache = (int) std::max(slots, 0); std::fprintf(stderr, "strata generate: expert cache auto: %.2f GiB free, %d MiB reserved (+%lld MiB for the " "draft head%s) -> %d slots\n", (double) free_b / 1073741824.0, o.vram_reserve_mib, (long long) (mtp_bind >> 20), auto_slots.late_priced ? ", +256 MiB for what is allocated after the cache" : "", o.expert_cache); #if defined(STRATA_USE_HIP) && !defined(_WIN32) // An APU's "VRAM" is system RAM: the device-free figure above counts the whole GPU-addressable pool and does not // subtract ordinary CPU allocations (the host expert arena), so a cache sized from it alone can ask the OOM killer // for nearly all RAM (PR #895). A warning, not a cap: the cache stays as asked, and --expert-cache N chooses. { cudaDeviceProp apu_prop{}; int apu_dev = 0; strata::core::detail::HostMemory hm{}; if (cudaGetDevice(&apu_dev) == cudaSuccess && cudaGetDeviceProperties(&apu_prop, apu_dev) == cudaSuccess && apu_prop.integrated && strata::core::detail::host_available_memory(hm)) { const int64_t host_headroom = (int64_t) strata::core::uma_desktop_reserve_bytes(strata::platform::total_physical_memory()); // the OS, the desktop and request-time CPU work const int64_t cache_b = (int64_t) o.expert_cache * blob; if (cache_b > (int64_t) hm.available - host_headroom) std::fprintf(stderr, "strata generate: WARNING: this GPU shares system RAM, and the cache above (%.2f GiB) is " "more than the host memory available now (%.2f GiB) less 4 GiB for the OS: the system may " "run out of memory; --expert-cache N sets the cache by hand\n", (double) cache_b / 1073741824.0, (double) hm.available / 1073741824.0); } } #endif // SHORT OF VRAM: A LOAN THAT LEAVES LESS. The prompt path borrows cache slots for its buffers and the cache keeps 128 behind; a card whose cache stays smaller // than that (8 GB NVIDIA, 128K: 112-212 slots) used to be squeezed by lowering the reserve to give the cache its 326 working slots, which left 100 MiB // free and stopped the first long prompt ("mmq: out of memory"), or gave the prompt path its own 600 MiB of buffers on top and stopped with "do not // fit". The loan may leave 16 slots instead: the cache is smaller, prompts are read in smaller chunks and slower, the reserve stays, and the start works. if (o.prefill_chunk > 0 && pf_borrow && o.prefill_auto && o.expert_cache < min_slots && !o.vram_reserve_given && std::getenv("STRATA_SPILL_OFF") == nullptr && spill_discrete_gpu()) { constexpr int64_t kTightKeep = 16; const int64_t tight_min = ((int64_t) strata::prefill::Prefill::bytes_needed(g, ss, 256) + blob - 1) / blob + kTightKeep; if (tight_min < min_slots) { std::fprintf(stderr, "strata generate: short of GPU memory: the cache (%d slots) is too small to lend the prompt path 256-token buffers and keep %lld more: " "the loan keeps %lld, prompts are read in smaller chunks, expect them to be slower\n", o.expert_cache, (long long) min_slots, (long long) kTightKeep); min_slots = tight_min; g_lend_keep = kTightKeep; auto_slots = strata::core::auto_cache_slots((int64_t) free_b, reserve, blob, min_slots, strata::qwen_defaults_026() ? 0 : strata::core::kLateAllocMib); int64_t s3 = auto_slots.slots; if (!profile.empty()) s3 = std::min(s3, (int64_t) profile.size()); o.expert_cache = (int) std::max(s3, 0); } } // #496: the verify window cannot start without a cache (#174), and a cache too small to lend the prompt path // a 256-token chunk's buffers (plus the 128 slots a loan leaves; one slot without --prefill) makes it // allocate its own on top - more than the reserve. When the default reserve leaves less than that (a 6 GB // card), the reserve shrinks to what leaves exactly that cache, down to kSmallReserveMib: what is allocated // after the cache - the prompt path's own part, the verify buffers, the draft head - comes out of the reserve, // and below ~550 MiB a card ends with less than the 256 MiB the serve check calls LOW (IQ3_XXS, 32K, a 300 MiB // reserve: 5 MiB left), so the cache gets no more than it needs, and the serve check says so plainly when it // ends LOW (`reserve_adapted`). A reserve given on the command line is kept. No slot at all: the start // stops, saying what is short and what makes room. A card the default reserve leaves that much is sized as // before. constexpr int kSmallReserveMib = 300; if (o.expert_cache < min_slots && !o.vram_reserve_given && o.vram_reserve_mib > kSmallReserveMib) { // the largest reserve (in MiB) that still leaves min_slots const int64_t fit_mib = ((int64_t) free_b - mtp_bind - pipe_first - min_slots * blob) / (1 << 20) - prefill_mib; if (fit_mib >= kSmallReserveMib) { const int r = (int) std::min(fit_mib, o.vram_reserve_mib); int64_t s2 = ((int64_t) free_b - ((((int64_t) r + prefill_mib) << 20) + mtp_bind + pipe_first)) / blob; if (!profile.empty()) s2 = std::min(s2, (int64_t) profile.size()); std::fprintf(stderr, "strata generate: expert cache auto: the %d MiB reserve leaves too few slots on " "this card (a working cache needs %lld): a %d MiB reserve instead -> %lld slots\n", o.vram_reserve_mib, (long long) min_slots, r, (long long) s2); o.vram_reserve_mib = r; o.expert_cache = (int) s2; reserve_adapted = true; } } // SHORT OF VRAM: THE PROMPT PATH GETS ITS OWN SMALL BUFFERS, NOT A LOAN. A cache below min_slots cannot lend the prompt path its chunk, so the // path allocates its own buffers after the cache, and nothing above priced them: the cache took what was left, and the first prompt (or the // verify arena, or DFlash2's staging) stopped with "do not fit" (8 GB NVIDIA, 128K, 2 requests: a 74-slot cache and 35 MiB left). Price them // here instead, at the largest chunk that still leaves a cache (1024, 512, 256 tokens), and give the cache the rest: slower (a smaller // cache, smaller prompt chunks), never a refused start. Not with a split, a cache or chunk given on the command line, or STRATA_SPILL_OFF=1. if (auto_cache && pf_borrow && o.prefill_auto && !o.vram_reserve_given && o.expert_cache < min_slots && !profile.empty() && std::getenv("STRATA_SPILL_OFF") == nullptr && spill_discrete_gpu()) { constexpr int64_t kSpillFloorMib = 100; // the verify arena, the head check and the cuBLAS workspace beside the late allocations int64_t pick_chunk = 0, pick_slots = 0, pick_own = 0, pick_late = 0; for (const int64_t c : {(int64_t) 1024, (int64_t) 512, (int64_t) 256}) { const int64_t own = ((int64_t) strata::prefill::Prefill::bytes_needed_owned(g, ss, c, srcp != nullptr) >> 20) + 64; const int64_t late = strata::qwen_defaults_026() ? 0 : (int64_t) strata::core::kLateAllocMib; const int64_t room = (int64_t) free_b - mtp_bind - pipe_first - ((own + late + kSpillFloorMib) << 20); const int64_t s = room > 0 ? std::min(room / blob, (int64_t) profile.size()) : 0; if (s >= 64 || (s >= 1 && pick_slots < 64)) { pick_chunk = c; pick_slots = s; pick_own = own; pick_late = late; } if (s >= 64) break; } if (pick_slots >= 1) { std::fprintf(stderr, "strata generate: short of GPU memory: the cache cannot lend the prompt path its buffers, so the prompt path keeps its own " "(%lld MiB for %lld-token chunks) and the cache is %lld slots (%lld MiB): more is read from RAM and the SSD, expect it to be slower\n", (long long) pick_own, (long long) pick_chunk, (long long) pick_slots, (long long) ((pick_slots * blob) >> 20)); o.expert_cache = (int) pick_slots; o.vram_reserve_mib = (int) (pick_own + pick_late + kSpillFloorMib); o.no_prefill_borrow = true; pf_borrow = false; o.prefill_auto = false; o.prefill_chunk = pick_chunk; reserve_adapted = true; } } // SHORT OF VRAM: THE OUTPUT HEAD ON THE HOST, LAST. When every step above left the cache no slot (4 requests at 128K on an 8 GB card: the sessions and the weights // leave 0.63 GiB after the head, and the cache needs 543 MiB beside a reserve), the head (0.41 GiB) moves to mapped pinned host memory and every logits row reads it // over PCIe: decode is about 3x slower (12.7 against 36.1 tok/s per user, 2 requests on a 12 GB mimic), but the start works. Only a card that would otherwise // refuse; STRATA_HEAD_HOST_OFF=1 keeps the refusal. if (o.expert_cache == 0 && native_head.loaded() && !native_head.on_host() && !o.vram_reserve_given && !multi_gpu && stages.empty() && std::getenv("STRATA_HEAD_HOST_OFF") == nullptr && std::getenv("STRATA_SPILL_OFF") == nullptr && spill_discrete_gpu()) { std::string herr; if (native_head.to_host(herr)) { free_b = strata::core::device_free_bytes(); strata::core::AutoCacheSlots a2 = strata::core::auto_cache_slots((int64_t) free_b, reserve, blob, min_slots, strata::qwen_defaults_026() ? 0 : strata::core::kLateAllocMib); int64_t s4 = a2.slots; if (!profile.empty()) s4 = std::min(s4, (int64_t) profile.size()); if (s4 < min_slots && o.vram_reserve_mib > kSmallReserveMib) { // the reserve lowered for the smaller cache, as above const int64_t fit_mib = ((int64_t) free_b - mtp_bind - pipe_first - min_slots * blob) / (1 << 20) - prefill_mib; if (fit_mib >= kSmallReserveMib) { const int r = (int) std::min(fit_mib, o.vram_reserve_mib); s4 = ((int64_t) free_b - ((((int64_t) r + prefill_mib) << 20) + mtp_bind + pipe_first)) / blob; if (!profile.empty()) s4 = std::min(s4, (int64_t) profile.size()); o.vram_reserve_mib = r; reserve_adapted = true; } } o.expert_cache = (int) std::max(s4, 0); std::fprintf(stderr, "strata generate: short of GPU memory: the cache had no room, so the output head (%llu MiB) moves to pinned host memory and is read over PCIe for " "every logits row: decode is slower; the cache is now %d slots\n", (unsigned long long) (native_head.weight_bytes() >> 20), o.expert_cache); } else { std::fprintf(stderr, "strata generate: short of GPU memory: the output head stays in VRAM (%s)\n", herr.empty() ? "type or build not movable" : herr.c_str()); } } if (o.expert_cache == 0) { // what is short, and what makes room: the numbers a small card picks from const int64_t at_reserve = o.vram_reserve_given ? o.vram_reserve_mib : std::min(o.vram_reserve_mib, kSmallReserveMib); const int64_t need_b = (((int64_t) at_reserve + prefill_mib) << 20) + mtp_bind + pipe_first + min_slots * blob; const int64_t short_mib = std::max(1, (need_b - (int64_t) free_b + (1 << 20) - 1) >> 20); const int64_t session_mib = (int64_t) (strata::core::session_bytes(g, o.max_context, K, 0, g.n_layers) >> 20); const std::string reserve_tip = o.vram_reserve_given && o.vram_reserve_mib > kSmallReserveMib ? ", a smaller --vram-reserve-mib (" + std::to_string(o.vram_reserve_mib) + " now; " + std::to_string(kSmallReserveMib) + " is enough on a small card)" : std::string(); std::fprintf(stderr, "strata generate: no VRAM is left for the expert cache: it needs at least %lld slots " "(%lld MiB), about %lld MiB more than this card has free. To make room: a smaller " "--max-context (the session, mostly its KV cache, takes %lld MiB at %lld tokens), " "--kv q4_0, the English draft subset (setup --draft-vocab en; the draft head takes " "%lld MiB now)%s, images on the CPU, or close other programs that use the GPU\n", (long long) min_slots, (long long) ((min_slots * blob) >> 20), (long long) short_mib, (long long) session_mib, (long long) o.max_context, (long long) (mtp_bind >> 20), reserve_tip.c_str()); } } else if (multi_gpu && o.expert_cache > 0) { // an explicit cache size leaves room for the prompt path's buffers and the reserve, or the first prompt // fails with "device buffers ... do not fit" (with borrowing - the default with a profile - the path lends // slots instead and `prefill_mib` is 0, so only the reserve is checked) size_t free_b = 0, total_b = 0; free_b = strata::core::device_free_bytes(); (void) total_b; const int64_t prefill_mib = owned_prefill_mib(); const int64_t reserve = (((int64_t) o.vram_reserve_mib + prefill_mib) << 20) + pipe_first; const int64_t fit = std::max(((int64_t) free_b - reserve) / (int64_t) nibble_max_slot_bytes(), 0); if (o.expert_cache > fit) { // a WARNING that names the knob: the user asked for this size, and gets fewer slots std::fprintf(stderr, "strata generate: WARNING: layer split: --expert-cache %d leaves no room for the " "prompt path's buffers (%lld MiB) and the %d MiB reserve on CUDA0: %lld slots instead " "(a smaller --vram-reserve-mib leaves more of them)\n", o.expert_cache, (long long) prefill_mib, o.vram_reserve_mib, (long long) fit); o.expert_cache = (int) fit; } } // plan v0.3 P6: a native pack's blobs differ per layer, so the same VRAM holds more experts than slots of // the largest blob would. The shared cache below sizes slots in profile order. // #369: that list does not match --expert-cache-per-layer. A range is layer * quota + n, so a size cut for // one layer can land in another layer's slot. Every expert in a layer is one size, so the per-layer list is // `quota` copies of that layer's own blob, in layer order. `--expert-cache N` stays the budget of N largest // blobs, and the quota is however many copies of every layer fit in it. std::vector sized_slots; uint64_t per_layer_bytes = 0; if (native_pack && o.expert_cache > 0 && o.expert_cache_per_layer) { const size_t free_b = strata::core::device_free_bytes(); // the same reading the shared-cache sizing uses const auto& lay = strata::kernels::cpu::expert_layout(); const int asked = o.expert_cache; const uint64_t budget = (uint64_t) asked * nibble_max_slot_bytes(); size_t free_room = free_b > ((size_t) o.vram_reserve_mib << 20) ? free_b - ((size_t) o.vram_reserve_mib << 20) : 0; const uint64_t cap = std::min(budget, (uint64_t) free_room); uint64_t sum = 0; for (int64_t l = 0; l < g.n_layers; ++l) sum += (uint64_t) strata::core::ExpertCache::slot_stride((int64_t) nib::slot_bytes(l), slot_guard); int64_t q = sum > 0 ? (int64_t) (cap / sum) : 0; if (q > g.n_expert) q = g.n_expert; if (q > 0) { per_layer_bytes = sum; sized_slots.reserve((size_t) q * (size_t) g.n_layers); for (int64_t l = 0; l < g.n_layers; ++l) { const int64_t b = (int64_t) nib::slot_bytes(l); for (int64_t s = 0; s < q; ++s) sized_slots.push_back(b); } o.expert_cache = (int) sized_slots.size(); std::fprintf(stderr, "strata generate: per-layer slots use each layer's blob: %d uniform slots " "(%.2f GiB) -> %d slots, %lld per layer (%.2f GiB)\n", asked, (double) budget / 1073741824.0, o.expert_cache, (long long) q, (double) ((uint64_t) q * per_layer_bytes) / 1073741824.0); } } else if (native_pack && o.expert_cache > 0 && !profile.empty()) { size_t free_b = 0, total_b = 0; free_b = strata::core::device_free_bytes(); (void) total_b; const auto& lay = strata::kernels::cpu::expert_layout(); // what the uniform sizing granted, in the 256-byte slots the loop below counts: the blob formats of 1280 / 2560 // rows are whole multiples of 256 already; an NVFP4 blob's 16-byte scale tail is not, and the unrounded budget // held one slot fewer than asked (--expert-cache 1: none) const uint64_t budget = (uint64_t) o.expert_cache * ((nibble_max_slot_bytes() + 255) / 256 * 256); uint64_t used = 0; const size_t keep_free = ((size_t) o.vram_reserve_mib << 20) + (size_t) pipe_first; size_t free_room = free_b > keep_free ? free_b - keep_free : 0; const uint64_t cap = std::min(budget, (uint64_t) free_room); for (const auto& pr : profile) { const uint64_t b = (uint64_t) strata::core::ExpertCache::slot_stride((int64_t) nib::slot_bytes(pr.first), slot_guard); if (used + b > cap) break; used += b; sized_slots.push_back((int64_t) nib::slot_bytes(pr.first)); } // #831: the sized-slots loop walks the profile's pairs, so the profile's length is the ceiling; an explicit // --expert-cache above it used to be cut with no word. A warning only (what is allocated does not change). if (!auto_cache && o.expert_cache > 0 && sized_slots.size() == profile.size() && (size_t) o.expert_cache > profile.size()) std::fprintf(stderr, "strata generate: WARNING: --expert-cache %d is more than the %zu pairs of the profile %s: " "%zu slots (the profile is the ceiling on a native pack; a profile that ranks every " "(layer, expert) pair lifts it - tools/make_profile.py)\n", o.expert_cache, profile.size(), o.expert_profile.c_str(), profile.size()); o.expert_cache = (int) sized_slots.size(); #if !defined(STRATA_USE_HIP) && !defined(STRATA_GPU_METAL) && !defined(_WIN32) // ---- AUTO NO-BORROW (0.2.10). With batch slots on one NVIDIA card the prompt path lent cache slots to its own // buffers, and every lent slot's expert was read again from the host during each chunk. When the card holds EVERY // expert of the profile and still has room for the path's own buffers (the chunk the loan would have used, 8192) // plus kNoBorrowKeepMib, the loan only costs time: the buffers are allocated instead, the chunk stays what it was, and // the arithmetic is the same (QUAL-PAR2: 12/12 identical, KL 0). A card that cannot hold all experts keeps the loan - // its cache is worth more than the buffers (a 16 GB A4000 lost 2.5x on a long prompt and ran out of memory with them). // Not with an explicit --prefill N, a split, helper caches, STRATA_PREFILL_BORROW=1 or STRATA_AUTO_NOBORROW=0. if (auto_cache && pf_borrow && o.prefill_auto && o.batch >= 2 && !multi_gpu && stages.empty() && !profile.empty() && sized_slots.size() == profile.size() && std::none_of(o.expert_cache_remote.begin(), o.expert_cache_remote.end(), [](int n) { return n > 0; })) { const char* e1 = std::getenv("STRATA_AUTO_NOBORROW"); const char* e2 = std::getenv("STRATA_PREFILL_BORROW"); if (!(e1 != nullptr && e1[0] == '0') && !(e2 != nullptr && e2[0] == '1')) { constexpr int64_t kNoBorrowChunk = 8192, kNoBorrowKeepMib = 3072; uint64_t used_b = 0; for (const int64_t sb : sized_slots) used_b += (uint64_t) strata::core::ExpertCache::slot_stride(sb, slot_guard); const int64_t chunk = std::min(kNoBorrowChunk, std::max(256, o.prefill_auto_max)); const int64_t own_mib = ((int64_t) strata::prefill::Prefill::bytes_needed_owned(g, ss, chunk, srcp != nullptr) >> 20) + 64; const size_t fb = strata::core::device_free_bytes(); const int64_t room_mib = fb > used_b ? (int64_t) ((fb - used_b) >> 20) - o.vram_reserve_mib - (int64_t) (pipe_first >> 20) : 0; const bool fits = room_mib >= own_mib + kNoBorrowKeepMib; std::fprintf(stderr, "strata generate: every expert fits the cache; the prompt path's own buffers (%lld MiB for a %lld-token chunk) %s " "(%lld MiB left beside the %d MiB reserve, %lld MiB kept free)%s\n", (long long) own_mib, (long long) chunk, fits ? "fit" : "do not fit", (long long) room_mib, o.vram_reserve_mib, (long long) kNoBorrowKeepMib, fits ? ": no loan of cache slots" : ": the loan stays"); if (fits) { o.no_prefill_borrow = true; pf_borrow = false; o.prefill_auto = false; o.prefill_chunk = chunk; } } } #endif } #if defined(STRATA_USE_HIP) && defined(__linux__) // LEND (kfd_quiet.hpp), integrated gfx11 under Linux: the prompt path keeps its own buffers instead of lending cache slots, the // rule of the Strix Halo on Windows (0.2.8, above) for this class. Every lent slot is copied back from the host arena after each // prompt: 1,967 slots (2.53 GiB) on p2006, +1.1-1.4 s on every short prompt with the arena unregistered (11-15). Decided HERE, // after the cache was sized as with a loan, so the cache keeps the slots it gets today (--expert-cache N or the auto size); the // own buffers then must fit in what the driver reports free beside it (AUTO NO-BORROW's arithmetic), else the loan stays. The // chunk is the one the loan would have used (no drop to 2,048). Off by default (kNoLendDefaultOn); STRATA_KFD_QUIET_LEND=1 turns // it on, =0 or STRATA_PREFILL_BORROW=1 keeps the loan. if (pf_borrow && o.prefill_chunk > 0 && strata::core::kfd_quiet::lend_rule_on(strata::core::kfd_quiet::class_flag().load(std::memory_order_relaxed), std::getenv("STRATA_KFD_QUIET"), std::getenv("STRATA_KFD_QUIET_LEND"), std::getenv("STRATA_PREFILL_BORROW"))) { const bool one_gpu = !multi_gpu && stages.empty() && o.peer_device < 1 && std::none_of(o.expert_cache_remote.begin(), o.expert_cache_remote.end(), [](int n) { return n > 0; }); uint64_t cache_b = 0; if (!sized_slots.empty()) for (const int64_t sb : sized_slots) cache_b += (uint64_t) strata::core::ExpertCache::slot_stride(sb, slot_guard); else cache_b = (uint64_t) std::max(o.expert_cache, 0) * (uint64_t) nibble_max_slot_bytes(); const int64_t own_mib = ((int64_t) strata::prefill::Prefill::bytes_needed_owned(g, ss, o.prefill_chunk, srcp != nullptr) >> 20) + 64; const size_t fb = strata::core::device_free_bytes(); const int64_t room_mib = fb > cache_b ? (int64_t) ((fb - cache_b) >> 20) - o.vram_reserve_mib - (int64_t) (pipe_first >> 20) : 0; const strata::core::kfd_quiet::NoLend nl = strata::core::kfd_quiet::no_lend_pick(true, pf_borrow, one_gpu, o.prefill_chunk, room_mib, own_mib); if (std::getenv("STRATA_TRACE") != nullptr) std::fprintf(stderr, "strata trace: kfd quiet: prompt path without a loan: %s (own buffers %lld MiB for a %lld-token chunk, %lld MiB free " "beside the %d-slot cache and the %d MiB reserve, %lld kept)\n", nl.no_lend ? "yes" : !one_gpu ? "no, not one GPU" : !nl.fits ? "no, they do not fit" : "no", (long long) own_mib, (long long) o.prefill_chunk, (long long) room_mib, o.expert_cache, o.vram_reserve_mib, (long long) strata::core::kfd_quiet::kNoLendKeepMib); if (nl.no_lend) { o.no_prefill_borrow = true; pf_borrow = false; o.prefill_auto = false; o.prefill_chunk = nl.chunk; } } #endif #if !defined(STRATA_USE_HIP) && !defined(STRATA_GPU_METAL) && !defined(_WIN32) // 0.2.10.1 (round0212 item 7): the FP16 weight cache is on when the engine runs batch slots on Linux CUDA. Bit-exact against the uncached // form (gemm_w16_parity, greedy identity 12/12, first-token KL 0); +3.8% (c=1) .. +6.6% (c=8) total tokens/s on l620. It takes only VRAM beyond // 3 GiB kept free; STRATA_PF_W16_CACHE_MIB=0 turns it off, =N is an explicit budget. if (o.batch >= 2) strata::prefill::Gemm::set_w16_auto_default(true); #endif // #533: --vram-elastic: the cache in physical segments (the VRAM command resizes it between requests). One GPU, // no helper caches, serve mode: anything else keeps the one cudaMalloc, said once. if (o.vram_elastic) { const char* why = !o.serve ? "it works between requests of --serve" : multi_gpu ? "a layer split has a cache per GPU" : std::any_of(o.expert_cache_remote.begin(), o.expert_cache_remote.end(), [](int n) { return n > 0; }) ? "the helper caches on other GPUs" : o.vram_segment_mib < 64 ? "--vram-segment-mib is below 64" : nullptr; #if defined(STRATA_USE_HIP) if (why == nullptr) why = "it is NVIDIA-only for now"; #endif if (why != nullptr) { std::fprintf(stderr, "strata generate: --vram-elastic is off: %s\n", why); o.vram_elastic = false; } else { xcache.set_segment_bytes(o.vram_segment_mib << 20); } } // STRATA_MMQ_DIRECT: the guard after each sized slot (kept across the retry loop's close/open) xcache.set_slot_guard(slot_guard); if (slot_guard > 0 && o.expert_cache > 0) { if (!sized_slots.empty()) std::fprintf(stderr, "strata generate: +%lld B guard per sized slot (STRATA_MMQ_DIRECT)\n", (long long) slot_guard); else // xcache.open below: every slot is the largest blob's size, and no guard is added std::fprintf(stderr, "strata generate: uniform expert slots, no guard (STRATA_MMQ_DIRECT): an expert is read " "in its slot where the slot's slack covers the over-read\n"); } if (o.expert_cache > 0) { // keep the first `keep_bytes` of the cache (the profile's hottest experts first); false when nothing is left auto shrink_to = [&](int64_t keep_bytes) -> bool { if (keep_bytes <= 0) { o.expert_cache = 0; sized_slots.clear(); return false; } if (per_layer_bytes > 0) { // Cutting the list short would put one layer's blob in the next layer's range. const auto& lay = strata::kernels::cpu::expert_layout(); int64_t q = keep_bytes / (int64_t) per_layer_bytes; if (q > g.n_expert) q = g.n_expert; sized_slots.clear(); if (q <= 0) { o.expert_cache = 0; return false; } for (int64_t l = 0; l < g.n_layers; ++l) { const int64_t b = (int64_t) nib::slot_bytes(l); for (int64_t s = 0; s < q; ++s) sized_slots.push_back(b); } o.expert_cache = (int) sized_slots.size(); return true; } if (!sized_slots.empty()) { int64_t used = 0; size_t keep = 0; while (keep < sized_slots.size() && used + strata::core::ExpertCache::slot_stride(sized_slots[keep], slot_guard) <= keep_bytes) used += strata::core::ExpertCache::slot_stride(sized_slots[keep++], slot_guard); sized_slots.resize(keep); o.expert_cache = (int) keep; } else { o.expert_cache = (int) (keep_bytes / (int64_t) strata::kernels::cpu::expert_layout().max_blob); } if (o.expert_cache <= 0) { o.expert_cache = 0; sized_slots.clear(); return false; } return true; }; auto cache_bytes = [&]() -> int64_t { if (sized_slots.empty()) return (int64_t) o.expert_cache * (int64_t) strata::kernels::cpu::expert_layout().max_blob; int64_t b = 0; for (const int64_t s : sized_slots) b += strata::core::ExpertCache::slot_stride(s, slot_guard); return b; }; // With `--expert-cache auto` the reserve must still be free once the slots are WRITTEN: under WDDM an // allocation is not resident until it is touched, and the free figure read before it can be ~1 GB too // high. A cache sized from it filled the card to 0 MiB, the driver then paged, and a request that needed a // page back while the verify graph spun on a host flag never finished. So the slots are zeroed and the // free figure read again; while it is short of the reserve the cache is reopened smaller. // STRATA_TEST_CACHE_FAIL=N: the first N opens fail as an out-of-commit cudaMalloc does (tests the retry) int fake_fails = std::getenv("STRATA_TEST_CACHE_FAIL") ? std::atoi(std::getenv("STRATA_TEST_CACHE_FAIL")) : 0; int failed = 0; int zero_reads = 0; for (int attempt = 0;; ++attempt) { bool ok = false; if (fake_fails > 0) { --fake_fails; err = "ExpertCache: cudaMalloc failed: out of memory (STRATA_TEST_CACHE_FAIL)"; } else { ok = sized_slots.empty() ? xcache.open(o.expert_cache, g.n_layers, g.n_expert, (int64_t) strata::kernels::cpu::expert_layout().max_blob, err) : xcache.open_sized(sized_slots, g.n_layers, g.n_expert, err); } if (!ok) { // Issue #60: on Windows a device allocation is also charged to the system commit (RAM + page file), // so with a small page file the cache's one big cudaMalloc fails while the VRAM is free. An auto // cache then tries three quarters of the size, a few times, instead of stopping the engine. char commit[96] = ""; #if defined(_WIN32) MEMORYSTATUSEX ms{}; ms.dwLength = sizeof ms; if (GlobalMemoryStatusEx(&ms)) std::snprintf(commit, sizeof commit, " (Windows has %.1f GiB of commit left: RAM + page file)", (double) ms.ullAvailPageFile / 1073741824.0); #endif if (auto_cache && failed < 8 && shrink_to(cache_bytes() / 4 * 3)) { ++failed; std::fprintf(stderr, "strata generate: %s%s; trying a smaller expert cache: %d slots\n", err.c_str(), commit, o.expert_cache); continue; } std::fprintf(stderr, "strata generate: %s\n", err.c_str()); #if defined(_WIN32) std::fprintf(stderr, "strata generate: on Windows the graphics card's memory also needs room in the page " "file: set it to \"System managed\" (System > About > Advanced system settings > " "Performance > Advanced > Virtual memory), or lower --expert-cache\n"); #endif return 1; } if (!auto_cache || attempt - failed >= 6) break; cudaMemset(xcache.device_slot(0), 0, (size_t) xcache.bytes()); cudaDeviceSynchronize(); size_t free_b = 0, total_b = 0; free_b = strata::core::device_free_bytes(); (void) total_b; const int64_t want = ((int64_t) o.vram_reserve_mib << 20) + pipe_first; if ((int64_t) free_b >= want - (64ll << 20)) break; // short by (want - free); a figure of 0 only says "at least": the first two such reads give back 1 GiB // each (under WDDM the free figure read before the allocation runs ~0.7 GiB high), later ones a quarter int64_t give = want - (int64_t) free_b + (64ll << 20); if (free_b < ((size_t) 16 << 20)) give = std::max(give, ++zero_reads <= 2 ? 1ll << 30 : xcache.bytes() / 4); const int64_t keep_bytes = xcache.bytes() - give; std::fprintf(stderr, "strata generate: only %lld MiB free once the slots are written (reserve %d MiB); " "shrinking the expert cache\n", (long long) (free_b >> 20), o.vram_reserve_mib); xcache.close(); if (!shrink_to(keep_bytes)) break; } if (failed > 0 && o.expert_cache > 0) std::fprintf(stderr, "strata generate: expert cache: %d slots (%.2f GiB) after %d smaller tries - a bigger " "page file lets it use more of the free VRAM\n", o.expert_cache, (double) xcache.bytes() / 1073741824.0, failed); } if (o.expert_cache > 0) { std::fprintf(stderr, "strata generate: expert cache %lld slots, %.2f GiB of VRAM; policy is\n", (long long) xcache.slots(), xcache.gib()); mem_mark("opening the expert cache"); xcache.set_per_layer_admission(o.expert_cache_per_layer); // Round 328 warned here that the GPU hit path was wrong (tokens diverged from a cache-off run from // token 0). That fault was fixed long since (native_expert_parity, expert_parity, the grouped kernels' // tests), and the warning outlived it (issue #23). What remains is rounding: a GPU expert and the CPU's // compute the same quantized expert with different float order, so a near-tie can flip. Measured teacher- // forced on 2,557 tokens (bench/results/2026-09-27-cache-parity): 95-98% same top-1, and perplexity equal // (on - off = -0.005 +- 0.005 nats). Neither output is more correct than the other. std::fprintf(stderr, "strata generate: the GPU computes the experts in the cache; it rounds differently from the CPU,\n" " so a reply can differ slightly from a run without the cache (same quality:\n" " bench/results/2026-09-27-cache-parity).\n"); if (o.expert_cache_per_layer) { int64_t lo = 0, hi = 0; xcache.layer_slot_range(0, lo, hi); std::fprintf(stderr, " R4.2g PER-LAYER: each layer owns %lld slots (%lld..%lld).\n", (long long) (hi - lo), (long long) lo, (long long) (hi - 1)); } else if (profile.empty()) { std::fprintf(stderr, " compulsory-miss (fills with whatever the run routes first).\n"); } else { std::fprintf(stderr, " PROFILE, ranked by routing frequency, no eviction.\n"); } } #if defined(STRATA_USE_HIP) && defined(__linux__) // integrated gfx11 (kfd_quiet.hpp, LOAD): the expert cache's GPU memory was just allocated (7.7 GiB on a 780M) and the kernel moves // pages after such a step; the profile fill, the graph capture and the first GPU work wait until the process's KFD eviction // counter has been quiet for 2 s (at most 10 s; nothing where the counter cannot be read; STRATA_NO_KFD_SETTLE=1 also turns it off) if (strata::core::kfd_quiet::load_moves().settle_after_cache) strata::core::kfd_settle::settle_before_ready(); #endif // ---- R4.2e: fill the tier from the profile. This is the only place the plan is applied, and it runs // ONCE: with `slots` pairs and `slots` slots the cache is full when this returns, so the decode-time // admission finds no room and every non-profiled expert stays a CPU miss. That is what makes the profile // the policy rather than a hint. int64_t prefilled = 0; // STRATA_EXPERT_NIBBLE: each cache's converted slots (RECHECK reads them per request) NibbleCache nib_x; std::vector nib_st; nib_st.reserve(stages.size()); if (!profile.empty() && srcp != nullptr) { // #369 (dag08): per layer, a full layer skips only its own pairs - each layer takes its hottest experts until // its range is full (one full layer used to end the whole fill, leaving most layers empty) const bool per_layer = xcache.per_layer_admission(); const int64_t want = per_layer ? (int64_t) profile.size() : std::min((int64_t) profile.size(), xcache.slots()); // #286: an unbuffered file tier reads the pairs in batches of 64, the next batch while this one is copied std::future ahead; auto read_batch = [&](int64_t at) { src.prefetch_pairs(profile.data() + at, std::min(64, want - at)); }; // mapped reads: advise the next `fill_ahead` pairs so their reads overlap; STRATA_FILL_AHEAD=0 turns it off int64_t fill_ahead = 0; if (!per_layer && srcp == &src && !src.unbuffered()) { const char* v = std::getenv("STRATA_FILL_AHEAD"); fill_ahead = v == nullptr ? 256 : std::max(0, std::atoi(v)); if (fill_ahead > 0 && !src.advise_pairs(profile.data(), std::min(fill_ahead, want))) fill_ahead = 0; std::fprintf(stderr, "strata generate: the profile fill asks for %lld pairs ahead (STRATA_FILL_AHEAD)\n", (long long) fill_ahead); } const auto fill_t0 = std::chrono::steady_clock::now(); uint64_t fill_bytes = 0; if (nib::any_on()) { // STRATA_EXPERT_NIBBLE: the converted layers' pairs go through the 4-bit fill instead int64_t conv = 0; for (int64_t i = 0; i < want; ++i) conv += nib::layer(profile[(size_t) i].first).on ? 1 : 0; if (conv > 0 && !nib_x.begin(xcache, conv, err)) { std::fprintf(stderr, "strata generate: STRATA_EXPERT_NIBBLE: %s\n", err.c_str()); return 1; } } for (int64_t i = 0; i < want; ++i) { if (!per_layer && srcp == &src && src.unbuffered() && i % 64 == 0) { if (ahead.valid()) ahead.get(); else read_batch(i); if (i + 64 < want) ahead = std::async(std::launch::async, [&read_batch](int64_t b) { strata::aux_cpus::pin_current_thread(); read_batch(b); }, i + 64); } if (fill_ahead > 0 && i + fill_ahead < want) (void) src.advise_pairs(profile.data() + i + fill_ahead, 1); const int32_t slot = xcache.admit(profile[(size_t) i].first, profile[(size_t) i].second); if (slot == strata::core::kNotResident) { if (per_layer) continue; break; } const uint8_t* b = srcp->blob_stable(profile[(size_t) i].first, profile[(size_t) i].second); const bool nib_pair = nib_x.active() && nib::layer(profile[(size_t) i].first).on; // STRATA_EXPERT_NIBBLE if (b == nullptr || !(nib_pair ? nib_x.add(profile[(size_t) i].first, profile[(size_t) i].second, slot, b, err) : xcache.fill_slot_blocking(slot, b, err, (int64_t) strata::kernels::cpu::expert_layout().blob_bytes(profile[(size_t) i].first)))) { std::fprintf(stderr, "strata generate: the profile fill failed at pair %lld: %s\n", (long long) i, err.c_str()); return 1; } fill_bytes += strata::kernels::cpu::expert_layout().blob_bytes(profile[(size_t) i].first); ++prefilled; } if (nib_x.active() && !nib_x.finish(err)) { std::fprintf(stderr, "strata generate: STRATA_EXPERT_NIBBLE: CUDA0: %s\n", err.c_str()); return 1; } const double fill_s = std::chrono::duration(std::chrono::steady_clock::now() - fill_t0).count(); // **AND ONE SLOT IS READ BACK AND COMPARED.** A residency table that is right about indices and wrong // about bytes produces a plausible token, which is this project's most expensive failure mode; the // cache's own `verify_slot` is the check and it costs one 1.38 MB D2H at startup. // (STRATA_EXPERT_NIBBLE: a converted slot holds 4-bit codes, not the blob's bytes - the 4-bit check below is its check) if (prefilled > 0 && !nib::layer(profile[0].first).on && !xcache.verify_slot(xcache.slot_of(profile[0].first, profile[0].second), srcp->blob_stable(profile[0].first, profile[0].second), err, (int64_t) strata::kernels::cpu::expert_layout().blob_bytes(profile[0].first))) { std::fprintf(stderr, "strata generate: %s\n", err.c_str()); return 1; } if (nib_x.active() && nib_x.n > 0) { // STRATA_EXPERT_NIBBLE: the hottest converted pair read back (its hash, its down rows); every item and every // rebuilt GGUF block of every converted slot was already checked on the device size_t c = 0; while (c < (size_t) want && !nib::layer(profile[c].first).on) ++c; if (!nib_x.check(profile[c].first, profile[c].second, srcp->blob_stable(profile[c].first, profile[c].second), err)) { std::fprintf(stderr, "strata generate: STRATA_EXPERT_NIBBLE: CUDA0: %s\n", err.c_str()); return 1; } std::set ls; for (const auto& pr : nib_x.pairs) ls.insert(pr.first); std::fprintf(stderr, "strata generate: STRATA_EXPERT_NIBBLE: CUDA0: %lld slots of %zu layers transcoded to 4-bit " "codes (%.2f s; every item round-tripped, every slot's GGUF blocks rebuilt and compared, " "slot hashes recorded); layer %d expert %d read back\n", (long long) nib_x.n, ls.size(), nib_x.seconds, (int) profile[c].first, (int) profile[c].second); } mem_mark("the profile fill"); std::fprintf(stderr, "strata generate: pre-filled %lld of %lld slots from the profile in %.1f s (%.0f MB/s); " "slot 0 verified\n", (long long) prefilled, (long long) (per_layer ? xcache.slots() : want), fill_s, fill_s > 0 ? (double) fill_bytes / 1e6 / fill_s : 0.0); if (std::getenv("STRATA_VERIFY_COMPLEMENT") != nullptr) { // tests: the filled slots' checksum (each slot's blob read back and hashed, then the hashes in slot order) std::vector> sl; // (slot, blob bytes) for (int64_t l = 0; l < g.n_layers; ++l) for (int64_t e = 0; e < g.n_expert; ++e) if (const int32_t s = xcache.slot_of(l, e); s >= 0) sl.emplace_back(s, (int64_t) strata::kernels::cpu::expert_layout().blob_bytes(l)); std::sort(sl.begin(), sl.end()); std::vector sh(sl.size(), 0); std::atomic next_slot{0}; std::atomic copy_ok{true}; auto hash_work = [&] { std::vector hb; for (size_t i; (i = next_slot.fetch_add(1)) < sl.size();) { hb.resize((size_t) sl[i].second); if (cudaMemcpy(hb.data(), xcache.device_slot(sl[i].first), hb.size(), cudaMemcpyDeviceToHost) != cudaSuccess) copy_ok = false; sh[i] = strata::core::fnv1a64(hb.data(), (uint64_t) hb.size()); } }; std::vector hth; for (int t = 1; t < 8; ++t) hth.emplace_back(hash_work); hash_work(); for (auto& t : hth) t.join(); uint64_t h = strata::core::fnv1a64(nullptr, 0); for (size_t i = 0; i < sl.size(); ++i) { // field by field: a pair's padding is not part of it const int64_t v[2] = {(int64_t) sl[i].first, sl[i].second}; h = strata::core::fnv1a64((const uint8_t*) v, sizeof v, h); h = strata::core::fnv1a64((const uint8_t*) &sh[i], sizeof sh[i], h); } std::fprintf(stderr, "strata generate: expert cache checksum %016llx (%zu slots%s)\n", (unsigned long long) h, sl.size(), copy_ok ? "" : ", A READ-BACK FAILED"); } } for (auto& stp : stages) { GpuStage& st = *stp; const auto& lay = strata::kernels::cpu::expert_layout(); // the drafter and the head are already allocated by now (they load above, before this), so what is left // to hold back is the windows - and `free_b` has already lost the drafter. Not the draft head and its // logits: the drafter allocates them when it binds, after this, as on one GPU (#199), so on the last stage // they come out of the cache here. Out of the reserve instead, a later card without a display (300 MiB) // had no room left for them: "mtp: the draft head does not fit" on two 16 GB cards. (Strata-DualGPU) const int64_t draft_head = (&st == last_st && !o.mtp.empty() && st.head.loaded()) ? (int64_t) mtp.bind_bytes(st.head.row_bytes(), n_vocab) : 0; int64_t room = stage_room(st.dev, true, false) - draft_head; const strata::core::OnDevice on(st.dev); #if defined(STRATA_HAVE_DFLASH2) // DFlash2's own draft head and logits (and, in serve, the prompt staging) are bound on its card AFTER the caches, as the single card prices them (mtp_bind above): without // this term the last stage ended its load with 130-400 MiB less than the plan kept (the serve check's LOW at 8 and 12 GB). Not under STRATA_DEFAULTS=026. if (use_df2 && &st == last_st && !df2_first && !strata::qwen_defaults_026()) { const int64_t df2_after = df2_head_bytes() + (48 << 20) + (o.serve ? (112 << 20) : 0); room = std::max(room - df2_after, 0); } #endif // THE LAYER SPLIT'S SPILL WALK, STEP 5: THE OUTPUT HEAD ON THE HOST, LAST. The card that holds the head (the last stage) has no room for a working cache beside it: the head // (0.41 GiB) moves to mapped pinned host memory and every logits row reads it over PCIe (decode is slower, the start works). Only a card that would otherwise refuse. if (&st == last_st && st.head.loaded() && !st.head.on_host() && !o.vram_reserve_given && std::getenv("STRATA_HEAD_HOST_OFF") == nullptr && std::getenv("STRATA_SPILL_OFF") == nullptr && spill_discrete_gpu() && room < strata::program::split_walk::kWorkingCacheSlots * (int64_t) lay.max_blob) { std::string herr; const uint64_t head_mib = st.head.weight_bytes() >> 20; if (st.head.to_host(herr)) { room = stage_room(st.dev, true, false); std::fprintf(stderr, "strata generate: short of GPU memory: CUDA%d: the cache would have no room, so the output head (%llu MiB) moves to pinned host memory and is read over " "PCIe for every logits row: decode is slower; the room for experts is now %.2f GiB\n", st.dev, (unsigned long long) head_mib, (double) room / 1073741824.0); } else { std::fprintf(stderr, "strata generate: short of GPU memory: CUDA%d: the output head stays in VRAM (%s)\n", st.dev, herr.empty() ? "type or build not movable" : herr.c_str()); } } { size_t fb = 0, tb = 0; cudaMemGetInfo(&fb, &tb); std::fprintf(stderr, "strata generate: layer split, CUDA%d: %.2f GiB free of %.2f, room for experts %.2f GiB\n", st.dev, (double) fb / 1073741824.0, (double) tb / 1073741824.0, (double) room / 1073741824.0); } std::vector sized; int64_t used = 0; for (const auto& pr : st.profile) { const int64_t b = native_pack ? strata::core::ExpertCache::slot_stride((int64_t) nib::slot_bytes(pr.first), slot_guard) : (int64_t) lay.max_blob; if (used + b > room) break; used += b; sized.push_back((int64_t) nib::slot_bytes(pr.first)); } // #841: a stage's cache can fail to open with the VRAM free (the card's allocation is also charged to the // Windows commit, or the free figure ran high): it is tried again with 90% of the slots, up to 3 times, each // try said. Nothing changes when the first open works. bool stage_open = false; st.cache.set_slot_guard(slot_guard); // STRATA_MMQ_DIRECT: the stages' prompt MMQ reads their own slots for (int attempt = 0; !sized.empty(); ++attempt) { stage_open = native_pack ? st.cache.open_sized(sized, g.n_layers, g.n_expert, err) : st.cache.open((int64_t) sized.size(), g.n_layers, g.n_expert, (int64_t) lay.max_blob, err); if (stage_open || attempt >= 3) break; (void) cudaGetLastError(); const size_t keep = sized.size() * 9 / 10; std::fprintf(stderr, "strata generate: layer split, CUDA%d expert cache: %s; trying %zu of %zu slots " "(try %d of 3)\n", st.dev, err.c_str(), keep, sized.size(), attempt + 1); if (keep == 0) break; st.cache.close(); sized.resize(keep); } if (!stage_open) { std::fprintf(stderr, "strata generate: layer split, CUDA%d expert cache: %s\n", st.dev, sized.empty() ? "no room" : err.c_str()); return 1; } int64_t filled = 0; NibbleCache& nib_c = nib_st.emplace_back(); // STRATA_EXPERT_NIBBLE: this stage's converted slots if (nib::any_on()) { int64_t conv = 0; for (const auto& pr : st.profile) conv += nib::layer(pr.first).on ? 1 : 0; if (conv > 0 && !nib_c.begin(st.cache, conv, err)) { std::fprintf(stderr, "strata generate: STRATA_EXPERT_NIBBLE: CUDA%d: %s\n", st.dev, err.c_str()); return 1; } } for (const auto& pr : st.profile) { if (filled >= st.cache.slots()) break; const int32_t slot = st.cache.admit(pr.first, pr.second); if (slot == strata::core::kNotResident) break; const uint8_t* b = srcp->blob_stable(pr.first, pr.second); const bool nib_pair = nib_c.active() && nib::layer(pr.first).on; // STRATA_EXPERT_NIBBLE if (b == nullptr || !(nib_pair ? nib_c.add(pr.first, pr.second, slot, b, err) : st.cache.fill_slot_blocking(slot, b, err, (int64_t) lay.blob_bytes(pr.first)))) { std::fprintf(stderr, "strata generate: layer split, CUDA%d profile fill failed at pair %lld: %s\n", st.dev, (long long) filled, err.c_str()); return 1; } ++filled; } if (nib_c.active() && !nib_c.finish(err)) { std::fprintf(stderr, "strata generate: STRATA_EXPERT_NIBBLE: CUDA%d: %s\n", st.dev, err.c_str()); return 1; } // (STRATA_EXPERT_NIBBLE: a converted slot holds 4-bit codes, not the blob's bytes - the 4-bit check below is its check) if (filled == 0 || (!nib::layer(st.profile[0].first).on && !st.cache.verify_slot(st.cache.slot_of(st.profile[0].first, st.profile[0].second), srcp->blob_stable(st.profile[0].first, st.profile[0].second), err, (int64_t) lay.blob_bytes(st.profile[0].first)))) { std::fprintf(stderr, "strata generate: layer split, CUDA%d expert cache: %s\n", st.dev, filled == 0 ? "nothing filled" : err.c_str()); return 1; } if (nib_c.active() && nib_c.n > 0) { // STRATA_EXPERT_NIBBLE: as CUDA0's above size_t c = 0; while (c < st.profile.size() && !nib::layer(st.profile[c].first).on) ++c; const auto& pc = st.profile[c]; if (!nib_c.check(pc.first, pc.second, srcp->blob_stable(pc.first, pc.second), err)) { std::fprintf(stderr, "strata generate: STRATA_EXPERT_NIBBLE: CUDA%d: %s\n", st.dev, err.c_str()); return 1; } std::set ls; for (const auto& pr : nib_c.pairs) ls.insert(pr.first); std::fprintf(stderr, "strata generate: STRATA_EXPERT_NIBBLE: CUDA%d: %lld slots of %zu layers transcoded to 4-bit " "codes (%.2f s; every item round-tripped, every slot's GGUF blocks rebuilt and compared, " "slot hashes recorded); layer %d expert %d read back\n", st.dev, (long long) nib_c.n, ls.size(), nib_c.seconds, (int) pc.first, (int) pc.second); } std::fprintf(stderr, "strata generate: layer split: CUDA%d runs layers %lld-%lld, expert cache %lld slots " "(%.2f GiB), %lld of its %zu profiled pairs; slot 0 verified\n", st.dev, (long long) st.lb, (long long) (st.le - 1), (long long) st.cache.slots(), st.cache.gib(), (long long) filled, st.profile.size()); } if (multi_gpu) std::fprintf(stderr, "strata generate: layer split: CUDA0 runs layers 0-%lld\n", (long long) (split_at[0] - 1)); // THE LAYER SPLIT'S SPILL WALK, STEP 4: THE LOAN KEEPS 16. A stage whose cache is too small to lend the prompt path a 256-token chunk and keep 128 slots behind makes the path // allocate its own buffers on top (more than the reserve): the same short card as the single card's, which keeps 16 slots instead (the cache is smaller, prompts are read in // smaller chunks, the start works). Never on a card with room: it only fires when a cache is below the usual loan. if (multi_gpu && !stages.empty() && g_lend_keep == 128 && o.prefill_chunk > 0 && pf_borrow && o.prefill_auto && !o.vram_reserve_given && std::getenv("STRATA_SPILL_OFF") == nullptr && spill_discrete_gpu()) { for (const auto& stp : stages) { const int64_t blob_s = (int64_t) nibble_max_slot_bytes(); const int64_t need_s = ((int64_t) strata::prefill::Prefill::bytes_needed(g, stp->ss, 256) + blob_s - 1) / blob_s + g_lend_keep; if ((int64_t) stp->cache.slots() < need_s) { std::fprintf(stderr, "strata generate: short of GPU memory: CUDA%d: the cache (%lld slots) is too small to lend the prompt path 256-token buffers and keep %lld more: " "the loan keeps 16, prompts are read in smaller chunks, expect them to be slower\n", stp->dev, (long long) stp->cache.slots(), (long long) g_lend_keep); g_lend_keep = 16; break; } } } if (nib::any_on()) { // STRATA_EXPERT_NIBBLE: every expert of every layer must be in VRAM, in the cache of the card that runs the layer. // A converted layer's miss would be computed from the GGUF blob by the CPU or over PCIe, and a non-converted // layer's residency would differ from the switch-off run's (its smaller slots leave room for more), so the // replies' bits would too. Then no slot is written again. for (int64_t l = 0; l < g.n_layers; ++l) { const strata::core::ExpertCache* owner = &xcache; int owner_dev = 0; if (multi_gpu && !split_at.empty() && l >= split_at[0]) { owner = nullptr; for (const auto& stp : stages) if (l >= stp->lb && l < stp->le) { owner = &stp->cache; owner_dev = stp->dev; } } int64_t missing = 0, first = -1; for (int64_t e = 0; e < g.n_expert; ++e) if (owner == nullptr || owner->slot_of(l, e) == strata::core::kNotResident) { if (first < 0) first = e; ++missing; } if (missing > 0) { std::fprintf(stderr, "strata generate: STRATA_EXPERT_NIBBLE refuses the start: layer %lld has %lld of its %lld " "experts out of CUDA%d's VRAM (expert %lld the first) - every expert must be resident " "(a profile that ranks every pair and room on the card; STRATA_EXPERT_NIBBLE_SKIP=" " keeps some layers' smaller GGUF slots)\n", (long long) l, (long long) missing, (long long) g.n_expert, owner_dev, (long long) first); return 1; } } xcache.seal(); for (auto& stp : stages) stp->cache.seal(); std::fprintf(stderr, "strata generate: STRATA_EXPERT_NIBBLE: all %lld experts of all %lld layers are VRAM-resident; " "the expert caches are sealed (nothing writes a slot from here on)\n", (long long) g.n_expert, (long long) g.n_layers); } // ---- LAYER 2: exact startability probe on the live free figures. Every session, cache and batch slot is // carved by now, so `cudaMemGetInfo` reads what serve's own_fits (5855-5869) will read. Run serve's own // predicates on the chosen split: every participant must lend a 512-token chunk, or afford its own buffers // with the 512 MiB headroom. Serve's live checks stay as the guard; this is the pre-flight confirmation. // STRATA_LAYER_SPLIT_PROBE=0 skips it. static const bool split_probe = [] { const char* v = std::getenv("STRATA_LAYER_SPLIT_PROBE"); return v == nullptr || v[0] != '0'; }(); if (multi_gpu && split_auto && split_probe && !split_at.empty()) { const int ns = (int) stages.size() + 1; const int64_t kPct = [] { const char* v = std::getenv("STRATA_PREFILL_LEND_PCT"); return v ? (int64_t) std::atoi(v) : g_lend_keep != 128 ? (int64_t) 100 // a card too short for the usual loan (see the cache sizing) lends what it must: the cap is for cards with room : (int64_t) (strata::prefill::Prefill::pinned_share() >= 0.9 ? 90 : 85); }(); const int64_t c = 512; bool probe_ok = true; int probe_dev = 0; int64_t probe_need = 0, probe_fb = 0, probe_slots = 0, probe_est = 0; for (int i = 0; i < ns; ++i) { const int dev = i == 0 ? 0 : stages[(size_t) i - 1]->dev; const strata::core::OnDevice on(dev); size_t fb = 0, tb = 0; cudaMemGetInfo(&fb, &tb); const strata::core::ExpertCache& xc = i == 0 ? xcache : stages[(size_t) i - 1]->cache; const uint64_t cn = strata::prefill::Prefill::bytes_needed(g, i == 0 ? ss : stages[(size_t) i - 1]->ss, c); const int64_t slots = xc.slots(); const uint64_t avg = slots > 0 ? xc.bytes() / (uint64_t) slots : (uint64_t) strata::kernels::cpu::expert_layout().max_blob; const int64_t slots_est = (int64_t) (((cn + 255) / 256 * 256 + avg - 1) / avg); const bool lends = slots > 0 && slots_est > 0 && slots_est + g_lend_keep <= slots && slots_est * 100 <= kPct * slots; if (lends) continue; if ((int64_t) cn + (512ll << 20) > (int64_t) fb) { probe_ok = false; probe_dev = dev; probe_need = (int64_t) cn; probe_fb = (int64_t) fb; probe_slots = slots; probe_est = slots_est; break; } } if (probe_ok) { std::fprintf(stderr, "strata generate: layer split auto: L2 probe: the split is startable on the live free figures\n"); } else { std::fprintf(stderr, "strata generate: layer split auto: L2 probe: CUDA%d cannot start the prompt path: " "a 512-token chunk needs %lld MiB of its own buffers (+512 MiB headroom) with %lld MiB " "free, and its %lld-slot cache cannot lend it (needs %lld slots)\n", probe_dev, (long long) (probe_need >> 20), (long long) (probe_fb >> 20), (long long) probe_slots, (long long) probe_est); std::fprintf(stderr, "strata generate: to make room: a smaller --max-context, --prefill 512, a smaller " "--vram-reserve-mib, an explicit --layer-split, or close other programs using the GPU\n"); } } std::array remote_experts; std::unique_ptr remote_opt; if (o.remote_expert_opt && o.expert_cache_remote[0] > 0) remote_opt = std::make_unique(); const bool multi_remote = o.expert_cache_remote[1] > 0 || o.expert_cache_remote[2] > 0; if (o.expert_cache_remote[0] > 0) { if (o.expert_cache <= 0 || profile.empty() || o.no_pool) { std::fprintf(stderr, "strata generate: remote experts need --expert-profile, " "a CUDA0 expert cache and the expert pool\n"); return 2; } std::vector> ranked = profile; if (!stages.empty()) { // a layer split: CUDA0's share of the profile, then the later stages' pairs no cache holds for (auto& st : stages) for (const auto& pr : st->profile) if (st->cache.slot_of(pr.first, pr.second) < 0) ranked.push_back(pr); } if (multi_remote || std::any_of(o.expert_cache_remote_auto.begin(), o.expert_cache_remote_auto.end(), [](bool automatic) { return automatic; })) { // The shipped frequency profile names only 8000 of 24576 experts. Once exhausted, // fill remaining VRAM from unranked pairs in expert-then-layer order: this spreads // the tail across all layers instead of concentrating it on layer zero. std::vector seen((size_t) g.n_layers * (size_t) g.n_expert, 0); for (const auto& pair : ranked) if (pair.first >= 0 && pair.first < g.n_layers && pair.second >= 0 && pair.second < g.n_expert) seen[(size_t) pair.first * (size_t) g.n_expert + (size_t) pair.second] = 1; for (int64_t e = 0; e < g.n_expert; ++e) for (int64_t l = 0; l < g.n_layers; ++l) if (!seen[(size_t) l * (size_t) g.n_expert + (size_t) e]) ranked.emplace_back((int32_t) l, (int32_t) e); std::fprintf(stderr, "strata generate: remote ranking: %zu profiled pairs, " "%zu other pairs to fill CUDA1..3\n", profile.size(), ranked.size() - profile.size()); } std::array>, 3> by_device; if (multi_remote) { // Either stripe experts for parallel GPU work, or give each layer one // secondary GPU to reduce switches and transfers over shared USB4. std::vector assigned((size_t) g.n_layers * (size_t) g.n_expert, 0); const int devices = 1 + (o.expert_cache_remote[1] > 0) + (o.expert_cache_remote[2] > 0); int next = 0; for (const auto& pair : ranked) { if (pair.first < 0 || pair.first >= g.n_layers || pair.second < 0 || pair.second >= g.n_expert || xcache.slot_of(pair.first, pair.second) >= 0) continue; const size_t index = (size_t) pair.first * (size_t) g.n_expert + (size_t) pair.second; if (assigned[index]) continue; int target = -1; if (o.expert_cache_remote_placement == "layer") { target = pair.first % devices; // Other layers' owners may still have room: keep scanning ranks. if (by_device[(size_t) target].size() >= (size_t) o.expert_cache_remote[(size_t) target]) continue; } else { for (int i = 0; i < devices; ++i) { const int r = (next + i) % devices; if (by_device[(size_t) r].size() < (size_t) o.expert_cache_remote[(size_t) r]) { target = r; break; } } if (target < 0) break; } assigned[index] = 1; by_device[(size_t) target].push_back(pair); next = (target + 1) % devices; } std::fprintf(stderr, "strata generate: remote ranks %s across %d CUDA devices\n", o.expert_cache_remote_placement == "layer" ? "grouped by layer" : "striped", devices); } else { by_device[0] = std::move(ranked); } std::vector claimed((size_t) g.n_layers * (size_t) g.n_expert, 0); for (auto& st : stages) // a layer split: what a stage's cache holds is no helper's for (const auto& pr : st->profile) if (st->cache.slot_of(pr.first, pr.second) >= 0) claimed[(size_t) pr.first * (size_t) g.n_expert + (size_t) pr.second] = 1; for (int r = 0; r < 3; ++r) if (o.expert_cache_remote[(size_t) r] > 0) { if (remote_opt) remote_opt->attach(remote_experts[(size_t) r]); if (!remote_experts[(size_t) r].open(remote_dev[r], o.expert_cache_remote[(size_t) r], g.n_layers, g.n_expert, by_device[(size_t) r], xcache, *srcp, claimed, err, o.expert_cache_remote_auto[(size_t) r])) { std::fprintf(stderr, "strata generate: %s\n", err.c_str()); return 1; } size_t hfree = 0, htotal = 0; { const strata::core::OnDevice on(remote_dev[r]); if (cudaMemGetInfo(&hfree, &htotal) != cudaSuccess) (void) cudaGetLastError(); } std::fprintf(stderr, "strata generate: CUDA%d: %lld additional experts, %.2f GiB; " "results return through pinned host rows (%zu of %zu MiB free on it)\n", remote_dev[r], (long long) remote_experts[(size_t) r].resident(), remote_experts[(size_t) r].gib(), hfree >> 20, htotal >> 20); } } // ---- Multi-GPU: the second GPU's expert tier, filled with the ranked pairs the primary does not hold strata::core::PeerExperts peer; if (o.peer_device >= 1) { if (profile.empty() || srcp == nullptr || o.expert_cache <= 0) { std::fprintf(stderr, "strata generate: --peer-device needs --expert-profile and the expert cache\n"); return 1; } const auto tp0 = Clock::now(); if (!peer.open(o.peer_device, profile, xcache, *srcp, g.n_layers, g.n_expert, o.peer_reserve_mib, o.peer_slots, err)) { std::fprintf(stderr, "strata generate: %s\n", err.c_str()); return 1; } std::fprintf(stderr, "strata generate: peer GPU %d: %lld experts, %.2f GiB (filled in %.1f s); with the primary's " "%lld that is %lld of %lld on the GPUs\n", o.peer_device, (long long) peer.resident(), peer.gib(), std::chrono::duration(Clock::now() - tp0).count(), (long long) xcache.slots(), (long long) (peer.resident() + xcache.slots()), (long long) (g.n_layers * g.n_expert)); } if (remote_opt && !remote_opt->init(err)) { std::fprintf(stderr, "strata generate: %s\n", err.c_str()); return 1; } Drive drive; // #731 (opt-in, STRATA_DISJOINT_ADAPT=1): the adaptive tiers leave an expert a helper GPU holds out of the primary's // promotion candidates (it would sit in both caches). Asked live, from the helper's own cache (RemoteExperts::holds, // #854), so an expert the helper's tier swaps in or out later is followed - never a copy taken at load. const bool disjoint_adapt = [] { const char* v = std::getenv("STRATA_DISJOINT_ADAPT"); return v != nullptr && std::atoi(v) != 0; }(); auto helper_holds = [&](int64_t l, int32_t e) -> bool { if (!disjoint_adapt) return false; for (int r = 0; r < drive.d.remote_count; ++r) if (drive.d.remote[r]->holds(l, e)) return true; return false; }; for (int r = 0; r < 3; ++r) if (o.expert_cache_remote[(size_t) r] > 0) drive.d.remote[drive.d.remote_count++] = &remote_experts[(size_t) r]; drive.d.peer = peer.valid() ? &peer : nullptr; drive.d.hit_cpu_order = o.expert_cache_cpu_order; drive.d.split_rows = !o.no_split_rows; drive.d.pool = &pool; drive.d.src = srcp; drive.d.n_expert = g.n_expert; drive.d.latent = lat_tab.latent; drive.d.lat_H = lat_tab.lat_H; drive.d.lat_ELL = lat_tab.lat_ELL; drive.d.lat_I = lat_tab.lat_I; drive.d.lat_G = lat_tab.lat_G; drive.d.lat_E = lat_tab.lat_E; drive.d.lat_dense = lat_tab.latent ? &lat_tab.dense : nullptr; drive.d.lat_labels = lat_tab.labels.empty() ? nullptr : lat_tab.labels.data(); drive.d.jobs.resize((size_t) K); // P1.8 (PR 4972, re-checked as residency changes): when every routed expert sits in the GPU caches the decode reads nothing // from the file tier, and its Linux defaults (io prefetch, the decode gate) and the routing-aware prefetch only cost time. // Measured on 2x W7900D (gfx1100), IQ3_S experts.bin, a layer split holding 24576 of 24576: decode 57 -> 80 tok/s, the // output byte-identical. Only what the defaults switched on is touched: STRATA_IO_PREFETCH=1 keeps io prefetch and the // look-ahead as before, STRATA_LOOKAHEAD=1 keeps the look-ahead. The check runs here, again at every request's start and // after a VRAM resize (a smaller cache, a loan that was not refilled, an adaptive swap), so a later eviction turns them // back on. STRATA_FILE_TIER_IDLE=0 turns the whole policy off. const bool file_tier_idle_ok = [] { const char* v = std::getenv("STRATA_FILE_TIER_IDLE"); return v == nullptr || std::atoi(v) != 0; }(); int64_t gpu_held_now = 0; bool gpu_holds_all = false, io_pf_suspended = false; // a (layer, expert) is held when a live slot of its stage's cache has it (a slot past the live ones was given back) auto count_gpu_held = [&]() -> int64_t { int64_t held = 0; for (int64_t l = 0; l < g.n_layers; ++l) { const int st = multi_gpu ? stage_of(l) : 0; const strata::core::ExpertCache& c = st > 0 ? stages[(size_t) st - 1]->cache : xcache; const int64_t live = c.slots(); for (int64_t e = 0; e < g.n_expert; ++e) { const int32_t sl = c.slot_of(l, e); held += sl != strata::core::kNotResident && sl < live; } } return held; }; if (srcp == &src && file_tier_idle_ok) { gpu_held_now = count_gpu_held(); gpu_holds_all = gpu_held_now == g.n_layers * g.n_expert; if (gpu_holds_all && io_pf_by_default) { src.set_io_prefetch(false, 0); io_pf_suspended = true; const char* sv = std::getenv("STRATA_IO_STATS"); src.set_io_stats(sv != nullptr && std::atoi(sv) != 0); std::fprintf(stderr, "strata generate: every expert is in the GPU caches (%lld of %lld): the file tier's Linux defaults " "(io prefetch, the decode gate) are off, the decode reads nothing from it (STRATA_IO_PREFETCH=1 keeps them)\n", (long long) gpu_held_now, (long long) (g.n_layers * g.n_expert)); } } const char* la_env = std::getenv("STRATA_LOOKAHEAD"); const bool la_asked = (la_env != nullptr && la_env[0] != '\0' && std::atoi(la_env) != 0) || [] { const char* v = std::getenv("STRATA_IO_PREFETCH"); return v != nullptr && v[0] != '\0' && std::atoi(v) != 0; }(); bool la_started = false; // CS-T: routing-aware prefetch of the file tier (the GGUF in place): the next layer's router on this layer's MoE // input predicts its experts and their pages are warmed meanwhile. It only warms pages; STRATA_LOOKAHEAD=0 is // the A/B arm, STRATA_LOOKAHEAD_K the experts per token (default 10). strata::core::RouterLookahead lookahead; // #1348, one prefetch design: with the Foresight swap space on (STRATA_FS_SLOTS) the look-ahead also runs on the pinned-RAM // tiers, where there are no pages to warm, and feeds its predictions to the swap space (STRATA_FS_AHEAD=0: not) const bool fs_ahead = srcp != nullptr && [] { const char* v = std::getenv("STRATA_FS_SLOTS"); return v != nullptr && std::atoi(v) > 0; }() && [] { const char* v = std::getenv("STRATA_FS_AHEAD"); return v == nullptr || std::atoi(v) != 0; }(); // STRATA_LOOKAHEAD_STATS=1 (measurement only): run the predictor on any tier and score it against the real routing const bool la_stats = srcp != nullptr && [] { const char* v = std::getenv("STRATA_LOOKAHEAD_STATS"); return v != nullptr && std::atoi(v) != 0; }(); if (srcp != nullptr && ((srcp == &src && src.warms()) || fs_ahead || la_stats) && (la_env == nullptr || std::atoi(la_env) != 0)) { std::vector> routers((size_t) g.n_layers); bool ok = true; for (int64_t l = 0; l < g.n_layers && ok; ++l) { const strata::core::WeightTable* owner = &wt; // the card that runs the layer holds its router int owner_dev = 0; for (const auto& st : stages) if (l >= st->lb && l < st->le) { owner = &st->wt; owner_dev = st->dev; } const strata::core::OnDevice on_owner(owner_dev); const strata::core::WeightRef* w = owner->find("blk." + std::to_string(l) + ".ffn_gate_inp.weight"); ok = w != nullptr && w->kind == strata::core::WeightKind::Bf16InF32 && w->bytes == (uint64_t) (g.n_expert * g.n_embd) * 2; if (!ok) break; routers[(size_t) l].resize((size_t) (g.n_expert * g.n_embd)); ok = cudaMemcpy(routers[(size_t) l].data(), w->data, (size_t) w->bytes, cudaMemcpyDeviceToHost) == cudaSuccess; } const char* kv = std::getenv("STRATA_LOOKAHEAD_K"); if (ok && lookahead.start(std::move(routers), g.n_embd, g.n_expert, kv ? std::atoi(kv) : 10, srcp, err, fs_ahead || la_stats)) { drive.d.lookahead = &lookahead; if (la_stats) lookahead.enable_stats(g.n_layers); if (const char* dv = std::getenv("STRATA_IO_PREFETCH_DEPTH"); dv != nullptr && std::atoi(dv) > 0) lookahead.set_depth(std::atoi(dv)); else if (srcp == &src && src.io_prefetch()) lookahead.set_depth(2); la_started = true; if (srcp == &src && gpu_holds_all && !la_asked && !fs_ahead && !la_stats) { // started, but not attached while nothing is read drive.d.lookahead = nullptr; std::fprintf(stderr, "strata generate: routing-aware prefetch off (every expert is in the GPU caches; STRATA_LOOKAHEAD=1 runs it)\n"); } else std::fprintf(stderr, "strata generate: routing-aware prefetch on (the next layer's router%s)\n", fs_ahead ? ", feeding the Foresight swap space" : ", file tier"); } else { (void) cudaGetLastError(); std::fprintf(stderr, "strata generate: routing-aware prefetch off (%s)\n", ok ? err.c_str() : "the routers are not BF16 in the arena"); err.clear(); } } // P1.8: the file tier's idle policy follows the residency. Called at a quiet point (a request's start, a VRAM resize): nothing // is in flight. Only what this policy turned off is turned on again. auto refresh_file_tier = [&]() { if (srcp != &src || !file_tier_idle_ok) return; const int64_t total = g.n_layers * g.n_expert; const int64_t held = count_gpu_held(); const bool all = held == total; if (all == gpu_holds_all) return; gpu_holds_all = all; bool acted = false; if (all) { if (io_pf_by_default && src.io_prefetch()) { src.set_io_prefetch(false, 0); io_pf_suspended = true; acted = true; const char* sv = std::getenv("STRATA_IO_STATS"); src.set_io_stats(sv != nullptr && std::atoi(sv) != 0); } if (la_started && !la_asked && !fs_ahead && !la_stats && drive.d.lookahead != nullptr) { drive.d.lookahead = nullptr; acted = true; } if (acted) std::fprintf(stderr, "strata serve: every expert is in the GPU caches again (%lld of %lld): the file tier's Linux defaults are off\n", (long long) held, (long long) total); } else { if (io_pf_suspended) { const char* th = std::getenv("STRATA_IO_PF_THREADS"); src.set_io_prefetch(true, th != nullptr ? std::atoi(th) : 0); io_pf_suspended = !src.io_prefetch(); acted = true; } if (la_started && drive.d.lookahead == nullptr) { drive.d.lookahead = &lookahead; if (!std::getenv("STRATA_IO_PREFETCH_DEPTH") && src.io_prefetch()) lookahead.set_depth(2); acted = true; } if (acted) std::fprintf(stderr, "strata serve: %lld of %lld experts are in the GPU caches now: the file tier's Linux defaults are on again\n", (long long) held, (long long) total); } }; // ---- R4.2c: THE HIT PATH. Every one of these is required for `hits_ready()`, which is all-or-nothing on // purpose: a half-configured hit path would compute some experts twice and others not at all, and a token // built on that is wrong rather than refused. void* hit_scratch = nullptr; int32_t* d_hit_slot = nullptr; int32_t* d_hit_dst = nullptr; uint8_t* d_hit_q8 = nullptr; float* d_hit_q8_scale = nullptr; ///< R4.2h: the fp32 activation scales the CPU path also uses float* d_hit_out = nullptr; if (o.expert_cache > 0 && !o.no_pool) { const uint64_t sb = strata::kernels::moe_hit_grouped_scratch_bytes(K, g.n_embd, strata::kernels::cpu::FF); if (cudaMalloc(&hit_scratch, (size_t) sb) != cudaSuccess || cudaMalloc((void**) &d_hit_slot, (size_t) K * sizeof(int32_t)) != cudaSuccess || cudaMalloc((void**) &d_hit_dst, (size_t) K * sizeof(int32_t)) != cudaSuccess || cudaMalloc((void**) &d_hit_q8, (size_t) (g.n_embd / 32) * 34) != cudaSuccess || // R4.2h: the fp32 activation scales. Without this the GPU's hits use the block's fp16 `d` // while the CPU's misses use `ActQ::scale`, which is fp32 - a 4.761e-04 relative disagreement on // every chunk, and the reason enabling the cache changed the tokens. cudaMalloc((void**) &d_hit_q8_scale, (size_t) (g.n_embd / 32) * sizeof(float)) != cudaSuccess || cudaMalloc((void**) &d_hit_out, (size_t) K * g.n_embd * 4) != cudaSuccess) { std::fprintf(stderr, "strata generate: the R4 hit path could not allocate its device buffers\n"); return 1; } drive.d.cache = &xcache; drive.d.cache_stream = main_cs; drive.d.cache_base = (const uint8_t*) xcache.device_slot(0); drive.d.cache_blob = (int64_t) strata::kernels::cpu::expert_layout().max_blob; drive.d.cache_slot_off = xcache.slot_offsets(); drive.d.hit_scratch = hit_scratch; drive.d.parts_out = d_parts; drive.d.hit_out = d_hit_out; drive.d.parts_elems = K * g.n_embd; drive.d.mixed = ss.block.mixed; drive.d.x_q8_0_hit = d_hit_q8; drive.d.x_q8_0_hit_scale = d_hit_q8_scale; drive.d.d_slot = d_hit_slot; drive.d.d_dst = d_hit_dst; drive.d.h_slot.resize((size_t) K); cudaEvent_t hit_done = nullptr; if (cudaEventCreate(&hit_done) != cudaSuccess) { std::fprintf(stderr, "strata generate: the hit path could not create its probe event\n"); return 1; } drive.d.hit_done = (void*) hit_done; drive.d.hit_poke = !o.no_hit_poke; drive.d.h_dst.resize((size_t) K); mem_mark("the R4 hit path"); std::fprintf(stderr, "strata generate: R4 hit path ON - resident experts are computed on the GPU\n"); } // ---- P0.S8: the routing trace. Only meaningful with the pool running, because the ids arrive through // the doorbell that the pool consumes - so `--no-pool` is refused rather than silently producing an empty // file that would read as "the router selected nothing". // ---- PER-STAGE TIMING. `--no-capture` only: an event recorded inside a stream capture is silently // dropped, so a captured graph cannot carry these events and the numbers would be zeros that read as // "every stage is free". Refusing is the fix. if (o.stage_timing) { if (!o.no_capture) { std::fprintf(stderr, "strata generate: --stage-timing records CUDA events inside the layer path, " "and an event record inside a stream capture is silently dropped. Pass " "--no-capture as well.\n"); return 2; } if (!strata::core::stage_timing_enable()) { std::fprintf(stderr, "strata generate: stage_timing_enable failed\n"); return 1; } strata::core::stage_timing_name(0, "gr_read (attn)"); strata::core::stage_timing_name(1, "attention block"); strata::core::stage_timing_name(2, "gr_write (attn)"); strata::core::stage_timing_name(3, "gr_read (ffn)"); strata::core::stage_timing_name(4, "moe_route"); strata::core::stage_timing_name(5, "moe_finish"); strata::core::stage_timing_name(6, "gr_write (ffn)"); // The GDN block's internals. It is 36 of the 48 layers, 0.96 ms each, and its entire weight traffic // is ~26 MB - so ~0.11 ms at the measured read rate. ~13 tiny latency-bound launches live in it and // a single "attention block" number cannot say which one costs anything. strata::core::stage_timing_name(8, " gdn: quantize x"); strata::core::stage_timing_name(9, " gdn: qkv gemv"); strata::core::stage_timing_name(10, " gdn: conv+silu"); strata::core::stage_timing_name(11, " gdn: l2 norms"); strata::core::stage_timing_name(12, " gdn: alpha/beta/gate"); strata::core::stage_timing_name(13, " gdn: gdn_step"); strata::core::stage_timing_name(14, " gdn: z + out_norm"); strata::core::stage_timing_name(15, " gdn: out gemv"); } std::FILE* routing = nullptr; if (!o.dump_routing.empty()) { if (o.no_pool) { std::fprintf(stderr, "strata generate: --dump-routing needs the expert pool; the routed ids reach " "the host through the doorbell the pool reads. Drop --no-pool.\n"); return 2; } routing = std::fopen(o.dump_routing.c_str(), "wb"); if (routing == nullptr) { std::fprintf(stderr, "strata generate: cannot write %s\n", o.dump_routing.c_str()); return 1; } drive.routing = routing; } strata::core::PoolFn pool_fn = o.no_pool ? nullptr : &drive_pool; // The hit hook rides the same switch as the pool: with no pool there is no `parts` staging to // write into, and a hit path with nowhere to write is a wrong token rather than an error. strata::core::HitFn hit_fn = (o.no_pool || o.expert_cache <= 0) ? nullptr : &strata::core::expert_hit_run; void* pool_user = o.no_pool ? nullptr : (void*) &drive; std::fprintf(stderr, "strata generate: %d expert-pool workers%s%s\n", pool.workers(), pool.host_works() ? " + the host thread" : "", o.no_pool ? " (UNUSED: --no-pool)" : ""); // **THE MISALIGNMENT WARNING THAT STOOD HERE IS GONE, BECAUSE THE MISALIGNMENT IS FIXED.** // // It said the tokens were not the model's, and it was true: `session_loop` handed layer `l`'s expert // outputs to layer `l+1`, which multiplied them by layer `l+1`'s router weights (LEDGER L100). The loop // now runs a captured PAIR per layer - `pre[l]` ending with the router and the doorbell, then the CPU // pool, then `post[l]` which combines those experts with THAT layer's weights - so layer `l`'s experts meet // layer `l`'s routing. The generated ids changed the moment it landed, which is what a correctness fix // looks like from the outside. // // The cost is real and is recorded rather than hidden: the window for the CPU pool is now whatever GPU // work follows the ring inside `pre[l]`, which is the shared expert and nothing else - 0.038 ms against // 0.514 ms of CPU work per layer. A per-layer CPU expert pool cannot be hidden behind a strictly serial // residual chain; the CPU term is answered by Phase 3's VRAM expert cache, not by this pipeline. // ---- the graphs strata::core::SessionGraphs gr; if (!o.no_capture && !native_pack) { // plan v0.3 P6: a native pack runs verify windows only // a layer split's CUDA0 session owns only [0, split_at[0]), so its graphs cover that range; the // whole-model replay paths (`session_loop`, the plain generate loop) refuse rather than read another // stage's state - a split runs its layers on the stages' verifiers (serve) or prefill stage chain if (!strata::core::session_capture(wt, g, ss, d_parts, gr, err, /*split=*/o.gpu_stages, 0, multi_gpu ? split_at[0] : -1)) { std::fprintf(stderr, "strata generate: session_capture: %s\n", err.c_str()); return 1; } } // **`--no-capture` AND THE EXPERTS ARE MUTUALLY EXCLUSIVE, AND SILENTLY SO.** // // The CPU expert pool is wired into `session_loop` - the host loop around the captured graphs - and // `session_token` has no pool hook at all. So `--no-capture` did not merely change HOW the layers were // launched: it ran the whole model with `parts` left at whatever the buffer held, which is ZERO, and the // only symptom was `expert blobs 0` in a stats line nobody had to read. A run that silently omits the // routed experts is not a slow measurement of this model, it is a measurement of a different model. // // Refusing is the fix. `--no-pool` is the explicit way to say "I want the GPU-only floor". if (o.no_capture && !o.no_pool) { std::fprintf(stderr, "strata generate: --no-capture runs `session_token`, which has NO CPU expert pool hook, so " "the routed experts would silently contribute nothing. Pass --no-pool as well if the " "GPU-only floor is what you want.\n"); return 2; } // The ladder is written by `session_loop`, and `session_token` does not touch the staging buffer at all - so // accepting the flag there would produce a file of uninitialised memory, which reads as a wrong answer rather // than as a mistake. `--no-capture` without `--no-pool` is already refused above, so this catches the pair. if (o.no_capture && !o.dump_layers.empty()) { std::fprintf(stderr, "strata generate: --dump-layers is written by `session_loop`; `--no-capture` runs " "`session_token` instead, which never fills the staging buffer. Drop one of the two.\n"); return 2; } if (o.no_capture && !o.dump_halves.empty()) { std::fprintf(stderr, "strata generate: --dump-halves is CAPTURED into the layer graphs, so it needs the " "captured path; `--no-capture` never records it. Drop one of the two.\n"); return 2; } mem_mark("the expert cache and the graphs"); std::fprintf(stderr, "strata generate: session is up (engine %s)\n", STRATA_VERSION); auto run_head = [&](void* stream) -> bool { if (!native_head.loaded()) return strata::core::lm_head(wt, g, ss.block, d_logits, stream, err); return strata::core::lm_head_mix(wt, g, ss.block, stream, err) && native_head.run(ss.block.mixed, d_logits, stream, err); }; float* d_emb = nullptr; if (cudaMalloc(&d_emb, (size_t) g.n_embd * 4) != cudaSuccess) { std::fprintf(stderr, "strata generate: the embedding buffer failed\n"); return 1; } // **`sample_tokens` TAKES DEVICE POINTERS.** It is a kernel launch; `logits` and `out` are both read and // written on the device. Passing `logits.data()` - the host vector - faults inside the kernel and the // error surfaces at the NEXT synchronising call, which here was the next token's `embed_row`, reporting an // illegal access on a weight plane. Nothing in the parameter names said device. int* d_next = nullptr; if (cudaMalloc(&d_next, sizeof(int)) != cudaSuccess) { std::fprintf(stderr, "strata generate: the sampler output buffer failed\n"); return 1; } // **`R` IS BOTH THE INPUT AND THE OUTPUT, SO THE NEW TOKEN'S EMBEDDING HAS TO REPLACE THE OLD RESIDUAL.** // At `pos == 0` that is `session_zero`, which is the reference's own initial condition - the embedding // broadcast to all `hc` streams. After that `session_zero` would also wipe the recurrence, so the // broadcast is done directly. Getting this wrong is invisible for exactly one token. void* token_stream = o.stream_token ? main_cs : nullptr; auto put_input = [&](int64_t tok, int64_t pos) -> bool { if (!strata::core::embed_row(wt, g, tok, d_emb, token_stream, err)) { std::fprintf(stderr, "strata generate: %s\n", err.c_str()); return false; } if (pos == 0) { strata::core::session_zero(ss, g, d_emb, token_stream); } else { for (int64_t c = 0; c < g.hc; ++c) if (cudaMemcpyAsync(ss.R + (size_t) c * g.n_embd, d_emb, (size_t) g.n_embd * 4, cudaMemcpyDeviceToDevice, (cudaStream_t) token_stream) != cudaSuccess) { std::fprintf(stderr, "strata generate: the residual broadcast failed\n"); return false; } } return o.stream_token || cudaDeviceSynchronize() == cudaSuccess; }; strata::kernels::SamplerParams sp; sp.greedy = o.greedy; sp.seed = o.seed; sp.top_k = o.top_k; sp.top_p = o.top_p; sp.temperature = o.temperature; // what this run actually samples with (the speculative loop below gets the same parameters); serve samples // per request instead if (!o.serve) { if (sp.greedy || sp.temperature <= 0.0f) std::fprintf(stderr, "strata generate: sampling greedy\n"); else std::fprintf(stderr, "strata generate: sampling temperature=%g top_k=%d top_p=%g seed=%llu\n", (double) sp.temperature, sp.top_k > 0 && sp.top_k < 64 ? sp.top_k : 64, (double) sp.top_p, (unsigned long long) sp.seed); } std::FILE* dump = nullptr; // The logits header is written WITH THE FIRST ROW, not at open: a native pack never reaches the // per-token dump site, and a header promising rows that were never written is worse than no file. int32_t hdr[2] = {0, 0}; bool hdr_written = false; const int64_t dump_positions = (int64_t) o.tokens.size() - 1 + o.max_new; if (!o.dump_logits.empty()) { if (dump_positions > INT32_MAX || n_vocab > INT32_MAX) { std::fprintf(stderr, "strata generate: logits dump dimensions exceed int32\n"); return 2; } dump = std::fopen(o.dump_logits.c_str(), "wb"); if (dump == nullptr) { std::fprintf(stderr, "strata generate: cannot write %s\n", o.dump_logits.c_str()); return 1; } // **THE COUNT IS `n_prompt - 1 + max_new`, NOT `n_prompt + max_new`.** The loop writes one row per // position from 0, and it stops once `produced` holds `max_new` tokens - and `produced` only starts // receiving at position `n_prompt - 1`. So a 5-token prompt with `--max-new 6` writes 10 rows, and the // header used to claim 11. A header that describes a different file from the one written is the same // class of defect as a self-check that verifies the wrong invariant: anything reading the count instead // of the size gets a wrong answer that looks authoritative. `tools/logits_identical.py` caught it by // parsing the header and refusing the file. const int32_t n_rows = (int32_t) strata::program::logits_selection::row_count(dump_positions, o.logits_stride); hdr[0] = n_vocab; hdr[1] = n_rows; } // ---- THE C1 ORACLE: ONE RESIDUAL SNAPSHOT PER LAYER PER POSITION, so the engine can be bisected against // `llama-debug`'s `l_last-` node instead of against a single end-to-end perplexity. The buffer is // PINNED because `session_loop` enqueues a device-to-host copy into it after every layer and the transfer // would otherwise be staged through a pageable bounce buffer on the critical path. std::FILE* layer_dump = nullptr; float* layer_stage = nullptr; const size_t layer_floats = (size_t) (g.n_layers + 1) * (size_t) g.hc * (size_t) g.n_embd; if (!o.dump_layers.empty()) { layer_dump = std::fopen(o.dump_layers.c_str(), "wb"); if (layer_dump == nullptr) { std::fprintf(stderr, "strata generate: cannot write %s\n", o.dump_layers.c_str()); return 1; } if (cudaHostAlloc((void**) &layer_stage, layer_floats * sizeof(float), cudaHostAllocDefault) != cudaSuccess) { std::fprintf(stderr, "strata generate: cannot pin the layer-dump staging buffer\n"); return 1; } } // ---- prefill is the DECODE PATH ONE TOKEN AT A TIME, which `phase-2-correct-engine.md:12-13` says is // fine here: "process the prompt through the decode-style graphs in small batches; a 19K-token prompt will // take minutes". A real batched prefill is P2.S6's other half and is not this. // // **THE LOOP IS `feed -> 48 layers -> head -> sample -> feed`, AND THE FIRST GENERATED TOKEN COMES FROM THE // LAST *PROMPT* POSITION.** The first version sampled only on the decode positions, so `produced` was // still empty when the first generated position asked for `produced.back()` - an out-of-bounds read on an // empty vector. Teacher forcing below is what makes the distinction unnecessary to special-case: for every // position before the last prompt one, the next input is the PROMPT's next token, and after that it is the // sampled one. std::vector produced; double total_ms = 0; double prefill_ms = 0; // positions 0 .. n_prompt-2: prompt tokens that only condition const Clock::time_point t_start = Clock::now(); double ttft_ms = 0; const int64_t n_prompt = (int64_t) o.tokens.size(); int64_t tok = o.tokens[0]; // ---- THE PURE-GPU MEASUREMENT. `session_replay` launches all 48 `pre` graphs back to back on one stream // with NO host work between them - no doorbell poll, no pool, no parts copy - so what it times is the GPU // executing the layer sequence and nothing else. It had been declared, defined and never called since the // day it was written. // // **THIS IS THE MEASUREMENT THAT SAYS WHETHER THE ENGINE IS HOST-BOUND OR GPU-BOUND**, and the stage table // cannot answer it: those events measure the interval between two marks on a stream, which includes every // gap where the GPU sat idle waiting for the host to enqueue the next kernel. In `--no-capture` those gaps // are the host's launch latency and they are proportional to the KERNEL COUNT rather than to any work, so // the no-capture stage shares are shares of kernel count - which is why the attention block, with the most // kernels, looks like 55% of the token there. // ---- R0.9: THE PER-STAGE TABLE ON THE CAPTURED GRAPH. if (o.gpu_stages) { strata::core::doorbell_reset(db); double mix = 0, ffn = 0, post = 0; if (!strata::core::session_replay_stages(g, 0, 0, ss, gr, main_cs, mix, ffn, post, err)) { // #610: a native (IQ) pack captures no per-layer graphs; the serve path times its window's stages std::fprintf(stderr, "strata generate: %s%s\n", err.c_str(), native_pack ? " - a native (IQ) pack has no per-layer graphs to replay. Its decode window's GPU " "stages are printed per request by the serve path instead: STRATA_VERIFY_PROFILE=1 " "STRATA_DECODE_TIMING=1 with --serve (docs/DETAILS.md, \"Where a decode window's " "time goes\")" : ""); return 1; } const int reps = 20; double t_mix = 0, t_ffn = 0, t_post = 0; for (int r = 0; r < reps; ++r) { if (!strata::core::session_replay_stages(g, 0, 0, ss, gr, main_cs, mix, ffn, post, err)) { std::fprintf(stderr, "strata generate: %s\n", err.c_str()); return 1; } t_mix += mix; t_ffn += ffn; t_post += post; } const double tot = t_mix + t_ffn + t_post; std::printf("\nper-stage GPU time on the CAPTURED graph, one token over %lld layers\n", (long long) g.n_layers); std::printf(" %-22s %9.3f ms/token %8.3f ms/layer %6.1f%%\n", "mixer (gr_read+attn+gr_write)", t_mix / reps, t_mix / reps / (double) g.n_layers, 100.0 * t_mix / tot); std::printf(" %-22s %9.3f ms/token %8.3f ms/layer %6.1f%%\n", "ffn front + router", t_ffn / reps, t_ffn / reps / (double) g.n_layers, 100.0 * t_ffn / tot); std::printf(" %-22s %9.3f ms/token %8.3f ms/layer %6.1f%%\n", "post (moe_finish+gr_write)", t_post / reps, t_post / reps / (double) g.n_layers, 100.0 * t_post / tot); std::printf(" %-22s %9.3f ms/token\n", "sum of the three", tot / reps); // ---- AND THE MIXER BY LAYER KIND, because 36 of the 48 are GDN and 12 are QSA and a total cannot // separate them. Round 309's uncaptured table put GDN at 10.88 ms for 36 layers against QSA's 4.56 for // 12, which would make the recurrence the largest single R3 target - and that table had `moe_finish` // wrong by 4x, so the ratio is re-derived here from the captured graph rather than inherited. { // **ACCUMULATED OVER `reps`, NOT MEASURED ONCE AND THEN DIVIDED.** The first version called the // per-layer replay a single time and printed `gdn / reps`, which reported GDN at 0.480 ms/token // against a mixer total of 14.039 - a factor of exactly `reps`, and the tell was that // 0.480 + 0.220 = 0.700 = 14.039 / 20. std::vector acc((size_t) g.n_layers, 0.0), per; double f2 = 0, p2 = 0; for (int r = 0; r < reps; ++r) { if (!strata::core::session_replay_stages_per_layer(g, 0, 0, ss, gr, main_cs, per, f2, p2, err)) { std::fprintf(stderr, "strata generate: %s\n", err.c_str()); return 1; } for (int64_t l = 0; l < g.n_layers; ++l) acc[(size_t) l] += per[(size_t) l]; } double gdn = 0, qsa = 0, worst = 0; int64_t ng = 0, nq = 0, worst_l = 0; for (int64_t l = 0; l < g.n_layers; ++l) { const double v = acc[(size_t) l] / reps; if (strata::core::is_qsa_layer(g, l)) { qsa += v; ++nq; } else { gdn += v; ++ng; } if (v > worst) { worst = v; worst_l = l; } } std::printf("\n the mixer by layer kind, averaged over %d runs\n", reps); std::printf(" %-22s %9.3f ms/token %8.3f ms/layer (%lld layers)\n", "GDN layers", gdn, ng ? gdn / (double) ng : 0.0, (long long) ng); std::printf(" %-22s %9.3f ms/token %8.3f ms/layer (%lld layers)\n", "QSA layers", qsa, nq ? qsa / (double) nq : 0.0, (long long) nq); std::printf(" %-22s layer %lld at %.3f ms\n", "worst mixer layer", (long long) worst_l, worst); std::printf(" %-22s %9.3f ms/token (must equal the mixer above)\n", "GDN + QSA", gdn + qsa); } // ================================ R0.11: THE FIVE STAGES SEPARATELY ================================ // // Prefixes 1..5 are replayed per layer with the residual restored between them, and consecutive // differences are the per-stage times. **THE CHECK IS THAT THE FIVE SUM TO THE THREE-GRAPH TOTAL** - // the same independent-restatement test that caught round 320's divide-by-reps bug, and it is the only // reason to believe a table built out of differences. { std::vector acc5(5, 0.0), per, s5; for (int r = 0; r < reps; ++r) { if (!strata::core::session_replay_stage_prefixes(g, 0, 0, ss, gr, main_cs, s5, per, err)) { std::fprintf(stderr, "strata generate: %s\n", err.c_str()); return 1; } for (int k = 0; k < 5; ++k) acc5[(size_t) k] += s5[(size_t) k]; } static const char* sn[5] = {"0 gr_read (attn)", "1 attention", "2 gr_write (attn)", "3 gr_read (ffn)", "4 moe_route (router)"}; const char* kind[5] = {"GR", "ATTN", "GR", "GR", "ROUTER"}; double tot5 = 0, gr_ms = 0; std::printf("\n the five stages separately, by differencing prefixes\n"); std::printf(" %-24s %-8s %10s %10s %8s\n", "stage", "kind", "ms/token", "ms/layer", "share"); for (int k = 0; k < 5; ++k) { const double v = acc5[(size_t) k] / reps; tot5 += v; if (k != 1 && k != 4) gr_ms += v; std::printf(" %-24s %-8s %10.3f %10.4f %7.1f%%\n", sn[k], kind[k], v, v / (double) g.n_layers, 0.0); } for (int k = 0; k < 5; ++k) { const double v = acc5[(size_t) k] / reps; (void) v; } std::printf(" %-24s %-8s %10.3f\n", "sum of the five", "", tot5); std::printf(" %-24s %-8s %10.3f <- R3.3's target is <= 3 ms for all four passes\n", "GR passes (0,2,3)", "GR", gr_ms); std::printf("\n the three-graph total above was %.3f ms/token; the five must account for it.\n", tot / reps); // ================================ R3.5c: THE SAME TABLE, A DIFFERENT WAY ================================ // // The differencing table above mixes five graphs per layer, so stage 4's interval carries the launch // of the FULL five-stage graph while stage 3's carries a four-stage one. This sweep launches ONE // graph type per layer and nothing else, so that bias cannot exist. **If the two disagree, the // difference IS the bias and this one is right** - and stage 4 is the router, so it is exactly the // number that must not be wrong. { double sweep[6] = {0, 0, 0, 0, 0, 0}; for (int k = 1; k <= 5; ++k) { double acc = 0, one = 0; for (int r = 0; r < reps; ++r) { if (!strata::core::session_replay_stage_sweep(g, 0, 0, ss, gr, main_cs, k, one, err)) { std::fprintf(stderr, "strata generate: %s\n", err.c_str()); return 1; } acc += one; } sweep[k] = acc / reps; } std::printf("\n the same five stages, by SWEEPING each prefix back to back (no graph switching)\n"); std::printf(" %-24s %10s %10s %12s\n", "stage", "prefix sweep", "difference", "bias"); static const char* sn2[5] = {"0 gr_read (attn)", "1 attention", "2 gr_write (attn)", "3 gr_read (ffn)", "4 moe_route (router)"}; for (int k = 0; k < 5; ++k) { const double sw = sweep[k + 1] - sweep[k]; const double df = acc5[(size_t) k] / reps; std::printf(" %-24s %10.3f %10.3f %11.1f%%\n", sn2[k], sw, df, sw != 0.0 ? 100.0 * (df / sw - 1.0) : 0.0); } std::printf(" %-24s %10.3f (full pre, 48 layers)\n", "prefix 5 total", sweep[5]); } } std::printf("\n compare `--gpu-only-full`, which replays the same work as TWO graphs per layer. The\n"); std::printf(" three sum slightly above it because each launch carries the driver's gap.\n"); strata::core::session_graphs_free(gr); strata::core::doorbell_free(db); cudaFree(d_next); return 0; } if (o.graph_only) { strata::core::doorbell_reset(db); // one warm pass so the first launch does not pay for page mapping if (!strata::core::session_replay(g, 0, 0, ss, gr, main_cs, err)) { std::fprintf(stderr, "strata generate: session_replay warm: %s\n", err.c_str()); return 1; } if (cudaDeviceSynchronize() != cudaSuccess) { std::fprintf(stderr, "strata generate: session_replay warm faulted\n"); return 1; } const int reps = 20; const Clock::time_point t0 = Clock::now(); for (int r = 0; r < reps; ++r) { if (!strata::core::session_replay(g, 0, 0, ss, gr, main_cs, err)) { std::fprintf(stderr, "strata generate: session_replay: %s\n", err.c_str()); return 1; } } if (cudaDeviceSynchronize() != cudaSuccess) { std::fprintf(stderr, "strata generate: session_replay faulted: %s\n", cudaGetErrorString(cudaGetLastError())); return 1; } const double ms = std::chrono::duration(Clock::now() - t0).count() / (double) reps; std::printf("pre graphs only %8.2f ms per token over %lld layers -> %.2f tok/s of GPU work\n", ms, (long long) g.n_layers, ms > 0 ? 1000.0 / ms : 0.0); std::printf(" %8.3f ms per layer\n", ms / (double) g.n_layers); return 0; } // ---- R0.3: THE TRUE PER-TOKEN GPU FLOOR. // // `--graph-only` above launches ONLY `gr.execs[l]`, the `pre` graphs. It omits the 48 `post` graphs - the // shared expert, the combine and the second `gr_write` - and the LM head. Everything this project published // as "39.8 ms pure GPU" came from that loop while being described as the whole GPU, which also made the // "host's share = 49.4 - 39.8 = 9.6 ms" figure wrong by however much the missing work costs. See // Memory/ERRORS.md A4/A5. // // This flag is what "pure GPU" has to mean, and it replaces that number everywhere. No pool runs, so // `parts` keeps whatever the buffer holds and the timing is GPU work alone. if (o.gpu_only_full) { strata::core::doorbell_reset(db); const int reps = 20; double ms_layers = 0, ms_head = 0; for (int r = -1; r < reps; ++r) { // r == -1 is the warm pass, not counted const Clock::time_point t0 = Clock::now(); if (!strata::core::session_replay_full(g, 0, 0, ss, gr, main_cs, err)) { std::fprintf(stderr, "strata generate: session_replay_full: %s\n", err.c_str()); return 1; } // The sync is INSIDE the interval on purpose: it is the wait for the GPU, so t1 - t0 is GPU time. if (cudaStreamSynchronize((cudaStream_t) main_cs) != cudaSuccess) { std::fprintf(stderr, "strata generate: gpu-only-full layers faulted: %s\n", cudaGetErrorString(cudaGetLastError())); return 1; } const Clock::time_point t1 = Clock::now(); if (!run_head(main_cs)) { std::fprintf(stderr, "strata generate: gpu-only-full lm_head: %s\n", err.c_str()); return 1; } if (cudaStreamSynchronize((cudaStream_t) main_cs) != cudaSuccess) { std::fprintf(stderr, "strata generate: gpu-only-full head faulted: %s\n", cudaGetErrorString(cudaGetLastError())); return 1; } const Clock::time_point t2 = Clock::now(); if (r < 0) continue; ms_layers += std::chrono::duration(t1 - t0).count(); ms_head += std::chrono::duration(t2 - t1).count(); } ms_layers /= (double) reps; ms_head /= (double) reps; const double ms = ms_layers + ms_head; std::printf("GPU floor pre+post+head %7.2f ms per token -> %.2f tok/s of GPU work\n", ms, ms > 0 ? 1000.0 / ms : 0.0); std::printf(" %8.3f ms layers (%lld x pre+post)\n", ms_layers, (long long) g.n_layers); std::printf(" %8.3f ms per layer\n", ms_layers / (double) g.n_layers); std::printf(" %8.3f ms LM head\n", ms_head); return 0; } // ---- **THE TOKEN PATH ALLOCATES NOTHING (P2.T10, review finding H3).** // // `session_loop` used to allocate its pinned staging buffer, its probe event and its host pin ON EVERY // TOKEN, and `cudaFreeHost` at the end of each call implicitly synchronises the device - so every token // finished with a device-wide sync nobody asked for. The scratch is created once here and reused; it also // owns the host pin for the whole session rather than taking and releasing it per token. strata::core::SessionLoopScratch loop_scratch; struct ScratchFree { strata::core::SessionLoopScratch* p; ~ScratchFree() { if (p != nullptr) p->free(); } } scratch_free{&loop_scratch}; // Initialised unconditionally, including under --no-pool: the loop validates the scratch it is handed, so // passing a default-constructed one is an error rather than a fallback. (It was, and the guard caught it - // which is the point of the guard.) One allocation at setup either way. if (!loop_scratch.init((size_t) K * g.n_embd * 4, err)) { std::fprintf(stderr, "strata generate: %s\n", err.c_str()); return 1; } // Plan v0.3 P3: the whole token as ONE graph whenever nothing needs a host step between the ring and post[l] // (the VRAM expert tier and the per-layer dumps do). `--no-token-graph` keeps two graphs per layer. strata::core::TokenGraph tgraph; struct TokenGraphFree { strata::core::TokenGraph* p; ~TokenGraphFree() { strata::core::token_graph_free(*p); } } tgraph_free{&tgraph}; // Plan v0.3 P4: with a PROFILE-filled cache the residency is static, so the hit decision moves onto the // device and the token graph keeps it. (A cache filled on demand still needs the per-layer host path.) std::vector host_res; // The residency table is read by kernels on non-blocking streams, which do not wait for the legacy stream a plain // cudaMemcpy runs on, and a pageable copy can return before its DMA has landed: each upload waits for its own copy // (the current device's legacy stream, stream 0 - nothing else; HIP has no cudaStreamLegacy name, #550). auto res_put = [&host_res](int32_t* dst) -> cudaError_t { const cudaError_t e = cudaMemcpy(dst, host_res.data(), host_res.size() * sizeof(int32_t), cudaMemcpyHostToDevice); return e != cudaSuccess ? e : cudaStreamSynchronize(nullptr); }; int32_t* d_res = nullptr; int32_t* d_hit_count = nullptr; strata::core::TokenHits thits; const bool graph_hits = hit_fn != nullptr && !profile.empty() && !o.no_pool; if (graph_hits && !o.no_capture && !o.no_token_graph && layer_dump == nullptr && half_dump == nullptr) { host_res.assign((size_t) (g.n_layers * g.n_expert), strata::core::kNotResident); int64_t resident = 0; for (int64_t l = 0; l < g.n_layers; ++l) for (int64_t e = 0; e < g.n_expert; ++e) { const int st = multi_gpu ? stage_of(l) : 0; const int32_t slot = st > 0 ? stages[(size_t) st - 1]->cache.slot_of(l, e) : xcache.slot_of(l, e); host_res[(size_t) (l * g.n_expert + e)] = slot; if (slot != strata::core::kNotResident) ++resident; } if (cudaMalloc((void**) &d_res, host_res.size() * sizeof(int32_t)) != cudaSuccess || cudaMalloc((void**) &d_hit_count, sizeof(int32_t)) != cudaSuccess || res_put(d_res) != cudaSuccess) { std::fprintf(stderr, "strata generate: the device residency table could not be staged\n"); return 1; } thits.d_res = d_res; thits.n_expert = g.n_expert; // a file-backed arena (STRATA_ARENA_MMAP): the experts no GPU holds are the ones the CPU pool and the // prompt path will read - start reading them now instead of faulting them in 4 KB at a time mid-request // ... and the ones a GPU holds are handed back first (STRATA_ARENA_RELEASE=0 keeps them): the fill read the // whole arena, and left mapped and referenced it crowds every other allocation into swap { static const bool keep = std::getenv("STRATA_ARENA_RELEASE") && std::getenv("STRATA_ARENA_RELEASE")[0] == '0'; rss_probe("before the release"); uint64_t released = 0; if (!keep) for (size_t i = 0; i < host_res.size(); ++i) if (host_res[i] != strata::core::kNotResident) released += srcp->release((int64_t) i / g.n_expert, (int64_t) i % g.n_expert); if (released > 0) std::fprintf(stderr, "strata generate: expert arena: %.2f GiB of VRAM-held experts handed back to the OS\n", (double) released / (1024.0 * 1024.0 * 1024.0)); rss_probe("after the release"); int64_t pf = 0; for (size_t i = 0; i < host_res.size(); ++i) if (host_res[i] == strata::core::kNotResident) { srcp->prefetch((int64_t) i / g.n_expert, (int64_t) i % g.n_expert); ++pf; } (void) pf; rss_probe("after the prefetch hints"); } for (auto& st : stages) { // layer split across GPUs: the same table on every device const strata::core::OnDevice on(st->dev); if (cudaMalloc((void**) &st->d_res, host_res.size() * sizeof(int32_t)) != cudaSuccess || res_put(st->d_res) != cudaSuccess) { std::fprintf(stderr, "strata generate: layer split: CUDA%d residency table failed\n", st->dev); return 1; } } thits.cache_base = drive.d.cache_base; thits.blob = drive.d.cache_blob; thits.d_slot = drive.d.d_slot; thits.d_dst = drive.d.d_dst; thits.d_count = d_hit_count; thits.x_q8 = drive.d.x_q8_0_hit; thits.x_scale = drive.d.x_q8_0_hit_scale; thits.scratch = drive.d.hit_scratch; thits.hit_out = drive.d.hit_out; drive.d.host_res = host_res.data(); std::fprintf(stderr, "strata generate: token graph hit path: %lld resident experts, decided on the device\n", (long long) resident); } if (!o.no_capture && !o.no_token_graph && layer_dump == nullptr && half_dump == nullptr && (hit_fn == nullptr || thits.on()) && !native_pack && !multi_gpu) { // a split's token graph cannot span stages if (!strata::core::session_capture_token(wt, g, ss, d_parts, loop_scratch.y_miss, loop_scratch.parts_bytes, tgraph, err, thits.on() ? &thits : nullptr)) { std::fprintf(stderr, "strata generate: %s\n", err.c_str()); return 1; } std::fprintf(stderr, "strata generate: token graph captured (48 layers, one launch per token)\n"); } // ================================ WHERE THE HOST TERM GOES, PER TOKEN ================================ // // **`--gpu-only-full` MEASURES THE 48 LAYER GRAPHS AND THE LM HEAD AND NOTHING ELSE.** It never enters // this loop, so it does not run `ple_stage_token`, `embed_row`, the whole-vocabulary logits readback, the // NaN scan or the sampler - and `--no-pool --stats` against that floor was being read as "the per-layer // round trip costs 12.4 ms" when an unknown part of it is per TOKEN, not per layer. That is the same error // the review catalogued as A4/A5, one level down: a difference between two measurements attributed to a // mechanism that neither of them isolates. // // Six accumulators, because the six have different fixes. Reported in `--stats` as ms/token. **The // boundary after the layer loop is the one that matters**: without it the head's interval swallows all 48 // layers and the report reads as "head = 50 ms", which is not a thing that can happen to 1.4 ms of GPU // work. That is not hypothetical - it is what the first version of this printed. double ms_ple = 0, ms_embed = 0, ms_layers = 0, ms_head = 0, ms_readback = 0, ms_sample = 0; int64_t phase_tokens = 0; // ================================ plan v0.3 P8: THE PERSISTENT ENGINE (--serve) ================================ // // The weights, the expert arena and the VRAM tier load once; then requests arrive on stdin, one per line, // // GEN // // and each generated token is written to stdout as `T ` as soon as its verify window is done, followed by // // DONE // ... (see the DONE line below; #471) // // `nonfinite` (#879): a window's head logits held a NaN or an infinity (Verifier::nonfinite_row). None of that // window's tokens was written; every state that may carry the poison (the live session, the checkpoints, the // parked conversations, the idle batch slots) is dropped at the next request's start, which reads its prompt from // token 0. A batch slot ends the same way: `BDONE nonfinite`. // // Before that, `RESUME ` (n prompt tokens are not read again), `PP ` // after every prompt chunk, and `REUSED ` once the prompt is read. (`ERR ` instead when a request // cannot run; `STOP` ends the running request at its next step; `QUIT` ends the process.) A request continues // from the live session or the longest conversation checkpoint its prompt starts with (see ConvCheckpoint), // otherwise from an empty sequence (`session_zero`); the rest of the prompt goes through the batched prompt path // and its last token through the first verify window - the path all three model files share. Decoding is greedy. // The expert-cache slots (from the end of the cache) that hold the prompt path's buffers for a chunk, and the // bytes from the first of them to the end. // the share of expert bytes the arena could pin (sizes the prompt path's streamed ring and its lend cap) if (srcp != nullptr && o.prefill_chunk > 0) { uint64_t pinned = 0, total = 0; const auto& lay = strata::kernels::cpu::expert_layout(); for (int64_t l = 0; l < g.n_layers; ++l) for (int64_t e = 0; e < g.n_expert; ++e) { const uint64_t b = lay.blob_bytes(l); total += b; if (srcp->pinned(l, e)) pinned += b; } double share = total ? (double) pinned / (double) total : 1.0; if (const char* t = std::getenv("STRATA_TEST_PINNED_SHARE")) share = std::atof(t); // tests: the Windows-like ring rule strata::prefill::Prefill::set_pinned_share(share); } // bytes -> slots for CUDA0's cache: exact when it knows its per-slot offsets (a native pack's blobs differ // per layer), otherwise max_blob each. auto slots_from_bytes = [&](uint64_t need) -> int64_t { const int64_t blob = (int64_t) strata::kernels::cpu::expert_layout().max_blob; int64_t k = (int64_t) ((need + (uint64_t) blob - 1) / (uint64_t) blob); if (xcache.slot_offsets() != nullptr) { // sized slots: take slots from the end until they hold `need` k = 0; while (k < xcache.slots() && (uint64_t) (xcache.bytes() - (int64_t) xcache.slot_offsets()[xcache.slots() - k]) < need) ++k; } return k; }; // ...and its inverse, for the ring's room: the bytes the cache's last `k` slots hold. k can arrive <= 0: the // caller's lend budget is `min(slots - 128, pct * slots / 100)` and goes negative on a cache smaller than 128 // slots, where `slots - k` would index slot_offsets() past its end. Such a cache lends nothing, so say so. auto bytes_from_slots = [&](int64_t k) -> uint64_t { if (k <= 0) return 0; if (xcache.slot_offsets() != nullptr) return (uint64_t) (xcache.bytes() - (int64_t) xcache.slot_offsets()[xcache.slots() - k]); return (uint64_t) k * (uint64_t) strata::kernels::cpu::expert_layout().max_blob; }; auto lend_slots = [&](int64_t c) -> int64_t { return slots_from_bytes(strata::prefill::Prefill::bytes_needed(g, ss, c, srcp != nullptr)); }; // `lend_bytes` went with the single-cache serve loan: a participant's loan is priced by `part_bytes` from its // OWN cache, and the only other user of the old helper was the serve path's own relayout. auto request_chunk = [](int64_t tokens, int64_t max_chunk) -> int64_t { if (tokens <= 0 || max_chunk <= 0) return 0; const int64_t rounded = tokens > std::numeric_limits::max() - 255 ? tokens : ((tokens + 255) / 256) * 256; return std::min(max_chunk, rounded); }; // The loan is sized from the walk the piece takes. The chunk above is rounded UP to the 256 grid, but the walk is decided from // the real token count (a piece below stream_all_min() walks staged), so a 999-token piece under a 1,024 floor was lent the // streamed layout's 512-slot ring and fused buffers while it walked staged: 478 more experts streamed per prompt, 275 ms at 1,000 // tokens (RTX A6000). Applies to every piece within 255 tokens under the floor (769-1,023 at 1,024; 2,817-3,071 under the CPU // share's 3,072). STRATA_PREFILL_LOAN_WALK=0 keeps the rounded chunk. static const bool loan_by_walk = [] { const char* e = std::getenv("STRATA_PREFILL_LOAN_WALK"); return !(e != nullptr && e[0] == '0'); }(); // The lent fused layout's MMQ tail is sized from the segment's own last chunk, not from the stream floor (a floor of 3,584 // against 1,024 costs ~92 expert slots on an RTX A6000, streamed again by every chunk above the floor). One GPU, no peer, no // --batch above one slot, no head alias; a layer split keeps the floor's tail. STRATA_PREFILL_TAIL_LOAN=0 keeps today's size. static const bool tail_loan_on = [] { const char* e = std::getenv("STRATA_PREFILL_TAIL_LOAN"); return !(e != nullptr && e[0] == '0'); }(); // STRATA_DBG_TAIL_NOREUSE=1 (a test of the backstop): a loan is reused by chunk alone, as before the tail rule - a later short segment then // overruns the tail and the chunk check in Prefill::run_impl must end the request with its error static const bool dbg_tail_noreuse = [] { const char* e = std::getenv("STRATA_DBG_TAIL_NOREUSE"); return e != nullptr && e[0] == '1'; }(); auto loan_chunk = [&](int64_t tokens, int64_t chunk) -> int64_t { return loan_by_walk ? strata::prefill::loan_rules::walk_chunk(tokens, chunk, strata::prefill::Prefill::stream_all_min_tokens()) : chunk; }; #if defined(STRATA_PREFILL_FUSED) && !defined(STRATA_PREFILL_MMQ) // A build without MMQ (prefill.cpp STRATA_PF_OWN_ONLY): ONE GPU reads a segment longer than its chunk in n = ceil(tokens / // max_chunk) chunks of EQUAL size by default, also when today's last chunk would be under the stream floor (a sub-floor // remainder costs close to a full pass where most experts stream: RTX 5070 12 GB, Q2_0, 14,000-32,000 tokens, 0.923-1.001 of // today's time; equal_cut_rule.hpp). `one_gpu`: no layer split, no peer card, one slot, no head alias. A layer split keeps // today's cut, or with STRATA_PREFILL_EQUAL=1 the older opt-in rule below (#693); STRATA_PREFILL_EQUAL=0 keeps today's cut // everywhere. `request_chunk` is unchanged (STRATA_SPLIT_SMALL_OWN uses it too). static const strata::prefill::equal_cut::Cut equal_cut_one = strata::prefill::equal_cut::pick(std::getenv("STRATA_PREFILL_EQUAL"), true); static const strata::prefill::equal_cut::Cut equal_cut_split = strata::prefill::equal_cut::pick(std::getenv("STRATA_PREFILL_EQUAL"), false); auto equal_chunk = [&](int64_t tokens, int64_t max_chunk, bool one_gpu) -> int64_t { return strata::prefill::equal_cut::chunk(one_gpu ? equal_cut_one : equal_cut_split, tokens, max_chunk, strata::prefill::Prefill::stream_all_min_tokens()); }; // #2824: as below; a prompt with no host plan takes the cut above auto planned_chunk = [&](int64_t tokens, int64_t cap, int64_t plan, bool one_gpu) -> int64_t { if (plan <= 0 || plan >= cap || tokens <= 0) return equal_chunk(tokens, cap, one_gpu); return strata::program::prefill_plan::balanced_chunk(tokens, cap, plan); }; #else // STRATA_PREFILL_EQUAL=1 (opt-in, PR #693): a segment of `tokens` reads in n = ceil(tokens / max_chunk) chunks of EQUAL // size (ceil(tokens / n) rounded up to 256) instead of full chunks and a short last one. A chunk of // stream_all_min_tokens() or more streams every expert the GPU does not hold, whatever its length, so a prompt's cost // is its number of such chunks and equal chunks borrow no more slots than that count needs. A last chunk below // stream_all_min_tokens() stays as it is (it moves only the experts its own tokens route to). Used ONLY where a // segment's chunk is chosen (the serve lend, generate's prompt); `request_chunk` is unchanged because // STRATA_SPLIT_SMALL_OWN uses it too. The chunk geometry changes the rounding, so it is off by default. static const bool equal_chunks = [] { const char* e = std::getenv("STRATA_PREFILL_EQUAL"); return e != nullptr && e[0] == '1'; }(); auto equal_chunk = [&](int64_t tokens, int64_t max_chunk) -> int64_t { const int64_t plain = request_chunk(tokens, max_chunk); if (!equal_chunks || tokens <= 0 || max_chunk <= 0) return plain; const int64_t n = tokens / max_chunk + (tokens % max_chunk != 0); const int64_t last = tokens - (n - 1) * max_chunk; if (n <= 1 || last < strata::prefill::Prefill::stream_all_min_tokens()) return plain; const int64_t per = tokens / n + (tokens % n != 0); const int64_t rounded = per > std::numeric_limits::max() - 255 ? per : ((per + 255) / 256) * 256; return std::min(max_chunk, rounded); }; // #2824: the chunk a request of `tokens` reads in when the host-aware plan chose `plan` (< cap, the buffers' chunk = what the VRAM // scan picked). A prompt that fits one chunk of `cap` keeps ONE chunk, as before (a single pass reads each expert once, so the // page cache cannot thrash, and splitting it would only add a pass); a longer one reads in n = ceil(tokens / plan) chunks of // EQUAL size (no tiny tail), at most `cap`. auto planned_chunk = [&](int64_t tokens, int64_t cap, int64_t plan) -> int64_t { if (plan <= 0 || plan >= cap || tokens <= 0) return equal_chunk(tokens, cap); return strata::program::prefill_plan::balanced_chunk(tokens, cap, plan); }; #endif // The prompt path's chunk and the slots it borrows for its buffers: the requested chunk halved until it fits, // or with --prefill auto the largest chunk whose buffers take at most kAutoLendPct % of the slots (a // lent slot's expert is streamed during the prompt and refilled after it; measured on a 12 GB card, 32K Q2_0 // prompt: 4096 791 tok/s, 6144 878, 8192 973 with 69% of the slots lent). A request lends only what its own // prompt needs (Prefill::relayout), so a big chunk costs short prompts nothing. 0 = none fits. // at 8192-token chunks nearly every expert streams anyway, so a lent slot costs little: 90% when the // copies are DMA from pinned RAM (Q2_0 8192 + a 384-slot ring: 1283 tok/s), 85% when host copies are the // limit (lending more only streams more through them). STRATA_PREFILL_LEND_PCT overrides (tuning). // Hoisted out of plan_lend: the serve path's per-stage loans obey the same cap, one participant at a time. const int64_t kAutoLendPct = [] { const char* v = std::getenv("STRATA_PREFILL_LEND_PCT"); return v ? (int64_t) std::atoi(v) : g_lend_keep != 128 ? (int64_t) 100 // a card too short for the usual loan (see the cache sizing) lends what it must: the cap is for cards with room : (int64_t) (strata::prefill::Prefill::pinned_share() >= 0.9 ? 90 : 85); }(); // The largest chunk --prefill auto may pick: the operator's ceiling (--prefill auto:N) and never past the // context, but a bare `auto` always reaches 8192. 32768 and 16384 stay opt-in (#282): a 32K prompt with // IQ2_XS (RTX 5090, 64K context) read at 5,624 tok/s in 8192-token chunks and 6,465 in one 32768 chunk (40K // -> 18K experts streamed; an NVFP4 pack at 262K: 3,535 -> 5,201). int64_t auto_ceiling = std::max(8192, std::min(o.prefill_auto_max, o.max_context)); // 0.1.44: a layer split reads a prompt as a pipeline of chunks (the later card reads chunk c while the first reads c+1), so a // 32K prompt in two 16384 chunks fills and drains the pipe for most of its time. 8192 chunks, same tokens: 2x R9700 // pp32k +14%, 4x +19%, pp64k +4% / +16%. STRATA_SPLIT_CHUNK16K=1 keeps the gfx12 16384 ceiling on a split. if (multi_gpu && o.prefill_gfx12_16k) { static const char* keep16 = std::getenv("STRATA_SPLIT_CHUNK16K"); // (the NVIDIA rule shares this: a layer split reads 8192-token chunks) if (!(keep16 != nullptr && std::atoi(keep16) != 0)) { auto_ceiling = std::min(auto_ceiling, 8192); o.prefill_auto_max = std::min(o.prefill_auto_max, 8192); // the 0.1.39 chunk list reads this one o.prefill_chunk = std::min(o.prefill_chunk, 8192); } } // #2090 (bdwilton): the gfx12 16384 ceiling lends the prompt path about twice the slots of 8192 (R9700, Swift 1.5 // IQ3_XXS: 3,907 slots / 6.38 GiB against 2,068 / 3.37 GiB), and every lent slot's expert is read from the RAM side // during the read. On a 30 GB PC with --resident-experts that was 3.4 GB available, 20 GB in swap, 1.5M major faults // and a killed engine on 38-47K prompts; 8192 ran them at 95 tok/s. The ceiling is the engine's default, not the // user's pick, so when the RAM available now does not cover the extra loan plus 6 GiB (that PC thrashed with 3.4 GB left and // ran with ~6.4) the default stays at 8192. // STRATA_GFX12_CHUNK=1 keeps the default ceiling anyway. The ceiling is 32768 now: the guard steps it down 32768 -> 16384 -> 8192 until the loan fits. for (int64_t cand = auto_ceiling; o.prefill_gfx12_16k && cand > 8192;) { static const char* force16 = std::getenv(std::strcmp(o.prefill_raise_who, "NVIDIA") == 0 ? "STRATA_NV_CHUNK" : "STRATA_GFX12_CHUNK"); const int64_t extra_slots = std::max(0, lend_slots(cand) - lend_slots(8192)); const uint64_t extra_mib = ((uint64_t) extra_slots * strata::kernels::cpu::expert_layout().max_blob) >> 20; const auto hm = strata::core::sample_host_memory(); // the cgroup / --memory-limit-mib cap counts too const uint64_t avail_mib = hm ? hm->available >> 20 : mem_sample().avail_mib; // --resident-experts pins its RAM copy after this point, and that copy also holds the lent slots' experts: what // has to fit is every expert the cache does not hold plus the 16384 loan (R9700 IQ3_XXS: 23.35 GiB at 16384) uint64_t pin_mib = 0; if (o.resident_cpu_experts) { const uint64_t total = strata::kernels::cpu::expert_layout().total; const uint64_t cached = (uint64_t) std::max(0, (int64_t) xcache.bytes()); pin_mib = ((total > cached ? total - cached : 0) + (uint64_t) std::max(0, lend_slots(8192)) * strata::kernels::cpu::expert_layout().max_blob) >> 20; } if (avail_mib > 0 && avail_mib < pin_mib + extra_mib + 6144 && !(force16 != nullptr && std::strcmp(force16, "1") == 0)) { const int64_t next = strata::core::gfx12_chunk_step_down(cand); auto_ceiling = std::min(auto_ceiling, next); o.prefill_auto_max = std::min(o.prefill_auto_max, next); o.prefill_chunk = std::min(o.prefill_chunk, next); std::fprintf(stderr, "strata generate: %s: prompt chunks stay at %lld: %lld would lend %lld more cache slots " "(%llu MiB more held in RAM during a prompt), and %llu MiB of RAM is available for %llu MiB " "of resident experts plus that (#2090; %s=1 takes the default ceiling anyway)\n", o.prefill_raise_who, (long long) next, (long long) cand, (long long) extra_slots, (unsigned long long) extra_mib, (unsigned long long) avail_mib, (unsigned long long) pin_mib, std::strcmp(o.prefill_raise_who, "NVIDIA") == 0 ? "STRATA_NV_CHUNK" : "STRATA_GFX12_CHUNK"); cand = next; continue; } break; } if (o.prefill_auto_cap > 0) auto_ceiling = std::min(auto_ceiling, o.prefill_auto_cap); // #1630 // The auto scan used to walk a fixed list of sizes - 32768, 16384, 8192, 6144, ... - and take the first that // fit. That list is coarse exactly where a rig needs it: this one affords ~8,700 tokens and was handed 8192, // and 8704 is not on it. `bytes_needed` is a sum of (T x positive constant) terms plus a max of such sums, // so it rises monotonically with T, and so does every test the scan applies - which makes the largest size // that fits a bisection on the 256-token grid the prompt path already works on (`request_chunk` rounds up to // it). log2(32768/256) = 7 probes, against the list's 10, at one `bytes_needed` per probe. auto biggest_chunk = [](int64_t ceiling, auto&& ok) -> int64_t { if (ceiling < 256) return 0; int64_t lo = 1, hi = ceiling / 256, best = 0; // n = T / 256, and ok() is monotone in n while (lo <= hi) { const int64_t mid = lo + (hi - lo) / 2; if (ok(mid * 256)) { best = mid * 256; lo = mid + 1; } else hi = mid - 1; } return best; }; // `tail` (>= 0, a build without MMQ): the serve scan's tail-0 count (fit_out_rule.hpp), priced as that scan prices it, for // the RAM copy's lend region; 0.1.39's chunk keeps today's tail. -1: today's count (every other caller). auto plan_lend = [&](int64_t& chunk, int64_t tail = -1) -> int64_t { #if defined(STRATA_PREFILL_FUSED) && !defined(STRATA_PREFILL_MMQ) auto slots_for = [&](int64_t c) -> int64_t { return tail < 0 ? lend_slots(c) : slots_from_bytes(strata::prefill::Prefill::bytes_needed(g, ss, c, srcp != nullptr, tail)); }; auto old_slots = lend_slots; #else (void) tail; auto slots_for = lend_slots; auto old_slots = lend_slots; #endif // 0.1.39's list with its ring (also the size up to which a prompt keeps that ring under #583) auto old_rule = [&]() -> int64_t { strata::prefill::Prefill::set_ring_budget(0, 0); static constexpr int64_t kAutoChunks[] = {32768, 16384, 8192, 6144, 4096, 3072, 2048, 1024, 512, 256}; for (const int64_t c : kAutoChunks) { // above 8192: only when asked for, and only when a prompt of the context can use it if (c > 8192 && (c > o.prefill_auto_max || c > o.max_context)) continue; if (o.prefill_auto_cap > 0 && c > o.prefill_auto_cap) continue; // #1630 const int64_t k = old_slots(c); if (k + g_lend_keep <= xcache.slots() && k * 100 <= kAutoLendPct * xcache.slots()) return c; } return 0; }; if (o.prefill_auto && !strata::prefill::Prefill::ring_bytes_enabled()) { // STRATA_RING_BYTES=0: 0.1.39's list const int64_t c = old_rule(); if (c > 0) { chunk = c; return slots_for(c); } return 0; } if (o.prefill_auto) { // the default since 0.1.39b (#583) // The chunk and the ring are one budget, and the ring is the better buy. Measured on this 4-way // IQ3_S rig (2x RTX 3060 + 2x RTX 5060, CUDA3 lending at its 90% cap) on a 120K prompt: 8960 tokens // with the 17-slot ring that leaves reads at 963 tok/s, 8192/130 at 1,008, 7168 with the ring full at // its 199-slot byte budget at 1,000, and 5632/199 at 915. A ring slot is worth ~0.53 tok/s there and // a chunk token ~0.05, so the 69 slots between a full ring and 8192's 130 are worth more than the // 512 chunk tokens they cost - and once the ring IS full, shrinking the chunk further buys nothing. // So: the largest chunk that still leaves the ring full. Only a rig where no chunk at all can afford // one falls back to the old rule, which takes the largest chunk whose ring clears kRingMin (the // value at or below which ring_slots() returns STAGE and streaming is off). constexpr int64_t kRingMin = 16; const int64_t small = old_rule(); // 0.1.39's chunk (and its ring for the prompts that fit it) const int64_t ring_max = strata::prefill::Prefill::ring_cap_for(small); const int64_t budget = std::min(xcache.slots() - g_lend_keep, kAutoLendPct * xcache.slots() / 100); // The room is a BYTE budget. A ring slot is max_blob bytes (`carve` lays out one whole blob each), // while these cache slots hold their own layer's blob, which is smaller than max_blob unless the cache // happens to hold the pack's biggest layer - on the 4-way IQ3_S rig that is 2.15 MiB a slot against a // 2.54 MiB max_blob. Counting the room in slots priced the ring at 0.85x what it costs, `fits` then // rejected the whole chunk instead of shrinking the ring, and the scan stopped a step short: measured // against chunk 6144/ring 199, 8192 was refused where the same bytes afford a ~87-slot ring. const int64_t blob = (int64_t) strata::kernels::cpu::expert_layout().max_blob; const uint64_t avail = bytes_from_slots(budget); auto room_of = [&](int64_t t) -> int64_t { #if defined(STRATA_PREFILL_FUSED) && !defined(STRATA_PREFILL_MMQ) uint64_t nonring = strata::prefill::Prefill::bytes_needed_no_ring(g, ss, t, srcp != nullptr); if (tail >= 0) { // the chunk's own buffers at that tail, as the serve scan's ring_room (the ring's bytes do not depend on it) const uint64_t full = strata::prefill::Prefill::bytes_needed(g, ss, t, srcp != nullptr); const uint64_t at = strata::prefill::Prefill::bytes_needed(g, ss, t, srcp != nullptr, tail); nonring -= std::min(nonring, full - std::min(full, at)); } #else const uint64_t nonring = strata::prefill::Prefill::bytes_needed_no_ring(g, ss, t, srcp != nullptr); #endif return std::min((int64_t) ((avail - std::min(avail, nonring)) / (uint64_t) blob), ring_max); }; // `room_of` is capped at ring_max, so "the ring is full" is exactly room == ring_max, and both that // test and the ones below it only get harder as t grows - the bisection stays valid. auto scan = [&](int64_t floor) -> int64_t { return biggest_chunk(auto_ceiling, [&](int64_t t) -> bool { const int64_t room = room_of(t); if (room < floor) return false; strata::prefill::Prefill::set_ring_budget((int) room, 0); // ring_slots() now returns `room` - unless STRATA_PREFILL_RING overrides it, in which case the // chunk has to fit THAT ring, which is the pre-fix rule and the A/B arm const int64_t k = slots_for(t); return k + g_lend_keep <= xcache.slots() && k * 100 <= kAutoLendPct * xcache.slots(); }); }; int64_t c = scan(ring_max); if (c == 0 && ring_max < strata::prefill::Prefill::ring_default_slots()) c = scan(kRingMin); // a prompt that fits 0.1.39's chunk keeps 0.1.39's ring (one chunk: the smaller ring only slowed it) if (small >= c) { // the scan bought nothing: 0.1.39's choice strata::prefill::Prefill::set_ring_budget(0, 0); if (small > 0) { chunk = small; return old_slots(small); } return 0; } strata::prefill::Prefill::set_ring_budget((int) room_of(c), small); chunk = c; return slots_for(c); } for (int64_t c = chunk; c >= 256; c /= 2) { const int64_t k = slots_for(c); if (k + g_lend_keep <= xcache.slots()) { chunk = c; return k; } } return 0; }; // ---- #2824: THE PROMPT PLAN PRICES THE HOST. The scans above ask whether a loan fits the GPU cache. But a lent // slot's expert is not in VRAM for the length of the prompt: it comes from the RAM copy if the copy kept it, else from // the model file, and a chunk streams every expert the GPU does not hold once per chunk. When that file set is bigger // than the RAM the OS keeps file pages in, it cycles through the page cache and each chunk reads most of it again // (2x RTX 3060, 32 GB, IQ2_XS, 29K prompt: 8192-token chunks read 28-45 GB, 4096 read ~1 GB). So the auto pick is // refined by prefill_plan (include/strata/program/prefill_plan.hpp): the chunk x ring grid at or below the VRAM pick, // each priced with the expert bytes its loan displaces without a RAM backup, the RAM left for the page cache, the // measured PCIe rate and a drive-speed class, and the least predicted prompt time wins. A set that fits the page cache // keeps today's pick untouched. Advisory: --prefill N and STRATA_PREFILL_RING are the operator's, and // STRATA_PREFILL_HOST_PLAN=0 turns this off. No weights or experts change; only the chunk shape (rounding). // fits_vram(c) whether every participant can lend chunk c at the ring currently set // lend_of(c, bytes, slots) the cache bytes and slots the loan of chunk c takes at the ring currently set // ring_full(c) the largest ring slot count on offer for chunk c // restore() puts the ring state back as the VRAM pick left it // Returns the chunk to use (== `chunk` when nothing changes); the ring state is set for it. auto host_plan_chunk = [&](int64_t chunk, uint64_t gpu_cache_bytes, int64_t cache_slots, const std::function& fits_vram, const std::function& lend_of, const std::function& ring_full, const std::function& restore, int64_t tokens_hint = 0) -> int64_t { namespace pp = strata::program::prefill_plan; const char* off = std::getenv("STRATA_PREFILL_HOST_PLAN"); if (!o.prefill_auto || chunk <= 0 || srcp != &src || (off != nullptr && off[0] == '0') || !strata::prefill::Prefill::ring_bytes_enabled()) return chunk; const auto& lay = strata::kernels::cpu::expert_layout(); uint64_t total = 0; for (int64_t l = 0; l < g.n_layers; ++l) total += (uint64_t) lay.blob_bytes(l) * (uint64_t) g.n_expert; if (total == 0 || gpu_cache_bytes >= total) return chunk; // the GPU holds every expert: no file tier const auto hm = strata::core::sample_host_memory(); if (!hm) return chunk; const uint64_t slack = 1200ull << 20; // MemAvailable overstates what the cache can hold (~1 GiB on the #2824 box) pp::Host host; host.page_cache = src.unbuffered() ? 0 : (hm->available > slack ? hm->available - slack : 0); host.h2d_gbps = g_last_h2d_gbps > 0.0 ? g_last_h2d_gbps : 12.0; std::string why; host.ssd_gbps = drive_read_gbps(o.native_preset.empty() ? o.pack : o.native_preset, why); // where the experts live if (const char* e = std::getenv("STRATA_PREFILL_PLAN_TOKS"); e != nullptr && std::atof(e) > 0.0) host.compute_tok_s = std::atof(e); const uint64_t ram_copy = src.complement_ready() ? src.resident_bytes() : 0; const int64_t kept_slots = src.complement_ready() ? src.resident_lent_slots() : 0; const uint64_t slot_avg = cache_slots > 0 ? gpu_cache_bytes / (uint64_t) cache_slots : 0; const uint64_t kept_bytes = (uint64_t) std::max(0, kept_slots) * slot_avg; // the copy's lend region pp::Tier tier; tier.experts_total = total; tier.gpu_cache = gpu_cache_bytes; const uint64_t ram_outside_gpu = ram_copy > kept_bytes ? ram_copy - kept_bytes : 0; tier.file_tier = total > gpu_cache_bytes + ram_outside_gpu ? total - gpu_cache_bytes - ram_outside_gpu : 0; tier.extra_file = o.ple_gguf.empty() ? 0 : (350ull << 20); // PLE rows the prompt touches (#2824: ~0.35 GiB) const int64_t tokens = tokens_hint > 0 ? tokens_hint : std::max(chunk, std::min(std::max(o.max_context, 4096), 32768)); std::vector opts; auto add = [&](int64_t c, int64_t ring_req) { strata::prefill::Prefill::set_ring_budget((int) ring_req, 0); if (!fits_vram(c)) return; pp::Option op; op.chunk = c; op.ring = strata::prefill::Prefill::ring_slots_for(c); op.ring_full = ring_full(c); uint64_t lb = 0; int64_t ls = 0; lend_of(c, lb, ls); op.lend_bytes = lb; op.lend_kept = std::min(lb, kept_bytes); for (const pp::Option& e : opts) if (e.chunk == op.chunk && e.ring == op.ring) return; opts.push_back(op); }; // today's pick first, priced under the ring state it left restore(); pp::Option base; base.chunk = chunk; base.ring = strata::prefill::Prefill::ring_slots_for(chunk); base.ring_full = ring_full(chunk); { uint64_t lb = 0; int64_t ls = 0; lend_of(chunk, lb, ls); base.lend_bytes = lb; base.lend_kept = std::min(lb, kept_bytes); } opts.push_back(base); for (int64_t c = chunk; c >= 512; c -= 256) { const int64_t full = ring_full(c); add(c, (int) full); if (full > 32) add(c, (int) (full / 2)); if (full > 16) add(c, 16); } pp::Pick pick = pp::choose(host, tier, tokens, opts, 0); std::fprintf(stderr, "%s\n", pp::describe(pick, host, tokens).c_str()); std::fprintf(stderr, "strata: prefill plan inputs: %.1f GiB experts, %.1f GiB in the GPU caches, %.1f GiB RAM copy " "(%lld lend slots kept), file tier %.1f GiB; %.1f GiB available for the page cache%s; PCIe %.1f GB/s; " "drive %.2f GB/s (%s); a %lld-token prompt\n", (double) total / pp::kGiB, (double) gpu_cache_bytes / pp::kGiB, (double) ram_copy / pp::kGiB, (long long) kept_slots, (double) tier.file_tier / pp::kGiB, (double) host.page_cache / pp::kGiB, src.unbuffered() ? " (the file tier reads unbuffered: none)" : "", host.h2d_gbps, host.ssd_gbps, why.c_str(), (long long) tokens); if (!pick.changed) { restore(); return chunk; } strata::prefill::Prefill::set_ring_budget((int) pick.best.opt.ring, 0); return pick.best.opt.chunk; }; // ---- 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; // the pools are elastic: every request's cells are mapped before it runs bool from_cache = false; // ... and the expert cache gives them its slots (else new VRAM only) int64_t top = 0, lo = 0; // slots [lo, top) hold no expert; their whole chunks may be with the K/V int64_t top0 = 0; // where the prompt path's loan starts (top rises past it for a long context) int64_t loan_min = 512; // slots the prompt path keeps for its smallest chunk 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 spare; // out of the cache, not (yet) in the K/V std::function uncaptured; // the verify windows still to capture (their graphs take VRAM later) int64_t grows = 0, trims = 0, fresh = 0, evicted = 0, refilled = 0; } kvg; // Pools made elastic at session init map only their first cells, so they grow whenever the session is elastic: a // cache that cannot give slots (no VMM range, residency table or expert source, or a top at or under the floor) // only means the K/V grows from new VRAM (kv_grow_rules.hpp). Before, such a start left the pools at their first // cells and a longer prompt wrote past them (an illegal memory access). auto kvg_start = [&](int64_t top) { const strata::core::KvGrowStart s = strata::core::kv_grow_start( strata::core::qsa_kv_elastic(), xcache.vmm_range() != nullptr, d_res != nullptr && !host_res.empty(), srcp != nullptr, top, kvg.floor); kvg.on = s.on; kvg.from_cache = s.from_cache; if (!kvg.on) return; kvg.top = kvg.lo = kvg.top0 = 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); if (!kvg.from_cache) return; // 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& quiesce) -> bool { if (!kvg.on || cells <= kvg.cells) return true; const int64_t target = strata::core::kv_grow_target(cells, kvg.step, o.max_context); 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(); int64_t gave = 0, moved = 0; // the expert cache gives the K/V slots only when kvg_start found it able to (kvg.from_cache); otherwise the // K/V grows from new VRAM alone (grow_take below), as it does when the cache is at its floor if (kvg.from_cache) { strata::core::VmmRange& r = *xcache.vmm_range(); const uint64_t G = strata::core::vmm_granularity(); std::vector 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 rank; std::vector> 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(); 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]; nib::guard_raw(layer, "the elastic K/V's slot move (kvg_ensure)"); 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; } } const int64_t top_in = kvg.top; static const size_t margin = [] { const char* v = std::getenv("STRATA_KV_GROW_MARGIN_MIB"); return (size_t) (v != nullptr ? std::max(0, std::atoi(v)) : 384) << 20; }(); int64_t fresh_ok = 0; { size_t fr = 0, tot = 0; const size_t room = margin + (size_t) (kvg.uncaptured ? std::max(0, kvg.uncaptured()) : 0) * ((size_t) 32 << 20); if (cudaMemGetInfo(&fr, &tot) == cudaSuccess && fr > room) fresh_ok = (int64_t) ((fr - room) / G); } // Past the floor the loan region gives slots too, from its bottom up: a context that long holds fewer experts // and the next prompt reads in a smaller chunk laid out above kvg.top (the loan is back between requests). while ((int64_t) kvg.spare.size() + freeable() + fresh_ok < need && kvg.top < xcache.slots() - kvg.loan_min) { 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; } if (const int32_t oi = owner[(size_t) kvg.top]; oi >= 0 && host_res[(size_t) oi] == (int32_t) kvg.top) { host_res[(size_t) oi] = strata::core::kNotResident; ++kvg.evicted; } ++kvg.top; ++gave; } // a hotter expert moved into a loan-region slot above (its `owner` entry is stale) goes too if (kvg.top > top_in) for (size_t i = 0; i < host_res.size(); ++i) if (host_res[i] >= top_in && host_res[i] < kvg.top) { host_res[i] = 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) != cudaSuccess) { std::fprintf(stderr, "strata: the residency table upload failed: %s\n", cudaGetErrorString(cudaGetLastError())); return false; } } int64_t fresh = 0; auto grow_take = [&]() -> 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; }; bool ok = strata::core::qsa_kv_elastic_grow(target, grow_take); // STRATA_PARK_VRAM_MIB: the parked conversations' VRAM copies of their K/V give way to the K/V itself if (!ok && strata::core::conversation_park_vram_release_all() > 0) { (void) cudaGetLastError(); ok = strata::core::qsa_kv_elastic_grow(target, grow_take); } 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, int64_t hold) -> bool { // `hold`: the cells a parked conversation could need if (!kvg.on || !kvg.from_cache) return true; // new VRAM only: nothing to hand back to the cache // #1128: a parked conversation comes back through kvg_ensure's grow, so a K/V that fell to a short request's // size is grown again (its experts shuffled again) after every short request in between: the K/V keeps the // longest parked conversation's cells while it is parked const int64_t want = std::max(cells, hold); const int64_t target = std::max(kvg.step, (want + kvg.step - 1) / kvg.step * kvg.step); if (kvg.cells < target + 2 * kvg.step || kvg.lo >= kvg.top) return true; 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(); auto take_spare = [&]() -> strata::core::VmmChunk { if (kvg.spare.empty()) return 0; const strata::core::VmmChunk h = kvg.spare.back(); kvg.spare.pop_back(); return h; }; auto slot_mapped = [&](int64_t s) { const int64_t a = (int64_t) (xcache.slot_offset(s) / G); const int64_t b = (int64_t) ((xcache.slot_offset(s + 1) + G - 1) / G); for (int64_t c = a; c < b; ++c) if (!r.mapped(c)) return false; return true; }; // the loan region's slots first (kvg.top past top0 for a long context), so the next prompt's chunk is whole const int64_t top1 = kvg.top; if (kvg.top > kvg.top0) { const int64_t ce = (int64_t) ((xcache.slot_offset(kvg.top) + G - 1) / G); const int64_t cfloor = (int64_t) (xcache.slot_offset(std::max(kvg.top0, kvg.lo)) / G); int64_t cs = ce, need = (int64_t) kvg.spare.size(); while (cs > cfloor && need > 0) need -= r.mapped(--cs) ? 0 : 1; if (!r.map_range(cs, ce, take_spare)) std::fprintf(stderr, "strata: the expert cache could not take its VRAM back from the K/V\n"); while (kvg.top > std::max(kvg.top0, kvg.lo) && slot_mapped(kvg.top - 1)) --kvg.top; } const int64_t c1 = (int64_t) (xcache.slot_offset(kvg.top) / G); { // one run from the lowest unmapped chunk, as long as the chunks handed back last (one access call) const int64_t c0 = (int64_t) (xcache.slot_offset(kvg.lo) / G); int64_t cend = c0, need = (int64_t) kvg.spare.size(); while (cend < c1 && need > 0) need -= r.mapped(cend++) ? 0 : 1; if (!r.map_range(c0, cend, [&]() -> strata::core::VmmChunk { if (kvg.spare.empty()) return 0; const strata::core::VmmChunk h = kvg.spare.back(); kvg.spare.pop_back(); return h; })) std::fprintf(stderr, "strata: the expert cache could not take its VRAM back from the K/V\n"); } 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; } // the refills on one stream and one sync (a blocking copy each was a driver round trip per expert) const auto& lay = strata::kernels::cpu::expert_layout(); std::vector> filled; // (residency index, slot), resident once the copies landed size_t pi = 0; std::vector back; // the slots that hold an expert again for (int64_t s = lo0; s < kvg.lo; ++s) back.push_back(s); for (int64_t s = kvg.top; s < top1; ++s) back.push_back(s); for (const int64_t s : back) { 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_stable(l, e); if (b == nullptr) continue; nib::guard_raw(l, "the elastic K/V's refill (kvg_trim)"); cudaMemcpyAsync(xcache.device_slot((int32_t) s), b, (size_t) lay.blob_bytes(l), cudaMemcpyHostToDevice, nullptr); filled.emplace_back(i, (int32_t) s); ++pi; break; } } if (cudaDeviceSynchronize() != cudaSuccess) { std::fprintf(stderr, "strata: refilling the expert cache failed: %s\n", cudaGetErrorString(cudaGetLastError())); return false; } for (const auto& [i, s] : filled) host_res[i] = s; kvg.refilled += (int64_t) filled.size(); // res_put waits for its copy: the next reader can be a verify window (a non-blocking stream) right away if (res_put(d_res) != cudaSuccess) return false; for (const strata::core::VmmChunk h : kvg.spare) strata::core::vmm_chunk_free(h); // new ones, if any kvg.spare.clear(); if (kvg.lo == kvg.top && kvg.top > kvg.top0) kvg.lo = kvg.top = kvg.top0; // the loan region is whole again ++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) back.size()); return true; }; // ---- 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, // after the prompt path's lend plan is known: the slots it may lend (the cache's last ones) have their experts // streamed during a prompt and copied back after it, so those are kept in RAM too as far as RAM allows. The // bytes are the file's bytes and the placement is the same, so the answers are the plain mmap mode's; the // share-of-pinned figure above (which sizes the prompt path) is left as the mmap mode's for the same reason. // --adapt-async (opt-in): where the asynchronous adaptive tier does not apply, the blocking tier runs, said once. // It exchanges experts between the GPU caches and the resident RAM copy only (the copy is checked once it is // built, below). Beside the --batch slots it advances between their windows, never between a prompt's chunks; // not with --batch-groups (pipelined slot groups), a peer tier or the helper GPUs' tier, which pick their swaps // from the same table. The pipelined decode loop (--pipeline-windows 2) has windows in flight at every tick: // there the steps that overwrite something a window may still read wait for those windows (see adapt_tick); // STRATA_PIPELINE_ADAPT_ASYNC=0 keeps the blocking tier beside it instead. auto adapt_async_off = [&](const char* why) { std::fprintf(stderr, "strata generate: --adapt-async 1 is off (%s): the blocking adaptive tier\n", why); o.adapt_async = 0; }; // Where the asynchronous tier could run on its own (CUDA, one GPU, the expert arena, no batch slots), the engine measures // and chooses during the session: see include/strata/core/adapt_async_default.hpp. --adapt-async 0 or // STRATA_ADAPT_ASYNC=0 keep the blocking tier; --adapt-async 1 keeps its old meaning. if (o.adapt_async_given < 0) { strata::core::AdaptAsyncAuto aa; aa.flag = o.adapt_async_given; aa.env = strata::core::adapt_async_env(); #if !defined(STRATA_USE_HIP) aa.cuda = true; #endif aa.serve = o.serve; aa.adaptive = o.adapt_every > 0 && o.adapt_swaps > 0; aa.arena = srcp == &arena_src; aa.multi_gpu = multi_gpu; aa.pipeline_windows = o.pipeline_windows >= 2; aa.batch = o.batch > 0; aa.peer = peer.valid(); aa.remote_opt = remote_opt != nullptr; aa.adapt_overlap = adapt_overlap(); o.adapt_async_self = strata::core::adapt_async_self_decides(aa); } if (o.adapt_async) { static const bool pl_async = [] { const char* v = std::getenv("STRATA_PIPELINE_ADAPT_ASYNC"); return v == nullptr || std::atoi(v) != 0; }(); const char* why = !o.serve ? "it needs --serve" : o.adapt_every <= 0 || o.adapt_swaps <= 0 ? "the adaptive tier is off" : !o.resident_cpu_experts && srcp != &arena_src ? "it needs the resident RAM mode, --resident-experts, or the expert arena" : multi_gpu && srcp == &arena_src ? "not with a layer split in the arena mode" : o.pipeline_windows >= 2 && srcp == &arena_src ? "not with --pipeline-windows 2 in the arena mode" : o.batch > 0 && o.batch_groups > 1 ? "not with --batch-groups (the pipelined slot groups)" : peer.valid() ? "not with --peer-device" : remote_opt ? "not with --remote-expert-opt" : o.pipeline_windows >= 2 && !pl_async ? "not with --pipeline-windows 2 (STRATA_PIPELINE_ADAPT_ASYNC=0)" : nullptr; if (why != nullptr) adapt_async_off(why); } // STRATA_PIPE_ADAPT_EVERY (batch_groups.hpp; the rounds run in the pipelined loop below): said once here, with the // other start-up lines, before READY if (o.serve && o.batch > 0 && o.batch_groups > 1 && multi_gpu) { const int every = strata::program::batch_groups::pipe_adapt_every(std::getenv("STRATA_PIPE_ADAPT_EVERY")); if (every > 0) std::fprintf(stderr, "strata batch: STRATA_PIPE_ADAPT_EVERY=%d: the pipelined groups run an adaptive-tier round " "every %d group windows (the pipeline empties for it)%s\n", every, every, o.adapt_every <= 0 || o.adapt_swaps <= 0 ? " - but the adaptive tier is off" : ""); } // #340 / STRATA_SPLIT_RING: a layer split's streamed-ring override, decided from the stage caches' residency. It // has to be in place BEFORE the split's lend regions are sized (Prefill::bytes_needed counts the ring): they were // sized with the default ring and the override applied afterwards, so a ring of 384 borrowed 5396 slots and the RAM // copy kept 4662 (the rest streamed from the GGUF mmap on every chunk). Called once; later calls do nothing. bool split_ring_decided = false; auto decide_split_ring = [&]() { if (split_ring_decided || !o.serve || !multi_gpu || host_res.empty()) return; split_ring_decided = true; int64_t res_n = 0; for (const int32_t r : host_res) res_n += r >= 0; const double res_share = (double) res_n / (double) host_res.size(); const int ring = strata::program::split_ring_slots(std::getenv("STRATA_SPLIT_RING"), res_share); if (ring > 0) { strata::prefill::Prefill::set_ring_override(ring); std::fprintf(stderr, "strata serve: layer split: %.0f%% of the experts resident, the prompt path's " "streamed ring %d slots\n", 100.0 * res_share, ring); } }; #if defined(STRATA_PREFILL_FUSED) && !defined(STRATA_PREFILL_MMQ) // fit_out_rule.hpp: what the serve scan knows when it picks its chunk, in ONE place: the scan below and the RAM copy's lend // region, which is sized before it, count the same tail auto fit_case = [&](int64_t chunk, bool small_path) -> strata::prefill::fit_out::ScanCase { strata::prefill::fit_out::ScanCase sc; sc.auto_chunk = o.prefill_auto && strata::prefill::Prefill::ring_bytes_enabled(); sc.one_gpu = stages.empty() && !multi_gpu && !peer.valid() && !o.prefill_head_alias && o.batch <= 1; sc.tail_loan = tail_loan_on; sc.equal_cut = equal_cut_one == strata::prefill::equal_cut::Cut::equal; sc.small_path = small_path; sc.fused_at_chunk = strata::prefill::Prefill::tail_matters(chunk, srcp != nullptr); return sc; }; int64_t region_chunk = 0; // the chunk the RAM copy's lend region was sized for (the warning below names it) int64_t region_today = 0, region_today_k = 0; // today's chunk and its start-up loan, which the scan keeps when the RAM holds less #endif if (o.resident_cpu_experts) { int64_t lend_from = -1; if (o.prefill_chunk > 0 && !o.no_prefill_borrow && d_res != nullptr && xcache.slots() > 0) { int64_t chunk = o.prefill_chunk; #if defined(STRATA_PREFILL_FUSED) && !defined(STRATA_PREFILL_MMQ) int64_t k = plan_lend(chunk); region_chunk = region_today = chunk; region_today_k = k; // the serve scan may take the tail-0 chunk: the region holds its start-up loan (today's tail, the largest loan any // request takes at that chunk), so the scan's hard guard can take it when the RAM keeps it. The small-card path is // decided later; its chunk is at most today's, which the region holds either way. if (k > 0 && o.serve && strata::prefill::fit_out::scan_tail(fit_case(chunk, false)) == 0) { int64_t c0 = o.prefill_chunk; int64_t k0 = plan_lend(c0, 0) > 0 && c0 > chunk ? lend_slots(c0) : 0; if (!strata::prefill::fit_out::loan_fits(k0, xcache.slots(), g_lend_keep, kAutoLendPct, false)) k0 = 0; // the scan's start-up test const int64_t kr = strata::prefill::fit_out::region_slots(k, k0, 0); if (kr != k) { k = kr; region_chunk = c0; } int64_t c1 = o.prefill_chunk; (void) plan_lend(c1); // the ring state as today's scan left it } #else const int64_t k = plan_lend(chunk); #endif if (k > 0) lend_from = xcache.slots() - k; } // a layer split: the experts every later stage's cache holds are left out of the RAM copy, as CUDA0's are // (with them the copy keeps no lend region: pin_cache_complement turns the loan off) // (true of the single lend region only: the stage_lend_regions block below hands every part's // borrowed tail to the copy as well, so under a split the copy keeps a lend region per part again) std::vector> stage_pairs; for (auto& st : stages) for (int64_t l = st->lb; l < st->le; ++l) for (int64_t e = 0; e < g.n_expert; ++e) if (st->cache.slot_of(l, e) >= 0) stage_pairs.emplace_back((int32_t) l, (int32_t) e); if ([] { const char* v = std::getenv("STRATA_HELPER_RAM_DISJOINT"); return v == nullptr || std::atoi(v) != 0; }()) { // A helper GPU's experts are left out of the RAM copy as a stage's are - the RAM // that duplication would take goes to colder experts instead. for (int r = 0; r < 3; ++r) { if (o.expert_cache_remote[(size_t) r] <= 0) continue; for (int64_t l = 0; l < g.n_layers; ++l) for (int64_t e = 0; e < g.n_expert; ++e) if (remote_experts[(size_t) r].holds(l, (int32_t) e)) stage_pairs.emplace_back((int32_t) l, (int32_t) e); } } // The split's lend regions. The serve scan lends the tail slots of EVERY part's cache - CUDA0's own // part first, then every stage (the `pf_parts` loop below) - and `lend_from` above is switched off in // pin_cache_complement the moment `additional_gpu_pairs` is non-empty, so until now none of those experts // were in the RAM copy: during a prompt they came back through page faults from the mapped files. // Measured 2026-10-06 on an RTX 2000 Ada + 5060 Ti rig (17/48 split, IQ3_S mapped from the GGUF, // --prefill auto, one 73K-token prompt): 3.7 GiB read from the NVMe for the one prompt (the arena // mode reads 1.1 GiB), and one 8192-token chunk spent 1.5 s of its 3.9 s on host staging (arena: // 0.37 s). Size each part's region at the largest chunk the scan can ever pick - auto's ceiling, or an // explicit --prefill, which the scan only walks down - take its tail slots with the scan's own // arithmetic, and list the pairs from the highest slot down, as the borrowing takes them. #340 is // honoured the same way (the same free-VRAM test, at this startup moment): a part whose card can // fund the bound chunk's buffers outright lends nothing at any pick, so it gets no region and no RAM // is spent on it. The single-GPU loan is untouched: without a split the lend region stays in // pin_cache_complement's own path, and no regions are set. std::vector>> stage_lends; decide_split_ring(); // the ring the prompt path really uses, BEFORE bytes_needed sizes the regions below if (pf_borrow && d_res != nullptr && o.prefill_chunk > 0 && multi_gpu && !stages.empty()) { const int64_t bound = o.prefill_auto ? auto_ceiling : o.prefill_chunk; static const bool own_ok = [] { const char* v = std::getenv("STRATA_SPLIT_OWN_BUFFERS"); return v == nullptr || v[0] != '0'; }(); for (size_t i = 0; i <= stages.size(); ++i) { // the scan's part order: CUDA0, then every stage strata::core::ExpertCache& xc = i == 0 ? xcache : stages[i - 1]->cache; const strata::core::SessionState& ses = i == 0 ? ss : stages[i - 1]->ss; const int64_t dev = i == 0 ? -1 : stages[i - 1]->dev; const int64_t lb = i == 0 ? 0 : stages[i - 1]->lb; const int64_t le = i == 0 ? split_at[0] : stages[i - 1]->le; if (xc.slots() <= 0 || le <= lb) continue; const uint64_t need = strata::prefill::Prefill::bytes_needed(g, ses, bound); if (own_ok) { // the card funds its buffers at any chunk the scan can pick: nothing is lent const strata::core::OnDevice on(dev); size_t fb = 0, tb = 0; if (cudaMemGetInfo(&fb, &tb) == cudaSuccess) { if ((uint64_t) fb >= need + (3ull << 29)) continue; } else (void) cudaGetLastError(); } // its tail slots, as the scan's `cache_slots_for` counts them int64_t k = strata::program::split_lend_slots( xc.slots(), xc.bytes(), xc.slot_offsets(), (uint64_t) strata::kernels::cpu::expert_layout().max_blob, need); k = std::min(k, xc.slots() - g_lend_keep); // the scan's 128-slot floor if (o.prefill_auto) k = std::min(k, kAutoLendPct * xc.slots() / 100); // the auto cap if (k <= 0) continue; std::vector> region; for (int64_t l = lb; l < le; ++l) for (int64_t e = 0; e < g.n_expert; ++e) if (xc.slot_of(l, e) >= xc.slots() - k) region.emplace_back((int32_t) l, (int32_t) e); std::sort(region.begin(), region.end(), [&](const std::pair& a, const std::pair& b) { return xc.slot_of(a.first, a.second) > xc.slot_of(b.first, b.second); }); if (!region.empty()) stage_lends.push_back(std::move(region)); } src.stage_lend_regions(std::move(stage_lends)); } { // the pack's and the MTP head's files: read at start, their cache is given back by the complement's drop std::vector drop; for (const std::string& d : {o.pack, o.mtp}) { std::error_code ec; if (d.empty()) continue; if (std::filesystem::is_regular_file(d, ec)) { drop.push_back(d); continue; } for (const auto& f : std::filesystem::directory_iterator(d, ec)) if (f.is_regular_file(ec)) drop.push_back(f.path().string()); } src.set_extra_drop_files(std::move(drop)); } #if defined(STRATA_USE_HIP) && defined(_WIN32) // BATCH SLOTS ON THE STRIX HALO: every session (the main one and each slot) pins its streamed K/V for the whole context, and with the RAM copy of experts // that is the page-locked memory of the start. 4 slots at 131,072 tokens with the usual 38 GiB budget (20.33 GiB of complement) stopped inside the prompt // path, and with 18 GiB the OS ran out of page-locked memory; 15 GiB started and served. So here the RAM copy is cut to what leaves complement + pinned K/V // at the level of the largest start that worked (include/strata/core/uma_cache.hpp, with the job ids); the experts left out are read from the SSD. Context, // slot count and prompt chunk are untouched. Only with --batch 2 or more, so a single request is as before. STRATA_UMA_PIN_CAP=0: the RAM budget stays as set (the way back). // The line below is printed after the pin, and only when the cap really left experts out (the RAM copy filled up to it): with 2 slots (12.47 GiB of complement) and // 3 slots (16.40 GiB) the whole complement is under the cap, nothing is cut and the start is as before (strix-20261112-1952-001f printed the line there). // The cap has no floor that turns into a refusal (owner, 11-12: "we should allow people to start, even if its read by ssd"): with so many slots that their K/V alone is over // the level the cap is 0 and the RAM copy is empty (budget 1 byte: 0 would mean "no limit"); every expert the GPU cache does not hold is read from the SSD, and the start goes on. bool uma_cap_applied = false; uint64_t uma_cap = 0; const char* const uma_pin_cap = std::getenv("STRATA_UMA_PIN_CAP"); if (o.batch >= 2 && o.prefill_own_keep_chunk && o.resident_budget > 0 && !(uma_pin_cap != nullptr && uma_pin_cap[0] == '0')) { const uint64_t kv = strata::core::qsa_kv_host_bytes(); uma_cap = strata::core::uma_pinned_complement_cap_bytes(kv); const uint64_t budget = strata::core::uma_pinned_complement_budget_bytes(kv); if (o.resident_budget > budget) { uma_cap_applied = true; o.resident_budget = budget; } } #endif const std::vector>& rank_all = !ram_rank.empty() ? ram_rank : profile_all.empty() ? profile : profile_all; src.budget_is_automatic(ram_fallback_resident); // its clamp line then names no flag bool resident_ok = src.pin_cache_complement(xcache, err, o.resident_pin, stage_pairs, lend_from, o.resident_headroom, o.resident_budget, &rank_all); #if defined(STRATA_USE_HIP) && defined(_WIN32) // cut = the RAM copy reached the cap (within 16 MiB: the ranked experts are taken while they fit, the last gap is under one expert's blob, about 4 MiB) if (uma_cap_applied && resident_ok && src.resident_bytes() + (16ull << 20) >= uma_cap) { if (uma_cap == 0) std::fprintf(stderr, "strata: %d requests at once: the experts are read from the SSD when needed so that everything fits in this PC's memory (STRATA_UMA_PIN_CAP=0 keeps the RAM budget as set)\n", o.batch); else std::fprintf(stderr, "strata: %d requests at once: %.1f GiB of experts are kept in RAM so that everything fits in this PC's memory; the rest are read from the SSD when needed (STRATA_UMA_PIN_CAP=0 keeps the RAM budget as set)\n", o.batch, (double) uma_cap / 1073741824.0); } #endif std::string whole_err; if (!resident_ok && o.resident_soft) { // #467: the whole complement does not fit - keep what does, the hottest by the profile, through the #403 // budget path (sized by available memory) instead of none: the misses outside it read the same file bytes // the mmap fallback reads, so the answers are unchanged. Nothing pinned: the old fallback below. whole_err = err; resident_ok = src.pin_cache_complement(xcache, err, o.resident_pin, stage_pairs, -1, o.resident_headroom, strata::core::FileExpertSource::kResidentWhatFits, &rank_all); if (resident_ok) std::fprintf(stderr, "strata generate: WARNING: the whole resident RAM mode does not fit (%s); %.2f " "GiB of the experts the GPU does not hold, the hottest by the expert profile, are " "kept in RAM and the rest are read from the model folder through the OS file " "cache\n", whole_err.c_str(), (double) src.resident_bytes() / 1073741824.0); else err = whole_err + "; " + err; } // the startup reads are done: the view of experts.bin back, the file tier as chosen above bool startup_kept = false; if (src.startup_unbuffered()) { std::string why; const auto end_t0 = std::chrono::steady_clock::now(); startup_kept = !src.end_startup_unbuffered(why); if (startup_kept) std::fprintf(stderr, "strata generate: WARNING: %s\n", why.c_str()); else std::fprintf(stderr, "strata generate: the startup reads are done: experts.bin mapped again (%.0f ms)\n", std::chrono::duration(std::chrono::steady_clock::now() - end_t0).count()); } // #669 / #765: a big chunk lends many cache slots to the prompt path, and each lent slot's expert is read back // from the SSD whenever the RAM could not keep its copy (31 GB: auto:32768 read prompts ~3x slower than auto). // Said, never capped: --prefill is the user's, and with the RAM for them it is the faster one (+21-35%). // #1683: with a RAM budget the lend region is kept after the ranked experts, as far as the budget reaches, so // the advice there is a larger budget, not a smaller chunk (the budget used to keep none of it whatever the chunk) #if defined(STRATA_PREFILL_FUSED) && !defined(STRATA_PREFILL_MMQ) // the loan the prompt path will really take: the region's chunk, or today's when the RAM keeps less than the region // of a tail-0 chunk (the serve scan's guard then keeps today's chunk; fit_out_rule.hpp region_holds) int64_t warn_chunk = region_chunk, warn_k = xcache.slots() - lend_from; if (region_chunk != region_today && src.resident_lent_slots() < warn_k) { warn_chunk = region_today; warn_k = region_today_k; } #else const int64_t warn_chunk = o.prefill_chunk, warn_k = xcache.slots() - lend_from; #endif if (resident_ok && lend_from >= 0 && (o.prefill_chunk > 8192 || o.resident_budget > 0) && warn_k > 0 && src.resident_lent_slots() < warn_k) std::fprintf(stderr, "strata generate: WARNING: a prompt chunk of %lld tokens lends %lld cache slots to the " "prompt path, but only %lld of their experts fit in RAM: the others are read from the " "SSD on every chunk, and prompts can read ~3x slower than with --prefill auto (#669). " "%s keeps them all in RAM\n", (long long) warn_chunk, (long long) warn_k, (long long) src.resident_lent_slots(), o.resident_budget > 0 ? (ram_fallback_resident ? "A larger automatic RAM copy (the lend region comes after the ranked experts), or a smaller --prefill," : "A larger --resident-budget-gib (the lend region comes after the ranked experts), or a smaller --prefill,") : "A smaller --prefill, or auto,"); if (resident_ok) { // --adapt-async: twice the exchange buffers - the second half bounces the copies in whose source is not // page-locked (an asynchronous copy instead of the driver's staged, synchronous one) if (o.adapt_async && !src.reserve_exchanges(2 * std::min(o.adapt_swaps, 96), err, std::min(o.adapt_swaps, 96))) adapt_async_off(err.c_str()); // pageable buffers would make every copy of a round synchronous (the driver stages them): that is the // blocking tier's cost, so the asynchronous tier is not worth running - said, and the blocking tier stays if (o.adapt_async && !src.exchange_pinned()) adapt_async_off("the exchange buffers could not be page-locked"); if (o.adapt_every > 0 && o.adapt_swaps > 0 && !src.reserve_exchanges(std::min(o.adapt_swaps, 96), err)) { std::fprintf(stderr, "strata generate: CPU expert residency: %s\n", err.c_str()); return 1; } { cudaDeviceProp ucp{}; int ucd = 0; if (src.complement_pinned() && cudaGetDevice(&ucd) == cudaSuccess && cudaGetDeviceProperties(&ucp, ucd) == cudaSuccess && ucp.integrated) g_uma_pinned_complement.store(true); } std::fprintf(stderr, "strata generate: resident RAM mode: %.2f GiB of experts in RAM (%s), %lld in the GPU " "cache; adaptive swaps %s\n", (double) src.resident_bytes() / 1073741824.0, src.complement_pinned() ? "page-locked" : src.locked_bytes() > 0 ? "locked" : "pageable", (long long) xcache.resident(), o.adapt_every > 0 && o.adapt_swaps > 0 ? "exchange them with the GPU cache (no file reads)" : "off"); } else if (o.resident_soft) { std::fprintf(stderr, "strata generate: WARNING: the resident RAM mode does not fit (%s); the experts the " "GPU does not hold are read from the model folder through the OS file cache " "(--mmap-experts), which is slower when the RAM cannot keep them\n", err.c_str()); } else if (o.resident_budget > 0) { // #403: a RAM budget that cannot be kept is not a reason to stop - the experts it would have held are // read from the files like the ones outside it (pin_cache_complement leaves nothing half-built) std::fprintf(stderr, "strata generate: WARNING: the RAM budget (%s) cannot be kept (%s); " "every expert the GPU does not hold is read from the model files %s " "(--mmap-experts), which is slower\n", ram_fallback_resident ? "the automatic RAM copy" : "--resident-budget-gib", err.c_str(), src.unbuffered() ? "with unbuffered I/O" : "through the OS file cache"); } else { std::fprintf(stderr, "strata generate: CPU expert residency: %s\n", err.c_str()); return 1; } // #577: the unbuffered choice above was made before the RAM copy existed, from the budget asked for; now the // copy is built, decide again from the RAM it really holds and the expert bytes outside it (on a 96 GB PC // the file cache keeps those, and every refill after a prompt read the drive instead). Windows and Linux: the // unbuffered reads exist there #if defined(_WIN32) || defined(__linux__) if (o.mmap_experts && o.resident_budget > 0 && !startup_kept) { std::string why; const bool was = src.unbuffered(); const bool ub = src.recheck_unbuffered(why); std::fprintf(stderr, "strata generate: the file tier reads %s%s (%s)\n", ub ? "unbuffered" : "through the file cache", ub == was ? "" : " (changed)", why.c_str()); if (ub != was) { // the plain line (owner 11-06): printed once, when the mode changes to the file cache; the RAM figures are the ones the rule // used (the group's own limit and room, no operator cap). STRATA_TRACE keeps the long technical line. constexpr double GiB = 1073741824.0; if (const auto mem = strata::core::sample_host_memory(strata::core::MemoryProbePaths{}, 0)) { if (!ub) std::fprintf(stderr, "strata: expert reads now go through the file cache (%.1f GiB of RAM free for them, %.1f GiB limit)\n", (double) mem->available / GiB, (double) mem->limit / GiB); if (std::getenv("STRATA_TRACE") != nullptr) std::fprintf(stderr, "strata trace: the file tier changed: RAM at the re-check: limit %.1f GiB (source: %s), current %.1f GiB, " "reclaimable cache credited %.1f GiB; available %.1f GiB (MemAvailable %.1f GiB)\n", (double) mem->limit / GiB, strata::core::memory_source_name(mem->source), (double) mem->current / GiB, (double) mem->credit / GiB, (double) mem->available / GiB, (double) mem->mem_available / GiB); } } // MODEL-UPDATE round 2 (opt-in STRATA_PROMPT_DIRECT=1): the prompt path's batched reads unbuffered while // decode keeps the file cache (z440, UD-Q4_K_XL, 39 GiB budget: all-unbuffered doubled the 6K prompt but // cost decode 9-13%). The same bytes either way. if (!ub && [] { const char* v = std::getenv("STRATA_PROMPT_DIRECT"); return v != nullptr && v[0] == '1'; }()) { std::string pw; const bool pd = src.open_prompt_direct(pw); std::fprintf(stderr, "strata generate: the prompt path's expert reads %s\n", pd ? "go unbuffered (STRATA_PROMPT_DIRECT=1)" : ("stay buffered: " + pw).c_str()); } } #endif } // (the arena mode has no RAM copy to exchange with: its experts are always in RAM, the tier only copies them in) if (o.adapt_async && !src.complement_ready() && srcp != &arena_src) adapt_async_off("the resident RAM mode is not running"); // pp-opt: with the file tier unbuffered, the mapped view of experts.bin is only a fallback from here on - and while // it exists NTFS serves the unbuffered reads one at a time (drop_mapping). STRATA_KEEP_MAPPING=1 keeps it (A/B). if (srcp == &src && src.unbuffered() && std::getenv("STRATA_KEEP_MAPPING") == nullptr) { std::string why; const bool dropped = src.drop_mapping(why); std::fprintf(stderr, "strata generate: the mapped view of the experts %s (%s)\n", dropped ? "is closed" : "stays open", why.c_str()); // --ple-io mmap / ram maps the PLE shard for the whole run; when that shard also holds experts, NTFS still runs // the unbuffered reads of that one file one at a time (the default --ple-io direct keeps no mapping) if (dropped && src.gguf_mode() && !o.ple_gguf.empty() && o.ple_io != "direct") std::fprintf(stderr, "strata generate: note: --ple-io %s keeps %s mapped; if that shard holds experts, their " "reads stay serialized (--ple-io direct, the default, keeps no mapping)\n", o.ple_io.c_str(), o.ple_gguf.c_str()); } // 0.1.42 (H11): the default CPU share is armed only when the host has the memory for it. One line says why not; // an explicit STRATA_PREFILL_CPU_SHARE (other than 0) is armed anyway, with a warning when memory is short. auto share_default_ok = [&]() -> bool { strata::prefill::share_rules::ShareMemory sm; strata::core::detail::HostMemory hm; if (strata::core::detail::host_available_memory(hm)) { sm.avail_ram = hm.available; sm.avail_commit = hm.commit == ~uint64_t{0} ? strata::prefill::share_rules::kUnknown : hm.commit; } sm.buffer_bytes = (uint64_t) (1024 + 8 * g.n_expert) * (uint64_t) g.n_embd * 4 + (256ull << 20); if (srcp == &src) { const auto& lay = strata::kernels::cpu::expert_layout(); for (int64_t l = 0; l < g.n_layers; ++l) for (int64_t e = 0; e < g.n_expert; ++e) if (xcache.slot_of(l, e) < 0 && src.resident_blob(l, e) == nullptr && !src.transient(l, e)) sm.inplace_bytes += (uint64_t) lay.blob_bytes(l); } const auto v = strata::prefill::share_rules::default_share_memory_verdict(sm); if (v.arm) return true; const char* ev = std::getenv("STRATA_PREFILL_CPU_SHARE"); if (ev == nullptr) std::fprintf(stderr, "strata: the CPU prefill share is not armed by default: %s. STRATA_PREFILL_CPU_SHARE=auto " "turns it on anyway\n", v.why.c_str()); else if (std::strcmp(ev, "0") != 0) std::fprintf(stderr, "strata: WARNING STRATA_PREFILL_CPU_SHARE=%s is set and kept, but %s: the share can slow " "prompts or fail on a machine this short of memory (STRATA_PREFILL_CPU_SHARE=0 turns it off)\n", ev, v.why.c_str()); return false; }; if (o.serve) { if (o.spec < 2 || o.prefill_chunk <= 0 || (graph_hits && (thits.d_res == nullptr || host_res.empty()))) { std::fprintf(stderr, "strata serve: needs --spec T and --prefill CHUNK (and a fillable " "--expert-cache; the graphed hit path additionally needs --expert-profile P)\n"); return 2; } // STRATA_VOLTA_BUILD backport (see docs/ and ninfer-flash-next-v100-backport): --mtp is optional here, // mirroring the plain `generate` command's own use_mtp handling below. Without it, drafting falls back // to the suffix/prompt-lookup drafter (DraftPolicy still picks Lookup vs plain per round) or, when // neither fires, plain one-token-per-round decoding - slower, never wrong: the verify window still // confirms every emitted token against the real model regardless of where the draft came from. const bool use_mtp = !o.mtp.empty(); // STRATA_PREFILL_HELPER_SOURCE (opt-in): the prompt path may take a blob a helper's VRAM cache already // holds from that cache instead of reading the files again. The helpers are idle while a prompt is read // (the serve path is serial: no batch slots), so the copy needs no ordering against their kernel streams. // Everything else - the fallback's batched unbuffered reads, its pinned RAM copy, the prompt path's own // decisions - is forwarded unchanged. Default off: the prompt path's source is srcp, exactly as before. std::vector prefill_helpers; for (int r = 0; r < drive.d.remote_count; ++r) prefill_helpers.push_back(drive.d.remote[r]); std::unique_ptr prefill_helper_src; strata::core::ExpertSource* prefill_src = srcp; uint64_t helper_blobs_before = 0, helper_bytes_before = 0; if (const char* hv = std::getenv("STRATA_PREFILL_HELPER_SOURCE"); hv != nullptr && std::atoi(hv) != 0 && srcp != nullptr && !multi_gpu && stages.empty() && o.batch <= 0 && !prefill_helpers.empty()) { prefill_helper_src = std::make_unique(*srcp, prefill_helpers); prefill_src = prefill_helper_src.get(); std::fprintf(stderr, "strata serve: the prompt path reads the experts a helper cache holds from that " "cache (STRATA_PREFILL_HELPER_SOURCE)\n"); } strata::prefill::Prefill sp; // 149-prefetch STRATA_RAM_ADAPT2=1 (with STRATA_RAM_ADAPT=n, the promotions staged per window): see the window loop struct RamAdapt2 { bool on = false; float prompt_w = 0.25f, cached_w = 0.15f; int per_layer = 2; int skip_top = 2; int64_t installed = 0; std::vector seed; } ram_adapt2; { const char* v = std::getenv("STRATA_RAM_ADAPT2"); ram_adapt2.on = v != nullptr && std::atoi(v) != 0; if (const char* w = std::getenv("STRATA_RAM_ADAPT_PROMPT_W")) ram_adapt2.prompt_w = (float) std::max(0.0, std::atof(w)); if (const char* w = std::getenv("STRATA_RAM_ADAPT_CACHED_W")) ram_adapt2.cached_w = (float) std::clamp(std::atof(w), 0.0, 1.0); if (const char* w = std::getenv("STRATA_RAM_ADAPT_PER_LAYER")) ram_adapt2.per_layer = std::max(1, std::atoi(w)); if (const char* w = std::getenv("STRATA_RAM_ADAPT_SKIP_TOP")) ram_adapt2.skip_top = std::max(0, std::atoi(w)); } // the pool is idle while a prompt is read unless batch slots decode between its parts; with // STRATA_PREFILL_CPU_SHARE the staged-chunk limit before the chunk below sizes the loans (bytes_needed reads it) // #1607: Windows, the commit limit (RAM + page file) is what ends the engine silently; compare what this run plans // to allocate on the host from here (the conversation cache, checkpoints) with the commit that is left #if defined(_WIN32) { MEMORYSTATUSEX cs{}; cs.dwLength = sizeof cs; if (GlobalMemoryStatusEx(&cs)) { const uint64_t planned = (o.prompt_cache > 0 ? (uint64_t) std::max(o.conversation_cache_mib, 0) << 20 : 0) + (2ull << 30); // checkpoints and prompt staging const auto cv = strata::platform::host_limits::commit_verdict((uint64_t) cs.ullAvailPageFile, (uint64_t) cs.ullTotalPageFile, planned, 4ull << 30); std::fprintf(stderr, "strata serve: Windows commit: %.1f GiB left of a %.1f GiB limit (RAM + page file)\n", (double) cs.ullAvailPageFile / 1073741824.0, (double) cs.ullTotalPageFile / 1073741824.0); if (cv.warn) std::fprintf(stderr, "strata serve: %s\n", cv.text.c_str()); } } #endif // STRATA_PREFILL_CPU_SHARE_BATCH=1 (opt-in): the prompt path gets the pool beside batch slots too; a read takes the // share only while no slot decodes (set_share_blocked before each read), since the slots' windows use the pool static const bool share_batch = [] { const char* v = std::getenv("STRATA_PREFILL_CPU_SHARE_BATCH"); return v != nullptr && v[0] == '1'; }(); const bool share_pool = (o.batch <= 0 || share_batch) && !o.no_pool; if (share_batch && o.batch > 0 && !o.no_pool) std::fprintf(stderr, "strata serve: STRATA_PREFILL_CPU_SHARE_BATCH=1: the prompt path may use the CPU pool beside the " "%lld batch slots, for a read with no slot decoding\n", (long long) o.batch); bool share_has_work = strata::prefill::share_rules::default_share_has_work( (int64_t) xcache.slots(), (int64_t) (g.n_layers * g.n_expert)); // #1595 if (!share_has_work) std::fprintf(stderr, "strata serve: every expert is in the GPU cache (%lld of %lld): the CPU prefill share has " "nothing to take, so it is not armed by default (STRATA_PREFILL_CPU_SHARE=auto forces it)\n", (long long) xcache.slots(), (long long) (g.n_layers * g.n_expert)); if (share_pool && stages.empty() && !multi_gpu && share_has_work && !share_default_ok()) share_has_work = false; // H11 if (stages.empty() && !multi_gpu && o.batch <= 0) // STRATA_SWITCH_POINT: one card, no batch slots; before any bytes_needed, like the share strata::prefill::Prefill::set_card_expert_share((int64_t) xcache.slots(), (int64_t) (g.n_layers * g.n_expert), xcache.slots() > 0 ? (double) xcache.bytes() / (double) xcache.slots() / 1e6 : 0.0, o.pcie_probe_gbps); strata::prefill::Prefill::arm_cpu_share(share_pool, share_pool && stages.empty() && !multi_gpu && share_has_work); void* borrow = nullptr; uint64_t borrow_bytes = 0; int32_t lend_first = -1; // the first slot the prompt path may borrow (its largest chunk) // ---- WHO BORROWS, AND FROM WHOSE CACHE. One entry per prompt path: CUDA0's (layers [0, split_at[0]), // which is the whole model without a split) borrowing the tail of CUDA0's cache, then one per stage // borrowing the tail of ITS OWN cache. A loan is sized by the exact `Prefill::bytes_needed` for the // chunk, is laid out by `Prefill::relayout`, and is refilled before any window reads - so outside the // prompt the whole cache is expert cache. THIS IS THE POINT OF THE STRUCT: the loan used to exist only // for CUDA0, and `no_prefill_borrow` made every stage instead withhold a chunk-sized reserve from its // cache for the entire session, which is what cost the 4-way its context (see the note at the top of the // layer-split block). A stage may only lend the rows for ITS OWN layers: `host_res` is one table whose // slot values are indices into whichever cache owns the layer, so a loan that marked rows by slot number // alone would hand CUDA0 a slot belonging to another stage's cache. struct PfPart { strata::core::ExpertCache* cache = nullptr; const strata::core::SessionState* ses = nullptr; strata::prefill::Prefill* sp = nullptr; int dev = -1; // -1: leave the device alone (CUDA0) int64_t lb = 0, le = 0; // the layers whose rows this cache holds - the only rows it may lend int32_t first = -1; // the first slot it may lend, for the chunk that was chosen int32_t first_now = -1; // where its buffers are laid out now int64_t lent_chunk = 0; std::vector> lent; }; // bytes -> slots for one cache: exact when it knows its per-slot offsets (a native pack's blobs differ // per layer), otherwise max_blob each. auto cache_slots_for = [&](const strata::core::ExpertCache& xc, uint64_t need) -> int64_t { return strata::program::split_lend_slots(xc.slots(), xc.bytes(), xc.slot_offsets(), (uint64_t) strata::kernels::cpu::expert_layout().max_blob, need); }; auto on_part_device = [](int dev) { return strata::core::OnDevice(dev); }; // `tail` (>= 0): the lent fused layout's MMQ tail in tokens (loan_rules.hpp); -1: today's floor - 1 auto part_slots = [&](const PfPart& p, int64_t c, int64_t tail = -1) -> int64_t { return cache_slots_for(*p.cache, strata::program::split_part_figure(on_part_device, p.dev, [&] { return strata::prefill::Prefill::bytes_needed(g, *p.ses, c, srcp != nullptr, tail); })); }; auto part_bytes = [&](const PfPart& p, int32_t first) -> uint64_t { strata::core::ExpertCache& xc = *p.cache; return xc.slot_offsets() ? (uint64_t) (xc.bytes() - (int64_t) xc.slot_offsets()[first]) : (uint64_t) (xc.slots() - first) * (uint64_t) strata::kernels::cpu::expert_layout().max_blob; }; // #340: a layer split whose caches already hold most experts streams few of them through the prompt path, so // the 384-slot ring (sized for a card that streams nearly every expert of a chunk) only makes every stage's // loan bigger: 96 slots (0.1.30's ring here) when >= 75% of the (layer, expert) pairs are resident. One GPU // keeps the pinned-share rule. STRATA_SPLIT_RING=N: N slots on a split; 0: the pinned-share rule. // (decided above, before the lend regions were sized: a no-op here unless the resident RAM mode skipped it) decide_split_ring(); std::vector pf_parts; int64_t pf_plan_chunk = 0; // #2824: the host-aware plan's chunk for prompts longer than o.prefill_chunk (0: none) #if defined(STRATA_PREFILL_FUSED) && !defined(STRATA_PREFILL_MMQ) int64_t pf_fit_tail = -1; // the tail the auto scan counts (fit_out_rule.hpp): -1 today's floor - 1, 0 after a tail-0 scan int64_t pf_fit_small = 0; // that scan's small_max (0.1.39's chunk): the request path's today's-cut limit after a tail-0 scan bool pf_small_taken = false; // the small-card prompt path was taken #endif // a cache too small to lend the prompt path its buffers would make it allocate them on top - on a card // whose cache already filled its reserve, that is the over-subscription the auto sizing avoids - so the // chunk is the largest one EVERY participant can lend (a smaller chunk only reads slower) if (pf_borrow && d_res != nullptr) { pf_parts.push_back({&xcache, &ss, &sp, -1, 0, multi_gpu ? split_at[0] : g.n_layers, -1, -1, 0, {}}); for (auto& st : stages) pf_parts.push_back({&st->cache, &st->ss, &st->sp, st->dev, st->lb, st->le, -1, -1, 0, {}}); // The two tests plan_lend makes for CUDA0 alone, one participant at a time: a loan must leave the // 128-slot floor. The percentage cap is an AUTO-chunk rule and only the auto scan applies it - an // explicit --prefill is the operator's number, and a loan of it only has to fit. With one participant // (no split) this reduces to plan_lend exactly, so the single-GPU loan is unchanged from main. auto fits_one = [&](const PfPart& p, int64_t c, bool cap) -> bool { #if defined(STRATA_PREFILL_FUSED) && !defined(STRATA_PREFILL_MMQ) const int64_t k = part_slots(p, c, cap ? pf_fit_tail : -1); // tail 0 only in the auto scan after fit_out's case #else const int64_t k = part_slots(p, c); #endif if (k <= 0 || k + g_lend_keep > p.cache->slots()) return false; return !(cap && k * 100 > kAutoLendPct * p.cache->slots()); }; // `only`: CUDA0's cache alone (#448: what one GPU would choose, for the log below); null: every one auto fits = [&](int64_t c, bool cap, const PfPart* only = nullptr) -> bool { if (only != nullptr) return fits_one(*only, c, cap); for (const PfPart& p : pf_parts) if (!fits_one(p, c, cap)) return false; return true; }; // The chunk and the ring are one budget. The ring used to be a fixed 384 slots taken off the top // before the chunk was considered: 506 MiB on a Q2_0 pack, where it was tuned, but 1,912 MiB on // Q8_0, more than half an 8 GB card's cache - which is what kept that card at a 1024-token chunk. // Size the chunk first and hand the ring what the smallest participant leaves over, up to the ring's // byte budget - but hand it ALL of it, as in plan_lend: the ring is the better buy per byte (the // measurements are there), so the chunk to take is the largest one that still leaves the ring full, // not the largest one that leaves it anything at all. kRingMin is the fallback floor for a rig where // no chunk can afford a full ring; ring_slots() returns STAGE at or below it, which turns streaming // off. constexpr int64_t kRingMin = 16; // The room is a BYTE budget, as in plan_lend: a ring slot is max_blob bytes, but a cache slot holds // its own layer's blob, which on this rig averages 0.85 of it. In slots the ring looked 18% cheaper // than it is, and a chunk whose ring only fitted after that discount was refused outright - the scan // stopped one step short while the chunk it did take had room to spare for the cap-sized ring. const int64_t kBlob = (int64_t) strata::kernels::cpu::expert_layout().max_blob; auto ring_room = [&](int64_t c, const PfPart* only, int64_t cap) -> int64_t { int64_t room = cap; for (const PfPart& p : pf_parts) { if (only != nullptr && &p != only) continue; // clamped at 0: a cache under 128 slots has a negative lend budget, and `slots - budget` is // then `slots`, which is off_[slots] - the end of the prefix sum, so that cache lends 0 bytes // rather than reading one entry past its offsets const int64_t budget = std::max(0, std::min(p.cache->slots() - g_lend_keep, kAutoLendPct * p.cache->slots() / 100)); const uint64_t avail = part_bytes(p, (int32_t) (p.cache->slots() - budget)); const uint64_t nonring = strata::program::split_part_figure(on_part_device, p.dev, [&] { #if defined(STRATA_PREFILL_FUSED) && !defined(STRATA_PREFILL_MMQ) // after fit_out's case: the chunk's own buffers at tail 0 (the ring's bytes do not depend on the tail) const uint64_t nr = strata::prefill::Prefill::bytes_needed_no_ring(g, *p.ses, c, srcp != nullptr); if (pf_fit_tail < 0) return nr; const uint64_t full = strata::prefill::Prefill::bytes_needed(g, *p.ses, c, srcp != nullptr); const uint64_t at0 = strata::prefill::Prefill::bytes_needed(g, *p.ses, c, srcp != nullptr, pf_fit_tail); return nr - std::min(nr, full - std::min(full, at0)); #else return strata::prefill::Prefill::bytes_needed_no_ring(g, *p.ses, c, srcp != nullptr); #endif }); room = std::min(room, (int64_t) ((avail - std::min(avail, nonring)) / (uint64_t) kBlob)); } return room; }; // The largest chunk on the 256-token grid that `only` - or, with null, every stage - can lend with the // ring still at its full byte budget (ring_room is capped at ring_max, so that is room == ring_max), // under the operator's ceiling (auto_ceiling keeps a bare `auto` at 8192, #282). Failing that, the // largest chunk whose ring clears kRingMin. // 0.1.39's list with its ring: the chunk it would pick, and the size up to which a prompt keeps that ring auto old_pick = [&](const PfPart* only) -> int64_t { strata::prefill::Prefill::set_ring_budget(0, 0); #if defined(STRATA_PREFILL_FUSED) && !defined(STRATA_PREFILL_MMQ) // 0.1.39's chunk is always priced with today's tail: it bounds every layout at or below it, a short tail included const int64_t fit_tail_was = pf_fit_tail; pf_fit_tail = -1; struct Back { int64_t& t; int64_t v; ~Back() { t = v; } } back{pf_fit_tail, fit_tail_was}; #endif static constexpr int64_t kAutoChunks[] = {32768, 16384, 8192, 6144, 4096, 3072, 2048, 1024, 512, 256}; for (const int64_t c : kAutoChunks) { if (c > 8192 && (c > o.prefill_auto_max || c > o.max_context)) continue; // #282, as plan_lend if (o.prefill_auto_cap > 0 && c > o.prefill_auto_cap) continue; // #1630 if (fits(c, true, only)) return c; } return 0; }; auto scan = [&](const PfPart* only) -> int64_t { if (!o.prefill_auto) { // an explicit --prefill is the operator's number, and a loan of it only has to fit for (int64_t c = o.prefill_chunk; c >= 256; c /= 2) if (fits(c, false, only)) return c; return 0; } if (!strata::prefill::Prefill::ring_bytes_enabled()) return old_pick(only); // STRATA_RING_BYTES=0 const int64_t small = old_pick(only); const int64_t cap = strata::prefill::Prefill::ring_cap_for(small); auto probe = [&](int64_t floor) -> int64_t { return biggest_chunk(auto_ceiling, [&](int64_t t) -> bool { const int64_t room = ring_room(t, only, cap); if (room < floor) return false; strata::prefill::Prefill::set_ring_budget((int) room, 0); // ring_slots() now returns `room` - unless STRATA_PREFILL_RING overrides it, in which // case the chunk has to fit THAT ring, which is the pre-fix rule and the A/B arm return fits(t, true, only); }); }; int64_t c = probe(cap); if (c == 0 && cap < strata::prefill::Prefill::ring_default_slots()) c = probe(kRingMin); return std::max(c, small); // never a smaller chunk than 0.1.39's }; int64_t chunk = scan(nullptr); // The small-card prompt path (strata::small_card_prompt_path; owner's yes 2026-11-02): this chunk is what the DEFAULT prompt path got from the cache. // Below 8,192 tokens the default streams every expert again for every chunk, and the unfused experts plus (from two chunks) the layer-major walk // read the same prompt 9-50% sooner (RESULTS-DF2MEM.md); the chunk is then sized again for that layout. One CUDA card, a native pack, an auto // chunk; STRATA_PF_FUSED / STRATA_PREFILL_LAYER_MAJOR set by the user win; STRATA_PF_SMALL=0 turns the rule off. if (chunk > 0 && o.prefill_auto && !multi_gpu && stages.empty() && !(std::getenv("STRATA_PF_SMALL") != nullptr && std::getenv("STRATA_PF_SMALL")[0] == '0')) { #if defined(STRATA_USE_HIP) constexpr bool pf_small_hip = true; #else constexpr bool pf_small_hip = false; #endif const char* fe = std::getenv("STRATA_PF_FUSED"); const char* le = std::getenv("STRATA_PREFILL_LAYER_MAJOR"); // STRATA_PF_FUSED "set by the user": a build without MMQ puts STRATA_PF_FUSED=1 into the environment itself before main (prefill.cpp, own_only_switches.hpp), // which is not a choice of the user's and must not switch the rule off; a value that was in the environment before that stays theirs const strata::SmallCardPromptPath pp = strata::small_card_prompt_path( chunk, pf_small_hip, 1, strata::kernels::cpu::expert_layout().native, strata::qwen_defaults_026(), strata::prefill::own_only_user_named("STRATA_PF_FUSED", fe), le != nullptr && le[0] != '\0'); if (pp.any()) { const int64_t chunk_default = chunk; // MMQ's buffer layout (so the layer-major walk runs); the native fused kernels still run in the walk's groups and the streamed chunks // (pf_fused_override.hpp), unless STRATA_PF_SMALL_FUSED=0 keeps MMQ's kernels there as before (a build without MMQ has none: always the fused kernels) if (pp.fused_off) strata::prefill::pf_fused_override().store(strata::prefill::own_only_build() || strata::prefill::small_card_kernels_on(std::getenv("STRATA_PF_SMALL_FUSED")) ? strata::prefill::kPfFusedKernelsOnly : 0); if (pp.layer_major) { #if defined(_WIN32) _putenv_s("STRATA_PREFILL_LAYER_MAJOR", "1"); #else setenv("STRATA_PREFILL_LAYER_MAJOR", "1", 0); #endif } chunk = scan(nullptr); #if defined(STRATA_PREFILL_FUSED) && !defined(STRATA_PREFILL_MMQ) pf_small_taken = chunk > 0; #endif if (chunk <= 0) { // the unfused layout's buffers do not fit anywhere: keep the default path as it was strata::prefill::pf_fused_override().store(-1); if (pp.layer_major) { #if defined(_WIN32) _putenv_s("STRATA_PREFILL_LAYER_MAJOR", ""); #else unsetenv("STRATA_PREFILL_LAYER_MAJOR"); #endif } chunk = scan(nullptr); std::fprintf(stderr, "strata serve: small expert cache: the unfused prompt path does not fit here; the default path stays (chunk %lld tokens)\n", (long long) chunk); } else std::fprintf(stderr, "strata serve: small expert cache: the default prompt path would read in chunks of %lld tokens (under %lld), " "so prompts are read the way that suits a card with little memory%s (chunk %lld tokens); STRATA_PF_SMALL=0 keeps the default path, " "STRATA_PF_FUSED / STRATA_PREFILL_LAYER_MAJOR set by hand win\n", (long long) chunk_default, (long long) strata::kSmallCardChunkBelow, pp.layer_major ? " and, from two chunks, the layer-major walk" : "", (long long) chunk); } } // #448: a small card in a layer split caps every stage's chunk (an RTX 3080's 512-slot cache held a // 32 GB card's split to 512 tokens: prompts 6.2x slower, decode the same). Named when it bites, so the // regression is one log line: each stage that cannot fund the chunk CUDA0 alone would read in. const int64_t alone = pf_parts.size() > 1 ? scan(&pf_parts[0]) : chunk; // both scans left the ring override on their own last trial: put it back on the chunk that won, which // is what `init` lays out and what the INFO line reports if (chunk > 0 && o.prefill_auto && strata::prefill::Prefill::ring_bytes_enabled()) { // a prompt that fits 0.1.39's chunk keeps 0.1.39's ring (one chunk: the smaller ring only slowed // it); the byte-budget ring is for the chunks past it const int64_t small = old_pick(nullptr); strata::prefill::Prefill::set_ring_budget( small >= chunk ? 0 : (int) ring_room(chunk, nullptr, strata::prefill::Prefill::ring_cap_for(small)), small); } // #2824: the VRAM pick, priced against the host (RAM left for the page cache, the displaced experts with no RAM // backup, the drive): a smaller chunk / ring when the file set the prompt re-reads outgrows the page cache. // The RAM copy is built by now, so its bytes and the lend slots it kept are known. const int64_t chunk_vram = chunk; if (chunk > 0 && o.prefill_auto && strata::prefill::Prefill::ring_bytes_enabled()) { const int64_t small0 = old_pick(nullptr); const int64_t cap0 = strata::prefill::Prefill::ring_cap_for(small0); const int64_t ring0 = small0 >= chunk ? 0 : ring_room(chunk, nullptr, cap0); auto restore_ring = [&] { strata::prefill::Prefill::set_ring_budget((int) ring0, small0); }; restore_ring(); uint64_t gc_bytes = 0; int64_t gc_slots = 0; for (const PfPart& p : pf_parts) { gc_bytes += (uint64_t) std::max(0, (int64_t) p.cache->bytes()); gc_slots += p.cache->slots(); } chunk = host_plan_chunk( chunk, gc_bytes, gc_slots, [&](int64_t c) { return fits(c, true, nullptr); }, [&](int64_t c, uint64_t& bytes, int64_t& slots) { bytes = 0; slots = 0; for (const PfPart& p : pf_parts) { const int64_t k = part_slots(p, c); if (k <= 0) continue; slots += k; bytes += part_bytes(p, (int32_t) (p.cache->slots() - k)); } }, [&](int64_t c) { return ring_room(c, nullptr, cap0); }, restore_ring); } // the buffers stay sized for today's chunk; the plan's smaller chunk applies to prompts longer than it (planned_chunk) if (chunk > 0 && chunk != chunk_vram) { pf_plan_chunk = chunk; chunk = chunk_vram; } #if defined(STRATA_PREFILL_FUSED) && !defined(STRATA_PREFILL_MMQ) // fit_out_rule.hpp: with the equal cut on one GPU and the request-sized tail loan, no layout above 0.1.39's chunk // carries a short tail, so the scan counts what those layouts carve: tail 0. Today's chunk stays when the // host-aware plan planned a smaller one, when it would plan one for the larger chunk, and when the start-up // layout of the larger chunk (today's tail) would not keep the 128-slot floor. if (chunk > 0 && pf_plan_chunk == 0) { namespace fo = strata::prefill::fit_out; const fo::ScanCase sc = fit_case(chunk, pf_small_taken); // pf_parts holds CUDA0 and every stage: one part iff stages.empty() if (fo::scan_tail(sc) == 0) { const int64_t small1 = old_pick(nullptr); // today's tail (old_pick) pf_fit_tail = 0; int64_t c_new = fo::pick(chunk, scan(nullptr), pf_fit_tail); if (c_new != chunk && !fits(c_new, false, nullptr)) c_new = chunk; // the start-up layout, today's tail // the RAM copy (resident modes): the larger chunk only when the copy keeps every slot of its start-up loan, // the largest loan any request takes at it; otherwise those experts would be read from the model file on // every chunk (#669). The arena holds every expert: no region, nothing to hold. if (c_new != chunk && !fo::region_holds(part_slots(pf_parts[0], c_new), src.complement_ready() ? src.resident_lent_slots() : -1)) c_new = chunk; const int64_t cap1 = strata::prefill::Prefill::ring_cap_for(small1); const int64_t ring1 = small1 >= c_new ? 0 : ring_room(c_new, nullptr, cap1); auto restore1 = [&] { strata::prefill::Prefill::set_ring_budget((int) ring1, small1); }; restore1(); if (c_new != chunk) { uint64_t gc_bytes = 0; int64_t gc_slots = 0; for (const PfPart& p : pf_parts) { gc_bytes += (uint64_t) std::max(0, (int64_t) p.cache->bytes()); gc_slots += p.cache->slots(); } const int64_t planned = host_plan_chunk( c_new, gc_bytes, gc_slots, [&](int64_t c) { return fits(c, true, nullptr); }, [&](int64_t c, uint64_t& bytes, int64_t& slots) { bytes = 0; slots = 0; for (const PfPart& p : pf_parts) { const int64_t k = part_slots(p, c, pf_fit_tail); if (k <= 0) continue; slots += k; bytes += part_bytes(p, (int32_t) (p.cache->slots() - k)); } }, [&](int64_t c) { return ring_room(c, nullptr, cap1); }, restore1); if (planned != c_new) c_new = chunk; } if (c_new == chunk) { // today's count and today's ring pf_fit_tail = -1; const int64_t small0 = old_pick(nullptr); strata::prefill::Prefill::set_ring_budget( small0 >= chunk ? 0 : (int) ring_room(chunk, nullptr, strata::prefill::Prefill::ring_cap_for(small0)), small0); } else { chunk = c_new; pf_fit_small = small1; } } } #endif if (chunk > 0 && alone > chunk_vram) { for (size_t i = 1; i < pf_parts.size(); ++i) { const PfPart& p = pf_parts[i]; if (fits_one(p, alone, o.prefill_auto)) continue; const int dev = p.dev < 0 ? 0 : p.dev; cudaDeviceProp prop{}; if (cudaGetDeviceProperties(&prop, dev) != cudaSuccess) { (void) cudaGetLastError(); prop.name[0] = 0; } const std::string pct = o.prefill_auto ? ", and lend at most " + std::to_string(kAutoLendPct) + "%" : ""; std::fprintf(stderr, "strata serve: WARNING: prompt chunk %lld tokens, not %lld: CUDA%d (%s) " "has %lld expert-cache slots, and a %lld-token chunk borrows %lld of them " "(it must keep 128%s) - prompts read slower than on CUDA0 alone (#448)\n", (long long) chunk_vram, (long long) alone, dev, prop.name, (long long) p.cache->slots(), (long long) alone, (long long) part_slots(p, alone), pct.c_str()); // the helper tiers start at CUDA1 without a split (and are enabled in order) std::fprintf(stderr, "strata serve: a card this small can serve as a helper expert cache " "instead of a split stage: without --layer-split, with %s " "(docs/SECOND_GPU.md)\n", dev == 1 ? "--expert-cache-device1 N" : "--expert-cache-device1..3 N, in order"); } } if (chunk > 0) { if (o.prefill_auto) // the RESOLVED ring, not the room offered: ring_slots() clamps to [16, RING_MAX] and a chunk // under stream_all_min() gets STAGE, and STRATA_PREFILL_RING overrides both. This is what // `init` lays out, and what the INFO line reports to the Monitor tab. { std::fprintf(stderr, "strata serve: prompt chunk auto: %lld tokens, a %lld-slot ring\n", (long long) chunk, (long long) strata::prefill::Prefill::ring_slots_for(chunk)); if (pf_plan_chunk > 0) std::fprintf(stderr, "strata serve: prompts longer than %lld tokens read in equal chunks of at most %lld " "(the host-aware plan); shorter ones in one chunk\n", (long long) chunk, (long long) pf_plan_chunk); } else if (chunk != o.prefill_chunk) std::fprintf(stderr, "strata serve: prompt chunk %lld -> %lld tokens so its buffers fit in " "every expert cache\n", (long long) o.prefill_chunk, (long long) chunk); o.prefill_chunk = chunk; for (PfPart& p : pf_parts) { p.first = (int32_t) (p.cache->slots() - part_slots(p, chunk)); p.first_now = p.first; } // #340: a split stage whose card still has room for the chunk's buffers (its cache already holds // every expert of its layers, so auto stopped short of its VRAM) keeps them as its own instead of // borrowing cache slots: nothing of it is lent, streamed during the prompt or refilled after it. // Room = the buffers + 1.5 GiB (the verify windows, the draft head, hipBLAS/cuBLAS workspaces made // after this). Layer splits only - one GPU keeps its loan exactly as before. // STRATA_SPLIT_OWN_BUFFERS=0: every stage borrows (0.1.30/0.1.31). static const bool own_ok = [] { const char* v = std::getenv("STRATA_SPLIT_OWN_BUFFERS"); return v == nullptr || v[0] != '0'; }(); if (pf_parts.size() > 1 && own_ok) { for (PfPart& p : pf_parts) { const strata::core::OnDevice on(p.dev); size_t fb = 0, tb = 0; if (cudaMemGetInfo(&fb, &tb) != cudaSuccess) { (void) cudaGetLastError(); continue; } const uint64_t need = strata::prefill::Prefill::bytes_needed(g, *p.ses, chunk, srcp != nullptr); if ((uint64_t) fb >= need + (3ull << 29)) { std::fprintf(stderr, "strata serve: CUDA%d keeps its own prompt buffers (%.2f GiB of " "%.2f GiB free): no loan\n", p.dev < 0 ? 0 : p.dev, (double) need / 1073741824.0, (double) fb / 1073741824.0); p.first = -1; p.first_now = -1; } } } lend_first = pf_parts[0].first; borrow = lend_first >= 0 ? xcache.device_slot(lend_first) : nullptr; borrow_bytes = lend_first >= 0 ? part_bytes(pf_parts[0], lend_first) : 0; } else if (o.prefill_auto) { o.prefill_chunk = 1024; // nothing lendable: small buffers of its own } else if (pf_parts.size() > 1) { // An explicit chunk no stage can lend in full. main falls back to the prompt path's own buffers // here and so do we, rather than refusing to start - but say what every stage has, because a split // stage that has to allocate these on top of a cache that already filled its VRAM will not fit, // and `init` would otherwise report only that the buffers do not fit. std::fprintf(stderr, "strata serve: no stage can lend the prompt path its %lld-token buffers, so " "each stage allocates its own:\n", (long long) o.prefill_chunk); for (const PfPart& p : pf_parts) std::fprintf(stderr, "strata serve: CUDA%d has %lld slots, and a %lld-token chunk needs " "the last %lld of them\n", p.dev < 0 ? 0 : p.dev, (long long) p.cache->slots(), (long long) o.prefill_chunk, (long long) part_slots(p, o.prefill_chunk)); } } else if (o.prefill_auto && d_res == nullptr) { o.prefill_chunk = 1024; // #85: no expert cache at all (a full 8 GB card): small buffers of its own } if (o.prefill_head_alias) { for (PfPart& p : pf_parts) { p.first = p.cache->slots() > 1 ? 1 : -1; p.first_now = p.first; } lend_first = pf_parts[0].first; borrow = lend_first >= 0 ? xcache.device_slot(lend_first) : nullptr; borrow_bytes = lend_first >= 0 ? part_bytes(pf_parts[0], lend_first) : 0; size_t free_b = 0, total_b = 0; cudaMemGetInfo(&free_b, &total_b); static constexpr int64_t candidates[] = {2048, 1536, 1024, 512}; for (const int64_t candidate : candidates) if (strata::prefill::Prefill::bytes_needed(g, ss, candidate) + (512ull << 20) <= free_b + borrow_bytes) { o.prefill_chunk = candidate; break; } std::fprintf(stderr, "strata serve: prompt chunk head alias: %lld tokens with %lld MiB borrowed and " "%lld MiB free\n", (long long) o.prefill_chunk, (long long) (borrow_bytes >> 20), (long long) (free_b >> 20)); } #if defined(STRATA_GPU_METAL) // Metal: the prompt path's buffers are the Metal window's own (a region of its expert arena, metal/src/engine/window.cpp) - there is // no loan of expert-cache slots. Taking one anyway made short prompts end in `Prefill::relayout` ("a chunk of at most 0": the Metal // Prefill has no borrowed layout) and long ones refill "lent" slots through a copy into device allocations the Metal window had given back. for (PfPart& p : pf_parts) { p.first = -1; p.first_now = -1; } lend_first = -1; borrow = nullptr; borrow_bytes = 0; #endif // STRATA_MTP_ROOM_MIN=TOKENS (opt-in): a request that READS at least TOKENS prompt tokens (0: every request) // points the prompt path's ring AT the MTP drafter's 512 routed experts - 708 MB that only the DECODE reads // (record_rest; the prompt's own passes, record_front's K/V and the prompt path's Prefill::draft_kv, run the // layer's dense tensors and its K/V) - for as long as the prompt is read. The block is lent IN PLACE: it is // never freed, never allocated again and never moves, so no prompt path is laid out again, the decode's // captured graphs stay valid (nothing is dropped), and what comes back before the first window is the // decode's own bytes (MtpDrafter::experts_reclaim). TOKENS counts the tokens this request reads, not the // whole prompt: a turn that reuses a cached conversation prefix and reads a few hundred tokens gains nothing // from the room and does not take it. Unset (the default): not one line below runs, and the prompt path is // laid out exactly as before. const int64_t mtp_room_min = [] { const char* v = std::getenv("STRATA_MTP_ROOM_MIN"); if (v == nullptr || v[0] == '\0') return (int64_t) -1; char* end = nullptr; const long long n = std::strtoll(v, &end, 10); if (end == v || *end != '\0' || n < 0) return (int64_t) -2; // not a count: say so, not "0: every request" return (int64_t) n; }(); if (mtp_room_min == -2) { std::fprintf(stderr, "strata generate: STRATA_MTP_ROOM_MIN=%s is not a token count (0: every request)\n", std::getenv("STRATA_MTP_ROOM_MIN")); return 2; } int mtp_room_slots = 0; if (mtp_room_min >= 0) { const char* why = !o.serve ? "it needs --serve" : o.mtp.empty() ? "it needs --mtp" : o.batch > 0 ? "it does not support --batch: its slot drafters share the drafter's weights" : mtp.experts_bytes() == 0 ? "the drafter's 512 experts are not this drafter's to lend" : nullptr; if (why != nullptr) { std::fprintf(stderr, "strata generate: STRATA_MTP_ROOM_MIN is unavailable: %s\n", why); return 2; } const int64_t blob = (int64_t) strata::kernels::cpu::expert_layout().max_blob; mtp_room_slots = blob > 0 ? (int) std::min(mtp.experts_bytes() / blob, 4096) : 0; std::fprintf(stderr, "strata serve: STRATA_MTP_ROOM_MIN=%lld: a request that reads %lld prompt tokens or " "more points the prompt path's ring on CUDA%d at the drafter's %llu MiB of experts " "(%d slots past its own) for as long as it is read, and the decode's own bytes are back " "before the first window\n", (long long) mtp_room_min, (long long) mtp_room_min, mtp.device(), (unsigned long long) (mtp.experts_bytes() >> 20), mtp_room_slots); } bool any_loan = borrow != nullptr; for (size_t i = 1; i < pf_parts.size(); ++i) any_loan = any_loan || pf_parts[i].first >= 0; if (nib::any_on()) { // STRATA_EXPERT_NIBBLE: the prompt path keeps its own buffers (a loan is refilled with GGUF blobs) and reads in // the chunk it reads without the switch (the chunking is part of the replies' bits: auto's ceiling, or // --prefill N, and no host-aware plan of smaller chunks). Otherwise refused, never a quietly different reply. std::string why; const int64_t expect = o.prefill_auto ? auto_ceiling : nib_chunk_asked; if (any_loan) why = "the prompt path borrows expert-cache slots (a loan is refilled with GGUF blobs)"; else if (o.prefill_chunk != expect) why = "the prompt chunk is " + std::to_string(o.prefill_chunk) + " tokens, not the " + std::to_string(expect) + " it is without the switch when nothing limits it (that would change the replies' bits; an explicit " "--prefill N that fits keeps N)"; else if (pf_plan_chunk > 0) why = "the host-aware plan reads long prompts in chunks of " + std::to_string(pf_plan_chunk) + " tokens"; std::string room; for (size_t i = 0; why.empty() && i <= stages.size(); ++i) { const int dev = i == 0 ? -1 : stages[i - 1]->dev; const strata::core::OnDevice on(dev); size_t fb = 0, tb = 0; if (cudaMemGetInfo(&fb, &tb) != cudaSuccess) { (void) cudaGetLastError(); continue; } char b[64]; std::snprintf(b, sizeof b, "CUDA%d %.2f GiB", dev < 0 ? 0 : dev, (double) fb / 1073741824.0); room += (room.empty() ? "" : ", ") + std::string(b); } if (!why.empty()) { std::fprintf(stderr, "strata serve: STRATA_EXPERT_NIBBLE refuses the start: %s (STRATA_EXPERT_NIBBLE_SKIP= " "keeps some layers' GGUF blocks and their smaller slots)\n", why.c_str()); return 1; } std::fprintf(stderr, "strata serve: STRATA_EXPERT_NIBBLE: prompt chunk %lld, no loan; free after the prompt " "buffers: %s\n", (long long) o.prefill_chunk, room.c_str()); } if (any_loan) { if (borrow != nullptr) std::fprintf(stderr, "strata serve: the prompt path borrows %lld CUDA0 cache slots (%.2f GiB)\n", (long long) (xcache.slots() - lend_first), (double) borrow_bytes / 1073741824.0); for (size_t i = 1; i < pf_parts.size(); ++i) // one loan per stage, from that stage's own cache if (pf_parts[i].first >= 0) std::fprintf(stderr, "strata serve: CUDA%d prompt path borrows %lld of its %lld slots (%.2f GiB)\n", pf_parts[i].dev, (long long) (pf_parts[i].cache->slots() - pf_parts[i].first), (long long) pf_parts[i].cache->slots(), (double) part_bytes(pf_parts[i], pf_parts[i].first) / 1073741824.0); // A split's RAM copy keeps the experts of the slots the prompt path borrows (the lend regions sized above): // every borrowed expert not kept is streamed from the GGUF mmap during every chunk. Say both counts side // by side - they used to differ whenever a ring override (STRATA_SPLIT_RING) was set, because the regions // were sized with the default ring before the override applied. if (multi_gpu && src.complement_ready()) { int64_t borrowed = borrow != nullptr ? xcache.slots() - lend_first : 0; for (size_t i = 1; i < pf_parts.size(); ++i) if (pf_parts[i].first >= 0) borrowed += pf_parts[i].cache->slots() - pf_parts[i].first; const int64_t kept = src.resident_lent_slots(); std::fprintf(stderr, "strata serve: lend sizing: the prompt path borrows %lld slots (ring %lld slots at " "chunk %lld), %lld of them keep their experts in RAM too\n", (long long) borrowed, (long long) strata::prefill::Prefill::ring_slots_for(o.prefill_chunk), (long long) o.prefill_chunk, (long long) kept); if (kept < borrowed) std::fprintf(stderr, "strata serve: WARNING: %lld of the %lld borrowed slots have no RAM copy: " "their experts are streamed from the model file during every chunk\n", (long long) (borrowed - kept), (long long) borrowed); } } else { std::fprintf(stderr, "strata serve: the prompt path allocates its own buffers (too few cache slots to borrow)\n"); } // A GPU that shares the system RAM (cudaDevAttrIntegrated: the DGX Spark's GB10) with every expert in its cache: the // pages the start read from the GGUF are a second copy of the cache's bytes, and CUDA there counts only the RAM the // kernel has free (cudaMemGetInfo equals MemFree, not MemAvailable), so the picture reader's CUDA start found // ~1 GiB and fell back to the CPU (91 s for a 2048x1536 picture against about 0.5 s on the card). The engine gives // those pages back; the experts of the slots the prompt path borrows keep theirs (their refill reads them). The // cache holds the same bytes either way, so no output bit changes. STRATA_UMA_DROP_PAGES=0 keeps the pages (the A/B arm). // Linux CUDA builds only: an AMD APU (HIP maps the attribute to hipDeviceAttributeIntegrated) is not measured with it, the // gfx906 layer has no such attribute, Metal reports every Mac as integrated, and Windows has no page drop // (tools/test_uma_drop_guard.py checks this guard). #if defined(__linux__) && !defined(STRATA_USE_HIP) && !defined(STRATA_HIP_GFX906) && !defined(STRATA_GPU_METAL) // SPARK-UMA-DROP if (srcp == &src && gpu_holds_all && !multi_gpu && stages.empty() && [] { const char* v = std::getenv("STRATA_UMA_DROP_PAGES"); return v == nullptr || v[0] != '0'; }()) { int dev = 0, integ = 0; if (cudaGetDevice(&dev) == cudaSuccess && cudaDeviceGetAttribute(&integ, cudaDevAttrIntegrated, dev) == cudaSuccess && integ) { size_t f0 = 0, f1 = 0, tb = 0; (void) cudaMemGetInfo(&f0, &tb); const int32_t keep_from = borrow != nullptr && lend_first >= 0 ? lend_first : INT32_MAX; const auto t0 = Clock::now(); const uint64_t freed = src.drop_cached_pages([&](int64_t l, int64_t e) { const int32_t sl = xcache.slot_of(l, e); return sl != strata::core::kNotResident && sl >= keep_from; }); (void) cudaMemGetInfo(&f1, &tb); // only when pages were given back if (freed > 0) std::fprintf(stderr, "strata serve: this GPU shares the system memory and holds every expert, so the " "model file's cached copy of them is given back.\n"); const char* tr = std::getenv("STRATA_UMA_DROP_PAGES"); // 2: the numbers too (research) if (tr != nullptr && tr[0] == '2') std::fprintf(stderr, "strata serve: STRATA_UMA_DROP_PAGES: %.2f GiB of expert pages given back in %.1f ms; " "free on the GPU %.2f -> %.2f GiB\n", (double) freed / 1073741824.0, std::chrono::duration(Clock::now() - t0).count(), (double) f0 / 1073741824.0, (double) f1 / 1073741824.0); } else { (void) cudaGetLastError(); } } #endif // SPARK-UMA-DROP rss_probe("the prompt path set up"); // layer split across GPUs: a prompt path per stage, each handing its chunk's rows to the next. // THE CHUNK STEPS DOWN INSTEAD OF EXITING. A split's stage caches are sized after the arena is registered, and // the prompt path's own buffers (no loan) are not priced into them: with the whole arena pinned (#253) a // `--prefill auto` split could stop at start with "device buffers for a chunk of 2048 tokens do not fit". A // chunk that does not fit is tried again one size smaller, down to 512 tokens (a smaller chunk only reads slower). // The path the room belongs to (set below): the one on the drafter's card, which is where the ring's slots // point into the drafter's expert block. The room's LAYOUT is a start-up property - it costs nothing to // hold (no allocation, no VRAM: the slots ARE the drafter's bytes) - and a prompt takes it by moving that // path's ring count (set_ring_room_active), so any later rebuild here re-carves it the same way. strata::prefill::Prefill* room_path = nullptr; auto init_prompt_paths = [&]() -> int { // 0: ready; 1: failed (err set); 2: failed with "do not fit" room_path = nullptr; for (size_t i = 0; i < stages.size(); ++i) { GpuStage& st = *stages[i]; st.sp.set_stage(st.lb, i + 1 < stages.size() ? st.le : -1, i + 1 < stages.size() ? &stages[i + 1]->sp : nullptr); const strata::core::OnDevice on(st.dev); void* sb = nullptr; // this stage's own loan, out of its own cache uint64_t sbb = 0; // `first < 0`: no loan was taken (nothing was lendable), so this stage allocates its own buffers if (i + 1 < pf_parts.size() && pf_parts[i + 1].first >= 0) { sb = st.cache.device_slot(pf_parts[i + 1].first); sbb = part_bytes(pf_parts[i + 1], pf_parts[i + 1].first); } // STRATA_MTP_ROOM_MIN: the drafter's card is the one whose prompt path is laid out with the room const bool room_here = mtp_room_slots > 0 && mtp.device() == st.dev; if (room_here) room_path = &st.sp; st.sp.set_ring_room(room_here ? mtp_room_slots : 0); st.sp.set_ring_room_base(room_here ? mtp.experts_base() : nullptr, room_here ? mtp.experts_bytes() : 0); if (share_pool) st.sp.set_cpu_pool(&pool); // one stage at a time takes it for a chunk (prefill.cpp) if (!st.sp.init(st.wt, g, st.ss, srcp, &st.cache, host_res.data(), o.prefill_chunk, (void*) st.stream, err, sb, sbb, o.prefill_head_alias)) { err = "layer split, CUDA" + std::to_string(st.dev) + " prompt path: " + err; return err.find("do not fit") != std::string::npos ? 2 : 1; } } if (multi_gpu) sp.set_stage(0, split_at[0], &stages[0]->sp); if (share_pool) sp.set_cpu_pool(&pool); int cur_dev = 0; cudaGetDevice(&cur_dev); // the device this path is about to run on (dev -1: the current one) const bool room_here = mtp_room_slots > 0 && mtp.device() == cur_dev; if (room_here) room_path = &sp; sp.set_ring_room(room_here ? mtp_room_slots : 0); sp.set_ring_room_base(room_here ? mtp.experts_base() : nullptr, room_here ? mtp.experts_bytes() : 0); if (!sp.init(wt, g, ss, prefill_src, &xcache, host_res.data(), o.prefill_chunk, main_cs, err, borrow, borrow_bytes, o.prefill_head_alias)) return err.find("do not fit") != std::string::npos ? 2 : 1; if (mtp_room_slots > 0 && room_path == nullptr) // the drafter's card holds none of the prompt paths std::fprintf(stderr, "strata serve: prompt room: no prompt path runs on CUDA%d, the drafter's card: the " "prompt reads with its own ring\n", mtp.device()); return 0; }; static constexpr int64_t kStepChunks[] = {6144, 4096, 3072, 2048, 1536, 1024, 512}; { // First by arithmetic: a prompt path without a loan allocates its buffers, so the chunk must leave // headroom on that device (a chunk that fits to the last MiB left hipBLAS nothing: its GEMMs then // failed to launch on gfx1201 and the prompt hung). `bytes_needed` is the same count `init` makes. const int64_t kHeadroom = (o.prefill_chunk <= 512 ? 128ll : 512ll) << 20; // (a 512-token chunk or less is the tight-card path: its buffers are priced with a floor of their own) auto own_fits = [&](int64_t c, int& dev_out, int64_t& need_out, int64_t& free_out) -> bool { for (size_t i = 0; i <= stages.size(); ++i) { const bool loan = i == 0 ? borrow != nullptr : (i < pf_parts.size() && pf_parts[i].first >= 0); if (loan) continue; const int dev = i == 0 ? -1 : stages[i - 1]->dev; const strata::core::OnDevice on(dev); size_t fb = 0, tb = 0; cudaMemGetInfo(&fb, &tb); const int64_t need = (int64_t) strata::prefill::Prefill::bytes_needed(g, i == 0 ? ss : stages[i - 1]->ss, c, srcp != nullptr); if (need + kHeadroom > (int64_t) fb) { dev_out = dev < 0 ? 0 : dev; need_out = need; free_out = (int64_t) fb; return false; } } return true; }; int dev = 0; int64_t need = 0, fb = 0; // gfx1151 (Strix Halo, Windows): `prefill_own_keep_chunk` is set above because the prompt path keeps its own buffers at the 16,384-token // chunk and the cache sizing already reserved them. The "free VRAM" read here is the unified pool's figure after the pinned RAM complement // (which the pool counts twice), not a limit: with 860 MiB "free" the MTP engine allocates the 6.7 GiB of buffers anyway and reads prompts at // 955 tok/s, but this step-down found 1.7 GiB "free" in the DFlash2-alone engine (no MTP layer, a slightly larger cache), cut the chunk to // 1,536 and read them at 303 tok/s (RESULTS-DF2STRIX.md). The step-down stays for a real allocation failure (the loop below). // STRATA_PF_OWN_CHECK=1 (tester) restores the arithmetic check on this card. static const bool own_check_restored = [] { const char* v = std::getenv("STRATA_PF_OWN_CHECK"); return v != nullptr && v[0] == '1'; }(); const bool keep_chunk_uma = o.prefill_own_keep_chunk && !own_check_restored; if (!own_fits(o.prefill_chunk, dev, need, fb)) { if (keep_chunk_uma) { std::fprintf(stderr, "strata serve: a %lld-token chunk's prompt buffers need %lld MiB, %lld MiB are reported free: kept (this GPU's memory is the " "unified pool; STRATA_PF_OWN_CHECK=1 steps the chunk down by that figure)\n", (long long) o.prefill_chunk, (long long) (need >> 20), (long long) (fb >> 20)); } else { int64_t c = 0; for (const int64_t s : kStepChunks) { int d2 = 0; int64_t n2 = 0, f2 = 0; if (s < o.prefill_chunk && own_fits(s, d2, n2, f2)) { c = s; break; } } if (c > 0) { std::fprintf(stderr, "strata serve: a %lld-token chunk's prompt buffers need %lld MiB on CUDA%d, " "%lld MiB free: %lld-token chunks\n", (long long) o.prefill_chunk, (long long) (need >> 20), dev, (long long) (fb >> 20), (long long) c); o.prefill_chunk = c; } } } } mem_mark("before the prompt path init"); for (;;) { const int r = init_prompt_paths(); if (r == 0) break; int64_t next = 0; for (const int64_t c : kStepChunks) if (c < o.prefill_chunk) { next = c; break; } if (r == 2 && next > 0) { std::fprintf(stderr, "strata serve: %s: trying a %lld-token chunk\n", err.c_str(), (long long) next); // start the prompt paths over (a failed init may hold buffers), and consume the failed allocation's // error: it is sticky, and the next launch check would report "out of memory" for a kernel for (auto& stp : stages) { const strata::core::OnDevice on(stp->dev); stp->sp.reset(); (void) cudaGetLastError(); } sp.reset(); (void) cudaGetLastError(); o.prefill_chunk = next; if (any_loan) { // smaller loans for the smaller chunk for (PfPart& p : pf_parts) if (p.first >= 0) { p.first = (int32_t) (p.cache->slots() - part_slots(p, next)); p.first_now = p.first; } lend_first = pf_parts[0].first; borrow = lend_first >= 0 ? xcache.device_slot(lend_first) : nullptr; borrow_bytes = lend_first >= 0 ? part_bytes(pf_parts[0], lend_first) : 0; } err.clear(); continue; } std::fprintf(stderr, "strata serve: %s\n", err.c_str()); const bool batch_memory = o.batch >= 2 && o.prefill_own_keep_chunk && (err.find("fit") != std::string::npos || err.find("copy stream") != std::string::npos); if (err.find("fit") != std::string::npos && !batch_memory) // #85: say what frees VRAM std::fprintf(stderr, "strata serve: the GPU has too little free VRAM for the prompt path: turn images " "off (setup: --vision no), close other programs using the GPU, use a shorter " "context, or read prompts in smaller chunks (--prefill 512)\n"); if (batch_memory) // (the chunk list has been tried by now, and a failed attempt leaves the pool full: no retry can follow) std::fprintf(stderr, "strata: %d requests at once do not fit in this PC's memory: start with --batch %d\n", o.batch, o.batch - 1); return 1; } uma_refuse_chunk_if_full(o.prefill_chunk, borrow != nullptr, xcache.gib()); // The peer's streaming and a split's helpers live INSIDE the layout (`set_peer` / `set_stage_helper` build // them in the path's own Impl), so a path that is laid out again - the prompt room, below - has to be armed // again. Both calls start by dropping what they built before, and both leave `err` clear on a decline. auto arm_prompt_helpers = [&]() { if (peer.valid() && o.peer_prefill_rows != 0) { const int64_t rows = o.peer_prefill_rows > 0 ? o.peer_prefill_rows : o.prefill_chunk * K / 2; if (!sp.set_peer(&peer, rows, err)) { std::fprintf(stderr, "strata serve: %s - the prompt path stays on the primary GPU\n", err.c_str()); err.clear(); (void) cudaGetLastError(); // (as above) } } // a layer split: a one-chunk prompt runs the stages one after the other, so each stage's prompt path gets the // next stage's GPU (the last one the first's) to stream and compute a share of its experts meanwhile if (multi_gpu && !stages.empty()) { std::vector> paths{{&sp, 0}}; for (const auto& st : stages) paths.emplace_back(&st->sp, st->dev); for (size_t i = 0; i < paths.size(); ++i) { const strata::core::OnDevice on(paths[i].second); if (!paths[i].first->set_stage_helper(paths[(i + 1) % paths.size()].first, err)) { std::fprintf(stderr, "strata serve: %s - stage %zu reads its prompts alone\n", err.c_str(), i); err.clear(); } } } }; arm_prompt_helpers(); mem_mark("the head and the prompt path"); // #340: STRATA_SPLIT_SMALL_OWN=S (tokens): on a layer split, every stage that borrows keeps the slots for an // S-token chunk's buffers for the whole session (0.1.29's own buffers, carved from the tail of its cache): // a request of at most S prompt tokens then lends, streams and refills nothing, a longer one lends (and // refills) only the slots above them. Their experts stay non-resident (the CPU / PCIe path computes them). // STRATA_SPLIT_SMALL_MAX=M: a request of at most M prompt tokens reads in S-token chunks on those stages // (several chunks, still nothing lent) instead of borrowing for a bigger one. int64_t split_small = 0, split_small_max = 0; if (multi_gpu && !pf_parts.empty() && !host_res.empty()) { const char* v = std::getenv("STRATA_SPLIT_SMALL_OWN"); const int64_t S = v ? request_chunk(std::atoll(v), o.prefill_chunk) : 0; const char* vm = std::getenv("STRATA_SPLIT_SMALL_MAX"); split_small = S; split_small_max = S > 0 ? std::max(S, vm ? std::atoll(vm) : S) : 0; int64_t evicted = 0; for (PfPart& p : pf_parts) { if (S <= 0 || p.first < 0) continue; const int32_t first_s = std::max(p.first, (int32_t) (p.cache->slots() - part_slots(p, S))); int64_t n = 0; for (int64_t l = p.lb; l < p.le; ++l) for (int64_t ex = 0; ex < g.n_expert; ++ex) { int32_t& r = host_res[(size_t) (l * g.n_expert + ex)]; if (r >= first_s) { r = strata::core::kNotResident; ++n; } } evicted += n; std::fprintf(stderr, "strata serve: CUDA%d keeps %lld slots for %lld-token prompts (%lld experts " "no longer resident)\n", p.dev < 0 ? 0 : p.dev, (long long) (p.cache->slots() - first_s), (long long) S, (long long) n); } if (evicted > 0) { if (d_res != nullptr) res_put(d_res); for (auto& st : stages) { const strata::core::OnDevice on(st->dev); res_put(st->d_res); } } } 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 // neutral path (no upload, no buffer handed to the sampler). constexpr int kPenaltyWindowCap = 4096; // (the widest window the run can have: a batch of more than kVerifyNarrowT slots is one way to a wider one, a // prompt-lookup window longer than that (--lookup-max-t) the other) const size_t kHistSlots = (size_t) kPenaltyWindowCap * (size_t) (o.lookup_max_t > (int) strata::kernels::kVerifyNarrowT ? strata::kernels::kVerifyLongT : o.batch > strata::kernels::kVerifyNarrowT ? strata::kernels::kVerifyMaxT : strata::kernels::kVerifyNarrowT); int32_t* d_hist = nullptr; std::vector hist_stage(kHistSlots, -1); const int hist_dev = last_st ? last_st->dev : -1; // with the head: the last stage's device if (const strata::core::OnDevice on_h(hist_dev); cudaMalloc(&d_hist, kHistSlots * sizeof(int32_t)) != cudaSuccess) { std::fprintf(stderr, "strata serve: the penalty-history allocation failed\n"); return 1; } strata::core::Verifier ver; kvg.uncaptured = [&ver] { return ver.uncaptured_windows(); }; strata::core::VerifyHits vh; vh.d_res = thits.d_res; // STRATA_ROUTE_RESIDENT_MTP=1 (EXPERIMENTAL, with STRATA_ROUTE_RESIDENT=; changes the output): the MTP // draft's router gets the same residency bias, with the last layer's residency row as its table (single GPU) if (use_mtp && stages.empty() && thits.d_res != nullptr && std::getenv("STRATA_ROUTE_RESIDENT") != nullptr && std::getenv("STRATA_ROUTE_RESIDENT_MTP") != nullptr && std::atoi(std::getenv("STRATA_ROUTE_RESIDENT_MTP")) != 0) { const float margin = (float) std::atof(std::getenv("STRATA_ROUTE_RESIDENT")); int lo = 6, hi = 9; if (const char* v = std::getenv("STRATA_ROUTE_RESIDENT_RANKS")) std::sscanf(v, "%d-%d", &lo, &hi); if (margin > 0.0f) { mtp.set_route_resident(thits.d_res + (size_t) (g.n_layers - 1) * (size_t) g.n_expert, margin, lo, hi); std::fprintf(stderr, "strata generate: STRATA_ROUTE_RESIDENT_MTP: the MTP draft's router is biased toward layer %lld's resident experts (margin %g, ranks %d-%d; experimental)\n", (long long) (g.n_layers - 1), margin, lo, hi); } } vh.h_res = host_res.empty() ? nullptr : host_res.data(); vh.cache_base = thits.cache_base; vh.blob = thits.blob; vh.slot_off = xcache.slot_offsets(); // E-6: the device plan's pointers vh.n_slots = xcache.slots(); // Layer split: `ver` runs layers [0, K1) and hands its residual to the next stage's verifier, and so on; the // last runs the head. The hand-offs are mapped pinned memory, portable: a stage on another GPU reads it. // (--split-device 0: the second stage on this GPU, sharing its weights, session and cache - the A/B.) strata::core::Verifier ver_same; SplitDrive split_drive; auto stage_ver = [&](int st) -> strata::core::Verifier& { return st == 0 ? ver : split_same ? ver_same : stages[(size_t) st - 1]->ver; }; auto pcie_num_of = [](double f) { return std::max(0, std::min(256, (int) (f * 256.0 + 0.5))); }; const int n_stages = split_devs.empty() ? 1 : (int) split_at.size() + 1; // a layer split's hand-off buffers (and its pipelined windows) hold kVerifyMaxT rows: --lookup-max-t stops there if (n_stages > 1 && o.spec > strata::kernels::kVerifyNarrowT) { std::fprintf(stderr, "strata serve: --lookup-max-t %d: a layer split's windows stop at %d tokens\n", o.lookup_max_t, strata::kernels::kVerifyNarrowT); o.spec = strata::kernels::kVerifyNarrowT; } // --pipeline-windows (decided where the split was): two verifiers per stage, one for the even windows and one // for the odd ones, sharing one stream of their card, and a hand-off per parity - so stage 0 can run window // K+1 while stage 1 still reads window K's hand-off. With more stages every stage but the last is a "front" // stage: window K+1 follows window K through them one card behind, and only the last stage waits for K's verdict const bool pipe = o.pipeline_windows > 0 && n_stages >= 2 && !split_same && (int) stages.size() == n_stages - 1; strata::core::Verifier ver_b; SplitDrive split_drive_b; std::vector pl_stream(pipe ? (size_t) n_stages : 0, nullptr); // stage st's verifier of one parity (0: the even windows, 1: the odd ones) auto stage_ver_p = [&](int st, int par) -> strata::core::Verifier& { if (st == 0) return par == 0 ? ver : ver_b; return par == 0 ? stages[(size_t) st - 1]->ver : stages[(size_t) st - 1]->ver_b; }; if (pipe) { bool ok_p = true; ok_p = cudaStreamCreateWithFlags(&pl_stream[0], cudaStreamNonBlocking) == cudaSuccess; // the current card for (int st = 1; st < n_stages && ok_p; ++st) { const strata::core::OnDevice on(stages[(size_t) st - 1]->dev); ok_p = cudaStreamCreateWithFlags(&pl_stream[(size_t) st], cudaStreamNonBlocking) == cudaSuccess; } if (!ok_p) { std::fprintf(stderr, "strata serve: --pipeline-windows: stream creation failed\n"); return 1; } for (int st = 0; st < n_stages; ++st) for (int par = 0; par < 2; ++par) { stage_ver_p(st, par).set_stream(pl_stream[(size_t) st]); stage_ver_p(st, par).set_always_publish(true); } } if (n_stages > 1) { // pipelined slot groups write their rows at hbase = group * rows-per-group, so with more than // kVerifyNarrowT slots in groups the hand-off holds one row per slot (otherwise kVerifyNarrowT, as before; a // wide build holds more only for a batch of more than that: the buffer is not made larger for a run that // never forms a window of 9..16 rows) // (STRATA_PIPED_MTP: per slot its token and up to pm_drafts proposals) const int hrows = piped_mtp ? std::max(strata::kernels::kVerifyNarrowT, (1 + pm_drafts) * o.batch) : !batch_mtp && o.batch_groups > 1 ? std::max(strata::kernels::kVerifyNarrowT, o.batch) : !batch_mtp ? std::max(strata::kernels::kVerifyNarrowT, std::min(o.batch, strata::kernels::kVerifyMaxT)) : strata::kernels::kVerifyNarrowT; const size_t hb = (size_t) hrows * (size_t) strata::core::Verifier::handoff_floats(g) * sizeof(float); std::vector hand((size_t) n_stages - 1, nullptr); for (float*& h : hand) { float* hh = nullptr; if (cudaHostAlloc((void**) &hh, hb, cudaHostAllocMapped | cudaHostAllocPortable) != cudaSuccess || cudaHostGetDevicePointer((void**) &h, hh, 0) != cudaSuccess) { std::fprintf(stderr, "strata serve: the layer-split hand-off allocation failed\n"); return 1; } std::memset(hh, 0, hb); } // STRATA_SPLIT_OVERLAP=1 (opt-in; measured on 2x RX 7900 XTX only): a ready word per hand-off, raised by the // writing stage's GPU, so the next stage's window is launched early and the host never syncs between // stages (Verifier::set_handoff_flags). Not for --split-device 0 (both stages on one GPU). const bool overlap_asked = [] { const char* v = std::getenv("STRATA_SPLIT_OVERLAP"); return v != nullptr && std::atoi(v) != 0; }(); // --pipeline-windows (#859) runs its own overlapped loop with its own hand-offs: the two do not mix const bool overlap = overlap_asked && !split_same && o.pipeline_windows == 0; if (overlap_asked && o.pipeline_windows > 0) std::fprintf(stderr, "strata serve: STRATA_SPLIT_OVERLAP is off beside --pipeline-windows %d " "(that loop overlaps the stages itself)\n", o.pipeline_windows); std::vector hflag_h((size_t) n_stages - 1, nullptr), hflag_d((size_t) n_stages - 1, nullptr); if (overlap) for (size_t i = 0; i < hflag_h.size(); ++i) { if (cudaHostAlloc((void**) &hflag_h[i], 64, cudaHostAllocMapped | cudaHostAllocPortable) != cudaSuccess || cudaHostGetDevicePointer((void**) &hflag_d[i], hflag_h[i], 0) != cudaSuccess) { std::fprintf(stderr, "strata serve: the layer-split hand-off flag allocation failed\n"); return 1; } std::memset(hflag_h[i], 0, 64); } split_drive.base = &drive; split_drive.n = n_stages; for (int st = 0; st < n_stages; ++st) { stage_ver(st).set_stage(st == 0 ? 0 : split_at[(size_t) st - 1], st + 1 < n_stages ? split_at[(size_t) st] : -1, st == 0 ? nullptr : hand[(size_t) st - 1], st + 1 < n_stages ? hand[(size_t) st] : nullptr); if (hrows > strata::kernels::kVerifyNarrowT) stage_ver(st).set_handoff_rows(hrows); #if defined(STRATA_HAVE_DFLASH2) if (use_df2 && st > 0) stage_ver(st).set_taps(df2.tap_layers()); // (stage 0 gets its taps below, as on one card) if (batch_df2 && st > 0) stage_ver(st).set_batch_taps(true); #endif if (overlap) stage_ver(st).set_handoff_flags(st == 0 ? nullptr : hflag_h[(size_t) st - 1], st == 0 ? nullptr : hflag_d[(size_t) st - 1], st + 1 < n_stages ? hflag_h[(size_t) st] : nullptr, st + 1 < n_stages ? hflag_d[(size_t) st] : nullptr); split_drive.end[st] = st + 1 < n_stages ? split_at[(size_t) st] : g.n_layers; split_drive.cache_base[st] = drive.d.cache_base; split_drive.cache_slot_off[st] = drive.d.cache_slot_off; split_drive.pcie_num[st] = pcie_num_of(o.pcie_frac); } for (int st = 1; st < n_stages; ++st) { bool ok_s = false; if (split_same) { { std::string le; if (!lat_tab.load(g, le)) { std::fprintf(stderr, "strata serve: %s\n", le.c_str()); return 1; } } ok_s = ver_same.init(wt, g, ss, vh, native_head.loaded() ? &native_head : nullptr, std::max(o.spec, std::min(o.batch, (int) strata::kernels::kVerifyMaxT)), err); } else { GpuStage& gs = *stages[(size_t) st - 1]; const strata::core::OnDevice on(gs.dev); strata::core::VerifyHits vs; vs.d_res = gs.d_res; vs.h_res = host_res.empty() ? nullptr : host_res.data(); vs.cache_base = gs.cache.device_slot(0); vs.blob = thits.blob; vs.slot_off = gs.cache.slot_offsets(); vs.n_slots = gs.cache.slots(); gs.ver.set_remote_expert_opt(remote_opt.get()); // --batch-mtp: every stage runs the same 2-rows-per-slot windows as the first (up to kVerifyMaxT // rows, the hand-off's size) and bounds its captured batch layouts like the first (below) if (batch_mtp) gs.ver.set_batch_graph_limit(64); // (STRATA_PIPED_MTP: a group's window is its one slot's token and proposals, at most --spec rows, // so the stage keeps the windows it has without --batch-mtp - the solo path's too) ok_s = gs.ver.init(gs.wt, g, gs.ss, vs, gs.head.loaded() ? &gs.head : nullptr, batch_max_t(), err); split_drive.cache_base[st] = gs.cache.device_slot(0); split_drive.cache_slot_off[st] = gs.cache.slot_offsets(); split_drive.pcie_num[st] = pcie_num_of(gs.pcie_frac); } if (!ok_s) { std::fprintf(stderr, "strata serve: layer split, stage %d: %s\n", st + 1, err.c_str()); return 1; } } for (int st = 0; st + 1 < n_stages; ++st) stage_ver(st).set_next(&stage_ver(st + 1), &split_drive); std::string plan_s = "0-" + std::to_string(split_at[0] - 1) + " (CUDA0)"; for (int st = 1; st < n_stages; ++st) plan_s += ", " + std::to_string(split_at[(size_t) st - 1]) + "-" + std::to_string(split_drive.end[st] - 1) + " (CUDA" + std::to_string(split_same ? 0 : stages[(size_t) st - 1]->dev) + ")"; std::fprintf(stderr, "strata serve: layer split: layers %s, one hand-off per window%s\n", plan_s.c_str(), overlap ? " (overlapped: STRATA_SPLIT_OVERLAP=1)" : ""); } // --pipeline-windows: the odd windows' verifiers and their hand-off (initialized before `ver`, which stays the // watchdog's verifier), and the drafter's own row buffer, which either parity's rows are copied into float* pl_mtp_R = nullptr; if (pipe) { const size_t hb = (size_t) strata::kernels::kVerifyNarrowT * (size_t) strata::core::Verifier::handoff_floats(g) * sizeof(float); std::vector hand_b((size_t) n_stages - 1, nullptr); // the odd windows' hand-off per boundary for (float*& h : hand_b) { float* hh = nullptr; if (cudaHostAlloc((void**) &hh, hb, cudaHostAllocMapped | cudaHostAllocPortable) != cudaSuccess || cudaHostGetDevicePointer((void**) &h, hh, 0) != cudaSuccess) { std::fprintf(stderr, "strata serve: --pipeline-windows: the second hand-off allocation failed\n"); return 1; } std::memset(hh, 0, hb); } ver_b.set_stage(0, split_at[0], nullptr, hand_b[0]); for (int st = 1; st < n_stages; ++st) { GpuStage& gs = *stages[(size_t) st - 1]; const bool last = st + 1 == n_stages; gs.ver_b.set_stage(split_at[(size_t) st - 1], last ? -1 : split_at[(size_t) st], hand_b[(size_t) st - 1], last ? nullptr : hand_b[(size_t) st]); const strata::core::OnDevice on(gs.dev); strata::core::VerifyHits vs; vs.d_res = gs.d_res; vs.h_res = host_res.empty() ? nullptr : host_res.data(); vs.cache_base = gs.cache.device_slot(0); vs.blob = thits.blob; vs.slot_off = gs.cache.slot_offsets(); vs.n_slots = gs.cache.slots(); if (!gs.ver_b.init(gs.wt, g, gs.ss, vs, gs.head.loaded() ? &gs.head : nullptr, o.spec, err)) { std::fprintf(stderr, "strata serve: --pipeline-windows: the second verifier on CUDA%d (stage %d): %s " "(raise --vram-reserve-mib by ~200, or --pipeline-windows 0)\n", gs.dev, st + 1, err.c_str()); return 1; } if (last && !mtp_first && cudaMalloc((void**) &pl_mtp_R, (size_t) strata::kernels::kVerifyNarrowT * (size_t) (g.hc * g.n_embd) * sizeof(float)) != cudaSuccess) { std::fprintf(stderr, "strata serve: --pipeline-windows: the drafter's row buffer does not fit\n"); return 1; } } if (mtp_first) { // the drafter's row buffer on its own card (the first) const strata::core::OnDevice on_m(mtp.device()); if (cudaMalloc((void**) &pl_mtp_R, (size_t) strata::kernels::kVerifyNarrowT * (size_t) (g.hc * g.n_embd) * sizeof(float)) != cudaSuccess) { std::fprintf(stderr, "strata serve: --pipeline-windows: the drafter's row buffer does not fit\n"); return 1; } } if (!ver_b.init(wt, g, ss, vh, native_head.loaded() ? &native_head : nullptr, o.spec, err)) { std::fprintf(stderr, "strata serve: --pipeline-windows: the second verifier on CUDA0 (the first card): " "%s (raise --vram-reserve-mib by ~200, or --pipeline-windows 0)\n", err.c_str()); return 1; } // the setters reach the later stages; the pipeline never chains run/commit for (int st = 0; st + 1 < n_stages; ++st) stage_ver_p(st, 1).set_next(&stage_ver_p(st + 1, 1), &split_drive_b); } ver.set_remote_expert_opt(remote_opt.get()); { std::string le; if (!lat_tab.load(g, le)) { std::fprintf(stderr, "strata serve: %s\n", le.c_str()); return 1; } } if (pcie_balance() && n_stages == 1) ver.set_pcie_balance(&drive.d.pcie_model); if (batch_mtp) ver.set_batch_graph_limit(64); // --batch-mtp only: slot rotation makes many layouts (LRU); 0.1.39 keeps all #if defined(STRATA_HAVE_DFLASH2) if (use_df2) ver.set_taps(df2.tap_layers()); if (batch_df2) ver.set_batch_taps(true); #endif if (!ver.init(wt, g, ss, vh, native_head.loaded() || prefill_head_alias_bound ? &native_head : nullptr, batch_max_t(), err) || (use_mtp && !prefill_head_alias_bound && !mtp.bind(last_st && !mtp_first ? last_st->wt : wt, last_st ? &last_st->head : &native_head, pipe ? pl_mtp_R : ver.final_R_all(), err))) { std::fprintf(stderr, "strata serve: %s\n", err.c_str()); return 1; } if (prefill_head_alias_bound) mtp.set_window_R(ver.final_R_all()); #if defined(STRATA_HAVE_DFLASH2) #if defined(STRATA_HAVE_DFLASH2) // DFlash2 prompt taps on a layer split. Every stage's prompt path taps the requested layers it runs into its own staging and hands them to its // on_taps callback (on that stage's thread). The callback lands the rows in a landing [2048][taps][n_embd] on the drafter's card at their // position, and the drafter's context is updated for every position all stages have delivered (in position order, the solo path's per-chunk calls). struct Df2PromptLand { std::mutex mu; float* dev = nullptr; int dev_id = 0; int64_t first = 0, flushed = 0; std::vector reached; std::vector slot0, nt; std::vector cs; // per stage: its copies into the landing (on the stage's own card) ~Df2PromptLand() { if (dev != nullptr) { cudaSetDevice(dev_id); cudaFree(dev); } } } dland; auto df2_stage_prefill = [&](int k) -> strata::prefill::Prefill& { return k == 0 ? sp : stages[(size_t) k - 1]->sp; }; auto df2_stage_prompt_taps_reserve = [&](std::string& why) -> bool { const int64_t nl = g.n_layers; dland.nt.assign((size_t) n_stages, 0); dland.slot0.assign((size_t) n_stages, 0); dland.reached.assign((size_t) n_stages, 0); for (int k = 0; k < n_stages; ++k) { const int64_t lb = k == 0 ? 0 : split_at[(size_t) k - 1], le = k + 1 < n_stages ? split_at[(size_t) k] : nl; for (int l : df2.tap_layers()) { if (l < 0 || l >= nl - 1) continue; if (l < lb) ++dland.slot0[(size_t) k]; else if (l < le) ++dland.nt[(size_t) k]; } } const strata::core::OnDevice on_d(df2.device()); dland.dev_id = df2.device(); if (cudaMalloc((void**) &dland.dev, (size_t) 2048 * (size_t) df2.n_taps() * (size_t) g.n_embd * 4) != cudaSuccess) { (void) cudaGetLastError(); dland.dev = nullptr; why = "the prompt landing of the DFlash2 taps does not fit in VRAM"; return false; } dland.cs.assign((size_t) n_stages, nullptr); for (int k = 0; k < n_stages; ++k) { if (dland.nt[(size_t) k] == 0) continue; const strata::core::OnDevice on_s(k == 0 ? 0 : stages[(size_t) k - 1]->dev); if (cudaStreamCreateWithFlags(&dland.cs[(size_t) k], cudaStreamNonBlocking) != cudaSuccess) { why = "the prompt tap copy stream"; return false; } if (!df2_stage_prefill(k).reserve_taps(df2.tap_layers(), 2048, g.n_embd, why)) return false; } return true; }; auto df2_stage_prompt_taps_install = [&]() { for (int k = 0; k < n_stages; ++k) { if (dland.nt[(size_t) k] == 0) continue; df2_stage_prefill(k).on_taps = [&, k](const float* taps, int64_t rows, int64_t pos0, std::string& e) -> bool { std::lock_guard lk(dland.mu); const size_t ntot = (size_t) df2.n_taps(), N = (size_t) g.n_embd; const int64_t row = pos0 - dland.first; if (row < 0 || row + rows > 2048) { e = "DFlash2 prompt taps: rows outside the landing"; return false; } const size_t w = (size_t) dland.nt[(size_t) k] * N * 4; cudaError_t ce = cudaMemcpy2DAsync(dland.dev + ((size_t) row * ntot + (size_t) dland.slot0[(size_t) k]) * N, ntot * N * 4, taps, w, w, (size_t) rows, cudaMemcpyDefault, dland.cs[(size_t) k]); if (ce == cudaSuccess) ce = cudaStreamSynchronize(dland.cs[(size_t) k]); if (ce != cudaSuccess) { e = std::string("DFlash2 prompt taps: ") + cudaGetErrorString(ce); return false; } if (dland.flushed < 0) dland.flushed = pos0; // the first delivered row: a request that resumes reads from there on dland.reached[(size_t) k] = pos0 + rows; int64_t m = INT64_MAX; for (int j = 0; j < n_stages; ++j) if (dland.nt[(size_t) j] > 0) m = std::min(m, dland.reached[(size_t) j]); if (m > dland.flushed) { if (!df2.context(dland.dev + (size_t) (dland.flushed - dland.first) * ntot * N, m - dland.flushed, dland.flushed, e)) return false; dland.flushed = m; } return true; }; } }; // a request starts: the stages tap the last 2047 prompt rows (the solo path's window) and the landing starts over auto df2_stage_prompt_taps_begin = [&](int64_t first) { std::lock_guard lk(dland.mu); dland.first = first; dland.flushed = -1; for (auto& r : dland.reached) r = -1; for (int k = 0; k < n_stages; ++k) df2_stage_prefill(k).set_taps(df2.tap_layers(), first, 2048); }; #endif if (use_df2) { // DFlash2 in the serve loop: one card or a layer split (taps gathered onto the drafter's card), one request at a time std::string why_not; df2.set_max_drafts((o.mtp_max_t > 0 ? std::min(o.mtp_max_t, o.spec) : o.spec) - 1); // the widest window - 1: the head and the walk run for that many rows df2_offer_head(); // where the drafter's weights come from: the last stage's card by default (its head rows and embedding path), as the MTP's const bool df2_on_last = multi_gpu && last_st != nullptr && !df2_first; const bool df2_chain = n_stages > 1; // the taps come from several verifiers (gather_taps lands them on the drafter's card) if (df2.device() != 0 && strata::core::native_embed() != nullptr && strata::core::native_embed()->in_vram()) why_not = "the embedding table sits in CUDA0's VRAM (STRATA_EMBED_VRAM), out of reach of the drafter's card"; else if (!(df2_chain ? ver.tapping_chain() : ver.tapping())) why_not = "the verifier keeps no taps here"; else if (!df2.bind(df2_on_last ? last_st->wt : wt, multi_gpu ? &last_st->head : &native_head, df2_vocab_path(), why_not, df2_first ? last_st->dev : -1) || !df2.prepare(df2_chain ? df2.landing() : ver.tap_dev(), why_not) || !(multi_gpu ? df2_stage_prompt_taps_reserve(why_not) : sp.reserve_taps(df2.tap_layers(), 2048, g.n_embd, why_not))) { if (why_not.empty()) why_not = "the drafter could not be set up"; } if (!why_not.empty()) { std::fprintf(stderr, "strata serve: --draft dflash2: %s. It needs about 1.2 GiB of VRAM in all (the pack 0.76 GiB, buffers and K/V ring 0.25 GiB, " "a draft head 0.2 GiB, 0.1 GiB of prompt staging); --vram-reserve-mib 1900 keeps it. The MTP drafts instead.\n", why_not.c_str()); if (df2_solo) { // --draft-fallback none: there is no MTP to draft instead std::fprintf(stderr, "strata serve: --draft-fallback none: no MTP is loaded, so the start ends here\n"); return 1; } use_df2 = false; if (o.draft_mtp_spec_set && o.spec > o.draft_mtp_spec) o.spec = o.draft_mtp_spec; // the MTP drafts with its own window, not DFlash2's } else { if (multi_gpu) df2_stage_prompt_taps_install(); else sp.on_taps = [&](const float* taps, int64_t rows, int64_t pos0, std::string& e) -> bool { df2_tap_dump(taps, rows, pos0, (int64_t) df2.tap_layers().size() * g.n_embd); return df2.context(taps, rows, pos0, e); }; std::fprintf(stderr, "strata serve: DFlash2 drafter on (%s, graphs captured in %.0f ms); windows up to %d tokens; %s%s\n", o.draft_model.c_str(), df2.ms_capture, o.spec, df2_solo ? "no MTP layer is loaded (--draft-fallback none)" : "the MTP layer stays as the fallback", df2_chain ? (std::string("; layer split: the drafter is on CUDA") + std::to_string(df2.device()) + " (" + (df2_on_last ? "last" : "first") + " stage), the other stages' taps are gathered onto it").c_str() : ""); } } // the taps of the window just run (rows 0..rows-1), where the drafter reads them: the verifier's own buffer on one card; on a layer split every // stage's share landed on the drafter's card (Verifier::gather_taps; the drafter's stream waits on the copies) auto df2_win_taps = [&](int rows, std::string& e) -> const float* { if (n_stages <= 1) return ver.tap_dev(); if (!ver.gather_taps(df2.landing(), df2.device(), 0, rows, 0, df2.stream(), e)) return nullptr; return df2.landing(); }; if (batch_df2 && use_df2) { // the slot drafters bind to the solo drafter's head and embedding and capture their graphs on their own landing for (size_t b = 0; b < slot_df2.size(); ++b) { auto& d = *slot_df2[b]; if (!d.clone_bind(df2, err)) { std::fprintf(stderr, "strata serve: STRATA_BATCH_DF2: slot %zu: %s\n", b, err.c_str()); return 1; } d.set_max_drafts((o.mtp_max_t > 0 ? std::min(o.mtp_max_t, o.spec) : o.spec) - 1); if (!d.prepare(d.landing(), err)) { std::fprintf(stderr, "strata serve: STRATA_BATCH_DF2: slot %zu: %s\n", b, err.c_str()); return 1; } } std::fprintf(stderr, "strata serve: STRATA_BATCH_DF2: %zu slot drafters ready (batch windows carry each slot's token and its spare-row drafts)\n", slot_df2.size()); } else if (batch_df2) { // the solo drafter did not start (a fallback is loaded): the slots decode without drafts std::fprintf(stderr, "strata serve: STRATA_BATCH_DF2 is off: DFlash2 did not start\n"); batch_df2 = false; batch_mtp = false; } #endif const bool draft_on = use_mtp || use_df2; // some drafter proposes (--draft-fallback none: DFlash2 alone, use_mtp false) if (pipe) mtp.set_source_R(ver.final_R_all()); // the serial decode's rows (the last stage's even verifier) auto free_slot_mtp_rows = [](float* p) { if (p != nullptr) (void) cudaFree(p); }; std::vector> slot_mtp_rows; if (batch_mtp && !batch_df2) { // like the solo drafter's `bind` above: the last stage's weights (embedding) and head, and the residual // buffers on the drafter's device (the last stage's GPU with a layer split) const strata::core::OnDevice on_slot_mtp(mtp.device()); for (int b = 0; b < o.batch; ++b) { float* r = nullptr; const size_t bytes = (size_t) o.spec * (size_t) g.hc * (size_t) g.n_embd * sizeof(float); if (cudaMalloc((void**) &r, bytes) != cudaSuccess) { std::fprintf(stderr, "strata serve: batch MTP slot %d residual buffer does not fit%s\n", b, vram_free_note().c_str()); return 1; } slot_mtp_rows.emplace_back(r, free_slot_mtp_rows); if (!slot_mtp[(size_t) b]->bind(last_st && !mtp_first ? last_st->wt : wt, last_st ? &last_st->head : &native_head, r, err, &mtp) || (piped_mtp && !slot_mtp[(size_t) b]->prepare_chain(err))) { // STRATA_PIPED_MTP: the chain graphs std::fprintf(stderr, "strata serve: batch MTP slot %d: %s%s\n", b, err.c_str(), vram_free_note().c_str()); return 1; } } } // each stage's verifier gets its stage's slot sessions if (o.batch > 0) { for (size_t k = 0; k < bslot_ss.size(); ++k) { std::vector ptrs; for (auto& u : bslot_ss[k]) ptrs.push_back(u.get()); strata::core::Verifier& vk = k == 0 ? ver : stages[k - 1]->ver; const strata::core::OnDevice on_k(k == 0 ? 0 : stages[k - 1]->dev); if (!vk.init_slots(ptrs, err)) { std::fprintf(stderr, "strata serve: --batch, stage %zu: %s\n", k + 1, err.c_str()); return 1; } // STRATA_PIPED_MTP: the rows a group's commit replays after the verdict, one hand-off row each if (piped_mtp && bslot_ss.size() > 1 && !vk.init_deferred_commit(std::max(strata::kernels::kVerifyNarrowT, (1 + pm_drafts) * o.batch), err)) { std::fprintf(stderr, "strata serve: STRATA_PIPED_MTP, stage %zu: %s\n", k + 1, err.c_str()); return 1; } } } for (int st = 0; st < n_stages && n_stages > 1; ++st) { split_drive.plan[st] = stage_ver(st).plan_sink(); if (st > 0) { stage_ver(st).set_split(o.spec_split); stage_ver(st).set_pcie_mode(o.pcie_mode == "dma" ? 0 : o.pcie_mode == "direct" ? 1 : 2); } } if (pipe) { // the odd windows' pool routing: the same as the even ones', with their plans split_drive_b = split_drive; for (int st = 0; st < n_stages; ++st) { split_drive_b.plan[st] = stage_ver_p(st, 1).plan_sink(); stage_ver_p(st, 1).set_split(o.spec_split); stage_ver_p(st, 1).set_pcie_mode(o.pcie_mode == "dma" ? 0 : o.pcie_mode == "direct" ? 1 : 2); } } // the pool the verify windows call: with a layer split, the wrapper that routes each layer to its stage const strata::core::PoolMultiFn win_pool_fn = n_stages > 1 ? &drive_pool_split : &drive_pool_multi; const strata::core::PoolMultiFn invariant_win_pool_fn = n_stages > 1 ? &drive_pool_split_invariant : &drive_pool_multi_invariant; void* const win_pool_user = n_stages > 1 ? (void*) &split_drive : (void*) &drive; mem_mark("the verifier and the drafter's binding"); ver.set_split(o.spec_split); // auto: the copy kernel for every pack. DMA (the native packs' default until 0.1.13) has the host call // cudaMemcpyAsync + cudaLaunchHostFunc inside a verify window while the GPU spins on the flag they raise; // issue #31's thread dumps show the host stuck in that cudaMemcpyAsync on a driver lock for good. The copy // kernel needs no host CUDA call there, and costs ~1-3% decode on IQ3_S (45.3 -> 44.8 tok/s, 8 requests). ver.set_pcie_mode(o.pcie_mode == "dma" ? 0 : o.pcie_mode == "direct" ? 1 : 2); // --pipeline-windows 2: stage 0's GDN state before a speculative commit, restored when the guess was wrong. // Window W reads the state its snapshot must hold and no window writes it (only commits do), so it is copied // on a side stream while W runs, into the buffer of W's parity, and only W's speculative commit waits for it // (STRATA_PIPELINE_SNAP_OVERLAP=0: one buffer, copied on the critical path). // With three or more stages every front stage (all but the last) runs speculative windows, so each keeps its own // pair of snapshots, side stream and events. struct PlSnap { int dev = 0; size_t bytes = 0; void* state = nullptr; // the stage's GDN state (its session's) float* buf[2] = {nullptr, nullptr}; cudaStream_t side = nullptr; cudaEvent_t pre[2] = {nullptr, nullptr}, ev[2] = {nullptr, nullptr}; }; const int pl_nf = pipe ? n_stages - 1 : 0; // the front stages std::vector pl_snaps((size_t) pl_nf); bool pl_snap_ok = false, pl_snap_overlap = false; if (pipe && o.pipeline_windows >= 2) { pl_snap_ok = true; pl_snap_overlap = [] { const char* v = pipe_dbg_env("STRATA_PIPELINE_SNAP_OVERLAP"); return v == nullptr || std::atoi(v) != 0; }(); for (int st = 0; st < pl_nf && pl_snap_ok; ++st) { PlSnap& sn = pl_snaps[(size_t) st]; strata::core::SessionState& sst = st == 0 ? ss : stages[(size_t) st - 1]->ss; sn.dev = stage_ver_p(st, 0).device(); sn.bytes = gdn_snapshot_bytes(sst); sn.state = (void*) sst.gdn_state; const strata::core::OnDevice on(sn.dev); if (cudaMalloc((void**) &sn.buf[0], sn.bytes) != cudaSuccess) { std::fprintf(stderr, "strata serve: --pipeline-windows 2: the GDN snapshot of stage %d (%.1f MiB) does " "not fit; the decode stays serial\n", st + 1, (double) sn.bytes / 1048576.0); cudaGetLastError(); sn.buf[0] = nullptr; pl_snap_ok = false; break; } if (pl_snap_overlap) { bool ok_s = cudaMalloc((void**) &sn.buf[1], sn.bytes) == cudaSuccess && cudaStreamCreateWithFlags(&sn.side, cudaStreamNonBlocking) == cudaSuccess; for (int i = 0; i < 2 && ok_s; ++i) ok_s = cudaEventCreateWithFlags(&sn.pre[i], cudaEventDisableTiming) == cudaSuccess && cudaEventCreateWithFlags(&sn.ev[i], cudaEventDisableTiming) == cudaSuccess; if (!ok_s) { cudaGetLastError(); pl_snap_overlap = false; } } } } if (pipe) std::fprintf(stderr, "strata serve: --pipeline-windows %d: two verifiers per stage, %d stages overlap across " "windows%s\n", o.pipeline_windows, n_stages, !pl_snap_ok ? "" : pl_snap_overlap ? " (decode too; the GDN snapshots beside the window)" : " (decode too; the GDN snapshot on the critical path)"); // the verifiers by [stage][parity] - the first stage and the LAST (stage 1 of a two-stage split; the decode loop // reaches the middle stages through stage_ver_p) - their pool routing, and the drafter's events (in a pipelined // prompt read, a stage-1 window waits until the drafter has read the rows of the same parity's previous window) strata::core::Verifier* PV[2][2] = {{&ver, &ver_b}, {pipe ? &stages.back()->ver : nullptr, pipe ? &stages.back()->ver_b : nullptr}}; SplitDrive* PSD[2] = {&split_drive, &split_drive_b}; cudaEvent_t pl_mtp_ev[2] = {nullptr, nullptr}; bool pl_mtp_live[2] = {false, false}; bool pl_prepared = false; // every graph captured and the drafter's prompt path sized while nothing is in flight (a capture syncs its stream) auto pl_prepare = [&](std::string& e) -> bool { if (pl_prepared) return true; for (int st = 0; st < n_stages; ++st) for (int par = 0; par < 2; ++par) { strata::core::Verifier& v = stage_ver_p(st, par); const strata::core::OnDevice on(v.device()); if (!v.capture_all(e)) return false; } if (!mtp.prepare_prefill(e)) return false; if (o.pipeline_windows >= 2 && pl_snap_ok && !mtp.prepare_chain(e)) return false; const strata::core::OnDevice on(mtp.device()); for (cudaEvent_t& ev : pl_mtp_ev) if (ev == nullptr && cudaEventCreateWithFlags(&ev, cudaEventDisableTiming) != cudaSuccess) { e = "pipeline: event creation failed"; return false; } pl_prepared = true; return true; }; // INVARIANT: nothing pipelined is in flight outside read_windows_pl and the pipelined decode loop - both end // here (a checkpoint, a park, the next request and the serial paths all find both stages and the drafter idle). // Every window in flight is served to its end (its picks discarded), then both stages and the drafter idle. // (--adapt-async: the decode loop then settles the asynchronous tier's round, a_pl_settle, see its end.) auto pl_drain = [&]() { std::string e2; for (int round = 0; round < 10000000; ++round) { bool any = false; for (int st = 0; st < n_stages && pipe; ++st) for (int par = 0; par < 2; ++par) { strata::core::Verifier& v = stage_ver_p(st, par); if (!v.in_flight()) continue; any = true; if (v.service(&drive_pool_split, PSD[par], e2) < 0) return; if (v.done(e2)) v.pl_finish(nullptr, e2); else if (!e2.empty()) return; } if (!any) break; } for (int st = 0; st < n_stages && pipe; ++st) { const strata::core::OnDevice on(stage_ver_p(st, 0).device()); cudaStreamSynchronize(stage_ver_p(st, 0).stream()); } const strata::core::OnDevice on(mtp.device()); cudaStreamSynchronize(mtp.stream()); }; std::vector cur; // ---- the conversation cache (see ConvCheckpoint). `live` is what the session holds right now: the tokens // it has consumed, so a request that starts with exactly them continues without any copy. `checks` are the // saved points; every one of them is a prefix of `live` (the loop drops the rest), so they form a chain - // the radix cache's tree collapsed onto the one branch of history whose cells the session holds. The // chain's root is the deepest point every request so far shared (the end of the system prompt, in // practice); the retention policy pins it and rotates the rest LRU (conv_cache.hpp), so a NEW chat that // shares that prefix mounts through it instead of reading it again. std::vector live; std::vector live_imgs, req_imgs; bool live_ok = false; // SCR (STRATA_SCR=1, core/scr.hpp): after an edit in the middle of a prompt the cells of the text that survived // are moved instead of read. `live_pads`: where `live` holds the pad tokens a splice read (the server's prompt // has none, so the next request gets them back); `scr_master_ok`: the cell ranges whose K master is current. static const bool scr_on = [] { const char* e = std::getenv("STRATA_SCR"); return e != nullptr && e[0] == '1'; }(); static const int64_t scr_min_gain = [] { // a splice must save at least this many reads const char* e = std::getenv("STRATA_SCR_MIN_GAIN"); return e != nullptr ? (int64_t) std::max(0LL, std::atoll(e)) : (int64_t) 1024; }(); static const int64_t scr_pad = [] { // the pad token ("\n" in Qwen3.8's vocabulary) const char* e = std::getenv("STRATA_SCR_PAD"); return e != nullptr ? (int64_t) std::atoll(e) : (int64_t) 198; }(); std::vector live_pads; std::vector> scr_master_ok; struct ScrLayerMem { uint16_t* master = nullptr; uint8_t* valid = nullptr; }; std::map scr_mem; std::map> scr_scratch; // per device: the K/V move scratch, the pooled scratch constexpr int64_t kScrChunk = 2048, kScrPooledChunk = 512; // #879: a window met non-finite logits: the next request drops every cached state first and reads from token 0 bool nan_flush = false; // #3465: the non-finite logits came in a window that reads the PROMPT's tail (the last few tokens, read through // the verify windows after the batched part). The retry reads that tail batched (--short-read 0 for one request): // a reporter's prompts failed there every time and passed with --short-read 0. bool nf_prompt_windows = false, short_read_off_once = false; // --short-read's default (64) is a class default where the staged fused entry takes the pieces the windows would otherwise read (Prefill::short_read_default); the user's own value wins if (!o.short_read_set) o.short_read = strata::prefill::Prefill::short_read_default(o.short_read); std::vector checks; // KVA: which prefixes of token ids a KVA read approximated, so the draft layer knows, for whatever state a request // continues from, the first cell built from a real row (kva_floor.hpp). Empty without KVA. strata::prefill::KvaFloorRegistry kva_floors; // STRATA_CKPT_POOL: the dropped checkpoints' storage, reused. STRATA_SLOT_CKPT_MOVE turns it on too: a moved // checkpoint frees nothing at the next prune, so every save would fault in fresh pages (17 -> 40-60 ms) CheckpointPool ckpt_pool(ckpt_pool_env() || slot_ckpt_move_env(), ckpt_pool_cap_env()); uint64_t check_clock = 0; // the checkpoints' LRU clock; creation and every use advance it int64_t tail_ckpt_len = -1; // --prompt-cache-tail: the length of the one tail checkpoint alive (-1 = none) // --prefill-pipe: the plan of the prompt segment being read (read_part sets it around its runs), for the // checkpoints taken inside it ConvCheckpoint::PromptPlan seg_plan; bool cvec_cached = true; // the control vector's state the live session and the checkpoints were read with // without --mtp the conversation cache stays on: a parked image carries the draft layer's K/V only when there is one // (the snapshots accept a null draft) // #3493: no --conversation-cache-mib given: size the cache for agent use from the RAM that is free now that the model is // loaded (an agent Harness alternates a long main conversation with shorter ones; with the cache off every request read // its whole prompt again, Reused 0 on 12 of 12). An explicit value, 0 included, is never touched. if (o.conversation_cache_mib < 0) { if (o.serve && o.prompt_cache > 0 && o.conversation_cache_slots > 0) { auto cache_room = strata::core::available_host_bytes(); // #4518: the residency policy locked the PLE table before it knew what the rest of the load would take; if the lock is what // leaves the automatic cache too little (or none), the lock is given back (the pages stay cached, the OS may reclaim them) // and the cache is sized again. --ple-io ram asked for by hand and --conversation-cache-mib N are never touched. if (ple_lock_by_policy && ple_table.locked() && strata::core::ple_lock_blocks_cache(cache_room, ple_table.table_bytes(), o.conversation_cache_min_free_mib)) { const auto before = cache_room; if (ple_table.unlock()) { strata::core::set_locked_own_file_bytes(0); cache_room = strata::core::available_host_bytes(); std::fprintf(stderr, "strata serve: PLE table lock given back: the lock left %.1f GiB of RAM for the conversation cache, " "%.1f GiB without it (the table stays cached; --conversation-cache-mib N and --ple-io ram are kept as asked)\n", before ? (double) *before / (1ull << 30) : 0.0, cache_room ? (double) *cache_room / (1ull << 30) : 0.0); } } o.conversation_cache_mib = strata::core::auto_conversation_cache_mib(cache_room, o.conversation_cache_min_free_mib); if (o.conversation_cache_mib > 0) std::fprintf(stderr, "strata serve: conversation cache sized from the free RAM: %lld MiB for up to %d parked " "conversations, so an agent's next turn reuses its prompt (--conversation-cache-mib N sets it, 0 turns it off)\n", (long long) o.conversation_cache_mib, o.conversation_cache_slots); else std::fprintf(stderr, "strata serve: conversation cache off: not enough free RAM to park conversations " "(--conversation-cache-mib N asks for one anyway)\n"); } else { o.conversation_cache_mib = 0; } } strata::core::ConversationCache conversations( o.prompt_cache > 0 ? (size_t) o.conversation_cache_mib * 1024 * 1024 : 0, (size_t) o.conversation_cache_slots, o.conversation_cache_min_tokens); // The park pools (park_pool_policy.hpp): memory held idle between parks so a park does not pay the first touch of fresh pages. // * the segment pool: one arena for the K/V buffers of parked conversations (STRATA_PARK_SEGPOOL_MIB=N sets its size, 0 turns it // off; unset: min(2 GiB, a quarter of the cache); Linux only, the OS layer of Windows and macOS is not written yet: inert there); // * the checkpoint pool with ready checkpoints (STRATA_CKPT_POOL=0 turns it off; STRATA_CKPT_POOL_READY=N sets the count; unset: // as many as fit in a twelfth of the cache, at most 4; a single-stage serve only, not in the Metal build). // Both count against the cache's budget (ConversationCache::set_pool) and are given back before any parked conversation is evicted // and before the RAM floor is reached; their top-up runs in the background and only while the budget and the RAM floor plus 1 GiB // leave room. The arena is never destroyed (a buffer made from it may outlive this scope's objects). strata::core::SegmentPool* segpool = nullptr; std::atomic segpool_allow{0}; // bytes the filler may still make resident in this pass (set on the host thread) std::unique_ptr segpool_filler; // (after the allowance: it is joined first) ParkPoolsBudget pools_budget(nullptr, &ckpt_pool); // (the arena joins below) const size_t cache_mib_now = conversations.enabled() ? (size_t) o.conversation_cache_mib : 0; size_t park_ckpt_bytes = 0; // one ready checkpoint (what pool_topup allocates) { const ConvStateSizes z = conv_state_sizes(g, ss); if (z.gdn > 0) { const uint64_t layers = (uint64_t) std::max(ss.qsa_alloc, 0); park_ckpt_bytes = (size_t) (z.gdn + (ss.ple_hist != nullptr ? z.ple : 0) + layers * ((uint64_t) z.tail + z.dead + z.block_pos)); } } const strata::core::ParkPoolPlan park_plan = strata::core::park_pool_plan(cache_mib_now, park_ckpt_bytes); // the checkpoint pool: on by default in a single-stage serve with a cache (STRATA_CKPT_POOL=0 turns it off), as before when asked for // or when STRATA_SLOT_CKPT_MOVE needs it; the count of ready checkpoints is the plan's unless STRATA_CKPT_POOL_READY says #if defined(STRATA_GPU_METAL) constexpr bool ckpt_default_build = false; // (the Mac engine keeps its own behaviour: not gated there, so not changed by the default) #else constexpr bool ckpt_default_build = true; #endif const bool ckpt_default_on = ckpt_default_build && ckpt_pool_env_state() == -1 && cache_mib_now > 0 && stages.empty() && park_ckpt_bytes > 0; if (ckpt_default_on) ckpt_pool_ready_default().store(park_plan.ckpt_ready); ckpt_pool.configure(ckpt_pool_env() || slot_ckpt_move_env() || ckpt_default_on, ckpt_pool_cap_env()); auto segpool_kick = [&] { if (segpool == nullptr || !segpool_filler) return; const size_t budget = o.prompt_cache > 0 ? (size_t) o.conversation_cache_mib * 1024 * 1024 : 0; const size_t used = conversations.resident_bytes(); segpool_allow.store(budget > used ? budget - used : 0); segpool_filler->kick(); }; { const long long env_mib = park_segpool_env_mib(); // -1 unset const size_t want_mib = env_mib >= 0 ? (size_t) env_mib : park_plan.segpool_mib; if (want_mib > 0 && conversations.enabled()) { const size_t budget = (size_t) o.conversation_cache_mib * 1024 * 1024; const size_t bytes = std::min(want_mib * 1024 * 1024, budget / 4); // never more than a quarter of the cache segpool = new strata::core::SegmentPool(strata::core::segment_pool_os(), bytes); if (segpool->active() && strata::core::segment_pool_install(segpool)) { pools_budget = ParkPoolsBudget(segpool, &ckpt_pool); const uint64_t floor = (uint64_t) o.conversation_cache_min_free_mib * 1024 * 1024; segpool_filler = std::make_unique(*segpool, [&segpool_allow, floor](size_t step) -> size_t { // upkeep only while the engine is idle (park_pool_policy.hpp): no page population beside a request's GPU work const size_t a = strata::core::park_pool_permit(strata::core::progress().busy.load(), std::min(step, segpool_allow.load())); if (a == 0) return 0; const auto mem = strata::core::sample_host_memory(); // the floor and one more GiB of RAM must stay free if (!mem || mem->available < floor + ((uint64_t) 1 << 30) + a) return 0; segpool_allow.fetch_sub(std::min(a, segpool_allow.load())); return a; }, [] { StageThreads::spread_current_thread(); }); if (std::getenv("STRATA_PARK_TRACE")) std::fprintf(stderr, "strata parktrace: segpool %zu MiB reserved (%s %zu MiB, cache %lld MiB)\n", segpool->capacity() >> 20, env_mib >= 0 ? "asked" : "default", want_mib, (long long) o.conversation_cache_mib); } else { if (std::getenv("STRATA_PARK_TRACE")) std::fprintf(stderr, "strata parktrace: segpool not reserved (%zu MiB wanted)\n", want_mib); segpool = nullptr; // (the object stays allocated, inert) } } } if (conversations.enabled() && (segpool != nullptr || ckpt_pool.on())) conversations.set_pool(&pools_budget); if (std::getenv("STRATA_PARK_TRACE")) std::fprintf(stderr, "strata parktrace: park pools: segment pool %zu MiB, checkpoint pool %s (ready %zu, cap %zu, %zu MiB each), cache %zu MiB, stages %zu\n", segpool != nullptr ? segpool->capacity() >> 20 : (size_t) 0, ckpt_pool.on() ? "on" : "off", ckpt_pool_ready_env(), ckpt_pool.cap(), park_ckpt_bytes >> 20, cache_mib_now, stages.size()); segpool_kick(); // Disk sessions: what a session file is bound to. The model fingerprint samples every model input this // engine loaded, by role (conversation_file.hpp), once; the config fingerprint covers the RESOLVED settings // that change what the saved bytes mean - the rope (K is cached post-RoPE), the loaded control vector, the // K/V format and the arithmetic switches. Sampling, seeds, draft tuning and the expert tier are not in it. std::optional model_fp, config_fp; auto session_identity = [&](strata::core::SessionFileIdentity& id, std::string& e, const std::function& next_file) -> bool { if (!model_fp) { // what the loaders actually resolved: the CLI inputs, the pack's files and - from the expert source // itself - every file its experts were read from (native_experts.txt can name GGUFs per layer/role) strata::core::SessionInputs in; in.native_shards = o.native_shards; in.native_dense = o.native_dense_gguf; in.native_head = o.native_head_shards; in.embedding = o.embd_gguf; in.ple = o.ple_gguf; in.pack = o.pack; in.mtp = o.mtp.empty() ? std::string() : o.mtp + "/dense.bin"; if (srcp != nullptr) in.experts = srcp->model_inputs(); std::vector files = strata::core::session_model_inputs(in); // the pack's other files the loader reads (weights.cpp, expert_layout.cpp) if (!o.pack.empty()) { for (const char* n : {"index.txt", "dense.bin"}) files.push_back({std::string("pack ") + n, o.pack + "/" + n}); for (const char* n : {"embd.bin", "extra.bin", "manifest.json"}) files.push_back({std::string("pack ") + n, o.pack + "/" + n, true}); if (srcp == nullptr) files.push_back({"pack experts.bin", o.pack + "/experts.bin", true}); } if (!o.mtp.empty()) { for (const char* n : {"dense.txt", "experts.bin"}) files.push_back({std::string("mtp ") + n, o.mtp + "/" + n}); files.push_back({"mtp draft_vocab.bin", o.mtp + "/draft_vocab.bin", true}); } uint64_t fp = 0; // each file is one blocking read of at most 2 MiB (head and tail): announced before it starts if (next_file) next_file(); if (!strata::core::session_model_fingerprint(files, fp, e, next_file)) return false; model_fp = fp; } if (!config_fp) { strata::core::SessionConfig c; c.engine_version = STRATA_VERSION; #if defined(STRATA_USE_HIP) c.backend = "hip"; #else c.backend = "cuda"; #endif c.kv = o.kv; c.max_context = o.max_context; c.kv_resident = o.kv_resident; c.mtp_window = o.mtp.empty() ? -1 : o.mtp_window; const char* rot = std::getenv("STRATA_KV_ROT"); c.kv_rot = rot != nullptr && rot[0] == '1'; c.rope = {(int64_t) rope_cfg.type, rope_cfg.freq_base, rope_cfg.factor, rope_cfg.freq_scale(), rope_cfg.orig_ctx, rope_cfg.ext_factor, rope_cfg.attn_factor, rope_cfg.beta_fast, rope_cfg.beta_slow}; c.cvec = cvec_digest; c.switches = { {"no_ple", o.no_ple}, {"native_bf16", o.native_bf16}, {"native_bf16_extra", o.native_bf16_extra}, {"native_ple_key", o.native_ple_key}, {"native_moe_combine", o.native_moe_combine}, {"native_gdn", o.native_gdn}, {"native_flash_attn_short", o.native_flash_attn_short}, {"native_qsa_indexer", o.native_qsa_indexer}, {"native_qsa", o.native_qsa}, {"native_rope", o.native_rope}, {"native_ple_postops", o.native_ple_postops}, {"native_router", o.native_router}, {"cpu_oracle_q8_0", o.cpu_oracle_q8_0}, {"gr_fp32_activations", o.gr_fp32_activations}, {"gr_native_mmvf", o.gr_native_mmvf}, {"native_preset", !o.native_preset.empty()}, {"shared_late", o.shared_late}, {"keep_canonical", o.keep_canonical}, {"no_fused_gr", o.no_fused_gr}, {"no_fast_attn", o.no_fast_attn}, {"no_fused_gdn", o.no_fused_gdn}, {"no_fast_select", o.no_fast_select}, {"vision", o.vision}}; config_fp = strata::core::session_config_fingerprint(c); } id.model = *model_fp; id.config = *config_fp; return true; }; // What a park captures: the main session's conversation (park_current) or an idle batch slot's (park_slot: // the reply it decoded, before an admission overwrites it). One budget / admission / snapshot path for both. struct ParkSource { const std::vector& ids; const std::vector& imgs; std::vector& checks; ///< moved apart into stage parts for the capture, put back after bool cvec; strata::core::SessionState& session; ///< stage 0's std::vector stage_sessions; ///< the later stages', in stage order (stages[k]->dev) const strata::core::QsaState* draft0; ///< the draft layer's K/V saved with stage 0's image (or none) const strata::core::QsaState* draft_last; ///< ... with the last stage's image (a split: the drafter's GPU) bool with_reuse; ///< the retained K/V describes this source (the main session's) std::string what; ///< the log's words after the token count ("", " from slot 1") }; // The NVMe tier: what the RAM tier evicts is written here, and what a request continues is read back. Its // reads have the bounds and the RAM floor a RESTORE has. strata::core::ConversationDisk conv_disk(o.prompt_cache > 0 && conversations.enabled() ? o.conversation_disk : "", (uint64_t) o.conversation_disk_gib << 30); auto conv_disk_limits = [&](strata::core::SessionReadLimits& limits, std::string& e) -> bool { const uint64_t floor = (uint64_t) o.conversation_cache_min_free_mib << 20; limits.admit = [floor](uint64_t need, std::string& why) { const auto mem = strata::core::sample_host_memory(); if (strata::core::conversation_memory_admit(mem ? std::optional(mem->available) : std::nullopt, need, floor)) return true; why = "not enough RAM to read it (" + std::to_string(need >> 20) + " MiB plus the floor)"; return false; }; if (!strata::core::conversation_session_read_limits(limits, ss, g, mtp.kv_state(), (uint64_t) o.max_context, (uint64_t) std::max(o.prompt_cache, 1), e)) return false; for (const auto& st_k : stages) { strata::core::SessionReadLimits lk; if (!strata::core::conversation_session_read_limits(lk, st_k->ss, g, mtp.kv_state(), (uint64_t) o.max_context, (uint64_t) std::max(o.prompt_cache, 1), e)) return false; limits.stage_limits.push_back(std::move(lk)); } return true; }; if (conv_disk.enabled()) { const size_t found = conv_disk.load(); std::fprintf(stderr, "strata serve: conversation disk: %s, %lld GiB; %zu parked conversation%s from before " "(%.1f GiB)\n", o.conversation_disk.c_str(), (long long) o.conversation_disk_gib, found, found == 1 ? "" : "s", conv_disk.bytes() / 1073741824.0); conversations.set_spill([&](const strata::core::SavedConversation& image) { const auto t0 = Clock::now(); strata::core::SessionFileIdentity id; std::string e; strata::core::SessionWriteOptions wo; wo.min_free_bytes = (uint64_t) o.session_min_free_mib << 20; wo.durable = false; // a cache: a copy lost to a crash is read again from the prompt if (session_identity(id, e, {}) && conv_disk.put(image, id, e, wo)) std::fprintf(stderr, "strata serve: conversation disk: wrote %zu tokens in %.0f ms; on disk %zu (%.1f GiB)\n", image.live.ids.size(), std::chrono::duration(Clock::now() - t0).count(), conv_disk.size(), conv_disk.bytes() / 1073741824.0); else std::fprintf(stderr, "strata serve: conversation disk: not written (%s)\n", e.c_str()); }); } // Save only on a switch/rewind, not on each continuing request. No graph // addresses change: all parked images live in ordinary host vectors. // STRATA_PARK_ASYNC: set by the request around its park - the live checkpoints it drops right after (they move // into the parked image instead of being copied); a background allocation then refills STRATA_CKPT_POOL std::function park_drops; std::future pool_refill; // STRATA_CKPT_POOL_READY=N (with STRATA_CKPT_POOL): the pool holds N checkpoints whose vectors already have the // session's sizes (the ones conversation_checkpoint_save resizes to, so a pooled one is never resized) with their // pages in: a fresh 118 MB vector costs ~40 ms of page faults at a save. Topped up on a background thread, off the // host's core, whenever a take leaves it short; one top-up at a time. Allocation only: a save overwrites every byte. // Not with a layer split (its checkpoints carry stage parts; saved as before). Unset: no ready checkpoints, nothing // allocated ahead of time. // Upkeep only while the engine is idle (park_pool_policy.hpp): while a request is in flight (progress().busy) this returns and a // take that finds the pool short gets fresh vectors; the serve loop calls it again between requests. Counters for the // request log line: checkpoints taken ready from the pool and allocated fresh. size_t ck_from_pool = 0, ck_fresh = 0; auto pool_topup = [&] { if (strata::core::park_pool_permit(strata::core::progress().busy.load(), 1) == 0) return; if (ckpt_pool_ready_env() == 0 || !ckpt_pool.on() || !stages.empty()) return; const ConvStateSizes pool_z = conv_state_sizes(g, ss); if (pool_z.gdn == 0) return; if (pool_refill.valid() && pool_refill.wait_for(std::chrono::seconds(0)) != std::future_status::ready) return; const size_t have = ckpt_pool.held(); if (have >= ckpt_pool_ready_env()) return; size_t topup = ckpt_pool_ready_env() - have; // the top-up stays inside the cache's budget and the RAM floor (plus 1 GiB): a checkpoint more than either leaves room for is not made if (park_ckpt_bytes > 0) { if (conversations.enabled()) { const size_t budget = (size_t) o.conversation_cache_mib * 1024 * 1024, used = conversations.resident_bytes(); topup = std::min(topup, budget > used ? (budget - used) / park_ckpt_bytes : (size_t) 0); } const auto mem = strata::core::sample_host_memory(); const uint64_t keep = ((uint64_t) o.conversation_cache_min_free_mib << 20) + ((uint64_t) 1 << 30); if (mem) topup = std::min(topup, mem->available > keep ? (size_t) ((mem->available - keep) / park_ckpt_bytes) : 0); else if (ckpt_pool_env_state() != 1) topup = 0; // (telemetry unknown: only when asked for by hand) } if (topup == 0) return; pool_refill = std::async(std::launch::async, [&ckpt_pool, want = topup, z = pool_z, layers = (size_t) std::max(ss.qsa_alloc, 0), ple = ss.ple_hist != nullptr] { StageThreads::spread_current_thread(); // (a thread the host starts inherits its one CPU: aux_cpus.hpp) for (size_t k = 0; k < want; ++k) { if (strata::core::park_pool_permit(strata::core::progress().busy.load(), 1) == 0) break; // a request began: stop after the one made ConvCheckpoint c; c.gdn.resize(z.gdn); c.ple.resize(ple ? z.ple : 0); c.tails.resize(layers * z.tail); c.dead.resize(layers * z.dead); c.block_pos.resize(layers * z.block_pos); ckpt_pool.give(std::move(c)); } }); }; pool_topup(); // the first request's checkpoints find the pool full auto park_source = [&](const ParkSource& src, size_t held) -> bool { // #2049: parking copies the outgoing conversation's running checkpoints and K/V into host memory, which // is a silent stretch of the "request" stage; when the OS has paged that memory out it takes minutes. // Named, so a stall report says "parking"; its copies beat (conversation_copy.hpp), so the watchdog // sees a park that moves and ends one that does not. struct ParkStage { ParkStage() { strata::core::progress_at("request: parking the previous conversation"); } ~ParkStage() { strata::core::progress_at("request"); strata::core::progress_beat(); } } park_stage; // --conversation-cache-min-tokens: a short conversation is not worth one of the slots. Parking is a // switch-time decision, so a client's small side requests would otherwise park themselves and, once the // cache is full, evict the long conversation they were interleaved with (oldest first) - the reuse it // wanted. Returning true is the same non-error skip the byte-budget and RAM-floor paths below take. if (!conversations.wants((int64_t) src.ids.size())) { std::fprintf(stderr, "strata serve: conversation cache: skip parking (%zu tokens, below the %lld " "minimum; parked=%zu)\n", src.ids.size(), (long long) o.conversation_cache_min_tokens, conversations.size()); return true; } // With a park pool, no pool memory is given back (shrink, eviction) while device work could still be pending: the GPU is // idle at a park, so this costs nothing if (segpool != nullptr || ckpt_pool.on()) (void) cudaDeviceSynchronize(); // #342: before make_room evicts oldest-first, the copies of this conversation a turn back go (they hold // nothing the outgoing chain does not, apart from the tail this conversation rewrote) if (const size_t dropped = conversations.drop_superseded(src.ids, src.imgs, src.checks, src.cvec)) std::fprintf(stderr, "strata serve: conversation cache: dropped %zu superseded cop%s of this " "conversation; parked=%zu\n", dropped, dropped == 1 ? "y" : "ies", conversations.size()); // A layer split parks one image per stage: the first stage's (with the draft layer's K/V) and one per // later stage (without it - the draft ring is saved once). The checkpoints are MOVED apart into their // stage parts for the capture and put back together whichever way this ends (no running state copied). const size_t n_st = stages.size(); // the draft layer's K/V lives on the last stage's GPU (the drafter is loaded there): with a split it is // saved with that stage's image, under its device; stage 0's image holds none const strata::core::QsaState* draft0 = src.draft0; // no --mtp: no draft K/V (snapshots accept null) auto draft_of = [&](size_t k) -> const strata::core::QsaState* { return k + 1 == n_st ? src.draft_last : nullptr; }; std::vector& checks = src.checks; strata::core::ConversationCheckpointSplit cs; if (n_st > 0) cs = strata::core::conversation_checkpoints_split(std::move(checks), n_st); // #752: two-phase; a bad_alloc leaves `checks` whole struct MergeBack { strata::core::ConversationCheckpointSplit& cs; std::vector& checks; bool on; ~MergeBack() { if (on && !strata::core::conversation_checkpoints_merge(std::move(cs), checks)) checks.clear(); } } merge_back{cs, checks, n_st > 0}; const strata::core::ConversationView view{src.ids, src.imgs, n_st > 0 ? cs.stage0 : checks, src.cvec}; const int64_t retained_n = src.with_reuse ? conversations.retained_tokens() : 0; // a batch slot's image carries no retained K/V (it describes the main session's conversation), and the // main session's stays retained for its own park auto reuse = src.with_reuse ? conversations.take_reuse_for(src.ids) // never another conversation's K/V : strata::core::ConversationKvReuse{}; if (retained_n > 0 && reuse.unchanged_tokens < retained_n) std::fprintf(stderr, "strata serve: conversation cache: retained K/V reused for %lld of its %lld tokens " "(the rest is not this conversation's)\n", (long long) reuse.unchanged_tokens, (long long) retained_n); std::vector stage_reuse = std::move(reuse.stages); stage_reuse.resize(n_st); reuse.stages.clear(); // the later stages' estimates, each with its own retained K/V when it still fits size_t stage_estimate = 0, stage_retained = 0; for (size_t k = 0; k < n_st; ++k) { auto& st = stages[k]; const strata::core::OnDevice on(st->dev); const strata::core::ConversationView view_k{src.ids, src.imgs, cs.parts[k], src.cvec}; size_t b = 0; if (!strata::core::conversation_snapshot_bytes(view_k, *src.stage_sessions[k], g, draft_of(k), b, err)) { std::fprintf(stderr, "strata serve: conversation cache: skip parking (stage CUDA%d: %s)\n", st->dev, err.c_str()); err.clear(); return true; } if (!stage_reuse[k].kv.empty()) { size_t r = 0; if (strata::core::conversation_snapshot_capture_bytes(stage_reuse[k], view_k, *src.stage_sessions[k], g, draft_of(k), r, err)) { b = r; stage_retained += stage_reuse[k].bytes(); } else { stage_reuse[k] = {}; err.clear(); } } stage_estimate += b; } size_t estimate = 0; if (!strata::core::conversation_snapshot_bytes(view, src.session, g, draft0, estimate, err)) { std::fprintf(stderr, "strata serve: conversation cache: skip parking (%s)\n", err.c_str()); err.clear(); // A recoverable miss must not poison the batched draft prefill's error channel. return true; } const size_t fresh_estimate = estimate; if (!reuse.kv.empty() && !strata::core::conversation_snapshot_capture_bytes( reuse, view, src.session, g, draft0, estimate, err)) { reuse = {}; estimate = fresh_estimate; err.clear(); } estimate += stage_estimate; // A park carrying its own retained K/V replaces memory the cache // already held, so capacity is make_room's call - it runs next either // way, and put()'s accounting still bounds the budget. The with-reuse // estimate must stay uncapped: it counts the retained buffers' // capacity and directories, and put() charges that same true size - // a capped figure would under-evict and overfill the budget. if (!conversations.make_room(estimate, held)) { std::fprintf(stderr, "strata serve: conversation cache: skip parking (snapshot %zu MiB exceeds available budget)\n", estimate >> 20); return true; } const auto t0 = Clock::now(); try { const uint64_t floor = (uint64_t) o.conversation_cache_min_free_mib * 1024 * 1024; const size_t retained = reuse.bytes() + stage_retained; const size_t additional = estimate > retained ? estimate - retained : 0; // The physical-RAM gate: the incoming snapshot has to fit beside the floor. make_room() // above only balanced the cache's own budget, so a full cache leaves this one short even // though every parked conversation could give its RAM back - and refusing here throws // away the whole prompt read that produced this snapshot (measured: 270k tokens, 96 s). // Evict the least recently active parked conversations until it fits, or until none are // left. #5697: freed memory can stay in the C library's heap, which MemAvailable does not // count (make_room's evictions above, dropped checkpoints): a failed check hands it back first // (release_free_heap), and evict_oldest() hands back each entry it drops, so the next check // reads it from /proc/meminfo. slots() bounds the loop, and the two lines // below say what it did either way. The reading is the guard's (MemAvailable, the cgroup // limits above the engine, --memory-limit-mib); `mem` keeps the last one for the refusal line. size_t evicted = 0; std::optional mem; auto admit = [&] { mem = strata::core::sample_host_memory(); return strata::core::conversation_memory_admit( mem ? std::optional(mem->available) : std::nullopt, additional, floor); }; // STRATA_PARK_SEGPOOL_MIB: the pool's idle bytes are the first RAM to go back (before the heap and before any // parked conversation), so the pool never makes this check fail where it would pass without it bool fits = admit(); if (!fits && pools_budget.idle_bytes() > 0) { pools_budget.shrink((size_t) -1); fits = admit(); } fits = fits || (strata::core::release_free_heap() && admit()); while (!fits && conversations.size() > 0 && evicted < conversations.slots() && conversations.evict_oldest()) { ++evicted; fits = admit(); } if (!fits) { std::fprintf(stderr, "strata serve: conversation cache: skip parking (physical RAM admission; need %zu MiB plus %lld MiB floor, %s; evicted %zu, %zu still parked)\n", additional >> 20, (long long) o.conversation_cache_min_free_mib, ram_note(mem).c_str(), evicted, conversations.size()); return true; } if (evicted) std::fprintf(stderr, "strata serve: conversation cache: evicted %zu parked conversation%s to admit this snapshot (%zu MiB plus %lld MiB floor)\n", evicted, evicted == 1 ? "" : "s", additional >> 20, (long long) o.conversation_cache_min_free_mib); strata::core::SavedConversation image; size_t reused_bytes = 0; // STRATA_CKPT_POOL: the running state and the checkpoint copies go into dropped checkpoints' vectors // (the ones this request drops refill the pool right after); what is left goes back std::vector storage; if (ckpt_pool.on() && n_st == 0) for (size_t k = 0; k <= view.checkpoints.size(); ++k) { ConvCheckpoint c = ckpt_pool.take(); if (c.gdn.empty()) break; ++ck_from_pool; storage.push_back(std::move(c)); } std::vector moved; // STRATA_PARK_ASYNC: the ones this request drops (view: the rest) if (park_drops && n_st == 0 && src.with_reuse) { // (the main session's checkpoints only, not an idle slot's) size_t w = 0; for (size_t i = 0; i < checks.size(); ++i) { if (park_drops(static_cast(checks[i]))) { moved.push_back(std::move(checks[i])); continue; } if (w != i) checks[w] = std::move(checks[i]); ++w; } checks.erase(checks.begin() + (std::ptrdiff_t) w, checks.end()); } const bool saved = strata::core::conversation_snapshot_save(image, view, src.session, g, draft0, err, std::move(reuse), &reused_bytes, storage.empty() ? nullptr : &storage, moved.empty() ? nullptr : &moved); for (ConvCheckpoint& c : storage) ckpt_pool.give(std::move(c)); if (!saved) return false; pool_topup(); // what the park took (and what moved out) is allocated again, in the background for (size_t k = 0; k < n_st; ++k) { // the later stages (the last one with the draft layer's K/V) auto& st = stages[k]; const strata::core::OnDevice on(st->dev); if (cudaDeviceSynchronize() != cudaSuccess) { err = "stage sync failed"; return false; } const strata::core::ConversationView view_k{src.ids, src.imgs, cs.parts[k], src.cvec}; strata::core::SavedConversation part; if (!strata::core::conversation_snapshot_save(part, view_k, *src.stage_sessions[k], g, draft_of(k), err, std::move(stage_reuse[k]), &reused_bytes)) return false; image.stage_images.push_back(std::move(part)); } auto mem_after = strata::core::sample_host_memory(); // (the park pools' idle memory is the first RAM to go back here too: a park the check refuses with the pools held would pass without them) if (!strata::core::conversation_memory_admit( mem_after ? std::optional(mem_after->available) : std::nullopt, 0, floor) && pools_budget.idle_bytes() > 0) { pools_budget.shrink((size_t) -1); mem_after = strata::core::sample_host_memory(); } if (!strata::core::conversation_memory_admit( mem_after ? std::optional(mem_after->available) : std::nullopt, 0, floor)) { std::fprintf(stderr, "strata serve: conversation cache: skip parking (RAM floor after capture: %lld MiB needed, %s)\n", (long long) o.conversation_cache_min_free_mib, ram_note(mem_after).c_str()); return true; } const size_t snapshot_bytes = image.bytes(); const bool stored = conversations.put(std::move(image), held); std::fprintf(stderr, "strata serve: conversation cache: %s %zu tokens%s in %.1f ms; parked=%zu bytes=%zu evictions=%zu snapshot_bytes=%zu reused_kv_bytes=%zu\n", stored ? "parked" : "skipped", src.ids.size(), src.what.c_str(), std::chrono::duration(Clock::now() - t0).count(), conversations.size(), conversations.bytes(), conversations.evictions(), snapshot_bytes, reused_bytes); if (segpool != nullptr) { segpool_kick(); // what this park freed or the pool gave back is topped up again in the background if (std::getenv("STRATA_PARK_TRACE")) std::fprintf(stderr, "strata parktrace: segpool resident %zu MiB, live %zu MiB, idle %zu MiB, hits %llu, misses %llu; cache images %zu MiB\n", segpool->resident_bytes() >> 20, segpool->live_requested() >> 20, segpool->idle_bytes() >> 20, (unsigned long long) segpool->hits(), (unsigned long long) segpool->misses(), conversations.bytes() >> 20); } } catch (const std::bad_alloc&) { // The active state has not been touched. Continue with normal // prompt processing rather than killing a serving process. std::fprintf(stderr, "strata serve: conversation cache: allocation failed; skip parking\n"); } return true; }; auto park_current_body = [&](size_t held) -> bool { if (!conversations.enabled() || !live_ok || live.empty()) return true; const size_t n_st = stages.size(); ParkSource src{live, live_imgs, checks, cvec_cached, ss, {}, (n_st > 0 && !mtp_first) || !use_mtp ? nullptr : &mtp.kv_state(), use_mtp && !mtp_first && n_st > 0 ? &mtp.kv_state() : nullptr, true, ""}; for (auto& st : stages) src.stage_sessions.push_back(&st->ss); return park_source(src, held); }; // #752: the whole park (the checkpoint split included) is under one try, so a host OOM skips parking instead of // ending the server auto park_current = [&](size_t held) -> bool { try { return park_current_body(held); } catch (const std::bad_alloc&) { std::fprintf(stderr, "strata serve: conversation cache: allocation failed; skip parking\n"); return true; } }; int64_t pp_total = 0, pp_from = 0, pp_next_check = 0; bool pp_tail_saved = false; // #471: the position the prompt pass has read up to (a chunk's or a window's end): what a request cancelled // mid-read reports as read, instead of the whole prompt int64_t pp_reached = 0; // #1620: the session holds exactly the tokens [0, pp_reached) of the prompt (no chunk or window is in flight, none // failed): a request cancelled here keeps them as the live conversation instead of dropping what it restored bool pp_exact = false; Clock::time_point pp_t0 = Clock::now(); // #879: this request met a window whose head logits were not all finite (nonfinite_hit): it ends with // DONE ... nonfinite, emitting none of that window's tokens bool nf_hit = false; auto nonfinite_hit = [&](const strata::core::Verifier& v, const char* what) -> bool { const int row = v.nonfinite_row(); if (row < 0) return false; std::fprintf(stderr, "strata serve: non-finite logits (#879) in a %s window at position %lld (row %d): its " "tokens are not emitted, the request ends (DONE nonfinite) and the next request reads " "its prompt from token 0\n", what, (long long) v.nonfinite_pos(), row); std::fflush(stderr); nf_hit = true; nan_flush = true; if (std::strcmp(what, "prompt") == 0) nf_prompt_windows = true; return true; }; auto imgs_below = [&](const std::vector& all, int64_t L) { std::vector v; for (const ImgKey& k : all) if (k.start < L) v.push_back(k); return v; }; // a checkpoint of the state after `cur[0, L)`; false only when the copy itself failed // A layer split's mid-prompt checkpoints: when the last stage reports a chunk, the earlier ones already read // the next, so each stage saves its own part when IT reaches a checkpoint position (the same rule as below: // every `prompt_cache_every` tokens from where the request resumed), and the last stage puts them together. std::mutex part_mu; std::map> part_at; // position -> one part per stage std::vector part_next(stages.size() + 1, INT64_MAX); // a checkpoint of the state after `cur[0, L)`; false only when the copy itself failed. `parts`: the stages' // states saved at L (a split's mid-prompt checkpoint); without, they are read now (everything is at L) // #613: why the last checkpoint_at failed - a failed device sync is the GPU itself (a hang Windows then resets), // not the checkpoint, and the error says so std::string ckpt_why; // STRATA_TRACE: what each checkpoint cost - the device syncs, the copies into RAM (the vectors' first fill // included), the eviction that frees one - one line per checkpoint; with the prompt's read parts summed per // request for a batch admission's line (below, at BADM) const bool ckpt_trace = std::getenv("STRATA_TRACE") != nullptr; struct ReqTimes { int ckpts = 0; double sync_ms = 0.0, save_ms = 0.0, evict_ms = 0.0, read_ms = 0.0, windows_ms = 0.0; } req_times; auto gpu_sync_ok = [&]() -> bool { const cudaError_t e = cudaDeviceSynchronize(); if (e == cudaSuccess) return true; ckpt_why = std::string(": the GPU stopped responding before it (") + cudaGetErrorString(e) + ") - a GPU hang; on Windows the driver is then reset"; return false; }; StageThreads ckpt_threads; // STRATA_CKPT_THREADS: the later stages' parts of a checkpoint (started on first use) auto checkpoint_at = [&](int64_t L, std::vector* parts = nullptr, bool as_tail = false) -> bool { ckpt_why.clear(); if (o.prompt_cache <= 0 || L < 1) return true; for (ConvCheckpoint& c : checks) if ((int64_t) c.ids.size() == L) { c.used = ++check_clock; if (!as_tail && L == tail_ckpt_len) tail_ckpt_len = -1; // a periodic one lands here: a normal item now return true; } ConvCheckpoint c = parts == nullptr ? ckpt_pool.take() : ConvCheckpoint{}; // (STRATA_CKPT_POOL) if (parts == nullptr && ckpt_pool.on()) (c.gdn.empty() ? ck_fresh : ck_from_pool)++; if (parts == nullptr) pool_topup(); // the next save finds one ready (between requests only) c.ids.assign(cur.begin(), cur.begin() + L); c.imgs = imgs_below(req_imgs, L); if (parts != nullptr) { if (parts->size() != stages.size() + 1) return false; c.gdn = std::move((*parts)[0].gdn); c.dev_tag = (*parts)[0].dev_tag; c.ple = std::move((*parts)[0].ple); c.tails = std::move((*parts)[0].tails); c.dead = std::move((*parts)[0].dead); c.block_pos = std::move((*parts)[0].block_pos); for (size_t i = 1; i < parts->size(); ++i) c.stage_parts.push_back(std::move((*parts)[i])); } else if (ckpt_pool.on() || ckpt_threads_env()) { // STRATA_CKPT_POOL / STRATA_CKPT_THREADS: the parts go into the vectors a pooled checkpoint already has // (none resized), with the threads all at once; part k is stage k's session, synchronized first const size_t n = stages.size() + 1; const bool reused = !c.gdn.empty(); // (a pooled one) c.stage_parts.resize(stages.size()); for (ConvCheckpoint& part : c.stage_parts) part.ids = c.ids; std::vector synced(n, 0), saved(n, 0); std::vector why(n); std::vector sync_part(n, 0.0), part_ms(n, 0.0); std::vector thrown(n); // (a failed allocation: thrown here, as without the threads) const std::function save_part = [&](size_t k) { try { const Clock::time_point p0 = Clock::now(); const strata::core::OnDevice on(k == 0 ? -1 : stages[k - 1]->dev); const cudaError_t e = cudaDeviceSynchronize(); if (e != cudaSuccess) { why[k] = std::string(": the GPU stopped responding before it (") + cudaGetErrorString(e) + ") - a GPU hang; on Windows the driver is then reset"; return; } synced[k] = 1; const Clock::time_point p1 = Clock::now(); saved[k] = checkpoint_save(k == 0 ? c : c.stage_parts[k - 1], k == 0 ? ss : stages[k - 1]->ss, g); sync_part[k] = std::chrono::duration(p1 - p0).count(); part_ms[k] = std::chrono::duration(Clock::now() - p0).count(); } catch (...) { thrown[k] = std::current_exception(); } }; const Clock::time_point t0 = Clock::now(); if (ckpt_threads_env()) { ckpt_threads.run(n, save_part); } else { for (size_t k = 0; k < n; ++k) { save_part(k); if (!synced[k] || !saved[k]) break; } } for (size_t k = 0; k < n; ++k) if (thrown[k]) std::rethrow_exception(thrown[k]); for (size_t k = 0; k < n; ++k) { if (!synced[k]) { ckpt_why = why[k]; return false; } if (!saved[k]) return false; } if (ckpt_trace) { // sync: the first stage's (the others' are in their parts' times) const double wall = std::chrono::duration(Clock::now() - t0).count(); std::string each; for (size_t k = 0; k < n; ++k) { char b[32]; std::snprintf(b, sizeof b, " %.1f", part_ms[k]); each += b; } ++req_times.ckpts; req_times.sync_ms += sync_part[0]; req_times.save_ms += wall - sync_part[0]; std::fprintf(stderr, "strata trace: checkpoint at %lld: sync %.1f ms, save %.1f ms (%zu stage(s)%s, " "each%s ms, %s)\n", (long long) L, sync_part[0], wall - sync_part[0], n, ckpt_threads_env() ? " at once" : "", each.c_str(), reused ? "into a dropped checkpoint's vectors" : "new vectors"); } } else { Clock::time_point t0 = Clock::now(); auto lap = [&](double& acc) { // (STRATA_TRACE only) if (!ckpt_trace) return; const Clock::time_point t1 = Clock::now(); acc += std::chrono::duration(t1 - t0).count(); t0 = t1; }; double sync_ms = 0.0, save_ms = 0.0; if (!gpu_sync_ok()) return false; lap(sync_ms); if (!checkpoint_save(c, ss, g)) return false; lap(save_ms); for (auto& st : stages) { // a layer split's later stages: their sessions' part const strata::core::OnDevice on(st->dev); ConvCheckpoint part; part.ids = c.ids; if (!gpu_sync_ok()) return false; lap(sync_ms); if (!checkpoint_save(part, st->ss, g)) return false; c.stage_parts.push_back(std::move(part)); lap(save_ms); } if (ckpt_trace) { ++req_times.ckpts; req_times.sync_ms += sync_ms; req_times.save_ms += save_ms; std::fprintf(stderr, "strata trace: checkpoint at %lld: sync %.1f ms, save %.1f ms (%zu stage(s))\n", (long long) L, sync_ms, save_ms, stages.size() + 1); } } c.used = ++check_clock; if (seg_plan.chunk > 0 && L > seg_plan.from && L < seg_plan.to) c.plan = seg_plan; // inside a planned segment if (as_tail) { // only one tail checkpoint stays alive: the previous request's goes const int64_t old_tail = tail_ckpt_len; auto old = [&](const ConvCheckpoint& k) { return old_tail >= 0 && (int64_t) k.ids.size() == old_tail; }; if (ckpt_pool.on()) ckpt_pool.erase_if(checks, old); else checks.erase(std::remove_if(checks.begin(), checks.end(), old), checks.end()); tail_ckpt_len = L; } else if (L == tail_ckpt_len) { tail_ckpt_len = -1; // the flagged tail was dropped and a normal checkpoint takes its length } checks.push_back(std::move(c)); const Clock::time_point te0 = Clock::now(); const size_t before_evict = checks.size(); while ((int) checks.size() > o.prompt_cache) { std::vector stamps; std::vector is_tail; stamps.reserve(checks.size()); for (const ConvCheckpoint& k : checks) { stamps.push_back(k.used); is_tail.push_back(tail_ckpt_len >= 0 && (int64_t) k.ids.size() == tail_ckpt_len); } // the tail checkpoint serves only a branch of the last request: it leaves before a periodic one std::unique_ptr tail_flags(new bool[is_tail.size()]); for (size_t i = 0; i < is_tail.size(); ++i) tail_flags[i] = is_tail[i] != 0; // the pin=N prefix is never the victim (flags only when one is pinned: nothing changes without) std::unique_ptr pin_flags; for (const ConvCheckpoint& k : checks) if (k.pinned) { pin_flags.reset(new bool[checks.size()]); for (size_t i = 0; i < checks.size(); ++i) pin_flags[i] = checks[i].pinned; break; } std::vector lens; for (const ConvCheckpoint& k : checks) lens.push_back((int64_t) k.ids.size()); const size_t victim = o.prompt_cache_spread ? strata::program::conv_cache::spread_victim(lens.data(), stamps.data(), stamps.size(), o.prompt_cache, tail_flags.get(), pin_flags.get()) : strata::program::conv_cache::eviction_victim(stamps.data(), stamps.size(), o.prompt_cache, tail_flags.get(), pin_flags.get()); ckpt_pool.give(std::move(checks[victim])); // (STRATA_CKPT_POOL; else nothing) checks.erase(checks.begin() + (std::ptrdiff_t) victim); } if (ckpt_trace && checks.size() < before_evict) { const double ms = std::chrono::duration(Clock::now() - te0).count(); req_times.evict_ms += ms; std::fprintf(stderr, "strata trace: checkpoint at %lld: %zu evicted in %.1f ms\n", (long long) L, before_evict - checks.size(), ms); } return true; }; // STRATA_SPLIT_MTP_BATCH=1 (default off): the layer split's drafter is on the last stage, so E-9 (Prefill::draft_kv) // runs there, on the Prefill that ran the chunk, instead of the drafter's own per-8-row pass. The drafts' K/V // come from Q8_1 x Q8_0 MMQ rather than mmvq: drafts may differ, the target's tokens never. static const bool split_mtp_batch = strata::program::draft_kv::split_env_on(std::getenv("STRATA_SPLIT_MTP_BATCH")); sp.on_chunk = [&](const float* R_rows, int64_t T, int64_t p0, std::string& e) -> bool { // KVA: a chunk the late layers did not compute has no real final rows: its draft cells are neither built // nor read (the floor rises before the cells are built, so they are skipped) if (use_mtp && mtp.cell_floor_enabled() && sp.kva_floor() > mtp.cell_floor()) mtp.set_cell_floor(sp.kva_floor()); std::vector nxt((size_t) T); for (int64_t t = 0; t < T; ++t) nxt[(size_t) t] = (int32_t) cur[(size_t) (p0 + t + 1)]; // E-9: batched through the prompt path when it can (a layer split: only with STRATA_SPLIT_MTP_BATCH=1) bool batched = false; const strata::program::draft_kv::Plan dkv = strata::program::draft_kv::plan( use_mtp, multi_gpu, split_mtp_batch && !mtp_first, strata::core::native_embed() != nullptr); if (dkv.try_batched || dkv.why != nullptr) { strata::prefill::Prefill& dsp = multi_gpu ? stages.back()->sp : sp; // the drafter's stage const char* why = dkv.why; if (dkv.try_batched) batched = dsp.draft_kv(mtp, R_rows, nxt.data(), T, p0, e, &why); if (multi_gpu) { // once per process: what this env did static bool said = false; if (!said && (batched || (e.empty() && why != nullptr))) { said = true; if (batched) std::fprintf(stderr, "strata serve: draft layer prompt K/V batched on CUDA%d (E-9 on the layer " "split, K/V mode %d)\n", stages.back()->dev, mtp.kv_state().kv_mode); else std::fprintf(stderr, "strata serve: STRATA_SPLIT_MTP_BATCH=1 declined, the drafter's own pass " "runs: %s\n", why); } } } if (!e.empty() || (use_mtp && !batched && !mtp.prefill(R_rows, nxt.data(), T, p0, e))) return false; #if defined(STRATA_HAVE_DFLASH2) if (use_df2) { std::vector tk((size_t) T); for (int64_t t = 0; t < T; ++t) tk[(size_t) t] = (int32_t) cur[(size_t) (p0 + t)]; df2.note_rows(tk.data(), T, p0); } #endif if (use_mtp && std::getenv("STRATA_SNAPSHOT_VERIFY") != nullptr) std::fprintf(stderr, "strata serve: DRAFT_PREFILL path=%s mode=%d cells=%lld\n", batched ? "batched" : "token", mtp.kv_state().kv_mode, (long long) T); // progress for the server window: PP const int64_t done = p0 + T; pp_reached = done; const double ms = std::chrono::duration(Clock::now() - pp_t0).count(); std::printf("PP %lld %lld %.0f %.1f\n", (long long) done, (long long) pp_total, ms, ms > 0.0 ? 1000.0 * (double) (done - pp_from) / ms : 0.0); strata::core::progress_at("reading the prompt (batched), done up to token", done); strata::core::progress_beat(); std::fflush(stdout); // layer-major prefill: a sub-chunk before its super-chunk's end has the super-chunk's state - the // checkpoint is taken at that end instead const bool periodic_checkpoint = o.prompt_cache_every > 0 && done >= pp_next_check && !sp.layer_major_mid(); // Keep the prefill's existing chunk geometry. One extra near-tail checkpoint // can serve a branch whose shared prefix ends before the final cached state. const bool tail_checkpoint = o.prompt_cache_tail && o.prompt_cache > 0 && o.prompt_cache_every > 0 && !multi_gpu && !pp_tail_saved && pp_total - done > std::max(1, o.short_read) && pp_total - done <= T && // this chunk's real size (--prefill auto chunks differ from o.prefill_chunk) !sp.layer_major_mid(); if (periodic_checkpoint || tail_checkpoint) { bool saved = false; if (multi_gpu) { // the stages' parts, saved when each of them read this chunk std::vector parts; { std::lock_guard lk(part_mu); auto it = part_at.find(done); if (it != part_at.end()) parts = std::move(it->second); part_at.erase(part_at.begin(), part_at.upper_bound(done)); } bool complete = parts.size() == stages.size() + 1; for (const ConvCheckpoint& k : parts) complete = complete && !k.gdn.empty(); saved = !complete || checkpoint_at(done, &parts); // an incomplete set: no checkpoint here } else { saved = checkpoint_at(done, nullptr, tail_checkpoint && !periodic_checkpoint); } if (!saved) { // #3350: only a GPU that is unwell ends the request; a copy that ran out of memory skips this checkpoint if (!ckpt_why.empty() || !checkpoint_failure_is_survivable()) { e = "saving a conversation checkpoint failed" + ckpt_why; return false; } std::fprintf(stderr, "strata serve: checkpoint at %lld skipped: its state could not be copied out (see " "above); the request goes on without it\n", (long long) done); } if (periodic_checkpoint) pp_next_check = done + o.prompt_cache_every; if (tail_checkpoint) pp_tail_saved = true; } return true; }; if (multi_gpu) { // the batched prompt is reported by its last stage (the drafter's rows are there) stages.back()->sp.on_chunk = std::move(sp.on_chunk); sp.on_chunk = nullptr; for (size_t i = 0; i <= stages.size(); ++i) { strata::prefill::Prefill& stage_sp = i == 0 ? sp : stages[i - 1]->sp; strata::core::SessionState& stage_ss = i == 0 ? ss : stages[i - 1]->ss; stage_sp.on_stage_chunk = [&, i](int64_t done, std::string& e) -> bool { if (o.prompt_cache <= 0 || o.prompt_cache_every <= 0 || done < part_next[i]) return true; part_next[i] = done + o.prompt_cache_every; ConvCheckpoint part; // this stage's state at `done` (its stream is synchronized) part.ids.assign(cur.begin(), cur.begin() + done); if (!checkpoint_save(part, stage_ss, g)) { // #3350: the copy ran out of memory (not the GPU): leave this part out. The set at `done` is then // incomplete and the checkpoint is skipped below, as for a part that was never made if (!checkpoint_failure_is_survivable()) { e = "saving a checkpoint part failed"; return false; } std::fprintf(stderr, "strata serve: checkpoint at %lld skipped: stage %zu's state could not be copied " "out (see above); the request goes on without it\n", (long long) done, i); std::lock_guard lk(part_mu); part_at[done].resize(stages.size() + 1); // (marks the set as seen; its empty parts make it incomplete) return true; } std::lock_guard lk(part_mu); auto& v = part_at[done]; v.resize(stages.size() + 1); v[i] = std::move(part); return true; }; } } drive.d.plan = ver.plan_sink(); // Foresight swap space (STRATA_FS_SLOTS; unset = null and nothing changes) std::unique_ptr fs_swap; { int main_dev = 0; cudaGetDevice(&main_dev); std::vector devs{main_dev}; for (auto& st : stages) devs.push_back(st->dev); std::vector card((size_t) g.n_layers, 0); for (int64_t l = 0; l < g.n_layers; ++l) card[(size_t) l] = multi_gpu ? stage_of(l) : 0; fs_swap.reset(strata::core::foresight_swap_from_env(g.n_layers, g.n_expert, card, devs)); drive.d.fs = fs_swap.get(); if (fs_swap && drive.d.lookahead != nullptr) lookahead.set_foresight(fs_swap.get()); src.set_foresight_swap(fs_swap.get()); // #2134: the exchanges hold the experts whose bytes they move } // the look-ahead thread and the exchanges must not touch the swap space once it is gone (declared after it: // destroyed first) struct FsDetach { strata::core::RouterLookahead* la; strata::core::FileExpertSource* src; ~FsDetach() { la->set_foresight(nullptr); src->set_foresight_swap(nullptr); } } fs_detach{&lookahead, &src}; // 0.2.10 (BW-MEASURE E26): PcieAuto starts from the pool size instead of the link-only 0.55 (0.15 on gfx12), so the first answers after a launch // do not run ~50 windows at a share the machine does not want. The pool's expert-byte rate R is assumed to be min(65, 4.0 GB/s per worker) // (measured: 31-35 GB/s at 6-8 workers, 47-52 at 12, 55-60 at 16-30, 73-75 at 32) and the share is the refinement's own formula, link / (link + // 1.85 R) rounded to 0.05 and clamped 0.10..0.60, so a weak CPU starts HIGH (4 workers 0.50, 2 workers 0.60). The converged share is unchanged. // STRATA_PCIE_START=old keeps the link-only start. First answer on an RTX PRO 5000 mimic (32 workers): +4..+12%; 8 workers and the R9700: +-1%. if (o.pcie_frac_auto && o.pcie_probe_gbps > 0.0) { const char* ps = std::getenv("STRATA_PCIE_START"); #if defined(STRATA_USE_HIP) // HIP: the new start is opt-in (STRATA_PCIE_START=new). On the R9700 it measured +-1% by the note above, and it flips near-tie tokens in the first // ~50 windows after a start (INT3/G2, p620, commit 06ebf2e4d: v0.2.9 vs the merged build with the other new defaults off 21/45 identical answers, // 45/45 with STRATA_PCIE_START=old), so AMD keeps v0.2.9's start share. CUDA keeps the new start by default (STRATA_PCIE_START=old restores). const bool new_start = ps != nullptr && std::strcmp(ps, "new") == 0; #else const bool new_start = ps == nullptr || std::strcmp(ps, "old") != 0; #endif if (new_start) { const double r = std::min(65.0, 4.0 * (double) pool.workers()); const double f0 = std::min(pcie_share_max(), std::max(0.10, std::round(o.pcie_probe_gbps / (o.pcie_probe_gbps + pcie_pool_k(r) * r) * 20.0) / 20.0)); std::fprintf(stderr, "strata serve: PCIe share: start %.2f from %d pool workers (assumed %.0f GB/s of expert bytes) and the %.1f GB/s link (was %.2f)\n", f0, pool.workers(), r, o.pcie_probe_gbps, o.pcie_frac); o.pcie_frac = f0; } } drive.d.pcie_num = std::max(0, std::min(256, (int) (o.pcie_frac * 256.0 + 0.5))); const bool all_experts_resident = !host_res.empty() && std::all_of(host_res.begin(), host_res.end(), [](int32_t r) { return r >= 0; }); // STRATA_ROUTE_TAIL_SKIP: ON BY DEFAULT on CUDA builds (owner decision, 0.1.42) and on HIP gfx1200/gfx1201 (0.1.43): a missed expert that every token of // a verify window routes at rank 7 or lower is neither copied nor computed (answers differ slightly from 0.1.41, // KL ~0.003-0.006; docs/DETAILS.md). =0 restores 0.1.41's bytes. Nothing to do, so no default and no line, when every // expert is in VRAM; off with --batch slots (a window then mixes requests, and one request's skip would depend on // another's tokens) and, as in the dispatch, with a peer or helper GPU. A layer split is fine: each stage skips by itself. { const char* tse = std::getenv("STRATA_ROUTE_TAIL_SKIP"); // #1884: with nearly every expert in the GPU cache (V100 32 GB, Coder IQ1_M: 94.8% of the experts, 99.9% decode hits) the few // misses are cheap and the skip costs more draft acceptance (70.1% -> 68.2%) than it saves: -1..2% decode. No default then. size_t cached_experts = 0; for (int32_t r : host_res) cached_experts += r >= 0 ? 1 : 0; // (STRATA_TAIL_SKIP_MAX_CACHED=, default 90, moves the line; 101 = never). 0.1.43: 60 on a HIP layer split, where // 2x R9700 (5 pairs, skip on vs off): Q2_0 story -6.2% at 70% cached, -1.8% at 60%; IQ3_S +6..15% at 44-52%, about 0 at 60%. #if defined(STRATA_USE_HIP) const double max_cached_default = n_stages > 1 ? 0.60 : 0.90; #else const double max_cached_default = 0.90; #endif const char* mcs = std::getenv("STRATA_TAIL_SKIP_MAX_CACHED"); const double max_cached = mcs != nullptr && mcs[0] != 0 ? std::atof(mcs) / 100.0 : max_cached_default; const bool nearly_all_cached = !host_res.empty() && !all_experts_resident && (double) cached_experts >= max_cached * (double) host_res.size(); // NVFP4 experts (any layer): no default (sergqwer/strata-nvfp4 c83625c3). On the fork's qwen-nvfp4-gptq pack the // skip moved the answers by teacher-forced KL 0.035 against it off - as much as the GPTQ quantization's own error // against an all-Q8_0 reference (0.038) - for +11.5% decode (RTX 5090). STRATA_ROUTE_TAIL_SKIP=7 opts in. bool nvfp4_experts = false; if (native_pack) for (const auto& f : strata::kernels::cpu::expert_layout().fmt) nvfp4_experts = nvfp4_experts || f.gu_type == strata::kernels::cpu::kNvfp4Type || f.d_type == strata::kernels::cpu::kNvfp4Type; const bool tail_default_path = tse == nullptr && !all_experts_resident && !nearly_all_cached && o.batch == 0 && decode_defaults_arch_ok() && o.peer_device < 0; const bool tail_default_ok = tail_default_path && !nvfp4_experts; if (tail_default_path && nvfp4_experts) std::fprintf(stderr, "strata serve: STRATA_ROUTE_TAIL_SKIP is off by default with NVFP4 experts (it moved an NVFP4 " "pack's answers by about as much as its quantization does); STRATA_ROUTE_TAIL_SKIP=7 turns it on\n"); if (tse == nullptr && nearly_all_cached && o.batch == 0 && o.peer_device < 0 && decode_defaults_arch_ok()) std::fprintf(stderr, "strata serve: STRATA_ROUTE_TAIL_SKIP is off by default: %.1f%% of the experts are in the GPU cache, so " "few are missed and skipping them costs more draft acceptance than it saves; " "STRATA_ROUTE_TAIL_SKIP=7 turns it on\n", 100.0 * (double) cached_experts / (double) host_res.size()); if (tail_default_ok) strata::core::set_tail_skip_rank(7); if (strata::core::tail_skip_rank() > 0 && !all_experts_resident) std::fprintf(stderr, "strata serve: STRATA_ROUTE_TAIL_SKIP=%d is ON%s: a missed expert that every token of a verify window routes at rank %d or " "lower is skipped (+10..20%% decode on 12-16 GB cards that miss experts, answers differ slightly from 0.1.41); " "STRATA_ROUTE_TAIL_SKIP=0 turns it off\n", strata::core::tail_skip_rank(), tse == nullptr ? " (default)" : "", strata::core::tail_skip_rank()); } if (((o.adapt_every > 0 && o.adapt_swaps > 0) || o.ram_adapt > 0) && !all_experts_resident) drive.d.usage.assign((size_t) (g.n_layers * g.n_expert), 0.0f); // --ram-adapt: the counts, no GPU rounds PcieAuto pcie_auto; if (o.pcie_frac_auto && !all_experts_resident && o.batch == 0 && o.peer_device < 0 && (n_stages == 1 || pcie_auto_split_ok())) { const auto& pl = strata::kernels::cpu::expert_layout(); double sum = 0.0; for (int64_t l = 0; l < g.n_layers; ++l) sum += (double) pl.blob_bytes(l); pcie_auto.on = true; pcie_auto.link_gbps = o.pcie_probe_gbps; pcie_auto.blob_bytes = g.n_layers > 0 ? sum / (double) g.n_layers : 0.0; } // PcieAuto after a decode window (the serial loop, and 0.1.44 the pipelined one at every verdict): the share, refined from // the CPU pool's speed. A layer split: every later stage takes the share its own probed link gives against the same pool // rate, on both parities' routing (the pipelined loop's second verifier). auto pcie_auto_step = [&](double& req_pcie_frac) { if (!pcie_auto.on) return; double tc_us = 0.0, rate = 0.0; const double nf = req_pcie_frac == o.pcie_frac ? pcie_auto.window(drive.d.ms_run, drive.d.multi_misses, o.pcie_frac, &tc_us, &rate) : (pcie_auto.mark(drive.d.ms_run, drive.d.multi_misses), -1.0); if (nf < 0.0) return; std::fprintf(stderr, "strata serve: PCIe share: the CPU pool takes %.0f us per missed expert (%.1f GB/s of expert bytes), " "the link %.1f GB/s -> pcie_frac %.2f (was %.2f; --pcie-frac N fixes it, " "STRATA_PCIE_FRAC_DEFAULT=old keeps the start-up rule)\n", tc_us, rate, pcie_auto.link_gbps, nf, o.pcie_frac); o.pcie_frac = nf; req_pcie_frac = nf; const auto num_of = [](double f) { return std::max(0, std::min(256, (int) (f * 256.0 + 0.5))); }; drive.d.pcie_num = num_of(nf); split_drive.pcie_num[0] = drive.d.pcie_num; split_drive_b.pcie_num[0] = drive.d.pcie_num; for (int st = 1; st < n_stages; ++st) { GpuStage& gs = *stages[(size_t) st - 1]; if (!(gs.link_gbps > 0.0)) continue; gs.pcie_frac = std::min(pcie_share_max(), std::max(0.10, std::round(gs.link_gbps / (gs.link_gbps + pcie_pool_k(rate) * rate) * 20.0) / 20.0)); split_drive.pcie_num[st] = num_of(gs.pcie_frac); split_drive_b.pcie_num[st] = split_drive.pcie_num[st]; std::fprintf(stderr, "strata serve: PCIe share: stage %d (link %.1f GB/s) -> pcie_frac %.2f\n", st + 1, gs.link_gbps, gs.pcie_frac); } }; // --draft-costs (repeatable output): PcieAuto's value comes from measured pool time, and a start that settles one reading later decodes // its windows in between with another share (one more or one fewer missed expert of a layer computed on the GPU instead of the CPU, // which round differently: on an RTX A6000 2 of 18 starts gave other tokens, 0 of 12 with the share fixed). So the settled share is // stored with the table and a later start runs with it fixed. One GPU only (a layer split keeps PcieAuto's per-stage refinement). const bool dc_pcie_ok = pcie_auto.on && n_stages == 1; auto fix_pcie_share = [&](double f) { pcie_auto.on = false; o.pcie_frac = f; drive.d.pcie_num = std::max(0, std::min(256, (int) (f * 256.0 + 0.5))); split_drive.pcie_num[0] = drive.d.pcie_num; split_drive_b.pcie_num[0] = drive.d.pcie_num; }; // the serial windows of one GPU, where the pool can admit (expert_pool_dispatch_multi's fetch_on) const char* fetch_off = d_res == nullptr ? "no residency table" : o.spec_split ? "--spec-split" : multi_gpu || !stages.empty() ? "a layer split" : peer.valid() ? "--peer-device" : remote_opt || drive.d.remote_count > 0 ? "helper GPUs" : o.adapt_async ? "--adapt-async" : o.pipeline_windows > 0 ? "--pipeline-windows" : o.batch > 0 ? "--batch" : adapt_overlap() ? "STRATA_ADAPT_OVERLAP=1" : nullptr; if (adapt_fetch() > 0) { // STRATA_ADAPT_FETCH (opt-in) const char* off = drive.d.usage.empty() ? "the adaptive tier is off" : fetch_off != nullptr ? fetch_off : o.pcie_mode == "dma" || o.pcie_mode == "direct" ? "--pcie-mode dma / direct" : drive.d.plan == nullptr ? "no GPU plan" : drive.d.pcie_num <= 0 ? "no PCIe share" : src.complement_ready() ? "the resident RAM mode" : nullptr; if (off != nullptr) std::fprintf(stderr, "strata serve: STRATA_ADAPT_FETCH is off (%s)\n", off); else { drive.d.fetch_admit = adapt_fetch(); drive.d.res_mut = host_res.data(); drive.d.in_flight.assign(host_res.size(), 0); drive.d.fetch_avail.assign((size_t) g.n_layers, 0); if (const char* v = std::getenv("STRATA_ADAPT_FETCH_MIN")) drive.d.fetch_min = (float) std::atof(v); if (const char* v = std::getenv("STRATA_ADAPT_FETCH_MARGIN")) drive.d.fetch_margin = (float) std::atof(v); std::fprintf(stderr, "strata serve: STRATA_ADAPT_FETCH=%d: the PCIe share takes each layer's most-routed " "misses and admits those routed >= %.2f and %.2f more than a resident one%s\n", drive.d.fetch_admit, drive.d.fetch_min, drive.d.fetch_margin, drive.d.fetch_admit == 2 ? "; the tier's own copies are off" : ""); } } // #477 --expert-profile-save: what the adaptive tier learned, kept across restarts (opt-in; off: `heat` stays // empty and nothing below runs). It needs the adaptive tier's counts and the residency table. std::vector heat; if (!o.expert_profile_save.empty() && !all_experts_resident) { if (drive.d.usage.empty() || host_res.empty()) std::fprintf(stderr, "strata serve: --expert-profile-save needs the adaptive tier (--adapt-every and " "--adapt-swaps above 0) and --expert-profile: nothing will be saved\n"); else heat.assign(drive.d.usage.size(), 0.0); } Clock::time_point profile_saved_at = Clock::now(); cudaStream_t adapt_stream = nullptr; if (cudaStreamCreateWithFlags(&adapt_stream, cudaStreamNonBlocking) != cudaSuccess) { std::fprintf(stderr, "strata serve: cannot create the refill stream\n"); return 1; } // plan v0.3 P6: swaps in flight - (residency index, slot) admitted when adapt_ev has completed std::vector> pending; int pending_age = 0; // the windows the pending swaps have waited (adapt_lag) std::vector pin_live; // the swaps' locked arena pages (pin_blob), unlocked once they have landed cudaEvent_t adapt_ev = nullptr; cudaEventCreateWithFlags(&adapt_ev, cudaEventDisableTiming); // 0.1.43 STRATA_ADAPT_OVERLAP=1 (adapt_overlap above): the single-GPU, plain-RAM-arena decode loop only strata::core::AdaptGate agate; bool aflipped = false; // the pending swaps are in the tables and their copies may still be landing bool aov = false; int64_t aov_flips = 0; // #2010: the overlap is opt-in on every backend now, so the off state is the default and has to be visible too. // The predicates are side-effect free, so they are read in both states: they name why it could not run. // A peer tier (--peer-device) joins the overlap: measured on one rig so far (RTX 5060 Ti x8 + RTX 3060, IQ3_XXS), // where the blocking wait took 3-8 ms of a 27-43 ms window. const bool aov_want = adapt_overlap(); const char* aov_why = multi_gpu || !stages.empty() ? "not on a layer split" : remote_opt ? "not with --remote-expert-opt" : o.adapt_async ? "not with --adapt-async" : o.pipeline_windows > 0 ? "not with --pipeline-windows" : pin_blobs_on() ? "not with page-locked swap sources" : strata::core::dma_batch_mode() != 0 ? "not with STRATA_DMA_BATCH" : adapt_lag() != 1 || adapt_nowait() ? "not with STRATA_ADAPT_LAG / STRATA_ADAPT_NOWAIT" // the resident RAM mode is exact too (soft_commit_exchanges) but not a win everywhere: RTX A4000 +7.0% // (5/5 pairs), RTX 3060 on a 46 GB box -2.6% (0/5; the CPU experts and the copies share the RAM bandwidth) : src.complement_ready() && !(std::getenv("STRATA_ADAPT_OVERLAP_RESIDENT") && std::getenv("STRATA_ADAPT_OVERLAP_RESIDENT")[0] == '1') ? "not in the resident RAM mode unless STRATA_ADAPT_OVERLAP_RESIDENT=1" : drive.d.usage.empty() || o.adapt_every <= 0 ? "the adaptive tier is off" : nullptr; if (aov_want) { if (aov_why == nullptr) { agate.ticks.resize((size_t) g.n_layers + 1); for (int64_t l = 0; l <= g.n_layers; ++l) agate.ticks[(size_t) l] = {&agate.landed, (int32_t) l}; agate.has.assign((size_t) g.n_layers, 0); agate.peer_has.assign((size_t) g.n_layers, 0); if (!ver.set_adapt_gate(&agate)) aov_why = "the device-planned layers (STRATA_VERIFY_DEVICE_PLAN) are on"; // #2188: on Windows the default is the host function. Under WDDM a stream's work sits in the driver's // command buffer until something flushes it, and nothing does while the host only spins on the pinned // int: the first request stopped with "copies for layer 45 never landed". STRATA_ADAPT_SIGNAL=copy asks // for the stream-ordered copy there too (the enqueue then flushes the stream), =host everywhere. const char* asig = std::getenv("STRATA_ADAPT_SIGNAL"); #if defined(_WIN32) const bool sig_copy = asig != nullptr && asig[0] == 'c'; #else const bool sig_copy = !(asig != nullptr && asig[0] == 'h'); #endif if (aov_why == nullptr && !sig_copy) std::fprintf(stderr, "strata serve: adaptive overlap signal: host functions%s\n", asig == nullptr ? " (the Windows default, #2188; STRATA_ADAPT_SIGNAL=copy: a stream-ordered copy)" : ""); if (aov_why == nullptr && sig_copy) { // the landing of each layer's copies is told by a stream-ordered D2H copy of the layer number into pinned memory // (STRATA_ADAPT_SIGNAL=host: a host function instead). No callback thread has to be scheduled while the pool's workers spin on every other CPU int32_t* vals = nullptr; void* hp = nullptr; std::vector iota((size_t) g.n_layers + 1); for (size_t i = 0; i < iota.size(); ++i) iota[i] = (int32_t) i; if (cudaMalloc((void**) &vals, iota.size() * 4) == cudaSuccess && cudaMemcpy(vals, iota.data(), iota.size() * 4, cudaMemcpyHostToDevice) == cudaSuccess && cudaHostAlloc(&hp, 64, cudaHostAllocPortable) == cudaSuccess) { *(volatile int32_t*) hp = -1; agate.hland = (volatile int32_t*) hp; agate.dvals = vals; std::fprintf(stderr, "strata serve: adaptive overlap signal: stream-ordered copies (STRATA_ADAPT_SIGNAL=host: a host function)\n"); } else { (void) cudaGetLastError(); } } // the peer tier's copies land over its own link and are gated the same way, with the same kind of signal if (aov_why == nullptr && peer.valid()) agate.peer_hland = peer.set_overlap_gate(&agate.peer_landed, &agate.peer_has, &agate.peer_last, sig_copy); } aov = aov_why == nullptr; if (aov) std::fprintf(stderr, "strata serve: adaptive overlap (STRATA_ADAPT_OVERLAP=0 turns it off): the adaptive tier's copies land while the next window runs " "(same tokens, a layer waits for its own copies)%s\n", !peer.valid() ? "" : agate.peer_hland != nullptr ? "; the peer tier's copies too, over its own link (stream-ordered copies)" : "; the peer tier's copies too, over its own link (host functions)"); else if (std::getenv("STRATA_ADAPT_OVERLAP") != nullptr) // the env var was set: say what stopped it std::fprintf(stderr, "strata serve: STRATA_ADAPT_OVERLAP=1 is off: %s\n", aov_why); } else std::fprintf(stderr, "strata serve: adaptive overlap: off%s%s\n", aov_why ? ": " : " (STRATA_ADAPT_OVERLAP=1 turns it on)", aov_why ? aov_why : ""); // a layer split's later stages keep a copy of the residency table on their devices, and swap on their own auto res_upload = [&]() -> cudaError_t { // the first error, every table tried cudaError_t r = d_res != nullptr ? res_put(d_res) : cudaSuccess; for (auto& st : stages) { const strata::core::OnDevice on(st->dev); const cudaError_t e = res_put(st->d_res); if (r == cudaSuccess) r = e; } return r; }; auto apply_pending = [&](bool wait) { if (peer.valid()) peer.apply_pending(wait); if (pending.empty()) { // a round where only the peer swapped: its copies have landed (or, without the wait, are still in // flight), and the gate closes with them if (!(peer.valid() && peer.has_pending())) { agate.active.store(false, std::memory_order_release); aflipped = false; } return; } if (wait) cudaEventSynchronize(adapt_ev); else if (cudaEventQuery(adapt_ev) != cudaSuccess) return; for (auto& st : stages) if (st->adapt_live) { if (wait) cudaEventSynchronize(st->adapt_ev); else if (cudaEventQuery(st->adapt_ev) != cudaSuccess) return; } for (auto& st : stages) st->adapt_live = false; unpin_blobs(pin_live); src.commit_exchanges(); // the resident RAM mode: the evicted experts take their places in RAM for (const auto& [i, slot] : pending) { host_res[(size_t) i] = slot; srcp->release((int64_t) i / g.n_expert, (int64_t) i % g.n_expert); // in VRAM now: RAM not needed if (!drive.d.in_flight.empty()) drive.d.in_flight[(size_t) i] = 0; } if (drive.d.evict_sync || drive.d.fetch_admit > 0) { // a failed upload leaves them to the pre-launch hook for (const auto& pr : pending) drive.d.res_dirty_idx.push_back(pr.first); drive.d.res_dirty = true; } pending.clear(); pending_age = 0; agate.active.store(false, std::memory_order_release); // 0.1.43: the copies have landed (STRATA_ADAPT_OVERLAP) aflipped = false; if (res_upload() == cudaSuccess) { // the whole table: the hook has nothing left drive.d.res_dirty = false; drive.d.res_dirty_idx.clear(); } }; // Where the tier does not wait for its copies (STRATA_ADAPT_NOWAIT=1, STRATA_ADAPT_LAG > 1), its evictions reach // the device's tables before the next window: adapt() marks them non-resident at once, apply_pending uploads // only when the round's copies land - a window or more later, and until then doorbell_publish_res skips the // activation of a layer whose routed experts all look resident, while the pool computes an evicted one from the // activation published before. The hook runs at each verifier's launch; the serial windows (one at a time, // the batch windows included, a layer split's stages one after another) take it. STRATA_ADAPT_FETCH's // admissions (the pool writes host_res during a window) go up the same way, whether the tier waits or not. // --batch-groups with a layer split launches a group while another is in flight on the other stage, which // waits on this thread: a synchronous upload there could wait on that window, so those verifiers publish // every activation instead (set_always_publish; the device table then decides nothing a stale entry breaks). // --pipeline-windows is exempt: its verifiers always publish, and the tier fences the windows in flight // before it overwrites a slot (adapt_fence). --adapt-async uploads at each of its steps. // STRATA_ADAPT_CHECKRES=1 reads the tables back at each launch and compares them with the host's. const bool piped_groups = o.batch > 0 && o.batch_groups > 1 && !stages.empty(); const bool serial_windows = !pipe && !piped_groups; const bool tier_lags = o.adapt_every > 0 && !drive.d.usage.empty() && (adapt_nowait() || adapt_lag() > 1); drive.d.evict_sync = serial_windows && tier_lags && (adapt_evict_sync() || drive.d.fetch_admit > 0); if (piped_groups && tier_lags && adapt_evict_sync()) { ver.set_always_publish(true); for (auto& st : stages) st->ver.set_always_publish(true); } const bool res_checking = std::getenv("STRATA_ADAPT_CHECKRES") != nullptr && serial_windows; std::vector res_back; int64_t res_windows = 0, res_bad = 0, res_bad_windows = 0; if (res_checking) { res_back.assign(host_res.size(), 0); drive.d.dres_check = res_back.data(); } // The changed entries go up by a kernel on each card's verifier stream, reading them from mapped memory: a // synchronous upload waits for the copy engine, which the tier's swaps of the round before still hold (~4 ms // on 33 swaps; measured +0.9 ms a chat round). Too many changes, or no mapped memory: the whole table. constexpr size_t kResPatchCap = 16384; std::vector res_devs{-1}; for (auto& st : stages) res_devs.push_back(st->dev); int32_t* res_pairs = (serial_windows && (drive.d.fetch_admit > 0 || drive.d.evict_sync)) ? res_pairs_alloc(kResPatchCap, res_devs) : nullptr; auto res_sync = [&](bool check, std::string& e) -> bool { if (drive.d.res_dirty) { const int64_t n = res_patch_pairs(drive.d.res_dirty_idx, host_res, res_pairs, kResPatchCap); cudaError_t r = cudaSuccess; if (n >= 0) { if (d_res != nullptr) { strata::kernels::res_patch(d_res, res_pairs, (int) n, ver.stream()); r = cudaGetLastError(); } for (size_t k = 0; k < stages.size() && r == cudaSuccess; ++k) { const strata::core::OnDevice on(stages[k]->dev); strata::kernels::res_patch(stages[k]->d_res, res_pairs, (int) n, stages[k]->ver.stream()); r = cudaGetLastError(); } } else { r = res_upload(); } if (r != cudaSuccess) { e = std::string("the residency table update failed: ") + cudaGetErrorString(r); return false; } drive.d.res_dirty = false; drive.d.res_dirty_idx.clear(); } if (!check) return true; cudaStreamSynchronize(ver.stream()); // the patches landed (the verifier streams do not block the read) for (auto& st : stages) { const strata::core::OnDevice on(st->dev); cudaStreamSynchronize(st->ver.stream()); } int64_t bad = 0; for (auto& st : stages) { // the later stages' copies first: res_back ends with CUDA0's (the pool's check) const strata::core::OnDevice on(st->dev); bad += res_check(st->d_res, host_res, res_back, g.n_expert, res_windows); } bad += res_check(d_res, host_res, res_back, g.n_expert, res_windows); ++res_windows; res_bad += bad; res_bad_windows += bad > 0; if ((res_windows & 255) == 0 || (bad > 0 && res_bad_windows <= 4)) std::fprintf(stderr, "strata serve: res check: %lld windows, %lld with mismatches (%lld entries), " "%lld layer-windows with CPU experts and no activation published\n", (long long) res_windows, (long long) res_bad_windows, (long long) res_bad, (long long) drive.d.stale_x); return true; }; struct PreLaunchOff { // the hooks' captures die before the verifiers strata::core::Verifier& v; std::vector>& stages; strata::core::ExpertDispatch& d; int32_t* pairs; ~PreLaunchOff() { v.set_pre_launch(nullptr); for (auto& st : stages) st->ver.set_pre_launch(nullptr); d.dres_check = nullptr; if (pairs != nullptr) cudaFreeHost(pairs); } } pre_launch_off{ver, stages, drive.d, res_pairs}; if (serial_windows && (drive.d.fetch_admit > 0 || drive.d.evict_sync || res_checking)) { ver.set_pre_launch([&](cudaStream_t, std::string& e) { return res_sync(res_checking, e); }); for (auto& st : stages) st->ver.set_pre_launch([&](cudaStream_t, std::string& e) { return res_sync(false, e); }); if (drive.d.evict_sync && adapt_evict_sync()) std::fprintf(stderr, "strata serve: the adaptive tier's evictions reach the device's table before the next " "window (STRATA_ADAPT_EVICT_SYNC=0: when its copies land)\n"); } // --pipeline-windows: set while the tier adapts beside windows in flight (see its use in adapt) std::function adapt_fence; int64_t adapt_nswaps = 0; // the blocking tier's swaps chosen, cumulative (the decode timing line's swaps/window) // the VRAM tier follows the conversation (the same rule as the speculative loop below) auto adapt = [&]() -> bool { if (!pending.empty()) return true; // the previous swaps are still in flight // STRATA_HELPER_ADAPT_SWAPS=N: the helpers' swaps per round (default the primary's --adapt-swaps; 0 keeps them // static). Each swap is a blocking fill over the helper's link, which a PCIe x4 card pays per window. static const int helper_swaps = [&] { const char* v = std::getenv("STRATA_HELPER_ADAPT_SWAPS"); return v != nullptr ? std::max(0, std::atoi(v)) : o.adapt_swaps; }(); if (remote_opt && !remote_opt->adapt(drive.d.usage, host_res, pending, helper_swaps, *srcp)) return false; struct Swap { float gain; int32_t layer, in, out; }; std::vector swaps; std::vector> cand, vict; for (int64_t l = 0; l < g.n_layers; ++l) { // STRATA_ADAPT_FETCH=2: where the PCIe share fetched since the last round, its fetchable experts are // the admission's; the tier keeps the rest (no share there, or not pinned) const bool fetched = drive.d.fetch_admit == 2 && !drive.d.fetch_avail.empty() && drive.d.fetch_avail[(size_t) l]; if (!drive.d.fetch_avail.empty()) drive.d.fetch_avail[(size_t) l] = 0; cand.clear(); vict.clear(); const float* u = drive.d.usage.data() + l * g.n_expert; const int32_t* r = host_res.data() + l * g.n_expert; for (int32_t e = 0; e < (int32_t) g.n_expert; ++e) { if (r[e] < 0) { if (u[e] >= 2.0f && !(peer.valid() && peer.has(l, e)) && !(remote_opt && remote_opt->owns(l, e)) && !helper_holds(l, e) && !(fetched && srcp->pinned(l, e))) cand.emplace_back(u[e], e); } else vict.emplace_back(u[e], e); } if (cand.empty() || vict.empty()) continue; std::sort(cand.begin(), cand.end(), [](auto& a, auto& b) { return a.first > b.first; }); const size_t nc = std::min(cand.size(), vict.size()); std::partial_sort(vict.begin(), vict.begin() + (ptrdiff_t) nc, vict.end(), [](auto& a, auto& b) { return a.first < b.first; }); for (size_t i = 0; i < nc; ++i) { if (cand[i].first < vict[i].first + o.adapt_min_gain) break; swaps.push_back({cand[i].first - vict[i].first, (int32_t) l, cand[i].second, vict[i].second}); } } std::sort(swaps.begin(), swaps.end(), [](const Swap& a, const Swap& b) { return a.gain > b.gain; }); if ((int) swaps.size() > o.adapt_swaps) swaps.resize((size_t) o.adapt_swaps); if (aov) { // 0.1.43: the copies go in layer order and each layer's landing is told to the verify window std::stable_sort(swaps.begin(), swaps.end(), [](const Swap& a, const Swap& b) { return a.layer < b.layer; }); agate.landed.store(-1, std::memory_order_release); if (agate.hland != nullptr) *agate.hland = -1; agate.has.assign((size_t) g.n_layers, 0); agate.last = -1; for (const Swap& s : swaps) { agate.has[(size_t) s.layer] = 1; agate.last = std::max(agate.last, s.layer); } // the peer's marks of the previous round go too (its adapt below sets this round's, if it swaps anything) agate.peer_landed.store(-1, std::memory_order_release); agate.peer_has.assign((size_t) g.n_layers, 0); agate.peer_last = -1; } // the copies back read the cache of the card that owns each layer (see resident_stage_swaps) auto home_of = [&](int64_t layer) -> SwapHome { const int stn = multi_gpu ? stage_of(layer) : 0; if (stn > 0) { GpuStage* gs = stages[(size_t) stn - 1].get(); return {&gs->cache, gs->adapt_stream, gs->dev}; } return {&xcache, adapt_stream, -1}; }; if (!resident_stage_swaps(src, host_res, g.n_expert, swaps, home_of)) return false; adapt_nswaps += (int64_t) swaps.size(); // (read after the thread's join) if (pin_blobs_on()) { // lock the batch's source pages (a file-backed arena on AMD; see pin_blobs) std::vector> spans; for (const Swap& s : swaps) if (const uint8_t* b = srcp->blob_stable(s.layer, s.in)) spans.emplace_back((uintptr_t) b, (uintptr_t) b + strata::kernels::cpu::expert_layout().blob_bytes(s.layer)); pin_blobs(std::move(spans), pin_live); } // --pipeline-windows: windows are in flight while the tier adapts. The evicted experts stop being planned // for the GPU first (the pool computes them on the CPU from the rows every layer publishes, see // Verifier::set_always_publish); then every copy into their slots waits until all the work the stages' // streams hold now has completed: any window that may still read those slots was launched before this. std::vector fenced_slots; if (adapt_fence && !swaps.empty()) { for (const Swap& s : swaps) { const size_t out = (size_t) s.layer * g.n_expert + s.out; fenced_slots.push_back(host_res[out]); host_res[out] = strata::core::kNotResident; } std::atomic_thread_fence(std::memory_order_seq_cst); adapt_fence(); } bool main_live = false; // STRATA_DMA_BATCH (F12): the main device's copies as one cudaMemcpyBatchAsync (mode 0: one each) const int dma_mode = multi_gpu ? 0 : strata::core::dma_batch_mode(); std::vector cp_dst; std::vector cp_src; std::vector cp_bytes; for (size_t si = 0; si < swaps.size(); ++si) { const Swap& s = swaps[si]; if (aov && (si == 0 || swaps[si - 1].layer != s.layer)) { // test hook (STRATA_ADAPT_OVERLAP_SLOW_US=N): a slow link, to make the windows wait for the copies static const int slow_us = [] { const char* e = std::getenv("STRATA_ADAPT_OVERLAP_SLOW_US"); return e ? std::atoi(e) : 0; }(); static int slow_arg = slow_us; if (slow_us > 0) cudaLaunchHostFunc(adapt_stream, [](void* p) { std::this_thread::sleep_for(std::chrono::microseconds(*(int*) p)); }, &slow_arg); } const size_t in = (size_t) s.layer * g.n_expert + s.in, out = (size_t) s.layer * g.n_expert + s.out; const int32_t slot = fenced_slots.empty() ? host_res[out] : fenced_slots[si]; const uint8_t* b = srcp->blob_stable(s.layer, s.in); nib::guard_raw(s.layer, "the adaptive tier's copy in"); const int stn = multi_gpu ? stage_of(s.layer) : 0; // the swap stays in the layer's own cache GpuStage* gs = stn > 0 ? stages[(size_t) stn - 1].get() : nullptr; const strata::core::OnDevice on(gs ? gs->dev : -1); if (dma_mode != 0 && slot >= 0 && b != nullptr) { cp_dst.push_back(xcache.device_slot(slot)); cp_src.push_back(b); cp_bytes.push_back((size_t) strata::kernels::cpu::expert_layout().blob_bytes(s.layer)); main_live = true; host_res[out] = strata::core::kNotResident; srcp->prefetch(s.layer, s.out); pending.emplace_back((int32_t) in, slot); if (!drive.d.in_flight.empty()) drive.d.in_flight[in] = 1; // STRATA_ADAPT_FETCH leaves it alone continue; } if (slot < 0 || b == nullptr || adapt_copy_h2d(gs ? gs->cache.device_slot(slot) : xcache.device_slot(slot), b, (size_t) strata::kernels::cpu::expert_layout().blob_bytes(s.layer), gs ? gs->adapt_stream : adapt_stream) != cudaSuccess) { std::fprintf(stderr, "strata serve: adaptive swap copy failed (layer %d, slot %d, pinned %d): %s\n", (int) s.layer, (int) slot, pin_live.empty() ? 0 : 1, cudaGetErrorString(cudaGetLastError())); return false; } if (gs) gs->adapt_live = true; else main_live = true; host_res[out] = strata::core::kNotResident; // evicted now: the CPU computes it meanwhile srcp->prefetch(s.layer, s.out); // a file-backed arena released its pages: read them back ahead pending.emplace_back((int32_t) in, slot); // resident once the copy has landed if (aov && (si + 1 == swaps.size() || swaps[si + 1].layer != s.layer) && (agate.hland != nullptr ? cudaMemcpyAsync((void*) agate.hland, agate.dvals + s.layer, 4, cudaMemcpyDeviceToHost, adapt_stream) : cudaLaunchHostFunc(adapt_stream, [](void* p) { auto* t = (strata::core::AdaptGate::Tick*) p; int32_t cur = t->counter->load(std::memory_order_relaxed); while (cur < t->layer && !t->counter->compare_exchange_weak(cur, t->layer, std::memory_order_release)) {} }, &agate.ticks[(size_t) s.layer])) != cudaSuccess) { (void) cudaGetLastError(); cudaStreamSynchronize(adapt_stream); // no callback: wait here, the gate opens at once agate.landed.store((int32_t) g.n_layers, std::memory_order_release); } if (!drive.d.in_flight.empty()) drive.d.in_flight[in] = 1; // STRATA_ADAPT_FETCH leaves it alone } if (drive.d.evict_sync && !swaps.empty()) { // the evicted ones are misses now (see the pre-launch hook) for (const Swap& s : swaps) drive.d.res_dirty_idx.push_back((int32_t) (s.layer * g.n_expert + s.out)); drive.d.res_dirty = true; } if (!cp_dst.empty() && strata::core::copy_blobs(cp_dst.data(), cp_src.data(), cp_bytes.data(), cp_dst.size(), adapt_stream, dma_mode) != cudaSuccess) { std::fprintf(stderr, "strata serve: adaptive swap copy failed (batched): %s\n", cudaGetErrorString(cudaGetLastError())); return false; } if (!swaps.empty()) cudaEventRecord(adapt_ev, adapt_stream); // #2188: hand the copies and their landing signals to the GPU now. WDDM batches a stream's work until a // driver call flushes it, and the verify window only spins on the pinned int (Linux submits at once: no-op) if (aov && agate.hland != nullptr && !swaps.empty()) (void) cudaStreamQuery(adapt_stream); (void) main_live; for (auto& st : stages) if (st->adapt_live) { const strata::core::OnDevice on(st->dev); cudaEventRecord(st->adapt_ev, st->adapt_stream); } // #477: the routing counted since the start (each count adds up to 1 / (1 - --adapt-decay) over its // decays: the sum is proportional to the routing itself) - only with --expert-profile-save, else `heat` // is empty for (size_t i = 0; i < heat.size(); ++i) heat[i] += (double) drive.d.usage[i]; if (peer.valid()) { // multi-GPU: the peer takes the next most-routed CPU misses std::vector r0 = host_res; for (const auto& [i, slot] : pending) r0[(size_t) i] = slot; // swapped into the primary already std::string perr; if (!peer.adapt(drive.d.usage.data(), r0.data(), o.peer_adapt_swaps >= 0 ? o.peer_adapt_swaps : o.adapt_swaps, perr)) { std::fprintf(stderr, "strata serve: %s\n", perr.c_str()); return false; } } for (float& v : drive.d.usage) v *= o.adapt_decay; return true; }; // ---- --adapt-async 1: the asynchronous adaptive tier (opt-in; the resident RAM mode, see the checks where // the RAM copy is built). adapt() runs a whole round - choose, copy the evicted slots back with a stream sync, // copy the new experts in from the RAM copy - on a thread the decode loop joins after the draft: ~24 ms every // 4th window with ~90 swaps. Here a round moves through four steps, each started by `adapt_tick` between // windows once the previous step's copies (events) and host work (the job thread) are done: // 1. job: choose (adapt()'s rule, over snapshots of the routing counts and the residency) and copy the // evicted slots back into exchange buffers (D2H), each from the cache of the card that owns its layer; // 2. stage the exchanges and mark the evicted experts non-resident (the CPU reads them from the exchange // buffers from the next window on); job: copy the new experts in (straight from a page-locked RAM copy, // else through a pinned bounce buffer), on the owning card's refill stream; // 3. mark the new experts resident; job: move the evicted blobs into the RAM places the new ones left; // 4. flip the copy's offsets. // A slot is overwritten only after its old expert stopped being planned for the GPU (step 2, between windows, // with the device copies of the residency table uploaded as apply_pending does), and a RAM place only once its // expert is resident (step 3), so no window computes from memory that is changing. A request starts with the // round drained (adapt_tick(true)), before its prompt lends any slot. Not bit-exact run to run: which window // first computes a swapped-in expert on the GPU (which rounds differently from the CPU) depends on when its // copy lands. `j`: the swap's exchange buffer (its copy back) and bounce buffer (a_cap + j). // --pipeline-windows 2: the pipelined decode loop has windows in flight on both cards at every tick (window K+1 // on the first while the last verifies or commits K), each one waiting on this thread at every layer (its // doorbell) and planning every layer from the residency table as it is when that layer is served. There the // tier keeps two rules (a_pl_idle, set by that loop alone; unset, nothing is in flight at a tick): // - no CUDA call of the tier reaches a card while a window there waits on this thread. A copy queued to a // card whose window spins on a host flag can block in the driver until that window ends (issue #31, where // the host waited forever), and a thread blocked in the driver can hold up this one, which the window // waits for. So the job thread does host work alone (the choice, the bounce copies, the RAM moves) and // this thread queues each card's copies at that card's next gap - a moment its stage has no window in // flight (a_gap: before a window is launched there, and at every tick) - from page-locked memory only; // - a gap of a stage after a step is also the step's fence for that card: every window planned there before // the step has completed. So step 2's copies into the evicted slots (queued at a gap after step 2) // overwrite no slot a window may still read, and step 3's RAM moves wait (AState::RamFence) for a gap after // step 3 on every card whose layers exchanged (a window planned before may still pull an incoming expert // over PCIe from the RAM place its evicted one takes). The CPU's reads need no fence: the pool runs inside // the loop's service calls. // The device copies of the residency table are not uploaded meanwhile (a synchronous copy; the pipelined // verifiers publish every row whatever they say): once, when the loop has drained. The loop ticks once per // verdict (after the drafter's chain is launched) and, while a round is in flight, every 0.5 ms without // counting a window. // The arena mode (srcp == &arena_src, a_arena below): every expert is in the arena already (a pageable or // partly pinned copy that never moves), so a round has no exchange and no RAM move - choose, mark the evicted // experts non-resident, copy the new ones in, mark them resident (steps 1-3 reduced to the copy in; RamFence and // step 4 pass through). By default (STRATA_ADAPT_PICK_INLINE) the choice runs on this thread in the tick that // starts the round, and the copies in are posted in the same tick; the next tick lands them // (STRATA_ADAPT_ASYNC_WAIT: it waits for the copies rather than polling, so the window at which an expert first // runs on the GPU does not depend on timing) and a new round may start at once. The job thread's copies // read the arena (blob_at: no counter) and block it on pageable memory, never this thread; // STRATA_ADAPT_ASYNC_BATCH caps the copies in flight per tick (the copy engine is shared with the windows). // Invariant (the serial loop, and the batch loop between windows): at a tick nothing in flight reads a slot - // a window's run ends with cudaStreamSynchronize (verify.cpp), the draft is synchronous and the commit does not // read the expert cache - so a slot whose expert was marked non-resident here may be overwritten right away; // and the job thread never touches host_res or drive.d.usage (it works on the snapshots a_usage / a_res). // Anything that gives a slot to something else (kvg_ensure's quiesce, a prompt's lend) calls adapt_quiesce first. struct ASwap { int32_t layer, in, out, slot; int home; int64_t j; bool exchange; const uint8_t* from; }; struct AHome { strata::core::ExpertCache* cache; cudaStream_t stream; cudaEvent_t ev; int dev; bool used; }; enum class AState { Idle, Pick, CopyBack, SwapIn, RamFence, Commit }; AState astate = AState::Idle; std::vector aswaps; std::vector a_usage; std::vector a_res; int64_t a_win = 0, a_last = 0, a_rounds = 0, a_swapped = 0; double a_ms = 0; // wall time from a round's start to its flip, summed (the "ms/round" stat) Clock::time_point a_t0; std::atomic a_err{false}; double a_pick_ms = 0; // the arena's inline choice, summed (the stats line) strata::program::AdaptiveCopyRange a_rng; // the batch being copied in (a_copy_in), and where the next one starts std::vector ahomes; // [0] = CUDA0's cache, [k] = layer split stage k's std::unique_ptr ajob; // the arena mode (srcp == &arena_src): every expert is in the arena already, so a round is a copy in only - no // exchange buffers, no RAM moves (see a_arena below) const bool a_arena = srcp == &arena_src; // as the blocking tier's exchange buffers; the arena has none, so its rounds are as large as the blocking tier's const int64_t a_cap = a_arena ? o.adapt_swaps : std::min(o.adapt_swaps, 96); const auto a_env = [](const char* name, int def) { const char* v = std::getenv(name); return v != nullptr && *v != 0 ? std::atoi(v) : def; }; // arena only (the other modes keep their steps as they were): the choice on this thread (STRATA_ADAPT_PICK_INLINE), // the wait for the copies (STRATA_ADAPT_ASYNC_WAIT), the copies in flight per tick (STRATA_ADAPT_ASYNC_BATCH, 0 = all) const bool a_inline = a_arena && a_env("STRATA_ADAPT_PICK_INLINE", 1) != 0; const bool a_wait = a_arena && a_env("STRATA_ADAPT_ASYNC_WAIT", 1) != 0; const size_t a_batch = a_arena ? (size_t) std::max(0, a_env("STRATA_ADAPT_ASYNC_BATCH", 0)) : 0; // o.adapt_async_self (arena, one GPU, nothing explicit): the homes are set up, the job thread is created only when the // session's measurement turns the asynchronous tier on (asw_*, in the decode loop) const bool a_self = o.adapt_async_self && !o.adapt_async && a_arena && !drive.d.usage.empty() && o.adapt_every > 0; if ((o.adapt_async || a_self) && !drive.d.usage.empty() && o.adapt_every > 0 && ((src.complement_ready() && src.exchange_capacity() >= 2 * a_cap) || a_arena)) { ahomes.push_back({&xcache, adapt_stream, adapt_ev, 0, false}); for (auto& st : stages) ahomes.push_back({&st->cache, st->adapt_stream, st->adapt_ev, st->dev, false}); if (o.adapt_async) { ajob = std::make_unique(); std::fprintf(stderr, "strata serve: adaptive tier asynchronous (--adapt-async 1): up to %lld swaps per round, " "a round every %d windows%s\n", (long long) a_cap, o.adapt_every, a_arena ? " (arena: copy-in only)" : ""); } else { std::fprintf(stderr, "strata serve: adaptive tier: blocking, and the asynchronous tier is tried once the session " "shows the swaps hold the windows up (--adapt-async 0 or STRATA_ADAPT_ASYNC=0: never)\n"); } } strata::core::AdaptAsyncSelf asw; // the session's choice between the two tiers (adapt_async_default.hpp) if (a_self && !ahomes.empty()) asw.arm(); // the pipelined loop's side (see above): whether stage `st` has no window in flight; per home, the copies back // and in to queue at its next gap, the RAM fence still to pass and the gaps seen std::function a_pl_idle; std::vector a_back_due(ahomes.size(), 0), a_in_due(ahomes.size(), 0), a_ram_due(ahomes.size(), 0); std::vector a_gap_seq(ahomes.size(), 0), a_ram_mark(ahomes.size(), 0); bool a_res_dirty = false; auto a_due = [](const std::vector& v) { return std::any_of(v.begin(), v.end(), [](uint8_t b) { return b != 0; }); }; auto a_mark = [&](AHome& h) { // an event after the copies just queued on h's stream, submitted now (WDDM) const strata::core::OnDevice on(h.dev); if (cudaEventRecord(h.ev, h.stream) != cudaSuccess) a_err = true; (void) cudaStreamQuery(h.stream); h.used = true; }; auto a_pick = [&]() { // step 1's choice (host work) struct C { float gain; int32_t layer, in, out; }; std::vector all; std::vector> cand, vict; for (int64_t l = 0; l < g.n_layers; ++l) { cand.clear(); vict.clear(); const float* u = a_usage.data() + l * g.n_expert; const int32_t* r = a_res.data() + l * g.n_expert; for (int32_t e = 0; e < (int32_t) g.n_expert; ++e) { if (r[e] < 0) { if (u[e] >= 2.0f && !helper_holds(l, e)) cand.emplace_back(u[e], e); } else vict.emplace_back(u[e], e); } if (cand.empty() || vict.empty()) continue; std::sort(cand.begin(), cand.end(), [](auto& a, auto& b) { return a.first > b.first; }); const size_t nc = std::min(cand.size(), vict.size()); std::partial_sort(vict.begin(), vict.begin() + (ptrdiff_t) nc, vict.end(), [](auto& a, auto& b) { return a.first < b.first; }); for (size_t i = 0; i < nc; ++i) { if (cand[i].first < vict[i].first + o.adapt_min_gain) break; all.push_back({cand[i].first - vict[i].first, (int32_t) l, cand[i].second, vict[i].second}); } } std::sort(all.begin(), all.end(), [](const C& a, const C& b) { return a.gain > b.gain; }); aswaps.clear(); for (const C& c : all) { if ((int64_t) aswaps.size() >= a_cap) break; const int32_t slot = a_res[(size_t) c.layer * g.n_expert + c.out]; if (slot < 0) continue; // an exchange (as resident_stage_swaps): `in` from the RAM copy, `out` held by its slot alone takes its // place there; otherwise `out` is in the copy already (the lend region) or `in` is not (a RAM budget) const bool x = !a_arena && src.has_resident(c.layer, c.in) && !src.has_resident(c.layer, c.out); aswaps.push_back({c.layer, c.in, c.out, slot, multi_gpu ? stage_of(c.layer) : 0, (int64_t) aswaps.size(), x, nullptr}); } }; auto a_back = [&](int hi) { // step 1's copies back (D2H) from home hi's cache, then its event AHome& h = ahomes[(size_t) hi]; bool any = false; { const strata::core::OnDevice on(h.dev); for (const ASwap& w : aswaps) { if (w.home != hi || !w.exchange) continue; nib::guard_raw(w.layer, "the async adaptive tier's copy back (a_back)"); if (const cudaError_t e = cudaMemcpyAsync(src.exchange_buffer(w.j, w.layer), h.cache->device_slot(w.slot), (size_t) strata::kernels::cpu::expert_layout().blob_bytes(w.layer), cudaMemcpyDeviceToHost, h.stream); e != cudaSuccess) { std::fprintf(stderr, "strata serve: adaptive tier: copy back of layer %d slot %d (CUDA%d) failed: %s\n", (int) w.layer, (int) w.slot, h.dev, cudaGetErrorString(e)); a_err = true; } any = true; } } if (any) a_mark(h); }; auto a_from = [&](const ASwap& w) -> const uint8_t* { // step 2: where `in` is copied from (host work) if (a_arena) { // the arena's blob, pinned or not (a pageable one blocks the job thread, not the host) const uint8_t* b = arena_src.blob_at(w.layer, w.in); // (blob() counts reads_: not from this thread) if (b == nullptr) { std::fprintf(stderr, "strata serve: adaptive tier: layer %d expert %d is not in the arena\n", (int) w.layer, (int) w.in); a_err = true; } return b; } if (src.pinned(w.layer, w.in)) if (const uint8_t* b = src.resident_blob(w.layer, w.in)) return b; // pageable, or not in the RAM copy: through a bounce buffer (an async copy) uint8_t* bb = src.exchange_buffer(a_cap + w.j); if (bb == nullptr || !src.copy_blob(w.layer, w.in, bb)) { std::fprintf(stderr, "strata serve: adaptive tier: layer %d expert %d could not be read\n", (int) w.layer, (int) w.in); a_err = true; return nullptr; } return bb; }; auto a_in_one = [&](const ASwap& w, const uint8_t* b) { // step 2: one copy in (H2D), on its home's stream AHome& h = ahomes[(size_t) w.home]; const strata::core::OnDevice on(h.dev); nib::guard_raw(w.layer, "the async adaptive tier's copy in (a_in_one)"); if (const cudaError_t e = cudaMemcpyAsync(h.cache->device_slot(w.slot), b, (size_t) strata::kernels::cpu::expert_layout().blob_bytes(w.layer), cudaMemcpyHostToDevice, h.stream); e != cudaSuccess) { std::fprintf(stderr, "strata serve: adaptive tier: copy of layer %d into slot %d (CUDA%d) failed: %s\n", (int) w.layer, (int) w.slot, h.dev, cudaGetErrorString(e)); a_err = true; } }; auto a_choose = [&]() { // step 1 on the job thread (the serial loop) a_pick(); for (AHome& h : ahomes) h.used = false; for (size_t hi = 0; hi < ahomes.size(); ++hi) a_back((int) hi); }; auto a_copy_in = [&]() { // step 2 on the job thread (the serial loop): each source read, then copied in std::vector used(ahomes.size(), 0); for (size_t i = a_rng.lo; i < a_rng.hi; ++i) { // (the batch; all the round's swaps unless the arena caps it) const ASwap& w = aswaps[i]; if (const uint8_t* b = a_from(w)) { a_in_one(w, b); used[(size_t) w.home] = 1; } } for (size_t hi = 0; hi < ahomes.size(); ++hi) if (used[hi]) a_mark(ahomes[hi]); }; auto a_post_batch = [&]() { // step 2: the next batch of copies in goes to the job thread (all of them but for the arena's cap) a_rng.next_batch(aswaps.size(), a_batch); ajob->post(a_copy_in); }; auto a_stage_in = [&]() { // step 2's host part on the job thread (the pipelined loop: a_in queues the copies) for (ASwap& w : aswaps) w.from = a_from(w); }; auto a_in = [&](int hi) { // step 2's copies in to home hi (the pipelined loop, at its gap) bool any = false; for (const ASwap& w : aswaps) if (w.home == hi && w.from != nullptr) { a_in_one(w, w.from); any = true; } if (any) a_mark(ahomes[(size_t) hi]); }; auto a_ready = [&](bool wait) -> bool { // the job and its copies are done if (wait) ajob->wait(); else if (!ajob->idle()) return false; for (AHome& h : ahomes) if (h.used) { const strata::core::OnDevice on(h.dev); if (wait) { if (cudaEventSynchronize(h.ev) != cudaSuccess) a_err = true; } else if (const cudaError_t q = cudaEventQuery(h.ev); q == cudaErrorNotReady) return false; else if (q != cudaSuccess) a_err = true; } return true; }; // --pipeline-windows 2: stage `st` has no window in flight (see above) - the copies due on its card are queued // now, and the steps taken before are fenced for it. On the loop's thread. auto a_gap = [&](int st) { if (!a_pl_idle || st < 0 || st >= (int) ahomes.size() || !a_pl_idle(st)) return; ++a_gap_seq[(size_t) st]; if (a_back_due[(size_t) st]) { a_back_due[(size_t) st] = 0; a_back(st); } if (a_in_due[(size_t) st] && ajob->idle()) { // once the job has read the sources a_in_due[(size_t) st] = 0; a_in(st); } }; auto a_picked = [&]() { // (pipelined) step 1's choice is made: each card's copies back at its next gap for (AHome& h : ahomes) h.used = false; for (const ASwap& w : aswaps) if (w.exchange) a_back_due[(size_t) w.home] = 1; astate = AState::CopyBack; for (int st = 0; st < (int) ahomes.size(); ++st) a_gap(st); }; // between windows: `drain` finishes the round in flight and starts none; `count` false (the pipelined loop // between verdicts) moves it on without counting a window. False when a copy failed. auto adapt_tick = [&](bool drain, bool count = true) -> bool { if (!ajob) return true; if (!drain && count) ++a_win; // one tick per window const bool pl = (bool) a_pl_idle; if (pl) for (int st = 0; st < (int) ahomes.size(); ++st) a_gap(st); for (;;) { if (a_err.load()) return false; switch (astate) { case AState::Idle: if (drain || a_win - a_last < (int64_t) o.adapt_every) return true; a_last = a_win; ++a_rounds; a_t0 = Clock::now(); a_usage = drive.d.usage; a_res = host_res; // #477: the routing counted, as adapt() counts it (--expert-profile-save; else `heat` is empty) for (size_t i = 0; i < heat.size(); ++i) heat[i] += (double) drive.d.usage[i]; for (float& v : drive.d.usage) v *= o.adapt_decay; if (a_inline) { // the arena: choose here (no copy back to wait for), then straight on to step 2 const Clock::time_point tp0 = Clock::now(); a_pick(); a_pick_ms += std::chrono::duration(Clock::now() - tp0).count(); for (AHome& h : ahomes) h.used = false; astate = AState::CopyBack; continue; } if (pl) { ajob->post(a_pick); astate = AState::Pick; } else { ajob->post(a_choose); astate = AState::CopyBack; } return true; case AState::Pick: // (pipelined) step 1: the copies back wait for the choice, then for their card's gap if (!ajob->idle()) { if (!drain) return true; ajob->wait(); } a_picked(); continue; case AState::CopyBack: { // step 2: the evicted experts leave the GPU's plan if (a_due(a_back_due)) return true; // (pipelined) a card not seen idle since the choice if (!a_ready(drain)) return true; if (a_err.load()) return false; size_t k = 0; for (size_t i = 0; i < aswaps.size(); ++i) { const ASwap w = aswaps[i]; const size_t out = (size_t) w.layer * g.n_expert + w.out; if (host_res[out] != w.slot) continue; // the table moved since the snapshot: not this one if (w.exchange && !src.stage_exchange(w.layer, w.in, w.out, w.j)) { std::fprintf(stderr, "strata serve: adaptive tier: stage_exchange refused layer %d in %d out %d\n", (int) w.layer, (int) w.in, (int) w.out); return false; } host_res[out] = strata::core::kNotResident; // the CPU computes it from the next window on srcp->prefetch(w.layer, w.out); aswaps[k++] = w; } aswaps.resize(k); if (aswaps.empty()) { // nothing to move (converged, or the table moved since the snapshot): the round ends here a_ms += std::chrono::duration(Clock::now() - a_t0).count(); astate = AState::Idle; continue; } for (AHome& h : ahomes) h.used = false; if (pl) { // the copies in at each card's next gap: after this step, so fenced (see above) a_res_dirty = true; for (const ASwap& w : aswaps) a_in_due[(size_t) w.home] = 1; // the whole round is one batch: when the pipelined loop drains before step 3, the next tick // takes step 3 on the serial rule and marks [lo, hi), which an earlier round left otherwise a_rng.whole_round(aswaps.size()); ajob->post(a_stage_in); } else { res_upload(); a_rng.clear(); a_post_batch(); } astate = AState::SwapIn; if (!drain) return true; continue; } case AState::SwapIn: // step 3: the new experts are in their slots if (a_due(a_in_due)) return true; // (pipelined) a card not seen idle since step 2 if (!a_ready(drain || a_wait)) return true; if (a_err.load()) return false; for (size_t i = a_rng.landed_begin(pl); i < a_rng.landed_end(pl, aswaps.size()); ++i) { // (the batch just landed) const ASwap& w = aswaps[i]; host_res[(size_t) w.layer * g.n_expert + w.in] = w.slot; srcp->release(w.layer, w.in); } if (pl) a_res_dirty = true; else res_upload(); a_swapped += (int64_t) (a_rng.landed_end(pl, aswaps.size()) - a_rng.landed_begin(pl)); if (!pl && a_rng.more(aswaps.size())) { // the arena's cap: the next batch goes now for (AHome& h : ahomes) h.used = false; a_post_batch(); if (!drain) return true; continue; } if (pl) // the RAM moves wait for a gap after this step on every card whose layers exchanged for (const ASwap& w : aswaps) if (w.exchange) { a_ram_due[(size_t) w.home] = 1; a_ram_mark[(size_t) w.home] = a_gap_seq[(size_t) w.home]; } astate = AState::RamFence; continue; case AState::RamFence: // step 3's RAM moves, once no window may still read the places they fill if (a_arena) { // no RAM copy to move astate = AState::Commit; continue; } if (pl) for (size_t hi = 0; hi < ahomes.size(); ++hi) if (a_ram_due[hi] && a_gap_seq[hi] <= a_ram_mark[hi]) return true; std::fill(a_ram_due.begin(), a_ram_due.end(), (uint8_t) 0); astate = AState::Commit; if (src.exchange_rotation()) continue; // STRATA_EXCHANGE_ROTATE: no bytes move, the flip is all there is ajob->post([&] { src.commit_copies(); }); if (!drain) return true; continue; case AState::Commit: // step 4 if (!a_ready(drain)) return true; if (a_err.load()) return false; if (!a_arena) src.commit_flip(); a_ms += std::chrono::duration(Clock::now() - a_t0).count(); aswaps.clear(); astate = AState::Idle; continue; // a round due now starts at this same boundary } } }; // kvg_ensure's `quiesce` (and any caller about to give cache slots away): nothing runs on the device, the blocking // tier's swaps have landed AND the asynchronous round in flight is finished - a swap still copying could write a // slot the K/V is lent. A failed refill is surfaced as ERR at the next tick (a_err). auto adapt_quiesce = [&] { cudaDeviceSynchronize(); apply_pending(true); if (!adapt_tick(true)) { // a failed round still has copies in flight: they land before any slot moves a_err = true; if (ajob) ajob->wait(); cudaDeviceSynchronize(); } }; // --pipeline-windows 2: the loop has drained (nothing in flight on either card): what waits for a gap goes now, // and the round in flight goes on unfenced (a_pl_idle unset) from the next tick, the next request's drain. The // job's work is the host's alone, so the wait for it ends. auto a_pl_settle = [&]() { if (!ajob || !a_pl_idle) return; ajob->wait(); bool idle = true; for (int st = 0; st < (int) ahomes.size(); ++st) idle = idle && a_pl_idle(st); if (idle) { if (astate == AState::Pick) a_picked(); for (int st = 0; st < (int) ahomes.size(); ++st) a_gap(st); if (a_res_dirty) res_upload(); } else { // the loop did not drain (a window failed): the round cannot go on, the next tick says so std::fprintf(stderr, "strata serve: adaptive tier: a window is still in flight after the pipelined loop\n"); a_err = true; } a_pl_idle = nullptr; a_res_dirty = false; }; // #477: write the learned profile (between requests and at QUIT: a prompt's lent slots are back by then). // A swap still in flight counts as done - its expert is resident once the copy lands. `why`: for the log. auto save_profile = [&](const char* why) { if (heat.empty()) return; std::vector resident(host_res.size(), 0); for (size_t i = 0; i < host_res.size(); ++i) resident[i] = host_res[i] >= 0; for (const auto& p : pending) resident[(size_t) p.first] = 1; if (astate == AState::SwapIn) // --adapt-async: the same for a round past its step 2 for (const ASwap& w : aswaps) resident[(size_t) w.layer * g.n_expert + w.in] = 1; std::string e; const auto ranked = strata::core::rank_learned_profile(g.n_layers, g.n_expert, resident, heat, profile_loaded); if (strata::core::write_expert_profile(o.expert_profile_save, g.n_layers, g.n_expert, ranked, e)) std::fprintf(stderr, "strata serve: expert profile saved to %s (%s)\n", o.expert_profile_save.c_str(), why); else std::fprintf(stderr, "strata serve: the expert profile was not saved: %s\n", e.c_str()); profile_saved_at = Clock::now(); }; // --ram-profile-save: the RAM copy as --ram-adapt left it first, then by its counts, then the ranking it started from auto save_ram_profile = [&](const char* why) { if (o.ram_profile_save.empty() || drive.d.usage.empty() || !src.complement_ready()) return; std::vector in_ram(drive.d.usage.size(), 0); std::vector counts(drive.d.usage.size(), 0.0); for (int64_t l = 0; l < g.n_layers; ++l) for (int64_t e = 0; e < g.n_expert; ++e) { const size_t i = (size_t) (l * g.n_expert + e); in_ram[i] = src.has_resident(l, e) ? 1 : 0; counts[i] = (double) drive.d.usage[i]; } const auto& prior = !ram_rank.empty() ? ram_rank : profile_all.empty() ? profile : profile_all; std::string e; const auto ranked = strata::core::rank_learned_profile(g.n_layers, g.n_expert, in_ram, counts, prior); if (strata::core::write_expert_profile(o.ram_profile_save, g.n_layers, g.n_expert, ranked, e)) std::fprintf(stderr, "strata serve: RAM profile saved to %s (%s)\n", o.ram_profile_save.c_str(), why); else std::fprintf(stderr, "strata serve: the RAM profile was not saved: %s\n", e.c_str()); }; // stdin is read on its own thread, so a STOP line reaches a request that is still running (the client went // away, or pressed Esc): the flag is checked between prompt chunks and between verify windows. // 0.1.44: the reader is detached and may sit in read(2) past QUIT (the server writes more, or closes stdin, while // main returns and the process exits), so what it touches is shared with it, never main's locals: a line or // EOF after QUIT used to lock a destroyed mutex (undefined behaviour; an abort on macOS). struct StdinShared { std::atomic stop_req{false}; std::mutex mu; std::condition_variable cv; std::deque lines; bool eof = false; }; const auto in_shared = std::make_shared(); std::atomic& stop_req = in_shared->stop_req; std::mutex& in_mu = in_shared->mu; std::condition_variable& in_cv = in_shared->cv; std::deque& in_lines = in_shared->lines; bool& in_eof = in_shared->eof; std::thread([st = in_shared] { strata::platform::name_this_thread("strata-stdin"); strata::aux_cpus::pin_current_thread(); // read(2) on the descriptor, not std::cin: glibc's exit() flushes every stdio stream and waits for // stdin's lock, which getline holds while it waits for input - an engine ending on an error (every // std::exit) would hang in exit() on Linux, and the server would wait for it forever std::string l, buf; char chunk[4096]; auto getline_fd = [&](std::string& out) -> bool { for (;;) { const size_t nlpos = buf.find('\n'); if (nlpos != std::string::npos) { out.assign(buf, 0, nlpos); buf.erase(0, nlpos + 1); return true; } #if defined(_WIN32) const int n = _read(0, chunk, (unsigned) sizeof chunk); #else const ssize_t n = ::read(0, chunk, sizeof chunk); if (n < 0 && errno == EINTR) continue; #endif if (n <= 0) { if (buf.empty()) return false; out.swap(buf); buf.clear(); return true; } buf.append(chunk, (size_t) n); } }; while (getline_fd(l)) { if (!l.empty() && l.back() == '\r') l.pop_back(); if (l == "STOP") { st->stop_req.store(true); continue; } std::lock_guard lk(st->mu); st->lines.push_back(l); st->cv.notify_one(); } std::lock_guard lk(st->mu); st->eof = true; st->cv.notify_one(); }).detach(); auto next_line = [&](std::string& out) -> bool { std::unique_lock lk(in_mu); in_cv.wait(lk, [&] { return !in_lines.empty() || in_eof; }); if (in_lines.empty()) return false; out = std::move(in_lines.front()); in_lines.pop_front(); return true; }; sp.should_stop = [&] { return stop_req.load(); }; #if defined(STRATA_USE_HIP) && defined(__linux__) kfdq_exit::g_stop.store(&stop_req); // EXIT (kfd_quiet.hpp): a signal ends the running request like STOP (nothing without the handler) #endif // 149-prefetch STRATA_RAM_ADAPT2: the prompt's routing seeds the RAM policy with a limited weight // (STRATA_RAM_ADAPT_PROMPT_W, default 0.25: an expert every prompt token routes to counts like ~5 decode routings), // fading by 5% a decode window; the decode's own counts and the GPU tier are untouched if (ram_adapt2.on && ram_adapt2.prompt_w > 0.0f) { ram_adapt2.seed.assign((size_t) (g.n_layers * g.n_expert), 0.0f); sp.on_routes = [&](int64_t l, const int32_t* ids, int64_t n) { if (l < 0 || l >= g.n_layers || n <= 0) return; const float per = ram_adapt2.prompt_w * 20.0f * (float) g.n_expert_used / (float) n; // = w x 20 / tokens float* sd = ram_adapt2.seed.data() + l * g.n_expert; for (int64_t i = 0; i < n; ++i) if (ids[i] >= 0 && ids[i] < g.n_expert) sd[ids[i]] += per; }; } // STRATA_TRACE=1: one stderr line per step of a request (the log shows where a request stops) const bool trace = std::getenv("STRATA_TRACE") != nullptr; auto tr = [&](const char* what, long long a = -1, long long b = -1) { if (!trace) return; static Clock::time_point t0; // process-wide: the stages run on different threads static bool t0_set = false; if (!t0_set) { t0 = Clock::now(); t0_set = true; } const double ms = std::chrono::duration(Clock::now() - t0).count(); std::fprintf(stderr, "strata trace: %s %lld %lld %.1f ms\n", what, a, b, ms); std::fflush(stderr); }; { // what is left once everything is allocated: under WDDM a GPU filled to the brim does not fail, it pages - // and a page-in while the verify graph spins on a host flag stalls the request for good size_t free_b = 0, total_b = 0; cudaMemGetInfo(&free_b, &total_b); // STRATA_VRAM_FREE=device: the whole card's figure when it is the smaller one (the same value otherwise) free_b = std::min(free_b, strata::core::device_free_bytes()); // below ~256 MiB a later allocation (a first-used window's buffers, the desktop, another program) can make // the driver page GPU memory, and a verify graph spinning on a host flag then never finishes const int64_t free_mib = (int64_t) (free_b >> 20); if (free_mib >= 256) { std::fprintf(stderr, "strata serve: %lld MiB of VRAM free with everything loaded\n", (long long) free_mib); #ifdef _WIN32 if (free_mib < 512 && o.prefill_auto) // #1275: said, never changed (the chunk is the operator's to cap) std::fprintf(stderr, "strata serve: that is little room for the verify windows' buffers under WDDM; if the " "engine exits right after this line, --prefill auto:8192 (a smaller prompt chunk " "borrows fewer cache slots) or a larger --vram-reserve-mib leaves more\n"); #endif rss_probe("serving"); } else if (reserve_adapted) { // #496: the reserve was already lowered to make the cache fit - a bigger one would leave it no room std::fprintf(stderr, "strata serve: WARNING: %lld MiB of VRAM free with everything loaded - this card " "only just fits the model (the VRAM reserve was lowered to %d MiB so the expert " "cache fits): requests may stall. Close other programs that use the GPU, or lower " "--max-context\n", (long long) free_mib, o.vram_reserve_mib); } else if (g_uma_pinned_complement.load()) { // Round 0216: said plainly, no reserve advice (a larger --vram-reserve-mib does not raise this figure here) std::fprintf(stderr, "strata serve: %lld MiB of graphics memory reported free. On this PC the graphics chip shares the system " "memory, so this figure reads low, and a larger --vram-reserve-mib won't raise it. If decode drops to a " "few tok/s, lower --max-context.\n", (long long) free_mib); } else { std::fprintf(stderr, "strata serve: %lld MiB of VRAM free with everything loaded - LOW: requests may stall;" " add --vram-reserve-mib %lld to the config's args (or lower --max-context)\n", (long long) free_mib, (long long) (o.vram_reserve_mib + 512 - free_mib)); // #781 / #831: an explicit --expert-cache N is a byte budget that is not checked against the VRAM once // the slots are written (auto is), so on a card it fills a smaller N is the cure: a few hundred slots // can be the difference between 14 and 100 tok/s under WDDM. Said, never changed. if (!auto_cache) std::fprintf(stderr, "strata serve: the expert cache was set with --expert-cache (%lld slots): a " "smaller one - or --expert-cache auto, which checks the free VRAM once the " "slots are written - leaves room; decode can be several times slower with the " "card this full\n", (long long) xcache.slots()); } // #2192: the same check on a layer split's later cards. The line above reads CUDA0 alone: on 2x RTX 2080 Ti // (WDDM, --batch 4) CUDA0 had 740 MiB free while CUDA1 started its window captures at 153 MiB and fell to // 52, and the first batch window on it never finished (the host stuck in cudaGraphLaunch: a page-in while the // other card's graph spins on a host flag). Said, never changed. for (const auto& stp : stages) { const strata::core::OnDevice on(stp->dev); size_t sf = 0, stot = 0; if (cudaMemGetInfo(&sf, &stot) != cudaSuccess) { (void) cudaGetLastError(); continue; } const int64_t sf_mib = (int64_t) (sf >> 20); const int later_reserve = o.vram_reserve_later_mib >= 0 ? o.vram_reserve_later_mib : o.vram_reserve_mib; if (sf_mib >= 512) std::fprintf(stderr, "strata serve: CUDA%d: %lld MiB of VRAM free with everything loaded\n", stp->dev, (long long) sf_mib); else std::fprintf(stderr, "strata serve: CUDA%d: %lld MiB of VRAM free with everything loaded - LOW: its window " "graphs are captured on first use and need room too, and %s; add " "--vram-reserve-later-mib %lld to the config's args (or lower --max-context)\n", stp->dev, (long long) sf_mib, #ifdef _WIN32 "under WDDM a full card pages instead of failing, which can stall a request for good (#2192)", #else "a full card can stall a request", #endif (long long) (later_reserve + 768 - sf_mib)); if (sf_mib < 512) { // #3702: how far the plan was off, so the reserve to ask for is not a guess strata::program::stage_reserve::Inputs rin; rin.base_reserve_mib = later_reserve; rin.prompt_buffers_mib = split_pf_mib; rin.later = true; rin.pipe_window_mib = kPipeWindowMib; const std::string why = strata::program::gpu_report::planned_vs_free_text( strata::program::stage_reserve::reserve_mib(rin), sf_mib); if (!why.empty()) std::fprintf(stderr, "strata serve: CUDA%d: %s\n", stp->dev, why.c_str()); } } } // what the server's Monitor tab shows (servers before 0.1.8 skip unknown lines until READY) { size_t free_b = 0, total_b = 0; cudaMemGetInfo(&free_b, &total_b); // "Experts in VRAM" is every tier, not one card's. This used to report `xcache` alone, so a layer split // showed CUDA0's cache as if it were the whole GPU's: a 4-GPU 256K run read 3327 experts when the four // cards held 13320, and the Monitor tab was wrong by 4x for every multi-GPU config. The tiers are // disjoint by construction (remote_experts.cpp skips any pair a stage already claimed), so they add. const int64_t slots_primary = (int64_t) xcache.slots(); const int64_t mib_primary = (int64_t) (xcache.bytes() >> 20); int64_t slots_all = slots_primary, mib_all = mib_primary; for (const auto& st : stages) { slots_all += (int64_t) st->cache.slots(); mib_all += (int64_t) (st->cache.bytes() >> 20); } for (int r = 0; r < 3; ++r) if (o.expert_cache_remote[(size_t) r] > 0) { slots_all += remote_experts[(size_t) r].resident(); mib_all += (int64_t) (remote_experts[(size_t) r].gib() * 1024.0); } std::printf("INFO logit_bias=1 context=%lld kv=%s kv_resident=%lld expert_slots=%lld expert_cache_mib=%lld " "expert_slots_primary=%lld expert_cache_primary_mib=%lld spec=%d " "mtp_max=%d lookup=%d vram_free_mib=%lld cvec=%s arena_mib=%lld pool_workers=%d pcie_frac=%.2f " "spec_min_p=%.2f conversation_cache_mib=%lld conversation_cache_slots=%d " "conversation_cache_min_free_mib=%lld conversation_cache_min_tokens=%lld " "tail_role_token=%lld vram_elastic=%d " "prefill_cap=%lld prefill_stages=%d stream_all_min=%lld prefill_pipe=%g%s engine=" STRATA_VERSION "\n", (long long) o.max_context, o.kv.c_str(), (long long) (g.n_qsa_layers() > 0 && ss.qsa_states[ss.qsa_primary()].kv_mode == 1 ? ss.qsa_states[ss.qsa_primary()].n_slots * 4 : 0), (long long) slots_all, (long long) mib_all, (long long) slots_primary, (long long) mib_primary, o.spec, o.mtp_max_t, o.suffix_draft, (long long) (free_b >> 20), cvec_summary.c_str(), (long long) ((o.mmap_experts ? src.resident_bytes() : strata::kernels::cpu::expert_layout().total) >> 20), pool.workers(), o.pcie_frac, o.spec_min_p, (long long) o.conversation_cache_mib, o.conversation_cache_slots, (long long) o.conversation_cache_min_free_mib, (long long) o.conversation_cache_min_tokens, (long long) o.tail_role_token, xcache.segmented() ? 1 : 0, // the prompt path: its chunk cap (the VRAM command's relend can lower it later), the stages a // prompt flows through, the chunk size from which a chunk streams every expert, --prefill-pipe (long long) o.prefill_chunk, sp.stage_count(), (long long) strata::prefill::Prefill::stream_all_min_tokens(), strata::prefill::Prefill::pipe_setting(), o.batch > 0 ? (" batch_slots=" + std::to_string(o.batch) + " slot_cache=" + std::to_string(o.prompt_cache > 0 ? 1 : 0) + " batch_groups=" + std::to_string(o.batch_groups)).c_str() : ""); if (strata::core::manifest::enabled()) { // STRATA_MANIFEST: engine choice and budgets (a diagnostic; off by default) auto& M = strata::core::manifest::instance(); M.engine("version", STRATA_VERSION); M.engine("engine", stages.empty() ? "native-single-gpu" : "native-layer-split"); M.engine("stages", std::to_string(stages.size() + 1)); M.engine("kv_format", o.kv); M.engine("drafter", !o.mtp.empty() ? "mtp" : "none-or-lookup"); M.engine("spec_window", std::to_string(o.spec)); M.engine("pipeline_windows", std::to_string(o.pipeline_windows)); M.engine("ple_io", o.ple_io); M.engine("expert_cache_request", o.expert_cache < 0 ? "auto" : std::to_string(o.expert_cache)); M.budget("max_context", (int64_t) o.max_context); M.budget("kv_resident_cells", (int64_t) o.kv_resident); M.budget("expert_slots_all", slots_all); M.budget("expert_cache_all_mib", mib_all); M.budget("expert_slots_primary", slots_primary); M.budget("expert_cache_primary_mib", mib_primary); M.budget("vram_reserve_mib", (int64_t) o.vram_reserve_mib); M.budget("prefill_chunk_cap", (int64_t) o.prefill_chunk); M.budget("prefill_stages", (int64_t) sp.stage_count()); M.budget("pool_workers", (int64_t) pool.workers()); M.budget("memory_limit_mib", (int64_t) o.memory_limit_mib); M.budget("resident_budget_bytes", (int64_t) o.resident_budget); M.budget("batch_slots", (int64_t) o.batch); M.budget("conversation_cache_mib", (int64_t) o.conversation_cache_mib); M.path("decode", "route-tail-skip", std::getenv("STRATA_ROUTE_TAIL_SKIP") == nullptr || std::getenv("STRATA_ROUTE_TAIL_SKIP")[0] != '0', std::getenv("STRATA_ROUTE_TAIL_SKIP") == nullptr ? "STRATA_ROUTE_TAIL_SKIP not set: the engine default applies (it skips tails only where the configuration allows)" : (std::string("STRATA_ROUTE_TAIL_SKIP=") + std::getenv("STRATA_ROUTE_TAIL_SKIP"))); M.path("transfer", "dma-batch", strata::core::dma_batch_mode() != 0, strata::core::dma_batch_mode() != 0 ? "STRATA_DMA_BATCH" : "mode 0: one copy per expert (the default loop)", std::string("mode ") + std::to_string(strata::core::dma_batch_mode())); } } // issue #29: a request whose heartbeat (tokens, prompt chunks, verify windows) stops for this long is stuck on // a flag nobody will raise - end the engine with where it was, so the server starts it again instead of the // GPU spinning forever. STRATA_WATCHDOG_S=0 turns it off. Issue #31: before it does, it reports what every // part was doing (stall_report), so one occurrence says where the wait is. { const char* ws = std::getenv("STRATA_WATCHDOG_S"); const int limit = ws ? std::atoi(ws) : 60; // one step (a prompt layer, a verify window) takes seconds // #1407: while the OS is still reading the file tier (major faults / bytes read advance), a silent step is // slow, not stuck; it gets up to STRATA_WATCHDOG_IO_S (default 10 x the limit) of such time. 0 = no allowance. const char* wio = std::getenv("STRATA_WATCHDOG_IO_S"); const int io_limit = wio ? std::atoi(wio) : limit * 10; if (limit > 0) std::thread([limit, io_limit] { strata::platform::name_this_thread("strata-watchdog"); strata::aux_cpus::pin_current_thread(); strata::core::Progress& p = strata::core::progress(); uint64_t last = p.beats.load(), ticks_at = p.ticks.load(); auto since = std::chrono::steady_clock::now(); auto io_since = since; uint64_t io_last = file_tier_activity(); auto io_active_at = since; // the last second the file tier was busy bool io_noted = false; for (;;) { std::this_thread::sleep_for(std::chrono::seconds(1)); const auto now = std::chrono::steady_clock::now(); const uint64_t b = p.beats.load(); if (!p.busy.load() || b != last) { last = b; ticks_at = p.ticks.load(); since = now; io_since = now; io_active_at = now; io_noted = false; io_last = file_tier_activity(); continue; } { // sampled every second, also during the first `limit` seconds, so a busy file tier is seen const uint64_t a = file_tier_activity(); if (a >= io_last + 16) io_active_at = now; // 16 = faults + MiB read in a second: busy io_last = a; } if (now - since < std::chrono::seconds(limit)) continue; if (io_limit > limit && now - io_since < std::chrono::seconds(io_limit)) { // a thrashing host has seconds with almost no reads (one thread waiting on one page while // swap is written): busy within the last 10 s still counts as slow, not stuck (P2003, 46 GB) if (now - io_active_at < std::chrono::seconds(10)) { if (!io_noted) { io_noted = true; std::fprintf(stderr, "strata serve: no step finished for %d s, but the file tier is still being read " "(slow storage or low RAM): waiting up to %d s in all (STRATA_WATCHDOG_IO_S) (#1407)\n", limit, io_limit); } continue; } } // a blocking step's explicit allowance (session files): still within it, not yet stuck if (strata::core::progress_now_ms() < p.allow_until_ms.load()) continue; std::fprintf(stderr, "strata serve: no progress for %d s during a request (%s) - stopping " "the engine so the server starts it again (issue #29)%s\n", limit, stage_text().c_str(), launch_blocking() ? "; CUDA_LAUNCH_BLOCKING=1 is set, and no verify window can " "finish with it (#1341)" : ""); stall_report(stderr, p.ticks.load() - ticks_at); strata::core::release_gpu_waits(stderr); // #267: no spin kernel outlives the process std::fflush(stderr); std::abort(); } }).detach(); } strata::core::pin_sim_report("at READY"); strata::core::pin_reserve_release_hard(); // the load is over: nothing else needs the headroom #if defined(STRATA_USE_HIP) && defined(__linux__) // integrated gfx11 (kfd_quiet.hpp, LOAD): one staged copy each way on the null stream (the stream of the lent refill and of // the cache's blocking fills), from and into pageable memory, so that the runtime makes its staging buffer and copy path now, // before the settle below, and not inside the first request (p2006: +10-15 MiB of GTT in 3-5 steps there, every mode). The // device buffer is kept for the run (a free later would be one more driver event); nothing reads it. Failures are ignored. if (strata::core::kfd_quiet::load_moves().staged_copy_warm) { static void* warm_dev = nullptr; const size_t wn = strata::core::kfd_quiet::kStagedWarmBytes; if (warm_dev == nullptr && cudaMalloc(&warm_dev, wn) != cudaSuccess) warm_dev = nullptr; if (warm_dev != nullptr) { std::vector wh(wn, 0); if (cudaMemcpy(warm_dev, wh.data(), wn, cudaMemcpyHostToDevice) == cudaSuccess) (void) cudaMemcpy(wh.data(), warm_dev, wn, cudaMemcpyDeviceToHost); } (void) cudaGetLastError(); if (std::getenv("STRATA_TRACE") != nullptr) std::fprintf(stderr, "strata trace: kfd quiet: staged copy before READY %s\n", warm_dev != nullptr ? "done" : "skipped (no device memory)"); } #endif strata::core::kfd_settle::settle_before_ready(); // integrated gfx11 under Linux: until the kernel has stopped moving the registered arena (nothing elsewhere) strata::core::manifest::instance().write("ready"); // STRATA_MANIFEST (a no-op unless it is set) // ---- window warm-up (lane DRAFT-COSTS): the first run of a window width builds its graph / pipeline (srv118 CUDA: a capture; Metal: the first execution), so a // width that the policy first picks inside a long request pays it there (M5 Max, IQ3_S: +60 ms on the first five-row lookup round, in the timed code request in 5 of 8 launches // with a table, because the release and the live costs happen to pay it in request 1). One dummy window per allowed width 1..S, once, before the first request is read; it // changes nothing a request can see: the windows write K/V cells 0..T-1 and the recurrent state of the session, and session_zero() below zeroes the session exactly as a request // that reuses nothing does (the engine's state after session_init); no checkpoint, conversation entry, RNG draw, policy sample or statistic is touched (the policy's observe_* // calls live in the decode loop); the expert cache may page in what the dummy token routes to (speed only). STRATA_WINDOW_WARM=0: off (research switch). { static const bool warm_off = [] { const char* v = std::getenv("STRATA_WINDOW_WARM"); return v != nullptr && v[0] == '0'; }(); if (!warm_off && o.spec >= 2 && n_stages == 1 && o.batch <= 0) { const Clock::time_point w0 = Clock::now(); std::vector wtok((size_t) o.spec, 1), wout((size_t) o.spec + 1, 0); std::string werr, wlist; bool wok = true; for (int t = 1; t <= o.spec && wok; ++t) { if (!((lookup_size_mask(o) >> t) & 1u)) continue; bool no_vram = false; if (!ver.prepare(t, no_vram, werr)) { if (no_vram) continue; wok = false; break; } // CUDA / HIP: the graph now (a size that finds no VRAM is left to the runtime rule); Metal: nothing to do const Clock::time_point t0 = Clock::now(); drive.d.layers = 0; drive.d.experts = 0; drive.d.failed = false; wok = ver.run(t, wtok.data(), 0, win_pool_fn, win_pool_user, wout.data(), werr) && !drive.d.failed; char wb[48]; std::snprintf(wb, sizeof wb, "%s%d:%.0f", wlist.empty() ? "" : " ", t, std::chrono::duration(Clock::now() - t0).count()); wlist += wb; } strata::core::session_zero(ss, g, nullptr, main_cs); cudaStreamSynchronize(main_stream); drive.d.layers = 0; drive.d.experts = 0; drive.d.failed = false; std::fprintf(stderr, "strata serve: window warm-up: ms per width %s, total %.0f ms%s%s\n", wlist.c_str(), std::chrono::duration(Clock::now() - w0).count(), wok ? "" : "; a window failed: ", wok ? "" : werr.c_str()); } } g_gpu_pause_idle.idle(gpu_pause_now()); // AMD on Linux: the gap before the first request starts here (the start-up's own pauses are not a "between") std::printf("READY %lld stop hold holdb\n", (long long) o.max_context); // "stop": this engine honours STOP; "hold": GEN hold=N:ID; "holdb": the --batch slots end at the hold too (BDONE hold) std::fflush(stdout); std::string line; int64_t rounds = 0; const int S = o.spec; const int S_mtp_wide = o.mtp_max_t > 0 ? std::min(o.mtp_max_t, S) : S; // the MTP's windows; suffixes go up to S // --draft auto: a request that drafts with the MTP layer has its own widest window (the MTP loses to itself above 4 on Blackwell), the DFlash2 requests S_mtp_wide const int S_mtp_narrow = o.draft_auto ? std::min(S_mtp_wide, std::max(2, o.draft_mtp_spec)) : S_mtp_wide; int S_mtp = S_mtp_wide; // this request's (set when it starts) int S_look = S; // --draft auto: the widest window a prompt-lookup draft may make for this request (the MTP requests keep the MTP's width, as without DFlash2) if (use_mtp && S_mtp < S) mtp.set_max_drafts(S_mtp - 1); // --pipeline-windows 2 loads the drafter with 8 rows: the serial loop's chain keeps its own length else if (use_mtp && mtp.max_t() > S_mtp) mtp.set_max_drafts(S_mtp - 1); strata::spec::SuffixDrafter sfx(std::max(1, o.suffix_draft), 64, (size_t) o.max_context + 4096); strata::spec::DraftPolicy policy(S); // MTP or lookup window, learned over the whole process strata::spec::DraftPolicy policy_idle(S); // --draft auto: the other drafter's learned costs; swapped in with it when a request uses the other drafter bool policy_is_df2 = use_df2; // which drafter's costs `policy` holds (the engine's first drafter; swapped with policy_idle when a request uses the other one) struct DraftBandit { double tps[2] = {0, 0}; int n[2] = {0, 0}; int64_t reqs = 0; }; // [1] = DFlash2, [0] = MTP: decode tok/s of finished requests (--draft-rule learn) std::unordered_map bandit; static const bool draft_log = std::getenv("STRATA_DRAFT_LOG") != nullptr; // one stderr line per request: drafter, tokens, rounds, ms, upkeep ms static const bool draft_keep_off = std::getenv("STRATA_DRAFT_KEEP") != nullptr && std::atoi(std::getenv("STRATA_DRAFT_KEEP")) == 0; // diagnostic: do not keep the idle drafter current int64_t draft_req_count = 0; const bool spec_cost = [] { const char* v = std::getenv("STRATA_SPEC_COST"); return v != nullptr && v[0] == '1'; }(); // cost-aware MTP window (A/B arm) strata::spec::DraftPolicy::ChainState chain_st; int chain_rows = 1; // the window the cost-aware rule kept in the MTP chain just drafted policy.set_robust(spec_cost); if (spec_cost && use_mtp) mtp.set_chain_rule([&](int idx, float pj) { const bool k = policy.keep_draft(chain_st, idx, pj, S_mtp); chain_rows = chain_st.best_rows; return k; }); policy.set_sizes(lookup_size_mask(o)); // a layer split's hand-off buffers hold kVerifyNarrowT rows: its windows stay at that if (n_stages > 1) policy.set_sizes(policy.sizes() & ((2u << strata::kernels::kVerifyNarrowT) - 1u)); // --draft-costs: this machine's fixed window costs, or learn them in this run (draft_costs_key(), CostLearner) constexpr int64_t kDraftCostRounds = 1000; // a learning stretch: about 3,000 generated tokens (DFlash2: 24 requests of 256 tokens = 1,215 rounds) constexpr int kDraftCostMinN = 20; // a window size needs this many rounds to be measured (fewer: filled in) std::string dc_key; bool dc_learning = false; bool dc_calib = false; // a table is used and its sizes are being calibrated against real rounds (DraftPolicy::start_calibration) // how long the engine has been busy: the learner keeps only the rounds of the first seconds of a busy run (CostLearner::kFreshS); a busy run // starts at a request that begins CostLearner::kIdleS or more after the last one ended (the GPU runs slower and steeper after a long load) Clock::time_point dc_busy_since = Clock::now(), dc_last_end = Clock::now(); bool dc_seen_request = false; bool dc_pcie_pending = false; // a loaded table without a PCIe share: written into it once PcieAuto has settled strata::spec::CostFile dc_file; // that table, as loaded bool dc_shares_due = false; // the table is held back (live costs): its stored CPU prompt share / PCIe share are fixed when it takes over auto dc_apply_shares = [&](const strata::spec::CostFile& cf) { if (cf.cpu_share >= 0.0) strata::prefill::Prefill::fix_cpu_share(cf.cpu_share); if (dc_pcie_ok && cf.pcie_frac >= 0.0) fix_pcie_share(cf.pcie_frac); }; if (!o.draft_costs.empty() && !policy.fixed()) { dc_key = draft_costs_key(argc, argv, o.draft_costs_key, spec_cost); strata::spec::CostFile cf; std::string why; // a machine with no table (a new engine, driver, model or setting discards the file) builds one from the rounds of its normal requests, with live // costs deciding meanwhile: no learning stretch. The old one-start stretch (forced filler windows, a burst of requests) runs only for the test // harnesses that set STRATA_DRAFT_COSTS_LEARN=1; the server and the launcher never do. const char* dc_lv = std::getenv("STRATA_DRAFT_COSTS_LEARN"); const bool dc_force_learn = dc_lv != nullptr && dc_lv[0] == '1'; const bool dc_read_ok = strata::spec::read_cost_file(o.draft_costs, dc_key, cf, why); if (dc_read_ok && cf.fresh) { // a file of the passive stretch: the real rounds collected so far dc_file = cf; policy.start_passive(cf, policy.top_size()); dc_calib = true; std::fprintf(stderr, "strata serve: draft costs: this machine's table is being built from real requests (%s; %d requests so far): live costs " "decide until every window size has %d own rounds or %d requests have run\n", o.draft_costs.c_str(), cf.reqs, strata::spec::DraftPolicy::kCalibN, strata::spec::DraftPolicy::kCalibReqs); } else if (!dc_read_ok && !dc_force_learn) { // no table yet cf.key = dc_key; cf.fresh = true; dc_file = cf; policy.start_passive(cf, policy.top_size()); dc_calib = true; std::fprintf(stderr, "strata serve: draft costs: no table for this machine yet (%s: %s): it is built from real requests, live costs decide " "until every window size has %d own rounds or %d requests have run\n", o.draft_costs.c_str(), why.c_str(), strata::spec::DraftPolicy::kCalibN, strata::spec::DraftPolicy::kCalibReqs); } else if (dc_read_ok) { std::string sizes; for (int k = 0; k < strata::spec::CostLearner::kCtxBuckets; ++k) if (!cf.tables[(size_t) k].empty()) { policy.set_fixed_costs(cf.tables[(size_t) k].data(), (int) cf.tables[(size_t) k].size(), k); sizes += (sizes.empty() ? "" : ", ") + std::to_string(cf.tables[(size_t) k].size()); } dc_file = cf; policy.start_calibration(cf.state_effect, cf.real, cf.cal, cf.real_cost, cf.reqs); dc_calib = policy.calibrating(); if (policy.table_held()) dc_shares_due = true; // a held table leaves the shares live too: they are fixed when the table takes over else dc_apply_shares(cf); std::string extra = cf.cpu_share >= 0.0 ? "; CPU prompt share " + std::to_string(cf.cpu_share).substr(0, 4) : ""; if (dc_pcie_ok && cf.pcie_frac >= 0.0) { // PcieAuto's settled share: fixed, no refinement in this run extra += "; PCIe share " + std::to_string(cf.pcie_frac).substr(0, 4); } else if (dc_pcie_ok) { // a file from before the stored PCIe share: refined as before, then written into the file dc_pcie_pending = true; extra += "; PCIe share: refined in this run, then stored"; } if (dc_calib && policy.table_held()) std::fprintf(stderr, "strata serve: draft costs: this machine's table is loaded (%s; window sizes %s%s), not used yet: the " "windows follow live costs until every size is calibrated against real requests (or 100 requests have run)\n", o.draft_costs.c_str(), sizes.c_str(), extra.c_str()); else if (dc_calib) std::fprintf(stderr, "strata serve: draft costs: this machine's table is used (%s; window sizes %s%s); sizes real requests have not " "reached yet keep collecting rounds and change the table once when they have their own\n", o.draft_costs.c_str(), sizes.c_str(), extra.c_str()); else std::fprintf(stderr, "strata serve: draft costs: this machine's table is used (%s; window sizes %s%s): the same request " "gives the same tokens on every start\n", o.draft_costs.c_str(), sizes.c_str(), extra.c_str()); } else { policy.set_learning(true); dc_learning = true; std::fprintf(stderr, "strata serve: draft costs: learning this machine's table (%s: %s); it is written after about " "%lld timed rounds and used from then on\n", o.draft_costs.c_str(), why.c_str(), (long long) kDraftCostRounds); } } if (o.lookup_max_t > 0) std::fprintf(stderr, "strata serve: --lookup-max-t %d: MTP windows up to %d tokens, window sizes %s\n", o.lookup_max_t, S_mtp, size_list(policy.sizes(), S).c_str()); // --lookup-max-t: a lookup window's graph is captured before its round; a size whose graph finds no VRAM is // dropped for good (the policy never picks it again) and the round takes the next smaller allowed size. // -1: a capture failed for another reason (err says why). auto graph_fits = [&](int t) -> int { while (t > 1) { bool no_vram = false; if (ver.prepare(t, no_vram, err)) return t; if (!no_vram) return -1; policy.disable(t); std::fprintf(stderr, "strata serve: no VRAM for the %d-token window graph: that size is dropped, " "sizes left %s (a larger --vram-reserve-mib keeps it)\n", t, size_list(policy.sizes(), S).c_str()); t = policy.fit(t - 1); } return 1; }; // The vision path (--vision): GENI carries images. The file is one // or more strata-vision records (int32 'SVE1', n, nx, ny, n_embd, then n x n_embd floats) in prompt order; // each image's rows go to its run of <|image_pad|> tokens, whose M-RoPE positions are mtmd's: t = p, // h = p + y, w = p + x, and the text after the image continues at p + max(nx, ny). constexpr int64_t kImagePad = 248056; // qwen4exp.ple.image_token_id: the PLE hash reads it for image cells bool mrope_identity = true; std::vector img_rows; std::vector row_ptr; // ---- #533: VRAM , between requests, only with --vram-elastic. It shrinks the expert cache // until that much VRAM is free for other programs (a game, a CAD session), or grows it back towards its full // size when more than that is free. Never on its own: only this command (the server's POST /v1/vram) moves // it. A shrink gives back the cache's LAST segments: the experts in their slots become CPU misses, as any // expert outside the cache is (no output changes beyond what a smaller cache decodes), the prompt path's // loan moves down to the end of what is left (a smaller chunk when it no longer fits). A grow maps them // again and puts each slot's expert back (or, when the adaptive tier already brought that one back, the // most-routed missing expert of the same layer); the adaptive tier carries on from there. std::vector> vram_evicted; // (residency index, slot) the shrinks took const int64_t chunk_full = o.prefill_chunk; // the loan's chunk with the whole cache auto relend = [&]() { // the prompt path's loan: the end of the slots left, its chunk as large as fits if (pf_parts.empty() || pf_parts[0].first < 0) return; PfPart& p = pf_parts[0]; const int64_t live = xcache.slots(); auto fits = [&](int64_t c) { #if defined(STRATA_PREFILL_FUSED) && !defined(STRATA_PREFILL_MMQ) // the cap with the auto scan's tail (fit_out_rule.hpp), the floor with today's (the start-up layout) const int64_t k = part_slots(p, c, o.prefill_auto ? pf_fit_tail : -1); const int64_t k_floor = part_slots(p, c); return k > 0 && k_floor > 0 && k_floor + g_lend_keep <= live && !(o.prefill_auto && k * 100 > kAutoLendPct * live); #else const int64_t k = part_slots(p, c); return k > 0 && k + g_lend_keep <= live && !(o.prefill_auto && k * 100 > kAutoLendPct * live); #endif }; int64_t c = chunk_full; while (c > 256 && !fits(c)) c = std::max(256, c / 2 / 256 * 256); o.prefill_chunk = c; p.first = (int32_t) std::max(0, live - part_slots(p, c)); p.first_now = -1; // laid out again at the next loan }; auto vram_command = [&](const std::string& cmd, std::string& e) -> bool { // `VRAM` alone: the reserve the engine started with (--vram-reserve-mib) char* end = nullptr; const bool bare = cmd.find_first_not_of(' ', 4) == std::string::npos; const long long reserve = bare ? (long long) o.vram_reserve_mib : std::strtoll(cmd.c_str() + 4, &end, 10); if (!bare && (end == cmd.c_str() + 4 || reserve < 0)) { e = "expected: VRAM [reserve_mib]"; return false; } if (!xcache.segmented()) { e = "VRAM needs an engine started with --vram-elastic (one NVIDIA GPU, --serve)"; return false; } if (src.complement_ready()) { e = "VRAM: not with the resident low-RAM mode (the cache holds experts RAM does not)"; return false; } if (peer.valid()) { e = "VRAM: not with --peer-device"; return false; } for (const PfPart& p : pf_parts) if (!p.lent.empty()) { e = "VRAM: a prompt's loan is still out"; return false; } if (!ver.wait_commit(e)) return false; adapt_quiesce(); // the adaptive tier's swaps in flight land first (async too) if (cudaDeviceSynchronize() != cudaSuccess) { e = std::string("VRAM: ") + cudaGetErrorString(cudaGetLastError()); return false; } const auto t0 = Clock::now(); size_t free_b = 0, total_b = 0; cudaMemGetInfo(&free_b, &total_b); const int64_t want_free = (int64_t) reserve << 20, mapped = xcache.mapped_bytes(); const int64_t before = xcache.slots(); // what stays at least: the prompt path's smallest loan (256 tokens) and the 128 slots it must leave const int64_t floor_slots = std::min(xcache.full_slots(), g_lend_keep + (pf_parts.empty() || pf_parts[0].first < 0 ? 0 : part_slots(pf_parts[0], 256))); std::string note; if ((int64_t) free_b < want_free) { const int64_t floor_b = xcache.bytes_of(floor_slots); int64_t keep = mapped - (want_free - (int64_t) free_b); if (keep < floor_b) { keep = floor_b; note = " (the cache keeps its smallest size: the prompt path's buffers)"; } // a shrink the driver refused part way has given segments back too: the slots past what stays mapped // hold nothing either way, so the tables and the loan follow what is left before the error goes out const bool shrunk = xcache.shrink(keep, e); strata::core::evict_slots_past(host_res, xcache.slots(), vram_evicted); res_upload(); if (!shrunk) { relend(); return false; } } else if (mapped < xcache.full_bytes()) { std::string gerr; if (!xcache.grow(mapped + ((int64_t) free_b - want_free), gerr)) note = " (" + gerr + ")"; const int64_t live = xcache.slots(); std::string ferr; std::vector> keep_out; for (const auto& [i, slot] : vram_evicted) { if (slot >= live) { keep_out.emplace_back(i, slot); continue; } const int64_t layer = i / g.n_expert; int64_t pick = i; if (host_res[(size_t) i] >= 0) { // back already (the adaptive tier): the layer's most-routed miss pick = -1; float best = -1.0f; for (int64_t ex = 0; ex < g.n_expert; ++ex) { const size_t j = (size_t) (layer * g.n_expert + ex); if (host_res[j] >= 0) continue; const float u = drive.d.usage.empty() ? 0.0f : drive.d.usage[j]; if (u > best) { best = u; pick = (int64_t) j; } } } if (pick < 0) continue; const uint8_t* b = srcp->blob_stable(layer, pick % g.n_expert); if (b == nullptr || !xcache.fill_slot_queued(slot, b, ferr, (int64_t) strata::kernels::cpu::expert_layout().blob_bytes(layer))) { e = "VRAM: refilling the cache failed: " + ferr; return false; } srcp->note_async_read(b, nullptr); // #1237: the queued copy reads a stage buffer; it is not recycled under it host_res[(size_t) pick] = slot; } vram_evicted.swap(keep_out); if (!xcache.sync_queued(ferr)) { e = "VRAM: " + ferr; return false; } res_upload(); } relend(); cudaMemGetInfo(&free_b, &total_b); std::fprintf(stderr, "strata serve: VRAM %lld MiB kept free: the expert cache %lld -> %lld of %lld slots " "(%.2f of %.2f GiB), %lld MiB free now, prompt chunk %lld, in %.0f ms%s\n", reserve, (long long) before, (long long) xcache.slots(), (long long) xcache.full_slots(), (double) xcache.mapped_bytes() / 1073741824.0, (double) xcache.full_bytes() / 1073741824.0, (long long) (free_b >> 20), (long long) o.prefill_chunk, std::chrono::duration(Clock::now() - t0).count(), note.c_str()); std::printf("VRAM reserve_mib=%lld expert_slots=%lld expert_slots_full=%lld expert_cache_mib=%lld " "expert_cache_full_mib=%lld vram_free_mib=%lld prompt_chunk=%lld\n", reserve, (long long) xcache.slots(), (long long) xcache.full_slots(), (long long) (xcache.mapped_bytes() >> 20), (long long) (xcache.full_bytes() >> 20), (long long) (free_b >> 20), (long long) o.prefill_chunk); return true; }; // ---- --batch: the slots of the batch windows struct BSlot { bool active = false, stop = false; int32_t x = 0; ///< the token the next window feeds (not yet in the slot's state) std::array draft{}; ///< the slot's next MTP proposal bool draft_ready = false; std::array dprob{}; ///< DFlash2 slot drafts: the selector's probability of each draft int n_drafts = 1; ///< STRATA_PIPED_MTP: how many of `draft` its next window checks int64_t p = 0; ///< its position int64_t produced = 0, max_new = 0; strata::core::SlotHold hold; ///< GEN / BGEN hold=N:ID (the server's thinking budget): the slot ends with BDONE "hold" after N emitted tokens unless ID came first Clock::time_point t0; // the slot's own conversation cache: the tokens its sessions hold (the prompt, then every token a window // fed). Kept when the request ends (`cached`), so the next turn of that conversation continues from it // instead of reading its history again (see `slot_source` in the request path). std::vector ids; int64_t reply0 = 0; ///< the index in `ids` where its penalty window starts (the last prompt token; 0 with STRATA_PENALTY_PROMPT=1) int pen_n = 0; ///< its request's penalty window (penalty_last_n) when it has a repeat / frequency / presence penalty, else 0 bool cached = false; ///< idle, and its sessions still hold `ids` bool cvec = true; ///< the control vector setting `ids` were read with bool img = false; ///< the conversation has pictures (never reused from the slot) // the checkpoint its prompt read took at the last turn boundary (the history before the new turn's // header): a client's next turn renders the history again WITHOUT this reply's thinking, so it matches // the slot's tokens only up to there - the slot's K/V up to it plus this state continue from it std::vector checks; // a prompt read that gave way to a waiting request (BYIELD): `ids` is the part read so far, and the same // request continues from it (the read goes on with the same chunks; `from0`: it had started at token 0) bool partial = false, partial_from0 = false; // #879: it was running when non-finite logits dropped the cached state; its state may have started from // that state (a checkpoint, a parked conversation), so it is not kept as a cache when it ends bool tainted = false; ConvCheckpoint::PromptPlan partial_plan; ///< --prefill-pipe: the segment it stopped in, read on in its chunks }; std::vector bs((size_t) std::max(o.batch, 0)); // STRATA_BATCH_DF2_DEFER=0: every round drafts for every slot, spare rows or not (the first measurement's behaviour, for the A/B) // STRATA_BATCH_DF2_CONF=P (default: --draft-conf, else 0.35; 0 off): a slot's draft rows stop where the product of the selector's probabilities falls below P; // STRATA_BATCH_DF2_MAXX=N: at most N draft rows a slot and window (default kDrafts) const double df2_conf = [&] { const char* e = std::getenv("STRATA_BATCH_DF2_CONF"); return e != nullptr && e[0] != '\0' ? std::atof(e) : (o.draft_conf > 0.0 ? o.draft_conf : 0.35); }(); const int df2_cap = [] { const char* e = std::getenv("STRATA_BATCH_DF2_MAXX"); return e != nullptr && e[0] != '\0' ? std::max(0, std::atoi(e)) : 99; }(); const bool batch_df2_defer = [] { const char* e = std::getenv("STRATA_BATCH_DF2_DEFER"); return !(e != nullptr && e[0] == '0'); }(); // timing of the batch windows since the slots were last all idle (one stderr line then) double bt_run = 0, bt_commit = 0, bt_emit = 0; double bt_wait0 = 0, bt_pool0 = 0; int64_t bt_miss0 = 0, bt_hits0 = 0, bt_pcie0 = 0; int64_t bt_windows = 0, bt_rows = 0, bt_tokens = 0, bt_accepted = 0; // bt_accepted: --batch-mtp proposals taken int64_t pipe_rows = 0; // the pipelined groups' rows, never reset (bt_rows restarts when the slots go idle) // per stage (0 = CUDA0's verifier): the GPU-reach wait and pool time when the timed windows began; and the routed // (token, expert) entries the CPU and the PCIe share had served by then (bt_hits0 holds the VRAM entries) std::vector bt_stage_wait0, bt_stage_pool0; int64_t bt_cpu_ent0 = 0, bt_off_ent0 = 0; // the adaptive VRAM tier in batch windows: windows seen since the engine started (--adapt-every counts them), and, // since the last timing line, its rounds, the experts it swapped in and the ms a window waited for it int64_t ba_window = 0, bt_adapt_rounds = 0, bt_adapt_swaps = 0; double bt_adapt_wait = 0; bool in_prompt_read = false; // batch_step runs between a prompt's chunks: the adaptive tier stands still then double serve_adapt_drain_ms = 0.0; // 149: the request's wait for the adaptive round in flight int64_t bt_a_rounds0 = 0, bt_a_swapped0 = 0; // the asynchronous tier's counters when the timed windows began Clock::time_point bt_start = Clock::now(); const char* batch_telemetry_env = std::getenv("STRATA_BATCH_TELEMETRY"); const bool batch_telemetry_enabled = batch_telemetry_env != nullptr && batch_telemetry_env[0] == '1' && batch_telemetry_env[1] == '\0'; strata::core::BatchWindowSampler batch_telemetry(batch_telemetry_enabled); strata::program::ParCounters pc; // STRATA_PAR_COUNTERS=1: counters only (par_counters.hpp); off: a branch auto pc_ex = [&]() { strata::program::ParCounters::Ex e; e.misses = drive.d.multi_misses; e.entries = drive.d.multi_entries; e.hits = drive.d.cache_hits; e.offload = drive.d.offload_entries; e.pcie = drive.d.pcie_experts; e.run_ms = drive.d.ms_run; e.jobs_ms = drive.d.ms_jobs; e.vwait_ms = ver.ms_wait; e.vpool_ms = ver.ms_pool; return e; }; auto report_batch_window = [&](int processed_rows, int active_rows, bool idle, Clock::time_point started) { if (!batch_telemetry_enabled) return; const auto sample = batch_telemetry.complete(processed_rows, active_rows, idle, started, Clock::now()); if (!sample) return; std::printf("BSTAT %lld %lld %lld %lld\n", (long long) sample->windows, (long long) sample->processed_rows, (long long) sample->active_rows, (long long) sample->elapsed_ms); std::fflush(stdout); }; int admit_slot = -1; ///< the slot the request being read will continue in (BGEN) long long admit_max_new = 0; // BCO (research, PAR-H; STRATA_COALESCE_PREFILL on the server): prompts of waiting requests, read in // the SAME layer-major pass as the next BGEN's prompt into the named idle slots' sessions (the experts a layer // streams are shared), so their own admissions find the prompt in the slot and read nothing. BCOK // says a slot holds its prompt; a declined or failed co-read says nothing and costs nothing. struct CoReq { int slot = -1; std::vector ids; }; std::vector co_pending, co_set; auto batch_on = [&] { for (const BSlot& b : bs) if (b.active) return true; return false; }; auto try_next_line = [&](std::string& out) -> bool { std::lock_guard lk(in_mu); if (in_lines.empty()) return false; out = std::move(in_lines.front()); in_lines.pop_front(); return true; }; // the session a request just left behind (its prompt) -> slot b's sessions, on every stage // the main sessions and the slot sessions of a stage live on the same device and are carved alike, so // a slot copy can go device to device (the same bytes into the same places as the checkpoint/K-V image // round trip through host memory, which costs ~40-90 ms per admission on a 4-card split); each device is // synchronized once before and once after. Opt-in: STRATA_SLOT_COPY_DIRECT=1 (default: the host path). static const bool slot_copy_direct = [] { const char* v = std::getenv("STRATA_SLOT_COPY_DIRECT"); return v != nullptr && v[0] != '\0' && v[0] != '0'; }(); auto direct_slot_copy = [&](bool into_slot, int b, const std::vector& ids, std::string& e) -> bool { const int64_t upto = (int64_t) ids.size(); auto sync_all = [&]() { bool ok = true; for (size_t k = 0; k < bslot_ss.size(); ++k) { const strata::core::OnDevice on_k(k == 0 ? 0 : stages[k - 1]->dev); ok = cudaDeviceSynchronize() == cudaSuccess && ok; } return ok; }; // a copy that fails part-way leaves earlier residency refreshes queued on the legacy stream: drain them // before the caller reuses the sessions (its zeroing runs on non-blocking streams, not ordered against these) auto failed = [&]() { (void) sync_all(); return false; }; if (!sync_all()) { e = "batch slot copy: device sync failed"; return false; } // STRATA_SLOT_COPY_BATCHSYNC: every copy is only queued, and the sync_all below is the one wait per device const bool queued = slot_copy_batchsync_env(); for (size_t k = 0; k < bslot_ss.size(); ++k) { strata::core::SessionState& main_ss = k == 0 ? ss : stages[k - 1]->ss; strata::core::SessionState& slot_ss = *bslot_ss[k][(size_t) b]; strata::core::SessionState& from = into_slot ? main_ss : slot_ss; strata::core::SessionState& to = into_slot ? slot_ss : main_ss; const strata::core::OnDevice on_k(k == 0 ? 0 : stages[k - 1]->dev); if (!strata::core::conversation_checkpoint_copy(from, to, ids, g, e, queued)) return failed(); for (int64_t j = 0; j < from.qsa_alloc; ++j) if (!strata::core::conversation_kv_copy(from.qsa_states[from.qsa_ord0 + j], to.qsa_states[to.qsa_ord0 + j], g, upto, true, e, queued)) return failed(); } if (!sync_all()) { e = "batch slot copy: device sync failed"; return false; } return true; }; auto copy_to_slot = [&](int b, const std::vector& ids, std::string& e) -> bool { const int64_t upto = (int64_t) ids.size(); #if defined(STRATA_GPU_METAL) // the running state and the K/V of the Metal window, not the session's device buffers return strata::metal_engine::window_slot_copy_main(true, b, upto, false, e); #endif if (slot_copy_direct) { if (!direct_slot_copy(true, b, ids, e)) return false; } else for (size_t k = 0; k < bslot_ss.size(); ++k) { strata::core::SessionState& from = k == 0 ? ss : stages[k - 1]->ss; strata::core::SessionState& to = *bslot_ss[k][(size_t) b]; const strata::core::OnDevice on_k(k == 0 ? 0 : stages[k - 1]->dev); if (cudaDeviceSynchronize() != cudaSuccess) { e = "batch admission: device sync failed"; return false; } strata::core::ConversationCheckpoint ck; ck.ids = ids; if (!strata::core::conversation_checkpoint_save(ck, from, g, e) || !strata::core::conversation_checkpoint_restore(ck, to, g, e)) return false; for (int64_t j = 0; j < from.qsa_alloc; ++j) { strata::core::ConversationKv img; if (!strata::core::conversation_kv_save(img, from.qsa_states[from.qsa_ord0 + j], g, upto, true, e)) return false; if (cudaDeviceSynchronize() != cudaSuccess) { e = "batch admission: device sync failed"; return false; } if (!strata::core::conversation_kv_restore(img, to.qsa_states[to.qsa_ord0 + j], g, upto, true, e)) return false; } if (cudaDeviceSynchronize() != cudaSuccess) { e = "batch admission: device sync failed"; return false; } } if (batch_df2) { // The solo drafter's ring holds the prompt (its taps came with the prompt read): the slot's drafter starts from an exact copy of it. #if defined(STRATA_HAVE_DFLASH2) if (!slot_df2[(size_t) b]->copy_state_from(df2, e)) return false; #endif } else if (batch_mtp) { // Admission first builds the solo draft KV; copy it into the slot before drafting. Both drafters' K/V // are on the drafter's device (the last stage's GPU with a layer split): the copy's ring refill is a // kernel launch there. const strata::core::OnDevice on_mtp(mtp.device()); strata::core::ConversationKv image; if (!mtp.idle(e) || !slot_mtp[(size_t) b]->idle(e) || !strata::core::conversation_kv_save(image, mtp.kv_state(), draft_geometry, upto, false, e) || !strata::core::conversation_kv_restore(image, slot_mtp[(size_t) b]->kv_state(), draft_geometry, upto, false, e) || cudaDeviceSynchronize() != cudaSuccess) return false; slot_mtp[(size_t) b]->set_prompt_len(upto); } return true; }; // slot b's sessions -> the main ones (the reverse of copy_to_slot): a request that continues the // conversation an idle slot holds reads on from there. Every stage, the same calls. // `at`: one of the slot's checkpoints - only the K/V up to it is copied and its state restored instead auto copy_from_slot = [&](int b, const ConvCheckpoint* at, std::string& e) -> bool { // the main session's K/V is replaced by the slot's: K/V retained from a restore described the old one conversations.take_reuse(); const int64_t upto = at != nullptr ? (int64_t) at->ids.size() : (int64_t) bs[(size_t) b].ids.size(); if (at != nullptr && at->stage_parts.size() != stages.size()) { e = "a checkpoint without its stage parts"; return false; } #if defined(STRATA_GPU_METAL) if (!strata::metal_engine::window_slot_copy_main(false, b, upto, at != nullptr, e)) return false; return at == nullptr || strata::core::conversation_checkpoint_restore(*at, ss, g, e); // (the checkpoint's running state) #endif if (slot_copy_direct && at == nullptr) { if (!direct_slot_copy(false, b, bs[(size_t) b].ids, e)) return false; } else for (size_t k = 0; k < bslot_ss.size(); ++k) { strata::core::SessionState& from = *bslot_ss[k][(size_t) b]; strata::core::SessionState& to = k == 0 ? ss : stages[k - 1]->ss; const strata::core::OnDevice on_k(k == 0 ? 0 : stages[k - 1]->dev); if (cudaDeviceSynchronize() != cudaSuccess) { e = "batch slot restore: device sync failed"; return false; } if (at != nullptr) { if (!strata::core::conversation_checkpoint_restore(k == 0 ? *at : at->stage_parts[k - 1], to, g, e)) return false; } else { strata::core::ConversationCheckpoint ck; ck.ids = bs[(size_t) b].ids; if (!strata::core::conversation_checkpoint_save(ck, from, g, e) || !strata::core::conversation_checkpoint_restore(ck, to, g, e)) return false; } for (int64_t j = 0; j < from.qsa_alloc; ++j) { strata::core::ConversationKv img; if (!strata::core::conversation_kv_save(img, from.qsa_states[from.qsa_ord0 + j], g, upto, true, e)) return false; if (cudaDeviceSynchronize() != cudaSuccess) { e = "batch slot restore: device sync failed"; return false; } if (!strata::core::conversation_kv_restore(img, to.qsa_states[to.qsa_ord0 + j], g, upto, true, e)) return false; } if (cudaDeviceSynchronize() != cudaSuccess) { e = "batch slot restore: device sync failed"; return false; } } if (batch_df2) { #if defined(STRATA_HAVE_DFLASH2) if (!df2.copy_state_from(*slot_df2[(size_t) b], e)) return false; // a returning solo request goes on from the slot's ring #endif } else if (batch_mtp) { // A returning solo request resumes from its slot's draft KV (on the drafter's device, as above). const strata::core::OnDevice on_mtp(mtp.device()); strata::core::ConversationKv image; if (!slot_mtp[(size_t) b]->idle(e) || !mtp.idle(e) || !strata::core::conversation_kv_save(image, slot_mtp[(size_t) b]->kv_state(), draft_geometry, upto, false, e) || !strata::core::conversation_kv_restore(image, mtp.kv_state(), draft_geometry, upto, false, e) || cudaDeviceSynchronize() != cudaSuccess) return false; mtp.set_prompt_len(upto); } return true; }; auto stage_verifier = [&](int k) -> strata::core::Verifier& { return k == 0 ? ver : stages[(size_t) k - 1]->ver; }; // What an idle slot holds (the conversation it decoded last: its sessions, its draft K/V and its checkpoints) // goes to the parked conversations before an admission overwrites it. The main session was parked with that // conversation's prompt only (the admission's copy), so the reply the slot decoded lives nowhere else: without // this, the conversation's next turn finds its prompt-read state and reads the whole reply again (measured on // four 200K chats over two slots: 255 of a 256-token reply re-read, and a chat whose copies the cache had // evicted meanwhile read from token 0). Nothing to do when the live main session or a parked conversation // already holds that state (or a continuation of it). // Parking is an optimization like a checkpoint (#3350): a skip and a failed snapshot (a host or device // allocation that ran out) are logged and the slot is overwritten as before. Nothing here ends the request // or the engine. auto park_slot = [&](int b) { BSlot& sl = bs[(size_t) b]; if (!conversations.enabled() || sl.active || !sl.cached || sl.img || sl.ids.empty()) return; auto prefix_of = [&](const std::vector& whole) { return whole.size() >= sl.ids.size() && std::equal(sl.ids.begin(), sl.ids.end(), whole.begin()); }; const bool in_main = live_ok && cvec_cached == sl.cvec && prefix_of(live) && imgs_below(live_imgs, (int64_t) sl.ids.size()).empty(); if (in_main || conversations.holds(sl.ids, {}, sl.cvec)) return; if (conversations.supersedes_richer(sl.ids, {}, sl.checks, sl.cvec)) { // its park would drop (as superseded) the main session's copy of this conversation, and with it the checkpoints the slot // does not hold - an agent's system-prompt root that the next requests borrow (#4420, as 0.2.6 did: the slot is overwritten) std::fprintf(stderr, "strata serve: conversation cache: slot %d not parked before its overwrite (a parked copy of its " "conversation holds checkpoints the slot does not; it stays)\n", b); return; } if (use_mtp && !batch_mtp) { // no draft K/V of its own: an image without it would not restore beside the drafter std::fprintf(stderr, "strata serve: conversation cache: slot %d not parked before its overwrite (its %zu tokens " "have no per-slot draft K/V without --batch-mtp)\n", b, sl.ids.size()); return; } if (cudaDeviceSynchronize() != cudaSuccess) { std::fprintf(stderr, "strata serve: conversation cache: slot %d not parked before its overwrite (device sync " "failed)\n", b); return; } std::string why; if (batch_mtp && !batch_df2 && !slot_mtp[(size_t) b]->idle(why)) { std::fprintf(stderr, "strata serve: conversation cache: slot %d not parked before its overwrite (%s)\n", b, why.c_str()); return; } const size_t n_st = stages.size(); static const std::vector no_imgs; ParkSource src{sl.ids, no_imgs, sl.checks, sl.cvec, *bslot_ss[0][(size_t) b], {}, (n_st > 0 && !mtp_first) || !batch_mtp || batch_df2 ? nullptr : &slot_mtp[(size_t) b]->kv_state(), batch_mtp && !batch_df2 && !mtp_first && n_st > 0 ? &slot_mtp[(size_t) b]->kv_state() : nullptr, false, " from slot " + std::to_string(b)}; for (size_t k = 1; k < bslot_ss.size(); ++k) src.stage_sessions.push_back(bslot_ss[k][(size_t) b].get()); try { if (park_source(src, 0)) return; // the snapshot failed (the copy's own memory, as in #3350): the slot is not touched, so go on without // the image; a non-sticky allocation error is cleared, a sticky one comes back from the next call std::fprintf(stderr, "strata serve: conversation cache: slot %d not parked before its overwrite (%s)\n", b, err.empty() ? "the snapshot failed" : err.c_str()); err.clear(); (void) checkpoint_failure_is_survivable(); } catch (const std::bad_alloc&) { std::fprintf(stderr, "strata serve: conversation cache: allocation failed; skip parking slot %d\n", b); } }; // one batch window over the active slots only (row t is the t-th active slot): an idle slot is not touched, // so it keeps the conversation it holds auto batch_step = [&]() -> bool { int S = 0; int rows[strata::kernels::kVerifyMaxT] = {}; int32_t tok[strata::kernels::kVerifyMaxT] = {}, outb[strata::kernels::kVerifyMaxT] = {}; int64_t pos[strata::kernels::kVerifyMaxT] = {}; int first[strata::kernels::kVerifyMaxT] = {}, active[strata::kernels::kVerifyMaxT] = {}; static size_t next_slot = 0; // Each MTP slot uses two rows; rotate slots when more than four are active. int A = 0; // (--batch-mtp: two rows a slot, at most kVerifyNarrowT; the plain windows hold up to kVerifyMaxT) const int win_cap = batch_mtp ? (int) strata::kernels::kVerifyNarrowT : (int) strata::kernels::kVerifyMaxT; int nrow[strata::kernels::kVerifyMaxT] = {}; // the rows slot a (the a-th active) holds: its token and its drafts // DFlash2 slots: the rows beyond one a slot are SPARE; they carry the slots' drafts, shared evenly in slot order (so the layout of a window // depends on which slots are active, not on the drafts: the captured batch graphs are reused). More slots than rows: no drafts, the slots // take turns as in the plain windows. A draft row a slot has no room for (its last tokens, the context's end) is not asked for. int df2_extra[64] = {}; if (batch_df2) { int act_ids[64] = {}, nact = 0; for (size_t b = 0; b < bs.size() && nact < (int) (sizeof act_ids / sizeof act_ids[0]); ++b) if (bs[b].active) act_ids[nact++] = (int) b; const int spare = std::max(0, win_cap - nact); for (int k = 0; k < nact && nact > 0; ++k) { const BSlot& q = bs[(size_t) act_ids[k]]; int want = spare / nact + (k < spare % nact ? 1 : 0); want = std::min(want, (int) strata::core::Dflash2Drafter::kDrafts); want = std::min(want, (int) std::max(0, strata::core::slot_cap(q.max_new, q.hold) - q.produced - 1)); want = std::min(want, (int) std::max(0, (int64_t) o.max_context - q.p - 2)); want = std::min(want, df2_cap); if (q.draft_ready && df2_conf > 0.0) { // a draft row is worth its cost where the chain so far is likely: the product of the selector's probabilities double chain = 1.0; int keep_n = 0; while (keep_n < want && (chain *= (double) q.dprob[(size_t) keep_n]) >= df2_conf) ++keep_n; want = keep_n; } if (act_ids[k] < (int) (sizeof df2_extra / sizeof df2_extra[0])) df2_extra[act_ids[k]] = want; } #if defined(STRATA_HAVE_DFLASH2) // A slot that sat out earlier rounds (no spare rows: its drafter did no work, the committed rows' taps wait on the host) gets its ring brought // up to date and its first drafts now, before the window is built. If that cannot be done it takes no drafts this round. for (int k = 0; k < nact; ++k) { const int b = act_ids[k]; BSlot& q = bs[(size_t) b]; if (b >= (int) (sizeof df2_extra / sizeof df2_extra[0]) || df2_extra[b] == 0 || q.draft_ready) continue; strata::core::Dflash2Drafter& d = *slot_df2[(size_t) b]; int32_t dd[strata::core::Dflash2Drafter::kDrafts]; float pp[strata::core::Dflash2Drafter::kDrafts]; const size_t row_bytes = (size_t) d.n_taps() * (size_t) g.n_embd * 4; const strata::core::OnDevice on_d(d.device()); if (!d.has_deferred() || d.deferred_hi() != q.p || !d.catch_up(q.p - 1, err) || cudaMemcpyAsync(d.landing(), d.deferred_row(q.p - 1), row_bytes, cudaMemcpyHostToDevice, d.stream()) != cudaSuccess || !d.draft(d.landing(), 1, q.p - 1, q.x, dd, pp, err)) { if (err.empty()) err = "the deferred rows do not end at the slot's position"; std::fprintf(stderr, "strata batch: DFlash2 slot %d: catch-up failed (%s): no drafts for it this round\n", b, err.c_str()); err.clear(); df2_extra[b] = 0; continue; } d.clear_deferred(); for (int j = 0; j < strata::core::Dflash2Drafter::kDrafts && j < (int) q.draft.size(); ++j) { q.draft[(size_t) j] = dd[j]; q.dprob[(size_t) j] = pp[j]; } q.draft_ready = true; } #endif } for (size_t offset = 0; offset < bs.size(); ++offset) { const int b = (int) ((next_slot + offset) % bs.size()); if (!bs[(size_t) b].active) continue; const int extra = batch_df2 ? (b < (int) (sizeof df2_extra / sizeof df2_extra[0]) ? df2_extra[b] : 0) : batch_mtp ? 1 : 0; if (S + 1 + extra > win_cap) break; BSlot& q = bs[(size_t) b]; if (batch_mtp && !q.draft_ready && !batch_df2) { err = "batch MTP: a live slot has no draft"; return false; } first[A] = S; nrow[A] = 1 + extra; active[A++] = b; rows[S] = b; tok[S] = q.x; pos[S] = q.p; ++S; for (int j = 0; j < extra; ++j) { rows[S] = b; tok[S] = q.draft[(size_t) j]; pos[S] = q.p + 1 + j; ++S; } } if (batch_mtp && A > 0) next_slot = ((size_t) active[A - 1] + 1) % bs.size(); if (S == 0) return true; const bool was_busy = strata::core::progress().busy.load(); strata::core::progress().busy.store(true); drive.d.layers = 0; drive.d.experts = 0; drive.d.failed = false; apply_pending(false); // --adapt-async: the round in flight moves on a step when its job and copies are done (or a due round starts). // Never between a prompt's chunks (its loan of cache slots and its chunks read the tables); a request drains // the round before its prompt starts (adapt_tick(true) where the request begins). The main thread's part is // small (the table changes and uploads); the copies are on the helper thread and the cards' refill streams. if (ajob && !in_prompt_read) { const Clock::time_point ta = Clock::now(); if (!adapt_tick(false)) { std::printf("ERR an adaptive refill failed\n"); return false; } bt_adapt_wait += std::chrono::duration(Clock::now() - ta).count(); } if (bt_windows == 0) { bt_start = Clock::now(); bt_wait0 = ver.ms_wait; bt_pool0 = ver.ms_pool; bt_miss0 = drive.d.multi_misses; bt_hits0 = drive.d.cache_hits; bt_pcie0 = drive.d.pcie_experts; bt_stage_wait0.assign(stages.size() + 1, 0.0); bt_stage_pool0.assign(stages.size() + 1, 0.0); for (size_t k = 0; k <= stages.size(); ++k) { bt_stage_wait0[k] = stage_verifier((int) k).ms_wait; bt_stage_pool0[k] = stage_verifier((int) k).ms_pool; } bt_cpu_ent0 = drive.d.multi_entries; bt_off_ent0 = drive.d.offload_entries; if (pc.on()) pc.begin(pc_ex(), (int) g.n_layers); bt_a_rounds0 = a_rounds; bt_a_swapped0 = a_swapped; } for (int t = 0; t < S; ++t) { // each penalised slot's reply tail for its penalty window (the verifier builds the rows from it and this window's tokens) const BSlot& ps = bs[(size_t) rows[t]]; if (ps.pen_n <= 0 || (t > 0 && rows[t - 1] == rows[t])) continue; const int64_t from = std::max(ps.reply0, (int64_t) ps.ids.size() - ps.pen_n); ver.set_slot_history(rows[t], ps.ids.data() + from, (int64_t) ps.ids.size() - from); } const Clock::time_point w0 = Clock::now(); if (!ver.run_slot_rows(rows, S, tok, pos, win_pool_fn, win_pool_user, outb, err) || drive.d.failed) { std::printf("ERR %s\n", drive.d.failed && drive.d.fail ? drive.d.fail : err.c_str()); return false; } const Clock::time_point w1 = Clock::now(); // The adaptive VRAM tier, as the solo loop runs it: every --adapt-every windows, on a thread beside the commit and // the drafts. Every stage's window has finished here (run_slot_rows synchronised each stage's stream), and // nothing in flight reads the cache slots a swap overwrites; the swapped-in experts are landed (apply_pending) // before this window ends, so no other path (a prompt chunk read between windows, a loan of cache slots, a KV // growth) ever meets swaps in flight. Not between a prompt's chunks: a loan of cache slots marks its lent // experts missing, and they are put back when the loan ends. (With --adapt-async the tier is ticked above.) struct AdaptRun { std::thread th; bool ok = true; ~AdaptRun() { if (th.joinable()) th.join(); } // an error return below still joins it } adapt_run; if (!drive.d.usage.empty() && o.adapt_every > 0 && !ajob && !in_prompt_read && (++ba_window % o.adapt_every) == 0 && pending.empty()) adapt_run.th = std::thread([&] { adapt_run.ok = adapt(); }); // Accept the proposal only when the target picked it and there is room to emit both tokens. std::vector keep(bs.size(), 0); for (int a = 0; a < A; ++a) { const int b = active[a], i = first[a]; const BSlot& sl = bs[(size_t) b]; const bool eos = std::find(o.eos_ids.begin(), o.eos_ids.end(), (int64_t) outb[i]) != o.eos_ids.end(); (void) eos; int kp = 1; // the proposals the target picked, in order: row j + 1 stands when the target's pick after row j is its token and nothing ended while (batch_mtp && kp < nrow[a] && outb[i + kp - 1] == tok[i + kp] && !sl.stop && std::find(o.eos_ids.begin(), o.eos_ids.end(), (int64_t) outb[i + kp - 1]) == o.eos_ids.end() && sl.produced + kp + 1 <= strata::core::slot_cap(sl.max_new, sl.hold) && sl.p + kp + 2 <= o.max_context) ++kp; keep[b] = kp; } if (!(batch_mtp ? ver.commit_slot_prefixes(keep.data(), err) : ver.commit_slots(err))) { std::printf("ERR %s\n", err.c_str()); return false; } const Clock::time_point w2 = Clock::now(); auto msd = [](Clock::time_point a0, Clock::time_point b0) { return std::chrono::duration(b0 - a0).count(); }; bt_run += msd(w0, w1); bt_commit += msd(w1, w2); ++bt_windows; for (int a = 0; a < A; ++a) { bt_rows += keep[active[a]]; bt_accepted += keep[active[a]] - 1; } std::vector df2_launched; // batch DFlash2: slots whose draft graph is queued for (int t = 0; t < A; ++t) { const int b = active[t]; BSlot& sl = bs[(size_t) b]; bool nf = false; // #879: a row of this slot held non-finite logits: the slot ends, nothing emitted for (int r = first[t]; r < first[t] + (batch_mtp ? nrow[t] : 1); ++r) nf = nf || ver.nonfinite_in(r); if (nf) { std::fprintf(stderr, "strata batch: non-finite logits (#879) in slot %d at position %lld: it ends " "(BDONE nonfinite) and the next request reads its prompt from token 0\n", b, (long long) pos[first[t]]); const double ms = std::chrono::duration(Clock::now() - sl.t0).count(); std::printf("BDONE %d %lld nonfinite %.1f\n", b, (long long) sl.produced, ms); sl.active = false; sl.cached = false; sl.checks.clear(); nan_flush = true; continue; } for (int j = 0; j < keep[b]; ++j) { const int32_t y = outb[first[t] + j]; sl.ids.push_back(tok[first[t] + j]); std::printf("BT %d %d\n", b, (int) y); ++sl.produced; strata::core::slot_hold_emitted(sl.hold, (int64_t) y); const bool eos = std::find(o.eos_ids.begin(), o.eos_ids.end(), (int64_t) y) != o.eos_ids.end(); const char* fin = eos ? "stop" : sl.stop ? "cancel" : sl.produced >= sl.max_new ? "length" : strata::core::slot_hold_reached(sl.hold, sl.produced, sl.max_new) ? "hold" : sl.p + 2 > o.max_context ? "length" : nullptr; if (fin != nullptr) { const double ms = std::chrono::duration(Clock::now() - sl.t0).count(); std::printf("BDONE %d %lld %s %.1f\n", b, (long long) sl.produced, fin, ms); sl.active = false; sl.cached = o.prompt_cache > 0 && !sl.img && !sl.tainted; break; } sl.x = y; sl.p += 1; } #if defined(STRATA_HAVE_DFLASH2) if (batch_df2 && sl.active) { // The slot's committed rows' taps (every stage's share, landed on the drafter's card) are its drafter's next context; its drafts follow // from the last committed token. The window's host sync is behind us, so the taps are final. strata::core::Dflash2Drafter& d = *slot_df2[(size_t) b]; const int kp = keep[b]; int32_t dd[strata::core::Dflash2Drafter::kDrafts]; float pp[strata::core::Dflash2Drafter::kDrafts]; d.note_rows(tok + first[t], kp, pos[first[t]]); if (nrow[t] > 1 || !batch_df2_defer) { // this window carried drafts for the slot: its drafter takes the committed rows' taps and drafts again if (d.has_deferred() && !d.catch_up(pos[first[t]], err)) { std::printf("ERR batch DFlash2 slot %d: %s\n", b, err.c_str()); return false; } d.clear_deferred(); if (!ver.gather_taps(d.landing(), d.device(), first[t], kp, 0, d.stream(), err) || !d.draft_launch(d.landing(), kp, pos[first[t]], outb[first[t] + kp - 1], err)) { std::printf("ERR batch DFlash2 slot %d: %s\n", b, err.c_str()); return false; } df2_launched.push_back(b); // finished after the loop: the slots' graphs run at the same time (void) dd; (void) pp; } else { // no spare row for the slot: no draft, no drafter work; the rows' taps wait on the host until spare rows return float* dst = d.defer_rows(pos[first[t]], kp, err); if (dst == nullptr || !ver.gather_taps_host(dst, first[t], kp, err)) { std::printf("ERR batch DFlash2 slot %d: %s\n", b, err.c_str()); return false; } sl.draft_ready = false; } } #endif if (batch_mtp && !batch_df2 && sl.active) { // The slot's two residual rows (the final residuals of the last stage: ver.final_R_all() follows the // chain, so with a layer split they are on the last stage's GPU, where the drafters are). The copy is // queued on the drafter's own stream after the window's host sync, so the draft graph reads it. const strata::core::OnDevice on_slot_mtp(slot_mtp[(size_t) b]->device()); const size_t stride = (size_t) g.hc * (size_t) g.n_embd; if (cudaMemcpyAsync(slot_mtp_rows[(size_t) b].get(), ver.final_R_all() + (size_t) first[t] * stride, 2 * stride * sizeof(float), cudaMemcpyDeviceToDevice, slot_mtp[(size_t) b]->stream()) != cudaSuccess || !slot_mtp[(size_t) b]->draft(2, outb + first[t], pos[first[t]], keep[b] - 1, sl.draft.data(), err)) { std::printf("ERR batch MTP slot %d: %s\n", b, err.c_str()); return false; } sl.draft_ready = true; } } #if defined(STRATA_HAVE_DFLASH2) for (const int b : df2_launched) { int32_t dd[strata::core::Dflash2Drafter::kDrafts]; float pp[strata::core::Dflash2Drafter::kDrafts]; BSlot& sl = bs[(size_t) b]; if (!slot_df2[(size_t) b]->draft_finish(dd, pp, err)) { std::printf("ERR batch DFlash2 slot %d: %s\n", b, err.c_str()); return false; } for (int j = 0; j < strata::core::Dflash2Drafter::kDrafts && j < (int) sl.draft.size(); ++j) { sl.draft[(size_t) j] = dd[j]; sl.dprob[(size_t) j] = pp[j]; } sl.draft_ready = true; } #endif std::fflush(stdout); bt_emit += msd(w2, Clock::now()); if (adapt_run.th.joinable()) { const Clock::time_point wa = Clock::now(); adapt_run.th.join(); if (!adapt_run.ok) { std::printf("ERR an adaptive refill failed\n"); return false; } ++bt_adapt_rounds; bt_adapt_swaps += (int64_t) pending.size(); apply_pending(true); // the copies land and the tables follow (the next window plans from them) bt_adapt_wait += msd(wa, Clock::now()); } strata::core::progress().busy.store(was_busy); report_batch_window(S, A, !batch_on(), w0); pc.window(S, A); if (!batch_on() && bt_windows > 0) { const double w = (double) bt_windows, wall = msd(bt_start, Clock::now()); pc.flush(wall, pc_ex()); const double L = (double) g.n_layers; const double e_vram = (double) (drive.d.cache_hits - bt_hits0), e_pcie = (double) (drive.d.offload_entries - bt_off_ent0), e_cpu = (double) (drive.d.multi_entries - bt_cpu_ent0); const double e_all = std::max(e_vram + e_pcie + e_cpu, 1.0); std::string per_stage; // every stage's own host wait for its GPU and its pool time (run_slot_rows recurses) for (size_t k = 0; k <= stages.size(); ++k) { char sb[96]; std::snprintf(sb, sizeof sb, "%sCUDA%d wait %.2f + pool %.2f", k == 0 ? "" : ", ", k == 0 ? 0 : stages[k - 1]->dev, (stage_verifier((int) k).ms_wait - bt_stage_wait0[k]) / w, (stage_verifier((int) k).ms_pool - bt_stage_pool0[k]) / w); per_stage += sb; } char adapt_txt[160] = ""; if (!drive.d.usage.empty() && ajob) std::snprintf(adapt_txt, sizeof adapt_txt, "; adaptive tier (async): %lld rounds started, %lld experts swapped in", (long long) (a_rounds - bt_a_rounds0), (long long) (a_swapped - bt_a_swapped0)); else if (!drive.d.usage.empty()) std::snprintf(adapt_txt, sizeof adapt_txt, "; adaptive tier: %lld rounds, %lld experts swapped in", (long long) bt_adapt_rounds, (long long) bt_adapt_swaps); std::fprintf(stderr, "strata batch: %lld windows, avg %.2f rows, %.2f ms/window = run %.2f (CUDA0 GPU-reach " "wait %.2f + CPU experts %.2f) + commit %.2f + emit %.2f + adapt wait %.2f; per stage " "(ms/window): %s; per layer-window: CPU experts %.2f, VRAM hits %.2f, PCIe %.2f; routed " "entries per window: VRAM %.1f (%.1f%%), PCIe %.1f (%.1f%%), CPU %.1f (%.1f%%)%s; %.1f rows/s " "over %.0f ms of wall time (admissions included)\n", (long long) bt_windows, bt_rows / w, (bt_run + bt_commit + bt_emit + bt_adapt_wait) / w, bt_run / w, (ver.ms_wait - bt_wait0) / w, (ver.ms_pool - bt_pool0) / w, bt_commit / w, bt_emit / w, bt_adapt_wait / w, per_stage.c_str(), (drive.d.multi_misses - bt_miss0) / (w * L), (drive.d.cache_hits - bt_hits0) / (w * L), (drive.d.pcie_experts - bt_pcie0) / (w * L), e_vram / w, 100.0 * e_vram / e_all, e_pcie / w, 100.0 * e_pcie / e_all, e_cpu / w, 100.0 * e_cpu / e_all, adapt_txt, 1000.0 * bt_rows / std::max(wall, 1e-9), wall); for (size_t k = 0; k <= stages.size(); ++k) { const std::string pr = (k == 0 ? ver : stages[k - 1]->ver).profile_report(); if (!pr.empty()) std::fprintf(stderr, "strata batch GPU stages, stage %zu (ms/window):%s\n", k + 1, pr.c_str()); } #if defined(STRATA_HAVE_DFLASH2) if (batch_df2) { int64_t cu = 0, cr = 0, dr = 0; double cm = 0; for (const auto& dsl : slot_df2) { cu += dsl->n_catchups; cr += dsl->n_catchup_rows; dr += dsl->n_deferred_rows; cm += dsl->ms_catchup; } std::fprintf(stderr, "strata batch: DFlash2 slots: %lld rows deferred (no spare window row), %lld catch-ups replayed %lld rows in %.1f ms (%.2f ms each)\n", (long long) dr, (long long) cu, (long long) cr, cm, cu > 0 ? cm / (double) cu : 0.0); } #endif if (batch_mtp) // each slot-window offers one proposal and yields 1 + (accepted) tokens std::fprintf(stderr, "strata batch: MTP proposals accepted %lld of %lld (%.1f%%)\n", (long long) bt_accepted, (long long) (bt_rows - bt_accepted), 100.0 * (double) bt_accepted / (double) std::max(bt_rows - bt_accepted, 1)); bt_run = bt_commit = bt_emit = bt_adapt_wait = 0; bt_windows = bt_rows = bt_tokens = bt_accepted = bt_adapt_rounds = bt_adapt_swaps = 0; } return true; }; // ---- --batch-groups: the slot groups pipelined through the stages (--batch-groups G > 1 with a layer split) const int n_pipe = (int) stages.size() + 1; const bool piped = o.batch > 0 && o.batch_groups > 1 && n_pipe > 1; strata::core::StageInFlightSampler stage_in_flight(n_pipe, piped && batch_telemetry_enabled); const int GS = piped ? o.batch / o.batch_groups : o.batch; // STRATA_PIPED_MTP: the pipelined groups draft too - a group's window carries each of its slots' rows (the slot's // token and that slot's own proposals), so any number of slots per group drafts - and every stage saves the rows // their commit replays const int pmtp_rows_per_slot = 1 + pm_drafts; // the slot's token + its proposals const int pmtp_rows_per_group = GS * pmtp_rows_per_slot; // the group's slots const bool pmtp = piped && piped_mtp && ver.deferred_commit_on() && pmtp_rows_per_group <= batch_max_t(); if (piped && batch_mtp && !pmtp) // #1413: said, not silent std::fprintf(stderr, "strata generate: WARNING: --batch-groups %d runs the pipelined path, which builds one row per slot: " "--batch-mtp's per-slot MTP drafts do not run there (their drafters still hold VRAM, about 0.9 GB per " "slot). Drop --batch-mtp, or use --batch-groups 1.\n", o.batch_groups); if (GS > strata::kernels::kVerifyMaxT && !batch_mtp) { // (slots_in_windows keeps it so: a group's window is // PGroup's rows, and the serial windows reach only the first kVerifyMaxT slots) std::fprintf(stderr, "strata generate: --batch %d in %d group%s: more than %d rows per window\n", o.batch, std::max(o.batch_groups, 1), o.batch_groups > 1 ? "s" : "", (int) strata::kernels::kVerifyMaxT); return 1; } struct PGroup { bool inflight = false; int stage = 0; ///< the stage it runs on or waits for int32_t tok[strata::kernels::kVerifyMaxT] = {}; int64_t pos[strata::kernels::kVerifyMaxT] = {}; int64_t since = 0; ///< tick it started waiting (fairness) int S = 0; ///< slots in its window: up to its last active one (idle ones cost rows) int active = 0; ///< live slots at launch; S can also include idle padding rows Clock::time_point started; ///< the group window's first stage launch // STRATA_PIPED_MTP (pmtp): S counts ROWS - each of the group's slots' token, then that slot's proposals - at // hand-off rows [hbase, hbase + S) int rows[strata::kernels::kVerifyMaxT] = {}; int hbase = 0; }; std::vector pg((size_t) (piped ? o.batch_groups : 0)); std::vector stage_group((size_t) n_pipe, -1); int64_t pipe_tick = 0, rr = 0; auto pipe_inflight = [&] { for (const PGroup& x : pg) if (x.inflight) return true; return false; }; auto group_active = [&](int gi) { for (int t = 0; t < GS; ++t) if (bs[(size_t) (gi * GS + t)].active) return true; return false; }; // STRATA_TRACE: the drain before the line in hand (an admission's first phase), and when the first rows came // after a batch admission (the pipeline's refill after BADM) or after a drain for another line (drain + refill) double line_drain_ms = 0.0, adm_drain_ms = 0.0; const char* rows_wait = nullptr; // what the next rows are timed from (rows_wait_t) Clock::time_point rows_wait_t{}; // STRATA_PIPED_CONCURRENT (read_part): while a prompt is read on a thread of its own, the slots' doorbells are // served on another (conc_serving); between windows that thread waits on bell_cv and a launch wakes it (a // timed sleep is a whole timer tick on Windows, up to 15.6 ms, and the window's first layer would wait for it) bool conc_serving = false; std::mutex bell_mu; std::condition_variable bell_cv; std::atomic bell_waiting{false}; // STRATA_PIPED_MTP: a slot whose next proposals are drafting (its chain in flight on the drafter's stream), and // per slot the event after the copy of its rows on the last stage's stream, which the chain waits for std::vector pm_drafting(bs.size(), 0); std::vector pm_copied(pmtp ? bs.size() : 0, nullptr); if (pmtp) { const strata::core::OnDevice on_last(stage_verifier(n_pipe - 1).device()); for (cudaEvent_t& e : pm_copied) if (cudaEventCreateWithFlags(&e, cudaEventDisableTiming) != cudaSuccess) { std::fprintf(stderr, "strata serve: STRATA_PIPED_MTP: event creation failed\n"); return 1; } } // the chain of slot b has landed: its proposals are the slot's next drafts (1), still drafting (0), or an error (-1) auto pmtp_poll_draft = [&](int b, bool wait) -> int { if (!pm_drafting[(size_t) b]) return 1; for (;;) { const int r = slot_mtp[(size_t) b]->chain_poll(err); if (r < 0) { std::printf("ERR batch MTP slot %d: %s\n", b, err.c_str()); return -1; } if (r == 1) break; if (!wait) return 0; } pm_drafting[(size_t) b] = 0; // the first proposal always; another while the draft layer was at least --spec-min-p sure of the one before // (the solo path's rule, MtpDrafter::draft) BSlot& sl = bs[(size_t) b]; const int32_t* tok = slot_mtp[(size_t) b]->chain_tok(); const float* prob = slot_mtp[(size_t) b]->chain_prob(); sl.n_drafts = 1; sl.draft[0] = tok[0]; while (sl.n_drafts < pm_drafts && prob[sl.n_drafts - 1] >= (float) o.spec_min_p) { sl.draft[(size_t) sl.n_drafts] = tok[sl.n_drafts]; ++sl.n_drafts; } sl.draft_ready = true; return 1; }; // STRATA_PIPED_MTP: the last stage has picked for group gi's window (its slot's token and G.S - 1 proposals). // Judge the proposals, queue every stage's commit of the kept rows (each stage runs it before that group's next // window there: the same stream), emit them, and start drafting the next proposals. auto pmtp_verdict = [&](PGroup& G, strata::core::Verifier& vk, const int32_t* outb) -> bool { auto is_eos = [&](int32_t y) { return std::find(o.eos_ids.begin(), o.eos_ids.end(), (int64_t) y) != o.eos_ids.end(); }; // each slot of the group owns a contiguous block of the window's rows: its token, then its own proposals struct Blk { int b = 0, f = 0, n = 0, keep = 1; }; std::vector blks; std::vector keep(bs.size(), 1); for (int t = 0; t < G.S;) { const int b = G.rows[t]; const int f = t; while (t < G.S && G.rows[t] == b) ++t; BSlot& sl = bs[(size_t) b]; // proposal j stands when the target picked it after the row before it (and every earlier one stood); the // group was started only with proposals there is room to emit Blk blk; blk.b = b; blk.f = f; blk.n = t - f; while (blk.keep < blk.n && !sl.stop && outb[f + blk.keep - 1] == G.tok[f + blk.keep] && !is_eos(outb[f + blk.keep - 1])) ++blk.keep; keep[(size_t) b] = blk.keep; bt_accepted += blk.keep - 1; bt_tokens += blk.n - 1; // (proposals checked) blks.push_back(blk); } for (int k = 0; k < n_pipe; ++k) if (!stage_verifier(k).batch_commit_rows(G.rows, G.S, G.hbase, keep.data(), G.tok, G.pos, err)) { std::printf("ERR %s\n", err.c_str()); return false; } // #879: a row with non-finite logits: the slot that owns it ends, nothing of it is emitted for (int t = 0; t < G.S; ++t) if (vk.nonfinite_in(t)) { const int b = G.rows[t]; BSlot& sl = bs[(size_t) b]; std::fprintf(stderr, "strata batch: non-finite logits (#879) in slot %d at position %lld: it ends (BDONE " "nonfinite) and the next request reads its prompt from token 0\n", b, (long long) sl.p); const double ms = std::chrono::duration(Clock::now() - sl.t0).count(); std::printf("BDONE %d %lld nonfinite %.1f\n", b, (long long) sl.produced, ms); sl.active = false; sl.cached = false; sl.draft_ready = false; sl.checks.clear(); nan_flush = true; } for (const Blk& blk : blks) { BSlot& sl = bs[(size_t) blk.b]; if (!sl.active) continue; // it ended above (non-finite logits) or before this window for (int j = 0; j < blk.keep; ++j) { const int32_t y = outb[blk.f + j]; std::printf("BT %d %d\n", blk.b, (int) y); ++sl.produced; ++bt_rows; ++pipe_rows; strata::core::slot_hold_emitted(sl.hold, (int64_t) y); const char* fin = is_eos(y) ? "stop" : sl.stop ? "cancel" : sl.produced >= sl.max_new ? "length" : strata::core::slot_hold_reached(sl.hold, sl.produced, sl.max_new) ? "hold" : sl.p + 2 > o.max_context ? "length" : nullptr; sl.ids.push_back(G.tok[blk.f + j]); if (fin != nullptr) { const double ms = std::chrono::duration(Clock::now() - sl.t0).count(); std::printf("BDONE %d %lld %s %.1f\n", blk.b, (long long) sl.produced, fin, ms); sl.active = false; sl.draft_ready = false; // a cache again (#857), as on the pipelined path without drafts: final once its commits have run // (pmtp_settle, before anything reads the slot's sessions) sl.cached = o.prompt_cache > 0 && !sl.img && !sl.tainted; break; } sl.x = y; sl.p += 1; } } // the next proposal: each slot's drafter catches up on ITS OWN rows of this window and drafts from the last // kept one, as a chain on its own stream (pmtp_poll_draft collects it before the group's next window). The // rows - the last stage's final residuals - are copied on THAT stage's stream, so its next window, which // rewrites them, runs after the copy; the chain waits for the copy. const size_t stride = (size_t) g.hc * (size_t) g.n_embd; for (const Blk& blk : blks) { BSlot& sl = bs[(size_t) blk.b]; if (!sl.active) continue; // it ended: no more drafts for it const strata::core::OnDevice on_slot_mtp(slot_mtp[(size_t) blk.b]->device()); sl.draft_ready = false; const float* src = vk.final_R_all() + (size_t) blk.f * stride; if (cudaMemcpyAsync(slot_mtp_rows[(size_t) blk.b].get(), src, (size_t) blk.n * stride * sizeof(float), cudaMemcpyDeviceToDevice, vk.stream()) != cudaSuccess || cudaEventRecord(pm_copied[(size_t) blk.b], vk.stream()) != cudaSuccess || cudaStreamWaitEvent(slot_mtp[(size_t) blk.b]->stream(), pm_copied[(size_t) blk.b], 0) != cudaSuccess || !slot_mtp[(size_t) blk.b]->chain_launch(blk.n, outb + blk.f, G.pos[blk.f], blk.keep - 1, nullptr, 0, pm_drafts, 0, err)) { std::printf("ERR batch MTP slot %d: %s\n", blk.b, err.empty() ? "the proposal's chain did not start" : err.c_str()); return false; } pm_drafting[(size_t) blk.b] = 1; } return true; }; // STRATA_PIPED_MTP: the commits queued after the verdicts have run on every stage, so whatever reads a slot's // sessions next (an admission, a parked conversation, the solo path taking a slot back) sees its final state auto pmtp_settle = [&]() -> bool { if (!pmtp) return true; for (int b = 0; b < (int) bs.size(); ++b) // (a chain in flight would refuse the drafter's next use) if (pmtp_poll_draft(b, true) < 0) return false; for (int k = 0; k < n_pipe; ++k) { strata::core::Verifier& vk = stage_verifier(k); const strata::core::OnDevice on_k(vk.device()); if (cudaStreamSynchronize(vk.stream()) != cudaSuccess) { std::printf("ERR a pipelined commit failed on stage %d\n", k + 1); return false; } } return true; }; // STRATA_PIPE_ADAPT_EVERY=N (opt-in; unset or 0: off, as before): the pipelined groups start no adaptive-tier round // of their own (batch_step starts one every --adapt-every windows; pump below never does), so under steady parallel // load the VRAM tier only moves when the slots go back to the solo path, and a fresh engine keeps its start-up // profile for minutes. With N > 0, after N group windows the pipeline starts no new group, lets the ones in flight // finish, and runs one round there as batch_step runs it between serial windows (nothing in flight reads a cache // slot; the swapped-in experts land before the next launch), then goes on. Never while a prompt is read beside // the slots (its loan of cache slots), nor with --adapt-async (its own ticks). // (the rule: batch_groups.hpp pipe_adapt_every / pipe_adapt_due, tested in batch_groups_test) const int pipe_adapt_every = strata::program::batch_groups::pipe_adapt_every(std::getenv("STRATA_PIPE_ADAPT_EVERY")); int64_t pa_windows = 0, pa_last = 0, pa_rounds = 0, pa_swaps = 0; double pa_ms = 0; auto pa_due = [&] { strata::program::batch_groups::PipeAdapt p; p.every = pipe_adapt_every; p.tier_on = !drive.d.usage.empty() && o.adapt_every > 0; p.async_tier = (bool) ajob; p.prompt_read = in_prompt_read; p.swaps_pending = !pending.empty(); p.windows = pa_windows; p.last = pa_last; return strata::program::batch_groups::pipe_adapt_due(p); }; // STRATA_P4_TIMING=1 / STRATA_P4_TRACE=PATH: where a pipelined window's time goes (pipe_probe.hpp; off: a branch) strata::program::PipeProbe p4(n_pipe, pg.size()); // one turn: serve every running stage, hand finished groups on, start what can start auto pump = [&](bool may_start) -> bool { ++pipe_tick; const strata::program::PipeProbe::PumpScope p4_scope(p4); if (p4.timing()) { int nb = 0, nf = 0; for (int k = 0; k < n_pipe; ++k) if (stage_group[(size_t) k] >= 0) ++nb; for (const PGroup& x : pg) if (x.inflight) ++nf; p4.busy(nb, nf); // a stage free with no group waiting at it = starved by the stage before, else it was only idle a moment for (int k = 1; k < n_pipe; ++k) { if (stage_group[(size_t) k] >= 0) continue; bool ready = false; for (size_t g2 = 0; g2 < pg.size() && !ready; ++g2) ready = pg[g2].inflight && pg[g2].stage == k; p4.free_stage(k, ready); } } if (bt_windows == 0 && !pipe_inflight()) { bt_start = Clock::now(); p4.span_start(bt_start); bt_wait0 = ver.ms_wait; bt_pool0 = ver.ms_pool; bt_miss0 = drive.d.multi_misses; bt_hits0 = drive.d.cache_hits; bt_pcie0 = drive.d.pcie_experts; if (pc.on()) pc.begin(pc_ex(), (int) g.n_layers); } for (int k = 0; k < n_pipe; ++k) { const int gi = stage_group[(size_t) k]; if (gi < 0) continue; strata::core::Verifier& vk = stage_verifier(k); const auto p4_p0 = p4.now(); const int r = vk.batch_poll(win_pool_fn, win_pool_user, err); p4.polled(p4_p0); if (r < 0) { std::printf("ERR %s\n", err.c_str()); return false; } if (r == 0) continue; p4.done(k, gi); if (batch_telemetry_enabled) stage_in_flight.complete(k, Clock::now()); stage_group[(size_t) k] = -1; PGroup& G = pg[(size_t) gi]; if (k + 1 < n_pipe) { G.stage = k + 1; G.since = pipe_tick; continue; } // the last stage: the group's picks const int32_t* outb = vk.batch_out(); if (pmtp && !pmtp_verdict(G, vk, outb)) return false; const strata::program::PipeProbe::VerdictScope p4_verdict(p4); for (int t = 0; t < G.S && !pmtp; ++t) { BSlot& sl = bs[(size_t) (gi * GS + t)]; if (!sl.active) continue; if (vk.nonfinite_in(t)) { // #879: the slot ends, nothing emitted std::fprintf(stderr, "strata batch: non-finite logits (#879) in slot %d at position %lld: it " "ends (BDONE nonfinite) and the next request reads its prompt from token 0\n", gi * GS + t, (long long) sl.p); const double ms = std::chrono::duration(Clock::now() - sl.t0).count(); std::printf("BDONE %d %lld nonfinite %.1f\n", gi * GS + t, (long long) sl.produced, ms); sl.active = false; sl.cached = false; sl.checks.clear(); nan_flush = true; continue; } const int32_t y = outb[t]; std::printf("BT %d %d\n", gi * GS + t, (int) y); ++sl.produced; ++bt_rows; ++pipe_rows; strata::core::slot_hold_emitted(sl.hold, (int64_t) y); const bool eos = std::find(o.eos_ids.begin(), o.eos_ids.end(), (int64_t) y) != o.eos_ids.end(); const char* fin = eos ? "stop" : sl.stop ? "cancel" : sl.produced >= sl.max_new ? "length" : strata::core::slot_hold_reached(sl.hold, sl.produced, sl.max_new) ? "hold" : sl.p + 2 > o.max_context ? "length" : nullptr; sl.ids.push_back(sl.x); if (fin != nullptr) { const double ms = std::chrono::duration(Clock::now() - sl.t0).count(); std::printf("BDONE %d %lld %s %.1f\n", gi * GS + t, (long long) sl.produced, fin, ms); sl.active = false; // a pipelined slot is a cache again (#857: a request left alone in its slot goes back to the solo path with its // drafts): its state is final once its last window has left the last stage. A later group window whose pad // row writes this slot clears the flag (below, where the group starts), so a stale state is never reused sl.cached = o.prompt_cache > 0 && !sl.img && !sl.tainted; } else { sl.x = y; sl.p += 1; } } std::fflush(stdout); if (rows_wait != nullptr) { std::fprintf(stderr, "strata trace: first rows %.1f ms after %s\n", std::chrono::duration(Clock::now() - rows_wait_t).count(), rows_wait); rows_wait = nullptr; } ++bt_windows; ++pa_windows; G.inflight = false; report_batch_window(G.S, G.active, !pipe_inflight() && !batch_on(), G.started); pc.window(G.S, G.active); } // start waiting groups on free stages, the longest waiting first; a new step on stage 0 round-robin for (int k = n_pipe - 1; k >= 0; --k) { if (stage_group[(size_t) k] >= 0) continue; int pick = -1; if (k > 0) { for (int gi = 0; gi < (int) pg.size(); ++gi) if (pg[(size_t) gi].inflight && pg[(size_t) gi].stage == k && (pick < 0 || pg[(size_t) gi].since < pg[(size_t) pick].since)) pick = gi; if (pick < 0) continue; } else { if (!may_start || pa_due()) continue; // STRATA_PIPE_ADAPT_EVERY: a round is due, the pipeline empties first for (int j = 0; j < (int) pg.size() && pick < 0; ++j) { const int gi = (int) ((rr + j) % (int64_t) pg.size()); if (pg[(size_t) gi].inflight || !group_active(gi)) continue; if (pmtp) { // its slots' proposal chains still running: another group goes first bool ready = true; for (int t = 0; t < GS; ++t) { const int dr = pmtp_poll_draft(gi * GS + t, false); if (dr < 0) return false; if (dr == 0) { ready = false; break; } } if (!ready) continue; } pick = gi; } if (pick < 0) continue; rr = pick + 1; PGroup& G = pg[(size_t) pick]; G.S = 0; if (pmtp) { // the group's slots: each its token, then its own proposals - as many as could be emitted G.hbase = pmtp_rows_per_group * pick; G.S = 0; G.active = 0; for (int t = 0; t < GS; ++t) { const int b = pick * GS + t; const BSlot& sl = bs[(size_t) b]; if (!sl.active) continue; // an idle slot carries no row (its state is left untouched) ++G.active; G.rows[G.S] = b; G.tok[G.S] = sl.x; G.pos[G.S] = sl.p; ++G.S; int nd = sl.draft_ready && !sl.stop ? sl.n_drafts : 0; nd = (int) std::min(nd, std::min(strata::core::slot_cap(sl.max_new, sl.hold) - sl.produced - 1, o.max_context - sl.p - 2)); for (int j = 0; j < nd; ++j) { G.rows[G.S] = b; G.tok[G.S] = sl.draft[(size_t) j]; G.pos[G.S] = sl.p + 1 + j; ++G.S; } } if (G.S == 0) { G.inflight = false; continue; } // every slot of the group went idle } else { G.active = 0; for (int t = 0; t < GS; ++t) if (bs[(size_t) (pick * GS + t)].active) { G.S = t + 1; ++G.active; } for (int t = 0; t < G.S; ++t) { BSlot& sl = bs[(size_t) (pick * GS + t)]; G.tok[t] = sl.active ? sl.x : 0; G.pos[t] = sl.active ? sl.p : 0; if (!sl.active) sl.cached = false; // its pad row writes its state } } G.inflight = true; G.stage = 0; if (batch_telemetry_enabled) G.started = Clock::now(); // (with the doorbells on their own thread, a failure it set for a window that left this stage is // not cleared unseen) if (conc_serving && drive.d.failed) { std::printf("ERR %s\n", drive.d.fail ? drive.d.fail : "the expert pool failed"); return false; } drive.d.failed = false; apply_pending(false); } PGroup& G = pg[(size_t) pick]; strata::core::progress().busy.store(true); if (batch_telemetry_enabled) stage_in_flight.launch(k, Clock::now()); if (k == 0) { // the penalised slots' reply tails for the group's rows (the last stage draws them) int grows[strata::kernels::kVerifyMaxT] = {}; for (int t = 0; t < G.S && t < (int) strata::kernels::kVerifyMaxT; ++t) grows[t] = pmtp ? G.rows[t] : pick * GS + t; for (int t = 0; t < G.S && t < (int) strata::kernels::kVerifyMaxT; ++t) { const BSlot& ps = bs[(size_t) grows[t]]; if (ps.pen_n <= 0 || (t > 0 && grows[t - 1] == grows[t])) continue; const int64_t from = std::max(ps.reply0, (int64_t) ps.ids.size() - ps.pen_n); ver.set_slot_history(grows[t], ps.ids.data() + from, (int64_t) ps.ids.size() - from); } } const auto p4_l0 = p4.now(); if (!(pmtp ? stage_verifier(k).batch_launch_rows(G.rows, G.S, G.hbase, G.tok, G.pos, err) : stage_verifier(k).batch_launch(pick * GS, G.S, G.tok, G.pos, err))) { std::printf("ERR %s\n", err.c_str()); return false; } p4.launched(k, pick, p4_l0); stage_group[(size_t) k] = pick; if (conc_serving) { // the doorbell thread may be waiting between windows: the launch above is seen std::atomic_thread_fence(std::memory_order_seq_cst); if (bell_waiting.load(std::memory_order_relaxed)) { std::lock_guard lk(bell_mu); bell_cv.notify_one(); } } } if (drive.d.failed) { std::printf("ERR %s\n", drive.d.fail ? drive.d.fail : "the expert pool failed"); return false; } if (pa_due() && !pipe_inflight()) { // STRATA_PIPE_ADAPT_EVERY: the pipeline is empty - one round, as batch_step if (pmtp && !pmtp_settle()) return false; // STRATA_PIPED_MTP: the queued commits and draft chains are done first const Clock::time_point ta = Clock::now(); pa_last = pa_windows; if (!adapt()) { std::printf("ERR an adaptive refill failed\n"); return false; } ++pa_rounds; pa_swaps += (int64_t) pending.size(); apply_pending(true); // the copies land and the tables follow (the next launch plans from them) pa_ms += std::chrono::duration(Clock::now() - ta).count(); } if (batch_telemetry_enabled) { const auto sample = stage_in_flight.sample(Clock::now(), !pipe_inflight() && !batch_on()); if (sample) { std::printf("PSTAT %zu %lld", sample->in_flight_us.size(), (long long) sample->elapsed_us); for (const int64_t busy : sample->in_flight_us) std::printf(" %lld", (long long) busy); std::printf("\n"); std::fflush(stdout); } } // every slot done: the last commits have run before anything reads a slot (between windows nothing does) if (pmtp && !pipe_inflight() && !batch_on() && !pmtp_settle()) return false; if (!pipe_inflight() && !batch_on() && bt_windows > 0) { // all idle: the timing line, as batch_step const double w = (double) bt_windows, wall = std::chrono::duration(Clock::now() - bt_start).count(); p4.span_end(wall); pc.flush(wall, pc_ex()); char pa_txt[160] = ""; if (pipe_adapt_every > 0) std::snprintf(pa_txt, sizeof pa_txt, "; adaptive tier (STRATA_PIPE_ADAPT_EVERY): %lld rounds, %lld experts " "swapped in, %.0f ms", (long long) pa_rounds, (long long) pa_swaps, pa_ms); std::fprintf(stderr, "strata batch (pipelined, %d groups of %d): %lld group-steps, %lld rows in %.0f ms = " "%.1f rows/s (admissions included)%s", o.batch_groups, GS, (long long) bt_windows, (long long) bt_rows, wall, 1000.0 * bt_rows / std::max(wall, 1e-9), pa_txt); if (pmtp) std::fprintf(stderr, " (%lld of %lld MTP proposals kept)", (long long) bt_accepted, (long long) bt_tokens); std::fprintf(stderr, "\n"); p4.flush(); pa_rounds = pa_swaps = 0; pa_ms = 0; for (int k = 0; k < n_pipe; ++k) { const std::string pr = stage_verifier(k).profile_report(); if (!pr.empty()) std::fprintf(stderr, "strata batch GPU stages, stage %d (ms/window):%s\n", k + 1, pr.c_str()); } bt_windows = bt_rows = bt_tokens = bt_accepted = 0; // (not while a prompt is read in a request: its windows ran beside it, and the watchdog stays on for // the rest of the read, STRATA_PIPED_CONCURRENT; the request's end turns it off) if (!in_prompt_read) strata::core::progress().busy.store(false); } return true; }; auto pipe_drain = [&]() -> bool { while (pipe_inflight()) if (!pump(false)) return false; return pmtp_settle(); }; for (;;) { line_drain_ms = 0.0; strata::core::manifest::instance().flush_if_dirty("request"); // STRATA_MANIFEST: what the last request added (a no-op when off) // Between requests (nothing in flight): the park pools' upkeep, which the park and the prompt read leave alone if (!batch_on() && !(piped && pipe_inflight()) && !strata::core::progress().busy.load()) { pool_topup(); segpool_kick(); } if (batch_on() || (piped && pipe_inflight())) { if (!try_next_line(line)) { if (!(piped ? pump(true) : batch_step())) return 1; continue; } // a request reads its prompt through every stage: the groups in flight finish first // (STRATA_PIPE_BYIELD_NODRAIN: not for a BYIELD, which is dropped below) if (piped && line.rfind("BSTOP ", 0) != 0 && !(pipe_byield_nodrain_env() && line.rfind("BYIELD", 0) == 0)) { const int in_flight = (trace || pc.on()) ? (int) std::count_if(pg.begin(), pg.end(), [](const PGroup& G) { return G.inflight; }) : 0; const auto td = Clock::now(); if (!pipe_drain()) return 1; if (pc.on()) pc.drain(line, in_flight, std::chrono::duration(Clock::now() - td).count()); if (trace) { // STRATA_TRACE: what the drain before this line cost (BGEN: an admission's first phase) line_drain_ms = std::chrono::duration(Clock::now() - td).count(); std::fprintf(stderr, "strata trace: drain for %.*s: %d groups in flight, %.1f ms\n", (int) std::min(line.find(' '), line.size()), line.c_str(), in_flight, line_drain_ms); const bool timed = in_flight > 0 && line.rfind("BYIELD", 0) == 0; rows_wait = timed ? "the drain for BYIELD started" : nullptr; rows_wait_t = td; std::fflush(stderr); } } } else if (!next_line(line)) { break; } // --batch: BSTOP ends that slot at its next batch window; BGEN ... reads the // request's prompt and first token as a GEN 1, then continues it in that slot if (line.rfind("BSTOP ", 0) == 0) { const int b = std::atoi(line.c_str() + 6); if (b >= 0 && b < (int) bs.size()) bs[(size_t) b].stop = true; continue; } if (line.rfind("BCO ", 0) == 0) { // BCO : kept for the next BGEN CoReq cr; char* e1 = nullptr; cr.slot = (int) std::strtol(line.c_str() + 4, &e1, 10); for (const char* q = e1; q != nullptr && *q != '\0';) { while (*q == ' ' || *q == ',') ++q; if (*q == '\0') break; char* e2 = nullptr; cr.ids.push_back((int64_t) std::strtoll(q, &e2, 10)); if (e2 == q) { cr.ids.clear(); break; } q = e2; } if (cr.slot >= 0 && cr.slot < (int) bs.size() && cr.ids.size() >= 3) co_pending.push_back(std::move(cr)); continue; } if (line.rfind("BYIELD", 0) == 0) { // for a prompt read that has ended meanwhile if (trace && piped) std::fprintf(stderr, "strata trace: BYIELD dropped, %d groups in flight\n", (int) std::count_if(pg.begin(), pg.end(), [](const PGroup& G) { return G.inflight; })); continue; } if (line.rfind("VRAM", 0) == 0) { // #533 (above): between requests, not a request std::string verr; if (batch_on()) verr = "VRAM: not while batch slots are decoding"; else vram_command(line, verr); if (!verr.empty()) std::printf("ERR %s\n", verr.c_str()); std::fflush(stdout); continue; } // a command may touch the expert cache (a request lends slots, a K/V growth moves them, a session restore // quiesces it): a round of the asynchronous tier that the batch windows left in flight lands first if (!adapt_tick(true)) { std::printf("ERR an adaptive refill failed\n"); return 1; } admit_slot = -1; if (line.rfind("BGEN ", 0) == 0 || line.rfind("BGENI ", 0) == 0) { const bool bimg = line.rfind("BGENI ", 0) == 0; char* e1 = nullptr; const long b = std::strtol(line.c_str() + (bimg ? 6 : 5), &e1, 10); char* e2 = nullptr; const long long mn = std::strtoll(e1, &e2, 10); if (bs.empty() || b < 0 || b >= (long) bs.size() || bs[(size_t) b].active || mn < 1 || e2 == e1) { std::printf("ERR BGEN: no such free slot (--batch %d) or a bad max_new\n", o.batch); std::fflush(stdout); continue; } admit_slot = (int) b; admit_max_new = mn; adm_drain_ms = line_drain_ms; co_set = std::move(co_pending); co_pending.clear(); line = std::string(bimg ? "GENI 1" : "GEN 1") + e2; } // #477: every --expert-profile-save-every minutes, before the next request (at QUIT: after the loop) if (!heat.empty() && line != "QUIT" && o.expert_profile_save_min > 0 && Clock::now() - profile_saved_at >= std::chrono::duration(o.expert_profile_save_min * 60.0)) save_profile("periodic"); if (line != "QUIT") save_ram_profile("before a request"); if (line == "QUIT") break; // the watchdog watches a request from here until this iteration ends, whichever way it ends struct BusyScope { BusyScope() { strata::core::progress().allow_until_ms.store(0); strata::core::progress().busy.store(true); strata::core::progress_at("request"); } ~BusyScope() { strata::core::progress().busy.store(false); strata::core::progress().allow_until_ms.store(0); strata::core::progress_at("idle"); g_gpu_pause_idle.idle(gpu_pause_now()); // the gap to the next request starts here, whichever way this one ended } } busy_scope; { // AMD on Linux: the driver's GPU pause counter, once per request; a pause since the engine went idle gets its own line const int64_t pause_begin = gpu_pause_now(); const std::string gap_line = g_gpu_pause_idle.begin(pause_begin); if (!gap_line.empty()) std::fprintf(stderr, "%s\n", gap_line.c_str()); g_req_gpu_pause_ms.store(pause_begin); } { // #2065: said, never changed - the free VRAM now (the verify windows' captures and the batch layouts // eat into what startup reported), once per 128 MiB lower it gets size_t vf_b = 0, vt_b = 0; if (cudaMemGetInfo(&vf_b, &vt_b) == cudaSuccess) { const int64_t vf = (int64_t) (vf_b >> 20); g_req_vram_free_mib.store(vf); static int64_t low_said_at = INT64_MAX; static bool uma_said = false; if (vf < kVramSafeMib && g_uma_pinned_complement.load()) { // Round 0216: a note, once, no reserve advice (see g_uma_pinned_complement) if (!uma_said) { uma_said = true; std::fprintf(stderr, "strata serve: Only %lld MiB of graphics memory reported free at the start of this request. " "On this PC the figure reads low because the graphics chip shares the system memory. " "If decode drops to a few tok/s, lower --max-context.\n", (long long) vf); } } else if (vf < kVramSafeMib && vf + 128 <= low_said_at) { low_said_at = vf; std::fprintf(stderr, "strata serve: WARNING: only %lld MiB of VRAM free at the start of this request " "(below %lld MiB): when the card is this full the driver can page GPU memory " "to system RAM, decode falls to a few tok/s and a window may never finish " "(#2065). Add --vram-reserve-mib %lld to the config's args, or lower " "--max-context / --batch\n", (long long) vf, (long long) kVramSafeMib, (long long) ((o.vram_reserve_mib + (kVramSafeMib - vf) + 63) / 64 * 64)); } } } stop_req.store(false); // a STOP that arrived between requests is stale err.clear(); // Disk sessions: SAVE | RESTORE , between requests (the path runs to the end of the line, // UTF-8). The file holds what a parked conversation holds (conversation_file.hpp). Answers: SAVED / // RESTORED ; SERR for a refusal // or failure that leaves the engine in step (the live session as it was, unless published=1 says the new // file already replaced the old one); FATAL (and the engine exits) for a restore transfer that // failed after the device state was touched. On the way: SESSION after every block of // the file moved (at most 16 MiB), and SWAIT before a step that blocks in one call // (fingerprint file, state capture, file flush, rename + folder flush, validation, device transfer): // that step is allowed (session_phase_limit_s) by the watchdog and by the server, no more. // (A verifier commit that fails before the command still answers ERR and exits, as for a request.) if (line.rfind("SAVE ", 0) == 0 || line.rfind("RESTORE ", 0) == 0) { const bool save = line[0] == 'S'; const std::string path = line.substr(save ? 5 : 8); const auto t0 = Clock::now(); auto ms = [&] { return std::chrono::duration(Clock::now() - t0).count(); }; auto refuse = [&](const std::string& why, strata::core::SessionError kind = strata::core::SessionError::invalid, bool published = false) { std::fprintf(stderr, "strata serve: session %s %s: %s\n", save ? "save" : "restore", path.c_str(), why.c_str()); std::string one = why; // one protocol line for (char& c : one) if (c == '\n' || c == '\r') c = ' '; std::printf("SERR %s %d %s\n", strata::core::session_error_name(kind), published ? 1 : 0, one.c_str()); std::fflush(stdout); err.clear(); }; auto moving = [&](uint64_t done, uint64_t total) { strata::core::progress_at(save ? "writing a session file, MiB" : "reading a session file, MiB", (int64_t) (done >> 20)); strata::core::progress_allow(0); // a block moved: the ordinary watchdog limit again, and a beat std::printf("SESSION %llu %llu\n", (unsigned long long) done, (unsigned long long) total); std::fflush(stdout); }; // a step that blocks in one call: its explicit allowance, on both sides, announced before it starts auto blocking = [&](const char* phase, uint64_t bytes) { const int64_t s = strata::core::session_phase_limit_s(bytes); strata::core::progress_at(phase); strata::core::progress_allow(s); std::printf("SWAIT %s %lld\n", phase, (long long) s); std::fflush(stdout); }; strata::core::progress_at(save ? "saving a session" : "restoring a session"); // the background copy of the last turn checkpoint (STRATA_CKPT_ASYNC) lands before anything below copies, frees // or writes the checkpoints (a join inside the session file writer would match only the copy of a checkpoint) strata::core::conversation_checkpoint_join(nullptr); strata::core::conversation_park_join(); // (STRATA_PARK_ASYNC: the last park's K/V) if (path.empty()) { refuse("missing path"); continue; } if (stages.empty() && multi_gpu) { refuse("session files do not support --layer-split"); continue; } if (o.peer_device >= 1) { refuse("session files do not support --peer-device"); continue; } if (o.batch > 0) { refuse("session files do not support --batch (parallel requests)"); continue; } if (o.prompt_cache <= 0) { refuse("session files need --prompt-cache > 0"); continue; } if (!ver.wait_commit(err)) { std::printf("ERR %s\n", err.c_str()); return 1; } strata::core::SessionFileIdentity id; try { if (!session_identity(id, err, [&] { blocking("fingerprint", 2u << 20); })) { refuse(err, strata::core::SessionError::io); continue; } } catch (const std::bad_alloc&) { refuse("session identity: out of memory", strata::core::SessionError::memory); continue; } catch (const std::exception& e) { refuse(std::string("session identity: ") + e.what(), strata::core::SessionError::io); continue; } if (save) { if (!live_ok || live.empty()) { refuse("no complete session to save"); continue; } size_t bytes = 0, kept = 0; double capture_ms = 0; try { // RAM PREFLIGHT for the save (not a reservation), BEFORE anything is copied: the deepest // checkpoint is chosen by reference, and the copies it will take (the list below and the one // in `meta`), the copied live running state with its tokens and images, the K/V source // directory and the 16 MiB write buffer are asked for above the parking floor. Only the // deepest checkpoint goes to disk (the next turn's resume point); the K/V is streamed from // the authoritative pools straight into the file, without a full host capture. strata::core::SessionSaveLive sl; { strata::core::ConversationStateSizes z; std::string why; uint64_t state = UINT64_MAX; // unknown sizes: the preflight refuses rather than guesses if (strata::core::conversation_session_sizes(g, ss, z, why)) { const uint64_t q = (uint64_t) std::max(ss.qsa_alloc, 0); const uint64_t per = (uint64_t) z.tail + z.dead + z.block_pos; if (q == 0 || per <= (UINT64_MAX - z.gdn - z.ple) / q) state = z.gdn + z.ple + q * per; } sl.state_bytes = state; sl.tokens = live.size(); sl.images = live_imgs.size(); sl.kv_layers = (uint64_t) std::max(ss.qsa_alloc, 0) + 1; } const uint64_t floor = (uint64_t) o.conversation_cache_min_free_mib << 20; pools_budget.shrink((size_t) -1); // (the park pools' idle memory goes back before the RAM checks of a session save) if (o.session_save_reclaim) { const auto freed = strata::core::session_save_reclaim( checks, conversations, sl, floor, strata::core::available_host_bytes); if (freed.bytes || freed.checkpoints || freed.parked) { // A removed tail must not mark a later checkpoint at this length as a tail. if (tail_ckpt_len >= 0 && std::none_of(checks.begin(), checks.end(), [&](const auto& c) { return int64_t(c.ids.size()) == tail_ckpt_len; })) tail_ckpt_len = -1; std::fprintf(stderr, "strata serve: save reclaimed %zu checkpoints, %zu parked, " "%zu host bytes; checking RAM again\n", freed.checkpoints, freed.parked, freed.bytes); } } auto admit = [&](uint64_t need, std::string& why) { const auto mem = strata::core::sample_host_memory(); const std::optional avail = mem ? std::optional(mem->available) : std::nullopt; if (strata::core::conversation_memory_admit(avail, need, floor)) return true; why = "not enough RAM to save the session (" + (need == UINT64_MAX ? std::string("unknown") : std::to_string(need >> 20)) + " MiB plus a floor of " + std::to_string((long long) o.conversation_cache_min_free_mib) + " MiB needed, " + ram_note(mem) + ")"; return false; }; std::vector disk_checks; std::string why; if (!strata::core::session_save_checkpoints(checks, sl, admit, disk_checks, why)) { refuse(why, strata::core::SessionError::memory); continue; } // STRATA_SESSION_CHAIN=1: the whole chain, so a restored session keeps its root (the end of the // system prompt) and the periodic checkpoints SCR restarts from, not only the deepest one static const bool save_chain = [] { const char* e = std::getenv("STRATA_SESSION_CHAIN"); return e != nullptr && e[0] == '1'; }(); if (save_chain && checks.size() > disk_checks.size()) { uint64_t chain_bytes = 0; for (const ConvCheckpoint& c : checks) chain_bytes += c.bytes(); std::string low; if (admit(chain_bytes, low)) disk_checks = checks; else std::fprintf(stderr, "strata serve: session save keeps only the deepest checkpoint: %s\n", low.c_str()); } kept = disk_checks.size(); strata::core::SessionWriteOptions wo; wo.min_free_bytes = (uint64_t) o.session_min_free_mib << 20; wo.progress = moving; wo.phase = blocking; strata::core::SessionStatus st; if (!stages.empty()) { // a layer split: one image per stage, captured as parking captures them (the draft // layer's K/V with the stage that holds the drafter), from copies of the checkpoints // moved apart into their stage parts; a checkpoint without every part is not saved const size_t n_st = stages.size(); const strata::core::QsaState* draft0 = (n_st > 0 && !mtp_first) || !use_mtp ? nullptr : &mtp.kv_state(); auto draft_of = [&](size_t k) -> const strata::core::QsaState* { return use_mtp && !mtp_first && k + 1 == n_st ? &mtp.kv_state() : nullptr; }; auto cs = strata::core::conversation_checkpoints_split(std::move(disk_checks), n_st); kept = cs.stage0.size(); strata::core::SavedConversation image; blocking("capture", sl.state_bytes == UINT64_MAX ? 0 : sl.state_bytes * (n_st + 1)); const strata::core::ConversationView view{live, live_imgs, cs.stage0, cvec_cached}; bool captured = strata::core::conversation_snapshot_save(image, view, ss, g, draft0, err); for (size_t k = 0; captured && k < n_st; ++k) { const strata::core::OnDevice on(stages[k]->dev); if (cudaDeviceSynchronize() != cudaSuccess) { err = "stage sync failed"; captured = false; break; } const strata::core::ConversationView view_k{live, live_imgs, cs.parts[k], cvec_cached}; strata::core::SavedConversation part; captured = strata::core::conversation_snapshot_save(part, view_k, stages[k]->ss, g, draft_of(k), err); if (captured) image.stage_images.push_back(std::move(part)); } if (!captured) { refuse(err, strata::core::SessionError::io); continue; } capture_ms = ms(); if (!strata::core::session_file_write(path, image, id, bytes, err, wo, &st)) { refuse(err, st.error, st.published); continue; } } else { const strata::core::ConversationView view{live, live_imgs, disk_checks, cvec_cached}; strata::core::SavedConversation meta; std::vector sources; // the live running state comes off the device in one synchronous copy blocking("capture", sl.state_bytes == UINT64_MAX ? 0 : sl.state_bytes); if (!strata::core::conversation_snapshot_sources(meta, sources, view, ss, g, mtp.kv_state(), err)) { refuse(err, strata::core::SessionError::io); continue; } capture_ms = ms(); if (!strata::core::session_file_write(path, meta, sources, id, bytes, err, wo, &st)) { refuse(err, st.error, st.published); continue; } } if (st.dir_flush_unsupported) std::fprintf(stderr, "strata serve: session saved to %s; this filesystem cannot flush a " "folder, so the new name is not flushed\n", path.c_str()); } catch (const std::bad_alloc&) { refuse("not enough RAM to save the session", strata::core::SessionError::memory); continue; } // SCR: the pads the session read go beside the file (its format has no place for them); a restore // takes them back only when the file's tokens are the ones they were saved with { const std::string pads_path = path + ".pads"; if (live_pads.empty()) { std::remove(pads_path.c_str()); } else if (std::FILE* pf = std::fopen(pads_path.c_str(), "wb")) { const uint64_t head[3] = {(uint64_t) live.size(), fnv1a(live.data(), live.size() * sizeof(int32_t)), (uint64_t) live_pads.size()}; const bool ok = std::fwrite(head, sizeof head, 1, pf) == 1 && std::fwrite(live_pads.data(), sizeof(int64_t), live_pads.size(), pf) == live_pads.size(); if (std::fclose(pf) != 0 || !ok) { std::remove(pads_path.c_str()); std::fprintf(stderr, "strata serve: session save: the pads were not written beside %s\n", path.c_str()); } } } std::fprintf(stderr, "strata serve: session saved %zu tokens, %zu of %zu checkpoints, %zu bytes to %s " "in %.1f ms (state %.1f ms)\n", live.size(), kept, checks.size(), bytes, path.c_str(), ms(), capture_ms); std::printf("SAVED %zu %zu %.1f\n", live.size(), bytes, ms()); } else { strata::core::SavedConversation image; size_t bytes = 0; try { // bounds this session can ever restore (geometry, layer range, tokens, checkpoints, every // state and K/V part), checked as the file is parsed and before each array is allocated; the // file size follows from them. The RAM the parse needs at its peak is asked first. strata::core::SessionReadLimits limits; limits.progress = moving; const uint64_t floor = (uint64_t) o.conversation_cache_min_free_mib << 20; pools_budget.shrink((size_t) -1); // (the park pools' idle memory goes back before the RAM checks of a session load) limits.admit = [floor, &o](uint64_t need, std::string& why) { const auto mem = strata::core::sample_host_memory(); const std::optional avail = mem ? std::optional(mem->available) : std::nullopt; if (strata::core::conversation_memory_admit(avail, need, floor)) return true; why = "not enough RAM to read it (" + std::to_string(need >> 20) + " MiB plus a floor of " + std::to_string((long long) o.conversation_cache_min_free_mib) + " MiB needed, " + ram_note(mem) + ")"; return false; }; if (!strata::core::conversation_session_read_limits( limits, ss, g, mtp.kv_state(), (uint64_t) o.max_context, (uint64_t) std::max(o.prompt_cache, 1), err)) { refuse(err, strata::core::SessionError::io); continue; } bool stage_limits_ok = true; for (const auto& st_k : stages) { // a layer split: every later stage's own carve strata::core::SessionReadLimits lk; if (!strata::core::conversation_session_read_limits( lk, st_k->ss, g, mtp.kv_state(), (uint64_t) o.max_context, (uint64_t) std::max(o.prompt_cache, 1), err)) { stage_limits_ok = false; break; } limits.stage_limits.push_back(std::move(lk)); } if (!stage_limits_ok) { refuse(err, strata::core::SessionError::io); continue; } strata::core::SessionStatus st; if (!strata::core::session_file_read(path, id, image, bytes, err, limits, &st)) { refuse(err, st.error); continue; } } catch (const std::bad_alloc&) { refuse("not enough RAM to read the session", strata::core::SessionError::memory); continue; } const double read_ms = ms(); // the whole image against this engine, still without any device write blocking("validate", bytes); // with a layer split the draft layer's K/V is in the image of the stage that holds the drafter const size_t n_st = stages.size(); const strata::core::QsaState* draft_main = n_st == 0 ? &mtp.kv_state() : use_mtp && mtp_first ? &mtp.kv_state() : nullptr; auto draft_of = [&](size_t k) -> const strata::core::QsaState* { return use_mtp && !mtp_first && k + 1 == n_st ? &mtp.kv_state() : nullptr; }; bool valid = image.stage_images.size() == n_st; if (!valid) err = "the file holds another number of GPU stages than this runtime"; for (size_t k = 0; valid && k < n_st; ++k) { const strata::core::OnDevice on(stages[k]->dev); valid = strata::core::conversation_snapshot_validate(image.stage_images[k], stages[k]->ss, g, draft_of(k), err); } if (!valid || !strata::core::conversation_snapshot_validate(image, ss, g, draft_main, err)) { refuse(err); continue; } // the elastic K/V (--kv-grow) maps only the cells it has grown to: make room for the file's cells if (!kvg_ensure((int64_t) image.live.ids.size() + 256, adapt_quiesce)) { refuse("the K/V cannot grow to the saved conversation: no VRAM is left", strata::core::SessionError::memory); continue; } conversations.take_reuse(); // retained K/V described the outgoing session live_ok = false; // host -> device in synchronous copies of the whole state: one bounded allowance blocking("transfer", bytes); bool transferred = strata::core::conversation_snapshot_restore(image, ss, g, draft_main, err) == strata::core::ConversationRestore::restored; for (size_t k = 0; transferred && k < n_st; ++k) { const strata::core::OnDevice on(stages[k]->dev); transferred = strata::core::conversation_snapshot_restore(image.stage_images[k], stages[k]->ss, g, draft_of(k), err) == strata::core::ConversationRestore::restored; if (transferred && cudaDeviceSynchronize() != cudaSuccess) { err = "stage sync failed"; transferred = false; } } if (!transferred) { // validated above: a failure here is a transfer failure, after device writes began - never // decode from a partial state; the server starts the engine again std::fprintf(stderr, "strata serve: session restore %s: transfer failed: %s\n", path.c_str(), err.c_str()); std::printf("FATAL restoring the session file failed after the device state was changed: %s\n", err.c_str()); std::fflush(stdout); return 1; } live = std::move(image.live.ids); live_imgs = std::move(image.live.imgs); live_pads.clear(); scr_master_ok.clear(); if (std::FILE* pf = std::fopen((path + ".pads").c_str(), "rb")) { // the pads saved beside it uint64_t head[3] = {}; std::vector pads; bool ok = std::fread(head, sizeof head, 1, pf) == 1 && head[0] == (uint64_t) live.size() && head[1] == fnv1a(live.data(), live.size() * sizeof(int32_t)) && head[2] <= live.size(); if (ok) { pads.resize((size_t) head[2]); ok = std::fread(pads.data(), sizeof(int64_t), pads.size(), pf) == pads.size(); } std::fclose(pf); for (size_t i = 0; ok && i < pads.size(); ++i) ok = pads[i] >= 0 && pads[i] < (int64_t) live.size() && live[(size_t) pads[i]] == (int32_t) scr_pad && (i == 0 || pads[i] > pads[i - 1]); if (ok) live_pads = std::move(pads); else std::fprintf(stderr, "strata serve: session restore: the pads beside %s do not match it\n", path.c_str()); } if (n_st == 0) { checks = std::move(image.checkpoints); } else { // give each checkpoint back its stage parts; none if they do not line up strata::core::ConversationCheckpointSplit cs; cs.stage0 = std::move(image.checkpoints); for (auto& si : image.stage_images) cs.parts.push_back(std::move(si.checkpoints)); if (!strata::core::conversation_checkpoints_merge(std::move(cs), checks)) checks.clear(); } for (const ConvCheckpoint& c : checks) check_clock = std::max(check_clock, c.used); cvec_cached = image.cvec; live_ok = true; if (nan_flush) { // #879: the file replaced the poisoned session; the parked ones go (no slots here) nan_flush = false; const size_t n_parked = conversations.clear() + conv_disk.clear(); std::fprintf(stderr, "strata serve: after non-finite logits (#879): the restored session " "replaces the live one; dropped %zu parked conversation%s\n", n_parked, n_parked == 1 ? "" : "s"); } std::fprintf(stderr, "strata serve: session restored %zu tokens, %zu checkpoints, %zu bytes from %s " "in %.1f ms (read+check %.1f ms)\n", live.size(), checks.size(), bytes, path.c_str(), ms(), read_ms); std::printf("RESTORED %zu %zu %.1f\n", live.size(), bytes, ms()); } std::fflush(stdout); continue; } const bool geni = line.rfind("GENI ", 0) == 0; if (geni || line.rfind("GEN ", 0) == 0) { refresh_file_tier(); if (dc_learning || dc_calib) { // the request's arrival, before its prompt is read: a pause since the last one ended starts a new busy run const Clock::time_point dc_now = Clock::now(); if (strata::spec::CostLearner::starts_busy_run(dc_seen_request, std::chrono::duration(dc_now - dc_last_end).count(), dc_learning)) dc_busy_since = dc_now; dc_seen_request = true; } } if (!geni && line.rfind("GEN ", 0) != 0) { std::printf("ERR expected: GEN or GENI \n"); continue; } char* endp = nullptr; const long long max_new = std::strtoll(line.c_str() + (geni ? 5 : 4), &endp, 10); // optional sampling keys between max_new and the ids: temperature=F, top_p=F, top_k=N, min_p=F, // penalty_last_n=N, penalty_repeat=F, penalty_freq=F, penalty_present=F, seed=N (text requests // only). Absent keys keep today's behavior: greedy, no penalties. float req_temperature = 0.0f, req_top_p = 1.0f; int req_top_k = 20; // the sampler's own default; the sampled path REQUIRES top_k in 1..64 unsigned long long req_seed = 0; float req_min_p = 0.0f, req_penalty_repeat = 1.0f, req_penalty_freq = 0.0f, req_penalty_present = 0.0f; int req_penalty_last_n = 0; long long req_pen_from = -1; // pen_from=N: this request continues one that began at token N (the last token of the original prompt): the penalty window starts there std::string req_bias_text; bool req_bias_present = false; int req_cvec = 1; // cvec=0|1: a loaded control vector for this request (on when absent) // logprobs=K (0..20): after each "T id" an "LP logprob id:logprob ..." line. // -1 (absent) = no LP lines, so a server that never asks sees today's output. int req_logprobs = -1; // allowed=a,b,c: with logprobs, print only these token ids (renormalized server-side). std::vector req_allowed; // ckpt=0: a one-shot call whose turn no later request extends. No checkpoint at its last turn boundary // (so no split there) nor every --prompt-cache-every tokens, and its session is neither continued nor // parked after it. It still resumes from a checkpoint it matches, and still saves the system-prompt root // when that reaches --prompt-cache-root. Absent = checkpointed as before. int req_ckpt = 1; // prefill=1 (with max_new 0): split serving. Read the prompt as a request would, up to the place where the first // verify window starts (the session holds n - 1 tokens, exactly what a next turn that continues it needs), and // stop: no token is made. A SAVE after it is the hand-over to another engine (docs/SPLIT_SERVE.md). bool req_prefill_only = false; // pin=N: the first N prompt tokens are a shared read-only prefix (a long document that many short queries // follow). The prompt is read in two parts at N, the checkpoint there is PINNED (retention never evicts it, // a parked conversation holding it stays parked) and a later request that resumes from it does not park the // branch it leaves: N queries cost one prefix, not N. Absent = as before. int64_t req_pin = 0; // hold=N:ID (the server's thinking budget, GEN only): end the request after N emitted tokens unless token ID // () came first, with the session at exactly what was emitted (serve_hold_remaining); DONE says "hold". // Absent = as before. An older engine skips the key (unknown keys are skipped), and says no "hold" in READY. long long req_hold_n = -1, req_hold_id = -1; // tuning keys (setup's calibration measures settings without restarting the engine): the PCIe share of // the missed experts and the draft-probability floor, for this request only double req_pcie_frac = o.pcie_frac, req_spec_min_p = o.spec_min_p; std::string req_draft; // draft=mtp|dflash2 (--draft auto): which drafter this request uses bool req_min_p_set = false; double req_pipe = -1.0; // --prefill-pipe for this request (setup's calibration of a layer split) int req_aux_cpus = -1; // aux_cpus=0|1: --aux-cpus for this request (-1 = the start-up value) // #2228: img_keys=,,... (GENI): each picture's key from the server (its normalized bytes' hash), // in prompt order. With them the conversation cache matches a picture by its key and grid, not by its // embedding floats, so a picture encoded again with other bits still matches. Absent: the embeddings' hash. std::vector req_img_keys; bool req_pcie_set = false; // the request names its own share (the measured one holds meanwhile) if (endp != nullptr) { // GENI takes the same keys (#75: image requests were always greedy); its // embedding file path is the first token without an = for (;;) { while (*endp == ' ') ++endp; const char* start = endp; while (*endp != '\0' && *endp != ' ') ++endp; if (endp == start) break; const std::string tok(start, (size_t) (endp - start)); const size_t eq = tok.find('='); if (eq == std::string::npos) { endp = const_cast(start); break; } const std::string key = tok.substr(0, eq); const float fv = std::strtof(tok.c_str() + eq + 1, nullptr); if (key == "logit_bias") { req_bias_text = tok.substr(eq + 1); req_bias_present = true; } else if (key == "pen_from") req_pen_from = std::atoll(tok.c_str() + eq + 1); else if (key == "cvec") req_cvec = std::atoi(tok.c_str() + eq + 1); else if (key == "ckpt") req_ckpt = std::atoi(tok.c_str() + eq + 1) != 0; else if (key == "prefill") req_prefill_only = std::atoi(tok.c_str() + eq + 1) != 0; else if (key == "pin") req_pin = std::max(0, std::atoll(tok.c_str() + eq + 1)); else if (key == "hold") { char* he = nullptr; const long long hn = std::strtoll(tok.c_str() + eq + 1, &he, 10); if (he != nullptr && *he == ':' && hn > 0) { char* ie = nullptr; const long long hid = std::strtoll(he + 1, &ie, 10); if (ie != he + 1 && *ie == '\0' && hid >= 0) { req_hold_n = hn; req_hold_id = hid; } } } else if (key == "temperature") req_temperature = fv; else if (key == "top_p") req_top_p = fv; else if (key == "top_k") req_top_k = std::atoi(tok.c_str() + eq + 1); else if (key == "logprobs") req_logprobs = std::atoi(tok.c_str() + eq + 1); else if (key == "allowed") { const std::string csv = tok.substr(eq + 1); size_t p = 0; while (p < csv.size()) { const size_t c = csv.find(",", p); const std::string one = csv.substr(p, c == std::string::npos ? std::string::npos : c - p); if (!one.empty()) req_allowed.push_back((int32_t) std::atoi(one.c_str())); if (c == std::string::npos) break; p = c + 1; } } else if (key == "min_p") req_min_p = fv; else if (key == "penalty_last_n") req_penalty_last_n = std::atoi(tok.c_str() + eq + 1); else if (key == "penalty_repeat") req_penalty_repeat = fv; else if (key == "penalty_freq") req_penalty_freq = fv; else if (key == "penalty_present") req_penalty_present = fv; else if (key == "seed") req_seed = std::strtoull(tok.c_str() + eq + 1, nullptr, 10); else if (key == "pcie_frac") { req_pcie_frac = std::clamp((double) fv, 0.0, 1.0); req_pcie_set = true; } else if (key == "spec_min_p") { req_spec_min_p = std::clamp((double) fv, 0.0, 1.0); req_min_p_set = true; } else if (key == "draft") req_draft = tok.substr(eq + 1); else if (key == "pipe") req_pipe = std::max(0.0, (double) fv); else if (key == "aux_cpus") req_aux_cpus = std::atoi(tok.c_str() + eq + 1) != 0 ? 1 : 0; else if (key == "img_keys") { req_img_keys.clear(); const char* q = tok.c_str() + eq + 1; while (*q != '\0') { char* qe = nullptr; const unsigned long long v = std::strtoull(q, &qe, 16); if (qe == q) { req_img_keys.clear(); break; } req_img_keys.push_back((uint64_t) v); q = *qe == ',' ? qe + 1 : qe; if (*qe != ',' && *qe != '\0') { req_img_keys.clear(); break; } } } // unknown keys are skipped: the ids start at the first token without '=' } } strata::prefill::Prefill::set_pipe_request(req_pipe); // every request sets it: none carries over bool req_df2 = use_df2; // --draft auto: this request's drafter, decided once the prompt is parsed (below) std::vector req_bias; std::string bias_error; if (req_bias_present && !strata::core::parse_logit_bias(req_bias_text, (int) n_vocab, req_bias, bias_error)) { std::printf("ERR logit_bias: %s\n", bias_error.c_str()); continue; } std::string emb_path; if (geni && endp != nullptr) { while (*endp == ' ') ++endp; char* gap = std::strchr(endp, ' '); if (gap != nullptr) { emb_path.assign(endp, (size_t) (gap - endp)); endp = gap; } } std::vector ids; std::string pe; if ((max_new < 1 && !(max_new == 0 && req_prefill_only)) || (req_prefill_only && max_new != 0) || endp == nullptr || (geni && emb_path.empty()) || !parse_i64_list(endp, ids, pe)) { std::printf("ERR bad request: %s\n", pe.empty() ? "max_new" : pe.c_str()); continue; } std::vector req_pads; // SCR: the positions in `ids` of the pads this request reads if (scr_on && !geni && live_ok && !live_pads.empty()) { std::vector carried; req_pads = strata::core::scr_carry(ids, live, live_pads, scr_pad, carried); if (!req_pads.empty()) ids = std::move(carried); } int64_t n = (int64_t) ids.size(); // --draft auto: this request's drafter. Without the DFlash2 drafter loaded every request uses the MTP, as before. uint64_t bandit_key = 0; if (use_df2 && o.draft_auto) { const std::string& d = !req_draft.empty() ? req_draft : o.draft_rule; if (d == "mtp") req_df2 = false; else if (d == "dflash2" || d == "df2") req_df2 = true; else if (d == "learn") { // what this kind of request (its first prompt tokens: the system prompt of the app) did best so far, with some exploring bandit_key = 1469598103934665603ull; for (int64_t i = 1; i < std::min(n, 33); ++i) bandit_key = (bandit_key ^ (uint64_t) ids[(size_t) i]) * 1099511628211ull; DraftBandit& b = bandit[bandit_key]; const int64_t r = b.reqs++; if (b.n[1] < 2) req_df2 = true; else if (b.n[0] < 2) req_df2 = false; else { const bool df_better = b.tps[1] >= 0.99 * b.tps[0]; // DFlash2 unless the MTP is clearly ahead const int every = std::fabs(b.tps[1] / b.tps[0] - 1.0) < 0.04 ? 6 : 12; // the other one is tried now and then req_df2 = (r % every == every - 1) ? !df_better : df_better; } } if (!req_df2 && !req_min_p_set && o.draft_mtp_min_p >= 0.0) req_spec_min_p = o.draft_mtp_min_p; if (req_df2 != policy_is_df2) { std::swap(policy, policy_idle); policy_is_df2 = req_df2; } S_mtp = req_df2 ? S_mtp_wide : S_mtp_narrow; S_look = req_df2 ? S : std::min(S, S_mtp_narrow); if (use_mtp) mtp.set_max_drafts(S_mtp - 1); } if (req_prefill_only && (geni || o.batch > 0 || n < 2)) { std::printf("ERR prefill=1 needs a text prompt of at least 2 tokens and no --batch\n"); continue; } req_imgs.clear(); if (geni && !o.vision) { std::printf("ERR this engine was started without --vision\n"); continue; } if (geni || !mrope_identity) { // positions for every cell this request can reach; the identity again for a text request std::string ve; row_ptr.assign((size_t) n, nullptr); const int64_t cells = (int64_t) mrope_host.size() / 3; auto put = [&](int64_t c, int64_t t, int64_t h, int64_t w) { mrope_host[(size_t) c * 3] = (int32_t) t; mrope_host[(size_t) c * 3 + 1] = (int32_t) h; mrope_host[(size_t) c * 3 + 2] = (int32_t) w; }; if (!geni) { for (int64_t c = 0; c < cells; ++c) put(c, c, c, c); } else { struct Img { int64_t n, nx, ny; size_t off; }; std::vector imgs; img_rows.clear(); std::FILE* f = std::fopen(emb_path.c_str(), "rb"); if (!f) ve = "cannot open " + emb_path; while (f && ve.empty()) { int32_t hdr[5]; const size_t got = std::fread(hdr, sizeof(int32_t), 5, f); if (got == 0) break; if (got != 5 || hdr[0] != 0x31455653 || hdr[1] < 1 || hdr[2] < 1 || hdr[3] < 1 || (int64_t) hdr[2] * hdr[3] != hdr[1] || hdr[4] != (int32_t) g.n_embd) { ve = "bad embeddings file (expected strata-vision records of width " + std::to_string((long long) g.n_embd) + ")"; break; } const size_t off = img_rows.size(), cnt = (size_t) hdr[1] * (size_t) hdr[4]; img_rows.resize(off + cnt); if (std::fread(img_rows.data() + off, sizeof(float), cnt, f) != cnt) { ve = "short embeddings file"; break; } imgs.push_back({hdr[1], hdr[2], hdr[3], off}); } if (f) std::fclose(f); int64_t p = 0, i = 0; size_t k = 0; while (ve.empty() && i < n) { if (ids[(size_t) i] != kImagePad) { put(i, p, p, p); ++p; ++i; continue; } if (k >= imgs.size()) { ve = "the prompt has more images than the embeddings file"; break; } const Img& im = imgs[k++]; { // what the conversation cache compares: a picture is its grid and its embeddings const int64_t grid[3] = {im.n, im.nx, im.ny}; uint64_t h = fnv1a(grid, sizeof grid); if (req_img_keys.size() == imgs.size()) // #2228: the server's key for picture k h = fnv1a(&req_img_keys[k - 1], sizeof(uint64_t), h); else h = fnv1a(img_rows.data() + im.off, (size_t) im.n * (size_t) g.n_embd * sizeof(float), h); req_imgs.push_back({i, h}); } for (int64_t j = 0; j < im.n && ve.empty(); ++j) if (i + j >= n || ids[(size_t) (i + j)] != kImagePad) ve = "image " + std::to_string(k) + " has " + std::to_string((long long) im.n) + " rows but fewer <|image_pad|> tokens"; for (int64_t j = 0; j < im.n && ve.empty(); ++j) { const int64_t y = j / im.nx, x = j % im.nx; put(i + j, p, p + y, p + x); row_ptr[(size_t) (i + j)] = img_rows.data() + im.off + (size_t) j * (size_t) g.n_embd; } i += im.n; p += std::max(im.nx, im.ny); } if (ve.empty() && k != imgs.size()) ve = "the embeddings file has more images than the prompt"; if (ve.empty() && n > 0 && ids[(size_t) (n - 1)] == kImagePad) ve = "the prompt cannot end in an image"; for (int64_t c = n; ve.empty() && c < cells; ++c) put(c, p + (c - n), p + (c - n), p + (c - n)); } tr("positions built", (long long) img_rows.size()); cudaDeviceSynchronize(); tr("device idle"); // CUDA0's table and, with a layer split, every later stage's (each device reads its own) auto upload_mrope = [&]() -> bool { bool ok = cudaMemcpy(d_mrope, mrope_host.data(), mrope_host.size() * sizeof(int32_t), cudaMemcpyHostToDevice) == cudaSuccess; for (auto& st : stages) { const strata::core::OnDevice on(st->dev); cudaDeviceSynchronize(); ok = ok && cudaMemcpy(st->mrope, mrope_host.data(), mrope_host.size() * sizeof(int32_t), cudaMemcpyHostToDevice) == cudaSuccess; } return ok; }; if (ve.empty() && !upload_mrope()) ve = "the image position upload failed"; if (!ve.empty()) { // leave the table as the identity so the next text request is untouched for (int64_t c = 0; c < cells; ++c) put(c, c, c, c); upload_mrope(); mrope_identity = true; std::printf("ERR %s\n", ve.c_str()); std::fflush(stdout); continue; } mrope_identity = !geni; } sp.embd_rows = geni ? row_ptr.data() : nullptr; if (n + max_new + 8 > o.max_context) { std::printf("ERR prompt (%lld tokens) + max_new (%lld) exceeds the context (%lld)\n", (long long) n, (long long) max_new, (long long) o.max_context); continue; } bool bad = false; for (int64_t t : ids) bad = bad || t < 0 || t >= n_vocab; if (bad) { std::printf("ERR a token id is outside the vocabulary\n"); continue; } std::array remote_before{}; std::array launches_before{}; std::array compact_before{}, full_before{}; // ms_begin/ms_wait are cumulative since boot; the log line used to print them next to per-request deltas, // so the host time read as if it belonged to this request. Take deltas here like every other column. std::array begin_before{}, wait_before{}; for (int r = 0; r < 3; ++r) if (o.expert_cache_remote[(size_t) r] > 0) { remote_before[(size_t) r] = remote_experts[(size_t) r].computed(); launches_before[(size_t) r] = remote_experts[(size_t) r].launched_layers(); compact_before[(size_t) r] = remote_experts[(size_t) r].returned_bytes(); full_before[(size_t) r] = remote_experts[(size_t) r].full_row_bytes(); begin_before[(size_t) r] = remote_experts[(size_t) r].ms_begin(); wait_before[(size_t) r] = remote_experts[(size_t) r].ms_wait(); } cur = ids; const Clock::time_point r0 = Clock::now(); tr("r0"); strata::core::conversation_checkpoint_join(nullptr); // STRATA_CKPT_ASYNC: the last save's copy has landed const int64_t streamed0 = sp.chain_experts_streamed(); // the DONE line's experts_streamed= is the difference // ---- where this request starts reading: the live session, or a checkpoint, whose tokens AND pictures are // exactly the start of this prompt - at most n - 1 of them, the last token is always the first window auto starts_with = [&](const std::vector& pre, const std::vector& pre_imgs) -> bool { const int64_t L = (int64_t) pre.size(); if (L < 1 || L > n - 1) return false; for (int64_t i = 0; i < L; ++i) if ((int32_t) ids[(size_t) i] != pre[(size_t) i]) return false; return imgs_below(req_imgs, L) == pre_imgs; }; const bool want_cvec = strata::kernels::cvec().loaded() ? req_cvec != 0 : true; // the last request's final commit may still be running on the verifier's stream (set_commit_async): // everything below reads, restores or zeroes the session from other streams and the host (the end of the // last request waited already; this covers a request that ended on an error path) if (!ver.wait_commit(err)) { std::printf("ERR %s\n", err.c_str()); return 1; } // STRATA_MTP_ROOM_MIN: this request points the prompt path's ring at the drafter's experts, if it reads // enough new tokens and the room applies here. The open is below, once `read_from` is known: the // threshold counts the tokens the request reads, not the whole prompt (a reused conversation prefix buys // nothing from the room). Nothing is laid out again - the room's slots are the drafter's own bytes // (Prefill::set_ring_room_base) - and `room_close` below gives the decode its contents back before the // first window. A room left open by an earlier request (a cancelled prompt) is closed first. bool mtp_room_open = mtp_room_slots > 0 && room_path != nullptr && !mtp.experts_resident(); auto head_restore = [&]() -> int { if (!o.prefill_head_alias || native_head.loaded()) return 0; sp.reset(); const auto head_t0 = Clock::now(); if (!native_head.load(o.native_head_shards, g.n_embd, n_vocab, err)) { std::printf("ERR restoring the native output head failed: %s\n", err.c_str()); return 1; } // the verify windows' captured graphs read the head at the address of their capture if (prefill_head_alias_at == nullptr) prefill_head_alias_at = native_head.weights(); if (native_head.weights() != prefill_head_alias_at) { std::printf("ERR --prefill-head-alias: the output head was reloaded at another address, so the " "captured verify graphs would read freed memory\n"); return 1; } std::fprintf(stderr, "strata serve: --prefill-head-alias: output head restored in %.1f ms before decode\n", std::chrono::duration(Clock::now() - head_t0).count()); return 0; }; auto room_close = [&](const char* why) -> int { const auto t0 = Clock::now(); if (room_path != nullptr) { // the ring goes back to the rule's count FIRST: nothing after this can stage into the lender's // bytes, and the streams are idle before they are written over (a prompt pass reads them) if (!room_path->idle(err)) { std::printf("ERR %s\n", err.c_str()); return 1; } room_path->set_ring_room_active(false); } if (!mtp.experts_reclaim(err)) { std::printf("ERR %s\n", err.c_str()); return 1; } mtp_room_open = false; std::fprintf(stderr, "strata serve: prompt room (%s): the drafter's experts are the decode's again in " "%.1f ms\n", why, std::chrono::duration(Clock::now() - t0).count()); return 0; }; if (mtp_room_open && room_close("left open") != 0) return 1; if (o.prefill_head_alias && native_head.loaded()) { const auto head_t0 = Clock::now(); native_head.unload(); sp.reset(); if (init_prompt_paths() != 0) { std::printf("ERR rebuilding the head-alias prompt path failed: %s\n", err.c_str()); return 1; } arm_prompt_helpers(); // the rebuild above dropped them (they live inside the layout) std::fprintf(stderr, "strata serve: --prefill-head-alias: prompt workspace rebuilt in %.1f ms\n", std::chrono::duration(Clock::now() - head_t0).count()); } auto kv_quiesce = adapt_quiesce; if (kvg.on) { // the elastic K/V: this prompt's cells (it gives back what it does not need below) // a failed growth may leave the tier half-changed: the engine stops (as for any CUDA failure) 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); return 1; } } nf_hit = false; // #879: an earlier window met non-finite logits. The poison sits in a conversation's K/V and recurrent // state, so nothing that may hold it is continued: the live session, every checkpoint, every parked // conversation and every idle batch slot go, and this prompt is read from token 0 (resume == 0 below) if (nan_flush) { nan_flush = false; if (nf_prompt_windows) { nf_prompt_windows = false; short_read_off_once = o.short_read > 0; } const size_t n_checks = checks.size(); live_ok = false; checks.clear(); tail_ckpt_len = -1; const size_t n_parked = conversations.clear() + conv_disk.clear(); size_t n_slots = 0, n_running = 0; for (BSlot& sl : bs) if (sl.active) { // a running slot finishes its reply, but is not kept as a cache after it sl.tainted = true; ++n_running; // STRATA_SLOT_CKPT_MOVE reads a running slot's checkpoints (and a finished one's: lent_slot): // they predate the flush, so they go now if (slot_ckpt_move_env()) { if (ckpt_pool.on()) for (ConvCheckpoint& c : sl.checks) ckpt_pool.give(std::move(c)); sl.checks.clear(); } } else if (sl.cached) { sl.cached = false; sl.partial = false; sl.checks.clear(); ++n_slots; } std::fprintf(stderr, "strata serve: after non-finite logits (#879): dropped the live session, %zu " "checkpoint%s, %zu parked conversation%s and %zu idle slot%s (%zu running slot%s " "not kept after their reply); reading this prompt from token 0\n", n_checks, n_checks == 1 ? "" : "s", n_parked, n_parked == 1 ? "" : "s", n_slots, n_slots == 1 ? "" : "s", n_running, n_running == 1 ? "" : "s"); } int64_t resume = 0; bool from_live = false; if (o.prompt_cache > 0 && want_cvec == cvec_cached) { if (live_ok && starts_with(live, live_imgs)) { resume = (int64_t) live.size(); from_live = true; } for (const ConvCheckpoint& c : checks) if ((int64_t) c.ids.size() > resume && starts_with(c.ids, c.imgs)) { resume = (int64_t) c.ids.size(); from_live = false; } } // STRATA_SLOT_CKPT_MOVE: a turn checkpoint a batch admission moved into its slot is still one of the main // session's while the main session holds its tokens (the cells below it are the ones it was taken over): // it is restored there as one of `checks` would be (lent_slot: the slot that keeps it). moved_in: the length // of a slot's checkpoint this request moved into `checks` (from the slot it is admitted to), -1: none int lent_slot = -1; int64_t moved_in = -1; if (slot_ckpt_move_env() && o.prompt_cache > 0 && want_cvec == cvec_cached && live_ok) for (int b = 0; b < (int) bs.size(); ++b) { if (bs[(size_t) b].cvec != cvec_cached || bs[(size_t) b].tainted) continue; // (#879) for (const ConvCheckpoint& c : bs[(size_t) b].checks) { const int64_t L = (int64_t) c.ids.size(); if (L > resume && L <= (int64_t) live.size() && starts_with(c.ids, c.imgs) && std::equal(c.ids.begin(), c.ids.end(), live.begin()) && imgs_below(live_imgs, L) == c.imgs) { resume = L; from_live = false; lent_slot = b; } } } // --batch: an idle slot that holds the start of this prompt (the conversation it served last) is a // source too - its sessions are copied back below, so only the new part is read. STRATA_SLOT_CKPT_MOVE: an // active slot's checkpoints too (its windows write its cells from p on, so the ones below a checkpoint still // hold its prompt; the groups have finished before a request is read) int slot_source = -1; int64_t slot_tokens = 0; bool resumed_from0 = false; // a prompt read parked in a slot (BYIELD) that had started at token 0 // --prefill-pipe: the plan of the segment a read goes on in (a BYIELD park, a periodic checkpoint), and // where it goes on; read_part reads the rest of that segment in its chunks ConvCheckpoint::PromptPlan resume_plan; int64_t resume_plan_at = -1, resume_plan_end = -1; // where it goes on, and the segment end it needs const ConvCheckpoint* slot_ck = nullptr; // the slot's checkpoint the prompt continues from (else its end) if (o.prompt_cache > 0 && req_imgs.empty()) for (int b = 0; b < (int) bs.size(); ++b) { const BSlot& sl = bs[(size_t) b]; const bool idle_source = !sl.active && sl.cached; // (an active slot only where the drafter's rows come along or are not drafted from: the copy // takes the main layers' cells, so the main drafter would keep another conversation's below it) const bool active_source = sl.active && !sl.tainted && slot_ckpt_move_env() && (!use_mtp || batch_mtp || admit_slot >= 0); if (sl.cvec != want_cvec || !(idle_source || active_source)) continue; if (idle_source && (int64_t) sl.ids.size() > std::max(resume, slot_tokens) && starts_with(sl.ids, {})) { slot_source = b; slot_tokens = (int64_t) sl.ids.size(); slot_ck = nullptr; } for (const ConvCheckpoint& c : sl.checks) if ((int64_t) c.ids.size() > std::max(resume, slot_tokens) && starts_with(c.ids, c.imgs)) { slot_source = b; slot_tokens = (int64_t) c.ids.size(); slot_ck = &c; } } // #2228: a checkpoint or the live state whose TOKENS this prompt starts with, deeper than what is reused, but // whose pictures differ (a picture is its grid and the hash of its embeddings: an image encoded again with // other bits - another encoder start, a CPU encoder that is not bit-reproducible - no longer matches). The // reuse then falls back to a checkpoint before that picture; said once per request, so the log tells this // apart from a client that rewrote its history. if (o.prompt_cache > 0 && !req_imgs.empty()) { int64_t deep = 0; const std::vector* deep_imgs = nullptr; auto tokens_match = [&](const std::vector& pre) { const int64_t L = (int64_t) pre.size(); if (L < 1 || L > n - 1) return false; for (int64_t i = 0; i < L; ++i) if ((int32_t) ids[(size_t) i] != pre[(size_t) i]) return false; return true; }; auto consider = [&](const std::vector& pre, const std::vector& pre_imgs) { if ((int64_t) pre.size() > std::max(deep, resume) && tokens_match(pre) && imgs_below(req_imgs, (int64_t) pre.size()) != pre_imgs) { deep = (int64_t) pre.size(); deep_imgs = &pre_imgs; } }; if (live_ok) consider(live, live_imgs); for (const ConvCheckpoint& c : checks) consider(c.ids, c.imgs); if (deep_imgs != nullptr) { const std::vector now = imgs_below(req_imgs, deep); size_t k = 0; while (k < now.size() && k < deep_imgs->size() && now[k] == (*deep_imgs)[k]) ++k; std::fprintf(stderr, "strata serve: conversation cache: the state at %lld tokens has this prompt's " "tokens but picture %zu (at token %lld) is not the same as when it was saved " "(its embeddings changed): it cannot be reused (#2228)\n", (long long) deep, k + 1, (long long) (k < now.size() ? now[k].start : -1)); } } const auto parked = conversations.best(ids, req_imgs, want_cvec, std::max(resume, slot_tokens)); std::optional incoming; auto incoming_match = parked; // where in the incoming image this prompt resumes // the NVMe tier, when it holds this prompt deeper than everything in memory const auto on_disk = conv_disk.enabled() ? conv_disk.best(ids, req_imgs, want_cvec, std::max({resume, slot_tokens, parked.tokens})) : strata::core::ConversationDisk::Match{}; if (on_disk.tokens > std::max({resume, slot_tokens, parked.tokens})) { const auto t0 = Clock::now(); strata::core::SessionFileIdentity id; strata::core::SessionReadLimits limits; strata::core::SavedConversation image; std::string e; if (session_identity(id, e, {}) && conv_disk_limits(limits, e) && conv_disk.take(on_disk.index, id, image, e, limits)) { std::fprintf(stderr, "strata serve: conversation disk: read %lld of this prompt's tokens back in %.0f ms\n", (long long) on_disk.tokens, std::chrono::duration(Clock::now() - t0).count()); incoming.emplace(std::move(image)); incoming_match = on_disk; } else { std::fprintf(stderr, "strata serve: conversation disk: cannot read it back (%s)\n", e.c_str()); } } // A checkpoint inside ANOTHER parked conversation (a sibling subagent's system prompt and tools, say) is // borrowed: its K/V up to there and the checkpoint come over, and that conversation stays parked for its // own next turn (ConversationCache::borrows). Everything else is taken whole, as before. // (a layer split restores whole stage images only, so it never borrows; a batch slot that holds a longer // start of this prompt wins as before) bool borrow = !incoming && stages.empty() && parked.tokens > std::max(resume, slot_tokens) && conversations.borrows(parked); if (!incoming && parked.tokens > std::max(resume, slot_tokens) && !borrow) incoming.emplace(conversations.take(parked.index)); if (incoming || borrow) slot_source = -1; // Reject the entire image before parking/overwriting the outgoing // state. Invalid entries can safely fall back to its existing prefix. if (incoming && incoming->stage_images.size() != stages.size()) { std::fprintf(stderr, "strata serve: conversation cache: discard snapshot (stage count)\n"); incoming.reset(); } if (incoming) for (size_t i = 0; i < stages.size(); ++i) { const strata::core::OnDevice on(stages[i]->dev); if (!strata::core::conversation_snapshot_validate(incoming->stage_images[i], stages[i]->ss, g, use_mtp && !mtp_first && i + 1 == stages.size() ? &mtp.kv_state() : nullptr, err)) { // the draft: the last stage's std::fprintf(stderr, "strata serve: conversation cache: discard invalid stage snapshot (%s)\n", err.c_str()); incoming.reset(); err.clear(); break; } } if (incoming && !strata::core::conversation_snapshot_validate(*incoming, ss, g, use_mtp && (stages.empty() || mtp_first) ? &mtp.kv_state() : nullptr, err)) { std::fprintf(stderr, "strata serve: conversation cache: discard invalid snapshot (%s)\n", err.c_str()); incoming.reset(); err.clear(); } // #2409: a restore writes into buffers that exist already. The one thing it can still allocate on a card is // this thread's private copy stream for it (a pooled one is reused), and an out-of-memory there is fatal // for the process (a failed restore must not be decoded from). So a card that would have to create one and // has less than kRestoreFirstUseMib free gets no restore: the snapshot goes back to the cache and this // prompt is read again. A card that already has its stream is never refused, however full it is. if (incoming) { std::vector restore_devs{-1}; for (const auto& stp : stages) restore_devs.push_back(stp->dev); std::vector restore_free; std::vector restore_ready; int tight = -1; bool sampled = true; for (const int rd : restore_devs) { const strata::core::OnDevice on(rd); int cur = 0; size_t fb = 0, tb = 0; if (cudaGetDevice(&cur) != cudaSuccess || cudaMemGetInfo(&fb, &tb) != cudaSuccess) { (void) cudaGetLastError(); sampled = false; // no sample: the restore goes ahead as it always did break; } restore_free.push_back((uint64_t) fb); restore_ready.push_back(strata::core::conversation_copy_stream_ready(cur) ? 1 : 0); } if (sampled && !strata::program::conv_cache::restore_fits(restore_free.data(), restore_ready.data(), restore_free.size(), strata::program::conv_cache::kRestoreFirstUseMib << 20)) { for (size_t k = 0; k < restore_free.size(); ++k) if (!restore_ready[k] && restore_free[k] < (strata::program::conv_cache::kRestoreFirstUseMib << 20)) tight = (int) k; std::fprintf(stderr, "strata serve: conversation cache: skip restore (%s has %lld MiB free and no copy stream " "yet, which needs up to %lld MiB); rereading the prompt\n", tight <= 0 ? "CUDA0" : ("stage " + std::to_string(tight)).c_str(), (long long) (tight >= 0 ? restore_free[(size_t) tight] >> 20 : 0), (long long) strata::program::conv_cache::kRestoreFirstUseMib); auto retry = std::move(*incoming); incoming.reset(); if (!conversations.put(std::move(retry))) std::fprintf(stderr, "strata serve: conversation cache: could not return the skipped snapshot\n"); err.clear(); } } if (borrow) { const strata::core::SavedConversation* donor = conversations.find(parked.serial); if (donor == nullptr || !strata::core::conversation_snapshot_validate(*donor, ss, g, use_mtp ? &mtp.kv_state() : nullptr, err)) { std::fprintf(stderr, "strata serve: conversation cache: cannot borrow from a parked conversation " "(%s)\n", err.empty() ? "gone" : err.c_str()); borrow = false; err.clear(); } } // SCR: a prompt the live session holds most of, edited in the middle. The cells of the text that survived // are moved to their new places (scr_move.hpp), the parts between them read, and the GDN state taken from // the checkpoint at the end of the last moved run (scr.hpp); everything after it is read as usual. const bool scr_cells_kept = !incoming && !borrow && slot_source < 0; strata::core::ScrPlan scr; std::vector scr_order; // the runs in an order that never overwrites a source still to move ConvCheckpoint scr_adopt; // the QSA states SCR moves: each stage's, on its device and stream struct ScrState { strata::core::QsaState* st; int dev; void* stream; }; auto scr_states = [&] { std::vector v; for (int64_t j = 0; j < ss.qsa_alloc; ++j) v.push_back({&ss.qsa_states[ss.qsa_ord0 + j], 0, main_cs}); for (auto& sg : stages) for (int64_t j = 0; j < sg->ss.qsa_alloc; ++j) v.push_back({&sg->ss.qsa_states[sg->ss.qsa_ord0 + j], sg->dev, (void*) sg->stream}); return v; }; auto scr_supported = [&] { for (const ScrState& s : scr_states()) { const strata::core::QsaState& q = *s.st; // (an elastic K/V has the same layout; kvg_ensure maps the cells the moves write, the trim keeps their sources) if (!q.kv_int8 || q.kv_hybrid || q.kv_rot || q.kv_q4 || q.kv_mode != 0 || !q.k_q || !q.idx_pooled || !q.idx_dead) return false; } return true; }; if (scr_on && scr_cells_kept && !from_live && req_imgs.empty() && live_imgs.empty() && live_ok && want_cvec == cvec_cached && o.prompt_cache > 0 && scr_supported()) { const auto t0 = Clock::now(); std::vector cks; // the GDN states the plan may continue from: the chain and the live state for (const ConvCheckpoint& c : checks) if (c.imgs.empty()) cks.push_back((int64_t) c.ids.size()); cks.push_back((int64_t) live.size()); strata::core::ScrPlan plan = strata::core::scr_plan(live, ids, cks, strata::core::ScrParams{}); const int64_t spliced = n + plan.pads() - plan.restore - plan.reused(); // a run moves once its target holds no source of a run still to move (llama-cpp-bonsai's rule) std::vector pending = plan.runs; while (!pending.empty()) { const auto next = std::find_if(pending.begin(), pending.end(), [&](const strata::core::ScrRun& r) { return std::none_of(pending.begin(), pending.end(), [&](const strata::core::ScrRun& q) { return &q != &r && q.old_start < r.at + r.n && r.at < q.old_start + q.n; }); }); if (next == pending.end()) break; scr_order.push_back(*next); pending.erase(next); } std::string why; if (plan.empty()) why = "nothing to move"; else if (n + plan.pads() + max_new + 8 > o.max_context) why = "the pads do not fit the context"; else if (spliced + scr_min_gain > n - resume) why = "not worth it"; else if (!pending.empty()) why = "the runs cannot be moved in any order"; if (why.empty()) { // the GDN state after the last run: the live state, or the checkpoint there; its indexer's last // block moves with the run bool taken = false; if (plan.adopt == (int64_t) live.size()) { scr_adopt.ids = live; taken = gpu_sync_ok() && checkpoint_save(scr_adopt, ss, g); for (auto& sg : stages) { const strata::core::OnDevice on(sg->dev); ConvCheckpoint part; part.ids = live; taken = taken && gpu_sync_ok() && checkpoint_save(part, sg->ss, g); scr_adopt.stage_parts.push_back(std::move(part)); } } else { for (const ConvCheckpoint& c : checks) if ((int64_t) c.ids.size() == plan.adopt) { scr_adopt = c; taken = c.stage_parts.size() == stages.size(); } } const int32_t shift = (int32_t) plan.runs.back().shift(); auto move_block_pos = [shift](ConvCheckpoint& c) { for (size_t b = 0; b + sizeof(int32_t) <= c.block_pos.size(); b += sizeof(int32_t)) { int32_t v; std::memcpy(&v, c.block_pos.data() + b, sizeof v); v += shift; std::memcpy(c.block_pos.data() + b, &v, sizeof v); } }; move_block_pos(scr_adopt); for (ConvCheckpoint& part : scr_adopt.stage_parts) move_block_pos(part); if (!taken) why = "the state after the last run could not be taken"; } if (!why.empty()) { std::fprintf(stderr, "strata serve: scr: %s (%s)\n", why.c_str(), plan.str().c_str()); scr_order.clear(); } else { for (const int64_t p : strata::core::scr_pad_positions(plan)) req_pads.push_back(p); std::sort(req_pads.begin(), req_pads.end()); ids = strata::core::scr_padded(ids, plan, scr_pad); n = (int64_t) ids.size(); cur = ids; resume = plan.restore; scr = std::move(plan); // the elastic K/V holds this prompt's cells: the pads add some, mapped before any run moves if (kvg.on && !kvg_ensure(n + 256, kv_quiesce)) { std::printf("ERR the K/V cannot grow to this prompt's pads\n"); return 1; } std::fprintf(stderr, "strata serve: scr: %s; moves %lld, reads %lld instead of %lld (planned in %.1f ms)\n", scr.str().c_str(), (long long) scr.reused(), (long long) spliced, (long long) (n - scr.pads() - resume), std::chrono::duration(Clock::now() - t0).count()); } } // Preserve the outgoing branch before any checkpoint rewind, reset, // or incoming restore overwrites the positional state it requires. // pin=N: this request resumes exactly at the pinned shared prefix of the conversation the session holds // (a sibling query of the last one). What the last query added past it is its private suffix - a few // dozen tokens, cheaper to read than the prefix's whole K/V is to copy to the host - so it is not parked: // N queries keep one prefix. A request without pin=, or one that resumes anywhere else, parks as before. bool pin_sibling = false; if (req_pin > 0 && req_ckpt && o.prompt_cache >= 3 && !from_live && !incoming && slot_source < 0 && resume == req_pin && live_ok) for (const ConvCheckpoint& c : checks) if ((int64_t) c.ids.size() == resume && c.pinned) pin_sibling = true; // STRATA_PARK_KEEP=F (opt-in): a request that resumes from this conversation's own checkpoint at F or more // of what the session holds rewrites only its tail (an agent's next turn drops the last reply's thinking): // the tail is not parked, which took ~1.7 s for 30K tokens before every such turn static const double park_keep = [] { const char* v = std::getenv("STRATA_PARK_KEEP"); return v ? std::atof(v) : 0.0; }(); const bool keep_tail = park_keep > 0.0 && scr.empty() && !from_live && !pin_sibling && !incoming && !borrow && slot_source < 0 && live_ok && !live.empty() && (double) resume >= park_keep * (double) live.size(); if (keep_tail) std::fprintf(stderr, "strata serve: conversation cache: not parking the %lld-token tail past %lld " "(STRATA_PARK_KEEP)\n", (long long) ((int64_t) live.size() - resume), (long long) resume); // The live branch past this request's resume point is only the reply this prompt replaces: the request resumes from // the live branch's own turn checkpoint and opens the same assistant turn there again (an OpenAI-style client's // next turn sends the reply back without its reasoning; an edited reply; a regenerate). That branch is not parked: // no request of the client sends the reply back as it was, and its park is a copy of the whole conversation on // this request's path that the next park drops as superseded (reply_branch.hpp). A real switch (another // conversation, a parked one coming back, a batch slot, a borrow, another cvec) parks as before. bool reply_replaced = false; if (!from_live && !incoming && !borrow && slot_source < 0 && lent_slot < 0 && live_ok && !pin_sibling && want_cvec == cvec_cached && resume > 0) { std::vector live_pictures; for (const ImgKey& k : live_imgs) live_pictures.push_back((int64_t) k.start); for (const ConvCheckpoint& c : checks) if ((int64_t) c.ids.size() == resume && starts_with(c.ids, c.imgs) && strata::program::live_tail_is_replaced_reply(live, ids, resume, o.turn_token, live_pictures)) { reply_replaced = true; break; } } if (reply_replaced) std::fprintf(stderr, "strata serve: conversation cache: the reply this request replaces is not parked (%lld " "tokens past the turn checkpoint at %lld)\n", (long long) ((int64_t) live.size() - resume), (long long) resume); // --conversation-cache-park-gain N: a park now would supersede the entry parked_prefix_tokens() reports (the copy // this conversation wrote last), so a conversation that advanced fewer than N tokens since then keeps it: // it still holds this conversation's prefix, and re-parking writes the whole snapshot only for the next // turn to drop it again. 0 (the default) parks every turn, as before. const size_t park_held = o.conversation_cache_park_gain > 0 ? conversations.parked_prefix_tokens(live, live_imgs, checks, cvec_cached) : 0; const bool park_worth = o.conversation_cache_park_gain <= 0 || park_held == 0 || (int64_t) live.size() >= (int64_t) park_held + o.conversation_cache_park_gain; // STRATA_PARK_ASYNC: the checkpoints this request drops after its park - all of them when another state // comes in (a parked conversation, a borrow, a batch slot) or the cvec changes, else the ones off this // prompt's path (off_path below) - move into the parked image struct ParkDrops { std::function& f; ~ParkDrops() { f = nullptr; } } park_drops_reset{park_drops}; if (park_async_env()) { const bool drops_all = incoming.has_value() || borrow || slot_source >= 0 || want_cvec != cvec_cached; park_drops = [&, drops_all](const ConvCheckpoint& c) { return drops_all || (int64_t) c.ids.size() > resume || !starts_with(c.ids, c.imgs); }; } if (scr.empty() && borrow && !pin_sibling && park_worth) { conversations.guard(parked.serial); // parking the outgoing conversation must not evict the donor const bool parked_ok = park_current(0); const bool blocked = conversations.guard_blocked(); conversations.unguard(); if (!parked_ok) { std::printf("ERR %s\n", err.c_str()); return 1; } if (blocked) { // the outgoing conversation fits only in the donor's room: it keeps its place, the donor is // taken whole as before (it was validated above) std::fprintf(stderr, "strata serve: conversation cache: no room beside the parked conversation " "this request starts with; taking it instead of borrowing\n"); borrow = false; if (const size_t at = conversations.index_of(parked.serial); at != SIZE_MAX) incoming.emplace(conversations.take(at)); if (!park_current(incoming ? incoming->bytes() : 0)) { std::printf("ERR %s\n", err.c_str()); return 1; } } } else if (scr.empty() && (!from_live || incoming || slot_source >= 0) && !pin_sibling && !reply_replaced && !keep_tail && park_worth && !park_current(incoming ? incoming->bytes() : 0)) { std::printf("ERR %s\n", err.c_str()); return 1; } if (slot_source >= 0) { lent_slot = -1; // (a longer start than the main session's) const auto t0 = Clock::now(); if (!copy_from_slot(slot_source, slot_ck, err)) { // the main session may be half written: read this prompt from the start std::fprintf(stderr, "strata batch: restoring slot %d failed (%s); reading the prompt\n", slot_source, err.c_str()); err.clear(); live.clear(); live_imgs.clear(); checks.clear(); resume = 0; from_live = false; } else { checks.clear(); // the main session's checkpoints were of the conversation it held before // a read that gave way, the same request again (into its own slot): on with it - its segments and // checkpoints as if it had not stopped if (slot_ck == nullptr && bs[(size_t) slot_source].partial && admit_slot == slot_source) { resumed_from0 = bs[(size_t) slot_source].partial_from0; resume_plan = bs[(size_t) slot_source].partial_plan; resume_plan_at = slot_tokens; resume_plan_end = resume_plan.to; bs[(size_t) slot_source].partial = false; bs[(size_t) slot_source].partial_plan = {}; } // the slot's checkpoints come along (the one continued from, and any shorter one: prefixes of what // was copied back, their K/V cells with it), so the chain keeps its branch points and the parked // copies of this conversation a turn back - whose deepest checkpoint the chain holds again - go // as superseded (#342) instead of taking a parked entry each until the cache evicts another chat. // STRATA_SLOT_CKPT_MOVE: the slot this request continues in drops its checkpoints at the // admission, so they move (the one continued from moves on into the slot then: moved_in) const bool move_cks = slot_ckpt_move_env() && admit_slot == slot_source; const int64_t ck_len = slot_ck != nullptr ? (int64_t) slot_ck->ids.size() : -1; std::vector& sc = bs[(size_t) slot_source].checks; // a shorter checkpoint comes along only when it is a prefix of the tokens copied back (text only): // its cells are then the ones the main session holds const std::vector copied_back = slot_ck != nullptr ? slot_ck->ids : bs[(size_t) slot_source].ids; auto prefix_of_copied = [&](const ConvCheckpoint& c) { return c.imgs.empty() && c.ids.size() <= copied_back.size() && std::equal(c.ids.begin(), c.ids.end(), copied_back.begin()); }; // the one continued from first, exactly as before this change (its copy is the one the request needs) const ConvCheckpoint* first = slot_ck; if (first != nullptr) { if (move_cks) { checks.push_back(std::move(sc[(size_t) (first - sc.data())])); sc.erase(sc.begin() + (first - sc.data())); first = nullptr; // gone from the slot } else { checks.push_back(*first); } } // then the shorter ones: an optimization, so a host allocation that fails skips them try { for (auto it = sc.begin(); it != sc.end();) { if ((int64_t) it->ids.size() > slot_tokens || &*it == first || !prefix_of_copied(*it)) { ++it; } else if (move_cks) { checks.push_back(std::move(*it)); it = sc.erase(it); } else { checks.push_back(*it); ++it; } } } catch (const std::bad_alloc&) { std::fprintf(stderr, "strata batch: slot %d: its shorter checkpoints were not all copied (out of " "memory); the rest are skipped\n", slot_source); } if (slot_ck != nullptr) { for (ConvCheckpoint& c : checks) // the main session's chain has it now if ((int64_t) c.ids.size() == ck_len) { live = c.ids; c.used = ++check_clock; slot_ck = &c; } if (move_cks) moved_in = ck_len; } else { live = bs[(size_t) slot_source].ids; } live_imgs.clear(); live_pads.clear(); resume = slot_tokens; from_live = true; std::fprintf(stderr, "strata batch: slot %d gave back %lld tokens of this conversation (%s) in " "%.1f ms\n", slot_source, (long long) slot_tokens, slot_ck != nullptr ? "its turn checkpoint" : "all it holds", std::chrono::duration(Clock::now() - t0).count()); } } // the elastic K/V: a parked conversation is restored whole, and it may be longer than this prompt // (STRATA_PARK_VRAM_MIB: the parked K/V copies in VRAM go first, then one more try) if (incoming && !kvg_ensure((int64_t) incoming->live.ids.size() + 256, kv_quiesce) && (strata::core::conversation_park_vram_release_all() == 0 || !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 (borrow) { const auto t0 = Clock::now(); const strata::core::SavedConversation* donor = conversations.find(parked.serial); // still parked if (donor == nullptr || strata::core::conversation_snapshot_restore_prefix(*donor, parked.tokens, ss, g, use_mtp ? &mtp.kv_state() : nullptr, err) != strata::core::ConversationRestore::restored) { // validated above and guarded while parking: a failure here is fatal, as for a whole restore std::printf("ERR restoring a borrowed conversation prefix: %s\n", err.empty() ? "gone" : err.c_str()); return 1; } // the donor's checkpoints on this prompt's path, copied: the donor keeps its own (the one at // parked.tokens is mounted below, as for any checkpoint resume) checks.clear(); for (const ConvCheckpoint& c : donor->checkpoints) if ((int64_t) c.ids.size() <= parked.tokens && starts_with(c.ids, c.imgs)) checks.push_back(c); for (const ConvCheckpoint& c : checks) if ((int64_t) c.ids.size() == parked.tokens) { live = c.ids; live_imgs = c.imgs; } cvec_cached = donor->cvec; resume = parked.tokens; from_live = false; conversations.count_borrow(); std::fprintf(stderr, "strata serve: conversation cache: borrowed %lld tokens from a parked " "conversation, which stays parked, in %.1f ms; parked=%zu bytes=%zu borrowed=%zu\n", (long long) resume, std::chrono::duration(Clock::now() - t0).count(), conversations.size(), conversations.bytes(), conversations.borrowed()); } if (incoming) { const auto t0 = Clock::now(); if (strata::core::conversation_snapshot_restore(*incoming, ss, g, use_mtp && (stages.empty() || mtp_first) ? &mtp.kv_state() : nullptr, err) != strata::core::ConversationRestore::restored) { // Already prevalidated above: a failure here is fatal, never // permission to decode from a partially restored session. std::printf("ERR restoring parked conversation: %s\n", err.c_str()); return 1; } for (size_t i = 0; i < stages.size(); ++i) { // the later stages' parts const strata::core::OnDevice on(stages[i]->dev); if (strata::core::conversation_snapshot_restore(incoming->stage_images[i], stages[i]->ss, g, use_mtp && !mtp_first && i + 1 == stages.size() ? &mtp.kv_state() : nullptr, err) != strata::core::ConversationRestore::restored) { std::printf("ERR restoring parked conversation (stage CUDA%d): %s\n", stages[i]->dev, err.c_str()); return 1; } if (cudaDeviceSynchronize() != cudaSuccess) { std::printf("ERR stage sync\n"); return 1; } } if (use_mtp && std::getenv("STRATA_SNAPSHOT_VERIFY") != nullptr) { uint64_t draft_hash = 0; const auto& draft_kv = stages.empty() || mtp_first ? incoming->kv.back() : incoming->stage_images.back().kv.back(); const strata::core::OnDevice on_d(stages.empty() || mtp_first ? 0 : stages.back()->dev); if (!strata::core::conversation_kv_verify(draft_kv, mtp.kv_state(), g, int64_t(incoming->live.ids.size()), false, draft_hash, err)) { std::printf("ERR verifying restored draft KV: %s\n", err.c_str()); return 1; } std::fprintf(stderr, "strata serve: SNAPSHOT_VERIFY draft=%016llx cells=%lld mode=%d source=%s resident=%lld\n", (unsigned long long) draft_hash, (long long) draft_kv.cells, mtp.kv_state().kv_mode, "ram", (long long) (mtp.kv_state().n_slots * strata::kernels::qsa_real_shapes().page_size)); } live = std::move(incoming->live.ids); live_imgs = std::move(incoming->live.imgs); live_pads.clear(); if (stages.empty()) { checks = std::move(incoming->checkpoints); } else { // give each checkpoint back its stage parts (moved, not copied); none if they do not line up strata::core::ConversationCheckpointSplit cs; cs.stage0 = std::move(incoming->checkpoints); for (auto& si : incoming->stage_images) cs.parts.push_back(std::move(si.checkpoints)); if (!strata::core::conversation_checkpoints_merge(std::move(cs), checks)) checks.clear(); } cvec_cached = incoming->cvec; resume = incoming_match.tokens; from_live = incoming_match.live; if (std::getenv("STRATA_SNAPSHOT_FULL_CAPTURE") == nullptr) { std::vector> stage_kv; // every stage's, for its next park for (auto& si : incoming->stage_images) stage_kv.push_back(std::move(si.kv)); conversations.retain(std::move(incoming->kv), int64_t(live.size()), std::move(stage_kv), live); } incoming.reset(); // Running-state/checkpoint copies are no longer needed. lent_slot = -1; // (the main session holds the parked conversation now) std::fprintf(stderr, "strata serve: conversation cache: restored %lld tokens (%s) in %.1f ms; parked=%zu bytes=%zu\n", (long long) resume, from_live ? "live" : "checkpoint", std::chrono::duration(Clock::now() - t0).count(), conversations.size(), conversations.bytes()); } if (want_cvec != cvec_cached) { live_ok = false; checks.clear(); cvec_cached = want_cvec; } if (strata::kernels::cvec().loaded()) strata::kernels::cvec_set_enabled(want_cvec); // this request rewrites every cell from `resume` on, so a checkpoint past it (or not on this prompt's // path) no longer has its cells; the ones kept are prefixes of both the old tokens and the new auto off_path = [&](const ConvCheckpoint& c) { return (int64_t) c.ids.size() > resume || !starts_with(c.ids, c.imgs); }; if (ckpt_pool.on()) // STRATA_CKPT_POOL: their storage is the next checkpoint's ckpt_pool.erase_if(checks, off_path); else checks.erase(std::remove_if(checks.begin(), checks.end(), off_path), 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(); // STRATA_KV_GROW_HOLD=1 (opt-in): keep the K/V as long as the longest parked conversation; default: trim to this request alone, as 0.1.40 static const bool hold_on = [] { const char* v = std::getenv("STRATA_KV_GROW_HOLD"); return v != nullptr && std::atoi(v) != 0; }(); int64_t scr_src_end = 0; // SCR moves cells from up to here: they stay mapped through the trim for (const strata::core::ScrRun& r : scr.runs) scr_src_end = std::max(scr_src_end, r.old_start + r.n); if (!kvg_trim(std::max(n, scr_src_end) + 256, hold_on ? conversations.longest_tokens() + 256 : 0)) { std::printf("ERR the K/V could not give its VRAM back to the expert cache\n"); std::fflush(stdout); return 1; } } int64_t reread_to = -1; // STRATA_CKPT_REREAD only: read [0, reread_to) again instead of restoring if (resume == 0) { // a splice from token 0 keeps the cells it is about to move strata::core::session_zero_running(ss, g, nullptr, main_cs, !scr.empty()); cudaStreamSynchronize(main_stream); for (auto& st : stages) { const strata::core::OnDevice on(st->dev); strata::core::session_zero_running(st->ss, g, nullptr, (void*) st->stream, !scr.empty()); cudaStreamSynchronize(st->stream); } checks.clear(); } else if (!from_live) { ConvCheckpoint* c = nullptr; for (ConvCheckpoint& k : checks) if ((int64_t) k.ids.size() == resume) c = &k; bool lent = false; // STRATA_SLOT_CKPT_MOVE: the one a slot keeps (found above) if (c == nullptr && lent_slot >= 0) for (ConvCheckpoint& k : bs[(size_t) lent_slot].checks) if ((int64_t) k.ids.size() == resume && starts_with(k.ids, k.imgs)) { c = &k; lent = true; } if (!lent) lent_slot = -1; if (c != nullptr) c->used = ++check_clock; // mounting through it is the use LRU counts static const bool reread = std::getenv("STRATA_CKPT_REREAD") != nullptr; if (reread && c != nullptr) { // THE CHECK OF THE CHECKPOINT: instead of restoring it, read its tokens again from position 0 in // one run (below, with the prompt path's slots lent like any read) - the same chunks the request // that saved it read them in, when that request started at 0. With the VRAM expert set fixed // (--adapt-swaps 0) the answer must match the restored one token for token; anything the // checkpoint missed shows up as a difference. strata::core::session_zero(ss, g, nullptr, main_cs); cudaStreamSynchronize(main_stream); for (auto& st : stages) { const strata::core::OnDevice on(st->dev); strata::core::session_zero(st->ss, g, nullptr, (void*) st->stream); cudaStreamSynchronize(st->stream); } reread_to = resume; std::fprintf(stderr, "strata serve: STRATA_CKPT_REREAD: reading %lld tokens again instead of " "restoring\n", (long long) resume); } else if (c == nullptr || !checkpoint_restore(*c, ss, g) || c->stage_parts.size() != stages.size() || [&] { for (size_t i = 0; i < stages.size(); ++i) { const strata::core::OnDevice on(stages[i]->dev); if (!checkpoint_restore(c->stage_parts[i], stages[i]->ss, g)) return true; } return false; }()) { std::printf("ERR restoring a conversation checkpoint failed\n"); return 1; } if (lent && lent_slot == admit_slot) { // the slot this request continues in drops its checkpoints at the admission: this one moves back // into the chain (and on into the slot then: moved_in) std::vector& sc = bs[(size_t) lent_slot].checks; const auto it = sc.begin() + (c - sc.data()); checks.push_back(std::move(*it)); sc.erase(it); moved_in = resume; lent_slot = -1; } if (lent && trace) std::fprintf(stderr, "strata trace: the checkpoint at %lld restored from slot %d's%s\n", (long long) resume, lent_slot >= 0 ? lent_slot : admit_slot, lent_slot >= 0 ? "" : " (moved back into the chain)"); } // --prefill-pipe: going on from a periodic checkpoint taken inside a planned segment (whatever restored it: // a checkpoint of this session, of a slot or of a parked conversation), the rest of that segment is read // in its chunks. STRATA_CKPT_REREAD reads [0, resume) again in the chunks the saving read had, which it // can only when that segment started at 0. The BYIELD park set resume_plan above. if (resume_plan.chunk <= 0 && resume > 0 && !stages.empty()) for (const ConvCheckpoint& k : checks) if ((int64_t) k.ids.size() == resume && k.plan.chunk > 0) { if (reread_to <= 0) { resume_plan = k.plan; resume_plan_at = resume; resume_plan_end = k.plan.to; } else if (k.plan.from == 0) { // [0, resume) only: its end is the checkpoint resume_plan = k.plan; resume_plan_at = 0; resume_plan_end = resume; } else { std::fprintf(stderr, "strata serve: STRATA_CKPT_REREAD: the checkpoint is inside a " "segment that started at %lld, so a read from 0 has other chunks\n", (long long) k.plan.from); } break; } // KV streaming: the drafter's ring may hold cells past `resume` from a longer turn; the main layers' // host copies and slots are always current (every writer writes both), so they need nothing if (use_mtp && resume > 0 && reread_to <= 0) mtp.kv_restore(resume); // SCR: the cells move before any part is read (a part may write where a later run's source still lies). // A K master is current only where no read has written since it was taken: up to where this request // starts reading, and in the cells a splice moves. auto scr_trim = [&](int64_t upto) { std::vector> kept; for (const auto& [a, b] : scr_master_ok) if (a < upto) kept.push_back({a, std::min(b, upto)}); scr_master_ok = std::move(kept); }; if (!scr_cells_kept) scr_master_ok.clear(); else scr_trim(resume); std::vector> scr_first; // per QSA state, per run: the pooled key of its first block if (!scr.empty()) { const auto tm = Clock::now(); const auto& rope = strata::kernels::rope_scaling(); const int64_t page = strata::kernels::qsa_real_shapes().page_size, D = g.idx_key_dim, bl = strata::kernels::qsa_real_shapes().idx_block; bool moved = true; for (const ScrState& s : scr_states()) { const strata::core::OnDevice on(s.dev); strata::core::QsaState& q = *s.st; ScrLayerMem& mem = scr_mem[&q]; if (mem.master == nullptr) { // pinned host memory every device reads (FP16 [cell][head][n_rot]) const size_t mb = (size_t) q.max_cells * g.n_head_kv * g.n_rot * 2; moved = moved && cudaHostAlloc((void**) &mem.master, mb, cudaHostAllocMapped | cudaHostAllocPortable) == cudaSuccess && cudaHostAlloc((void**) &mem.valid, (size_t) q.max_cells, cudaHostAllocMapped | cudaHostAllocPortable) == cudaSuccess; if (!moved) break; } std::memset(mem.valid, 0, (size_t) q.max_cells); for (const auto& [a, b] : scr_master_ok) std::memset(mem.valid + a, 1, (size_t) (b - a)); auto& sc = scr_scratch[s.dev]; strata::kernels::ScrKvLayer l; l.k_q = q.k_q; l.v_q = q.v_q; l.k_scale = q.k_scale; l.v_scale = q.v_scale; l.master = mem.master; l.master_valid = mem.valid; l.kv_heads = (int) g.n_head_kv; l.head_dim = (int) g.head_dim; l.page_size = (int) page; l.n_rot = (int) g.n_rot; l.max_cells = q.max_cells; if (sc.first == nullptr) { moved = moved && cudaMalloc(&sc.first, strata::kernels::scr_move_kv_scratch_bytes(l, kScrChunk)) == cudaSuccess && cudaMalloc(&sc.second, (size_t) kScrPooledChunk * D * sizeof(float)) == cudaSuccess; if (!moved) break; } for (const strata::core::ScrRun& r : scr_order) { moved = moved && strata::kernels::scr_move_kv(l, r.old_start, r.n, r.shift(), rope, sc.first, kScrChunk, s.stream) && strata::kernels::scr_move_pooled(q.idx_pooled, q.idx_pooled_rows, (int) D, (int) g.n_rot, (int) bl, r.old_start / bl, r.n / bl, r.shift() / bl, rope, sc.second, kScrPooledChunk, s.stream); } // each run's first pooled key, which the part read before it overwrites with the spare; the spare // after each run, where the next part (or the tail) goes on std::vector first; for (const strata::core::ScrRun& r : scr.runs) { float* row = nullptr; moved = moved && cudaMalloc(&row, (size_t) D * sizeof(float)) == cudaSuccess; if (!moved) break; cudaMemcpyAsync(row, q.idx_pooled + (r.at / bl) * D, (size_t) D * sizeof(float), cudaMemcpyDeviceToDevice, (cudaStream_t) s.stream); first.push_back(row); } for (const strata::core::ScrRun& r : scr.runs) cudaMemcpyAsync(q.idx_pooled + ((r.at + r.n) / bl) * D, q.idx_dead, (size_t) D * sizeof(float), cudaMemcpyDeviceToDevice, (cudaStream_t) s.stream); scr_first.push_back(std::move(first)); moved = moved && cudaStreamSynchronize((cudaStream_t) s.stream) == cudaSuccess; if (!moved) break; } if (!moved) { // the cells may be half moved: the engine stops, as for any CUDA failure in the session std::printf("ERR scr: moving the cached cells failed\n"); std::fflush(stdout); return 1; } scr_trim(scr.restore); for (const strata::core::ScrRun& r : scr.runs) scr_master_ok.push_back({r.at, r.at + r.n}); std::fprintf(stderr, "strata serve: scr: moved %lld cells in %zu runs over %zu QSA states in %.1f ms\n", (long long) scr.reused(), scr.runs.size(), scr_first.size(), std::chrono::duration(Clock::now() - tm).count()); } tr("request", n, geni ? 1 : 0); req_times = ReqTimes{}; if (use_mtp) mtp.set_prompt_len(n); // KVA: the draft layer's first real cell for the state this request continues from (0 for a cold read - the // first segment raises it if KVA approximates it - and for any state no KVA read produced) if (use_mtp && mtp.cell_floor_enabled()) mtp.set_cell_floor(resume > 0 && reread_to <= 0 ? kva_floors.floor_for(ids.data(), resume) : 0); #if defined(STRATA_HAVE_DFLASH2) if (use_df2) { // the drafter's ring goes on from the live conversation, or starts over (a parked or edited one) std::vector idv(ids.begin(), ids.end()); bool cold = false; df2.begin_request(idv.data(), (int64_t) idv.size(), reread_to > 0 ? 0 : resume, &cold); if (df2.last_rebuilt > 0) std::fprintf(stderr, "strata serve: DFlash2: %s%lld context rows of the window rebuilt from the drafter's log in %.1f ms%s\n", df2.last_swapped ? "a parked conversation came back: " : "", (long long) df2.last_rebuilt, df2.last_ms, df2.last_missing >= 64 ? " (the rest were never logged)" : ""); if (cold && df2.last_missing >= 64) // (a few rows missing are not worth a line: they are counted in the ring stats) std::fprintf(stderr, "strata serve: DFlash2: %lld context rows of the window are not the drafter's to give (a conversation it has no log of: edited, " "from a session file, or its log was evicted): it drafts poorly for the first rounds (the answers are the same)\n", (long long) std::max(df2.last_missing, 1)); if (multi_gpu) df2_stage_prompt_taps_begin(std::max(0, n - 2047)); else sp.set_taps(df2.tap_layers(), std::max(0, n - 2047), 2048); } #endif const int64_t read_from = reread_to > 0 ? 0 : resume; // STRATA_MTP_ROOM_MIN: opened here, once the reused prefix is known - the threshold counts the tokens this // request reads (an agent turn on a long conversation reads a few hundred and gains nothing from the room). // Before `lend()` below, so a relayout re-carves with the room (its slots are the drafter's own bytes). if (mtp_room_slots > 0 && room_path != nullptr && n - read_from >= mtp_room_min && mtp.experts_resident()) { const auto room_t0 = Clock::now(); if (!mtp.experts_lend(err)) { std::fprintf(stderr, "strata serve: prompt room: %s: this prompt reads as it always did\n", err.c_str()); } else { room_path->set_ring_room_active(true); // before the loan: a relayout re-carves with the room mtp_room_open = true; std::fprintf(stderr, "strata serve: prompt room: %lld tokens to read, the prompt path's ring is the " "drafter's %llu MiB (%d slots past its own, lent in %.1f ms)\n", (long long) (n - read_from), (unsigned long long) (mtp.experts_bytes() >> 20), mtp_room_slots, std::chrono::duration(Clock::now() - room_t0).count()); } } conversations.limit_reuse(read_from); pp_total = n; pp_from = read_from; pp_reached = read_from; pp_exact = true; // a restore, a checkpoint mount or a zeroed session: the state is exactly at read_from pp_t0 = r0; pp_next_check = reread_to > 0 || !req_ckpt ? INT64_MAX : resume + o.prompt_cache_every; // ckpt=0: none pp_tail_saved = reread_to > 0 || !req_ckpt; // ckpt=0 (#861): no tail checkpoint either { std::lock_guard lk(part_mu); part_at.clear(); std::fill(part_next.begin(), part_next.end(), pp_next_check); } std::printf("RESUME %lld\n", (long long) resume); // before reading: this many prompt tokens are reused strata::core::progress_at("reading the prompt, from token", read_from); std::fflush(stdout); // A SHORT PART OF THE PROMPT - the new message of a chat that continues from a checkpoint, the assistant // header - goes through the verify windows, S tokens at a time, as decode reads them. The batched path // costs ~300 ms per run however few tokens it has (it streams every expert the chunk routes to that is // not in VRAM over PCIe), and it borrows slots it must refill after (~180 ms); a window costs ~16 ms a // token, with the misses on the CPU. Each part below is decided on its own, so a long first message is // read batched and its header still goes through the windows. Picture rows need the batched path. // STRATA_CKPT_REREAD compares a restored checkpoint with a batched re-read, so it keeps every read batched. static const bool no_short = std::getenv("STRATA_CKPT_REREAD") != nullptr; int64_t req_short_read = o.short_read; // STRATA_PIPELINE_SWITCH may set it per request (short_read=) if (short_read_off_once) { // #3465: the request after non-finite logits in a prompt window short_read_off_once = false; req_short_read = 0; std::fprintf(stderr, "strata serve: after non-finite logits in a prompt window (#3465): this request reads its " "whole prompt through the batched path, none of it through the verify windows\n"); } auto windows_ok = [&](int64_t a, int64_t b) -> bool { if (no_short || b - a > req_short_read) return false; if (sp.embd_rows != nullptr) for (int64_t i = a; i < b; ++i) if (sp.embd_rows[i] != nullptr) return false; return true; }; // --pipeline-windows, testing: STRATA_PIPELINE_SWITCH= is read at every request, "pw=<0|1|2> // theta= force_miss= short_read=" - an A/B of the pipelined and the serial loops (and forced // rollbacks) on one server, with the same expert placement int pl_pw = pipe ? o.pipeline_windows : 0; float pl_theta = [] { // a speculative window is launched only when its estimated chance is at least this const char* v = pipe_dbg_env("STRATA_PIPELINE_THETA"); return v ? (float) std::atof(v) : 0.2f; }(); int pl_force_miss = [] { // exactness test: every k-th speculative window gets a wrong first token const char* v = pipe_dbg_env("STRATA_PIPELINE_FORCE_MISS"); return v ? std::max(0, std::atoi(v)) : 0; }(); if (static const char* sw = pipe_dbg_env("STRATA_PIPELINE_SWITCH"); sw != nullptr && pipe) { if (std::FILE* f = std::fopen(sw, "r")) { char buf[256] = {}; const size_t nr = std::fread(buf, 1, sizeof buf - 1, f); std::fclose(f); buf[nr] = 0; if (const char* q = std::strstr(buf, "pw=")) pl_pw = std::max(0, std::min(2, std::atoi(q + 3))); if (const char* q = std::strstr(buf, "theta=")) pl_theta = (float) std::atof(q + 6); if (const char* q = std::strstr(buf, "force_miss=")) pl_force_miss = std::max(0, std::atoi(q + 11)); if (const char* q = std::strstr(buf, "short_read=")) req_short_read = std::max(0LL, std::atoll(q + 11)); std::fprintf(stderr, "strata pipeline switch: pw=%d theta=%.3f force_miss=%d short_read=%lld\n", pl_pw, pl_theta, pl_force_miss, (long long) req_short_read); } } // --pipeline-windows: tokens [a, b) through the windows with the stages overlapped. The tokens are known, // so every window commits whole: stage 0 queues window K, its commit and window K+1 back to back (each // parity's verifier keeps its own window), and stage 1 runs window K once stage 0 is done with it. Every // stage runs the same windows in the same order as read_windows below, so the session ends the same. auto read_windows_pl = [&](int64_t a, int64_t b, std::string& e) -> bool { strata::core::progress_at("reading the prompt (pipelined verify windows), from token", a); if (!pl_prepare(e)) return false; for (int par = 0; par < 2; ++par) PV[0][par]->set_head_sampling(false); // reaches stage 1 (set_next) struct Restore { strata::core::Verifier* v[2]; ~Restore() { v[0]->set_head_sampling(true); v[1]->set_head_sampling(true); } } restore{{PV[0][0], PV[0][1]}}; struct Win { int T; int64_t q; }; std::vector wins; for (int64_t q = a; q < b;) { const int T = (int) std::min(S, b - q); wins.push_back({T, q}); q += T; } const size_t N = wins.size(); std::vector w0((size_t) S), w1((size_t) S), nx((size_t) S); size_t l0 = 0, f0 = 0, l1 = 0, f1 = 0; // stage 0 launched / finished, stage 1 launched / finished drive.d.layers = 0; drive.d.experts = 0; drive.d.failed = false; auto fail = [&](std::string why) -> bool { pl_drain(); e = why.empty() ? std::string("a pipelined prompt window failed") : why; return false; }; // The drafter's prefill blocks this thread until its stream is idle (on HIP, MtpDrafter::prefill syncs // once per group whatever its `sync` says: prefill_per_group_sync, src/core/mtp.cpp). With the drafter // on the first card (mtp_first) a stage-0 window still in flight spins on that GPU for doorbells only // this thread serves, so a prefill called beside it never returns: the prompt read stopped for good at // its first window (0.1.56, gfx1201 + gfx1030, --pipeline-windows 2, issue #5147). Serve stage 0 to its // end first; the rest of the read keeps both stages overlapped. The tokens are unchanged: the same // windows, in the same order, only served a little earlier. auto serve_stage0_to_end = [&]() -> bool { while (f0 < l0) { strata::core::Verifier& v0 = *PV[0][f0 & 1]; if (v0.service(win_pool_fn, PSD[f0 & 1], e) < 0) return false; if (v0.done(e)) { if (!v0.pl_finish(nullptr, e)) return false; ++f0; } else if (!e.empty()) return false; } return true; }; while (f1 < N) { if (stop_req.load()) return fail("cancelled"); // stage 0: up to two windows queued; window K+2 (K's parity) only once stage 1 has finished window // K, whose hand-off K+2 overwrites while (l0 < N && l0 < f0 + 2 && l0 < f1 + 2) { const Win& w = wins[l0]; for (int t = 0; t < w.T; ++t) w0[(size_t) t] = (int32_t) cur[(size_t) (w.q + t)]; strata::core::Verifier& v = *PV[0][l0 & 1]; if (!v.pl_launch(w.T, w0.data(), w.q, e) || !v.pl_commit_async(w.T, e)) return fail(e); ++l0; } if (f0 < l0) { strata::core::Verifier& v = *PV[0][f0 & 1]; if (v.service(win_pool_fn, PSD[f0 & 1], e) < 0) return fail(e); if (v.done(e)) { if (!v.pl_finish(nullptr, e)) return fail(e); ++f0; } else if (!e.empty()) return fail(e); } if (l1 < f0 && l1 == f1) { // stage 1: the next window, its stage 0 done const Win& w = wins[l1]; for (int t = 0; t < w.T; ++t) w1[(size_t) t] = (int32_t) cur[(size_t) (w.q + t)]; strata::core::Verifier& v = *PV[1][l1 & 1]; if (pl_mtp_live[l1 & 1]) { // the drafter has read this parity's previous rows first const strata::core::OnDevice on(mtp.device()); cudaStreamWaitEvent(v.stream(), pl_mtp_ev[l1 & 1], 0); } if (!v.pl_launch(w.T, w1.data(), w.q, e) || !v.pl_commit_async(w.T, e)) return fail(e); ++l1; } if (f1 < l1) { strata::core::Verifier& v = *PV[1][f1 & 1]; if (v.service(win_pool_fn, PSD[f1 & 1], e) < 0) return fail(e); if (v.done(e)) { if (!v.pl_finish(nullptr, e)) return fail(e); if (nonfinite_hit(v, "prompt")) return fail("non-finite logits (#879)"); const Win& w = wins[f1]; for (int t = 0; t < w.T; ++t) nx[(size_t) t] = (int32_t) cur[(size_t) (w.q + t + 1)]; // the drafter shares stage 0's card: no stage-0 window may still be in flight when its // prefill waits on the host (see serve_stage0_to_end) if (mtp_first && !serve_stage0_to_end()) return fail(e); if (!mtp.prefill(v.final_R(0), nx.data(), w.T, w.q, e, false)) return fail(e); { const strata::core::OnDevice on(mtp.device()); cudaEventRecord(pl_mtp_ev[f1 & 1], mtp.stream()); } pl_mtp_live[f1 & 1] = true; pp_reached = w.q + w.T; // #471 ++f1; } else if (!e.empty()) return fail(e); } if (drive.d.failed) return fail(drive.d.fail ? drive.d.fail : "the expert pool failed"); } pl_drain(); // nothing in flight: both stages' commits and the drafter's rows have landed pl_mtp_live[0] = pl_mtp_live[1] = false; const double ms = std::chrono::duration(Clock::now() - pp_t0).count(); std::printf("PP %lld %lld %.0f %.1f\n", (long long) b, (long long) pp_total, ms, ms > 0.0 ? 1000.0 * (double) (b - pp_from) / ms : 0.0); strata::core::progress_beat(); std::fflush(stdout); return true; }; // tokens [a, b) through the windows: commit all of them, then give the draft layer their residuals auto read_windows = [&](int64_t a, int64_t b, std::string& e) -> bool { // (STRATA_LOGPOS reads every window's logits: the serial loop) // the pipelined prompt read stays two-stage (three or more stages read serially; only the decode overlaps) if (pipe && n_stages == 2 && pl_pw >= 1 && std::getenv("STRATA_LOGPOS") == nullptr) return read_windows_pl(a, b, e); strata::core::progress_at("reading the prompt (verify windows), from token", a); // #217: not "batched" // every token is committed and the picks are discarded: no head sampling (see set_head_sampling) struct NoHeadSampling { strata::core::Verifier& v; explicit NoHeadSampling(strata::core::Verifier& x) : v(x) { v.set_head_sampling(false); } ~NoHeadSampling() { v.set_head_sampling(true); } } no_head_sampling(ver); std::vector win((size_t) S), outw((size_t) S), nxt((size_t) S); pp_exact = true; // between windows the session is exactly at `a` for (int64_t q = a; q < b;) { if (stop_req.load()) { e = "cancelled"; return false; } pp_exact = false; // until this window and the drafter's rows are in int T = (int) std::min(S, b - q); // --lookup-max-t: the prompt's windows take the allowed sizes too (each size is a graph of its own); // one whose graph finds no VRAM is dropped as in decode if (o.lookup_max_t > 0) { T = graph_fits(policy.fit(T)); if (T < 0) { e = err; return false; } } for (int t = 0; t < T; ++t) { win[(size_t) t] = (int32_t) cur[(size_t) (q + t)]; nxt[(size_t) t] = (int32_t) cur[(size_t) (q + t + 1)]; } drive.d.layers = 0; drive.d.experts = 0; drive.d.failed = false; if (!ver.run(T, win.data(), q, win_pool_fn, win_pool_user, outw.data(), e) || drive.d.failed) { if (drive.d.failed && drive.d.fail) e = drive.d.fail; return false; } if (nonfinite_hit(ver, "prompt")) { // (its commit is not needed: the next request reads from 0) e = "non-finite logits (#879)"; return false; } // STRATA_LOGPOS=: the teacher-forced log-probability of every token read here (every // token is committed and nxt[t] is the prompt's own next token), appended to ; the last // column is the log-probability of STRATA_LOGPOS_EXTRA (default 248046, <|im_end|>), so the // end-of-turn mass a chat model puts on raw text can be taken out of the measurement static std::FILE* logpos = [] { const char* p = std::getenv("STRATA_LOGPOS"); return p != nullptr ? std::fopen(p, "ab") : nullptr; }(); static const int32_t logpos_extra = [] { const char* p = std::getenv("STRATA_LOGPOS_EXTRA"); return p != nullptr ? (int32_t) std::atoi(p) : (int32_t) 248046; }(); if (logpos != nullptr && !ver.window_logprobs(nxt.data(), T, q, logpos_extra, logpos, e)) return false; if (!ver.commit(T, e) || (use_mtp && !mtp.prefill(ver.final_R_all(), nxt.data(), T, q, e))) return false; #if defined(STRATA_HAVE_DFLASH2) if (use_df2) { const float* tp = df2_win_taps((int) T, e); if (tp == nullptr || !df2.context(tp, T, q, e)) return false; df2.note_rows(win.data(), T, q); } #endif q += T; pp_reached = q; // #471 pp_exact = true; } // the batched prompt path (other streams), checkpoints and snapshots may follow: the last commit first if (!ver.wait_commit(e)) return false; const double ms = std::chrono::duration(Clock::now() - pp_t0).count(); std::printf("PP %lld %lld %.0f %.1f\n", (long long) b, (long long) pp_total, ms, ms > 0.0 ? 1000.0 * (double) (b - pp_from) / ms : 0.0); strata::core::progress_beat(); std::fflush(stdout); return true; }; // the batched path's slots are lent just before its first run and given back (refilled) before a window // reads - so the windows always see the whole expert cache - or once the prompt is read // Every participant gives its loan back here: the rows it lent are refilled into the SAME slots from // the arena, the residency table is restored, and one upload puts it on every device. A stage refills // through its own cache and its own device - a slot refilled into the wrong cache would leave that // stage's cache holding an expert it does not own, which is silent and produces plausible tokens. // (split in two halves so a layer split can queue every stage's copies before it waits for any: #340) // STRATA_REFILL_PARTS=1 (gfx1151's table): a lent slot of a GGUF read in place is refilled from the pieces in the mapping. // The default assembles the blob in a staging buffer first (a 4 MB copy on this thread), then copies that. static const bool refill_parts = [] { const char* v = std::getenv("STRATA_REFILL_PARTS"); return v != nullptr && std::atoi(v) != 0; }(); auto refill_issue = [&](PfPart& p, std::string& e) -> bool { tr("refill start", (long long) p.lent.size()); const strata::core::OnDevice on(p.dev); for (const auto& [i, slot] : p.lent) { // D-4: queued, one wait (STRATA_REFILL_BLOCKING=1: each) strata::core::BlobPart parts[3]; const int np = refill_parts && !refill_blocking() ? srcp->blob_parts(i / g.n_expert, i % g.n_expert, parts) : 0; if (np > 0) { // the GGUF read in place: the tensors' pieces go from the mapping to the slot, no assembled copy if (!p.cache->fill_slot_queued_parts(slot, parts, np, e)) return false; host_res[(size_t) i] = slot; continue; } const uint8_t* b = srcp->blob_stable(i / g.n_expert, i % g.n_expert); const int64_t nb = (int64_t) strata::kernels::cpu::expert_layout().blob_bytes(i / g.n_expert); if (b == nullptr || !(refill_blocking() ? p.cache->fill_slot_blocking(slot, b, e, nb) : p.cache->fill_slot_queued(slot, b, e, nb))) return false; if (!refill_blocking()) srcp->note_async_read(b, nullptr); // #1237 host_res[(size_t) i] = slot; } return true; }; auto refill_wait = [&](PfPart& p, std::string& e) -> bool { const strata::core::OnDevice on(p.dev); if (!p.cache->sync_queued(e)) return false; #if defined(_WIN32) // The copies have landed: the file pages touched by the loan need not stay in the working set. for (const auto& [i, slot] : p.lent) srcp->release(i / g.n_expert, i % g.n_expert); #endif p.lent.clear(); p.lent_chunk = 0; return true; }; auto refill_one = [&](PfPart& p, std::string& e) -> bool { if (p.lent.empty()) return true; return refill_issue(p, e) && refill_wait(p, e); }; // #340: with several stages every stage's copies go out first (each card on its own link), then each is // waited for - the same copies into the same slots, so the same cache; one stage: refill_one exactly. // STRATA_REFILL_SERIAL=1: stage after stage, as 0.1.30/0.1.31. static const bool refill_serial = std::getenv("STRATA_REFILL_SERIAL") != nullptr; auto refill = [&](std::string& e) -> bool { const auto t_rf = Clock::now(); int64_t n_lent = 0, n_parts = 0; for (PfPart& p : pf_parts) if (!p.lent.empty()) { n_lent += (int64_t) p.lent.size(); ++n_parts; } if (n_parts > 1 && !refill_serial) { for (PfPart& p : pf_parts) if (!p.lent.empty() && !refill_issue(p, e)) return false; for (PfPart& p : pf_parts) if (!p.lent.empty() && !refill_wait(p, e)) return false; } else { for (PfPart& p : pf_parts) if (!p.lent.empty() && !refill_one(p, e)) return false; } if (n_parts > 0) res_upload(); if (trace && n_parts > 0) { std::fprintf(stderr, "strata trace: refilled %lld slots on %lld stage(s) in %.1f ms\n", (long long) n_lent, (long long) n_parts, std::chrono::duration(Clock::now() - t_rf).count()); std::fflush(stderr); } return true; }; // lend the slots `tokens` batched prompt tokens need: the prompt path's buffers for min(chunk, tokens // rounded up to 256), laid out in the last of the slots it may borrow - per participant, out of that // participant's own cache, and marking only that participant's own layers int64_t seg_lend = 0; // the loan the last lend left (the largest participant's chunk; 0: none) auto lend = [&](int64_t tokens, std::string& e, int64_t exact) -> bool { seg_lend = 0; if (pf_parts.empty()) return true; // its own buffers: nothing to lend const auto t_ln = Clock::now(); // what this segment needs, capped by the configured chunk: a request lends only what its own // prompt needs, so a large chunk costs a short prompt nothing #if defined(STRATA_PREFILL_FUSED) && !defined(STRATA_PREFILL_MMQ) // one GPU: equal chunks (equal_cut_rule.hpp), unless their loan would take more slots than today's cut const bool eq_one_gpu = pf_parts.size() == 1 && stages.empty() && !multi_gpu && !peer.valid() && !o.prefill_head_alias && o.batch <= 1; int64_t want_full = loan_chunk(tokens, planned_chunk(tokens, o.prefill_chunk, pf_plan_chunk, eq_one_gpu)); // the equal chunk that kEqualMinChunk turned down (equal_cut_rule.hpp declined_equal; 0: none): kept below // when today's cut, handed back for it, cannot be lent but the equal cut can (keep_equal) int64_t pf_declined_eq = 0; if (eq_one_gpu && equal_cut_one == strata::prefill::equal_cut::Cut::equal && (pf_plan_chunk <= 0 || pf_plan_chunk >= o.prefill_chunk)) pf_declined_eq = strata::prefill::equal_cut::declined_equal(tokens, o.prefill_chunk, strata::prefill::Prefill::stream_all_min_tokens()); if (eq_one_gpu) { const int64_t want_today = loan_chunk(tokens, planned_chunk(tokens, o.prefill_chunk, pf_plan_chunk, false)); if (want_full != want_today && pf_parts[0].first >= 0) { const int64_t floor_eq = strata::prefill::Prefill::stream_all_min_tokens(); auto tail_eq = [&](int64_t w) -> int64_t { return tail_loan_on && strata::prefill::Prefill::tail_matters(w, srcp != nullptr) ? strata::prefill::loan_rules::segment_tail(tokens, w, floor_eq) : -1; }; // after a tail-0 scan only at or below 0.1.39's chunk: today's cut above it would carve the short tail the // scan did not count (fit_out_rule.hpp today_cut_ok) if (!strata::prefill::equal_cut::loan_ok(part_slots(pf_parts[0], want_full, tail_eq(want_full)), part_slots(pf_parts[0], want_today, tail_eq(want_today))) && strata::prefill::fit_out::today_cut_ok(pf_fit_tail, want_today, pf_fit_small)) want_full = want_today; } } #else const int64_t want_full = loan_chunk(tokens, planned_chunk(tokens, o.prefill_chunk, pf_plan_chunk)); #endif // #340: a short enough request reads in the stages' own S-token chunks (nothing lent) const int64_t want_seg = o.prefill_head_alias ? o.prefill_chunk : split_small > 0 && tokens <= split_small_max ? std::min(want_full, split_small) : want_full; // `exact`: a planned segment read on - the loan it was read with (what is left would size another) const int64_t want = exact > 0 ? std::min(exact, o.prefill_chunk) : want_seg; if (want <= 0) { e = "prefill: cannot lend buffers for an empty request segment"; return false; } bool any = false; namespace lr = strata::prefill::loan_rules; using strata::prefill::Prefill; const int64_t floor_t = Prefill::stream_all_min_tokens(); const bool tail_ok = tail_loan_on && pf_parts.size() == 1 && stages.empty() && !multi_gpu && !peer.valid() && !o.prefill_head_alias && o.batch <= 1; for (PfPart& p : pf_parts) { if (p.first < 0) continue; if (!p.lent.empty()) { // its current loan already covers this: the chunk, and (a fused layout) the tail the segment's last // chunk needs when it is read in the loan's own chunks if (tail_ok && !dbg_tail_noreuse ? lr::reuse_ok(want, tokens, p.lent_chunk, p.sp->tail_room(), floor_t) : want <= p.lent_chunk) continue; // ONLY this participant's loan goes back: `refill` would return the other participants' // loans too, and their buffers are still laid out in their caches - marking those slots // resident again would hand the next window a prompt buffer in place of an expert if (!refill_one(p, e)) return false; } const strata::core::OnDevice on(p.dev); int64_t want_p = want; int64_t tail_p = -1; // the tail the layout is laid out with (-1: floor - 1) int32_t first = p.first_now; // --prefill-head-alias: the loan laid out at start (slot 1 on) is kept; a hybrid layout cannot relayout. // (STRATA_MTP_ROOM_MIN's room is not one: its slots are the drafter's own bytes, so a roomed // request lends and is laid out exactly as any other - a relayout re-carves the room with it.) if (!o.prefill_head_alias) { // #2090: the loan a chunk needs is NOT monotonic in the chunk: a chunk above the scan's small_max // lays out the byte-budget ring (199 slots at 5120), one at or below it 0.1.39's (384 at 4096), so // a request's smaller chunk can need MORE slots than the auto chunk's region (p.first) holds. The // loan starts where the chunk itself needs it (the 128-slot floor aside); a chunk that cannot be // lent even then is halved until it can, instead of ending the engine. // the tail this layout is carved with for chunks of `w` (-1: today's floor - 1): grow-only while the layout's // chunk stays (loan_rules::next_tail), the need of the moment otherwise auto tail_for = [&](int64_t w) -> int64_t { if (!tail_ok || !Prefill::tail_matters(w, srcp != nullptr)) return -1; return lr::next_tail(p.sp->chunk(), p.sp->layout_tail(), w, lr::segment_tail(tokens, w, floor_t), floor_t); }; tail_p = tail_for(want_p); int64_t need_p = part_slots(p, want_p, tail_p); int64_t want_cut = want; // the chunk this request asked for (the equal one when keep_equal took it) #if defined(STRATA_PREFILL_FUSED) && !defined(STRATA_PREFILL_MMQ) if (pf_declined_eq > 0 && want == want_full) { const int64_t eq_w = loan_chunk(tokens, pf_declined_eq); const int64_t eq_tail = tail_for(eq_w); const int64_t eq_need = part_slots(p, eq_w, eq_tail); if (strata::prefill::equal_cut::keep_equal(need_p, eq_need, (int64_t) p.cache->slots() - (int64_t) g_lend_keep)) { std::fprintf(stderr, "strata serve: prompt chunk %lld -> %lld tokens for this request: the old cut's " "buffers do not fit the slots that can be lent, the equal cut's do\n", (long long) want_p, (long long) eq_w); want_p = eq_w; want_cut = eq_w; tail_p = eq_tail; need_p = eq_need; } } #endif while ((need_p <= 0 || need_p + g_lend_keep > p.cache->slots()) && want_p > 256) { want_p = std::max(256, want_p / 2 / 256 * 256); tail_p = tail_for(want_p); need_p = part_slots(p, want_p, tail_p); } if (need_p <= 0 || need_p + g_lend_keep > p.cache->slots()) { e = "prefill: no chunk of this request fits the slots that can be lent (#2090)"; return false; } if (want_p != want_cut) std::fprintf(stderr, "strata serve: prompt chunk %lld -> %lld tokens for this request: its " "buffers do not fit the slots that can be lent (#2090)\n", (long long) want_cut, (long long) want_p); if (need_p > p.cache->slots() - p.first) // the case that ended the engine before (#2090) std::fprintf(stderr, "strata serve: the loan for a chunk of %lld tokens (%lld slots) is larger than the " "auto chunk's (%lld slots): starting it earlier (#2090)\n", (long long) want_p, (long long) need_p, (long long) (p.cache->slots() - p.first)); // --kv-grow: a long context's K/V holds slots of the loan region (kvg.top past its start) if (kvg.on && p.cache == &xcache && need_p > p.cache->slots() - kvg.top) { const int64_t asked = want_p; while (need_p > p.cache->slots() - kvg.top && want_p > 256) { want_p = std::max(256, want_p / 2 / 256 * 256); need_p = part_slots(p, want_p); } if (need_p <= 0 || need_p > p.cache->slots() - kvg.top) { e = "prefill: no chunk of this request fits beside the K/V"; return false; } std::fprintf(stderr, "strata serve: prompt chunk %lld -> %lld tokens for this request: the K/V " "holds slots up to %lld\n", (long long) asked, (long long) want_p, (long long) kvg.top); } first = (int32_t) (p.cache->slots() - need_p); } if (want_p != p.sp->chunk() || first != p.first_now || (tail_p >= 0 && tail_p != p.sp->layout_tail())) { const auto t_rl = Clock::now(); if (!p.sp->relayout(want_p, p.cache->device_slot(first), part_bytes(p, first), e, tail_p)) return false; p.first_now = first; if (tail_p >= 0) { static bool said = false; if (!said) { said = true; std::fprintf(stderr, "strata serve: the lent prompt buffers are sized for the request's own short last chunk " "(tail %lld tokens, not the stream floor's %lld); STRATA_PREFILL_TAIL_LOAN=0 keeps the floor's\n", (long long) tail_p, (long long) (floor_t - 1)); } if (trace) std::fprintf(stderr, "strata trace: relayout for %lld tokens, tail %lld, first slot %d: %.1f ms\n", (long long) want_p, (long long) tail_p, (int) first, std::chrono::duration(Clock::now() - t_rl).count()); } } for (int64_t l = p.lb; l < p.le; ++l) // THIS participant's layers only for (int64_t ex = 0; ex < g.n_expert; ++ex) { const size_t i = (size_t) (l * g.n_expert + ex); if (host_res[i] >= first) { p.lent.emplace_back((int32_t) i, host_res[i]); host_res[i] = strata::core::kNotResident; any = true; } } p.lent_chunk = want_p; } for (const PfPart& p : pf_parts) if (p.first >= 0) seg_lend = std::max(seg_lend, p.lent_chunk); if (any) res_upload(); if (trace) { int64_t n_lent = 0; for (const PfPart& p : pf_parts) n_lent += (int64_t) p.lent.size(); std::fprintf(stderr, "strata trace: lent %lld slots for %lld tokens in %.1f ms\n", (long long) n_lent, (long long) want, std::chrono::duration(Clock::now() - t_ln).count()); std::fflush(stderr); } return true; }; // --batch: a prompt read while slots are decoding goes one prompt chunk at a time (the same chunks as one // run: each run starts where the last ended, at a multiple of the chunk), and between two chunks the slots // decode for a share of the time the chunk took (STRATA_BATCH_DECODE_SHARE, default 0.5), so a long // prompt does not stop the others. The slots' windows then see the cache without the slots this prompt // borrowed (marked missing: those experts run on the CPU), never a prompt buffer. static const double decode_share = [] { const char* v = std::getenv("STRATA_BATCH_DECODE_SHARE"); return v != nullptr ? std::max(0.0, std::atof(v)) : 0.5; }(); bool batch_fatal = false; int64_t il_parts = 0; // the slots' windows run between this prompt's chunks double il_ms = 0; int64_t yielded_at = -1; // BYIELD: the read stopped here and its slot holds it int yielded_slot = -1; // `BYIELD ` (the server: a shorter request is waiting): at the next chunk boundary the part read so // far is copied into (this admission's own, or a free one the server reserved for a solo request), // the request ends with `YIELDED ` + DONE cancel, and the server sends it again later: it // continues from the slot with the same chunks. #656's cooperative preemption, with a slot as the park. int64_t req_chunk = 0, req_chunk_len = 0; // the DONE line's chunk=: the longest batched segment's first chunk // STRATA_PREFILL_CPU_SHARE_BATCH: the read takes the CPU share only with no slot decoding (their windows use the pool) auto share_gate = [&]() { int busy = 0; for (const auto& x : bs) busy += x.active ? 1 : 0; strata::prefill::Prefill::set_share_blocked(busy > 0); static int said = 0; static const bool on = [] { const char* v = std::getenv("STRATA_PREFILL_CPU_SHARE_BATCH"); return v != nullptr && v[0] == '1'; }(); if (on && said < 4) { ++said; std::fprintf(stderr, "strata batch: CPU share for this read: %s (%d slot(s) decoding)\n", busy > 0 ? "off" : "on", busy); } }; auto read_part = [&](int64_t a0, int64_t b0, std::string& e) -> bool { // --prefill-pipe on a layer split: the segment's chunk is planned ONCE, on its whole length (or taken // from the read it goes on from: resume_plan), and every run of it reads in that chunk (force_chunk) - // the same chunks whether it is read in one run, in pieces beside decoding slots, or goes on after a // BYIELD or from a checkpoint. Without the pipe nothing here changes: runs read in the buffers' chunk. ConvCheckpoint::PromptPlan plan; if (!stages.empty()) { if (resume_plan.chunk > 0 && a0 == resume_plan_at) { using strata::prefill::Prefill; const ConvCheckpoint::PromptPlan& rp = resume_plan; if (b0 == resume_plan_end && rp.from >= 0 && rp.from <= a0 && (a0 - rp.from) % rp.chunk == 0 && rp.chunk <= sp.chunk() && Prefill::pipe_key(rp.pipe) == Prefill::pipe_key(Prefill::pipe_setting())) { plan = rp; } else { std::fprintf(stderr, "strata prefill: the read going on at %lld is not the segment " "[%lld, %lld) it was planned in (%lld-token chunks): planned again\n", (long long) a0, (long long) rp.from, (long long) rp.to, (long long) rp.chunk); } resume_plan = {}; // the first segment only } if (plan.chunk <= 0) { const int64_t c = sp.plan_chunk(b0 - a0); if (c > 0) { plan.chunk = c; plan.from = a0; plan.to = b0; plan.lend = seg_lend; plan.pipe = strata::prefill::Prefill::pipe_setting(); plan.single = b0 - a0 <= c; plan.chunked = c < std::min(b0 - a0, sp.chunk()); if (plan.chunked) strata::prefill::Prefill::log_plan(b0 - a0, c, sp.stage_count()); } } } const bool planned = plan.chunk > 0; const bool plan_single = planned && plan.single; if (b0 - a0 > req_chunk_len) { req_chunk_len = b0 - a0; req_chunk = planned ? std::min(plan.chunk, b0 - a0) : std::min(sp.chunk(), b0 - a0); } seg_plan = plan; // the checkpoints taken inside it keep it; cleared when the segment is done struct SegPlanScope { ConvCheckpoint::PromptPlan& p; ~SegPlanScope() { p = {}; } } seg_plan_scope{seg_plan}; // the first run of a BGEN with co-reads: the waiting prompts are read in the same layer-major pass bool co_tried = false; auto co_run = [&](int64_t q, int64_t r, std::string& ce) -> bool { using PSeg = strata::prefill::Prefill::Seg; std::vector segs; PSeg lead; lead.tokens = ids.data() + q; lead.n = r - q; lead.pos0 = q; segs.push_back(lead); std::vector used; for (const CoReq& c : co_set) { if (c.slot < 0 || c.slot >= (int) bs.size() || c.slot == admit_slot || bs[(size_t) c.slot].active || bs[(size_t) c.slot].partial) continue; bool dup = false; for (const CoReq* u : used) dup = dup || u->slot == c.slot; if (dup) continue; PSeg sg; sg.tokens = c.ids.data(); sg.n = (int64_t) c.ids.size() - 1; // (the last token goes through the slot's own first window) sg.pos0 = 0; for (size_t k = 0; k < bslot_ss.size(); ++k) sg.stage_ss.push_back(bslot_ss[k][(size_t) c.slot].get()); segs.push_back(sg); used.push_back(&c); } if (segs.size() < 2) return sp.run(lead.tokens, lead.n, lead.pos0, ce); for (const CoReq* c : used) { park_slot(c->slot); // the conversation the slot holds, before this read overwrites it for (size_t k = 0; k < bslot_ss.size(); ++k) { const strata::core::OnDevice on_k(k == 0 ? 0 : stages[k - 1]->dev); strata::core::session_zero(*bslot_ss[k][(size_t) c->slot], g, nullptr, nullptr); cudaDeviceSynchronize(); } bs[(size_t) c->slot] = BSlot{}; // (it holds nothing until the read is done) } const auto tco = Clock::now(); std::fprintf(stderr, "strata batch: co-read starting: %zu more prompt(s) with this request's %lld tokens\n", used.size(), (long long) lead.n); std::fflush(stderr); if (!sp.run_multi(segs, ce)) { if (ce.rfind("prefill: multi-prompt read declined", 0) == 0) { // nothing was read: the usual run std::fprintf(stderr, "strata batch: co-read of %zu prompt(s) declined (%s)\n", used.size(), ce.c_str()); ce.clear(); return sp.run(lead.tokens, lead.n, lead.pos0, ce); } return false; } for (const CoReq* c : used) { BSlot& sl = bs[(size_t) c->slot]; sl = BSlot{}; sl.ids.assign(c->ids.begin(), c->ids.end() - 1); sl.cached = true; sl.cvec = want_cvec; std::printf("BCOK %d %lld\n", c->slot, (long long) sl.ids.size()); } std::fflush(stdout); std::fprintf(stderr, "strata batch: co-read: %zu more prompt(s) read in the same pass as this request's %lld tokens " "(%.0f ms)\n", used.size(), (long long) lead.n, std::chrono::duration(Clock::now() - tco).count()); return true; }; bool conc_read = false; // run_conc: the slots decode beside the read, so the share stays off for all of it // the per-length schedule's short read (STRATA_PREFILL_SHORT_MAX): 1 read, 0 declined (nothing read: the // split read follows), -1 failed. The first stage's session gets layers [0, split_at[0]) by a snapshot // of the scratch session, before anything decodes. auto short_read = [&](int64_t n, std::string& se) -> int { GpuStage& st = *stages.back(); { const strata::core::OnDevice on(st.dev); strata::core::session_zero(short_ss, g, nullptr, nullptr); if (cudaDeviceSynchronize() != cudaSuccess) { se = "short read: zeroing the scratch session failed"; return -1; } } if (!st.sp.read_short(ids.data(), n, 0, &short_ss, split_at[0], &sp, se)) { if (se.rfind("prefill: short read declined", 0) != 0) return -1; static std::string said; if (se != said) { said = se; std::fprintf(stderr, "strata prefill: %s\n", se.c_str()); } se.clear(); return 0; } const std::vector vids(ids.begin(), ids.begin() + n); const std::vector no_images; const std::vector no_checkpoints; const strata::core::ConversationView view{vids, no_images, no_checkpoints, false}; strata::core::SavedConversation image; { const strata::core::OnDevice on(st.dev); if (cudaDeviceSynchronize() != cudaSuccess || !strata::core::conversation_snapshot_save(image, view, short_ss, g, nullptr, se)) { se = "short read: the hand-back image: " + se; return -1; } } const strata::core::OnDevice on0(0); if (strata::core::conversation_snapshot_restore(image, ss, g, nullptr, se) != strata::core::ConversationRestore::restored || cudaDeviceSynchronize() != cudaSuccess) { se = "short read: the hand-back restore: " + se; return -1; } ss.ple_prev[0] = short_ss.ple_prev[0]; ss.ple_prev[1] = short_ss.ple_prev[1]; return 1; }; auto run = [&](int64_t q, int64_t r) -> bool { if (planned) sp.force_chunk(plan.chunk, plan_single, plan.chunked); if (!conc_read) share_gate(); // STRATA_PREFILL_CPU_SHARE_BATCH: re-decided for every run (a piece beside decoding slots too) bool run_ok; if (!co_set.empty() && !co_tried && admit_slot >= 0 && req_imgs.empty()) { co_tried = true; run_ok = co_run(q, r, e); } else if (short_on && q == 0 && r >= short_min && r <= short_max) { const int s = short_read(r, e); run_ok = s > 0 || (s == 0 && sp.run(ids.data() + q, r - q, q, e)); } else { run_ok = sp.run(ids.data() + q, r - q, q, e); } if (run_ok && q == 0 && sp.kva_floor() > 0) { // KVA approximated the start of this prompt: remember which tokens kva_floors.note(ids.data(), sp.kva_floor()); if (use_mtp && mtp.cell_floor_enabled()) mtp.set_cell_floor(sp.kva_floor()); } return run_ok; }; // STRATA_BATCH_CONCURRENT_READ=1 (opt-in, one GPU, --batch with --no-prefill-borrow): the prompt is read on a // thread of its own while this thread keeps the slots' batch windows going, so the decoding slots do not // stop for an admission. The prompt writes the main session, the windows the slots' sessions; the prompt // borrows no cache slots (--no-prefill-borrow), so the windows' experts stay where they are. The same // bytes are computed as in the serial form (a window's rows do not depend on what else is on the GPU). static const bool conc1 = [] { const char* v = std::getenv("STRATA_BATCH_CONCURRENT_READ"); return v != nullptr && std::atoi(v) != 0; }(); auto run_conc = [&](int64_t q, int64_t r) -> bool { if (!conc1 || piped || !stages.empty() || o.batch <= 0 || !o.no_prefill_borrow || !batch_on() || !req_imgs.empty() || kvg.on) return run(q, r); std::atomic done{false}; bool read_ok = false; in_prompt_read = true; conc_read = true; strata::prefill::Prefill::set_share_blocked(true); std::thread reader([&] { try { // (an exception leaving a std::thread ends the process: a failed read instead) read_ok = run(q, r); } catch (const std::exception& x) { read_ok = false; e = std::string("the prompt read failed: ") + x.what(); } catch (...) { read_ok = false; e = "the prompt read failed"; } done.store(true, std::memory_order_release); { std::lock_guard lk(in_mu); } in_cv.notify_all(); }); bool step_ok = true; int64_t windows0 = bt_windows; const auto tc = Clock::now(); while (!done.load(std::memory_order_acquire)) { if (step_ok && batch_on()) { step_ok = batch_step(); } else { std::unique_lock lk(in_mu); in_cv.wait_for(lk, std::chrono::milliseconds(2), [&] { return done.load(std::memory_order_acquire); }); } std::lock_guard lk(in_mu); // a BSTOP that came meanwhile ends its slot at its next window for (auto it = in_lines.begin(); it != in_lines.end();) { if (it->rfind("BSTOP ", 0) == 0) { const int b = std::atoi(it->c_str() + 6); if (b >= 0 && b < (int) bs.size()) bs[(size_t) b].stop = true; it = in_lines.erase(it); } else { ++it; } } } reader.join(); in_prompt_read = false; conc_read = false; std::fprintf(stderr, "strata batch: read %lld tokens on a thread of its own in %.0f ms; the slots ran %lld windows meanwhile\n", (long long) (r - q), std::chrono::duration(Clock::now() - tc).count(), (long long) (bt_windows - windows0)); if (!step_ok) { batch_fatal = true; e = "a batch window failed"; return false; } return read_ok; }; // (a layer split reads its stages as a pipeline over one run's chunks: beside slots a chunk at a time, with // none decoding in pieces of STRATA_BATCH_YIELD_CHUNKS chunks (default 8; 0 = one run) so a BYIELD is taken) static const int64_t yield_chunks = [] { const char* v = std::getenv("STRATA_BATCH_YIELD_CHUNKS"); return v != nullptr ? (int64_t) std::max(0, std::atoi(v)) : (int64_t) 8; }(); // a piece's chunk: the buffers' chunk, or with a plan as many whole planned chunks as that holds (the // stages still pipeline inside a piece, and every piece starts on the plan's grid) const int64_t C = planned ? std::max(1, sp.chunk() / plan.chunk) * plan.chunk : std::max(sp.chunk(), 1); const int64_t C_read = planned ? plan.chunk : C; // what the yield test calls a chunk // BYIELD with the read stopped at q (nothing in flight): the part read waits in slot ys and the // read ends with e = "yield" (true); false when it cannot give way there (the read goes on). Only // where the rest is read the same way after it (more than a chunk and more than a short read left), // text only, and into a slot that is not decoding. auto give_way = [&](int ys, int64_t q, std::string& err) -> bool { const bool can = ys < (int) bs.size() && !bs[(size_t) ys].active && (admit_slot < 0 || ys == admit_slot) && req_imgs.empty() && o.prompt_cache > 0 && b0 - q > std::max(C_read, o.short_read); std::string ye; const auto ty = Clock::now(); std::vector pre(ids.begin(), ids.begin() + q); if (can) park_slot(ys); // the conversation the slot holds, before this read overwrites it if (can && copy_to_slot(ys, pre, ye)) { BSlot& sl = bs[(size_t) ys]; sl = BSlot{}; sl.ids = std::move(pre); sl.cached = true; sl.partial = true; sl.partial_from0 = read_from == 0 || resumed_from0; if (planned) sl.partial_plan = plan; // the resend reads the rest in these chunks sl.cvec = cvec_cached; for (const ConvCheckpoint& c : checks) // the root / periodic checkpoints of this read if ((int64_t) c.ids.size() <= q && std::equal(c.ids.begin(), c.ids.end(), ids.begin(), [](int32_t x, int64_t y) { return (int64_t) x == y; })) sl.checks.push_back(c); yielded_at = q; yielded_slot = ys; std::fprintf(stderr, "strata batch: the prompt read gives way at %lld of %lld tokens; slot %d " "holds it (copied in %.1f ms)\n", (long long) q, (long long) n, ys, std::chrono::duration(Clock::now() - ty).count()); err = "yield"; return true; } if (can) bs[(size_t) ys].cached = false; // half written std::fprintf(stderr, "strata batch: BYIELD %d not taken at %lld of %lld%s%s\n", ys, (long long) q, (long long) n, ye.empty() ? "" : ": ", ye.c_str()); return false; }; // Opt-in, experimental: STRATA_PIPED_CONCURRENT=1 reads the prompt on a thread of its own while // this thread keeps the slot groups decoding through the pipeline (pump), so they never stop for it // and the read has no drain inside it. The prompt and the windows use their own streams and memory // (the prompt's K/V goes to the main sessions, the slots' to theirs; the PLE table is locked), and // the adaptive tier stands still (its round landed before the read). The slots the prompt borrowed // were lent before this read with nothing in flight and are refilled after it, so the windows see // them missing and compute those experts on the CPU, as between pieces. A BYIELD ends the run at // its next chunk (Prefill::stop_at_chunk): the pipeline is drained there and the part read gives // way as below, or the read goes on from there. // Not where a read's thread allocates or frees (the idle stage's help, STRATA_PREFILL_HELP; the batched // draft K/V, STRATA_SPLIT_MTP_BATCH: a free waits for the device), where serving a doorbell makes a // CUDA call (--pcie-mode dma, the Foresight swap space STRATA_FS_SLOTS, the helper caches), and where // the expert source recycles the buffers it hands out (the GGUF in place, an unbuffered source, the // I/O read-ahead: one thread at a time). Pictures are read the usual way (their rows go up through // pinned slots of a size known only then). static const bool pr_conc = [&] { const char* v = std::getenv("STRATA_PIPED_CONCURRENT"); if (v == nullptr || std::atoi(v) == 0) return false; auto env_on = [](const char* k) { const char* x = std::getenv(k); return x != nullptr && std::atoi(x) != 0; }; strata::program::ConcurrentReadSetup s; s.prefill_help = env_on("STRATA_PREFILL_HELP"); s.split_mtp_batch = env_on("STRATA_SPLIT_MTP_BATCH"); s.fs_slots = env_on("STRATA_FS_SLOTS"); s.pcie_dma = o.pcie_mode == "dma"; // (--remote-expert-opt works only through a helper cache, so without one it does not count) s.helper_caches = prefill_src != srcp; for (int r = 0; r < 3; ++r) s.helper_caches |= o.expert_cache_remote[(size_t) r] > 0; s.staged_source = srcp == &src && src.stages_blobs(); s.other_source = srcp != &src && srcp != &arena_src; if (const char* why = strata::program::concurrent_read_off(s)) { std::fprintf(stderr, "strata batch: STRATA_PIPED_CONCURRENT is off beside %s\n", why); return false; } return true; }(); // STRATA_PIPED_CONCURRENT_MIN=N (opt-in, with STRATA_PIPED_CONCURRENT=1): only a read of at least N tokens // runs beside the decoding slots on its own thread; a shorter one takes the usual path (drained windows, // no priority streams' cost on the short prompts' TTFT and throughput). Unset or 0: every read, as before. static const int64_t pr_conc_min = [] { const char* v = std::getenv("STRATA_PIPED_CONCURRENT_MIN"); return v != nullptr ? (int64_t) std::max(0LL, std::atoll(v)) : (int64_t) 0; }(); if (piped && pr_conc && req_imgs.empty() && (b0 - a0) >= pr_conc_min) { // (with no slot decoding it only watches for a BYIELD) // the drafter's prompt pass captures its graphs and grows its records at first use, and the // prompt path's pinned upload slots grow at their first larger upload: done here, with nothing in // flight (on the reader's thread a capture, an allocation or a free takes the driver's lock and // can wait for the device, #31) if (use_mtp && !mtp.reserve_prefill(C, e)) return false; if (!sp.reserve_uploads(C)) std::fprintf(stderr, "strata batch: the prompt path's pinned upload slots could not be " "reserved (they grow at first use)\n"); // where the read's thread and the doorbell thread run: on Linux a thread inherits its creator's // CPUs, and the host thread is pinned to the one core the pool leaves it, so both would share that // core with the host thread that pumps the windows - every window then waits its turn there for // the doorbell of each layer (4x RTX 5080, 4 stages: 6 rows/s during a read). They move off the // host's core and the pool workers' CPUs instead (--aux-cpus places them, when it is on). // STRATA_PIPED_CONCURRENT_UNPIN=0 keeps the inherited CPUs (an A/B); STRATA_TEST_CONC_ON_HOST_CPU=1 // (Windows, a test) puts them on the host thread's CPUs first, as Linux does. static const bool conc_unpin = [] { const char* v = std::getenv("STRATA_PIPED_CONCURRENT_UNPIN"); return v == nullptr || std::atoi(v) != 0; }(); #if defined(_WIN32) static const bool conc_on_host = std::getenv("STRATA_TEST_CONC_ON_HOST_CPU") != nullptr; std::vector host_cpu_sets; if (conc_on_host) { const HANDLE self = GetCurrentThread(); ULONG count = 0; if (GetThreadSelectedCpuSets(self, nullptr, 0, &count) || GetLastError() == ERROR_INSUFFICIENT_BUFFER) { host_cpu_sets.resize(count); if (count && !GetThreadSelectedCpuSets(self, host_cpu_sets.data(), count, &count)) host_cpu_sets.clear(); } static bool said = false; if (!said) { said = true; std::fprintf(stderr, "strata batch: test: the read's and the doorbell threads start on the " "host thread's %zu CPU set(s)%s\n", host_cpu_sets.size(), conc_unpin ? ", then leave them (the fix)" : " and stay there (as on Linux)"); } } #endif // the threads that already inherited the host's core (the prompt path's copy threads, started by // the first prompt on the host thread) work during the read too: off that core as well (Linux) if (conc_unpin && !strata::aux_cpus::enabled()) if (const int moved = strata::aux_cpus::release_host_inheritors(); moved > 0) std::fprintf(stderr, "strata batch: %d threads that ran on the host thread's core moved off " "it, for reads beside the slots\n", moved); auto conc_thread_cpus = [&] { strata::aux_cpus::pin_current_thread(); #if defined(_WIN32) const HANDLE self = GetCurrentThread(); if (conc_on_host && !host_cpu_sets.empty()) SetThreadSelectedCpuSets(self, host_cpu_sets.data(), (ULONG) host_cpu_sets.size()); if (conc_unpin && conc_on_host) SetThreadSelectedCpuSets(self, nullptr, 0); #else if (conc_unpin && !strata::aux_cpus::enabled()) (void) strata::aux_cpus::place_off_host(); #endif }; // the slots' doorbells are served on a thread of their own for the read, which makes no CUDA // call: a call here or on the read's threads can wait for the driver's lock while its holder // waits for the GPU (a free; a module the first kernel of a shape loads), and a window on that // GPU waits for its doorbell (#31). Ends (and hands the service back to pump) on every exit. struct Doorbells { std::atomic on{true}; std::thread th; std::function wake, off; ~Doorbells() { on.store(false, std::memory_order_release); if (wake) wake(); if (th.joinable()) th.join(); if (off) off(); } } bells; for (int k = 0; k < n_pipe; ++k) stage_verifier(k).set_external_serve(true); conc_serving = true; bells.off = [&] { for (int k = 0; k < n_pipe; ++k) stage_verifier(k).set_external_serve(false); conc_serving = false; }; bells.wake = [&] { std::lock_guard lk(bell_mu); bell_cv.notify_one(); }; bells.th = std::thread([&] { conc_thread_cpus(); auto any_busy = [&] { for (int k = 0; k < n_pipe; ++k) if (stage_verifier(k).batch_busy()) return true; return false; }; while (bells.on.load(std::memory_order_acquire)) { bool busy = false; for (int k = 0; k < n_pipe; ++k) { auto& vk = stage_verifier(k); if (vk.batch_busy()) { busy = true; vk.batch_serve(win_pool_fn, win_pool_user); } } if (busy) continue; // STRATA_TEST_BELL_SLEEP_US=N (a test, an A/B of the wait below): sleep N us instead, as // the first form of this thread did (a whole timer tick on Windows) static const int test_sleep_us = [] { const char* t = std::getenv("STRATA_TEST_BELL_SLEEP_US"); return t != nullptr ? std::max(0, std::atoi(t)) : 0; }(); if (test_sleep_us > 0) { std::this_thread::sleep_for(std::chrono::microseconds(test_sleep_us)); continue; } // no window in flight: wait for pump's next launch (it notifies when this is set; the // fences pair the flag with batch_launch's running flag, so one of the two sides sees the // other), or for the end of the read std::unique_lock lk(bell_mu); bell_waiting.store(true, std::memory_order_relaxed); std::atomic_thread_fence(std::memory_order_seq_cst); bell_cv.wait_for(lk, std::chrono::milliseconds(2), [&] { return !bells.on.load(std::memory_order_acquire) || any_busy(); }); bell_waiting.store(false, std::memory_order_relaxed); } }); for (int64_t q0 = a0; q0 < b0;) { const auto tc = Clock::now(); const int64_t rows0 = pipe_rows; // per stage, for the read's log line: its windows and the host time that set them up (the // PLE gather included, which waits while the prompt holds the table) - both this thread's std::vector> st0((size_t) n_pipe); for (int k = 0; k < n_pipe; ++k) st0[(size_t) k] = {stage_verifier(k).windows, stage_verifier(k).ms_host}; std::atomic done{false}; std::atomic want_yield{-1}; bool read_ok = true; std::string read_err; in_prompt_read = true; sp.stop_at_chunk = [&] { return want_yield.load(std::memory_order_acquire) >= 0; }; share_gate(); // on this thread, before the reader starts std::thread reader([&] { conc_thread_cpus(); try { // (an exception leaving a std::thread ends the process: a failed read instead) if (planned) sp.force_chunk(plan.chunk, plan_single, plan.chunked); read_ok = sp.run(ids.data() + q0, b0 - q0, q0, read_err); } catch (const std::exception& x) { read_ok = false; read_err = std::string("the prompt read failed: ") + x.what(); } catch (...) { read_ok = false; read_err = "the prompt read failed"; } done.store(true, std::memory_order_release); { std::lock_guard lk(in_mu); } // (the loop below may be waiting on in_cv) in_cv.notify_all(); }); struct ReadEnd { // on every way out of this round (an exception too): the reader joined first std::thread& t; std::function& hook; bool& reading; ~ReadEnd() { if (t.joinable()) t.join(); hook = nullptr; reading = false; } } read_end{reader, sp.stop_at_chunk, in_prompt_read}; bool pump_ok = true; size_t seen = 0; // in_lines' length after the last look: a line that comes wakes the wait while (!done.load(std::memory_order_acquire)) { const bool decoding = pump_ok && (batch_on() || pipe_inflight()); if (decoding) pump_ok = pump(true); std::unique_lock lk(in_mu); if (!decoding) // nothing to pump: until the read ends or a line comes (both notify) in_cv.wait_for(lk, std::chrono::milliseconds(2), [&] { return done.load(std::memory_order_acquire) || in_lines.size() != seen; }); // a BSTOP that came meanwhile ends its slot at its next window; a BYIELD ends the read at // its next chunk for (auto it = in_lines.begin(); it != in_lines.end();) { if (it->rfind("BSTOP ", 0) == 0) { const int b = std::atoi(it->c_str() + 6); if (b >= 0 && b < (int) bs.size()) bs[(size_t) b].stop = true; it = in_lines.erase(it); } else if (it->rfind("BYIELD ", 0) == 0 && want_yield.load() < 0) { want_yield.store(std::atoi(it->c_str() + 7), std::memory_order_release); it = in_lines.erase(it); } else { ++it; } } seen = in_lines.size(); } reader.join(); // (a failed window leaves the read to finish: it is not stopped mid-run) sp.stop_at_chunk = nullptr; in_prompt_read = false; if (!pump_ok || !pipe_drain()) { batch_fatal = true; e = "a pipelined batch window failed"; return false; } const int64_t q = read_ok && sp.stopped_at() >= 0 ? q0 + sp.stopped_at() : b0; const double read_ms = std::chrono::duration(Clock::now() - tc).count(); std::string per; for (int k = 0; k < n_pipe; ++k) { const auto& v = stage_verifier(k); const int64_t w = v.windows - st0[(size_t) k].first; char b[96]; const double host = w > 0 ? (v.ms_host - st0[(size_t) k].second) / (double) w : 0.0; std::snprintf(b, sizeof b, "%sstage %d: %lld windows, %.1f ms host each", k ? "; " : "", k + 1, (long long) w, host); per += b; } std::fprintf(stderr, "strata batch: read %lld tokens on a thread of its own in %.0f ms " "(concurrent, to %lld of %lld); the slots decoded %lld rows meanwhile " "(%.1f rows/s; %s)\n", (long long) (q - q0), read_ms, (long long) q, (long long) n, (long long) (pipe_rows - rows0), read_ms > 0.0 ? 1000.0 * (double) (pipe_rows - rows0) / read_ms : 0.0, per.c_str()); if (!read_ok) { e = read_err; return false; } if (q < b0 && give_way(want_yield.load(), q, e)) return false; q0 = q; // done, or the give-way was not taken there: the rest goes on the same way } return true; } // Opt-in (#1906): on the pipelined slot groups a read goes in pieces of STRATA_PIPED_READ_PIECE tokens // (whole chunks). A piece's end has the pipeline drained, so a waiting shorter request can take // over there (BYIELD); with slots decoding, the groups then decode through the pipeline (pump) for // STRATA_BATCH_DECODE_SHARE x the piece's time, capped / floored by STRATA_PIPED_DECODE_MAX_MS / // _MIN_MS, and are drained (pipe_drain) before the next piece, as before any read. Unset: one run. static const int64_t pr_piece = [] { const char* v = std::getenv("STRATA_PIPED_READ_PIECE"); return v != nullptr ? (int64_t) std::max(0, std::atoi(v)) : (int64_t) 0; }(); static const double pr_cap = [] { const char* v = std::getenv("STRATA_PIPED_DECODE_MAX_MS"); return v != nullptr ? std::max(0.0, std::atof(v)) : 0.0; }(); static const double pr_floor = [] { const char* v = std::getenv("STRATA_PIPED_DECODE_MIN_MS"); return v != nullptr ? std::max(0.0, std::atof(v)) : 0.0; }(); const bool pr_on = piped && pr_piece > 0; auto piece_now = [&]() -> int64_t { return pr_on ? strata::program::piped_read_piece(pr_piece, C) : strata::program::batch_read_piece(o.batch > 0, piped, !stages.empty(), batch_on(), C, yield_chunks); }; // the slots decode through the pipeline for budget_ms, drained before the next read auto piped_decode = [&](double budget_ms, std::string& err) -> bool { const auto td = Clock::now(); in_prompt_read = true; do { if (!pump(true)) { in_prompt_read = false; batch_fatal = true; err = "a pipelined batch window failed"; return false; } } while (batch_on() && std::chrono::duration(Clock::now() - td).count() < budget_ms); if (!pipe_drain()) { in_prompt_read = false; batch_fatal = true; err = "a pipelined batch window failed"; return false; } in_prompt_read = false; ++il_parts; il_ms += std::chrono::duration(Clock::now() - td).count(); return true; }; // prompts arriving back to back: one decode budget before a read that follows a piecewise read static Clock::time_point pr_prev_end{}; static bool pr_have_prev = false; static double pr_prev_piece_ms = 0.0; // the previous read's last full piece if (pr_on) { const double lead = pr_prev_piece_ms > 0.0 ? strata::program::piped_decode_budget_ms(pr_prev_piece_ms, decode_share, pr_cap, pr_floor) : (pr_cap > 0.0 ? pr_cap : std::max(pr_floor, 200.0)); const double since = pr_have_prev ? std::chrono::duration(Clock::now() - pr_prev_end).count() : -1.0; if (strata::program::piped_read_lead_in(true, batch_on(), since, lead)) { const int64_t rows0 = pipe_rows; const auto tl = Clock::now(); if (!piped_decode(lead, e)) return false; std::fprintf(stderr, "strata batch: a read right after a read: the slots decoded %lld rows in " "%.0f ms first\n", (long long) (pipe_rows - rows0), std::chrono::duration(Clock::now() - tl).count()); } } int64_t piece = piece_now(); if (piece <= 0) return run(a0, b0); for (int64_t q = a0; q < b0;) { const int64_t r = std::min(b0, q + piece); const auto tq = Clock::now(); if (!run_conc(q, r)) return false; const double piece_ms = std::chrono::duration(Clock::now() - tq).count(); if (pr_on && r < b0) pr_prev_piece_ms = piece_ms; const int64_t piece_tokens = r - q; q = r; if (q >= b0) continue; int ys = -1; { // a BSTOP that came meanwhile ends its slot at its next window; a BYIELD is for this read std::lock_guard lk(in_mu); for (auto it = in_lines.begin(); it != in_lines.end();) { if (it->rfind("BSTOP ", 0) == 0) { const int b = std::atoi(it->c_str() + 6); if (b >= 0 && b < (int) bs.size()) bs[(size_t) b].stop = true; it = in_lines.erase(it); } else if (it->rfind("BYIELD ", 0) == 0) { ys = std::atoi(it->c_str() + 7); it = in_lines.erase(it); } else { ++it; } } } if (ys >= 0 && give_way(ys, q, e)) return false; // (on the pipelined path a piece's end has the pipeline drained - nothing runs during a piece and // every decode budget ends in pipe_drain - so the part read can give way there as off the pipeline) if (pr_on) { // the pipelined pieces: the slots decode through the pipeline, then it is drained if (!batch_on()) { std::fprintf(stderr, "strata batch: piped read %lld tokens in %.0f ms (to %lld of %lld)\n", (long long) piece_tokens, piece_ms, (long long) q, (long long) n); continue; } const double budget = strata::program::piped_decode_budget_ms(piece_ms, decode_share, pr_cap, pr_floor); const int64_t rows0 = pipe_rows; const auto td = Clock::now(); if (!piped_decode(budget, e)) return false; std::fprintf(stderr, "strata batch: piped read %lld tokens in %.0f ms (to %lld of %lld), " "then the slots decoded %lld rows in %.0f ms\n", (long long) piece_tokens, piece_ms, (long long) q, (long long) n, (long long) (pipe_rows - rows0), std::chrono::duration(Clock::now() - td).count()); continue; } if (decode_share <= 0.0 || !batch_on()) continue; const double budget = decode_share * std::chrono::duration(Clock::now() - tq).count(); const auto td = Clock::now(); in_prompt_read = true; do { if (!batch_step()) { in_prompt_read = false; batch_fatal = true; e = "a batch window failed"; return false; } } while (batch_on() && std::chrono::duration(Clock::now() - td).count() < budget); in_prompt_read = false; ++il_parts; il_ms += std::chrono::duration(Clock::now() - td).count(); if (trace) { std::fprintf(stderr, "strata trace: prompt chunk to %lld, then the slots decoded %.0f ms\n", (long long) q, std::chrono::duration(Clock::now() - td).count()); std::fflush(stderr); } } if (pr_on) { pr_prev_end = Clock::now(); pr_have_prev = true; } // for the next read's lead-in return true; }; apply_pending(true); const auto drain_t0 = Clock::now(); const bool drained_ok = adapt_tick(true); // 149: how long the request waited for the adaptive round still in flight (in the prompt's time) serve_adapt_drain_ms = std::chrono::duration(Clock::now() - drain_t0).count(); if (!drained_ok) { // --adapt-async: the round in flight lands before the prompt lends any slot std::printf("ERR an adaptive refill failed\n"); return 1; } // per-request sampling for the verify window's head (greedy when temperature is absent) strata::kernels::SamplerParams req_sp; req_sp.greedy = req_temperature <= 0.0f; req_sp.temperature = req_temperature; req_sp.top_p = req_top_p; req_sp.top_k = req_top_k; req_sp.seed = req_seed ? req_seed : (unsigned long long) std::chrono::steady_clock::now().time_since_epoch().count(); req_sp.min_p = std::clamp(req_min_p, 0.0f, 1.0f); req_sp.penalty_last_n = std::max(req_penalty_last_n, 0); req_sp.penalty_repeat = req_penalty_repeat; req_sp.penalty_freq = req_penalty_freq; req_sp.penalty_present = req_penalty_present; req_sp.counter = 0; if (!ver.set_logit_bias(req_bias, err) || (pipe && !ver_b.set_logit_bias(req_bias, err)) || (use_mtp && !mtp.set_draft_ban(req_bias, err))) { std::printf("ERR %s\n", err.c_str()); return 1; } ver.set_sampling(req_sp); if (pipe) ver_b.set_sampling(req_sp); // (reaches the later stage's odd verifier) if (use_mtp) mtp.set_draft_sampling(req_sp); // STRATA_SPEC_COUPLED=1: sampled drafts (a no-op otherwise) const bool gated_proposal = use_mtp && mtp.prob() && strata::core::spec_gate_pick() && gated_proposal_usable(o.pipeline_windows < 2 && o.batch == 0 && n_stages == 1 && !multi_gpu && drive.d.remote_count == 0, o.lookup_chain, o.adapt_swaps, req_pcie_frac != 0.0 || o.pcie_frac_auto, spec_cost || req_df2, S, req_spec_min_p); { // aux_cpus=0|1: where the non-pool, non-host threads run for this request (-1 = the start-up --aux-cpus); moves // threads only. An enabled placement is swept at every request: it catches threads created since. static const bool aux_start = strata::aux_cpus::enabled(); const bool was_on = strata::aux_cpus::enabled(); const bool want = req_aux_cpus < 0 ? aux_start : req_aux_cpus != 0; strata::aux_cpus::set_enabled(want); if (want != was_on) std::fprintf(stderr, "strata serve: aux cpus %s for this request%s\n", strata::aux_cpus::enabled() ? "ON" : "off", want && !strata::aux_cpus::enabled() ? " (asked for, but no CPU is spare: see the start-up line)" : ""); } ver.pause_pcie_balance(req_pcie_set); // the measured costs keep across requests drive.d.pcie_num = std::max(0, std::min(256, (int) (req_pcie_frac * 256.0 + 0.5))); // a layer split: CUDA0's share as asked; a later GPU keeps its own (its link) unless the request sets one for (int st = 0; st < split_drive.n; ++st) split_drive.pcie_num[st] = (st == 0 || split_same || req_pcie_frac != o.pcie_frac) ? drive.d.pcie_num : pcie_num_of(stages[(size_t) st - 1]->pcie_frac); if (pipe) for (int st = 0; st < split_drive.n; ++st) split_drive_b.pcie_num[st] = split_drive.pcie_num[st]; const int hist_n = std::min(req_sp.penalty_last_n, kPenaltyWindowCap); // #4590: the repeat / frequency / presence penalties count the tokens this reply has written, not the prompt's last // tokens (the prompt's own numbers and quoted answers were penalised, and a conversation whose last turn asks for // something new could get its previous answer back). Earlier assistant turns inside the prompt are not counted // either. STRATA_PENALTY_PROMPT=1 brings the old window back (the last penalty_last_n tokens of prompt + reply). // The history is rebuilt from the request's prompt ids every time, so a conversation restored from the cache or a // saved slot seeds it exactly as a cold read does. static const bool pen_prompt = strata::kernels::penalty_counts_prompt(std::getenv("STRATA_PENALTY_PROMPT")); ver.set_history(hist_n > 0 ? d_hist : nullptr, hist_n); if (pipe) ver_b.set_history(hist_n > 0 ? d_hist : nullptr, hist_n); bool cancelled = false; tr("prompt start", n - 1); // The prompt is read in two parts when it has a turn boundary past `resume`: up to the last <|im_start|> // (the conversation so far), a checkpoint there, then the new turn's header. The next request of the same // chat renders the same history - but not always the same header or the thinking of this reply - so that // checkpoint is the one it reuses. int64_t turn_at = -1; if (o.prompt_cache > 0 && o.turn_token >= 0) for (int64_t i = n - 1; i > resume; --i) if (ids[(size_t) i] == o.turn_token) { turn_at = i; break; } // #458 (opt-in): a short turn of --tail-role-token's role right before the new assistant turn (the // server's trailing reasoning-effort turn) stays out of the checkpoint, so the next request - another // effort, or the next turn of the chat - finds the conversation without it if (turn_at > 0 && o.tail_role_token >= 0) for (int64_t i = turn_at - 1; i > resume; --i) if (ids[(size_t) i] == o.turn_token) { if (ids[(size_t) i + 1] == o.tail_role_token) turn_at = i; break; } // A prompt read from token 0 also stops at its FIRST turn boundary: the end of the system prompt (with // the tools), which every new chat of the same client shares. That checkpoint becomes the chain's root, // which the retention policy pins (conv_cache.hpp), so the next new chat reads only what comes after it. // (PR #65, code-martin.) Only for a system prompt of --prompt-cache-root tokens or more: a small one // is cheaper to read again than the extra part costs (~0.3 s). const int64_t last_turn = turn_at; // ckpt=0 drops the split there, the root is still looked for before it if (!req_ckpt) turn_at = -1; int64_t root_at = -1; if (o.prompt_cache > 0 && o.turn_token >= 0 && o.prompt_cache_root > 0 && (read_from == 0 || resumed_from0)) for (int64_t i = 1; i < last_turn; ++i) if (ids[(size_t) i] == o.turn_token) { if (i >= o.prompt_cache_root) root_at = i; break; } static const bool message_checkpoint = [] { const char* e = std::getenv("STRATA_CACHE_MESSAGE_BOUNDARY"); return e != nullptr && std::atoi(e) != 0; }(); // Only add a snapshot; the existing token and image checks still decide reuse. const int64_t message_at = message_checkpoint && !multi_gpu && o.prompt_cache > 0 ? strata::program::message_checkpoint_boundary(ids, resume, turn_at, o.turn_token) : -1; // pin=N (opt-in): one more place the prompt is read to and checkpointed. One pinned prefix at a time: a // new pin replaces the old; it needs room for the root, the pin and a rotating checkpoint int64_t pin_at = -1; auto pin_checkpoint = [&](int64_t L) { bool found = false; for (ConvCheckpoint& c : checks) { c.pinned = (int64_t) c.ids.size() == L; found = found || c.pinned; } return found; }; if (req_pin > 0) { if (o.prompt_cache < 3 || !req_ckpt) std::fprintf(stderr, "strata serve: pin=%lld ignored: %s\n", (long long) req_pin, req_ckpt ? "it needs --prompt-cache 3 or more" : "ckpt=0 keeps no checkpoint"); else if (req_pin >= n - 1) std::fprintf(stderr, "strata serve: pin=%lld ignored: the prefix must be shorter than the prompt " "(%lld tokens)\n", (long long) req_pin, (long long) n); else if (req_pin > read_from) pin_at = req_pin; else if (!pin_checkpoint(req_pin)) std::fprintf(stderr, "strata serve: pin=%lld: the cache has no checkpoint there to pin (it resumed from " "%lld)\n", (long long) req_pin, (long long) read_from); } std::vector cuts = {reread_to, root_at, message_at, turn_at, n - 1}; if (pin_at >= 0) cuts.push_back(pin_at); for (const strata::core::ScrRun& r : scr.runs) cuts.push_back(r.at); // SCR: each part ends at a run if (pin_at >= 0 || !scr.empty()) std::sort(cuts.begin(), cuts.end()); // the skipped -1s first, n - 1 still last int64_t at = read_from; // STRATA_ADMIT_MERGE_FIRST: the last part, when it goes through the windows, leaves its last tokens (up to // max_t with the last prompt token) to the first window, which starts at merge_at (-1: the first window // holds the last prompt token alone). Only where every window row is the same in any window: a batch // admission's first token, every expert of every stage in VRAM (the zero-doorbell graphs, no loan, no swap) // and the serial loop with nothing else reading its windows int64_t merge_at = -1; auto merge_from = [&](int64_t a0, int64_t to) -> int64_t { if (!admit_merge_first_env() || admit_slot < 0 || max_new != 1 || batch_mtp || pipe) return -1; if (hist_n > 0 && !pen_prompt) return -1; // #4590: the merged window's prompt rows would join the reply-only penalty window if (to != n - 1 || to == turn_at || to == root_at || to == message_at || to == pin_at) return -1; if (!req_imgs.empty() || kvg.on || peer.valid() || remote_caches || remote_opt || fs_swap) return -1; if (std::getenv("STRATA_LOGPOS") != nullptr) return -1; if (host_res.empty() || !pending.empty() || std::any_of(host_res.begin(), host_res.end(), [](int32_t r) { return r < 0; })) return -1; int mt = strata::kernels::kVerifyMaxT; for (int k = 0; k < n_pipe; ++k) { if (!stage_verifier(k).ar_live()) return -1; mt = std::min(mt, stage_verifier(k).max_t()); } if (mt < 2) return -1; return std::max(a0, n - mt); }; // SCR: the read reached a run. Its first pooled key comes back (the part's spare overwrote it), the read // goes on after it, and after the last run the GDN state and the indexer's tail are the checkpoint's there. size_t scr_next = 0; auto scr_take = [&]() -> bool { const strata::core::ScrRun& r = scr.runs[scr_next]; const int64_t D = g.idx_key_dim, bl = strata::kernels::qsa_real_shapes().idx_block; const auto states = scr_states(); bool ok = true; for (size_t i = 0; i < states.size(); ++i) { const strata::core::OnDevice on(states[i].dev); float*& row = scr_first[i][scr_next]; ok = ok && cudaMemcpyAsync(states[i].st->idx_pooled + (r.at / bl) * D, row, (size_t) D * sizeof(float), cudaMemcpyDeviceToDevice, (cudaStream_t) states[i].stream) == cudaSuccess && cudaStreamSynchronize((cudaStream_t) states[i].stream) == cudaSuccess; cudaFree(row); row = nullptr; } at = r.at + r.n; pp_reached = at; if (++scr_next == scr.runs.size()) { // STRATA_SCR_ADOPT_GDN=0: the indexer's tail from the checkpoint, but the GDN and PLE state as the // parts read it (the checkpoint's state also holds the text the edit removed) static const bool adopt_gdn = [] { const char* e = std::getenv("STRATA_SCR_ADOPT_GDN"); return e == nullptr || e[0] != '0'; }(); if (!adopt_gdn) { ConvCheckpoint now; ok = ok && gpu_sync_ok() && checkpoint_save(now, ss, g); scr_adopt.gdn = std::move(now.gdn); scr_adopt.ple = std::move(now.ple); for (size_t i = 0; ok && i < stages.size(); ++i) { const strata::core::OnDevice on(stages[i]->dev); ConvCheckpoint part; ok = gpu_sync_ok() && checkpoint_save(part, stages[i]->ss, g); scr_adopt.stage_parts[i].gdn = std::move(part.gdn); scr_adopt.stage_parts[i].ple = std::move(part.ple); } } ok = ok && gpu_sync_ok() && checkpoint_restore(scr_adopt, ss, g); for (size_t i = 0; ok && i < stages.size(); ++i) { const strata::core::OnDevice on(stages[i]->dev); ok = gpu_sync_ok() && checkpoint_restore(scr_adopt.stage_parts[i], stages[i]->ss, g); } } // the n-gram hash's predecessors are the run's last tokens const int32_t p0 = at >= 2 ? (int32_t) ids[(size_t) (at - 2)] : -1, p1 = (int32_t) ids[(size_t) (at - 1)]; ss.ple_prev[0] = p0; ss.ple_prev[1] = p1; for (auto& sg : stages) { sg->ss.ple_prev[0] = p0; sg->ss.ple_prev[1] = p1; } return ok; }; for (const int64_t to : cuts) { while (scr_next < scr.runs.size() && scr.runs[scr_next].at == at) if (!scr_take()) { std::printf("ERR scr: restoring the state after a moved run failed\n"); std::fflush(stdout); return 1; } if (to <= at) continue; err.clear(); const bool win = windows_ok(at, to); if (win && !refill(err)) { std::printf("ERR refilling a lent slot failed: %s\n", err.c_str()); return 1; } // a read going on in a planned segment gets the loan it was read with (what is left would size // another, and the loan decides which experts are read in place: bits) const int64_t plan_lend = resume_plan.chunk > 0 && at == resume_plan_at && to == resume_plan_end ? resume_plan.lend : 0; if (!win && !lend(to - at, err, plan_lend)) { std::printf("ERR lending the prompt path its slots failed: %s\n", err.c_str()); return 1; } if (win) merge_at = merge_from(at, to); // (after the refill: the loans are back) const int64_t read_to = merge_at >= 0 ? merge_at : to; // (merge_at > at: the part's windows before it) const auto tsp = Clock::now(); pp_exact = false; // a batched or pipelined part is in flight: a cancel may leave the state past pp_reached const bool sp_ok = read_to <= at || (win ? read_windows(at, read_to, err) : read_part(at, to, err)); if (sp_ok) pp_exact = true; if (trace) { const double ms = std::chrono::duration(Clock::now() - tsp).count(); (win ? req_times.windows_ms : req_times.read_ms) += ms; std::fprintf(stderr, "strata trace: read %lld tokens (%s) in %.1f ms\n", (long long) (read_to - at), win ? "windows" : "batched", ms); if (merge_at >= 0) std::fprintf(stderr, "strata trace: the first window takes the last %lld prompt tokens\n", (long long) (n - merge_at)); std::fflush(stderr); } if (!sp_ok && nf_hit) { // #879: DONE nonfinite (the lent slots are refilled below) cancelled = true; break; } if (sp_ok && merge_at >= 0) { // the server's progress reaches the prompt's end, as after its last window const double ms = std::chrono::duration(Clock::now() - pp_t0).count(); std::printf("PP %lld %lld %.0f %.1f\n", (long long) to, (long long) pp_total, ms, ms > 0.0 ? 1000.0 * (double) (to - pp_from) / ms : 0.0); std::fflush(stdout); } if (!sp_ok) { if (yielded_at < 0 && (batch_fatal || !stop_req.load())) { std::fprintf(stderr, "strata serve: %s\n", err.c_str()); std::printf("ERR %s\n", err.c_str()); // #224: a CUDA fault (an illegal address) poisons the context for the whole process, and // unwinding the destructors on it could hang until the 60 s watchdog: leave at once if (cudaPeekAtLastError() != cudaSuccess) { std::fflush(stdout); std::fflush(stderr); std::_Exit(1); } return 1; } cancelled = true; // stopped while reading the prompt: refill the lent slots below, then DONE cancel break; } at = to; if ((to == turn_at || to == root_at || to == message_at || to == pin_at) && !checkpoint_at(to, nullptr, to == message_at && to != turn_at && to != root_at && to != pin_at)) { // the tail kind leaves first if (!ckpt_why.empty() || !checkpoint_failure_is_survivable()) { // #3350: only an unwell GPU ends the request std::printf("ERR saving a conversation checkpoint failed%s\n", ckpt_why.c_str()); return 1; } std::fprintf(stderr, "strata serve: checkpoint at %lld skipped: its state could not be copied out (see " "above); the request goes on without it\n", (long long) to); } if (to == pin_at && !pin_checkpoint(pin_at)) std::fprintf(stderr, "strata serve: pin=%lld: its checkpoint was not kept\n", (long long) pin_at); if (trace && to == message_at) std::fprintf(stderr, "strata serve: message boundary checkpoint: %lld tokens, %lld tail\n", (long long) message_at, (long long) (turn_at - message_at)); } if (!refill(err)) { std::printf("ERR refilling a lent slot failed: %s\n", err.c_str()); return 1; } if (mtp_room_open && room_close("prompt done") != 0) return 1; if (head_restore() != 0) return 1; tr("prompt done (slots refilled)"); if (il_parts > 0) std::fprintf(stderr, "strata batch: the prompt was read in %lld parts, the slots decoding %.0f ms between " "them\n", (long long) il_parts + 1, il_ms); const double prompt_ms = std::chrono::duration(Clock::now() - r0).count(); std::printf("REUSED %lld\n", (long long) resume); // the prompt is read; the first window comes next std::fflush(stdout); // the verify windows: the first holds the last prompt token alone (STRATA_ADMIT_MERGE_FIRST: the prompt // tokens from merge_at on, the last one's output its first token) const int merge_T = merge_at >= 0 && !cancelled ? (int) (n - merge_at) : 0; int64_t p = merge_T > 0 ? merge_at : n - 1; int32_t x = (int32_t) ids[(size_t) p]; // STRATA_SESSION_DUMP=: stage 0's session after the prompt (the cells [0, p) its read wrote), as // ., for cmp if (const char* dp = std::getenv("STRATA_SESSION_DUMP"); dp != nullptr && dp[0] != '\0') { static int dump_req = 0; const std::vector dump_ids(ids.begin(), ids.begin() + (std::ptrdiff_t) p); const std::string dump_path = std::string(dp) + "." + std::to_string(dump_req++); std::string dump_err; int dump_dev = 0; (void) cudaGetDevice(&dump_dev); (void) cudaSetDevice(primary_device); if (!strata::core::conversation_session_dump(ss, g, dump_ids, dump_path, dump_err)) std::fprintf(stderr, "strata serve: STRATA_SESSION_DUMP: %s\n", dump_err.c_str()); else std::fprintf(stderr, "strata serve: session dumped to %s (layers %lld-%lld, %lld tokens)\n", dump_path.c_str(), (long long) ss.layer_lo, (long long) ss.layer_hi, (long long) p); (void) cudaSetDevice(dump_dev); } // (the drafter writes max_t - 1 drafts: 8 rows with --pipeline-windows 2) const size_t DS = (size_t) std::max(S, use_mtp ? mtp.max_t() : 0); const size_t WS = (size_t) std::max(S, merge_T); std::vector drafts(DS, 0), window(WS), outv(WS); std::vector dprob(DS, 0.0f); std::array dwin_s{}; // the probabilities the current window was chosen from (STRATA_SPEC_COST) // STRATA_SPEC_TRACE= in serve (bench only, off by default): per round "R p T a sfx ms k match | probs | drafts | lookup draft | committed tokens" static std::FILE* const df2_trace = [] { const char* tf = std::getenv("STRATA_SPEC_TRACE"); return tf != nullptr && tf[0] != '\0' ? std::fopen(tf, "a") : nullptr; }(); static const bool trace_nopick = std::getenv("STRATA_SPEC_TRACE_NOPICK") != nullptr; // the lookup draft is logged but never taken std::array tr_d{}; std::array tr_s{}; int tr_k = 0, tr_match = 0; std::vector sbuf((size_t) S, 0); const bool sfx_on = o.suffix_draft > 0 || o.lookup_chain > 0; if (sfx_on) { sfx.reset(); for (int64_t t : ids) sfx.append((int32_t) t); } if (o.lookup_chain > 0) { extra_sources_reset(); for (int64_t t : ids) { const int32_t t32 = (int32_t) t; extra_sources_append(&t32, 1); } } // This request's source planner: the live policy at its start, then only committed outcomes (no round // times, no rows past the accepted ones: their Philox counters are drawn again by the next rounds). auto source_policy = policy; strata::core::MtpDrafter::DraftResult generation; strata::core::gated::Packet proposal; // immutable through the synchronous verifier call bool first_window = true; int64_t produced_n = 0, sfx_windows = 0, sfx_drafts = 0, sfx_ok = 0; // STRATA_FOLLOW= (token forcing, measurement only, off by default; tools/force_check.py): one line per request in the order the // engine decodes them, comma-separated token ids (an empty line: that request is not forced). The serial decode windows below // take the line's tokens in place of the head's argmax, so drafts are accepted exactly when they equal the forced continuation, and // STRATA_FOLLOW_LOGPOS= gets one STRATA_LOGPOS row (FP32 head logits, STRATA_LOGPOS_TOPK) for every row whose logits are valid // (each accepted row plus the one that follows): "position, forced token, logp(forced), argmax, logp(argmax), match, ..." static const std::vector> fol_sets = [] { std::vector> v; if (const char* f = std::getenv("STRATA_FOLLOW"); f != nullptr && f[0] != '\0') { std::ifstream in(f); std::string line; while (std::getline(in, line)) { std::vector ids; for (const char* q = line.c_str(); *q != '\0';) { if (*q >= '0' && *q <= '9') { ids.push_back((int32_t) std::atoi(q)); while (*q >= '0' && *q <= '9') ++q; } else ++q; } v.push_back(std::move(ids)); } } return v; }(); static size_t fol_next = 0; static std::FILE* const fol_lp = [] { const char* p = std::getenv("STRATA_FOLLOW_LOGPOS"); return p != nullptr && p[0] != '\0' ? std::fopen(p, "ab") : nullptr; }(); const std::vector* fol = nullptr; if (!fol_sets.empty()) { if (fol_next < fol_sets.size() && !fol_sets[fol_next].empty()) fol = &fol_sets[fol_next]; ++fol_next; } // on by default on every backend (measured on HIP: 4 x R9700, Qwen3.8-Flash-Next IQ3_S, 0 of 16 continuations fell back to // the older checkpoint against 4 of 16 without it, #4677; it changes no emitted token, only which accepted rows the // session keeps); STRATA_SERVE_STOP_BOUND=0 turns it off static const bool stop_bound = strata::core::serve_stop_bound_on(std::getenv("STRATA_SERVE_STOP_BOUND")); // a window that finishes after the server's STOP is dropped whole (no commit, no tokens): the session ends at the rows the // client was sent. Research switch, on by default; STRATA_SERVE_STOP_SKIP=0 turns it off (serve_stop_bound.hpp) static const bool stop_skip = strata::core::serve_stop_skip_on(std::getenv("STRATA_SERVE_STOP_SKIP")); int64_t chain_windows = 0, chain_drafts = 0, chain_ok = 0; // --lookup-chain's own counts int64_t t2_rej[8] = {}, t2_hit[8] = {}; // STRATA_MTP_TOP2: rejections inside the MTP drafts by depth, runner-up hits int64_t dp_tested[8] = {}, dp_ok[8] = {}; // STRATA_SPEC_DEPTH=1: MTP drafts tested / accepted by depth std::vector cbuf((size_t) S, 0), ctail; strata::spec::PromptLookupSource lookup_src(sfx); static const bool chain_fixed = std::getenv("STRATA_LOOKUP_CHAIN_FIXED") != nullptr; // no policy gate int64_t draft_offered = 0, draft_accepted = 0; // what the session holds once this request is done: the prompt read so far, then every committed token std::vector consumed; consumed.reserve((size_t) (n + max_new + S)); double keep_ms = 0; // --draft auto: host time spent queueing the idle drafter's upkeep bool keep_pending = false; auto keep_sync = [&]() -> bool { // the queued upkeep is done: the verifier may rewrite the taps / residual rows now if (!keep_pending) return true; keep_pending = false; #if defined(STRATA_HAVE_DFLASH2) if (use_df2 && !df2.context_wait(err)) return false; #endif if (use_mtp && cudaStreamSynchronize(mtp.stream()) != cudaSuccess) { err = "the MTP upkeep failed"; return false; } return true; }; const int64_t rounds_at_start = rounds; for (int64_t i = 0; i < p; ++i) consumed.push_back((int32_t) ids[(size_t) i]); // #4590: where the penalty window may start in `consumed` (see pen_prompt above): the end of the prompt without its // last token, which joins the window as the fed-back head `x`. size_t pen_gen0 = strata::kernels::penalty_window_from(consumed.size(), pen_prompt); if (req_pen_from >= 0 && !pen_prompt) pen_gen0 = std::min(pen_gen0, (size_t) req_pen_from); // a continued request: its reply began earlier const char* finish = "length"; // GEN hold=N:ID: on until ID is emitted; meanwhile the request's cap is min(max_new, N) bool hold_on = req_hold_n > 0 && req_hold_id >= 0; auto cap_now = [&]() -> int64_t { return hold_on ? std::min(max_new, req_hold_n) : (int64_t) max_new; }; const Clock::time_point d0 = Clock::now(); // STRATA_DECODE_TIMING=1: where a request's decode time goes (one line per request) static const bool dec_timing = std::getenv("STRATA_DECODE_TIMING") != nullptr; struct DecSnap { double wait, pool, host, plan, actq, jobs, run; int64_t misses, entries, hits, pcie; }; auto dec_snap = [&]() { return DecSnap{ver.ms_wait, ver.ms_pool, ver.ms_host, drive.d.ms_plan, drive.d.ms_actq, drive.d.ms_jobs, drive.d.ms_run, drive.d.multi_misses, drive.d.multi_entries, drive.d.cache_hits, drive.d.pcie_experts}; }; const DecSnap ds0 = dec_snap(); double dt_run = 0, dt_commit = 0, dt_draft = 0; double dt_adapt_wait = 0, dt_adapt_join = 0; // the tier's wait before a window / join after the draft (ms, summed) const int64_t dt_sw0 = ajob ? a_swapped : adapt_nswaps; int64_t dec_windows = 0, dec_T = 0; const int64_t decode_hits0 = drive.d.cache_hits; // CS-T: the RAM and file tiers of this request (the mmap source; 0 with the arena) const int64_t ram0 = src.ram_reads(), files0 = src.file_reads(); const uint64_t file_bytes0 = src.file_read_bytes(); const strata::platform::ProcIo dec_io0 = strata::platform::proc_io_sample(); // the decode's own OS reads const int64_t decode_look0 = drive.d.cache_hits + drive.d.cache_admitted + drive.d.cache_refused; const int64_t offload0 = drive.d.offload_entries; // #588 pcie_auto.mark(drive.d.ms_run, drive.d.multi_misses); // the prompt's windows are not the decode's if (cancelled) finish = nf_hit ? "nonfinite" : "cancel"; // ======== --pipeline-windows 2: the decode windows with the two cards overlapped ======== // Stage 0 (the first card) runs window K+1 while stage 1 verifies window K, on the guess that K is accepted // whole and that its bonus token is the drafter's. The drafter, teacher-forced through K+1's drafts, // guesses K+1's bonus and drafts K+2 while stage 1 runs K+1. A wrong guess costs the speculative window: // stage 0's GDN state comes back from a snapshot and K's commit is replayed with its real count (the // window's own commit inputs are intact in its parity's verifier). Stage 1 never runs a speculative window // and a window row computes what it would in any other window, so every emitted token is the serial loop's // (with STRATA_IQ_MT_MIN=1 bit for bit; sampled requests with the same Philox draw per position). bool pl_ran = false; const bool pl_want = pipe && pl_pw >= 2 && pl_snap_ok; const char* pl_serial = !pl_want ? nullptr : hist_n > 0 ? "repetition penalties (penalty_last_n)" : mtp.coupled() ? "coupled draft sampling" : nullptr; if (pl_serial != nullptr) { // said once per reason static std::set said; if (said.insert(pl_serial).second) std::fprintf(stderr, "strata serve: --pipeline-windows: a request with %s decodes serially\n", pl_serial); } if (pl_want && pl_serial == nullptr && !cancelled && produced_n < cap_now()) { pl_ran = true; if (!pl_prepare(err)) { std::printf("ERR %s\n", err.c_str()); return 1; } struct PW { int T = 0, seq = 0; int64_t p = 0; int32_t tok[8] = {}; float prob[8] = {}; // prob[i]: the drafter's probability of tok[i + 1] float p_on = 0.0f; // the chain's estimate that the window before is accepted whole, tok[0] its bonus // launched: on stage 0; finished: done on every front stage (all but the last); s1: on the last bool ready = false, launched = false, finished = false, s1 = false, s1_done = false; int fr = 0; // front stages done bool fl = false; // in flight on front stage `fr` uint32_t com = 0; // the front stages this window was committed on speculatively (bit per stage) bool spec = false; // launched speculatively (behind the window before, ahead of its verdict) bool made = false; // made from a chain (its outcome can be scored even when the gate held it) bool sfx = false; // a lookup window (the suffix drafter's drafts) int sfx_match = 0; }; // front stage `st`'s verifier of w's parity, and the last stage's auto VF = [&](int st, const PW& w) -> strata::core::Verifier& { return stage_ver_p(st, w.seq & 1); }; auto V1 = [&](const PW& w) -> strata::core::Verifier& { return *PV[1][w.seq & 1]; }; auto SDf = [&](const PW& w) { return (void*) PSD[w.seq & 1]; }; const float theta = pl_theta; const int force_miss = pl_force_miss; static const bool pl_log = pipe_dbg_env("STRATA_PIPELINE_LOG") != nullptr; // the snapshot of the GDN state window `seq` reads on front stage `st` (overlapped: before its launch // there, on the stage's side stream) auto snap_take = [&](int st, int seq) -> bool { if (!pl_snap_overlap) return true; PlSnap& sn = pl_snaps[(size_t) st]; const strata::core::OnDevice on(sn.dev); cudaStream_t cs = pl_stream[(size_t) st]; const int q = seq & 1; return cudaEventRecord(sn.pre[q], cs) == cudaSuccess && cudaStreamWaitEvent(sn.side, sn.pre[q], 0) == cudaSuccess && cudaMemcpyAsync(sn.buf[q], sn.state, sn.bytes, cudaMemcpyDeviceToDevice, sn.side) == cudaSuccess && cudaEventRecord(sn.ev[q], sn.side) == cudaSuccess && (cudaStreamQuery(sn.side), true); }; PW A, B, D; // A: the oldest window not verified; B: the next; D: a wrong speculative window bool doomed = false; // D still runs: when it finishes, stage 0 goes back to undo_w's real commit PW undo_w; int undo_keep = 0; int32_t undo_ple[2] = {-1, -1}; int chain_kind = 0; // 1: after an on-path verdict (A's drafts forced); 2: fresh (A's drafts from it) bool early_used = false; bool b_done = false; // B has been made from the chain in flight int chain_n = 0; int64_t pl_spec = 0, pl_on = 0, pl_undo = 0, pl_gate = 0, pl_fm = 0; std::vector outp(8, 0); bool ending = false; A.T = 1; A.p = p; A.tok[0] = x; A.ready = true; drive.d.layers = 0; drive.d.experts = 0; drive.d.failed = false; // the adaptive tier beside the pipeline: the serial loop's rule and adapt() on a thread of its own (its // copies wait for the windows in flight, which this loop keeps serving meanwhile). --adapt-async: the // asynchronous tier's steps instead, its copies queued here at each card's gaps (a_pl_idle, a_gap) std::thread pl_adapt_thr; std::atomic pl_adapt_done{true}; bool pl_adapt_ok = true; // an error ends the engine, as the serial loop's do: every GPU wait is released first (#267), so no // window in flight keeps spinning on a flag nobody raises, and the tier's thread can finish (the // asynchronous tier's job does host work alone: it ends) auto die = [&](const std::string& m) -> int { std::fprintf(stderr, "strata serve: pipelined decode: %s\n", m.c_str()); strata::core::diag_pipeline_fn().store(nullptr); strata::core::release_gpu_waits(stderr); if (pl_adapt_thr.joinable()) pl_adapt_thr.join(); if (ajob) { ajob->wait(); a_pl_idle = nullptr; } std::printf("ERR %s\n", m.c_str()); std::fflush(stdout); return 1; }; // STRATA_PIPELINE_TRACE=: every event of the loop with its time (appended per request) static const char* pl_trace_path = pipe_dbg_env("STRATA_PIPELINE_TRACE"); std::string pl_trace; const Clock::time_point pl_tr0 = Clock::now(); auto tre = [&](const char* ev, int seq, int x0 = 0, int x1 = 0) { if (pl_trace_path == nullptr) return; char b[96]; std::snprintf(b, sizeof b, "%.3f %s %d %d %d\n", std::chrono::duration(Clock::now() - pl_tr0).count(), ev, seq, x0, x1); pl_trace += b; }; auto pump0 = [&](PW& w) -> bool { // w's front stage in flight if (!w.fl) return true; strata::core::Verifier& v = VF(w.fr, w); // a doomed window (its guess was wrong) gets empty plans: no expert work on the CPU or the GPU for // its remaining layers, so it frees stage 0 and the pool sooner (its rows are discarded and the // undo restores everything it wrote). STRATA_PIPELINE_DOOM_SKIP=0: served in full. static const bool doom_skip = [] { const char* e = pipe_dbg_env("STRATA_PIPELINE_DOOM_SKIP"); return e == nullptr || std::atoi(e) != 0; }(); const bool skip = doom_skip && doomed && &w == &D; if (v.service(skip ? nullptr : &drive_pool_split, SDf(w), err) < 0) return false; if (v.done(err)) { if (!v.pl_finish(nullptr, err)) return false; w.fl = false; if (++w.fr == pl_nf) w.finished = true; tre("F0", w.seq, w.fr, w.spec); } return err.empty(); }; // the serial loop's window size over the chain's outputs from index `from` (`avail` of them) auto t_rule = [&](const float* pr, int from, int avail) { int T = S_mtp; if (req_spec_min_p > 0.0) { T = 1; while (T < S_mtp && from + T - 1 < avail && pr[from + T - 1] >= (float) req_spec_min_p) ++T; } return std::max(1, std::min(T, 1 + avail - from)); }; // B from the chain's outputs: its row 0 is the guess at index `base`, its drafts follow auto make_b = [&](const int32_t* oc, const float* op, int base, int avail, float pa) { B = PW{}; if (base >= avail) return; B.seq = A.seq + 1; B.p = A.p + A.T; B.tok[0] = oc[base]; B.T = t_rule(op, base + 1, avail); for (int i = 1; i < B.T; ++i) { B.tok[i] = oc[base + i]; B.prob[i - 1] = op[base + i]; } B.p_on = pa * op[base]; if (force_miss > 0 && ++pl_fm % force_miss == 0) B.tok[0] = B.tok[0] == 0 ? 1 : 0; B.ready = true; B.made = true; }; // events after all the work both stages' streams hold now, and whether they have passed std::vector fence_ev((size_t) n_stages, nullptr), exch_ev((size_t) n_stages, nullptr); for (int st = 0; st < n_stages; ++st) { const strata::core::OnDevice on(stage_ver_p(st, 0).device()); cudaEventCreateWithFlags(&fence_ev[(size_t) st], cudaEventDisableTiming); cudaEventCreateWithFlags(&exch_ev[(size_t) st], cudaEventDisableTiming); } auto stage_record = [&](std::vector& ev) { // after the work every stage's stream holds now for (int st = 0; st < n_stages; ++st) { const strata::core::OnDevice on(stage_ver_p(st, 0).device()); cudaEventRecord(ev[(size_t) st], pl_stream[(size_t) st]); (void) cudaStreamQuery(pl_stream[(size_t) st]); } }; auto stage_passed = [&](std::vector& ev) { for (cudaEvent_t e : ev) if (cudaEventQuery(e) == cudaErrorNotReady) return false; return true; }; // adapt()'s fence, on the tier's thread: it waits on the HOST. A device-side wait (the refill streams // waiting for the stages' events) would queue copies behind windows that need this loop, beside it. adapt_fence = [&]() { stage_record(fence_ev); while (!stage_passed(fence_ev)) std::this_thread::yield(); }; src.prepare_overrides(); // The swaps land in two steps. Once their copies are done, the incoming experts are resident (the plans // from then on use their slots). What gives their RAM back - the resident RAM mode's exchange, the // released or unpinned pages - waits until every window that may still pull them over PCIe (a plan // published before that point) has completed: both stages' streams are fenced there. bool exch_wait = false; std::vector pl_landed; auto pl_release = [&]() { unpin_blobs(pin_live); src.commit_exchanges(); for (const int32_t i : pl_landed) srcp->release((int64_t) i / g.n_expert, (int64_t) i % g.n_expert); pl_landed.clear(); exch_wait = false; }; auto pl_apply = [&]() { if (exch_wait) { if (stage_passed(exch_ev)) pl_release(); return; } if (pending.empty() || cudaEventQuery(adapt_ev) != cudaSuccess) return; for (auto& st : stages) if (st->adapt_live && cudaEventQuery(st->adapt_ev) != cudaSuccess) return; for (auto& st : stages) st->adapt_live = false; for (const auto& [i, slot] : pending) { host_res[(size_t) i] = slot; pl_landed.push_back(i); } pending.clear(); pending_age = 0; res_upload(); stage_record(exch_ev); exch_wait = true; }; // --adapt-async: the asynchronous tier beside the windows (see adapt_tick). A stage is idle when neither // of its verifiers has a window in flight (a commit or a snapshot copy waits on nothing of the host's) if (ajob) a_pl_idle = [&](int st) { return !PV[st][0]->in_flight() && !PV[st][1]->in_flight(); }; double a_poll_ms = 0.0; auto pl_adapt = [&]() -> bool { // the blocking tier (--adapt-async 0) if (pl_adapt_thr.joinable() && pl_adapt_done.load()) { pl_adapt_thr.join(); if (!pl_adapt_ok) return false; } if (pl_adapt_thr.joinable()) return true; // still adapting pl_apply(); if (!drive.d.usage.empty() && o.adapt_every > 0 && (rounds % o.adapt_iv(rounds)) == 0 && pending.empty() && !exch_wait) { pl_adapt_done = false; pl_adapt_thr = std::thread([&] { strata::platform::name_this_thread("strata-adapt"); strata::aux_cpus::pin_current_thread(); pl_adapt_ok = adapt(); pl_adapt_done = true; }); } return true; }; // the serial loop's prompt lookup for a fresh window: where the text repeats an earlier stretch and the // drafter's own first guess agrees, the policy may take the lookup's continuation (up to S rows) std::vector pl_sbuf((size_t) (2 * S), 0); // a lookup window's continuation goes on past it: the next window (B) is taken from the same lookup and // speculated behind it (a copied stretch is mostly accepted whole). STRATA_PIPELINE_LOOKUP_PON: B's // estimate (default 0.75; 0 = no lookup B) static const float pl_lookup_pon = [] { const char* v = pipe_dbg_env("STRATA_PIPELINE_LOOKUP_PON"); return v ? (float) std::atof(v) : 0.75f; }(); auto pick_lookup = [&](PW& w, const int32_t* chain0) { if (o.suffix_draft <= 0 || w.seq == 0) return; const int k = sfx.propose(2 * S - 1, pl_sbuf.data()); const int match = sfx.last_match(); if (k <= 0 || pl_sbuf[0] != chain0[0]) return; const strata::spec::DraftPolicy::Pick pk = policy.choose(w.T, std::min(k, S - 1), match); if (!pk.lookup) return; w.T = pk.t; for (int i = 1; i < w.T; ++i) { w.tok[i] = pl_sbuf[(size_t) i - 1]; w.prob[i - 1] = 1.0f; } w.sfx = true; w.sfx_match = match; const int rest = k - (w.T - 1); // lookup tokens past w: B's row 0 (w's bonus guess) and its drafts if (&w == &A && rest >= 1 && pl_lookup_pon > 0.0f && !b_done) { B = PW{}; B.seq = A.seq + 1; B.p = A.p + A.T; B.T = std::min(S, rest); for (int i = 0; i < B.T; ++i) B.tok[i] = pl_sbuf[(size_t) (A.T - 1 + i)]; for (int i = 1; i < B.T; ++i) B.prob[i - 1] = 1.0f; B.p_on = pl_lookup_pon; B.ready = true; B.made = true; b_done = true; // the chain in flight makes no B for this A tre("CD", A.seq + 1, 3, (int) (1000.0f * B.p_on)); } }; const Clock::time_point pl_t0 = Clock::now(); for (int st = 0; st < 2; ++st) for (int par = 0; par < 2; ++par) g_pl_diag.v[st][par] = PV[st][par]; strata::core::diag_pipeline_fn().store(&pl_diag_print); auto pw_bits = [](const PW& w) { return (w.ready ? 1 : 0) | (w.launched ? 2 : 0) | (w.finished ? 4 : 0) | (w.com != 0 ? 8 : 0) | (w.s1 ? 16 : 0) | (w.s1_done ? 32 : 0); }; // per window class (0: fresh, 1: run speculatively ahead of its predecessor's verdict): the time from // the previous verdict, the tokens it emitted, how many double cls_ms[2] = {0, 0}, cls_tok[2] = {0, 0}, cls_n[2] = {0, 0}; int64_t cal_n[10] = {}, cal_on[10] = {}; // per p_on decile: windows scored, on the path double last_verdict = 0.0; int64_t pl_disagree = 0, pl_late = 0; static const bool pl_prestage = [] { // STRATA_PIPELINE_PRESTAGE=0: B staged at its launch const char* v = pipe_dbg_env("STRATA_PIPELINE_PRESTAGE"); return v == nullptr || std::atoi(v) != 0; }(); static const bool pl_agree = [] { // STRATA_PIPELINE_AGREE=0: only the old chain's probabilities const char* v = pipe_dbg_env("STRATA_PIPELINE_AGREE"); return v == nullptr || std::atoi(v) != 0; }(); auto ms_now = [&]() { return std::chrono::duration(Clock::now() - pl_t0).count(); }; while (true) { g_pl_diag.iters.fetch_add(1, std::memory_order_relaxed); g_pl_diag.a_seq.store(A.seq, std::memory_order_relaxed); g_pl_diag.a_bits.store(pw_bits(A), std::memory_order_relaxed); g_pl_diag.b_bits.store(pw_bits(B), std::memory_order_relaxed); g_pl_diag.d_bits.store(pw_bits(D), std::memory_order_relaxed); g_pl_diag.chain_kind.store(chain_kind, std::memory_order_relaxed); g_pl_diag.chain_live.store(mtp.chain_live() ? 1 : 0, std::memory_order_relaxed); g_pl_diag.doomed.store(doomed ? 1 : 0, std::memory_order_relaxed); g_pl_diag.ending.store(ending ? 1 : 0, std::memory_order_relaxed); // ---- --adapt-async: the round in flight moves on between verdicts too (at most every 0.5 ms) if (ajob && astate != AState::Idle) { const double t = ms_now(); if (t - a_poll_ms >= 0.5) { a_poll_ms = t; if (!adapt_tick(false, false)) return die("an adaptive refill failed"); } } // ---- every window in flight served if ((doomed && !pump0(D)) || !pump0(A) || !pump0(B)) return die(err); if (A.s1 && !A.s1_done) { strata::core::Verifier& v = V1(A); if (v.service(&drive_pool_split, SDf(A), err) < 0) return die(err); if (v.done(err)) { if (!v.pl_finish(outp.data(), err)) return die(err); A.s1_done = true; tre("F1", A.seq, A.T); } else if (!err.empty()) return die(err); } if (drive.d.failed) return die(drive.d.fail ? drive.d.fail : "the expert pool failed"); // ---- a wrong speculative window has stopped (it is launched on no further stage once doomed): // every front stage it ran on back to the verified window's real commit if (doomed && !D.fl) { for (int st = 0; st < pl_nf; ++st) { if ((undo_w.com & (1u << st)) == 0) continue; PlSnap& sn = pl_snaps[(size_t) st]; { const strata::core::OnDevice on(sn.dev); if (cudaMemcpyAsync(sn.state, sn.buf[pl_snap_overlap ? (undo_w.seq & 1) : 0], sn.bytes, cudaMemcpyDeviceToDevice, pl_stream[(size_t) st]) != cudaSuccess) return die("restoring the GDN snapshot failed"); } if (st == 0) { ss.ple_prev[0] = undo_ple[0]; ss.ple_prev[1] = undo_ple[1]; } if (undo_keep > 0 && !VF(st, undo_w).pl_commit_async(undo_keep, err)) return die(err); // 0: the window was dropped (stop_skip) } doomed = false; ++pl_undo; tre("U", undo_w.seq, undo_keep); } if (ending) { if (!doomed) break; continue; } // ---- the drafter's chain, read as its outputs land (an event after each): a fresh A once its size // is decided, then B once ITS size is decided - its bonus guess and a draft below spec_min_p (or // S_mtp - 1 drafts) - so stage 0 need not wait for the whole chain if (chain_kind != 0) { const int k_ready = mtp.chain_outputs_ready(err); if (k_ready < 0) return die(err); if (chain_kind == 2 && !early_used) { // A's size is decided by its first outputs: a draft below spec_min_p ends it (the serial // loop's rule), so A goes to stage 0 as soon as that is known, not after all S_mtp - 1 const int k = k_ready; bool decided = k >= S_mtp - 1; if (!decided && req_spec_min_p > 0.0) for (int j = 0; j < k; ++j) if (mtp.chain_prob()[j] < (float) req_spec_min_p) { decided = true; break; } if (decided) { A.T = t_rule(mtp.chain_prob(), 0, std::min(k, S_mtp - 1)); for (int i = 1; i < A.T; ++i) { A.tok[i] = mtp.chain_tok()[i - 1]; A.prob[i - 1] = mtp.chain_prob()[i - 1]; } pick_lookup(A, mtp.chain_tok()); A.ready = true; early_used = true; tre("CE", A.seq, A.T); } } const int r = mtp.chain_poll(err); if (r < 0) return die(err); const int k = r == 1 ? chain_n : k_ready; const int32_t* oc = mtp.chain_tok(); const float* op = mtp.chain_prob(); if (r == 1 && chain_kind == 2 && !early_used) { A.T = t_rule(op, 0, std::min(chain_n, S_mtp - 1)); for (int i = 1; i < A.T; ++i) { A.tok[i] = oc[i - 1]; A.prob[i - 1] = op[i - 1]; } pick_lookup(A, oc); A.ready = true; early_used = true; } if (!b_done && (chain_kind == 1 || early_used)) { const int base = A.T - 1; // B's row 0: the guess of A's bonus bool decided = r == 1 || k >= base + S_mtp; if (!decided && k > base + 1 && req_spec_min_p > 0.0) for (int j = base + 1; j < k; ++j) if (op[j] < (float) req_spec_min_p) { decided = true; break; } if (decided) { float pa = 1.0f; if (chain_kind == 1) { // forced through A's drafts: its outputs there are the drafter's own picks from // A's verified predecessor, a better estimate of A's acceptance than the chain that // drafted A; a disagreement means A is unlikely to be accepted whole bool agree = true; for (int i = 0; i + 1 < A.T; ++i) { if (oc[i] != A.tok[i + 1]) agree = false; pa *= pl_agree ? op[i] : A.prob[i]; } if (pl_agree && !agree) { pa = 0.0f; ++pl_disagree; } } else { for (int i = 0; i + 1 < A.T; ++i) pa *= A.prob[i]; } if (!A.sfx) make_b(oc, op, base, k, pa); // a lookup window's bonus is not the chain's // stage B now (its PLE rows from the tokens before it as they will be once A is // committed whole), so its launch behind A is only the graph launch (never while a // rollback is pending: B's verifier is the one the undo commit reads) if (B.ready && B.p_on >= theta && pl_prestage && !VF(0, B).in_flight() && !doomed) { int32_t prev[2] = {ss.ple_prev[0], ss.ple_prev[1]}; for (int i = 0; i < A.T; ++i) { prev[0] = prev[1]; prev[1] = A.tok[i]; } if (!VF(0, B).prestage(B.T, B.tok, B.p, prev, err)) return die(err); } b_done = true; tre("CD", A.seq, chain_kind, (int) (1000.0f * B.p_on)); if (pl_log) std::fprintf(stderr, "strata pipeline: chain %d for p=%lld T=%d: B T=%d p_on %.3f (%d " "outputs)\n", chain_kind, (long long) A.p, A.T, B.T, B.p_on, k); } } if (r == 1) chain_kind = 0; } // ---- the front stages: A on its next one (never while a wrong window still holds a front stage's // state) if (A.ready && !A.fl && A.fr < pl_nf && !doomed) { const int st = A.fr; if (st == 0 && A.p + A.T > o.max_context) { ending = true; continue; } if (ajob && st == 0) a_gap(0); // --adapt-async: stage 0 is idle until this launch if (!snap_take(st, A.seq)) return die("the GDN snapshot failed"); if (!VF(st, A).pl_launch(A.T, A.tok, A.p, err)) return die(err); A.fl = true; if (st == 0) A.launched = true; tre("L0", A.seq, A.T, st); } // ---- the front stages: B, speculatively, one stage behind A. On each stage A is committed there // (its snapshot taken first) right before B launches, as stage 0 alone did with two stages // STRATA_PIPELINE_SPEC_DEPTH=k (debug): B runs speculatively on the first k front stages only static const int pl_spec_depth = [] { const char* v = pipe_dbg_env("STRATA_PIPELINE_SPEC_DEPTH"); return v ? std::max(1, std::atoi(v)) : 1 << 20; }(); if (B.ready && !B.fl && B.fr < pl_nf && B.fr < pl_spec_depth && A.fr > B.fr && !doomed) { const int st = B.fr; if (st > 0 || (B.p_on >= theta && B.p + B.T <= o.max_context)) { if (ajob && st == 0) a_gap(0); // --adapt-async: stage 0 is idle until this launch PlSnap& sn = pl_snaps[(size_t) st]; cudaStream_t cs = pl_stream[(size_t) st]; { const strata::core::OnDevice on(sn.dev); if (pl_snap_overlap ? cudaStreamWaitEvent(cs, sn.ev[A.seq & 1], 0) != cudaSuccess : cudaMemcpyAsync(sn.buf[0], sn.state, sn.bytes, cudaMemcpyDeviceToDevice, cs) != cudaSuccess) return die("the GDN snapshot failed"); } if (st == 0) { undo_ple[0] = ss.ple_prev[0]; undo_ple[1] = ss.ple_prev[1]; } if (!VF(st, A).pl_commit_async(A.T, err) || !snap_take(st, B.seq) || !VF(st, B).pl_launch(B.T, B.tok, B.p, err)) return die(err.empty() ? std::string("the GDN snapshot failed") : err); A.com |= 1u << st; B.fl = true; if (st == 0) { B.launched = true; B.spec = true; ++pl_spec; } tre("L0", B.seq, B.T, 10 + st); } else { B.ready = false; // not worth it: A's verdict decides the next window ++pl_gate; } } // ---- the last stage: A, once every front stage is done if (A.finished && !A.s1) { if (chain_kind == 1 && !B.ready) ++pl_late; // stage 0 idles until the chain has B if (ajob) a_gap(1); // --adapt-async: stage 1 is idle until this launch if (!V1(A).pl_launch(A.T, A.tok, A.p, err)) return die(err); A.s1 = true; tre("L1", A.seq, A.T); } // ---- A's verdict if (!A.s1_done) continue; // the drafter must be idle before the next chain. The chain needs nothing from the host, so this // wait is bounded even with B (made from its first outputs) in flight on stage 0; in practice the // chain ended long before a verdict that needs a whole stage-1 window. while (chain_kind != 0 && mtp.chain_live()) if (mtp.chain_poll(err) < 0) return die(err); if (chain_kind != 0 && !B.launched && !B.made) B = PW{}; chain_kind = 0; int a = 0; while (a < A.T - 1 && A.tok[a + 1] == outp[(size_t) a]) ++a; if (stop_bound || hold_on) // (a hold always bounds the commit: the server's next pass continues from it) a = strata::core::serve_stop_bound(a + 1, strata::core::serve_hold_remaining(a + 1, produced_n, max_new, hold_on ? req_hold_n : -1, req_hold_id, outp.data()), outp.data(), [&](int32_t y) { return std::find(o.eos_ids.begin(), o.eos_ids.end(), (int64_t) y) != o.eos_ids.end(); }) - 1; // STOP arrived while A was in flight: A is dropped whole (serve_skip_stopped_window), not committed on any stage and not // printed. A front stage that B ran on has A committed speculatively (A.com): it goes back to the snapshot taken before // A, with no replay (undo_keep 0); a stage B never reached never committed A. if (stop_skip && stop_req.load() && A.seq > 0) { bool deferred = V1(A).commit_deferred(); for (int st = 0; deferred && st < pl_nf; ++st) deferred = VF(st, A).commit_deferred(); if (strata::core::serve_skip_stopped_window(true, true, false, false, deferred)) { finish = "cancel"; if (B.launched) { doomed = true; D = B; undo_w = A; undo_keep = 0; } B = PW{}; ending = true; continue; } } if (!V1(A).pl_commit_async(a + 1, err)) return die(err); for (int i = 0; i <= a; ++i) consumed.push_back(A.tok[i]); draft_offered += A.T - 1; draft_accepted += a; ++rounds; if (drive.d.fs) drive.d.fs->completed.fetch_add(1, std::memory_order_release); ++dec_windows; dec_T += A.T; const bool nf = nonfinite_hit(V1(A), "decode"); // #879: none of its tokens goes out bool eos = false; for (int i = 0; !nf && i <= a && produced_n < cap_now() && !eos; ++i) { std::printf("T %d\n", (int) outp[(size_t) i]); if (hold_on && (int64_t) outp[(size_t) i] == req_hold_id) hold_on = false; if (req_logprobs >= 0) emit_lp_line(V1(A), i, outp[(size_t) i], req_logprobs, req_allowed); strata::core::progress_beat(); ++produced_n; if (o.suffix_draft > 0) sfx.append(outp[(size_t) i]); eos = std::find(o.eos_ids.begin(), o.eos_ids.end(), (int64_t) outp[(size_t) i]) != o.eos_ids.end(); } std::fflush(stdout); if (nf) finish = "nonfinite"; else if (eos) finish = "stop"; else if (stop_req.load()) finish = "cancel"; const bool last = nf || eos || produced_n >= cap_now() || stop_req.load(); const bool on = !nf && B.launched && a == A.T - 1 && B.tok[0] == outp[(size_t) A.T - 1]; if (B.made) { // the gate's calibration: would B have been on the path, by its estimate p_on const bool would = a == A.T - 1 && B.tok[0] == outp[(size_t) A.T - 1]; const int bin = std::min(9, std::max(0, (int) (B.p_on * 10.0f))); cal_n[bin] += 1; cal_on[bin] += would ? 1 : 0; } tre("V", A.seq, a, on ? 1 : (B.launched ? -1 : 0)); { const double now = ms_now(); const int c = A.spec ? 1 : 0; if (A.sfx) { ++sfx_windows; sfx_drafts += A.T - 1; sfx_ok += a; } if (A.seq > 0 && !last) policy.observe(A.sfx, A.T, a, A.sfx_match, now - last_verdict); cls_ms[c] += now - last_verdict; cls_tok[c] += a + 1; cls_n[c] += 1; last_verdict = now; } if (pl_log) std::fprintf(stderr, "strata pipeline: verdict p=%lld T=%d a=%d B %s%s (B front %d%s, A com %x) out", (long long) A.p, A.T, a, B.launched ? "launched" : B.ready ? "ready" : "none", on ? " ON" : "", B.fr, B.fl ? "+" : "", A.com); if (pl_log) { for (int i = 0; i <= a; ++i) std::fprintf(stderr, " %d", (int) outp[(size_t) i]); std::fprintf(stderr, "\n"); } x = outp[(size_t) a]; p = A.p + a + 1; pcie_auto_step(req_pcie_frac); // 0.1.44: the measured share in the pipelined loop too (STRATA_PCIE_AUTO_SPLIT=1 on a split) if (!last && !ajob && !pl_adapt()) return die("an adaptive refill failed"); if (on && !last) { ++pl_on; // the chain over A, forced through B's drafts: B's bonus guess and the next window's drafts mtp.set_source_R(V1(A).final_R(0)); chain_n = std::min(strata::kernels::kVerifyNarrowT - 1, B.T + S_mtp - 1); if (!mtp.chain_launch(A.T, outp.data(), A.p, a, B.tok + 1, B.T - 1, chain_n, chain_n, err)) return die(err); chain_kind = 1; tre("CL", A.seq, 1); early_used = false; b_done = false; // A accepted whole: its commit on the front stages B has not reached yet (B, now A, runs there // after it) for (int st = 0; st < pl_nf; ++st) if ((A.com & (1u << st)) == 0 && !VF(st, A).pl_commit_async(A.T, err)) return die(err); A = B; B = PW{}; } else { // the front stages B never ran on take A's real commit now; those it did run on are undone // (snapshot restored, the commit replayed) once it has stopped for (int st = 0; st < pl_nf; ++st) if ((A.com & (1u << st)) == 0 && !VF(st, A).pl_commit_async(a + 1, err)) return die(err); if (B.launched) { // a wrong guess (or the end): undo once it has stopped doomed = true; D = B; undo_w = A; undo_keep = a + 1; } // B is D now (or dropped): never pump it twice (whichever copy saw the window complete first // would finish it, and the other would wait for it forever) B = PW{}; if (!last) { mtp.set_source_R(V1(A).final_R(0)); chain_n = strata::kernels::kVerifyNarrowT - 1; if (!mtp.chain_launch(A.T, outp.data(), A.p, a, nullptr, 0, chain_n, chain_n, err)) return die(err); chain_kind = 2; tre("CL", A.seq, 2); early_used = false; b_done = false; PW nA; nA.seq = A.seq + 1; nA.p = A.p + a + 1; nA.tok[0] = outp[(size_t) a]; A = nA; } } // --adapt-async: the verdict's tick, once the drafter's chain is launched (off its critical path) if (!last && ajob && !adapt_tick(false)) return die("an adaptive refill failed"); if (last) ending = true; } pl_drain(); // nothing in flight: both stages' commits and the drafter have landed strata::core::diag_pipeline_fn().store(nullptr); if (pl_adapt_thr.joinable()) pl_adapt_thr.join(); // its copies waited only for finished work adapt_fence = nullptr; if (exch_wait) pl_release(); // every window has completed (drained) // --adapt-async: both stages idle now: the copies still due are queued and the round in flight goes on // unfenced (the INVARIANT at pl_drain: a checkpoint, a park, the serial loop and the next request find // nothing pipelined in flight) at the next tick, the next request's drain a_pl_settle(); for (cudaEvent_t ev : fence_ev) if (ev) cudaEventDestroy(ev); for (cudaEvent_t ev : exch_ev) if (ev) cudaEventDestroy(ev); if (pl_trace_path != nullptr && !pl_trace.empty()) { if (std::FILE* f = std::fopen(pl_trace_path, "a")) { std::fprintf(f, "# request p0=%lld\n", (long long) (n - 1)); std::fwrite(pl_trace.data(), 1, pl_trace.size(), f); std::fclose(f); } } // the odd windows' counters and GPU profiles into the verifiers that report them for (int st = 0; st < n_stages; ++st) stage_ver_p(st, 0).absorb_stats(stage_ver_p(st, 1)); if (!pl_adapt_ok) { std::printf("ERR an adaptive refill failed\n"); return 1; } while (mtp.chain_live() && mtp.chain_poll(err) == 0) {} mtp.set_source_R(ver.final_R_all()); // the serial loop's rows again const double pl_ms = std::chrono::duration(Clock::now() - pl_t0).count(); dt_run += pl_ms; if (dec_timing) { auto avg = [](double s_, double n_) { return n_ > 0 ? s_ / n_ : 0.0; }; std::fprintf(stderr, "strata pipeline: %lld windows in %.0f ms (%.2f ms/window): %lld speculative, %lld on " "the path, %lld rolled back, %lld below the gate (theta %.2f)\n", (long long) dec_windows, pl_ms, avg(pl_ms, (double) dec_windows), (long long) pl_spec, (long long) pl_on, (long long) pl_undo, (long long) pl_gate, theta); std::fprintf(stderr, "strata pipeline classes: fresh %.0f windows %.2f ms %.2f tok | speculative %.0f " "windows %.2f ms %.2f tok | forced-chain disagreements %lld, chain late %lld\n", cls_n[0], avg(cls_ms[0], cls_n[0]), avg(cls_tok[0], cls_n[0]), cls_n[1], avg(cls_ms[1], cls_n[1]), avg(cls_tok[1], cls_n[1]), (long long) pl_disagree, (long long) pl_late); std::fprintf(stderr, "strata pipeline: drafter on CUDA%d: %.3f ms of host time per chain launch (%.3f ms of it " "staging the source rows, %lld times so far)\n", mtp.device(), avg(mtp.ms_draft, (double) mtp.rounds), avg(mtp.ms_src, (double) mtp.n_src), (long long) mtp.n_src); std::string cal; char b[48]; for (int i = 0; i < 10; ++i) if (cal_n[i] > 0) { std::snprintf(b, sizeof b, " %.1f:%lld/%lld", i / 10.0, (long long) cal_on[i], (long long) cal_n[i]); cal += b; } std::fprintf(stderr, "strata pipeline calibration (p_on decile: on/scored):%s\n", cal.c_str()); } } #if defined(STRATA_HAVE_DFLASH2) #if defined(STRATA_GPU_METAL) const int df2_skip_min = strata::spec::df2_lookup_skip_min(8); #else const int df2_skip_min = strata::spec::df2_lookup_skip_min(0); #endif bool df2_deferred = false; int dfr_n = 0; int64_t dfr_pos = 0; int32_t dfr_anchor = 0; // a long suffix match: the next round's DFlash2 draft is deferred to that round's start (spec/window_rule.hpp skip_draft_for_lookup) auto defer_df2 = [&](int a_) -> bool { if (o.suffix_draft <= 0 || df2_skip_min <= 0 || !req_df2) return false; const int ks = sfx.propose(S_look - 1, sbuf.data()); if (!strata::spec::skip_draft_for_lookup(true, df2_skip_min, ks, sfx.last_match())) return false; df2_deferred = true; dfr_n = a_ + 1; dfr_pos = p; dfr_anchor = outv[(size_t) a_]; return true; }; // the next round's drafts from the committed rows' taps (DFlash2), as the CLI loop does auto draft_df2 = [&](int a_) -> bool { int32_t dd[strata::core::Dflash2Drafter::kDrafts]; float pp[strata::core::Dflash2Drafter::kDrafts]; const float* tp = df2_win_taps(a_ + 1, err); if (tp == nullptr || !df2.draft(tp, a_ + 1, p, outv[(size_t) a_], dd, pp, err)) return false; for (size_t i = 0; i < drafts.size() && i < (size_t) strata::core::Dflash2Drafter::kDrafts; ++i) { drafts[i] = dd[i]; dprob[i] = pp[i]; } if (ss.ple.ready() && ss.ple.table != nullptr) { // the PLE rows of the next window's tokens, read ahead (as the MTP's draft does) int n_pf = 0; const int cap = std::min(S_mtp, (int) drafts.size() + 1); for (int t = 1; t < cap && (req_spec_min_p <= 0.0 || dprob[(size_t) t - 1] >= (float) req_spec_min_p); ++t) ++n_pf; int32_t prev[2] = {ss.ple_prev[0], ss.ple_prev[1]}; auto pf = [&](int32_t tok) { uint32_t rows16[strata::kernels::PLE_N_HEADS]; strata::kernels::ngram_rows(&tok, prev, 1, ss.ple.consts, rows16); prev[0] = prev[1]; prev[1] = tok; ss.ple.table->prefetch_rows(rows16); }; pf(outv[(size_t) a_]); for (int i = 0; i < n_pf; ++i) pf(drafts[(size_t) i]); } return true; }; #else auto draft_df2 = [&](int) -> bool { return false; }; #endif if (df2_trace != nullptr) std::fprintf(df2_trace, "# request prompt %lld df2 %d spec %d\n", (long long) n, req_df2 ? 1 : 0, S_mtp); while (!pl_ran && !cancelled && produced_n < cap_now()) { int T = 1; policy.set_context(p); const bool merged = first_window && merge_T > 0; // the prompt's last tokens and the first token bool from_sfx = false; int sfx_pad = 0; // a learning stretch's lookup window longer than the proposal: the filler rows (DraftPolicy::Pick::pad) int sfx_match = 0; bool dfr_lookup = false; int dfr_T = 0, dfr_match = 0; #if defined(STRATA_HAVE_DFLASH2) if (df2_deferred) { // the draft skipped for a long lookup match: the lookup if the policy takes it, else the draft now (same taps and rows) df2_deferred = false; const int kd = sfx.propose(S_look - 1, sbuf.data()); const int md = sfx.last_match(); const strata::spec::DraftPolicy::Pick pk = kd > 0 ? policy.choose(S_mtp, kd, md) : strata::spec::DraftPolicy::Pick{}; if (kd > 0 && pk.lookup) { dfr_lookup = true; dfr_T = pk.t; dfr_match = md; if (!df2.context(ver.tap_dev(), dfr_n, dfr_pos, err)) { std::printf("ERR %s\n", err.c_str()); return 1; } } else { int32_t dd[strata::core::Dflash2Drafter::kDrafts]; float pp[strata::core::Dflash2Drafter::kDrafts]; if (!df2.draft(ver.tap_dev(), dfr_n, dfr_pos, dfr_anchor, dd, pp, err)) { std::printf("ERR %s\n", err.c_str()); return 1; } for (size_t i = 0; i < drafts.size() && i < (size_t) strata::core::Dflash2Drafter::kDrafts; ++i) { drafts[i] = dd[i]; dprob[i] = pp[i]; } } } #endif if (gated_proposal) { const int room = (int) std::min(S, o.max_context - p); source_policy.apply_costs(p); // held round times whose draws are all committed now if (!prepare_gated_window(proposal, generation, sfx, source_policy, o.suffix_draft > 0, first_window, room, S_mtp, (int) ver.vocab(), (float) req_spec_min_p, mtp.spec_q(), drafts.data(), dprob.data(), sbuf.data(), sfx_match, err)) { std::printf("ERR %s\n", err.c_str()); return 1; } T = proposal.T; from_sfx = proposal.from_sfx; if (first_window && merge_T > 0) T = merge_T; // STRATA_ADMIT_MERGE_FIRST: the prompt's last tokens ride in this window } else { T = draft_on ? S_mtp : 1; // no drafter: one token a round unless a lookup draft fires { // the window rule of this request's ACTIVE source (spec/window_rule.hpp), as in the CLI loop: the MTP chain's cost rule // and probabilities do not govern DFlash2's candidates, though the MTP may stay loaded beside it strata::spec::WindowRuleIn wr; wr.use_mtp = use_mtp; wr.draft_on = draft_on; wr.df2_active = req_df2; wr.spec_cost = spec_cost; wr.first_window = first_window; wr.chain_rows = chain_rows; wr.cap = S_mtp; wr.start = T; wr.spec_min_p = req_spec_min_p; wr.draft_conf = o.draft_conf; wr.dprob = dprob.data(); T = strata::spec::choose_window(wr); } if (first_window) T = merge_T > 0 ? merge_T : 1; // a repeat of earlier context (prompt lookup) where the MTP's own first guess agrees: the policy takes it // when its expected tokens per ms, from the measured acceptance and window costs, beat the MTP window's if (o.suffix_draft > 0 && !first_window) { const int k = sfx.propose(S_look - 1, sbuf.data()); sfx_match = sfx.last_match(); if (df2_trace != nullptr) { tr_k = std::min(k, 16); tr_match = sfx_match; for (int i = 0; i < tr_k; ++i) tr_s[(size_t) i] = sbuf[(size_t) i]; } // a probabilistic window must not condition the source on the draw: the policy copy fixed at the request's start // chooses, and the lookup is taken without asking whether the MTP's first guess agrees const bool probabilistic = use_mtp && !req_df2 && mtp.prob(); // DFlash2's candidates are not draws from the MTP's q if (k > 0 && (probabilistic || !draft_on || sbuf[0] == drafts[0])) { // a learning stretch may run a longer window than the proposal to time that size: the extra rows repeat the proposal's last // token, which the verifier rejects (a deterministic proposal only: a probabilistic window keeps its own draws) const strata::spec::DraftPolicy::Pick pk = probabilistic ? source_policy.choose(S_mtp, k, sfx_match) : policy.choose(T, k, sfx_match, dc_learning ? S_look - 1 : 0); if (pk.lookup && !trace_nopick && pk.t - 1 <= (int) sbuf.size()) { T = pk.t; from_sfx = true; if (pk.pad > 0) { sfx_pad = pk.pad; for (int i = k; i < k + pk.pad; ++i) sbuf[(size_t) i] = sbuf[(size_t) k - 1]; } } if (pk.lookup && !trace_nopick && o.lookup_max_t > 0) { // --lookup-max-t: a size whose window graph fits const int t = graph_fits(T); if (t < 0) { std::printf("ERR %s\n", err.c_str()); return 1; } T = t; } } else if (k == 0 && dc_learning && draft_on && !probabilistic && !trace_nopick) { // no proposal at all: a learning stretch may still time a lookup-type window size (every row after the first is filler, // the MTP's own first guess repeated; the verifier rejects them), so that sizes only lookups reach get measured const int s = policy.explore_lookup(std::min(S_look, (int) sbuf.size() + 1)); if (s > 0) { T = s; from_sfx = true; sfx_pad = s - 1; sfx_match = 0; for (int i = 0; i < s - 1; ++i) sbuf[(size_t) i] = drafts[0]; if (o.lookup_max_t > 0) { // --lookup-max-t: a size whose window graph fits const int t = graph_fits(T); if (t < 0) { std::printf("ERR %s\n", err.c_str()); return 1; } T = t; } } } } } if (dfr_lookup) { // the lookup window chosen before the draft (the draft was skipped) sfx.propose(S_look - 1, sbuf.data()); T = dfr_T; from_sfx = true; sfx_match = dfr_match; if (o.lookup_max_t > 0) { const int t = graph_fits(T); if (t < 0) { std::printf("ERR %s\n", err.c_str()); return 1; } T = t; } } std::copy(dprob.begin(), dprob.begin() + (std::ptrdiff_t) std::min(dprob.size(), 8), dwin_s.begin()); if (df2_trace != nullptr) std::copy(drafts.begin(), drafts.begin() + (std::ptrdiff_t) std::min(drafts.size(), 8), tr_d.begin()); // --lookup-chain: what followed an earlier occurrence of the context + the MTP's drafts, after them int chain_n = 0, cm = 0; if (o.lookup_chain > 0 && !first_window && !from_sfx && T < S) { int csrc = -1; const int nt = chain_tail(sfx, drafts.data(), T - 1, ctail); chain_n = strata::spec::propose_from_sources(lookup_src, ctail.data(), nt, T - 1, std::min(o.lookup_chain, S_look - T), o.lookup_chain_min, cbuf.data(), &cm, &csrc); // the policy keeps the chained tokens that pay at this machine's measured window costs if (chain_n > 0 && !chain_fixed) { double p_mtp = 1.0; for (int i = 0; i < T - 1; ++i) p_mtp *= dprob[(size_t) i]; chain_n = policy.chain(T, p_mtp, chain_n, cm); } if (chain_n > 0 && o.lookup_max_t > 0) { const int t = graph_fits(T + chain_n); if (t < 0) { std::printf("ERR %s\n", err.c_str()); return 1; } chain_n = std::max(0, t - T); } } // a learning stretch times the window sizes the round's own rule does not reach: the MTP / drafter window of a round with no lookup and no // chain is run at another size (the rows past the real drafts are whatever the drafts array holds: valid ids that the verifier rejects); // a deterministic window only, and only the learning stretch (DraftPolicy::explore_window) bool win_forced = false; if (dc_learning && draft_on && !first_window && !merged && !from_sfx && chain_n == 0 && !gated_proposal && !(use_mtp && !req_df2 && mtp.prob())) { const int sx = policy.explore_window(T, std::min(S_mtp, (int) drafts.size() + 1)); if (sx > 0 && p + sx <= o.max_context) { T = sx; win_forced = true; } } const int T_mtp = T; T += chain_n; const bool timed_round = !first_window; const Clock::time_point round0 = Clock::now(); if (p + T > o.max_context) break; window[0] = x; for (int i = 1; i < T_mtp; ++i) window[(size_t) i] = merged ? (int32_t) ids[(size_t) (p + i)] : from_sfx ? sbuf[(size_t) i - 1] : drafts[(size_t) i - 1]; for (int i = 0; i < chain_n; ++i) window[(size_t) (T_mtp + i)] = cbuf[(size_t) i]; if (!keep_sync()) { std::printf("ERR %s\n", err.c_str()); return 1; } drive.d.layers = 0; drive.d.experts = 0; drive.d.failed = false; // #463: the previous adapt round's copies land first - with a non-blocking query, whether a swapped-in // expert ran on the GPU or the CPU (they round differently) depended on the copy's timing // (STRATA_ADAPT_NOWAIT=1: 0.1.37's non-blocking query, the A/B) const Clock::time_point taw0 = Clock::now(); const bool asw_skip = first_window || merged; // the session's tier choice counts steady decode windows only double asw_wait_ms = 0; if (adapt_nowait()) apply_pending(false); else if (aov && (!pending.empty() || (peer.valid() && peer.has_pending())) && !aflipped) { // 0.1.43 STRATA_ADAPT_OVERLAP: the tables take the swaps now, exactly where the wait would have ended; // the copies still landing are waited for per layer inside the window (AdaptGate) // (resident RAM mode: the staged evicted experts look committed to the planner at once, the RAM // copy's places stay as they are until the copies have landed; see soft_commit_exchanges) if (src.complement_ready() && !src.soft_commit_exchanges()) { apply_pending(true); // not possible here: the plain wait } else { for (const auto& [i, slot] : pending) host_res[(size_t) i] = slot; if (peer.valid()) peer.flip_pending(); // its copies land over its own link, gated the same way res_upload(); aflipped = true; ++aov_flips; agate.active.store(true, std::memory_order_release); } } else if (pending.empty() || ++pending_age >= adapt_lag()) apply_pending(true); // STRATA_RAM_ADAPT= (opt-in, the resident RAM mode on one GPU): the RAM copy is chosen once, at // start, so an expert it does not hold is read from the file every time the conversation routes to // it. With this, before a window and while no adaptive round is in flight, up to n experts the windows // keep routing to (the adaptive tier's decayed count, at least its own candidate floor of 2) take the // RAM places of experts of their layer that are not routed to (count below 0.5), one pair per layer, // the largest difference first. One blob read each, on this thread; the RAM stays the same size, and // the routing, the weights and the VRAM tier's own rule are untouched. static const int ram_adapt_env = [] { const char* e = std::getenv("STRATA_RAM_ADAPT"); return e != nullptr ? std::max(0, std::atoi(e)) : 0; }(); const int ram_adapt_n = o.ram_adapt > 0 ? o.ram_adapt : ram_adapt_env; if (o.ram_adapt > 0 && o.ram_adapt_decay < 1.0f && o.adapt_every <= 0) // --ram-adapt-decay: per window for (float& v : drive.d.usage) v *= o.ram_adapt_decay; // STRATA_RAM_ADAPT_SPLIT=1 (opt-in): also on a layer split; the RAM copy is the host's, read by every stage static const bool ram_adapt_split = [] { const char* e = std::getenv("STRATA_RAM_ADAPT_SPLIT"); return e != nullptr && std::atoi(e) != 0; }(); if (ram_adapt_n > 0 && ram_adapt2.on && !first_window && !drive.d.usage.empty() && pending.empty() && (!ajob || astate == AState::Idle) && src.complement_ready() && (!multi_gpu || ram_adapt_split || o.ram_adapt > 0) && !peer.valid() && !remote_opt && o.batch == 0) { // 149-prefetch STRATA_RAM_ADAPT2=1: install the promotions whose reads have landed (window boundary: // nothing reads the RAM copy now), then stage the next ones, ranked by the stall they are expected to // save per byte: (decayed decode count + the prompt's seed) x the miss's cost (a cold expert costs // a drive read, one in the page cache STRATA_RAM_ADAPT_CACHED_W of that), against what the evicted // one is expected to cost; up to STRATA_RAM_ADAPT_PER_LAYER pairs a layer. The reads run on the // source's I/O thread, not here. ram_adapt2.installed += src.ram_install(host_res.data(), g.n_expert); for (float& x : ram_adapt2.seed) x *= 0.95f; struct Cand { float score; int32_t e; }; struct RamSwap2 { float gain; int32_t layer, in, out; }; std::vector swaps; std::vector ins, outs; for (int64_t l = 0; l < g.n_layers; ++l) { const float* u = drive.d.usage.data() + l * g.n_expert; const float* sd = ram_adapt2.seed.empty() ? nullptr : ram_adapt2.seed.data() + l * g.n_expert; const int32_t* r = host_res.data() + l * g.n_expert; ins.clear(); outs.clear(); for (int32_t e = 0; e < (int32_t) g.n_expert; ++e) { if (r[e] >= 0) continue; // in VRAM const float ue = u[e] + (sd != nullptr ? sd[e] : 0.0f); if (src.has_resident(l, e)) outs.push_back({ue, e}); else if (ue >= 2.0f) ins.push_back({ue, e}); } // the GPU tier's own next picks are left to it: its round takes the layer's most used experts // outside VRAM (about 2 a layer a round), and a RAM place spent on one of them is skipped at the // install (measured: 60% of the promotions skipped before this rule) - STRATA_RAM_ADAPT_SKIP_TOP if (ram_adapt2.skip_top > 0 && !ins.empty()) { std::vector du; for (const Cand& c : ins) du.push_back(u[c.e]); const size_t k = std::min(du.size(), (size_t) ram_adapt2.skip_top); std::nth_element(du.begin(), du.begin() + (std::ptrdiff_t) (k - 1), du.end(), std::greater()); const float top = du[k - 1]; size_t dropped = 0; ins.erase(std::remove_if(ins.begin(), ins.end(), [&](const Cand& c) { if (dropped < k && u[c.e] >= top) { ++dropped; return true; } return false; }), ins.end()); } if (ins.empty() || outs.empty()) continue; const size_t P = (size_t) ram_adapt2.per_layer; const size_t ni = std::min(ins.size(), 2 * P), no = std::min(outs.size(), P); std::partial_sort(ins.begin(), ins.begin() + (std::ptrdiff_t) ni, ins.end(), [](const Cand& a, const Cand& b) { return a.score > b.score; }); std::partial_sort(outs.begin(), outs.begin() + (std::ptrdiff_t) no, outs.end(), [](const Cand& a, const Cand& b) { return a.score < b.score; }); ins.resize(ni); for (Cand& c : ins) { // the miss cost of the few best: cold on the drive, or in the page cache if (src.ram_queued(l, c.e)) { c.score = -1.0f; continue; } c.score *= src.tier_of(l, c.e) == 1 ? ram_adapt2.cached_w : 1.0f; } std::sort(ins.begin(), ins.end(), [](const Cand& a, const Cand& b) { return a.score > b.score; }); const double bytes = (double) std::max(1, src.blob_bytes(l)); size_t oi = 0; for (size_t k = 0; k < ins.size() && oi < no; ++k) { while (oi < no && src.ram_queued(l, outs[oi].e)) ++oi; if (oi >= no) break; const float gain = ins[k].score - outs[oi].score; // the evicted one would cost a drive read if (ins[k].score <= 0.0f || gain < 1.0f) break; swaps.push_back({(float) (gain / bytes * 1048576.0), (int32_t) l, ins[k].e, outs[oi].e}); ++oi; } } std::sort(swaps.begin(), swaps.end(), [](const RamSwap2& a, const RamSwap2& b) { return a.gain > b.gain; }); int staged_n = 0; for (const RamSwap2& x : swaps) { if (staged_n >= ram_adapt_n) break; if (src.ram_stage(x.layer, x.in, x.out)) ++staged_n; } } else if (ram_adapt_n > 0 && !first_window && !drive.d.usage.empty() && pending.empty() && (!ajob || astate == AState::Idle) && src.complement_ready() && (!multi_gpu || ram_adapt_split || o.ram_adapt > 0) && !peer.valid() && !remote_opt && o.batch == 0) { // up to kRamAdaptPerLayer pairs a layer: the layer's most routed experts outside the copy against its least // routed ones in it, paired in that order while the outgoing one is still unused constexpr float kRamAdaptRouted = 2.0f, kRamAdaptUnused = 0.5f; constexpr size_t kRamAdaptPerLayer = 4; struct RamSwap { float gain; int32_t layer, in, out; }; std::vector swaps; std::vector ins, outs; for (int64_t l = 0; l < g.n_layers; ++l) { const float* u = drive.d.usage.data() + l * g.n_expert; const int32_t* r = host_res.data() + l * g.n_expert; ins.clear(); outs.clear(); for (int32_t e = 0; e < (int32_t) g.n_expert; ++e) { if (r[e] >= 0) continue; // in VRAM: the RAM copy does not hold it if (src.has_resident(l, e)) outs.push_back(e); else if (u[e] >= kRamAdaptRouted) ins.push_back(e); } const size_t ni = std::min(ins.size(), kRamAdaptPerLayer), no = std::min(outs.size(), kRamAdaptPerLayer); std::partial_sort(ins.begin(), ins.begin() + (std::ptrdiff_t) ni, ins.end(), [&](int32_t a, int32_t b) { return u[a] > u[b]; }); std::partial_sort(outs.begin(), outs.begin() + (std::ptrdiff_t) no, outs.end(), [&](int32_t a, int32_t b) { return u[a] < u[b]; }); for (size_t i = 0; i < ni && i < no && u[outs[i]] < kRamAdaptUnused; ++i) swaps.push_back({u[ins[i]] - u[outs[i]], (int32_t) l, ins[i], outs[i]}); } std::sort(swaps.begin(), swaps.end(), [](const RamSwap& a, const RamSwap& b) { return a.gain > b.gain; }); // the incoming expert was usually just read for the window before: a pair whose `in` still sits in that // read's stage buffer moves with a copy out of it (no file read); n caps only the pairs that need the file read int file_left = ram_adapt_n; for (const RamSwap& x : swaps) { if (src.replace_resident_staged(x.layer, x.in, x.out)) continue; if (file_left > 0) { --file_left; src.replace_resident(x.layer, x.in, x.out); } } } if (!adapt_tick(false)) { // --adapt-async: the round in flight moves on a step when it can std::printf("ERR an adaptive refill failed\n"); return 1; } asw_wait_ms = std::chrono::duration(Clock::now() - taw0).count(); dt_adapt_wait += asw_wait_ms; if (hist_n > 0) { // the tails the penalties count over, ONE PER ROW: the tokens the state has consumed, the // fed-back head `x` (it joins `consumed` only after this window commits), then the drafts // before that row - what plain decode would have counted there. (Until 0.1.19 only row 0 // was staged, and the drafted rows read unwritten slots.) strata::kernels::penalty_rows(consumed.data() + pen_gen0, (int64_t) (consumed.size() - pen_gen0), window.data(), T, hist_n, hist_stage.data()); const strata::core::OnDevice on_h(hist_dev); 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, adapt_quiesce)) { 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(); // STRATA_SPEC_PROB: the MTP drafts' distributions q, judged by rejection sampling (core/spec_prob.hpp); // a suffix window and the lookup chain's tail are point masses and keep the exact-match rule // (never on a first window: a merged one holds prompt tokens, not drafts) if (gated_proposal) ver.set_spec_proposal(proposal.n_q ? proposal.mu.data() : nullptr, proposal.n_q); else if (strata::spec::mtp_q_applies(use_mtp, req_df2, use_mtp && mtp.prob(), from_sfx, first_window, T_mtp)) ver.set_spec_q(mtp.spec_q(), T_mtp - 1); // only candidates the MTP drew const auto decode_pool_fn = use_mtp && mtp.prob() ? invariant_win_pool_fn : win_pool_fn; exit_if_gpu_fatal(""); // (the test hook counts windows here) if (!ver.run(T, window.data(), p, decode_pool_fn, win_pool_user, outv.data(), err) || drive.d.failed) { exit_if_gpu_fatal(drive.d.failed && drive.d.fail ? drive.d.fail : err); std::printf("ERR %s\n", drive.d.failed && drive.d.fail ? drive.d.fail : err.c_str()); return 1; } if (aflipped) apply_pending(true); // 0.1.43: every layer's copies were waited for in the window; the bookkeeping now // Diagnostics (as in generate): STRATA_DUMP_FIRST_LOGITS= writes the logits of each request's first // window to ., so the prompt paths (a peer card's share, a split) can be compared by KL if (first_window) { static const char* fl = std::getenv("STRATA_DUMP_FIRST_LOGITS"); static int fl_n = 0; if (fl != nullptr) { std::vector row((size_t) ver.vocab()); const std::string path = std::string(fl) + "." + std::to_string(fl_n++); std::FILE* f = ver.copy_logits(merged ? T - 1 : 0, row.data()) ? std::fopen(path.c_str(), "wb") : nullptr; if (f == nullptr || std::fwrite(row.data(), sizeof(float), row.size(), f) != row.size()) std::fprintf(stderr, "strata serve: STRATA_DUMP_FIRST_LOGITS: cannot write %s\n", path.c_str()); if (f) std::fclose(f); } } // STOP arrived while this window ran: drop it whole (serve_skip_stopped_window). Not committed, not printed - the server throws // away every token after its STOP - so the session ends at the rows the client was sent and the next request continues // from it. One flag read per window; a request that ends by its cap or EOS never sets the flag. if (stop_skip && stop_req.load() && strata::core::serve_skip_stopped_window(true, true, merged, first_window, ver.commit_deferred())) { finish = "cancel"; break; } if (fol != nullptr) { // STRATA_FOLLOW: the forced continuation stands in for the argmax (row i answers continuation index produced_n + i) for (int i = 0; i < T; ++i) { const int64_t fi = produced_n + i - (merged ? T - 1 : 0); if (fi >= 0 && fi < (int64_t) fol->size()) outv[(size_t) i] = (*fol)[(size_t) fi]; } } int a = merged ? T - 1 : 0; // a merged window commits every row, as the prompt windows do while (a < T - 1 && window[(size_t) a + 1] == outv[(size_t) a]) ++a; if (fol != nullptr && fol_lp != nullptr) { // rows 0..a have valid logits (their inputs are the accepted tokens) std::vector fol_tg((size_t) a + 1, -1); for (int i = 0; i <= a; ++i) { const int64_t fi = produced_n + i - (merged ? T - 1 : 0); fol_tg[(size_t) i] = merged && i < T - 1 ? window[(size_t) i + 1] : (fi >= 0 && fi < (int64_t) fol->size()) ? (*fol)[(size_t) fi] : -1; } std::string fe; if (!ver.window_logprobs(fol_tg.data(), a + 1, p, 248046, fol_lp, fe)) std::fprintf(stderr, "strata serve: STRATA_FOLLOW_LOGPOS: %s\n", fe.c_str()); } // A merged window contains prompt rows: every one must still be committed. // Otherwise do not cache accepted rows whose outputs this request cannot emit. if ((stop_bound || hold_on) && !merged) a = strata::core::serve_stop_bound(a + 1, strata::core::serve_hold_remaining(a + 1, produced_n, max_new, hold_on ? req_hold_n : -1, req_hold_id, outv.data()), outv.data(), [&](int32_t y) { return std::find(o.eos_ids.begin(), o.eos_ids.end(), (int64_t) y) != o.eos_ids.end(); }) - 1; if (from_sfx) { ++sfx_windows; sfx_drafts += T - 1; sfx_ok += a; } if (chain_n > 0) { ++chain_windows; chain_drafts += chain_n; chain_ok += std::max(0, a - (T_mtp - 1)); } if (!from_sfx && !first_window) for (int d = 0; d < T_mtp - 1 && d < 8 && d <= a; ++d) { ++dp_tested[d]; dp_ok[d] += d < a; } if (strata::core::MtpDrafter::top2_env() && !from_sfx && !first_window && a < T_mtp - 1 && a < 8) { ++t2_rej[a]; if (mtp.top2(a) == outv[(size_t) a]) ++t2_hit[a]; } const Clock::time_point tw1 = Clock::now(); std::thread adapt_thr; // the adaptive tier beside the commit and the draft (as in generate) bool adapt_ok = true; // (--adapt-async 1: the asynchronous tier above instead, ticked before the window) if (!drive.d.usage.empty() && o.adapt_every > 0 && !ajob && ((rounds + 1) % o.adapt_iv(rounds)) == 0) adapt_thr = std::thread([&] { strata::platform::name_this_thread("strata-adapt"); strata::aux_cpus::pin_current_thread(); adapt_ok = adapt(); }); if (!ver.commit(a + 1, err)) { exit_if_gpu_fatal(err); if (adapt_thr.joinable()) adapt_thr.join(); std::printf("ERR %s\n", err.c_str()); return 1; } if (nonfinite_hit(ver, first_window ? "first decode" : "decode")) { // #879: none of its tokens goes out if (adapt_thr.joinable()) adapt_thr.join(); if (!adapt_ok) { std::printf("ERR an adaptive refill failed\n"); return 1; } finish = "nonfinite"; break; } // a merged window: the drafter's rows of the prompt tokens in it, as the prompt windows give them if (merged && use_mtp && !mtp.prefill(ver.final_R_all(), window.data() + 1, T - 1, p, err)) { if (adapt_thr.joinable()) adapt_thr.join(); std::printf("ERR %s\n", err.c_str()); return 1; } // the window's first a + 1 tokens are in the session now (the last output is not: it is next x) for (int i = 0; i <= a; ++i) consumed.push_back(window[(size_t) i]); #if defined(STRATA_HAVE_DFLASH2) if (use_df2) df2.note_rows(window.data(), a + 1, p); // --draft auto: the drafter this request does not use keeps up with the commit (its context / its K/V), so a later request can use it if (use_df2 && o.draft_auto && !merged && !draft_keep_off) { const Clock::time_point tk0 = Clock::now(); // queued on the idle drafter's own stream, overlapped with the other's draft; keep_sync() below waits before the next window rewrites the taps / rows if (!req_df2) { if (!df2.context_async(ver.tap_dev(), a + 1, p, err)) { if (adapt_thr.joinable()) adapt_thr.join(); std::printf("ERR %s\n", err.c_str()); return 1; } keep_pending = true; } else if (use_mtp) { if (!mtp.prefill(ver.final_R_all(), outv.data(), a + 1, p, err, false)) { if (adapt_thr.joinable()) adapt_thr.join(); std::printf("ERR %s\n", err.c_str()); return 1; } keep_pending = true; } keep_ms += std::chrono::duration(Clock::now() - tk0).count(); } #endif if (!merged) { // (a merged window's rows are prompt tokens, not drafts) draft_offered += T - 1; draft_accepted += a; } const bool initial_round = first_window; // a single-row window: no proposal to learn from first_window = false; bool eos = false; for (int i = merged ? a : 0; i <= a && produced_n < cap_now() && !eos; ++i) { // (merged: row T-1 only) std::printf("T %d\n", (int) outv[(size_t) i]); if (hold_on && (int64_t) outv[(size_t) i] == req_hold_id) hold_on = false; if (req_logprobs >= 0) emit_lp_line(ver, i, outv[(size_t) i], req_logprobs, req_allowed); strata::core::progress_beat(); ++produced_n; if (sfx_on) sfx.append(outv[(size_t) i]); if (o.lookup_chain > 0) extra_sources_append(&outv[(size_t) i], 1); eos = std::find(o.eos_ids.begin(), o.eos_ids.end(), (int64_t) outv[(size_t) i]) != o.eos_ids.end(); } std::fflush(stdout); ++rounds; if (drive.d.fs) drive.d.fs->completed.fetch_add(1, std::memory_order_release); const Clock::time_point tw2 = Clock::now(); // coupled drafts with penalties: the next window's row-0 history (`consumed` holds this window's // commit, outv[a] is its row 0) - the drafts extend it on the device as the verify rows will if (use_mtp && hist_n > 0 && mtp.coupled() && !eos && produced_n < cap_now()) mtp.set_draft_history(consumed.data() + pen_gen0, (int64_t) (consumed.size() - pen_gen0), outv[(size_t) a]); generation = {}; // a skipped or failed production must not expose an older q view #if defined(STRATA_HAVE_DFLASH2) // The request ends here, so no draft follows and the window's committed rows would never reach the drafter's ring or its log: every turn would // leave a hole of a + 1 positions behind it, which a later turn that resumes after this one finds blank (and cannot rebuild). Update them now. static const bool df2_end_update = std::getenv("STRATA_DF2_END_UPDATE") == nullptr || std::getenv("STRATA_DF2_END_UPDATE")[0] != '0'; // =0: the pre-fix behaviour (diagnostics) if (df2_end_update && use_df2 && req_df2 && !merged && (eos || produced_n >= cap_now())) { const float* tp_end = df2_win_taps(a + 1, err); // (on a layer split: every stage's taps gathered onto the drafter's card) if (tp_end == nullptr || !df2.context(tp_end, a + 1, p, err)) { if (adapt_thr.joinable()) adapt_thr.join(); std::printf("ERR %s\n", err.c_str()); return 1; } } #endif const GatedDraftLimit draft_limit(mtp, gated_proposal, S_mtp, p + a + 1, o.max_context); const bool drafted = !draft_on || eos || produced_n >= cap_now() || (req_df2 ? ((!merged && defer_df2(a)) || draft_df2(a)) : mtp.draft_long(T, outv.data(), p, a, drafts.data(), err, dprob.data(), (float) req_spec_min_p, nullptr, gated_proposal ? &generation : nullptr)); { const Clock::time_point tw3 = Clock::now(); auto msd = [](Clock::time_point a0, Clock::time_point b0) { return std::chrono::duration(b0 - a0).count(); }; dt_run += msd(tw0, tw1); dt_commit += msd(tw1, tw2); dt_draft += msd(tw2, tw3); ++dec_windows; dec_T += merged ? 1 : T; // a merged window's prompt rows are not decode rows } pcie_auto_step(req_pcie_frac); // the default share, refined from the CPU pool's speed (PcieAuto); a request's own share is left alone if (adapt_thr.joinable()) { const Clock::time_point taj0 = Clock::now(); adapt_thr.join(); const double asw_join = std::chrono::duration(Clock::now() - taj0).count(); dt_adapt_join += asw_join; asw_wait_ms += asw_join; } if (!adapt_ok) { std::printf("ERR an adaptive refill failed\n"); return 1; } // the session's choice of the adaptive tier (adapt_async_default.hpp): ~64 windows on the blocking tier, then // ~64 on the asynchronous one if the swaps held the windows up, kept only if the decode got faster if (!asw_skip && (asw.phase() == strata::core::AdaptAsyncSelf::Phase::Measure || asw.trialing())) { const bool was_trial = asw.trialing(); const double asw_ms = std::chrono::duration(Clock::now() - taw0).count(); const auto act = asw.window(asw_ms, asw_wait_ms, a + 1); if (act == strata::core::AdaptAsyncSelf::Action::ToAsync) { ajob = std::make_unique(); std::fprintf(stderr, "strata serve: adaptive tier: the swaps held the windows up by %.1f%% (%.2f ms per " "token): trying the asynchronous tier for a while\n", 100.0 * asw.wait_fraction(), asw.measure_ms_per_token()); } else if (act == strata::core::AdaptAsyncSelf::Action::ToBlocking) { adapt_quiesce(); ajob.reset(); std::fprintf(stderr, "strata serve: adaptive tier: the asynchronous tier was slower (%.2f against " "%.2f ms per token): back to the blocking tier for this session\n", asw.trial_ms_per_token(), asw.measure_ms_per_token()); } else if (was_trial && asw.kept()) { std::fprintf(stderr, "strata serve: adaptive tier: the asynchronous tier stays on (%.2f against %.2f ms " "per token)\n", asw.trial_ms_per_token(), asw.measure_ms_per_token()); } } if (!drafted) { std::printf("ERR %s\n", err.c_str()); return 1; } if (gated_proposal && !eos && !initial_round) source_policy.observe_committed(from_sfx, from_sfx ? T : std::min(S_mtp, (int) std::min(S, o.max_context - p)), a, sfx_match); if (gated_proposal && !eos && !initial_round && timed_round) // after the next draft: its counters too source_policy.defer_cost(std::max(p + T - 1, p + a + 1 + S_mtp), T, std::chrono::duration(Clock::now() - round0).count()); if (df2_trace != nullptr && timed_round) { std::fprintf(df2_trace, "R %lld %d %d %d %.3f %d %d |", (long long) p, T, a, from_sfx ? 1 : 0, std::chrono::duration(Clock::now() - round0).count(), tr_k, tr_match); for (int i = 0; i < 7; ++i) std::fprintf(df2_trace, " %.4f", (double) dwin_s[(size_t) i]); std::fprintf(df2_trace, " |"); for (int i = 0; i < 7; ++i) std::fprintf(df2_trace, " %d", (int) tr_d[(size_t) i]); std::fprintf(df2_trace, " |"); for (int i = 0; i < tr_k; ++i) std::fprintf(df2_trace, " %d", (int) tr_s[(size_t) i]); std::fprintf(df2_trace, " |"); for (int i = 0; i <= a; ++i) std::fprintf(df2_trace, " %d", (int) outv[(size_t) i]); std::fprintf(df2_trace, "\n"); tr_k = 0; } if (spec_cost && use_mtp && timed_round && !from_sfx && !win_forced) policy.observe_probs(dwin_s.data(), T_mtp - 1, a); if (dc_learning || dc_calib) policy.set_busy_age(std::chrono::duration(Clock::now() - dc_busy_since).count()); if (timed_round && !eos && chain_n == 0 && ((sfx_pad > 0 && from_sfx) || win_forced)) // a window run for its size's sake: its time only policy.observe_forced(T, std::chrono::duration(Clock::now() - round0).count()); else if (timed_round && !eos && chain_n == 0) policy.observe(from_sfx, T, a, sfx_match, std::chrono::duration(Clock::now() - round0).count()); else if (timed_round && !eos) // a chained window: its MTP part, its chain, its cost policy.observe_chain(T_mtp, chain_n, a, cm, std::chrono::duration(Clock::now() - round0).count()); if (eos) { finish = "stop"; break; } if (stop_req.load()) { finish = "cancel"; break; } x = outv[(size_t) a]; p += a + 1; } // GEN hold=N:ID reached (ID not emitted): the server wraps up the thinking or asks for more // (a --batch admission is a GEN of one token whose hold may be that one token: the slot must not start then) if (hold_on && std::strcmp(finish, "length") == 0 && produced_n >= req_hold_n && (produced_n < max_new || admit_slot >= 0)) finish = "hold"; if (!keep_sync()) { std::printf("ERR %s\n", err.c_str()); return 1; } const double decode_ms = std::chrono::duration(Clock::now() - d0).count(); dc_last_end = Clock::now(); // the busy run goes on when the next request starts within CostLearner::kIdleS of this if (use_df2 && o.draft_auto && bandit_key != 0 && produced_n >= 48 && decode_ms > 0.0) { DraftBandit& b = bandit[bandit_key]; const int w = req_df2 ? 1 : 0; const double tps = 1000.0 * (double) produced_n / decode_ms; b.tps[w] = b.n[w] == 0 ? tps : 0.65 * b.tps[w] + 0.35 * tps; ++b.n[w]; } if (draft_log && use_df2) std::fprintf(stderr, "strata draft: request %lld drafter=%s window<=%d tokens=%lld rounds=%lld decode_ms=%.1f keep_ms=%.1f (%.3f per round)\n", (long long) ++draft_req_count, req_df2 ? "dflash2" : "mtp", S_mtp, (long long) produced_n, (long long) (rounds - rounds_at_start), decode_ms, keep_ms, rounds > rounds_at_start ? keep_ms / (double) (rounds - rounds_at_start) : 0.0); // --draft-costs: at a request's end, a learning stretch that is long enough becomes this machine's table (from the next request // on); one that looks disturbed (a load beside the engine, a stall) is dropped and learned again if (dc_learning && policy.learning()) { const strata::spec::CostLearner::Verdict v = policy.learner().check(kDraftCostRounds, kDraftCostMinN); if (v.ready && v.disturbed) { std::fprintf(stderr, "strata serve: draft costs: the learning stretch looks disturbed (%s): it is learned again\n", v.why.c_str()); policy.reset_learning(); } else if (v.ready) { strata::spec::CostFile cf; cf.key = dc_key; for (int k = 0; k < strata::spec::CostLearner::kCtxBuckets; ++k) cf.tables[(size_t) k] = policy.learner().table(k, kDraftCostMinN, policy.top_size()); cf.state_effect = policy.learner().state_effect(0, kDraftCostMinN); // real rounds are counted by the same rule (fresh only, or all) strata::spec::mark_learned_real(cf); // the stretch measured every size: the next start uses the table at once, and nothing rewrites the file // the CPU prompt share, when it is on and balancing from measured times: its balance as measured so far, to a 0.05 // step (0.5 when no short prompt has measured it yet: on an RTX A6000 a fixed 0.5 read a 981-token chunk as fast as the // balancing share, 1,001-1,009 against 995-997 ms); fixed from now on like the table if (strata::prefill::Prefill::cpu_share_balancing()) { const strata::prefill::PrefillStats& pst = sp.stats(); const double s = pst.cpu_share_readings > 0 ? pst.cpu_share_balanced : 0.5; cf.cpu_share = std::clamp(std::round(s * 20.0) / 20.0, 0.05, 0.9); } // the decode PCIe share as PcieAuto has it now (its third reading, or what it had reached by this request's end); // fixed from now on like the table if (dc_pcie_ok) cf.pcie_frac = o.pcie_frac; std::string why; const bool saved = strata::spec::write_cost_file(o.draft_costs, cf, why); for (int k = 0; k < strata::spec::CostLearner::kCtxBuckets; ++k) if (!cf.tables[(size_t) k].empty()) policy.set_fixed_costs(cf.tables[(size_t) k].data(), (int) cf.tables[(size_t) k].size(), k); policy.set_learning(false); policy.reset_learning(); dc_learning = false; dc_file = cf; policy.start_calibration(cf.state_effect, cf.real, cf.cal, cf.real_cost, cf.reqs); dc_calib = policy.calibrating(); if (policy.table_held()) dc_shares_due = true; // the shares stay live until the table takes over else dc_apply_shares(cf); std::string t0; char b[24]; for (size_t i = 0; i < cf.tables[0].size(); ++i) { std::snprintf(b, sizeof b, "%s%.2f", i ? "," : "", cf.tables[0][i]); t0 += b; } if (cf.cpu_share >= 0.0) { std::snprintf(b, sizeof b, "; CPU prompt share %.2f", cf.cpu_share); t0 += b; } if (cf.pcie_frac >= 0.0) { std::snprintf(b, sizeof b, "; PCIe share %.2f", cf.pcie_frac); t0 += b; } std::fprintf(stderr, "strata serve: draft costs: this machine's table is learned (%s); %s%s%s\n", t0.c_str(), dc_calib ? "live costs decide until every size is calibrated against real requests (or 100 requests have run), then it is fixed" : "it is fixed from the next request on", saved ? "" : " (not saved: ", saved ? "" : (why + "; the next start learns again)").c_str()); } } // --draft-costs, calibration: the real rounds of this request that the sizes still at their learned cost have collected; a size with // kCalibN of them takes their mean (the file is rewritten whole, the new cost applies from the next request on, no later change) if (dc_calib && (policy.calib_dirty() || policy.table_held())) { const bool dc_was_held = policy.table_held(), dc_was_passive = policy.passive(); strata::spec::CostFile cc = dc_file; std::string rep, why; if (policy.calibrate(cc, rep)) { if (dc_was_passive && !policy.passive()) { // the table is made: the shares go in with it, the CPU share only when a short prompt has measured it if (strata::prefill::Prefill::cpu_share_balancing() && sp.stats().cpu_share_readings > 0) cc.cpu_share = std::clamp(std::round(sp.stats().cpu_share_balanced * 20.0) / 20.0, 0.05, 0.9); if (dc_pcie_ok) { if (!pcie_auto.on) cc.pcie_frac = o.pcie_frac; else dc_pcie_pending = true; } dc_shares_due = true; } const bool saved = strata::spec::write_cost_file(o.draft_costs, cc, why); dc_file = cc; if (!rep.empty()) std::fprintf(stderr, "strata serve: draft costs: calibrated against real requests: %s%s\n", rep.c_str(), saved ? "" : (" (not saved: " + why + ")").c_str()); } dc_calib = policy.calibrating(); if (dc_was_held && policy.fixed()) { // the table takes over: the stored shares are fixed with it if (dc_shares_due) dc_apply_shares(dc_file); dc_shares_due = false; std::fprintf(stderr, "strata serve: draft costs: %s; this machine's table decides the windows from the next request on%s\n", dc_calib ? "100 requests have run, sizes real requests did not reach keep a scaled learned cost until they have their own rounds" : "every size is calibrated", dc_file.cpu_share >= 0.0 || dc_file.pcie_frac >= 0.0 ? " (the stored shares are fixed with it)" : ""); } } // --draft-costs with a table from before the stored PCIe share: once PcieAuto has settled (three readings, or it gave up), its // share goes into the file beside the table and is fixed from the next request; the next start loads it if (dc_pcie_pending && !pcie_auto.on) { dc_pcie_pending = false; strata::spec::CostFile cf = dc_file; cf.key = dc_key; cf.pcie_frac = o.pcie_frac; std::string why; const bool saved = strata::spec::write_cost_file(o.draft_costs, cf, why); dc_file = cf; if (policy.table_held()) dc_shares_due = true; // held back: fixed when the table takes over else fix_pcie_share(cf.pcie_frac); std::fprintf(stderr, "strata serve: draft costs: the PCIe share settled at %.2f; it is %s and fixed %s\n", cf.pcie_frac, saved ? "stored with this machine's table" : ("not stored (" + why + ")").c_str(), policy.table_held() ? "when the table takes over" : "from the next request on"); } // the last commit (set_commit_async): the session is complete before anything reads or copies it if (!ver.wait_commit(err)) { exit_if_gpu_fatal(err); std::printf("ERR %s\n", err.c_str()); return 1; } if (dec_timing && dec_windows > 0) { const DecSnap d1 = dec_snap(); const double w = (double) dec_windows, L = (double) g.n_layers; if (!pl_ran) { const double dt_other = decode_ms - dt_adapt_wait - dt_run - dt_commit - dt_draft - dt_adapt_join; std::fprintf(stderr, "strata decode timing: %lld windows, avg T %.2f, %.2f tokens/window, %.2f ms/window = " "adapt wait %.2f + verify %.2f (GPU-reach wait %.2f + per-layer host %.2f " "[plan %.2f actq %.2f jobs %.2f CPU %.2f] + stage %.2f) + commit/emit %.2f + " "draft %.2f + adapt join %.2f + other %.2f; per layer-window: CPU experts " "%.2f (%.2f entries), VRAM hits %.2f, PCIe %.2f; %.1f swaps/window\n", (long long) dec_windows, dec_T / w, produced_n / w, decode_ms / w, dt_adapt_wait / w, dt_run / w, (d1.wait - ds0.wait) / w, (d1.pool - ds0.pool) / w, (d1.plan - ds0.plan) / w, (d1.actq - ds0.actq) / w, (d1.jobs - ds0.jobs) / w, (d1.run - ds0.run) / w, (d1.host - ds0.host) / w, dt_commit / w, dt_draft / w, dt_adapt_join / w, dt_other / w, (d1.misses - ds0.misses) / (w * L), (d1.entries - ds0.entries) / (w * L), (d1.hits - ds0.hits) / (w * L), (d1.pcie - ds0.pcie) / (w * L), (double) ((ajob ? a_swapped : adapt_nswaps) - dt_sw0) / w); } else { // Keep the pipeline's existing timing format. std::fprintf(stderr, "strata decode timing: %lld windows, avg T %.2f, %.2f tokens/window, %.2f ms/window = " "verify %.2f (GPU-reach wait %.2f + per-layer host %.2f [plan %.2f actq %.2f jobs %.2f " "CPU %.2f] + stage %.2f) + commit/emit %.2f + draft %.2f; per layer-window: CPU experts " "%.2f (%.2f entries), VRAM hits %.2f, PCIe %.2f; adapt wait %.2f join %.2f, %.1f swaps/window\n", (long long) dec_windows, dec_T / w, produced_n / w, decode_ms / w, dt_run / w, (d1.wait - ds0.wait) / w, (d1.pool - ds0.pool) / w, (d1.plan - ds0.plan) / w, (d1.actq - ds0.actq) / w, (d1.jobs - ds0.jobs) / w, (d1.run - ds0.run) / w, (d1.host - ds0.host) / w, dt_commit / w, dt_draft / w, (d1.misses - ds0.misses) / (w * L), (d1.entries - ds0.entries) / (w * L), (d1.hits - ds0.hits) / (w * L), (d1.pcie - ds0.pcie) / (w * L), dt_adapt_wait / w, dt_adapt_join / w, (double) ((ajob ? a_swapped : adapt_nswaps) - dt_sw0) / w); } if (aov) std::fprintf(stderr, "strata decode adapt overlap: %lld windows took swaps still landing, a layer waited %.2f ms in all so far\n", (long long) aov_flips, ver.ms_gate); for (int st = 0; st < n_stages; ++st) { // every stage's GPU profile, not only the first card's const std::string pr = stage_ver(st).profile_report(); if (pr.empty()) continue; if (st == 0) std::fprintf(stderr, "strata decode GPU stages (ms/window):%s\n", pr.c_str()); // text as before else std::fprintf(stderr, "strata decode GPU stages, stage %d (ms/window):%s\n", st, pr.c_str()); } } if (drive.d.fs) std::fprintf(stderr, "strata serve: %s\n", drive.d.fs->report().c_str()); if (!cancelled) { // a prompt stopped halfway leaves the session somewhere between two chunks: nothing to continue from // (the checkpoints taken while reading it are still good) live.swap(consumed); live_pads = req_pads; live_imgs = imgs_below(req_imgs, (int64_t) live.size()); live_ok = o.prompt_cache > 0 && req_ckpt; // ckpt=0: nothing to continue or park (#830) if (nf_hit) live_ok = false; // #879 (the next request's start drops the rest) } else if (!nf_hit && pp_exact && pp_reached > 0 && o.prompt_cache > 0 && req_ckpt && pp_reached <= (int64_t) cur.size()) { // #1620: stopped between two windows (or before the first token was read): the session is exactly at // pp_reached, so it stays the live conversation - the next request continues from it or parks it. // Without this a cancelled request that had restored a parked conversation dropped it. live.assign(cur.begin(), cur.begin() + pp_reached); live_pads.clear(); for (const int64_t p : req_pads) if (p < pp_reached) live_pads.push_back(p); live_imgs = imgs_below(req_imgs, pp_reached); live_ok = true; std::fprintf(stderr, "strata serve: cancelled request keeps its conversation: %lld tokens live\n", (long long) pp_reached); } if (nib::config().recheck && nib::any_on() && !cancelled) { // STRATA_EXPERT_NIBBLE_RECHECK=1 (debug): every converted slot's hash again on its own device, against the // hash recorded at load - a path that wrote a slot after the seal is found here std::string rerr; int64_t bad_layer = -1; const auto rt0 = Clock::now(); bool ok = nib_x.recheck(rerr, bad_layer); int64_t checked = nib_x.n; for (size_t i = 0; ok && i < nib_st.size(); ++i) { ok = nib_st[i].recheck(rerr, bad_layer); checked += nib_st[i].n; } if (!ok) { std::fprintf(stderr, "strata serve: STRATA_EXPERT_NIBBLE_RECHECK: %s\n", rerr.c_str()); if (bad_layer >= 0) nib::fatal(bad_layer, "STRATA_EXPERT_NIBBLE_RECHECK", "a slot changed after the load"); std::fflush(stderr); std::abort(); } std::fprintf(stderr, "strata serve: STRATA_EXPERT_NIBBLE_RECHECK: %lld 4-bit slots hash as at load (%.0f ms)\n", (long long) checked, std::chrono::duration(Clock::now() - rt0).count()); } static const bool state_hash = std::getenv("STRATA_STATE_HASH") != nullptr; if (state_hash && !cancelled && o.prompt_cache > 0) { // every finished request, ckpt=0 too (parity gates) // DEBUG: a fingerprint of every part of the session over the positions it holds ([0, L)), and // separately of what lies past them in the last KV page (stale cells, fine unless something reads them) if (cudaDeviceSynchronize() != cudaSuccess) { std::printf("ERR synchronizing state fingerprint\n"); return 1; } const int64_t L = (int64_t) live.size(); const strata::kernels::QsaShapes qs = strata::core::qsa_shapes(g); bool hash_ok = true; std::array hash_buffer; auto hash_dev = [&](const void* p, size_t bytes, uint64_t h) { for (size_t offset = 0; hash_ok && offset < bytes;) { const size_t n = std::min(hash_buffer.size(), bytes - offset); // VRAM or a streamed host copy, with fixed diagnostic workspace. if (cudaMemcpy(hash_buffer.data(), static_cast(p) + offset, n, cudaMemcpyDefault) != cudaSuccess) { hash_ok = false; break; } h = fnv1a(hash_buffer.data(), n, h); offset += n; } return h; }; // the cells [c0, c1) of one int8 K or V pool ([page][kv_head][page_size][head_dim]), bytes per value `w` auto hash_cells = [&](const void* pool, int64_t per_cell, int64_t c0, int64_t c1, uint64_t h) { const int64_t ps = qs.page_size; for (int64_t pg = c0 / ps; pg * ps < c1; ++pg) for (int64_t hd = 0; hd < qs.n_head_kv; ++hd) { const int64_t a = std::max(c0, pg * ps) - pg * ps, e = std::min(c1, (pg + 1) * ps) - pg * ps; const size_t off = (size_t) (((pg * qs.n_head_kv + hd) * ps + a) * per_cell); h = hash_dev((const uint8_t*) pool + off, (size_t) ((e - a) * per_cell), h); } return h; }; const ConvStateSizes z = conv_state_sizes(g, ss); uint64_t h_gdn = hash_dev(ss.gdn_state, z.gdn, 1469598103934665603ull); if (std::getenv("STRATA_STATE_HASH_GDN") != nullptr && ss.gdn_alloc > 0) { // per GDN layer: which one differs first const size_t per = z.gdn / (size_t) ss.gdn_alloc; std::string s; char b[8]; for (int64_t i = 0; i < ss.gdn_alloc; ++i) { std::snprintf(b, sizeof(b), "%04llx ", (unsigned long long) (hash_dev((const uint8_t*) ss.gdn_state + i * per, per, 1469598103934665603ull) & 0xffff)); s += b; } std::fprintf(stderr, "strata serve: STATE_HASH_GDN %s\n", s.c_str()); } uint64_t h_ple = hash_dev(ss.ple_hist, ss.ple_hist ? z.ple : 0, 1469598103934665603ull); uint64_t h_tail = 1469598103934665603ull, h_pool = h_tail, h_kv = h_tail, h_stale = h_tail; // pooled= keeps its 0.1.29 meaning: the completed rows [0, L / idx_block) only. pooled_full= adds the // spare row at L / idx_block (the `dead` key the next block completion overwrites), which a // conversation restore writes back; dead= is the spare key itself uint64_t h_dead = h_tail, h_pool_full = h_tail; const int64_t kvb = qs.head_dim, scb = (qs.head_dim / 64) * 2; // a state's K/V arrays and their bytes per (cell, head) row: the host copy when it has one auto kv_arrays = [&](const strata::core::QsaState& st) { const bool h = st.kv_mode != 0; std::vector> a; if (st.kv_q4) { const int64_t q4b = (int64_t) strata::kernels::kv_q4_bytes_per_head((int) qs.head_dim); a = {{h ? st.host.k_q4 : st.k_q4, q4b}, {h ? st.host.v_q4 : st.v_q4, q4b}}; } else if (st.kv_hybrid) { const int64_t q4b = (int64_t) strata::kernels::kv_q4_bytes_per_head((int) qs.head_dim); a = {{h ? st.host.k_q : st.k_q, kvb}, {h ? st.host.v_q4 : st.v_q4, q4b}, {h ? st.host.k_scale : st.k_scale, scb}}; } else if (st.kv_int8) { a = {{h ? st.host.k_q : st.k_q, kvb}, {h ? st.host.v_q : st.v_q, kvb}, {h ? st.host.k_scale : st.k_scale, scb}, {h ? st.host.v_scale : st.v_scale, scb}}; } else { a = {{h ? st.host.k_pool : st.k_pool, qs.head_dim * 2}, {h ? st.host.v_pool : st.v_pool, qs.head_dim * 2}}; } return a; }; const int64_t end_cell = std::min(((L + qs.page_size - 1) / qs.page_size) * qs.page_size, ss.max_cells); // = the primary state's max_cells for (int64_t j = 0; j < ss.qsa_alloc; ++j) { // this session's owned QSA ordinals only const strata::core::QsaState& st = ss.qsa_states[ss.qsa_ord0 + j]; h_tail = hash_dev(st.idx_tail, z.tail, h_tail); h_dead = hash_dev(st.idx_dead, z.dead, h_dead); h_pool = hash_dev(st.idx_pooled, (size_t) (L / qs.idx_block) * qs.idx_dim * 4, h_pool); h_pool_full = hash_dev(st.idx_pooled, (size_t) (L > 0 ? L / qs.idx_block + 1 : 0) * qs.idx_dim * 4, h_pool_full); // KV streaming: the host copy is the identity layout and holds every cell for (const auto& [pool, w] : kv_arrays(st)) { h_kv = hash_cells(pool, w, 0, L, h_kv); h_stale = hash_cells(pool, w, L, end_cell, h_stale); } } uint64_t h_mtp = 1469598103934665603ull; if (use_mtp) { const strata::core::QsaState& ms = mtp.kv_state(); const int64_t mL = std::min(L, ms.max_cells); for (const auto& [pool, w] : kv_arrays(ms)) if (pool != nullptr) h_mtp = hash_cells(pool, w, 0, mL, h_mtp); } if (!hash_ok) { std::printf("ERR reading state fingerprint\n"); return 1; } std::fprintf(stderr, "strata serve: STATE_HASH L=%lld gdn=%016llx ple=%016llx tail=%016llx pooled=%016llx " "kv=%016llx mtp=%016llx stale=%016llx dead=%016llx pooled_full=%016llx ple_prev=%d,%d\n", (long long) L, (unsigned long long) h_gdn, (unsigned long long) h_ple, (unsigned long long) h_tail, (unsigned long long) h_pool, (unsigned long long) h_kv, (unsigned long long) h_mtp, (unsigned long long) h_stale, (unsigned long long) h_dead, (unsigned long long) h_pool_full, ss.ple_prev[0], ss.ple_prev[1]); } const int64_t req_hits = drive.d.cache_hits - decode_hits0; const int64_t req_look = (drive.d.cache_hits + drive.d.cache_admitted + drive.d.cache_refused) - decode_look0; const int64_t req_offload = drive.d.offload_entries - offload0; // #471: the prompt tokens this request read - all the fresh ones, or as far as the prompt pass got when a // cancel stopped it part-way (a cancelled request used to be logged and counted as having read them all) // SCR: the moved cells count as reused, the pads as nothing (the prompt as sent is n - pads tokens) const int64_t reused_n = resume + scr.reused(); const int64_t fresh = n - (int64_t) req_pads.size() - reused_n; const int64_t read_n = cancelled ? std::clamp(pp_reached - resume - scr.reused(), 0, fresh) : fresh; // DONE [hits] [lookups] // [RAM blobs] [file blobs] [file MB] (CS-T tiers; appended, so an older server reads the rest) // [prompt tokens read] (#471: fewer than - when a cancel stopped the read) // [offloaded] (#588: the decode's routed experts the GPU read over PCIe or another GPU computed; // not in [lookups]) // [lookup-chain accepted] [lookup-chain offered] [suffix accepted] [suffix offered] [windows] // (only with --lookup-chain) // chunk= experts_streamed= (key=value, last: the first chunk of the request's longest // batched segment, 0 when it read none; the expert blobs its prompt read copied host -> device on // every stage - not the CPU share's, the stage helper's or a --peer-device peer's) char chain_txt[128] = ""; if (o.lookup_chain > 0) std::snprintf(chain_txt, sizeof(chain_txt), " %lld %lld %lld %lld %lld", (long long) chain_ok, (long long) chain_drafts, (long long) sfx_ok, (long long) sfx_drafts, (long long) dec_windows); if (yielded_at >= 0) std::printf("YIELDED %d %lld\n", yielded_slot, (long long) yielded_at); std::printf("DONE %lld %lld %.1f %.1f %s %lld %lld %lld %lld %lld %lld %lld %.1f %lld %lld%s chunk=%lld " "experts_streamed=%lld\n", (long long) produced_n, (long long) (n - (int64_t) req_pads.size()), prompt_ms, decode_ms, finish, (long long) draft_accepted, (long long) draft_offered, (long long) reused_n, (long long) req_hits, (long long) req_look, (long long) (src.ram_reads() - ram0), (long long) (src.file_reads() - files0), (double) (src.file_read_bytes() - file_bytes0) / 1e6, (long long) read_n, (long long) req_offload, chain_txt, (long long) req_chunk, (long long) (sp.chain_experts_streamed() - streamed0)); std::fflush(stdout); if (admit_slot >= 0) { // --batch: BADM <1 = continues in the batch windows | 0 = done> bool cont = !cancelled && produced_n == 1 && admit_max_new > 1 && std::strcmp(finish, "length") == 0 && (int64_t) live.size() == p; const auto tc0 = Clock::now(); if (cont) park_slot(admit_slot); // the conversation the slot holds, before this one overwrites it if (cont && !copy_to_slot(admit_slot, live, err)) { std::fprintf(stderr, "strata serve: batch admission failed: %s\n", err.c_str()); bs[(size_t) admit_slot].cached = false; // its sessions may be half written cont = false; } const auto tc1 = Clock::now(); if (cont) { ver.set_slot_sampling(admit_slot, req_sp); // the request's own sampling, row by row if (!ver.set_slot_logit_bias(admit_slot, req_bias, err)) { // and its own logit bias std::printf("ERR %s\n", err.c_str()); return 1; } BSlot& sl = bs[(size_t) admit_slot]; if (ckpt_pool.on()) for (ConvCheckpoint& c : sl.checks) ckpt_pool.give(std::move(c)); sl = BSlot{}; const auto tc2 = Clock::now(); // (the slot's old checkpoints freed) sl.active = true; sl.x = x; sl.p = p; sl.produced = 1; sl.max_new = admit_max_new; sl.hold = strata::core::slot_hold_from(req_hold_n, req_hold_id, hold_on); // the thinking budget goes on in the slot's windows (hold_on: the first token was not ID) sl.t0 = Clock::now(); sl.ids = live; { // the penalty window of the slot's decode: the reply, from the last prompt token (the first window fed it), as the solo loop counts it const bool slot_pen = req_sp.penalty_last_n > 0 && (req_sp.penalty_repeat != 1.0f || req_sp.penalty_freq != 0.0f || req_sp.penalty_present != 0.0f); sl.pen_n = slot_pen ? std::min(req_sp.penalty_last_n, kPenaltyWindowCap) : 0; sl.reply0 = (int64_t) strata::kernels::penalty_window_from(live.size() > 0 ? live.size() - 1 : 0, pen_prompt); if (req_pen_from >= 0 && !pen_prompt) sl.reply0 = std::min(sl.reply0, req_pen_from); // a continued request (prompt + what it generated): the reply began earlier } #if defined(STRATA_HAVE_DFLASH2) if (batch_df2) { // the slot's first drafts: the last prompt row's taps (still in the verifiers from the admission's window) and the token it produced strata::core::Dflash2Drafter& d = *slot_df2[(size_t) admit_slot]; int32_t dd[strata::core::Dflash2Drafter::kDrafts]; float pp[strata::core::Dflash2Drafter::kDrafts]; if (!ver.gather_taps(d.landing(), d.device(), 0, 1, 0, d.stream(), err) || !d.draft(d.landing(), 1, sl.p - 1, sl.x, dd, pp, err)) { std::fprintf(stderr, "strata batch: DFlash2 admission for slot %d failed: %s\n", admit_slot, err.c_str()); return 1; } for (int j = 0; j < strata::core::Dflash2Drafter::kDrafts && j < (int) sl.draft.size(); ++j) { sl.draft[(size_t) j] = dd[j]; sl.dprob[(size_t) j] = pp[j]; } sl.draft_ready = true; } else #endif if (batch_mtp) { int nd = 1; // (STRATA_PIPED_MTP: up to its proposals per window, as --spec-min-p allows) if (!slot_mtp[(size_t) admit_slot]->draft_first(1, ver.final_R_all(), sl.x, sl.p - 1, sl.draft.data(), err, nullptr, piped_mtp ? (float) o.spec_min_p : 0.0f, &nd)) { std::fprintf(stderr, "strata batch: MTP admission for slot %d failed: %s\n", admit_slot, err.c_str()); return 1; } sl.n_drafts = std::max(1, nd); sl.draft_ready = true; } sl.cvec = cvec_cached; sl.img = !live_imgs.empty(); // pictures: not matched again by tokens alone, so not cached const ConvCheckpoint* best = nullptr; size_t best_at = 0; // its place in `checks` (STRATA_SLOT_CKPT_MOVE) for (size_t i = 0; i < checks.size(); ++i) { const ConvCheckpoint& c = checks[i]; if (c.ids.size() < live.size() && (best == nullptr || c.ids.size() > best->ids.size()) && std::equal(c.ids.begin(), c.ids.end(), live.begin())) { best = &c; best_at = i; } } bool best_lent = false; // STRATA_SLOT_CKPT_MOVE: the checkpoint this request mounted from another slot (that slot keeps it) if (lent_slot >= 0 && lent_slot != admit_slot && (best == nullptr || (int64_t) best->ids.size() < resume)) for (const ConvCheckpoint& c : bs[(size_t) lent_slot].checks) if ((int64_t) c.ids.size() == resume && c.ids.size() < live.size() && std::equal(c.ids.begin(), c.ids.end(), live.begin())) { best = &c; best_lent = true; } // STRATA_SLOT_CKPT_MOVE: this request's own turn checkpoint (or the one it moved out of this slot) // moves into the slot; a pinned prefix, a root and any other the chain shares are copied as before const bool move_best = slot_ckpt_move_env() && best != nullptr && !best_lent && !sl.img && !best->pinned && ((turn_at > 0 && (int64_t) best->ids.size() == turn_at) || (int64_t) best->ids.size() == moved_in); const auto tc3 = Clock::now(); if (move_best) { sl.checks.push_back(std::move(checks[best_at])); checks.erase(checks.begin() + (std::ptrdiff_t) best_at); } else if (best != nullptr && !sl.img) { if (ckpt_pool.on()) { // a copy into a dropped checkpoint's vectors (their pages are in) ConvCheckpoint c = ckpt_pool.take(); c = *best; sl.checks.push_back(std::move(c)); } else { sl.checks.push_back(*best); } } const auto tc4 = Clock::now(); std::fprintf(stderr, "strata batch: slot %d takes %lld tokens (copied in %.1f ms)\n", admit_slot, (long long) live.size(), std::chrono::duration(tc4 - tc0).count()); pc.admission((long long) live.size(), prompt_ms); if (trace) { // STRATA_TRACE: the admission's phases (ms), from the drain before BGEN to this copy auto span = [](Clock::time_point a, Clock::time_point b) { return std::chrono::duration(b - a).count(); }; const double ck = req_times.sync_ms + req_times.save_ms + req_times.evict_ms; std::fprintf(stderr, "strata trace: admission of slot %d: drain %.1f, prompt %.1f (read %.1f, " "windows %.1f, %d checkpoint(s) %.1f = sync %.1f + save %.1f + evict %.1f, " "rest %.1f), first window %.1f, slot copy %.1f, slot freed %.1f, " "checkpoint copy %.1f%s\n", admit_slot, adm_drain_ms, prompt_ms, req_times.read_ms, req_times.windows_ms, req_times.ckpts, ck, req_times.sync_ms, req_times.save_ms, req_times.evict_ms, prompt_ms - req_times.read_ms - req_times.windows_ms - ck, decode_ms, span(tc0, tc1), span(tc1, tc2), span(tc3, tc4), move_best ? " (moved)" : ""); } } std::printf("BADM %d %d\n", admit_slot, cont ? 1 : 0); if (trace && piped && cont) { rows_wait = "the admission"; rows_wait_t = Clock::now(); } adm_drain_ms = 0.0; std::fflush(stdout); admit_slot = -1; } if (drive.routing != nullptr) std::fflush(drive.routing); // the routing trace survives a crash and is watchable mid-session // "12288 of 98179" when cancelled mid-read (#471), the rate from what was read char read_txt[64]; if (cancelled) std::snprintf(read_txt, sizeof(read_txt), "%lld of %lld", (long long) read_n, (long long) fresh); else std::snprintf(read_txt, sizeof(read_txt), "%lld", (long long) fresh); std::fprintf(stderr, "strata serve: prompt %lld tokens = %lld reused + %s read in %.0f ms (%.1f tok/s), " "%lld generated in %.0f ms (%.1f tok/s), drafts accepted %lld of %lld, %zu checkpoints%s\n", (long long) (n - (int64_t) req_pads.size()), (long long) reused_n, read_txt, prompt_ms, prompt_ms > 0 ? 1000.0 * read_n / prompt_ms : 0.0, (long long) produced_n, decode_ms, decode_ms > 0 ? 1000.0 * produced_n / decode_ms : 0.0, (long long) draft_accepted, (long long) draft_offered, checks.size(), cancelled ? " (cancelled)" : ""); if (ck_from_pool + ck_fresh > 0) std::fprintf(stderr, "strata serve: checkpoint pool: this request took %zu checkpoint%s ready from the pool and allocated %zu fresh\n", ck_from_pool, ck_from_pool == 1 ? "" : "s", ck_fresh); ck_from_pool = ck_fresh = 0; { // AMD on Linux: the time the driver kept the GPU paused inside this request, when it is worth a line const std::string pause_line = strata::core::gpu_pause_request_line(g_req_gpu_pause_ms.load(), gpu_pause_now()); if (!pause_line.empty()) std::fprintf(stderr, "%s\n", pause_line.c_str()); } if (serve_adapt_drain_ms >= 1.0) std::fprintf(stderr, "strata serve: the request first waited %.0f ms for the adaptive tier's round in flight\n", serve_adapt_drain_ms); // the VRAM share of the experts the pool looked up while decoding; experts it sent over PCIe for the GPU // to read (--pcie-frac) are in neither count - #588: so that share is said beside it (raising --pcie-frac // raises the hit rate while the PCIe reads may make the decode slower) if (req_look > 0) { char off[160] = ""; if (req_offload > 0) std::snprintf(off, sizeof off, "; %lld more read by the GPU over PCIe or from another GPU (%.1f%% of " "all %lld routed)", (long long) req_offload, 100.0 * (double) req_offload / (double) (req_look + req_offload), (long long) (req_look + req_offload)); std::fprintf(stderr, "strata serve: decode expert cache hit rate: %.1f%% (%lld hits / %lld lookups)%s\n", 100.0 * (double) req_hits / (double) req_look, (long long) req_hits, (long long) req_look, off); } if (drive.d.tail_experts > 0) // STRATA_ROUTE_TAIL_SKIP, cumulative std::fprintf(stderr, "strata serve: route tail skip: %lld missed experts skipped (%lld entries) since the " "start\n", (long long) drive.d.tail_experts, (long long) drive.d.tail_skipped); // the resident RAM mode, cumulative: experts read from experts.bin since the copy was made (what the plain // mmap mode reads through the OS file cache, from the SSD when the RAM could not keep it) if (src.complement_ready()) std::fprintf(stderr, "strata serve: resident RAM: %.2f GiB of experts in RAM, %lld exchanged with the " "VRAM tier, %lld blob reads from the file\n", (double) src.resident_bytes() / 1073741824.0, (long long) src.exchanges(), (long long) src.file_reads()); if (ram_adapt2.on) // 149-prefetch: the staged promotions, cumulative std::fprintf(stderr, "strata serve: resident RAM (STRATA_RAM_ADAPT2): %lld promotions read on the I/O thread, " "%lld installed, %lld skipped at the install (%lld of them: the GPU tier took one of the pair)\n", (long long) src.ram_staged_reads(), (long long) ram_adapt2.installed, (long long) (src.ram_install_skips() + src.ram_install_gpu()), (long long) src.ram_install_gpu()); if (src.ram_adapts() > 0) // STRATA_RAM_ADAPT, cumulative std::fprintf(stderr, "strata serve: resident RAM: %lld experts moved in in place of unused ones, %lld of " "them out of a stage buffer (STRATA_RAM_ADAPT)\n", (long long) src.ram_adapts(), (long long) src.ram_staged()); if (ajob) // --adapt-async, cumulative (a round may still be in flight: it lands before the next request) std::fprintf(stderr, "strata serve: asynchronous adaptive tier: %lld rounds, %lld experts swapped in, " "%.1f ms per round (start to flip, between windows)", (long long) a_rounds, (long long) a_swapped, a_rounds > 0 ? a_ms / (double) a_rounds : 0.0); if (ajob) { if (a_arena) std::fprintf(stderr, " (arena, copy-in only, batch %zu, wait %d, pick %s %.2f ms/round)\n", a_batch, (int) a_wait, a_inline ? "inline" : "on the job", a_rounds > 0 ? a_pick_ms / (double) a_rounds : 0.0); else std::fprintf(stderr, "\n"); } if (src.exchange_rotation()) std::fprintf(stderr, "strata serve: exchange rotation: %llu blocks, %llu host memcpy bytes avoided (cumulative payload)\n", (unsigned long long)src.rotated_exchanges(), (unsigned long long)src.avoided_exchange_copy_bytes()); // CS-T: the tiers, cumulative - GPU cache hits (the decode lookups above), RAM copy, files (SSD / OS cache) if (srcp == &src) { std::fprintf(stderr, "strata serve: expert tiers: GPU %lld hits this request; since the start RAM %lld blobs, files %lld blobs " "%.1f MB read%s\n", (long long) req_hits, (long long) src.ram_reads(), (long long) src.file_reads(), (double) src.file_read_bytes() / 1e6, src.gguf_mode() ? " (the GGUF in place)" : ""); // what the OS did for this request (since the previous one): the drive's share of the file tier's reads // against the page cache's, and what the I/O path did about it static strata::platform::ProcIo io_prev; static strata::core::FileExpertSource::IoCounters ic_prev; static uint64_t fb_prev = 0; const strata::platform::ProcIo io_now = strata::platform::proc_io_sample(); const strata::core::FileExpertSource::IoCounters ic = src.io_counters(); const uint64_t fb = src.file_read_bytes(); if (const std::string rr = src.reuse_report(); !rr.empty()) // STRATA_FILE_REUSE=1 std::fprintf(stderr, "strata serve: %s\n", rr.c_str()); if (io_now.valid) { std::fprintf(stderr, "strata serve: file tier I/O this request: the OS read %.1f MB from storage (%llu major faults) for " "%.1f MB of expert reads", (double) (io_now.read_bytes - io_prev.read_bytes) / 1e6, (unsigned long long) (io_now.major_faults - io_prev.major_faults), (double) (fb - fb_prev) / 1e6); if (src.io_stats()) std::fprintf(stderr, "; page cache held %.1f MB at the read, not %.1f MB", (double) (ic.cached_bytes - ic_prev.cached_bytes) / 1e6, (double) (ic.uncached_bytes - ic_prev.uncached_bytes) / 1e6); if (src.io_prefetch()) std::fprintf(stderr, "; io prefetch: %llu read ahead (%.1f MB by pread), %llu used, %llu unused, %llu skipped " "(cached), %llu dropped; decode waited %.1f ms in %llu fetches", (unsigned long long) (ic.pf_read_blobs - ic_prev.pf_read_blobs), (double) (ic.pread_bytes - ic_prev.pread_bytes) / 1e6, (unsigned long long) (ic.pf_used - ic_prev.pf_used), (unsigned long long) (ic.pf_unused - ic_prev.pf_unused), (unsigned long long) (ic.pf_resident_skips - ic_prev.pf_resident_skips), (unsigned long long) (ic.pf_dropped - ic_prev.pf_dropped), (double) (ic.crit_us - ic_prev.crit_us) / 1e3, (unsigned long long) (ic.crit_n - ic_prev.crit_n)); if (src.io_prefetch() && src.gate_on()) // 149 STRATA_IO_PF_GATE: the decode's held share, the gate std::fprintf(stderr, "; decode gate: cache room %.2f of the experts, read-ahead used %.0f%%, page cache " "held %.0f%% of the decode's reads (EWMA), %s, closed in %lld windows so far, %lld flips", src.gate_ratio(), 100.0 * src.gate_useful(), 100.0 * std::max(0.0, src.gate_held()), src.gate_open() ? "open" : "closed", (long long) src.gate_closed_windows(), (long long) src.gate_flips()); if (src.io_prefetch()) // 149-prefetch: bytes read ahead, of them used before their demand; the scheduler's drops std::fprintf(stderr, "; read ahead %.1f MB, %.1f MB of it used; %llu late, %llu not admitted (confidence), " "%llu (budget %.0f MB/window)", (double) (ic.pf_bytes - ic_prev.pf_bytes) / 1e6, (double) (ic.pf_used_bytes - ic_prev.pf_used_bytes) / 1e6, (unsigned long long) (ic.pf_late - ic_prev.pf_late), (unsigned long long) (ic.pf_rej_conf - ic_prev.pf_rej_conf), (unsigned long long) (ic.pf_rej_budget - ic_prev.pf_rej_budget), (double) ic.pf_budget_bytes / 1048576.0); std::fprintf(stderr, "\n"); if (dec_io0.valid && produced_n > 0) std::fprintf(stderr, "strata serve: decode file tier I/O: the OS read %.1f MB (%llu major faults) for %.1f MB " "of expert reads, %.2f MB per token\n", (double) (io_now.read_bytes - dec_io0.read_bytes) / 1e6, (unsigned long long) (io_now.major_faults - dec_io0.major_faults), (double) (fb - file_bytes0) / 1e6, (double) (io_now.read_bytes - dec_io0.read_bytes) / 1e6 / (double) produced_n); io_prev = io_now; ic_prev = ic; fb_prev = fb; } } static const bool cold_log = std::getenv("STRATA_COLD_OVERLAP") != nullptr || std::getenv("STRATA_IO_STATS") != nullptr; if (drive.d.cold_mode != 0 && cold_log) { // 149-cold STRATA_COLD_OVERLAP: this request's layers that had a blob to read static strata::core::ExpertDispatch cp; const strata::core::ExpertDispatch& c = drive.d; const double nl = (double) std::max(1, c.cold_layers - cp.cold_layers); std::fprintf(stderr, "strata serve: cold reads (STRATA_COLD_OVERLAP=%d) this request: %lld experts from the mapping " "directly; %lld layers with a blob to " "read (%lld such experts, %lld ready beside them, %lld pool batches); per such layer: " "R %.3f ms, C_r %.3f ms, C_c %.3f ms, the decode waited %.3f ms; total waited %.1f ms, min(R, C_r) %.1f ms\n", c.cold_mode, (long long) (c.cold_zc - cp.cold_zc), (long long) (c.cold_layers - cp.cold_layers), (long long) (c.cold_pending - cp.cold_pending), (long long) (c.cold_ready - cp.cold_ready), (long long) (c.cold_batches - cp.cold_batches), (c.ms_cold_r - cp.ms_cold_r) / nl, (c.ms_cold_cr - cp.ms_cold_cr) / nl, (c.ms_cold_cc - cp.ms_cold_cc) / nl, (c.ms_cold_wait - cp.ms_cold_wait) / nl, c.ms_cold_wait - cp.ms_cold_wait, c.ms_cold_hide - cp.ms_cold_hide); cp.cold_layers = c.cold_layers; cp.cold_pending = c.cold_pending; cp.cold_ready = c.cold_ready; cp.cold_zc = c.cold_zc; cp.cold_batches = c.cold_batches; cp.ms_cold_r = c.ms_cold_r; cp.ms_cold_cr = c.ms_cold_cr; cp.ms_cold_cc = c.ms_cold_cc; cp.ms_cold_wait = c.ms_cold_wait; cp.ms_cold_hide = c.ms_cold_hide; } // STRATA_SPLIT_TIMING: where each verify stage's host time went, cumulative per window since the start // (waiting for its GPU to ring a layer, the CPU pool and plan per layer, staging the window) if (static const bool st_timing = std::getenv("STRATA_SPLIT_TIMING") != nullptr; st_timing) for (int st = 0; st < n_stages; ++st) { const strata::core::Verifier& v = stage_ver(st); const double w = v.windows > 0 ? (double) v.windows : 1.0; std::fprintf(stderr, "strata serve: stage %d: %lld windows; per window: wait for the GPU %.3f ms, " "pool + plan %.3f ms, host staging %.3f ms, commit %.3f ms\n", st, (long long) v.windows, v.ms_wait / w, v.ms_pool / w, v.ms_host / w, v.ms_commit / w); } if (g.n_qsa_layers() > 0 && ss.qsa_states[ss.qsa_primary()].kv_mode == 1) { // KV streaming, cumulative over the process: blocks the selections named vs blocks read from RAM // (this device's owned ordinals; a split's other stages hold theirs) uint64_t miss = 0, look = 0; bool over = false; for (int64_t j = 0; j < ss.qsa_alloc; ++j) { const strata::kernels::KvStreamCounters c = strata::kernels::kv_stream_counters(ss.qsa_states[ss.qsa_ord0 + j].map); miss += c.misses; look += c.lookups; over = over || c.overflow; } std::fprintf(stderr, "strata serve: KV streaming: %.2f%% of %llu block reads hit VRAM, %.1f MiB read " "from RAM%s\n", look ? 100.0 * (double) (look - miss) / (double) look : 100.0, (unsigned long long) look, (double) miss * 4224.0 / 1048576.0, over ? " - OVERFLOW (too few resident cells)" : ""); } if (sfx_windows > 0) std::fprintf(stderr, "strata serve: suffix drafts: %lld windows, %lld of %lld drafts accepted\n", (long long) sfx_windows, (long long) sfx_ok, (long long) sfx_drafts); if (o.lookup_chain > 0) std::fprintf(stderr, "strata serve: lookup chain: %lld of %lld windows, %lld of %lld chained drafts accepted\n", (long long) chain_windows, (long long) dec_windows, (long long) chain_ok, (long long) chain_drafts); if (std::getenv("STRATA_SPEC_DEPTH") != nullptr) std::fprintf(stderr, "strata serve: spec depth: accepted/tested %lld/%lld %lld/%lld %lld/%lld %lld/%lld %lld/%lld\n", (long long) dp_ok[0], (long long) dp_tested[0], (long long) dp_ok[1], (long long) dp_tested[1], (long long) dp_ok[2], (long long) dp_tested[2], (long long) dp_ok[3], (long long) dp_tested[3], (long long) dp_ok[4], (long long) dp_tested[4]); if (strata::core::MtpDrafter::top2_env()) std::fprintf(stderr, "strata serve: mtp top2: rejected/runner-up by depth %lld/%lld %lld/%lld %lld/%lld %lld/%lld " "of %lld windows\n", (long long) t2_rej[0], (long long) t2_hit[0], (long long) t2_rej[1], (long long) t2_hit[1], (long long) t2_rej[2], (long long) t2_hit[2], (long long) t2_rej[3], (long long) t2_hit[3], (long long) dec_windows); for (int r = 0; r < 3; ++r) if (o.expert_cache_remote[(size_t) r] > 0) std::fprintf(stderr, "strata serve: CUDA%d: %lld expert entries, %lld active layer launches, %.1f MiB returned " "(%.1f MiB with full rows) in this request; host %.0f ms staging+launching, %.0f ms " "waiting for it in this request\n", r + 1, (long long) (remote_experts[(size_t) r].computed() - remote_before[(size_t) r]), (long long) (remote_experts[(size_t) r].launched_layers() - launches_before[(size_t) r]), (double) (remote_experts[(size_t) r].returned_bytes() - compact_before[(size_t) r]) / 1048576.0, (double) (remote_experts[(size_t) r].full_row_bytes() - full_before[(size_t) r]) / 1048576.0, remote_experts[(size_t) r].ms_begin() - begin_before[(size_t) r], remote_experts[(size_t) r].ms_wait() - wait_before[(size_t) r]); if (prefill_helper_src) { const uint64_t blobs = prefill_helper_src->helper_blobs(), bytes = prefill_helper_src->helper_bytes(); std::fprintf(stderr, "strata serve: prefill helper source: %lld blobs / %.1f MiB taken from a helper's " "cache in this request\n", (long long) (blobs - helper_blobs_before), (double) (bytes - helper_bytes_before) / 1048576.0); helper_blobs_before = blobs; helper_bytes_before = bytes; } } save_profile("exit"); // #477: QUIT, or the server closed stdin save_ram_profile("exit"); #if defined(STRATA_USE_HIP) && defined(__linux__) kfdq_exit::g_stop.store(nullptr); // the flag goes with this scope #endif // the NVMe tier keeps every conversation this engine holds, the live one too, for the next start if (conv_disk.enabled()) { const auto t0 = Clock::now(); if (!park_current(0)) err.clear(); const size_t n = conversations.spill_all(); std::fprintf(stderr, "strata serve: conversation disk: wrote %zu parked conversation%s at exit in %.1f s\n", n, n == 1 ? "" : "s", std::chrono::duration(Clock::now() - t0).count()); } #if defined(STRATA_GPU_METAL) // the stdin reader (detached above) may still take in_mu when the server closes the pipe after QUIT; on macOS // locking that mutex once this scope has destroyed it throws (the engine ended with an abort): end here std::fflush(stdout); std::fflush(stderr); std::_Exit(0); #endif return 0; } // ---- plan v0.3 P5: the prompt's conditioning positions [0, n_prompt - 1) in batched chunks. The token loop // then starts at the last prompt position, whose prediction is the first generated token. int64_t pos_start = 0; int64_t spec_pos = strata::spec::kSpecNotStarted; // plan v0.3 P6: where the speculative loop starts (0 is a real position: a 1-token prompt on a native pack) strata::prefill::Prefill prefill; if (!multi_gpu && o.batch <= 0) // STRATA_SWITCH_POINT: before any bytes_needed, like the share strata::prefill::Prefill::set_card_expert_share((int64_t) xcache.slots(), (int64_t) (g.n_layers * g.n_expert), xcache.slots() > 0 ? (double) xcache.bytes() / (double) xcache.slots() / 1e6 : 0.0, o.pcie_probe_gbps); // #1595: not by default when the cache holds every expert (nothing to take) strata::prefill::Prefill::arm_cpu_share(!multi_gpu && !o.no_pool, !multi_gpu && !o.no_pool && o.batch <= 0 && strata::prefill::share_rules::default_share_has_work((int64_t) xcache.slots(), (int64_t) (g.n_layers * g.n_expert)) && share_default_ok()); // H11 // before the chunk below sizes the loan 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 final_r_host(final_r ? (size_t) (g.hc * g.n_embd) : 0); std::vector> lent; // (residency index, slot) lent to the prompt path const int64_t n_batched = (o.prefill_until > 0 && o.prefill_until < n_prompt - 1) ? o.prefill_until : n_prompt - 1; if (o.prefill_chunk > 0 && n_prompt > 1) { void* borrow = nullptr; uint64_t borrow_bytes = 0; if (!o.no_prefill_borrow && !host_res.empty() && d_res != nullptr) { int64_t chunk = o.prefill_chunk; const int64_t chunk_in = chunk; int64_t k = plan_lend(chunk); // auto: the largest chunk that fits; fixed: halved to fit if (k > 0 && o.prefill_auto && n_batched > 1024) { // #2824: priced against the host, for THIS prompt's length const int64_t vram_chunk = chunk; chunk = host_plan_chunk( chunk, (uint64_t) std::max(0, (int64_t) xcache.bytes()), xcache.slots(), [&](int64_t c) { const int64_t kk = lend_slots(c); return kk + g_lend_keep <= xcache.slots() && kk * 100 <= kAutoLendPct * xcache.slots(); }, [&](int64_t c, uint64_t& bytes, int64_t& slots) { slots = lend_slots(c); bytes = bytes_from_slots(slots); }, [&](int64_t) { return strata::prefill::Prefill::ring_cap_for(4096); }, [&] { int64_t c2 = chunk_in; (void) plan_lend(c2); }, n_batched); if (chunk != vram_chunk) { // the whole prompt fits today's chunk: one pass, keep it (the plan's ring state goes back with it) if (request_chunk(n_batched, std::numeric_limits::max() / 2) <= vram_chunk) { chunk = vram_chunk; int64_t c2 = chunk_in; (void) plan_lend(c2); } else { #if defined(STRATA_PREFILL_FUSED) && !defined(STRATA_PREFILL_MMQ) chunk = std::min(vram_chunk, planned_chunk(n_batched, vram_chunk, chunk, false)); // equal chunks, no tail #else chunk = std::min(vram_chunk, planned_chunk(n_batched, vram_chunk, chunk)); // equal chunks, no tail #endif } k = lend_slots(chunk); } } #if defined(STRATA_PREFILL_FUSED) && !defined(STRATA_PREFILL_MMQ) // one GPU: equal chunks (equal_cut_rule.hpp), unless their loan would take more slots than today's cut const bool eq_one_gpu = !multi_gpu && !peer.valid() && !o.prefill_head_alias && o.batch <= 1; int64_t request_sized = loan_chunk(n_batched, equal_chunk(n_batched, chunk, eq_one_gpu)); if (eq_one_gpu) { const int64_t request_today = loan_chunk(n_batched, equal_chunk(n_batched, chunk, false)); if (request_sized != request_today && !strata::prefill::equal_cut::loan_ok(lend_slots(request_sized), lend_slots(request_today))) request_sized = request_today; // today's cut handed back for a short equal chunk (equal_cut_rule.hpp declined_equal), but its loan does not // fit while the equal cut's does: keep the equal cut (keep_equal) const int64_t declined = equal_cut_one == strata::prefill::equal_cut::Cut::equal ? strata::prefill::equal_cut::declined_equal(n_batched, chunk, strata::prefill::Prefill::stream_all_min_tokens()) : 0; if (declined > 0) { const int64_t eq_sized = loan_chunk(n_batched, declined); if (strata::prefill::equal_cut::keep_equal(lend_slots(request_sized), lend_slots(eq_sized), (int64_t) xcache.slots() - (int64_t) g_lend_keep)) { std::fprintf(stderr, "strata generate: prompt chunk %lld -> %lld tokens: the old cut's buffers do not fit " "the slots that can be lent, the equal cut's do\n", (long long) request_sized, (long long) eq_sized); request_sized = eq_sized; } } } #else const int64_t request_sized = loan_chunk(n_batched, equal_chunk(n_batched, chunk)); #endif if (k > 0 && request_sized < chunk) { // no bigger than this prompt segment needs chunk = request_sized; k = lend_slots(chunk); if (k + g_lend_keep > xcache.slots()) k = 0; if (!o.prefill_auto) o.prefill_chunk = chunk; } if (o.prefill_auto) { o.prefill_chunk = k > 0 ? chunk : request_chunk(n_batched, 1024); std::fprintf(stderr, "strata generate: prompt chunk auto: %lld tokens\n", (long long) o.prefill_chunk); } else if (chunk != o.prefill_chunk) { k = 0; // a fixed chunk that does not fit: its own buffers, as before } if (k > 0 && nib::any_on()) { // STRATA_EXPERT_NIBBLE: the lent slots would be refilled with GGUF blobs std::fprintf(stderr, "strata generate: STRATA_EXPERT_NIBBLE refuses the start: the prompt path would borrow %lld " "cache slots (--no-prefill-borrow keeps its own buffers)\n", (long long) k); return 1; } const int64_t blob = (int64_t) strata::kernels::cpu::expert_layout().max_blob; #if defined(STRATA_GPU_METAL) k = 0; // Metal: no loan of expert-cache slots (the prompt buffers are the Metal window's own); the refill after it copied into given-back allocations #endif 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]); host_res[i] = strata::core::kNotResident; } res_put(d_res); borrow = xcache.device_slot(first); borrow_bytes = xcache.slot_offsets() ? (uint64_t) (xcache.bytes() - (int64_t) xcache.slot_offsets()[first]) : (uint64_t) k * (uint64_t) blob; std::fprintf(stderr, "strata generate: prompt path borrows %lld cache slots (%.2f GiB)\n", (long long) k, (double) borrow_bytes / 1073741824.0); } } if (borrow == nullptr) std::fprintf(stderr, "strata generate: prompt path allocates its own buffers (no cache slots to borrow)\n"); if (!multi_gpu && !o.no_pool) prefill.set_cpu_pool(&pool); { std::string le; if (!lat_tab.load(g, le)) { std::fprintf(stderr, "strata generate: %s\n", le.c_str()); return 1; } } if (!prefill.init(wt, g, ss, srcp, o.expert_cache > 0 ? &xcache : nullptr, host_res.empty() ? nullptr : host_res.data(), o.prefill_chunk, main_cs, err, borrow, borrow_bytes)) { std::fprintf(stderr, "strata generate: %s\n", err.c_str()); return 1; } uma_refuse_chunk_if_full(o.prefill_chunk, borrow != nullptr, xcache.gib()); mem_mark("the prompt path's buffers"); if (std::getenv("STRATA_TRACE") != nullptr) { // what the buffers of this chunk take, and (Windows) the commit left std::fprintf(stderr, "strata trace: the prompt path's own buffers for a %lld-token chunk: %lld MiB (bytes_needed_owned)", (long long) o.prefill_chunk, (long long) (strata::prefill::Prefill::bytes_needed_owned(g, ss, o.prefill_chunk, srcp != nullptr) >> 20)); #if defined(_WIN32) MEMORYSTATUSEX ms_t{}; ms_t.dwLength = sizeof ms_t; if (GlobalMemoryStatusEx(&ms_t)) std::fprintf(stderr, "; commit left %.1f GiB, RAM available %.1f GiB", (double) ms_t.ullAvailPageFile / 1073741824.0, (double) ms_t.ullAvailPhys / 1073741824.0); #endif std::fprintf(stderr, "\n"); } if (!o.mtp.empty()) { if (!mtp.bind(wt, &native_head, nullptr, err)) { std::fprintf(stderr, "strata generate: %s\n", err.c_str()); return 1; } prefill.on_chunk = [&](const float* R_rows, int64_t T, int64_t p0, std::string& e) -> bool { if (mtp.cell_floor_enabled() && prefill.kva_floor() > mtp.cell_floor()) mtp.set_cell_floor(prefill.kva_floor()); // KVA // cell i pairs R_i with the token at i + 1 (every such token is in the prompt) std::vector nxt((size_t) T); for (int64_t t = 0; t < T; ++t) nxt[(size_t) t] = (int32_t) o.tokens[(size_t) (p0 + t + 1)]; if (prefill.draft_kv(mtp, R_rows, nxt.data(), T, p0, e)) return true; // E-9 return e.empty() && mtp.prefill(R_rows, nxt.data(), T, p0, e); }; } #if defined(STRATA_HAVE_DFLASH2) if (use_df2) { // the drafter's context: the last 2047 prompt rows' taps df2.reset(); prefill.set_taps(df2.tap_layers(), std::max(0, n_prompt - 2047), 2048); prefill.on_taps = [&](const float* taps, int64_t rows, int64_t pos0, std::string& e) -> bool { df2_tap_dump(taps, rows, pos0, (int64_t) df2.tap_layers().size() * g.n_embd); return df2.context(taps, rows, pos0, e); }; } #endif 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()); return 1; } // refill the lent slots from the arena and give them back to the decode tier if (!lent.empty()) { const Clock::time_point tr = Clock::now(); for (const auto& [i, slot] : lent) { // D-4: queued, one wait (STRATA_REFILL_BLOCKING=1: each) const uint8_t* b = srcp->blob_stable(i / g.n_expert, i % g.n_expert); const int64_t nb = (int64_t) strata::kernels::cpu::expert_layout().blob_bytes(i / g.n_expert); if (b == nullptr || !(refill_blocking() ? xcache.fill_slot_blocking(slot, b, err, nb) : xcache.fill_slot_queued(slot, b, err, nb))) { std::fprintf(stderr, "strata generate: refilling a lent slot failed: %s\n", err.c_str()); return 1; } if (!refill_blocking()) srcp->note_async_read(b, nullptr); // #1237 host_res[(size_t) i] = slot; } if (!xcache.sync_queued(err)) { std::fprintf(stderr, "strata generate: refilling the lent slots failed: %s\n", err.c_str()); return 1; } #if defined(_WIN32) for (const auto& [i, slot] : lent) srcp->release(i / g.n_expert, i % g.n_expert); #endif res_put(d_res); std::fprintf(stderr, "strata generate: %zu lent slots refilled in %.1f ms\n", lent.size(), std::chrono::duration(Clock::now() - tr).count()); } #if defined(STRATA_HAVE_DFLASH2) prefill.clear_taps(); #endif prefill_batched_ms = std::chrono::duration(Clock::now() - tp0).count(); prefill_ms += prefill_batched_ms; mem_mark("the prompt was read"); pos_start = n_batched; tok = o.tokens[(size_t) pos_start]; // the PLE window of the token path: the two tokens before `pos_start` ss.ple_prev[0] = pos_start >= 2 ? (int32_t) o.tokens[(size_t) (pos_start - 2)] : -1; ss.ple_prev[1] = pos_start >= 1 ? (int32_t) o.tokens[(size_t) (pos_start - 1)] : -1; const strata::prefill::PrefillStats& ps = prefill.stats(); std::fprintf(stderr, "strata generate: prefill %lld tokens in %lld chunks, %.1f ms (%.1f tok/s); experts " "streamed %lld (%lld by DMA, host %.1f ms), resident %lld, on the CPU %lld (share %.2f); PLE %.1f ms\n", (long long) ps.tokens, (long long) ps.chunks, ps.ms_total, ps.ms_total > 0 ? 1000.0 * (double) ps.tokens / ps.ms_total : 0.0, (long long) ps.experts_streamed, (long long) ps.experts_dma, ps.ms_experts_host, (long long) ps.experts_resident, (long long) ps.experts_cpu, ps.cpu_share, ps.ms_ple); if (ps.experts_direct > 0) std::fprintf(stderr, "strata generate: prompt MMQ read %lld of the %lld resident experts in their slots " "(STRATA_MMQ_DIRECT)\n", (long long) ps.experts_direct, (long long) ps.experts_resident); } 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; } if (pos >= o.max_context) { std::fprintf(stderr, "strata generate: ran out of context at position %lld\n", (long long) pos); return 2; } // **THE TOKEN TIMER STARTS HERE, BEFORE ANY OF THE TOKEN'S WORK (A7).** It used to start after // `put_input`/`embed_row`, which excluded the embedding and the PLE window advance from the reported // rate, and it stopped before the NaN scan, the logits dump and the sampler. The published tok/s // figure is a WALL-CLOCK rate: everything one token costs, PLE advance to sampled id. A rate that // excludes real per-token work is not a rate anyone can plan against. const Clock::time_point t0 = Clock::now(); // **THE PLE'S TOKEN WINDOW ADVANCES HERE, ONCE PER TOKEN, AND `ple_stage_token` RUNS OUTSIDE THE // CAPTURE.** Both are the driver's job: `ngram_rows` is a host hash over the last three tokens and the // table gather is a host read, so either one inside a captured graph would run once at capture time and // replay forever. `ple_prev` is OLDEST FIRST and `-1` means "no predecessor", which `ngram_rows` // treats as the EOS cut - a sequence boundary. ss.ple_token = (int32_t) tok; Clock::time_point tp = Clock::now(); // Plan v0.3 P2: the 16 SSD reads start here and complete while the embedding is staged; `ms_ple` is // the issue plus the time still spent WAITING afterwards, i.e. the part the embedding did not hide. if (ss.ple.ready() && !strata::core::ple_issue_token(ss.ple, err)) { std::fprintf(stderr, "strata generate: %s\n", err.c_str()); return 1; } { const Clock::time_point n = Clock::now(); ms_ple += std::chrono::duration(n - tp).count(); tp = n; } if (!put_input(tok, pos)) return 1; { const Clock::time_point n = Clock::now(); ms_embed += std::chrono::duration(n - tp).count(); tp = n; } if (ss.ple.ready() && !strata::core::ple_finish_token(ss.ple, token_stream, err)) { std::fprintf(stderr, "strata generate: %s\n", err.c_str()); return 1; } { const Clock::time_point n = Clock::now(); ms_ple += std::chrono::duration(n - tp).count(); tp = n; } if (pos % 256 == 0 || pos + 1 >= n_prompt - 1) std::fprintf(stderr, "strata generate: position %lld, token %lld%s\n", (long long) pos, (long long) tok, pos < n_prompt ? " (prompt)" : ""); // **`d.layers` IS THE BLOB'S LAYER AXIS, NOT A COUNTER.** The adapter uses it to index // `experts.bin` as `layer * n_expert + expert`, so it MUST restart at 0 for every token. Leaving it // running across tokens asks for layer 48 of a 48-layer file on the second token - which // `FileExpertSource` REFUSES rather than wrapping into layer 0's experts, and that refusal is the only // reason this was a clean error instead of a silently wrong second token. drive.d.layers = 0; drive.d.experts = 0; drive.d.failed = false; err.clear(); if (o.no_capture) { if (!strata::core::session_token(wt, g, pos, /*pos_base=*/0, ss, d_parts, main_cs, o.sync_every_layer, err)) { std::fprintf(stderr, "strata generate: session_token: %s\n", err.c_str()); return 1; } } else { strata::core::doorbell_reset(db); if (tgraph.captured) { if (!strata::core::session_run_token(g, pos, /*pos_base=*/0, ss, tgraph, pool_fn, pool_user, loop_scratch.y_miss, main_cs, err)) { std::fprintf(stderr, "strata generate: %s\n", err.c_str()); return 1; } } else if (!strata::core::session_loop(g, pos, /*pos_base=*/0, ss, gr, pool_fn, hit_fn, pool_user, /*overlap=*/true, main_cs, err, layer_stage, &loop_scratch)) { std::fprintf(stderr, "strata generate: session_loop: %s\n", err.c_str()); return 1; } } if (final_r != nullptr) { cudaMemcpy(final_r_host.data(), ss.R, final_r_host.size() * sizeof(float), cudaMemcpyDeviceToHost); const int64_t posrec[2] = {pos, tok}; std::fwrite(posrec, sizeof posrec, 1, final_r); std::fwrite(final_r_host.data(), sizeof(float), final_r_host.size(), final_r); } if (drive.d.failed) { std::fprintf(stderr, "strata generate: the expert pool failed at layer %lld expert %lld: %s\n", (long long) drive.d.fail_layer, (long long) drive.d.fail_expert, drive.d.fail ? drive.d.fail : "(no message)"); return 1; } { // **THE LAYER LOOP ITSELF, WHICH IS WHAT `--gpu-only-full` HAS TO BE COMPARED AGAINST.** const Clock::time_point n = Clock::now(); ms_layers += std::chrono::duration(n - tp).count(); tp = n; } // ---- the ladder for THIS position, in the order `session_loop` filled it: layer 0 first. if (layer_dump != nullptr) std::fwrite(layer_stage, sizeof(float), layer_floats, layer_dump); if (half_dump != nullptr) { std::fwrite(half_stage, sizeof(float), (size_t) g.n_layers * (size_t) half_stride, half_dump); } if (!run_head(token_stream)) { std::fprintf(stderr, "strata generate: lm_head: %s\n", err.c_str()); return 1; } // **A CHECKPOINT AFTER THE HEAD, BECAUSE AN ASYNC FAULT IS STICKY AND LIES ABOUT WHERE IT HAPPENED.** // Measured, and it cost an hour: without this, `embed_row`'s D2H on the NEXT token reported "an illegal // memory access" at a plane offset that has nothing to do with the fault, and the layer that actually // faulted had completed its own error checks successfully - because its kernels had not run yet. A // sticky error surfaces at the next SYNCHRONISING call, which is whatever happens to come next. if (!o.stream_token && cudaDeviceSynchronize() != cudaSuccess) { std::fprintf(stderr, "strata generate: the device faulted in lm_head at position %lld: %s\n", (long long) pos, cudaGetErrorString(cudaGetLastError())); return 1; } { const Clock::time_point n = Clock::now(); ms_head += std::chrono::duration(n - tp).count(); tp = n; } const bool emit_logits = dump != nullptr && strata::program::logits_selection::selected(pos, dump_positions, o.logits_stride); const bool read_logits = !o.stream_token || o.check_logits || emit_logits; if (read_logits && (cudaMemcpyAsync(logits.data(), d_logits, (size_t) n_vocab * 4, cudaMemcpyDeviceToHost, (cudaStream_t) token_stream) != cudaSuccess || cudaStreamSynchronize((cudaStream_t) token_stream) != cudaSuccess)) { std::fprintf(stderr, "strata generate: reading the logits back failed\n"); return 1; } int bad = 0; if (read_logits) for (float v : logits) if (!std::isfinite(v)) ++bad; if (bad != 0) { std::fprintf(stderr, "strata generate: %d of %lld logits are not finite at position %lld\n", bad, (long long) n_vocab, (long long) pos); return 1; } // the header with the first row (see `hdr`): a run that dumps nothing leaves an empty file if (emit_logits && !hdr_written && std::fwrite(hdr, sizeof hdr, 1, dump) != 1) { std::fprintf(stderr, "strata generate: cannot write logits header\n"); std::fclose(dump); return 1; } if (emit_logits) hdr_written = true; if (emit_logits && std::fwrite(logits.data(), sizeof(float), (size_t) n_vocab, dump) != (size_t) n_vocab) { std::fprintf(stderr, "strata generate: cannot write logits at position %lld\n", (long long) pos); std::fclose(dump); return 1; } { // **993 KB OF SYNCHRONOUS D2H AND A 248,320-FLOAT HOST SCAN, EVERY TOKEN.** (The review's notes // say 151,936 floats; the artifact's `output.weight` is 248,320 rows, so the real figure is 1.6x // that - a number nobody had checked because nothing measured this term.) R2.6 asks for the dump // and the scan to be behind flags; round 36 did exactly that and measured it SLOWER, because on // this driver a large blocking readback is also what flushes the pipeline for the sampler that // follows. Timed so the claim can be re-checked rather than remembered. const Clock::time_point n = Clock::now(); ms_readback += std::chrono::duration(n - tp).count(); tp = n; } int next = 0; // The draw is Philox(seed, position), as in a verify window (row t at pos0 draws pos0 + t): a seed gives // the same text whether a token comes from this path or from the speculative loop below. sp.counter = (uint64_t) pos; strata::kernels::sample_tokens(d_logits, 1, (int) n_vocab, nullptr, 0, sp, d_next, token_stream); if (cudaMemcpyAsync(&next, d_next, sizeof(int), cudaMemcpyDeviceToHost, (cudaStream_t) token_stream) != cudaSuccess || cudaStreamSynchronize((cudaStream_t) token_stream) != cudaSuccess) { std::fprintf(stderr, "strata generate: reading the sampled token back failed: %s\n", cudaGetErrorString(cudaGetLastError())); return 1; } // The sampled-token synchronization also completes every captured QSA // status readback. Retain one status per layer so a later layer cannot // hide an earlier failure; no extra synchronization or token allocation. if (o.native_flash_attn_short) for (int64_t j = 0; j < ss.qsa_alloc; ++j) { const int64_t i = ss.qsa_ord0 + j; // the global ordinal, as the session's carve names it const int32_t status = ss.qsa_states[i].host_step[strata::kernels::kStepCount]; if (status != 0) { std::fprintf(stderr, "strata generate: native attention status %d at QSA layer %lld, position %lld\n", status, (long long) i, (long long) pos); return 1; } } if (next < 0 || next >= n_vocab) { std::fprintf(stderr, "strata generate: the sampler returned %d, outside 0..%lld\n", next, (long long) (n_vocab - 1)); return 1; } { // **TWO DEVICE-WIDE SYNCS FOR FOUR BYTES.** `sample_tokens(nullptr)` ends in // `cudaDeviceSynchronize()` (`sampler.cu:245`) and the blocking 4-byte read below is the second. const Clock::time_point n = Clock::now(); ms_sample += std::chrono::duration(n - tp).count(); ++phase_tokens; } // CHARGED HERE, AFTER THE SAMPLER, so the wall-clock rate covers the whole token including the embedding, // the NaN scan, the logits readback and the sample (A7). Only DECODE positions count; prefill is // measured separately. if (pos >= n_prompt - 1) total_ms += std::chrono::duration(Clock::now() - t0).count(); else prefill_ms += std::chrono::duration(Clock::now() - t0).count(); if (pos == n_prompt - 1) ttft_ms = std::chrono::duration(Clock::now() - t_start).count(); // **THE PREDICTION AT THE LAST PROMPT POSITION *IS* THE FIRST GENERATED TOKEN.** Sampling on every // position and recording only from `n_prompt - 1` onward is what keeps the two cases from needing // separate handling - and the version that "obviously" only samples after the prompt loses exactly one // token's worth of conditioning. if (pos >= n_prompt - 1) produced.push_back(next); if ((int64_t) produced.size() >= o.max_new) break; if (o.stop_eos && pos >= n_prompt - 1 && std::find(o.eos_ids.begin(), o.eos_ids.end(), (int64_t) next) != o.eos_ids.end()) break; // TEACHER FORCING while the prompt lasts: the next input is the prompt's own next token, not the // model's guess. Feeding the guess would make the run depend on the model's own errors from position // 1, which is a different (and worse) measurement of the same prompt. // and the window advances: the token just decoded becomes the newest predecessor. ss.ple_prev[0] = ss.ple_prev[1]; ss.ple_prev[1] = (int32_t) tok; tok = (pos + 1 < n_prompt) ? o.tokens[(size_t) (pos + 1)] : next; // Plan v0.3 P6: from the first generated token on, the speculative loop below takes over. if (o.spec > 0 && pos >= n_prompt - 1) { spec_pos = pos + 1; break; } } // ================================ plan v0.3 P6: SPECULATIVE DECODING ================================ // // Each round verifies [the last emitted token, drafts...] in one window; the window's argmax after token t // is exactly what greedy decode would emit there, so the first draft that differs ends the round and the // round emits (accepted drafts + 1) tokens. `commit` keeps the state of the tokens that were emitted. const bool ended = o.stop_eos && !produced.empty() && std::find(o.eos_ids.begin(), o.eos_ids.end(), (int64_t) produced.back()) != o.eos_ids.end(); if (strata::spec::spec_loop_runs(spec_pos, (int64_t) produced.size(), o.max_new, ended)) { auto read_ids = [](const std::string& path, std::vector& ids) { std::ifstream in(path); std::string text((std::istreambuf_iterator(in)), std::istreambuf_iterator()); std::string e; return (bool) in && parse_i64_list(text.c_str(), ids, e); }; std::vector oracle, follow; if (!o.spec_oracle.empty() && !read_ids(o.spec_oracle, oracle)) { std::fprintf(stderr, "strata generate: cannot read --spec-oracle %s\n", o.spec_oracle.c_str()); return 2; } if (!o.spec_follow.empty() && !read_ids(o.spec_follow, follow)) { std::fprintf(stderr, "strata generate: cannot read --spec-follow %s\n", o.spec_follow.c_str()); return 2; } // --spec-follow: the run ends with the continuation const int64_t max_new = follow.empty() ? o.max_new : std::min(o.max_new, (int64_t) follow.size()); int64_t follow_differ = 0, follow_emitted = 0; if (thits.d_res == nullptr) { std::fprintf(stderr, "strata generate: --spec needs the device residency table (--expert-profile, " "--expert-cache and the token graph)\n"); return 2; } mem_mark("the head and the prompt path"); strata::core::Verifier ver; strata::core::VerifyHits vh; vh.d_res = thits.d_res; vh.h_res = host_res.empty() ? nullptr : host_res.data(); vh.cache_base = thits.cache_base; vh.blob = thits.blob; vh.slot_off = xcache.slot_offsets(); // E-6: the device plan's pointers vh.n_slots = xcache.slots(); if (pcie_balance()) ver.set_pcie_balance(&drive.d.pcie_model); #if defined(STRATA_HAVE_DFLASH2) if (use_df2) ver.set_taps(df2.tap_layers()); #endif if (!ver.init(wt, g, ss, vh, native_head.loaded() ? &native_head : nullptr, o.spec, err)) { std::fprintf(stderr, "strata generate: %s\n", err.c_str()); return 1; } const bool use_mtp = !o.mtp.empty(); if (use_mtp && !mtp.bind(wt, &native_head, ver.final_R_all(), err)) { std::fprintf(stderr, "strata generate: %s\n", err.c_str()); return 1; } #if defined(STRATA_HAVE_DFLASH2) if (use_df2 && !ver.tapping()) { std::fprintf(stderr, "strata generate: --draft dflash2: the verifier keeps no taps here; the MTP drafts instead\n"); use_df2 = false; } if (use_df2) df2_offer_head(); if (use_df2 && !df2.bind(wt, &native_head, df2_vocab_path(), err)) { std::fprintf(stderr, "strata generate: --draft dflash2: %s. It needs about 1.2 GiB of VRAM in all (the pack 0.76 GiB, buffers and K/V ring " "0.25 GiB, a draft head 0.2 GiB); --vram-reserve-mib 1900 keeps it (the expert cache gives up about 2.5%% of its experts " "to the CPU). The MTP drafts instead.\n", err.c_str()); use_df2 = false; } if (use_df2) df2.set_max_drafts((o.mtp_max_t > 0 ? std::min(o.mtp_max_t, o.spec) : o.spec) - 1); // the widest window - 1: the head and the walk run for that many rows if (use_df2 && !df2.prepare(ver.tap_dev(), err)) { std::fprintf(stderr, "strata generate: --draft dflash2: %s. It needs about 1.2 GiB of VRAM in all (the pack 0.76 GiB, buffers and K/V ring " "0.25 GiB, a draft head 0.2 GiB); --vram-reserve-mib 1900 keeps it (the expert cache gives up about 2.5%% of its experts " "to the CPU). The MTP drafts instead.\n", err.c_str()); use_df2 = false; } if (use_df2) std::fprintf(stderr, "strata generate: DFlash2 drafter on (%s, graphs captured in %.0f ms), %s\n", o.draft_model.c_str(), df2.ms_capture, df2_solo ? "no MTP layer is loaded (--draft-fallback none)" : "the MTP layer stays as the fallback"); else if (o.draft == "dflash2" && o.draft_mtp_spec_set && o.spec > o.draft_mtp_spec) o.spec = o.draft_mtp_spec; // fell back: the MTP's own window #endif if (df2_solo && !use_df2) { // --draft-fallback none: the reason is printed above; there is no MTP to draft instead std::fprintf(stderr, "strata generate: --draft-fallback none: DFlash2 did not start and no MTP is loaded, so the run ends here\n"); return 1; } const bool draft_on = use_mtp || use_df2; // some drafter proposes (--draft-fallback none: DFlash2 alone, use_mtp false) mem_mark("the verifier and the drafter's binding"); ver.set_sampling(sp); // the CLI's own sampling (until 0.1.19 this loop was always greedy); no penalties here if (use_mtp) mtp.set_draft_sampling(sp); // STRATA_SPEC_COUPLED=1: sampled drafts (a no-op otherwise) ver.set_split(o.spec_split); // auto: the copy kernel for every pack. DMA (the native packs' default until 0.1.13) has the host call // cudaMemcpyAsync + cudaLaunchHostFunc inside a verify window while the GPU spins on the flag they raise; // issue #31's thread dumps show the host stuck in that cudaMemcpyAsync on a driver lock for good. The copy // kernel needs no host CUDA call there, and costs ~1-3% decode on IQ3_S (45.3 -> 44.8 tok/s, 8 requests). ver.set_pcie_mode(o.pcie_mode == "dma" ? 0 : o.pcie_mode == "direct" ? 1 : 2); drive.d.plan = ver.plan_sink(); drive.d.pcie_num = (int) (o.pcie_frac * 256.0 + 0.5); if (drive.d.pcie_num < 0) drive.d.pcie_num = 0; if (drive.d.pcie_num > 256) drive.d.pcie_num = 256; const int64_t pcie0 = drive.d.pcie_experts; // CS-T: the file tier since the decode began (the prompt path's copies are before this) const int64_t files0 = src.file_reads(), ram0 = src.ram_reads(); const uint64_t fbytes0 = src.file_blob_bytes(), fall0 = src.file_read_bytes(); const double fms0 = src.file_ms(); if (o.adapt_every > 0 && o.adapt_swaps > 0) drive.d.usage.assign((size_t) (g.n_layers * g.n_expert), 0.0f); const char* fetch_off = d_res == nullptr ? "no residency table" : o.spec_split ? "--spec-split" : multi_gpu ? "a layer split" : drive.d.peer != nullptr ? "a peer tier" : drive.d.remote_count > 0 ? "helper GPUs" : nullptr; if (adapt_fetch() > 0) { // STRATA_ADAPT_FETCH (opt-in) const char* off = drive.d.usage.empty() ? "the adaptive tier is off" : fetch_off != nullptr ? fetch_off : o.pcie_mode == "dma" || o.pcie_mode == "direct" ? "--pcie-mode dma / direct" : drive.d.plan == nullptr ? "no GPU plan" : drive.d.pcie_num <= 0 ? "no PCIe share" : src.complement_ready() ? "the resident RAM mode" : nullptr; if (off != nullptr) std::fprintf(stderr, "strata generate: STRATA_ADAPT_FETCH is off (%s)\n", off); else { drive.d.fetch_admit = adapt_fetch(); drive.d.res_mut = host_res.data(); drive.d.in_flight.assign(host_res.size(), 0); drive.d.fetch_avail.assign((size_t) g.n_layers, 0); if (const char* v = std::getenv("STRATA_ADAPT_FETCH_MIN")) drive.d.fetch_min = (float) std::atof(v); if (const char* v = std::getenv("STRATA_ADAPT_FETCH_MARGIN")) drive.d.fetch_margin = (float) std::atof(v); drive.d.fetch_log_on = std::getenv("STRATA_ADAPT_FETCH_VERIFY") != nullptr; std::fprintf(stderr, "strata generate: STRATA_ADAPT_FETCH=%d: the PCIe share takes each layer's most-routed " "misses and admits those routed >= %.2f and %.2f more than a resident one%s\n", drive.d.fetch_admit, drive.d.fetch_min, drive.d.fetch_margin, drive.d.fetch_admit == 2 ? "; the tier's own copies are off" : ""); } } // before every window: the device's table follows the host's (the tier's evictions while its copies are in // flight, STRATA_ADAPT_FETCH's admissions - see the serve path); the hook's captures live in this block, so it // is taken off the verifier when the block ends const bool res_checking = std::getenv("STRATA_ADAPT_CHECKRES") != nullptr && d_res != nullptr; std::vector res_back; int64_t res_windows = 0, res_bad = 0, res_bad_windows = 0; if (res_checking) { res_back.assign(host_res.size(), 0); drive.d.dres_check = res_back.data(); } drive.d.evict_sync = d_res != nullptr && !drive.d.usage.empty() && (adapt_nowait() || adapt_lag() > 1) && (adapt_evict_sync() || drive.d.fetch_admit > 0); // the changed entries by a kernel on the verifier's stream (see the serve path) constexpr size_t kResPatchCap = 16384; int32_t* res_pairs = (drive.d.fetch_admit > 0 || drive.d.evict_sync) ? res_pairs_alloc(kResPatchCap, {-1}) : nullptr; struct PreLaunchOff { strata::core::Verifier& v; strata::core::ExpertDispatch& d; int32_t* pairs; ~PreLaunchOff() { v.set_pre_launch(nullptr); d.dres_check = nullptr; if (pairs != nullptr) cudaFreeHost(pairs); } } pre_launch_off{ver, drive.d, res_pairs}; if (drive.d.fetch_admit > 0 || drive.d.evict_sync || res_checking) ver.set_pre_launch([&](cudaStream_t cs, std::string& e) -> bool { if (drive.d.res_dirty) { const int64_t n = res_patch_pairs(drive.d.res_dirty_idx, host_res, res_pairs, kResPatchCap); cudaError_t r; if (n >= 0) { strata::kernels::res_patch(d_res, res_pairs, (int) n, cs); r = cudaGetLastError(); } else { r = res_put(d_res); } if (r != cudaSuccess) { e = std::string("the residency table update failed: ") + cudaGetErrorString(r); return false; } drive.d.res_dirty = false; drive.d.res_dirty_idx.clear(); } if (!res_checking) return true; cudaStreamSynchronize(cs); // the patch landed const int64_t bad = res_check(d_res, host_res, res_back, g.n_expert, res_windows); ++res_windows; res_bad += bad; res_bad_windows += bad > 0; return true; }); int64_t swaps_total = 0; double ms_adapt = 0; cudaStream_t adapt_stream = nullptr; if (!drive.d.usage.empty() && cudaStreamCreateWithFlags(&adapt_stream, cudaStreamNonBlocking) != cudaSuccess) { std::fprintf(stderr, "strata generate: cannot create the refill stream\n"); return 1; } // plan v0.3 P6: swaps in flight - (residency index, slot) admitted when adapt_ev has completed std::vector> pending; int pending_age = 0; // the windows the pending swaps have waited (adapt_lag) std::vector pin_live; // the swaps' locked arena pages (pin_blob), unlocked once they have landed cudaEvent_t adapt_ev = nullptr; cudaEventCreateWithFlags(&adapt_ev, cudaEventDisableTiming); int64_t adapt_rounds = 0; // counted here: `rounds` is declared below the adapt lambda auto apply_pending = [&](bool wait) { if (pending.empty()) return; // STRATA_TRACE_ADAPT=1: whether a round's copies had landed when the next window read the table static const bool trace_pending = std::getenv("STRATA_TRACE_ADAPT") != nullptr; if (wait) cudaEventSynchronize(adapt_ev); else if (cudaEventQuery(adapt_ev) != cudaSuccess) { if (trace_pending) std::fprintf(stderr, "strata: PENDING not landed, %zu stay non-resident this window\n", pending.size()); return; } if (trace_pending) std::fprintf(stderr, "strata: PENDING landed, %zu experts become resident\n", pending.size()); unpin_blobs(pin_live); src.commit_exchanges(); // the resident RAM mode: the evicted experts take their places in RAM for (const auto& [i, slot] : pending) { host_res[(size_t) i] = slot; srcp->release((int64_t) i / g.n_expert, (int64_t) i % g.n_expert); // in VRAM now: RAM not needed if (!drive.d.in_flight.empty()) drive.d.in_flight[(size_t) i] = 0; } if (drive.d.evict_sync || drive.d.fetch_admit > 0) { // a failed upload leaves them to the pre-launch hook for (const auto& pr : pending) drive.d.res_dirty_idx.push_back(pr.first); drive.d.res_dirty = true; } pending.clear(); pending_age = 0; if (d_res != nullptr && res_put(d_res) == cudaSuccess) { // the whole table: the hook has nothing left drive.d.res_dirty = false; drive.d.res_dirty_idx.clear(); } }; // Plan v0.3 P6: the VRAM tier follows the conversation. Candidates are missing experts routed at least // twice (decayed); each is paired with its layer's least-routed resident expert and swapped when it was // routed clearly more often. Copies run between rounds, when the GPU is idle. auto adapt = [&]() -> bool { const Clock::time_point ta = Clock::now(); ++adapt_rounds; // STRATA_TRACE_ADAPT: why an adapt round did or did not swap. Default off, one getenv, and it // reports the only thing that can make an adapt round a coin flip: whether the PREVIOUS round's // asynchronous expert copies had landed by the time this round started. static const bool trace_adapt = std::getenv("STRATA_TRACE_ADAPT") != nullptr; if (!pending.empty()) { if (trace_adapt) std::fprintf(stderr, "strata: ADAPT round=%lld SKIPPED, %zu swaps still in flight\n", (long long) adapt_rounds, pending.size()); return true; // the previous swaps are still in flight } if (trace_adapt) std::fprintf(stderr, "strata: ADAPT round=%lld considering\n", (long long) adapt_rounds); struct Swap { float gain; int32_t layer, in, out; }; std::vector swaps; std::vector> cand, vict; for (int64_t l = 0; l < g.n_layers; ++l) { // STRATA_ADAPT_FETCH=2: where the PCIe share fetched since the last round, its fetchable experts are // the admission's; the tier keeps the rest (no share there, or not pinned) const bool fetched = drive.d.fetch_admit == 2 && !drive.d.fetch_avail.empty() && drive.d.fetch_avail[(size_t) l]; if (!drive.d.fetch_avail.empty()) drive.d.fetch_avail[(size_t) l] = 0; cand.clear(); vict.clear(); const float* u = drive.d.usage.data() + l * g.n_expert; const int32_t* r = host_res.data() + l * g.n_expert; for (int32_t e = 0; e < (int32_t) g.n_expert; ++e) { if (r[e] < 0) { if (u[e] >= 2.0f && !helper_holds(l, e) && !(fetched && srcp->pinned(l, e))) cand.emplace_back(u[e], e); } else vict.emplace_back(u[e], e); } if (cand.empty() || vict.empty()) continue; std::sort(cand.begin(), cand.end(), [](auto& a, auto& b) { return a.first > b.first; }); const size_t nc = std::min(cand.size(), vict.size()); std::partial_sort(vict.begin(), vict.begin() + (ptrdiff_t) nc, vict.end(), [](auto& a, auto& b) { return a.first < b.first; }); for (size_t i = 0; i < nc; ++i) { if (cand[i].first < vict[i].first + 1.5f) break; swaps.push_back({cand[i].first - vict[i].first, (int32_t) l, cand[i].second, vict[i].second}); } } std::sort(swaps.begin(), swaps.end(), [](const Swap& a, const Swap& b) { return a.gain > b.gain; }); if ((int) swaps.size() > o.adapt_swaps) swaps.resize((size_t) o.adapt_swaps); // this (non-serve) path refills CUDA0's cache only, so its copies back read CUDA0's cache too if (!resident_stage_swaps(src, host_res, g.n_expert, swaps, [&](int64_t) -> SwapHome { return {&xcache, adapt_stream, -1}; })) { std::fprintf(stderr, "strata generate: an adaptive refill failed (copying evicted experts back)\n"); return false; } if (pin_blobs_on()) { // lock the batch's source pages (a file-backed arena on AMD; see pin_blobs) std::vector> spans; for (const Swap& s : swaps) if (const uint8_t* b = srcp->blob_stable(s.layer, s.in)) spans.emplace_back((uintptr_t) b, (uintptr_t) b + strata::kernels::cpu::expert_layout().blob_bytes(s.layer)); pin_blobs(std::move(spans), pin_live); } // STRATA_DMA_BATCH (F12): the round's copies as one cudaMemcpyBatchAsync; mode 0 is the loop of one copy each const int dma_mode = strata::core::dma_batch_mode(); std::vector cp_dst; std::vector cp_src; std::vector cp_bytes; for (const Swap& s : swaps) { const size_t in = (size_t) s.layer * g.n_expert + s.in, out = (size_t) s.layer * g.n_expert + s.out; const int32_t slot = host_res[out]; const uint8_t* b = srcp->blob_stable(s.layer, s.in); nib::guard_raw(s.layer, "the adaptive refill's copy in"); const size_t blob_n = (size_t) strata::kernels::cpu::expert_layout().blob_bytes(s.layer); // asynchronous: the copies run while the MTP drafts; the next window waits for them if (slot < 0 || b == nullptr) { std::fprintf(stderr, "strata generate: an adaptive refill failed\n"); return false; } if (dma_mode != 0) { cp_dst.push_back(xcache.device_slot(slot)); cp_src.push_back(b); cp_bytes.push_back(blob_n); } else if (adapt_copy_h2d(xcache.device_slot(slot), b, blob_n, adapt_stream) != cudaSuccess) { std::fprintf(stderr, "strata generate: an adaptive refill failed\n"); return false; } host_res[out] = strata::core::kNotResident; // evicted now: the CPU computes it meanwhile srcp->prefetch(s.layer, s.out); // a file-backed arena released its pages: read them back ahead pending.emplace_back((int32_t) in, slot); // resident once the copy has landed if (!drive.d.in_flight.empty()) drive.d.in_flight[in] = 1; // STRATA_ADAPT_FETCH leaves it alone } if (drive.d.evict_sync && !swaps.empty()) { // the evicted ones are misses now (see the pre-launch hook) for (const Swap& s : swaps) drive.d.res_dirty_idx.push_back((int32_t) (s.layer * g.n_expert + s.out)); drive.d.res_dirty = true; } if (!cp_dst.empty() && strata::core::copy_blobs(cp_dst.data(), cp_src.data(), cp_bytes.data(), cp_dst.size(), adapt_stream, dma_mode) != cudaSuccess) { std::fprintf(stderr, "strata generate: an adaptive refill failed\n"); return false; } if (!swaps.empty()) cudaEventRecord(adapt_ev, adapt_stream); if (trace_adapt) std::fprintf(stderr, "strata: ADAPT round=%lld swapped %zu of %d slots, usage decayed\n", (long long) adapt_rounds, swaps.size(), o.adapt_swaps); for (float& v : drive.d.usage) v *= o.adapt_decay; swaps_total += (int64_t) swaps.size(); ms_adapt += std::chrono::duration(Clock::now() - ta).count(); return true; }; int64_t p = spec_pos; int32_t x = (int32_t) tok; std::vector drafts((size_t) o.spec, 0); std::vector dprob((size_t) o.spec, 1.0f); std::vector window_hist((size_t) o.spec + 1, 0); // STRATA_SPEC_T_CYCLE=1,2,3,4,5,6,7,8 (bench only, off by default): the window size cycles through the list, so one run // measures the cost of each verify width (with --spec-oracle drafts every row is accepted); the first round of a // width (its graph capture) is not counted std::vector t_cycle; if (const char* tc = std::getenv("STRATA_SPEC_T_CYCLE"); tc != nullptr && tc[0] != '\0') { for (const char* q = tc; *q != '\0';) { const int v = std::atoi(q); if (v >= 1 && v <= o.spec) t_cycle.push_back(v); while (*q != '\0' && *q != ',') ++q; if (*q == ',') ++q; } } // STRATA_SPEC_TRACE= (bench only, off by default): one line per round, "T a sfx ms p1 p2 ..." (window rows, drafts accepted, // lookup window, round ms, the MTP draft probabilities), for offline window-length policy studies // STRATA_SPEC_COST=1 (A/B arm, bench): the MTP window by expected tokens per ms at this machine's measured row costs // (DraftPolicy::keep_draft, step by step) instead of "draft probability >= --spec-min-p" const bool spec_cost = [] { const char* v = std::getenv("STRATA_SPEC_COST"); return v != nullptr && v[0] == '1'; }(); std::vector dwin((size_t) o.spec, 0.0f); // the draft probabilities this round's window was chosen from std::FILE* spec_trace = nullptr; if (const char* tf = std::getenv("STRATA_SPEC_TRACE"); tf != nullptr && tf[0] != '\0') spec_trace = std::fopen(tf, "w"); std::vector t_cycle_ms((size_t) o.spec + 1, 0.0); std::vector t_cycle_n((size_t) o.spec + 1, 0), t_cycle_seen((size_t) o.spec + 1, 0); // plan v0.3 P6: with a native pack the first window is the last prompt token alone (it produces the first // generated token and the MTP's first cell); otherwise the token loop already did that. bool first_window = native_pack; const int S_mtp = o.mtp_max_t > 0 ? std::min(o.mtp_max_t, o.spec) : o.spec; #if defined(STRATA_HAVE_DFLASH2) const bool spec_uses_df2 = use_df2; #else const bool spec_uses_df2 = false; // no DFlash2 drafter in this build (Metal) #endif const bool gated_proposal = use_mtp && mtp.prob() && strata::core::spec_gate_pick() && gated_proposal_usable(o.pipeline_windows < 2 && o.batch == 0 && !multi_gpu && drive.d.remote_count == 0, o.lookup_chain, o.adapt_swaps, o.pcie_frac != 0.0 || o.pcie_frac_auto, spec_cost || spec_uses_df2 || !t_cycle.empty() || o.spec_corrupt > 0, o.spec, o.spec_min_p); if (gated_proposal && !follow.empty()) std::fprintf(stderr, "strata generate: --spec-follow replaces outputs before acceptance (teacher-forced diagnostic, not sampling-law evidence)\n"); strata::core::MtpDrafter::DraftResult generation; strata::core::gated::Packet proposal; { // Non-native prefill already emitted x; draft_first(cell=p-1) samples at p. const GatedDraftLimit draft_limit(mtp, gated_proposal, S_mtp, p, o.max_context); if (use_mtp && !first_window && !mtp.draft_first(o.spec, ss.R, x, p - 1, drafts.data(), err, dprob.data(), (float) o.spec_min_p, nullptr, gated_proposal ? &generation : nullptr)) { std::fprintf(stderr, "strata generate: %s\n", err.c_str()); return 1; } } std::vector window((size_t) o.spec), outv((size_t) o.spec); std::vector fdiff((size_t) o.spec, 0); std::FILE* hashes = o.window_hashes.empty() ? nullptr : std::fopen(o.window_hashes.c_str(), "w"); if (!o.window_hashes.empty() && hashes == nullptr) { std::fprintf(stderr, "strata generate: cannot write %s\n", o.window_hashes.c_str()); return 1; } std::vector hash_rows; std::vector accepted_hist((size_t) o.spec, 0); int64_t rounds = 0, drafts_total = 0, drafts_ok = 0, corrupt_counter = 0; if (use_mtp && S_mtp < o.spec) mtp.set_max_drafts(S_mtp - 1); strata::spec::SuffixDrafter sfx(std::max(1, o.suffix_draft), 64, (size_t) o.max_context + 4096); strata::spec::DraftPolicy policy(o.spec); // MTP or lookup window (see draft_policy.hpp) auto source_policy = policy; // this generation's: committed outcomes only (observe_committed) strata::spec::DraftPolicy::ChainState chain_st; int chain_rows = 1; // STRATA_SPEC_COST: the window the cost-aware rule kept in the MTP chain just drafted if (const char* tab = std::getenv("STRATA_SPEC_COST_TABLE"); spec_cost && tab != nullptr && tab[0] != '\0') { // "T1,T2,..;T1,T2,..;T1,..": the row costs of the 3 context buckets (< 6K, < 24K, longer); one list seeds the first double ms[strata::spec::DraftPolicy::kMaxT] = {}; int n = 0, bucket = 0; for (const char* q = tab; *q != '\0' && bucket < strata::spec::DraftPolicy::kCtxBuckets;) { if (n < strata::spec::DraftPolicy::kMaxT) ms[n++] = std::atof(q); while (*q != '\0' && *q != ',' && *q != ';') ++q; const bool end_list = *q == ';' || *q == '\0'; if (*q != '\0') ++q; if (end_list) { policy.seed_costs(ms, n, 6.0, bucket++); n = 0; } } } policy.set_robust(spec_cost); if (spec_cost && use_mtp) mtp.set_chain_rule([&](int idx, float pj) { const bool k = policy.keep_draft(chain_st, idx, pj, S_mtp); chain_rows = chain_st.best_rows; return k; }); policy.set_sizes(lookup_size_mask(o)); std::vector sbuf((size_t) o.spec, 0); int64_t sfx_windows = 0, sfx_drafts = 0, sfx_ok = 0; int64_t chain_windows = 0, chain_drafts = 0, chain_ok = 0; // --lookup-chain's own counts std::vector cbuf((size_t) o.spec, 0), ctail; strata::spec::PromptLookupSource lookup_src(sfx); const bool sfx_on = o.suffix_draft > 0 || o.lookup_chain > 0; if (sfx_on) { for (int64_t t : o.tokens) sfx.append((int32_t) t); for (int64_t t : produced) sfx.append((int32_t) t); } if (o.lookup_chain > 0) { extra_sources_reset(); for (int64_t t : o.tokens) { const int32_t t32 = (int32_t) t; extra_sources_append(&t32, 1); } for (int64_t t : produced) { const int32_t t32 = (int32_t) t; extra_sources_append(&t32, 1); } } const double pool_ms0 = drive.cpu_ms; const int64_t misses0 = drive.d.multi_misses, entries0 = drive.d.multi_entries; // STRATA_SPEC_WATCH= (diagnostics, off by default): the serve watchdog for this loop. A run whose verify // windows and prompt chunks stop beating for that long prints the stage it is in and the stall report, then ends. if (const char* sw = std::getenv("STRATA_SPEC_WATCH"); sw != nullptr && std::atoi(sw) > 0) { const int limit = std::atoi(sw); strata::core::progress().busy.store(true); std::thread([limit] { strata::core::Progress& pr = strata::core::progress(); uint64_t last = pr.beats.load(), ticks_at = pr.ticks.load(); auto since = std::chrono::steady_clock::now(); for (;;) { std::this_thread::sleep_for(std::chrono::seconds(1)); const auto now = std::chrono::steady_clock::now(); const uint64_t b = pr.beats.load(); if (b != last) { last = b; ticks_at = pr.ticks.load(); since = now; continue; } if (now - since < std::chrono::seconds(limit)) continue; std::fprintf(stderr, "strata generate: no progress for %d s (%s)\n", limit, stage_text().c_str()); stall_report(stderr, pr.ticks.load() - ticks_at); strata::core::release_gpu_waits(stderr); std::fflush(stderr); std::abort(); } }).detach(); } // DFlash2 with a long suffix match: the draft of the next round is deferred (spec/window_rule.hpp) #if defined(STRATA_GPU_METAL) const int df2_skip_min = strata::spec::df2_lookup_skip_min(8); #else const int df2_skip_min = strata::spec::df2_lookup_skip_min(0); #endif bool df2_deferred = false; int dfr_n = 0; int64_t dfr_pos = 0; int32_t dfr_anchor = 0; // the next round's drafts after a commit: the MTP chain, or the DFlash2 block from the committed rows' taps auto draft_next = [&](int T_, int a_) -> bool { #if defined(STRATA_HAVE_DFLASH2) if (use_df2) { if (o.suffix_draft > 0 && !first_window) { // a long suffix match: no draft now (spec/window_rule.hpp skip_draft_for_lookup); the next round decides const int ks = sfx.propose(o.spec - 1, sbuf.data()); if (strata::spec::skip_draft_for_lookup(true, df2_skip_min, ks, sfx.last_match())) { df2_deferred = true; dfr_n = a_ + 1; dfr_pos = p; dfr_anchor = outv[(size_t) a_]; return true; } } static const bool wait_commit_first = std::getenv("STRATA_DF2_WAITCOMMIT") != nullptr; // measurement: no overlap with the async commit if (wait_commit_first && !ver.wait_commit(err)) return false; int32_t dd[strata::core::Dflash2Drafter::kDrafts]; float pp[strata::core::Dflash2Drafter::kDrafts]; if (!df2.draft(ver.tap_dev(), a_ + 1, p, outv[(size_t) a_], dd, pp, err)) return false; for (size_t i = 0; i < drafts.size() && i < (size_t) strata::core::Dflash2Drafter::kDrafts; ++i) { drafts[i] = dd[i]; dprob[i] = pp[i]; } // what the MTP does while it drafts: the PLE rows of the tokens the next window will hold are read ahead // (the window's gather would otherwise wait for them: 1.8 ms a round on strix) if (ss.ple.ready() && ss.ple.table != nullptr) { int n_pf = 0; const int cap = std::min(S_mtp, (int) drafts.size() + 1); double chain = 1.0; for (int t = 1; t < cap; ++t) { if (o.draft_conf > 0.0) { if ((chain *= (double) dprob[(size_t) t - 1]) < o.draft_conf) break; } else if (o.spec_min_p > 0.0 && dprob[(size_t) t - 1] < (float) o.spec_min_p) break; ++n_pf; } int32_t prev[2] = {ss.ple_prev[0], ss.ple_prev[1]}; auto pf = [&](int32_t tok) { uint32_t rows16[strata::kernels::PLE_N_HEADS]; strata::kernels::ngram_rows(&tok, prev, 1, ss.ple.consts, rows16); prev[0] = prev[1]; prev[1] = tok; ss.ple.table->prefetch_rows(rows16); }; pf(outv[(size_t) a_]); for (int i = 0; i < n_pf; ++i) pf(drafts[(size_t) i]); } return true; } #endif return mtp.draft_long(T_, outv.data(), p, a_, drafts.data(), err, dprob.data(), (float) o.spec_min_p, nullptr, gated_proposal ? &generation : nullptr); }; int win_cap = o.spec; // the widest window the VRAM allows (lowered on an out-of-memory capture, see below) while ((int64_t) produced.size() < max_new) { const Clock::time_point t0 = Clock::now(); bool dfr_lookup = false; int dfr_T = 0, dfr_match = 0; #if defined(STRATA_HAVE_DFLASH2) if (df2_deferred) { // the draft this round skipped for a long lookup match: the lookup if the policy takes it, else the draft now (same taps, same rows) df2_deferred = false; const int kd = sfx.propose(o.spec - 1, sbuf.data()); const int md = sfx.last_match(); const strata::spec::DraftPolicy::Pick pk = kd > 0 ? policy.choose(S_mtp, kd, md) : strata::spec::DraftPolicy::Pick{}; if (kd > 0 && pk.lookup) { dfr_lookup = true; dfr_T = pk.t; dfr_match = md; if (!df2.context(ver.tap_dev(), dfr_n, dfr_pos, err)) { std::fprintf(stderr, "strata generate: %s\n", err.c_str()); return 1; } } else { int32_t dd[strata::core::Dflash2Drafter::kDrafts]; float pp[strata::core::Dflash2Drafter::kDrafts]; if (!df2.draft(ver.tap_dev(), dfr_n, dfr_pos, dfr_anchor, dd, pp, err)) { std::fprintf(stderr, "strata generate: %s\n", err.c_str()); return 1; } for (size_t i = 0; i < drafts.size() && i < (size_t) strata::core::Dflash2Drafter::kDrafts; ++i) { drafts[i] = dd[i]; dprob[i] = pp[i]; } } } #endif retry_round: strata::core::progress_at("spec loop: choosing the window", (int64_t) produced.size()); int T = S_mtp; policy.set_context(p); bool from_sfx = false; int sfx_match = 0; if (gated_proposal) { source_policy.apply_costs(p); // held round times whose draws are all committed now if (!prepare_gated_window(proposal, generation, sfx, source_policy, o.suffix_draft > 0, first_window, (int) std::min(win_cap, o.max_context - p), S_mtp, (int) ver.vocab(), (float) o.spec_min_p, mtp.spec_q(), drafts.data(), dprob.data(), sbuf.data(), sfx_match, err)) { std::fprintf(stderr, "strata generate: %s\n", err.c_str()); return 1; } T = proposal.T; from_sfx = proposal.from_sfx; std::copy(dprob.begin(), dprob.begin() + (std::ptrdiff_t) o.spec, dwin.begin()); } else { { // the window rule of the round's ACTIVE source (spec/window_rule.hpp): the MTP chain's cost rule and probabilities do not // govern DFlash2's candidates, though the MTP may stay loaded beside it as the fallback (use_mtp) strata::spec::WindowRuleIn wr; wr.use_mtp = use_mtp; wr.draft_on = draft_on; wr.df2_active = spec_uses_df2; wr.spec_cost = spec_cost; wr.first_window = first_window; wr.chain_rows = chain_rows; wr.cap = S_mtp; wr.start = T; wr.spec_min_p = o.spec_min_p; wr.draft_conf = o.draft_conf; wr.dprob = dprob.data(); T = strata::spec::choose_window(wr); } if (first_window) T = 1; std::copy(dprob.begin(), dprob.begin() + (std::ptrdiff_t) o.spec, dwin.begin()); if (!t_cycle.empty() && !first_window) T = t_cycle[(size_t) (rounds % (int64_t) t_cycle.size())]; if (o.suffix_draft > 0 && !first_window) { const int k = sfx.propose(o.spec - 1, sbuf.data()); sfx_match = sfx.last_match(); // a probabilistic window must not condition the source on the draw: the policy copy fixed at the start chooses, and the // lookup is taken without asking whether the MTP's first guess agrees const bool probabilistic = use_mtp && !spec_uses_df2 && mtp.prob(); // DFlash2's candidates are not draws from the MTP's q if (k > 0 && (probabilistic || !draft_on || sbuf[0] == drafts[0])) { const strata::spec::DraftPolicy::Pick pk = probabilistic ? source_policy.choose(S_mtp, k, sfx_match) : policy.choose(T, k, sfx_match); if (pk.lookup) { T = pk.t; from_sfx = true; } } } } if (dfr_lookup) { // the lookup window chosen before the draft (the draft was skipped) sfx.propose(o.spec - 1, sbuf.data()); T = dfr_T; from_sfx = true; sfx_match = dfr_match; } // The window's rows sit at p .. p + T - 1, and past the context there is no cell to verify them in: near // its end the window takes only the rows that fit (the admission checked the prompt and max_new, which a // full window can overrun) const int room = (int) std::min(win_cap, o.max_context - p); T = std::min(T, room); // --lookup-chain: what followed an earlier occurrence of the context + the MTP's drafts, after them int chain_n = 0, cm = 0; if (o.lookup_chain > 0 && draft_on && !first_window && !from_sfx && T < room) { int csrc = -1; const int nt = chain_tail(sfx, drafts.data(), T - 1, ctail); chain_n = strata::spec::propose_from_sources(lookup_src, ctail.data(), nt, T - 1, std::min(o.lookup_chain, room - T), o.lookup_chain_min, cbuf.data(), &cm, &csrc); if (chain_n > 0 && std::getenv("STRATA_LOOKUP_CHAIN_FIXED") == nullptr) { double p_mtp = 1.0; for (int i = 0; i < T - 1; ++i) p_mtp *= dprob[(size_t) i]; chain_n = policy.chain(T, p_mtp, chain_n, cm); } } const int T_mtp = T; T += chain_n; const bool timed_round = !first_window; ++window_hist[(size_t) T]; if (p + T > o.max_context) { std::fprintf(stderr, "strata generate: ran out of context at position %lld\n", (long long) p); return 2; } window[0] = x; for (int i = 1; i < T; ++i) { const size_t at = produced.size() - 1 + (size_t) i; int32_t d = from_sfx ? sbuf[(size_t) i - 1] : draft_on ? drafts[(size_t) i - 1] : at < oracle.size() ? (int32_t) oracle[at] : 0; if (i >= T_mtp) d = cbuf[(size_t) (i - T_mtp)]; if (o.spec_corrupt > 0 && (++corrupt_counter % o.spec_corrupt) == 0) d = (d + 1) % (int32_t) n_vocab; window[(size_t) i] = d; } drive.d.layers = 0; drive.d.experts = 0; drive.d.failed = false; // #463: the previous adapt round's copies land first - with a non-blocking query, whether a swapped-in // expert ran on the GPU or the CPU (they round differently) depended on the copy's timing // (STRATA_ADAPT_NOWAIT=1: 0.1.37's non-blocking query, the A/B) if (adapt_nowait()) apply_pending(false); else if (pending.empty() || ++pending_age >= adapt_lag()) apply_pending(true); if (!drive.d.fetch_log.empty()) { // STRATA_ADAPT_FETCH_VERIFY: each admitted slot read back static int64_t checked = 0, bad = 0; cudaDeviceSynchronize(); for (const auto& [i, slot] : drive.d.fetch_log) { std::string verr; const int64_t l = i / g.n_expert; const bool same = host_res[(size_t) i] != slot || // evicted again since: nothing to check xcache.verify_slot(slot, srcp->blob_stable(l, i % g.n_expert), verr, (int64_t) strata::kernels::cpu::expert_layout().blob_bytes(l)); ++checked; if (!same) { ++bad; std::fprintf(stderr, "strata: FETCH VERIFY layer %lld expert %lld slot %d: %s\n", (long long) l, (long long) (i % g.n_expert), (int) slot, verr.c_str()); } } drive.d.fetch_log.clear(); if ((checked & 1023) < 64) std::fprintf(stderr, "strata: fetch verify: %lld admitted slots read back, %lld differ\n", (long long) checked, (long long) bad); } if (gated_proposal) ver.set_spec_proposal(proposal.n_q ? proposal.mu.data() : nullptr, proposal.n_q); // the MTP's q lists judge only candidates the MTP drew: DFlash2's are a deterministic pick (exact-match path) else if (strata::spec::mtp_q_applies(use_mtp, spec_uses_df2, use_mtp && mtp.prob(), from_sfx, first_window, T_mtp) && o.spec_corrupt <= 0) ver.set_spec_q(mtp.spec_q(), T_mtp - 1); const auto decode_pool_fn = use_mtp && mtp.prob() ? &drive_pool_multi_invariant : &drive_pool_multi; if (!ver.run(T, window.data(), p, decode_pool_fn, &drive, outv.data(), err)) { // The graph of a window size is captured the first time it is used, and the draft source took VRAM: when the capture runs // out of memory the window gets one row narrower (the widths below it are already captured) instead of the run failing. if (T > 2 && !first_window && !gated_proposal && err.find("out of memory") != std::string::npos) { win_cap = T - 1; --window_hist[(size_t) T]; std::fprintf(stderr, "strata generate: not enough VRAM left for a %d-token verify window: windows are %d tokens at most from here\n", T, win_cap); err.clear(); goto retry_round; } std::fprintf(stderr, "strata generate: %s\n", err.c_str()); return 1; } if (drive.d.failed) { std::fprintf(stderr, "strata generate: the expert pool failed at layer %lld expert %lld: %s\n", (long long) drive.d.fail_layer, (long long) drive.d.fail_expert, drive.d.fail ? drive.d.fail : "(no message)"); return 1; } if (hashes != nullptr) { // FNV-1a over the window's final residual rows (a test path: a plain copy) const size_t n_floats = (size_t) T * (size_t) (g.hc * g.n_embd); hash_rows.resize(n_floats); cudaMemcpy(hash_rows.data(), ver.final_R_all(), n_floats * sizeof(float), cudaMemcpyDeviceToHost); uint64_t h = 1469598103934665603ull; const auto* bytes = (const uint8_t*) hash_rows.data(); for (size_t i = 0; i < n_floats * sizeof(float); ++i) h = (h ^ bytes[i]) * 1099511628211ull; std::fprintf(hashes, "%lld %lld %d %016llx", (long long) rounds, (long long) p, T, (unsigned long long) h); for (int i = 0; i < T; ++i) std::fprintf(hashes, " %d", (int) outv[(size_t) i]); std::fprintf(hashes, "\n"); } if (!follow.empty()) { // the continuation stands in for the argmax const size_t k0 = produced.size(); for (int i = 0; i < T && k0 + (size_t) i < follow.size(); ++i) { fdiff[(size_t) i] = outv[(size_t) i] != (int32_t) follow[k0 + (size_t) i]; outv[(size_t) i] = (int32_t) follow[k0 + (size_t) i]; } } int a = 0; while (a < T - 1 && window[(size_t) a + 1] == outv[(size_t) a]) ++a; const bool initial_round = first_window; // a single-row window: no proposal to learn from if (first_window) { first_window = false; ttft_ms = std::chrono::duration(Clock::now() - t_start).count(); // Diagnostics: the first window runs the prompt's last token over the state the prompt path left // (keys, values, recurrent state), so its logits carry whatever that path did. A native pack never // runs the per-token loop --dump-logits reads; this is where prompt paths can be compared by output. if (const char* fl = std::getenv("STRATA_DUMP_FIRST_LOGITS")) { std::vector row((size_t) ver.vocab()); std::FILE* f = ver.copy_logits(0, row.data()) ? std::fopen(fl, "wb") : nullptr; if (f == nullptr || std::fwrite(row.data(), sizeof(float), row.size(), f) != row.size()) std::fprintf(stderr, "strata generate: STRATA_DUMP_FIRST_LOGITS: cannot write %s\n", fl); if (f) std::fclose(f); } } // plan v0.3 P6: the adaptive tier's host work (ranking, copy submission) runs on its own thread while the // GPU commits and drafts; it touches only the residency tables, which nothing reads until the next window std::thread adapt_thr; bool adapt_ok = true; if (!drive.d.usage.empty() && ((rounds + 1) % o.adapt_iv(rounds)) == 0) adapt_thr = std::thread([&] { strata::platform::name_this_thread("strata-adapt"); strata::aux_cpus::pin_current_thread(); adapt_ok = adapt(); }); strata::core::progress_at("spec loop: commit", (int64_t) T); if (!ver.commit(a + 1, err)) { if (adapt_thr.joinable()) adapt_thr.join(); std::fprintf(stderr, "strata generate: %s\n", err.c_str()); return 1; } ++rounds; drafts_total += T - 1; drafts_ok += a; ++accepted_hist[(size_t) a]; if (from_sfx) { ++sfx_windows; sfx_drafts += T - 1; sfx_ok += a; } if (chain_n > 0) { ++chain_windows; chain_drafts += chain_n; chain_ok += std::max(0, a - (T_mtp - 1)); } bool eos = false; for (int i = 0; i <= a && (int64_t) produced.size() < max_new && !eos; ++i) { produced.push_back(outv[(size_t) i]); if (sfx_on) sfx.append(outv[(size_t) i]); if (o.lookup_chain > 0) extra_sources_append(&outv[(size_t) i], 1); eos = o.stop_eos && std::find(o.eos_ids.begin(), o.eos_ids.end(), (int64_t) outv[(size_t) i]) != o.eos_ids.end(); if (!follow.empty()) { follow_differ += fdiff[(size_t) i]; ++follow_emitted; } } if (eos) { if (adapt_thr.joinable()) adapt_thr.join(); total_ms += std::chrono::duration(Clock::now() - t0).count(); break; } generation = {}; const GatedDraftLimit draft_limit(mtp, gated_proposal, S_mtp, p + a + 1, o.max_context); const bool drafted = !draft_on || (int64_t) produced.size() >= max_new || draft_next(T, a); if (adapt_thr.joinable()) adapt_thr.join(); if (!adapt_ok) return 1; if (!drafted) { std::fprintf(stderr, "strata generate: %s\n", err.c_str()); return 1; } x = outv[(size_t) a]; p += a + 1; const double round_ms = std::chrono::duration(Clock::now() - t0).count(); total_ms += round_ms; if (gated_proposal && !initial_round) source_policy.observe_committed(from_sfx, from_sfx ? T : std::min(S_mtp, room), a, sfx_match); if (gated_proposal && !initial_round && timed_round) // p has advanced: the window was p - a - 1 .. source_policy.defer_cost(std::max(p - a - 2 + T, p + S_mtp), T, round_ms); if (spec_trace != nullptr && timed_round) { std::fprintf(spec_trace, "%d %d %d %.3f", T, a, from_sfx ? 1 : 0, round_ms); for (int i = 0; i < o.spec - 1; ++i) std::fprintf(spec_trace, " %.4f", (double) dwin[(size_t) i]); std::fprintf(spec_trace, "\n"); } if (!t_cycle.empty() && timed_round && T <= o.spec && t_cycle_seen[(size_t) T]++ > 0) { t_cycle_ms[(size_t) T] += round_ms; ++t_cycle_n[(size_t) T]; } if (spec_cost && use_mtp && timed_round && !from_sfx) policy.observe_probs(dwin.data(), T_mtp - 1, a); if (timed_round && chain_n == 0) policy.observe(from_sfx, T, a, sfx_match, round_ms); else if (timed_round) policy.observe_chain(T_mtp, chain_n, a, cm, round_ms); if (rounds % 64 == 0) std::fprintf(stderr, "strata generate: position %lld, %lld tokens, %lld rounds\n", (long long) p, (long long) produced.size(), (long long) rounds); } // the last commit (set_commit_async) before anything reads the session again if (!ver.wait_commit(err)) { std::fprintf(stderr, "strata generate: %s\n", err.c_str()); return 1; } if (hashes != nullptr) std::fclose(hashes); if (spec_trace != nullptr) std::fclose(spec_trace); std::printf("%-24s %lld rounds of %d, drafts accepted %lld of %lld (%.3f), %.2f tokens per round\n", "speculation", (long long) rounds, o.spec, (long long) drafts_ok, (long long) drafts_total, drafts_total > 0 ? (double) drafts_ok / (double) drafts_total : 0.0, rounds > 0 ? (double) (drafts_ok + rounds) / (double) rounds : 0.0); if (!follow.empty()) std::printf("%-24s %lld of %lld emitted tokens differ from the argmax\n", "follow", (long long) follow_differ, (long long) follow_emitted); if (o.spec_min_p > 0.0 || o.draft_conf > 0.0 || spec_cost) { // (any rule that sets the width) std::printf("%-24s", "window sizes"); for (size_t i = 1; i < window_hist.size(); ++i) std::printf(" T%zu:%lld", i, (long long) window_hist[i]); std::printf(" (min draft probability %.2f, draft-conf %.2f, cost rule %d)\n", o.spec_min_p, o.draft_conf, spec_cost ? 1 : 0); } if (ver.spec_windows > 0) // STRATA_SPEC_PROB: windows judged against the MTP's q lists (only an MTP-drawn window should be) std::printf("%-24s %lld windows judged against q lists (source: %s)\n", "probabilistic accept", (long long) ver.spec_windows, spec_uses_df2 ? "DFlash2" : "MTP"); if (o.suffix_draft > 0) std::printf("%-24s %lld windows, drafts accepted %lld of %lld\n", "suffix drafts", (long long) sfx_windows, (long long) sfx_ok, (long long) sfx_drafts); if (o.lookup_chain > 0) std::printf("%-24s %lld windows, chained drafts accepted %lld of %lld\n", "lookup chain", (long long) chain_windows, (long long) chain_ok, (long long) chain_drafts); if (spec_cost) std::printf("%-24s %s\n", "spec cost table", policy.cost_table_text().c_str()); if (!t_cycle.empty()) { std::printf("%-24s", "window cost (ms/round)"); for (size_t i = 1; i < t_cycle_ms.size(); ++i) if (t_cycle_n[i] > 0) std::printf(" T%zu:%.2f(n=%lld)", i, t_cycle_ms[i] / (double) t_cycle_n[i], (long long) t_cycle_n[i]); std::printf("\n"); { // STRATA_VERIFY_PROFILE / STRATA_ROUTE_STATS: the same split per window width (bench only) const std::string pt = ver.profile_by_t_report(); if (!pt.empty()) std::printf("GPU stages per window width (ms):\n%s", pt.c_str()); const std::string rs = ver.route_stats_report(); if (!rs.empty()) std::printf("routed experts per window width:\n%s", rs.c_str()); } } std::printf("%-24s", "accepted per round"); for (size_t i = 0; i < accepted_hist.size(); ++i) std::printf(" %zu:%lld", i, (long long) accepted_hist[i]); std::printf("\n"); if (rounds > 0) std::printf("%-24s wait for rings %.3f pool %.3f host %.3f commit %.3f ms/round; CPU experts %.2f " "distinct / %.2f routed per layer\n", "verify window", ver.ms_wait / rounds, ver.ms_pool / rounds, ver.ms_host / rounds, ver.ms_commit / rounds, (double) (drive.d.multi_misses - misses0) / (double) (rounds * g.n_layers), (double) (drive.d.multi_entries - entries0) / (double) (rounds * g.n_layers)); if (rounds > 0) std::printf("%-24s gate/up %.3f quantize %.3f down %.3f ms/round; %.1f GB/s over the rows phases; " "CPU pool call %.3f ms/round", "pool multi", pool.ms_multi_gu / rounds, pool.ms_multi_q / rounds, pool.ms_multi_down / rounds, (double) pool.multi_bytes / 1e6 / std::max(1e-9, pool.ms_multi_gu + pool.ms_multi_down), (drive.cpu_ms - pool_ms0) / rounds); if (rounds > 0 && pool.numa_slices() == 2) // STRATA_NUMA_SPLIT: each slice's drain, publish to its last task std::printf("; numa slices: s0 %.3f ms s1 %.3f ms", pool.numa_slice_ms(0) / rounds, pool.numa_slice_ms(1) / rounds); if (rounds > 0) std::printf("\n"); if (rounds > 0) std::printf("%-24s plan %.3f activation quantize %.3f jobs %.3f run %.3f ms/round\n", "dispatch", drive.d.ms_plan / rounds, drive.d.ms_actq / rounds, drive.d.ms_jobs / rounds, drive.d.ms_run / rounds); if (rounds > 0 && !drive.d.usage.empty()) std::printf("%-24s %lld experts swapped into the VRAM tier (every %d rounds, %.3f ms/round)\n", "adaptive tier", (long long) swaps_total, o.adapt_every, ms_adapt / rounds); if (rounds > 0 && drive.d.fetch_admit > 0) std::printf("%-24s %lld experts admitted from the PCIe share (%.2f a round)\n", "fetch admission", (long long) drive.d.fetch_admitted, (double) drive.d.fetch_admitted / (double) rounds); if (res_checking) std::printf("%-24s %lld windows, %lld with mismatches (%lld entries), %lld layer-windows with CPU experts and " "no activation published\n", "residency check", (long long) res_windows, (long long) res_bad_windows, (long long) res_bad, (long long) drive.d.stale_x); if (src.complement_ready()) std::printf("%-24s %.2f GiB of experts in RAM, %lld exchanged with the VRAM tier, %lld blob reads from " "the file\n", "resident RAM", (double) src.resident_bytes() / 1073741824.0, (long long) src.exchanges(), (long long) src.file_reads()); if (srcp == &src) { // CS-T: the RAM and file tiers (the GPU cache's share is the hit rate above) const double fms = src.file_ms() - fms0, fmb = (double) (src.file_blob_bytes() - fbytes0) / 1e6; std::printf("%-24s decode: RAM %lld blobs, files %lld blobs, %.1f MB read from the files (%.2f MB/round, " "%.1f ms/round of reading, %.2f GB/s per reading thread)%s; prompt copies %.1f MB\n", "expert tiers", (long long) (src.ram_reads() - ram0), (long long) (src.file_reads() - files0), fmb, rounds > 0 ? fmb / rounds : 0.0, rounds > 0 ? fms / rounds : 0.0, fms > 0 ? fmb / fms : 0.0, src.gguf_mode() ? " (the GGUF in place)" : "", (double) (fall0 - fbytes0) / 1e6); if (src.io_stats()) { const strata::core::FileExpertSource::IoCounters ic = src.io_counters(); std::printf("%-24s file reads: page cache held %.1f MB, not %.1f MB (mincore at the read); io prefetch %s: " "%llu read ahead, %llu used, %llu unused, %llu skipped (cached), %llu dropped; pread %.1f MB in %llu calls " "(%.2f ms each); decode waited %.1f ms/round in the fetches\n", "io path", (double) ic.cached_bytes / 1e6, (double) ic.uncached_bytes / 1e6, src.io_prefetch() ? "on" : "off", (unsigned long long) ic.pf_read_blobs, (unsigned long long) ic.pf_used, (unsigned long long) ic.pf_unused, (unsigned long long) ic.pf_resident_skips, (unsigned long long) ic.pf_dropped, (double) ic.pread_bytes / 1e6, (unsigned long long) ic.pread_n, ic.pread_n > 0 ? (double) ic.pread_us / 1e3 / (double) ic.pread_n : 0.0, rounds > 0 ? (double) ic.crit_us / 1e3 / rounds : 0.0); } if (drive.d.lookahead != nullptr) std::printf("%-24s %lld experts warmed, %lld of the file tier's %lld blob reads had been warmed (%.1f%%); " "predictor %.1f ms/round on its thread, %lld layers skipped (still busy)\n", "routing prefetch", (long long) src.warmed(), (long long) src.warmed_hits(), (long long) (src.file_reads() - files0), src.file_reads() > files0 ? 100.0 * (double) src.warmed_hits() / (double) (src.file_reads() - files0) : 0.0, rounds > 0 ? drive.d.lookahead->busy_ms() / rounds : 0.0, (long long) drive.d.lookahead->skipped()); } if (rounds > 0 && drive.d.pcie_num > 0) std::printf("%-24s %.2f distinct experts per layer read over PCIe (share %d/256 of the misses)\n", "pcie experts", (double) (drive.d.pcie_experts - pcie0) / (double) (rounds * g.n_layers), drive.d.pcie_num); if (rounds > 0 && ver.pcie_balance_on()) { const strata::core::PcieModel& pm = drive.d.pcie_model; std::printf("%-24s CPU %.0f us + %.0f an expert + %.0f a PCIe one, GPU %.0f us + %.0f a PCIe expert (the " "PCIe count per layer from these)\n", "pcie model", 1000 * pm.a, 1000 * pm.c, 1000 * pm.d, 1000 * pm.g0, 1000 * pm.g); } (void) pool_ms0; #if defined(STRATA_HAVE_DFLASH2) if (use_df2 && df2.rounds > 0) std::printf("%-24s %.3f ms/round drafting (%lld rounds, GPU %.3f), %.0f MiB of VRAM\n", "dflash2", df2.ms_draft / (double) df2.rounds, (long long) df2.rounds, df2.ms_gpu / (double) df2.rounds, (double) df2.vram_bytes() / 1048576.0); else #endif if (use_mtp && rounds > 0) std::printf("%-24s %.3f ms/round drafting (%lld rounds), MTP prompt %.1f ms, %.0f MiB of VRAM\n", "mtp", mtp.ms_draft / (double) mtp.rounds, (long long) mtp.rounds, mtp.ms_prefill, (double) mtp.vram_bytes() / 1048576.0); } if (dump != nullptr && std::fclose(dump) != 0) { std::fprintf(stderr, "strata generate: cannot finish logits dump\n"); return 1; } if (layer_dump != nullptr) { std::fclose(layer_dump); cudaFreeHost(layer_stage); std::printf("%-24s %s (%lld layers + the input x %d streams x %lld per position)\n", "layers dumped", o.dump_layers.c_str(), (long long) g.n_layers, (int) g.hc, (long long) g.n_embd); } if (half_dump != nullptr) { std::fclose(half_dump); cudaFreeHost(half_stage); std::printf("%-24s %s (%lld layers x %llu per position)\n", "halves dumped", o.dump_halves.c_str(), (long long) g.n_layers, (unsigned long long) half_stride); } if (routing != nullptr) { std::fclose(routing); drive.routing = nullptr; std::printf("%-24s %s (%lld records of layer, k, ids, weights)\n", "routing dumped", o.dump_routing.c_str(), (long long) drive.calls); } if (o.stage_timing) strata::core::stage_timing_report(g.n_layers); const int64_t decoded = (int64_t) produced.size(); std::printf("prompt :"); for (int64_t t : o.tokens) std::printf(" %lld", (long long) t); std::printf("\noutput :"); for (int64_t t : produced) std::printf(" %lld", (long long) t); std::printf("\n"); const double decode_ms = decoded > 0 ? total_ms / (double) decoded : 0.0; std::printf("%-24s %lld tokens in %.1f ms -> %.2f tok/s\n", "decode", (long long) decoded, total_ms, decode_ms > 0.0 ? 1000.0 / decode_ms : 0.0); if (n_prompt > 1) std::printf("%-24s %lld tokens in %.1f ms -> %.2f tok/s (time to first token %.1f ms)\n", "prefill", (long long) (n_prompt - 1), prefill_ms, prefill_ms > 0 ? 1000.0 * (double) (n_prompt - 1) / prefill_ms : 0.0, ttft_ms); if (!o.dump_mixed.empty()) { std::vector mx((size_t) g.n_embd); if (cudaMemcpy(mx.data(), ss.block.mixed, mx.size() * sizeof(float), cudaMemcpyDeviceToHost) != cudaSuccess) { std::fprintf(stderr, "strata generate: reading mixed back failed\n"); return 1; } std::FILE* mf = std::fopen(o.dump_mixed.c_str(), "wb"); if (mf == nullptr) { std::fprintf(stderr, "strata generate: cannot write %s\n", o.dump_mixed.c_str()); return 1; } std::fwrite(mx.data(), sizeof(float), mx.size(), mf); std::fclose(mf); double s2 = 0, mag = 0; for (float v : mx) { s2 += (double) v * (double) v; mag += std::fabs((double) v); } std::printf("%-24s %s (n_embd %lld, rms %.5g, mean|.| %.5g)\n", "mixed dumped", o.dump_mixed.c_str(), (long long) g.n_embd, std::sqrt(s2 / (double) mx.size()), mag / (double) mx.size()); } // ---- the residual, for bisecting the head against the layers (see `dump_residual`'s note) if (!o.dump_residual.empty()) { std::vector R((size_t) g.hc * g.n_embd); if (cudaMemcpy(R.data(), ss.R, R.size() * sizeof(float), cudaMemcpyDeviceToHost) != cudaSuccess) { std::fprintf(stderr, "strata generate: reading R back failed\n"); return 1; } std::FILE* rf = std::fopen(o.dump_residual.c_str(), "wb"); if (rf == nullptr) { std::fprintf(stderr, "strata generate: cannot write %s\n", o.dump_residual.c_str()); return 1; } const int32_t hdr[2] = {(int32_t) g.hc, (int32_t) g.n_embd}; std::fwrite(hdr, sizeof hdr, 1, rf); std::fwrite(R.data(), sizeof(float), R.size(), rf); std::fclose(rf); double mag = 0, mx = 0; int bad = 0; for (float v : R) { if (!std::isfinite(v)) ++bad; else { mag += std::fabs((double) v); mx = std::max(mx, (double) std::fabs((double) v)); } } std::printf("%-24s %s (%d x %lld, nonfinite %d, mean|.| %.4g, max|.| %.4g)\n", "residual dumped", o.dump_residual.c_str(), (int) g.hc, (long long) g.n_embd, bad, mag / (double) R.size(), mx); } if (o.stats) { std::printf("%-24s %.3f ms/token (WALL CLOCK: embed, layers, head, sample)\n", " per token", decode_ms); // **THE PER-TOKEN HOST TERM, WHICH `--gpu-only-full` CANNOT SEE.** That measurement never enters the // token loop, so it excludes all six of these. On the 78-token fixture + 200 generated tokens the six // sum to ~9 ms of non-layer work against ~1.5 ms of actual head GPU work - 16% of the token, and it is // not the pool. if (phase_tokens > 0) { const double pt = (double) phase_tokens; std::printf("%-24s PLE %.3f embed %.3f LAYERS %.3f head %.3f readback %.3f sample %.3f " "(sum %.3f of %.3f ms)\n", " token host phases", ms_ple / pt, ms_embed / pt, ms_layers / pt, ms_head / pt, ms_readback / pt, ms_sample / pt, (ms_ple + ms_embed + ms_layers + ms_head + ms_readback + ms_sample) / pt, decode_ms); } if (const std::string io = ple_table.io_report(); !io.empty()) std::printf(" %s\n", io.c_str()); // **THE DENOMINATOR IS THE POSITIONS THE POOL ACTUALLY RAN ON, NOT THE DECODED TOKENS (A6).** // `drive_pool` is called once per layer per position and PREFILL runs the loop too, so accumulating // `cpu_ms` over prefill and then dividing by `decoded` inflates this figure. `drive.calls / n_layers` // is the number of positions - the same correction the ring counters below already received, which is // why they print "of 192" rather than "240 of 192". const double pool_positions = g.n_layers > 0 ? (double) drive.calls / (double) g.n_layers : 0.0; std::printf("%-24s %.3f ms/token over %lld layers (%.0f positions, %lld dispatches)\n", " the CPU expert pool", pool_positions > 0.0 ? drive.cpu_ms / pool_positions : 0.0, (long long) g.n_layers, pool_positions, (long long) drive.calls); // **AND WHERE INSIDE `run()` IT WENT.** Three phases per layer and they were one number, which cannot // tell a pool that is slow at the WORK from one that is slow at the SYNCHRONISATION - opposite fixes. // Wait-for-park is expected to be ~0 (the workers re-parked at the end of the previous layer); the // question is whether the time is in the drain or in the re-park barrier. if (pool_positions > 0.0) { double wp = 0, dr = 0, rp = 0; pool.phase_ms(wp, dr, rp); const double per = pool_positions; std::printf("%-24s wait-park %.3f drain %.3f re-park %.3f ms/token\n", " pool phases", wp / per, dr / per, rp / per); } std::printf("%-24s %lld blobs read\n", " expert blobs", (long long) srcp->reads()); for (int r = 0; r < 3; ++r) if (o.expert_cache_remote[(size_t) r] > 0) std::printf(" CUDA%d experts %lld routed entries computed\n", r + 1, (long long) remote_experts[(size_t) r].computed()); // ---- **R4's DISPATCH MEASUREMENT: h, ON THE ENGINE'S OWN ROUTING.** No offline trace, no corpus // question, no k-fold - these are the ids the router actually produced on this run. Reported as // hits/lookups so it can be read directly as the h the cache would deliver, and alongside `refused` // so a full cache is visible rather than silently capping the rate. if (o.expert_cache > 0) { const int64_t look = drive.d.cache_hits + drive.d.cache_admitted + drive.d.cache_refused; const int64_t hl = drive.d.hit_ready + drive.d.hit_late; std::printf("%-24s %lld of %lld layers the hit work was DONE when the pool returned\n", " R4 overlap", (long long) drive.d.hit_ready, (long long) hl); std::printf("%-24s %lld of %lld = %.4f (%lld admitted, %lld refused, cache %.4f%% full)\n", " R4 expert-cache hits", (long long) drive.d.cache_hits, (long long) look, look > 0 ? (double) drive.d.cache_hits / (double) look : 0.0, (long long) drive.d.cache_admitted, (long long) drive.d.cache_refused, 100.0 * (double) (drive.d.cache_admitted + drive.d.cache_hits > 0 ? (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", " token graph", tgraph.ms_wait / per, tgraph.ms_pool / per, (long long) tgraph.flushes, (long long) tgraph.calls); } if (gr.captured && gr.calls_total > 0) { // The counters are CUMULATIVE over every `session_loop` call, and PREFILL runs the loop too - so // the denominator is the number of positions, not the number of generated tokens. Dividing by // `n_layers * decoded` printed "240 of 192", which is a reporting bug that looks like a ring // firing more often than it should. const int64_t positions = gr.calls_total; std::printf("%-24s %lld of %lld over %lld positions\n", " rings seen MID-GRAPH", (long long) gr.rings_mid_graph, (long long) (g.n_layers * positions), (long long) positions); std::printf("%-24s %.3f ms of a %.3f ms layer\n", " ring latency", gr.ms_to_ring / (double) (g.n_layers * positions), decode_ms / (double) g.n_layers); // **THE ROUND TRIP, SPLIT AT THE RING.** `ring latency` is the first half and stops when the ring // is seen; this is the second half - the driver calls after it, during which the GPU is IDLE // because `post[l]` has not been launched yet. `--no-pool` is the arm that isolates it: 38.73 // ms/token against a 26.32 ms pure-GPU floor is 12.4 ms of round trip with no expert work at all. // // Same denominator as the pool line above (the positions the loop actually ran on), so the two can // be added without one of them being inflated by prefill. const double perlap = (double) (g.n_layers * positions); std::printf("%-24s %.3f ms/token over %.0f positions (%.3f ms/layer, after the ring)\n", " host after ring", pool_positions > 0.0 ? gr.ms_host / pool_positions : 0.0, pool_positions, gr.ms_host / perlap); } } if (dump != nullptr) std::printf("%-24s %s\n", "logits dumped", o.dump_logits.c_str()); strata::core::session_graphs_free(gr); strata::core::doorbell_free(db); cudaFree(d_next); cudaFree(d_logits); cudaFree(d_emb); cudaFree(d_parts); cudaFree(sbuf); cudaFree(arena); return 0; } #if defined(STRATA_USE_HIP) && defined(_WIN32) // #3431: no stack, heap block or mapping the engine uses may lie under the GPU alias of a pinned expert-arena range (see // claim_alias in src/core/pinned.cu: such a range and the ones after it are left unpinned, which is right but slower). The // aliases sit low in the address space (seen between 8 and 300 GiB), where Windows also places stacks and heaps, and in about one // start in ten an alias covered the engine thread's stack. So the free address space below 1 TiB is reserved here, for the life // of the process (address space only, nothing committed), and the engine runs on a new thread: its stack, and everything the // process allocates later, is placed above. The aliases are not moved by it; one inside the reservation is clear. What existed // before main stays low: this first thread's stack (it only waits from here on, so an alias may cover it) and a few blocks of the // process, which claim_alias still checks. STRATA_STACK_ISOLATE=0 runs the engine on the first thread with nothing reserved. namespace { struct EngineArgs { int argc; char** argv; int rc; }; DWORD WINAPI engine_thread(LPVOID p) { EngineArgs* a = static_cast(p); a->rc = engine_main(a->argc, a->argv); return 0; } // every free piece below `limit` that a reservation can start in (64 KiB-aligned), reserved; the start of each piece std::vector reserve_low_address_space(uint64_t limit) { std::vector held; SYSTEM_INFO si; GetSystemInfo(&si); const uint64_t gran = si.dwAllocationGranularity; uint64_t at = (uint64_t) si.lpMinimumApplicationAddress; MEMORY_BASIC_INFORMATION mbi; while (at < limit && VirtualQuery((void*) at, &mbi, sizeof mbi) == sizeof mbi) { const uint64_t end = (uint64_t) mbi.BaseAddress + mbi.RegionSize; if (mbi.State == MEM_FREE) { const uint64_t b = (at + gran - 1) & ~(gran - 1), e = std::min(end, limit); if (b < e) { if (VirtualAlloc((void*) b, (SIZE_T) (e - b), MEM_RESERVE, PAGE_NOACCESS) != nullptr) held.push_back(b); } } if (end <= at) break; at = end; } return held; } } // namespace int main(int argc, char** argv) { const char* iso = std::getenv("STRATA_STACK_ISOLATE"); if (iso == nullptr || iso[0] != '0') { ULONG_PTR lo = 0, hi = 0; GetCurrentThreadStackLimits(&lo, &hi); strata::core::set_idle_thread_stack(lo, hi); strata::core::set_held_address_space(reserve_low_address_space(1ull << 40)); EngineArgs a{argc, argv, 1}; HANDLE h = CreateThread(nullptr, 0, engine_thread, &a, 0, nullptr); // 0: the exe's own stack size, as the first thread's if (h != nullptr) { WaitForSingleObject(h, INFINITE); CloseHandle(h); return a.rc; } strata::core::set_idle_thread_stack(0, 0); // the engine runs on this thread after all } return engine_main(argc, argv); } #endif