radiance 1.7.0

- every model serves without a GPU: libavx covers every op, so `--kernels libavx` alone serves
  every shipped container
- Qwen3-ASR (zivius): speech to text on /v1/audio/transcriptions and live over /v1/realtime
- /v1/messages works with Claude Code as it ships (gearwave00001)
- a long agent conversation keeps its cached history when the client rewrites its last turn
  (manueloverride)
- a stream's first event goes out with the first token, so llama-benchy measures prefill right
- opt-in --prefill-interleave (Smellyyyy, baKon) and --prefill-span (keptn42)
- four-rank TP releases the link early; four-rank selftests and docs/TP4.md (goodman-b)
- NVFP4 and FP8 compressed-tensors imports (devmilan); tools/rad-export for finetunes and LoRA
  adapters (baKon)
- many fixes, among them lost tokens on stop strings under concurrency, keep-alive, MiniCPM5 tool
  arguments and the CPU's vision and audio encoders
- plugin ABI 17 and changed op schemas: out-of-tree plugins must be rebuilt
This commit is contained in:
Deadcode committed 2026-10-16 18:25:18 +02:00
1 parent b068190326
commit 1e968f6e1d
739 files changed
+128447 -84632

No files matched your search

+58 -87
View File
@@ -1,19 +1,16 @@
/* 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.
* lifetimes are packed into one arena sized once, so the hot path never allocates.
*
* 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.
* Two deliberate conservatisms (both in the spec): the arena is sized for max_tok, and liveness
* covers the declared list, a superset of what any step issues. A plan 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.
* The packer is greedy interval colouring, largest first: each buffer takes the lowest aligned
* offset that collides with no placed buffer whose lifetime overlaps. O(n^2) in the buffer count,
* microseconds for a few hundred activations, and within a few percent of optimal on real shapes
* (the one big activation goes first). Optimal packing is NP-hard and not worth a solver.
*/
#include "rad_build.h"
#include "rad_internal.h"
@@ -23,13 +20,11 @@
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. */
/* Every buffer starts at a 256-byte boundary: the container's sub-block alignment, and enough for
* any RDNA4 vector load (dwordx4 is 16 B). A kernel needing more alignment for 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 {
@@ -41,8 +36,8 @@ struct Item {
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. */
/* Lowest aligned offset that fits `want` without colliding with anything already placed
* (off >= 0) 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());
@@ -58,6 +53,22 @@ int64_t first_fit(const Item& want, const std::vector<Item>& placed) {
return off;
}
/* Places every item, largest first, ties by lifetime start then index, so the plan is identical
* on every rank and every run. Returns the packed extent. */
int64_t pack(std::vector<Item>& items) {
std::sort(items.begin(), items.end(), [](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;
});
int64_t end = 0;
for (Item& it : items) {
it.off = first_fit(it, items);
end = std::max(end, it.off + it.bytes);
}
return end;
}
} /* namespace */
int plan_buffers(Program& p, BufPlanReport* rep) {
@@ -79,50 +90,35 @@ int plan_buffers(Program& p, BufPlanReport* rep) {
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. */
/* No declared use: live for the whole program. */
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.
/* Each domain is coloured separately, with offsets relative to its own arena. One shared
* offset space would leave both arenas sparse and spend VRAM on 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. */
/* peak_live: what a perfect packer would reach (see BufPlanReport). */
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.
/* PERSIST survives across steps and DERIVED is written by the core before any op runs, so
* both are live for every op and share with nothing.
*
* 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. */
* They go at the bottom, transients above. A smaller step packs its transients smaller
* (plan_level) and lends the unused top of the arena to the expert slab, so the fixed region
* must sit where no level moves it: its contents outlive the step that wrote them. */
int64_t off = 0;
for (const Item& it : persist) {
p.buffers[it.idx].arena_offset = off;
@@ -132,32 +128,17 @@ int plan_buffers(Program& p, BufPlanReport* rep) {
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);
}
const int64_t tr_end = pack(transient);
for (const Item& it : transient) p.buffers[it.idx].arena_offset = fixed + it.off;
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);
}
/* The host arena has its own base pointer; these offsets are relative to it. Same packer in
* one pass: a host PERSIST is live for the whole program, so it shares with nothing. */
const int64_t host_end = pack(host);
for (const Item& it : host) p.buffers[it.idx].arena_offset = it.off;
r.host_bytes = host_end;
p.host_arena_bytes = host_end;
@@ -192,9 +173,8 @@ int plan_level(const Program& full, const Program& probe, int64_t rows, ArenaLev
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. */
/* Only the rows may shrink. Every other extent is a stride some kernel was resolved
* against at the real size. */
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",
@@ -203,36 +183,27 @@ int plan_level(const Program& full, const Program& probe, int64_t rows, ArenaLev
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. */
/* The fixed region and the host arena are the same at every level. A persistent buffer
* holds an earlier step's data, so it cannot move, and it keeps its full size: one sized
* by the step (a per-token plane written outside the op order) is only smaller at a
* smaller step, and the real 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. */
/* The real declare's liveness: the op list is the same 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(); }
if (it.lo < 0 || it.hi < it.lo) {
it.lo = 0;
it.hi = std::max<int32_t>((int32_t)full.ops.size() - 1, 0);
}
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);
}
const int64_t tr_end = pack(transient);
for (const Item& it : transient) lv.offset[it.idx] = full.arena_fixed_bytes + it.off;
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 "
+79 -137
View File
@@ -1,26 +1,21 @@
/* rad_build.h -- the declare phase (spec §3.1). The architecture plugin states everything it will
* ever do; this is what receives it.
/* rad_build.h -- the declare phase (spec §3.1): receives everything the architecture plugin will
* ever do.
*
* 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, band and domain
* that resolved to nothing is collected with the constraint that refused it and reported at the
* end, which shows whether a plugin or a model is missing.
*
* 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. After declare the model is static (every op, its kernel, the
* weights it touches, the order). The bucket table, weight manifest, buffer plan and KV block
* sizes are built once here, so the step path indexes tables.
*
* 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.
* The kernel hierarchy, op schemas, constraint matching and bucket boundaries belong to
* core/plugin/. The Builder calls Registry::validate and Registry::build_bands rather than
* reimplementing them, so selector and builder cannot drift apart.
*
* 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.
* Lifetime: every KernelRow, Resolved and RadOpSchema in the Program points into a plugin's static
* tables, which the Registry dlclose()s. Neither the Builder nor the Program may outlive the
* Registry.
*/
#pragma once
#include "plugin/registry.h"
@@ -33,32 +28,27 @@
#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. */
/* The plugin's handle. rad_builder.h only forward-declares it; as a base of rad::Builder, the C
* shims reach the Builder with a static_cast. */
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. */
/* Process-lifetime storage for declared names. RadNameMap and RadKernelInfo hold raw
* `const char*` and the Program outlives the Builder, so the strings are interned: a few thousand,
* deduplicated, never freed. Owning them in RadNameMap would be an ABI change. */
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. */
/* Names for the enums the graph dump prints; `bld_` prefixed to keep them apart from the
* planner's tier_name and site_name in rad_core.h. */
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. */
/* Packing results for the --debug-graph report. `sum_bytes` (no sharing) and `peak_live` (a
* perfect packer) bracket the arena and show what the greedy pass left unused. */
struct BufPlanReport {
int64_t transient_bytes = 0; /* the packed, shared region */
int64_t persist_bytes = 0; /* PERSIST + DERIVED: their own non-overlapping region */
@@ -69,37 +59,37 @@ struct BufPlanReport {
};
/* 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.
* treated as live for the whole program, which is sound.
*
* 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. */
/* The arena layout for steps of at most `rows` tokens: the real plan's buffers, the fixed region
* unchanged, and the transients repacked, so the arena past `end` is unused by such a 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. */
/* Lay out `probe`'s buffers (a sizing declare at `rows`) over `full`'s. Refused, with the reason
* in `why`, unless both declares describe the same buffers with only fewer rows; otherwise they
* 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. */
/* Bytes a declared buffer occupies. 0 means the core cannot size it: a plugin-private dtype, legal
* for a weight (the kernel's layout hook sizes it) but 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. */
/* What the model holds for a logical weight: its encoding and logical extents. rad_weight_encoding
* answers with it and every declaration is checked against it (spec §2.4). The engine answers from
* the container or checkpoint it loads, rad-convert from its recipe. `prog` is the declare so far,
* whose name map is used to search a checkpoint. RAD_OK, or RAD_E_NOTFOUND for a weight the model
* does not have. */
struct WeightSource {
RadEncoding enc{};
uint32_t rank = 0;
@@ -111,12 +101,11 @@ using WeightSourceFn = std::function<int(const std::string& name, const Program&
/* ------------------------------------------------------------------ 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. */
/* The Registry must outlive the Builder and its Program (see the file header). */
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. */
/* Where rad_weight_encoding's answers come from. Unset (tests, synthetic tools), every source
* is RAD_E_NOTFOUND and a weight is read as plain in its declared dtype. */
void set_sources(WeightSourceFn f) { sources_ = std::move(f); }
/* The C surface, one method per rad_builder.h entry point. */
@@ -140,15 +129,9 @@ public:
int declare_generator(const RadGeneratorDecl* 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. */
/* An op's buffer operands (rad_op_reads/rad_op_writes in rad_builder.h), which give the
* buffer planner activation liveness. A transient no op names is live for the whole
* program; the --debug-graph buffer report counts those. */
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);
@@ -158,48 +141,43 @@ public:
int kv_group_zero(rad_kvgroup g);
/* 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. */
* RAD_OK, or the first structural error class. Resolution misses are not errors here: an
* unresolved op returns a null handle and the plugin should offer a fallback (spec §2.3); it
* becomes an error only if 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. */
/* A sizing declare (RadBuildCtx::shape_probe): each op takes the bands `ref` resolved at the
* same position, and finish() initialises nothing. The plugin sees the real declare's answers
* (which ops resolved, each group's block size), so it declares the same graph and nothing is
* selected or set up twice. An op that differs from `ref`'s at that position is an error: a
* different graph cannot be laid over the real buffers. */
void set_reference(const Program* ref) { ref_ = ref; }
/* WITHOUT INSTANCES: finish() selects every kernel and initialises none. For a caller that
* launches nothing -- rad-convert plans a container's stored form, which is the kernels'
* layouts and not their setup. A kernel's init is about the process it runs in (a ring, a
* peer's buffers) and the conversion is often not that process: libavx's n-gram gather
* refuses a process that may not make an io_uring ring, and a sandbox that forbids one still
* has to be able to convert the model. */
/* Off: finish() selects every kernel and initialises none, for callers that launch nothing.
* rad-convert needs only the kernels' layouts; a kernel's init depends on the running process
* (a ring, a peer's buffers), and libavx's n-gram gather refuses a process that cannot create
* an io_uring ring, which must not stop a sandboxed conversion. */
void set_instances(bool on) { instances_ = on; }
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. */
/* Structural failures (a bad schema, two ranged parameters, a duplicate name), all of them,
* like 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. */
/* Record a structural error and its class. Returns 0 so a decl_ function can
* `return err(...)` and yield a null handle. */
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. */
/* init() for every surviving instance, after the whole graph has resolved, so a failing init
* cannot abort declare before the miss report is assembled. */
void finish_instances();
int32_t find_kv_consumer(rad_kvgroup g);
void finish_layouts();
@@ -218,32 +196,30 @@ private:
std::string scope_;
/* Parallel to prog_.ops. Empty until the ABI carries buffer operands. */
/* Parallel to prog_.ops: the buffers each op declared it reads and writes. */
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. */
/* Buffers touched from the second lane (rad_buf_concurrent). Their declared op range does not
* bound when their bytes are in use, so they are live for the whole program. */
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(). */
/* Parallel to prog_.kv_groups: where in the op list the group was declared, and the op found
* to consume it. Declaration order is the only link between an op and 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. */
/* Declared name -> index of its first prog_.name_map entry, so a repeated declaration is
* checked in constant time; a routed model declares tens of thousands of weights. */
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. */
/* Declared weight name -> handle, for the same reason (Flash-Next declares about 100K weights
* per rank). */
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. */
/* The model's answers, cached per source: a routed model declares each expert's codes and
* scales as two weights over one source, and a checkpoint lookup walks the name map. */
WeightSourceFn sources_;
std::unordered_map<std::string, std::pair<int, WeightSource>> source_cache_;
int lookup_source(const std::string& name, WeightSource* out);
@@ -252,50 +228,16 @@ private:
};
/* ------------------------------------------------------------------ --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. */
/* The entire declared graph: every op in declared order with its bucket table (one line per band:
* the resolving kernel, variant and plugin, the matched constraints, the weights touched and the
* buffer written); then the weight manifest, buffer plan, KV groups, tuning requests and miss
* report. The bucket-table block is exactly 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. */
/* The same walk as JSON, for the server's Model view, grouped by (op, band table): an op declared
* once per layer with one bucket table is one row with a count. */
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
+269 -426
View File
File diff suppressed because it is too large. Load diff
+79 -152
View File
@@ -1,20 +1,16 @@
/* rad_graph.cpp -- `--debug-graph` (spec §16).
/* rad_graph.cpp -- `--debug-graph` (spec §16): the full record of what runs. Every op in declared
* order with its bucket table (one line per band: the resolving kernel, variant and plugin), the
* matched constraints, the weights it touches and the buffer it writes; then the weight manifest,
* buffer plan, KV groups, tuning requests and miss report.
*
* "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:
* The bucket-table block is exactly 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.
* Everything else goes on its own lines at a deeper indent, so the table stays greppable.
*/
#include "rad_build.h"
@@ -29,14 +25,13 @@
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. */
/* ordered_json keeps keys in insertion order rather than alphabetical. */
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. */
/* A constraint as the kernel wrote it. constraint_why() phrases it as a refusal
* ("M <= 16, have 8192") for the miss column. */
std::string constraint_str(const RadConstraint& c) {
switch (c.op) {
case RAD_C_EQ: return fmt("%s == %lld", c.key, c.ival);
@@ -48,22 +43,20 @@ std::string constraint_str(const RadConstraint& c) {
}
}
/* "(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). */
/* "(libr4d, prio 20)", plus the tuned point only for a kernel with declared axes, so rows that
* were tuned stand out (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. */
/* Same spelling as render_band_table in core/plugin/. */
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. */
/* The left half of a band line, through the arrow. Ranged and fixed forms share column positions
* so they 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());
@@ -82,8 +75,7 @@ void dump_bucket_table(std::string& s, const OpInfo& o, int d) {
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). */
/* Misses are reported per band, not per op (spec §2.2). */
s += band_prefix(o, b) + fmt("%-24s", "(nothing)")
+ "-- " + (b.miss[d].empty() ? "no kernel matched" : b.miss[d]) + "\n";
}
@@ -91,8 +83,7 @@ void dump_bucket_table(std::string& s, const OpInfo& o, int d) {
}
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. */
/* One line per distinct kernel, not per band. */
std::vector<const RadKernelInfo*> seen;
for (const Band& b : o.bands) {
const Resolved& r = b.dom[d];
@@ -110,21 +101,14 @@ void dump_matched(std::string& s, const OpInfo& o, int d) {
}
}
/* 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. */
/* Append a table row with trailing spaces trimmed; the tier and site columns are empty at declare
* (the planner fills them). */
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) {
@@ -144,9 +128,8 @@ std::string dump_graph_str(const Program& p, const std::vector<std::string>* err
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. */
/* Device first and unlabelled, the §2.2 form. A host-only kernel set (a primary target,
* not a fallback) gets a labelled host table instead of a device 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;
@@ -164,25 +147,24 @@ std::string dump_graph_str(const Program& p, const std::vector<std::string>* err
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());
s += fmt(" weights %s\n", join(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. */
/* Buffers this op writes, read off the plan: a transient whose live range begins here is
* defined by this op. */
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. */
/* Whole-program liveness means no declared use; attributing it to the first and last
* op would be wrong. The buffer plan section counts these. */
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());
if (!defs.empty()) s += fmt(" writes %s\n", join(defs).c_str());
if (!ends.empty()) s += fmt(" last use %s\n", join(ends).c_str());
s += "\n";
}
@@ -197,10 +179,9 @@ std::string dump_graph_str(const Program& p, const std::vector<std::string>* err
"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. */
/* `layout` is the storage form the resolved kernel asked for, which is why stored bytes may
* differ from logical ones. tier and site stay blank: the planner fills them after
* declare, and a default would read as a decision. */
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,
@@ -238,8 +219,7 @@ std::string dump_graph_str(const Program& p, const std::vector<std::string>* err
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. */
/* Two arenas, coloured separately (see plan_buffers). */
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());
@@ -308,18 +288,10 @@ std::string dump_graph_str(const Program& p, const std::vector<std::string>* err
/* ---------------------------------------------------------------- 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. */
* Launches that stand in for several ops. A kernel with `replaces` declares, as data, the
* conventional chain it computes; rad-check checks it against that chain. This section is
* coverage, not advice: an op with no fusion is not a defect, and a fusion that did not fire
* is usually banded on purpose. */
{
std::vector<std::string> lines;
int n_fused = 0, n_ops_replaced = 0;
@@ -329,20 +301,15 @@ std::string dump_graph_str(const Program& p, const std::vector<std::string>* err
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. */
/* Walk the chain; the hook ends it by declining the step past the end. */
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". */
/* RAD_FUSE_PRESENT_ALL: the declared graph records ops and geometry, not
* which optional operands a given issue passes (a per-step property). So
* the row means "what this kernel stands in for", described for the operand
* set the kernel publishes, not "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);
@@ -403,30 +370,22 @@ void dump_graph(const Program& p, FILE* out, const std::vector<std::string>* err
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.
* dump_graph_str's content and more, for the server's Model view. It walks the same Program with
* the same helpers (origin, constraint_str, the fuse hook), so the two views cannot disagree.
*
* 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.
* The extra detail lives in the per-op panel: the schema doc and operands, declared geometry,
* each band's winner and the candidates that lost with their reasons, the kernel's own
* description, what it stands in for, the weights read (size, layout) and the buffers whose lives
* begin and end at the op.
*
* 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. */
* Ops are grouped by (op name, every band's resolution), so a per-layer op is one entry with a
* count. Per-occurrence facts (weights, buffers, op index) are the first declaration's, and the
* page labels them so. */
/* 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. */
/* A RadFuseStep's own geometry, which differs from the fused op's: `qk_norm_rope_gate` replaces
* an rmsnorm at M = T * n_head, a product absent from the fused op's parameters. */
static std::string params_str(const RadParam* p, int n) {
std::string s;
for (int i = 0; i < n; ++i) {
@@ -443,18 +402,14 @@ static std::string params_str(const RadParam* p, int n) {
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. */
/* The chain this kernel declares it computes, with each step's geometry, which makes the claim
* checkable and which 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. */
/* RAD_FUSE_PRESENT_ALL: see the same call in dump_graph_str. */
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;
@@ -467,11 +422,9 @@ static json fuse_steps(const Resolved& r) {
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. */
/* The optional ABI hooks a kernel supplies, which decide what the tools can do with it: without
* `opd_shape` rad-check skips the row, without `unrelayout` a dense oracle has nothing to compare,
* without `replaces` a fusion is unchecked. */
static json kernel_hooks(const RadKernelInfo* k) {
json h = json::array();
if (k->init) h.push_back("init");
@@ -493,8 +446,7 @@ static json resolved_json(const Resolved& r) {
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. */
/* The kernel author's own description. */
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;
@@ -503,11 +455,8 @@ static json resolved_json(const Resolved& r) {
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. */
/* Every axis with its full range, not just the choice, so a reader can tell a tuned
choice from a forced one (an axis with no alternatives at this shape). */
json ax = json::array();
int64_t space = 1;
for (int i = 0; i < k->n_tunables; ++i) {
@@ -525,10 +474,8 @@ static json resolved_json(const Resolved& r) {
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`. */
/* The kernel's declared constraints, which selection matched it on. With the band's
* `considered` list and `priority`, they explain why it won. */
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);
@@ -543,20 +490,11 @@ static json resolved_json(const Resolved& r) {
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. */
/* Every candidate for this band and what refused it (SelectionTrace::candidates; build_bands keeps
* only the miss reason). Recomputed rather than stored on every Band, which would hold megabytes of
* strings for the process lifetime; the cost is one pass over one op's rows per distinct band
* table. `record = false` keeps the selection table's "asked" counts to the engine's own
* queries. */
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);
@@ -576,9 +514,8 @@ static json considered_json(Registry& reg, const OpInfo& o, const Band& b, int d
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. */
/* The op's schema. The operand list matters most: `RadArgs.t` is positional, so it is the only
* way to read a fused kernel's `from` wiring. */
static json schema_json(const RadOpSchema* s) {
if (!s) return nullptr;
json j;
@@ -614,9 +551,8 @@ static std::string shape_str(const int64_t* dims, uint32_t rank) {
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. */
/* A weight one declaration of this op reads: its stored size, and the layout the winning kernel
* demanded (why stored bytes may differ from logical ones). */
static json weight_json(const WeightInfo& w) {
json j;
j["name"] = w.name;
@@ -663,9 +599,7 @@ std::string dump_graph_json(const Program& p) {
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. */
/* The plugin hierarchy: an override is a plugin ahead of the default in this list. */
json plugs = json::array();
for (const Plugin& pl : reg.plugins()) {
json j;
@@ -704,9 +638,8 @@ std::string dump_graph_json(const Program& p) {
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. */
/* The grouping key is formed before the candidate lists are added: `considered`
* depends only on op and band, so hashing it would add cost and nothing else. */
key += "|" + jb.dump();
for (int d = 0; d < RAD_N_DOMAINS; ++d)
jb[std::string(bld_domain_name(d)) + "_considered"] =
@@ -731,11 +664,8 @@ std::string dump_graph_json(const Program& p) {
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. */
/* Buffers whose lives begin or end at this op, read off the plan as in the text dump.
* Whole-program buffers (no declared use) are skipped. */
json writes = json::array(), frees = json::array();
for (size_t bi = 1; bi < p.buffers.size(); ++bi) {
const BufferInfo& bf = p.buffers[bi];
@@ -767,10 +697,8 @@ std::string dump_graph_json(const Program& p) {
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. */
/* The declared order as indices into `ops`, which the grouping dropped and the diagram needs.
* One small integer per declared op, far smaller than emitting every op in full. */
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) {
@@ -779,8 +707,7 @@ std::string dump_graph_json(const Program& p) {
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. */
/* First and last position of the group's declarations in the flow. */
for (size_t k = 0; k < ops.size(); ++k) {
ops[k]["first_at"] = first_at[k];
ops[k]["last_at"] = last_at[k];
+64 -89
View File
@@ -1,9 +1,6 @@
/* 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.
* The tools use the same Registry and Builder as the engine (see startup.h), so they resolve the
* same program.
*/
#include "build/startup.h"
#include "build/rad_build.h"
@@ -14,22 +11,17 @@
#include <algorithm>
#include <cstdlib>
#include <cstring>
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.
/* One Registry for the life of the process: Resolved, Band and KernelRow point into plugin
* static tables, and the Program outlives the call that built it.
*
* NEVER DESTROYED, because exit destroys in the wrong order for it. A function-local static is
* constructed before the first plugin is loaded, so its destructor runs AFTER every plugin's own
* static destructors -- and closing from there calls each instance's fini into plugin state that
* no longer exists. libr4d's router keeps its per-device counter blocks in a global map; fini
* looked up and erased a node of the destroyed map, a double free that glibc reported as
* "corrupted size vs. prev_size" or "free(): invalid pointer" on whichever exit the heap layout
* exposed it. A caller that needs the finis to run closes the registry itself while the plugins
* are alive, as Engine's shutdown does; at exit the process is ending and what the instances
* hold goes with it. */
* Never destroyed. A function-local static would be destroyed after the plugins' own static
* destructors, and its close would call each instance's fini into destroyed plugin state (e.g.
* libr4d's router erasing from its destroyed global map: a double free). A caller that needs the
* finis closes the registry while plugins are alive, as Engine's shutdown does. */
Registry& rad_tools_registry() {
static Registry* r = new Registry();
return *r;
@@ -37,16 +29,10 @@ Registry& rad_tools_registry() {
/* ------------------------------------------------------------------ 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. */
/* An op is "on the reference" when no band in any domain offers a non-reference kernel
* (RadPluginReferenceFn). A reference library usually serves the host domain for every op, so
* only an op with no other implementation is flagged: wherever it is placed, it runs naive code.
* Counted once per declared instance; `out` lists distinct op names. */
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) {
@@ -58,8 +44,7 @@ int rad_reference_ops(const Program& p, std::vector<std::string>* out) {
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. */
/* Deduplicated by op name. */
if (out && std::find(out->begin(), out->end(), oi.op) == out->end())
out->push_back(oi.op);
}
@@ -71,9 +56,8 @@ int rad_gate_reference_kernels(const Program& p, bool allow, const char* what) {
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. */
const std::string list = join(ops);
/* The reference libraries involved, by plugin name. */
std::vector<std::string> refs;
for (size_t i = 1; i < p.ops.size(); ++i)
for (const Band& b : p.ops[i].bands)
@@ -81,8 +65,7 @@ int rad_gate_reference_kernels(const Program& p, bool allow, const char* what) {
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]; }
const std::string libs = join(refs);
if (allow) {
RAD_WARN("%d declared op(s) resolve to a reference implementation (%s) and "
@@ -92,15 +75,12 @@ int rad_gate_reference_kernels(const Program& p, bool allow, const char* what) {
return RAD_OK;
}
RAD_ERR("%d declared op(s) resolve only to a reference implementation (%s).\n"
RAD_ERR("%d declared op(s) resolve only to a reference implementation (%s), which runs "
"orders of magnitude slower; %s refuses them (spec §17).\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);
" Supply a kernel plugin that covers these ops, or pass "
"--debug-accept-reference-kernels to accept the cost.",
n, libs.c_str(), what, ops.size(), list.c_str());
return RAD_E_NOKERNEL;
}
@@ -145,13 +125,9 @@ int rad_tools_load_plugins(const std::string& home, const std::vector<std::strin
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. */
/* Kernels first, in hierarchy order, then architectures (unordered: no two may claim the same
* id). A home need not have every directory, but kernels/ and architectures/ must each exist
* somewhere on the path, or the scan reports 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");
@@ -163,9 +139,8 @@ int rad_tools_load_plugins(const std::string& home, const std::vector<std::strin
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. */
/* Quantisers: rad-convert drives them, and the oracle decodes through them for schemes the
* core does not define. Optional. */
const std::vector<std::string> qdirs = home_subdirs(home, "quantizers");
if (!qdirs.empty()) {
s = r.load_dirs(qdirs, {});
@@ -174,18 +149,16 @@ int rad_tools_load_plugins(const std::string& home, const std::vector<std::strin
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. */
/* The tuning cache, once the kernel set is known. A missing file leaves every shape on its
* plugin's first variant. Logged when it has rows; --debug-graph shows the per-shape
* source. */
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. */
/* The selection key is the (arch_id, quant) pair (spec §2.4), matched exactly with no
* fallback; a mismatched plugin would only fail later at the name map with a worse message. */
for (const Plugin& p : r.plugins()) {
if (p.kind == RAD_PLUGIN_KERNEL) {
out->kernels.push_back({ p.name, p.version });
@@ -198,7 +171,7 @@ int rad_tools_load_plugins(const std::string& home, const std::vector<std::strin
}
}
/* AN IMPORTED QUANTISATION is served by the family's quantised plugin (startup.h). */
/* An imported quantisation is served by the family's quantised plugin (startup.h). */
if (imported && !arch_id.empty() && out->arch_plugin.empty()) {
std::vector<const Plugin*> fam, quantised;
for (const Plugin& p : r.plugins())
@@ -234,10 +207,8 @@ int rad_tools_load_plugins(const std::string& home, const std::vector<std::strin
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. */
/* No match, no model (spec §1). List what is installed with its quantisation, to tell an
* unsupported architecture from one supported only at another weight format. */
std::string have, same;
for (const Plugin& p : r.plugins()) {
if (p.kind != RAD_PLUGIN_ARCH) continue;
@@ -261,13 +232,9 @@ int rad_tools_load_plugins(const std::string& home, const std::vector<std::strin
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. */
/* Optional export. Without it, or on failure, every field is zero and the caller uses its own
* defaults. A failed probe is not an error: the plugin can still refuse in declare, where it has
* the whole configuration and can say why. */
int rad_tools_probe(const LoadedPlugins& lp, const RadModelMeta& meta, RadArchProbe* out) {
if (!out) return RAD_E_INVAL;
*out = RadArchProbe{};
@@ -289,6 +256,21 @@ const RadChatFormat* rad_tools_chat_format(const LoadedPlugins& lp, const RadMod
return ap->arch_chat_format(&meta);
}
const RadAudioFormat* rad_tools_audio_format(const LoadedPlugins& lp, const RadModelMeta& meta) {
const Plugin* ap = rad_tools_registry().plugin(lp.arch_plugin);
if (!ap || !ap->arch_audio_format) return nullptr;
const RadAudioFormat* f = ap->arch_audio_format(&meta);
if (!f) return nullptr;
/* The plugin's struct may be older than ours: it is copied into a zeroed one up to the size
* it states, so a field it predates reads as null (rad_builder.h). */
static thread_local RadAudioFormat copy;
copy = RadAudioFormat{};
const size_t n = f->struct_size < sizeof copy ? f->struct_size : sizeof copy;
std::memcpy(&copy, f, n);
copy.struct_size = (uint32_t)sizeof copy;
return &copy;
}
WeightSourceFn rad_container_sources(const RadFile& f) {
return [&f](const std::string& name, const Program&, WeightSource* out) {
const RadFileEntry* e = f.find(name);
@@ -313,8 +295,8 @@ int CheckpointSources::answer(const std::string& name, const Program& prog, Weig
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. */
/* Not-found is not cached, since declare may map the name later, but its reason is kept
* for the loader to report. */
if (st == RAD_E_NOTFOUND) {
missing_[name] = why;
return st;
@@ -369,7 +351,6 @@ int rad_tools_declare(const LoadedPlugins& lp, const RadModelMeta& meta, const R
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);
@@ -382,20 +363,15 @@ int rad_tools_declare(const LoadedPlugins& lp, const RadModelMeta& meta, const R
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. */
/* NOT FOR AN EMBEDDING PROGRAM (rad_declare_pooled) OR AN IMAGE GENERATOR: neither samples a
* token, so a sampler chain in it would be ops and buffers no step ever issues. */
/* The sampler declares into the same builder before finish(). An unresolved sampler op is not
* a declare failure (a deployment that never sends `typical_p` needs no typical kernel), so a
* negative return here is structural. Skipped for embedding programs and image generators,
* which sample no token. */
if (also && b.program().pooled_buf == RAD_NULL_HANDLE && !b.program().is_generator()) {
/* 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. */
/* This rank's vocabulary width, taken from the declared logits buffer rather than
* re-derived from n_vocab and world_size, which would break when a plugin does not split
* the vocabulary (arch/common/rad_arch.h does not). A wrong width does not crash; it
* samples 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()) {
@@ -410,8 +386,7 @@ int rad_tools_declare(const LoadedPlugins& lp, const RadModelMeta& meta, const R
}
s = b.finish();
/* Declare ALWAYS completes: a structural error is reported whole, not first-failure-at-the-top
* (spec §3.1). */
/* Declare always completes; every structural error is reported (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();
+59 -60
View File
@@ -1,14 +1,13 @@
/* startup.h -- steps 1 through 4 of spec §1's startup sequence, shared by the engine and by every
* tool that needs them.
/* startup.h -- steps 1 through 4 of spec §1's startup sequence, shared by the engine and the
* tools.
*
* 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.
* In core because rad-convert, rad-check and rad-tune are the engine's startup with a different
* last step (spec §4.4, §15, §17). A second implementation could disagree on hierarchy order,
* which decides the layout baked into a container.
*/
#pragma once
#include "rad_core.h"
@@ -29,17 +28,16 @@ namespace rad {
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. */
/* Kernel plugins in hierarchy order, which decides selection. */
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. */
/* The quantisation half of the selection key, "" for an unquantised container. */
std::string arch_quant;
/* `name@version`, space separated, in hierarchy order: what a benchmark records as the
* libraries it measured. */
/* `name@version`, space separated, in hierarchy order; what a benchmark records as the
* libraries measured. */
std::string libraries() const {
std::string s;
for (const auto& p : kernels) {
@@ -50,29 +48,27 @@ struct LoadedPlugins {
}
};
/* $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. */
/* $RADIANCE_HOME is a ':'-separated search path, first home first, so a directory of one's own
* plugins can precede an installation. Each home may hold kernels/, architectures/ and
* quantizers/; a plugin earlier on the path shadows one with the same file name later. Non-plugin
* files (the tuning cache, rad-kbench 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. */
/*
* `imported` is a checkpoint whose quantisation is imported weight by weight
* (Checkpoint::imports): its descriptor names the tool that made it and no plugin claims it, so
* the plugin is the architecture's QUANTISED one -- the one plugin of the family claiming a
* descriptor, or the family's only plugin when that claims none. Two quantised plugins are a
* choice this cannot make, and are refused by name. `out->arch_quant` is the descriptor chosen,
* which is what a container converted from it records. */
/* Loads into the process-lifetime registry (rad_tools_registry).
*
* `arch_id` and `quant` together are the selection key (spec §2.4, rad_builder.h): a family has
* one plugin per weight format, all answering the same architecture id. `quant` is the container's
* descriptor (RadModelMeta::quant, RadFileHeader::quant); "" is unquantised and matches only a
* plugin that says "".
*
* `imported`: the checkpoint's quantisation is imported weight by weight (Checkpoint::imports), so
* its descriptor names the producing tool and no plugin claims it. The family's quantised plugin
* serves it: the one plugin claiming a descriptor, or the only plugin if none does. Two quantised
* plugins are refused by name. `out->arch_quant` is the chosen descriptor, which a container
* converted from it records. */
int rad_tools_load_plugins(const std::string& radiance_home,
const std::vector<std::string>& hierarchy,
const std::string& arch_id,
@@ -80,24 +76,34 @@ int rad_tools_load_plugins(const std::string& radiance_home,
LoadedPlugins* out,
bool imported = false);
/* `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. */
/* The architecture plugin's rad_arch_probe answers, given before declare. */
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. */
/* `instances` false selects every kernel and initialises none (Builder::set_instances): for a
* caller that launches nothing, such as rad-convert planning a container's stored form. */
/* The architecture plugin's declared audio format (rad_arch_audio_format), or null when it
* declares none -- a model the speech routes do not serve. A format whose struct_size is too
* small to hold a field reads that field as null. */
const RadAudioFormat* rad_tools_audio_format(const LoadedPlugins& plugins, const RadModelMeta& meta);
/* Run declare.
*
* `also` declares into the same builder after the architecture plugin, which is how the sampler
* chain joins the Program: its ops resolve through the same hierarchy, so a missing sampler kernel
* is in the same miss list rather than found at the first request (spec §3.1, §13). Empty for the
* tools, which have no sampler.
*
* `ref` makes this a sizing declare (RadBuildCtx::shape_probe, Builder::set_reference): the plugin
* declares against `ref`'s bands, nothing is selected or initialised, and the result is used only
* for its buffers.
*
* `sources` answers rad_weight_encoding (Builder::set_sources): container entries, checkpoint
* tensors, or a recipe. Empty: every weight is plain in its declared dtype.
*
* `instances` false selects every kernel and initialises none (Builder::set_instances), for
* callers that launch nothing, such as rad-convert. */
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 = {},
@@ -108,14 +114,13 @@ int rad_tools_declare(const LoadedPlugins& plugins, const RadModelMeta& meta,
* 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.
/* A checkpoint served directly as the source (spec §4.3). Each declared weight is resolved
* through the name map once and kept for the loader, which reads the same tensors. Locked, since
* every rank declares concurrently.
*
* 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. */
* Only trivial encodings are answered (bf16, f16, f32, block-scaled FP8) because nothing is
* quantised at load. Anything else is recorded with its reason and answered RAD_E_UNSUPPORTED;
* refused() lists them after declare, and the remedy is a container. */
class CheckpointSources {
public:
explicit CheckpointSources(Checkpoint& ck) : ck_(ck) {}
@@ -136,22 +141,16 @@ private:
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. */
/* A reference library (RadPluginReferenceFn) is both the slow fallback for an unsupported model
* and the oracle rad-kbench measures against (spec §17). As a silent fallback it runs orders of
* magnitude below the machine with no visible sign, so resolving to one is fatal unless
* --debug-accept-reference-kernels is passed. */
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. */
* "the container's layout") so the message states the consequence. */
int rad_gate_reference_kernels(const Program& p, bool allow, const char* what);
Registry& rad_tools_registry();