Archived
radiance 1.0.0
This commit is contained in:
commit
ae74a8aebf
616 files changed
+338692
No files matched your search
@@ -0,0 +1,244 @@
|
||||
/* rad_bufplan.cpp -- the buffer plan (spec §3.1).
|
||||
*
|
||||
* Activations are declared, liveness is computed over the declared op list, and non-overlapping
|
||||
* lifetimes are packed into one arena sized once. The alternative is an allocator on the hot
|
||||
* path, and an allocator on the hot path is the thing this engine exists to remove.
|
||||
*
|
||||
* Two conservatisms are deliberate and both are stated in the spec: the arena is sized for
|
||||
* max_tok, and liveness is computed over the declared list, which is a superset of what any given
|
||||
* step issues. A plan that is correct for the worst step is correct for every step.
|
||||
*
|
||||
* The packer is greedy interval colouring, largest first: for each buffer in descending size
|
||||
* order, take the lowest aligned offset that collides with no already-placed buffer whose
|
||||
* lifetime overlaps. It is O(n^2) in the buffer count at declare, which for a few hundred
|
||||
* activations is microseconds, and it is within a few percent of optimal on the shapes that
|
||||
* matter -- the one big activation is placed first and everything else fills in around it.
|
||||
* Optimal packing here is NP-hard and the difference is not worth a solver.
|
||||
*/
|
||||
#include "rad_build.h"
|
||||
#include "rad_internal.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <climits>
|
||||
|
||||
namespace rad {
|
||||
|
||||
/* Every buffer starts at a 256-byte boundary: the container's sub-block alignment, and wide
|
||||
* enough for any vector load an RDNA4 kernel issues (dwordx4 is 16 B). A kernel that needs more
|
||||
* than this from its scratch says so through its scratch hook, which is sized separately. */
|
||||
static constexpr int64_t kBufAlign = (int64_t)RAD_ALIGN_SUB;
|
||||
|
||||
#include <cstdlib>
|
||||
|
||||
namespace {
|
||||
|
||||
struct Item {
|
||||
size_t idx; /* index into Program::buffers */
|
||||
int64_t bytes; /* already rounded up to kBufAlign */
|
||||
int32_t lo, hi; /* inclusive op-index lifetime */
|
||||
int64_t off = -1;
|
||||
};
|
||||
|
||||
bool overlaps(const Item& a, const Item& b) { return a.lo <= b.hi && b.lo <= a.hi; }
|
||||
|
||||
/* Lowest aligned offset at or above 0 that fits `need` bytes without colliding with anything in
|
||||
* `placed` that is alive at the same time. */
|
||||
int64_t first_fit(const Item& want, const std::vector<Item>& placed) {
|
||||
std::vector<std::pair<int64_t, int64_t>> occ;
|
||||
occ.reserve(placed.size());
|
||||
for (const Item& p : placed)
|
||||
if (p.off >= 0 && overlaps(p, want)) occ.emplace_back(p.off, p.off + p.bytes);
|
||||
std::sort(occ.begin(), occ.end());
|
||||
|
||||
int64_t off = 0;
|
||||
for (auto& [s, e] : occ) {
|
||||
if (s >= off + want.bytes) break; /* the gap below this block is big enough */
|
||||
off = std::max(off, align_up(e, kBufAlign));
|
||||
}
|
||||
return off;
|
||||
}
|
||||
|
||||
} /* namespace */
|
||||
|
||||
int plan_buffers(Program& p, BufPlanReport* rep) {
|
||||
BufPlanReport r;
|
||||
int status = RAD_OK;
|
||||
|
||||
const int32_t last_op = (int32_t)p.ops.size() - 1;
|
||||
|
||||
std::vector<Item> transient, persist, host;
|
||||
for (size_t i = 1; i < p.buffers.size(); ++i) {
|
||||
BufferInfo& b = p.buffers[i];
|
||||
if (b.bytes <= 0) b.bytes = buffer_bytes(b.decl);
|
||||
if (b.bytes <= 0) {
|
||||
RAD_ERR("buffer plan: '%s' cannot be sized (dtype %u, rank %u)", b.name.c_str(),
|
||||
b.decl.dtype, b.decl.rank);
|
||||
status = RAD_E_INVAL;
|
||||
continue;
|
||||
}
|
||||
|
||||
Item it{ i, align_up(b.bytes, kBufAlign), b.first_def, b.last_use };
|
||||
if (it.lo < 0 || it.hi < it.lo) {
|
||||
/* Live for the whole program: the sound assumption when nothing declared a use. */
|
||||
it.lo = 0;
|
||||
it.hi = last_op > 0 ? last_op : 0;
|
||||
if (b.decl.kind == RAD_BUF_TRANSIENT) ++r.n_unknown_live;
|
||||
}
|
||||
|
||||
/* The two domains are coloured SEPARATELY and each offset is relative to its own arena.
|
||||
* A host-site activation cannot index device memory, so interleaving them in one offset
|
||||
* space would leave both arenas sparse -- correct, and paying VRAM for host activations.
|
||||
* Program::arena_bytes is the device high-water mark, host_arena_bytes the host one. */
|
||||
if (b.decl.domain == RAD_DOMAIN_HOST) host.push_back(it);
|
||||
else if (b.decl.kind == RAD_BUF_TRANSIENT) transient.push_back(it);
|
||||
else persist.push_back(it);
|
||||
}
|
||||
|
||||
/* Largest first, ties broken by lifetime start and then by index, so the plan is the same on
|
||||
* every rank and every run -- a placement that varies between ranks is a debugging nightmare
|
||||
* for a bug that only shows up as a numerical difference. */
|
||||
auto by_size = [](const Item& a, const Item& b) {
|
||||
if (a.bytes != b.bytes) return a.bytes > b.bytes;
|
||||
if (a.lo != b.lo) return a.lo < b.lo;
|
||||
return a.idx < b.idx;
|
||||
};
|
||||
std::sort(transient.begin(), transient.end(), by_size);
|
||||
std::sort(host.begin(), host.end(), by_size);
|
||||
|
||||
for (const Item& t : transient) r.sum_bytes += t.bytes;
|
||||
|
||||
/* peak_live is what a perfect packer would reach, so the pair (peak_live, transient_bytes)
|
||||
* brackets the arena and says whether the greedy pass left anything on the table. */
|
||||
for (int32_t t = 0; t <= std::max<int32_t>(last_op, 0); ++t) {
|
||||
int64_t live = 0;
|
||||
for (const Item& it : transient) if (it.lo <= t && t <= it.hi) live += it.bytes;
|
||||
r.peak_live = std::max(r.peak_live, live);
|
||||
}
|
||||
|
||||
/* PERSIST survives across steps and DERIVED is written once per step by the core before any
|
||||
* op runs, so neither may share with a transient or with each other: both are live for every
|
||||
* op that could read them.
|
||||
*
|
||||
* THEY GO AT THE BOTTOM, and the transients above them. A step smaller than the largest packs
|
||||
* its transients smaller (plan_level), and what it does not reach at the TOP of the arena is
|
||||
* lent to the expert slab; the fixed region has to be where no level moves it, because what
|
||||
* it holds outlives the step that wrote it. */
|
||||
int64_t off = 0;
|
||||
for (const Item& it : persist) {
|
||||
p.buffers[it.idx].arena_offset = off;
|
||||
off += it.bytes;
|
||||
off = align_up(off, kBufAlign);
|
||||
}
|
||||
const int64_t fixed = align_up(off, kBufAlign);
|
||||
r.persist_bytes = fixed;
|
||||
|
||||
std::vector<Item> placed;
|
||||
placed.reserve(transient.size());
|
||||
int64_t tr_end = 0;
|
||||
for (Item it : transient) {
|
||||
it.off = first_fit(it, placed);
|
||||
tr_end = std::max(tr_end, it.off + it.bytes);
|
||||
p.buffers[it.idx].arena_offset = fixed + it.off;
|
||||
placed.push_back(it);
|
||||
}
|
||||
r.transient_bytes = tr_end;
|
||||
|
||||
p.arena_fixed_bytes = fixed;
|
||||
p.arena_bytes = fixed + tr_end;
|
||||
|
||||
/* The host arena is its own address space and its own base pointer. Offsets below are relative
|
||||
* to it, not to Program::arena_bytes. */
|
||||
std::vector<Item> host_placed;
|
||||
int64_t host_end = 0;
|
||||
for (Item it : host) {
|
||||
/* One pass, same packer: a host PERSIST is live for the whole program by construction, so
|
||||
* first_fit already refuses to share it with anything. */
|
||||
it.off = first_fit(it, host_placed);
|
||||
host_end = std::max(host_end, it.off + it.bytes);
|
||||
p.buffers[it.idx].arena_offset = it.off;
|
||||
host_placed.push_back(it);
|
||||
}
|
||||
r.host_bytes = host_end;
|
||||
p.host_arena_bytes = host_end;
|
||||
|
||||
if (rep) *rep = r;
|
||||
return status;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ a smaller step's plan */
|
||||
|
||||
int plan_level(const Program& full, const Program& probe, int64_t rows, ArenaLevel* out,
|
||||
std::string* why) {
|
||||
auto refuse = [&](const std::string& w) {
|
||||
if (why) *why = w;
|
||||
return RAD_E_STATE;
|
||||
};
|
||||
if (probe.buffers.size() != full.buffers.size())
|
||||
return refuse(fmt("the sizing declare named %zu buffers and the real one %zu",
|
||||
probe.buffers.size() - 1, full.buffers.size() - 1));
|
||||
|
||||
ArenaLevel lv;
|
||||
lv.rows = rows;
|
||||
lv.offset.assign(full.buffers.size(), -1);
|
||||
lv.decl.assign(full.buffers.size(), RadBufDecl{});
|
||||
|
||||
std::vector<Item> transient;
|
||||
for (size_t i = 1; i < full.buffers.size(); ++i) {
|
||||
const BufferInfo& fb = full.buffers[i];
|
||||
const BufferInfo& pb = probe.buffers[i];
|
||||
const RadBufDecl& f = fb.decl;
|
||||
const RadBufDecl& q = pb.decl;
|
||||
if (fb.name != pb.name || f.kind != q.kind || f.domain != q.domain ||
|
||||
f.dtype != q.dtype || f.rank != q.rank)
|
||||
return refuse(fmt("buffer %zu is '%s' in the real declare and '%s' in the sizing one",
|
||||
i, fb.name.c_str(), pb.name.c_str()));
|
||||
/* ONLY THE ROWS MAY SHRINK. Every other extent is a stride some kernel was resolved
|
||||
* against at the real size, and a buffer narrower in any of them would be read at the
|
||||
* wrong pitch. */
|
||||
for (uint32_t d = 1; d < f.rank; ++d)
|
||||
if (f.shape[d] != q.shape[d])
|
||||
return refuse(fmt("buffer '%s' changes extent %u (%lld to %lld) with the step size",
|
||||
fb.name.c_str(), d, (long long)f.shape[d], (long long)q.shape[d]));
|
||||
if (f.rank > 0 && q.shape[0] > f.shape[0])
|
||||
return refuse(fmt("buffer '%s' is larger for a smaller step (%lld rows to %lld)",
|
||||
fb.name.c_str(), (long long)f.shape[0], (long long)q.shape[0]));
|
||||
lv.decl[i] = q;
|
||||
/* THE FIXED REGION AND THE HOST ARENA ARE THE SAME AT EVERY LEVEL. A persistent buffer
|
||||
* holds what an earlier step wrote, so it cannot move -- and it keeps its full size too:
|
||||
* one the plugin sizes by the step (a per-token plane it writes from outside the op order)
|
||||
* is only ever smaller at a smaller step, and the real declare's extent covers it. */
|
||||
if (f.kind != RAD_BUF_TRANSIENT || f.domain == RAD_DOMAIN_HOST) {
|
||||
lv.decl[i] = f;
|
||||
lv.offset[i] = fb.arena_offset;
|
||||
continue;
|
||||
}
|
||||
/* The real declare's liveness: the op list is the same, and it is the one the kernels were
|
||||
* issued against. */
|
||||
Item it{ i, align_up(buffer_bytes(q), kBufAlign), fb.first_def, fb.last_use };
|
||||
if (it.lo < 0 || it.hi < it.lo) { it.lo = 0; it.hi = (int32_t)full.ops.size(); }
|
||||
transient.push_back(it);
|
||||
}
|
||||
|
||||
auto by_size = [](const Item& a, const Item& b) {
|
||||
if (a.bytes != b.bytes) return a.bytes > b.bytes;
|
||||
if (a.lo != b.lo) return a.lo < b.lo;
|
||||
return a.idx < b.idx;
|
||||
};
|
||||
std::sort(transient.begin(), transient.end(), by_size);
|
||||
std::vector<Item> placed;
|
||||
int64_t tr_end = 0;
|
||||
for (Item it : transient) {
|
||||
it.off = first_fit(it, placed);
|
||||
tr_end = std::max(tr_end, it.off + it.bytes);
|
||||
lv.offset[it.idx] = full.arena_fixed_bytes + it.off;
|
||||
placed.push_back(it);
|
||||
}
|
||||
lv.end = full.arena_fixed_bytes + tr_end;
|
||||
if (lv.end > full.arena_bytes)
|
||||
return refuse(fmt("packing the smaller buffers took %lld bytes, more than the full plan's "
|
||||
"%lld", (long long)lv.end, (long long)full.arena_bytes));
|
||||
*out = std::move(lv);
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
} /* namespace rad */
|
||||
@@ -0,0 +1,285 @@
|
||||
/* rad_build.h -- the declare phase (spec §3.1). The architecture plugin states everything it will
|
||||
* ever do; this is what receives it.
|
||||
*
|
||||
* Two properties are the whole point of the phase and everything here is arranged around them:
|
||||
*
|
||||
* DECLARE ALWAYS COMPLETES. A missing kernel does not stop the walk. Every op, every band and
|
||||
* every domain that resolved to nothing is accumulated with the constraint that refused it, and
|
||||
* the full list is reported at the end. The first failure at the top tells you one thing; the
|
||||
* whole list tells you whether you are missing a plugin or missing a model.
|
||||
*
|
||||
* NOTHING IS DECIDED TWICE. Between declare and plan the model is known statically -- every op,
|
||||
* every kernel that will service it, every weight it touches, and the order. The bucket table,
|
||||
* the weight manifest, the buffer plan and the KV block sizes are all built once, here, so the
|
||||
* step path indexes tables instead of asking questions.
|
||||
*
|
||||
* WHAT THIS COMPONENT DOES NOT DO. The kernel hierarchy, the op schemas, the constraint match and
|
||||
* the bucket boundaries are core/plugin/'s, and the Builder asks rather than reimplements: it
|
||||
* calls Registry::validate for the schema check and Registry::build_bands for the bucket table.
|
||||
* Two answers to one question is how a selector and a builder drift apart.
|
||||
*
|
||||
* LIFETIME. Every KernelRow, Resolved and RadOpSchema in the Program points into a plugin's static
|
||||
* tables, which the Registry dlclose()s. The Program must not outlive the Registry it was built
|
||||
* against, and neither may.
|
||||
*/
|
||||
#pragma once
|
||||
#include "plugin/registry.h"
|
||||
|
||||
#include <cstdio>
|
||||
#include <functional>
|
||||
#include <set>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <unordered_map>
|
||||
#include <vector>
|
||||
|
||||
/* The handle the plugin holds. rad_builder.h only forward-declares it; core/build/ owns it, and
|
||||
* making it a base of rad::Builder means the C shims are a static_cast rather than a lookup. */
|
||||
struct RadBuilder { };
|
||||
|
||||
namespace rad {
|
||||
|
||||
/* Process-lifetime storage for declared names.
|
||||
*
|
||||
* RadNameMap and RadKernelInfo hold raw `const char*`, and the Program outlives the Builder that
|
||||
* filled it -- so a std::string member would dangle and there is nowhere in the frozen struct to
|
||||
* put one. These are interned instead: a few thousand short strings, deduplicated, never freed.
|
||||
* Freeing them would mean making RadNameMap own its storage, which is an ABI change for a few
|
||||
* kilobytes. */
|
||||
const char* intern(std::string_view s);
|
||||
|
||||
/* Names for the enums the graph dump prints. `bld_` prefixed because tier_name and site_name in
|
||||
* rad_core.h belong to the planner and these are the same kind of thing for a different axis. */
|
||||
const char* bld_domain_name(int domain);
|
||||
const char* bld_access_name(int access);
|
||||
const char* bld_buf_kind_name(int kind);
|
||||
const char* bld_kv_kind_name(int kind);
|
||||
|
||||
/* ------------------------------------------------------------------ the buffer plan */
|
||||
/* What the packing produced, for the --debug-graph report. `sum_bytes` is what no sharing at all
|
||||
* would have cost and `peak_live` is what a perfect packer would reach, so the pair brackets the
|
||||
* arena and says whether the greedy pass left anything on the table. */
|
||||
struct BufPlanReport {
|
||||
int64_t transient_bytes = 0; /* the packed, shared region */
|
||||
int64_t persist_bytes = 0; /* PERSIST + DERIVED: their own non-overlapping region */
|
||||
int64_t host_bytes = 0; /* domain=HOST buffers; a separate address space (see below) */
|
||||
int64_t peak_live = 0; /* max over op index of the bytes live at it */
|
||||
int64_t sum_bytes = 0; /* every transient, unshared */
|
||||
int n_unknown_live = 0; /* transients whose liveness nothing declared */
|
||||
};
|
||||
|
||||
/* Liveness must already be in BufferInfo::first_def / last_use; a transient with first_def < 0 is
|
||||
* treated as live for the whole program, which is the sound assumption and not a guess.
|
||||
*
|
||||
* Assigns BufferInfo::arena_offset for every buffer and sets Program::arena_bytes. Returns RAD_OK,
|
||||
* or RAD_E_INVAL if a buffer could not be sized (a plugin-private dtype the core cannot measure). */
|
||||
int plan_buffers(Program& p, BufPlanReport* rep = nullptr);
|
||||
|
||||
/* ONE SIZE OF STEP'S ARENA LAYOUT. The same buffers as the real plan, the fixed region where it
|
||||
* was, and the transients packed for a step of at most `rows` tokens -- so the arena past `end`
|
||||
* is unused by any such step and can be lent. `offset` and `decl` are indexed by buffer handle. */
|
||||
struct ArenaLevel {
|
||||
int64_t rows = 0;
|
||||
int64_t end = 0;
|
||||
std::vector<int64_t> offset;
|
||||
std::vector<RadBufDecl> decl;
|
||||
};
|
||||
/* Lay out `probe`'s buffers -- a sizing declare at `rows` -- over `full`'s. Refused, with the
|
||||
* reason in `why`, when the two declares do not describe the same buffers with only their rows
|
||||
* smaller: anything else cannot share the real plan's fixed region and kernels. */
|
||||
int plan_level(const Program& full, const Program& probe, int64_t rows, ArenaLevel* out,
|
||||
std::string* why);
|
||||
|
||||
/* Bytes a declared buffer occupies. 0 means the core cannot size it -- a plugin-private dtype,
|
||||
* which is legal for a WEIGHT (the kernel's layout hook sizes those) and not for an activation. */
|
||||
int64_t buffer_bytes(const RadBufDecl& d);
|
||||
|
||||
/* ------------------------------------------------------------------ the model behind a declare */
|
||||
/* WHAT THE MODEL HOLDS FOR A LOGICAL WEIGHT: its encoding and its logical extents. This is what
|
||||
* rad_weight_encoding answers and what every declaration is checked against (spec §4.3). The
|
||||
* engine answers from the container or the checkpoint it loads, rad-convert from the recipe it
|
||||
* will quantise by; `prog` is the declare so far, whose name map is how a checkpoint is searched.
|
||||
* RAD_OK, or RAD_E_NOTFOUND for a weight the model does not have. */
|
||||
struct WeightSource {
|
||||
RadEncoding enc{};
|
||||
uint32_t rank = 0;
|
||||
int64_t shape[RAD_MAX_RANK] = {0};
|
||||
};
|
||||
using WeightSourceFn = std::function<int(const std::string& name, const Program& prog,
|
||||
WeightSource* out)>;
|
||||
|
||||
/* ------------------------------------------------------------------ the builder */
|
||||
class Builder : public RadBuilder {
|
||||
public:
|
||||
/* The Registry must outlive the Builder AND the Program it produces: every KernelRow the
|
||||
* bands hold points into a plugin the Registry dlclose()s. */
|
||||
Builder(Registry& reg, const RadModelMeta& meta, const RadBuildCtx& ctx);
|
||||
|
||||
/* Where rad_weight_encoding's answers come from. Unset, every source is RAD_E_NOTFOUND and a
|
||||
* weight is read as plain in its declared dtype -- a test, a synthetic tool. */
|
||||
void set_sources(WeightSourceFn f) { sources_ = std::move(f); }
|
||||
|
||||
/* The C surface, one method per rad_builder.h entry point. */
|
||||
rad_weight decl_weight (const char* name, const RadWeightDecl* d);
|
||||
int weight_encoding(const char* source, RadEncoding* out, int64_t* shape,
|
||||
uint32_t* rank);
|
||||
rad_buf decl_buffer (const char* name, const RadBufDecl* d);
|
||||
rad_kvgroup decl_kv_group(const char* name, const RadKVGroupDecl* d);
|
||||
int64_t kv_block_size(rad_kvgroup g);
|
||||
int bind_layer_kv(int layer, rad_kvgroup g);
|
||||
rad_op decl_op (const char* op, const RadParam* p, int n_p,
|
||||
const rad_weight* w, int n_w);
|
||||
int op_resolved (rad_op h) const;
|
||||
int decl_name_map(const RadNameMap* m);
|
||||
int declare_logits(rad_buf b);
|
||||
int declare_drafter(const RadDrafterDecl* d);
|
||||
int declare_encoder(const RadEncoderDecl* d);
|
||||
void note_v (const char* f, va_list ap);
|
||||
|
||||
/* The buffer operands of an op.
|
||||
*
|
||||
* NOT in rad_builder.h, and it needs to be -- see the proposed ABI addition at the foot of this
|
||||
* header. rad_decl_op names an op's WEIGHT operands but not its buffer operands, so declare
|
||||
* cannot compute activation liveness from the ABI as frozen, and without liveness the arena is
|
||||
* the sum of every transient rather than the peak of them. Until the two functions below are added to the frozen header (purely additive,
|
||||
* no existing signature changes), a plugin cannot supply this and every transient is assumed
|
||||
* live for the whole program: correct, and as wasteful as it sounds. The --debug-graph buffer
|
||||
* report prints how many buffers fell into that case, so the cost is never invisible. */
|
||||
int op_reads (rad_op h, const rad_buf* b, int n);
|
||||
int op_writes(rad_op h, const rad_buf* b, int n);
|
||||
int buf_concurrent(rad_buf b);
|
||||
int weight_shard_span(rad_weight w, int64_t lo, int64_t hi);
|
||||
|
||||
/* Finalise: weight first/last use, KV group geometry, buffer liveness and packing. Returns
|
||||
* RAD_OK, or the first structural error class. Resolution MISSES are not an error here -- an
|
||||
* op that did not resolve returns a null handle and the plugin is expected to have offered a
|
||||
* fallback (spec §2.3); it becomes an error when the run phase issues it. */
|
||||
int finish();
|
||||
|
||||
/* A SIZING DECLARE (RadBuildCtx::shape_probe): every op takes the bands `ref` resolved for
|
||||
* the op at the same position instead of resolving its own, and finish() initialises nothing.
|
||||
* The plugin then sees exactly the answers the real declare gave -- which ops resolved, which
|
||||
* block size a group has -- so it declares the same graph, and nothing is selected or set up
|
||||
* a second time. An op that is not the one `ref` has at that position ends the probe with an
|
||||
* error: the plugin declared a different graph at the smaller size, and its buffers cannot be
|
||||
* laid over the real ones. */
|
||||
void set_reference(const Program* ref) { ref_ = ref; }
|
||||
|
||||
Program& program() { return prog_; }
|
||||
const Program& program() const { return prog_; }
|
||||
|
||||
/* Structural failures: a bad schema, two ranged parameters, a duplicate name. Every one of
|
||||
* them, not the first -- same rule as the miss list. */
|
||||
const std::vector<std::string>& errors() const { return errors_; }
|
||||
int status() const { return status_; }
|
||||
const BufPlanReport& buf_report() const { return bufrep_; }
|
||||
|
||||
private:
|
||||
/* Record a structural error and remember its class. Returns 0 so callers can `return err(...)`
|
||||
* straight out of a decl_ function, which is what makes a failed decl_* falsy. */
|
||||
uint32_t err(int code, const char* f, ...) __attribute__((format(printf, 3, 4)));
|
||||
std::string scoped(const char* name) const;
|
||||
|
||||
void resolve_bands(OpInfo& oi);
|
||||
void record_tune_request(const Resolved& r);
|
||||
/* init() for every surviving instance, run once the WHOLE graph has resolved. Running it
|
||||
* during resolution would let a failing init abort declare before the miss report was
|
||||
* assembled, and the miss report is the point of the phase. */
|
||||
void finish_instances();
|
||||
int32_t find_kv_consumer(rad_kvgroup g);
|
||||
void finish_layouts();
|
||||
void finish_kv_groups();
|
||||
void finish_weight_uses();
|
||||
void finish_buffer_liveness();
|
||||
|
||||
Registry& reg_;
|
||||
Program prog_;
|
||||
const Program* ref_ = nullptr;
|
||||
|
||||
std::vector<std::string> errors_;
|
||||
int status_ = RAD_OK;
|
||||
bool finished_ = false;
|
||||
|
||||
std::string scope_;
|
||||
|
||||
/* Parallel to prog_.ops. Empty until the ABI carries buffer operands. */
|
||||
struct OpBufUse { std::vector<rad_buf> reads, writes; };
|
||||
std::vector<OpBufUse> op_bufs_;
|
||||
|
||||
/* Buffers the architecture said it touches from the second lane. See rad_buf_concurrent:
|
||||
* their declared op range does not bound when their bytes are in use, so liveness gives them
|
||||
* the whole program instead. */
|
||||
std::set<rad_buf> concurrent_bufs_;
|
||||
|
||||
/* Parallel to prog_.kv_groups: where in the op list the group was declared, and which op was
|
||||
* found to consume it. Declaration order is the binding, because nothing else links an op to
|
||||
* a group -- see find_kv_consumer(). */
|
||||
std::vector<int32_t> kv_decl_at_;
|
||||
std::vector<int32_t> kv_consumer_;
|
||||
|
||||
/* Declared name -> the index in prog_.name_map of its FIRST entry, so a repeated declaration
|
||||
* can be checked against it in constant time. A linear scan would be quadratic in the weight
|
||||
* count, and a routed model declares tens of thousands of them. */
|
||||
std::unordered_map<std::string, size_t> name_map_first_;
|
||||
|
||||
/* Declared weight name -> its handle, for the same reason: Flash-Next declares about a hundred
|
||||
* thousand weights a rank, and a scan of the ones before each made declare take seconds. */
|
||||
std::unordered_map<std::string, rad_weight> weight_by_name_;
|
||||
|
||||
/* The model's answers, asked once a source: a routed model declares each expert's codes and
|
||||
* scales as two weights over one source, and a checkpoint lookup is a name-map walk. */
|
||||
WeightSourceFn sources_;
|
||||
std::unordered_map<std::string, std::pair<int, WeightSource>> source_cache_;
|
||||
int lookup_source(const std::string& name, WeightSource* out);
|
||||
|
||||
BufPlanReport bufrep_;
|
||||
};
|
||||
|
||||
/* ------------------------------------------------------------------ --debug-graph (spec §16) */
|
||||
/* The entire declared graph: every op in declared order, its bucket table with one line per band,
|
||||
* the kernel and variant that resolved each band and which plugin it came from, the constraints
|
||||
* that matched, the weights it touches and the buffer it writes; then the weight manifest, the
|
||||
* buffer plan, the KV groups, the tuning requests and the miss report.
|
||||
*
|
||||
* This is the answer to "it is unclear what even runs", so it is a first-class artifact and not a
|
||||
* debug print: the bucket-table block is byte-for-byte the format in spec §2.2. */
|
||||
std::string dump_graph_str(const Program& p, const std::vector<std::string>* errors = nullptr);
|
||||
|
||||
/* The same walk, as JSON, for the server's Model view. Grouped by (op, band table): a 64-layer
|
||||
* model declares one op sixty-four times with one bucket table, and sixty-four identical rows are
|
||||
* not more information than one row saying x64. */
|
||||
std::string dump_graph_json(const Program& p);
|
||||
void dump_graph (const Program& p, FILE* out,
|
||||
const std::vector<std::string>* errors = nullptr);
|
||||
|
||||
} /* namespace rad */
|
||||
|
||||
/* ------------------------------------------------------------------ PROPOSED ABI ADDITION */
|
||||
/* These two belong in include/rad/rad_builder.h beside rad_decl_op, and they are declared here
|
||||
* only because that header is frozen and this one is not. They are purely additive: no existing
|
||||
* signature changes and no existing plugin breaks.
|
||||
*
|
||||
* Without them, an op names its weight operands and not its buffer operands, so the declare phase
|
||||
* cannot compute activation liveness and the arena is the sum of every transient rather than the
|
||||
* peak of them -- on a 64-layer model with a per-layer residual and a per-layer FFN intermediate
|
||||
* that is the difference between one buffer and a hundred and twenty-eight. The declaration reads:
|
||||
*
|
||||
* rad_op h = RAD_OP(b, "gemm_nt", RAD_PARAMS(...), RAD_WEIGHTS(w));
|
||||
* rad_op_reads (b, h, RAD_BUFS(x));
|
||||
* rad_op_writes(b, h, RAD_BUFS(y));
|
||||
*
|
||||
* Separate calls rather than more arguments to rad_decl_op, so the common declaration stays one
|
||||
* line and the buffer plan is opt-in per op. */
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
int rad_op_reads (RadBuilder* b, rad_op h, const rad_buf* bufs, int n);
|
||||
int rad_op_writes(RadBuilder* b, rad_op h, const rad_buf* bufs, int n);
|
||||
|
||||
#define RAD_BUFS(...) ((const rad_buf[]){ __VA_ARGS__ }), \
|
||||
(int)(sizeof((const rad_buf[]){ __VA_ARGS__ }) / sizeof(rad_buf))
|
||||
|
||||
#ifdef __cplusplus
|
||||
} /* extern "C" */
|
||||
#endif
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,828 @@
|
||||
/* rad_graph.cpp -- `--debug-graph` (spec §16).
|
||||
*
|
||||
* "It is unclear what even runs" is the complaint this project exists to answer, so this is not a
|
||||
* debug print: it is the artifact. Every op in declared order, its bucket table with one line per
|
||||
* band, the kernel and variant that resolved each band and which plugin it came from, the
|
||||
* constraints that matched, the weights it touches and the buffer it writes -- then the weight
|
||||
* manifest, the buffer plan, the KV groups, the tuning requests and the miss report.
|
||||
*
|
||||
* The bucket-table block is byte-for-byte the format in spec §2.2:
|
||||
*
|
||||
* gemm_w4a8_nt N=8192 K=5120
|
||||
* M <= 16 -> gemm_w4a8_nt_m64 (libr4d, prio 20)
|
||||
* M <= 64 -> gemm_w4a8_nt_m64 (libr4d, prio 20)
|
||||
* M <= 8192 -> gemm_w4a8_prefill (libr4d, prio 10)
|
||||
*
|
||||
* Everything this file adds beyond that goes on its own lines at a deeper indent, so the table
|
||||
* stays a table and stays greppable.
|
||||
*/
|
||||
#include "rad_build.h"
|
||||
|
||||
#include "startup.h"
|
||||
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
#include <climits>
|
||||
#include <unordered_map>
|
||||
#include <cstring>
|
||||
|
||||
namespace rad {
|
||||
|
||||
/* ordered_json, so the object reads in the order it was written -- a graph dump whose keys are
|
||||
* alphabetised is a graph dump nobody can scan. */
|
||||
using json = nlohmann::ordered_json;
|
||||
|
||||
namespace {
|
||||
|
||||
/* A constraint as the kernel wrote it. constraint_why() in rad_util.cpp phrases the same thing as
|
||||
* a refusal ("M <= 16, have 8192"), which is right for the miss column and wrong here. */
|
||||
std::string constraint_str(const RadConstraint& c) {
|
||||
switch (c.op) {
|
||||
case RAD_C_EQ: return fmt("%s == %lld", c.key, c.ival);
|
||||
case RAD_C_LE: return fmt("%s <= %lld", c.key, c.ival);
|
||||
case RAD_C_GE: return fmt("%s >= %lld", c.key, c.ival);
|
||||
case RAD_C_DIV: return fmt("%s %% %lld == 0", c.key, c.ival);
|
||||
case RAD_C_IN: return fmt("%s in {%s}", c.key, c.sval ? c.sval : "");
|
||||
default: return fmt("%s ?", c.key);
|
||||
}
|
||||
}
|
||||
|
||||
/* "(libr4d, prio 20)" -- and the tuned point only when there was a choice to report. A kernel with no
|
||||
* declared axis has nothing to say about tuning, and printing "- (axis defaults)" for
|
||||
* every row of every table buries the ones that do (spec §15). */
|
||||
std::string origin(const Resolved& r) {
|
||||
const RadKernelInfo* k = r.row->info;
|
||||
if (!k || k->n_tunables <= 0) return fmt("(%s, prio %d)", r.row->plugin.c_str(),
|
||||
k ? k->priority : 0);
|
||||
const char* vn = r.choice.empty() ? "?" : r.choice.c_str();
|
||||
/* Same spelling as render_band_table in core/plugin/: two dumps of one table that punctuate
|
||||
* differently are two dumps somebody has to reconcile by eye. */
|
||||
return fmt("(%s, prio %d, %s from %s)", r.row->plugin.c_str(), k->priority, vn,
|
||||
r.tune_source.empty() ? "axis defaults" : r.tune_source.c_str());
|
||||
}
|
||||
|
||||
/* The left half of a band line, up to and including the arrow. Identical column positions in both
|
||||
* the ranged and the fixed case, so the two forms stack in one table. */
|
||||
std::string band_prefix(const OpInfo& o, const Band& b) {
|
||||
if (o.ranged_key.empty()) return " always -> ";
|
||||
if (b.hi == LLONG_MAX) return fmt(" %s <= any -> ", o.ranged_key.c_str());
|
||||
return fmt(" %s <= %4lld -> ", o.ranged_key.c_str(), (long long)b.hi);
|
||||
}
|
||||
|
||||
bool domain_has_any(const OpInfo& o, int d) {
|
||||
for (const Band& b : o.bands) if (b.dom[d]) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
void dump_bucket_table(std::string& s, const OpInfo& o, int d) {
|
||||
for (const Band& b : o.bands) {
|
||||
const Resolved& r = b.dom[d];
|
||||
if (r) {
|
||||
s += band_prefix(o, b) + fmt("%-24s", r.row->info ? r.row->info->name : "?")
|
||||
+ origin(r) + "\n";
|
||||
} else {
|
||||
/* The missing-kernel report is per band. A range with a hole in it is reported as that
|
||||
* band, not as the whole op (spec §2.2). */
|
||||
s += band_prefix(o, b) + fmt("%-24s", "(nothing)")
|
||||
+ "-- " + (b.miss[d].empty() ? "no kernel matched" : b.miss[d]) + "\n";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void dump_matched(std::string& s, const OpInfo& o, int d) {
|
||||
/* One line per distinct kernel rather than per band: sixty-four layers and three bands sharing
|
||||
* one kernel is one fact, not a hundred and ninety-two. */
|
||||
std::vector<const RadKernelInfo*> seen;
|
||||
for (const Band& b : o.bands) {
|
||||
const Resolved& r = b.dom[d];
|
||||
if (!r || !r.row->info) continue;
|
||||
if (std::find(seen.begin(), seen.end(), r.row->info) != seen.end()) continue;
|
||||
seen.push_back(r.row->info);
|
||||
|
||||
std::string cs;
|
||||
for (int i = 0; i < r.row->info->n_constraints; ++i) {
|
||||
if (i) cs += ", ";
|
||||
cs += constraint_str(r.row->info->constraints[i]);
|
||||
}
|
||||
if (cs.empty()) cs = "(unconstrained -- serves any geometry)";
|
||||
s += fmt(" matched %s: %s\n", r.row->info->name, cs.c_str());
|
||||
}
|
||||
}
|
||||
|
||||
/* Append a table row with the trailing columns trimmed. The tier and site columns are empty at
|
||||
* declare -- the planner fills them -- and a line of trailing spaces is a diff nobody wants to
|
||||
* read twice. */
|
||||
void append_row(std::string& s, std::string row) {
|
||||
while (!row.empty() && row.back() == ' ') row.pop_back();
|
||||
s += row;
|
||||
s += '\n';
|
||||
}
|
||||
|
||||
std::string join_names(const std::vector<std::string>& v) {
|
||||
std::string s;
|
||||
for (size_t i = 0; i < v.size(); ++i) { if (i) s += ", "; s += v[i]; }
|
||||
return s;
|
||||
}
|
||||
|
||||
} /* namespace */
|
||||
|
||||
std::string dump_graph_str(const Program& p, const std::vector<std::string>* errors) {
|
||||
std::string s;
|
||||
|
||||
s += fmt("==== declared graph: %s [%s] rank %d/%d max_tok %lld max_seqs %lld%s\n\n",
|
||||
p.meta.name ? p.meta.name : "?", p.meta.arch_id ? p.meta.arch_id : "?",
|
||||
p.ctx.rank, p.ctx.world_size, (long long)p.ctx.max_tok, (long long)p.ctx.max_seqs,
|
||||
(p.ctx.scope && *p.ctx.scope) ? fmt(" scope '%s'", p.ctx.scope).c_str() : "");
|
||||
|
||||
/* ---------------------------------------------------------------- the ops */
|
||||
for (size_t i = 1; i < p.ops.size(); ++i) {
|
||||
const OpInfo& o = p.ops[i];
|
||||
|
||||
std::string params = o.base.str();
|
||||
s += o.op;
|
||||
if (!params.empty()) { s += " "; s += params; }
|
||||
s += "\n";
|
||||
|
||||
/* Device first and unlabelled, which is the §2.2 form. A host-only kernel set -- which is
|
||||
* the primary development target here, not a fallback -- gets its table labelled instead
|
||||
* of a table of holes. */
|
||||
bool dev = domain_has_any(o, RAD_DOMAIN_DEVICE);
|
||||
bool hst = domain_has_any(o, RAD_DOMAIN_HOST);
|
||||
bool printed_device = dev || !hst;
|
||||
|
||||
if (printed_device) dump_bucket_table(s, o, RAD_DOMAIN_DEVICE);
|
||||
if (hst) {
|
||||
if (printed_device) s += " host domain:\n";
|
||||
dump_bucket_table(s, o, RAD_DOMAIN_HOST);
|
||||
}
|
||||
|
||||
if (printed_device) dump_matched(s, o, RAD_DOMAIN_DEVICE);
|
||||
if (hst) dump_matched(s, o, RAD_DOMAIN_HOST);
|
||||
|
||||
if (!o.weights.empty()) {
|
||||
std::vector<std::string> names;
|
||||
for (rad_weight h : o.weights)
|
||||
names.push_back(h < p.weights.size() ? p.weights[h].name : fmt("<bad handle %u>", h));
|
||||
s += fmt(" weights %s\n", join_names(names).c_str());
|
||||
}
|
||||
|
||||
/* The buffer this op writes, read off the plan rather than off a second bookkeeping
|
||||
* structure: a transient whose live range begins here is one this op defines. */
|
||||
std::vector<std::string> defs, ends;
|
||||
const int32_t nops = (int32_t)p.ops.size() - 1;
|
||||
for (size_t bi = 1; bi < p.buffers.size(); ++bi) {
|
||||
const BufferInfo& b = p.buffers[bi];
|
||||
if (b.decl.kind != RAD_BUF_TRANSIENT) continue;
|
||||
/* A buffer whose live range is the whole program is one nothing declared a use for.
|
||||
* Printing it against the first and last op would be inventing a fact; the buffer plan
|
||||
* says how many of these there are, which is the honest version. */
|
||||
if (b.first_def <= 0 && b.last_use >= nops) continue;
|
||||
if (b.first_def == (int32_t)i) defs.push_back(b.name);
|
||||
else if (b.last_use == (int32_t)i) ends.push_back(b.name);
|
||||
}
|
||||
if (!defs.empty()) s += fmt(" writes %s\n", join_names(defs).c_str());
|
||||
if (!ends.empty()) s += fmt(" last use %s\n", join_names(ends).c_str());
|
||||
|
||||
s += "\n";
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- the weight manifest */
|
||||
int64_t wtotal = 0;
|
||||
for (size_t i = 1; i < p.weights.size(); ++i) wtotal += p.weights[i].stored_bytes;
|
||||
s += fmt("---- weights: %zu, %s held by rank %d of %d\n",
|
||||
p.weights.size() - 1, humanb(wtotal).c_str(), p.ctx.rank, p.ctx.world_size);
|
||||
append_row(s, fmt(" %-40s %12s %6s %-12s %6s %7s %6s %6s %-16s %-5s %-5s",
|
||||
"name", "bytes", "align", "access", "layer", "expert", "first", "last",
|
||||
"layout", "tier", "site"));
|
||||
for (size_t i = 1; i < p.weights.size(); ++i) {
|
||||
const WeightInfo& w = p.weights[i];
|
||||
/* `layout` is what the resolved kernel asked its weights be stored as, and it is why the
|
||||
* stored bytes may differ from the logical ones. tier and site are left blank on purpose:
|
||||
* the planner fills them, after declare and before load, and printing a default here would
|
||||
* read as a decision nobody made. */
|
||||
append_row(s, fmt(" %-40s %12s %6lld %-12s %6d %7d %6d %6d %-16s %-5s %-5s",
|
||||
w.name.c_str(), humanb(w.stored_bytes).c_str(), (long long)w.align,
|
||||
bld_access_name(w.decl.access), w.decl.group.layer, w.decl.group.expert,
|
||||
w.first_use_op, w.last_use_op,
|
||||
w.layout_tag.empty() ? "as declared" : w.layout_tag.c_str(), "", ""));
|
||||
}
|
||||
s += "\n";
|
||||
|
||||
/* ---------------------------------------------------------------- the buffer plan */
|
||||
int64_t sum = 0, peak = 0, unknown = 0, persist = 0;
|
||||
const int32_t last_op = (int32_t)p.ops.size() - 1;
|
||||
for (size_t i = 1; i < p.buffers.size(); ++i) {
|
||||
const BufferInfo& b = p.buffers[i];
|
||||
if (b.decl.domain == RAD_DOMAIN_HOST) continue;
|
||||
if (b.decl.kind == RAD_BUF_TRANSIENT) {
|
||||
sum += b.bytes;
|
||||
if (b.first_def <= 0 && b.last_use >= last_op) ++unknown;
|
||||
} else {
|
||||
persist += b.bytes;
|
||||
}
|
||||
}
|
||||
for (int32_t t = 1; t <= std::max<int32_t>(last_op, 1); ++t) {
|
||||
int64_t live = 0;
|
||||
for (size_t i = 1; i < p.buffers.size(); ++i) {
|
||||
const BufferInfo& b = p.buffers[i];
|
||||
if (b.decl.kind != RAD_BUF_TRANSIENT || b.decl.domain == RAD_DOMAIN_HOST) continue;
|
||||
if (b.first_def <= t && t <= b.last_use) live += b.bytes;
|
||||
}
|
||||
peak = std::max(peak, live);
|
||||
}
|
||||
|
||||
s += fmt("---- buffer plan: arena %s, scratch %s\n",
|
||||
humanb(p.arena_bytes).c_str(), humanb(p.scratch_bytes).c_str());
|
||||
s += fmt(" transient %12s packed from %s unshared (peak live %s, waste %s)\n",
|
||||
humanb(p.arena_bytes - persist).c_str(), humanb(sum).c_str(),
|
||||
humanb(peak).c_str(), humanb(p.arena_bytes - persist - peak).c_str());
|
||||
s += fmt(" persist %12s\n", humanb(persist).c_str());
|
||||
/* Two arenas, coloured separately: a host-site activation cannot index device memory, so each
|
||||
* domain gets its own offset space and its own high-water mark. */
|
||||
if (p.host_arena_bytes)
|
||||
s += fmt(" host arena %12s (its own offset space and its own base pointer)\n",
|
||||
humanb(p.host_arena_bytes).c_str());
|
||||
if (unknown)
|
||||
s += fmt(" %lld transient buffer(s) had no declared use and are assumed live for the "
|
||||
"whole program -- that is the arena's waste, and it goes away when ops name "
|
||||
"their buffer operands\n", (long long)unknown);
|
||||
|
||||
std::vector<const BufferInfo*> big;
|
||||
for (size_t i = 1; i < p.buffers.size(); ++i) big.push_back(&p.buffers[i]);
|
||||
std::sort(big.begin(), big.end(),
|
||||
[](const BufferInfo* a, const BufferInfo* b) { return a->bytes > b->bytes; });
|
||||
for (size_t i = 0; i < big.size() && i < 5; ++i)
|
||||
s += fmt(" %-32s %12s %-9s live [%d,%d] @ %lld\n", big[i]->name.c_str(),
|
||||
humanb(big[i]->bytes).c_str(), bld_buf_kind_name(big[i]->decl.kind),
|
||||
big[i]->first_def, big[i]->last_use, (long long)big[i]->arena_offset);
|
||||
s += "\n";
|
||||
|
||||
/* ---------------------------------------------------------------- KV groups */
|
||||
if (p.kv_groups.size() > 1) {
|
||||
s += fmt("---- kv groups: %zu\n", p.kv_groups.size() - 1);
|
||||
for (size_t i = 1; i < p.kv_groups.size(); ++i) {
|
||||
const KVGroupInfo& g = p.kv_groups[i];
|
||||
s += fmt(" %-20s %-7s block %-5lld %12s/block %12s/state %zu layer(s)\n",
|
||||
g.name.c_str(), bld_kv_kind_name(g.decl.kind), (long long)g.block_size,
|
||||
humanb(g.bytes_per_block).c_str(), humanb(g.bytes_per_state).c_str(),
|
||||
g.layers.size());
|
||||
}
|
||||
s += "\n";
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- the drafter (spec §10) */
|
||||
if (p.drafter.kind != RAD_DRAFT_NONE) {
|
||||
const bool blk = p.drafter.kind == RAD_DRAFT_BLOCK;
|
||||
s += fmt("---- drafter: '%s', %s, %d token(s) a step\n",
|
||||
p.drafter_name.c_str(),
|
||||
blk ? "RAD_DRAFT_BLOCK -- a context pass, then one pass fills the whole block"
|
||||
: "RAD_DRAFT_SERIAL -- one dependent pass a token",
|
||||
p.drafter.depth);
|
||||
s += fmt(" proposal %s\n",
|
||||
p.drafter.proposal
|
||||
? fmt("%s [%lld a row]", p.buffers[p.drafter.proposal].name.c_str(),
|
||||
(long long)p.drafter.proposal_pitch).c_str()
|
||||
: "the sampler's token buffer (this head's logits go through the chain)");
|
||||
if (blk)
|
||||
s += fmt(" block %lld row(s) a sequence, the head over the last %d, mask token "
|
||||
"%d, drafter window %lld\n",
|
||||
(long long)p.drafter.block, p.drafter.depth,
|
||||
(int)p.drafter.mask_token, (long long)p.drafter.window);
|
||||
s += "\n";
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- tuning (spec §15) */
|
||||
if (!p.tune_requests.empty()) {
|
||||
s += fmt("---- tuning requests: %zu (rad-tune benchmarks each on this machine)\n",
|
||||
p.tune_requests.size());
|
||||
for (const auto& t : p.tune_requests)
|
||||
s += fmt(" %-24s %-14s %2d axes %s\n", t.kernel.c_str(), t.plugin.c_str(),
|
||||
t.info ? t.info->n_tunables : 0, t.geom.str().c_str());
|
||||
s += "\n";
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- fusions (spec §2.3)
|
||||
*
|
||||
* WHICH OF THIS PROGRAM'S LAUNCHES ARE STANDING IN FOR SEVERAL OPS, AND WHAT ARE THEY.
|
||||
*
|
||||
* spec.md:19 lists "fusion coverage" as one of the seven patch classes this engine exists to
|
||||
* answer, and its answer is "fused ops are ops you can select on" -- a claim that needs a
|
||||
* number behind it, which is this section. A kernel that declares `replaces` is a kernel
|
||||
* saying, in data rather than in prose, which conventional chain it computes. That is what
|
||||
* makes it substitutable, it is what rad-check checks it against, and it is what this prints.
|
||||
*
|
||||
* Read this as coverage, not as advice to act on: an op with no fusion is not a defect, and a
|
||||
* fusion that did not fire is usually banded on purpose. What the section is for is answering
|
||||
* "what actually ran" without reading the kernel source, which is the complaint the whole
|
||||
* graph dump exists to answer. */
|
||||
{
|
||||
std::vector<std::string> lines;
|
||||
int n_fused = 0, n_ops_replaced = 0;
|
||||
for (size_t i = 1; i < p.ops.size(); ++i) {
|
||||
const OpInfo& o = p.ops[i];
|
||||
for (size_t b = 0; b < o.bands.size(); ++b) {
|
||||
for (int d = 0; d < RAD_N_DOMAINS; ++d) {
|
||||
const Resolved& r = o.bands[b].dom[d];
|
||||
if (!r || !r.row || !r.row->info || !r.row->info->replaces) continue;
|
||||
/* Walk the chain the kernel names. The hook reports its own length by
|
||||
* declining the step past the end, so there is no count to disagree with it. */
|
||||
std::string chain;
|
||||
int n_step = 0;
|
||||
for (int step = 0; step < RAD_MAX_FUSE_OPD; ++step) {
|
||||
RadFuseStep fs{};
|
||||
/* RAD_FUSE_PRESENT_ALL, and it is the honest answer here rather than a
|
||||
* shortcut. A declared graph records which OPS were declared and at what
|
||||
* geometry; it does not record which optional operands each issue passes,
|
||||
* because that is a property of a step and this dump is a property of the
|
||||
* program. So the kernel is asked to describe the chain for the operand set
|
||||
* its own description publishes, which is exactly what the constant means,
|
||||
* and the row below is read as "what this kernel stands in for" rather than
|
||||
* as "what ran on the last token". */
|
||||
const int st = r.row->info->replaces(r.geom.params(), r.geom.n_params(),
|
||||
RAD_FUSE_PRESENT_ALL,
|
||||
step, &fs);
|
||||
if (st != RAD_OK) break;
|
||||
if (!fs.op) break;
|
||||
chain += (chain.empty() ? "" : " -> ");
|
||||
chain += fs.op;
|
||||
++n_step;
|
||||
}
|
||||
if (n_step < 2) continue; /* a one-op "chain" is not a fusion */
|
||||
++n_fused;
|
||||
n_ops_replaced += n_step;
|
||||
lines.push_back(fmt(" %-24s %-28s %s", o.op.c_str(), r.row->info->name,
|
||||
chain.c_str()));
|
||||
}
|
||||
}
|
||||
}
|
||||
if (n_fused > 0) {
|
||||
std::sort(lines.begin(), lines.end());
|
||||
lines.erase(std::unique(lines.begin(), lines.end()), lines.end());
|
||||
s += fmt("---- fusions: %d resolved kernel(s) stand in for %d op(s)\n",
|
||||
n_fused, n_ops_replaced);
|
||||
s += " each row is a kernel and the conventional chain it declares it computes;\n"
|
||||
" rad-check runs that chain out of the same plugin and compares the bytes\n";
|
||||
for (const std::string& l : lines) s += l + "\n";
|
||||
s += "\n";
|
||||
}
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- plugin notes */
|
||||
if (!p.notes.empty()) {
|
||||
s += "---- notes from the architecture plugin\n";
|
||||
for (const auto& n : p.notes) s += " " + n + "\n";
|
||||
s += "\n";
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- what did not resolve */
|
||||
if (!p.misses.empty()) {
|
||||
s += fmt("---- unresolved: %zu op/band/domain combination(s)\n", p.misses.size());
|
||||
s += " no DEVICE kernel is fatal for that band; no HOST kernel removes host-site\n"
|
||||
" placement for that op and nothing else (spec §2.1)\n";
|
||||
for (const auto& m : p.misses) s += " " + m.line() + "\n";
|
||||
s += "\n";
|
||||
}
|
||||
|
||||
if (errors && !errors->empty()) {
|
||||
s += fmt("---- declare errors: %zu\n", errors->size());
|
||||
for (const auto& e : *errors) s += " " + e + "\n";
|
||||
s += "\n";
|
||||
}
|
||||
|
||||
return s;
|
||||
}
|
||||
|
||||
void dump_graph(const Program& p, FILE* out, const std::vector<std::string>* errors) {
|
||||
std::string s = dump_graph_str(p, errors);
|
||||
fwrite(s.data(), 1, s.size(), out ? out : stderr);
|
||||
fflush(out ? out : stderr);
|
||||
}
|
||||
|
||||
|
||||
/* ================================================================== the graph, as JSON
|
||||
*
|
||||
* The same content as dump_graph_str and then some, for the server's Model view. NOT a second
|
||||
* source of truth: both walk the same Program and both call origin()/constraint_str()/the fuse
|
||||
* hook, so a kernel that reads one way in the text dump cannot read another way in the browser.
|
||||
*
|
||||
* WHY IT CARRIES MORE THAN THE TEXT DUMP. A text dump is read top to bottom and every extra
|
||||
* column costs every reader; a view with a selection has somewhere to put the detail that only
|
||||
* matters once you have pointed at something. So the flow carries the shape and the panel carries
|
||||
* everything the core knows about ONE op: what the op means (its schema doc and its operands),
|
||||
* what geometry it was declared at, which kernel won each band AND WHICH ONES LOST AND WHY, what
|
||||
* that kernel says about itself, what it stands in for, which weights it reads at what size and
|
||||
* layout, and which buffers begin and end their lives at it.
|
||||
*
|
||||
* GROUPED BY (op, band table). A 64-layer model declares the same op with the same bucket table
|
||||
* sixty-four times, and sixty-four identical rows is not more information than one row saying
|
||||
* "x64" -- it is the same information, spread over enough screen that nobody reads it. The
|
||||
* grouping key is what a reader would compare by eye: the op name and every band's resolution.
|
||||
* The per-occurrence facts (which weights, which buffers, which op index) are those of the FIRST
|
||||
* declaration in the group and are labelled as such in the page. */
|
||||
|
||||
/* A RadFuseStep's own geometry, which is NOT the fused op's -- `qk_norm_rope_gate` replaces an
|
||||
* rmsnorm at M = T * n_head, and nothing in the fused op's parameter list is that product. */
|
||||
static std::string params_str(const RadParam* p, int n) {
|
||||
std::string s;
|
||||
for (int i = 0; i < n; ++i) {
|
||||
if (!p[i].key) continue;
|
||||
if (!s.empty()) s += " ";
|
||||
switch (p[i].kind) {
|
||||
case RAD_P_INT: s += fmt("%s=%lld", p[i].key, p[i].ival); break;
|
||||
case RAD_P_STR: s += fmt("%s=%s", p[i].key, p[i].sval ? p[i].sval : ""); break;
|
||||
case RAD_P_F64: s += fmt("%s=%g", p[i].key, p[i].dval); break;
|
||||
case RAD_P_RANGE: s += fmt("%s=[%lld,%lld]", p[i].key, p[i].ival, p[i].ihi); break;
|
||||
default: s += p[i].key; break;
|
||||
}
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
/* The chain this kernel declares it computes, WITH each step's geometry. The names alone are the
|
||||
* advisory; the geometries are what make it checkable, and they are the part a reader cannot
|
||||
* derive. */
|
||||
static json fuse_steps(const Resolved& r) {
|
||||
json out = json::array();
|
||||
if (!r || !r.row || !r.row->info || !r.row->info->replaces) return out;
|
||||
for (int step = 0; step < RAD_MAX_FUSE_OPD; ++step) {
|
||||
RadFuseStep fs{};
|
||||
/* RAD_FUSE_PRESENT_ALL -- see the long note at the same call in dump_graph_str: a declared
|
||||
* graph records which ops were declared and at what geometry, not which optional operands
|
||||
* each issue passes, so the kernel is asked to describe the chain for the operand set its
|
||||
* own description publishes. */
|
||||
if (r.row->info->replaces(r.geom.params(), r.geom.n_params(),
|
||||
RAD_FUSE_PRESENT_ALL, step, &fs) != RAD_OK) break;
|
||||
if (!fs.op) break;
|
||||
json j;
|
||||
j["op"] = fs.op;
|
||||
j["params"] = params_str(fs.p, fs.n_p);
|
||||
out.push_back(std::move(j));
|
||||
}
|
||||
if (out.size() < 2) return json::array(); /* a one-op "chain" is not a fusion */
|
||||
return out;
|
||||
}
|
||||
|
||||
/* WHAT THIS KERNEL CAN DESCRIBE ABOUT ITSELF. Every one of these is an optional ABI hook, and
|
||||
* which of them a row supplies decides what the tools around it can do: no `opd_shape` and
|
||||
* rad-check skips the row by name, no `unrelayout` and a dense oracle has nothing to compare
|
||||
* against, no `replaces` and a fusion's claim stays prose. A reader asking "why does rad-check
|
||||
* skip this" is asking exactly this list. */
|
||||
static json kernel_hooks(const RadKernelInfo* k) {
|
||||
json h = json::array();
|
||||
if (k->init) h.push_back("init");
|
||||
if (k->scratch) h.push_back("scratch");
|
||||
if (k->layout) h.push_back("layout");
|
||||
if (k->relayout) h.push_back("relayout");
|
||||
if (k->unrelayout) h.push_back("unrelayout");
|
||||
if (k->opd_shape) h.push_back("opd_shape");
|
||||
if (k->replaces) h.push_back("replaces");
|
||||
return h;
|
||||
}
|
||||
|
||||
static json resolved_json(const Resolved& r) {
|
||||
if (!r || !r.row || !r.row->info) return nullptr;
|
||||
const RadKernelInfo* k = r.row->info;
|
||||
json j;
|
||||
j["kernel"] = k->name ? k->name : "?";
|
||||
j["plugin"] = r.row->plugin;
|
||||
j["priority"] = k->priority;
|
||||
j["geometry"] = r.geom.str();
|
||||
j["domain"] = bld_domain_name(k->domain);
|
||||
/* The kernel's own prose. It is written by the person who wrote the kernel and it is the only
|
||||
* sentence in this whole structure that a reader does not have to reconstruct. */
|
||||
if (k->family && *k->family) j["family"] = k->family;
|
||||
if (k->computes && *k->computes) j["computes"] = k->computes;
|
||||
if (k->shape && *k->shape) j["shape"] = k->shape;
|
||||
if (k->dtypes && *k->dtypes) j["dtypes"] = k->dtypes;
|
||||
if (r.scratch_bytes) j["scratch"] = r.scratch_bytes;
|
||||
if (k->n_tunables > 0) {
|
||||
j["tuned"] = r.choice;
|
||||
j["tuned_source"] = r.tune_source.empty() ? "axis defaults" : r.tune_source;
|
||||
/* EVERY AXIS AND ITS WHOLE RANGE, not just what was chosen: "this kernel has these axes,
|
||||
the tuner timed the legal points of them and picked these" is the sentence rad-tune
|
||||
exists to produce, and the ranges are what make it one. It is also how a reader sees
|
||||
that an axis HAS no alternatives at this shape, which is the difference between a tuned
|
||||
choice and a forced one. */
|
||||
json ax = json::array();
|
||||
int64_t space = 1;
|
||||
for (int i = 0; i < k->n_tunables; ++i) {
|
||||
const RadTunable& t = k->tunables[i];
|
||||
json a;
|
||||
a["key"] = t.key ? t.key : "?";
|
||||
a["default"] = t.deflt;
|
||||
if (t.doc && *t.doc) a["doc"] = t.doc;
|
||||
json vals = json::array();
|
||||
for (int v = 0; v < t.n_values; ++v) vals.push_back(t.values[v]);
|
||||
a["values"] = std::move(vals);
|
||||
ax.push_back(std::move(a));
|
||||
space *= (int64_t)t.n_values;
|
||||
}
|
||||
j["tunables"] = std::move(ax);
|
||||
j["tune_space"] = space;
|
||||
}
|
||||
/* WHY THIS KERNEL: the constraints it declares, which are exactly what selection matched it
|
||||
* on. A reader asking "why did this one win" is asking three things -- what it demanded, who
|
||||
* else wanted the row, and what beat them -- and the first is here, the second is in the
|
||||
* band's `considered`, and the third is `priority`. */
|
||||
json cons = json::array();
|
||||
for (int i = 0; i < k->n_constraints; ++i) cons.push_back(constraint_str(k->constraints[i]));
|
||||
j["constraints"] = std::move(cons);
|
||||
j["hooks"] = kernel_hooks(k);
|
||||
|
||||
/* Names only, for the flow's chip and the filter's haystack; the steps carry the geometries. */
|
||||
json names = json::array();
|
||||
json steps = fuse_steps(r);
|
||||
for (const json& st : steps) names.push_back(st["op"]);
|
||||
j["replaces"] = std::move(names);
|
||||
j["fuse_steps"] = std::move(steps);
|
||||
return j;
|
||||
}
|
||||
|
||||
/* WHO ELSE WANTED THIS BAND, AND WHAT REFUSED THEM.
|
||||
*
|
||||
* The selector already builds this list -- SelectionTrace::candidates carries every row it walked
|
||||
* with the constraint that turned it away -- and build_bands keeps only the miss reason out of it.
|
||||
* Recovering it here is what makes selection legible: "gemm_nt_q M <= 64 went to
|
||||
* r4d_gemm_fp8_narrow, and r4d_gemm_fp8_tiled wanted it too and lost on priority, and the ref row
|
||||
* lost on the domain" is the whole of selection in one table.
|
||||
*
|
||||
* Recomputed rather than stored. Keeping the candidates on every Band would hold a few megabytes
|
||||
* of strings for the life of the process to answer a question nobody asks until they open a
|
||||
* browser; asking the selector again costs one pass over one op's rows, once per DISTINCT band
|
||||
* table -- which on a 64-layer model is tens of tables, not one per declared op. `record = false`
|
||||
* so the selection table's "asked" counts stay a record of what the engine asked for, not of what
|
||||
* the graph dump asked on its behalf. */
|
||||
static json considered_json(Registry& reg, const OpInfo& o, const Band& b, int dom) {
|
||||
Geometry q = o.base;
|
||||
if (!o.ranged_key.empty()) q.set_i(o.ranged_key, b.hi == INT64_MAX ? o.range_hi : b.hi);
|
||||
SelectionTrace t;
|
||||
reg.select(o.op, q, dom, &t, /*record=*/false);
|
||||
|
||||
json out = json::array();
|
||||
for (const SelectionTrace::Candidate& c : t.candidates) {
|
||||
json j;
|
||||
j["kernel"] = c.kernel;
|
||||
j["plugin"] = c.plugin;
|
||||
j["priority"] = c.priority;
|
||||
j["ok"] = c.ok;
|
||||
j["why"] = c.why;
|
||||
out.push_back(std::move(j));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/* WHAT THE OP MEANS, from the schema the plugin hierarchy agreed on. The operand list is the part
|
||||
* that pays: `RadArgs.t` is positional, and a reader looking at a fused kernel's `from` wiring
|
||||
* has no way to know which slot is which without it. */
|
||||
static json schema_json(const RadOpSchema* s) {
|
||||
if (!s) return nullptr;
|
||||
json j;
|
||||
if (s->doc && *s->doc) j["doc"] = s->doc;
|
||||
json ps = json::array();
|
||||
for (int i = 0; i < s->n_params; ++i) {
|
||||
json p;
|
||||
p["key"] = s->params[i].key ? s->params[i].key : "?";
|
||||
p["type"] = s->params[i].type == RAD_P_STR ? "str" : "int";
|
||||
p["need"] = s->params[i].required == RAD_REQUIRED ? "required"
|
||||
: s->params[i].required == RAD_DERIVED ? "derived" : "optional";
|
||||
ps.push_back(std::move(p));
|
||||
}
|
||||
j["params"] = std::move(ps);
|
||||
json os = json::array();
|
||||
for (int i = 0; i < s->n_operands; ++i) {
|
||||
const int role = s->operands[i].role;
|
||||
json p;
|
||||
p["name"] = s->operands[i].name ? s->operands[i].name : "?";
|
||||
p["role"] = role == RAD_OPD_OUT ? "out" : role == RAD_OPD_INOUT ? "inout"
|
||||
: role == RAD_OPD_WEIGHT ? "weight" : role == RAD_OPD_WTAB ? "wtab" : "in";
|
||||
p["optional"] = s->operands[i].optional != 0;
|
||||
os.push_back(std::move(p));
|
||||
}
|
||||
j["operands"] = std::move(os);
|
||||
return j;
|
||||
}
|
||||
|
||||
static std::string shape_str(const int64_t* dims, uint32_t rank) {
|
||||
if (!rank) return "";
|
||||
std::string s;
|
||||
for (uint32_t i = 0; i < rank; ++i) s += (i ? " x " : "") + std::to_string((long long)dims[i]);
|
||||
return s;
|
||||
}
|
||||
|
||||
/* The weights ONE declaration of this op reads, with the two facts a reader is actually after:
|
||||
* how big it is where it lives, and what layout the winning kernel demanded -- which is why the
|
||||
* stored bytes may not be the logical ones. */
|
||||
static json weight_json(const WeightInfo& w) {
|
||||
json j;
|
||||
j["name"] = w.name;
|
||||
j["bytes"] = w.stored_bytes;
|
||||
j["logical"] = w.logical_bytes;
|
||||
j["dtype"] = rad_dtype_name(w.stored_dtype);
|
||||
j["shape"] = shape_str(w.stored_shape, w.stored_rank);
|
||||
j["layout"] = w.layout_tag.empty() ? std::string("as declared") : w.layout_tag;
|
||||
j["access"] = bld_access_name(w.decl.access);
|
||||
j["tier"] = tier_name(w.tier);
|
||||
j["site"] = site_name(w.site);
|
||||
j["layer"] = w.decl.group.layer;
|
||||
if (w.decl.group.expert >= 0) j["expert"] = w.decl.group.expert;
|
||||
return j;
|
||||
}
|
||||
|
||||
std::string dump_graph_json(const Program& p) {
|
||||
Registry& reg = rad_tools_registry();
|
||||
json root;
|
||||
json meta;
|
||||
meta["arch"] = p.meta.arch_id ? p.meta.arch_id : "";
|
||||
meta["name"] = p.meta.name ? p.meta.name : "";
|
||||
meta["quant"] = p.meta.quant ? p.meta.quant : "";
|
||||
meta["n_layers"] = p.meta.n_layers;
|
||||
meta["n_embd"] = p.meta.n_embd;
|
||||
meta["n_vocab"] = p.meta.n_vocab;
|
||||
meta["rank"] = p.ctx.rank;
|
||||
meta["world"] = p.ctx.world_size;
|
||||
meta["max_tok"] = p.ctx.max_tok;
|
||||
meta["max_seqs"] = p.ctx.max_seqs;
|
||||
root["model"] = std::move(meta);
|
||||
|
||||
int64_t wtotal = 0;
|
||||
for (size_t i = 1; i < p.weights.size(); ++i) wtotal += p.weights[i].stored_bytes;
|
||||
|
||||
json counts;
|
||||
counts["ops"] = (int64_t)p.ops.size() - 1;
|
||||
counts["weights"] = (int64_t)p.weights.size() - 1;
|
||||
counts["buffers"] = (int64_t)p.buffers.size() - 1;
|
||||
counts["kv_groups"] = (int64_t)p.kv_groups.size();
|
||||
counts["weight_bytes"] = wtotal;
|
||||
counts["arena_bytes"] = p.arena_bytes;
|
||||
counts["host_arena_bytes"] = p.host_arena_bytes;
|
||||
counts["scratch_bytes"] = p.scratch_bytes;
|
||||
root["counts"] = std::move(counts);
|
||||
|
||||
/* THE PLUGIN HIERARCHY, which is the answer to "where did this kernel come from" one level up
|
||||
* from the kernel row: an override is a plugin ahead of the default in this list, and a reader
|
||||
* who sees `libref` winning a row wants to know what was ahead of it. */
|
||||
json plugs = json::array();
|
||||
for (const Plugin& pl : reg.plugins()) {
|
||||
json j;
|
||||
j["name"] = pl.name;
|
||||
j["order"] = pl.order;
|
||||
j["version"] = pl.version;
|
||||
j["kernels"] = pl.n_kernels;
|
||||
j["schemas"] = pl.n_schemas;
|
||||
if (!pl.description.empty()) j["description"] = pl.description;
|
||||
if (!pl.build_target.empty()) j["build_target"] = pl.build_target;
|
||||
if (!pl.arch_id.empty()) j["arch"] = pl.arch_id + (pl.arch_quant.empty()
|
||||
? std::string() : " " + pl.arch_quant);
|
||||
plugs.push_back(std::move(j));
|
||||
}
|
||||
root["plugins"] = std::move(plugs);
|
||||
|
||||
/* One entry per distinct (op, band table), with how many declarations collapsed into it. */
|
||||
std::vector<std::string> order; /* unique keys, first-seen order */
|
||||
std::vector<std::string> seq; /* every declared op, in order, by key */
|
||||
std::unordered_map<std::string, json> group;
|
||||
std::unordered_map<std::string, int64_t> tally;
|
||||
|
||||
const int32_t nops = (int32_t)p.ops.size() - 1;
|
||||
|
||||
for (size_t i = 1; i < p.ops.size(); ++i) {
|
||||
const OpInfo& o = p.ops[i];
|
||||
json bands = json::array();
|
||||
std::string key = o.op;
|
||||
for (const Band& b : o.bands) {
|
||||
json jb;
|
||||
jb["span"] = b.span;
|
||||
jb["hi"] = b.hi; /* the page picks the widest band as the node's headline */
|
||||
for (int d = 0; d < RAD_N_DOMAINS; ++d) {
|
||||
json rj = resolved_json(b.dom[d]);
|
||||
const char* dn = bld_domain_name(d);
|
||||
if (!rj.is_null()) jb[dn] = std::move(rj);
|
||||
else if (!b.miss[d].empty()) jb[std::string(dn) + "_miss"] = b.miss[d];
|
||||
}
|
||||
/* The grouping key is formed BEFORE the candidate lists go on, so two declarations
|
||||
* that resolved identically stay one group: `considered` is a function of the op and
|
||||
* the band, so it cannot differ between them, and hashing it would only cost. */
|
||||
key += "|" + jb.dump();
|
||||
for (int d = 0; d < RAD_N_DOMAINS; ++d)
|
||||
jb[std::string(bld_domain_name(d)) + "_considered"] =
|
||||
considered_json(reg, o, b, d);
|
||||
bands.push_back(std::move(jb));
|
||||
}
|
||||
seq.push_back(key);
|
||||
auto it = group.find(key);
|
||||
if (it != group.end()) { tally[key] += 1; continue; }
|
||||
|
||||
json j;
|
||||
j["op"] = o.op;
|
||||
j["index"] = o.index;
|
||||
j["geometry"] = o.base.str();
|
||||
j["ranged"] = o.ranged_key;
|
||||
if (!o.ranged_key.empty()) { j["range_lo"] = o.range_lo; j["range_hi"] = o.range_hi; }
|
||||
j["issued"] = o.issued;
|
||||
j["schema"] = schema_json(o.schema ? o.schema : reg.schema(o.op));
|
||||
|
||||
json ws = json::array();
|
||||
for (rad_weight w : o.weights)
|
||||
if (w && w < p.weights.size()) ws.push_back(weight_json(p.weights[w]));
|
||||
j["weights"] = std::move(ws);
|
||||
|
||||
/* THE BUFFERS THIS OP BEGINS AND ENDS. Read off the plan rather than off a second
|
||||
* bookkeeping structure, exactly as the text dump does: a transient whose live range
|
||||
* begins here is one this op defines, and one whose range ends here is storage the arena
|
||||
* hands to something else after it. A buffer live for the whole program is one nothing
|
||||
* declared a use for, and pinning it on the first op would be inventing a fact. */
|
||||
json writes = json::array(), frees = json::array();
|
||||
for (size_t bi = 1; bi < p.buffers.size(); ++bi) {
|
||||
const BufferInfo& bf = p.buffers[bi];
|
||||
if (bf.decl.kind != RAD_BUF_TRANSIENT) continue;
|
||||
if (bf.first_def <= 0 && bf.last_use >= nops) continue;
|
||||
if (bf.first_def != (int32_t)i && bf.last_use != (int32_t)i) continue;
|
||||
json jb;
|
||||
jb["name"] = bf.name;
|
||||
jb["bytes"] = bf.bytes;
|
||||
jb["domain"] = bld_domain_name(bf.decl.domain);
|
||||
jb["live"] = fmt("[%d, %d]", bf.first_def, bf.last_use);
|
||||
if (bf.first_def == (int32_t)i) writes.push_back(std::move(jb));
|
||||
else frees.push_back(std::move(jb));
|
||||
}
|
||||
j["writes"] = std::move(writes);
|
||||
j["frees"] = std::move(frees);
|
||||
j["bands"] = std::move(bands);
|
||||
group.emplace(key, std::move(j));
|
||||
order.push_back(key);
|
||||
tally[key] = 1;
|
||||
}
|
||||
|
||||
std::unordered_map<std::string, int> index_of;
|
||||
json ops = json::array();
|
||||
for (const std::string& key : order) {
|
||||
index_of[key] = (int)ops.size();
|
||||
json j = group[key];
|
||||
j["count"] = tally[key];
|
||||
ops.push_back(std::move(j));
|
||||
}
|
||||
|
||||
/* THE DECLARED ORDER, as an index into `ops`. The groups above collapse the sixty-four copies
|
||||
* of a layer into one entry; a DIAGRAM needs the sequence back, and the sequence is what the
|
||||
* grouping threw away. One small integer per declared op -- six kilobytes against the two
|
||||
* megabytes that emitting every op in full would cost. */
|
||||
json ord = json::array();
|
||||
std::vector<int> first_at((size_t)ops.size(), -1), last_at((size_t)ops.size(), -1);
|
||||
for (size_t k = 0; k < seq.size(); ++k) {
|
||||
const int gi = index_of[seq[k]];
|
||||
ord.push_back(gi);
|
||||
if (first_at[(size_t)gi] < 0) first_at[(size_t)gi] = (int)k;
|
||||
last_at[(size_t)gi] = (int)k;
|
||||
}
|
||||
/* Where in the flow this group's declarations sit -- one op index is a group of sixty-four
|
||||
* telling the reader about its first copy only, and the pair says so. */
|
||||
for (size_t k = 0; k < ops.size(); ++k) {
|
||||
ops[k]["first_at"] = first_at[k];
|
||||
ops[k]["last_at"] = last_at[k];
|
||||
}
|
||||
root["ops"] = std::move(ops);
|
||||
root["order"] = std::move(ord);
|
||||
|
||||
json kvs = json::array();
|
||||
for (const KVGroupInfo& g : p.kv_groups) {
|
||||
if (g.name.empty() || g.layers.empty()) continue;
|
||||
json j;
|
||||
j["name"] = g.name;
|
||||
j["kind"] = bld_kv_kind_name(g.decl.kind);
|
||||
j["layers"] = (int64_t)g.layers.size();
|
||||
j["block_size"] = g.block_size;
|
||||
j["bytes_per_block"] = g.bytes_per_block;
|
||||
j["bytes_per_state"] = g.bytes_per_state;
|
||||
kvs.push_back(std::move(j));
|
||||
}
|
||||
root["kv_groups"] = std::move(kvs);
|
||||
|
||||
if (p.drafter.kind != RAD_DRAFT_NONE) {
|
||||
json d;
|
||||
d["name"] = p.drafter_name;
|
||||
d["kind"] = p.drafter.kind == RAD_DRAFT_BLOCK ? "block" : "serial";
|
||||
d["depth"] = p.drafter.depth;
|
||||
if (p.drafter.kind == RAD_DRAFT_BLOCK) {
|
||||
d["window"] = p.drafter.window;
|
||||
d["block"] = p.drafter.block;
|
||||
}
|
||||
root["drafter"] = std::move(d);
|
||||
}
|
||||
|
||||
json notes = json::array();
|
||||
for (const std::string& n : p.notes) notes.push_back(n);
|
||||
root["notes"] = std::move(notes);
|
||||
|
||||
json misses = json::array();
|
||||
for (const Program::Miss& m : p.misses) {
|
||||
json j;
|
||||
j["op"] = m.op; j["geometry"] = m.geom; j["span"] = m.span;
|
||||
j["domain"] = bld_domain_name(m.domain); j["why"] = m.why;
|
||||
misses.push_back(std::move(j));
|
||||
}
|
||||
root["misses"] = std::move(misses);
|
||||
return root.dump();
|
||||
}
|
||||
|
||||
} /* namespace rad */
|
||||
@@ -0,0 +1,381 @@
|
||||
/* startup.cpp -- the tools' seam onto core/plugin and core/build, and the shared CLI plumbing.
|
||||
*
|
||||
* rad-convert, rad-check and rad-tune are the engine's startup with a different last step, so they
|
||||
* do not get their own loader: they call the same Registry and the same Builder the engine will,
|
||||
* through the two functions below. A tool that resolved kernels differently from the engine would
|
||||
* be a tool whose answers are about a different program.
|
||||
*/
|
||||
#include "build/startup.h"
|
||||
#include "build/rad_build.h"
|
||||
#include "format/tunecache.h"
|
||||
#include "plugin/registry.h"
|
||||
|
||||
#include <sys/stat.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstdlib>
|
||||
|
||||
namespace rad {
|
||||
|
||||
/* One Registry for the life of the process. A Resolved, a Band and a KernelRow all point into a
|
||||
* plugin's static tables, and the Program outlives the call that built it, so the registry cannot
|
||||
* be a local. registry.h says the same thing about the engine. */
|
||||
Registry& rad_tools_registry() {
|
||||
static Registry r;
|
||||
return r;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ the reference-kernel gate */
|
||||
|
||||
/* An op counts as "on the reference" when NO domain and NO band offers a kernel from a library that
|
||||
* is not a reference implementation (RadPluginReferenceFn).
|
||||
*
|
||||
* The narrower reading matters. A reference library is usually a HOST plugin, so every op's host
|
||||
* band resolves to it -- that is what makes the host domain work at all, and flagging it would
|
||||
* flag the entire vocabulary of every model. What is a hazard is an op a reference is the ONLY
|
||||
* implementation of: wherever the planner puts it, it runs naive generic code.
|
||||
*
|
||||
* The op is still counted once per declared instance, because "rmsnorm resolves to ref" reads very
|
||||
* differently at one layer and at sixty-four. */
|
||||
int rad_reference_ops(const Program& p, std::vector<std::string>* out) {
|
||||
int n = 0;
|
||||
for (size_t i = 1; i < p.ops.size(); ++i) {
|
||||
const OpInfo& oi = p.ops[i];
|
||||
bool real = false;
|
||||
for (const Band& b : oi.bands)
|
||||
for (int d = 0; d < RAD_N_DOMAINS && !real; ++d)
|
||||
if (b.dom[d] && b.dom[d].row && !b.dom[d].row->reference)
|
||||
real = true;
|
||||
if (real) continue;
|
||||
++n;
|
||||
/* By op NAME and deduplicated: a 64-layer model declares sixty-four identical rmsnorms and
|
||||
* the useful sentence is "rmsnorm has no kernel", not sixty-four copies of it. */
|
||||
if (out && std::find(out->begin(), out->end(), oi.op) == out->end())
|
||||
out->push_back(oi.op);
|
||||
}
|
||||
return n;
|
||||
}
|
||||
|
||||
int rad_gate_reference_kernels(const Program& p, bool allow, const char* what) {
|
||||
std::vector<std::string> ops;
|
||||
const int n = rad_reference_ops(p, &ops);
|
||||
if (n == 0) return RAD_OK;
|
||||
|
||||
std::string list;
|
||||
for (size_t i = 0; i < ops.size(); ++i) { if (i) list += ", "; list += ops[i]; }
|
||||
/* Which reference libraries those are, by the name each one gave itself. */
|
||||
std::vector<std::string> refs;
|
||||
for (size_t i = 1; i < p.ops.size(); ++i)
|
||||
for (const Band& b : p.ops[i].bands)
|
||||
for (int d = 0; d < RAD_N_DOMAINS; ++d)
|
||||
if (b.dom[d] && b.dom[d].row && b.dom[d].row->reference &&
|
||||
std::find(refs.begin(), refs.end(), b.dom[d].row->plugin) == refs.end())
|
||||
refs.push_back(b.dom[d].row->plugin);
|
||||
std::string libs;
|
||||
for (size_t i = 0; i < refs.size(); ++i) { if (i) libs += ", "; libs += refs[i]; }
|
||||
|
||||
if (allow) {
|
||||
RAD_WARN("%d declared op(s) resolve to a reference implementation (%s) and "
|
||||
"--debug-accept-reference-kernels was passed, so %s continues. This is not a "
|
||||
"production configuration: %zu distinct op(s) run the naive generic "
|
||||
"implementation -- %s", n, libs.c_str(), what, ops.size(), list.c_str());
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
RAD_ERR("%d declared op(s) resolve only to a reference implementation (%s).\n"
|
||||
" %zu distinct op(s): %s\n"
|
||||
" A reference library exists to be an ORACLE and a last resort, not a deployment. "
|
||||
"Falling back to it silently is a model running orders of magnitude below the machine "
|
||||
"with nothing in the output to say so, which is the failure spec §17 exists to prevent "
|
||||
"-- so %s refuses rather than serving it.\n"
|
||||
" Either supply a kernel plugin that covers these ops, or pass "
|
||||
"--debug-accept-reference-kernels to accept the cost deliberately.",
|
||||
n, libs.c_str(), ops.size(), list.c_str(), what);
|
||||
return RAD_E_NOKERNEL;
|
||||
}
|
||||
|
||||
std::vector<std::string> rad_home_dirs(const std::string& home) {
|
||||
std::vector<std::string> out;
|
||||
size_t i = 0;
|
||||
while (i <= home.size()) {
|
||||
size_t e = home.find(':', i);
|
||||
if (e == std::string::npos) e = home.size();
|
||||
if (e > i) out.push_back(home.substr(i, e - i));
|
||||
i = e + 1;
|
||||
}
|
||||
if (out.empty()) out.push_back(".");
|
||||
return out;
|
||||
}
|
||||
|
||||
std::string rad_home_file(const std::string& home, const std::string& rel) {
|
||||
const std::vector<std::string> dirs = rad_home_dirs(home);
|
||||
for (const std::string& d : dirs) {
|
||||
struct stat st {};
|
||||
if (stat((d + "/" + rel).c_str(), &st) == 0) return d + "/" + rel;
|
||||
}
|
||||
return dirs.front() + "/" + rel;
|
||||
}
|
||||
|
||||
/* The homes on the path that have the directory `sub`. */
|
||||
static std::vector<std::string> home_subdirs(const std::string& home, const char* sub) {
|
||||
std::vector<std::string> out;
|
||||
for (const std::string& d : rad_home_dirs(home)) {
|
||||
struct stat st {};
|
||||
const std::string p = d + "/" + sub;
|
||||
if (stat(p.c_str(), &st) == 0 && S_ISDIR(st.st_mode)) out.push_back(p);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
int rad_tools_load_plugins(const std::string& home, const std::vector<std::string>& hierarchy,
|
||||
const std::string& arch_id, const std::string& quant,
|
||||
LoadedPlugins* out) {
|
||||
if (!out) return RAD_E_INVAL;
|
||||
*out = LoadedPlugins{};
|
||||
|
||||
Registry& r = rad_tools_registry();
|
||||
|
||||
/* Kernels first and in hierarchy order, then architectures. The order matters for kernels and
|
||||
* not for architectures: no two architecture plugins may claim the same id, so there is
|
||||
* nothing for a hierarchy to break a tie between.
|
||||
*
|
||||
* A home on the path need not have every directory -- one holding a single kernel library is
|
||||
* the ordinary shape of a home of one's own -- but kernels/ and architectures/ must each be
|
||||
* somewhere on it, or the scan names the first home's as missing. */
|
||||
const std::string first = rad_home_dirs(home).front();
|
||||
std::vector<std::string> kdirs = home_subdirs(home, "kernels");
|
||||
if (kdirs.empty()) kdirs.push_back(first + "/kernels");
|
||||
int s = r.load_dirs(kdirs, hierarchy);
|
||||
if (s < 0) return s;
|
||||
|
||||
std::vector<std::string> adirs = home_subdirs(home, "architectures");
|
||||
if (adirs.empty()) adirs.push_back(first + "/architectures");
|
||||
s = r.load_dirs(adirs, {});
|
||||
if (s < 0) return s;
|
||||
|
||||
/* The quantisers, which rad-convert drives and the oracle decodes through for a scheme the
|
||||
* core does not define. A home without the directory has none, which is not an error for an
|
||||
* engine serving a container whose encodings the core decodes itself. */
|
||||
const std::vector<std::string> qdirs = home_subdirs(home, "quantizers");
|
||||
if (!qdirs.empty()) {
|
||||
s = r.load_dirs(qdirs, {});
|
||||
if (s < 0) return s;
|
||||
}
|
||||
|
||||
RAD_TRY(r.check_complete());
|
||||
|
||||
/* The tuning cache, once the kernel set is known. A missing file is not an error and leaves
|
||||
* every shape on its plugin's first variant; a present one moves the shapes rad-tune measured.
|
||||
* Reported when it has rows, because "which variant am I running" is otherwise a question with
|
||||
* no visible answer -- --debug-graph prints the per-shape source beside each kernel. */
|
||||
const std::string tune = rad_home_file(home, TuneCache::rel_path(rad_machine_key()));
|
||||
const std::string tune_home = tune.substr(0, tune.size() - TuneCache::rel_path(rad_machine_key()).size() - 1);
|
||||
const int n_tuned = r.load_tune(tune_home);
|
||||
if (n_tuned > 0) RAD_INFO("tune cache: %d row(s) from %s", n_tuned, tune.c_str());
|
||||
|
||||
/* The selection key is the PAIR (spec §2.4). An exact match on both halves, with no fallback:
|
||||
* a quantised container handed to a plugin that declares dense weights fails later, at the
|
||||
* name map, with a worse message than the one below. */
|
||||
for (const Plugin& p : r.plugins()) {
|
||||
if (p.kind == RAD_PLUGIN_KERNEL) {
|
||||
out->kernels.push_back({ p.name, p.version });
|
||||
} else if (p.kind == RAD_PLUGIN_ARCH && !arch_id.empty() && p.arch_id == arch_id &&
|
||||
p.arch_quant == quant) {
|
||||
out->arch_plugin = p.name;
|
||||
out->arch_version = p.version;
|
||||
out->arch_id = p.arch_id;
|
||||
out->arch_quant = p.arch_quant;
|
||||
}
|
||||
}
|
||||
|
||||
if (out->kernels.empty()) {
|
||||
RAD_ERR("no kernel plugin loaded from %s/kernels. Every weight's layout comes from the "
|
||||
"kernel that will read it, so there is nothing to lay a container out for.",
|
||||
home.c_str());
|
||||
return RAD_E_NOKERNEL;
|
||||
}
|
||||
if (!arch_id.empty() && out->arch_plugin.empty()) {
|
||||
/* No match, no model (spec §1). Name what IS installed AND at which quantisation, because
|
||||
* the two causes look identical otherwise: an architecture nobody has written a plugin for,
|
||||
* and one that is written but only for another weight format. The second is the common one
|
||||
* for a family with more than one member. */
|
||||
std::string have, same;
|
||||
for (const Plugin& p : r.plugins()) {
|
||||
if (p.kind != RAD_PLUGIN_ARCH) continue;
|
||||
const std::string q = p.arch_quant.empty() ? "(unquantised)" : p.arch_quant;
|
||||
if (!have.empty()) have += ", ";
|
||||
have += p.arch_id + " @ " + q;
|
||||
if (p.arch_id == arch_id) { if (!same.empty()) same += ", "; same += q; }
|
||||
}
|
||||
if (!same.empty())
|
||||
RAD_ERR("no architecture plugin claims '%s' at quantisation '%s'. '%s' is served at: "
|
||||
"%s. Either the container's quantisation descriptor is not one this project "
|
||||
"has a plugin for, or the container was written before the descriptor was "
|
||||
"recorded -- rad-info prints it.",
|
||||
arch_id.c_str(), quant.empty() ? "(unquantised)" : quant.c_str(),
|
||||
arch_id.c_str(), same.c_str());
|
||||
else
|
||||
RAD_ERR("no architecture plugin claims '%s'. %s/architectures offers: %s",
|
||||
arch_id.c_str(), home.c_str(), have.empty() ? "(none)" : have.c_str());
|
||||
return RAD_E_NOTFOUND;
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* WHAT THE ARCHITECTURE PLUGIN SAYS BEFORE IT DECLARES. Optional export: a plugin without one
|
||||
* leaves every field zero, which the caller reads as "no opinion" and answers from its own
|
||||
* defaults.
|
||||
*
|
||||
* Not an error path. A probe that fails is a plugin declining to answer, not a model that cannot
|
||||
* be served -- the caller falls back to its own default and the plugin gets to refuse properly in
|
||||
* declare, where it has the whole configuration in front of it and can say why. */
|
||||
int rad_tools_probe(const LoadedPlugins& lp, const RadModelMeta& meta, RadArchProbe* out) {
|
||||
if (!out) return RAD_E_INVAL;
|
||||
*out = RadArchProbe{};
|
||||
const Plugin* ap = rad_tools_registry().plugin(lp.arch_plugin);
|
||||
if (!ap || !ap->arch_probe) return RAD_E_UNSUPPORTED;
|
||||
const int s = ap->arch_probe(&meta, out);
|
||||
if (s < 0) {
|
||||
RAD_WARN("%s: rad_arch_probe returned %s; the core will use its own defaults",
|
||||
lp.arch_plugin.c_str(), rad_strerror(s));
|
||||
*out = RadArchProbe{};
|
||||
return s;
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
const RadChatFormat* rad_tools_chat_format(const LoadedPlugins& lp, const RadModelMeta& meta) {
|
||||
const Plugin* ap = rad_tools_registry().plugin(lp.arch_plugin);
|
||||
if (!ap || !ap->arch_chat_format) return nullptr;
|
||||
return ap->arch_chat_format(&meta);
|
||||
}
|
||||
|
||||
WeightSourceFn rad_container_sources(const RadFile& f) {
|
||||
return [&f](const std::string& name, const Program&, WeightSource* out) {
|
||||
const RadFileEntry* e = f.find(name);
|
||||
if (!e) return RAD_E_NOTFOUND;
|
||||
out->enc = f.encoding(*e);
|
||||
out->rank = e->rank;
|
||||
for (int i = 0; i < RAD_MAX_RANK; ++i) out->shape[i] = e->shape[i];
|
||||
return RAD_OK;
|
||||
};
|
||||
}
|
||||
|
||||
WeightSourceFn CheckpointSources::fn() {
|
||||
return [this](const std::string& name, const Program& prog, WeightSource* out) {
|
||||
return answer(name, prog, out);
|
||||
};
|
||||
}
|
||||
|
||||
int CheckpointSources::answer(const std::string& name, const Program& prog, WeightSource* out) {
|
||||
std::lock_guard<std::mutex> lk(mu_);
|
||||
auto it = got_.find(name);
|
||||
if (it == got_.end()) {
|
||||
CkptWeight w;
|
||||
std::string why;
|
||||
const int st = ckpt_resolve(ck_, prog, name, false, &w, &why);
|
||||
/* Not found is not remembered as an answer -- declare may map the name later -- but
|
||||
* its reason is, for the loader to give if it never is. */
|
||||
if (st == RAD_E_NOTFOUND) {
|
||||
missing_[name] = why;
|
||||
return st;
|
||||
}
|
||||
missing_.erase(name);
|
||||
if (st < 0) {
|
||||
refused_[name] = why;
|
||||
return st;
|
||||
}
|
||||
it = got_.emplace(name, std::move(w)).first;
|
||||
}
|
||||
const CkptWeight& w = it->second;
|
||||
if (!w.trivial) {
|
||||
refused_[name] = w.why;
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
out->enc = w.enc;
|
||||
out->rank = w.rank;
|
||||
for (int i = 0; i < RAD_MAX_RANK; ++i) out->shape[i] = w.shape[i];
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
const CkptWeight* CheckpointSources::find(const std::string& name) const {
|
||||
std::lock_guard<std::mutex> lk(mu_);
|
||||
auto it = got_.find(name);
|
||||
return it == got_.end() || !it->second.trivial ? nullptr : &it->second;
|
||||
}
|
||||
|
||||
std::string CheckpointSources::missing(const std::string& name) const {
|
||||
std::lock_guard<std::mutex> lk(mu_);
|
||||
auto it = missing_.find(name);
|
||||
return it == missing_.end() ? std::string() : it->second;
|
||||
}
|
||||
|
||||
std::vector<std::string> CheckpointSources::refused() const {
|
||||
std::lock_guard<std::mutex> lk(mu_);
|
||||
std::vector<std::string> out;
|
||||
for (const auto& [n, why] : refused_) out.push_back(n + ": " + why);
|
||||
return out;
|
||||
}
|
||||
|
||||
int rad_tools_declare(const LoadedPlugins& lp, const RadModelMeta& meta, const RadBuildCtx& ctx,
|
||||
Program* out, const std::function<int(RadBuilder*, int64_t)>& also,
|
||||
const Program* ref, const WeightSourceFn& sources) {
|
||||
if (!out) return RAD_E_INVAL;
|
||||
|
||||
Registry& r = rad_tools_registry();
|
||||
const Plugin* ap = r.plugin(lp.arch_plugin);
|
||||
if (!ap || !ap->arch_declare) {
|
||||
RAD_ERR("architecture plugin '%s' is not loaded or exports no rad_arch_declare",
|
||||
lp.arch_plugin.c_str());
|
||||
return RAD_E_NOTFOUND;
|
||||
}
|
||||
|
||||
/* The Builder takes the Registry directly: there is no selector adapter between the two. */
|
||||
Builder b(r, meta, ctx);
|
||||
if (ref) b.set_reference(ref);
|
||||
if (sources) b.set_sources(sources);
|
||||
|
||||
int s = ap->arch_declare(&b, &meta, &ctx);
|
||||
if (s < 0) {
|
||||
RAD_ERR("%s: rad_arch_declare returned %s", lp.arch_plugin.c_str(), rad_strerror(s));
|
||||
for (const auto& e : b.errors()) RAD_ERR(" %s", e.c_str());
|
||||
return s;
|
||||
}
|
||||
|
||||
/* The sampler declares here, into the same builder and before finish(), so its ops go through
|
||||
* the same resolution as the plugin's. A sampler op that does not resolve is deliberately NOT
|
||||
* a declare failure -- a deployment that never sends `typical_p` does not need a typical
|
||||
* kernel -- so this returning negative means something structural, not a miss. */
|
||||
if (also) {
|
||||
/* THE WIDTH THE PLUGIN ACTUALLY DECLARED, handed over rather than re-derived. The sampler
|
||||
* needs to know how much vocabulary THIS RANK produces, and the one place that is a fact
|
||||
* is the logits buffer the plugin just named. Computing it a second time from n_vocab and
|
||||
* world_size puts the sharding rule in two files, and the two disagree the moment a plugin
|
||||
* stops splitting the vocabulary -- which arch/common/rad_arch.h currently does, on
|
||||
* purpose. A sampler reading 248320 logits out of a 124160-wide row is not a crash; it is
|
||||
* fluent text with the wrong tokens. */
|
||||
int64_t lw = 0;
|
||||
if (b.program().logits_buf != RAD_NULL_HANDLE &&
|
||||
(size_t)b.program().logits_buf < b.program().buffers.size()) {
|
||||
const RadBufDecl& d = b.program().buffers[b.program().logits_buf].decl;
|
||||
if (d.rank > 0) lw = d.shape[d.rank - 1];
|
||||
}
|
||||
s = also(&b, lw);
|
||||
if (s < 0) {
|
||||
for (const auto& e : b.errors()) RAD_ERR(" %s", e.c_str());
|
||||
return s;
|
||||
}
|
||||
}
|
||||
|
||||
s = b.finish();
|
||||
/* Declare ALWAYS completes: a structural error is reported whole, not first-failure-at-the-top
|
||||
* (spec §3.1). */
|
||||
for (const auto& e : b.errors()) RAD_ERR(" %s", e.c_str());
|
||||
if (s < 0) return s;
|
||||
if (b.status() < 0) return b.status();
|
||||
|
||||
*out = std::move(b.program());
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
} /* namespace rad */
|
||||
@@ -0,0 +1,148 @@
|
||||
/* startup.h -- steps 1 through 4 of spec §1's startup sequence, shared by the engine and by every
|
||||
* tool that needs them.
|
||||
*
|
||||
* 1. Load kernel plugins from $RADIANCE_HOME/kernels/, in the configured hierarchy order.
|
||||
* 3. Look up the architecture id in $RADIANCE_HOME/architectures/.
|
||||
* 4. Declare.
|
||||
*
|
||||
* These live in core rather than in tools/ because rad-convert, rad-check and rad-tune are all
|
||||
* the engine's startup with a different last step (spec §4.2, §15, §17). Two implementations of
|
||||
* "load the plugins and run declare" would eventually disagree about hierarchy order, and the
|
||||
* hierarchy order is what decides which layout got baked into the container.
|
||||
*/
|
||||
#pragma once
|
||||
#include "rad_core.h"
|
||||
#include "format/radfile.h"
|
||||
#include "format/checkpoint.h"
|
||||
#include "plugin/registry.h"
|
||||
#include "build/rad_build.h"
|
||||
|
||||
#include <functional>
|
||||
#include <map>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace rad {
|
||||
|
||||
/* A loaded plugin, as a tool names it. */
|
||||
struct PluginId { std::string name, version; };
|
||||
|
||||
struct LoadedPlugins {
|
||||
/* Kernel plugins in HIERARCHY ORDER, which is what decides selection, so a report of what ran
|
||||
* names them in it. */
|
||||
std::vector<PluginId> kernels;
|
||||
std::string arch_plugin;
|
||||
std::string arch_version;
|
||||
std::string arch_id;
|
||||
/* The other half of the key that selected it, "" for an unquantised container. */
|
||||
std::string arch_quant;
|
||||
|
||||
/* `name@version`, space separated, in hierarchy order: what a benchmark records as the
|
||||
* libraries it measured. */
|
||||
std::string libraries() const {
|
||||
std::string s;
|
||||
for (const auto& p : kernels) {
|
||||
if (!s.empty()) s += ' ';
|
||||
s += p.name + "@" + (p.version.empty() ? "0" : p.version);
|
||||
}
|
||||
return s;
|
||||
}
|
||||
};
|
||||
|
||||
/* $RADIANCE_HOME AS A SEARCH PATH: one or more homes separated by ':', the first taking precedence
|
||||
* -- a directory of one's own plugins ahead of an installation's, without copying the installation.
|
||||
* Each home holds kernels/, architectures/ and quantizers/, any of which it may lack; a plugin a
|
||||
* home earlier on the path supplies shadows one of the same file name later on it. Files that are
|
||||
* not plugins -- the tuning cache, rad-kbench's fixtures -- are read from the first home that has
|
||||
* them and written to the first home. */
|
||||
std::vector<std::string> rad_home_dirs(const std::string& home);
|
||||
/* `<home>/<rel>` for the first home on the path that has it; the first home's when none does. */
|
||||
std::string rad_home_file(const std::string& home, const std::string& rel);
|
||||
|
||||
/* The Registry loaded into is process-lifetime, because a Resolved, a Band and a KernelRow all
|
||||
* point into a plugin's static tables and the Program outlives this call. */
|
||||
/* `arch_id` and `quant` are BOTH halves of the selection key (spec §2.4, rad_builder.h): a family
|
||||
* has one plugin per weight format and they all answer the same architecture id. `quant` is the
|
||||
* container's own descriptor -- RadModelMeta::quant, RadFileHeader::quant -- and "" is the
|
||||
* unquantised case, which matches a plugin that says "" and nothing else. */
|
||||
int rad_tools_load_plugins(const std::string& radiance_home,
|
||||
const std::vector<std::string>& hierarchy,
|
||||
const std::string& arch_id,
|
||||
const std::string& quant,
|
||||
LoadedPlugins* out);
|
||||
|
||||
/* `also` declares into the SAME builder after the architecture plugin has. That is what puts the
|
||||
* sampler chain in the same Program: its ops resolve through the same hierarchy at the same
|
||||
* time as the plugin's, so a missing sampler kernel is in the same miss list rather than
|
||||
* discovered at the first request that asks for it (spec §3.1, §13). Empty for the tools --
|
||||
* rad-convert cares about the weight layout and has no sampler. */
|
||||
int rad_tools_probe(const LoadedPlugins& plugins, const RadModelMeta& meta, RadArchProbe* out);
|
||||
|
||||
/* The architecture plugin's declared reply format (rad_arch_chat_format), or null when it
|
||||
* declares none and the format is to be derived from the chat template. */
|
||||
const RadChatFormat* rad_tools_chat_format(const LoadedPlugins& plugins, const RadModelMeta& meta);
|
||||
|
||||
/* `ref`, when given, makes this a SIZING declare (RadBuildCtx::shape_probe, Builder::
|
||||
* set_reference): the plugin declares against the bands `ref` resolved and nothing is selected
|
||||
* or initialised. The Program that comes back is for its buffers and nothing else. */
|
||||
/* `sources` answers rad_weight_encoding (Builder::set_sources): a container's entries, a
|
||||
* checkpoint's tensors, or a recipe. Empty, every weight is read as plain in its declared dtype. */
|
||||
int rad_tools_declare(const LoadedPlugins& plugins, const RadModelMeta& meta,
|
||||
const RadBuildCtx& ctx, Program* out,
|
||||
const std::function<int(RadBuilder*, int64_t logits_width)>& also = {},
|
||||
const Program* ref = nullptr, const WeightSourceFn& sources = {});
|
||||
|
||||
/* A container's entries as the source of every declaration's encoding. `f` must outlive the
|
||||
* declare. */
|
||||
WeightSourceFn rad_container_sources(const RadFile& f);
|
||||
|
||||
/* A CHECKPOINT AS THE SOURCE, served directly (spec §4.3): each declared weight resolved through
|
||||
* the name map once, and kept for the loader, which reads the same tensors the answer was made
|
||||
* from. Every rank declares at once, so it is locked.
|
||||
*
|
||||
* Only a TRIVIAL encoding is answered -- bf16, f16, f32, block-scaled FP8 -- because nothing is
|
||||
* quantised at load. A weight whose checkpoint form is anything else is recorded with the reason
|
||||
* and answered RAD_E_UNSUPPORTED; refused() names them after declare, and the remedy is a
|
||||
* container. */
|
||||
class CheckpointSources {
|
||||
public:
|
||||
explicit CheckpointSources(Checkpoint& ck) : ck_(ck) {}
|
||||
WeightSourceFn fn();
|
||||
/* After declare: what `name` resolved to, or null. */
|
||||
const CkptWeight* find(const std::string& name) const;
|
||||
/* Why `name` resolved to nothing, as the name map last answered it; empty if it did. */
|
||||
std::string missing(const std::string& name) const;
|
||||
/* Every weight that is not served as it stands, "name: why", sorted. */
|
||||
std::vector<std::string> refused() const;
|
||||
|
||||
private:
|
||||
int answer(const std::string& name, const Program& prog, WeightSource* out);
|
||||
Checkpoint& ck_;
|
||||
mutable std::mutex mu_;
|
||||
std::map<std::string, CkptWeight> got_;
|
||||
std::map<std::string, std::string> refused_;
|
||||
std::map<std::string, std::string> missing_;
|
||||
};
|
||||
|
||||
|
||||
/* ------------------------------------------------------------------ the reference-kernel gate */
|
||||
/* A reference library -- one that declares itself so, RadPluginReferenceFn -- is BOTH the fallback
|
||||
* that makes an unsupported model run at reduced speed and the oracle rad-kbench measures against
|
||||
* (spec §17). The first of those is a hazard in production and
|
||||
* the second is not, so which one is happening has to be a decision and not a discovery: a model
|
||||
* that silently fell back to the reference implementation for its GEMMs is a model running orders
|
||||
* of magnitude below what the machine can do, and nothing in the output says so.
|
||||
*
|
||||
* So: resolving to a reference library is FATAL unless --debug-accept-reference-kernels was
|
||||
* passed. The flag is spelled with `debug` in it because that is what it is for. */
|
||||
|
||||
int rad_reference_ops(const Program& p, std::vector<std::string>* out);
|
||||
|
||||
/* Report and refuse, or report and continue when `allow`. `what` names the caller ("serve",
|
||||
* "the container's layout") so the message says what the consequence actually is. */
|
||||
int rad_gate_reference_kernels(const Program& p, bool allow, const char* what);
|
||||
|
||||
Registry& rad_tools_registry();
|
||||
|
||||
} /* namespace rad */
|
||||
Reference in new issue
Block a user