radiance 1.0.0

This commit is contained in:
Deadcode committed 2026-10-04 12:02:41 +02:00
commit ae74a8aebf
616 files changed
+338692

No files matched your search

+2207
View File
File diff suppressed because it is too large. Load diff
+90
View File
@@ -0,0 +1,90 @@
/* aql.h -- what the AQL backend's translation units share.
*
* 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.
*/
#pragma once
#include <cstddef>
#include <cstdint>
#include <string>
#include <vector>
namespace rad {
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`. */
enum class Hidden : uint8_t {
None, /* an explicit parameter */
Pad, /* hidden_none: bytes the compiler reserved and reads nothing from */
BlockCountX, BlockCountY, BlockCountZ,
GroupSizeX, GroupSizeY, GroupSizeZ,
RemainderX, RemainderY, RemainderZ,
GlobalOffsetX, GlobalOffsetY, GlobalOffsetZ,
GridDims,
DynamicLds,
Unsupported, /* anything else: a kernel that wants it is refused by name */
};
struct KernelArg {
uint32_t offset = 0;
uint32_t size = 0;
Hidden hidden = Hidden::None;
std::string kind; /* the metadata's value_kind, for the refusal message */
};
struct KernelMeta {
std::string symbol; /* "<name>.kd" */
uint32_t kernarg_size = 0;
uint32_t group_size = 0; /* static LDS */
uint32_t private_size = 0; /* static scratch */
bool dynamic_stack = false;
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. */
bool bundle_code_object(const void* bundle, const std::vector<std::string>& isas, const void** out,
size_t* out_size, std::string* why);
/* Every kernel described in an AMDGPU code object's metadata note. */
bool code_object_kernels(const void* elf, size_t size, std::vector<KernelMeta>* out,
std::string* why);
/* ------------------------------------------------------------------ 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. */
enum : uint8_t { kFenceAcquireSystem = 1, kFenceReleaseSystem = 2 };
void set_next_fence(uint8_t f);
} // namespace aql
} // namespace rad
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. */
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. */
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. */
int rad_aql_blit_ranges(void* dst, const void* src, uint64_t prefix, const RadCopyRange* ranges,
int n, void* stream);
}
+252
View File
@@ -0,0 +1,252 @@
/* aql_blit.hip -- the copy and fill kernels the AQL backend dispatches for rad_memcpy_async,
* rad_memcpy_2d_async and rad_memset_async.
*
* 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.
*
* 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.
*/
#include <hip/hip_runtime.h>
#include <cstdint>
#include "aql.h"
#include "device.h"
namespace {
constexpr int kThreads = 256;
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. */
__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;
uint64_t i = (uint64_t)blockIdx.x * kThreads + threadIdx.x;
for (; i + 3 * stride < n; i += 4 * stride) {
const u32x4 a = src[i], b = src[i + stride], c = src[i + 2 * stride], d = src[i + 3 * stride];
dst[i] = a; dst[i + stride] = b; dst[i + 2 * stride] = c; dst[i + 3 * stride] = d;
}
for (; i < n; i += stride) dst[i] = src[i];
}
/* A COPY THAT READS OR WRITES ACROSS THE LINK 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:
*
* 16 x 256 threads, 4 loads in flight 28.9 GB/s
* 1 x 256 threads, 16 in flight 28.9
* 1 x 128 threads, 16 in flight 28.9 <- this
* 1 x 64 threads, 16 in flight 16.8
* 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.
*
* 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. */
constexpr int kLinkThreads = 128, kLinkDepth = 16;
constexpr uint64_t kLinkByteBlocks = 16;
__global__ __launch_bounds__(kLinkThreads) void aql_copy_link(const u32x4* __restrict__ src,
u32x4* __restrict__ dst, uint64_t n) {
uint64_t i = threadIdx.x;
for (; i + (uint64_t)(kLinkDepth - 1) * kLinkThreads < n; i += (uint64_t)kLinkDepth * kLinkThreads) {
u32x4 v[kLinkDepth];
#pragma unroll
for (int k = 0; k < kLinkDepth; ++k) v[k] = src[i + (uint64_t)k * kLinkThreads];
#pragma unroll
for (int k = 0; k < kLinkDepth; ++k) dst[i + (uint64_t)k * kLinkThreads] = v[k];
}
if (i >= n) return;
u32x4 v[kLinkDepth];
#pragma unroll
for (int k = 0; k < kLinkDepth; ++k) {
const uint64_t j = i + (uint64_t)k * kLinkThreads;
v[k] = src[j < n ? j : n - 1];
}
#pragma unroll
for (int k = 0; k < kLinkDepth; ++k) {
const uint64_t j = i + (uint64_t)k * kLinkThreads;
if (j < n) dst[j] = v[k];
}
}
__global__ __launch_bounds__(kThreads) void aql_copy1(const unsigned char* __restrict__ src,
unsigned char* __restrict__ dst, uint64_t n) {
const uint64_t stride = (uint64_t)gridDim.x * kThreads;
for (uint64_t i = (uint64_t)blockIdx.x * kThreads + threadIdx.x; i < n; i += stride)
dst[i] = src[i];
}
__global__ __launch_bounds__(kThreads) void aql_copy2d16(const u32x4* __restrict__ src,
u32x4* __restrict__ dst, uint64_t spitch16,
uint64_t dpitch16, uint64_t w16,
uint64_t height) {
const uint64_t cstride = (uint64_t)gridDim.x * kThreads;
for (uint64_t r = blockIdx.y; r < height; r += gridDim.y) {
const u32x4* s = src + r * spitch16;
u32x4* d = dst + r * dpitch16;
for (uint64_t c = (uint64_t)blockIdx.x * kThreads + threadIdx.x; c < w16; c += cstride)
d[c] = s[c];
}
}
__global__ __launch_bounds__(kThreads) void aql_copy2d1(const unsigned char* __restrict__ src,
unsigned char* __restrict__ dst,
uint64_t spitch, uint64_t dpitch,
uint64_t width, uint64_t height) {
const uint64_t cstride = (uint64_t)gridDim.x * kThreads;
for (uint64_t r = blockIdx.y; r < height; r += gridDim.y) {
const unsigned char* s = src + r * spitch;
unsigned char* d = dst + r * dpitch;
for (uint64_t c = (uint64_t)blockIdx.x * kThreads + threadIdx.x; c < width; c += cstride)
d[c] = s[c];
}
}
/* 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. */
constexpr int kRangeWords = 16;
__global__ __launch_bounds__(kThreads) void aql_copy_ranges(const u32x4* __restrict__ src16,
u32x4* __restrict__ dst16, uint64_t n16,
unsigned prefix_blocks,
const RadCopyRange* __restrict__ r) {
if (blockIdx.x < prefix_blocks) {
const uint64_t stride = (uint64_t)prefix_blocks * kThreads;
uint64_t i = (uint64_t)blockIdx.x * kThreads + threadIdx.x;
for (; i + 3 * stride < n16; i += 4 * stride) {
const u32x4 a = src16[i], b = src16[i + stride], c = src16[i + 2 * stride],
d = src16[i + 3 * stride];
dst16[i] = a; dst16[i + stride] = b; dst16[i + 2 * stride] = c; dst16[i + 3 * stride] = d;
}
for (; i < n16; i += stride) dst16[i] = src16[i];
return;
}
const RadCopyRange g = r[blockIdx.x - prefix_blocks];
const unsigned* s4 = (const unsigned*)((const char*)src16 + g.src);
unsigned* d4 = (unsigned*)((char*)dst16 + g.dst);
const int64_t n = g.bytes / 4;
for (int64_t base = 0; base < n; base += (int64_t)kThreads * kRangeWords) {
unsigned v[kRangeWords];
#pragma unroll
for (int k = 0; k < kRangeWords; ++k) {
const int64_t w = base + (int64_t)k * kThreads + threadIdx.x;
v[k] = s4[w < n ? w : n - 1];
}
#pragma unroll
for (int k = 0; k < kRangeWords; ++k) {
const int64_t w = base + (int64_t)k * kThreads + threadIdx.x;
if (w < n) d4[w] = v[k];
}
}
}
__global__ __launch_bounds__(kThreads) void aql_fill16(u32x4* __restrict__ dst, unsigned v,
uint64_t n) {
const uint64_t stride = (uint64_t)gridDim.x * kThreads;
const u32x4 w = { v, v, v, v };
for (uint64_t i = (uint64_t)blockIdx.x * kThreads + threadIdx.x; i < n; i += stride) dst[i] = w;
}
__global__ __launch_bounds__(kThreads) void aql_fill1(unsigned char* __restrict__ dst,
unsigned char v, uint64_t n) {
const uint64_t stride = (uint64_t)gridDim.x * kThreads;
for (uint64_t i = (uint64_t)blockIdx.x * kThreads + threadIdx.x; i < n; i += stride) dst[i] = v;
}
inline unsigned blocks_for(uint64_t n, uint64_t per_block, uint64_t cap = kMaxBlocks) {
uint64_t b = (n + per_block - 1) / per_block;
if (b < 1) b = 1;
if (b > cap) b = cap;
return (unsigned)b;
}
inline bool aligned16(uint64_t v) { return (v & 15u) == 0; }
inline int launched() { return hipGetLastError() == hipSuccess ? 0 : -1; }
} // namespace
extern "C" int rad_aql_blit_copy(void* dst, const void* src, uint64_t bytes, void* stream,
bool link) {
if (bytes == 0) return 0;
const hipStream_t s = (hipStream_t)stream;
if (aligned16((uint64_t)(uintptr_t)dst | (uint64_t)(uintptr_t)src | bytes)) {
const uint64_t n = bytes / 16;
if (link)
hipLaunchKernelGGL(aql_copy_link, dim3(1), dim3(kLinkThreads), 0, s,
(const u32x4*)src, (u32x4*)dst, n);
else
hipLaunchKernelGGL(aql_copy16, dim3(blocks_for(n, 4 * kThreads)), dim3(kThreads), 0,
s, (const u32x4*)src, (u32x4*)dst, n);
} 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. */
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);
}
return launched();
}
extern "C" int rad_aql_blit_copy2d(void* dst, uint64_t dpitch, const void* src, uint64_t spitch,
uint64_t width, uint64_t height, void* stream) {
if (width == 0 || height == 0) return 0;
const hipStream_t s = (hipStream_t)stream;
const unsigned by = (unsigned)(height < 65535 ? height : 65535);
if (aligned16((uint64_t)(uintptr_t)dst | (uint64_t)(uintptr_t)src | dpitch | spitch | width)) {
const uint64_t w16 = width / 16;
hipLaunchKernelGGL(aql_copy2d16, dim3(blocks_for(w16, kThreads), by), dim3(kThreads), 0, s,
(const u32x4*)src, (u32x4*)dst, spitch / 16, dpitch / 16, w16, height);
} else {
hipLaunchKernelGGL(aql_copy2d1, dim3(blocks_for(width, kThreads), by), dim3(kThreads), 0, s,
(const unsigned char*)src, (unsigned char*)dst, spitch, dpitch, width,
height);
}
return launched();
}
extern "C" int rad_aql_blit_ranges(void* dst, const void* src, uint64_t prefix,
const RadCopyRange* ranges, int n, void* stream) {
const uint64_t n16 = prefix / 16;
const unsigned pb = n16 ? blocks_for(n16, 4 * kThreads) : 0;
if (pb == 0 && n == 0) return 0;
hipLaunchKernelGGL(aql_copy_ranges, dim3(pb + (unsigned)n), dim3(kThreads), 0,
(hipStream_t)stream, (const u32x4*)src, (u32x4*)dst, n16, pb, ranges);
return launched();
}
extern "C" int rad_aql_blit_fill(void* dst, int value, uint64_t bytes, void* stream) {
if (bytes == 0) return 0;
const hipStream_t s = (hipStream_t)stream;
const unsigned char b = (unsigned char)value;
if (aligned16((uint64_t)(uintptr_t)dst | bytes)) {
const unsigned v = 0x01010101u * b;
const uint64_t n = bytes / 16;
hipLaunchKernelGGL(aql_fill16, dim3(blocks_for(n, 4 * kThreads)), dim3(kThreads), 0, s,
(u32x4*)dst, v, n);
} else {
hipLaunchKernelGGL(aql_fill1, dim3(blocks_for(bytes, 4 * kThreads)), dim3(kThreads), 0, s,
(unsigned char*)dst, b, bytes);
}
return launched();
}
+324
View File
@@ -0,0 +1,324 @@
/* 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.
*
* 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.
*
* Nothing here touches a device, so it builds and is tested without one.
*/
#include "aql.h"
#include <cstring>
namespace rad {
namespace aql {
/* ------------------------------------------------------------------ the offload bundle */
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. */
struct TargetId {
std::string proc;
std::vector<std::pair<std::string, char>> feat;
};
TargetId parse_target_id(const std::string& s) {
TargetId t;
size_t i = s.find(':');
t.proc = s.substr(0, i);
while (i != std::string::npos) {
const size_t j = s.find(':', i + 1);
const std::string f = s.substr(i + 1, j == std::string::npos ? std::string::npos : j - i - 1);
if (f.size() > 1 && (f.back() == '+' || f.back() == '-'))
t.feat.emplace_back(f.substr(0, f.size() - 1), f.back());
i = j;
}
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. */
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. */
int target_fit(const TargetId& co, const TargetId& card) {
if (co.proc != card.proc) return -1;
for (const auto& f : co.feat) {
bool ok = false;
for (const auto& g : card.feat)
if (g.first == f.first) { ok = g.second == f.second; break; }
if (!ok) return -1;
}
return (int)co.feat.size();
}
} // namespace
bool bundle_code_object(const void* bundle, const std::vector<std::string>& isas, const void** out,
size_t* out_size, std::string* why) {
static const char kMagic[] = "__CLANG_OFFLOAD_BUNDLE__";
const unsigned char* b = static_cast<const unsigned char*>(bundle);
*out = nullptr;
*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 "
"--offload-compress";
return false;
}
if (std::memcmp(b, kMagic, sizeof kMagic - 1) != 0) {
*why = "the fat binary does not start with a clang offload bundle header";
return false;
}
uint64_t n = 0;
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. */
struct Entry { uint64_t off, size; TargetId id; std::string text; };
std::vector<Entry> ents;
const unsigned char* p = b + 32;
for (uint64_t i = 0; i < n; ++i) {
uint64_t off = 0, size = 0, tl = 0;
std::memcpy(&off, p, 8);
std::memcpy(&size, p + 8, 8);
std::memcpy(&tl, p + 16, 8);
if (tl > 4096) { *why = "offload bundle entry with an implausible triple"; return false; }
const std::string triple(reinterpret_cast<const char*>(p + 24), (size_t)tl);
p += 24 + tl;
const std::string id = target_id_of(triple);
if (size == 0 || id.empty()) continue;
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. */
for (const std::string& isa : isas) {
const TargetId card = parse_target_id(target_id_of(isa).empty() ? isa : target_id_of(isa));
const Entry* best = nullptr;
int best_fit = -1;
for (const Entry& e : ents) {
const int f = target_fit(e.id, card);
if (f > best_fit) { best_fit = f; best = &e; }
}
if (best) {
*out = b + best->off;
*out_size = (size_t)best->size;
return true;
}
}
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));
*why = "the fat binary has code objects for [" + (have.empty() ? std::string("none") : have) +
"] and this card runs [" + want + "]";
return false;
}
/* ------------------------------------------------------------------ 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. */
namespace {
struct MP {
enum T : uint8_t { Nil, Bool, Int, Str, Arr, Map, Other } t = Nil;
int64_t i = 0;
const char* s = nullptr;
uint32_t n = 0;
std::vector<MP> a; /* array items, or map keys and values interleaved */
const MP* get(const char* key) const {
if (t != Map) return nullptr;
const size_t kl = std::strlen(key);
for (size_t k = 0; k + 1 < a.size(); k += 2)
if (a[k].t == Str && a[k].n == kl && std::memcmp(a[k].s, key, kl) == 0) return &a[k + 1];
return nullptr;
}
std::string str() const { return t == Str ? std::string(s, n) : std::string(); }
};
struct Reader {
const unsigned char* p;
const unsigned char* e;
bool ok = true;
uint64_t be(int nb) {
if (e - p < nb) { ok = false; return 0; }
uint64_t v = 0;
for (int k = 0; k < nb; ++k) v = (v << 8) | p[k];
p += nb;
return v;
}
void str(MP* m, uint32_t n) {
if ((uint64_t)(e - p) < n) { ok = false; return; }
m->t = MP::Str; m->s = reinterpret_cast<const char*>(p); m->n = n; p += n;
}
void items(MP* m, uint32_t n, int depth) {
m->a.resize(n);
for (uint32_t k = 0; k < n && ok; ++k) read(&m->a[k], depth + 1);
}
void read(MP* m, int depth) {
if (!ok || p >= e || depth > 64) { ok = false; return; }
const unsigned char c = *p++;
if (c <= 0x7f) { m->t = MP::Int; m->i = c; return; }
if (c >= 0xe0) { m->t = MP::Int; m->i = (int8_t)c; return; }
if ((c & 0xf0) == 0x80) { m->t = MP::Map; items(m, 2u * (c & 0x0f), depth); return; }
if ((c & 0xf0) == 0x90) { m->t = MP::Arr; items(m, c & 0x0f, depth); return; }
if ((c & 0xe0) == 0xa0) { str(m, c & 0x1f); return; }
switch (c) {
case 0xc0: m->t = MP::Nil; return;
case 0xc2: m->t = MP::Bool; m->i = 0; return;
case 0xc3: m->t = MP::Bool; m->i = 1; return;
case 0xcc: m->t = MP::Int; m->i = (int64_t)be(1); return;
case 0xcd: m->t = MP::Int; m->i = (int64_t)be(2); return;
case 0xce: m->t = MP::Int; m->i = (int64_t)be(4); return;
case 0xcf: m->t = MP::Int; m->i = (int64_t)be(8); return;
case 0xd0: m->t = MP::Int; m->i = (int8_t)be(1); return;
case 0xd1: m->t = MP::Int; m->i = (int16_t)be(2); return;
case 0xd2: m->t = MP::Int; m->i = (int32_t)be(4); return;
case 0xd3: m->t = MP::Int; m->i = (int64_t)be(8); return;
case 0xca: m->t = MP::Other; be(4); return;
case 0xcb: m->t = MP::Other; be(8); return;
case 0xd9: str(m, (uint32_t)be(1)); return;
case 0xda: str(m, (uint32_t)be(2)); return;
case 0xdb: str(m, (uint32_t)be(4)); return;
case 0xc4: case 0xc5: case 0xc6: {
const uint32_t n = (uint32_t)be(c == 0xc4 ? 1 : c == 0xc5 ? 2 : 4);
str(m, n); m->t = MP::Other; return;
}
case 0xdc: m->t = MP::Arr; items(m, (uint32_t)be(2), depth); return;
case 0xdd: m->t = MP::Arr; items(m, (uint32_t)be(4), depth); return;
case 0xde: m->t = MP::Map; items(m, 2u * (uint32_t)be(2), depth); return;
case 0xdf: m->t = MP::Map; items(m, 2u * (uint32_t)be(4), depth); return;
default: ok = false; return; /* ext types: never in code object metadata */
}
}
};
Hidden hidden_kind(const std::string& k) {
if (k.compare(0, 7, "hidden_") != 0) return Hidden::None;
static const struct { const char* n; Hidden h; } kTab[] = {
{ "hidden_none", Hidden::Pad },
{ "hidden_block_count_x", Hidden::BlockCountX },
{ "hidden_block_count_y", Hidden::BlockCountY },
{ "hidden_block_count_z", Hidden::BlockCountZ },
{ "hidden_group_size_x", Hidden::GroupSizeX },
{ "hidden_group_size_y", Hidden::GroupSizeY },
{ "hidden_group_size_z", Hidden::GroupSizeZ },
{ "hidden_remainder_x", Hidden::RemainderX },
{ "hidden_remainder_y", Hidden::RemainderY },
{ "hidden_remainder_z", Hidden::RemainderZ },
{ "hidden_global_offset_x", Hidden::GlobalOffsetX },
{ "hidden_global_offset_y", Hidden::GlobalOffsetY },
{ "hidden_global_offset_z", Hidden::GlobalOffsetZ },
{ "hidden_grid_dims", Hidden::GridDims },
{ "hidden_dynamic_lds_size", Hidden::DynamicLds },
};
for (const auto& t : kTab) if (k == t.n) return t.h;
return Hidden::Unsupported;
}
} // namespace
/* ------------------------------------------------------------------ the metadata note */
bool code_object_kernels(const void* elf, size_t size, std::vector<KernelMeta>* out,
std::string* why) {
out->clear();
const unsigned char* b = static_cast<const unsigned char*>(elf);
if (size < 64 || std::memcmp(b, "\x7f" "ELF", 4) != 0 || b[4] != 2 /* ELFCLASS64 */) {
*why = "not a 64-bit ELF code object";
return false;
}
uint64_t phoff = 0;
uint16_t phentsize = 0, phnum = 0;
std::memcpy(&phoff, b + 32, 8);
std::memcpy(&phentsize, b + 54, 2);
std::memcpy(&phnum, b + 56, 2);
if (phentsize < 56 || phoff + (uint64_t)phentsize * phnum > size) {
*why = "code object program headers run past its end";
return false;
}
for (uint16_t h = 0; h < phnum; ++h) {
const unsigned char* ph = b + phoff + (uint64_t)h * phentsize;
uint32_t type = 0;
uint64_t off = 0, fsz = 0;
std::memcpy(&type, ph, 4);
std::memcpy(&off, ph + 8, 8);
std::memcpy(&fsz, ph + 32, 8);
if (type != 4 /* PT_NOTE */ || off + fsz > size) continue;
const unsigned char* q = b + off;
const unsigned char* qe = q + fsz;
while (qe - q >= 12) {
uint32_t namesz = 0, descsz = 0, ntype = 0;
std::memcpy(&namesz, q, 4);
std::memcpy(&descsz, q + 4, 4);
std::memcpy(&ntype, q + 8, 4);
const unsigned char* name = q + 12;
const unsigned char* desc = name + ((namesz + 3u) & ~3u);
const unsigned char* next = desc + ((descsz + 3u) & ~3u);
if (next > qe) break;
q = next;
if (ntype != 32 /* NT_AMDGPU_METADATA */ || namesz != 7 ||
std::memcmp(name, "AMDGPU", 6) != 0)
continue;
Reader r{ desc, desc + descsz };
MP root;
r.read(&root, 0);
if (!r.ok || root.t != MP::Map) { *why = "malformed AMDGPU metadata"; return false; }
const MP* ks = root.get("amdhsa.kernels");
if (!ks || ks->t != MP::Arr) { *why = "metadata has no amdhsa.kernels"; return false; }
for (const MP& k : ks->a) {
KernelMeta m;
const MP* sym = k.get(".symbol");
if (!sym) continue;
m.symbol = sym->str();
if (const MP* v = k.get(".kernarg_segment_size")) m.kernarg_size = (uint32_t)v->i;
if (const MP* v = k.get(".group_segment_fixed_size")) m.group_size = (uint32_t)v->i;
if (const MP* v = k.get(".private_segment_fixed_size")) m.private_size = (uint32_t)v->i;
if (const MP* v = k.get(".uses_dynamic_stack")) m.dynamic_stack = v->i != 0;
if (const MP* as = k.get(".args"); as && as->t == MP::Arr) {
for (const MP& a : as->a) {
KernelArg ka;
if (const MP* v = a.get(".offset")) ka.offset = (uint32_t)v->i;
if (const MP* v = a.get(".size")) ka.size = (uint32_t)v->i;
if (const MP* v = a.get(".value_kind")) ka.kind = v->str();
ka.hidden = hidden_kind(ka.kind);
m.args.push_back(std::move(ka));
}
}
out->push_back(std::move(m));
}
return true;
}
}
*why = "code object has no AMDGPU metadata note";
return false;
}
} // namespace aql
} // namespace rad
+379
View File
@@ -0,0 +1,379 @@
/* device.h -- the device layer's internal face.
*
* `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.
*
* 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.
*/
#pragma once
#include "rad_abi.h"
#include "rad_device.h"
#include <cstdint>
#include <string>
#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. */
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. */
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. */
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. */
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. */
extern "C" int rad_memcpy_ranges_async(void* dst, const void* src, int64_t prefix,
const RadCopyRange* ranges, int n, 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. */
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:
*
* 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.
*
* 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.
*/
/* ------------------------------------------------------------------ the backend vtable */
/* One entry per call in rad_device.h. `name` is what device_backend_name() returns. */
struct DeviceBackend {
const char* name;
int (*count)(void);
int (*set)(int device);
int (*props)(int device, RadDeviceProps* out);
int (*enable_peer)(int self, int peer);
void* (*alloc)(int64_t bytes, int kind);
void (*free)(void* p, int kind);
void* (*host_ptr)(void* p);
void* (*device_ptr)(void* p);
int (*stream_create)(RadStream* out, int high_priority);
void (*stream_destroy)(RadStream s);
int (*stream_sync)(RadStream s);
/* `flags`: see rad_event_create_as. A backend with no scope to choose ignores RAD_EVENT_LOCAL. */
int (*event_create)(RadEvent* out, unsigned flags);
void (*event_destroy)(RadEvent e);
int (*event_record)(RadEvent e, RadStream s);
int (*event_wait)(RadStream s, RadEvent e);
int (*event_query)(RadEvent e);
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. */
void (*host_wrote)(void);
int (*memcpy_async)(void* dst, const void* src, int64_t bytes, RadStream s);
int (*memcpy_2d_async)(void* dst, int64_t dpitch, const void* src, int64_t spitch,
int64_t width, int64_t height, RadStream s);
int (*memset_async)(void* dst, int value, int64_t bytes, RadStream s);
int (*memcpy_ranges_async)(void* dst, const void* src, int64_t prefix,
const RadCopyRange* ranges, int n, 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.
*
* `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. */
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`. */
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. */
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.
*
* 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.
*
* 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.
*
* 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.
*
* `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. */
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);
int (*vmem_commit)(void* addr, int64_t bytes);
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. */
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. */
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. */
int (*integrated)(int device);
};
const DeviceBackend* host_backend(void);
/* The current backend's recorded passes; RAD_E_UNSUPPORTED (or null) from one that has none. */
bool tape_supported();
int tape_begin();
int tape_mark();
void tape_pause(bool on);
RadTape tape_end(bool keep);
int tape_len(RadTape t);
int tape_play(RadTape t, int from, int to);
int tape_diff(RadTape a, RadTape b, std::string* why);
void tape_destroy(RadTape t);
int tape_record(RadTape t, int i, int* kind, uint32_t* queue);
int tape_set_overlap(RadTape t, int i, bool on);
/* 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). */
size_t dev_code_mark();
int dev_code_runs(size_t from, size_t to, int device, std::string* why);
/* The current backend's DeviceBackend::integrated. */
bool dev_integrated(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. */
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. */
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);
/* ------------------------------------------------------------------ elastic memory
* One reserved address range and the record of 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 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.
*
* 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. */
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. */
static bool supported();
static int64_t granularity(); /* 0 when unsupported */
VMem() = default;
~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. */
VMem(VMem&& o) noexcept
: base_(o.base_), size_(o.size_), committed_(o.committed_), ext_(std::move(o.ext_)) {
o.base_ = nullptr;
o.size_ = o.committed_ = 0;
o.ext_.clear();
}
VMem& operator=(VMem&& o) noexcept {
if (this != &o) {
release();
base_ = o.base_;
size_ = o.size_;
committed_ = o.committed_;
ext_ = std::move(o.ext_);
o.base_ = nullptr;
o.size_ = o.committed_ = 0;
o.ext_.clear();
}
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. */
int reserve(int64_t bytes, int64_t align = 0);
void release(); /* decommits whatever is still backed, then frees the VA */
void* base() const { return base_; }
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. */
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. */
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. */
std::vector<std::pair<int64_t, int64_t>> ext_;
/* Adds a newly mapped piece and merges it with whatever it touches. */
void add_extent(int64_t off, int64_t bytes);
void drop_extent(int64_t off, int64_t bytes);
};
/* 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. */
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. */
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. */
const DeviceBackend* aql_backend_if_present(void);
/* Bytes copied to or from pageable host memory so far: every such copy is a host wait. */
int64_t aql_pageable_bytes(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. */
void device_set_error(const char* fmt, ...) __attribute__((format(printf, 1, 2)));
} /* namespace rad */
+228
View File
@@ -0,0 +1,228 @@
/* directio.cpp -- see directio.h for why the page cache is not wanted here. */
#include "directio.h"
#include "../rad_internal.h"
#include <algorithm>
#include <cerrno>
#include <cstdlib>
#include <cstring>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
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. */
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. */
int64_t pread_some(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) break;
done += r;
}
return done;
}
int pwrite_exact(int fd, const void* src, int64_t bytes, int64_t off) {
int64_t done = 0;
while (done < bytes) {
ssize_t w = ::pwrite(fd, (const uint8_t*)src + done, (size_t)(bytes - done),
(off_t)(off + done));
if (w <= 0) {
if (w < 0 && errno == EINTR) continue;
return RAD_E_IO;
}
done += w;
}
return RAD_OK;
}
} /* namespace */
DirectFile::~DirectFile() { close(); }
int DirectFile::open(const char* path, int flags) {
if (!path || !*path) return RAD_E_INVAL;
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. */
int oflags = want_write ? O_RDWR : O_RDONLY;
if (flags & RAD_DIO_CREATE) oflags |= O_CREAT;
if (flags & RAD_DIO_TRUNC) oflags |= O_TRUNC;
fd_ = ::open(path, oflags | O_DIRECT, 0600);
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. */
if (flags & RAD_DIO_ALLOW_BUFFERED) {
fd_ = ::open(path, oflags, 0600);
direct_ = false;
if (fd_ >= 0)
RAD_WARN("directio: %s does not support O_DIRECT; opened buffered. Reads will go "
"through the page cache, which is a second copy of every byte and evicts "
"the weight pool's own pages.", path);
} else {
RAD_ERR("directio: cannot open %s with O_DIRECT: %s. The tier directory must be on a "
"filesystem that supports it.", path, std::strerror(errno));
return RAD_E_IO;
}
}
if (fd_ < 0) {
RAD_ERR("directio: cannot open %s: %s", path, std::strerror(errno));
return RAD_E_IO;
}
return RAD_OK;
}
void DirectFile::close() {
if (fd_ >= 0) ::close(fd_);
fd_ = -1;
direct_ = false;
std::free(bounce_);
bounce_ = nullptr;
bounce_bytes_ = 0;
}
int64_t DirectFile::size() const {
if (fd_ < 0) return -1;
struct stat st{};
if (::fstat(fd_, &st) != 0) return -1;
return (int64_t)st.st_size;
}
int DirectFile::bounce_ready() {
if (bounce_) return RAD_OK;
void* p = nullptr;
if (posix_memalign(&p, (size_t)alignment(), (size_t)kBounceBytes) != 0 || !p)
return RAD_E_NOMEM;
bounce_ = (uint8_t*)p;
bounce_bytes_ = kBounceBytes;
return RAD_OK;
}
/* ------------------------------------------------------------------ read */
int DirectFile::read_at(void* dst, int64_t off, int64_t bytes) {
if (fd_ < 0) return RAD_E_STATE;
if (!dst || off < 0 || bytes < 0) return RAD_E_INVAL;
if (bytes == 0) return RAD_OK;
const int64_t A = alignment();
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. */
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. */
RAD_TRY(bounce_ready());
const int64_t lo = align_down(off, A);
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);
const int64_t s = std::max(off, base);
const int64_t e = std::min(off + bytes, base + span);
if (e <= s) continue;
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). */
if (got < e - base) return RAD_E_IO;
std::memcpy((uint8_t*)dst + (s - off), bounce_ + (s - base), (size_t)(e - s));
}
return RAD_OK;
}
/* ------------------------------------------------------------------ write */
/* The store is written to as well as read: the SSD prefix-cache tier (core/mem/sstier.cpp)
* publishes blocks, and the SSD weight tier is populated once at load. Both write whole aligned
* slots, so this has the same shape as read_at -- one fast path, and a read-modify-write for
* anything that does not cover a whole block. */
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;
if (bytes == 0) return RAD_OK;
const int64_t A = alignment();
const bool aligned = (off % A) == 0 && (bytes % A) == 0 &&
((uintptr_t)src % (uintptr_t)A) == 0;
if (aligned) return pwrite_exact(fd_, src, bytes, off);
RAD_TRY(bounce_ready());
const int64_t old_size = size();
if (old_size < 0) return RAD_E_IO;
const int64_t lo = align_down(off, A);
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. */
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));
const int64_t s = std::max(off, base);
const int64_t e = std::min(off + bytes, base + span);
if (e > s)
std::memcpy(bounce_ + (s - base), (const uint8_t*)src + (s - off), (size_t)(e - s));
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. */
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;
}
} /* namespace rad */
+80
View File
@@ -0,0 +1,80 @@
/* directio.h -- the file tier's reader.
*
* 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.
*
* 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.
*/
#pragma once
#include <cstdint>
namespace rad {
enum {
RAD_DIO_READ = 1,
RAD_DIO_WRITE = 2, /* implies read: a partial block is a read-modify-write */
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 and the prefix cache are
* sized in gigabytes and read in megabyte runs; a silent buffered fallback turns both into a
* page-cache pump that is three times slower and looks like nothing at all in a profile. An
* operator who pointed --prefix-cache-dir at tmpfs wants to be told, not accommodated. The flag is
* for tests, which have to run on whatever /tmp happens to be. */
RAD_DIO_ALLOW_BUFFERED = 16,
};
class DirectFile {
public:
DirectFile() = default;
~DirectFile();
DirectFile(const DirectFile&) = delete;
DirectFile& operator=(const DirectFile&) = delete;
/* RAD_OK, or a negative RAD_E_*. `flags` is the RAD_DIO_* set above. */
int open(const char* path, int flags);
void close();
bool is_open() const { return fd_ >= 0; }
/* Whether the open actually got O_DIRECT. False only under RAD_DIO_ALLOW_BUFFERED. */
bool direct() const { return direct_; }
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. */
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. */
static constexpr int64_t alignment() { return 4096; }
private:
int bounce_ready();
int fd_ = -1;
bool direct_ = false;
uint8_t* bounce_ = nullptr;
int64_t bounce_bytes_ = 0;
};
} /* namespace rad */
+493
View File
@@ -0,0 +1,493 @@
/* 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 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.
*/
#include "device.h"
#include "../rad_internal.h"
#include <algorithm>
#include <cstdarg>
#include <cstdio>
#include <cstring>
#include <atomic>
#include <cstdlib>
#include <mutex>
#include <string>
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. */
static thread_local std::string t_last_error;
void device_set_error(const char* f, ...) {
char buf[1024];
va_list ap;
va_start(ap, 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. */
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). */
static std::string device_inventory(const DeviceBackend* b) {
std::string s;
const int n = b->count();
for (int i = 0; i < n; ++i) {
RadDeviceProps p{};
if (b->props(i, &p) < 0) continue;
s += fmt("%s%d:%s", i ? " " : "", i, p.arch);
}
return s;
}
static const DeviceBackend* select_backend() {
#if defined(RAD_HAVE_HIP) && RAD_HAVE_HIP
if (const DeviceBackend* b = aql_backend_if_present()) {
RAD_INFO("device: AQL backend, %d device(s) [%s]", b->count(),
device_inventory(b).c_str());
return b;
}
RAD_INFO("device: built with HIP but no device is visible -- using the host backend");
#endif
const DeviceBackend* b = host_backend();
RAD_INFO("device: host backend, %d device(s) [%s]", b->count(), device_inventory(b).c_str());
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. */
static const DeviceBackend* g_backend = nullptr;
static std::once_flag g_once;
static inline const DeviceBackend* dev() {
std::call_once(g_once, [] { g_backend = select_backend(); });
return g_backend;
}
bool device_is_host() { return std::strcmp(dev()->name, "host") == 0; }
const char* device_backend_name() { return dev()->name; }
} /* namespace rad */
/* ------------------------------------------------------------------ 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.
*
* 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.
*
* 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 every allocation of at least N bytes as it happens. That is the
* instrument; the counters are the summary. */
namespace rad {
namespace {
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 */
/* 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. */
std::atomic<int64_t> g_live_events{0};
int64_t trace_floor() {
static const int64_t v = [] {
const char* e = std::getenv("RADIANCE_TRACE_ALLOC");
if (!e || !*e) return (int64_t)-1;
const long long x = std::atoll(e);
return x >= 0 ? (int64_t)x : (int64_t)0;
}();
return v;
}
const char* kind_name(int kind) {
switch (kind) {
case RAD_MEM_DEVICE: return "device";
case RAD_MEM_HOST: return "host";
case RAD_MEM_HOST_PINNED: return "host-pinned";
case RAD_MEM_HOST_MAPPED: return "host-mapped";
default: return "?";
}
}
} /* 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 (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); }
/* ------------------------------------------------------------------ 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. */
namespace {
std::atomic<int64_t> g_vmem_committed{0};
} /* namespace */
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. */
bool VMem::supported() { return dev()->vmem_reserve != nullptr && VMem::granularity() > 0; }
int64_t VMem::granularity() {
if (!dev()->vmem_granularity) return 0;
const int64_t g = dev()->vmem_granularity();
return g > 0 ? g : 0;
}
int VMem::reserve(int64_t bytes, int64_t align) {
release();
if (bytes <= 0) return RAD_E_INVAL;
if (!supported()) {
device_set_error("elastic memory: the %s backend has none", device_backend_name());
return RAD_E_UNSUPPORTED;
}
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. */
const int64_t want = align_up(bytes, g);
void* p = dev()->vmem_reserve(want, align);
if (!p) return RAD_E_NOMEM;
base_ = p;
size_ = want;
committed_ = 0;
ext_.clear();
return RAD_OK;
}
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. */
const int64_t g = granularity();
for (const auto& e : ext_) {
if (dev()->vmem_decommit && g > 0)
for (int64_t o = e.first; o < e.first + e.second; o += g)
(void)dev()->vmem_decommit((char*)base_ + o, g);
g_vmem_committed.fetch_sub(e.second, std::memory_order_relaxed);
}
if (dev()->vmem_release) dev()->vmem_release(base_, size_);
base_ = nullptr;
size_ = 0;
committed_ = 0;
ext_.clear();
}
bool VMem::is_committed(int64_t off, int64_t bytes) const {
if (bytes <= 0) return true;
if (off < 0 || off + bytes > size_) return false;
for (const auto& e : ext_)
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.
*
* 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. */
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. */
const int64_t lo = (off < 0 ? 0 : off / g * g);
int64_t hi = align_up(off + bytes, g);
if (hi > size_) hi = size_;
if (lo >= hi) return RAD_OK;
std::vector<int64_t> want;
want.reserve((size_t)((hi - lo) / g));
for (int64_t o = lo; o < hi; o += g)
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. */
int rc = RAD_OK;
size_t took = 0;
for (; took < want.size(); ++took) {
rc = dev()->vmem_commit((char*)base_ + want[took], g);
if (rc < 0) break;
add_extent(want[took], g);
}
/* 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. */
int prc = RAD_OK;
if (took > 0 && dev()->vmem_protect) {
for (const auto& e : ext_) {
if (e.first + e.second <= lo || e.first >= hi) continue;
prc = dev()->vmem_protect((char*)base_ + e.first, e.second);
if (prc < 0) break;
}
}
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. */
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);
}
return prc;
}
return rc;
}
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. */
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. */
std::vector<int64_t> drop;
for (int64_t o = lo; o < hi; o += g)
if (is_committed(o, g)) drop.push_back(o);
for (const int64_t o : drop) {
const int rc = dev()->vmem_decommit((char*)base_ + o, g);
if (rc < 0) return rc;
drop_extent(o, g);
}
return RAD_OK;
}
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. */
size_t i = 0;
while (i < ext_.size() && ext_[i].first < off) ++i;
ext_.insert(ext_.begin() + (long)i, { off, bytes });
for (size_t j = 0; j + 1 < ext_.size();) {
if (ext_[j].first + ext_[j].second >= ext_[j + 1].first) {
const int64_t end = std::max(ext_[j].first + ext_[j].second,
ext_[j + 1].first + ext_[j + 1].second);
ext_[j].second = end - ext_[j].first;
ext_.erase(ext_.begin() + (long)j + 1);
} else {
++j;
}
}
}
/* 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. */
void VMem::drop_extent(int64_t off, int64_t bytes) {
committed_ -= bytes;
g_vmem_committed.fetch_sub(bytes, std::memory_order_relaxed);
for (size_t i = 0; i < ext_.size(); ++i) {
const int64_t es = ext_[i].first, ee = es + ext_[i].second;
if (off < es || off + bytes > ee) continue;
ext_.erase(ext_.begin() + (long)i);
if (off + bytes < ee) ext_.insert(ext_.begin() + (long)i, { off + bytes, ee - off - bytes });
if (es < off) ext_.insert(ext_.begin() + (long)i, { es, off - es });
return;
}
}
} /* namespace rad */
/* ------------------------------------------------------------------ the ABI surface */
using rad::dev;
extern "C" {
int rad_dev_count(void) { return dev()->count(); }
int rad_dev_set(int device) { return dev()->set(device); }
int rad_dev_props(int device, RadDeviceProps* o) { return dev()->props(device, o); }
int rad_dev_enable_peer(int self, int peer) { return dev()->enable_peer(self, peer); }
void* rad_dev_alloc(int64_t bytes, int kind) {
void* p = dev()->alloc(bytes, kind);
if (p && kind >= 0 && kind < 4) {
rad::g_ledger[kind].bytes.fetch_add(bytes, std::memory_order_relaxed);
rad::g_ledger[kind].count.fetch_add(1, std::memory_order_relaxed);
const int64_t floor_ = rad::trace_floor();
if (floor_ >= 0 && bytes >= floor_)
RAD_INFO("alloc %s %s (%lld live in %lld allocations)", rad::kind_name(kind),
rad::humanb(bytes).c_str(),
(long long)rad::g_ledger[kind].bytes.load(std::memory_order_relaxed),
(long long)rad::g_ledger[kind].count.load(std::memory_order_relaxed));
}
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. */
dev()->free(p, kind);
}
void* rad_dev_host_ptr(void* p) { return dev()->host_ptr(p); }
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); }
} /* extern "C" */
namespace rad {
bool tape_supported() { return dev()->tape_begin != nullptr; }
int dev_vram_used(int device, int64_t* out) {
return dev()->vram_used ? dev()->vram_used(device, out) : RAD_E_UNSUPPORTED;
}
int tape_begin() { return dev()->tape_begin ? dev()->tape_begin() : RAD_E_UNSUPPORTED; }
int tape_mark() { return dev()->tape_mark ? dev()->tape_mark() : RAD_E_UNSUPPORTED; }
void tape_pause(bool on) { if (dev()->tape_pause) dev()->tape_pause(on ? 1 : 0); }
RadTape tape_end(bool keep) { return dev()->tape_end ? dev()->tape_end(keep ? 1 : 0) : nullptr; }
int tape_len(RadTape t) { return dev()->tape_len ? dev()->tape_len(t) : RAD_E_UNSUPPORTED; }
int tape_play(RadTape t, int from, int to) {
return dev()->tape_play ? dev()->tape_play(t, from, to) : RAD_E_UNSUPPORTED;
}
int tape_diff(RadTape a, RadTape b, std::string* why) {
if (!dev()->tape_diff) return RAD_E_UNSUPPORTED;
char buf[512];
buf[0] = 0;
const int at = dev()->tape_diff(a, b, buf, (int)sizeof buf);
if (why) *why = buf;
return at;
}
void tape_destroy(RadTape t) { if (dev()->tape_destroy) dev()->tape_destroy(t); }
int tape_record(RadTape t, int i, int* kind, uint32_t* queue) {
return dev()->tape_record ? dev()->tape_record(t, i, kind, queue) : RAD_E_UNSUPPORTED;
}
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; }
size_t dev_code_mark() { return dev()->code_mark ? dev()->code_mark() : 0; }
int dev_code_runs(size_t from, size_t to, int device, std::string* why) {
if (!dev()->code_runs || from >= to) return 1;
char buf[1024];
buf[0] = 0;
const int r = dev()->code_runs(from, to, device, buf, (int)sizeof buf);
if (why) *why = buf;
return r;
}
} /* namespace rad */
extern "C" {
int rad_event_create_as(RadEvent* out, unsigned flags) {
const int s = dev()->event_create(out, flags);
if (s >= 0 && out && *out) rad::g_live_events.fetch_add(1, std::memory_order_relaxed);
return s;
}
int rad_event_create(RadEvent* out) { return rad_event_create_as(out, RAD_EVENT_HOST_WAIT); }
int rad_event_create_local(RadEvent* out) { return rad_event_create_as(out, RAD_EVENT_LOCAL); }
void rad_event_destroy(RadEvent e) {
if (!e) return;
rad::g_live_events.fetch_sub(1, std::memory_order_relaxed);
dev()->event_destroy(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); }
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);
}
int rad_memcpy_async(void* dst, const void* src, int64_t bytes, RadStream s) {
return dev()->memcpy_async(dst, src, bytes, s);
}
int rad_memcpy_2d_async(void* dst, int64_t dpitch, const void* src, int64_t spitch,
int64_t width, int64_t height, RadStream s) {
return dev()->memcpy_2d_async(dst, dpitch, src, spitch, width, height, s);
}
int rad_memset_async(void* dst, int value, int64_t bytes, RadStream s) {
return dev()->memset_async(dst, value, bytes, s);
}
int rad_memcpy_ranges_async(void* dst, const void* src, int64_t prefix,
const RadCopyRange* ranges, int n, RadStream s) {
return dev()->memcpy_ranges_async(dst, src, prefix, ranges, n, s);
}
/* 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. */
const char* rad_dev_last_error(void) {
static thread_local std::string drained;
drained.swap(rad::t_last_error);
rad::t_last_error.clear();
return drained.c_str();
}
} /* extern "C" */
+393
View File
@@ -0,0 +1,393 @@
/* 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.
*
* 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.
*
* 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.
*/
#include "device.h"
#if defined(RAD_HAVE_HIP) && RAD_HAVE_HIP
#include "../rad_internal.h"
#include <hip/hip_runtime.h>
#include <atomic>
#include <cstdint>
#include <cstdlib>
#include <mutex>
#include <new>
#include <vector>
#include <cstring>
#include <cstdio>
#include <strings.h>
#include <fcntl.h>
#include <unistd.h>
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(). */
int hip_fail(hipError_t e, const char* who) {
device_set_error("%s: %s (%s)", who, hipGetErrorString(e), hipGetErrorName(e));
switch (e) {
case hipErrorOutOfMemory: return RAD_E_NOMEM;
case hipErrorInvalidValue:
case hipErrorInvalidDevice:
case hipErrorInvalidHandle: return RAD_E_INVAL;
case hipErrorNotSupported: return RAD_E_UNSUPPORTED;
default: return RAD_E_DEVICE;
}
}
#define HIP_TRY(call) \
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. */
void hip_note(hipError_t e, const char* who) {
if (e != hipSuccess) RAD_WARN("device: %s: %s", who, hipGetErrorString(e));
}
#define HIP_NOTE(call) hip_note((call), #call)
/* ------------------------------------------------------------------ devices */
int d_count(void) {
int n = 0;
if (hipGetDeviceCount(&n) != hipSuccess) return 0;
return n;
}
int d_set(int device) {
HIP_TRY(hipSetDevice(device));
return RAD_OK;
}
/* ------------------------------------------------------------------ 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 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. */
constexpr int kMaxVramNodes = 64;
std::atomic<int> g_vram_used_fd[kMaxVramNodes] = {}; /* 0: not opened; else the fd plus one */
static int64_t sysfs_vram_free(int device, int64_t total) {
char bus[64] = {0};
if (hipDeviceGetPCIBusId(bus, (int)sizeof bus, device) != hipSuccess || !bus[0]) return -1;
const size_t buslen = std::strlen(bus);
for (int c = 0; c < 64; ++c) {
char path[160];
std::snprintf(path, sizeof path, "/sys/class/drm/card%d/device/uevent", c);
FILE* f = std::fopen(path, "r");
if (!f) continue;
bool match = false;
char line[256];
while (std::fgets(line, (int)sizeof line, f))
if (!std::strncmp(line, "PCI_SLOT_NAME=", 14) &&
!strncasecmp(line + 14, bus, buslen)) { match = true; break; }
std::fclose(f);
if (!match) continue;
auto read_u64 = [&](const char* leaf, long long* out_v) {
char p[160];
std::snprintf(p, sizeof p, "/sys/class/drm/card%d/device/%s", c, leaf);
FILE* g = std::fopen(p, "r");
if (!g) return false;
const bool ok = std::fscanf(g, "%lld", out_v) == 1 && *out_v >= 0;
std::fclose(g);
return ok;
};
long long tot = 0, used = 0;
if (!read_u64("mem_info_vram_total", &tot) || !read_u64("mem_info_vram_used", &used))
return -1;
if (tot != (long long)total) return -1; /* different accountings; do not mix them */
if (device >= 0 && device < kMaxVramNodes &&
g_vram_used_fd[device].load(std::memory_order_acquire) == 0) {
char p[160];
std::snprintf(p, sizeof p, "/sys/class/drm/card%d/device/mem_info_vram_used", c);
const int fd = ::open(p, O_RDONLY | O_CLOEXEC);
int none = 0;
if (fd >= 0 && !g_vram_used_fd[device].compare_exchange_strong(none, fd + 1))
::close(fd);
}
return total - (int64_t)used;
}
return -1;
}
/* A sysfs attribute is regenerated by a read at offset 0, so the descriptor is read with pread and
* never moved. */
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;
if (fd < 0) return RAD_E_UNSUPPORTED;
char buf[32];
const ssize_t n = ::pread(fd, buf, sizeof buf - 1, 0);
if (n <= 0) return RAD_E_IO;
buf[n] = '\0';
char* end = nullptr;
const long long v = std::strtoll(buf, &end, 10);
if (end == buf || v < 0) return RAD_E_IO;
*out = (int64_t)v;
return RAD_OK;
}
int d_integrated(int device) {
int v = 0;
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. */
static int64_t host_mem_available() {
FILE* f = std::fopen("/proc/meminfo", "r");
if (!f) return -1;
char line[256];
long long kb = -1;
while (std::fgets(line, (int)sizeof line, f))
if (std::sscanf(line, "MemAvailable: %lld kB", &kb) == 1) break;
std::fclose(f);
return kb >= 0 ? (int64_t)kb * 1024 : -1;
}
int d_props(int device, RadDeviceProps* out) {
if (!out) return RAD_E_INVAL;
hipDeviceProp_t p{};
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. */
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. */
if (char* c = std::strchr(out->arch, ':')) *c = '\0';
out->device_id = device;
out->n_cu = p.multiProcessorCount;
out->warp_size = p.warpSize;
out->vram_bytes = (int64_t)p.totalGlobalMem;
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. */
int prev = 0;
bool moved = false;
if (hipGetDevice(&prev) == hipSuccess && prev != device &&
hipSetDevice(device) == hipSuccess)
moved = true;
size_t freeb = 0, totalb = 0;
if (hipMemGetInfo(&freeb, &totalb) == hipSuccess) {
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. */
{
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. */
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. */
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. */
int n = d_count();
for (int i = 0; i < n && !out->supports_p2p; ++i) {
if (i == device) continue;
int can = 0;
if (hipDeviceCanAccessPeer(&can, device, i) == hipSuccess && can) out->supports_p2p = 1;
}
return RAD_OK;
}
int d_enable_peer(int self, int peer) {
if (self == peer) return RAD_OK;
int can = 0;
HIP_TRY(hipDeviceCanAccessPeer(&can, self, peer));
if (!can) {
device_set_error("rad_dev_enable_peer(%d, %d): the driver reports no peer path; "
"a kernel library's peer-to-peer all-reduce needs one (spec §9)", self,
peer);
return RAD_E_UNSUPPORTED;
}
int prev = 0;
HIP_TRY(hipGetDevice(&prev));
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. */
if (e != hipSuccess && e != hipErrorPeerAccessAlreadyEnabled)
return hip_fail(e, "hipDeviceEnablePeerAccess");
return RAD_OK;
}
/* ------------------------------------------------------------------ memory */
void* d_alloc(int64_t bytes, int kind) {
if (bytes <= 0) {
device_set_error("rad_dev_alloc(%lld): size must be positive", (long long)bytes);
return nullptr;
}
void* p = nullptr;
hipError_t e = hipSuccess;
switch (kind) {
case RAD_MEM_DEVICE:
e = hipMalloc(&p, (size_t)bytes);
break;
case RAD_MEM_HOST_PINNED:
/* The mover's staging pool and the O_DIRECT landing zone. Pinned so a transfer is a
* DMA the driver does not have to stage through its own bounce buffer (spec §5.4). */
e = hipHostMalloc(&p, (size_t)bytes, hipHostMallocDefault);
break;
case RAD_MEM_HOST_MAPPED:
/* The zero-copy execution site: tier host, site device, no slab slot -- row three of
* spec §5.1's table. hipHostMallocMapped is what makes the allocation addressable from
* a kernel over the link, which is the whole mechanism. The cost is that every read is
* a link read, so this is for read-once weights and the planner decides which
* (spec §19.3). */
e = hipHostMalloc(&p, (size_t)bytes, hipHostMallocMapped);
break;
case RAD_MEM_HOST:
/* Pageable. Aligned to a page anyway so the same buffer 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;
default:
device_set_error("rad_dev_alloc: unknown memory kind %d", kind);
return nullptr;
}
if (e != hipSuccess || !p) {
hip_fail(e == hipSuccess ? hipErrorOutOfMemory : e, "rad_dev_alloc");
return nullptr;
}
return p;
}
void d_free(void* p, int kind) {
if (!p) return;
switch (kind) {
case RAD_MEM_DEVICE: HIP_NOTE(hipFree(p)); break;
case RAD_MEM_HOST_PINNED:
case RAD_MEM_HOST_MAPPED: HIP_NOTE(hipHostFree(p)); break;
case RAD_MEM_HOST: std::free(p); break;
default:
RAD_WARN("rad_dev_free(%p): unknown memory kind %d; leaked rather than freed with the "
"wrong allocator", p, kind);
break;
}
}
void* d_host_ptr(void* p) {
if (!p) return nullptr;
hipPointerAttribute_t a{};
if (hipPointerGetAttributes(&a, p) != hipSuccess) return nullptr;
return a.hostPointer;
}
void* d_device_ptr(void* p) {
if (!p) return nullptr;
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. */
void* d = nullptr;
if (hipHostGetDevicePointer(&d, p, 0) == hipSuccess) return d;
return nullptr;
}
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. */
nullptr, nullptr, nullptr,
nullptr, nullptr, nullptr, nullptr,
nullptr, nullptr, nullptr,
nullptr,
nullptr, nullptr, nullptr, nullptr,
/* Recorded passes: likewise the AQL backend's. */
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"). */
nullptr, nullptr, nullptr, nullptr, nullptr, nullptr,
d_vram_used,
/* Plugin device code: the AQL backend's, which owns the fat-binary registrations. */
nullptr, nullptr,
d_integrated,
};
} /* namespace */
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. */
RAD_DEBUG("device: hipGetDeviceCount -> %s, %d device(s)", hipGetErrorName(e), n);
return nullptr;
}
return &g_hip;
}
} /* namespace rad */
#endif /* RAD_HAVE_HIP */
+793
View File
@@ -0,0 +1,793 @@
/* 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.
*
* 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 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.
*/
#include "device.h"
#include "../rad_internal.h"
#include <atomic>
#include <chrono>
#include <condition_variable>
#include <cstdlib>
#include <cstring>
#include <mutex>
#include <thread>
#include <unordered_map>
#include <vector>
#include <sys/mman.h>
#include <unistd.h>
namespace rad {
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. */
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. */
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. */
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.
*
* `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. */
struct HostEvent {
std::mutex m;
std::condition_variable cv;
uint64_t recorded = 0;
uint64_t completed = 0;
Clock::time_point stamp{}; /* when the worker reached the most recent record */
std::atomic<int> refs{1};
bool host = false; /* RAD_EVENT_HOST_WAIT */
};
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. */
void event_release(HostEvent* e) {
if (e->refs.fetch_sub(1, std::memory_order_acq_rel) == 1) delete e;
}
/* ------------------------------------------------------------------ tasks */
struct Task {
enum Kind : uint8_t { Copy, Copy2D, Ranges, Memset, Record, Wait, Stop };
Kind kind = Stop;
void* dst = nullptr;
const void* src = nullptr;
int64_t a = 0, b = 0, c = 0, d = 0;
const void* aux = nullptr;
HostEvent* ev = nullptr;
uint64_t seq = 0;
};
/* ------------------------------------------------------------------ streams */
struct HostStream {
std::mutex m;
std::condition_variable cv_work; /* worker waits on this for a task or a stop */
std::condition_variable cv_room; /* producers wait on this when the ring is full */
std::condition_variable cv_done; /* rad_stream_sync waits on this */
std::vector<Task> ring;
size_t head = 0; /* next slot to pop */
size_t tail = 0; /* next slot to push */
size_t count = 0;
uint64_t submitted = 0; /* tasks ever pushed */
uint64_t retired = 0; /* tasks ever finished executing */
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. */
int stream_push(HostStream* s, const Task& t) {
std::unique_lock<std::mutex> lk(s->m);
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();
++s->count;
++s->submitted;
lk.unlock();
s->cv_work.notify_one();
return RAD_OK;
}
void stream_run(HostStream* s) {
for (;;) {
Task t;
{
std::unique_lock<std::mutex> lk(s->m);
s->cv_work.wait(lk, [s] { return s->count > 0; });
t = s->ring[s->head];
s->head = (s->head + 1) % s->ring.size();
--s->count;
}
s->cv_room.notify_one();
bool done = false;
switch (t.kind) {
case Task::Copy:
std::memcpy(t.dst, t.src, (size_t)t.a);
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. */
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);
break;
case Task::Ranges: {
/* a = prefix bytes, b = range count; the list is read now, as the device's is. */
std::memcpy(t.dst, t.src, (size_t)t.a);
const RadCopyRange* r = (const RadCopyRange*)t.aux;
for (int64_t i = 0; i < t.b; ++i)
std::memcpy((uint8_t*)t.dst + r[i].dst, (const uint8_t*)t.src + r[i].src,
(size_t)r[i].bytes);
break;
}
case Task::Memset:
std::memset(t.dst, (int)t.a, (size_t)t.b);
break;
case Task::Record: {
std::lock_guard<std::mutex> lk(t.ev->m);
if (t.seq > t.ev->completed) {
t.ev->completed = t.seq;
t.ev->stamp = Clock::now();
}
t.ev->cv.notify_all();
break;
}
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. */
std::unique_lock<std::mutex> lk(t.ev->m);
t.ev->cv.wait(lk, [&t] { return t.ev->completed >= t.seq; });
break;
}
case Task::Stop:
done = true;
break;
}
/* After the task's lock has gone out of scope: this may be the last reference. */
if (t.ev) event_release(t.ev);
{
std::lock_guard<std::mutex> lk(s->m);
++s->retired;
}
s->cv_done.notify_all();
if (done) return;
}
}
/* ------------------------------------------------------------------ allocation bookkeeping */
struct AllocRec {
int64_t bytes = 0;
int kind = 0;
int device = 0;
};
std::mutex& alloc_mutex() { static std::mutex m; return m; }
std::unordered_map<void*, AllocRec>& alloc_table() {
static std::unordered_map<void*, AllocRec> t;
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). */
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. */
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) {
std::lock_guard<std::mutex> lk(alloc_mutex());
auto it = alloc_table().find(p);
if (it == alloc_table().end()) return false;
*out = it->second;
return true;
}
/* ------------------------------------------------------------------ devices */
int64_t env_i64(const char* key, int64_t dflt) {
const char* v = std::getenv(key);
if (!v || !*v) return dflt;
char* end = nullptr;
long long n = std::strtoll(v, &end, 10);
if (end == v || n < 0) {
RAD_WARN("%s=\"%s\" is not a non-negative integer; using %lld", key, v, (long long)dflt);
return dflt;
}
return (int64_t)n;
}
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). */
static int n = [] {
int64_t v = env_i64("RADIANCE_HOST_DEVICES", 1);
if (v < 1) v = 1;
if (v > kMaxFakeDevices) {
RAD_WARN("RADIANCE_HOST_DEVICES=%lld clamped to %d", (long long)v, kMaxFakeDevices);
v = kMaxFakeDevices;
}
if (v > 1) RAD_INFO("device: host backend presenting %lld fake devices", (long long)v);
return (int)v;
}();
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. */
thread_local int t_device = 0;
int64_t physical_ram() {
long pages = sysconf(_SC_PHYS_PAGES), page = sysconf(_SC_PAGESIZE);
if (pages <= 0 || page <= 0) return 8ll << 30;
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. */
int64_t host_vram_bytes() {
int64_t mib = env_i64("RADIANCE_HOST_VRAM_MIB", 0);
if (mib > 0) return mib << 20;
return (physical_ram() / 2) / host_count();
}
const char* cpu_model() {
static std::string s = [] {
std::string out = "host cpu";
FILE* f = std::fopen("/proc/cpuinfo", "r");
if (!f) return out;
char line[512];
while (std::fgets(line, sizeof line, f)) {
if (std::strncmp(line, "model name", 10) != 0) continue;
const char* c = std::strchr(line, ':');
if (!c) break;
++c;
while (*c == ' ' || *c == '\t') ++c;
out.assign(c);
while (!out.empty() && (out.back() == '\n' || out.back() == ' ')) out.pop_back();
break;
}
std::fclose(f);
return out;
}();
return s.c_str();
}
/* ------------------------------------------------------------------ the fourteen calls */
int h_count(void) { return host_count(); }
int h_set(int device) {
if (device < 0 || device >= host_count()) {
device_set_error("rad_dev_set(%d): host backend has %d device(s)", device, host_count());
return RAD_E_INVAL;
}
t_device = device;
return RAD_OK;
}
int h_props(int device, RadDeviceProps* out) {
if (!out) return RAD_E_INVAL;
if (device < 0 || device >= host_count()) {
device_set_error("rad_dev_props(%d): host backend has %d device(s)", device, host_count());
return RAD_E_INVAL;
}
std::memset(out, 0, sizeof *out);
snprintf(out->name, sizeof out->name, "%s", cpu_model());
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. */
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. */
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. */
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. */
out->supports_p2p = 1;
out->is_host_backend = 1;
return RAD_OK;
}
int h_enable_peer(int self, int peer) {
if (self < 0 || self >= host_count() || peer < 0 || peer >= host_count()) {
device_set_error("rad_dev_enable_peer(%d, %d): host backend has %d device(s)",
self, peer, host_count());
return RAD_E_INVAL;
}
return RAD_OK; /* one address space; nothing to enable */
}
void* h_alloc(int64_t bytes, int kind) {
if (bytes <= 0) {
device_set_error("rad_dev_alloc(%lld): size must be positive", (long long)bytes);
return nullptr;
}
if (kind < RAD_MEM_DEVICE || kind > RAD_MEM_HOST_MAPPED) {
device_set_error("rad_dev_alloc: unknown memory kind %d", 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. */
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);
return nullptr;
}
int dev = t_device;
alloc_note(p, bytes, kind, dev);
if (kind == RAD_MEM_DEVICE) g_used[dev].fetch_add(bytes, std::memory_order_relaxed);
return p;
}
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. */
RAD_WARN("rad_dev_free(%p, kind=%d): pointer was not allocated by the device layer",
p, kind);
return;
}
if (r.kind != kind)
RAD_WARN("rad_dev_free(%p): freed as kind %d, allocated as kind %d", p, kind, r.kind);
if (r.kind == RAD_MEM_DEVICE) g_used[r.device].fetch_sub(r.bytes, std::memory_order_relaxed);
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. */
void* h_host_ptr(void* p) {
if (!p) return nullptr;
AllocRec r;
return alloc_find(p, &r) ? p : nullptr;
}
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. */
(void)high_priority;
auto* s = new (std::nothrow) HostStream();
if (!s) { device_set_error("rad_stream_create: out of memory"); return RAD_E_NOMEM; }
s->ring.resize(kQueueDepth);
s->worker = std::thread(stream_run, s);
*out = (RadStream)s;
return RAD_OK;
}
void h_stream_destroy(RadStream st) {
if (!st) return;
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. */
stream_push(s, t);
if (s->worker.joinable()) s->worker.join();
delete s;
}
int h_stream_sync(RadStream st) {
if (!st) {
device_set_error("rad_stream_sync: null stream");
return RAD_E_INVAL;
}
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. */
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. */
int h_event_create(RadEvent* out, unsigned flags) {
if (!out) return RAD_E_INVAL;
auto* e = new (std::nothrow) HostEvent();
if (!e) { device_set_error("rad_event_create: out of memory"); return RAD_E_NOMEM; }
e->host = (flags & RAD_EVENT_HOST_WAIT) != 0;
*out = (RadEvent)e;
return RAD_OK;
}
/* Drops the handle. A record or wait still queued keeps the event alive until the worker is past
* it -- see HostEvent. */
void h_event_destroy(RadEvent ev) { if (ev) event_release((HostEvent*)ev); }
int h_event_record(RadEvent ev, RadStream st) {
if (!ev || !st) {
device_set_error("rad_event_record: null %s", ev ? "stream" : "event");
return RAD_E_INVAL;
}
auto* e = (HostEvent*)ev;
uint64_t seq;
{
std::lock_guard<std::mutex> lk(e->m);
seq = ++e->recorded; /* pending from this instant, on the host, before the push */
}
Task t;
t.kind = Task::Record;
t.ev = e;
t.seq = seq;
event_retain(e);
return stream_push((HostStream*)st, t);
}
int h_event_wait(RadStream st, RadEvent ev) {
if (!ev || !st) {
device_set_error("rad_event_wait: null %s", ev ? "stream" : "event");
return RAD_E_INVAL;
}
auto* e = (HostEvent*)ev;
uint64_t target;
{
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. */
if (target == 0) return RAD_OK;
Task t;
t.kind = Task::Wait;
t.ev = e;
t.seq = target;
event_retain(e);
return stream_push((HostStream*)st, t);
}
int h_event_query(RadEvent ev) {
if (!ev) return RAD_E_INVAL;
auto* e = (HostEvent*)ev;
std::lock_guard<std::mutex> lk(e->m);
return e->completed >= e->recorded ? 1 : 0;
}
/* Host kernels read host memory directly, so there is nothing to make visible. */
void h_host_wrote(void) {}
int h_event_sync(RadEvent ev) {
if (!ev) return RAD_E_INVAL;
auto* e = (HostEvent*)ev;
if (!e->host) {
device_set_error("rad_event_sync: the event was made without RAD_EVENT_HOST_WAIT");
return RAD_E_INVAL;
}
std::unique_lock<std::mutex> lk(e->m);
const uint64_t target = e->recorded;
e->cv.wait(lk, [e, target] { return e->completed >= target; });
return RAD_OK;
}
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;
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;
}
*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. */
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, "
"create one with rad_stream_create", who);
return RAD_E_INVAL;
}
int h_memcpy_async(void* dst, const void* src, int64_t bytes, RadStream st) {
RAD_TRY(check_stream(st, "rad_memcpy_async"));
if (bytes == 0) return RAD_OK;
if (!dst || !src || bytes < 0) {
device_set_error("rad_memcpy_async(%p <- %p, %lld): invalid argument",
dst, src, (long long)bytes);
return RAD_E_INVAL;
}
Task t;
t.kind = Task::Copy;
t.dst = dst;
t.src = src;
t.a = bytes;
return stream_push((HostStream*)st, t);
}
int h_memcpy_2d_async(void* dst, int64_t dpitch, const void* src, int64_t spitch,
int64_t width, int64_t height, RadStream st) {
RAD_TRY(check_stream(st, "rad_memcpy_2d_async"));
if (width == 0 || height == 0) return RAD_OK;
if (!dst || !src || width < 0 || height < 0 || dpitch < width || spitch < width) {
device_set_error("rad_memcpy_2d_async: w=%lld h=%lld dpitch=%lld spitch=%lld "
"-- a pitch shorter than the row is a caller bug",
(long long)width, (long long)height,
(long long)dpitch, (long long)spitch);
return RAD_E_INVAL;
}
Task t;
t.kind = Task::Copy2D;
t.dst = dst;
t.src = src;
t.a = dpitch;
t.b = spitch;
t.c = width;
t.d = height;
return stream_push((HostStream*)st, t);
}
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);
return RAD_E_INVAL;
}
if (prefix == 0 && n == 0) return RAD_OK;
Task t;
t.kind = Task::Ranges;
t.dst = dst;
t.src = src;
t.a = prefix;
t.b = n;
t.aux = ranges;
return stream_push((HostStream*)st, t);
}
int h_memset_async(void* dst, int value, int64_t bytes, RadStream st) {
RAD_TRY(check_stream(st, "rad_memset_async"));
if (bytes == 0) return RAD_OK;
if (!dst || bytes < 0) {
device_set_error("rad_memset_async(%p, %lld): invalid argument", dst, (long long)bytes);
return RAD_E_INVAL;
}
Task t;
t.kind = Task::Memset;
t.dst = dst;
t.a = value & 0xff;
t.b = bytes;
return stream_push((HostStream*)st, t);
}
/* ------------------------------------------------------------------ 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.
*
* 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. */
constexpr int64_t kVmemGranule = RAD_ALIGN_POOL;
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. */
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);
if (raw == MAP_FAILED) {
device_set_error("vmem_reserve(%lld): mmap failed", (long long)bytes);
return nullptr;
}
char* base = (char*)align_up((int64_t)(uintptr_t)raw, align);
const size_t head = (size_t)(base - (char*)raw);
if (head) ::munmap(raw, head);
const size_t tail = raw_len - head - (size_t)bytes;
if (tail) ::munmap(base + bytes, tail);
return base;
}
void h_vmem_release(void* base, int64_t bytes) {
if (base && bytes > 0) ::munmap(base, (size_t)bytes);
}
int h_vmem_commit(void* addr, int64_t bytes) {
if (!addr || bytes <= 0) return RAD_E_INVAL;
void* p = ::mmap(addr, (size_t)bytes, PROT_READ | PROT_WRITE,
MAP_FIXED | MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
if (p != addr) {
device_set_error("vmem_commit(%p, %lld): mmap failed", addr, (long long)bytes);
return RAD_E_NOMEM;
}
g_used[t_device].fetch_add(bytes, std::memory_order_relaxed);
return RAD_OK;
}
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. */
void* p = ::mmap(addr, (size_t)bytes, PROT_NONE,
MAP_FIXED | MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
if (p != addr) {
device_set_error("vmem_decommit(%p, %lld): mmap failed", addr, (long long)bytes);
return RAD_E_INVAL;
}
g_used[t_device].fetch_sub(bytes, std::memory_order_relaxed);
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. */
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) {
device_set_error("vmem_protect(%p, %lld): mprotect failed", addr, (long long)bytes);
return RAD_E_INVAL;
}
return RAD_OK;
}
int h_vram_used(int device, int64_t* out) {
if (!out || device < 0 || device >= kMaxFakeDevices) return RAD_E_INVAL;
*out = g_used[device].load(std::memory_order_relaxed);
return RAD_OK;
}
const DeviceBackend g_host = {
"host",
h_count, h_set, h_props, h_enable_peer,
h_alloc, h_free, h_host_ptr, h_device_ptr,
h_stream_create, h_stream_destroy, h_stream_sync,
h_event_create, h_event_destroy, h_event_record, h_event_wait,
h_event_query, h_event_sync, h_event_elapsed_ms,
h_host_wrote,
h_memcpy_async, h_memcpy_2d_async, h_memset_async, h_memcpy_ranges_async,
/* 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. */
nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr,
/* Elastic memory, which the host backend DOES have: see above. */
h_vmem_granularity, h_vmem_reserve, h_vmem_release, h_vmem_commit, h_vmem_decommit,
h_vmem_protect,
h_vram_used,
};
} /* namespace */
const DeviceBackend* host_backend(void) { return &g_host; }
} /* namespace rad */