Files
Strata/include/strata/program/gpu_report.hpp
T
Niko1221 2a9a67c174 Later-card VRAM: audit fixes for failed allocations, the reserve arithmetic as a tested helper, a per-card out-of-memory report (#3638 #3702 #3797)
Problem. On a layer split the later cards are left with very little VRAM after loading (#3702: 68 MiB on the last card; #3638:
268 and 666 MiB, then every batched prompt read of more than ~400 tokens ends non-finite after hours; #3797: the weight arena
fails with 320 MiB free and the message does not say who holds the rest). The window-graph eviction (12b0bce95) and the copy
stream pool (#3350) are in already; this is the rest of the code audit of what is allocated after load.

Audit. The table of every lazy allocation after load (what, when, size, how a failure is handled) is in
phaseA-tests/notes-027-gh-eng-d.md. Bugs found and fixed here, each small:
- verify.cpp capture / capture_batch and mtp.cpp finish_capture: the cudaGraphUpload and its sync were only printed. The
  upload is a warm-up, but a failure (no VRAM) stayed as the thread's pending error and the next kernel wrapper's
  cudaGetLastError ended the engine. The error is now cleared and the first launch uploads the graph.
- verify.cpp capture_commit and mtp.cpp finish_capture: the commit graph called cudaGraphInstantiate directly (no
  eviction of older layouts, unlike the window graphs) and reported the status of the end-of-capture call, which is success,
  so the message read "no error". capture_commit now goes through instantiate_evicting and reports the instantiate's status.
- instantiate_evicting instantiates into a local and sets the member only on success (what a failed instantiate leaves in
  its output is not specified, and a non-null member means "captured").
- prefill.cpp carve: after a failed take of the shared region the sub-allocators had no base and each cudaMalloc'd its
  buffer (hundreds of MiB in all) on the card that had just run out. carve now returns at once; the caller reports the
  failure as before.
- generate.cpp: a failed set_stage_helper / set_peer is reported and the run goes on, but its CUDA error stayed pending;
  cleared.
Found and not changed: relend() re-plans only the first participant (#3638 comment). Read: it runs only from the VRAM
command, which is off on a layer split, so it cannot touch a later stage's loan. Other candidates (ignored cudaEventCreate for
the pipelined fences, unchecked expert copies, cudaFuncSetAttribute flags set before success) are in the notes.

Changes for the report of #3797 and the reserve (#3702).
- include/strata/program/gpu_report.hpp: on a failed weight-arena allocation (first card and each stage) the engine now
  also prints, for every card of the run, the free and total memory and the largest other programs that hold memory on it
  (NVML, loaded at run time; where the driver does not list them it says so). Text only; the failure is the same.
  tests/program/gpu_report_test.cpp pins the text.
- include/strata/program/stage_reserve.hpp: the arithmetic of stage_room (what the split keeps free on a card) moved out of
  generate.cpp unchanged; tests/program/stage_reserve_test.cpp compares it with the old expression over a grid. The file
  also holds a PROPOSAL for a larger window term on a later card (96 MiB + 6 MiB per further window size + 48 MiB, 174 MiB
  for --spec 4) which nothing calls: the default placement is not changed. gates/3702-later-reserve.sh measures it.
- The low-VRAM warning of a later card now adds how many MiB the plan meant to keep free there and how far off that was.

Tests: gpu_report_test, stage_reserve_test (host only, built on z440).
Not covered: no model was run. What the ~700 MiB the plan does not count on the last card is (window graph sets, kernel code
loads) needs the run in gates/3702-later-reserve.sh.
2026-10-27 02:02:46 +01:00

218 lines
9.7 KiB
C++

// include/strata/program/gpu_report.hpp - #3797: what to tell the user when a GPU allocation at start fails.
//
// "cudaMalloc(818947840) for the weight arena failed: 320 MiB of 21998 MiB free" says that the card is full, not by
// whom. The usual answer is another program (or an engine that is still exiting), so the report names, per card, the
// memory that is free and the largest other processes that hold some. The text is a warning added to the message that
// was already there; nothing about the failure changes.
//
// `format_gpu_memory_report` is a pure function (tests/program/gpu_report_test.cpp). `query_other_processes` asks
// the NVIDIA driver library (NVML, loaded at run time: no link-time dependency, so a build without it, an AMD card,
// a missing driver library or a failed call just returns false and the report leaves the process list out). It
// never throws and never ends the process.
#pragma once
#include <algorithm>
#include <cstdint>
#include <cstdio>
#include <string>
#include <vector>
#if defined(_WIN32)
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include <windows.h>
#else
#include <dlfcn.h>
#endif
namespace strata::program::gpu_report {
struct Process {
uint32_t pid = 0;
std::string name; ///< the program's file name; empty when the system would not say
uint64_t used_mib = 0; ///< 0 = the driver does not report it (Windows WDDM does not for most programs)
};
struct Card {
int index = 0; ///< the CUDA device number
std::string name; ///< "NVIDIA GeForce RTX 2080 Ti"; may be empty
uint64_t free_mib = 0;
uint64_t total_mib = 0;
bool processes_known = false; ///< the driver answered the process query (the list may still be empty)
std::vector<Process> processes; ///< every process that holds memory on this card, in any order
};
namespace detail {
inline std::string size_text(uint64_t mib) {
char b[48];
if (mib >= 10240) std::snprintf(b, sizeof b, "%.1f GiB", (double) mib / 1024.0);
else std::snprintf(b, sizeof b, "%llu MiB", (unsigned long long) mib);
return b;
}
inline std::string base_name(const std::string& path) {
const size_t cut = path.find_last_of("/\\");
return cut == std::string::npos ? path : path.substr(cut + 1);
}
} // namespace detail
/// One line per card: the free and total memory and, when the driver listed them, the largest other processes
/// (`self_pid` and any process of 0 MiB that the driver does list are left out of "largest"; at most `max_procs`
/// are named). Ends with no newline. `cards` empty: an empty string.
inline std::string format_gpu_memory_report(const std::vector<Card>& cards, uint32_t self_pid, size_t max_procs = 3) {
std::string out;
for (const Card& c : cards) {
if (!out.empty()) out += "\n";
out += "strata generate: CUDA" + std::to_string(c.index);
if (!c.name.empty()) out += " (" + c.name + ")";
out += ": " + std::to_string((unsigned long long) c.free_mib) + " MiB free of " +
std::to_string((unsigned long long) c.total_mib) + " MiB"; // (as the engine's other memory lines)
if (!c.processes_known) {
out += "; the driver does not say which programs use it here";
continue;
}
std::vector<Process> others;
size_t unsized = 0;
for (const Process& p : c.processes) {
if (p.pid == self_pid) continue;
if (p.used_mib == 0) { ++unsized; continue; }
others.push_back(p);
}
std::sort(others.begin(), others.end(), [](const Process& a, const Process& b) {
return a.used_mib != b.used_mib ? a.used_mib > b.used_mib : a.pid < b.pid;
});
if (others.empty() && unsized == 0) {
out += "; the driver lists no other program using it";
continue;
}
out += "; other programs on it: ";
for (size_t i = 0; i < others.size() && i < max_procs; ++i) {
if (i > 0) out += ", ";
const std::string n = detail::base_name(others[i].name);
out += (n.empty() ? "pid " + std::to_string(others[i].pid) : n + " (pid " + std::to_string(others[i].pid) + ")") + " " +
detail::size_text(others[i].used_mib);
}
if (others.size() > max_procs) out += ", and " + std::to_string(others.size() - max_procs) + " more";
if (unsized > 0) out += std::string(others.empty() ? "" : "; ") + std::to_string(unsized) +
(unsized == 1 ? " program whose memory the driver does not report" : " programs whose memory the driver does not report");
}
return out;
}
/// "The split planned to keep N MiB free on this card, M MiB are free" for the low-VRAM warning: how far the engine's
/// own estimate was off. Empty when the card has at least what was planned (nothing to explain).
inline std::string planned_vs_free_text(int64_t planned_mib, int64_t free_mib) {
if (planned_mib <= 0 || free_mib >= planned_mib) return {};
return "the layer split planned to keep " + std::to_string((long long) planned_mib) + " MiB free here after loading; " +
std::to_string((long long) std::max<int64_t>(free_mib, 0)) + " MiB are free, so " +
std::to_string((long long) (planned_mib - std::max<int64_t>(free_mib, 0))) + " MiB went to something the plan did not count";
}
// ---------------------------------------------------------------------------------------------- the driver query
namespace detail {
struct NvmlProc { // nvmlProcessInfo_v2_t / the layout the _v3 calls fill
unsigned int pid;
unsigned long long usedGpuMemory;
unsigned int gpuInstanceId;
unsigned int computeInstanceId;
};
constexpr unsigned long long kNvmlNotAvailable = ~0ull;
using NvmlInit = int (*)();
using NvmlHandleByPci = int (*)(const char*, void**);
using NvmlProcs = int (*)(void*, unsigned int*, NvmlProc*);
using NvmlProcName = int (*)(unsigned int, char*, unsigned int);
struct Nvml {
void* lib = nullptr;
NvmlHandleByPci by_pci = nullptr;
NvmlProcs compute = nullptr;
NvmlProcs graphics = nullptr;
NvmlProcName name = nullptr;
NvmlInit shutdown = nullptr;
};
inline void* open_lib() {
#if defined(_WIN32)
return (void*) LoadLibraryA("nvml.dll");
#else
for (const char* n : {"libnvidia-ml.so.1", "libnvidia-ml.so"})
if (void* h = dlopen(n, RTLD_LAZY | RTLD_LOCAL)) return h;
return nullptr;
#endif
}
inline void* sym(void* lib, const char* n) {
#if defined(_WIN32)
return (void*) GetProcAddress((HMODULE) lib, n);
#else
return dlsym(lib, n);
#endif
}
inline void close_lib(void* lib) {
#if defined(_WIN32)
if (lib) FreeLibrary((HMODULE) lib);
#else
if (lib) dlclose(lib);
#endif
}
} // namespace detail
/// The processes that hold memory on the card with this PCI bus id ("0000:65:00.0", what cudaDeviceGetPCIBusId
/// returns). true: the driver answered (the list may be empty). false: it could not be asked. Best effort.
inline bool query_other_processes(const char* pci_bus_id, std::vector<Process>& out) {
out.clear();
if (pci_bus_id == nullptr || pci_bus_id[0] == '\0') return false;
detail::Nvml n;
n.lib = detail::open_lib();
if (n.lib == nullptr) return false;
bool ok = false;
do {
auto init = (detail::NvmlInit) detail::sym(n.lib, "nvmlInit_v2");
n.shutdown = (detail::NvmlInit) detail::sym(n.lib, "nvmlShutdown");
n.by_pci = (detail::NvmlHandleByPci) detail::sym(n.lib, "nvmlDeviceGetHandleByPciBusId_v2");
n.name = (detail::NvmlProcName) detail::sym(n.lib, "nvmlSystemGetProcessName");
// _v3 and _v2 take the 24-byte record above; the unversioned (v1) call has another record, so it is not used
n.compute = (detail::NvmlProcs) detail::sym(n.lib, "nvmlDeviceGetComputeRunningProcesses_v3");
if (!n.compute) n.compute = (detail::NvmlProcs) detail::sym(n.lib, "nvmlDeviceGetComputeRunningProcesses_v2");
n.graphics = (detail::NvmlProcs) detail::sym(n.lib, "nvmlDeviceGetGraphicsRunningProcesses_v3");
if (!n.graphics) n.graphics = (detail::NvmlProcs) detail::sym(n.lib, "nvmlDeviceGetGraphicsRunningProcesses_v2");
if (!init || !n.by_pci || !n.compute || init() != 0) break;
void* dev = nullptr;
if (n.by_pci(pci_bus_id, &dev) != 0 || dev == nullptr) { if (n.shutdown) n.shutdown(); break; }
for (detail::NvmlProcs call : {n.compute, n.graphics}) {
if (!call) continue;
std::vector<detail::NvmlProc> recs(128);
unsigned int count = (unsigned int) recs.size();
int rc = call(dev, &count, recs.data());
if (rc == 7 && count > recs.size()) { // NVML_ERROR_INSUFFICIENT_SIZE: `count` is the number
recs.resize((size_t) count + 8);
count = (unsigned int) recs.size();
rc = call(dev, &count, recs.data());
}
if (rc != 0) continue;
ok = true;
for (unsigned int i = 0; i < count && i < recs.size(); ++i) {
bool seen = false;
for (Process& p : out)
if (p.pid == recs[i].pid) { seen = true; break; }
if (seen) continue;
Process p;
p.pid = recs[i].pid;
p.used_mib = recs[i].usedGpuMemory == detail::kNvmlNotAvailable ? 0 : (uint64_t) (recs[i].usedGpuMemory >> 20);
if (n.name) {
char buf[260] = {};
if (n.name(p.pid, buf, (unsigned int) sizeof buf) == 0) p.name = buf;
}
out.push_back(std::move(p));
}
}
if (n.shutdown) n.shutdown();
} while (false);
detail::close_lib(n.lib);
return ok;
}
} // namespace strata::program::gpu_report