Archived
radiance 1.0.0
This commit is contained in:
commit
ae74a8aebf
616 files changed
+338692
No files matched your search
@@ -0,0 +1,5 @@
|
||||
# The plugin layer's own sources (registry.h, loader.cpp, schema.cpp, select.cpp, bands.cpp) are
|
||||
# picked up by core/CMakeLists.txt's per-directory glob and compiled into rad_core. This file
|
||||
# exists only for the test plugins below it, which must be .so files rather than part of the
|
||||
# engine -- the plugin loader cannot be tested by anything it does not dlopen.
|
||||
add_subdirectory(testplugin)
|
||||
@@ -0,0 +1,129 @@
|
||||
/* bands.cpp -- the bucket table. spec.md §2.2.
|
||||
*
|
||||
* A parameter may be declared as a range rather than a value, because some of them are properties
|
||||
* of the batch and not of the model. M is the obvious one: a GEMM sees one row at decode,
|
||||
* sixty-four at a speculative verify and thousands in a prefill chunk, and libr4d has a different
|
||||
* kernel for each band. Resolving once at M = max_tok would pick the prefill kernel and then run
|
||||
* it at M = 1, which is exactly the loss that skinny-GEMM specialisation exists to recover.
|
||||
*
|
||||
* THE BUCKET BOUNDARIES ARE THE CONSTRAINT VALUES THEMSELVES. Nothing here picks a policy, a
|
||||
* power-of-two ladder or a bucket count: the kernels already said where their bands end, and this
|
||||
* file only collects what they said. A kernel whose fast band sits at an odd boundary gets that
|
||||
* boundary, because it said so.
|
||||
*/
|
||||
#include "registry.h"
|
||||
|
||||
#include <algorithm>
|
||||
|
||||
namespace rad {
|
||||
|
||||
namespace {
|
||||
|
||||
/* "M <= 64" for the first band, "M in (16, 64]" for a later one -- the half-open form is what a
|
||||
* band actually is, and a reader who sees only "<= 64" on the second row will read the table as
|
||||
* overlapping. */
|
||||
std::string band_span(std::string_view key, int64_t lo_excl, int64_t hi, bool first) {
|
||||
if (hi == INT64_MAX) return std::string("any shape"); /* the op has no ranged parameter */
|
||||
if (first) return fmt("%.*s <= %lld", (int)key.size(), key.data(), (long long)hi);
|
||||
return fmt("%.*s in (%lld, %lld]", (int)key.size(), key.data(), (long long)lo_excl,
|
||||
(long long)hi);
|
||||
}
|
||||
|
||||
} /* namespace */
|
||||
|
||||
std::vector<Band> Registry::build_bands(std::string_view op, std::string_view ranged_key,
|
||||
int64_t lo, int64_t hi, const Geometry& base,
|
||||
const RowFilter* accept) {
|
||||
std::vector<Band> out;
|
||||
|
||||
/* No ranged parameter: one band covering everything. hi is INT64_MAX rather than the declared
|
||||
* value so the issue path's band scan finds it for any issue count -- an op with no range has no
|
||||
* value to index by, and a table that can miss on an op that cannot miss is a trap. */
|
||||
if (ranged_key.empty()) {
|
||||
lo = 0;
|
||||
hi = INT64_MAX;
|
||||
} else if (hi < lo) {
|
||||
RAD_WARN("op '%s' declares the empty range %s in [%lld, %lld]; resolving the single value "
|
||||
"%lld", std::string(op).c_str(), std::string(ranged_key).c_str(),
|
||||
(long long)lo, (long long)hi, (long long)lo);
|
||||
hi = lo;
|
||||
}
|
||||
|
||||
/* The union of the LE, GE and EQ values candidate kernels place on the ranged parameter, from
|
||||
* EVERY plugin and BOTH domains -- the boundaries are a property of the op's candidate set,
|
||||
* not of whichever kernel happens to win a given band. DIV and IN cut nothing: a kernel that
|
||||
* wants K divisible by 128 wants it at every value in the range, and set membership is not an
|
||||
* interval, so neither can be a band edge. */
|
||||
std::vector<int64_t> bounds;
|
||||
auto add = [&](int64_t b) {
|
||||
if (b >= lo && b < hi) bounds.push_back(b); /* clamped to the declared range; hi closes
|
||||
* the last band and is appended below */
|
||||
};
|
||||
if (!ranged_key.empty()) {
|
||||
if (const std::vector<const KernelRow*>* rows = rows_for(op)) {
|
||||
for (const KernelRow* r : *rows) {
|
||||
for (int i = 0; i < r->info->n_constraints; ++i) {
|
||||
const RadConstraint& c = r->info->constraints[i];
|
||||
if (!c.key || ranged_key != c.key) continue;
|
||||
switch (c.op) {
|
||||
case RAD_C_LE: add(c.ival); break;
|
||||
/* A kernel that starts at v ends the band below it at v-1, so the band it
|
||||
* serves begins exactly where it said it does. */
|
||||
case RAD_C_GE: add(c.ival - 1); break;
|
||||
/* An EQ needs both edges, or the single value it serves would share a band
|
||||
* with values it does not. */
|
||||
case RAD_C_EQ: add(c.ival - 1); add(c.ival); break;
|
||||
default: break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
std::sort(bounds.begin(), bounds.end());
|
||||
bounds.erase(std::unique(bounds.begin(), bounds.end()), bounds.end());
|
||||
bounds.push_back(hi);
|
||||
|
||||
/* Each band is resolved AT ITS UPPER BOUND, in both domains. The upper bound is the worst case
|
||||
* in the band, so a kernel that serves it serves the whole band; resolving at the lower bound
|
||||
* would hand a band to a kernel that cannot run its largest value. */
|
||||
int64_t prev = lo - 1;
|
||||
for (size_t i = 0; i < bounds.size(); ++i) {
|
||||
Band b;
|
||||
b.hi = bounds[i];
|
||||
|
||||
Geometry g = base;
|
||||
if (!ranged_key.empty()) g.set_i(ranged_key, b.hi);
|
||||
|
||||
SelectionTrace t;
|
||||
for (int dom = 0; dom < RAD_N_DOMAINS; ++dom) {
|
||||
b.dom[dom] = resolve(op, g, dom, &t, accept);
|
||||
if (!b.dom[dom]) b.miss[dom] = t.reason;
|
||||
}
|
||||
|
||||
b.span = band_span(ranged_key, prev, b.hi, i == 0);
|
||||
if (!b.dom[RAD_DOMAIN_DEVICE]) {
|
||||
/* Fatal, but not here: declare always completes, and the caller reports every miss at
|
||||
* the end rather than the first one at the top (§3.1). A range with a hole in it is
|
||||
* reported as that band, not as the whole op. */
|
||||
RAD_DEBUG("op '%s' %s: no device kernel -- %s", std::string(op).c_str(),
|
||||
b.span.c_str(), b.miss[RAD_DOMAIN_DEVICE].c_str());
|
||||
}
|
||||
if (!b.dom[RAD_DOMAIN_HOST])
|
||||
b.miss[RAD_DOMAIN_HOST] += "; site 'host' is unavailable for this band";
|
||||
out.push_back(std::move(b));
|
||||
prev = bounds[i];
|
||||
}
|
||||
|
||||
/* Absence is asymmetric. No device kernel is fatal and the caller says so; no host kernel
|
||||
* removes one placement option -- host-site execution needs a RAD_DOMAIN_HOST kernel, and
|
||||
* where none resolves the planner may not put this op's arithmetic on the host. The host
|
||||
* and SSD TIERS are untouched: a weight can still live there and stage to the device (§5.1).
|
||||
*
|
||||
* NEITHER IS REPORTED HERE. This function runs once per DECLARED OP, so a 64-layer model
|
||||
* calls it 64 times for the same op name, and a warning emitted here would print one line
|
||||
* per (layer, band) -- hundreds of identical sentences at startup. The band's miss string is
|
||||
* the record instead; Builder collects them and reports once, over the whole graph. */
|
||||
return out;
|
||||
}
|
||||
|
||||
} /* namespace rad */
|
||||
@@ -0,0 +1,701 @@
|
||||
/* loader.cpp -- dlopen, the ABI gate, the configured hierarchy, and the registration of one
|
||||
* plugin's schemas and kernel rows. spec.md §2, §18.
|
||||
*/
|
||||
#include "registry.h"
|
||||
#include "../device/device.h"
|
||||
#include "../format/encoding.h"
|
||||
|
||||
#include <dlfcn.h>
|
||||
#include <dirent.h>
|
||||
#include <sys/stat.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <climits>
|
||||
#include <cerrno>
|
||||
#include <cstdarg>
|
||||
#include <cstring>
|
||||
|
||||
namespace rad {
|
||||
|
||||
namespace {
|
||||
|
||||
/* dlsym returns void*, which is not a function pointer in standard C++ and is one everywhere this
|
||||
* engine will ever run. The cast is isolated here so the rest of the file reads. */
|
||||
template <class Fn>
|
||||
Fn dl_fn(void* h, const char* name) {
|
||||
dlerror();
|
||||
return reinterpret_cast<Fn>(dlsym(h, name));
|
||||
}
|
||||
|
||||
std::string stem_of(const std::string& path) {
|
||||
size_t slash = path.find_last_of('/');
|
||||
std::string base = slash == std::string::npos ? path : path.substr(slash + 1);
|
||||
if (base.size() > 3 && base.compare(base.size() - 3, 3, ".so") == 0)
|
||||
base.resize(base.size() - 3);
|
||||
if (base.compare(0, 3, "lib") == 0 && base.size() > 3) base.erase(0, 3);
|
||||
return base;
|
||||
}
|
||||
|
||||
const char* or_empty(const char* s) { return s ? s : ""; }
|
||||
|
||||
/* Does a plugin's declared coverage include this device's architecture? The field is a list, so a
|
||||
* binary built for several is one entry per name, separated by spaces or commas. */
|
||||
bool target_covers(const std::string& declared, const char* arch) {
|
||||
for (size_t i = 0; i < declared.size(); ) {
|
||||
size_t e = declared.find_first_of(" ,;", i);
|
||||
if (e == std::string::npos) e = declared.size();
|
||||
if (e > i && declared.compare(i, e - i, arch) == 0) return true;
|
||||
i = e + 1;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/* Two schemas for one op name are the SAME schema when every positional slot means the same thing.
|
||||
* Parameter keys, types and requiredness are load-bearing: they are the geometry the selector
|
||||
* matches on. Operand roles, count and optionality are load-bearing: arguments are positional.
|
||||
* Operand NAMES are not -- the ABI says they are for diagnostics -- so two plugins spelling slot 1
|
||||
* "b" and "w_gate" agree, and refusing that would be refusing a synonym. */
|
||||
bool schema_same(const RadOpSchema& a, const RadOpSchema& b, std::string* diff) {
|
||||
if (a.n_params != b.n_params) {
|
||||
*diff = fmt("%d parameters vs %d", a.n_params, b.n_params);
|
||||
return false;
|
||||
}
|
||||
for (int i = 0; i < a.n_params; ++i) {
|
||||
const RadParamSpec& x = a.params[i];
|
||||
const RadParamSpec& y = b.params[i];
|
||||
if (std::strcmp(or_empty(x.key), or_empty(y.key)) != 0) {
|
||||
*diff = fmt("parameter %d is '%s' vs '%s'", i, or_empty(x.key), or_empty(y.key));
|
||||
return false;
|
||||
}
|
||||
if (x.type != y.type) {
|
||||
*diff = fmt("parameter '%s' is %s vs %s", or_empty(x.key),
|
||||
x.type == RAD_P_STR ? "a string" : "an integer",
|
||||
y.type == RAD_P_STR ? "a string" : "an integer");
|
||||
return false;
|
||||
}
|
||||
if (x.required != y.required) {
|
||||
*diff = fmt("parameter '%s' is %s vs %s", or_empty(x.key),
|
||||
x.required ? "required" : "optional", y.required ? "required" : "optional");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
if (a.n_operands != b.n_operands) {
|
||||
*diff = fmt("%d operands vs %d", a.n_operands, b.n_operands);
|
||||
return false;
|
||||
}
|
||||
for (int i = 0; i < a.n_operands; ++i) {
|
||||
if (a.operands[i].role != b.operands[i].role ||
|
||||
a.operands[i].optional != b.operands[i].optional) {
|
||||
*diff = fmt("operand %d ('%s' / '%s') has a different role", i,
|
||||
or_empty(a.operands[i].name), or_empty(b.operands[i].name));
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
} /* namespace */
|
||||
|
||||
/* ------------------------------------------------------------------ diagnostics */
|
||||
void Registry::err_(const char* f, ...) {
|
||||
char msg[2048];
|
||||
va_list ap;
|
||||
va_start(ap, f);
|
||||
vsnprintf(msg, sizeof msg, f, ap);
|
||||
va_end(ap);
|
||||
load_errors_.emplace_back(msg);
|
||||
RAD_ERR("%s", msg);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ staging */
|
||||
/* dlopen and read the plugin's identity, without registering anything. Two phases, because the
|
||||
* hierarchy is ordered by plugin NAME and the name lives inside the .so: the whole directory must
|
||||
* be open before anything can be registered, and registration order is what fixes an op's schema. */
|
||||
int Registry::stage_(const std::string& path, Staged* out) {
|
||||
out->path = path;
|
||||
out->file = stem_of(path);
|
||||
|
||||
/* RTLD_LOCAL is not a preference. Every kernel plugin exports the same four symbol names --
|
||||
* rad_kernel_count and friends -- so RTLD_GLOBAL would let the first plugin loaded answer for
|
||||
* every plugin after it, and the failure would look like a plugin whose kernels vanished. We
|
||||
* dlsym against the handle instead, which is exactly what RTLD_LOCAL is for. */
|
||||
out->code_from = rad::dev_code_mark();
|
||||
out->handle = dlopen(path.c_str(), RTLD_NOW | RTLD_LOCAL);
|
||||
out->code_to = rad::dev_code_mark();
|
||||
if (!out->handle) {
|
||||
err_("plugin '%s' failed to load: %s", path.c_str(), or_empty(dlerror()));
|
||||
return RAD_E_IO;
|
||||
}
|
||||
|
||||
auto abi = dl_fn<uint32_t (*)(void)>(out->handle, "rad_plugin_abi_version");
|
||||
if (!abi) {
|
||||
err_("'%s' is not a radiance plugin: it exports no rad_plugin_abi_version", path.c_str());
|
||||
unstage_(*out);
|
||||
return RAD_E_ABI;
|
||||
}
|
||||
const uint32_t v = abi();
|
||||
if (v != RAD_ABI_VERSION) {
|
||||
/* Named by FILE, not by RadPluginInfo::name: the struct is exactly the thing that may have
|
||||
* changed shape between ABI versions, so reading it here would be reading a different
|
||||
* layout than the one this build was compiled against. Both versions are printed because
|
||||
* "ABI mismatch" alone does not tell an operator which side is stale. */
|
||||
err_("plugin '%s' was built against ABI version %u; this engine is version %u -- refused",
|
||||
path.c_str(), v, (unsigned)RAD_ABI_VERSION);
|
||||
unstage_(*out);
|
||||
return RAD_E_ABI;
|
||||
}
|
||||
|
||||
auto info_fn = dl_fn<const RadPluginInfo* (*)(void)>(out->handle, "rad_plugin_info");
|
||||
if (!info_fn || !(out->info = info_fn())) {
|
||||
err_("plugin '%s' exports no usable rad_plugin_info", path.c_str());
|
||||
unstage_(*out);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
out->name = out->info->name && out->info->name[0] ? out->info->name : out->file;
|
||||
if (auto ref = dl_fn<RadPluginReferenceFn>(out->handle, "rad_plugin_reference"))
|
||||
out->reference = out->info->kind == RAD_PLUGIN_KERNEL && ref() != 0;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
void Registry::unstage_(Staged& s) {
|
||||
if (s.handle) dlclose(s.handle);
|
||||
s.handle = nullptr;
|
||||
s.info = nullptr;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ registration */
|
||||
int Registry::commit_(Staged& s, int order) {
|
||||
for (const Plugin& p : plugins_) {
|
||||
if (p.name == s.name) {
|
||||
err_("two plugins claim the name '%s': %s and %s -- refusing the second",
|
||||
s.name.c_str(), p.path.c_str(), s.path.c_str());
|
||||
unstage_(s);
|
||||
return RAD_E_DUPLICATE;
|
||||
}
|
||||
}
|
||||
|
||||
Plugin p;
|
||||
p.name = s.name;
|
||||
p.file = s.file;
|
||||
p.path = s.path;
|
||||
p.version = or_empty(s.info->version);
|
||||
p.description = or_empty(s.info->description);
|
||||
p.build_target = or_empty(s.info->build_target);
|
||||
p.kind = s.info->kind;
|
||||
p.reference = s.reference;
|
||||
p.order = order;
|
||||
p.handle = s.handle;
|
||||
p.close = dl_fn<RadPluginCloseFn>(s.handle, "rad_plugin_close");
|
||||
|
||||
std::vector<const RadOpSchema*> staged_schemas;
|
||||
std::vector<std::pair<const RadKernelInfo*, int>> staged_rows; /* the row and its index */
|
||||
std::vector<const RadQuantizerInfo*> staged_quants;
|
||||
int n_declared_schemas = 0;
|
||||
|
||||
if (p.kind == RAD_PLUGIN_ARCH) {
|
||||
auto id_fn = dl_fn<const char* (*)(void)>(s.handle, "rad_arch_id");
|
||||
p.arch_declare = dl_fn<int (*)(RadBuilder*, const RadModelMeta*, const RadBuildCtx*)>(
|
||||
s.handle, "rad_arch_declare");
|
||||
p.arch_step = dl_fn<void (*)(RadCtx*, const RadBatch*)>(s.handle, "rad_arch_step");
|
||||
if (!id_fn || !p.arch_declare || !p.arch_step) {
|
||||
err_("architecture plugin '%s' is missing rad_arch_id, rad_arch_declare or "
|
||||
"rad_arch_step", p.name.c_str());
|
||||
unstage_(s);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
p.arch_id = or_empty(id_fn());
|
||||
if (p.arch_id.empty()) {
|
||||
err_("architecture plugin '%s' returns an empty architecture id", p.name.c_str());
|
||||
unstage_(s);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
/* The second half of the key. OPTIONAL: a plugin written before this export existed serves
|
||||
* an unquantised container, which is what "" means, so its absence is not an error. */
|
||||
if (auto q_fn = dl_fn<const char* (*)(void)>(s.handle, "rad_arch_quant"))
|
||||
p.arch_quant = or_empty(q_fn());
|
||||
|
||||
/* ALSO OPTIONAL, and for the same reason: it answers what the core needs to know before
|
||||
* it can build the RadBuildCtx that declare runs against. Absent means every answer is
|
||||
* the zero -- see rad_builder.h. */
|
||||
p.arch_probe = dl_fn<int (*)(const RadModelMeta*, RadArchProbe*)>(s.handle,
|
||||
"rad_arch_probe");
|
||||
/* AND THE REPLY FORMAT, optional for the same reason: a plugin that says nothing has its
|
||||
* model's format read off the chat template. */
|
||||
p.arch_chat_format = dl_fn<const RadChatFormat* (*)(const RadModelMeta*)>(
|
||||
s.handle, "rad_arch_chat_format");
|
||||
|
||||
/* One plugin implements one architecture id AT ONE QUANTISATION, and no two may claim the
|
||||
* same pair: the pair is what selects the plugin, so two claimants is a coin toss over
|
||||
* which graph a model gets built from (§2.4). Two plugins sharing an id at different
|
||||
* quantisations is the NORMAL case -- qwen35_bf16 and qwen35_fp8 are the same architecture
|
||||
* over two weight formats -- and refusing that would make §2.4 unimplementable. */
|
||||
for (const Plugin& q : plugins_) {
|
||||
if (q.arch_id == p.arch_id && q.arch_quant == p.arch_quant) {
|
||||
err_("architecture id '%s' at quantisation '%s' is claimed by both '%s' and '%s' "
|
||||
"-- refusing the second", p.arch_id.c_str(),
|
||||
p.arch_quant.empty() ? "(unquantised)" : p.arch_quant.c_str(),
|
||||
q.name.c_str(), p.name.c_str());
|
||||
unstage_(s);
|
||||
return RAD_E_DUPLICATE;
|
||||
}
|
||||
}
|
||||
} else if (p.kind == RAD_PLUGIN_KERNEL) {
|
||||
auto sc_n = dl_fn<int (*)(void)>(s.handle, "rad_kernel_schema_count");
|
||||
auto sc_at = dl_fn<const RadOpSchema* (*)(int)>(s.handle, "rad_kernel_schema_at");
|
||||
auto k_n = dl_fn<int (*)(void)>(s.handle, "rad_kernel_count");
|
||||
auto k_at = dl_fn<const RadKernelInfo* (*)(int)>(s.handle, "rad_kernel_at");
|
||||
if (!sc_n || !sc_at || !k_n || !k_at) {
|
||||
err_("kernel plugin '%s' is missing rad_kernel_schema_count/at or "
|
||||
"rad_kernel_count/at", p.name.c_str());
|
||||
unstage_(s);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
|
||||
/* Schemas are checked WHOLE before any of them is committed. A plugin that conflicts on
|
||||
* its fourth op must not leave its first three registered under its name -- a half-loaded
|
||||
* plugin is a state nobody can reason about afterwards. */
|
||||
n_declared_schemas = sc_n();
|
||||
for (int i = 0; i < n_declared_schemas; ++i) {
|
||||
const RadOpSchema* sch = sc_at(i);
|
||||
if (!sch || !sch->op || !sch->op[0]) {
|
||||
err_("kernel plugin '%s' declares a schema with no op name at index %d",
|
||||
p.name.c_str(), i);
|
||||
unstage_(s);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
std::string diff;
|
||||
auto it = schemas_.find(sch->op);
|
||||
if (it != schemas_.end()) {
|
||||
if (!schema_same(*it->second.schema, *sch, &diff)) {
|
||||
/* Refused at load with both plugins named. Since arguments are positional, two
|
||||
* disagreeing schemas would make the same call mean different things depending
|
||||
* on which plugin won selection, and that is not a diagnosable failure -- it
|
||||
* is silent numerical garbage (§2.3). The whole plugin is refused, not just
|
||||
* the op: a plugin built against a different vocabulary is stale everywhere. */
|
||||
err_("op '%s' has two different schemas: '%s' fixed it first, '%s' disagrees "
|
||||
"(%s) -- refusing '%s'",
|
||||
sch->op, it->second.plugin.c_str(), p.name.c_str(), diff.c_str(),
|
||||
p.name.c_str());
|
||||
unstage_(s);
|
||||
return RAD_E_DUPLICATE;
|
||||
}
|
||||
continue; /* same-shape re-declaration: expected, every plugin declares its ops */
|
||||
}
|
||||
for (const RadOpSchema* q : staged_schemas) {
|
||||
if (std::strcmp(q->op, sch->op) == 0 && !schema_same(*q, *sch, &diff)) {
|
||||
err_("kernel plugin '%s' declares op '%s' twice with different schemas (%s)",
|
||||
p.name.c_str(), sch->op, diff.c_str());
|
||||
unstage_(s);
|
||||
return RAD_E_DUPLICATE;
|
||||
}
|
||||
}
|
||||
staged_schemas.push_back(sch);
|
||||
}
|
||||
|
||||
for (int i = 0, n = k_n(); i < n; ++i) {
|
||||
const RadKernelInfo* k = k_at(i);
|
||||
if (!k || !k->name || !k->op || !k->op[0]) {
|
||||
err_("kernel plugin '%s' declares a kernel with no name or op at index %d",
|
||||
p.name.c_str(), i);
|
||||
unstage_(s);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
/* A row with no entry point is a row that resolves and then cannot run, which is the
|
||||
* one failure this layer exists to make impossible. */
|
||||
if (!k->launch) {
|
||||
err_("kernel '%s' in plugin '%s' has no launch function", k->name, p.name.c_str());
|
||||
unstage_(s);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (k->domain != RAD_DOMAIN_DEVICE && k->domain != RAD_DOMAIN_HOST) {
|
||||
err_("kernel '%s' in plugin '%s' declares domain %d, which is neither device nor "
|
||||
"host", k->name, p.name.c_str(), k->domain);
|
||||
unstage_(s);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
/* EVERY TUNABLE AXIS CARRIES A DEFAULT, AND THE DEFAULT IS ONE OF ITS OWN VALUES.
|
||||
*
|
||||
* This is what makes an untuned install fast rather than broken (spec §15): a machine
|
||||
* with no cache, a shape nobody measured, a cache from a different card -- all of them
|
||||
* land on the defaults, and there is no other fallback beneath them. A kernel that
|
||||
* declares an axis without a usable default has no answer at all for those cases, so
|
||||
* it is refused here rather than resolving and then launching a zero tile.
|
||||
*
|
||||
* Checked at LOAD and not at first use, for the same reason the missing launch
|
||||
* function above is: a library author finds out when the plugin loads, not when some
|
||||
* shape three hours into a serve happens to miss the cache. */
|
||||
for (int v = 0; v < k->n_tunables; ++v) {
|
||||
const RadTunable& t = k->tunables[v];
|
||||
if (!t.key || !t.key[0] || !t.values || t.n_values <= 0) {
|
||||
err_("kernel '%s' in plugin '%s' declares tunable %d with no key or no legal "
|
||||
"values", k->name, p.name.c_str(), v);
|
||||
unstage_(s);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
bool ok = false;
|
||||
for (int j = 0; j < t.n_values; ++j) if (t.values[j] == t.deflt) ok = true;
|
||||
if (!ok) {
|
||||
err_("kernel '%s' in plugin '%s': tunable '%s' defaults to %lld, which is not "
|
||||
"one of the values it declares. The default is what runs when this "
|
||||
"machine has no measurement for a shape, so it has to be a value the "
|
||||
"kernel can actually launch",
|
||||
k->name, p.name.c_str(), t.key, (long long)t.deflt);
|
||||
unstage_(s);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
for (int w = 0; w < v; ++w)
|
||||
if (k->tunables[w].key && std::strcmp(k->tunables[w].key, t.key) == 0) {
|
||||
err_("kernel '%s' in plugin '%s' declares tunable '%s' twice", k->name,
|
||||
p.name.c_str(), t.key);
|
||||
unstage_(s);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
}
|
||||
staged_rows.emplace_back(k, i);
|
||||
}
|
||||
|
||||
/* A KERNEL LIBRARY WITH NO CODE FOR THIS CARD IS LEFT OUT OF THE CARD'S SELECTION. Its
|
||||
* device rows would otherwise resolve -- a row's constraints say nothing about which card
|
||||
* it was compiled for -- and the first launch would fail, so an installation carrying
|
||||
* libraries for several cards would serve none of them but the first in the hierarchy.
|
||||
* What the library carries is read out of the fat binaries its dlopen registered, which is
|
||||
* what the launch itself will consult (core/device/aql_code.cpp), not out of
|
||||
* build_target, which is prose. Its host rows run anywhere and stay. */
|
||||
int n_device = 0;
|
||||
for (const auto& r : staged_rows) n_device += r.first->domain == RAD_DOMAIN_DEVICE;
|
||||
std::string why;
|
||||
if (n_device > 0 && s.code_to > s.code_from &&
|
||||
rad::dev_code_runs(s.code_from, s.code_to, code_device_, &why) == 0) {
|
||||
std::vector<std::pair<const RadKernelInfo*, int>> keep;
|
||||
for (const auto& r : staged_rows)
|
||||
if (r.first->domain != RAD_DOMAIN_DEVICE) keep.push_back(r);
|
||||
RAD_WARN("kernel plugin '%s' has no device code for device %d: %s. Its %d device "
|
||||
"kernel(s) are left out of selection here%s.", p.name.c_str(), code_device_,
|
||||
why.c_str(), n_device,
|
||||
keep.empty() ? "" : fmt(" and its %zu host kernel(s) stay", keep.size()).c_str());
|
||||
staged_rows.swap(keep);
|
||||
p.device_code_absent = true;
|
||||
}
|
||||
} else if (p.kind == RAD_PLUGIN_QUANT) {
|
||||
auto q_n = dl_fn<int (*)(void)>(s.handle, "rad_quant_count");
|
||||
auto q_at = dl_fn<const RadQuantizerInfo* (*)(int)>(s.handle, "rad_quant_at");
|
||||
if (!q_n || !q_at) {
|
||||
err_("quantiser plugin '%s' is missing rad_quant_count or rad_quant_at",
|
||||
p.name.c_str());
|
||||
unstage_(s);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
/* Checked WHOLE before any is registered, for the reason the kernel schemas are: a plugin
|
||||
* refused on its third quantiser must not leave the first two answering to a recipe. */
|
||||
for (int i = 0, n = q_n(); i < n; ++i) {
|
||||
const RadQuantizerInfo* q = q_at(i);
|
||||
if (!q || !q->name || !q->name[0] || !q->encoding || !q->quantize) {
|
||||
err_("quantiser plugin '%s' declares a quantiser with no name, no encoding hook or "
|
||||
"no quantize hook at index %d", p.name.c_str(), i);
|
||||
unstage_(s);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
/* A NAME IS ONE QUANTISER. A recipe that names it would otherwise mean different
|
||||
* numbers depending on which plugin loaded first. */
|
||||
auto clash = [&](const char* other) { return std::strcmp(other, q->name) == 0; };
|
||||
for (const QuantRow& r : quants_)
|
||||
if (clash(r.info->name)) {
|
||||
err_("quantiser '%s' is offered by both '%s' and '%s' -- refusing '%s'",
|
||||
q->name, r.plugin.c_str(), p.name.c_str(), p.name.c_str());
|
||||
unstage_(s);
|
||||
return RAD_E_DUPLICATE;
|
||||
}
|
||||
for (const RadQuantizerInfo* o : staged_quants)
|
||||
if (clash(o->name)) {
|
||||
err_("quantiser plugin '%s' declares '%s' twice", p.name.c_str(), q->name);
|
||||
unstage_(s);
|
||||
return RAD_E_DUPLICATE;
|
||||
}
|
||||
staged_quants.push_back(q);
|
||||
}
|
||||
} else {
|
||||
err_("plugin '%s' declares kind %u, which is not a kernel, architecture or quantiser "
|
||||
"plugin", p.name.c_str(), p.kind);
|
||||
unstage_(s);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
|
||||
/* Once after the plugin is loaded and before any selection (rad_abi.h). A plugin that cannot
|
||||
* open -- no device, no config table -- is refused rather than asked to select. */
|
||||
if (auto open = dl_fn<RadPluginOpenFn>(s.handle, "rad_plugin_open")) {
|
||||
int st = open();
|
||||
/* RAD_E_UNSUPPORTED is a plugin saying this machine is not one it serves -- a library for
|
||||
* another card, in an installation that ships several. That is a skip, said once, and
|
||||
* not a failure: the next library in the hierarchy is the one that serves this card. */
|
||||
if (st == RAD_E_UNSUPPORTED) {
|
||||
RAD_INFO("plugin '%s' declines this machine and is not loaded", p.name.c_str());
|
||||
unstage_(s);
|
||||
return 1;
|
||||
}
|
||||
if (st < 0) {
|
||||
err_("plugin '%s' refused to open: %s", p.name.c_str(), rad_strerror(st));
|
||||
unstage_(s);
|
||||
return st;
|
||||
}
|
||||
}
|
||||
|
||||
/* What the plugin DECLARES, not what it fixed: a plugin below another one re-declares the same
|
||||
* ops with the same shapes, and reporting 0 there would read as a plugin that declares
|
||||
* nothing. Which plugin fixed a given op is schema_owner()'s answer, not a count. */
|
||||
p.n_schemas = n_declared_schemas;
|
||||
p.n_kernels = (int)staged_rows.size();
|
||||
for (const RadOpSchema* sch : staged_schemas) schemas_[sch->op] = SchemaEntry{sch, p.name};
|
||||
for (const RadQuantizerInfo* q : staged_quants) {
|
||||
quants_.push_back(QuantRow{ q, p.name });
|
||||
/* Its own schemes are read through it, by everything that decodes a weight. */
|
||||
if (q->decode) enc_add_decoder(q->decode);
|
||||
}
|
||||
const auto concurrent = dl_fn<RadKernelConcurrentFn>(s.handle, "rad_kernel_concurrent");
|
||||
for (const auto& sr : staged_rows) {
|
||||
KernelRow row;
|
||||
row.info = sr.first;
|
||||
row.plugin = p.name;
|
||||
row.plugin_order = order;
|
||||
row.index = sr.second;
|
||||
row.concurrent = concurrent && concurrent(sr.second) != 0;
|
||||
row.reference = p.reference;
|
||||
rows_.push_back(row);
|
||||
}
|
||||
|
||||
/* A KERNEL LIBRARY BUILT FOR ANOTHER CARD FAILS AT EVERY LAUNCH, AND THIS IS THE ONE PLACE IT
|
||||
* CAN BE NAMED ONCE. An installed .so travelling to a machine it was not compiled for is
|
||||
* otherwise invisible until the first dispatch, where it surfaces as a driver error carrying a
|
||||
* kernel name and nothing about why.
|
||||
*
|
||||
* A WARNING AND NOT A REFUSAL, deliberately. build_target is text the plugin's author writes;
|
||||
* it is not derived from what the binary actually contains, so a library covering several
|
||||
* architectures may still name only one, and refusing on it would be refusing on a claim the
|
||||
* engine cannot verify. The launch is what is authoritative. This predicts it by name.
|
||||
*
|
||||
* "host" and "" are not claims about a device: the first is a library of CPU kernels, which
|
||||
* run anywhere, and the second is a plugin that declines to claim anything. */
|
||||
if (p.kind == RAD_PLUGIN_KERNEL && s.code_to == s.code_from && !p.build_target.empty() &&
|
||||
p.build_target != "host") {
|
||||
RadDeviceProps dp{};
|
||||
if (rad_dev_count() > code_device_ && rad_dev_props(code_device_, &dp) == RAD_OK &&
|
||||
dp.arch[0] && !target_covers(p.build_target, dp.arch))
|
||||
RAD_WARN("kernel plugin '%s' declares it was built for %s and this machine reports %s. "
|
||||
"Its kernels will fail to launch; build it for %s, or put a library that "
|
||||
"serves this device ahead of it with --kernels.",
|
||||
p.name.c_str(), p.build_target.c_str(), dp.arch, dp.arch);
|
||||
}
|
||||
|
||||
RAD_DEBUG("plugin %d: %s %s (%s) -- %d kernels, %d schemas, %zu fat binaries, %s", order,
|
||||
p.name.c_str(), p.version.c_str(), p.path.c_str(), p.n_kernels, p.n_schemas,
|
||||
s.code_to - s.code_from, p.build_target.empty() ? "portable" : p.build_target.c_str());
|
||||
plugins_.push_back(std::move(p));
|
||||
index_rows_();
|
||||
s.handle = nullptr; /* the Plugin owns it now */
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* The per-op index select() walks, in (hierarchy order, declaration order). Rebuilt whole on every
|
||||
* registration: loading is startup and the row count is in the hundreds, so the simple thing is
|
||||
* also the fast enough thing, and an index that can never be stale is one fewer invariant. */
|
||||
void Registry::index_rows_() {
|
||||
by_op_.clear();
|
||||
for (const KernelRow& r : rows_) by_op_[r.info->op].push_back(&r);
|
||||
for (auto& kv : by_op_) {
|
||||
std::stable_sort(kv.second.begin(), kv.second.end(),
|
||||
[](const KernelRow* a, const KernelRow* b) {
|
||||
if (a->plugin_order != b->plugin_order)
|
||||
return a->plugin_order < b->plugin_order;
|
||||
return a->index < b->index;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ the public loading API */
|
||||
int Registry::load_plugin(const std::string& path, int order) {
|
||||
Staged s;
|
||||
int st = stage_(path, &s);
|
||||
if (st < 0) return st;
|
||||
return commit_(s, order);
|
||||
}
|
||||
|
||||
int Registry::load_dir(const std::string& dir, const std::vector<std::string>& hierarchy) {
|
||||
return load_dirs({ dir }, hierarchy);
|
||||
}
|
||||
|
||||
int Registry::load_dirs(const std::vector<std::string>& dirs,
|
||||
const std::vector<std::string>& hierarchy) {
|
||||
int first_error = RAD_OK;
|
||||
|
||||
/* Directory by directory in the order given, and within one in filename order, so a set of
|
||||
* plugins nobody named still loads the same way twice. A file whose name an earlier directory
|
||||
* already supplied is SHADOWED rather than loaded: the first directory is the one the operator
|
||||
* put first -- their own plugins ahead of an installation's -- and loading both would be two
|
||||
* plugins claiming one name, which is refused. */
|
||||
std::vector<std::string> files, stems;
|
||||
std::string where;
|
||||
for (const std::string& dir : dirs) {
|
||||
DIR* d = opendir(dir.c_str());
|
||||
if (!d) {
|
||||
err_("plugin directory '%s': %s", dir.c_str(), std::strerror(errno));
|
||||
return RAD_E_IO;
|
||||
}
|
||||
where += (where.empty() ? "" : ", ") + dir;
|
||||
std::vector<std::string> here;
|
||||
while (const dirent* e = readdir(d)) {
|
||||
const std::string n = e->d_name;
|
||||
if (n.size() < 4 || n.compare(n.size() - 3, 3, ".so") != 0) continue;
|
||||
const std::string path = dir + "/" + n;
|
||||
struct stat st {};
|
||||
if (stat(path.c_str(), &st) != 0 || !S_ISREG(st.st_mode)) continue;
|
||||
here.push_back(path);
|
||||
}
|
||||
closedir(d);
|
||||
std::sort(here.begin(), here.end());
|
||||
for (const std::string& f : here) {
|
||||
const std::string stem = stem_of(f);
|
||||
auto at = std::find(stems.begin(), stems.end(), stem);
|
||||
if (at != stems.end()) {
|
||||
RAD_INFO("plugin %s is shadowed by %s, which comes first on the search path",
|
||||
f.c_str(), files[(size_t)(at - stems.begin())].c_str());
|
||||
continue;
|
||||
}
|
||||
files.push_back(f);
|
||||
stems.push_back(stem);
|
||||
}
|
||||
}
|
||||
const std::string dir = where;
|
||||
|
||||
std::vector<Staged> staged;
|
||||
for (const std::string& f : files) {
|
||||
Staged s;
|
||||
int st = stage_(f, &s);
|
||||
if (st < 0) {
|
||||
if (first_error == RAD_OK) first_error = st;
|
||||
continue;
|
||||
}
|
||||
staged.push_back(s);
|
||||
}
|
||||
|
||||
/* The hierarchy is configured, not discovered. A plugin the operator named takes that
|
||||
* position; a plugin present on disk but absent from the list loads after everything named,
|
||||
* so dropping an .so into the directory adds it with no configuration and naming it ahead of
|
||||
* another is what substitutes it.
|
||||
*
|
||||
* A REFERENCE LIBRARY IS PINNED BELOW EVERY OTHER UNNAMED PLUGIN. It declares a kernel for
|
||||
* every op it knows, so a plugin ranked behind it is unreachable -- an unnamed kernel library
|
||||
* for this machine's card would load, never be selected for anything, and leave the whole
|
||||
* model resolving to the naive implementation. Pinning it is what makes an unconfigured
|
||||
* drop-in work. Naming it in the hierarchy overrides this, which is how it is put in front of
|
||||
* a library to compare against. Which library is one is its own declaration
|
||||
* (RadPluginReferenceFn), not its name. */
|
||||
const size_t kUnnamed = (size_t)INT_MAX - 1;
|
||||
std::vector<size_t> rank(staged.size());
|
||||
for (size_t i = 0; i < staged.size(); ++i)
|
||||
rank[i] = staged[i].reference ? (size_t)INT_MAX : kUnnamed;
|
||||
for (size_t h = 0; h < hierarchy.size(); ++h) {
|
||||
bool found = false;
|
||||
for (size_t i = 0; i < staged.size(); ++i) {
|
||||
if (staged[i].name == hierarchy[h] || staged[i].file == hierarchy[h]) {
|
||||
rank[i] = h;
|
||||
found = true;
|
||||
}
|
||||
}
|
||||
if (!found)
|
||||
RAD_WARN("kernel hierarchy names '%s', which is not in %s -- ignored",
|
||||
hierarchy[h].c_str(), dir.c_str());
|
||||
}
|
||||
std::vector<size_t> idx(staged.size());
|
||||
for (size_t i = 0; i < idx.size(); ++i) idx[i] = i;
|
||||
std::stable_sort(idx.begin(), idx.end(),
|
||||
[&](size_t a, size_t b) { return rank[a] < rank[b]; });
|
||||
|
||||
/* Orders continue from what is already loaded, so loading kernels/ and then architectures/
|
||||
* does not produce two plugins at position 0. */
|
||||
int order = 0;
|
||||
for (const Plugin& p : plugins_) order = std::max(order, p.order + 1);
|
||||
|
||||
for (size_t i : idx) {
|
||||
int st = commit_(staged[i], order);
|
||||
if (st < 0) {
|
||||
if (first_error == RAD_OK) first_error = st;
|
||||
continue; /* refused, and the next plugin still gets its chance */
|
||||
}
|
||||
if (st > 0) continue; /* declined this machine */
|
||||
++order;
|
||||
}
|
||||
|
||||
int st = check_complete();
|
||||
if (st < 0 && first_error == RAD_OK) first_error = st;
|
||||
return first_error;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ the tuning cache (§15) */
|
||||
int Registry::load_tune(const std::string& radiance_home, const std::string& machine) {
|
||||
const std::string key = machine.empty() ? rad_machine_key() : machine;
|
||||
const int s = tune_.load(radiance_home, key);
|
||||
if (s < 0) return s;
|
||||
/* A cache measured on another card is not a slower answer, it is a wrong one -- tunecache.h
|
||||
* makes the machine key line 2 of the file for exactly this. `load` already refuses a
|
||||
* mismatch, so reaching here with rows means they are this machine's. */
|
||||
return (int)tune_.rows().size();
|
||||
}
|
||||
|
||||
/* Kernel plugins declare the ops they implement AND the parameter schema for each. A row whose op
|
||||
* has no schema anywhere in the loaded set is a plugin that supplied only half of that contract,
|
||||
* and the cost is exact: no architecture plugin's parameters for that op can ever be checked, so a
|
||||
* typo in them becomes a silent miss instead of a named one. Checked once the set is complete,
|
||||
* because an override plugin may legitimately rely on the schema of the plugin BELOW it, which
|
||||
* loads later. */
|
||||
int Registry::check_complete() {
|
||||
int st = RAD_OK;
|
||||
for (const KernelRow& r : rows_) {
|
||||
if (schemas_.find(r.info->op) == schemas_.end()) {
|
||||
err_("kernel '%s' in plugin '%s' implements op '%s', which no loaded plugin declares a "
|
||||
"schema for", r.info->name, r.plugin.c_str(), r.info->op);
|
||||
st = RAD_E_NOSCHEMA;
|
||||
}
|
||||
}
|
||||
return st;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ lookup and teardown */
|
||||
const Plugin* Registry::plugin(std::string_view name) const {
|
||||
for (const Plugin& p : plugins_)
|
||||
if (p.name == name || p.file == name) return &p;
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
const Registry::QuantRow* Registry::quantizer(std::string_view name) const {
|
||||
for (const QuantRow& q : quants_)
|
||||
if (name == q.info->name) return &q;
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
const std::vector<const KernelRow*>* Registry::rows_for(std::string_view op) const {
|
||||
auto it = by_op_.find(std::string(op));
|
||||
return it == by_op_.end() ? nullptr : &it->second;
|
||||
}
|
||||
|
||||
void Registry::close() {
|
||||
fini_instances();
|
||||
for (const QuantRow& q : quants_)
|
||||
if (q.info && q.info->decode) enc_remove_decoder(q.info->decode);
|
||||
/* Reverse order: a plugin lower in the hierarchy may have been opened against state a higher
|
||||
* one established, and unwinding in the order things were built is the only order that is
|
||||
* always safe. */
|
||||
for (auto it = plugins_.rbegin(); it != plugins_.rend(); ++it) {
|
||||
if (it->close) it->close();
|
||||
if (it->handle) dlclose(it->handle);
|
||||
}
|
||||
plugins_.clear();
|
||||
rows_.clear();
|
||||
quants_.clear();
|
||||
by_op_.clear();
|
||||
schemas_.clear();
|
||||
load_errors_.clear();
|
||||
clear_selections();
|
||||
}
|
||||
|
||||
Registry::~Registry() { close(); }
|
||||
|
||||
} /* namespace rad */
|
||||
@@ -0,0 +1,358 @@
|
||||
/* registry.h -- the plugin layer: dlopen, the configured hierarchy, the op-schema registry, the
|
||||
* constraint selector, bucket tables and the selection table. spec.md §2 and §16.
|
||||
*
|
||||
* Four rules live here and nowhere else, because every one of them is a rule somebody would
|
||||
* otherwise reinvent slightly differently in a second place:
|
||||
*
|
||||
* THE HIERARCHY IS ABSOLUTE. Plugins are queried in configured order and the first plugin with
|
||||
* any matching kernel supplies it. A lower-priority plugin never outbids a higher one no matter
|
||||
* how specialised its kernel -- that is what makes a user override an override (§2.1).
|
||||
*
|
||||
* SPECIFICITY IS DECLARED, NOT DERIVED. Within one plugin the highest `priority` among matching
|
||||
* rows wins, ties broken by declaration order. Counting matched constraints gets it backwards:
|
||||
* {head_dim<=1024, gqa>=1, block%16==0, causal in {0,1}} matches four and {head_dim==256, gqa==6}
|
||||
* matches two, and the second is by far the more specialised.
|
||||
*
|
||||
* SCHEMAS ARE FIXED BY FIRST DECLARATION. The first plugin in hierarchy order to declare an op
|
||||
* fixes its schema; a later plugin declaring the same op name with a different one is refused at
|
||||
* load with both plugins named. Arguments are positional, so two disagreeing schemas make the
|
||||
* same call mean different things depending on which plugin won selection -- silent numerical
|
||||
* garbage rather than a diagnosable failure (§2.3).
|
||||
*
|
||||
* THE BUCKET BOUNDARIES ARE THE CONSTRAINT VALUES THEMSELVES. The union of the LE, GE and EQ
|
||||
* values candidate kernels place on the ranged parameter, clamped to the declared range. No
|
||||
* policy is chosen by anyone (§2.2).
|
||||
*
|
||||
* A REFERENCE LIBRARY IS LAST BY CONSTRUCTION. A library that declares itself one
|
||||
* (RadPluginReferenceFn) matches every op it declares, so anything ranked behind it would be
|
||||
* unreachable. An unnamed plugin sorts after every named one but still ahead of a reference,
|
||||
* which is what makes dropping in a kernel library for a new card work with no configuration
|
||||
* (§2.1). Naming it in the hierarchy still overrides that. The rule is keyed on the declaration,
|
||||
* never on a name: the libraries that ship with radiance load exactly as a third party's do.
|
||||
*
|
||||
* LIFETIME. A Resolved, a Band and a KernelRow all point into a plugin's static tables. They are
|
||||
* valid exactly as long as the Registry that loaded them: close() dlcloses, and everything handed
|
||||
* out before it dangles after. The core keeps one Registry for the life of the process, so this
|
||||
* costs nothing; a tool that loads two kernel sets in turn has to finish with the first.
|
||||
*
|
||||
* THREADING. Loading is startup, single-threaded, before the rank threads exist. select() and
|
||||
* init_instance() are called from every rank thread during declare, so the selection log and the
|
||||
* instance list are behind one mutex. It is uncontended at declare and never touched on the step
|
||||
* path, which is the only place a lock would cost anything.
|
||||
*/
|
||||
#pragma once
|
||||
#include "rad_core.h"
|
||||
#include "rad_quant.h"
|
||||
#include "../format/tunecache.h"
|
||||
|
||||
#include <deque>
|
||||
#include <mutex>
|
||||
#include <functional>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <unordered_map>
|
||||
#include <vector>
|
||||
|
||||
namespace rad {
|
||||
|
||||
inline const char* domain_name(int d) { return d == RAD_DOMAIN_HOST ? "host" : "device"; }
|
||||
|
||||
|
||||
/* ------------------------------------------------------------------ one loaded .so */
|
||||
struct Plugin {
|
||||
std::string name; /* RadPluginInfo::name -- what the hierarchy list names */
|
||||
std::string file; /* the .so's stem; the hierarchy list accepts this spelling too */
|
||||
std::string path;
|
||||
std::string version;
|
||||
std::string description;
|
||||
std::string build_target;
|
||||
|
||||
uint32_t kind = 0; /* RAD_PLUGIN_KERNEL | RAD_PLUGIN_ARCH */
|
||||
int order = 0; /* hierarchy position; 0 is highest */
|
||||
void* handle = nullptr;
|
||||
|
||||
int n_kernels = 0;
|
||||
int n_schemas = 0;
|
||||
/* A kernel library whose fat binaries hold no code object the card runs: its device rows were
|
||||
* left out at load (loader.cpp, commit_), and only its host rows are selectable. */
|
||||
bool device_code_absent = false;
|
||||
/* A kernel library that declared itself a reference implementation (RadPluginReferenceFn). */
|
||||
bool reference = false;
|
||||
|
||||
/* Architecture plugins are loaded and IDENTIFIED here; the build component drives them. The
|
||||
* core never calls declare or step from the registry -- it only guarantees that no two
|
||||
* plugins claim the same (architecture id, quantisation) PAIR (§2.4). The pair, not the id:
|
||||
* qwen35_bf16 and qwen35_fp8 are the same architecture at two weight formats and both answer
|
||||
* "qwen35", which is the whole reason §2.4 splits on quantisation at all. `arch_quant` is ""
|
||||
* for a plugin that serves an unquantised container, including one that predates the export. */
|
||||
std::string arch_id;
|
||||
std::string arch_quant;
|
||||
int (*arch_declare)(RadBuilder*, const RadModelMeta*, const RadBuildCtx*) = nullptr;
|
||||
void (*arch_step)(RadCtx*, const RadBatch*) = nullptr;
|
||||
/* OPTIONAL (rad_builder.h): null when the plugin exports none, and every question then
|
||||
* answers zero. It is what the core asks BEFORE declare, so that a fact which is an input to
|
||||
* declaration and a property of the model is still read by the plugin and not by us. */
|
||||
int (*arch_probe)(const RadModelMeta*, RadArchProbe*) = nullptr;
|
||||
/* OPTIONAL (rad_builder.h): null when the plugin exports none, and the reply format is then
|
||||
* derived from the chat template. */
|
||||
const RadChatFormat* (*arch_chat_format)(const RadModelMeta*) = nullptr;
|
||||
|
||||
RadPluginCloseFn close = nullptr;
|
||||
};
|
||||
|
||||
/* ------------------------------------------------------------------ one selection question */
|
||||
/* What select() did, in enough detail to print §16's table and to answer "why did it not pick the
|
||||
* kernel I wrote". `candidates` is every row that was CONSIDERED -- rows of the other domain are
|
||||
* not, since they answer a different question, and rows behind a plugin that already supplied a
|
||||
* match are not either, because the hierarchy stopped there. */
|
||||
struct SelectionTrace {
|
||||
struct Candidate {
|
||||
std::string plugin;
|
||||
std::string kernel;
|
||||
int priority = 0;
|
||||
bool ok = false;
|
||||
std::string why; /* the constraint that refused it, or "ok" */
|
||||
};
|
||||
|
||||
std::string op;
|
||||
std::string query; /* the geometry as asked */
|
||||
int domain = RAD_DOMAIN_DEVICE;
|
||||
|
||||
std::string kernel; /* empty on a miss */
|
||||
std::string plugin;
|
||||
int priority = 0;
|
||||
std::string reason; /* on a miss: the constraint(s) that refused it */
|
||||
|
||||
/* A RAD_DERIVED parameter the CALLER did not supply: its constraints were skipped during
|
||||
* matching, and the winning kernel's RAD_C_EQ value for the key was written into the resolved
|
||||
* geometry afterwards. `known` is false when the winner has no EQ on that key -- ref's
|
||||
* `block_size >= 1` is exactly that case -- and an unset derived key is a condition the
|
||||
* caller has to report, not a zero to be read. */
|
||||
struct DerivedParam {
|
||||
std::string key;
|
||||
long long value = 0;
|
||||
bool known = false;
|
||||
};
|
||||
std::vector<DerivedParam> derived;
|
||||
|
||||
std::vector<Candidate> candidates;
|
||||
bool other_domain_has_rows = false; /* the op exists, just not in the domain asked for */
|
||||
};
|
||||
|
||||
/* ------------------------------------------------------------------ the registry */
|
||||
class Registry {
|
||||
public:
|
||||
Registry() = default;
|
||||
~Registry();
|
||||
Registry(const Registry&) = delete;
|
||||
Registry& operator=(const Registry&) = delete;
|
||||
|
||||
/* ---------------------------------------------------------- loading (§2, §18) */
|
||||
/* Scan a directory of .so files and load them in HIERARCHY ORDER. The hierarchy is configured,
|
||||
* not discovered: `hierarchy` is an ordered list of plugin names (RadPluginInfo::name, or the
|
||||
* file's stem, whichever the operator wrote), so substituting a kernel is dropping an .so in a
|
||||
* directory and naming it ahead of the default. A plugin present on disk but absent from the
|
||||
* list loads at the END, after everything named, in filename order so the result is
|
||||
* reproducible.
|
||||
*
|
||||
* Always completes: every plugin that can be loaded is, every refusal is recorded in
|
||||
* load_errors(), and the FIRST negative status is returned. Reporting the whole list beats
|
||||
* reporting the first failure at the top -- an operator with two stale plugins wants to hear
|
||||
* about both in one run (§3.1). */
|
||||
int load_dir(const std::string& dir, const std::vector<std::string>& hierarchy);
|
||||
/* The same over several directories -- a $RADIANCE_HOME search path -- as one set: the
|
||||
* hierarchy orders plugins across all of them, and a file an earlier directory already holds
|
||||
* by the same name is shadowed, not loaded. */
|
||||
int load_dirs(const std::vector<std::string>& dirs, const std::vector<std::string>& hierarchy);
|
||||
|
||||
/* One plugin at a known hierarchy position. rad-info and rad-kbench load a single .so; the
|
||||
* engine goes through load_dir. 1, and nothing registered, when the plugin declines this
|
||||
* machine (its rad_plugin_open answers RAD_E_UNSUPPORTED). */
|
||||
int load_plugin(const std::string& path, int order);
|
||||
|
||||
/* Every registered kernel row's op must have a schema SOMEWHERE in the loaded set -- an
|
||||
* override plugin may legitimately ship kernels for an op whose schema the plugin below it
|
||||
* declared, and that plugin loads later, so the check can only run once the set is complete.
|
||||
* load_dir calls this; a caller assembling a set by hand calls it when it is done. */
|
||||
int check_complete();
|
||||
|
||||
/* The device a kernel library's device code is checked against when it loads: the first card
|
||||
* the caller will run on. 0 unless the caller says otherwise -- the engine says so before it
|
||||
* loads anything, once it has chosen its cards. */
|
||||
void set_code_device(int device) { code_device_ = device; }
|
||||
|
||||
void close(); /* fini instances, close hooks, dlclose, forget everything */
|
||||
|
||||
const std::vector<Plugin>& plugins() const { return plugins_; }
|
||||
const Plugin* plugin(std::string_view name) const;
|
||||
const std::vector<std::string>& load_errors() const { return load_errors_; }
|
||||
|
||||
/* Every quantiser the loaded quantiser plugins offer, in load order. A name is unique across
|
||||
* them -- two plugins naming one quantiser is refused at load -- so the lookup is the answer
|
||||
* and not the first of several. Null when nothing offers it. */
|
||||
struct QuantRow {
|
||||
const RadQuantizerInfo* info = nullptr;
|
||||
std::string plugin;
|
||||
};
|
||||
const std::deque<QuantRow>& quantizers() const { return quants_; }
|
||||
const QuantRow* quantizer(std::string_view name) const;
|
||||
|
||||
/* Every kernel row, in (hierarchy order, declaration order). rad-info prints this. */
|
||||
const std::deque<KernelRow>& rows() const { return rows_; }
|
||||
/* The rows implementing one op, in the order select() considers them. Empty if none. */
|
||||
const std::vector<const KernelRow*>* rows_for(std::string_view op) const;
|
||||
|
||||
/* ---------------------------------------------------------- op schemas (§2.3) */
|
||||
const RadOpSchema* schema(std::string_view op) const;
|
||||
const Plugin* schema_owner(std::string_view op) const;
|
||||
std::vector<std::string> op_names() const; /* sorted; the vocabulary this set implements */
|
||||
|
||||
/* Check a declared parameter set against the op's schema. Without this, a typo and an
|
||||
* unimplemented op are the same diagnostic; with it, a misspelled op fails declare with the
|
||||
* near-miss named. Returns RAD_OK, RAD_E_NOSCHEMA (no such op) or RAD_E_SCHEMA, and fills
|
||||
* `err` with a sentence an architecture-plugin author can act on. */
|
||||
int validate(std::string_view op, const RadParam* p, int n_p, std::string* err) const;
|
||||
|
||||
/* The closest known op name to `op` within a small edit distance, or "" if nothing is close.
|
||||
* Public because the builder wants it in its own messages too. */
|
||||
std::string near_miss(std::string_view op) const;
|
||||
|
||||
/* ---------------------------------------------------------- the tuning cache (§15) */
|
||||
/* Load $RADIANCE_HOME/tune/<machine>.tune, which rad-tune wrote. resolve() then moves a shape
|
||||
* off each axis's declared default wherever there is a row for it. A missing file is not an
|
||||
* error and leaves every shape on that default, which is what makes an untuned install fast
|
||||
* rather than broken.
|
||||
*
|
||||
* THE CORE OWNS THE CACHE AND THE POLICY, so no plugin has to (tunecache.h; the choice is
|
||||
* applied in select.cpp). Without this call every kernel runs its axis defaults whatever the
|
||||
* file on disk says, which is slow rather than wrong -- but silently so.
|
||||
*
|
||||
* Returns the number of rows loaded, or a negative status. */
|
||||
int load_tune(const std::string& radiance_home, const std::string& machine = std::string());
|
||||
const TuneCache& tune() const { return tune_; }
|
||||
|
||||
/* ---------------------------------------------------------- selection (§2.1) */
|
||||
/* The first plugin in hierarchy order with any matching row supplies the kernel; within that
|
||||
* plugin the highest declared priority wins, ties on declaration order. Null on a miss, with
|
||||
* the refusing constraint in `why->reason`. Every call is recorded in the selection table.
|
||||
*
|
||||
* RAD_DERIVED parameters (rad_abi.h) are supplied by the KERNEL, so a constraint on one is
|
||||
* SKIPPED here when the caller did not name it, and the winner's RAD_C_EQ value for the key
|
||||
* comes back in `why->derived` -- resolve() is what writes it into the geometry. Without that
|
||||
* skip, spec §7.2 is circular: the block manager reads the block size off the resolved
|
||||
* attention kernel, but a kernel constrained to block_size == 16 can never be selected by a
|
||||
* query that omits block_size, because a constraint whose key the geometry lacks does not
|
||||
* hold. A caller that supplies the key anyway pins it and matches normally, which is how an
|
||||
* operator forces a block size and gets a refusal by name instead of a substitution. */
|
||||
/* `record` is false for a caller asking the selector a question the ENGINE did not ask -- the
|
||||
* graph dump replays every band to recover the candidate list it threw away. The selection
|
||||
* table is a record of what this deployment resolved, and a reporting tool inflating its
|
||||
* counts would make it a record of itself. */
|
||||
/* `accept`, when given, is asked of every row whose constraints hold, and an answer that is
|
||||
* not empty takes the row out as a candidate with that answer as the reason. It is how a
|
||||
* weight's encoding takes part in selection: a kernel whose layout hook does not read the
|
||||
* encoding a weight operand has (RAD_E_DTYPE) is not a candidate, and the next one is chosen
|
||||
* -- a bf16 lm_head goes to the bf16 GEMM instead of being refused by the fp8 one. */
|
||||
using RowFilter = std::function<std::string(const KernelRow&, const Geometry&)>;
|
||||
const KernelRow* select(std::string_view op, const Geometry& g, int domain,
|
||||
SelectionTrace* why = nullptr, bool record = true,
|
||||
const RowFilter* accept = nullptr);
|
||||
|
||||
/* Selection plus the per-instance bookkeeping: the tuned axes, where they came from, and the frozen
|
||||
* geometry -- the query plus whatever the winning kernel supplied for a derived key, so
|
||||
* rad_kv_block_size() and RadArgs.p both see it. init() is NOT called here -- see
|
||||
* init_instance(). */
|
||||
Resolved resolve(std::string_view op, const Geometry& g, int domain, SelectionTrace* why = nullptr,
|
||||
const RowFilter* accept = nullptr);
|
||||
|
||||
/* ---------------------------------------------------------- bucket tables (§2.2) */
|
||||
/* Resolve a ranged parameter into a bucket table: one resolution per band, per domain, built
|
||||
* at declare and indexed by the actual value at issue. The boundaries are the constraint
|
||||
* values themselves. Each band is resolved AT ITS UPPER BOUND, which is the worst case in the
|
||||
* band and therefore the only value that is safe to size and select on.
|
||||
*
|
||||
* `ranged_key` empty means the op has no ranged parameter: exactly one band is returned, whose
|
||||
* hi is INT64_MAX so the issue path's band scan always finds it.
|
||||
*
|
||||
* Both domains are resolved wherever both exist, so the core can change execution site at
|
||||
* runtime without re-resolving. Absence is asymmetric: a band with no DEVICE kernel is fatal
|
||||
* and the caller reports it (this function does not abort -- declare always completes); a band
|
||||
* with no HOST kernel is a warning naming the placement options it just removed. */
|
||||
std::vector<Band> build_bands(std::string_view op, std::string_view ranged_key,
|
||||
int64_t lo, int64_t hi, const Geometry& base,
|
||||
const RowFilter* accept = nullptr);
|
||||
|
||||
/* ---------------------------------------------------------- instances (§2.1) */
|
||||
/* init() once per resolved instance -- one op, one band, one domain -- with the frozen
|
||||
* geometry, the rank and the world size. libr4d's all-reduce needs its peer signal buffers and
|
||||
* IPC handles established across ranks before the first call, and a kernel that JITs or loads
|
||||
* a config table wants somewhere to do it that is not the hot path. A negative return aborts
|
||||
* startup and the caller names the kernel. */
|
||||
int init_instance(Resolved& r, int rank, int world_size);
|
||||
void fini_instances();
|
||||
size_t n_instances() const;
|
||||
|
||||
/* ---------------------------------------------------------- the selection table (§16) */
|
||||
/* Every DISTINCT question the selector was asked, in the order first asked, with what it
|
||||
* resolved to and, for a miss, the constraint that refused it. Repeats are folded and counted:
|
||||
* a 64-layer model asks the same question 64 times, and "asked 64 times" says how much of the
|
||||
* model resolved to that kernel. This is the record of why a fallback is running. */
|
||||
std::string selection_table() const;
|
||||
size_t n_selections() const;
|
||||
void clear_selections();
|
||||
|
||||
private:
|
||||
struct Staged {
|
||||
void* handle = nullptr;
|
||||
std::string path, file, name;
|
||||
const RadPluginInfo* info = nullptr;
|
||||
/* The device backend's fat-binary registrations before and after this plugin's dlopen:
|
||||
* [code_from, code_to) is the device code it brought in. */
|
||||
size_t code_from = 0, code_to = 0;
|
||||
bool reference = false; /* RadPluginReferenceFn answered nonzero */
|
||||
};
|
||||
|
||||
struct SchemaEntry {
|
||||
const RadOpSchema* schema = nullptr;
|
||||
std::string plugin; /* who fixed it, for the conflict message */
|
||||
};
|
||||
|
||||
struct SelectionRecord {
|
||||
std::string op, query, key, kernel, plugin, reason;
|
||||
std::string derived; /* "block_size:=16", rendered apart from the query because it
|
||||
* was NOT part of the question the selector was asked */
|
||||
int domain = 0;
|
||||
int priority = 0;
|
||||
long long count = 1;
|
||||
};
|
||||
|
||||
int code_device_ = 0;
|
||||
TuneCache tune_;
|
||||
|
||||
int stage_(const std::string& path, Staged* out);
|
||||
int commit_(Staged& s, int order);
|
||||
void unstage_(Staged& s);
|
||||
void index_rows_();
|
||||
void record_(const std::string& op, int domain, const Geometry& g, const SelectionTrace& t);
|
||||
void err_(const char* fmt, ...) __attribute__((format(printf, 2, 3)));
|
||||
|
||||
std::vector<Plugin> plugins_;
|
||||
std::deque<KernelRow> rows_; /* deque: KernelRow* handed out must stay valid */
|
||||
std::deque<QuantRow> quants_;
|
||||
std::unordered_map<std::string, std::vector<const KernelRow*>> by_op_;
|
||||
std::unordered_map<std::string, SchemaEntry> schemas_;
|
||||
std::vector<std::string> load_errors_;
|
||||
|
||||
mutable std::mutex mu_;
|
||||
std::vector<SelectionRecord> log_;
|
||||
std::vector<std::pair<const RadKernelInfo*, void*>> instances_;
|
||||
};
|
||||
|
||||
/* The value a kernel's own constraints place on one key, e.g. the paged block size the resolved
|
||||
* attention kernel is compiled for. §7.2: the block manager reads that off the resolved kernel and
|
||||
* sizes itself accordingly, because a core that picked its own block size would be a core that has
|
||||
* to be edited when a kernel changes. Returns false when the kernel says nothing about that key
|
||||
* with that operator -- which is not the same as a default, and the caller has to decide. */
|
||||
bool kernel_constraint(const KernelRow& r, std::string_view key, int c_op, long long* out);
|
||||
|
||||
} /* namespace rad */
|
||||
@@ -0,0 +1,202 @@
|
||||
/* schema.cpp -- the op-schema registry and the check an architecture plugin's declared parameters
|
||||
* go through. spec.md §2.3.
|
||||
*
|
||||
* Without a schema, a typo and an unimplemented op are the same diagnostic: both are "nothing
|
||||
* resolved". With one, a misspelled op fails declare with the near-miss named, and that is the
|
||||
* whole reason this file exists -- new ops still need no core change, because the core learns the
|
||||
* vocabulary from the plugins rather than carrying a copy of it.
|
||||
*/
|
||||
#include "registry.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstring>
|
||||
|
||||
namespace rad {
|
||||
|
||||
namespace {
|
||||
|
||||
/* Levenshtein, bounded by the two lengths. The strings are op and parameter names -- a dozen
|
||||
* characters against a few hundred candidates, once per failed declare -- so the textbook O(nm)
|
||||
* table is already far below anything worth optimising. */
|
||||
int edit_distance(std::string_view a, std::string_view b) {
|
||||
const size_t n = b.size();
|
||||
std::vector<int> prev(n + 1), cur(n + 1);
|
||||
for (size_t j = 0; j <= n; ++j) prev[j] = (int)j;
|
||||
for (size_t i = 1; i <= a.size(); ++i) {
|
||||
cur[0] = (int)i;
|
||||
for (size_t j = 1; j <= n; ++j) {
|
||||
const int sub = prev[j - 1] + (a[i - 1] == b[j - 1] ? 0 : 1);
|
||||
cur[j] = std::min({ sub, prev[j] + 1, cur[j - 1] + 1 });
|
||||
}
|
||||
prev.swap(cur);
|
||||
}
|
||||
return prev[n];
|
||||
}
|
||||
|
||||
/* How wrong a name may be and still be worth suggesting. One edit for a short name, up to three
|
||||
* for a long one: "gemm_nt" against "gemm_nq" is a typo worth naming, and "rmsnorm" against
|
||||
* "softmax" is not -- a suggestion that is wrong is worse than none, because it sends the reader
|
||||
* to check something that was never the problem. */
|
||||
bool close_enough(std::string_view a, std::string_view b, int d) {
|
||||
const size_t len = std::max(a.size(), b.size());
|
||||
const int budget = len <= 4 ? 1 : (len <= 10 ? 2 : 3);
|
||||
return d <= budget;
|
||||
}
|
||||
|
||||
std::string suggest(std::string_view want, const std::vector<std::string>& known) {
|
||||
std::string best;
|
||||
int best_d = INT32_MAX;
|
||||
for (const std::string& k : known) {
|
||||
const int d = edit_distance(want, k);
|
||||
if (d < best_d || (d == best_d && k < best)) { best_d = d; best = k; }
|
||||
}
|
||||
if (best.empty() || !close_enough(want, best, best_d)) return "";
|
||||
return best;
|
||||
}
|
||||
|
||||
const char* kind_name(int kind) {
|
||||
switch (kind) {
|
||||
case RAD_P_INT: return "an integer";
|
||||
case RAD_P_STR: return "a string";
|
||||
case RAD_P_RANGE: return "a range";
|
||||
case RAD_P_F64: return "a float";
|
||||
default: return "of an unknown kind";
|
||||
}
|
||||
}
|
||||
|
||||
} /* namespace */
|
||||
|
||||
const RadOpSchema* Registry::schema(std::string_view op) const {
|
||||
auto it = schemas_.find(std::string(op));
|
||||
return it == schemas_.end() ? nullptr : it->second.schema;
|
||||
}
|
||||
|
||||
const Plugin* Registry::schema_owner(std::string_view op) const {
|
||||
auto it = schemas_.find(std::string(op));
|
||||
return it == schemas_.end() ? nullptr : plugin(it->second.plugin);
|
||||
}
|
||||
|
||||
std::vector<std::string> Registry::op_names() const {
|
||||
std::vector<std::string> out;
|
||||
out.reserve(schemas_.size());
|
||||
for (const auto& kv : schemas_) out.push_back(kv.first);
|
||||
/* Rows may implement an op nobody declared a schema for -- check_complete() calls that out,
|
||||
* but until it is fixed the name should still show up in a near-miss search, or the author of
|
||||
* the broken plugin gets told their own op does not exist. */
|
||||
for (const KernelRow& r : rows_)
|
||||
if (schemas_.find(r.info->op) == schemas_.end()) out.emplace_back(r.info->op);
|
||||
std::sort(out.begin(), out.end());
|
||||
out.erase(std::unique(out.begin(), out.end()), out.end());
|
||||
return out;
|
||||
}
|
||||
|
||||
std::string Registry::near_miss(std::string_view op) const {
|
||||
return suggest(op, op_names());
|
||||
}
|
||||
|
||||
int Registry::validate(std::string_view op, const RadParam* p, int n_p, std::string* err) const {
|
||||
std::string sink;
|
||||
if (!err) err = &sink;
|
||||
err->clear();
|
||||
|
||||
const std::string name(op);
|
||||
auto it = schemas_.find(name);
|
||||
if (it == schemas_.end()) {
|
||||
const std::string did = near_miss(op);
|
||||
*err = fmt("no loaded kernel plugin declares op '%s'%s", name.c_str(),
|
||||
did.empty() ? "" : fmt("; did you mean '%s'?", did.c_str()).c_str());
|
||||
return RAD_E_NOSCHEMA;
|
||||
}
|
||||
const RadOpSchema& s = *it->second.schema;
|
||||
|
||||
std::vector<std::string> keys;
|
||||
keys.reserve((size_t)s.n_params);
|
||||
for (int i = 0; i < s.n_params; ++i) keys.emplace_back(s.params[i].key ? s.params[i].key : "");
|
||||
|
||||
int n_ranged = 0;
|
||||
std::string ranged_key;
|
||||
for (int i = 0; i < n_p; ++i) {
|
||||
if (!p[i].key || !p[i].key[0]) {
|
||||
*err = fmt("%s: parameter %d has no name", name.c_str(), i);
|
||||
return RAD_E_SCHEMA;
|
||||
}
|
||||
for (int j = 0; j < i; ++j) {
|
||||
if (p[j].key && std::strcmp(p[i].key, p[j].key) == 0) {
|
||||
*err = fmt("%s: parameter '%s' is given twice", name.c_str(), p[i].key);
|
||||
return RAD_E_SCHEMA;
|
||||
}
|
||||
}
|
||||
|
||||
const RadParamSpec* spec = nullptr;
|
||||
for (int j = 0; j < s.n_params; ++j)
|
||||
if (keys[(size_t)j] == p[i].key) { spec = &s.params[j]; break; }
|
||||
if (!spec) {
|
||||
const std::string did = suggest(p[i].key, keys);
|
||||
*err = fmt("%s: no parameter '%s' in this op's schema%s", name.c_str(), p[i].key,
|
||||
did.empty() ? "" : fmt("; did you mean '%s'?", did.c_str()).c_str());
|
||||
return RAD_E_SCHEMA;
|
||||
}
|
||||
|
||||
/* A range is an integer parameter that has not been collapsed yet, so it satisfies an
|
||||
* integer slot and nothing else. */
|
||||
const bool int_ok = (p[i].kind == RAD_P_INT || p[i].kind == RAD_P_RANGE);
|
||||
if (spec->type == RAD_P_INT && !int_ok) {
|
||||
*err = fmt("%s: parameter '%s' is %s, but the schema says it is an integer",
|
||||
name.c_str(), p[i].key, kind_name(p[i].kind));
|
||||
return RAD_E_SCHEMA;
|
||||
}
|
||||
if (spec->type == RAD_P_STR && p[i].kind != RAD_P_STR) {
|
||||
*err = fmt("%s: parameter '%s' is %s, but the schema says it is a string",
|
||||
name.c_str(), p[i].key, kind_name(p[i].kind));
|
||||
return RAD_E_SCHEMA;
|
||||
}
|
||||
if (spec->type == RAD_P_STR && !p[i].sval) {
|
||||
*err = fmt("%s: string parameter '%s' is null", name.c_str(), p[i].key);
|
||||
return RAD_E_SCHEMA;
|
||||
}
|
||||
/* A float slot takes a float and nothing else. An integer in it would land in `ival` while
|
||||
* the kernel reads `dval`, which is a zero eps rather than a diagnostic -- exactly the
|
||||
* silent-garbage class the schema exists to catch. Constraints never match on a float
|
||||
* (rad_types.h), so this check is the only thing standing between the two spellings. */
|
||||
if (spec->type == RAD_P_F64 && p[i].kind != RAD_P_F64) {
|
||||
*err = fmt("%s: parameter '%s' is %s, but the schema says it is a float -- declare it "
|
||||
"with RAD_F64()", name.c_str(), p[i].key, kind_name(p[i].kind));
|
||||
return RAD_E_SCHEMA;
|
||||
}
|
||||
|
||||
if (p[i].kind == RAD_P_RANGE) {
|
||||
if (p[i].ihi < p[i].ival) {
|
||||
*err = fmt("%s: parameter '%s' is the empty range [%lld, %lld]", name.c_str(),
|
||||
p[i].key, p[i].ival, p[i].ihi);
|
||||
return RAD_E_SCHEMA;
|
||||
}
|
||||
if (++n_ranged == 1) ranged_key = p[i].key;
|
||||
else {
|
||||
/* At most one ranged parameter per op. That is what keeps the bucket-table index a
|
||||
* single integer at issue, and it is a promise the run phase depends on rather
|
||||
* than a limitation of the table (docs/OPS.md). */
|
||||
*err = fmt("%s: '%s' and '%s' are both ranges; an op may have at most one ranged "
|
||||
"parameter", name.c_str(), ranged_key.c_str(), p[i].key);
|
||||
return RAD_E_SCHEMA;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (int j = 0; j < s.n_params; ++j) {
|
||||
/* RAD_REQUIRED and nothing else. RAD_DERIVED is supplied by the KERNEL, so demanding it
|
||||
* from the caller would re-create the circularity it exists to break: the caller cannot
|
||||
* know the block size until a kernel is resolved, and no kernel resolves until the block
|
||||
* size is known (rad_abi.h, spec §7.2). A caller MAY still supply one, which pins it. */
|
||||
if (s.params[j].required != RAD_REQUIRED) continue;
|
||||
bool given = false;
|
||||
for (int i = 0; i < n_p && !given; ++i) given = (keys[(size_t)j] == p[i].key);
|
||||
if (!given) {
|
||||
*err = fmt("%s: required parameter '%s' was not given (declared by plugin '%s')",
|
||||
name.c_str(), keys[(size_t)j].c_str(), it->second.plugin.c_str());
|
||||
return RAD_E_SCHEMA;
|
||||
}
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
} /* namespace rad */
|
||||
@@ -0,0 +1,436 @@
|
||||
/* select.cpp -- the constraint selector, the selection table, and the per-instance init/fini.
|
||||
* spec.md §2.1 and §16.
|
||||
*
|
||||
* The selector answers one question: is there a kernel compiled for this geometry, in this domain,
|
||||
* in the highest plugin that has one. It is a NECESSARY condition and not a sufficient one --
|
||||
* strides, contiguity, alignment and buffer sizes are properties of a call rather than of a model
|
||||
* and stay in the entry point, which still rejects what it cannot run. libr4d's registry makes the
|
||||
* same point at length.
|
||||
*/
|
||||
#include "registry.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstdlib>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
#include <cstring>
|
||||
|
||||
namespace rad {
|
||||
|
||||
namespace {
|
||||
|
||||
/* True when every constraint holds. Otherwise `why` names the FIRST one that did not and what it
|
||||
* wanted: "no kernel" on its own is not an answer anyone can act on, and the first failure is the
|
||||
* one a reader can fix -- listing all four of a row's unmet constraints buries it. */
|
||||
bool row_matches(const KernelRow& r, const Geometry& g, const std::vector<std::string>& skip,
|
||||
std::string* why) {
|
||||
for (int i = 0; i < r.info->n_constraints; ++i) {
|
||||
const RadConstraint& c = r.info->constraints[i];
|
||||
/* A constraint on a RAD_DERIVED parameter the caller did not name is not a predicate on
|
||||
* the question -- it IS the answer, read back afterwards. Matching on it would make the
|
||||
* kernel unreachable by the only query anyone can ask (rad_abi.h, spec §7.2). */
|
||||
if (c.key && std::find(skip.begin(), skip.end(), c.key) != skip.end()) continue;
|
||||
if (!constraint_holds(c, g)) {
|
||||
if (why) *why = constraint_why(c, g);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
if (why) *why = "ok";
|
||||
return true;
|
||||
}
|
||||
|
||||
/* The question, normalised so two spellings of the same one fold together in the table. The
|
||||
* geometry is displayed as asked, because a plugin author writes the parameters in the order that
|
||||
* reads best; only the fold key is sorted. */
|
||||
std::string fold_key(std::string_view op, int domain, const Geometry& g) {
|
||||
const std::string q = g.str(); /* named: split_ws returns views into it */
|
||||
std::vector<std::string> kv;
|
||||
for (auto tok : split_ws(q)) kv.emplace_back(tok);
|
||||
std::sort(kv.begin(), kv.end());
|
||||
std::string k = std::string(op) + "/" + domain_name(domain) + "/";
|
||||
for (const std::string& s : kv) { k += s; k += ';'; }
|
||||
return k;
|
||||
}
|
||||
|
||||
} /* namespace */
|
||||
|
||||
bool kernel_constraint(const KernelRow& r, std::string_view key, int c_op, long long* out) {
|
||||
if (!r.info) return false;
|
||||
for (int i = 0; i < r.info->n_constraints; ++i) {
|
||||
const RadConstraint& c = r.info->constraints[i];
|
||||
if (c.op != c_op || !c.key || key != c.key) continue;
|
||||
if (out) *out = c.ival;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ selection */
|
||||
const KernelRow* Registry::select(std::string_view op, const Geometry& g, int domain,
|
||||
SelectionTrace* why, bool record, const RowFilter* accept) {
|
||||
SelectionTrace local;
|
||||
SelectionTrace& t = why ? *why : local;
|
||||
t = SelectionTrace{};
|
||||
t.op = std::string(op);
|
||||
t.query = g.str();
|
||||
t.domain = domain;
|
||||
|
||||
/* The derived keys of this op that the caller did NOT supply. Derivedness is a property of the
|
||||
* op's schema, so it is known here and nowhere else; a caller that supplied one anyway has
|
||||
* pinned it, and it drops out of this list and matches like any other parameter. */
|
||||
std::vector<std::string> derived_keys;
|
||||
if (const RadOpSchema* sch = schema(op)) {
|
||||
for (int i = 0; i < sch->n_params; ++i) {
|
||||
if (sch->params[i].required != RAD_DERIVED || !sch->params[i].key) continue;
|
||||
if (!g.has(sch->params[i].key)) derived_keys.emplace_back(sch->params[i].key);
|
||||
}
|
||||
}
|
||||
|
||||
const std::vector<const KernelRow*>* rows = rows_for(op);
|
||||
const KernelRow* best = nullptr;
|
||||
std::vector<std::string> misses;
|
||||
|
||||
if (rows) {
|
||||
bool in_group = false;
|
||||
int cur_order = 0;
|
||||
for (const KernelRow* r : *rows) {
|
||||
/* A kernel in the other domain answers a different question. It is not a candidate and
|
||||
* not a refusal -- but the fact that it exists is worth carrying, because "there is a
|
||||
* device kernel and no host one" is the sentence the placement planner needs (§5.1). */
|
||||
if (r->info->domain != domain) { t.other_domain_has_rows = true; continue; }
|
||||
|
||||
if (!in_group || r->plugin_order != cur_order) {
|
||||
/* THE HIERARCHY IS ABSOLUTE. The first plugin with any matching kernel supplies
|
||||
* it; the moment we would step down to the next plugin with a winner in hand, we
|
||||
* stop. A lower-priority plugin never outbids a higher one no matter how
|
||||
* specialised its kernel -- that is what makes a user override an override. */
|
||||
if (best) break;
|
||||
cur_order = r->plugin_order;
|
||||
in_group = true;
|
||||
}
|
||||
|
||||
std::string whynot;
|
||||
bool ok = row_matches(*r, g, derived_keys, &whynot);
|
||||
if (ok && accept && *accept) {
|
||||
whynot = (*accept)(*r, g);
|
||||
ok = whynot.empty();
|
||||
}
|
||||
if (ok) {
|
||||
t.candidates.push_back({ r->plugin, r->info->name, r->info->priority, true, "ok" });
|
||||
/* SPECIFICITY IS DECLARED, NOT DERIVED: the highest priority wins, and a tie goes
|
||||
* to the row declared first. Counting matched constraints would get it backwards. */
|
||||
if (!best || r->info->priority > best->info->priority) best = r;
|
||||
} else {
|
||||
t.candidates.push_back({ r->plugin, r->info->name, r->info->priority, false, whynot });
|
||||
if (std::find(misses.begin(), misses.end(), whynot) == misses.end())
|
||||
misses.push_back(whynot);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (best) {
|
||||
t.kernel = best->info->name;
|
||||
t.plugin = best->plugin;
|
||||
t.priority = best->info->priority;
|
||||
/* The answer to the question that could not be asked: whatever the winner's RAD_C_EQ says
|
||||
* about each skipped derived key. A kernel with no EQ on one -- ref's `block_size >= 1`,
|
||||
* which admits every value -- leaves it UNKNOWN rather than zero, because "any" is not a
|
||||
* number and the caller has to decide rather than be handed a plausible one. */
|
||||
for (const std::string& key : derived_keys) {
|
||||
SelectionTrace::DerivedParam d;
|
||||
d.key = key;
|
||||
d.known = kernel_constraint(*best, key, RAD_C_EQ, &d.value);
|
||||
t.derived.push_back(std::move(d));
|
||||
}
|
||||
} else if (!rows) {
|
||||
const std::string did = near_miss(op);
|
||||
t.reason = fmt("no loaded kernel plugin implements op '%s'%s", t.op.c_str(),
|
||||
did.empty() ? "" : fmt("; did you mean '%s'?", did.c_str()).c_str());
|
||||
} else if (misses.empty()) {
|
||||
t.reason = fmt("no %s kernel for op '%s' in any plugin", domain_name(domain), t.op.c_str());
|
||||
} else {
|
||||
for (size_t i = 0; i < misses.size(); ++i) t.reason += (i ? "; " : "") + misses[i];
|
||||
}
|
||||
|
||||
if (record) record_(t.op, domain, g, t);
|
||||
return best;
|
||||
}
|
||||
|
||||
/* "gemm_nt:sk=8,mb=1;all_reduce:drain=3" -> the axes asked for `op`, or empty. Parsed on every
|
||||
* resolve rather than once: resolve runs a few thousand times at startup and never again, and a
|
||||
* parsed-once cache would need a mutex for a string that does not change. */
|
||||
static std::string tune_pin_for(const char* spec, std::string_view op) {
|
||||
for (const char* p = spec; *p;) {
|
||||
const char* semi = std::strchr(p, ';');
|
||||
const char* end = semi ? semi : p + std::strlen(p);
|
||||
if (const char* colon = (const char*)std::memchr(p, ':', (size_t)(end - p))) {
|
||||
if (op == std::string_view(p, (size_t)(colon - p)))
|
||||
return std::string(colon + 1, (size_t)(end - colon - 1));
|
||||
}
|
||||
p = semi ? semi + 1 : end;
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
/* For an error message, which is the whole value of refusing a bad pin rather than defaulting. */
|
||||
static std::string tunable_names(const RadKernelInfo* k) {
|
||||
std::string s;
|
||||
for (int i = 0; i < k->n_tunables; ++i) {
|
||||
if (i) s += ", ";
|
||||
s += k->tunables[i].key;
|
||||
s += '=';
|
||||
for (int j = 0; j < k->tunables[i].n_values; ++j) {
|
||||
if (j) s += '|';
|
||||
s += std::to_string((long long)k->tunables[i].values[j]);
|
||||
}
|
||||
}
|
||||
return s.empty() ? "(nothing tunable)" : s;
|
||||
}
|
||||
|
||||
/* Is `v` one of the values this axis declares? A cached or pinned value outside the list is not
|
||||
* applied: the axis list is the kernel's statement of what it can run, and honouring a number it
|
||||
* never offered is how a stale cache launches a shape the kernel cannot serve. */
|
||||
static bool axis_allows(const RadTunable& t, int64_t v) {
|
||||
for (int i = 0; i < t.n_values; ++i) if (t.values[i] == v) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
/* Does this combination survive the kernel's own cross-axis test? Null means yes. */
|
||||
static bool choice_valid(const RadKernelInfo* k, const Geometry& g,
|
||||
const std::vector<std::pair<std::string, int64_t>>& c) {
|
||||
if (!k->tune_valid) return true;
|
||||
std::vector<RadParam> cp;
|
||||
cp.reserve(c.size());
|
||||
for (const auto& e : c) {
|
||||
RadParam p{};
|
||||
p.key = e.first.c_str();
|
||||
p.kind = RAD_P_INT;
|
||||
p.ival = e.second;
|
||||
cp.push_back(p);
|
||||
}
|
||||
return k->tune_valid(g.params(), g.n_params(), cp.data(), (int)cp.size()) == 1;
|
||||
}
|
||||
|
||||
Resolved Registry::resolve(std::string_view op, const Geometry& g, int domain, SelectionTrace* why,
|
||||
const RowFilter* accept) {
|
||||
SelectionTrace local;
|
||||
SelectionTrace& t = why ? *why : local;
|
||||
|
||||
Resolved r;
|
||||
r.row = select(op, g, domain, &t, true, accept);
|
||||
if (!r.row) return r;
|
||||
|
||||
/* The frozen geometry is the query PLUS what the kernel supplied for it. Writing the derived
|
||||
* value here rather than leaving it to the caller is what makes rad_kv_block_size() and
|
||||
* RadArgs.p agree: the kernel is launched with the block size it was compiled for, and the
|
||||
* block manager sizes itself from the same number. */
|
||||
r.geom = g;
|
||||
for (const SelectionTrace::DerivedParam& d : t.derived)
|
||||
if (d.known) r.geom.set_i(d.key, d.value);
|
||||
/* THE TUNED AXES. A kernel declares a SPACE (RadTunable) and this is where a point in it is
|
||||
* chosen: the cache when this shape has been measured on this machine, each axis's own
|
||||
* `deflt` otherwise -- so an untuned install is fast rather than broken (spec §15). The core
|
||||
* owns the cache and the policy, so no plugin has to.
|
||||
*
|
||||
* THE KEY IS THE FROZEN GEOMETRY BEFORE THE CHOICES GO IN, which is why `geom_key` is captured
|
||||
* here and the choices are folded into `geom` afterwards. rad-tune keys its rows on the
|
||||
* geometry the builder recorded; a key that included its own answer could never match. It also
|
||||
* has to sit after the derived parameters are written in, or the two spellings of one shape
|
||||
* would never meet.
|
||||
*
|
||||
* An axis the cached row does not mention keeps its default, and a key the row carries that
|
||||
* this kernel no longer declares is ignored. That is exactly what tunecache.h promises: a
|
||||
* library may add or widen an axis between builds without throwing away the measurements that
|
||||
* still apply, and a cache is an optimisation that must never stop a server. */
|
||||
r.geom_key = TuneCache::canon_geometry(r.geom);
|
||||
|
||||
const RadKernelInfo* ki = r.row->info;
|
||||
if (ki->n_tunables > 0) {
|
||||
std::vector<std::pair<std::string, int64_t>> chosen;
|
||||
chosen.reserve((size_t)ki->n_tunables);
|
||||
for (int i = 0; i < ki->n_tunables; ++i)
|
||||
chosen.emplace_back(ki->tunables[i].key, ki->tunables[i].deflt);
|
||||
r.tune_source = "axis defaults";
|
||||
|
||||
if (!tune_.empty()) {
|
||||
if (const TuneRow* tr = tune_.find(ki->name, r.row->plugin, r.geom_key)) {
|
||||
bool took = false;
|
||||
for (const auto& kv : TuneCache::parse_choice(tr->choice))
|
||||
for (int i = 0; i < ki->n_tunables; ++i)
|
||||
if (kv.first == ki->tunables[i].key &&
|
||||
axis_allows(ki->tunables[i], kv.second)) {
|
||||
chosen[(size_t)i].second = kv.second;
|
||||
took = true;
|
||||
}
|
||||
if (took) r.tune_source = "tuned " + tr->measured;
|
||||
}
|
||||
}
|
||||
|
||||
/* RADIANCE_TUNE=op:key=value[,key=value][;op:...] pins axes for every kernel serving that
|
||||
* op. It is the debug half of the cache, and it exists because an axis is where a kernel's
|
||||
* fences and launch geometry live: the all-reduce's drain depth and acquire ordering are
|
||||
* axes, so questions like "is the missing acquire fence why this deployment is not
|
||||
* reproducible" are answerable without a rebuild.
|
||||
*
|
||||
* An unknown key, or a value the axis does not offer, is a HARD ERROR rather than a silent
|
||||
* default: a pin that did not take is worse than no pin, because the run looks like it
|
||||
* tested something. A kernel with nothing tunable is not a failed pin, though -- the same
|
||||
* op is served by libr4d on the device and by libref on the host, and libref declares no
|
||||
* axes for anything, so refusing here would take the host band out over a device pin. */
|
||||
if (const char* pin = std::getenv("RADIANCE_TUNE")) {
|
||||
const std::string want = tune_pin_for(pin, op);
|
||||
for (const auto& kv : TuneCache::parse_choice(want)) {
|
||||
int idx = -1;
|
||||
for (int i = 0; i < ki->n_tunables; ++i)
|
||||
if (kv.first == ki->tunables[i].key) { idx = i; break; }
|
||||
if (idx < 0 || !axis_allows(ki->tunables[idx], kv.second)) {
|
||||
RAD_ERR("RADIANCE_TUNE asks %s=%lld of op '%s', which kernel '%s' does not "
|
||||
"offer. It has: %s", kv.first.c_str(), (long long)kv.second,
|
||||
std::string(op).c_str(), ki->name, tunable_names(ki).c_str());
|
||||
r.row = nullptr;
|
||||
return r;
|
||||
}
|
||||
chosen[(size_t)idx].second = kv.second;
|
||||
r.tune_source = "RADIANCE_TUNE";
|
||||
}
|
||||
}
|
||||
|
||||
/* A combination the kernel's own cross-axis test refuses is not launched. Falling back to
|
||||
* every axis's default is the one answer that cannot be wrong here: the defaults are what
|
||||
* an untuned install runs, so they are the kernel's own statement of what it can always
|
||||
* do. A cache written for a different build, or a pin that is individually legal on each
|
||||
* axis but not together, lands here. */
|
||||
if (!choice_valid(ki, r.geom, chosen)) {
|
||||
std::vector<std::pair<std::string, int64_t>> dflt;
|
||||
for (int i = 0; i < ki->n_tunables; ++i)
|
||||
dflt.emplace_back(ki->tunables[i].key, ki->tunables[i].deflt);
|
||||
if (r.tune_source != "axis defaults")
|
||||
RAD_WARN("kernel '%s' refuses the %s axes for %s; falling back to its defaults",
|
||||
ki->name, r.tune_source.c_str(), r.geom_key.c_str());
|
||||
chosen = std::move(dflt);
|
||||
r.tune_source = "axis defaults";
|
||||
}
|
||||
|
||||
for (const auto& kv : chosen) r.geom.set_i(kv.first, kv.second);
|
||||
r.choice = TuneCache::canon_choice(chosen);
|
||||
}
|
||||
|
||||
/* scratch_bytes stays 0: the scratch hook takes a RadArgs, which needs the operand tensors,
|
||||
* and those belong to the builder. It sizes the arena; this layer only says which kernel. */
|
||||
return r;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ the selection table (§16) */
|
||||
void Registry::record_(const std::string& op, int domain, const Geometry& g,
|
||||
const SelectionTrace& t) {
|
||||
const std::string key = fold_key(op, domain, g);
|
||||
std::lock_guard<std::mutex> lk(mu_);
|
||||
for (SelectionRecord& s : log_) {
|
||||
if (s.key == key) { ++s.count; return; } /* same question, therefore the same answer */
|
||||
}
|
||||
SelectionRecord s;
|
||||
s.op = op;
|
||||
s.domain = domain;
|
||||
s.query = g.str();
|
||||
s.key = key;
|
||||
s.kernel = t.kernel;
|
||||
s.plugin = t.plugin;
|
||||
s.priority = t.priority;
|
||||
s.reason = t.reason;
|
||||
/* Kept apart from the query. A derived key was not part of the question -- printing it inside
|
||||
* the geometry would read as something the caller asked for, and the next reader would go
|
||||
* looking for the code that passed it. ":=" is the kernel answering, "?" is a winner with no
|
||||
* EQ on the key, which is a hole the caller has to fill and not a value. */
|
||||
for (const SelectionTrace::DerivedParam& d : t.derived) {
|
||||
if (!s.derived.empty()) s.derived += ' ';
|
||||
s.derived += d.known ? fmt("%s:=%lld", d.key.c_str(), d.value)
|
||||
: fmt("%s:=?", d.key.c_str());
|
||||
}
|
||||
log_.push_back(std::move(s));
|
||||
}
|
||||
|
||||
size_t Registry::n_selections() const {
|
||||
std::lock_guard<std::mutex> lk(mu_);
|
||||
return log_.size();
|
||||
}
|
||||
|
||||
void Registry::clear_selections() {
|
||||
std::lock_guard<std::mutex> lk(mu_);
|
||||
log_.clear();
|
||||
}
|
||||
|
||||
std::string Registry::selection_table() const {
|
||||
std::lock_guard<std::mutex> lk(mu_);
|
||||
if (log_.empty()) return "selection table: the selector was never asked anything\n";
|
||||
|
||||
size_t wop = 2, wdom = 3, wq = 8;
|
||||
long long total = 0;
|
||||
for (const SelectionRecord& s : log_) {
|
||||
wop = std::max(wop, s.op.size());
|
||||
wdom = std::max(wdom, std::strlen(domain_name(s.domain)));
|
||||
wq = std::max(wq, s.query.size());
|
||||
total += s.count;
|
||||
}
|
||||
|
||||
std::string out = fmt("selection table -- %zu distinct questions, %lld asked\n",
|
||||
log_.size(), total);
|
||||
out += fmt(" %-*s %-*s %5s %-*s %s\n", (int)wop, "op", (int)wdom, "domain", "asked",
|
||||
(int)wq, "geometry", "resolved");
|
||||
for (const SelectionRecord& s : log_) {
|
||||
std::string got = s.kernel.empty()
|
||||
? fmt("-- none: %s", s.reason.c_str())
|
||||
: fmt("%s (%s, prio %d)%s%s", s.kernel.c_str(), s.plugin.c_str(), s.priority,
|
||||
s.derived.empty() ? "" : " derived ", s.derived.c_str());
|
||||
out += fmt(" %-*s %-*s %5lld %-*s %s\n", (int)wop, s.op.c_str(),
|
||||
(int)wdom, domain_name(s.domain), s.count, (int)wq, s.query.c_str(),
|
||||
got.c_str());
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ instances */
|
||||
/* init() once per resolved instance -- one op, one band, one domain -- with the frozen geometry,
|
||||
* the rank and the world size. Some kernels have per-instance state that must be established once
|
||||
* and not per launch: libr4d's all-reduce needs its peer signal buffers and IPC handles set up
|
||||
* across ranks before the first call, and a kernel that JITs or loads a config table wants
|
||||
* somewhere to do it that is not the hot path. */
|
||||
int Registry::init_instance(Resolved& r, int rank, int world_size) {
|
||||
if (!r.row || !r.row->info) return RAD_E_INVAL;
|
||||
const RadKernelInfo* k = r.row->info;
|
||||
if (!k->init) { r.instance = nullptr; return RAD_OK; }
|
||||
|
||||
void* inst = nullptr;
|
||||
const int st = k->init(r.geom.params(), r.geom.n_params(), rank, world_size, &inst);
|
||||
if (st < 0) {
|
||||
/* A negative init aborts startup, and the caller names the kernel -- which it can, because
|
||||
* the message below already did. Continuing would mean launching a kernel whose one-time
|
||||
* setup failed, and that is a fault three frames later instead of here. */
|
||||
RAD_ERR("kernel '%s' (%s) failed to initialise for %s: %s", k->name, r.row->plugin.c_str(),
|
||||
r.geom.str().c_str(), rad_strerror(st));
|
||||
return st;
|
||||
}
|
||||
r.instance = inst;
|
||||
/* Registered even when the kernel returned null: fini pairs 1:1 with a successful init, and a
|
||||
* kernel with global setup and no handle still needs its fini call. */
|
||||
std::lock_guard<std::mutex> lk(mu_);
|
||||
instances_.emplace_back(k, inst);
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
void Registry::fini_instances() {
|
||||
std::vector<std::pair<const RadKernelInfo*, void*>> take;
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(mu_);
|
||||
take.swap(instances_);
|
||||
}
|
||||
for (auto it = take.rbegin(); it != take.rend(); ++it)
|
||||
if (it->first->fini) it->first->fini(it->second);
|
||||
}
|
||||
|
||||
size_t Registry::n_instances() const {
|
||||
std::lock_guard<std::mutex> lk(mu_);
|
||||
return instances_.size();
|
||||
}
|
||||
|
||||
} /* namespace rad */
|
||||
@@ -0,0 +1,51 @@
|
||||
# Test plugins from one source, so that plugin_test has a hierarchy to load, a schema conflict to
|
||||
# refuse and a stale ABI to reject. They go under $RADIANCE_HOME/testkernels rather than kernels/,
|
||||
# because the engine scans kernels/ at startup and these rows implement nothing: a test plugin that
|
||||
# a real run could select is a fallback nobody knows about (spec.md §17).
|
||||
#
|
||||
# The two that must be refused live one directory down, so that loading testkernels/ is a clean
|
||||
# load and the refusals are asked for explicitly by path.
|
||||
rad_add_plugin(radtest_base testkernels SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/testplugin.cc)
|
||||
target_compile_definitions(radtest_base PRIVATE RADTEST_BASE=1)
|
||||
|
||||
rad_add_plugin(radtest_over testkernels SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/testplugin.cc)
|
||||
target_compile_definitions(radtest_over PRIVATE RADTEST_OVER=1)
|
||||
|
||||
rad_add_plugin(radtest_conflict testkernels/bad SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/testplugin.cc)
|
||||
target_compile_definitions(radtest_conflict PRIVATE RADTEST_CONFLICT=1)
|
||||
|
||||
rad_add_plugin(radtest_badabi testkernels/bad SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/testplugin.cc)
|
||||
target_compile_definitions(radtest_badabi PRIVATE RADTEST_BADABI=1)
|
||||
|
||||
# Two architecture plugins claiming one architecture id, in their own directory so that loading it
|
||||
# is the whole test: the first is identified, the second is refused.
|
||||
rad_add_plugin(radtest_arch testarch SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/testplugin.cc)
|
||||
target_compile_definitions(radtest_arch PRIVATE RADTEST_ARCH=1)
|
||||
|
||||
rad_add_plugin(radtest_arch2 testarch SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/testplugin.cc)
|
||||
target_compile_definitions(radtest_arch2 PRIVATE RADTEST_ARCH2=1)
|
||||
|
||||
# Two more from the same source, in a directory of their own, so that a load with NO hierarchy has
|
||||
# something to be observed on. One of them declares itself a reference implementation.
|
||||
#
|
||||
# THE FILE NAMES ARE THE POINT. load_dir reads a directory in sorted order, so `..._a` (the
|
||||
# reference) is staged first; if the loader did not pin a reference library below every other
|
||||
# kernel plugin, it would keep that position and answer for every op, and the library that actually
|
||||
# serves the card would never be selected. Naming them the other way round would make the test pass
|
||||
# on alphabetical order alone. Its name is nobody's in particular: the rule is the declaration's.
|
||||
rad_add_plugin(radtest_ord_a testkernels/order SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/testplugin.cc)
|
||||
target_compile_definitions(radtest_ord_a PRIVATE RADTEST_BASE=1 RADTEST_REFERENCE=1
|
||||
RADTEST_BASE_NAME=\"radtest_reference\")
|
||||
|
||||
rad_add_plugin(radtest_ord_b testkernels/order SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/testplugin.cc)
|
||||
target_compile_definitions(radtest_ord_b PRIVATE RADTEST_BASE=1)
|
||||
|
||||
# The KV tiers' transfer test. Unlike everything above it COMPUTES -- byte-row gather and scatter
|
||||
# registered in the device domain, running on the host backend's memory -- so it lives in a
|
||||
# directory of its own that only tests/mem_test.cpp loads, by path. It calls back into the device
|
||||
# API for stream order, which the test executable exports.
|
||||
rad_add_plugin(radtest_rows testrows SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/tierrows.cc)
|
||||
|
||||
# A quantiser with a scheme of its own, which only its decode hook reads: tests/quant_test.cpp
|
||||
# loads it by path to show a weight it wrote decodes through the core's decoder all the same.
|
||||
rad_add_plugin(radtest_quant testquant SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/testquant.cc)
|
||||
@@ -0,0 +1,429 @@
|
||||
/* testplugin.cc -- in-tree kernel plugins that exist to be loaded by tests/plugin_test.cpp.
|
||||
*
|
||||
* It computes nothing: every launch returns RAD_E_UNSUPPORTED, because a test kernel that returned
|
||||
* RAD_OK would be a slow path nobody knows about, waiting to be selected by a real model. What it
|
||||
* does have is a registry: rows that exercise every constraint operator, two plugins' worth of
|
||||
* hierarchy, a priority tie, a schema conflict that must be refused, and an op with kernels at
|
||||
* M<=16, M<=64 and unconstrained -- which is spec.md §2.2's worked example, so the test can assert
|
||||
* the exact band table and the paragraph becomes a regression test.
|
||||
*
|
||||
* One source, six .so files, selected by -D: two kernel plugins that load, two that must be
|
||||
* refused, and two architecture plugins that claim one id between them. The rows are worth reading
|
||||
* side by side, and six near-copies of this file would drift.
|
||||
*
|
||||
* The extension is .cc, not .cpp, and that is load-bearing: core/CMakeLists.txt globs
|
||||
* every core/plugin .cpp file into the rad_core static library, and a plugin's exports
|
||||
* (rad_kernel_count and friends) do not belong inside the engine. The alternative is an
|
||||
* exclusion rule in a file this component does not own.
|
||||
*/
|
||||
#include "rad_abi.h"
|
||||
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
|
||||
#if defined(RADTEST_ARCH) || defined(RADTEST_ARCH2)
|
||||
#define RADTEST_IS_ARCH 1
|
||||
#include "rad_builder.h"
|
||||
#include "rad_runtime.h"
|
||||
#endif
|
||||
|
||||
#if !defined(RADTEST_BASE) && !defined(RADTEST_OVER) && !defined(RADTEST_CONFLICT) && \
|
||||
!defined(RADTEST_BADABI) && !defined(RADTEST_IS_ARCH)
|
||||
#define RADTEST_BASE 1
|
||||
#endif
|
||||
|
||||
#define NELEM(a) (int)(sizeof(a) / sizeof((a)[0]))
|
||||
|
||||
/* ------------------------------------------------------------------ hooks */
|
||||
namespace {
|
||||
|
||||
int g_open_calls = 0;
|
||||
int g_init_calls = 0;
|
||||
int g_fini_calls = 0;
|
||||
|
||||
struct TestInstance {
|
||||
long long m; /* the frozen geometry's ranged value, so a test can prove which band's
|
||||
* upper bound reached init */
|
||||
int rank, world;
|
||||
};
|
||||
|
||||
/* Every row shares one launch, and it refuses. Nothing here can run. */
|
||||
[[maybe_unused]] int t_launch(const RadArgs* a, RadStream s) {
|
||||
(void)a; (void)s;
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
|
||||
[[maybe_unused]] int t_init(const RadParam* p, int n_p, int rank, int world_size, void** out) {
|
||||
TestInstance* inst = (TestInstance*)std::calloc(1, sizeof(TestInstance));
|
||||
if (!inst) return RAD_E_NOMEM;
|
||||
inst->m = -1;
|
||||
inst->rank = rank;
|
||||
inst->world = world_size;
|
||||
for (int i = 0; i < n_p; ++i)
|
||||
if (p[i].kind == RAD_P_INT && p[i].key && std::strcmp(p[i].key, "M") == 0)
|
||||
inst->m = p[i].ival;
|
||||
*out = inst;
|
||||
++g_init_calls;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
[[maybe_unused]] void t_fini(void* inst) {
|
||||
++g_fini_calls;
|
||||
std::free(inst);
|
||||
}
|
||||
|
||||
/* A kernel whose one-time setup fails. A negative init aborts startup naming the kernel, and that
|
||||
* path needs a kernel that takes it. */
|
||||
[[maybe_unused]] int t_init_fails(const RadParam* p, int n_p, int rank, int world_size, void** out) {
|
||||
(void)p; (void)n_p; (void)rank; (void)world_size; (void)out;
|
||||
return RAD_E_NOMEM;
|
||||
}
|
||||
|
||||
} /* namespace */
|
||||
|
||||
extern "C" {
|
||||
|
||||
int radtest_open_calls(void) { return g_open_calls; }
|
||||
int radtest_init_calls(void) { return g_init_calls; }
|
||||
int radtest_fini_calls(void) { return g_fini_calls; }
|
||||
long long radtest_instance_m(void* inst) { return inst ? ((TestInstance*)inst)->m : -1; }
|
||||
|
||||
int rad_plugin_open(void) { ++g_open_calls; return RAD_OK; }
|
||||
|
||||
/* ------------------------------------------------------------------ operands */
|
||||
/* Roles matter to the core (a weight operand is resolved through a handle, an output feeds the
|
||||
* buffer planner); names are diagnostics only, which is why two plugins may spell them
|
||||
* differently and still agree on the schema. */
|
||||
static const RadOperandSpec kOpdGemm[] = {
|
||||
{ "a", RAD_OPD_IN, 0 }, { "b", RAD_OPD_WEIGHT, 0 }, { "y", RAD_OPD_OUT, 0 },
|
||||
};
|
||||
static const RadOperandSpec kOpdNorm[] = {
|
||||
{ "x", RAD_OPD_IN, 0 }, { "w", RAD_OPD_WEIGHT, 0 }, { "y", RAD_OPD_OUT, 0 },
|
||||
};
|
||||
static const RadOperandSpec kOpdAttn[] = {
|
||||
{ "q", RAD_OPD_IN, 0 }, { "kv_cache", RAD_OPD_INOUT, 0 }, { "out", RAD_OPD_OUT, 0 },
|
||||
};
|
||||
|
||||
/* ------------------------------------------------------------------ schemas */
|
||||
static const RadParamSpec kPGemm[] = {
|
||||
{ "M", RAD_P_INT, RAD_REQUIRED },
|
||||
{ "N", RAD_P_INT, RAD_REQUIRED },
|
||||
{ "K", RAD_P_INT, RAD_REQUIRED },
|
||||
{ "dtype", RAD_P_STR, RAD_REQUIRED },
|
||||
};
|
||||
static const RadParamSpec kPNorm[] = {
|
||||
{ "M", RAD_P_INT, RAD_REQUIRED },
|
||||
{ "n", RAD_P_INT, RAD_REQUIRED },
|
||||
/* A float slot. Constraints never match on one; it is here so the schema check has something
|
||||
* to refuse an integer spelling of. */
|
||||
{ "eps", RAD_P_F64, RAD_OPTIONAL },
|
||||
{ "dtype", RAD_P_STR, RAD_REQUIRED },
|
||||
};
|
||||
static const RadParamSpec kPTie[] = {
|
||||
{ "M", RAD_P_INT, RAD_REQUIRED },
|
||||
{ "n", RAD_P_INT, RAD_REQUIRED },
|
||||
};
|
||||
static const RadParamSpec kPAttn[] = {
|
||||
{ "q_len", RAD_P_INT, RAD_REQUIRED },
|
||||
{ "head_dim", RAD_P_INT, RAD_REQUIRED },
|
||||
{ "window", RAD_P_INT, RAD_REQUIRED },
|
||||
/* Supplied by the KERNEL, which is what makes t_attn_paged reachable at all: its
|
||||
* block_size == 16 would otherwise refuse every query that did not already know the answer
|
||||
* (rad_abi.h RAD_DERIVED, spec §7.2). */
|
||||
{ "block_size", RAD_P_INT, RAD_DERIVED },
|
||||
{ "causal", RAD_P_INT, RAD_REQUIRED },
|
||||
{ "n_head", RAD_P_INT, RAD_REQUIRED },
|
||||
{ "kv_dtype", RAD_P_STR, RAD_REQUIRED },
|
||||
};
|
||||
|
||||
/* The conflicting spelling: same op name, no dtype. Since arguments are positional, a call built
|
||||
* against this schema and served by a kernel selected against the other one is not a diagnosable
|
||||
* failure -- it is silent numerical garbage, which is why the load refuses it (§2.3). */
|
||||
static const RadParamSpec kPGemmWrong[] = {
|
||||
{ "M", RAD_P_INT, RAD_REQUIRED },
|
||||
{ "N", RAD_P_INT, RAD_REQUIRED },
|
||||
{ "K", RAD_P_INT, RAD_REQUIRED },
|
||||
};
|
||||
|
||||
/* ------------------------------------------------------------------ constraints */
|
||||
/* Between them these rows use every operator the ABI has: EQ, LE, GE, DIV and IN. */
|
||||
static const RadConstraint kCGemmM16[] = {
|
||||
RAD_CLE("M", 16), RAD_CDIV("K", 256), RAD_CIN("dtype", "bf16 w4a8"),
|
||||
};
|
||||
static const RadConstraint kCGemmM64[] = {
|
||||
RAD_CLE("M", 64), RAD_CDIV("K", 16), RAD_CIN("dtype", "bf16 w4a8"),
|
||||
};
|
||||
static const RadConstraint kCNorm4096[] = {
|
||||
RAD_CEQ("n", 4096),
|
||||
};
|
||||
static const RadConstraint kCTie[] = {
|
||||
RAD_CGE("M", 1),
|
||||
};
|
||||
/* Constraint ORDER is the order the miss message reports in: the first unmet one is what a reader
|
||||
* is told, so the cheapest and most identifying predicate goes first. */
|
||||
static const RadConstraint kCAttn[] = {
|
||||
RAD_CEQ("head_dim", 128), RAD_CGE("window", 0), RAD_CEQ("block_size", 16),
|
||||
RAD_CIN("causal", "0 1"), RAD_CLE("q_len", 16), RAD_CDIV("n_head", 4),
|
||||
RAD_CIN("kv_dtype", "bf16 fp8_e4m3"),
|
||||
};
|
||||
/* The other half of the derived story: a row that admits every block size and names none. ref's
|
||||
* rows are exactly this -- every extent is read off the operands at launch -- so the winner has no
|
||||
* RAD_C_EQ to read back and the derived key stays UNSET. "any" is not a number. */
|
||||
static const RadConstraint kCAttnAny[] = {
|
||||
RAD_CEQ("head_dim", 128), RAD_CGE("block_size", 1), RAD_CIN("kv_dtype", "bf16 fp8_e4m3"),
|
||||
};
|
||||
static const RadConstraint kCSkinnyM64[] = { RAD_CLE("M", 64) };
|
||||
static const RadConstraint kCSkinnyBig[] = { RAD_CGE("M", 4096) };
|
||||
static const RadConstraint kCEqM32[] = { RAD_CEQ("M", 32) };
|
||||
|
||||
/* A TUNABLE AXIS, declared the way an out-of-tree library declares one: the legal values and a
|
||||
* default, not a list of pre-named combinations. `deflt` is what runs when this machine has no
|
||||
* measurement for an instantiation, and the loader refuses the plugin if it is not one of the
|
||||
* values (§15). */
|
||||
static const int64_t kBnValues[] = { 64, 128 };
|
||||
static const RadTunable kTGemmM64[] = {
|
||||
{ "bn", kBnValues, NELEM(kBnValues), 64, "columns of C one block covers" },
|
||||
};
|
||||
|
||||
/* ================================================================== radtest_base */
|
||||
#if defined(RADTEST_BASE)
|
||||
|
||||
static const RadOpSchema kSchemas[] = {
|
||||
{ "t_gemm", kPGemm, NELEM(kPGemm), kOpdGemm, NELEM(kOpdGemm), "the §2.2 worked example" },
|
||||
{ "t_norm", kPNorm, NELEM(kPNorm), kOpdNorm, NELEM(kOpdNorm), "hierarchy vs priority" },
|
||||
{ "t_tie", kPTie, NELEM(kPTie), kOpdNorm, NELEM(kOpdNorm), "a declaration-order tie" },
|
||||
{ "t_attn", kPAttn, NELEM(kPAttn), kOpdAttn, NELEM(kOpdAttn), "every constraint operator" },
|
||||
{ "t_attn_ref", kPAttn, NELEM(kPAttn), kOpdAttn, NELEM(kOpdAttn),
|
||||
"a derived key its kernel does not pin" },
|
||||
{ "t_skinny", kPGemm, NELEM(kPGemm), kOpdGemm, NELEM(kOpdGemm), "a range with a hole in it" },
|
||||
{ "t_eq", kPTie, NELEM(kPTie), kOpdNorm, NELEM(kOpdNorm), "an EQ band boundary" },
|
||||
};
|
||||
|
||||
static const RadKernelInfo kKernels[] = {
|
||||
{ .name = "t_gemm_m16", .op = "t_gemm", .family = "gemm",
|
||||
.computes = "nothing; a registry row", .shape = "M <= 16, K divisible by 256",
|
||||
.dtypes = "bf16 / w4a8", .domain = RAD_DOMAIN_DEVICE, .priority = 30,
|
||||
.constraints = kCGemmM16, .n_constraints = NELEM(kCGemmM16),
|
||||
.init = t_init, .fini = t_fini, .launch = t_launch },
|
||||
|
||||
{ .name = "t_gemm_m64", .op = "t_gemm", .family = "gemm",
|
||||
.computes = "nothing; a registry row", .shape = "M <= 64, K divisible by 16",
|
||||
.dtypes = "bf16 / w4a8", .domain = RAD_DOMAIN_DEVICE, .priority = 20,
|
||||
.constraints = kCGemmM64, .n_constraints = NELEM(kCGemmM64),
|
||||
.tunables = kTGemmM64, .n_tunables = NELEM(kTGemmM64),
|
||||
.init = t_init, .fini = t_fini, .launch = t_launch },
|
||||
|
||||
/* Unconstrained, and lowest priority: the prefill row that serves whatever the two skinny rows
|
||||
* above it will not. It is what closes the last band of the bucket table. */
|
||||
{ .name = "t_gemm_any", .op = "t_gemm", .family = "gemm",
|
||||
.computes = "nothing; a registry row", .shape = "any", .dtypes = "any",
|
||||
.domain = RAD_DOMAIN_DEVICE, .priority = 10,
|
||||
.init = t_init, .fini = t_fini, .launch = t_launch },
|
||||
|
||||
/* A CPU kernel is an ordinary kernel with domain = host, resolved through the same hierarchy
|
||||
* and the same constraints (§2.1). */
|
||||
{ .name = "t_gemm_host", .op = "t_gemm", .family = "gemm",
|
||||
.computes = "nothing; a registry row", .shape = "any", .dtypes = "any",
|
||||
.domain = RAD_DOMAIN_HOST, .priority = 10, .launch = t_launch },
|
||||
|
||||
/* Very specialised and very high priority -- and still beaten by a plugin above it, which is
|
||||
* the point of the t_norm rows. */
|
||||
{ .name = "t_norm_specialised", .op = "t_norm", .family = "norm",
|
||||
.computes = "nothing; a registry row", .shape = "n == 4096", .dtypes = "bf16",
|
||||
.domain = RAD_DOMAIN_DEVICE, .priority = 100,
|
||||
.constraints = kCNorm4096, .n_constraints = NELEM(kCNorm4096), .launch = t_launch },
|
||||
{ .name = "t_norm_host", .op = "t_norm", .family = "norm",
|
||||
.computes = "nothing; a registry row", .shape = "any", .dtypes = "any",
|
||||
.domain = RAD_DOMAIN_HOST, .priority = 10, .launch = t_launch },
|
||||
|
||||
/* Same op, same priority, same constraints. Ties break on declaration order, so t_tie_first
|
||||
* wins -- and if it ever does not, the tie rule has silently changed. */
|
||||
{ .name = "t_tie_first", .op = "t_tie", .family = "norm",
|
||||
.computes = "nothing; a registry row", .shape = "M >= 1", .dtypes = "any",
|
||||
.domain = RAD_DOMAIN_DEVICE, .priority = 10,
|
||||
.constraints = kCTie, .n_constraints = NELEM(kCTie), .launch = t_launch },
|
||||
{ .name = "t_tie_second", .op = "t_tie", .family = "norm",
|
||||
.computes = "nothing; a registry row", .shape = "M >= 1", .dtypes = "any",
|
||||
.domain = RAD_DOMAIN_DEVICE, .priority = 10,
|
||||
.constraints = kCTie, .n_constraints = NELEM(kCTie), .launch = t_launch },
|
||||
|
||||
/* Device only: nothing serves t_attn on the host, which is the asymmetric-absence case. */
|
||||
{ .name = "t_attn_paged", .op = "t_attn", .family = "attn",
|
||||
.computes = "nothing; a registry row",
|
||||
.shape = "head_dim 128, block 16, q_len <= 16, n_head divisible by 4",
|
||||
.dtypes = "bf16 / fp8_e4m3 kv", .domain = RAD_DOMAIN_DEVICE, .priority = 10,
|
||||
.constraints = kCAttn, .n_constraints = NELEM(kCAttn), .launch = t_launch },
|
||||
|
||||
{ .name = "t_attn_ref_any", .op = "t_attn_ref", .family = "attn",
|
||||
.computes = "nothing; a registry row", .shape = "head_dim 128, any block size",
|
||||
.dtypes = "bf16 / fp8_e4m3 kv", .domain = RAD_DOMAIN_DEVICE, .priority = 10,
|
||||
.constraints = kCAttnAny, .n_constraints = NELEM(kCAttnAny), .launch = t_launch },
|
||||
|
||||
/* M <= 64 and M >= 4096, with nothing in between: a range with a hole in it, reported as that
|
||||
* band rather than as the whole op (§2.2). */
|
||||
{ .name = "t_skinny_m64", .op = "t_skinny", .family = "gemm",
|
||||
.computes = "nothing; a registry row", .shape = "M <= 64", .dtypes = "any",
|
||||
.domain = RAD_DOMAIN_DEVICE, .priority = 10,
|
||||
.constraints = kCSkinnyM64, .n_constraints = NELEM(kCSkinnyM64), .launch = t_launch },
|
||||
{ .name = "t_skinny_big", .op = "t_skinny", .family = "gemm",
|
||||
.computes = "nothing; a registry row", .shape = "M >= 4096", .dtypes = "any",
|
||||
.domain = RAD_DOMAIN_DEVICE, .priority = 5,
|
||||
.constraints = kCSkinnyBig, .n_constraints = NELEM(kCSkinnyBig), .launch = t_launch },
|
||||
|
||||
{ .name = "t_eq_m32", .op = "t_eq", .family = "norm",
|
||||
.computes = "nothing; a registry row", .shape = "M == 32", .dtypes = "any",
|
||||
.domain = RAD_DOMAIN_DEVICE, .priority = 10,
|
||||
.constraints = kCEqM32, .n_constraints = NELEM(kCEqM32),
|
||||
.init = t_init_fails, .launch = t_launch },
|
||||
};
|
||||
|
||||
/* The name is a -D so that two of these can load side by side, and one of them can declare itself
|
||||
* a reference implementation -- the only way to observe the loader's rule that a reference library
|
||||
* sorts below every other kernel plugin. */
|
||||
#ifndef RADTEST_BASE_NAME
|
||||
#define RADTEST_BASE_NAME "radtest_base"
|
||||
#endif
|
||||
static const RadPluginInfo kInfo = {
|
||||
RAD_PLUGIN_KERNEL, RADTEST_BASE_NAME, "0.1",
|
||||
"test rows: the §2.2 band table, a priority tie, every constraint operator", "host",
|
||||
};
|
||||
#ifdef RADTEST_REFERENCE
|
||||
extern "C" int rad_plugin_reference(void) { return 1; }
|
||||
#endif
|
||||
|
||||
/* ================================================================== radtest_over */
|
||||
#elif defined(RADTEST_OVER)
|
||||
|
||||
/* The same schemas, declared again with the same shape. That is expected and not an error: every
|
||||
* plugin declares the ops it implements, and an override that did not would be relying on a plugin
|
||||
* below it that a user may well have removed. */
|
||||
static const RadOpSchema kSchemas[] = {
|
||||
{ "t_gemm", kPGemm, NELEM(kPGemm), kOpdGemm, NELEM(kOpdGemm), "re-declared, same shape" },
|
||||
{ "t_norm", kPNorm, NELEM(kPNorm), kOpdNorm, NELEM(kOpdNorm), "re-declared, same shape" },
|
||||
};
|
||||
|
||||
static const RadKernelInfo kKernels[] = {
|
||||
/* Unconstrained and priority 1 -- as unspecialised as a row can be. Placed above
|
||||
* radtest_base in the hierarchy it still wins t_norm outright, because the hierarchy is
|
||||
* absolute and priority only orders rows WITHIN one plugin. */
|
||||
{ .name = "t_over_norm", .op = "t_norm", .family = "norm",
|
||||
.computes = "nothing; a registry row", .shape = "any", .dtypes = "any",
|
||||
.domain = RAD_DOMAIN_DEVICE, .priority = 1, .launch = t_launch },
|
||||
};
|
||||
|
||||
static const RadPluginInfo kInfo = {
|
||||
RAD_PLUGIN_KERNEL, "radtest_over", "0.1",
|
||||
"one generic row that must still beat a specialised one below it", "host",
|
||||
};
|
||||
|
||||
/* ================================================================== radtest_conflict */
|
||||
#elif defined(RADTEST_CONFLICT)
|
||||
|
||||
static const RadOpSchema kSchemas[] = {
|
||||
{ "t_gemm", kPGemmWrong, NELEM(kPGemmWrong), kOpdGemm, NELEM(kOpdGemm),
|
||||
"the same op name with a different parameter list" },
|
||||
};
|
||||
|
||||
static const RadKernelInfo kKernels[] = {
|
||||
{ .name = "t_conflict_gemm", .op = "t_gemm", .family = "gemm",
|
||||
.computes = "nothing; a registry row", .shape = "any", .dtypes = "any",
|
||||
.domain = RAD_DOMAIN_DEVICE, .priority = 1000, .launch = t_launch },
|
||||
};
|
||||
|
||||
static const RadPluginInfo kInfo = {
|
||||
RAD_PLUGIN_KERNEL, "radtest_conflict", "0.1",
|
||||
"declares t_gemm with a different schema; must be refused at load", "host",
|
||||
};
|
||||
|
||||
/* ================================================================== radtest_arch, radtest_arch2 */
|
||||
/* Two architecture plugins claiming ONE architecture id. An architecture id is what selects the
|
||||
* plugin a model is built from, so two claimants is a coin toss over which graph gets built --
|
||||
* refused at load, and the second one loses (§2.4). They export no kernel symbols at all, which is
|
||||
* how the loader learns that an arch plugin is not a kernel plugin with missing exports. */
|
||||
#elif defined(RADTEST_IS_ARCH)
|
||||
|
||||
static const RadPluginInfo kInfo = {
|
||||
RAD_PLUGIN_ARCH,
|
||||
#if defined(RADTEST_ARCH)
|
||||
"radtest_arch",
|
||||
#else
|
||||
"radtest_arch2",
|
||||
#endif
|
||||
"0.1", "claims architecture id 'radtest.v1'", "host",
|
||||
};
|
||||
|
||||
/* ================================================================== radtest_badabi */
|
||||
#else
|
||||
|
||||
static const RadOpSchema kSchemas[] = {
|
||||
{ "t_gemm", kPGemm, NELEM(kPGemm), kOpdGemm, NELEM(kOpdGemm), "never registered" },
|
||||
};
|
||||
|
||||
static const RadKernelInfo kKernels[] = {
|
||||
{ .name = "t_badabi_gemm", .op = "t_gemm", .family = "gemm",
|
||||
.computes = "nothing; a registry row", .shape = "any", .dtypes = "any",
|
||||
.domain = RAD_DOMAIN_DEVICE, .priority = 1000, .launch = t_launch },
|
||||
};
|
||||
|
||||
static const RadPluginInfo kInfo = {
|
||||
RAD_PLUGIN_KERNEL, "radtest_badabi", "0.1",
|
||||
"reports an ABI version this engine does not speak; must be refused at load", "host",
|
||||
};
|
||||
|
||||
#endif
|
||||
|
||||
/* ------------------------------------------------------------------ the exports */
|
||||
#if defined(RADTEST_BADABI)
|
||||
/* Deliberately wrong. A plugin that does not report exactly RAD_ABI_VERSION is refused at load, by
|
||||
* name, with both versions printed. */
|
||||
uint32_t rad_plugin_abi_version(void) { return RAD_ABI_VERSION + 7u; }
|
||||
#else
|
||||
uint32_t rad_plugin_abi_version(void) { return RAD_ABI_VERSION; }
|
||||
#endif
|
||||
|
||||
const RadPluginInfo* rad_plugin_info(void) { return &kInfo; }
|
||||
|
||||
#if defined(RADTEST_IS_ARCH)
|
||||
const char* rad_arch_id(void) { return "radtest.v1"; }
|
||||
/* The other half of the selection key (spec §2.4). This plugin serves an unquantised container,
|
||||
* which is what "" means. */
|
||||
const char* rad_arch_quant(void) { return ""; }
|
||||
/* The core loads and identifies architecture plugins; the build component drives them. Neither
|
||||
* hook is called by anything this test exercises, and declare refuses rather than pretending. */
|
||||
int rad_arch_declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) {
|
||||
(void)b; (void)meta; (void)ctx;
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
void rad_arch_step(RadCtx* c, const RadBatch* batch) { (void)c; (void)batch; }
|
||||
|
||||
#if defined(RADTEST_ARCH)
|
||||
/* The optional reply-format export, declared the way an out-of-tree plugin would declare its
|
||||
* model's syntax: static storage, struct_size as compiled. radtest_arch2 leaves it out. */
|
||||
static const char* const kTestBreaks[] = { "<call>" };
|
||||
static const char* const kTestTriggers[] = { "<call>" };
|
||||
static const RadChatFormat kTestFormat = {
|
||||
sizeof(RadChatFormat), "radtest-format",
|
||||
"<reason>", "</reason>", kTestBreaks, 1, RAD_CHAT_THINK_FROM_PROMPT,
|
||||
"", "", "",
|
||||
"<call>", "</call>", "<fn ", ">", "</fn>",
|
||||
"<arg ", "", "=", "</arg>",
|
||||
RAD_CHAT_VALUE_CDATA, RAD_CHAT_VALUE_JSON, 0,
|
||||
kTestTriggers, 1,
|
||||
};
|
||||
const RadChatFormat* rad_arch_chat_format(const RadModelMeta* meta) {
|
||||
(void)meta;
|
||||
return &kTestFormat;
|
||||
}
|
||||
#endif
|
||||
#else
|
||||
int rad_kernel_schema_count(void) { return NELEM(kSchemas); }
|
||||
const RadOpSchema* rad_kernel_schema_at(int i) {
|
||||
return (i < 0 || i >= NELEM(kSchemas)) ? nullptr : &kSchemas[i];
|
||||
}
|
||||
int rad_kernel_count(void) { return NELEM(kKernels); }
|
||||
const RadKernelInfo* rad_kernel_at(int i) {
|
||||
return (i < 0 || i >= NELEM(kKernels)) ? nullptr : &kKernels[i];
|
||||
}
|
||||
#endif
|
||||
|
||||
} /* extern "C" */
|
||||
@@ -0,0 +1,60 @@
|
||||
/* testquant.cc -- a quantiser plugin with a scheme of its own, for tests/quant_test.cpp.
|
||||
*
|
||||
* "radtest-halves" stores each value as the nearest multiple of one half, as an i8 code that is
|
||||
* twice the value, and nothing else: one plane, no scale, a scheme the core does not define. What
|
||||
* it exists to show is that a weight written that way is READ through the quantiser that wrote it
|
||||
* -- enc_decode_rows asks the loaded quantisers' decode hooks for any scheme but plain and affine
|
||||
* (abi/rad_quant.h) -- and that a decoder answers RAD_E_UNSUPPORTED for a scheme it did not write.
|
||||
*/
|
||||
#include "rad_quant.h"
|
||||
|
||||
#include <cmath>
|
||||
#include <cstring>
|
||||
|
||||
namespace {
|
||||
|
||||
const char kScheme[] = "radtest-halves";
|
||||
|
||||
int enc(const RadParam*, int, const RadQuantWeight* w, RadEncoding* out) {
|
||||
if (w->rank < 2) return RAD_E_UNSUPPORTED;
|
||||
rad_enc_clear(out);
|
||||
rad_enc_copy_str(out->scheme, kScheme);
|
||||
rad_enc_add_plane(out, "codes", RAD_I8, 1, 1);
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int64_t row_block(const RadParam*, int, const RadQuantWeight*) { return 1; }
|
||||
|
||||
int quantize(const RadParam*, int, const RadQuantWeight* w, float* src, int64_t, int64_t rows,
|
||||
void* const* planes) {
|
||||
int8_t* q = static_cast<int8_t*>(planes[0]);
|
||||
for (int64_t i = 0; i < rows * w->cols; ++i) {
|
||||
const float v = std::nearbyint(src[i] * 2.0f);
|
||||
q[i] = (int8_t)(v > 127.f ? 127.f : v < -128.f ? -128.f : v);
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int decode(const RadEncoding* e, const RadQuantWeight* w, const void* const* planes, int64_t row0,
|
||||
int64_t rows, float* out) {
|
||||
if (std::strcmp(e->scheme, kScheme) != 0) return RAD_E_UNSUPPORTED;
|
||||
const int8_t* q = static_cast<const int8_t*>(planes[0]) + row0 * w->cols;
|
||||
for (int64_t i = 0; i < rows * w->cols; ++i) out[i] = 0.5f * (float)q[i];
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
const RadQuantizerInfo kQuant[] = {{
|
||||
"radtest-halves", "the nearest multiple of one half, as twice it in i8: a scheme of its own",
|
||||
nullptr, 0, enc, row_block, quantize, decode,
|
||||
}};
|
||||
|
||||
const RadPluginInfo kInfo = {
|
||||
RAD_PLUGIN_QUANT, "radtest_quant", "0.1", "a quantiser whose scheme only it decodes", "host",
|
||||
};
|
||||
|
||||
} // namespace
|
||||
|
||||
extern "C" uint32_t rad_plugin_abi_version(void) { return RAD_ABI_VERSION; }
|
||||
extern "C" const RadPluginInfo* rad_plugin_info(void) { return &kInfo; }
|
||||
extern "C" int rad_quant_count(void) { return 1; }
|
||||
extern "C" const RadQuantizerInfo* rad_quant_at(int i) { return i == 0 ? &kQuant[0] : nullptr; }
|
||||
@@ -0,0 +1,114 @@
|
||||
/* tierrows.cc -- device-domain byte-row gather and scatter on the host backend, for the KV tiers'
|
||||
* transfer test (tests/mem_test.cpp).
|
||||
*
|
||||
* The tiers move KV through `gather_rows` and `scatter_rows` resolved in the DEVICE domain, and the
|
||||
* reference library registers those ops in the host domain only -- so without this, the one piece
|
||||
* of the tier that can put another conversation's context into a restored entry (the addressing:
|
||||
* layer-major strides, staging pitch, arena runs, a rank's window of a shared slot) could only be
|
||||
* tested on a card. Here the host backend's memory stands in for the card's.
|
||||
*
|
||||
* STREAM ORDER IS KEPT BY WAITING. The host backend runs each stream on a worker thread, and a
|
||||
* launch here runs on the caller's thread; draining the stream first puts the kernel exactly where
|
||||
* a device launch would sit -- after everything enqueued before it and before everything enqueued
|
||||
* after it returns. The test executable exports the device API for that call (tests/CMakeLists.txt).
|
||||
*
|
||||
* It lives in its own directory, under a name no hierarchy lists, so nothing but the test that asks
|
||||
* for it by path ever loads it: a kernel that computes, registered in the device domain, is exactly
|
||||
* what a real run must never select by accident.
|
||||
*/
|
||||
#include "rad_abi.h"
|
||||
#include "rad_device.h"
|
||||
|
||||
#include <cstdint>
|
||||
#include <cstring>
|
||||
|
||||
#define NELEM(a) (int)(sizeof(a) / sizeof((a)[0]))
|
||||
|
||||
namespace {
|
||||
|
||||
/* Rows of bytes: shape[0] rows of shape[1] bytes, rows `stride[0]` bytes apart. */
|
||||
struct Rows {
|
||||
char* p;
|
||||
int64_t n, width, pitch;
|
||||
};
|
||||
bool rows_of(const RadTensor& t, Rows* out) {
|
||||
if (t.rank != 2 || t.dtype != RAD_U8 || !t.data || t.stride[1] != 1) return false;
|
||||
out->p = (char*)t.data;
|
||||
out->n = t.shape[0];
|
||||
out->width = t.shape[1];
|
||||
out->pitch = t.stride[0];
|
||||
return true;
|
||||
}
|
||||
|
||||
int copy_rows(const RadArgs* a, RadStream s, bool scatter) {
|
||||
if (!a || a->n_t != 3) return RAD_E_INVAL;
|
||||
if (rad_stream_sync(s) != RAD_OK) return RAD_E_DEVICE;
|
||||
/* gather: pool, idx, pack. scatter: pack, idx, pool. */
|
||||
Rows pool, pack;
|
||||
if (!rows_of(a->t[scatter ? 2 : 0], &pool) || !rows_of(a->t[scatter ? 0 : 2], &pack))
|
||||
return RAD_E_SHAPE;
|
||||
const RadTensor& idx = a->t[1];
|
||||
if (idx.dtype != RAD_I32 || !idx.data || idx.shape[0] < pack.n || pack.width != pool.width)
|
||||
return RAD_E_SHAPE;
|
||||
const int32_t* ix = (const int32_t*)idx.data;
|
||||
for (int64_t i = 0; i < pack.n; ++i) {
|
||||
const int32_t r = ix[i];
|
||||
if (r >= pool.n) return RAD_E_INVAL;
|
||||
char* row = pack.p + i * pack.pitch;
|
||||
if (r < 0) {
|
||||
if (!scatter) std::memset(row, 0, (size_t)pack.width);
|
||||
continue;
|
||||
}
|
||||
char* slot = pool.p + (int64_t)r * pool.pitch;
|
||||
if (scatter) std::memcpy(slot, row, (size_t)pack.width);
|
||||
else std::memcpy(row, slot, (size_t)pack.width);
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int t_gather(const RadArgs* a, RadStream s) { return copy_rows(a, s, false); }
|
||||
int t_scatter(const RadArgs* a, RadStream s) { return copy_rows(a, s, true); }
|
||||
|
||||
} /* namespace */
|
||||
|
||||
extern "C" {
|
||||
|
||||
static const RadParamSpec kP[] = {
|
||||
{ "M", RAD_P_INT, RAD_REQUIRED }, { "n", RAD_P_INT, RAD_REQUIRED },
|
||||
{ "dtype", RAD_P_STR, RAD_REQUIRED },
|
||||
};
|
||||
static const RadOperandSpec kGather[] = {
|
||||
{ "x", RAD_OPD_IN, 0 }, { "idx", RAD_OPD_IN, 0 }, { "y", RAD_OPD_OUT, 0 },
|
||||
};
|
||||
static const RadOperandSpec kScatter[] = {
|
||||
{ "v", RAD_OPD_IN, 0 }, { "idx", RAD_OPD_IN, 0 }, { "x", RAD_OPD_INOUT, 0 },
|
||||
};
|
||||
static const RadOpSchema kSchemas[] = {
|
||||
{ "gather_rows", kP, NELEM(kP), kGather, NELEM(kGather), "y[i,:] = x[idx[i],:]" },
|
||||
{ "scatter_rows", kP, NELEM(kP), kScatter, NELEM(kScatter), "x[idx[i],:] = v[i,:]" },
|
||||
};
|
||||
static const RadKernelInfo kKernels[] = {
|
||||
{ .name = "t_rows_gather", .op = "gather_rows", .family = "elem",
|
||||
.computes = "byte rows, on the host backend's memory", .shape = "any", .dtypes = "u8",
|
||||
.domain = RAD_DOMAIN_DEVICE, .priority = 0, .launch = t_gather },
|
||||
{ .name = "t_rows_scatter", .op = "scatter_rows", .family = "elem",
|
||||
.computes = "byte rows, on the host backend's memory", .shape = "any", .dtypes = "u8",
|
||||
.domain = RAD_DOMAIN_DEVICE, .priority = 0, .launch = t_scatter },
|
||||
};
|
||||
static const RadPluginInfo kInfo = {
|
||||
RAD_PLUGIN_KERNEL, "radtest_rows", "0.1",
|
||||
"device-domain byte-row gather/scatter for the KV tier transfer test", "host",
|
||||
};
|
||||
|
||||
uint32_t rad_plugin_abi_version(void) { return RAD_ABI_VERSION; }
|
||||
const RadPluginInfo* rad_plugin_info(void) { return &kInfo; }
|
||||
int rad_kernel_schema_count(void) { return NELEM(kSchemas); }
|
||||
const RadOpSchema* rad_kernel_schema_at(int i) {
|
||||
return (i < 0 || i >= NELEM(kSchemas)) ? nullptr : &kSchemas[i];
|
||||
}
|
||||
int rad_kernel_count(void) { return NELEM(kKernels); }
|
||||
const RadKernelInfo* rad_kernel_at(int i) {
|
||||
return (i < 0 || i >= NELEM(kKernels)) ? nullptr : &kKernels[i];
|
||||
}
|
||||
|
||||
} /* extern "C" */
|
||||
Reference in new issue
Block a user