radiance 2.0.0

Radiance becomes a multi-model engine: one process serves several models behind one port, loads
each when a request names it, parks it in host memory or restores it from its container, and
shares the cards between them (docs/MULTIMODEL.md). The configuration is one YAML file; the
command line flags are gone (`radiance --config FILE`, hot reload on SIGHUP).

Formats. IQ8R (rotated int8) and IQR-V4 replace FP8 and MXFP4 as whole-model formats, with an
int8 KV cache (`kv-cache-dtype: i8`) in place of the fp8 one. Containers whose weights are block
FP8, MXFP4, M2XFP4, NVFP4 or ParoQuant are refused at startup by the name of the first such
weight. Not served until they have int8 containers: GLM-5.3-Flash, Ornith-1.5, Sage-A1.5,
Nemotron-3.5-Bolt-74B, Ling-3.0-flash, drama-3 and Anima's FP8 container; Nemotron-3.5-Bolt-E4B,
the Gemma 4 31B DFlash containers and MiniCPM5-2B bf16 serve without their drafter. 1.17.0
serves all of them.

Speed. Chained launches for Qwen3.8-27B, Gemma 4, Gemma 3 and the small bf16 models, a new
Qwen3.8-Flash-Next container (IQR-V4 experts, int8 trunk) with its decode step and prefill
reworked, and a reworked adaptive draft window.

Deployment. deploy/compose has two fleet files, tp1.yaml and tp2.yaml, each with its
configuration beside it, in place of the per-model files. `host-pool-mib` is a model's host pool
in all, split among its ranks. The dashboard is rebuilt: an hour of history kept by the server,
each accelerator's memory by model, model states over time.

