diff --git a/include/strata/core/expert_source.hpp b/include/strata/core/expert_source.hpp index 941eff73..e798670a 100644 --- a/include/strata/core/expert_source.hpp +++ b/include/strata/core/expert_source.hpp @@ -750,8 +750,9 @@ private: /// layout's type and dimensions, and inside the file. `native` is the --native shard (see set_gguf). bool check_experts_gguf(const std::string& native, const strata::kernels::cpu::ExpertLayout& lay, std::string& err); /// Fills `dst` (lay.total bytes, the experts.bin layout) from the GGUF files, one role at a time. -/// `unbuffered`: each chunk read past the file cache (Windows). +/// `unbuffered`: each chunk read past the file cache (Windows); `ready`: layer l is written only once +/// *ready > l + 1 (an arena that is still being registered). LoadStats load_experts_gguf(const std::string& native, uint8_t* dst, const strata::kernels::cpu::ExpertLayout& lay, - int threads, bool unbuffered = false); + int threads, bool unbuffered = false, const std::atomic* ready = nullptr); } // namespace strata::core diff --git a/include/strata/core/pinned.hpp b/include/strata/core/pinned.hpp index 28a6f987..51d0948f 100644 --- a/include/strata/core/pinned.hpp +++ b/include/strata/core/pinned.hpp @@ -14,6 +14,7 @@ // fallback is the common case and not an error path. #pragma once +#include #include #include #include @@ -51,6 +52,14 @@ struct PinnedArena { /// 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); + /// #285: reserve only; the caller registers the slices with register_slices(), on a thread, while its readers + /// fill the ones already registered (one registration of the whole arena cost ~2.5 s at 33 GiB of 4 KB pages). + struct Deferred {}; + PinnedArena(uint64_t bytes, const std::vector& bounds, Deferred); + /// Registers the deferred slices in order, publishing how many are done in `ready`, and INT_MAX once it + /// returns (a slice CUDA refuses ends the registration, and the rest is kept resident by the working-set lock). + void register_slices(std::atomic& ready); + std::vector bounds_; 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 @@ -101,14 +110,19 @@ struct LoadStats { LoadStats load_experts(const std::string& path, uint8_t* dst, uint64_t blob_bytes, uint64_t blobs_per_layer, uint64_t layers, int threads, uint64_t chunk); /// Plan v0.3 P6: the same with one byte range per layer (`layer_off[L]`, `layer_bytes[L]`). +/// `ready` (optional): layer L is written only once *ready > L + 1 - its slice and the next one registered (a +/// PinnedArena registering its slices meanwhile: writing a page while cudaHostRegister runs on it corrupted the +/// arena under WDDM, even on large pages; a layer boundary inside a page puts that page in both registrations). LoadStats load_experts_ranges(const std::string& path, uint8_t* dst, const std::vector& layer_off, - const std::vector& layer_bytes, int threads, uint64_t chunk); + const std::vector& layer_bytes, int threads, uint64_t chunk, + const std::atomic* ready = nullptr); /// The same ranges read UNBUFFERED straight into `dst` (Windows): no staging buffer and no file-cache copy - the /// drive's DMA lands where the experts live. Every range, `dst` and `chunk` must be 4 KiB aligned; returns ok = /// false with an empty `error` when they are not (or off Windows), and the caller falls back to load_experts_ranges. LoadStats load_experts_direct(const std::string& path, uint8_t* dst, const std::vector& layer_off, - const std::vector& layer_bytes, int threads, uint64_t chunk); + const std::vector& layer_bytes, int threads, uint64_t chunk, + const std::atomic* ready = nullptr); /// Whether the expert files are better read unbuffered (Windows; false elsewhere): a timed probe of random 64 KiB /// reads says they are not in the OS file cache (a cached read takes ~10 us, the drive ~80), and the RAM left diff --git a/src/core/expert_source.cpp b/src/core/expert_source.cpp index be4a8139..05c20f8b 100644 --- a/src/core/expert_source.cpp +++ b/src/core/expert_source.cpp @@ -2917,7 +2917,13 @@ bool check_experts_gguf(const std::string& gguf, const strata::kernels::cpu::Exp // `unbuffered` (Windows, experts_unbuffered): each chunk's 4 KiB-aligned window is read with FILE_FLAG_NO_BUFFERING into // an aligned buffer and scattered into the blobs - no copy through the file cache when the drive is read anyway. LoadStats load_experts_gguf(const std::string& gguf, uint8_t* dst, const strata::kernels::cpu::ExpertLayout& lay, - int threads, bool unbuffered) { + int threads, bool unbuffered, const std::atomic* ready) { + // `ready`: layer l is written only once *ready > l + 1 (a PinnedArena registering its slices meanwhile; the next + // slice too, since its registration starts on the page that may hold this layer's tail) + auto wait_ready = [ready](int64_t l) { + if (ready != nullptr) + while (ready->load(std::memory_order_acquire) <= l + 1) std::this_thread::yield(); + }; LoadStats st; st.layers = (uint64_t) lay.n_layers; const auto t0 = std::chrono::steady_clock::now(); @@ -2947,6 +2953,7 @@ LoadStats load_experts_gguf(const std::string& gguf, uint8_t* dst, const strata: for (;;) { const int64_t l = next.fetch_add(1); if (l >= lay.n_layers || bad) break; + wait_ready(l); const auto& fm = lay.fmt[(size_t) l]; const uint64_t blob = lay.bytes[(size_t) l]; const uint64_t per[3] = {fm.up_off, fm.up_off, blob - fm.down_off}; @@ -3025,6 +3032,7 @@ LoadStats load_experts_gguf(const std::string& gguf, uint8_t* dst, const strata: for (;;) { const int64_t l = next.fetch_add(1); if (l >= lay.n_layers || bad) break; + wait_ready(l); const auto& fm = lay.fmt[(size_t) l]; const uint64_t blob = lay.bytes[(size_t) l]; const uint64_t per[3] = {fm.up_off, fm.up_off, blob - fm.down_off}; @@ -3195,8 +3203,20 @@ 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, - shared_arena_file, pack_hash); + // #285: on Windows the per-layer registration runs on a thread ahead of the readers, which wait for their + // layer's slice (the whole arena registered before the load cost ~2.5 s at 33 GiB of 4 KB pages, not hidden). + // Only where the whole arena would be registered: no cap (STRATA_ARENA_PIN_GIB, multi-GPU), no shared arena. + // Linux keeps the whole-arena pin (#253). STRATA_DEFERRED_REGISTER=0: the registration before the load. +#ifdef _WIN32 + const char* defer_env = std::getenv("STRATA_DEFERRED_REGISTER"); + const bool deferred = max_pinned_bytes == 0 && arena_pin_cap_gib() == -1 && shared_arena_file.empty() && + (defer_env == nullptr || defer_env[0] != '0'); +#else + const bool deferred = false; +#endif + PinnedArena* a = deferred ? new PinnedArena(want + (uint64_t) blob, bounds, PinnedArena::Deferred{}) + : 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; @@ -3221,13 +3241,25 @@ bool ArenaExpertSource::open(const std::string& pack_dir, int64_t n_layers, int6 const bool unbuffered = experts_unbuffered(files, want + (uint64_t) blob, why); const int readers = unbuffered ? std::max(threads, 16) : threads; // 16 keep a PCIe 5 drive's queue full LoadStats st; - if (from_gguf) { - st = load_experts_gguf(gguf_, a->data(), lay, readers, unbuffered); - } else { - if (unbuffered) st = load_experts_direct(path, a->data(), loff, lbytes, readers, /*chunk=*/8u << 20); - if (!unbuffered || (!st.ok && st.error.empty())) // unaligned ranges: the buffered reader - st = load_experts_ranges(path, a->data(), loff, lbytes, threads, /*chunk=*/8u << 20); + std::atomic ready{0}; + std::thread reg; + if (deferred) { + int dev = 0; + cudaGetDevice(&dev); + reg = std::thread([a, &ready, dev] { + cudaSetDevice(dev); + a->register_slices(ready); + }); } + const std::atomic* rp = deferred ? &ready : nullptr; + if (from_gguf) { + st = load_experts_gguf(gguf_, a->data(), lay, readers, unbuffered, rp); + } else { + if (unbuffered) st = load_experts_direct(path, a->data(), loff, lbytes, readers, /*chunk=*/8u << 20, rp); + if (!unbuffered || (!st.ok && st.error.empty())) // unaligned ranges: the buffered reader + st = load_experts_ranges(path, a->data(), loff, lbytes, threads, /*chunk=*/8u << 20, rp); + } + if (reg.joinable()) reg.join(); std::fprintf(stderr, "strata generate: expert arena read %s (%s)\n", unbuffered ? "unbuffered" : "through the file cache", why.c_str()); if (!st.ok) { @@ -3240,6 +3272,10 @@ bool ArenaExpertSource::open(const std::string& pack_dir, int64_t n_layers, int6 err = "ArenaExpertSource: the load read " + std::to_string(st.bytes) + " B of " + std::to_string(want); return false; } + if (std::getenv("STRATA_VERIFY_ARENA") != nullptr) { // tests: the loaded arena's checksum, any loader + std::fprintf(stderr, "strata generate: expert arena checksum %016llx (%.2f GiB)\n", + (unsigned long long) fnv1a64(a->data(), want), (double) want / (1ull << 30)); + } // the first start: write experts.bin for the mapped starts after this one - only when the drive has room for it // and 2 GiB more (a full drive fails other writes too); otherwise this start says so and runs pinned as before std::error_code space_ec; diff --git a/src/core/pinned.cu b/src/core/pinned.cu index fbc3b3c7..072a166c 100644 --- a/src/core/pinned.cu +++ b/src/core/pinned.cu @@ -5,6 +5,7 @@ #include #include +#include #include #include #include @@ -426,6 +427,46 @@ PinnedArena::PinnedArena(uint64_t bytes, const std::vector& bounds, } } +PinnedArena::PinnedArena(uint64_t bytes, const std::vector& bounds, Deferred) + : capacity(bytes), bounds_(bounds) { + if (bytes == 0 || bounds.size() < 2) return; + base = reserve(bytes, backing, note, std::string{}, 0, mapping_base, mapping_bytes); + if (base != nullptr && mapping_base == nullptr) { + mapping_base = base; + mapping_bytes = bytes; + } + slice_bytes = 1; // sliced: one registration per layer +} + +void PinnedArena::register_slices(std::atomic& ready) { + const int n = (int) bounds_.size() - 1; + int i = 0; + for (; base != nullptr && i < n; ++i) { + const uint64_t off = bounds_[(size_t) i], len = bounds_[(size_t) i + 1] - off; + if (cudaHostRegister((uint8_t*) base + off, (size_t) len, cudaHostRegisterPortable | cudaHostRegisterMapped) != + cudaSuccess) { + (void) cudaGetLastError(); + break; + } + slice_starts.push_back(off); + registered_bytes = off + len; + ++registered_slices; + ready.store(i + 1, std::memory_order_release); + } + note = "cudaHostRegister per layer, pipelined with the load: " + std::to_string(registered_slices) + " of " + + std::to_string(n) + " slices pinned; " + note; + if (i < n && base != nullptr) { // the rest stays resident through the working-set lock, as the sliced fallback does + const char* env = std::getenv("STRATA_ARENA_LOCK"); + if (env == nullptr || std::string(env) != "0") { + const strata::platform::LockResult lr = + strata::platform::lock_resident((uint8_t*) base + registered_bytes, capacity - registered_bytes); + locked_bytes = lr.locked_bytes; + note = lr.note + "; " + note; + } + } + ready.store(INT_MAX, std::memory_order_release); // every slice done (or given up on) +} + PinnedArena::~PinnedArena() { if (base) { if (locked_bytes) strata::platform::unlock_resident((uint8_t*) base + (slice_bytes ? registered_bytes : 0), locked_bytes); @@ -449,19 +490,20 @@ LoadStats load_experts(const std::string& path, uint8_t* dst, uint64_t blob_byte } LoadStats load_experts_direct(const std::string& path, uint8_t* dst, const std::vector& layer_off, - const std::vector& layer_bytes, int threads, uint64_t chunk) { + const std::vector& layer_bytes, int threads, uint64_t chunk, + const std::atomic* ready) { LoadStats st; st.ok = false; #ifdef _WIN32 constexpr uint64_t kAlign = 4096; if (((uintptr_t) dst % kAlign) != 0 || chunk == 0 || chunk % kAlign != 0) return st; - struct Piece { uint64_t off, n; }; + struct Piece { uint64_t off, n; int layer; }; std::vector pieces; uint64_t bytes = 0; for (size_t L = 0; L < layer_off.size(); ++L) { if (layer_off[L] % kAlign != 0 || layer_bytes[L] % kAlign != 0) return st; for (uint64_t p = 0; p < layer_bytes[L]; p += chunk) - pieces.push_back({layer_off[L] + p, std::min(chunk, layer_bytes[L] - p)}); + pieces.push_back({layer_off[L] + p, std::min(chunk, layer_bytes[L] - p), (int) L}); bytes += layer_bytes[L]; } if (threads < 1) threads = 1; @@ -485,6 +527,8 @@ LoadStats load_experts_direct(const std::string& path, uint8_t* dst, const std:: for (;;) { const size_t i = next.fetch_add(1); if (i >= pieces.size()) break; + if (ready != nullptr) // the slice must be registered before its pages are touched + while (ready->load(std::memory_order_acquire) <= pieces[i].layer + 1) std::this_thread::yield(); OVERLAPPED ov{}; ov.Offset = (DWORD) pieces[i].off; ov.OffsetHigh = (DWORD) (pieces[i].off >> 32); @@ -515,7 +559,7 @@ LoadStats load_experts_direct(const std::string& path, uint8_t* dst, const std:: st.bytes = bytes; st.seconds = std::chrono::duration(std::chrono::steady_clock::now() - t0).count(); #else - (void) path; (void) dst; (void) layer_off; (void) layer_bytes; (void) threads; (void) chunk; + (void) path; (void) dst; (void) layer_off; (void) layer_bytes; (void) threads; (void) chunk; (void) ready; #endif return st; } @@ -590,7 +634,8 @@ bool experts_unbuffered(const std::vector& files, uint64_t arena_by } LoadStats load_experts_ranges(const std::string& path, uint8_t* dst, const std::vector& layer_off, - const std::vector& layer_bytes, int threads, uint64_t chunk) { + const std::vector& layer_bytes, int threads, uint64_t chunk, + const std::atomic* ready) { LoadStats st; const uint64_t layers = (uint64_t) layer_off.size(); st.layers = layers; @@ -631,6 +676,8 @@ LoadStats load_experts_ranges(const std::string& path, uint8_t* dst, const std:: for (;;) { const uint64_t L = next_layer.fetch_add(1); if (L >= layers) break; + if (ready != nullptr) // the slice must be registered before its pages are touched + while (ready->load(std::memory_order_acquire) <= (int) L + 1) std::this_thread::yield(); const uint64_t off = layer_off[(size_t) L]; uint64_t remaining = layer_bytes[(size_t) L]; uint64_t pos = 0;