Integrated gfx11 under Linux: a stop by signal drains the GPU before the process ends

Reset 45 on p2006: SIGTERM 1 s into the first request ended the engine with kernels in
flight and the expert arena still registered; the kernel's exit then evicted the busy
queues ("Failed to evict queue 1", "Failed to quiesce KFD") and MES reset the GPU.

Now SIGTERM, SIGINT and SIGHUP take this order: the handler only writes the signal's
number into a pipe; a thread of its own (strata-stop) sets the serve loop's STOP flag,
releases the verify windows' GPU waits (the #267 release, silent, through a new bounded
hook release_gpu_waits_within), waits for the whole device for what is left of 3 s
(cudaDeviceSynchronize on a helper thread, the wait bounded), drops the arena's
registration only when the device finished (unregister_arena_ranges, pinned.cu, which
unregisters the ranges register_range recorded), and ends the process by the same
signal, so the wait status the caller sees is unchanged. A second signal during the
stop ends the process at once.

The bound: the server stops its engine with STOP + QUIT and waits 20 s, then SIGTERM and
5 s, then SIGKILL (serve/server.py:114, :3011-3034); Control sends SIGTERM to the server
and kills its process group after shutdown_timeout + 8 s (strata_control/runtime.py:
1113-1134); the macOS lifeline waits 10 s after its SIGTERM (serve/lifeline.py:132-145);
Linux children get SIGKILL by PDEATHSIG when the server dies. 3 s stays inside the 5 s.
QUIT was left as it is: it already leaves the serve scope through the destructors (the
verifier syncs its streams, the prefill frees) and ~ArenaExpertSource (the local at
generate.cpp:7898) unregisters the arena before main returns.

Cost by reading: a stop by signal during a request takes up to 3 s longer; nothing while
the engine runs.

Scope: compiled only with STRATA_USE_HIP on __linux__; installed at run time only when
kfd_quiet::class_flag() is set (integrated gfx1103 / gfx1150 / gfx1151, every visible
card), and only for a signal whose action is still the default (nohup's ignored SIGHUP
stays ignored). No signal mask is changed anywhere. Elsewhere the new code is a pointer
stored in Verifier::init and a list of registered range starts kept on Linux; neither is
read without the handler. STRATA_KFD_QUIET=0 or STRATA_KFD_QUIET_EXIT=0 keeps the old
death by signal; STRATA_TRACE prints one line when the handler is in and one at the stop.
Test: the stop's order with a fake GPU layer in tests/core/kfd_quiet_test.cpp.
This commit is contained in:
Niko1221 committed 2026-11-15 01:56:18 +01:00
1 parent f9932c6aee
commit 59375eb069
7 files changed
+253

No files matched your search

