radiance 1.7.0

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

No files matched your search

+251 -355
View File
@@ -1,7 +1,6 @@
/* rad_abi.h -- the plugin ABI. This file and rad_types.h are the whole contract between the
* engine and an .so it loads. Everything is C: C++ across an .so boundary is a standing
* invitation to a mismatch that manifests as corruption three frames later, and this boundary is
* exactly where a user is expected to substitute their own build. See spec.md §2.
/* rad_abi.h -- the plugin ABI. This file and rad_types.h are the contract between the engine and
* an .so it loads. The interface is plain C: C++ across an .so boundary invites ABI mismatches,
* and this is the boundary where users substitute their own builds. See spec.md §2.
*/
#ifndef RAD_ABI_H
#define RAD_ABI_H
@@ -13,27 +12,26 @@
extern "C" {
#endif
/* Bumped whenever anything a plugin compiles against changes shape -- this header, rad_types.h,
/* Bumped whenever anything a plugin compiles against changes shape: this header, rad_types.h,
* rad_builder.h, rad_runtime.h, rad_device.h, rad_encoding.h, rad_quant.h or rad_sample.h. Every
* kind of plugin reports it. A plugin that does not report exactly this is refused at load, by
* name, with both versions printed. An OPTIONAL export added beside the existing ones
* (rad_plugin_reference, say) is not a change of shape: a plugin without it is read as answering
* the default. */
#define RAD_ABI_VERSION 16u
* kind of plugin reports it, and a plugin that does not report exactly this version is refused at
* load with both versions printed. A new optional export (e.g. rad_plugin_reference) is not a
* change of shape: a plugin without it gets the default. */
#define RAD_ABI_VERSION 17u
/* ================================================================== plugin identity */
/* RAD_PLUGIN_QUANT is a quantiser plugin: rad_quant.h is its whole contract. */
/* One value per plugin, not flags (QUANT is 3). RAD_PLUGIN_QUANT is a quantiser plugin:
* rad_quant.h is its whole contract. */
enum { RAD_PLUGIN_KERNEL = 1, RAD_PLUGIN_ARCH = 2, RAD_PLUGIN_QUANT = 3 };
typedef struct RadPluginInfo {
uint32_t kind; /* RAD_PLUGIN_KERNEL | RAD_PLUGIN_ARCH | RAD_PLUGIN_QUANT */
uint32_t kind; /* one of RAD_PLUGIN_KERNEL, _ARCH, _QUANT */
const char* name; /* "libr4d", "libref", "qwen3_dense_bf16" */
const char* version;
const char* description;
/* The devices this build of the plugin can run on, as the backend spells an architecture in
* RadDeviceProps::arch. "host" for a library of CPU kernels, which run anywhere; "" for a
* plugin that claims nothing. Several architectures may be listed, separated by spaces or
* commas, for a binary built to cover more than one. */
/* The devices this build can run on, spelled as RadDeviceProps::arch. "host" for a library of
* CPU kernels, which run anywhere; "" for a plugin that claims nothing. A binary built for
* several architectures lists them separated by spaces or commas. */
const char* build_target;
} RadPluginInfo;
@@ -43,8 +41,8 @@ const RadPluginInfo* rad_plugin_info(void);
/* ================================================================== execution domain */
/* A CPU kernel is an ordinary kernel with domain RAD_DOMAIN_HOST, resolved through the same
* hierarchy and the same constraints. Declare resolves both domains where both exist, so the
* core can change execution site at runtime without re-resolving -- spec §5.1. */
* hierarchy and constraints. Declare resolves both domains where both exist, so the core can
* change execution site at runtime without re-resolving (spec §2.1). */
enum { RAD_DOMAIN_DEVICE = 0, RAD_DOMAIN_HOST = 1, RAD_N_DOMAINS = 2 };
/* ================================================================== kernel arguments */
@@ -60,9 +58,8 @@ typedef struct RadArgs {
int world_size;
} RadArgs;
/* Read a parameter by key. Definitions, not declarations: a plugin links the ABI headers and
* nothing of the engine's, so a function declared here and defined in the core would be
* unlinkable from the plugins that are its only callers. See the note in rad_types.h. */
/* Read a parameter by key. Inline definitions, because a plugin links only the ABI headers and
* nothing of the engine's. See the note in rad_types.h. */
static inline int rad_args_geti(const RadArgs* a, const char* key, long long* out) {
if (!a || !key) return 0;
for (int i = 0; i < a->n_p; ++i)
@@ -82,95 +79,44 @@ static inline const char* rad_args_gets(const RadArgs* a, const char* key) {
}
/* ================================================================== kernel hooks */
/* init/fini exist because 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.
/* init/fini hold per-instance state that is set up once rather than per launch: libr4d's
* all-reduce exchanges peer signal buffers and IPC handles across ranks before the first call,
* and a kernel that JITs or loads a config table does it here, off the hot path.
*
* init is called once per RESOLVED INSTANCE (one op, one band, one domain), after selection and
* before load, with the frozen geometry. It returns an opaque pointer handed back in
* RadArgs.instance, or null. A negative status aborts startup. */
* init is called once per resolved instance (one op, one band, one domain), after selection and
* before load, with the frozen geometry. The pointer it returns (or null) is handed back in
* RadArgs.instance. A negative status aborts startup. */
typedef int (*RadInitFn) (const RadParam* p, int n_p, int rank, int world_size,
void** out_instance);
typedef void (*RadFiniFn) (void* instance);
/* The launch. Must not allocate and must not synchronise. Returns RAD_OK or negative; a negative
* return aborts the step and fails the requests in it, naming the kernel and the geometry. A launch
* return aborts the step and fails its requests, naming the kernel and the geometry. A launch
* handed `link_gate` may return RAD_LINK_ENDED instead of RAD_OK (rad_kernel_collective). */
typedef int (*RadLaunchFn) (const RadArgs* a, RadStream stream);
/* ================================================================== the described launch */
/* A KERNEL THAT DESCRIBES ITS LAUNCH INSTEAD OF PERFORMING IT, so the runtime can turn one
* description into either a dispatch or a graph node update.
*
* WHY THIS EXISTS. The engine re-issues a fixed op sequence every step: the topology is identical
* from step to step and only a few of the dispatches carry an operand that moved. The cost of
* launching a graph is roughly flat in the number of nodes, while submitting the same dispatches
* one at a time is linear in it, so replaying such a sequence as a graph is cheaper. What a
* `launch` hook cannot support is the UPDATE: it performs the dispatch itself, marshalling its own
* arguments, so nothing above it knows which argument slot holds which operand -- and a node update
* needs exactly that slot. `describe` reports the dispatch instead of performing it.
*
* IT IS OPTIONAL. `launch` remains the required entry point and every kernel that only implements
* it keeps working unchanged -- it simply never becomes a graph node, and a sequence containing
* one is submitted the ordinary way. Implement `describe` for a kernel that is issued repeatedly
* with a stable shape; there is nothing to gain on one that runs once.
*
* THE TRAP, AND THE ONE WAY TO AVOID IT. `launch` and `describe` must dispatch the SAME kernel
* with the SAME arguments, and nothing can check that for you: a divergence is not a crash, it is
* a wrong number produced only on the graph path, only after a capture, and it will read as a
* numerics bug anywhere but here. Do NOT write the two bodies twice. Write the shape arithmetic
* once and let it emit into a sink that is either a stream or a descriptor -- libr4d does this
* with one macro, and an out-of-tree plugin should do the same.
*
* ALLOCATION-FREE, like `launch`. The runtime owns the RadLaunchDesc storage and keeps it alive
* for as long as the node exists, so the shim writes its argument VALUES into `blob` and points
* `params[i]` at them. Pointing `params[i]` at anything else is legal only if that storage
* outlives the graph -- a string literal or the instance state does, a local does not. */
/* Fill `out[0..cap)` with the dispatches this call WOULD perform and write how many to `n_out`.
* Most kernels emit one; a split-K kernel and its finisher emit two. Returns RAD_E_FULL without
* writing anything if `cap` is too small, so the runtime can retry with a bigger array; returns
* RAD_OK having written `*n_out` otherwise. Must not allocate, must not synchronise and must not
* touch the device -- it is called at capture time, off the step path, and again whenever the
* runtime needs to know whether an argument moved.
*
* IT DESCRIBES A KERNEL DISPATCH AND ONLY THAT. An op whose work is a memory copy -- libr4d's
* `cast` is a hipMemcpy2DAsync, not a launch -- has nothing to put in a RadLaunchDesc and should
* leave `describe` null. A graph can hold copy nodes, but expressing one would need a second
* descriptor shape, and the ops that want it are the ops a graph saves least on.
*
* IT TAKES THE STREAM, because some launches depend on which one they are going onto: libr4d's
* split-K GEMM takes its arrival counter from a per-stream pool, so a description made without
* the stream would name a different counter than the launch would have used -- a divergence of
* exactly the kind the paragraph above says nothing can check for you. The runtime passes the
* stream the dispatch will actually run on, which for a graph node is the stream the graph is
* launched on. */
typedef int (*RadDescribeFn)(const RadArgs* a, RadStream s, RadLaunchDesc* out,
int cap, int* n_out);
/* Bytes of scratch one launch of this shape needs. Null means none. Called at declare with the
* band's upper bound, so the arena is sized for the worst step. */
typedef int64_t (*RadScratchFn)(const RadArgs* a);
/* ================================================================== weight layout
*
* WHAT A KERNEL STORES FOR A WEIGHT, GIVEN WHAT THE WEIGHT IS. spec.md §4.1, §4.3.
* What a kernel stores for a weight, given the weight's encoding. spec.md §4.1, §4.3.
*
* A container holds each weight's ENCODING -- its codes, scales and zero points as canonical planes
* (rad_encoding.h) -- and nothing shaped for a kernel. The kernel that reads a weight says here
* what it wants instead, and the loader turns one into the other when the model loads. Lossless,
* always: a relayout moves bits and derives nothing a reader of the planes could not derive -- a
* fragment order, a scale repeated into a row's tail, a reference exponent that is a row's
* maximum. Choosing numbers is a quantiser's job (rad_quant.h); a kernel that did it here would
* make the served numbers depend on which library loaded the container. So a kernel library may
* change every layout it has and no container is converted again. */
* A container holds each weight's encoding (codes, scales and zero points as canonical planes,
* rad_encoding.h) and nothing shaped for a kernel. The kernel that reads a weight describes the
* form it wants here, and the loader converts when the model loads. The conversion is lossless: a
* relayout moves bits and derives only what a reader of the planes could derive (a fragment order,
* a scale repeated into a row's tail, a reference exponent that is a row's maximum). Choosing
* numbers is the quantiser's job (rad_quant.h); a kernel doing it here would make the served
* numbers depend on which library loaded the container. So a kernel library may change any layout
* without containers being converted again. */
typedef struct RadLayout {
const char* tag; /* stable name of the arrangement, for messages and for checking
* that every kernel reading one weight wants the same bytes */
uint32_t dtype; /* the stored dtype, possibly a plugin-private one */
uint32_t rank;
int64_t shape[RAD_MAX_RANK]; /* the STORED shape, which may differ from the logical one */
int64_t shape[RAD_MAX_RANK]; /* the stored shape, which may differ from the logical one */
int64_t align; /* byte alignment the stored base must satisfy */
int64_t bytes; /* total, including any padding the layout implies */
} RadLayout;
@@ -178,93 +124,103 @@ typedef struct RadLayout {
/* Describe what this kernel stores for operand `operand` of the given geometry.
*
* `enc` is the weight's encoding and `sel[i]` the index into `enc->plane` of planes[i], the planes
* this operand takes, in the order the declaration named them (RadWeightDecl::planes). Each plane
* is THIS RANK'S SLICE, dense: rank 2, [rows, cols] in the plane's own elements, every row starting
* on a byte and rad_dtype_bytes(dtype, cols) long. Here the planes carry their geometry and a null
* `data`.
* this operand takes, in RadWeightDecl::planes order. Each plane is this rank's slice, dense: rank
* 2, [rows, cols] in the plane's own elements, every row starting on a byte and
* rad_dtype_bytes(dtype, cols) long. Here the planes carry their geometry and a null `data`.
*
* RAD_OK `out` describes the stored form, and `relayout` will produce it.
* RAD_E_UNSUPPORTED stored as it is: the one selected plane, its bytes unchanged -- what most
* weights are, and what a kernel with no hook at all gets. Only such a weight
* can be read where it lies in the container (the file and mapped tiers).
* RAD_E_DTYPE THE KERNEL DOES NOT READ THIS ENCODING -- an fp8 GEMM handed int4, a
* rotated weight to a kernel that does not rotate its activation. A
* declare-time error that names the weight, the encoding and the kernel.
* RAD_E_SHAPE the planes selected, or their extents, are not what the kernel reads. */
* RAD_E_UNSUPPORTED stored as is: the one selected plane, bytes unchanged. This is most
* weights, and what a kernel with no hook gets. Only such a weight can be
* read where it lies in the container (the file and mapped tiers).
* RAD_E_DTYPE the kernel does not read this encoding (an fp8 GEMM handed int4, a rotated
* weight to a kernel that does not rotate its activation). A declare-time
* error naming the weight, the encoding and the kernel.
* RAD_E_SHAPE the selected planes, or their extents, are not what the kernel reads. */
typedef int (*RadLayoutFn)(const RadParam* p, int n_p, int operand, const RadEncoding* enc,
const int* sel, const RadTensor* planes, int n_planes,
RadLayout* out);
/* Write the stored form `layout` described into `dst`, `dst_bytes` long, from the planes, which
* now carry their bytes. Pure host code, run by the loader -- on a pool, behind the read of the
* container, so it has to keep pace with the disk. */
* now carry their bytes. Pure host code, run by the loader on a pool behind the container read,
* so it has to keep pace with the disk. */
typedef int (*RadRelayoutFn)(const RadParam* p, int n_p, int operand, const RadEncoding* enc,
const int* sel, const RadTensor* planes, int n_planes, void* dst,
int64_t dst_bytes);
/* ...AND BACK: recover the planes from a stored form. `planes` arrive with their geometry and a
/* The inverse: recover the planes from a stored form. `planes` arrive with their geometry and a
* buffer each.
*
* WHY THE INVERSE HAS TO EXIST, stated from the failure it prevents. A tool that checks a kernel
* against the oracle holds the STORED bytes -- what the kernel reads -- and libref reads canonical
* planes. Handed the stored bytes it computes a correct answer to a permuted question, and the
* comparison is then between two unrelated tensors: a relative error of the size two independent
* draws give, reported against a kernel that is in fact correct. Only the plugin knows its
* permutation, so only the plugin can undo it. A kernel that relayouts and supplies no inverse is
* not a fault -- it is simply not checkable against a dense oracle, and the tools say so BY NAME
* rather than guessing. */
* A tool checking a kernel against the oracle holds the stored bytes, but libref reads canonical
* planes; given the stored bytes it answers a permuted question, and the comparison reports an
* error the size of two unrelated tensors against a correct kernel. Only the plugin knows its
* permutation. A kernel that relayouts without an inverse is not at fault, only not checkable
* against a dense oracle, and the tools report it by name. */
typedef int (*RadUnrelayoutFn)(const RadParam* p, int n_p, int operand, const RadEncoding* enc,
const int* sel, const void* src, int64_t src_bytes,
const RadTensor* planes, int n_planes);
/* ================================================================== operand description */
/* HOW BIG IS OPERAND i OF THIS OP, AND WHAT MAY BE IN IT.
/* How big operand i of an op is, and what values it may hold.
*
* An op's schema names its operands and their roles but not their extents, because the extents
* are not derivable from the parameters in general -- the run phase supplies them at issue. So a
* tool that wants to CALL an op cold, which is what a correctness check and a benchmark both do,
* has to size its buffers somehow. A hand-written table inside `tools/` cannot serve that: it
* covers only the ops someone wrote a row for and skips the rest, it cannot be extended without
* patching the engine, and it is a place where a tool knows something about an op.
* A schema names operands and their roles but not their extents, which are in general not
* derivable from the parameters (the run phase supplies them at issue). A tool that calls an op
* cold, such as a correctness check or a benchmark, asks the kernel through this hook instead of
* keeping its own table of ops.
*
* The kernel is the component that knows. This hook asks it.
*
* WHAT IS IN AN OPERAND MATTERS AS MUCH AS HOW BIG IT IS, and that is why this carries a fill
* domain rather than only a shape. A gated-delta-net `g` is an intra-chunk cumulative sum of
* log-decays: non-increasing and never positive, because every decay the scan forms is
* e^{g_i - g_j} with j <= i and that is <= 1 only because g is monotone. Feed it normals and the
* ORACLE overflows to 2e38 while the kernel does something else, and the comparison then measures
* the test rather than the kernel. The same is true of a sigmoid gate, of a lower-triangular
* factor, and of every index operand: a KV slot indexes n_blocks * block_size positions and a
* block-table entry indexes n_blocks, and drawing either from the wrong range tests the kernel's
* out-of-range handling and calls the result correctness. */
* The fill domain matters as much as the shape. A gated-delta-net `g` is an intra-chunk cumulative
* sum of log-decays: non-increasing and never positive, since each decay e^{g_i - g_j} with j <= i
* is <= 1 only because g is monotone. Fed normals, the oracle overflows to 2e38 and the comparison
* measures the test rather than the kernel. The same holds for a sigmoid gate, a lower-triangular
* factor and every index operand: a KV slot indexes n_blocks * block_size positions and a
* block-table entry n_blocks, and a draw outside that range tests out-of-range handling instead. */
enum {
RAD_FILL_NORMAL = 0, /* standard normals -- the default for a float operand */
RAD_FILL_SIGMOID = 1, /* (0, 1): a gate */
RAD_FILL_GATE_CUMSUM = 2, /* non-increasing and <= 0, reset every `fill_chunk` rows */
RAD_FILL_TRI_LOWER = 3, /* zero above the diagonal within a `fill_chunk` block */
RAD_FILL_INDEX = 4, /* integers; see idx_max / idx_const / the IDX flags */
/* UNIT L2 NORM ALONG THE LAST DIMENSION. The gated-delta-net key is normalised by the
* model's own qk_norm before it reaches the solve, and the solve inverts I + tril(beta k k^T,
* -1): drawn as unit normals over a 128-wide head that matrix has off-diagonals a hundred
* times too large, its inverse is enormous, and two implementations summing an
* ill-conditioned product in different orders disagree by however ill-conditioned it is. What
* that reports is the condition number of the TEST. Same correction as SIGMOID and
* GATE_CUMSUM above: put the operand in the domain the op is only ever handed. */
/* Unit L2 norm along the last dimension. The gated-delta-net key is normalised by qk_norm
* before the solve, which inverts I + tril(beta k k^T, -1). With unit normals over a 128-wide
* head the off-diagonals are ~100x too large, the matrix is ill-conditioned, and two
* summation orders disagree by its condition number. Like SIGMOID and GATE_CUMSUM, this puts
* the operand in the domain the op is actually given. */
RAD_FILL_UNIT_ROW = 5,
/* The samplers' `params` plane: [rows, 24] 32-bit words, each row a RadSampleParams
* (rad_sample.h) as a request sets it, its flags agreeing with its fields. Drawn as numbers,
* the integer fields and `flags` are bit patterns (a window is all or nothing, a mask row is
* never in range, each flag is a coin toss) and XTC's threshold is past any probability, so
* the mask and XTC stages do nothing and the others act on a random part of the rows.
* Row 0 switches every stage on; every other row switches each stage on or leaves it at its
* identity at random, and a minority is greedy. `fill_chunk` is the width of the op's history
* plane (0 when it has none: the window is then empty) and `idx_max` the row count of its
* bitmask plane (0 when it has none: `mask_row` is then -1). A tool that does not know the
* value draws normals. */
RAD_FILL_SAMPLE_PARAMS = 6,
};
enum {
/* An OPTIONAL operand this geometry does not pass. One entry per schema operand is still
* emitted -- that count is what catches a hook that has drifted from its schema -- so absence
* needs a spelling, and a null RadTensor.data is what the ABI already means by it. */
/* An optional operand this geometry does not pass. One entry per schema operand is still
* emitted, since that count catches a hook that drifted from its schema; a null
* RadTensor.data marks the absence. */
RAD_OPD_F_ABSENT = 1u << 0,
/* A SCATTER DESTINATION: no value may repeat. Two tokens drawn onto one slot make the store a
* race, and two implementations resolve it differently -- so the comparison would measure the
* scheduler. A read-side index (a gather row, a block-table entry) may repeat and does. */
/* A scatter destination: no value may repeat. Two tokens on one slot make the store a race
* that two implementations resolve differently. A read-side index (a gather row, a
* block-table entry) may repeat. */
RAD_OPD_F_IDX_UNIQUE = 1u << 1,
/* CUMULATIVE SEQUENCE LENGTHS, [0, ..., T]. Not a draw: it is the batch's shape. */
/* Cumulative sequence lengths, [0, ..., T]: the batch's shape, not a draw. */
RAD_OPD_F_IDX_CU = 1u << 2,
/* A routing histogram's offsets, [0, ..., idx_max - 1]: non-decreasing, first 0, last the row
* count, each bucket a run of random length (moe_scatter's `expert_offset`). A uniform draw is
* a malformed histogram that two correct implementations may read differently. Additive:
* RAD_ABI_VERSION does not move, and a tool that does not know the flag draws as before. */
RAD_OPD_F_IDX_PREFIX = 1u << 3,
/* A token history, [rows, width] ids in [0, idx_max): each row repeats itself as generated
* text does, drawing on a few ids spread over the range and copying runs of its own earlier
* tokens. A uniform draw over a vocabulary never repeats, so a frequency penalty never counts
* past one and DRY (which penalises the token that would extend a repeated suffix) never
* finds a repeat. Additive, as IDX_PREFIX: a tool that does not know the flag draws uniform
* ids. */
RAD_OPD_F_IDX_HISTORY = 1u << 4,
};
typedef struct RadOpdDesc {
@@ -273,14 +229,15 @@ typedef struct RadOpdDesc {
int64_t shape[RAD_MAX_RANK];
uint32_t fill; /* RAD_FILL_* */
int64_t fill_chunk; /* the reset width for GATE_CUMSUM and TRI_LOWER */
/* The reset width for GATE_CUMSUM and TRI_LOWER; the history plane's width for
* SAMPLE_PARAMS. */
int64_t fill_chunk;
/* RAD_FILL_INDEX only. `idx_max` is the EXCLUSIVE upper bound of the draw; 0 means "the
* leading extent of the previous operand", which is the common case and saves every gather
* from restating it. `idx_const` >= 0 makes every element that value rather than a draw --
* `seqused` is the one that needs it, because a random context length shorter than the query
* makes a causal attention read a prefix that does not exist, which both implementations
* would then agree about while neither computed what the model asks for. */
/* RAD_FILL_INDEX only, except that SAMPLE_PARAMS reads `idx_max` as its bitmask plane's row
* count. `idx_max` is the exclusive upper bound of the draw; 0 means the leading extent of the
* previous operand, the common case for a gather. `idx_const` >= 0 sets every element to that
* value instead of drawing. `seqused` needs it: a random context length shorter than the query
* makes causal attention read a prefix that does not exist. */
int64_t idx_max;
int64_t idx_const; /* -1 to draw */
@@ -288,95 +245,75 @@ typedef struct RadOpdDesc {
} RadOpdDesc;
/* Fill `out` for operand `operand` of this op at this geometry. `p`/`n_p` is the resolved
* parameter list, exactly as `launch` would receive it. Return RAD_OK, or RAD_E_UNSUPPORTED when
* this geometry does not carry what the description needs -- a caller SKIPS AND COUNTS that
* rather than guessing an extent, because a tool that invents one tests the kernel's bounds
* handling and calls the result correctness.
* parameter list, exactly as `launch` would receive it. Returns RAD_OK, or RAD_E_UNSUPPORTED when
* this geometry lacks what the description needs; a caller skips and counts that instead of
* guessing an extent.
*
* Pure host code, no device memory, no side effects: it is called before anything is allocated. */
typedef int (*RadShapeFn)(const RadParam* p, int n_p, int operand, RadOpdDesc* out);
/* ================================================================== tunable instantiation */
/* A KERNEL IS A FAMILY, NOT AN IMPLEMENTATION. Tile sizes, split counts, waves per block: which
* member of the family is fastest is a property of the shape and the machine, and the only way to
* know is to measure it on the machine (spec §15). A library declares the AXES here and the core
* takes the cross product.
/* A kernel is a family: tile sizes, split counts, waves per block. Which member is fastest
* depends on the shape and the machine and must be measured there (spec §15). A library declares
* the axes here and the core takes their cross product. Axes rather than a list of named
* combinations, because a hand-enumerated list has holes (a shape with 40 rows of work runs a
* 64-row tile), and because it keeps the tuning policy out of the launch adapter, where an
* out-of-tree author could not write it.
*
* AXES, NOT A LIST OF PRE-NAMED COMBINATIONS. Hand-enumerating the interesting points of a
* multi-axis space -- "wv1_sk8_mb3_npw4" and its twenty-odd siblings -- leaves HOLES, and a hole
* costs step time silently: a ladder that skips a value runs the next tile up, so a shape with
* forty rows of work gets a sixty-four-row tile. A cross product has no holes.
*
* It also keeps the tuning LAW out of the launch adapter, where it would be C++ -- ladders, caps,
* a hand-written picker -- that an out-of-tree author cannot write.
*
* THE CHOSEN VALUES ARRIVE AS ORDINARY PARAMETERS. There is no variant index: once the core has
* picked a point in the space it appends the choices to RadArgs::p, and the kernel reads `sk` with
* the same rad_args_geti() it reads `M` with. One way in, for a value the caller supplied and a
* value the tuner chose. */
* The chosen values arrive as ordinary parameters appended to RadArgs::p, with no variant index:
* the kernel reads `sk` with the same rad_args_geti() it reads `M` with. */
typedef struct RadTunable {
const char* key; /* the kernel's own name for the axis: "sk", "bm", "npw" */
const int64_t* values; /* legal values, ascending; the core tries exactly these */
int n_values;
/* WHAT RUNS WHEN THIS MACHINE HAS NO MEASUREMENT FOR THIS INSTANTIATION -- a fresh install, a
* shape nobody tuned, a cache from another card. There is no fallback beneath it, so it must
* be a value the kernel can actually launch: the loader CHECKS that it appears in `values`
* and refuses the plugin by name if it does not. */
/* The value used when this machine has no measurement for this instantiation (a fresh
* install, an untuned shape, a cache from another card). There is no fallback beneath it, so
* it must be launchable: the loader checks it appears in `values` and refuses the plugin by
* name if not. */
int64_t deflt;
const char* doc; /* what the axis does, for the tuner's report */
} RadTunable;
/* IS THIS COMBINATION LEGAL AT THIS GEOMETRY? Cross-axis rules live here rather than in the axis
* lists, because they are exactly what a product of independent lists cannot say: libr4d's skinny
* GEMM needs `wv * sk * 32` inside the block bound AND `K % (sk * unit) == 0`, and neither is a
* property of `sk` alone.
/* Whether a combination is legal at this geometry. Cross-axis rules live here because independent
* axis lists cannot express them: libr4d's skinny GEMM needs `wv * sk * 32` inside the block bound
* and `K % (sk * unit) == 0`.
*
* `p` is the resolved geometry, `choice` the candidate as key/value parameters. Pure host code,
* called before anything is allocated, once per candidate.
* called once per candidate before anything is allocated.
*
* Returns 1 for legal and 0 for SKIP -- which is not an error. A kernel may serve a subset of its
* own cross product, and the tuner reports a skipped candidate as skipped rather than as a
* failure. Null means every combination is legal. */
* Returns 1 for legal and 0 for skip, which is not an error: a kernel may serve a subset of its
* cross product, and the tuner reports the candidate as skipped. Null means every combination is
* legal. */
typedef int (*RadTuneValidFn)(const RadParam* p, int n_p, const RadParam* choice, int n_choice);
/* ================================================================== op schemas */
/* A parameter is supplied by the caller (REQUIRED), may be (OPTIONAL), or is supplied by the
* KERNEL (DERIVED).
/* A parameter is supplied by the caller (REQUIRED), may be supplied (OPTIONAL), or is supplied by
* the kernel (DERIVED).
*
* DERIVED exists because of a circularity that block_size makes concrete. Spec §7.2 says the
* paged block size comes from the resolved attention kernel and not from a core constant --
* libr4d is compiled for 16 and rejects anything else. But a constraint whose key the geometry
* does not carry does NOT hold (libr4d's rule, and the reason its two-shot all-reduce rows have
* to precede the one-shot ones), so a kernel constrained to block_size == 16 can never be
* selected by a query that omits block_size -- and the resolution the answer was to be read off
* never happens.
* DERIVED breaks a circularity. The paged block size comes from the resolved attention kernel, not
* a core constant (spec §7.2; libr4d is compiled for 16). But a constraint whose key the geometry
* does not carry does not hold (which is also why libr4d's two-shot all-reduce rows must precede
* the one-shot ones), so a kernel constrained to block_size == 16 could never be selected by a
* query that omits block_size.
*
* So: constraints on a DERIVED parameter are SKIPPED during matching, and once a kernel wins,
* its RAD_C_EQ value for that key is written into the resolved geometry. A caller that supplies
* one anyway pins it, and it matches normally -- which is how an operator forces a block size
* and gets a refusal by name rather than a silent substitution. A kernel with no EQ on a derived
* key leaves it unset, and rad_kv_block_size() reports that rather than returning zero. */
* So constraints on a DERIVED parameter are skipped during matching, and the winning kernel's
* RAD_C_EQ value for that key is written into the resolved geometry. A caller that supplies one
* pins it and it matches normally, so a forced block size is refused by name rather than silently
* substituted. A kernel with no EQ on a derived key leaves it unset, and rad_kv_block_size()
* reports that rather than returning zero. */
enum { RAD_OPTIONAL = 0, RAD_REQUIRED = 1, RAD_DERIVED = 2 };
/* WHAT A PARAMETER MEANS TO THE CORE, when the core has to act on one it did not invent.
*
* Almost none of them: a parameter is a key the plugin and the kernel agree on and the core
* carries it opaquely, which is the whole reason a third party can add an op. The exception is
* the SEQUENCE CHUNK. A linear-state scan tiles the token stream, its kernel is compiled for one
* tile length, and the SCHEDULER has to cut its steps on a multiple of that or a chunk straddles
* a sequence boundary -- so the core does need to find that one number in a geometry it otherwise
* does not read.
*
* The schema is where that number is named, and the alternative is worse: a core that found it by
* SPELLING would carry a list of likely keys ("chunk", "chunk_size", "state_chunk", ...) inside
* the scheduler, which makes the core the thing you edit to add a kernel that spells it
* differently. Declaring the role costs a field and keeps the core free of that vocabulary. */
/* RAD_PROLE_CAPACITY is a count the kernel is handed as a BOUND and never writes past its
* operands for: it launches, loops and writes by the extents of the tensors it is given. That is
* what lets the activation arena be declared again at a smaller step (RadBuildCtx::shape_probe) --
* the kernel keeps the geometry it was selected with, including the real declare's value here,
* while its buffers are the smaller step's -- so it is the KERNEL's claim to make, and a fixed
* parameter that differs between the two declares without it refuses the smaller size. */
/* What a parameter means to the core. The core carries almost every parameter opaquely, which is
* what lets a third party add an op. The exception is the sequence chunk: a linear-state scan is
* compiled for one tile length, and the scheduler must cut its steps on a multiple of it or a
* chunk straddles a sequence boundary. The schema names that role so the core does not have to
* find the parameter by guessing its spelling. */
/* RAD_PROLE_CAPACITY marks a count the kernel is handed as a bound and never writes past its
* operands for: it launches, loops and writes by the extents of the tensors it is given. That lets
* the activation arena be declared again at a smaller step (RadBuildCtx::shape_probe) while the
* kernel keeps the geometry it was selected with, including the real declare's value here. It is
* the kernel's claim to make; without it, a fixed parameter that differs between the two declares
* refuses the smaller size. */
enum { RAD_PROLE_NONE = 0, RAD_PROLE_SEQ_CHUNK = 1, RAD_PROLE_CAPACITY = 2 };
typedef struct RadParamSpec {
@@ -386,13 +323,12 @@ typedef struct RadParamSpec {
int role; /* RAD_PROLE_*; 0 for every parameter the core does not interpret */
} RadParamSpec;
/* Positional operand roles. The core needs to know which operands are weights (so issue can
* resolve a handle and wait on the mover) and which are written (so the buffer planner can
* compute liveness). It does not need to know anything else about them. */
/* RAD_OPD_WTAB is a weight operand whose issue names a RUN of weights rather than one -- a MoE
* layer's experts -- and the kernel is handed a device array of pointers. It is a role of its own
* and not a flag on RAD_OPD_WEIGHT so that a tool reading the schema knows the operand is not a
* plane it can describe with one shape: see RAD_WTAB in rad_runtime.h. */
/* Positional operand roles. The core needs to know only which operands are weights (issue resolves
* a handle and waits on the mover) and which are written (the buffer planner computes liveness). */
/* RAD_OPD_WTAB is a weight operand whose issue names a run of weights (a MoE layer's experts);
* the kernel is handed a device array of pointers. It is a separate role, not a flag on
* RAD_OPD_WEIGHT, so a tool reading the schema knows the operand is not one plane it can describe
* with one shape: see RAD_WTAB in rad_runtime.h. */
enum { RAD_OPD_IN = 0, RAD_OPD_OUT = 1, RAD_OPD_INOUT = 2, RAD_OPD_WEIGHT = 3,
RAD_OPD_WTAB = 4 };
@@ -412,46 +348,31 @@ typedef struct RadOpSchema {
/* ================================================================== declared fusions
*
* WHAT CHAIN OF CONVENTIONAL OPS DOES THIS KERNEL COMPUTE?
* Which chain of conventional ops a kernel computes.
*
* The obvious design is for a kernel library to advertise that "kernel A can be used to fuse B
* and C", and for the engine to apply that repeatedly until the graph converges. spec.md §2.3
* refuses the second half -- "a fusion rewriter is a compiler, and a compiler is the thing whose output nobody can
* predict" -- and the declare phase keeps nothing a rewriter could work on in any case: `Program`
* holds no operand edges. The Builder computes them, collapses each buffer's whole use-set to a
* `first_def`/`last_use` pair with reads and writes MERGED, and discards the rest when it returns.
* This is a declaration, not a rewriter. spec.md §2.3 rules out a fusion rewriter, and the
* declare phase keeps nothing one could work on: `Program` holds no operand edges, and the Builder
* collapses each buffer's use-set to a `first_def`/`last_use` pair with reads and writes merged.
* "Op A's output is op B's only input" is not recoverable from that, which is also why
* `--debug-graph` declines to print an edge it cannot prove.
* `--debug-graph` prints no edge it cannot prove. Fusion stays a selection: the architecture asks
* for the fused op and emits the sequence when nothing serves it (rad_op_resolved in
* rad_builder.h is the idiom for a banded or optional fusion).
*
* So this is a DECLARATION, not a rewriter. Fusion stays a selection: the architecture asks for
* the fused op and emits the sequence when nothing serves it (spec.md 2.3, and rad_op_resolved in
* rad_builder.h, which is the idiom an out-of-tree plugin needs for a banded or optional fusion).
* What the declaration adds is that the EQUIVALENCE becomes machine-readable instead of prose in a
* kernel row -- "byte-identical to the two ops it replaces" -- and prose cannot be checked. It
* buys three things:
* The declaration makes the equivalence machine-readable, which gives:
* - an oracle: a fused kernel with no libref counterpart is checked against its chain run on the
* same plugin's unfused rows, and the answer should be byte-identical;
* - an advisory in --debug-graph: these declared ops form a chain some kernel can run in one
* launch, and why it did not fire;
* - the per-library fusion-claim count in rad-kbench's report.
*
* AN ORACLE, which is the one that matters. A fused kernel with no libref counterpart can only
* be skipped by name, and such skips dominate what a coverage run reports on a model built out
* of fusions. A fused kernel that declares its chain can instead be checked against that chain
* run out of the SAME plugin's unfused rows -- which is precisely the claim the row makes, and
* a stronger test than a tolerance against ref, because the answer should be BYTE-IDENTICAL.
* It is a hook rather than a table because a step's geometry is not always derivable from the
* fused op's: `qk_norm_rope_gate` replaces an `rmsnorm` at M = T * n_head, a product that is not
* in its parameter list.
*
* AN ADVISORY in --debug-graph: these N declared ops are a chain some kernel says it can do in
* one launch, and here is why it did not fire.
*
* A COVERAGE METRIC, which spec.md:19 lists.
*
* WHY A HOOK AND NOT A TABLE. A step's geometry is not the fused op's geometry and is not always
* derivable by a caller: `qk_norm_rope_gate` replaces an `rmsnorm` at M = T * n_head, and nothing
* in the fused op's parameter list is that product. The kernel is the component that knows, which
* is the same argument RadShapeFn and RadLayoutFn already make.
*
* OPERAND WIRING. Every operand of every step is either an operand of the FUSED kernel or a
* TEMPORARY the chain passes between its own steps. A temporary needs no description here: it is
* sized and typed by the step's own `opd_shape`, which every kernel that wants to be checked this
* way already publishes. Note how often no temporary is needed at all -- the fp8 folds still WRITE
* their intermediate when `out_bf16` is passed, precisely so the fused and unfused forms leave the
* same buffers behind. */
* Operand wiring: every operand of every step is either an operand of the fused kernel or a
* temporary passed between steps. A temporary needs no description here; the step op's own
* `opd_shape` sizes and types it. Often none is needed: the fp8 folds still write their
* intermediate when `out_bf16` is passed, so the fused and unfused forms leave the same buffers. */
enum {
RAD_FUSE_NONE = -1, /* this step does not pass that optional operand */
};
@@ -465,12 +386,11 @@ enum { RAD_MAX_FUSE_OPD = 16, RAD_MAX_FUSE_PARAMS = 12, RAD_MAX_FUSE_TMP = 8 };
typedef struct RadFuseStep {
const char* op; /* a conventional op name -- see docs/OPS.md */
RadParam p[RAD_MAX_FUSE_PARAMS]; /* this STEP's geometry, not the fused one's */
RadParam p[RAD_MAX_FUSE_PARAMS]; /* this step's geometry, not the fused one's */
int n_p;
/* One entry per operand of `op`, in its schema's order: an operand index of the fused kernel,
* RAD_FUSE_TMP(t), or RAD_FUSE_NONE. The count is checked against the step op's schema, so a
* hook that drifts from the vocabulary is a diagnosable error rather than a silent misfire --
* the same rule RadShapeFn's operand count follows, and for the same reason. */
* hook that drifts from the vocabulary is a diagnosable error (as with RadShapeFn). */
int16_t from[RAD_MAX_FUSE_OPD];
int n_from;
} RadFuseStep;
@@ -478,34 +398,22 @@ typedef struct RadFuseStep {
/* Describe step `step` of the chain this kernel replaces, for this geometry and variant.
*
* RAD_OK `out` is filled; ask again with step + 1.
* RAD_E_NOTFOUND `step` is past the end. This is how a caller learns the chain's LENGTH,
* and it is why there is no count beside the hook: the chain may differ with
* the geometry (an `rmsnorm_quant_fp8` with a residual replaces `rmsnorm_add`
* and without one replaces `rmsnorm`).
* RAD_E_UNSUPPORTED this geometry or variant has no unfused equivalent in the vocabulary. An
* honest answer, and the right one wherever a fusion computes something the
* conventional ops cannot express between them.
* RAD_E_NOTFOUND `step` is past the end. This is how a caller learns the chain's length,
* which may differ with the geometry (an `rmsnorm_quant_fp8` with a residual
* replaces `rmsnorm_add`, without one `rmsnorm`).
* RAD_E_UNSUPPORTED this geometry or variant has no unfused equivalent in the vocabulary.
*
* A chain must be EXACT, not approximate. A kernel that is merely close to the sequence it names
* should publish no hook at all: the whole value of the declaration is that a caller may
* substitute one for the other and compare the bytes. */
/* WHICH OPTIONAL OPERANDS THIS CALL PASSES, one bit per operand of the FUSED op, bit i set when
* operand i is present.
* A chain must be exact. A kernel that is merely close to a sequence publishes no hook, because
* callers substitute one for the other and compare the bytes. */
/* `present` has bit i set when operand i of the fused op is passed. The chain can depend on an
* operand, not only on a parameter: `rmsnorm_quant_fp8` replaces `add` -> `rmsnorm` ->
* `quant_act_fp8` given a residual and `rmsnorm` -> `quant_act_fp8` without. Inferring presence
* from the plugin's own RadShapeFn is right for a checker calling the kernel cold but wrong for a
* caller holding a real issue, such as the graph dump. `RAD_FUSE_NONE` cannot express it, since
* the operands that vary are the step's required ones.
*
* THIS IS NOT DECORATION: without it the chain is not answerable at all.
* `rmsnorm_quant_fp8` replaces `add` -> `rmsnorm` -> `quant_act_fp8` when it is given a residual
* and `rmsnorm` -> `quant_act_fp8` when it is not: THE CHAIN LENGTH ITSELF depends on an operand,
* not on a parameter. Without this the hook has to infer presence, and the only honest inference
* available is "whatever this plugin's own RadShapeFn publishes" -- which is right for a checker
* calling the kernel cold, since that is where its buffers came from, and WRONG for a caller
* holding a real issue, which is what the graph dump has. A fold with no residual would be
* described as three steps and the advisory would be a lie.
*
* Nor could `RAD_FUSE_NONE` express it: the operands that vary are the step's REQUIRED ones.
*
* RAD_FUSE_PRESENT_ALL is what a caller passes when it does not know, and it means exactly "answer
* for every operand your description says exists". That is a contract rather than a coupling: the
* hook may then assume its own RadShapeFn, and a caller that knows better says so. */
* RAD_FUSE_PRESENT_ALL means the caller does not know: answer for every operand your RadShapeFn
* says exists. */
#define RAD_FUSE_PRESENT_ALL ((uint64_t)~0ull)
#define RAD_FUSE_HAS(mask, i) (((mask) >> (i)) & 1ull)
@@ -522,13 +430,13 @@ typedef struct RadKernelInfo {
const char* dtypes;
int domain; /* RAD_DOMAIN_DEVICE | RAD_DOMAIN_HOST */
int priority; /* higher wins WITHIN THIS PLUGIN; ties break on declaration order */
int priority; /* higher wins within this plugin; ties break on declaration order */
const RadConstraint* constraints; int n_constraints;
/* The axes of this kernel's instantiation space, and the cross-axis legality test. Null/0
* means one implementation with nothing to tune, which is the common case and costs nothing:
* the core appends no choices and the kernel reads no tuned key. See RadTunable. */
/* The axes of this kernel's instantiation space and the cross-axis legality test. Null/0
* means one implementation with nothing to tune (the common case): the core appends no
* choices and the kernel reads no tuned key. See RadTunable. */
const RadTunable* tunables; int n_tunables;
RadTuneValidFn tune_valid;
@@ -538,37 +446,30 @@ typedef struct RadKernelInfo {
RadScratchFn scratch;
RadLayoutFn layout;
RadRelayoutFn relayout;
/* How to size and fill each operand, for a tool that calls this kernel cold. Null means this
* kernel cannot describe itself and every tool that needs a buffer for it skips it BY NAME
* rather than guessing. libref supplies it for the whole conventional vocabulary, so an
* op that stays inside docs/OPS.md is describable even when the kernel under test is not. */
/* How to size and fill each operand, for a tool that calls this kernel cold. Null means tools
* that need a buffer for it skip it by name. libref supplies it for the whole conventional
* vocabulary, so an op in docs/OPS.md is describable even when the kernel under test is not. */
RadShapeFn opd_shape;
/* The inverse of `relayout`, for a tool holding the stored bytes rather than the planes.
* Null means this kernel's stored form cannot be read back, and a dense oracle therefore has
* nothing to compare against -- which is a skip, named, and not a failure. */
/* The inverse of `relayout`, for a tool holding the stored bytes rather than the planes. Null
* means the stored form cannot be read back, so a dense oracle has nothing to compare
* against: a named skip, not a failure. */
RadUnrelayoutFn unrelayout;
/* The chain of conventional ops this kernel computes in one launch, or null for a kernel that
* is not a fusion. Non-null is also the fusion-coverage metric's numerator: it is a kernel
* saying "I stand in for these, and you may check me against them". */
RadFuseFn replaces;
/* Optional. The same dispatch, described rather than performed, so a repeatedly issued
* sequence can be replayed as a graph. Null means this kernel is always submitted
* individually, which is correct and merely slower. See RadDescribeFn for the one trap.
/* The chain of conventional ops this kernel computes in one launch, or null if it is not a
* fusion. Non-null also counts in rad-kbench's fusion-claim column.
*
* LAST IN THE STRUCT ON PURPOSE. Every kernel table in this tree is a POSITIONAL aggregate
* initialiser -- `{..., nullptr, nullptr, r4d_rad_embed_lookup, nullptr, ...}` -- so a field
* inserted anywhere else silently shifts every initialiser after it, and `nullptr` converts
* to any function pointer type, so part of that shift would compile. Append here. */
RadDescribeFn describe;
* Keep this field last. Kernel tables are positional aggregate initialisers
* (`{..., nullptr, nullptr, r4d_rad_embed_lookup, nullptr, ...}`), so a field inserted
* anywhere else shifts every later initialiser, and since `nullptr` converts to any function
* pointer type, part of that shift would still compile. Append new fields after this one. */
RadFuseFn replaces;
} RadKernelInfo;
/* ================================================================== kernel plugin exports */
/* Every kernel plugin exports the whole set. The schemas come first: the first plugin in
* hierarchy order to declare an op fixes its schema, and a later plugin declaring the same op
* name with a different schema is 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 (spec §2.3). */
/* Every kernel plugin exports the whole set. The first plugin in hierarchy order to declare an op
* fixes its schema; a later plugin declaring the same op name with a different schema is refused
* at load with both plugins named. Arguments are positional, so disagreeing schemas would make
* the same call mean different things depending on which plugin won selection, silently
* (spec §2.3). */
int rad_kernel_schema_count(void);
const RadOpSchema* rad_kernel_schema_at(int i);
int rad_kernel_count(void);
@@ -577,59 +478,54 @@ const RadKernelInfo* rad_kernel_at(int i);
/* Optional. Called once after the plugin is loaded and before any selection, and once at
* shutdown. A plugin with no global state need not export them.
*
* THE SYMBOL NAMES ARE `rad_plugin_open` and `rad_plugin_close`. The types are named here so a
* plugin can declare them with the right signature; the loader resolves them by those exact
* names, and a plugin that spells them differently is silently never initialised.
* The symbol names are `rad_plugin_open` and `rad_plugin_close`; the types exist so a plugin can
* declare them with the right signature. The loader resolves those exact names, so a plugin that
* spells them differently is silently never initialised.
*
* `rad_plugin_open` answering RAD_E_UNSUPPORTED DECLINES this machine: the plugin is unloaded and
* the rest of the installation carries on, which is how one installation ships libraries for
* several cards. Any other negative status refuses the plugin as an error. A kernel library does
* not need to decline a card its device code was not built for -- the loader reads that out of
* the code objects it carries and leaves its device kernels out on its own. */
* `rad_plugin_open` returning RAD_E_UNSUPPORTED declines this machine: the plugin is unloaded and
* the rest of the installation carries on, so one installation can ship libraries for several
* cards. Any other negative status refuses the plugin as an error. A kernel library need not
* decline a card its device code was not built for: the loader reads that from the code objects
* and leaves those device kernels out itself. */
typedef int (*RadPluginOpenFn) (void);
typedef void (*RadPluginCloseFn)(void);
/* Optional, and a promise about kernel `i` of rad_kernel_at: nonzero means every launch of it
* reads and writes no memory but its operands and the scratch it was handed -- no allocation it
* keeps for itself, no counter it keeps between launches -- so two launches may run at the same
* time on one device whenever their operands and scratch do not overlap. The engine then lets a
* launch start before the independent ones in front of it on its queue have finished. A plugin
* that does not export the symbol, or answers 0, has every launch ordered behind everything
* before it, which is always correct. The symbol name is `rad_kernel_concurrent`. */
/* Optional promise about kernel `i` of rad_kernel_at: nonzero means every launch reads and writes
* only its operands and the scratch it was handed (no allocation it keeps, no counter kept between
* launches), so two launches may run at once on one device when their operands and scratch do not
* overlap. The engine then lets such a launch start before independent earlier launches on its
* queue finish. Without the symbol, or with 0, every launch is ordered behind everything before
* it, which is always correct. Symbol name: `rad_kernel_concurrent`. */
typedef int (*RadKernelConcurrentFn)(int i);
/* Optional, and a promise about kernel `i` of rad_kernel_at: nonzero means it is a COLLECTIVE --
* its launches exchange data with the other ranks' cards, so the interconnect carries their bytes
* for as long as they run and the step waits on it. The engine then keeps its own bulk traffic on
* the same links (weights it streams onto the card while the card computes) out of their way for
* that time. A plugin that does not export the symbol, or answers 0, has only the conventional
* `all_reduce` op treated as one. The symbol name is `rad_kernel_collective`.
/* Optional promise about kernel `i` of rad_kernel_at: nonzero means it is a collective. Its
* launches exchange data with the other ranks' cards, so the interconnect carries their bytes
* while they run and the step waits on it. The engine keeps its own bulk traffic on those links
* (weights streamed to the card during compute) out of the way for that time. Without the symbol,
* or with 0, only the conventional `all_reduce` op is treated as a collective. Symbol name:
* `rad_kernel_collective`.
*
* 2 promises more: every launch of the kernel ends that time itself, as soon as the last byte the
* other ranks send this card for it has landed -- a kernel that reduces after the exchange has the
* link to spare for the rest of its run. The engine then hands each launch it holds the link for
* the parameter `link_gate`, the address of a 64-bit word in memory the kernel reaches at system
* scope; a launch without it holds nothing and has nothing to end. The kernel reads the word on
* the device as it starts -- not the host in the launch call, where the hold has not taken effect
* yet -- and, once those bytes have landed, takes one off it with a system-scope atomic if it was
* odd; an even word it leaves alone. A launch that did so returns RAD_LINK_ENDED; any other
* success is RAD_OK, and the engine then ends the hold behind the launch, so a path that does not
* know the word is always safe. */
* 2 promises more: each launch ends the link hold itself as soon as the last byte the other ranks
* send this card for it has landed, so a kernel that reduces after the exchange frees the link for
* the rest of its run. The engine then passes each launch it holds the link for the parameter
* `link_gate`, the address of a 64-bit word the kernel reaches at system scope; a launch without
* it holds nothing. The kernel reads the word on the device as it starts (not on the host in the
* launch call, where the hold is not yet in effect) and, once those bytes have landed, decrements
* it with a system-scope atomic if it was odd; an even word it leaves alone. A launch that
* decremented returns RAD_LINK_ENDED. Any other success returns RAD_OK and the engine ends the
* hold behind the launch, so a path that ignores the word is always safe. */
typedef int (*RadKernelCollectiveFn)(int i);
#define RAD_LINK_ENDED 1
/* Optional: nonzero declares this kernel library a REFERENCE implementation -- written to be
* plainly correct rather than fast. Three things follow, for any library that says so and for no
* other, whatever it is called:
/* Optional: nonzero declares this kernel library a reference implementation, written to be
* plainly correct rather than fast. For any library that says so, whatever its name:
* - the loader ranks it below every unnamed kernel library, because a reference matches every
* op it declares and would otherwise answer for them ahead of the library serving the card
* (naming it in --kernels still puts it where it is named, and a --kernels list that does
* not name it leaves it out);
* op it declares and would otherwise win over the library serving the card (naming it in
* --kernels still places it where named, and a --kernels list that omits it leaves it out);
* - the engine refuses to serve a model with an op only a reference library implements, unless
* told to with --debug-accept-reference-kernels;
* given --debug-accept-reference-kernels;
* - rad-kbench checks every other library against it.
* A plugin that does not export the symbol, or answers 0, is an ordinary library. The symbol name
* is `rad_plugin_reference`. */
* Without the symbol, or with 0, it is an ordinary library. Symbol name: `rad_plugin_reference`. */
typedef int (*RadPluginReferenceFn)(void);
#ifdef __cplusplus