Archived
radiance 1.7.0
- every model serves without a GPU: libavx covers every op, so `--kernels libavx` alone serves every shipped container - Qwen3-ASR (zivius): speech to text on /v1/audio/transcriptions and live over /v1/realtime - /v1/messages works with Claude Code as it ships (gearwave00001) - a long agent conversation keeps its cached history when the client rewrites its last turn (manueloverride) - a stream's first event goes out with the first token, so llama-benchy measures prefill right - opt-in --prefill-interleave (Smellyyyy, baKon) and --prefill-span (keptn42) - four-rank TP releases the link early; four-rank selftests and docs/TP4.md (goodman-b) - NVFP4 and FP8 compressed-tensors imports (devmilan); tools/rad-export for finetunes and LoRA adapters (baKon) - many fixes, among them lost tokens on stop strings under concurrency, keep-alive, MiniCPM5 tool arguments and the CPU's vision and audio encoders - plugin ABI 17 and changed op schemas: out-of-tree plugins must be rebuilt
This commit is contained in:
1 parent
b068190326
commit
1e968f6e1d
739 files changed
+128447
-84632
No files matched your search
+30
-14
@@ -9,16 +9,14 @@ int Arena::init(int64_t plan_bytes, int64_t scratch_bytes, int kind, int regions
|
||||
release();
|
||||
if (plan_bytes < 0 || scratch_bytes < 0 || regions < 1) return RAD_E_INVAL;
|
||||
|
||||
/* The scratch region starts on a page boundary. Kernels that want 4 KiB alignment for a
|
||||
* workspace get it for free, and the ones that do not are not charged for it -- the padding is
|
||||
* one page against an arena measured in hundreds of megabytes. */
|
||||
/* Scratch starts on a page boundary, so a workspace gets 4 KiB alignment for at most one
|
||||
* page of padding. */
|
||||
const int64_t off = align_up(plan_bytes, RAD_ALIGN_UNIT);
|
||||
const int64_t pitch = align_up(scratch_bytes, RAD_ALIGN_UNIT);
|
||||
const int64_t tail = pitch * regions;
|
||||
int64_t total = off + tail;
|
||||
|
||||
/* A zero-byte arena would hand every buffer a null base and turn a plan bug into a segfault
|
||||
* with no name on it. One page instead, so a stray offset lands somewhere reportable. */
|
||||
/* Never zero bytes: a null base would turn a plan bug into an anonymous segfault. */
|
||||
if (total == 0) total = RAD_ALIGN_UNIT;
|
||||
|
||||
void* p = rad_dev_alloc(total, kind);
|
||||
@@ -50,13 +48,25 @@ void Arena::release() {
|
||||
}
|
||||
|
||||
|
||||
/* See arena.h. The walk is Ctx::bind_arena's, lifted here whole so the budget resolver and the
|
||||
* allocation cannot disagree.
|
||||
*
|
||||
* THIS ASSUMES the plan gives host-domain buffers their own offset space. If it interleaves them
|
||||
* with device buffers instead, both arenas come out sparse: correct, but paying VRAM for host
|
||||
* activations. BufferInfo carries one arena_offset and one total, so the contract has to be stated
|
||||
* somewhere and this is it. */
|
||||
int64_t arena_host_bytes(const Program& P) {
|
||||
int64_t host_hw = 0;
|
||||
for (size_t i = 1; i < P.buffers.size(); ++i) {
|
||||
const BufferInfo& bi = P.buffers[i];
|
||||
if (bi.arena_offset < 0 || bi.decl.domain != RAD_DOMAIN_HOST) continue;
|
||||
int64_t bytes = bi.bytes;
|
||||
if (bytes <= 0) {
|
||||
int64_t n = 1;
|
||||
for (uint32_t d = 0; d < bi.decl.rank; ++d) n *= bi.decl.shape[d];
|
||||
bytes = rad_dtype_bytes(bi.decl.dtype, n);
|
||||
}
|
||||
host_hw = std::max(host_hw, bi.arena_offset + bytes);
|
||||
}
|
||||
return host_hw;
|
||||
}
|
||||
|
||||
/* Assumes the plan gives host-domain buffers their own offset space (BufferInfo carries one
|
||||
* arena_offset). If it interleaved them with device buffers, both arenas would come out sparse:
|
||||
* correct, but paying VRAM for host activations. */
|
||||
int64_t arena_plan_bytes(const Program& P, int64_t* dev_out, int64_t* total_out) {
|
||||
int64_t dev_hw = 0, host_hw = 0;
|
||||
for (size_t i = 1; i < P.buffers.size(); ++i) {
|
||||
@@ -74,8 +84,7 @@ int64_t arena_plan_bytes(const Program& P, int64_t* dev_out, int64_t* total_out)
|
||||
/* With no host-domain buffers the plan's own total is authoritative: it may carry alignment
|
||||
* slack the high-water mark does not see. */
|
||||
int64_t dev_bytes = host_hw > 0 ? dev_hw : std::max(dev_hw, P.arena_bytes);
|
||||
/* The staging region sits above every buffer, so it is its own term, whichever of the two
|
||||
* above set the high-water mark. */
|
||||
/* The staging region sits above every buffer, so it is a separate term. */
|
||||
if (P.arena_stage_bytes > 0 && P.arena_stage_off >= 0)
|
||||
dev_bytes = std::max(dev_bytes, P.arena_stage_off + P.arena_stage_bytes);
|
||||
int64_t total = align_up(dev_bytes, RAD_ALIGN_UNIT) +
|
||||
@@ -85,4 +94,11 @@ int64_t arena_plan_bytes(const Program& P, int64_t* dev_out, int64_t* total_out)
|
||||
if (total_out) *total_out = total;
|
||||
return total;
|
||||
}
|
||||
int arena_level_for(const std::vector<int64_t>& level_rows, int64_t rows) {
|
||||
int level = 0;
|
||||
for (size_t k = 1; k < level_rows.size(); ++k)
|
||||
if (level_rows[k] >= rows && (level == 0 || level_rows[k] < level_rows[(size_t)level]))
|
||||
level = (int)k;
|
||||
return level;
|
||||
}
|
||||
} /* namespace rad */
|
||||
+27
-26
@@ -1,22 +1,16 @@
|
||||
/* arena.h -- ONE contiguous allocation, sized by the buffer plan at load and never allocated from
|
||||
/* arena.h -- one contiguous allocation, sized by the buffer plan at load and never allocated from
|
||||
* at runtime.
|
||||
*
|
||||
* There is deliberately no allocate() on this class. If there were one somebody would eventually
|
||||
* call it from inside rad_arch_step, and an allocator on the step path is precisely the class of
|
||||
* dynamic behaviour this engine exists to remove (spec §3.1). Offsets come from the buffer plan,
|
||||
* which computed liveness over the declared op list and is conservative on purpose: a plan that is
|
||||
* correct for the worst step is correct for every step. The arena only owns the block those
|
||||
* offsets index into.
|
||||
* There is deliberately no allocate(): an allocator on the step path is the dynamic behaviour this
|
||||
* engine exists to remove (spec §3.1). Offsets come from the buffer plan, which computes liveness
|
||||
* over the declared op list for the worst step; the arena only owns the block they index into.
|
||||
*
|
||||
* The scratch region sits at the tail and is shared by every op on a stream. That is safe and not
|
||||
* merely convenient: launches on one stream execute in order, so no two kernels' scratch lifetimes
|
||||
* overlap. A context's second lane is a second stream, where that order does not hold, so a program
|
||||
* that declares one gets a second region and each lane's kernels are handed their own
|
||||
* (Program::scratch_regions). A lane used without that declaration shares region 0, and there
|
||||
* Ctx::issue orders a scratch user behind one on the other lane that nothing has ordered it after
|
||||
* yet. Program::scratch_bytes is the largest single kernel's requirement, so a region of that size
|
||||
* serves all of them -- and if a kernel asks for more than the plan reserved, prepare refuses by
|
||||
* name rather than handing it a short buffer.
|
||||
* Scratch sits at the tail and is shared by every op on a stream, which is safe because launches
|
||||
* on one stream execute in order. A context's second lane is a second stream, so a program that
|
||||
* declares one gets a second region per lane (Program::scratch_regions). A lane used without that
|
||||
* declaration shares region 0, and Ctx::issue orders a scratch user behind an unordered one on the
|
||||
* other lane. Program::scratch_bytes is the largest single kernel's requirement; a kernel asking
|
||||
* for more is refused by name in prepare.
|
||||
*/
|
||||
#pragma once
|
||||
#include "../rad_core.h"
|
||||
@@ -30,9 +24,9 @@ public:
|
||||
Arena(const Arena&) = delete;
|
||||
Arena& operator=(const Arena&) = delete;
|
||||
|
||||
/* `kind` is a RAD_MEM_* class. The device arena is RAD_MEM_DEVICE; a program with
|
||||
* RAD_DOMAIN_HOST buffers gets a second arena in RAD_MEM_HOST. `regions` scratch regions of
|
||||
* `scratch_bytes` each sit at the tail, one per lane (Program::scratch_regions). */
|
||||
/* `kind` is a RAD_MEM_* class: RAD_MEM_DEVICE for the device arena, RAD_MEM_HOST for the
|
||||
* second arena a program with RAD_DOMAIN_HOST buffers gets. `regions` scratch regions of
|
||||
* `scratch_bytes` each sit at the tail, one per lane. */
|
||||
int init(int64_t plan_bytes, int64_t scratch_bytes, int kind, int regions = 1);
|
||||
void release();
|
||||
|
||||
@@ -58,14 +52,21 @@ private:
|
||||
};
|
||||
|
||||
|
||||
/* THE ARENA'S SIZE, COMPUTED WITHOUT ALLOCATING IT. Two callers need the same answer at two
|
||||
* different times: Ctx::bind_arena, which allocates it at the end of startup, and the VRAM budget
|
||||
* resolver, which has to subtract it from the card BEFORE the pools are allocated near the top of
|
||||
* startup. Two copies of this walk would agree today and drift the first time the plan grows a
|
||||
* domain -- and the failure would be a budget that overcommits the card by exactly the difference.
|
||||
/* The arena's size, computed without allocating it. Shared by Ctx::bind_arena (allocates at the
|
||||
* end of startup) and the VRAM budget resolver (subtracts it before the pools are allocated), so
|
||||
* the two cannot drift apart and overcommit the card.
|
||||
*
|
||||
* `dev_out` is what the device arena's init() will be given as plan_bytes; `total_out` is what it
|
||||
* will actually allocate, plan and scratch both padded to RAD_ALIGN_UNIT as Arena::init pads them.
|
||||
* `dev_out` is the plan_bytes the device arena's init() receives; `total_out` is what it
|
||||
* allocates, plan and scratch both padded to RAD_ALIGN_UNIT as Arena::init pads them.
|
||||
* Returns the total. */
|
||||
int64_t arena_plan_bytes(const Program& P, int64_t* dev_out, int64_t* total_out);
|
||||
|
||||
/* The host activation arena's size (the RAD_DOMAIN_HOST buffers), which Ctx::bind_arena pins and
|
||||
* maps at the end of startup; 0 when the program declares none. */
|
||||
int64_t arena_host_bytes(const Program& P);
|
||||
|
||||
/* The arena level a step of `rows` tokens runs at: the smallest level that holds it, or 0 (the
|
||||
* full plan) when none does. `level_rows[k]` is the largest step level k serves; entry 0 is the
|
||||
* full plan and is never chosen by size. */
|
||||
int arena_level_for(const std::vector<int64_t>& level_rows, int64_t rows);
|
||||
} /* namespace rad */
|
||||
+191
-326
@@ -1,6 +1,5 @@
|
||||
/* ctx.cpp -- everything the run phase does that is not the hot path: bringing the arena and the
|
||||
* plans up, driving a step, the routing handoff, and the opt-in per-op timing. The hot path itself
|
||||
* is issue.cpp, kept in its own translation unit so it stays readable at the size it has to be.
|
||||
/* ctx.cpp -- the run phase outside the hot path: arena and plan bring-up, the step driver, the
|
||||
* routing handoff and opt-in per-op timing. The hot path is issue.cpp.
|
||||
*/
|
||||
#include <vector>
|
||||
#include "ctx.h"
|
||||
@@ -27,6 +26,7 @@ int Ctx::init(const CtxDesc& d) {
|
||||
device_ = d.device;
|
||||
record_passes_ = d.record_passes;
|
||||
residency_ = d.residency;
|
||||
registry_ = d.registry;
|
||||
kv_ = d.kv;
|
||||
arch_step_ = d.arch_step;
|
||||
profiling_ = d.profile_ops;
|
||||
@@ -39,14 +39,13 @@ int Ctx::init(const CtxDesc& d) {
|
||||
stream_ = d.stream;
|
||||
own_stream_ = false;
|
||||
} else {
|
||||
/* Ordinary priority. The mover runs on its own stream and the compute stream waits on its
|
||||
* events (spec §5.4); making compute high-priority would let it preempt the transfers it
|
||||
* is about to wait for, which is exactly backwards. */
|
||||
/* Ordinary priority: compute waits on the mover's events (spec §5.4), so a high-priority
|
||||
* compute stream would preempt the transfers it is about to wait for. */
|
||||
RAD_TRY(rad_stream_create(&stream_, 0));
|
||||
own_stream_ = true;
|
||||
}
|
||||
|
||||
/* The second lane is NOT created here. See lane_init(). */
|
||||
/* The second lane is created lazily; see lane_init(). */
|
||||
|
||||
int s = prepare();
|
||||
if (s < 0) { shutdown(); return s; }
|
||||
@@ -56,11 +55,8 @@ int Ctx::init(const CtxDesc& d) {
|
||||
void Ctx::shutdown() {
|
||||
oracle_close();
|
||||
xp_close();
|
||||
/* The one host synchronisation in the whole component, and it is at teardown rather than on
|
||||
* the step path. Everything below frees memory the stream may still be reading or writing --
|
||||
* the routing staging is the destination of a copy nobody waited on by design (spec §5.5), and
|
||||
* the arena is every kernel's operands. Freeing either out from under an in-flight stream is a
|
||||
* use-after-free that reproduces once a week and never under a debugger. */
|
||||
/* Teardown sync, before freeing memory the streams may still use: the routing staging is the
|
||||
* destination of unwaited copies (spec §5.5) and the arena holds every kernel's operands. */
|
||||
if (stream_) rad_stream_sync(stream_);
|
||||
if (lane1_) rad_stream_sync(lane1_);
|
||||
|
||||
@@ -80,9 +76,7 @@ void Ctx::shutdown() {
|
||||
if (route_pool_) { rad_dev_free(route_pool_, RAD_MEM_HOST_PINNED); route_pool_ = nullptr; }
|
||||
if (route_dev_) { rad_dev_free(route_dev_, RAD_MEM_DEVICE); route_dev_ = nullptr; }
|
||||
|
||||
/* The expert pointer tables. Freed after the stream syncs above for exactly the reason those
|
||||
* syncs exist: the device half is the source operand of a grouped GEMM and the host half is
|
||||
* the source of a copy on that stream. */
|
||||
/* After the syncs: the device half is a grouped GEMM operand, the host half a copy source. */
|
||||
free_weight_tables();
|
||||
|
||||
arena_.release();
|
||||
@@ -113,29 +107,23 @@ int Ctx::prepare() {
|
||||
oracle_open();
|
||||
RAD_TRY(bind_arena());
|
||||
RAD_TRY(bind_buffers());
|
||||
RAD_TRY(bind_weights(/*refresh_only=*/false));
|
||||
RAD_TRY(bind_weights());
|
||||
RAD_TRY(bind_weight_tables());
|
||||
RAD_TRY(bind_ops());
|
||||
RAD_TRY(bind_routing());
|
||||
RAD_TRY(bind_profiling());
|
||||
/* Recorded passes need a backend that records, and are off for everything that has to see
|
||||
* each issue: the per-op profile, the oracle, and the argument digest. */
|
||||
tape_on_ = record_passes_ && tape_supported() && !profiling_ && !oracle_ &&
|
||||
std::getenv("RADIANCE_DEBUG_ARGSHA") == nullptr;
|
||||
/* Recorded passes need a recording backend, and are off whenever every issue must be seen:
|
||||
* per-op profile, oracle. */
|
||||
tape_on_ = record_passes_ && tape_supported() && !profiling_ && !oracle_;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int Ctx::bind_arena() {
|
||||
Program& P = *program_;
|
||||
|
||||
/* The buffer plan hands us one offset per buffer, and arena_plan_bytes() turns those into the
|
||||
* two numbers Arena::init wants. THE WALK LIVES THERE AND NOT HERE because the VRAM budget
|
||||
* resolver has to subtract this allocation from the card before any of it exists -- see
|
||||
* core/mem/vram_budget.cpp. What stays here is the part that can only be done at bind time:
|
||||
* refusing a plan that did not run, and filling in a size the plan left at zero.
|
||||
*
|
||||
* Where a program has RAD_DOMAIN_HOST buffers -- host-site execution, spec §5.1 -- those
|
||||
* offsets cannot index the same block, so there are two arenas. */
|
||||
/* Sizing is arena_plan_bytes(), shared with the VRAM budget (core/mem/vram_budget.cpp). Here:
|
||||
* refuse a plan that did not run, and fill in sizes the plan left at zero. RAD_DOMAIN_HOST
|
||||
* buffers (host-site execution, spec §5.1) get a second arena. */
|
||||
int64_t host_hw = 0;
|
||||
for (size_t i = 1; i < P.buffers.size(); ++i) {
|
||||
BufferInfo& bi = P.buffers[i];
|
||||
@@ -159,40 +147,23 @@ int Ctx::bind_arena() {
|
||||
arena_plan_bytes(P, &dev_bytes, &total);
|
||||
|
||||
RAD_TRY(arena_.init(dev_bytes, P.scratch_bytes, RAD_MEM_DEVICE, std::max(P.scratch_regions, 1)));
|
||||
/* SAY WHAT THIS COSTS, BECAUSE NOTHING ELSE DOES. The allocation is in no pool, and it is not
|
||||
* something --gpu-headroom-mib can cover: it scales with max_tok, so any round number an
|
||||
* operator picks either under-reserves or wastes VRAM. On a part whose experts do not fit,
|
||||
* waste is not free -- a GiB of headroom nothing uses is about 1.4 ms a decode step, because
|
||||
* that GiB is experts that would otherwise be resident. So it is computed and charged by name:
|
||||
* core/mem/vram_budget.cpp does the charging, this line is the receipt, and the two numbers
|
||||
* must agree. */
|
||||
/* The arena is in no pool and scales with max_tok, so core/mem/vram_budget.cpp charges it by
|
||||
* name rather than leaving it to --gpu-headroom-mib. This log line must agree with that
|
||||
* charge. */
|
||||
RAD_INFO("arena: %s device + %d x %s scratch = %s, charged to the VRAM budget before it was "
|
||||
"split", humanb(dev_bytes).c_str(), arena_.scratch_regions(),
|
||||
humanb(P.scratch_bytes).c_str(), humanb(total).c_str());
|
||||
|
||||
if (host_hw > 0) {
|
||||
/* RAD_MEM_HOST_MAPPED AND NOT RAD_MEM_HOST, AND THAT IS THE WHOLE OF HOW A HOST RUN
|
||||
* REACHES THE DEVICE GRAPH.
|
||||
*
|
||||
* A host-site op writes a host-domain buffer and something downstream reads it on the
|
||||
* device. NOTHING IN THIS RUNTIME COPIES BETWEEN THE TWO ARENAS -- there is no transfer op
|
||||
* and no implicit staging in rad_issue, and the planner's `link_crossings` is an objective
|
||||
* it minimises, not a mechanism it provides. With plain RAD_MEM_HOST the host arena is
|
||||
* "ordinary malloc'd pages the GPU has never been shown" (core/device/hip.cpp), so the
|
||||
* device side of that hand-off had no way to read it and host-site execution could not
|
||||
* complete a step. Mapped, the same allocation is addressable from a kernel over the link
|
||||
* and the crossing IS the read -- which is row three of spec 5.1 applied to an activation
|
||||
* rather than to a weight.
|
||||
*
|
||||
* The cost is that every device access to a host-domain buffer is a link read, so this is
|
||||
* for the narrow hand-off at a host run's edge and not for a hot activation. A buffer's
|
||||
* domain is declared by the ARCHITECTURE, so that judgement stays where it belongs. */
|
||||
/* RAD_MEM_HOST_MAPPED, not RAD_MEM_HOST: nothing copies between the two arenas, so device
|
||||
* kernels must read host-domain buffers directly over the link (spec §5.1, row three,
|
||||
* applied to activations). Plain RAD_MEM_HOST pages are not device-visible
|
||||
* (core/device/hip.cpp). Every device access is a link read, so host-domain buffers suit
|
||||
* only the hand-off at a host run's edge; the architecture declares the domain. */
|
||||
RAD_TRY(host_arena_.init(host_hw, 0, RAD_MEM_HOST_MAPPED));
|
||||
/* ONE POINTER SERVES BOTH SIDES, AND THAT IS CHECKED RATHER THAN ASSUMED. bind_buffers
|
||||
* stores a single base per buffer, which is correct exactly while the mapped allocation's
|
||||
* host and device views share an address -- true under HIP's unified addressing and true
|
||||
* by construction on the host backend. A backend where they differ gets a refusal here
|
||||
* instead of handing one of the two sides a pointer into nothing. */
|
||||
/* bind_buffers stores one pointer per buffer, valid only while the mapped allocation's
|
||||
* host and device views share an address (true under HIP unified addressing and on the
|
||||
* host backend). Checked, not assumed. */
|
||||
void* hb = host_arena_.base();
|
||||
void* db = rad_dev_device_ptr(hb);
|
||||
if (!db || db != hb) {
|
||||
@@ -235,8 +206,7 @@ int Ctx::bind_buffers() {
|
||||
return RAD_E_FULL;
|
||||
}
|
||||
|
||||
/* rad_buf_ptr is arena_base + BufferInfo::arena_offset, and nothing else -- there is no
|
||||
* table walk and no allocator between a handle and its bytes. */
|
||||
/* rad_buf_ptr is arena_base + BufferInfo::arena_offset. */
|
||||
t.data = a.base() + bi.arena_offset;
|
||||
bi.ptr = t.data;
|
||||
buf_bits_[i] = rad_dtype_bits(bi.decl.dtype);
|
||||
@@ -255,7 +225,7 @@ int Ctx::add_level(int64_t rows, const std::vector<int64_t>& offset,
|
||||
std::vector<RadTensor> t = level_tmpl_[0];
|
||||
for (size_t i = 1; i < P.buffers.size(); ++i) {
|
||||
const BufferInfo& bi = P.buffers[i];
|
||||
/* THE HOST ARENA AND THE FIXED REGION ARE NOT LEVELLED: their template is level 0's. */
|
||||
/* The host arena and the fixed region are not levelled: level 0's template. */
|
||||
if (bi.decl.domain == RAD_DOMAIN_HOST || bi.decl.kind != RAD_BUF_TRANSIENT) {
|
||||
if (offset[i] != bi.arena_offset) return RAD_E_STATE;
|
||||
continue;
|
||||
@@ -288,50 +258,33 @@ int Ctx::set_level(int level) {
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int Ctx::bind_weights(bool refresh_only) {
|
||||
/* The weights' addresses as the load phase left them. A weight the mover relocates afterwards is
|
||||
* read through the ResidencyTable (sync_residency), never through its template. */
|
||||
int Ctx::bind_weights() {
|
||||
Program& P = *program_;
|
||||
++w_tmpl_epoch_;
|
||||
if (!refresh_only) {
|
||||
w_tmpl_.assign(P.weights.size(), RadTensor{});
|
||||
w_bits_.assign(P.weights.size(), 0);
|
||||
w_gen_.assign(P.weights.size(), 0);
|
||||
waited_gen_.assign(P.weights.size(), UINT32_MAX);
|
||||
w_direct_.assign(P.weights.size(), 0);
|
||||
}
|
||||
w_tmpl_.assign(P.weights.size(), RadTensor{});
|
||||
w_bits_.assign(P.weights.size(), 0);
|
||||
waited_gen_.assign(P.weights.size(), UINT32_MAX);
|
||||
w_direct_.assign(P.weights.size(), 0);
|
||||
|
||||
for (size_t i = 1; i < P.weights.size(); ++i) {
|
||||
WeightInfo& wi = P.weights[i];
|
||||
const uint32_t gen = wi.generation.load(std::memory_order_acquire);
|
||||
if (refresh_only && w_gen_[i] == gen) continue;
|
||||
|
||||
const WeightInfo& wi = P.weights[i];
|
||||
RadTensor& t = w_tmpl_[i];
|
||||
/* The stored dtype is what the resolved kernel's layout hook asked for; the logical dtype
|
||||
* is what the plugin declared. The kernel reads the layout it chose, so the stored one
|
||||
* wins where the layout pass filled it in.
|
||||
/* Stored dtype (from the resolved kernel's layout hook) wins over the declared one, since
|
||||
* the kernel reads the layout it chose.
|
||||
*
|
||||
* THE SHAPE IS THE DECLARED ONE and the dtype is the stored one, which is a seam worth
|
||||
* naming rather than a symmetry. WeightInfo DOES carry stored_shape -- the layout pass
|
||||
* fills it beside stored_dtype -- and this deliberately does not use it, because a kernel
|
||||
* whose layout reshapes has to keep working out its own stride from the geometry either
|
||||
* way: a row-sharded weight's stored shape is the whole tensor's, not this rank's.
|
||||
*
|
||||
* So a layout that changes the WIDTH (libr4d's fp8 lm_head appends each row's scales to
|
||||
* its own row) is invisible here, and its kernel derives the stride from the same rule its
|
||||
* layout hook used. What keeps the two honest is the layout TAG the engine checks at load,
|
||||
* not a shape it could compare. The declared shape is already divided by world_size,
|
||||
* because the plugin declares dimensions per rank (spec §9). */
|
||||
* The shape is deliberately the declared one, not WeightInfo::stored_shape: a row-sharded
|
||||
* weight's stored shape is the whole tensor's, not this rank's, so a re-laying kernel
|
||||
* derives its own stride anyway (e.g. libr4d's fp8 lm_head appends row scales to each
|
||||
* row). Consistency is enforced by the layout tag checked at load. The declared shape is
|
||||
* per rank (spec §9). */
|
||||
t.dtype = wi.stored_dtype != RAD_DT_INVALID ? wi.stored_dtype : wi.decl.dtype;
|
||||
t.rank = wi.decl.rank;
|
||||
for (uint32_t d = 0; d < wi.decl.rank && d < RAD_MAX_RANK; ++d) t.shape[d] = wi.decl.shape[d];
|
||||
rad_tensor_pack(&t);
|
||||
t.data = wi.ptr;
|
||||
w_bits_[i] = rad_dtype_bits(t.dtype);
|
||||
w_gen_[i] = gen;
|
||||
}
|
||||
/* A rebinding can move any template, and a table entry the residency table has no slot for
|
||||
* reads its template: every table resolves every entry at its next issue. */
|
||||
if (refresh_only)
|
||||
for (WeightTable& t : wtabs_) if (t.checked) { t.full = true; t.pend.clear(); }
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
@@ -347,11 +300,10 @@ int Ctx::bind_ops() {
|
||||
issue_table_.clear();
|
||||
gate_params_.clear();
|
||||
|
||||
int64_t n_bands_total = 0, n_plans = 0;
|
||||
for (auto& o : P.ops) { n_bands_total += (int64_t)o.bands.size(); }
|
||||
n_plans = n_bands_total * RAD_N_DOMAINS;
|
||||
int64_t n_bands_total = 0;
|
||||
for (auto& o : P.ops) n_bands_total += (int64_t)o.bands.size();
|
||||
band_table_.reserve((size_t)n_bands_total);
|
||||
issue_table_.reserve((size_t)n_plans);
|
||||
issue_table_.reserve((size_t)(n_bands_total * RAD_N_DOMAINS));
|
||||
|
||||
for (size_t i = 1; i < P.ops.size(); ++i) {
|
||||
OpInfo& oi = P.ops[i];
|
||||
@@ -361,7 +313,7 @@ int Ctx::bind_ops() {
|
||||
p.n_bands = (int32_t)oi.bands.size();
|
||||
p.plan_off = (int32_t)issue_table_.size();
|
||||
p.n_opd_schema = oi.schema ? (int32_t)oi.schema->n_operands : -1;
|
||||
/* Matched by name once, here, rather than on the issue path -- see OpPlan::billed. */
|
||||
/* Matched by name once here, not on the issue path; see OpPlan::billed. */
|
||||
p.billed = (oi.op == "all_reduce");
|
||||
p.collective = p.billed;
|
||||
|
||||
@@ -374,11 +326,11 @@ int Ctx::bind_ops() {
|
||||
if (r && r.row && r.row->info && r.row->info->launch) {
|
||||
ip.row = r.row;
|
||||
ip.launch = r.row->info->launch;
|
||||
ip.ranged_div = r.ranged_div;
|
||||
if (r.row->collective) p.collective = true;
|
||||
|
||||
/* Bound once. args.p views the frozen geometry inside Program::ops, which is
|
||||
* why declare must not touch a Resolved after this point: the vector would
|
||||
* reallocate and every one of these would dangle. */
|
||||
/* args.p views the frozen geometry inside Program::ops; declare must not
|
||||
* touch a Resolved after this, or these pointers dangle. */
|
||||
ip.args.t = tbuf_;
|
||||
ip.args.n_t = 0;
|
||||
ip.args.p = r.geom.params();
|
||||
@@ -388,8 +340,8 @@ int Ctx::bind_ops() {
|
||||
ip.args.instance = r.instance;
|
||||
ip.args.rank = rank_;
|
||||
ip.args.world_size = world_size_;
|
||||
/* A launch that ends its own hold on the link is handed the word the hold is
|
||||
* kept in, as one parameter more after the geometry's -- when it holds one. */
|
||||
/* A launch that ends its own link hold gets the hold word as an extra
|
||||
* `link_gate` parameter after the geometry's. */
|
||||
if (r.row->releases_link)
|
||||
if (void* g = rad_link_gate(stream_)) {
|
||||
std::vector<RadParam>& v =
|
||||
@@ -417,15 +369,12 @@ int Ctx::bind_ops() {
|
||||
}
|
||||
}
|
||||
|
||||
/* Execution site. Site is a property of the weights (spec §5.1), so an op whose every
|
||||
* weight operand was placed on the host runs its host kernel and everything else runs on
|
||||
* the device. An op with no weights stays on the device; the planner overrides through
|
||||
* set_op_domain, which is where the "contiguous host runs" objective actually lands.
|
||||
/* Execution site follows the weights (spec §5.1): an op whose every weight is on the host
|
||||
* runs its host kernel, everything else the device. An op with no weights stays on the
|
||||
* device; the planner overrides through set_op_domain.
|
||||
*
|
||||
* ON THE HOST BACKEND (no card visible: CPU-only serving) the device domain is the host's
|
||||
* own memory and an op with no device kernel in any band runs its host kernel -- the
|
||||
* whole model on libavx (or libref) with no switch to set. An op that does carry device
|
||||
* rows there is a test registering fakes, and keeps them. */
|
||||
* On the host backend (CPU-only), an op with no device kernel in any band runs its host
|
||||
* kernel (libavx or libref). Device rows there come from tests registering fakes. */
|
||||
int dom = RAD_DOMAIN_DEVICE;
|
||||
if (device_is_host()) {
|
||||
bool any_device = false;
|
||||
@@ -440,9 +389,8 @@ int Ctx::bind_ops() {
|
||||
const WeightInfo* wi = P.weight(w);
|
||||
if (!wi || wi->site != Site::Host) { all_host = false; break; }
|
||||
}
|
||||
/* ...and whether that host kernel can READ the weights, which is a separate question
|
||||
* from whether one exists. The planner asked for the host; the device is always a
|
||||
* correct answer, so this is a fallback and a warning rather than a refusal. */
|
||||
/* The host kernel must also read the stored layout. The device is always correct,
|
||||
* so this falls back with a warning rather than refusing. */
|
||||
std::string why;
|
||||
if (all_host && check_domain_layout((rad_op)i, RAD_DOMAIN_HOST, &why) < 0) {
|
||||
RAD_WARN("op '%s' was placed on the host and runs on the device instead: %s",
|
||||
@@ -461,27 +409,16 @@ int Ctx::bind_ops() {
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* CAN THE KERNEL THAT WOULD SERVE THIS OP ON `domain` READ THE BYTES THE CONTAINER HOLDS?
|
||||
/* Whether the kernel serving this op on `domain` can read the bytes the container holds.
|
||||
*
|
||||
* A weight is stored ONCE, in whatever arrangement the kernel that claimed it at declare asked
|
||||
* for (spec 4.2), and that claimant is always a DEVICE row: rad_builder.cpp exempts the host
|
||||
* domain from the layout claim deliberately, because libref declares no layout for anything and
|
||||
* every re-laying device kernel would otherwise collide with its own reference fallback and no
|
||||
* model would declare at all.
|
||||
* A weight is stored once, in the arrangement its claiming kernel asked for (spec 4.3), and the
|
||||
* claimant is a device row wherever one reads the weight: rad_builder.cpp lets a host row claim
|
||||
* only what no device row did. A host kernel reading as declared would see e.g. libr4d's fp8a8
|
||||
* WMMA fragment order -- same N*K bytes, so every shape check passes -- and compute plausible
|
||||
* wrong answers. The load-time tag check in engine_bringup only checks the claiming row.
|
||||
*
|
||||
* So moving an op to a domain whose kernel reads its weights AS DECLARED hands that kernel a
|
||||
* plane it cannot read. libr4d stores an fp8a8 weight in WMMA fragment order -- the same N*K
|
||||
* bytes in a different arrangement -- so the byte count matches, every shape check passes, and
|
||||
* the op computes a plausible wrong answer for the life of the process. Two readings of one
|
||||
* permuted plane are uncorrelated tensors, which is a model that serves and lies.
|
||||
*
|
||||
* The load-time tag check in engine_bringup cannot see this: it compares the container against
|
||||
* the tag the claimant recorded, and both of those are the device row's. This asks the same
|
||||
* question of the kernel that will actually run.
|
||||
*
|
||||
* `why` gets the sentence; the caller decides whether it is a warning or a refusal, because the
|
||||
* two callers differ. The planner ASKED for the host and can be given the device instead, which
|
||||
* is always a correct answer; an explicit set_op_domain has no such fallback. */
|
||||
* `why` gets the message. The caller picks the severity: the planner's host request falls back
|
||||
* to the device, an explicit set_op_domain has no fallback. */
|
||||
int Ctx::check_domain_layout(rad_op h, int domain, std::string* why) const {
|
||||
if (h == RAD_NULL_HANDLE || h >= plans_.size()) return RAD_E_INVAL;
|
||||
if (domain < 0 || domain >= RAD_N_DOMAINS) return RAD_E_INVAL;
|
||||
@@ -504,9 +441,9 @@ int Ctx::check_domain_layout(rad_op h, int domain, std::string* why) const {
|
||||
RadLayout L{};
|
||||
RadTensor t[RAD_ENC_MAX_PLANES];
|
||||
weight_planes(w, t);
|
||||
/* A row with no hook, or one that declines this operand, is asserting that it reads
|
||||
* the selected plane AS IT IS -- the same reading rad_builder.cpp gives the same code.
|
||||
* One that does not read the encoding at all cannot take the op either. */
|
||||
/* A row with no hook, or one that declines this operand, reads the selected plane as
|
||||
* stored (as rad_builder.cpp interprets it). One that cannot read the encoding at all
|
||||
* cannot take the op. */
|
||||
const int st = ki->layout ? ki->layout(ip.args.p, ip.args.n_p, opd, &w.enc, w.sel, t,
|
||||
w.n_sel, &L)
|
||||
: RAD_E_UNSUPPORTED;
|
||||
@@ -548,7 +485,7 @@ int Ctx::check_domain(rad_op h, int domain) const {
|
||||
return RAD_E_NOKERNEL;
|
||||
}
|
||||
|
||||
/* A kernel existing for the band is not the same as a kernel that can READ THE WEIGHT. */
|
||||
/* A kernel existing for every band does not mean it can read the stored weight. */
|
||||
std::string why;
|
||||
if (check_domain_layout(h, domain, &why) < 0) {
|
||||
RAD_ERR("op '%s' cannot run on the %s domain: %s", p.info->op.c_str(),
|
||||
@@ -576,20 +513,10 @@ int Ctx::op_domain(rad_op h) const {
|
||||
|
||||
int Ctx::bind_routing() {
|
||||
const Program& P = *program_;
|
||||
/* THE ROUTED LAYER COUNT IS NOT meta.n_layers, AND A DRAFTER IS WHY.
|
||||
*
|
||||
* `meta.n_layers` counts TRUNK layers. An MTP head is a further block with its own expert
|
||||
* plane, and it reports itself as the layer one past that count. Sized from `meta.n_layers`
|
||||
* this vector is one short, so every one of that head's route reports is refused with an error
|
||||
* and the heat engine never sees a single count for it. The placement plan still knows about
|
||||
* the units but has no measurement to promote on, so they stay wherever the warm start left
|
||||
* them -- and the head's experts stream over the link on EVERY draft round of every step,
|
||||
* which is worth several percent of the decode step on a model that has one.
|
||||
*
|
||||
* The weights know the answer and the header does not, so ask them. A drafter, a shared
|
||||
* expert plane, anything a plugin declares past the trunk lands here by construction rather
|
||||
* than by the core being told about it.
|
||||
*/
|
||||
/* The routed layer count comes from the expert weights, not meta.n_layers, which counts only
|
||||
* trunk layers. An MTP head (or any expert block declared past the trunk) reports as a layer
|
||||
* beyond that count; without a slot its reports are refused and the heat engine never places
|
||||
* its experts. */
|
||||
int64_t n_layer = P.meta.n_layers;
|
||||
for (const WeightInfo& w : P.weights)
|
||||
if (w.decl.group.expert >= 0)
|
||||
@@ -600,15 +527,13 @@ int Ctx::bind_routing() {
|
||||
route_n_expert_ = n_expert;
|
||||
route_.assign((size_t)n_layer, RouteSlot{});
|
||||
|
||||
/* One pinned block for every bank, and ONE ROW A LAYER on the card. Pinned because the copy
|
||||
* has to be a real asynchronous DMA: a pageable destination makes the driver stage it through
|
||||
* its own buffer and, on some paths, synchronise -- which would put a host sync on the compute
|
||||
* stream, which is the one thing §5.5 says routing must never do.
|
||||
/* One pinned host block for all banks, and one row per layer on the card. Pinned so the copy
|
||||
* is a true async DMA; a pageable destination can make the driver synchronise, and routing
|
||||
* must never host-sync (spec §5.5).
|
||||
*
|
||||
* The card's rows are not banked: a pass's reports land in them and the pass's flush carries
|
||||
* them to the step's bank on the host, both on the compute stream, so the next pass's reports
|
||||
* queue behind the flush that reads them. A report's copy then names the same address every
|
||||
* step, which is what lets a recorded pass be replayed without rewriting it. */
|
||||
* The card rows are not banked: reports and the end-of-pass flush are both on the compute
|
||||
* stream, so the next pass's reports queue behind the flush. A report's copy then targets the
|
||||
* same address every step, so recorded passes replay unchanged. */
|
||||
const int64_t elems = n_layer * kRouteBanks * n_expert;
|
||||
const int64_t bytes = elems * (int64_t)sizeof(int32_t);
|
||||
const int64_t dbytes = n_layer * n_expert * (int64_t)sizeof(int32_t);
|
||||
@@ -629,17 +554,17 @@ int Ctx::bind_routing() {
|
||||
RouteSlot& r = route_[(size_t)l];
|
||||
for (int i = 0; i < kRouteBanks; ++i) {
|
||||
r.staging[i] = route_pool_ + ((int64_t)i * n_layer + l) * n_expert;
|
||||
r.step[i] = -1; /* never written, as against written at step 0 */
|
||||
r.step[i] = -1; /* never written (distinct from step 0) */
|
||||
}
|
||||
}
|
||||
/* Local: the host reads the bank on the strength of this event, but the bytes it reads were
|
||||
* put in host memory by the copy in front of it, whose own packets carry the system scope. */
|
||||
/* Local scope is enough: the preceding copy's own packets carry the system-scope release that
|
||||
* makes the bank visible to the host. */
|
||||
for (RadEvent& e : route_done_) RAD_TRY(rad_event_create_local(&e));
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* THE PASS'S HISTOGRAMS GO TO THE HOST IN ONE TRANSFER: the layers it reported, which are
|
||||
* contiguous rows of the bank, and then the bank's event. Called at the end of every pass. */
|
||||
/* Copies the pass's reported rows [route_lo_, route_hi_] to the step's host bank in one transfer
|
||||
* and records the bank's event. Called at the end of every pass. */
|
||||
int Ctx::route_flush() {
|
||||
if (route_bank_ < 0 || route_lo_ > route_hi_) return RAD_OK;
|
||||
const int64_t n_layer = (int64_t)route_.size();
|
||||
@@ -677,9 +602,8 @@ int Ctx::route_report_impl(int layer, const RadRouting* r, bool copy) {
|
||||
const int step = batch_ ? batch_->step : 0;
|
||||
const int bank = ((step % kRouteBanks) + kRouteBanks) % kRouteBanks;
|
||||
|
||||
/* The plugin computed these with ordinary declared ops. This is the handoff, not a
|
||||
* computation: we record the device buffers so the mover can be told what was wanted, and
|
||||
* nothing here reads them. */
|
||||
/* A handoff only: records the plugin's device buffers for the mover; nothing here reads
|
||||
* them. */
|
||||
s.routing = *r;
|
||||
s.reported = step;
|
||||
|
||||
@@ -691,37 +615,23 @@ int Ctx::route_report_impl(int layer, const RadRouting* r, bool copy) {
|
||||
n = route_n_expert_;
|
||||
}
|
||||
if (n > 0) {
|
||||
/* Asynchronous, on the compute stream, and nothing waits on it. The heat engine reads
|
||||
* it on the NEXT step, so placement decisions are always one step stale -- which for
|
||||
* heat-based promotion is irrelevant, because a hot expert is hot across many steps
|
||||
* (spec §5.5).
|
||||
/* Async on the compute stream; the host never waits. The heat engine reads it a step
|
||||
* later, which is fine since hot experts stay hot (spec §5.5).
|
||||
*
|
||||
* "NOTHING WAITS ON IT" IS TRUE OF THE HOST AND NOT OF THE STREAM. A copy is a blit
|
||||
* kernel, so it sits in the compute stream's order and every later kernel queues
|
||||
* behind it -- and a copy INTO HOST MEMORY must also make its writes visible to the
|
||||
* host before it completes, which waits out every write still crossing the link. With
|
||||
* the link carrying streamed experts, that release and the event record after it would
|
||||
* cost a routed layer several microseconds of an otherwise idle compute stream.
|
||||
*
|
||||
* So the layer's counts are copied WITHIN THE CARD, into its row of the step's bank,
|
||||
* and the rows this pass wrote cross to the host once, at the end of the pass
|
||||
* (route_flush). One card-local blit a routed layer is the whole cost -- and none when
|
||||
* the router wrote the row itself (rad_route_counts), which is the report naming it.
|
||||
*
|
||||
* MOVING IT OFF THE COMPUTE STREAM IS WORTH LESS THAN IT LOOKS. The second lane would
|
||||
* have to wait on this stream first, or the copy races the routing kernel that writes
|
||||
* `expert_count`. That is a lane_join a routed layer and an event record back on the
|
||||
* compute stream, which costs more than the blit it moves. */
|
||||
/* RECYCLING A BANK NOBODY READ IS THE RING BEING TOO SHALLOW FOR THIS RUN-AHEAD, and
|
||||
* it is the only way evidence is lost, since the drain takes every landed bank. It
|
||||
* is counted here, at the one place it can happen, rather than inferred from a total
|
||||
* that came up short. A second report of the SAME step is not a recycle: the drain
|
||||
* does not take a bank before its step is over, and `reports` carries the pass. */
|
||||
* The copy still sits in stream order, and a copy into host memory must wait out
|
||||
* every in-flight link write before completing. So each layer's counts are copied
|
||||
* within the card into its row, and the pass's rows cross to the host once at the
|
||||
* end (route_flush). No copy at all when the router wrote the row itself
|
||||
* (rad_route_counts). Moving the blit to the second lane would need a lane_join per
|
||||
* layer to avoid racing the routing kernel, which costs more than the blit. */
|
||||
/* Recycling an uncredited bank means the ring is shallower than the host's run-ahead;
|
||||
* it is the only way evidence is lost, so it is counted here. A second report of the
|
||||
* same step is not a recycle (`reports` counts it). */
|
||||
const bool again = s.step[bank] == step;
|
||||
if (s.step[bank] >= 0 && !again && !s.credited[bank]) ++route_dropped_;
|
||||
s.credited[bank] = false;
|
||||
if (route_bank_ != bank) {
|
||||
/* Empty: every pass flushes at its end. Not recorded if it were not. */
|
||||
/* Normally a no-op, since every pass flushes at its end; kept out of the tape. */
|
||||
if (rec_) tape_pause(true);
|
||||
const int rf = route_flush();
|
||||
if (rec_) tape_pause(false);
|
||||
@@ -741,34 +651,19 @@ int Ctx::route_report_impl(int layer, const RadRouting* r, bool copy) {
|
||||
s.reports[bank] = again ? s.reports[bank] + 1 : 1;
|
||||
s.step[bank] = step;
|
||||
|
||||
/* ==================== WHAT A FAULT LOOKS LIKE IN THIS HISTOGRAM ====================
|
||||
/* RADIANCE_DEBUG_ROUTING=<layer>: prints that layer's histogram for the first steps.
|
||||
* It synchronises the stream, so it is off by default.
|
||||
*
|
||||
* The sum of a layer's counts is the number of placements, which cannot exceed
|
||||
* n_tok * top_k. Negative counts, or totals orders of magnitude above that bound, say
|
||||
* something OUTSIDE this path wrote over the buffer rather than that the routing
|
||||
* kernel is wrong.
|
||||
*
|
||||
* The shape such an overrun takes is worth knowing, because it hides. A routed expert
|
||||
* plane is one row per (token, slot), so a buffer declared at max_tok rows is written
|
||||
* `rows * top_k` deep and runs past its declaration -- and the overrun only EXISTS
|
||||
* once rows * top_k exceeds the declared extent. A short prefill chunk and a decode
|
||||
* step are therefore clean while a full batch is not, and the discriminator is not
|
||||
* `n_tok == max_tok` but how far past the end the write reaches and what the arena
|
||||
* put there. core/runtime/issue.cpp carries the guard that refuses an operand reaching
|
||||
* past its declaration.
|
||||
*
|
||||
* RADIANCE_DEBUG_ROUTING: a composition fault in a routed model shows up here first.
|
||||
* It SYNCHRONISES THE STREAM, which is exactly what the copy above exists to avoid --
|
||||
* so it is an environment variable, off, and costs nothing when it is not set. The
|
||||
* value is the layer to print. */
|
||||
* A layer's counts sum to at most n_tok * top_k. Negative counts or far larger totals
|
||||
* mean something outside this path overwrote the buffer, e.g. an expert plane declared
|
||||
* at max_tok rows but written rows * top_k deep (refused by the operand guard in
|
||||
* issue.cpp). */
|
||||
static const char* dbg = std::getenv("RADIANCE_DEBUG_ROUTING");
|
||||
if (copy && dbg && layer == (int)std::strtol(dbg, nullptr, 10) && step < 3) {
|
||||
RAD_TRY(route_flush());
|
||||
rad_stream_sync(stream_);
|
||||
/* READ THE DEVICE BUFFER AGAIN, SYNCHRONOUSLY, and print both totals. The staging
|
||||
* copy is asynchronous and this print is the only reader of it, so a disagreement
|
||||
* here says the copy raced and an agreement says the histogram itself is what it
|
||||
* is. Debug-only, so the extra transfer costs nothing when the variable is off. */
|
||||
/* Also read the device buffer directly: a mismatch with the staged copy means the
|
||||
* copy raced. */
|
||||
std::vector<int32_t> direct((size_t)n, 0);
|
||||
int64_t dtot = 0;
|
||||
if (rad_memcpy_async(direct.data(), r->expert_count,
|
||||
@@ -795,28 +690,19 @@ int Ctx::route_report_impl(int layer, const RadRouting* r, bool copy) {
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* THE OLDEST LANDED BANK THIS LAYER HAS NOT BEEN CREDITED FOR, or -1 when there is none.
|
||||
*
|
||||
* OLDEST AND NOT NEWEST, because the caller drains in a loop and the heat engine decays a layer's
|
||||
* plane on every observation. Fed newest-first, a burst would apply the most recent decay to the
|
||||
* oldest evidence and rank the plane by an order the device never produced.
|
||||
*
|
||||
* A BANK IS SKIPPED UNTIL ITS COPY HAS COMPLETED. `step[b]` is stamped when the copy is ISSUED,
|
||||
* which on a long prefill chunk is many steps before the device reaches it; reading the staging
|
||||
* then would hand back whatever the bank's previous occupant left in it, which is a histogram from
|
||||
* kRouteBanks steps ago wearing this step's number. The event is the only thing that separates
|
||||
* the two, so it is queried rather than assumed -- and that also excludes a half-written bank,
|
||||
* which a mid-step reader would otherwise see.
|
||||
*
|
||||
* A BANK OF A STEP STILL BEING ISSUED IS SKIPPED TOO, landed or not: a later pass of that step can
|
||||
* still report into it. See `before_step` in ctx.h.
|
||||
*/
|
||||
void Ctx::mark_credited(int layer, int bank) {
|
||||
if (layer < 0 || (size_t)layer >= route_.size()) return;
|
||||
if (bank < 0 || bank >= kRouteBanks) return;
|
||||
route_[(size_t)layer].credited[bank] = true;
|
||||
}
|
||||
|
||||
/* The oldest landed bank in (after_step, before_step) for this layer, or -1.
|
||||
*
|
||||
* Oldest first, because the heat engine decays a layer's plane on every observation and must see
|
||||
* them in device order. A bank is skipped until its event says the copy completed: `step[b]` is
|
||||
* stamped at issue, and the staging would otherwise still hold the previous occupant's histogram.
|
||||
* A bank of a step still being issued is skipped too (see `before_step` in ctx.h).
|
||||
*/
|
||||
int Ctx::next_histogram(int layer, int after_step, int before_step, int8_t* landed) const {
|
||||
if (layer < 0 || (size_t)layer >= route_.size()) return -1;
|
||||
const RouteSlot& s = route_[(size_t)layer];
|
||||
@@ -869,23 +755,16 @@ int Ctx::bind_profiling() {
|
||||
prof_wait_ms_.assign(program_->ops.size(), 0.0);
|
||||
if (!profiling_) return RAD_OK;
|
||||
|
||||
/* Printed, not buried in a doc. Anyone reading a profiled run's numbers has to see this on the
|
||||
* same terminal that produced them. */
|
||||
RAD_WARN("per-op timing is ON. It restores synchronisations that change the mover's slot "
|
||||
"supply, so THIS RUN IS NOT COMPARABLE against an unprofiled one (spec §16). "
|
||||
"Anything being measured across builds runs without it.");
|
||||
RAD_WARN("per-op timing is on; it adds synchronisations that change the mover's slot supply, "
|
||||
"so this run is not comparable with an unprofiled one (spec §16)");
|
||||
|
||||
/* A fixed ring, allocated here, because the step path does not allocate. 8192 pairs covers a
|
||||
* 64-layer model at ~20 ops a layer with room for speculation; past that we stop timing and
|
||||
* say so, rather than growing a vector inside a step.
|
||||
/* A fixed ring, since the step path does not allocate. 8192 pairs covers a 64-layer model at
|
||||
* ~20 ops a layer with room for speculation; overflow stops timing with a warning.
|
||||
*
|
||||
* CARD-LOCAL EVENTS, NOT HOST-WAIT ONES. A host-wait record takes an interrupt signal, of which
|
||||
* a process has a few thousand, and every pair recorded in a step holds two until the pair is
|
||||
* recorded again a step later: a prefill step on a large model records more pairs than that
|
||||
* across the ranks, and the engine's own staging event then has no signal left to take. The
|
||||
* host never waits on these one at a time -- profile_collect waits for the stream once -- and
|
||||
* a card-scope release keeps the records from waiting out writes still on their way to the
|
||||
* host, which would be charged to the op they bracket. */
|
||||
* Card-local events: a host-wait event takes one of a process's few thousand interrupt
|
||||
* signals, and a large prefill step would exhaust them. The host only waits on the stream
|
||||
* (profile_collect), and a card-scope release does not wait out in-flight host writes that
|
||||
* would be charged to the bracketed op. */
|
||||
const size_t cap = 8192;
|
||||
prof_ring_.resize(cap);
|
||||
for (size_t i = 0; i < cap; ++i) {
|
||||
@@ -899,18 +778,15 @@ int Ctx::bind_profiling() {
|
||||
}
|
||||
|
||||
void Ctx::profile_collect() {
|
||||
/* This is the synchronisation the caveat above is about. It is here, at the end of the step,
|
||||
* rather than per launch, so at least the ordering inside a step is undisturbed -- but the
|
||||
* mover's slot supply still sees a step boundary it would not otherwise see. */
|
||||
/* The profiling sync, once at the end of the step so ordering within the step is
|
||||
* undisturbed. */
|
||||
if (prof_n_ > 0) {
|
||||
/* Lane 1 is already joined into the compute stream (end of step), so that stream finishing
|
||||
* is every bracketed launch finishing. */
|
||||
++n_host_syncs_; /* counted, so the caveat is a number and not a claim */
|
||||
/* Lane 1 is already joined into the compute stream, so this covers every launch. */
|
||||
++n_host_syncs_;
|
||||
if (rad_stream_sync(stream_) < 0) prof_n_ = 0;
|
||||
}
|
||||
/* The idle time before each op, per lane: the first op a lane runs in the step has nothing
|
||||
* before it on that lane, and the gap from the last step is mostly this collection's own
|
||||
* synchronisation, so it is not charged. */
|
||||
/* Idle time before each op, per lane. A lane's first op in the step is not charged: its gap
|
||||
* is mostly this collection's own sync. */
|
||||
const ProfSlot* prev[2] = { nullptr, nullptr };
|
||||
for (size_t i = 0; i < prof_n_; ++i) {
|
||||
ProfSlot& s = prof_ring_[i];
|
||||
@@ -937,16 +813,16 @@ void Ctx::dump_profile() const {
|
||||
if (!program_) { RAD_WARN("per-op timing: the context has already been shut down"); return; }
|
||||
|
||||
fprintf(stderr,
|
||||
"\nper-op timing, rank %d. NOT COMPARABLE against an unprofiled run:\n"
|
||||
"\nper-op timing, rank %d. Not comparable with an unprofiled run:\n"
|
||||
"enabling this restores synchronisations that change the mover's slot supply.\n"
|
||||
"A row marked `host` was timed on the HOST CLOCK around a host-site launch and\n"
|
||||
"A row marked `host` was timed on the host clock around a host-site launch and\n"
|
||||
"includes everything that call waited on -- page faults, link reads. The rest are\n"
|
||||
"device event pairs around a kernel. `wait us` is how long, a call, the op's lane\n"
|
||||
"sat idle before it started -- stream waits and issue delays, in no op's time.\n\n"
|
||||
" %10s %12s %10s %5s %10s %10s %s\n", rank_, "calls", "total ms", "us/call", "site",
|
||||
"join us", "wait us", "op / geometry");
|
||||
|
||||
/* Slowest first: the only ordering anybody reads this table in. */
|
||||
/* Slowest first. */
|
||||
std::vector<size_t> order;
|
||||
for (size_t i = 1; i < prof_calls_.size(); ++i) if (prof_calls_[i]) order.push_back(i);
|
||||
std::sort(order.begin(), order.end(),
|
||||
@@ -960,10 +836,8 @@ void Ctx::dump_profile() const {
|
||||
if (ho && i < prof_join_ms_.size())
|
||||
std::snprintf(jbuf, sizeof jbuf, "%10.2f",
|
||||
prof_join_ms_[i] * 1000.0 / (double)prof_calls_[i]);
|
||||
/* The op's position and its first weight name the LAYER: every layer's instance of an
|
||||
* op declares the same geometry, so without them sixty rows read alike and a per-layer
|
||||
* cost -- residency, a pooled expert streamed by one layer and not the next -- cannot be
|
||||
* tied to anything. */
|
||||
/* The op index and first weight identify the layer, since every layer's instance has
|
||||
* the same geometry. */
|
||||
const char* wname = !o.weights.empty() && o.weights[0] < program_->weights.size()
|
||||
? program_->weights[o.weights[0]].name.c_str() : "-";
|
||||
const double wait = i < prof_wait_ms_.size() ? prof_wait_ms_[i] : 0.0;
|
||||
@@ -980,26 +854,19 @@ void Ctx::dump_profile() const {
|
||||
|
||||
/* ================================================================== the step driver */
|
||||
|
||||
/* LAZY, AND THAT IS THE POINT: an architecture that never asks for a second lane must take the
|
||||
* same code path an architecture with one lane would take if this feature did not exist, so that
|
||||
* "the lane costs nothing when unused" is a property of the source rather than a claim about a
|
||||
* measurement. Building the stream eagerly would make it one -- and one that is hard to establish,
|
||||
* because a second stream's cost is small enough to sit inside the run-to-run spread a warming
|
||||
* part produces. */
|
||||
/* Lazy, so an architecture that never asks for a second lane runs exactly the single-lane code
|
||||
* path. */
|
||||
int Ctx::lane_init() {
|
||||
if (lane1_) return RAD_OK;
|
||||
RAD_TRY(rad_dev_set(device_));
|
||||
RAD_TRY(rad_stream_create(&lane1_, 0));
|
||||
own_lane1_ = true;
|
||||
/* Local: a lane join orders one card's two queues and nothing else reads through it. */
|
||||
/* Local scope: a lane join only orders this card's two queues. */
|
||||
for (int i = 0; i < 2; ++i)
|
||||
if (!lane_ev_[i]) RAD_TRY(rad_event_create_local(&lane_ev_[i]));
|
||||
/* A NEW LANE STARTS BEHIND EVERYTHING LANE 0 HAS ISSUED. Its first use is mid-step, and the
|
||||
* join an architecture puts in front of it -- rad_lane_join(0, 1), then rad_lane(1) -- found no
|
||||
* lane 1 to order and returned without doing anything. Unordered, the first op on the new
|
||||
* stream reads lane 0's output before lane 0 has written it: on Qwen-Image's two-rank pass
|
||||
* the first picture after startup took its first all-reduce of stale rows and came out a
|
||||
* different picture, every later one the right one. */
|
||||
/* A new lane starts behind everything lane 0 has issued. Its first use is mid-step, where a
|
||||
* preceding rad_lane_join(0, 1) found no lane 1 and did nothing, so without this the first op
|
||||
* on the new stream could read lane 0's output before it is written. */
|
||||
RAD_TRY(rad_event_record(lane_ev_[0], stream_));
|
||||
RAD_TRY(rad_event_wait(lane1_, lane_ev_[0]));
|
||||
return RAD_OK;
|
||||
@@ -1016,9 +883,8 @@ int Ctx::set_lane(int lane) {
|
||||
int Ctx::lane_join(int from, int to) {
|
||||
if (from == to) return RAD_OK;
|
||||
if (from < 0 || from > 1 || to < 0 || to > 1) return RAD_E_INVAL;
|
||||
/* Nothing was ever issued on lane 1, so there is nothing to order against -- and a lane 1
|
||||
* built later starts behind lane 0 (lane_init). This is the arm every unpipelined step takes
|
||||
* at the end of run_step, and it must not build a stream. */
|
||||
/* No lane 1 yet: nothing to order, and a later lane 1 starts behind lane 0 (lane_init). Every
|
||||
* single-lane step takes this at the end of run_step; it must not build a stream. */
|
||||
if (!lane1_) return RAD_OK;
|
||||
RadStream fs = from ? lane1_ : stream_, ts = to ? lane1_ : stream_;
|
||||
RAD_TRY(rad_event_record(lane_ev_[from], fs));
|
||||
@@ -1030,9 +896,17 @@ int Ctx::lane_join(int from, int to) {
|
||||
/* ================================================================== recorded passes */
|
||||
/* See "recorded passes" in ctx.h. */
|
||||
|
||||
/* The key below reads every RadBatch field a pass's shape or arguments can depend on, by hand. A
|
||||
* field added to RadBatch changes its size: decide whether the key must read it, then update the
|
||||
* size here. */
|
||||
static_assert(sizeof(void*) != 8 || sizeof(RadBatch) == 312,
|
||||
"RadBatch changed: check that Ctx::pass_key reads every new field a pass depends on");
|
||||
static_assert(sizeof(void*) != 8 || sizeof(RadKVGroupBatch) == 72,
|
||||
"RadKVGroupBatch changed: check that Ctx::pass_key reads every new field");
|
||||
|
||||
uint64_t Ctx::pass_key(const RadBatch* b) const {
|
||||
/* An encoder pass is shaped by its media, and a pass that carries encoder rows issues the
|
||||
* scatter that puts them in place only when it has some: neither repeats as a tape would. */
|
||||
/* Not recordable: encoder passes are shaped by their media, and passes carrying encoder rows
|
||||
* issue the scatter only when they have some. */
|
||||
if (b->enc || b->n_mm_rows > 0) return 0;
|
||||
/* A generator pass is shaped by what RadBatch::gen_b carries, which no key below reads. */
|
||||
if (b->gen) return 0;
|
||||
@@ -1059,7 +933,6 @@ uint64_t Ctx::pass_key(const RadBatch* b) const {
|
||||
mix((uint64_t)k.state_index_pitch); mix((uint64_t)k.block_size); mix((uint64_t)k.max_blocks);
|
||||
}
|
||||
mix((uint64_t)level_);
|
||||
mix(w_tmpl_epoch_);
|
||||
mix(dense_epoch_);
|
||||
mix(domain_epoch_.load(std::memory_order_relaxed));
|
||||
ptr(arena_.base());
|
||||
@@ -1142,18 +1015,18 @@ int Ctx::record_pass(const RadBatch* b, uint64_t key, PassTape* out) {
|
||||
return 1;
|
||||
}
|
||||
|
||||
/* WHICH DISPATCHES OF A RECORDED PASS CAN START BEFORE THE ONES IN FRONT OF THEM FINISH.
|
||||
/* Marks which dispatches of a recorded pass may start before the ones ahead of them finish.
|
||||
*
|
||||
* Walked once, in queue order, per queue: the ops launched since the queue last ordered a packet
|
||||
* are in flight together, and the next op may join them when it reads nothing they write and
|
||||
* writes nothing they read or write. Anything the walk cannot see into orders its packet: the
|
||||
* dispatch after an event, every dispatch after an op's first (an op's own dispatches depend on
|
||||
* each other), a dispatch no op owns (a routing copy), and an opaque op on either side. A run is
|
||||
* cut at kTapeOverlapRun, the bound the backend reclaims its argument slots on.
|
||||
* One walk per queue, in order. The ops since the queue's last ordered packet are in flight
|
||||
* together; the next op may join them if it reads nothing they write and writes nothing they
|
||||
* read or write. Ordered regardless: the dispatch after an event, every dispatch after an op's
|
||||
* first (an op's dispatches depend on each other), a dispatch no op owns (e.g. a routing copy),
|
||||
* and opaque ops on either side. A run is cut at kTapeOverlapRun, the bound on which the backend
|
||||
* reclaims argument slots.
|
||||
*
|
||||
* The host work between played stretches needs nothing here. A host op joins the device work it
|
||||
* depends on before it runs, and whatever a stretch of host work puts on a queue -- a table patch,
|
||||
* a mover wait -- makes the backend order the next played packet on that queue itself. */
|
||||
* Host work between played stretches needs nothing here: a host op joins its dependencies, and
|
||||
* anything host work puts on a queue (table patch, mover wait) makes the backend order the next
|
||||
* played packet on that queue. */
|
||||
int Ctx::haz_mark(PassTape& t) {
|
||||
const int n = tape_len(t.dev);
|
||||
if (n < 0) return n;
|
||||
@@ -1187,8 +1060,8 @@ int Ctx::haz_mark(PassTape& t) {
|
||||
Q* q = nullptr;
|
||||
for (Q& x : qs) if (x.id == qid) { q = &x; break; }
|
||||
if (!q) { qs.push_back(Q{}); q = &qs.back(); q->id = qid; }
|
||||
/* An event's packet, and the dispatch after it is ordered too: a wait is complete only
|
||||
* once the event it names is, and nothing after it may start before that. */
|
||||
/* An event packet: the next dispatch is ordered, since nothing after a wait may start
|
||||
* before its event completes. */
|
||||
if (kind != 0) { q->infl.clear(); q->opaque = true; q->run = 0; continue; }
|
||||
++t.dispatches;
|
||||
|
||||
@@ -1210,7 +1083,7 @@ int Ctx::haz_mark(PassTape& t) {
|
||||
++t.unordered;
|
||||
continue;
|
||||
}
|
||||
/* Ordered: everything before it has finished, and it is what is in flight now. */
|
||||
/* Ordered: everything before it has finished; it starts a new in-flight set. */
|
||||
const int32_t own = part_of[(size_t)i];
|
||||
q->infl.clear();
|
||||
if (own >= 0) q->infl.push_back(own);
|
||||
@@ -1220,7 +1093,7 @@ int Ctx::haz_mark(PassTape& t) {
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* Two recordings of one key, compared: the backend's records, and the host work between them. */
|
||||
/* Compares two recordings of one key: the backend's records and the host work between them. */
|
||||
bool Ctx::tapes_agree(const PassTape& a, const PassTape& b, std::string* why) {
|
||||
if (a.steps.size() != b.steps.size()) {
|
||||
*why = fmt("%zu stretches against %zu", a.steps.size(), b.steps.size());
|
||||
@@ -1235,6 +1108,11 @@ bool Ctx::tapes_agree(const PassTape& a, const PassTape& b, std::string* why) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
if (a.host.size() != b.host.size() || a.route.size() != b.route.size()) {
|
||||
*why = fmt("%zu host ops and %zu routing reports against %zu and %zu", a.host.size(),
|
||||
a.route.size(), b.host.size(), b.route.size());
|
||||
return false;
|
||||
}
|
||||
for (size_t i = 0; i < a.host.size(); ++i) {
|
||||
const TapeHost& x = a.host[i];
|
||||
const TapeHost& y = b.host[i];
|
||||
@@ -1343,7 +1221,7 @@ int Ctx::play_pass(PassTape& t) {
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* THE PASS: played from its tape, or issued -- and recorded, or checked against its tape. */
|
||||
/* Runs one pass: played from its tape, or issued live (and possibly recorded or audited). */
|
||||
int Ctx::run_pass(const RadBatch* b) {
|
||||
const auto bump = [](std::atomic<int64_t>& c) { c.fetch_add(1, std::memory_order_relaxed); };
|
||||
scratch_cur_[0] = scratch_cur_[1] = 0;
|
||||
@@ -1368,8 +1246,8 @@ int Ctx::run_pass(const RadBatch* b) {
|
||||
|
||||
if (t) {
|
||||
bump(pc_audited_);
|
||||
/* The check: issue the pass for real, recording it, and compare. The first comparison
|
||||
* comes before the tape is ever played, and then one every kAuditPlays plays. */
|
||||
/* Audit: issue the pass live, recording it, and compare. Runs before the first play and
|
||||
* then every kAuditPlays plays. */
|
||||
PassTape fresh;
|
||||
if (!record_pass(b, key, &fresh)) return RAD_OK;
|
||||
std::string why;
|
||||
@@ -1391,13 +1269,9 @@ int Ctx::run_pass(const RadBatch* b) {
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* A KEY IS RECORDED THE SECOND TIME IT IS SEEN, so a pass that never recurs -- a prefill
|
||||
* chunk, whose token count and positions are its own -- costs no recording and does not push
|
||||
* a tape that will be played out of the least-recently-used set. A DECODE pass recurs by
|
||||
* construction: the same shape runs every step until a sequence's context crosses its bound's
|
||||
* bucket, and then the new key runs every step after that. Seen-once is a whole live issue
|
||||
* spent learning that, at every crossing, so a decode pass is recorded the first time. The
|
||||
* audit before its first play is unchanged. */
|
||||
/* Non-decode keys are recorded on their second sighting, so one-off passes (prefill chunks)
|
||||
* cost no recording and do not evict useful tapes. Decode passes recur every step until a
|
||||
* bound crosses its bucket, so they are recorded on first sight. */
|
||||
if (b->phase != RAD_PHASE_DECODE && !tape_seen(key)) {
|
||||
bump(pc_first_);
|
||||
arch_step_(this, b);
|
||||
@@ -1427,36 +1301,31 @@ int Ctx::run_step(const RadBatch* b) {
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
|
||||
/* BEFORE THE RESIDENCY SYNC: a stager may give back weights it published for this pass when
|
||||
* it turns the pass down (runtime/stager.h), and the sync is what carries that into the
|
||||
* tables the pass resolves. */
|
||||
/* Before the residency sync, which carries any weights a declining stager gave back into the
|
||||
* tables (runtime/stager.h). */
|
||||
staging_ = stager_ != nullptr && stager_->begin_pass(b);
|
||||
|
||||
/* The mover relocates between steps, never during one. Honouring WeightInfo::generation here
|
||||
* costs one relaxed atomic load per step instead of one per weight per issue. */
|
||||
if (weights_dirty_.exchange(false, std::memory_order_acq_rel))
|
||||
bind_weights(/*refresh_only=*/true);
|
||||
sync_residency();
|
||||
|
||||
batch_ = b;
|
||||
step_status_ = RAD_OK;
|
||||
step_fail_.clear();
|
||||
prof_n_ = 0;
|
||||
in_step_ = true;
|
||||
{
|
||||
const int rc = run_pass(b);
|
||||
if (rc < 0 && step_status_ >= 0) step_status_ = rc;
|
||||
}
|
||||
|
||||
/* EVERY LANE JOINS BACK BEFORE THE STEP ENDS, whatever the architecture did or forgot to do.
|
||||
* The engine synchronises the COMPUTE stream to know a step is finished; work still queued on
|
||||
* lane 1 would be read by the sampler, or freed under, while it was in flight. Ordering lane 0
|
||||
* behind lane 1 here costs one event record and one wait on a step that never used lane 1 --
|
||||
* and it means a plugin cannot leave the runtime in a state where that is possible. */
|
||||
/* Always join lane 1 back into lane 0 before the step ends: the engine syncs only the
|
||||
* compute stream, so work left on lane 1 could be read by the sampler or freed while in
|
||||
* flight. */
|
||||
lane_ = 0;
|
||||
lane_join(1, 0); /* a no-op, and allocates nothing, when lane 1 is unbuilt */;
|
||||
/* Behind the join, so the compute stream is behind every reader of what the stager published;
|
||||
* and whatever the pass's status, because a staged weight must never outlive its pass. */
|
||||
{
|
||||
const int lj = lane_join(1, 0); /* no-op when lane 1 is unbuilt */
|
||||
if (lj < 0 && step_status_ >= 0) step_status_ = lj;
|
||||
}
|
||||
/* After the join, so the compute stream is behind every reader of staged weights; regardless
|
||||
* of status, because a staged weight must never outlive its pass. */
|
||||
if (staging_) {
|
||||
const int se = stager_->end_pass(stream_);
|
||||
if (se < 0 && step_status_ >= 0) step_status_ = se;
|
||||
@@ -1467,17 +1336,13 @@ int Ctx::run_step(const RadBatch* b) {
|
||||
if (rf < 0 && step_status_ >= 0) step_status_ = rf;
|
||||
}
|
||||
|
||||
in_step_ = false;
|
||||
if (profiling_) profile_collect();
|
||||
flush_issued();
|
||||
return step_status_;
|
||||
}
|
||||
|
||||
/* WHICH DECLARED OPS THE RUN PHASE HAS ACTUALLY ISSUED, copied out of the per-step plans into the
|
||||
* Program the graph dump reads. Walks only the ops not yet seen issued and drops each one as it
|
||||
* fires, so the cost falls away within a few steps to the ops that have never fired -- and those
|
||||
* are exactly what a reader of this field is looking for. Shrinking in place, so no allocation on
|
||||
* the step path. */
|
||||
/* Copies OpPlan::issued into the Program for the graph dump. Walks only ops not yet seen issued
|
||||
* and compacts the list in place (no allocation). */
|
||||
void Ctx::flush_issued() {
|
||||
size_t w = 0;
|
||||
for (size_t r = 0; r < unflushed_.size(); ++r) {
|
||||
|
||||
+272
-393
@@ -1,28 +1,19 @@
|
||||
/* ctx.h -- the run phase. Ordinary C++ with one rule: it may only issue handles obtained during
|
||||
* declare (spec §3.2). Nothing else is constrained, and its whole job is to be cheap.
|
||||
* declare (spec §3.2).
|
||||
*
|
||||
* Everything expensive already happened. Declare resolved every op against the kernel hierarchy
|
||||
* per band and per domain, the buffer plan sized one arena for the worst step, and the planner
|
||||
* assigned every weight a tier and a site. What is left for a step is: index a bucket table with
|
||||
* an integer, copy a tensor template per operand, patch in the pointers, and launch. The per-issue
|
||||
* work is filling a struct we already own, not constructing one.
|
||||
* Declare already resolved every op against the kernel hierarchy per band and domain, the buffer
|
||||
* plan sized one arena for the worst step, and the planner assigned every weight a tier and site.
|
||||
* A step indexes a bucket table, copies a tensor template per operand, patches in pointers and
|
||||
* launches.
|
||||
*
|
||||
* COST. An issue is single-digit nanoseconds. Nearly all of it is the RadTensor template copies at
|
||||
* 112 bytes each; the band scan is one or two compares off a cache line and the RadArgs patch is a
|
||||
* single store. tests/runtime_test.cpp times it and prints it, so the number is checkable rather
|
||||
* than claimed, and it is a tripwire -- a hundredfold miss means somebody put an allocation or a
|
||||
* map lookup back on this path.
|
||||
* Cost: an issue is single-digit nanoseconds, mostly the 112-byte RadTensor template copies.
|
||||
* tests/runtime_test.cpp times it; a hundredfold miss means an allocation or map lookup got onto
|
||||
* this path. A 64-layer model issues ~1280 ops a decode step, ~10 us of core time; launching them
|
||||
* through hipLaunchKernel would cost 1-2 ms of driver time, which the device backend avoids by
|
||||
* writing AQL packets itself (spec §3.2).
|
||||
*
|
||||
* At a 64-layer model issuing ~20 ops a layer that is ~1280 issues, so order ten microseconds of
|
||||
* CORE time per decode step. Spec §3.2 accepts roughly 1-2 ms of launch overhead per step at 64
|
||||
* layers; the rest of that budget is the driver's own per-launch dispatch cost -- order 1 us per
|
||||
* hipLaunchKernel, which is what 1280 launches actually costs -- and it is not ours to spend. It is
|
||||
* also what HIP-graph capture would attack if v1 wanted it, which §3.2 says is a change to that
|
||||
* section and not to the ABI. The core is therefore not where the step budget goes, against a
|
||||
* Python engine's 10-20 ms of the same thing.
|
||||
*
|
||||
* A residency table with a pending event adds one rad_event_wait -- once per weight per
|
||||
* GENERATION, not per issue, which is why residency.h makes the mover bump it.
|
||||
* A pending residency event adds one rad_event_wait per weight per generation, not per issue
|
||||
* (residency.h).
|
||||
*/
|
||||
#pragma once
|
||||
#include "../rad_core.h"
|
||||
@@ -39,140 +30,107 @@
|
||||
#include <vector>
|
||||
#include <unordered_map>
|
||||
|
||||
/* RadCtx is opaque in the ABI: rad_runtime.h forward-declares it and nothing else. Completing it
|
||||
* here as an empty base gives a well-defined static_cast from the C handle to the C++ object,
|
||||
* instead of a reinterpret_cast that merely happens to work. The run phase is the only component
|
||||
* that ever holds one, so this is the right place for the definition. */
|
||||
/* RadCtx is opaque in the ABI (rad_runtime.h only forward-declares it). Completing it as an empty
|
||||
* base makes the C handle to C++ object conversion a well-defined static_cast. */
|
||||
struct RadCtx { };
|
||||
|
||||
namespace rad {
|
||||
|
||||
class Registry;
|
||||
struct XpState;
|
||||
struct XpLayer;
|
||||
|
||||
/* The widest op in the conventional vocabulary is gdn_conv_prep at sixteen operands, with
|
||||
* gdn_recurrent_update behind it at fourteen -- both grew when the two kernel plugins' schemas
|
||||
* were reconciled (docs/OPS.md, "How a schema is written"). Thirty-two leaves room for an
|
||||
* architecture plugin's private ops without putting a variable-length array on the hot path. */
|
||||
/* The widest conventional op is gdn_conv_prep at sixteen operands (docs/OPS.md). Thirty-two leaves
|
||||
* room for an architecture plugin's private ops without a variable-length array on the hot path. */
|
||||
constexpr int MAX_OPERANDS = 32;
|
||||
|
||||
typedef void (*ArchStepFn)(RadCtx*, const RadBatch*);
|
||||
|
||||
/* "[shape]/[stride]" of a tensor's live dimensions, for diagnostics. */
|
||||
std::string tensor_shape_str(const RadTensor& t);
|
||||
|
||||
/* ------------------------------------------------------------------ the issue plan */
|
||||
/* One resolved (op, band, domain) with everything that does not change per issue already filled
|
||||
* in: the geometry view the kernel reads its parameters out of, the scratch pointer, the instance
|
||||
* init() returned, the rank and the world size. Per issue we set `t` and `n_t` and call `launch`.
|
||||
/* One resolved (op, band, domain) with everything that does not change per issue filled in: the
|
||||
* geometry view, the scratch pointer, the instance init() returned, rank and world size. Per issue
|
||||
* we set `t` and `n_t` and call `launch`.
|
||||
*
|
||||
* `launch` is hoisted out of row->info so the fast path chases one pointer rather than two, and
|
||||
* `row` is diagnostics only -- it is read when a launch fails and never otherwise. */
|
||||
* `launch` is hoisted out of row->info to save a pointer chase; `row` is read only when a launch
|
||||
* fails. */
|
||||
struct IssuePlan {
|
||||
RadArgs args{};
|
||||
RadLaunchFn launch = nullptr;
|
||||
const KernelRow* row = nullptr;
|
||||
/* The parameters a launch that holds the link is handed: the geometry's and `link_gate`, for a
|
||||
* row that ends the hold itself; null for every other. Only such a launch takes them, so a
|
||||
* step that holds nothing -- every decode step -- never pays the kernel's read of the word. */
|
||||
/* For a row that ends the link hold itself: the geometry's parameters plus `link_gate`. Null
|
||||
* for every other row, so a step that holds nothing (every decode step) never reads the word. */
|
||||
const RadParam* gate_p = nullptr;
|
||||
int gate_n_p = 0;
|
||||
/* Resolved::ranged_div: an issued value this does not divide is refused. 0 for most rows. */
|
||||
int64_t ranged_div = 0;
|
||||
};
|
||||
|
||||
/* Per declared op. Trivially copyable on purpose: the bucket table and the issue plans live in two
|
||||
* flat Ctx-owned arrays and this holds offsets into them, so a step touches one small dense record
|
||||
* per op instead of walking two vectors' worth of indirection. */
|
||||
/* Per declared op. Trivially copyable: it holds offsets into two flat Ctx-owned arrays (bucket
|
||||
* table, issue plans), so a step touches one small dense record per op. */
|
||||
struct OpPlan {
|
||||
const OpInfo* info = nullptr;
|
||||
int32_t band_off = 0; /* into Ctx::band_table_ */
|
||||
int32_t n_bands = 0;
|
||||
int32_t plan_off = 0; /* into Ctx::issue_table_, band * RAD_N_DOMAINS + domain */
|
||||
/* The schema's operand count, copied here so the arity check is a compare against a hot field
|
||||
* rather than two pointer chases into a cold OpInfo. -1 when the op has no schema. */
|
||||
/* The schema's operand count, cached so the arity check avoids a cold OpInfo. -1 when the op
|
||||
* has no schema. */
|
||||
int32_t n_opd_schema = -1;
|
||||
bool issued = false; /* did the run phase ever issue it (spec §16's graph dump) */
|
||||
/* IS THIS OP A COLLECTIVE -- i.e. does issuing it put bytes on the interconnect? Set once at
|
||||
* bind, from the rows it resolved to (rad_kernel_collective) and the conventional all_reduce,
|
||||
* so the issue path tests a predicted branch and not a string. The weight stager's copies
|
||||
* share the link, and give way to it while it runs (Ctx::issue_body). */
|
||||
/* Whether issuing it puts bytes on the interconnect. Set at bind from the resolved rows
|
||||
* (rad_kernel_collective) and the conventional all_reduce. The weight stager's copies share
|
||||
* the link and give way to it while it runs (Ctx::issue_body). */
|
||||
bool collective = false;
|
||||
/* The conventional all_reduce, whose `n` IS the message's element count -- the one collective
|
||||
* the link bill can be charged for without guessing its wire format. The link is shared with
|
||||
* the expert mover, so separating "how much of it is the all-reduce" needs this counted. */
|
||||
/* The conventional all_reduce, whose `n` is the message's element count, so its link bytes
|
||||
* can be counted (ar_bytes) apart from the expert mover's. */
|
||||
bool billed = false;
|
||||
};
|
||||
|
||||
/* ------------------------------------------------------------------ routing handoff */
|
||||
/* A RING OF STAGING BANKS, indexed by step, so that the heat engine reads a histogram the device
|
||||
* actually wrote rather than one still queued behind it.
|
||||
/* A ring of routing-histogram staging banks, indexed by step, so the heat engine reads histograms
|
||||
* the device has actually written.
|
||||
*
|
||||
* TWO BANKS ARE NOT ENOUGH AND THE REASON IS THE HOST'S RUN-AHEAD. The dispatch that consumes
|
||||
* these runs before the step is issued and every issue path returns immediately, so on a long
|
||||
* prefill chunk -- most of a second of device time -- the host reaches the end of the prompt while
|
||||
* the card is still on its first chunks. With two banks, the copy for step S is overwritten by the
|
||||
* one for S+2 long before the device has reached either, the freshest bank always holds a copy in
|
||||
* flight, and the engine skips the layer: over 41 chunks of 2048 tokens, two banks credit 79
|
||||
* layer-histograms and skip 3800 as not yet landed.
|
||||
* The ring must be as deep as the host's run-ahead. Issue returns immediately, so on a long
|
||||
* prefill the host can be many steps ahead of the card; a shallow ring overwrites a bank before
|
||||
* its copy lands, and the layer's evidence is lost. The drain credits every landed bank, not only
|
||||
* the newest.
|
||||
*
|
||||
* THE BYTES ARE NOT THE PROBLEM -- the device does execute every copy, in order, spread over its
|
||||
* own progress. A shallow ring overwrites them before anyone reads them. A ring as deep as the
|
||||
* run-ahead keeps each one until it is credited, and the dispatch drains every landed bank rather
|
||||
* than only the newest, so a burst of host steps followed by a wait still credits every histogram
|
||||
* the card produced in between.
|
||||
*
|
||||
* DEPTH IS A MEMORY-FOR-EVIDENCE TRADE AND IT IS CHEAP: one int32 an expert a bank a layer, which
|
||||
* on a 49-layer 254-expert plane is about 50 KiB a bank. What it cannot do is exceed the run-ahead
|
||||
* for free, so the engine counts what it still loses and prints it -- see the routing-evidence
|
||||
* line at shutdown. */
|
||||
* Cost is one int32 per expert per layer per bank (~50 KiB a bank for 49 layers x 254 experts).
|
||||
* Losses still happen past the ring's depth and are counted (route_dropped) and printed at
|
||||
* shutdown. */
|
||||
static const int kRouteBanks = 32;
|
||||
|
||||
struct RouteSlot {
|
||||
RadRouting routing{};
|
||||
int32_t* staging[kRouteBanks] = {}; /* this layer's row of the bank's host copy */
|
||||
int step[kRouteBanks] = {};
|
||||
/* HOW MANY TIMES THIS LAYER REPORTED INTO THAT BANK, which is not always once. A bank is
|
||||
* indexed by the step, so every report a layer makes WITHIN one step lands in the same one
|
||||
* and overwrites the last -- and a speculative draft head reports once per draft pass, n_spec
|
||||
* times a step. Uncredited, the heat engine sees a fraction of that layer's routing and prices
|
||||
* its experts accordingly, which starves a draft head's resident set relative to every other
|
||||
* layer's. The histogram itself cannot be summed here -- it arrives by an async copy off the
|
||||
* compute stream -- but the COUNT is free, and one pass credited n times is the right
|
||||
* expectation when the passes route from the same distribution.
|
||||
*
|
||||
* THIS IS AN ACCOUNTING FIX, NOT A PERFORMANCE LEVER, and the distinction is the useful part.
|
||||
* Crediting the passes raises that layer's resident expert count and tightens the spread
|
||||
* across layers, and the step time does not move.
|
||||
*
|
||||
* WHY IT IS NULL IS THE THING TO REMEMBER: RESIDENCY AGAINST TIME IS CONVEX, STEEPLY. A cache
|
||||
* whose hot set is already in has nothing left to gain from the marginal entry, and a layer
|
||||
* holding more than half its experts already has its hot set in. Rescuing a layer at 35-45%
|
||||
* residency is worth about a millisecond a step; topping one up from 55% to 63% is worth zero
|
||||
* -- do not price the second from the first.
|
||||
*/
|
||||
/* How many times this layer reported into that bank. A draft head reports once per draft
|
||||
* pass (n_spec times a step) into the same step's bank, each overwriting the last. The
|
||||
* histograms arrive by async copy and cannot be summed here, so the bank is credited `reports`
|
||||
* times, which is right when the passes route from the same distribution. Without it the heat
|
||||
* engine undercounts the draft head's routing and starves its resident set. */
|
||||
int reports[kRouteBanks] = {};
|
||||
/* Whether the drain has taken this bank yet, which is what makes "the ring lost one" an exact
|
||||
* count rather than an upper bound: a bank recycled while this is false held evidence nobody
|
||||
* read. */
|
||||
/* Whether the drain has taken this bank. A bank recycled while this is false is an exact
|
||||
* count of one lost histogram. */
|
||||
bool credited[kRouteBanks] = {};
|
||||
int reported = -1; /* the last step this layer reported at all */
|
||||
};
|
||||
|
||||
/* ------------------------------------------------------------------ construction */
|
||||
/* Where a KV group's pool lives, per group, bound at load. RAD_OPK_KV resolves through this:
|
||||
* RadKVGroupBatch carries the slot mapping, the block table and the sequence lengths, but the pool
|
||||
* BASE belongs to the block manager and not to a per-step batch -- it does not change from step to
|
||||
* step and rebuilding it every step would be work the arena exists to avoid.
|
||||
/* Where a KV group's pool lives, bound at load; RAD_OPK_KV resolves through it. The per-step
|
||||
* RadKVGroupBatch carries slot mapping, block table and lengths; the pool base belongs to the
|
||||
* block manager and does not change between steps.
|
||||
*
|
||||
* One cache per BOUND LAYER, so the operand's `offset` is the layer and `layer_stride` is what
|
||||
* separates two layers of the same group. A group with no bound layers never gets here: the
|
||||
* builder refuses it at declare, because its page size would otherwise be a guess. */
|
||||
/* ONE LAYER'S CACHE, WITH ITS SHAPE. The shape is here and not in the kernel because the core is
|
||||
* where every number in it already lives: the group's RadKVGroupDecl gives the head count, the head
|
||||
* dimension, the per-head state geometry and the conv width, and the block manager decided the
|
||||
* block size, the block count and the state count. A kernel handed a flat span would have to
|
||||
* reconstruct all of that from its own parameters -- and cannot: the conv window's depth is
|
||||
* `conv_width - 1 + n_spec` and the slot count is `max_num_seqs`, neither of which appears in any
|
||||
* op's parameter list. Shims check a cache operand's rank -- 4 for a paged cache, 3 for a conv
|
||||
* window -- and refuse anything else, so a RAD_OPK_KV operand may not arrive as a flat byte span.
|
||||
* One cache per bound layer: the operand's `offset` is the layer, `layer_stride` separates layers.
|
||||
* The builder refuses a group with no bound layers at declare.
|
||||
*
|
||||
* The layouts are the ones libref/ref_ops.h states once for the whole project:
|
||||
* The shape lives here because the core holds every number in it (RadKVGroupDecl plus the block
|
||||
* manager's sizes); a kernel cannot rebuild it from op parameters, since the conv window depth
|
||||
* (`conv_width - 1 + n_spec`) and slot count (`max_num_seqs`) are in none. Shims refuse a cache
|
||||
* operand that is not rank 4 (paged) or rank 3 (conv), so it never arrives as a flat span.
|
||||
* Layouts, as libref/ref_ops.h defines them:
|
||||
*
|
||||
* FULL / WINDOW [n_blocks, n_head_kv, block_size, 2 * head_dim] K then V inside a slot
|
||||
* LINEAR [n_states, n_head_kv, state_dim[0], state_dim[1]]
|
||||
@@ -183,12 +141,9 @@ struct KVPoolBinding {
|
||||
int64_t layer_stride = 0; /* bytes between one layer's cache and the next */
|
||||
int64_t bytes = 0; /* the whole group's pool, for the bounds check */
|
||||
uint32_t dtype = RAD_DT_INVALID;
|
||||
/* THE OPERAND NAMES AN ABSOLUTE MODEL LAYER AND THE GROUP HOLDS ONE CACHE PER BOUND LAYER, so
|
||||
* the rebase is a POSITION LOOKUP and not a subtraction. Subtracting the first bound layer is
|
||||
* right only when a group's layers are contiguous, and they need not be -- 15 attention layers
|
||||
* scattered through 64, say, where the fifth of them at absolute index 19 would come out as
|
||||
* slot 16 of a 15-slot pool. Indexed by absolute layer; -1 means the group does not
|
||||
* hold that layer, which is a caller bug rather than a runtime condition. */
|
||||
/* Absolute model layer -> cache slot in this group. A lookup, not a subtraction, because a
|
||||
* group's layers need not be contiguous. -1: the group does not hold that layer (a caller
|
||||
* bug). */
|
||||
std::vector<int32_t> layer_slot;
|
||||
uint32_t rank = 0; /* 0 when the group has no plan: the operand stays a flat span */
|
||||
int64_t shape[RAD_MAX_RANK] = {0};
|
||||
@@ -204,14 +159,18 @@ struct CtxDesc {
|
||||
ArchStepFn arch_step = nullptr; /* the architecture plugin's rad_arch_step */
|
||||
bool profile_ops = false; /* spec §16, and it changes what you measure */
|
||||
/* Whether a repeated pass may be recorded and played back. False for a caller whose pass
|
||||
* body issues work the batch does not describe -- a test driving another component through
|
||||
* run_step -- so every pass is issued, since a recording keyed on the batch would stand for
|
||||
* passes that differ. */
|
||||
* issues work the batch does not describe (e.g. a test driving another component through
|
||||
* run_step), since a recording keyed on the batch would replay the wrong pass. */
|
||||
bool record_passes = true;
|
||||
|
||||
/* By rad_kvgroup. Empty until the KV manager has allocated, which is why it is bound here and
|
||||
* not derived: a Ctx built before the pools exist would resolve every cache operand to null. */
|
||||
/* By rad_kvgroup. Bound rather than derived because the pools may not exist yet when the Ctx
|
||||
* is built. */
|
||||
std::vector<KVPoolBinding> kv;
|
||||
|
||||
/* The kernel registry, read only by the op oracle (RADIANCE_OP_ORACLE) to resolve the
|
||||
* reference library's host rows. Null: the oracle checks a band only where the reference
|
||||
* library won its host row. */
|
||||
Registry* registry = nullptr;
|
||||
};
|
||||
|
||||
/* ------------------------------------------------------------------ Ctx */
|
||||
@@ -231,15 +190,14 @@ public:
|
||||
void set_stager(OpStager* s) { stager_ = s; }
|
||||
|
||||
/* ---------------------------------------------------------- the step driver */
|
||||
/* Sets the batch and calls the architecture plugin's rad_arch_step through the function
|
||||
* pointer the engine handed us. Under tensor parallel N rank threads each own one Ctx and one
|
||||
* device and are released against the SAME RadBatch by pointer (spec §1); the batch is const
|
||||
* and nobody writes it during a step. Returns RAD_OK, or the negative status of the first
|
||||
* kernel that refused -- rad_arch_step is void, so the abort has to be latched. */
|
||||
/* Sets the batch and calls the architecture plugin's rad_arch_step. Under tensor parallel each
|
||||
* rank thread owns one Ctx and device, and all share the same const RadBatch by pointer
|
||||
* (spec §1). Returns RAD_OK or the first refusing kernel's status, latched because
|
||||
* rad_arch_step is void. */
|
||||
int run_step(const RadBatch* b);
|
||||
|
||||
/* The rank thread must call this once before its first run_step: the device backend's "current
|
||||
* device" is thread-local, and init may well have run on the engine's thread. */
|
||||
/* Call once on the rank thread before its first run_step: the backend's current device is
|
||||
* thread-local, and init may have run on another thread. */
|
||||
int bind_thread();
|
||||
|
||||
/* ---------------------------------------------------------- run-phase queries */
|
||||
@@ -249,18 +207,15 @@ public:
|
||||
RadStream stream() const { return stream_; }
|
||||
Program* program() const { return program_; }
|
||||
|
||||
/* The lane subsequent issues launch on, and the stream that is. Lane 0 is `stream_` and is
|
||||
* what every architecture that does not ask for a second lane ever sees. See lane1_ for the
|
||||
* three things a second lane may not do. */
|
||||
/* The lane subsequent issues launch on, and its stream. Lane 0 is `stream_`. See lane1_ for
|
||||
* the constraints on a second lane. */
|
||||
RadStream cur_stream() const { return lane_ ? lane1_ : stream_; }
|
||||
int lane() const { return lane_; }
|
||||
int set_lane(int lane);
|
||||
/* Builds the second stream and its events on first use. Never called by an architecture that
|
||||
* does not ask for a lane, which is what keeps this feature free when it is unused. */
|
||||
/* Builds the second stream and its events on first use; free when no lane is asked for. */
|
||||
int lane_init();
|
||||
/* Order `to` behind everything already issued on `from`: an event recorded on `from` that
|
||||
* `to` waits for. The HOST does not block, and neither stream is drained -- this is the only
|
||||
* thing that makes two lanes a pipeline rather than a race. */
|
||||
/* Order `to` behind everything already issued on `from` (event record + stream wait). The
|
||||
* host does not block and neither stream is drained. */
|
||||
int lane_join(int from, int to);
|
||||
|
||||
void* weight_ptr(rad_weight w);
|
||||
@@ -276,103 +231,75 @@ public:
|
||||
return nullptr;
|
||||
return route_dev_ + (int64_t)layer * route_n_expert_;
|
||||
}
|
||||
/* How many layers reported routing, which is how many the heat engine has to sweep. Zero on a
|
||||
* dense model, where nothing routes and bind_routing allocated nothing. */
|
||||
/* How many layers report routing (the heat engine's sweep). Zero on a dense model. */
|
||||
int n_route_layers() const { return (int)route_.size(); }
|
||||
int64_t route_n_expert() const { return route_n_expert_; }
|
||||
|
||||
/* ---------------------------------------------------- the next-layer expert prefetch
|
||||
* (xprefetch.h). xp_open at bringup, once the placement has made its pinned pools: their device
|
||||
* ranges and unit strides; it stays off -- and the three calls no-ops -- where the backend or the
|
||||
* placement gives it nothing to do. */
|
||||
* (xprefetch.h). xp_open at bringup, after placement has made its pinned pools, with their
|
||||
* device ranges and unit strides. Where there is nothing to do it stays off and the three
|
||||
* calls are no-ops. */
|
||||
void xp_open(const uint64_t* lo, const uint64_t* hi, const uint64_t* stride, int n);
|
||||
void xp_close();
|
||||
int xp_predict(const RadPrefetchNext* next, rad_buf h, int64_t r0, int64_t rows, int64_t n_embd);
|
||||
int xp_mark();
|
||||
int xp_step(int layer);
|
||||
/* DRAIN, DO NOT SAMPLE. `next_histogram` returns the oldest staging bank holding a LANDED
|
||||
* histogram for a step past `after_step` and before `before_step`, or -1; a caller loops on it
|
||||
* with the step of the last one it credited and so sees every histogram the device produced,
|
||||
* in order, rather than whichever one happened to be newest when it looked. The three readers
|
||||
* below take the bank it returned. Null / -1 / 0 for a layer that has never reported.
|
||||
/* Drain, do not sample. `next_histogram` returns the oldest bank holding a landed histogram
|
||||
* for a step in (`after_step`, `before_step`), or -1. A caller loops on it with the step it
|
||||
* last credited, so it sees every histogram in order. The readers below take that bank; they
|
||||
* return null / -1 / 0 for a layer that never reported.
|
||||
*
|
||||
* `before_step` IS THE STEP THE CALLER IS ABOUT TO ISSUE, and a bank of that step or later is
|
||||
* not finished. A step runs as more than one pass when it drafts, every pass reports into the
|
||||
* step's one bank, and the drain runs again before each of them: a bank credited between two
|
||||
* passes stands for the passes so far, and the rest land after `after_step` has moved to that
|
||||
* step, where nothing will ever read them.
|
||||
* `before_step` is the step about to be issued; its bank is unfinished, because a drafting
|
||||
* step runs several passes into one bank and the drain runs before each.
|
||||
*
|
||||
* `landed`, when given, is kRouteBanks entries of -1 that this fills in as it asks: whether a
|
||||
* bank's copy has landed is the bank's answer, not the layer's, so a sweep over every layer
|
||||
* asks each bank's event once rather than once a layer. */
|
||||
* `landed`, when given, is kRouteBanks entries initialised to -1 and filled in as banks are
|
||||
* queried, so a sweep over all layers queries each bank's event once. */
|
||||
int next_histogram(int layer, int after_step, int before_step,
|
||||
int8_t* landed = nullptr) const;
|
||||
const int32_t* last_histogram(int layer, int bank) const;
|
||||
int last_histogram_step(int layer, int bank) const;
|
||||
/* How many times that layer reported into that bank. 1 for every layer of a non-speculative
|
||||
* step; n_spec for a draft head. See RouteSlot::reports. */
|
||||
/* Reports into that bank: 1 normally, n_spec for a draft head. See RouteSlot::reports. */
|
||||
int last_histogram_reports(int layer, int bank) const;
|
||||
/* HISTOGRAMS THE RING LOST: a bank recycled for a later step while it still held an
|
||||
* uncredited copy, which is what says the ring is shallower than the host's run-ahead. Nothing
|
||||
* reads a dropped histogram, so this is the whole of the error in the routing-evidence
|
||||
* accounting. A further pass of the SAME step reporting into its bank is not a loss: the bank
|
||||
* counts it in `reports` and is credited for all of them at once. */
|
||||
/* Histograms the ring lost: banks recycled for a later step while still uncredited, i.e. the
|
||||
* ring is shallower than the host's run-ahead. Another pass of the same step reporting into
|
||||
* its bank is not a loss (it counts in `reports`). */
|
||||
uint64_t route_dropped() const { return route_dropped_; }
|
||||
/* Told by the drain, so the ring knows which banks are still owed a reader. */
|
||||
/* Called by the drain, so the ring knows which banks are still unread. */
|
||||
void mark_credited(int layer, int bank);
|
||||
const RadRouting* last_routing(int layer) const;
|
||||
|
||||
/* ---------------------------------------------------------- the placement seam */
|
||||
/* Change an op's execution site. Refuses with RAD_E_NOKERNEL, naming the op and the band, if
|
||||
* the requested domain has a hole in its bucket table -- §5.1 says the planner was told at
|
||||
* declare which sites are unavailable, so asking for one anyway is a planner bug and not a
|
||||
* runtime condition to paper over. */
|
||||
/* Change an op's execution site. Refuses with RAD_E_NOKERNEL, naming op and band, if the
|
||||
* domain has a hole in its bucket table: the planner knew the unavailable sites at declare
|
||||
* (§5.1), so this is a planner bug. */
|
||||
int set_op_domain(rad_op h, int domain);
|
||||
int op_domain(rad_op h) const;
|
||||
/* The mover calls this after relocating weights. WeightInfo::generation is honoured BETWEEN
|
||||
* steps rather than per issue: a per-issue atomic load of a cold WeightInfo line costs more
|
||||
* than the relocation it guards against, and within a step the ResidencyTable is the
|
||||
* authority on where a weight is. */
|
||||
void note_weights_moved() { weights_dirty_.store(true, std::memory_order_release); }
|
||||
|
||||
/* ---------------------------------------------------------- diagnostics */
|
||||
/* OpPlan::issued -> Program::ops[i].issued, which is what /graph publishes. Called at the end
|
||||
* of every step, and it must be: without it the graph dump reports every op in the model as
|
||||
* never issued, and a reader using that to find a dead declaration gets all of them. */
|
||||
/* OpPlan::issued -> Program::ops[i].issued, which /graph publishes. Must run at the end of
|
||||
* every step, or the graph dump reports every op as never issued. */
|
||||
void flush_issued();
|
||||
void dump_profile() const; /* spec §16, opt-in, with its caveat printed */
|
||||
const char* step_error() const { return step_fail_.c_str(); }
|
||||
int64_t stream_waits() const { return n_stream_waits_; }
|
||||
/* Host synchronisations the runtime performed on the STEP PATH. Zero, always, unless per-op
|
||||
* timing is on -- which is the caveat in spec §16 expressed as a number a test can read,
|
||||
* rather than a claim in a comment. Teardown's drain is not counted; it is not a step. */
|
||||
/* Host synchronisations on the step path. Always zero unless per-op timing is on (spec §16);
|
||||
* tests read it. Teardown's drain is not counted. */
|
||||
int64_t host_syncs() const { return n_host_syncs_; }
|
||||
/* WHAT THIS RANK PUT ON THE INTERCONNECT, and why it is counted here rather than in the
|
||||
* kernel. The link between the two cards carries two completely different things -- the
|
||||
* tensor-parallel all-reduce after every attention and MLP block, and the expert mover's
|
||||
* promotions and demotions -- and they compete for the same PCIe bytes. The mover counts its
|
||||
* own (MoverStats) and this counts the collective's, so "is the link busy because the model is
|
||||
* wide or because placement is thrashing" has an answer.
|
||||
/* This rank's all-reduce traffic. The inter-card link carries both the tensor-parallel
|
||||
* all-reduce and the expert mover's transfers; the mover counts its own (MoverStats), so the
|
||||
* two can be told apart.
|
||||
*
|
||||
* `ar_bytes` is the MESSAGE PAYLOAD: numel * the operand's element size, summed over issues.
|
||||
* At two ranks that IS the bytes this rank pushes across the link -- libr4d's one-shot exact
|
||||
* kernel pushes the whole input into the peer's scratch once, and the two-shot's
|
||||
* reduce-scatter plus all-gather is (N-1)/N of it twice, which is the same at N=2. At more
|
||||
* ranks it is a floor. A lossy wire (--tp-wire) compresses below it and the number stays the
|
||||
* payload, because what a reader is comparing against the mover's bytes is the traffic the
|
||||
* model asked for, not the encoding it got.
|
||||
* `ar_bytes` is the message payload, numel * element size, summed over issues. At two ranks
|
||||
* that equals the bytes pushed across the link (one-shot and two-shot alike); at more ranks it
|
||||
* is a floor. A lossy wire (--tp-wire) still counts the uncompressed payload.
|
||||
*
|
||||
* Relaxed atomics: written by this rank's step thread, read by whatever thread is drawing. */
|
||||
* Relaxed atomics: written by this rank's step thread, read by any thread. */
|
||||
int64_t ar_calls() const { return ar_calls_.load(std::memory_order_relaxed); }
|
||||
int64_t ar_bytes() const { return ar_bytes_.load(std::memory_order_relaxed); }
|
||||
|
||||
/* HOW EACH PASS WAS RUN, since the host cost of a pass is almost all in which of these it
|
||||
* took: a play writes the recorded packets, every other outcome walks the architecture's
|
||||
* issue path. `issued_*` split the passes that had no tape to play by why -- the pass had no
|
||||
* key, its key was refused, or its key was seen for the first time. `audited` counts the
|
||||
* plays that re-issued to check the tape. `dispatched` is the kernels the plays wrote and
|
||||
* `unordered` how many of them went without the barrier bit (see haz_mark). Same threading as
|
||||
* ar_calls. */
|
||||
/* How each pass was run. A play writes recorded packets; every other outcome walks the issue
|
||||
* path. `issued_*` split unplayed passes by cause: no key, key refused, key seen first time.
|
||||
* `audited` counts plays re-issued to check the tape. `dispatched` is the kernels plays wrote,
|
||||
* `unordered` those without the barrier bit (haz_mark). Same threading as ar_calls. */
|
||||
struct PassCounts {
|
||||
int64_t played = 0, recorded = 0, audited = 0;
|
||||
int64_t issued_unkeyed = 0, issued_refused = 0, issued_first = 0;
|
||||
@@ -391,128 +318,108 @@ public:
|
||||
return c;
|
||||
}
|
||||
void* arena_base() const { return arena_.base(); }
|
||||
int64_t arena_bytes() const { return arena_.bytes(); }
|
||||
void* scratch() const { return arena_.scratch(); }
|
||||
|
||||
/* ---- the arena's levels ------------------------------------------------------------------
|
||||
*
|
||||
* Level 0 is the plan the arena was built for: every buffer sized for the largest step. A
|
||||
* later level is the same buffers packed for a step of at most `rows` tokens (ArenaLevel,
|
||||
* core/build/rad_bufplan.cpp), so the arena past its `end` is free while the steps are that
|
||||
* small -- and the engine lends it to the expert slab. The fixed region is at the same address
|
||||
* in every level, which is what lets a persistent buffer outlive a change of level.
|
||||
* Level 0 is the plan the arena was built for, every buffer sized for the largest step. A
|
||||
* later level packs the same buffers for steps of at most `rows` tokens (ArenaLevel,
|
||||
* core/build/rad_bufplan.cpp); the arena past its `end` is then lent to the expert slab. The
|
||||
* fixed region has the same address in every level, so persistent buffers survive a change.
|
||||
*
|
||||
* A LEVEL IS CHANGED BETWEEN STEPS, NEVER DURING ONE, and only while this rank's thread is
|
||||
* parked: every issue reads the active table, and a step that saw two would hand one op a
|
||||
* buffer another op of the same step had placed somewhere else. The operand guard in issue
|
||||
* checks against the active level's extents, so a step larger than its level is refused by
|
||||
* name rather than written past the level's end into lent memory. */
|
||||
* Invariant: the level changes only between steps, while this rank's thread is parked. The
|
||||
* operand guard in issue checks the active level's extents, so a step larger than its level
|
||||
* is refused instead of writing into lent memory. */
|
||||
int add_level(int64_t rows, const std::vector<int64_t>& offset,
|
||||
const std::vector<RadBufDecl>& decl);
|
||||
int set_level(int level);
|
||||
int level() const { return level_; }
|
||||
int n_levels() const { return (int)level_tmpl_.size(); }
|
||||
|
||||
/* The key a pass over `b` is recorded and played under (see "recorded passes" below); 0 for a
|
||||
* pass that is never recorded. Public so tests can check that it reads every dependency. */
|
||||
uint64_t pass_key(const RadBatch* b) const;
|
||||
|
||||
private:
|
||||
int prepare();
|
||||
int bind_arena();
|
||||
int bind_buffers();
|
||||
int bind_weights(bool refresh_only);
|
||||
int bind_weights();
|
||||
int bind_ops();
|
||||
int bind_routing();
|
||||
int bind_profiling();
|
||||
int check_domain(rad_op h, int domain) const;
|
||||
/* Whether the kernel serving this op on `domain` reads the layout the weights are STORED in.
|
||||
* A weight is stored once, in the claiming DEVICE row's arrangement, so a domain move can
|
||||
* hand a kernel a plane it cannot read -- same byte count, different order, no shape check
|
||||
* anywhere can see it. Fills `why` with the sentence and leaves the severity to the caller. */
|
||||
/* Whether the kernel serving this op on `domain` reads the layout the weights are stored in.
|
||||
* A weight is stored once, in the claiming device row's arrangement, so a domain move can hand
|
||||
* a kernel a plane of the right size in the wrong order. Fills `why`; the caller picks the
|
||||
* severity. */
|
||||
int check_domain_layout(rad_op h, int domain, std::string* why) const;
|
||||
void profile_collect();
|
||||
/* Which staging bank the heat engine may read. Mid-step that is the one this step is NOT
|
||||
* filling; between steps it is simply the freshest, so "one step stale" means exactly one
|
||||
* step and never two. */
|
||||
uint64_t route_dropped_ = 0;
|
||||
|
||||
/* The handle-to-pointer resolution, shared by the issue path and rad_weight_ptr. Waits on the
|
||||
* mover's event where one is pending, on the STREAM, never on the host. */
|
||||
/* Handle-to-pointer resolution for the issue path and rad_weight_ptr. Waits on a pending mover
|
||||
* event on the stream, never on the host. */
|
||||
void* resolve_weight(rad_weight w);
|
||||
|
||||
/* ---- weight TABLES (RAD_OPK_WTAB), which a routed mixture of experts issues and nothing
|
||||
* else does.
|
||||
/* ---- weight tables (RAD_OPK_WTAB), issued by routed mixture-of-experts layers.
|
||||
*
|
||||
* A run of consecutively declared weights becomes a DEVICE ARRAY OF POINTERS, because after
|
||||
* placement a layer's experts are not in one place and `base + e*stride` is true only of the
|
||||
* all-in-VRAM case. One table per (op, operand position), bound at prepare and kept.
|
||||
* A run of consecutively declared weights becomes a device array of pointers, because after
|
||||
* placement a layer's experts are not contiguous. One table per (op, operand position), bound
|
||||
* at prepare.
|
||||
*
|
||||
* The first issue resolves every entry and uploads the whole array from `host`, which is
|
||||
* pinned because the copy is asynchronous and never written again. After that the device
|
||||
* array changes only by patch (runtime/wtab.h): the residency table names the weights the
|
||||
* mover changed (ResidencyTable::changes), sync_residency queues each one against the tables
|
||||
* holding it, and the table's next issue resolves those entries and writes the ones whose
|
||||
* pointer differs from `cur`. A step moves a handful of experts, so that is a handful of
|
||||
* resolves, where re-walking every table whenever anything moved would be the whole expert
|
||||
* set of every routed layer on most steps. */
|
||||
* The first issue resolves every entry and uploads the array from `host` (pinned, since the
|
||||
* copy is async). After that the device array changes only by patch (runtime/wtab.h):
|
||||
* sync_residency queues ResidencyTable::changes against the tables holding each weight, and
|
||||
* the next issue resolves those entries and writes the ones that differ from `cur`. */
|
||||
struct WeightTable {
|
||||
uint64_t key = 0; /* (op << 32) | operand position */
|
||||
rad_weight first = 0;
|
||||
int64_t n = 0;
|
||||
void** host = nullptr;
|
||||
void* dev = nullptr;
|
||||
/* THE SHAPE AGREEMENT IS CHECKED ONCE, AT THE FIRST ISSUE, beside the first upload. What
|
||||
* the check compares -- dtype, rank, shape and stride of each entry against entry 0 -- are
|
||||
* declaration facts, fixed before a step has ever run and incapable of changing
|
||||
* afterwards. */
|
||||
/* Entries' dtype, rank, shape and stride are checked against entry 0 once, at the first
|
||||
* issue; they are declaration facts and cannot change. */
|
||||
bool checked = false;
|
||||
std::vector<void*> cur; /* what the device array holds, entry for entry */
|
||||
std::vector<int32_t> pend; /* entries a residency change named since the last issue */
|
||||
bool full = false; /* every entry: the templates were rebound */
|
||||
};
|
||||
/* Which tables hold a weight, as a list per weight: `wmemb_head_[w]` indexes `wmemb_`, and
|
||||
* -1 means none. A table's entries are declared weights, and nothing stops two ops sharing a
|
||||
* run, so a weight can be in more than one. */
|
||||
/* Which tables hold a weight, as a linked list per weight: `wmemb_head_[w]` indexes `wmemb_`,
|
||||
* -1 means none. Two ops may share a run, so a weight can be in several tables. */
|
||||
struct WMemb { int32_t slot, entry, next; };
|
||||
std::vector<int32_t> wmemb_head_;
|
||||
std::vector<WMemb> wmemb_;
|
||||
/* Whether a weight was ever resolved straight into an operand (RAD_W, rad_weight_ptr) rather
|
||||
* than through a table. Such a pointer is part of the pass's arguments, so a move of that
|
||||
* weight bumps `dense_epoch_`; a move of a table-only weight changes one device entry. */
|
||||
/* Whether a weight was ever resolved directly into an operand (RAD_W, rad_weight_ptr) rather
|
||||
* than through a table. Such a pointer is in the pass's arguments, so moving it bumps
|
||||
* `dense_epoch_`; moving a table-only weight changes one device entry. */
|
||||
std::vector<uint8_t> w_direct_;
|
||||
uint64_t dense_epoch_ = 0;
|
||||
/* The residency table's changes, queued against the tables they touch. Once a pass, before
|
||||
* any of it is issued. */
|
||||
/* Queues the residency table's changes against the tables they touch. Once per pass, before
|
||||
* anything is issued. */
|
||||
void sync_residency();
|
||||
/* Brings the table's device array up to date on the current stream: every entry on the first
|
||||
* issue, afterwards the queued ones. */
|
||||
int table_refresh(rad_op h, int operand, WeightTable& t);
|
||||
/* ------------------------------------------------------------------ recorded passes
|
||||
*
|
||||
* A DECODE PASS IS THE SAME PASS STEP AFTER STEP: the same kernels, with the same arguments,
|
||||
* on the same queues. Everything the host does to produce it -- the architecture's block code,
|
||||
* the operand resolution in `issue`, the kernel library's argument packing, the dispatch -- is
|
||||
* therefore the same work repeated, and it is almost the whole of a rank thread's time. So a
|
||||
* pass is recorded once (the backend keeps the finished packets and argument blocks, see
|
||||
* DeviceBackend::tape_begin) and after that written straight into the queues.
|
||||
* A decode pass repeats step after step: same kernels, arguments and queues. The host work
|
||||
* that produces it (block code, operand resolution, argument packing, dispatch) is most of a
|
||||
* rank thread's time, so a pass is recorded once (DeviceBackend::tape_begin keeps the finished
|
||||
* packets and argument blocks) and then written straight into the queues.
|
||||
*
|
||||
* WHAT MAKES TWO PASSES THE SAME is the KEY: every field of the batch that a pass's shape or
|
||||
* arguments can depend on -- counts, the host-side bounds, every device pointer, each KV
|
||||
* group's geometry -- and the runtime state the issue path reads: the arena level, the weight
|
||||
* templates, the directly resolved weights (dense_epoch_), the op domains, and the lane and
|
||||
* host-arena bookkeeping a pass starts from. The batch builder rounds the two bounds that grow
|
||||
* with the context (batch.cpp, bound_bucket), which is what keeps a key standing for hundreds
|
||||
* of steps. The step number is not in it: nothing a pass issues depends on it except the
|
||||
* routing bank, which is the host's.
|
||||
* Key: every batch field a pass's shape or arguments can depend on (counts, host-side bounds,
|
||||
* device pointers, KV group geometry) plus the runtime state the issue path reads (arena
|
||||
* level, weight templates, dense_epoch_, op domains, lane and host-arena bookkeeping). The
|
||||
* batch builder rounds the context-growing bounds (batch.cpp, bound_bucket) so a key holds for
|
||||
* many steps. The step number is excluded; only the host-side routing bank depends on it.
|
||||
*
|
||||
* WHAT A TAPE CANNOT HOLD is the host work inside a pass, and it is cut around each piece and
|
||||
* replays it: a HOST-site op (joined and run again, on the operands it recorded), a routed
|
||||
* layer's report (the host bookkeeping; the copy is in the tape), and a weight table's refresh
|
||||
* (the patch of whatever the mover changed since, see table_refresh). A table the mover did
|
||||
* not touch costs its step a flag test.
|
||||
* Host work inside a pass is cut out of the tape and replayed: host-site ops (rerun on their
|
||||
* recorded operands), routed-layer reports (host bookkeeping; the copy is in the tape) and
|
||||
* weight-table refreshes (table_refresh). An untouched table costs a flag test.
|
||||
*
|
||||
* TRUSTED ONLY AFTER IT IS CHECKED. A key is recorded the second time it is seen, recorded
|
||||
* again and compared the third, and only then played; a played tape is compared against a
|
||||
* fresh issue again every kAuditPlays plays. A difference means the pass depends on something
|
||||
* the key does not carry, and it fails the step naming the first dispatch that differs -- a
|
||||
* silent difference would be wrong output. */
|
||||
* Verification: a key is recorded on its second sighting (first, for decode), recorded again
|
||||
* and compared on the next, and only then played. Every kAuditPlays plays the tape is compared against a fresh
|
||||
* issue. A difference means the key misses a dependency; the step fails, naming the first
|
||||
* differing dispatch. */
|
||||
enum TapeKind : uint8_t { kTapePlay = 0, kTapeTable = 1, kTapeHost = 2, kTapeRoute = 3,
|
||||
kTapeXp = 4, kTapeXpMark = 5, kTapeXpStep = 6 };
|
||||
/* A prefetch call (Ctx::xp_predict), run again where the pass made it. */
|
||||
@@ -550,17 +457,15 @@ private:
|
||||
uint64_t used = 0;
|
||||
int32_t dispatches = 0, unordered = 0; /* its kernels, and those haz_mark left unordered */
|
||||
};
|
||||
/* WHAT EACH DEVICE OP OF A PASS BEING RECORDED READS AND WRITES, as byte ranges, so the tape
|
||||
* can be played with the dispatches that depend on nothing still running left unordered
|
||||
* behind it (haz_mark). The packet processor otherwise waits for each kernel to finish before
|
||||
* it launches the next, and on independent kernels that wait is pure idle.
|
||||
/* The byte ranges each device op of a recorded pass reads and writes, so haz_mark can leave
|
||||
* dispatches that depend on nothing still running without the barrier bit. Otherwise the
|
||||
* packet processor waits for each kernel to finish before launching the next.
|
||||
*
|
||||
* Ranges come from the operands the op was issued with and the roles its schema gives them --
|
||||
* a weight is never written in a pass, a table's entries are written only between played
|
||||
* stretches -- and the op's scratch is a range like any other. What cannot be bounded makes
|
||||
* the op OPAQUE, ordered on both sides: a kernel whose plugin does not promise it touches
|
||||
* nothing else (rad_kernel_concurrent), a collective (its flags live outside every operand),
|
||||
* an op with no schema, an operand with no extent. */
|
||||
* Ranges come from the issued operands and their schema roles (weights are never written in a
|
||||
* pass; table entries only between played stretches); scratch is a range like any other. An
|
||||
* op is opaque, ordered on both sides, if it cannot be bounded: a kernel not marked
|
||||
* rad_kernel_concurrent, a collective (its flags are outside every operand), an op with no
|
||||
* schema, or an operand with no extent. */
|
||||
struct HazOp {
|
||||
int32_t rec0 = 0, rec1 = 0; /* its dispatches in the tape */
|
||||
uint32_t op = 0;
|
||||
@@ -589,16 +494,26 @@ private:
|
||||
int rec_mark_ = 0; /* the backend record its current play step starts at */
|
||||
std::atomic<uint64_t> domain_epoch_{0}; /* bumped by set_op_domain */
|
||||
|
||||
uint64_t pass_key(const RadBatch* b) const;
|
||||
int run_pass(const RadBatch* b);
|
||||
int record_pass(const RadBatch* b, uint64_t key, PassTape* out);
|
||||
int play_pass(PassTape& t);
|
||||
void tape_cut(); /* while recording: close the current play step */
|
||||
/* While recording: `st` becomes a host step that re-runs at every play. Closes the current
|
||||
* play step, appends `st` on this lane, and runs `run` with the device tape paused. */
|
||||
template <class F> int tape_host(TapeStep st, F&& run) {
|
||||
tape_cut();
|
||||
st.lane = (uint8_t)lane_;
|
||||
rec_->steps.push_back(st);
|
||||
tape_pause(true);
|
||||
const int rc = run();
|
||||
tape_pause(false);
|
||||
return rc;
|
||||
}
|
||||
void tape_drop(PassTape& t);
|
||||
static bool tapes_agree(const PassTape& a, const PassTape& b, std::string* why);
|
||||
bool tape_seen(uint64_t key); /* true the second time a key is asked about */
|
||||
/* A routed layer's report. With `copy` false it is the host bookkeeping alone, which is what a
|
||||
* replay runs: the copy itself is in the tape. */
|
||||
/* A routed layer's report. `copy` false runs only the host bookkeeping, as a replay does; the
|
||||
* copy is in the tape. */
|
||||
int route_report_impl(int layer, const RadRouting* r, bool copy);
|
||||
|
||||
std::vector<WeightTable> wtabs_;
|
||||
@@ -614,50 +529,49 @@ private:
|
||||
RadTensor* out);
|
||||
void free_weight_tables();
|
||||
|
||||
/* Cold, noinline paths. Kept out of issue() so the hot path stays one straight line. */
|
||||
/* Cold, noinline paths, kept out of issue(). */
|
||||
int abort_step(rad_op h, int band, int dom, const IssuePlan& ip, int64_t n, int status);
|
||||
int abort_step_msg(rad_op h, int status, std::string what);
|
||||
|
||||
public:
|
||||
/* What rad_step_fail() reaches. Same effect as an operand rejection -- the step stops and the
|
||||
* message is what the engine prints -- with the reason coming from the caller. */
|
||||
/* Backs rad_step_fail(): stops the step like an operand rejection, with the caller's
|
||||
* message. */
|
||||
int step_fail(const char* what);
|
||||
private:
|
||||
[[noreturn]] void fatal_issue(rad_op h, int64_t n, const char* why) const;
|
||||
|
||||
/* ---- the op oracle. runtime/oracle.cpp; inert unless RADIANCE_OP_ORACLE names an op.
|
||||
* It runs the HOST kernel for the same (op, band) on a host copy of the operands the device
|
||||
* kernel was just given, and compares. Everything about it is off the hot path: `oracle_` is
|
||||
* null in every run that did not ask for it, and the one branch that reads it is the same
|
||||
* predictable not-taken compare as the profiling branch beside it. */
|
||||
/* ---- the op oracle (runtime/oracle.cpp), inert unless RADIANCE_OP_ORACLE names an op. Runs
|
||||
* the host kernel for the same (op, band) on a host copy of the device kernel's operands and
|
||||
* compares. `oracle_` is null otherwise, so the hot path pays one not-taken branch. */
|
||||
struct OracleState;
|
||||
OracleState* oracle_ = nullptr;
|
||||
void oracle_open();
|
||||
void oracle_close();
|
||||
bool oracle_arm(rad_op h) const;
|
||||
/* Extents, aliasing and the per-operand byte count for one issue. Separate from the copy
|
||||
* because a weight TABLE operand is an array of pointers and its snapshot is the STACKED
|
||||
* plane behind them -- a size the operand itself does not state. */
|
||||
/* Extents, aliasing and per-operand byte counts for one issue. Separate from the copy because
|
||||
* a weight-table operand's snapshot is the stacked plane behind its pointers, a size the
|
||||
* operand does not state. */
|
||||
void oracle_size(rad_op h, int n_opd);
|
||||
int64_t oracle_opd_bytes(int i) const;
|
||||
void oracle_snap(int n_opd, bool post);
|
||||
void oracle_run(rad_op h, const IssuePlan& hip, int64_t seq, int n_opd);
|
||||
/* Put a re-laid weight back into the form a dense reference reads, through the DEVICE row's
|
||||
* own inverse, into the logical form the HOST row describes. False when the comparison cannot
|
||||
* be made honestly, which is a named skip. */
|
||||
/* Converts a re-laid weight back, through the device row's inverse, into the logical form the
|
||||
* host row reads. False (a named skip) when no valid comparison is possible. */
|
||||
bool oracle_unrelayout(rad_op h, const IssuePlan& hip, const IssuePlan& dip, int64_t seq,
|
||||
int n_opd);
|
||||
/* Repeat mode (RADIANCE_OP_REPEAT): no host kernel. The DEVICE plan is re-launched on the
|
||||
* restored bytes and the two results are byte-compared, which names a kernel that is not a
|
||||
* function of its inputs. A host-vs-device oracle structurally cannot see that: both of its
|
||||
* sides run once, so a kernel that answers differently on the same bytes agrees with itself
|
||||
* exactly as often as it disagrees. */
|
||||
/* Repeat mode (RADIANCE_OP_REPEAT): re-launches the device plan on the restored inputs and
|
||||
* byte-compares the two results, finding kernels that are not a function of their inputs,
|
||||
* which a host-vs-device comparison cannot detect. */
|
||||
void oracle_repeat(rad_op h, const IssuePlan& dip, int64_t seq, int n_opd);
|
||||
const char* ip_kernel_name(rad_op h) const;
|
||||
/* The reference library's host plan for (op, band): the band's own host plan when a reference
|
||||
* library won it, else one resolved from `registry_` on first use. Null when none exists. */
|
||||
const IssuePlan* oracle_reference(rad_op h, int band);
|
||||
const IssuePlan* oracle_before(rad_op h, int band, int n_opd);
|
||||
void oracle_after(rad_op h, const IssuePlan& hip, const IssuePlan& dip, int n_opd);
|
||||
|
||||
Program* program_ = nullptr;
|
||||
Registry* registry_ = nullptr; /* CtxDesc::registry */
|
||||
std::vector<KVPoolBinding> kv_; /* by rad_kvgroup; RAD_OPK_KV resolves through it */
|
||||
ResidencyTable* residency_ = nullptr;
|
||||
OpStager* stager_ = nullptr;
|
||||
@@ -681,82 +595,61 @@ private:
|
||||
RadStream stream_ = nullptr;
|
||||
bool own_stream_ = false;
|
||||
|
||||
/* ---- THE SECOND LANE, and it exists for exactly one thing: overlapping the tensor-parallel
|
||||
* all-reduce with compute at prefill, which is worth on the order of 15% of prefill
|
||||
* throughput. Nothing else may use it without reading the three constraints below.
|
||||
/* ---- The second lane: overlaps the tensor-parallel all-reduce with compute at prefill
|
||||
* (order of 15% prefill throughput). Any use must respect these constraints:
|
||||
*
|
||||
* ONE: EVERY COLLECTIVE MUST RIDE THE SAME LANE. The all-reduce carries a per-block `seq`
|
||||
* counter and double-buffers its scratch on `seq & 1`, so two launches that race differently
|
||||
* on the two ranks would pick DIFFERENT slots for the same message and deadlock or corrupt.
|
||||
* Both ranks run the same architecture code, so putting every all-reduce on lane 1 keeps them
|
||||
* ordered against each other and therefore identically numbered on both ranks. Splitting the
|
||||
* collectives ACROSS lanes is the bug this comment exists to prevent.
|
||||
* 1. Every collective rides the same lane. The all-reduce double-buffers its scratch on a
|
||||
* per-block `seq & 1`, so collectives that race differently on two ranks pick different
|
||||
* slots for the same message and deadlock or corrupt.
|
||||
*
|
||||
* TWO: A DEVICE-WIDE ARRIVAL COUNTER MUST BE KEYED ON THE STREAM. `split_ctr` in
|
||||
* r4d_gemm_fp8a8.hip is the split-K finisher's counter, self-resetting, and it is sound only
|
||||
* because two launches of this kernel never overlap -- they are ordered by the same stream.
|
||||
* One counter block for the whole device would hold only with one compute stream a rank; a
|
||||
* second lane running a narrow GEMM beside one on lane 0 breaks it. There is therefore one
|
||||
* counter block a STREAM, so ordering does the work again -- and any OTHER plugin kernel with
|
||||
* a device-wide counter has to do the same or stay off lane 1, because nothing here can check
|
||||
* it.
|
||||
* 2. A device-wide arrival counter must be per stream. `split_ctr` in r4d_gemm_fp8a8.hip (the
|
||||
* self-resetting split-K finisher counter) is sound only because its launches are ordered
|
||||
* by one stream, so there is one counter block per stream. Any other plugin kernel with a
|
||||
* device-wide counter must do the same or stay off lane 1; nothing here can check it.
|
||||
*
|
||||
* THREE: THE BUFFER PLANNER PACKS FROM ONE LINEAR ORDER. Two lanes can therefore write the
|
||||
* same arena bytes through two buffers whose declared lifetimes do not overlap. The
|
||||
* architecture names the buffers its second lane touches to `rad_buf_concurrent`, which hands
|
||||
* each of them the whole program -- a few MiB for one block's transients.
|
||||
* 3. The buffer planner packs from one linear order, so two lanes can alias arena bytes
|
||||
* through buffers with disjoint declared lifetimes. The architecture passes every buffer
|
||||
* its second lane touches to `rad_buf_concurrent`, which makes it live for the whole
|
||||
* program.
|
||||
*
|
||||
* FOUR: A SLICE MUST LAND IN THE SAME BUCKET-TABLE BAND AS THE WHOLE. This is the one that
|
||||
* would silently change the model's output rather than break it. An op's kernel is chosen by
|
||||
* which band `n` falls in, and `--debug-graph` prints the boundaries a model actually has.
|
||||
* They are sparse and uneven -- a representative set is
|
||||
* 4. A slice must land in the same bucket-table band as the whole, or it picks a kernel with
|
||||
* a different summation order and silently changes output. `--debug-graph` prints a model's
|
||||
* band boundaries; a representative set is
|
||||
*
|
||||
* 8 16 56 64 256 1024 4096 8192 16384 49152 65536
|
||||
* 8 16 56 64 256 1024 4096 8192 16384 49152 65536
|
||||
*
|
||||
* so a 4096-token chunk cut in HALF gives 2048 and 2048, both inside (1024, 4096] and both
|
||||
* resolving to the same kernel -- while cutting it in FOUR gives 1024, which is the TOP of the
|
||||
* band below and picks a different kernel with a different summation order. The ragged last
|
||||
* chunk of a prompt is worse: 16449 tokens is four full chunks and then 65, and halving 65
|
||||
* crosses the boundaries at 64 and 56. So the rule a pipelined path must obey is that every
|
||||
* slice sits strictly above the largest boundary below T, which at a 4096-token chunk means
|
||||
* TWO slices and no more.
|
||||
* Halving a 4096-token chunk gives 2048 + 2048, inside (1024, 4096]; quartering gives
|
||||
* 1024, the top of the band below. A ragged last chunk of 65 halves across 64 and 56. Every
|
||||
* slice must sit strictly above the largest boundary below T, which at 4096 means at most
|
||||
* two slices. The architecture's own T-dependent selections hold at two slices:
|
||||
* `ar_wire_is_exact` flips only below T = 13, and the gated-GEMM fold and fused attention
|
||||
* prologue band at T <= 64.
|
||||
*
|
||||
* The T-dependent selections inside the architecture hold at two slices: `ar_wire_is_exact`
|
||||
* only flips below T = 13 (`numel * 2 < wire_min_bytes`), and the gated-GEMM fold and the
|
||||
* fused attention prologue both band at T <= 64.
|
||||
*
|
||||
* WHAT MAKES ALL OF THIS WORTH IT: a many-block SPINNING kernel on one stream does not starve
|
||||
* a bandwidth-bound kernel on another. The all-reduce launches min(M, 256) blocks that spin on
|
||||
* a peer flag while the fabric drains, and if those held their CUs there would be nothing to
|
||||
* overlap with. Run a dependent-FMA spinner and a large copy on two streams and the pair costs
|
||||
* the MAX of the two rather than the sum: the copy finishes inside the spinner's window at
|
||||
* every block count, including counts higher than the part can hold resident at once. */
|
||||
* The overlap works because a many-block spinning kernel on one stream does not starve a
|
||||
* bandwidth-bound kernel on another: the all-reduce's min(M, 256) blocks spin on a peer flag,
|
||||
* and a spinner plus a large copy on two streams cost the max of the two, not the sum. */
|
||||
RadStream lane1_ = nullptr;
|
||||
bool own_lane1_ = false;
|
||||
int lane_ = 0;
|
||||
RadEvent lane_ev_[2] = { nullptr, nullptr };
|
||||
/* THE LAST DEVICE OP ON EACH LANE THAT TOUCHED HOST-DOMAIN MEMORY. A host op reads and writes
|
||||
* the host arena at issue, on this thread, while the device may still be working through what
|
||||
* this thread issued before it. What it has to be ordered behind is every device op that
|
||||
* touched the host arena before it -- the producer of its input, or a reader of bytes its
|
||||
* output reuses -- and on each lane those complete no later than the last of them. So a device
|
||||
* op with a host-domain buffer operand re-records its lane's event, and a host op waits on the
|
||||
* recorded ones instead of on everything the stream holds (see the host join in Ctx::issue). */
|
||||
/* The last device op on each lane that touched host-domain memory. A host op runs at issue on
|
||||
* this thread and must be ordered behind every earlier device op that touched the host arena;
|
||||
* on each lane those complete no later than the last one. So a device op with a host-domain
|
||||
* operand re-records its lane's event, and a host op waits on those events instead of draining
|
||||
* the streams (see the host join in Ctx::issue). */
|
||||
RadEvent host_touch_ev_[2] = { nullptr, nullptr };
|
||||
bool host_touch_pending_[2] = { false, false };
|
||||
int host_join(const RadOperand* opd, int n_opd);
|
||||
bool host_join_drains(const RadOperand* opd, int n_opd) const;
|
||||
int host_join_wait(bool drain);
|
||||
/* A lane issued a kernel that uses the shared scratch region and the other lane has not been
|
||||
* joined behind it since. The issue path reads these to keep two scratch users off the region
|
||||
* at once; lane_join clears its `from` side. See the scratch block in Ctx::issue. */
|
||||
/* A lane issued a scratch user and the other lane has not been joined behind it since. Keeps
|
||||
* two lanes off the shared region at once; lane_join clears its `from` side. See the scratch
|
||||
* block in Ctx::issue. */
|
||||
bool scratch_open_[2] = { false, false };
|
||||
bool scratch_join_warned_ = false;
|
||||
/* WHERE IN ITS REGION THE NEXT SCRATCH USER STARTS. Consecutive users are handed consecutive
|
||||
* slices rather than all the same bytes, wrapping to the start when one does not fit, so two
|
||||
* of them that are otherwise independent share nothing and may run at once (haz_mark). Back
|
||||
* to zero at the start of every pass, so a pass issued twice hands its ops the same slices --
|
||||
* the pointers are in its recording's arguments. */
|
||||
/* Where in its region the next scratch user starts. Consecutive users get consecutive slices,
|
||||
* wrapping when one does not fit, so independent users share no bytes and may overlap
|
||||
* (haz_mark). Reset every pass, so a re-issued pass gets the same slices as its recording. */
|
||||
int64_t scratch_cur_[2] = { 0, 0 };
|
||||
void* scratch_take(int region, int64_t bytes);
|
||||
/* The kernel that last opened each lane's scratch, and its row count, for the warning. */
|
||||
@@ -768,44 +661,40 @@ private:
|
||||
|
||||
const RadBatch* batch_ = nullptr;
|
||||
|
||||
/* Per-issue tensor storage, bound into every IssuePlan::args.t at prepare so an issue stores
|
||||
* n_t and nothing else. One array, because issues do not nest. */
|
||||
/* Per-issue tensor storage, bound into every IssuePlan::args.t at prepare. One array, because
|
||||
* issues do not nest. */
|
||||
RadTensor tbuf_[MAX_OPERANDS];
|
||||
|
||||
/* Prebuilt tensor templates, indexed by handle. A buffer's template already carries its arena
|
||||
* pointer, dtype, shape and packed strides; a weight's already carries WeightInfo::ptr. An
|
||||
* issue copies one and patches at most the data pointer and dim 0. */
|
||||
/* Prebuilt tensor templates by handle: a buffer's carries its arena pointer, dtype, shape and
|
||||
* packed strides; a weight's carries WeightInfo::ptr. An issue copies one and patches at most
|
||||
* the data pointer and dim 0. */
|
||||
std::vector<RadTensor> buf_tmpl_;
|
||||
std::vector<int32_t> buf_bits_;
|
||||
std::vector<uint8_t> buf_host_; /* per handle: a RAD_DOMAIN_HOST buffer */
|
||||
/* Every level's templates; `buf_tmpl_` is a copy of the active one, so the issue path reads
|
||||
* one vector whatever level it is at. */
|
||||
/* Every level's templates; `buf_tmpl_` is a copy of the active one. */
|
||||
std::vector<std::vector<RadTensor>> level_tmpl_;
|
||||
int level_ = 0;
|
||||
std::vector<RadTensor> w_tmpl_;
|
||||
std::vector<int32_t> w_bits_;
|
||||
std::vector<uint32_t> w_gen_; /* the generation each template was built from */
|
||||
std::vector<uint32_t> waited_gen_; /* the generation we last made the stream wait on */
|
||||
|
||||
std::vector<OpPlan> plans_;
|
||||
/* THE OPS NOT YET SEEN ISSUED. flush_issued walks this rather than every op, and drops each
|
||||
* index as it fires, so the per-step cost falls to the ops that have never fired -- which
|
||||
* after a few steps is only the ones that never will, and those are the point. */
|
||||
/* Ops not yet seen issued. flush_issued walks only these and drops each once it fires. */
|
||||
std::vector<uint32_t> unflushed_;
|
||||
std::vector<int64_t> band_table_;
|
||||
std::vector<IssuePlan> issue_table_;
|
||||
/* The parameter lists of the launches handed `link_gate`: the geometry's and that one. A deque,
|
||||
* so a plan's pointer into one stays good as the next is added. */
|
||||
/* Parameter lists (geometry plus `link_gate`) for the launches that take the gate. A deque,
|
||||
* so IssuePlan::gate_p stays valid as entries are added. */
|
||||
std::deque<std::vector<RadParam>> gate_params_;
|
||||
std::vector<std::atomic<uint8_t>> op_domain_; /* sized once, never resized */
|
||||
|
||||
std::vector<RouteSlot> route_;
|
||||
int64_t route_n_expert_ = 0;
|
||||
/* A BANK IS ONE STEP'S HISTOGRAMS FOR EVERY LAYER, [kRouteBanks][n_layer][n_expert] in pinned
|
||||
* host memory. A report copies one layer's counts into that layer's row on the card,
|
||||
* [n_layer][n_expert], which is a copy within the card and orders nothing else; the end of the
|
||||
* pass copies the rows it touched into the step's bank in one transfer and records the bank's
|
||||
* event. See route_report. */
|
||||
/* A bank is one step's histograms for every layer: [kRouteBanks][n_layer][n_expert] in pinned
|
||||
* host memory. A report copies a layer's counts into its row of the card-side
|
||||
* [n_layer][n_expert] (an on-card copy that orders nothing else); the end of the pass copies
|
||||
* the touched rows into the step's bank in one transfer and records the bank's event. See
|
||||
* route_report. */
|
||||
int32_t* route_pool_ = nullptr; /* host */
|
||||
int32_t* route_dev_ = nullptr; /* card */
|
||||
RadEvent route_done_[kRouteBanks] = {};
|
||||
@@ -813,8 +702,8 @@ private:
|
||||
int route_bank_ = -1, route_lo_ = 1, route_hi_ = 0;
|
||||
int route_flush();
|
||||
|
||||
/* Profiling. Off by default; when on it restores synchronisations that change the mover's slot
|
||||
* supply, so a profiled run is not comparable against an unprofiled one (spec §16). */
|
||||
/* Profiling. Off by default; when on it adds synchronisations that change the mover's slot
|
||||
* supply, so profiled and unprofiled runs are not comparable (spec §16). */
|
||||
bool profiling_ = false;
|
||||
struct ProfSlot { RadEvent a = nullptr, b = nullptr; int32_t op = 0; uint8_t lane = 0; };
|
||||
std::vector<ProfSlot> prof_ring_;
|
||||
@@ -822,27 +711,17 @@ private:
|
||||
bool prof_overflowed_ = false;
|
||||
std::vector<double> prof_ms_;
|
||||
std::vector<int64_t> prof_calls_;
|
||||
/* Which rows were timed on the HOST clock rather than by a device event pair. The two are not
|
||||
* the same measurement -- a host row includes page faults and link reads, a device row is
|
||||
* kernel time -- so the table says which each one is rather than letting a reader assume. */
|
||||
/* Rows timed on the host clock rather than by a device event pair. A host row includes page
|
||||
* faults and link reads, a device row is kernel time, so the table labels each. */
|
||||
std::vector<uint8_t> prof_host_;
|
||||
/* The stream drain a host-site op forces, timed apart from the op itself: it is the cost of
|
||||
* the pipeline the op STOPS, not of the arithmetic it does, and the two differ by two orders
|
||||
* of magnitude on the PLE gather. */
|
||||
/* The stream drain a host-site op forces, timed apart from the op: it is the cost of stopping
|
||||
* the pipeline, which can exceed the op itself by 100x (PLE gather). */
|
||||
std::vector<double> prof_join_ms_;
|
||||
/* How long each op's lane sat idle before the op started: from the end of the op before it on
|
||||
* that lane to this one's start. A stream wait (a staged layer's copies, the other lane, a
|
||||
* host op's output) and a host that has not issued the op yet both land here, and neither is
|
||||
* in any op's own time -- so a step whose ops sum to less than its wall time says where the
|
||||
* rest went. */
|
||||
/* Lane idle time before each op: previous op's end on that lane to this one's start. Stream
|
||||
* waits (staged copies, the other lane, a host op) and late host issue land here, accounting
|
||||
* for wall time the ops' own times do not cover. */
|
||||
std::vector<double> prof_wait_ms_;
|
||||
|
||||
std::atomic<bool> weights_dirty_{false};
|
||||
/* Bumped whenever bind_weights rewrites the templates: any weight pointer resolved from one
|
||||
* before may have moved. */
|
||||
uint64_t w_tmpl_epoch_ = 1;
|
||||
|
||||
bool in_step_ = false;
|
||||
int step_status_ = RAD_OK;
|
||||
std::string step_fail_;
|
||||
|
||||
|
||||
+177
-421
@@ -1,17 +1,13 @@
|
||||
/* issue.cpp -- THE hot path, and the C surface the architecture plugin actually calls.
|
||||
/* issue.cpp -- the hot path, and the C surface the architecture plugin calls.
|
||||
*
|
||||
* Per rad_issue, in order: index the op's bucket table with `n`, pick the domain from the resolved
|
||||
* instance's current execution site, materialise a RadTensor for each operand out of a template
|
||||
* built at declare, resolve every weight handle to a pointer (waiting on the mover's event on the
|
||||
* STREAM if the weight is in flight), store the operand count into a RadArgs that was already
|
||||
* filled in, and launch.
|
||||
* Per rad_issue: index the op's bucket table with `n`, pick the domain from the op's current
|
||||
* execution site, build a RadTensor per operand from its declare-time template, resolve weight
|
||||
* handles (a stream wait on the mover's event if in flight), set the operand count in the
|
||||
* prefilled RadArgs, and launch.
|
||||
*
|
||||
* NO ALLOCATION. NO HOST SYNCHRONISATION. NO DEVICE ROUND TRIP. Every one of those is a property
|
||||
* you lose by accident, so each of them is checkable here: the only writes are into arrays sized
|
||||
* at prepare, the only device call besides the launch is rad_event_wait (which orders a stream and
|
||||
* does not block the host), and nothing in this file reads a device value back.
|
||||
*
|
||||
* See ctx.h for the per-issue cost and where it sits against spec §3.2's budget.
|
||||
* No allocation, no host synchronisation, no device read-back: writes go only to arrays sized at
|
||||
* prepare, and the only device call besides the launch is rad_event_wait, which does not block
|
||||
* the host. See ctx.h for the cost budget (spec §3.2).
|
||||
*/
|
||||
#include <algorithm>
|
||||
#include <chrono>
|
||||
@@ -29,28 +25,22 @@
|
||||
|
||||
namespace rad {
|
||||
|
||||
/* A COLUMN SLICE: `cols` narrows the LAST dimension while every stride is left alone, so the
|
||||
* declared width stays the row pitch. That is what makes a fused projection usable without a
|
||||
* copy -- q and the attention gate are interleaved per head inside one buffer, and GDN's `a` and
|
||||
* `b` are columns of one in-projection. The element offset is what selects the first column, so
|
||||
* the two fields compose: offset picks the start, cols picks the width.
|
||||
/* Column slice: `cols` narrows the last dimension and leaves every stride alone, so the declared
|
||||
* width stays the row pitch. This reads a fused projection without a copy (q and the attention
|
||||
* gate interleaved per head; GDN's `a` and `b` in one in-projection). The element offset picks the
|
||||
* first column, `cols` the width.
|
||||
*
|
||||
* Narrowing the last dimension rather than dim 0 is the whole point: shortening the OUTERMOST
|
||||
* dimension leaves every stride correct because they are products of the trailing ones, and
|
||||
* shortening the INNERMOST one leaves them correct because nothing is a product of it. Any other
|
||||
* dimension would need the strides rewritten, so the ABI offers only these two. */
|
||||
* Only the outermost and innermost dimensions can be shortened without rewriting strides, so the
|
||||
* ABI offers only those two. */
|
||||
static inline void narrow_cols(const RadOperand& o, RadTensor* t) {
|
||||
if (o.cols > 0 && t->rank >= 1) t->shape[t->rank - 1] = o.cols;
|
||||
}
|
||||
|
||||
/* DOES THE OPERAND FIT THE BUFFER IT NAMES? The span is the largest element index the descriptor
|
||||
* can reach, measured from the buffer's base -- `offset` plus the sum of (extent - 1) * stride
|
||||
* over every dimension. It is NOT shape[0] against the declared shape[0]: a row count larger than
|
||||
* the declared one is legitimate when `cols` is narrower, because a [T, 2560] buffer read at 160
|
||||
* columns IS T*16 rows of 160 and the PLE gather does exactly that. The span is the only reading
|
||||
* that accepts the legal case and refuses the overrun.
|
||||
/* Whether the operand fits the buffer it names. The span is the largest reachable element index,
|
||||
* `offset` + sum((extent - 1) * stride). Comparing shape[0] instead would be wrong: a [T, 2560]
|
||||
* buffer read at 160 columns is legitimately T*16 rows of 160 (the PLE gather does this).
|
||||
*
|
||||
* An empty extent reaches nothing and is not an error here; the kernel's own bounds decide. */
|
||||
* An empty extent reaches nothing; the kernel's own bounds decide. */
|
||||
static inline bool operand_fits(const RadTensor& t, int64_t offset, const RadTensor& decl) {
|
||||
if (offset < 0) return false;
|
||||
int64_t span = offset;
|
||||
@@ -61,9 +51,7 @@ static inline bool operand_fits(const RadTensor& t, int64_t offset, const RadTen
|
||||
return span < rad_tensor_numel(&decl);
|
||||
}
|
||||
|
||||
/* Extents and strides, for the message that refuses. oracle.cpp has one of these in an anonymous
|
||||
* namespace; duplicating four lines beats exporting a debug formatter across translation units. */
|
||||
static inline std::string opd_shape_str(const RadTensor& t) {
|
||||
std::string tensor_shape_str(const RadTensor& t) {
|
||||
std::string s = "[";
|
||||
for (uint32_t d = 0; d < t.rank; ++d)
|
||||
s += fmt("%s%lld", d ? "," : "", (long long)t.shape[d]);
|
||||
@@ -73,10 +61,9 @@ static inline std::string opd_shape_str(const RadTensor& t) {
|
||||
return s + "]";
|
||||
}
|
||||
|
||||
/* Element offset to byte offset. Split out because the sub-byte cases are the interesting ones:
|
||||
* a W4 weight has no addressable odd element, and a plugin-private dtype has no size the core
|
||||
* knows at all -- both are refused by name rather than silently truncated into a misaligned
|
||||
* pointer. Returns false when the offset cannot be expressed. */
|
||||
/* Element offset to byte offset. False when it cannot be expressed: a mid-byte offset into a
|
||||
* packed sub-byte weight (e.g. an odd W4 element), or a plugin-private dtype with no core-known
|
||||
* size. */
|
||||
static inline bool byte_delta(int bits, int64_t elems, int64_t* out) {
|
||||
if (bits >= 8) { *out = elems * (int64_t)(bits >> 3); return true; }
|
||||
if (bits <= 0) return false; /* plugin-private: the core has no size */
|
||||
@@ -87,24 +74,21 @@ static inline bool byte_delta(int bits, int64_t elems, int64_t* out) {
|
||||
}
|
||||
|
||||
void* Ctx::resolve_weight(rad_weight w) {
|
||||
/* The template already carries WeightInfo::ptr, bound at prepare and refreshed between steps
|
||||
* when the mover says it moved something. In the all-in-VRAM case that is the whole answer and
|
||||
* there is no table, no virtual call and no branch beyond this one. */
|
||||
/* The template carries WeightInfo::ptr, refreshed between steps after a move. In the
|
||||
* all-in-VRAM case that is the answer. */
|
||||
void* p = w_tmpl_[w].data;
|
||||
if (!residency_) return p;
|
||||
|
||||
const WeightSlot* s = residency_->lookup(w); /* never blocks -- residency.h */
|
||||
if (s) {
|
||||
p = s->ptr;
|
||||
/* Wait once per generation, not once per issue. A stream wait orders everything issued
|
||||
* after it, so repeating it buys nothing and at eight experts a layer across 64 layers it
|
||||
* would be thousands of runtime calls a step. The mover bumps `generation` when it starts
|
||||
* a transfer, which is what makes the memo sound (residency.h). */
|
||||
/* Wait once per generation, not per issue; a stream wait orders everything issued after
|
||||
* it. Sound because the mover bumps `generation` per transfer (residency.h). */
|
||||
if (s->ready && waited_gen_[w] != s->generation) {
|
||||
/* Not part of a recording: once issued it orders everything after it, every later
|
||||
* play included, and a move of a weight a pass names directly re-keys the pass. */
|
||||
/* Kept out of a recording: it orders every later play too, and moving a weight a
|
||||
* pass names directly re-keys the pass. */
|
||||
if (rec_) tape_pause(true);
|
||||
rad_event_wait(cur_stream(), s->ready); /* the STREAM waits; the host does not */
|
||||
rad_event_wait(cur_stream(), s->ready); /* the stream waits, not the host */
|
||||
if (rec_) tape_pause(false);
|
||||
waited_gen_[w] = s->generation;
|
||||
++n_stream_waits_;
|
||||
@@ -115,29 +99,15 @@ void* Ctx::resolve_weight(rad_weight w) {
|
||||
|
||||
/* ================================================================== weight tables
|
||||
*
|
||||
* RAD_OPK_WTAB. See the comment on Ctx::WeightTable and the RAD_WTAB macro in rad_runtime.h: this
|
||||
* is where a run of declared weights becomes the device pointer array a grouped GEMM walks.
|
||||
* RAD_OPK_WTAB (Ctx::WeightTable, RAD_WTAB in rad_runtime.h): a run of declared weights becomes
|
||||
* the device pointer array a grouped GEMM walks.
|
||||
*
|
||||
* THE ENTRIES MUST AGREE ABOUT SHAPE AND DTYPE, and the check is not pedantry -- the kernel is
|
||||
* given one set of trailing extents for the whole table and strides its way through an entry with
|
||||
* them, so a run that mixes two shapes is a run the kernel reads off the end of. A MoE layer
|
||||
* declares 256 identical experts, so this holds by construction and a violation is a plugin bug
|
||||
* that is worth naming at the first issue rather than debugging from wrong logits. */
|
||||
/* THE TABLE'S MEMORY, ALLOCATED ONCE AND NOT ON THE STEP PATH.
|
||||
*
|
||||
* Allocating it inside resolve_weight_table, which runs at ISSUE, would have the first step of the
|
||||
* first request allocate one pinned array and one device array per grouped-GEMM operand -- an
|
||||
* allocator on the step path, and spec §3.1 says there is not one. It would also be invisible to
|
||||
* the VRAM budget: the pools are sized before a step has ever run, so those bytes would come out
|
||||
* of --gpu-headroom-mib without being named in it.
|
||||
*
|
||||
* Binding every declared table at prepare() avoids both. The run is a property of the DECLARATION
|
||||
* (OpInfo::weights with OpInfo::weight_opd naming the operand position), not of the issue, so
|
||||
* there is nothing about it that has to wait for a step. resolve_weight_table still handles a
|
||||
* miss, because a plugin may legally issue a table the declaration did not describe -- it just
|
||||
* does not happen on any model this engine ships.
|
||||
*
|
||||
* Returns the slot in wtabs_. */
|
||||
* Entries must agree on shape and dtype: the kernel strides every entry with one set of trailing
|
||||
* extents, so a mixed run reads out of bounds. A violation is a plugin bug, named at first issue. */
|
||||
/* A table's pinned and device arrays, allocated once. Normally called from prepare
|
||||
* (bind_weight_tables), so no allocation happens on the step path (spec §3.1) and the bytes are
|
||||
* not taken unbudgeted from --gpu-headroom-mib. resolve_weight_table calls it on a miss, which is
|
||||
* legal for a table the declaration did not describe. Returns the slot in wtabs_. */
|
||||
int Ctx::ensure_weight_table(uint64_t key, rad_weight first, int64_t n, size_t* slot_out) {
|
||||
auto it = wtab_of_.find(key);
|
||||
if (it != wtab_of_.end()) { *slot_out = it->second; return RAD_OK; }
|
||||
@@ -169,11 +139,9 @@ int Ctx::ensure_weight_table(uint64_t key, rad_weight first, int64_t n, size_t*
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* Every RAD_OPD_WTAB operand of every declared op, bound before the first step. The run is
|
||||
* contiguous by construction -- rad_decl_weight hands out consecutive indices and a declaration
|
||||
* loop over experts produces exactly such a run -- so it is the smallest declared handle at that
|
||||
* operand position and the count of them. A gap would be a plugin bug, and it is named rather
|
||||
* than papered over: a table assembled from a non-contiguous run would read the wrong expert. */
|
||||
/* Binds every RAD_OPD_WTAB operand of every declared op before the first step. A run is the
|
||||
* smallest declared handle at that operand position plus the count; rad_decl_weight hands out
|
||||
* consecutive indices, so a gap is a plugin bug and is refused (it would read the wrong expert). */
|
||||
int Ctx::bind_weight_tables() {
|
||||
const Program& P = *program_;
|
||||
int64_t tables = 0, bytes = 0;
|
||||
@@ -194,7 +162,7 @@ int Ctx::bind_weight_tables() {
|
||||
if (cnt <= 0) continue;
|
||||
if ((int64_t)(hi - lo) + 1 != cnt) {
|
||||
RAD_ERR("op '%s' operand %d is a weight table of %lld entries whose declared "
|
||||
"handles run [%u, %u] -- a table must be a CONTIGUOUS run, because the "
|
||||
"handles run [%u, %u]; a table must be a contiguous run, because the "
|
||||
"kernel is handed one base and strides through it",
|
||||
op.op.c_str(), p, (long long)cnt, lo, hi);
|
||||
return RAD_E_INVAL;
|
||||
@@ -213,16 +181,14 @@ int Ctx::bind_weight_tables() {
|
||||
}
|
||||
}
|
||||
if (tables > 0)
|
||||
RAD_DEBUG("weight tables: %lld bound at prepare, %s of pointer arrays -- none of it "
|
||||
"allocated on the step path", (long long)tables, humanb(bytes).c_str());
|
||||
RAD_DEBUG("weight tables: %lld bound at prepare, %s of pointer arrays",
|
||||
(long long)tables, humanb(bytes).c_str());
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
static const bool g_dbg_issue = std::getenv("RADIANCE_DEBUG_ISSUE") != nullptr;
|
||||
/* THE WEIGHT-TABLE WALK, charged separately from the rest of `own`. A grouped-GEMM operand names a
|
||||
* run of experts; the first issue walks every entry and later ones the entries the mover changed
|
||||
* (WeightTable::pend). Two counters -- entries walked, and the wall time of the walks -- so that
|
||||
* cost is read directly rather than inferred from the difference between two builds. */
|
||||
/* RADIANCE_DEBUG_ISSUE: entries walked and wall time spent in weight-table refreshes, reported
|
||||
* separately from the rest of `own`. */
|
||||
static double g_wtab_us = 0.0, g_wtab_us_p = 0.0;
|
||||
static long g_wtab_e = 0, g_wtab_e_p = 0;
|
||||
|
||||
@@ -232,10 +198,8 @@ int Ctx::resolve_weight_table(rad_op h, int operand, rad_weight first, int64_t n
|
||||
size_t slot;
|
||||
auto it = wtab_of_.find(key);
|
||||
if (it == wtab_of_.end()) {
|
||||
/* A MISS IS NOT THE NORMAL PATH ANY MORE -- bind_weight_tables() bound every table the
|
||||
* declaration describes. Reaching here means a plugin issued a table at an operand
|
||||
* position its declaration did not name as one, which is legal and is served, but it is
|
||||
* an allocation on the step path and the log says so once. */
|
||||
/* A plugin issued a table at an operand position its declaration did not name. Legal, but
|
||||
* it allocates on the step path. */
|
||||
RAD_DEBUG("op %u operand %d issued a weight table of %lld entries that the declaration did "
|
||||
"not describe; allocating it now", (unsigned)h, operand, (long long)n);
|
||||
const int rc = ensure_weight_table(key, first, n, &slot);
|
||||
@@ -254,8 +218,8 @@ int Ctx::resolve_weight_table(rad_op h, int operand, rad_weight first, int64_t n
|
||||
first, (long long)n));
|
||||
}
|
||||
WeightTable& t = wtabs_[slot];
|
||||
/* In a pass being recorded the refresh is host work: the recording is cut and the table named,
|
||||
* so a play refreshes it here, on this lane, with whatever the mover has changed by then. */
|
||||
/* While recording, the refresh is host work: cut the tape and name the table, so a play
|
||||
* refreshes it on this lane with whatever the mover has changed by then. */
|
||||
if (rec_) {
|
||||
tape_cut();
|
||||
TapeStep st;
|
||||
@@ -276,7 +240,7 @@ int Ctx::resolve_weight_table(rad_op h, int operand, rad_weight first, int64_t n
|
||||
|
||||
int Ctx::table_refresh(rad_op h, int operand, WeightTable& t) {
|
||||
const RadTensor& e0 = w_tmpl_[t.first];
|
||||
const bool wt_time = g_dbg_issue && rank() == 0; /* same rule: one thread accumulates */
|
||||
const bool wt_time = g_dbg_issue && rank() == 0; /* one thread accumulates */
|
||||
const auto t_wt0 = wt_time ? std::chrono::steady_clock::now()
|
||||
: std::chrono::steady_clock::time_point{};
|
||||
auto resolve = [&](int64_t e, void** out) -> int {
|
||||
@@ -294,9 +258,8 @@ int Ctx::table_refresh(rad_op h, int operand, WeightTable& t) {
|
||||
|
||||
int64_t walked = 0;
|
||||
if (!t.checked) {
|
||||
/* THE FIRST ISSUE: agreement, every entry, and the whole array up in one copy. `host` is
|
||||
* never written after this, so the copy reads what was resolved here however late the
|
||||
* card reaches it. */
|
||||
/* First issue: check agreement, resolve every entry, upload the whole array. `host` is
|
||||
* never written again, so the async copy is safe however late it runs. */
|
||||
t.cur.assign((size_t)t.n, nullptr);
|
||||
for (int64_t e = 0; e < t.n; ++e) {
|
||||
const rad_weight w = (rad_weight)(t.first + e);
|
||||
@@ -327,8 +290,8 @@ int Ctx::table_refresh(rad_op h, int operand, WeightTable& t) {
|
||||
fmt("operand %d: the weight table could not be uploaded", operand));
|
||||
t.checked = true;
|
||||
} else {
|
||||
/* THE ENTRIES THAT MAY HAVE MOVED, each resolved -- which is also what orders the stream
|
||||
* behind a transfer still in flight -- and written only if its pointer differs. */
|
||||
/* Entries that may have moved: resolve each (which also orders the stream behind an
|
||||
* in-flight transfer) and patch only those whose pointer differs. */
|
||||
WtabPatch pt;
|
||||
auto one = [&](int64_t e) -> int {
|
||||
void* p = nullptr;
|
||||
@@ -364,8 +327,8 @@ int Ctx::table_refresh(rad_op h, int operand, WeightTable& t) {
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* The residency table's changes since the last pass, queued against every table that holds the
|
||||
* weight. A weight also resolved straight into an operand moves `dense_epoch_` as well. */
|
||||
/* Queues the residency table's changes against every table holding each weight. A weight also
|
||||
* resolved directly into an operand bumps `dense_epoch_`. */
|
||||
void Ctx::sync_residency() {
|
||||
if (!residency_) return;
|
||||
const std::vector<rad_weight>& ch = residency_->changes();
|
||||
@@ -375,8 +338,7 @@ void Ctx::sync_residency() {
|
||||
if ((size_t)w >= wmemb_head_.size()) continue;
|
||||
for (int32_t m = wmemb_head_[w]; m >= 0; m = wmemb_[(size_t)m].next) {
|
||||
WeightTable& t = wtabs_[(size_t)wmemb_[(size_t)m].slot];
|
||||
/* A table not yet issued resolves every entry at its first issue, and one already
|
||||
* marked resolves every entry at its next. */
|
||||
/* Unissued or already-full tables resolve every entry at their next issue. */
|
||||
if (!t.checked || t.full) continue;
|
||||
if ((int64_t)t.pend.size() >= t.n) { t.full = true; t.pend.clear(); continue; }
|
||||
t.pend.push_back(wmemb_[(size_t)m].entry);
|
||||
@@ -385,9 +347,8 @@ void Ctx::sync_residency() {
|
||||
residency_->clear_changes();
|
||||
}
|
||||
|
||||
/* The operand a kernel is handed for a table: entry 0's dtype and trailing extents, with the
|
||||
* expert axis PREPENDED at stride zero -- the marker that says the axis is not addressable by
|
||||
* arithmetic and `data` is a pointer array. */
|
||||
/* The operand a kernel sees for a table: entry 0's dtype and extents with the expert axis
|
||||
* prepended at stride 0, which marks `data` as a pointer array. */
|
||||
int Ctx::weight_table_tensor(rad_op h, int operand, const WeightTable& t, const RadTensor& e0,
|
||||
RadTensor* out) {
|
||||
if (e0.rank + 1 > RAD_MAX_RANK)
|
||||
@@ -415,98 +376,24 @@ void Ctx::free_weight_tables() {
|
||||
wtab_of_.clear();
|
||||
}
|
||||
|
||||
/* RADIANCE_DEBUG_ISSUE: WHAT THE ISSUE PATH ACTUALLY COSTS, split from the launch it wraps.
|
||||
/* RADIANCE_DEBUG_ISSUE: host cost of the issue path, split from the launch it wraps. Kernel
|
||||
* traces and the per-op profiler only see device time.
|
||||
*
|
||||
* A draft pass costs several microseconds a dispatch where a bare `hipLaunchKernelGGL` costs
|
||||
* around one and a half (`isa/graphrate.hip` prices one). The difference has to be here, and
|
||||
* nothing else in the tree can see it: an op's host cost is invisible in a kernel trace, and the
|
||||
* per-op profiler times the DEVICE.
|
||||
* `own` is everything before the launch (band scan, domain lookup, operand resolution); `launch`
|
||||
* is the plugin shim plus HIP. Costs two clock reads (~50 ns) per issue when enabled.
|
||||
*
|
||||
* `own` is everything before the launch -- the band scan, the domain lookup, the operand
|
||||
* resolution loop. `launch` is the plugin shim plus HIP. Two clock reads an issue, ~50 ns on a
|
||||
* path this says is microseconds, and only when the variable is set.
|
||||
*
|
||||
* REPORTED PER WINDOW AND NOT AS A RUNNING MEAN. Load and the first prefill put seconds into the
|
||||
* accumulator over relatively few issues, so a cumulative average decays through a series of
|
||||
* individually plausible numbers, every one of them the startup transient and none of them the
|
||||
* steady state. A statistic that is still moving after a million samples is measuring the warm-up,
|
||||
* and printing it as "us each" invites exactly the wrong conclusion. */
|
||||
|
||||
/* RADIANCE_DEBUG_ARGSHA: ARE A DRAFTER PASS'S KERNEL ARGUMENTS THE SAME EVERY STEP?
|
||||
*
|
||||
* This is the one question that decides what a captured graph would cost to maintain. A draft pass
|
||||
* is the same op sequence at the same shapes every step -- the concurrency does not change inside a
|
||||
* request -- so if the ARGUMENTS are identical too, a graph can be captured once and replayed. If
|
||||
* they move, every replay needs `hipGraphExecKernelNodeSetParams` over ~50 nodes, which is most of
|
||||
* the submit cost back.
|
||||
*
|
||||
* The staging arena is DOUBLE BUFFERED, so the expectation is not one digest but TWO, alternating.
|
||||
* That still replays -- two graphs, picked by parity -- and it is worth knowing before anyone
|
||||
* builds either.
|
||||
*
|
||||
* Digests the operand bytes and `n` of every issue of pass 1 into one FNV-1a and prints it a step. */
|
||||
static const bool g_dbg_argsha = std::getenv("RADIANCE_DEBUG_ARGSHA") != nullptr;
|
||||
|
||||
static int g_argsha_pass = -99;
|
||||
static long g_argsha_seen = 0;
|
||||
/* ONE DIGEST AN ISSUE, not one a pass: the pass-wide digest only says "something moved", and what
|
||||
* decides whether a captured graph is maintainable is HOW MANY nodes move. Kept per position in
|
||||
* the pass and compared against the previous step's. */
|
||||
/* TWO digests, not one, and the op handle beside them. A count of moving nodes is enough to SIZE
|
||||
* a graph; it is not enough to DESIGN one. A node whose operand pointer moved can be left alone if
|
||||
* the pointer can be made stable -- the same address refilled in place -- and then the captured
|
||||
* graph replays untouched. A node whose SHAPE moved cannot: the launch geometry is baked into the
|
||||
* node at capture, so that one needs a real update, which needs launch params only the plugin shim
|
||||
* has. Which kind the ten are decides whether this is a contained change or an ABI change. */
|
||||
struct ArgSha { rad_op h; uint64_t ptr; uint64_t shp; };
|
||||
static std::vector<ArgSha> g_argsha_cur, g_argsha_prev;
|
||||
static size_t g_argsha_i = 0;
|
||||
static ArgSha argsha_of(rad_op h, int64_t n, const RadTensor* t, int n_opd) {
|
||||
uint64_t v = 1469598103934665603ull, w = 1469598103934665603ull;
|
||||
auto mix = [&](const void* p, size_t k) {
|
||||
const unsigned char* b = (const unsigned char*)p;
|
||||
for (size_t i = 0; i < k; ++i) { v ^= b[i]; v *= 1099511628211ull; }
|
||||
};
|
||||
auto mixw = [&](const void* p, size_t k) {
|
||||
const unsigned char* b = (const unsigned char*)p;
|
||||
for (size_t i = 0; i < k; ++i) { w ^= b[i]; w *= 1099511628211ull; }
|
||||
};
|
||||
mix(&h, sizeof h);
|
||||
mixw(&h, sizeof h);
|
||||
mixw(&n, sizeof n); /* the row count IS geometry: it is what the grid is derived from */
|
||||
/* ONLY THE LIVE FIELDS. `RadTensor` carries shape[RAD_MAX_RANK] and stride[RAD_MAX_RANK] of
|
||||
* which only `rank` are meaningful, and `tbuf_` is REUSED across issues -- so hashing the
|
||||
* struct whole picks up whatever the last op left in the tail slots and reports very nearly
|
||||
* every issue as having moved, which is the instrument's own scratch and not the model's
|
||||
* arguments. */
|
||||
for (int i = 0; i < n_opd; ++i) {
|
||||
const RadTensor& tt = t[i];
|
||||
mix(&tt.data, sizeof tt.data); /* WHERE -- a node-update-free fix exists */
|
||||
mixw(&tt.dtype, sizeof tt.dtype); /* WHAT -- baked into the node at capture */
|
||||
mixw(&tt.rank, sizeof tt.rank);
|
||||
for (uint32_t d = 0; d < tt.rank && d < RAD_MAX_RANK; ++d) {
|
||||
mixw(&tt.shape[d], sizeof tt.shape[d]);
|
||||
mixw(&tt.stride[d], sizeof tt.stride[d]);
|
||||
}
|
||||
}
|
||||
return ArgSha{h, v, w};
|
||||
}
|
||||
/* PER OP, because the average is the one number that cannot be acted on. Subtracting the price of
|
||||
* a bare fifteen-argument hipLaunchKernelGGL (isa/graphrate.hip has one) from `launch` leaves most
|
||||
* of a microsecond an issue in the shim's own prologue -- but that is a subtraction across two
|
||||
* different kernels, and an average over a step's ~1850 issues hides whether it is a flat tax or
|
||||
* three ops doing something silly. This charges host launch time to the op that spent it. */
|
||||
* Reported per window, not as a running mean, so load and the first prefill do not dominate, and
|
||||
* per op, so host launch time is charged to the op that spent it. */
|
||||
struct IssOp { double lau = 0.0, own = 0.0; long n = 0; };
|
||||
static std::unordered_map<uint32_t, IssOp> g_iss_by_op;
|
||||
static double g_iss_own = 0.0, g_iss_lau = 0.0;
|
||||
static double g_iss_own_p = 0.0, g_iss_lau_p = 0.0;
|
||||
static long g_iss_n = 0;
|
||||
|
||||
/* THE STAGER'S TWO CALLS, around an op of a pass it armed for. Before the op, because what it
|
||||
* stages for this op has to be in the residency table before the op's tables are resolved -- and
|
||||
* sync_residency is what carries a table change into the tables that hold the weight, which the
|
||||
* pass otherwise does once, at its start. After the op, on the stream the op went to, because that
|
||||
* is where "every reader of this weight is behind us" can be recorded. */
|
||||
/* Wraps issue_body with the stager's calls on a pass it armed for. before_op runs before the
|
||||
* op's tables are resolved, followed by sync_residency if the stager changed the residency table.
|
||||
* after_op runs on the op's stream, where "every reader of this weight is behind us" can be
|
||||
* recorded. */
|
||||
int Ctx::issue(rad_op h, const RadOperand* opd, int n_opd, int64_t n) {
|
||||
if (!staging_) return issue_body(h, opd, n_opd, n);
|
||||
if (step_status_ < 0) return step_status_;
|
||||
@@ -526,9 +413,8 @@ int Ctx::issue(rad_op h, const RadOperand* opd, int n_opd, int64_t n) {
|
||||
int Ctx::issue_body(rad_op h, const RadOperand* opd, int n_opd, int64_t n) {
|
||||
const auto t_iss0 = g_dbg_issue ? std::chrono::steady_clock::now()
|
||||
: std::chrono::steady_clock::time_point{};
|
||||
/* The step is already aborted. rad_arch_step is void and cannot know, so it will keep issuing
|
||||
* the rest of the layer; launching those would burn a step whose output is already wrong and
|
||||
* bury the first error under fifty more. */
|
||||
/* Step already aborted. rad_arch_step is void and keeps issuing; skip the rest so the first
|
||||
* error stays the reported one. */
|
||||
if (step_status_ < 0) return step_status_;
|
||||
|
||||
if (h == RAD_NULL_HANDLE || (size_t)h >= plans_.size())
|
||||
@@ -537,13 +423,12 @@ int Ctx::issue_body(rad_op h, const RadOperand* opd, int n_opd, int64_t n) {
|
||||
|
||||
OpPlan& p = plans_[h];
|
||||
|
||||
/* RAD_N_BATCH is what almost every op wants: the ranged parameter is the step's token count. */
|
||||
/* RAD_N_BATCH: the ranged parameter is the step's token count. */
|
||||
if (n == RAD_N_BATCH) n = batch_ ? batch_->n_tok : 0;
|
||||
|
||||
/* The bucket table. Bands are sorted by their inclusive upper bound and there are two to four
|
||||
* of them -- the union of the LE/GE/EQ values the candidate kernels placed on the ranged
|
||||
* parameter (spec §2.2). A linear scan is one to three predictable compares off one cache
|
||||
* line, which beats any table or division scheme at this size. */
|
||||
/* The bucket table: two to four bands sorted by inclusive upper bound, from the candidate
|
||||
* kernels' LE/GE/EQ constraints on the ranged parameter (spec §2.2). A linear scan is the
|
||||
* fastest option at this size. */
|
||||
const int64_t* hi = band_table_.data() + p.band_off;
|
||||
int b = 0;
|
||||
while (b < p.n_bands && n > hi[b]) ++b;
|
||||
@@ -558,6 +443,12 @@ int Ctx::issue_body(rad_op h, const RadOperand* opd, int n_opd, int64_t n) {
|
||||
? "has no host kernel for this band, and the placement planner put "
|
||||
"it on the host anyway"
|
||||
: "has no device kernel for this band");
|
||||
/* The row's DIV on the ranged parameter held at the band's upper bound, maybe not here. */
|
||||
if (ip.ranged_div > 1 && n % ip.ranged_div != 0)
|
||||
return abort_step_msg(h, RAD_E_SHAPE,
|
||||
fmt("issued at %lld, which kernel %s does not serve: it requires a "
|
||||
"multiple of %lld and was selected at the band's upper bound",
|
||||
(long long)n, ip.row->info->name, (long long)ip.ranged_div));
|
||||
|
||||
if (n_opd < 0 || n_opd > MAX_OPERANDS)
|
||||
return abort_step_msg(h, RAD_E_INVAL,
|
||||
@@ -583,8 +474,8 @@ int Ctx::issue_body(rad_op h, const RadOperand* opd, int n_opd, int64_t n) {
|
||||
return abort_step_msg(h, RAD_E_INVAL,
|
||||
fmt("operand %d names buffer handle %u, which declare never "
|
||||
"returned", i, bh));
|
||||
/* One struct copy: dtype, rank, shape and packed strides came from the declaration and
|
||||
* the data pointer is already arena_base + BufferInfo::arena_offset. */
|
||||
/* Template: declared dtype, rank, shape and packed strides; data is already
|
||||
* arena_base + BufferInfo::arena_offset. */
|
||||
tt = buf_tmpl_[bh];
|
||||
touches_host |= buf_host_[bh] != 0;
|
||||
if (o.offset) {
|
||||
@@ -598,50 +489,27 @@ int Ctx::issue_body(rad_op h, const RadOperand* opd, int n_opd, int64_t n) {
|
||||
rad_dtype_name(tt.dtype)));
|
||||
tt.data = static_cast<char*>(tt.data) + d;
|
||||
}
|
||||
/* rows > 0 narrows dim 0, which is how a prefill chunk of `rows` tokens issues against
|
||||
* a buffer the plan sized at max_tok. The strides do not change and must not: they are
|
||||
* products of the trailing dimensions, so shortening the outermost one leaves every
|
||||
* one of them correct. That is the whole reason the narrowing is dim 0 only. */
|
||||
/* rows > 0 narrows dim 0, so a prefill chunk issues against a buffer sized at
|
||||
* max_tok. Strides stay valid since they are products of the trailing dimensions. */
|
||||
if (o.rows > 0) tt.shape[0] = o.rows;
|
||||
narrow_cols(o, &tt);
|
||||
/* AND IT HAS TO FIT THE BUFFER IT NAMES. Narrowing dim 0 is how a chunk of `rows`
|
||||
* tokens issues against a plan sized at max_tok, and the arrow points one way only:
|
||||
* an operand may name FEWER rows than the declaration, never more.
|
||||
*
|
||||
* A read past the end is uninitialised memory. A WRITE past the end is another
|
||||
* buffer's bytes, and the arena packs by liveness -- so what it lands on is whatever
|
||||
* the planner put there, which changes with the graph. That is the worst shape of
|
||||
* bug this runtime can have: it is silent, it is not reproducible across a config
|
||||
* change, and the model can stay correct for as long as the victim happens to be
|
||||
* dead. The canonical shape of it is a MoE expert plane declared at max_tok rows while
|
||||
* the gated quantiser writes rows*top_k of them, which nothing notices until some
|
||||
* later op happens to read the buffer the overrun lands on. */
|
||||
/* An operand may name fewer rows than the declaration, never more. A write past the
|
||||
* end lands on whatever buffer the liveness packing placed there, which changes with
|
||||
* the graph, so the corruption is silent and config-dependent (e.g. a MoE expert plane
|
||||
* declared at max_tok rows but written at rows*top_k). */
|
||||
if (!operand_fits(tt, o.offset, buf_tmpl_[bh]))
|
||||
return abort_step_msg(h, RAD_E_SHAPE,
|
||||
fmt("operand %d reaches past buffer '%s': %s at offset "
|
||||
"%lld, declared %s", i,
|
||||
program_->buffers[bh].name.c_str(),
|
||||
opd_shape_str(tt).c_str(), (long long)o.offset,
|
||||
opd_shape_str(buf_tmpl_[bh]).c_str()));
|
||||
/* AND THE OP HAS TO BE INSIDE THE BUFFER'S PLANNED LIFETIME.
|
||||
*
|
||||
* rad_op_reads/rad_op_writes are what the buffer plan is computed from, and they are
|
||||
* OPT-IN per op -- a buffer nothing declared gets the whole program and shares nothing,
|
||||
* which is the sound default. What is NOT sound is an op that touches a buffer other
|
||||
* ops DID declare, outside the range those declarations produced: the arena has laid
|
||||
* something else over those bytes, and what comes back is whatever the planner put
|
||||
* there. It reads as data, so nothing downstream can tell.
|
||||
*
|
||||
* This defect class recurs, and its shape is always the same: an op acquires a read
|
||||
* its declaration never mentioned. `attn_paged` reading the QSA selection is the
|
||||
* pattern -- the block table arrives as a raw batch pointer, so the op's declared read
|
||||
* set is just the query, and a page id fetched out of a reused buffer is an address
|
||||
* outside every mapping. It survives every step until a wider buffer changes the
|
||||
* packing.
|
||||
*
|
||||
* REFUSED RATHER THAN WARNED, because the failure it prevents is silent and is not
|
||||
* reproducible across a graph change -- the victim buffer is whatever the plan chose
|
||||
* this time. */
|
||||
tensor_shape_str(tt).c_str(), (long long)o.offset,
|
||||
tensor_shape_str(buf_tmpl_[bh]).c_str()));
|
||||
/* The op must lie inside the buffer's planned lifetime. The plan is computed from the
|
||||
* opt-in rad_op_reads/rad_op_writes; a buffer nothing declared lives for the whole
|
||||
* program. An op touching a declared buffer outside [first_def, last_use] may see
|
||||
* bytes the arena reused for another buffer, typically because the op gained a read
|
||||
* its declaration never mentioned. Refused, not warned: the failure is silent and
|
||||
* depends on the plan's packing. */
|
||||
{
|
||||
const BufferInfo& bi = program_->buffers[bh];
|
||||
if (bi.first_def >= 0 &&
|
||||
@@ -684,26 +552,23 @@ int Ctx::issue_body(rad_op h, const RadOperand* opd, int n_opd, int64_t n) {
|
||||
}
|
||||
if (o.rows > 0) tt.shape[0] = o.rows;
|
||||
narrow_cols(o, &tt);
|
||||
/* THE SAME FIT A BUFFER OPERAND HAS TO PASS, for the same reason. A slice that reaches
|
||||
* past the declared weight reads whatever the loader or the mover put after it -- the
|
||||
* next weight in the slab, or the end of the allocation -- and a GEMM over it produces
|
||||
* plausible numbers. Only a sliced operand can overrun, so the whole-weight case every
|
||||
* RAD_W issue takes skips the arithmetic. */
|
||||
/* Same fit check as a buffer: an overrunning slice reads the next weight in the slab
|
||||
* and yields plausible numbers. Only a sliced operand can overrun, so whole-weight
|
||||
* issues skip it. */
|
||||
if ((o.offset || o.rows > 0 || o.cols > 0) &&
|
||||
!operand_fits(tt, o.offset, w_tmpl_[wh]))
|
||||
return abort_step_msg(h, RAD_E_SHAPE,
|
||||
fmt("operand %d reaches past weight '%s': %s at offset "
|
||||
"%lld, declared %s", i,
|
||||
program_->weights[wh].name.c_str(),
|
||||
opd_shape_str(tt).c_str(), (long long)o.offset,
|
||||
opd_shape_str(w_tmpl_[wh]).c_str()));
|
||||
tensor_shape_str(tt).c_str(), (long long)o.offset,
|
||||
tensor_shape_str(w_tmpl_[wh]).c_str()));
|
||||
break;
|
||||
}
|
||||
|
||||
case RAD_OPK_WTAB: {
|
||||
/* A RUN of declared weights, handed over as a device array of pointers. `handle` is
|
||||
* the first and `rows` is the count -- rad_decl_weight gives out consecutive indices,
|
||||
* so a declaration loop over experts produces exactly such a run. */
|
||||
/* A run of declared weights, passed as a device array of pointers. `handle` is the
|
||||
* first, `rows` the count. */
|
||||
const uint32_t w0 = o.handle;
|
||||
const int64_t cnt = o.rows;
|
||||
if (w0 == RAD_NULL_HANDLE || cnt <= 0 ||
|
||||
@@ -723,10 +588,9 @@ int Ctx::issue_body(rad_op h, const RadOperand* opd, int n_opd, int64_t n) {
|
||||
}
|
||||
|
||||
case RAD_OPK_RAW:
|
||||
/* A pointer the core did not allocate -- a RadBatch field, almost always. It has no
|
||||
* BufferInfo, so there is no dtype and no shape to derive: the kernel knows both from
|
||||
* the op's schema, which is where that knowledge belongs. The core carries the pointer
|
||||
* and, if the caller gave one, the row count. */
|
||||
/* A pointer the core did not allocate, usually a RadBatch field. No BufferInfo, so
|
||||
* dtype and shape come from the op's schema; the core carries the pointer and the
|
||||
* optional row count. */
|
||||
if (o.offset && o.dtype == RAD_DT_INVALID)
|
||||
return abort_step_msg(h, RAD_E_INVAL,
|
||||
fmt("operand %d is a raw pointer with an element offset of "
|
||||
@@ -736,13 +600,10 @@ int Ctx::issue_body(rad_op h, const RadOperand* opd, int n_opd, int64_t n) {
|
||||
i, (long long)o.offset));
|
||||
std::memset(&tt, 0, sizeof tt);
|
||||
tt.data = o.raw;
|
||||
tt.dtype = o.dtype; /* RAD_DT_INVALID unless the caller said, which is the point of
|
||||
* the field: libref reads positions, cu_seqlens and
|
||||
* num_accepted through the tensor's dtype and cannot guess. */
|
||||
/* `cols` on a RAW operand is the SECOND EXTENT, not a column slice: there is no
|
||||
* declared width to slice out of. RAD_P_T2 is how a batch field that is genuinely
|
||||
* two-dimensional says so, and the block table is why it exists -- [n_seq, max_blocks]
|
||||
* handed over as rank 1 loses its width, and every kernel that reads it then guesses. */
|
||||
tt.dtype = o.dtype; /* RAD_DT_INVALID unless given; libref reads positions,
|
||||
* cu_seqlens and num_accepted through the tensor's dtype. */
|
||||
/* On a raw operand `cols` is the second extent, not a column slice (RAD_P_T2), e.g.
|
||||
* the [n_seq, max_blocks] block table. */
|
||||
if (o.rows > 0 && o.cols > 0) {
|
||||
tt.rank = 2;
|
||||
tt.shape[0] = o.rows; tt.shape[1] = o.cols;
|
||||
@@ -753,10 +614,9 @@ int Ctx::issue_body(rad_op h, const RadOperand* opd, int n_opd, int64_t n) {
|
||||
break;
|
||||
|
||||
case RAD_OPK_KV: {
|
||||
/* A KV group's cache for one layer. `handle` is the rad_kvgroup and `offset` is the
|
||||
* ABSOLUTE layer index, which the binding rebases -- a group holds one cache per bound
|
||||
* layer, not one per model layer, and 48 GDN layers interleaved with 16 attention ones
|
||||
* would otherwise index a 64-deep pool that was never allocated. */
|
||||
/* A KV group's cache for one layer. `handle` is the rad_kvgroup, `offset` the absolute
|
||||
* layer index, rebased through the binding because a group holds one cache per bound
|
||||
* layer, not per model layer. */
|
||||
const uint32_t g = o.handle;
|
||||
if ((size_t)g >= kv_.size() || !kv_[g].base)
|
||||
return abort_step_msg(h, RAD_E_STATE,
|
||||
@@ -767,10 +627,8 @@ int Ctx::issue_body(rad_op h, const RadOperand* opd, int n_opd, int64_t n) {
|
||||
"rad_kv_group_zero and then issued against, which the "
|
||||
"plugin must not do", i, g));
|
||||
const KVPoolBinding& b = kv_[g];
|
||||
/* A POSITION LOOKUP, not `o.offset - first_layer`. The subtraction is right only for a
|
||||
* group whose layers are contiguous, and they need not be: with 15 attention layers
|
||||
* interleaved through 64, absolute layer 19 -- the fifth of them -- subtracts to slot
|
||||
* 16 of a 15-slot pool, which the bounds check below refuses. */
|
||||
/* A lookup, not a subtraction: a group's layers need not be contiguous
|
||||
* (KVPoolBinding::layer_slot). */
|
||||
const int64_t layer = (o.offset >= 0 && (size_t)o.offset < b.layer_slot.size())
|
||||
? b.layer_slot[(size_t)o.offset]
|
||||
: -1;
|
||||
@@ -783,11 +641,8 @@ int Ctx::issue_body(rad_op h, const RadOperand* opd, int n_opd, int64_t n) {
|
||||
std::memset(&tt, 0, sizeof tt);
|
||||
tt.data = static_cast<char*>(b.base) + off;
|
||||
tt.dtype = b.dtype;
|
||||
/* THE OPERAND CARRIES THE LAYER'S SHAPE, not a flat byte span. The binding composed it
|
||||
* at load out of the plugin's declaration and the block manager's decisions, because
|
||||
* neither half alone is enough (core/runtime/ctx.h says which numbers and why). Every
|
||||
* libr4d shim refuses a flat span -- `if (kv->rank != 4) return RAD_E_SHAPE` -- and
|
||||
* refuses correctly: a paged cache walked as one dimension is not a cache. */
|
||||
/* The operand carries the layer's shape, composed at load (see KVPoolBinding in
|
||||
* ctx.h); libr4d shims refuse a flat span. */
|
||||
if (b.rank) {
|
||||
tt.rank = b.rank;
|
||||
for (uint32_t d = 0; d < b.rank; ++d) tt.shape[d] = b.shape[d];
|
||||
@@ -811,112 +666,41 @@ int Ctx::issue_body(rad_op h, const RadOperand* opd, int n_opd, int64_t n) {
|
||||
}
|
||||
}
|
||||
|
||||
/* Everything else in RadArgs -- the geometry view, the scratch pointer and its size, the
|
||||
* instance init() returned, the rank and the world size -- was filled in at prepare and has
|
||||
* not changed. args.t already points at tbuf_. */
|
||||
/* The rest of RadArgs was filled in at prepare; args.t already points at tbuf_. */
|
||||
ip.args.n_t = n_opd;
|
||||
p.issued = true;
|
||||
++n_issues_;
|
||||
|
||||
/* RADIANCE_DEBUG_ARGSHA -- see the note by the digest. Pass 1 only, so the sequence compared
|
||||
* step to step is the same sequence. */
|
||||
|
||||
/* RANK 0 ONLY. These accumulators are file-scope statics and `Ctx::issue` runs on EVERY rank
|
||||
* thread, so without this the two ranks interleave into one sequence: the issue COUNT then
|
||||
* varies run to run and every digest differs, which reads exactly like a data-dependent op
|
||||
* sequence and is not one. */
|
||||
if (g_dbg_argsha && batch_ && rank() == 0) {
|
||||
const int dp = batch_->draft_pass;
|
||||
if (dp != g_argsha_pass) {
|
||||
if (g_argsha_pass == 1 && !g_argsha_cur.empty() && g_argsha_seen < 12) {
|
||||
size_t mptr = 0, mshp = 0;
|
||||
const size_t k = g_argsha_cur.size() < g_argsha_prev.size()
|
||||
? g_argsha_cur.size() : g_argsha_prev.size();
|
||||
for (size_t i = 0; i < k; ++i) {
|
||||
if (g_argsha_cur[i].ptr != g_argsha_prev[i].ptr) ++mptr;
|
||||
if (g_argsha_cur[i].shp != g_argsha_prev[i].shp) ++mshp;
|
||||
}
|
||||
if (!g_argsha_prev.empty()) {
|
||||
std::fprintf(stderr,
|
||||
"D argsha: draft pass 1 -- %zu issues, %zu moved a POINTER, "
|
||||
"%zu moved a SHAPE\n",
|
||||
g_argsha_cur.size(), mptr, mshp);
|
||||
if (g_argsha_seen < 2) {
|
||||
auto nm = [&](rad_op oh) -> const char* {
|
||||
return (oh != RAD_NULL_HANDLE && (size_t)oh < plans_.size() &&
|
||||
plans_[oh].info)
|
||||
? plans_[oh].info->op.c_str() : "<?>";
|
||||
};
|
||||
for (size_t i = 0; i < k; ++i) {
|
||||
const bool p = g_argsha_cur[i].ptr != g_argsha_prev[i].ptr;
|
||||
const bool q = g_argsha_cur[i].shp != g_argsha_prev[i].shp;
|
||||
if (p || q)
|
||||
std::fprintf(stderr, "D argsha: %2zu %-24s %s%s\n", i,
|
||||
nm(g_argsha_cur[i].h), p ? "ptr " : "",
|
||||
q ? "shape" : "");
|
||||
}
|
||||
}
|
||||
}
|
||||
++g_argsha_seen;
|
||||
g_argsha_prev = g_argsha_cur;
|
||||
} else if (g_argsha_pass == 1) {
|
||||
g_argsha_prev = g_argsha_cur;
|
||||
}
|
||||
if (dp == 1) { g_argsha_cur.clear(); g_argsha_i = 0; }
|
||||
g_argsha_pass = dp;
|
||||
}
|
||||
if (dp == 1) { g_argsha_cur.push_back(argsha_of(h, n, t, n_opd)); ++g_argsha_i; }
|
||||
}
|
||||
|
||||
/* THE LINK BILL, charged where the message size is known and nothing has to be guessed: `n`
|
||||
* IS the collective's `numel` (every all_reduce declares it as the ranged parameter) and
|
||||
* operand 0 carries the dtype it is sent in, which is the ACTIVATION's dtype and not the op's
|
||||
* `dtype` key -- that key is the architecture's operand-combination spelling ("w4a8"), which
|
||||
* is not an element width. Two relaxed adds on seventeen issues a step. */
|
||||
/* All-reduce link accounting: `n` is the collective's numel (its ranged parameter) and operand
|
||||
* 0's dtype is the wire element type. The op's `dtype` key ("w4a8") is not an element
|
||||
* width. */
|
||||
if (p.billed && n_opd > 0) {
|
||||
const int bits = rad_dtype_bits(t[0].dtype);
|
||||
ar_calls_.fetch_add(1, std::memory_order_relaxed);
|
||||
if (bits > 0) ar_bytes_.fetch_add(n * bits / 8, std::memory_order_relaxed);
|
||||
}
|
||||
|
||||
/* The oracle, if this issue is one it was asked about. It snapshots every operand to the host
|
||||
* before the launch so the host kernel can be given the same bytes -- an in-place op would
|
||||
* otherwise be compared against its own output. Null in every run that did not arm it. */
|
||||
/* The oracle snapshots every operand before the launch, so the host kernel sees the same
|
||||
* input bytes even for an in-place op. */
|
||||
const IssuePlan* horacle = oracle_ ? oracle_before(h, b, n_opd) : nullptr;
|
||||
|
||||
/* ============================== A HOST LAUNCH IS A JOIN ==============================
|
||||
/* ============================== a host launch is a join ==============================
|
||||
*
|
||||
* THE HOST THREAD RUNS AHEAD OF THE DEVICE. Every device launch is asynchronous, so by the
|
||||
* time this function is called for op N the GPU may still be somewhere back at op N-200 --
|
||||
* that gap is the whole reason the issue path is allowed to cost a microsecond. A HOST-SITE op
|
||||
* is the one place it stops being harmless: it runs NOW, on this thread, and reads and writes
|
||||
* the host arena NOW.
|
||||
* The host runs ahead of the device, but a host-site op reads and writes the host arena now,
|
||||
* on this thread. Without a join it reads stale data, e.g. a host PLE gather
|
||||
* (`embed_lookup_q`) reading row ids a device `ngram_ids` has not yet written: valid ids,
|
||||
* wrong rows, fluent wrong output.
|
||||
*
|
||||
* A PLE gather on the host is exactly that shape. `ngram_ids` writes the hashed row ids into a
|
||||
* host-domain buffer on the device, and `embed_lookup_q` reads them on the host. With no join
|
||||
* the host reads whatever the arena holds from an earlier step and gathers the rows of the
|
||||
* wrong n-gram -- valid ids, valid rows, every kernel agreeing with its oracle, and fluent text
|
||||
* that is a stable wrong answer rather than an intermittent one.
|
||||
* The join waits on the last device op per lane that touched the host arena (host_touch_ev_),
|
||||
* not the whole stream: every hazard is with such an op, and draining would idle the device
|
||||
* while the host works. An architecture can issue the producer early and keep the device busy
|
||||
* meanwhile. A host op naming an untracked operand (raw pointer, KV cache, device-domain
|
||||
* buffer) drains its stream instead (host_join).
|
||||
*
|
||||
* WHAT THE JOIN WAITS FOR is the last device op on each lane that touched the host arena
|
||||
* (host_touch_ev_), not the whole stream. Every hazard a host op has is with such an op -- the
|
||||
* producer of an input, or a device reader of bytes its output reuses -- and on one lane they
|
||||
* all complete no later than the last of them. Draining the stream instead waits for
|
||||
* everything issued before the op, which on a decode step is every layer in front of it, and
|
||||
* then the device runs dry while the host works, because nothing after the host op has been
|
||||
* issued yet. Waiting on the producer alone lets an architecture issue it early and keep the
|
||||
* device busy with the layers issued in between while the host gathers.
|
||||
*
|
||||
* AN OPERAND THE ARENA DOES NOT DESCRIBE IS NOT TRACKED -- a raw batch pointer, a KV cache, a
|
||||
* device-domain buffer -- so a host op that names one drains its stream (host_join).
|
||||
*
|
||||
* AND THE HOST'S WRITES HAVE TO REACH THE DEVICE. Host-arena memory is cached on the device like
|
||||
* any other memory, and with no host wait between the host op and the kernel that reads its
|
||||
* output, nothing would make that kernel look past a stale line: rad_dev_host_wrote, after the
|
||||
* launch below, is what does. */
|
||||
* The device caches host-arena memory, so rad_dev_host_wrote after the launch makes the
|
||||
* host's writes visible to later kernels. */
|
||||
if (dom == RAD_DOMAIN_HOST) {
|
||||
/* TIMED APART FROM THE OP, because it is not the op's cost -- it is the cost of the
|
||||
* PIPELINE this op stops. */
|
||||
/* Timed apart from the op: it is the cost of stopping the pipeline. */
|
||||
if (profiling_) {
|
||||
const auto j0 = std::chrono::steady_clock::now();
|
||||
const int js = host_join(opd, n_opd);
|
||||
@@ -929,22 +713,17 @@ int Ctx::issue_body(rad_op h, const RadOperand* opd, int n_opd, int64_t n) {
|
||||
}
|
||||
}
|
||||
|
||||
/* A SCRATCH REGION IS ONE STREAM'S. The kernels on a lane are handed consecutive slices of it
|
||||
* (scratch_take), and two that could run at once on the lane are kept apart by the slices
|
||||
* being disjoint -- the pass's recording orders any pair whose slices meet (haz_mark). A
|
||||
* scratch user on each lane with no join between them overlaps with nothing recorded to order
|
||||
* it, and the two would overwrite each other's partials with nothing downstream able to tell.
|
||||
* A split-K router GEMM on lane 0 and the shared arm's split-K GEMM on lane 1 meet exactly
|
||||
* like that on every MoE layer.
|
||||
/* A scratch region belongs to one stream. Kernels on a lane get consecutive slices
|
||||
* (scratch_take); a recorded pass orders any pair whose slices meet (haz_mark). Scratch users
|
||||
* on two unjoined lanes would overwrite each other's partials (e.g. split-K router GEMM on
|
||||
* lane 0 and the shared arm's split-K GEMM on lane 1, every MoE layer).
|
||||
*
|
||||
* So a program that declares its second lane gets a region per lane, and each launch is
|
||||
* pointed at its own lane's. A lane used WITHOUT that declaration shares region 0, and there
|
||||
* the second of such a pair is ordered behind the first instead -- the overlap is given up for
|
||||
* that launch, never the numbers. That fallback is kept on lane 0 before lane 1 exists as well:
|
||||
* a lane built later starts with nothing ordering it behind what lane 0 already issued. */
|
||||
* A program that declares its second lane gets a region per lane. Otherwise both lanes share
|
||||
* region 0 and the second user is ordered behind the first, giving up the overlap but not
|
||||
* correctness. That also covers lane 0 before lane 1 exists, since a lane built later has
|
||||
* nothing ordering it behind lane 0's earlier work. */
|
||||
if (ip.args.scratch_bytes > 0 && dom != RAD_DOMAIN_HOST && arena_.scratch_regions() > 1) {
|
||||
/* Each lane has its own region, so two scratch users on two lanes never share bytes and
|
||||
* nothing has to be ordered. The plan entry serves whichever lane issues it. */
|
||||
/* Per-lane regions: nothing to order. */
|
||||
ip.args.scratch = scratch_take(lane_, ip.args.scratch_bytes);
|
||||
} else if (ip.args.scratch_bytes > 0 && dom != RAD_DOMAIN_HOST) {
|
||||
ip.args.scratch = scratch_take(0, ip.args.scratch_bytes);
|
||||
@@ -968,9 +747,9 @@ int Ctx::issue_body(rad_op h, const RadOperand* opd, int n_opd, int64_t n) {
|
||||
scratch_n_[lane_] = n;
|
||||
}
|
||||
|
||||
/* A HOST-SITE OP IN A PASS BEING RECORDED is host work a tape cannot hold: the recording is
|
||||
* cut here and the op kept, to be joined and run again on these operands at every play. Its
|
||||
* launch is not recorded either way -- anything it submitted would be submitted twice. */
|
||||
/* A host-site op while recording: cut the tape and keep the op, to be joined and rerun on
|
||||
* these operands at every play. Its launch is not recorded, or anything it submitted would be
|
||||
* submitted twice. */
|
||||
if (rec_ && dom == RAD_DOMAIN_HOST) {
|
||||
tape_cut();
|
||||
TapeHost th;
|
||||
@@ -991,10 +770,9 @@ int Ctx::issue_body(rad_op h, const RadOperand* opd, int n_opd, int64_t n) {
|
||||
if (host_paused) tape_pause(true);
|
||||
const int rec0 = rec_ && !host_paused ? tape_mark() : 0;
|
||||
|
||||
/* A COLLECTIVE HAS THE CARD'S LINK TO ITSELF in a pass the stager copies weights through: the
|
||||
* stager's lists yield while the hold is in force (rad_link_hold says why). Taken here, after
|
||||
* every wait this op's operands put on the stream, so the stream waits on nothing between the
|
||||
* hold and its release -- a weight it waited on could be behind a yielding list. */
|
||||
/* In a staged pass a collective holds the card's link; the stager's copy lists yield meanwhile
|
||||
* (see rad_link_hold). Taken after every wait this op's operands put on the stream, so nothing
|
||||
* between hold and release can wait on a weight stuck behind a yielding list. */
|
||||
const bool hold = staging_ && p.collective && dom == RAD_DOMAIN_DEVICE;
|
||||
const RadArgs* la = &ip.args;
|
||||
RadArgs gate_args;
|
||||
@@ -1012,18 +790,9 @@ int Ctx::issue_body(rad_op h, const RadOperand* opd, int n_opd, int64_t n) {
|
||||
int s;
|
||||
if (profiling_ && dom == RAD_DOMAIN_HOST) {
|
||||
|
||||
/* A HOST-SITE OP IS TIMED ON THE HOST CLOCK, because device events cannot see it: they
|
||||
* record when the STREAM reaches them and the stream does not stall for a host call, so an
|
||||
* event pair around this launch measures nothing and the op vanishes from the table.
|
||||
*
|
||||
* Without this the most expensive thing in the step vanishes from the table. The PLE
|
||||
* gather reads sixteen 160-byte rows out of a multi-gigabyte mapping per token, so its
|
||||
* layer costs milliseconds a step against tens of microseconds of device kernels -- and a
|
||||
* device-event profile shows only the tens of microseconds. A host kernel's cost is a
|
||||
* STALL in the middle of the step, which is the one thing an operator most needs named.
|
||||
*
|
||||
* Wall clock and not a device event, so it includes whatever the host call waits on:
|
||||
* page faults, the link read of its input, everything. That is the number that matters. */
|
||||
/* A host-site op is timed on the host wall clock; a device event pair around it would
|
||||
* measure nothing. It includes page faults and link reads, which can make a host op (e.g.
|
||||
* the PLE gather) the most expensive thing in the step. */
|
||||
const auto t0 = std::chrono::steady_clock::now();
|
||||
s = ip.launch(la, cur_stream());
|
||||
const auto t1 = std::chrono::steady_clock::now();
|
||||
@@ -1032,9 +801,8 @@ int Ctx::issue_body(rad_op h, const RadOperand* opd, int n_opd, int64_t n) {
|
||||
prof_calls_[(size_t)h] += 1;
|
||||
if ((size_t)h < prof_host_.size()) prof_host_[(size_t)h] = 1;
|
||||
} else if (profiling_) {
|
||||
/* One predictable branch in exchange for §16's per-op timing. The events go on the compute
|
||||
* stream around the launch; the synchronisation that reads them is at the end of the step,
|
||||
* and it is what makes a profiled run incomparable to an unprofiled one. */
|
||||
/* Spec §16 per-op timing: events around the launch, read by a sync at the end of the
|
||||
* step (which is why profiled runs are not comparable). */
|
||||
if (prof_n_ < prof_ring_.size()) {
|
||||
ProfSlot& ps = prof_ring_[prof_n_++];
|
||||
ps.op = (int32_t)h;
|
||||
@@ -1046,11 +814,8 @@ int Ctx::issue_body(rad_op h, const RadOperand* opd, int n_opd, int64_t n) {
|
||||
prof_overflowed_ = true;
|
||||
s = ip.launch(la, cur_stream());
|
||||
}
|
||||
/* RANK 0 ONLY, FOR THE SECOND TIME IN THIS FILE. `Ctx::issue` runs on every rank thread, so a
|
||||
* file-scope accumulator is written by both. Unguarded, the digest above gives wrong NUMBERS
|
||||
* -- two ranks interleaving into one sequence -- and the per-op std::unordered_map here gives
|
||||
* a SEGFAULT within a window. Doubles race benignly enough to mislead, a hash map does not
|
||||
* race at all. Anything this instrument accumulates belongs to one thread. */
|
||||
/* Rank 0 only: these file-scope accumulators (including an unordered_map) are not
|
||||
* thread-safe, and every rank thread runs this. */
|
||||
} else if (g_dbg_issue && rank() == 0) {
|
||||
const auto ta = std::chrono::steady_clock::now();
|
||||
s = ip.launch(la, cur_stream());
|
||||
@@ -1068,7 +833,7 @@ int Ctx::issue_body(rad_op h, const RadOperand* opd, int n_opd, int64_t n) {
|
||||
"an issue (%.3f total)\n",
|
||||
g_iss_n, (g_iss_own - g_iss_own_p) / w, (g_iss_lau - g_iss_lau_p) / w,
|
||||
(g_iss_own - g_iss_own_p + g_iss_lau - g_iss_lau_p) / w);
|
||||
/* The walk is inside `own`, so this says how much of `own` it IS. */
|
||||
/* The table walk is part of `own`. */
|
||||
std::fprintf(stderr, "D issue: of which weight tables: %.3f us an issue over "
|
||||
"%.1f entries (%.1f ns an entry)\n",
|
||||
(g_wtab_us - g_wtab_us_p) / w,
|
||||
@@ -1076,9 +841,7 @@ int Ctx::issue_body(rad_op h, const RadOperand* opd, int n_opd, int64_t n) {
|
||||
(g_wtab_e - g_wtab_e_p) > 0
|
||||
? (g_wtab_us - g_wtab_us_p) * 1000.0 / (double)(g_wtab_e - g_wtab_e_p)
|
||||
: 0.0);
|
||||
/* Top by TOTAL host launch time, not by the per-issue mean: an op issued 48 times a
|
||||
* step at 2 us costs more than one issued twice at 20. Both columns are printed so a
|
||||
* fat prologue and a fat call count can be told apart. */
|
||||
/* Top ops by total host launch time, with the per-issue mean beside it. */
|
||||
std::vector<std::pair<double, uint32_t>> ord;
|
||||
ord.reserve(g_iss_by_op.size());
|
||||
for (const auto& kv : g_iss_by_op) ord.push_back({kv.second.lau, kv.first});
|
||||
@@ -1103,8 +866,8 @@ int Ctx::issue_body(rad_op h, const RadOperand* opd, int n_opd, int64_t n) {
|
||||
s = ip.launch(la, cur_stream());
|
||||
}
|
||||
if (hold) {
|
||||
/* Released whatever the launch said, by a barrier unless the launch said it ended the hold
|
||||
* itself (RAD_LINK_ENDED): a list waiting on the hold would otherwise never end. */
|
||||
/* Always released, by a barrier unless the launch ended the hold itself
|
||||
* (RAD_LINK_ENDED); otherwise a list waiting on the hold never ends. */
|
||||
const int hr = rad_link_hold(cur_stream(), la != &ip.args && s == RAD_LINK_ENDED ? 2 : 0);
|
||||
if (hr < 0 && s >= 0) s = hr;
|
||||
}
|
||||
@@ -1191,13 +954,12 @@ void Ctx::haz_note(const OpPlan& p, const IssuePlan& ip, const RadTensor* t, int
|
||||
haz_ops_.push_back(o);
|
||||
}
|
||||
|
||||
/* THE HOST OP'S JOIN; see "A HOST LAUNCH IS A JOIN" in Ctx::issue. */
|
||||
/* See "a host launch is a join" in Ctx::issue_body. */
|
||||
int Ctx::host_join(const RadOperand* opd, int n_opd) {
|
||||
return host_join_wait(host_join_drains(opd, n_opd));
|
||||
}
|
||||
|
||||
/* Whether an operand is one the arena does not track, which the join can only cover by draining
|
||||
* the stream. */
|
||||
/* Whether any operand is untracked by the host arena, so the join must drain the stream. */
|
||||
bool Ctx::host_join_drains(const RadOperand* opd, int n_opd) const {
|
||||
for (int i = 0; i < n_opd; ++i) {
|
||||
const RadOperand& o = opd[i];
|
||||
@@ -1228,9 +990,7 @@ int Ctx::abort_step(rad_op h, int band, int dom, const IssuePlan& ip, int64_t n,
|
||||
const Resolved& r = o.bands[(size_t)band].dom[dom];
|
||||
const char* key = o.ranged_key.empty() ? "n" : o.ranged_key.c_str();
|
||||
|
||||
/* std::string here, on a path that has already lost the step. The hot path above allocates
|
||||
* nothing; this one is allowed to, because the alternative is a truncated diagnostic on the
|
||||
* one occasion anybody needs a complete one. */
|
||||
/* Allocating is fine here: the step is already lost, and the diagnostic must be complete. */
|
||||
step_fail_ = fmt("kernel %s (%s, %s, %s domain) refused op '%s' at %s=%lld "
|
||||
"[band %s<=%lld] geometry {%s}: %s",
|
||||
kname, pname, r.choice.empty() ? "no tunables" : r.choice.c_str(),
|
||||
@@ -1239,11 +999,10 @@ int Ctx::abort_step(rad_op h, int band, int dom, const IssuePlan& ip, int64_t n,
|
||||
(long long)o.bands[(size_t)band].hi, r.geom.str().c_str(),
|
||||
rad_strerror(status));
|
||||
|
||||
RAD_ERR("%s", step_fail_.c_str());
|
||||
RAD_ERR("a kernel returning negative at issue is a bug in SELECTION, not a runtime condition. "
|
||||
"The step is aborted and the requests in it fail. There is no fallback here, silent "
|
||||
"or otherwise -- a silent fallback is how you ship a slow path nobody knows about "
|
||||
"(spec §17).");
|
||||
/* A kernel refusing at issue is a selection bug, not a runtime condition: the step fails
|
||||
* and there is no fallback (spec §17). */
|
||||
RAD_ERR("%s; the step is aborted (a kernel that refuses at issue was selected wrongly)",
|
||||
step_fail_.c_str());
|
||||
|
||||
step_status_ = status;
|
||||
return status;
|
||||
@@ -1296,9 +1055,8 @@ void* Ctx::buf_ptr(rad_buf b) {
|
||||
} /* namespace rad */
|
||||
|
||||
/* ================================================================== the C surface */
|
||||
/* rad_runtime.h is C, and this is the whole of its implementation. Ctx derives from RadCtx, so
|
||||
* every one of these is a static_cast and a forwarded call -- the compiler sees straight through
|
||||
* it, which is the point of the empty base rather than a reinterpret_cast. */
|
||||
/* rad_runtime.h's implementation. Ctx derives from RadCtx, so each entry is a static_cast and a
|
||||
* forwarded call. */
|
||||
extern "C" {
|
||||
|
||||
int rad_issue(RadCtx* c, rad_op op, const RadOperand* opd, int n_opd, int64_t n) {
|
||||
@@ -1308,7 +1066,7 @@ int rad_issue(RadCtx* c, rad_op op, const RadOperand* opd, int n_opd, int64_t n)
|
||||
|
||||
int rad_step_fail(RadCtx* c, const char* what) {
|
||||
if (!c) rad::fatal("rad_step_fail: null RadCtx");
|
||||
return static_cast<rad::Ctx*>(c)->step_fail(what ? what : "the architecture block refused this batch");
|
||||
return static_cast<rad::Ctx*>(c)->step_fail(what);
|
||||
}
|
||||
|
||||
const RadBatch* rad_batch(RadCtx* c) { return c ? static_cast<rad::Ctx*>(c)->batch() : nullptr; }
|
||||
@@ -1316,12 +1074,10 @@ int rad_rank(RadCtx* c) { return c ? static_cast<rad::Ctx*>(c)
|
||||
int rad_world_size(RadCtx* c) { return c ? static_cast<rad::Ctx*>(c)->world_size() : 1; }
|
||||
RadStream rad_stream(RadCtx* c) { return c ? static_cast<rad::Ctx*>(c)->stream() : nullptr; }
|
||||
|
||||
/* The second lane. `rad_lane` says which one subsequent issues launch on; `rad_lane_join` orders
|
||||
* one behind the other with an event and blocks neither the host nor either stream. The runtime
|
||||
* joins lane 1 back into lane 0 at the end of every step whatever the plugin did, so forgetting
|
||||
* the join is a performance bug and not a correctness one. Read Ctx::lane1_ before using this:
|
||||
* every collective must ride ONE lane, a second lane may not carry a split-K GEMM, and the buffer
|
||||
* planner packs from a single linear order. */
|
||||
/* The second lane. `rad_lane` selects the lane subsequent issues launch on; `rad_lane_join`
|
||||
* orders one behind the other with an event, blocking neither the host nor a stream. The runtime
|
||||
* joins lane 1 back into lane 0 at the end of every step, so a missing join costs performance,
|
||||
* not correctness. See Ctx::lane1_ for the constraints before using it. */
|
||||
int rad_lane(RadCtx* c, int lane) {
|
||||
if (!c) return RAD_E_INVAL;
|
||||
return static_cast<rad::Ctx*>(c)->set_lane(lane);
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
/* kvbind.cpp -- see kvbind.h. */
|
||||
#include "kvbind.h"
|
||||
|
||||
#include "mem/kv.h"
|
||||
|
||||
namespace rad {
|
||||
|
||||
void bind_kv_pools(const Program& p, const std::function<const KVGroupPlan*(int32_t)>& plan_of,
|
||||
std::vector<KVPoolBinding>* out) {
|
||||
out->assign(p.kv_groups.size(), KVPoolBinding{});
|
||||
for (size_t g = 0; g < p.kv_groups.size(); ++g) {
|
||||
const KVGroupPlan* gp = plan_of((int32_t)g);
|
||||
if (!gp) continue;
|
||||
KVPoolBinding& b = (*out)[g];
|
||||
b.base = gp->base;
|
||||
b.layer_stride = gp->layer_stride();
|
||||
b.bytes = gp->pool_bytes;
|
||||
b.dtype = p.kv_groups[g].decl.dtype;
|
||||
|
||||
/* The position of every bound layer, indexed by its absolute number. */
|
||||
const std::vector<int32_t>& ls = p.kv_groups[g].layers;
|
||||
int32_t hi = -1;
|
||||
for (int32_t l : ls) if (l > hi) hi = l;
|
||||
b.layer_slot.assign((size_t)(hi + 1), -1);
|
||||
for (size_t i = 0; i < ls.size(); ++i) b.layer_slot[(size_t)ls[i]] = (int32_t)i;
|
||||
|
||||
/* One layer's cache shape, in the layout libref/ref_ops.h defines. Built here because only
|
||||
* this point has both the plugin's declaration (heads, head_dim, state_dim, conv_width)
|
||||
* and the block manager's decisions (block_size, n_blocks, n_states, conv_slots); a
|
||||
* kernel cannot derive the conv depth or slot count from op parameters. */
|
||||
const RadKVGroupDecl& d = p.kv_groups[g].decl;
|
||||
switch (gp->kind) {
|
||||
case RAD_KV_FULL:
|
||||
case RAD_KV_WINDOW:
|
||||
b.rank = 4;
|
||||
b.shape[0] = gp->n_blocks;
|
||||
b.shape[1] = d.n_head_kv;
|
||||
b.shape[2] = gp->block_size;
|
||||
b.shape[3] = 2 * d.head_dim;
|
||||
break;
|
||||
case RAD_KV_LINEAR:
|
||||
b.rank = 4;
|
||||
b.shape[0] = gp->n_states;
|
||||
b.shape[1] = d.n_head_kv;
|
||||
b.shape[2] = d.state_dim[0];
|
||||
b.shape[3] = d.state_dim[1];
|
||||
break;
|
||||
case RAD_KV_CONV:
|
||||
b.rank = 3;
|
||||
b.shape[0] = gp->n_states;
|
||||
b.shape[1] = d.n_head_kv * d.head_dim;
|
||||
b.shape[2] = gp->conv_slots;
|
||||
break;
|
||||
default:
|
||||
b.rank = 0; /* the null sentinel at handle 0; nothing issues against it */
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
} /* namespace rad */
|
||||
@@ -0,0 +1,19 @@
|
||||
/* kvbind.h -- the KV group pools as the run phase addresses them (KVPoolBinding, ctx.h). */
|
||||
#pragma once
|
||||
#include "ctx.h"
|
||||
|
||||
#include <functional>
|
||||
#include <vector>
|
||||
|
||||
namespace rad {
|
||||
|
||||
struct KVGroupPlan;
|
||||
|
||||
/* One binding per KV group of `p`, from the block manager's plan for it (`plan_of(g)`, null for a
|
||||
* group with none). An operand names an absolute model layer while a pool holds only its group's
|
||||
* layers, so each bound layer maps to its position in the group: in a group of layers 3, 7, ...,
|
||||
* layer 7 is the second; subtracting the first bound layer would give the fifth. */
|
||||
void bind_kv_pools(const Program& p, const std::function<const KVGroupPlan*(int32_t)>& plan_of,
|
||||
std::vector<KVPoolBinding>* out);
|
||||
|
||||
} /* namespace rad */
|
||||
+300
-369
File diff suppressed because it is too large.
Load diff
@@ -9,9 +9,8 @@ void RankBarrier::arrive_and_wait() {
|
||||
|
||||
const uint64_t my_gen = gen_;
|
||||
if (++waiting_ == n_) {
|
||||
/* Last one in flips the generation and releases the rest. The counter is reset here rather
|
||||
* than by the wakers, so a rank that re-enters immediately observes a generation it has
|
||||
* not seen and blocks instead of racing through. */
|
||||
/* Last one in resets the counter and flips the generation, so a rank that re-enters at
|
||||
* once waits on the new generation instead of racing through. */
|
||||
waiting_ = 0;
|
||||
++gen_;
|
||||
lk.unlock();
|
||||
|
||||
+10
-20
@@ -1,21 +1,13 @@
|
||||
/* rank_barrier.h -- the release point for the tensor-parallel rank threads.
|
||||
*
|
||||
* WHY THIS IS NOT IPC. Radiance is one process. One thread per rank, each owning one device
|
||||
* (spec §1). The ranks therefore share an address space, so the step batch is shared BY POINTER
|
||||
* rather than broadcast: there is nothing to serialise, no shared-memory segment to map, no file
|
||||
* descriptor, no pickling, and no handshake protocol that can get out of step with itself. All
|
||||
* that is left for the barrier to do is establish happens-before between the scheduler's release
|
||||
* and each rank's first rad_issue, and between the ranks' last issue and the scheduler's next
|
||||
* batch build.
|
||||
* Radiance is one process with one thread per rank, each owning one device (spec §1), so the step
|
||||
* batch is shared by pointer rather than serialised to other processes. The barrier only
|
||||
* establishes happens-before between the scheduler's release and each rank's first rad_issue, and
|
||||
* between the ranks' last issue and the scheduler's next batch build. A condvar round trip costs
|
||||
* ~1-2 us; an IPC broadcast of the batch costs tens of microseconds per step.
|
||||
*
|
||||
* A futex round trip through a condvar is ~1-2 us on this class of machine. The multiprocessing
|
||||
* equivalent -- serialise the batch, write it down a pipe, wake N processes, have each one
|
||||
* deserialise it -- is tens of microseconds per step before any work happens, and it is most of
|
||||
* what a Python engine's multiprocessing budget actually buys. That difference is the reason §1
|
||||
* is written the way it is, and this class is the whole of the cost on our side.
|
||||
*
|
||||
* Sense reversal, not a counter reset, so a fast rank that comes back round for the next step
|
||||
* cannot slip through the barrier its slower peers have not left yet.
|
||||
* Generation-based (sense reversal), so a fast rank re-entering for the next step cannot slip
|
||||
* through a barrier its slower peers have not left yet.
|
||||
*/
|
||||
#pragma once
|
||||
#include "../rad_core.h"
|
||||
@@ -34,11 +26,9 @@ public:
|
||||
|
||||
void arrive_and_wait();
|
||||
|
||||
/* Release everyone regardless of how many have arrived, and refuse every later arrival. The
|
||||
* engine calls this on shutdown and on a device fault: a rank that has already exited must not
|
||||
* leave its peers parked on a barrier that can no longer be completed (spec §17 -- a device
|
||||
* fault is not recoverable in-process, and the engine exits rather than serving from a wedged
|
||||
* queue, which it cannot do while a thread is blocked here). */
|
||||
/* Release everyone regardless of how many have arrived, and make every later arrival return
|
||||
* at once. Called on shutdown and on a device fault, so ranks are not left parked on a barrier
|
||||
* an exited rank can no longer complete; the engine must be able to exit (spec §17). */
|
||||
void abort();
|
||||
|
||||
|
||||
|
||||
+24
-40
@@ -1,16 +1,11 @@
|
||||
/* residency.h -- the seam the placement component plugs into.
|
||||
*
|
||||
* The run phase takes weight HANDLES, never pointers (spec §3.2). It resolves a handle to a
|
||||
* pointer at issue time, which is the only reason the mover is allowed to relocate a weight while
|
||||
* the model is serving. This header is the whole of the contract between the two: the run phase
|
||||
* asks a question that never blocks, and the placement component answers it out of a table it
|
||||
* owns.
|
||||
* The run phase takes weight handles, never pointers (spec §3.2), and resolves them at issue time,
|
||||
* which is what lets the mover relocate a weight while serving. The run phase asks a non-blocking
|
||||
* question; the placement component answers from a table it owns.
|
||||
*
|
||||
* The degenerate case matters as much as the interesting one. In the all-in-VRAM deployment the
|
||||
* planner assigned everything to tier 0 and the mover never runs, so no ResidencyTable is
|
||||
* installed at all and the lookup collapses to WeightInfo::ptr -- a pointer the run phase already
|
||||
* baked into its per-weight tensor template. There is no virtual call, no branch on a table entry,
|
||||
* and nothing to pay for a feature that deployment is not using.
|
||||
* In an all-in-VRAM deployment no ResidencyTable is installed and the lookup collapses to
|
||||
* WeightInfo::ptr, already baked into the per-weight tensor template: no virtual call, no cost.
|
||||
*/
|
||||
#pragma once
|
||||
#include "../rad_core.h"
|
||||
@@ -19,22 +14,16 @@
|
||||
|
||||
namespace rad {
|
||||
|
||||
/* Where a weight's bytes are RIGHT NOW, and whether they have arrived.
|
||||
/* Where a weight's bytes are now, and whether they have arrived.
|
||||
*
|
||||
* `ready` is the mover's event. Null means resident and settled: nothing to wait on, which is the
|
||||
* common case even under expert offload because a hot expert stays put for many steps. Non-null
|
||||
* means a transfer into `ptr` is in flight and the compute stream must be ordered behind it -- a
|
||||
* STREAM wait, never a host sync, which is what lets placement be dynamic without serialising the
|
||||
* step (spec §5.4).
|
||||
* `ready` is the mover's event. Null means resident and settled (the common case, even under
|
||||
* expert offload). Non-null means a transfer into `ptr` is in flight and the compute stream must
|
||||
* wait on it -- a stream wait, never a host sync (spec §5.4).
|
||||
*
|
||||
* `generation` is what makes that wait cheap, and it is a contract the mover has to keep: it MUST
|
||||
* be bumped whenever a new transfer into this slot begins. The run phase memoises "the compute
|
||||
* stream has already been made to wait on generation g of weight w" and skips the wait every time
|
||||
* afterwards. That is sound because a stream wait orders everything issued after it, so one wait
|
||||
* per generation is sufficient and per-issue waits are pure cost -- at 64 layers and eight experts
|
||||
* a step they would be thousands of runtime calls buying nothing. A mover that reuses an event
|
||||
* without bumping the generation silently loses the ordering, and the symptom is garbage output
|
||||
* three layers later with no way to bisect it.
|
||||
* Invariant: the mover bumps `generation` whenever a new transfer into the slot begins. The run
|
||||
* phase waits once per (weight, generation) and skips later waits, since a stream wait orders
|
||||
* everything issued after it. Reusing an event without bumping the generation silently loses the
|
||||
* ordering and corrupts output.
|
||||
*/
|
||||
struct WeightSlot {
|
||||
void* ptr;
|
||||
@@ -46,27 +35,22 @@ class ResidencyTable {
|
||||
public:
|
||||
virtual ~ResidencyTable() = default;
|
||||
|
||||
/* NEVER blocks. Not "usually does not block" -- this is called once per weight operand per
|
||||
* issue, inside the step, and a lock here would serialise the mover against compute, which is
|
||||
* the exact failure this design exists to avoid. Returning null means "I have nothing for this
|
||||
* handle" and the run phase falls back to WeightInfo::ptr. */
|
||||
/* Never blocks: called once per weight operand per issue, and a lock would serialise the
|
||||
* mover against compute. Null means no entry; the run phase falls back to WeightInfo::ptr. */
|
||||
virtual const WeightSlot* lookup(rad_weight) const = 0;
|
||||
|
||||
/* A count that changes whenever any slot's pointer, event or generation does. Everything
|
||||
* lookup() returns is a function of it, so a caller that resolved a run of weights at one
|
||||
* epoch may reuse that answer for as long as the epoch stands -- which is what keeps a routed
|
||||
* layer's expert table from being walked, entry by entry, at every issue. */
|
||||
/* Changes whenever any slot's pointer, event or generation does. Lookups resolved at one
|
||||
* epoch stay valid while it stands, so a routed layer's expert table is not re-walked at
|
||||
* every issue. */
|
||||
virtual uint64_t epoch() const = 0;
|
||||
|
||||
/* THE SLOTS WHOSE POINTER OR EVENT CHANGED since the run phase last cleared the list, each
|
||||
* named once. A routed layer's weight table holds its whole expert set and a step moves a
|
||||
* handful of experts, so the run phase updates the entries named here rather than resolving
|
||||
* every entry of every table whenever the epoch moves -- which, with experts moving on most
|
||||
* steps, would be every entry of every table on most steps.
|
||||
/* The slots whose pointer or event changed since the last clear_changes(), each named once.
|
||||
* A step moves a handful of experts, so the run phase updates only these entries instead of
|
||||
* re-resolving every table when the epoch moves. A slot that only settled (same pointer) is
|
||||
* not named.
|
||||
*
|
||||
* One reader: the run phase of the rank this table belongs to, on the thread that also drives
|
||||
* the writers, so neither call races the other. A slot that only SETTLED -- its transfer
|
||||
* landed, the pointer stayed -- is not named, because nothing a reader holds becomes wrong. */
|
||||
* One reader: this rank's run phase, on the thread that also drives the writers, so the two
|
||||
* calls do not race. */
|
||||
virtual const std::vector<rad_weight>& changes() const = 0;
|
||||
virtual void clear_changes() = 0;
|
||||
};
|
||||
|
||||
+11
-15
@@ -1,15 +1,13 @@
|
||||
/* stager.h -- the seam a step-time weight stager plugs into.
|
||||
*
|
||||
* The run phase resolves weights through the residency table (runtime/residency.h), and the mover
|
||||
* changes that table between steps. A stager changes it WITHIN a step: it copies a weight that
|
||||
* lives off the card into VRAM ahead of the op that reads it and publishes the copy for that op,
|
||||
* then publishes the host address again once the op is behind it. The run phase does not know what
|
||||
* is staged or why; it calls the stager around the ops of a pass it armed for and re-reads the
|
||||
* residency table when the stager says it changed it.
|
||||
* The mover changes the residency table (runtime/residency.h) between steps; a stager changes it
|
||||
* within a step. It copies an off-card weight into VRAM ahead of the op that reads it, publishes
|
||||
* the copy for that op, and republishes the host address once the op is behind it. The run phase
|
||||
* calls the stager around the ops of a pass it armed for and re-reads the residency table when
|
||||
* told it changed.
|
||||
*
|
||||
* A PASS THE STAGER ARMS FOR IS ISSUED LIVE, never recorded or played from a tape: a tape replays
|
||||
* the packets of the pass it recorded and not the host work between them, and the copies and
|
||||
* publishes here are exactly that host work.
|
||||
* A pass the stager arms for is issued live, never recorded or replayed from a tape: a tape
|
||||
* replays only packets, not the host work (copies, publishes) between them.
|
||||
*/
|
||||
#pragma once
|
||||
#include "../rad_core.h"
|
||||
@@ -31,7 +29,7 @@ public:
|
||||
virtual int before_op(rad_op h, RadStream s, bool* resync) = 0;
|
||||
|
||||
/* After op `h` was issued on stream `s`: the point a staged weight's last reader is behind. */
|
||||
virtual int after_op(rad_op h, RadStream s) = 0;
|
||||
virtual int after_op(rad_op, RadStream) { return RAD_OK; }
|
||||
|
||||
/* The pass has been issued, on `s`: nothing the stager published for it may outlive it. It
|
||||
* may publish weights for a later pass it expects to arm for, which that pass's begin_pass
|
||||
@@ -39,11 +37,9 @@ public:
|
||||
virtual int end_pass(RadStream s) = 0;
|
||||
};
|
||||
|
||||
/* TWO STAGERS ON ONE PASS, each called only on the passes it armed for. A stager that declined a
|
||||
* pass is not handed its ops: one that arms only for large passes -- because its buffers are lent
|
||||
* out the rest of the time -- must not stage into memory it does not own because another stager
|
||||
* armed. The order is fixed, so the copies and stream waits each issues land in the same order on
|
||||
* every pass. */
|
||||
/* Two stagers on one pass, each called only on the passes it armed for, so a stager whose
|
||||
* buffers are lent out on small passes never stages because the other one armed. The call order
|
||||
* is fixed, so copies and stream waits land in the same order on every pass. */
|
||||
class StagerChain final : public OpStager {
|
||||
public:
|
||||
void set(OpStager* a, OpStager* b) { s_[0] = a; s_[1] = b; }
|
||||
|
||||
+68
-122
@@ -10,11 +10,9 @@ namespace rad {
|
||||
|
||||
TierExec::~TierExec() { close(); }
|
||||
|
||||
/* The two ops are resolved ONCE, at configure, and at the width they will actually be called at.
|
||||
* `n` is the fragment in bytes and it is a per-group constant, so nothing here re-resolves on the
|
||||
* maintenance path -- a selector call between steps would be affordable and is still the wrong
|
||||
* shape: the kernel that serves a transfer must not be able to change underneath a half-finished
|
||||
* batch. */
|
||||
/* gather_rows and scatter_rows are resolved once here, at the width they are called at (`n` is the
|
||||
* per-group fragment in bytes). Nothing re-resolves on the maintenance path, so the kernel serving
|
||||
* a transfer cannot change in the middle of a batch. */
|
||||
int TierExec::configure(Registry* reg, KVManager* kv, IdleTiers* tiers,
|
||||
const std::vector<int32_t>& groups, int max_batch, int64_t max_copy,
|
||||
int64_t max_chain, bool leader, int device, int64_t slot_off,
|
||||
@@ -47,9 +45,8 @@ int TierExec::configure(Registry* reg, KVManager* kv, IdleTiers* tiers,
|
||||
gi_.push_back(gi);
|
||||
continue;
|
||||
}
|
||||
/* THE FRAGMENT WIDTH IS THE CONSTRAINT THE KERNEL IS PICKED ON. libr4d's byte-row pair
|
||||
* takes n as a multiple of 4; a geometry that does not satisfy it resolves to nothing
|
||||
* here rather than failing at launch inside a batch. */
|
||||
/* The kernel is picked on the fragment width (libr4d's byte-row pair needs n % 4 == 0).
|
||||
* An unsupported width fails here rather than at launch inside a batch. */
|
||||
Geometry q;
|
||||
q.set_s("dtype", "u8");
|
||||
q.set_i("n", gi.frag);
|
||||
@@ -67,9 +64,8 @@ int TierExec::configure(Registry* reg, KVManager* kv, IdleTiers* tiers,
|
||||
gi_.push_back(gi);
|
||||
}
|
||||
if (gi_.empty()) return RAD_E_UNSUPPORTED;
|
||||
/* EVERY CACHED GROUP ZERO ON THIS RANK: it would hold nothing of any entry, and an empty
|
||||
* entry is a zero-width copy on every path below. Said, and the tiers are off -- one rank
|
||||
* that cannot take part takes them off for all. */
|
||||
/* Every cached group is zero on this rank, so its entry would be empty. One rank that cannot
|
||||
* take part turns the tiers off for all. */
|
||||
if (off == 0) {
|
||||
RAD_WARN("kv tiers: this rank keeps no cache for any group the prefix cache holds "
|
||||
"(rad_kv_group_zero), so it has no part of an entry to move. The tiers are off.");
|
||||
@@ -78,10 +74,7 @@ int TierExec::configure(Registry* reg, KVManager* kv, IdleTiers* tiers,
|
||||
}
|
||||
entry_bytes_ = off;
|
||||
|
||||
/* NOTHING IS BUILT ON THE DEVICE HERE -- see device_init(). A tier that is configured but has
|
||||
* no job to run must cost the step nothing, and on this engine that is not a figure of speech:
|
||||
* building the staging buffer and the stream at bringup costs 13.3 ms of a 20.5 ms decode step
|
||||
* on a two-card R9700 Flash-Next server, whether or not a single byte ever moves. */
|
||||
/* Nothing is built on the device here; see device_init(). */
|
||||
verify_ = leader && std::getenv("RADIANCE_DEBUG_TIER_VERIFY") != nullptr;
|
||||
|
||||
char buf[320];
|
||||
@@ -97,9 +90,8 @@ int TierExec::configure(Registry* reg, KVManager* kv, IdleTiers* tiers,
|
||||
TierExec::Sizes TierExec::sizes(int64_t entry_bytes, int64_t max_ctx, int64_t block_size) {
|
||||
Sizes s;
|
||||
if (entry_bytes <= 0) return s;
|
||||
/* 16 MiB of staging a rank, as entries, between 64 and 4096 of them: the reasons are at the
|
||||
* call in bringup. A copy out is four batches, and a restore is a whole chain, as long as the
|
||||
* longest context the server takes. */
|
||||
/* 16 MiB of staging per rank, clamped to 64..4096 entries (rationale at the bringup call site).
|
||||
* A copy out is four batches; a restore is a whole chain as long as the longest context. */
|
||||
s.max_batch = (int)std::min<int64_t>(4096, std::max<int64_t>(64, (16ll << 20) / entry_bytes));
|
||||
s.max_copy = 4ll * s.max_batch;
|
||||
const int64_t bs = std::max<int64_t>(1, block_size);
|
||||
@@ -107,8 +99,7 @@ TierExec::Sizes TierExec::sizes(int64_t entry_bytes, int64_t max_ctx, int64_t bl
|
||||
return s;
|
||||
}
|
||||
|
||||
/* What device_init() allocates, each allocation rounded to the pool granule the card hands VRAM
|
||||
* out in. */
|
||||
/* What device_init() allocates, each allocation rounded to the VRAM pool granule. */
|
||||
int64_t TierExec::device_bytes(int64_t entry_bytes, int n_groups, const Sizes& s) {
|
||||
if (entry_bytes <= 0 || n_groups <= 0 || s.max_batch <= 0) return 0;
|
||||
const int64_t idx_n = (int64_t)n_groups * (s.max_copy + (int64_t)kRing * s.max_chain);
|
||||
@@ -117,21 +108,11 @@ int64_t TierExec::device_bytes(int64_t entry_bytes, int n_groups, const Sizes& s
|
||||
}
|
||||
|
||||
void TierExec::close() {
|
||||
/* Nothing may still be reading the buffers about to be freed. */
|
||||
/* Drain before freeing buffers the stream may still read. */
|
||||
if (stream_) (void)rad_stream_sync(stream_);
|
||||
if (stream_ && own_stream_) rad_stream_destroy(stream_);
|
||||
stream_ = nullptr; shared_ = nullptr; own_stream_ = false;
|
||||
if (stage_) { rad_dev_free(stage_, RAD_MEM_DEVICE); stage_ = nullptr; }
|
||||
if (idx_dev_) { rad_dev_free(idx_dev_, RAD_MEM_DEVICE); idx_dev_ = nullptr; }
|
||||
if (idx_host_) { rad_dev_free(idx_host_, RAD_MEM_HOST_PINNED); idx_host_ = nullptr; }
|
||||
for (int i = 0; i < kRing; ++i) {
|
||||
if (ring_ev_[i]) rad_event_destroy(ring_ev_[i]);
|
||||
ring_ev_[i] = nullptr;
|
||||
ring_used_[i] = false;
|
||||
}
|
||||
if (ev_compute_) { rad_event_destroy(ev_compute_); ev_compute_ = nullptr; }
|
||||
if (ev_copy_) { rad_event_destroy(ev_copy_); ev_copy_ = nullptr; }
|
||||
if (ev_restore_) { rad_event_destroy(ev_restore_); ev_restore_ = nullptr; }
|
||||
release_device();
|
||||
copy_out_ = false;
|
||||
gi_.clear();
|
||||
order_.clear();
|
||||
@@ -143,26 +124,25 @@ void TierExec::close() {
|
||||
report_.clear();
|
||||
}
|
||||
|
||||
/* THE DEVICE SIDE, BUILT ON FIRST USE AND NOT BEFORE.
|
||||
*
|
||||
* Ctx::lane_init() makes the same argument for the second compute lane: a stream is cheap
|
||||
* enough that its cost hides inside the run-to-run spread of a warming part, so the only honest
|
||||
* way to claim the lane costs nothing when unused is to not build it. The tiers follow the same
|
||||
* rule, and here the cost is not small enough to hide in anything. Decode step time with the
|
||||
* device side built at bringup, on a two-card R9700 Flash-Next server at 200K context:
|
||||
*
|
||||
* no tiers 20.54 ms/step collect 14.66
|
||||
* tiers on, 512 MiB host arena 33.94 ms/step collect 26.78
|
||||
* tiers on, idle threshold a day -- NOTHING EVER MOVED 33.88 ms/step collect 26.66
|
||||
*
|
||||
* In the third line not one byte crosses the link, and the step is still 65% longer. The cost is
|
||||
* in `collect` -- device time -- and a configured tier that has nothing to do pays it on every
|
||||
* step. It is not the transfers, not the pinned host arena (512 MiB costs exactly what 12 GiB
|
||||
* does) and not the VRAM the staging takes (with no tiers and --gpu-headroom-mib lowered to leave
|
||||
* the same 17 MiB free, the step runs at full speed).
|
||||
*
|
||||
* So the device side is built when the first job needs it, and a server whose conversations never
|
||||
* finish pays nothing for the tiers. */
|
||||
void TierExec::release_device() {
|
||||
if (stage_) { rad_dev_free(stage_, RAD_MEM_DEVICE); stage_ = nullptr; }
|
||||
if (idx_dev_) { rad_dev_free(idx_dev_, RAD_MEM_DEVICE); idx_dev_ = nullptr; }
|
||||
if (idx_host_) { rad_dev_free(idx_host_, RAD_MEM_HOST_PINNED); idx_host_ = nullptr; }
|
||||
for (int i = 0; i < kRing; ++i) {
|
||||
if (ring_ev_[i]) rad_event_destroy(ring_ev_[i]);
|
||||
ring_ev_[i] = nullptr;
|
||||
ring_used_[i] = false;
|
||||
}
|
||||
if (ev_compute_) { rad_event_destroy(ev_compute_); ev_compute_ = nullptr; }
|
||||
if (ev_copy_) { rad_event_destroy(ev_copy_); ev_copy_ = nullptr; }
|
||||
if (ev_restore_) { rad_event_destroy(ev_restore_); ev_restore_ = nullptr; }
|
||||
}
|
||||
|
||||
/* Builds the device side on first use, never at bringup (same rule as Ctx::lane_init()). Built
|
||||
* eagerly, it makes every decode step 65% longer even when nothing ever moves: on two R9700s with
|
||||
* Flash-Next at 200K context, 20.5 -> 33.9 ms/step, all of it device time. The cost is not the
|
||||
* transfers, the pinned arena size or the staging VRAM; it is the extra hardware queue (see
|
||||
* stream_ in tierexec.h). */
|
||||
int TierExec::device_init() {
|
||||
if (stream_) return RAD_OK;
|
||||
RAD_TRY(rad_dev_set(device_));
|
||||
@@ -176,21 +156,10 @@ int TierExec::device_init() {
|
||||
bool ev = rad_event_create(&ev_compute_) == RAD_OK && rad_event_create(&ev_copy_) == RAD_OK &&
|
||||
rad_event_create(&ev_restore_) == RAD_OK;
|
||||
for (int i = 0; i < kRing && ev; ++i) ev = rad_event_create(&ring_ev_[i]) == RAD_OK;
|
||||
auto undo = [&] {
|
||||
if (stage_) { rad_dev_free(stage_, RAD_MEM_DEVICE); stage_ = nullptr; }
|
||||
if (idx_dev_) { rad_dev_free(idx_dev_, RAD_MEM_DEVICE); idx_dev_ = nullptr; }
|
||||
if (idx_host_) { rad_dev_free(idx_host_, RAD_MEM_HOST_PINNED); idx_host_ = nullptr; }
|
||||
for (int i = 0; i < kRing; ++i) { if (ring_ev_[i]) rad_event_destroy(ring_ev_[i]); ring_ev_[i] = nullptr; }
|
||||
if (ev_compute_) { rad_event_destroy(ev_compute_); ev_compute_ = nullptr; }
|
||||
if (ev_copy_) { rad_event_destroy(ev_copy_); ev_copy_ = nullptr; }
|
||||
if (ev_restore_) { rad_event_destroy(ev_restore_); ev_restore_ = nullptr; }
|
||||
};
|
||||
if (!stage_ || !idx_dev_ || !idx_host_ || !ev) { undo(); return RAD_E_NOMEM; }
|
||||
/* THE MOVER'S STREAM IF THERE IS ONE, AND A NEW ONE ONLY IF THERE IS NOT. Both move bytes
|
||||
* nobody is waiting for, so one maintenance stream a rank serves both -- and the fourth
|
||||
* hardware queue a second one would claim costs about 13 ms a decode step (see
|
||||
* device_init). Never the step's own stream: a copy out would then be a dependency of the
|
||||
* next token. */
|
||||
if (!stage_ || !idx_dev_ || !idx_host_ || !ev) { release_device(); return RAD_E_NOMEM; }
|
||||
/* Borrow the mover's maintenance stream if there is one; both move bytes nobody waits for,
|
||||
* and a fourth hardware queue costs about 13 ms per decode step. Never the step's own
|
||||
* stream, or a copy out would become a dependency of the next token. */
|
||||
if (shared_) {
|
||||
stream_ = shared_;
|
||||
own_stream_ = false;
|
||||
@@ -198,24 +167,14 @@ int TierExec::device_init() {
|
||||
own_stream_ = true;
|
||||
} else {
|
||||
stream_ = nullptr;
|
||||
undo();
|
||||
release_device();
|
||||
return RAD_E_DEVICE;
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int64_t tier_entry_bytes(const KVManager& kv, const std::vector<int32_t>& groups) {
|
||||
int64_t n = 0;
|
||||
for (int32_t g : groups) {
|
||||
const KVGroupPlan* p = kv.plan(g);
|
||||
if (p && p->paged()) n += p->bytes_per_block;
|
||||
}
|
||||
return n;
|
||||
}
|
||||
|
||||
/* One (group, layer) launch. `stage_base` is the first entry's staging slot; the rows this call
|
||||
* writes (or reads) are at a stride of entry_bytes_ from it, which is what puts each entry's
|
||||
* fragment inside its own contiguous staging entry. */
|
||||
/* One (group, layer) launch. Staging rows are at stride entry_bytes_ from `stage_base` (the first
|
||||
* entry's slot), so each fragment lands inside its own contiguous staging entry. */
|
||||
int TierExec::run_rows(const Resolved& r, bool scatter, const GroupInfo& gi, int64_t layer,
|
||||
void* stage_base, const int32_t* d_idx, int64_t n_jobs) {
|
||||
RadTensor pool{};
|
||||
@@ -234,7 +193,7 @@ int TierExec::run_rows(const Resolved& r, bool scatter, const GroupInfo& gi, int
|
||||
pack.dtype = RAD_U8;
|
||||
pack.rank = 2;
|
||||
pack.shape[0] = n_jobs; pack.shape[1] = gi.frag;
|
||||
pack.stride[0] = entry_bytes_; /* <-- the whole trick: one entry's stride, not one row's */
|
||||
pack.stride[0] = entry_bytes_; /* one entry's stride, not one row's */
|
||||
pack.stride[1] = 1;
|
||||
pack.data = (char*)stage_base + gi.off + layer * gi.frag;
|
||||
|
||||
@@ -242,10 +201,8 @@ int TierExec::run_rows(const Resolved& r, bool scatter, const GroupInfo& gi, int
|
||||
if (scatter) { t3[0] = pack; t3[1] = idx; t3[2] = pool; }
|
||||
else { t3[0] = pool; t3[1] = idx; t3[2] = pack; }
|
||||
|
||||
/* THE RESOLVED GEOMETRY, not a hand-built one. It carries whatever the winning kernel
|
||||
* supplied for a derived key as well as the query, and M in it is the band's upper bound --
|
||||
* which is correct and is the convention: both implementations take the row count from the
|
||||
* OPERAND extent, because M is ranged and the value in the args is the worst case. */
|
||||
/* Pass the resolved geometry, which carries the winning kernel's derived keys. Its M is the
|
||||
* band's upper bound; kernels take the row count from the operand extent. */
|
||||
RadArgs a{};
|
||||
a.t = t3; a.n_t = 3;
|
||||
a.p = r.geom.params(); a.n_p = r.geom.n_params();
|
||||
@@ -273,17 +230,15 @@ void TierExec::verify_check(const BlockHash& key, const void* p, int64_t n) {
|
||||
if (it == out_sum_.end()) return; /* never went out through this process */
|
||||
const uint64_t back = tier_fnv(p, n);
|
||||
if (back == it->second) return;
|
||||
RAD_ERR("kv tiers: the attention blocks for %s came back DIFFERENT (%016llx out, %016llx in). "
|
||||
"The tier is moving the wrong bytes, not the engine choosing differently downstream.",
|
||||
RAD_ERR("kv tiers: the attention blocks for %s came back different (%016llx out, %016llx in); "
|
||||
"the tier moved the wrong bytes",
|
||||
key.str().c_str(), (unsigned long long)it->second, (unsigned long long)back);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ helpers */
|
||||
|
||||
/* WHY THIS IS NOT RAD_TRY. A tier that fails is invisible: the entry stays where it was, the pool
|
||||
* keeps its blocks, and everything still works -- just slower, forever, with a counter nobody is
|
||||
* looking at. The first failure names the call it came from, because "5824 failures" and nothing
|
||||
* else is a day of bisecting. */
|
||||
/* Like RAD_TRY, but the first failure is logged with the call it came from. A failing tier is
|
||||
* otherwise invisible: entries stay put and the server only gets slower. */
|
||||
#define TIER_TRY(call, what) \
|
||||
do { const int _s = (call); \
|
||||
if (_s != RAD_OK) { warn_once(what, _s); return _s; } } while (0)
|
||||
@@ -339,9 +294,8 @@ int TierExec::issue_copy(std::vector<TierJob>& jobs, RadStream compute) {
|
||||
TIER_TRY(rad_dev_set(device_), "selecting the rank device");
|
||||
TIER_TRY(device_init(), "building the transfer staging");
|
||||
const int st = enqueue_copy(jobs, compute);
|
||||
/* A COPY THAT FAILED PART OF THE WAY IN IS DRAINED BEFORE ITS SLOTS GO BACK. The report frees
|
||||
* every host slot the batch was handed, and a transfer already queued into one would land on
|
||||
* whatever the arena gives that slot to next. */
|
||||
/* Drain a partly enqueued copy before its host slots are freed by the report, or a queued
|
||||
* transfer would land on the slot's next owner. */
|
||||
if (st != RAD_OK) (void)rad_stream_sync(stream_);
|
||||
return st;
|
||||
}
|
||||
@@ -351,13 +305,11 @@ int TierExec::enqueue_copy(std::vector<TierJob>& jobs, RadStream compute) {
|
||||
for (TierJob& j : jobs) if (!j.blocks.empty()) order_.push_back(&j);
|
||||
const int64_t n = (int64_t)order_.size();
|
||||
if (n > copy_idx_) return RAD_E_INVAL;
|
||||
/* EVERY ID FIRST, BEFORE ANY OF THEM IS LAUNCHED AGAINST. A gather over an unbacked id faults
|
||||
* the whole card rather than failing the transfer. */
|
||||
/* Check every id before any launch: a gather over an unbacked id faults the whole card. */
|
||||
for (TierJob* j : order_)
|
||||
if (!blocks_backed(j->blocks, "copy to host")) return RAD_E_STATE;
|
||||
|
||||
/* AFTER EVERYTHING THE COMPUTE STREAM HAS BEEN GIVEN, which includes the step that wrote these
|
||||
* blocks. A stream wait, not a host wait. */
|
||||
/* Stream-ordered after everything given to compute, including the step that wrote these. */
|
||||
TIER_TRY(rad_event_record(ev_compute_, compute), "ordering the copy after the step");
|
||||
TIER_TRY(rad_event_wait(stream_, ev_compute_), "ordering the copy after the step");
|
||||
|
||||
@@ -435,15 +387,13 @@ int TierExec::issue_restore(std::vector<TierJob>& jobs, RadStream compute,
|
||||
TIER_TRY(device_init(), "building the transfer staging");
|
||||
const size_t ng = gi_.size();
|
||||
|
||||
/* WHO CHOOSES THE BLOCKS, AND WHO KEEPS THE BOOKS. Ids are shared across ranks -- one block
|
||||
* table indexes every rank's shard -- so exactly one rank may choose, and that same rank is
|
||||
* the only one whose allocator means anything: the prefix cache holds the KV references and
|
||||
* the prefix cache is rank 0's. A follower writes into the ids it is handed and reserves
|
||||
* nothing.
|
||||
/* Block ids are shared across ranks (one block table indexes every shard), so only the leader
|
||||
* chooses and reserves them; its allocator is the one the prefix cache (rank 0's) references.
|
||||
* Followers write into the ids they are handed.
|
||||
*
|
||||
* THE WHOLE CHAIN IS RESERVED BEFORE ANY OF IT MOVES, one recall of the loan for all of it.
|
||||
* Where the pool runs short the chain is cut at that point and the rest stay unstarted: a hit
|
||||
* needs a contiguous prefix, so an entry past a gap would be restored for nothing. */
|
||||
* The whole chain is reserved before anything moves, with one loan recall. If the pool runs
|
||||
* short the chain is cut there: a hit needs a contiguous prefix, so entries past a gap are
|
||||
* useless. */
|
||||
if (leader_) {
|
||||
const int64_t n = (int64_t)jobs.size();
|
||||
std::vector<std::vector<int32_t>> ids(ng);
|
||||
@@ -463,15 +413,13 @@ int TierExec::issue_restore(std::vector<TierJob>& jobs, RadStream compute,
|
||||
}
|
||||
size_t m = 0;
|
||||
while (m < jobs.size() && jobs[m].blocks.size() == ng) ++m;
|
||||
/* AND WHETHER THIS RANK CAN ADDRESS WHAT IT WAS HANDED. The leader chose these ids against its
|
||||
* own live mark and the recall moved every follower's with it; this is the check that it did. */
|
||||
/* The leader chose ids against its own live mark and the recall should have moved every
|
||||
* follower's with it; verify that here. */
|
||||
for (size_t i = 0; i < m; ++i)
|
||||
if (!blocks_backed(jobs[i].blocks, "restore")) { m = i; break; }
|
||||
|
||||
/* THE CUT IS WHAT THE FOLLOWERS READ. They find their chain by which jobs carry block ids,
|
||||
* so every job past the point the leader stopped gives its ids back and carries none. A
|
||||
* follower handed ids for an entry the leader could not address would copy into blocks that
|
||||
* are not the cache's. */
|
||||
/* Followers find the chain by which jobs carry block ids, so every job past the cut releases
|
||||
* its ids and carries none; otherwise a follower would copy into blocks the cache does not own. */
|
||||
if (leader_) {
|
||||
for (size_t i = m; i < jobs.size(); ++i) {
|
||||
for (size_t k = 0; k < ng && k < jobs[i].blocks.size(); ++k)
|
||||
@@ -487,11 +435,10 @@ int TierExec::issue_restore(std::vector<TierJob>& jobs, RadStream compute,
|
||||
verify_check(jobs[i].key, (char*)tiers_->arena().at(jobs[i].host_slot) + slot_off_,
|
||||
entry_bytes_);
|
||||
|
||||
/* FROM HERE ON A FAILURE LEAVES A MIXTURE, so every job about to be written is marked started
|
||||
* first -- report() drops a started job that failed rather than trusting its host copy to
|
||||
* describe blocks some layers of which were overwritten. And the compute stream is made to
|
||||
* wait on whatever was enqueued, success or not: a failed job's blocks go back to the pool,
|
||||
* and nothing may be written into them before the transfers already queued against them. */
|
||||
/* From here a failure leaves blocks partly overwritten. Mark jobs started first, so report()
|
||||
* drops a failed started job instead of trusting its host copy. The compute stream waits on
|
||||
* whatever was enqueued, success or not, because a failed job's blocks return to the pool and
|
||||
* must not be reused before the queued transfers into them. */
|
||||
for (size_t i = 0; i < m; ++i) jobs[i].started = true;
|
||||
const int ri = ring_next_;
|
||||
ring_next_ = (ring_next_ + 1) % kRing;
|
||||
@@ -522,8 +469,8 @@ int TierExec::issue_restore(std::vector<TierJob>& jobs, RadStream compute,
|
||||
for (size_t i = 0; i < done; ++i) (*ok)[i] = 1;
|
||||
st_.bytes_in += (int64_t)done * entry_bytes_;
|
||||
|
||||
/* THE STEP THAT READS THESE WAITS FOR THEM, on the device. If even the marker cannot be
|
||||
* enqueued the only ordering left is the host's. */
|
||||
/* The reading step waits on the device; if the event cannot be enqueued, fall back to a host
|
||||
* wait. */
|
||||
if (rad_event_record(ev_restore_, stream_) != RAD_OK ||
|
||||
rad_event_wait(compute, ev_restore_) != RAD_OK) {
|
||||
(void)rad_stream_sync(stream_);
|
||||
@@ -542,9 +489,8 @@ void TierExec::report_pass(std::vector<TierJob>& jobs, const std::vector<char>&
|
||||
for (size_t i = 0; i < jobs.size(); ++i) {
|
||||
TierJob& j = jobs[i];
|
||||
const bool good = i < ok.size() && ok[i];
|
||||
/* A PROMOTION THAT FAILED AS A WHOLE gives back the blocks the leader took for it, once
|
||||
* nothing queued against them can still land: report() drops or keeps the record, and
|
||||
* nothing will ever name these blocks again. */
|
||||
/* A failed promotion releases the leader's blocks once nothing queued against them can
|
||||
* still land; after report() nothing names them again. */
|
||||
if (j.kind == TierJob::Kind::ToDevice && !good) {
|
||||
if (!quiet) { quiesce(); quiet = true; }
|
||||
for (size_t k = 0; k < gi_.size() && k < j.blocks.size(); ++k)
|
||||
|
||||
+73
-115
@@ -1,39 +1,28 @@
|
||||
/* tierexec.h -- the side of the KV tiers that actually moves bytes.
|
||||
/* tierexec.h -- executes KV tier transfers.
|
||||
*
|
||||
* core/mem/kvtier.h decides WHAT should move and hands out TierJobs; this executes them. The split
|
||||
* is the one KVManager already uses for BlockCopy and it is not decoration: core/mem has no stream
|
||||
* and must not acquire one, because a synchronisation on the step path is what this design spends
|
||||
* itself avoiding (spec §5.4).
|
||||
* core/mem/kvtier.h decides what moves and hands out TierJobs; this runs them. core/mem has no
|
||||
* stream and must not get one, because the design avoids host synchronisation on the step path
|
||||
* (spec §5.4). Same split as KVManager and BlockCopy.
|
||||
*
|
||||
* ============================== NOTHING HERE WAITS ON THE HOST ================================
|
||||
* Nothing here waits on the host. Copies are enqueued and ordered by events:
|
||||
* - a copy out waits on the transfer stream for everything the compute stream had been given
|
||||
* when it was issued (including the step that wrote the blocks) and signals an event the
|
||||
* engine polls between steps. The engine keeps building steps meanwhile and the scheduler
|
||||
* lock is not held;
|
||||
* - a restore in makes the compute stream wait for it, so the step reading the restored blocks
|
||||
* runs after they land.
|
||||
*
|
||||
* A copy out and a restore in are both ENQUEUED and ordered by events, never by a host wait:
|
||||
* Transfer shape. A paged pool is layer-major: layer l of group g owns
|
||||
* `[base + l*layer_stride, + layer_stride)` and a block in it is at
|
||||
* `block * layer_bytes_per_block()`. A logical block is thus `n_layers` fragments of a few hundred
|
||||
* bytes, too small to move one at a time. Within a layer, blocks are dense rows of a matrix, so
|
||||
* packing a set is `gather_rows` and restoring it is `scatter_rows`: one launch per (group, layer)
|
||||
* per staging batch.
|
||||
*
|
||||
* - a copy out waits, on the transfer stream, for everything the compute stream had been given
|
||||
* when it was issued -- the step that wrote the blocks is in there -- and signals an event the
|
||||
* engine polls between steps. The engine thread goes on building steps the whole time, and the
|
||||
* scheduler's lock is not held while it runs;
|
||||
* - a restore in makes the COMPUTE stream wait for it, so the step that reads the restored
|
||||
* blocks runs after they land without the host having waited for anything.
|
||||
*
|
||||
* ============================== THE TRANSFER, AND WHY IT IS SHAPED THIS WAY ====================
|
||||
*
|
||||
* A paged pool is LAYER-MAJOR: layer l of group g owns `[base + l*layer_stride, + layer_stride)`
|
||||
* and a block inside it is `block * layer_bytes_per_block()`. So a logical block is `n_layers`
|
||||
* fragments of a few hundred bytes, and moving one block at a time means a few hundred bytes a
|
||||
* transfer -- dispatch cost with the data as a rounding error.
|
||||
*
|
||||
* Turned around, WITHIN a layer the blocks are dense rows of a matrix. That makes packing an
|
||||
* arbitrary set of them exactly `gather_rows` and restoring them exactly `scatter_rows`, and the
|
||||
* transfer count becomes ONE LAUNCH PER (GROUP, LAYER) for a whole staging batch rather than per
|
||||
* block.
|
||||
*
|
||||
* THE STAGING BUFFER'S LAYOUT IS WHAT MAKES THE HOST COPY CONTIGUOUS. Device staging is
|
||||
* `max_batch * entry_bytes`, and one entry's bytes are [group][layer][fragment] laid end to end.
|
||||
* For a given (group, layer) the destination rows are then at a stride of `entry_bytes` from a
|
||||
* base inside the first entry -- which is exactly `gather_rows`'s `y` pitch, so one launch writes
|
||||
* every entry's fragment for that layer directly into the place it will be copied from. The host
|
||||
* side is then one strided copy per run of consecutive arena slots.
|
||||
* Staging layout. Device staging is `max_batch * entry_bytes`; one entry is [group][layer][fragment]
|
||||
* end to end. For a given (group, layer) the destination rows sit at stride `entry_bytes` from a
|
||||
* base in the first entry, which is `gather_rows`'s `y` pitch, so one launch writes every entry's
|
||||
* fragment in place and the host side is one strided copy per run of consecutive arena slots.
|
||||
*/
|
||||
#pragma once
|
||||
#include "mem/kv.h"
|
||||
@@ -52,12 +41,9 @@ class TierExec {
|
||||
public:
|
||||
~TierExec();
|
||||
/* `groups` is PrefixCache::cached_groups(): the paged groups an entry holds a block in, in the
|
||||
* order the entry's `blocks` vector uses. The staging layout is derived from them once here,
|
||||
* because a second derivation of the same offsets is a second place to get them wrong.
|
||||
*
|
||||
* `max_batch` is the staging buffer in entries, `max_copy` the most entries one copy out may
|
||||
* carry, and `max_chain` the longest chain one restore brings back -- the index buffers are
|
||||
* sized from the last two. */
|
||||
* order of the entry's `blocks` vector. The staging layout is derived from them here only.
|
||||
* `max_batch` is the staging buffer in entries, `max_copy` the most entries per copy out and
|
||||
* `max_chain` the longest restore chain; the index buffers are sized from the last two. */
|
||||
int configure(Registry* reg, KVManager* kv, IdleTiers* tiers,
|
||||
const std::vector<int32_t>& groups, int max_batch, int64_t max_copy,
|
||||
int64_t max_chain, bool leader, int device, int64_t slot_off,
|
||||
@@ -66,53 +52,44 @@ public:
|
||||
bool enabled() const { return enabled_; }
|
||||
std::string report() const { return report_; }
|
||||
|
||||
/* THE SIZES A CONFIGURE IS GIVEN, from one entry's bytes on this rank, the longest context and
|
||||
* the block size, and the VRAM device_init() then takes for them. The VRAM budget reserves
|
||||
* device_bytes() before any of this exists and bringup configures with sizes(), so the two
|
||||
* cannot drift apart. */
|
||||
/* configure()'s sizes from one entry's bytes on this rank, the longest context and the block
|
||||
* size, and the VRAM device_init() takes for them. The VRAM budget reserves device_bytes() and
|
||||
* bringup configures with sizes(), so the two cannot drift apart. */
|
||||
struct Sizes { int max_batch = 0; int64_t max_copy = 0, max_chain = 0; };
|
||||
static Sizes sizes(int64_t entry_bytes, int64_t max_ctx, int64_t block_size);
|
||||
static int64_t device_bytes(int64_t entry_bytes, int n_groups, const Sizes& s);
|
||||
|
||||
/* DECIDING AND DOING ARE SEPARATE, and under tensor parallelism that is the point. The policy
|
||||
* is one object describing CONVERSATIONS, which are not sharded; the transfer is per rank,
|
||||
* because each rank holds its own shard of every block. So the leader plans, every rank runs
|
||||
* the same job list, and the leader reports the outcome once.
|
||||
*
|
||||
* A follower that consulted the policy itself would find each record already pending -- or
|
||||
* already reported -- and would move nothing, silently, leaving its shard of the pool holding
|
||||
* whatever was there before. That is corrupt KV on one card and not the other, which is the
|
||||
* worst shape this failure can take. */
|
||||
/* Planning and transfer are separate for tensor parallelism. The policy describes conversations,
|
||||
* which are not sharded; the transfer is per rank, since each rank holds its own shard of every
|
||||
* block. The leader plans, every rank runs the same job list, and the leader reports once. A
|
||||
* follower consulting the policy itself would find records already pending and silently move
|
||||
* nothing, corrupting KV on one card only. */
|
||||
|
||||
/* ---------------- copy on idle ----------------
|
||||
*
|
||||
* Enqueue a batch of WriteBack jobs on this rank and return. The copy is ordered after
|
||||
* everything `compute` had been given, and `copy_state` says when it has landed. One batch
|
||||
* at a time: the engine does not issue the next until this one has reported, which is what
|
||||
* lets the staging and index buffers be reused without a wait. */
|
||||
* Enqueues a batch of WriteBack jobs on this rank, ordered after everything `compute` had been
|
||||
* given; `copy_state` says when it has landed. One batch at a time: the engine issues the next
|
||||
* only after this one reports, so the staging and index buffers are reused without a wait. */
|
||||
int issue_copy(std::vector<TierJob>& jobs, RadStream compute);
|
||||
/* 1 when nothing is out or the last batch has landed, 0 while it is in flight, negative when
|
||||
* the transfer stream reported an error. Taking the answer clears it. */
|
||||
int copy_state();
|
||||
bool copy_out() const { return copy_out_; }
|
||||
/* copy_state, after waiting for the batch to land. For a caller that cannot go on until the
|
||||
* copy has a host slot to show for it -- an eviction that would otherwise lose the entry. */
|
||||
/* copy_state after waiting for the batch to land, for a caller that needs the host copy
|
||||
* first (an eviction that would otherwise lose the entry). */
|
||||
int wait_copy();
|
||||
/* EVERYTHING THIS RANK ENQUEUED HAS LANDED. For a block given back on a failure path while a
|
||||
* copy into it may still be in flight: the pool would hand it to a sequence whose writes the
|
||||
* late copy then overwrites. */
|
||||
/* Waits until everything this rank enqueued has landed. Used before a block is given back on a
|
||||
* failure path, where a late in-flight copy would overwrite its next owner's writes. */
|
||||
void quiesce();
|
||||
|
||||
/* ---------------- restore ----------------
|
||||
*
|
||||
* Enqueue a chain of ToDevice jobs, in chain order, and make `compute` wait for them. The
|
||||
* leader chooses every block first, recalling the loan for the
|
||||
* whole chain at once; a chain the pool cannot hold is cut where the reservation ran out, and
|
||||
* the jobs past the cut are left unstarted. `ok[i]` is whether job i was fully enqueued on
|
||||
* this rank. */
|
||||
* Enqueues a chain of ToDevice jobs in chain order and makes `compute` wait for them. The
|
||||
* leader chooses every block first, recalling the loan for the whole chain at once; a chain
|
||||
* the pool cannot hold is cut where the reservation ran out and the rest left unstarted.
|
||||
* `ok[i]` is whether job i was fully enqueued on this rank. */
|
||||
int issue_restore(std::vector<TierJob>& jobs, RadStream compute, std::vector<char>* ok);
|
||||
/* Leader only. Gives back what a failed job held -- a restore's blocks -- and reports every
|
||||
* job to the policy. `now_ns` is when the pass ran: a promotion is a use. */
|
||||
/* Leader only. Gives back a failed restore's blocks and reports every job to the policy.
|
||||
* `now_ns` is the pass time; a promotion counts as a use. */
|
||||
void report_pass(std::vector<TierJob>& jobs, const std::vector<char>& ok, uint64_t now_ns);
|
||||
|
||||
/* A lookup hit off-device: the job that would bring it back, or false when the entry is not
|
||||
@@ -131,24 +108,21 @@ private:
|
||||
int64_t n_blocks = 0;
|
||||
void* base = nullptr;
|
||||
int64_t off = 0; /* this group's start inside one entry's staging bytes */
|
||||
/* rad_kv_group_zero: no shard on this rank. Kept in its place, because a job's block ids
|
||||
* are one per cached group in the same order on every rank; nothing is gathered or
|
||||
* scattered for it and it is no part of this rank's entry. */
|
||||
/* rad_kv_group_zero: no shard on this rank. Kept in place because a job's block ids are
|
||||
* one per cached group in the same order on every rank; it moves no bytes. */
|
||||
bool zero = false;
|
||||
Resolved gather, scatter;
|
||||
};
|
||||
|
||||
/* The staging buffer, the index buffers, the events and the transfer stream, built on the
|
||||
* first pass that has a job and never at bringup. The cost of building them eagerly is quoted
|
||||
* where it is defined; it is not small. */
|
||||
/* Builds the staging and index buffers, events and transfer stream lazily on the first pass
|
||||
* with a job, never at bringup (see the definition for the cost). */
|
||||
int device_init();
|
||||
/* WHETHER EVERY ID THIS RANK IS ABOUT TO ADDRESS IS THE CACHE'S TO WRITE.
|
||||
*
|
||||
* THE KERNEL'S BOUND IS THE CARVE AND NOT THE LIVE MARK. gather_rows and scatter_rows refuse
|
||||
* an index outside [0, n_blocks), which is every id the carve created -- but the blocks above
|
||||
* live_blocks() are lent to the expert slab, and a restore into one writes over weights a
|
||||
* kernel is reading. That reads as fluent text with a new hash on whichever rank is behind
|
||||
* rather than as a failed transfer, so it is tested here, where the job can still be refused. */
|
||||
/* Frees what device_init() allocated; the stream is the caller's to drain first. */
|
||||
void release_device();
|
||||
/* Whether every id this rank is about to address belongs to the cache. The kernels only bound
|
||||
* ids by the carve, [0, n_blocks), but blocks above live_blocks() are lent to the expert slab,
|
||||
* and a restore into one overwrites weights in use. That corrupts output silently, so it is
|
||||
* checked here, where the job can still be refused. */
|
||||
bool blocks_backed(const std::vector<int32_t>& blocks, const char* what);
|
||||
void warn_once(const char* what, int st);
|
||||
int run_rows(const Resolved& r, bool scatter, const GroupInfo& gi, int64_t layer,
|
||||
@@ -161,19 +135,15 @@ private:
|
||||
bool enabled_ = false;
|
||||
bool leader_ = false; /* this rank chooses block ids; the others follow */
|
||||
bool warned_ = false;
|
||||
/* Separate from `warned_`: a transfer that failed and an id this rank cannot address are
|
||||
* different reports, and the second is a broken invariant rather than a tier having trouble.
|
||||
* Said once, so a refusal the pass retries every tick does not fill the log with it. */
|
||||
/* Separate from `warned_`: an unaddressable id is a broken invariant, not a transfer failure.
|
||||
* Logged once, since the pass retries the refusal every tick. */
|
||||
bool warned_unbacked_ = false;
|
||||
/* THE CARD THIS RANK OWNS. Every allocation and every launch below takes the CURRENT device,
|
||||
* and the engine loop leaves whatever device the last rank used current. Pinned here rather
|
||||
* than assumed. */
|
||||
/* This rank's card. Allocations and launches use the current device, and the engine loop leaves
|
||||
* the last rank's device current, so it is set explicitly. */
|
||||
int device_ = -1;
|
||||
/* WHERE THIS RANK'S BYTES LIVE INSIDE A SHARED SLOT. One host slot holds an entry for the
|
||||
* WHOLE ENGINE, and under tensor parallelism an entry is n_ranks shards of KV that are not
|
||||
* interchangeable. Every rank writing at offset zero would mean the last one to run wins and
|
||||
* every rank scatters back somebody else's half. So the slot is n_ranks entries wide and a
|
||||
* rank only ever touches its own window. */
|
||||
/* This rank's offset inside a shared host slot. A slot holds the whole engine's entry, which
|
||||
* under tensor parallelism is n_ranks distinct KV shards, so the slot is n_ranks entries wide
|
||||
* and each rank touches only its own window. */
|
||||
int64_t slot_off_ = 0;
|
||||
int64_t slot_bytes_ = 0; /* the whole shared slot: n_ranks * entry_bytes_ */
|
||||
Registry* reg_ = nullptr;
|
||||
@@ -187,13 +157,10 @@ private:
|
||||
void* stage_ = nullptr; /* device, max_batch_ * entry_bytes_ */
|
||||
/* ---- the block indices ----
|
||||
*
|
||||
* ONE REGION FOR THE COPY OUT AND A RING OF THEM FOR RESTORES, pinned on the host and mirrored
|
||||
* on the device. An index list is uploaded with the transfer it serves and read by kernels
|
||||
* later in the same stream, so a region may be refilled only once the upload that last read
|
||||
* it has run: one copy is out at a time, so its region is always free when the next is
|
||||
* issued; several restores can be issued in one step, so each takes the next region of the
|
||||
* ring and waits on that region's event -- the upload of a restore issued kRing restores ago,
|
||||
* which has long since run. */
|
||||
* One region for the copy out and a ring of kRing for restores, pinned on the host and mirrored
|
||||
* on the device. A region may be refilled only after the upload that last read it has run. One
|
||||
* copy is out at a time, so its region is always free; several restores can be issued per step,
|
||||
* so each takes the next ring region and waits on its event (the upload kRing restores ago). */
|
||||
static constexpr int kRing = 4;
|
||||
int32_t* idx_host_ = nullptr; /* pinned: copy region, then kRing restore regions */
|
||||
int32_t* idx_dev_ = nullptr;
|
||||
@@ -206,28 +173,19 @@ private:
|
||||
RadEvent ev_copy_ = nullptr; /* the last copy out, landed */
|
||||
RadEvent ev_restore_ = nullptr; /* the last restore, landed */
|
||||
bool copy_out_ = false;
|
||||
/* THE TRANSFER STREAM, WHICH IS USUALLY SOMEBODY ELSE'S. A stream costs a hardware queue and
|
||||
* a fourth queue costs this card 65% of its decode step, so the tier takes the expert mover's
|
||||
* maintenance stream when there is one (Mover::transfer_stream) and only makes its own when
|
||||
* there is not. `own_stream_` is which of those happened, because close() must not destroy a
|
||||
* stream it was lent. */
|
||||
/* Transfer stream. Each stream costs a hardware queue, and a fourth queue costs this card 65% of
|
||||
* its decode step, so the tier borrows the expert mover's maintenance stream
|
||||
* (Mover::transfer_stream) when there is one. `own_stream_` tells close() whether to destroy it. */
|
||||
RadStream stream_ = nullptr;
|
||||
RadStream shared_ = nullptr;
|
||||
bool own_stream_ = false;
|
||||
std::vector<TierJob*> order_;
|
||||
/* ---- RADIANCE_DEBUG_TIER_VERIFY ----
|
||||
*
|
||||
* DID THE BYTES SURVIVE THE ROUND TRIP. A tier that corrupts reads back as fluent, plausible,
|
||||
* wrong text and nothing about the engine says which of a dozen steps lost the bytes. This
|
||||
* hashes what went out and what came back and names the entry when they differ, which splits
|
||||
* the only question worth asking first: is the tier moving the wrong bytes, or is it moving
|
||||
* the right ones and something downstream is choosing differently?
|
||||
*
|
||||
* A DIAGNOSTIC, NOT A GUARD. It hashes on the host, which is a cost on every entry --
|
||||
* affordable when a run is being bisected and not otherwise. Off
|
||||
* unless the variable is set, and leader-only, because the map is keyed by an object the
|
||||
* followers do not own. A copy out is hashed when it has LANDED, which is when copy_state
|
||||
* first sees it done. */
|
||||
* Round-trip check: hashes each entry going out and coming back and names the entry when they
|
||||
* differ, separating "the tier moved wrong bytes" from a downstream fault. A diagnostic, not a
|
||||
* guard: host hashing costs on every entry. Off unless set; leader-only because the map is keyed
|
||||
* by an object followers do not own. A copy out is hashed once landed (first seen by copy_state). */
|
||||
bool verify_ = false;
|
||||
std::unordered_map<BlockHash, uint64_t, BlockHashHash> out_sum_;
|
||||
struct VerifyNote { BlockHash key; int32_t host_slot = -1; };
|
||||
|
||||
@@ -8,8 +8,8 @@ namespace rad {
|
||||
|
||||
int wtab_patch(const WtabPatch& p, RadStream s) {
|
||||
if (p.n == 0) return RAD_OK;
|
||||
/* After the stream's queued work, for the reason step_advance gives: a host stream is a queue
|
||||
* with a worker, and a write made ahead of it changes a table that work issued earlier reads. */
|
||||
/* A host stream is a queue with a worker: write only after its queued work, which may read
|
||||
* the old table (same reason as step_advance). */
|
||||
if (device_is_host()) {
|
||||
RAD_TRY(rad_stream_sync(s));
|
||||
for (uint32_t i = 0; i < p.n; ++i) *p.dst[i] = p.val[i];
|
||||
|
||||
+5
-5
@@ -1,10 +1,10 @@
|
||||
/* wtab.h -- writing entries of a device weight table in stream order.
|
||||
*
|
||||
* A routed layer's weight table is a device array of expert pointers, and the mover changes a few
|
||||
* of its entries on most steps. The new values travel IN THE KERNEL'S ARGUMENTS, which the backend
|
||||
* copies when the dispatch is enqueued. A copy out of a host array would read that array when the
|
||||
* card reaches the copy instead -- and the host runs ahead of the card, so by then it may hold the
|
||||
* NEXT step's pointers, including one whose transfer that earlier step was never ordered behind.
|
||||
* A routed layer's weight table is a device array of expert pointers; the mover changes a few
|
||||
* entries on most steps. The new values travel in the kernel arguments, which the backend copies
|
||||
* at enqueue. A copy from a host array would read it when the card reaches the copy, and since the
|
||||
* host runs ahead, it could then hold the next step's pointers, including one whose transfer this
|
||||
* step is not ordered behind.
|
||||
*/
|
||||
#pragma once
|
||||
#include <cstdint>
|
||||
|
||||
@@ -59,8 +59,8 @@ struct XpState {
|
||||
std::vector<XpLayer> layers;
|
||||
uint32_t seq[kXpGroups] = {};
|
||||
int last_layer = -1; /* the last layer predicted for: a lower one starts a pass */
|
||||
/* WHETHER IT PAYS: the share of its copies the steps use, judged every kXpWindow predictions from
|
||||
* the counters (stats_h, one window on their way to the host); under kXpMinUse it rests. */
|
||||
/* Payoff: the share of copies the steps use, judged every kXpWindow predictions from the
|
||||
* counters (stats_h lags one window); below kXpMinUse the prefetch rests. */
|
||||
int64_t passes = 0, rest_until = 0, rests = 0;
|
||||
int64_t calls = 0;
|
||||
uint32_t snap_copied = 0, snap_routed = 0;
|
||||
|
||||
+36
-58
@@ -30,21 +30,18 @@ namespace {
|
||||
|
||||
/* A pool class wider than this holds whole tables (the token embedding read in place), not experts. */
|
||||
constexpr uint64_t kXpMaxUnit = (uint64_t)64 << 20;
|
||||
/* Lists the queue may be behind before a request is dropped. Nothing waits for these lists, so
|
||||
* nothing slows a queue that falls behind but this: its copies could not land in time anyway, and a
|
||||
* queue that only grows would end up polling marks that have long gone back to the pool. */
|
||||
/* Lists the queue may be behind before a request is dropped. Nothing else throttles a lagging
|
||||
* queue: its copies would land too late anyway, and an ever-growing queue would end up polling
|
||||
* marks already returned to the pool. */
|
||||
constexpr int64_t kXpBehind = 3;
|
||||
/* Dispatches past a dropped request's mark before the signal can be made again: far more than the
|
||||
/* Dispatches after a dropped request's mark before its signal may be reused; far more than the
|
||||
* pass that completes it. */
|
||||
constexpr int64_t kXpMarkHold = 4096;
|
||||
/* WHETHER IT PAYS. A copy the step uses saves the link time of reading that expert under the GEMM;
|
||||
* one it does not use costs link time the GEMMs wanted, and the prediction costs a little whatever
|
||||
* comes of it. Measured on Qwen3.8-Flash-Next, the two balance near a quarter of the copies used: at
|
||||
* --tp 1 the steps used half of them and the decode step was 3.6% faster, at --tp 2 -- where each card
|
||||
* keeps most experts and its pool holds the ones the steps rarely route -- a sixth, and it was 4-6%
|
||||
* slower. So every kXpWindow predictions the prefetch looks at the share of its copies used over the
|
||||
* last window, and under kXpMinUse it rests for kXpRest passes -- no prediction, no copy -- and then
|
||||
* measures again. */
|
||||
/* Payoff. A used copy saves link time under the GEMM; an unused one costs link time the GEMMs
|
||||
* wanted, and the prediction always costs a little. On Qwen3.8-Flash-Next break-even is near a
|
||||
* quarter of copies used (--tp 1 used half and decode was 3.6% faster; --tp 2, where the pool holds
|
||||
* rarely routed experts, used a sixth and was 4-6% slower). Every kXpWindow predictions the share
|
||||
* used over the last window is judged; below kXpMinUse the prefetch rests for kXpRest passes. */
|
||||
constexpr int64_t kXpWindow = 2048;
|
||||
constexpr double kXpMinUse = 0.30;
|
||||
constexpr uint32_t kXpMinJudged = 512;
|
||||
@@ -65,8 +62,8 @@ void Ctx::xp_free(XpState& x) {
|
||||
if (x.stream) rad_stream_destroy(x.stream);
|
||||
}
|
||||
|
||||
/* At bringup, once the placement has made its pinned pools: everything the prefetch needs, or nothing
|
||||
* and a line saying why it is off. */
|
||||
/* At bringup, after placement has made its pinned pools: allocates everything, or nothing and logs
|
||||
* why the prefetch is off. */
|
||||
void Ctx::xp_open(const uint64_t* lo, const uint64_t* hi, const uint64_t* stride, int n) {
|
||||
if (xp_ || device_is_host() || route_.empty()) return;
|
||||
if (!rad_xp_supported(device_)) {
|
||||
@@ -122,8 +119,8 @@ void Ctx::xp_open(const uint64_t* lo, const uint64_t* hi, const uint64_t* stride
|
||||
void Ctx::xp_close() {
|
||||
if (!xp_) return;
|
||||
XpState& x = *xp_;
|
||||
/* NOTHING MAY READ OR WRITE THE RING WHEN IT GOES: the compute work issued so far can read it
|
||||
* through entries still pointed at it, and the queue's lists write it until they finish. */
|
||||
/* Nothing may touch the ring when it is freed: issued compute work can read it through entries
|
||||
* still pointing at it, and queued DMA lists write it until they finish. */
|
||||
if (stream_) rad_stream_sync(stream_);
|
||||
if (lane1_) rad_stream_sync(lane1_);
|
||||
{
|
||||
@@ -141,7 +138,7 @@ void Ctx::xp_close() {
|
||||
}
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(1));
|
||||
}
|
||||
/* What it came to: copies planned, and of the restored ones how many the step routed. */
|
||||
/* Summary: copies planned, and how many restored copies the step routed. */
|
||||
if (x.stream && rad_memcpy_async(x.stats_h, x.stats, sizeof(XpStats), x.stream) >= 0 &&
|
||||
rad_stream_sync(x.stream) >= 0 && x.stats_h->planned)
|
||||
RAD_INFO("rank %d: expert prefetch: %u copies planned, %u of %u looked back on routed (%.1f%%), %lld "
|
||||
@@ -152,7 +149,7 @@ void Ctx::xp_close() {
|
||||
xp_.reset();
|
||||
}
|
||||
|
||||
/* The host thread: each request's mailbox, once the plan has written it, to the DMA queue. */
|
||||
/* Host thread: hands each request's mailbox to the DMA queue once the plan has written it. */
|
||||
void Ctx::xp_serve(XpState& x) {
|
||||
for (;;) {
|
||||
XpReq r;
|
||||
@@ -163,14 +160,14 @@ void Ctx::xp_serve(XpState& x) {
|
||||
r = x.q.front();
|
||||
x.q.pop_front();
|
||||
}
|
||||
/* The marks of finished lists go back to the pool. */
|
||||
/* Return the marks of finished lists to the pool. */
|
||||
const int64_t behind = rad_xp_behind(x.device);
|
||||
while (!x.marks.empty() && x.marks.front().second <= x.lists - behind) {
|
||||
rad_ride_release(x.marks.front().first, nullptr, 0);
|
||||
x.marks.pop_front();
|
||||
}
|
||||
/* The mailbox reaches the request's number once the plan has run; a number past it means it
|
||||
* was written over by a later request and this one is stale. */
|
||||
/* The mailbox reaches the request number once the plan has run; a higher number means a
|
||||
* later request overwrote it and this one is stale. */
|
||||
volatile XpBox* b = x.box + r.g;
|
||||
const auto t0 = std::chrono::steady_clock::now();
|
||||
bool got = true;
|
||||
@@ -215,8 +212,8 @@ void Ctx::xp_serve(XpState& x) {
|
||||
}
|
||||
}
|
||||
|
||||
/* The layer's map from expert to table entries, once all its tables are bound; false until then. An
|
||||
* expert whose weights are not each in exactly one table stays out of the map. */
|
||||
/* Builds the layer's expert -> table-entry map; false until all its tables are bound. An expert
|
||||
* whose weights are not each in exactly one table is left out. */
|
||||
bool Ctx::xp_bind(XpLayer& L, int layer) {
|
||||
const RadPrefetchNext& nx = L.next;
|
||||
std::vector<void**> hm((size_t)kXpMaxNe * kXpParts, nullptr);
|
||||
@@ -241,7 +238,7 @@ bool Ctx::xp_bind(XpLayer& L, int layer) {
|
||||
XpState& x = *xp_;
|
||||
void** map = x.maps + (size_t)layer * kXpMaxNe * kXpParts;
|
||||
int32_t* place = x.places + (size_t)layer * kXpMaxNe;
|
||||
/* Once a layer, at its first issue: the one host wait here is not on the step path. */
|
||||
/* Runs once per layer at first issue, so this host wait is off the step path. */
|
||||
if (rad_memcpy_async(map, hm.data(), (int64_t)hm.size() * (int64_t)sizeof(void*), stream_) < 0 ||
|
||||
rad_memcpy_async(place, hp.data(), (int64_t)hp.size() * 4, stream_) < 0 || rad_stream_sync(stream_) < 0)
|
||||
return false;
|
||||
@@ -251,9 +248,9 @@ bool Ctx::xp_bind(XpLayer& L, int layer) {
|
||||
return true;
|
||||
}
|
||||
|
||||
/* The counters the last judgement sent to the host are a window old: the share of copies used is
|
||||
* judged from them, then the next window's are sent. A window that follows a rest is not judged --
|
||||
* its counters left before the rest -- so a rest is followed by one full window measured afresh. */
|
||||
/* Judges the share of copies used from the counters sent to the host one window ago, then sends the
|
||||
* next window's. The first window after a rest is not judged (its counters predate the rest), so
|
||||
* each rest is followed by one full fresh window. */
|
||||
void Ctx::xp_judge(XpState& x) {
|
||||
if (x.have_snap) {
|
||||
const volatile XpStats* h = x.stats_h;
|
||||
@@ -275,14 +272,12 @@ void Ctx::xp_judge(XpState& x) {
|
||||
if (rad_memcpy_async(x.stats_h, x.stats, sizeof(XpStats), x.stream) >= 0) x.have_snap = true;
|
||||
}
|
||||
|
||||
/* A pass being recorded keeps each of the three calls as a step of its own, run again where the tape
|
||||
* plays it: what a call issues -- on its own stream, or a ride on the next played dispatch -- is
|
||||
* issued again at every play rather than recorded. */
|
||||
/* When recording, each of the three calls becomes its own tape step and is re-run at every play:
|
||||
* its stream work and rides are issued afresh, not recorded. */
|
||||
int Ctx::xp_predict(const RadPrefetchNext* nx, rad_buf h, int64_t r0, int64_t rows, int64_t n_embd) {
|
||||
/* A pass this wide predicts nothing, and its tape is better without a step that does nothing. */
|
||||
/* Too wide to predict; keep the tape free of an empty step. */
|
||||
if (!xp_ || !nx || rows <= 0 || rows > kXpMaxRows) return RAD_OK;
|
||||
if (!rec_) return xp_predict_run(*nx, h, r0, rows, n_embd);
|
||||
tape_cut();
|
||||
TapeXp p;
|
||||
p.next = *nx;
|
||||
p.h = h;
|
||||
@@ -291,43 +286,26 @@ int Ctx::xp_predict(const RadPrefetchNext* nx, rad_buf h, int64_t r0, int64_t ro
|
||||
p.n_embd = n_embd;
|
||||
TapeStep st;
|
||||
st.kind = kTapeXp;
|
||||
st.lane = (uint8_t)lane_;
|
||||
st.a = (int32_t)rec_->xp.size();
|
||||
rec_->xp.push_back(p);
|
||||
rec_->steps.push_back(st);
|
||||
tape_pause(true);
|
||||
const int rc = xp_predict_run(*nx, h, r0, rows, n_embd);
|
||||
tape_pause(false);
|
||||
return rc;
|
||||
return tape_host(st, [&] { return xp_predict_run(*nx, h, r0, rows, n_embd); });
|
||||
}
|
||||
|
||||
int Ctx::xp_mark() {
|
||||
if (!xp_) return RAD_OK;
|
||||
if (!rec_) return xp_mark_run();
|
||||
tape_cut();
|
||||
TapeStep st;
|
||||
st.kind = kTapeXpMark;
|
||||
st.lane = (uint8_t)lane_;
|
||||
rec_->steps.push_back(st);
|
||||
tape_pause(true);
|
||||
const int rc = xp_mark_run();
|
||||
tape_pause(false);
|
||||
return rc;
|
||||
return tape_host(st, [&] { return xp_mark_run(); });
|
||||
}
|
||||
|
||||
int Ctx::xp_step(int layer) {
|
||||
if (!xp_) return RAD_OK;
|
||||
if (!rec_) return xp_step_run(layer);
|
||||
tape_cut();
|
||||
TapeStep st;
|
||||
st.kind = kTapeXpStep;
|
||||
st.lane = (uint8_t)lane_;
|
||||
st.a = layer;
|
||||
rec_->steps.push_back(st);
|
||||
tape_pause(true);
|
||||
const int rc = xp_step_run(layer);
|
||||
tape_pause(false);
|
||||
return rc;
|
||||
return tape_host(st, [&] { return xp_step_run(layer); });
|
||||
}
|
||||
|
||||
int Ctx::xp_predict_run(const RadPrefetchNext& nx, rad_buf h, int64_t r0, int64_t rows, int64_t n_embd) {
|
||||
@@ -346,8 +324,8 @@ int Ctx::xp_predict_run(const RadPrefetchNext& nx, rad_buf h, int64_t r0, int64_
|
||||
const char* hb = (const char*)buf_ptr(h);
|
||||
if (!w || !hb) return RAD_OK;
|
||||
const RadStream cs = cur_stream();
|
||||
/* A NEW PASS waits for the prefetch stream's work of the last one, so that stream is never a pass
|
||||
* behind the compute stream: the records and mailboxes a request reuses are three layers old. */
|
||||
/* A new pass waits for the prefetch stream's work from the last pass, so that stream is never a
|
||||
* pass behind: the records and mailboxes a request reuses are three layers old. */
|
||||
if (layer <= x.last_layer) {
|
||||
if (x.tail_live) {
|
||||
RAD_TRY(rad_event_record(x.tail, x.stream));
|
||||
@@ -358,8 +336,8 @@ int Ctx::xp_predict_run(const RadPrefetchNext& nx, rad_buf h, int64_t r0, int64_
|
||||
}
|
||||
x.last_layer = layer;
|
||||
if (x.passes < x.rest_until) return RAD_OK;
|
||||
/* THE ROUTER INPUT IS READ IN PLACE, behind the next dispatch on the compute stream -- the router,
|
||||
* which reads it -- by a ride rather than a barrier packet between two kernels. */
|
||||
/* The router input is read in place, riding behind the next compute dispatch (the router, which
|
||||
* reads it) rather than via a barrier packet between two kernels. */
|
||||
void* rt = nullptr;
|
||||
if (rad_ride(cs, &rt) == RAD_OK) {
|
||||
RAD_TRY(rad_ride_wait(x.stream, rt));
|
||||
@@ -367,7 +345,7 @@ int Ctx::xp_predict_run(const RadPrefetchNext& nx, rad_buf h, int64_t r0, int64_
|
||||
RAD_TRY(rad_event_record(x.sync, cs));
|
||||
RAD_TRY(rad_event_wait(x.stream, x.sync));
|
||||
}
|
||||
/* An earlier request still waiting for its mark goes now, unmarked. */
|
||||
/* An earlier request still waiting for its mark is sent now, unmarked. */
|
||||
if (x.pend.valid) {
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(x.mu);
|
||||
@@ -405,7 +383,7 @@ int Ctx::xp_predict_run(const RadPrefetchNext& nx, rad_buf h, int64_t r0, int64_
|
||||
int Ctx::xp_mark_run() {
|
||||
XpState& x = *xp_;
|
||||
if (!x.pend.valid) return RAD_OK;
|
||||
/* Refused only while another ride waits on the stream: the list then starts without one. */
|
||||
/* Refused only while another ride waits on the stream; the list then starts unmarked. */
|
||||
void* mark = nullptr;
|
||||
if (rad_ride(cur_stream(), &mark) == RAD_OK) {
|
||||
x.pend.mark = mark;
|
||||
|
||||
+24
-27
@@ -1,31 +1,28 @@
|
||||
/* xprefetch.h -- the next-layer expert prefetch at decode: what the host half (xprefetch.cpp) and the
|
||||
/* xprefetch.h -- next-layer expert prefetch at decode: what the host half (xprefetch.cpp) and the
|
||||
* kernels (xprefetch.hip) share.
|
||||
*
|
||||
* WHAT IT DOES. Under expert-tiered placement a routed layer's GEMMs read the experts that are not on
|
||||
* the card from the pinned host pool, across the link, while they run. A layer's router input predicts
|
||||
* the NEXT routed layer's choice well: that layer's router applied to it ranks the experts the next
|
||||
* layer will route. So at each routed layer the prefetch applies the next layer's router to this
|
||||
* layer's router input, takes the likeliest experts that sit in the pinned pool, copies them onto the
|
||||
* card with the DMA engine while the rest of this layer runs, and points the next layer's weight tables
|
||||
* at the copies just before its GEMMs. The GEMMs then read those experts from the card.
|
||||
* Under expert-tiered placement, a routed layer's GEMMs read off-card experts from the pinned host
|
||||
* pool across the link. A layer's router input predicts the next routed layer's choice well, so at
|
||||
* each routed layer the prefetch applies the next layer's router to this layer's router input,
|
||||
* copies the likeliest pinned-pool experts onto the card with the DMA engine, and points the next
|
||||
* layer's weight tables at the copies just before its GEMMs.
|
||||
*
|
||||
* NOTHING IT DOES CHANGES A RESULT. A copy holds the bytes of the pool slot it was made from, and an
|
||||
* entry is pointed at it only where it still names that slot (a compare-and-swap: a heat-engine move
|
||||
* since then wins) and only once the copy has landed. Late copies are not used; nothing waits for them.
|
||||
* Results never change: a copy holds the bytes of the pool slot it came from, and an entry is
|
||||
* redirected only where it still names that slot (compare-and-swap; a heat-engine move wins) and
|
||||
* only once the copy has landed. Late copies go unused; nothing waits for them.
|
||||
*
|
||||
* THE PIECES, per routed layer l predicting layer l+1:
|
||||
* - at l's router input (Ctx::xp_predict): on a stream of its own, behind the compute stream's
|
||||
* dispatch that reads the input (a ride), xp_logits applies l+1's router to the input rows and
|
||||
* xp_plan picks the copies and writes them to a mailbox in pinned host memory;
|
||||
* - after l's routed down GEMM (Ctx::xp_mark): a ride on the compute stream that the DMA list polls,
|
||||
* so the copies cross the link under l+1's attention rather than under l's own streamed experts;
|
||||
* - a host thread hands each mailbox to the card's prefetch DMA queue: wait for the mark, copy, then
|
||||
* write the request's number to the group's done word;
|
||||
* - ahead of l+1's routed GEMMs (Ctx::xp_step, on the compute stream): xp_step puts the previous
|
||||
* layer's entries back (its GEMMs are behind it in the stream) and points l+1's at the copies if
|
||||
* the done word says they have landed.
|
||||
* The ring holds kXpGroups layers' copies, kXpSlots each; a group is copied into again three layers
|
||||
* later, after the step that put its entries back. */
|
||||
* Pieces, per routed layer l predicting l+1:
|
||||
* - at l's router input (Ctx::xp_predict): on its own stream, riding behind the compute dispatch
|
||||
* that reads the input, xp_logits applies l+1's router and xp_plan writes the chosen copies to
|
||||
* a mailbox in pinned host memory;
|
||||
* - after l's routed down GEMM (Ctx::xp_mark): a ride on the compute stream that the DMA list
|
||||
* polls, so the copies cross the link under l+1's attention, not under l's streamed experts;
|
||||
* - a host thread hands each mailbox to the prefetch DMA queue: wait for the mark, copy, then
|
||||
* write the request number to the group's done word;
|
||||
* - before l+1's routed GEMMs (Ctx::xp_step, compute stream): restore the previous layer's
|
||||
* entries (its GEMMs are earlier in the stream) and redirect l+1's if the done word matches.
|
||||
* The ring holds kXpGroups layers of kXpSlots copies; a group is reused three layers later, after
|
||||
* the step that restored its entries. */
|
||||
#pragma once
|
||||
#include <cstdint>
|
||||
|
||||
@@ -67,9 +64,9 @@ struct XpStats {
|
||||
unsigned int copied, routed, planned, pad;
|
||||
};
|
||||
|
||||
/* What the prefetch takes on the card for a model of `layers` routed layers whose largest expert unit
|
||||
* is `unit` bytes: the ring and the buffers beside it (Ctx::xp_open allocates exactly these), in the
|
||||
* 2 MiB grains the card's allocations come in -- the ring its own, the small buffers sharing theirs. */
|
||||
/* Device bytes the prefetch takes for `layers` routed layers with largest expert unit `unit` bytes:
|
||||
* the ring and its side buffers (exactly what Ctx::xp_open allocates), each rounded to the card's
|
||||
* 2 MiB allocation grain. */
|
||||
inline int64_t xp_device_bytes(int64_t unit, int64_t layers) {
|
||||
constexpr int64_t kGrain = (int64_t)2 << 20;
|
||||
auto grains = [](int64_t b) { return (b + kGrain - 1) / kGrain * kGrain; };
|
||||
|
||||
+25
-28
@@ -8,17 +8,15 @@ namespace {
|
||||
|
||||
__device__ __forceinline__ float xp_bf(uint32_t x) { return __uint_as_float(x << 16); }
|
||||
|
||||
/* logits[r, e] = h[r, :] . w[e, :], h and w bf16. A block takes 16 experts, two a 32-lane group. Every
|
||||
* lane issues all of its weight loads first -- n_embd / 256 sixteen-byte loads an expert, kept in
|
||||
* registers -- so the kernel waits on memory once rather than once a K chunk; the rows are staged in
|
||||
* LDS in as few chunks as 40 KiB allows (one at sixteen rows of 2560 needs two). fp32 accumulation.
|
||||
* Requires n_embd % 256 == 0 and n_embd <= 4096 (rad_xp_logits_launch checks). WIDE ON PURPOSE: the
|
||||
* router input is read in place and the block overwrites it once its GEMMs are done, so a narrower
|
||||
* grid that waits longer for CUs beside the compute stream reads it too late and predicts badly. */
|
||||
/* logits[r, e] = h[r, :] . w[e, :], bf16 in, fp32 accumulation. A block takes 16 experts, two per
|
||||
* 32-lane group. Each lane issues all its weight loads first (n_embd / 256 16-byte loads per expert,
|
||||
* held in registers) so the kernel waits on memory once; rows are staged in LDS in as few 40 KiB
|
||||
* chunks as fit (16 rows of 2560 need two). Requires n_embd % 256 == 0 and n_embd <= 4096 (the
|
||||
* launcher checks). The grid is wide on purpose: the router input is read in place and overwritten
|
||||
* once the block's GEMMs finish, so a narrower grid waiting for CUs reads it too late. */
|
||||
constexpr uint32_t kLgE = 16, kLgJ = 16, kLgLds = 40u << 10;
|
||||
/* For gfx9-4-generic, one of rad_core's portable targets, LLVM leaves the row loop inside the
|
||||
* unrolled K loop a loop and warns once a copy; every other target unrolls it. The warning is
|
||||
* silenced for this kernel only, which changes no code. */
|
||||
/* On gfx9-4-generic LLVM does not unroll the row loop inside the unrolled K loop and warns per
|
||||
* copy; other targets unroll it. Silenced for this kernel only. */
|
||||
#pragma clang diagnostic push
|
||||
#pragma clang diagnostic ignored "-Wpass-failed"
|
||||
__global__ __launch_bounds__(256) void xp_logits(const uint16_t* __restrict__ h,
|
||||
@@ -80,7 +78,7 @@ __global__ __launch_bounds__(256) void xp_logits(const uint16_t* __restrict__ h,
|
||||
#pragma unroll
|
||||
for (int a = 0; a < 2; ++a) {
|
||||
const uint32_t e = e0 + (uint32_t)a;
|
||||
/* No unroll pragma: the exit at `rows` keeps this a loop, and the compiler refuses one. */
|
||||
/* No unroll pragma: the early exit at `rows` makes the compiler refuse it. */
|
||||
for (int r = 0; r < rad::kXpMaxRows; ++r) {
|
||||
if ((uint32_t)r >= rows) break;
|
||||
float v = acc[a][r];
|
||||
@@ -91,11 +89,11 @@ __global__ __launch_bounds__(256) void xp_logits(const uint16_t* __restrict__ h,
|
||||
}
|
||||
#pragma clang diagnostic pop
|
||||
|
||||
/* One block. Count what the group's previous records came to (whether the step routed them), take each
|
||||
* row's top-k with its softmax probability, keep the distinct experts whose entries all sit in one
|
||||
* pinned pool slot, score each by its highest probability -- half as much again where the previous
|
||||
* pass routed it at this layer -- and write the kXpSlots best into the ring's group as jobs, then the
|
||||
* mailbox's number. The previous records' entries are back already: xp_step puts them back. */
|
||||
/* One block. Counts whether the step routed the group's previous records, takes each row's top-k
|
||||
* with softmax probabilities, keeps distinct experts whose entries all sit in one pinned pool slot,
|
||||
* scores each by its highest probability (x1.5 if the previous pass routed it at this layer), and
|
||||
* writes the kXpSlots best as jobs, then the mailbox number. xp_step has already restored the
|
||||
* previous records' entries. */
|
||||
constexpr float kXpPrevBoost = 0.5f;
|
||||
__global__ __launch_bounds__(256) void xp_plan(const float* __restrict__ lg, uint32_t rows, uint32_t ne,
|
||||
uint32_t k, void** const* __restrict__ map,
|
||||
@@ -176,8 +174,8 @@ __global__ __launch_bounds__(256) void xp_plan(const float* __restrict__ lg, uin
|
||||
int pi = -1;
|
||||
for (int i = 0; i < pools.n; ++i)
|
||||
if (p >= pools.lo[i] && p < pools.hi[i]) { pi = i; break; }
|
||||
/* Every entry of the unit in the same pool slot: the mover patches a layer's tables
|
||||
* one at a time, and a unit caught between two of its patches is left alone. */
|
||||
/* All entries of the unit must sit in one pool slot: the mover patches tables one
|
||||
* at a time, so skip a unit caught between two of its patches. */
|
||||
if (pi >= 0) {
|
||||
const uint64_t lo = pools.lo[pi], st = pools.stride[pi];
|
||||
const uint64_t base = lo + ((p - lo) / st) * st;
|
||||
@@ -203,8 +201,7 @@ __global__ __launch_bounds__(256) void xp_plan(const float* __restrict__ lg, uin
|
||||
if (u < o) first = false;
|
||||
best = fmaxf(best, s_pr[u]);
|
||||
}
|
||||
/* The previous pass routed it here: the counts row still holds that pass until this layer's
|
||||
* router runs. */
|
||||
/* The counts row holds the previous pass until this layer's router runs. */
|
||||
if (first && cnt && place && e >= 0 && (uint32_t)e < ne) {
|
||||
const int pl = place[e];
|
||||
if (pl >= 0 && cnt[pl] > 0) best *= 1.f + kXpPrevBoost;
|
||||
@@ -231,9 +228,9 @@ __global__ __launch_bounds__(256) void xp_plan(const float* __restrict__ lg, uin
|
||||
const uint64_t base = lo + ((s_p[o] - lo) / st) * st;
|
||||
const uint64_t dst = ring + (uint64_t)j * rs;
|
||||
if (q == 0) {
|
||||
/* System-scope stores write through to host memory themselves, so the tag needs only their
|
||||
* completion, not a writeback of the whole L2 -- which would take the compute stream's dirty
|
||||
* lines with it, every layer. */
|
||||
/* System-scope stores write through to host memory, so the tag needs only their
|
||||
* completion, not a full L2 writeback (which would flush the compute stream's dirty
|
||||
* lines every layer). */
|
||||
__hip_atomic_store(&box->jobs[j].src, base, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM);
|
||||
__hip_atomic_store(&box->jobs[j].dst, dst, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM);
|
||||
__hip_atomic_store(&box->jobs[j].bytes, st, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM);
|
||||
@@ -247,7 +244,7 @@ __global__ __launch_bounds__(256) void xp_plan(const float* __restrict__ lg, uin
|
||||
rec[j].oldv[q] = (void*)old;
|
||||
rec[j].newv[q] = (void*)(dst + (old - base));
|
||||
}
|
||||
/* The tag after the job's own stores have completed: a tag the host sees vouches for them. */
|
||||
/* Tag after the job's stores complete, so a visible tag implies a complete job. */
|
||||
if (q == 0) {
|
||||
__builtin_amdgcn_fence(__ATOMIC_RELEASE, "agent");
|
||||
__hip_atomic_store(&box->jobs[j].tag, (uint64_t)seq, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM);
|
||||
@@ -263,10 +260,10 @@ __global__ __launch_bounds__(256) void xp_plan(const float* __restrict__ lg, uin
|
||||
}
|
||||
}
|
||||
|
||||
/* On the compute stream ahead of a layer's routed GEMMs. The previous layer's patches go back -- its
|
||||
* GEMMs are behind this in the stream -- then this layer's units point at the ring, only where an entry
|
||||
* still holds what the plan read (a heat-engine move since wins) and only if the copies have landed:
|
||||
* the list's last write before its number puts the request's number in `done`. */
|
||||
/* Compute stream, before a layer's routed GEMMs. Restores the previous layer's patches (its GEMMs
|
||||
* are earlier in the stream), then points this layer's units at the ring, only where an entry still
|
||||
* holds what the plan read (a later heat-engine move wins) and only if `done` holds the request
|
||||
* number, which the DMA list writes after its copies. */
|
||||
__global__ __launch_bounds__(128) void xp_step(const rad::XpRec* __restrict__ rrec, const int32_t* __restrict__ rn,
|
||||
const rad::XpRec* __restrict__ prec, const int32_t* __restrict__ pn,
|
||||
const uint32_t* done, uint32_t seq) {
|
||||
|
||||
Reference in new issue
Block a user