From 7a7c568b9a4d9e8c6c858eb16804e17fdfb2e01e Mon Sep 17 00:00:00 2001 From: Evan Date: Tue, 6 Oct 2026 15:33:15 +0200 Subject: [PATCH 1/9] resident split: a test that the RAM copy keeps each stage's lend region (red: FileExpertSource has no stage_lend_regions, and no append_stage_lend_regions) --- CMakeLists.txt | 15 ++ tests/core/file_expert_source_test.cpp | 46 +++++ tests/core/split_lend_complement_test.cpp | 219 ++++++++++++++++++++++ 3 files changed, 280 insertions(+) create mode 100644 tests/core/split_lend_complement_test.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 6e0ce1c4..b93a5a4c 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -468,6 +468,21 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) target_link_libraries(vmm_test PRIVATE strata_engine) add_test(NAME vmm_test COMMAND vmm_test) set_tests_properties(vmm_test PROPERTIES TIMEOUT 60) + # The resident RAM mode with a layer split: the copy keeps each stage's lend region, and the experts the + # prompt path borrows are served from RAM (the file source reads none of them). The device calls are + # wrapped - conversation_transfer_test's pattern - and `pin = false` keeps the copy pageable, so this + # runs on a CPU-only PC. + if(NOT STRATA_ENABLE_HIP AND UNIX AND NOT APPLE AND CMAKE_CXX_COMPILER_ID MATCHES "GNU|Clang") + add_executable(split_lend_complement_test tests/core/split_lend_complement_test.cpp) + target_link_libraries(split_lend_complement_test PRIVATE strata_engine) + target_link_options(split_lend_complement_test PRIVATE + -Wl,--wrap=cudaMalloc -Wl,--wrap=cudaFree -Wl,--wrap=cudaMemset -Wl,--wrap=cudaMemcpy + -Wl,--wrap=cudaMemcpyAsync -Wl,--wrap=cudaStreamSynchronize -Wl,--wrap=cudaDeviceSynchronize + -Wl,--wrap=cudaGetLastError -Wl,--wrap=cudaGetDevice -Wl,--wrap=cudaSetDevice + -Wl,--wrap=cudaMemGetInfo -Wl,--wrap=cudaHostAlloc -Wl,--wrap=cudaFreeHost) + add_test(NAME split_lend_complement_test COMMAND split_lend_complement_test) + set_tests_properties(split_lend_complement_test PROPERTIES ENVIRONMENT "CUDA_VISIBLE_DEVICES=-1" TIMEOUT 120) + endif() endif() # #477: the learned expert profile (--expert-profile-save): its order and make_profile.py's file format (CPU only) if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/tests/core/expert_profile_save_test.cpp") diff --git a/tests/core/file_expert_source_test.cpp b/tests/core/file_expert_source_test.cpp index 975f42fa..321c623c 100644 --- a/tests/core/file_expert_source_test.cpp +++ b/tests/core/file_expert_source_test.cpp @@ -291,6 +291,51 @@ void test_resident_lend_region() { require(choose_resident_keep_from({}, 0, 0, 0) == 0, "an empty cache"); } +void test_split_lend_regions() { + using namespace strata::core::detail; + // two layers, three experts; a layer-0 blob is 5 bytes and a layer-1 blob 3. The plan under + // construction already holds the (0,1) expert (an expert no cache holds); stage 0's region lends + // (0,2) and (0,1) from its highest slots, stage 1's lends (1,2), (1,0), (1,1) in that order. + const std::vector blobs{5, 3}; + const std::vector>> regions = {{{0, 2}, {0, 1}}, {{1, 2}, {1, 0}, {1, 1}}}; + std::string err; + std::vector offsets; + uint64_t bytes = 0; + + // room for everything: (0,1) is already in the copy and is passed over, not counted twice + offsets = {kNoCacheComplement, 0, kNoCacheComplement, kNoCacheComplement, kNoCacheComplement, kNoCacheComplement}; + bytes = 5; + require(append_stage_lend_regions(2, 3, blobs, offsets, bytes, 100, regions, err) == 4, + "both stage lend regions must be kept"); + require(bytes == 19 && + offsets == std::vector{kNoCacheComplement, 0, 5, 13, 16, 10}, + "the stage lend regions got wrong compact offsets"); + + // the cap is the whole copy's: the stage-0 walk fits (0,2) and stage 1 stops at the first pair that + // does not fit; that stage's rest stays on the file + offsets = {kNoCacheComplement, 0, kNoCacheComplement, kNoCacheComplement, kNoCacheComplement, kNoCacheComplement}; + bytes = 5; + require(append_stage_lend_regions(2, 3, blobs, offsets, bytes, 10, regions, err) == 1, "cap 10 keeps only (0,2)"); + require(bytes == 10 && offsets[2] == 5 && offsets[3] == kNoCacheComplement && offsets[5] == kNoCacheComplement, + "the walk placed experts past the cap"); + + // (0,2)'s 5 bytes do not fit in the 4 left: stage 0 keeps nothing, and stage 1's own walk still runs - + // its (1,2) fits, its (1,0) stops that stage + offsets = {kNoCacheComplement, 0, kNoCacheComplement, kNoCacheComplement, kNoCacheComplement, kNoCacheComplement}; + bytes = 5; + require(append_stage_lend_regions(2, 3, blobs, offsets, bytes, 9, regions, err) == 1, + "a stage refused at the cap must not stop the next stage's walk"); + require(bytes == 8 && offsets[2] == kNoCacheComplement && offsets[5] == 5 && offsets[3] == kNoCacheComplement, + "the refused stage's experts entered the copy, or the next stage's did not"); + + // a pair outside the geometry is an error, and the plan is left untouched: validate before appending + offsets = {kNoCacheComplement, 0, kNoCacheComplement, kNoCacheComplement, kNoCacheComplement, kNoCacheComplement}; + bytes = 5; + require(append_stage_lend_regions(2, 3, blobs, offsets, bytes, 100, {{{0, 2}, {2, 0}}}, err) == -1 && + !err.empty() && bytes == 5 && offsets[2] == kNoCacheComplement, + "an out-of-range lend-region pair was accepted, or a rejected walk touched the plan"); +} + void test_resident_exchange() { using namespace strata::core; using namespace strata::core::detail; @@ -686,6 +731,7 @@ int main(int argc, char** argv) { try { test_complement_plan(); test_resident_lend_region(); + test_split_lend_regions(); test_resident_exchange(); test_resident_memory_budget(); test_pin_pacing(); diff --git a/tests/core/split_lend_complement_test.cpp b/tests/core/split_lend_complement_test.cpp new file mode 100644 index 00000000..c6d5dd51 --- /dev/null +++ b/tests/core/split_lend_complement_test.cpp @@ -0,0 +1,219 @@ +// The resident RAM mode with a layer split: the compact copy holds the experts no stage's cache holds AND each +// stage's LEND REGION - the experts in the cache slots the prompt path borrows - so a prompt streams the +// borrowed experts from RAM instead of reading the model files through page faults. Runs on a CPU-only +// PC: the device calls are wrapped at the link (`--wrap` in CMakeLists.txt, conversation_transfer_test's +// pattern), the memory is ordinary memory, and `pin = false` keeps the copy pageable. +#include "strata/core/expert_source.hpp" +#include "strata/kernels/cpu/expert_layout.hpp" + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// ---- the wrapped device calls: memory is ordinary memory and every operation completes at once. +extern "C" cudaError_t __wrap_cudaMalloc(void** p, size_t n) { + *p = std::malloc(n); + return *p ? cudaSuccess : cudaErrorMemoryAllocation; +} +extern "C" cudaError_t __wrap_cudaFree(void* p) { std::free(p); return cudaSuccess; } +extern "C" cudaError_t __wrap_cudaMemset(void* d, int v, size_t n) { std::memset(d, v, n); return cudaSuccess; } +extern "C" cudaError_t __wrap_cudaMemcpy(void* d, const void* s, size_t n, cudaMemcpyKind k) { + std::memcpy(d, s, n); + return cudaSuccess; +} +extern "C" cudaError_t __wrap_cudaMemcpyAsync(void* d, const void* s, size_t n, cudaMemcpyKind k, cudaStream_t st) { + std::memcpy(d, s, n); + return cudaSuccess; +} +extern "C" cudaError_t __wrap_cudaStreamSynchronize(cudaStream_t st) { return cudaSuccess; } +extern "C" cudaError_t __wrap_cudaDeviceSynchronize(void) { return cudaSuccess; } +extern "C" cudaError_t __wrap_cudaGetLastError(void) { return cudaSuccess; } +extern "C" cudaError_t __wrap_cudaGetDevice(int* d) { *d = 0; return cudaSuccess; } +extern "C" cudaError_t __wrap_cudaSetDevice(int d) { return cudaSuccess; } +extern "C" cudaError_t __wrap_cudaMemGetInfo(size_t* free_b, size_t* total_b) { + *free_b = 64ull << 30; + *total_b = 128ull << 30; + return cudaSuccess; +} +extern "C" cudaError_t __wrap_cudaHostAlloc(void** p, size_t n, unsigned f) { + *p = std::malloc(n); + return *p ? cudaSuccess : cudaErrorMemoryAllocation; +} +extern "C" cudaError_t __wrap_cudaFreeHost(void* p) { std::free(p); return cudaSuccess; } + +namespace fs = std::filesystem; + +namespace { + +constexpr int64_t kLayers = 2; // stage 0 owns layer 0, stage 1 owns layer 1 (the split's `claimed` layers) +constexpr int64_t kExperts = 4; + +void require(bool ok, const std::string& message) { + if (!ok) throw std::runtime_error(message); +} + +struct TempDirectory { + fs::path path; + + explicit TempDirectory(const fs::path& base = fs::temp_directory_path()) { + const auto stamp = std::chrono::steady_clock::now().time_since_epoch().count(); + path = base / ("strata-split-lend-test-" + std::to_string(stamp)); + fs::create_directories(path); + } + + ~TempDirectory() { + std::error_code ignored; + fs::remove_all(path, ignored); + } +}; + +const uint8_t truth_byte(int64_t l, int64_t e, size_t i) { + return (uint8_t) ((i * 131u + (size_t) (l * kExperts + e) * 37u) ^ (i >> 8)); +} + +// one fully-built fixture: experts.bin written, the source open, both stage caches open with their +// own layer's experts admitted and filled (highest slot = highest expert, as the +// cache fills from slot 0 up) +struct Rig { + std::vector> truth; // [layer * kExperts + expert] + TempDirectory dir; + strata::core::FileExpertSource src; + strata::core::ExpertCache stage0, stage1; // the two split stages' caches + size_t blob = 0; + + explicit Rig(const char* tag) { + std::string err; + require(strata::kernels::cpu::expert_layout_load(dir.path.string(), kLayers, kExperts, err), err); + blob = (size_t) strata::kernels::cpu::BLOB; + truth.resize((size_t) kLayers * kExperts); + { + std::ofstream out(dir.path / "experts.bin", std::ios::binary); + for (int64_t l = 0; l < kLayers; ++l) + for (int64_t e = 0; e < kExperts; ++e) { + std::vector& t = truth[(size_t) l * kExperts + e]; + t.resize(blob); + for (size_t i = 0; i < blob; ++i) t[i] = truth_byte(l, e, i); + out.write((const char*) t.data(), (std::streamsize) blob); + } + require((bool) out, std::string(tag) + ": fixture write failed"); + } + require(src.open(dir.path.string(), kLayers, kExperts, err), err); + // kExperts slots each: every layer of the stage, and the tail the prompt path borrows + require(stage0.open(kExperts, kLayers, kExperts, blob, err), err); + require(stage1.open(kExperts, kLayers, kExperts, blob, err), err); + for (int64_t e = 0; e < kExperts; ++e) { + const int32_t s0 = stage0.admit(0, e); + require(s0 >= 0 && stage0.fill_slot_blocking(s0, truth[(size_t) e].data(), err), err); + const int32_t s1 = stage1.admit(1, e); + require(s1 >= 0 && stage1.fill_slot_blocking(s1, truth[(size_t) kExperts + e].data(), err), err); + } + } + + // every expert of stage 1's cache, the way generate hands the later stages to pin_cache_complement + std::vector> stage1_pairs() const { + std::vector> pairs; + for (int64_t e = 0; e < kExperts; ++e) pairs.emplace_back(1, (int32_t) e); + return pairs; + } +}; + +// both stage caches hold everything of their layer: the complement - the experts NO cache +// holds - is empty, so before this feature the copy kept no bytes at all and every expert a prompt borrowed +// came back through page faults from the mapped files. +void test_split_lend_region_served_from_ram() { + Rig rig("split lend region"); + std::string err; + + // each stage lends its two highest slots to the prompt path: pairs listed highest slot first, + // as the borrowing takes them + rig.src.stage_lend_regions({{{0, 3}, {0, 2}}, {{1, 3}, {1, 2}}}); + require(rig.src.pin_cache_complement(rig.stage0, err, false, rig.stage1_pairs(), -1, 0, 0), err); + + require(rig.src.resident_bytes() == 4 * (uint64_t) rig.blob, + "the copy is the empty complement plus the two stages' lend regions"); + require(rig.src.resident_lent_slots() == 4, "the copy reports both stages' lend regions"); + for (int64_t l = 0; l < kLayers; ++l) + for (int64_t e = 0; e < kExperts; ++e) { + const bool in_a_cache = true; // every pair is held by some stage's cache: none is in the complement + require(rig.src.has_resident(l, e) == (e >= 2), "the copy holds exactly the two stages' lent experts"); + } + + // the borrowed experts are served from the RAM copy: the lookup resolves into the copy, the bytes match + // the file's, and not one read touched the file source + std::vector dst(rig.blob); + for (int64_t l = 0; l < kLayers; ++l) + for (int64_t e = 2; e < kExperts; ++e) { + require(rig.src.blob(l, e) == rig.src.resident_blob(l, e), "a lent expert is not served from the copy"); + require(rig.src.copy_blob(l, e, dst.data()) && + dst == rig.truth[(size_t) l * kExperts + e], + "the copy serves wrong bytes for a lent expert"); + } + require(rig.src.file_reads() == 0 && rig.src.file_read_bytes() == 0, + "the prompt path's borrowed experts came from the file source, not the RAM copy"); +} + +// a --resident-budget-gib smaller than the regions: the copy keeps the bytes it can - the same budget +// caps the region walk - and the experts past it keep the file fallback that reads the same bytes +void test_split_lend_region_budget() { + Rig rig("split lend region budget"); + std::string err; + + rig.src.stage_lend_regions({{{0, 3}, {0, 2}}, {{1, 3}, {1, 2}}}); + const uint64_t budget = 2 * (uint64_t) rig.blob; // room for one stage's region, not both + require(rig.src.pin_cache_complement(rig.stage0, err, false, rig.stage1_pairs(), -1, 0, budget), err); + + require(rig.src.resident_bytes() == budget, "the budget did not cap the stage lend regions"); + require(rig.src.resident_lent_slots() == 2, "the clamped regions kept the wrong count"); + require(rig.src.has_resident(0, 3) && rig.src.has_resident(0, 2), "the first stage's region was not kept"); + require(!rig.src.has_resident(1, 3) && !rig.src.has_resident(1, 2), "bytes past the budget entered the copy"); + + std::vector dst(rig.blob); + require(rig.src.copy_blob(0, 3, dst.data()) && dst == rig.truth[3], "wrong bytes from the region inside the cap"); + require(rig.src.file_reads() == 0, "an expert the copy holds was read from the file"); + require(rig.src.copy_blob(1, 3, dst.data()) && dst == rig.truth[kExperts + 3], + "the expert past the budget lost its file fallback"); + require(rig.src.file_reads() == 0 && rig.src.file_read_bytes() == (uint64_t) rig.blob, + "the expert past the budget was served by the file source, exactly one blob read"); +} + +// the #848 shape, with no stage regions set: with the later stage's pairs handed over as +// `additional_gpu_pairs` the copy keeps NOTHING (the complement is empty and the single lend region is off), so +// this is the state that measured 3.7 GB of NVMe reads over one 73K-token prompt on 2026-10-06 +void test_split_without_regions_keeps_nothing() { + Rig rig("split without regions"); + std::string err; + + require(rig.src.pin_cache_complement(rig.stage0, err, false, rig.stage1_pairs(), -1, 0, 0), err); + require(rig.src.complement_ready(), "the empty complement did not complete"); + require(rig.src.resident_bytes() == 0 && rig.src.resident_lent_slots() == 0, + "without stage regions the copy should hold no expert at all"); + for (int64_t l = 0; l < kLayers; ++l) + for (int64_t e = 0; e < kExperts; ++e) + require(!rig.src.has_resident(l, e), "an expert neither in a cache's complement region entered the copy"); +} + +} // namespace + +int main() { + try { + test_split_lend_region_served_from_ram(); + test_split_lend_region_budget(); + test_split_without_regions_keeps_nothing(); + std::cout << "split_lend_complement_test: PASS\n"; + return 0; + } catch (const std::exception& error) { + std::cerr << "split_lend_complement_test: " << error.what() << '\n'; + return 1; + } +} From aea9dc3ed83622be5b653b2f2d0e715ad4c02f9c Mon Sep 17 00:00:00 2001 From: Evan Date: Tue, 6 Oct 2026 15:41:07 +0200 Subject: [PATCH 2/9] resident split: pin_cache_complement keeps each stage's lend region in the RAM copy too (stage_lend_regions, append_stage_lend_regions) - the experts the prompt path borrows under a split streamed from the mapped files through page faults (3.7 GiB read for one 73K prompt, 1.5 s of a 3.9 s chunk on host staging, 2026-10-06 rig); one budget caps complement and regions, experts past it keep the file fallback --- include/strata/core/expert_source.hpp | 22 ++++++++ src/core/expert_source.cpp | 79 +++++++++++++++++++++++++++ 2 files changed, 101 insertions(+) diff --git a/include/strata/core/expert_source.hpp b/include/strata/core/expert_source.hpp index dfc249d8..c1b1ed02 100644 --- a/include/strata/core/expert_source.hpp +++ b/include/strata/core/expert_source.hpp @@ -124,6 +124,18 @@ int64_t choose_resident_keep_from(const std::vector& slot_bytes, uint6 /// (the caller copies out's bytes there). False, and nothing changed, unless `in` is in the copy and `out` is not. bool exchange_cache_complement(std::vector& offsets, size_t in, size_t out); +/// A layer split: add each stage's lend region to a plan built from the complement plus every stage's +/// cache (the `additional_gpu_pairs` shape). Each region lists one stage's (layer, expert) pairs, the +/// pairs in its cache's highest slots first - the slots the prompt path borrows, from the tail in. A pair +/// already in the plan is passed over; a stage's walk stops at the first pair that does not fit `cap_bytes` +/// and the NEXT stage's walk still runs (the pairs past the cap keep the mapped-file fallback they had). +/// Returns the pairs added, or -1 - leaving the plan untouched - when a pair is outside the geometry or a +/// region repeats one. +int64_t append_stage_lend_regions(int64_t n_layers, int64_t n_expert, const std::vector& layer_blob_bytes, + std::vector& offsets, uint64_t& bytes, uint64_t cap_bytes, + const std::vector>>& regions, + std::string& err); + } // namespace detail @@ -516,6 +528,15 @@ public: const std::vector>& additional_gpu_pairs = {}, int64_t lend_from_slot = -1, uint64_t headroom_bytes = 8ull << 30, uint64_t budget_bytes = 0, const std::vector>* rank = nullptr); + /// A layer split: the prompt path borrows the TAIL SLOTS of every stage's cache - CUDA0's own part + /// first, then every stage in order. Set these BEFORE `pin_cache_complement` to keep those slots' experts + /// in the RAM copy too: each region lists its stage's (layer, expert) pairs, the highest cache slot first, + /// as the borrowing takes them. Pairs past the budget keep the mapped-file fallback. Empty (the + /// default) keeps #848's shape: with `additional_gpu_pairs` the single lend region is off and the copy + /// holds only the complement. + void stage_lend_regions(std::vector>> regions) { + stage_lend_regions_ = std::move(regions); + } void close(); bool mapped() const { return base_ != nullptr; } @@ -776,6 +797,7 @@ private: bool complement_ready_ = false; uint64_t complement_locked_ = 0; ///< bytes held in the working set (pin refused) int64_t complement_lent_slots_ = 0; + std::vector>> stage_lend_regions_; ///< a split: each stage's lend region std::vector override_; ///< staged exchanges: an evicted expert read from its exchange buffer struct Exchange { size_t in, out; int64_t q; uint64_t bytes; }; std::vector staged_; diff --git a/src/core/expert_source.cpp b/src/core/expert_source.cpp index e4b46490..f92994fd 100644 --- a/src/core/expert_source.cpp +++ b/src/core/expert_source.cpp @@ -210,6 +210,46 @@ int64_t choose_resident_keep_from(const std::vector& slot_bytes, uint6 return keep; } +int64_t append_stage_lend_regions(int64_t n_layers, int64_t n_expert, const std::vector& layer_blob_bytes, + std::vector& offsets, uint64_t& bytes, uint64_t cap_bytes, + const std::vector>>& regions, + std::string& err) { + const size_t blobs = (size_t) (n_layers * n_expert); + if (n_layers <= 0 || n_expert <= 0 || layer_blob_bytes.size() != (size_t) n_layers || offsets.size() != blobs) { + err = "append_stage_lend_regions: the plan does not match the geometry"; + return -1; + } + std::vector> sorted; + for (const auto& region : regions) { // validate the whole request before touching the plan + for (const auto& pair : region) + if (pair.first < 0 || pair.first >= n_layers || pair.second < 0 || pair.second >= n_expert) { + err = "append_stage_lend_regions: a lend-region expert is outside the model"; + return -1; + } + sorted = region; + std::sort(sorted.begin(), sorted.end()); + for (size_t i = 1; i < sorted.size(); ++i) + if (sorted[i] == sorted[i - 1]) { + err = "append_stage_lend_regions: a stage's lend region repeats an expert"; + return -1; + } + } + int64_t kept = 0; + for (const auto& region : regions) { + for (const auto& pair : region) { + const size_t index = (size_t) pair.first * (size_t) n_expert + (size_t) pair.second; + if (offsets[index] != kNoCacheComplement) continue; // already in the copy: the complement, or a + // CUDA0 lend slot the region is asked to skip + const uint64_t b = layer_blob_bytes[(size_t) pair.first]; + if (b > cap_bytes - bytes) break; // this stage's rest keeps the file fallback + offsets[index] = bytes; + bytes += b; + ++kept; + } + } + return kept; +} + bool exchange_cache_complement(std::vector& offsets, size_t in, size_t out) { if (in == out || in >= offsets.size() || out >= offsets.size() || offsets[in] == kNoCacheComplement || offsets[out] != kNoCacheComplement) return false; @@ -2332,6 +2372,36 @@ bool FileExpertSource::pin_cache_complement( } } + // A layer split: generate hands the copy every stage's lend region (`stage_lend_regions`, set before the + // call). The prompt path borrows the tail slots of EVERY part's cache, and with `additional_gpu_pairs` + // non-empty the single lend region above is off - so without this the borrowed experts sat in neither + // VRAM nor RAM during a prompt and came back through page faults from the mapped shards: measured + // 2026-10-06 on an RTX 2000 Ada + 5060 Ti rig (17/48 split, IQ3_S mapped from the GGUF, --prefill auto, + // one 73K-token prompt) 3.7 GiB read from the NVMe for the one prompt (arena mode reads 1.1 GiB), and one + // 8192-token chunk spent 1.5 s of its 3.9 s on host staging (arena: 0.37 s). The regions walk each + // stage's highest slots first, as the borrowing does; the whole copy - complement and regions + // together - stays within one budget, and experts past it keep the file fallback they had. + int64_t stage_lent = 0; + uint64_t stage_lent_bytes = 0; + if (!stage_lend_regions_.empty()) { + if (budget == std::numeric_limits::max()) { // #403: the one reading, taken now + uint64_t physical = budget_physical, commit = budget_commit; + if (physical == 0 && !available_memory_bytes(physical, &commit)) { + err = "FileExpertSource: cannot determine available memory for the stage lend regions"; + return false; + } + const uint64_t available = std::min(physical, commit); + budget = available > headroom_bytes ? available - headroom_bytes : 0; + } + uint64_t cap = budget; // an explicit --resident-budget-gib caps the whole copy, regions included + if (budget_bytes > 0 && budget_bytes != kResidentWhatFits && budget_bytes < cap) cap = budget_bytes; + const uint64_t before = bytes; + stage_lent = detail::append_stage_lend_regions(n_layers_, n_expert_, layer_blob_bytes_, offsets, bytes, cap, + stage_lend_regions_, err); + if (stage_lent < 0) return false; + stage_lent_bytes = bytes - before; + } + void* arena = nullptr; const uint8_t* host = nullptr; const uint8_t* device = nullptr; @@ -2701,6 +2771,7 @@ bool FileExpertSource::pin_cache_complement( complement_locked_ = locked; complement_lock_off_ = lock_off; complement_lent_slots_ = lend ? n_slots - keep_from : 0; + complement_lent_slots_ += stage_lent; // and the split stages' regions: pairs the copy kept of them complement_ready_ = true; std::fprintf(stderr, "FileExpertSource: %s cache complement ready: resident %.2f GiB, pinned %.2f GiB in %.0f s%s%s\n", complement_pinned_ ? "mapped pinned" : pin ? "locked resident" : "pageable resident", @@ -2723,6 +2794,14 @@ bool FileExpertSource::pin_cache_complement( "cost 26%%). Free RAM or lower STRATA_RESIDENT_HEADROOM_GIB (now the RAM left free at start) and restart; " "the line above should read N of N.\n", missing, lendable, 100.0 * (double) missing / (double) std::max(1, lendable)); } + if (!stage_lend_regions_.empty()) { + int64_t offered = 0; + for (const auto& region : stage_lend_regions_) offered += (int64_t) region.size(); + std::fprintf(stderr, "FileExpertSource: the split stages lend %lld slots to the prompt path: %lld keep " + "their experts in RAM too (%.2f GiB)%s\n", + (long long) offered, (long long) stage_lent, (double) stage_lent_bytes / 1073741824.0, + stage_lent < offered ? " (the rest are read from the file when lent: not enough RAM for them)" : ""); + } if (!additional_gpu_pairs.empty()) { std::fprintf(stderr, "FileExpertSource: %zu verified additional-GPU experts remain on the mmap fallback\n", additional_gpu_pairs.size()); From 51d55a9ab46b9e5901888b0ad3fdf94496b992b5 Mon Sep 17 00:00:00 2001 From: Evan Date: Tue, 6 Oct 2026 15:41:07 +0200 Subject: [PATCH 3/9] generate: size every part's lend region for a layer split by the serve scan's own arithmetic (auto ceiling or the explicit chunk, the 128-slot floor, the auto percentage cap), #340's own-buffer rule deciding which parts lend nothing - and hand them to the resident copy before it pins --- src/program/generate.cpp | 61 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 433d3957..78da2dba 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -6097,11 +6097,72 @@ int main(int argc, char** argv) { } // a layer split: the experts every later stage's cache holds are left out of the RAM copy, as CUDA0's are // (with them the copy keeps no lend region: pin_cache_complement turns the loan off) + // (true of the single lend region only: the stage_lend_regions block below hands every part's + // borrowed tail to the copy as well, so under a split the copy keeps a lend region per part again) std::vector> stage_pairs; for (auto& st : stages) for (int64_t l = st->lb; l < st->le; ++l) for (int64_t e = 0; e < g.n_expert; ++e) if (st->cache.slot_of(l, e) >= 0) stage_pairs.emplace_back((int32_t) l, (int32_t) e); + // The split's lend regions. The serve scan lends the tail slots of EVERY part's cache - CUDA0's own + // part first, then every stage (the `pf_parts` loop below) - and `lend_from` above is switched off in + // pin_cache_complement the moment `additional_gpu_pairs` is non-empty, so until now none of those experts + // were in the RAM copy: during a prompt they came back through page faults from the mapped files. + // Measured 2026-10-06 on an RTX 2000 Ada + 5060 Ti rig (17/48 split, IQ3_S mapped from the GGUF, + // --prefill auto, one 73K-token prompt): 3.7 GiB read from the NVMe for the one prompt (the arena + // mode reads 1.1 GiB), and one 8192-token chunk spent 1.5 s of its 3.9 s on host staging (arena: + // 0.37 s). Size each part's region at the largest chunk the scan can ever pick - auto's ceiling, or an + // explicit --prefill, which the scan only walks down - take its tail slots with the scan's own + // arithmetic, and list the pairs from the highest slot down, as the borrowing takes them. #340 is + // honoured the same way (the same free-VRAM test, at this startup moment): a part whose card can + // fund the bound chunk's buffers outright lends nothing at any pick, so it gets no region and no RAM + // is spent on it. The single-GPU loan is untouched: without a split the lend region stays in + // pin_cache_complement's own path, and no regions are set. + std::vector>> stage_lends; + if (pf_borrow && d_res != nullptr && o.prefill_chunk > 0 && multi_gpu && !stages.empty()) { + const int64_t bound = o.prefill_auto ? auto_ceiling : o.prefill_chunk; + static const bool own_ok = [] { + const char* v = std::getenv("STRATA_SPLIT_OWN_BUFFERS"); + return v == nullptr || v[0] != '0'; + }(); + for (size_t i = 0; i <= stages.size(); ++i) { // the scan's part order: CUDA0, then every stage + strata::core::ExpertCache& xc = i == 0 ? xcache : stages[i - 1]->cache; + const strata::core::SessionState& ses = i == 0 ? ss : stages[i - 1]->ss; + const int64_t dev = i == 0 ? -1 : stages[i - 1]->dev; + const int64_t lb = i == 0 ? 0 : stages[i - 1]->lb; + const int64_t le = i == 0 ? split_at[0] : stages[i - 1]->le; + if (xc.slots() <= 0 || le <= lb) continue; + const uint64_t need = strata::prefill::Prefill::bytes_needed(g, ses, bound); + if (own_ok) { // the card funds its buffers at any chunk the scan can pick: nothing is lent + const strata::core::OnDevice on(dev); + size_t fb = 0, tb = 0; + if (cudaMemGetInfo(&fb, &tb) == cudaSuccess) { + if ((uint64_t) fb >= need + (3ull << 29)) continue; + } else (void) cudaGetLastError(); + } + int64_t k = 0; // its tail slots, as the scan's `cache_slots_for` counts them + if (xc.slot_offsets() != nullptr) { + while (k < xc.slots() && + (uint64_t) (xc.bytes() - (int64_t) xc.slot_offsets()[xc.slots() - k]) < need) ++k; + } else { + const int64_t blob = (int64_t) strata::kernels::cpu::expert_layout().max_blob; + k = (int64_t) ((need + (uint64_t) blob - 1) / (uint64_t) blob); + } + k = std::min(k, xc.slots() - 128); // the scan's 128-slot floor + if (o.prefill_auto) k = std::min(k, kAutoLendPct * xc.slots() / 100); // the auto cap + if (k <= 0) continue; + std::vector> region; + for (int64_t l = lb; l < le; ++l) + for (int64_t e = 0; e < g.n_expert; ++e) + if (xc.slot_of(l, e) >= xc.slots() - k) region.emplace_back((int32_t) l, (int32_t) e); + std::sort(region.begin(), region.end(), + [&](const std::pair& a, const std::pair& b) { + return xc.slot_of(a.first, a.second) > xc.slot_of(b.first, b.second); + }); + if (!region.empty()) stage_lends.push_back(std::move(region)); + } + src.stage_lend_regions(std::move(stage_lends)); + } const std::vector>& rank_all = profile_all.empty() ? profile : profile_all; bool resident_ok = src.pin_cache_complement(xcache, err, o.resident_pin, stage_pairs, lend_from, o.resident_headroom, o.resident_budget, &rank_all); From d3fb3e6f75a4c2663a00f343f13e6d1384456e1d Mon Sep 17 00:00:00 2001 From: noon-at-cgn <75719527+noon-at-cgn@users.noreply.github.com> Date: Thu, 8 Oct 2026 04:26:58 -0400 Subject: [PATCH 4/9] split: decide STRATA_SPLIT_RING before sizing the lend regions; log borrowed vs RAM-kept slots Builds on #1190. The layer split sized its lend regions (the RAM copies of the experts the prompt path borrows) with Prefill::bytes_needed before the split's ring override was applied (Prefill::set_ring_override says it must be set before any bytes_needed), so with STRATA_SPLIT_RING=384 the prompt path borrowed 5396 slots and the copy kept 4662. The override is now decided first (decide_split_ring); include/strata/program/split_ring.hpp holds the pure helpers (split_ring_slots, split_lend_slots - the scan's own tail-slot arithmetic, now one function for the region and the borrow), src/program/split_ring_test.cpp covers them on the CPU. A start line reports borrowed vs kept slots and warns when kept < borrowed. Docs: MULTI_GPU.md. --- CMakeLists.txt | 4 ++ docs/MULTI_GPU.md | 17 ++++++ include/strata/program/split_ring.hpp | 36 ++++++++++++ src/program/generate.cpp | 75 +++++++++++++++--------- src/program/split_ring_test.cpp | 84 +++++++++++++++++++++++++++ 5 files changed, 188 insertions(+), 28 deletions(-) create mode 100644 include/strata/program/split_ring.hpp create mode 100644 src/program/split_ring_test.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index b93a5a4c..5460231b 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1075,6 +1075,10 @@ if(STRATA_BUILD_TESTS OR STRATA_BUILD_CONVERSATION_TESTS) add_executable(message_boundary_test src/program/message_boundary_test.cpp) target_include_directories(message_boundary_test PRIVATE include) add_test(NAME message_boundary_test COMMAND message_boundary_test) + # a layer split's ring override and the lend slots sized with it: the RAM copy must keep every borrowed slot (CPU) + add_executable(split_ring_test src/program/split_ring_test.cpp) + target_include_directories(split_ring_test PRIVATE include) + add_test(NAME split_ring_test COMMAND split_ring_test) # the serve loop's conversation-cache retention policy (header-only, no library to link) add_executable(conv_cache_test src/program/conv_cache_test.cpp) target_include_directories(conv_cache_test PRIVATE include) diff --git a/docs/MULTI_GPU.md b/docs/MULTI_GPU.md index 5659f97e..5553ee50 100644 --- a/docs/MULTI_GPU.md +++ b/docs/MULTI_GPU.md @@ -127,6 +127,23 @@ The split with `--mmap-experts` catches up once the OS file cache holds the expe running; the resident copy is there from the first request and stays locked when other programs need the RAM. With `--pcie-frac 0 --adapt-every 0` the split's greedy output is the same with either mode. +**The prompt path's loan on a split and its streamed ring (`STRATA_SPLIT_RING`).** Under a split the prompt path borrows +the tail slots of each card's expert cache for its buffers (they are given back after the prompt), and the resident RAM +copy keeps those experts too, so a borrowed expert is not read back from the model file during a prompt. How many slots +are borrowed depends on the prompt path's streamed ring: a split uses 96 ring slots when at least 75% of the (layer, +expert) pairs sit in some card's cache, and `STRATA_SPLIT_RING=N` sets N slots (`0` goes back to the pinned-share rule). +The ring used to be chosen after the RAM copy's regions were sized, so the regions were sized for a different ring than +the prompt path then used: with `STRATA_SPLIT_RING=384` it borrowed 5,396 slots and the copy kept 4,662, and the +other 734 were read from the model file in every chunk. The ring is now chosen first (`Prefill::set_ring_override` +says it must be set before the buffers are counted). The start-up line `strata serve: lend sizing: the prompt path +borrows N slots (ring R slots at chunk C), K of them keep their experts in RAM too` shows both numbers, and a +`WARNING` follows when K is below N. Without a split, or without `--resident-experts`, nothing changes. With a split +the order of the two steps changed for every ring choice, the 96-slot rule included: its regions used to be sized for +the larger default ring, so there the copy probably kept more slots than were borrowed (not measured). The 5,396 / +4,662 figures are from one start on the test machine (2x RTX 3080 20 GB, UD-Q4_K_XL, `--layer-split 23`); +TODO-EVIDENCE (PREvidence: borrowed and kept slots before and after, with `STRATA_SPLIT_RING` unset and at 384, and the +prompt time of a long prompt, n and the A/A). + **A separate VRAM reserve for the later cards:** `--vram-reserve-later-mib N` (default: `--vram-reserve-mib`'s value). The card that drives the monitors needs more headroom than one that drives none; with the display on the last card, `--vram-reserve-mib 300 --vram-reserve-later-mib 1800` gives the first card's cache that VRAM. diff --git a/include/strata/program/split_ring.hpp b/include/strata/program/split_ring.hpp new file mode 100644 index 00000000..13489e16 --- /dev/null +++ b/include/strata/program/split_ring.hpp @@ -0,0 +1,36 @@ +#pragma once + +#include +#include + +// A layer split's prompt-path ring and the lend slots sized from it, kept apart from the engine so they can be tested +// on the CPU (header-only, like pipeline_gate.hpp). +// +// 1. split_ring_slots: the streamed-ring override a split chooses (STRATA_SPLIT_RING, else 96 when most experts are +// resident). The choice must be made BEFORE anything sizes the prompt path with Prefill::bytes_needed (which counts +// ring_slots * max_blob): the split's lend regions (the RAM copies of the experts the prompt path borrows) used to +// be sized first, with the default ring, so a larger ring borrowed more slots than the copy kept. +// 2. split_lend_slots: how many tail slots of a cache `need` bytes take - the scan's own arithmetic, used for the +// RAM-copy region and for the borrow itself so the two cannot disagree. +namespace strata::program { + +/// The ring override (slots) for a layer split, 0 = none (the pinned-share rule stays). +/// env STRATA_SPLIT_RING as read from the environment (nullptr = unset); 0 / non-numeric = the pinned-share rule +/// res_share the share of (layer, expert) pairs resident in some stage cache, 0..1 +inline int split_ring_slots(const char* env, double res_share) { + const int ring = env != nullptr ? std::atoi(env) : (res_share >= 0.75 ? 96 : 0); + return ring > 0 ? ring : 0; +} + +/// The number of tail slots of a cache of `slots` slots whose bytes cover `need`. `offsets` is the cache's per-slot +/// byte-offset prefix sum (slots + 1 entries, `bytes` = offsets[slots]) or nullptr when every slot is `max_blob` bytes. +inline int64_t split_lend_slots(int64_t slots, int64_t bytes, const uint64_t* offsets, uint64_t max_blob, uint64_t need) { + if (offsets != nullptr) { + int64_t k = 0; + while (k < slots && (uint64_t) (bytes - (int64_t) offsets[slots - k]) < need) ++k; + return k; + } + return max_blob == 0 ? 0 : (int64_t) ((need + max_blob - 1) / max_blob); +} + +} // namespace strata::program diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 78da2dba..3e143f53 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -58,6 +58,7 @@ #include "strata/core/mtp.hpp" #include "strata/prefill/prefill.hpp" #include "strata/core/native_dense.hpp" +#include "strata/program/split_ring.hpp" #include "strata/program/logits_selection.hpp" #include "strata/program/conv_cache.hpp" #include "strata/program/message_boundary.hpp" @@ -6088,6 +6089,24 @@ int main(int argc, char** argv) { : nullptr; if (why != nullptr) adapt_async_off(why); } + // #340 / STRATA_SPLIT_RING: a layer split's streamed-ring override, decided from the stage caches' residency. It + // has to be in place BEFORE the split's lend regions are sized (Prefill::bytes_needed counts the ring): they were + // sized with the default ring and the override applied afterwards, so a ring of 384 borrowed 5396 slots and the RAM + // copy kept 4662 (the rest streamed from the GGUF mmap on every chunk). Called once; later calls do nothing. + bool split_ring_decided = false; + auto decide_split_ring = [&]() { + if (split_ring_decided || !o.serve || !multi_gpu || host_res.empty()) return; + split_ring_decided = true; + int64_t res_n = 0; + for (const int32_t r : host_res) res_n += r >= 0; + const double res_share = (double) res_n / (double) host_res.size(); + const int ring = strata::program::split_ring_slots(std::getenv("STRATA_SPLIT_RING"), res_share); + if (ring > 0) { + strata::prefill::Prefill::set_ring_override(ring); + std::fprintf(stderr, "strata serve: layer split: %.0f%% of the experts resident, the prompt path's " + "streamed ring %d slots\n", 100.0 * res_share, ring); + } + }; if (o.resident_cpu_experts) { int64_t lend_from = -1; if (o.prefill_chunk > 0 && !o.no_prefill_borrow && d_res != nullptr && xcache.slots() > 0) { @@ -6119,6 +6138,7 @@ int main(int argc, char** argv) { // is spent on it. The single-GPU loan is untouched: without a split the lend region stays in // pin_cache_complement's own path, and no regions are set. std::vector>> stage_lends; + decide_split_ring(); // the ring the prompt path really uses, BEFORE bytes_needed sizes the regions below if (pf_borrow && d_res != nullptr && o.prefill_chunk > 0 && multi_gpu && !stages.empty()) { const int64_t bound = o.prefill_auto ? auto_ceiling : o.prefill_chunk; static const bool own_ok = [] { @@ -6140,14 +6160,10 @@ int main(int argc, char** argv) { if ((uint64_t) fb >= need + (3ull << 29)) continue; } else (void) cudaGetLastError(); } - int64_t k = 0; // its tail slots, as the scan's `cache_slots_for` counts them - if (xc.slot_offsets() != nullptr) { - while (k < xc.slots() && - (uint64_t) (xc.bytes() - (int64_t) xc.slot_offsets()[xc.slots() - k]) < need) ++k; - } else { - const int64_t blob = (int64_t) strata::kernels::cpu::expert_layout().max_blob; - k = (int64_t) ((need + (uint64_t) blob - 1) / (uint64_t) blob); - } + // its tail slots, as the scan's `cache_slots_for` counts them + int64_t k = strata::program::split_lend_slots( + xc.slots(), xc.bytes(), xc.slot_offsets(), + (uint64_t) strata::kernels::cpu::expert_layout().max_blob, need); k = std::min(k, xc.slots() - 128); // the scan's 128-slot floor if (o.prefill_auto) k = std::min(k, kAutoLendPct * xc.slots() / 100); // the auto cap if (k <= 0) continue; @@ -6298,14 +6314,8 @@ int main(int argc, char** argv) { // bytes -> slots for one cache: exact when it knows its per-slot offsets (a native pack's blobs differ // per layer), otherwise max_blob each. auto cache_slots_for = [&](const strata::core::ExpertCache& xc, uint64_t need) -> int64_t { - if (xc.slot_offsets() != nullptr) { // sized slots: from the end until they hold `need` - int64_t k = 0; - while (k < xc.slots() && - (uint64_t) (xc.bytes() - (int64_t) xc.slot_offsets()[xc.slots() - k]) < need) ++k; - return k; - } - const int64_t blob = (int64_t) strata::kernels::cpu::expert_layout().max_blob; - return (int64_t) ((need + (uint64_t) blob - 1) / (uint64_t) blob); + return strata::program::split_lend_slots(xc.slots(), xc.bytes(), xc.slot_offsets(), + (uint64_t) strata::kernels::cpu::expert_layout().max_blob, need); }; auto part_slots = [&](const PfPart& p, int64_t c) -> int64_t { return cache_slots_for(*p.cache, strata::prefill::Prefill::bytes_needed(g, *p.ses, c)); @@ -6320,18 +6330,8 @@ int main(int argc, char** argv) { // the 384-slot ring (sized for a card that streams nearly every expert of a chunk) only makes every stage's // loan bigger: 96 slots (0.1.30's ring here) when >= 75% of the (layer, expert) pairs are resident. One GPU // keeps the pinned-share rule. STRATA_SPLIT_RING=N: N slots on a split; 0: the pinned-share rule. - if (multi_gpu && !host_res.empty()) { - int64_t res_n = 0; - for (const int32_t r : host_res) res_n += r >= 0; - const double res_share = (double) res_n / (double) host_res.size(); - const char* v = std::getenv("STRATA_SPLIT_RING"); - const int ring = v ? std::atoi(v) : (res_share >= 0.75 ? 96 : 0); - if (ring > 0) { - strata::prefill::Prefill::set_ring_override(ring); - std::fprintf(stderr, "strata serve: layer split: %.0f%% of the experts resident, the prompt path's " - "streamed ring %d slots\n", 100.0 * res_share, ring); - } - } + // (decided above, before the lend regions were sized: a no-op here unless the resident RAM mode skipped it) + decide_split_ring(); std::vector pf_parts; // a cache too small to lend the prompt path its buffers would make it allocate them on top - on a card // whose cache already filled its reserve, that is the over-subscription the auto sizing avoids - so the @@ -6536,6 +6536,25 @@ int main(int argc, char** argv) { pf_parts[i].dev, (long long) (pf_parts[i].cache->slots() - pf_parts[i].first), (long long) pf_parts[i].cache->slots(), (double) part_bytes(pf_parts[i], pf_parts[i].first) / 1073741824.0); + // A split's RAM copy keeps the experts of the slots the prompt path borrows (the lend regions sized above): + // every borrowed expert not kept is streamed from the GGUF mmap during every chunk. Say both counts side + // by side - they used to differ whenever a ring override (STRATA_SPLIT_RING) was set, because the regions + // were sized with the default ring before the override applied. + if (multi_gpu && src.complement_ready()) { + int64_t borrowed = borrow != nullptr ? xcache.slots() - lend_first : 0; + for (size_t i = 1; i < pf_parts.size(); ++i) + if (pf_parts[i].first >= 0) borrowed += pf_parts[i].cache->slots() - pf_parts[i].first; + const int64_t kept = src.resident_lent_slots(); + std::fprintf(stderr, "strata serve: lend sizing: the prompt path borrows %lld slots (ring %lld slots at " + "chunk %lld), %lld of them keep their experts in RAM too\n", + (long long) borrowed, + (long long) strata::prefill::Prefill::ring_slots_for(o.prefill_chunk), + (long long) o.prefill_chunk, (long long) kept); + if (kept < borrowed) + std::fprintf(stderr, "strata serve: WARNING: %lld of the %lld borrowed slots have no RAM copy: " + "their experts are streamed from the model file during every chunk\n", + (long long) (borrowed - kept), (long long) borrowed); + } } else { std::fprintf(stderr, "strata serve: the prompt path allocates its own buffers (too few cache slots to borrow)\n"); } diff --git a/src/program/split_ring_test.cpp b/src/program/split_ring_test.cpp new file mode 100644 index 00000000..71fbd3d6 --- /dev/null +++ b/src/program/split_ring_test.cpp @@ -0,0 +1,84 @@ +#include "strata/program/split_ring.hpp" + +#include +#include +#include + +using namespace strata::program; + +#define CHECK(cond) \ + do { \ + if (!(cond)) { \ + std::printf("split_ring_test FAIL line %d: %s\n", __LINE__, #cond); \ + return 1; \ + } \ + ++checks; \ + } while (0) + +// a cache of `slots` slots whose blobs vary per layer like a native pack's (2.4 .. 3.6 MB), as the prefix sum the +// expert cache keeps +static std::vector make_offsets(int64_t slots) { + std::vector off((size_t) slots + 1, 0); + for (int64_t i = 0; i < slots; ++i) off[(size_t) i + 1] = off[(size_t) i] + 2400000ull + (uint64_t) (i % 13) * 100000ull; + return off; +} + +int main() { + int checks = 0; + + // 1. the ring the split chooses: the env wins, else 96 when most experts are resident, 0 = the pinned-share rule + CHECK(split_ring_slots(nullptr, 0.9) == 96); + CHECK(split_ring_slots(nullptr, 0.75) == 96); + CHECK(split_ring_slots(nullptr, 0.74) == 0); + CHECK(split_ring_slots("384", 0.9) == 384); + CHECK(split_ring_slots("384", 0.1) == 384); + CHECK(split_ring_slots("512", 0.9) == 512); + CHECK(split_ring_slots("0", 0.9) == 0); + CHECK(split_ring_slots("-3", 0.9) == 0); + CHECK(split_ring_slots("junk", 0.9) == 0); + + // 2. the lend count: uniform slots round up, sized slots walk from the end + CHECK(split_lend_slots(1000, 1000 * 100, nullptr, 100, 0) == 0); + CHECK(split_lend_slots(1000, 1000 * 100, nullptr, 100, 1) == 1); + CHECK(split_lend_slots(1000, 1000 * 100, nullptr, 100, 100) == 1); + CHECK(split_lend_slots(1000, 1000 * 100, nullptr, 100, 101) == 2); + CHECK(split_lend_slots(1000, 0, nullptr, 0, 500) == 0); // no blob size: nothing to count + { + const std::vector off = make_offsets(50); + const int64_t bytes = (int64_t) off.back(); + CHECK(split_lend_slots(50, bytes, off.data(), 3600000, 0) == 0); + const uint64_t last = off[50] - off[49]; + CHECK(split_lend_slots(50, bytes, off.data(), 3600000, last) == 1); + CHECK(split_lend_slots(50, bytes, off.data(), 3600000, last + 1) == 2); + CHECK(split_lend_slots(50, bytes, off.data(), 3600000, off[50]) == 50); + CHECK(split_lend_slots(50, bytes, off.data(), 3600000, off[50] + 1) == 50); // never past the cache + } + + // 3. the order: the RAM copy's lend region and the borrow must be sized with the SAME ring. The need of a chunk is + // its own buffers plus ring_slots * max_blob (Prefill::bytes_needed); the engine used to size the region with the + // default ring (96) and apply the STRATA_SPLIT_RING override afterwards, so a ring of 384 borrowed more slots + // than the region kept. + { + const int64_t slots = 6000; + const std::vector off = make_offsets(slots); + const int64_t bytes = (int64_t) off.back(); + const uint64_t max_blob = 3600000, buffers = 3000ull << 20; + auto need = [&](int ring) { return buffers + (uint64_t) ring * max_blob; }; + auto lend = [&](int ring) { return split_lend_slots(slots, bytes, off.data(), max_blob, need(ring)); }; + + const int default_ring = 96; + const int ring = split_ring_slots("384", 0.9); // STRATA_SPLIT_RING=384 + const int64_t borrowed = lend(ring); // what the prompt path borrows with the override in force + const int64_t kept_old_order = lend(default_ring); // the region sized before the override applied + const int64_t kept_new_order = lend(split_ring_slots("384", 0.9)); // decided first, then sized + CHECK(kept_old_order < borrowed); // the bug: borrowed experts without a RAM copy + CHECK(kept_new_order == borrowed); // the fix: the copy keeps every borrowed slot + // no override in play (production: STRATA_SPLIT_RING unset, ring 96 either way): nothing changes + CHECK(lend(split_ring_slots(nullptr, 0.5) > 0 ? split_ring_slots(nullptr, 0.5) : default_ring) == + kept_old_order); + // a bigger ring borrows monotonically more + CHECK(lend(96) <= lend(256) && lend(256) <= lend(384) && lend(384) <= lend(512)); + } + + std::printf("split_ring_test OK (%d checks)\n", checks); +} From f47349002c5863c55dcab3e061cba4f5c0f5cacb Mon Sep 17 00:00:00 2001 From: noon-at-cgn <75719527+noon-at-cgn@users.noreply.github.com> Date: Thu, 8 Oct 2026 14:16:47 -0400 Subject: [PATCH 5/9] docs: replace the evidence placeholder in the lend-sizing paragraph with the measured result --- docs/MULTI_GPU.md | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/docs/MULTI_GPU.md b/docs/MULTI_GPU.md index 5553ee50..72f567d3 100644 --- a/docs/MULTI_GPU.md +++ b/docs/MULTI_GPU.md @@ -140,9 +140,15 @@ borrows N slots (ring R slots at chunk C), K of them keep their experts in RAM t `WARNING` follows when K is below N. Without a split, or without `--resident-experts`, nothing changes. With a split the order of the two steps changed for every ring choice, the 96-slot rule included: its regions used to be sized for the larger default ring, so there the copy probably kept more slots than were borrowed (not measured). The 5,396 / -4,662 figures are from one start on the test machine (2x RTX 3080 20 GB, UD-Q4_K_XL, `--layer-split 23`); -TODO-EVIDENCE (PREvidence: borrowed and kept slots before and after, with `STRATA_SPLIT_RING` unset and at 384, and the -prompt time of a long prompt, n and the A/A). +4,662 figures were measured on the test machine (2x RTX 3080 20 GB at 220 W, Xeon E5-2696 v4, UD-Q4_K_XL, +`--layer-split 23`, resident RAM mode, `--prefill auto:16384`, 2 slots), one restart per arm, with `STRATA_SPLIT_RING=384` +and `STRATA_PREFILL_RING` unset. Before the change a 104K-token prompt made 413 blob reads and read 10.3 GB of experts +from the model file per request; after it, 0, with all 5,396 borrowed slots kept in RAM, for 2.15 GiB more pinned RAM +(13.61 -> 15.76 GiB). 25K and 51K prompts read nothing from the file in either case. With the override unset and +`STRATA_PREFILL_RING=384` the lend lines are identical before and after (5,396 / 5,396, 15.76 GiB). No speed gain is +shown: the medians of three 104K reads were 2,803 tok/s before and 2,907 after, but the spread before is 2,540-2,897 +(its first read faulted 4.2 GB in from NVMe) and there is no A/A restart. Here the page cache absorbed the 10 GB per +request; with less spare page cache it would be disk traffic. Not measured: both ring variables unset. **A separate VRAM reserve for the later cards:** `--vram-reserve-later-mib N` (default: `--vram-reserve-mib`'s value). The card that drives the monitors needs more headroom than one that drives none; with the display on the last card, From 91f1e85dd1895f083295f574e79fd1f266e68401 Mon Sep 17 00:00:00 2001 From: noon-at-cgn <75719527+noon-at-cgn@users.noreply.github.com> Date: Wed, 7 Oct 2026 16:06:59 -0400 Subject: [PATCH 6/9] --aux-cpus: put the engine's threads that are neither pool workers nor the host on spare CPUs (Linux, off by default) Header-only placement (include/strata/platform/aux_cpus.hpp): the spare CPU set (the host core's SMT siblings, then CPUs of physical cores with no worker; never a CPU that shares a core with a worker), the list parser, threads the engine creates pin themselves, threads somebody else created (the CUDA driver's) are moved by a sweep over /proc/self/task after the pool exists and at every request; pool workers and the host thread are never moved. --aux-cpus off|auto|LIST / STRATA_AUX_CPUS; per request strata_tune aux_cpus=0|1 (serve/server.py). Default off: the hooks do nothing. tests/platform/aux_cpus_test covers the derivation and live threads (CPU only). --- CMakeLists.txt | 5 + docs/DETAILS.md | 31 +++ include/strata/platform/aux_cpus.hpp | 361 +++++++++++++++++++++++++++ serve/server.py | 6 + serve/test_server.py | 8 + src/core/expert_source.cpp | 6 +- src/core/session.cpp | 2 + src/kernels/cpu/pool.cpp | 2 + src/ngram/ple_reader.cpp | 3 +- src/platform/direct_file.cpp | 5 +- src/prefill/prefill.cpp | 15 +- src/program/generate.cpp | 63 ++++- tests/platform/aux_cpus_test.cpp | 217 ++++++++++++++++ 13 files changed, 714 insertions(+), 10 deletions(-) create mode 100644 include/strata/platform/aux_cpus.hpp create mode 100644 tests/platform/aux_cpus_test.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 5460231b..a8f101cb 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1539,6 +1539,11 @@ if(STRATA_BUILD_TESTS) target_link_libraries(direct_file_async_test PRIVATE Threads::Threads) add_test(NAME direct_file_async_test COMMAND direct_file_async_test) endif() + # --aux-cpus: the CPU-set derivation (pure) and the placement of live threads; header-only, no GPU + add_executable(aux_cpus_test tests/platform/aux_cpus_test.cpp) + target_include_directories(aux_cpus_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include) + target_link_libraries(aux_cpus_test PRIVATE Threads::Threads) + add_test(NAME aux_cpus_test COMMAND aux_cpus_test) endif() if(STRATA_BUILD_TESTS) diff --git a/docs/DETAILS.md b/docs/DETAILS.md index d5a0c1fd..130e8f09 100644 --- a/docs/DETAILS.md +++ b/docs/DETAILS.md @@ -1454,6 +1454,37 @@ the pairs in which the switched arm won). They are here so you can try them on y - **`STRATA_ADAPT_LAG=2`: the adaptive tier's copies are waited for one window later** (#764). Decode, 6 pairs: Tesla P100 (PCIe 3.0 x16) +3.5% (6/6 pairs faster), RTX 5070 +0.2% (4/6), RTX 3060 -1.3% (0/6), so it stays opt-in. +## Thread placement: `--aux-cpus` (Linux, off by default) + +The CPU pool pins its workers (one logical CPU per physical core) and the host thread pins itself to the pool's reserved +core. A thread the engine starts after that inherits the host's one CPU: the adaptive tier's job thread, the prefill +helpers, the router look-ahead. The threads the CUDA driver starts are free to run on any CPU, the workers' included. +`--aux-cpus` puts every thread that is neither a pool worker nor the host thread on spare CPUs. It moves threads only and +never changes a result. + +- **Which CPUs.** `--aux-cpus auto` (or `STRATA_AUX_CPUS=auto`): the SMT siblings of the host's core first, then the CPUs of + physical cores that have no pool worker. A CPU that shares a core with a worker is never taken; when no CPU is spare + the feature does nothing and the start-up line says so. A list (`--aux-cpus 24,26` or `24-27`) is used as given, minus + the host's CPU and the workers' CPUs, and only CPUs the process may run on. `--aux-cpus off` is the default. +- **How.** Threads the engine starts pin themselves first thing: the adaptive tier's job thread and its per-round + threads, the prefill copy threads and helpers, the router look-ahead, the PLE reader, the file readers, the stdin reader + and the watchdog. The threads someone else started (the CUDA driver's) are moved by a sweep over `/proc/self/task` + once the pool exists and again at the start of every request. The pool's workers and the host thread are never moved, + and neither is a thread somebody pinned to one CPU. An explicit `STRATA_ADAPT_JOB_CPU` still wins for the adaptive tier's + job thread. `STRATA_AUX_STAGER=0` leaves the prefill copy threads where they were started: with a one-CPU spare set up + to 32 of them (`STRATA_STAGER_THREADS`) would share that CPU, which can slow the read of a long prompt. +- **Per request.** `"strata_tune": {"aux_cpus": 1}` (`serve/server.py` forwards `1`, `0`, `true` and `false`) moves the + threads to the set; `0` puts every moved thread back to the placement it had. A request without the key goes back to the + start-up setting. With `--batch` the most recently admitted request's value holds, as for the other `strata_tune` keys. + An engine started without `--aux-cpus` plans the set anyway, so `1` takes `auto`. +- **What it prints.** At start: `strata aux cpus: threads that are neither pool workers nor the host go to CPUs 24 (on; + N threads placed so far)`, or `(off at start; a request's aux_cpus=1 turns it on)`. A request that changes the state + prints `strata serve: aux cpus ON/off for this request`. +- **Not covered.** Other processes (the Python launcher, a container runtime) and the engine's host thread. +- **Measured.** TODO-EVIDENCE (PREvidence: the machine and CPU, `--aux-cpus` off against `auto` in interleaved pairs of + whole engine runs, the number of pairs and the A/A control, the host thread's involuntary context switches and + decode and prompt tok/s, cold rounds and warm rounds separately). + --- ## Experimental speed projection (EXPERIMENTAL, off by default) diff --git a/include/strata/platform/aux_cpus.hpp b/include/strata/platform/aux_cpus.hpp new file mode 100644 index 00000000..3a560316 --- /dev/null +++ b/include/strata/platform/aux_cpus.hpp @@ -0,0 +1,361 @@ +// strata/platform/aux_cpus.hpp - where the engine's OTHER threads run. +// +// The pool pins its workers (one logical CPU per physical core) and the host thread pins itself to the pool's reserved +// core. Every thread the host creates afterwards inherits the host's single CPU (the adaptive tier's job thread, the +// prefill helpers, the router lookahead ...), and the threads the CUDA driver creates float over every CPU, the pool +// workers' included. Measured on a 16-worker box: while the adaptive tier was busy the host thread was preempted 5x +// as often and the per-layer wait for the host's flag was 60-155 us instead of 8. +// +// `--aux-cpus LIST|auto|off` (STRATA_AUX_CPUS) puts every thread that is neither a pool worker nor the host thread on +// a small set of CPUs no worker uses: +// * threads the engine creates call `pin_current_thread()` first thing (a no-op while the feature is off); +// * threads somebody else created (the CUDA driver's) are caught by `sweep()` over /proc/self/task, run after the +// start-up and at every request. +// `auto` takes the SMT siblings of the host's core, then every CPU of a physical core no worker is pinned to. It +// never takes a CPU that shares a core with a worker (that would steal the worker's cycles): with nothing spare the +// feature does nothing. A list (`--aux-cpus 24,26`) is taken as given, minus the host's CPU and the workers' CPUs. +// +// Linux only (the other systems get empty functions). Header-only on purpose: the callers sit in four libraries that +// do not link each other. No output of the engine depends on where a thread runs. +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#if defined(__linux__) +#include +#include +#include +#include +#endif + +namespace strata::aux_cpus { + +/// One logical CPU the process may use and the physical core it belongs to (-1: unknown). +struct LogicalCpu { + int cpu = -1; + long pkg = -1; + long core = -1; +}; + +/// "24,26,30-31" -> {24, 26, 30, 31} (sorted, no duplicates). False for anything else (empty items, letters, +/// reversed ranges, negative numbers); `out` is then empty. +inline bool parse_cpu_list(const std::string& text, std::vector& out) { + out.clear(); + if (text.empty()) return false; + size_t i = 0; + auto number = [&](long& v) { + if (i >= text.size() || text[i] < '0' || text[i] > '9') return false; + v = 0; + while (i < text.size() && text[i] >= '0' && text[i] <= '9') { + v = v * 10 + (text[i] - '0'); + if (v > 100000) return false; + ++i; + } + return true; + }; + for (;;) { + long lo = 0, hi = 0; + if (!number(lo)) { out.clear(); return false; } + hi = lo; + if (i < text.size() && text[i] == '-') { + ++i; + if (!number(hi) || hi < lo) { out.clear(); return false; } + } + for (long c = lo; c <= hi; ++c) out.push_back((int) c); + if (i == text.size()) break; + if (text[i] != ',') { out.clear(); return false; } + ++i; + } + std::sort(out.begin(), out.end()); + out.erase(std::unique(out.begin(), out.end()), out.end()); + return true; +} + +/// The CPUs `auto` gives to the aux threads, in order: the SMT siblings of the host's physical core first, then every +/// CPU of a physical core that has no worker and is not the host's. A CPU that shares a core with a worker is never +/// returned, and neither is one whose core is unknown (no sysfs): it might be a worker's sibling. +inline std::vector derive(const std::vector& allowed, int host_cpu, const std::vector& worker_cpus) { + using Key = std::pair; + auto key_of = [&](int cpu, Key& k) { + for (const LogicalCpu& c : allowed) + if (c.cpu == cpu) { k = {c.pkg, c.core}; return c.pkg >= 0 && c.core >= 0; } + return false; + }; + std::vector worker_keys; + for (int w : worker_cpus) { + Key k; + if (key_of(w, k)) worker_keys.push_back(k); + } + Key host_key; + const bool host_known = host_cpu >= 0 && key_of(host_cpu, host_key); + std::vector siblings, free_cores; + for (const LogicalCpu& c : allowed) { + if (c.cpu == host_cpu || c.pkg < 0 || c.core < 0) continue; + if (std::find(worker_cpus.begin(), worker_cpus.end(), c.cpu) != worker_cpus.end()) continue; + const Key k{c.pkg, c.core}; + if (host_known && k == host_key) { + siblings.push_back(c.cpu); + } else if (std::find(worker_keys.begin(), worker_keys.end(), k) == worker_keys.end()) { + free_cores.push_back(c.cpu); + } + } + std::sort(siblings.begin(), siblings.end()); + std::sort(free_cores.begin(), free_cores.end()); + siblings.insert(siblings.end(), free_cores.begin(), free_cores.end()); + return siblings; +} + +/// An explicit list, restricted to CPUs the process may use, without the host's CPU and the workers' CPUs. +inline std::vector restrict_list(const std::vector& list, const std::vector& allowed, int host_cpu, + const std::vector& worker_cpus) { + std::vector out; + for (int c : list) { + if (c == host_cpu || std::find(worker_cpus.begin(), worker_cpus.end(), c) != worker_cpus.end()) continue; + const bool ok = std::any_of(allowed.begin(), allowed.end(), [&](const LogicalCpu& a) { return a.cpu == c; }); + if (ok) out.push_back(c); + } + return out; +} + +/// What `--aux-cpus` / STRATA_AUX_CPUS said. `on`: placed from the start-up; `use_list`: the list, not `auto`. +struct Config { + bool on = false; + bool use_list = false; + std::vector list; +}; + +/// "" and "off": off at start (a request can still turn it on with `auto`); "auto"; or a CPU list. +inline bool parse_spec(const std::string& spec, Config& cfg, std::string& err) { + cfg = Config{}; + if (spec.empty() || spec == "off") return true; + if (spec == "auto") { cfg.on = true; return true; } + if (!parse_cpu_list(spec, cfg.list)) { + err = "--aux-cpus takes off, auto or a CPU list such as 24,26 or 24-27 (got '" + spec + "')"; + return false; + } + cfg.on = true; + cfg.use_list = true; + return true; +} + +#if defined(__linux__) + +namespace detail { + +struct State { + std::mutex mu; + Config cfg; + std::atomic enabled{false}; + std::atomic have_plan{false}; + std::vector allowed; ///< the process's CPUs, snapshotted before any thread is pinned + std::vector plan; ///< the aux CPUs (empty: nothing to do) + std::vector workers; ///< the pool's CPUs: their threads are never touched + cpu_set_t target; + std::set owned; ///< tids of pool workers and host threads + std::map original; ///< tid -> the mask it had before this module moved it + State() { CPU_ZERO(&target); } +}; + +inline State& state() { + static State s; + return s; +} + +inline int self_tid() { return (int) syscall(SYS_gettid); } + +inline bool same_mask(const cpu_set_t& a, const cpu_set_t& b) { return CPU_EQUAL(&a, &b) != 0; } + +/// Moves `tid` to the aux set. Caller holds `mu`. Returns true if the thread's mask changed. +inline bool move_locked(State& s, int tid) { + cpu_set_t now; + CPU_ZERO(&now); + if (sched_getaffinity(tid, sizeof now, &now) != 0) return false; + if (same_mask(now, s.target)) return false; + if (CPU_COUNT(&now) == 1) { // pinned to one CPU of a worker by somebody: not ours + for (int w : s.workers) + if (CPU_ISSET(w, &now)) return false; + } + if (sched_setaffinity(tid, sizeof s.target, &s.target) != 0) return false; + s.original.emplace(tid, now); // the first mask only: a second move keeps the real original + return true; +} + +inline bool alive(int tid) { + char path[48]; + std::snprintf(path, sizeof path, "/proc/self/task/%d", tid); + return access(path, F_OK) == 0; +} + +inline std::vector task_ids() { + std::vector ids; + if (DIR* d = opendir("/proc/self/task")) { + while (const dirent* e = readdir(d)) + if (e->d_name[0] >= '0' && e->d_name[0] <= '9') ids.push_back(std::atoi(e->d_name)); + closedir(d); + } + return ids; +} + +/// Forgets the threads that have ended (their tids may come back for another thread). Caller holds `mu`. +inline void purge_locked(State& s) { + for (auto it = s.original.begin(); it != s.original.end();) it = alive(it->first) ? std::next(it) : s.original.erase(it); + for (auto it = s.owned.begin(); it != s.owned.end();) it = alive(*it) ? std::next(it) : s.owned.erase(it); +} + +} // namespace detail + +/// Reads the CPUs the calling thread may use and the spec. Call once, early, on the thread that has not been pinned +/// yet (the engine's main thread, before the pool exists). The main thread counts as the host. +inline bool configure(const std::string& spec, std::string& err) { + detail::State& s = detail::state(); + Config cfg; + if (!parse_spec(spec, cfg, err)) return false; + std::lock_guard lk(s.mu); + s.cfg = cfg; + s.allowed.clear(); + cpu_set_t now; + CPU_ZERO(&now); + if (sched_getaffinity(0, sizeof now, &now) == 0) + for (int c = 0; c < CPU_SETSIZE; ++c) + if (CPU_ISSET(c, &now)) s.allowed.push_back(c); + s.owned.insert(detail::self_tid()); + return true; +} + +/// The calling thread belongs to the pool or is the host: the sweep leaves it alone. +inline void note_owned_thread() { + detail::State& s = detail::state(); + std::lock_guard lk(s.mu); + s.owned.insert(detail::self_tid()); +} + +/// Moves every thread of the process that is not owned to the aux set (or, with the feature off, does nothing). +/// Returns the number of threads whose placement changed. +inline int sweep() { + detail::State& s = detail::state(); + if (!s.enabled.load(std::memory_order_acquire)) return 0; + std::lock_guard lk(s.mu); + detail::purge_locked(s); + int n = 0; + for (int tid : detail::task_ids()) + if (s.owned.find(tid) == s.owned.end() && detail::move_locked(s, tid)) ++n; + return n; +} + +/// First thing a thread the engine creates does: it goes to the aux set while the feature is on. Cheap when off. +inline void pin_current_thread() { + detail::State& s = detail::state(); + if (!s.enabled.load(std::memory_order_acquire)) return; + std::lock_guard lk(s.mu); + const int tid = detail::self_tid(); + if (s.owned.find(tid) == s.owned.end()) detail::move_locked(s, tid); +} + +/// Puts back the placement every moved thread had. Returns how many were restored. +inline int restore() { + detail::State& s = detail::state(); + std::lock_guard lk(s.mu); + int n = 0; + for (const auto& [tid, mask] : s.original) + if (detail::alive(tid) && sched_setaffinity(tid, sizeof mask, &mask) == 0) ++n; + s.original.clear(); + return n; +} + +/// Turns the placement on (sweeping at once) or off (restoring the moved threads). A no-op without a plan. +inline void set_enabled(bool on) { + detail::State& s = detail::state(); + if (on) { + if (!s.have_plan.load(std::memory_order_acquire)) return; + s.enabled.store(true, std::memory_order_release); + (void) sweep(); + } else { + s.enabled.store(false, std::memory_order_release); + (void) restore(); + } +} + +inline bool enabled() { return detail::state().enabled.load(std::memory_order_acquire); } + +/// The aux CPUs of the plan ({} when there is none). +inline std::vector plan() { + detail::State& s = detail::state(); + std::lock_guard lk(s.mu); + return s.plan; +} + +/// Reads sysfs for the cores of the process's CPUs. `cpus` empty: every CPU `configure` saw. +inline std::vector read_topology(const std::vector& cpus) { + auto read_id = [](int cpu, const char* what) -> long { + char path[96]; + std::snprintf(path, sizeof path, "/sys/devices/system/cpu/cpu%d/topology/%s", cpu, what); + long v = -1; + if (std::FILE* f = std::fopen(path, "r")) { + if (std::fscanf(f, "%ld", &v) != 1) v = -1; + std::fclose(f); + } + return v; + }; + std::vector out; + for (int c : cpus) out.push_back({c, read_id(c, "physical_package_id"), read_id(c, "core_id")}); + return out; +} + +/// Works the plan out once the pool exists: `host_cpu` is the CPU the host thread is pinned to (-1: unknown) and +/// `worker_cpus` the CPUs of the pool's workers. With the start-up setting on, the placement starts now. Returns one +/// line for the log. +inline std::string set_topology(int host_cpu, const std::vector& worker_cpus) { + detail::State& s = detail::state(); + std::vector plan; + std::string note; + { + std::lock_guard lk(s.mu); + const std::vector allowed = read_topology(s.allowed); + plan = s.cfg.use_list ? restrict_list(s.cfg.list, allowed, host_cpu, worker_cpus) + : derive(allowed, host_cpu, worker_cpus); + s.plan = plan; + s.workers = worker_cpus; + CPU_ZERO(&s.target); + for (int c : plan) CPU_SET(c, &s.target); + s.have_plan.store(!plan.empty(), std::memory_order_release); + for (size_t i = 0; i < plan.size(); ++i) note += (i ? "," : "") + std::to_string(plan[i]); + } + if (plan.empty()) note = "none spare (every CPU is the host's, a worker's or shares a core with a worker or has no known core)"; + if (s.cfg.on && !plan.empty()) set_enabled(true); + long moved; + { + std::lock_guard lk(s.mu); + moved = (long) s.original.size(); + } + return "strata aux cpus: threads that are neither pool workers nor the host go to CPUs " + note + + (!s.cfg.on ? " (off at start; a request's aux_cpus=1 turns it on)" + : plan.empty() ? " (nothing to do)" : " (on; " + std::to_string(moved) + " threads placed so far)"); +} + +#else // not Linux: the same names, doing nothing + +inline bool configure(const std::string& spec, std::string& err) { + Config cfg; + return parse_spec(spec, cfg, err); +} +inline void note_owned_thread() {} +inline int sweep() { return 0; } +inline void pin_current_thread() {} +inline int restore() { return 0; } +inline void set_enabled(bool) {} +inline bool enabled() { return false; } +inline std::vector plan() { return {}; } +inline std::string set_topology(int, const std::vector&) { return "strata aux cpus: not available on this system"; } + +#endif + +} // namespace strata::aux_cpus diff --git a/serve/server.py b/serve/server.py index 553f440c..2e7a5888 100644 --- a/serve/server.py +++ b/serve/server.py @@ -966,6 +966,12 @@ class StrataEngine: v = tune.get(k) if isinstance(v, (int, float)) and not isinstance(v, bool) and 0.0 <= float(v) <= 1.0: keys += f" {k}={float(v)!r}" + # --aux-cpus for this request: 1 puts the engine's threads that are neither pool workers nor the host on the + # spare CPUs, 0 leaves them where they were created (true/false or 1/0; the engine started without a spare CPU + # ignores a 1). Anything else is not sent. + ac = tune.get("aux_cpus") + if isinstance(ac, bool) or (isinstance(ac, (int, float)) and ac in (0, 1)): + keys += f" aux_cpus={int(ac)}" # "strata_checkpoint": false - a one-shot call (a classification, a probe) whose turn no later request # extends: no conversation checkpoint for it (#830). It still reuses a cached prefix. Absent = as before. if sampling.get("strata_checkpoint") is False: diff --git a/serve/test_server.py b/serve/test_server.py index 60e909e8..ec05503c 100644 --- a/serve/test_server.py +++ b/serve/test_server.py @@ -1522,6 +1522,14 @@ class SamplingKeys(unittest.TestCase): bad = self.keys(strata_tune={"pcie_frac": 3, "spec_min_p": True, "pool_workers": 2}) self.assertFalse([x for x in bad if x.split("=")[0] in ("pcie_frac", "spec_min_p", "pool_workers")]) + def test_tune_aux_cpus(self): + for val, want in ((True, "aux_cpus=1"), (1, "aux_cpus=1"), (False, "aux_cpus=0"), (0, "aux_cpus=0"), + (1.0, "aux_cpus=1"), (0.0, "aux_cpus=0")): + self.assertIn(want, self.keys(strata_tune={"aux_cpus": val}), val) + for bad in (2, -1, 0.5, "1", None, "auto"): + self.assertFalse([x for x in self.keys(strata_tune={"aux_cpus": bad}) if x.startswith("aux_cpus=")], bad) + self.assertFalse([x for x in self.keys(temperature=0) if x.startswith("aux_cpus=")]) + def test_checkpoint_key(self): self.assertIn("ckpt=0", self.keys(temperature=0, strata_checkpoint=False)) for absent in ({}, {"strata_checkpoint": True}, {"strata_checkpoint": 0}, {"cache_prompt": False}): diff --git a/src/core/expert_source.cpp b/src/core/expert_source.cpp index f92994fd..064381f4 100644 --- a/src/core/expert_source.cpp +++ b/src/core/expert_source.cpp @@ -2,6 +2,7 @@ #include "strata/core/expert_source.hpp" #include "strata/core/foresight_swap.hpp" #include "strata/core/on_device.hpp" +#include "strata/platform/aux_cpus.hpp" #include "strata/core/remote_experts.hpp" #include "strata/core/peer_experts.hpp" #include "strata/kernels/cpu/expert_layout.hpp" @@ -1949,7 +1950,10 @@ bool RouterLookahead::start(std::vector> routers, int64_t k_ = k < 1 ? 1 : k > (int) n_expert ? (int) n_expert : k; src_ = src; x_.assign((size_t) (8 * n_embd), 0.f); - thread_ = std::thread([this] { run(); }); + thread_ = std::thread([this] { + strata::aux_cpus::pin_current_thread(); + run(); + }); return true; } diff --git a/src/core/session.cpp b/src/core/session.cpp index d87452d0..8d1fad91 100644 --- a/src/core/session.cpp +++ b/src/core/session.cpp @@ -8,6 +8,7 @@ #include "strata/kernels/quantize_act.hpp" #include "strata/kernels/s2_expert_grouped.hpp" #include "strata/kernels/cpu/pool.hpp" +#include "strata/platform/aux_cpus.hpp" #include "strata/kernels/ngram.hpp" #include @@ -556,6 +557,7 @@ bool SessionLoopScratch::init(size_t parts_bytes_in, std::string& err) { pinned = pinned_core.valid; } } + strata::aux_cpus::note_owned_thread(); // the host: --aux-cpus leaves it where it is return true; } diff --git a/src/kernels/cpu/pool.cpp b/src/kernels/cpu/pool.cpp index 16e3fb2d..af1eb5a5 100644 --- a/src/kernels/cpu/pool.cpp +++ b/src/kernels/cpu/pool.cpp @@ -1,6 +1,7 @@ // src/kernels/cpu/pool.cpp - P2.S3: the CPU expert pool. Read pool.hpp first; it explains the protocol. #include "strata/kernels/cpu/pool.hpp" #include "strata/core/progress.hpp" +#include "strata/platform/aux_cpus.hpp" #include "strata/kernels/cpu/expert_layout.hpp" #include @@ -458,6 +459,7 @@ ExpertPool::ExpertPool(int n_workers, bool pin, bool host_works, PoolAffinity af for (int i = 0; i < n_; ++i) { const int core = pin ? (i < (int) topo_.worker_cores.size() ? topo_.worker_cores[(size_t) i] : -1) : -1; threads_.emplace_back([this, i, core] { + strata::aux_cpus::note_owned_thread(); // --aux-cpus never moves a worker pin_this_thread(core, i); worker(i); }); diff --git a/src/ngram/ple_reader.cpp b/src/ngram/ple_reader.cpp index a03e4c04..9d2a0505 100644 --- a/src/ngram/ple_reader.cpp +++ b/src/ngram/ple_reader.cpp @@ -1,5 +1,6 @@ // src/ngram/ple_reader.cpp - see include/strata/ngram/ple_reader.hpp. #include "strata/ngram/ple_reader.hpp" +#include "strata/platform/aux_cpus.hpp" #include #include @@ -363,7 +364,7 @@ bool PleReader::open(const std::string& path, uint64_t table_offset, uint64_t n_ impl_->threaded = io_thread; if (io_thread) { try { - impl_->worker = std::thread([this] { impl_->worker_loop(); }); + impl_->worker = std::thread([this] { strata::aux_cpus::pin_current_thread(); impl_->worker_loop(); }); } catch (const std::exception& e) { err = std::string("PleReader: cannot create I/O worker: ") + e.what(); close(); diff --git a/src/platform/direct_file.cpp b/src/platform/direct_file.cpp index cd4f6a71..5f8d9962 100644 --- a/src/platform/direct_file.cpp +++ b/src/platform/direct_file.cpp @@ -1,5 +1,6 @@ // src/platform/direct_file.cpp - see include/strata/platform/direct_file.hpp. #include "strata/platform/direct_file.hpp" +#include "strata/platform/aux_cpus.hpp" #include #include @@ -184,7 +185,7 @@ bool DirectFile::open(const std::string& path, std::string& err) { // Completions of reads that finish synchronously are still queued to the port, so every issued read // produces exactly one packet; `wait` is the only completion path. const int n = io_threads(4); - for (int i = 0; i < n; ++i) impl_->pool.emplace_back([this] { impl_->worker(); }); + for (int i = 0; i < n; ++i) impl_->pool.emplace_back([this] { strata::aux_cpus::pin_current_thread(); impl_->worker(); }); return true; } @@ -311,7 +312,7 @@ bool DirectFile::open(const std::string& path, std::string& err) { if (fstat(impl_->fd, &st) != 0) { err = "DirectFile: cannot size " + path; close(); return false; } impl_->size = (uint64_t) st.st_size; const int n = io_threads(16); - for (int i = 0; i < n; ++i) impl_->pool.emplace_back([this] { impl_->worker(); }); + for (int i = 0; i < n; ++i) impl_->pool.emplace_back([this] { strata::aux_cpus::pin_current_thread(); impl_->worker(); }); return true; } diff --git a/src/prefill/prefill.cpp b/src/prefill/prefill.cpp index 4e03dc8b..11cebaf2 100644 --- a/src/prefill/prefill.cpp +++ b/src/prefill/prefill.cpp @@ -5,6 +5,7 @@ #include "strata/core/mtp.hpp" #include "strata/core/progress.hpp" #include "strata/core/on_device.hpp" +#include "strata/platform/aux_cpus.hpp" #include "strata/core/layout.hpp" #include "strata/kernels/cpu/expert.hpp" @@ -442,7 +443,15 @@ struct Stager { : cudaEventDisableTiming) != cudaSuccess) return false; } cudaGetDevice(&device); - for (int t = 0; t < nthreads; ++t) threads.emplace_back([this] { work(); }); + for (int t = 0; t < nthreads; ++t) + threads.emplace_back([this] { + // --aux-cpus: the copy threads go to the spare CPUs with the other helpers; STRATA_AUX_STAGER=0 leaves them where + // they were created (a small spare set would then hold all of them: it limits the copy rate of a long read) + static const bool keep = [] { const char* v = std::getenv("STRATA_AUX_STAGER"); return v != nullptr && std::atoi(v) == 0; }(); + if (keep) strata::aux_cpus::note_owned_thread(); + else strata::aux_cpus::pin_current_thread(); + work(); + }); return true; } ~Stager() { @@ -2122,6 +2131,7 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri // layer 1 on, and gathering them here first left the GPU idle for the whole read (~0.4 s of a 32K prompt) if (ple_on && !ple_next.valid()) ple_next = std::async(std::launch::async, [&ple_gather, &ple_next_err, c0, b = ple_buf] { + strata::aux_cpus::pin_current_thread(); return ple_gather(c0, b, ple_next_err); }); bool ple_pending = ple_on; @@ -2147,6 +2157,7 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri return false; } ple_next = std::async(std::launch::async, [&ple_gather, &ple_next_err, c1 = c0 + m.T, b = ple_buf ^ 1] { + strata::aux_cpus::pin_current_thread(); return ple_gather(c1, b, ple_next_err); }); } @@ -2330,6 +2341,7 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri const bool threaded_issue = stream_all && issuer_on; if (threaded_issue) { issuer = std::thread([&] { + strata::aux_cpus::pin_current_thread(); const core::OnDevice od(m.device); for (size_t idx = 0; idx < seq.size(); ++idx) { while (idx >= a_consumed.load(std::memory_order_acquire) + (size_t) m.ring) { @@ -3908,6 +3920,7 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri next_->hand_in_ = h; next_->single_chunk_ = single_chunk; next_run_ = std::async(std::launch::async, [this, tokens, c0, T, p0] { + strata::aux_cpus::pin_current_thread(); return next_->run_impl(tokens + c0, T, p0, next_err_); }); hand_buf_ ^= 1; diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 3e143f53..351b8091 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -36,6 +36,7 @@ #include "strata/core/weights.hpp" #include "strata/kernels/cpu/expert.hpp" #include "strata/kernels/cpu/pool.hpp" +#include "strata/platform/aux_cpus.hpp" #include "strata/kernels/cpu/expert_layout.hpp" #include "strata/kernels/ngram.hpp" #include "strata/kernels/iq_kernels.hpp" @@ -415,6 +416,8 @@ struct Options { strata::kernels::cpu::PoolAffinity pool_affinity = strata::kernels::cpu::PoolAffinity::All; /// --host-core first|last (STRATA_HOST_CORE): the host thread's core (see HostCore in pool.hpp) std::string host_core; + /// --aux-cpus off|auto|LIST (STRATA_AUX_CPUS): where the non-pool, non-host threads run (strata/platform/aux_cpus.hpp) + std::string aux_cpus; /// R2.2's first half, as an A/B arm. **ON by default**, because the measurement that justifies it is the /// pool's own drain: 33.7 GB/s against 5/6 x 44.14 = 36.8 for five workers, on a machine whose sixth core /// is reserved for a host thread that has nothing to do while the drain runs. @@ -852,6 +855,13 @@ void usage() { " interrupts to one logical processor, usually the first, and every copy that lands\n" " raises one: a spinning host there waits for them. Moves threads only, never a\n" " result. Not on hybrid CPUs (STRATA_HOST_CORE sets it too).\n" + " --aux-cpus SET Where the threads that are neither pool workers nor the host thread run (the\n" + " adaptive tier's job thread, the prefill helpers, the CUDA driver's threads, ...):\n" + " off (the default: wherever they were created), auto (the SMT siblings of the host's\n" + " core, then physical cores with no worker; never a CPU that shares a core with a\n" + " worker; nothing is done when none is spare) or a CPU list such as 24,26 (Linux; the\n" + " host's and the workers' CPUs are dropped from it). Moves threads only, never a\n" + " result. STRATA_AUX_CPUS sets it too; a request's strata_tune aux_cpus=0|1 beats it.\n" " --pool-affinity MODE Worker CPU affinity: all (default: one worker per physical core, as\n" " always), auto (hybrid CPUs: P-cores first, then their SMT siblings,\n" " then E-cores) or p-cores (P-cores and their siblings only).\n" @@ -1320,10 +1330,13 @@ private: } void loop() { // the job's memcpys stay off the host's core and the pool's: by default the spare SMT sibling of the last - // two-thread core (Windows); STRATA_ADAPT_JOB_CPU=, or -1 for no pinning + // two-thread core (Windows); STRATA_ADAPT_JOB_CPU=, or -1 for no pinning. Without either, --aux-cpus + // (off by default) puts the thread on the spare CPUs; an explicit STRATA_ADAPT_JOB_CPU is the user's word over it. const char* c = std::getenv("STRATA_ADAPT_JOB_CPU"); const int cpu = c != nullptr ? std::atoi(c) : smt_spare_cpu(); if (cpu >= 0) (void) strata::kernels::cpu::pin_current_thread(cpu); + if (c != nullptr) strata::aux_cpus::note_owned_thread(); + else if (cpu < 0) strata::aux_cpus::pin_current_thread(); for (;;) { std::function f; { @@ -1733,6 +1746,15 @@ int main(int argc, char** argv) { return 2; } } + else if (a == "--aux-cpus") { + o.aux_cpus = next("--aux-cpus"); + std::string aerr; + strata::aux_cpus::Config acfg; + if (!strata::aux_cpus::parse_spec(o.aux_cpus, acfg, aerr)) { + std::fprintf(stderr, "strata generate: %s\n", aerr.c_str()); + return 2; + } + } else if (a == "--pool-affinity") { const std::string v = next("--pool-affinity"); if (v == "auto") o.pool_affinity = strata::kernels::cpu::PoolAffinity::Auto; @@ -1965,6 +1987,17 @@ int main(int argc, char** argv) { if (const char* e = std::getenv("STRATA_HOST_CORE")) hc = e; if (hc == "last") strata::kernels::cpu::set_host_core(strata::kernels::cpu::HostCore::Last); } + { // --aux-cpus / STRATA_AUX_CPUS: read the CPUs this process may use now, before any thread is pinned; the plan + // follows once the pool exists (it needs the workers' CPUs) + std::string ac = o.aux_cpus; + if (ac.empty()) + if (const char* e = std::getenv("STRATA_AUX_CPUS")) ac = e; + std::string aerr; + if (!strata::aux_cpus::configure(ac, aerr)) { + std::fprintf(stderr, "strata generate: STRATA_AUX_CPUS: %s\n", aerr.c_str()); + return 2; + } + } strata::core::set_peer_portable(o.peer_device >= 1); // multi-GPU: the Portable flag on mapped host buffers only with a peer device (before any allocation) if (o.serve && o.conversation_cache_mib > 0 && (o.prompt_cache == 0 || o.conversation_cache_slots == 0)) std::fprintf(stderr, "strata serve: warning: conversation caching is disabled by %s\n", @@ -4273,6 +4306,12 @@ int main(int argc, char** argv) { "(--host-core %s)\n", pool.workers(), on.c_str(), ht.host_core, pool.host_works() ? " (draining too)" : "", strata::kernels::cpu::host_core_setting() == strata::kernels::cpu::HostCore::Last ? "last" : "first"); + // --aux-cpus: the plan, now the workers' CPUs are known; the threads that exist already (the CUDA driver's) move + // now when it is on, the ones created later pin themselves (strata/platform/aux_cpus.hpp) + const size_t nw = std::min((size_t) pool.workers(), ht.worker_cores.size()); + std::fprintf(stderr, "%s\n", + strata::aux_cpus::set_topology(ht.host_core, std::vector(ht.worker_cores.begin(), + ht.worker_cores.begin() + (long) nw)).c_str()); } if (o.no_ple_prefetch) strata::kernels::ple_prefetch_enable(false); // ---- R4's slot storage. Allocated AFTER the weights and the session, so `cudaMemGetInfo` inside `open` @@ -4669,7 +4708,7 @@ int main(int argc, char** argv) { if (!per_layer && srcp == &src && src.unbuffered() && i % 64 == 0) { if (ahead.valid()) ahead.get(); else read_batch(i); - if (i + 64 < want) ahead = std::async(std::launch::async, read_batch, i + 64); + if (i + 64 < want) ahead = std::async(std::launch::async, [&read_batch](int64_t b) { strata::aux_cpus::pin_current_thread(); read_batch(b); }, i + 64); } if (fill_ahead > 0 && i + fill_ahead < want) (void) src.advise_pairs(profile.data() + i + fill_ahead, 1); const int32_t slot = xcache.admit(profile[(size_t) i].first, profile[(size_t) i].second); @@ -8007,6 +8046,7 @@ int main(int argc, char** argv) { std::deque in_lines; bool in_eof = false; std::thread([&] { + strata::aux_cpus::pin_current_thread(); // read(2) on the descriptor, not std::cin: glibc's exit() flushes every stdio stream and waits for // stdin's lock, which getline holds while it waits for input - an engine ending on an error (every // std::exit) would hang in exit() on Linux, and the server would wait for it forever @@ -8152,6 +8192,7 @@ int main(int argc, char** argv) { const int io_limit = wio ? std::atoi(wio) : limit * 10; if (limit > 0) std::thread([limit, io_limit] { + strata::aux_cpus::pin_current_thread(); strata::core::Progress& p = strata::core::progress(); uint64_t last = p.beats.load(), ticks_at = p.ticks.load(); auto since = std::chrono::steady_clock::now(); @@ -9016,6 +9057,7 @@ int main(int argc, char** argv) { // tuning keys (setup's calibration measures settings without restarting the engine): the PCIe share of // the missed experts and the draft-probability floor, for this request only double req_pcie_frac = o.pcie_frac, req_spec_min_p = o.spec_min_p; + int req_aux_cpus = -1; // aux_cpus=0|1: --aux-cpus for this request (-1 = the start-up value) if (endp != nullptr) { // GENI takes the same keys (#75: image requests were always greedy); its // embedding file path is the first token without an = for (;;) { @@ -9042,6 +9084,7 @@ int main(int argc, char** argv) { else if (key == "seed") req_seed = std::strtoull(tok.c_str() + eq + 1, nullptr, 10); else if (key == "pcie_frac") req_pcie_frac = std::clamp((double) fv, 0.0, 1.0); else if (key == "spec_min_p") req_spec_min_p = std::clamp((double) fv, 0.0, 1.0); + else if (key == "aux_cpus") req_aux_cpus = std::atoi(tok.c_str() + eq + 1) != 0 ? 1 : 0; // unknown keys are skipped: the ids start at the first token without '=' } } @@ -9878,6 +9921,16 @@ int main(int argc, char** argv) { ver.set_sampling(req_sp); if (pipe) ver_b.set_sampling(req_sp); // (reaches the later stage's odd verifier) if (use_mtp) mtp.set_draft_sampling(req_sp); // STRATA_SPEC_COUPLED=1: sampled drafts (a no-op otherwise) + { // aux_cpus=0|1: where the non-pool, non-host threads run for this request (-1 = the start-up --aux-cpus); moves + // threads only. An enabled placement is swept at every request: it catches threads created since. + static const bool aux_start = strata::aux_cpus::enabled(); + const bool was_on = strata::aux_cpus::enabled(); + const bool want = req_aux_cpus < 0 ? aux_start : req_aux_cpus != 0; + strata::aux_cpus::set_enabled(want); + if (want != was_on) + std::fprintf(stderr, "strata serve: aux cpus %s for this request%s\n", strata::aux_cpus::enabled() ? "ON" : "off", + want && !strata::aux_cpus::enabled() ? " (asked for, but no CPU is spare: see the start-up line)" : ""); + } drive.d.pcie_num = std::max(0, std::min(256, (int) (req_pcie_frac * 256.0 + 0.5))); // a layer split: CUDA0's share as asked; a later GPU keeps its own (its link) unless the request sets one for (int st = 0; st < split_drive.n; ++st) @@ -10297,7 +10350,7 @@ int main(int argc, char** argv) { if (!drive.d.usage.empty() && o.adapt_every > 0 && (rounds % o.adapt_every) == 0 && pending.empty() && !exch_wait) { pl_adapt_done = false; - pl_adapt_thr = std::thread([&] { pl_adapt_ok = adapt(); pl_adapt_done = true; }); + pl_adapt_thr = std::thread([&] { strata::aux_cpus::pin_current_thread(); pl_adapt_ok = adapt(); pl_adapt_done = true; }); } return true; }; @@ -10794,7 +10847,7 @@ int main(int argc, char** argv) { 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_every) == 0) - adapt_thr = std::thread([&] { adapt_ok = adapt(); }); + adapt_thr = std::thread([&] { strata::aux_cpus::pin_current_thread(); adapt_ok = adapt(); }); if (!ver.commit(a + 1, err)) { if (adapt_thr.joinable()) adapt_thr.join(); std::printf("ERR %s\n", err.c_str()); @@ -11907,7 +11960,7 @@ int main(int argc, char** argv) { 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(); }); + adapt_thr = std::thread([&] { strata::aux_cpus::pin_current_thread(); adapt_ok = adapt(); }); 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/tests/platform/aux_cpus_test.cpp b/tests/platform/aux_cpus_test.cpp new file mode 100644 index 00000000..665ab99c --- /dev/null +++ b/tests/platform/aux_cpus_test.cpp @@ -0,0 +1,217 @@ +// aux_cpus_test: the CPU-set derivation of --aux-cpus (pure functions, no GPU) and, on Linux, the placement of live +// threads (a thread of the process moved to the aux set by the sweep, one that pins itself at creation, the owned ones +// left alone, and the original placement put back). +#include "strata/platform/aux_cpus.hpp" + +#include +#include +#include +#include +#include + +using namespace strata::aux_cpus; + +namespace { +int failures = 0; +#define CHECK(c) \ + do { \ + if (!(c)) { \ + std::fprintf(stderr, "FAILED %s:%d: %s\n", __FILE__, __LINE__, #c); \ + ++failures; \ + } \ + } while (0) + +using V = std::vector; + +std::vector cpus(std::initializer_list> rows) { + std::vector out; + for (const auto& r : rows) out.push_back({(int) r[0], r[1], r[2]}); + return out; +} + +// SMT machine: CPU i and i + n are the two threads of core i +std::vector smt(int n_cores, int n_threads_total) { + std::vector out; + for (int c = 0; c < n_threads_total; ++c) out.push_back({c, 0, c % n_cores}); + return out; +} + +void test_parse() { + V v; + CHECK(parse_cpu_list("24", v) && v == V{24}); + CHECK(parse_cpu_list("26,24", v) && v == (V{24, 26})); + CHECK(parse_cpu_list("24-27,30,25", v) && v == (V{24, 25, 26, 27, 30})); + CHECK(parse_cpu_list("0", v) && v == V{0}); + for (const char* bad : {"", ",", "1,", ",1", "a", "1-", "-1", "3-1", "1,,2", "1 2", "1;2", "99999999"}) { + CHECK(!parse_cpu_list(bad, v)); + CHECK(v.empty()); + } + Config c; + std::string err; + CHECK(parse_spec("", c, err) && !c.on); + CHECK(parse_spec("off", c, err) && !c.on); + CHECK(parse_spec("auto", c, err) && c.on && !c.use_list); + CHECK(parse_spec("24,26", c, err) && c.on && c.use_list && c.list == (V{24, 26})); + CHECK(!parse_spec("fast", c, err) && !err.empty()); +} + +void test_derive() { + // the production box's shape: 16 workers on 16 physical cores, the host on core 2, 24 allowed CPUs - CPUs 0-15 + // are cores 0-15 and 22-29 the second threads of cores 0-7: the host's sibling (CPU 24) is the only spare one + { + std::vector a; + for (int c = 0; c < 16; ++c) a.push_back({c, 0, c}); + for (int c = 22; c < 30; ++c) a.push_back({c, 0, c - 22}); + V workers; + for (int c = 0; c < 16; ++c) + if (c != 2) workers.push_back(c); + CHECK(derive(a, 2, workers) == V{24}); + // an explicit list is taken as given, minus the host's CPU and the workers' CPUs + CHECK(restrict_list({24, 26, 2, 5, 99}, a, 2, workers) == (V{24, 26})); + } + // 12 cores x 2 threads, host on CPU 0, workers on CPUs 1-7: the host's sibling first (12), then both threads of + // the four worker-free cores 8-11; the siblings of the workers (13-19) are never offered + { + const auto a = smt(12, 24); + CHECK(derive(a, 0, V{1, 2, 3, 4, 5, 6, 7}) == (V{12, 8, 9, 10, 11, 20, 21, 22, 23})); + } + // no SMT, every other core a worker: nothing spare + { + const auto a = cpus({{0, 0, 0}, {1, 0, 1}, {2, 0, 2}, {3, 0, 3}}); + CHECK(derive(a, 0, V{1, 2, 3}).empty()); + } + // no SMT, a core without a worker: that core + { + const auto a = cpus({{0, 0, 0}, {1, 0, 1}, {2, 0, 2}, {3, 0, 3}}); + CHECK(derive(a, 0, V{1, 2}) == V{3}); + } + // every CPU is a worker or the host's: nothing, with SMT too + { + const auto a = smt(4, 8); + CHECK(derive(a, 0, V{1, 2, 3}) == V{4}); // only the host's sibling + CHECK(derive(a, 0, V{1, 2, 3, 4}).empty()); // CPU 4 is a worker: the host core's sibling is taken + } + // two packages: core 1 of package 1 is not core 1 of package 0 + { + const auto a = cpus({{0, 0, 0}, {1, 0, 1}, {2, 1, 0}, {3, 1, 1}}); + CHECK(derive(a, 0, V{1, 2}) == V{3}); + } + // unknown cores (no sysfs): a CPU of unknown core could be a worker's sibling - none offered + { + const auto a = cpus({{0, -1, -1}, {1, -1, -1}, {2, -1, -1}, {3, -1, -1}}); + CHECK(derive(a, 0, V{1}).empty()); + } + // the host's CPU unknown: the free cores only + { + const auto a = smt(4, 8); + CHECK(derive(a, -1, V{0, 1}) == (V{2, 3, 6, 7})); + } + // CPUs the process may not use are not offered (a taskset): 5 and 6 are outside `a` + { + const auto a = cpus({{0, 0, 0}, {1, 0, 1}, {4, 0, 0}}); + CHECK(derive(a, 0, V{1}) == V{4}); + } + CHECK(derive(std::vector{}, 0, V{1}).empty()); +} + +#if defined(__linux__) +int tid_of_self() { return (int) syscall(SYS_gettid); } + +std::vector mask_of(int tid) { + cpu_set_t m; + CPU_ZERO(&m); + std::vector out; + if (sched_getaffinity(tid, sizeof m, &m) != 0) return out; + for (int c = 0; c < CPU_SETSIZE; ++c) + if (CPU_ISSET(c, &m)) out.push_back(c); + return out; +} + +void test_live() { + const std::vector allowed = mask_of(0); + if (allowed.size() < 4) { + std::printf("aux_cpus_test: live placement skipped (needs 4 allowed CPUs, have %zu)\n", allowed.size()); + return; + } + const int host = allowed[0], worker = allowed[1], aux_a = allowed[2], aux_b = allowed[3]; + std::string err; + CHECK(configure(std::to_string(aux_a) + "," + std::to_string(aux_b), err)); + // before the plan exists nothing is moved + CHECK(sweep() == 0); + const std::string line = set_topology(host, V{worker}); + std::printf("%s\n", line.c_str()); + CHECK(plan() == (V{aux_a, aux_b})); + CHECK(enabled()); + + // threads that stay alive until told: `floater` is created before the sweep (a CUDA driver thread's case), `owned` + // is a pool worker (registered), `late` pins itself at creation + std::atomic tid_floater{0}, tid_owned{0}, tid_late{0}; + std::atomic stop{false}; + auto body = [&](std::atomic& tid, bool owned, bool pin) { + if (owned) note_owned_thread(); + if (pin) pin_current_thread(); + tid = tid_of_self(); + while (!stop.load()) std::this_thread::sleep_for(std::chrono::milliseconds(2)); + }; + set_enabled(false); // earlier threads are born unmoved + CHECK(!enabled()); + std::thread floater([&] { body(tid_floater, false, false); }); + std::thread owned([&] { body(tid_owned, true, false); }); + for (int i = 0; i < 500 && (!tid_floater || !tid_owned); ++i) std::this_thread::sleep_for(std::chrono::milliseconds(2)); + CHECK(mask_of(tid_floater) == allowed); + + set_enabled(true); // the sweep + const V aux{aux_a, aux_b}; + CHECK(mask_of(tid_floater) == aux); + CHECK(mask_of(tid_owned) == allowed); // owned threads are left alone + CHECK(mask_of(tid_of_self()) == allowed); // so is the main thread (configure registered it) + + std::thread late([&] { body(tid_late, false, true); }); + for (int i = 0; i < 500 && !tid_late; ++i) std::this_thread::sleep_for(std::chrono::milliseconds(2)); + CHECK(mask_of(tid_late) == aux); // pinned at creation + + set_enabled(false); // back to the placements they had + CHECK(mask_of(tid_floater) == allowed); + CHECK(mask_of(tid_late) == allowed); + CHECK(mask_of(tid_owned) == allowed); + CHECK(sweep() == 0); // off: nothing moves + + // a thread pinned to ONE worker CPU by someone else is not ours even when unregistered + std::atomic tid_pinned{0}; + std::thread pinned([&] { + cpu_set_t m; + CPU_ZERO(&m); + CPU_SET(worker, &m); + sched_setaffinity(0, sizeof m, &m); + tid_pinned = tid_of_self(); + while (!stop.load()) std::this_thread::sleep_for(std::chrono::milliseconds(2)); + }); + for (int i = 0; i < 500 && !tid_pinned; ++i) std::this_thread::sleep_for(std::chrono::milliseconds(2)); + set_enabled(true); + CHECK(mask_of(tid_pinned) == V{worker}); + CHECK(mask_of(tid_floater) == aux); + set_enabled(false); + + stop = true; + floater.join(); + owned.join(); + late.join(); + pinned.join(); +} +#else +void test_live() { std::printf("aux_cpus_test: live placement is Linux only\n"); } +#endif + +} // namespace + +int main() { + test_parse(); + test_derive(); + test_live(); + if (failures) { + std::fprintf(stderr, "aux_cpus_test: %d check(s) failed\n", failures); + return 1; + } + std::printf("aux_cpus_test: ok\n"); + return 0; +} From 12019dc4a3dc1d1a89a8ed1956c6f76c7d265fbd Mon Sep 17 00:00:00 2001 From: noon-at-cgn <75719527+noon-at-cgn@users.noreply.github.com> Date: Thu, 8 Oct 2026 14:17:28 -0400 Subject: [PATCH 7/9] docs: replace the evidence placeholder in the thread-placement section with the measured result --- docs/DETAILS.md | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/docs/DETAILS.md b/docs/DETAILS.md index 130e8f09..37b9afc2 100644 --- a/docs/DETAILS.md +++ b/docs/DETAILS.md @@ -1481,9 +1481,20 @@ never changes a result. N threads placed so far)`, or `(off at start; a request's aux_cpus=1 turns it on)`. A request that changes the state prints `strata serve: aux cpus ON/off for this request`. - **Not covered.** Other processes (the Python launcher, a container runtime) and the engine's host thread. -- **Measured.** TODO-EVIDENCE (PREvidence: the machine and CPU, `--aux-cpus` off against `auto` in interleaved pairs of - whole engine runs, the number of pairs and the A/A control, the host thread's involuntary context switches and - decode and prompt tok/s, cold rounds and warm rounds separately). +- **Measured.** One machine: 2x RTX 3080 20 GB at 220 W, Xeon E5-2696 v4 (24 logical CPUs in the container, 16 pool + workers each on its own CPU), UD-Q4_K_XL, layer split 23, `--batch-mtp`, two slots, adaptive tier on. `auto` put the + host thread on CPU 2 and the helper threads on CPU 24. Same binary in every arm, only the flag differs. Two pairs of + whole engine restarts in the order `auto`, off, `auto`, off (12 solo decodes and 10 two-stream rounds per restart, + medians): solo decode 79.7 and 80.4 tok/s with `auto` against 72.1 and 72.4 off (off / `auto` = 0.904 and 0.900), two + streams in aggregate 90.8 and 90.7 against 80.8 and 82.8 (0.890 and 0.912). The same configuration restarted twice + moved solo by 1.009 and 1.005 and two streams by 0.999 and 1.024. Live on one engine, switching per request with + `strata_tune` and rotating the order (20 solo requests per arm, 16 two-stream rounds): off / on = 0.888 solo and + 0.917 two streams, against 0.985 and 0.990 for an A/A control of the same setting. The host thread's involuntary + context switches over a bench of about ten minutes were 43.8k and 42.8k with the flag off and 3.9k and 2.8k with + `auto`. Prompt reads (24K, 25K, 51K, 104K) do not depend on the flag: off is +0.7% to +1.5% against `auto`, inside the + restart noise. The mean and the p99 of the doorbell-to-flag time are not worse without the flag; what appears is rare + stalls above 100 us, in 7 and 8 of 12 requests off against 0 or 1 with `auto`. That preemption of the host causes the + loss is an inference; the counters do not prove it. The warm-up requests of each run were discarded. --- From a22a0e8c4653788836ca3808b8191834b013318e Mon Sep 17 00:00:00 2001 From: noon-at-cgn <75719527+noon-at-cgn@users.noreply.github.com> Date: Wed, 7 Oct 2026 23:32:28 -0400 Subject: [PATCH 8/9] split: batched draft-layer prompt K/V on the last stage (STRATA_SPLIT_MTP_BATCH=1, opt-in) On one GPU the prompt path computes the draft layer's K/V for each chunk in batches (Prefill::draft_kv, E-9). A layer split always ran the drafter's own per-group pass instead, because the drafter sits on the last stage. With STRATA_SPLIT_MTP_BATCH=1 the last stage's prompt path runs E-9 there. Default off: the default path is unchanged. The drafter's K/V come from Q8_1 x Q8_0 MMQ instead of its own mmvq, so its drafts can differ; the target's tokens are decided by the verify window. Prefill::draft_kv says why it declined (optional out-parameter, also in the SYCL port's prefill.cpp), and the split logs once what the variable did. Which path runs is a pure header (include/strata/program/draft_kv_plan.hpp) with a CPU test. tools/split_mtp_batch_parity.py compares the greedy texts of the two arms on a live server. Docs: MULTI_GPU.md. --- CMakeLists.txt | 4 ++ docs/MULTI_GPU.md | 15 +++++ include/strata/prefill/prefill.hpp | 3 +- include/strata/program/draft_kv_plan.hpp | 44 +++++++++++++ src/prefill/prefill.cpp | 22 ++++--- src/program/draft_kv_plan_test.cpp | 62 ++++++++++++++++++ src/program/generate.cpp | 28 +++++++- sycl/src/prefill/prefill.cpp | 23 ++++--- tools/split_mtp_batch_parity.py | 81 ++++++++++++++++++++++++ 9 files changed, 262 insertions(+), 20 deletions(-) create mode 100644 include/strata/program/draft_kv_plan.hpp create mode 100644 src/program/draft_kv_plan_test.cpp create mode 100755 tools/split_mtp_batch_parity.py diff --git a/CMakeLists.txt b/CMakeLists.txt index a8f101cb..ee449c97 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1083,6 +1083,10 @@ if(STRATA_BUILD_TESTS OR STRATA_BUILD_CONVERSATION_TESTS) add_executable(conv_cache_test src/program/conv_cache_test.cpp) target_include_directories(conv_cache_test PRIVATE include) add_test(NAME conv_cache_test COMMAND conv_cache_test) + # which path computes the draft layer's prompt K/V, and STRATA_SPLIT_MTP_BATCH's parsing (header-only, CPU) + add_executable(draft_kv_plan_test src/program/draft_kv_plan_test.cpp) + target_include_directories(draft_kv_plan_test PRIVATE include) + add_test(NAME draft_kv_plan_test COMMAND draft_kv_plan_test) # coupled draft sampling's counter and penalty-ring arithmetic (header-only, CPU) add_executable(coupled_draft_test src/core/coupled_draft_test.cpp) target_include_directories(coupled_draft_test PRIVATE include) diff --git a/docs/MULTI_GPU.md b/docs/MULTI_GPU.md index 72f567d3..68ce802d 100644 --- a/docs/MULTI_GPU.md +++ b/docs/MULTI_GPU.md @@ -100,6 +100,21 @@ The engine flags behind it: `--layer-split K1[,K2..]|auto` and `--split-device D devices; default the next visible ones). `--layer-split K --split-device 0` runs both stages on one card sharing everything - the bit-exact check of the hand-off, not a speed mode. +**The draft layer's prompt K/V in batches on a split (opt-in, `STRATA_SPLIT_MTP_BATCH=1`).** With `--mtp` the draft +layer sits on the last card, and each prompt chunk ends by filling that layer's K/V for the chunk's rows. On one card the +prompt path does it in batches (`Prefill::draft_kv`, a few large matrix products per chunk); on a split the drafter's own +pass always did it, one graph launch and four device copies per group of 8 rows (1,024 groups per 8,192-token chunk). +With the variable set, the last card's prompt path batches it as it does on one card. Restart-only; default off, so the +default start is unchanged. It needs a `--native` pack (the GGUF-form token table) and a paged or ring (`--kv-resident`) +draft K/V (`STRATA_MTP_BATCH_RING=0` sends a ring back to the old pass); otherwise it says why once and keeps the old pass: +`strata serve: draft layer prompt K/V batched on CUDA ...` or `strata serve: STRATA_SPLIT_MTP_BATCH=1 declined, the +drafter's own pass runs: `. The draft layer's K/V come out of Q8_1 x Q8_0 MMQ instead of its own mmvq, so the +drafts, and how many are accepted, can move; the target's tokens are decided by the verify window. +`tools/split_mtp_batch_parity.py` compares the greedy texts of the two arms. Preliminary, one machine (2x RTX 3080 20 GB, +UD-Q4_K_XL, `--layer-split 23`, `--batch-mtp`, two slots), few runs per arm, TODO-EVIDENCE (n, the A/A control and the +parity result): a 24K-token prompt read at 1,751 tok/s without and 1,857 with; 25K-token prompts +5 to 7%, 104K +2%; +drafts accepted 0.633 without, 0.635 with. + **Each card loads only its own layers' dense weights** (0.1.39, PR #639) with explicit split points (`--layer-split 27`, not `auto`): every card used to keep a full copy (~3.4 GB for the Coder) though its stage reads only its own layers, and the VRAM it frees goes to that card's expert cache (2x MI50 16 GB, Coder: 8,819 -> 10,626 experts in diff --git a/include/strata/prefill/prefill.hpp b/include/strata/prefill/prefill.hpp index c1b0a911..14de3ccd 100644 --- a/include/strata/prefill/prefill.hpp +++ b/include/strata/prefill/prefill.hpp @@ -51,8 +51,9 @@ public: /// scratch - call it from on_chunk. false with `err` empty: not applicable here (a ring or hybrid K/V, another /// device, too little scratch; STRATA_MTP_BATCH=0), the caller runs the drafter's own pass. Not bit-identical to /// that pass (FP16 GEMMs instead of Q8_1 activations): the drafts may differ, never the target's tokens' logits. + /// `why` (optional): on a decline (false, `err` empty) the reason, a static string. bool draft_kv(core::MtpDrafter& mtp, const float* R_rows, const int32_t* next_tokens, int64_t n, int64_t cell0, - std::string& err); + std::string& err, const char** why = nullptr); Prefill(); ~Prefill(); Prefill(const Prefill&) = delete; diff --git a/include/strata/program/draft_kv_plan.hpp b/include/strata/program/draft_kv_plan.hpp new file mode 100644 index 00000000..0bff531d --- /dev/null +++ b/include/strata/program/draft_kv_plan.hpp @@ -0,0 +1,44 @@ +// include/strata/program/draft_kv_plan.hpp - which code computes the draft layer's prompt K/V for a chunk. +// +// One GPU: the prompt path's batched pass (E-9, `Prefill::draft_kv`) tries first and the drafter's own +// per-8-row pass (`MtpDrafter::prefill`) takes what it declines. A layer split: only the drafter's own pass +// ran, until `STRATA_SPLIT_MTP_BATCH=1` (opt-in) lets the last stage's prompt path try E-9 as well. The +// drafter's K/V then come from Q8_1 x Q8_0 MMQ instead of its own mmvq, so its drafts can differ a little; the +// target's tokens are decided by the verify window and do not. +// +// Pure (no GPU, no environment read): generate.cpp passes in what it knows. +#pragma once + +#include + +namespace strata::program::draft_kv { + +/// `STRATA_SPLIT_MTP_BATCH`'s value: any whole number other than 0 turns it on; unset, empty, `0` and text +/// that is not a number leave it off. +inline bool split_env_on(const char* value) { return value != nullptr && std::atoi(value) != 0; } + +struct Plan { + bool try_batched = false; ///< call Prefill::draft_kv for this chunk + const char* why = nullptr; ///< when `try_batched` is false only because of a missing prerequisite: what is missing +}; + +/// `use_mtp`: the engine runs a draft layer. `multi_gpu`: a layer split. `split_env`: split_env_on(...) of the +/// variable. `has_native_embed`: the GGUF-form token embedding table exists (a --native pack): the split's +/// last stage reads it, a single GPU's path can also gather from its own weights. +inline Plan plan(bool use_mtp, bool multi_gpu, bool split_env, bool has_native_embed) { + Plan p; + if (!use_mtp) return p; + if (!multi_gpu) { + p.try_batched = true; + return p; + } + if (!split_env) return p; // the default on a split: the drafter's own pass, nothing to say + if (!has_native_embed) { + p.why = "the split's last stage has no GGUF-form token embedding table (not --native)"; + return p; + } + p.try_batched = true; + return p; +} + +} // namespace strata::program::draft_kv diff --git a/src/prefill/prefill.cpp b/src/prefill/prefill.cpp index 11cebaf2..d0b1744a 100644 --- a/src/prefill/prefill.cpp +++ b/src/prefill/prefill.cpp @@ -1281,8 +1281,10 @@ bool Prefill::relayout(int64_t chunk, void* borrow, uint64_t borrow_bytes, std:: int64_t Prefill::chunk() const { return impl_->T; } bool Prefill::draft_kv(core::MtpDrafter& mtp, const float* R_rows, const int32_t* next_tokens, int64_t n, int64_t cell0, - std::string& err) { + std::string& err, const char** why) { Impl& m = *impl_; + const core::OnDevice on_device(m.device); // the stage's own GPU current (a layer split's drafter: the last stage) + auto decline = [&](const char* reason) { if (why != nullptr) *why = reason; return false; }; static const bool off = [] { const char* v = std::getenv("STRATA_MTP_BATCH"); return v != nullptr && v[0] == '0'; }(); // A ring (KV streaming: the drafter's window, page p in slot p % n_slots over a host copy) takes the same appends // with its own page table and host copy, as a streamed main layer does; the cells written are those the window can @@ -1290,9 +1292,12 @@ bool Prefill::draft_kv(core::MtpDrafter& mtp, const float* R_rows, const int32_t // drafter's own pass for a ring (the A/B). static const bool ring_ok = [] { const char* v = std::getenv("STRATA_MTP_BATCH_RING"); return v == nullptr || v[0] != '0'; }(); core::QsaState& st = mtp.kv_state_rw(); - if (off || n <= 0 || m.g == nullptr || m.region == nullptr || (st.kv_mode != 0 && !(st.kv_mode == 2 && ring_ok)) || - st.kv_hybrid || mtp.device() != m.device) - return false; + if (off) return decline("STRATA_MTP_BATCH=0"); + if (n <= 0 || m.g == nullptr || m.region == nullptr) return decline("no prompt scratch region on this path"); + if (st.kv_mode != 0 && !(st.kv_mode == 2 && ring_ok)) + return decline(st.kv_mode == 2 ? "the drafter's K/V is a ring and STRATA_MTP_BATCH_RING=0" : "the drafter's K/V mode is not paged/ring"); + if (st.kv_hybrid) return decline("the drafter's K/V is hybrid (kv_hybrid)"); + if (mtp.device() != m.device) return decline("the drafter is on another device than this prefill path"); const auto t0 = Clock::now(); const core::ModelGeometry& g = *m.g; const int64_t Nn = g.n_embd, HCN = g.hc * g.n_embd, KV = g.n_head_kv * g.head_dim; @@ -1307,12 +1312,13 @@ bool Prefill::draft_kv(core::MtpDrafter& mtp, const float* R_rows, const int32_t const void* w_k = mtp.tensor_q8("self_attn.k_proj.weight"); const void* w_v = mtp.tensor_q8("self_attn.v_proj.weight"); const float* w_kn = mtp.tensor_f32("self_attn.k_norm.weight"); - if (!w_ne || !w_fe || !w_nh || !w_fh || !w_hn || !w_dn || !w_up || !w_k || !w_v || !w_kn) return false; + if (!w_ne || !w_fe || !w_nh || !w_fh || !w_hn || !w_dn || !w_up || !w_k || !w_v || !w_kn) + return decline("a drafter tensor is missing (Q8_0 projections / norms)"); const core::NativeEmbed* nemb = core::native_embed(); const core::WeightRef* wemb = nemb ? nullptr : m.wt->find("token_embd.weight"); if (!nemb && (wemb == nullptr || wemb->codebook_iq4nl || wemb->ne0 != g.n_embd || wemb->group_elems <= 0 || (wemb->code_bits != 2 && wemb->code_bits != 4 && wemb->code_bits != 8))) - return false; + return decline("the token embedding is not gatherable on this path"); // the cells the drafter's window can still reach const int64_t r0 = std::max(0, mtp.first_needed() - cell0); if (r0 >= n) return true; @@ -1327,7 +1333,7 @@ bool Prefill::draft_kv(core::MtpDrafter& mtp, const float* R_rows, const int32_t int64_t B = std::min(n - r0, (int64_t) (m.region_bytes / per_row) & ~(int64_t) 63); if (st.kv_mode == 2) // a ring: one batch's cells must not share a slot (a batch can straddle one page more) B = std::min(B, ((st.n_slots - 1) * strata::kernels::qsa_real_shapes().page_size) & ~(int64_t) 63); - if (B < 64) return false; + if (B < 64) return decline("too little scratch for a 64-row batch"); uint8_t* q = m.region; auto carve = [&](size_t bytes) { void* p = q; q += (bytes + 255) & ~(size_t) 255; return p; }; float* emb = (float*) carve((size_t) B * Nn * 4); @@ -1350,7 +1356,7 @@ bool Prefill::draft_kv(core::MtpDrafter& mtp, const float* R_rows, const int32_t void* xq = q8 ? carve(mmq::q8_bytes(B * g.hc, Nn)) : nullptr; int32_t* ident = q8 ? (int32_t*) carve((size_t) B * g.hc * 4) : nullptr; int32_t* bnd = q8 ? (int32_t*) carve(16) : nullptr; - if ((uint64_t) (q - m.region) > m.region_bytes) return false; + if ((uint64_t) (q - m.region) > m.region_bytes) return decline("the batch buffers do not fit the scratch region"); static const bool timing = std::getenv("STRATA_DRAFT_TIMING") != nullptr; // debug: where this pass's time goes if (timing) cudaStreamSynchronize(m.cs); const auto ti0 = Clock::now(); diff --git a/src/program/draft_kv_plan_test.cpp b/src/program/draft_kv_plan_test.cpp new file mode 100644 index 00000000..d48fdb75 --- /dev/null +++ b/src/program/draft_kv_plan_test.cpp @@ -0,0 +1,62 @@ +// src/program/draft_kv_plan_test.cpp - which path computes the draft layer's prompt K/V (header-only, CPU). +// +// 1. STRATA_SPLIT_MTP_BATCH: unset, empty, 0 and text that is not a number are off; any other whole number is on; +// 2. one GPU: the batched pass is tried whatever the variable says (the default before this change); +// 3. a layer split: the default stays the drafter's own pass, silently; with the variable on the batched pass is +// tried, unless the pack has no GGUF-form token table, which is reported instead; +// 4. no draft layer: nothing is tried and nothing is said. +#include "strata/program/draft_kv_plan.hpp" + +#include +#include + +namespace dkv = strata::program::draft_kv; + +namespace { +int g_fail = 0; +void check(bool ok, const char* what) { + std::printf(" %-72s %s\n", what, ok ? "ok" : "FAIL"); + if (!ok) ++g_fail; +} +} // namespace + +int main() { + std::printf("draft_kv_plan_test\n"); + check(!dkv::split_env_on(nullptr), "unset is off"); + check(!dkv::split_env_on(""), "empty is off"); + check(!dkv::split_env_on("0"), "0 is off"); + check(!dkv::split_env_on("off"), "text that is not a number is off"); + check(dkv::split_env_on("1"), "1 is on"); + check(dkv::split_env_on("2"), "any other whole number is on"); + + for (const bool env : {false, true}) + for (const bool native : {false, true}) { + const dkv::Plan p = dkv::plan(true, false, env, native); + check(p.try_batched && p.why == nullptr, "one GPU: the batched pass is tried, nothing is reported"); + } + + { + const dkv::Plan p = dkv::plan(true, true, false, true); + check(!p.try_batched && p.why == nullptr, "split, variable off: the drafter's own pass, silently"); + } + { + const dkv::Plan p = dkv::plan(true, true, false, false); + check(!p.try_batched && p.why == nullptr, "split, variable off, no token table: still silent"); + } + { + const dkv::Plan p = dkv::plan(true, true, true, true); + check(p.try_batched && p.why == nullptr, "split, variable on: the batched pass is tried on the last stage"); + } + { + const dkv::Plan p = dkv::plan(true, true, true, false); + check(!p.try_batched && p.why != nullptr, "split, variable on, no token table: declined with a reason"); + } + for (const bool multi : {false, true}) + for (const bool env : {false, true}) { + const dkv::Plan p = dkv::plan(false, multi, env, true); + check(!p.try_batched && p.why == nullptr, "no draft layer: nothing tried, nothing said"); + } + + std::printf(g_fail == 0 ? "draft_kv_plan_test: all ok\n" : "draft_kv_plan_test: %d FAILED\n", g_fail); + return g_fail == 0 ? 0 : 1; +} diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 351b8091..46c9d1c5 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -62,6 +62,7 @@ #include "strata/program/split_ring.hpp" #include "strata/program/logits_selection.hpp" #include "strata/program/conv_cache.hpp" +#include "strata/program/draft_kv_plan.hpp" #include "strata/program/message_boundary.hpp" #include "strata/spec/draft_policy.hpp" #include "strata/spec/draft_source.hpp" @@ -7408,11 +7409,34 @@ int main(int argc, char** argv) { } return true; }; + // STRATA_SPLIT_MTP_BATCH=1 (default off): the layer split's drafter is on the last stage, so E-9 (Prefill::draft_kv) + // runs there, on the Prefill that ran the chunk, instead of the drafter's own per-8-row pass. The drafts' K/V + // come from Q8_1 x Q8_0 MMQ rather than mmvq: drafts may differ, the target's tokens never. + static const bool split_mtp_batch = strata::program::draft_kv::split_env_on(std::getenv("STRATA_SPLIT_MTP_BATCH")); sp.on_chunk = [&](const float* R_rows, int64_t T, int64_t p0, std::string& e) -> bool { std::vector nxt((size_t) T); for (int64_t t = 0; t < T; ++t) nxt[(size_t) t] = (int32_t) cur[(size_t) (p0 + t + 1)]; - // E-9: batched through the prompt path when it can (one GPU: a layer split's drafter is on the last stage) - const bool batched = use_mtp && !multi_gpu && sp.draft_kv(mtp, R_rows, nxt.data(), T, p0, e); + // E-9: batched through the prompt path when it can (a layer split: only with STRATA_SPLIT_MTP_BATCH=1) + bool batched = false; + const strata::program::draft_kv::Plan dkv = strata::program::draft_kv::plan( + use_mtp, multi_gpu, split_mtp_batch, strata::core::native_embed() != nullptr); + if (dkv.try_batched || dkv.why != nullptr) { + strata::prefill::Prefill& dsp = multi_gpu ? stages.back()->sp : sp; // the drafter's stage + const char* why = dkv.why; + if (dkv.try_batched) batched = dsp.draft_kv(mtp, R_rows, nxt.data(), T, p0, e, &why); + if (multi_gpu) { // once per process: what this env did + static bool said = false; + if (!said && (batched || (e.empty() && why != nullptr))) { + said = true; + if (batched) + std::fprintf(stderr, "strata serve: draft layer prompt K/V batched on CUDA%d (E-9 on the layer " + "split, K/V mode %d)\n", stages.back()->dev, mtp.kv_state().kv_mode); + else + std::fprintf(stderr, "strata serve: STRATA_SPLIT_MTP_BATCH=1 declined, the drafter's own pass " + "runs: %s\n", why); + } + } + } if (!e.empty() || (use_mtp && !batched && !mtp.prefill(R_rows, nxt.data(), T, p0, e))) return false; if (use_mtp && std::getenv("STRATA_SNAPSHOT_VERIFY") != nullptr) std::fprintf(stderr, "strata serve: DRAFT_PREFILL path=%s mode=%d cells=%lld\n", diff --git a/sycl/src/prefill/prefill.cpp b/sycl/src/prefill/prefill.cpp index 08fe3fc2..1aef34d4 100644 --- a/sycl/src/prefill/prefill.cpp +++ b/sycl/src/prefill/prefill.cpp @@ -1275,8 +1275,9 @@ catch (sycl::exception const &exc) { int64_t Prefill::chunk() const { return impl_->T; } bool Prefill::draft_kv(core::MtpDrafter& mtp, const float* R_rows, const int32_t* next_tokens, int64_t n, int64_t cell0, - std::string& err) { + std::string& err, const char** why) { Impl& m = *impl_; + auto decline = [&](const char* reason) { if (why != nullptr) *why = reason; return false; }; static const bool off = [] { const char* v = std::getenv("STRATA_MTP_BATCH"); return v != nullptr && v[0] == '0'; }(); // A ring (KV streaming: the drafter's window, page p in slot p % n_slots over a host copy) takes the same appends // with its own page table and host copy, as a streamed main layer does; the cells written are those the window can @@ -1284,9 +1285,12 @@ bool Prefill::draft_kv(core::MtpDrafter& mtp, const float* R_rows, const int32_t // drafter's own pass for a ring (the A/B). static const bool ring_ok = [] { const char* v = std::getenv("STRATA_MTP_BATCH_RING"); return v == nullptr || v[0] != '0'; }(); core::QsaState& st = mtp.kv_state_rw(); - if (off || n <= 0 || m.g == nullptr || m.region == nullptr || (st.kv_mode != 0 && !(st.kv_mode == 2 && ring_ok)) || - st.kv_hybrid || mtp.device() != m.device) - return false; + if (off) return decline("STRATA_MTP_BATCH=0"); + if (n <= 0 || m.g == nullptr || m.region == nullptr) return decline("no prompt scratch region on this path"); + if (st.kv_mode != 0 && !(st.kv_mode == 2 && ring_ok)) + return decline(st.kv_mode == 2 ? "the drafter's K/V is a ring and STRATA_MTP_BATCH_RING=0" : "the drafter's K/V mode is not paged/ring"); + if (st.kv_hybrid) return decline("the drafter's K/V is hybrid (kv_hybrid)"); + if (mtp.device() != m.device) return decline("the drafter is on another device than this prefill path"); const auto t0 = Clock::now(); const core::ModelGeometry& g = *m.g; const int64_t Nn = g.n_embd, HCN = g.hc * g.n_embd, KV = g.n_head_kv * g.head_dim; @@ -1301,12 +1305,13 @@ bool Prefill::draft_kv(core::MtpDrafter& mtp, const float* R_rows, const int32_t const void* w_k = mtp.tensor_q8("self_attn.k_proj.weight"); const void* w_v = mtp.tensor_q8("self_attn.v_proj.weight"); const float* w_kn = mtp.tensor_f32("self_attn.k_norm.weight"); - if (!w_ne || !w_fe || !w_nh || !w_fh || !w_hn || !w_dn || !w_up || !w_k || !w_v || !w_kn) return false; + if (!w_ne || !w_fe || !w_nh || !w_fh || !w_hn || !w_dn || !w_up || !w_k || !w_v || !w_kn) + return decline("a drafter tensor is missing (Q8_0 projections / norms)"); const core::NativeEmbed* nemb = core::native_embed(); const core::WeightRef* wemb = nemb ? nullptr : m.wt->find("token_embd.weight"); if (!nemb && (wemb == nullptr || wemb->codebook_iq4nl || wemb->ne0 != g.n_embd || wemb->group_elems <= 0 || (wemb->code_bits != 2 && wemb->code_bits != 4 && wemb->code_bits != 8))) - return false; + return decline("the token embedding is not gatherable on this path"); // the cells the drafter's window can still reach const int64_t r0 = std::max(0, mtp.first_needed() - cell0); if (r0 >= n) return true; @@ -1321,11 +1326,11 @@ bool Prefill::draft_kv(core::MtpDrafter& mtp, const float* R_rows, const int32_t // SYCL port: B is the batch buffers' capacity, not the row count (each batch uses nb <= B rows), so a short // prompt gets 64-row buffers instead of the per-6-token fallback (19 tokens: 106 ms there, a few ms here) const int64_t cap = (int64_t) (m.region_bytes / per_row) & ~(int64_t) 63; - if (cap < 64) return false; + if (cap < 64) return decline("too little scratch for a 64-row batch"); int64_t B = std::min(std::max(n - r0, 64), cap); if (st.kv_mode == 2) // #453: a ring: one batch's cells must not share a slot (a batch can straddle one page more) B = std::min(B, ((st.n_slots - 1) * strata::kernels::qsa_real_shapes().page_size) & ~(int64_t) 63); - if (B < 64) return false; + if (B < 64) return decline("too little scratch for a 64-row batch"); uint8_t* q = m.region; auto carve = [&](size_t bytes) { void* p = q; q += (bytes + 255) & ~(size_t) 255; return p; }; float* emb = (float*) carve((size_t) B * Nn * 4); @@ -1348,7 +1353,7 @@ bool Prefill::draft_kv(core::MtpDrafter& mtp, const float* R_rows, const int32_t void* xq = q8 ? carve(mmq::q8_bytes(B * g.hc, Nn)) : nullptr; int32_t* ident = q8 ? (int32_t*) carve((size_t) B * g.hc * 4) : nullptr; int32_t* bnd = q8 ? (int32_t*) carve(16) : nullptr; - if ((uint64_t) (q - m.region) > m.region_bytes) return false; + if ((uint64_t) (q - m.region) > m.region_bytes) return decline("the batch buffers do not fit the scratch region"); static const bool timing = std::getenv("STRATA_DRAFT_TIMING") != nullptr; // debug: where this pass's time goes if (timing) m.cs->wait(); const auto ti0 = Clock::now(); diff --git a/tools/split_mtp_batch_parity.py b/tools/split_mtp_batch_parity.py new file mode 100755 index 00000000..e976fbb8 --- /dev/null +++ b/tools/split_mtp_batch_parity.py @@ -0,0 +1,81 @@ +#!/usr/bin/env python3 +"""Live parity check for STRATA_SPLIT_MTP_BATCH (needs a running engine; no model on the build box). + + split_mtp_batch_parity.py dump OUT.json [--url URL] [--key-file FILE] [--long-words N] + split_mtp_batch_parity.py compare A.json B.json + +`dump` sends 5 fixed greedy prompts x 256 tokens and one long prompt (default ~25k tokens) x 256 tokens to a +server started WITHOUT the env (A) or WITH STRATA_SPLIT_MTP_BATCH=1 (B), and stores the texts. `compare` exits 0 +when every text is identical, 1 otherwise, printing PASS/FAIL lines. The drafter's K/V is not bit-identical +(Q8_1 x Q8_0 MMQ instead of mmvq), so only the target's tokens are compared here; read `drafts accepted X of Y` +from the engine log for each arm (expect within +-3 points). +""" +import json +import sys +import urllib.request + +PROMPTS = [ + "Write a 200 word story about a lighthouse keeper who finds a message in a bottle.", + "Explain how a binary search tree stays balanced, with a short Python example.", + "List the planets of the solar system with one fact each.", + "Translate to French and then explain the grammar: 'The quick brown fox jumps over the lazy dog.'", + "Write a C function that reverses a singly linked list and explain its complexity.", +] + + +def haystack(n_entries): + w = ["amber", "birch", "cedar", "delta", "ember", "fjord", "grove", "harbor", "iris", "juniper"] + return "\n".join( + f"Entry {i}: the {w[(i * 3) % 10]} station {(i * 7) % 997} logged a reading of {(i * 31) % 1009}." + for i in range(n_entries) + ) + + +def ask(url, key, content, n): + body = json.dumps({"model": "qwen3.8-flash-next-ud-q4_k_xl", "messages": [{"role": "user", "content": content}], + "max_tokens": n, "temperature": 0.0, "chat_template_kwargs": {"enable_thinking": False}}).encode() + hdr = {"Content-Type": "application/json"} + if key: + hdr["Authorization"] = "Bearer " + key + d = json.load(urllib.request.urlopen(urllib.request.Request(url, body, hdr), timeout=3600)) + return d["choices"][0]["message"]["content"], d["usage"] + + +def main(argv): + if len(argv) >= 3 and argv[0] == "compare": + a, b = (json.load(open(p)) for p in argv[1:3]) + bad = 0 + for k in a: + same = a[k]["text"] == b.get(k, {}).get("text") + print(("PASS" if same else "FAIL"), k, f"({a[k]['completion_tokens']} vs {b.get(k, {}).get('completion_tokens')} tokens)") + bad += not same + print("PARITY", "OK" if not bad else f"BROKEN ({bad} differ)") + return 1 if bad else 0 + if len(argv) >= 2 and argv[0] == "dump": + url = "http://127.0.0.1:8000/v1/chat/completions" + key = None + words = 1100 + i = 2 + while i < len(argv): + if argv[i] == "--url": + url = argv[i + 1] + elif argv[i] == "--key-file": + key = open(argv[i + 1]).read().strip() + elif argv[i] == "--long-words": + words = int(argv[i + 1]) + i += 2 + out = {} + for n, p in enumerate(PROMPTS): + t, u = ask(url, key, p, 256) + out[f"short{n}"] = {"text": t, "completion_tokens": u["completion_tokens"], "prompt_tokens": u["prompt_tokens"]} + t, u = ask(url, key, "Summarise the log below in three sentences.\n" + haystack(words), 256) + out["long"] = {"text": t, "completion_tokens": u["completion_tokens"], "prompt_tokens": u["prompt_tokens"]} + json.dump(out, open(argv[1], "w"), indent=1) + print({k: v["prompt_tokens"] for k, v in out.items()}) + return 0 + print(__doc__) + return 2 + + +if __name__ == "__main__": + sys.exit(main(sys.argv[1:])) From 425fc48a821193bffc2c1d99c1ecee4f4bcfc0c7 Mon Sep 17 00:00:00 2001 From: noon-at-cgn <75719527+noon-at-cgn@users.noreply.github.com> Date: Thu, 8 Oct 2026 14:17:03 -0400 Subject: [PATCH 9/9] docs: replace the evidence placeholder in the split MTP-batch paragraph with the measured result --- docs/MULTI_GPU.md | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/docs/MULTI_GPU.md b/docs/MULTI_GPU.md index 68ce802d..f925c658 100644 --- a/docs/MULTI_GPU.md +++ b/docs/MULTI_GPU.md @@ -110,10 +110,17 @@ draft K/V (`STRATA_MTP_BATCH_RING=0` sends a ring back to the old pass); otherwi `strata serve: draft layer prompt K/V batched on CUDA ...` or `strata serve: STRATA_SPLIT_MTP_BATCH=1 declined, the drafter's own pass runs: `. The draft layer's K/V come out of Q8_1 x Q8_0 MMQ instead of its own mmvq, so the drafts, and how many are accepted, can move; the target's tokens are decided by the verify window. -`tools/split_mtp_batch_parity.py` compares the greedy texts of the two arms. Preliminary, one machine (2x RTX 3080 20 GB, -UD-Q4_K_XL, `--layer-split 23`, `--batch-mtp`, two slots), few runs per arm, TODO-EVIDENCE (n, the A/A control and the -parity result): a 24K-token prompt read at 1,751 tok/s without and 1,857 with; 25K-token prompts +5 to 7%, 104K +2%; -drafts accepted 0.633 without, 0.635 with. +`tools/split_mtp_batch_parity.py` compares the greedy texts of the two arms. Measured on one machine (2x RTX 3080 20 GB +at 220 W, Xeon E5-2696 v4, UD-Q4_K_XL, `--layer-split 23`, `--batch-mtp`, two slots, `--prefill auto:16384`), two full +restarts per arm in the order off, on, off, on, the same binary in every arm: pooled medians of the prompt read were 1,996 +tok/s without and 2,129 with at 25K tokens (+6.7%), 2,448 and 2,553 at 51K (+4.3%), 2,846 and 2,940 at 104K (+3.3%); all 8 +on/off ratios of medians are above 1 (1.03 to 1.08), and the two off restarts differ by at most 2% at 25K and 0.3% at the +other sizes. The host's "after each chunk" time per request fell from 0.9-1.3 s to 0.1-0.25 s (one restart per arm). Greedy +output (`--adapt-every 0 --suffix-draft 0`, five prompts of 256 tokens and one 25.5K-token prompt) was identical in 6 of 6 +prompts in all five comparisons, the two runs inside one process (A/A) included, and the drafts accepted were 826 of 1,210 +in every run, so no difference in acceptance was visible. Decode is not shown to be unchanged: the medians with the variable +set were about 3% lower (pooled solo 82.6 -> 80.2 tok/s, two streams 93.2 -> 90.8), and the same configuration restarted +twice moved up to 4.7%, so two restarts per arm can neither confirm nor exclude it; the change touches only the prompt path. **Each card loads only its own layers' dense weights** (0.1.39, PR #639) with explicit split points (`--layer-split 27`, not `auto`): every card used to keep a full copy (~3.4 GB for the Coder) though its stage reads only its own