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.
This commit is contained in:
Daehun authored and Niko1221 committed 2026-09-30 16:36:32 +02:00
1 parent e200e08f54
commit 80f83268d4
7 files changed
+329 -10

No files matched your search

+6
View File
@@ -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})
+1 -1
View File
@@ -385,7 +385,7 @@ public:
/// Allocates and loads `<pack_dir>/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();
+8 -1
View File
@@ -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<uint64_t>& 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<uint64_t>& bounds, uint64_t max_pinned_bytes = 0,
const std::string& shared_file = {}, uint64_t shared_pack_hash = 0);
std::vector<uint64_t> 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;
+117 -3
View File
@@ -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<uint8_t> 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<uint8_t> buf((size_t) std::min<uint64_t>(sample, bytes));
for (uint64_t off : starts) {
if (buf.empty()) break;
const uint64_t at = std::min<uint64_t>(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<std::filesystem::path> 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<uint64_t> 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)
+125 -4
View File
@@ -5,6 +5,7 @@
#include <cuda_runtime.h>
#include <atomic>
#include <cerrno>
#include <cstdlib>
#include <cstdio>
#include <cstring>
@@ -23,7 +24,10 @@
#ifdef _WIN32
#include <windows.h>
#else
#include <fcntl.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <unistd.h>
#include <linux/mman.h>
#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<uint64_t>& 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;
}
}
+61
View File
@@ -0,0 +1,61 @@
// Linux selftest for the optional MAP_SHARED backing of PinnedArena.
#include "strata/core/pinned.hpp"
#include <cstdio>
#include <cstdlib>
#include <string>
#include <vector>
#include <unistd.h>
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<uint64_t> 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;
}
+11 -1
View File
@@ -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;
}