diff --git a/docs/VRAM_ELASTIC.md b/docs/VRAM_ELASTIC.md index c343c2a48d..f9de66c4ae 100644 --- a/docs/VRAM_ELASTIC.md +++ b/docs/VRAM_ELASTIC.md @@ -1,4 +1,4 @@ -# POST /v1/vram: what it does and what it answers (opt-in, one NVIDIA GPU, #533, #1034) +# POST /v1/vram: what it does and what it answers (opt-in; NVIDIA, across a layer split per card or one device; #533, #1034) This page is written from `terminal/serve/server.py` and the engine's `VRAM` command (`engine/src/program/generate.cpp`, `engine/src/core/expert_cache.cpp`), and the cases the unit tests in `terminal/serve/test_vram.py` pin. A line marked **(code)** is @@ -14,10 +14,10 @@ them again when more is free. Nothing resizes on its own. Only the expert cache MTP head, the CUDA context and the prompt buffers stay, so Strata never gives back "everything". The engine switches the feature off at start, with one line in its log (`--vram-elastic is off: ...`), when it is not -a `--serve` engine, with a layer split, with helper caches on other GPUs, with a segment below 64 MiB, and on HIP +a `--serve` engine, with helper caches on other GPUs (`--peer-device`, an expert-profile tier), with a segment below 64 MiB, and on HIP (NVIDIA only). If the driver offers no virtual memory management the cache is one block and the engine starts all the same (`--vram-elastic is off: the driver or this GPU offers no virtual memory management`) **(code; not run on such a driver)**. -Without the flag nothing changes: the same answers as without it. +Without the flag nothing changes: the same answers as without it. Across a `--layer-split` each card keeps its own segmented cache, so by default one call keeps the reserve on every card at once; pass a `"device"` to free just that CUDA device and leave the others with their full expert cache. ## The request @@ -25,6 +25,7 @@ Without the flag nothing changes: the same answers as without it. POST /v1/vram Content-Type: application/json (anything else: 415) {"reserve_mib": 8000} (a whole number of MiB, 0 or more; null = the reserve the engine started with) +{"reserve_mib": 4096, "device": 1} (free only CUDA device 1; every other card keeps its full expert cache) ``` - The server's API key applies as for the other `/v1` routes. A request that carries a foreign `Origin` is refused @@ -32,13 +33,15 @@ Content-Type: application/json (anything else: 415) - `reserve_mib` is the free VRAM you want left on the card after the call (it counts what any program holds, not only Strata). Below 0, a string, a boolean or a fraction: 400. - `null` and `0` are the grow-back requests: `null` keeps the `--vram-reserve-mib` the engine started with, `0` keeps - nothing free on purpose. + nothing free on purpose. With a layer split these apply to every card; add `"device"` to aim one call at that device only. +- `device` is an optional CUDA index (the engine's grammar is `VRAM [dev]`, reserve first). It needs an explicit + `reserve_mib` (`device` with a null reserve: 400); below 0, a string or a boolean: 400. Absent means every card. On one GPU it is the only card (and so optional). ## What comes back | Case | Status | Body | |---|---|---| -| Done (or nothing to do) | 200 | `{"status": "ok", "reserve_mib", "expert_slots", "expert_slots_full", "expert_cache_mib", "expert_cache_full_mib", "vram_free_mib", "prompt_chunk"}` | +| Done (or nothing to do) | 200 | `{"status": "ok", "reserve_mib", "expert_slots", "expert_slots_full", "expert_cache_mib", "expert_cache_full_mib", "vram_free_mib", "prompt_chunk"}` plus a `"per_device"` map (`"": {"mapped_mib", "free_mib"}`, every card after the call) and, when one device was named, `"device"` and `"vram_free_on_device_mib"` | | The model is unloaded | 200 | `{"status": "not loaded", "reserve_mib": N, "note": "applied when the model loads"}` | | Bad `reserve_mib` | 400 | `invalid_request_error` | | The engine refuses the command | 400 | `invalid_request_error`, the engine's reason in `message`. The engine stays up. | diff --git a/engine/include/strata/core/residency_trim.hpp b/engine/include/strata/core/residency_trim.hpp index 4f5ab0f5f9..855d9aac63 100644 --- a/engine/include/strata/core/residency_trim.hpp +++ b/engine/include/strata/core/residency_trim.hpp @@ -13,12 +13,17 @@ namespace strata::core { -/// Every entry of `res` (residency index -> slot) whose slot is at or past `live` (the slots still mapped) becomes -/// kNotResident, and (index, slot) is appended to `evicted` in table order (a later grow puts those experts back). -/// Returns how many entries it took. -inline int64_t evict_slots_past(std::vector& res, int64_t live, std::vector>& evicted) { +/// The same over a layer range: only entries whose expert sits on a layer in `[lo_layer, hi_layer)` (a card's own layers +/// under a layer split) are checked against `live` (that cache's slots still mapped). Slot numbers are per-card-local and +/// overlap across cards, so with a split each cache must trim only its own experts; with one GPU the range covers every +/// layer. Returns how many entries it took, appended to `evicted` in table order (a later grow puts those back). +inline int64_t evict_slots_past(std::vector& res, int64_t live, int64_t lo_layer, int64_t hi_layer, + int64_t n_expert, std::vector>& evicted) { + const size_t begin = (size_t) (lo_layer * n_expert); + const int64_t total = (int64_t) res.size(); // one sign for the comparisons below: a residency table never nears INT64_MAX. + const size_t cap = (size_t) ((hi_layer == INT64_MAX || hi_layer > total) ? total : hi_layer * n_expert); int64_t n = 0; - for (size_t i = 0; i < res.size(); ++i) + for (size_t i = begin; i < res.size() && i < cap; ++i) if (res[i] >= live) { evicted.emplace_back((int32_t) i, res[i]); res[i] = kNotResident; @@ -27,4 +32,11 @@ inline int64_t evict_slots_past(std::vector& res, int64_t live, std::ve return n; } +/// Every entry of `res` (residency index -> slot) whose slot is at or past `live` (the slots still mapped) becomes +/// kNotResident, and (index, slot) is appended to `evicted` in table order (a later grow puts those experts back). +/// Returns how many entries it took. One GPU: the whole table belongs to that one cache. +inline int64_t evict_slots_past(std::vector& res, int64_t live, std::vector>& evicted) { + return evict_slots_past(res, live, 0, INT64_MAX, 1, evicted); +} + } // namespace strata::core diff --git a/engine/include/strata/program/split_rules.hpp b/engine/include/strata/program/split_rules.hpp index e9c6c235cf..fba7eea7ad 100644 --- a/engine/include/strata/program/split_rules.hpp +++ b/engine/include/strata/program/split_rules.hpp @@ -169,6 +169,19 @@ inline std::vector link_miss_scale(const std::vector& gbps, doub return s; } +// ---- the gate-off fallback must still load. When no placement can start the prompt path the search chooses by decode speed +// alone, and nothing checked that a later stage's cache can hold anything; a later stage with no room for one expert slot ends +// the start ("layer split, CUDA1 expert cache: no room"). 2x 8 GB (RTX 3060 Ti + RTX 3070 Ti) with DFlash2 on CUDA1: the PCIe +// probe put the link gap at 3.66-4.33, on both sides of kLinkScaleMin, and the K=45 it picked below the step could not load. +// So the fallback first keeps to placements in which every later stage holds at least one slot; with none, it picks as before. + +/// held[i]: the expert slots stage i's cache holds in the search's fill. True when a stage after the first holds none. +inline bool later_stage_empty(const std::vector& held) { + for (size_t i = 1; i < held.size(); ++i) + if (held[i] <= 0) return true; + return false; +} + /// The smallest spare room over the stages of `cuts`: room[i] - session(lb, le) - need(lb, le), where `need_prefix[l]` /// is the bytes of every expert of layers [0, l) (n_layers + 1 entries). template diff --git a/engine/include/strata/program/stage_reserve.hpp b/engine/include/strata/program/stage_reserve.hpp index b29d378b9e..ce65737817 100644 --- a/engine/include/strata/program/stage_reserve.hpp +++ b/engine/include/strata/program/stage_reserve.hpp @@ -17,12 +17,28 @@ namespace strata::program::stage_reserve { constexpr int64_t kWindowMib = 96; ///< the verify windows on a later stage; 75 MiB measured, rounded up constexpr int64_t kDrafterMib = 1000; ///< the MTP drafter (839 MiB) + the head, on the last stage only +constexpr int64_t kDf2BindMib = 48; ///< DFlash2's draft logits, bound on its card after the expert cache +constexpr int64_t kDf2ServeStagingMib = 112; ///< serve: DFlash2's prompt staging, bound there after the cache too + +/// What DFlash2 binds on its card after the expert cache, beside its own draft head (generate.cpp's `df2_after` less +/// `df2_head_bytes()`), in MiB. The cache step takes it out of the last stage's room, so the split search plans it too. +inline int64_t df2_after_mib(bool serve) { return kDf2BindMib + (serve ? kDf2ServeStagingMib : 0); } + +/// DFlash2's drafter and the head on the last stage, over kDrafterMib's MTP figure. 2x 8 GB, 0.1.63, serve: CUDA1 went from +/// "holds its weights" to the cache step 7.30 -> 6.21 GiB at K=47 and 7.23 -> 6.13 GiB at K=46, ~1100 MiB with the session +/// (~10 MiB a layer) taken out ("strata dflash2: ... drafter 765 MiB of VRAM" + the head): ~100 MiB over, rounded up. +constexpr int64_t kDf2DrafterOverMib = 112; + +/// What the split search books for DFlash2 on the drafter's stage: its drafter over kDrafterMib, and what it binds after the +/// cache (df2_after_mib). The cache step measures the loaded drafter, so it subtracts only df2_after_mib. +inline int64_t df2_search_mib(bool serve) { return kDf2DrafterOverMib + df2_after_mib(serve); } struct Inputs { int64_t base_reserve_mib = 0; ///< --vram-reserve-later-mib on a later stage when given, else --vram-reserve-mib int64_t prompt_buffers_mib = 0; ///< the prompt path's own buffers (0 when they are borrowed from the cache) bool later = false; ///< a stage after the first bool drafter = false; ///< the stage that carries the MTP drafter and the head + int64_t df2_bind_mib = 0; ///< the drafter's stage with DFlash2 on it: df2_search_mib (0: no DFlash2 there) int64_t pipe_window_mib = 0; ///< --pipeline-windows: a second verifier on every stage int64_t pipe_snap_mib = 0; ///< --pipeline-windows 2 or more: the first stage's second GDN state }; @@ -30,7 +46,7 @@ struct Inputs { /// What the plan keeps free on the card, in MiB (generate.cpp's `reserve` before the shift). inline int64_t reserve_mib(const Inputs& in) { return in.base_reserve_mib + in.prompt_buffers_mib + (in.later ? kWindowMib : in.pipe_snap_mib) + in.pipe_window_mib + - (in.drafter ? kDrafterMib : 0); + (in.drafter ? kDrafterMib + in.df2_bind_mib : 0); } /// The room the cache may use: the free bytes less the reserve, never below 0. diff --git a/engine/src/core/peer_experts.cpp b/engine/src/core/peer_experts.cpp index e5508905bc..775a742589 100644 --- a/engine/src/core/peer_experts.cpp +++ b/engine/src/core/peer_experts.cpp @@ -17,6 +17,11 @@ #include #include #include +#if defined(__linux__) +#include +#include +#include +#endif namespace strata::core { @@ -50,18 +55,71 @@ struct On { /// were zeros and the rows it sent back never arrived, so the first prompt's MoE output was garbage and the logits NaN. Without /// peer access enabled the same copies are right (the driver stages them). So the pair is asked once, with a small copy each way, /// whether the direct path really carries data. true = both ways exact (or nothing could be tested: the old trust is kept). +/// Returns false when two CUDA GPUs sit behind separate PCIe root ports (PHB / SYS topology) without +/// NVLink / native P2P atomics. On such boards (e.g. Intel Xeon PHB + ACS, 2x RTX A4000) merely calling +/// cudaDeviceEnablePeerAccess + cudaMemcpyPeer can fault GPU 1's CUDA context (unspecified launch failure) +/// or stall at ~98 ms per copy. Skipping P2P upfront avoids poisoning the device and uses fast portable host staging. +bool p2p_topology_safe(int dev0, int dev1) { + if (const char* np = std::getenv("STRATA_PEER_NO_P2P"); np != nullptr && np[0] != '\0' && std::atoi(np) == 0) return true; +#if !defined(STRATA_USE_HIP) + int atomic_ok = 0; + if (cudaDeviceGetP2PAttribute(&atomic_ok, cudaDevP2PAttrNativeAtomicSupported, dev0, dev1) == cudaSuccess && atomic_ok) { + return true; // NVLink or true hardware P2P switch with native atomics + } + (void) cudaGetLastError(); +#if defined(__linux__) + auto ancestors = [](int d) -> std::vector { + char bdf[64] = {}; + if (cudaDeviceGetPCIBusId(bdf, sizeof(bdf), d) != cudaSuccess) { (void) cudaGetLastError(); return {}; } + for (char* p = bdf; *p; ++p) *p = (char) std::tolower((unsigned char) *p); + std::string sys = std::string("/sys/bus/pci/devices/") + bdf; + char resolved[PATH_MAX] = {}; + if (!realpath(sys.c_str(), resolved)) return {}; + std::vector parts; + std::string s(resolved); + size_t pos = 0; + while (pos < s.size()) { + size_t nxt = s.find('/', pos); + if (nxt == std::string::npos) nxt = s.size(); + if (nxt > pos) parts.push_back(s.substr(pos, nxt - pos)); + pos = nxt + 1; + } + if (!parts.empty()) parts.pop_back(); // drop the GPU's own BDF + return parts; + }; + const auto a0 = ancestors(dev0), a1 = ancestors(dev1); + if (!a0.empty() && !a1.empty()) { + size_t common_bridges = 0; + const size_t n = std::min(a0.size(), a1.size()); + for (size_t i = 0; i < n && a0[i] == a1[i]; ++i) { + // PCI bridge components look like "0000:00:02.0" (contains ':' and '.'), whereas root complex is "pci0000:00" + if (a0[i].find(':') != std::string::npos && a0[i].find('.') != std::string::npos) ++common_bridges; + } + if (common_bridges == 0) return false; // PHB / NODE / SYS (no shared PCIe switch) + } +#endif +#endif + return true; +} + bool p2p_copies_data(int device) { constexpr size_t kN = 1 << 14; // floats std::vector h(kN), back(kN); for (size_t i = 0; i < kN; ++i) h[i] = 1.0f + (float) ((i * 2654435761u) % 4093u); float* d[2] = {nullptr, nullptr}; - const int dev[2] = {0, device}; + cudaStream_t st[2] = {nullptr, nullptr}; + const int dev[2] = {primary_device(), device}; bool ok = true, tested = true; for (int k = 0; k < 2 && tested; ++k) { On on(dev[k]); - if (cudaMalloc((void**) &d[k], kN * 4) != cudaSuccess) { cudaGetLastError(); tested = false; } + if (cudaMalloc((void**) &d[k], kN * 4) != cudaSuccess || + cudaStreamCreateWithFlags(&st[k], cudaStreamNonBlocking) != cudaSuccess) { + cudaGetLastError(); + tested = false; + } } - for (int dir = 0; dir < 2 && tested && ok; ++dir) { // 0: device 0 -> peer, 1: peer -> device 0 + double copy_ms = 0.0; + for (int dir = 0; dir < 2 && tested && ok; ++dir) { // 0: primary -> peer, 1: peer -> primary const int from = dir == 0 ? 0 : 1, to = 1 - from; { On on(dev[from]); @@ -70,18 +128,23 @@ bool p2p_copies_data(int device) { { On on(dev[to]); if (cudaMemset(d[to], 0, kN * 4) != cudaSuccess) { tested = false; break; } - } - if (cudaMemcpyPeer(d[to], dev[to], d[from], dev[from], kN * 4) != cudaSuccess) { tested = false; break; } - { - On on(dev[to]); + const auto t0 = std::chrono::steady_clock::now(); + if (cudaMemcpyPeerAsync(d[to], dev[to], d[from], dev[from], kN * 4, st[to]) != cudaSuccess || + cudaStreamSynchronize(st[to]) != cudaSuccess) { tested = false; break; } + copy_ms += std::chrono::duration(std::chrono::steady_clock::now() - t0).count(); if (cudaMemcpy(back.data(), d[to], kN * 4, cudaMemcpyDeviceToHost) != cudaSuccess) { tested = false; break; } } ok = std::memcmp(back.data(), h.data(), kN * 4) == 0; + if (copy_ms > 5.0) break; } - for (int k = 0; k < 2; ++k) - if (d[k] != nullptr) { On on(dev[k]); cudaFree(d[k]); } - if (!tested) { cudaGetLastError(); return true; } - return ok; + for (int k = 0; k < 2; ++k) { + On on(dev[k]); + if (st[k] != nullptr) cudaStreamDestroy(st[k]); + if (d[k] != nullptr) cudaFree(d[k]); + } + if (!tested) { cudaGetLastError(); return false; } + if (!ok) return false; + return copy_ms <= 2.0; // reject stalling PCIe host-bridge P2P (~98 ms/copy) in favor of portable host staging } bool ck(cudaError_t e, const char* what, std::string& err) { @@ -132,9 +195,9 @@ bool PeerExperts::open(int device, const std::vector close(); int count = 0; if (!ck(cudaGetDeviceCount(&count), "cudaGetDeviceCount", err)) return false; - if (device < 1 || device >= count) { - err = "peer experts: CUDA device " + std::to_string(device) + " is not visible (" + std::to_string(count) + - " devices; set CUDA_VISIBLE_DEVICES)"; + if (device < 0 || device >= count || device == primary_device()) { + err = "peer experts: CUDA device " + std::to_string(device) + " is not a valid secondary GPU (" + std::to_string(count) + + " devices, primary=" + std::to_string(primary_device()) + "; set CUDA_VISIBLE_DEVICES)"; return false; } const auto& lay = strata::kernels::cpu::expert_layout(); @@ -148,6 +211,11 @@ bool PeerExperts::open(int device, const std::vector cudaDeviceCanAccessPeer(&b, device, primary_device()); if (const char* np = std::getenv("STRATA_PEER_NO_P2P"); np != nullptr && std::atoi(np) != 0) a = 0; // test knob: pretend the pair has no P2P p2p_ = a && b; + if (p2p_ && !p2p_topology_safe(primary_device(), device)) { + std::fprintf(stderr, "strata: peer GPU %d: GPUs sit behind a PCIe host bridge (PHB/SYS, no shared PCIe switch or NVLink); " + "using portable host-pinned staging instead of P2P (STRATA_PEER_NO_P2P=0 overrides)\n", device); + p2p_ = false; + } if (p2p_) { On on0(primary_device()); cudaError_t e0 = cudaDeviceEnablePeerAccess(device, 0); @@ -161,8 +229,8 @@ bool PeerExperts::open(int device, const std::vector std::fprintf(stderr, "strata: peer GPU %d: peer access is enabled but a test copy between the two GPUs arrived wrong " "(a host bridge between them, no real P2P): the prompt path takes the host route instead " "(STRATA_PEER_NO_P2P=1 does that by hand)\n", device); - { On q0(0); cudaDeviceDisablePeerAccess(device); cudaGetLastError(); } - { On q1(device); cudaDeviceDisablePeerAccess(0); cudaGetLastError(); } + { On q0(primary_device()); cudaDeviceDisablePeerAccess(device); cudaGetLastError(); } + { On q1(device); cudaDeviceDisablePeerAccess(primary_device()); cudaGetLastError(); } p2p_ = false; } } @@ -226,15 +294,13 @@ bool PeerExperts::open(int device, const std::vector if (advise && i + kAhead < pick.size()) (void) src.advise_pairs(&pick[i + kAhead], 1); const int32_t slot = cache_.admit(pr.first, pr.second); const uint8_t* b = src.blob(pr.first, pr.second); - if (slot < 0 || b == nullptr || !cache_.fill_slot(slot, b, refill_, err, (int64_t) lay.blob_bytes(pr.first))) { + if (slot < 0 || b == nullptr || !cache_.fill_slot_blocking(slot, b, err, (int64_t) lay.blob_bytes(pr.first))) { err = "peer experts: fill failed: " + err; close(); return false; } - src.note_async_read(b, refill_); // #1237 res_[(size_t) (pr.first * n_expert + pr.second)] = slot; } - if (!ck(cudaStreamSynchronize(refill_), "fill", err)) { close(); return false; } const auto& f0 = pick.front(); if (!cache_.verify_slot(res_[(size_t) (f0.first * n_expert + f0.second)], src.blob(f0.first, f0.second), err, (int64_t) lay.blob_bytes(f0.first))) { diff --git a/engine/src/prefill/prefill.cpp b/engine/src/prefill/prefill.cpp index ad14b800a9..92163ebeb8 100644 --- a/engine/src/prefill/prefill.cpp +++ b/engine/src/prefill/prefill.cpp @@ -1573,6 +1573,9 @@ struct Prefill::Impl { PinnedUpload steps_up; int32_t* sel_ids = nullptr; float* sel_scores = nullptr; // [sel_batch, max_blocks] + float* tp_ref_sc = nullptr; // STRATA_SELECT_TWO_PASS_CHECK=1 when m.attn is too small: today's row and ids + int32_t* tp_ref_ids = nullptr; + size_t tp_ref_sc_n = 0, tp_ref_ids_n = 0; int64_t sel_batch = 256, max_blocks = 0; float* attn_scratch = nullptr; int64_t attn_batch = 32, cap = 0; @@ -5382,11 +5385,8 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri // STRATA_SELECT_TWO_PASS_CHECK=1 (diagnostic, one GPU): today's scores and ids for the same // queries, compared with the two-pass ones (counts at the prompt's end). Their buffers are the // rest of m.attn past the two-pass scratch when it is large enough (the attention below writes - // m.attn after the comparison), else buffers of their own + // m.attn after the comparison), else the stage's own buffers on its own card (freed with m.owned) if (tp_call && tp_check) { - static float* own_sc = nullptr; - static int32_t* own_ids = nullptr; - static size_t own_sc_n = 0, own_ids_n = 0; const size_t want_sc = (size_t) m.sel_batch * (size_t) m.max_blocks, want_ids = (size_t) m.sel_batch * (size_t) m.cap; const uint64_t at = (strata::kernels::qsa_two_pass_scratch_bytes(m.sel_batch, m.max_blocks) + 255u) & ~uint64_t(255u); const uint64_t at_ids = at + (((uint64_t) want_sc * 4u + 255u) & ~uint64_t(255u)); @@ -5396,23 +5396,25 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri ref_sc = reinterpret_cast(reinterpret_cast(m.attn) + at); ref_ids = reinterpret_cast(reinterpret_cast(m.attn) + at_ids); } else { - if (want_sc > own_sc_n || want_ids > own_ids_n) { - cudaStreamSynchronize(m.cs); - cudaFree(own_sc); - cudaFree(own_ids); - own_sc = nullptr; - own_ids = nullptr; - own_sc_n = own_ids_n = 0; - if (cudaMalloc((void**) &own_sc, want_sc * 4) != cudaSuccess || - cudaMalloc((void**) &own_ids, want_ids * 4) != cudaSuccess) { + // a larger need takes a new pair; the smaller one stays in m.owned until release + if (want_sc > m.tp_ref_sc_n || want_ids > m.tp_ref_ids_n) { + float* own_sc = nullptr; + int32_t* own_ids = nullptr; + const bool ok = cudaMalloc((void**) &own_sc, want_sc * 4) == cudaSuccess && + cudaMalloc((void**) &own_ids, want_ids * 4) == cudaSuccess; + if (own_sc) m.owned.push_back(own_sc); + if (own_ids) m.owned.push_back(own_ids); + if (!ok) { err = "STRATA_SELECT_TWO_PASS_CHECK: no room for its buffers"; return false; } - own_sc_n = want_sc; - own_ids_n = want_ids; + m.tp_ref_sc = own_sc; + m.tp_ref_ids = own_ids; + m.tp_ref_sc_n = want_sc; + m.tp_ref_ids_n = want_ids; } - ref_sc = own_sc; - ref_ids = own_ids; + ref_sc = m.tp_ref_sc; + ref_ids = m.tp_ref_ids; } if (!strata::kernels::qsa_block_scores_tc(st.idx_pooled, st.idx_dead, m.q_idx + t0 * kIdxQW, steps0, nb, m.max_blocks, s, ref_sc, m.cs, active)) { diff --git a/engine/src/program/generate.cpp b/engine/src/program/generate.cpp index 9d57f2b406..bbb98533ed 100644 --- a/engine/src/program/generate.cpp +++ b/engine/src/program/generate.cpp @@ -6710,6 +6710,14 @@ int main(int argc, char** argv) { carve_memo.emplace(key, total); return total; }; + // DFlash2 will draft on the last stage (its cache step takes `df2_after` out of that stage's room, below): the search plans it + // there too. The same conditions as that term and the DFlash2 block's refusals that are known this early. +#if defined(STRATA_HAVE_DFLASH2) + const bool df2_last = multi_gpu && !stages.empty() && o.draft == "dflash2" && !o.draft_auto && !df2_first && o.pipeline_windows <= 0 && + native_pack && !o.draft_model.empty() && (df2_solo || !o.mtp.empty()) && !strata::qwen_defaults_026(); +#else + constexpr bool df2_last = false; +#endif static const bool place_with_reserve = [] { const char* v = std::getenv("STRATA_SPLIT_OWN_PLACE"); return v != nullptr && std::string(v) == "reserve"; @@ -6731,6 +6739,7 @@ int main(int argc, char** argv) { rin.prompt_buffers_mib = pf; rin.later = later; rin.drafter = drafter; + rin.df2_bind_mib = search && drafter && df2_last ? strata::program::stage_reserve::df2_search_mib(o.serve) : 0; rin.pipe_window_mib = kPipeWindowMib; rin.pipe_snap_mib = kPipeSnapMib; return strata::program::stage_reserve::room_bytes((int64_t) fb, rin); @@ -7058,6 +7067,7 @@ int main(int argc, char** argv) { return parts; }; bool gate_on = true; // off only when no placement can start (below): then the best one is kept and a warning said + bool slot_floor = false; // with the gate off: first only placements whose later stages hold an expert slot (split_rules::later_stage_empty) 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 @@ -7071,6 +7081,7 @@ int main(int argc, char** argv) { double hm = 0; int64_t held = 0; const double ms = predict(at, hm, held); + if (slot_floor && strata::program::split_rules::later_stage_empty(held_cnt)) return; // its cache step would end the start ++tried; if (ns <= 3) priced.emplace_back(ms, at); const double mx = stage_max(at); @@ -7164,6 +7175,7 @@ int main(int argc, char** argv) { 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; + if (slot_floor && strata::program::split_rules::later_stage_empty({held_at[a], held_at[b], held_at[c], held_at[d]})) 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; @@ -7301,7 +7313,12 @@ int main(int argc, char** argv) { 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; + // but not a placement whose later card has no room for one expert slot: that card's cache step ends the start ("expert cache: no + // room"), and the server starts again without a drafter. With none that has, the pick is as before. + slot_floor = true; search(); + slot_floor = false; + if (best.empty()) search(); if (!best.empty()) split_diagnosis(best); } if (best.empty()) { @@ -9219,11 +9236,11 @@ int main(int argc, char** argv) { // 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. + // #533: --vram-elastic: the caches in physical segments (the VRAM command resizes them between requests). Serve + // mode, no helper caches; a layer split resizes every card's segmented cache with its own reserve (address-stable + // per-card arenas). 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; @@ -9534,7 +9551,7 @@ int main(int argc, char** argv) { // 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); + const int64_t df2_after = df2_head_bytes() + (strata::program::stage_reserve::df2_after_mib(o.serve) << 20); // (the split search plans the same, stage_room) room = std::max(room - df2_after, 0); } #endif @@ -9575,6 +9592,8 @@ int main(int argc, char** argv) { // 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 + if (o.vram_elastic) // #533 multi-GPU: this card's cache in segments so the VRAM command resizes it too. + st.cache.set_segment_bytes(o.vram_segment_mib << 20); 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); @@ -14750,10 +14769,18 @@ int main(int argc, char** argv) { // --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) + // #6560: request thread owns drive.d.usage exclusively (no race with expert_pool_dispatch_multi's += 1.0f + // under --pipeline-windows 2); snapshot + heat + decay run on the request thread before spawning adapt(). + auto snapshot_usage = [&]() -> std::vector { + std::vector snap = drive.d.usage; + for (size_t i = 0; i < heat.size(); ++i) heat[i] += (double) snap[i]; + for (float& v : drive.d.usage) v *= o.adapt_decay; + return snap; + }; // the VRAM tier follows the conversation (the same rule as the speculative loop below) - auto adapt = [&]() -> bool { + auto adapt = [&](const std::vector& usage_snap) -> bool { if (!pending.empty()) return true; // the previous swaps are still in flight - if (remote_opt && !remote_opt->adapt(drive.d.usage, host_res, pending, o.adapt_swaps, *srcp)) return false; + if (remote_opt && !remote_opt->adapt(usage_snap, host_res, pending, o.adapt_swaps, *srcp)) return false; struct Swap { float gain; int32_t layer, in, out; }; std::vector swaps; std::vector> cand, vict; @@ -14764,7 +14791,7 @@ int main(int argc, char** argv) { 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 float* u = usage_snap.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); } @@ -14907,21 +14934,16 @@ int main(int argc, char** argv) { 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(), + if (!peer.adapt(usage_snap.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 @@ -15934,35 +15956,65 @@ int main(int argc, char** argv) { // 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) { + auto relend = [&]() { // the prompt path's loan: one chunk that fits every card, each part ending at its own slots left. + if (pf_parts.empty()) return; + bool any_loan = false; + for (const PfPart& p : pf_parts) if (p.first >= 0) any_loan = true; + if (!any_loan) return; + auto fits_all = [&](int64_t c) { + for (const PfPart& p : pf_parts) { + if (!p.cache || p.first < 0) continue; + const int64_t live = p.cache->slots(); #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); + const int64_t k = part_slots(p, c, o.prefill_auto ? pf_fit_tail : -1); + const int64_t k_floor = part_slots(p, c); #else - const int64_t k = part_slots(p, c); - return k > 0 && k + g_lend_keep <= live && !(o.prefill_auto && k * 100 > kAutoLendPct * live); + const int64_t k = part_slots(p, c); + const int64_t k_floor = k; #endif + if (k <= 0 || k_floor <= 0) return false; + if (g_lend_keep + k_floor > live) return false; + if (o.prefill_auto && k * 100 > kAutoLendPct * live) return false; + } + return true; }; int64_t c = chunk_full; - while (c > 256 && !fits(c)) c = std::max(256, c / 2 / 256 * 256); + while (c > 256 && !fits_all(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 + for (PfPart& p : pf_parts) { + if (!p.cache || p.first < 0) continue; + const int64_t live = p.cache->slots(); +#if defined(STRATA_PREFILL_FUSED) && !defined(STRATA_PREFILL_MMQ) + const int64_t k = part_slots(p, c, o.prefill_auto ? pf_fit_tail : -1); +#else + const int64_t k = part_slots(p, c); +#endif + p.first = (int32_t) std::max(0, live - std::max(k, 0)); + 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; } + // Grammar (back-compat kept): `VRAM` = every card to start reserve; `VRAM ` = every card; + // `VRAM ` = ONE card only (CUDA device id). + std::vector tk; + { std::string t; for (char ch : (cmd.size() > 4 ? cmd.substr(4) : std::string())) + if (ch == ' ' || ch == '\t') { if (!t.empty()) { tk.push_back(t); t.clear(); } } else t += ch; + if (!t.empty()) tk.push_back(t); } + const auto is_nonneg_int = [](const std::string& x) { + if (x.empty()) return false; + for (char ch : x) if (ch < '0' || ch > '9') return false; + return true; + }; + long long reserve = o.vram_reserve_mib; + int dev_sel = -1; + if (tk.empty()) { /* bare: start reserve, every card */ } + else if (tk.size() == 1 && is_nonneg_int(tk[0])) { reserve = std::strtoll(tk[0].c_str(), nullptr, 10); } + else if (tk.size() == 2 && is_nonneg_int(tk[0]) && is_nonneg_int(tk[1])) { + reserve = std::strtoll(tk[0].c_str(), nullptr, 10); + dev_sel = (int) std::strtoll(tk[1].c_str(), nullptr, 10); + } else { e = "expected: VRAM [reserve_mib] [dev]"; return false; } if (!xcache.segmented()) { - e = "VRAM needs an engine started with --vram-elastic (one NVIDIA GPU, --serve)"; + e = "VRAM needs an engine started with --vram-elastic (NVIDIA GPU, --serve)"; return false; } if (src.complement_ready()) { @@ -15979,77 +16031,116 @@ int main(int argc, char** argv) { return false; } const auto t0 = Clock::now(); + struct VCard { strata::core::ExpertCache* c; int dev; int64_t lo, hi; PfPart* part; }; + std::vector cards; + cards.push_back({&xcache, 0, 0, stages.empty() ? (int64_t) g.n_layers : stages.front()->lb, + pf_parts.empty() ? nullptr : &pf_parts[0]}); + for (size_t i = 0; i < stages.size(); ++i) + cards.push_back({&stages[i]->cache, stages[i]->dev, stages[i]->lb, stages[i]->le, + i + 1 < pf_parts.size() ? &pf_parts[i + 1] : nullptr}); + const int64_t want_free = (int64_t) reserve << 20; 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; } + std::vector sel; + if (dev_sel == -1) { + for (size_t i = 0; i < cards.size(); ++i) sel.push_back((int) i); + } else { + bool found = false; + for (size_t i = 0; i < cards.size(); ++i) + if (cards[i].dev == dev_sel) { sel.push_back((int) i); found = true; } + if (!found) { e = "VRAM: no such device"; return false; } + } + for (int ci : sel) { + VCard& cd = cards[(size_t) ci]; + const strata::core::OnDevice on(cd.dev); + size_t fb = 0, tb = 0; + cudaMemGetInfo(&fb, &tb); + const int64_t mapped = cd.c->mapped_bytes(); + if ((int64_t) fb < want_free) { + const int64_t floor_slots = std::min(cd.c->full_slots(), + g_lend_keep + (cd.part != nullptr && cd.part->first >= 0 ? part_slots(*cd.part, 256) : 0)); + const int64_t floor_b = cd.c->bytes_of(floor_slots); + int64_t keep = mapped - (want_free - (int64_t) fb); + if (keep < floor_b) { + keep = floor_b; + note = " (a cache keeps its smallest size: the prompt path's buffers)"; + } + const bool shrunk = cd.c->shrink(keep, e); + strata::core::evict_slots_past(host_res, cd.c->slots(), cd.lo, cd.hi, g.n_expert, vram_evicted); + if (!shrunk) { relend(); res_upload(); return false; } + } else if (mapped < cd.c->full_bytes()) { + std::string gerr; + if (!cd.c->grow(mapped + ((int64_t) fb - want_free), gerr)) note = " (" + gerr + ")"; + const int64_t live = cd.c->slots(); + std::vector> keep_out; + for (const auto& [i, slot] : vram_evicted) { + const int64_t layer = i / g.n_expert; + if (layer < cd.lo || layer >= cd.hi) { keep_out.emplace_back(i, slot); continue; } + if (slot >= live) { keep_out.emplace_back(i, slot); continue; } + int64_t pick = i; + if (host_res[(size_t) i] >= 0) { + 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 || !cd.c->fill_slot_queued(slot, b, e, + (int64_t) strata::kernels::cpu::expert_layout().blob_bytes(layer))) { + e = "VRAM: refilling a cache failed: " + e; + vram_evicted.swap(keep_out); + relend(); + res_upload(); + return false; + } + srcp->note_async_read(b, nullptr); + host_res[(size_t) pick] = slot; } - 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 (!cd.c->sync_queued(e)) { e = "VRAM: " + e; relend(); res_upload(); return false; } } - vram_evicted.swap(keep_out); - if (!xcache.sync_queued(ferr)) { e = "VRAM: " + ferr; return false; } - res_upload(); } relend(); + res_upload(); 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, + long long sum_slots = 0, sum_full = 0; + int64_t sum_mapped = 0, sum_bytes = 0; + std::string card_detail; + long long dev_free = -1; + for (const VCard& cd : cards) { + const strata::core::OnDevice on(cd.dev); + size_t f2 = 0, t2 = 0; + cudaMemGetInfo(&f2, &t2); + sum_slots += cd.c->slots(); + sum_full += cd.c->full_slots(); + sum_mapped += cd.c->mapped_bytes(); + sum_bytes += cd.c->full_bytes(); + char buf[96]; + std::snprintf(buf, sizeof buf, "%s%d:%lld:%lld", card_detail.empty() ? "" : "|", cd.dev, + (long long) (cd.c->mapped_bytes() >> 20), (long long) (f2 >> 20)); + card_detail += buf; + if (dev_sel >= 0 && cd.dev == dev_sel) dev_free = (long long) (f2 >> 20); + } + std::fprintf(stderr, "strata serve: VRAM %lld MiB kept free on each card: the expert caches hold %lld of %lld slots " + "(%.2f of %.2f GiB over %zu cache(s)), CUDA0 %lld MiB free now, prompt chunk %lld, in %.0f ms%s\n", + reserve, sum_slots, sum_full, (double) sum_mapped / 1073741824.0, (double) sum_bytes / 1073741824.0, + cards.size(), (long long) (free_b >> 20), (long long) o.prefill_chunk, std::chrono::duration(Clock::now() - t0).count(), note.c_str()); + std::string extra = " cards=" + card_detail; + if (dev_sel >= 0) { + char d[80]; + std::snprintf(d, sizeof d, " device=%d vram_free_on_device_mib=%lld", dev_sel, dev_free); + extra += d; + } 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); + "expert_cache_full_mib=%lld vram_free_mib=%lld prompt_chunk=%lld%s\n", reserve, + sum_slots, sum_full, (long long) (sum_mapped >> 20), (long long) (sum_bytes >> 20), + (long long) (free_b >> 20), (long long) o.prefill_chunk, extra.c_str()); return true; }; // ---- --batch: the slots of the batch windows @@ -16566,8 +16657,10 @@ int main(int argc, char** argv) { bool ok = true; ~AdaptRun() { if (th.joinable()) th.join(); } // an error return below still joins it } adapt_run; - if (!drive.d.usage.empty() && !ajob && !in_prompt_read && (++ba_window % o.adapt_every) == 0 && pending.empty()) - adapt_run.th = std::thread([&] { adapt_run.ok = adapt(); }); + if (!drive.d.usage.empty() && !ajob && !in_prompt_read && (++ba_window % o.adapt_every) == 0 && pending.empty()) { + auto usnap = snapshot_usage(); + adapt_run.th = std::thread([&, u = std::move(usnap)] { adapt_run.ok = adapt(u); }); + } // 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) { @@ -17581,9 +17674,12 @@ int main(int argc, char** argv) { 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; + if (pending.empty()) { + const auto usnap = snapshot_usage(); + if (!adapt(usnap)) { + std::printf("ERR an adaptive refill failed\n"); + return false; + } } ++pa_rounds; pa_swaps += (int64_t) pending.size(); @@ -21200,8 +21296,9 @@ int main(int argc, char** argv) { pl_apply(); if (!drive.d.usage.empty() && o.adapt_every > 0 && (rounds % o.adapt_iv(rounds)) == 0 && pending.empty() && !exch_wait) { + auto usnap = snapshot_usage(); 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; }); + pl_adapt_thr = std::thread([&, u = std::move(usnap)] { strata::platform::name_this_thread("strata-adapt"); strata::aux_cpus::pin_current_thread(); pl_adapt_ok = adapt(u); pl_adapt_done = true; }); } return true; }; @@ -22204,8 +22301,10 @@ int main(int argc, char** argv) { 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() && !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 (!drive.d.usage.empty() && !ajob && pending.empty() && ((rounds + 1) % o.adapt_iv(rounds)) == 0) { + auto usnap = snapshot_usage(); + adapt_thr = std::thread([&, u = std::move(usnap)] { strata::platform::name_this_thread("strata-adapt"); strata::aux_cpus::pin_current_thread(); adapt_ok = adapt(u); }); + } if (!ver.commit(a + 1, err)) { exit_if_gpu_fatal(err); if (adapt_thr.joinable()) adapt_thr.join(); @@ -23801,7 +23900,7 @@ int main(int argc, char** argv) { // 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 { + auto adapt = [&](const std::vector& usage_snap) -> 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 @@ -23825,7 +23924,7 @@ int main(int argc, char** argv) { 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 float* u = usage_snap.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); } @@ -23899,7 +23998,6 @@ int main(int argc, char** argv) { 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; @@ -24286,8 +24384,11 @@ int main(int argc, char** argv) { // 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(); }); + if (!drive.d.usage.empty() && pending.empty() && ((rounds + 1) % o.adapt_iv(rounds)) == 0) { + std::vector usnap = drive.d.usage; + for (float& v : drive.d.usage) v *= o.adapt_decay; + adapt_thr = std::thread([&, u = std::move(usnap)] { strata::platform::name_this_thread("strata-adapt"); strata::aux_cpus::pin_current_thread(); adapt_ok = adapt(u); }); + } strata::core::progress_at("spec loop: commit", (int64_t) T); if (!ver.commit(a + 1, err)) { if (adapt_thr.joinable()) adapt_thr.join(); diff --git a/engine/src/split/CMakeLists.txt b/engine/src/split/CMakeLists.txt index 31102acdac..819d6856be 100644 --- a/engine/src/split/CMakeLists.txt +++ b/engine/src/split/CMakeLists.txt @@ -18,11 +18,11 @@ set(STRATA_SPLIT_ARCH "" CACHE STRING "compute capability strata-split is built set(STRATA_SPLIT_PF_JOB "64" CACHE STRING "rows of one expert per prompt-path job: 64 (default) or 128") set(_fnx_hip OFF) -if(STRATA_ENABLE_HIP AND NOT STRATA_ENABLE_CUDA AND NOT WIN32 AND NOT APPLE) +if(STRATA_ENABLE_HIP AND NOT STRATA_ENABLE_CUDA AND NOT APPLE) set(_fnx_hip ON) endif() if(NOT _fnx_hip AND (NOT STRATA_ENABLE_CUDA OR WIN32 OR APPLE)) - message(STATUS "STRATA_BUILD_SPLIT: needs a Linux CUDA or HIP build, skipped") + message(STATUS "STRATA_BUILD_SPLIT: needs a Linux CUDA or Linux/Windows HIP build, skipped") return() endif() # the quant header (block layouts, codebook tables): Strata's include/strata/quant/strata-quant-common.h, the split's only header from the root include/; its dot products are its own @@ -39,22 +39,31 @@ if(_fnx_hip) # (strata_control/split_engine.py AUTO_SPLIT_AMD_ARCHS); on another card the engine runs src/selftest.cu before it loads the model # STRATA_SPLIT_HIP_ARCHS names the split engine's code objects when they are not the tree's CMAKE_HIP_ARCHITECTURES (whose list the HIP backend checks for the main # engine and does not know gfx11-generic); empty: the tree's list - set(STRATA_SPLIT_HIP_ARCHS "" CACHE STRING "code objects of strata-split-N (gfx1201;gfx1200;gfx11-generic), empty: CMAKE_HIP_ARCHITECTURES") + set(STRATA_SPLIT_HIP_ARCHS "" CACHE STRING "code objects of strata-split-N (gfx1201;gfx1200;gfx11-generic), empty: supported subset of CMAKE_HIP_ARCHITECTURES") + set(_fnx_hip_ok gfx1100 gfx1101 gfx1102 gfx1103 gfx11-generic gfx1200 gfx1201) if(STRATA_SPLIT_HIP_ARCHS) set(_fnx_hip_archs ${STRATA_SPLIT_HIP_ARCHS}) + set(_fnx_hip_bad "") + foreach(_a ${_fnx_hip_archs}) + if(NOT _a IN_LIST _fnx_hip_ok) + list(APPEND _fnx_hip_bad ${_a}) + endif() + endforeach() + if(_fnx_hip_bad) + message(WARNING "STRATA_BUILD_SPLIT (HIP): the split engine builds for ${_fnx_hip_ok} only (got ${_fnx_hip_archs}), skipped") + return() + endif() else() - set(_fnx_hip_archs ${STRATA_HIP_ARCH_LIST}) - endif() - set(_fnx_hip_ok gfx1100 gfx1101 gfx1102 gfx1103 gfx11-generic gfx1200 gfx1201) - set(_fnx_hip_bad "") - foreach(_a ${_fnx_hip_archs}) - if(NOT _a IN_LIST _fnx_hip_ok) - list(APPEND _fnx_hip_bad ${_a}) + set(_fnx_hip_archs "") + foreach(_a ${STRATA_HIP_ARCH_LIST}) + if(_a IN_LIST _fnx_hip_ok) + list(APPEND _fnx_hip_archs ${_a}) + endif() + endforeach() + if(NOT _fnx_hip_archs) + message(STATUS "STRATA_BUILD_SPLIT (HIP): no supported split archs in ${STRATA_HIP_ARCH_LIST} (supported: ${_fnx_hip_ok}), skipped") + return() endif() - endforeach() - if(NOT _fnx_hip_archs OR _fnx_hip_bad) - message(WARNING "STRATA_BUILD_SPLIT (HIP): the split engine builds for ${_fnx_hip_ok} only (got ${_fnx_hip_archs}), skipped") - return() endif() set(STRATA_SPLIT_ARCH 1201) # (FNX_ARCH is only compared with 80 and 70: any HIP value takes the WMMA paths) elseif(NOT STRATA_SPLIT_ARCH) @@ -181,12 +190,14 @@ if(STRATA_BUILD_TESTS) set_target_properties(split_convert_dump PROPERTIES CUDA_ARCHITECTURES OFF) target_link_libraries(split_convert_dump PRIVATE Threads::Threads) # the weight tiles of the prompt kernel run on a GPU against the file (tests/split/tile_check.py reads its output); not a ctest - add_executable(split_moe_tile_test ${_sp}/tools/moe_tile_test.cu ${_sp}/src/gguf.cpp) - target_include_directories(split_moe_tile_test PRIVATE ${_sp}/src ${_sp}/tools ${_sp_quant}) - target_compile_definitions(split_moe_tile_test PRIVATE FNX_NCARD=${_n0} FNX_ARCH=${STRATA_SPLIT_ARCH} FNX_27B=0) - target_compile_options(split_moe_tile_test PRIVATE $<$:--use_fast_math --expt-relaxed-constexpr -Wno-deprecated-gpu-targets>) - set_target_properties(split_moe_tile_test PROPERTIES CUDA_ARCHITECTURES "${STRATA_SPLIT_ARCH}-real" CUDA_STANDARD 17 CXX_STANDARD 17) - target_link_libraries(split_moe_tile_test PRIVATE Threads::Threads) + if(NOT _fnx_hip) + add_executable(split_moe_tile_test ${_sp}/tools/moe_tile_test.cu ${_sp}/src/gguf.cpp) + target_include_directories(split_moe_tile_test PRIVATE ${_sp}/src ${_sp}/tools ${_sp_quant}) + target_compile_definitions(split_moe_tile_test PRIVATE FNX_NCARD=${_n0} FNX_ARCH=${STRATA_SPLIT_ARCH} FNX_27B=0) + target_compile_options(split_moe_tile_test PRIVATE $<$:--use_fast_math --expt-relaxed-constexpr -Wno-deprecated-gpu-targets>) + set_target_properties(split_moe_tile_test PROPERTIES CUDA_ARCHITECTURES "${STRATA_SPLIT_ARCH}-real" CUDA_STANDARD 17 CXX_STANDARD 17) + target_link_libraries(split_moe_tile_test PRIVATE Threads::Threads) + endif() # the same dots against the stored digests tools/qdot_golden.txt (written by split_qdot_test --write-golden), without ggml: the check that stays when the # vendored tree goes. A ctest that skips (77) without a GPU. CUDA only for now: the HIP build gets it once its bits were compared on a card. if(NOT _fnx_hip) @@ -207,15 +218,17 @@ if(STRATA_BUILD_TESTS) set_target_properties(split_gdn_tc_test PROPERTIES CUDA_ARCHITECTURES "${STRATA_SPLIT_ARCH}-real" CUDA_STANDARD 17 CXX_STANDARD 17) endif() # fnx_run: sFNX's test driver (teacher-forced logits to an .lgr file, prompt/decode checks), the same engine objects with its own main - set(_sp_run_src ${_sp_engine}) - list(REMOVE_ITEM _sp_run_src ${_sp}/tools/sfnx.cpp) - add_executable(split_fnx_run ${_sp_run_src} ${_sp}/tools/fnx_run.cpp ${_sp_kparts}) - set_source_files_properties(${_sp}/tools/fnx_run.cpp PROPERTIES LANGUAGE CUDA) - target_include_directories(split_fnx_run PRIVATE ${_sp}/src ${_sp}/tools ${_sp_quant}) - target_compile_definitions(split_fnx_run PRIVATE FNX_NCARD=${_n0} FNX_ARCH=${STRATA_SPLIT_ARCH} FNX_27B=0 FNX_HOSTRING=1 FNX_DIR="${_sp}") - target_compile_options(split_fnx_run PRIVATE $<$:--use_fast_math --expt-relaxed-constexpr -Wno-deprecated-gpu-targets>) - set_target_properties(split_fnx_run PROPERTIES CUDA_ARCHITECTURES "${STRATA_SPLIT_ARCH}-real" CUDA_STANDARD 17 CUDA_STANDARD_REQUIRED ON CXX_STANDARD 17) - find_package(CUDAToolkit REQUIRED) - target_link_libraries(split_fnx_run PRIVATE CUDA::cublas CUDA::cublasLt CUDA::cuda_driver Threads::Threads) - set_target_properties(split_fnx_run PROPERTIES CUDA_RUNTIME_LIBRARY Shared) + if(NOT _fnx_hip) + set(_sp_run_src ${_sp_engine}) + list(REMOVE_ITEM _sp_run_src ${_sp}/tools/sfnx.cpp) + add_executable(split_fnx_run ${_sp_run_src} ${_sp}/tools/fnx_run.cpp ${_sp_kparts}) + set_source_files_properties(${_sp}/tools/fnx_run.cpp PROPERTIES LANGUAGE CUDA) + target_include_directories(split_fnx_run PRIVATE ${_sp}/src ${_sp}/tools ${_sp_quant}) + target_compile_definitions(split_fnx_run PRIVATE FNX_NCARD=${_n0} FNX_ARCH=${STRATA_SPLIT_ARCH} FNX_27B=0 FNX_HOSTRING=1 FNX_DIR="${_sp}") + target_compile_options(split_fnx_run PRIVATE $<$:--use_fast_math --expt-relaxed-constexpr -Wno-deprecated-gpu-targets>) + set_target_properties(split_fnx_run PROPERTIES CUDA_ARCHITECTURES "${STRATA_SPLIT_ARCH}-real" CUDA_STANDARD 17 CUDA_STANDARD_REQUIRED ON CXX_STANDARD 17) + find_package(CUDAToolkit REQUIRED) + target_link_libraries(split_fnx_run PRIVATE CUDA::cublas CUDA::cublasLt CUDA::cuda_driver Threads::Threads) + set_target_properties(split_fnx_run PROPERTIES CUDA_RUNTIME_LIBRARY Shared) + endif() endif() diff --git a/engine/src/split/src/df2_bridge.cpp b/engine/src/split/src/df2_bridge.cpp index 76d81e7bf2..bd27d6abf7 100644 --- a/engine/src/split/src/df2_bridge.cpp +++ b/engine/src/split/src/df2_bridge.cpp @@ -47,7 +47,11 @@ bool Bridge::load(const std::string& pack, int device, int lanes, const std::vec I.device = device; I.embed = std::move(embed); // the ring log (host copies of the activation rows for a rebuild) is the main engine's way of resuming a conversation; the split starts a lane's ring over instead +#ifdef _WIN32 + if (!std::getenv("STRATA_DF2_RING_LOG")) _putenv_s("STRATA_DF2_RING_LOG", "0"); +#else ::setenv("STRATA_DF2_RING_LOG", "0", 0); +#endif if (cudaSetDevice(device) != cudaSuccess) { err = "dflash2: cannot select the card"; return false; } I.d.emplace_back(new Dflash2Drafter); Dflash2Drafter& parent = *I.d[0]; diff --git a/engine/src/split/src/engine.cu b/engine/src/split/src/engine.cu index c8f6565537..0d7d00229a 100644 --- a/engine/src/split/src/engine.cu +++ b/engine/src/split/src/engine.cu @@ -8,7 +8,9 @@ #include "pf_pick.hpp" #include +#ifndef _WIN32 #include +#endif #include #include diff --git a/engine/src/split/src/engine_common.cu b/engine/src/split/src/engine_common.cu index 4ab679bb50..11b4435373 100644 --- a/engine/src/split/src/engine_common.cu +++ b/engine/src/split/src/engine_common.cu @@ -3,6 +3,13 @@ #include "env.hpp" #include +#ifdef _WIN32 +#ifndef NOMINMAX +#define NOMINMAX +#endif +#include +#include +#endif #include #include @@ -67,6 +74,12 @@ void install_graph(CardBuf::GraphSlot& s, cudaGraph_t g, const std::vector& } long host_available_mib() { +#ifdef _WIN32 + MEMORYSTATUSEX st{}; + st.dwLength = sizeof(st); + if (!GlobalMemoryStatusEx(&st)) return -1; + return (long) (st.ullAvailPhys / (1024ull * 1024ull)); +#else std::FILE* f = std::fopen("/proc/meminfo", "r"); if (!f) return -1; char line[256]; @@ -75,6 +88,7 @@ long host_available_mib() { if (std::sscanf(line, "MemAvailable: %ld kB", &kb) == 1) break; std::fclose(f); return kb < 0 ? -1 : kb / 1024; +#endif } struct CardPool { @@ -482,7 +496,11 @@ size_t Engine::SeqState::total() const { } Engine::SeqState::~SeqState() { +#ifdef _WIN32 + for (void* p : host) if (p) _aligned_free(p); +#else for (void* p : host) std::free(p); +#endif } void stage_copy(CardBuf& b, const std::vector>& pieces, char* host, size_t total, bool to_host) { @@ -577,7 +595,11 @@ std::shared_ptr Engine::save_state(bool kv) { pieces[(size_t) c] = state_pieces(*cb_[c], m_.cards[c], mtp_ != nullptr, pos_, kv, half, lanes_[(size_t) cur_].pages); size_t n = 0; for (const auto& p : pieces[(size_t) c]) n += p.second; +#ifdef _WIN32 + s->host[c] = _aligned_malloc((n + 4095) / 4096 * 4096, 4096); +#else s->host[c] = std::aligned_alloc(4096, (n + 4095) / 4096 * 4096); +#endif if (!s->host[c]) throw std::runtime_error("save_state: host memory for " + std::to_string(n >> 20) + " MiB (" + std::to_string(host_available_mib()) + " MiB available)"); diff --git a/engine/src/split/src/gguf.cpp b/engine/src/split/src/gguf.cpp index 1e40846036..7a00761afa 100644 --- a/engine/src/split/src/gguf.cpp +++ b/engine/src/split/src/gguf.cpp @@ -1,9 +1,17 @@ #include "gguf.hpp" +#ifdef _WIN32 +#ifndef NOMINMAX +#define NOMINMAX +#endif +#include +#include +#else #include #include #include #include +#endif #include #include @@ -190,14 +198,44 @@ void Gguf::convert_small_tensors() { Gguf::~Gguf() { for (Map& mp : maps_) { +#ifdef _WIN32 + if (mp.base) UnmapViewOfFile(mp.base); + if (mp.hmap) CloseHandle((HANDLE) mp.hmap); + if (mp.hfile && mp.hfile != INVALID_HANDLE_VALUE) CloseHandle((HANDLE) mp.hfile); +#else if (mp.base) munmap(mp.base, mp.size); if (mp.fd >= 0) close(mp.fd); +#endif } } void Gguf::load_shard(const std::string& path, bool meta) { Map mp; mp.path = path; +#ifdef _WIN32 + HANDLE hf = CreateFileA(path.c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); + if (hf == INVALID_HANDLE_VALUE) throw std::runtime_error("gguf: cannot open " + path); + LARGE_INTEGER fsz{}; + if (!GetFileSizeEx(hf, &fsz) || fsz.QuadPart <= 0) { + CloseHandle(hf); + throw std::runtime_error("gguf: cannot stat " + path); + } + HANDLE hm = CreateFileMappingA(hf, nullptr, PAGE_READONLY, 0, 0, nullptr); + if (!hm) { + CloseHandle(hf); + throw std::runtime_error("gguf: CreateFileMapping failed for " + path); + } + void* base = MapViewOfFile(hm, FILE_MAP_READ, 0, 0, 0); + if (!base) { + CloseHandle(hm); + CloseHandle(hf); + throw std::runtime_error("gguf: MapViewOfFile failed for " + path); + } + mp.hfile = (void*) hf; + mp.hmap = (void*) hm; + mp.size = (size_t) fsz.QuadPart; + mp.base = base; +#else mp.fd = open(path.c_str(), O_RDONLY); if (mp.fd < 0) throw std::runtime_error("gguf: cannot open " + path); struct stat st; @@ -205,6 +243,7 @@ void Gguf::load_shard(const std::string& path, bool meta) { mp.size = (size_t) st.st_size; mp.base = mmap(nullptr, mp.size, PROT_READ, MAP_SHARED, mp.fd, 0); if (mp.base == MAP_FAILED) throw std::runtime_error("gguf: mmap failed for " + path); +#endif maps_.push_back(mp); Cur c{(const uint8_t*) mp.base, (const uint8_t*) mp.base + mp.size}; if (c.get() != 0x46554747u) throw std::runtime_error("gguf: bad magic in " + path); @@ -346,6 +385,17 @@ constexpr uint64_t MERGE_GAP = 1ull << 20; // tensors closer than this in a fi Stager::Stager(const Gguf& g, std::vector groups, int consumers, int ahead) : g_(g), consumers_(consumers), ahead_(ahead) { if (consumers < 1 || ahead < 1) throw std::runtime_error("stager: needs a consumer and a group ahead"); +#ifdef _WIN32 + for (int s = 0; s < g.shards(); ++s) { + HANDLE hf = CreateFileA(g.shard_path(s).c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); + if (hf == INVALID_HANDLE_VALUE) { + for (void* h : plain_handle_) CloseHandle((HANDLE) h); + plain_handle_.clear(); + throw std::runtime_error("stager: cannot open " + g.shard_path(s)); + } + plain_handle_.push_back((void*) hf); + } +#else bool no_direct = false; for (int s = 0; s < g.shards(); ++s) { const int pf = ::open(g.shard_path(s).c_str(), O_RDONLY); @@ -358,6 +408,7 @@ Stager::Stager(const Gguf& g, std::vector groups, int consumers, int ahea direct_fd_.push_back(df); } if (no_direct) std::fprintf(stderr, "gguf: the model's file system refuses O_DIRECT: read through the page cache\n"); +#endif groups_.resize(groups.size()); for (size_t i = 0; i < groups.size(); ++i) { G& gr = groups_[i]; @@ -409,11 +460,17 @@ Stager::~Stager() { } cv_.notify_all(); reader_.join(); +#ifdef _WIN32 + for (G& gr : groups_) if (gr.buf) _aligned_free(gr.buf); + for (uint8_t* b : free_) if (b) _aligned_free(b); + for (void* h : plain_handle_) CloseHandle((HANDLE) h); +#else for (G& gr : groups_) std::free(gr.buf); for (uint8_t* b : free_) std::free(b); for (int fd : plain_fd_) ::close(fd); for (int fd : direct_fd_) if (fd >= 0) ::close(fd); +#endif } void Stager::run() { @@ -428,9 +485,15 @@ void Stager::run() { } try { if (!buf) { +#ifdef _WIN32 + void* p = _aligned_malloc(std::max(buf_bytes_, PAGE), PAGE); + if (!p) + throw std::runtime_error("stager: " + std::to_string(buf_bytes_ >> 20) + " MiB for a group's buffer"); +#else void* p = nullptr; if (posix_memalign(&p, PAGE, std::max(buf_bytes_, PAGE))) throw std::runtime_error("stager: " + std::to_string(buf_bytes_ >> 20) + " MiB for a group's buffer"); +#endif buf = (uint8_t*) p; } gr.buf = buf; @@ -461,12 +524,31 @@ void Stager::read_group(G& gr) { std::vector th; for (int r = 0; r < READERS; ++r) th.emplace_back([&, r] { +#ifndef _WIN32 std::vector inc(PIECE / PAGE); +#endif try { for (size_t i; (i = next.fetch_add(1)) < pieces.size();) { const Span& s = *pieces[i].s; const uint64_t fo = s.off + pieces[i].k, n = std::min(PIECE, s.len - pieces[i].k); const uint64_t file = g_.shard_size(s.shard), valid = std::min(n, file - fo); // the span's last page may pass the end + uint8_t* dst = gr.buf + s.at + pieces[i].k; +#ifdef _WIN32 + HANDLE hf = (HANDLE) plain_handle_[(size_t) s.shard]; + uint64_t got = 0; + while (got < valid) { + OVERLAPPED ov{}; + const uint64_t pos = fo + got; + ov.Offset = (DWORD) (pos & 0xffffffffull); + ov.OffsetHigh = (DWORD) (pos >> 32); + const DWORD want = (DWORD) std::min(valid - got, 16ull << 20); + DWORD rd = 0; + if (!ReadFile(hf, dst + got, want, &rd, &ov) || rd == 0) + throw std::runtime_error("stager: read of " + g_.shard_path(s.shard) + " at " + std::to_string(pos)); + got += rd; + } + disk_bytes_ += valid; +#else if (mincore((void*) (g_.shard_base(s.shard) + fo), valid, inc.data()) != 0) throw std::runtime_error(std::string("stager: mincore: ") + std::strerror(errno)); bool cached = gr.spec.cached; @@ -475,7 +557,6 @@ void Stager::read_group(G& gr) { for (uint64_t p = 0; p < (valid + PAGE - 1) / PAGE; ++p) cached &= inc[p] & 1; } const int fd = cached || direct_fd_[(size_t) s.shard] < 0 ? plain_fd_[(size_t) s.shard] : direct_fd_[(size_t) s.shard]; - uint8_t* dst = gr.buf + s.at + pieces[i].k; uint64_t got = 0; while (got < valid) { // O_DIRECT reads whole pages: the last piece of a file asks past its end and gets what is there @@ -487,6 +568,7 @@ void Stager::read_group(G& gr) { got += (uint64_t) k; } (cached ? cache_bytes_ : disk_bytes_) += valid; +#endif } } catch (const std::exception& e) { errs[(size_t) r] = e.what(); diff --git a/engine/src/split/src/gguf.hpp b/engine/src/split/src/gguf.hpp index 2bd5efec68..88d0dc3352 100644 --- a/engine/src/split/src/gguf.hpp +++ b/engine/src/split/src/gguf.hpp @@ -73,7 +73,16 @@ public: const uint8_t* shard_base(int s) const { return (const uint8_t*) maps_[(size_t) s].base; } private: - struct Map { void* base = nullptr; size_t size = 0; int fd = -1; std::string path; }; + struct Map { + void* base = nullptr; + size_t size = 0; + int fd = -1; +#ifdef _WIN32 + void* hfile = nullptr; + void* hmap = nullptr; +#endif + std::string path; + }; std::vector maps_; std::map tensors_; std::map ints_; @@ -131,7 +140,11 @@ private: }; const Gguf& g_; std::vector groups_; +#ifdef _WIN32 + std::vector plain_handle_; +#else std::vector direct_fd_, plain_fd_; +#endif std::vector free_; // buffers given back, for the next groups size_t buf_bytes_ = 0; int consumers_, ahead_, held_ = 0; diff --git a/engine/src/split/src/hip/rccl_dl.hpp b/engine/src/split/src/hip/rccl_dl.hpp index b79dff1e1a..38551e4d39 100644 --- a/engine/src/split/src/hip/rccl_dl.hpp +++ b/engine/src/split/src/hip/rccl_dl.hpp @@ -5,7 +5,9 @@ // The six functions and the two enum values are RCCL's (rccl.h: ncclSum = 0, ncclFloat16 = 6, ncclFloat32 = 7, ncclSuccess = 0). #pragma once +#if !defined(_WIN32) #include +#endif #include #include @@ -31,6 +33,12 @@ struct RcclApi { // path: the library to load ("" = librccl.so.1 from the library path; FNX_RCCL_LIB overrides it, for tests). false with the reason in why. inline bool rccl_load(RcclApi& api, const std::string& path, std::string& why) { +#if defined(_WIN32) + (void) api; + (void) path; + why = "RCCL is not available on Windows"; + return false; +#else const char* over = std::getenv("FNX_RCCL_LIB"); const std::string lib = over && *over ? over : (path.empty() ? "librccl.so.1" : path); api.handle = dlopen(lib.c_str(), RTLD_NOW | RTLD_LOCAL); @@ -56,6 +64,7 @@ inline bool rccl_load(RcclApi& api, const std::string& path, std::string& why) { } why = lib; return true; +#endif } // The decision: FNX_PF_RCCL=0 or unset (the default, until the screens say the prompt sums win): the host exchange, no line. =1: only with the peer push on (RCCL moves its diff --git a/engine/src/split/src/memlock.hpp b/engine/src/split/src/memlock.hpp index 0046fc8825..43a3dcf801 100644 --- a/engine/src/split/src/memlock.hpp +++ b/engine/src/split/src/memlock.hpp @@ -12,8 +12,15 @@ // A failing mlock call (another process used the allowance, the kernel said no) only leaves its range unlocked. #pragma once +#ifdef _WIN32 +#ifndef NOMINMAX +#define NOMINMAX +#endif +#include +#else #include #include +#endif #include #include @@ -79,6 +86,21 @@ inline uint64_t lock_page_ceil(uint64_t x) { return (x + kLockPage - 1) / kLockP // Step 1 and the environment: the soft limit raised towards the hard limit for `need` bytes (plus 1 GiB of room for the other locks), then what is left. inline LockEnv read_lock_env(uint64_t need) { LockEnv e; +#ifdef _WIN32 + (void) need; + MEMORYSTATUSEX st{}; + st.dwLength = sizeof(st); + if (GlobalMemoryStatusEx(&st)) { + e.avail = (uint64_t) st.ullAvailPhys; + e.reserve = std::max(kLockReserveMinBytes, (uint64_t) st.ullTotalPhys / kLockReserveShareDiv); + } else { + e.avail = UINT64_MAX; + e.reserve = kLockReserveMinBytes; + } + e.limit = 0; // Windows uses parallel fault-in without VirtualLock working-set limits + e.limit_hard = 0; + return e; +#else struct rlimit rl {}; if (getrlimit(RLIMIT_MEMLOCK, &rl) == 0) { const uint64_t room = need + (1ull << 30); @@ -101,6 +123,7 @@ inline LockEnv read_lock_env(uint64_t need) { e.avail = avail ? avail : UINT64_MAX; // no /proc/meminfo: no RAM cut e.reserve = std::max(kLockReserveMinBytes, total / kLockReserveShareDiv); return e; +#endif } // Steps 2 and 3: how many bytes of each part are to be locked (the budget handed out in order, page-sized pieces); returns the total. @@ -122,9 +145,15 @@ inline uint64_t plan_lock(const std::vector& parts, const LockEnv& env return total; } +#ifdef _WIN32 +inline int default_mlock(const void*, size_t) { errno = ENOSYS; return -1; } +#else +inline int default_mlock(const void* p, size_t n) { return ::mlock(p, n); } +#endif + // Step 4 and the locking: LOCKERS threads, each locks its piece of the planned range and then reads in its piece of the rest (a cold file is read 2x faster // by 16 threads side by side than by one; tools/stage_test.cpp). A part's `locked` is the length of the planned prefix whose pieces all succeeded in a row. -inline LockOutcome lock_parts(std::vector& parts, LockEnv env, MlockFn fn = ::mlock) { +inline LockOutcome lock_parts(std::vector& parts, LockEnv env, MlockFn fn = default_mlock) { constexpr int LOCKERS = 16; LockOutcome out; out.env = env; diff --git a/engine/src/split/src/model.cpp b/engine/src/split/src/model.cpp index b5dc854504..f5c2eed68f 100644 --- a/engine/src/split/src/model.cpp +++ b/engine/src/split/src/model.cpp @@ -13,11 +13,19 @@ #include +#ifdef _WIN32 +#ifndef NOMINMAX +#define NOMINMAX +#endif +#include +#include +#else #include #include #include #include +#endif #include #include @@ -40,6 +48,7 @@ void ck(cudaError_t e, const char* what) { if (e != cudaSuccess) throw std::runtime_error(std::string(what) + ": " + cudaGetErrorString(e)); } +#if !FNX_HOSTRING && !defined(_WIN32) // a card's PCI address in sysfs's spelling std::string card_bdf(int dev) { char bus[32]; @@ -90,6 +99,7 @@ void check_bar1(int dev, const std::string& bdf, const std::string& dir, const c if (bad) throw std::runtime_error("card " + std::to_string(dev) + ": cannot read " + path); require_bar1_covers(dev, bdf, prop.name, bar1_bytes(text, path), prop.totalGlobalMem, NCARD); } +#endif // the Makefile passes the arch the kernels were compiled for (ARCH): a default here would let a card of another one // run them through the driver's PTX compiler unchecked #ifndef FNX_ARCH @@ -891,16 +901,44 @@ struct MtpFiles { std::map t; void* base = nullptr; size_t size = 0; +#ifdef _WIN32 + void* hfile = nullptr; + void* hmap = nullptr; +#endif std::vector gate_b, up_b, down_b; // the experts' blocks: [512][640][2560], [512][640][2560], [512][2560][640] uint32_t etype = T_Q4_0; Tensor gate, up, down; explicit MtpFiles(const std::string& dir) { +#ifdef _WIN32 + HANDLE hf = CreateFileA((dir + "/dense.bin").c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); + if (hf == INVALID_HANDLE_VALUE) throw std::runtime_error("mtp: cannot open " + dir + "/dense.bin"); + LARGE_INTEGER fsz{}; + if (!GetFileSizeEx(hf, &fsz) || fsz.QuadPart <= 0) { + CloseHandle(hf); + throw std::runtime_error("mtp: cannot stat " + dir + "/dense.bin"); + } + HANDLE hm = CreateFileMappingA(hf, nullptr, PAGE_READONLY, 0, 0, nullptr); + if (!hm) { + CloseHandle(hf); + throw std::runtime_error("mtp: cannot map dense.bin"); + } + base = MapViewOfFile(hm, FILE_MAP_READ, 0, 0, 0); + if (!base) { + CloseHandle(hm); + CloseHandle(hf); + throw std::runtime_error("mtp: cannot map dense.bin"); + } + hfile = (void*) hf; + hmap = (void*) hm; + size = (size_t) fsz.QuadPart; +#else const int fd = ::open((dir + "/dense.bin").c_str(), O_RDONLY); if (fd < 0) throw std::runtime_error("mtp: cannot open " + dir + "/dense.bin"); size = (size_t) lseek(fd, 0, SEEK_END); base = mmap(nullptr, size, PROT_READ, MAP_PRIVATE, fd, 0); ::close(fd); if (base == MAP_FAILED) throw std::runtime_error("mtp: cannot map dense.bin"); +#endif std::ifstream idx(dir + "/dense.txt"); if (!idx) throw std::runtime_error("mtp: cannot open " + dir + "/dense.txt"); std::string line; @@ -934,7 +972,15 @@ struct MtpFiles { std::fprintf(stderr, "fnx: draft layer experts %s\n", ex.c_str()); views(); } - ~MtpFiles() { if (base) munmap(base, size); } + ~MtpFiles() { +#ifdef _WIN32 + if (base) UnmapViewOfFile(base); + if (hmap) CloseHandle((HANDLE) hmap); + if (hfile && hfile != INVALID_HANDLE_VALUE) CloseHandle((HANDLE) hfile); +#else + if (base) munmap(base, size); +#endif + } const Tensor& operator[](const std::string& n) const { const auto it = t.find(n); if (it == t.end()) throw std::runtime_error("mtp: " + n + " is missing"); @@ -1132,8 +1178,14 @@ Mtp::Mtp(const Model& m, const std::string& dir, const std::string& vocab_file) { std::FILE* f = std::fopen(vocab_file.c_str(), "rb"); if (!f) throw std::runtime_error("mtp: cannot open " + vocab_file); +#ifdef _WIN32 + struct _stat64 stb{}; + const int st_ok = _fstat64(_fileno(f), &stb); +#else struct stat stb{}; - if (fstat(fileno(f), &stb) != 0 || stb.st_size % 4 != 0) { + const int st_ok = fstat(fileno(f), &stb); +#endif + if (st_ok != 0 || stb.st_size % 4 != 0) { std::fclose(f); throw std::runtime_error("mtp: " + vocab_file + " is not whole int32 token ids (" + std::to_string((long long) stb.st_size) + " bytes)"); } @@ -1180,8 +1232,14 @@ Mtp::Mtp(const Model& m, const std::string& dir, const std::string& vocab_file) const std::string vf = vocab_file.empty() ? dir + "/draft_vocab.bin" : vocab_file; std::FILE* f = std::fopen(vf.c_str(), "rb"); if (!f) throw std::runtime_error("mtp: cannot open " + vf); +#ifdef _WIN32 + struct _stat64 stb{}; + const int st_ok = _fstat64(_fileno(f), &stb); +#else struct stat stb{}; - if (fstat(fileno(f), &stb) != 0 || stb.st_size % 4 != 0) { + const int st_ok = fstat(fileno(f), &stb); +#endif + if (st_ok != 0 || stb.st_size % 4 != 0) { std::fclose(f); throw std::runtime_error("mtp: " + vf + " is not whole int32 token ids (" + std::to_string((long long) stb.st_size) + " bytes)"); } diff --git a/engine/src/split/tools/sfnx.cpp b/engine/src/split/tools/sfnx.cpp index e4fdd124e8..11bf62e5aa 100644 --- a/engine/src/split/tools/sfnx.cpp +++ b/engine/src/split/tools/sfnx.cpp @@ -95,7 +95,11 @@ Args parse_args(int argc, char** argv) { const std::string s = val(); if (const char* e = std::getenv("FNX_ROPE_SCALE"); e && s != e) throw std::runtime_error("--rope-scale " + s + " and FNX_ROPE_SCALE=" + e + " disagree"); +#ifdef _WIN32 + _putenv_s("FNX_ROPE_SCALE", s.c_str()); +#else ::setenv("FNX_ROPE_SCALE", s.c_str(), 1); +#endif } else if (k == "--vision") a.vision = true; else throw std::runtime_error("unknown argument " + k); diff --git a/engine/sycl/src/program/generate.cpp b/engine/sycl/src/program/generate.cpp index 801d1c19ee..0af4884788 100644 --- a/engine/sycl/src/program/generate.cpp +++ b/engine/sycl/src/program/generate.cpp @@ -2256,7 +2256,7 @@ int main(int argc, char **argv) try { 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) - if (!split_auto || stage_dev(d)) split_devs.push_back(d); + if (stage_dev(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) { @@ -2272,7 +2272,7 @@ int main(int argc, char **argv) try { 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; + ok = split_devs[i] > 0 && split_devs[i] < n_dev && stage_dev(split_devs[i]); for (size_t j = 0; ok && j < i; ++j) ok = split_devs[i] != split_devs[j]; } } @@ -8582,17 +8582,25 @@ int main(int argc, char **argv) try { }; // --pipeline-windows: set while the tier adapts beside windows in flight (see its use in adapt) std::function adapt_fence; + // #6560: request thread owns drive.d.usage exclusively (no race with expert_pool_dispatch_multi's += 1.0f + // under --pipeline-windows 2); snapshot + heat + decay run on the request thread before spawning adapt(). + auto snapshot_usage = [&]() -> std::vector { + std::vector snap = drive.d.usage; + for (size_t i = 0; i < heat.size(); ++i) heat[i] += (double) snap[i]; + for (float& v : drive.d.usage) v *= o.adapt_decay; + return snap; + }; // the VRAM tier follows the conversation (the same rule as the speculative loop below) - auto adapt = [&]() -> bool { + auto adapt = [&](const std::vector& usage_snap) -> bool { if (!pending.empty()) return true; // the previous swaps are still in flight - if (remote_opt && !remote_opt->adapt(drive.d.usage, host_res, pending, o.adapt_swaps, *srcp)) return false; + if (remote_opt && !remote_opt->adapt(usage_snap, host_res, pending, o.adapt_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) { cand.clear(); vict.clear(); - const float* u = drive.d.usage.data() + l * g.n_expert; + const float* u = usage_snap.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)) cand.emplace_back(u[e], e); } @@ -8638,7 +8646,6 @@ int main(int argc, char **argv) try { dpct::get_in_order_queue().memcpy(mirror_table_d, tab.data(), tab.size() * 8).wait_and_throw(); res_upload(); } - for (float& value : drive.d.usage) value *= o.adapt_decay; return true; } // the copies back read the cache of the card that owns each layer (see resident_stage_swaps) @@ -8758,21 +8765,16 @@ int main(int argc, char **argv) try { const strata::core::OnDevice on(st->dev); dpct::sync_barrier(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(), + if (!peer.adapt(usage_snap.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 @@ -11750,8 +11752,9 @@ int main(int argc, char **argv) try { pl_apply(); if (!drive.d.usage.empty() && o.adapt_every > 0 && (rounds % o.adapt_every) == 0 && pending.empty() && !exch_wait) { + auto usnap = snapshot_usage(); pl_adapt_done = false; - pl_adapt_thr = std::thread([&] { pl_adapt_ok = adapt(); pl_adapt_done = true; }); + pl_adapt_thr = std::thread([&, u = std::move(usnap)] { pl_adapt_ok = adapt(u); pl_adapt_done = true; }); } return true; }; @@ -12487,9 +12490,10 @@ int main(int argc, char **argv) try { strata::workload_trace::Scope commit_trace("decode.commit_emit", nullptr, T); std::thread adapt_thr; // the adaptive tier beside the commit and the draft (as in generate) bool adapt_ok = true; - if (!drive.d.usage.empty() && !ajob && ((rounds + 1) % o.adapt_every) == 0) { - if (sycl_mirror_adapt()) adapt_ok = adapt(); - else adapt_thr = std::thread([&] { adapt_ok = adapt(); }); + if (!drive.d.usage.empty() && !ajob && pending.empty() && ((rounds + 1) % o.adapt_every) == 0) { + auto usnap = snapshot_usage(); + if (sycl_mirror_adapt()) adapt_ok = adapt(usnap); + else adapt_thr = std::thread([&, u = std::move(usnap)] { adapt_ok = adapt(u); }); } if (sycl_mirror_adapt() && !adapt_ok) { std::printf("ERR SYCL mirror adaptive exchange failed\n"); return 1; } if (!ver.commit(a + 1, err)) { @@ -13538,7 +13542,7 @@ int main(int argc, char **argv) try { // 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 { + auto adapt = [&](const std::vector& usage_snap) -> 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 @@ -13558,7 +13562,7 @@ int main(int argc, char **argv) try { for (int64_t l = 0; l < g.n_layers; ++l) { cand.clear(); vict.clear(); - const float* u = drive.d.usage.data() + l * g.n_expert; + const float* u = usage_snap.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)) cand.emplace_back(u[e], e); } @@ -13629,7 +13633,6 @@ int main(int argc, char **argv) try { 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; @@ -13865,8 +13868,11 @@ int main(int argc, char **argv) try { // 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_every) == 0) - adapt_thr = std::thread([&] { adapt_ok = adapt(); }); + if (!drive.d.usage.empty() && pending.empty() && ((rounds + 1) % o.adapt_every) == 0) { + std::vector usnap = drive.d.usage; + for (float& v : drive.d.usage) v *= o.adapt_decay; + adapt_thr = std::thread([&, u = std::move(usnap)] { adapt_ok = adapt(u); }); + } if (!ver.commit(a + 1, err)) { if (adapt_thr.joinable()) adapt_thr.join(); std::fprintf(stderr, "strata generate: %s\n", err.c_str()); diff --git a/engine/tests/core/residency_trim_test.cpp b/engine/tests/core/residency_trim_test.cpp index 2a26851de7..d644c87cf6 100644 --- a/engine/tests/core/residency_trim_test.cpp +++ b/engine/tests/core/residency_trim_test.cpp @@ -30,6 +30,23 @@ int main() { // no slot left: every resident entry goes CHECK(evict_slots_past(res, 0, ev) == 2 && ev.size() == 6); for (const int32_t s : res) CHECK(s == kNotResident); + + // #533 range overload: under a layer split each card trims only its own layers [lo, hi); slot numbers overlap across cards. + std::vector t = {5, 0, 7, kNotResident, 9, 4, 6, 1}; // n_expert=2 -> layer=i/2: L0{0,1} L1{2,3} L2{4,5} L3{6,7} + std::vector> er; + CHECK(evict_slots_past(t, 3, 1, 3, 2, er) == 3); // card owns layers [1,3): in-range idx{2,4,5} sit past live=3 -> taken (idx3 not-resident stays) + CHECK(er.size() == 3 && er[0] == std::make_pair(2, 7) && er[1] == std::make_pair(4, 9) && er[2] == std::make_pair(5, 4)); // table order within the range + CHECK(t[0] == 5 && t[6] == 6); // another card's past-slot experts (idx0 L0, idx6 L3) are left alone + CHECK(t[1] == 0 && t[2] == kNotResident && t[4] == kNotResident && t[5] == kNotResident && t[7] == 1); // in-range taken; below-live and not-resident kept + + std::vector g = {1, 9, 2, 8}; // n_expert=1 -> layer=i + std::vector> eb; + CHECK(evict_slots_past(g, 5, 0, 2, 1, eb) == 1); // [0,2): only idx1 (9>=live) taken; hi is exclusive so idx3 stays even though >=live + CHECK(eb.size() == 1 && eb[0] == std::make_pair(1, 9)); + CHECK(g[1] == kNotResident && g[3] == 8); // boundary: the index at hi (and past it) is untouched + + std::vector> ef; // the whole range reproduces the one-GPU behaviour + CHECK(evict_slots_past(g, 5, 0, INT64_MAX, 1, ef) == 1 && ef.size() == 1); // takes what the bounded call left: idx3 if (failed) { std::fprintf(stderr, "residency_trim_test: %d failed\n", failed); return 1; diff --git a/engine/tests/program/split_rules_test.cpp b/engine/tests/program/split_rules_test.cpp index 2a06b77864..3fddcc7866 100644 --- a/engine/tests/program/split_rules_test.cpp +++ b/engine/tests/program/split_rules_test.cpp @@ -4,6 +4,7 @@ #include #include "strata/program/split_rules.hpp" +#include "strata/program/stage_reserve.hpp" using namespace strata::program::split_rules; @@ -158,6 +159,51 @@ int main() { CHECK(trim_credit(0, 0) == 0); CHECK(trim_credit(0, -5) == 0); // trim off: trim_frees is 0 (never negative); a negative figure is no credit } + // The gate-off fallback keeps to placements whose later stages hold an expert slot. 2x 8 GB (RTX 3060 Ti + RTX 3070 Ti), + // 48 layers, serve with DFlash2 on CUDA1 and --vram-reserve-later-mib 5800: no placement could start the prompt path, so + // auto chose by decode speed alone, and the PCIe probe decided K. CUDA0 read 10.6-12.6 GB/s and CUDA1 2.9, a gap of + // 3.66-4.34 on both sides of kLinkScaleMin: below it K=45 (CUDA1 runs 45-47), which stopped at "CUDA1 expert cache: no + // room"; above it K=47, which loaded with 28 slots. + { + const int64_t MiB = 1 << 20; + CHECK(link_miss_scale({10.6, 2.9})[1] == 1.0); // gap 3.66: unscaled, K=45 is the faster + CHECK(link_miss_scale({12.6, 2.9})[1] > 4.0); // gap 4.34: scaled, K=47 is the faster + // CUDA1's room before its session carve, planned as the cache step will size it: 7578 MiB free, 5800 + 256 + 96 + // reserved, 1000 for the drafter and the head, DFlash2's drafter over that (112) and what it binds after the cache + // (160 MiB in serve) + strata::program::stage_reserve::Inputs in; + in.base_reserve_mib = 5800 + 256; + in.later = true; + in.drafter = true; + in.df2_bind_mib = strata::program::stage_reserve::df2_search_mib(true); + const int64_t room = strata::program::stage_reserve::room_bytes(7578 * MiB, in); + // each placement's session and weights on CUDA1: the search logged 143 MiB left at K=45 and 294 at K=47 of 426, and + // (with the after-cache term alone booked) 57 at K=46 of 266 + const int64_t carve45 = (426 - 143) * MiB, carve46 = (266 - 57) * MiB, carve47 = (426 - 294) * MiB; + const int64_t slot = 13 * MiB / 10; // an expert slot, ~1.3 MiB + auto held = [&](int64_t k) { // CUDA0's cache held 400 slots at either K + const int64_t left = room - (k == 45 ? carve45 : k == 46 ? carve46 : carve47); + return std::vector{400, left > 0 ? left / slot : 0}; + }; + CHECK(later_stage_empty(held(45))); // K=45: -129 MiB planned (the cache step found 0.00 GiB, 6.06 GiB free) + CHECK(later_stage_empty(held(46))); // K=46: -55 MiB planned (the cache step found 0.00 GiB, 6.13 GiB free) + CHECK(!later_stage_empty(held(47))); // K=47: 22 MiB planned (the cache step found 0.04 GiB: 28 slots) + // the fallback's pick: the fastest whose later stages hold a slot, else the fastest + auto pick = [&](const std::vector& by_speed) { + for (const int64_t k : by_speed) + if (!later_stage_empty(held(k))) return k; + return by_speed.front(); + }; + CHECK(pick({45, 46, 47}) == 47); // gap 3.66 + CHECK(pick({46, 45, 47}) == 47); // the pick with the after-cache term alone booked (gap 4.15, STRATA_SPLIT_LINK_MIN=4.5) + CHECK(pick({47, 46, 45}) == 47); // gap 4.34 + std::printf("split_rules_test: DFlash2 on CUDA1, gate off: K=45 holds %lld slots, K=46 %lld, K=47 %lld; pick K=%lld at " + "gap 3.66, K=%lld at 4.34\n", (long long) held(45)[1], (long long) held(46)[1], (long long) held(47)[1], + (long long) pick({45, 46, 47}), (long long) pick({47, 46, 45})); + // nothing with a slot: the pick is as before; the first stage and a single card are not this rule's + CHECK(later_stage_empty({400, 0}) && later_stage_empty({400, 5, 0})); + CHECK(!later_stage_empty({0, 5}) && !later_stage_empty({0}) && !later_stage_empty({})); + } if (failed == 0) std::printf("split_rules_test: ok\n"); return failed ? 1 : 0; } diff --git a/engine/tests/program/stage_reserve_test.cpp b/engine/tests/program/stage_reserve_test.cpp index f0e090131b..81d960b6e2 100644 --- a/engine/tests/program/stage_reserve_test.cpp +++ b/engine/tests/program/stage_reserve_test.cpp @@ -72,6 +72,24 @@ int main() { in.later = true; check(reserve_mib(in) == 1496, "the workaround reserve: 1400 + 96"); } + // DFlash2 on the last card of a layer split: the cache step takes what it binds after the cache (its draft logits and, in + // serve, the prompt staging) out of that stage's room, so the plan books it on the drafter's stage only. 2x 8 GB (RTX + // 3060 Ti + RTX 3070 Ti), --vram-reserve-later-mib 5800, CUDA1 7578 MiB free at the search ("0.42 GiB free before its + // session carve") + { + check(df2_after_mib(true) == 160 && df2_after_mib(false) == 48, "DFlash2 binds 48 MiB after the cache, 160 in serve"); + Inputs in; + in.base_reserve_mib = 5800 + 256; + in.later = true; + in.drafter = true; + const int64_t free_b = int64_t(7578) << 20; + check((room_bytes(free_b, in) >> 20) == 426, "without DFlash2 the last card's plan is unchanged: 426 MiB"); + check(df2_search_mib(true) == 112 + 160, "the search books DFlash2's drafter over kDrafterMib and its after-cache bind"); + in.df2_bind_mib = df2_search_mib(true); + check((room_bytes(free_b, in) >> 20) == 154, "with DFlash2 the last card's plan keeps 272 MiB more: 154 MiB"); + in.drafter = false; + check(reserve_mib(in) == 5800 + 256 + 96, "a stage without the drafter books no DFlash2 term"); + } std::printf("stage_reserve_test: %ld cases, %s\n", cases, g_fail ? "FAIL" : "PASS"); return g_fail ? 1 : 0; } diff --git a/terminal/tools/hip/build_windows.bat b/terminal/tools/hip/build_windows.bat index 12101cac02..6dd0132149 100644 --- a/terminal/tools/hip/build_windows.bat +++ b/terminal/tools/hip/build_windows.bat @@ -21,6 +21,7 @@ rem STRATA_GGML_DIR optional override (kept for two releases): a llama.cp rem STRATA_ROCM_KEEP 1 = use the ROCM_VENV as it is (no pip install, even when its archs differ from STRATA_HIP_ARCHS) rem STRATA_VISION_HIP_ARCHS the GPU reader's archs (default: STRATA_HIP_ARCHS; about 70 MB of the zip per arch) rem STRATA_NO_VISION 1 = skip the two picture readers (strata-vision.exe for the CPU, strata-vision-hip.exe for the GPU) +rem STRATA_NO_SPLIT 1 = skip the 2-GPU split engine (strata-split-2-amd.exe) rem STRATA_CMAKE_EXTRA extra cmake configure arguments (for example -DSTRATA_WINDOW_MAX_T=8) setlocal EnableDelayedExpansion for %%I in ("%~dp0..\..\..") do set "SRC=%%~fI" @@ -70,9 +71,12 @@ set "PATH=%ROCM%\bin;%ROCM%\lib\llvm\bin;%PATH%" rem ---- 3. configure + build (STRATA_PORTABLE: the CPU kernels for an AVX2 baseline, as in the NVIDIA zip) set "GGML=" if defined STRATA_GGML_DIR set "GGML=-DSTRATA_GGML_DIR=%STRATA_GGML_DIR:\=/%" +set "BUILD_SPLIT=ON" +if "%STRATA_NO_SPLIT%"=="1" set "BUILD_SPLIT=OFF" if not exist "%BUILD_DIR%\build.ninja" ( cmake -G Ninja -S "%SRC%\engine" -B "%BUILD_DIR%" -DCMAKE_BUILD_TYPE=Release ^ -DSTRATA_ENABLE_HIP=ON -DSTRATA_ENABLE_CUDA=OFF -DSTRATA_BUILD_TESTS=%TESTS% ^ + -DSTRATA_BUILD_SPLIT=%BUILD_SPLIT% ^ -DSTRATA_NATIVE_EXPERTS=ON -DSTRATA_PORTABLE=ON "-DCMAKE_HIP_ARCHITECTURES=%STRATA_HIP_ARCHS%" ^ "-DCMAKE_C_COMPILER=%ROCM_F%/lib/llvm/bin/clang.exe" "-DCMAKE_CXX_COMPILER=%ROCM_F%/lib/llvm/bin/clang++.exe" ^ "-DCMAKE_HIP_COMPILER=%ROCM_F%/lib/llvm/bin/clang++.exe" "-DCMAKE_HIP_COMPILER_ROCM_ROOT=%ROCM_F%" ^ @@ -83,6 +87,15 @@ if "%TESTS%"=="ON" ( cmake --build "%BUILD_DIR%" || exit /b 1 ) else ( cmake --build "%BUILD_DIR%" --target strata strata-device || exit /b 1 + if "%BUILD_SPLIT%"=="ON" ( + findstr /c:"strata-split-2" "%BUILD_DIR%\build.ninja" >nul 2>nul && ( + cmake --build "%BUILD_DIR%" --target strata-split-2 || exit /b 1 + ) + ) +) +set "SPLIT_ARGS=" +if exist "%BUILD_DIR%\src\split\strata-split-2.exe" ( + set "SPLIT_ARGS=--split-2 %BUILD_DIR%\src\split\strata-split-2.exe" ) rem ---- 3b. the picture readers (terminal/tools/vision, Strata's own tower): strata-vision.exe on the CPU (MSVC, portable: the @@ -109,7 +122,7 @@ if not "%STRATA_NO_VISION%"=="1" ( rem ---- 4. the zip: the programs, the ROCm DLLs they load (+ rocBLAS/hipBLASLt kernels for these archs), licenses "%ROCM_VENV%\Scripts\python.exe" "%SRC%\terminal\tools\hip\package_windows.py" --build "%BUILD_DIR%" --rocm "%ROCM%" ^ - --archs "%STRATA_HIP_ARCHS%" --rocm-version "%STRATA_ROCM_VERSION%" --out "%DIST_DIR%" !VISION_ARGS! || exit /b 1 + --archs "%STRATA_HIP_ARCHS%" --rocm-version "%STRATA_ROCM_VERSION%" --out "%DIST_DIR%" !VISION_ARGS! !SPLIT_ARGS! || exit /b 1 echo. echo Done: %DIST_DIR%\strata-windows-x64-hip.zip endlocal diff --git a/terminal/tools/hip/package_windows.py b/terminal/tools/hip/package_windows.py index e06336138d..fc0ed28e5c 100644 --- a/terminal/tools/hip/package_windows.py +++ b/terminal/tools/hip/package_windows.py @@ -88,6 +88,7 @@ def main() -> int: ap.add_argument("--out", required=True, type=Path) ap.add_argument("--vision-cpu", type=Path, help="strata-vision.exe built for the CPU (tools/vision, STRATA_PORTABLE=ON)") ap.add_argument("--vision-hip", type=Path, help="strata-vision-hip.exe built for the same archs (STRATA_VISION_HIP=ON)") + ap.add_argument("--split-2", type=Path, help="strata-split-2.exe built with STRATA_BUILD_SPLIT=ON (packaged as strata-split-2-amd.exe)") a = ap.parse_args() archs = [x for x in re.split(r"[;, ]+", a.archs) if x] rbin = a.rocm / "bin" @@ -98,13 +99,20 @@ def main() -> int: for p in PROGRAMS: shutil.copy2(a.build / p, stage / p) - readers = [(src, src.name) for src in (a.vision_cpu, a.vision_hip) if src is not None] - for src, name in readers: + extras: list[tuple[Path, str]] = [(src, src.name) for src in (a.vision_cpu, a.vision_hip) if src is not None] + split2 = a.split_2 + if split2 is None: + cand = a.build / "src" / "split" / "strata-split-2.exe" + if cand.is_file(): + split2 = cand + if split2 is not None and split2.is_file(): + extras.append((split2, "strata-split-2-amd.exe")) + for src, name in extras: shutil.copy2(src, stage / name) # the ROCm DLLs: the programs' imports, followed through the ROCm DLLs themselves rocm_dlls = {p.name.lower(): p for p in rbin.glob("*.dll")} - need, todo, crt = [], [stage / p for p in PROGRAMS] + [stage / n for _, n in readers] + [rbin / d for d in DYNAMIC], set() + need, todo, crt = [], [stage / p for p in PROGRAMS] + [stage / n for _, n in extras] + [rbin / d for d in DYNAMIC], set() while todo: f = todo.pop() for name in imports(objdump, f): @@ -179,6 +187,8 @@ def main() -> int: meta.update({"vision": "cpu", "vision_cpu": a.vision_cpu.name}) if a.vision_hip is not None: meta.update({"vision": "gpu", "vision_gpu": a.vision_hip.name, "vision_archs": archs}) + if split2 is not None and split2.is_file(): + meta["split"] = ["strata-split-2-amd.exe"] (stage / "BUILD.json").write_text(json.dumps(meta, indent=1), encoding="utf-8") # the hipBLASLt tuning tables of tools/hip for these archs and exactly this hipBLASLt version, in tuning/ (strata_control/hipblaslt_tuning.py): # the engine start points STRATA_HIPBLASLT_TUNING at the one for the card; an arch without a table keeps plain hipBLAS