mirror of
https://github.com/Niko1221/Strata.git
synced 2026-12-04 07:18:50 +00:00
Guard (strata/platform/vram_guard.hpp, src/platform/vram_guard.cpp, vram_guard_driver.hpp): tells the runner the headroom of one card and, with hysteresis (low < target < high, dwell, quiet time after pressure, step cap), when to shed experts (Shed N) and when it may take them back (MayReclaim N). poll() is one clock read until the period has passed; spare_for_growth() samples once per call. Windows: the adapter of the device's LUID through dxgi.dll and the adapter-wide "GPU Adapter Memory" counters through pdh.dll (both loaded at run time, no link dependency); on WDDM the driver free and the DXGI budget are the process's own view and do not follow other programs, the adapter counters do. Linux and TCC: the driver query. Integrated GPUs on shared memory leave the guard off. Linked into strata_inkling_core. Tests: vram_guard_test (CTest, no GPU), vram_guard_live (real card, a second process allocating in steps). Launcher fit (terminal/strata_control/inkling_fit.py): an engine that reports "elastic_experts": true in its BUILD.json is planned with the elastic pool (K/V grows in the experts' pool down to STRATA_INK_ELASTIC_MIN_EXP_MIB, 1536 MiB; no host K/V; how much of the pool the context lent). Any other engine is planned as before; 128K stays the default context.
322 lines
16 KiB
C++
322 lines
16 KiB
C++
// vram_guard_live: the real-card test of strata/platform/vram_guard.hpp on Windows (WDDM). Not part of CTest: it needs an NVIDIA card.
|
|
// MIT, Copyright (c) 2026 Niko1221 and the Strata contributors.
|
|
//
|
|
// Two modes, two processes (the second plays "another program that takes VRAM", the first plays the runner):
|
|
// vram_guard_live watch --pool-mib 1024 --chunk-mib 64 --secs 40 --low-below-mib 600 --target-below-mib 450 --high-below-mib 300 --log watch.csv
|
|
// takes a pool of cuMemAlloc blocks (the "experts"), runs the guard in a 50 ms loop and OBEYS its advice: Shed = frees blocks,
|
|
// MayReclaim = takes back what it shed. The watermarks are set relative to the headroom measured after the pool is taken
|
|
// (headroom0 - N), so the test never needs the whole card. One CSV row per tick.
|
|
// vram_guard_live hog --step-mib 128 --max-mib 800 --interval-ms 1000 --start-delay-ms 6000 --hold-ms 10000 --min-free-mib 2048 --log hog.csv
|
|
// allocates in steps, holds, frees in steps. Refuses a step that would leave less than --min-free-mib free on the card.
|
|
// The CUDA driver (nvcuda.dll) is loaded at run time: no toolkit, no import library. Build (MSVC):
|
|
// cl /nologo /std:c++17 /O2 /EHsc /W4 /I engine\include engine\tests\platform\vram_guard_live.cpp engine\src\platform\vram_guard.cpp /Fe:vram_guard_live.exe
|
|
#include "strata/platform/vram_guard.hpp"
|
|
|
|
#include <chrono>
|
|
#include <cstdio>
|
|
#include <cstdlib>
|
|
#include <cstring>
|
|
#include <string>
|
|
#include <vector>
|
|
|
|
#if !defined(_WIN32)
|
|
int main() { std::printf("vram_guard_live: Windows only\n"); return 77; }
|
|
#else
|
|
#ifndef WIN32_LEAN_AND_MEAN
|
|
#define WIN32_LEAN_AND_MEAN
|
|
#endif
|
|
#ifndef NOMINMAX
|
|
#define NOMINMAX
|
|
#endif
|
|
#include <windows.h>
|
|
|
|
using namespace strata::platform;
|
|
|
|
namespace {
|
|
|
|
const uint64_t MiB = 1ull << 20;
|
|
|
|
// --- the CUDA driver API, by name (types as in cuda.h: CUdevice int, CUcontext void*, CUdeviceptr unsigned long long)
|
|
struct Cu {
|
|
HMODULE mod = nullptr;
|
|
int (*cuInit)(unsigned) = nullptr;
|
|
int (*cuDeviceGet)(int*, int) = nullptr;
|
|
int (*cuDeviceGetLuid)(char*, unsigned*, int) = nullptr;
|
|
int (*cuCtxCreate)(void**, unsigned, int) = nullptr;
|
|
int (*cuCtxSetCurrent)(void*) = nullptr;
|
|
int (*cuMemGetInfo)(size_t*, size_t*) = nullptr;
|
|
int (*cuMemAlloc)(unsigned long long*, size_t) = nullptr;
|
|
int (*cuMemFree)(unsigned long long) = nullptr;
|
|
int (*cuMemsetD8)(unsigned long long, unsigned char, size_t) = nullptr;
|
|
int (*cuCtxSynchronize)() = nullptr;
|
|
void* ctx = nullptr;
|
|
int dev = 0;
|
|
char luid[8] = {0};
|
|
bool has_luid = false;
|
|
bool load() {
|
|
mod = LoadLibraryExW(L"nvcuda.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32);
|
|
if (!mod) return false;
|
|
#define CUF(n, sym) n = reinterpret_cast<decltype(n)>(reinterpret_cast<void*>(GetProcAddress(mod, sym)))
|
|
CUF(cuInit, "cuInit"); CUF(cuDeviceGet, "cuDeviceGet"); CUF(cuDeviceGetLuid, "cuDeviceGetLuid");
|
|
CUF(cuCtxCreate, "cuCtxCreate_v2"); CUF(cuCtxSetCurrent, "cuCtxSetCurrent"); CUF(cuMemGetInfo, "cuMemGetInfo_v2");
|
|
CUF(cuMemAlloc, "cuMemAlloc_v2"); CUF(cuMemFree, "cuMemFree_v2"); CUF(cuMemsetD8, "cuMemsetD8_v2");
|
|
CUF(cuCtxSynchronize, "cuCtxSynchronize");
|
|
#undef CUF
|
|
return cuInit && cuDeviceGet && cuCtxCreate && cuMemGetInfo && cuMemAlloc && cuMemFree && cuMemsetD8 && cuCtxSynchronize;
|
|
}
|
|
bool open(int ordinal) {
|
|
if (!load() || cuInit(0) != 0 || cuDeviceGet(&dev, ordinal) != 0) return false;
|
|
unsigned mask = 0;
|
|
has_luid = cuDeviceGetLuid && cuDeviceGetLuid(luid, &mask, dev) == 0;
|
|
return cuCtxCreate(&ctx, 0, dev) == 0;
|
|
}
|
|
};
|
|
Cu g_cu;
|
|
|
|
bool cu_mem(void*, size_t* f, size_t* t) { return g_cu.cuMemGetInfo(f, t) == 0; }
|
|
|
|
// NVML (nvml.dll, by name): the adapter-wide used / free memory, what nvidia-smi shows. cuMemGetInfo on WDDM is the process's own view.
|
|
struct NvmlMem { unsigned long long total, free, used; };
|
|
struct Nvml {
|
|
HMODULE mod = nullptr;
|
|
int (*init)() = nullptr;
|
|
int (*byIndex)(unsigned, void**) = nullptr;
|
|
int (*memInfo)(void*, NvmlMem*) = nullptr;
|
|
void* h = nullptr;
|
|
bool open() {
|
|
mod = LoadLibraryExW(L"nvml.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32);
|
|
if (!mod) return false;
|
|
init = reinterpret_cast<decltype(init)>(reinterpret_cast<void*>(GetProcAddress(mod, "nvmlInit_v2")));
|
|
byIndex = reinterpret_cast<decltype(byIndex)>(reinterpret_cast<void*>(GetProcAddress(mod, "nvmlDeviceGetHandleByIndex_v2")));
|
|
memInfo = reinterpret_cast<decltype(memInfo)>(reinterpret_cast<void*>(GetProcAddress(mod, "nvmlDeviceGetMemoryInfo")));
|
|
return init && byIndex && memInfo && init() == 0 && byIndex(0, &h) == 0;
|
|
}
|
|
};
|
|
Nvml g_nvml;
|
|
bool nvml_mem(void*, size_t* f, size_t* t) {
|
|
NvmlMem m{};
|
|
if (!g_nvml.h || g_nvml.memInfo(g_nvml.h, &m) != 0) return false;
|
|
*f = static_cast<size_t>(m.free);
|
|
*t = static_cast<size_t>(m.total);
|
|
return true;
|
|
}
|
|
unsigned long long nvml_free_mib() {
|
|
size_t f = 0, t = 0;
|
|
return nvml_mem(nullptr, &f, &t) ? static_cast<unsigned long long>(f / MiB) : 0ull;
|
|
}
|
|
|
|
double wall_ms() { // UTC milliseconds, to line the two processes' logs up
|
|
FILETIME ft;
|
|
GetSystemTimePreciseAsFileTime(&ft);
|
|
const unsigned long long t = (static_cast<unsigned long long>(ft.dwHighDateTime) << 32) | ft.dwLowDateTime;
|
|
return static_cast<double>(t) / 10000.0;
|
|
}
|
|
double mono_ms() {
|
|
return std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now().time_since_epoch()).count();
|
|
}
|
|
|
|
struct Args {
|
|
std::vector<std::string> v;
|
|
long num(const char* k, long d) const {
|
|
for (size_t i = 0; i + 1 < v.size(); ++i) if (v[i] == k) return std::strtol(v[i + 1].c_str(), nullptr, 10);
|
|
return d;
|
|
}
|
|
std::string str(const char* k, const char* d) const {
|
|
for (size_t i = 0; i + 1 < v.size(); ++i) if (v[i] == k) return v[i + 1];
|
|
return d;
|
|
}
|
|
};
|
|
|
|
int run_hog(const Args& a) {
|
|
if (!g_cu.open(0)) { std::printf("hog: no CUDA driver\n"); return 2; }
|
|
const uint64_t step = static_cast<uint64_t>(a.num("--step-mib", 128)) * MiB;
|
|
const uint64_t maxb = static_cast<uint64_t>(a.num("--max-mib", 800)) * MiB;
|
|
const uint64_t min_free = static_cast<uint64_t>(a.num("--min-free-mib", 2048)) * MiB;
|
|
const long interval = a.num("--interval-ms", 1000), delay = a.num("--start-delay-ms", 6000), hold = a.num("--hold-ms", 10000);
|
|
FILE* lg = std::fopen(a.str("--log", "hog.csv").c_str(), "w");
|
|
if (!lg) return 3;
|
|
g_nvml.open();
|
|
std::fprintf(lg, "wall_ms,event,hog_mib,free_mib,nvml_free_mib\n");
|
|
std::vector<unsigned long long> blocks;
|
|
auto row = [&](const char* ev) {
|
|
size_t f = 0, t = 0;
|
|
g_cu.cuMemGetInfo(&f, &t);
|
|
std::fprintf(lg, "%.1f,%s,%llu,%llu,%llu\n", wall_ms(), ev, static_cast<unsigned long long>(blocks.size() * step / MiB),
|
|
static_cast<unsigned long long>(f / MiB), nvml_free_mib());
|
|
std::fflush(lg);
|
|
};
|
|
row("start");
|
|
Sleep(static_cast<DWORD>(delay));
|
|
while (blocks.size() * step < maxb) {
|
|
size_t f = 0, t = 0;
|
|
g_cu.cuMemGetInfo(&f, &t);
|
|
const uint64_t true_free = g_nvml.h ? static_cast<uint64_t>(nvml_free_mib()) * MiB : f; // adapter-wide when NVML is there
|
|
if (true_free < min_free + step) { row("refused_low_free"); break; }
|
|
unsigned long long p = 0;
|
|
if (g_cu.cuMemAlloc(&p, step) != 0) { row("alloc_failed"); break; }
|
|
g_cu.cuMemsetD8(p, 0x5A, step);
|
|
g_cu.cuCtxSynchronize();
|
|
blocks.push_back(p);
|
|
row("alloc");
|
|
Sleep(static_cast<DWORD>(interval));
|
|
}
|
|
row("hold");
|
|
Sleep(static_cast<DWORD>(hold));
|
|
while (!blocks.empty()) {
|
|
g_cu.cuMemFree(blocks.back());
|
|
blocks.pop_back();
|
|
row("free");
|
|
Sleep(static_cast<DWORD>(interval));
|
|
}
|
|
row("done");
|
|
std::fclose(lg);
|
|
return 0;
|
|
}
|
|
|
|
int run_watch(const Args& a) {
|
|
if (!g_cu.open(0)) { std::printf("watch: no CUDA driver\n"); return 2; }
|
|
const uint64_t chunk = static_cast<uint64_t>(a.num("--chunk-mib", 64)) * MiB;
|
|
const uint64_t pool0 = static_cast<uint64_t>(a.num("--pool-mib", 1024)) * MiB;
|
|
const long secs = a.num("--secs", 40);
|
|
FILE* lg = std::fopen(a.str("--log", "watch.csv").c_str(), "w");
|
|
if (!lg) return 3;
|
|
|
|
// the "experts": blocks the runner holds and can give back
|
|
std::vector<unsigned long long> pool;
|
|
for (uint64_t got = 0; got < pool0; got += chunk) {
|
|
unsigned long long p = 0;
|
|
if (g_cu.cuMemAlloc(&p, chunk) != 0) break;
|
|
g_cu.cuMemsetD8(p, 0x33, chunk);
|
|
pool.push_back(p);
|
|
}
|
|
g_cu.cuCtxSynchronize();
|
|
const size_t pool_n0 = pool.size();
|
|
|
|
// the cost of one sample, driver + DXGI, and DXGI alone
|
|
VramGuardConfig base;
|
|
base.device = 0;
|
|
base.has_luid = g_cu.has_luid;
|
|
std::memcpy(base.luid, g_cu.luid, 8);
|
|
base.read_env = false;
|
|
base.chunk_bytes = chunk;
|
|
VramGuardConfig probe = base;
|
|
g_nvml.open();
|
|
const bool use_nvml = a.str("--driver", "cuda") == "nvml" && g_nvml.h != nullptr; // adapter-wide free instead of the process's own view
|
|
probe.driver_mem = use_nvml ? &nvml_mem : &cu_mem;
|
|
std::printf("watch: driver query = %s\n", use_nvml ? "NVML (adapter-wide)" : "cuMemGetInfo");
|
|
VramGuard cost;
|
|
const bool ok0 = cost.init(probe);
|
|
std::printf("watch: guard init=%d status=\"%s\" luid=%d\n", ok0 ? 1 : 0, cost.status(), g_cu.has_luid ? 1 : 0);
|
|
double us_both = 0, us_dxgi = 0;
|
|
{
|
|
const int N = 2000;
|
|
double t0 = mono_ms();
|
|
for (int i = 0; i < N; ++i) cost.sample();
|
|
us_both = (mono_ms() - t0) * 1000.0 / N;
|
|
VramGuardConfig dx = base; // no driver query, no counters: DXGI alone
|
|
dx.use_adapter_counters = false;
|
|
VramGuard gd;
|
|
if (gd.init(dx)) {
|
|
t0 = mono_ms();
|
|
for (int i = 0; i < N; ++i) gd.sample();
|
|
us_dxgi = (mono_ms() - t0) * 1000.0 / N;
|
|
}
|
|
VramGuardConfig dc = probe; // driver + dxgi, no counters
|
|
dc.use_adapter_counters = false;
|
|
VramGuard gc;
|
|
double us_nc = 0;
|
|
if (gc.init(dc)) {
|
|
t0 = mono_ms();
|
|
for (int i = 0; i < N; ++i) gc.sample();
|
|
us_nc = (mono_ms() - t0) * 1000.0 / N;
|
|
}
|
|
std::printf("watch: sample cost: all sources %.1f us, driver+dxgi %.1f us, dxgi only %.1f us\n", us_both, us_nc, us_dxgi);
|
|
}
|
|
const VramSnapshot s0 = cost.sample();
|
|
std::printf("watch: adapter counters: used %llu of %llu MiB (nvml free %llu MiB)\n", static_cast<unsigned long long>(s0.adapter_used / MiB),
|
|
static_cast<unsigned long long>(s0.adapter_total / MiB), nvml_free_mib());
|
|
std::printf("watch: pool %zu x %llu MiB; driver free %llu total %llu MiB; dxgi budget %llu usage %llu MiB; headroom %llu MiB (source %d)\n",
|
|
pool_n0, static_cast<unsigned long long>(chunk / MiB), static_cast<unsigned long long>(s0.driver_free / MiB),
|
|
static_cast<unsigned long long>(s0.driver_total / MiB), static_cast<unsigned long long>(s0.dxgi_budget / MiB),
|
|
static_cast<unsigned long long>(s0.dxgi_usage / MiB), static_cast<unsigned long long>(s0.headroom_bytes / MiB), s0.source);
|
|
cost.shutdown();
|
|
|
|
// the real guard, watermarks relative to the headroom now
|
|
const long lo_b = a.num("--low-below-mib", 600), tg_b = a.num("--target-below-mib", 450), hi_b = a.num("--high-below-mib", 300);
|
|
const long h0 = static_cast<long>(s0.headroom_bytes / MiB);
|
|
VramGuardConfig cfg = probe;
|
|
cfg.low_mib = static_cast<uint64_t>(std::max(64L, h0 - lo_b));
|
|
cfg.target_mib = static_cast<uint64_t>(std::max(65L, h0 - tg_b));
|
|
cfg.high_mib = static_cast<uint64_t>(std::max(66L, h0 - hi_b));
|
|
if (a.num("--low-mib", 0) > 0) { // absolute watermarks (the contention test)
|
|
cfg.low_mib = static_cast<uint64_t>(a.num("--low-mib", 0));
|
|
cfg.target_mib = static_cast<uint64_t>(a.num("--target-mib", 0));
|
|
cfg.high_mib = static_cast<uint64_t>(a.num("--high-mib", 0));
|
|
}
|
|
cfg.reclaim_dwell_ms = static_cast<uint32_t>(a.num("--dwell-ms", 2000));
|
|
cfg.quiet_after_pressure_ms = static_cast<uint32_t>(a.num("--quiet-ms", 3000));
|
|
cfg.max_reclaim_step_mib = static_cast<uint64_t>(a.num("--step-mib", 128));
|
|
VramGuard guard;
|
|
if (!guard.init(cfg)) { std::printf("watch: guard init failed: %s\n", guard.status()); return 4; }
|
|
std::printf("watch: low %llu target %llu high %llu MiB (headroom0 %ld), period %u ms, status \"%s\"\n",
|
|
static_cast<unsigned long long>(guard.low_bytes() / MiB), static_cast<unsigned long long>(guard.target_bytes() / MiB),
|
|
static_cast<unsigned long long>(guard.high_bytes() / MiB), h0, cfg.period_ms, guard.status());
|
|
|
|
std::fprintf(lg, "wall_ms,headroom_mib,driver_free_mib,dxgi_budget_mib,dxgi_usage_mib,sampled,advice,advice_mib,pool_mib,low_mib,target_mib,high_mib,nvml_free_mib,adapter_used_mib,adapter_total_mib\n");
|
|
uint64_t shed_total = 0;
|
|
int sheds = 0, reclaims = 0;
|
|
const double t_end = mono_ms() + secs * 1000.0;
|
|
while (mono_ms() < t_end) {
|
|
const VramSnapshot raw = guard.sample(); // what is true now (50 ms resolution)
|
|
const VramAdvice adv = guard.poll(shed_total); // what the runner's decode loop would see (it can only take back what it shed)
|
|
uint64_t shed = 0, back = 0;
|
|
if (adv.kind == VramAdvice::Shed) {
|
|
for (uint64_t got = 0; got < adv.bytes && !pool.empty(); got += chunk) {
|
|
g_cu.cuMemFree(pool.back());
|
|
pool.pop_back();
|
|
shed += chunk;
|
|
}
|
|
shed_total += shed;
|
|
++sheds;
|
|
} else if (adv.kind == VramAdvice::MayReclaim) {
|
|
for (uint64_t got = 0; got < adv.bytes && got < shed_total; got += chunk) { // only what was shed is taken back
|
|
unsigned long long p = 0;
|
|
if (g_cu.cuMemAlloc(&p, chunk) != 0) break;
|
|
g_cu.cuMemsetD8(p, 0x33, chunk);
|
|
pool.push_back(p);
|
|
back += chunk;
|
|
}
|
|
shed_total -= std::min(shed_total, back);
|
|
if (back) ++reclaims;
|
|
}
|
|
if (shed || back) guard.report_applied(shed, back);
|
|
std::fprintf(lg, "%.1f,%llu,%llu,%llu,%llu,%d,%d,%llu,%llu,%llu,%llu,%llu,%llu,%llu,%llu\n", wall_ms(),
|
|
static_cast<unsigned long long>(raw.headroom_bytes / MiB), static_cast<unsigned long long>(raw.driver_free / MiB),
|
|
static_cast<unsigned long long>(raw.dxgi_budget / MiB), static_cast<unsigned long long>(raw.dxgi_usage / MiB),
|
|
adv.sampled ? 1 : 0, adv.kind, static_cast<unsigned long long>(adv.bytes / MiB),
|
|
static_cast<unsigned long long>(pool.size() * chunk / MiB), static_cast<unsigned long long>(guard.low_bytes() / MiB),
|
|
static_cast<unsigned long long>(guard.target_bytes() / MiB), static_cast<unsigned long long>(guard.high_bytes() / MiB),
|
|
nvml_free_mib(), static_cast<unsigned long long>(raw.adapter_used / MiB),
|
|
static_cast<unsigned long long>(raw.adapter_total / MiB));
|
|
Sleep(50);
|
|
}
|
|
std::fflush(lg);
|
|
std::fclose(lg);
|
|
std::printf("watch: done, %d shed steps, %d reclaim steps, pool %zu -> %zu blocks\n", sheds, reclaims, pool_n0, pool.size());
|
|
for (unsigned long long p : pool) g_cu.cuMemFree(p);
|
|
return 0;
|
|
}
|
|
|
|
} // namespace
|
|
|
|
int main(int argc, char** argv) {
|
|
Args a;
|
|
for (int i = 1; i < argc; ++i) a.v.emplace_back(argv[i]);
|
|
if (a.v.empty()) { std::printf("usage: vram_guard_live watch|hog [options]\n"); return 1; }
|
|
if (a.v[0] == "watch") return run_watch(a);
|
|
if (a.v[0] == "hog") return run_hog(a);
|
|
std::printf("unknown mode\n");
|
|
return 1;
|
|
}
|
|
#endif
|