From 80f83268d466d279cf25035e4cbd7813c0456ea7 Mon Sep 17 00:00:00 2001 From: Daehun <43494047+rhgo1749@users.noreply.github.com> Date: Wed, 30 Sep 2026 07:58:40 +0900 Subject: [PATCH] core: add guarded shared expert arena backing Rebase the shared-arena primitive onto 0.1.26, bind backing files to a pack fingerprint with a small header, and document tmpfs/hugetlbfs placement. --- CMakeLists.txt | 6 ++ include/strata/core/expert_source.hpp | 2 +- include/strata/core/pinned.hpp | 9 +- src/core/expert_source.cpp | 120 +++++++++++++++++++++++- src/core/pinned.cu | 129 +++++++++++++++++++++++++- src/core/pinned_shared_test.cpp | 61 ++++++++++++ src/program/generate.cpp | 12 ++- 7 files changed, 329 insertions(+), 10 deletions(-) create mode 100644 src/core/pinned_shared_test.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 4c430ed3..f61b78d5 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -531,6 +531,12 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) target_link_libraries(platform_memory_test PRIVATE strata_core ${_strata_gpu_runtime_target}) add_test(NAME platform_memory_test COMMAND platform_memory_test) + if(CMAKE_SYSTEM_NAME STREQUAL "Linux") + add_executable(pinned_shared_test src/core/pinned_shared_test.cpp) + target_link_libraries(pinned_shared_test PRIVATE strata_core ${_strata_gpu_runtime_target}) + add_test(NAME pinned_shared_test COMMAND pinned_shared_test) + endif() + # Plan v0.3 P2: the n-gram table read straight from the SSD. The selftest needs only the CPU and a temp file. add_executable(ple_reader_test src/ngram/ple_reader_test.cpp) target_include_directories(ple_reader_test PRIVATE ${_strata_gpu_include_directories}) diff --git a/include/strata/core/expert_source.hpp b/include/strata/core/expert_source.hpp index 0b357a1b..16305e34 100644 --- a/include/strata/core/expert_source.hpp +++ b/include/strata/core/expert_source.hpp @@ -385,7 +385,7 @@ public: /// Allocates and loads `/experts.bin`. Prints nothing; the caller reports `note()` and the load /// rate, because those are the two numbers that say whether the arena is the one that was asked for. bool open(const std::string& pack_dir, int64_t n_layers, int64_t n_expert, int threads, std::string& err, - uint64_t max_pinned_bytes = 0); + uint64_t max_pinned_bytes = 0, const std::string& shared_arena_file = {}); /// Plan v0.3 P6: a native pack without experts.bin takes its experts from the model's shard 1. void set_gguf(const std::string& shard1) { gguf_ = shard1; } void close(); diff --git a/include/strata/core/pinned.hpp b/include/strata/core/pinned.hpp index cc4ef1cb..530acd4d 100644 --- a/include/strata/core/pinned.hpp +++ b/include/strata/core/pinned.hpp @@ -40,8 +40,15 @@ struct PinnedArena { /// Plan v0.3 P6: slices of different sizes (one per layer of a native pack), given as their start offsets /// followed by the end of the last one. `slice_starts` holds the registered ones. /// `max_pinned_bytes`: optional cap on CUDA registration. 0 preserves the normal unrestricted path. - PinnedArena(uint64_t bytes, const std::vector& bounds, uint64_t max_pinned_bytes = 0); + /// `shared_file`: on Linux, use a file-backed MAP_SHARED mapping instead of anonymous memory. + /// `shared_pack_hash` identifies the pack that is allowed to populate that backing. The file carries a + /// small header and is refused when its stored hash does not match. Empty `shared_file` preserves the + /// existing allocation path. Population/coordination and backing-file lifetime remain the caller's job. + PinnedArena(uint64_t bytes, const std::vector& bounds, uint64_t max_pinned_bytes = 0, + const std::string& shared_file = {}, uint64_t shared_pack_hash = 0); std::vector slice_starts; + void* mapping_base = nullptr; ///< actual mapping start; differs from base when a shared-file header exists + uint64_t mapping_bytes = 0; ///< bytes to release from mapping_base ~PinnedArena(); PinnedArena(const PinnedArena&) = delete; PinnedArena& operator=(const PinnedArena&) = delete; diff --git a/src/core/expert_source.cpp b/src/core/expert_source.cpp index d235b958..5ee7acd1 100644 --- a/src/core/expert_source.cpp +++ b/src/core/expert_source.cpp @@ -1100,6 +1100,111 @@ void expert_hit_run(void* user, void* stream, HitPhase phase, const int32_t* ids // ================================ THE RESIDENT ARENA (R2.1) ================================ +namespace { + +void hash_u64(uint64_t& h, uint64_t v) { + h = fnv1a64((const uint8_t*) &v, sizeof v, h); +} + +void hash_text(uint64_t& h, const std::string& s) { + h = fnv1a64((const uint8_t*) s.data(), (uint64_t) s.size(), h); +} + +bool hash_small_file(const std::filesystem::path& path, uint64_t& h, std::string& err) { + hash_text(h, path.filename().string()); + std::ifstream f(path, std::ios::binary); + if (!f) { + hash_u64(h, 0); + return true; + } + hash_u64(h, 1); + std::vector buf(64u << 10); + for (;;) { + f.read((char*) buf.data(), (std::streamsize) buf.size()); + const std::streamsize n = f.gcount(); + if (n > 0) h = fnv1a64(buf.data(), (uint64_t) n, h); + if (f.eof()) break; + if (!f) { + err = "ArenaExpertSource: cannot hash pack metadata " + path.string(); + return false; + } + } + return true; +} + +bool hash_sampled_file(const std::filesystem::path& path, uint64_t& h, std::string& err) { + std::ifstream f(path, std::ios::binary | std::ios::ate); + if (!f) { + err = "ArenaExpertSource: cannot sample pack source " + path.string(); + return false; + } + const std::streamoff end = f.tellg(); + if (end < 0) { + err = "ArenaExpertSource: cannot size pack source " + path.string(); + return false; + } + const uint64_t bytes = (uint64_t) end; + hash_text(h, path.filename().string()); + hash_u64(h, bytes); + constexpr uint64_t sample = 64u << 10; + const uint64_t starts[3] = {0, bytes / 2, bytes > sample ? bytes - sample : 0}; + std::vector buf((size_t) std::min(sample, bytes)); + for (uint64_t off : starts) { + if (buf.empty()) break; + const uint64_t at = std::min(off, bytes - (uint64_t) buf.size()); + f.clear(); + f.seekg((std::streamoff) at); + f.read((char*) buf.data(), (std::streamsize) buf.size()); + if ((size_t) f.gcount() != buf.size()) { + err = "ArenaExpertSource: short read while hashing pack source " + path.string(); + return false; + } + hash_u64(h, at); + h = fnv1a64(buf.data(), (uint64_t) buf.size(), h); + } + return true; +} + +bool shared_arena_pack_hash(const std::string& pack_dir, const std::string& experts_path, + const std::string& gguf, const strata::kernels::cpu::ExpertLayout& lay, + uint64_t& out, std::string& err) { + uint64_t h = 1469598103934665603ull; + hash_text(h, "strata-shared-expert-arena-pack-v1"); + hash_u64(h, (uint64_t) lay.n_layers); + hash_u64(h, (uint64_t) lay.n_expert); + hash_u64(h, lay.total); + hash_u64(h, lay.max_blob); + hash_u64(h, lay.native ? 1 : 0); + + const std::filesystem::path pack(pack_dir); + for (const char* name : {"manifest.json", "index.txt", "native_experts.txt"}) { + if (!hash_small_file(pack / name, h, err)) return false; + } + + if (std::filesystem::exists(experts_path)) { + if (!hash_sampled_file(experts_path, h, err)) return false; + } else if (!gguf.empty()) { + // Native packs may read experts straight from one or more GGUF shards. Sample every distinct source + // file named by native_experts.txt; this keeps the fingerprint cheap while still tying it to the model + // bytes rather than only to an equal-size layout. + const std::filesystem::path first(gguf); + std::vector sources{first}; + for (const std::string& name : lay.gguf_file) { + if (name.empty()) continue; + const std::filesystem::path p = first.parent_path() / name; + if (std::find(sources.begin(), sources.end(), p) == sources.end()) sources.push_back(p); + } + for (const auto& p : sources) { + if (!hash_sampled_file(p, h, err)) return false; + } + } + + out = h == 0 ? 1 : h; + return true; +} + +} // namespace + // Plan v0.3 P6: the arena from the model's shard 1. Each layer's gate, up and down tensors hold the 512 experts // one after another; they are read in chunks and each expert's slice lands at its place in the blob // [gate rows | up rows | down rows] - the layout tools/iq_pack.py would have written to experts.bin. @@ -1172,7 +1277,8 @@ LoadStats load_experts_gguf(const std::string& gguf, uint8_t* dst, const strata: ArenaExpertSource::~ArenaExpertSource() { close(); } bool ArenaExpertSource::open(const std::string& pack_dir, int64_t n_layers, int64_t n_expert, int threads, - std::string& err, uint64_t max_pinned_bytes) { + std::string& err, uint64_t max_pinned_bytes, + const std::string& shared_arena_file) { close(); const std::string path = pack_dir + "/experts.bin"; // plan v0.3 P6: the layout (canonical, or a native pack's per-layer blobs) was loaded by the driver @@ -1204,6 +1310,10 @@ bool ArenaExpertSource::open(const std::string& pack_dir, int64_t n_layers, int6 } } + uint64_t pack_hash = 0; + if (!shared_arena_file.empty() && + !shared_arena_pack_hash(pack_dir, path, gguf_, lay, pack_hash, err)) return false; + // one layer per registration slice, so no expert straddles two registrations. The arena is one blob // longer than the file: a copy of a whole VRAM slot (the largest blob) may then start at any expert. std::vector bounds, loff, lbytes; @@ -1213,10 +1323,14 @@ bool ArenaExpertSource::open(const std::string& pack_dir, int64_t n_layers, int6 lbytes.push_back(lay.blob_bytes(l) * (uint64_t) n_expert); } bounds.push_back(want); - PinnedArena* a = new PinnedArena(want + (uint64_t) blob, bounds, max_pinned_bytes); + PinnedArena* a = new PinnedArena(want + (uint64_t) blob, bounds, max_pinned_bytes, + shared_arena_file, pack_hash); if (!a->valid()) { + const std::string why = a->note; delete a; - err = "ArenaExpertSource: the arena could not be reserved (" + std::to_string(want) + " B)"; + err = "ArenaExpertSource: the arena could not be reserved (" + + std::to_string(want + (uint64_t) blob) + " B)" + + (why.empty() ? std::string{} : ": " + why); return false; } const LoadStats st = from_gguf ? load_experts_gguf(gguf_, a->data(), lay, threads) diff --git a/src/core/pinned.cu b/src/core/pinned.cu index 0e3e6b4a..49bb5c47 100644 --- a/src/core/pinned.cu +++ b/src/core/pinned.cu @@ -5,6 +5,7 @@ #include #include +#include #include #include #include @@ -23,7 +24,10 @@ #ifdef _WIN32 #include #else +#include #include +#include +#include #include #ifndef MAP_HUGE_2MB #define MAP_HUGE_2MB (21 << 26) @@ -34,9 +38,31 @@ namespace strata::core { namespace { +constexpr uint64_t kSharedArenaHeaderBytes = 4096; +constexpr char kSharedArenaMagic[16] = "STRATA-ARENA-V1"; + +struct SharedArenaHeader { + char magic[16]; + uint32_t version; + uint32_t header_bytes; + uint64_t arena_bytes; + uint64_t pack_hash; + uint64_t reserved[4]; +}; +static_assert(sizeof(SharedArenaHeader) <= kSharedArenaHeaderBytes); + // A 2 MB-aligned reservation. Large pages first, then the largest alignment the OS will give us for free. -void* reserve(uint64_t bytes, PageBacking& got, std::string& note) { +// A non-empty shared_file instead maps one file whose first 4 KiB identify the pack and whose remaining bytes +// are the resident arena. Keeping the header inside the same mapping also works for tmpfs and hugetlbfs. +void* reserve(uint64_t bytes, PageBacking& got, std::string& note, const std::string& shared_file, + uint64_t shared_pack_hash, void*& mapping_base, uint64_t& mapping_bytes) { + mapping_base = nullptr; + mapping_bytes = 0; #ifdef _WIN32 + if (!shared_file.empty()) { + note = "shared-file arena backing is not implemented on Windows"; + return nullptr; + } // MEM_LARGE_PAGES needs SeLockMemoryPrivilege. Having it assigned to the account is not enough: the // PROCESS must enable it in its own token (AdjustTokenPrivileges) before VirtualAlloc, or the call fails. // An account without the assignment, or a failure to enable, leaves the process as it was: VirtualAlloc @@ -84,6 +110,94 @@ void* reserve(uint64_t bytes, PageBacking& got, std::string& note) { got = PageBacking::NormalPages; return p; #else + if (!shared_file.empty()) { + if (shared_pack_hash == 0) { + note = "shared arena requires a nonzero pack hash"; + return nullptr; + } + if (bytes > UINT64_MAX - kSharedArenaHeaderBytes) { + note = "shared arena size overflows its header"; + return nullptr; + } + const uint64_t file_bytes = kSharedArenaHeaderBytes + bytes; + const int fd = open(shared_file.c_str(), O_RDWR | O_CREAT | O_CLOEXEC, 0600); + if (fd < 0) { + note = "cannot open shared arena " + shared_file + ": " + std::strerror(errno); + return nullptr; + } + struct stat st{}; + if (fstat(fd, &st) != 0) { + const int e = errno; + close(fd); + note = "cannot stat shared arena " + shared_file + ": " + std::strerror(e); + return nullptr; + } + + const bool fresh = st.st_size == 0; + if (fresh) { + if (ftruncate(fd, (off_t) file_bytes) != 0) { + const int e = errno; + close(fd); + note = "cannot size shared arena " + shared_file + ": " + std::strerror(e); + return nullptr; + } + SharedArenaHeader hdr{}; + std::memcpy(hdr.magic, kSharedArenaMagic, sizeof hdr.magic); + hdr.version = 1; + hdr.header_bytes = (uint32_t) kSharedArenaHeaderBytes; + hdr.arena_bytes = bytes; + hdr.pack_hash = shared_pack_hash; + const ssize_t written = pwrite(fd, &hdr, sizeof hdr, 0); + if (written != (ssize_t) sizeof hdr) { + const int e = errno; + close(fd); + note = "cannot write shared arena header " + shared_file + ": " + + (written < 0 ? std::string(std::strerror(e)) : std::string("short write")); + return nullptr; + } + } else { + if (st.st_size < 0 || (uint64_t) st.st_size != file_bytes) { + close(fd); + note = "shared arena " + shared_file + " is " + + std::to_string((unsigned long long) st.st_size) + " B, expected " + + std::to_string((unsigned long long) file_bytes) + " B including its header"; + return nullptr; + } + SharedArenaHeader hdr{}; + const ssize_t got_header = pread(fd, &hdr, sizeof hdr, 0); + if (got_header != (ssize_t) sizeof hdr || + std::memcmp(hdr.magic, kSharedArenaMagic, sizeof hdr.magic) != 0 || + hdr.version != 1 || hdr.header_bytes != kSharedArenaHeaderBytes || hdr.arena_bytes != bytes) { + close(fd); + note = "shared arena " + shared_file + " has an incompatible or missing header"; + return nullptr; + } + if (hdr.pack_hash != shared_pack_hash) { + close(fd); + char b[256]; + std::snprintf(b, sizeof b, + "shared arena %s was written for pack hash %016llx, expected %016llx", + shared_file.c_str(), (unsigned long long) hdr.pack_hash, + (unsigned long long) shared_pack_hash); + note = b; + return nullptr; + } + } + + void* map = mmap(nullptr, (size_t) file_bytes, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); + const int e = errno; + close(fd); + if (map == MAP_FAILED) { + note = "cannot map shared arena " + shared_file + ": " + std::strerror(e); + return nullptr; + } + mapping_base = map; + mapping_bytes = file_bytes; + got = PageBacking::NormalPages; + note = "MAP_SHARED file " + shared_file + " (pack hash checked)"; + return (uint8_t*) map + kSharedArenaHeaderBytes; + } + void* p = mmap(nullptr, bytes, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS | MAP_HUGETLB | MAP_HUGE_2MB, -1, 0); if (p != MAP_FAILED) { @@ -138,9 +252,14 @@ PinnedArena::PinnedArena(uint64_t bytes, uint64_t slice) : PinnedArena(bytes, un } PinnedArena::PinnedArena(uint64_t bytes, const std::vector& bounds, - uint64_t max_pinned_bytes) : capacity(bytes) { + uint64_t max_pinned_bytes, const std::string& shared_file, + uint64_t shared_pack_hash) : capacity(bytes) { if (bytes == 0) return; - base = reserve(bytes, backing, note); + base = reserve(bytes, backing, note, shared_file, shared_pack_hash, mapping_base, mapping_bytes); + if (base != nullptr && mapping_base == nullptr) { + mapping_base = base; + mapping_bytes = bytes; + } // Register with CUDA BEFORE any page is touched: cudaHostRegister pins what is resident now, and a region // that has already been faulted in page by page is far more expensive to register and may fail outright. @@ -218,8 +337,10 @@ PinnedArena::~PinnedArena() { } else { cudaHostUnregister(base); } - release(base, capacity); + release(mapping_base ? mapping_base : base, mapping_bytes ? mapping_bytes : capacity); base = nullptr; + mapping_base = nullptr; + mapping_bytes = 0; } } diff --git a/src/core/pinned_shared_test.cpp b/src/core/pinned_shared_test.cpp new file mode 100644 index 00000000..c663f1a0 --- /dev/null +++ b/src/core/pinned_shared_test.cpp @@ -0,0 +1,61 @@ +// Linux selftest for the optional MAP_SHARED backing of PinnedArena. +#include "strata/core/pinned.hpp" + +#include +#include +#include +#include + +#include + +int main() { + char path[] = "/tmp/strata-shared-arena-XXXXXX"; + const int fd = mkstemp(path); + if (fd < 0) { + std::perror("mkstemp"); + return 2; + } + close(fd); + + int fail = 0; + const uint64_t bytes = 64u << 10; + const uint64_t pack_hash = 0x0123456789abcdefull; + const std::vector no_bounds; + { + strata::core::PinnedArena first(bytes, no_bounds, 0, path, pack_hash); + if (!first.valid()) { + std::fprintf(stderr, "first shared arena failed: %s\n", first.note.c_str()); + fail = 1; + } else { + first.data()[123] = 0x5a; + + strata::core::PinnedArena second(bytes, no_bounds, 0, path, pack_hash); + if (!second.valid()) { + std::fprintf(stderr, "second shared arena failed: %s\n", second.note.c_str()); + fail = 1; + } else if (second.data()[123] != 0x5a) { + std::fprintf(stderr, "shared mapping did not expose the same bytes\n"); + fail = 1; + } + + strata::core::PinnedArena wrong_pack(bytes, no_bounds, 0, path, pack_hash + 1); + if (wrong_pack.valid() || wrong_pack.note.find("pack hash") == std::string::npos) { + std::fprintf(stderr, "pack mismatch was not refused: %s\n", wrong_pack.note.c_str()); + fail = 1; + } + + strata::core::PinnedArena wrong_size(bytes * 2, no_bounds, 0, path, pack_hash); + if (wrong_size.valid() || wrong_size.note.find("expected") == std::string::npos) { + std::fprintf(stderr, "size mismatch was not refused: %s\n", wrong_size.note.c_str()); + fail = 1; + } + } + } + + if (unlink(path) != 0) { + std::perror("unlink"); + fail = 1; + } + std::printf("pinned_shared_test: %s\n", fail ? "FAILED" : "OK"); + return fail; +} diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 60700870..e75ac2c8 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -182,6 +182,7 @@ struct Options { /// is reserved for a host thread that has nothing to do while the drain runs. bool no_host_worker = false; bool mmap_experts = false; ///< R2.1: opt OUT of the resident arena, back to MapViewOfFile + std::string shared_expert_arena; ///< Linux: optional file backing for the resident arena shared by processes bool resident_cpu_experts = false; ///< mmap-backed static-cache misses copied into ordinary RAM /// R4: slots of VRAM-resident experts. **0 = off, and off is the default.** /// **THE COMMENT THAT USED TO BE HERE WAS FALSE AND ROUND 328 MEASURED IT.** It said "the cache has no @@ -436,6 +437,9 @@ void usage() { " --mmap-experts R2.1: opt OUT of the resident expert arena, back to MapViewOfFile.\n" " The A/B arm: the mmap's rate depends on the OS page cache holding\n" " 34 GB, and measured 71.97 vs 34.78 ms/token cold vs warm.\n" + " --shared-expert-arena FILE Linux: back the resident arena with one MAP_SHARED file.\n" + " Put this file on /dev/shm or hugetlbfs, not ordinary SSD storage.\n" + " A small header binds an existing backing file to the same pack.\n" " --resident-cpu-experts with mmap and a static profile, keep CPU misses resident in ordinary RAM.\n" " Borrowed GPU-cache entries may read from mmap during prompt prefill.\n"); } @@ -1071,6 +1075,7 @@ int main(int argc, char** argv) { else if (a == "--expert-profile") o.expert_profile = next("--expert-profile"); else if (a == "--gpu-stages") o.gpu_stages = true; else if (a == "--mmap-experts") o.mmap_experts = true; + else if (a == "--shared-expert-arena") o.shared_expert_arena = next("--shared-expert-arena"); else if (a == "--resident-cpu-experts") o.resident_cpu_experts = true; else if (a == "--stats") o.stats = true; else if (a == "--shared-late") o.shared_late = true; @@ -1140,6 +1145,10 @@ int main(int argc, char** argv) { } } const bool multi_gpu = !split_devs.empty() && !split_same; + if (o.mmap_experts && !o.shared_expert_arena.empty()) { + std::fprintf(stderr, "strata generate: --shared-expert-arena backs the resident arena and cannot be used with --mmap-experts\n"); + return 2; + } if (o.resident_cpu_experts && (!o.mmap_experts || o.expert_profile.empty() || o.adapt_every != 0)) { std::fprintf(stderr, "strata generate: --resident-cpu-experts requires --mmap-experts, a static --expert-profile and --adapt-every 0\n"); return 2; @@ -1820,7 +1829,8 @@ int main(int argc, char** argv) { // (a layer split across GPUs too: pinning all of it into two contexts leaves WDDM refusing every later // allocation - measured on the 5080 + 3090 rig: cudaMemGetInfo and the next cudaMalloc fail) const uint64_t pin_limit = (o.expert_cache_remote[0] > 0 || multi_gpu) ? (8ull << 30) : 0; - if (!arena_src.open(o.pack, g.n_layers, g.n_expert, /*threads=*/6, err, pin_limit)) { + if (!arena_src.open(o.pack, g.n_layers, g.n_expert, /*threads=*/6, err, pin_limit, + o.shared_expert_arena)) { std::fprintf(stderr, "strata generate: %s\n", err.c_str()); return 1; }