Archived
radiance 1.0.0
This commit is contained in:
commit
ae74a8aebf
616 files changed
+338692
No files matched your search
@@ -0,0 +1,88 @@
|
||||
/* arena.cpp -- one allocation, sized once. See arena.h for why there is no allocate(). */
|
||||
#include "arena.h"
|
||||
|
||||
#include <algorithm>
|
||||
|
||||
namespace rad {
|
||||
|
||||
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. */
|
||||
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. */
|
||||
if (total == 0) total = RAD_ALIGN_UNIT;
|
||||
|
||||
void* p = rad_dev_alloc(total, kind);
|
||||
if (!p) {
|
||||
RAD_ERR("arena: %s of %s failed: %s",
|
||||
kind == RAD_MEM_DEVICE ? "device allocation" : "host allocation",
|
||||
humanb(total).c_str(), rad_dev_last_error());
|
||||
return RAD_E_NOMEM;
|
||||
}
|
||||
|
||||
base_ = static_cast<char*>(p);
|
||||
kind_ = kind;
|
||||
bytes_ = total;
|
||||
scratch_off_ = off;
|
||||
scratch_bytes_ = scratch_bytes;
|
||||
scratch_pitch_ = pitch;
|
||||
scratch_regions_ = regions;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
void Arena::release() {
|
||||
if (base_) rad_dev_free(base_, kind_);
|
||||
base_ = nullptr;
|
||||
bytes_ = 0;
|
||||
scratch_off_ = 0;
|
||||
scratch_bytes_ = 0;
|
||||
scratch_pitch_ = 0;
|
||||
scratch_regions_ = 1;
|
||||
}
|
||||
|
||||
|
||||
/* 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_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) {
|
||||
const BufferInfo& bi = P.buffers[i];
|
||||
if (bi.arena_offset < 0) continue; /* the plan did not run; bind_arena refuses by name */
|
||||
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);
|
||||
}
|
||||
int64_t& hw = (bi.decl.domain == RAD_DOMAIN_HOST) ? host_hw : dev_hw;
|
||||
hw = std::max(hw, bi.arena_offset + bytes);
|
||||
}
|
||||
/* 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. */
|
||||
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) +
|
||||
align_up(P.scratch_bytes, RAD_ALIGN_UNIT) * std::max<int64_t>(P.scratch_regions, 1);
|
||||
if (total == 0) total = RAD_ALIGN_UNIT; /* Arena::init's floor, for the same reason */
|
||||
if (dev_out) *dev_out = dev_bytes;
|
||||
if (total_out) *total_out = total;
|
||||
return total;
|
||||
}
|
||||
} /* namespace rad */
|
||||
@@ -0,0 +1,71 @@
|
||||
/* 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.
|
||||
*
|
||||
* 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.
|
||||
*/
|
||||
#pragma once
|
||||
#include "../rad_core.h"
|
||||
|
||||
namespace rad {
|
||||
|
||||
class Arena {
|
||||
public:
|
||||
Arena() = default;
|
||||
~Arena() { release(); }
|
||||
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). */
|
||||
int init(int64_t plan_bytes, int64_t scratch_bytes, int kind, int regions = 1);
|
||||
void release();
|
||||
|
||||
char* base() const { return base_; }
|
||||
/* Region `r`, or region 0 when the arena holds fewer. */
|
||||
void* scratch(int r = 0) const {
|
||||
if (!base_) return nullptr;
|
||||
return base_ + scratch_off_ + (r > 0 && r < scratch_regions_ ? r * scratch_pitch_ : 0);
|
||||
}
|
||||
int64_t scratch_bytes() const { return scratch_bytes_; }
|
||||
int scratch_regions() const { return scratch_regions_; }
|
||||
int64_t bytes() const { return bytes_; }
|
||||
bool live() const { return base_ != nullptr; }
|
||||
|
||||
private:
|
||||
char* base_ = nullptr;
|
||||
int kind_ = RAD_MEM_DEVICE;
|
||||
int64_t bytes_ = 0;
|
||||
int64_t scratch_off_ = 0;
|
||||
int64_t scratch_bytes_ = 0;
|
||||
int64_t scratch_pitch_ = 0; /* scratch_bytes_ padded to RAD_ALIGN_UNIT */
|
||||
int scratch_regions_ = 1;
|
||||
};
|
||||
|
||||
|
||||
/* 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.
|
||||
*
|
||||
* `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.
|
||||
* Returns the total. */
|
||||
int64_t arena_plan_bytes(const Program& P, int64_t* dev_out, int64_t* total_out);
|
||||
} /* namespace rad */
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,807 @@
|
||||
/* 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.
|
||||
*
|
||||
* 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.
|
||||
*
|
||||
* 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.
|
||||
*
|
||||
* 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.
|
||||
*/
|
||||
#pragma once
|
||||
#include "../rad_core.h"
|
||||
#include "arena.h"
|
||||
#include "rank_barrier.h"
|
||||
#include "residency.h"
|
||||
#include "stager.h"
|
||||
#include "device/device.h"
|
||||
|
||||
#include <atomic>
|
||||
#include <string>
|
||||
#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. */
|
||||
struct RadCtx { };
|
||||
|
||||
namespace rad {
|
||||
|
||||
/* 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. */
|
||||
constexpr int MAX_OPERANDS = 32;
|
||||
|
||||
typedef void (*ArchStepFn)(RadCtx*, const RadBatch*);
|
||||
|
||||
/* ------------------------------------------------------------------ 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`.
|
||||
*
|
||||
* `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. */
|
||||
struct IssuePlan {
|
||||
RadArgs args{};
|
||||
RadLaunchFn launch = nullptr;
|
||||
const KernelRow* row = nullptr;
|
||||
};
|
||||
|
||||
/* 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. */
|
||||
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. */
|
||||
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, so the accounting on the issue path is a predicted branch and not a string compare.
|
||||
* The link is shared with the expert mover, so separating "how much of it is the all-reduce"
|
||||
* needs the collective's own traffic counted. */
|
||||
bool collective = 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.
|
||||
*
|
||||
* 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 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. */
|
||||
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.
|
||||
*/
|
||||
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. */
|
||||
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.
|
||||
*
|
||||
* 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.
|
||||
*
|
||||
* The layouts are the ones libref/ref_ops.h states once for the whole project:
|
||||
*
|
||||
* 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]]
|
||||
* CONV [n_states, n_head_kv * head_dim, conv_slots] channel-major, then time
|
||||
*/
|
||||
struct KVPoolBinding {
|
||||
void* base = nullptr;
|
||||
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. */
|
||||
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};
|
||||
};
|
||||
|
||||
struct CtxDesc {
|
||||
Program* program = nullptr;
|
||||
int rank = 0;
|
||||
int world_size = 1;
|
||||
int device = 0; /* the one device this rank owns */
|
||||
RadStream stream = nullptr; /* null: the Ctx creates its own compute stream */
|
||||
ResidencyTable* residency = nullptr; /* null in the all-in-VRAM case */
|
||||
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. */
|
||||
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. */
|
||||
std::vector<KVPoolBinding> kv;
|
||||
};
|
||||
|
||||
/* ------------------------------------------------------------------ Ctx */
|
||||
class Ctx : public RadCtx {
|
||||
public:
|
||||
Ctx() = default;
|
||||
~Ctx();
|
||||
Ctx(const Ctx&) = delete;
|
||||
Ctx& operator=(const Ctx&) = delete;
|
||||
|
||||
int init(const CtxDesc& d);
|
||||
void shutdown();
|
||||
|
||||
/* ---------------------------------------------------------- the hot path */
|
||||
int issue(rad_op h, const RadOperand* opd, int n_opd, int64_t n);
|
||||
/* A weight stager for the passes it arms for (runtime/stager.h); null for none. */
|
||||
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. */
|
||||
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. */
|
||||
int bind_thread();
|
||||
|
||||
/* ---------------------------------------------------------- run-phase queries */
|
||||
const RadBatch* batch() const { return batch_; }
|
||||
int rank() const { return rank_; }
|
||||
int world_size() const { return world_size_; }
|
||||
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. */
|
||||
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. */
|
||||
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. */
|
||||
int lane_join(int from, int to);
|
||||
|
||||
void* weight_ptr(rad_weight w);
|
||||
void* buf_ptr(rad_buf b);
|
||||
|
||||
/* ---------------------------------------------------------- routing (spec §5.5) */
|
||||
int route_report(int layer, const RadRouting* r);
|
||||
/* Layer `layer`'s row of the card-side histogram, when it holds `n_expert` counts; null
|
||||
* otherwise. A report naming this row is taken in place (see rad_route_counts). */
|
||||
int32_t* route_counts(int layer, int64_t n_expert) const {
|
||||
if (!route_dev_ || layer < 0 || (size_t)layer >= route_.size() || n_expert <= 0 ||
|
||||
n_expert > route_n_expert_)
|
||||
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. */
|
||||
int n_route_layers() const { return (int)route_.size(); }
|
||||
int64_t route_n_expert() const { return route_n_expert_; }
|
||||
/* 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.
|
||||
*
|
||||
* `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.
|
||||
*
|
||||
* `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. */
|
||||
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. */
|
||||
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. */
|
||||
uint64_t route_dropped() const { return route_dropped_; }
|
||||
/* Told by the drain, so the ring knows which banks are still owed a reader. */
|
||||
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. */
|
||||
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. */
|
||||
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. */
|
||||
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.
|
||||
*
|
||||
* `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.
|
||||
*
|
||||
* Relaxed atomics: written by this rank's step thread, read by whatever thread is drawing. */
|
||||
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. */
|
||||
struct PassCounts {
|
||||
int64_t played = 0, recorded = 0, audited = 0;
|
||||
int64_t issued_unkeyed = 0, issued_refused = 0, issued_first = 0;
|
||||
int64_t dispatched = 0, unordered = 0;
|
||||
};
|
||||
PassCounts pass_counts() const {
|
||||
PassCounts c;
|
||||
c.played = pc_played_.load(std::memory_order_relaxed);
|
||||
c.recorded = pc_recorded_.load(std::memory_order_relaxed);
|
||||
c.audited = pc_audited_.load(std::memory_order_relaxed);
|
||||
c.issued_unkeyed = pc_unkeyed_.load(std::memory_order_relaxed);
|
||||
c.issued_refused = pc_refused_.load(std::memory_order_relaxed);
|
||||
c.issued_first = pc_first_.load(std::memory_order_relaxed);
|
||||
c.dispatched = pc_dispatched_.load(std::memory_order_relaxed);
|
||||
c.unordered = pc_unordered_.load(std::memory_order_relaxed);
|
||||
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.
|
||||
*
|
||||
* 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. */
|
||||
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(); }
|
||||
|
||||
private:
|
||||
int prepare();
|
||||
int bind_arena();
|
||||
int bind_buffers();
|
||||
int bind_weights(bool refresh_only);
|
||||
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. */
|
||||
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. */
|
||||
void* resolve_weight(rad_weight w);
|
||||
|
||||
/* ---- weight TABLES (RAD_OPK_WTAB), which a routed mixture of experts issues and nothing
|
||||
* else does.
|
||||
*
|
||||
* 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.
|
||||
*
|
||||
* 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. */
|
||||
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. */
|
||||
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. */
|
||||
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. */
|
||||
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. */
|
||||
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.
|
||||
*
|
||||
* 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.
|
||||
*
|
||||
* 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.
|
||||
*
|
||||
* 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. */
|
||||
enum TapeKind : uint8_t { kTapePlay = 0, kTapeTable = 1, kTapeHost = 2, kTapeRoute = 3 };
|
||||
struct TapeStep {
|
||||
uint8_t kind = kTapePlay;
|
||||
uint8_t lane = 0; /* the lane the host work ran on */
|
||||
int16_t opd = 0; /* kTapeTable: the operand position, for its error message */
|
||||
int32_t a = 0, b = 0; /* play [a, b) | table slot, op | host op index | route index */
|
||||
};
|
||||
struct TapeHost {
|
||||
rad_op h = 0;
|
||||
RadLaunchFn launch = nullptr;
|
||||
RadArgs args{}; /* as it ran; `t` points at `t` below */
|
||||
RadTensor t[MAX_OPERANDS] = {};
|
||||
int64_t n = 0;
|
||||
bool drain = false; /* an operand the arena does not track: drain instead */
|
||||
};
|
||||
struct PassTape {
|
||||
uint64_t key = 0;
|
||||
RadTape dev = nullptr;
|
||||
std::vector<TapeStep> steps;
|
||||
std::vector<TapeHost> host;
|
||||
std::vector<std::pair<int, RadRouting>> route;
|
||||
/* What the recording added to the Ctx's counters, and the bookkeeping it ended on. */
|
||||
int64_t issues = 0, ar_calls = 0, ar_bytes = 0, stream_waits = 0, host_syncs = 0;
|
||||
bool touch_pending[2] = {};
|
||||
bool scratch_open[2] = {};
|
||||
int64_t plays = 0;
|
||||
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.
|
||||
*
|
||||
* 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. */
|
||||
struct HazOp {
|
||||
int32_t rec0 = 0, rec1 = 0; /* its dispatches in the tape */
|
||||
uint32_t op = 0;
|
||||
bool opaque = false;
|
||||
uint32_t rd = 0, n_rd = 0, wr = 0, n_wr = 0; /* into haz_rng_ */
|
||||
};
|
||||
std::vector<HazOp> haz_ops_;
|
||||
std::vector<std::pair<uintptr_t, uintptr_t>> haz_rng_;
|
||||
void haz_note(const OpPlan& p, const IssuePlan& ip, const RadTensor* t, int n_opd, int rec0,
|
||||
int rec1);
|
||||
int haz_mark(PassTape& t);
|
||||
|
||||
static constexpr size_t kTapes = 24; /* recorded passes kept, least recently used out */
|
||||
static constexpr int64_t kAuditPlays = 1024;
|
||||
|
||||
std::vector<PassTape> tapes_;
|
||||
uint64_t tape_clock_ = 0;
|
||||
/* Keys seen once, and keys recorded once and not yet verified. */
|
||||
uint64_t tape_seen_[32] = {};
|
||||
size_t tape_seen_at_ = 0;
|
||||
std::vector<uint64_t> tape_refused_; /* keys whose pass could not be recorded */
|
||||
uint64_t tape_told_ = 0; /* draft passes whose first recording was logged */
|
||||
bool tape_on_ = false; /* the backend can, and nothing needs every issue */
|
||||
bool record_passes_ = true; /* CtxDesc::record_passes */
|
||||
PassTape* rec_ = nullptr; /* the tape being recorded, while one is */
|
||||
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 */
|
||||
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. */
|
||||
int route_report_impl(int layer, const RadRouting* r, bool copy);
|
||||
|
||||
std::vector<WeightTable> wtabs_;
|
||||
std::unordered_map<uint64_t, size_t> wtab_of_;
|
||||
|
||||
/* Resolves the run, refreshes the table if it moved, and fills `out` with the tensor the
|
||||
* kernel sees: entry 0's dtype and trailing extents, `shape[0]` = n, `stride[0]` = 0.
|
||||
* Returns RAD_OK, or aborts the step and returns its status. */
|
||||
int ensure_weight_table(uint64_t key, rad_weight first, int64_t n, size_t* slot_out);
|
||||
int bind_weight_tables();
|
||||
int resolve_weight_table(rad_op h, int operand, rad_weight first, int64_t n, RadTensor* out);
|
||||
int weight_table_tensor(rad_op h, int operand, const WeightTable& t, const RadTensor& e0,
|
||||
RadTensor* out);
|
||||
void free_weight_tables();
|
||||
|
||||
/* Cold, noinline paths. Kept out of issue() so the hot path stays one straight line. */
|
||||
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. */
|
||||
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. */
|
||||
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. */
|
||||
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. */
|
||||
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. */
|
||||
void oracle_repeat(rad_op h, const IssuePlan& dip, int64_t seq, int n_opd);
|
||||
const char* ip_kernel_name(rad_op h) const;
|
||||
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;
|
||||
std::vector<KVPoolBinding> kv_; /* by rad_kvgroup; RAD_OPK_KV resolves through it */
|
||||
ResidencyTable* residency_ = nullptr;
|
||||
OpStager* stager_ = nullptr;
|
||||
bool staging_ = false; /* the stager armed for the pass being issued */
|
||||
int issue_body(rad_op h, const RadOperand* opd, int n_opd, int64_t n);
|
||||
ArchStepFn arch_step_ = nullptr;
|
||||
|
||||
int rank_ = 0;
|
||||
int world_size_ = 1;
|
||||
int device_ = 0;
|
||||
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.
|
||||
*
|
||||
* 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.
|
||||
*
|
||||
* 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.
|
||||
*
|
||||
* 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.
|
||||
*
|
||||
* 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
|
||||
*
|
||||
* 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.
|
||||
*
|
||||
* 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. */
|
||||
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). */
|
||||
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. */
|
||||
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. */
|
||||
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. */
|
||||
const char* scratch_kernel_[2] = { nullptr, nullptr };
|
||||
int64_t scratch_n_[2] = { 0, 0 };
|
||||
|
||||
Arena arena_; /* device: the buffer plan plus the shared scratch region */
|
||||
Arena host_arena_; /* only if the program declares RAD_DOMAIN_HOST buffers */
|
||||
|
||||
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. */
|
||||
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. */
|
||||
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. */
|
||||
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. */
|
||||
std::vector<uint32_t> unflushed_;
|
||||
std::vector<int64_t> band_table_;
|
||||
std::vector<IssuePlan> issue_table_;
|
||||
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. */
|
||||
int32_t* route_pool_ = nullptr; /* host */
|
||||
int32_t* route_dev_ = nullptr; /* card */
|
||||
RadEvent route_done_[kRouteBanks] = {};
|
||||
/* The layers this pass reported into `route_bank_`, as [lo, hi]; lo > hi when none. */
|
||||
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). */
|
||||
bool profiling_ = false;
|
||||
struct ProfSlot { RadEvent a = nullptr, b = nullptr; int32_t op = 0; };
|
||||
std::vector<ProfSlot> prof_ring_;
|
||||
size_t prof_n_ = 0;
|
||||
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. */
|
||||
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. */
|
||||
std::vector<double> prof_join_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_;
|
||||
|
||||
int64_t n_issues_ = 0;
|
||||
int64_t n_stream_waits_ = 0;
|
||||
int64_t n_host_syncs_ = 0;
|
||||
std::atomic<int64_t> ar_calls_{0}, ar_bytes_{0};
|
||||
std::atomic<int64_t> pc_played_{0}, pc_recorded_{0}, pc_audited_{0};
|
||||
std::atomic<int64_t> pc_unkeyed_{0}, pc_refused_{0}, pc_first_{0};
|
||||
std::atomic<int64_t> pc_dispatched_{0}, pc_unordered_{0};
|
||||
};
|
||||
|
||||
} /* namespace rad */
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,958 @@
|
||||
/* oracle.cpp -- run the HOST kernel beside the device one, on the same bytes, every issue.
|
||||
*
|
||||
* ================================================================= why this exists
|
||||
*
|
||||
* rad-kbench falsifies one op at a time against libref, with operands rad-kbench invented. A build
|
||||
* can pass nearly every configuration it knows while the engine answers the same token to every
|
||||
* prompt. That gap is structural and not a gap in coverage: rad-kbench's operands are ITS shapes, dense and
|
||||
* rank-2 and freshly filled, and the engine's are row slices of a max_tok buffer, column slices of
|
||||
* a fused projection, rank-3 views a scan kernel required, and weights that came off a file. An op
|
||||
* can be correct at every shape rad-kbench knows and wrong at the one shape the model issues.
|
||||
*
|
||||
* So this checks the shape the model actually issued. For a matching op it
|
||||
*
|
||||
* 1. copies every operand to the host BEFORE the launch -- inputs, outputs, weights, all of it;
|
||||
* 2. lets the device kernel run and synchronises;
|
||||
* 3. copies every operand back into a second host buffer;
|
||||
* 4. puts every weight the device row stores RELAID back through that row's own
|
||||
* RadUnrelayoutFn, because the kernel rearranged it at load and a dense reference reads the
|
||||
* canonical planes (see oracle_unrelayout -- this step is not optional, it is the
|
||||
* difference between checking a kernel and comparing a permutation against itself);
|
||||
* 5. runs the HOST kernel for the same (op, band) on the copy from step 1 -- same RadTensor
|
||||
* shapes, same strides, same parameters, only the pointers differ;
|
||||
* 6. compares, per operand, the host result against the device result.
|
||||
*
|
||||
* Step 5 is the part that has no substitute. The host row is libref's, resolved by the same
|
||||
* selector into the same bucket table -- `issue_table_[plan_off + band*RAD_N_DOMAINS + HOST]` is
|
||||
* already sitting there beside the device plan, filled in at prepare and never used, because the
|
||||
* placement planner put every op on the device. It is a second implementation of the op, against
|
||||
* the same schema, and it is free.
|
||||
*
|
||||
* ================================================================= what it costs
|
||||
*
|
||||
* Everything. Two device-to-host copies of every operand -- a fused gate_up weight is 170 MiB --
|
||||
* a host synchronisation per issue, and a reference kernel that is not trying to be fast. A step
|
||||
* with the oracle on takes minutes. It is a debugging instrument and it is off unless asked.
|
||||
*
|
||||
* ================================================================= how to ask
|
||||
*
|
||||
* RADIANCE_OP_ORACLE=gemm_nt_q,rmsnorm op names, comma separated; `*` for every op
|
||||
* RADIANCE_OP_ORACLE_MAX=32 stop after this many checks (default 32)
|
||||
* RADIANCE_OP_ORACLE_FROM=0 first ISSUE INDEX to consider (default 0)
|
||||
* RADIANCE_OP_ORACLE_TO=100000 last issue index to consider
|
||||
* RADIANCE_OP_ORACLE_TOL=0.02 relative tolerance below which an operand is silent
|
||||
* RADIANCE_OP_ORACLE_MAXBYTES the largest operand a check will copy (default 4 GiB)
|
||||
*
|
||||
* The issue index is the same counter Ctx tracks internally and the same order --debug-graph
|
||||
* prints, so a failure names a position in the graph and not just an op.
|
||||
*
|
||||
* ================================================================= the repeat mode
|
||||
*
|
||||
* RADIANCE_OP_REPEAT asks a different question with the same machinery: not "does this kernel
|
||||
* agree with libref" but "does this kernel agree with ITSELF". It snapshots the operands, lets
|
||||
* the device kernel run, puts the operands back exactly as they were, runs the SAME DEVICE KERNEL
|
||||
* again, and byte-compares the two results.
|
||||
*
|
||||
* That is the one fault class every other instrument here is structurally blind to. The oracle,
|
||||
* rad-kbench and the residual probe all run an op ONCE per side, so a kernel with an unordered
|
||||
* reduction, a workgroup reading what another workgroup is writing, or a workspace it assumed was
|
||||
* zeroed passes them at exactly the rate it happens to be right. Byte-exact, no tolerance: the
|
||||
* same kernel on the same bytes has no licence to move, and one mantissa bit is a different token
|
||||
* a few hundred greedy steps later.
|
||||
*
|
||||
* RADIANCE_OP_REPEAT=* op names, comma separated; `*` for every op
|
||||
* RADIANCE_OP_REPEAT_MAX=1000000 stop after this many checks
|
||||
* RADIANCE_OP_REPEAT_FROM / _TO issue index window
|
||||
* RADIANCE_OP_REPEAT_MAXBYTES=8388608 operands above this are not copied, restored or
|
||||
* compared -- which is what keeps a 170 MiB fused weight
|
||||
* from making the mode unaffordable, and is right only
|
||||
* because such an operand is read-only.
|
||||
*
|
||||
* ================================================================= what it cannot see
|
||||
*
|
||||
* An op ISSUED ON A LANE THE SNAPSHOT DOES NOT SYNCHRONISE -- fixed for lane 1, which is the only
|
||||
* one the ABI has, and a third would need the same line.
|
||||
*
|
||||
* An op with no host kernel for the band -- the oracle skips it and says so once. An op whose
|
||||
* dtype the core cannot size (a plugin-private one) -- skipped, since a byte span is the one thing
|
||||
* this needs to know. An op whose device row re-lays a weight and publishes no inverse -- skipped
|
||||
* BY NAME, because the alternative is a page of false mismatches that drowns the true ones. And
|
||||
* an op that is wrong in the SAME WAY on both sides, which is what a shared misreading of the
|
||||
* schema would look like; that is what rad-kbench's independent operands
|
||||
* are for, and the two instruments are complementary rather than redundant.
|
||||
*/
|
||||
#include "ctx.h"
|
||||
#include "format/encoding.h"
|
||||
#include "rad_plugin.h"
|
||||
|
||||
#include <cmath>
|
||||
#include <cstdint>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace rad {
|
||||
|
||||
/* ------------------------------------------------------------------ the state */
|
||||
struct Ctx::OracleState {
|
||||
std::vector<std::string> want; /* op names; a single "*" means every op */
|
||||
int64_t budget = 32;
|
||||
int64_t from = 0, to = INT64_MAX;
|
||||
double tol = 2e-2;
|
||||
int64_t checked = 0, skipped_nohost = 0;
|
||||
bool said_nohost = false;
|
||||
/* ---- repeat mode. `maxbytes` is what makes it affordable: a fused gate_up operand is 170 MiB
|
||||
* and a weight is read-only, so an operand past the cap is not snapshotted, not restored and
|
||||
* not compared. Every activation this graph carries at decode is far below it. */
|
||||
bool repeat = false;
|
||||
int64_t maxbytes = 8 << 20;
|
||||
/* ---- AN OPERAND THE HOST CANNOT HOLD, which is the oracle mode's own cap and not the one
|
||||
* above. A snapshot is two host copies of every operand, plus a third for a weight stored
|
||||
* re-laid, so an operand of tens of gigabytes does not make a check slow -- it ends the
|
||||
* process with nothing reported. Four gibibytes clears a routed layer's whole expert table,
|
||||
* which is the largest operand a check has to hold. */
|
||||
int64_t maxopd = 4LL << 30;
|
||||
int64_t differed = 0, unchecked = 0;
|
||||
int skip[MAX_OPERANDS] = {0};
|
||||
|
||||
std::vector<uint8_t> scratch; /* the host kernel's, sized per launch */
|
||||
/* A re-laid weight inverted back into the form a dense reference reads, one buffer per
|
||||
* operand that needed it, and which operands those were. See oracle_unrelayout. */
|
||||
std::vector<std::vector<uint8_t>> logical;
|
||||
int unlaid[MAX_OPERANDS] = {0};
|
||||
std::vector<std::vector<uint8_t>> pre, post; /* one snapshot per operand */
|
||||
int64_t span[MAX_OPERANDS] = {0}; /* elements, stacked */
|
||||
int64_t ent [MAX_OPERANDS] = {0}; /* bytes, ONE entry */
|
||||
/* Entries when the operand is a weight TABLE and 0 when it is a plane. See oracle_size: a
|
||||
* table is materialised stacked, because the operand itself is an array of pointers. */
|
||||
int64_t tab [MAX_OPERANDS] = {0};
|
||||
int alias[MAX_OPERANDS] = {0}; /* which operand owns the copy */
|
||||
RadTensor ht[MAX_OPERANDS]{};
|
||||
};
|
||||
|
||||
namespace {
|
||||
|
||||
/* The number of ELEMENTS a tensor's strides can reach, which is what has to be copied. Not
|
||||
* numel: a row slice of a [max_tok, n] buffer is dense, but a column slice of a fused projection
|
||||
* is not, and copying numel elements of one of those copies the wrong bytes. */
|
||||
int64_t span_of(const RadTensor* t) {
|
||||
if (!t->data || t->rank == 0) return 0;
|
||||
int64_t s = 1;
|
||||
for (uint32_t d = 0; d < t->rank; ++d) {
|
||||
if (t->shape[d] <= 0) return 0;
|
||||
const int64_t st = t->stride[d];
|
||||
if (st > 0) s += (t->shape[d] - 1) * st;
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
float f8e4m3_to_f32(uint8_t b) {
|
||||
const uint32_t sgn = (uint32_t)(b & 0x80u) << 24;
|
||||
const int e = (b >> 3) & 0x0F;
|
||||
const uint32_t m = b & 0x07u;
|
||||
float f;
|
||||
uint32_t u;
|
||||
if (e == 0) { /* subnormal: m * 2^-9 */
|
||||
if (!m) { u = sgn; std::memcpy(&f, &u, 4); return f; }
|
||||
int ex = -6; uint32_t mm = m;
|
||||
while (!(mm & 0x08u)) { mm <<= 1; --ex; } /* normalise into 1.mmm */
|
||||
u = sgn | ((uint32_t)(ex + 127) << 23) | ((mm & 0x07u) << 20);
|
||||
} else if (e == 0x0F && m == 0x07) { /* the two NaN encodings */
|
||||
u = sgn | 0x7FC00000u;
|
||||
} else {
|
||||
u = sgn | ((uint32_t)(e - 7 + 127) << 23) | (m << 20);
|
||||
}
|
||||
std::memcpy(&f, &u, 4);
|
||||
return f;
|
||||
}
|
||||
|
||||
/* One element as a double, by dtype. Returns false for a dtype with no meaningful value -- the
|
||||
* comparison then falls back to a byte compare, which is the right answer for an index plane. */
|
||||
bool elem(const uint8_t* p, uint32_t dt, int64_t i, double* out) {
|
||||
switch (dt) {
|
||||
case RAD_F32: { float v; std::memcpy(&v, p + i * 4, 4); *out = v; return true; }
|
||||
case RAD_BF16: { uint32_t u = (uint32_t)((uint16_t)(p[i * 2] | (p[i * 2 + 1] << 8))) << 16;
|
||||
float v; std::memcpy(&v, &u, 4); *out = v; return true; }
|
||||
case RAD_F16: { uint16_t h = (uint16_t)(p[i * 2] | (p[i * 2 + 1] << 8));
|
||||
const uint32_t s = (uint32_t)(h & 0x8000u) << 16;
|
||||
const int e = (h >> 10) & 0x1F;
|
||||
const uint32_t m = h & 0x3FFu;
|
||||
uint32_t u;
|
||||
if (e == 0) u = s | (m ? ((uint32_t)(127 - 15 + 1) << 23) | (m << 13) : 0u);
|
||||
else if (e == 31) u = s | 0x7F800000u | (m << 13);
|
||||
else u = s | ((uint32_t)(e - 15 + 127) << 23) | (m << 13);
|
||||
float v; std::memcpy(&v, &u, 4); *out = v; return true; }
|
||||
case RAD_F8E4M3: *out = f8e4m3_to_f32(p[i]); return true;
|
||||
case RAD_I8: *out = (double)(int8_t)p[i]; return true;
|
||||
case RAD_U8:
|
||||
case RAD_BOOL: *out = (double)p[i]; return true;
|
||||
case RAD_I16: { int16_t v; std::memcpy(&v, p + i * 2, 2); *out = v; return true; }
|
||||
case RAD_I32: { int32_t v; std::memcpy(&v, p + i * 4, 4); *out = v; return true; }
|
||||
case RAD_U32: { uint32_t v; std::memcpy(&v, p + i * 4, 4); *out = v; return true; }
|
||||
case RAD_I64: { int64_t v; std::memcpy(&v, p + i * 8, 8); *out = (double)v; return true; }
|
||||
default: return false;
|
||||
}
|
||||
}
|
||||
|
||||
double row_at(const uint8_t* p, uint32_t dt, int64_t base, int64_t k, int64_t n) {
|
||||
double v = 0;
|
||||
if (base + k < n) elem(p, dt, base + k, &v);
|
||||
return v;
|
||||
}
|
||||
|
||||
std::string 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]);
|
||||
s += "]/[";
|
||||
for (uint32_t d = 0; d < t->rank; ++d)
|
||||
s += fmt("%s%lld", d ? "," : "", (long long)t->stride[d]);
|
||||
return s + "]";
|
||||
}
|
||||
|
||||
} /* namespace */
|
||||
|
||||
/* ------------------------------------------------------------------ open / close */
|
||||
void Ctx::oracle_open() {
|
||||
/* REPEAT MODE IS THE SAME MACHINERY WITH THE SECOND SIDE SWAPPED, so it shares the arming,
|
||||
* the op filter and the snapshot and differs only in what it runs and how it compares. Named
|
||||
* separately because the two answer different questions: the oracle asks whether a kernel is
|
||||
* RIGHT, this asks whether it is a FUNCTION. */
|
||||
const char* spec = std::getenv("RADIANCE_OP_REPEAT");
|
||||
const bool rep = spec && *spec;
|
||||
if (!rep) spec = std::getenv("RADIANCE_OP_ORACLE");
|
||||
if (!spec || !*spec) return;
|
||||
|
||||
oracle_ = new OracleState();
|
||||
oracle_->repeat = rep;
|
||||
for (const char* s = spec; *s; ) {
|
||||
const char* e = s;
|
||||
while (*e && *e != ',') ++e;
|
||||
if (e > s) oracle_->want.emplace_back(s, (size_t)(e - s));
|
||||
s = *e ? e + 1 : e;
|
||||
}
|
||||
auto geti = [](const char* k, int64_t d) {
|
||||
const char* v = std::getenv(k);
|
||||
return (v && *v) ? (int64_t)std::strtoll(v, nullptr, 10) : d;
|
||||
};
|
||||
oracle_->budget = geti(rep ? "RADIANCE_OP_REPEAT_MAX" : "RADIANCE_OP_ORACLE_MAX", rep ? 1000000 : 32);
|
||||
oracle_->maxbytes = geti("RADIANCE_OP_REPEAT_MAXBYTES", 8 << 20);
|
||||
oracle_->maxopd = geti("RADIANCE_OP_ORACLE_MAXBYTES", 4LL << 30);
|
||||
oracle_->from = geti(rep ? "RADIANCE_OP_REPEAT_FROM" : "RADIANCE_OP_ORACLE_FROM", 0);
|
||||
oracle_->to = geti(rep ? "RADIANCE_OP_REPEAT_TO" : "RADIANCE_OP_ORACLE_TO", INT64_MAX);
|
||||
if (const char* t = std::getenv("RADIANCE_OP_ORACLE_TOL")) oracle_->tol = std::strtod(t, nullptr);
|
||||
|
||||
if (oracle_->repeat) {
|
||||
RAD_WARN("op REPEAT armed for {%s}: issues [%lld,%lld], at most %lld checks, operands up "
|
||||
"to %lld bytes. Every matching issue runs its DEVICE kernel TWICE on the same "
|
||||
"bytes and byte-compares. A difference is a kernel that is not a function of its "
|
||||
"inputs. This run is not a measurement of anything.",
|
||||
spec, (long long)oracle_->from, (long long)oracle_->to,
|
||||
(long long)oracle_->budget, (long long)oracle_->maxbytes);
|
||||
return;
|
||||
}
|
||||
RAD_WARN("op oracle ARMED for {%s}: issues [%lld,%lld], at most %lld checks, tolerance %.3g, "
|
||||
"operands up to %lld MiB. Every matching issue copies all its operands to the host "
|
||||
"twice and runs the host kernel beside the device one -- this run is not a "
|
||||
"measurement of anything.",
|
||||
spec, (long long)oracle_->from, (long long)oracle_->to,
|
||||
(long long)oracle_->budget, oracle_->tol, (long long)(oracle_->maxopd >> 20));
|
||||
}
|
||||
|
||||
void Ctx::oracle_close() {
|
||||
if (!oracle_) return;
|
||||
if (oracle_->repeat)
|
||||
RAD_WARN("op REPEAT: %lld issue(s) run twice, %lld of them ANSWERED DIFFERENTLY; %lld "
|
||||
"more were NOT JUDGED because an operand was over the copy cap (raise "
|
||||
"RADIANCE_OP_REPEAT_MAXBYTES to cover those)",
|
||||
(long long)oracle_->checked, (long long)oracle_->differed,
|
||||
(long long)oracle_->unchecked);
|
||||
else
|
||||
RAD_WARN("op oracle: %lld op(s) checked, %lld skipped for want of a host kernel",
|
||||
(long long)oracle_->checked, (long long)oracle_->skipped_nohost);
|
||||
delete oracle_;
|
||||
oracle_ = nullptr;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ the check */
|
||||
bool Ctx::oracle_arm(rad_op h) const {
|
||||
OracleState& o = *oracle_;
|
||||
if (o.budget <= 0) return false;
|
||||
if (n_issues_ < o.from || n_issues_ > o.to) return false;
|
||||
const std::string& name = plans_[h].info->op;
|
||||
for (const std::string& w : o.want)
|
||||
if (w == "*" || w == name) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ sizing the snapshot
|
||||
*
|
||||
* WHAT IS BEING SIZED IS NOT ALWAYS WHAT THE OPERAND POINTS AT, and a routed mixture is where the
|
||||
* difference is total. A grouped GEMM's weight operand is a TABLE (Ctx::WeightTable): after
|
||||
* placement a layer's experts are in different places, so the operand handed to the kernel is a
|
||||
* device array of POINTERS with a zero leading stride, and `base + e*stride` describes only the
|
||||
* all-in-VRAM case, which stops being true the moment anything is offloaded.
|
||||
*
|
||||
* Read as a plane that operand is n*8 bytes pretending to be N*K of weight. Copying it as one
|
||||
* reads far past the pointer array, and the host kernel then dereferences DEVICE pointers -- so
|
||||
* the largest weight in the model would be the one the instrument cannot be pointed at without
|
||||
* reading out of bounds. What it gets instead is the STACKED form: every entry copied into one
|
||||
* contiguous host buffer behind a non-zero leading stride, which is the other reading libref's
|
||||
* expert_entry() already accepts and the one a fixture uses.
|
||||
*
|
||||
* A PLUGIN-PRIVATE DTYPE HAS NO BYTE COUNT IN THE CORE, by design -- a 4-bit expert plane is two
|
||||
* elements to a byte and the core deliberately knows nothing about the packing (spec 4.2). The
|
||||
* container does: the layout pass wrote the resolved kernel's own answer into WeightInfo, so an
|
||||
* operand the core cannot size is sized from the weight it is bound to, and only an operand that
|
||||
* is neither sizeable nor a weight is declined. */
|
||||
void Ctx::oracle_size(rad_op h, int n_opd) {
|
||||
OracleState& o = *oracle_;
|
||||
const OpInfo& oi = *plans_[h].info;
|
||||
|
||||
/* The stored byte count of the weight at each operand position, from the layout pass. Every
|
||||
* entry of a table maps to one position and they are proven identical at first issue, so the
|
||||
* last writer and the first agree. */
|
||||
int64_t wb[MAX_OPERANDS] = {0};
|
||||
int wlaid[MAX_OPERANDS] = {0};
|
||||
if (program_)
|
||||
for (size_t j = 0; j < oi.weights.size() && j < oi.weight_opd.size(); ++j) {
|
||||
const rad_weight wh = oi.weights[j];
|
||||
const int k = (int)oi.weight_opd[j];
|
||||
if (!wh || (size_t)wh >= program_->weights.size()) continue;
|
||||
if (k < 0 || k >= n_opd) continue;
|
||||
wb[k] = program_->weights[(size_t)wh].stored_bytes;
|
||||
wlaid[k] = program_->weights[(size_t)wh].layout_tag.empty() ? 0 : 1;
|
||||
}
|
||||
|
||||
for (int i = 0; i < n_opd; ++i) {
|
||||
const RadTensor& t = tbuf_[i];
|
||||
/* A ZERO LEADING STRIDE IS THE MARKER. resolve_weight_table() prepends the expert axis
|
||||
* that way precisely to say "this axis is not addressable by arithmetic". */
|
||||
o.tab[i] = (t.data && t.rank >= 2 && t.stride[0] == 0 && t.shape[0] > 0) ? t.shape[0] : 0;
|
||||
const int64_t es = span_of(&t); /* one entry, or the whole plane when not a table */
|
||||
o.span[i] = o.tab[i] ? es * o.tab[i] : es;
|
||||
o.ent[i] = es > 0 ? rad_dtype_bytes(t.dtype, es) : 0;
|
||||
if (o.ent[i] <= 0 && es > 0) o.ent[i] = wb[i];
|
||||
/* A RE-LAID WEIGHT IS AS BIG AS THE CONTAINER SAYS, NOT AS BIG AS ITS DECLARED PLANE, and
|
||||
* the two differ even where the dtype has a byte count. The fp8 lm_head pads each stored
|
||||
* row to a 16-byte boundary and carries that row's block scales inside it, so the plane
|
||||
* is 2608 bytes a row where n_embd * 1 says 2560 -- and the inverse, which checks the
|
||||
* byte count it is handed against the stride it wrote, refuses a snapshot sized from the
|
||||
* declared plane. The layout pass records the resolved kernel's own answer for exactly
|
||||
* this; where a weight is stored re-laid, it wins. */
|
||||
if (wlaid[i] && wb[i] > 0) o.ent[i] = wb[i];
|
||||
o.ht[i] = t;
|
||||
/* The stacked reading: the expert axis becomes addressable and its stride is one entry. */
|
||||
if (o.tab[i]) o.ht[i].stride[0] = es;
|
||||
|
||||
/* ALIASED OPERANDS SHARE ONE HOST BUFFER. A residual add is issued {x, h} -> {x}: two
|
||||
* of its three operands are the same device bytes, and giving each its own copy makes
|
||||
* the host kernel write into a buffer the device kernel's own read-modify-write also
|
||||
* wrote -- which reports the op as a mismatch of exactly the size of the addend, every
|
||||
* time, on an op that is correct. The first operand with a given pointer owns the
|
||||
* copy and the rest point into it, which is what the device sees. */
|
||||
o.alias[i] = i;
|
||||
for (int j = 0; j < i; ++j)
|
||||
if (t.data && tbuf_[j].data == t.data) { o.alias[i] = o.alias[j]; break; }
|
||||
}
|
||||
}
|
||||
|
||||
/* Bytes the snapshot of operand `i` occupies, which for a table is every entry of it. */
|
||||
int64_t Ctx::oracle_opd_bytes(int i) const {
|
||||
const OracleState& o = *oracle_;
|
||||
if (o.span[i] <= 0 || o.ent[i] <= 0) return 0;
|
||||
return o.tab[i] ? o.ent[i] * o.tab[i] : o.ent[i];
|
||||
}
|
||||
|
||||
void Ctx::oracle_snap(int n_opd, bool post) {
|
||||
OracleState& o = *oracle_;
|
||||
std::vector<std::vector<uint8_t>>& into = post ? o.post : o.pre;
|
||||
into.resize(MAX_OPERANDS);
|
||||
std::vector<void*> ptr;
|
||||
/* THE SECOND LANE IS DRAINED FIRST, AND THE ORDER IS THE WHOLE POINT. An architecture may
|
||||
* issue on lane 1 -- the MoE shared expert does -- and the copies below go on `stream_`, which
|
||||
* is not ordered against it. Draining lane 1 AFTER them leaves the copy racing the kernel
|
||||
* that writes what it is copying, which is not a fix: the copy has already returned its bytes.
|
||||
*
|
||||
* Both snapshots need it and for different reasons. In `post` the race reads an OUTPUT before
|
||||
* its kernel wrote it, and a correct kernel reports as having produced nothing. In `pre` it
|
||||
* reads an INPUT before its producer wrote it, and then the two sides are not even given the
|
||||
* same problem -- the host kernel gets a half-written operand, the device kernel gets the
|
||||
* whole one, and the operand the oracle prints is an INPUT that disagrees with itself. The
|
||||
* oracle already costs a host synchronisation per issue; one more stream is free. */
|
||||
if (lane1_) rad_stream_sync(lane1_);
|
||||
for (int i = 0; i < n_opd; ++i) {
|
||||
const RadTensor& t = tbuf_[i];
|
||||
if (o.alias[i] != i) continue;
|
||||
const int64_t bytes = oracle_opd_bytes(i);
|
||||
/* THE CAP IS A REPEAT-MODE THING ONLY. The oracle has to see every operand or its host
|
||||
* kernel has nothing to read; the repeat re-launches the device kernel on the operands
|
||||
* still in place, so an operand it declines to copy is simply one it cannot restore and
|
||||
* will not compare -- which is right for a weight and would be wrong for an output. */
|
||||
if (!post) o.skip[i] = o.repeat && bytes > o.maxbytes;
|
||||
if (o.skip[i]) { into[(size_t)i].clear(); continue; }
|
||||
/* A SLOT KEEPS THE HIGH-WATER CAPACITY OF EVERY OPERAND THAT EVER LANDED IN IT, and on a
|
||||
* large model that is not a rounding error: operand 2 of one op is a 170 MiB fused weight
|
||||
* and operand 2 of the next is a few kilobytes, so thirty-two slots across `pre`, `post`
|
||||
* and `logical` hold the sum of the largest thing each has ever seen -- on a container
|
||||
* of well over a hundred GiB, enough for the host OOM killer to end a sweep part way
|
||||
* through. Shrinking when the slot is grossly oversized bounds the footprint by the
|
||||
* largest SINGLE issue instead of by the sum over the graph; the reallocation costs
|
||||
* nothing against a synchronised copy. */
|
||||
into[(size_t)i].assign((size_t)bytes, 0);
|
||||
if (into[(size_t)i].capacity() > (size_t)bytes * 2 + (1u << 20))
|
||||
into[(size_t)i].shrink_to_fit();
|
||||
if (bytes <= 0) continue;
|
||||
if (!o.tab[i]) { rad_memcpy_async(into[(size_t)i].data(), t.data, bytes, stream_); continue; }
|
||||
/* The entries are wherever placement put them, so their pointers come back first and the
|
||||
* copies are issued against those. An entry may be device- or host-resident and the
|
||||
* direction is inferred from the pointer, which is what makes one call serve both. */
|
||||
ptr.assign((size_t)o.tab[i], nullptr);
|
||||
rad_memcpy_async(ptr.data(), t.data, o.tab[i] * (int64_t)sizeof(void*), stream_);
|
||||
rad_stream_sync(stream_);
|
||||
for (int64_t e = 0; e < o.tab[i]; ++e)
|
||||
if (ptr[(size_t)e])
|
||||
rad_memcpy_async(into[(size_t)i].data() + e * o.ent[i], ptr[(size_t)e],
|
||||
o.ent[i], stream_);
|
||||
}
|
||||
rad_stream_sync(stream_);
|
||||
if (!post)
|
||||
for (int i = 0; i < n_opd; ++i)
|
||||
o.ht[i].data = o.span[i] > 0 ? (void*)o.pre[(size_t)o.alias[i]].data() : nullptr;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ the stored layout
|
||||
*
|
||||
* THE HOST KERNEL READS A WEIGHT CANONICALLY AND THE ENGINE DOES NOT HOLD IT THAT WAY.
|
||||
*
|
||||
* A container holds each weight's encoding as canonical planes, and the kernel that reads it may
|
||||
* rearrange them at load (spec §4.3): libr4d's fp8a8 GEMMs claim WMMA FRAGMENT ORDER, the same N*K
|
||||
* bytes permuted so a wave's sixteen rows arrive in lane order off one coalesced load. libref
|
||||
* declares no layout for anything and reads [N, K] row-major. Handing it the operand pointer
|
||||
* unchanged therefore compares two readings of one permuted plane, which are uncorrelated tensors
|
||||
* -- a relative error around 1.35 on every operand from element zero, on a kernel that is not
|
||||
* wrong.
|
||||
*
|
||||
* So the stored bytes go back through the device row's own inverse to the canonical planes, and
|
||||
* from those to the form the HOST row reads: a single plane converted element by element -- an
|
||||
* expert's int4 codes as the integers the reference multiplies -- or a whole encoding decoded by
|
||||
* the core's decoder, which is what a reference reading an lm_head of codes and scales together
|
||||
* wants. Both sides then see the same values, expressed the way each of them reads.
|
||||
*
|
||||
* NO INVERSE MEANS NO CHECK, and it is a named skip rather than a tolerance: a comparison that
|
||||
* cannot be made honestly is worse than one not made, because a page of false failures drowns the
|
||||
* true ones. Returns false in that case, and the issue is not counted as checked.
|
||||
*
|
||||
* WHICH LOGICAL FORM, AND WHO SAYS SO. `opd_shape` describes the operand the kernel is HANDED --
|
||||
* for a relayed weight that is the stored form, which is the thing being inverted and cannot also
|
||||
* be the answer. The form wanted here is the one the READER reads, so the host row is asked first
|
||||
* and the device row is the fallback. libref publishes a shape for the whole conventional
|
||||
* vocabulary, so an op inside docs/OPS.md is describable even when the kernel under test
|
||||
* describes nothing.
|
||||
*
|
||||
* The extents come from the parameters AT THIS ISSUE, not from the weight's declaration: a
|
||||
* tensor-parallel shard's op carries the per-rank N and K. */
|
||||
bool Ctx::oracle_unrelayout(rad_op h, const IssuePlan& hip, const IssuePlan& dip, int64_t seq,
|
||||
int n_opd) {
|
||||
OracleState& o = *oracle_;
|
||||
const OpInfo& oi = *plans_[h].info;
|
||||
for (int i = 0; i < n_opd; ++i) o.unlaid[i] = 0;
|
||||
|
||||
const RadKernelInfo* ki = dip.row ? dip.row->info : nullptr;
|
||||
if (!ki || !ki->layout || !program_) return true; /* every operand is read as it is */
|
||||
const RadKernelInfo* hk = hip.row ? hip.row->info : nullptr;
|
||||
const RadShapeFn shape = hk && hk->opd_shape ? hk->opd_shape : ki->opd_shape;
|
||||
|
||||
o.logical.resize(MAX_OPERANDS);
|
||||
for (size_t j = 0; j < oi.weights.size() && j < oi.weight_opd.size(); ++j) {
|
||||
const rad_weight wh = oi.weights[j];
|
||||
if (!wh || (size_t)wh >= program_->weights.size()) continue;
|
||||
const WeightInfo& w = program_->weights[(size_t)wh];
|
||||
if (w.layout_tag.empty()) continue; /* stored as it is */
|
||||
const int i = oi.weight_opd[j];
|
||||
if (i < 0 || i >= n_opd || o.span[i] <= 0 || o.unlaid[i]) continue;
|
||||
|
||||
if (!ki->unrelayout || !shape) {
|
||||
RAD_WARN("oracle #%lld op '%s': NOT CHECKED. '%s' is stored as %s's '%s', and no %s "
|
||||
"can be had for it -- so the reference would read a permuted plane row-major "
|
||||
"and disagree with a kernel that is right.",
|
||||
(long long)seq, oi.op.c_str(), w.name.c_str(), ki->name,
|
||||
w.layout_tag.c_str(), ki->unrelayout ? "RadShapeFn" : "RadUnrelayoutFn");
|
||||
return false;
|
||||
}
|
||||
RadOpdDesc d{};
|
||||
if (shape(dip.args.p, dip.args.n_p, i, &d) != RAD_OK || d.rank == 0) {
|
||||
RAD_WARN("oracle #%lld op '%s': NOT CHECKED. nothing could describe the logical form "
|
||||
"of '%s' at this geometry, so there is nothing to invert its layout into.",
|
||||
(long long)seq, oi.op.c_str(), w.name.c_str());
|
||||
return false;
|
||||
}
|
||||
RadTensor lg{};
|
||||
lg.dtype = d.dtype;
|
||||
lg.rank = d.rank;
|
||||
int64_t n = 1, acc = 1;
|
||||
for (uint32_t k = 0; k < d.rank && k < RAD_MAX_RANK; ++k) { lg.shape[k] = d.shape[k]; n *= d.shape[k]; }
|
||||
for (int k = (int)d.rank - 1; k >= 0; --k) { lg.stride[k] = acc; acc *= lg.shape[k]; }
|
||||
const int64_t bytes = rad_dtype_bytes(lg.dtype, n);
|
||||
if (bytes <= 0) return false;
|
||||
/* A TABLE'S DESCRIPTION MUST BE THE STACKED PLANE. The two agree on every other axis, so
|
||||
* a disagreement here is a description that answered for one expert where the operand
|
||||
* carries the layer's whole set -- and inverting into it would write past the buffer. */
|
||||
if (o.tab[i] && (d.rank < 2 || lg.shape[0] != o.tab[i])) {
|
||||
RAD_WARN("oracle #%lld op '%s': NOT CHECKED. '%s' is a table of %lld experts and the "
|
||||
"logical form offered for it leads with %lld, so the two are not the same "
|
||||
"tensor.", (long long)seq, oi.op.c_str(), w.name.c_str(),
|
||||
(long long)o.tab[i], (long long)(d.rank ? lg.shape[0] : 0));
|
||||
return false;
|
||||
}
|
||||
o.logical[(size_t)i].assign((size_t)bytes, 0);
|
||||
if (o.logical[(size_t)i].capacity() > (size_t)bytes * 2 + (1u << 20))
|
||||
o.logical[(size_t)i].shrink_to_fit();
|
||||
lg.data = o.logical[(size_t)i].data();
|
||||
|
||||
/* ONE CALL PER ENTRY FOR A TABLE. The hook answers for a weight, and an expert IS the
|
||||
* weight -- the table is the engine's way of saying where the experts ended up, not a
|
||||
* shape the plugin ever agreed to. So each entry's stored bytes are inverted on their own
|
||||
* and land at their own offset in the stacked tensor. */
|
||||
const std::vector<uint8_t>& src = o.pre[(size_t)o.alias[i]];
|
||||
const int64_t n_ent = o.tab[i] ? o.tab[i] : 1;
|
||||
const int64_t ent_bytes = o.tab[i] ? o.ent[i] : (int64_t)src.size();
|
||||
const int64_t ent_n = n / n_ent;
|
||||
std::vector<std::vector<uint8_t>> pl((size_t)w.n_sel);
|
||||
RadTensor pt[RAD_ENC_MAX_PLANES];
|
||||
weight_planes(w, pt);
|
||||
int rc = RAD_OK;
|
||||
std::string why;
|
||||
for (int64_t e = 0; e < n_ent && rc >= 0; ++e) {
|
||||
for (int k = 0; k < w.n_sel; ++k) {
|
||||
pl[(size_t)k].assign((size_t)(w.sel_rows[k] *
|
||||
rad_enc_row_bytes(pt[k].dtype, w.sel_cols[k])), 0);
|
||||
pt[k].data = pl[(size_t)k].data();
|
||||
}
|
||||
rc = ki->unrelayout(dip.args.p, dip.args.n_p, i, &w.enc, w.sel,
|
||||
src.data() + e * ent_bytes, ent_bytes, pt, w.n_sel);
|
||||
if (rc < 0) break;
|
||||
uint8_t* dst = (uint8_t*)lg.data + rad_dtype_bytes(lg.dtype, ent_n * e);
|
||||
const void* pd[RAD_ENC_MAX_PLANES] = {};
|
||||
for (int k = 0; k < w.n_sel; ++k) pd[k] = pl[(size_t)k].data();
|
||||
rc = enc_selection_logical(w.enc, w.sel, w.n_sel, w.sel_rows, w.sel_cols, pd,
|
||||
lg.dtype, ent_n, dst, &why);
|
||||
}
|
||||
if (rc < 0) {
|
||||
/* THE TWO NUMBERS IT DISAGREED ABOUT. An inverse refuses on a shape far more often
|
||||
* than on anything else, and "shape this kernel does not serve" without them says
|
||||
* only that one of the two sides is wrong -- which is the whole question. */
|
||||
RAD_WARN("oracle #%lld op '%s': NOT CHECKED. %s could not invert its own layout for "
|
||||
"'%s' (%s%s%s): %lld stored bytes into %lld %s elements, so the reference has "
|
||||
"nothing it can read.",
|
||||
(long long)seq, oi.op.c_str(), ki->name, w.name.c_str(), rad_strerror(rc),
|
||||
why.empty() ? "" : ": ", why.c_str(), (long long)ent_bytes, (long long)ent_n,
|
||||
rad_dtype_name(lg.dtype));
|
||||
return false;
|
||||
}
|
||||
o.ht[i] = lg;
|
||||
o.unlaid[i] = 1;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
void Ctx::oracle_run(rad_op h, const IssuePlan& hip, int64_t seq, int n_opd) {
|
||||
OracleState& o = *oracle_;
|
||||
const OpInfo& oi = *plans_[h].info;
|
||||
|
||||
/* The host kernel writes into the PRE copy: same shapes, same strides, same parameters, and
|
||||
* pointers that are the only thing about the call that differs from the device's. */
|
||||
RadArgs a = hip.args;
|
||||
a.t = o.ht;
|
||||
a.n_t = n_opd;
|
||||
o.scratch.assign((size_t)(a.scratch_bytes > 0 ? a.scratch_bytes : 0), 0);
|
||||
a.scratch = o.scratch.empty() ? nullptr : o.scratch.data();
|
||||
|
||||
const int rc = hip.launch(&a, nullptr);
|
||||
if (rc < 0) {
|
||||
/* RAD_E_UNSUPPORTED IS NOT A FINDING. It is the reference saying "not this contract" --
|
||||
* an op whose parameters name a form it does not implement, which `gdn_recurrent_update`'s
|
||||
* two state layouts are the live example of. Reported as the coverage gap it is, because
|
||||
* the alternative is a reader treating a declined comparison as a passed one. Any OTHER
|
||||
* code is the reference refusing shapes it claims to serve, and that is about the engine's
|
||||
* operands rather than about the oracle. */
|
||||
if (rc == RAD_E_UNSUPPORTED)
|
||||
RAD_WARN("oracle #%lld op '%s': NOT CHECKED. the host kernel (%s) does not implement "
|
||||
"what these parameters ask for {%s}, so there is no comparison to make.",
|
||||
(long long)seq, oi.op.c_str(),
|
||||
hip.row && hip.row->info ? hip.row->info->name : "?", oi.base.str().c_str());
|
||||
else {
|
||||
/* AND THE SHAPES IT REFUSED, since that is what this line says the finding is about.
|
||||
* An error name on its own leaves no way to tell an engine operand the reference
|
||||
* genuinely cannot serve from a geometry it was handed wrongly, which is the whole
|
||||
* thing a reader comes to this line for. */
|
||||
std::string sh;
|
||||
for (int i = 0; i < n_opd; ++i)
|
||||
if (o.ht[i].data)
|
||||
sh += fmt("%s%d:%s", sh.empty() ? "" : " ", i, shape_str(&o.ht[i]).c_str());
|
||||
RAD_WARN("oracle #%lld op '%s': the host kernel (%s) REFUSED the engine's own operands "
|
||||
"with %s. That is a finding about the shapes, not about the oracle: {%s} %s",
|
||||
(long long)seq, oi.op.c_str(),
|
||||
hip.row && hip.row->info ? hip.row->info->name : "?", rad_strerror(rc),
|
||||
oi.base.str().c_str(), sh.c_str());
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
/* Per operand: the largest disagreement, scaled by the device side's own magnitude. A pure
|
||||
* input comes out at zero because neither side touched it, which is the check that the
|
||||
* snapshot itself is sound. */
|
||||
std::string line;
|
||||
bool bad = false;
|
||||
for (int i = 0; i < n_opd; ++i) {
|
||||
if (o.span[i] <= 0) continue;
|
||||
/* AN INVERTED WEIGHT IS NOT COMPARED. `pre` holds the stored plane and `post` the device's
|
||||
* copy of the same read-only bytes, so there is nothing here the two sides could disagree
|
||||
* about -- what the host kernel actually read is the separate logical buffer, in a form
|
||||
* neither of those two holds. Printed rather than dropped, so that a reader can see the
|
||||
* operand was handled and know which shape the host side saw. */
|
||||
if (o.unlaid[i]) {
|
||||
line += fmt(" opd%d~ %-6s %-22s read through %s's own inverse; not compared\n",
|
||||
i, rad_dtype_name(o.ht[i].dtype), shape_str(&o.ht[i]).c_str(),
|
||||
ip_kernel_name(h) ? ip_kernel_name(h) : "?");
|
||||
continue;
|
||||
}
|
||||
const uint32_t dt = o.ht[i].dtype;
|
||||
const uint8_t* hp = o.pre[(size_t)o.alias[i]].data();
|
||||
const uint8_t* dp = o.post[(size_t)o.alias[i]].data();
|
||||
const int64_t n = o.span[i];
|
||||
|
||||
double worst = 0, scale = 0, hv = 0, dv = 0, sum = 0, hsum = 0;
|
||||
int64_t at = -1, nbad = 0;
|
||||
int64_t badix[4] = { -1, -1, -1, -1 };
|
||||
double x = 0, y = 0;
|
||||
if (!elem(hp, dt, 0, &x)) {
|
||||
const bool same = std::memcmp(hp, dp, o.pre[(size_t)o.alias[i]].size()) == 0;
|
||||
line += fmt(" opd%d %-6s %s %s\n", i, rad_dtype_name(dt),
|
||||
shape_str(&o.ht[i]).c_str(), same ? "bytes equal" : "BYTES DIFFER");
|
||||
bad = bad || !same;
|
||||
continue;
|
||||
}
|
||||
/* ONE CODE STEP IN AN fp8 PLANE IS THE FORMAT, NOT A DISAGREEMENT.
|
||||
*
|
||||
* E4M3 has three mantissa bits, so the gap between neighbouring codes is between 1/16 and
|
||||
* 1/8 of the value -- four to eight times the tolerance a comparison of continuous values
|
||||
* is held to. Any difference at all in the bf16 the quantiser reads, down to a single ulp
|
||||
* from a different summation order, moves an element that sits near a rounding boundary
|
||||
* onto the next code, and the reported relative error is then a whole quantum on a kernel
|
||||
* that is right -- typically a handful of elements in ten thousand, one code apart (host
|
||||
* 176, device 192), on an fp8 output plane such as rmsnorm_quant_fp8's or hc_read's.
|
||||
*
|
||||
* So the two sides are compared in CODE space for these dtypes, where adjacent is a
|
||||
* question with an exact answer: same sign bit, magnitude codes one apart. Those are
|
||||
* COUNTED and reported and do not set the verdict; anything further apart is a real
|
||||
* disagreement and is measured like any other. A kernel whose arithmetic is actually
|
||||
* wrong does not land one code away on six elements in ten thousand. */
|
||||
const bool fp8 = (dt == RAD_F8E4M3 || dt == RAD_F8E5M2);
|
||||
int64_t ulp1 = 0;
|
||||
for (int64_t k = 0; k < n; ++k) {
|
||||
if (!elem(hp, dt, k, &x) || !elem(dp, dt, k, &y)) break;
|
||||
scale = std::max(scale, std::fabs(y));
|
||||
if (std::isfinite(y)) sum += y;
|
||||
if (std::isfinite(x)) hsum += x;
|
||||
if (fp8 && hp[k] != dp[k]) {
|
||||
const int da = (int)(hp[k] & 0x7Fu) - (int)(dp[k] & 0x7Fu);
|
||||
if (((hp[k] ^ dp[k]) & 0x80u) == 0 && (da == 1 || da == -1)) { ++ulp1; continue; }
|
||||
}
|
||||
const double d = std::fabs(x - y);
|
||||
if (std::isnan(x) != std::isnan(y) || d > worst) {
|
||||
worst = std::isnan(x) != std::isnan(y) ? INFINITY : d;
|
||||
at = k; hv = x; dv = y;
|
||||
}
|
||||
/* The individually bad elements, not just the worst: WHERE they sit says whether a
|
||||
* whole operand is wrong or one lane of it is, and those are different bugs. */
|
||||
if (d > 1e-30 && (std::isnan(x) != std::isnan(y) || d > o.tol * std::fabs(x))) {
|
||||
if (nbad < 4) badix[nbad] = k;
|
||||
++nbad;
|
||||
}
|
||||
}
|
||||
const double rel = worst / (scale > 0 ? scale : 1.0);
|
||||
if (rel > o.tol) bad = true;
|
||||
double f[4] = {0, 0, 0, 0};
|
||||
for (int64_t k = 0; k < 4 && k < n; ++k) elem(dp, dt, k, &f[k]);
|
||||
/* PER-ROW SUMS, up to three rows. A whole-tensor sum is a weak fingerprint and the first
|
||||
* four values only ever describe row 0, so between them they can say "token 0 is exactly
|
||||
* right and the total is wrong" -- a statement about the OTHER tokens that neither column
|
||||
* can localise. A row here is dim 0, which is the token for every activation the graph
|
||||
* carries. */
|
||||
std::string rows;
|
||||
if (o.ht[i].rank >= 2 && o.ht[i].shape[0] > 1 && o.ht[i].stride[0] > 0) {
|
||||
const int64_t nr = o.ht[i].shape[0] < 3 ? o.ht[i].shape[0] : 3;
|
||||
const int64_t w = o.ht[i].stride[0];
|
||||
for (int64_t r = 0; r < nr; ++r) {
|
||||
double rs = 0;
|
||||
for (int64_t k = r * w; k < (r + 1) * w && k < n; ++k) {
|
||||
double y = 0;
|
||||
if (!elem(dp, dt, k, &y)) break;
|
||||
if (std::isfinite(y)) rs += y;
|
||||
}
|
||||
double t[3] = {0, 0, 0};
|
||||
const int64_t last = (r + 1) * w < n ? (r + 1) * w : n;
|
||||
for (int j = 0; j < 3; ++j)
|
||||
if (last - 3 + j >= r * w) elem(dp, dt, last - 3 + j, &t[j]);
|
||||
/* HEAD AND TAIL OF EVERY ROW, which is exactly what llama.cpp's eval-callback
|
||||
* prints -- three at each end and an ellipsis. A sum agrees between two vectors
|
||||
* that are not the same vector, which is the shape these mismatches take. */
|
||||
rows += fmt("\n row%lld sum %.6g head [%.5g %.5g %.5g] tail [%.5g %.5g %.5g]",
|
||||
(long long)r, rs,
|
||||
row_at(dp, dt, r * w, 0, n), row_at(dp, dt, r * w, 1, n),
|
||||
row_at(dp, dt, r * w, 2, n), t[0], t[1], t[2]);
|
||||
}
|
||||
}
|
||||
/* WHERE the worst element is, and what each side said there. Without it a mismatch is a
|
||||
* number: "rel 2 on a gate cumsum" cannot distinguish a whole tensor that is wrong from
|
||||
* one padding lane that is, and those want different fixes. The index is flat over the
|
||||
* operand, which is the same order the row sums above walk. */
|
||||
std::string at_s;
|
||||
if (at >= 0 && rel > o.tol) {
|
||||
at_s = fmt("\n worst at [%lld]: host %.9g device %.9g (diff %.4g)"
|
||||
"\n %lld of %lld element(s) differ; host sum %.6g vs device sum %.6g"
|
||||
"\n first bad at",
|
||||
(long long)at, hv, dv, worst, (long long)nbad, (long long)n, hsum, sum);
|
||||
for (int b = 0; b < 4 && badix[b] >= 0; ++b) at_s += fmt(" %lld", (long long)badix[b]);
|
||||
}
|
||||
/* The one-code-step count is PRINTED whether or not anything else disagreed. Silently
|
||||
* absorbing them would make the operand look byte-equal, and a reader comparing two runs
|
||||
* of the same build wants to see that six elements moved. */
|
||||
const std::string u1 = ulp1 ? fmt(" %lld at one fp8 code step", (long long)ulp1)
|
||||
: std::string();
|
||||
line += fmt(" opd%d %-6s %-22s n=%-9lld amax %.4g sum %.6g [%.5g %.5g %.5g %.5g]%s"
|
||||
" rel %.4g%s%s%s\n",
|
||||
i, rad_dtype_name(dt), shape_str(&o.ht[i]).c_str(), (long long)n, scale,
|
||||
sum, f[0], f[1], f[2], f[3], rows.c_str(), rel, u1.c_str(),
|
||||
rel > o.tol ? " <-- MISMATCH" : "", at_s.c_str());
|
||||
}
|
||||
|
||||
const char* dk = ip_kernel_name(h);
|
||||
RAD_WARN("oracle #%lld op '%s' %s [device %s vs host %s] {%s}\n%s",
|
||||
(long long)seq, oi.op.c_str(), bad ? "MISMATCH" : "agrees",
|
||||
dk, hip.row && hip.row->info ? hip.row->info->name : "?",
|
||||
oi.base.str().c_str(), line.c_str());
|
||||
}
|
||||
|
||||
/* The device kernel's name for the report, looked up the same way abort_step does. */
|
||||
const char* Ctx::ip_kernel_name(rad_op h) const {
|
||||
const OpPlan& p = plans_[h];
|
||||
const int dom = (int)op_domain_[h].load(std::memory_order_relaxed);
|
||||
for (int b = 0; b < p.n_bands; ++b) {
|
||||
const IssuePlan& ip = issue_table_[(size_t)p.plan_off + (size_t)b * RAD_N_DOMAINS + dom];
|
||||
if (ip.row && ip.row->info) return ip.row->info->name;
|
||||
}
|
||||
return "?";
|
||||
}
|
||||
|
||||
/* The one entry point issue() calls. Returns the host plan to check against, or null. */
|
||||
/* ------------------------------------------------------------------ the repeat check */
|
||||
/* RUN THE DEVICE KERNEL A SECOND TIME ON THE BYTES THE FIRST ONE SAW, AND COMPARE.
|
||||
*
|
||||
* The oracle above asks whether a kernel agrees with libref. This asks a question no two-sided
|
||||
* comparison can: whether the kernel agrees with ITSELF. A kernel with an unordered reduction, a
|
||||
* workgroup that reads what another workgroup is writing, or a workspace it assumed was zeroed is
|
||||
* CORRECT on the run the oracle happens to look at and wrong on the next one, and every
|
||||
* instrument in this tree that runs an op once is blind to it.
|
||||
*
|
||||
* BYTE-EXACT AND NO TOLERANCE, deliberately. "Within 2%" is the right question for an
|
||||
* implementation and the wrong one here: the same kernel on the same bytes has no licence to move
|
||||
* at all, and a difference in the last mantissa bit is the finding, because greedy decoding
|
||||
* amplifies it into a different token a few hundred steps later.
|
||||
*
|
||||
* WHAT IT CANNOT SEE. A race between the two ranks of a tensor-parallel step: both Ctxs walk the
|
||||
* same graph and both re-launch, so a collective still meets itself and does not deadlock, but
|
||||
* what the second launch measures is the pair re-running together rather than either one alone.
|
||||
* And a kernel whose output depends on a buffer this declined to restore -- see the cap. */
|
||||
void Ctx::oracle_repeat(rad_op h, const IssuePlan& dip, int64_t seq, int n_opd) {
|
||||
OracleState& o = *oracle_;
|
||||
|
||||
/* AN OPERAND THIS COULD NOT COPY MAKES THE WHOLE ISSUE UNJUDGEABLE, and saying so is the
|
||||
* difference between an instrument and a rumour. The cap exists for read-only weights, but
|
||||
* nothing here knows that an operand IS a weight -- and a GDN recurrent state is both an input
|
||||
* and an output and is far over the default cap. Left unrestored it hands the second launch a
|
||||
* state the first one already advanced, and every GDN issue in the model then reports as
|
||||
* non-deterministic when what actually happened is that it was asked a different question.
|
||||
* Raise RADIANCE_OP_REPEAT_MAXBYTES to check those ops; do not guess about them. */
|
||||
for (int i = 0; i < n_opd; ++i)
|
||||
if (o.skip[i]) { ++o.unchecked; return; }
|
||||
|
||||
/* The first result, before anything is put back. oracle_snap writes `post`, so it is moved
|
||||
* aside rather than copied: the second launch needs the same destination. */
|
||||
oracle_snap(n_opd, true);
|
||||
std::vector<std::vector<uint8_t>> first;
|
||||
first.swap(o.post);
|
||||
|
||||
/* PUT BACK ONLY WHAT THE KERNEL ACTUALLY CHANGED, and decide that by comparing rather than by
|
||||
* believing the schema. An op issued {x, h} -> {x} has already overwritten one of its own
|
||||
* inputs, so without a restore the second launch is not given the same problem and every
|
||||
* in-place op in the graph reports as non-deterministic.
|
||||
*
|
||||
* Restoring everything SEGFAULTS instead: a small weight is a perfectly ordinary operand under
|
||||
* the size cap, and a weight on Tier::Mapped is the container's read-only mmap. A kernel never
|
||||
* writes an operand it only reads, so "changed" is both the safe test and the cheap one.
|
||||
*
|
||||
* A WEIGHT TABLE IS NEVER RESTORED WHATEVER THE COMPARISON SAYS. Its snapshot is the STACKED
|
||||
* plane behind an array of pointers (oracle_size), so a byte-for-byte write back would put
|
||||
* gigabytes of expert weight over a few kilobytes of pointers. No op writes one, which is
|
||||
* why the comparison alone is enough; if one ever did, a write back would take every weight
|
||||
* in the graph off its address. */
|
||||
bool wrote[MAX_OPERANDS] = {false};
|
||||
for (int i = 0; i < n_opd; ++i) {
|
||||
if (o.alias[i] != i || o.skip[i] || o.span[i] <= 0 || o.tab[i]) continue;
|
||||
const std::vector<uint8_t>& A = o.pre[(size_t)i];
|
||||
const std::vector<uint8_t>& B = first[(size_t)i];
|
||||
if (A.empty() || A.size() != B.size()) continue;
|
||||
if (std::memcmp(A.data(), B.data(), A.size()) == 0) continue;
|
||||
wrote[i] = true;
|
||||
if (tbuf_[i].data) rad_memcpy_async(tbuf_[i].data, A.data(), A.size(), stream_);
|
||||
}
|
||||
rad_stream_sync(stream_);
|
||||
|
||||
/* THE SAME PLAN, THE SAME ARGS, THE SAME STREAM. dip.args.t still points at tbuf_ -- the
|
||||
* device pointers -- because the oracle's rebinding only ever touched its own `ht`. */
|
||||
RadArgs a = dip.args;
|
||||
a.n_t = n_opd;
|
||||
const int rc = dip.launch(&a, cur_stream());
|
||||
if (rc < 0) {
|
||||
RAD_WARN("repeat #%lld op '%s': the second launch was REFUSED with %s, so this issue says "
|
||||
"nothing about determinism", (long long)seq, plans_[h].info->op.c_str(),
|
||||
rad_strerror(rc));
|
||||
return;
|
||||
}
|
||||
oracle_snap(n_opd, true);
|
||||
|
||||
std::string line;
|
||||
for (int i = 0; i < n_opd; ++i) {
|
||||
/* ONLY THE OPERANDS THE KERNEL WROTE. One it merely read is equal by construction, and
|
||||
* saying so for every input on every issue buries the finding. */
|
||||
if (!wrote[i]) continue;
|
||||
const std::vector<uint8_t>& A = first[(size_t)i];
|
||||
const std::vector<uint8_t>& B = o.post[(size_t)i];
|
||||
if (A.size() != B.size() || A.empty()) continue;
|
||||
if (std::memcmp(A.data(), B.data(), A.size()) == 0) continue;
|
||||
|
||||
/* WHICH ELEMENTS AND BY HOW MUCH. One lane apart at the last bit and a whole tensor of
|
||||
* garbage are both "BYTES DIFFER", and they are different bugs: the first is a reduction
|
||||
* order, the second is a read of memory another workgroup owns. */
|
||||
const uint32_t dt = o.ht[i].dtype;
|
||||
const int64_t n = o.span[i];
|
||||
int64_t nbad = 0, at = -1;
|
||||
double worst = 0, av = 0, bv = 0, scale = 0;
|
||||
for (int64_t k = 0; k < n; ++k) {
|
||||
double x = 0, y = 0;
|
||||
if (!elem(A.data(), dt, k, &x) || !elem(B.data(), dt, k, &y)) { nbad = -1; break; }
|
||||
if (x == y) continue;
|
||||
++nbad;
|
||||
const double d = std::fabs(x - y);
|
||||
if (d > worst) { worst = d; at = k; av = x; bv = y; }
|
||||
scale = std::max(scale, std::fabs(y));
|
||||
}
|
||||
if (nbad < 0)
|
||||
line += fmt(" opd%d %-6s %s BYTES DIFFER (dtype not scalar)\n", i,
|
||||
rad_dtype_name(dt), shape_str(&o.ht[i]).c_str());
|
||||
else
|
||||
line += fmt(" opd%d %-6s %s %lld of %lld element(s) differ; worst at [%lld] "
|
||||
"run1 %.9g run2 %.9g (diff %.4g, rel %.3g)\n",
|
||||
i, rad_dtype_name(dt), shape_str(&o.ht[i]).c_str(),
|
||||
(long long)nbad, (long long)n, (long long)at, av, bv, worst,
|
||||
worst / (scale > 0 ? scale : 1.0));
|
||||
}
|
||||
if (line.empty()) return;
|
||||
++o.differed;
|
||||
RAD_ERR("REPEAT #%lld op '%s' (kernel %s) IS NOT A FUNCTION OF ITS INPUTS: two launches on the "
|
||||
"same bytes disagreed.\n%s", (long long)seq, plans_[h].info->op.c_str(),
|
||||
ip_kernel_name(h) ? ip_kernel_name(h) : "?", line.c_str());
|
||||
}
|
||||
|
||||
const IssuePlan* Ctx::oracle_before(rad_op h, int band, int n_opd) {
|
||||
if (!oracle_ || !oracle_arm(h)) return nullptr;
|
||||
oracle_size(h, n_opd);
|
||||
if (oracle_->repeat) {
|
||||
for (int i = 0; i < n_opd; ++i)
|
||||
if (tbuf_[i].data && oracle_opd_bytes(i) <= 0) return nullptr;
|
||||
oracle_snap(n_opd, false);
|
||||
/* REPEAT MODE NEEDS NO HOST KERNEL, and the issue path carries this pointer back only to
|
||||
* say "armed". oracle_after re-launches the DEVICE plan it is handed instead. */
|
||||
static const IssuePlan kRepeatArmed{};
|
||||
return &kRepeatArmed;
|
||||
}
|
||||
/* NOT GATED ON THE DEVICE DOMAIN. Under RADIANCE_HOST_DOMAIN the launch IS the host kernel,
|
||||
* so the comparison is host against host and agrees by construction -- but the per-operand
|
||||
* lines are still the only ordered trace of what the graph computed, and diffing those
|
||||
* against another engine's is what the whole-model reference exists for. */
|
||||
const OpPlan& p = plans_[h];
|
||||
const IssuePlan& hip =
|
||||
issue_table_[(size_t)p.plan_off + (size_t)band * RAD_N_DOMAINS + RAD_DOMAIN_HOST];
|
||||
if (!hip.launch) {
|
||||
++oracle_->skipped_nohost;
|
||||
if (!oracle_->said_nohost) {
|
||||
oracle_->said_nohost = true;
|
||||
RAD_WARN("oracle: op '%s' has no host kernel in this band, so it cannot be checked. "
|
||||
"A library with host kernels -- a reference one, or the host library -- "
|
||||
"must be on the kernel search path for the oracle to see anything.", plans_[h].info->op.c_str());
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
/* AN OPERAND WITH NO BYTE COUNT IS A NAMED SKIP, not a silent one. The count is missing when
|
||||
* the dtype is plugin-private and the operand is not a weight the layout pass sized -- a
|
||||
* packed plane the core is not meant to understand (spec 4.2). Dropping the whole issue
|
||||
* without saying so would report a routed model's expert GEMM as "0 checked" beside a page of
|
||||
* agreements, which reads as nothing to check rather than as a gap. */
|
||||
for (int i = 0; i < n_opd; ++i) {
|
||||
if (!tbuf_[i].data || oracle_opd_bytes(i) > 0) continue;
|
||||
RAD_WARN("oracle #%lld op '%s': NOT CHECKED. operand %d is %s and the core cannot size "
|
||||
"it -- a plugin-private dtype is the plugin's to measure, and nothing bound "
|
||||
"this operand to a weight whose stored size the container records.",
|
||||
(long long)n_issues_, plans_[h].info->op.c_str(), i,
|
||||
rad_dtype_name(tbuf_[i].dtype));
|
||||
return nullptr;
|
||||
}
|
||||
/* AND AN OPERAND THE HOST CANNOT HOLD IS A NAMED SKIP TOO. The snapshot is two host copies
|
||||
* of every operand and a third for a weight stored re-laid, so an operand of tens of
|
||||
* gigabytes is not a slow check -- it is the process being killed with nothing reported, and
|
||||
* no reason in the log because there is no chance to write one. A 47 GiB n-gram table read
|
||||
* at decode is such an operand. */
|
||||
for (int i = 0; i < n_opd; ++i) {
|
||||
if (!tbuf_[i].data || oracle_->alias[i] != i) continue;
|
||||
const int64_t b = oracle_opd_bytes(i);
|
||||
if (b <= oracle_->maxopd) continue;
|
||||
const OpInfo& oi = *plans_[h].info;
|
||||
const char* wn = nullptr;
|
||||
if (program_)
|
||||
for (size_t j = 0; j < oi.weights.size() && j < oi.weight_opd.size(); ++j)
|
||||
if ((int)oi.weight_opd[j] == i && oi.weights[j]
|
||||
&& (size_t)oi.weights[j] < program_->weights.size())
|
||||
wn = program_->weights[(size_t)oi.weights[j]].name.c_str();
|
||||
RAD_WARN("oracle #%lld op '%s': NOT CHECKED. operand %d%s%s%s is %lld MiB against a cap of "
|
||||
"%lld MiB, and two host copies of it would end the run instead of reporting on "
|
||||
"it. RADIANCE_OP_ORACLE_MAXBYTES raises the cap.",
|
||||
(long long)n_issues_, oi.op.c_str(), i, wn ? " ('" : "", wn ? wn : "",
|
||||
wn ? "')" : "", (long long)(b >> 20), (long long)(oracle_->maxopd >> 20));
|
||||
return nullptr;
|
||||
}
|
||||
oracle_snap(n_opd, false);
|
||||
return &hip;
|
||||
}
|
||||
|
||||
void Ctx::oracle_after(rad_op h, const IssuePlan& hip, const IssuePlan& dip, int n_opd) {
|
||||
if (oracle_->repeat) {
|
||||
oracle_repeat(h, dip, n_issues_, n_opd);
|
||||
--oracle_->budget;
|
||||
++oracle_->checked;
|
||||
return;
|
||||
}
|
||||
oracle_snap(n_opd, true);
|
||||
/* The pre snapshot's tensors still point into `pre`, which oracle_snap(false) bound -- except
|
||||
* for a weight the device row stores re-laid, which this repoints at its own inverse. A row
|
||||
* that cannot be inverted is not checked at all, and not counted as checked either. */
|
||||
if (!oracle_unrelayout(h, hip, dip, n_issues_, n_opd)) return;
|
||||
oracle_run(h, hip, n_issues_, n_opd);
|
||||
--oracle_->budget;
|
||||
++oracle_->checked;
|
||||
}
|
||||
|
||||
} /* namespace rad */
|
||||
@@ -0,0 +1,34 @@
|
||||
/* rank_barrier.cpp -- see rank_barrier.h for why this is a condvar and not an IPC handshake. */
|
||||
#include "rank_barrier.h"
|
||||
|
||||
namespace rad {
|
||||
|
||||
void RankBarrier::arrive_and_wait() {
|
||||
std::unique_lock<std::mutex> lk(m_);
|
||||
if (aborted_) return;
|
||||
|
||||
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. */
|
||||
waiting_ = 0;
|
||||
++gen_;
|
||||
lk.unlock();
|
||||
cv_.notify_all();
|
||||
return;
|
||||
}
|
||||
cv_.wait(lk, [&] { return aborted_ || gen_ != my_gen; });
|
||||
}
|
||||
|
||||
void RankBarrier::abort() {
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(m_);
|
||||
aborted_ = true;
|
||||
waiting_ = 0;
|
||||
++gen_;
|
||||
}
|
||||
cv_.notify_all();
|
||||
}
|
||||
|
||||
} /* namespace rad */
|
||||
@@ -0,0 +1,54 @@
|
||||
/* 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.
|
||||
*
|
||||
* 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.
|
||||
*/
|
||||
#pragma once
|
||||
#include "../rad_core.h"
|
||||
|
||||
#include <condition_variable>
|
||||
#include <mutex>
|
||||
|
||||
namespace rad {
|
||||
|
||||
class RankBarrier {
|
||||
public:
|
||||
explicit RankBarrier(int n_ranks) : n_(n_ranks < 1 ? 1 : n_ranks), waiting_(0), gen_(0) {}
|
||||
|
||||
RankBarrier(const RankBarrier&) = delete;
|
||||
RankBarrier& operator=(const RankBarrier&) = delete;
|
||||
|
||||
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). */
|
||||
void abort();
|
||||
|
||||
|
||||
private:
|
||||
std::mutex m_;
|
||||
std::condition_variable cv_;
|
||||
int n_;
|
||||
int waiting_;
|
||||
uint64_t gen_;
|
||||
bool aborted_ = false;
|
||||
};
|
||||
|
||||
} /* namespace rad */
|
||||
@@ -0,0 +1,74 @@
|
||||
/* 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 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.
|
||||
*/
|
||||
#pragma once
|
||||
#include "../rad_core.h"
|
||||
|
||||
#include <vector>
|
||||
|
||||
namespace rad {
|
||||
|
||||
/* Where a weight's bytes are RIGHT 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).
|
||||
*
|
||||
* `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.
|
||||
*/
|
||||
struct WeightSlot {
|
||||
void* ptr;
|
||||
RadEvent ready;
|
||||
uint32_t generation;
|
||||
};
|
||||
|
||||
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. */
|
||||
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. */
|
||||
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.
|
||||
*
|
||||
* 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. */
|
||||
virtual const std::vector<rad_weight>& changes() const = 0;
|
||||
virtual void clear_changes() = 0;
|
||||
};
|
||||
|
||||
} /* namespace rad */
|
||||
@@ -0,0 +1,87 @@
|
||||
/* 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.
|
||||
*
|
||||
* 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.
|
||||
*/
|
||||
#pragma once
|
||||
#include "../rad_core.h"
|
||||
#include "rad_device.h"
|
||||
|
||||
namespace rad {
|
||||
|
||||
class OpStager {
|
||||
public:
|
||||
virtual ~OpStager() = default;
|
||||
|
||||
/* The pass is about to be issued: whether the stager takes part in it. */
|
||||
virtual bool begin_pass(const RadBatch* b) = 0;
|
||||
|
||||
/* Before op `h` is issued on stream `s`. `*resync` is set when the residency table changed,
|
||||
* so the run phase brings the op's weight tables up to date before resolving them. */
|
||||
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;
|
||||
|
||||
/* The pass has been issued, on `s`: nothing the stager published may outlive it. */
|
||||
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. */
|
||||
class StagerChain final : public OpStager {
|
||||
public:
|
||||
void set(OpStager* a, OpStager* b) { s_[0] = a; s_[1] = b; }
|
||||
|
||||
bool begin_pass(const RadBatch* b) override {
|
||||
bool any = false;
|
||||
for (int i = 0; i < 2; ++i) {
|
||||
on_[i] = s_[i] != nullptr && s_[i]->begin_pass(b);
|
||||
any = any || on_[i];
|
||||
}
|
||||
return any;
|
||||
}
|
||||
int before_op(rad_op h, RadStream s, bool* resync) override {
|
||||
*resync = false;
|
||||
for (int i = 0; i < 2; ++i) {
|
||||
if (!on_[i]) continue;
|
||||
bool r = false;
|
||||
const int rc = s_[i]->before_op(h, s, &r);
|
||||
if (rc < 0) return rc;
|
||||
*resync = *resync || r;
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
int after_op(rad_op h, RadStream s) override {
|
||||
for (int i = 0; i < 2; ++i)
|
||||
if (on_[i]) { const int rc = s_[i]->after_op(h, s); if (rc < 0) return rc; }
|
||||
return RAD_OK;
|
||||
}
|
||||
int end_pass(RadStream s) override {
|
||||
int rc = RAD_OK;
|
||||
for (int i = 0; i < 2; ++i) {
|
||||
if (!on_[i]) continue;
|
||||
const int r = s_[i]->end_pass(s);
|
||||
if (r < 0 && rc >= 0) rc = r;
|
||||
on_[i] = false;
|
||||
}
|
||||
return rc;
|
||||
}
|
||||
|
||||
private:
|
||||
OpStager* s_[2] = { nullptr, nullptr };
|
||||
bool on_[2] = { false, false };
|
||||
};
|
||||
|
||||
} /* namespace rad */
|
||||
@@ -0,0 +1,772 @@
|
||||
#include "runtime/tierexec.h"
|
||||
|
||||
#include "mem/sstier.h"
|
||||
#include "rad_internal.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
|
||||
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. */
|
||||
int TierExec::configure(Registry* reg, KVManager* kv, IdleTiers* tiers, SSDTier* disk,
|
||||
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,
|
||||
int64_t ck_slot_off, RadStream shared) {
|
||||
close();
|
||||
if (!reg || !kv || !tiers || groups.empty() || max_batch <= 0 || max_copy <= 0 ||
|
||||
max_chain <= 0)
|
||||
return RAD_E_INVAL;
|
||||
reg_ = reg; kv_ = kv; tiers_ = tiers; disk_ = disk; leader_ = leader; device_ = device;
|
||||
max_batch_ = max_batch; max_copy_ = max_copy; max_chain_ = max_chain;
|
||||
slot_off_ = slot_off;
|
||||
slot_bytes_ = tiers->entry_bytes();
|
||||
ck_bytes_ = kv->checkpoint_bytes();
|
||||
ck_slot_bytes_ = tiers->ckpt_bytes();
|
||||
ck_slot_off_ = ck_slot_off;
|
||||
shared_ = shared;
|
||||
RAD_TRY(rad_dev_set(device_));
|
||||
|
||||
int64_t off = 0;
|
||||
for (int32_t g : groups) {
|
||||
const KVGroupPlan* p = kv->plan(g);
|
||||
if (!p || !p->paged()) continue;
|
||||
GroupInfo gi;
|
||||
gi.g = g;
|
||||
gi.n_layers = p->n_layers;
|
||||
gi.frag = p->layer_bytes_per_block();
|
||||
gi.layer_stride = p->layer_stride();
|
||||
gi.n_blocks = p->n_blocks;
|
||||
gi.base = p->base;
|
||||
gi.off = off;
|
||||
/* 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. */
|
||||
Geometry q;
|
||||
q.set_s("dtype", "u8");
|
||||
q.set_i("n", gi.frag);
|
||||
q.set_i("M", max_batch);
|
||||
gi.gather = reg->resolve("gather_rows", q, RAD_DOMAIN_DEVICE);
|
||||
gi.scatter = reg->resolve("scatter_rows", q, RAD_DOMAIN_DEVICE);
|
||||
if (!gi.gather || !gi.scatter) {
|
||||
RAD_WARN("kv tiers: no device gather/scatter for group %d at a %lld-byte fragment, "
|
||||
"so a finished conversation cannot leave VRAM. The tiers are off.",
|
||||
(int)g, (long long)gi.frag);
|
||||
close();
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
off += gi.n_layers * gi.frag;
|
||||
gi_.push_back(gi);
|
||||
}
|
||||
if (gi_.empty()) return RAD_E_UNSUPPORTED;
|
||||
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. */
|
||||
verify_ = leader && std::getenv("RADIANCE_DEBUG_TIER_VERIFY") != nullptr;
|
||||
|
||||
char buf[320];
|
||||
std::snprintf(buf, sizeof buf,
|
||||
"kv tier transfer: %zu paged group(s), %s an entry, batches of %d through "
|
||||
"gather_rows/scatter_rows at u8%s%s",
|
||||
gi_.size(), humanb(entry_bytes_).c_str(), max_batch_,
|
||||
ck_bytes_ > 0 ? "; linear state as one contiguous copy of " : "",
|
||||
ck_bytes_ > 0 ? humanb(ck_bytes_).c_str() : "");
|
||||
report_ = buf;
|
||||
enabled_ = true;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
void TierExec::close() {
|
||||
/* Nothing may still be reading the buffers about to be freed. */
|
||||
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; }
|
||||
copy_out_ = false;
|
||||
gi_.clear();
|
||||
order_.clear();
|
||||
verify_pending_.clear();
|
||||
entry_bytes_ = 0;
|
||||
ck_bytes_ = ck_slot_bytes_ = ck_slot_off_ = 0;
|
||||
enabled_ = false;
|
||||
leader_ = false;
|
||||
reg_ = nullptr; kv_ = nullptr; tiers_ = nullptr; disk_ = nullptr;
|
||||
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, no disk 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. */
|
||||
int TierExec::device_init() {
|
||||
if (stream_) return RAD_OK;
|
||||
RAD_TRY(rad_dev_set(device_));
|
||||
const int64_t ng = (int64_t)gi_.size();
|
||||
copy_idx_ = max_copy_;
|
||||
chain_idx_ = max_chain_;
|
||||
const int64_t idx_n = ng * (copy_idx_ + (int64_t)kRing * chain_idx_);
|
||||
stage_ = rad_dev_alloc((int64_t)max_batch_ * entry_bytes_, RAD_MEM_DEVICE);
|
||||
idx_dev_ = (int32_t*)rad_dev_alloc(idx_n * (int64_t)sizeof(int32_t), RAD_MEM_DEVICE);
|
||||
idx_host_ = (int32_t*)rad_dev_alloc(idx_n * (int64_t)sizeof(int32_t), RAD_MEM_HOST_PINNED);
|
||||
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 (shared_) {
|
||||
stream_ = shared_;
|
||||
own_stream_ = false;
|
||||
} else if (rad_stream_create(&stream_, /*high_priority=*/0) == RAD_OK) {
|
||||
own_stream_ = true;
|
||||
} else {
|
||||
stream_ = nullptr;
|
||||
undo();
|
||||
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. */
|
||||
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{};
|
||||
pool.dtype = RAD_U8;
|
||||
pool.rank = 2;
|
||||
pool.shape[0] = gi.n_blocks; pool.shape[1] = gi.frag;
|
||||
pool.stride[0] = gi.frag; pool.stride[1] = 1;
|
||||
pool.data = (char*)gi.base + layer * gi.layer_stride;
|
||||
|
||||
RadTensor idx{};
|
||||
idx.dtype = RAD_I32; idx.rank = 1;
|
||||
idx.shape[0] = n_jobs; idx.stride[0] = 1;
|
||||
idx.data = (void*)d_idx;
|
||||
|
||||
RadTensor pack{};
|
||||
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[1] = 1;
|
||||
pack.data = (char*)stage_base + gi.off + layer * gi.frag;
|
||||
|
||||
RadTensor t3[3];
|
||||
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. */
|
||||
RadArgs a{};
|
||||
a.t = t3; a.n_t = 3;
|
||||
a.p = r.geom.params(); a.n_p = r.geom.n_params();
|
||||
a.instance = r.instance;
|
||||
return r.row->info->launch(&a, stream_);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ RADIANCE_DEBUG_TIER_VERIFY */
|
||||
|
||||
static uint64_t tier_fnv(const void* p, int64_t n) {
|
||||
uint64_t h = 1469598103934665603ull;
|
||||
const unsigned char* b = (const unsigned char*)p;
|
||||
for (int64_t i = 0; i < n; ++i) { h ^= b[i]; h *= 1099511628211ull; }
|
||||
return h;
|
||||
}
|
||||
|
||||
void TierExec::verify_note(const BlockHash& key, const void* p, int64_t n, bool snapshot) {
|
||||
if (!verify_ || !leader_ || !p || n <= 0) return;
|
||||
(snapshot ? out_ck_ : out_sum_)[key] = tier_fnv(p, n);
|
||||
}
|
||||
|
||||
void TierExec::verify_check(const BlockHash& key, const void* p, int64_t n, bool snapshot) {
|
||||
if (!verify_ || !leader_ || !p || n <= 0) return;
|
||||
auto& m = snapshot ? out_ck_ : out_sum_;
|
||||
auto it = m.find(key);
|
||||
if (it == m.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 %s for %s came back DIFFERENT (%016llx out, %016llx in). The tier is "
|
||||
"moving the wrong bytes, not the engine choosing differently downstream.",
|
||||
snapshot ? "linear-state snapshot" : "attention blocks", 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. */
|
||||
#define TIER_TRY(call, what) \
|
||||
do { const int _s = (call); \
|
||||
if (_s != RAD_OK) { warn_once(what, _s); return _s; } } while (0)
|
||||
|
||||
void TierExec::warn_once(const char* what, int st) {
|
||||
if (warned_) return;
|
||||
warned_ = true;
|
||||
RAD_WARN("kv tiers: %s failed with %s. The entry stays where it was; this is said once, and "
|
||||
"the running failure count is in /sessions.", what, rad_strerror(st));
|
||||
}
|
||||
|
||||
bool TierExec::blocks_backed(const std::vector<int32_t>& blocks, const char* what) {
|
||||
if (!kv_) return false;
|
||||
for (size_t k = 0; k < gi_.size(); ++k) {
|
||||
if (k >= blocks.size()) continue; /* an absent group is the gather's -1 row */
|
||||
const int32_t b = blocks[k];
|
||||
if (b < 0) continue;
|
||||
const int64_t live = kv_->live_blocks(gi_[k].g);
|
||||
if (b < live) continue;
|
||||
if (warned_unbacked_) return false;
|
||||
warned_unbacked_ = true;
|
||||
RAD_ERR("kv tier %s: block %d of group %d is at or past this rank's live mark of %lld, so "
|
||||
"it is lent to the expert slab and holds weights. The transfer is refused; the "
|
||||
"entry stays where it is.", what, (int)b, (int)gi_[k].g, (long long)live);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
int TierExec::copy_runs(const std::vector<TierJob*>& order, size_t first, int64_t n, bool out) {
|
||||
int64_t k = 0;
|
||||
while (k < n) {
|
||||
const int32_t s0 = order[first + (size_t)k]->host_slot;
|
||||
int64_t run = 1;
|
||||
while (k + run < n && order[first + (size_t)(k + run)]->host_slot == s0 + run) ++run;
|
||||
char* host = (char*)tiers_->arena().at(s0);
|
||||
if (!host) return RAD_E_STATE;
|
||||
host += slot_off_;
|
||||
char* dev = (char*)stage_ + k * entry_bytes_;
|
||||
const int st = out
|
||||
? rad_memcpy_2d_async(host, slot_bytes_, dev, entry_bytes_, entry_bytes_, run, stream_)
|
||||
: rad_memcpy_2d_async(dev, entry_bytes_, host, slot_bytes_, entry_bytes_, run, stream_);
|
||||
if (st != RAD_OK) return st;
|
||||
k += run;
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ copy on idle */
|
||||
|
||||
int TierExec::issue_copy(std::vector<TierJob>& jobs, RadStream compute) {
|
||||
if (!enabled_ || jobs.empty()) return RAD_OK;
|
||||
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. */
|
||||
if (st != RAD_OK) (void)rad_stream_sync(stream_);
|
||||
return st;
|
||||
}
|
||||
|
||||
int TierExec::enqueue_copy(std::vector<TierJob>& jobs, RadStream compute) {
|
||||
order_.clear();
|
||||
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. */
|
||||
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 and the save that wrote the snapshots. A stream wait, not a host wait. */
|
||||
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");
|
||||
|
||||
if (n > 0) {
|
||||
const int64_t ng = (int64_t)gi_.size();
|
||||
int32_t* h = idx_host_; /* the copy region */
|
||||
for (int64_t g = 0; g < ng; ++g)
|
||||
for (int64_t k = 0; k < n; ++k) {
|
||||
const std::vector<int32_t>& b = order_[(size_t)k]->blocks;
|
||||
h[g * n + k] = (size_t)g < b.size() ? b[(size_t)g] : -1;
|
||||
}
|
||||
TIER_TRY(rad_memcpy_async(idx_dev_, h, ng * n * (int64_t)sizeof(int32_t), stream_),
|
||||
"the block-index upload");
|
||||
for (int64_t s = 0; s < n; s += max_batch_) {
|
||||
const int64_t c = std::min<int64_t>(max_batch_, n - s);
|
||||
for (size_t gidx = 0; gidx < gi_.size(); ++gidx)
|
||||
for (int64_t l = 0; l < gi_[gidx].n_layers; ++l)
|
||||
TIER_TRY(run_rows(gi_[gidx].gather, /*scatter=*/false, gi_[gidx], l, stage_,
|
||||
idx_dev_ + (int64_t)gidx * n + s, c),
|
||||
"the gather out of the pool");
|
||||
TIER_TRY(copy_runs(order_, (size_t)s, c, /*out=*/true), "the copy to host memory");
|
||||
}
|
||||
st_.bytes_out += n * entry_bytes_;
|
||||
}
|
||||
|
||||
/* The linear half: one contiguous copy each, out of the device slot the snapshot sits in. */
|
||||
for (TierJob& j : jobs) {
|
||||
if (j.ck_host < 0 || j.ck_dev < 0 || ck_bytes_ <= 0) continue;
|
||||
if (kv_->back_checkpoint(j.ck_dev) < 0) { j.ck_ok = false; continue; }
|
||||
const void* src = kv_->checkpoint_ptr(j.ck_dev);
|
||||
char* dst = (char*)tiers_->ckpt_arena().at(j.ck_host);
|
||||
if (!src || !dst) { j.ck_ok = false; continue; }
|
||||
const int st = rad_memcpy_async(dst + ck_slot_off_, src, ck_bytes_, stream_);
|
||||
if (st != RAD_OK) {
|
||||
warn_once("the snapshot copy to host memory", st);
|
||||
j.ck_ok = false;
|
||||
continue;
|
||||
}
|
||||
st_.bytes_out += ck_bytes_;
|
||||
}
|
||||
|
||||
TIER_TRY(rad_event_record(ev_copy_, stream_), "marking the copy");
|
||||
copy_out_ = true;
|
||||
++st_.passes;
|
||||
st_.jobs += (int64_t)jobs.size();
|
||||
if (verify_)
|
||||
for (const TierJob& j : jobs)
|
||||
verify_pending_.push_back({j.key, j.blocks.empty() ? -1 : j.host_slot,
|
||||
j.ck_ok ? j.ck_host : -1});
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int TierExec::copy_state() {
|
||||
if (!copy_out_) return 1;
|
||||
(void)rad_dev_set(device_);
|
||||
const int q = rad_event_query(ev_copy_);
|
||||
if (q == 0) return 0;
|
||||
copy_out_ = false;
|
||||
if (q > 0 && verify_) {
|
||||
for (const VerifyNote& v : verify_pending_) {
|
||||
if (v.host_slot >= 0)
|
||||
verify_note(v.key, (char*)tiers_->arena().at(v.host_slot) + slot_off_,
|
||||
entry_bytes_, false);
|
||||
if (v.ck_host >= 0)
|
||||
verify_note(v.key, (char*)tiers_->ckpt_arena().at(v.ck_host) + ck_slot_off_,
|
||||
ck_bytes_, true);
|
||||
}
|
||||
}
|
||||
verify_pending_.clear();
|
||||
if (q < 0) warn_once("the copy to host memory", q);
|
||||
return q > 0 ? 1 : q;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ restore */
|
||||
|
||||
int TierExec::issue_restore(std::vector<TierJob>& jobs, RadStream compute,
|
||||
std::vector<char>* ok) {
|
||||
ok->assign(jobs.size(), 0);
|
||||
if (!enabled_ || jobs.empty()) return RAD_OK;
|
||||
TIER_TRY(rad_dev_set(device_), "selecting the rank device");
|
||||
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.
|
||||
*
|
||||
* 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. */
|
||||
if (leader_) {
|
||||
const int64_t n = (int64_t)jobs.size();
|
||||
std::vector<std::vector<int32_t>> ids(ng);
|
||||
int64_t m = n;
|
||||
for (size_t k = 0; k < ng; ++k) {
|
||||
ids[k].reserve((size_t)n);
|
||||
m = std::min(m, kv_->reserve_blocks(gi_[k].g, m, &ids[k]));
|
||||
}
|
||||
for (size_t k = 0; k < ng; ++k)
|
||||
for (size_t i = (size_t)m; i < ids[k].size(); ++i) kv_->release_block(gi_[k].g, ids[k][i]);
|
||||
for (size_t i = 0; i < jobs.size(); ++i) {
|
||||
jobs[i].blocks.clear();
|
||||
if ((int64_t)i >= m) continue;
|
||||
jobs[i].blocks.resize(ng);
|
||||
for (size_t k = 0; k < ng; ++k) jobs[i].blocks[k] = ids[k][i];
|
||||
}
|
||||
}
|
||||
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. */
|
||||
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. */
|
||||
if (leader_) {
|
||||
for (size_t i = m; i < jobs.size(); ++i) {
|
||||
for (size_t k = 0; k < ng && k < jobs[i].blocks.size(); ++k)
|
||||
if (jobs[i].blocks[k] >= 0) kv_->release_block(gi_[k].g, jobs[i].blocks[k]);
|
||||
jobs[i].blocks.clear();
|
||||
}
|
||||
}
|
||||
if (m == 0) return RAD_OK;
|
||||
|
||||
order_.clear();
|
||||
for (size_t i = 0; i < m; ++i) order_.push_back(&jobs[i]);
|
||||
for (size_t i = 0; i < m; ++i)
|
||||
verify_check(jobs[i].key, (char*)tiers_->arena().at(jobs[i].host_slot) + slot_off_,
|
||||
entry_bytes_, false);
|
||||
|
||||
/* 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. */
|
||||
for (size_t i = 0; i < m; ++i) jobs[i].started = true;
|
||||
const int ri = ring_next_;
|
||||
ring_next_ = (ring_next_ + 1) % kRing;
|
||||
int32_t* h = idx_host_ + ng * copy_idx_ + (int64_t)ri * (int64_t)ng * chain_idx_;
|
||||
int32_t* d = idx_dev_ + ng * copy_idx_ + (int64_t)ri * (int64_t)ng * chain_idx_;
|
||||
int st = RAD_OK;
|
||||
size_t done = 0;
|
||||
for (size_t s = 0; s < m && st == RAD_OK; s += (size_t)chain_idx_) {
|
||||
const int64_t c = std::min<int64_t>(chain_idx_, (int64_t)(m - s));
|
||||
if (ring_used_[ri] && (st = rad_event_sync(ring_ev_[ri])) != RAD_OK) break;
|
||||
for (size_t g = 0; g < ng; ++g)
|
||||
for (int64_t k = 0; k < c; ++k) h[(int64_t)g * c + k] = jobs[s + (size_t)k].blocks[g];
|
||||
if ((st = rad_memcpy_async(d, h, (int64_t)ng * c * (int64_t)sizeof(int32_t), stream_)) != RAD_OK)
|
||||
break;
|
||||
if ((st = rad_event_record(ring_ev_[ri], stream_)) != RAD_OK) break;
|
||||
ring_used_[ri] = true;
|
||||
for (int64_t b = 0; b < c && st == RAD_OK; b += max_batch_) {
|
||||
const int64_t cc = std::min<int64_t>(max_batch_, c - b);
|
||||
if ((st = copy_runs(order_, s + (size_t)b, cc, /*out=*/false)) != RAD_OK) break;
|
||||
for (size_t gidx = 0; gidx < ng && st == RAD_OK; ++gidx)
|
||||
for (int64_t l = 0; l < gi_[gidx].n_layers && st == RAD_OK; ++l)
|
||||
st = run_rows(gi_[gidx].scatter, /*scatter=*/true, gi_[gidx], l, stage_,
|
||||
d + (int64_t)gidx * c + b, cc);
|
||||
}
|
||||
if (st == RAD_OK) done = s + (size_t)c;
|
||||
}
|
||||
if (st != RAD_OK) warn_once("the restore into the pool", st);
|
||||
for (size_t i = 0; i < done; ++i) (*ok)[i] = 1;
|
||||
st_.bytes_in += (int64_t)done * entry_bytes_;
|
||||
|
||||
/* THE LINEAR HALF, into a slot the leader allocates. The same rule as the blocks: the id is
|
||||
* rank 0's to choose, and a follower takes the id it is handed and backs its own pages. A
|
||||
* snapshot that cannot be placed is not a failure of the restore -- the session keeps its
|
||||
* attention hit and replays its linear layers, which is what it would have done with no
|
||||
* tiers at all.
|
||||
*
|
||||
* THE DEEPEST ONE IS WORTH A SLOT SOMEBODY ELSE HAS. A hit resumes from the last checkpoint at
|
||||
* or below its attention hit, which on a restored chain is the chain's last snapshot; the
|
||||
* earlier ones take a slot only where one is free. A full pool is then made room in for that
|
||||
* one snapshot by detaching another session's, which that session's own next restore brings
|
||||
* back -- rather than for every snapshot on the chain, which would push out as many other
|
||||
* sessions' states as this one has checkpoints. */
|
||||
size_t deepest = done;
|
||||
for (size_t i = 0; i < done; ++i)
|
||||
if (jobs[i].ck_want && jobs[i].ck_ok && jobs[i].ck_host >= 0) deepest = i;
|
||||
for (size_t i = 0; i < done; ++i) {
|
||||
TierJob& j = jobs[i];
|
||||
if (!j.ck_want || !j.ck_ok || j.ck_host < 0 || ck_bytes_ <= 0) continue;
|
||||
if (leader_) {
|
||||
int32_t slot = -1;
|
||||
if (kv_->alloc_checkpoint(&slot) != RAD_OK || slot < 0) {
|
||||
slot = -1;
|
||||
if (i != deepest || !ck_room_ || !ck_room_() ||
|
||||
kv_->alloc_checkpoint(&slot) != RAD_OK || slot < 0)
|
||||
continue;
|
||||
}
|
||||
j.ck_dev = slot;
|
||||
}
|
||||
if (j.ck_dev < 0) continue;
|
||||
if (kv_->back_checkpoint(j.ck_dev) < 0) { j.ck_ok = false; continue; }
|
||||
const char* src = (const char*)tiers_->ckpt_arena().at(j.ck_host);
|
||||
void* dst = kv_->checkpoint_ptr(j.ck_dev);
|
||||
if (!src || !dst) { j.ck_ok = false; continue; }
|
||||
verify_check(j.key, src + ck_slot_off_, ck_bytes_, true);
|
||||
const int cs = rad_memcpy_async(dst, src + ck_slot_off_, ck_bytes_, stream_);
|
||||
if (cs != RAD_OK) { warn_once("the snapshot copy back into the pool", cs); j.ck_ok = false; continue; }
|
||||
st_.bytes_in += ck_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. */
|
||||
if (rad_event_record(ev_restore_, stream_) != RAD_OK ||
|
||||
rad_event_wait(compute, ev_restore_) != RAD_OK) {
|
||||
(void)rad_stream_sync(stream_);
|
||||
}
|
||||
++st_.passes;
|
||||
st_.jobs += (int64_t)m;
|
||||
return st;
|
||||
}
|
||||
|
||||
int TierExec::fence(RadEvent* out) {
|
||||
*out = nullptr;
|
||||
if (!enabled_ || !stream_) return RAD_OK;
|
||||
RAD_TRY(rad_dev_set(device_));
|
||||
RadEvent e = nullptr;
|
||||
RAD_TRY(rad_event_create(&e));
|
||||
const int st = rad_event_record(e, stream_);
|
||||
if (st != RAD_OK) { rad_event_destroy(e); return st; }
|
||||
*out = e;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ the disk store */
|
||||
|
||||
void TierExec::run_disk(std::vector<TierJob>& jobs, std::vector<char>* ok) {
|
||||
ok->assign(jobs.size(), 1);
|
||||
for (size_t i = 0; i < jobs.size(); ++i) (*ok)[i] = run_write(jobs[i]) ? 1 : 0;
|
||||
}
|
||||
|
||||
bool TierExec::run_write(TierJob& j) {
|
||||
if (j.kind != TierJob::Kind::ToDisk) return true; /* the drops move nothing */
|
||||
bool ok = true;
|
||||
/* THE WHOLE SLOT, every rank's shard of it, because a disk entry read back must be able to
|
||||
* serve all of them. A job may carry only the snapshot half, when the blocks are already on
|
||||
* disk or their write went out earlier. */
|
||||
if (j.host_slot >= 0) {
|
||||
const void* src = tiers_->arena().at(j.host_slot);
|
||||
ok = disk_ && src && disk_->put_block(j.key, nullptr, 0, src, slot_bytes_) == RAD_OK;
|
||||
}
|
||||
if (j.ck_host >= 0) {
|
||||
const void* cs = tiers_->ckpt_arena().at(j.ck_host);
|
||||
/* A snapshot store that was never opened -- no room for one inside the disk cap -- refuses
|
||||
* this, which is the right answer and not an error: the host copy stays the only one, as
|
||||
* it was. */
|
||||
j.ck_ok = disk_ && cs && disk_->put_checkpoint(j.key, j.ck_pos, cs, ck_slot_bytes_) == RAD_OK;
|
||||
}
|
||||
return ok;
|
||||
}
|
||||
|
||||
void TierExec::run_fetch(std::vector<TierJob>& jobs, std::vector<char>* ok) {
|
||||
ok->assign(jobs.size(), 1);
|
||||
std::vector<BlockHash> keys;
|
||||
std::vector<void*> dst;
|
||||
std::vector<size_t> at;
|
||||
for (size_t i = 0; i < jobs.size(); ++i) {
|
||||
TierJob& j = jobs[i];
|
||||
j.started = true;
|
||||
if (j.host_slot < 0) continue; /* only the snapshot half */
|
||||
keys.push_back(j.key);
|
||||
dst.push_back(tiers_->arena().at(j.host_slot));
|
||||
at.push_back(i);
|
||||
}
|
||||
if (!keys.empty()) {
|
||||
std::vector<char> got(keys.size(), 0);
|
||||
if (disk_) (void)disk_->get_blocks(keys.data(), (int64_t)keys.size(), dst.data(),
|
||||
slot_bytes_, got.data());
|
||||
for (size_t k = 0; k < keys.size(); ++k) (*ok)[at[k]] = got[k];
|
||||
st_.bytes_in += (int64_t)keys.size() * slot_bytes_;
|
||||
}
|
||||
for (TierJob& j : jobs) {
|
||||
if (j.ck_host < 0) continue;
|
||||
void* cs = tiers_->ckpt_arena().at(j.ck_host);
|
||||
j.ck_ok = disk_ && cs && disk_->get_checkpoint(j.key, j.ck_pos, cs, ck_slot_bytes_) == RAD_OK;
|
||||
}
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ the report */
|
||||
|
||||
void TierExec::report_pass(std::vector<TierJob>& jobs, const std::vector<char>& ok,
|
||||
uint64_t now_ns) {
|
||||
if (!enabled_ || !leader_) return;
|
||||
for (size_t i = 0; i < jobs.size(); ++i) {
|
||||
TierJob& j = jobs[i];
|
||||
const bool good = i < ok.size() && ok[i];
|
||||
/* A SNAPSHOT IS RESTORED ONLY IF EVERY RANK RESTORED ITS SHARD, and the leader is the only
|
||||
* one that can act on that. It allocates the checkpoint slot and fills its own window
|
||||
* first, so a follower that then fails leaves the slot holding this rank's new state beside
|
||||
* another rank's stale state -- a checkpoint the cache would go on to serve, one card
|
||||
* resuming the conversation and the other resuming whatever it last held.
|
||||
*
|
||||
* A PROMOTION THAT FAILED AS A WHOLE gives back everything the leader took for it: report()
|
||||
* drops or keeps the record, and nothing will ever name these blocks or this slot again. */
|
||||
if (j.kind == TierJob::Kind::ToDevice && j.ck_dev >= 0 && (!j.ck_ok || !good)) {
|
||||
kv_->free_checkpoint(j.ck_dev);
|
||||
j.ck_dev = -1;
|
||||
}
|
||||
if (j.kind == TierJob::Kind::ToDevice && !good) {
|
||||
for (size_t k = 0; k < gi_.size() && k < j.blocks.size(); ++k)
|
||||
if (j.blocks[k] >= 0) kv_->release_block(gi_[k].g, j.blocks[k]);
|
||||
j.blocks.clear();
|
||||
}
|
||||
tiers_->report(j, good, now_ns);
|
||||
}
|
||||
std::vector<int32_t> frees;
|
||||
tiers_->take_checkpoint_frees(&frees);
|
||||
for (int32_t s : frees) kv_->free_checkpoint(s);
|
||||
}
|
||||
|
||||
bool TierExec::plan_promote(const BlockHash& key, TierJob* out) {
|
||||
if (!enabled_ || !leader_) return false;
|
||||
return tiers_->plan_promote(key, out);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ TierIO */
|
||||
|
||||
TierIO::~TierIO() { stop(); }
|
||||
|
||||
void TierIO::start(TierExec* leader) {
|
||||
stop();
|
||||
x_ = leader;
|
||||
stop_ = false;
|
||||
th_ = std::thread([this] { loop(); });
|
||||
}
|
||||
|
||||
void TierIO::stop() {
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(mu_);
|
||||
stop_ = true;
|
||||
}
|
||||
cv_.notify_all();
|
||||
if (th_.joinable()) th_.join();
|
||||
has_work_ = has_done_ = false;
|
||||
work_.clear();
|
||||
done_.clear();
|
||||
ok_.clear();
|
||||
work_at_ = 0;
|
||||
fetch_q_.clear();
|
||||
fetch_done_.clear();
|
||||
}
|
||||
|
||||
bool TierIO::submit(std::vector<TierJob>&& jobs) {
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(mu_);
|
||||
if (has_work_ || has_done_ || !th_.joinable()) return false;
|
||||
work_ = std::move(jobs);
|
||||
ok_.assign(work_.size(), 1);
|
||||
work_at_ = 0;
|
||||
has_work_ = true;
|
||||
}
|
||||
cv_.notify_all();
|
||||
return true;
|
||||
}
|
||||
|
||||
bool TierIO::submit_fetch(Fetch&& f) {
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(mu_);
|
||||
if (!th_.joinable()) return false;
|
||||
fetch_q_.push_back(std::move(f));
|
||||
}
|
||||
cv_.notify_all();
|
||||
return true;
|
||||
}
|
||||
|
||||
bool TierIO::take_fetch(Fetch* out) {
|
||||
std::lock_guard<std::mutex> lk(mu_);
|
||||
if (fetch_done_.empty()) return false;
|
||||
*out = std::move(fetch_done_.front());
|
||||
fetch_done_.pop_front();
|
||||
return true;
|
||||
}
|
||||
|
||||
bool TierIO::take(std::vector<TierJob>* jobs, std::vector<char>* ok) {
|
||||
std::lock_guard<std::mutex> lk(mu_);
|
||||
if (!has_done_) return false;
|
||||
*jobs = std::move(done_);
|
||||
*ok = std::move(ok_);
|
||||
done_.clear();
|
||||
ok_.clear();
|
||||
has_done_ = false;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool TierIO::busy() const {
|
||||
std::lock_guard<std::mutex> lk(mu_);
|
||||
return has_work_ || has_done_;
|
||||
}
|
||||
|
||||
void TierIO::loop() {
|
||||
for (;;) {
|
||||
Fetch f;
|
||||
bool read = false;
|
||||
size_t i = 0;
|
||||
{
|
||||
std::unique_lock<std::mutex> lk(mu_);
|
||||
cv_.wait(lk, [this] { return stop_ || !fetch_q_.empty() || (has_work_ && !has_done_); });
|
||||
if (stop_) return;
|
||||
if (!fetch_q_.empty()) {
|
||||
f = std::move(fetch_q_.front());
|
||||
fetch_q_.pop_front();
|
||||
read = true;
|
||||
} else {
|
||||
i = work_at_;
|
||||
}
|
||||
}
|
||||
if (read) {
|
||||
/* NOT A BYTE UNTIL EVERY RANK'S RESTORES THAT COULD READ THESE SLOTS HAVE RUN. A fence
|
||||
* that cannot be waited on leaves the read unstarted, and the records stay on disk. */
|
||||
bool fenced = true;
|
||||
for (RadEvent e : f.fences) if (e && rad_event_sync(e) != RAD_OK) fenced = false;
|
||||
if (fenced) x_->run_fetch(f.jobs, &f.ok);
|
||||
else f.ok.assign(f.jobs.size(), 0);
|
||||
std::lock_guard<std::mutex> lk(mu_);
|
||||
fetch_done_.push_back(std::move(f));
|
||||
continue;
|
||||
}
|
||||
/* One write at a time, so a read that arrives behind a long batch waits for one job. */
|
||||
const bool ok = i < work_.size() ? x_->run_write(work_[i]) : true;
|
||||
std::lock_guard<std::mutex> lk(mu_);
|
||||
if (i < ok_.size()) ok_[i] = ok ? 1 : 0;
|
||||
work_at_ = i + 1;
|
||||
if (work_at_ >= work_.size()) {
|
||||
done_ = std::move(work_);
|
||||
work_.clear();
|
||||
has_work_ = false;
|
||||
has_done_ = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
} /* namespace rad */
|
||||
@@ -0,0 +1,315 @@
|
||||
/* tierexec.h -- the side of the KV tiers that actually moves bytes.
|
||||
*
|
||||
* 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).
|
||||
*
|
||||
* ============================== NOTHING HERE WAITS ON THE HOST ================================
|
||||
*
|
||||
* A copy out and a restore in are both ENQUEUED and ordered by events, never by a host wait:
|
||||
*
|
||||
* - 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 disk store is the one part that is synchronous by nature, and it runs on a thread of its own
|
||||
* (TierIO below), so the engine thread never waits on a file either.
|
||||
*
|
||||
* ============================== 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.
|
||||
*/
|
||||
#pragma once
|
||||
#include "mem/kv.h"
|
||||
#include "mem/kvtier.h"
|
||||
#include "plugin/registry.h"
|
||||
#include "rad_core.h"
|
||||
|
||||
#include <functional>
|
||||
#include <condition_variable>
|
||||
#include <cstdint>
|
||||
#include <deque>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
#include <unordered_map>
|
||||
#include <vector>
|
||||
|
||||
namespace rad {
|
||||
|
||||
class SSDTier;
|
||||
|
||||
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. */
|
||||
int configure(Registry* reg, KVManager* kv, IdleTiers* tiers, SSDTier* disk,
|
||||
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,
|
||||
int64_t ck_slot_off, RadStream shared);
|
||||
void close();
|
||||
bool enabled() const { return enabled_; }
|
||||
std::string report() const { return report_; }
|
||||
|
||||
/* 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. */
|
||||
|
||||
/* ---------------- 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. */
|
||||
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_; }
|
||||
|
||||
/* ---------------- restore ----------------
|
||||
*
|
||||
* Enqueue a chain of ToDevice jobs, in chain order, and make `compute` wait for them. Every
|
||||
* job's bytes are in host memory -- a disk entry was read in first (run_fetch) -- so nothing
|
||||
* here waits on a file. 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. */
|
||||
int issue_restore(std::vector<TierJob>& jobs, RadStream compute, std::vector<char>* ok);
|
||||
|
||||
/* A MARK ON THIS RANK'S TRANSFER STREAM, after everything enqueued on it so far. A restore
|
||||
* reads host slots asynchronously, and a slot it is still reading may be given up and handed
|
||||
* to a read off disk the moment the restore has reported; the IO thread waits for this mark
|
||||
* before it writes into any slot it was handed. Null when nothing was ever enqueued here. The
|
||||
* caller owns the event. */
|
||||
int fence(RadEvent* out);
|
||||
|
||||
/* ---------------- the disk store (leader only; TierIO's thread) ---------------- */
|
||||
void run_disk(std::vector<TierJob>& jobs, std::vector<char>* ok);
|
||||
/* One ToDisk job; true when it was written. */
|
||||
bool run_write(TierJob& j);
|
||||
/* ToHost jobs: the blocks read in parallel into the host slots they were given, then the
|
||||
* snapshots. `ok[i]` is the blocks' result, `ck_ok` the snapshot's. */
|
||||
void run_fetch(std::vector<TierJob>& jobs, std::vector<char>* ok);
|
||||
|
||||
/* Leader only. Gives back what a failed job held -- a restore's blocks and checkpoint slot --
|
||||
* reports every job to the policy, and frees the device checkpoint slots a finished copy was
|
||||
* holding on the cache's behalf. `now_ns` is when the pass ran: a promotion is 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
|
||||
* off-device or already has work outstanding. */
|
||||
bool plan_promote(const BlockHash& key, TierJob* out); /* leader only */
|
||||
|
||||
/* Leader only: how a restore gets a device checkpoint slot when the pool is full. The cache
|
||||
* owns the policy for which snapshot gives its slot up (PrefixCache::free_checkpoint_for_restore);
|
||||
* this object only knows it needs one. True when a slot was freed. */
|
||||
void set_checkpoint_room(std::function<bool()> f) { ck_room_ = std::move(f); }
|
||||
|
||||
struct Stats { int64_t passes = 0, jobs = 0, bytes_out = 0, bytes_in = 0; };
|
||||
const Stats& stats() const { return st_; }
|
||||
|
||||
private:
|
||||
struct GroupInfo {
|
||||
int32_t g = -1;
|
||||
int64_t n_layers = 0;
|
||||
int64_t frag = 0; /* layer_bytes_per_block() */
|
||||
int64_t layer_stride = 0;
|
||||
int64_t n_blocks = 0;
|
||||
void* base = nullptr;
|
||||
int64_t off = 0; /* this group's start inside one entry's staging bytes */
|
||||
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. */
|
||||
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. */
|
||||
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,
|
||||
void* stage_base, const int32_t* d_idx, int64_t n_jobs);
|
||||
/* One strided copy per run of consecutive arena slots, `n` entries starting at job `first` of
|
||||
* `order`. To host when `out`, from host otherwise. */
|
||||
int copy_runs(const std::vector<TierJob*>& order, size_t first, int64_t n, bool out);
|
||||
int enqueue_copy(std::vector<TierJob>& jobs, RadStream compute);
|
||||
|
||||
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. */
|
||||
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. */
|
||||
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. */
|
||||
int64_t slot_off_ = 0;
|
||||
int64_t slot_bytes_ = 0; /* the whole shared slot: n_ranks * entry_bytes_ */
|
||||
Registry* reg_ = nullptr;
|
||||
KVManager* kv_ = nullptr;
|
||||
IdleTiers* tiers_ = nullptr;
|
||||
SSDTier* disk_ = nullptr;
|
||||
std::function<bool()> ck_room_;
|
||||
std::vector<GroupInfo> gi_;
|
||||
int64_t entry_bytes_ = 0;
|
||||
/* ---- the linear half ----
|
||||
* `ck_bytes_` is THIS RANK's shard of one snapshot and `ck_slot_bytes_` the whole shared slot,
|
||||
* exactly as entry_bytes_ and slot_bytes_ are for blocks. Zero on a model with no recurrent
|
||||
* state, which is the whole of the "off" path here. */
|
||||
int64_t ck_bytes_ = 0;
|
||||
int64_t ck_slot_bytes_ = 0;
|
||||
int64_t ck_slot_off_ = 0;
|
||||
int max_batch_ = 0;
|
||||
int64_t max_copy_ = 0;
|
||||
int64_t max_chain_ = 0;
|
||||
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. */
|
||||
static constexpr int kRing = 4;
|
||||
int32_t* idx_host_ = nullptr; /* pinned: copy region, then kRing restore regions */
|
||||
int32_t* idx_dev_ = nullptr;
|
||||
int64_t copy_idx_ = 0; /* entries a copy region holds, per group */
|
||||
int64_t chain_idx_ = 0; /* entries a restore region holds, per group */
|
||||
RadEvent ring_ev_[kRing] = {};
|
||||
bool ring_used_[kRing] = {};
|
||||
int ring_next_ = 0;
|
||||
RadEvent ev_compute_ = nullptr; /* the compute stream, as a copy out found it */
|
||||
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. */
|
||||
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 for a snapshot is tens of
|
||||
* milliseconds an 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. */
|
||||
bool verify_ = false;
|
||||
std::unordered_map<BlockHash, uint64_t, BlockHashHash> out_sum_, out_ck_;
|
||||
struct VerifyNote { BlockHash key; int32_t host_slot = -1; int32_t ck_host = -1; };
|
||||
std::vector<VerifyNote> verify_pending_;
|
||||
void verify_note(const BlockHash& key, const void* p, int64_t n, bool snapshot);
|
||||
void verify_check(const BlockHash& key, const void* p, int64_t n, bool snapshot);
|
||||
|
||||
std::string report_;
|
||||
Stats st_;
|
||||
};
|
||||
|
||||
/* ------------------------------------------------------------------ the disk thread */
|
||||
/* THE DISK STORE ON A THREAD OF ITS OWN. A host-to-disk move is a file write of the whole slot,
|
||||
* and a pass that makes room for a conversation's worth of copies is hundreds of megabytes of it
|
||||
* -- the engine thread would build no step for as long as the writes took. So a batch is handed
|
||||
* over and collected later. The thread touches the host arena and the disk store and nothing
|
||||
* else: every decision about the records is made before the hand-over and after the collection,
|
||||
* on the engine thread, under the scheduler's lock.
|
||||
*
|
||||
* TWO KINDS OF WORK, AND THE READS GO FIRST. A write batch is the background copy to disk: one at
|
||||
* a time, and the engine does not hand over the next until it has collected the last. A read
|
||||
* batch is a conversation a request is waiting on (IdleTiers::plan_fetch), so reads queue in the
|
||||
* order they were asked for and each one is taken ahead of whatever write is out -- between two
|
||||
* of its jobs, not after the whole batch. */
|
||||
class TierIO {
|
||||
public:
|
||||
~TierIO();
|
||||
void start(TierExec* leader);
|
||||
void stop();
|
||||
/* False when a batch is already out. */
|
||||
bool submit(std::vector<TierJob>&& jobs);
|
||||
/* The finished batch, when there is one. */
|
||||
bool take(std::vector<TierJob>* jobs, std::vector<char>* ok);
|
||||
bool busy() const;
|
||||
|
||||
/* A read off disk. `tag` is the caller's (the request waiting on it); `fences` are waited on
|
||||
* before the first byte is written (TierExec::fence) and stay the caller's to destroy. */
|
||||
struct Fetch {
|
||||
uint64_t tag = 0;
|
||||
std::vector<TierJob> jobs;
|
||||
std::vector<RadEvent> fences;
|
||||
std::vector<char> ok;
|
||||
};
|
||||
/* False when the thread is not running. */
|
||||
bool submit_fetch(Fetch&& f);
|
||||
/* A finished read, oldest first. */
|
||||
bool take_fetch(Fetch* out);
|
||||
|
||||
private:
|
||||
void loop();
|
||||
TierExec* x_ = nullptr;
|
||||
std::thread th_;
|
||||
mutable std::mutex mu_;
|
||||
std::condition_variable cv_;
|
||||
std::vector<TierJob> work_, done_;
|
||||
std::vector<char> ok_;
|
||||
size_t work_at_ = 0; /* the next write job; the thread's alone while has_work_ */
|
||||
bool has_work_ = false, has_done_ = false, stop_ = false;
|
||||
std::deque<Fetch> fetch_q_, fetch_done_;
|
||||
};
|
||||
|
||||
} /* namespace rad */
|
||||
@@ -0,0 +1,22 @@
|
||||
/* wtab.cpp -- issuing a weight-table patch. See wtab.h. */
|
||||
#include "wtab.h"
|
||||
|
||||
#include "device/device.h"
|
||||
|
||||
namespace rad {
|
||||
|
||||
int wtab_patch(const WtabPatch& p, RadStream s) {
|
||||
if (p.n == 0) return RAD_OK;
|
||||
if (device_is_host()) {
|
||||
for (uint32_t i = 0; i < p.n; ++i) *p.dst[i] = p.val[i];
|
||||
return RAD_OK;
|
||||
}
|
||||
#if defined(RAD_HAVE_HIP) && RAD_HAVE_HIP
|
||||
return rad_wtab_patch_launch(&p, (void*)s) == 0 ? RAD_OK : RAD_E_DEVICE;
|
||||
#else
|
||||
(void)s;
|
||||
return RAD_E_UNSUPPORTED;
|
||||
#endif
|
||||
}
|
||||
|
||||
} /* namespace rad */
|
||||
@@ -0,0 +1,34 @@
|
||||
/* 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.
|
||||
*/
|
||||
#pragma once
|
||||
#include <cstdint>
|
||||
|
||||
#include "rad_device.h"
|
||||
|
||||
namespace rad {
|
||||
|
||||
/* One dispatch's worth of writes: dst[i] = val[i] for i < n. Sized so the argument block stays
|
||||
* inside the backend's per-dispatch argument slot with the implicit arguments beside it. */
|
||||
constexpr int kWtabPatch = 24;
|
||||
|
||||
struct WtabPatch {
|
||||
uint32_t n = 0;
|
||||
uint32_t pad = 0;
|
||||
void** dst[kWtabPatch] = {};
|
||||
void* val[kWtabPatch] = {};
|
||||
};
|
||||
|
||||
/* Enqueue `p` on `s`. Under the host backend, whose streams run their work as it is issued and
|
||||
* whose device memory is host memory, the writes happen here. */
|
||||
int wtab_patch(const WtabPatch& p, RadStream s);
|
||||
|
||||
} /* namespace rad */
|
||||
|
||||
/* The launcher in wtab.hip: one kernel onto `stream` through hipLaunchKernel. */
|
||||
extern "C" int rad_wtab_patch_launch(const rad::WtabPatch* p, void* stream);
|
||||
@@ -0,0 +1,19 @@
|
||||
/* wtab.hip -- the weight-table patch kernel: one thread a write. See wtab.h. */
|
||||
#include <hip/hip_runtime.h>
|
||||
|
||||
#include "wtab.h"
|
||||
|
||||
namespace {
|
||||
|
||||
__global__ __launch_bounds__(64) void rad_wtab_patch(rad::WtabPatch p) {
|
||||
const uint32_t i = threadIdx.x;
|
||||
if (i < p.n) *p.dst[i] = p.val[i];
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
extern "C" int rad_wtab_patch_launch(const rad::WtabPatch* p, void* stream) {
|
||||
if (!p || p->n == 0) return 0;
|
||||
hipLaunchKernelGGL(rad_wtab_patch, dim3(1), dim3(64), 0, (hipStream_t)stream, *p);
|
||||
return hipGetLastError() == hipSuccess ? 0 : -1;
|
||||
}
|
||||
Reference in new issue
Block a user