All under __APPLE__ / STRATA_GPU_METAL, so the Linux and Windows code is unchanged: - direct_file.cpp: no O_DIRECT on macOS; F_NOCACHE after open keeps the reads out of the buffer cache - memory.cpp: F_RDADVISE is the read-ahead hint where posix_fadvise(WILLNEED) is used - expert_source.cpp: available memory from host_statistics64 (free + inactive + purgeable); the posix_fadvise of a released expert layer is skipped (the madvise before it already released the mapping) - generate.cpp: <sys/sysmacros.h> is not on macOS (major/minor come from <sys/types.h>); the CUDA toolkit mismatch check is CUDA's - vmm.cpp: the cuMem* virtual memory stays CUDA's (Metal takes the HIP branch: elastic K/V off) - prefill.cpp: std::max<size_t> where size_t and uint64_t meet (the same type on Linux, distinct on macOS)
4995 lines
245 KiB
C++
4995 lines
245 KiB
C++
// src/core/expert_source.cpp - the adapter. See the header for the three clauses of the contract.
|
|
#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"
|
|
#include "strata/artifact/gguf_reader.hpp"
|
|
|
|
#include "strata/core/pinned.hpp"
|
|
#include "strata/platform/memory.hpp"
|
|
#include "strata/kernels/elementwise.hpp"
|
|
#include "strata/kernels/quantize_act.hpp"
|
|
#include "strata/kernels/s2_expert_grouped.hpp"
|
|
#include "strata/kernels/cpu/kq_avx1.hpp"
|
|
#include "strata/kernels/cpu/kq_avx2.hpp"
|
|
|
|
#include <cuda_runtime.h>
|
|
|
|
#include <algorithm>
|
|
#include <atomic>
|
|
#include <cerrno>
|
|
#include <chrono>
|
|
#include <cstdio>
|
|
#include <cstdlib>
|
|
#include <cstring>
|
|
#include <deque>
|
|
#include <fstream>
|
|
#include <filesystem>
|
|
#include <sstream>
|
|
#include <limits>
|
|
#include <map>
|
|
#include <memory>
|
|
#include <mutex>
|
|
#include <thread>
|
|
#include <utility>
|
|
#include <vector>
|
|
|
|
#if defined(_WIN32)
|
|
#define WIN32_LEAN_AND_MEAN
|
|
#ifndef NOMINMAX
|
|
#define NOMINMAX // std::numeric_limits<T>::max() below
|
|
#endif
|
|
#include <windows.h>
|
|
#else
|
|
#include <fcntl.h>
|
|
#if defined(__APPLE__)
|
|
#include <mach/mach.h> // host_statistics64: the available memory
|
|
#endif
|
|
#include <sys/mman.h>
|
|
#include <sys/stat.h>
|
|
#include <unistd.h>
|
|
#endif
|
|
#if defined(__linux__)
|
|
#include <cerrno>
|
|
#include <linux/aio_abi.h> // the kernel's own asynchronous reads (io_submit): no library, allowed by Docker's seccomp
|
|
#include <sys/syscall.h>
|
|
#endif
|
|
|
|
// a 64-bit seek (as in pinned.cu): the 32-bit `fseek` wraps past 4 GiB, and the spelling differs per platform
|
|
#ifndef STRATA_FSEEK64
|
|
#ifdef _WIN32
|
|
#define STRATA_FSEEK64(f, o) _fseeki64((f), (long long) (o), SEEK_SET)
|
|
#else
|
|
#define STRATA_FSEEK64(f, o) fseeko((f), (off_t) (o), SEEK_SET)
|
|
#endif
|
|
#endif
|
|
|
|
namespace strata::core {
|
|
|
|
namespace detail {
|
|
|
|
bool cgroup_available_bytes(uint64_t limit, const CgroupMemoryStat& stat, uint64_t& bytes) {
|
|
bytes = 0;
|
|
if (!stat.valid) return false;
|
|
|
|
// memory.stat's inactive_file can race memory.current, so bound it to charged usage first.
|
|
uint64_t reclaimable = std::min(stat.inactive_file, stat.current);
|
|
reclaimable = stat.file_dirty >= reclaimable ? 0 : reclaimable - stat.file_dirty;
|
|
reclaimable = stat.file_writeback >= reclaimable ? 0 : reclaimable - stat.file_writeback;
|
|
|
|
// Reclaiming clean file pages reduces usage; saturating subtraction also handles a transient over-limit read.
|
|
const uint64_t usage_after_reclaim = stat.current - reclaimable;
|
|
bytes = usage_after_reclaim < limit ? limit - usage_after_reclaim : 0;
|
|
return true;
|
|
}
|
|
|
|
uint64_t clamp_resident_budget(uint64_t requested, uint64_t physical, uint64_t commit, uint64_t headroom) {
|
|
const uint64_t available = std::min(physical, commit);
|
|
const uint64_t room = available > headroom ? available - headroom : 0;
|
|
if (requested <= room) return requested;
|
|
const uint64_t margin = 256ull << 20;
|
|
return room > margin ? room - margin : 0;
|
|
}
|
|
|
|
bool pin_depends_on_reclaim(uint64_t free_now, uint64_t bytes, uint64_t reserve) {
|
|
return bytes > 0 && free_now < bytes + reserve;
|
|
}
|
|
|
|
bool pin_step_fits(uint64_t available, uint64_t step, uint64_t reserve) {
|
|
return available >= step + reserve;
|
|
}
|
|
|
|
uint64_t meminfo_bytes(const std::string& meminfo_text, const std::string& key) {
|
|
std::istringstream in(meminfo_text);
|
|
std::string line;
|
|
const std::string want = key + ":";
|
|
while (std::getline(in, line)) {
|
|
std::istringstream fields(line);
|
|
std::string k, unit;
|
|
uint64_t value = 0;
|
|
if (fields >> k >> value && k == want) {
|
|
fields >> unit;
|
|
return unit == "kB" ? value * 1024 : value;
|
|
}
|
|
}
|
|
return 0;
|
|
}
|
|
|
|
uint64_t numa_pin_free(uint64_t global_free, const std::vector<uint64_t>& node_free) {
|
|
if (node_free.size() < 2) return global_free;
|
|
const uint64_t smallest = *std::min_element(node_free.begin(), node_free.end());
|
|
return std::min<uint64_t>(global_free, smallest * (uint64_t) node_free.size());
|
|
}
|
|
|
|
std::string page_cache_hint(const std::string& meminfo_text) {
|
|
const uint64_t cache = meminfo_bytes(meminfo_text, "Cached") + meminfo_bytes(meminfo_text, "Buffers");
|
|
if (cache < (1ull << 30)) return "";
|
|
char msg[420];
|
|
std::snprintf(msg, sizeof msg,
|
|
"; %.1f GiB of the RAM is file cache (earlier runs' model files, which Linux gives back on demand - "
|
|
"'free' showing little is normal). If the start still fails, free it with: "
|
|
"sync; echo 1 | sudo tee /proc/sys/vm/drop_caches (or start strata serve with "
|
|
"STRATA_DROP_CACHE_ON_EXIT=1 so it releases its model files when it stops)",
|
|
(double) cache / 1073741824.0);
|
|
return msg;
|
|
}
|
|
|
|
bool make_cache_complement_plan(
|
|
int64_t n_layers, int64_t n_expert, const std::vector<uint64_t>& layer_blob_bytes,
|
|
const std::vector<std::pair<int32_t, int32_t>>& primary_gpu_pairs,
|
|
const std::vector<std::pair<int32_t, int32_t>>& additional_gpu_pairs,
|
|
std::vector<uint64_t>& offsets, uint64_t& bytes, std::string& err) {
|
|
offsets.clear();
|
|
bytes = 0;
|
|
err.clear();
|
|
if (n_layers <= 0 || n_expert <= 0 || layer_blob_bytes.size() != (size_t) n_layers) {
|
|
err = "FileExpertSource: invalid geometry for the cache complement plan";
|
|
return false;
|
|
}
|
|
if ((uint64_t) n_layers > (uint64_t) std::numeric_limits<size_t>::max() / (uint64_t) n_expert) {
|
|
err = "FileExpertSource: cache complement index table is too large";
|
|
return false;
|
|
}
|
|
const size_t count = (size_t) n_layers * (size_t) n_expert;
|
|
std::vector<uint8_t> omitted(count, 0);
|
|
auto mark_pairs = [&](const std::vector<std::pair<int32_t, int32_t>>& pairs, uint8_t bit,
|
|
const char* label) -> bool {
|
|
for (const auto& pair : pairs) {
|
|
if (pair.first < 0 || pair.second < 0 || pair.first >= n_layers || pair.second >= n_expert) {
|
|
err = std::string("FileExpertSource: ") + label + " pair is outside the expert geometry";
|
|
return false;
|
|
}
|
|
const size_t index = (size_t) pair.first * (size_t) n_expert + (size_t) pair.second;
|
|
if ((omitted[index] & bit) != 0) {
|
|
err = std::string("FileExpertSource: duplicate ") + label + " pair in the cache complement plan";
|
|
return false;
|
|
}
|
|
if (bit == 2 && (omitted[index] & 1) != 0) {
|
|
err = "FileExpertSource: the primary and additional GPU expert tiers overlap";
|
|
return false;
|
|
}
|
|
omitted[index] |= bit;
|
|
}
|
|
return true;
|
|
};
|
|
if (!mark_pairs(primary_gpu_pairs, 1, "primary GPU") ||
|
|
!mark_pairs(additional_gpu_pairs, 2, "additional GPU")) return false;
|
|
for (uint64_t blob_bytes : layer_blob_bytes) {
|
|
if (blob_bytes == 0) {
|
|
err = "FileExpertSource: cache complement layer has zero-sized expert blobs";
|
|
return false;
|
|
}
|
|
}
|
|
|
|
offsets.assign(count, kNoCacheComplement);
|
|
for (int64_t layer = 0; layer < n_layers; ++layer) {
|
|
const uint64_t blob_bytes = layer_blob_bytes[(size_t) layer];
|
|
for (int64_t expert = 0; expert < n_expert; ++expert) {
|
|
const size_t index = (size_t) layer * (size_t) n_expert + (size_t) expert;
|
|
if (omitted[index] != 0) continue;
|
|
if (bytes > std::numeric_limits<uint64_t>::max() - blob_bytes) {
|
|
offsets.clear();
|
|
bytes = 0;
|
|
err = "FileExpertSource: cache complement size overflows";
|
|
return false;
|
|
}
|
|
offsets[index] = bytes;
|
|
bytes += blob_bytes;
|
|
}
|
|
}
|
|
if (bytes > (uint64_t) std::numeric_limits<size_t>::max()) {
|
|
offsets.clear();
|
|
bytes = 0;
|
|
err = "FileExpertSource: cache complement exceeds the host address space";
|
|
return false;
|
|
}
|
|
return true;
|
|
}
|
|
|
|
const uint8_t* cache_complement_blob_or_fallback(
|
|
size_t index, const std::vector<uint64_t>& offsets, const uint8_t* complement_host,
|
|
const uint8_t* mapped_fallback) {
|
|
if (complement_host != nullptr && index < offsets.size() && offsets[index] != kNoCacheComplement)
|
|
return complement_host + (size_t) offsets[index];
|
|
return mapped_fallback;
|
|
}
|
|
|
|
int64_t choose_resident_keep_from(const std::vector<uint64_t>& slot_bytes, uint64_t base_bytes, uint64_t budget,
|
|
int64_t lend_from) {
|
|
if (base_bytes > budget) return -1;
|
|
const int64_t slots = (int64_t) slot_bytes.size();
|
|
if (lend_from < 0 || lend_from > slots) lend_from = slots; // no lend region: only the experts no slot holds
|
|
int64_t keep = slots;
|
|
uint64_t bytes = base_bytes;
|
|
while (keep > lend_from) {
|
|
const uint64_t b = slot_bytes[(size_t) keep - 1];
|
|
if (b > budget - bytes) break;
|
|
bytes += b;
|
|
--keep;
|
|
}
|
|
return keep;
|
|
}
|
|
|
|
int64_t append_stage_lend_regions(int64_t n_layers, int64_t n_expert, const std::vector<uint64_t>& layer_blob_bytes,
|
|
std::vector<uint64_t>& offsets, uint64_t& bytes, uint64_t cap_bytes,
|
|
const std::vector<std::vector<std::pair<int32_t, int32_t>>>& 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<std::pair<int32_t, int32_t>> 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<uint64_t>& offsets, size_t in, size_t out) {
|
|
if (in == out || in >= offsets.size() || out >= offsets.size() || offsets[in] == kNoCacheComplement ||
|
|
offsets[out] != kNoCacheComplement) return false;
|
|
offsets[out] = offsets[in];
|
|
offsets[in] = kNoCacheComplement;
|
|
return true;
|
|
}
|
|
|
|
} // namespace detail
|
|
|
|
namespace {
|
|
|
|
#if defined(__linux__)
|
|
bool read_cgroup_memory_stat(const std::filesystem::path& path, uint64_t current,
|
|
detail::CgroupMemoryStat& stat) {
|
|
std::ifstream input(path / "memory.stat");
|
|
if (!input) return false;
|
|
|
|
bool inactive_file = false, file_dirty = false, file_writeback = false;
|
|
std::string line;
|
|
while (std::getline(input, line)) {
|
|
std::istringstream fields(line);
|
|
std::string key;
|
|
uint64_t value = 0;
|
|
if (!(fields >> key >> value)) return false;
|
|
fields >> std::ws;
|
|
if (!fields.eof()) return false;
|
|
|
|
if (key == "inactive_file") {
|
|
if (inactive_file) return false;
|
|
inactive_file = true;
|
|
stat.inactive_file = value;
|
|
} else if (key == "file_dirty") {
|
|
if (file_dirty) return false;
|
|
file_dirty = true;
|
|
stat.file_dirty = value;
|
|
} else if (key == "file_writeback") {
|
|
if (file_writeback) return false;
|
|
file_writeback = true;
|
|
stat.file_writeback = value;
|
|
}
|
|
}
|
|
if (!input.eof() || !inactive_file || !file_dirty || !file_writeback) return false;
|
|
stat.current = current;
|
|
stat.valid = true;
|
|
return true;
|
|
}
|
|
#endif
|
|
|
|
} // namespace
|
|
|
|
namespace detail {
|
|
|
|
bool host_available_memory(HostMemory& m, const std::string& meminfo, const std::string& self_cgroup,
|
|
const std::string& cgroup_root) {
|
|
m = HostMemory{};
|
|
#if defined(_WIN32)
|
|
(void) meminfo; (void) self_cgroup; (void) cgroup_root;
|
|
MEMORYSTATUSEX status{};
|
|
status.dwLength = sizeof(status);
|
|
if (!GlobalMemoryStatusEx(&status)) return false;
|
|
m.available = (uint64_t) status.ullAvailPhys;
|
|
m.commit = (uint64_t) status.ullAvailPageFile;
|
|
return m.available > 0;
|
|
#elif defined(__linux__)
|
|
// MemAvailable includes reclaimable page cache, unlike _SC_AVPHYS_PAGES.
|
|
std::ifstream info(meminfo);
|
|
std::string line;
|
|
uint64_t bytes = 0;
|
|
while (std::getline(info, line)) {
|
|
std::istringstream fields(line);
|
|
std::string key, unit;
|
|
uint64_t value = 0;
|
|
if (fields >> key >> value >> unit && key == "MemAvailable:" && unit == "kB" &&
|
|
value <= std::numeric_limits<uint64_t>::max() / 1024) bytes = value * 1024;
|
|
}
|
|
if (bytes == 0) return false;
|
|
// Account for the tightest cgroup ancestor limit when its normal mount is visible.
|
|
// This is a point-in-time guard, not a reservation against concurrent allocations.
|
|
std::ifstream groups(self_cgroup);
|
|
if (!groups) return false;
|
|
const std::filesystem::path root(cgroup_root);
|
|
bool v2 = false;
|
|
std::string v1_path; // the memory controller's group (cgroup v1), when there is no v2 line
|
|
while (std::getline(groups, line)) {
|
|
if (line.rfind("0::/", 0) != 0) {
|
|
// v1: "N:controller[,controller]:/path"
|
|
const size_t c1 = line.find(':'), c2 = c1 == std::string::npos ? c1 : line.find(':', c1 + 1);
|
|
if (c2 == std::string::npos) continue;
|
|
std::istringstream ctl(line.substr(c1 + 1, c2 - c1 - 1));
|
|
for (std::string c; std::getline(ctl, c, ',');)
|
|
if (c == "memory") v1_path = line.substr(c2 + 1);
|
|
continue;
|
|
}
|
|
auto path = (root / line.substr(4)).lexically_normal();
|
|
if (path.string().rfind(root.string(), 0) != 0 || !std::filesystem::is_directory(path)) return false;
|
|
v2 = true;
|
|
while (path.string().rfind(root.string(), 0) == 0) {
|
|
std::ifstream limit_file(path / "memory.max"), current_file(path / "memory.current");
|
|
std::string limit;
|
|
uint64_t current = 0;
|
|
const bool readable = bool(limit_file >> limit) && bool(current_file >> current);
|
|
// The host's root cgroup has no memory.max; ordinary child groups must expose their limits.
|
|
if (!readable && !(path == root && !std::filesystem::exists(path / "memory.max") &&
|
|
std::filesystem::exists(path / "cgroup.controllers"))) return false;
|
|
if (readable && limit != "max") {
|
|
try {
|
|
size_t consumed = 0;
|
|
const uint64_t cap = std::stoull(limit, &consumed);
|
|
if (consumed != limit.size()) return false;
|
|
CgroupMemoryStat stat;
|
|
if (!read_cgroup_memory_stat(path, current, stat)) return false;
|
|
uint64_t cgroup_available = 0;
|
|
if (!cgroup_available_bytes(cap, stat, cgroup_available)) return false;
|
|
bytes = std::min(bytes, cgroup_available);
|
|
m.cgroup_limit = std::min(m.cgroup_limit, cap);
|
|
} catch (...) { return false; }
|
|
}
|
|
if (path == root) break;
|
|
path = path.parent_path();
|
|
}
|
|
}
|
|
if (!v2 && !v1_path.empty()) {
|
|
// #633: cgroup v1 (older Docker hosts, RHEL 7/8): the memory controller's group and its ancestors. An
|
|
// unlimited group says a number near 2^63 (rounded to its page size); a group whose files are not
|
|
// visible (no mount in this namespace) is skipped - MemAvailable alone, as with no cgroup at all.
|
|
const std::filesystem::path mroot = root / "memory";
|
|
auto path = (mroot / v1_path.substr(v1_path.rfind('/', 0) == 0 ? 1 : 0)).lexically_normal();
|
|
while (path.string().rfind(mroot.string(), 0) == 0) {
|
|
std::ifstream limit_file(path / "memory.limit_in_bytes"), usage_file(path / "memory.usage_in_bytes");
|
|
uint64_t cap = 0, usage = 0;
|
|
if (limit_file >> cap && usage_file >> usage && cap < (1ull << 62)) {
|
|
bytes = std::min(bytes, usage < cap ? cap - usage : 0);
|
|
m.cgroup_limit = std::min(m.cgroup_limit, cap);
|
|
}
|
|
if (path == mroot) break;
|
|
path = path.parent_path();
|
|
}
|
|
}
|
|
m.available = bytes;
|
|
return true;
|
|
#elif defined(__APPLE__)
|
|
// macOS: free + inactive + purgeable pages (what the OS can hand out without swapping), as vm_stat reports them
|
|
(void) meminfo; (void) self_cgroup; (void) cgroup_root;
|
|
vm_statistics64_data_t vs{};
|
|
mach_msg_type_number_t count = HOST_VM_INFO64_COUNT;
|
|
vm_size_t page_bytes = 0;
|
|
if (host_page_size(mach_host_self(), &page_bytes) != KERN_SUCCESS ||
|
|
host_statistics64(mach_host_self(), HOST_VM_INFO64, (host_info64_t) &vs, &count) != KERN_SUCCESS) return false;
|
|
m.available = ((uint64_t) vs.free_count + vs.inactive_count + vs.purgeable_count) * (uint64_t) page_bytes;
|
|
return m.available > 0;
|
|
#else
|
|
(void) meminfo; (void) self_cgroup; (void) cgroup_root;
|
|
const long pages = sysconf(_SC_AVPHYS_PAGES);
|
|
const long page_bytes = sysconf(_SC_PAGESIZE);
|
|
if (pages <= 0 || page_bytes <= 0 ||
|
|
(uint64_t) pages > std::numeric_limits<uint64_t>::max() / (uint64_t) page_bytes) return false;
|
|
m.available = (uint64_t) pages * (uint64_t) page_bytes;
|
|
return m.available > 0;
|
|
#endif
|
|
}
|
|
|
|
} // namespace detail
|
|
|
|
namespace {
|
|
|
|
bool available_memory_bytes(uint64_t& bytes, uint64_t* commit = nullptr) {
|
|
detail::HostMemory m;
|
|
if (!detail::host_available_memory(m)) return false;
|
|
bytes = m.available;
|
|
if (commit != nullptr) *commit = m.commit;
|
|
return bytes > 0;
|
|
}
|
|
|
|
/// #1250: the pages that are really free (MemFree), not the reclaimable cache MemAvailable counts; false when unknown.
|
|
bool free_memory_bytes(uint64_t& bytes) {
|
|
#if defined(__linux__)
|
|
std::ifstream info("/proc/meminfo");
|
|
if (!info) return false;
|
|
std::stringstream text;
|
|
text << info.rdbuf();
|
|
bytes = detail::meminfo_bytes(text.str(), "MemFree");
|
|
if (bytes == 0) return false;
|
|
// 0.1.42: a multi-socket host's nodes each have their own free pages; judge by the emptiest one too
|
|
std::vector<uint64_t> nodes;
|
|
for (int n = 0; n < 64; ++n) {
|
|
std::ifstream node("/sys/devices/system/node/node" + std::to_string(n) + "/meminfo");
|
|
if (!node) break;
|
|
std::string line;
|
|
while (std::getline(node, line)) {
|
|
std::istringstream f(line);
|
|
std::string a, id, key;
|
|
uint64_t kb = 0;
|
|
if (f >> a >> id >> key >> kb && key == "MemFree:") { nodes.push_back(kb * 1024); break; }
|
|
}
|
|
}
|
|
bytes = detail::numa_pin_free(bytes, nodes);
|
|
return bytes > 0;
|
|
#else
|
|
bytes = 0;
|
|
return false;
|
|
#endif
|
|
}
|
|
|
|
void log_complement_memory(const char* stage, uint64_t requested) {
|
|
#if defined(_WIN32)
|
|
MEMORYSTATUSEX status{};
|
|
status.dwLength = sizeof(status);
|
|
if (!GlobalMemoryStatusEx(&status)) {
|
|
std::fprintf(stderr, "FileExpertSource: %s: GlobalMemoryStatusEx failed (error %lu)\n", stage, GetLastError());
|
|
return;
|
|
}
|
|
std::fprintf(stderr, "FileExpertSource: %s: requested %.2f GiB, available RAM %.2f GiB, available commit %.2f GiB "
|
|
"(limit %.2f GiB), available virtual address space %.2f GiB\n",
|
|
stage, (double) requested / 1073741824.0, (double) status.ullAvailPhys / 1073741824.0,
|
|
(double) status.ullAvailPageFile / 1073741824.0, (double) status.ullTotalPageFile / 1073741824.0,
|
|
(double) status.ullAvailVirtual / 1073741824.0);
|
|
#else
|
|
(void) stage;
|
|
(void) requested;
|
|
#endif
|
|
}
|
|
|
|
/// #286: an unbuffered file handle - a HANDLE on Windows, an O_DIRECT descriptor (as a pointer-sized integer) on Linux.
|
|
void close_direct(void* h) {
|
|
#if defined(_WIN32)
|
|
CloseHandle((HANDLE) h);
|
|
#else
|
|
::close((int) (intptr_t) h);
|
|
#endif
|
|
}
|
|
|
|
/// #286/#577: whether the file tier reads its `read_bytes` unbuffered, beside `arena_bytes` of RAM copy still to be
|
|
/// taken. Windows times probe reads too (experts_unbuffered); on Linux the same rule as its `cache_counts = false`
|
|
/// arm decides: whether the file cache could keep those bytes at all, from MemAvailable and the tightest cgroup
|
|
/// limit (host_available_memory). STRATA_UNBUFFERED_LOAD=1 / 0 forces it either way, as on Windows.
|
|
bool file_tier_unbuffered(const std::vector<std::string>& paths, uint64_t arena_bytes, uint64_t read_bytes,
|
|
std::string& why) {
|
|
#if defined(_WIN32)
|
|
return experts_unbuffered(paths, arena_bytes, why, /*cache_counts=*/false, read_bytes);
|
|
#elif defined(__linux__)
|
|
(void) paths;
|
|
if (const char* env = std::getenv("STRATA_UNBUFFERED_LOAD"); env != nullptr && env[0] != '\0') {
|
|
why = std::string("STRATA_UNBUFFERED_LOAD=") + env;
|
|
return env[0] != '0';
|
|
}
|
|
uint64_t avail = 0;
|
|
if (!available_memory_bytes(avail)) {
|
|
why = "the available RAM is unknown";
|
|
return false;
|
|
}
|
|
// #1194: the experts read from the files are a skewed set: a cache holding a twentieth of them (at least 1.5 GiB)
|
|
// serves most of the repeats, and beat the unbuffered reads at every room measured (it reads 2 to 7 times less from
|
|
// the drive). `avail` already has what this process and the cgroup hold taken off, so 1 GiB is left for the rest.
|
|
const bool keepable = strata::platform::file_cache_keeps(avail, arena_bytes, read_bytes, 1ull << 30, 0.05,
|
|
3ull << 29);
|
|
char msg[256];
|
|
std::snprintf(msg, sizeof msg, "%.1f GiB available, %.1f GiB of it still to be taken by the RAM copy, %.1f GiB "
|
|
"of experts read from the files: the file cache %s keep the ones that come back",
|
|
(double) avail / (1ull << 30), (double) arena_bytes / (1ull << 30), (double) read_bytes / (1ull << 30),
|
|
keepable ? "can" : "cannot");
|
|
why = msg;
|
|
return !keepable;
|
|
#else
|
|
(void) paths; (void) arena_bytes; (void) read_bytes;
|
|
why = "through the file cache (no unbuffered reads on this platform)";
|
|
return false;
|
|
#endif
|
|
}
|
|
|
|
} // namespace
|
|
|
|
// ================================ THE FILE-BACKED SOURCE ================================
|
|
|
|
FileExpertSource::~FileExpertSource() { close(); }
|
|
|
|
#if defined(__linux__)
|
|
namespace {
|
|
/// Bytes of [p, p + n) whose pages are in the page cache (mincore, page-granular); 0 when the call fails.
|
|
uint64_t resident_in(const uint8_t* p, uint64_t n) {
|
|
if (n == 0) return 0;
|
|
static thread_local std::vector<unsigned char> vec;
|
|
const uintptr_t a = (uintptr_t) p & ~(uintptr_t) 4095, e = ((uintptr_t) p + (uintptr_t) n + 4095) & ~(uintptr_t) 4095;
|
|
vec.resize((size_t) ((e - a) / 4096));
|
|
if (mincore((void*) a, (size_t) (e - a), vec.data()) != 0) return 0;
|
|
uint64_t pages = 0;
|
|
for (unsigned char c : vec) pages += c & 1;
|
|
return std::min<uint64_t>(n, pages * 4096);
|
|
}
|
|
/// A cheap residency probe: the first, last and two inner pages; the bytes of the range when all four are cached, else 0.
|
|
uint64_t resident_sampled(const uint8_t* p, uint64_t n) {
|
|
if (n == 0) return 0;
|
|
const uintptr_t a = (uintptr_t) p & ~(uintptr_t) 4095, e = ((uintptr_t) p + (uintptr_t) n - 1) & ~(uintptr_t) 4095;
|
|
const uintptr_t pages = (e - a) / 4096;
|
|
const uintptr_t at[4] = {a, a + (pages / 3) * 4096, a + (pages * 2 / 3) * 4096, e};
|
|
for (uintptr_t x : at) {
|
|
unsigned char v = 0;
|
|
if (mincore((void*) x, 4096, &v) != 0 || (v & 1) == 0) return 0;
|
|
}
|
|
return n;
|
|
}
|
|
bool resident_sampled_n(const uint8_t* p, uint64_t n) { return resident_sampled(p, n) >= n; }
|
|
/// The whole range with pread (a short read continues); false on an error or an end of file.
|
|
bool pread_full(int fd, uint8_t* dst, uint64_t n, uint64_t off) {
|
|
uint64_t done = 0;
|
|
while (done < n) {
|
|
const ssize_t r = ::pread(fd, dst + done, (size_t) (n - done), (off_t) (off + done));
|
|
if (r < 0) { if (errno == EINTR) continue; return false; }
|
|
if (r == 0) return false;
|
|
done += (uint64_t) r;
|
|
}
|
|
return true;
|
|
}
|
|
} // namespace
|
|
#endif
|
|
|
|
int FileExpertSource::spans(int64_t layer, int64_t expert, Span* out) const {
|
|
if (layer < 0 || expert < 0 || layer >= n_layers_ || expert >= n_expert_) return 0;
|
|
if (!role_ptr_.empty()) {
|
|
if (unmapped_) return 0; // the GGUF views are closed (drop_mapping)
|
|
uint64_t at = 0;
|
|
for (int r = 0; r < 3; ++r) {
|
|
const size_t i = (size_t) (3 * layer + r);
|
|
const uint64_t per = role_bytes_[i];
|
|
const uint8_t* p = role_ptr_[i] + (size_t) ((uint64_t) expert * per);
|
|
const size_t f = (size_t) role_file_[i];
|
|
out[r] = {p, per, f < io_fds_.size() ? io_fds_[f] : -1, (uint64_t) (p - maps_[f].base), at};
|
|
at += per;
|
|
}
|
|
return 3;
|
|
}
|
|
const uint8_t* b = mapped_blob(layer, expert);
|
|
if (b == nullptr) return 0;
|
|
out[0] = {b, layer_blob_bytes_[(size_t) layer], io_fds_.empty() ? -1 : io_fds_[0], (uint64_t) (b - base_), 0};
|
|
return 1;
|
|
}
|
|
|
|
uint64_t FileExpertSource::cached_bytes(int64_t layer, int64_t expert, uint64_t& total, bool exact) const {
|
|
total = 0;
|
|
#if defined(__linux__)
|
|
Span sp[3];
|
|
const int ns = spans(layer, expert, sp);
|
|
uint64_t res = 0;
|
|
for (int i = 0; i < ns; ++i) {
|
|
total += sp[i].n;
|
|
res += exact ? resident_in(sp[i].p, sp[i].n) : resident_sampled(sp[i].p, sp[i].n);
|
|
}
|
|
return res;
|
|
#else
|
|
(void) layer; (void) expert;
|
|
return 0;
|
|
#endif
|
|
}
|
|
|
|
FileExpertSource::IoCounters FileExpertSource::io_counters() const {
|
|
IoCounters c;
|
|
c.cached_bytes = io_cached_.load(std::memory_order_relaxed);
|
|
c.uncached_bytes = io_uncached_.load(std::memory_order_relaxed);
|
|
c.pread_bytes = io_pread_bytes_.load(std::memory_order_relaxed);
|
|
c.pread_us = io_pread_us_.load(std::memory_order_relaxed);
|
|
c.pread_n = io_pread_n_.load(std::memory_order_relaxed);
|
|
c.pf_jobs = io_pf_jobs_.load(std::memory_order_relaxed);
|
|
c.pf_demand = io_pf_demand_.load(std::memory_order_relaxed);
|
|
c.pf_read_blobs = io_pf_blobs_.load(std::memory_order_relaxed);
|
|
c.pf_resident_skips = io_pf_skips_.load(std::memory_order_relaxed);
|
|
c.pf_dropped = io_pf_dropped_.load(std::memory_order_relaxed);
|
|
c.pf_used = io_pf_used_.load(std::memory_order_relaxed);
|
|
c.pf_unused = io_pf_unused_.load(std::memory_order_relaxed);
|
|
c.crit_us = io_crit_us_.load(std::memory_order_relaxed);
|
|
c.crit_n = io_crit_n_.load(std::memory_order_relaxed);
|
|
return c;
|
|
}
|
|
|
|
void FileExpertSource::set_io_prefetch(bool on, int threads) {
|
|
io_stop();
|
|
#if defined(__linux__)
|
|
if (!on) return;
|
|
if (base_ == nullptr || paths_.empty() || !direct_.empty()) return; // unbuffered readers batch their own reads
|
|
std::vector<int> fds;
|
|
for (const std::string& path : paths_) {
|
|
const int fd = ::open(path.c_str(), O_RDONLY | O_CLOEXEC);
|
|
if (fd < 0) {
|
|
for (int f : fds) ::close(f);
|
|
return;
|
|
}
|
|
(void) posix_fadvise(fd, 0, 0, POSIX_FADV_RANDOM); // read exactly the range asked for, no read-ahead beyond it
|
|
fds.push_back(fd);
|
|
}
|
|
io_fds_ = std::move(fds);
|
|
{
|
|
std::lock_guard<std::mutex> lk(stage_mu_);
|
|
for (uint64_t b : layer_blob_bytes_) stage_blob_ = std::max(stage_blob_, b);
|
|
}
|
|
if (!warm_stamp_) warm_stamp_.reset(new std::atomic<uint32_t>[(size_t) (n_layers_ * n_expert_)]());
|
|
io_threads_ = threads > 0 ? threads : 8;
|
|
if (const char* v = std::getenv("STRATA_IO_PF_AHEAD")) io_ahead_ = std::atoi(v) != 0;
|
|
{ // experts.bin: fill the page cache from the workers and let the kernels read the mapping (STRATA_IO_PF_STAGE=1: stage)
|
|
const char* v = std::getenv("STRATA_IO_PF_STAGE");
|
|
io_fill_ = role_ptr_.empty() && !(v != nullptr && std::atoi(v) != 0);
|
|
}
|
|
io_pf_ = true;
|
|
io_stats_ = true;
|
|
io_quit_ = false;
|
|
for (int i = 0; i < io_threads_; ++i) io_workers_.emplace_back([this] { io_worker(); });
|
|
#else
|
|
(void) on; (void) threads;
|
|
#endif
|
|
}
|
|
|
|
void FileExpertSource::io_stop() {
|
|
{
|
|
std::lock_guard<std::mutex> lk(io_mu_);
|
|
io_quit_ = true;
|
|
io_q_.clear();
|
|
}
|
|
io_cv_.notify_all();
|
|
for (std::thread& t : io_workers_)
|
|
if (t.joinable()) t.join();
|
|
io_workers_.clear();
|
|
#if defined(__linux__)
|
|
for (int f : io_fds_) ::close(f);
|
|
#endif
|
|
io_fds_.clear();
|
|
io_pf_ = false;
|
|
io_quit_ = false;
|
|
}
|
|
|
|
void FileExpertSource::io_enqueue(int64_t layer, int64_t expert) {
|
|
{
|
|
std::lock_guard<std::mutex> lk(io_mu_);
|
|
if (io_q_.size() >= 512) { // the predictions run ahead of the reads: the oldest are the stalest
|
|
io_q_.pop_front();
|
|
io_pf_dropped_.fetch_add(1, std::memory_order_relaxed);
|
|
}
|
|
io_q_.emplace_back((int32_t) layer, (int32_t) expert);
|
|
}
|
|
io_cv_.notify_one();
|
|
}
|
|
|
|
// A read-ahead worker: takes a predicted (layer, expert), skips it when its pages are cached or it is already
|
|
// staged, and otherwise reads the whole blob into a staging buffer (copy_from_files preads what is not cached).
|
|
void FileExpertSource::io_worker() {
|
|
for (;;) {
|
|
int32_t layer, expert;
|
|
{
|
|
std::unique_lock<std::mutex> lk(io_mu_);
|
|
io_cv_.wait(lk, [&] { return io_quit_ || !io_q_.empty(); });
|
|
if (io_quit_) return;
|
|
layer = io_q_.back().first; // the newest prediction first: it is the layer that comes next
|
|
expert = io_q_.back().second;
|
|
io_q_.pop_back();
|
|
}
|
|
io_pf_jobs_.fetch_add(1, std::memory_order_relaxed);
|
|
const size_t index = (size_t) layer * (size_t) n_expert_ + (size_t) expert;
|
|
if (complement_ready_ && resident_blob(index) != nullptr) continue;
|
|
if (!override_.empty() && override_[index] != nullptr) continue;
|
|
if (io_fill_) { // read what is not cached into a scratch buffer: the pages stay in the page cache for the kernels
|
|
#if defined(__linux__)
|
|
static thread_local std::vector<uint8_t> scratch;
|
|
Span sp[3];
|
|
const int ns = spans(layer, expert, sp);
|
|
bool any = false;
|
|
for (int i = 0; i < ns; ++i) {
|
|
if (sp[i].fd < 0 || resident_sampled_n(sp[i].p, sp[i].n)) continue;
|
|
if (scratch.size() < sp[i].n) scratch.resize((size_t) sp[i].n);
|
|
const auto t0 = std::chrono::steady_clock::now();
|
|
if (pread_full(sp[i].fd, scratch.data(), sp[i].n, sp[i].off)) {
|
|
io_pread_bytes_.fetch_add(sp[i].n, std::memory_order_relaxed);
|
|
io_pread_us_.fetch_add((uint64_t) std::chrono::duration<double, std::micro>(std::chrono::steady_clock::now() - t0).count(),
|
|
std::memory_order_relaxed);
|
|
io_pread_n_.fetch_add(1, std::memory_order_relaxed);
|
|
any = true;
|
|
}
|
|
}
|
|
if (any) io_pf_blobs_.fetch_add(1, std::memory_order_relaxed);
|
|
else io_pf_skips_.fetch_add(1, std::memory_order_relaxed);
|
|
#endif
|
|
continue;
|
|
}
|
|
uint64_t total = 0;
|
|
if (cached_bytes(layer, expert, total, false) >= total) {
|
|
io_pf_skips_.fetch_add(1, std::memory_order_relaxed);
|
|
continue;
|
|
}
|
|
size_t v = 0;
|
|
bool fill = false;
|
|
uint8_t* dst = nullptr;
|
|
{
|
|
std::lock_guard<std::mutex> lk(stage_mu_);
|
|
if (stage_blob_ == 0) continue;
|
|
const bool have = claim_stage((int64_t) layer * n_expert_ + expert, v, fill, /*ahead=*/true);
|
|
if (have || !fill) continue; // already staged or being read, or no buffer
|
|
stage_pf_[v] = 1;
|
|
dst = stage_buf_[v].get();
|
|
}
|
|
const bool ok = copy_from_files(layer, expert, dst);
|
|
io_pf_blobs_.fetch_add(1, std::memory_order_relaxed);
|
|
if (ok) file_read_bytes_.fetch_add(layer_blob_bytes_[(size_t) layer], std::memory_order_relaxed);
|
|
{
|
|
std::lock_guard<std::mutex> lk(stage_mu_);
|
|
stage_busy_[v] = 0;
|
|
if (!ok) {
|
|
stage_of_.erase(stage_key_[v]);
|
|
stage_key_[v] = -1;
|
|
stage_pf_[v] = 0;
|
|
}
|
|
}
|
|
stage_cv_.notify_all();
|
|
}
|
|
}
|
|
|
|
// The decode's hand-out of a blob in the experts.bin file tier with io prefetch on: what a layer's prediction read
|
|
// ahead is staged; a blob whose pages are all cached is the mapping itself (no copy); the rest is read with one
|
|
// pread into a staging buffer, not faulted in by the kernels one small request at a time.
|
|
const uint8_t* FileExpertSource::io_blob(int64_t layer, int64_t expert) {
|
|
const int64_t key = layer * n_expert_ + expert;
|
|
if (io_fill_) {
|
|
const uint8_t* b = mapped_blob(layer, expert);
|
|
if (b != nullptr) {
|
|
const uint64_t total = layer_blob_bytes_[(size_t) layer];
|
|
file_read_bytes_.fetch_add(total, std::memory_order_relaxed);
|
|
}
|
|
return b;
|
|
}
|
|
bool have;
|
|
{
|
|
std::lock_guard<std::mutex> lk(stage_mu_);
|
|
have = stage_of_.find(key) != stage_of_.end();
|
|
}
|
|
if (!have) {
|
|
// prefetch() (every decode layer calls it first) staged what was not cached: what is not staged is cached
|
|
const uint8_t* b = mapped_blob(layer, expert);
|
|
if (b != nullptr) {
|
|
const uint64_t total = layer_blob_bytes_[(size_t) layer];
|
|
io_cached_.fetch_add(total, std::memory_order_relaxed);
|
|
file_read_bytes_.fetch_add(total, std::memory_order_relaxed);
|
|
return b;
|
|
}
|
|
}
|
|
return staged_blob(layer, expert);
|
|
}
|
|
|
|
bool FileExpertSource::open(const std::string& pack_dir, int64_t n_layers, int64_t n_expert, std::string& err) {
|
|
close();
|
|
if (n_layers <= 0 || n_expert <= 0) { err = "FileExpertSource: the geometry is empty"; return false; }
|
|
const auto& layout = strata::kernels::cpu::expert_layout();
|
|
if (layout.n_layers != n_layers || layout.n_expert != n_expert) {
|
|
err = "FileExpertSource: the requested geometry does not match the loaded expert layout";
|
|
return false;
|
|
}
|
|
if ((uint64_t) n_layers > (uint64_t) std::numeric_limits<int64_t>::max() / (uint64_t) n_expert) {
|
|
err = "FileExpertSource: the expert count overflows";
|
|
return false;
|
|
}
|
|
const uint64_t blob_count = (uint64_t) n_layers * (uint64_t) n_expert;
|
|
if (blob_count > (uint64_t) std::numeric_limits<int64_t>::max() ||
|
|
(uint64_t) n_layers > (uint64_t) std::numeric_limits<size_t>::max()) {
|
|
err = "FileExpertSource: the expert count overflows";
|
|
return false;
|
|
}
|
|
|
|
std::vector<uint64_t> layer_offsets((size_t) n_layers), layer_blob_bytes((size_t) n_layers);
|
|
const uint64_t want = layout.total;
|
|
if (want == 0 || want > (uint64_t) std::numeric_limits<size_t>::max()) {
|
|
err = "FileExpertSource: the loaded expert layout has an invalid size";
|
|
return false;
|
|
}
|
|
if (!layout.native) {
|
|
if (blob_count > std::numeric_limits<uint64_t>::max() / (uint64_t) strata::kernels::cpu::BLOB) {
|
|
err = "FileExpertSource: the canonical expert size overflows";
|
|
return false;
|
|
}
|
|
const uint64_t canonical_size = blob_count * (uint64_t) strata::kernels::cpu::BLOB;
|
|
if (want != canonical_size) {
|
|
err = "FileExpertSource: the canonical expert layout has an inconsistent size";
|
|
return false;
|
|
}
|
|
const uint64_t bytes = (uint64_t) strata::kernels::cpu::BLOB;
|
|
const uint64_t layer_bytes = (uint64_t) n_expert * bytes;
|
|
for (int64_t layer = 0; layer < n_layers; ++layer) {
|
|
layer_offsets[(size_t) layer] = (uint64_t) layer * layer_bytes;
|
|
layer_blob_bytes[(size_t) layer] = bytes;
|
|
}
|
|
} else {
|
|
if (layout.offset.size() != (size_t) n_layers || layout.bytes.size() != (size_t) n_layers ||
|
|
layout.fmt.size() != (size_t) n_layers) {
|
|
err = "FileExpertSource: the native expert layout is incomplete";
|
|
return false;
|
|
}
|
|
uint64_t at = 0;
|
|
for (int64_t layer = 0; layer < n_layers; ++layer) {
|
|
const size_t i = (size_t) layer;
|
|
const uint64_t bytes = (uint64_t) layout.fmt[i].bytes;
|
|
if (layout.offset[i] != at || bytes == 0 || layout.bytes[i] != bytes ||
|
|
bytes > std::numeric_limits<uint64_t>::max() / (uint64_t) n_expert) {
|
|
err = "FileExpertSource: the native expert layout is invalid at layer " + std::to_string(layer);
|
|
return false;
|
|
}
|
|
const uint64_t layer_bytes = bytes * (uint64_t) n_expert;
|
|
if (at > want || layer_bytes > want - at) {
|
|
err = "FileExpertSource: the native expert layout exceeds its declared size at layer " +
|
|
std::to_string(layer);
|
|
return false;
|
|
}
|
|
layer_offsets[i] = layout.offset[i];
|
|
layer_blob_bytes[i] = bytes;
|
|
at += layer_bytes;
|
|
}
|
|
if (at != want) {
|
|
err = "FileExpertSource: the native expert layout has an inconsistent size";
|
|
return false;
|
|
}
|
|
}
|
|
const std::string path = pack_dir + "/experts.bin";
|
|
if (layout.native && !gguf_.empty() && !std::filesystem::exists(path)) {
|
|
// CS-T: no experts.bin - the model's GGUF shards, read in place
|
|
blobs_ = (int64_t) blob_count;
|
|
n_layers_ = n_layers;
|
|
n_expert_ = n_expert;
|
|
layer_offsets_ = std::move(layer_offsets);
|
|
layer_blob_bytes_ = std::move(layer_blob_bytes);
|
|
if (!open_gguf(err)) { close(); return false; }
|
|
record_inputs(path, gguf_, layout, true);
|
|
return true;
|
|
}
|
|
|
|
#if defined(_WIN32)
|
|
// UTF-8 -> UTF-16: the pack may live under a path with non-ASCII characters, and `CreateFileA` would
|
|
// silently mangle it into a file-not-found.
|
|
const int wide = MultiByteToWideChar(CP_UTF8, 0, path.c_str(), -1, nullptr, 0);
|
|
std::vector<wchar_t> wpath((size_t) (wide > 0 ? wide : 1));
|
|
if (wide > 0) MultiByteToWideChar(CP_UTF8, 0, path.c_str(), -1, wpath.data(), wide);
|
|
// **`FILE_FLAG_RANDOM_ACCESS` WAS HERE AND IT COST 14x.**
|
|
//
|
|
// The design depends on the OS page cache holding the whole 34 GB expert set, because this machine has
|
|
// 64 GB of DDR5 and `L9` measured the CPU path at 44.14 GB/s from DRAM. `FILE_FLAG_RANDOM_ACCESS` tells
|
|
// the cache manager the opposite: it disables read-ahead AND it lets the manager drop the pages again
|
|
// quickly, on the assumption that a large randomly-accessed file will not be re-read. Measured, on
|
|
// `strata generate --max-new 24`: **1.93 GB/s** - disk speed, 344 ms/token, and it never warmed up over 25
|
|
// tokens, because the pages were being evicted as fast as they were faulted in.
|
|
//
|
|
// The correct flag is NO flag. The access pattern IS random (10 of 512 experts per layer, a different 10
|
|
// each layer), but every byte read is read again on the next token, so retention is the whole game.
|
|
HANDLE f = CreateFileW(wpath.data(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING,
|
|
FILE_ATTRIBUTE_NORMAL, nullptr);
|
|
if (f == INVALID_HANDLE_VALUE) {
|
|
err = "FileExpertSource: cannot open " + path;
|
|
return false;
|
|
}
|
|
LARGE_INTEGER sz{};
|
|
if (!GetFileSizeEx(f, &sz)) {
|
|
CloseHandle(f);
|
|
err = "FileExpertSource: cannot size " + path;
|
|
return false;
|
|
}
|
|
if ((uint64_t) sz.QuadPart != want) {
|
|
char buf[400];
|
|
std::snprintf(buf, sizeof buf,
|
|
"FileExpertSource: %s is %llu B but the loaded expert layout requires %llu B - this is not "
|
|
"the pack this geometry came from",
|
|
path.c_str(), (unsigned long long) sz.QuadPart, (unsigned long long) want);
|
|
CloseHandle(f);
|
|
err = buf;
|
|
return false;
|
|
}
|
|
HANDLE m = CreateFileMappingW(f, nullptr, PAGE_READONLY, 0, 0, nullptr);
|
|
if (m == nullptr) {
|
|
CloseHandle(f);
|
|
err = "FileExpertSource: CreateFileMapping failed on " + path;
|
|
return false;
|
|
}
|
|
void* view = MapViewOfFile(m, FILE_MAP_READ, 0, 0, 0);
|
|
if (view == nullptr) {
|
|
CloseHandle(m);
|
|
CloseHandle(f);
|
|
err = "FileExpertSource: MapViewOfFile failed on " + path;
|
|
return false;
|
|
}
|
|
file_ = f;
|
|
mapping_ = m;
|
|
base_ = (const uint8_t*) view;
|
|
paths_.assign(1, path);
|
|
#else
|
|
const int fd = ::open(path.c_str(), O_RDONLY);
|
|
if (fd < 0) { err = "FileExpertSource: cannot open " + path; return false; }
|
|
struct stat st{};
|
|
if (fstat(fd, &st) != 0) { ::close(fd); err = "FileExpertSource: cannot stat " + path; return false; }
|
|
if (st.st_size < 0 || (uint64_t) st.st_size != want) {
|
|
char buf[400];
|
|
std::snprintf(buf, sizeof buf,
|
|
"FileExpertSource: %s is %llu B but the loaded expert layout requires %llu B - this is not "
|
|
"the pack this geometry came from",
|
|
path.c_str(), (unsigned long long) (st.st_size < 0 ? 0 : st.st_size),
|
|
(unsigned long long) want);
|
|
::close(fd);
|
|
err = buf;
|
|
return false;
|
|
}
|
|
void* view = mmap(nullptr, (size_t) want, PROT_READ, MAP_SHARED, fd, 0);
|
|
if (view == MAP_FAILED) { ::close(fd); err = "FileExpertSource: mmap failed on " + path; return false; }
|
|
fd_ = fd;
|
|
base_ = (const uint8_t*) view;
|
|
paths_.assign(1, path); // #286: open_direct opens it again with O_DIRECT
|
|
#endif
|
|
blobs_ = (int64_t) blob_count;
|
|
n_layers_ = n_layers;
|
|
n_expert_ = n_expert;
|
|
mapped_bytes_ = want;
|
|
layer_offsets_ = std::move(layer_offsets);
|
|
layer_blob_bytes_ = std::move(layer_blob_bytes);
|
|
record_inputs(path, gguf_, layout, false);
|
|
return true;
|
|
}
|
|
|
|
void FileExpertSource::close() {
|
|
io_stop();
|
|
inputs_.clear();
|
|
if (complement_arena_ != nullptr) {
|
|
if (complement_pinned_ && !complement_registered_) (void) cudaFreeHost(complement_arena_);
|
|
else {
|
|
if (complement_registered_) (void) cudaHostUnregister(complement_arena_);
|
|
if (complement_locked_ > 0)
|
|
strata::platform::unlock_resident((uint8_t*) complement_arena_ + complement_lock_off_, complement_locked_);
|
|
std::free(complement_arena_);
|
|
}
|
|
}
|
|
if (xstage_ != nullptr) {
|
|
if (xstage_pinned_) (void) cudaFreeHost(xstage_);
|
|
else std::free(xstage_);
|
|
}
|
|
xstage_ = nullptr;
|
|
xstage_pinned_ = false;
|
|
xstage_cap_ = 0;
|
|
xstage_blob_ = 0;
|
|
override_.clear();
|
|
staged_.clear();
|
|
exchange_storage_.clear();
|
|
exchanges_ = 0;
|
|
file_reads_.store(0);
|
|
complement_arena_ = nullptr;
|
|
complement_host_ = nullptr;
|
|
complement_device_ = nullptr;
|
|
complement_bytes_ = 0;
|
|
complement_offsets_.clear();
|
|
complement_pinned_ = false;
|
|
complement_partial_ = false;
|
|
complement_registered_ = false;
|
|
complement_pin_limit_ = 0;
|
|
complement_lock_off_ = 0;
|
|
complement_ready_ = false;
|
|
complement_locked_ = 0;
|
|
complement_lent_slots_ = 0;
|
|
if (!maps_.empty()) {
|
|
for (Map& m : maps_) {
|
|
#if defined(_WIN32)
|
|
if (m.base != nullptr && !m.closed) UnmapViewOfFile((LPCVOID) m.base);
|
|
if (m.mapping != nullptr) CloseHandle((HANDLE) m.mapping);
|
|
if (m.file != nullptr) CloseHandle((HANDLE) m.file);
|
|
#else
|
|
if (m.base != nullptr && !m.closed) munmap((void*) m.base, (size_t) m.bytes);
|
|
if (m.fd >= 0) ::close(m.fd);
|
|
#endif
|
|
}
|
|
maps_.clear();
|
|
base_ = nullptr; // one of the views above
|
|
unmapped_ = false;
|
|
}
|
|
role_ptr_.clear();
|
|
role_bytes_.clear();
|
|
role_file_.clear();
|
|
paths_.clear();
|
|
for (void* h : direct_) close_direct(h);
|
|
direct_.clear();
|
|
{
|
|
std::lock_guard<std::mutex> lk(stage_mu_);
|
|
// the buffers' last copies end before they are freed (#1237)
|
|
if (!stage_ev_.empty()) (void) cudaDeviceSynchronize();
|
|
stage_free_events();
|
|
stage_buf_.clear();
|
|
stage_key_.clear();
|
|
stage_epoch_.clear();
|
|
stage_used_.clear();
|
|
stage_busy_.clear();
|
|
stage_pf_.clear();
|
|
stage_of_.clear();
|
|
stage_blob_ = 0;
|
|
stage_seq_ = 0;
|
|
epoch_ = 0;
|
|
last_layer_ = -1;
|
|
stage_grew_ = false;
|
|
}
|
|
ram_reads_.store(0);
|
|
warm_stamp_.reset();
|
|
warm_hits_.store(0);
|
|
warm_count_.store(0);
|
|
file_read_bytes_.store(0);
|
|
file_blob_bytes_.store(0);
|
|
file_us_.store(0);
|
|
io_cached_.store(0); io_uncached_.store(0); io_pread_bytes_.store(0); io_pread_us_.store(0); io_pread_n_.store(0);
|
|
io_pf_jobs_.store(0); io_pf_blobs_.store(0); io_pf_skips_.store(0); io_pf_dropped_.store(0);
|
|
io_pf_used_.store(0); io_pf_unused_.store(0); io_crit_us_.store(0); io_crit_n_.store(0);
|
|
#if defined(_WIN32)
|
|
if (base_ != nullptr && !unmapped_) UnmapViewOfFile((LPCVOID) base_);
|
|
unmapped_ = false;
|
|
if (mapping_ != nullptr) CloseHandle((HANDLE) mapping_);
|
|
if (file_ != nullptr) CloseHandle((HANDLE) file_);
|
|
mapping_ = nullptr;
|
|
file_ = nullptr;
|
|
#else
|
|
if (base_ != nullptr) munmap((void*) base_, (size_t) mapped_bytes_);
|
|
if (fd_ >= 0) ::close(fd_);
|
|
fd_ = -1;
|
|
#endif
|
|
base_ = nullptr;
|
|
blobs_ = 0;
|
|
n_layers_ = 0;
|
|
n_expert_ = 0;
|
|
mapped_bytes_ = 0;
|
|
layer_offsets_.clear();
|
|
layer_blob_bytes_.clear();
|
|
reads_ = 0;
|
|
}
|
|
|
|
|
|
bool ExpertSource::copy_blob(int64_t layer, int64_t expert, uint8_t* dst) {
|
|
const uint8_t* b = blob(layer, expert);
|
|
if (b == nullptr || dst == nullptr) return false;
|
|
std::memcpy(dst, b, (size_t) strata::kernels::cpu::expert_layout().blob_bytes(layer));
|
|
return true;
|
|
}
|
|
|
|
bool ExpertSource::copy_blobs(const int32_t* layers, const int32_t* experts, uint8_t* const* dst, size_t n) {
|
|
for (size_t i = 0; i < n; ++i)
|
|
if (!copy_blob(layers[i], experts[i], dst[i])) return false;
|
|
return true;
|
|
}
|
|
|
|
// ================================ CS-T: THE GGUF SHARDS IN PLACE ================================
|
|
//
|
|
// A native pack without experts.bin: every file native_experts.txt names is mapped (MapViewOfFile / mmap, no
|
|
// flag - the same retention argument as experts.bin above), and an expert's blob [gate rows | up rows | down rows]
|
|
// is three slices of three tensors, possibly in two shards (UD-Q4_K_XL's layer 11). Nothing is read at open; a
|
|
// blob is assembled when it is asked for (`blob`, into a small pool of buffers) or copied where it is needed
|
|
// (`copy_blob`: the RAM copy, the prompt path's pinned stager buffers).
|
|
bool FileExpertSource::open_gguf(std::string& err) {
|
|
const auto& lay = strata::kernels::cpu::expert_layout();
|
|
if (!check_experts_gguf(gguf_, lay, err)) { err = "FileExpertSource: " + err; return false; }
|
|
const size_t cut = gguf_.find_last_of("/\\");
|
|
const std::string dir = cut == std::string::npos ? std::string() : gguf_.substr(0, cut + 1);
|
|
std::map<std::string, size_t> index;
|
|
role_ptr_.assign((size_t) (3 * n_layers_), nullptr);
|
|
role_bytes_.assign((size_t) (3 * n_layers_), 0);
|
|
role_file_.assign((size_t) (3 * n_layers_), 0);
|
|
for (int64_t l = 0; l < n_layers_; ++l) {
|
|
const auto& fm = lay.fmt[(size_t) l];
|
|
const uint64_t per[3] = {fm.up_off, fm.up_off, lay.bytes[(size_t) l] - fm.down_off};
|
|
for (int r = 0; r < 3; ++r) {
|
|
const size_t i = (size_t) (3 * l + r);
|
|
const std::string path = lay.gguf_file.size() > i && !lay.gguf_file[i].empty() ? dir + lay.gguf_file[i]
|
|
: gguf_;
|
|
auto it = index.find(path);
|
|
if (it == index.end()) {
|
|
Map m;
|
|
#if defined(_WIN32)
|
|
const int wide = MultiByteToWideChar(CP_UTF8, 0, path.c_str(), -1, nullptr, 0);
|
|
std::vector<wchar_t> wpath((size_t) (wide > 0 ? wide : 1));
|
|
if (wide > 0) MultiByteToWideChar(CP_UTF8, 0, path.c_str(), -1, wpath.data(), wide);
|
|
HANDLE f = CreateFileW(wpath.data(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING,
|
|
FILE_ATTRIBUTE_NORMAL, nullptr);
|
|
LARGE_INTEGER sz{};
|
|
if (f == INVALID_HANDLE_VALUE || !GetFileSizeEx(f, &sz)) {
|
|
if (f != INVALID_HANDLE_VALUE) CloseHandle(f);
|
|
err = "FileExpertSource: cannot open " + path;
|
|
return false;
|
|
}
|
|
HANDLE mh = CreateFileMappingW(f, nullptr, PAGE_READONLY, 0, 0, nullptr);
|
|
void* view = mh != nullptr ? MapViewOfFile(mh, FILE_MAP_READ, 0, 0, 0) : nullptr;
|
|
if (view == nullptr) {
|
|
if (mh != nullptr) CloseHandle(mh);
|
|
CloseHandle(f);
|
|
err = "FileExpertSource: cannot map " + path;
|
|
return false;
|
|
}
|
|
m.file = f;
|
|
m.mapping = mh;
|
|
m.bytes = (uint64_t) sz.QuadPart;
|
|
m.base = (const uint8_t*) view;
|
|
#else
|
|
const int fd = ::open(path.c_str(), O_RDONLY);
|
|
struct stat st{};
|
|
if (fd < 0 || fstat(fd, &st) != 0 || st.st_size <= 0) {
|
|
if (fd >= 0) ::close(fd);
|
|
err = "FileExpertSource: cannot open " + path;
|
|
return false;
|
|
}
|
|
void* view = mmap(nullptr, (size_t) st.st_size, PROT_READ, MAP_SHARED, fd, 0);
|
|
if (view == MAP_FAILED) { ::close(fd); err = "FileExpertSource: cannot map " + path; return false; }
|
|
m.fd = fd;
|
|
m.bytes = (uint64_t) st.st_size;
|
|
m.base = (const uint8_t*) view;
|
|
#endif
|
|
maps_.push_back(m);
|
|
paths_.push_back(path);
|
|
it = index.emplace(path, maps_.size() - 1).first;
|
|
}
|
|
const Map& m = maps_[it->second];
|
|
role_file_[i] = (int) it->second;
|
|
const uint64_t at = lay.gguf_off[i], bytes = per[r] * (uint64_t) n_expert_;
|
|
if (at > m.bytes || bytes > m.bytes - at) { // check_experts_gguf proved it; the mapping must agree
|
|
err = "FileExpertSource: an expert span runs past the end of " + path;
|
|
return false;
|
|
}
|
|
role_ptr_[i] = m.base + (size_t) at;
|
|
role_bytes_[i] = per[r];
|
|
}
|
|
}
|
|
base_ = maps_.front().base; // "opened"; mapped_blob answers nullptr in this mode
|
|
warm_stamp_.reset(new std::atomic<uint32_t>[(size_t) (n_layers_ * n_expert_)]());
|
|
for (uint64_t b : layer_blob_bytes_) stage_blob_ = std::max(stage_blob_, b);
|
|
return true;
|
|
}
|
|
|
|
bool FileExpertSource::copy_from_files(int64_t layer, int64_t expert, uint8_t* dst) const {
|
|
if (dst == nullptr || layer < 0 || expert < 0 || layer >= n_layers_ || expert >= n_expert_) return false;
|
|
if (!direct_.empty()) { // #286: from the drive; a failed read falls back to the mapping below
|
|
const Fill f{0, layer, expert, dst};
|
|
if (read_direct(&f, 1)) return true;
|
|
direct_fallbacks_.fetch_add(1, std::memory_order_relaxed);
|
|
}
|
|
#if defined(__linux__)
|
|
if (io_pf_ || io_stats_) { // count what the page cache holds; with io prefetch, read what it does not with pread
|
|
Span sp[3];
|
|
const int ns = spans(layer, expert, sp);
|
|
for (int i = 0; i < ns; ++i) {
|
|
const uint64_t res = resident_in(sp[i].p, sp[i].n);
|
|
io_cached_.fetch_add(res, std::memory_order_relaxed);
|
|
io_uncached_.fetch_add(sp[i].n - res, std::memory_order_relaxed);
|
|
if (io_pf_ && res < sp[i].n && sp[i].fd >= 0) {
|
|
const auto t0 = std::chrono::steady_clock::now();
|
|
const bool ok = pread_full(sp[i].fd, dst + sp[i].at, sp[i].n, sp[i].off);
|
|
io_pread_us_.fetch_add((uint64_t) std::chrono::duration<double, std::micro>(std::chrono::steady_clock::now() - t0).count(),
|
|
std::memory_order_relaxed);
|
|
io_pread_n_.fetch_add(1, std::memory_order_relaxed);
|
|
if (ok) {
|
|
io_pread_bytes_.fetch_add(sp[i].n, std::memory_order_relaxed);
|
|
continue;
|
|
}
|
|
}
|
|
std::memcpy(dst + sp[i].at, sp[i].p, (size_t) sp[i].n);
|
|
}
|
|
if (ns > 0) return true;
|
|
}
|
|
#endif
|
|
if (!role_ptr_.empty()) {
|
|
if (unmapped_) return false; // drop_mapping closed the GGUF views: only the unbuffered reads remain
|
|
uint64_t at = 0;
|
|
for (int r = 0; r < 3; ++r) {
|
|
const size_t i = (size_t) (3 * layer + r);
|
|
const uint64_t per = role_bytes_[i];
|
|
std::memcpy(dst + at, role_ptr_[i] + (size_t) ((uint64_t) expert * per), (size_t) per);
|
|
at += per;
|
|
}
|
|
return true;
|
|
}
|
|
const uint8_t* b = mapped_blob(layer, expert);
|
|
if (b == nullptr) return false;
|
|
std::memcpy(dst, b, (size_t) layer_blob_bytes_[(size_t) layer]);
|
|
return true;
|
|
}
|
|
|
|
// Pinned stage buffers (PR 1237): opt-in (STRATA_STAGE_PIN=1). On by default they corrupted IQ3_S decode after a 4096-token
|
|
// prompt in the 0.1.41 release gate (48 tokens of id 0; off = identical to 0.1.40.4): with page-locked buffers the cache-fill
|
|
// copy is truly asynchronous, so a recycled stage buffer can be overwritten before its copy finishes. Off until that is fixed.
|
|
#define STAGE_PIN_DEFAULT 0
|
|
constexpr uint64_t kStagePinFloor = 3ull << 30; // RAM left available after a pinned stage buffer
|
|
void FileExpertSource::StageBufFree::operator()(uint8_t* p) const noexcept {
|
|
if (pinned) (void) cudaFreeHost(p);
|
|
else delete[] p;
|
|
}
|
|
|
|
// A blob assembled from the three role slices. The buffer of a (layer, expert) is reused for another only once
|
|
// its blob has not been asked for during `kStageAge` layers (begin_layer) or 256 assemblies, whichever comes
|
|
// first, and never while it is being filled: the pool computes a layer's misses before it starts the next, and a
|
|
// fill (the GPU cache at startup, an adaptive swap, a helper GPU) copies the blob right away.
|
|
//
|
|
// `claim_stage` finds or reserves the buffer of `key` (stage_mu_ held): true when the blob is already there (or
|
|
// being filled by another thread - the caller then waits), false when the caller must fill buffer `v`.
|
|
bool FileExpertSource::claim_stage(int64_t key, size_t& v, bool& fill, bool ahead) {
|
|
constexpr uint64_t kStageSeq = 256;
|
|
const uint64_t seq = ++stage_seq_;
|
|
auto it = stage_of_.find(key);
|
|
fill = false;
|
|
if (it != stage_of_.end()) {
|
|
v = it->second;
|
|
stage_epoch_[v] = epoch_;
|
|
stage_used_[v] = seq;
|
|
if (!ahead && stage_pf_[v]) { stage_pf_[v] = 0; io_pf_used_.fetch_add(1, std::memory_order_relaxed); } // a layer asked for what was read ahead
|
|
return true;
|
|
}
|
|
v = stage_buf_.size();
|
|
uint64_t oldest = std::numeric_limits<uint64_t>::max();
|
|
for (size_t i = 0; i < stage_buf_.size(); ++i)
|
|
if (!stage_busy_[i] && (stage_epoch_[i] + kStageAge <= epoch_ || stage_used_[i] + kStageSeq <= seq) &&
|
|
stage_used_[i] < oldest) {
|
|
oldest = stage_used_[i];
|
|
v = i;
|
|
}
|
|
if (v == stage_buf_.size()) {
|
|
// Pinned, where the driver allows: a stage buffer is the source of the cache fill's cudaMemcpyAsync,
|
|
// and a pageable source is staged through the driver's bounce buffer - an extra copy at a fraction of
|
|
// the transfer rate, on the calling thread. A failure falls back to pageable for this buffer.
|
|
// STRATA_STAGE_PIN: 0 keeps them pageable (as before 0.1.41), 1 always tries to pin, unset (the default) pins while
|
|
// the host has kStagePinFloor of RAM to spare beside this buffer (the pool grows to ~257 buffers, 0.4-0.6 GiB):
|
|
// a low-RAM box keeps pageable ones instead of paying for the pinning (recommend, never force).
|
|
static const int pin_mode = [] { const char* v = std::getenv("STRATA_STAGE_PIN"); return v == nullptr ? -1 : (std::atoi(v) != 0 ? 1 : 0); }();
|
|
bool want_pin = pin_mode != 0;
|
|
if (pin_mode < 0) {
|
|
uint64_t avail = 0;
|
|
want_pin = STAGE_PIN_DEFAULT && available_memory_bytes(avail) && avail >= (uint64_t) stage_blob_ + kStagePinFloor;
|
|
}
|
|
void* p = nullptr;
|
|
cudaError_t pin_err = cudaSuccess;
|
|
if (want_pin) pin_err = cudaHostAlloc(&p, (size_t) stage_blob_, cudaHostAllocDefault);
|
|
const bool pinned = want_pin && pin_err == cudaSuccess && p != nullptr;
|
|
if (!pinned) (void) cudaGetLastError(); // the failed alloc's sticky error is ours, not the caller's
|
|
uint8_t* raw = pinned ? (uint8_t*) p : new (std::nothrow) uint8_t[(size_t) stage_blob_];
|
|
if (raw == nullptr) return false;
|
|
stage_buf_.emplace_back(raw, StageBufFree{pinned});
|
|
stage_idx_[raw] = stage_buf_.size() - 1;
|
|
stage_ev_.push_back(nullptr);
|
|
stage_ev_live_.push_back(0);
|
|
if (pinned && !stage_pin_said_) {
|
|
stage_pin_said_ = true;
|
|
std::fprintf(stderr, "FileExpertSource: the stage buffers are pinned (cudaHostAlloc)\n");
|
|
} else if (!pinned && want_pin && !stage_pin_failed_said_) {
|
|
stage_pin_failed_said_ = true;
|
|
std::fprintf(stderr, "FileExpertSource: cudaHostAlloc failed for a stage buffer (%s) - pageable it is\n",
|
|
cudaGetErrorString(pin_err));
|
|
}
|
|
stage_key_.push_back(-1);
|
|
stage_epoch_.push_back(0);
|
|
stage_used_.push_back(0);
|
|
stage_busy_.push_back(0);
|
|
stage_pf_.push_back(0);
|
|
if (stage_buf_.size() == 512 && !stage_grew_) {
|
|
stage_grew_ = true;
|
|
std::fprintf(stderr, "FileExpertSource: %zu blobs assembled from the GGUF are in use at once (%.2f GiB)\n",
|
|
stage_buf_.size(), (double) stage_buf_.size() * (double) stage_blob_ / 1073741824.0);
|
|
}
|
|
} else {
|
|
stage_of_.erase(stage_key_[v]);
|
|
if (stage_pf_[v]) { stage_pf_[v] = 0; io_pf_unused_.fetch_add(1, std::memory_order_relaxed); } // read ahead, never asked for
|
|
// #1237: a page-locked buffer is read by the DMA after the copy call returned: it is refilled only once the
|
|
// last copy queued out of it (note_async_read) has finished. Rare: the pool is sized so that a buffer asked
|
|
// for has long been consumed; a wait here means the stream is more than a pool behind.
|
|
if (v < stage_ev_live_.size() && stage_ev_live_[v]) {
|
|
stage_ev_live_[v] = 0;
|
|
if (stage_ev_[v] != nullptr) {
|
|
if (cudaEventQuery((cudaEvent_t) stage_ev_[v]) == cudaErrorNotReady) {
|
|
stage_fence_waits_.fetch_add(1, std::memory_order_relaxed);
|
|
(void) cudaEventSynchronize((cudaEvent_t) stage_ev_[v]);
|
|
}
|
|
(void) cudaGetLastError();
|
|
}
|
|
}
|
|
}
|
|
stage_key_[v] = key;
|
|
stage_epoch_[v] = epoch_;
|
|
stage_used_[v] = seq;
|
|
stage_busy_[v] = 1;
|
|
stage_of_[key] = v;
|
|
fill = true;
|
|
return false;
|
|
}
|
|
|
|
// Fills buffer `v` (reserved by claim_stage) outside the lock, then publishes it.
|
|
bool FileExpertSource::fill_stage(size_t v, int64_t layer, int64_t expert, uint8_t* dst) {
|
|
const auto t0 = std::chrono::steady_clock::now();
|
|
const bool ok = copy_from_files(layer, expert, dst);
|
|
publish_stage(v, layer, ok, std::chrono::duration<double, std::micro>(std::chrono::steady_clock::now() - t0).count());
|
|
return ok;
|
|
}
|
|
|
|
void FileExpertSource::publish_stage(size_t v, int64_t layer, bool ok, double us) {
|
|
file_us_.fetch_add((uint64_t) us, std::memory_order_relaxed);
|
|
if (ok) {
|
|
file_read_bytes_.fetch_add(layer_blob_bytes_[(size_t) layer], std::memory_order_relaxed);
|
|
file_blob_bytes_.fetch_add(layer_blob_bytes_[(size_t) layer], std::memory_order_relaxed);
|
|
}
|
|
{
|
|
std::lock_guard<std::mutex> lk(stage_mu_);
|
|
stage_busy_[v] = 0;
|
|
if (!ok) {
|
|
stage_of_.erase(stage_key_[v]);
|
|
stage_key_[v] = -1;
|
|
}
|
|
}
|
|
stage_cv_.notify_all();
|
|
}
|
|
|
|
void FileExpertSource::note_async_read(const uint8_t* blob, void* stream) {
|
|
if (blob == nullptr) return;
|
|
std::lock_guard<std::mutex> lk(stage_mu_);
|
|
const auto it = stage_idx_.find(blob);
|
|
if (it == stage_idx_.end()) return; // not a stage buffer: the mapping or the resident arena
|
|
const size_t v = it->second;
|
|
if (!stage_buf_[v].get_deleter().pinned) return; // pageable: the driver copied it before the call returned
|
|
if (stage_ev_[v] == nullptr) {
|
|
cudaEvent_t ev = nullptr;
|
|
if (cudaEventCreateWithFlags(&ev, cudaEventDisableTiming) != cudaSuccess) {
|
|
(void) cudaGetLastError();
|
|
(void) cudaStreamSynchronize((cudaStream_t) stream); // no event: wait for the copy itself
|
|
return;
|
|
}
|
|
stage_ev_[v] = ev;
|
|
}
|
|
if (cudaEventRecord((cudaEvent_t) stage_ev_[v], (cudaStream_t) stream) != cudaSuccess) {
|
|
(void) cudaGetLastError();
|
|
(void) cudaStreamSynchronize((cudaStream_t) stream);
|
|
return;
|
|
}
|
|
stage_ev_live_[v] = 1;
|
|
}
|
|
|
|
void FileExpertSource::stage_free_events() {
|
|
for (void*& e : stage_ev_)
|
|
if (e != nullptr) { (void) cudaEventDestroy((cudaEvent_t) e); e = nullptr; }
|
|
stage_ev_.clear();
|
|
stage_ev_live_.clear();
|
|
stage_idx_.clear();
|
|
}
|
|
|
|
const uint8_t* FileExpertSource::staged_blob(int64_t layer, int64_t expert) {
|
|
const int64_t key = layer * n_expert_ + expert;
|
|
size_t v = 0;
|
|
bool fill = false;
|
|
uint8_t* dst = nullptr;
|
|
const auto t0 = std::chrono::steady_clock::now();
|
|
auto crit = [&] {
|
|
if (!io_pf_) return;
|
|
io_crit_us_.fetch_add((uint64_t) std::chrono::duration<double, std::micro>(std::chrono::steady_clock::now() - t0).count(),
|
|
std::memory_order_relaxed);
|
|
io_crit_n_.fetch_add(1, std::memory_order_relaxed);
|
|
};
|
|
{
|
|
std::unique_lock<std::mutex> lk(stage_mu_);
|
|
const bool have = claim_stage(key, v, fill);
|
|
if (!have && !fill) return nullptr;
|
|
dst = stage_buf_[v].get();
|
|
if (have) {
|
|
// another thread (a prefetch, the adaptive tier) is filling it: wait for that
|
|
stage_cv_.wait(lk, [&] { return !stage_busy_[v] || stage_key_[v] != key; });
|
|
if (stage_key_[v] != key) return nullptr; // its fill failed
|
|
lk.unlock();
|
|
crit();
|
|
return dst;
|
|
}
|
|
}
|
|
const bool ok = fill_stage(v, layer, expert, dst);
|
|
crit();
|
|
return ok ? dst : nullptr;
|
|
}
|
|
|
|
void FileExpertSource::prefetch(int64_t layer, const int64_t* experts, int64_t n) {
|
|
if (!staged() || n <= 0 || layer < 0 || layer >= n_layers_) return;
|
|
if (io_fill_ && io_pf_ && direct_.empty()) { // hand the layer's uncached blobs to the workers and go on: the kernels
|
|
for (int64_t i = 0; i < n; ++i) { // that reach one before it lands wait on its pages, the rest compute
|
|
const int64_t e = experts[i];
|
|
if (e < 0 || e >= n_expert_) continue;
|
|
const size_t index = (size_t) layer * (size_t) n_expert_ + (size_t) e;
|
|
if (complement_ready_ && resident_blob(index) != nullptr) continue;
|
|
if (!override_.empty() && override_[index] != nullptr) continue;
|
|
uint64_t total = 0;
|
|
if (cached_bytes(layer, e, total, false) >= total) continue;
|
|
io_pf_demand_.fetch_add(1, std::memory_order_relaxed);
|
|
io_enqueue(layer, e);
|
|
}
|
|
return;
|
|
}
|
|
std::vector<Fill> todo;
|
|
// experts.bin with io prefetch: a blob whose pages are cached is handed out as the mapping (io_blob); only the
|
|
// uncached ones are read here, together, on the fetch threads
|
|
const bool only_uncached = io_pf_ && role_ptr_.empty() && direct_.empty();
|
|
std::vector<char> cold;
|
|
if (only_uncached) {
|
|
cold.assign((size_t) n, 0);
|
|
for (int64_t i = 0; i < n; ++i) {
|
|
const int64_t e = experts[i];
|
|
if (e < 0 || e >= n_expert_) continue;
|
|
uint64_t total = 0;
|
|
cold[(size_t) i] = cached_bytes(layer, e, total, false) < total ? 1 : 0;
|
|
}
|
|
}
|
|
const auto t0 = std::chrono::steady_clock::now();
|
|
{
|
|
std::lock_guard<std::mutex> lk(stage_mu_);
|
|
for (int64_t i = 0; i < n; ++i) {
|
|
const int64_t e = experts[i];
|
|
if (e < 0 || e >= n_expert_) continue;
|
|
const size_t index = (size_t) layer * (size_t) n_expert_ + (size_t) e;
|
|
if (complement_ready_ && resident_blob(index) != nullptr)
|
|
continue; // in the RAM copy
|
|
if (!override_.empty() && override_[index] != nullptr) continue;
|
|
if (only_uncached && !cold[(size_t) i] && stage_of_.find(layer * n_expert_ + e) == stage_of_.end()) continue;
|
|
size_t v = 0;
|
|
bool fill = false;
|
|
if (!claim_stage(layer * n_expert_ + e, v, fill) && fill) {
|
|
todo.push_back({v, layer, e, stage_buf_[v].get()});
|
|
if (warm_stamp_) {
|
|
const uint32_t s = warm_stamp_[index].load(std::memory_order_relaxed);
|
|
if (s != 0 && (uint64_t) s + 3 >= epoch_ + 1) warm_hits_.fetch_add(1, std::memory_order_relaxed);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
fill_many(todo);
|
|
if (io_pf_ && !todo.empty()) {
|
|
io_crit_us_.fetch_add((uint64_t) std::chrono::duration<double, std::micro>(std::chrono::steady_clock::now() - t0).count(),
|
|
std::memory_order_relaxed);
|
|
io_crit_n_.fetch_add(1, std::memory_order_relaxed);
|
|
}
|
|
}
|
|
|
|
void FileExpertSource::prefetch_pairs(const std::pair<int32_t, int32_t>* pairs, int64_t n) {
|
|
if (direct_.empty() || pairs == nullptr || n <= 0) return; // unbuffered only: the mapped fill stays as it was
|
|
std::vector<Fill> todo;
|
|
{
|
|
std::lock_guard<std::mutex> lk(stage_mu_);
|
|
for (int64_t i = 0; i < std::min<int64_t>(n, 64); ++i) {
|
|
const int64_t l = pairs[i].first, e = pairs[i].second;
|
|
if (l < 0 || e < 0 || l >= n_layers_ || e >= n_expert_) continue;
|
|
size_t v = 0;
|
|
bool fill = false;
|
|
if (!claim_stage(l * n_expert_ + e, v, fill) && fill) todo.push_back({v, l, e, stage_buf_[v].get()});
|
|
}
|
|
}
|
|
fill_many(todo);
|
|
}
|
|
|
|
bool FileExpertSource::advise_pairs(const std::pair<int32_t, int32_t>* pairs, int64_t n) const {
|
|
if (base_ == nullptr || unmapped_ || !direct_.empty() || !strata::platform::read_ahead_enabled()) return false;
|
|
for (int64_t i = 0; pairs != nullptr && i < n; ++i) {
|
|
const int64_t l = pairs[i].first, e = pairs[i].second;
|
|
if (l < 0 || e < 0 || l >= n_layers_ || e >= n_expert_) continue;
|
|
if (role_ptr_.empty()) { // experts.bin: the blob is one contiguous range
|
|
if (const uint8_t* b = mapped_blob(l, e)) strata::platform::advise_willneed(b, layer_blob_bytes_[(size_t) l]);
|
|
continue;
|
|
}
|
|
for (int r = 0; r < 3; ++r) {
|
|
const size_t k = (size_t) (3 * l + r);
|
|
strata::platform::advise_willneed(role_ptr_[k] + (size_t) ((uint64_t) e * role_bytes_[k]), role_bytes_[k]);
|
|
}
|
|
}
|
|
return true;
|
|
}
|
|
|
|
void FileExpertSource::fill_many(const std::vector<Fill>& todo) {
|
|
if (todo.empty()) return;
|
|
if (!direct_.empty()) {
|
|
// #286: overlapped batches - every role window of 16 blobs in flight at once; a big batch (the profile
|
|
// fill) on up to 4 threads, a decode layer's few misses on this one
|
|
std::atomic<size_t> next{0};
|
|
auto work = [&] {
|
|
for (size_t at; (at = next.fetch_add(16)) < todo.size();) {
|
|
const size_t k = std::min<size_t>(16, todo.size() - at);
|
|
const auto t0 = std::chrono::steady_clock::now();
|
|
const bool ok = read_direct(todo.data() + at, k);
|
|
const double us = std::chrono::duration<double, std::micro>(std::chrono::steady_clock::now() - t0).count();
|
|
for (size_t i = at; i < at + k; ++i) {
|
|
const Fill& f = todo[i];
|
|
// a failed batch: each blob again on its own (copy_from_files falls back to the mapping)
|
|
if (ok) publish_stage(f.v, f.layer, true, us / (double) k);
|
|
else (void) fill_stage(f.v, f.layer, f.e, f.dst);
|
|
}
|
|
}
|
|
};
|
|
const size_t nt = std::min<size_t>(4, (todo.size() + 15) / 16);
|
|
std::vector<std::thread> th;
|
|
for (size_t t = 1; t < nt; ++t) th.emplace_back(work);
|
|
work();
|
|
for (auto& t : th) t.join();
|
|
return;
|
|
}
|
|
#if defined(_WIN32)
|
|
// One PrefetchVirtualMemory call for every slice about to be copied: the memory manager reads them in large
|
|
// requests, all queued at once, where the copies' page faults would read a few clusters each. The copies below
|
|
// then find the pages resident (or in flight). STRATA_FETCH_PVM=0 is the A/B arm.
|
|
{
|
|
using Pvm = BOOL(WINAPI*)(HANDLE, ULONG_PTR, PWIN32_MEMORY_RANGE_ENTRY, ULONG);
|
|
static const Pvm pvm = [] {
|
|
const char* v = std::getenv("STRATA_FETCH_PVM");
|
|
if (v != nullptr && std::atoi(v) == 0) return (Pvm) nullptr;
|
|
return (Pvm) (void*) GetProcAddress(GetModuleHandleW(L"kernel32.dll"), "PrefetchVirtualMemory");
|
|
}();
|
|
if (pvm != nullptr) {
|
|
std::vector<WIN32_MEMORY_RANGE_ENTRY> ranges;
|
|
ranges.reserve(todo.size() * 3);
|
|
for (const Fill& f : todo)
|
|
for (int r = 0; r < 3; ++r) {
|
|
const size_t i = (size_t) (3 * f.layer + r);
|
|
ranges.push_back({(PVOID) (role_ptr_[i] + (size_t) ((uint64_t) f.e * role_bytes_[i])),
|
|
(SIZE_T) role_bytes_[i]});
|
|
}
|
|
(void) pvm(GetCurrentProcess(), (ULONG_PTR) ranges.size(), ranges.data(), 0);
|
|
}
|
|
}
|
|
#endif
|
|
// the page faults of a mapped read are one outstanding request each: several threads keep the SSD's queue full
|
|
std::atomic<size_t> next{0};
|
|
auto work = [&] {
|
|
for (size_t i; (i = next.fetch_add(1)) < todo.size();)
|
|
(void) fill_stage(todo[i].v, todo[i].layer, todo[i].e, todo[i].dst);
|
|
};
|
|
const size_t nt = std::min<size_t>(todo.size(), (size_t) fetch_threads_);
|
|
std::vector<std::thread> th;
|
|
for (size_t t = 1; t < nt; ++t) th.emplace_back(work);
|
|
work();
|
|
for (auto& t : th) t.join();
|
|
}
|
|
|
|
uint64_t FileExpertSource::expert_bytes() const {
|
|
uint64_t total = 0;
|
|
for (uint64_t b : layer_blob_bytes_) total += b * (uint64_t) n_expert_;
|
|
return total;
|
|
}
|
|
|
|
bool FileExpertSource::open_direct(std::string& why) {
|
|
#if defined(_WIN32)
|
|
for (const std::string& path : paths_) {
|
|
const int wide = MultiByteToWideChar(CP_UTF8, 0, path.c_str(), -1, nullptr, 0);
|
|
std::vector<wchar_t> w((size_t) (wide > 0 ? wide : 1), L'\0');
|
|
if (wide > 0) MultiByteToWideChar(CP_UTF8, 0, path.c_str(), -1, w.data(), wide);
|
|
HANDLE h = CreateFileW(w.data(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING,
|
|
FILE_FLAG_NO_BUFFERING | FILE_FLAG_OVERLAPPED, nullptr);
|
|
if (h == INVALID_HANDLE_VALUE) {
|
|
why += "; cannot open " + path + " unbuffered (error " + std::to_string((unsigned long long) GetLastError()) +
|
|
"), read through the file cache";
|
|
for (void* d : direct_) CloseHandle((HANDLE) d);
|
|
direct_.clear();
|
|
return false;
|
|
}
|
|
direct_.push_back(h);
|
|
}
|
|
if (role_ptr_.empty()) { // experts.bin: blob() now assembles into the stage buffers, sized for the largest blob
|
|
std::lock_guard<std::mutex> lk(stage_mu_);
|
|
for (uint64_t b : layer_blob_bytes_) stage_blob_ = std::max(stage_blob_, b);
|
|
}
|
|
return true;
|
|
#elif defined(__linux__)
|
|
// O_DIRECT: the reads bypass the page cache, as FILE_FLAG_NO_BUFFERING does (4 KiB-aligned windows, read_direct)
|
|
for (const std::string& path : paths_) {
|
|
const int fd = ::open(path.c_str(), O_RDONLY | O_DIRECT | O_CLOEXEC);
|
|
if (fd < 0) {
|
|
why += "; cannot open " + path + " with O_DIRECT (" + std::strerror(errno) + "), read through the file cache";
|
|
for (void* d : direct_) close_direct(d);
|
|
direct_.clear();
|
|
return false;
|
|
}
|
|
direct_.push_back((void*) (intptr_t) fd);
|
|
}
|
|
if (role_ptr_.empty()) { // experts.bin: blob() now assembles into the stage buffers, sized for the largest blob
|
|
std::lock_guard<std::mutex> lk(stage_mu_);
|
|
for (uint64_t b : layer_blob_bytes_) stage_blob_ = std::max(stage_blob_, b);
|
|
}
|
|
return true;
|
|
#else
|
|
(void) why;
|
|
return false;
|
|
#endif
|
|
}
|
|
|
|
bool FileExpertSource::set_unbuffered(uint64_t ram_bytes, std::string& why) {
|
|
#if defined(_WIN32) || defined(__linux__)
|
|
if (base_ == nullptr || paths_.empty() || !direct_.empty()) {
|
|
why = !direct_.empty() ? "already unbuffered" : "no expert files open";
|
|
return !direct_.empty();
|
|
}
|
|
// #577: the file tier reads the experts outside the RAM copy, not every byte of the shards (dense weights, the
|
|
// PLE table), and the copy holds at most every expert - the budget asked for can be more than that
|
|
const uint64_t experts = expert_bytes();
|
|
const uint64_t arena = std::min(ram_bytes, experts);
|
|
if (!file_tier_unbuffered(paths_, arena, experts - arena, why)) return false;
|
|
return open_direct(why);
|
|
#else
|
|
(void) ram_bytes;
|
|
why = "through the file cache (no unbuffered reads on this platform)";
|
|
return false;
|
|
#endif
|
|
}
|
|
|
|
bool FileExpertSource::recheck_unbuffered(std::string& why) {
|
|
#if defined(_WIN32) || defined(__linux__)
|
|
if (const char* env = std::getenv("STRATA_UNBUFFERED_LOAD"); env != nullptr && env[0] != '\0') {
|
|
why = std::string("STRATA_UNBUFFERED_LOAD=") + env;
|
|
return !direct_.empty();
|
|
}
|
|
if (base_ == nullptr || paths_.empty()) {
|
|
why = "no expert files open";
|
|
return false;
|
|
}
|
|
// #577: the RAM copy is built (and already out of the available RAM), so what the file cache would have to keep
|
|
// is exactly the experts outside it - the GPU cache's (refilled after a prompt borrowed their slots) and the
|
|
// ones neither holds
|
|
const uint64_t experts = expert_bytes();
|
|
const uint64_t read = experts > complement_bytes_ ? experts - complement_bytes_ : 0;
|
|
std::string w;
|
|
const bool ub = file_tier_unbuffered(paths_, 0, read, w);
|
|
char head[96];
|
|
std::snprintf(head, sizeof head, "re-checked with the RAM copy built (%.2f GiB): ",
|
|
(double) complement_bytes_ / 1073741824.0);
|
|
why = head + w;
|
|
if (ub == !direct_.empty()) return ub;
|
|
if (ub) return open_direct(why);
|
|
// through the file cache after all: the mapped reads take over (staged() stays true for the GGUF in place)
|
|
for (void* d : direct_) close_direct(d);
|
|
direct_.clear();
|
|
return false;
|
|
#else
|
|
why = "through the file cache (no unbuffered reads on this platform)";
|
|
return false;
|
|
#endif
|
|
}
|
|
|
|
bool FileExpertSource::drop_mapping(std::string& why) {
|
|
#if defined(_WIN32)
|
|
if (direct_.empty()) { why = "the reads are not unbuffered"; return false; }
|
|
if (!role_ptr_.empty() || !maps_.empty()) {
|
|
// the GGUF in place: nothing in the engine reads the shards through these views any more (the token embedding is
|
|
// copied into pinned host memory at load, the dense weights and the head into VRAM, the PLE table has its own
|
|
// reader), so every shard goes: with one mapped, NTFS runs the unbuffered reads of that file one at a time
|
|
if (unmapped_) { why = "already closed"; return true; }
|
|
for (Map& m : maps_) {
|
|
if (m.closed) continue;
|
|
if (m.base != nullptr && !UnmapViewOfFile((LPCVOID) m.base)) { why = "UnmapViewOfFile failed"; return false; }
|
|
m.closed = true; // m.base stays: the read offsets are taken from it
|
|
if (m.mapping != nullptr) CloseHandle((HANDLE) m.mapping);
|
|
m.mapping = nullptr;
|
|
if (m.file != nullptr) CloseHandle((HANDLE) m.file);
|
|
m.file = nullptr;
|
|
}
|
|
unmapped_ = true;
|
|
char note[160];
|
|
std::snprintf(note, sizeof note, "%zu GGUF shard%s unmapped; every expert outside RAM and VRAM is read unbuffered",
|
|
maps_.size(), maps_.size() == 1 ? "" : "s");
|
|
why = note;
|
|
return true;
|
|
}
|
|
if (base_ == nullptr || unmapped_) { why = base_ == nullptr ? "not open" : "already closed"; return unmapped_; }
|
|
if (!UnmapViewOfFile((LPCVOID) base_)) { why = "UnmapViewOfFile failed"; return false; }
|
|
unmapped_ = true;
|
|
if (mapping_ != nullptr) CloseHandle((HANDLE) mapping_);
|
|
mapping_ = nullptr;
|
|
// the cached handle too: only the unbuffered handles (direct_) read the file from here on
|
|
if (file_ != nullptr) CloseHandle((HANDLE) file_);
|
|
file_ = nullptr;
|
|
why = "every expert outside RAM and VRAM is read unbuffered";
|
|
return true;
|
|
#else
|
|
// Linux's page cache has no such lock: only the tests close the GGUF views (STRATA_TEST_UNMAP_GGUF=1), to run the
|
|
// unmapped path the Windows file tier takes
|
|
const char* t = std::getenv("STRATA_TEST_UNMAP_GGUF");
|
|
if (t == nullptr || t[0] == ' |