radiance 1.7.0

- every model serves without a GPU: libavx covers every op, so `--kernels libavx` alone serves
  every shipped container
- Qwen3-ASR (zivius): speech to text on /v1/audio/transcriptions and live over /v1/realtime
- /v1/messages works with Claude Code as it ships (gearwave00001)
- a long agent conversation keeps its cached history when the client rewrites its last turn
  (manueloverride)
- a stream's first event goes out with the first token, so llama-benchy measures prefill right
- opt-in --prefill-interleave (Smellyyyy, baKon) and --prefill-span (keptn42)
- four-rank TP releases the link early; four-rank selftests and docs/TP4.md (goodman-b)
- NVFP4 and FP8 compressed-tensors imports (devmilan); tools/rad-export for finetunes and LoRA
  adapters (baKon)
- many fixes, among them lost tokens on stop strings under concurrency, keep-alive, MiniCPM5 tool
  arguments and the CPU's vision and audio encoders
- plugin ABI 17 and changed op schemas: out-of-tree plugins must be rebuilt
This commit is contained in:
Deadcode committed 2026-10-16 18:25:18 +02:00
1 parent b068190326
commit 1e968f6e1d
739 files changed
+128447 -84632

No files matched your search

+492 -461
View File
File diff suppressed because it is too large. Load diff
+21 -23
View File
@@ -1,9 +1,8 @@
/* aql.h -- what the AQL backend's translation units share.
/* aql.h -- declarations shared by the AQL backend's translation units.
*
* Three files: aql_code.cpp reads code objects (the offload bundle, the ELF note, the msgpack
* metadata inside it), aql.cpp owns the queues and everything submitted to them, and
* aql_blit.hip holds the copy and fill kernels the backend dispatches for itself. The last one is
* compiled as HIP, so nothing in this header may pull in HSA or anything HIP would object to.
* aql_code.cpp reads code objects (offload bundle, ELF note, msgpack metadata), aql.cpp owns the
* queues and all submission, and aql_blit.hip holds the backend's own copy and fill kernels.
* aql_blit.hip is compiled as HIP, so this header must not pull in HSA.
*/
#pragma once
@@ -17,9 +16,9 @@ namespace aql {
/* ------------------------------------------------------------------ code objects */
/* One kernel argument as the code object's metadata lays it out. `hidden` names the implicit
* arguments the compiler appends after the declared ones; every other kind is an explicit
* parameter, and those map one to one, in order, onto hipLaunchKernel's `kernelParams`. */
/* One kernel argument as laid out in the code object's metadata. `hidden` names the implicit
* arguments the compiler appends; explicit parameters map in order onto hipLaunchKernel's
* `kernelParams`. */
enum class Hidden : uint8_t {
None, /* an explicit parameter */
Pad, /* hidden_none: bytes the compiler reserved and reads nothing from */
@@ -48,13 +47,12 @@ struct KernelMeta {
std::vector<KernelArg> args;
};
/* The code object a card runs, out of a clang offload bundle, or an empty span with `*why` naming
* what the bundle holds and what the card accepts. `isas` is the card's own list of the targets it
* accepts, in the runtime's order of preference: "amdgcn-amd-amdhsa--gfx1036", then the family's
* "amdgcn-amd-amdhsa--gfx10-3-generic", each carrying the modes the card runs in
* ("gfx942:sramecc+:xnack-"). The bundle carries no total length, so it is read entry by entry from
* its own header; a compressed bundle is refused rather than decompressed, because nothing in this
* tree builds one. */
/* Selects the card's code object from a clang offload bundle, or fails with `*why` naming what
* the bundle holds and what the card accepts. `isas` lists the card's accepted targets in the
* runtime's order of preference ("amdgcn-amd-amdhsa--gfx1036", then the family's
* "amdgcn-amd-amdhsa--gfx10-3-generic"), each with its modes ("gfx942:sramecc+:xnack-"). The
* bundle has no total length, so it is walked entry by entry. Compressed bundles are refused;
* nothing in this tree builds one. */
bool bundle_code_object(const void* bundle, const std::vector<std::string>& isas, const void** out,
size_t* out_size, std::string* why);
@@ -64,8 +62,8 @@ bool code_object_kernels(const void* elf, size_t size, std::vector<KernelMeta>*
/* ------------------------------------------------------------------ fence policy
*
* What the next dispatch on this thread has to be fenced at, beyond the agent scope every kernel
* gets. Set by the backend around its own blits and cleared by the dispatch that consumes it. */
* Extra fence scope for the next dispatch on this thread, beyond the agent scope every kernel
* gets. Set by the backend around its own blits; cleared by the dispatch that consumes it. */
enum : uint8_t { kFenceAcquireSystem = 1, kFenceReleaseSystem = 2 };
void set_next_fence(uint8_t f);
@@ -74,17 +72,17 @@ void set_next_fence(uint8_t f);
struct RadCopyRange;
/* The blit kernels' launchers, defined in aql_blit.hip. Each issues exactly one kernel onto
* `stream` through hipLaunchKernel, which the backend intercepts. Alignment is the caller's: the
* 16-byte forms need both addresses and the length 16-byte aligned. */
/* Blit kernel launchers, defined in aql_blit.hip. Each issues one kernel onto `stream` through
* hipLaunchKernel, which the backend intercepts. The caller guarantees alignment: the 16-byte
* forms need both addresses and the length 16-byte aligned. */
extern "C" {
/* `link` when either side is across the link (pinned host memory): one narrow workgroup instead
* of a grid that fills the card; aql_blit.hip says why. */
/* `link`: either side is pinned host memory, so use one narrow workgroup instead of a full grid
* (see aql_blit.hip). */
int rad_aql_blit_copy(void* dst, const void* src, uint64_t bytes, void* stream, bool link = false);
int rad_aql_blit_copy2d(void* dst, uint64_t dpitch, const void* src, uint64_t spitch,
uint64_t width, uint64_t height, void* stream);
int rad_aql_blit_fill(void* dst, int value, uint64_t bytes, void* stream);
/* rad_memcpy_ranges_async's kernel: `prefix` a multiple of sixteen and both bases 16-aligned. */
/* rad_memcpy_ranges_async's kernel: `prefix` a multiple of 16, both bases 16-byte aligned. */
int rad_aql_blit_ranges(void* dst, const void* src, uint64_t prefix, const RadCopyRange* ranges,
int n, void* stream);
}
+25 -30
View File
@@ -1,14 +1,13 @@
/* aql_blit.hip -- the copy and fill kernels the AQL backend dispatches for rad_memcpy_async,
* rad_memcpy_2d_async and rad_memset_async.
/* aql_blit.hip -- copy and fill kernels behind rad_memcpy_async, rad_memcpy_2d_async and
* rad_memset_async on the AQL backend.
*
* A copy on this backend is a kernel on the stream's own queue, the same as HIP's blit path: the
* alternative is the DMA engine, which is a second queue to order against with signals and costs
* more in latency than a small copy takes to run. Every address these kernels see is one the GPU
* can reach directly -- device memory, a peer's, or pinned host memory; pageable host memory is
* staged by the caller.
* A copy is a kernel on the stream's own queue, like HIP's blit path. The DMA engine would be a
* second queue to order against with signals, and its latency exceeds a small copy's run time.
* Every address is GPU-reachable (device, peer or pinned host memory); the caller stages
* pageable host memory.
*
* The launchers go through hipLaunchKernel like any plugin's, and the backend intercepts that, so
* these kernels are dispatched exactly as a kernel library's are.
* The launchers go through hipLaunchKernel, which the backend intercepts, so these kernels are
* dispatched like any kernel library's.
*/
#include <hip/hip_runtime.h>
@@ -24,8 +23,8 @@ constexpr uint64_t kMaxBlocks = 2048;
typedef unsigned u32x4 __attribute__((ext_vector_type(4)));
/* Four loads in flight a thread before the first store: a copy that reads pinned host memory is
* link-latency bound, and one outstanding load a thread leaves most of the link idle. */
/* Four loads in flight per thread before the first store: a copy from pinned host memory is
* link-latency bound, and one outstanding load per thread leaves most of the link idle. */
__global__ __launch_bounds__(kThreads) void aql_copy16(const u32x4* __restrict__ src,
u32x4* __restrict__ dst, uint64_t n) {
const uint64_t stride = (uint64_t)gridDim.x * kThreads;
@@ -37,15 +36,12 @@ __global__ __launch_bounds__(kThreads) void aql_copy16(const u32x4* __restrict__
for (; i < n; i += stride) dst[i] = src[i];
}
/* A COPY THAT READS OR WRITES ACROSS THE LINK IS ONE WORKGROUP OF FOUR WAVES.
/* A copy across the link (pinned host memory) is one workgroup of four waves.
*
* The link delivers ~29 GB/s whatever the grid, so the only question is how few waves reach that,
* because every wave a copy holds is one the compute queue's kernels do not get while the copy
* crawls along at link speed. A wide link copy -- 16 workgroups of 256 threads, 128 waves -- costs
* a prefill whose stager keeps a copy running beside every layer ~15%: hc_read at a 2048-row chunk
* takes 1154 us a call with such copies running and 609 without, because its down product is
* exactly one wave of workgroups on the part and any slot a copy holds pushes some of it into a
* second. Link bandwidth by grid, one card, 89 MB from pinned host memory:
* The link delivers ~29 GB/s regardless of grid size, so the copy should hold as few waves as
* possible: every wave it holds is denied to compute kernels for the copy's duration (a wide link
* copy beside each layer slows a staged prefill by ~15%). Link bandwidth by grid, one card,
* 89 MB from pinned host memory:
*
* 16 x 256 threads, 4 loads in flight 28.9 GB/s
* 1 x 256 threads, 16 in flight 28.9
@@ -54,11 +50,10 @@ __global__ __launch_bounds__(kThreads) void aql_copy16(const u32x4* __restrict__
* 1 x 64 threads, 8 in flight 10.4
*
* 32 KiB in flight is several times the link's bandwidth-delay product; fewer threads leave the
* link idle, and 32 loads a thread spill. Non-temporal loads and stores change nothing: it is the
* slots, not the caches.
* link idle and 32 loads per thread spill. Non-temporal loads and stores make no difference.
*
* The last round loads clamped rather than guarded, so its loads are all in flight at once: a
* guarded load waits for the one before it. */
* The last round clamps its load indices instead of guarding them, so all its loads are in flight
* at once; a guarded load waits for the one before it. */
constexpr int kLinkThreads = 128, kLinkDepth = 16;
constexpr uint64_t kLinkByteBlocks = 16;
@@ -119,11 +114,11 @@ __global__ __launch_bounds__(kThreads) void aql_copy2d1(const unsigned char* __r
}
}
/* A RANGED COPY: the first `prefix_blocks` workgroups move the prefix as aql_copy16 does, and each
* workgroup after them one range. A range is four-byte aligned only, so it moves in words, sixteen
* a thread a round: every load of a round is issued before its first store, since each is a read
* across the link, and the loads past the range's end read its last word rather than branch
* around the load -- a guarded load waits for the one before it. */
/* Ranged copy: the first `prefix_blocks` workgroups copy the prefix as aql_copy16 does, and each
* later workgroup copies one range. Ranges are only 4-byte aligned, so they move in words, 16 per
* thread per round, with all loads issued before the first store (each is a read across the
* link). Loads past the range end clamp to its last word instead of branching, since a guarded
* load waits for the one before it. */
constexpr int kRangeWords = 16;
__global__ __launch_bounds__(kThreads) void aql_copy_ranges(const u32x4* __restrict__ src16,
@@ -199,8 +194,8 @@ extern "C" int rad_aql_blit_copy(void* dst, const void* src, uint64_t bytes, voi
hipLaunchKernelGGL(aql_copy16, dim3(blocks_for(n, 4 * kThreads)), dim3(kThreads), 0,
s, (const u32x4*)src, (u32x4*)dst, n);
} else {
/* Unaligned: byte copies, one byte a thread in flight, so across the link they take
* sixteen workgroups rather than the one narrow workgroup of the aligned path. */
/* Unaligned: byte copies have one byte per thread in flight, so across the link they
* use 16 workgroups instead of the aligned path's one. */
const uint64_t cap = link ? kLinkByteBlocks : kMaxBlocks;
hipLaunchKernelGGL(aql_copy1, dim3(blocks_for(bytes, 4 * kThreads, cap)), dim3(kThreads),
0, s, (const unsigned char*)src, (unsigned char*)dst, bytes);
+29 -29
View File
@@ -1,10 +1,9 @@
/* aql_code.cpp -- reading AMDGPU code objects: the offload bundle a HIP fat binary is, the ELF
* inside it, and the msgpack metadata note that says where each kernel's arguments go.
/* aql_code.cpp -- reads AMDGPU code objects: the offload bundle of a HIP fat binary, the ELF
* inside it, and the msgpack metadata note that gives each kernel's argument layout.
*
* The AQL backend dispatches kernels HIP compiled and registered, so it needs two things HIP keeps
* to itself: the code object for this card, to load into an executable of its own, and each
* kernel's argument layout, to write a kernarg segment without HIP's help. Both are in the fat
* binary the compiler embedded, and this file reads them.
* The AQL backend dispatches HIP-registered kernels itself, so it needs two things HIP does not
* expose: the card's code object, to load into its own executable, and each kernel's argument
* layout, to write kernarg segments. Both come from the embedded fat binary.
*
* Nothing here touches a device, so it builds and is tested without one.
*/
@@ -21,10 +20,9 @@ namespace {
const char kHsaPrefix[] = "amdgcn-amd-amdhsa--";
/* A target ID as LLVM writes it after the triple: a processor and any number of target features,
* each `name+` or `name-` ("gfx942:sramecc+:xnack-"). A feature left out of a code object's ID
* means the code object runs in either mode; one left out of a card's ID means the card has no
* such mode. */
/* A target ID as LLVM writes it after the triple: a processor and target features, each `name+`
* or `name-` ("gfx942:sramecc+:xnack-"). A feature absent from a code object's ID means it runs in
* either mode; absent from a card's ID, the card has no such mode. */
struct TargetId {
std::string proc;
std::vector<std::pair<std::string, char>> feat;
@@ -44,18 +42,22 @@ TargetId parse_target_id(const std::string& s) {
return t;
}
/* The target ID out of an ISA name ("amdgcn-amd-amdhsa--gfx1036") or a bundle entry's triple
* ("hipv4-amdgcn-amd-amdhsa--gfx1036"); empty for anything that is not an AMDGPU HSA target, such
* as the bundle's host entry. */
/* The target ID from an ISA name ("amdgcn-amd-amdhsa--gfx1036") or a bundle entry's triple
* ("hipv4-amdgcn-amd-amdhsa--gfx1036"); empty for non-AMDGPU targets such as the host entry. */
std::string target_id_of(const std::string& name) {
const size_t at = name.find(kHsaPrefix);
if (at == std::string::npos) return std::string();
return name.substr(at + sizeof kHsaPrefix - 1);
}
/* -1 when a code object built for `co` cannot run on a card that accepts `card`; otherwise how
* many target features the code object pins, so that one built for the card's exact mode is
* preferred to one built for either mode. */
/* An ISA name's target ID, or the name itself when it carries no HSA prefix. */
std::string isa_target(const std::string& isa) {
const std::string id = target_id_of(isa);
return id.empty() ? isa : id;
}
/* -1 if a code object for `co` cannot run on a card accepting `card`; otherwise the number of
* features the code object pins, so one built for the card's exact mode is preferred. */
int target_fit(const TargetId& co, const TargetId& card) {
if (co.proc != card.proc) return -1;
for (const auto& f : co.feat) {
@@ -77,7 +79,7 @@ bool bundle_code_object(const void* bundle, const std::vector<std::string>& isas
*out_size = 0;
if (!b) { *why = "null bundle"; return false; }
if (std::memcmp(b, "CCOB", 4) == 0) {
*why = "the fat binary is a COMPRESSED offload bundle; build the kernel library without "
*why = "the fat binary is a compressed offload bundle; build the kernel library without "
"--offload-compress";
return false;
}
@@ -89,8 +91,8 @@ bool bundle_code_object(const void* bundle, const std::vector<std::string>& isas
std::memcpy(&n, b + 24, 8);
if (n == 0 || n > 4096) { *why = "offload bundle with an implausible entry count"; return false; }
/* Every device entry, as "<kind>-amdgcn-amd-amdhsa--<target ID>". Both kinds HIP has used,
* "hip" and "hipv4", carry the same code object format for this purpose. */
/* Device entries are "<kind>-amdgcn-amd-amdhsa--<target ID>"; both kinds, "hip" and "hipv4",
* carry the same code object format for this purpose. */
struct Entry { uint64_t off, size; TargetId id; std::string text; };
std::vector<Entry> ents;
const unsigned char* p = b + 32;
@@ -107,13 +109,11 @@ bool bundle_code_object(const void* bundle, const std::vector<std::string>& isas
ents.push_back({ off, size, parse_target_id(id), id });
}
/* THE CARD'S LIST DECIDES, IN THE CARD'S ORDER. The runtime reports the processor itself
* first and then the generic target of its family ("gfx1036", then "gfx10-3-generic"), each
* with the modes the card runs in. So a library built for the exact chip is used where it
* exists, and one built once for a family runs on every member of it. Within one accepted
* target, a code object pinned to the card's mode beats one built for either mode. */
/* Walk the card's ISA list in its own order: the exact processor first, then its family's
* generic target. An exact-chip build wins where present; a family build runs on every
* member. Within one target, a code object pinned to the card's mode wins. */
for (const std::string& isa : isas) {
const TargetId card = parse_target_id(target_id_of(isa).empty() ? isa : target_id_of(isa));
const TargetId card = parse_target_id(isa_target(isa));
const Entry* best = nullptr;
int best_fit = -1;
for (const Entry& e : ents) {
@@ -130,7 +130,7 @@ bool bundle_code_object(const void* bundle, const std::vector<std::string>& isas
std::string have, want;
for (const Entry& e : ents) have += (have.empty() ? "" : ", ") + e.text;
for (const std::string& isa : isas)
want += (want.empty() ? "" : ", ") + (target_id_of(isa).empty() ? isa : target_id_of(isa));
want += (want.empty() ? "" : ", ") + isa_target(isa);
*why = "the fat binary has code objects for [" + (have.empty() ? std::string("none") : have) +
"] and this card runs [" + want + "]";
return false;
@@ -138,9 +138,9 @@ bool bundle_code_object(const void* bundle, const std::vector<std::string>& isas
/* ------------------------------------------------------------------ msgpack
*
* The subset a code object's metadata uses: maps, arrays, strings, integers, booleans and nil.
* A DOM, because the metadata is walked by key and is a few hundred kilobytes at most, read once
* per module at the first dispatch into it. */
* The subset code object metadata uses: maps, arrays, strings, integers, booleans and nil. Parsed
* into a DOM: the metadata is looked up by key, is a few hundred KB at most, and is read once per
* module at its first dispatch. */
namespace {
struct MP {
+207 -226
View File
@@ -1,16 +1,12 @@
/* device.h -- the device layer's internal face.
/* device.h -- the device layer's internal interface.
*
* `abi/rad_device.h` is what the rest of the engine and every plugin calls. This header is
* the seam between the two implementations of it, plus the two questions the rest of the core
* actually needs to ask about which one won.
* `abi/rad_device.h` is what the engine and plugins call. This header is the seam between its
* backend implementations, plus queries for which backend is active.
*
* The seam is a vtable rather than an `#ifdef` at every call site. That is a deliberate trade: an
* indirect call costs a load and a jump, which is unmeasurable against a `hipMemcpyAsync` and
* unmeasurable against a `memcpy` of anything worth enqueuing, and in exchange there is exactly one
* definition of each `rad_dev_*` symbol and no way for the two backends to drift into implementing
* different contracts. Two device layers that have silently diverged is the failure this avoids,
* and it is the failure that matters, because the host backend is where everything above the
* kernels is developed (docs/IMPLEMENTATION.md) and the HIP backend is where it has to still work.
* The seam is a vtable, not an `#ifdef` per call site. The indirect call is unmeasurable next to
* any copy worth enqueuing, and in exchange each `rad_dev_*` symbol has one definition, so the
* backends cannot drift into different contracts. That matters because the host backend is where
* everything above the kernels is developed (docs/IMPLEMENTATION.md).
*/
#pragma once
#include "rad_abi.h"
@@ -21,105 +17,95 @@
#include <utility>
#include <vector>
/* AN EVENT THAT ONLY ORDERS WORK ON ONE CARD. Its record makes the recording stream's writes
* visible to the rest of that card and to nothing else, so it may be waited on by another stream
* of the same card and queried or synchronised by the host for WHEN, but the host must not read
* device-written memory on the strength of it, and no other card may wait on it. What that buys
* is the release: making writes visible to the system waits for every write still in flight to
* host memory, and with the link busy streaming weights that is most of a microsecond at best and
* over ten at worst on every record, where the card-wide release costs the packet alone. */
/* An event that orders work on one card only. Its record makes the stream's writes visible to
* that card and nothing else: another stream of the same card may wait on it and the host may
* query or sync it for timing, but the host must not read device-written memory on its strength
* and no other card may wait on it. The gain is the cheaper release: a system-scope release waits
* for every in-flight write to host memory, ~1-10 us per record while the link streams weights. */
extern "C" int rad_event_create_local(RadEvent* out);
/* WHAT AN EVENT IS FOR, fixed when it is made. RAD_EVENT_LOCAL is rad_event_create_local's scope.
* RAD_EVENT_HOST_WAIT is an event the host synchronises on: its records complete with an interrupt
* the waiting thread blocks on, where the other kind complete silently and can only be waited on by
* a stream. rad_event_create is RAD_EVENT_HOST_WAIT, rad_event_create_local is RAD_EVENT_LOCAL
* alone, and rad_event_sync refuses an event made without RAD_EVENT_HOST_WAIT. */
/* Event purpose, fixed at creation. RAD_EVENT_LOCAL is rad_event_create_local's scope.
* RAD_EVENT_HOST_WAIT records complete with an interrupt a host thread can block on; without it
* records complete silently and only a stream can wait on them. rad_event_create is
* RAD_EVENT_HOST_WAIT, rad_event_create_local is RAD_EVENT_LOCAL alone, and rad_event_sync refuses
* an event made without RAD_EVENT_HOST_WAIT. */
enum : unsigned {
RAD_EVENT_LOCAL = 1u,
RAD_EVENT_HOST_WAIT = 2u,
};
extern "C" int rad_event_create_as(RadEvent* out, unsigned flags);
/* The host has just written memory a kernel issued after this call reads, and no host wait came
* between: a host-site op's output, read over the link by the device op after it. */
/* The host has just written memory that a kernel issued after this call reads, with no host wait
* in between (e.g. a host-site op's output read over the link by the next device op). */
extern "C" void rad_dev_host_wrote(void);
/* ONE RANGE OF A RANGED COPY: `bytes` from byte `src` of the source to byte `dst` of the
* destination, all three multiples of four. */
/* One range of a ranged copy: `bytes` from source offset `src` to destination offset `dst`, all
* three multiples of four. */
struct RadCopyRange {
int64_t src;
int64_t dst;
int64_t bytes;
};
/* A FIXED PREFIX AND A LIST OF RANGES, IN ONE DISPATCH: src[0, prefix) to dst[0, prefix) -- a
* multiple of sixteen, and it may be zero -- and then every range. The copy reads `ranges` when it
* runs, so the list lives in memory the device reaches (pinned host memory beside `src`) and stays
* as written until the stream has passed the copy, like `src` itself. One workgroup copies one
* range, so a caller cuts a long run into ranges of a few kilobytes. */
/* Copies src[0, prefix) to dst[0, prefix) (a multiple of 16, possibly zero), then every range,
* in one dispatch. The kernel reads `ranges` when it runs, so the list must be device-reachable
* (pinned host memory beside `src`) and stay unchanged until the stream passes the copy. One
* workgroup copies one range, so callers cut long runs into ranges of a few KB. */
extern "C" int rad_memcpy_ranges_async(void* dst, const void* src, int64_t prefix,
const RadCopyRange* ranges, int n, RadStream s);
/* ONE COPY OF A LIST: `bytes` from `src` to `dst`, both absolute addresses. */
/* One copy of a list: `bytes` from `src` to `dst`, both absolute addresses. */
struct RadCopySeg {
const void* src;
void* dst;
int64_t bytes;
};
/* MANY UNRELATED COPIES, IN LIST ORDER ON THE STREAM, on the card's DMA engine where the backend
* has one. The list is read at the call, so it need not outlive it; the bytes it names do, like
* any copy's. A backend without a DMA engine copies the segments one by one, in order. An empty
* list puts nothing on the stream, and readies what the backend's first list on that stream's card
* would otherwise set up, so a caller can take that cost at bring-up.
/* Many unrelated copies, in list order on the stream, on the card's DMA engine where the backend
* has one (otherwise segment by segment). The list itself is read at the call; the bytes it names
* must live until the copy runs. An empty list enqueues nothing but performs the card's first-list
* setup, so a caller can pay that cost at bring-up.
*
* It exists for bulk copies across the link while the card computes -- the prefill stager's,
* a layer's pooled experts a call. A copy as a kernel holds a compute unit's slot for as long as
* the link takes, and waits for one to free up at every launch: beside kernels that keep every unit
* busy, 1.3 MB copies from pinned host memory ran at 2.3 GB/s as kernels and at 28.7 GB/s -- the
* link -- on the DMA engine, which cost those kernels nothing (aql.cpp, "the DMA lane").
* For bulk link copies while the card computes (e.g. a layer's pooled experts in the prefill
* stager). A copy kernel holds a CU slot for the link's duration and waits for a free one at
* launch: beside busy kernels, 1.3 MB pinned-host copies run at 2.3 GB/s as kernels versus
* 28.7 GB/s (link rate) on the DMA engine, at no cost to the kernels (aql.cpp, "the DMA lane").
*
* RAD_COPY_YIELD makes the list give way to the card's collectives: it waits, between pieces of
* about a megabyte, while a stream of that card holds the link (rad_link_hold). */
* RAD_COPY_YIELD makes the list yield to the card's collectives: between ~1 MB pieces it waits
* while a stream of that card holds the link (rad_link_hold). */
#define RAD_COPY_YIELD 1u
extern "C" int rad_memcpy_list_async(const RadCopySeg* segs, int n, unsigned flags, RadStream s);
/* THE CARD'S LINK, HELD BY A STREAM FOR WHAT IT ISSUES BETWEEN TWO CALLS: `on` 1 at the point in
* `s` where traffic the step waits on starts to cross the card's link -- a collective -- and 0
* where it ends, or 2 where the work in between ended the hold itself (rad_link_gate). Lists issued
* RAD_COPY_YIELD for that card stop between pieces while it is held. The holds of one card
* alternate, on then off, in the order they are issued across all its streams: they never nest or
* overlap. And the holding stream must not wait, between the two
* calls, on anything behind a yielding list -- the list would wait for the hold to end, and the
* hold for the list. A backend without a DMA engine holds nothing.
/* Holds the card's link for the work `s` issues between two calls. `on` = 1 where step-critical
* link traffic (a collective) starts, 0 where it ends, or 2 where the work in between released the
* hold itself (rad_link_gate). RAD_COPY_YIELD lists for that card pause between pieces while held.
* A card's holds alternate on/off in issue order across all its streams; they never nest or
* overlap. Between the two calls the holding stream must not wait on anything behind a yielding
* list, or the list and the hold deadlock. A backend without a DMA engine holds nothing.
*
* WHY: a card's inbound link carries a collective's peer bytes and the stager's copies alike, and
* the DMA engine takes its share at the link's full rate. A 4 MB all-reduce message that crosses in
* 165 us on its own took 301 us beside a layer's copies, and the step waits on every one; the
* copies have the rest of the layer to finish in. */
* Why: collective peer bytes and stager copies share the inbound link, and the DMA engine takes
* its share at full rate. A 4 MB all-reduce message takes 165 us alone and 301 us beside a layer's
* 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 WORD THE HOLD IS KEPT IN, for a launch that ends its own: a 64-bit word in memory every
* engine and kernel of the card reaches, odd while the link is held. rad_link_hold(s, 2) after a
* launch that was handed this address records that the launch released the hold itself, by taking
* one off the word -- once, and only if it found it odd -- as soon as the bytes it waited for had
* landed. Null where the backend holds nothing. */
/* 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
* with rad_link_hold(s, 2). Null where the backend holds nothing. */
extern "C" void* rad_link_gate(RadStream s);
/* THE EXPERT PREFETCH'S DEVICE HALF (core/runtime/xprefetch.cpp). A backend that cannot make a
* dispatch complete a signal, or has no DMA engine to spare for it, leaves these out:
* rad_xp_supported is then 0 and the prefetch is off.
/* Device half of the expert prefetch (core/runtime/xprefetch.cpp). A backend that cannot have a
* dispatch complete a signal, or has no spare DMA engine, leaves these out; rad_xp_supported is
* then 0 and the prefetch is off.
*
* A RIDE is a signal the next dispatch issued on a stream completes -- that dispatch keeps its
* ordering bit, so the signal stands for everything before it on the stream -- in place of a
* barrier packet of its own between two kernels. rad_ride_wait puts a barrier on another stream
* that waits for it and gives the signal back behind that barrier; a ride the DMA engine polls
* instead goes back with rad_ride_release once nothing can poll it: at once (`after` null) when the
* list that polled it has finished, else once `after` is `packets` dispatches further on, which is
* long after the ridden dispatch has completed it.
* A ride is a signal completed by the next dispatch on a stream, instead of a separate barrier
* packet. That dispatch keeps its ordering bit, so the signal covers everything before it.
* rad_ride_wait puts a barrier waiting on it onto another stream and recycles the signal behind
* that barrier. A ride polled by the DMA engine is returned with rad_ride_release once nothing can
* poll it: immediately (`after` null) when the polling list has finished, else once `after` is
* `packets` dispatches further on.
*
* rad_xp_list hands the card's prefetch DMA queue a list: wait for `mark` (a ride, or null), copy
* the `n` ranges, then write `done_val` to `done` (pinned host memory, or null). rad_xp_behind is how
* many lists the queue has been handed and not yet finished. The prefetch's ring is uncached device
* memory (rad_dev_alloc_uncached): the engine writes it and kernels read it, and no cache may hold
* what a slot held before. */
* rad_xp_list gives the card's prefetch DMA queue a list: wait for `mark` (a ride, or null), copy
* the `n` ranges, then write `done_val` to `done` (pinned host memory, or null). rad_xp_behind
* counts lists handed over and not yet finished. The prefetch ring is uncached device memory
* (rad_dev_alloc_uncached): the engine writes it and kernels read it, so no cache may hold a
* slot's previous contents. */
extern "C" int rad_xp_supported(int device);
extern "C" int rad_xp_stream_create(RadStream* out);
extern "C" int rad_ride(RadStream s, void** token);
@@ -131,35 +117,53 @@ extern "C" int64_t rad_xp_behind(int device);
extern "C" void* rad_dev_alloc_uncached(int64_t bytes);
extern "C" void rad_dev_free_uncached(void* p);
/* A gate on a stream: the stream stops at the point rad_stream_gate enqueues and goes on once the
* host calls rad_gate_open. Everything enqueued behind the gate meanwhile is then ready at once, so
* the device runs it back to back however long the host took to submit it. For timing a batch of
* launches without the host's submission rate in the measurement (tools/kbench_timer.cpp); the
* engine has no use for it.
*
* Behind a closed gate the queue only fills. A caller enqueues at most rad_gate_room(s) more
* submissions, counting each launch's own (a kernel may issue several), and must not wait on the
* stream before opening the gate. The backends refuse with RAD_E_STATE, rather than deadlock, a
* submission that would wait for room and a rad_stream_sync on a gated stream; an event sync on a
* record behind the gate is not caught. Open every gate before destroying its stream.
*
* The gate itself acquires at system scope, so nothing behind it takes the acquire a first
* dispatch after a host wait otherwise takes. rad_gate_room counts the submissions that fit
* before the queue is full or before a dispatch would take the periodic system-scope acquire
* (an L2 invalidate, see aql.cpp "fences"); on a stream without a closed gate it is the same
* count with the device still draining. `gate` is single-use: opening it frees it. Not inside a
* tape capture. RAD_E_UNSUPPORTED (and a room of 0) on a backend without gates. */
extern "C" int rad_stream_gate(RadStream s, void** gate);
extern "C" int rad_gate_open(void* gate);
extern "C" int64_t rad_gate_room(RadStream s);
namespace rad {
/* A recorded pass, owned by the backend that recorded it. See DeviceBackend::tape_begin. */
typedef void* RadTape;
/* ------------------------------------------------------------------ who won */
/* Decided once, at first use, and cached. Callers: the planner (a host backend has no VRAM tier
* worth planning against, only a budget), the selector (RAD_DOMAIN_HOST is the only domain that
* can run), and every test that must skip a device-only assertion rather than fail it. */
/* ------------------------------------------------------------------ active backend */
/* Decided once at first use and cached. Used by the planner (a host backend has only a budget,
* no VRAM tier), the selector (only RAD_DOMAIN_HOST can run) and tests that skip device-only
* assertions. */
bool device_is_host();
const char* device_backend_name(); /* "host" or "aql" */
/* ------------------------------------------------------------------ two contract notes
*
* These are properties of rad_device.h that the frozen header does not state and that
* tests/device_test.cpp pins against a real card. Written down here rather than left to be
* rediscovered:
* Properties of rad_device.h that the frozen header does not state; tests/device_test.cpp pins
* them against a real card.
*
* 1. `rad_memset_async` requires a DEVICE-ACCESSIBLE destination: RAD_MEM_DEVICE,
* RAD_MEM_HOST_PINNED or RAD_MEM_HOST_MAPPED. Plain RAD_MEM_HOST is pageable memory the GPU
* has never been shown and hipMemsetAsync refuses it. The host backend cannot reproduce that
* refusal, so this is the one asymmetry between the two -- see the comment on d_memset_async
* in hip.cpp for why it is reported rather than papered over. `rad_memcpy_async` has no such
* restriction: hipMemcpyDefault handles pageable memory on both ends.
* 1. `rad_memset_async` requires a device-accessible destination: RAD_MEM_DEVICE,
* RAD_MEM_HOST_PINNED or RAD_MEM_HOST_MAPPED. hipMemsetAsync refuses pageable RAD_MEM_HOST.
* The host backend cannot reproduce that refusal, so this is the one asymmetry between the
* two (see d_memset_async in hip.cpp). `rad_memcpy_async` has no such restriction.
*
* 2. A null RadStream is refused by BOTH backends. HIP's stream 0 serialises against every other
* blocking stream in the process, which is the opposite of spec §5.4's requirement that a
* transfer involve no host synchronisation; the engine creates its streams and never uses the
* default one, so passing null is a bug and the host backend reports it as one as well.
* 2. Both backends refuse a null RadStream. HIP's stream 0 serialises against every blocking
* stream, contrary to spec §5.4 (no host synchronisation in a transfer). The engine never uses
* the default stream, so null is a bug.
*/
/* ------------------------------------------------------------------ the backend vtable */
@@ -190,9 +194,8 @@ struct DeviceBackend {
int (*event_sync)(RadEvent e);
int (*event_elapsed_ms)(RadEvent a, RadEvent b, float* out);
/* The host has written memory a kernel issued from here on will read, without a host wait
* having come between: whatever makes the device see host writes after a wait has to be done
* now as well. */
/* The host wrote memory that kernels issued from here on read, with no host wait in between:
* do whatever a wait would have done to make host writes visible to the device. */
void (*host_wrote)(void);
int (*memcpy_async)(void* dst, const void* src, int64_t bytes, RadStream s);
@@ -205,73 +208,59 @@ struct DeviceBackend {
int (*link_hold)(RadStream s, int on);
void* (*link_gate)(RadStream s);
/* ---- recorded passes. A backend with none leaves these null, and the run phase then issues
* every pass; see Ctx::run_step for what a tape is for and when one is kept.
/* ---- recorded passes. Null on a backend without them; the run phase then issues every
* pass. See Ctx::run_step for what a tape is for.
*
* `tape_begin` opens a capture of every submission THIS THREAD makes -- dispatches, event
* records and waits -- while `tape_pause` is not in effect (it nests). `tape_mark` is the
* number of records so far, which is how the caller cuts a tape into the stretches between
* its own host work. `tape_end` closes the capture and returns the tape, or null when `keep`
* is 0 or the pass did something a tape cannot reproduce (the reason is in
* rad_dev_last_error). `tape_play` submits records [from, to) again, onto the queues they
* were recorded on. `tape_destroy` may be called while a play is still queued; the backend
* frees the tape once nothing can read it. */
* `tape_begin` captures every submission this thread makes (dispatches, event records and
* waits) outside `tape_pause` (which nests). `tape_mark` returns the record count, so the
* caller can cut the tape at its own host work. `tape_end` returns the tape, or null when
* `keep` is 0 or the pass did something a tape cannot reproduce (reason in
* rad_dev_last_error). `tape_play` resubmits records [from, to) onto their recorded queues.
* `tape_destroy` may be called while a play is queued; the tape is freed once unreachable. */
int (*tape_begin)(void);
int (*tape_mark)(void);
void (*tape_pause)(int on);
RadTape (*tape_end)(int keep);
int (*tape_len)(RadTape t);
int (*tape_play)(RadTape t, int from, int to);
/* The first record at which two tapes differ, -1 when they agree: the same submissions to the
* same queues, the same packets but for where their arguments live, the same argument bytes.
* What differs is described into `why`. */
/* First record at which two tapes differ, or -1 if they agree (same submissions to the same
* queues, same packets apart from argument addresses, same argument bytes). The difference is
* described into `why`. */
int (*tape_diff)(RadTape a, RadTape b, char* why, int cap);
void (*tape_destroy)(RadTape t);
/* Record `i` of a tape: what it is (0 a dispatch, 1 an event record or wait) and the queue it
* goes to. And the one edit a closed tape takes: whether dispatch `i` is played WITHOUT the
* barrier bit, launching while the packets in front of it on its queue are still running.
* The caller sets it only where it has shown the dispatch touches nothing those packets write,
* and on at most kTapeOverlapRun dispatches in a row; see Ctx::haz_mark. */
/* `tape_record`: record `i`'s kind (0 dispatch, 1 event record or wait) and queue.
* `tape_set_overlap`, the one edit a closed tape accepts: play dispatch `i` without the barrier
* bit, so it launches while earlier packets on its queue still run. The caller sets it only
* where the dispatch touches nothing those packets write, and on at most kTapeOverlapRun
* consecutive dispatches; see Ctx::haz_mark. */
int (*tape_record)(RadTape t, int i, int* kind, uint32_t* queue);
int (*tape_set_overlap)(RadTape t, int i, int on);
/* ---- elastic memory: an address range whose SIZE IS FIXED AND WHOSE BACKING IS NOT.
/* ---- elastic memory: an address range of fixed size whose backing comes and goes.
*
* A pool allocated whole owns its bytes for the life of the process, which is the right trade
* for a pool whose demand is known at startup and the wrong one for two pools that take
* turns. The KV cache and the expert slab are that pair: the cache holds what the live
* sessions hold and nothing more, and a byte it is not holding is a byte the expert plane
* would rather have resident than stream over the link.
* Lets two pools that take turns share memory: the KV cache backs only what live sessions
* hold, and the expert plane keeps the rest resident instead of streaming it over the link.
*
* WHY THIS IS A PRIMITIVE AND NOT FREE-THEN-REALLOCATE. The KV pool is layer-major
* (core/mem/kv.h): layer i lives at `base + i * n_blocks * layer_bytes_per_block`, so the
* block count is baked into every layer's base address and the unused blocks are a stripe
* inside each layer rather than a tail anyone could hand back. Reserving the address range at
* its maximum and backing only part of it leaves every stride where the kernels already
* expect it while the physical pages come and go underneath.
* Free-then-reallocate does not work: the KV pool is layer-major (core/mem/kv.h), layer i at
* `base + i * n_blocks * layer_bytes_per_block`, so unused blocks are a stripe inside each
* layer, not a tail. Reserving the maximum range and backing part of it keeps every stride
* where the kernels expect it.
*
* A backend without elastic memory leaves these null, and everything above it sizes its pools
* once and lives with the split: the absence is a configuration rather than a degradation.
*
* The contract:
*
* `vmem_reserve` takes address space and no pages.
*
* `vmem_commit` backs ONE GRANULE and `vmem_decommit` unbacks one. A MAPPING IS UNMAPPED
* EXACTLY AS IT WAS MAPPED: a driver handed four granules in one call refuses to unmap the
* second of them on its own. VMem below therefore issues one call per granule and never a
* run, which is what makes the granule the unit a pool can grow and shrink by.
*
* `vmem_protect` grants this device read/write access to a range that is already backed. It
* is separate from the commit because the range to name is not the one just mapped: access
* set over a granule adjacent to an already-accessible one is refused where the whole
* contiguous run containing both is accepted, so VMem names the run.
* A backend without elastic memory leaves these null and pools are sized once at startup;
* that is a supported configuration.
*
* 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_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.
* `vmem_release` takes a range with nothing committed in it.
*
* The bookkeeping that keeps a commit off a commit lives in VMem below, once, rather than in
* each backend. */
* Overlap bookkeeping lives once in VMem below, not in each backend. */
int64_t (*vmem_granularity)(void); /* commit quantum; 0 = unsupported */
void* (*vmem_reserve)(int64_t bytes, int64_t align);
void (*vmem_release)(void* base, int64_t bytes);
@@ -279,47 +268,41 @@ struct DeviceBackend {
int (*vmem_decommit)(void* addr, int64_t bytes);
int (*vmem_protect)(void* addr, int64_t bytes);
/* ---- observation. The VRAM in use on a card, every process's, as the driver counts it, read
* without entering the device runtime: a dashboard polls it, and a runtime call can wait on
* a lock the launch path holds. Available once props() has been read for the device;
* RAD_E_UNSUPPORTED before that, and from a backend with no such counter. Last in the table
* so that a backend listing its entries in order may leave it out. */
/* ---- observation. VRAM in use on a card by all processes, as the driver counts it, read
* without entering the device runtime (a dashboard polls it, and a runtime call can block on
* a lock the launch path holds). Available once props() has been read for the device;
* otherwise, or without such a counter, RAD_E_UNSUPPORTED. */
int (*vram_used)(int device, int64_t* out);
/* ---- plugin device code. A backend that loads device code out of the fat binaries kernel
* plugins carry counts each registration; `code_mark` is how many there have been, and
* `code_runs` answers whether every one in [from, to) holds a code object `device` runs (1),
* not (0, with the reason in `why`), or cannot say (< 0). The plugin loader brackets each
* dlopen with marks, so the run is exactly that plugin's. Null on a backend that loads no
* device code. */
/* ---- plugin device code. `code_mark` counts fat-binary registrations so far; `code_runs`
* reports whether every registration in [from, to) has a code object `device` runs (1), not
* (0, reason in `why`), or unknown (< 0). The plugin loader brackets each dlopen with marks.
* Null on a backend that loads no device code. */
size_t (*code_mark)(void);
int (*code_runs)(size_t from, size_t to, int device, char* why, int cap);
/* ---- 1 when the device is integrated graphics: its memory is the host's, so what it reports
* as device memory is shared with every process on the machine. Null on a backend with no such
* devices, which answers 0. */
/* ---- 1 when the device is integrated graphics: its "device memory" is host memory shared
* with every process. Null (answers 0) on a backend with no such devices. */
int (*integrated)(int device);
/* ---- 1 when `self` can read and write `peer`'s memory directly, 0 when it cannot, < 0 when
* the backend cannot say. Asked, not enabled: rad_dev_enable_peer is the call that maps the
* memory. Null on a backend whose devices share one address space, which answers 1. */
/* ---- 1 when `self` can access `peer`'s memory directly, 0 when not, < 0 when unknown. A
* query only; rad_dev_enable_peer maps the memory. Null (answers 1) on a backend whose devices
* share one address space. */
int (*peer_access)(int self, int peer);
/* ---- the card's PCI address, "0000:03:00.0", into `out`; RAD_E_UNSUPPORTED from a backend
* whose devices are not PCI devices. It is what joins the runtime's device index to the
* kernel's description of the same card -- its link, its power limits, its IOMMU group -- in
* the startup report (core/diag/diag.h). */
/* ---- the card's PCI address, "0000:03:00.0", into `out`; RAD_E_UNSUPPORTED for non-PCI
* devices. The startup report (core/diag/diag.h) uses it to join the runtime's device index to
* the kernel's view of the card (link, power limits, IOMMU group). */
int (*pci_address)(int device, char* out, int cap);
/* ---- the device runtime's name and version, "HIP 7.2.25403", into `out`. Null on a backend
* with no runtime behind it. */
* with no runtime. */
int (*runtime_version)(char* out, int cap);
/* ---- what carries the engine's copy lists for `device` (rad_memcpy_list_async), into `out`:
* the card's DMA engine on a queue of the process's own, or why not. Null on a backend that
* copies every list segment by segment. */
/* ---- what carries rad_memcpy_list_async for `device`, into `out`: the card's DMA engine on
* the process's own queue, or why not. Null on a backend that copies segment by segment. */
int (*dma_lane)(int device, char* out, int cap);
/* ---- the expert prefetch's device half: see rad_xp_supported. Last in the table, so a backend
* listing its entries in order leaves them null. */
/* ---- expert prefetch device half: see rad_xp_supported. Last in the table, so a backend
* listing its entries positionally leaves them null. */
int (*xp_supported)(int device);
int (*xp_stream_create)(RadStream* out);
int (*ride)(RadStream s, void** token);
@@ -330,6 +313,11 @@ struct DeviceBackend {
int64_t (*xp_behind)(int device);
void* (*alloc_uncached)(int64_t bytes);
void (*free_uncached)(void* p);
/* ---- gates: see rad_stream_gate. Null on a backend without them. */
int (*stream_gate)(RadStream s, void** gate);
int (*gate_open)(void* gate);
int64_t (*gate_room)(RadStream s);
};
@@ -354,8 +342,8 @@ int dev_peer_access(int self, int peer);
/* The current backend's DeviceBackend::vram_used. */
int dev_vram_used(int device, int64_t* out);
/* The current backend's DeviceBackend::code_mark and code_runs. A backend without them has no
* device code to check: the mark is 0 and every plugin runs (1). */
/* The current backend's DeviceBackend::code_mark and code_runs. Without them the mark is 0 and
* every plugin runs (1). */
size_t dev_code_mark();
int dev_code_runs(size_t from, size_t to, int device, std::string* why);
@@ -368,41 +356,40 @@ std::string dev_runtime_version();
/* The current backend's DeviceBackend::dma_lane, "" where it has none. */
std::string dev_dma_lane(int device);
/* THE LONGEST RUN OF DISPATCHES A PLAYED TAPE LEAVES UNORDERED. Of any kTapeOverlapRun + 1
* consecutive packets on a queue, one carries the barrier bit, so a packet having been launched
* still proves that everything more than that many packets before it has completed -- which is
* what the backend's argument slots and a tape's own lifetime are reclaimed on. */
/* Longest run of dispatches a played tape leaves unordered. Of any kTapeOverlapRun + 1
* consecutive packets on a queue one carries the barrier bit, so a launched packet still proves
* that everything more than that many packets earlier has completed. Argument slots and tape
* lifetimes are reclaimed on that guarantee. */
constexpr int kTapeOverlapRun = 6;
/* ------------------------------------------------------------------ the allocation ledger
* What rad_dev_alloc has handed out, by RAD_MEM_* kind, since the process started. See the
* comment on the ledger in dispatch.cpp for what it is for and -- more to the point -- what it
* cannot see: a kernel plugin that calls hipMalloc directly never reaches this file. */
* What rad_dev_alloc has handed out since process start, by RAD_MEM_* kind. It does not see a
* 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);
/* 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);
/* ------------------------------------------------------------------ elastic memory
* One reserved address range and the record of which granules inside it are backed.
* One reserved address range and which granules inside it are backed.
*
* The interval bookkeeping is here rather than in the backends because the driver refuses a
* commit that overlaps a commit and a decommit that covers a hole, and two implementations of
* "which parts of this range are already backed" is two places for that answer to drift. The
* backends get granule-aligned, disjoint ranges and no decisions.
* The interval bookkeeping lives here, not in the backends, because the driver refuses a commit
* overlapping a commit and a decommit covering a hole. Backends get granule-aligned, disjoint
* ranges and make no decisions.
*
* THE TWO ROUNDINGS GO OPPOSITE WAYS, AND IT IS NOT A DETAIL. A commit rounds OUTWARD, so the
* bytes the caller asked for are certainly backed; a decommit rounds INWARD, so a granule holding
* one byte the caller still wants is never taken away. The alternative -- one rounding for both --
* either strands memory or unmaps live data, and the second reads as a kernel fault at an address
* that was valid a moment ago.
* The roundings differ on purpose: commit rounds outward, so every requested byte is backed;
* decommit rounds inward, so a granule holding any byte still in use is kept. A shared rounding
* would either strand memory or unmap live data (a kernel fault at a valid address).
*
* Nothing here is thread-safe. A range is owned by whatever owns the pool it backs, and the
* commit/decommit path is a policy decision, not a step-path one. */
* Not thread-safe. A range is owned by the owner of the pool it backs, and commit/decommit is
* policy, not step-path work. */
class VMem {
public:
/* Whether this process's backend has elastic memory at all. Callers size their pools whole
* when it does not: see the DeviceBackend comment for why that is a supported configuration. */
/* Whether the backend has elastic memory. Without it callers size pools whole (a supported
* configuration; see DeviceBackend). */
static bool supported();
static int64_t granularity(); /* 0 when unsupported */
@@ -410,9 +397,8 @@ public:
~VMem() { release(); }
VMem(const VMem&) = delete;
VMem& operator=(const VMem&) = delete;
/* Movable, because an elastic range is owned by whatever structure holds it and those
* structures live in vectors. The source is left naming nothing, so the destructor it still
* gets does not unmap a range the destination now owns. */
/* 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_)) {
o.base_ = nullptr;
@@ -433,9 +419,8 @@ public:
return *this;
}
/* Address space only: no pages, no VRAM, nothing the card notices. `align` defaults to the
* granularity. Reserving large is the point -- the range is the MAXIMUM the pool may ever
* reach, because it is the one thing that cannot be changed later without moving addresses. */
/* Address space only: no pages, no VRAM. `align` defaults to the granularity. Reserve the
* maximum the pool may ever reach; the range cannot grow later without moving addresses. */
int reserve(int64_t bytes, int64_t align = 0);
void release(); /* decommits whatever is still backed, then frees the VA */
@@ -443,22 +428,22 @@ public:
int64_t size() const { return size_; }
int64_t committed() const { return committed_; } /* bytes actually backed right now */
/* Both are idempotent and both clamp to the range. commit() backs every granule touching
* [off, off+bytes) that is not backed; decommit() unbacks every granule wholly inside it that
* is. Either may do nothing and report success. */
/* Idempotent and clamped to the range. commit() backs every unbacked granule touching
* [off, off+bytes); decommit() unbacks every backed granule wholly inside it. Doing nothing is
* success. */
int commit(int64_t off, int64_t bytes);
int decommit(int64_t off, int64_t bytes);
/* Is every byte of [off, off+bytes) backed? The question a caller asks before handing the
* range to a kernel. */
/* Whether every byte of [off, off+bytes) is backed; check before handing a range to a
* kernel. */
bool is_committed(int64_t off, int64_t bytes) const;
private:
void* base_ = nullptr;
int64_t size_ = 0;
int64_t committed_ = 0;
/* Sorted, disjoint and never adjacent: a commit that touches an existing extent merges into
* it, so the list length tracks the number of live REGIONS and not the number of calls. */
/* 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_;
/* Adds a newly mapped piece and merges it with whatever it touches. */
@@ -466,34 +451,30 @@ private:
void drop_extent(int64_t off, int64_t bytes);
};
/* What every VMem in this process has backed, for the receipt Engine::start prints. Device memory
* committed this way never reaches the rad_dev_alloc ledger -- it is not an allocation -- so
* without this line the card's own accounting and the engine's disagree by exactly the elastic
* pools. */
/* 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);
#if defined(RAD_HAVE_HIP) && RAD_HAVE_HIP
/* Null when the build has HIP but the machine shows no device. A build that can talk to a GPU and
* a machine that has one are separate facts, and conflating them is how a CI container that
* happens to have ROCm headers installed fails at the first hipMalloc instead of running the host
* backend it was always going to run. The configure decides which kernels are COMPILED; this
* decides whether there is a card to run them on, and neither answer implies the other. */
/* Null when the build has HIP but the machine shows no device, so a machine with ROCm installed
* but no card runs the host backend instead of failing at the first hipMalloc. Configure decides
* which kernels are compiled; this decides whether there is a card to run them. */
const DeviceBackend* hip_backend_if_present(void);
/* The HIP backend with its streams, events, copies and fills replaced by AQL packets the engine
* writes itself (aql.cpp). Aborts, naming why, on a machine it cannot run on. */
/* The HIP backend with streams, events, copies and fills replaced by AQL packets the engine writes
* itself (aql.cpp). Aborts with the reason on a machine it cannot run on. */
const DeviceBackend* aql_backend_if_present(void);
/* Bytes copied to or from pageable host memory so far: every such copy is a host wait. */
/* Bytes copied to or from pageable host memory so far; each such copy is a host wait. */
int64_t aql_pageable_bytes(void);
/* The fat binaries registered so far, counted whichever backend runs: the registration hooks are
* this build's own exported symbols and see every dlopen'ed kernel plugin's device code, card or
* no card. The host backend's code_mark in a HIP build. */
/* Fat binaries registered so far, counted whichever backend runs: the registration hooks are this
* build's exported symbols and see every dlopen'ed plugin's device code, card or not. Serves as
* the host backend's code_mark in a HIP build. */
size_t aql_code_registered(void);
#endif
/* ------------------------------------------------------------------ the error slot */
/* Both backends write here; rad_dev_last_error() drains it. Thread-local, because spec §1 puts one
* thread per tensor-parallel rank and the mover on its own: a fault on the mover's thread reported
* as the compute rank's would send the operator to the wrong half of the engine. */
/* Both backends write here; rad_dev_last_error() drains it. Thread-local because spec §1 gives each
* tensor-parallel rank and the mover their own thread, and an error must be reported on the thread
* that caused it. */
void device_set_error(const char* fmt, ...) __attribute__((format(printf, 1, 2)));
} /* namespace rad */
+22 -46
View File
@@ -15,30 +15,12 @@
namespace rad {
namespace {
/* The bounce is one megabyte, allocated on first misaligned use and never on the aligned path.
* Big enough that a misaligned read of a whole weight is a handful of syscalls; small enough that
* a DirectFile nobody misuses costs nothing. */
/* Bounce buffer size; allocated on first misaligned use only. */
constexpr int64_t kBounceBytes = 1 << 20;
int64_t align_down(int64_t v, int64_t a) { return v / a * a; }
/* Fill `bytes` exactly. A short pread inside the file is a torn read, not a smaller one. */
int pread_exact(int fd, void* dst, int64_t bytes, int64_t off) {
int64_t done = 0;
while (done < bytes) {
ssize_t r = ::pread(fd, (uint8_t*)dst + done, (size_t)(bytes - done), (off_t)(off + done));
if (r < 0) {
if (errno == EINTR) continue;
return RAD_E_IO;
}
if (r == 0) return RAD_E_IO; /* end of file inside a range the caller said was there */
done += r;
}
return RAD_OK;
}
/* As much as the file has, which is what the aligned superset of a misaligned tail asks for.
* Negative is an error; otherwise the byte count. */
/* Reads up to `bytes`, stopping at end of file. Returns the byte count, or a negative error. */
int64_t pread_some(int fd, void* dst, int64_t bytes, int64_t off) {
int64_t done = 0;
while (done < bytes) {
@@ -53,6 +35,14 @@ int64_t pread_some(int fd, void* dst, int64_t bytes, int64_t off) {
return done;
}
/* Fill `bytes` exactly. A short pread inside the file is a torn read, not a smaller one: end of
* file inside a range the caller said was there is an error. */
int pread_exact(int fd, void* dst, int64_t bytes, int64_t off) {
const int64_t got = pread_some(fd, dst, bytes, off);
if (got < 0) return (int)got;
return got == bytes ? RAD_OK : RAD_E_IO;
}
int pwrite_exact(int fd, const void* src, int64_t bytes, int64_t off) {
int64_t done = 0;
while (done < bytes) {
@@ -76,9 +66,7 @@ int DirectFile::open(const char* path, int flags) {
close();
const bool want_write = (flags & RAD_DIO_WRITE) != 0;
/* O_RDWR whenever writing, even if the caller only said RAD_DIO_WRITE: a write that does not
* cover a whole block has to read the block first (see write_at), and O_WRONLY would turn that
* into an EBADF at the worst possible moment. */
/* O_RDWR whenever writing: a partial-block write reads the block first (see write_at). */
int oflags = want_write ? O_RDWR : O_RDONLY;
if (flags & RAD_DIO_CREATE) oflags |= O_CREAT;
if (flags & RAD_DIO_TRUNC) oflags |= O_TRUNC;
@@ -87,7 +75,7 @@ int DirectFile::open(const char* path, int flags) {
direct_ = fd_ >= 0;
if (fd_ < 0 && (errno == EINVAL || errno == ENOTSUP || errno == EOPNOTSUPP)) {
/* The filesystem, not the file: tmpfs and some network mounts refuse O_DIRECT outright. */
/* tmpfs and some network mounts refuse O_DIRECT outright. */
if (flags & RAD_DIO_ALLOW_BUFFERED) {
fd_ = ::open(path, oflags, 0600);
direct_ = false;
@@ -145,19 +133,13 @@ int DirectFile::read_at(void* dst, int64_t off, int64_t bytes) {
const bool aligned = (off % A) == 0 && (bytes % A) == 0 &&
((uintptr_t)dst % (uintptr_t)A) == 0;
/* THE PATH THAT MATTERS. One pread, straight into the caller's pinned buffer, no intermediate
* copy anywhere -- which is what makes the mover able to DMA from it (spec §5.4). Every extent
* the .rad container describes lands here, because the container aligns its movement units to
* RAD_ALIGN_UNIT and rad_dev_alloc aligns its pools to the same. */
/* Fast path: one pread straight into the caller's pinned buffer. Every .rad extent lands here
* (movement units and rad_dev_alloc pools are both RAD_ALIGN_UNIT-aligned). */
if (aligned) return pread_exact(fd_, dst, bytes, off);
/* THE ONLY BOUNCE IN THE ENGINE'S READ PATH, and it is here because O_DIRECT gives no
* alternative: the kernel will EINVAL a transfer whose offset, length or buffer is not
* block-aligned, so an unaligned extent can either be read through an aligned superset and
* copied out, or not read at all. It is acceptable here and nowhere else for one reason --
* this path is not the mover's. It serves the tail of a file whose length is not a block
* multiple, and callers reading a header or a footer rather than a movement unit. Anything on
* the step path that finds itself here has a layout bug, not a performance problem. */
/* O_DIRECT rejects unaligned transfers with EINVAL, so read an aligned superset through the
* bounce and copy out. This serves file tails and header/footer reads, never the mover; a
* step-path read landing here indicates a layout bug. */
RAD_TRY(bounce_ready());
const int64_t lo = align_down(off, A);
@@ -170,9 +152,7 @@ int DirectFile::read_at(void* dst, int64_t off, int64_t bytes) {
const int64_t got = pread_some(fd_, bounce_, span, base);
if (got < 0) return (int)got;
/* A short read is only survivable when the file ends past the slice the caller asked for.
* Otherwise the caller named bytes that are not in the file, which is RAD_E_IO and not a
* partial success (see read_at's contract in the header). */
/* A short read is fine only if it still covers the requested slice. */
if (got < e - base) return RAD_E_IO;
std::memcpy((uint8_t*)dst + (s - off), bounce_ + (s - base), (size_t)(e - s));
}
@@ -181,8 +161,7 @@ int DirectFile::read_at(void* dst, int64_t off, int64_t bytes) {
/* ------------------------------------------------------------------ write */
/* The same shape as read_at -- one fast path for whole aligned blocks, and a read-modify-write for
* anything that does not cover a whole block. */
/* Aligned writes go straight through; anything else is a read-modify-write of whole blocks. */
int DirectFile::write_at(const void* src, int64_t off, int64_t bytes) {
if (fd_ < 0) return RAD_E_STATE;
if (!src || off < 0 || bytes < 0) return RAD_E_INVAL;
@@ -201,10 +180,8 @@ int DirectFile::write_at(const void* src, int64_t off, int64_t bytes) {
const int64_t hi = align_up(off + bytes, A);
for (int64_t base = lo; base < hi; base += bounce_bytes_) {
const int64_t span = std::min(bounce_bytes_, hi - base);
/* Read-modify-write the whole chunk, including blocks the request covers completely. That
* is a wasted read per interior block and it is deliberate: the branchless version is
* short enough to be obviously correct, and this path exists for correctness at a boundary,
* not for throughput. The aligned path above is the one that has to be fast. */
/* Read-modify-write the whole chunk, including fully covered interior blocks. The extra
* reads are deliberate: this path is for correctness at boundaries, not throughput. */
const int64_t got = pread_some(fd_, bounce_, span, base);
if (got < 0) return (int)got;
if (got < span) std::memset(bounce_ + got, 0, (size_t)(span - got));
@@ -216,8 +193,7 @@ int DirectFile::write_at(const void* src, int64_t off, int64_t bytes) {
RAD_TRY(pwrite_exact(fd_, bounce_, span, base));
}
/* The last chunk padded the file out to a block boundary. Cut it back, so size() reports what
* was actually written and a later read_at of the tail sees the real end of file. */
/* The last chunk padded the file to a block boundary; truncate back to the real end. */
const int64_t want = std::max(old_size, off + bytes);
if (size() > want && ::ftruncate(fd_, (off_t)want) != 0) return RAD_E_IO;
return RAD_OK;
+17 -31
View File
@@ -1,21 +1,14 @@
/* directio.h -- the file tier's reader.
/* directio.h -- the file tier's reader (spec §5.4): O_DIRECT reads into pinned buffers, used by
* the weight tier and the KV tier.
*
* spec §5.4: "a file tier read with O_DIRECT into pinned buffers. Predictable latency, no
* page-cache double-copy, and reads land where the mover can DMA from them without a bounce."
* This file is that approach, narrowed to the one thing the weight tier and the KV tier both need.
* The page cache is avoided for two reasons:
* - it is a second copy of every byte already headed for a pinned buffer;
* - it evicts. A large tier read through the page cache throws out the mapped `.rad` pool's
* pages, which shows up later as an untraceable decode stall.
*
* Two reasons the page cache is the wrong place for this and not merely a redundant one:
*
* - it is a second copy of bytes that are already going to a pinned buffer, paid on every read,
* of a store measured in gigabytes;
* - it evicts. A weight-tier read pulling a hundred megabytes through the page cache throws out
* the mapped `.rad` pool's own pages, and the cost of that shows up in decode as a stall
* nobody can trace back to the read that caused it.
*
* The alignment rules are O_DIRECT's: the file offset, the transfer length and the buffer address
* must all be block-aligned. Everything rad_dev_alloc returns already is (host.cpp), and .rad
* pads its movement units to RAD_ALIGN_UNIT (rad_format.h), so the mover's every read takes the
* path with no bounce in it. The bounce exists for the other callers.
* O_DIRECT requires the file offset, transfer length and buffer address to be block-aligned.
* rad_dev_alloc memory is (host.cpp) and .rad pads movement units to RAD_ALIGN_UNIT
* (rad_format.h), so every mover read takes the unbounced path. The bounce is for other callers.
*/
#pragma once
#include <cstdint>
@@ -28,13 +21,9 @@ enum {
RAD_DIO_CREATE = 4,
RAD_DIO_TRUNC = 8,
/* Open buffered when the filesystem refuses O_DIRECT, instead of failing the open.
*
* Off by default, and that default is the point. The weight tier is sized in gigabytes and
* read in megabyte runs; a silent buffered fallback turns it into a page-cache pump that is
* three times slower and looks like nothing at all in a profile. An operator whose container
* sits on tmpfs wants to be told, not accommodated. The flag is for tests, which have to run
* on whatever /tmp happens to be. */
/* Open buffered when the filesystem refuses O_DIRECT, instead of failing. Off by default: a
* silent buffered fallback makes the weight tier ~3x slower and is invisible in a profile.
* For tests, which run on whatever /tmp is. */
RAD_DIO_ALLOW_BUFFERED = 16,
};
@@ -55,17 +44,14 @@ public:
int fd() const { return fd_; }
int64_t size() const;
/* Exact reads and writes: a short transfer is RAD_E_IO, never a partial success. A mover that
* has to check a byte count on every extent is a mover with a branch on the step path, and a
* caller that forgets to check gets half a weight. */
/* Exact reads and writes: a short transfer is RAD_E_IO, never a partial success, so callers
* need no byte-count check. */
int read_at(void* dst, int64_t off, int64_t bytes);
int write_at(const void* src, int64_t off, int64_t bytes);
/* The alignment every fast-path extent must satisfy. 4096 rather than the device's own logical
* block size (which is 512 on plenty of hardware, and queryable via STATX_DIOALIGN on a recent
* kernel): 4096 is a superset of every real requirement, it is RAD_ALIGN_UNIT, and accepting
* 512-aligned extents would only widen the fast path for extents the .rad container never
* produces. One constant, no per-filesystem behaviour to reproduce a bug against. */
/* The alignment every fast-path extent must satisfy. A fixed 4096 rather than the device's
* logical block size (often 512, see STATX_DIOALIGN): it covers every real requirement, equals
* RAD_ALIGN_UNIT, and keeps behaviour independent of the filesystem. */
static constexpr int64_t alignment() { return 4096; }
private:
+115 -152
View File
@@ -1,13 +1,10 @@
/* dispatch.cpp -- picks a backend once, then forwards.
*
* The only definition of every rad_dev_* / rad_stream_* / rad_event_* symbol in the engine.
* host.cpp and hip.cpp export vtables and nothing else, so there is no #ifdef anywhere above this
* file and no way for the two to end up implementing different contracts.
* The only definition of every rad_dev_* / rad_stream_* / rad_event_* symbol. host.cpp and hip.cpp
* export vtables only, so there is no #ifdef above this file and both backends share one contract.
*
* The selection rule: a build with HIP still runs the host backend when the machine shows no
* device. Having ROCm installed and having a card are separate facts -- a CI container with the
* headers and no `/dev/kfd` is the normal case -- and the honest response is to say which backend
* won at Info and carry on, not to fail at the first hipMalloc.
* A build with HIP still runs the host backend when no device is visible (e.g. a CI container
* with ROCm headers and no /dev/kfd); the chosen backend is logged at Info.
*/
#include "device.h"
#include "../rad_internal.h"
@@ -18,6 +15,7 @@
#include <cstring>
#include <atomic>
#include <cstdlib>
#include <iterator>
#include <map>
#include <mutex>
#include <string>
@@ -27,9 +25,8 @@
namespace rad {
/* ------------------------------------------------------------------ the error slot */
/* Thread-local and drained by reading, which is the ABI's own contract. One thread per rank plus
* the mover (spec §1), so a fault reported on the wrong thread would name the wrong half of the
* engine to an operator who has to decide whether to restart. */
/* Thread-local and cleared by reading, per the ABI. Each rank and the mover run on their own
* thread (spec §1), so an error must stay on the thread that raised it. */
static thread_local std::string t_last_error;
void device_set_error(const char* f, ...) {
@@ -39,23 +36,16 @@ void device_set_error(const char* f, ...) {
vsnprintf(buf, sizeof buf, f, ap);
va_end(ap);
t_last_error.assign(buf);
/* Debug rather than Error: most of these are answered by the caller (a pool that tries an
* allocation, finds it does not fit and asks the planner for a smaller one). The ones that are
* fatal are reported by whoever decided they were fatal, with context this layer does not have. */
/* Debug, not Error: callers often recover (e.g. a pool retrying smaller), and fatal ones are
* reported by the caller with more context. */
RAD_DEBUG("device: %s", buf);
}
/* ------------------------------------------------------------------ selection */
/* One line, listing every visible device by index and arch.
*
* This is not decoration. A machine reports more devices than it has accelerators: a workstation
* with two discrete cards and an APU reports three, and the integrated one claims tens of GiB of
* "VRAM" that is really system RAM. A --tp matching that count, or a planner that sums vram_bytes
* across devices, is wrong in a way that shows up as a memory error much later -- and the arch
* printed here is what tells the two kinds apart. The device layer does not filter -- which
* devices are usable is the engine's decision and it has rad_dev_props to make it with -- but it
* does not let the inventory go unsaid either (spec §16). */
/* The startup line's list of every visible device by index and arch. A machine may report more
* devices than accelerators: an APU shows up beside discrete cards and claims system RAM as
* "VRAM". The arch tells them apart. Filtering is the engine's decision (via rad_dev_props). */
static std::string device_inventory(const DeviceBackend* b) {
std::string s;
const int n = b->count();
@@ -68,15 +58,12 @@ static std::string device_inventory(const DeviceBackend* b) {
}
#if defined(RAD_HAVE_HIP) && RAD_HAVE_HIP
/* COMPUTE WAVE SAVE/RESTORE OFF IS A GPU HANG WAITING FOR AN EVICTION. The driver evicts a
* process's queues whenever host memory the card maps is moved or reclaimed under memory pressure,
* and a serve with a host pool or a host KV tier maps gigabytes of it. With
* amdgpu.cwsr_enable=0 it cannot preempt a running queue and waits for it to drain, which a queue
* a serve keeps fed never does: the queue stops inside whatever kernel it was running, MES fails
* REMOVE_QUEUE, and the driver resets the card. Said at startup because nothing later can tell
* that hang from a kernel bug -- and said here, as the backend comes up, and not only in the
* startup report: a hang during the load ends the process before the report prints, and the
* tools that bring a backend up (rad-kbench, rad-tune) print no report at all. */
/* With amdgpu.cwsr_enable=0 (compute wave save/restore off) a queue eviction hangs the GPU. The
* driver evicts a process's queues when card-mapped host memory is moved or reclaimed, and a serve
* maps gigabytes of it. Without CWSR the driver waits for the queue to drain, a busy queue never
* does, MES fails REMOVE_QUEUE and the card resets. Warned here as the backend comes up, not only
* in the startup report: a hang during load kills the process first, and rad-kbench and rad-tune
* print no report. */
static void warn_cwsr_off() {
FILE* f = std::fopen("/sys/module/amdgpu/parameters/cwsr_enable", "r");
if (!f) return;
@@ -90,11 +77,10 @@ static void warn_cwsr_off() {
"amdgpu.cwsr_enable=1 (module option, then rebuild the initramfs and reboot)");
}
/* THE HOST BACKEND IN A BUILD THAT HAS HIP STILL COUNTS THE GPU CODE PLUGINS BRING. The
* registration hooks are this build's own exported symbols and see every dlopen'ed kernel
* library's fat binaries, card or no card, so the plugin loader can bracket each dlopen and know
* which library brought device code. An engine serving here leaves that library's device rows out
* of selection (Registry::set_no_device_code); a tool that only selects keeps them. */
/* The host backend in a HIP build still counts plugin GPU code. This build's fat-binary
* registration hooks see every dlopen'ed kernel library, card or no card, so the plugin loader can
* tell which library brought device code. A serving engine drops those device rows from selection
* (Registry::set_no_device_code); a selection-only tool keeps them. */
static DeviceBackend g_host_beside_hip;
#endif
@@ -117,9 +103,7 @@ static const DeviceBackend* select_backend() {
return b;
}
/* std::call_once rather than a function-local static, because the answer is read from every rank
* thread and the guard variable's acquire load is the cheaper of the two on the paths that matter
* -- and because a backend chosen twice would be a backend chosen differently twice. */
/* Selected exactly once, under std::call_once; read from every rank thread. */
static const DeviceBackend* g_backend = nullptr;
static std::once_flag g_once;
@@ -135,36 +119,22 @@ const char* device_backend_name() { return dev()->name; }
/* ------------------------------------------------------------------ the ledger
*
* EVERY DEVICE ALLOCATION THIS ENGINE MAKES, COUNTED, because without it an unaccounted allocation
* can only be found by sampling /sys/class/drm through startup and correlating the steps against
* the log by eye.
* Counts every device allocation the engine makes. The VRAM budget (core/mem/vram_budget.cpp)
* spends the card down to --gpu-headroom-mib, so whatever lands outside the two pools and is not
* derived from the buffer plan or run configuration must be counted here.
*
* The VRAM budget (core/mem/vram_budget.cpp) spends the card down to --gpu-headroom-mib, which
* only works if what lands outside the two pools is known. Most of it is known by construction:
* the activation arena is computed from the buffer plan, the step batch staging from the run
* configuration. Everything else has to be counted here, because an allocation nobody counts is an
* allocation that eats the headroom and then fails somebody else's.
* Not seen: plugins that call hipMalloc directly (libr4d's split-tail workspaces and all-reduce
* peer scratch). Engine::start reads the card back after allocation for that reason.
*
* WHAT THIS DOES NOT SEE, and it is stated here because the number is only honest with the caveat
* attached: a kernel plugin that calls hipMalloc itself goes nowhere near this file. libr4d does,
* for its split-tail workspaces and its all-reduce peer scratch, and the engine's own accounting
* cannot include them. Engine::start reads the card back after everything has allocated for
* exactly that reason -- the ledger says what the core spent, the card says what was spent.
* RADIANCE_TRACE_ALLOC=N logs each allocation of at least N bytes.
*
* RADIANCE_TRACE_ALLOC=N logs every allocation of at least N bytes as it happens. That is the
* instrument; the counters are the summary.
*
* RADIANCE_DEBUG_POISON_ALLOC=B fills every fresh DEVICE allocation with byte B (0..255) before
* it is handed out, so a buffer that is read before anything wrote it shows up as garbage rather
* than as the zeros a wiped card hands back by luck. A card that has just been through a driver
* reset ("VRAM is lost") is that garbage for real, which is where such a read is otherwise first
* seen. A correct engine serves the same output with it set. RADIANCE_DEBUG_POISON_RANGE=lo:hi
* narrows the fill to device allocations with ordinal in [lo, hi) -- ordinals count from 1 in
* allocation order ON THE ALLOCATING THREAD, the `#n on this thread` the trace prints -- to bisect
* to the one allocation that matters. Both are instruments: the fill is synchronous, through one
* stream per thread and device that lives until exit (a stream is a hardware queue, and creating
* and destroying one per allocation is both slow and the queue churn ROCr's Trim path faults on).
* A byte outside 0..255 or a range that does not parse is refused at the first allocation. */
* RADIANCE_DEBUG_POISON_ALLOC=B fills every fresh DEVICE allocation with byte B (0..255), so a
* read-before-write shows up as garbage instead of lucky zeros (as after a driver reset, "VRAM is
* lost"). A correct engine serves the same output with it set. RADIANCE_DEBUG_POISON_RANGE=lo:hi
* limits the fill to device allocations with ordinal in [lo, hi), counted from 1 per allocating
* thread (the trace's `#n on this thread`), for bisecting. The fill is synchronous on one stream
* per thread and device, kept until exit: a stream is a hardware queue, and per-allocation queue
* churn is slow and faults in ROCr's Trim path. Bad values abort at the first allocation. */
namespace rad {
namespace {
@@ -172,12 +142,14 @@ struct Ledger {
std::atomic<int64_t> bytes{0};
std::atomic<int64_t> count{0};
};
Ledger g_ledger[4]; /* indexed by RAD_MEM_*; see rad_dev_alloc below for the bound check */
Ledger g_ledger[4]; /* indexed by RAD_MEM_*; rad_dev_alloc bounds the kind */
/* Event handles, counted here and not in a backend so the number means the same on both. An
* event a component forgets at teardown is reclaimed at exit and reported by nothing else, so
* this is the one place such a leak shows. */
/* 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};
/* Host blocks through the ABI (rad_event_sync, rad_stream_sync), counted here so a test can
* assert that a path never stops the host, whichever backend runs it. */
std::atomic<int64_t> g_host_blocks{0};
int64_t trace_floor() {
static const int64_t v = [] {
@@ -232,17 +204,21 @@ const char* kind_name(int kind) {
} /* namespace */
void rad_dev_alloc_totals(int kind, int64_t* bytes, int64_t* count) {
if (kind < 0 || kind >= 4) { if (bytes) *bytes = 0; if (count) *count = 0; return; }
if (kind < 0 || kind >= (int)std::size(g_ledger)) {
if (bytes) *bytes = 0;
if (count) *count = 0;
return;
}
if (bytes) *bytes = g_ledger[kind].bytes.load(std::memory_order_relaxed);
if (count) *count = g_ledger[kind].count.load(std::memory_order_relaxed);
}
int64_t rad_dev_live_events(void) { return g_live_events.load(std::memory_order_relaxed); }
int64_t rad_dev_host_blocks(void) { return g_host_blocks.load(std::memory_order_relaxed); }
/* ------------------------------------------------------------------ elastic memory */
/* See device.h for what this is for. What is here is the interval arithmetic and the two
* roundings; the backends do the mapping. */
/* See device.h. Interval arithmetic and rounding here; the backends do the mapping. */
namespace {
std::atomic<int64_t> g_vmem_committed{0};
@@ -250,10 +226,8 @@ std::atomic<int64_t> g_vmem_committed{0};
int64_t rad_dev_vmem_committed(void) { return g_vmem_committed.load(std::memory_order_relaxed); }
/* BOTH HALVES OF THE QUESTION. A backend can carry the entries and still be running on a device
* whose driver has no virtual memory manager -- d_vmem_granularity answers 0 there -- and a pool
* that asked only whether the function pointers existed would reserve an address range it could
* never back, then fail at the first commit instead of sizing itself whole at startup. */
/* Both checks: a backend may have the entries on a driver with no virtual memory manager
* (granularity 0). Checking only the pointers would reserve a range that can never be backed. */
bool VMem::supported() { return dev()->vmem_reserve != nullptr && VMem::granularity() > 0; }
int64_t VMem::granularity() {
if (!dev()->vmem_granularity) return 0;
@@ -271,8 +245,7 @@ int VMem::reserve(int64_t bytes, int64_t align) {
const int64_t g = granularity();
if (g <= 0) return RAD_E_UNSUPPORTED;
if (align <= 0) align = g;
/* ROUNDED UP TO A GRANULE, because the last granule of a range that is not a whole number of
* them can never be committed and the bytes in it are then reserved and unreachable. */
/* Round up to a granule: a partial last granule could never be committed. */
const int64_t want = align_up(bytes, g);
void* p = dev()->vmem_reserve(want, align);
if (!p) return RAD_E_NOMEM;
@@ -285,9 +258,8 @@ int VMem::reserve(int64_t bytes, int64_t align) {
void VMem::release() {
if (!base_) { size_ = 0; committed_ = 0; ext_.clear(); return; }
/* A range released with pages still in it leaks the pages and, on some drivers, refuses the
* address free as well -- so the teardown order is fixed here rather than asked of callers.
* Granule at a time, because that is how each of them was mapped. */
/* 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();
for (const auto& e : ext_) {
if (dev()->vmem_decommit && g > 0)
@@ -309,29 +281,20 @@ bool VMem::is_committed(int64_t off, int64_t bytes) const {
if (off >= e.first && off + bytes <= e.first + e.second) return true;
return false; /* extents are merged, so one of them covers it or none does */
}
/* WHAT TO MAP IS COMPUTED BEFORE ANYTHING IS MAPPED, and that is not a style choice. add_extent
* MERGES, so the list this walk is reading rearranges itself under the walk the moment a gap is
* filled -- the cursor then lands past the end of a list that just got shorter and the tail of the
* request is mapped a second time. On the host backend a double map silently succeeds and only
* the accounting is wrong; on a card the driver refuses it and a pool fails to grow.
/* The granules to map are gathered before mapping any: add_extent merges, so walking ext_ while
* mapping would skip entries and map the tail twice (the driver refuses a double map).
*
* ONE GRANULE PER CALL, AND THE ACCESS OVER THE RUN. Both halves of that are the driver's rule
* rather than a preference, and they pull in opposite directions:
*
* A mapping can only be unbacked exactly as it was backed, so a run mapped in one call is a run
* that can only be released whole. Mapping the granules separately is what lets a pool hand back
* the top of its range while it keeps the rest, which is the entire purpose of an elastic pool.
*
* Access, though, cannot be granted per granule: a granule that sits against an already-
* accessible one is refused on its own and accepted as part of the contiguous run containing
* both. So the maps are named one at a time and the access is named once, over every extent the
* new granules ended up part of -- which add_extent has already merged by then. Re-granting
* access over a range that has it is free and is what makes that simple. */
* Driver rules:
* - A mapping can only be unbacked exactly as it was backed, so each granule is mapped
* separately; that lets the pool hand back the top of its range.
* - 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. */
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();
if (g <= 0) return RAD_E_UNSUPPORTED;
/* OUTWARD: the caller asked for these bytes and must get all of them. */
/* Round outward: every requested byte must be committed. */
const int64_t lo = (off < 0 ? 0 : off / g * g);
int64_t hi = align_up(off + bytes, g);
if (hi > size_) hi = size_;
@@ -343,9 +306,8 @@ int VMem::commit(int64_t off, int64_t bytes) {
if (!is_committed(o, g)) want.push_back(o);
if (want.empty()) return RAD_OK;
/* A failure part way through leaves what already mapped mapped AND RECORDED. Half a grow is a
* smaller pool, which the caller can live with; half a grow the bookkeeping has forgotten is
* memory this process can neither use nor return. */
/* On a failure part way, what already mapped stays mapped and recorded: a partial grow is
* usable, untracked mappings are not. */
int rc = RAD_OK;
size_t took = 0;
for (; took < want.size(); ++took) {
@@ -354,9 +316,7 @@ int VMem::commit(int64_t off, int64_t bytes) {
add_extent(want[took], g);
}
/* AND THE ACCESS IS GRANTED EVEN WHEN THE GROW STOPPED SHORT, for the same reason. A pool that
* got half of what it asked for is one the caller can live with; one whose new granules are
* mapped and unreachable is not, and the granules that did map are in the run either way. */
/* Grant access even if the grow stopped short, so the granules that did map are usable. */
int prc = RAD_OK;
if (took > 0 && dev()->vmem_protect) {
for (const auto& e : ext_) {
@@ -366,9 +326,8 @@ int VMem::commit(int64_t off, int64_t bytes) {
}
}
if (prc < 0) {
/* MAPPED BUT UNREACHABLE IS WORSE THAN NOT MAPPED: the VRAM is spent and the first kernel
* to touch it faults. Give back exactly what this call took and leave the rest, which is
* reachable and was before. */
/* Mapped but inaccessible memory faults the first kernel that touches it. Undo exactly
* what this call mapped; earlier extents were already accessible. */
for (size_t i = 0; i < took; ++i) {
if (dev()->vmem_decommit) (void)dev()->vmem_decommit((char*)base_ + want[i], g);
drop_extent(want[i], g);
@@ -382,14 +341,13 @@ int VMem::decommit(int64_t off, int64_t bytes) {
if (!base_ || bytes <= 0) return bytes <= 0 ? RAD_OK : RAD_E_INVAL;
const int64_t g = granularity();
if (g <= 0) return RAD_E_UNSUPPORTED;
/* INWARD: a granule holding one byte the caller still wants stays. */
/* Round inward: a granule holding any byte outside the range stays. */
const int64_t lo = align_up(off < 0 ? 0 : off, g);
int64_t hi = (off + bytes) / g * g;
if (hi > size_) hi = size_;
if (lo >= hi) return RAD_OK;
/* Gathered first, for the same reason as commit, and unmapped one granule at a time because
* that is how each was mapped. */
/* Gathered first and unmapped per granule, as in commit. */
std::vector<int64_t> drop;
for (int64_t o = lo; o < hi; o += g)
if (is_committed(o, g)) drop.push_back(o);
@@ -405,9 +363,8 @@ int VMem::decommit(int64_t off, int64_t bytes) {
void VMem::add_extent(int64_t off, int64_t bytes) {
committed_ += bytes;
g_vmem_committed.fetch_add(bytes, std::memory_order_relaxed);
/* Insert in order, then absorb any neighbour it touches. Merging is not cosmetic: an extent
* list that grows by one per commit turns is_committed() into a scan of every call ever made,
* and the pool that uses this grows a granule at a time. */
/* Insert in order, then merge touching neighbours, so is_committed() stays a short scan
* although pools grow one granule at a time. */
size_t i = 0;
while (i < ext_.size() && ext_[i].first < off) ++i;
ext_.insert(ext_.begin() + (long)i, { off, bytes });
@@ -423,9 +380,8 @@ void VMem::add_extent(int64_t off, int64_t bytes) {
}
}
/* The inverse, and it takes a piece that lies WHOLLY INSIDE one extent by construction -- decommit
* clips every part it gathers to the extent it came from. What is left of that extent is nothing,
* a head, a tail, or both. */
/* 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) {
committed_ -= bytes;
g_vmem_committed.fetch_sub(bytes, std::memory_order_relaxed);
@@ -460,12 +416,11 @@ int rad_dev_props(int device, RadDeviceProps* o) { return dev()->props(device,
int rad_dev_enable_peer(int self, int peer) { return dev()->enable_peer(self, peer); }
void* rad_dev_alloc(int64_t bytes, int kind) {
/* The poison range is over THIS THREAD's device allocations, because a rank brings itself up on
* its own thread in a fixed order while the threads interleave freely: a process-wide ordinal
* would name a different allocation on every run, and a bisect over it would not converge. */
/* 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);
if (p && kind >= 0 && kind < 4) {
if (p && kind >= 0 && kind < (int)std::size(rad::g_ledger)) {
rad::g_ledger[kind].bytes.fetch_add(bytes, std::memory_order_relaxed);
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;
@@ -475,8 +430,7 @@ void* rad_dev_alloc(int64_t bytes, int kind) {
rad::kind_name(kind), rad::humanb(bytes).c_str(), (long long)ordinal,
(long long)rad::g_ledger[kind].bytes.load(std::memory_order_relaxed),
(long long)total);
/* The poison fill (see the top of this file). Through the backend's own stream so it
* holds on both backends; synchronous, so the bytes are there before the caller sees p. */
/* Poison fill (see the ledger header): synchronous, so it lands before p is returned. */
const int poison = rad::poison_byte();
if (poison >= 0 && kind == RAD_MEM_DEVICE && rad::poison_in_range(ordinal)) {
RadStream& s = t_poison_stream[t_device];
@@ -493,9 +447,8 @@ void* rad_dev_alloc(int64_t bytes, int kind) {
return p;
}
void rad_dev_free(void* p, int kind) {
/* The ledger tracks what was TAKEN, not what is live: rad_dev_free has no size and the
* backends do not keep one. Every caller in this engine frees at teardown and nowhere else,
* so the two numbers differ only after the run is over. */
/* The ledger counts allocations, not live bytes: rad_dev_free has no size. The engine frees
* only at teardown, so the two agree while running. */
dev()->free(p, kind);
}
void* rad_dev_host_ptr(void* p) { return dev()->host_ptr(p); }
@@ -503,7 +456,10 @@ void* rad_dev_device_ptr(void* p) { return dev()->device_ptr(p);
int rad_stream_create(RadStream* out, int hi) { return dev()->stream_create(out, hi); }
void rad_stream_destroy(RadStream s) { dev()->stream_destroy(s); }
int rad_stream_sync(RadStream s) { return dev()->stream_sync(s); }
int rad_stream_sync(RadStream s) {
rad::g_host_blocks.fetch_add(1, std::memory_order_relaxed);
return dev()->stream_sync(s);
}
} /* extern "C" */
@@ -537,38 +493,29 @@ int tape_set_overlap(RadTape t, int i, bool on) {
return dev()->tape_set_overlap ? dev()->tape_set_overlap(t, i, on ? 1 : 0) : RAD_E_UNSUPPORTED;
}
bool dev_integrated(int device) { return dev()->integrated && dev()->integrated(device) > 0; }
/* A FAILURE ANSWERED HERE, as "", is not one for the next reader of rad_dev_last_error: that
* reader is reporting a failure of its own and would name this one instead. The slot is put back
* as the call found it. */
std::string dev_pci_address(int device) {
char buf[64] = { 0 };
if (!dev()->pci_address) return std::string();
/* These getters answer "" on failure and restore the error slot, so the next
* rad_dev_last_error reader does not see an unrelated error. `get` fills a buffer of `n` bytes. */
template <class Get> static std::string dev_string(int n, Get get) {
std::string buf((size_t)n, '\0');
const std::string before = t_last_error;
if (dev()->pci_address(device, buf, (int)sizeof buf) < 0) {
if (get(buf.data(), n) < 0) {
t_last_error = before;
return std::string();
}
buf.resize(std::strlen(buf.c_str()));
return buf;
}
std::string dev_pci_address(int device) {
if (!dev()->pci_address) return std::string();
return dev_string(64, [&](char* b, int n) { return dev()->pci_address(device, b, n); });
}
std::string dev_dma_lane(int device) {
char buf[256] = { 0 };
if (!dev()->dma_lane) return std::string();
const std::string before = t_last_error;
if (dev()->dma_lane(device, buf, (int)sizeof buf) < 0) {
t_last_error = before;
return std::string();
}
return buf;
return dev_string(256, [&](char* b, int n) { return dev()->dma_lane(device, b, n); });
}
std::string dev_runtime_version() {
char buf[128] = { 0 };
if (!dev()->runtime_version) return std::string();
const std::string before = t_last_error;
if (dev()->runtime_version(buf, (int)sizeof buf) < 0) {
t_last_error = before;
return std::string();
}
return buf;
return dev_string(128, [&](char* b, int n) { return dev()->runtime_version(b, n); });
}
int dev_peer_access(int self, int peer) {
if (self == peer) return 1;
@@ -604,7 +551,10 @@ void rad_event_destroy(RadEvent e) {
int rad_event_record(RadEvent e, RadStream s) { return dev()->event_record(e, s); }
int rad_event_wait(RadStream s, RadEvent e) { return dev()->event_wait(s, e); }
int rad_event_query(RadEvent e) { return dev()->event_query(e); }
int rad_event_sync(RadEvent e) { return dev()->event_sync(e); }
int rad_event_sync(RadEvent e) {
rad::g_host_blocks.fetch_add(1, std::memory_order_relaxed);
return dev()->event_sync(e);
}
void rad_dev_host_wrote(void) { dev()->host_wrote(); }
int rad_event_elapsed_ms(RadEvent a, RadEvent b, float* out) {
return dev()->event_elapsed_ms(a, b, out);
@@ -673,9 +623,22 @@ void* rad_dev_alloc_uncached(int64_t bytes) {
void rad_dev_free_uncached(void* p) {
if (const auto f = dev()->free_uncached) f(p);
}
int rad_stream_gate(RadStream s, void** gate) {
if (gate) *gate = nullptr;
if (const auto f = dev()->stream_gate) return f(s, gate);
rad::device_set_error("rad_stream_gate: the %s backend has no gates", dev()->name);
return RAD_E_UNSUPPORTED;
}
int rad_gate_open(void* gate) {
if (const auto f = dev()->gate_open) return f(gate);
return RAD_E_UNSUPPORTED;
}
int64_t rad_gate_room(RadStream s) {
if (const auto f = dev()->gate_room) return f(s);
return 0;
}
/* Cleared by reading it, per the header. Never null: a caller printing "%s" on a path where
* nothing failed should get an empty line, not a segfault. */
/* Cleared by reading. Never null; "" when nothing failed. */
const char* rad_dev_last_error(void) {
static thread_local std::string drained;
drained.swap(rad::t_last_error);
+44 -78
View File
@@ -1,16 +1,14 @@
/* hip.cpp -- the HIP half of the device backend: devices, memory and elastic memory.
*
* Streams, events, copies and fills are not here. They are AQL packets the engine writes into
* queues it owns (aql.cpp), which starts from this table and fills in the rest -- pinned host
* memory included, because the copies have to recognise it.
* Streams, events, copies and fills are AQL packets on engine-owned queues (aql.cpp), which
* starts from this table and fills in the rest, pinned host memory included because the copies
* must recognise it.
*
* Thin by design. Every entry point is one hip* call plus an error capture, because anything
* cleverer than that is a place where the host backend and this one can disagree, and the host
* backend is where all of it is tested (docs/IMPLEMENTATION.md). If a call here grows a policy,
* the policy belongs in the component that wanted it, not in the device layer.
* Thin by design: each entry point is one hip* call plus error capture, so it cannot diverge from
* the host backend, where the logic is tested (docs/IMPLEMENTATION.md). Policy belongs in the
* component that wants it.
*
* The whole file compiles to nothing without RAD_HAVE_HIP, so a no-ROCm configure builds it and
* gets an empty object rather than needing the source list to know about the backend split.
* Compiles to nothing without RAD_HAVE_HIP, so the source list needs no backend split.
*/
#include "device.h"
@@ -36,9 +34,7 @@
namespace rad {
namespace {
/* One place that turns a hipError_t into a RAD_E_*. The mapping is coarse on purpose: the string
* carries the detail, the code carries the class, and a caller that wants to know exactly what the
* driver said reads rad_dev_last_error(). */
/* Maps a hipError_t to a coarse RAD_E_* class; the detail goes to rad_dev_last_error(). */
int hip_fail(hipError_t e, const char* who) {
device_set_error("%s: %s (%s)", who, hipGetErrorString(e), hipGetErrorName(e));
switch (e) {
@@ -55,9 +51,8 @@ int hip_fail(hipError_t e, const char* who) {
do { hipError_t _e = (call); \
if (_e != hipSuccess) return hip_fail(_e, #call); } while (0)
/* For the calls whose caller returns void -- the frees and the destroys. A failing teardown is
* still worth naming: hipFree returning anything but success means the pointer was not what the
* caller thought it was, and the next allocation of that class is the one that will look wrong. */
/* For void callers (frees, destroys): a failing teardown is still logged, since it means the
* pointer was not what the caller thought. */
void hip_note(hipError_t e, const char* who) {
if (e != hipSuccess) RAD_WARN("device: %s: %s", who, hipGetErrorString(e));
}
@@ -79,24 +74,14 @@ int d_set(int device) {
/* ------------------------------------------------------------------ how much VRAM is really free
*
* hipMemGetInfo IS NOT THE ANSWER ON THIS DRIVER, and the error is large enough to pay for.
* On a card that also drives a display, hipMemGetInfo's "free" sits up to 0.7 GiB below the
* amdgpu driver's own per-card accounting, and that gap is allocatable. So read the driver's
* counters (bytes, per card, all processes) from the drm node matched by PCI slot. The node's
* total must equal HIP's total, so both describe the same memory; any failure returns -1 and the
* caller keeps hipMemGetInfo. -1 on every non-amdgpu platform.
*
* On a card that also drives a display, hipMemGetInfo's "free" sits up to 0.7 GiB below what the
* amdgpu driver's own per-card accounting reports as unused -- while two otherwise identical cards
* differ by only tens of MiB in the driver's numbers. That gap is not memory anything holds: a run
* budgeted past hipMemGetInfo's figure allocates all of it and serves, with sysfs still reporting
* hundreds of MiB unused afterwards. Believing HIP's number costs that 0.7 GiB, which on a model
* whose experts do not fit is most of a millisecond a decode step.
*
* amdgpu publishes its own accounting, in bytes, per card, counting every process on it. Match the
* HIP device to a drm node by PCI slot and read it. Two guards: the node's total must equal the
* total HIP reports, so the two accountings are known to be the same accounting, and any failure
* at any step falls back to hipMemGetInfo rather than inventing a number.
*
* Returns -1 when sysfs cannot answer, which is every non-amdgpu platform.
*
* The node's `mem_info_vram_used` is also kept open, per device, for d_vram_used: an observer
* reads the card through that one descriptor and never through the runtime. */
* The node's `mem_info_vram_used` is also kept open per device for d_vram_used, so an observer
* reads the card through that descriptor and never through the runtime. */
constexpr int kMaxVramNodes = 64;
std::atomic<int> g_vram_used_fd[kMaxVramNodes] = {}; /* 0: not opened; else the fd plus one */
@@ -144,8 +129,7 @@ static int64_t sysfs_vram_free(int device, int64_t total) {
}
return -1;
}
/* A sysfs attribute is regenerated by a read at offset 0, so the descriptor is read with pread and
* never moved. */
/* A sysfs attribute is regenerated by a read at offset 0, so read with pread at 0. */
int d_vram_used(int device, int64_t* out) {
if (!out || device < 0 || device >= kMaxVramNodes) return RAD_E_INVAL;
const int fd = g_vram_used_fd[device].load(std::memory_order_acquire) - 1;
@@ -166,8 +150,7 @@ int d_integrated(int device) {
return hipDeviceGetAttribute(&v, hipDeviceAttributeIntegrated, device) == hipSuccess ? v : 0;
}
/* /proc/meminfo's MemAvailable: what the host could still hand out without swapping, -1 when it
* cannot be read. */
/* /proc/meminfo's MemAvailable in bytes, or -1. */
static int64_t host_mem_available() {
FILE* f = std::fopen("/proc/meminfo", "r");
if (!f) return -1;
@@ -185,17 +168,12 @@ int d_props(int device, RadDeviceProps* out) {
HIP_TRY(hipGetDeviceProperties(&p, device));
std::memset(out, 0, sizeof *out);
/* TRUNCATION IS INTENDED AND IS SAID SO. HIP's name and gcnArchName are 256 bytes each and
* these fields are 128 and 32; snprintf would cut them safely anyway, but silently enough that
* gcc warns about it, and a build that carries a warning nobody intends to act on is a build
* whose warnings stop being read. The explicit precision is the same cut, declared. Real
* values are far inside both -- a product name and a gcnArchName run to a couple of dozen
* characters -- so this is about the bound, not about the data. */
/* Intended truncation: HIP's fields are 256 bytes, ours 128 and 32. The explicit precision
* silences gcc's truncation warning; real values are a few dozen characters. */
snprintf(out->name, sizeof out->name, "%.*s", (int)(sizeof out->name) - 1, p.name);
snprintf(out->arch, sizeof out->arch, "%.*s", (int)(sizeof out->arch) - 1, p.gcnArchName);
/* gcnArchName carries the feature suffixes -- "gfx1201:sramecc-:xnack-". The arch a kernel
* plugin's constraints match on is the bare target, so cut at the colon here rather than
* making every consumer do it. */
/* Strip feature suffixes ("gfx1201:sramecc-:xnack-"): plugin constraints match the bare
* target. */
if (char* c = std::strchr(out->arch, ':')) *c = '\0';
out->device_id = device;
@@ -205,10 +183,8 @@ int d_props(int device, RadDeviceProps* out) {
out->lds_bytes = (int64_t)p.sharedMemPerBlock;
out->is_host_backend = 0;
/* hipMemGetInfo reports the CURRENT device, so ask about `device` by visiting it. That costs
* two context switches on a call nobody makes per step -- props is read at startup and by
* rad-info -- and the alternative is a vram_free that silently describes the wrong card under
* tensor parallel. */
/* hipMemGetInfo reports the current device, so switch to `device` and back. props is not
* called per step. */
int prev = 0;
bool moved = false;
if (hipGetDevice(&prev) == hipSuccess && prev != device &&
@@ -219,30 +195,24 @@ int d_props(int device, RadDeviceProps* out) {
out->vram_free = (int64_t)freeb;
if (totalb) out->vram_bytes = (int64_t)totalb;
}
/* And then prefer the driver's own counter where it can be read -- see sysfs_vram_free. The
* fallback above is what every non-amdgpu platform gets; it is conservative by up to a GiB on
* a card that drives a display. */
/* Prefer the driver's counter where readable (see sysfs_vram_free). */
{
const int64_t sf = sysfs_vram_free(device, out->vram_bytes);
if (sf >= 0) {
out->vram_free = sf;
} else if (d_integrated(device)) {
/* INTEGRATED GRAPHICS WHOSE "DEVICE MEMORY" IS THE HOST'S. When the runtime reports
* more than the carve-out the driver counts as VRAM, the rest is system RAM mapped for
* the GPU, and the runtime's free figure knows nothing of the other processes using
* it: a budget derived from it claims memory the machine is already running on. What
* the host can still give is the bound. A carve-out the runtime reports as it is --
* the case sysfs answers above -- is dedicated memory and is left alone. */
/* Integrated GPU whose reported memory exceeds the driver's carve-out: the rest is
* system RAM, and the runtime's free figure ignores other processes using it. Bound
* it by MemAvailable. (A carve-out reported as-is is answered by sysfs above.) */
const int64_t avail = host_mem_available();
if (avail >= 0 && avail < out->vram_free) out->vram_free = avail;
}
}
/* A failed restore leaves this thread pointed at the wrong card, which under tensor parallel
* is a rank quietly working on its neighbour's memory. Say so. */
/* A failed restore leaves this thread on the wrong card; under TP that is a rank working on
* its neighbour's memory, so it is logged. */
if (moved) HIP_NOTE(hipSetDevice(prev));
/* Whether any peer is reachable at all. The engine asks for a specific pair through
* rad_dev_enable_peer; this flag is for the report. */
/* Whether any peer is reachable, for the report; pairs go through rad_dev_enable_peer. */
int n = d_count();
for (int i = 0; i < n && !out->supports_p2p; ++i) {
if (i == device) continue;
@@ -258,8 +228,8 @@ int d_peer_access(int self, int peer) {
return can ? 1 : 0;
}
/* The runtime's bus id, rewritten in the kernel's spelling (lower case, four-digit domain) so it
* names the same directory under /sys/bus/pci/devices. */
/* The runtime's bus id in the kernel's spelling (lower case, four-digit domain), matching
* /sys/bus/pci/devices. */
int d_pci_address(int device, char* out, int cap) {
if (!out || cap <= 0) return RAD_E_INVAL;
char bus[64] = { 0 };
@@ -297,8 +267,8 @@ int d_enable_peer(int self, int peer) {
HIP_TRY(hipSetDevice(self));
hipError_t e = hipDeviceEnablePeerAccess(peer, 0);
HIP_NOTE(hipSetDevice(prev));
/* Already enabled is success. The kernel plugin's init() hook runs per resolved instance
* (spec §2.1) and several instances legitimately want the same pair. */
/* Already enabled is success: init() runs per resolved instance (spec §2.1) and several may
* want the same pair. */
if (e != hipSuccess && e != hipErrorPeerAccessAlreadyEnabled)
return hip_fail(e, "hipDeviceEnablePeerAccess");
return RAD_OK;
@@ -319,12 +289,11 @@ void* d_alloc(int64_t bytes, int kind) {
break;
case RAD_MEM_HOST_PINNED:
case RAD_MEM_HOST_MAPPED:
/* The AQL backend's, which pins host memory through ROCr in pieces the IOMMU can map
* (aql.cpp, "pinned host memory, in pieces"). */
/* Pinned by the AQL backend through ROCr (aql.cpp, "pinned host memory, in pieces"). */
device_set_error("rad_dev_alloc: pinned host memory is the AQL backend's");
return nullptr;
case RAD_MEM_HOST:
/* Pageable. Aligned to a page anyway so the same buffer can be an O_DIRECT target. */
/* Pageable, page-aligned so it can be an O_DIRECT target. */
if (posix_memalign(&p, 4096, (size_t)((bytes + 4095) / 4096 * 4096)) != 0) p = nullptr;
if (!p) e = hipErrorOutOfMemory;
break;
@@ -367,7 +336,7 @@ void* d_device_ptr(void* p) {
hipPointerAttribute_t a{};
if (hipPointerGetAttributes(&a, p) != hipSuccess) return nullptr;
if (a.devicePointer) return a.devicePointer;
/* A mapped host allocation that the attribute query did not resolve: ask the explicit way. */
/* Mapped host allocation not resolved by the attribute query. */
void* d = nullptr;
if (hipHostGetDevicePointer(&d, p, 0) == hipSuccess) return d;
return nullptr;
@@ -378,22 +347,20 @@ const DeviceBackend g_hip = {
"hip",
d_count, d_set, d_props, d_enable_peer,
d_alloc, d_free, d_host_ptr, d_device_ptr,
/* Streams, events, copies and fills: the AQL backend's (aql.cpp), which starts from this
* table and fills these in. */
/* Streams, events, copies and fills: filled in by the AQL backend (aql.cpp). */
nullptr, nullptr, nullptr,
nullptr, nullptr, nullptr, nullptr,
nullptr, nullptr, nullptr,
nullptr,
nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr,
/* Recorded passes: likewise the AQL backend's. */
/* Recorded passes: AQL backend. */
nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr,
/* Elastic memory: likewise the AQL backend's, which reserves and backs ranges through HSA
* (aql.cpp, "elastic memory, through HSA"). */
/* Elastic memory: AQL backend, through HSA (aql.cpp, "elastic memory, through HSA"). */
nullptr, nullptr, nullptr, nullptr, nullptr, nullptr,
d_vram_used,
/* Plugin device code: the AQL backend's, which owns the fat-binary registrations. */
/* Plugin device code: AQL backend, which owns the fat-binary registrations. */
nullptr, nullptr,
d_integrated,
d_peer_access,
@@ -409,8 +376,7 @@ const DeviceBackend* hip_backend_if_present(void) {
int n = 0;
hipError_t e = hipGetDeviceCount(&n);
if (e != hipSuccess || n <= 0) {
/* Not an error and not a warning: a HIP build on a machine with no visible card is a
* supported configuration, it is just the host one. dispatch.cpp says so at Info. */
/* Supported configuration (host backend); dispatch.cpp logs it at Info. */
RAD_DEBUG("device: hipGetDeviceCount -> %s, %d device(s)", hipGetErrorName(e), n);
return nullptr;
}
+187 -169
View File
@@ -1,24 +1,16 @@
/* host.cpp -- the host device backend.
*
* This is a primary development target, not a fallback. On a machine with no ROCm the builder, the
* planner, the mover, the scheduler, the KV manager, the tokeniser, the sampler's host reference
* chain and the server all run and are tested through these fourteen calls
* (docs/IMPLEMENTATION.md). It is also the code path a RAD_DOMAIN_HOST kernel runs on when the
* planner puts a layer on the CPU, which is the fourth row of spec §5.1's table.
* A primary development target, not a fallback: without ROCm the whole engine (builder, planner,
* mover, scheduler, KV manager, tokeniser, sampler host reference, server) runs and is tested
* through these calls (docs/IMPLEMENTATION.md). It is also where RAD_DOMAIN_HOST kernels run when
* the planner puts a layer on the CPU (spec §5.1).
*
* The one design decision worth defending: **the streams are real.** Each stream is an in-order
* work queue with its own worker thread, and an event is a sequence number that a stream reaches.
* A backend whose "async" calls execute inline would let ordering bugs -- a missing
* rad_event_wait, a buffer reused before the mover's copy landed -- pass every test here and
* corrupt weights on a real device. The cost is one thread per stream and one condition-variable
* wake per enqueue, which is nothing against the value of exercising the contract the HIP backend
* actually has.
* The streams are real: each is an in-order queue with its own worker thread, and an event is a
* sequence number the stream reaches. Inline "async" calls would let ordering bugs (a missing
* rad_event_wait, a buffer reused before a copy landed) pass here and corrupt a real device.
*
* The second: **no allocation on the step path.** The mover enqueues a transfer per weight per
* layer dispatch, so the queue is a fixed-capacity ring of POD tasks sized at stream creation, not
* a deque of std::function. A std::function holding a destination, a source and a length does not
* fit libstdc++'s small-object buffer and would call operator new inside rad_memcpy_async, which
* is exactly the thing docs/IMPLEMENTATION.md forbids on the step path.
* No allocation on the step path: the queue is a fixed-capacity ring of POD tasks, not
* std::function, which would heap-allocate inside rad_memcpy_async.
*/
#include "device.h"
#include "../rad_internal.h"
@@ -41,36 +33,27 @@ namespace {
using Clock = std::chrono::steady_clock;
/* Every allocation kind maps to page-aligned host memory. 4096 is not arbitrary: it is
* RAD_ALIGN_UNIT, the .rad container's movement unit, and it is what O_DIRECT demands of a buffer
* (directio.cpp), so a pinned pool allocated here is directly usable as a file-tier landing zone
* with no bounce. */
/* Every allocation kind is page-aligned host memory. 4096 is RAD_ALIGN_UNIT and the O_DIRECT
* buffer alignment (directio.cpp), so pools here are file-tier targets without a bounce. */
constexpr int64_t kAlign = 4096;
/* A stream's queue depth. Deep enough that a layer dispatch's worth of mover transfers plus the
* compute stream's issues never touch the backpressure path; shallow enough that the ring is a
* few tens of KiB. Enqueue onto a full ring blocks, which is honest -- a saturated hardware queue
* does the same thing -- and it is the only place in this file a caller can be made to wait. */
/* Per-stream queue depth: enough that a layer's mover transfers plus compute issues never hit
* backpressure, small enough for a ring of a few tens of KiB. Enqueue onto a full ring blocks, as
* on a saturated hardware queue. */
constexpr size_t kQueueDepth = 1024;
/* Tensor-parallel world sizes past 8 are not served: libr4d supplies 2/4/8-rank all-reduce and
* nothing wider (spec §9), so a fake host backend that claimed 16 cards would only ever produce a
* declare-time miss further down. */
/* libr4d all-reduce supports at most 8 ranks (spec §9), so more fake devices are useless. */
constexpr int kMaxFakeDevices = 8;
/* ------------------------------------------------------------------ events */
/* An event is a pair of sequence numbers. `recorded` advances on the host, at the moment
* rad_event_record is called; `completed` advances on the stream's worker, when the queue reaches
* that record. The event is complete when the second has caught the first, which is exactly HIP's
* rule that re-recording an event makes it pending again.
/* An event is two sequence numbers: `recorded` advances on the host at rad_event_record,
* `completed` on the stream worker when it reaches that record. Complete when completed has caught
* up, so re-recording makes it pending again, as in HIP.
*
* `refs` is one for the caller's handle plus one for every queued task that names the event.
* HIP lets a caller destroy an event whose record or wait is still queued -- the call returns and
* the resources go once the queue is past them -- and teardown code written against a card does
* exactly that. Freeing the object at rad_event_destroy instead leaves those tasks pointing at
* freed memory, and the worker that reaches one locks a mutex whose bytes the allocator has
* overwritten: the stream wedges and the rad_stream_destroy behind it never returns. */
* `refs` counts the handle plus every queued task naming the event. HIP allows destroying an event
* whose record or wait is still queued; freeing it at destroy would leave the worker locking a
* freed mutex and wedge the stream. */
struct HostEvent {
std::mutex m;
std::condition_variable cv;
@@ -83,7 +66,7 @@ struct HostEvent {
void event_retain(HostEvent* e) { e->refs.fetch_add(1, std::memory_order_relaxed); }
/* The last reference out frees it, whether that is the handle or the last task naming it. */
/* The last reference, handle or task, frees it. */
void event_release(HostEvent* e) {
if (e->refs.fetch_sub(1, std::memory_order_acq_rel) == 1) delete e;
}
@@ -116,17 +99,23 @@ struct HostStream {
uint64_t submitted = 0; /* tasks ever pushed */
uint64_t retired = 0; /* tasks ever finished executing */
int gates = 0; /* closed gates (rad_stream_gate) queued on this stream */
std::thread worker;
};
void stream_run(HostStream* s);
/* Push one task, blocking while the ring is full; see kQueueDepth. Always succeeds -- there is no
* "stream is closing" state to report, because rad_stream_destroy queues its stop behind the work
* already submitted rather than racing it. */
/* Push one task, blocking while the ring is full. Fails only behind a closed gate: the ring cannot
* drain until the host opens it, and the host is the caller. Destroy queues its stop behind
* submitted work, so there is no closing state. */
int stream_push(HostStream* s, const Task& t) {
std::unique_lock<std::mutex> lk(s->m);
if (s->count >= s->ring.size() && s->gates > 0) {
device_set_error("a submission onto a full stream behind a closed gate: open the gate "
"(rad_gate_open) first");
return RAD_E_STATE;
}
s->cv_room.wait(lk, [s] { return s->count < s->ring.size(); });
s->ring[s->tail] = t;
s->tail = (s->tail + 1) % s->ring.size();
@@ -156,9 +145,7 @@ void stream_run(HostStream* s) {
break;
case Task::Copy2D:
/* a = dpitch, b = spitch, c = width bytes, d = height rows. Row by row, because
* the pitches are what make a 2D copy a 2D copy: a KV block's rows are strided by
* the pool's row pitch, not packed. */
/* a = dpitch, b = spitch, c = width bytes, d = height rows. */
for (int64_t r = 0; r < t.d; ++r)
std::memcpy((uint8_t*)t.dst + r * t.a, (const uint8_t*)t.src + r * t.b,
(size_t)t.c);
@@ -189,10 +176,8 @@ void stream_run(HostStream* s) {
}
case Task::Wait: {
/* The worker blocks here, which is the whole point: no host thread synchronises,
* the *stream* does (spec §5.4). A wait whose event is only ever recorded later on
* this same stream wedges the stream -- which is precisely what the same construction
* does to a hardware queue, so it is a bug to catch, not a case to smooth over. */
/* The stream blocks, not a host thread (spec §5.4). Waiting on an event recorded
* later on this same stream wedges it, as it would a hardware queue. */
std::unique_lock<std::mutex> lk(t.ev->m);
t.ev->cv.wait(lk, [&t] { return t.ev->completed >= t.seq; });
break;
@@ -202,7 +187,7 @@ void stream_run(HostStream* s) {
done = true;
break;
}
/* After the task's lock has gone out of scope: this may be the last reference. */
/* After the event lock is released: this may be the last reference. */
if (t.ev) event_release(t.ev);
{
@@ -228,33 +213,24 @@ std::unordered_map<void*, AllocRec>& alloc_table() {
return t;
}
/* Per-device VRAM accounting, so rad_dev_props reports a vram_free that moves. The placement
* planner's "did it fit" path is one of the things the host backend exists to exercise, and a
* constant vram_free would let a plan that overcommits a real card pass here (spec §5.3). */
/* Per-device VRAM accounting, so vram_free moves and the planner's fit checks are exercised
* (spec §5.3). */
std::atomic<int64_t> g_used[kMaxFakeDevices];
/* A map lookup under a mutex on every alloc and free is fine and stays fine: allocation happens at
* load and at pool construction, never inside rad_arch_step. If that ever changes, it is a
* declare-phase bug and this mutex is where it will show up. */
/* A mutex-guarded map is fine: allocation happens at load and pool construction, never inside
* rad_arch_step. */
void alloc_note(void* p, int64_t bytes, int kind, int device) {
std::lock_guard<std::mutex> lk(alloc_mutex());
alloc_table()[p] = AllocRec{bytes, kind, device};
}
bool alloc_take(void* p, AllocRec* out) {
std::lock_guard<std::mutex> lk(alloc_mutex());
auto it = alloc_table().find(p);
if (it == alloc_table().end()) return false;
*out = it->second;
alloc_table().erase(it);
return true;
}
bool alloc_find(void* p, AllocRec* out) {
/* The record of allocation `p`, removed from the table when `take`. */
bool alloc_find(void* p, AllocRec* out, bool take = false) {
std::lock_guard<std::mutex> lk(alloc_mutex());
auto it = alloc_table().find(p);
if (it == alloc_table().end()) return false;
*out = it->second;
if (take) alloc_table().erase(it);
return true;
}
@@ -273,9 +249,8 @@ int64_t env_i64(const char* key, int64_t dflt) {
}
int host_count() {
/* Memoised: the device count must not change under a rank thread that already called
* rad_dev_set. RADIANCE_HOST_DEVICES is how tensor-parallel code gets tested without two
* cards -- two ranks, two budgets, one address space (spec §9). */
/* Memoised so the count cannot change under a rank thread. RADIANCE_HOST_DEVICES fakes
* several devices in one address space for testing tensor parallel without cards (spec §9). */
static int n = [] {
int64_t v = env_i64("RADIANCE_HOST_DEVICES", 1);
if (v < 1) v = 1;
@@ -289,9 +264,7 @@ int host_count() {
return n;
}
/* Per-thread, matching hipSetDevice: spec §1 gives one thread per tensor-parallel rank, each
* owning one device, so the current device is a property of the rank thread and never of the
* process. */
/* Per-thread, matching hipSetDevice: one thread per rank, one device per rank (spec §1). */
thread_local int t_device = 0;
int64_t physical_ram() {
@@ -300,12 +273,8 @@ int64_t physical_ram() {
return (int64_t)pages * (int64_t)page;
}
/* The budget the placement planner plans against. Read on every call rather than memoised: props
* is not on the step path, and re-reading is what lets a test set the budget and see it.
*
* The default is half of physical RAM, divided by the fake device count -- a two-"card" host
* backend that each claimed half the machine would let a plan pass here that cannot be loaded, and
* the planner is exactly the component this budget exists to falsify. */
/* The fake per-device VRAM budget. Read on every call so a test can change it. Default: half of
* physical RAM, split across the fake devices so their sum is loadable. */
int64_t host_vram_bytes() {
int64_t mib = env_i64("RADIANCE_HOST_VRAM_MIB", 0);
if (mib > 0) return mib << 20;
@@ -358,30 +327,23 @@ int h_props(int device, RadDeviceProps* out) {
snprintf(out->arch, sizeof out->arch, "host");
out->device_id = device;
/* Threads, divided the same way the budget is: a fake two-device backend on a 32-core box is
* two 16-"CU" devices, so a kernel plugin's occupancy arithmetic sees a coherent machine
* rather than two copies of the whole one. */
/* Hardware threads split across fake devices, like the budget. */
unsigned hw = std::thread::hardware_concurrency();
out->n_cu = (int)((hw ? hw : 1u) / (unsigned)host_count());
if (out->n_cu < 1) out->n_cu = 1;
/* A host lane is one element wide. Any code that divides a tile by warp_size gets the honest
* answer for a scalar backend. */
/* A host lane is one element wide. */
out->warp_size = 1;
out->vram_bytes = host_vram_bytes();
int64_t used = g_used[device].load(std::memory_order_relaxed);
out->vram_free = out->vram_bytes > used ? out->vram_bytes - used : 0;
/* There is no LDS on a CPU, and this is a stand-in with one job. Budget arithmetic of the
* form "how many tiles fit in LDS" divides by this, and a zero would trap on the backend
* whose whole purpose is to run that arithmetic on a machine with no card. The figure is a
* conventional per-workgroup scratch budget, not a property of this machine: host kernels are
* not LDS-bound and must not read it as a limit. */
/* A CPU has no LDS. Nonzero because budget arithmetic divides by it; a conventional
* per-workgroup figure, not a limit host kernels should honour. */
out->lds_bytes = 64 * 1024;
/* Every fake device shares one address space, so peer access is not merely available, it is
* the only thing there is. */
/* All fake devices share one address space. */
out->supports_p2p = 1;
out->is_host_backend = 1;
return RAD_OK;
@@ -406,13 +368,9 @@ void* h_alloc(int64_t bytes, int kind) {
return nullptr;
}
void* p = nullptr;
/* All four kinds are the same aligned host memory here. The distinction still matters and is
* still recorded, because the planner reasons in kinds and on a real device rad_dev_free has
* to give the right one back; the host backend's job is to make that code run, not to make the
* distinction vanish. */
/* Rounded up to a whole page as well as aligned to one, so a buffer handed to DirectFile can
* receive the aligned superset of a misaligned extent without overrunning. That is the same
* reason .rad pads its movement units to RAD_ALIGN_UNIT. */
/* All kinds are the same memory here, but the kind is recorded so mismatched frees are
* caught. The size is rounded up to whole pages so DirectFile can read an aligned superset
* into it without overrunning. */
if (posix_memalign(&p, (size_t)kAlign, (size_t)align_up(bytes, kAlign)) != 0 || !p) {
device_set_error("rad_dev_alloc(%lld, kind=%d): out of host memory",
(long long)bytes, kind);
@@ -427,9 +385,8 @@ void* h_alloc(int64_t bytes, int kind) {
void h_free(void* p, int kind) {
if (!p) return;
AllocRec r;
if (!alloc_take(p, &r)) {
/* Not ours. Freeing it would be a heap corruption three frames later, which is the class of
* bug the plugin ABI's C-only rule exists to avoid; refuse loudly instead. */
if (!alloc_find(p, &r, /*take=*/true)) {
/* Not ours: freeing it would corrupt the heap, so refuse and warn. */
RAD_WARN("rad_dev_free(%p, kind=%d): pointer was not allocated by the device layer",
p, kind);
return;
@@ -440,10 +397,8 @@ void h_free(void* p, int kind) {
std::free(p);
}
/* Both views are the same pointer: on this backend the zero-copy execution site of spec §5.1 is
* degenerate, and that is the correct answer rather than a shortcut -- the bytes really are
* reachable from both sides without a transfer. Null for a pointer the layer did not allocate,
* which is what the ABI's "null if the kind has no such view" means here. */
/* Host and device views are the same pointer (spec §5.1 zero-copy is trivial here). Null for a
* pointer the device layer did not allocate. */
void* h_host_ptr(void* p) {
if (!p) return nullptr;
AllocRec r;
@@ -453,10 +408,8 @@ void* h_device_ptr(void* p) { return h_host_ptr(p); }
int h_stream_create(RadStream* out, int high_priority) {
if (!out) return RAD_E_INVAL;
/* Priority is accepted and ignored. The mover and the compute stream ask for different
* priorities on a real device and the same code has to run here; raising a thread's scheduling
* class needs privileges this process does not have and would buy nothing on a queue that is
* one thread deep. */
/* Priority is ignored: raising a thread's scheduling class needs privileges and buys nothing
* on a one-thread queue. */
(void)high_priority;
auto* s = new (std::nothrow) HostStream();
if (!s) { device_set_error("rad_stream_create: out of memory"); return RAD_E_NOMEM; }
@@ -471,9 +424,7 @@ void h_stream_destroy(RadStream st) {
auto* s = (HostStream*)st;
Task t;
t.kind = Task::Stop;
/* Queued behind everything already submitted, so destroy drains rather than discards -- the
* mover's last transfer must land before its stream goes away, or a weight is half-written and
* nothing says so. */
/* Queued behind submitted work, so destroy drains rather than discards. */
stream_push(s, t);
if (s->worker.joinable()) s->worker.join();
delete s;
@@ -486,16 +437,20 @@ int h_stream_sync(RadStream st) {
}
auto* s = (HostStream*)st;
std::unique_lock<std::mutex> lk(s->m);
/* Snapshot: sync waits for work submitted *before* this call, not for work another thread
* pushes while we wait. That is hipStreamSynchronize's contract and the scheduler depends on
* it -- a sync that could never return under a busy mover would be a step-path stall. */
if (s->gates > 0) {
device_set_error("rad_stream_sync: the stream waits at a closed gate, which only "
"rad_gate_open releases");
return RAD_E_STATE;
}
/* 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->cv_done.wait(lk, [s, target] { return s->retired >= target; });
return RAD_OK;
}
/* RAD_EVENT_LOCAL means nothing in one memory; RAD_EVENT_HOST_WAIT is kept, so a host sync on an
* event made without it is refused here as it is on a card. */
/* RAD_EVENT_LOCAL is meaningless here; RAD_EVENT_HOST_WAIT is kept so event_sync refuses events
* created without it, as on a card. */
int h_event_create(RadEvent* out, unsigned flags) {
if (!out) return RAD_E_INVAL;
auto* e = new (std::nothrow) HostEvent();
@@ -505,8 +460,7 @@ int h_event_create(RadEvent* out, unsigned flags) {
return RAD_OK;
}
/* Drops the handle. A record or wait still queued keeps the event alive until the worker is past
* it -- see HostEvent. */
/* Drops the handle; queued tasks keep the event alive (see HostEvent). */
void h_event_destroy(RadEvent ev) { if (ev) event_release((HostEvent*)ev); }
int h_event_record(RadEvent ev, RadStream st) {
@@ -539,9 +493,8 @@ int h_event_wait(RadStream st, RadEvent ev) {
std::lock_guard<std::mutex> lk(e->m);
target = e->recorded;
}
/* Waiting on an event that was never recorded is a no-op, matching hipStreamWaitEvent. The
* mover relies on it: a weight with no transfer in flight has an event nobody recorded, and
* making that case an error would put a branch on the issue path for nothing. */
/* Waiting on a never-recorded event is a no-op, matching hipStreamWaitEvent; the mover relies
* on it. */
if (target == 0) return RAD_OK;
Task t;
t.kind = Task::Wait;
@@ -576,29 +529,23 @@ int h_event_sync(RadEvent ev) {
int h_event_elapsed_ms(RadEvent a, RadEvent b, float* out) {
if (!a || !b || !out) return RAD_E_INVAL;
auto* ea = (HostEvent*)a;
auto* eb = (HostEvent*)b;
/* An event's stamp, if it was recorded and has completed. */
auto stamp = [](RadEvent ev, Clock::time_point* t) {
auto* e = (HostEvent*)ev;
std::lock_guard<std::mutex> lk(e->m);
if (e->recorded == 0 || e->completed < e->recorded) return false;
*t = e->stamp;
return true;
};
Clock::time_point ta, tb;
{
std::lock_guard<std::mutex> lk(ea->m);
if (ea->recorded == 0 || ea->completed < ea->recorded) return RAD_E_STATE;
ta = ea->stamp;
}
{
std::lock_guard<std::mutex> lk(eb->m);
if (eb->recorded == 0 || eb->completed < eb->recorded) return RAD_E_STATE;
tb = eb->stamp;
}
if (!stamp(a, &ta) || !stamp(b, &tb)) return RAD_E_STATE;
*out = std::chrono::duration<float, std::milli>(tb - ta).count();
return RAD_OK;
}
/* A null stream is refused on both backends, and that is a decision rather than an oversight.
* HIP's stream 0 carries legacy implicit-synchronisation semantics: work on it serialises against
* every other blocking stream in the process. That is the exact opposite of spec §5.4's
* requirement that a transfer involve no host synchronisation and not serialise the step, so the
* engine never wants it, and letting it through here would let a caller pick it up by accident and
* only find out on a real device. */
/* A null stream is refused on both backends. HIP's stream 0 implicitly synchronises with every
* blocking stream, which spec §5.4 forbids for transfers; accepting it here would hide such a
* caller until it ran on a card. */
int check_stream(RadStream s, const char* who) {
if (s) return RAD_OK;
device_set_error("%s: null stream -- radiance does not use the default stream, "
@@ -647,12 +594,20 @@ int h_memcpy_2d_async(void* dst, int64_t dpitch, const void* src, int64_t spitch
int h_memcpy_ranges_async(void* dst, const void* src, int64_t prefix, const RadCopyRange* ranges,
int n, RadStream st) {
RAD_TRY(check_stream(st, "rad_memcpy_ranges_async"));
if (!dst || !src || prefix < 0 || n < 0 || (n > 0 && !ranges)) {
device_set_error("rad_memcpy_ranges_async(%p <- %p, prefix %lld, %d ranges): invalid "
"argument", dst, src, (long long)prefix, n);
/* The card's copy kernel moves 16-byte pieces (aql.cpp, a_memcpy_ranges_async), so the same
* calls are refused here: a caller passing the host suite must run on a card. Whether the
* memory is pinned cannot be told on this backend. */
if (!dst || !src || prefix < 0 || (prefix & 15) || n < 0 || (n > 0 && !ranges)) {
device_set_error("rad_memcpy_ranges_async(%p <- %p, prefix %lld (a multiple of 16), %d "
"ranges): invalid argument", dst, src, (long long)prefix, n);
return RAD_E_INVAL;
}
if (prefix == 0 && n == 0) return RAD_OK;
if (((uintptr_t)dst | (uintptr_t)src) & 15) {
device_set_error("rad_memcpy_ranges_async(%p <- %p): both bases must be 16-byte aligned",
dst, src);
return RAD_E_UNSUPPORTED;
}
Task t;
t.kind = Task::Ranges;
t.dst = dst;
@@ -663,8 +618,7 @@ int h_memcpy_ranges_async(void* dst, const void* src, int64_t prefix, const RadC
return stream_push((HostStream*)st, t);
}
/* A copy a segment, queued in list order: this stream has no dispatch to save, and a task holds
* no list, so the list is read here, at the call, as the device backend reads it. */
/* One copy task per segment, in list order. The list is read at the call, as on the device. */
int h_memcpy_list_async(const RadCopySeg* segs, int n, unsigned, RadStream st) {
RAD_TRY(check_stream(st, "rad_memcpy_list_async"));
if (n < 0 || (n > 0 && !segs)) {
@@ -690,17 +644,81 @@ int h_memset_async(void* dst, int value, int64_t bytes, RadStream st) {
return stream_push((HostStream*)st, t);
}
/* ------------------------------------------------------------------ gates */
/* A gate is a wait task on an event whose one record only the host completes: recorded is 1 from
* the start and rad_gate_open sets completed. The task holds a reference, so the event outlives
* the handle until the worker has passed it. */
struct HostGate {
HostEvent* e = nullptr;
HostStream* s = nullptr;
};
int h_stream_gate(RadStream st, void** out) {
RAD_TRY(check_stream(st, "rad_stream_gate"));
if (!out) return RAD_E_INVAL;
auto* s = (HostStream*)st;
auto* e = new (std::nothrow) HostEvent();
auto* g = new (std::nothrow) HostGate();
if (!e || !g) {
delete e;
delete g;
device_set_error("rad_stream_gate: out of memory");
return RAD_E_NOMEM;
}
e->recorded = 1;
Task t;
t.kind = Task::Wait;
t.ev = e;
t.seq = 1;
event_retain(e);
const int rc = stream_push(s, t);
if (rc < 0) {
event_release(e);
event_release(e);
delete g;
return rc;
}
{
std::lock_guard<std::mutex> lk(s->m);
++s->gates;
}
g->e = e;
g->s = s;
*out = g;
return RAD_OK;
}
int h_gate_open(void* p) {
auto* g = (HostGate*)p;
if (!g || !g->e) return RAD_E_INVAL;
{
std::lock_guard<std::mutex> lk(g->e->m);
g->e->completed = 1;
}
g->e->cv.notify_all();
{
std::lock_guard<std::mutex> lk(g->s->m);
--g->s->gates;
}
event_release(g->e);
delete g;
return RAD_OK;
}
int64_t h_gate_room(RadStream st) {
if (!st) return 0;
auto* s = (HostStream*)st;
std::lock_guard<std::mutex> lk(s->m);
return (int64_t)(s->ring.size() - s->count);
}
/* ------------------------------------------------------------------ elastic memory */
/* mmap is the host backend's answer to the card's virtual memory manager, and it is the same
* mechanism rather than a simulation of one: PROT_NONE takes address space and no pages, MAP_FIXED
* over it backs a granule, and PROT_NONE over that hands the pages back to the kernel. What a test
* proves here -- that a decommitted range comes back zeroed, that the addresses never move, that
* committing over a commit is the caller's bug -- is true of the HIP path for the same reasons.
/* Elastic memory via mmap, the same mechanism as the card's VMM: PROT_NONE reserves address space
* without pages, MAP_FIXED read/write backs a granule, and PROT_NONE over it returns the pages.
* Decommitted ranges come back zeroed and addresses never move, as on the HIP path.
*
* THE GRANULE IS THE POOL ALIGNMENT AND NOT THE PAGE SIZE. A host page is 4 KiB and a card's
* allocation granularity is 2 MiB, so rounding to the page here would let a pool size that only
* works on this backend pass its tests and then strand up to 2 MiB per stripe on the card. Matching
* the coarser number is what makes the host suite able to hold the arithmetic down. */
* The granule is the pool alignment (the card's 2 MiB), not the 4 KiB page, so pool sizing that
* passes here does not strand memory on a card. */
constexpr int64_t kVmemGranule = RAD_ALIGN_POOL;
int64_t h_vmem_granularity(void) { return kVmemGranule; }
@@ -708,10 +726,8 @@ int64_t h_vmem_granularity(void) { return kVmemGranule; }
void* h_vmem_reserve(int64_t bytes, int64_t align) {
if (bytes <= 0) return nullptr;
if (align < kVmemGranule) align = kVmemGranule;
/* Over-reserve by one alignment, then give back the head and the tail, so the range that
* remains is exactly [base, base+bytes) and release() is a single munmap of what it was
* handed. The alternative -- remembering the raw mapping in a side table -- is a table whose
* only purpose is to survive until teardown. */
/* Over-reserve by one alignment and unmap the head and tail, so the range is exactly
* [base, base+bytes) and release is one munmap with no side table. */
const size_t raw_len = (size_t)(bytes + align);
void* raw = ::mmap(nullptr, raw_len, PROT_NONE,
MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
@@ -745,9 +761,8 @@ int h_vmem_commit(void* addr, int64_t bytes) {
int h_vmem_decommit(void* addr, int64_t bytes) {
if (!addr || bytes <= 0) return RAD_E_INVAL;
/* MAP_FIXED over the same range rather than munmap: munmap would leave a HOLE in the
* reservation that an unrelated mmap could be handed, and the whole promise of this primitive
* is that the address range stays the caller's until it releases it. */
/* 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,
MAP_FIXED | MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
if (p != addr) {
@@ -758,11 +773,8 @@ int h_vmem_decommit(void* addr, int64_t bytes) {
return RAD_OK;
}
/* The host backend's commit already maps readable and writable, so this has nothing to grant. It
* is implemented rather than left null because the run VMem computes for it is the same run the
* card is handed, and a path that only ever runs on the machine with the card is a path whose
* arithmetic the host suite cannot hold down. mprotect over an anonymous mapping that already has
* these bits is a permission check and a no-op. */
/* Commit already maps read/write, so this is a no-op mprotect. It is implemented anyway so the
* host suite exercises the ranges VMem computes for the card. */
int h_vmem_protect(void* addr, int64_t bytes) {
if (!addr || bytes <= 0) return RAD_E_INVAL;
if (::mprotect(addr, (size_t)bytes, PROT_READ | PROT_WRITE) != 0) {
@@ -773,7 +785,7 @@ int h_vmem_protect(void* addr, int64_t bytes) {
}
int h_vram_used(int device, int64_t* out) {
if (!out || device < 0 || device >= kMaxFakeDevices) return RAD_E_INVAL;
if (!out || device < 0 || device >= host_count()) return RAD_E_INVAL;
*out = g_used[device].load(std::memory_order_relaxed);
return RAD_OK;
}
@@ -789,15 +801,21 @@ const DeviceBackend g_host = {
h_memcpy_async, h_memcpy_2d_async, h_memset_async, h_memcpy_ranges_async,
h_memcpy_list_async,
nullptr, nullptr, /* no DMA engine, so no link to hold */
/* No recorded passes: a host stream runs its work as it is issued, so there is no queue to
* write a recording into, and every pass is issued. */
/* No recorded passes: host streams run work as issued. */
nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr,
/* Elastic memory, which the host backend DOES have: see above. */
/* Elastic memory: see above. */
h_vmem_granularity, h_vmem_reserve, h_vmem_release, h_vmem_commit, h_vmem_decommit,
h_vmem_protect,
h_vram_used,
nullptr, nullptr, /* no device code to register */
nullptr, nullptr, /* not integrated graphics; one address space */
nullptr, nullptr, nullptr, /* no PCI address, runtime or DMA engine */
/* No expert prefetch. */
nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr,
h_stream_gate, h_gate_open, h_gate_room,
};
} /* namespace */