Archived
radiance 1.7.0
- every model serves without a GPU: libavx covers every op, so `--kernels libavx` alone serves every shipped container - Qwen3-ASR (zivius): speech to text on /v1/audio/transcriptions and live over /v1/realtime - /v1/messages works with Claude Code as it ships (gearwave00001) - a long agent conversation keeps its cached history when the client rewrites its last turn (manueloverride) - a stream's first event goes out with the first token, so llama-benchy measures prefill right - opt-in --prefill-interleave (Smellyyyy, baKon) and --prefill-span (keptn42) - four-rank TP releases the link early; four-rank selftests and docs/TP4.md (goodman-b) - NVFP4 and FP8 compressed-tensors imports (devmilan); tools/rad-export for finetunes and LoRA adapters (baKon) - many fixes, among them lost tokens on stop strings under concurrency, keep-alive, MiniCPM5 tool arguments and the CPU's vision and audio encoders - plugin ABI 17 and changed op schemas: out-of-tree plugins must be rebuilt
This commit is contained in:
1 parent
b068190326
commit
1e968f6e1d
739 files changed
+128447
-84632
No files matched your search
@@ -1,5 +1,3 @@
|
||||
# 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.
|
||||
# The plugin layer's sources are compiled into rad_core by core/CMakeLists.txt's glob. This file
|
||||
# only adds the test plugins, which must be separate .so files so the loader can dlopen them.
|
||||
add_subdirectory(testplugin)
|
||||
+52
-42
@@ -1,27 +1,40 @@
|
||||
/* 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.
|
||||
* A parameter may be declared as a range, because some parameters belong to the batch rather
|
||||
* than the model. M is the main one: a GEMM sees one row at decode, 64 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 run the prefill kernel at M = 1.
|
||||
*
|
||||
* 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.
|
||||
* The bucket boundaries are the candidate kernels' own constraint values. There is no
|
||||
* power-of-two ladder or bucket-count policy here.
|
||||
*/
|
||||
#include "registry.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstdlib>
|
||||
#include <string>
|
||||
|
||||
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. */
|
||||
/* The DIV a row places on the ranged parameter, or the least common multiple of several; 0 when
|
||||
* it places none. */
|
||||
int64_t ranged_div(const KernelRow* r, std::string_view key) {
|
||||
if (!r || !r->info || key.empty()) return 0;
|
||||
int64_t d = 0;
|
||||
for (int i = 0; i < r->info->n_constraints; ++i) {
|
||||
const RadConstraint& c = r->info->constraints[i];
|
||||
if (c.op != RAD_C_DIV || !c.key || key != c.key || c.ival <= 1) continue;
|
||||
int64_t a = d ? d : 1, b = c.ival;
|
||||
while (b) { const int64_t t = a % b; a = b; b = t; }
|
||||
d = (d ? d : 1) / a * c.ival;
|
||||
}
|
||||
return d;
|
||||
}
|
||||
|
||||
/* "M <= 64" for the first band, "M in (16, 64]" for a later one, so the printed table does not
|
||||
* read 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);
|
||||
@@ -36,9 +49,8 @@ std::vector<Band> Registry::build_bands(std::string_view op, std::string_view ra
|
||||
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. */
|
||||
/* No ranged parameter: one band covering everything. hi is INT64_MAX, not the declared value,
|
||||
* so the issue path's band scan finds it for any issue count. */
|
||||
if (ranged_key.empty()) {
|
||||
lo = 0;
|
||||
hi = INT64_MAX;
|
||||
@@ -49,11 +61,13 @@ std::vector<Band> Registry::build_bands(std::string_view op, std::string_view ra
|
||||
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. */
|
||||
/* The union of the LE, GE and EQ values that candidate kernels from every plugin and both
|
||||
* domains place on the ranged parameter: boundaries belong to the candidate set, not to the
|
||||
* kernel that wins a band. An IN on the ranged parameter lists its values, each an EQ with a
|
||||
* band of its own, so the row wins only values it serves. A DIV is not an interval and cuts no
|
||||
* edge: a row with one is resolved at a band's upper bound, which it divides, and the band
|
||||
* records the divisor so the issue path refuses a value inside it the row does not serve
|
||||
* (Resolved::ranged_div). */
|
||||
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
|
||||
@@ -67,12 +81,18 @@ std::vector<Band> Registry::build_bands(std::string_view op, std::string_view ra
|
||||
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. */
|
||||
/* A kernel that starts at v ends the band below it at v-1. */
|
||||
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. */
|
||||
/* An EQ needs both edges, so its value gets a band of its own. */
|
||||
case RAD_C_EQ: add(c.ival - 1); add(c.ival); break;
|
||||
case RAD_C_IN:
|
||||
for (std::string_view tok : split_ws(c.sval ? c.sval : "")) {
|
||||
const std::string t(tok);
|
||||
char* end = nullptr;
|
||||
const long long v = std::strtoll(t.c_str(), &end, 10);
|
||||
if (end && *end == '\0' && end != t.c_str()) { add(v - 1); add(v); }
|
||||
}
|
||||
break;
|
||||
default: break;
|
||||
}
|
||||
}
|
||||
@@ -83,9 +103,8 @@ std::vector<Band> Registry::build_bands(std::string_view op, std::string_view ra
|
||||
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. */
|
||||
/* Each band is resolved at its upper bound, in both domains: the upper bound is the band's
|
||||
* worst case, so a kernel that serves it serves the whole band. */
|
||||
int64_t prev = lo - 1;
|
||||
for (size_t i = 0; i < bounds.size(); ++i) {
|
||||
Band b;
|
||||
@@ -98,31 +117,22 @@ std::vector<Band> Registry::build_bands(std::string_view op, std::string_view ra
|
||||
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;
|
||||
else b.dom[dom].ranged_div = ranged_div(b.dom[dom].row, ranged_key);
|
||||
}
|
||||
|
||||
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).
|
||||
/* No device kernel is fatal. No host kernel only removes host-site execution for this op;
|
||||
* its weights may still live in the host and SSD tiers 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. */
|
||||
* Neither is reported here: this runs once per declared op (64 times for the same op on a
|
||||
* 64-layer model). Declare always completes, and Builder collects the bands' miss strings and
|
||||
* reports once per graph (§3.1), a hole in a range as that band. */
|
||||
return out;
|
||||
}
|
||||
|
||||
|
||||
+85
-138
@@ -19,8 +19,8 @@ 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. */
|
||||
/* dlsym returns void*; converting it to a function pointer is conditionally supported in
|
||||
* standard C++ and works on every target here. The cast is isolated in one place. */
|
||||
template <class Fn>
|
||||
Fn dl_fn(void* h, const char* name) {
|
||||
dlerror();
|
||||
@@ -38,8 +38,8 @@ std::string stem_of(const std::string& path) {
|
||||
|
||||
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. */
|
||||
/* Whether a plugin's declared build target list (separated by spaces, commas or semicolons)
|
||||
* names this device's architecture. */
|
||||
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);
|
||||
@@ -50,11 +50,10 @@ bool target_covers(const std::string& declared, const char* arch) {
|
||||
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. */
|
||||
/* Two schemas for one op are the same when every positional slot means the same thing: parameter
|
||||
* keys, types and requiredness (what the selector matches on) and operand count, roles and
|
||||
* optionality (arguments are positional). Operand names are for diagnostics only (ABI), so "b"
|
||||
* and "w_gate" in slot 1 agree. */
|
||||
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);
|
||||
@@ -68,9 +67,8 @@ bool schema_same(const RadOpSchema& a, const RadOpSchema& b, std::string* diff)
|
||||
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");
|
||||
*diff = fmt("parameter '%s' is %s vs %s", or_empty(x.key), param_kind_name(x.type),
|
||||
param_kind_name(y.type));
|
||||
return false;
|
||||
}
|
||||
if (x.required != y.required) {
|
||||
@@ -108,17 +106,16 @@ void Registry::err_(const char* f, ...) {
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ 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. */
|
||||
/* dlopen and read the plugin's identity without registering anything. Loading has two phases
|
||||
* because the hierarchy is ordered by plugin name, which lives inside the .so: the whole directory
|
||||
* is opened before anything registers, and registration order 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. */
|
||||
/* RTLD_LOCAL is required: every kernel plugin exports the same symbol names (rad_kernel_count
|
||||
* and friends), so with RTLD_GLOBAL the first plugin loaded would answer for all later ones.
|
||||
* Symbols are looked up per handle. */
|
||||
out->code_from = rad::dev_code_mark();
|
||||
out->handle = dlopen(path.c_str(), RTLD_NOW | RTLD_LOCAL);
|
||||
out->code_to = rad::dev_code_mark();
|
||||
@@ -135,10 +132,8 @@ int Registry::stage_(const std::string& path, Staged* out) {
|
||||
}
|
||||
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. */
|
||||
/* Named by file, not RadPluginInfo::name: that struct's layout may differ across ABI
|
||||
* versions. Both versions are printed so the operator can tell 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);
|
||||
@@ -209,26 +204,25 @@ int Registry::commit_(Staged& s, int order) {
|
||||
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. */
|
||||
/* The second half of the key. Optional: a plugin without it serves an unquantised
|
||||
* container, which "" means. */
|
||||
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. */
|
||||
/* Optional: answers what the core needs before it builds the RadBuildCtx for declare.
|
||||
* Absent means every answer is zero (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. */
|
||||
/* Optional: absent means the reply format is read off the chat template. */
|
||||
p.arch_chat_format = dl_fn<const RadChatFormat* (*)(const RadModelMeta*)>(
|
||||
s.handle, "rad_arch_chat_format");
|
||||
/* Optional: absent means the model serves no speech route. */
|
||||
p.arch_audio_format = dl_fn<const RadAudioFormat* (*)(const RadModelMeta*)>(
|
||||
s.handle, "rad_arch_audio_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. */
|
||||
/* The (architecture id, quantisation) pair selects the plugin, so no two plugins may claim
|
||||
* the same pair (§2.4). Sharing an id at different quantisations is normal (qwen35_bf16
|
||||
* and qwen35_fp8). */
|
||||
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' "
|
||||
@@ -251,9 +245,8 @@ int Registry::commit_(Staged& s, int order) {
|
||||
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. */
|
||||
/* All schemas are checked before any is committed, so a plugin refused on one op leaves
|
||||
* nothing registered. */
|
||||
n_declared_schemas = sc_n();
|
||||
for (int i = 0; i < n_declared_schemas; ++i) {
|
||||
const RadOpSchema* sch = sc_at(i);
|
||||
@@ -267,11 +260,9 @@ int Registry::commit_(Staged& s, int order) {
|
||||
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. */
|
||||
/* Disagreeing positional schemas would silently change a call's meaning
|
||||
* (§2.3). The whole plugin is refused, not just the op: it was built against
|
||||
* a different vocabulary. */
|
||||
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(),
|
||||
@@ -300,8 +291,7 @@ int Registry::commit_(Staged& s, int order) {
|
||||
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. */
|
||||
/* A row with no entry point would resolve and then fail to run. */
|
||||
if (!k->launch) {
|
||||
err_("kernel '%s' in plugin '%s' has no launch function", k->name, p.name.c_str());
|
||||
unstage_(s);
|
||||
@@ -313,17 +303,10 @@ int Registry::commit_(Staged& s, int order) {
|
||||
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. */
|
||||
/* Every tunable axis must carry a default that is one of its own values. Untuned
|
||||
* shapes (no cache, an unmeasured shape, another card's cache) run the defaults, with
|
||||
* no other fallback (spec §15). Checked at load rather than first use so a bad axis
|
||||
* fails at startup, not when some shape first misses 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) {
|
||||
@@ -336,9 +319,7 @@ int Registry::commit_(Staged& s, int order) {
|
||||
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",
|
||||
"one of its declared values",
|
||||
k->name, p.name.c_str(), t.key, (long long)t.deflt);
|
||||
unstage_(s);
|
||||
return RAD_E_INVAL;
|
||||
@@ -354,14 +335,12 @@ int Registry::commit_(Staged& s, int order) {
|
||||
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. On the host backend
|
||||
* an engine that serves says no GPU code runs at all (set_no_device_code). */
|
||||
/* A kernel library with no code for this card has its device rows dropped: constraints
|
||||
* do not say which card a row was compiled for, so the rows would resolve and then fail
|
||||
* to launch, and an installation with libraries for several cards would serve only the
|
||||
* first. Coverage is read from the fat binaries its dlopen registered, which the launch
|
||||
* consults (core/device/aql_code.cpp), not from build_target. Host rows stay. On the host
|
||||
* backend no GPU code runs at all (set_no_device_code). */
|
||||
int n_device = 0;
|
||||
for (const auto& r : staged_rows) n_device += r.first->domain == RAD_DOMAIN_DEVICE;
|
||||
std::string why;
|
||||
@@ -389,8 +368,7 @@ int Registry::commit_(Staged& s, int order) {
|
||||
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. */
|
||||
/* All checked before any is registered, as with kernel schemas. */
|
||||
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) {
|
||||
@@ -399,8 +377,8 @@ int Registry::commit_(Staged& s, int order) {
|
||||
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. */
|
||||
/* Quantiser names are unique, so a recipe means the same thing whatever the load
|
||||
* order. */
|
||||
auto clash = [&](const char* other) { return std::strcmp(other, q->name) == 0; };
|
||||
for (const QuantRow& r : quants_)
|
||||
if (clash(r.info->name)) {
|
||||
@@ -424,13 +402,12 @@ int Registry::commit_(Staged& s, int order) {
|
||||
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. */
|
||||
/* Called once after load, before any selection (rad_abi.h). A plugin that cannot open is
|
||||
* refused. */
|
||||
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. */
|
||||
/* RAD_E_UNSUPPORTED: the plugin does not serve this machine (e.g. a library for another
|
||||
* card). A skip, not a failure. */
|
||||
if (st == RAD_E_UNSUPPORTED) {
|
||||
RAD_INFO("plugin '%s' declines this machine and is not loaded", p.name.c_str());
|
||||
unstage_(s);
|
||||
@@ -443,15 +420,14 @@ int Registry::commit_(Staged& s, int order) {
|
||||
}
|
||||
}
|
||||
|
||||
/* 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. */
|
||||
/* What the plugin declares, including ops an earlier plugin already fixed; schema_owner()
|
||||
* answers which plugin fixed an op. */
|
||||
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. */
|
||||
/* Register its decoder so every weight reader can decode its schemes. */
|
||||
if (q->decode) enc_add_decoder(q->decode);
|
||||
}
|
||||
const auto concurrent = dl_fn<RadKernelConcurrentFn>(s.handle, "rad_kernel_concurrent");
|
||||
@@ -470,18 +446,10 @@ int Registry::commit_(Staged& s, int order) {
|
||||
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. */
|
||||
/* A library built for another card fails at every launch with an unhelpful driver error;
|
||||
* warn once here instead. Only a warning: build_target is author-written text, not derived
|
||||
* from the binary, so it cannot justify a refusal. "host" (CPU kernels) and "" (no claim) say
|
||||
* nothing about a device. Applies to libraries whose dlopen registered no fat binaries. */
|
||||
if (p.kind == RAD_PLUGIN_KERNEL && s.code_to == s.code_from && !p.build_target.empty() &&
|
||||
p.build_target != "host") {
|
||||
RadDeviceProps dp{};
|
||||
@@ -502,9 +470,8 @@ int Registry::commit_(Staged& s, int order) {
|
||||
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. */
|
||||
/* The per-op index select() walks, in (hierarchy order, declaration order). Rebuilt whole on
|
||||
* every registration; there are only hundreds of rows, at startup. */
|
||||
void Registry::index_rows_() {
|
||||
by_op_.clear();
|
||||
for (const KernelRow& r : rows_) by_op_[r.info->op].push_back(&r);
|
||||
@@ -534,11 +501,9 @@ 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. */
|
||||
/* Directories in the given order, files in filename order, so an unconfigured set loads
|
||||
* reproducibly. A file name an earlier directory already supplied is shadowed: the operator's
|
||||
* own plugins come ahead of an installation's, and loading both would be a duplicate name. */
|
||||
std::vector<std::string> files, stems;
|
||||
std::string where;
|
||||
for (const std::string& dir : dirs) {
|
||||
@@ -571,7 +536,6 @@ int Registry::load_dirs(const std::vector<std::string>& dirs,
|
||||
stems.push_back(stem);
|
||||
}
|
||||
}
|
||||
const std::string dir = where;
|
||||
|
||||
std::vector<Staged> staged;
|
||||
for (const std::string& f : files) {
|
||||
@@ -584,8 +548,8 @@ int Registry::load_dirs(const std::vector<std::string>& dirs,
|
||||
staged.push_back(s);
|
||||
}
|
||||
|
||||
/* An entry names a library by its declared name or by its file, written as the operator sees
|
||||
* it on disk: `libr4d`, `r4d`, `libr4d.so` and a path to it are one library. */
|
||||
/* An entry matches a library's declared name or its file: `libr4d`, `r4d`, `libr4d.so` and a
|
||||
* path to it are one library. */
|
||||
auto names = [](const std::string& h, const Staged& s) {
|
||||
return h == s.name || h == s.file || stem_of(h) == s.file;
|
||||
};
|
||||
@@ -594,13 +558,10 @@ int Registry::load_dirs(const std::vector<std::string>& dirs,
|
||||
if (s.info && s.info->kind == RAD_PLUGIN_KERNEL)
|
||||
found += (found.empty() ? "" : ", ") + s.name;
|
||||
|
||||
/* A HIERARCHY NAMES THE KERNEL LIBRARIES THAT SERVE, AND ONLY THOSE LOAD. Ordering alone
|
||||
* cannot keep a library out: selection runs per domain, so a library named first that has no
|
||||
* device row for an op leaves that op to whichever unnamed library does -- a GPU library on a
|
||||
* machine whose card it was not built for, say -- and an operator who listed what to use gets
|
||||
* something else. A kernel library on the search path that the list leaves out is closed again
|
||||
* before it registers anything, and said once. Architecture and quantiser plugins are not
|
||||
* kernel libraries and no list ranks them. */
|
||||
/* A non-empty hierarchy is exclusive. Ordering alone cannot keep a library out: selection
|
||||
* runs per domain, so an op the named library has no device row for would fall to an unnamed
|
||||
* one. Unnamed kernel libraries are closed before registering anything. Architecture and
|
||||
* quantiser plugins are never ranked. */
|
||||
if (!hierarchy.empty()) {
|
||||
std::vector<Staged> kept;
|
||||
std::string left_out;
|
||||
@@ -623,17 +584,10 @@ int Registry::load_dirs(const std::vector<std::string>& dirs,
|
||||
"does not name, and so not loaded: %s", left_out.c_str());
|
||||
}
|
||||
|
||||
/* The hierarchy is configured, not discovered: a library the operator named takes that
|
||||
* position. With no list every kernel library on the search path loads, so dropping an .so
|
||||
* into the directory adds it with no configuration.
|
||||
*
|
||||
* 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 places it where it is named, 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. */
|
||||
/* A named library takes its position in the list; unnamed ones follow. A reference library
|
||||
* (RadPluginReferenceFn) is pinned below every other unnamed plugin, because it matches every
|
||||
* op it declares and would make anything behind it unreachable. Naming it places it where
|
||||
* named, e.g. ahead of a library to compare against. */
|
||||
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)
|
||||
@@ -646,20 +600,19 @@ int Registry::load_dirs(const std::vector<std::string>& dirs,
|
||||
hit = true;
|
||||
}
|
||||
}
|
||||
/* The list is what loads, so an entry that matches nothing is a library that is not
|
||||
* there to select -- and a list none of whose entries match loads no kernel library. */
|
||||
/* The list is what loads: an entry that matches nothing loads nothing in its place. */
|
||||
if (!hit)
|
||||
RAD_WARN("--kernels (or RADIANCE_KERNELS) names '%s', which is no kernel library in "
|
||||
"%s, so nothing loads in its place; the kernel libraries there are: %s",
|
||||
hierarchy[h].c_str(), dir.c_str(), found.empty() ? "none" : found.c_str());
|
||||
hierarchy[h].c_str(), where.c_str(), found.empty() ? "none" : found.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. */
|
||||
/* Continue from what is already loaded, so loading kernels/ then architectures/ does not put
|
||||
* two plugins at position 0. */
|
||||
int order = 0;
|
||||
for (const Plugin& p : plugins_) order = std::max(order, p.order + 1);
|
||||
|
||||
@@ -683,18 +636,14 @@ int Registry::load_tune(const std::string& radiance_home, const std::string& mac
|
||||
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. */
|
||||
/* `load` refuses a file whose machine key (line 2, tunecache.h) is another machine's, so
|
||||
* these rows 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. */
|
||||
/* A row whose op has no schema in the loaded set cannot have its parameters checked, so a typo
|
||||
* would become a silent miss. Checked once the set is complete, because an override plugin may
|
||||
* rely on the schema of a plugin below it, which loads later. */
|
||||
int Registry::check_complete() {
|
||||
int st = RAD_OK;
|
||||
for (const KernelRow& r : rows_) {
|
||||
@@ -729,9 +678,7 @@ 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. */
|
||||
/* Reverse load order: a later plugin may depend on state an earlier one established. */
|
||||
for (auto it = plugins_.rbegin(); it != plugins_.rend(); ++it) {
|
||||
if (it->close) it->close();
|
||||
if (it->handle) dlclose(it->handle);
|
||||
|
||||
+135
-149
@@ -1,44 +1,38 @@
|
||||
/* 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:
|
||||
* Rules enforced here and nowhere else:
|
||||
*
|
||||
* 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).
|
||||
* The hierarchy is absolute. Plugins are queried in configured order and the first plugin with
|
||||
* any matching kernel supplies it; a lower-ranked plugin never outbids a higher one, however
|
||||
* 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.
|
||||
* Specificity is declared, not derived. Within one plugin the highest `priority` among matching
|
||||
* rows wins, ties by declaration order. Counting matched constraints gets it backwards:
|
||||
* {head_dim<=1024, gqa>=1, block%16==0, causal in {0,1}} matches four, {head_dim==256, gqa==6}
|
||||
* matches two, and the second is 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).
|
||||
* Schemas are fixed by first declaration. The first plugin in hierarchy order to declare an op
|
||||
* fixes its schema; a later plugin declaring it differently is refused at load with both named.
|
||||
* Arguments are positional, so disagreeing schemas would give the same call different meanings
|
||||
* depending on which plugin won selection (§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).
|
||||
* Bucket boundaries are the constraint values: the union of the LE, GE and EQ values candidate
|
||||
* kernels place on the ranged parameter, clamped to the declared range (§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.
|
||||
* A reference library is last. 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 ahead of a reference, so a kernel library for a new
|
||||
* card works with no configuration (§18); naming it in the hierarchy overrides that. The rule
|
||||
* is keyed on the declaration, never on a name, so bundled libraries load like third-party ones.
|
||||
*
|
||||
* 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.
|
||||
* Lifetime: a Resolved, a Band and a KernelRow point into a plugin's static tables and are valid
|
||||
* only as long as the Registry that loaded them; close() dlcloses. The core keeps one Registry for
|
||||
* the process; a tool that loads two kernel sets in turn must 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.
|
||||
* Threading: loading is single-threaded, before the rank threads exist. select() and
|
||||
* init_instance() run on every rank thread during declare, so the selection log and instance list
|
||||
* share one mutex. It is never taken on the step path.
|
||||
*/
|
||||
#pragma once
|
||||
#include "rad_core.h"
|
||||
@@ -67,7 +61,7 @@ struct Plugin {
|
||||
std::string description;
|
||||
std::string build_target;
|
||||
|
||||
uint32_t kind = 0; /* RAD_PLUGIN_KERNEL | RAD_PLUGIN_ARCH */
|
||||
uint32_t kind = 0; /* one of RAD_PLUGIN_KERNEL, _ARCH, _QUANT */
|
||||
int order = 0; /* hierarchy position; 0 is highest */
|
||||
void* handle = nullptr;
|
||||
|
||||
@@ -79,32 +73,30 @@ struct Plugin {
|
||||
/* 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. */
|
||||
/* Architecture plugins are loaded and identified here; the build component drives them. The
|
||||
* registry only guarantees that no two plugins claim the same (architecture id, quantisation)
|
||||
* pair (§2.4): qwen35_bf16 and qwen35_fp8 both answer "qwen35" at two weight formats.
|
||||
* `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. */
|
||||
/* Optional (rad_builder.h); null means every question answers zero. Asked before declare, so
|
||||
* model facts that are inputs to declaration are still read by the plugin, not the core. */
|
||||
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. */
|
||||
/* Optional (rad_builder.h); null means the reply format is derived from the chat template. */
|
||||
const RadChatFormat* (*arch_chat_format)(const RadModelMeta*) = nullptr;
|
||||
/* Optional (rad_builder.h); null means the model serves no speech route. */
|
||||
const RadAudioFormat* (*arch_audio_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. */
|
||||
/* What select() did, in enough detail to print §16's table and explain why a kernel was not
|
||||
* picked. `candidates` holds every row considered: not rows of the other domain, and not rows
|
||||
* behind a plugin that already supplied a match. */
|
||||
struct SelectionTrace {
|
||||
struct Candidate {
|
||||
std::string plugin;
|
||||
@@ -123,11 +115,10 @@ struct SelectionTrace {
|
||||
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. */
|
||||
/* A RAD_DERIVED parameter the caller did not supply: its constraints were skipped during
|
||||
* matching and the winner's RAD_C_EQ value for the key was written into the resolved
|
||||
* geometry. `known` is false when the winner has no EQ on the key (e.g. ref's
|
||||
* `block_size >= 1`); the caller must report that, not read a zero. */
|
||||
struct DerivedParam {
|
||||
std::string key;
|
||||
long long value = 0;
|
||||
@@ -148,53 +139,44 @@ public:
|
||||
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 as the operator wrote it -- `libr4d`, `r4d`, `libr4d.so`), so substituting a kernel is
|
||||
* dropping an .so in a directory and naming it ahead of the default. A non-empty list is
|
||||
* EXCLUSIVE: a kernel library it does not name is closed before it registers anything, and an
|
||||
* entry that matches nothing is warned about by name. An empty list loads every kernel library
|
||||
* found, in filename order so the result is reproducible, with a reference library last.
|
||||
/* Scan a directory of .so files and load them in hierarchy order. `hierarchy` is an ordered
|
||||
* list of plugin names (RadPluginInfo::name, or the file as written: `libr4d`, `r4d`,
|
||||
* `libr4d.so`), so substituting a kernel means dropping an .so in and naming it ahead of the
|
||||
* default. A non-empty list is exclusive: a kernel library it does not name is closed before
|
||||
* it registers anything, and an entry that matches nothing is warned about. An empty list
|
||||
* loads every kernel library in filename order (reproducible), a reference library last.
|
||||
* Architecture and quantiser plugins are not ranked and always load.
|
||||
*
|
||||
* 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). */
|
||||
* Always completes: every loadable plugin is loaded, every refusal goes to load_errors(), and
|
||||
* the first negative status is returned, so one run reports every failure (§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. */
|
||||
/* The same over several directories (a $RADIANCE_HOME search path) as one set: the hierarchy
|
||||
* orders plugins across all of them, and a file name an earlier directory holds shadows later
|
||||
* ones. */
|
||||
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). */
|
||||
/* One plugin at a known hierarchy position (rad-info, rad-kbench); the engine uses load_dir.
|
||||
* Returns 1, with nothing registered, when 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. */
|
||||
/* Every kernel row's op must have a schema somewhere in the loaded set. An override plugin
|
||||
* may ship kernels for an op whose schema a later-loading plugin declares, so this runs once
|
||||
* the set is complete: load_dir calls it, a caller assembling a set by hand calls it last. */
|
||||
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. */
|
||||
/* The device a kernel library's device code is checked against at load: the first card the
|
||||
* caller will run on. Default 0; the engine sets it after choosing its cards, before loading. */
|
||||
void set_code_device(int device) { code_device_ = device; }
|
||||
|
||||
/* THE ENGINE ABOUT TO SERVE ON THE HOST BACKEND SAYS SO: no card is visible, and no GPU code
|
||||
* object runs in this process at all. A kernel library that brought device code then has its
|
||||
* device rows left out of selection at load, its host rows staying, so every op takes its host
|
||||
* kernel. Only the engine says this. A tool that selects without serving -- rad-convert's
|
||||
* recipe check, rad-kbench's tables, a test of a library's constraints -- sees every row, as
|
||||
* it would on the machine the model is served on. */
|
||||
/* Set by the engine when serving on the host backend, where no GPU code object runs: device
|
||||
* rows are left out at load and every op takes its host kernel. Only the engine sets it; tools
|
||||
* that select without serving (rad-convert's recipe check, rad-kbench, constraint tests) see
|
||||
* every row, as on the serving machine. */
|
||||
void set_no_device_code(bool v) { no_device_code_ = v; }
|
||||
/* WHAT THE ENGINE MEASURED ABOUT THE RANKS' DEVICES, for the constraints on "device." keys
|
||||
* (rad_types.h). Set before the first selection, by whoever chose the devices; a registry
|
||||
* nobody told anything has no facts, and a kernel constrained on one is not selected. */
|
||||
/* Measured facts about the ranks' devices, for constraints on "device." keys (rad_types.h).
|
||||
* Set before the first selection by whoever chose the devices; without a fact, a kernel
|
||||
* constrained on it is not selected. */
|
||||
void set_device_fact(std::string_view key, long long v) { device_facts_.set_i(key, v); }
|
||||
const Geometry& device_facts() const { return device_facts_; }
|
||||
|
||||
void close(); /* fini instances, close hooks, dlclose, forget everything */
|
||||
|
||||
@@ -202,9 +184,8 @@ public:
|
||||
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. */
|
||||
/* Every quantiser the loaded quantiser plugins offer, in load order. Names are unique (a
|
||||
* duplicate is refused at load); quantizer() is null when nothing offers the name. */
|
||||
struct QuantRow {
|
||||
const RadQuantizerInfo* info = nullptr;
|
||||
std::string plugin;
|
||||
@@ -222,25 +203,19 @@ public:
|
||||
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. */
|
||||
/* Check a declared parameter set against the op's schema; a misspelled op fails with the
|
||||
* near-miss named. Returns RAD_OK, RAD_E_NOSCHEMA (no such op) or RAD_E_SCHEMA, with `err`
|
||||
* written for an architecture-plugin author. */
|
||||
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. */
|
||||
/* The closest known op name within a small edit distance, or "". Also used by the builder. */
|
||||
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.
|
||||
/* Load $RADIANCE_HOME/tune/<machine>.tune (written by rad-tune). resolve() then moves a shape
|
||||
* off each axis's declared default wherever the file has a row for it. A missing file is not
|
||||
* an error; every shape stays on its default. The core owns the cache and the policy
|
||||
* (tunecache.h, applied in select.cpp). Without this call the file is silently ignored.
|
||||
*
|
||||
* Returns the number of rows loaded, or a negative status. */
|
||||
int load_tune(const std::string& radiance_home, const std::string& machine = std::string());
|
||||
@@ -251,67 +226,66 @@ public:
|
||||
* 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. */
|
||||
* RAD_DERIVED parameters (rad_abi.h) are supplied by the kernel, so a constraint on one is
|
||||
* skipped when the caller did not name it, and the winner's RAD_C_EQ value comes back in
|
||||
* `why->derived` (resolve() writes it into the geometry). This breaks the §7.2 cycle: the
|
||||
* block manager reads the block size off the resolved attention kernel, and a constraint whose
|
||||
* key the geometry lacks does not hold. A caller that supplies the key pins it and matches
|
||||
* normally, so a forced block size is refused by name rather than substituted.
|
||||
*
|
||||
* `record` is false for questions the engine did not ask (the graph dump replaying bands), so
|
||||
* the selection table records only what this deployment resolved.
|
||||
*
|
||||
* `accept`, when given, is asked of every row whose constraints hold; a non-empty answer drops
|
||||
* the row with that reason. This is how a weight's encoding takes part in selection: a kernel
|
||||
* whose layout hook rejects the operand's encoding (RAD_E_DTYPE) is skipped and the next one
|
||||
* chosen, so a bf16 lm_head goes to the bf16 GEMM rather than 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(). */
|
||||
/* The row select() would choose if `plugin` were the whole hierarchy: the same constraint
|
||||
* match, derived-key skip, device facts and filter, restricted to one plugin and never
|
||||
* recorded. rad-kbench asks each library this way so a replay runs the row the engine would
|
||||
* run with that library alone. `why->derived` carries the winner's derived values. */
|
||||
const KernelRow* select_in(std::string_view plugin, std::string_view op, const Geometry& g,
|
||||
int domain, const RowFilter* accept = nullptr,
|
||||
SelectionTrace* why = nullptr) const;
|
||||
|
||||
/* Selection plus per-instance bookkeeping: the tuned axes and their source, and the frozen
|
||||
* geometry (the query plus the winner's derived keys, so rad_kv_block_size() and RadArgs.p
|
||||
* both see them). Does not call init(); 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.
|
||||
/* 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. Each band is resolved at its upper
|
||||
* bound, the band's worst case and so the only value 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.
|
||||
* An empty `ranged_key` returns one band with hi = INT64_MAX, which the issue path's band scan
|
||||
* always finds.
|
||||
*
|
||||
* 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. */
|
||||
* Both domains are resolved so the execution site can change at runtime without re-resolving.
|
||||
* A band with no device kernel is fatal; one with no host kernel only removes host-site
|
||||
* execution. Neither aborts here: the caller reports misses once declare completes. */
|
||||
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. */
|
||||
/* Calls init() once per resolved instance (one op, band and domain) with the frozen geometry,
|
||||
* rank and world size, off the hot path: e.g. libr4d's all-reduce sets up peer signal buffers
|
||||
* and IPC handles here. A negative return aborts startup; 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. */
|
||||
/* Every distinct question the selector was asked, in first-asked order, with its answer and,
|
||||
* for a miss, the refusing constraint. Repeats are folded into a count, which shows how much
|
||||
* of the model resolved to each kernel. */
|
||||
std::string selection_table() const;
|
||||
size_t n_selections() const;
|
||||
void clear_selections();
|
||||
@@ -334,8 +308,8 @@ private:
|
||||
|
||||
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 */
|
||||
std::string derived; /* "block_size:=16", kept apart from the query because it was
|
||||
* not part of the question asked */
|
||||
int domain = 0;
|
||||
int priority = 0;
|
||||
long long count = 1;
|
||||
@@ -362,14 +336,26 @@ private:
|
||||
|
||||
mutable std::mutex mu_;
|
||||
std::vector<SelectionRecord> log_;
|
||||
std::unordered_map<std::string, size_t> log_at_; /* SelectionRecord::key -> index in 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. */
|
||||
* attention kernel is compiled for; the block manager sizes itself from it (§7.2). Returns false
|
||||
* when the kernel has no constraint on that key with that operator; that is not a default, and
|
||||
* the caller decides. */
|
||||
bool kernel_constraint(const KernelRow& r, std::string_view key, int c_op, long long* out);
|
||||
|
||||
/* "an integer", "a string", ... for a RAD_P_* parameter kind, for diagnostics. */
|
||||
const char* param_kind_name(int kind);
|
||||
|
||||
/* Why kernel `ki` cannot read weight operand `operand` (named `name`) stored as encoding `enc` with
|
||||
* planes `sel` described by `planes` (dtype and extents; data unused), or "" when it can. A row
|
||||
* whose layout hook answers RAD_E_DTYPE does not read the encoding, and a device row with no hook
|
||||
* reads a single plane as stored. A hookless host row reads canonically. The builder's band
|
||||
* resolution and rad-kbench's replay both ask this, so they choose the same row. */
|
||||
std::string weight_refusal(const RadKernelInfo* ki, const Geometry& g, int operand,
|
||||
const RadEncoding& enc, const int* sel, const RadTensor* planes,
|
||||
int n_sel, std::string_view name);
|
||||
|
||||
} /* namespace rad */
|
||||
+22
-31
@@ -1,10 +1,9 @@
|
||||
/* 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.
|
||||
* Without a schema, a typo and an unimplemented op give the same "nothing resolved". With one, a
|
||||
* misspelled op fails declare with the near-miss named. The core learns the op vocabulary from
|
||||
* the plugins, so new ops need no core change.
|
||||
*/
|
||||
#include "registry.h"
|
||||
|
||||
@@ -15,9 +14,7 @@ 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. */
|
||||
/* Levenshtein, O(nm). Runs on short names, once per failed declare. */
|
||||
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);
|
||||
@@ -33,10 +30,8 @@ int edit_distance(std::string_view a, std::string_view b) {
|
||||
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. */
|
||||
/* How far a name may be from a known one and still be suggested: one edit for a short name, up
|
||||
* to three for a long one. A wrong suggestion is worse than none. */
|
||||
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);
|
||||
@@ -54,7 +49,9 @@ std::string suggest(std::string_view want, const std::vector<std::string>& known
|
||||
return best;
|
||||
}
|
||||
|
||||
const char* kind_name(int kind) {
|
||||
} /* namespace */
|
||||
|
||||
const char* param_kind_name(int kind) {
|
||||
switch (kind) {
|
||||
case RAD_P_INT: return "an integer";
|
||||
case RAD_P_STR: return "a string";
|
||||
@@ -64,8 +61,6 @@ const char* kind_name(int 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;
|
||||
@@ -80,9 +75,8 @@ 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. */
|
||||
/* Include ops that have rows but no schema (check_complete() reports those), so a near-miss
|
||||
* search can still name them. */
|
||||
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());
|
||||
@@ -142,25 +136,24 @@ int Registry::validate(std::string_view op, const RadParam* p, int n_p, std::str
|
||||
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));
|
||||
name.c_str(), p[i].key, param_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));
|
||||
name.c_str(), p[i].key, param_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. */
|
||||
/* A float slot takes only a float: an integer would land in `ival` while the kernel
|
||||
* reads `dval` (a silent zero eps). Constraints never match on a float (rad_types.h), so
|
||||
* only this check catches it. */
|
||||
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));
|
||||
"with RAD_F64()", name.c_str(), p[i].key, param_kind_name(p[i].kind));
|
||||
return RAD_E_SCHEMA;
|
||||
}
|
||||
|
||||
@@ -172,9 +165,8 @@ int Registry::validate(std::string_view op, const RadParam* p, int n_p, std::str
|
||||
}
|
||||
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). */
|
||||
/* At most one ranged parameter per op, so the bucket-table index at issue is a
|
||||
* single integer; the run phase depends on this (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;
|
||||
@@ -183,10 +175,9 @@ int Registry::validate(std::string_view op, const RadParam* p, int n_p, std::str
|
||||
}
|
||||
|
||||
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. */
|
||||
/* Only RAD_REQUIRED. RAD_DERIVED is supplied by the kernel: the caller cannot know, e.g.,
|
||||
* the block size before a kernel resolves (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);
|
||||
|
||||
+176
-125
@@ -1,11 +1,9 @@
|
||||
/* 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.
|
||||
* The selector finds a kernel compiled for this geometry and domain in the highest plugin that has
|
||||
* one. A match is necessary, not sufficient: strides, contiguity, alignment and buffer sizes are
|
||||
* properties of a call, and the entry point still rejects what it cannot run.
|
||||
*/
|
||||
#include "registry.h"
|
||||
|
||||
@@ -20,17 +18,16 @@ 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. */
|
||||
/* True when every constraint holds. Otherwise `why` names the first one that failed and what it
|
||||
* wanted. */
|
||||
bool row_matches(const KernelRow& r, const Geometry& g, const Geometry& facts,
|
||||
const std::vector<std::string>& skip, std::string* why) {
|
||||
static const size_t kFact = std::strlen(RAD_DEVICE_FACT_PREFIX);
|
||||
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). */
|
||||
/* A constraint on a RAD_DERIVED parameter the caller did not name is the answer, read back
|
||||
* afterwards, not a predicate; matching on it would make the kernel unreachable
|
||||
* (rad_abi.h, spec §7.2). */
|
||||
if (c.key && std::find(skip.begin(), skip.end(), c.key) != skip.end()) continue;
|
||||
/* A "device." key is a fact about the machine, read from what the engine measured. */
|
||||
if (c.key && std::strncmp(c.key, RAD_DEVICE_FACT_PREFIX, kFact) == 0) {
|
||||
@@ -50,9 +47,30 @@ bool row_matches(const KernelRow& r, const Geometry& g, const Geometry& facts,
|
||||
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. */
|
||||
/* The op's RAD_DERIVED keys (from its schema) that the caller did not supply. A supplied one is
|
||||
* pinned and matches like any other parameter. */
|
||||
std::vector<std::string> unsupplied_derived(const RadOpSchema* sch, const Geometry& g) {
|
||||
std::vector<std::string> keys;
|
||||
if (!sch) return keys;
|
||||
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)) keys.emplace_back(sch->params[i].key);
|
||||
}
|
||||
return keys;
|
||||
}
|
||||
|
||||
/* The scan select() and select_in() share: the first plugin in hierarchy order with a match
|
||||
* supplies the row, the highest priority within it wins, ties to the row declared first. With
|
||||
* `only` set, rows of every other plugin are passed over. Every row considered goes into
|
||||
* `t.candidates` and each distinct refusal into `misses`. */
|
||||
const KernelRow* scan_rows(const std::vector<const KernelRow*>* rows, const Geometry& g,
|
||||
int domain, const Geometry& facts,
|
||||
const std::vector<std::string>& derived_keys,
|
||||
const Registry::RowFilter* accept, std::string_view only,
|
||||
SelectionTrace& t, std::vector<std::string>* misses);
|
||||
|
||||
/* The question, normalised so two spellings of it fold together in the table. Only the fold key
|
||||
* is sorted; the geometry is displayed as asked. */
|
||||
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;
|
||||
@@ -86,67 +104,18 @@ const KernelRow* Registry::select(std::string_view op, const Geometry& g, int do
|
||||
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<std::string> derived_keys = unsupplied_derived(schema(op), g);
|
||||
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, device_facts_, 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
const KernelRow* best = scan_rows(rows, g, domain, device_facts_, derived_keys, accept, {},
|
||||
t, &misses);
|
||||
|
||||
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. */
|
||||
/* Each skipped derived key takes the winner's RAD_C_EQ value. A kernel with no EQ on it
|
||||
* (e.g. ref's `block_size >= 1`) leaves it unknown rather than zero; the caller decides. */
|
||||
for (const std::string& key : derived_keys) {
|
||||
SelectionTrace::DerivedParam d;
|
||||
d.key = key;
|
||||
@@ -167,9 +136,111 @@ const KernelRow* Registry::select(std::string_view op, const Geometry& g, int do
|
||||
return best;
|
||||
}
|
||||
|
||||
const KernelRow* Registry::select_in(std::string_view plugin, std::string_view op,
|
||||
const Geometry& g, int domain, const RowFilter* accept,
|
||||
SelectionTrace* why) const {
|
||||
SelectionTrace local;
|
||||
SelectionTrace& t = why ? *why : local;
|
||||
t = SelectionTrace{};
|
||||
t.op = std::string(op);
|
||||
t.query = g.str();
|
||||
t.domain = domain;
|
||||
if (plugin.empty()) {
|
||||
t.reason = "no plugin named";
|
||||
return nullptr;
|
||||
}
|
||||
const std::vector<std::string> derived_keys = unsupplied_derived(schema(op), g);
|
||||
std::vector<std::string> misses;
|
||||
const KernelRow* best = scan_rows(rows_for(op), g, domain, device_facts_, derived_keys,
|
||||
accept, plugin, t, &misses);
|
||||
if (best) {
|
||||
t.kernel = best->info->name;
|
||||
t.plugin = best->plugin;
|
||||
t.priority = best->info->priority;
|
||||
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 {
|
||||
for (size_t i = 0; i < misses.size(); ++i) t.reason += (i ? "; " : "") + misses[i];
|
||||
if (t.reason.empty())
|
||||
t.reason = fmt("no %s kernel for op '%s' in %.*s", domain_name(domain), t.op.c_str(),
|
||||
(int)plugin.size(), plugin.data());
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
namespace {
|
||||
|
||||
const KernelRow* scan_rows(const std::vector<const KernelRow*>* rows, const Geometry& g,
|
||||
int domain, const Geometry& facts,
|
||||
const std::vector<std::string>& derived_keys,
|
||||
const Registry::RowFilter* accept, std::string_view only,
|
||||
SelectionTrace& t, std::vector<std::string>* misses) {
|
||||
const KernelRow* best = nullptr;
|
||||
if (!rows) return best;
|
||||
bool in_group = false;
|
||||
int cur_order = 0;
|
||||
for (const KernelRow* r : *rows) {
|
||||
if (!only.empty() && r->plugin != only) continue;
|
||||
/* Rows of the other domain are neither candidates nor refusals, but their existence is
|
||||
* recorded for the placement planner (§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: stop at the first plugin with a match, before a lower
|
||||
* plugin can outbid it. */
|
||||
if (best) break;
|
||||
cur_order = r->plugin_order;
|
||||
in_group = true;
|
||||
}
|
||||
|
||||
std::string whynot;
|
||||
bool ok = row_matches(*r, g, facts, 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" });
|
||||
/* Highest declared priority wins; a tie goes to the row declared first. */
|
||||
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);
|
||||
}
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
} /* namespace */
|
||||
|
||||
std::string weight_refusal(const RadKernelInfo* ki, const Geometry& g, int operand,
|
||||
const RadEncoding& enc, const int* sel, const RadTensor* planes,
|
||||
int n_sel, std::string_view name) {
|
||||
char es[256];
|
||||
if (!ki->layout) {
|
||||
if (ki->domain == RAD_DOMAIN_DEVICE && n_sel > 1) {
|
||||
rad_enc_format(&enc, es, sizeof es);
|
||||
return fmt("reads '%.*s' as stored, and it is %d planes of %s", (int)name.size(),
|
||||
name.data(), n_sel, es);
|
||||
}
|
||||
return std::string();
|
||||
}
|
||||
RadLayout L{};
|
||||
if (ki->layout(g.params(), g.n_params(), operand, &enc, sel, planes, n_sel, &L) ==
|
||||
RAD_E_DTYPE) {
|
||||
rad_enc_format(&enc, es, sizeof es);
|
||||
return fmt("does not read '%.*s' encoded %s", (int)name.size(), name.data(), es);
|
||||
}
|
||||
return std::string();
|
||||
}
|
||||
|
||||
/* "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. */
|
||||
* resolve: resolve runs only at startup, and a parsed-once cache would need a mutex. */
|
||||
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, ';');
|
||||
@@ -183,7 +254,7 @@ static std::string tune_pin_for(const char* spec, std::string_view op) {
|
||||
return {};
|
||||
}
|
||||
|
||||
/* For an error message, which is the whole value of refusing a bad pin rather than defaulting. */
|
||||
/* Every axis and its legal values, for the bad-pin error message. */
|
||||
static std::string tunable_names(const RadKernelInfo* k) {
|
||||
std::string s;
|
||||
for (int i = 0; i < k->n_tunables; ++i) {
|
||||
@@ -198,15 +269,14 @@ static std::string tunable_names(const RadKernelInfo* k) {
|
||||
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. */
|
||||
/* Whether `v` is one of the axis's declared values. A cached or pinned value outside the list is
|
||||
* never applied, so a stale cache cannot launch 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. */
|
||||
/* Whether the combination passes the kernel's cross-axis test; no test 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;
|
||||
@@ -231,28 +301,22 @@ Resolved Registry::resolve(std::string_view op, const Geometry& g, int domain, S
|
||||
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
|
||||
/* The frozen geometry is the query plus the kernel's derived values, so rad_kv_block_size()
|
||||
* and RadArgs.p agree: the kernel launches 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.
|
||||
/* Tuned axes. A kernel declares a space (RadTunable); the point chosen is the cached one when
|
||||
* this shape was measured on this machine, else each axis's `deflt` (spec §15).
|
||||
*
|
||||
* 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.
|
||||
* The cache key is the frozen geometry after the derived parameters and before the choices
|
||||
* go in: rad-tune keys rows on the geometry the builder recorded, so a key that included its
|
||||
* own answer could never match.
|
||||
*
|
||||
* 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. */
|
||||
* An axis the cached row does not mention keeps its default, and a row key the kernel no
|
||||
* longer declares is ignored (tunecache.h), so a library may add or widen axes between builds
|
||||
* and keep the measurements that still apply. */
|
||||
r.geom_key = TuneCache::canon_geometry(r.geom);
|
||||
|
||||
const RadKernelInfo* ki = r.row->info;
|
||||
@@ -278,17 +342,14 @@ Resolved Registry::resolve(std::string_view op, const Geometry& g, int domain, S
|
||||
}
|
||||
|
||||
/* 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.
|
||||
* op, for debugging without a rebuild (e.g. the all-reduce's drain depth and acquire
|
||||
* ordering are axes).
|
||||
*
|
||||
* 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")) {
|
||||
* An unknown key or a value the axis does not offer is a hard error: a pin that silently
|
||||
* did not take is worse than none. A kernel with no axes is not a failed pin (libref
|
||||
* declares none), so a device pin does not remove the host band. */
|
||||
static const char* const pin = std::getenv("RADIANCE_TUNE");
|
||||
if (pin) {
|
||||
const std::string want = tune_pin_for(pin, op);
|
||||
for (const auto& kv : TuneCache::parse_choice(want)) {
|
||||
int idx = -1;
|
||||
@@ -306,11 +367,9 @@ Resolved Registry::resolve(std::string_view op, const Geometry& g, int domain, S
|
||||
}
|
||||
}
|
||||
|
||||
/* 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. */
|
||||
/* A combination the kernel's cross-axis test refuses (a cache from another build, or a
|
||||
* pin legal per axis but not together) falls back to all defaults, which the kernel must
|
||||
* always be able to run. */
|
||||
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)
|
||||
@@ -326,8 +385,8 @@ Resolved Registry::resolve(std::string_view op, const Geometry& g, int domain, S
|
||||
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. */
|
||||
/* scratch_bytes stays 0: the scratch hook needs a RadArgs with the operand tensors, which the
|
||||
* builder owns and sizes the arena with. */
|
||||
return r;
|
||||
}
|
||||
|
||||
@@ -336,9 +395,9 @@ 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 */
|
||||
}
|
||||
/* The same question, therefore the same answer. */
|
||||
const auto at = log_at_.try_emplace(key, log_.size());
|
||||
if (!at.second) { ++log_[at.first->second].count; return; }
|
||||
SelectionRecord s;
|
||||
s.op = op;
|
||||
s.domain = domain;
|
||||
@@ -348,10 +407,8 @@ void Registry::record_(const std::string& op, int domain, const Geometry& g,
|
||||
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. */
|
||||
/* Derived keys are kept apart from the query because the caller did not ask for them. ":="
|
||||
* is the kernel's answer; "?" is a winner with no EQ on the key, which the caller must fill. */
|
||||
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)
|
||||
@@ -368,6 +425,7 @@ size_t Registry::n_selections() const {
|
||||
void Registry::clear_selections() {
|
||||
std::lock_guard<std::mutex> lk(mu_);
|
||||
log_.clear();
|
||||
log_at_.clear();
|
||||
}
|
||||
|
||||
std::string Registry::selection_table() const {
|
||||
@@ -400,11 +458,7 @@ std::string Registry::selection_table() const {
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ 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. */
|
||||
/* See registry.h: init_instance. */
|
||||
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;
|
||||
@@ -413,16 +467,13 @@ int Registry::init_instance(Resolved& r, int rank, int world_size) {
|
||||
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. */
|
||||
/* A negative init aborts startup rather than launching a kernel whose setup failed. */
|
||||
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. */
|
||||
/* Registered even when the instance is null: fini pairs 1:1 with every successful init. */
|
||||
std::lock_guard<std::mutex> lk(mu_);
|
||||
instances_.emplace_back(k, inst);
|
||||
return RAD_OK;
|
||||
|
||||
@@ -1,10 +1,8 @@
|
||||
# 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.
|
||||
# Test plugins built from one source: a hierarchy for plugin_test to load, a schema conflict to
|
||||
# refuse and a stale ABI to reject. They go under $RADIANCE_HOME/testkernels, not kernels/, because
|
||||
# the engine scans kernels/ at startup and must never select a row that implements nothing
|
||||
# (spec.md §17). The two that must be refused live in testkernels/bad, so loading testkernels/ is
|
||||
# clean and the refusals are requested by path.
|
||||
rad_add_plugin(radtest_base testkernels SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/testplugin.cc)
|
||||
target_compile_definitions(radtest_base PRIVATE RADTEST_BASE=1)
|
||||
|
||||
@@ -17,22 +15,18 @@ 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.
|
||||
# Two architecture plugins claiming one architecture id: the first is identified, the second
|
||||
# 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.
|
||||
# Two plugins for a load with no hierarchy; one declares itself a reference implementation.
|
||||
# Do not rename: load_dir reads in sorted order, so the reference (`..._a`) is staged first, and
|
||||
# the test checks that the loader still ranks it below every other kernel plugin. The reverse
|
||||
# naming would pass on alphabetical order alone.
|
||||
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\")
|
||||
@@ -40,12 +34,54 @@ target_compile_definitions(radtest_ord_a PRIVATE RADTEST_BASE=1 RADTEST_REFERENC
|
||||
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.
|
||||
# Rows for rules the base plugin does not reach (a non-interval ranged constraint, a cross-axis
|
||||
# tune test, a layout hook, a capacity parameter), in their own directory so loading testkernels/
|
||||
# is unchanged.
|
||||
rad_add_plugin(radtest_extra testkernels/extra SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/testplugin.cc)
|
||||
target_compile_definitions(radtest_extra PRIVATE RADTEST_EXTRA=1)
|
||||
|
||||
# Two tunable axes the loader must refuse, loaded by path, and a library that declines the machine.
|
||||
rad_add_plugin(radtest_badtune_default testkernels/bad
|
||||
SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/testplugin.cc)
|
||||
target_compile_definitions(radtest_badtune_default PRIVATE RADTEST_BADTUNE=1)
|
||||
rad_add_plugin(radtest_badtune_twice testkernels/bad SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/testplugin.cc)
|
||||
target_compile_definitions(radtest_badtune_twice PRIVATE RADTEST_BADTUNE=2)
|
||||
rad_add_plugin(radtest_decline testkernels/decline SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/testplugin.cc)
|
||||
target_compile_definitions(radtest_decline PRIVATE RADTEST_DECLINE=1)
|
||||
|
||||
# One architecture family at three quantisations, for the (id, quantisation) selection key.
|
||||
foreach(q plain fp8 w4)
|
||||
set(_rad_q "${q}")
|
||||
if(q STREQUAL "plain")
|
||||
set(_rad_q "")
|
||||
endif()
|
||||
rad_add_plugin(radtest_archq_${q} testarchq SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/testplugin.cc)
|
||||
target_compile_definitions(radtest_archq_${q} PRIVATE RADTEST_ARCHQ=1
|
||||
RADTEST_ARCHQ_NAME="radtest_archq_${q}"
|
||||
RADTEST_ARCHQ_QUANT="${_rad_q}")
|
||||
endforeach()
|
||||
|
||||
# KV tier transfer test plugin. Unlike the others it computes (byte-row gather and scatter in the
|
||||
# device domain, on host backend memory), so only tests/mem_test.cpp loads it, by path. It calls
|
||||
# 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.
|
||||
# A quantiser with its own scheme, read only by its decode hook. tests/quant_test.cpp loads it by
|
||||
# path to check that its weights decode through the core's decoder.
|
||||
rad_add_plugin(radtest_quant testquant SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/testquant.cc)
|
||||
|
||||
# Deliberately defective kernel libraries, one per defect, for tests/kbench_mutant_test.cpp: a
|
||||
# replay must fail each of them (or, for kbm_ok, pass it). One source, as above; KBM_MUTANT picks
|
||||
# the defect. Under testkernels/kbmut, loaded only by name.
|
||||
set(RAD_KBM_MUTANTS ok scale nan half overrun refuse shape argmax inwrite enc
|
||||
CACHE INTERNAL "the kbmutant.cc builds, read by tests/CMakeLists.txt")
|
||||
set(i 0)
|
||||
foreach(m ${RAD_KBM_MUTANTS})
|
||||
rad_add_plugin(kbm_${m} testkernels/kbmut SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/kbmutant.cc)
|
||||
target_compile_definitions(kbm_${m} PRIVATE KBM_MUTANT=${i} KBM_NAME=\"kbm_${m}\")
|
||||
math(EXPR i "${i} + 1")
|
||||
endforeach()
|
||||
|
||||
# An architecture that declares a norm, a projection and an add from a synthetic container, so
|
||||
# tests/kbench_mutant_test.cpp can record a fixture on the host with libref alone.
|
||||
rad_add_plugin(radtest_kbarch testarch/kbench SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/kbarch.cc)
|
||||
@@ -0,0 +1,93 @@
|
||||
/* kbarch.cc -- an architecture small enough to declare from a synthetic container, for
|
||||
* tests/kbench_mutant_test.cpp: rad-kbench records a fixture from it on the host backend, from the
|
||||
* container and again from the container's skeleton, with libref the only kernel library.
|
||||
*
|
||||
* It declares a norm with a gain and a projection, both read from the container, and an add. It
|
||||
* never runs a step. Loaded only by path, from a test's own home.
|
||||
*/
|
||||
#include "rad_abi.h"
|
||||
#include "rad_builder.h"
|
||||
|
||||
#include <cstring>
|
||||
|
||||
namespace {
|
||||
|
||||
RadParam p_int(const char* k, long long v) {
|
||||
RadParam p{};
|
||||
p.key = k;
|
||||
p.kind = RAD_P_INT;
|
||||
p.ival = v;
|
||||
return p;
|
||||
}
|
||||
RadParam p_range(const char* k, long long lo, long long hi) {
|
||||
RadParam p = p_int(k, lo);
|
||||
p.kind = RAD_P_RANGE;
|
||||
p.ihi = hi;
|
||||
return p;
|
||||
}
|
||||
RadParam p_str(const char* k, const char* v) {
|
||||
RadParam p{};
|
||||
p.key = k;
|
||||
p.kind = RAD_P_STR;
|
||||
p.sval = v;
|
||||
return p;
|
||||
}
|
||||
RadParam p_f64(const char* k, double v) {
|
||||
RadParam p{};
|
||||
p.key = k;
|
||||
p.kind = RAD_P_F64;
|
||||
p.dval = v;
|
||||
return p;
|
||||
}
|
||||
|
||||
} /* namespace */
|
||||
|
||||
extern "C" {
|
||||
|
||||
static const RadPluginInfo kInfo = {
|
||||
RAD_PLUGIN_ARCH, "radtest_kbarch", "0.1",
|
||||
"declares a norm, a projection and an add from a synthetic container, for rad-kbench's tests",
|
||||
"host",
|
||||
};
|
||||
|
||||
uint32_t rad_plugin_abi_version(void) { return RAD_ABI_VERSION; }
|
||||
const RadPluginInfo* rad_plugin_info(void) { return &kInfo; }
|
||||
const char* rad_arch_id(void) { return "radtest.kbench"; }
|
||||
const char* rad_arch_quant(void) { return ""; }
|
||||
|
||||
int rad_arch_declare(RadBuilder* b, const RadModelMeta* m, const RadBuildCtx* ctx) {
|
||||
const int64_t n = m->n_embd, N = m->n_ff;
|
||||
if (n <= 0 || N <= 0 || ctx->max_tok <= 0) return RAD_E_INVAL;
|
||||
RadWeightDecl g{};
|
||||
g.dtype = RAD_BF16;
|
||||
g.rank = 1;
|
||||
g.shape[0] = n;
|
||||
g.access = RAD_ACCESS_PER_TOKEN;
|
||||
g.shard = RAD_SHARD_NONE;
|
||||
g.group.layer = -1;
|
||||
g.group.expert = -1;
|
||||
const rad_weight wn = rad_decl_weight(b, "norm.weight", &g);
|
||||
RadWeightDecl w = g;
|
||||
w.rank = 2;
|
||||
w.shape[0] = N;
|
||||
w.shape[1] = n;
|
||||
const rad_weight wp = rad_decl_weight(b, "proj.weight", &w);
|
||||
if (!wn || !wp) return RAD_E_INVAL;
|
||||
|
||||
const RadParam pn[] = { p_range("M", 1, ctx->max_tok), p_int("n", n), p_f64("eps", 1e-6),
|
||||
p_str("dtype", "bf16") };
|
||||
const RadParam pg[] = { p_range("M", 1, ctx->max_tok), p_int("N", N), p_int("K", n),
|
||||
p_str("dtype", "bf16") };
|
||||
const RadParam pa[] = { p_range("M", 1, ctx->max_tok), p_int("n", N), p_str("dtype", "bf16") };
|
||||
if (!rad_decl_op(b, "rmsnorm", pn, 4, &wn, 1)) return RAD_E_INVAL;
|
||||
if (!rad_decl_op(b, "gemm_nt", pg, 4, &wp, 1)) return RAD_E_INVAL;
|
||||
if (!rad_decl_op(b, "add", pa, 3, nullptr, 0)) return RAD_E_INVAL;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
void rad_arch_step(struct RadCtx* c, const struct RadBatch* batch) {
|
||||
(void)c;
|
||||
(void)batch;
|
||||
}
|
||||
|
||||
} /* extern "C" */
|
||||
@@ -0,0 +1,272 @@
|
||||
/* kbmutant.cc -- kernel libraries that are wrong on purpose, for tests/kbench_mutant_test.cpp.
|
||||
*
|
||||
* rad-kbench's verdicts are only worth something if a wrong kernel fails them. Each build of this
|
||||
* file (-DKBM_MUTANT=..., see CMakeLists.txt) is one library implementing a few libref ops, with
|
||||
* one defect: an output scaled past its tolerance, a NaN, an unwritten half, a write one byte past
|
||||
* an output, a refusal of a geometry its constraints accept, a description of an output that
|
||||
* disagrees with the reference's, an id off by one, a write into an input, and a preferred row that
|
||||
* cannot read its weight's encoding. KBM_OK is the same library without a defect.
|
||||
*
|
||||
* It declares no schemas: libref's own fix the ops. Device-domain rows run on the host backend's
|
||||
* memory, after draining the stream, so the guarded allocations and their margins are real; the
|
||||
* gather and scatter device rows instead queue their work on the stream as copies, which the
|
||||
* timing pass's gate can hold. Like
|
||||
* tierrows.cc, a computing library registered in the device domain must never be found by a real
|
||||
* run, so it lives under testkernels/ and is loaded only by name.
|
||||
*/
|
||||
#include "rad_abi.h"
|
||||
#include "rad_device.h"
|
||||
#include "rad_plugin.h"
|
||||
|
||||
#include <cmath>
|
||||
#include <cstdint>
|
||||
#include <cstring>
|
||||
|
||||
#define NELEM(a) (int)(sizeof(a) / sizeof((a)[0]))
|
||||
|
||||
#define KBM_OK 0
|
||||
#define KBM_SCALE 1
|
||||
#define KBM_NAN 2
|
||||
#define KBM_HALF 3
|
||||
#define KBM_OVERRUN 4
|
||||
#define KBM_REFUSE 5
|
||||
#define KBM_SHAPE 6
|
||||
#define KBM_ARGMAX 7
|
||||
#define KBM_INWRITE 8
|
||||
#define KBM_ENC 9
|
||||
|
||||
#ifndef KBM_MUTANT
|
||||
#define KBM_MUTANT KBM_OK
|
||||
#endif
|
||||
#ifndef KBM_NAME
|
||||
#define KBM_NAME "kbm_ok"
|
||||
#endif
|
||||
|
||||
namespace {
|
||||
|
||||
int64_t numel(const RadTensor& t) { return rad_tensor_numel(&t); }
|
||||
|
||||
/* A device row runs where a device launch would: after everything enqueued before it. */
|
||||
int order(RadStream s) { return s && rad_stream_sync(s) != RAD_OK ? RAD_E_DEVICE : RAD_OK; }
|
||||
|
||||
/* y = a + b, with this library's defect. */
|
||||
int add_impl(const RadArgs* a, RadStream s, bool device) {
|
||||
if (order(s) != RAD_OK) return RAD_E_DEVICE;
|
||||
if (!a || a->n_t < 3 || !a->t[0].data || !a->t[1].data || !a->t[2].data) return RAD_E_INVAL;
|
||||
if (KBM_MUTANT == KBM_REFUSE) return RAD_E_SHAPE;
|
||||
const RadTensor &x = a->t[0], &y = a->t[1], &o = a->t[2];
|
||||
const int64_t n = numel(o);
|
||||
for (int64_t i = 0; i < n; ++i) {
|
||||
if (KBM_MUTANT == KBM_HALF && i >= n / 2) break;
|
||||
float v = rad_load_f32(x.data, x.dtype, i) + rad_load_f32(y.data, y.dtype, i);
|
||||
/* Three times the bf16 tolerance (6e-3). */
|
||||
if (KBM_MUTANT == KBM_SCALE) v *= 1.018f;
|
||||
rad_store_f32(o.data, o.dtype, i, v);
|
||||
}
|
||||
if (KBM_MUTANT == KBM_NAN) rad_store_f32(o.data, o.dtype, n / 3, std::nanf(""));
|
||||
if (KBM_MUTANT == KBM_OVERRUN && device)
|
||||
((uint8_t*)o.data)[rad_dtype_bytes(o.dtype, n)] = 0x5A;
|
||||
if (KBM_MUTANT == KBM_INWRITE && !device)
|
||||
rad_store_f32(x.data, x.dtype, 0, rad_load_f32(x.data, x.dtype, 0) + 1.0f);
|
||||
return RAD_OK;
|
||||
}
|
||||
int add_host(const RadArgs* a, RadStream s) { return add_impl(a, s, false); }
|
||||
int add_device(const RadArgs* a, RadStream s) { return add_impl(a, s, true); }
|
||||
|
||||
/* y[i,:] = x[idx[i],:], byte rows. */
|
||||
int gather_rows(const RadArgs* a, RadStream s) {
|
||||
if (order(s) != RAD_OK) return RAD_E_DEVICE;
|
||||
if (!a || a->n_t < 3) return RAD_E_INVAL;
|
||||
const RadTensor &x = a->t[0], &idx = a->t[1], &y = a->t[2];
|
||||
if (x.rank != 2 || y.rank != 2 || idx.dtype != RAD_I32) return RAD_E_SHAPE;
|
||||
const int64_t row = rad_dtype_bytes(y.dtype, y.shape[1]);
|
||||
for (int64_t i = 0; i < y.shape[0]; ++i) {
|
||||
const int32_t r = ((const int32_t*)idx.data)[i];
|
||||
if (r < 0 || r >= x.shape[0]) return RAD_E_INVAL;
|
||||
std::memcpy((uint8_t*)y.data + i * row, (const uint8_t*)x.data + r * row, (size_t)row);
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* The same gather as one stream copy a row: a device row whose work is on its stream, which the
|
||||
* timing pass can queue behind a gate (the rows above compute when called, after draining it). It
|
||||
* reads `idx` when called, which only the host backend's device memory allows. */
|
||||
int gather_rows_device(const RadArgs* a, RadStream s) {
|
||||
if (!a || a->n_t < 3 || !s) return RAD_E_INVAL;
|
||||
const RadTensor &x = a->t[0], &idx = a->t[1], &y = a->t[2];
|
||||
if (x.rank != 2 || y.rank != 2 || idx.dtype != RAD_I32) return RAD_E_SHAPE;
|
||||
const int64_t row = rad_dtype_bytes(y.dtype, y.shape[1]);
|
||||
for (int64_t i = 0; i < y.shape[0]; ++i) {
|
||||
const int32_t r = ((const int32_t*)idx.data)[i];
|
||||
if (r < 0 || r >= x.shape[0]) return RAD_E_INVAL;
|
||||
if (rad_memcpy_async((uint8_t*)y.data + i * row, (const uint8_t*)x.data + r * row, row, s) !=
|
||||
RAD_OK)
|
||||
return RAD_E_DEVICE;
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* x[idx[i],:] = v[i,:], in place: on the host, and as stream copies (see gather_rows_device). */
|
||||
int scatter_rows(const RadArgs* a, RadStream s) {
|
||||
if (order(s) != RAD_OK) return RAD_E_DEVICE;
|
||||
if (!a || a->n_t < 3) return RAD_E_INVAL;
|
||||
const RadTensor &v = a->t[0], &idx = a->t[1], &x = a->t[2];
|
||||
if (v.rank != 2 || x.rank != 2 || idx.dtype != RAD_I32) return RAD_E_SHAPE;
|
||||
const int64_t row = rad_dtype_bytes(v.dtype, v.shape[1]);
|
||||
for (int64_t i = 0; i < v.shape[0]; ++i) {
|
||||
const int32_t r = ((const int32_t*)idx.data)[i];
|
||||
if (r < 0 || r >= x.shape[0]) return RAD_E_INVAL;
|
||||
uint8_t* dst = (uint8_t*)x.data + r * row;
|
||||
const uint8_t* src = (const uint8_t*)v.data + i * row;
|
||||
/* A destination already holding its value was written by an earlier launch, so `x` was
|
||||
* not restored in between: refused, which is how kbench_mutant_test sees that the timing
|
||||
* pass restores in-place operands. Drawn rows never match by chance. */
|
||||
if (std::memcmp(dst, src, (size_t)row) == 0) return RAD_E_STATE;
|
||||
std::memcpy(dst, src, (size_t)row);
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
int scatter_rows_device(const RadArgs* a, RadStream s) {
|
||||
if (!a || a->n_t < 3 || !s) return RAD_E_INVAL;
|
||||
const RadTensor &v = a->t[0], &idx = a->t[1], &x = a->t[2];
|
||||
if (v.rank != 2 || x.rank != 2 || idx.dtype != RAD_I32) return RAD_E_SHAPE;
|
||||
const int64_t row = rad_dtype_bytes(v.dtype, v.shape[1]);
|
||||
for (int64_t i = 0; i < v.shape[0]; ++i) {
|
||||
const int32_t r = ((const int32_t*)idx.data)[i];
|
||||
if (r < 0 || r >= x.shape[0]) return RAD_E_INVAL;
|
||||
if (rad_memcpy_async((uint8_t*)x.data + r * row, (const uint8_t*)v.data + i * row, row, s) !=
|
||||
RAD_OK)
|
||||
return RAD_E_DEVICE;
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* token[m] = the lower id of a row's largest logit. */
|
||||
int sample_argmax(const RadArgs* a, RadStream s) {
|
||||
if (order(s) != RAD_OK) return RAD_E_DEVICE;
|
||||
if (!a || a->n_t < 3) return RAD_E_INVAL;
|
||||
const RadTensor &l = a->t[0], &tok = a->t[2];
|
||||
if (l.rank != 2 || l.dtype != RAD_F32 || tok.dtype != RAD_I32) return RAD_E_DTYPE;
|
||||
for (int64_t m = 0; m < l.shape[0]; ++m) {
|
||||
const float* row = (const float*)l.data + m * l.shape[1];
|
||||
int32_t best = 0;
|
||||
for (int64_t v = 1; v < l.shape[1]; ++v) if (row[v] > row[best]) best = (int32_t)v;
|
||||
if (KBM_MUTANT == KBM_ARGMAX) best += 1;
|
||||
((int32_t*)tok.data)[m] = best;
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* y = x * rsqrt(mean(x^2) + eps) * (w + wadd), as libref computes it. */
|
||||
int rmsnorm(const RadArgs* a, RadStream s) {
|
||||
if (order(s) != RAD_OK) return RAD_E_DEVICE;
|
||||
if (!a || a->n_t < 3 || !a->t[1].data) return RAD_E_INVAL;
|
||||
const RadTensor &x = a->t[0], &w = a->t[1], &y = a->t[2];
|
||||
const int64_t n = rad_args_geti_or(a, "n", 0);
|
||||
const double eps = rad_args_getf_or(a, "eps", 1e-6);
|
||||
const double wadd = rad_args_getf_or(a, "wadd", 0.0);
|
||||
if (n <= 0 || numel(x) % n) return RAD_E_SHAPE;
|
||||
for (int64_t r = 0; r < numel(x) / n; ++r) {
|
||||
float ss = 0.0f;
|
||||
for (int64_t i = 0; i < n; ++i) {
|
||||
const float v = rad_load_f32(x.data, x.dtype, r * n + i);
|
||||
ss += v * v;
|
||||
}
|
||||
const float inv = 1.0f / std::sqrt(ss / (float)n + (float)eps);
|
||||
for (int64_t i = 0; i < n; ++i)
|
||||
rad_store_f32(y.data, y.dtype, r * n + i,
|
||||
rad_load_f32(x.data, x.dtype, r * n + i) * inv *
|
||||
(rad_load_f32(w.data, w.dtype, i) + (float)wadd));
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* A preferred row that reads no encoding a recording carries: its layout hook refuses, so the
|
||||
* engine passes it over, and its launch would fail the comparison if a replay chose it anyway. */
|
||||
[[maybe_unused]] int rmsnorm_wrong(const RadArgs* a, RadStream s) {
|
||||
const int rc = rmsnorm(a, s);
|
||||
if (rc == RAD_OK) rad_store_f32(a->t[2].data, a->t[2].dtype, 0, 1e6f);
|
||||
return rc;
|
||||
}
|
||||
[[maybe_unused]] int refuse_layout(const RadParam*, int, int, const RadEncoding*, const int*,
|
||||
const RadTensor*, int, RadLayout*) {
|
||||
return RAD_E_DTYPE;
|
||||
}
|
||||
|
||||
/* `add` described with an output one column wider than the reference describes it. */
|
||||
[[maybe_unused]] int add_shape_wide(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
|
||||
if (operand < 0 || operand > 2) return RAD_E_SHAPE;
|
||||
std::memset(out, 0, sizeof *out);
|
||||
out->idx_const = -1;
|
||||
out->dtype = RAD_BF16;
|
||||
out->rank = 2;
|
||||
out->shape[0] = rad_param_getdim(p, n_p, "M", 0);
|
||||
out->shape[1] = rad_param_getdim(p, n_p, "n", 0) + (operand == 2 ? 1 : 0);
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
const RadConstraint kSmall[] = { RAD_CLE("M", 4) };
|
||||
|
||||
} /* namespace */
|
||||
|
||||
extern "C" {
|
||||
|
||||
#if KBM_MUTANT == KBM_SHAPE
|
||||
#define KBM_ADD_SHAPE add_shape_wide
|
||||
#else
|
||||
#define KBM_ADD_SHAPE nullptr
|
||||
#endif
|
||||
|
||||
static const RadKernelInfo kKernels[] = {
|
||||
{ .name = "kbm_add", .op = "add", .family = "elem", .computes = "y = a + b",
|
||||
.shape = "any", .dtypes = "bf16", .domain = RAD_DOMAIN_HOST, .priority = 0,
|
||||
.launch = add_host, .opd_shape = KBM_ADD_SHAPE },
|
||||
{ .name = "kbm_add_device", .op = "add", .family = "elem", .computes = "y = a + b",
|
||||
.shape = "any", .dtypes = "bf16", .domain = RAD_DOMAIN_DEVICE, .priority = 0,
|
||||
.launch = add_device, .opd_shape = KBM_ADD_SHAPE },
|
||||
/* Reached only at M <= 4, which the recorded cases do not use: --record-rows' target. */
|
||||
{ .name = "kbm_add_small", .op = "add", .family = "elem", .computes = "y = a + b",
|
||||
.shape = "M <= 4", .dtypes = "bf16", .domain = RAD_DOMAIN_HOST, .priority = 5,
|
||||
.constraints = kSmall, .n_constraints = NELEM(kSmall), .launch = add_host,
|
||||
.opd_shape = KBM_ADD_SHAPE },
|
||||
{ .name = "kbm_gather_rows", .op = "gather_rows", .family = "elem", .computes = "byte rows",
|
||||
.shape = "any", .dtypes = "any", .domain = RAD_DOMAIN_HOST, .priority = 0,
|
||||
.launch = gather_rows },
|
||||
{ .name = "kbm_gather_rows_device", .op = "gather_rows", .family = "elem",
|
||||
.computes = "byte rows, one stream copy each", .shape = "any", .dtypes = "any",
|
||||
.domain = RAD_DOMAIN_DEVICE, .priority = 0, .launch = gather_rows_device },
|
||||
{ .name = "kbm_scatter_rows", .op = "scatter_rows", .family = "elem", .computes = "byte rows",
|
||||
.shape = "any", .dtypes = "any", .domain = RAD_DOMAIN_HOST, .priority = 0,
|
||||
.launch = scatter_rows },
|
||||
{ .name = "kbm_scatter_rows_device", .op = "scatter_rows", .family = "elem",
|
||||
.computes = "byte rows, one stream copy each", .shape = "any", .dtypes = "any",
|
||||
.domain = RAD_DOMAIN_DEVICE, .priority = 0, .launch = scatter_rows_device },
|
||||
{ .name = "kbm_sample_argmax", .op = "sample_argmax", .family = "sample",
|
||||
.computes = "greedy", .shape = "any", .dtypes = "f32", .domain = RAD_DOMAIN_HOST,
|
||||
.priority = 0, .launch = sample_argmax },
|
||||
#if KBM_MUTANT == KBM_ENC
|
||||
{ .name = "kbm_rmsnorm_wide", .op = "rmsnorm", .family = "norm",
|
||||
.computes = "reads a layout no recording carries", .shape = "any", .dtypes = "bf16",
|
||||
.domain = RAD_DOMAIN_HOST, .priority = 10, .launch = rmsnorm_wrong,
|
||||
.layout = refuse_layout },
|
||||
#endif
|
||||
{ .name = "kbm_rmsnorm", .op = "rmsnorm", .family = "norm", .computes = "rmsnorm",
|
||||
.shape = "any", .dtypes = "bf16", .domain = RAD_DOMAIN_HOST, .priority = 0,
|
||||
.launch = rmsnorm },
|
||||
};
|
||||
|
||||
static const RadPluginInfo kInfo = {
|
||||
RAD_PLUGIN_KERNEL, KBM_NAME, "0.1",
|
||||
"a deliberately defective kernel library for rad-kbench's own tests", "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 0; }
|
||||
const RadOpSchema* rad_kernel_schema_at(int) { return nullptr; }
|
||||
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" */
|
||||
@@ -7,9 +7,10 @@
|
||||
* 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.
|
||||
* One source, several .so files, selected by -D: kernel plugins that load, kernel plugins that must
|
||||
* be refused or that decline the machine, and architecture plugins that claim one id between them
|
||||
* or one family at several quantisations. The rows are worth reading side by side, and 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
|
||||
@@ -17,18 +18,20 @@
|
||||
* exclusion rule in a file this component does not own.
|
||||
*/
|
||||
#include "rad_abi.h"
|
||||
#include "rad_planes.h"
|
||||
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
|
||||
#if defined(RADTEST_ARCH) || defined(RADTEST_ARCH2)
|
||||
#if defined(RADTEST_ARCH) || defined(RADTEST_ARCH2) || defined(RADTEST_ARCHQ)
|
||||
#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)
|
||||
!defined(RADTEST_BADABI) && !defined(RADTEST_IS_ARCH) && !defined(RADTEST_EXTRA) && \
|
||||
!defined(RADTEST_BADTUNE) && !defined(RADTEST_DECLINE)
|
||||
#define RADTEST_BASE 1
|
||||
#endif
|
||||
|
||||
@@ -88,7 +91,15 @@ 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; }
|
||||
/* radtest_decline is a library for another machine: it declines this one at open. */
|
||||
int rad_plugin_open(void) {
|
||||
++g_open_calls;
|
||||
#if defined(RADTEST_DECLINE)
|
||||
return RAD_E_UNSUPPORTED;
|
||||
#else
|
||||
return RAD_OK;
|
||||
#endif
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ operands */
|
||||
/* Roles matter to the core (a weight operand is resolved through a handle, an output feeds the
|
||||
@@ -333,6 +344,177 @@ static const RadPluginInfo kInfo = {
|
||||
extern "C" int rad_plugin_reference(void) { return 1; }
|
||||
#endif
|
||||
|
||||
/* ================================================================== radtest_extra */
|
||||
/* Rows for rules the base plugin's ops do not reach: a constraint on the ranged key that is not an
|
||||
* interval, a tunable axis with a cross-axis test, a kernel that relayouts its weight, and a
|
||||
* capacity parameter. In testkernels/extra, so loading testkernels/ alone is unchanged. */
|
||||
#elif defined(RADTEST_EXTRA)
|
||||
|
||||
static const RadOperandSpec kOpdCap[] = {
|
||||
{ "x", RAD_OPD_IN, 0 }, { "y", RAD_OPD_OUT, 0 },
|
||||
};
|
||||
static const RadParamSpec kPCap[] = {
|
||||
{ "M", RAD_P_INT, RAD_REQUIRED, RAD_PROLE_NONE },
|
||||
{ "cap", RAD_P_INT, RAD_REQUIRED, RAD_PROLE_CAPACITY },
|
||||
{ "n", RAD_P_INT, RAD_REQUIRED, RAD_PROLE_NONE },
|
||||
};
|
||||
|
||||
static const RadOpSchema kSchemas[] = {
|
||||
{ "t_div", kPTie, NELEM(kPTie), kOpdNorm, NELEM(kOpdNorm),
|
||||
"IN and DIV on the ranged key" },
|
||||
{ "t_tune", kPGemm, NELEM(kPGemm), kOpdGemm, NELEM(kOpdGemm),
|
||||
"a tunable axis with a cross-axis test" },
|
||||
{ "t_lay", kPGemm, NELEM(kPGemm), kOpdGemm, NELEM(kOpdGemm),
|
||||
"a kernel that stores its weight in its own layout" },
|
||||
{ "t_join", kPGemm, NELEM(kPGemm), kOpdGemm, NELEM(kOpdGemm),
|
||||
"a weight of several planes: a device kernel's own form, a host kernel's joined one" },
|
||||
{ "t_cap", kPCap, NELEM(kPCap), kOpdCap, NELEM(kOpdCap),
|
||||
"a capacity a sizing declare may shrink" },
|
||||
};
|
||||
|
||||
/* M in {8, 24}, and M divisible by 16 up to 64. */
|
||||
static const RadConstraint kCDivIn[] = { RAD_CIN("M", "8 24") };
|
||||
static const RadConstraint kCDivM16[] = { RAD_CDIV("M", 16), RAD_CLE("M", 64) };
|
||||
|
||||
/* bn = 128 only where the output has at least 128 columns. */
|
||||
static int t_tune_valid(const RadParam* p, int n_p, const RadParam* choice, int n_choice) {
|
||||
long long n = 0, bn = 0;
|
||||
for (int i = 0; i < n_p; ++i)
|
||||
if (p[i].key && std::strcmp(p[i].key, "N") == 0) n = p[i].ival;
|
||||
for (int i = 0; i < n_choice; ++i)
|
||||
if (choice[i].key && std::strcmp(choice[i].key, "bn") == 0) bn = choice[i].ival;
|
||||
return bn <= n ? 1 : 0;
|
||||
}
|
||||
|
||||
/* Stores a bf16 weight, or fp8 codes with their scales, in a "tiled" form of its own, and reads no
|
||||
* other encoding (plain fp8 among them). */
|
||||
static int t_lay_layout(const RadParam* p, int n_p, int operand, const RadEncoding* enc,
|
||||
const int* sel, const RadTensor* planes, int n_planes, RadLayout* out) {
|
||||
(void)p; (void)n_p; (void)operand;
|
||||
if (!enc || !sel || !planes || n_planes < 1 || !out) return RAD_E_INVAL;
|
||||
const uint32_t codes = enc->plane[sel[0]].dtype;
|
||||
const bool bf16 = n_planes == 1 && codes == RAD_BF16;
|
||||
const bool fp8 = n_planes == 2 && codes == RAD_F8E4M3;
|
||||
if (!bf16 && !fp8) return RAD_E_DTYPE;
|
||||
out->tag = bf16 ? "tiled" : "tiled-fp8";
|
||||
out->dtype = codes;
|
||||
out->rank = 2;
|
||||
out->shape[0] = planes[0].shape[0];
|
||||
out->shape[1] = planes[0].shape[1];
|
||||
out->align = 4096;
|
||||
int64_t bytes = 0;
|
||||
for (int i = 0; i < n_planes; ++i)
|
||||
bytes += rad_dtype_bytes(planes[i].dtype, rad_tensor_numel(&planes[i]));
|
||||
out->bytes = bytes > 0 ? bytes : 1;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* The joined form every host library shares (abi/rad_planes.h). */
|
||||
static int t_join_host_layout(const RadParam* p, int n_p, int operand, const RadEncoding* enc,
|
||||
const int* sel, const RadTensor* planes, int n_planes,
|
||||
RadLayout* out) {
|
||||
(void)p; (void)n_p; (void)operand;
|
||||
return rad_planes_layout(enc, sel, planes, n_planes, out);
|
||||
}
|
||||
|
||||
static const RadConstraint kCLayTiled[] = { RAD_CLE("M", 16) };
|
||||
static const RadConstraint kCLayPlain[] = { RAD_CLE("M", 4096) };
|
||||
|
||||
static const RadKernelInfo kKernels[] = {
|
||||
{ .name = "t_div_in", .op = "t_div", .family = "norm",
|
||||
.computes = "nothing; a registry row", .shape = "M in {8, 24}", .dtypes = "any",
|
||||
.domain = RAD_DOMAIN_DEVICE, .priority = 40,
|
||||
.constraints = kCDivIn, .n_constraints = NELEM(kCDivIn), .launch = t_launch },
|
||||
{ .name = "t_div_m16", .op = "t_div", .family = "norm",
|
||||
.computes = "nothing; a registry row", .shape = "M <= 64, M divisible by 16",
|
||||
.dtypes = "any", .domain = RAD_DOMAIN_DEVICE, .priority = 30,
|
||||
.constraints = kCDivM16, .n_constraints = NELEM(kCDivM16), .launch = t_launch },
|
||||
{ .name = "t_div_any", .op = "t_div", .family = "norm",
|
||||
.computes = "nothing; a registry row", .shape = "any", .dtypes = "any",
|
||||
.domain = RAD_DOMAIN_DEVICE, .priority = 10, .launch = t_launch },
|
||||
|
||||
{ .name = "t_tune_picky", .op = "t_tune", .family = "gemm",
|
||||
.computes = "nothing; a registry row", .shape = "any", .dtypes = "any",
|
||||
.domain = RAD_DOMAIN_DEVICE, .priority = 10,
|
||||
.tunables = kTGemmM64, .n_tunables = NELEM(kTGemmM64), .tune_valid = t_tune_valid,
|
||||
.launch = t_launch },
|
||||
|
||||
{ .name = "t_lay_tiled", .op = "t_lay", .family = "gemm",
|
||||
.computes = "nothing; a registry row", .shape = "M <= 16", .dtypes = "bf16 / fp8 + scale",
|
||||
.domain = RAD_DOMAIN_DEVICE, .priority = 20,
|
||||
.constraints = kCLayTiled, .n_constraints = NELEM(kCLayTiled),
|
||||
.launch = t_launch, .layout = t_lay_layout },
|
||||
{ .name = "t_lay_plain", .op = "t_lay", .family = "gemm",
|
||||
.computes = "nothing; a registry row", .shape = "M <= 4096", .dtypes = "as stored",
|
||||
.domain = RAD_DOMAIN_DEVICE, .priority = 10,
|
||||
.constraints = kCLayPlain, .n_constraints = NELEM(kCLayPlain), .launch = t_launch },
|
||||
{ .name = "t_lay_host", .op = "t_lay", .family = "gemm",
|
||||
.computes = "nothing; a registry row", .shape = "any", .dtypes = "as stored",
|
||||
.domain = RAD_DOMAIN_HOST, .priority = 10, .launch = t_launch },
|
||||
|
||||
{ .name = "t_join_tiled", .op = "t_join", .family = "gemm",
|
||||
.computes = "nothing; a registry row", .shape = "M <= 16", .dtypes = "fp8 + scale",
|
||||
.domain = RAD_DOMAIN_DEVICE, .priority = 20,
|
||||
.constraints = kCLayTiled, .n_constraints = NELEM(kCLayTiled),
|
||||
.launch = t_launch, .layout = t_lay_layout },
|
||||
{ .name = "t_join_host", .op = "t_join", .family = "gemm",
|
||||
.computes = "nothing; a registry row", .shape = "any", .dtypes = "planes joined",
|
||||
.domain = RAD_DOMAIN_HOST, .priority = 10, .launch = t_launch,
|
||||
.layout = t_join_host_layout },
|
||||
|
||||
{ .name = "t_cap_any", .op = "t_cap", .family = "norm",
|
||||
.computes = "nothing; a registry row", .shape = "any", .dtypes = "any",
|
||||
.domain = RAD_DOMAIN_DEVICE, .priority = 10, .launch = t_launch },
|
||||
};
|
||||
|
||||
static const RadPluginInfo kInfo = {
|
||||
RAD_PLUGIN_KERNEL, "radtest_extra", "0.1",
|
||||
"non-interval ranged constraints, a cross-axis tune test, layout hooks, a capacity", "host",
|
||||
};
|
||||
|
||||
/* ================================================================== radtest_badtune_* */
|
||||
/* A tunable axis the loader must refuse: a default that is not one of its values
|
||||
* (RADTEST_BADTUNE=1), or one axis declared twice (2). */
|
||||
#elif defined(RADTEST_BADTUNE)
|
||||
|
||||
static const RadOpSchema kSchemas[] = {
|
||||
{ "t_gemm", kPGemm, NELEM(kPGemm), kOpdGemm, NELEM(kOpdGemm), "never registered" },
|
||||
};
|
||||
#if RADTEST_BADTUNE == 1
|
||||
static const RadTunable kTBad[] = {
|
||||
{ "bn", kBnValues, NELEM(kBnValues), 96, "a default the axis does not offer" },
|
||||
};
|
||||
#else
|
||||
static const RadTunable kTBad[] = {
|
||||
{ "bn", kBnValues, NELEM(kBnValues), 64, "the axis" },
|
||||
{ "bn", kBnValues, NELEM(kBnValues), 128, "the same axis again" },
|
||||
};
|
||||
#endif
|
||||
static const RadKernelInfo kKernels[] = {
|
||||
{ .name = "t_badtune_gemm", .op = "t_gemm", .family = "gemm",
|
||||
.computes = "nothing; a registry row", .shape = "any", .dtypes = "any",
|
||||
.domain = RAD_DOMAIN_DEVICE, .priority = 10,
|
||||
.tunables = kTBad, .n_tunables = NELEM(kTBad), .launch = t_launch },
|
||||
};
|
||||
static const RadPluginInfo kInfo = {
|
||||
RAD_PLUGIN_KERNEL, "radtest_badtune", "0.1", "a tunable axis the loader refuses", "host",
|
||||
};
|
||||
|
||||
/* ================================================================== radtest_decline */
|
||||
#elif defined(RADTEST_DECLINE)
|
||||
|
||||
static const RadOpSchema kSchemas[] = {
|
||||
{ "t_gemm", kPGemm, NELEM(kPGemm), kOpdGemm, NELEM(kOpdGemm), "never registered" },
|
||||
};
|
||||
static const RadKernelInfo kKernels[] = {
|
||||
{ .name = "t_decline_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_decline", "0.1", "declines this machine at open", "host",
|
||||
};
|
||||
|
||||
/* ================================================================== radtest_over */
|
||||
#elif defined(RADTEST_OVER)
|
||||
|
||||
@@ -384,14 +566,26 @@ static const RadPluginInfo kInfo = {
|
||||
* 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",
|
||||
/* RADTEST_ARCHQ plugins are one family at several quantisations, each named, with its
|
||||
* quantisation, by -D. */
|
||||
#if defined(RADTEST_ARCHQ)
|
||||
#define RADTEST_ARCH_NAME RADTEST_ARCHQ_NAME
|
||||
#define RADTEST_ARCH_ID "radtest.q"
|
||||
#define RADTEST_ARCH_QUANT RADTEST_ARCHQ_QUANT
|
||||
#elif defined(RADTEST_ARCH)
|
||||
#define RADTEST_ARCH_NAME "radtest_arch"
|
||||
#else
|
||||
"radtest_arch2",
|
||||
#define RADTEST_ARCH_NAME "radtest_arch2"
|
||||
#endif
|
||||
"0.1", "claims architecture id 'radtest.v1'", "host",
|
||||
#ifndef RADTEST_ARCH_ID
|
||||
#define RADTEST_ARCH_ID "radtest.v1"
|
||||
#endif
|
||||
#ifndef RADTEST_ARCH_QUANT
|
||||
#define RADTEST_ARCH_QUANT ""
|
||||
#endif
|
||||
|
||||
static const RadPluginInfo kInfo = {
|
||||
RAD_PLUGIN_ARCH, RADTEST_ARCH_NAME, "0.1", "claims an architecture id", "host",
|
||||
};
|
||||
|
||||
/* ================================================================== radtest_badabi */
|
||||
@@ -426,10 +620,9 @@ uint32_t rad_plugin_abi_version(void) { return RAD_ABI_VERSION; }
|
||||
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 ""; }
|
||||
const char* rad_arch_id(void) { return RADTEST_ARCH_ID; }
|
||||
/* The other half of the selection key (spec §2.4); "" is an unquantised container. */
|
||||
const char* rad_arch_quant(void) { return RADTEST_ARCH_QUANT; }
|
||||
/* 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) {
|
||||
|
||||
Reference in new issue
Block a user