Merged since 1.17.0: Nemotron-3.5-Bolt-74B-A9B by keptn42 (#339); GLM-5.3-Flash on four cards by
AnimusNull (#397); chained launches for Flash-Next's decode step (#396) and preempted requests
keeping their prefix and place (#405) by mici81; --prefill-interleave auto by Code000 (#410);
eight more libr3d kernels and the w4a4 reference by RikshaDriver (#403, #407, #408); libr3d
large-BAR and E4M3 decode fixes by neuromanMD (#438, #439); int4/int5 decode tiles by Kezi
(#426); attention for Nanbeige 4.3 33B by everplays (#417); expert_stats_report.py by baKon
(#431). Fixed: #398, #402, #419, #437 (dschmitz's patch); added the metrics of #392, and
multi-model serving as asked for in #367 and #109.

Plugin ABI 39: out-of-tree plugins need to be rebuilt.

Thanks to @keptn42, @AnimusNull, @mici81, @Code000, @RikshaDriver, @neuromanMD, @Kezi, @everplays, @baKon and @dschmitz.
This commit is contained in:
Deadcode committed 2026-11-14 22:32:28 +01:00
1 parent b4c04b6042
commit ddcb9c69bb
696 files changed
+120770 -56596

No files matched your search

+632 -56
View File
@@ -60,6 +60,7 @@
#include <mutex>
#include <new>
#include <string>
#include <thread>
#include <unordered_map>
#include <vector>
@@ -148,6 +149,7 @@ thread_local bool t_ours = false;
inline hipError_t ret(hipError_t e) { t_err = e; t_ours = true; return e; }
thread_local uint8_t t_next_fence = 0;
thread_local bool t_peer = false; /* a_peer_launch: the launches are a collective's */
/* Whether any work was forwarded to a HIP stream (a stream this backend does not own). Until
* then HIP's default stream is empty and synchronising it is answered here; asking HIP would
@@ -205,6 +207,9 @@ struct Registry {
std::vector<Module*> order;
};
/* Moves when a stub comes to name another kernel, which empties every thread's stub cache. */
std::atomic<uint64_t> g_stub_epoch{0};
Registry& reg() {
static Registry* r = new Registry(); /* never destroyed: unregistration runs from atexit */
return *r;
@@ -563,13 +568,14 @@ KernelRec* resolve(Func* fn, int ord) {
}
/* One lookup per launch: a thread-local direct-mapped cache in front of the registry. */
struct CacheEnt { const void* stub; int ord; KernelRec* k; };
struct CacheEnt { const void* stub; int ord; KernelRec* k; uint64_t epoch; };
thread_local CacheEnt t_cache[512];
KernelRec* kernel_for(const void* stub, int ord, std::string* why) {
const size_t h = (((uintptr_t)stub >> 4) ^ ((uintptr_t)stub >> 13) ^ (size_t)ord) & 511u;
CacheEnt& c = t_cache[h];
if (c.stub == stub && c.ord == ord && c.k) return c.k;
const uint64_t epoch = g_stub_epoch.load(std::memory_order_acquire);
if (c.stub == stub && c.ord == ord && c.k && c.epoch == epoch) return c.k;
Func* fn = nullptr;
{
Registry& r = reg();
@@ -580,7 +586,7 @@ KernelRec* kernel_for(const void* stub, int ord, std::string* why) {
if (!fn) { *why = "the kernel was never registered with HIP"; return nullptr; }
KernelRec* k = resolve(fn, ord);
if (!k) { *why = fn->name + ": " + fn->err[ord]; return nullptr; }
c = { stub, ord, k };
c = { stub, ord, k, epoch };
return k;
}
@@ -601,6 +607,7 @@ struct Stream {
uint64_t epoch = 0; /* host epoch at the last system acquire */
hsa_signal_t ride{}; /* rad_ride: the next dispatch's completion signal */
bool agent_only = false; /* rad_xp_stream_create: never a system-scope acquire */
bool high = false; /* created or last reused at high priority */
std::atomic<int> gates{0}; /* closed gates (rad_stream_gate) on this queue */
std::atomic<int> fault{0};
char* bounce = nullptr; /* pinned, for pageable copies */
@@ -610,11 +617,21 @@ struct Stream {
* far, and whether the last packet on the queue was a chained kernel. */
uint64_t* chain_ctr = nullptr;
uint64_t chain_issued = 0;
/* The blocks issued before the last packet that depends on what precedes it: what a chained
* kernel played beside that packet (an overlap) waits for, since it reads nothing issued
* from that packet on. */
uint64_t chain_frontier = 0;
/* Whether that packet went out without its barrier bit (a chained kernel behind chained ones):
* packets before it may then still run while later packets launch. */
bool frontier_open = false;
bool prev_chained = false;
/* Whether a packet that adds nothing to the counter (a plain kernel) may still be running: one
* launched since the last packet whose barrier bit held it behind everything before. A chained
* kernel's wait covers only chained blocks, so while this is set the next one keeps its bit. */
bool plain_inflight = false;
/* Whether a collective's packet may still be running: one published since the last packet
* whose barrier bit held it behind everything before (see "collectives on a shared card"). */
bool peer_inflight = false;
void lock() {
while (busy.exchange(true, std::memory_order_acquire))
@@ -636,6 +653,19 @@ std::vector<uint32_t> g_queue_free; /* destroyed queues' slots
uint32_t g_queue_next_slot = 0;
uint32_t g_queue_gen[kMaxQueues];
/* Drained streams kept for the next rad_stream_create on their card, instead of destroyed.
*
* Destroying a hardware queue makes the scheduler firmware unmap it (MES REMOVE_QUEUE), and on
* RDNA4 that request can fail while another queue keeps the same card busy; the driver then resets
* the card and every allocation on it is lost. A process serving several models unloads one while
* another computes on the card, so a model's queues outlive it here and the next engine on that
* card takes them over. A kept queue holds its context save area on the card, about 41 MiB on an
* R9700 (24 of them 0.99 GiB, measured). The queues of a card are destroyed at process exit, and
* where the caller answers for nothing computing on the card (a_stream_trim). Keyed by card and
* priority. */
std::mutex g_spare_mu;
std::vector<Stream*> g_spare[kMaxDevices][2];
/* The queue an id names, or null once it is destroyed. The slot's id is stored before its queue
* (release), so a queue read here that belongs to a later generation is seen with that
* generation's id and refused. */
@@ -663,6 +693,10 @@ inline uint64_t steady_ns() {
std::chrono::steady_clock::now().time_since_epoch()).count();
}
void report_running(int card);
/* A queue the runtime stopped stays stopped, and `faulted` ends every wait in the process, so
* nothing can serve after this: the report, then the exit a GPU memory fault takes. */
void on_queue_error(hsa_status_t st, hsa_queue_t*, void* data) {
Stream* s = static_cast<Stream*>(data);
const char* m = nullptr;
@@ -673,6 +707,9 @@ void on_queue_error(hsa_status_t st, hsa_queue_t*, void* data) {
G().faulted.store(true, std::memory_order_release);
hsa_signal_store_screlease(G().fault, 1);
RAD_ERR("device %d: the AQL queue faulted: %s", s->ord, m ? m : "?");
report_running(s->ord);
fatal("a queue on device %d stopped for good (the report is above); exiting so a restart can "
"bring the server back", s->ord);
}
/* Queue dump, printed once when a host wait has not returned for 5 s. Nothing on the step path
@@ -814,6 +851,7 @@ std::string where_is(uintptr_t a) {
if (a >= f->base && a < f->base + (uintptr_t)f->bytes)
return fmt("inside FREED %s, freed %.1f s ago", rec_str(*f, a).c_str(),
(double)(now - f->freed_ns) * 1e-9);
if (const std::string paged = dev_fault_where((const void*)a); !paged.empty()) return "in " + paged;
std::string s = "in no range this process holds or recently freed";
if (it != g_live.begin()) {
const AllocRec& r = std::prev(it)->second;
@@ -867,10 +905,16 @@ hsa_status_t on_system_event(const hsa_amd_event_t* e, void*) {
RAD_ERR("device %d: GPU memory fault at %#" PRIxPTR " (%s ): %s; %s", card, va,
why.empty() ? " ?" : why.c_str(), where_is(va).c_str(), runtime_view(va).c_str());
}
/* The running kernel and its arguments. A queue's read index stays on a packet until it
* completes, so the packet there is in flight. Every pointer-shaped argument word is located
* like the address, which names the operand that got a stale or short buffer. Only card
* `card`'s queues; the host reads the arguments at the packet's kernarg_address. */
report_running(card);
fatal("a GPU memory fault on device %d stopped its queue for good (the report is above); "
"exiting so a restart can bring the server back", card);
}
/* The running kernel and its arguments. A queue's read index stays on a packet until it
* completes, so the packet there is in flight. Every pointer-shaped argument word is located
* like the address, which names the operand that got a stale or short buffer. Only card
* `card`'s queues; the host reads the arguments at the packet's kernarg_address. */
void report_running(int card) {
std::lock_guard<std::mutex> sl(G().streams_mu);
for (Stream* s : G().streams) {
if (s->ord != card) continue;
@@ -897,8 +941,6 @@ hsa_status_t on_system_event(const hsa_amd_event_t* e, void*) {
RAD_ERR(" argument +%u = %#" PRIx64 ": %s", i * 8, w, where_is((uintptr_t)w).c_str());
}
}
fatal("a GPU memory fault on device %d stopped its queue for good (the report is above); "
"exiting so a restart can bring the server back", card);
}
/* Stall detector for a spin loop. tick() reads the clock every 64k iterations, a few thousand
@@ -968,6 +1010,17 @@ int64_t stuck_ms() {
* kTapeOverlapRun consecutive packets (TapeRec::overlap), so the margin is that run plus one. */
constexpr uint64_t kReserveMargin = (uint64_t)kTapeOverlapRun + 2;
/* The wait for room in a full ring sleeps rather than spins. A full queue holds thousands of
* packets the card has yet to run, at least ~3 us each (the dispatch floor), so the card is many
* milliseconds from idle and a nap of this length costs it nothing; a spinning wait held a core
* for the whole of a long prefill, which outruns the card by the queue's depth. */
constexpr long kFullNapNs = 100000;
inline void full_nap() {
const timespec ts{0, kFullNapNs};
nanosleep(&ts, nullptr);
}
inline int reserve(Stream* s, uint64_t* out) {
const uint64_t idx = s->wr;
const uint64_t size = s->mask + 1;
@@ -984,8 +1037,8 @@ inline int reserve(Stream* s, uint64_t* out) {
"gate (rad_gate_open) first");
return RAD_E_STATE;
}
st.tick();
_mm_pause();
st.check();
full_nap();
}
}
*out = idx;
@@ -1033,6 +1086,8 @@ struct TapeRec {
/* A chained kernel (RadKernelChainFn): played from the queue's own argument slot with a chain
* record, and without the barrier bit behind another chained kernel. */
uint8_t chain = 0;
/* A collective's launch (a_peer_launch). */
uint8_t peer = 0;
};
struct Tape {
@@ -1059,6 +1114,7 @@ void tape_note_dispatch(Stream* s, const hsa_kernel_dispatch_packet_t* p, uint16
r.kind = kTapeDispatch;
r.fence = fence;
r.chain = chain ? 1 : 0;
r.peer = t_peer ? 1 : 0;
r.s = s;
r.pkt = *p;
r.pkt.header = 0;
@@ -1093,12 +1149,34 @@ inline int acquire_scope(Stream* s, uint64_t idx, bool forced) {
return HSA_FENCE_SCOPE_AGENT;
}
/* The chain record of a chained launch (RadKernelChainFn) at `slot`: wait for every chained
* block issued before it on `s`. `on` false writes a record no kernel accepts. */
inline void chain_record(Stream* s, char* slot, bool on) {
/* Collectives on a shared card.
*
* A chained kernel launched behind a running one holds its wave slots while it waits in its
* prologue, and the packet processor launches as far ahead as the card has slots. Behind a
* collective that is a wait on another card: a collective's block finishes when the peer rank's
* block of the same launch has run there. With one engine on the cards the peer's block always
* gets its slot, because each rank's collective is launched before anything waits behind it. With
* two engines it may not. Engine A's collective on card 0 waits for its half on card 1; card 1 is
* full of engine B's chained kernels waiting behind B's collective; B's half on card 0 gets no
* slot beside A's, since a prefill junction launches up to 512 blocks, more than the card runs at
* once. Nothing advances from there: Qwen3.8-27B prefilling beside Gemma 4 12B decoding, both on
* the same two R9700, stopped within 12 s.
*
* So on a card that more than one multi-card engine has claimed (a_cards_claim), a chained packet
* keeps its barrier bit while a collective's packet may be running on its queue. Only the
* collectives' own blocks then wait on the card for another card; everything else waiting there
* waits for kernels that finish by themselves. An engine alone on its cards pays nothing. */
std::atomic<int> g_card_claims[kMaxDevices];
inline bool card_shared(const Stream* s) {
return s->ord < kMaxDevices && g_card_claims[s->ord].load(std::memory_order_relaxed) > 1;
}
/* The chain record of a chained launch (RadKernelChainFn) at `slot`: wait for the first `target`
* chained blocks issued on `s`. `on` false writes a record no kernel accepts. */
inline void chain_record(Stream* s, char* slot, bool on, uint64_t target) {
uint64_t rec[4];
rec[0] = on ? RAD_CHAIN_MAGIC : 0;
rec[1] = s->chain_issued;
rec[1] = target;
rec[2] = (uint64_t)(uintptr_t)s->chain_ctr;
rec[3] = rec[0] ^ rec[1] ^ rec[2] ^ RAD_CHAIN_CHECK;
std::memcpy(slot + RAD_CHAIN_KARG_OFF, rec, sizeof rec);
@@ -1119,6 +1197,9 @@ int barrier(Stream* s, hsa_signal_t dep, hsa_signal_t done, int acq, int rel,
if (rc < 0) { s->unlock(); return rc; }
s->prev_chained = false;
s->plain_inflight = false;
s->peer_inflight = false;
s->chain_frontier = s->chain_issued;
s->frontier_open = false;
if (out_idx) *out_idx = idx;
auto* p = reinterpret_cast<hsa_barrier_and_packet_t*>(
static_cast<hsa_kernel_dispatch_packet_t*>(s->q->base_address) + (idx & s->mask));
@@ -1184,7 +1265,7 @@ int dispatch(Stream* s, const KernelRec* k, dim3 g, dim3 b, void** args, size_t
/* A chained kernel (RadKernelChainFn, named r4dchain*): its record in the slot's tail. */
const bool chain = k->chained && rad_dev_chain_enabled() && s->chain_ctr &&
n <= RAD_CHAIN_KARG_OFF;
if (k->chained) chain_record(s, slot, chain);
if (k->chained) chain_record(s, slot, chain, s->chain_issued);
if (capturing()) tape_note_dispatch(s, p, setup, ka, n, fence, chain);
/* Attach the ride after the tape copied the packet: a recorded packet carries no signal, and
* a play attaches whichever ride is pending then (PlayRun::put). */
@@ -1196,11 +1277,15 @@ int dispatch(Stream* s, const KernelRec* k, dim3 g, dim3 b, void** args, size_t
const int rel = (fence & kFenceReleaseSystem) ? HSA_FENCE_SCOPE_SYSTEM : HSA_FENCE_SCOPE_AGENT;
/* Behind another chained kernel a chained one waits in its prologue; a completion signal keeps
* the bit, since its completion must cover everything before it. */
const bool keep = !(chain && s->prev_chained && !s->plain_inflight && !p->completion_signal.handle);
const bool keep = !(chain && s->prev_chained && !s->plain_inflight && !p->completion_signal.handle &&
!(s->peer_inflight && card_shared(s)));
publish(s, idx, header(HSA_PACKET_TYPE_KERNEL_DISPATCH, acq, rel, keep), setup);
s->chain_frontier = s->chain_issued;
s->frontier_open = !keep;
if (chain) s->chain_issued += blocks_of(p);
s->prev_chained = chain;
s->plain_inflight = keep ? !chain : s->plain_inflight || !chain;
s->peer_inflight = keep ? t_peer : s->peer_inflight || t_peer;
s->unlock();
return RAD_OK;
}
@@ -1298,14 +1383,21 @@ struct PlayRun {
/* A chained record plays from this queue's own argument slot, where its chain record goes:
* the tape's copy is shared by every play, and the next step's play may be written while
* this one runs. */
bool chain = false;
const bool chain = r.chain && tape && s->chain_ctr && r.karg_len <= RAD_CHAIN_KARG_OFF;
/* A dispatch that depends on what precedes it; the rest overlap the packets in flight
* (they touch nothing issued since the last dependent one). A plain overlap counts as
* dependent while the frontier is open: the analysis let it start beside the last
* dependent packet because that packet's barrier held both behind everything earlier, and
* a chained packet that dropped the bit holds only itself, in its prologue. */
const bool dependent = foreign || !r.overlap || done.handle || (!chain && s->frontier_open);
if (r.chain && tape) {
char* slot = s->karg + (size_t)(idx & s->mask) * kKargSlot;
chain = s->chain_ctr && r.karg_len <= RAD_CHAIN_KARG_OFF;
if (chain) {
std::memcpy(slot, tape->karg_host.data() + r.karg_off, r.karg_len);
p->kernarg_address = slot;
chain_record(s, slot, true);
/* An overlap waits for the blocks before the packet it runs beside, and adds its
* own, so the next dependent chained kernel waits for it too. */
chain_record(s, slot, true, dependent ? s->chain_issued : s->chain_frontier);
}
}
const int acq = acquire_scope(s, idx, (r.fence & kFenceAcquireSystem) != 0);
@@ -1314,12 +1406,15 @@ struct PlayRun {
/* A dispatch carrying a record keeps the bit: its completion must cover everything before
* it on the queue, which an unordered dispatch's does not. A chained kernel behind another chained one
* on this queue waits in its prologue instead. */
bool ordered = foreign || !r.overlap || done.handle;
bool ordered = dependent;
/* Not while a plain packet may still run: a played plain kernel the overlap analysis let
* start early (it touched nothing in flight) adds nothing to the counter, so a chained
* kernel that reads its output and sits behind a chained one (a cache read beside a
* collective, say) would wait for the chained blocks only. */
if (chain && s->prev_chained && !s->plain_inflight && !foreign && !done.handle) ordered = false;
/* Nor behind a collective on a shared card, which covers a chained overlap as well: its
* prologue waits for blocks that may be the collective's. */
if (chain && s->peer_inflight && card_shared(s)) ordered = true;
if (stamp) {
stamp->ordered = ordered;
stamp->chained = chain;
@@ -1328,9 +1423,14 @@ struct PlayRun {
__atomic_store_n(reinterpret_cast<uint32_t*>(p), (uint32_t)h | ((uint32_t)r.pkt.setup << 16),
__ATOMIC_RELEASE);
foreign = false;
if (dependent) {
s->chain_frontier = s->chain_issued;
s->frontier_open = !ordered;
}
if (chain) s->chain_issued += blocks_of(p);
s->prev_chained = chain;
s->plain_inflight = ordered ? !chain : s->plain_inflight || !chain;
s->peer_inflight = ordered ? r.peer != 0 : s->peer_inflight || r.peer != 0;
s->wr = idx + 1;
next = idx + 1;
*out_idx = idx;
@@ -1342,9 +1442,16 @@ struct PlayRun {
/* One interrupt signal per thread for synchronous waits (see "host waits"). A signal is only
* waited on by the thread that armed it, so two threads waiting on one queue do not share. */
hsa_signal_t thread_signal() {
thread_local hsa_signal_t s{0};
if (!s.handle && hsa_signal_create(0, 0, nullptr, &s) != HSA_STATUS_SUCCESS) s.handle = 0;
return s;
/* Destroyed when the thread ends: an engine's rank threads come and go with the engine, and a
* process that loads and unloads models (docs/MULTIMODEL.md) would otherwise leak one signal
* per thread it ever ran. Nothing waits on it then, since only its own thread arms it. */
struct Owned {
hsa_signal_t s{0};
~Owned() { if (s.handle) hsa_signal_destroy(s); }
};
thread_local Owned o;
if (!o.s.handle && hsa_signal_create(0, 0, nullptr, &o.s) != HSA_STATUS_SUCCESS) o.s.handle = 0;
return o.s;
}
/* ------------------------------------------------------------------ host waits
@@ -1555,6 +1662,27 @@ namespace {
using namespace aql;
/* A drained stream's queue, argument ring and bounce buffer back to the runtime. */
void stream_close(Stream* s) {
{
std::lock_guard<std::mutex> lk(G().streams_mu);
auto& v = G().streams;
for (size_t i = 0; i < v.size(); ++i) if (v[i] == s) { v.erase(v.begin() + (long)i); break; }
}
g_queue_by_id[s->id % kMaxQueues].store(nullptr, std::memory_order_release);
hsa_queue_destroy(s->q);
{
std::lock_guard<std::mutex> lk(g_queue_slot_mu);
g_queue_free.push_back(s->id % kMaxQueues);
}
note_free(s->karg);
note_free(s->bounce);
hsa_amd_memory_pool_free(s->karg);
hsa_amd_memory_pool_free(s->bounce);
s->magic = 0;
delete s;
}
int a_stream_create(RadStream* out, int high_priority) {
if (!out) return RAD_E_INVAL;
int ord = 0;
@@ -1563,8 +1691,40 @@ int a_stream_create(RadStream* out, int high_priority) {
return RAD_E_DEVICE;
}
const Dev& d = G().dev[(size_t)ord];
if (ord < kMaxDevices) {
Stream* r = nullptr;
{
std::lock_guard<std::mutex> lk(g_spare_mu);
auto& v = g_spare[ord][high_priority ? 1 : 0];
if (!v.empty()) { r = v.back(); v.pop_back(); }
}
if (r) {
/* Every packet it held has completed (a_stream_destroy drained it), so its counters
* start over; its packet indices keep counting, as the queue's own do. A new id, so
* nothing recorded against the previous owner's id reaches this queue. */
r->agent_only = false;
r->chain_issued = 0;
r->chain_frontier = 0;
r->frontier_open = false;
r->prev_chained = false;
r->plain_inflight = false;
r->peer_inflight = false;
*reinterpret_cast<volatile uint64_t*>(r->chain_ctr) = 0;
_mm_sfence();
{
std::lock_guard<std::mutex> lk(g_queue_slot_mu);
const uint32_t slot = r->id % kMaxQueues;
r->id = g_queue_gen[slot]++ * kMaxQueues + slot;
g_queue_id_at[slot].store(r->id, std::memory_order_release);
g_queue_by_id[slot].store(r->q, std::memory_order_release);
}
*out = (RadStream)r;
return RAD_OK;
}
}
auto s = std::make_unique<Stream>();
s->ord = ord;
s->high = high_priority != 0;
s->agent = d.agent;
if (hsa_queue_create(d.agent, kQueuePackets, HSA_QUEUE_TYPE_SINGLE, on_queue_error, s.get(),
UINT32_MAX, UINT32_MAX, &s->q) != HSA_STATUS_SUCCESS) {
@@ -1641,23 +1801,67 @@ void a_stream_destroy(RadStream rs) {
"argument ring stay allocated", rad_strerror(rc));
return;
}
{
std::lock_guard<std::mutex> lk(G().streams_mu);
auto& v = G().streams;
for (size_t i = 0; i < v.size(); ++i) if (v[i] == s) { v.erase(v.begin() + (long)i); break; }
/* Kept for the card's next stream (see g_spare); a faulted queue is not handed on. Its id
* stops naming it at once, as a destroyed queue's would. */
if (s->ord < kMaxDevices && s->fault.load(std::memory_order_acquire) == 0 &&
s->gates.load(std::memory_order_acquire) == 0) {
g_queue_by_id[s->id % kMaxQueues].store(nullptr, std::memory_order_release);
std::lock_guard<std::mutex> lk(g_spare_mu);
g_spare[s->ord][s->high ? 1 : 0].push_back(s);
return;
}
g_queue_by_id[s->id % kMaxQueues].store(nullptr, std::memory_order_release);
hsa_queue_destroy(s->q);
{
std::lock_guard<std::mutex> lk(g_queue_slot_mu);
g_queue_free.push_back(s->id % kMaxQueues);
stream_close(s);
}
/* How many hardware queues card `ord` has open, and how many of them are kept ones no stream
* holds. */
void a_stream_counts(int ord, int* open, int* idle) {
int n = 0, k = 0;
if (ord >= 0 && ord < kMaxDevices) {
{
std::lock_guard<std::mutex> lk(G().streams_mu);
for (const Stream* s : G().streams) n += s->ord == ord;
}
std::lock_guard<std::mutex> lk(g_spare_mu);
k = (int)(g_spare[ord][0].size() + g_spare[ord][1].size());
}
note_free(s->karg);
note_free(s->bounce);
hsa_amd_memory_pool_free(s->karg);
hsa_amd_memory_pool_free(s->bounce);
s->magic = 0;
delete s;
if (open) *open = n;
if (idle) *idle = k;
}
/* Card `ord`'s kept queues destroyed until `keep` are left, the number destroyed. A queue takes
* about 41 MiB of the card (its context save area, mostly), and the kept ones are what a model
* that needs nearly all of a card is short of.
*
* Destroying a queue while another keeps the card busy is what g_spare exists to avoid, so
* nothing is destroyed unless every queue of the card is empty, the ones streams hold included;
* the caller answers for nothing being launched on the card meanwhile (a fleet with every other
* model off the card and the one asking stopped in its bring-up). The kept queues were drained
* when their streams closed. */
int a_stream_trim(int ord, int keep) {
if (ord < 0 || ord >= kMaxDevices) return 0;
std::vector<Stream*> go;
{
std::lock_guard<std::mutex> lk(g_spare_mu);
{
std::lock_guard<std::mutex> ls(G().streams_mu);
for (const Stream* s : G().streams)
if (s->ord == ord && hsa_queue_load_read_index_scacquire(s->q) !=
hsa_queue_load_write_index_scacquire(s->q))
return 0;
}
size_t left = g_spare[ord][0].size() + g_spare[ord][1].size();
for (int hi = 1; hi >= 0; --hi) {
auto& v = g_spare[ord][hi];
while (!v.empty() && left > (size_t)std::max(keep, 0)) {
go.push_back(v.back());
v.pop_back();
--left;
}
}
}
for (Stream* s : go) stream_close(s);
return (int)go.size();
}
int a_stream_sync(RadStream rs) {
@@ -2883,8 +3087,8 @@ int dma_put(DmaQueue* q, const uint32_t* dw, uint64_t n) {
device_set_error("rad_memcpy_list_async: a queue faulted while the DMA ring was full");
return RAD_E_DEVICE;
}
st.tick();
_mm_pause();
st.check();
full_nap();
}
}
for (uint64_t i = 0; i < pad; ++i) q->rb[at + i] = 0;
@@ -3341,6 +3545,54 @@ int a_link_hold(RadStream rs, int on) {
return RAD_OK;
}
void a_peer_launch(int on) { t_peer = on != 0; }
int a_cards_claim(const int* cards, int n, int on) {
bool shared = false;
for (int i = 0; i < n; ++i) {
if (cards[i] < 0 || cards[i] >= kMaxDevices) continue;
/* Once a card, however many of the engine's ranks sit on it. */
bool seen = false;
for (int j = 0; j < i; ++j) seen = seen || cards[j] == cards[i];
if (seen) continue;
if (on) shared = g_card_claims[cards[i]].fetch_add(1) + 1 > 1 || shared;
else g_card_claims[cards[i]].fetch_sub(1);
}
if (!on || !shared) return RAD_OK;
/* The other engine may have chained packets in flight behind a collective, published before
* the claim. Every packet after it sees the claim (the count is read under the queue's lock,
* which the drain's barrier takes), so once each queue of the shared cards has drained, none
* is left. The registry's lock is not held across the drains: every host wait reads the
* queues' progress under it. A queue lives on as a spare after its engine (g_spare); the one
* kind that is destroyed, a faulted one, is skipped. */
std::vector<Stream*> queues;
{
std::lock_guard<std::mutex> lk(G().streams_mu);
for (Stream* s : G().streams) {
if (!card_shared(s) || s->fault.load(std::memory_order_acquire) != 0) continue;
for (int i = 0; i < n; ++i)
if (cards[i] == s->ord) { queues.push_back(s); break; }
}
}
for (Stream* s : queues) {
/* A queue at a closed gate drains once its owner opens the gate, within a step. */
const uint64_t t0 = steady_ns();
while (s->gates.load(std::memory_order_acquire) > 0) {
if (steady_ns() - t0 > 30ull * 1000000000ull) {
device_set_error("rad_dev_cards_claim: a queue on card %d stayed at a closed gate "
"for 30 s", s->ord);
return RAD_E_STATE;
}
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
if (const int rc = stream_drain(s); rc < 0) {
device_set_error("rad_dev_cards_claim: a queue on card %d could not drain", s->ord);
return rc;
}
}
return RAD_OK;
}
int a_dma_lane(int device, char* out, int cap) {
if (device < 0 || device >= kMaxDevices || device >= (int)G().dev.size() || !out || cap <= 0)
return RAD_E_INVAL;
@@ -3441,14 +3693,88 @@ std::string card_holders(int ord) {
return s + ".";
}
/* ---- spare device memory.
*
* A decommit keeps the card memory it unmaps, as a handle of its size, and the next commit of that
* size on that card maps it again. Memory handed back to the driver is wiped before its pages can
* be had again, at ~95 GB/s on gfx1201 (0.66 ms a 64 MiB chunk), and a park followed by the next
* model's page-in (the fleet's model swap) waited for the wipe of memory it was about to take
* back: 2.8 s over the fleet bench's sequential plan. A spare counts as free in the card's figure
* (a_props); a commit or allocation the driver cannot give gives the card's spares back first
* (card_has_room, create_handle). A recycled handle holds what its last mapping left; a commit
* reports that, so a caller that needs zeros clears it. */
struct Spare { hsa_amd_vmem_alloc_handle_t h; int64_t bytes; };
std::mutex g_spare_mu;
std::vector<Spare> g_spares[kMaxDevices];
std::atomic<int64_t> g_spare_bytes[kMaxDevices];
bool take_spare(int ord, int64_t bytes, hsa_amd_vmem_alloc_handle_t* h) {
std::lock_guard<std::mutex> lk(g_spare_mu);
std::vector<Spare>& v = g_spares[ord];
for (size_t i = v.size(); i-- > 0;)
if (v[i].bytes == bytes) {
*h = v[i].h;
v.erase(v.begin() + (ptrdiff_t)i);
g_spare_bytes[ord].fetch_sub(bytes, std::memory_order_relaxed);
return true;
}
return false;
}
void put_spare(int ord, hsa_amd_vmem_alloc_handle_t h, int64_t bytes) {
std::lock_guard<std::mutex> lk(g_spare_mu);
g_spares[ord].push_back({ h, bytes });
g_spare_bytes[ord].fetch_add(bytes, std::memory_order_relaxed);
}
/* Gives card `ord`'s spares back to the driver; the bytes. */
int64_t release_spares(int ord) {
std::vector<Spare> v;
{
std::lock_guard<std::mutex> lk(g_spare_mu);
v.swap(g_spares[ord]);
g_spare_bytes[ord].store(0, std::memory_order_relaxed);
}
int64_t n = 0;
for (const Spare& sp : v) {
(void)hsa_amd_vmem_handle_release(sp.h);
n += sp.bytes;
}
return n;
}
/* A device-memory handle of `bytes` on card `ord`. A refusal is retried for up to two seconds,
* with the card's spares given back first: memory given back is counted free by the driver's
* figure at once, but its pages come free only as the wipe reaches them. */
bool create_handle(int ord, hsa_amd_memory_pool_t pool, int64_t bytes, hsa_amd_vmem_alloc_handle_t* h) {
if (hsa_amd_vmem_handle_create(pool, (size_t)bytes, MEMORY_TYPE_NONE, 0, h) == HSA_STATUS_SUCCESS)
return true;
const int64_t gave = ord >= 0 && ord < kMaxDevices ? release_spares(ord) : 0;
const auto until = std::chrono::steady_clock::now() + std::chrono::seconds(2);
while (std::chrono::steady_clock::now() < until) {
std::this_thread::sleep_for(std::chrono::milliseconds(5));
if (hsa_amd_vmem_handle_create(pool, (size_t)bytes, MEMORY_TYPE_NONE, 0, h) == HSA_STATUS_SUCCESS)
return true;
}
device_set_error("vmem: %lld bytes could not be backed on device %d (for two seconds, %s of "
"spares given back; the driver has %s left to give)", (long long)bytes, ord,
humanb(gave).c_str(), humanb(card_available(ord)).c_str());
return false;
}
/* True when card `ord` can take `bytes` more; otherwise false with the refusal set, `what` naming
* the call. If the driver gives no figure the allocation is allowed. */
* the call. If the driver gives no figure the allocation is allowed. Short with spares held, it
* gives them back (the figure counts them at once) and looks again. */
bool card_has_room(int ord, int64_t bytes, const char* what) {
const int64_t avail = card_available(ord);
int64_t avail = card_available(ord);
if (avail < 0) return true;
constexpr int64_t kUnit = (int64_t)2 << 20;
const int64_t need = (bytes + kUnit - 1) / kUnit * kUnit;
if (need <= avail) return true;
if (ord >= 0 && ord < kMaxDevices && release_spares(ord) > 0) {
avail = card_available(ord);
if (avail < 0 || need <= avail) return true;
}
device_set_error("%s(%s) on card %d: the driver has %s left to give on it.%s Memory another "
"process took after the VRAM budget was measured is the usual cause: stop "
"that process, or start this one again once it has gone",
@@ -3477,7 +3803,9 @@ bool card_has_room(int ord, int64_t bytes, const char* what) {
struct VRes { uintptr_t base; uintptr_t end; int ord; };
std::mutex g_vres_mu;
std::vector<VRes> g_vres;
std::unordered_map<uintptr_t, hsa_amd_vmem_alloc_handle_t> g_vmaps;
/* A mapping's handle, and whether it is host memory (vmem_commit_host). */
struct VMap { hsa_amd_vmem_alloc_handle_t h{}; bool host = false; int64_t bytes = 0; };
std::unordered_map<uintptr_t, VMap> g_vmaps;
int vres_ord(const void* addr) {
const uintptr_t a = (uintptr_t)addr;
@@ -3602,12 +3930,11 @@ int a_vmem_commit(void* addr, int64_t bytes) {
if (dev < 0 && hipGetDevice(&dev) != hipSuccess) return RAD_E_DEVICE;
if (dev < 0 || dev >= (int)G().dev.size()) return RAD_E_DEVICE;
const Dev& d = G().dev[(size_t)dev];
if (!card_has_room(dev, bytes, "vmem commit")) return RAD_E_NOMEM;
hsa_amd_vmem_alloc_handle_t h{};
if (hsa_amd_vmem_handle_create(d.vram, (size_t)bytes, MEMORY_TYPE_NONE, 0, &h) !=
HSA_STATUS_SUCCESS) {
device_set_error("vmem: %lld bytes could not be backed on device %d", (long long)bytes, dev);
return RAD_E_NOMEM;
const bool recycled = take_spare(dev, bytes, &h);
if (!recycled) {
if (!card_has_room(dev, bytes, "vmem commit")) return RAD_E_NOMEM;
if (!create_handle(dev, d.vram, bytes, &h)) return RAD_E_NOMEM;
}
if (hsa_amd_vmem_map(addr, (size_t)bytes, 0, h, 0) != HSA_STATUS_SUCCESS) {
(void)hsa_amd_vmem_handle_release(h);
@@ -3621,9 +3948,173 @@ int a_vmem_commit(void* addr, int64_t bytes) {
device_set_error("vmem: device %d could not be given access to %p", dev, addr);
return RAD_E_DEVICE;
}
std::lock_guard<std::mutex> lk(g_vres_mu);
g_vmaps[(uintptr_t)addr] = h;
{
std::lock_guard<std::mutex> lk(g_vres_mu);
g_vmaps[(uintptr_t)addr] = VMap{ h, false, bytes };
}
loc_forget(); /* the range is backed, no longer only reserved */
return recycled ? 1 : RAD_OK;
}
int a_vmem_commit_units(void* addr, int64_t bytes, int64_t unit) {
if (!addr || bytes <= 0 || unit <= 0 || bytes % unit) return RAD_E_INVAL;
int dev = vres_ord(addr);
if (dev < 0 && hipGetDevice(&dev) != hipSuccess) return RAD_E_DEVICE;
if (dev < 0 || dev >= (int)G().dev.size()) return RAD_E_DEVICE;
const Dev& d = G().dev[(size_t)dev];
std::vector<hsa_amd_vmem_alloc_handle_t> hs;
hs.reserve((size_t)(bytes / unit));
/* Spares first, as many as there are; the rest is checked against the driver's figure. */
std::vector<hsa_amd_vmem_alloc_handle_t> spare;
for (int64_t o = 0; o < bytes; o += unit) {
hsa_amd_vmem_alloc_handle_t h{};
if (!take_spare(dev, unit, &h)) break;
spare.push_back(h);
}
const bool recycled = !spare.empty();
const int64_t fresh = bytes - (int64_t)spare.size() * unit;
if (fresh > 0 && !card_has_room(dev, fresh, "vmem commit")) {
for (const auto& h : spare) put_spare(dev, h, unit);
return RAD_E_NOMEM;
}
/* What this call mapped goes again in one unmap; its handles are let go. */
auto undo = [&] {
if (!hs.empty()) (void)hsa_amd_vmem_unmap(addr, hs.size() * (size_t)unit);
for (const auto& h : hs) (void)hsa_amd_vmem_handle_release(h);
for (size_t i = hs.size(); i < spare.size(); ++i) put_spare(dev, spare[i], unit);
};
for (int64_t o = 0; o < bytes; o += unit) {
hsa_amd_vmem_alloc_handle_t h{};
if (hs.size() < spare.size()) {
h = spare[hs.size()];
} else if (!create_handle(dev, d.vram, unit, &h)) {
undo();
return RAD_E_NOMEM;
}
if (hsa_amd_vmem_map((char*)addr + o, (size_t)unit, 0, h, 0) != HSA_STATUS_SUCCESS) {
if (hs.size() < spare.size()) spare.erase(spare.begin() + (ptrdiff_t)hs.size());
(void)hsa_amd_vmem_handle_release(h);
undo();
device_set_error("vmem: a map of %lld bytes at %p failed", (long long)unit, (char*)addr + o);
return RAD_E_DEVICE;
}
hs.push_back(h);
}
const hsa_amd_memory_access_desc_t acc{ HSA_ACCESS_PERMISSION_RW, d.agent };
if (hsa_amd_vmem_set_access(addr, (size_t)bytes, &acc, 1) != HSA_STATUS_SUCCESS) {
undo();
device_set_error("vmem: device %d could not be given access to %p", dev, addr);
return RAD_E_DEVICE;
}
{
std::lock_guard<std::mutex> lk(g_vres_mu);
for (size_t i = 0; i < hs.size(); ++i)
g_vmaps[(uintptr_t)addr + i * (uintptr_t)unit] = VMap{ hs[i], false, unit };
}
loc_forget();
return recycled ? 1 : RAD_OK;
}
/* Access for a mapping at `addr` on card `dev`: the card alone for its own memory; the card and
* the host for host memory, so the host can write a parked copy to disk straight out of it. */
int vmem_grant(void* addr, int64_t bytes, int dev, bool host) {
const Dev& d = G().dev[(size_t)dev];
const hsa_amd_memory_access_desc_t acc[2] = { { HSA_ACCESS_PERMISSION_RW, d.agent },
{ HSA_ACCESS_PERMISSION_RW, G().cpu } };
return hsa_amd_vmem_set_access(addr, (size_t)bytes, acc, host ? 2 : 1) == HSA_STATUS_SUCCESS
? RAD_OK : RAD_E_DEVICE;
}
/* The coarse-grained system pool: the card reads it at the link's full rate (27 GB/s on a
* gfx1201 at PCIe 5 x16, against 15 GB/s from the fine-grained one). Parked weights need no
* coherence with the host while a kernel runs. */
hsa_amd_memory_pool_t* host_coarse_pool() {
static hsa_amd_memory_pool_t pool{};
static bool have = false;
static std::once_flag once;
std::call_once(once, [] {
auto cb = [](hsa_amd_memory_pool_t p, void* data) -> hsa_status_t {
hsa_amd_segment_t seg;
uint32_t flags = 0;
bool alloc = false;
hsa_amd_memory_pool_get_info(p, HSA_AMD_MEMORY_POOL_INFO_SEGMENT, &seg);
if (seg != HSA_AMD_SEGMENT_GLOBAL) return HSA_STATUS_SUCCESS;
hsa_amd_memory_pool_get_info(p, HSA_AMD_MEMORY_POOL_INFO_GLOBAL_FLAGS, &flags);
hsa_amd_memory_pool_get_info(p, HSA_AMD_MEMORY_POOL_INFO_RUNTIME_ALLOC_ALLOWED, &alloc);
auto* out = static_cast<std::pair<hsa_amd_memory_pool_t*, bool*>*>(data);
if (alloc && (flags & HSA_AMD_MEMORY_POOL_GLOBAL_FLAG_COARSE_GRAINED) && !*out->second) {
*out->first = p;
*out->second = true;
}
return HSA_STATUS_SUCCESS;
};
std::pair<hsa_amd_memory_pool_t*, bool*> out{ &pool, &have };
hsa_amd_agent_iterate_memory_pools(G().cpu, cb, &out);
});
return have ? &pool : nullptr;
}
int a_vmem_commit_host(void* addr, int64_t bytes) {
if (!addr || bytes <= 0) return RAD_E_INVAL;
int dev = vres_ord(addr);
if (dev < 0 && hipGetDevice(&dev) != hipSuccess) return RAD_E_DEVICE;
if (dev < 0 || dev >= (int)G().dev.size()) return RAD_E_DEVICE;
hsa_amd_memory_pool_t* pool = host_coarse_pool();
if (!pool) {
device_set_error("vmem: no coarse-grained host memory pool");
return RAD_E_UNSUPPORTED;
}
hsa_amd_vmem_alloc_handle_t h{};
if (hsa_amd_vmem_handle_create(*pool, (size_t)bytes, MEMORY_TYPE_NONE, 0, &h) != HSA_STATUS_SUCCESS) {
device_set_error("vmem: %lld bytes of host memory could not be had", (long long)bytes);
return RAD_E_NOMEM;
}
if (hsa_amd_vmem_map(addr, (size_t)bytes, 0, h, 0) != HSA_STATUS_SUCCESS) {
(void)hsa_amd_vmem_handle_release(h);
device_set_error("vmem: a map of %lld bytes of host memory at %p failed", (long long)bytes, addr);
return RAD_E_DEVICE;
}
if (vmem_grant(addr, bytes, dev, true) < 0) {
(void)hsa_amd_vmem_unmap(addr, (size_t)bytes);
(void)hsa_amd_vmem_handle_release(h);
device_set_error("vmem: device %d could not be given access to host memory at %p", dev, addr);
return RAD_E_DEVICE;
}
{
std::lock_guard<std::mutex> lk(g_vres_mu);
g_vmaps[(uintptr_t)addr] = VMap{ h, true, bytes };
}
loc_forget();
return RAD_OK;
}
int a_vmem_swap(void* a, void* b, int64_t bytes) {
if (!a || !b || bytes <= 0) return RAD_E_INVAL;
const int da = vres_ord(a), db = vres_ord(b);
if (da < 0 || db < 0) return RAD_E_INVAL;
VMap ma, mb;
{
std::lock_guard<std::mutex> lk(g_vres_mu);
auto ia = g_vmaps.find((uintptr_t)a), ib = g_vmaps.find((uintptr_t)b);
if (ia == g_vmaps.end() || ib == g_vmaps.end()) {
device_set_error("vmem: a swap of %p and %p names a range not mapped", a, b);
return RAD_E_INVAL;
}
ma = ia->second;
mb = ib->second;
}
loc_forget();
if (hsa_amd_vmem_unmap(a, (size_t)bytes) != HSA_STATUS_SUCCESS ||
hsa_amd_vmem_unmap(b, (size_t)bytes) != HSA_STATUS_SUCCESS ||
hsa_amd_vmem_map(a, (size_t)bytes, 0, mb.h, 0) != HSA_STATUS_SUCCESS ||
hsa_amd_vmem_map(b, (size_t)bytes, 0, ma.h, 0) != HSA_STATUS_SUCCESS ||
vmem_grant(a, bytes, da, mb.host) < 0 || vmem_grant(b, bytes, db, ma.host) < 0) {
device_set_error("vmem: a swap of %lld bytes at %p and %p failed", (long long)bytes, a, b);
return RAD_E_DEVICE;
}
std::lock_guard<std::mutex> lk(g_vres_mu);
g_vmaps[(uintptr_t)a] = mb;
g_vmaps[(uintptr_t)b] = ma;
return RAD_OK;
}
@@ -3634,21 +4125,68 @@ int a_vmem_protect(void* addr, int64_t bytes) {
int a_vmem_decommit(void* addr, int64_t bytes) {
if (!addr || bytes <= 0) return RAD_E_INVAL;
loc_forget();
hsa_amd_vmem_alloc_handle_t h{};
bool have = false;
/* The mappings that tile the range, front to back. A range they do not tile exactly is the
* one mapping at its start, unmapped as it was mapped. */
std::vector<VMap> hs;
{
std::lock_guard<std::mutex> lk(g_vres_mu);
auto it = g_vmaps.find((uintptr_t)addr);
if (it != g_vmaps.end()) { h = it->second; have = true; g_vmaps.erase(it); }
const uintptr_t a = (uintptr_t)addr, z = a + (uintptr_t)bytes;
std::vector<uintptr_t> keys;
uintptr_t at = a;
while (at < z) {
const auto it = g_vmaps.find(at);
if (it == g_vmaps.end() || it->second.bytes <= 0) break;
keys.push_back(at);
hs.push_back(it->second);
at += (uintptr_t)it->second.bytes;
}
if (at != z) {
keys.clear();
hs.clear();
if (const auto it = g_vmaps.find(a); it != g_vmaps.end()) {
keys.push_back(a);
hs.push_back(it->second);
}
}
for (const uintptr_t k : keys) g_vmaps.erase(k);
}
if (hsa_amd_vmem_unmap(addr, (size_t)bytes) != HSA_STATUS_SUCCESS) {
device_set_error("vmem: an unmap of %lld bytes at %p failed", (long long)bytes, addr);
return RAD_E_DEVICE;
}
if (have) (void)hsa_amd_vmem_handle_release(h);
/* Card memory is kept as spares (see "spare device memory"); host memory goes back. */
const int dev = vres_ord(addr);
for (const VMap& m : hs) {
if (!m.host && dev >= 0 && dev < kMaxDevices) put_spare(dev, m.h, m.bytes);
else (void)hsa_amd_vmem_handle_release(m.h);
}
return RAD_OK;
}
/* Card `ord`'s spares back to the driver, or every card's for -1; the bytes. */
int64_t a_vmem_trim(int ord) {
int64_t n = 0;
for (int d = 0; d < kMaxDevices; ++d)
if (ord < 0 || ord == d) n += release_spares(d);
return n;
}
/* The runtime's figures, with the spares counted as free: they are this process's to map again,
* and any allocation that needs them gives them back first (card_has_room). Free memory is the
* lower of the card's counter and what the driver will still give (card_available), which every
* allocation and commit is checked against: under a fleet's load the driver's figure ran 90-230
* MiB below the counter, past the room plan's headroom, and a restore planned on the counter was
* refused its last commit. The counter is the lower one for a while after a free (it trails). */
int (*g_hip_props)(int, RadDeviceProps*) = nullptr;
int a_props(int device, RadDeviceProps* out) {
const int rc = g_hip_props(device, out);
if (rc >= 0 && device >= 0 && device < kMaxDevices) {
if (const int64_t av = card_available(device); av >= 0 && av < out->vram_free) out->vram_free = av;
out->vram_free += g_spare_bytes[device].load(std::memory_order_relaxed);
}
return rc;
}
/* ------------------------------------------------------------------ pinned host memory, in pieces
*
* Every pinned or mapped host allocation is one address range locked in pieces of at most
@@ -3748,6 +4286,25 @@ const char* hsa_why(hsa_status_t st) {
return hsa_status_string(st, &m) == HSA_STATUS_SUCCESS && m ? m : "unknown HSA status";
}
/* Faults [p, p + len) in from several threads before the lock takes it. The lock faults what is
* not yet present on the calling thread, page by page, and the kernel's zeroing of fresh pages
* is most of a lock's cost: a 4 GiB pin takes 0.33 s locked as it is, 0.21 s faulted in by four
* threads first (13 -> 20 GB/s; a 64 MiB pin 4.4 -> 2.2 ms). Locking the pieces in parallel
* gains nothing, the driver serialises them. Small ranges are not worth a thread. */
void prefault(char* p, int64_t len) {
constexpr int64_t kMin = (int64_t)16 << 20;
constexpr int kThreads = 4;
if (len < kMin) return;
const int64_t per = align_up((len + kThreads - 1) / kThreads, (int64_t)RAD_ALIGN_POOL);
auto touch = [p, len](int64_t lo, int64_t hi) {
for (int64_t o = lo; o < std::min(hi, len); o += 4096) ((volatile char*)p)[o] = 0;
};
std::thread th[kThreads - 1];
for (int t = 1; t < kThreads; ++t) th[t - 1] = std::thread(touch, t * per, (t + 1) * per);
touch(0, per);
for (std::thread& x : th) if (x.joinable()) x.join();
}
/* Whether the driver offers the SVM API, so a locked piece is mapped in place. */
bool svm_in_place() {
static const bool on = [] {
@@ -3856,6 +4413,7 @@ void* pin_pieces(int64_t bytes) {
warn_if_no_huge_pages();
}
(void)::madvise(p, (size_t)len, MADV_DONTFORK);
prefault(p, len);
if (!lock_pieces(p, len, bytes, cards, "rad_dev_alloc")) {
::munmap(p, (size_t)len);
@@ -4074,6 +4632,11 @@ const DeviceBackend* aql_backend_if_present(void) {
g_hip_free = hip->free;
g_hip_host_ptr = hip->host_ptr;
g_hip_device_ptr = hip->device_ptr;
g_hip_props = hip->props;
g_aql.props = a_props;
g_aql.vmem_trim = a_vmem_trim;
g_aql.stream_counts = a_stream_counts;
g_aql.stream_trim = a_stream_trim;
g_aql.alloc = a_alloc;
g_aql.map_file = a_map_file;
g_aql.free = a_free;
@@ -4097,6 +4660,8 @@ const DeviceBackend* aql_backend_if_present(void) {
g_aql.memcpy_list_async = a_memcpy_list_async;
g_aql.link_hold = a_link_hold;
g_aql.link_gate = a_link_gate;
g_aql.peer_launch = a_peer_launch;
g_aql.cards_claim = a_cards_claim;
g_aql.xp_supported = a_xp_supported;
g_aql.xp_stream_create = a_xp_stream_create;
g_aql.ride = a_ride;
@@ -4112,8 +4677,11 @@ const DeviceBackend* aql_backend_if_present(void) {
g_aql.vmem_reserve = a_vmem_reserve;
g_aql.vmem_release = a_vmem_release;
g_aql.vmem_commit = a_vmem_commit;
g_aql.vmem_commit_units = a_vmem_commit_units;
g_aql.vmem_decommit = a_vmem_decommit;
g_aql.vmem_protect = a_vmem_protect;
g_aql.vmem_commit_host = a_vmem_commit_host;
g_aql.vmem_swap = a_vmem_swap;
g_aql.tape_begin = a_tape_begin;
g_aql.tape_mark = a_tape_mark;
g_aql.tape_pause = a_tape_pause;
@@ -4200,6 +4768,14 @@ void __hipRegisterFunction(void** modules, const void* host_fn, char* device_fn,
auto it = r.by_handle.find(modules);
if (it == r.by_handle.end() || !host_fn || !device_name) return;
Func*& f = r.by_stub[host_fn];
/* A plugin closed when its model unloaded leaves its stubs here. The same library loaded again
* names the same kernels and keeps their records, whose code is still loaded. Another library
* could map a different kernel at the same address, which must not inherit the old record. */
if (f && f->name != device_name) {
RAD_WARN("device: a kernel stub at %p now names %s, not %s", host_fn, device_name, f->name.c_str());
f = nullptr;
g_stub_epoch.fetch_add(1, std::memory_order_release);
}
if (!f) f = new Func();
f->mod = it->second;
f->name = device_name;
+20
View File
@@ -14,6 +14,7 @@
#include <cstdint>
#include "aql.h"
#include "chain_kernel.h"
#include "device.h"
namespace {
@@ -36,6 +37,22 @@ __global__ __launch_bounds__(kThreads) void aql_copy16(const u32x4* __restrict__
for (; i < n; i += stride) dst[i] = src[i];
}
/* aql_copy16 as a chained form (chain_kernel.h), launched where launches chain: a card-side copy
* between two kernels of a pass (a routed layer's counts into the core's row) then costs no
* barrier on either side. */
__global__ __launch_bounds__(kThreads) void r4dchain_copy16(const u32x4* __restrict__ src,
u32x4* __restrict__ dst, uint64_t n) {
rad_chain_wait();
const uint64_t stride = (uint64_t)gridDim.x * kThreads;
uint64_t i = (uint64_t)blockIdx.x * kThreads + threadIdx.x;
for (; i + 3 * stride < n; i += 4 * stride) {
const u32x4 a = src[i], b = src[i + stride], c = src[i + 2 * stride], d = src[i + 3 * stride];
dst[i] = a; dst[i + stride] = b; dst[i + 2 * stride] = c; dst[i + 3 * stride] = d;
}
for (; i < n; i += stride) dst[i] = src[i];
rad_chain_done();
}
/* A copy across the link (pinned host memory) is one workgroup of four waves.
*
* The link delivers ~29 GB/s regardless of grid size, so the copy should hold as few waves as
@@ -190,6 +207,9 @@ extern "C" int rad_aql_blit_copy(void* dst, const void* src, uint64_t bytes, voi
if (link)
hipLaunchKernelGGL(aql_copy_link, dim3(1), dim3(kLinkThreads), 0, s,
(const u32x4*)src, (u32x4*)dst, n);
else if (rad_dev_chain_enabled())
hipLaunchKernelGGL(r4dchain_copy16, dim3(blocks_for(n, 4 * kThreads)), dim3(kThreads),
0, s, (const u32x4*)src, (u32x4*)dst, n);
else
hipLaunchKernelGGL(aql_copy16, dim3(blocks_for(n, 4 * kThreads)), dim3(kThreads), 0,
s, (const u32x4*)src, (u32x4*)dst, n);
+49
View File
@@ -0,0 +1,49 @@
/* chain_kernel.h -- the chained form's wait and completion for the core's own kernels
* (RadKernelChainFn, abi/rad_abi.h).
*
* The backend gives a kernel named r4dchain* a record at RAD_CHAIN_KARG_OFF and drops its barrier
* bit behind another chained kernel. Before the first read one lane waits for the queue's counter
* to reach the record's target; after the last write the block releases and adds 1. A record that
* does not check out means: run plain. Every block must reach rad_chain_done exactly once.
*/
#pragma once
#include <hip/hip_runtime.h>
#include <cstdint>
#include "rad_abi.h"
struct RadChainRec {
unsigned long long magic, target;
unsigned long long* ctr;
unsigned long long check;
};
__device__ __forceinline__ const RadChainRec* rad_chain_rec() {
const RadChainRec* r = (const RadChainRec*)((const char*)__builtin_amdgcn_kernarg_segment_ptr() +
RAD_CHAIN_KARG_OFF);
const unsigned long long magic = r->magic, target = r->target, check = r->check;
if (magic != RAD_CHAIN_MAGIC ||
check != (magic ^ target ^ (unsigned long long)(uintptr_t)r->ctr ^ RAD_CHAIN_CHECK))
return nullptr;
return r;
}
__device__ __forceinline__ void rad_chain_wait() {
const RadChainRec* r = rad_chain_rec();
if (!r) return;
if (threadIdx.x == 0 && threadIdx.y == 0 && threadIdx.z == 0)
while (__hip_atomic_load(r->ctr, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT) < r->target)
__builtin_amdgcn_s_sleep(1);
__syncthreads();
__builtin_amdgcn_fence(__ATOMIC_ACQUIRE, "agent");
}
__device__ __forceinline__ void rad_chain_done() {
const RadChainRec* r = rad_chain_rec();
if (!r) return;
__builtin_amdgcn_fence(__ATOMIC_RELEASE, "agent");
__syncthreads();
if (threadIdx.x == 0 && threadIdx.y == 0 && threadIdx.z == 0)
__hip_atomic_fetch_add(r->ctr, 1ull, __ATOMIC_RELEASE, __HIP_MEMORY_SCOPE_AGENT);
}
+315 -6
View File
@@ -13,6 +13,8 @@
#include "rad_device.h"
#include <cstdint>
#include <map>
#include <functional>
#include <string>
#include <utility>
#include <vector>
@@ -39,8 +41,8 @@ extern "C" void rad_dev_host_wrote(void);
/* Chained launches: chainable rows run their chained forms (RadKernelChainFn), and the backend
* lets a chained kernel (named r4dchain*) wait in its prologue instead of behind the barrier bit.
* Only on the AQL backend, whose queues keep the completion counter, and only where the model's
* plugin measured a gain with its speculative drafter (RadArchProbe::chain_pays) and that drafter
* decodes speculatively (rad_dev_chain_infer, from the engine before any row resolves). */
* plugin measured a gain (RadArchProbe::chain_pays): with its drafter decoding speculatively, or
* with and without one (rad_dev_chain_infer, from the engine before any row resolves). */
extern "C" int rad_dev_chain_enabled(void);
extern "C" void rad_dev_chain_infer(int pays);
@@ -91,6 +93,17 @@ extern "C" int rad_memcpy_list_async(const RadCopySeg* segs, int n, unsigned fla
* copies; the step waits on the collective, while the copies have the rest of the layer. */
extern "C" int rad_link_hold(RadStream s, int on);
/* The launches this thread issues between `on` 1 and `on` 0 are a collective's: their blocks wait
* for the other ranks' blocks of the same launch on another card. A recorded pass keeps the mark.
*
* rad_dev_cards_claim tells the backend which cards an engine's collectives run on (`on` 1, once
* per engine with more than one rank) and that the engine is gone (`on` 0). On a card more than one
* engine has claimed, nothing may wait on the card behind a collective except the collective's own
* blocks (aql.cpp, "collectives on a shared card"). A claim that makes a card shared returns once
* everything issued before it on that card's streams has finished. */
extern "C" void rad_dev_peer_launch(int on);
extern "C" int rad_dev_cards_claim(const int* cards, int n, int on);
/* The hold word, for a launch that ends its own hold: a 64-bit word reachable by every engine and
* kernel of the card, odd while the link is held. A launch handed this address releases the hold
* by decrementing the word once, only if odd, as soon as its awaited bytes have landed; follow it
@@ -280,9 +293,14 @@ struct DeviceBackend {
*
* Contract:
* `vmem_reserve` takes address space, no pages.
* `vmem_commit` backs one granule and `vmem_decommit` unbacks one. The driver unmaps a
* mapping only exactly as it was mapped (four granules mapped in one call cannot be unmapped
* singly), so VMem issues one call per granule.
* `vmem_commit` backs one granule. The driver unmaps a mapping only exactly as it was
* mapped (four granules mapped as one cannot be unmapped singly), so VMem maps a mapping per
* granule, a run of them in one `vmem_commit_units` call where the backend has it. It
* returns 1 when the backing is recycled memory that holds what its last mapping left, 0
* when it reads zero.
* `vmem_decommit` unbacks a range that is one mapping or a contiguous run of whole ones, in
* one unmap: each unmap costs a driver round trip that grows with the mappings the process
* holds (8.8 us a granule alone, 48 beside 6000 others; 26 for a run, per granule).
* `vmem_protect` grants this device read/write access to an already-backed range. It is
* separate from commit because access set on a granule adjacent to an accessible one is
* refused, while the whole contiguous run is accepted; VMem names the run.
@@ -355,6 +373,36 @@ struct DeviceBackend {
/* ---- see dev_stuck_ms. Null on a backend that cannot tell. */
int64_t (*stuck_ms)(void);
/* ---- host-backed mappings, for parking (paging.cpp). `vmem_commit_host` backs a reserved
* granule with pinned host memory that the reservation's card reads and writes in place, at
* that address, and the host can too. `vmem_swap` exchanges what backs two mapped ranges of
* equal size (each keeps its kind: a range of device memory stays device memory wherever it
* is mapped). Remapped addresses need dev_settle_maps before the card writes them. Null on a
* backend without them; parking then keeps no host copies. */
int (*vmem_commit_host)(void* addr, int64_t bytes);
int (*vmem_swap)(void* a, void* b, int64_t bytes);
/* ---- [addr, addr + bytes) backed as one mapping per `unit` bytes, each of which can be
* unbacked alone later, with access granted once over the run: per granule, granting access
* costs about as much as the map (41.9 us a granule backed singly, 24.6 as a run). All or
* nothing: on failure nothing of the run stays backed. Null: VMem backs a granule at a time. */
int (*vmem_commit_units)(void* addr, int64_t bytes, int64_t unit);
/* ---- device memory a decommit kept for the next commit of its size (counted as free in
* props), given back to the driver: card `device`'s, or every card's for -1; the bytes. Null
* on a backend that keeps none. */
int64_t (*vmem_trim)(int device);
/* rad_dev_peer_launch and rad_dev_cards_claim. Null on a backend that never launches a kernel
* ahead of the one before it. */
void (*peer_launch)(int on);
int (*cards_claim)(const int* cards, int n, int on);
/* ---- the hardware queues card `device` has open and how many of them no stream holds (a
* closed stream's queue is kept for the card's next stream); and the kept ones destroyed
* until `keep` are left, the number destroyed, none while any queue of the card holds a
* packet. Null on a backend that keeps none. */
void (*stream_counts)(int device, int* open, int* idle);
int (*stream_trim)(int device, int keep);
};
@@ -411,12 +459,44 @@ constexpr int kTapeOverlapRun = 6;
* kernel plugin that calls hipMalloc directly; see the ledger in dispatch.cpp. */
void rad_dev_alloc_totals(int kind, int64_t* bytes, int64_t* count);
/* `fn` is called after every device-memory free (RAD_MEM_DEVICE) with the range freed: a kernel
* library's rad_plugin_freed (abi/rad_abi.h), registered by the plugin loader. Registrations are
* counted: every registry that loads the library registers its hook, and rad_dev_off_free, which
* the loader calls before it closes the library, takes one back. The hook goes with the last,
* once no free is calling it: a library opened again can land at another address, and a hook
* left behind would call into memory nothing maps. */
void rad_dev_on_free(void (*fn)(const void* base, int64_t bytes));
void rad_dev_off_free(void (*fn)(const void* base, int64_t bytes));
/* Event handles created and not yet destroyed, process-wide. */
int64_t rad_dev_live_events(void);
/* Calls to rad_event_sync and rad_stream_sync since process start, from any thread: the host
* blocks the ABI makes. */
int64_t rad_dev_host_blocks(void);
/* A parked allocation's contents (docs/MULTIMODEL.md §7): in pinned host memory, in a file of the
* disk tier, or both. A copy written to disk can let its host memory go and be read back later. */
struct HostCopy {
void* host = nullptr; /* pinned, `bytes` rounded up to the direct-I/O block */
int64_t bytes = 0;
std::string file; /* the disk tier's copy, when written */
bool on_disk = false; /* `file` holds exactly what `host` holds (or held) */
int64_t ram() const { return host ? bytes : 0; }
/* Pinned memory for `n` bytes; what the copy held before, host memory and file, is freed. */
int alloc(int64_t n);
/* Writes the host bytes to a new file under `dir` (O_DIRECT). Between pieces it asks `gate`
* (when given): 0 goes on, 1 waits (a model loading reads its container from the same drive),
* -1 abandons the write (RAD_E_STATE, no file left). */
int spill(const std::string& dir, const std::function<int()>& gate = {});
/* Frees the host memory of a copy that is on disk. */
void drop_host();
/* Reads the file back into fresh pinned memory when the host copy is gone. */
int load();
/* Frees everything: the host memory and the file. */
void release();
};
/* ------------------------------------------------------------------ elastic memory
* One reserved address range and which granules inside it are backed.
*
@@ -444,10 +524,15 @@ public:
/* Movable, since owners live in vectors. The source is left empty so its destructor does not
* unmap the range the destination now owns. */
VMem(VMem&& o) noexcept
: base_(o.base_), size_(o.size_), committed_(o.committed_), ext_(std::move(o.ext_)) {
: base_(o.base_), size_(o.size_), committed_(o.committed_), ext_(std::move(o.ext_)),
device_(o.device_), copy_(std::move(o.copy_)), parked_(std::move(o.parked_)),
discarded_(o.discarded_) {
rekey(&o, this);
o.base_ = nullptr;
o.size_ = o.committed_ = 0;
o.ext_.clear();
o.copy_ = HostCopy{};
o.parked_.clear();
}
VMem& operator=(VMem&& o) noexcept {
if (this != &o) {
@@ -456,9 +541,16 @@ public:
size_ = o.size_;
committed_ = o.committed_;
ext_ = std::move(o.ext_);
device_ = o.device_;
copy_ = std::move(o.copy_);
parked_ = std::move(o.parked_);
discarded_ = o.discarded_;
rekey(&o, this);
o.base_ = nullptr;
o.size_ = o.committed_ = 0;
o.ext_.clear();
o.copy_ = HostCopy{};
o.parked_.clear();
}
return *this;
}
@@ -482,19 +574,236 @@ public:
* kernel. */
bool is_committed(int64_t off, int64_t bytes) const;
/* Parking (dev_page_out): every backed extent copied to pinned host memory on `s`, then
* unbacked; the bytes held on the host, or an error. page_in backs the same extents again and
* copies them back. With `discard` nothing in the range is kept (a cache with no live
* sequence and its index reset): page_out copies nothing and returns 0, and page_in backs the
* extents again without copying anything back. */
int64_t page_out(RadStream s, bool discard = false);
int page_in(RadStream s);
bool parked() const { return !parked_.empty(); }
int64_t parked_bytes() const {
int64_t n = 0;
for (const auto& e : parked_) n += e.second;
return n;
}
/* The card the range was reserved on, for the copies' stream. */
int device() const { return device_; }
/* Host bytes held for the parked extents (zero once they live only on disk). */
int64_t host_bytes() const { return parked_.empty() ? 0 : copy_.ram(); }
/* The disk tier (dev_page_spill): write the parked copy out, or let its host memory go. */
int spill(const std::string& dir, const std::function<int()>& gate = {}) {
return parked_.empty() ? RAD_OK : copy_.spill(dir, gate);
}
int64_t drop_host() {
if (parked_.empty() || !copy_.on_disk || !copy_.host) return 0;
const int64_t n = copy_.bytes;
copy_.drop_host();
return n;
}
private:
/* The owner registry follows the object when it moves (reserve() files it under the thread's
* engine owner). */
static void rekey(VMem* from, VMem* to);
void* base_ = nullptr;
int64_t size_ = 0;
int64_t committed_ = 0;
/* Backed extents (offset, bytes): sorted, disjoint and never adjacent, since a touching
* commit merges. Length tracks live regions, not calls. */
std::vector<std::pair<int64_t, int64_t>> ext_;
int device_ = 0;
HostCopy copy_; /* parked: the extents' contents */
std::vector<std::pair<int64_t, int64_t>> parked_; /* parked: the extents to back again */
bool discarded_ = false; /* parked without a copy */
/* Adds a newly mapped piece and merges it with whatever it touches. */
void add_extent(int64_t off, int64_t bytes);
void drop_extent(int64_t off, int64_t bytes);
};
/* ------------------------------------------------------------------ parking (paging.cpp)
* docs/MULTIMODEL.md §7. A device allocation of 2 MiB or more made on a thread working for an
* engine (engine_owner, rad_internal.h) is reserved as one address range and mapped in chunks, and
* an elastic range reserved on such a thread is filed under the engine too, so the engine's memory
* can leave the card in part or whole and come back at the same addresses.
*
* A chunk out of the card is somewhere else: in pinned host memory, in a file of the disk tier,
* both, or nowhere when it was discarded (its contents not needed: an expert slab's free slots).
* Restoring maps every chunk out and copies back the ones that had a copy. The engine must be
* quiet for both: nothing it issued still runs, nothing new is issued until the page-in. */
constexpr int64_t kPageMin = (int64_t)2 << 20;
/* For rad_dev_alloc and rad_dev_free: an engine's pageable allocation, and its release (false when
* `p` is not one). */
void* page_alloc(int64_t bytes, int owner, int device);
bool page_free(void* p);
/* Device bytes `owner` holds on card `device`: its allocations and elastic backing (a load in
* flight, for the fleet's reservation). */
int64_t dev_owner_bytes(int owner, int device);
/* The backend rad_dev_* calls go to. */
const DeviceBackend* active_backend();
/* The owner's elastic ranges (dispatch.cpp's registry). */
std::vector<VMem*> vmems_of(int owner);
struct PageOut {
/* Bytes to take off each card; empty takes everything. */
std::map<int, int64_t> want;
/* New host memory the copies may take; past it they go to `dir`, and without a `dir` the
* page-out stops there. */
int64_t host_budget = INT64_MAX;
std::string dir;
/* The elastic ranges (the KV cache) are dropped, not copied. */
bool discard_elastic = false;
};
struct PageResult {
std::map<int, int64_t> freed; /* bytes unmapped on each card */
int64_t host = 0; /* host bytes the copies took */
int64_t disk = 0; /* bytes written straight to the disk tier */
int64_t dropped = 0; /* bytes unmapped with nothing kept (discarded) */
int64_t reused = 0; /* bytes unmapped against a copy made earlier */
int64_t file = 0; /* bytes unmapped against the container they were loaded from */
double quiet_s = 0; /* the engine coming to rest (responses drained, loop held) */
double slab_s = 0; /* lent slots recalled and the expert slab emptied */
double out_s = 0; /* the page-out itself */
};
int dev_page_out(int owner, const PageOut& req, PageResult* out);
/* A stretch of memory a page-in mapped for its owner to fill (dev_page_refilled). */
struct PageSpan { char* p; int64_t bytes; int device; };
/* Every chunk of the owner that is out comes back. Those of an allocation the owner refills are
* only mapped, and appended to `refill` for the owner to fill before anything reads them; a
* page-in with such chunks out and no `refill` fails (RAD_E_STATE) and maps nothing. */
int dev_page_in(int owner, std::vector<PageSpan>* refill = nullptr, bool elastic = true);
/* The owner's elastic ranges backed again (and their copies, if they were kept), what a page-in
* does last; then the cards' translations settled. A page-in with `elastic` false leaves this to
* the caller, which can run it beside the refill: nothing of the refill reads those ranges, and
* an image model's KV cache is ten thousand commits (0.5 s). */
int dev_page_in_elastic(int owner);
/* The owner's chunks wholly inside these ranges hold nothing that needs keeping: the next page-out
* unmaps them first and copies nothing (an expert slab's slots after it dropped its units). */
void dev_page_discard(int owner, const std::vector<std::pair<const void*, int64_t>>& ranges);
/* Bytes mapped on cards, and bytes of host copies (parked or kept). */
void dev_page_stats(int owner, int64_t* device, int64_t* host);
/* Bytes of the owner's pageable memory still on each card. */
std::map<int, int64_t> dev_page_mapped_bytes(int owner);
/* Bytes the owner has out of the card right now, by card. With `live`, only what dev_page_in_live
* would map: the sealed chunks parked in host memory stay out of the sum, read in place. */
std::map<int, int64_t> dev_page_out_bytes(int owner, bool live = false);
/* [off, off + bytes) of the pageable allocation `p` (all of it for bytes < 0) is never written after
* the load (a static plan's weights pool, a tiered one's statics): a copy, once made, is kept after
* the page-in, and later page-outs of those chunks only unmap. */
void dev_page_seal(void* p, int64_t off = 0, int64_t bytes = -1);
/* The pageable allocation `p` is rebuilt by its owner from its source (a weights pool from its
* container) after a page-in: its sealed chunks leave the card with no copy at all, an unmap, and
* dev_page_in hands them back to be filled. Its chunks are no longer checked against the
* container (dev_page_source). */
void dev_page_refilled(void* p);
/* [p, p + bytes) is being written (an expert moved into a slab slot): the kept copies of the
* chunks it touches are stale. A no-op for memory that is not pageable. Called when the write is
* issued and again when it lands, so a copy made across it is never taken as exact. */
void dev_page_invalidate(const void* p, int64_t bytes);
/* Memory mapped again at an address that was mapped before (a page-in, a pool growing back) is not
* written until the cards' translation caches have been flushed in full: a map flushes them only
* lightly, and copies into such memory can land nowhere, so the memory reads back its previous
* owner's bytes or zeros (Linux 7.1 with gfx1201; tests/device_test.cpp
* two_allocations_of_one_owner_come_back_exact_from_the_disk_tier). Unpinning host memory makes
* the driver flush every card it was mapped on in full, so this pins one page and unpins it.
* Called after a batch of maps, before anything writes them. */
/* Where address `a` lies among the elastic reservations and pageable allocations, for a fault report:
* its owner, card, offset, whether it is backed and what its paging chunk holds. Empty when it is in
* none. Takes no lock it would wait for, since a fault can arrive while one is held. */
std::string dev_fault_where(const void* a);
int dev_settle_maps();
/* VMem::commit on this thread leaves its flush (dev_settle_maps) for the end of this scope, so a
* run of ranges mapped together flushes once. Nothing may write the new ranges before end(), which
* reports the flush's result; the destructor ends a batch left open by an early return. */
class MapBatch {
public:
MapBatch();
~MapBatch();
MapBatch(const MapBatch&) = delete;
MapBatch& operator=(const MapBatch&) = delete;
int end();
private:
bool ended_ = false;
};
/* The backend's kept device memory on card `device` (-1: every card) back to the driver, the
* bytes; its pages come free as the driver wipes them (~95 GB/s). For a caller about to allocate
* outside the elastic calls, or done with the swap that would have reused it. */
int64_t dev_vmem_trim(int device);
/* The hardware queues card `device` has open, and how many of them are kept for its next streams
* (0 and 0 on a backend that keeps none). */
void dev_stream_counts(int device, int* open, int* idle);
/* Card `device`'s kept queues destroyed until `keep` are left: the number destroyed, about 41 MiB
* of the card each. Nothing is destroyed while any queue of the card holds a packet, and the
* caller sees to it that nothing is launched on the card during the call: destroying a queue
* beside a busy one can reset the card. */
int dev_stream_trim(int device, int keep);
/* The device this thread last selected with rad_dev_set. */
int dev_current();
/* The container at `path`, by an id for dev_page_source (the same path gives the same id). */
int dev_page_file(const char* path);
/* The load copied container `file`'s rows [0, ny) of wb bytes at foff + y * sp verbatim onto
* [dst, dst + ny * wb). A chunk of pageable memory filled this way can go out against the container
* instead of a copy: a page-out (or backup) reads the device bytes back, compares them with the
* container (zero where nothing was loaded) and writes nothing when they match; the page-in reads
* the container. A chunk written since (dev_page_invalidate) is copied as any other. A no-op for
* memory that is not pageable. */
void dev_page_source(const void* dst, int file, int64_t foff, int64_t wb, int64_t ny, int64_t sp);
/* Bytes of the owner's mapped chunks a page-out would have to copy (no discard, no kept copy,
* not loaded verbatim from a container, not refilled by the owner). */
int64_t dev_page_uncopied(int owner);
/* A restore that serves at once: like dev_page_in, but a sealed chunk parked in host memory stays
* there, read in place over the link, until dev_page_promote moves it; *left is how much. */
int dev_page_in_live(int owner, int64_t* left, std::vector<PageSpan>* refill = nullptr,
bool elastic = true);
/* dev_page_in (`left` null) or dev_page_in_live in two halves, for an owner that refills: the begin
* maps every chunk, hands back those to refill and starts the copies of the chunks held in host
* memory; the end waits for those copies and swaps their memory in, and must follow every begin
* that succeeded. The refill runs between the two, beside the copies: it writes none of those
* chunks. Elastic ranges are left to dev_page_in_elastic. */
int dev_page_in_begin(int owner, int64_t* left, std::vector<PageSpan>* refill);
int dev_page_in_end(int owner);
/* Between the two halves: waits for the clears the begin issued on recycled refill chunks, which
* it does not wait for itself. The refill calls it before its first write into them; the end
* waits for them too. The calling thread's current device is kept. */
int dev_page_in_cleared(int owner);
/* Moves up to `max_bytes` of the chunks dev_page_in_live left in host memory onto their cards,
* while the engine serves: each is copied to device memory first, then `quiet` runs the swap of
* mappings with nothing of the engine in flight (Engine::run_quiet). Returns the bytes moved, 0
* when none is left, or an error (no device memory for them: the rest stays in host memory). */
int64_t dev_page_promote(int owner, int64_t max_bytes,
const std::function<int(const std::function<int()>&)>& quiet);
/* Bytes of `owner`'s chunks served from host memory in place, on `device` (-1: all). */
int64_t dev_page_live_bytes(int owner, int device = -1);
/* Host memory all parked and kept copies hold (they are host-backed mappings, not pinned
* allocations, so rad_dev_alloc_totals does not count them). */
int64_t dev_page_host_bytes();
/* Frees host copies of mapped sealed chunks (a file copy stays). The host bytes freed. */
int64_t dev_page_drop_copies(int owner);
/* Writes every host copy without a file copy to the disk tier; `gate` as HostCopy::spill. */
int64_t dev_page_spill(int owner, const std::string& dir, const std::function<int()>& gate = {});
/* Frees host copies that have a file copy. The host bytes freed. */
int64_t dev_page_drop_host(int owner);
/* A parked owner's chunks whose only copy is the disk tier or its container: their bytes. */
int64_t dev_page_fillable(int owner);
/* The owner's parked chunks of allocations it refills that have no host memory yet, one span a
* chunk, in address order. */
std::vector<PageSpan> dev_page_refill_chunks(int owner);
/* A host fill by the owner (Engine::fill_host): host memory mapped at each of these chunks (from
* dev_page_refill_chunks), as a park to host memory leaves a chunk, for the owner to fill from its
* source; then dev_page_fill_end: `filled`, the chunks' host copies are theirs and the next restore
* copies them over the link (exact until written, so a later park keeps them); otherwise the host
* memory goes again and the chunks stay to be refilled. */
int dev_page_fill_begin(int owner, const std::vector<PageSpan>& chunks);
void dev_page_fill_end(int owner, const std::vector<PageSpan>& chunks, bool filled);
/* Up to max_bytes of those read into host memory and mapped at their own addresses, as a park to
* host memory leaves them, so the next restore copies over the link instead of reading the drive
* (and a live restore serves from them in place). The owner must be parked and idle. Returns the
* bytes filled, or a negative status. */
int64_t dev_page_fill_host(int owner, int64_t max_bytes);
/* Bytes backed by every VMem in the process, for Engine::start's receipt. VMem commits bypass the
* rad_dev_alloc ledger, so without this the engine's accounting would miss the elastic pools. */
int64_t rad_dev_vmem_committed(void);
+411 -43
View File
@@ -7,6 +7,7 @@
* with ROCm headers and no /dev/kfd); the chosen backend is logged at Info.
*/
#include "device.h"
#include "directio.h"
#include "../rad_internal.h"
#include <algorithm>
@@ -18,10 +19,18 @@
#include <iterator>
#include <map>
#include <mutex>
#include <shared_mutex>
#include <unordered_map>
#include <string>
#include <utility>
#include <vector>
#include <thread>
#include <chrono>
#include <cstdint>
#include <unistd.h>
/* The device rad_dev_set last bound on this thread. */
static thread_local int t_device = 0;
namespace rad {
@@ -147,24 +156,43 @@ Ledger g_ledger[4]; /* indexed by RAD_MEM_*; rad_dev_alloc bounds the kin
/* Each live allocation's size, so rad_dev_free (which has none) takes it back off the ledger's
* bytes: pinned ranges are freed and taken again during bring-up, and the pin-cap check reads the
* ledger as what the process holds. Allocations are rare, never per step. */
struct LiveAlloc { int64_t bytes; int kind; };
struct LiveAlloc { int64_t bytes; int kind; int owner; int device; };
/* Device bytes each engine holds on each card (dev_owner_bytes): its rad_dev_alloc allocations and
* its elastic ranges' backing. */
std::mutex g_owner_mu;
std::map<std::pair<int, int>, int64_t> g_owner_bytes;
void owner_add(int owner, int device, int64_t n) {
if (owner <= 0 || n == 0) return;
std::lock_guard<std::mutex> lk(g_owner_mu);
g_owner_bytes[{ owner, device }] += n;
}
std::mutex g_ledger_mu;
std::unordered_map<void*, LiveAlloc> g_ledger_live;
void ledger_add(void* p, int64_t bytes, int kind) {
void ledger_add(void* p, int64_t bytes, int kind, int owner, int device) {
g_ledger[kind].bytes.fetch_add(bytes, std::memory_order_relaxed);
if (kind == RAD_MEM_DEVICE) owner_add(owner, device, bytes);
std::lock_guard<std::mutex> lk(g_ledger_mu);
g_ledger_live[p] = LiveAlloc{ bytes, kind };
g_ledger_live[p] = LiveAlloc{ bytes, kind, owner, device };
}
void ledger_drop(void* p) {
if (!p) return;
/* The allocation's bytes, or 0 when the ledger does not know it. */
int64_t ledger_drop(void* p) {
if (!p) return 0;
std::lock_guard<std::mutex> lk(g_ledger_mu);
const auto it = g_ledger_live.find(p);
if (it == g_ledger_live.end()) return;
g_ledger[it->second.kind].bytes.fetch_sub(it->second.bytes, std::memory_order_relaxed);
if (it == g_ledger_live.end()) return 0;
const int64_t bytes = it->second.bytes;
g_ledger[it->second.kind].bytes.fetch_sub(bytes, std::memory_order_relaxed);
if (it->second.kind == RAD_MEM_DEVICE) owner_add(it->second.owner, it->second.device, -bytes);
g_ledger_live.erase(it);
return bytes;
}
/* rad_dev_on_free's hooks and how many registrations each has. Registered at plugin load and
* read on every device free, which holds the lock shared while it calls them. */
std::shared_mutex g_free_hooks_mu;
std::vector<std::pair<void (*)(const void*, int64_t), int>> g_free_hooks;
/* Live event handles, counted here so the number is backend-independent; the only place an
* event leaked at teardown shows. */
std::atomic<int64_t> g_live_events{0};
@@ -224,6 +252,24 @@ const char* kind_name(int kind) {
} /* namespace */
void rad_dev_on_free(void (*fn)(const void* base, int64_t bytes)) {
if (!fn) return;
std::unique_lock<std::shared_mutex> lk(g_free_hooks_mu);
for (auto& h : g_free_hooks)
if (h.first == fn) { ++h.second; return; }
g_free_hooks.push_back({ fn, 1 });
}
void rad_dev_off_free(void (*fn)(const void* base, int64_t bytes)) {
if (!fn) return;
std::unique_lock<std::shared_mutex> lk(g_free_hooks_mu);
for (auto it = g_free_hooks.begin(); it != g_free_hooks.end(); ++it)
if (it->first == fn) {
if (--it->second == 0) g_free_hooks.erase(it);
return;
}
}
void rad_dev_alloc_totals(int kind, int64_t* bytes, int64_t* count) {
if (kind < 0 || kind >= (int)std::size(g_ledger)) {
if (bytes) *bytes = 0;
@@ -243,8 +289,19 @@ int64_t rad_dev_host_blocks(void) { return g_host_blocks.load(std::memory_order_
namespace {
std::atomic<int64_t> g_vmem_committed{0};
/* Elastic ranges (VMem) reserved on a thread working for an engine are filed under it, so its
* park (paging.cpp) finds them. */
std::mutex g_page_mu;
std::map<VMem*, int> g_vmem_owner;
} /* namespace */
static int vmem_owner_of(const VMem* v) {
std::lock_guard<std::mutex> lk(g_page_mu);
auto it = g_vmem_owner.find(const_cast<VMem*>(v));
return it == g_vmem_owner.end() ? 0 : it->second;
}
int64_t rad_dev_vmem_committed(void) { return g_vmem_committed.load(std::memory_order_relaxed); }
/* Both checks: a backend may have the entries on a driver with no virtual memory manager
@@ -274,18 +331,34 @@ int VMem::reserve(int64_t bytes, int64_t align) {
size_ = want;
committed_ = 0;
ext_.clear();
device_ = t_device;
if (const int owner = engine_owner(); owner > 0) {
std::lock_guard<std::mutex> lk(g_page_mu);
g_vmem_owner[this] = owner;
}
return RAD_OK;
}
void VMem::rekey(VMem* from, VMem* to) {
std::lock_guard<std::mutex> lk(g_page_mu);
auto it = g_vmem_owner.find(from);
if (it == g_vmem_owner.end()) return;
const int owner = it->second;
g_vmem_owner.erase(it);
if (to) g_vmem_owner[to] = owner;
}
void VMem::release() {
owner_add(vmem_owner_of(this), device_, -committed_);
rekey(this, nullptr);
copy_.release();
parked_.clear();
if (!base_) { size_ = 0; committed_ = 0; ext_.clear(); return; }
/* Decommit before release: releasing a range with pages still mapped leaks them, and some
* drivers refuse the free. One granule at a time, as each was mapped. */
const int64_t g = granularity();
* drivers refuse the free. An extent is a run of whole mappings (one a granule), so it goes in
* one unmap. */
for (const auto& e : ext_) {
if (dev()->vmem_decommit && g > 0)
for (int64_t o = e.first; o < e.first + e.second; o += g)
(void)dev()->vmem_decommit((char*)base_ + o, g);
if (dev()->vmem_decommit) (void)dev()->vmem_decommit((char*)base_ + e.first, e.second);
g_vmem_committed.fetch_sub(e.second, std::memory_order_relaxed);
}
if (dev()->vmem_release) dev()->vmem_release(base_, size_);
@@ -311,6 +384,23 @@ bool VMem::is_committed(int64_t off, int64_t bytes) const {
* - Access cannot be granted per granule: a granule adjacent to an accessible one is refused on
* its own. Access is granted once per merged extent the new granules belong to; re-granting
* access to a range is free. */
namespace {
thread_local int t_map_batch = 0;
thread_local bool t_map_due = false;
}
MapBatch::MapBatch() { ++t_map_batch; }
MapBatch::~MapBatch() { (void)end(); }
int MapBatch::end() {
if (ended_) return RAD_OK;
ended_ = true;
if (--t_map_batch > 0 || !t_map_due) return RAD_OK;
t_map_due = false;
return dev_settle_maps();
}
int VMem::commit(int64_t off, int64_t bytes) {
if (!base_ || bytes <= 0) return bytes <= 0 ? RAD_OK : RAD_E_INVAL;
const int64_t g = granularity();
@@ -328,13 +418,27 @@ int VMem::commit(int64_t off, int64_t bytes) {
if (want.empty()) return RAD_OK;
/* On a failure part way, what already mapped stays mapped and recorded: a partial grow is
* usable, untracked mappings are not. */
* usable, untracked mappings are not. A contiguous run goes in one call; one that fails (the
* card lacks room for all of it) is backed a granule at a time, so it grows by what fits.
* `took`: the granules of `want` backed, a prefix of it. */
int rc = RAD_OK;
size_t took = 0;
for (; took < want.size(); ++took) {
rc = dev()->vmem_commit((char*)base_ + want[took], g);
if (rc < 0) break;
add_extent(want[took], g);
while (took < want.size() && rc >= 0) {
size_t j = took + 1;
while (j < want.size() && want[j] == want[j - 1] + g) ++j;
const int64_t run = (int64_t)(j - took) * g;
if (j - took > 1 && dev()->vmem_commit_units &&
dev()->vmem_commit_units((char*)base_ + want[took], run, g) >= 0) {
add_extent(want[took], run);
took = j;
continue;
}
for (; took < j; ++took) {
rc = dev()->vmem_commit((char*)base_ + want[took], g);
if (rc < 0) break;
rc = RAD_OK; /* recycled memory (1) is fine here: a pool's contents are written before they are read */
add_extent(want[took], g);
}
}
/* Grant access even if the grow stopped short, so the granules that did map are usable. */
@@ -355,6 +459,10 @@ int VMem::commit(int64_t off, int64_t bytes) {
}
return prc;
}
if (took > 0) {
if (t_map_batch > 0) t_map_due = true;
else if (const int src = dev_settle_maps(); src < 0) return src;
}
return rc;
}
@@ -368,20 +476,30 @@ int VMem::decommit(int64_t off, int64_t bytes) {
if (hi > size_) hi = size_;
if (lo >= hi) return RAD_OK;
/* Gathered first and unmapped per granule, as in commit. */
/* Gathered first; each contiguous run of granules (a mapping each) goes in one unmap. */
std::vector<int64_t> drop;
for (int64_t o = lo; o < hi; o += g)
if (is_committed(o, g)) drop.push_back(o);
for (const int64_t o : drop) {
const int rc = dev()->vmem_decommit((char*)base_ + o, g);
if (rc < 0) return rc;
drop_extent(o, g);
for (size_t i = 0; i < drop.size();) {
size_t j = i + 1;
while (j < drop.size() && drop[j] == drop[j - 1] + g) ++j;
const int64_t run = (int64_t)(j - i) * g;
if (const int rc = dev()->vmem_decommit((char*)base_ + drop[i], run); rc < 0) return rc;
drop_extent(drop[i], run);
i = j;
}
return RAD_OK;
}
int64_t dev_owner_bytes(int owner, int device) {
std::lock_guard<std::mutex> lk(g_owner_mu);
auto it = g_owner_bytes.find({ owner, device });
return it == g_owner_bytes.end() ? 0 : it->second;
}
void VMem::add_extent(int64_t off, int64_t bytes) {
owner_add(vmem_owner_of(this), device_, bytes);
committed_ += bytes;
g_vmem_committed.fetch_add(bytes, std::memory_order_relaxed);
/* Insert in order, then merge touching neighbours, so is_committed() stays a short scan
@@ -401,9 +519,215 @@ void VMem::add_extent(int64_t off, int64_t bytes) {
}
}
int64_t VMem::page_out(RadStream s, bool discard) {
if (!base_ || ext_.empty() || !parked_.empty()) return 0;
int64_t total = 0;
for (const auto& e : ext_) total += e.second;
if (discard) {
/* Nothing in the range is kept: back it again on page_in with whatever the pages hold. */
parked_ = ext_;
discarded_ = true;
for (const auto& e : parked_)
if (const int rc = decommit(e.first, e.second); rc < 0) return rc;
return 0;
}
discarded_ = false;
if (const int rc = copy_.alloc(total); rc < 0) return rc;
int64_t at = 0;
for (const auto& e : ext_) {
if (const int rc = rad_memcpy_async((char*)copy_.host + at, (char*)base_ + e.first, e.second, s); rc < 0)
return rc;
at += e.second;
}
if (const int rc = rad_stream_sync(s); rc < 0) return rc;
parked_ = ext_;
for (const auto& e : parked_)
if (const int rc = decommit(e.first, e.second); rc < 0) return rc;
return total;
}
int dev_current() { return t_device; }
int64_t dev_vmem_trim(int device) {
return dev()->vmem_trim ? dev()->vmem_trim(device) : 0;
}
void dev_stream_counts(int device, int* open, int* idle) {
if (open) *open = 0;
if (idle) *idle = 0;
if (dev()->stream_counts) dev()->stream_counts(device, open, idle);
}
int dev_stream_trim(int device, int keep) {
return dev()->stream_trim ? dev()->stream_trim(device, keep) : 0;
}
std::string dev_page_where(uintptr_t a);
std::string dev_fault_where(const void* p) {
const uintptr_t a = (uintptr_t)p;
std::string s = dev_page_where(a);
std::unique_lock<std::mutex> lk(g_page_mu, std::try_to_lock);
if (!lk.owns_lock()) return s;
for (const auto& [v, owner] : g_vmem_owner) {
const uintptr_t b = (uintptr_t)v->base();
if (!b || a < b || a >= b + (uintptr_t)v->size()) continue;
const int64_t off = (int64_t)(a - b), g = std::max<int64_t>(VMem::granularity(), 1);
return (s.empty() ? s : s + "; ") + fmt("elastic reservation of owner %d card %d, %s long, %s backed, +%s %s", owner, v->device(),
humanb(v->size()).c_str(), humanb(v->committed()).c_str(), humanb(off).c_str(),
v->is_committed(off / g * g, g) ? "is backed" : "is NOT backed");
}
return s;
}
int dev_settle_maps() {
if (device_is_host()) return RAD_OK;
void* x = dev()->alloc(4096, RAD_MEM_HOST_PINNED);
if (!x) {
device_set_error("vmem: no page of pinned host memory to flush the cards' translations with");
return RAD_E_NOMEM;
}
dev()->free(x, RAD_MEM_HOST_PINNED);
return RAD_OK;
}
int VMem::page_in(RadStream s) {
if (parked_.empty()) return RAD_OK;
MapBatch maps;
if (discarded_) {
for (const auto& e : parked_)
if (const int rc = commit(e.first, e.second); rc < 0) return rc;
if (const int rc = maps.end(); rc < 0) return rc;
parked_.clear();
discarded_ = false;
return RAD_OK;
}
if (const int rc = copy_.load(); rc < 0) return rc;
for (const auto& e : parked_)
if (const int rc = commit(e.first, e.second); rc < 0) return rc;
if (const int rc = maps.end(); rc < 0) return rc;
int64_t at = 0;
for (const auto& e : parked_) {
if (const int rc = rad_memcpy_async((char*)base_ + e.first, (char*)copy_.host + at, e.second, s); rc < 0)
return rc;
at += e.second;
}
if (const int rc = rad_stream_sync(s); rc < 0) return rc;
parked_.clear();
copy_.release();
return RAD_OK;
}
/* ---- HostCopy */
namespace {
std::atomic<uint64_t> g_copy_seq{0};
/* The unit of a copy's file I/O: what one write asks the gate about, what one reader takes. */
constexpr int64_t kCopyPiece = (int64_t)64 << 20;
}
int HostCopy::alloc(int64_t n) {
release();
bytes = n;
host = rad_dev_alloc(align_up(n, DirectFile::alignment()), RAD_MEM_HOST_PINNED);
if (!host) {
device_set_error("parking: no pinned host memory for %s", humanb(n).c_str());
return RAD_E_NOMEM;
}
return RAD_OK;
}
int HostCopy::spill(const std::string& dir, const std::function<int()>& gate) {
if (on_disk || !host || bytes <= 0) return RAD_OK;
/* Not the page files' name: their counter is another one (paging.cpp). */
const std::string path = dir + "/radiance-vmem-" + std::to_string((long long)getpid()) + "-" +
std::to_string((unsigned long long)g_copy_seq.fetch_add(1)) + ".bin";
DirectFile f;
if (const int rc = f.open(path.c_str(), RAD_DIO_WRITE | RAD_DIO_CREATE | RAD_DIO_TRUNC); rc < 0)
return rc;
const int64_t n = align_up(bytes, DirectFile::alignment());
int rc = RAD_OK;
for (int64_t at = 0; at < n; at += kCopyPiece) {
int g = gate ? gate() : 0;
while (g == 1) {
std::this_thread::sleep_for(std::chrono::milliseconds(20));
g = gate();
}
if (g < 0) { rc = RAD_E_STATE; break; }
if ((rc = f.write_at((const char*)host + at, at, std::min(kCopyPiece, n - at))) < 0) break;
}
f.close();
if (rc < 0) {
::unlink(path.c_str());
return rc;
}
file = path;
on_disk = true;
return RAD_OK;
}
void HostCopy::drop_host() {
if (!on_disk || !host) return;
rad_dev_free(host, RAD_MEM_HOST_PINNED);
host = nullptr;
}
int HostCopy::load() {
if (host) return RAD_OK;
if (!on_disk) {
device_set_error("parking: a copy has neither host memory nor a file");
return RAD_E_STATE;
}
const int64_t n = align_up(bytes, DirectFile::alignment());
host = rad_dev_alloc(n, RAD_MEM_HOST_PINNED);
if (!host) {
device_set_error("parking: no pinned host memory to read %s back", humanb(bytes).c_str());
return RAD_E_NOMEM;
}
/* A read that fails leaves no host memory behind, so the next load() reads again instead of
* taking a partial copy as the copy. */
auto fail = [&](int rc) {
rad_dev_free(host, RAD_MEM_HOST_PINNED);
host = nullptr;
return rc;
};
DirectFile f;
if (const int rc = f.open(file.c_str(), RAD_DIO_READ); rc < 0) return fail(rc);
/* Four readers over the file: one stream of O_DIRECT reads leaves an NVMe drive half idle. */
std::atomic<int64_t> next{0};
std::atomic<int> err{RAD_OK};
auto reader = [&] {
DirectFile g;
if (g.open(file.c_str(), RAD_DIO_READ) < 0) { err.store(RAD_E_IO); return; }
for (;;) {
const int64_t at = next.fetch_add(kCopyPiece);
if (at >= n || err.load() < 0) return;
if (g.read_at((char*)host + at, at, std::min(kCopyPiece, n - at)) < 0) { err.store(RAD_E_IO); return; }
}
};
std::vector<std::thread> th;
for (int i = 0; i < 4; ++i) th.emplace_back(reader);
for (auto& t : th) t.join();
if (err.load() < 0) {
device_set_error("parking: reading %s back failed", file.c_str());
return fail(err.load());
}
return RAD_OK;
}
void HostCopy::release() {
if (host) rad_dev_free(host, RAD_MEM_HOST_PINNED);
host = nullptr;
if (!file.empty()) ::unlink(file.c_str());
file.clear();
on_disk = false;
bytes = 0;
}
/* Precondition: the piece lies wholly inside one extent (decommit only drops committed granules).
* What remains of that extent is nothing, a head, a tail, or both. */
void VMem::drop_extent(int64_t off, int64_t bytes) {
owner_add(vmem_owner_of(this), device_, -bytes);
committed_ -= bytes;
g_vmem_committed.fetch_sub(bytes, std::memory_order_relaxed);
for (size_t i = 0; i < ext_.size(); ++i) {
@@ -416,6 +740,16 @@ void VMem::drop_extent(int64_t off, int64_t bytes) {
}
}
const DeviceBackend* active_backend() { return dev(); }
std::vector<VMem*> vmems_of(int owner) {
std::vector<VMem*> v;
std::lock_guard<std::mutex> lk(g_page_mu);
for (auto& [m, o] : g_vmem_owner)
if (o == owner) v.push_back(m);
return v;
}
} /* namespace rad */
/* ------------------------------------------------------------------ the ABI surface */
@@ -425,8 +759,7 @@ using rad::dev;
extern "C" {
int rad_dev_count(void) { return dev()->count(); }
/* The device this thread last selected, for the poison fill's stream (rad_dev_alloc). */
static thread_local int t_device = 0;
/* This thread's stream for the poison fill (rad_dev_alloc), one per device. */
static thread_local std::map<int, RadStream> t_poison_stream;
int rad_dev_set(int device) {
const int st = dev()->set(device);
@@ -440,9 +773,16 @@ void* rad_dev_alloc(int64_t bytes, int kind) {
/* Poison ordinals are per thread: each rank allocates in a fixed order on its own thread, but
* threads interleave, so a process-wide ordinal would not be repeatable. */
thread_local int64_t t_device_ordinal = 0;
void* p = dev()->alloc(bytes, kind);
void* p = nullptr;
const int owner = rad::engine_owner();
/* A large device allocation for an engine is mapped in chunks it can be parked by
* (paging.cpp). Where the backend has no virtual memory manager it is an ordinary allocation,
* and the model parks only by unloading. */
if (kind == RAD_MEM_DEVICE && bytes >= rad::kPageMin && owner > 0 && rad::VMem::supported())
p = rad::page_alloc(bytes, owner, t_device);
if (!p) p = dev()->alloc(bytes, kind);
if (p && kind >= 0 && kind < (int)std::size(rad::g_ledger)) {
rad::ledger_add(p, bytes, kind);
rad::ledger_add(p, bytes, kind, owner, t_device);
const int64_t total = rad::g_ledger[kind].count.fetch_add(1, std::memory_order_relaxed) + 1;
const int64_t ordinal = kind == RAD_MEM_DEVICE ? ++t_device_ordinal : total;
const int64_t floor_ = rad::trace_floor();
@@ -468,8 +808,13 @@ void* rad_dev_alloc(int64_t bytes, int kind) {
return p;
}
void rad_dev_free(void* p, int kind) {
rad::ledger_drop(p);
dev()->free(p, kind);
const int64_t bytes = rad::ledger_drop(p);
if (!(p && kind == RAD_MEM_DEVICE && rad::page_free(p))) dev()->free(p, kind);
/* Kernel libraries drop state they keep for addresses in the freed range (rad_plugin_freed). */
if (p && bytes > 0 && kind == RAD_MEM_DEVICE) {
std::shared_lock<std::shared_mutex> lk(rad::g_free_hooks_mu);
for (const auto& h : rad::g_free_hooks) h.first(p, bytes);
}
}
void* rad_dev_host_ptr(void* p) { return dev()->host_ptr(p); }
void* rad_dev_device_ptr(void* p) { return dev()->device_ptr(p); }
@@ -587,23 +932,38 @@ int rad_event_sync(RadEvent e) {
}
void rad_dev_host_wrote(void) { dev()->host_wrote(); }
/* Whether launches chain, from the engine (rad_dev_chain_infer), and the answer once taken. Only
* where the backend chains: the AQL backend writes the record a chained form reads, while a HIP
* launch carries only the kernel's own arguments. */
static std::atomic<int> g_chain_pays{0};
static std::atomic<int> g_chain{-1};
/* Whether launches chain, by engine: rad_dev_chain_infer on a thread of an engine (EngineScope)
* records that engine's answer and rad_dev_chain_enabled on any of its threads reads it. A process
* serves several models, each with its own plugin's answer; a single answer for the process was
* the answer of whichever model started last. Owner 0 is a thread outside every engine (a tool, a
* test). Only where the backend chains: the AQL backend writes the record a chained form reads,
* while a HIP launch carries only the kernel's own arguments. */
static std::mutex g_chain_mu;
static std::map<int, int> g_chain_pays; /* by owner */
static std::atomic<uint64_t> g_chain_gen{1};
void rad_dev_chain_infer(int pays) {
g_chain_pays.store(pays ? 1 : 0, std::memory_order_relaxed);
g_chain.store(-1, std::memory_order_relaxed);
{
std::lock_guard<std::mutex> lk(g_chain_mu);
g_chain_pays[rad::engine_owner()] = pays ? 1 : 0;
}
g_chain_gen.fetch_add(1, std::memory_order_release);
}
int rad_dev_chain_enabled(void) {
int on = g_chain.load(std::memory_order_relaxed);
if (on < 0) {
on = g_chain_pays.load(std::memory_order_relaxed) != 0 &&
std::strcmp(rad::device_backend_name(), "aql") == 0
? 1
: 0;
g_chain.store(on, std::memory_order_relaxed);
/* Asked on every launch: a thread keeps its engine's answer until some answer changes. */
thread_local uint64_t seen = 0;
thread_local int owner = -1, on = 0;
const uint64_t gen = g_chain_gen.load(std::memory_order_acquire);
const int o = rad::engine_owner();
if (seen != gen || owner != o) {
int pays = 0;
{
std::lock_guard<std::mutex> lk(g_chain_mu);
const auto it = g_chain_pays.find(o);
if (it != g_chain_pays.end()) pays = it->second;
}
on = pays && std::strcmp(rad::device_backend_name(), "aql") == 0 ? 1 : 0;
seen = gen;
owner = o;
}
return on;
}
@@ -643,6 +1003,14 @@ void* rad_link_gate(RadStream s) {
if (const auto f = dev()->link_gate) return f(s);
return nullptr;
}
void rad_dev_peer_launch(int on) {
if (const auto f = dev()->peer_launch) f(on);
}
int rad_dev_cards_claim(const int* cards, int n, int on) {
if (!cards || n <= 0) return RAD_E_INVAL;
if (const auto f = dev()->cards_claim) return f(cards, n, on);
return RAD_OK;
}
int rad_xp_supported(int device) {
const auto* d = dev();
return d->xp_supported && d->xp_stream_create && d->ride && d->ride_wait && d->ride_release && d->xp_list &&
@@ -685,7 +1053,7 @@ void* rad_dev_map_file(int fd, int64_t foff, int64_t bytes) {
}
void* p = f(fd, foff, bytes);
if (p) {
rad::ledger_add(p, bytes, RAD_MEM_HOST_MAPPED);
rad::ledger_add(p, bytes, RAD_MEM_HOST_MAPPED, 0, t_device);
rad::g_ledger[RAD_MEM_HOST_MAPPED].count.fetch_add(1, std::memory_order_relaxed);
}
return p;
+101 -11
View File
@@ -22,6 +22,7 @@
#include <cstring>
#include <map>
#include <mutex>
#include <set>
#include <thread>
#include <unordered_map>
#include <vector>
@@ -100,6 +101,8 @@ struct HostStream {
uint64_t submitted = 0; /* tasks ever pushed */
uint64_t retired = 0; /* tasks ever finished executing */
int sync_waiters = 0; /* h_stream_sync calls inside cv_done.wait */
int room_waiters = 0; /* stream_push calls inside cv_room.wait */
int gates = 0; /* closed gates (rad_stream_gate) queued on this stream */
std::thread worker;
@@ -117,27 +120,48 @@ int stream_push(HostStream* s, const Task& t) {
"(rad_gate_open) first");
return RAD_E_STATE;
}
++s->room_waiters;
s->cv_room.wait(lk, [s] { return s->count < s->ring.size(); });
--s->room_waiters;
/* The worker can only be asleep on cv_work when the ring was empty, so only that push pays
* the futex wake; its wait re-tests the predicate under the lock, so a wake it did not need
* (it was already running) is the only kind this can lose. */
const bool was_empty = s->count == 0;
s->ring[s->tail] = t;
s->tail = (s->tail + 1) % s->ring.size();
++s->count;
++s->submitted;
lk.unlock();
s->cv_work.notify_one();
if (was_empty) s->cv_work.notify_one();
return RAD_OK;
}
/* Pop the head task, with the stream lock held. Notifies are the caller's, after the unlock:
* cv_room is only worth a wake while a producer is asleep on it (room_waiters). Every pop
* wakes one while any is: a pop that only wakes on leaving a full ring loses the second of two
* producers behind it, when the next pop comes before the first one has pushed. */
static Task stream_pop_locked(HostStream* s, bool* wake_room) {
*wake_room = s->room_waiters > 0;
Task t = s->ring[s->head];
s->head = (s->head + 1) % s->ring.size();
--s->count;
return t;
}
void stream_run(HostStream* s) {
Task t;
bool have = false; /* t holds a task popped under the previous task's retire lock */
for (;;) {
Task t;
{
std::unique_lock<std::mutex> lk(s->m);
s->cv_work.wait(lk, [s] { return s->count > 0; });
t = s->ring[s->head];
s->head = (s->head + 1) % s->ring.size();
--s->count;
if (!have) {
bool wake_room = false;
{
std::unique_lock<std::mutex> lk(s->m);
s->cv_work.wait(lk, [s] { return s->count > 0; });
t = stream_pop_locked(s, &wake_room);
}
if (wake_room) s->cv_room.notify_one();
}
s->cv_room.notify_one();
have = false;
bool done = false;
switch (t.kind) {
@@ -191,11 +215,22 @@ void stream_run(HostStream* s) {
/* After the event lock is released: this may be the last reference. */
if (t.ev) event_release(t.ev);
/* Retire this task and take the next under the same lock, so a busy stream pays one lock
* a task instead of two. cv_done is only worth a futex wake when a sync is actually
* asleep on it (sync_waiters, under this lock; the wait's predicate is re-tested under
* the lock too, so no retire can be missed). */
bool notify_done = false, wake_room = false;
{
std::lock_guard<std::mutex> lk(s->m);
++s->retired;
notify_done = s->sync_waiters > 0;
if (!done && s->count > 0) {
t = stream_pop_locked(s, &wake_room);
have = true;
}
}
s->cv_done.notify_all();
if (notify_done) s->cv_done.notify_all();
if (wake_room) s->cv_room.notify_one();
if (done) return;
}
}
@@ -446,7 +481,9 @@ int h_stream_sync(RadStream st) {
/* Waits only for work submitted before this call, as hipStreamSynchronize does; the
* scheduler relies on sync returning while another thread keeps pushing. */
const uint64_t target = s->submitted;
++s->sync_waiters;
s->cv_done.wait(lk, [s, target] { return s->retired >= target; });
--s->sync_waiters;
return RAD_OK;
}
@@ -784,8 +821,24 @@ int h_vmem_commit(void* addr, int64_t bytes) {
return RAD_OK;
}
/* Pages are what an mmap backs, so a run is one commit and any part of it decommits alone. */
int h_vmem_commit_units(void* addr, int64_t bytes, int64_t unit) {
if (unit <= 0 || bytes % unit) return RAD_E_INVAL;
return h_vmem_commit(addr, bytes);
}
/* Ranges backed as host memory (h_vmem_commit_host): not counted as the device's. */
std::mutex g_hostkind_mu;
std::set<const char*> g_hostkind;
bool take_hostkind(const void* addr) {
std::lock_guard<std::mutex> lk(g_hostkind_mu);
return g_hostkind.erase((const char*)addr) > 0;
}
int h_vmem_decommit(void* addr, int64_t bytes) {
if (!addr || bytes <= 0) return RAD_E_INVAL;
const bool host = take_hostkind(addr);
/* MAP_FIXED rather than munmap: a hole in the reservation could be handed to an unrelated
* mmap. */
void* p = ::mmap(addr, (size_t)bytes, PROT_NONE,
@@ -794,7 +847,40 @@ int h_vmem_decommit(void* addr, int64_t bytes) {
device_set_error("vmem_decommit(%p, %lld): mmap failed", addr, (long long)bytes);
return RAD_E_INVAL;
}
g_used[vmem_device_of(addr)].fetch_sub(bytes, std::memory_order_relaxed);
if (!host) g_used[vmem_device_of(addr)].fetch_sub(bytes, std::memory_order_relaxed);
return RAD_OK;
}
/* Host memory is all there is here: the same pages as a commit, not charged to the device. */
int h_vmem_commit_host(void* addr, int64_t bytes) {
if (!addr || bytes <= 0) return RAD_E_INVAL;
void* p = ::mmap(addr, (size_t)bytes, PROT_READ | PROT_WRITE,
MAP_FIXED | MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
if (p != addr) {
device_set_error("vmem_commit_host(%p, %lld): mmap failed", addr, (long long)bytes);
return RAD_E_NOMEM;
}
std::lock_guard<std::mutex> lk(g_hostkind_mu);
g_hostkind.insert((const char*)addr);
return RAD_OK;
}
/* The pages move with mremap, through a spare range, so each keeps its bytes and its kind. */
int h_vmem_swap(void* a, void* b, int64_t bytes) {
if (!a || !b || bytes <= 0) return RAD_E_INVAL;
const size_t n = (size_t)bytes;
void* t = ::mmap(nullptr, n, PROT_NONE, MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
if (t == MAP_FAILED) return RAD_E_NOMEM;
if (::mremap(a, n, n, MREMAP_MAYMOVE | MREMAP_FIXED, t) != t ||
::mremap(b, n, n, MREMAP_MAYMOVE | MREMAP_FIXED, a) != a ||
::mremap(t, n, n, MREMAP_MAYMOVE | MREMAP_FIXED, b) != b) {
device_set_error("vmem_swap(%p, %p, %lld): mremap failed", a, b, (long long)bytes);
return RAD_E_INVAL;
}
std::lock_guard<std::mutex> lk(g_hostkind_mu);
const bool ha = g_hostkind.erase((const char*)a) > 0, hb = g_hostkind.erase((const char*)b) > 0;
if (hb) g_hostkind.insert((const char*)a);
if (ha) g_hostkind.insert((const char*)b);
return RAD_OK;
}
@@ -842,6 +928,10 @@ const DeviceBackend g_host = {
h_stream_gate, h_gate_open, h_gate_room,
nullptr, /* event_dma: no DMA queue */
nullptr, /* map_file */
nullptr, /* stuck_ms */
h_vmem_commit_host, h_vmem_swap,
h_vmem_commit_units,
};
} /* namespace */
File diff suppressed because it is too large. Load diff