okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

waveringanaSTRATA_KV_GROW_ANY=1 lets --kv-grow run beside the resident RAM budget and the helper caches (only CUDA0's cache goes into the VMM range): 30K decode +12%, 64K prefill 81 -> 60 s with --prefill auto3eb5c0d94

main
41.4 KiB955 linesraw
1// src/core/expert_cache.cpp - R4's slot storage and residency table.  Read the header first.
2#include "strata/core/expert_cache.hpp"
3#include "strata/core/expert_cache_refuse.hpp"
4
5// #533's segmented cache uses CUDA's virtual memory management (cuMem*): not on HIP, neither the RDNA backend nor
6// the gfx906 compat build (PR #638), which compiles this file as HIP without STRATA_USE_HIP
7#if defined(STRATA_USE_HIP) || defined(STRATA_HIP_GFX906) || defined(STRATA_GPU_METAL)
8#define STRATA_EC_NO_VMM 1
9#endif
10
11#include <thread>
12#include <mutex>
13#include <cuda_runtime.h>
14#if !defined(STRATA_EC_NO_VMM)
15#include <cuda.h>   // #533: the virtual memory management types (the functions come through the runtime's entry points)
16#endif
17
18#include <algorithm>
19#include <atomic>
20#include <cstdio>
21#include <filesystem>
22#include <cstdlib>
23#include <utility>
24#include <cstring>
25
26// (not in a SYCL build: its CUDA names are a compatibility layer without the PCI ids NVML is matched by)
27#if defined(_WIN32) && !defined(STRATA_EC_NO_VMM) && !defined(SYCL_LANGUAGE_VERSION)
28#ifndef WIN32_LEAN_AND_MEAN
29#define WIN32_LEAN_AND_MEAN
30#endif
31#ifndef NOMINMAX
32#define NOMINMAX
33#endif
34#include <windows.h>
35#define STRATA_EC_NVML_FREE 1
36#endif
37
38namespace strata::core {
39
40#if defined(STRATA_EC_NVML_FREE)
41namespace {
42
43// STRATA_VRAM_FREE=device (opt-in, Windows + NVIDIA).  Under WDDM cudaMemGetInfo answers for THIS process: memory
44// another process holds on the card (the image encoder, a browser, another engine) is not in its free figure.
45// Measured on an RTX 5090, driver 610.88: with 6 GiB written by another process, cudaMemGetInfo in a second process
46// still read 30,994 MiB free where NVML read 24,348.  NVML (nvml.dll, installed with every driver) counts the whole
47// card.  The library is loaded from the system directory only, at first use; false when it cannot answer.
48bool nvml_device_free(size_t& out) {
49    struct Memory { unsigned long long total, free, used; };
50    typedef int (*InitFn)(void);
51    typedef int (*ByBusFn)(const char*, void**);
52    typedef int (*MemFn)(void*, Memory*);
53    struct Lib {
54        ByBusFn by_bus = nullptr;
55        MemFn mem = nullptr;
56        Lib() {
57            HMODULE h = LoadLibraryExW(L"nvml.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32);
58            if (h == nullptr) return;
59            const auto init = (InitFn) (void*) GetProcAddress(h, "nvmlInit_v2");
60            const auto bus = (ByBusFn) (void*) GetProcAddress(h, "nvmlDeviceGetHandleByPciBusId_v2");
61            const auto m = (MemFn) (void*) GetProcAddress(h, "nvmlDeviceGetMemoryInfo");
62            if (init == nullptr || bus == nullptr || m == nullptr || init() != 0) return;
63            by_bus = bus;
64            mem = m;
65        }
66    };
67    static const Lib lib;
68    if (lib.mem == nullptr) return false;
69    int dev = 0;
70    cudaDeviceProp prop{};
71    if (cudaGetDevice(&dev) != cudaSuccess || cudaGetDeviceProperties(&prop, dev) != cudaSuccess) return false;
72    char bus[32];
73    std::snprintf(bus, sizeof bus, "%08X:%02X:%02X.0", (unsigned) prop.pciDomainID, (unsigned) prop.pciBusID,
74                  (unsigned) prop.pciDeviceID);
75    void* handle = nullptr;
76    Memory m{};
77    if (lib.by_bus(bus, &handle) != 0 || lib.mem(handle, &m) != 0) return false;
78    out = (size_t) m.free;
79    return true;
80}
81
82}  // namespace
83#endif
84
85namespace {
86// STRATA_EXPERT_NIBBLE: a write into a sealed cache (see ExpertCache::seal).  Says which call and stops: the slots hold
87// 4-bit codes the GGUF bytes would overwrite, or a GGUF expert where a 4-bit one is expected - a wrong reply, not an error.
88[[noreturn]] void sealed_write(const char* call, int32_t slot) {
89    std::fprintf(stderr, "strata: STRATA_EXPERT_NIBBLE: ExpertCache::%s(slot %d) after the cache was sealed - a GGUF "
90                         "blob would be written into the 4-bit expert slots: stopping\n", call, (int) slot);
91    std::fflush(stderr);
92    std::abort();
93}
94}  // namespace
95
96// See the header.  NVIDIA's DGX Spark Porting Guide (section 5.5, "Memory reporting on UMA systems") recommends the same:
97// not to rely on cudaMemGetInfo alone but to count the memory the OS can reclaim.  Swap is not counted here (unlike
98// NVIDIA's reference snippet): an expert cache that pushes the system into swap would be far slower than a smaller one.
99size_t device_free_bytes() {
100    size_t free_b = 0, total_b = 0;
101    if (const cudaError_t e = cudaMemGetInfo(&free_b, &total_b); e != cudaSuccess) {
102        // #5708: a failed query is not a full card.  It still counts as nothing free (the callers size from it), but the
103        // engine says why, once per kind of error, so a "0.00 GiB free" after it is not read as a measurement; the error
104        // is taken off the thread's last-error state so a later check does not report it as its own.
105        free_b = 0;
106        (void) cudaGetLastError();
107        static std::atomic<int> said{(int) cudaSuccess};
108        if (said.exchange((int) e) != (int) e)
109            // the error's text and number: cudaGetErrorName is not in every build's runtime layer (the Mac's
110            // metal_compat, the HIP shim)
111            std::fprintf(stderr, "strata: the free graphics memory could not be read (%s, error %d); the expert cache "
112                                 "counts it as none free, so it may start with no GPU slots. If this repeats, restart "
113                                 "the computer.\n", cudaGetErrorString(e), (int) e);
114    }
115#if defined(__linux__) && !defined(STRATA_HIP_GFX906)   // (the gfx906 compat layer has no cudaDevAttrIntegrated; that GPU is discrete)
116    // per device: a box can mix an integrated GPU (an APU) with a discrete one, and the answer is the CURRENT device's
117    static std::atomic<int> uma_cache[64];   // 0 unknown, 1 integrated (unified memory), 2 discrete
118    bool unified_memory = false;
119    {
120        int dev = 0, v = 0;
121        if (cudaGetDevice(&dev) == cudaSuccess && dev >= 0 && dev < 64) {
122            int c = uma_cache[dev].load(std::memory_order_acquire);
123            if (c == 0) {
124                c = cudaDeviceGetAttribute(&v, cudaDevAttrIntegrated, dev) == cudaSuccess && v ? 1 : 2;
125                uma_cache[dev].store(c, std::memory_order_release);
126            }
127            unified_memory = c == 1;
128        }
129    }
130    if (unified_memory) {
131        if (FILE* m = std::fopen("/proc/meminfo", "r")) {
132            char line[256];
133            unsigned long long kb = 0;
134            while (std::fgets(line, sizeof line, m))
135                if (std::sscanf(line, "MemAvailable: %llu kB", &kb) == 1) break;
136            std::fclose(m);
137            // STRATA_UMA_HEADROOM_GIB: a whole number of GiB, 0..1024; anything else keeps the default 6 (said once)
138            static const long gib = [] {
139                const char* h = std::getenv("STRATA_UMA_HEADROOM_GIB");
140                if (h == nullptr) return 6L;
141                char* end = nullptr;
142                const long v = std::strtol(h, &end, 10);
143                if (end != h && *end == '\0' && v >= 0 && v <= 1024) return v;
144                std::fprintf(stderr, "strata: STRATA_UMA_HEADROOM_GIB=%s is not a whole number of GiB (0-1024): using 6\n", h);
145                return 6L;
146            }();
147            const unsigned long long head = (unsigned long long) gib << 30;
148            const unsigned long long avail = kb << 10;
149            if (avail > head && avail - head > free_b) free_b = (size_t) (avail - head);
150        }
151    }
152#endif
153#if defined(STRATA_EC_NVML_FREE)
154    static const bool device_wide = [] {
155        const char* v = std::getenv("STRATA_VRAM_FREE");
156        return v != nullptr && std::strcmp(v, "device") == 0;
157    }();
158    if (device_wide) {
159        size_t nvml_b = 0;
160        const bool got = nvml_device_free(nvml_b);
161        static std::atomic<bool> said{false};
162        if (!said.exchange(true)) {
163            if (got)
164                std::fprintf(stderr, "strata generate: STRATA_VRAM_FREE=device: free VRAM is read for the whole card "
165                                     "(NVML: %lld MiB now; CUDA's figure for this process alone: %lld MiB)\n",
166                             (long long) (nvml_b >> 20), (long long) (free_b >> 20));
167            else
168                std::fprintf(stderr, "strata generate: STRATA_VRAM_FREE=device: NVML did not answer (nvml.dll); free "
169                                     "VRAM stays CUDA's figure for this process\n");
170        }
171        if (got) free_b = std::min(free_b, nvml_b);
172    }
173#endif
174    return free_b;
175}
176
177bool read_expert_profile(const std::string& path, int64_t n_layers, int64_t n_expert,
178                         std::vector<std::pair<int32_t, int32_t>>& ranked, int64_t& slots, std::string& err) {
179    std::FILE* f = std::fopen(path.c_str(), "rb");
180    if (f == nullptr) {
181        err = "read_expert_profile: cannot open " + path;
182        return false;
183    }
184    char magic[4] = {0, 0, 0, 0};
185    uint32_t hdr[5] = {0, 0, 0, 0, 0};
186    if (std::fread(magic, 1, 4, f) != 4 || std::fread(hdr, 4, 5, f) != 5) {
187        std::fclose(f);
188        err = "read_expert_profile: " + path + " is too short to hold a header";
189        return false;
190    }
191    if (std::memcmp(magic, "STRP", 4) != 0) {
192        std::fclose(f);
193        err = "read_expert_profile: " + path + " does not start with STRP";
194        return false;
195    }
196    const uint32_t version = hdr[0], nl = hdr[1], ne = hdr[2], want = hdr[3], n_ranked = hdr[4];
197    // the version comes first: the fields after it are only known to be these in a version 1 file, so a later
198    // format is refused by its number rather than read as if it were this one
199    if (version != 1) {
200        std::fclose(f);
201        char buf[256];
202        std::snprintf(buf, sizeof buf,
203                      "read_expert_profile: %s is a version %u profile but this engine reads version 1 - it was "
204                      "written by a different release's tools/make_profile.py or --expert-profile-save",
205                      path.c_str(), version);
206        err = buf;
207        return false;
208    }
209    if ((int64_t) nl != n_layers || (int64_t) ne != n_expert) {
210        std::fclose(f);
211        char buf[256];
212        std::snprintf(buf, sizeof buf,
213                      "read_expert_profile: %s is %ux%u but this model is %lldx%lld - it is a profile for a "
214                      "different artifact", path.c_str(), nl, ne, (long long) n_layers, (long long) n_expert);
215        err = buf;
216        return false;
217    }
218    if (n_ranked > want) {
219        std::fclose(f);
220        err = "read_expert_profile: the header claims more ranked pairs than slots";
221        return false;
222    }
223    ranked.assign(n_ranked, {0, 0});
224    std::vector<uint16_t> raw((size_t) n_ranked * 2);
225    if (n_ranked > 0 && std::fread(raw.data(), 2, (size_t) n_ranked * 2, f) != (size_t) n_ranked * 2) {
226        std::fclose(f);
227        err = "read_expert_profile: the ranked list is truncated";
228        return false;
229    }
230    std::fclose(f);
231    for (uint32_t i = 0; i < n_ranked; ++i) {
232        const int32_t l = (int32_t) raw[(size_t) i * 2], e = (int32_t) raw[(size_t) i * 2 + 1];
233        if (l < 0 || l >= n_layers || e < 0 || e >= n_expert) {
234            char buf[256];
235            std::snprintf(buf, sizeof buf, "read_expert_profile: pair %u is (layer %d, expert %d), out of range",
236                          i, l, e);
237            err = buf;
238            return false;
239        }
240        ranked[(size_t) i] = {l, e};
241    }
242    slots = (int64_t) want;
243    return true;
244}
245
246std::vector<std::pair<int32_t, int32_t>> rank_learned_profile(int64_t n_layers, int64_t n_expert,
247                                                              const std::vector<uint8_t>& resident,
248                                                              const std::vector<double>& heat,
249                                                              const std::vector<std::pair<int32_t, int32_t>>& prior) {
250    const size_t n = (size_t) (n_layers * n_expert);
251    std::vector<int64_t> prior_rank(n, INT64_MAX);
252    for (size_t r = 0; r < prior.size(); ++r) {
253        const auto [l, e] = prior[r];
254        if (l >= 0 && l < n_layers && e >= 0 && e < n_expert) {
255            int64_t& pr = prior_rank[(size_t) (l * n_expert + e)];
256            if (pr == INT64_MAX) pr = (int64_t) r;
257        }
258    }
259    std::vector<int64_t> order(n);
260    for (size_t i = 0; i < n; ++i) order[i] = (int64_t) i;
261    auto res = [&](int64_t i) { return (size_t) i < resident.size() && resident[(size_t) i] != 0; };
262    auto ht = [&](int64_t i) { return (size_t) i < heat.size() ? heat[(size_t) i] : 0.0; };
263    std::stable_sort(order.begin(), order.end(), [&](int64_t a, int64_t b) {
264        if (res(a) != res(b)) return res(a);
265        if (ht(a) != ht(b)) return ht(a) > ht(b);
266        if (prior_rank[(size_t) a] != prior_rank[(size_t) b]) return prior_rank[(size_t) a] < prior_rank[(size_t) b];
267        return a < b;
268    });
269    std::vector<std::pair<int32_t, int32_t>> ranked(n);
270    for (size_t r = 0; r < n; ++r)
271        ranked[r] = {(int32_t) (order[r] / n_expert), (int32_t) (order[r] % n_expert)};
272    return ranked;
273}
274
275bool write_expert_profile(const std::string& path, int64_t n_layers, int64_t n_expert,
276                          const std::vector<std::pair<int32_t, int32_t>>& ranked, std::string& err) {
277    if (n_layers <= 0 || n_expert <= 0 || n_layers > 65535 || n_expert > 65535) {
278        err = "write_expert_profile: the model's layout does not fit the format";
279        return false;
280    }
281    std::vector<int32_t> table((size_t) (n_layers * n_expert), -1);
282    std::vector<uint16_t> pairs;
283    pairs.reserve(ranked.size() * 2);
284    for (size_t r = 0; r < ranked.size(); ++r) {
285        const auto [l, e] = ranked[r];
286        if (l < 0 || l >= n_layers || e < 0 || e >= n_expert) {
287            err = "write_expert_profile: a ranked pair is out of range";
288            return false;
289        }
290        table[(size_t) (l * n_expert + e)] = (int32_t) r;
291        pairs.push_back((uint16_t) l);
292        pairs.push_back((uint16_t) e);
293    }
294    const uint32_t hdr[5] = {1u, (uint32_t) n_layers, (uint32_t) n_expert, (uint32_t) ranked.size(),
295                             (uint32_t) ranked.size()};
296    const std::string tmp = path + ".tmp";
297    std::FILE* f = std::fopen(tmp.c_str(), "wb");
298    if (f == nullptr) {
299        err = "write_expert_profile: cannot create " + tmp;
300        return false;
301    }
302    // the format is little-endian (make_profile.py's "<"): so is every machine this engine runs on
303    bool ok = std::fwrite("STRP", 1, 4, f) == 4 && std::fwrite(hdr, 4, 5, f) == 5 &&
304              (pairs.empty() || std::fwrite(pairs.data(), 2, pairs.size(), f) == pairs.size()) &&
305              std::fwrite(table.data(), 4, table.size(), f) == table.size();
306    ok = (std::fclose(f) == 0) && ok;
307    std::error_code ec;
308    if (ok) std::filesystem::rename(tmp, path, ec);   // replaces an existing file (MoveFileEx / rename(2))
309    if (!ok || ec) {
310        std::filesystem::remove(tmp, ec);
311        err = "write_expert_profile: cannot write " + path;
312        return false;
313    }
314    return true;
315}
316
317ExpertCache::~ExpertCache() { close(); }
318
319namespace ec_test {   // strata/core/expert_cache_refuse.hpp: tests only, null in the engine
320bool (*refuse_segment_call)(const char* call, int64_t seg) = nullptr;
321}  // namespace ec_test
322
323// ---- #533: the segmented arena (--vram-elastic).  The driver API's virtual memory functions, looked up through the
324// runtime (no link against the driver library): one address range for the whole arena, backed by physical segments,
325// and the tail's segments unmapped / mapped again later.  Nothing here runs unless a segment size was set.
326#if !defined(STRATA_EC_NO_VMM)
327namespace {
328struct Vmm {
329    CUresult (CUDAAPI* device_get)(CUdevice*, int) = nullptr;
330    CUresult (CUDAAPI* attribute)(int*, CUdevice_attribute, CUdevice) = nullptr;
331    CUresult (CUDAAPI* granularity)(size_t*, const CUmemAllocationProp*, CUmemAllocationGranularity_flags) = nullptr;
332    CUresult (CUDAAPI* reserve)(CUdeviceptr*, size_t, size_t, CUdeviceptr, unsigned long long) = nullptr;
333    CUresult (CUDAAPI* address_free)(CUdeviceptr, size_t) = nullptr;
334    CUresult (CUDAAPI* create)(CUmemGenericAllocationHandle*, size_t, const CUmemAllocationProp*,
335                               unsigned long long) = nullptr;
336    CUresult (CUDAAPI* release)(CUmemGenericAllocationHandle) = nullptr;
337    CUresult (CUDAAPI* map)(CUdeviceptr, size_t, size_t, CUmemGenericAllocationHandle, unsigned long long) = nullptr;
338    CUresult (CUDAAPI* unmap)(CUdeviceptr, size_t) = nullptr;
339    CUresult (CUDAAPI* set_access)(CUdeviceptr, size_t, const CUmemAccessDesc*, size_t) = nullptr;
340    bool ok = false;
341};
342
343template <class F> bool entry(const char* name, F& f) {
344    void* p = nullptr;
345    cudaDriverEntryPointQueryResult q{};
346#if CUDART_VERSION >= 12050
347    const cudaError_t e = cudaGetDriverEntryPointByVersion(name, &p, 12000, cudaEnableDefault, &q);
348#else
349    const cudaError_t e = cudaGetDriverEntryPoint(name, &p, cudaEnableDefault, &q);
350#endif
351    if (e != cudaSuccess || q != cudaDriverEntryPointSuccess || p == nullptr) {
352        (void) cudaGetLastError();
353        return false;
354    }
355    f = reinterpret_cast<F>(p);
356    return true;
357}
358
359const Vmm& vmm() {
360    static const Vmm v = [] {
361        Vmm x;
362        x.ok = entry("cuDeviceGet", x.device_get) && entry("cuDeviceGetAttribute", x.attribute) &&
363               entry("cuMemGetAllocationGranularity", x.granularity) && entry("cuMemAddressReserve", x.reserve) &&
364               entry("cuMemAddressFree", x.address_free) && entry("cuMemCreate", x.create) &&
365               entry("cuMemRelease", x.release) && entry("cuMemMap", x.map) && entry("cuMemUnmap", x.unmap) &&
366               entry("cuMemSetAccess", x.set_access);
367        return x;
368    }();
369    return v;
370}
371
372CUmemAllocationProp device_prop(int dev) {
373    CUmemAllocationProp prop{};
374    prop.type = CU_MEM_ALLOCATION_TYPE_PINNED;
375    prop.location.type = CU_MEM_LOCATION_TYPE_DEVICE;
376    prop.location.id = dev;
377    return prop;
378}
379
380// one segment: a physical allocation mapped at `va`, readable and writable by this device
381bool map_segment(const Vmm& v, int dev, CUdeviceptr va, size_t bytes, unsigned long long& handle) {
382    const CUmemAllocationProp prop = device_prop(dev);
383    CUmemGenericAllocationHandle h = 0;
384    if (v.create(&h, bytes, &prop, 0) != CUDA_SUCCESS) return false;
385    if (v.map(va, bytes, 0, h, 0) != CUDA_SUCCESS) {
386        v.release(h);
387        return false;
388    }
389    CUmemAccessDesc access{};
390    access.location.type = CU_MEM_LOCATION_TYPE_DEVICE;
391    access.location.id = dev;
392    access.flags = CU_MEM_ACCESS_FLAGS_PROT_READWRITE;
393    if (v.set_access(va, bytes, &access, 1) != CUDA_SUCCESS) {
394        v.unmap(va, bytes);
395        v.release(h);
396        return false;
397    }
398    handle = (unsigned long long) h;
399    return true;
400}
401}  // namespace
402#endif
403
404#if !defined(STRATA_EC_NO_VMM)
405// the driver and this GPU offer the virtual memory functions the segmented arena needs (the check open_segmented makes first)
406static bool segmented_supported() {
407    const Vmm& v = vmm();
408    int dev = 0, supported = 0;
409    CUdevice cu = 0;
410    return v.ok && cudaGetDevice(&dev) == cudaSuccess && v.device_get(&cu, dev) == CUDA_SUCCESS &&
411           v.attribute(&supported, CU_DEVICE_ATTRIBUTE_VIRTUAL_MEMORY_MANAGEMENT_SUPPORTED, cu) == CUDA_SUCCESS && supported;
412}
413#endif
414
415bool ExpertCache::open_segmented(uint64_t want, std::string& err) {
416#if defined(STRATA_EC_NO_VMM)
417    (void) want;
418    err = "ExpertCache: --vram-elastic (a segmented expert cache) is CUDA-only for now";
419    return false;
420#else
421    const Vmm& v = vmm();
422    int dev = 0, supported = 0;
423    CUdevice cu = 0;
424    if (!v.ok || cudaGetDevice(&dev) != cudaSuccess || v.device_get(&cu, dev) != CUDA_SUCCESS ||
425        v.attribute(&supported, CU_DEVICE_ATTRIBUTE_VIRTUAL_MEMORY_MANAGEMENT_SUPPORTED, cu) != CUDA_SUCCESS ||
426        !supported) {
427        err = "ExpertCache: --vram-elastic needs the driver's virtual memory management, which this GPU or driver "
428              "does not offer";
429        return false;
430    }
431    const CUmemAllocationProp prop = device_prop(dev);
432    size_t gran = 0;
433    if (v.granularity(&gran, &prop, CU_MEM_ALLOC_GRANULARITY_RECOMMENDED) != CUDA_SUCCESS || gran == 0) {
434        err = "ExpertCache: cannot read the driver's allocation granularity";
435        return false;
436    }
437    const uint64_t g = (uint64_t) gran;
438    const uint64_t total = (want + g - 1) / g * g;
439    seg_ = (int64_t) (((uint64_t) seg_req_ + g - 1) / g * g);
440    CUdeviceptr va = 0;
441    if (v.reserve(&va, (size_t) total, 0, 0, 0) != CUDA_SUCCESS) {
442        err = "ExpertCache: cannot reserve the address range of the segmented expert cache";
443        return false;
444    }
445    base_ = reinterpret_cast<uint8_t*>(va);
446    reserved_ = total;
447    for (uint64_t at = 0; at < total; at += (uint64_t) seg_) {
448        segs_.push_back(0);
449        seg_size_.push_back((int64_t) std::min<uint64_t>((uint64_t) seg_, total - at));
450    }
451    for (size_t i = 0; i < segs_.size(); ++i) {
452        if (!map_segment(v, dev, va + (CUdeviceptr) ((uint64_t) i * (uint64_t) seg_), (size_t) seg_size_[i],
453                         segs_[i])) {
454            char buf[200];
455            std::snprintf(buf, sizeof buf, "ExpertCache: cudaMalloc failed: segment %zu of %zu (%.2f GiB) of the "
456                          "segmented cache could not be allocated", i + 1, segs_.size(),
457                          (double) seg_size_[i] / 1073741824.0);
458            err = buf;   // "cudaMalloc failed": the auto cache's smaller-retry path reads it as an allocation failure
459            release_segmented();
460            return false;
461        }
462        mapped_segs_ = (int64_t) i + 1;
463    }
464    return true;
465#endif
466}
467
468void ExpertCache::release_segmented() {
469#if !defined(STRATA_EC_NO_VMM)
470    const Vmm& v = vmm();
471    if (base_ != nullptr) cudaDeviceSynchronize();
472    const CUdeviceptr va = reinterpret_cast<CUdeviceptr>(base_);
473    for (size_t i = 0; i < segs_.size(); ++i)
474        if (segs_[i] != 0) {
475            // a handle past mapped_segs_ is one a shrink unmapped and the driver did not take back: released only
476            if (i < (size_t) mapped_segs_) v.unmap(va + (CUdeviceptr) ((uint64_t) i * (uint64_t) seg_), (size_t) seg_size_[i]);
477            v.release((CUmemGenericAllocationHandle) segs_[i]);
478        }
479    if (base_ != nullptr && reserved_ > 0) v.address_free(va, (size_t) reserved_);
480#endif
481    segs_.clear();
482    seg_size_.clear();
483    mapped_segs_ = 0;
484    reserved_ = 0;
485    base_ = nullptr;
486}
487
488int64_t ExpertCache::mapped_bytes() const {
489    if (segs_.empty()) return base_ != nullptr ? full_bytes() : 0;
490    int64_t b = 0;
491    for (int64_t i = 0; i < mapped_segs_; ++i) b += seg_size_[(size_t) i];
492    return b;
493}
494
495int64_t ExpertCache::slots_within(int64_t bytes) const {
496    if (bytes >= full_bytes()) return slots_;
497    if (bytes <= 0) return 0;
498    if (off_.empty()) return blob_ > 0 ? bytes / blob_ : 0;
499    // off_[i + 1] is slot i's end: count the slots whose end is at most `bytes`
500    return (int64_t) (std::upper_bound(off_.begin() + 1, off_.end(), (uint64_t) bytes) - (off_.begin() + 1));
501}
502
503bool ExpertCache::shrink(int64_t keep_bytes, std::string& err) {
504    if (segs_.empty()) {
505        err = "the expert cache is not segmented (the engine needs --vram-elastic)";
506        return false;
507    }
508#if defined(STRATA_EC_NO_VMM)
509    (void) keep_bytes;
510    return false;
511#else
512    const Vmm& v = vmm();
513    int64_t keep = 0, at = 0;   // the segments [0, keep) hold the first keep_bytes
514    while (keep < (int64_t) segs_.size() && at < keep_bytes) at += seg_size_[(size_t) keep++];
515    if (keep >= mapped_segs_) return true;
516    if (cudaDeviceSynchronize() != cudaSuccess) {
517        err = std::string("the device failed before the cache shrank: ") + cudaGetErrorString(cudaGetLastError());
518        return false;
519    }
520    const CUdeviceptr va = reinterpret_cast<CUdeviceptr>(base_);
521    auto refused = [](const char* call, int64_t seg) {
522        return ec_test::refuse_segment_call != nullptr && ec_test::refuse_segment_call(call, seg);
523    };
524    for (int64_t i = mapped_segs_ - 1; i >= keep; --i) {
525        const CUdeviceptr p = va + (CUdeviceptr) ((uint64_t) i * (uint64_t) seg_);
526        if (refused("unmap", i) || v.unmap(p, (size_t) seg_size_[(size_t) i]) != CUDA_SUCCESS) {
527            err = "the driver refused to release an expert-cache segment";
528            live_slots_ = slots_within(mapped_bytes());   // segment i is still mapped: [0, i] stay
529            return false;
530        }
531        mapped_segs_ = i;   // unmapped: its slots are gone, whether or not the driver takes the handle back
532        if (refused("release", i) || v.release((CUmemGenericAllocationHandle) segs_[(size_t) i]) != CUDA_SUCCESS) {
533            err = "the driver refused to release an expert-cache segment";
534            live_slots_ = slots_within(mapped_bytes());   // the handle stays in segs_[i]: grow and close release it again
535            return false;
536        }
537        segs_[(size_t) i] = 0;
538    }
539    live_slots_ = slots_within(mapped_bytes());
540    return true;
541#endif
542}
543
544bool ExpertCache::grow(int64_t want_bytes, std::string& err) {
545    if (segs_.empty()) {
546        err = "the expert cache is not segmented (the engine needs --vram-elastic)";
547        return false;
548    }
549#if defined(STRATA_EC_NO_VMM)
550    (void) want_bytes;
551    return false;
552#else
553    const Vmm& v = vmm();
554    int dev = 0;
555    cudaGetDevice(&dev);
556    const CUdeviceptr va = reinterpret_cast<CUdeviceptr>(base_);
557    int64_t at = mapped_bytes();
558    while (mapped_segs_ < (int64_t) segs_.size() && at + seg_size_[(size_t) mapped_segs_] <= want_bytes) {
559        const size_t i = (size_t) mapped_segs_;
560        if (segs_[i] != 0) {   // a shrink unmapped this segment and the driver kept its handle then: it goes back first
561            if (v.release((CUmemGenericAllocationHandle) segs_[i]) != CUDA_SUCCESS) {
562                err = "the driver has no VRAM for another expert-cache segment";
563                live_slots_ = slots_within(mapped_bytes());
564                return false;
565            }
566            segs_[i] = 0;
567        }
568        if (!map_segment(v, dev, va + (CUdeviceptr) ((uint64_t) i * (uint64_t) seg_), (size_t) seg_size_[i],
569                         segs_[i])) {
570            (void) cudaGetLastError();
571            err = "the driver has no VRAM for another expert-cache segment";
572            live_slots_ = slots_within(mapped_bytes());
573            return false;
574        }
575        at += seg_size_[i];
576        ++mapped_segs_;
577    }
578    live_slots_ = slots_within(mapped_bytes());
579    return true;
580#endif
581}
582
583#if defined(STRATA_USE_HIP)
584bool ExpertCache::ensure_blocking_staging(std::size_t bytes, std::string& err) {
585    if (bytes <= blocking_staging_bytes_) return true;
586    void* next = nullptr;
587    const cudaError_t status = cudaHostAlloc(&next, bytes, cudaHostAllocDefault);
588    if (status != cudaSuccess) {
589        err = std::string("ExpertCache: HIP blocking staging allocation: ") + cudaGetErrorString(status);
590        return false;
591    }
592    if (blocking_staging_) (void) cudaFreeHost(blocking_staging_);
593    blocking_staging_ = static_cast<uint8_t*>(next);
594    blocking_staging_bytes_ = bytes;
595    return true;
596}
597#endif
598
599namespace {
600bool g_cache_vmm = false;   // set_vmm
601}  // namespace
602
603void ExpertCache::set_vmm(bool enabled) { g_cache_vmm = enabled; }
604
605bool ExpertCache::open(int64_t n_slots, int64_t n_layers, int64_t n_expert, int64_t blob_bytes,
606                       std::string& err) {
607    close();
608    if (n_slots <= 0) {
609        err = "ExpertCache: n_slots must be positive";
610        return false;
611    }
612    if (n_layers <= 0 || n_expert <= 0 || blob_bytes <= 0) {
613        err = "ExpertCache: n_layers, n_expert and blob_bytes must all be positive";
614        return false;
615    }
616
617    const uint64_t want = (uint64_t) n_slots * (uint64_t) blob_bytes;
618
619    // ---- **THE ALLOCATION IS CHECKED AGAINST THE CARD, NOT AGAINST THE REQUEST.**
620    //
621    // `cudaMalloc` failing is the easy case. The one that matters is a machine where the weights already own
622    // most of VRAM: the cache then takes what is left and `slots()` would report the number ASKED FOR while
623    // `device_slot()` walks off the end. So the free-VRAM figure is read and compared BEFORE the allocation,
624    // and the two numbers are named in the refusal.
625    size_t free_b = 0, total_b = 0;
626    if (cudaMemGetInfo(&free_b, &total_b) == cudaSuccess) {
627        free_b = device_free_bytes();   // unified memory: what the OS can give back counts (see the header)
628        if ((uint64_t) free_b < want) {
629            char buf[320];
630            std::snprintf(buf, sizeof buf,
631                          "ExpertCache: %lld slots x %lld B = %.2f GiB, but only %.2f GiB of VRAM is free "
632                          "(%.2f GiB of %.2f GiB total). Lower --expert-cache.",
633                          (long long) n_slots, (long long) blob_bytes, (double) want / 1073741824.0,
634                          (double) free_b / 1073741824.0, (double) (total_b - free_b) / 1073741824.0,
635                          (double) total_b / 1073741824.0);
636            err = buf;
637            return false;
638        }
639    }
640
641#if !defined(STRATA_EC_NO_VMM)
642    if (seg_req_ > 0 && !segmented_supported()) {   // a driver without them: one block, the engine starts all the same
643        std::fprintf(stderr, "ExpertCache: --vram-elastic is off: the driver or this GPU offers no virtual memory management; "
644                             "the cache is one block\n");
645        seg_req_ = 0;
646    }
647#endif
648    if (seg_req_ > 0) {   // #533: --vram-elastic: physical segments behind one address range (zeroed below)
649        if (!open_segmented(want, err)) return false;
650    } else if (g_cache_vmm && vmm_available() && [] { int d = 0; return cudaGetDevice(&d) == cudaSuccess && d == 0; }()) {
651        // (only CUDA0's: the elastic K/V takes chunks of the main cache; a helper card's cache is one allocation)
652        // the elastic K/V: every chunk mapped now; the K/V may later take some of them (and give them back)
653        auto r = std::make_unique<VmmRange>();
654        if (!r->reserve(want) || !r->map_range(0, r->chunks(), [] { return (VmmChunk) 0; })) {
655            char buf[256];
656            std::snprintf(buf, sizeof buf, "ExpertCache: mapping %.2f GiB of VRAM failed: out of memory",
657                          (double) want / 1073741824.0);
658            err = buf;
659            return false;
660        }
661        base_ = r->base();
662        vmm_ = std::move(r);
663    } else if (cudaMalloc((void**) &base_, (size_t) want) != cudaSuccess) {
664        base_ = nullptr;
665        char buf[256];
666        std::snprintf(buf, sizeof buf, "ExpertCache: cudaMalloc(%.2f GiB) failed: %s",
667                      (double) want / 1073741824.0, cudaGetErrorString(cudaGetLastError()));
668        err = buf;
669        return false;
670    }
671    // Zeroed so a slot read before it is filled is a DETERMINISTIC wrong answer rather than whatever the
672    // allocator handed back.  A stale block of a previous process's memory would still sum to finite floats.
673    if (cudaMemset(base_, 0, (size_t) want) != cudaSuccess) {
674        err = "ExpertCache: cudaMemset of the slot arena failed";
675        close();
676        return false;
677    }
678
679    residency_.assign((size_t) (n_layers * n_expert), kNotResident);
680    slots_ = n_slots;
681    live_slots_ = n_slots;
682    n_layers_ = n_layers;
683    n_expert_ = n_expert;
684    blob_ = blob_bytes;
685#if defined(STRATA_USE_HIP)
686    if (!ensure_blocking_staging((std::size_t) blob_, err)) {
687        close();
688        return false;
689    }
690#endif
691    next_free_ = 0;
692    fills_ = 0;
693    admitted_ = 0;
694    // R4.2g: each layer starts at the bottom of its own range.  Built here rather than lazily so `admit`
695    // stays allocation-free on the token path.
696    layer_next_.assign((size_t) (n_layers > 0 ? n_layers : 0), 0);
697    for (int64_t l = 0; l < n_layers; ++l) {
698        int64_t lo = 0, hi = 0;
699        layer_slot_range(l, lo, hi);
700        layer_next_[(size_t) l] = (int32_t) lo;
701    }
702    return true;
703}
704
705bool ExpertCache::open_sized(const std::vector<int64_t>& slot_bytes, int64_t n_layers, int64_t n_expert,
706                             std::string& err) {
707    if (slot_bytes.empty()) { err = "ExpertCache: no slots"; return false; }
708    int64_t mx = 0;
709    std::vector<uint64_t> off(slot_bytes.size() + 1, 0);
710    for (size_t i = 0; i < slot_bytes.size(); ++i) {
711        // 256-byte aligned slots, so every blob starts where the kernels' vector loads expect it (and the
712        // STRATA_MMQ_DIRECT guard after each blob, 0 by default)
713        off[i + 1] = off[i] + (uint64_t) slot_stride(slot_bytes[i], guard_req_);
714        mx = slot_bytes[i] > mx ? slot_bytes[i] : mx;
715    }
716    // one allocation of the summed size, through the uniform path's checks: n "slots" of 1 byte
717    if (!open((int64_t) off.back(), n_layers, n_expert, 1, err)) return false;
718    slots_ = (int64_t) slot_bytes.size();
719    live_slots_ = slots_;
720    blob_ = mx;
721    off_ = std::move(off);
722    guard_ = guard_req_;
723#if defined(STRATA_USE_HIP)
724    if (!ensure_blocking_staging((std::size_t) blob_, err)) {
725        close();
726        return false;
727    }
728#endif
729    // #369: each layer's cursor at the bottom of its own range, as open() seeds it - open() above ran on byte-sized
730    // "slots", so its seeds are not slot indices
731    layer_next_.assign((size_t) (n_layers > 0 ? n_layers : 0), 0);
732    for (int64_t l = 0; l < n_layers; ++l) {
733        int64_t lo = 0, hi = 0;
734        layer_slot_range(l, lo, hi);
735        layer_next_[(size_t) l] = (int32_t) lo;
736    }
737    return true;
738}
739
740void ExpertCache::close() {
741#if defined(STRATA_USE_HIP)
742    if (blocking_staging_) (void) cudaFreeHost(blocking_staging_);
743    blocking_staging_ = nullptr;
744    blocking_staging_bytes_ = 0;
745#endif
746    off_.clear();
747    guard_ = 0;
748    if (!segs_.empty()) {
749        release_segmented();
750    } else if (vmm_) {
751        vmm_.reset();   // unmaps and frees every chunk it still holds
752        base_ = nullptr;
753    } else if (base_ != nullptr) {
754        cudaFree(base_);
755        base_ = nullptr;
756    }
757    residency_.clear();
758    slots_ = 0;
759    live_slots_ = 0;
760    n_layers_ = 0;
761    n_expert_ = 0;
762    blob_ = 0;
763    next_free_ = 0;
764    fills_ = 0;
765    admitted_ = 0;
766    sealed_ = false;
767    layer_next_.clear();
768}
769
770/// R4.2g.  Layer `l` owns `[l*q, (l+1)*q)` with `q = slots_ / n_layers_`; the LAST layer takes whatever is
771/// left over, so the ranges always cover `0..slots_` exactly and no slot is orphaned by the division.
772void ExpertCache::layer_slot_range(int64_t layer, int64_t& lo, int64_t& hi) const {
773    lo = 0;
774    hi = 0;
775    if (n_layers_ <= 0 || slots_ <= 0 || layer < 0 || layer >= n_layers_) return;
776    const int64_t q = slots_ / n_layers_;
777    lo = layer * q;
778    hi = (layer == n_layers_ - 1) ? slots_ : (layer + 1) * q;
779}
780
781int32_t ExpertCache::slot_of(int64_t layer, int64_t expert) const {
782    if (layer < 0 || layer >= n_layers_ || expert < 0 || expert >= n_expert_) return kNotResident;
783    return residency_[(size_t) (layer * n_expert_ + expert)];
784}
785
786int32_t ExpertCache::admit(int64_t layer, int64_t expert) {
787    if (sealed_) return kNotResident;   // STRATA_EXPERT_NIBBLE: nothing is admitted (and so filled) after the startup fill
788    if (layer < 0 || layer >= n_layers_ || expert < 0 || expert >= n_expert_) return kNotResident;
789    const size_t at = (size_t) (layer * n_expert_ + expert);
790    if (residency_[at] != kNotResident) return residency_[at];
791    // R4.2g: THE PER-LAYER PATH.  Same "no eviction" rule, but the ceiling is this layer's own range rather
792    // than one counter shared by all 48 - which is what confined the measured hit rate to 2.97%.
793    if (per_layer_) {
794        if (layer_next_.empty()) return kNotResident;
795        int64_t lo = 0, hi = 0;
796        layer_slot_range(layer, lo, hi);
797        if ((int64_t) layer_next_[(size_t) layer] >= hi) return kNotResident;   // this layer's quota is full
798        residency_[at] = layer_next_[(size_t) layer]++;
799        ++admitted_;
800        return residency_[at];
801    }
802    if (next_free_ >= slots_) return kNotResident;   // full: no eviction, deliberately - see the header
803    residency_[at] = (int32_t) next_free_;
804    return (int32_t) next_free_++;
805}
806
807uint8_t* ExpertCache::device_slot(int32_t slot) {
808    if (slot < 0 || slot >= slots_) return nullptr;
809    if (!off_.empty()) return base_ + off_[(size_t) slot];
810    return base_ + (size_t) slot * (size_t) blob_;
811}
812
813const uint8_t* ExpertCache::device_slot(int32_t slot) const {
814    if (slot < 0 || slot >= slots_) return nullptr;
815    if (!off_.empty()) return base_ + off_[(size_t) slot];
816    return base_ + (size_t) slot * (size_t) blob_;
817}
818
819bool ExpertCache::fill_slot(int32_t slot, const uint8_t* host_blob, void* stream, std::string& err, int64_t bytes) {
820    if (sealed_) sealed_write("fill_slot", slot);
821    const size_t n = (size_t) (bytes > 0 && bytes <= blob_ ? bytes : blob_);
822    uint8_t* dst = device_slot(slot);
823    if (dst == nullptr) {
824        err = "ExpertCache::fill_slot: slot " + std::to_string(slot) + " is outside 0.." +
825              std::to_string(slots_ - 1);
826        return false;
827    }
828    if (host_blob == nullptr) {
829        err = "ExpertCache::fill_slot: the host blob is null";
830        return false;
831    }
832    const cudaError_t e = cudaMemcpyAsync(dst, host_blob, n, cudaMemcpyHostToDevice,
833                                          (cudaStream_t) stream);
834    if (e != cudaSuccess) {
835        err = std::string("ExpertCache::fill_slot: ") + cudaGetErrorString(e);
836        return false;
837    }
838    ++fills_;
839    return true;
840}
841
842bool ExpertCache::fill_slot_blocking(int32_t slot, const uint8_t* host_blob, std::string& err, int64_t bytes) {
843    if (sealed_) sealed_write("fill_slot_blocking", slot);
844    const size_t n = (size_t) (bytes > 0 && bytes <= blob_ ? bytes : blob_);
845    uint8_t* dst = device_slot(slot);
846    if (dst == nullptr) {
847        err = "ExpertCache::fill_slot_blocking: slot outside the arena";
848        return false;
849    }
850    if (host_blob == nullptr) {
851        err = "ExpertCache::fill_slot_blocking: the host blob is null";
852        return false;
853    }
854#if defined(STRATA_USE_HIP)
855    // Bound HIP's pageable-source staging to one expert instead of repeatedly
856    // registering regions of the mmap. The blocking copy completes before reuse.
857    if (!blocking_staging_ || n > blocking_staging_bytes_) {
858        err = "ExpertCache::fill_slot_blocking: HIP staging buffer is too small";
859        return false;
860    }
861    std::memcpy(blocking_staging_, host_blob, n);
862    const cudaError_t e = cudaMemcpy(dst, blocking_staging_, n, cudaMemcpyHostToDevice);
863#else
864    const cudaError_t e = cudaMemcpy(dst, host_blob, n, cudaMemcpyHostToDevice);
865#endif
866    if (e != cudaSuccess) {
867        err = std::string("ExpertCache::fill_slot_blocking: ") + cudaGetErrorString(e);
868        return false;
869    }
870    ++fills_;
871    return true;
872}
873
874bool ExpertCache::fill_slot_queued(int32_t slot, const uint8_t* host_blob, std::string& err, int64_t bytes) {
875    if (sealed_) sealed_write("fill_slot_queued", slot);
876    const size_t n = (size_t) (bytes > 0 && bytes <= blob_ ? bytes : blob_);
877    uint8_t* dst = device_slot(slot);
878    if (dst == nullptr || host_blob == nullptr) {
879        err = dst == nullptr ? "ExpertCache::fill_slot_queued: slot outside the arena"
880                             : "ExpertCache::fill_slot_queued: the host blob is null";
881        return false;
882    }
883    const cudaError_t e = cudaMemcpyAsync(dst, host_blob, n, cudaMemcpyHostToDevice, (cudaStream_t) 0);
884    if (e != cudaSuccess) {
885        err = std::string("ExpertCache::fill_slot_queued: ") + cudaGetErrorString(e);
886        return false;
887    }
888    ++fills_;
889    return true;
890}
891
892bool ExpertCache::fill_slot_queued_parts(int32_t slot, const BlobPart* parts, int n, std::string& err) {
893    if (sealed_) sealed_write("fill_slot_queued_parts", slot);
894    uint8_t* dst = device_slot(slot);
895    if (dst == nullptr || parts == nullptr || n <= 0) {
896        err = "ExpertCache::fill_slot_queued_parts: slot outside the arena or no pieces";
897        return false;
898    }
899    uint64_t total = 0;
900    for (int i = 0; i < n; ++i) total += parts[i].n;
901    if (total > (uint64_t) blob_) {
902        err = "ExpertCache::fill_slot_queued_parts: the pieces are larger than a slot";
903        return false;
904    }
905    for (int i = 0; i < n; ++i) {
906        const cudaError_t e = cudaMemcpyAsync(dst + parts[i].at, parts[i].p, (size_t) parts[i].n, cudaMemcpyHostToDevice,
907                                              (cudaStream_t) 0);
908        if (e != cudaSuccess) {
909            err = std::string("ExpertCache::fill_slot_queued_parts: ") + cudaGetErrorString(e);
910            return false;
911        }
912    }
913    ++fills_;
914    return true;
915}
916
917bool ExpertCache::sync_queued(std::string& err) {
918    const cudaError_t e = cudaStreamSynchronize((cudaStream_t) 0);
919    if (e != cudaSuccess) {
920        err = std::string("ExpertCache::sync_queued: ") + cudaGetErrorString(e);
921        return false;
922    }
923    return true;
924}
925
926bool ExpertCache::verify_slot(int32_t slot, const uint8_t* host_blob, std::string& err, int64_t bytes) {
927    const int64_t nb = bytes > 0 && bytes <= blob_ ? bytes : blob_;
928    const uint8_t* src = device_slot(slot);
929    if (src == nullptr) {
930        err = "ExpertCache::verify_slot: slot outside the arena";
931        return false;
932    }
933    // `cudaMemcpy` and not `cudaMemcpyAsync`: this is a startup check, and a check that can be read before it
934    // has happened is not a check.  It also synchronises the fills queued before it, which is what makes the
935    // comparison meaningful.
936    std::vector<uint8_t> got((size_t) nb);
937    const cudaError_t e = cudaMemcpy(got.data(), src, (size_t) nb, cudaMemcpyDeviceToHost);
938    if (e != cudaSuccess) {
939        err = std::string("ExpertCache::verify_slot: ") + cudaGetErrorString(e);
940        return false;
941    }
942    if (std::memcmp(got.data(), host_blob, (size_t) nb) != 0) {
943        size_t first = 0;
944        while (first < (size_t) nb && got[first] == host_blob[first]) ++first;
945        char buf[256];
946        std::snprintf(buf, sizeof buf,
947                      "ExpertCache::verify_slot: slot %d differs from the arena at byte %llu (of %lld)",
948                      (int) slot, (unsigned long long) first, (long long) blob_);
949        err = buf;
950        return false;
951    }
952    return true;
953}
954
955}  // namespace strata::core