diff --git a/CMakeLists.txt b/CMakeLists.txt index 24e472b8..cbe1c07a 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -98,6 +98,9 @@ if(STRATA_BUILD_CONVERSATION_TESTS) add_executable(conversation_cache_test src/core/conversation_cache_test.cpp) target_include_directories(conversation_cache_test PRIVATE include) add_test(NAME conversation_cache_test COMMAND conversation_cache_test) + add_executable(conversation_split_failure_test src/core/conversation_split_failure_test.cpp) + target_include_directories(conversation_split_failure_test PRIVATE include) + add_test(NAME conversation_split_failure_test COMMAND conversation_split_failure_test) add_executable(conversation_memory_test src/core/conversation_memory_test.cpp src/core/conversation_memory.cpp) target_include_directories(conversation_memory_test PRIVATE include) add_test(NAME conversation_memory_test COMMAND conversation_memory_test) diff --git a/docs/MULTI_GPU.md b/docs/MULTI_GPU.md index 1270125b..5c128232 100644 --- a/docs/MULTI_GPU.md +++ b/docs/MULTI_GPU.md @@ -102,6 +102,29 @@ it goes). A card holding more experts can change which experts run on the GPU, so the output can differ slightly from a run without it. +**The resident RAM mode works on a split** (`--resident-experts`, the low-RAM mode). The RAM copy of the experts +leaves out the ones every card's cache holds, not only the first card's, and when the rest does not fit whole it keeps +the hottest by the expert profile over all the layers. An adaptive swap copies the evicted expert back into RAM from +the card that owns its layer. Before, `--resident-experts` with a split ran as `--mmap-experts`, and setup recommended +one card in the low-RAM mode; with an engine that has it (`RESIDENT_SPLIT_ENGINE` in setup.py), setup keeps the cards +together and the experts no card holds in RAM. Swift 1.5 IQ3_XXS at +160K (q4_0 KV, `--prefill 4096`, `--spec 4` with the stock draft layer), RTX 4060 Ti (layers 0-19) + RTX 5080 (20-47), +i9-14900KF, 32 GB of RAM, Windows 11, four greedy prompts at a time, decode tok/s: + +| | first four prompts | after three more rounds | +|---|---|---| +| 5080 alone, `--resident-experts` | 25 | 29 | +| split, `--mmap-experts` (what `--resident-experts` became on a split) | 32 | 64 | +| split, `--resident-experts` (22 GiB of experts locked in RAM) | 71 | 69 | + +The split with `--mmap-experts` catches up once the OS file cache holds the experts, on a PC with nothing else +running; the resident copy is there from the first request and stays locked when other programs need the RAM. With +`--pcie-frac 0 --adapt-every 0` the split's greedy output is the same with either mode. + +**A separate VRAM reserve for the later cards:** `--vram-reserve-later-mib N` (default: `--vram-reserve-mib`'s value). +The card that drives the monitors needs more headroom than one that drives none; with the display on the last card, +`--vram-reserve-mib 300 --vram-reserve-later-mib 1800` gives the first card's cache that VRAM. + **auto** tries every placement (all of them for two or three cards; proportional to the free VRAM beyond that) and keeps the one whose caches would hold the most of the expert profile, hottest pairs weighted most; ties go to the placement that leaves the fullest card the most room. The startup log prints the choice: diff --git a/include/strata/core/conversation_cache.hpp b/include/strata/core/conversation_cache.hpp index b105deb6..c28ae01f 100644 --- a/include/strata/core/conversation_cache.hpp +++ b/include/strata/core/conversation_cache.hpp @@ -79,17 +79,39 @@ inline ConversationCheckpointSplit conversation_checkpoints_split(std::vector exec_bm_, commit_bm_; ///< key: batch_key(rows, S, hand-off base) int last_rows_[8] = {}; ///< the slots of the last batch window's rows + uint64_t bkey(const int* rows, int S, int hbase) const { // #871: the doorbell variant has its own graphs + return batch_key(rows, S, hbase) | (ar_off_ ? (1ull << 63) : 0ull); + } static uint64_t batch_key(const int* rows, int S, int hbase) { uint64_t k = (uint64_t) hbase << 40 | (uint64_t) S << 32; for (int t = 0; t < S; ++t) k |= (uint64_t) (rows[t] & 15) << (4 * t); @@ -256,8 +259,16 @@ private: int device_ = -1; ///< the device `init` ran on: run/commit switch to it (layer split) std::atomic released_{false}; ///< #267: release_gpu_waits ran (maybe on the watchdog thread): no more windows bool all_resident_ = false; ///< 100% of experts in [lb_, le_) resident in VRAM: zero-doorbell graph + /// #871: the zero-doorbell graph plans from the device residency table alone, so it is only right while every + /// expert of the stage is in VRAM. A prompt loan, a VRAM shrink or an adaptive swap marks some -1 for a while: + /// every window then runs the doorbell graph (exec_nr_ / the batch key's top bit), the same as a stage that never + /// was all-resident. refresh_ar() looks at the host table before each window. + bool ar_off_ = false; + bool ar_on() const { return all_resident_ && !ar_off_; } + void refresh_ar(); + uint32_t* h_plan_err_ = nullptr; uint32_t* m_plan_err_ = nullptr; // set by resident_plan on a -1 (all-resident graph) + const int32_t* h_res_ = nullptr; ///< the host residency table (VerifyHits::h_res) bool device_plan_ = false; ///< E-6: resident-only layers planned on the device (STRATA_VERIFY_DEVICE_PLAN) - bool resident_ = false; ///< STRATA_VERIFY_RESIDENT: every expert resident, no host step per layer uint32_t* skip_ = nullptr; ///< E-6: per group, the ring whose plan the device built (0: the host's) unsigned* qcnt_ = nullptr; ///< S26 STRATA_QFUSE: the HC read's q8_1 group counters (n_embd / 32) unsigned long long* slot_off_d_ = nullptr; ///< E-6: the slot offsets on the device @@ -302,6 +313,7 @@ private: cudaStream_t sh_cs_ = nullptr; cudaEvent_t ev_fork_ = nullptr, ev_join_ = nullptr; cudaGraphExec_t exec_[9] = {}; + cudaGraphExec_t exec_nr_[9] = {}; // #871: the doorbell variant of a stage that is all-resident otherwise cudaGraphExec_t commit_exec_ = nullptr; // mapped staging (host pointer, device alias) diff --git a/include/strata/kernels/verify_kernels.hpp b/include/strata/kernels/verify_kernels.hpp index 11f31b61..8c80bafa 100644 --- a/include/strata/kernels/verify_kernels.hpp +++ b/include/strata/kernels/verify_kernels.hpp @@ -47,9 +47,11 @@ void gpu_stamp(unsigned long long* buf, int i, void* stream); /// One group's plan, built on the device when every routed expert of its n*k entries is resident: the host pool's /// layout (counts | start | dst | tok | pad | ptr | ptr2 | start2, `capx` entries) and order (distinct experts in /// routing order, their entries ascending), no PCIe groups. *skip = ring when it did, else 0. +/// #871: without `skip` (the all-resident graph) an entry whose expert is not in VRAM cannot be planned: the plan is +/// left empty and *plan_err (mapped host memory) is set to 1, so the host sees it instead of running a stale plan. void resident_plan(const int32_t* ids, int n_entries, int k, const int32_t* res_layer, int n_expert, const uint8_t* cache_base, const unsigned long long* slot_off, long long blob, int32_t* plan, - long long capx, uint32_t* skip, uint32_t ring, void* stream); + long long capx, uint32_t* skip, uint32_t ring, void* stream, uint32_t* plan_err = nullptr); /// wait_flag_ge that also returns when *skip == value (device memory). void wait_flag_ge_or(const uint32_t* flag, uint32_t value, const uint32_t* skip, void* stream); /// copy_i32_from_mapped unless *skip == value. diff --git a/serve/server.py b/serve/server.py index 9e669827..bfc2a4f2 100644 --- a/serve/server.py +++ b/serve/server.py @@ -743,6 +743,11 @@ class StrataEngine: if len(f) >= 3 and f[1].isdigit() and f[2].isdigit(): self.progress = (int(f[1]), int(f[2])) self.prefill_tok_s_mean = float(f[4]) if len(f) >= 5 else None + if not stopped and cancel.is_set(): + # #879: a Stop during the prompt read went out only after the first token (or after 10 s of + # silence, which a stream of PP lines never allows): the engine read the whole prompt first + self._send("STOP") + stopped = True yield None elif line.startswith("DONE"): self._parse_done(line) diff --git a/serve/test_control_cancel.py b/serve/test_control_cancel.py new file mode 100644 index 00000000..2f6b3540 --- /dev/null +++ b/serve/test_control_cancel.py @@ -0,0 +1,50 @@ +"""#879: a Stop that arrives while the engine reads the prompt (PP lines, no tokens yet) is sent at once, not after the +first token.""" +import os +import queue +import sys +import threading +import unittest + +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + +from serve import server # noqa: E402 + + +class ControlCancelTest(unittest.TestCase): + def _engine(self, lines): + eng = object.__new__(server.StrataEngine) + eng.lines = queue.Queue() + for l in lines: + eng.lines.put(l) + eng.sent = [] + eng._send = eng.sent.append + eng._ctl_mode = "solo" + eng._ctl_result = None + eng.progress = None + eng.prefill_tok_s_mean = None + eng._last_done = None + eng._parse_done = lambda line: None + return eng + + def test_stop_during_prompt_read(self): + cancel = threading.Event() + eng = self._engine(["PP 256 4096 1 100.0", "PP 512 4096 2 100.0", "PP 768 4096 3 100.0", "DONE 0"]) + gen = eng._control(cancel, lambda t: None) + self.assertIsNone(next(gen)) # first PP line, nothing cancelled yet + self.assertEqual(eng.sent, []) + cancel.set() + self.assertIsNone(next(gen)) # the next PP line: STOP goes out now + self.assertEqual(eng.sent, ["STOP"]) + self.assertIsNone(next(gen)) + self.assertEqual(eng.sent, ["STOP"]) # once + + def test_no_stop_without_cancel(self): + eng = self._engine(["PP 256 4096 1 100.0", "DONE 0"]) + for _ in eng._control(threading.Event(), lambda t: None): + pass + self.assertEqual(eng.sent, []) + + +if __name__ == "__main__": + unittest.main() diff --git a/setup.py b/setup.py index 80d1fba5..1368f940 100644 --- a/setup.py +++ b/setup.py @@ -802,9 +802,10 @@ def split_mmap(cfg: dict) -> bool: """#364 #384: the low-RAM mode's resident variant (--resident-experts) has no layer split yet. A config with it that runs on several GPUs reads the experts the GPUs do not hold through the OS file cache instead (--mmap-experts: the placement those reports measured 1.3-1.6x faster than one GPU), said plainly - the engine - used to refuse the pair. True when the config changed.""" + used to refuse the pair. #642: the engines from RESIDENT_SPLIT_ENGINE run it on a split, so it is kept. True + when the config changed.""" a = cfg.get("args", []) - if "--resident-experts" not in a: + if "--resident-experts" not in a or resident_split(): return False a[a.index("--resident-experts")] = "--mmap-experts" warn("the low-RAM mode's resident variant (--resident-experts) has no layer split yet: on several GPUs the experts " @@ -897,8 +898,9 @@ def offer_together(cfg_path: Path, cfg: dict, yes: bool) -> dict: return cfg pair = can[:2] cfg["gpus_asked"] = True - # #364 #384: the resident low-RAM variant stays on one card unless the user says otherwise (its RAM use is steady) - resident = "--resident-experts" in cfg.get("args", []) + # #364 #384: the resident low-RAM variant stays on one card unless the user says otherwise (its RAM use is steady); + # #642: the engines from RESIDENT_SPLIT_ENGINE keep it on both cards, so they are offered as for any config + resident = "--resident-experts" in cfg.get("args", []) and not resident_split() say() say(" This PC has " + " and ".join(gpu_name(g) for g in pair) + ": Strata can share the model across both.") say(" Together they hold about twice the model's experts and read prompts about 20% faster (docs/MULTI_GPU.md).") @@ -2342,6 +2344,14 @@ DATA_ITEMS = ("models", "packs", "mtp") LOW_RAM_HEADROOM_GB = 10 # RAM beside the experts: the OS, the engine's other buffers, the server RESIDENT_ENGINE = (0, 1, 30) # the first engine with --resident-experts (the low-RAM mode's resident variant) +RESIDENT_SPLIT_ENGINE = (0, 1, 40) # #642: the first engine that runs it on a layer split + + +def resident_split() -> bool: + """#642: the engine setup requires runs the low-RAM mode's resident variant on a layer split - each card's cache + holds the most-used experts of its own layers, and the RAM copy leaves out what any card holds. Before it, a + resident config on several GPUs read those experts through the OS file cache (#364 #384).""" + return MIN_ENGINE >= RESIDENT_SPLIT_ENGINE def low_ram_needed(model, ram) -> bool: @@ -3927,9 +3937,11 @@ def main() -> int: "the low-RAM mode") low_ram = budget is None and (a.low_ram in ("on", "resident", "mmap") or (a.low_ram == "auto" and low_ram_needed(model, ram))) - if low_ram and multi and not low_ram_together(a, model, ram, gpu, chosen): + # #642: the engines from RESIDENT_SPLIT_ENGINE run the low-RAM mode on the chosen cards as on one (decided below) + if low_ram and multi and not resident_split() and not low_ram_together(a, model, ram, gpu, chosen): multi, sel, chosen = [], [gpu["index"]], [gpu] - # (the low-RAM mode's variant is decided once the context is known, below; on several GPUs it is the mapped one) + # (the low-RAM mode's variant is decided once the context is known, below; on several GPUs it is the mapped one + # before RESIDENT_SPLIT_ENGINE, #642) if not low_ram and budget is None and ram < MODELS[model]["ram_gb"] - 4: confirm_paging(model, ram, a.low_ram, a.yes, bool(a.model)) ok(f"size: {model}") @@ -4019,16 +4031,24 @@ def main() -> int: share = low_ram_gpu_share(model, vram, ctx, kv) rest = arena - low_ram_gpu_gb(model, vram, ctx, kv) resident = a.low_ram == "resident" or (a.low_ram != "mmap" and low_ram_resident(model, ram, vram, ctx, kv)) - if multi: # #364 #384: every chosen card's share (the image encoder on the main one), the mapped variant + if multi: # every chosen card's share (the image encoder on the main one); #364 #384: the mapped variant held = min(arena, low_ram_gpu_gb(model, vram, ctx, kv) + sum(low_ram_gpu_gb(model, x["vram_gb"], ctx, kv) for x in chosen[1:])) - share, resident = held / arena, False - ok(f"low-RAM mode on {len(chosen)} GPUs: {model}'s experts ({arena:.0f} GB) are read from the model folder " - f"through the OS file cache instead of a copy in RAM ({ram:.0f} GB); the GPUs hold ~{100 * share:.0f}% " - "of them") - if share < 0.6: - warn("most of the experts are read from the SSD while it answers: expect it to be much slower than " - "with enough RAM (a faster SSD and a smaller size help)") + share, rest = held / arena, arena - held + # #642: the resident variant on a split, by the same rule as on one card - what no card holds fits the RAM + resident = resident_split() and (a.low_ram == "resident" or + (a.low_ram != "mmap" and ram >= rest + LOW_RAM_HEADROOM_GB)) + if resident: + ok(f"low-RAM mode on {len(chosen)} GPUs: they hold ~{100 * share:.0f}% of {model}'s experts " + f"({arena:.0f} GB) and the other ~{rest:.0f} GB stay in RAM ({ram:.0f} GB), read once from a copy " + "in the model folder") + else: + ok(f"low-RAM mode on {len(chosen)} GPUs: {model}'s experts ({arena:.0f} GB) are read from the model " + f"folder through the OS file cache instead of a copy in RAM ({ram:.0f} GB); the GPUs hold " + f"~{100 * share:.0f}% of them") + if share < 0.6: + warn("most of the experts are read from the SSD while it answers: expect it to be much slower " + "than with enough RAM (a faster SSD and a smaller size help)") elif resident: ok(f"low-RAM mode: the GPU holds ~{100 * share:.0f}% of {model}'s experts ({arena:.0f} GB) and the other " f"~{rest:.0f} GB stay in RAM ({ram:.0f} GB), read once from a copy in the model folder") diff --git a/src/core/conversation_split_failure_test.cpp b/src/core/conversation_split_failure_test.cpp new file mode 100644 index 00000000..c383d837 --- /dev/null +++ b/src/core/conversation_split_failure_test.cpp @@ -0,0 +1,62 @@ +#include "strata/core/conversation_cache.hpp" +#include +#include +#include +static long fail_after=-1; +void* operator new(std::size_t n) { + if(fail_after==0) throw std::bad_alloc(); + if(fail_after>0) --fail_after; + if(void* p=std::malloc(n?n:1)) return p; + throw std::bad_alloc(); +} +void operator delete(void* p) noexcept { std::free(p); } +void operator delete(void* p,std::size_t) noexcept { std::free(p); } +using strata::core::ConversationCheckpoint; +bool equal(const ConversationCheckpoint& a,const ConversationCheckpoint& b) { + if(a.ids!=b.ids || a.imgs!=b.imgs || a.gdn!=b.gdn || a.ple!=b.ple || a.tails!=b.tails || a.dead!=b.dead || a.block_pos!=b.block_pos || a.used!=b.used || a.stage_parts.size()!=b.stage_parts.size()) return false; + for(size_t i=0;i checks(4); + for(size_t i=0;i0?0:3; +} diff --git a/src/core/verify.cpp b/src/core/verify.cpp index d7f47e91..77cc4b4a 100644 --- a/src/core/verify.cpp +++ b/src/core/verify.cpp @@ -284,6 +284,8 @@ Verifier::~Verifier() { if (sh_cs_) cudaStreamSynchronize(sh_cs_); for (auto& e : exec_) if (e) cudaGraphExecDestroy(e); + for (auto& e : exec_nr_) + if (e) cudaGraphExecDestroy(e); if (commit_exec_) cudaGraphExecDestroy(commit_exec_); for (auto& kv : exec_bm_) if (kv.second) cudaGraphExecDestroy(kv.second); @@ -300,7 +302,7 @@ Verifier::~Verifier() { if (ev_join_) cudaEventDestroy(ev_join_); if (arena_) cudaFree(arena_); void* hosts[] = {h_tok_, h_step_, h_pos_, h_commit_, h_ple_, h_out_, h_x_, h_ids_, h_w_, h_seq_, h_flag_, h_ymiss_, - h_flagA_, h_plan_, h_flagB_}; + h_flagA_, h_plan_, h_flagB_, h_plan_err_}; for (void* h : hosts) if (h) cudaFreeHost(h); } @@ -383,6 +385,7 @@ bool Verifier::init(const WeightTable& wt, const ModelGeometry& g, SessionState& mapped(64, (void**) &h_flag_, (void**) &m_flag_) && mapped(64, (void**) &h_flagA_, (void**) &m_flagA_) && mapped(64, (void**) &h_flagB_, (void**) &m_flagB_) && + mapped(64, (void**) &h_plan_err_, (void**) &m_plan_err_) && mapped(T * K * N * 4, (void**) &h_ymiss_, (void**) &m_ymiss_); if (!ok) { err = "verify: mapped staging allocation failed"; return false; } // the GPU plan: counts(4) | start(cap+1) | dst(cap) | tok(cap) | pad | ptr(cap u64) | ptr2(cap u64) | start2(cap+1) @@ -500,6 +503,9 @@ bool Verifier::init(const WeightTable& wt, const ModelGeometry& g, SessionState& // When true, every layer plans on device and writes directly into parts_ without any CPU doorbells, // wait_flag_ge spins, PCIe empty launches, or moe_hit_add copies. all_resident_ = false; + ar_off_ = false; + h_res_ = hits.h_res; + if (h_plan_err_ != nullptr) *(volatile uint32_t*) h_plan_err_ = 0; if (hits.h_res != nullptr && hits.d_res != nullptr && hits.cache_base != nullptr) { const char* v_ar = std::getenv("STRATA_VERIFY_ALL_RESIDENT"); if (v_ar == nullptr || std::atoi(v_ar) != 0) { @@ -521,26 +527,7 @@ bool Verifier::init(const WeightTable& wt, const ModelGeometry& g, SessionState& const char* v = std::getenv("STRATA_VERIFY_DEVICE_PLAN"); device_plan_ = !all_resident_ && (v != nullptr && std::atoi(v) != 0); } - // STRATA_VERIFY_RESIDENT=1 (opt-in): when EVERY routed expert of every layer is resident in the VRAM/UMA tier - // (checked here, once; a full cache never evicts), the window graph is recorded without the host round trip: - // no doorbell, no flag waits, no plan copy from mapped memory, no PCIe/CPU share (fetch, rebase, its grouped - // launch, the mapped-row copy); the device plans each group (the host's exact loop, E-6) and the combine reads - // the hit rows as `0.0f + hit` (what the zeroed CPU rows + moe_hit_add gave). Same tokens, same arithmetic. - { - const char* v = std::getenv("STRATA_VERIFY_RESIDENT"); - if (v != nullptr && std::atoi(v) != 0 && lb_ == 0 && le_ == g.n_layers && next_ == nullptr && - remote_opt_ == nullptr && hits.d_res != nullptr) { - std::vector res((size_t) (g.n_layers * g.n_expert)); - bool all = cudaMemcpy(res.data(), hits.d_res, res.size() * sizeof(int32_t), cudaMemcpyDeviceToHost) == - cudaSuccess; - for (size_t i = 0; all && i < res.size(); ++i) all = res[i] >= 0; - if (all) { device_plan_ = true; all_resident_ = false; } // (this window's own resident path) - resident_ = all; - std::fprintf(stderr, "strata verify: STRATA_VERIFY_RESIDENT=1: %s\n", - all ? "every expert resident, the window runs without the host round trip" - : "not every expert is resident - the host-planned window stays"); - } - } + // (halo's STRATA_VERIFY_RESIDENT=1 is this window's all_resident_ graph above, which 0.1.39 has on by default) if (g_qfuse) { // S26: the HC read's q8_1 group counters, zeroed once (each launch leaves them zero) if (cudaMalloc((void**) &qcnt_, sizeof(unsigned) * (size_t) (g.n_embd / 32)) != cudaSuccess || cudaMemset(qcnt_, 0, sizeof(unsigned) * (size_t) (g.n_embd / 32)) != cudaSuccess) { @@ -558,7 +545,7 @@ bool Verifier::init(const WeightTable& wt, const ModelGeometry& g, SessionState& cudaMemcpy(slot_off_d_, hits.slot_off, (size_t) hits.n_slots * sizeof(unsigned long long), cudaMemcpyHostToDevice) == cudaSuccess; } - if (!ok2) { cudaGetLastError(); all_resident_ = false; device_plan_ = false; resident_ = false; } + if (!ok2) { cudaGetLastError(); all_resident_ = false; device_plan_ = false; } } std::fprintf(stderr, "strata verify: window up to %d tokens, %.1f MiB of device buffers%s\n", max_t, (double) count.used / 1048576.0, @@ -603,7 +590,7 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { const int tb_[2] = {0, (T + 1) / 2}, te_[2] = {G == 2 ? (T + 1) / 2 : T, T}; // S26 STRATA_LFUSE=1: where the shared expert's gate / scale fusions apply (the paths they replace are the ones taken) auto lfuse_on = [&](int n) { - return g_lfuse && resident_ && native_moe_combine_enabled() && dec_batch && n > 1 && n <= 8 && + return g_lfuse && ar_on() && native_moe_combine_enabled() && dec_batch && n > 1 && n <= 8 && shared_expert_native_bf16_enabled(); }; bool sg_gated_[2] = {false, false}; // per group: the combine applies the shared gate @@ -677,7 +664,7 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { bool pending = l > 0 && !cvec().covers(l - 1); if (l == 1 && ple_on) { if (grp == 0) { - if (all_resident_) wait_flag_ge(m_flag_, 1, cs); + if (ar_on()) wait_flag_ge(m_flag_, 1, cs); copy_from_mapped(ple_, m_ple_, (int64_t) T * N, cs); } float* normalized = (float*) ((uint8_t*) ss.ple.scratch + ple_block_scratch_bytes()); @@ -1021,17 +1008,16 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { mb.logits = logits_ + t * NE; mb.ids = ids_ + t * K; mb.weights = w_ + t * K; if (!moe_route(wt, g, l, K, mb, mixed_ + t * N, cs, err, nullptr)) return false; } - if (all_resident_) { + if (ar_on()) { resident_plan(ids_ + tb * K, n * (int) K, (int) K, hits_.d_res + l * g.n_expert, (int) g.n_expert, hits_.cache_base, slot_off_d_, (long long) hits_.blob, - plan_ + (size_t) grp * (size_t) (plan_i32_ + 16), (long long) max_t_ * K, nullptr, 0, cs); + plan_ + (size_t) grp * (size_t) (plan_i32_ + 16), (long long) max_t_ * K, nullptr, 0, cs, m_plan_err_); } else { if (device_plan_) // E-6: every routed expert resident: this group's plan without the host resident_plan(ids_ + tb * K, n * (int) K, (int) K, hits_.d_res + l * g.n_expert, (int) g.n_expert, hits_.cache_base, slot_off_d_, (long long) hits_.blob, plan_ + (size_t) grp * (size_t) (plan_i32_ + 16), (long long) max_t_ * K, skip_ + grp, (uint32_t) ((l - lb_) * G + grp + 1), cs); - if (!resident_) { // STRATA_VERIFY_RESIDENT: no host step, so no doorbell #if defined(STRATA_USE_HIP) if (g_doorbell_store) // #649 A/B: the step's ring stored, not incremented over PCIe doorbell_publish_value(xm, ids_ + tb * K, w_ + tb * K, (int64_t) n * N, (int64_t) n * K, m_x_ + tb * N, @@ -1046,7 +1032,6 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { doorbell_publish_res(xm, ids_ + tb * K, layer_res, (int) g.n_expert, (int64_t) n * N, (int64_t) n * K, m_x_ + tb * N, m_ids_ + tb * K, m_seq_, cs); } - } } stamp(l, 17, grp); { @@ -1103,7 +1088,6 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { const uint32_t ring = (uint32_t) ((l - lb_) * G + grp + 1); const int64_t cap = (int64_t) n * K, capx = (int64_t) max_t_ * K; int32_t* pl = plan_ + (size_t) grp * (size_t) (plan_i32_ + 16); - bool combined = false; // STRATA_VERIFY_RESIDENT: the combine below already wrote bo_ const int32_t* p_counts = pl; const int32_t* p_start = pl + 4; const int32_t* p_dst = p_start + capx + 1; @@ -1129,31 +1113,7 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { hit_xs_ + (size_t) tb * (N / 32), hit_scratch_, dst_buf, cs); } }; - if (resident_) { - // STRATA_VERIFY_RESIDENT: every expert is resident and resident_plan (pre) wrote this group's plan: no host step - stamp(l, 19, grp); - grouped(p_ptr, p_start, p_counts, 0, hit_out); - stamp(l, 20, grp); - if (!prof_on_ && sh_cs_ != nullptr && ev_fork_ != nullptr && ev_join_ != nullptr) - cudaStreamWaitEvent(cs, ev_join_, 0); // the shared expert's rows are read below - if (native_moe_combine_enabled()) { - // every row is a hit: combine straight from hit_out as 0.0f + hit (= the zeroed row + moe_hit_add) - try { - if (sg_gated_[grp]) - native_moe_combine_multi_hits_gated(hit_out, w_ + tb * K, shared_ + tb * N, sh_g_ + tb, bo_ + tb * N, - N, K, n, cs); - else - native_moe_combine_multi_hits(hit_out, w_ + tb * K, shared_ + tb * N, bo_ + tb * N, N, K, n, cs); - } catch (const std::exception& e) { err = "verify combine: " + std::string(e.what()); return false; } - combined = true; - } else { - if (cudaMemsetAsync(parts_out, 0, sizeof(float) * (size_t) n * K * N, cs) != cudaSuccess) { - err = "verify: zeroing the parts failed"; - return false; - } - moe_hit_add(parts_out, hit_out, p_dst, p_counts + 1, cap, N, cs); - } - } else if (all_resident_) { + if (ar_on()) { stamp(l, 19, grp); grouped(p_ptr, p_start, p_counts, 0, parts_out); stamp(l, 20, grp); @@ -1201,7 +1161,11 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { if (!prof_on_ && sh_cs_ != nullptr && ev_fork_ != nullptr && ev_join_ != nullptr) { cudaStreamWaitEvent(cs, ev_join_, 0); } - if (!combined) { + if (sg_gated_[grp]) { // STRATA_LFUSE: the shared expert's gate was not applied: the combine applies it (all rows are hits) + try { + native_moe_combine_multi_hits_gated(parts_out, w_ + tb * K, shared_ + tb * N, sh_g_ + tb, bo_ + tb * N, N, K, n, cs); + } catch (const std::exception& e) { err = "verify combine: " + std::string(e.what()); return false; } + } else if (dec_batch && n > 1 && native_moe_combine_enabled()) { // one launch for the window's rows try { native_moe_combine_multi(parts_ + (size_t) tb * K * N, w_ + tb * K, shared_ + tb * N, bo_ + tb * N, N, K, n, cs); @@ -1212,7 +1176,6 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { mb.weights = w_ + t * K; mb.shared = shared_ + t * N; if (!moe_combine_parts(g, l, K, mb, parts_ + (size_t) t * K * N, bo_ + t * N, cs, err)) return false; } - } // !combined if (remote_opt_) remote_opt_->combine(bo_ + tb * N, y_dummy_ + tb * N, tb, n, device_plan_ ? skip_ + grp : nullptr, ring, cs); stamp(l, 24, grp); @@ -1340,8 +1303,28 @@ std::string Verifier::profile_report() { return out; } +// #871: is the zero-doorbell graph right for the next window? Only while every expert of [lb_, le_) is in VRAM now +// (the host table is the one the device copy was uploaded from; a loan, a VRAM shrink or a swap in flight has +// marked some -1). Not: the doorbell graph, which asks the pool for what the device does not hold. +void Verifier::refresh_ar() { + if (!all_resident_ || h_res_ == nullptr || g_ == nullptr) return; + const int64_t ne = g_->n_expert; + const int32_t* r = h_res_ + lb_ * ne; + const int64_t n = (le_ < 0 ? g_->n_layers : le_) * ne - lb_ * ne; + int32_t lo = 0; + for (int64_t i = 0; i < n; ++i) lo = std::min(lo, r[i]); + const bool off = lo < 0; + if (off != ar_off_) { + ar_off_ = off; + std::fprintf(stderr, "strata verify: layers [%lld, %lld) %s\n", (long long) lb_, (long long) (le_ < 0 ? g_->n_layers : le_), + off ? "have experts out of VRAM (a prompt loan, a shrink or a swap): the doorbell graph runs the windows" + : "are 100% VRAM resident again: the zero-doorbell graph"); + } +} + bool Verifier::capture(int T, std::string& err) { - if (exec_[T] != nullptr) return true; + cudaGraphExec_t& exec_t = ar_off_ ? exec_nr_[T] : exec_[T]; + if (exec_t != nullptr) return true; if (cudaStreamBeginCapture(cs_, cudaStreamCaptureModeThreadLocal) != cudaSuccess) { err = "verify: begin capture failed"; return false; @@ -1390,13 +1373,13 @@ bool Verifier::capture(int T, std::string& err) { std::fprintf(stderr, "\n"); } #endif - const cudaError_t ie = cudaGraphInstantiate(&exec_[T], graph, 0); + const cudaError_t ie = cudaGraphInstantiate(&exec_t, graph, 0); cudaGraphDestroy(graph); if (ie != cudaSuccess) { err = std::string("verify: instantiate: ") + cudaGetErrorString(ie); return false; } - const cudaError_t ue = cudaGraphUpload(exec_[T], cs_); + const cudaError_t ue = cudaGraphUpload(exec_t, cs_); const cudaError_t us = cudaStreamSynchronize(cs_); std::fprintf(stderr, "strata verify: captured the %d-token window (upload %s, sync %s)\n", T, cudaGetErrorString(ue), cudaGetErrorString(us)); @@ -1539,6 +1522,7 @@ bool Verifier::run(int T, const int32_t* tokens, int64_t pos0, PoolMultiFn pool, const ModelGeometry& g = *g_; SessionState& ss = *ss_; if (pos0 + T > ss.qsa_states[ss.qsa_primary()].max_cells) { err = "verify: the window runs past the context"; return false; } + refresh_ar(); if (!capture(T, err) || !capture_commit(err)) return false; VDBG("captured; staging\n"); const Clock::time_point t0 = Clock::now(); @@ -1560,7 +1544,8 @@ bool Verifier::run(int T, const int32_t* tokens, int64_t pos0, PoolMultiFn pool, trace_ev("WINDOW", -1, -1, pos0 * 16 + T); ms_host += ms_since(t0); VDBG("staged; launching\n"); - const cudaError_t le = cudaGraphLaunch(exec_[T], cs_); + if (ar_on() && h_plan_err_ != nullptr) *(volatile uint32_t*) h_plan_err_ = 0; + const cudaError_t le = cudaGraphLaunch(ar_off_ ? exec_nr_[T] : exec_[T], cs_); trace_ev("LAUNCHED", -1, -1, (int64_t) le); if (le != cudaSuccess) { err = std::string("verify: launch: ") + cudaGetErrorString(le); return false; } (void) cudaStreamQuery(cs_); @@ -1569,9 +1554,9 @@ bool Verifier::run(int T, const int32_t* tokens, int64_t pos0, PoolMultiFn pool, volatile uint32_t* const flag = h_flag_; const int G = groups_[T] > 0 ? groups_[T] : 1; const int gtb[2] = {0, (T + 1) / 2}, gte[2] = {G == 2 ? (T + 1) / 2 : T, T}; - const int64_t steps = resident_ ? 0 : (le_ - lb_) * G; // STRATA_VERIFY_RESIDENT: the GPU never rings + const int64_t steps = (le_ - lb_) * G; const bool test_stall = g_test_stall > 0 && windows + 1 == g_test_stall; // #267 test hook (off: false) - if (all_resident_ && !test_stall) { + if (ar_on() && !test_stall) { if (do_ple) { const Clock::time_point tp = Clock::now(); if (!ss.ple.table->gather_batch(ple_rows, (size_t) T, h_ple_, err)) return false; @@ -1674,6 +1659,11 @@ bool Verifier::run(int T, const int32_t* tokens, int64_t pos0, PoolMultiFn pool, const cudaError_t se = cudaStreamSynchronize(cs_); trace_ev("SYNCED", -1, -1, (int64_t) se); if (se != cudaSuccess) { err = std::string("verify: ") + cudaGetErrorString(se); return false; } + if (ar_on() && h_plan_err_ != nullptr && *(volatile uint32_t*) h_plan_err_ != 0) { // #871: refresh_ar saw the table whole + *(volatile uint32_t*) h_plan_err_ = 0; + err = "verify: the all-resident plan met an expert that is not in VRAM (the residency table changed during the window)"; + return false; + } commit_pending_ = false; progress_at("verify window: waiting for the expert copies", (int64_t) T); if (copy_used_) { @@ -1920,7 +1910,7 @@ bool Verifier::init_slots(const std::vector& slots, std::string& } bool Verifier::capture_batch(const int* rows, int S, int hbase, std::string& err) { - cudaGraphExec_t& ex = exec_bm_[batch_key(rows, S, hbase)]; + cudaGraphExec_t& ex = exec_bm_[bkey(rows, S, hbase)]; if (ex != nullptr) return true; if (cudaStreamBeginCapture(cs_, cudaStreamCaptureModeThreadLocal) != cudaSuccess) { err = "verify: begin batch capture failed"; @@ -2046,6 +2036,7 @@ bool Verifier::stage_batch(const int* rows, int S, int hbase, const int32_t* tok err = "verify: slot " + std::to_string(rows[t]) + " runs past its context"; return false; } + refresh_ar(); if (!capture_batch(rows, S, hbase, err) || !capture_commit_batch(rows, S, hbase, err)) return false; const Clock::time_point t0 = Clock::now(); const QsaShapes s = shapes_of(g); @@ -2103,7 +2094,7 @@ bool Verifier::run_slot_rows(const int* rows, int S, const int32_t* tokens, cons const OnDevice on_device(device_); const ModelGeometry& g = *g_; if (!stage_batch(rows, S, 0, tokens, pos, err)) return false; - const cudaError_t le = cudaGraphLaunch(exec_bm_[batch_key(rows, S, 0)], cs_); + const cudaError_t le = cudaGraphLaunch(exec_bm_[bkey(rows, S, 0)], cs_); if (le != cudaSuccess) { err = std::string("verify: batch launch: ") + cudaGetErrorString(le); return false; } (void) cudaStreamQuery(cs_); volatile uint32_t* const seq = h_seq_; @@ -2210,7 +2201,7 @@ bool Verifier::batch_launch(int base, int S, const int32_t* tokens, const int64_ int rows[8] = {}; for (int t = 0; t < S && t < 8; ++t) rows[t] = base + t; if (!stage_batch(rows, S, base, tokens, pos, err)) return false; - cudaError_t le = cudaGraphLaunch(exec_bm_[batch_key(rows, S, base)], cs_); + cudaError_t le = cudaGraphLaunch(exec_bm_[bkey(rows, S, base)], cs_); if (le == cudaSuccess) le = cudaGraphLaunch(commit_bm_[batch_key(rows, S, base)], cs_); // right behind it: every row is kept if (le != cudaSuccess) { err = std::string("verify: batch launch: ") + cudaGetErrorString(le); return false; } (void) cudaStreamQuery(cs_); diff --git a/src/kernels/cuda/iq_kernels.cu b/src/kernels/cuda/iq_kernels.cu index 3fe38ecb..17ef0a8d 100644 --- a/src/kernels/cuda/iq_kernels.cu +++ b/src/kernels/cuda/iq_kernels.cu @@ -3071,11 +3071,11 @@ __global__ void __launch_bounds__(256) native_gu_fused_kernel(const unsigned lon amax = fmaxf(amax, __shfl_xor_sync(0xffffffffu, amax, o)); sum += __shfl_xor_sync(0xffffffffu, sum, o); } - const float d = amax / 127.0f; - const int8_t q = amax == 0.0f ? 0 : roundf(xi / d); + const float d = q8_1_finite(amax / 127.0f); // #606, as q8_1_store: finite blocks bit for bit + const int8_t q = q8_1_quant(xi, d, amax); block_q8_1* y = hq + (size_t) (c0 + warp) * hb + blockIdx.x; y->qs[lane] = q; - if (lane == 0) y->ds = make_half2(d, sum); + if (lane == 0) y->ds = q8_1_ds(d, sum); } } } diff --git a/src/kernels/cuda/native_mmvq.cu b/src/kernels/cuda/native_mmvq.cu index 29b1b6b2..5a5b0105 100644 --- a/src/kernels/cuda/native_mmvq.cu +++ b/src/kernels/cuda/native_mmvq.cu @@ -169,10 +169,10 @@ __global__ void native_swiglu_quantize_q8_1_kernel(const float* __restrict__ gat const float xi = __fmul_rn(__fdividef(gi, __fadd_rn(1.0f, __expf(-gi))), up[i]); const float amax = warp_max(fabsf(xi)); const float sum = warp_sum(xi); - const float d = amax / 127.0f; - const int8_t q = amax == 0.0f ? 0 : roundf(xi / d); + const float d = q8_1_finite(amax / 127.0f); // #606, as native_quantize_q8_1_kernel: finite blocks bit for bit + const int8_t q = q8_1_quant(xi, d, amax); y[i / Q8K].qs[i % Q8K] = q; - if (i % Q8K == 0) y[i / Q8K].ds = make_half2(d, sum); + if (i % Q8K == 0) y[i / Q8K].ds = q8_1_ds(d, sum); } // Exact pinned vec_dot_q5_K_q8_1_impl_vmmq expression and integer dot order. diff --git a/src/kernels/cuda/verify_kernels.cu b/src/kernels/cuda/verify_kernels.cu index d48015da..f12f1251 100644 --- a/src/kernels/cuda/verify_kernels.cu +++ b/src/kernels/cuda/verify_kernels.cu @@ -730,7 +730,7 @@ static_assert(kVerifyMaxT * 10 <= kResidentPlanMax, "resident_plan: one thread p __global__ void __launch_bounds__(kResidentPlanMax) resident_plan_kernel(const int32_t* __restrict__ ids, int n, int k, const int32_t* __restrict__ res, int n_expert, const uint8_t* cache_base, const unsigned long long* slot_off, long long blob, int32_t* __restrict__ pl, long long capx, uint32_t* skip, - uint32_t ring) { + uint32_t ring, volatile uint32_t* plan_err) { __shared__ int32_t s_ids[kResidentPlanMax]; __shared__ unsigned long long s_ptr[kResidentPlanMax]; __shared__ int32_t s_first[kResidentPlanMax]; @@ -755,6 +755,10 @@ __global__ void __launch_bounds__(kResidentPlanMax) resident_plan_kernel(const i __syncthreads(); if (s_bad) { if (tid == 0 && skip != nullptr) *skip = 0; + if (tid == 0 && skip == nullptr) { // #871: the all-resident graph has no host plan to fall back on + pl[0] = 0; pl[1] = 0; pl[2] = 0; // an empty plan: no expert runs on a stale pointer + if (plan_err != nullptr) { *plan_err = 1; __threadfence_system(); } + } return; } @@ -900,9 +904,9 @@ __global__ void copy_or_zero_kernel(float4* __restrict__ dst, const volatile flo void resident_plan(const int32_t* ids, int n_entries, int k, const int32_t* res_layer, int n_expert, const uint8_t* cache_base, const unsigned long long* slot_off, long long blob, int32_t* plan, - long long capx, uint32_t* skip, uint32_t ring, void* stream) { + long long capx, uint32_t* skip, uint32_t ring, void* stream, uint32_t* plan_err) { resident_plan_kernel<<<1, kResidentPlanMax, 0, (cudaStream_t) stream>>>(ids, n_entries, k, res_layer, n_expert, cache_base, slot_off, - blob, plan, capx, skip, ring); + blob, plan, capx, skip, ring, plan_err); check("resident_plan"); } void wait_flag_ge_or(const uint32_t* flag, uint32_t value, const uint32_t* skip, void* stream) { diff --git a/src/kernels/iq_multi_parity.cpp b/src/kernels/iq_multi_parity.cpp index ace6facf..27b06d1e 100644 --- a/src/kernels/iq_multi_parity.cpp +++ b/src/kernels/iq_multi_parity.cpp @@ -326,9 +326,10 @@ void bench(cudaStream_t s, std::mt19937& rng) { } } -// #606: both q8_1 activation quantizers (quantize_q8_1_rows and native_quantize_q8_1) against a host transcription -// of the 0.1.38 formula: every finite block bit for bit; a block whose sum (or scale) overflowed fp16 is now stored -// finite (the largest half, its sign), with its values in the int8 range. +// #606: the q8_1 activation quantizers (quantize_q8_1_rows, native_quantize_q8_1 and the shared expert's fused +// native_swiglu_quantize_q8_1) against a host transcription of the 0.1.38 formula: every finite block bit for bit; a +// block whose sum (or scale) overflowed fp16 is now stored finite (the largest half, its sign), with its values in the +// int8 range. The fused one gets gate = 32 and up = x / 32: silu(32) is 32 in float, so its activations are x exactly. void check_q8_1_finite(cudaStream_t s, std::mt19937& rng) { const int n = 2560, rows = 3, nb = n / 32; std::vector x = random_x((size_t) rows * n, rng); @@ -338,10 +339,17 @@ void check_q8_1_finite(cudaStream_t s, std::mt19937& rng) { x[(size_t) n + 40] = 2.0e7f; // amax / 127 overflowed too float* dx = dalloc(x.size()); ck(cudaMemcpy(dx, x.data(), x.size() * 4, cudaMemcpyHostToDevice), "x"); + std::vector gate(x.size(), 32.0f), up(x.size()); + for (size_t i = 0; i < x.size(); ++i) up[i] = x[i] / 32.0f; + float* dg = dalloc(x.size()); + float* du = dalloc(x.size()); + ck(cudaMemcpy(dg, gate.data(), x.size() * 4, cudaMemcpyHostToDevice), "gate"); + ck(cudaMemcpy(du, up.data(), x.size() * 4, cudaMemcpyHostToDevice), "up"); uint8_t* dq = dalloc((size_t) rows * nb * 36); - for (int path = 0; path < 2; ++path) { + for (int path = 0; path < 3; ++path) { if (path == 0) k::quantize_q8_1_rows(dx, rows, n, dq, s); - else k::native_quantize_q8_1(dx, dq, n, rows, s); + else if (path == 1) k::native_quantize_q8_1(dx, dq, n, rows, s); + else k::native_swiglu_quantize_q8_1(dg, du, dq, n, rows, s); ck(cudaStreamSynchronize(s), "quantize"); std::vector got((size_t) rows * nb * 36); ck(cudaMemcpy(got.data(), dq, got.size(), cudaMemcpyDeviceToHost), "q"); @@ -370,7 +378,7 @@ void check_q8_1_finite(cudaStream_t s, std::mt19937& rng) { want[4 + i] = (uint8_t) (int8_t) (amax == 0.0f ? 0.0f : std::round(v[i] / d)); // native_mmvq.cu is built with --use_fast_math (its divisions are approximate): there the sum must be // the same bits, the scale within one fp16 step and each value within one step - bool near = path == 1 && gs == os && std::abs((int) gd - (int) od) <= 1; + bool near = path >= 1 && gs == os && std::abs((int) gd - (int) od) <= 1; for (int i = 0; near && i < 32; ++i) near = std::abs((int) (int8_t) g[4 + i] - (int) (int8_t) want[4 + i]) <= 1; if (std::memcmp(want, g, 36) == 0 || near) ++same; else { ++bad; std::printf(" q8_1 path %d block %d: changed although it was finite\n", path, b); } @@ -384,10 +392,13 @@ void check_q8_1_finite(cudaStream_t s, std::mt19937& rng) { } } std::printf("q8_1 finite (%s): %d finite blocks as before, %d overflowed blocks clamped finite%s\n", - path == 0 ? "quantize_q8_1_rows" : "native_quantize_q8_1", same, clamped, bad ? " FAIL" : ""); + path == 0 ? "quantize_q8_1_rows" : path == 1 ? "native_quantize_q8_1" : "native_swiglu_quantize_q8_1", + same, clamped, bad ? " FAIL" : ""); g_fail += bad + (clamped != 3); } cudaFree(dx); + cudaFree(dg); + cudaFree(du); cudaFree(dq); } diff --git a/src/prefill/prefill.cpp b/src/prefill/prefill.cpp index 9ff9d1ba..37da380f 100644 --- a/src/prefill/prefill.cpp +++ b/src/prefill/prefill.cpp @@ -99,6 +99,12 @@ constexpr int kSplitHelpRing = 48; // layer split help: the helper stage's ring // Step 3: from this chunk size on, every non-resident expert of every layer streams in a fixed order through a // ring_slots()-slot ring (nearly all 512 are routed at such a chunk), so the copy engine keeps working through the // attention halves instead of waiting for each layer's routing. +// #828: STRATA_TEST_PAGEABLE=1 makes every pinned host allocation with a pageable fallback in Prefill::init fail, so the +// fallbacks (what an LXC container's memlock limit forces) run on a PC that can pin - for ASan / MALLOC_CHECK_=3 runs. +inline bool force_pageable() { + static const bool v = [] { const char* e = std::getenv("STRATA_TEST_PAGEABLE"); return e != nullptr && e[0] == '1'; }(); + return v; +} constexpr int RING_MAX = 1024; // the arrays; the ring itself is ring_slots(), at most ring_cap() // The chunk size from which every expert streams: 1024 since 0.1.30 (was 2048). Measured on the 5070, Q2_0 / IQ2_XS, // fixed cache: 1,500-token prompts 621 -> 785 / 612 -> 735 tok/s, 2,000 727 -> 934 / 712 -> 892, 4,000 (its last @@ -332,7 +338,7 @@ struct Stager { dma_done.assign((size_t) kRing, nullptr); pageable.resize(kRing); for (int i = 0; i < kRing; ++i) { - pinned[i] = cudaHostAlloc((void**) &buf[i], blob_bytes, cudaHostAllocDefault) == cudaSuccess; + pinned[i] = !force_pageable() && cudaHostAlloc((void**) &buf[i], blob_bytes, cudaHostAllocDefault) == cudaSuccess; if (!pinned[i]) { cudaGetLastError(); pageable[(size_t) i].resize(blob_bytes); @@ -847,7 +853,8 @@ bool Prefill::init(const core::WeightTable& wt, const core::ModelGeometry& g, co m.grp_host = m.grp_dev = nullptr; m.grp_n = m.grp_tk = 0; void *h = nullptr, *d = nullptr; - if (cudaHostAlloc(&h, need * 4, cudaHostAllocMapped | (core::peer_portable() ? cudaHostAllocPortable : 0)) == cudaSuccess && + if (!force_pageable() && + cudaHostAlloc(&h, need * 4, cudaHostAllocMapped | (core::peer_portable() ? cudaHostAllocPortable : 0)) == cudaSuccess && cudaHostGetDevicePointer(&d, h, 0) == cudaSuccess) { m.grp_host = (int32_t*) h; m.grp_dev = (int32_t*) d; @@ -861,7 +868,7 @@ bool Prefill::init(const core::WeightTable& wt, const core::ModelGeometry& g, co } for (int b = 0; b < 2; ++b) { if (!m.ple_emb_host[b] && - cudaHostAlloc((void**) &m.ple_emb_host[b], (size_t) T * N * 4, cudaHostAllocDefault) != cudaSuccess) { + (force_pageable() || cudaHostAlloc((void**) &m.ple_emb_host[b], (size_t) T * N * 4, cudaHostAllocDefault) != cudaSuccess)) { cudaGetLastError(); m.ple_pageable[b].resize(T * N); // pageable: the upload is staged before it returns m.ple_emb_host[b] = m.ple_pageable[b].data(); diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 04b8041f..415e29f1 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -210,13 +210,23 @@ using Clock = std::chrono::steady_clock; // 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. -template -bool resident_stage_swaps(strata::core::FileExpertSource& src, strata::core::ExpertCache& cache, - const std::vector& host_res, int64_t n_expert, std::vector& swaps, - cudaStream_t stream) { +// +// 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) { @@ -225,17 +235,35 @@ bool resident_stage_swaps(strata::core::FileExpertSource& src, strata::core::Exp 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; - if (cudaMemcpyAsync(src.exchange_buffer(q), cache.device_slot(slot), + const SwapHome home = locate(s.layer); + const strata::core::OnDevice on(home.dev); + if (const cudaError_t e = cudaMemcpyAsync(src.exchange_buffer(q), home.cache->device_slot(slot), (size_t) strata::kernels::cpu::expert_layout().blob_bytes(s.layer), cudaMemcpyDeviceToHost, - stream) != cudaSuccess) + 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()) { - if (cudaStreamSynchronize(stream) != cudaSuccess) return false; + 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)) return false; + 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; @@ -428,6 +456,9 @@ struct Options { /// `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. Every expert a chunk @@ -1413,6 +1444,8 @@ int main(int argc, char** argv) { 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; @@ -1662,19 +1695,10 @@ int main(int argc, char** argv) { } const bool remote_caches = o.expert_cache_remote[0] > 0 || o.expert_cache_remote[1] > 0 || o.expert_cache_remote[2] > 0; - if (o.resident_cpu_experts && !o.layer_split.empty() && !remote_caches && o.resident_soft && - !o.resident_cpu_explicit && o.resident_budget == 0) { - // #364 #384: setup's --resident-experts with a layer split (--gpus at start, or a config edited by hand) runs - // as the plain mmap mode - the placement those users measured 1.3-1.6x faster than one GPU - instead of - // refusing. Exactly --mmap-experts: nothing else reads these flags (the headroom only sizes the copy). - std::fprintf(stderr, "strata generate: WARNING: the resident RAM mode (--resident-experts) does not support a " - "layer split yet: the experts the GPUs do not hold are read through the OS file cache " - "(--mmap-experts), and RAM may fill up during long prompts\n"); - o.resident_cpu_experts = o.resident_pin = o.resident_soft = false; - o.resident_headroom = 8ull << 30; - } - if (o.resident_cpu_experts && (!o.layer_split.empty() || remote_caches)) { - std::fprintf(stderr, "strata generate: --resident-cpu-experts does not support layer splits or remote expert caches\n"); + // 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). + if (o.resident_cpu_experts && remote_caches) { + std::fprintf(stderr, "strata generate: --resident-cpu-experts does not support remote expert caches\n"); return 2; } // the helper-GPU expert caches (--expert-cache-remote, docs/SECOND_GPU.md): CUDA1..3 on one GPU; with a layer @@ -2803,7 +2827,9 @@ int main(int argc, char** argv) { 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; - const int64_t reserve = ((int64_t) o.vram_reserve_mib + pf + (later ? kWindowMib : 0) + + const int64_t base_reserve = + later && o.vram_reserve_later_mib >= 0 ? o.vram_reserve_later_mib : o.vram_reserve_mib; + const int64_t reserve = (base_reserve + pf + (later ? kWindowMib : 0) + (drafter ? kDrafterMib : 0)) << 20; return std::max((int64_t) fb - reserve, 0); }; @@ -2910,7 +2936,12 @@ int main(int argc, char** argv) { 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); @@ -4324,6 +4355,13 @@ int main(int argc, char** argv) { // 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; @@ -4340,7 +4378,7 @@ int main(int argc, char** argv) { } if (cudaMalloc((void**) &d_res, host_res.size() * sizeof(int32_t)) != cudaSuccess || cudaMalloc((void**) &d_hit_count, sizeof(int32_t)) != cudaSuccess || - cudaMemcpy(d_res, host_res.data(), host_res.size() * sizeof(int32_t), cudaMemcpyHostToDevice) != cudaSuccess) { + res_put(d_res) != cudaSuccess) { std::fprintf(stderr, "strata generate: the device residency table could not be staged\n"); return 1; } @@ -4374,7 +4412,7 @@ int main(int argc, char** argv) { 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 || - cudaMemcpy(st->d_res, host_res.data(), host_res.size() * sizeof(int32_t), cudaMemcpyHostToDevice) != + res_put(st->d_res) != cudaSuccess) { std::fprintf(stderr, "strata generate: layer split: CUDA%d residency table failed\n", st->dev); return 1; @@ -4607,16 +4645,24 @@ int main(int argc, char** argv) { const int64_t k = plan_lend(chunk); if (k > 0) lend_from = xcache.slots() - k; } - bool resident_ok = src.pin_cache_complement(xcache, err, o.resident_pin, {}, lend_from, o.resident_headroom, - o.resident_budget, &profile); + // 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) + 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); + const std::vector>& rank_all = profile_all.empty() ? profile : profile_all; + bool resident_ok = src.pin_cache_complement(xcache, err, o.resident_pin, stage_pairs, lend_from, + o.resident_headroom, o.resident_budget, &rank_all); 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 the RAM alone) 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, {}, -1, o.resident_headroom, - strata::core::FileExpertSource::kResidentWhatFits, &profile); + 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 " @@ -5100,10 +5146,10 @@ int main(int argc, char** argv) { } if (evicted > 0) { if (d_res != nullptr) - cudaMemcpy(d_res, host_res.data(), host_res.size() * sizeof(int32_t), cudaMemcpyHostToDevice); + res_put(d_res); for (auto& st : stages) { const strata::core::OnDevice on(st->dev); - cudaMemcpy(st->d_res, host_res.data(), host_res.size() * sizeof(int32_t), cudaMemcpyHostToDevice); + res_put(st->d_res); } } } @@ -5248,7 +5294,7 @@ int main(int argc, char** argv) { (size_t) o.conversation_cache_slots); // Save only on a switch/rewind, not on each continuing request. No graph // addresses change: all parked images live in ordinary host vectors. - auto park_current = [&](size_t held) -> bool { + auto park_current_body = [&](size_t held) -> bool { if (!conversations.enabled() || !live_ok || live.empty()) return true; // #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) @@ -5264,7 +5310,7 @@ int main(int argc, char** argv) { const strata::core::QsaState* draft0 = n_st > 0 ? nullptr : &mtp.kv_state(); auto draft_of = [&](size_t k) -> const strata::core::QsaState* { return k + 1 == n_st ? &mtp.kv_state() : nullptr; }; strata::core::ConversationCheckpointSplit cs; - if (n_st > 0) cs = strata::core::conversation_checkpoints_split(std::move(checks), n_st); + 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(); } @@ -5368,6 +5414,15 @@ int main(int argc, char** argv) { } return true; }; + // #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; // #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 @@ -5524,10 +5579,10 @@ int main(int argc, char** argv) { // a layer split's later stages keep a copy of the residency table on their devices, and swap on their own auto res_upload = [&]() { if (d_res != nullptr) - cudaMemcpy(d_res, host_res.data(), host_res.size() * sizeof(int32_t), cudaMemcpyHostToDevice); + res_put(d_res); for (auto& st : stages) { const strata::core::OnDevice on(st->dev); - cudaMemcpy(st->d_res, host_res.data(), host_res.size() * sizeof(int32_t), cudaMemcpyHostToDevice); + res_put(st->d_res); } }; auto apply_pending = [&](bool wait) { @@ -5578,7 +5633,16 @@ int main(int argc, char** argv) { } 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 (!resident_stage_swaps(src, xcache, host_res, g.n_expert, swaps, adapt_stream)) return false; + // 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; 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) @@ -7308,8 +7372,12 @@ int main(int argc, char** argv) { (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)); - const std::string pr = ver.profile_report(); - if (!pr.empty()) std::fprintf(stderr, "strata decode GPU stages (ms/window):%s\n", pr.c_str()); + 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 (!cancelled) { // a prompt stopped halfway leaves the session somewhere between two chunks: nothing to continue from @@ -7620,7 +7688,7 @@ int main(int argc, char** argv) { lent.emplace_back((int32_t) i, host_res[i]); host_res[i] = strata::core::kNotResident; } - cudaMemcpy(d_res, host_res.data(), host_res.size() * sizeof(int32_t), cudaMemcpyHostToDevice); + 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; @@ -7671,7 +7739,7 @@ int main(int argc, char** argv) { std::fprintf(stderr, "strata generate: refilling the lent slots failed: %s\n", err.c_str()); return 1; } - cudaMemcpy(d_res, host_res.data(), host_res.size() * sizeof(int32_t), cudaMemcpyHostToDevice); + 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()); } @@ -8006,7 +8074,7 @@ int main(int argc, char** argv) { } pending.clear(); if (d_res != nullptr) - cudaMemcpy(d_res, host_res.data(), host_res.size() * sizeof(int32_t), cudaMemcpyHostToDevice); + res_put(d_res); }; // 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 @@ -8049,7 +8117,9 @@ int main(int argc, char** argv) { } 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 (!resident_stage_swaps(src, xcache, host_res, g.n_expert, swaps, adapt_stream)) { + // 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; } diff --git a/tools/test_setup_risk.py b/tools/test_setup_risk.py index 366421d9..3e569a98 100644 --- a/tools/test_setup_risk.py +++ b/tools/test_setup_risk.py @@ -244,6 +244,24 @@ class LowRamGpus(unittest.TestCase): self.assertEqual(cfg["gpu"], 0) self.assertFalse(any("Low-RAM mode" in q for q in asked), asked) + def test_low_ram_on_gpus_with_a_resident_split_engine(self): + """#642: an engine that runs the resident variant on a layer split keeps the cards together, resident.""" + ram, found = PROFILES["32GB-2x24GB"] + with mock.patch.object(setup, "MIN_ENGINE", setup.RESIDENT_SPLIT_ENGINE): + code, out, cfg, asked = install(ram, found, ["--family", "qwen", "--model", "Q2_0", "--no-start"], + answers="") + self.assertEqual(code, 0, out) + self.assertEqual(cfg["gpu"], [0, 1]) + self.assertIn("--resident-experts", cfg["args"]) + self.assertFalse(any("Low-RAM mode" in q for q in asked), asked) + self.assertIn("stay in RAM", out) + code, out, cfg, _ = install(ram, found, ["--family", "qwen", "--model", "Q2_0", "--no-start", + "--gpus", "0,1", "--low-ram", "resident"]) + self.assertEqual(code, 0, out) + self.assertEqual(cfg["gpu"], [0, 1]) + self.assertIn("--resident-experts", cfg["args"]) + self.assertNotIn("no layer split yet", out) + class StartOnSeveralGpus(unittest.TestCase): """A resident low-RAM config started on several GPUs reads the experts through the file cache (#364 #384).""" @@ -280,6 +298,18 @@ class StartOnSeveralGpus(unittest.TestCase): code, out, asked, cfg = self.offer(["--mmap-experts"], None) # other configs: as before self.assertEqual(cfg["gpu"], [0, 1]) + def test_resident_split_engine_keeps_a_resident_config(self): + """#642: from RESIDENT_SPLIT_ENGINE a resident config is offered both cards as any other, and stays resident.""" + with mock.patch.object(setup, "MIN_ENGINE", setup.RESIDENT_SPLIT_ENGINE): + cfg = {"args": ["--pack", "p", "--resident-experts", "--kv", "int8"]} + self.assertFalse(setup.split_mmap(cfg)) + self.assertEqual(cfg["args"], ["--pack", "p", "--resident-experts", "--kv", "int8"]) + code, out, asked, cfg = self.offer(["--resident-experts"], None) # --yes: the recommendation + self.assertIsNone(code, out) + self.assertEqual(cfg["gpu"], [0, 1]) + self.assertEqual(cfg["args"], ["--resident-experts", "--remote-expert-opt"]) + self.assertNotIn("OS file cache", out) + def test_start_with_gpus(self): found = PROFILES["32GB-2x24GB"][1] with tempfile.TemporaryDirectory() as d: