Archived
Merge upstream main (v1.17.0 -> v2.1.0) into the SYCL port
102 upstream commits. Nine conflicts resolved. Fork side of the merge: - libxe2: declare the givens_dense_quant schema (upstream 2.0 dropped it from libavx and libref; the device libraries now each carry it). - plain_norm becomes an ABI 42 append to RadBuildCtx; abi layout table regenerated, kTableAbi = 42. Known before the PR: arch_test (MTP lint and pinned graph hashes for qwen35_fp8, qwen35moe_fp8, qwen4exp with MTP). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
commit
4b70a96378
850 files changed
+157819
-58519
No files matched your search
+853
-74
File diff suppressed because it is too large.
Load diff
@@ -72,6 +72,25 @@ void set_next_fence(uint8_t f);
|
||||
/* Whether the signal behind a rad_ride token could be handed out again now (tests/device_test.cpp). */
|
||||
bool ride_reusable(void* token);
|
||||
|
||||
/* `pairs` launches of two chained kernels onto `stream`, one behind the other: the first stores
|
||||
* i + 1 over the 64 words at `x`; the second loads x[0] the way a kernel loads a value all its
|
||||
* lanes share (a scalar load) and each of its `blocks` blocks stores what it saw, at
|
||||
* seen[i * blocks + block]. Every reader must have seen the store in front of it
|
||||
* (tests/device_test.cpp). RAD_E_UNSUPPORTED in a build without the backend. */
|
||||
int chain_probe(void* stream, unsigned* x, unsigned* seen, unsigned pairs, unsigned blocks);
|
||||
|
||||
/* `n` chained launches onto `stream`, launch i storing i + 1 at seen[i]: each takes where to
|
||||
* store from its own arguments, so a launch that read another's leaves a word unwritten
|
||||
* (tests/device_test.cpp). RAD_E_UNSUPPORTED in a build without the backend. */
|
||||
int chain_marks(void* stream, unsigned* seen, unsigned n);
|
||||
|
||||
/* `n` chained launches onto `stream`, each a card-side copy of `bytes` (a multiple of 16) from
|
||||
* `src` to `dst` that also stores at seen[i] whether it found a chain record in its argument
|
||||
* slot: i + 1 if every block did, that with the top bit set if one did not. A block that found
|
||||
* none still counts, so the launches behind it are not left waiting (tests/device_test.cpp).
|
||||
* RAD_E_UNSUPPORTED in a build without the backend. */
|
||||
int chain_asks(void* stream, const void* src, void* dst, uint64_t bytes, unsigned* seen, unsigned n);
|
||||
|
||||
} // namespace aql
|
||||
} // namespace rad
|
||||
|
||||
@@ -90,4 +109,10 @@ int rad_aql_blit_fill(void* dst, int value, uint64_t bytes, void* stream);
|
||||
/* rad_memcpy_ranges_async's kernel: `prefix` a multiple of 16, both bases 16-byte aligned. */
|
||||
int rad_aql_blit_ranges(void* dst, const void* src, uint64_t prefix, const RadCopyRange* ranges,
|
||||
int n, void* stream);
|
||||
/* aql::chain_probe's two kernels, aql::chain_marks's one and aql::chain_asks's one. */
|
||||
int rad_aql_probe_store(unsigned* x, unsigned v, void* stream);
|
||||
int rad_aql_probe_load(const unsigned* x, unsigned* seen, unsigned blocks, void* stream);
|
||||
int rad_aql_probe_mark(unsigned* seen, unsigned v, void* stream);
|
||||
int rad_aql_probe_ask(const void* src, void* dst, uint64_t bytes, unsigned* seen, unsigned v,
|
||||
unsigned long long* ctr, void* stream);
|
||||
}
|
||||
@@ -14,6 +14,7 @@
|
||||
#include <cstdint>
|
||||
|
||||
#include "aql.h"
|
||||
#include "chain_kernel.h"
|
||||
#include "device.h"
|
||||
|
||||
namespace {
|
||||
@@ -36,6 +37,22 @@ __global__ __launch_bounds__(kThreads) void aql_copy16(const u32x4* __restrict__
|
||||
for (; i < n; i += stride) dst[i] = src[i];
|
||||
}
|
||||
|
||||
/* aql_copy16 as a chained form (chain_kernel.h), launched where launches chain: a card-side copy
|
||||
* between two kernels of a pass (a routed layer's counts into the core's row) then costs no
|
||||
* barrier on either side. */
|
||||
__global__ __launch_bounds__(kThreads) void r4dchain_copy16(const u32x4* __restrict__ src,
|
||||
u32x4* __restrict__ dst, uint64_t n) {
|
||||
rad_chain_wait();
|
||||
const uint64_t stride = (uint64_t)gridDim.x * kThreads;
|
||||
uint64_t i = (uint64_t)blockIdx.x * kThreads + threadIdx.x;
|
||||
for (; i + 3 * stride < n; i += 4 * stride) {
|
||||
const u32x4 a = src[i], b = src[i + stride], c = src[i + 2 * stride], d = src[i + 3 * stride];
|
||||
dst[i] = a; dst[i + stride] = b; dst[i + 2 * stride] = c; dst[i + 3 * stride] = d;
|
||||
}
|
||||
for (; i < n; i += stride) dst[i] = src[i];
|
||||
rad_chain_done();
|
||||
}
|
||||
|
||||
/* A copy across the link (pinned host memory) is one workgroup of four waves.
|
||||
*
|
||||
* The link delivers ~29 GB/s regardless of grid size, so the copy should hold as few waves as
|
||||
@@ -190,6 +207,9 @@ extern "C" int rad_aql_blit_copy(void* dst, const void* src, uint64_t bytes, voi
|
||||
if (link)
|
||||
hipLaunchKernelGGL(aql_copy_link, dim3(1), dim3(kLinkThreads), 0, s,
|
||||
(const u32x4*)src, (u32x4*)dst, n);
|
||||
else if (rad_dev_chain_enabled())
|
||||
hipLaunchKernelGGL(r4dchain_copy16, dim3(blocks_for(n, 4 * kThreads)), dim3(kThreads),
|
||||
0, s, (const u32x4*)src, (u32x4*)dst, n);
|
||||
else
|
||||
hipLaunchKernelGGL(aql_copy16, dim3(blocks_for(n, 4 * kThreads)), dim3(kThreads), 0,
|
||||
s, (const u32x4*)src, (u32x4*)dst, n);
|
||||
@@ -230,6 +250,75 @@ extern "C" int rad_aql_blit_ranges(void* dst, const void* src, uint64_t prefix,
|
||||
return launched();
|
||||
}
|
||||
|
||||
/* aql::chain_probe's pair (aql.h). The reader's load has one address for the whole wave and
|
||||
* nothing in the kernel writes there, so the compiler makes it a scalar load: served from the
|
||||
* scalar data cache, which the wait must have emptied (chain_kernel.h) for the kernel to see the
|
||||
* store in front of it. */
|
||||
namespace {
|
||||
__global__ __launch_bounds__(64) void r4dchain_probe_store(unsigned* __restrict__ x, unsigned v) {
|
||||
rad_chain_wait();
|
||||
x[threadIdx.x] = v;
|
||||
rad_chain_done();
|
||||
}
|
||||
__global__ __launch_bounds__(32) void r4dchain_probe_load(const unsigned* __restrict__ x,
|
||||
unsigned* __restrict__ seen) {
|
||||
rad_chain_wait();
|
||||
const unsigned v = x[0];
|
||||
if (threadIdx.x == 0) seen[blockIdx.x] = v;
|
||||
rad_chain_done();
|
||||
}
|
||||
/* aql::chain_marks's kernel: where it stores comes from its arguments alone. */
|
||||
__global__ __launch_bounds__(32) void r4dchain_probe_mark(unsigned* __restrict__ seen, unsigned v) {
|
||||
rad_chain_wait();
|
||||
if (threadIdx.x == 0) seen[v - 1u] = v;
|
||||
rad_chain_done();
|
||||
}
|
||||
|
||||
/* aql::chain_asks's kernel: a card-side copy like r4dchain_copy16 that says whether there was a
|
||||
* chain record in its argument slot when it started. A block that found none counts nothing in
|
||||
* rad_chain_done, so it counts by the address in its arguments instead and the launches behind
|
||||
* it do not wait for it for good. */
|
||||
__global__ __launch_bounds__(kThreads) void r4dchain_probe_ask(const u32x4* __restrict__ src,
|
||||
u32x4* __restrict__ dst, uint64_t n,
|
||||
unsigned* __restrict__ seen, unsigned v,
|
||||
unsigned long long* __restrict__ ctr) {
|
||||
const bool found = rad_chain_rec() != nullptr;
|
||||
rad_chain_wait();
|
||||
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];
|
||||
if (threadIdx.x == 0)
|
||||
__hip_atomic_fetch_or(&seen[v - 1u], found ? v : (v | 0x80000000u), __ATOMIC_RELAXED,
|
||||
__HIP_MEMORY_SCOPE_AGENT);
|
||||
rad_chain_done();
|
||||
if (!found && threadIdx.x == 0)
|
||||
__hip_atomic_fetch_add(ctr, 1ull, __ATOMIC_RELEASE, __HIP_MEMORY_SCOPE_AGENT);
|
||||
}
|
||||
} // namespace
|
||||
|
||||
extern "C" int rad_aql_probe_ask(const void* src, void* dst, uint64_t bytes, unsigned* seen, unsigned v,
|
||||
unsigned long long* ctr, void* stream) {
|
||||
const uint64_t n = bytes / 16;
|
||||
hipLaunchKernelGGL(r4dchain_probe_ask, dim3(blocks_for(n, 4 * kThreads)), dim3(kThreads), 0,
|
||||
(hipStream_t)stream, (const u32x4*)src, (u32x4*)dst, n, seen, v, ctr);
|
||||
return launched();
|
||||
}
|
||||
|
||||
extern "C" int rad_aql_probe_mark(unsigned* seen, unsigned v, void* stream) {
|
||||
hipLaunchKernelGGL(r4dchain_probe_mark, dim3(1), dim3(32), 0, (hipStream_t)stream, seen, v);
|
||||
return launched();
|
||||
}
|
||||
|
||||
extern "C" int rad_aql_probe_store(unsigned* x, unsigned v, void* stream) {
|
||||
hipLaunchKernelGGL(r4dchain_probe_store, dim3(1), dim3(64), 0, (hipStream_t)stream, x, v);
|
||||
return launched();
|
||||
}
|
||||
|
||||
extern "C" int rad_aql_probe_load(const unsigned* x, unsigned* seen, unsigned blocks, void* stream) {
|
||||
if (blocks == 0) return 0;
|
||||
hipLaunchKernelGGL(r4dchain_probe_load, dim3(blocks), dim3(32), 0, (hipStream_t)stream, x, seen);
|
||||
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;
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
/* chain_kernel.h -- the chained form's wait and completion for the core's own kernels
|
||||
* (RadKernelChainFn, abi/rad_abi.h).
|
||||
*
|
||||
* The backend gives a kernel named r4dchain* a record at RAD_CHAIN_KARG_OFF and drops its barrier
|
||||
* bit behind another chained kernel. Before the first read one lane waits for the queue's counter
|
||||
* to reach the record's target; after the last write the block releases and adds 1. A record that
|
||||
* does not check out means: run plain. Every block must reach rad_chain_done exactly once.
|
||||
*/
|
||||
#pragma once
|
||||
#include <hip/hip_runtime.h>
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
#include "rad_abi.h"
|
||||
|
||||
struct RadChainRec {
|
||||
unsigned long long magic, target;
|
||||
unsigned long long* ctr;
|
||||
unsigned long long check;
|
||||
};
|
||||
|
||||
__device__ __forceinline__ const RadChainRec* rad_chain_rec() {
|
||||
const RadChainRec* r = (const RadChainRec*)((const char*)__builtin_amdgcn_kernarg_segment_ptr() +
|
||||
RAD_CHAIN_KARG_OFF);
|
||||
const unsigned long long magic = r->magic, target = r->target, check = r->check;
|
||||
if (magic != RAD_CHAIN_MAGIC ||
|
||||
check != (magic ^ target ^ (unsigned long long)(uintptr_t)r->ctr ^ RAD_CHAIN_CHECK))
|
||||
return nullptr;
|
||||
return r;
|
||||
}
|
||||
|
||||
__device__ __forceinline__ void rad_chain_wait() {
|
||||
const RadChainRec* r = rad_chain_rec();
|
||||
if (!r) return;
|
||||
if (threadIdx.x == 0 && threadIdx.y == 0 && threadIdx.z == 0)
|
||||
while (__hip_atomic_load(r->ctr, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT) < r->target)
|
||||
__builtin_amdgcn_s_sleep(1);
|
||||
__syncthreads();
|
||||
__builtin_amdgcn_fence(__ATOMIC_ACQUIRE, "agent");
|
||||
/* The fence empties the vector caches. A load every lane shares may be a scalar one, and the
|
||||
* scalar data cache still holds what a launch read from the address before the launch in front
|
||||
* of this one wrote it: only the packet processor's acquire empties that cache, and it runs
|
||||
* when the kernel is launched, before the launch in front has written. */
|
||||
asm volatile("s_dcache_inv" ::: "memory");
|
||||
}
|
||||
|
||||
__device__ __forceinline__ void rad_chain_done() {
|
||||
const RadChainRec* r = rad_chain_rec();
|
||||
if (!r) return;
|
||||
__builtin_amdgcn_fence(__ATOMIC_RELEASE, "agent");
|
||||
__syncthreads();
|
||||
if (threadIdx.x == 0 && threadIdx.y == 0 && threadIdx.z == 0)
|
||||
__hip_atomic_fetch_add(r->ctr, 1ull, __ATOMIC_RELEASE, __HIP_MEMORY_SCOPE_AGENT);
|
||||
}
|
||||
+339
-6
@@ -12,7 +12,10 @@
|
||||
#include "rad_abi.h"
|
||||
#include "rad_device.h"
|
||||
|
||||
#include <atomic>
|
||||
#include <cstdint>
|
||||
#include <map>
|
||||
#include <functional>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
@@ -39,9 +42,19 @@ extern "C" void rad_dev_host_wrote(void);
|
||||
/* Chained launches: chainable rows run their chained forms (RadKernelChainFn), and the backend
|
||||
* lets a chained kernel (named r4dchain*) wait in its prologue instead of behind the barrier bit.
|
||||
* Only on the AQL backend, whose queues keep the completion counter, and only where the model's
|
||||
* plugin measured a gain with its speculative drafter (RadArchProbe::chain_pays) and that drafter
|
||||
* decodes speculatively (rad_dev_chain_infer, from the engine before any row resolves). */
|
||||
* plugin measured a gain (RadArchProbe::chain_pays): with its drafter decoding speculatively, or
|
||||
* with and without one (rad_dev_chain_infer, from the engine before any row resolves).
|
||||
*
|
||||
* rad_dev_chain_infer(2) says more: every chained form this engine can launch fences itself
|
||||
* (RadKernelChainFn saying 2, abi/rad_abi.h). rad_dev_chain_unfenced then answers 1, and the
|
||||
* backend issues a chained launch that has lost its barrier bit without the packet processor's
|
||||
* acquire as well (aql.cpp, "the acquire of a chained launch"). */
|
||||
extern "C" int rad_dev_chain_enabled(void);
|
||||
/* VRAM the runtime keeps resident as queue scratch on `props`' card once a kernel with a private
|
||||
* segment has run (0 on the host backend and on unified memory). Charged to the VRAM budget with
|
||||
* the hardware queues. */
|
||||
extern "C" int64_t rad_dev_resident_scratch_bytes(const RadDeviceProps* props);
|
||||
extern "C" int rad_dev_chain_unfenced(void);
|
||||
extern "C" void rad_dev_chain_infer(int pays);
|
||||
|
||||
/* One range of a ranged copy: `bytes` from source offset `src` to destination offset `dst`, all
|
||||
@@ -91,6 +104,17 @@ extern "C" int rad_memcpy_list_async(const RadCopySeg* segs, int n, unsigned fla
|
||||
* copies; the step waits on the collective, while the copies have the rest of the layer. */
|
||||
extern "C" int rad_link_hold(RadStream s, int on);
|
||||
|
||||
/* The launches this thread issues between `on` 1 and `on` 0 are a collective's: their blocks wait
|
||||
* for the other ranks' blocks of the same launch on another card. A recorded pass keeps the mark.
|
||||
*
|
||||
* rad_dev_cards_claim tells the backend which cards an engine's collectives run on (`on` 1, once
|
||||
* per engine with more than one rank) and that the engine is gone (`on` 0). On a card more than one
|
||||
* engine has claimed, nothing may wait on the card behind a collective except the collective's own
|
||||
* blocks (aql.cpp, "collectives on a shared card"). A claim that makes a card shared returns once
|
||||
* everything issued before it on that card's streams has finished. */
|
||||
extern "C" void rad_dev_peer_launch(int on);
|
||||
extern "C" int rad_dev_cards_claim(const int* cards, int n, int on);
|
||||
|
||||
/* The hold word, for a launch that ends its own hold: a 64-bit word reachable by every engine and
|
||||
* kernel of the card, odd while the link is held. A launch handed this address releases the hold
|
||||
* by decrementing the word once, only if odd, as soon as its awaited bytes have landed; follow it
|
||||
@@ -280,9 +304,14 @@ struct DeviceBackend {
|
||||
*
|
||||
* Contract:
|
||||
* `vmem_reserve` takes address space, no pages.
|
||||
* `vmem_commit` backs one granule and `vmem_decommit` unbacks one. The driver unmaps a
|
||||
* mapping only exactly as it was mapped (four granules mapped in one call cannot be unmapped
|
||||
* singly), so VMem issues one call per granule.
|
||||
* `vmem_commit` backs one granule. The driver unmaps a mapping only exactly as it was
|
||||
* mapped (four granules mapped as one cannot be unmapped singly), so VMem maps a mapping per
|
||||
* granule, a run of them in one `vmem_commit_units` call where the backend has it. It
|
||||
* returns 1 when the backing is recycled memory that holds what its last mapping left, 0
|
||||
* when it reads zero.
|
||||
* `vmem_decommit` unbacks a range that is one mapping or a contiguous run of whole ones, in
|
||||
* one unmap: each unmap costs a driver round trip that grows with the mappings the process
|
||||
* holds (8.8 us a granule alone, 48 beside 6000 others; 26 for a run, per granule).
|
||||
* `vmem_protect` grants this device read/write access to an already-backed range. It is
|
||||
* separate from commit because access set on a granule adjacent to an accessible one is
|
||||
* refused, while the whole contiguous run is accepted; VMem names the run.
|
||||
@@ -355,6 +384,36 @@ struct DeviceBackend {
|
||||
|
||||
/* ---- see dev_stuck_ms. Null on a backend that cannot tell. */
|
||||
int64_t (*stuck_ms)(void);
|
||||
|
||||
/* ---- host-backed mappings, for parking (paging.cpp). `vmem_commit_host` backs a reserved
|
||||
* granule with pinned host memory that the reservation's card reads and writes in place, at
|
||||
* that address, and the host can too. `vmem_swap` exchanges what backs two mapped ranges of
|
||||
* equal size (each keeps its kind: a range of device memory stays device memory wherever it
|
||||
* is mapped). Remapped addresses need dev_settle_maps before the card writes them. Null on a
|
||||
* backend without them; parking then keeps no host copies. */
|
||||
int (*vmem_commit_host)(void* addr, int64_t bytes);
|
||||
int (*vmem_swap)(void* a, void* b, int64_t bytes);
|
||||
|
||||
/* ---- [addr, addr + bytes) backed as one mapping per `unit` bytes, each of which can be
|
||||
* unbacked alone later, with access granted once over the run: per granule, granting access
|
||||
* costs about as much as the map (41.9 us a granule backed singly, 24.6 as a run). All or
|
||||
* nothing: on failure nothing of the run stays backed. Null: VMem backs a granule at a time. */
|
||||
int (*vmem_commit_units)(void* addr, int64_t bytes, int64_t unit);
|
||||
|
||||
/* ---- device memory a decommit kept for the next commit of its size (counted as free in
|
||||
* props), given back to the driver: card `device`'s, or every card's for -1; the bytes. Null
|
||||
* on a backend that keeps none. */
|
||||
int64_t (*vmem_trim)(int device);
|
||||
/* rad_dev_peer_launch and rad_dev_cards_claim. Null on a backend that never launches a kernel
|
||||
* ahead of the one before it. */
|
||||
void (*peer_launch)(int on);
|
||||
int (*cards_claim)(const int* cards, int n, int on);
|
||||
/* ---- the hardware queues card `device` has open and how many of them no stream holds (a
|
||||
* closed stream's queue is kept for the card's next stream); and the kept ones destroyed
|
||||
* until `keep` are left, the number destroyed, none while any queue of the card holds a
|
||||
* packet. Null on a backend that keeps none. */
|
||||
void (*stream_counts)(int device, int* open, int* idle);
|
||||
int (*stream_trim)(int device, int keep);
|
||||
};
|
||||
|
||||
|
||||
@@ -399,6 +458,19 @@ std::string dev_dma_lane(int device);
|
||||
* tell. */
|
||||
int64_t dev_stuck_ms();
|
||||
|
||||
/* How long the device may be stuck (dev_stuck_ms) before the backend ends the process, in ms; 0
|
||||
* never. Set from `scheduler.stuck-exit` before serving; a backend that can tell reads it when a
|
||||
* stall is standing. A device that has advanced nothing for a minute is not coming back: the
|
||||
* reported hangs stood for hours, and a stall that clears does so within seconds. */
|
||||
extern std::atomic<int64_t> dev_stuck_exit_ms;
|
||||
|
||||
/* Whether at least one engine has finished bringup. The stuck-exit watchdog reads it: a stall
|
||||
* verdict standing DURING load is a slow load -- a cold start faulting a mapped tier from disk
|
||||
* advances none of the counters the verdict watches, and that is legitimate work, not a hang.
|
||||
* A watchdog that fires there turns one patient start into a supervisor's crash loop. Nothing
|
||||
* disarms: the phase the flag exempts is only the engine's first. */
|
||||
extern std::atomic<bool> dev_engine_ready;
|
||||
|
||||
/* Longest run of dispatches a played tape leaves unordered. Of any kTapeOverlapRun + 1
|
||||
* consecutive packets on a queue one carries the barrier bit, so a launched packet still proves
|
||||
* that everything more than that many packets earlier has completed. Argument slots and tape
|
||||
@@ -411,12 +483,44 @@ constexpr int kTapeOverlapRun = 6;
|
||||
* kernel plugin that calls hipMalloc directly; see the ledger in dispatch.cpp. */
|
||||
void rad_dev_alloc_totals(int kind, int64_t* bytes, int64_t* count);
|
||||
|
||||
/* `fn` is called after every device-memory free (RAD_MEM_DEVICE) with the range freed: a kernel
|
||||
* library's rad_plugin_freed (abi/rad_abi.h), registered by the plugin loader. Registrations are
|
||||
* counted: every registry that loads the library registers its hook, and rad_dev_off_free, which
|
||||
* the loader calls before it closes the library, takes one back. The hook goes with the last,
|
||||
* once no free is calling it: a library opened again can land at another address, and a hook
|
||||
* left behind would call into memory nothing maps. */
|
||||
void rad_dev_on_free(void (*fn)(const void* base, int64_t bytes));
|
||||
void rad_dev_off_free(void (*fn)(const void* base, int64_t bytes));
|
||||
|
||||
/* Event handles created and not yet destroyed, process-wide. */
|
||||
int64_t rad_dev_live_events(void);
|
||||
/* Calls to rad_event_sync and rad_stream_sync since process start, from any thread: the host
|
||||
* blocks the ABI makes. */
|
||||
int64_t rad_dev_host_blocks(void);
|
||||
|
||||
/* A parked allocation's contents (docs/MULTIMODEL.md §7): in pinned host memory, in a file of the
|
||||
* disk tier, or both. A copy written to disk can let its host memory go and be read back later. */
|
||||
struct HostCopy {
|
||||
void* host = nullptr; /* pinned, `bytes` rounded up to the direct-I/O block */
|
||||
int64_t bytes = 0;
|
||||
std::string file; /* the disk tier's copy, when written */
|
||||
bool on_disk = false; /* `file` holds exactly what `host` holds (or held) */
|
||||
|
||||
int64_t ram() const { return host ? bytes : 0; }
|
||||
/* Pinned memory for `n` bytes; what the copy held before, host memory and file, is freed. */
|
||||
int alloc(int64_t n);
|
||||
/* Writes the host bytes to a new file under `dir` (O_DIRECT). Between pieces it asks `gate`
|
||||
* (when given): 0 goes on, 1 waits (a model loading reads its container from the same drive),
|
||||
* -1 abandons the write (RAD_E_STATE, no file left). */
|
||||
int spill(const std::string& dir, const std::function<int()>& gate = {});
|
||||
/* Frees the host memory of a copy that is on disk. */
|
||||
void drop_host();
|
||||
/* Reads the file back into fresh pinned memory when the host copy is gone. */
|
||||
int load();
|
||||
/* Frees everything: the host memory and the file. */
|
||||
void release();
|
||||
};
|
||||
|
||||
/* ------------------------------------------------------------------ elastic memory
|
||||
* One reserved address range and which granules inside it are backed.
|
||||
*
|
||||
@@ -444,10 +548,15 @@ public:
|
||||
/* Movable, since owners live in vectors. The source is left empty so its destructor does not
|
||||
* unmap the range the destination now owns. */
|
||||
VMem(VMem&& o) noexcept
|
||||
: base_(o.base_), size_(o.size_), committed_(o.committed_), ext_(std::move(o.ext_)) {
|
||||
: base_(o.base_), size_(o.size_), committed_(o.committed_), ext_(std::move(o.ext_)),
|
||||
device_(o.device_), copy_(std::move(o.copy_)), parked_(std::move(o.parked_)),
|
||||
discarded_(o.discarded_) {
|
||||
rekey(&o, this);
|
||||
o.base_ = nullptr;
|
||||
o.size_ = o.committed_ = 0;
|
||||
o.ext_.clear();
|
||||
o.copy_ = HostCopy{};
|
||||
o.parked_.clear();
|
||||
}
|
||||
VMem& operator=(VMem&& o) noexcept {
|
||||
if (this != &o) {
|
||||
@@ -456,9 +565,16 @@ public:
|
||||
size_ = o.size_;
|
||||
committed_ = o.committed_;
|
||||
ext_ = std::move(o.ext_);
|
||||
device_ = o.device_;
|
||||
copy_ = std::move(o.copy_);
|
||||
parked_ = std::move(o.parked_);
|
||||
discarded_ = o.discarded_;
|
||||
rekey(&o, this);
|
||||
o.base_ = nullptr;
|
||||
o.size_ = o.committed_ = 0;
|
||||
o.ext_.clear();
|
||||
o.copy_ = HostCopy{};
|
||||
o.parked_.clear();
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
@@ -482,19 +598,236 @@ public:
|
||||
* kernel. */
|
||||
bool is_committed(int64_t off, int64_t bytes) const;
|
||||
|
||||
/* Parking (dev_page_out): every backed extent copied to pinned host memory on `s`, then
|
||||
* unbacked; the bytes held on the host, or an error. page_in backs the same extents again and
|
||||
* copies them back. With `discard` nothing in the range is kept (a cache with no live
|
||||
* sequence and its index reset): page_out copies nothing and returns 0, and page_in backs the
|
||||
* extents again without copying anything back. */
|
||||
int64_t page_out(RadStream s, bool discard = false);
|
||||
int page_in(RadStream s);
|
||||
bool parked() const { return !parked_.empty(); }
|
||||
int64_t parked_bytes() const {
|
||||
int64_t n = 0;
|
||||
for (const auto& e : parked_) n += e.second;
|
||||
return n;
|
||||
}
|
||||
/* The card the range was reserved on, for the copies' stream. */
|
||||
int device() const { return device_; }
|
||||
/* Host bytes held for the parked extents (zero once they live only on disk). */
|
||||
int64_t host_bytes() const { return parked_.empty() ? 0 : copy_.ram(); }
|
||||
/* The disk tier (dev_page_spill): write the parked copy out, or let its host memory go. */
|
||||
int spill(const std::string& dir, const std::function<int()>& gate = {}) {
|
||||
return parked_.empty() ? RAD_OK : copy_.spill(dir, gate);
|
||||
}
|
||||
int64_t drop_host() {
|
||||
if (parked_.empty() || !copy_.on_disk || !copy_.host) return 0;
|
||||
const int64_t n = copy_.bytes;
|
||||
copy_.drop_host();
|
||||
return n;
|
||||
}
|
||||
|
||||
private:
|
||||
/* The owner registry follows the object when it moves (reserve() files it under the thread's
|
||||
* engine owner). */
|
||||
static void rekey(VMem* from, VMem* to);
|
||||
void* base_ = nullptr;
|
||||
int64_t size_ = 0;
|
||||
int64_t committed_ = 0;
|
||||
/* Backed extents (offset, bytes): sorted, disjoint and never adjacent, since a touching
|
||||
* commit merges. Length tracks live regions, not calls. */
|
||||
std::vector<std::pair<int64_t, int64_t>> ext_;
|
||||
int device_ = 0;
|
||||
HostCopy copy_; /* parked: the extents' contents */
|
||||
std::vector<std::pair<int64_t, int64_t>> parked_; /* parked: the extents to back again */
|
||||
bool discarded_ = false; /* parked without a copy */
|
||||
|
||||
/* Adds a newly mapped piece and merges it with whatever it touches. */
|
||||
void add_extent(int64_t off, int64_t bytes);
|
||||
void drop_extent(int64_t off, int64_t bytes);
|
||||
};
|
||||
|
||||
/* ------------------------------------------------------------------ parking (paging.cpp)
|
||||
* docs/MULTIMODEL.md §7. A device allocation of 2 MiB or more made on a thread working for an
|
||||
* engine (engine_owner, rad_internal.h) is reserved as one address range and mapped in chunks, and
|
||||
* an elastic range reserved on such a thread is filed under the engine too, so the engine's memory
|
||||
* can leave the card in part or whole and come back at the same addresses.
|
||||
*
|
||||
* A chunk out of the card is somewhere else: in pinned host memory, in a file of the disk tier,
|
||||
* both, or nowhere when it was discarded (its contents not needed: an expert slab's free slots).
|
||||
* Restoring maps every chunk out and copies back the ones that had a copy. The engine must be
|
||||
* quiet for both: nothing it issued still runs, nothing new is issued until the page-in. */
|
||||
constexpr int64_t kPageMin = (int64_t)2 << 20;
|
||||
/* For rad_dev_alloc and rad_dev_free: an engine's pageable allocation, and its release (false when
|
||||
* `p` is not one). */
|
||||
void* page_alloc(int64_t bytes, int owner, int device);
|
||||
bool page_free(void* p);
|
||||
/* Device bytes `owner` holds on card `device`: its allocations and elastic backing (a load in
|
||||
* flight, for the fleet's reservation). */
|
||||
int64_t dev_owner_bytes(int owner, int device);
|
||||
/* The backend rad_dev_* calls go to. */
|
||||
const DeviceBackend* active_backend();
|
||||
/* The owner's elastic ranges (dispatch.cpp's registry). */
|
||||
std::vector<VMem*> vmems_of(int owner);
|
||||
|
||||
struct PageOut {
|
||||
/* Bytes to take off each card; empty takes everything. */
|
||||
std::map<int, int64_t> want;
|
||||
/* New host memory the copies may take; past it they go to `dir`, and without a `dir` the
|
||||
* page-out stops there. */
|
||||
int64_t host_budget = INT64_MAX;
|
||||
std::string dir;
|
||||
/* The elastic ranges (the KV cache) are dropped, not copied. */
|
||||
bool discard_elastic = false;
|
||||
};
|
||||
struct PageResult {
|
||||
std::map<int, int64_t> freed; /* bytes unmapped on each card */
|
||||
int64_t host = 0; /* host bytes the copies took */
|
||||
int64_t disk = 0; /* bytes written straight to the disk tier */
|
||||
int64_t dropped = 0; /* bytes unmapped with nothing kept (discarded) */
|
||||
int64_t reused = 0; /* bytes unmapped against a copy made earlier */
|
||||
int64_t file = 0; /* bytes unmapped against the container they were loaded from */
|
||||
double quiet_s = 0; /* the engine coming to rest (responses drained, loop held) */
|
||||
double slab_s = 0; /* lent slots recalled and the expert slab emptied */
|
||||
double out_s = 0; /* the page-out itself */
|
||||
};
|
||||
int dev_page_out(int owner, const PageOut& req, PageResult* out);
|
||||
/* A stretch of memory a page-in mapped for its owner to fill (dev_page_refilled). */
|
||||
struct PageSpan { char* p; int64_t bytes; int device; };
|
||||
/* Every chunk of the owner that is out comes back. Those of an allocation the owner refills are
|
||||
* only mapped, and appended to `refill` for the owner to fill before anything reads them; a
|
||||
* page-in with such chunks out and no `refill` fails (RAD_E_STATE) and maps nothing. */
|
||||
int dev_page_in(int owner, std::vector<PageSpan>* refill = nullptr, bool elastic = true);
|
||||
/* The owner's elastic ranges backed again (and their copies, if they were kept), what a page-in
|
||||
* does last; then the cards' translations settled. A page-in with `elastic` false leaves this to
|
||||
* the caller, which can run it beside the refill: nothing of the refill reads those ranges, and
|
||||
* an image model's KV cache is ten thousand commits (0.5 s). */
|
||||
int dev_page_in_elastic(int owner);
|
||||
/* The owner's chunks wholly inside these ranges hold nothing that needs keeping: the next page-out
|
||||
* unmaps them first and copies nothing (an expert slab's slots after it dropped its units). */
|
||||
void dev_page_discard(int owner, const std::vector<std::pair<const void*, int64_t>>& ranges);
|
||||
/* Bytes mapped on cards, and bytes of host copies (parked or kept). */
|
||||
void dev_page_stats(int owner, int64_t* device, int64_t* host);
|
||||
/* Bytes of the owner's pageable memory still on each card. */
|
||||
std::map<int, int64_t> dev_page_mapped_bytes(int owner);
|
||||
/* Bytes the owner has out of the card right now, by card. With `live`, only what dev_page_in_live
|
||||
* would map: the sealed chunks parked in host memory stay out of the sum, read in place. */
|
||||
std::map<int, int64_t> dev_page_out_bytes(int owner, bool live = false);
|
||||
/* [off, off + bytes) of the pageable allocation `p` (all of it for bytes < 0) is never written after
|
||||
* the load (a static plan's weights pool, a tiered one's statics): a copy, once made, is kept after
|
||||
* the page-in, and later page-outs of those chunks only unmap. */
|
||||
void dev_page_seal(void* p, int64_t off = 0, int64_t bytes = -1);
|
||||
/* The pageable allocation `p` is rebuilt by its owner from its source (a weights pool from its
|
||||
* container) after a page-in: its sealed chunks leave the card with no copy at all, an unmap, and
|
||||
* dev_page_in hands them back to be filled. Its chunks are no longer checked against the
|
||||
* container (dev_page_source). */
|
||||
void dev_page_refilled(void* p);
|
||||
/* [p, p + bytes) is being written (an expert moved into a slab slot): the kept copies of the
|
||||
* chunks it touches are stale. A no-op for memory that is not pageable. Called when the write is
|
||||
* issued and again when it lands, so a copy made across it is never taken as exact. */
|
||||
void dev_page_invalidate(const void* p, int64_t bytes);
|
||||
/* Memory mapped again at an address that was mapped before (a page-in, a pool growing back) is not
|
||||
* written until the cards' translation caches have been flushed in full: a map flushes them only
|
||||
* lightly, and copies into such memory can land nowhere, so the memory reads back its previous
|
||||
* owner's bytes or zeros (Linux 7.1 with gfx1201; tests/device_test.cpp
|
||||
* two_allocations_of_one_owner_come_back_exact_from_the_disk_tier). Unpinning host memory makes
|
||||
* the driver flush every card it was mapped on in full, so this pins one page and unpins it.
|
||||
* Called after a batch of maps, before anything writes them. */
|
||||
/* Where address `a` lies among the elastic reservations and pageable allocations, for a fault report:
|
||||
* its owner, card, offset, whether it is backed and what its paging chunk holds. Empty when it is in
|
||||
* none. Takes no lock it would wait for, since a fault can arrive while one is held. */
|
||||
std::string dev_fault_where(const void* a);
|
||||
|
||||
int dev_settle_maps();
|
||||
|
||||
/* VMem::commit on this thread leaves its flush (dev_settle_maps) for the end of this scope, so a
|
||||
* run of ranges mapped together flushes once. Nothing may write the new ranges before end(), which
|
||||
* reports the flush's result; the destructor ends a batch left open by an early return. */
|
||||
class MapBatch {
|
||||
public:
|
||||
MapBatch();
|
||||
~MapBatch();
|
||||
MapBatch(const MapBatch&) = delete;
|
||||
MapBatch& operator=(const MapBatch&) = delete;
|
||||
int end();
|
||||
private:
|
||||
bool ended_ = false;
|
||||
};
|
||||
/* The backend's kept device memory on card `device` (-1: every card) back to the driver, the
|
||||
* bytes; its pages come free as the driver wipes them (~95 GB/s). For a caller about to allocate
|
||||
* outside the elastic calls, or done with the swap that would have reused it. */
|
||||
int64_t dev_vmem_trim(int device);
|
||||
/* The hardware queues card `device` has open, and how many of them are kept for its next streams
|
||||
* (0 and 0 on a backend that keeps none). */
|
||||
void dev_stream_counts(int device, int* open, int* idle);
|
||||
/* Card `device`'s kept queues destroyed until `keep` are left: the number destroyed, about 41 MiB
|
||||
* of the card each. Nothing is destroyed while any queue of the card holds a packet, and the
|
||||
* caller sees to it that nothing is launched on the card during the call: destroying a queue
|
||||
* beside a busy one can reset the card. */
|
||||
int dev_stream_trim(int device, int keep);
|
||||
/* The device this thread last selected with rad_dev_set. */
|
||||
int dev_current();
|
||||
/* The container at `path`, by an id for dev_page_source (the same path gives the same id). */
|
||||
int dev_page_file(const char* path);
|
||||
/* The load copied container `file`'s rows [0, ny) of wb bytes at foff + y * sp verbatim onto
|
||||
* [dst, dst + ny * wb). A chunk of pageable memory filled this way can go out against the container
|
||||
* instead of a copy: a page-out (or backup) reads the device bytes back, compares them with the
|
||||
* container (zero where nothing was loaded) and writes nothing when they match; the page-in reads
|
||||
* the container. A chunk written since (dev_page_invalidate) is copied as any other. A no-op for
|
||||
* memory that is not pageable. */
|
||||
void dev_page_source(const void* dst, int file, int64_t foff, int64_t wb, int64_t ny, int64_t sp);
|
||||
/* Bytes of the owner's mapped chunks a page-out would have to copy (no discard, no kept copy,
|
||||
* not loaded verbatim from a container, not refilled by the owner). */
|
||||
int64_t dev_page_uncopied(int owner);
|
||||
/* A restore that serves at once: like dev_page_in, but a sealed chunk parked in host memory stays
|
||||
* there, read in place over the link, until dev_page_promote moves it; *left is how much. */
|
||||
int dev_page_in_live(int owner, int64_t* left, std::vector<PageSpan>* refill = nullptr,
|
||||
bool elastic = true);
|
||||
/* dev_page_in (`left` null) or dev_page_in_live in two halves, for an owner that refills: the begin
|
||||
* maps every chunk, hands back those to refill and starts the copies of the chunks held in host
|
||||
* memory; the end waits for those copies and swaps their memory in, and must follow every begin
|
||||
* that succeeded. The refill runs between the two, beside the copies: it writes none of those
|
||||
* chunks. Elastic ranges are left to dev_page_in_elastic. */
|
||||
int dev_page_in_begin(int owner, int64_t* left, std::vector<PageSpan>* refill);
|
||||
int dev_page_in_end(int owner);
|
||||
/* Between the two halves: waits for the clears the begin issued on recycled refill chunks, which
|
||||
* it does not wait for itself. The refill calls it before its first write into them; the end
|
||||
* waits for them too. The calling thread's current device is kept. */
|
||||
int dev_page_in_cleared(int owner);
|
||||
/* Moves up to `max_bytes` of the chunks dev_page_in_live left in host memory onto their cards,
|
||||
* while the engine serves: each is copied to device memory first, then `quiet` runs the swap of
|
||||
* mappings with nothing of the engine in flight (Engine::run_quiet). Returns the bytes moved, 0
|
||||
* when none is left, or an error (no device memory for them: the rest stays in host memory). */
|
||||
int64_t dev_page_promote(int owner, int64_t max_bytes,
|
||||
const std::function<int(const std::function<int()>&)>& quiet);
|
||||
/* Bytes of `owner`'s chunks served from host memory in place, on `device` (-1: all). */
|
||||
int64_t dev_page_live_bytes(int owner, int device = -1);
|
||||
/* Host memory all parked and kept copies hold (they are host-backed mappings, not pinned
|
||||
* allocations, so rad_dev_alloc_totals does not count them). */
|
||||
int64_t dev_page_host_bytes();
|
||||
/* Frees host copies of mapped sealed chunks (a file copy stays). The host bytes freed. */
|
||||
int64_t dev_page_drop_copies(int owner);
|
||||
/* Writes every host copy without a file copy to the disk tier; `gate` as HostCopy::spill. */
|
||||
int64_t dev_page_spill(int owner, const std::string& dir, const std::function<int()>& gate = {});
|
||||
/* Frees host copies that have a file copy. The host bytes freed. */
|
||||
int64_t dev_page_drop_host(int owner);
|
||||
/* A parked owner's chunks whose only copy is the disk tier or its container: their bytes. */
|
||||
int64_t dev_page_fillable(int owner);
|
||||
/* The owner's parked chunks of allocations it refills that have no host memory yet, one span a
|
||||
* chunk, in address order. */
|
||||
std::vector<PageSpan> dev_page_refill_chunks(int owner);
|
||||
/* A host fill by the owner (Engine::fill_host): host memory mapped at each of these chunks (from
|
||||
* dev_page_refill_chunks), as a park to host memory leaves a chunk, for the owner to fill from its
|
||||
* source; then dev_page_fill_end: `filled`, the chunks' host copies are theirs and the next restore
|
||||
* copies them over the link (exact until written, so a later park keeps them); otherwise the host
|
||||
* memory goes again and the chunks stay to be refilled. */
|
||||
int dev_page_fill_begin(int owner, const std::vector<PageSpan>& chunks);
|
||||
void dev_page_fill_end(int owner, const std::vector<PageSpan>& chunks, bool filled);
|
||||
/* Up to max_bytes of those read into host memory and mapped at their own addresses, as a park to
|
||||
* host memory leaves them, so the next restore copies over the link instead of reading the drive
|
||||
* (and a live restore serves from them in place). The owner must be parked and idle. Returns the
|
||||
* bytes filled, or a negative status. */
|
||||
int64_t dev_page_fill_host(int owner, int64_t max_bytes);
|
||||
|
||||
/* Bytes backed by every VMem in the process, for Engine::start's receipt. VMem commits bypass the
|
||||
* rad_dev_alloc ledger, so without this the engine's accounting would miss the elastic pools. */
|
||||
int64_t rad_dev_vmem_committed(void);
|
||||
|
||||
+431
-46
@@ -7,6 +7,7 @@
|
||||
* with ROCm headers and no /dev/kfd); the chosen backend is logged at Info.
|
||||
*/
|
||||
#include "device.h"
|
||||
#include "directio.h"
|
||||
#include "../rad_internal.h"
|
||||
#if defined(RAD_HAVE_SYCL) && RAD_HAVE_SYCL
|
||||
#include "sycl_host.h"
|
||||
@@ -21,10 +22,18 @@
|
||||
#include <iterator>
|
||||
#include <map>
|
||||
#include <mutex>
|
||||
#include <shared_mutex>
|
||||
#include <unordered_map>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
#include <thread>
|
||||
#include <chrono>
|
||||
#include <cstdint>
|
||||
#include <unistd.h>
|
||||
|
||||
/* The device rad_dev_set last bound on this thread. */
|
||||
static thread_local int t_device = 0;
|
||||
|
||||
namespace rad {
|
||||
|
||||
@@ -176,24 +185,43 @@ Ledger g_ledger[4]; /* indexed by RAD_MEM_*; rad_dev_alloc bounds the kin
|
||||
/* Each live allocation's size, so rad_dev_free (which has none) takes it back off the ledger's
|
||||
* bytes: pinned ranges are freed and taken again during bring-up, and the pin-cap check reads the
|
||||
* ledger as what the process holds. Allocations are rare, never per step. */
|
||||
struct LiveAlloc { int64_t bytes; int kind; };
|
||||
struct LiveAlloc { int64_t bytes; int kind; int owner; int device; };
|
||||
/* Device bytes each engine holds on each card (dev_owner_bytes): its rad_dev_alloc allocations and
|
||||
* its elastic ranges' backing. */
|
||||
std::mutex g_owner_mu;
|
||||
std::map<std::pair<int, int>, int64_t> g_owner_bytes;
|
||||
void owner_add(int owner, int device, int64_t n) {
|
||||
if (owner <= 0 || n == 0) return;
|
||||
std::lock_guard<std::mutex> lk(g_owner_mu);
|
||||
g_owner_bytes[{ owner, device }] += n;
|
||||
}
|
||||
std::mutex g_ledger_mu;
|
||||
std::unordered_map<void*, LiveAlloc> g_ledger_live;
|
||||
|
||||
void ledger_add(void* p, int64_t bytes, int kind) {
|
||||
void ledger_add(void* p, int64_t bytes, int kind, int owner, int device) {
|
||||
g_ledger[kind].bytes.fetch_add(bytes, std::memory_order_relaxed);
|
||||
if (kind == RAD_MEM_DEVICE) owner_add(owner, device, bytes);
|
||||
std::lock_guard<std::mutex> lk(g_ledger_mu);
|
||||
g_ledger_live[p] = LiveAlloc{ bytes, kind };
|
||||
g_ledger_live[p] = LiveAlloc{ bytes, kind, owner, device };
|
||||
}
|
||||
void ledger_drop(void* p) {
|
||||
if (!p) return;
|
||||
/* The allocation's bytes, or 0 when the ledger does not know it. */
|
||||
int64_t ledger_drop(void* p) {
|
||||
if (!p) return 0;
|
||||
std::lock_guard<std::mutex> lk(g_ledger_mu);
|
||||
const auto it = g_ledger_live.find(p);
|
||||
if (it == g_ledger_live.end()) return;
|
||||
g_ledger[it->second.kind].bytes.fetch_sub(it->second.bytes, std::memory_order_relaxed);
|
||||
if (it == g_ledger_live.end()) return 0;
|
||||
const int64_t bytes = it->second.bytes;
|
||||
g_ledger[it->second.kind].bytes.fetch_sub(bytes, std::memory_order_relaxed);
|
||||
if (it->second.kind == RAD_MEM_DEVICE) owner_add(it->second.owner, it->second.device, -bytes);
|
||||
g_ledger_live.erase(it);
|
||||
return bytes;
|
||||
}
|
||||
|
||||
/* rad_dev_on_free's hooks and how many registrations each has. Registered at plugin load and
|
||||
* read on every device free, which holds the lock shared while it calls them. */
|
||||
std::shared_mutex g_free_hooks_mu;
|
||||
std::vector<std::pair<void (*)(const void*, int64_t), int>> g_free_hooks;
|
||||
|
||||
/* Live event handles, counted here so the number is backend-independent; the only place an
|
||||
* event leaked at teardown shows. */
|
||||
std::atomic<int64_t> g_live_events{0};
|
||||
@@ -253,6 +281,24 @@ const char* kind_name(int kind) {
|
||||
|
||||
} /* namespace */
|
||||
|
||||
void rad_dev_on_free(void (*fn)(const void* base, int64_t bytes)) {
|
||||
if (!fn) return;
|
||||
std::unique_lock<std::shared_mutex> lk(g_free_hooks_mu);
|
||||
for (auto& h : g_free_hooks)
|
||||
if (h.first == fn) { ++h.second; return; }
|
||||
g_free_hooks.push_back({ fn, 1 });
|
||||
}
|
||||
|
||||
void rad_dev_off_free(void (*fn)(const void* base, int64_t bytes)) {
|
||||
if (!fn) return;
|
||||
std::unique_lock<std::shared_mutex> lk(g_free_hooks_mu);
|
||||
for (auto it = g_free_hooks.begin(); it != g_free_hooks.end(); ++it)
|
||||
if (it->first == fn) {
|
||||
if (--it->second == 0) g_free_hooks.erase(it);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
void rad_dev_alloc_totals(int kind, int64_t* bytes, int64_t* count) {
|
||||
if (kind < 0 || kind >= (int)std::size(g_ledger)) {
|
||||
if (bytes) *bytes = 0;
|
||||
@@ -272,8 +318,19 @@ int64_t rad_dev_host_blocks(void) { return g_host_blocks.load(std::memory_order_
|
||||
|
||||
namespace {
|
||||
std::atomic<int64_t> g_vmem_committed{0};
|
||||
|
||||
/* Elastic ranges (VMem) reserved on a thread working for an engine are filed under it, so its
|
||||
* park (paging.cpp) finds them. */
|
||||
std::mutex g_page_mu;
|
||||
std::map<VMem*, int> g_vmem_owner;
|
||||
} /* namespace */
|
||||
|
||||
static int vmem_owner_of(const VMem* v) {
|
||||
std::lock_guard<std::mutex> lk(g_page_mu);
|
||||
auto it = g_vmem_owner.find(const_cast<VMem*>(v));
|
||||
return it == g_vmem_owner.end() ? 0 : it->second;
|
||||
}
|
||||
|
||||
int64_t rad_dev_vmem_committed(void) { return g_vmem_committed.load(std::memory_order_relaxed); }
|
||||
|
||||
/* Both checks: a backend may have the entries on a driver with no virtual memory manager
|
||||
@@ -303,18 +360,34 @@ int VMem::reserve(int64_t bytes, int64_t align) {
|
||||
size_ = want;
|
||||
committed_ = 0;
|
||||
ext_.clear();
|
||||
device_ = t_device;
|
||||
if (const int owner = engine_owner(); owner > 0) {
|
||||
std::lock_guard<std::mutex> lk(g_page_mu);
|
||||
g_vmem_owner[this] = owner;
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
void VMem::rekey(VMem* from, VMem* to) {
|
||||
std::lock_guard<std::mutex> lk(g_page_mu);
|
||||
auto it = g_vmem_owner.find(from);
|
||||
if (it == g_vmem_owner.end()) return;
|
||||
const int owner = it->second;
|
||||
g_vmem_owner.erase(it);
|
||||
if (to) g_vmem_owner[to] = owner;
|
||||
}
|
||||
|
||||
void VMem::release() {
|
||||
owner_add(vmem_owner_of(this), device_, -committed_);
|
||||
rekey(this, nullptr);
|
||||
copy_.release();
|
||||
parked_.clear();
|
||||
if (!base_) { size_ = 0; committed_ = 0; ext_.clear(); return; }
|
||||
/* Decommit before release: releasing a range with pages still mapped leaks them, and some
|
||||
* drivers refuse the free. One granule at a time, as each was mapped. */
|
||||
const int64_t g = granularity();
|
||||
* drivers refuse the free. An extent is a run of whole mappings (one a granule), so it goes in
|
||||
* one unmap. */
|
||||
for (const auto& e : ext_) {
|
||||
if (dev()->vmem_decommit && g > 0)
|
||||
for (int64_t o = e.first; o < e.first + e.second; o += g)
|
||||
(void)dev()->vmem_decommit((char*)base_ + o, g);
|
||||
if (dev()->vmem_decommit) (void)dev()->vmem_decommit((char*)base_ + e.first, e.second);
|
||||
g_vmem_committed.fetch_sub(e.second, std::memory_order_relaxed);
|
||||
}
|
||||
if (dev()->vmem_release) dev()->vmem_release(base_, size_);
|
||||
@@ -340,6 +413,23 @@ bool VMem::is_committed(int64_t off, int64_t bytes) const {
|
||||
* - Access cannot be granted per granule: a granule adjacent to an accessible one is refused on
|
||||
* its own. Access is granted once per merged extent the new granules belong to; re-granting
|
||||
* access to a range is free. */
|
||||
namespace {
|
||||
thread_local int t_map_batch = 0;
|
||||
thread_local bool t_map_due = false;
|
||||
}
|
||||
|
||||
MapBatch::MapBatch() { ++t_map_batch; }
|
||||
|
||||
MapBatch::~MapBatch() { (void)end(); }
|
||||
|
||||
int MapBatch::end() {
|
||||
if (ended_) return RAD_OK;
|
||||
ended_ = true;
|
||||
if (--t_map_batch > 0 || !t_map_due) return RAD_OK;
|
||||
t_map_due = false;
|
||||
return dev_settle_maps();
|
||||
}
|
||||
|
||||
int VMem::commit(int64_t off, int64_t bytes) {
|
||||
if (!base_ || bytes <= 0) return bytes <= 0 ? RAD_OK : RAD_E_INVAL;
|
||||
const int64_t g = granularity();
|
||||
@@ -357,13 +447,27 @@ int VMem::commit(int64_t off, int64_t bytes) {
|
||||
if (want.empty()) return RAD_OK;
|
||||
|
||||
/* On a failure part way, what already mapped stays mapped and recorded: a partial grow is
|
||||
* usable, untracked mappings are not. */
|
||||
* usable, untracked mappings are not. A contiguous run goes in one call; one that fails (the
|
||||
* card lacks room for all of it) is backed a granule at a time, so it grows by what fits.
|
||||
* `took`: the granules of `want` backed, a prefix of it. */
|
||||
int rc = RAD_OK;
|
||||
size_t took = 0;
|
||||
for (; took < want.size(); ++took) {
|
||||
rc = dev()->vmem_commit((char*)base_ + want[took], g);
|
||||
if (rc < 0) break;
|
||||
add_extent(want[took], g);
|
||||
while (took < want.size() && rc >= 0) {
|
||||
size_t j = took + 1;
|
||||
while (j < want.size() && want[j] == want[j - 1] + g) ++j;
|
||||
const int64_t run = (int64_t)(j - took) * g;
|
||||
if (j - took > 1 && dev()->vmem_commit_units &&
|
||||
dev()->vmem_commit_units((char*)base_ + want[took], run, g) >= 0) {
|
||||
add_extent(want[took], run);
|
||||
took = j;
|
||||
continue;
|
||||
}
|
||||
for (; took < j; ++took) {
|
||||
rc = dev()->vmem_commit((char*)base_ + want[took], g);
|
||||
if (rc < 0) break;
|
||||
rc = RAD_OK; /* recycled memory (1) is fine here: a pool's contents are written before they are read */
|
||||
add_extent(want[took], g);
|
||||
}
|
||||
}
|
||||
|
||||
/* Grant access even if the grow stopped short, so the granules that did map are usable. */
|
||||
@@ -384,6 +488,10 @@ int VMem::commit(int64_t off, int64_t bytes) {
|
||||
}
|
||||
return prc;
|
||||
}
|
||||
if (took > 0) {
|
||||
if (t_map_batch > 0) t_map_due = true;
|
||||
else if (const int src = dev_settle_maps(); src < 0) return src;
|
||||
}
|
||||
return rc;
|
||||
}
|
||||
|
||||
@@ -397,20 +505,30 @@ int VMem::decommit(int64_t off, int64_t bytes) {
|
||||
if (hi > size_) hi = size_;
|
||||
if (lo >= hi) return RAD_OK;
|
||||
|
||||
/* Gathered first and unmapped per granule, as in commit. */
|
||||
/* Gathered first; each contiguous run of granules (a mapping each) goes in one unmap. */
|
||||
std::vector<int64_t> drop;
|
||||
for (int64_t o = lo; o < hi; o += g)
|
||||
if (is_committed(o, g)) drop.push_back(o);
|
||||
|
||||
for (const int64_t o : drop) {
|
||||
const int rc = dev()->vmem_decommit((char*)base_ + o, g);
|
||||
if (rc < 0) return rc;
|
||||
drop_extent(o, g);
|
||||
for (size_t i = 0; i < drop.size();) {
|
||||
size_t j = i + 1;
|
||||
while (j < drop.size() && drop[j] == drop[j - 1] + g) ++j;
|
||||
const int64_t run = (int64_t)(j - i) * g;
|
||||
if (const int rc = dev()->vmem_decommit((char*)base_ + drop[i], run); rc < 0) return rc;
|
||||
drop_extent(drop[i], run);
|
||||
i = j;
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int64_t dev_owner_bytes(int owner, int device) {
|
||||
std::lock_guard<std::mutex> lk(g_owner_mu);
|
||||
auto it = g_owner_bytes.find({ owner, device });
|
||||
return it == g_owner_bytes.end() ? 0 : it->second;
|
||||
}
|
||||
|
||||
void VMem::add_extent(int64_t off, int64_t bytes) {
|
||||
owner_add(vmem_owner_of(this), device_, bytes);
|
||||
committed_ += bytes;
|
||||
g_vmem_committed.fetch_add(bytes, std::memory_order_relaxed);
|
||||
/* Insert in order, then merge touching neighbours, so is_committed() stays a short scan
|
||||
@@ -430,9 +548,215 @@ void VMem::add_extent(int64_t off, int64_t bytes) {
|
||||
}
|
||||
}
|
||||
|
||||
int64_t VMem::page_out(RadStream s, bool discard) {
|
||||
if (!base_ || ext_.empty() || !parked_.empty()) return 0;
|
||||
int64_t total = 0;
|
||||
for (const auto& e : ext_) total += e.second;
|
||||
if (discard) {
|
||||
/* Nothing in the range is kept: back it again on page_in with whatever the pages hold. */
|
||||
parked_ = ext_;
|
||||
discarded_ = true;
|
||||
for (const auto& e : parked_)
|
||||
if (const int rc = decommit(e.first, e.second); rc < 0) return rc;
|
||||
return 0;
|
||||
}
|
||||
discarded_ = false;
|
||||
if (const int rc = copy_.alloc(total); rc < 0) return rc;
|
||||
int64_t at = 0;
|
||||
for (const auto& e : ext_) {
|
||||
if (const int rc = rad_memcpy_async((char*)copy_.host + at, (char*)base_ + e.first, e.second, s); rc < 0)
|
||||
return rc;
|
||||
at += e.second;
|
||||
}
|
||||
if (const int rc = rad_stream_sync(s); rc < 0) return rc;
|
||||
parked_ = ext_;
|
||||
for (const auto& e : parked_)
|
||||
if (const int rc = decommit(e.first, e.second); rc < 0) return rc;
|
||||
return total;
|
||||
}
|
||||
|
||||
int dev_current() { return t_device; }
|
||||
|
||||
int64_t dev_vmem_trim(int device) {
|
||||
return dev()->vmem_trim ? dev()->vmem_trim(device) : 0;
|
||||
}
|
||||
|
||||
void dev_stream_counts(int device, int* open, int* idle) {
|
||||
if (open) *open = 0;
|
||||
if (idle) *idle = 0;
|
||||
if (dev()->stream_counts) dev()->stream_counts(device, open, idle);
|
||||
}
|
||||
|
||||
int dev_stream_trim(int device, int keep) {
|
||||
return dev()->stream_trim ? dev()->stream_trim(device, keep) : 0;
|
||||
}
|
||||
|
||||
std::string dev_page_where(uintptr_t a);
|
||||
|
||||
std::string dev_fault_where(const void* p) {
|
||||
const uintptr_t a = (uintptr_t)p;
|
||||
std::string s = dev_page_where(a);
|
||||
std::unique_lock<std::mutex> lk(g_page_mu, std::try_to_lock);
|
||||
if (!lk.owns_lock()) return s;
|
||||
for (const auto& [v, owner] : g_vmem_owner) {
|
||||
const uintptr_t b = (uintptr_t)v->base();
|
||||
if (!b || a < b || a >= b + (uintptr_t)v->size()) continue;
|
||||
const int64_t off = (int64_t)(a - b), g = std::max<int64_t>(VMem::granularity(), 1);
|
||||
return (s.empty() ? s : s + "; ") + fmt("elastic reservation of owner %d card %d, %s long, %s backed, +%s %s", owner, v->device(),
|
||||
humanb(v->size()).c_str(), humanb(v->committed()).c_str(), humanb(off).c_str(),
|
||||
v->is_committed(off / g * g, g) ? "is backed" : "is NOT backed");
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
int dev_settle_maps() {
|
||||
if (device_is_host()) return RAD_OK;
|
||||
void* x = dev()->alloc(4096, RAD_MEM_HOST_PINNED);
|
||||
if (!x) {
|
||||
device_set_error("vmem: no page of pinned host memory to flush the cards' translations with");
|
||||
return RAD_E_NOMEM;
|
||||
}
|
||||
dev()->free(x, RAD_MEM_HOST_PINNED);
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int VMem::page_in(RadStream s) {
|
||||
if (parked_.empty()) return RAD_OK;
|
||||
MapBatch maps;
|
||||
if (discarded_) {
|
||||
for (const auto& e : parked_)
|
||||
if (const int rc = commit(e.first, e.second); rc < 0) return rc;
|
||||
if (const int rc = maps.end(); rc < 0) return rc;
|
||||
parked_.clear();
|
||||
discarded_ = false;
|
||||
return RAD_OK;
|
||||
}
|
||||
if (const int rc = copy_.load(); rc < 0) return rc;
|
||||
for (const auto& e : parked_)
|
||||
if (const int rc = commit(e.first, e.second); rc < 0) return rc;
|
||||
if (const int rc = maps.end(); rc < 0) return rc;
|
||||
int64_t at = 0;
|
||||
for (const auto& e : parked_) {
|
||||
if (const int rc = rad_memcpy_async((char*)base_ + e.first, (char*)copy_.host + at, e.second, s); rc < 0)
|
||||
return rc;
|
||||
at += e.second;
|
||||
}
|
||||
if (const int rc = rad_stream_sync(s); rc < 0) return rc;
|
||||
parked_.clear();
|
||||
copy_.release();
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ---- HostCopy */
|
||||
|
||||
namespace {
|
||||
std::atomic<uint64_t> g_copy_seq{0};
|
||||
/* The unit of a copy's file I/O: what one write asks the gate about, what one reader takes. */
|
||||
constexpr int64_t kCopyPiece = (int64_t)64 << 20;
|
||||
}
|
||||
|
||||
int HostCopy::alloc(int64_t n) {
|
||||
release();
|
||||
bytes = n;
|
||||
host = rad_dev_alloc(align_up(n, DirectFile::alignment()), RAD_MEM_HOST_PINNED);
|
||||
if (!host) {
|
||||
device_set_error("parking: no pinned host memory for %s", humanb(n).c_str());
|
||||
return RAD_E_NOMEM;
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int HostCopy::spill(const std::string& dir, const std::function<int()>& gate) {
|
||||
if (on_disk || !host || bytes <= 0) return RAD_OK;
|
||||
/* Not the page files' name: their counter is another one (paging.cpp). */
|
||||
const std::string path = dir + "/radiance-vmem-" + std::to_string((long long)getpid()) + "-" +
|
||||
std::to_string((unsigned long long)g_copy_seq.fetch_add(1)) + ".bin";
|
||||
DirectFile f;
|
||||
if (const int rc = f.open(path.c_str(), RAD_DIO_WRITE | RAD_DIO_CREATE | RAD_DIO_TRUNC); rc < 0)
|
||||
return rc;
|
||||
const int64_t n = align_up(bytes, DirectFile::alignment());
|
||||
int rc = RAD_OK;
|
||||
for (int64_t at = 0; at < n; at += kCopyPiece) {
|
||||
int g = gate ? gate() : 0;
|
||||
while (g == 1) {
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(20));
|
||||
g = gate();
|
||||
}
|
||||
if (g < 0) { rc = RAD_E_STATE; break; }
|
||||
if ((rc = f.write_at((const char*)host + at, at, std::min(kCopyPiece, n - at))) < 0) break;
|
||||
}
|
||||
f.close();
|
||||
if (rc < 0) {
|
||||
::unlink(path.c_str());
|
||||
return rc;
|
||||
}
|
||||
file = path;
|
||||
on_disk = true;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
void HostCopy::drop_host() {
|
||||
if (!on_disk || !host) return;
|
||||
rad_dev_free(host, RAD_MEM_HOST_PINNED);
|
||||
host = nullptr;
|
||||
}
|
||||
|
||||
int HostCopy::load() {
|
||||
if (host) return RAD_OK;
|
||||
if (!on_disk) {
|
||||
device_set_error("parking: a copy has neither host memory nor a file");
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
const int64_t n = align_up(bytes, DirectFile::alignment());
|
||||
host = rad_dev_alloc(n, RAD_MEM_HOST_PINNED);
|
||||
if (!host) {
|
||||
device_set_error("parking: no pinned host memory to read %s back", humanb(bytes).c_str());
|
||||
return RAD_E_NOMEM;
|
||||
}
|
||||
/* A read that fails leaves no host memory behind, so the next load() reads again instead of
|
||||
* taking a partial copy as the copy. */
|
||||
auto fail = [&](int rc) {
|
||||
rad_dev_free(host, RAD_MEM_HOST_PINNED);
|
||||
host = nullptr;
|
||||
return rc;
|
||||
};
|
||||
DirectFile f;
|
||||
if (const int rc = f.open(file.c_str(), RAD_DIO_READ); rc < 0) return fail(rc);
|
||||
/* Four readers over the file: one stream of O_DIRECT reads leaves an NVMe drive half idle. */
|
||||
std::atomic<int64_t> next{0};
|
||||
std::atomic<int> err{RAD_OK};
|
||||
auto reader = [&] {
|
||||
DirectFile g;
|
||||
if (g.open(file.c_str(), RAD_DIO_READ) < 0) { err.store(RAD_E_IO); return; }
|
||||
for (;;) {
|
||||
const int64_t at = next.fetch_add(kCopyPiece);
|
||||
if (at >= n || err.load() < 0) return;
|
||||
if (g.read_at((char*)host + at, at, std::min(kCopyPiece, n - at)) < 0) { err.store(RAD_E_IO); return; }
|
||||
}
|
||||
};
|
||||
std::vector<std::thread> th;
|
||||
for (int i = 0; i < 4; ++i) th.emplace_back(reader);
|
||||
for (auto& t : th) t.join();
|
||||
if (err.load() < 0) {
|
||||
device_set_error("parking: reading %s back failed", file.c_str());
|
||||
return fail(err.load());
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
void HostCopy::release() {
|
||||
if (host) rad_dev_free(host, RAD_MEM_HOST_PINNED);
|
||||
host = nullptr;
|
||||
if (!file.empty()) ::unlink(file.c_str());
|
||||
file.clear();
|
||||
on_disk = false;
|
||||
bytes = 0;
|
||||
}
|
||||
|
||||
/* Precondition: the piece lies wholly inside one extent (decommit only drops committed granules).
|
||||
* What remains of that extent is nothing, a head, a tail, or both. */
|
||||
void VMem::drop_extent(int64_t off, int64_t bytes) {
|
||||
owner_add(vmem_owner_of(this), device_, -bytes);
|
||||
committed_ -= bytes;
|
||||
g_vmem_committed.fetch_sub(bytes, std::memory_order_relaxed);
|
||||
for (size_t i = 0; i < ext_.size(); ++i) {
|
||||
@@ -445,6 +769,16 @@ void VMem::drop_extent(int64_t off, int64_t bytes) {
|
||||
}
|
||||
}
|
||||
|
||||
const DeviceBackend* active_backend() { return dev(); }
|
||||
|
||||
std::vector<VMem*> vmems_of(int owner) {
|
||||
std::vector<VMem*> v;
|
||||
std::lock_guard<std::mutex> lk(g_page_mu);
|
||||
for (auto& [m, o] : g_vmem_owner)
|
||||
if (o == owner) v.push_back(m);
|
||||
return v;
|
||||
}
|
||||
|
||||
} /* namespace rad */
|
||||
|
||||
/* ------------------------------------------------------------------ the ABI surface */
|
||||
@@ -454,8 +788,7 @@ using rad::dev;
|
||||
extern "C" {
|
||||
|
||||
int rad_dev_count(void) { return dev()->count(); }
|
||||
/* The device this thread last selected, for the poison fill's stream (rad_dev_alloc). */
|
||||
static thread_local int t_device = 0;
|
||||
/* This thread's stream for the poison fill (rad_dev_alloc), one per device. */
|
||||
static thread_local std::map<int, RadStream> t_poison_stream;
|
||||
int rad_dev_set(int device) {
|
||||
const int st = dev()->set(device);
|
||||
@@ -469,9 +802,16 @@ void* rad_dev_alloc(int64_t bytes, int kind) {
|
||||
/* Poison ordinals are per thread: each rank allocates in a fixed order on its own thread, but
|
||||
* threads interleave, so a process-wide ordinal would not be repeatable. */
|
||||
thread_local int64_t t_device_ordinal = 0;
|
||||
void* p = dev()->alloc(bytes, kind);
|
||||
void* p = nullptr;
|
||||
const int owner = rad::engine_owner();
|
||||
/* A large device allocation for an engine is mapped in chunks it can be parked by
|
||||
* (paging.cpp). Where the backend has no virtual memory manager it is an ordinary allocation,
|
||||
* and the model parks only by unloading. */
|
||||
if (kind == RAD_MEM_DEVICE && bytes >= rad::kPageMin && owner > 0 && rad::VMem::supported())
|
||||
p = rad::page_alloc(bytes, owner, t_device);
|
||||
if (!p) p = dev()->alloc(bytes, kind);
|
||||
if (p && kind >= 0 && kind < (int)std::size(rad::g_ledger)) {
|
||||
rad::ledger_add(p, bytes, kind);
|
||||
rad::ledger_add(p, bytes, kind, owner, t_device);
|
||||
const int64_t total = rad::g_ledger[kind].count.fetch_add(1, std::memory_order_relaxed) + 1;
|
||||
const int64_t ordinal = kind == RAD_MEM_DEVICE ? ++t_device_ordinal : total;
|
||||
const int64_t floor_ = rad::trace_floor();
|
||||
@@ -497,8 +837,13 @@ void* rad_dev_alloc(int64_t bytes, int kind) {
|
||||
return p;
|
||||
}
|
||||
void rad_dev_free(void* p, int kind) {
|
||||
rad::ledger_drop(p);
|
||||
dev()->free(p, kind);
|
||||
const int64_t bytes = rad::ledger_drop(p);
|
||||
if (!(p && kind == RAD_MEM_DEVICE && rad::page_free(p))) dev()->free(p, kind);
|
||||
/* Kernel libraries drop state they keep for addresses in the freed range (rad_plugin_freed). */
|
||||
if (p && bytes > 0 && kind == RAD_MEM_DEVICE) {
|
||||
std::shared_lock<std::shared_mutex> lk(rad::g_free_hooks_mu);
|
||||
for (const auto& h : rad::g_free_hooks) h.first(p, bytes);
|
||||
}
|
||||
}
|
||||
void* rad_dev_host_ptr(void* p) { return dev()->host_ptr(p); }
|
||||
void* rad_dev_device_ptr(void* p) { return dev()->device_ptr(p); }
|
||||
@@ -558,6 +903,8 @@ std::string dev_pci_address(int device) {
|
||||
if (!dev()->pci_address) return std::string();
|
||||
return dev_string(64, [&](char* b, int n) { return dev()->pci_address(device, b, n); });
|
||||
}
|
||||
std::atomic<int64_t> dev_stuck_exit_ms{60000};
|
||||
std::atomic<bool> dev_engine_ready{false};
|
||||
int64_t dev_stuck_ms() {
|
||||
const auto f = dev()->stuck_ms;
|
||||
return f ? f() : 0;
|
||||
@@ -616,26 +963,56 @@ int rad_event_sync(RadEvent e) {
|
||||
}
|
||||
void rad_dev_host_wrote(void) { dev()->host_wrote(); }
|
||||
|
||||
/* Whether launches chain, from the engine (rad_dev_chain_infer), and the answer once taken. Only
|
||||
* where the backend chains: the AQL backend writes the record a chained form reads, while a HIP
|
||||
* launch carries only the kernel's own arguments. */
|
||||
static std::atomic<int> g_chain_pays{0};
|
||||
static std::atomic<int> g_chain{-1};
|
||||
/* The VRAM the runtime keeps as queue scratch on `p`'s card once kernels with a private segment
|
||||
* (spill, or a local array: step_advance's) have been dispatched: the runtime hands a queue
|
||||
* scratch memory at the first such dispatch, and the card showed +114 MiB after the first
|
||||
* speculative step and kept it, 150 MiB with a larger segment. The budget did not count it, so
|
||||
* serving left 27-65 MiB free. 5 MiB a CU (the R9700 reports 32), 160 MiB, over the measured. */
|
||||
extern "C" int64_t rad_dev_resident_scratch_bytes(const RadDeviceProps* p) {
|
||||
if (!p || p->is_host_backend || p->unified) return 0;
|
||||
return (int64_t)p->n_cu * (5LL * 1024 * 1024);
|
||||
}
|
||||
|
||||
/* Whether launches chain, by engine: rad_dev_chain_infer on a thread of an engine (EngineScope)
|
||||
* records that engine's answer and rad_dev_chain_enabled on any of its threads reads it. A process
|
||||
* serves several models, each with its own plugin's answer; a single answer for the process was
|
||||
* the answer of whichever model started last. Owner 0 is a thread outside every engine (a tool, a
|
||||
* test). Only where the backend chains: the AQL backend writes the record a chained form reads,
|
||||
* while a HIP launch carries only the kernel's own arguments. The answer is 2 where every chained
|
||||
* form the engine can launch fences itself (RadKernelChainFn saying 2), which
|
||||
* rad_dev_chain_unfenced reads. */
|
||||
static std::mutex g_chain_mu;
|
||||
static std::map<int, int> g_chain_pays; /* by owner: 0, 1, or 2 (their packets unacquired) */
|
||||
static std::atomic<uint64_t> g_chain_gen{1};
|
||||
void rad_dev_chain_infer(int pays) {
|
||||
g_chain_pays.store(pays ? 1 : 0, std::memory_order_relaxed);
|
||||
g_chain.store(-1, std::memory_order_relaxed);
|
||||
}
|
||||
int rad_dev_chain_enabled(void) {
|
||||
int on = g_chain.load(std::memory_order_relaxed);
|
||||
if (on < 0) {
|
||||
on = g_chain_pays.load(std::memory_order_relaxed) != 0 &&
|
||||
std::strcmp(rad::device_backend_name(), "aql") == 0
|
||||
? 1
|
||||
: 0;
|
||||
g_chain.store(on, std::memory_order_relaxed);
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(g_chain_mu);
|
||||
g_chain_pays[rad::engine_owner()] = pays == 2 ? 2 : pays ? 1 : 0;
|
||||
}
|
||||
return on;
|
||||
g_chain_gen.fetch_add(1, std::memory_order_release);
|
||||
}
|
||||
/* The calling thread's engine's answer where the backend chains, else 0: asked on every launch,
|
||||
* so a thread keeps it until some answer changes. */
|
||||
static int chain_mode() {
|
||||
thread_local uint64_t seen = 0;
|
||||
thread_local int owner = -1, mode = 0;
|
||||
const uint64_t gen = g_chain_gen.load(std::memory_order_acquire);
|
||||
const int o = rad::engine_owner();
|
||||
if (seen != gen || owner != o) {
|
||||
int pays = 0;
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(g_chain_mu);
|
||||
const auto it = g_chain_pays.find(o);
|
||||
if (it != g_chain_pays.end()) pays = it->second;
|
||||
}
|
||||
mode = pays && std::strcmp(rad::device_backend_name(), "aql") == 0 ? pays : 0;
|
||||
seen = gen;
|
||||
owner = o;
|
||||
}
|
||||
return mode;
|
||||
}
|
||||
int rad_dev_chain_enabled(void) { return chain_mode() != 0; }
|
||||
int rad_dev_chain_unfenced(void) { return chain_mode() == 2; }
|
||||
|
||||
int rad_event_elapsed_ms(RadEvent a, RadEvent b, float* out) {
|
||||
return dev()->event_elapsed_ms(a, b, out);
|
||||
@@ -672,6 +1049,14 @@ void* rad_link_gate(RadStream s) {
|
||||
if (const auto f = dev()->link_gate) return f(s);
|
||||
return nullptr;
|
||||
}
|
||||
void rad_dev_peer_launch(int on) {
|
||||
if (const auto f = dev()->peer_launch) f(on);
|
||||
}
|
||||
int rad_dev_cards_claim(const int* cards, int n, int on) {
|
||||
if (!cards || n <= 0) return RAD_E_INVAL;
|
||||
if (const auto f = dev()->cards_claim) return f(cards, n, on);
|
||||
return RAD_OK;
|
||||
}
|
||||
int rad_xp_supported(int device) {
|
||||
const auto* d = dev();
|
||||
return d->xp_supported && d->xp_stream_create && d->ride && d->ride_wait && d->ride_release && d->xp_list &&
|
||||
@@ -714,7 +1099,7 @@ void* rad_dev_map_file(int fd, int64_t foff, int64_t bytes) {
|
||||
}
|
||||
void* p = f(fd, foff, bytes);
|
||||
if (p) {
|
||||
rad::ledger_add(p, bytes, RAD_MEM_HOST_MAPPED);
|
||||
rad::ledger_add(p, bytes, RAD_MEM_HOST_MAPPED, 0, t_device);
|
||||
rad::g_ledger[RAD_MEM_HOST_MAPPED].count.fetch_add(1, std::memory_order_relaxed);
|
||||
}
|
||||
return p;
|
||||
|
||||
+101
-11
@@ -22,6 +22,7 @@
|
||||
#include <cstring>
|
||||
#include <map>
|
||||
#include <mutex>
|
||||
#include <set>
|
||||
#include <thread>
|
||||
#include <unordered_map>
|
||||
#include <vector>
|
||||
@@ -100,6 +101,8 @@ struct HostStream {
|
||||
|
||||
uint64_t submitted = 0; /* tasks ever pushed */
|
||||
uint64_t retired = 0; /* tasks ever finished executing */
|
||||
int sync_waiters = 0; /* h_stream_sync calls inside cv_done.wait */
|
||||
int room_waiters = 0; /* stream_push calls inside cv_room.wait */
|
||||
int gates = 0; /* closed gates (rad_stream_gate) queued on this stream */
|
||||
|
||||
std::thread worker;
|
||||
@@ -117,27 +120,48 @@ int stream_push(HostStream* s, const Task& t) {
|
||||
"(rad_gate_open) first");
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
++s->room_waiters;
|
||||
s->cv_room.wait(lk, [s] { return s->count < s->ring.size(); });
|
||||
--s->room_waiters;
|
||||
/* The worker can only be asleep on cv_work when the ring was empty, so only that push pays
|
||||
* the futex wake; its wait re-tests the predicate under the lock, so a wake it did not need
|
||||
* (it was already running) is the only kind this can lose. */
|
||||
const bool was_empty = s->count == 0;
|
||||
s->ring[s->tail] = t;
|
||||
s->tail = (s->tail + 1) % s->ring.size();
|
||||
++s->count;
|
||||
++s->submitted;
|
||||
lk.unlock();
|
||||
s->cv_work.notify_one();
|
||||
if (was_empty) s->cv_work.notify_one();
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* Pop the head task, with the stream lock held. Notifies are the caller's, after the unlock:
|
||||
* cv_room is only worth a wake while a producer is asleep on it (room_waiters). Every pop
|
||||
* wakes one while any is: a pop that only wakes on leaving a full ring loses the second of two
|
||||
* producers behind it, when the next pop comes before the first one has pushed. */
|
||||
static Task stream_pop_locked(HostStream* s, bool* wake_room) {
|
||||
*wake_room = s->room_waiters > 0;
|
||||
Task t = s->ring[s->head];
|
||||
s->head = (s->head + 1) % s->ring.size();
|
||||
--s->count;
|
||||
return t;
|
||||
}
|
||||
|
||||
void stream_run(HostStream* s) {
|
||||
Task t;
|
||||
bool have = false; /* t holds a task popped under the previous task's retire lock */
|
||||
for (;;) {
|
||||
Task t;
|
||||
{
|
||||
std::unique_lock<std::mutex> lk(s->m);
|
||||
s->cv_work.wait(lk, [s] { return s->count > 0; });
|
||||
t = s->ring[s->head];
|
||||
s->head = (s->head + 1) % s->ring.size();
|
||||
--s->count;
|
||||
if (!have) {
|
||||
bool wake_room = false;
|
||||
{
|
||||
std::unique_lock<std::mutex> lk(s->m);
|
||||
s->cv_work.wait(lk, [s] { return s->count > 0; });
|
||||
t = stream_pop_locked(s, &wake_room);
|
||||
}
|
||||
if (wake_room) s->cv_room.notify_one();
|
||||
}
|
||||
s->cv_room.notify_one();
|
||||
have = false;
|
||||
|
||||
bool done = false;
|
||||
switch (t.kind) {
|
||||
@@ -191,11 +215,22 @@ void stream_run(HostStream* s) {
|
||||
/* After the event lock is released: this may be the last reference. */
|
||||
if (t.ev) event_release(t.ev);
|
||||
|
||||
/* Retire this task and take the next under the same lock, so a busy stream pays one lock
|
||||
* a task instead of two. cv_done is only worth a futex wake when a sync is actually
|
||||
* asleep on it (sync_waiters, under this lock; the wait's predicate is re-tested under
|
||||
* the lock too, so no retire can be missed). */
|
||||
bool notify_done = false, wake_room = false;
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(s->m);
|
||||
++s->retired;
|
||||
notify_done = s->sync_waiters > 0;
|
||||
if (!done && s->count > 0) {
|
||||
t = stream_pop_locked(s, &wake_room);
|
||||
have = true;
|
||||
}
|
||||
}
|
||||
s->cv_done.notify_all();
|
||||
if (notify_done) s->cv_done.notify_all();
|
||||
if (wake_room) s->cv_room.notify_one();
|
||||
if (done) return;
|
||||
}
|
||||
}
|
||||
@@ -446,7 +481,9 @@ int h_stream_sync(RadStream st) {
|
||||
/* Waits only for work submitted before this call, as hipStreamSynchronize does; the
|
||||
* scheduler relies on sync returning while another thread keeps pushing. */
|
||||
const uint64_t target = s->submitted;
|
||||
++s->sync_waiters;
|
||||
s->cv_done.wait(lk, [s, target] { return s->retired >= target; });
|
||||
--s->sync_waiters;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
@@ -784,8 +821,24 @@ int h_vmem_commit(void* addr, int64_t bytes) {
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* Pages are what an mmap backs, so a run is one commit and any part of it decommits alone. */
|
||||
int h_vmem_commit_units(void* addr, int64_t bytes, int64_t unit) {
|
||||
if (unit <= 0 || bytes % unit) return RAD_E_INVAL;
|
||||
return h_vmem_commit(addr, bytes);
|
||||
}
|
||||
|
||||
/* Ranges backed as host memory (h_vmem_commit_host): not counted as the device's. */
|
||||
std::mutex g_hostkind_mu;
|
||||
std::set<const char*> g_hostkind;
|
||||
|
||||
bool take_hostkind(const void* addr) {
|
||||
std::lock_guard<std::mutex> lk(g_hostkind_mu);
|
||||
return g_hostkind.erase((const char*)addr) > 0;
|
||||
}
|
||||
|
||||
int h_vmem_decommit(void* addr, int64_t bytes) {
|
||||
if (!addr || bytes <= 0) return RAD_E_INVAL;
|
||||
const bool host = take_hostkind(addr);
|
||||
/* MAP_FIXED rather than munmap: a hole in the reservation could be handed to an unrelated
|
||||
* mmap. */
|
||||
void* p = ::mmap(addr, (size_t)bytes, PROT_NONE,
|
||||
@@ -794,7 +847,40 @@ int h_vmem_decommit(void* addr, int64_t bytes) {
|
||||
device_set_error("vmem_decommit(%p, %lld): mmap failed", addr, (long long)bytes);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
g_used[vmem_device_of(addr)].fetch_sub(bytes, std::memory_order_relaxed);
|
||||
if (!host) g_used[vmem_device_of(addr)].fetch_sub(bytes, std::memory_order_relaxed);
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* Host memory is all there is here: the same pages as a commit, not charged to the device. */
|
||||
int h_vmem_commit_host(void* addr, int64_t bytes) {
|
||||
if (!addr || bytes <= 0) return RAD_E_INVAL;
|
||||
void* p = ::mmap(addr, (size_t)bytes, PROT_READ | PROT_WRITE,
|
||||
MAP_FIXED | MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
|
||||
if (p != addr) {
|
||||
device_set_error("vmem_commit_host(%p, %lld): mmap failed", addr, (long long)bytes);
|
||||
return RAD_E_NOMEM;
|
||||
}
|
||||
std::lock_guard<std::mutex> lk(g_hostkind_mu);
|
||||
g_hostkind.insert((const char*)addr);
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* The pages move with mremap, through a spare range, so each keeps its bytes and its kind. */
|
||||
int h_vmem_swap(void* a, void* b, int64_t bytes) {
|
||||
if (!a || !b || bytes <= 0) return RAD_E_INVAL;
|
||||
const size_t n = (size_t)bytes;
|
||||
void* t = ::mmap(nullptr, n, PROT_NONE, MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
|
||||
if (t == MAP_FAILED) return RAD_E_NOMEM;
|
||||
if (::mremap(a, n, n, MREMAP_MAYMOVE | MREMAP_FIXED, t) != t ||
|
||||
::mremap(b, n, n, MREMAP_MAYMOVE | MREMAP_FIXED, a) != a ||
|
||||
::mremap(t, n, n, MREMAP_MAYMOVE | MREMAP_FIXED, b) != b) {
|
||||
device_set_error("vmem_swap(%p, %p, %lld): mremap failed", a, b, (long long)bytes);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
std::lock_guard<std::mutex> lk(g_hostkind_mu);
|
||||
const bool ha = g_hostkind.erase((const char*)a) > 0, hb = g_hostkind.erase((const char*)b) > 0;
|
||||
if (hb) g_hostkind.insert((const char*)a);
|
||||
if (ha) g_hostkind.insert((const char*)b);
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
@@ -842,6 +928,10 @@ const DeviceBackend g_host = {
|
||||
|
||||
h_stream_gate, h_gate_open, h_gate_room,
|
||||
nullptr, /* event_dma: no DMA queue */
|
||||
nullptr, /* map_file */
|
||||
nullptr, /* stuck_ms */
|
||||
h_vmem_commit_host, h_vmem_swap,
|
||||
h_vmem_commit_units,
|
||||
};
|
||||
|
||||
} /* namespace */
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
Reference in new issue
Block a user