+38
View File
@@ -76,4 +76,42 @@ inline LoadMoves load_moves() {
return load_moves(class_flag().load(std::memory_order_relaxed), std::getenv("STRATA_KFD_QUIET"), std::getenv(fix_env(Fix::Load)));
}
// ---- EXIT: the teardown order ---------------------------------------------------------------------------------------------------
/// The bound of the stop, seconds. The server stops its engine with STOP + QUIT and waits 20 s, then sends SIGTERM and waits 5 s
/// before SIGKILL (serve/server.py ENGINE_QUIT_WAIT_S / ENGINE_TERM_WAIT_S); the macOS lifeline waits 10 s. 3 s stays inside 5 s.
constexpr double kExitBoundS = 3.0;
struct TeardownResult {
bool released = false; // the verify windows' GPU waits were released and their streams finished
bool drained = false; // the whole device finished within the bound
bool unregistered = false; // the arena's registration was dropped (only when drained)
};
/// The order of the stop: `stop()` (the request ends at its next step), `release(ms)` -> bool (raise the spin flags; wait at most ms
/// for the verify streams), `drain(ms)` -> bool (wait at most ms for the whole device), and only when drained `unregister()`.
/// `now()` is seconds; the release and the drain share one bound of `bound_s` from the call.
template <class Stop, class Release, class Drain, class Unregister, class Now>
TeardownResult teardown(Stop stop, Release release, Drain drain, Unregister unregister, Now now, double bound_s) {
TeardownResult r;
const double t0 = now();
auto left_ms = [&] {
const double l = bound_s - (now() - t0);
return l > 0.0 ? (int) (l * 1000.0) : 0;
};
stop();
r.released = release(left_ms());
r.drained = drain(left_ms());
if (r.drained) {
unregister();
r.unregistered = true;
}
return r;
}
/// What a signal does once the handler is in: the first SIGTERM / SIGINT / SIGHUP starts the teardown; a second one while it runs
/// ends the process at once by its default action (a user pressing Ctrl+C twice).
enum class OnSignal { StartTeardown, DefaultAction };
inline OnSignal on_signal(int signals_before) { return signals_before == 0 ? OnSignal::StartTeardown : OnSignal::DefaultAction; }
} // namespace strata::core::kfd_quiet
+5
View File
@@ -116,6 +116,11 @@ struct PinnedArena {
uint8_t* data() const { return (uint8_t*) base; }
};
/// Linux: drops the GPU driver's registration of every arena range registered so far, for a process that ends right after
/// (kfd_quiet.hpp, EXIT: then the kernel's exit has no userptr of ours to evict the queues for). The arenas stay mapped; their
/// destructors must not run after it. Returns the ranges unregistered; 0 elsewhere.
int unregister_arena_ranges();
struct LoadStats {
double seconds = 0.0;
// Loader fix: the two halves of `seconds`, both SUMMED OVER THE READER THREADS rather than wall clock, so
+8
View File
@@ -42,6 +42,14 @@ inline std::atomic<DiagFn>& release_gpu_fn() { static std::atomic<DiagFn> f{null
inline void release_gpu_waits(std::FILE* f) {
if (auto fn = release_gpu_fn().load()) fn(f);
}
/// The same release with one bound for all live verifiers, silent; true when their streams finished within `ms` (kfd_quiet.hpp,
/// EXIT). True when no verifier is live.
using ReleaseWithinFn = bool (*)(int);
inline std::atomic<ReleaseWithinFn>& release_gpu_within_fn() { static std::atomic<ReleaseWithinFn> f{nullptr}; return f; }
inline bool release_gpu_waits_within(int ms) {
if (auto fn = release_gpu_within_fn().load()) return fn(ms);
return true;
}
/// --pipeline-windows: the pipelined loop's windows and the drafter's chain (set while that loop runs)
inline std::atomic<DiagFn>& diag_pipeline_fn() { static std::atomic<DiagFn> f{nullptr}; return f; }
+26
View File
@@ -722,8 +722,20 @@ void release_alias_claims(std::vector<void*>& claims) {
// pin_register for the arena's ranges. Windows HIP: a range whose GPU alias covers memory in use is unregistered again and
// reported as refused, so the caller's "the driver refused it" path applies to it (#3431).
#if defined(__linux__)
// every range start registered here, for unregister_arena_ranges (kfd_quiet.hpp, EXIT); bookkeeping only
std::mutex g_reg_mu;
std::vector<void*> g_reg_starts;
#endif
cudaError_t register_range(PinnedArena& arena, void* p, uint64_t n) {
const cudaError_t e = pin_register(p, (size_t) n, cudaHostRegisterPortable | cudaHostRegisterMapped);
#if defined(__linux__)
if (e == cudaSuccess) {
std::lock_guard<std::mutex> lk(g_reg_mu);
g_reg_starts.push_back(p);
}
#endif
#if defined(_WIN32) && defined(STRATA_USE_HIP)
std::string why;
if (e == cudaSuccess && !claim_alias(p, n, arena.alias_claims, why)) {
@@ -740,6 +752,20 @@ cudaError_t register_range(PinnedArena& arena, void* p, uint64_t n) {
}
} // namespace
int unregister_arena_ranges() {
#if defined(__linux__)
std::lock_guard<std::mutex> lk(g_reg_mu);
int n = 0;
for (void* p : g_reg_starts)
if (pin_unregister(p) == cudaSuccess) ++n;
(void) cudaGetLastError();
g_reg_starts.clear();
return n;
#else
return 0;
#endif
}
PinnedArena::PinnedArena(uint64_t bytes, uint64_t slice) : PinnedArena(bytes, uniform_bounds(bytes, slice)) {
if (slice_bytes) slice_bytes = slice; // sliced registration: record the uniform size
}
+12
View File
@@ -562,6 +562,17 @@ void release_live_verifiers(std::FILE* f) {
}
if (f != nullptr) std::fflush(f);
}
// the same, silent, with one bound for all of them (kfd_quiet.hpp, EXIT: an integrated gfx11's stop on a signal)
bool release_live_verifiers_within(int ms) {
const Clock::time_point t0 = Clock::now();
bool all = true;
for (auto& slot : g_live)
if (Verifier* v = slot.load()) {
const int64_t left = (int64_t) ms - (int64_t) ms_since(t0);
if (!v->release_gpu_waits(left > 0 ? (int) left : 0)) all = false;
}
return all;
}
// #649: the host side of STRATA_VERIFY_TRACE - a ring of the last kTraceN handshake events of every verifier
struct TraceEv {
int64_t t_ns;
@@ -885,6 +896,7 @@ bool Verifier::init(const WeightTable& wt, const ModelGeometry& g, SessionState&
if (slot.load() == this || slot.compare_exchange_strong(none, this)) break;
}
release_gpu_fn().store(&release_live_verifiers);
release_gpu_within_fn().store(&release_live_verifiers_within);
cudaGetDevice(&device_); // a layer split's stage on another GPU: its streams, graphs and buffers live there
rr_stats_ = route_resident_cfg().stats_on(device_); // STRATA_ROUTE_RESIDENT: this GPU's counters, outside graph capture
strata::kernels::fused_gr_check(); // once per card: which bitwise-equal hyper-connection read runs there
+98
View File
@@ -369,6 +369,91 @@ const bool crash_bt_installed = [] {
} // namespace
#endif
#if defined(STRATA_USE_HIP) && defined(__linux__)
// EXIT (kfd_quiet.hpp), integrated gfx11 under Linux only: SIGTERM / SIGINT / SIGHUP no longer end the process with kernels in flight
// and the arena registered (the kernel's exit then evicts busy queues: reset 45 on p2006). The handler only writes the signal's
// number into a pipe; a thread of its own stops the request, releases the verify windows' GPU waits, waits at most 3 s for the
// device, drops the arena's registration only when the device finished, and then ends the process by the same signal (the same
// wait status as before). Installed only once the card is known to be of that class, only for a signal whose action is still the
// default (nohup's ignored SIGHUP stays ignored); no signal mask is changed. A second signal during the stop ends it at once.
namespace kfdq_exit {
std::atomic<std::atomic<bool>*> g_stop{nullptr}; // the serve loop's STOP flag while it exists
int g_pipe[2] = {-1, -1};
volatile sig_atomic_t g_count = 0;
int g_dev = 0;
void handler(int sig) {
if (strata::core::kfd_quiet::on_signal((int) g_count) == strata::core::kfd_quiet::OnSignal::DefaultAction) {
signal(sig, SIG_DFL);
raise(sig);
return;
}
g_count = g_count + 1;
const unsigned char b = (unsigned char) sig;
(void) !write(g_pipe[1], &b, 1);
}
[[noreturn]] void stop_and_end(int sig) {
using clk = std::chrono::steady_clock;
const clk::time_point base = clk::now();
auto now = [&] { return std::chrono::duration<double>(clk::now() - base).count(); };
auto stop = [] { if (std::atomic<bool>* f = g_stop.load()) f->store(true); };
auto release = [](int ms) { return strata::core::release_gpu_waits_within(ms); };
auto drain = [](int ms) {
struct Shared { std::mutex mu; std::condition_variable cv; bool done = false, ok = false; };
auto sh = std::make_shared<Shared>();
std::thread([sh] { // may never return on a GPU that hangs: the wait below is bounded, the process ends anyway
(void) cudaSetDevice(g_dev);
const bool ok = cudaDeviceSynchronize() == cudaSuccess;
std::lock_guard<std::mutex> lk(sh->mu);
sh->done = true;
sh->ok = ok;
sh->cv.notify_all();
}).detach();
std::unique_lock<std::mutex> lk(sh->mu);
sh->cv.wait_for(lk, std::chrono::milliseconds(ms), [&] { return sh->done; });
return sh->done && sh->ok;
};
int ranges = 0;
auto unreg = [&] { ranges = strata::core::unregister_arena_ranges(); };
const strata::core::kfd_quiet::TeardownResult r =
strata::core::kfd_quiet::teardown(stop, release, drain, unreg, now, strata::core::kfd_quiet::kExitBoundS);
if (std::getenv("STRATA_TRACE") != nullptr)
std::fprintf(stderr, "strata trace: kfd quiet: signal %d: waits released %s, device drained %s, %d arena ranges unregistered, %.0f ms\n",
sig, r.released ? "yes" : "no", r.drained ? "yes" : "no", ranges, now() * 1000.0);
std::fflush(stdout);
std::fflush(stderr);
signal(sig, SIG_DFL);
raise(sig);
_exit(128 + sig);
}
void install(int dev) {
g_dev = dev;
if (pipe2(g_pipe, O_CLOEXEC) != 0) return;
std::thread([] {
strata::platform::name_this_thread("strata-stop");
unsigned char b = 0;
for (;;) {
const ssize_t n = read(g_pipe[0], &b, 1);
if (n == 1) stop_and_end((int) b);
if (n < 0 && errno == EINTR) continue;
if (n <= 0) return;
}
}).detach();
for (int sig : {SIGTERM, SIGINT, SIGHUP}) {
struct sigaction old{};
if (sigaction(sig, nullptr, &old) != 0 || (old.sa_flags & SA_SIGINFO) || old.sa_handler != SIG_DFL) continue;
struct sigaction sa{};
sa.sa_handler = handler;
sigemptyset(&sa.sa_mask);
sa.sa_flags = SA_RESTART;
(void) sigaction(sig, &sa, nullptr);
}
}
} // namespace kfdq_exit
#endif
// STRATA_PIPE_BYIELD_NODRAIN=1 (read once; off by default): with the pipelined groups, a BYIELD that reaches the main
// loop is dropped without draining the groups first. A pipelined read never gives way (batch_read_piece), so the
@@ -4027,6 +4112,13 @@ int main(int argc, char** argv) {
strata::core::kfd_quiet::class_flag().store(true);
if (std::getenv("STRATA_TRACE") != nullptr && strata::core::kfd_quiet::on(strata::core::kfd_quiet::Fix::Load))
std::fprintf(stderr, "strata trace: kfd quiet: load order active (check first, settle after the expert cache, first prompt's buffers at init)\n");
if (strata::core::kfd_quiet::on(strata::core::kfd_quiet::Fix::Exit)) {
int cur = 0;
if (cudaGetDevice(&cur) != cudaSuccess) { cur = 0; (void) cudaGetLastError(); }
kfdq_exit::install(cur);
if (std::getenv("STRATA_TRACE") != nullptr)
std::fprintf(stderr, "strata trace: kfd quiet: stop on SIGTERM / SIGINT / SIGHUP drains the GPU first (at most 3 s)\n");
}
}
#endif
// and the file cache of the model files is given back while the expert arena is read and after it (page_cache_drop.hpp):
@@ -14733,6 +14825,9 @@ int main(int argc, char** argv) {
return true;
};
sp.should_stop = [&] { return stop_req.load(); };
#if defined(STRATA_USE_HIP) && defined(__linux__)
kfdq_exit::g_stop.store(&stop_req); // EXIT (kfd_quiet.hpp): a signal ends the running request like STOP (nothing without the handler)
#endif
// 149-prefetch STRATA_RAM_ADAPT2: the prompt's routing seeds the RAM policy with a limited weight
// (STRATA_RAM_ADAPT_PROMPT_W, default 0.25: an expert every prompt token routes to counts like ~5 decode routings),
// fading by 5% a decode window; the decode's own counts and the GPU tier are untouched
@@ -21354,6 +21449,9 @@ int main(int argc, char** argv) {
}
}
save_profile("exit"); // #477: QUIT, or the server closed stdin
#if defined(STRATA_USE_HIP) && defined(__linux__)
kfdq_exit::g_stop.store(nullptr); // the flag goes with this scope
#endif
#if defined(STRATA_GPU_METAL)
// the stdin reader (detached above) may still take in_mu when the server closes the pipe after QUIT; on macOS
// locking that mutex once this scope has destroyed it throws (the engine ended with an abort): end here
+66
View File
@@ -47,11 +47,77 @@ void load_order() {
CHECK(!class_flag().load());
CHECK(!on(Fix::Load) && !on(Fix::Exit));
}
// a fake GPU layer for the stop: a clock in seconds, a GPU that finishes after `busy_s` once released (never when `hung`)
struct FakeGpu {
double t = 0.0;
double busy_s = 0.5;
bool hung = false;
bool stopped = false, unregistered = false;
std::string order;
TeardownResult run(double bound) {
auto stop = [&] { stopped = true; order += "S"; };
auto wait_for = [&](int ms) { // waits until done or ms passed; true when done
const double lim = ms / 1000.0;
if (!hung && busy_s <= lim) { t += busy_s; busy_s = 0.0; return true; }
t += lim;
if (!hung) busy_s -= lim;
return false;
};
auto release = [&](int ms) { order += "R"; return wait_for(ms); };
auto drain = [&](int ms) { order += "D"; return wait_for(ms); };
auto unreg = [&] { unregistered = true; order += "U"; };
return teardown(stop, release, drain, unreg, [&] { return t; }, bound);
}
};
void stop_order() {
// a GPU that finishes in 0.5 s: stop, release, drain, unregister; inside the bound
{
FakeGpu g;
const TeardownResult r = g.run(kExitBoundS);
CHECK(g.order == "SRDU");
CHECK(r.released && r.drained && r.unregistered && g.unregistered);
CHECK(g.t <= kExitBoundS + 1e-9);
}
// a GPU that takes 2.5 s: the release uses most of the bound, the drain the rest; still drained
{
FakeGpu g;
g.busy_s = 2.5;
const TeardownResult r = g.run(kExitBoundS);
CHECK(r.released && r.drained && r.unregistered);
CHECK(g.t <= kExitBoundS + 1e-9);
}
// a GPU that takes 5 s: not drained within 3 s: the registration stays (unregistering under a running copy is worse), and
// the whole stop took no more than the bound
{
FakeGpu g;
g.busy_s = 5.0;
const TeardownResult r = g.run(kExitBoundS);
CHECK(!r.released && !r.drained && !r.unregistered && !g.unregistered);
CHECK(g.order == "SRD");
CHECK(g.t <= kExitBoundS + 0.002);
}
// a hung GPU: the same, bounded
{
FakeGpu g;
g.hung = true;
const TeardownResult r = g.run(kExitBoundS);
CHECK(!r.drained && !g.unregistered && g.stopped);
CHECK(g.t <= kExitBoundS + 0.002);
}
// the bound stays inside the server's 5 s between SIGTERM and SIGKILL (serve/server.py ENGINE_TERM_WAIT_S)
CHECK(kExitBoundS > 0.0 && kExitBoundS < 5.0);
// the first signal starts the stop, a second one takes the default action at once
CHECK(on_signal(0) == OnSignal::StartTeardown);
CHECK(on_signal(1) == OnSignal::DefaultAction);
CHECK(on_signal(2) == OnSignal::DefaultAction);
}
} // namespace
int main() {
switches();
load_order();
stop_order();
if (failed) {
std::fprintf(stderr, "kfd_quiet_test: %d check(s) failed\n", failed);
return 1;