radiance 1.0.0

This commit is contained in:
Deadcode committed 2026-10-04 12:02:41 +02:00
commit ae74a8aebf
616 files changed
+338692

No files matched your search

+616
View File
@@ -0,0 +1,616 @@
/* 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.
*/
#ifndef RAD_ABI_H
#define RAD_ABI_H
#include "rad_types.h"
#include "rad_encoding.h"
#ifdef __cplusplus
extern "C" {
#endif
/* 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 15u
/* ================================================================== plugin identity */
/* 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 */
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. */
const char* build_target;
} RadPluginInfo;
/* Every plugin exports these two. */
uint32_t rad_plugin_abi_version(void);
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. */
enum { RAD_DOMAIN_DEVICE = 0, RAD_DOMAIN_HOST = 1, RAD_N_DOMAINS = 2 };
/* ================================================================== kernel arguments */
typedef struct RadArgs {
const RadTensor* t; /* operands, positional, in the op schema's order */
int n_t;
const RadParam* p; /* the resolved geometry: every param, ranges collapsed */
int n_p;
void* scratch; /* device (or host) scratch, >= the scratch hook's answer */
int64_t scratch_bytes;
void* instance; /* whatever init() returned for this resolved instance */
int rank; /* tensor-parallel rank and world size, for collectives */
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. */
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)
if (a->p[i].kind == RAD_P_INT && strcmp(a->p[i].key, key) == 0) {
if (out) *out = a->p[i].ival;
return 1;
}
return 0;
}
/* Null if absent. */
static inline const char* rad_args_gets(const RadArgs* a, const char* key) {
if (!a || !key) return 0;
for (int i = 0; i < a->n_p; ++i)
if (a->p[i].kind == RAD_P_STR && strcmp(a->p[i].key, key) == 0) return a->p[i].sval;
return 0;
}
/* ================================================================== 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 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. */
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. */
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.
*
* 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. */
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 align; /* byte alignment the stored base must satisfy */
int64_t bytes; /* total, including any padding the layout implies */
} 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`.
*
* 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. */
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. */
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
* 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. */
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.
*
* 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.
*
* 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. */
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. */
RAD_FILL_UNIT_ROW = 5,
};
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. */
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. */
RAD_OPD_F_IDX_UNIQUE = 1u << 1,
/* CUMULATIVE SEQUENCE LENGTHS, [0, ..., T]. Not a draw: it is the batch's shape. */
RAD_OPD_F_IDX_CU = 1u << 2,
};
typedef struct RadOpdDesc {
uint32_t dtype;
uint32_t rank;
int64_t shape[RAD_MAX_RANK];
uint32_t fill; /* RAD_FILL_* */
int64_t fill_chunk; /* the reset width for GATE_CUMSUM and TRI_LOWER */
/* 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. */
int64_t idx_max;
int64_t idx_const; /* -1 to draw */
uint32_t flags; /* RAD_OPD_F_* */
} 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.
*
* 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.
*
* 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. */
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. */
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.
*
* `p` is the resolved geometry, `choice` the candidate as key/value parameters. Pure host code,
* called before anything is allocated, once per candidate.
*
* 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. */
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).
*
* 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.
*
* 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. */
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. */
enum { RAD_PROLE_NONE = 0, RAD_PROLE_SEQ_CHUNK = 1, RAD_PROLE_CAPACITY = 2 };
typedef struct RadParamSpec {
const char* key;
int type; /* RAD_P_INT | RAD_P_STR */
int required;
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. */
enum { RAD_OPD_IN = 0, RAD_OPD_OUT = 1, RAD_OPD_INOUT = 2, RAD_OPD_WEIGHT = 3,
RAD_OPD_WTAB = 4 };
typedef struct RadOperandSpec {
const char* name; /* for diagnostics: "x", "w_gate", "out" */
int role;
int optional; /* an absent optional operand is a null RadTensor.data */
} RadOperandSpec;
typedef struct RadOpSchema {
const char* op;
const RadParamSpec* params; int n_params;
const RadOperandSpec* operands; int n_operands;
const char* doc;
} RadOpSchema;
/* ================================================================== declared fusions
*
* WHAT CHAIN OF CONVENTIONAL OPS DOES THIS KERNEL COMPUTE?
*
* 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.
* "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.
*
* 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:
*
* 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.
*
* 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. */
enum {
RAD_FUSE_NONE = -1, /* this step does not pass that optional operand */
};
/* Temporary `t`, for t in [0, RAD_MAX_FUSE_TMP). Encoded so that a non-negative value is always an
* operand of the fused kernel and needs no tagging. */
#define RAD_FUSE_TMP(t) ((int16_t)(-2 - (t)))
#define RAD_FUSE_IS_TMP(v) ((v) <= -2)
#define RAD_FUSE_TMP_INDEX(v) ((int)(-2 - (v)))
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 */
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. */
int16_t from[RAD_MAX_FUSE_OPD];
int n_from;
} 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.
*
* 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.
*
* 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. */
#define RAD_FUSE_PRESENT_ALL ((uint64_t)~0ull)
#define RAD_FUSE_HAS(mask, i) (((mask) >> (i)) & 1ull)
typedef int (*RadFuseFn)(const RadParam* p, int n_p, uint64_t present, int step,
RadFuseStep* out);
/* ================================================================== kernel rows */
typedef struct RadKernelInfo {
const char* name; /* entry point, unique within the plugin */
const char* op; /* the op it implements -- the key callers select on */
const char* family; /* attn | gdn | ar | gemm | norm | sample | ... , for grouping only */
const char* computes; /* prose, for a human */
const char* shape; /* the geometry it is compiled for, prose */
const char* dtypes;
int domain; /* RAD_DOMAIN_DEVICE | RAD_DOMAIN_HOST */
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. */
const RadTunable* tunables; int n_tunables;
RadTuneValidFn tune_valid;
RadInitFn init;
RadFiniFn fini;
RadLaunchFn launch;
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. */
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. */
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.
*
* 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;
} 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). */
int rad_kernel_schema_count(void);
const RadOpSchema* rad_kernel_schema_at(int i);
int rad_kernel_count(void);
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.
*
* `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. */
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`. */
typedef int (*RadKernelConcurrentFn)(int i);
/* 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:
* - 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);
* - the engine refuses to serve a model with an op only a reference library implements, unless
* told to with --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`. */
typedef int (*RadPluginReferenceFn)(void);
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif /* RAD_ABI_H */
+690
View File
@@ -0,0 +1,690 @@
/* rad_builder.h -- the declare phase. An architecture plugin states everything it will ever do
* before it does any of it: every weight, every buffer, every op, in order. See spec.md §3.1.
*
* Between declare and plan the whole model is known statically -- every op, every kernel that
* will service it, every weight it touches, and the order. That is the property the rest of the
* engine spends.
*/
#ifndef RAD_BUILDER_H
#define RAD_BUILDER_H
#include "rad_abi.h"
#ifdef __cplusplus
extern "C" {
#endif
typedef struct RadBuilder RadBuilder;
/* ================================================================== model metadata */
/* What the loader read out of the container's header before any plugin ran. Dimensions come from
* here, so one plugin covers every size in a family: qwen3_dense_bf16.so serves 2B, 9B and 27B. */
typedef struct RadModelMeta {
const char* arch_id; /* the string that selected this plugin */
const char* name;
const char* quant; /* the quantisation descriptor, e.g. "w4a8_symz_g128" */
int64_t n_layers;
int64_t n_embd;
int64_t n_head;
int64_t n_head_kv;
int64_t head_dim;
int64_t n_ff;
int64_t n_vocab;
int64_t n_ctx_train;
int64_t n_expert; /* 0 for a dense model */
int64_t n_expert_used;
int64_t n_expert_shared;
float rms_eps;
float rope_theta;
float rope_scale;
/* Free-form key/value from the container header, for anything the struct above does not
* name. A plugin reads what it needs; the core never interprets these. */
int n_kv;
const char* const* kv_key;
const char* const* kv_val;
} RadModelMeta;
long long rad_meta_geti(const RadModelMeta* m, const char* key, long long dflt);
double rad_meta_getf(const RadModelMeta* m, const char* key, double dflt);
const char* rad_meta_gets(const RadModelMeta* m, const char* key, const char* dflt);
/* ================================================================== build context */
typedef struct RadBuildCtx {
int rank; /* declare runs once per rank; the plugin declares dimensions */
int world_size; /* ALREADY DIVIDED -- the core inserts no collectives (spec §9) */
int64_t max_tok; /* the largest token count one step may carry */
int64_t max_seqs; /* the largest number of sequences one step may carry */
int64_t max_ctx; /* context bound this deployment was configured for */
int max_spec; /* speculative window bound, 0 if speculation is off */
/* THE TENSOR-PARALLEL WIRE. 0 -- which is what a zero-initialised context gives, and that is
* deliberate -- is the EXACT all-reduce. Nonzero says this deployment accepts a lossy wire,
* which at two ranks libr4d serves as a Walsh-Hadamard-rotated 6-bit payload: 6 bits an
* element plus a bf16 scale per group of 64, against 16 bits an element, so the message a
* prefill chunk pushes across the link drops by 2.4x. The plugin inverts it into
* `all_reduce`'s `exact` parameter. The polarity is this way round because the sum a rank
* receives is then not the sum it would have received, and a field that defaults to lossy
* when someone forgets to fill it is the failure spec §17 exists to prevent. */
int tp_wire_lossy;
/* WHERE THE LOSSY WIRE STARTS PAYING, in bytes of one all-reduce message. Below it the exact
* kernel wins and the plugin must use it even when `tp_wire_lossy` is set: compression only
* pays once the transfer is bandwidth-bound, and a decode step's message is not -- it is a few
* tokens of the residual stream, where the rotate/pack/unpack costs more than the bytes it
* saves. Above it a prefill chunk is squarely on the wire and the 2.4x is real. 0 means the
* plugin's own default, which is 128 KiB. */
int64_t tp_wire_min_bytes;
/* THE KV CACHE'S WIDTH, AND IT IS A DEPLOYMENT CHOICE RATHER THAN A PROPERTY OF THE
* CHECKPOINT. `kv_dtype` follows the CACHE, not the weights: a container whose weights are
* fp8 may well want a bf16 cache and vice versa, and one field read as "the cache is bf16
* because the weights are" was true of one checkpoint and never a rule.
*
* RAD_DT_INVALID -- which is what a zero-initialised context gives -- means the plugin's own
* default, which every architecture in this tree takes as bf16. RAD_F8E4M3 is the other
* value anything implements today; the fp8kv attention family is band-gated on it and the
* store side writes E4M3 with per-(sequence, head) descales.
*
* IT IS AN ABI FIELD AND NOT AN ENVIRONMENT VARIABLE because it changes what the model
* computes. A per-architecture environment switch gives "is the cache fp8" one answer per
* architecture, each with its own default, and none of them appears in the startup log or in
* a bug report. --kv-cache-dtype is the one answer. */
int kv_dtype; /* RAD_DT_INVALID = the plugin's default (bf16); or RAD_F8E4M3 */
int is_draft; /* this builder scope is a drafter (spec §10) */
const char* scope; /* "", "draft", "vision", "audio" -- prefixes declared names */
/* A DECLARE THAT ONLY SIZES THE ACTIVATIONS, at a `max_tok` smaller than the deployment's.
* The core runs one per level of the activation arena it lends out: what the plugin declares
* says how big every buffer is when no step carries more than `max_tok` tokens, and the top of
* the arena past that is lent to the expert slab while the steps are that small.
*
* THE PLUGIN MUST LEAVE ITS OWN STATE ALONE WHILE THIS IS SET. The state its step function
* reads was written by the real declare, at the real `max_tok`, and a sizing declare that
* overwrote it would run every later step against the smaller configuration. Declare into
* scratch storage instead; nothing a sizing declare produces is ever issued, and its op
* handles are the real declare's.
*
* Only asked of a plugin that set RadArchProbe::shape_probe_ok. Trailing and zero-defaulted,
* so a plugin built against the older struct is unchanged. */
int shape_probe;
/* THE MOST PATCHES ONE ENCODER PASS MAY CARRY, and 0 means this deployment serves no media:
* the plugin declares no encoder, so a tower the container carries stays off the card. It is
* the encoder's `max_tok` -- every activation it declares is sized against it -- and it bounds
* the largest single image the server accepts, since one image is one attention segment and a
* segment is never split across passes. */
int64_t max_enc_patches;
/* THE MOST LOGITS ROWS ONE STEP MAY NAME, when that is more than the plugin's own rule of one
* per sequence (1 + max_spec at a speculative step). 0 is the rule. The engine's KL mode sets
* it to a whole step's tokens plus a row a sequence, because it reads a full-vocabulary row at
* every prompt position; the logits buffer and the lm_head's row range are sized from it. The
* engine reads the declared logits buffer back and refuses the mode when it is shorter, so a
* plugin that ignores the field is refused rather than overrun.
*
* Trailing and zero-defaulted, so a plugin built against the older struct is unchanged. */
int64_t max_out_rows;
} RadBuildCtx;
/* ================================================================== weights */
/* Access class, declared per weight because it is information only the architecture plugin has.
* It is what tells the placement planner whether prefetch can be exact (spec §5.2). */
enum {
RAD_ACCESS_PER_TOKEN = 0, /* read every forward pass -- dense weights */
RAD_ACCESS_PER_REQUEST = 1, /* read once per request -- an encoder tower, with an image */
RAD_ACCESS_CONDITIONAL = 2, /* read only if selected -- routed experts */
RAD_ACCESS_RARE = 3, /* may not be read at all in a given deployment */
RAD_ACCESS_VOCAB = 4 /* lm_head and the embedding table: read every token, enormous,
* and one of them is a gather rather than a GEMM. Its own class
* because neither PER_TOKEN's prefetch nor CONDITIONAL's
* prediction describes it (spec §19.2). */
};
/* How a weight is split across tensor-parallel ranks. The plugin says; the core does not infer. */
enum {
RAD_SHARD_NONE = 0, /* replicated on every rank */
RAD_SHARD_ROW = 1, /* split along dim 0 -- column-parallel in the usual naming */
RAD_SHARD_COL = 2 /* split along dim 1 -- row-parallel, needs a following all-reduce */
};
/* Grouping key: the unit of movement. An expert's gate/up/down share one, because the unit of
* transfer is an expert, not a tensor (spec §4.1). Layer grouping is what makes layer offload a
* contiguous run rather than a scatter. */
typedef struct RadWeightGroup {
int32_t layer; /* -1 for a model-level weight */
int32_t expert; /* -1 for a non-expert weight */
int32_t slot; /* free index within the group, e.g. gate=0 up=1 down=2 */
} RadWeightGroup;
/* NOTE: these are C compound literals, which C++ accepts only as a GNU extension. An architecture
* plugin written in C++ -- which is the norm -- should use the grp_layer()/grp_expert()/grp_model()
* inline functions in `<arch/rad_arch.h>` instead: the installed spelling, which the plugins in
* radiance's own tree use as well. Same values, no extension. */
#define rad_group_layer(l) ((RadWeightGroup){ (int32_t)(l), -1, 0 })
#define rad_group_expert(l, e) ((RadWeightGroup){ (int32_t)(l), (int32_t)(e), 0 })
#define rad_group_model() ((RadWeightGroup){ -1, -1, 0 })
/* The most projections one stored tensor may stack along dim 0. Five is what the bf16 delta net
* needs -- q, k, v, a, b in one row -- and eight leaves room without making the decl big. */
enum { RAD_MAX_ROW_PARTS = 8 };
typedef struct RadWeightDecl {
uint32_t dtype; /* what the kernel reads; the stored layout comes from the kernel */
uint32_t rank;
int64_t shape[RAD_MAX_RANK]; /* THIS RANK's extent of what `planes` select (below) */
int access; /* RAD_ACCESS_* */
int shard; /* RAD_SHARD_* */
RadWeightGroup group;
int optional; /* absent in the container is not an error */
/* WHAT IS STACKED IN DIM 0, for a RAD_SHARD_ROW weight whose stored tensor is several
* projections concatenated -- [gate|up], or the delta net's [q|k|v]. Rows of THIS RANK, in
* stored order, summing to shape[0]; 0 parts means one part and dim 0 is one projection.
*
* It exists because a tensor-parallel rank owns a slice of EACH stacked projection and not a
* contiguous slice of the stack. Taking rows [rank*D, (rank+1)*D) of a fused gate_up hands
* rank 0 the whole gate and rank 1 the whole up; both ranks then compute a perfectly
* well-formed wrong thing and the model produces fluent wrong text, which is the failure
* class spec §17 exists to prevent. The parts are NOT inferable from the container: it holds
* the fused result and not the shapes it was fused from, and a single checkpoint tensor may
* already be a fusion nothing in the name map mentions (in_proj_qkv is three head groups in
* one [10240, 5120]). The plugin is the only component that knows, so the plugin says. */
int n_row_parts;
int64_t row_parts[RAD_MAX_ROW_PARTS];
/* WHICH STORED WEIGHT THIS IS A VIEW OF, AND WHICH OF ITS PLANES. spec.md §4.3.
*
* A container entry, or a checkpoint tensor, is a LOGICAL weight: the planes of its encoding
* (rad_encoding.h) -- a block-fp8 linear's codes and its scale plane are one weight, not two.
* A kernel takes them as whatever operands its schema has: gemm_nt_q takes the codes and the
* scales as two, the fp8 lm_head one operand holding both. So a declared weight names its
* `source` -- null for the logical weight of its own name -- and the `planes` it takes, by
* role, comma-separated: "codes", "scale", "codes,scale". Null takes every plane, which for a
* plain weight is its one.
*
* One declared weight is one stored buffer. Its dtype and shape describe what is selected: a
* single plane's own dtype and extents, or, for several, the codes' dtype and the logical
* extents. A dtype other than the plane's is legal only as an exact widening -- a bf16 norm
* read as f32 -- which the loader performs; anything lossy is a quantiser's job and happens
* before a container is written. */
const char* source;
const char* planes;
} RadWeightDecl;
rad_weight rad_decl_weight(RadBuilder* b, const char* name, const RadWeightDecl* d);
/* WHAT A STORED WEIGHT IS: its encoding, and its logical extents in `shape` (RAD_MAX_RANK
* entries, may be null) with the rank returned in `rank` (may be null). RAD_OK, or RAD_E_NOTFOUND
* when the model has no such weight.
*
* The answer comes from wherever the model is being loaded from -- a container's entry, a
* checkpoint's tensor, or, in rad-convert, the recipe that will quantise it -- so a plugin learns
* the same thing the same way at convert and at load, and chooses its ops by it: an fp8 GEMM for
* a block-fp8 weight, the rotated expert kernels for `i4*bf16[1x128]/fwht128`. Ask after the
* weight's name map entry (rad_decl_name_map), which is how a checkpoint is searched for it. A
* builder with no model behind it -- a test, a synthetic tool -- answers RAD_E_NOTFOUND, and a
* weight declared there is read as plain in its declared dtype. */
int rad_weight_encoding(RadBuilder* b, const char* source, RadEncoding* out, int64_t* shape,
uint32_t* rank);
/* ================================================================== buffers */
/* Activations are declared too, or the buffer plan has nothing to analyse. Liveness is computed
* over the declared op list, so scratch and intermediates come from one arena sized once instead
* of an allocator called per step (spec §3.1). */
enum {
RAD_BUF_TRANSIENT = 0, /* liveness-analysed, may share storage with another transient */
RAD_BUF_PERSIST = 1, /* survives across steps: a KV-adjacent scratch, a routing histogram */
RAD_BUF_DERIVED = 2 /* computed once per step by the core from the batch (spec §8) */
};
typedef struct RadBufDecl {
uint32_t dtype;
uint32_t rank;
int64_t shape[RAD_MAX_RANK]; /* sized at max_tok, which is the worst step */
int kind; /* RAD_BUF_* */
int domain; /* RAD_DOMAIN_DEVICE or RAD_DOMAIN_HOST */
const char* derive; /* RAD_BUF_DERIVED: the derivation the core runs */
/* WHICH KV GROUP A DERIVATION IS ABOUT, or 0 for "the only one of its kind".
*
* `conv_state_index` computes a read cursor inside a rolling window, which means it needs THAT
* GROUP's slot per sequence and THAT GROUP's window depth -- and a model may declare several.
* Qwen4-Exp's PLE layer has two conv states of different depths and dtypes beside the gated
* delta net's third. Leaving this 0 with more than one group of the kind a derivation reads is
* refused rather than guessed at: the wrong window's depth produces a plausible cursor and a
* convolution that reads history it never wrote.
*
* Trailing and zero-defaulted, so a plugin built against the older struct is unchanged. */
rad_kvgroup kv;
} RadBufDecl;
rad_buf rad_decl_buffer(RadBuilder* b, const char* name, const RadBufDecl* d);
/* ================================================================== KV groups */
/* Each distinct state kind is a KV group with its own block geometry, its own pool, and its own
* slot mapping in the step batch. Linear-attention state is a KV group too: it is not paged the
* same way, but it is allocated, mapped and freed by the same manager, because otherwise two
* allocators disagree about what a sequence owns (spec §7.2). */
enum {
RAD_KV_FULL = 0, /* paged, per-token, growing -- full attention */
RAD_KV_WINDOW = 1, /* paged, per-token, bounded by the window */
RAD_KV_LINEAR = 2, /* per-sequence, fixed size -- GDN recurrent state */
RAD_KV_CONV = 3 /* per-sequence, a rolling window of width-1 + num_spec entries */
};
typedef struct RadKVGroupDecl {
int kind; /* RAD_KV_* */
uint32_t dtype;
int64_t window; /* RAD_KV_WINDOW: the window; 0 otherwise */
int64_t n_head_kv;
int64_t head_dim;
int64_t state_dim[2]; /* RAD_KV_LINEAR: the per-head state geometry, e.g. {128,128} */
int64_t conv_width; /* RAD_KV_CONV */
/* Block size is NOT declared. It is taken off the resolved attention kernel's constraints at
* declare, because a core that picked its own would be a core that has to be edited when a
* kernel changes (spec §7.2). Read it back with rad_kv_block_size() after declaring the
* attention op that consumes this group. */
} RadKVGroupDecl;
/* `rad_kvgroup` is in rad_types.h with the other handles -- RadBufDecl above carries one. */
rad_kvgroup rad_decl_kv_group(RadBuilder* b, const char* name, const RadKVGroupDecl* d);
/* Valid only after the op that reads this group has been declared. 0 before that. */
int64_t rad_kv_block_size(RadBuilder* b, rad_kvgroup g);
/* Bind a layer to a group, so the block manager knows how many state instances a sequence owns. */
int rad_bind_layer_kv(RadBuilder* b, int layer, rad_kvgroup g);
/* ================================================================== ops */
/* Declared with their parameters and their weight operands. The core resolves each against the
* kernel hierarchy, per band, per domain. This phase ALWAYS completes; if anything failed to
* resolve, the full list is reported at the end rather than the first failure at the top. */
rad_op rad_decl_op(RadBuilder* b, const char* op,
const RadParam* params, int n_params,
const rad_weight* weights, int n_weights);
/* Convenience wrappers so a declare function reads like a list of what the model does.
* rad_op h = RAD_OP(b, "gemm_w4a8_nt",
* RAD_PARAMS(RAD_RANGE("M",1,max_tok), RAD_INT("N",8192), RAD_INT("K",5120)),
* RAD_WEIGHTS(w));
*/
#define RAD_PARAMS(...) ((const RadParam[]){ __VA_ARGS__ }), \
(int)(sizeof((const RadParam[]){ __VA_ARGS__ }) / sizeof(RadParam))
#define RAD_NOPARAMS ((const RadParam*)0), 0
#define RAD_WEIGHTS(...) ((const rad_weight[]){ __VA_ARGS__ }), \
(int)(sizeof((const rad_weight[]){ __VA_ARGS__ }) / sizeof(rad_weight))
#define RAD_NOWEIGHTS ((const rad_weight*)0), 0
#define RAD_OP(b, op, ...) rad_decl_op((b), (op), __VA_ARGS__)
/* An op's BUFFER operands, which rad_decl_op does not name -- it names weights, because those are
* what placement moves. But the buffer planner needs liveness, and liveness is exactly which ops
* read and write which buffers. Without these a transient has no declared use and must be assumed
* live for the whole program, which is sound (a plugin may issue any handle in any order) and as
* wasteful as it sounds; --debug-graph prints how many buffers fell into that case so the cost is
* never invisible.
*
* Separate from rad_decl_op rather than more arguments to it, because the common case is one call
* with one read set and one write set and the alternative is four more parameters on every
* declaration. */
int rad_op_reads (RadBuilder* b, rad_op h, const rad_buf* bufs, int n);
int rad_op_writes(RadBuilder* b, rad_op h, const rad_buf* bufs, int n);
/* A BUFFER THE ARCHITECTURE TOUCHES FROM THE SECOND LANE, which is the one case where the op
* range a buffer's declarations imply is NOT a bound on when its bytes are in use.
*
* The planner packs transients from ONE LINEAR ORDER (spec §3.1): two whose declared lives do not
* overlap share arena bytes. `rad_lane` breaks that assumption rather than the declarations --
* lane 1's ops are issued at op indices that sit inside lane 0's, so a shared-arm scratch whose
* life is "ops 41..42" can be laid over a routed-arm scratch whose life is "ops 37..38", and on
* two streams those two runs OVERLAP IN TIME. Nothing downstream can tell: it reads as data.
*
* So a buffer named here is given the WHOLE PROGRAM, which is what a buffer with no declared use
* already gets and is sound for the same reason. It is deliberately per-buffer and not a mode:
* unsharing every buffer would cost ~220 MiB on a model this size, where the lane-1 transients
* of one block are a few MiB. Call it at declare, for every buffer the
* second lane reads or writes -- the ones lane 0 touches in the same window are covered by
* symmetry, since sharing needs both sides.
*
* Calling it for a PERSIST or DERIVED buffer is a no-op: those are live everywhere already. */
int rad_buf_concurrent(RadBuilder* b, rad_buf buf);
/* AN UNEVEN SHARD: this rank's slice of a RAD_SHARD_ROW or RAD_SHARD_COL weight's split dimension
* is [lo, hi) and not the even 1/tp of it -- rows of EACH stacked row part for ROW, columns for
* COL, in the container's (unsharded) units. The declared extent must already be `hi - lo` (each
* row part's, for ROW).
*
* For a width that does not divide into equal whole blocks across the ranks: a 640-column
* projection with 128-column scale blocks is five blocks, which two ranks can split three and two
* but not in half. The stacked parts of a ROW weight must be equal in the container, since only
* the rank's own part sizes are declared. Refused by a container converted for more than one
* rank, whose entries are already even shares, and by a stored layout whose row runs or column
* groups the span would cut. */
int rad_weight_shard_span(RadBuilder* b, rad_weight w, int64_t lo, int64_t hi);
#define RAD_BUFS(...) ((const rad_buf[]){ __VA_ARGS__ }), \
(int)(sizeof((const rad_buf[]){ __VA_ARGS__ }) / sizeof(rad_buf))
/* Did the last rad_decl_op resolve? A plugin asks for the fused op first and emits the unfused
* sequence when it does not, which is what makes fusion a selection rather than a compiler pass
* (spec §2.3). A handle that did not resolve is RAD_NULL_HANDLE and is NOT an error yet -- it
* becomes one only if the plugin issues it. */
int rad_op_resolved(RadBuilder* b, rad_op h);
/* ================================================================== checkpoint name map */
/* The plugin owns the map from checkpoint tensor names to declared weight names, including
* convert-time fusions -- q/k/v into a single qkv, gate and up into gate_up. It is the only
* component that knows both sides, and rad-convert reads the map from it (spec §2.4). */
enum { RAD_MAP_COPY = 0, RAD_MAP_CONCAT = 1 };
typedef struct RadNameMap {
const char* declared; /* the name given to rad_decl_weight */
int mode; /* RAD_MAP_COPY | RAD_MAP_CONCAT */
int n_src;
const char* src[8]; /* checkpoint tensor names */
int concat_dim;
/* A sub-tensor index within src[i], or -1 for the whole tensor. GGUF stores a MoE layer's
* experts stacked as one ffn_gate_exps of shape [.., n_expert], while placement needs one
* declared weight per expert -- the movement unit is an expert, not a tensor. Without this
* the expert index survives only inside the declared NAME, which is an unwritten convention
* rad-convert would have to parse. */
int src_index[8];
} RadNameMap;
/* RAD_MAP_COPY with n_src > 1 means FIRST SOURCE PRESENT IN THE CONTAINER WINS. That is how a
* tied lm_head is expressed -- output.weight if the checkpoint has one, else token_embd.weight --
* and without it a model family whose members differ only in tying needs two plugins.
* RAD_MAP_CONCAT with n_src > 1 concatenates all of them along concat_dim and requires every one. */
int rad_decl_name_map(RadBuilder* b, const RadNameMap* m);
/* ================================================================== the step's output */
/* WHICH BUFFER HOLDS THIS STEP'S LOGITS. The core samples from it -- the sampler chain is core
* logic and its ops resolve through the same hierarchy at the same time as the plugin's (spec
* §13) -- so the core has to be told which buffer that is, and the plugin is the only one who
* knows.
*
* A name convention would do it and is wrong: a drafter or an encoder tower declares into a SCOPE
* (RadBuildCtx::scope, spec §10, §11), so "the buffer called logits" is two different buffers in
* one Program and matching on the string would sample the draft model's distribution into the
* target's tokens. It is one call and it removes a string match from startup.
*
* Its extent along dim 0 bounds RadBatch::n_out: the buffer holds one row per sampled position,
* not one per token of the step. Declaring it [max_tok, n_vocab] is legal and, at a 248K
* vocabulary, 8 GiB.
*
* A Program with no logits buffer cannot serve, and the engine says so at startup rather than at
* the first step. An embedding-only or encoder-only plugin declares none, deliberately. */
int rad_declare_logits(RadBuilder* b, rad_buf logits);
/* ================================================================== the drafter */
/* WHAT THE PLUGIN'S DRAFT HEAD IS, declared the same way and for the same reason the logits
* buffer above is: the core drives the extra passes, so it has to be told what it is driving,
* and the plugin is the only one who knows.
*
* IT REPLACES A WEIGHT-NAME MATCH. The alternative is for the engine to decide whether a
* container drafts by scanning the declared weights for names like `mtp.fc.weight` or
* `dflash.fc.weight`, and then to re-read the drafter's own configuration keys -- block size,
* mask token, sliding window, predicted-layer count -- every one of them a key the plugin has
* already read to build the thing. Two readers of one fact is two places for it to disagree, and
* the second reader would be the core, which is the one that must not know.
*
* KIND IS A SHAPE, NOT A MODEL. There are two ways a draft head can be driven and the difference
* is visible from outside it: SERIAL runs `depth` dependent passes, each embedding what the last
* one proposed, so the tokens arrive one at a time and a pass that declines ends the chain.
* BLOCK runs a context pass and then ONE pass that fills every drafted position at once. MTP,
* EAGLE and Medusa-serial are all SERIAL; DFlash2 and any other block-diffusion drafter is
* BLOCK. A plugin picks the shape that describes it and needs no core change to do it.
*
* `proposal` is the buffer a pass writes its token ids into, and 0 means "the sampler's token
* buffer" -- which is what a head whose logits go through the ordinary sampler chain wants. A
* by-name lookup cannot supply this field: it would have to suffix-match a name that is not
* unique in the Program, in exactly the way the comment above rad_declare_logits explains is
* wrong -- a drafter declares into its own scope.
*
* A plugin that declares no drafter is not an error and is the normal case; the scheduler's
* prompt-lookup drafter still runs. */
typedef enum {
RAD_DRAFT_NONE = 0,
RAD_DRAFT_SERIAL = 1, /* `depth` dependent passes, one proposal each */
RAD_DRAFT_BLOCK = 2, /* a context pass, then one pass that fills the whole block */
} RadDraftKind;
typedef struct RadDrafterDecl {
const char* name; /* "mtp", "dflash2" -- for messages and the graph dump */
int kind; /* RAD_DRAFT_* */
int depth; /* tokens proposed a step; must equal RadBuildCtx::max_spec */
/* Where a pass leaves its proposal. 0 = the sampler's token buffer. */
rad_buf proposal;
int64_t proposal_pitch; /* elements a row in `proposal`; 0 means 1 */
/* BLOCK only. `mask_token` is the id every unfilled position of the block embeds, and a
* block drafter without one has nothing to run. `window` is the drafter's OWN sliding
* window over its OWN cache, 0 for unbounded -- the core stages the block pass against it,
* so it must be the same number the plugin gated its attention with. */
int32_t mask_token;
int64_t window;
/* BLOCK only: HOW MANY ROWS THE QUERY PASS RUNS OVER, one sequence's worth. 0 means
* `depth + 1`.
*
* IT IS NOT ALWAYS depth + 1, AND THE DIFFERENCE IS A ROW ALIGNMENT. The core stages the
* block as an anchor -- the token the sampler just chose -- followed by `block - 1` copies of
* `mask_token`, and THE HEAD RUNS OVER THE LAST `depth` ROWS. That one rule covers both
* conventions a block-diffusion drafter can be trained in:
*
* block = depth + 1 the anchor row predicts NOTHING and each mask row predicts the token
* at ITS OWN position. The head sees rows 1..depth. DFlash2.
* block = depth every row predicts the token at the position AFTER it, the anchor
* row included -- the ordinary next-token relation, so the anchor is
* not a wasted row. The head sees rows 0..depth-1. DSpark, whose
* reference takes `hidden[:, -block_size:, :]` over exactly this.
*
* GETTING IT WRONG IS INVISIBLE FROM THE OUTSIDE. Both values run, both produce `depth`
* tokens, and the model's own output stays exactly correct because every draft is verified;
* what happens instead is that the proposals are shifted by one position and acceptance
* collapses to roughly the rate of chance. That is why this is declared by the plugin that
* knows how its checkpoint was trained, and not inferred here. */
int64_t block;
} RadDrafterDecl;
int rad_declare_drafter(RadBuilder* b, const RadDrafterDecl* d);
/* ================================================================== the encoder */
/* A MEDIA ENCODER THE PLUGIN RUNS ON AN ENCODER PASS (RadBatch::enc), declared for the reason the
* logits buffer and the drafter are: the core drives the pass and reads its result, so it has to
* be told what it is driving, and only the plugin knows. A plugin that declares none serves text,
* and the server refuses a media part by name.
*
* WHAT IS HERE IS THE SHAPE OF THE INTERFACE, NOT THE MODEL. The core stages patches of
* `patch_dim` elements and reads back one `n_embd`-wide row for every `merge` of them; what turns
* the one into the other -- the tower's depth, its attention, its position scheme -- is the
* plugin's business and appears nowhere in the core. How an image or a video becomes patches is
* the processor's (core/mm), which reads its geometry from the container: the two agree through
* `patch_dim` and `merge`, and the core refuses a program whose encoder disagrees with the
* processor about either. */
enum {
RAD_MM_IMAGE = 1u << 0,
RAD_MM_VIDEO = 1u << 1,
};
typedef struct RadEncoderDecl {
const char* name; /* "vision" -- for messages */
uint32_t modalities; /* RAD_MM_* this encoder serves */
int64_t patch_dim; /* elements in one input patch row */
int64_t merge; /* input patches per output row */
int64_t max_patches; /* must equal RadBuildCtx::max_enc_patches */
int64_t n_embd; /* the width of an output row, the model's embedding width */
/* [max_patches / merge, n_embd] bf16: where a pass leaves its rows. The core reads it after
* the pass and before any other pass runs, so the planner may share its bytes with buffers
* no encoder pass touches. */
rad_buf out;
} RadEncoderDecl;
int rad_declare_encoder(RadBuilder* b, const RadEncoderDecl* d);
/* ================================================================== diagnostics */
/* A plugin may annotate the graph dump. Free-form, printed under --debug-graph. */
void rad_note(RadBuilder* b, const char* fmt, ...);
/* ================================================================== the arch plugin exports */
const char* rad_arch_id(void);
/* THE QUANTISATION THIS PLUGIN SERVES, and the second half of the key that selects it.
*
* spec §2.4 is one plugin per (architecture, quantisation): a w4a8 model wants
* rmsnorm_had_quant_i8 where a bf16 model wants a plain rmsnorm, and a plugin full of branches on
* a quant descriptor is how you get back to "unclear what actually runs". So `qwen35_bf16` and
* `qwen35_fp8` both answer "qwen35" to rad_arch_id and are told apart HERE, by the string the
* container already carries in RadModelMeta::quant.
*
* The match is EXACT and there is no fallback. An unquantised container and an unquantised plugin
* both say "" -- the symbol is optional and a plugin that does not export it is read as "".
* Falling back from a quantised container to a plugin that declares dense weights would fail
* later, at the name map, with a worse message than "no plugin claims qwen35 at fp8_e4m3; qwen35
* is served at: (unquantised)". */
const char* rad_arch_quant(void);
/* WHAT THE PLUGIN CAN SAY BEFORE IT DECLARES ANYTHING. OPTIONAL: a plugin that does not export
* it answers every question with the zero, which is each field's default.
*
* It exists for the ONE fact that is an INPUT to declaration and a property of the model:
* the draft depth. `RadBuildCtx::max_spec` sizes buffers, bands kernels and sets the scheduler's
* window, so it must be fixed before rad_arch_declare runs -- but "how deep does this container's
* drafter want to go" is answerable only by reading the drafter's own configuration, which is the
* plugin's job. The alternative is a core that reads those keys itself, by name, with an
* architecture's own prefix in the string.
*
* A serial head names a THROUGHPUT TRADE-OFF: more rounds cost a pass each and acceptance decays,
* so the number is measured, not derived. A block drafter names the block length ITS CHECKPOINT
* WAS TRAINED AT, and asking for anything else is a silently worse draft. Both are the plugin's
* to know. 0 means "this container carries no drafter", which is the right answer to "speculate
* as deeply as this model can" on a model that cannot.
*
* --num-speculative-tokens overrides whatever comes back, and the plugin sees the result in
* RadBuildCtx::max_spec; a plugin whose checkpoint cannot serve that depth refuses in declare,
* where it has the whole configuration in front of it. */
typedef struct RadArchProbe {
int draft_depth;
/* WHETHER THAT DEPTH IS THE ONLY ONE THE DRAFTER SERVES, and the two callers of this need
* different answers. A SERIAL head names a throughput trade-off: more passes cost one each
* and acceptance decays, so the depth it reports is an operating point and one more pass
* still runs. A BLOCK drafter
* names the block length its checkpoint was TRAINED at -- its convolution masks the position
* within that block -- so any other depth is not a shorter proposal, it is a refusal.
*
* `--num-speculative-tokens auto` takes `draft_depth` either way; it is choosing an operating
* point. rad-convert must not: a CONTAINER carries what the model can serve, so narrowing it
* to a serial head's preferred depth would mean a deployment asking for one more had to
* convert again. It widens to `draft_depth` only when this says the drafter has no choice. */
int draft_depth_fixed;
/* THE PLUGIN HONOURS RadBuildCtx::shape_probe: a sizing declare leaves the state its step
* function reads untouched. Zero -- what a plugin that never heard of it leaves -- means the
* core does not ask, and the activation arena is not lent. */
int shape_probe_ok;
} RadArchProbe;
int rad_arch_probe(const RadModelMeta* meta, RadArchProbe* out);
/* HOW THIS MODEL SPELLS A TURN, AS DATA. OPTIONAL: a plugin that does not export it leaves the
* engine to derive the format by analysing the chat template.
*
* A reply is read back into reasoning, content and tool calls by one streaming parser driven by
* this description, and the lazy grammar that constrains a call and the literal words that
* trigger it are generated from it too -- so a model whose format the template analysis cannot
* find, or finds wrongly, is supported by stating the format here once. What it describes is the
* tagged family:
*
* [reasoning_open] reasoning [reasoning_close] content
* [call_open] name_prefix NAME name_suffix
* arg_prefix ARG arg_name_suffix arg_value_prefix VALUE arg_value_suffix ...
* call_end [call_close]
*
* Qwen3.8, for example, is "<think>\n" / "\n</think>\n\n", calls "<tool_call>\n" / "</tool_call>",
* "<function=" / ">\n" / "</function>\n", arguments "<parameter=" / ">\n" / "" / "</parameter>\n".
* Whitespace at the ends of a tag is optional when matching. Every string is NUL-terminated
* UTF-8; NULL reads as "". The engine copies what it needs while loading, so static storage in
* the plugin is enough.
*
* THE STRUCT GROWS AT ITS END AND NEVER CHANGES IN THE MIDDLE. `struct_size` is
* sizeof(RadChatFormat) as the plugin was compiled; the engine reads only the fields that size
* covers and treats the rest as zero, so a plugin built against an older header keeps loading
* and a field added later is appended with a zero that means "as before". That is why this
* export does not move RAD_ABI_VERSION: it is additive, and a plugin that lacks it or predates a
* field is read correctly. A change that is NOT additive -- a field reordered, retyped or
* removed -- is a layout change and bumps RAD_ABI_VERSION like any other. */
enum {
RAD_CHAT_VALUE_RAW = 0, /* the text between the delimiters, verbatim */
RAD_CHAT_VALUE_CDATA = 1, /* verbatim, unless wrapped in <![CDATA[ ... ]]>, which is removed */
RAD_CHAT_VALUE_JSON = 2 /* a JSON value; text that does not parse as JSON is taken raw */
};
enum {
/* The generation prompt shows whether the reply starts inside a reasoning block: whatever
* follows the first `reasoning_open` in it is the start of the reply's own text. */
RAD_CHAT_THINK_FROM_PROMPT = 0,
RAD_CHAT_THINK_ALWAYS = 1, /* the reply is inside a reasoning block from its first byte */
RAD_CHAT_THINK_NEVER = 2 /* the model opens its own block, if any */
};
typedef struct RadChatFormat {
uint32_t struct_size;
const char* name; /* for the startup log; NULL is the plugin's name */
const char* reasoning_open; /* "" when the model does not reason */
const char* reasoning_close;
/* Literals that end a reasoning block the model forgot to close, when a call starts there.
* Each must be the call opener: `call_open`, or `name_prefix` when there is no call_open. */
const char* const* reasoning_breaks;
uint32_t n_reasoning_breaks;
uint32_t reasoning_in_prompt; /* RAD_CHAT_THINK_* */
/* Around ALL of a turn's calls, and between two calls beyond whitespace. The parser does not
* read either yet, so a format that needs one is refused at startup by name; they are fields
* so that supporting them does not change the struct. */
const char* section_open;
const char* section_close;
const char* call_separator;
const char* call_open; /* around each call; "" when calls are not wrapped */
const char* call_close;
const char* name_prefix; /* "" when the model has no tool calls */
const char* name_suffix;
const char* call_end;
const char* arg_prefix;
const char* arg_name_suffix; /* "" when arg_value_prefix alone ends the name */
const char* arg_value_prefix;
const char* arg_value_suffix;
uint32_t string_value; /* RAD_CHAT_VALUE_RAW or _CDATA: a string-typed argument */
uint32_t other_value; /* RAD_CHAT_VALUE_JSON: any other type (or _RAW, as text) */
/* Non-zero: one newline at each end of a value is punctuation, not part of the value. */
uint32_t value_newlines;
/* The literal words that start constrained decoding of a call. None: no grammar, and the
* reply is read unconstrained. */
const char* const* triggers;
uint32_t n_triggers;
} RadChatFormat;
/* Return the format, or NULL for "derive it from the chat template". Called once at startup. */
const RadChatFormat* rad_arch_chat_format(const RadModelMeta* meta);
int rad_arch_declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx);
/* Forward declaration; the signature is in rad_runtime.h. */
struct RadCtx;
struct RadBatch;
void rad_arch_step(struct RadCtx* c, const struct RadBatch* batch);
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif /* RAD_BUILDER_H */
+79
View File
@@ -0,0 +1,79 @@
/* rad_device.h -- the device layer. Thin on purpose: everything above it is written once, and
* every backend implements exactly the small set of calls below.
*
* The host backend is not a toy. It is what lets the core, the scheduler, the planner, the
* tokeniser, the server and libref be built and tested on a machine with no accelerator, and it
* is the same code path RAD_DOMAIN_HOST kernels run on when the planner puts a layer on the CPU
* (spec §5.1).
*/
#ifndef RAD_DEVICE_H
#define RAD_DEVICE_H
#include "rad_types.h"
#ifdef __cplusplus
extern "C" {
#endif
typedef void* RadEvent;
enum { RAD_MEM_DEVICE = 0, RAD_MEM_HOST_PINNED = 1, RAD_MEM_HOST = 2, RAD_MEM_HOST_MAPPED = 3 };
/* WHAT THE ENGINE KNOWS ABOUT A DEVICE, AND IT IS ONLY THIS. Nothing above this layer names a
* vendor, a product or an instruction set: the scheduler, the planner and the budgets are written
* against these fields and learn the machine from them at run time. A kernel library is where
* hardware knowledge belongs, and it declares which devices it serves.
*
* Every field carries whatever the backend reports, in the backend's own vocabulary. */
typedef struct RadDeviceProps {
char name[128]; /* the product name, for logs and for the tuning cache's key */
char arch[32]; /* the backend's name for the architecture, with any feature
* suffixes cut -- "gfx1201", "sm_90". This is what a kernel
* plugin's build_target is compared against. */
int device_id;
int n_cu; /* independent compute units, however the backend counts them */
int warp_size; /* lanes executed in lockstep; 1 on a scalar backend */
int64_t vram_bytes; /* device-local memory, total and unclaimed */
int64_t vram_free;
int64_t lds_bytes; /* per-workgroup scratch, for occupancy arithmetic only */
int supports_p2p;
int is_host_backend; /* 1 when there is no accelerator behind this device */
} RadDeviceProps;
int rad_dev_count(void);
int rad_dev_set(int device);
int rad_dev_props(int device, RadDeviceProps* out);
int rad_dev_enable_peer(int self, int peer);
void* rad_dev_alloc(int64_t bytes, int kind);
void rad_dev_free(void* p, int kind);
/* Host-visible pointer for a RAD_MEM_HOST_MAPPED allocation, so the zero-copy execution site can
* hand the same allocation to both sides (spec §5.1). Null if the kind has no such view. */
void* rad_dev_host_ptr(void* p);
void* rad_dev_device_ptr(void* p);
int rad_stream_create(RadStream* out, int high_priority);
void rad_stream_destroy(RadStream s);
int rad_stream_sync(RadStream s);
int rad_event_create(RadEvent* out);
void rad_event_destroy(RadEvent e);
int rad_event_record(RadEvent e, RadStream s);
int rad_event_wait(RadStream s, RadEvent e); /* stream waits; no host sync */
int rad_event_query(RadEvent e); /* 1 = complete, 0 = pending, <0 = error */
int rad_event_sync(RadEvent e);
int rad_event_elapsed_ms(RadEvent a, RadEvent b, float* out);
int rad_memcpy_async(void* dst, const void* src, int64_t bytes, RadStream s);
int rad_memcpy_2d_async(void* dst, int64_t dpitch, const void* src, int64_t spitch,
int64_t width, int64_t height, RadStream s);
int rad_memset_async(void* dst, int value, int64_t bytes, RadStream s);
/* The last device error, cleared by reading it. A device fault is not recoverable in-process;
* the engine exits non-zero rather than serving from a wedged queue (spec §17). */
const char* rad_dev_last_error(void);
#ifdef __cplusplus
}
#endif
#endif /* RAD_DEVICE_H */
+421
View File
@@ -0,0 +1,421 @@
/* rad_encoding.h -- what a stored weight's numbers ARE, independently of how any kernel wants them
* arranged. spec.md §4.1.
*
* An ENCODING is the code type, the codebook the codes index if any, the grouping of the scales,
* zero points and minimums over the weight, and the transform the weight went through before it
* was quantised. It is a property of the model: choosing one is lossy and can be expensive (GPTQ
* wants a calibration run), and changing one means quantising again. A LAYOUT -- fragment order, a
* scale carried in each row's tail, a nibble order that suits one unpack -- is a property of a
* kernel, lossless and cheap, and it is applied when the model loads (rad_abi.h). A container holds
* encodings only, so a kernel library can change every layout it has without a reconvert.
*
* AN ENCODING IS DATA RATHER THAN A NAME IN AN ENUM, so a quantiser plugin can invent one without
* the core learning about it: the core can size, slice and place any encoding from this struct
* alone, and it decodes every encoding of the one scheme it defines, "affine", which is wide enough
* to hold every format in common use -- per-channel and grouped integers of any width, block FP8,
* MXFP4/6/8, NVFP4, llama.cpp's legacy, K- and I-quants, AWQ's column scales, GPTQ's act-order
* permutation, Hadamard and Givens rotations.
*
* ===================================================================== PLANES
*
* An encoding is up to RAD_ENC_MAX_PLANES planes, each a dense ROW-MAJOR array of one core dtype.
* A plane is one of two kinds:
*
* TILED it covers the weight. A weight of logical shape [d0, ..., dn] is seen as [rows, cols]
* with rows = d0 * ... * d(n-1) and cols = dn (a rank-1 weight is one row); a TILED
* plane whose block is [br, bc] has ceil(rows/br) x ceil(cols/bc) elements, element
* (i, j) covering logical rows [i*br, (i+1)*br) and columns [j*bc, (j+1)*bc). A block
* extent of 0 is the whole extent, so a per-tensor scale is one element and a
* per-column scale is a block of [0 x 1].
* TABLE it does not: a codebook, a lattice grid, a rotation's parameters. Its extents are its
* own, [extent0 x extent1], and every slice of the weight carries all of it.
*
* SUB-BYTE AND ODD-WIDTH ELEMENTS ARE A BIT STREAM ALONG THE ROW, lowest bits first: element j of a
* b-bit row occupies bits [j*b, (j+1)*b) counted from bit 0 of the row's first byte, so two 4-bit
* codes share a byte with element 0 in bits 0-3, and a 3-bit code may straddle a byte. Every row
* starts on a byte. That is the order a reference implementation and a person reading a hex dump
* assume; a kernel that wants its nibbles permuted for its own unpack does it in its relayout.
*
* ===================================================================== THE AFFINE SCHEME
*
* The planes are found by ROLE, and only "codes" is required. A weight element decodes as
*
* q = code codes is TILED; its block is [1 x 1] -- one code a value -- or
* [1 x V] with a "grid", one code a V-vector
* q = grid[code][k] grid TABLE [entries x V]: a VECTOR codebook (the IQ2/IQ3/IQ1
* lattices); value k of the code's V-vector
* q = table[code] table TABLE [1 x entries]: a SCALAR codebook (IQ4_NL)
* q = -q if the sign bit is set signs TILED u1 [1 x 1], one bit a value
* q = q - zero zero TILED; an integer or real offset in the CODE's domain
* v = q * scale * scale.1 * ... scale, scale.1, ... TILED: every scale level, multiplied
* v = v - min * min.1 * ... min, min.1, ... TILED: a minimum in the VALUE's domain
* w = v . T^-1 the transform, per row, over the columns (below)
*
* so NVFP4 is fp4 codes, an e4m3 scale per [1 x 16] and an f32 scale.1 per tensor; Q4_K is u4
* codes, a u6 scale and u6 min per [1 x 32] each times an f16 per [1 x 256]; IQ2_XXS is u8 codes
* per [1 x 8] into a 256 x 8 grid with a sign bit a value and two scale levels. Any other scheme
* is a quantiser's own, and that quantiser decodes it (rad_quant.h).
*
* ===================================================================== TRANSFORMS
*
* `transform` names what was done to each row before it was quantised: the stored row is v = w . T,
* so a kernel computes <w, x> = <v, x . T^-T> and transforms its ACTIVATION, never the weight.
*
* "" none.
* "fwhtN" T = H_N / N block-diagonally over groups of N columns, H_N the UNNORMALISED
* Sylvester Hadamard (entries +-1, H H = N I). Decoding applies H_N once (w = H v);
* the activation is rotated by H_N, unnormalised, with nothing folded at runtime --
* the 1/N lives in the stored scale.
* "perm" T is a column permutation: TABLE "t.perm" i32 [1 x cols], v[j] = w[perm[j]] --
* GPTQ's act-order, which quantises the columns in a different order than they sit.
* "givens" T = D . G_1 . ... . G_S: D = diag(t.scale) when TABLE "t.scale" f32 [1 x cols]
* is present, and G_s a stage of disjoint Givens rotations -- TABLE "t.pairs" i32
* [S x cols] lists stage s's pairs as (pairs[s][2p], pairs[s][2p+1]), TABLE "t.angle"
* f32 [S x cols/2] their angles, and a row vector's pair (a, b) at angle t becomes
* (a cos t + b sin t, b cos t - a sin t). ParoQuant's scaled pairwise rotation.
*
* Pure C, header-only, like the rest of abi/.
*/
#ifndef RAD_ENCODING_H
#define RAD_ENCODING_H
#include "rad_types.h"
#include <stdio.h>
#include <string.h>
#ifdef __cplusplus
extern "C" {
#endif
enum { RAD_ENC_MAX_PLANES = 8, RAD_ENC_STR = 24 };
enum { RAD_PLANE_TILED = 0, RAD_PLANE_TABLE = 1 };
typedef struct RadEncPlane {
char role[RAD_ENC_STR]; /* "codes", "scale", "scale.1", "zero", "min", "grid", "t.perm" */
uint32_t dtype; /* a core dtype -- never a plugin-private one */
uint32_t kind; /* RAD_PLANE_TILED | RAD_PLANE_TABLE */
int64_t block[2]; /* TILED: logical rows x cols one element covers; 0 = whole */
int64_t extent[2]; /* TABLE: the plane's own rows x cols */
} RadEncPlane;
typedef struct RadEncoding {
char scheme[RAD_ENC_STR]; /* "plain" | "affine" | a quantiser's own */
char transform[RAD_ENC_STR]; /* "" | "fwhtN" | "perm" | "givens" */
int32_t n_planes;
int32_t reserved;
RadEncPlane plane[RAD_ENC_MAX_PLANES];
} RadEncoding;
/* ================================================================== building one */
static inline void rad_enc_copy_str(char* dst, const char* src) {
size_t n = src ? strlen(src) : 0;
if (n >= RAD_ENC_STR) n = RAD_ENC_STR - 1;
memset(dst, 0, RAD_ENC_STR);
if (n) memcpy(dst, src, n);
}
static inline void rad_enc_clear(RadEncoding* e) { memset(e, 0, sizeof *e); }
/* Append a TILED plane. Returns its index, or -1 when the encoding is full. */
static inline int rad_enc_add_plane(RadEncoding* e, const char* role, uint32_t dtype,
int64_t block_rows, int64_t block_cols) {
RadEncPlane* p;
if (e->n_planes >= RAD_ENC_MAX_PLANES) return -1;
p = &e->plane[e->n_planes];
memset(p, 0, sizeof *p);
rad_enc_copy_str(p->role, role);
p->dtype = dtype;
p->kind = RAD_PLANE_TILED;
p->block[0] = block_rows;
p->block[1] = block_cols;
return e->n_planes++;
}
/* Append a TABLE plane of its own [rows x cols]. */
static inline int rad_enc_add_table(RadEncoding* e, const char* role, uint32_t dtype,
int64_t rows, int64_t cols) {
const int i = rad_enc_add_plane(e, role, dtype, 0, 0);
if (i < 0) return i;
e->plane[i].kind = RAD_PLANE_TABLE;
e->plane[i].extent[0] = rows;
e->plane[i].extent[1] = cols;
return i;
}
/* A weight stored as it is: one plane of `dtype`, one element a value. */
static inline RadEncoding rad_enc_plain(uint32_t dtype) {
RadEncoding e;
rad_enc_clear(&e);
rad_enc_copy_str(e.scheme, "plain");
rad_enc_add_plane(&e, "codes", dtype, 1, 1);
return e;
}
/* value = code * scale, one scale per [block_rows x block_cols]. Further planes go on with
* rad_enc_add_plane / rad_enc_add_table, and a transform with
* rad_enc_copy_str(e.transform, ...). */
static inline RadEncoding rad_enc_affine(uint32_t codes, uint32_t scale, int64_t block_rows,
int64_t block_cols) {
RadEncoding e;
rad_enc_clear(&e);
rad_enc_copy_str(e.scheme, "affine");
rad_enc_add_plane(&e, "codes", codes, 1, 1);
rad_enc_add_plane(&e, "scale", scale, block_rows, block_cols);
return e;
}
/* ================================================================== reading one */
static inline int rad_enc_is(const RadEncoding* e, const char* scheme) {
return e && strncmp(e->scheme, scheme, RAD_ENC_STR) == 0;
}
/* The index of the plane with this role, or -1. */
static inline int rad_enc_find(const RadEncoding* e, const char* role) {
int i;
if (!e || !role) return -1;
for (i = 0; i < e->n_planes; ++i)
if (strncmp(e->plane[i].role, role, RAD_ENC_STR) == 0) return i;
return -1;
}
/* The plane with this role, or null. */
static inline const RadEncPlane* rad_enc_plane(const RadEncoding* e, const char* role) {
const int i = rad_enc_find(e, role);
return i < 0 ? 0 : &e->plane[i];
}
/* The index of level `level` of a multiplied chain -- "scale", "scale.1", "scale.2" -- or -1. */
static inline int rad_enc_find_level(const RadEncoding* e, const char* base, int level) {
char r[RAD_ENC_STR];
if (level == 0) return rad_enc_find(e, base);
snprintf(r, sizeof r, "%s.%d", base, level);
return rad_enc_find(e, r);
}
/* Does `role` belong to the chain `base` ("scale" -> scale, scale.1, ...)? */
static inline int rad_enc_role_in_chain(const char* role, const char* base) {
const size_t n = strlen(base);
int lv = 0;
if (strncmp(role, base, n) != 0) return 0;
if (role[n] == 0) return 1;
return role[n] == '.' && sscanf(role + n + 1, "%d", &lv) == 1 && lv > 0;
}
/* The order N of an "fwhtN" transform, 0 when the transform is not one, -1 when it is malformed. */
static inline int64_t rad_enc_fwht(const RadEncoding* e) {
long long n = 0;
if (!e || strncmp(e->transform, "fwht", 4) != 0) return 0;
if (sscanf(e->transform + 4, "%lld", &n) != 1 || n < 2 || (n & (n - 1)) != 0) return -1;
return (int64_t)n;
}
/* Byte-for-byte equality, which is what two encodings agreeing means: the strings are
* zero-padded by construction, so there is nothing a memcmp could see that a reader cannot. */
static inline int rad_enc_equal(const RadEncoding* a, const RadEncoding* b) {
return a && b && memcmp(a, b, sizeof *a) == 0;
}
/* ================================================================== geometry */
/* The [rows, cols] a logical shape is seen as. */
static inline void rad_enc_view(uint32_t rank, const int64_t* shape, int64_t* rows,
int64_t* cols) {
uint32_t i;
int64_t r = 1;
if (rank == 0) { *rows = 1; *cols = 1; return; }
for (i = 0; i + 1 < rank; ++i) r *= shape[i];
*rows = r;
*cols = shape[rank - 1];
}
/* A plane's element extents over a [rows, cols] weight. */
static inline void rad_enc_plane_dims(const RadEncPlane* p, int64_t rows, int64_t cols,
int64_t* prows, int64_t* pcols) {
if (p->kind == RAD_PLANE_TABLE) {
*prows = p->extent[0];
*pcols = p->extent[1];
return;
}
*prows = p->block[0] > 0 ? (rows + p->block[0] - 1) / p->block[0] : 1;
*pcols = p->block[1] > 0 ? (cols + p->block[1] - 1) / p->block[1] : 1;
}
/* Bytes of one row of `n` elements: every row starts on a byte. 0 for a dtype the core does not
* size, which an encoding may never hold. */
static inline int64_t rad_enc_row_bytes(uint32_t dtype, int64_t n) {
return rad_dtype_bytes(dtype, n);
}
static inline int64_t rad_enc_plane_bytes(const RadEncPlane* p, int64_t rows, int64_t cols) {
int64_t pr, pc;
rad_enc_plane_dims(p, rows, cols, &pr, &pc);
return pr * rad_enc_row_bytes(p->dtype, pc);
}
/* How many values one code stands for: 1, or V for a vector code into a grid. */
static inline int64_t rad_enc_code_width(const RadEncoding* e) {
return (e && e->n_planes > 0 && e->plane[0].block[1] > 1) ? e->plane[0].block[1] : 1;
}
/* Is the encoding well formed? 1 if so.
*
* Every plane has a role and a core dtype, the "codes" plane comes first, is TILED and covers one
* row of one value -- or of V values when a grid of width V is there to expand it -- and the
* planes the affine scheme reads have the kinds it reads them as. A scheme the core does not
* define is checked for the first two only: its planes are its quantiser's business. */
static inline int rad_enc_valid(const RadEncoding* e) {
int i, g;
int64_t v;
const char* t;
if (!e || e->n_planes < 1 || e->n_planes > RAD_ENC_MAX_PLANES || !e->scheme[0]) return 0;
for (i = 0; i < e->n_planes; ++i) {
const RadEncPlane* p = &e->plane[i];
if (!p->role[0] || rad_dtype_bits(p->dtype) == 0) return 0;
if (p->kind == RAD_PLANE_TILED && (p->block[0] < 0 || p->block[1] < 0)) return 0;
if (p->kind == RAD_PLANE_TABLE && (p->extent[0] < 1 || p->extent[1] < 1)) return 0;
if (p->kind != RAD_PLANE_TILED && p->kind != RAD_PLANE_TABLE) return 0;
if (rad_enc_find(e, p->role) != i) return 0; /* roles are unique */
}
if (strncmp(e->plane[0].role, "codes", RAD_ENC_STR) != 0) return 0;
if (e->plane[0].kind != RAD_PLANE_TILED || e->plane[0].block[0] != 1) return 0;
if (rad_enc_is(e, "plain"))
return e->n_planes == 1 && !e->transform[0] && e->plane[0].block[1] == 1;
if (!rad_enc_is(e, "affine")) return e->plane[0].block[1] >= 1;
/* nothing beyond the codes is "plain", and one weight has one spelling */
if (e->n_planes == 1 && !e->transform[0]) return 0;
v = e->plane[0].block[1];
g = rad_enc_find(e, "grid");
if (v < 1) return 0;
if (g >= 0) {
if (e->plane[g].kind != RAD_PLANE_TABLE || e->plane[g].extent[1] != v) return 0;
} else if (v != 1) {
return 0;
}
if (rad_enc_find(e, "table") >= 0 && (g >= 0 || e->plane[rad_enc_find(e, "table")].kind
!= RAD_PLANE_TABLE)) return 0;
for (i = 1; i < e->n_planes; ++i) {
const RadEncPlane* p = &e->plane[i];
const int tiled = rad_enc_role_in_chain(p->role, "scale") ||
rad_enc_role_in_chain(p->role, "min") ||
!strncmp(p->role, "zero", RAD_ENC_STR) ||
!strncmp(p->role, "signs", RAD_ENC_STR);
const int table = !strncmp(p->role, "grid", RAD_ENC_STR) ||
!strncmp(p->role, "table", RAD_ENC_STR) || !strncmp(p->role, "t.", 2);
if (!tiled && !table) return 0; /* a role nothing reads */
if (tiled && p->kind != RAD_PLANE_TILED) return 0;
if (table && p->kind != RAD_PLANE_TABLE) return 0;
}
/* a chain level exists only above the one before it */
for (i = 1; i < e->n_planes; ++i) {
int lv = 0;
const char* r = e->plane[i].role;
const char* base = rad_enc_role_in_chain(r, "scale") ? "scale"
: rad_enc_role_in_chain(r, "min") ? "min" : 0;
if (!base || !strchr(r, '.')) continue;
sscanf(strchr(r, '.') + 1, "%d", &lv);
if (rad_enc_find_level(e, base, lv - 1) < 0) return 0;
}
if (rad_enc_find(e, "signs") >= 0 &&
(e->plane[rad_enc_find(e, "signs")].dtype != RAD_U1 ||
e->plane[rad_enc_find(e, "signs")].block[0] != 1 ||
e->plane[rad_enc_find(e, "signs")].block[1] != 1)) return 0;
t = e->transform;
if (!t[0]) return 1;
if (!strncmp(t, "fwht", 4)) return rad_enc_fwht(e) > 0;
if (!strcmp(t, "perm")) return rad_enc_find(e, "t.perm") > 0;
if (!strcmp(t, "givens"))
return rad_enc_find(e, "t.pairs") > 0 && rad_enc_find(e, "t.angle") > 0;
return 0;
}
/* ================================================================== the canonical spelling
*
* What a person, a log line and rad-info read. Kernels read the struct.
*
* plain <dtype> bf16
* affine, codes and scales <codes>*<scale>[RxC]*<scale.1>[RxC] fp4_e2m1*fp8_e4m3[1x16]*f32[*x*]
* with an integer zero ...-<zero>[RxC] u2*f16[1x128]-u8[1x128]
* anything else <scheme>:<role>=<dtype><shape>,... affine:codes=u4[1x1],...
* and a transform .../<transform> i4*bf16[1x128]/fwht128
*
* A block extent of 0 -- the whole extent -- is written `*`, and a TABLE plane's shape is written
* `{RxC}`. Returns the length written, like snprintf; the output is always terminated. */
static inline int rad_enc_shape_str(const RadEncPlane* p, char* buf, size_t n) {
char r[24], c[24];
if (p->kind == RAD_PLANE_TABLE)
return snprintf(buf, n, "{%lldx%lld}", (long long)p->extent[0], (long long)p->extent[1]);
if (p->block[0] > 0) snprintf(r, sizeof r, "%lld", (long long)p->block[0]);
else snprintf(r, sizeof r, "*");
if (p->block[1] > 0) snprintf(c, sizeof c, "%lld", (long long)p->block[1]);
else snprintf(c, sizeof c, "*");
return snprintf(buf, n, "[%sx%s]", r, c);
}
/* Codes, a scale chain and at most an integer zero: the shape that has a short spelling. */
static inline int rad_enc_is_simple_affine(const RadEncoding* e) {
int i, lv;
if (!rad_enc_is(e, "affine") || e->plane[0].block[1] != 1) return 0;
for (i = 1; i < e->n_planes; ++i) {
const char* r = e->plane[i].role;
if (!rad_enc_role_in_chain(r, "scale") && strncmp(r, "zero", RAD_ENC_STR) != 0 &&
strncmp(r, "t.", 2) != 0) return 0;
}
/* and the scales in level order, so the spelling is read the way it is multiplied */
for (i = 1, lv = 0; i < e->n_planes; ++i) {
if (!rad_enc_role_in_chain(e->plane[i].role, "scale")) continue;
if (rad_enc_find_level(e, "scale", lv++) != i) return 0;
}
return lv > 0;
}
static inline int rad_enc_format(const RadEncoding* e, char* buf, size_t n) {
char shp[64];
size_t at = 0;
int i;
#define RAD_ENC_PUT(...) \
do { \
int w_ = snprintf(buf + (at < n ? at : n), at < n ? n - at : 0, __VA_ARGS__); \
if (w_ > 0) at += (size_t)w_; \
} while (0)
if (!buf || n == 0) return 0;
buf[0] = 0;
if (!e || e->n_planes < 1) {
RAD_ENC_PUT("(none)");
} else if (rad_enc_is(e, "plain") && e->n_planes == 1) {
RAD_ENC_PUT("%s", rad_dtype_name(e->plane[0].dtype));
} else if (rad_enc_is_simple_affine(e)) {
RAD_ENC_PUT("%s", rad_dtype_name(e->plane[0].dtype));
for (i = 1; i < e->n_planes; ++i) {
if (!rad_enc_role_in_chain(e->plane[i].role, "scale")) continue;
rad_enc_shape_str(&e->plane[i], shp, sizeof shp);
RAD_ENC_PUT("*%s%s", rad_dtype_name(e->plane[i].dtype), shp);
}
i = rad_enc_find(e, "zero");
if (i > 0) {
rad_enc_shape_str(&e->plane[i], shp, sizeof shp);
RAD_ENC_PUT("-%s%s", rad_dtype_name(e->plane[i].dtype), shp);
}
} else {
RAD_ENC_PUT("%s:", e->scheme);
for (i = 0; i < e->n_planes; ++i) {
rad_enc_shape_str(&e->plane[i], shp, sizeof shp);
RAD_ENC_PUT("%s%s=%s%s", i ? "," : "", e->plane[i].role,
rad_dtype_name(e->plane[i].dtype), shp);
}
}
if (e && e->transform[0]) RAD_ENC_PUT("/%s", e->transform);
#undef RAD_ENC_PUT
return (int)at;
}
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif /* RAD_ENCODING_H */
+164
View File
@@ -0,0 +1,164 @@
/* rad_format.h -- the .rad container (spec.md §4.2).
*
* canonical, not kernel-shaped -- an entry is a LOGICAL weight holding the planes of its
* encoding (rad_encoding.h), row-major; no kernel library
* is named anywhere in the file, and the kernel that reads a
* weight rearranges it at load (spec §4.3)
* grouped by movement unit -- an expert's entries are adjacent, and addressing within a
* layer is base + id*stride
* aligned -- pool 2 MiB, movement unit 4 KiB, plane 256 B
* self-describing -- each entry carries its encoding, its logical shape and the
* quantiser and options that made it
*
* Little-endian only. Every offset is from the start of the file. Every string is an offset into
* the string blob, so the directory is fixed-stride and mmap-walkable without a parse.
*
* THERE IS ONE VERSION. A file in any other is refused with the instruction to convert again: the
* product has no installed base, and a second reader would be a second set of invariants. */
#ifndef RAD_FORMAT_H
#define RAD_FORMAT_H
#include "rad_types.h"
#include "rad_encoding.h"
#ifdef __cplusplus
extern "C" {
#endif
#define RAD_MAGIC 0x31444152u /* "RAD1" little-endian: the family; the version follows */
#define RAD_FORMAT_VER 2u
#define RAD_ALIGN_POOL (2u * 1024u * 1024u)
#define RAD_ALIGN_UNIT 4096u
#define RAD_ALIGN_SUB 256u
typedef uint64_t rad_stroff; /* offset into the string blob; 0 is the empty string */
/* ------------------------------------------------------------------ header */
typedef struct RadFileHeader {
uint32_t magic;
uint32_t version;
uint64_t file_bytes;
rad_stroff arch_id;
rad_stroff model_name;
rad_stroff quant; /* the source checkpoint's quantisation descriptor, "" for none:
* with arch_id, what selects the architecture plugin (spec §2.4) */
rad_stroff recipe; /* the recipe it was converted with, as text; "" for none */
rad_stroff created_by; /* rad-convert version + the source checkpoint's identity */
uint64_t str_off, str_bytes;
uint64_t meta_off, meta_count; /* RadFileKV[] */
uint64_t dir_off, dir_count; /* RadFileEntry[] */
uint64_t plane_off, plane_count; /* RadFilePlane[] */
uint64_t enc_off, enc_count; /* RadEncoding[], each distinct one once */
uint64_t vocab_off, vocab_bytes; /* RadVocabHeader + its payload */
uint64_t prof_off, prof_count; /* RadFileProfile[] -- expert popularity */
uint64_t data_off, data_bytes; /* the blob; RAD_ALIGN_POOL-aligned */
uint64_t reserved[8];
} RadFileHeader;
/* ------------------------------------------------------------------ metadata */
typedef struct RadFileKV {
rad_stroff key;
uint32_t type; /* RAD_P_INT | RAD_P_STR, or RAD_KV_F64 */
uint32_t pad;
union {
int64_t i;
double f;
rad_stroff s;
} v;
} RadFileKV;
enum { RAD_KV_F64 = 100 };
/* ------------------------------------------------------------------ weight directory */
/* One LOGICAL weight: what a declaration's `source` names (RadWeightDecl). Fixed stride, so an
* expert's address inside a layer is base + id*stride and no table is walked on the critical
* path. */
typedef struct RadFileEntry {
rad_stroff name; /* the logical weight's name */
rad_stroff quantizer; /* the quantiser that wrote the planes; "" for the checkpoint's own */
rad_stroff options; /* the options it ran with, "k=v,k=v" sorted by key */
uint32_t enc; /* index into the encoding table */
uint32_t rank;
int64_t shape[RAD_MAX_RANK]; /* the LOGICAL shape */
int32_t layer; /* RadWeightGroup, flattened: the movement unit */
int32_t expert;
int32_t slot;
uint32_t n_planes; /* the encoding's, in its order */
uint64_t plane_first; /* index into the plane table */
uint64_t offset; /* the entry's first byte, from file start, RAD_ALIGN_UNIT-aligned */
uint64_t bytes; /* to the end of its last plane */
uint64_t reserved[2];
} RadFileEntry;
/* One plane of an entry: dense, row-major, every row starting on a byte, exactly
* rad_enc_plane_bytes() long for the entry's logical shape. */
typedef struct RadFilePlane {
uint64_t offset; /* from file start, RAD_ALIGN_SUB-aligned */
uint64_t bytes;
} RadFilePlane;
/* ------------------------------------------------------------------ expert profile */
/* Derived from the imatrix's activation counts. A WARM START, not a policy (spec §5.3): what a
* calibration set routes to is not what decoding routes to, so this is worth a small improvement
* in residency hit rate over starting cold and no more. */
typedef struct RadFileProfile {
int32_t layer;
int32_t expert;
float share; /* fraction of tokens routed here in the calibration set */
float reserved;
} RadFileProfile;
/* ------------------------------------------------------------------ vocab */
/* rad-convert interprets tokenizer.json properly and bakes the result here, rather than hashing
* the file against a hardcoded enum the way llama.cpp does (spec §12). */
enum { RAD_TOK_BPE = 1, RAD_TOK_UNIGRAM = 2, RAD_TOK_WORDPIECE = 3, RAD_TOK_RWKV = 4 };
/* Normaliser / pre-tokeniser / decoder steps, in declared order. */
enum {
RAD_NORM_NFC = 1, RAD_NORM_NFKC = 2, RAD_NORM_NFD = 3, RAD_NORM_NFKD = 4,
RAD_NORM_LOWERCASE = 5, RAD_NORM_STRIP = 6, RAD_NORM_REPLACE = 7, RAD_NORM_PREPEND = 8,
RAD_PRE_BYTELEVEL = 32, RAD_PRE_SPLIT = 33, RAD_PRE_METASPACE = 34,
RAD_PRE_WHITESPACE = 35, RAD_PRE_PUNCTUATION = 36, RAD_PRE_DIGITS = 37,
RAD_PRE_BYTE_FALLBACK = 38,
RAD_DEC_BYTELEVEL = 64, RAD_DEC_METASPACE = 65, RAD_DEC_REPLACE = 66,
RAD_DEC_STRIP = 67, RAD_DEC_FUSE = 68, RAD_DEC_BYTE_FALLBACK = 69
};
typedef struct RadVocabStep {
uint32_t kind; /* RAD_NORM_* | RAD_PRE_* | RAD_DEC_* */
uint32_t flags; /* step-specific: invert, add_prefix_space, use_regex, ... */
rad_stroff arg0; /* a pattern, a replacement, a prepend string */
rad_stroff arg1;
int64_t iarg;
} RadVocabStep;
typedef struct RadVocabHeader {
uint32_t kind; /* RAD_TOK_* */
uint32_t n_tokens;
uint32_t n_merges;
uint32_t n_steps;
uint64_t tok_text_off; /* rad_stroff[n_tokens] */
uint64_t tok_score_off; /* float[n_tokens], unigram only */
uint64_t tok_type_off; /* uint8[n_tokens]: normal/unknown/control/user/byte */
uint64_t merge_off; /* uint32[n_merges][2] */
uint64_t step_off; /* RadVocabStep[n_steps] */
int32_t bos, eos, eot, pad_id, unk, sep;
uint32_t add_bos, add_eos;
rad_stroff chat_template;
uint64_t reserved[4];
} RadVocabHeader;
enum { RAD_TT_NORMAL = 1, RAD_TT_UNKNOWN = 2, RAD_TT_CONTROL = 3,
RAD_TT_USER_DEFINED = 4, RAD_TT_BYTE = 6 };
#ifdef __cplusplus
}
#endif
#endif /* RAD_FORMAT_H */
+520
View File
@@ -0,0 +1,520 @@
/* rad_plugin.h -- everything a kernel or architecture plugin needs and cannot link.
*
* ===================================================================== WHY THIS FILE EXISTS
*
* A plugin is a shared object that exports the symbols in rad_abi.h and links NOTHING of
* radiance's. That boundary is fixed. What it leaves an author with, though, is the raw structs
* and nothing else -- so without this header every plugin arrives independently at the same dozen
* helpers: an optional-operand fetch, a parameter-with-default, a contiguity test, a row pitch,
* and f32<->bf16, f32<->f16 and f32<->fp8 conversions.
*
* Two of those are not merely a duplication of effort. The narrowing conversions define what a
* result IS: libref's contract is f32 accumulation, IEEE round-to-nearest-even, no FMA and
* no reassociation, and a plugin whose bf16 rounding truncates instead of rounding to even does
* not reproduce the reference and cannot be checked against it. That convention belongs in the
* ABI, stated once, not rediscovered per plugin. And the meaning of an ABSENT OPTIONAL OPERAND --
* a null RadTensor.data, not a short operand count -- is a rule you get wrong silently: read the
* operand after it and every weight in the model shifts by one.
*
* ===================================================================== WHAT IS AND IS NOT HERE
*
* Here: pure, total, header-only functions over the ABI's own types. Nothing allocates, nothing
* has state, nothing calls back into the core, and nothing may ever start.
*
* Not here: anything that needs the core. A plugin that wants a device allocation, a stream or a
* builder handle calls the functions in rad_device.h / rad_builder.h / rad_runtime.h, which the
* host exports because it must -- those genuinely cannot be inlined, and the loader's ABI check
* is what keeps them honest.
*
* This header is OPTIONAL. A plugin that includes only rad_abi.h is complete and correct; this
* is convenience and one shared definition of the rounding, not a requirement.
*
* Pure C, like the rest of abi/. See spec.md 2.
*/
#ifndef RAD_PLUGIN_H
#define RAD_PLUGIN_H
#include "rad_abi.h"
#include <string.h>
#ifdef __cplusplus
extern "C" {
#endif
/* ================================================================== parameters
*
* Two families, because a plugin is asked for things in two shapes. `launch` and `scratch` get a
* RadArgs; `layout`, `relayout`, `unrelayout` and `opd_shape` get a bare (const RadParam*, int)
* pair with no tensors at all. Both are the same lookup and neither should be written twice. */
static inline const RadParam* rad_param_find(const RadParam* p, int n_p, const char* key) {
if (!p || !key) return 0;
for (int i = 0; i < n_p; ++i)
if (p[i].key && strcmp(p[i].key, key) == 0) return &p[i];
return 0;
}
/* An int parameter, or `dflt` if the key is absent or is not an int.
*
* A RANGE is deliberately NOT accepted here. A ranged parameter is the one axis a declared op is
* bucketed over, and by the time a kernel runs it has been resolved to a value -- so a range
* arriving at a launch is a selection bug, and quietly returning its low bound would hide it. */
static inline long long rad_param_geti(const RadParam* p, int n_p, const char* key,
long long dflt) {
const RadParam* f = rad_param_find(p, n_p, key);
return (f && f->kind == RAD_P_INT) ? f->ival : dflt;
}
/* THE SAME PARAMETER READ BY A SHAPE HOOK RATHER THAN BY A LAUNCH, which is the one place a range
* is legitimate and must be read as its HIGH bound.
*
* `opd_shape` is called to size buffers BEFORE selection has collapsed anything: a tool asking
* "how big is this operand" over a banded op is describing the whole band, and the arena has to
* hold it. The low end fits inside the high end, so ihi is the answer and rad_param_geti's refusal
* -- correct for a launch, where a surviving range is a selection bug -- is wrong here.
*
* Anyone writing a shape hook needs this on the first one they write, which is why it belongs in
* the ABI rather than once per plugin. */
static inline long long rad_param_getdim(const RadParam* p, int n_p, const char* key,
long long dflt) {
const RadParam* f = rad_param_find(p, n_p, key);
if (!f) return dflt;
if (f->kind == RAD_P_INT) return f->ival;
if (f->kind == RAD_P_RANGE) return f->ihi;
return dflt;
}
static inline const char* rad_param_gets(const RadParam* p, int n_p, const char* key,
const char* dflt) {
const RadParam* f = rad_param_find(p, n_p, key);
return (f && f->kind == RAD_P_STR && f->sval) ? f->sval : dflt;
}
static inline double rad_param_getf(const RadParam* p, int n_p, const char* key, double dflt) {
const RadParam* f = rad_param_find(p, n_p, key);
return (f && f->kind == RAD_P_F64) ? f->dval : dflt;
}
/* The dtype a parameter names, parsed. RAD_DT_INVALID if the key is absent or unrecognised --
* which a kernel should treat as a refusal, because a dtype it cannot name is one it cannot
* read. */
static inline uint32_t rad_param_getdt(const RadParam* p, int n_p, const char* key) {
return rad_dtype_parse(rad_param_gets(p, n_p, key, 0));
}
/* The RadArgs forms. rad_args_geti/gets are in rad_abi.h and return presence; these return the
* value with a default, which is what a launch almost always wants. */
static inline long long rad_args_geti_or(const RadArgs* a, const char* key, long long dflt) {
long long v = 0;
return (a && rad_args_geti(a, key, &v)) ? v : dflt;
}
static inline const char* rad_args_gets_or(const RadArgs* a, const char* key, const char* dflt) {
const char* s = a ? rad_args_gets(a, key) : 0;
return s ? s : dflt;
}
static inline double rad_args_getf_or(const RadArgs* a, const char* key, double dflt) {
return a ? rad_param_getf(a->p, a->n_p, key, dflt) : dflt;
}
/* ================================================================== operands
*
* THE ABSENT-OPERAND RULE, WHICH IS THE EASIEST THING IN THIS ABI TO GET WRONG.
*
* An optional operand a call does not pass is a RadTensor whose `data` is null -- NOT a shorter
* `n_t`. The distinction is load-bearing because operands are POSITIONAL: if a plugin treated
* absence as "the array is shorter" it would read operand i+1 where operand i was meant, and for
* a weight that means every weight after it is off by one. Nothing in the arithmetic would fault;
* the model would simply produce wrong numbers.
*
* So: one entry per schema operand, always, and this returns null for both spellings of absent --
* past the end, or present with no data. A caller that needs to tell those apart has a schema
* disagreement rather than an absent operand, and should say so. */
static inline const RadTensor* rad_arg_in(const RadArgs* a, int i) {
if (!a || !a->t || i < 0 || i >= a->n_t) return 0;
return a->t[i].data ? &a->t[i] : 0;
}
/* THERE IS NO rad_arg_out, AND THAT IS THE ABI SPEAKING RATHER THAN AN OMISSION. RadArgs::t is a
* `const RadTensor*`: the DESCRIPTORS are const, and a kernel writes an output through the
* non-const `void* data` inside one. So an output operand is fetched exactly like an input and
* the constness a caller sees is the same either way. A separate accessor would have to cast the
* descriptor's constness away and would be advertising a promise the ABI does not make. */
/* Are the first `n` operands all present? The usual opening line of a launch, where the required
* ones are a prefix. */
static inline int rad_args_have(const RadArgs* a, int n) {
for (int i = 0; i < n; ++i) if (!rad_arg_in(a, i)) return 0;
return 1;
}
/* ================================================================== tensor shape helpers */
/* [rows..., K] flattened to (M, K): every leading axis is a row count and only the last is
* structural. This is what a kernel that owns whole rows -- one workgroup per row -- wants.
* Returns 0 on a rank-0 tensor. */
static inline int64_t rad_tensor_rows(const RadTensor* t) {
if (!t || t->rank == 0) return 0;
int64_t m = 1;
for (uint32_t i = 0; i + 1 < t->rank; ++i) m *= t->shape[i];
return m;
}
static inline int64_t rad_tensor_lastdim(const RadTensor* t) {
return (t && t->rank > 0) ? t->shape[t->rank - 1] : 0;
}
/* The element distance between consecutive rows. For a contiguous tensor this is the last extent;
* for a strided one it is the stride of the second-to-last axis, which is the pitch a row-owning
* kernel has to honour. Strides are in ELEMENTS, not bytes (rad_types.h). */
static inline int64_t rad_tensor_row_pitch(const RadTensor* t) {
if (!t || t->rank == 0) return 0;
if (t->rank == 1) return t->shape[0];
return t->stride[t->rank - 2];
}
/* Is `p` aligned to `bytes`? Kernels that issue wide loads need this and the ABI does not promise
* it -- alignment is one of the things a constraint row cannot express, so it is checked in the
* entry point (rad_types.h: constraints are necessary, not sufficient). */
static inline int rad_ptr_aligned(const void* p, int64_t bytes) {
return bytes > 0 && ((uintptr_t)p % (uintptr_t)bytes) == 0;
}
/* ================================================================== narrowing conversions
*
* THESE DEFINE WHAT A RESULT IS, so they are stated once here rather than per plugin.
*
* libref's contract -- and therefore the definition every kernel is checked against -- is
* f32 accumulation, IEEE round-to-nearest-ties-to-even, no fused multiply-add and no
* reassociation. `-ffp-contract=off` is a CORRECTNESS flag in this project, not a tuning one. A
* plugin whose bf16 narrowing truncates instead of rounding to even is off by up to one ulp on
* every element, which is not a tolerance question: it means the plugin cannot reproduce the
* reference and cannot be checked against it.
*
* Every one of these is exact in the widening direction and RTNE in the narrowing direction, and
* each handles subnormals rather than flushing them -- the hardware decodes subnormals correctly,
* and flushing loses the smallest block of every quantised weight. */
static inline float rad_bf16_to_f32(uint16_t h) {
uint32_t u = (uint32_t)h << 16;
float f;
memcpy(&f, &u, 4);
return f;
}
/* The `(u >> 16) & 1` is the tie-break: it adds one more than the halfway point exactly when the
* surviving bit is odd, which is what sends a tie up rather than down. Overflow falls out --
* 0x7f7fffff plus the rounding carries into 0x7f80, the bf16 infinity -- and a NaN is forced
* quiet rather than allowed to round into an infinity. */
static inline uint16_t rad_f32_to_bf16(float f) {
uint32_t u;
memcpy(&u, &f, 4);
if ((u & 0x7fffffffu) > 0x7f800000u) return (uint16_t)((u >> 16) | 0x0040u);
return (uint16_t)((u + 0x7fffu + ((u >> 16) & 1u)) >> 16);
}
static inline float rad_f16_to_f32(uint16_t h) {
uint32_t s = (uint32_t)(h >> 15) << 31;
uint32_t e = (uint32_t)(h >> 10) & 0x1fu;
uint32_t m = (uint32_t)h & 0x3ffu;
uint32_t u;
if (e == 0u) {
if (m == 0u) {
u = s;
} else {
int sh = 0; /* subnormal: renormalise into f32's range */
while (!(m & 0x400u)) { m <<= 1; ++sh; }
m &= 0x3ffu;
u = s | ((uint32_t)(127 - 15 - sh + 1) << 23) | (m << 13);
}
} else if (e == 0x1fu) {
u = s | 0x7f800000u | (m << 13);
} else {
u = s | ((e - 15u + 127u) << 23) | (m << 13);
}
float f;
memcpy(&f, &u, 4);
return f;
}
/* RTNE, with subnormals and overflow-to-infinity handled explicitly rather than by leaning on a
* hardware convert whose mode a caller could have changed. */
static inline uint16_t rad_f32_to_f16(float f) {
uint32_t u;
memcpy(&u, &f, 4);
uint32_t s = (u >> 16) & 0x8000u;
uint32_t a = u & 0x7fffffffu;
if (a >= 0x7f800000u) /* inf or nan */
return (uint16_t)(s | 0x7c00u | (a > 0x7f800000u ? ((a >> 13) & 0x3ffu) | 0x200u : 0u));
if (a >= 0x47800000u) return (uint16_t)(s | 0x7c00u); /* overflow -> inf */
if (a < 0x33000000u) return (uint16_t)s; /* underflow -> zero */
{
int e = (int)(a >> 23) - 127;
uint32_t m = a & 0x7fffffu;
if (e < -14) { /* subnormal half */
int sh = -14 - e + 13;
uint32_t lo, q, half;
m |= 0x800000u;
lo = m & ((1u << sh) - 1u);
q = m >> sh;
half = 1u << (sh - 1);
if (lo > half || (lo == half && (q & 1u))) ++q;
return (uint16_t)(s | q);
}
{
uint32_t q = m >> 13;
uint32_t lo = m & 0x1fffu;
uint32_t he;
if (lo > 0x1000u || (lo == 0x1000u && (q & 1u))) ++q;
he = (uint32_t)(e + 15);
if (q == 0x400u) { q = 0; ++he; } /* rounding carried into the exp */
if (he >= 0x1fu) return (uint16_t)(s | 0x7c00u);
return (uint16_t)(s | (he << 10) | q);
}
}
}
/* OCP fp8 e4m3 ("e4m3fn"): 1-4-3, bias 7, NO infinity, S1111111 is the only NaN, max 448. This is
* the KV-cache format and the block-scaled weight format, so its rounding sits on the attention
* oracle's critical path and on every fp8 GEMM's. */
static inline float rad_fp8e4m3_to_f32(uint8_t b) {
uint32_t s = (uint32_t)(b >> 7) << 31;
uint32_t e = (uint32_t)(b >> 3) & 0xfu;
uint32_t m = (uint32_t)b & 0x7u;
uint32_t u;
if (e == 0u) {
if (m == 0u) {
u = s;
} else {
int sh = 0;
while (!(m & 0x8u)) { m <<= 1; ++sh; }
m &= 0x7u;
u = s | ((uint32_t)(127 - 6 - sh) << 23) | (m << 20);
}
} else if (e == 0xfu && m == 0x7u) {
u = s | 0x7fc00000u; /* the single NaN encoding */
} else {
u = s | ((e - 7u + 127u) << 23) | (m << 20);
}
float f;
memcpy(&f, &u, 4);
return f;
}
/* SATURATES at 448 rather than overflowing. Returning a NaN for a large activation would turn one
* outlier into a poison that spreads through the whole row, and every fp8 cast in this project
* clamps for that reason. */
static inline uint8_t rad_f32_to_fp8e4m3(float f) {
uint32_t u;
memcpy(&u, &f, 4);
{
uint8_t s = (uint8_t)((u >> 24) & 0x80u);
uint32_t a = u & 0x7fffffffu;
int e;
uint32_t m;
if (a > 0x7f800000u) return (uint8_t)(s | 0x7fu); /* nan */
if (a >= 0x43e00000u) return (uint8_t)(s | 0x7eu); /* >= 448: clamp to the largest */
e = (int)(a >> 23) - 127;
m = a & 0x7fffffu;
/* The smallest subnormal is 2^-9, so everything under HALF of it -- exponent -11 and
* below -- rounds to zero. Exponent -10 is [2^-10, 2^-9): its tie point 2^-10 rounds to
* the even zero and the rest of it up to 2^-9, which the subnormal branch does with a
* 24-bit shift. */
if (e < -10) return s;
if (e < -6) { /* subnormal fp8 */
int sh = -6 - e + 20;
uint32_t lo, q, half;
m |= 0x800000u;
lo = m & ((1u << sh) - 1u);
q = m >> sh;
half = 1u << (sh - 1);
if (lo > half || (lo == half && (q & 1u))) ++q;
return (uint8_t)(s | q);
}
{
uint32_t q = m >> 20;
uint32_t lo = m & 0xfffffu;
int ee;
if (lo > 0x80000u || (lo == 0x80000u && (q & 1u))) ++q;
ee = e + 7;
if (q == 0x8u) { q = 0; ++ee; }
if (ee > 15 || (ee == 15 && q >= 7u)) return (uint8_t)(s | 0x7eu);
return (uint8_t)(s | ((uint32_t)ee << 3) | q);
}
}
}
/* fp8 e5m2: 1-5-2, bias 15, IEEE-shaped -- it has infinities and NaNs, unlike e4m3fn. It is the
* top byte of an f16, so both directions go through the f16 path and the narrowing rounds to even
* a SECOND time on the way down. */
static inline float rad_fp8e5m2_to_f32(uint8_t b) {
return rad_f16_to_f32((uint16_t)((uint16_t)b << 8));
}
static inline uint8_t rad_f32_to_fp8e5m2(float f) {
uint16_t h = rad_f32_to_f16(f);
uint16_t lo = (uint16_t)(h & 0xffu);
uint16_t q = (uint16_t)(h >> 8);
if (lo > 0x80u || (lo == 0x80u && (q & 1u))) ++q;
return (uint8_t)q;
}
/* OCP FP4 e2m1: 1-2-1, bias 1, no infinity and no NaN, so every one of the sixteen codes is a
* number and the largest is 6. */
static inline float rad_fp4e2m1_to_f32(uint8_t nib) {
static const float mag[8] = { 0.0f, 0.5f, 1.0f, 1.5f, 2.0f, 3.0f, 4.0f, 6.0f };
return (nib & 8u) ? -mag[nib & 7u] : mag[nib & 7u];
}
/* OCP FP6, both forms. No infinity and no NaN; e2m3 has bias 1 and tops out at 7.5, e3m2 has
* bias 3 and tops out at 28. */
static inline float rad_fp6_to_f32(uint8_t c, int ebits) {
const int mbits = 5 - ebits, bias = ebits == 2 ? 1 : 3;
const int e = (c >> mbits) & ((1 << ebits) - 1), m = c & ((1 << mbits) - 1);
const float frac = (float)m / (float)(1 << mbits);
const float pow2 = e >= bias ? (float)(1 << (e - bias)) : 1.0f / (float)(1 << (bias - e));
const float mag = e == 0 ? frac / (float)(1 << (bias - 1)) : (1.0f + frac) * pow2;
return (c & 0x20) ? -mag : mag;
}
/* THE BIT STREAM, for every element narrower than a byte or not a power of two wide.
*
* Element `i` of a b-bit row occupies bits [i*b, (i+1)*b) counted from bit 0 of `base`, lowest
* first, so it may straddle a byte; the read touches only the bytes the element is in. Widths to
* 16 bits. rad_encoding.h is where the order is defined. */
static inline uint32_t rad_load_bits(const void* base, int bits, int64_t i) {
const uint8_t* b8 = (const uint8_t*)base;
const int64_t o = i * (int64_t)bits;
const int64_t byte = o >> 3;
const int sh = (int)(o & 7);
uint32_t w = b8[byte];
if (sh + bits > 8) w |= (uint32_t)b8[byte + 1] << 8;
if (sh + bits > 16) w |= (uint32_t)b8[byte + 2] << 16;
return (w >> sh) & ((1u << bits) - 1u);
}
static inline void rad_store_bits(void* base, int bits, int64_t i, uint32_t code) {
uint8_t* b8 = (uint8_t*)base;
const int64_t o = i * (int64_t)bits;
int64_t byte = o >> 3;
int sh = (int)(o & 7), left = bits;
code &= (1u << bits) - 1u;
while (left > 0) {
const int take = 8 - sh < left ? 8 - sh : left;
const uint8_t m = (uint8_t)(((1u << take) - 1u) << sh);
b8[byte] = (uint8_t)((b8[byte] & ~m) | ((code << sh) & m));
code >>= take;
left -= take;
sh = 0;
++byte;
}
}
/* Signed widths from the table, sign-extended from the stream; 0 for a dtype that is not a
* packed integer. */
static inline int rad_dtype_packed_int(uint32_t dt, int* is_signed) {
switch (dt) {
case RAD_I2: case RAD_I3: case RAD_I4: case RAD_I5: case RAD_I6: case RAD_I7:
*is_signed = 1; return rad_dtype_bits(dt);
case RAD_U1: case RAD_U2: case RAD_U3: case RAD_U4: case RAD_U5: case RAD_U6:
case RAD_U7: case RAD_U9: case RAD_U10: case RAD_U11: case RAD_U12:
*is_signed = 0; return rad_dtype_bits(dt);
default:
*is_signed = 0; return 0;
}
}
/* OCP E8M0: a bare biased exponent, 2^(e-127), with 0xFF the NaN. Exact in f32 except at the two
* ends, where 2^-127 is subnormal and still exact and 2^128 does not exist. */
static inline float rad_e8m0_to_f32(uint8_t e) {
uint32_t u;
float f;
if (e == 0xffu) u = 0x7fc00000u;
else if (e == 0u) u = 0x00400000u; /* 2^-127, the one subnormal */
else u = (uint32_t)e << 23;
memcpy(&f, &u, 4);
return f;
}
/* ================================================================== dtype-generic access
*
* Load or store element `i` of a plane as f32, whatever it is stored as. This is what a host
* kernel and a converter both need, and it is the one place the dtype enum and the conversions
* above are wired together -- so a plugin that adds support for a dtype adds it once. Returns 0
* for a dtype it cannot read, which a caller must treat as a refusal rather than as a value.
*
* A SUB-BYTE `i` COUNTS ELEMENTS FROM `base`, which is right inside one row and wrong across rows
* whose element count does not fill their last byte: a row starts on a byte (rad_encoding.h), so
* a caller crossing rows steps `base` a row's bytes at a time. */
static inline float rad_load_f32(const void* base, uint32_t dtype, int64_t i) {
const uint8_t* b8 = (const uint8_t*)base;
int sgn = 0;
const int pb = rad_dtype_packed_int(dtype, &sgn);
if (pb) {
const uint32_t c = rad_load_bits(base, pb, i);
return sgn ? (float)((int32_t)(c ^ (1u << (pb - 1))) - (int32_t)(1u << (pb - 1)))
: (float)c;
}
switch (dtype) {
case RAD_FP4E2M1: return rad_fp4e2m1_to_f32((uint8_t)rad_load_bits(base, 4, i));
case RAD_FP6E2M3: return rad_fp6_to_f32((uint8_t)rad_load_bits(base, 6, i), 2);
case RAD_FP6E3M2: return rad_fp6_to_f32((uint8_t)rad_load_bits(base, 6, i), 3);
case RAD_E8M0: return rad_e8m0_to_f32(b8[i]);
case RAD_U16: return (float)((const uint16_t*)base)[i];
case RAD_F32: return ((const float*)base)[i];
case RAD_F16: return rad_f16_to_f32(((const uint16_t*)base)[i]);
case RAD_BF16: return rad_bf16_to_f32(((const uint16_t*)base)[i]);
case RAD_F8E4M3: return rad_fp8e4m3_to_f32(((const uint8_t*)base)[i]);
case RAD_F8E5M2: return rad_fp8e5m2_to_f32(((const uint8_t*)base)[i]);
case RAD_I8: return (float)((const int8_t*)base)[i];
case RAD_U8: return (float)((const uint8_t*)base)[i];
case RAD_I16: return (float)((const int16_t*)base)[i];
case RAD_I32: return (float)((const int32_t*)base)[i];
case RAD_U32: return (float)((const uint32_t*)base)[i];
case RAD_I64: return (float)((const int64_t*)base)[i];
case RAD_BOOL: return ((const uint8_t*)base)[i] ? 1.0f : 0.0f;
default: return 0.0f;
}
}
/* Store the raw CODE of element `i` of a sub-byte or byte plane -- the bit pattern, already
* chosen, masked to the dtype's width -- leaving its neighbours in the same byte alone. A signed
* code is passed as its value (-8..7 for i4) and stored two's complement. The quantisers' half of
* rad_load_f32; nothing rounds here. Returns 0 for a dtype wider than 16 bits. */
static inline int rad_store_code(void* base, uint32_t dtype, int64_t i, int code) {
const int bits = rad_dtype_bits(dtype);
if (bits < 1 || bits > 16) return 0;
if (bits == 16) { ((uint16_t*)base)[i] = (uint16_t)code; return 1; }
if (bits == 8) { ((uint8_t*)base)[i] = (uint8_t)code; return 1; }
rad_store_bits(base, bits, i, (uint32_t)code);
return 1;
}
static inline void rad_store_f32(void* base, uint32_t dtype, int64_t i, float v) {
switch (dtype) {
case RAD_F32: ((float*)base)[i] = v; break;
case RAD_F16: ((uint16_t*)base)[i] = rad_f32_to_f16(v); break;
case RAD_BF16: ((uint16_t*)base)[i] = rad_f32_to_bf16(v); break;
case RAD_F8E4M3: ((uint8_t*)base)[i] = rad_f32_to_fp8e4m3(v); break;
case RAD_F8E5M2: ((uint8_t*)base)[i] = rad_f32_to_fp8e5m2(v); break;
case RAD_I8: ((int8_t*)base)[i] = (int8_t)v; break;
case RAD_U8: ((uint8_t*)base)[i] = (uint8_t)v; break;
case RAD_I16: ((int16_t*)base)[i] = (int16_t)v; break;
case RAD_I32: ((int32_t*)base)[i] = (int32_t)v; break;
case RAD_U32: ((uint32_t*)base)[i] = (uint32_t)v; break;
case RAD_I64: ((int64_t*)base)[i] = (int64_t)v; break;
case RAD_BOOL: ((uint8_t*)base)[i] = v != 0.0f ? 1u : 0u; break;
default: break;
}
}
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif /* RAD_PLUGIN_H */
+116
View File
@@ -0,0 +1,116 @@
/* rad_quant.h -- the quantiser plugin ABI. spec.md §4.5.
*
* A quantiser turns a weight, handed to it in f32, into the planes of an ENCODING (rad_encoding.h).
* It is the third plugin kind beside kernels and architectures, loaded from
* $RADIANCE_HOME/quantizers, and it is the only place a weight's numbers are chosen: a kernel
* rearranges planes it is given (rad_abi.h, RadRelayoutFn) and never quantises.
*
* rad-convert drives quantisers through a RECIPE -- ordered rules from a logical weight name to a
* quantiser and its options (spec §4.4). For each weight a rule picks, it asks the quantiser which
* encoding it would write (`encoding`), lets the architecture plugin declare against that, and
* then hands the weight over in row blocks (`row_block`, `quantize`), so a 51 GB table streams.
*
* WHAT A QUANTISER IS GIVEN. The weight's logical name, shape and movement group, and when the
* converter has an imatrix, the weight's column importances. Anything else it calibrates on -- a
* GPTQ Hessian, AutoRound's activations -- is an option it reads itself (`calib=DIR`): what a
* Hessian is and how it is stored is the quantiser's business, exactly as a layout is a kernel's.
*
* WHAT IT HANDS BACK is the canonical planes and nothing else, so its output is readable by every
* kernel library that accepts the encoding and by the core's own decoder -- which is how rad-convert
* measures its error without knowing what it did.
*
* Pure C, like the rest of abi/.
*/
#ifndef RAD_QUANT_H
#define RAD_QUANT_H
#include "rad_abi.h"
#include "rad_encoding.h"
#ifdef __cplusplus
extern "C" {
#endif
/* What a quantiser is told about the weight it is quantising. */
typedef struct RadQuantWeight {
const char* name; /* the logical (declared) name: "blk.7.ffn_down_exps.3.weight" */
uint32_t rank;
int64_t shape[RAD_MAX_RANK]; /* the logical shape */
int64_t rows, cols; /* the [rows, cols] view every plane is laid over */
/* The movement group; -1 for none. -1 also when `encoding` is asked at declare, which runs
* before the weight's group exists -- so an encoding may depend on the name and the shape and
* not on these, and rad-convert refuses a quantiser whose answer moves once it is told. */
int32_t layer, expert;
/* The imatrix's column importances for this weight -- a second moment of its input, one a
* column -- or null when the converter has none. Per expert where the imatrix has the form. */
const float* importance;
} RadQuantWeight;
/* One option a quantiser takes, for `rad-convert --list-quantizers` and for typing a recipe's
* `key=value` text before the quantiser sees it: an option declared RAD_P_INT arrives as an int,
* RAD_P_F64 as a double, RAD_P_STR as the text. An option a recipe gives and the table does not
* name is refused by the converter, by name, before anything is quantised. */
typedef struct RadQuantOption {
const char* key;
int type; /* RAD_P_INT | RAD_P_F64 | RAD_P_STR */
const char* deflt; /* the default, as text; null for none */
const char* doc;
} RadQuantOption;
/* The encoding this quantiser writes for `w` under options `o`. RAD_E_UNSUPPORTED declines -- a
* weight it does not quantise, like a rank-1 norm -- and the converter moves on to the next rule;
* any other failure is an error in the recipe, said with the weight's name. */
typedef int (*RadQuantEncodingFn)(const RadParam* o, int n_o, const RadQuantWeight* w,
RadEncoding* out);
/* The rows one `quantize` call may take: every call but the last gets a multiple of this, starting
* on a multiple of it. 0 means the whole weight in one call -- what anything with a cross-row
* decision needs (a per-tensor scale it derives, a rotation it learns, a Hessian it shares). It must
* be a multiple of every TILED plane's block rows. */
typedef int64_t (*RadQuantRowBlockFn)(const RadParam* o, int n_o, const RadQuantWeight* w);
/* Quantise logical rows [row0, row0 + rows) of `w`, given as f32 [rows, cols] in `src`, into the
* planes. `planes[i]` points at the element row of plane i that covers logical row `row0` -- for a
* TILED plane of block rows br that is row row0 / br, for a plane covering the whole extent and for
* a TABLE plane it is the plane's start -- and the call writes exactly the rows its block covers.
* The buffers arrive zeroed. `src` may be modified. */
typedef int (*RadQuantizeFn)(const RadParam* o, int n_o, const RadQuantWeight* w,
float* src, int64_t row0, int64_t rows, void* const* planes);
/* Decode rows [row0, row0 + rows) back to f32 [rows, cols], for an encoding whose scheme the core
* does not decode. Null for a quantiser that writes only "plain" and "affine", which the core
* decodes itself. `planes[i]` points at plane i's start.
*
* It is how a scheme of a quantiser's own is READ: the oracle checking a kernel against the
* reference, rad-kbench drawing a weight, rad-convert measuring the quantiser's error all decode
* through it. The core asks every loaded quantiser that has one, in load order, and takes the
* first answer that is not RAD_E_UNSUPPORTED -- so a decoder answers RAD_E_UNSUPPORTED for an
* encoding it did not write. `w` names the weight where the caller knows it; a decoder must not
* need more than the encoding, `rows` and `cols`, because the oracle knows no more. */
typedef int (*RadQuantDecodeFn)(const RadEncoding* e, const RadQuantWeight* w,
const void* const* planes, int64_t row0, int64_t rows,
float* out);
typedef struct RadQuantizerInfo {
const char* name; /* what a recipe names: "fp8-block", "int", "gptq" */
const char* doc;
const RadQuantOption* options;
int n_options;
RadQuantEncodingFn encoding;
RadQuantRowBlockFn row_block;
RadQuantizeFn quantize;
RadQuantDecodeFn decode; /* optional */
} RadQuantizerInfo;
/* Every quantiser plugin exports these, beside rad_plugin_abi_version and rad_plugin_info (whose
* kind is RAD_PLUGIN_QUANT). Two plugins naming the same quantiser is refused at load, both named,
* for the reason two kernel plugins may not disagree about an op's schema: a recipe that names it
* would mean different numbers depending on load order. */
int rad_quant_count(void);
const RadQuantizerInfo* rad_quant_at(int i);
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif /* RAD_QUANT_H */
+382
View File
@@ -0,0 +1,382 @@
/* rad_runtime.h -- the run phase. Ordinary C++ with one rule: it may only issue handles obtained
* during declare. Nothing else is constrained; in particular there is no capture discipline on
* this code, because a graph is built out of the kernels' own launch DESCRIPTIONS (RadDescribeFn
* in rad_abi.h) rather than by capturing the step. See spec.md §3.2.
*/
#ifndef RAD_RUNTIME_H
#define RAD_RUNTIME_H
#include "rad_builder.h"
#ifdef __cplusplus
extern "C" {
#endif
typedef struct RadCtx RadCtx;
/* ================================================================== the step batch */
/* Built ONCE PER STEP BY THE CORE and shared by every layer and every KV group. Rebuilding it per
* KV-cache group and per layer instead turns a substantial share of a decode step into host work
* with the device idle, which is the cost spec §8 exists to avoid.
*
* Every pointer here is device memory unless the field name says _h. The host mirrors exist
* because the scheduler and the run phase both need the bounds without a device read. */
enum { RAD_PHASE_PREFILL = 0, RAD_PHASE_DECODE = 1, RAD_PHASE_MIXED = 2 };
typedef struct RadKVGroupBatch {
rad_kvgroup group;
int32_t* slot_mapping; /* [n_tok] flat slot index per token, device */
int32_t* block_table; /* [n_seq, max_blocks] device */
int64_t block_table_pitch;
int32_t* seqused; /* [n_seq] context length in this group, device */
int32_t* state_index; /* [n_seq, state_index_pitch] state slots per sequence, device */
/* HOW MANY SLOTS A SEQUENCE NAMES, and it is 1 unless the group's kernel asked for scratch
* beside the state. A linear kernel serving speculation does: it cannot commit the state
* until acceptance is known, so it keeps the committed one in column 0 and its own replay
* scratch in the columns after it. The engine zeroes every one of them when the sequence is
* admitted and otherwise does not look inside. Zero means 1, for a caller that predates it. */
int64_t state_index_pitch;
int64_t block_size;
int64_t max_blocks;
} RadKVGroupBatch;
typedef struct RadBatch {
int phase; /* RAD_PHASE_* -- the run phase uses it to index bucket tables */
int step; /* monotonic, for the heat engine and for logs */
int64_t n_tok; /* total tokens across all sequences in this step */
int64_t n_seq;
const int32_t* token_ids; /* [n_tok] device */
const int32_t* positions; /* [n_tok] device */
const int32_t* cu_seqlens; /* [n_seq+1] device: sequence boundaries within this step */
const int32_t* seq_ids; /* [n_seq] device: engine-side sequence identity */
/* WHICH TOKENS THE SAMPLER WANTS LOGITS FOR: indices into THIS STEP's tokens, [n_out].
*
* A prefill chunk computes hidden states for every token in it and the sampler wants one row
* per sequence -- the last. Without this array the architecture plugin has to run the lm_head
* GEMM over all n_tok rows, which is n_tok/n_seq times the work and, at max_tok 8192 against
* a 248K vocab, an 8 GiB logits buffer instead of a 63 MiB one. The plugin issues gather_rows
* against it and then multiplies only what came back (docs/OPS.md, "Vocabulary edges").
*
* n_out is 0 for a chunk that finishes no sequence, which is the ordinary middle of a long
* prefill: no logits are produced at all and the lm_head is not touched. */
int64_t n_out;
const int32_t* out_ids; /* [n_out] device */
const int32_t* q_lens; /* [n_seq] device: query length this step */
const int32_t* ctx_lens; /* [n_seq] device: context length BEFORE this step */
int32_t max_q_len; /* host-side bounds -- these select kernel bands */
int32_t max_ctx_len;
int n_kv_groups;
const RadKVGroupBatch* kv; /* [n_kv_groups] */
/* Speculative window (spec §10). n_spec == 0 for an ordinary decode step. */
int n_spec; /* draft tokens per sequence this step */
const int32_t* num_accepted; /* [n_seq] device, from the PREVIOUS verify */
const int32_t* spec_parent; /* [n_tok] device, tree layout; null for a linear chain */
/* THE DRAFT PASS. 0 is an ordinary step and the plugin runs the trunk; a non-zero value runs
* ONLY the draft head, and the SIGN says which kind of pass:
*
* r < 0 a HISTORY pass: one row a token, gathered from the trunk step's rows
* (out_ids). The head attends to its own K and V, and nothing else in the engine
* writes those -- a prefill fills the trunk's layers and leaves the head's
* untouched. This fills them for the positions the step just committed. When
* `n_draft_out` is non-zero the pass is ALSO draft round 1: it ends in the lm_head
* over the rows `draft_out_ids` names, one a drafting sequence (see there).
* r > 1 draft round r, ONE-BASED. One row a sequence, reading the head's own output
* from the round before, ending in the lm_head; the token it samples is the r-th
* draft. There is no pass with r == 1: the history pass carries that round.
*
* Zero is the ordinary step so that a zeroed RadBatch runs the model, the same reason
* `num_accepted` is one-based (docs/OPS.md).
*
* On any such pass `token_ids` is already shifted: the head at index i reads the token at
* i + 1, and the batch builder applies that shift so no kernel and no plugin has to know it.
* Everything else in this struct means what it means on any other step. */
int32_t draft_pass;
/* Linear-state checkpointing (spec §7.3): tokens at which the scheduler wants a checkpoint
* written, already aligned to the checkpoint interval by the chunk split. */
int n_checkpoints;
const int32_t* checkpoint_tok; /* [n_checkpoints] device: index into this step's tokens */
const int32_t* checkpoint_slot; /* [n_checkpoints] device: destination snapshot slot */
/* THE DECODE / PREFILL SPLIT WITHIN A MIXED STEP.
*
* Sequences [0, n_seq_decode) carry decode rows and the rest carry prefill chunks. The
* scheduler orders every step that way, so a block that has to treat the two differently can
* issue over each as a CONTIGUOUS sub-range of the per-sequence arrays -- `cu_seqlens +
* n_seq_decode`, `state_index + n_seq_decode * pitch`, and so on -- while leaving the token
* operands at their base. That works because cu_seqlens holds ABSOLUTE row offsets: a kernel
* whose workgroup n reads cu[n] and cu[n+1] finds the right rows whichever sub-array it was
* handed, and no kernel changes to allow it.
*
* It exists because without the split a mixed step is prefill-shaped for every sequence in it,
* so the decode rows travelling with a prefill chunk cannot verify a draft and produce one
* token where they could have produced several. On an interactive load a large fraction of
* steps are mixed, so that is a large fraction of all decode rows.
*
* n_seq_decode == n_seq on a pure decode step and 0 on a pure prefill one, so a block that
* does not care can ignore all three fields, and one that does needs no phase test. */
int64_t n_seq_decode;
/* AND WHERE THEIR TOKENS END. The decode rows are tokens [0, n_tok_decode) and the prefill
* chunks are the rest, which a per-TOKEN op needs and cannot derive: each decode row is
* 1 + its own draft count, and those differ between sequences. */
int64_t n_tok_decode;
/* The longest query in each half, because max_q_len over a mixed step is the prefill chunk and
* banding the decode half with it would hand a thousand-row GEMM's band to eight rows.
*
* ONLY THE DECODE ONE IS READ TODAY, by the GDN blocks. The prefill one is here because the
* pair is what makes the split legible, and because a block whose prefill path bands on a
* per-sequence query length will want it -- the GDN prefill ops band on the step's TOTAL
* tokens instead, which they take from their operands, so they never ask. Said plainly rather
* than left to be discovered: an unread field that looks consumed is worse than one that
* says it is not. */
int32_t max_q_len_decode;
int32_t max_q_len_prefill;
/* DRAFT ROUND 1, CARRIED BY THE HISTORY PASS: [n_draft_out] device, indices into THIS pass's
* rows, one a sequence that drafts, in the order the later rounds' rows take.
*
* Round 1 continues from the last position the verify step committed, with the token the
* trunk chose after it -- and the history pass already has a row with exactly those inputs,
* because it covers every position the verify step could have committed and repeats the last
* committed one in the rows past it (core/sched/advance.h, ADV_HIST). A separate round-1 pass
* would run the head's whole layer again over a row that pass has just computed. So each
* drafting sequence's LAST history row is its round-1 row, and the pass ends in the lm_head
* over those rows; the head's wide state at them is what round 2 continues from.
*
* 0 on a history pass that drafts nothing, and on every other pass. */
int64_t n_draft_out;
const int32_t* draft_out_ids;
/* THE PROMPT THAT FOLLOWS THIS STEP: `n_ahead` more tokens of the LAST sequence, stored in
* `token_ids` right after its n_tok -- the next chunk of a prefill with more prompt to run, and
* 0 on every other step (a decode step, a draft pass, a prefill's last chunk).
*
* Nothing is computed on them and no output depends on them. They exist so an op that fetches
* per-token data from a slow tier can start the NEXT step's reads while this step runs: the
* PLE gather reads its rows from the container file, a few tens of thousands of random reads
* a chunk, and the chunk after this one is already known (docs/OPS.md, ngram_ids' `ahead_ids`
* and embed_lookup_q's `ahead`). */
int64_t n_ahead;
/* ================================================ multimodal (spec §11) */
/* THE ROTARY POSITION OF EVERY TOKEN, AND IT IS NOT `positions`. `positions` is a token's
* index in its sequence -- the KV slot, the QSA block and every other piece of bookkeeping
* count in it -- and a rotary embedding over several position components does not. Qwen-VL
* style M-RoPE gives each token three components (temporal, height, width): a text token has
* all three equal, an image token has the image's start in the first and its row and column
* offsets in the other two, and the text after an image continues from the image's largest
* component, so from the first image on the rotary position runs BEHIND the index.
*
* [3, n_tok] device, COMPONENT-MAJOR: plane c is rope_pos + c * n_tok, each n_tok long. Plane
* 0 alone is a valid one-component position for every token whose three components agree,
* which is every token on a pass where `rope_mixed` is 0 -- so a kernel that reads a position
* per token (a cos/sin table row, say) takes plane 0 on such a pass and needs no change.
*
* Null when the program declares no encoder: nothing can move a rotary position away from
* the index then, and `positions` is the rotary position. */
const int32_t* rope_pos;
/* Host-side: non-zero when some token on this pass has components that differ -- an image or
* video span is in the rows. A block whose fast path reads one component a token takes the
* multi-component path on such a pass. */
int32_t rope_mixed;
/* ROWS THAT TAKE AN ENCODER'S OUTPUT IN PLACE OF A TOKEN EMBEDDING. The placeholder ids a
* media span holds in `token_ids` are real ids -- a hashed n-gram embedding reads them -- but
* the embedding the model sees at those rows is the encoder's, and this is it: row i of
* `mm_embd` replaces the embedding of this pass's token `mm_rows[i]`.
*
* RANK 0 HOLDS THE ROWS AND EVERY OTHER RANK HOLDS ZEROS, which is the split a vocabulary-
* sharded embedding lookup produces: a token's embedding comes from the one rank that owns
* its id and the rest contribute zero to the reduction that follows. So a plugin overwrites
* its lookup's output with these rows BEFORE that reduction, and every row arrives once --
* whether the reduction is its own all-reduce or folded into the first layer's norm. At one
* rank there is no difference.
*
* On a pass that shifts its tokens (a draft head's history pass) the rows are shifted with
* them. 0 rows on every pass with no media in it. */
int64_t n_mm_rows;
const int32_t* mm_rows; /* [n_mm_rows] device: index into this pass's tokens */
const void* mm_embd; /* [n_mm_rows, n_embd] bf16 device */
/* THE ENCODER PASS. Non-zero `enc` runs the plugin's declared encoder (rad_declare_encoder)
* and nothing else: no token rows, no KV, no logits. Its input is a list of patches, already
* resized, normalised and cut by the processor, and its output is the encoder's declared
* `out` buffer, one row per `merge` patches, which the core reads back after the pass.
*
* Patches are grouped into SEGMENTS -- one per image, and one per temporal group of a video
* -- and attention runs within a segment. `enc_coord` gives each patch its place in its
* segment, which is everything a learned position table and a 2-D rotary embedding need. */
int32_t enc;
int64_t enc_n_patch;
const void* enc_pixels; /* [enc_n_patch, patch_dim] bf16 device */
/* [4, enc_n_patch] device, COMPONENT-MAJOR like rope_pos: row, column, the segment's height
* and its width, all in patches. Planes 0 and 1 together are a [2, enc_n_patch] position. */
const int32_t* enc_coord;
int64_t enc_n_seg;
const int32_t* enc_cu; /* [enc_n_seg + 1] device: segment boundaries in patches */
int32_t enc_max_seg; /* host: the longest segment, which bands the attention */
} RadBatch;
/* ================================================================== operands */
/* RAD_OPK_KV names a KV group's pool rather than a buffer: attention and kv_store take the cache
* as an operand, and RadKVGroupBatch carries the slot mapping and the block table but not the
* pool base -- the pool belongs to the block manager, not to the batch. handle is the
* rad_kvgroup and offset is the LAYER, because a group's pool holds one cache per bound layer. */
/* RAD_OPK_WTAB names a RUN of consecutively declared weights rather than one weight, and it
* exists because a routed mixture of experts has no single base to stride from. A layer's experts
* are separate movement units (spec §4.1) -- after placement one of them is in VRAM, the next is
* streamed over the link and the third is still on disk -- so "expert e is base + e*stride" is
* true only of the all-in-VRAM case and silently wrong of every other. The core therefore
* resolves each handle in the run the way it resolves any weight (residency table, mover event,
* use note) and hands the kernel a DEVICE ARRAY OF POINTERS, one per expert, in declaration
* order. See the RadTensor shape rule at RAD_WTAB below. */
enum { RAD_OPK_BUF = 0, RAD_OPK_WEIGHT = 1, RAD_OPK_RAW = 2, RAD_OPK_NONE = 3, RAD_OPK_KV = 4,
RAD_OPK_WTAB = 5 };
typedef struct RadOperand {
uint8_t kind;
uint32_t dtype; /* RAD_OPK_RAW only: what the pointer points at. A buffer and a weight
* carry their dtype in the declaration; a raw pointer is a batch field
* the core did not allocate and has nowhere else to say. RAD_DT_INVALID
* means "the kernel knows from the op schema position", which is true
* for a specialised kernel and false for libref. */
uint32_t handle; /* rad_buf or rad_weight */
void* raw; /* RAD_OPK_RAW: a pointer the core did not allocate (a batch field) */
int64_t offset; /* element offset into the buffer or weight */
int64_t rows; /* 0 = the declared extent; >0 = only this many rows of dim 0 */
int64_t cols; /* 0 = the declared extent; >0 = a COLUMN SLICE of that width, with the
* declared width kept as the stride. This is what makes a fused qkv
* projection usable: q, k and v are views of one buffer, and without it
* the architecture plugin has to declare three buffers and copy. */
} RadOperand;
#define RAD_B(h) ((RadOperand){ RAD_OPK_BUF, RAD_DT_INVALID, (h), 0, 0, 0, 0 })
#define RAD_B_AT(h, o) ((RadOperand){ RAD_OPK_BUF, RAD_DT_INVALID, (h), 0, (o), 0, 0 })
#define RAD_B_N(h, o, n) ((RadOperand){ RAD_OPK_BUF, RAD_DT_INVALID, (h), 0, (o), (n), 0 })
/* A column slice: `w` columns starting at column `c`, keeping the buffer's declared width as the
* stride. RAD_B_COL(qkv, 0, n_q) is the q view of a fused projection. */
#define RAD_B_COL(h, c, w) ((RadOperand){ RAD_OPK_BUF, RAD_DT_INVALID, (h), 0, (c), 0, (w) })
#define RAD_W(h) ((RadOperand){ RAD_OPK_WEIGHT, RAD_DT_INVALID, (h), 0, 0, 0, 0 })
/* A WEIGHT TABLE: the `n` weights declared at handles h, h+1, ... h+n-1 -- which is what a
* declaration loop over experts produces, because rad_decl_weight hands out consecutive indices.
*
* WHAT THE KERNEL RECEIVES. `RadTensor::data` is a device array of `n` `void*`, entry e being
* expert e's first byte. `shape[0]` is n and `stride[0]` is 0, which is the marker: a zero
* leading stride says the axis is not addressable by arithmetic and the table must be indexed.
* `dtype` and `shape[1..]` / `stride[1..]` are ONE entry's -- every weight in a run must agree
* about those, and the core refuses the issue by name if they do not, because a table whose
* entries have different shapes is a table the kernel cannot walk.
*
* The table is rebuilt only when a pointer in it actually changes, so a resident model pays one
* comparison per expert per issue and no copy at all. */
#define RAD_WTAB(h, n) ((RadOperand){ RAD_OPK_WTAB, RAD_DT_INVALID, (h), 0, 0, (n), 0 })
#define RAD_KV(g, layer) ((RadOperand){ RAD_OPK_KV, RAD_DT_INVALID, (g), 0, (layer), 0, 0 })
#define RAD_P(ptr) ((RadOperand){ RAD_OPK_RAW, RAD_DT_INVALID, 0, (void*)(ptr), 0, 0, 0 })
#define RAD_P_T(ptr, dt) ((RadOperand){ RAD_OPK_RAW, (dt), 0, (void*)(ptr), 0, 0, 0 })
/* A raw pointer to a DENSE 2-D array: [rows, cols], packed. `cols` on a raw operand is not the
* column SLICE it is on a buffer -- there is no declared width to slice out of -- it is the second
* extent, and giving it is the only way a batch field that is genuinely two-dimensional can say so.
* The block table is the case that forced it: [n_seq, max_blocks], and passed as a rank-1 array of
* n_seq the width is simply gone. Every kernel that reads it then has to guess, and the only two
* guesses available are to refuse the operand for not being rank 2 or to read a width of one. */
#define RAD_P_T2(ptr, dt, r, c) \
((RadOperand){ RAD_OPK_RAW, (dt), 0, (void*)(ptr), 0, (r), (c) })
#define RAD_NONE ((RadOperand){ RAD_OPK_NONE, RAD_DT_INVALID, 0, 0, 0, 0, 0 })
#define RAD_OPD(...) ((const RadOperand[]){ __VA_ARGS__ }), \
(int)(sizeof((const RadOperand[]){ __VA_ARGS__ }) / sizeof(RadOperand))
/* ================================================================== issue */
/* The core resolves each weight handle to a pointer, waits on the mover's event if the weight is
* in flight, indexes the op's bucket table with `n`, and dispatches to the device or host
* implementation according to the current execution site.
*
* `n` is the value of the op's ranged parameter -- at most one per op, which is what keeps this
* a single integer on the hot path. RAD_N_BATCH means "the batch's token count", which is what
* almost every op wants. An op with no ranged parameter ignores it.
*
* If an op received a void*, the weight's location would be fixed at declare and placement could
* not be a core feature at all. This is the single ABI decision the whole placement design rests
* on (spec §3.2). */
#define RAD_N_BATCH ((int64_t)-1)
int rad_issue(RadCtx* c, rad_op op, const RadOperand* opd, int n_opd, int64_t n);
/* THE SECOND LANE, for overlapping a collective -- or an arm no shard divides -- with compute.
* `rad_lane` selects which stream subsequent issues launch on (0 or 1); `rad_lane_join(c, from,
* to)` orders `to` behind everything already issued on `from` without blocking the host or
* draining either. The runtime joins lane 1 back into lane 0 at the end of every step, so a
* missing join costs speed and not correctness.
*
* THREE RULES, and Ctx::lane1_ in core carries the reasons: every collective must ride the SAME
* lane (the all-reduce numbers its scratch slots per launch and the two ranks must agree); a
* kernel that carries a device-wide arrival counter must key it on the STREAM, which libr4d's
* split-K GEMM does and a plugin that does not may not run here; and the buffer planner packs
* transients from a SINGLE LINEAR ORDER, so every buffer the second lane touches has to be named
* to rad_buf_concurrent, which gives up a few buffers' worth of the arena's sharing. */
int rad_lane(RadCtx* c, int lane);
int rad_lane_join(RadCtx* c, int from, int to);
/* Same, with the ranged value taken from the batch. */
#define RAD_ISSUE(c, op, ...) rad_issue((c), (op), RAD_OPD(__VA_ARGS__), RAD_N_BATCH)
#define RAD_ISSUE_N(c, op, n, ...) rad_issue((c), (op), RAD_OPD(__VA_ARGS__), (n))
/* FAIL THE STEP WITH A REASON. An architecture block's step() returns void, so without this the
* only way to refuse a batch it cannot serve is to issue something invalid and let the operand
* check reject it -- which reports the wrong cause. A block that knows it does not serve
* a batch shape says so here, and the engine stops with `what` in the message rather than
* producing numbers nobody should trust. Returns the status it set, so `return rad_step_fail(...)`
* reads naturally in a helper. */
int rad_step_fail(RadCtx* c, const char* what);
/* ================================================================== run-phase queries */
const RadBatch* rad_batch(RadCtx* c);
int rad_rank(RadCtx* c);
int rad_world_size(RadCtx* c);
RadStream rad_stream(RadCtx* c);
/* The routing result for a MoE layer, resolved on device against the current residency table.
* Routing NEVER blocks the compute stream: the histogram is copied back asynchronously and the
* heat engine consumes it on the next step (spec §5.5). This returns the device-side buffers,
* not host-visible expert ids -- the plugin issues its expert ops against them. */
typedef struct RadRouting {
const int32_t* expert_ids; /* [n_tok, top_k] device */
const float* expert_w; /* [n_tok, top_k] device */
const int32_t* expert_count; /* [n_expert] device: tokens routed to each */
const int32_t* sorted_tok; /* [n_tok * top_k] device: tokens grouped by expert */
const int32_t* expert_offset; /* [n_expert+1] device */
int64_t top_k;
int64_t n_expert;
} RadRouting;
/* Record that this layer's routing lives in these buffers, so the heat engine can read the
* histogram back and the mover can be told what was wanted. The plugin computed them with
* ordinary declared ops; this is the handoff, not a computation. */
int rad_route_report(RadCtx* c, int layer, const RadRouting* r);
/* WHERE A LAYER'S EXPERT COUNTS CAN BE WRITTEN IN PLACE: a device row of at least `n_expert` int32
* that the core owns and carries to the host itself, once, at the end of the pass. A router that
* writes its counts here and reports this pointer as `expert_count` hands them over for nothing;
* any other pointer is copied into this row, which is a dispatch a routed layer on the compute
* stream. Null when the core keeps no histogram for `layer` or its row is narrower than
* `n_expert` -- the router then writes its own buffer and reports that. */
int32_t* rad_route_counts(RadCtx* c, int layer, int64_t n_expert);
/* A weight's pointer, for the rare op that genuinely needs one (a plugin-private kernel invoked
* outside the op vocabulary). Waits on the mover. Using this forfeits nothing except the ability
* to move that weight while the pointer is live, so it is legal only within one issue. */
void* rad_weight_ptr(RadCtx* c, rad_weight w);
void* rad_buf_ptr(RadCtx* c, rad_buf b);
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif /* RAD_RUNTIME_H */
+135
View File
@@ -0,0 +1,135 @@
/* rad_sample.h -- the per-sequence sampling row, and why it is part of the ABI.
*
* Every sampler op takes `params` as an OPERAND: an array of the struct below, one row per sampled
* position, uploaded once per step. That makes its layout a wire format between the core and every
* kernel plugin, so it belongs here beside RadTensor rather than in core/sample/ where it started
* -- a kernel plugin cannot include a core header, and a struct the host writes and the device
* reads is a struct whose layout has to be STATED, not inferred.
*
* ============================== WHY NOT PARAMETERS ==============================
*
* `rep`, `freq`, `pres`, `k` and `p` read like op PARAMETERS, and docs/OPS.md names them that way.
* They cannot be. Parameters are geometry: the selector matches constraints against them and they
* are frozen at declare (spec §2.2). A per-sequence value cannot live there, and the failure is
* not subtle -- two requests in one batch with different top_p would be two different geometries
* and therefore two different resolutions of the same op, which is not something a batch can
* contain. A deployment would have one top_p.
*
* So the values are DATA and they travel as an operand. `seed` and `offset`, which docs/OPS.md
* gives `sample_pick` as two more operands, are fields of the row for the same reason.
*
* core/sample/sampler.h carries the full schema table this implies; libref implements it.
*/
#ifndef RAD_SAMPLE_H
#define RAD_SAMPLE_H
#include "rad_types.h"
#ifdef __cplusplus
extern "C" {
#endif
/* Flags, so a kernel can skip a stage for a sequence without reading five floats to discover they
* are the identity. One integer test beats five float comparisons per row per stage.
*
* RAD_SP_GREEDY OWNS THE ROW'S TOKEN. `sample_argmax` writes it, and every candidate stage after
* it -- `sample_topk`, the narrowing stages, `sample_merge_topk` and `sample_pick` -- treats the
* row as having no candidates and leaves `token` alone. A batch mixing greedy and sampled rows
* issues both paths over every row, so a stage that ignored the flag would overwrite the argmax
* with a draw. A greedy row that has to go through the candidate chain instead -- a split
* vocabulary, where the argmax's column is not a token id -- is staged at top_k = 1 WITHOUT this
* flag. */
enum {
RAD_SP_GREEDY = 1 << 0, /* argmax path; the candidate chain is not run for this sequence */
RAD_SP_PENALTY = 1 << 1, /* any of rep / freq / pres is non-identity */
RAD_SP_MASK = 1 << 2, /* a grammar is constraining this sequence this step */
RAD_SP_XTC = 1 << 3,
RAD_SP_DRY = 1 << 4
};
/* One row per sampled position. Laid out so the 8-byte fields are aligned and the struct has no
* padding anywhere, including at the tail.
*
* THE HISTORY WINDOW. `hist_off` and `hist_len` address the row's OWN row of the history plane,
* [M, max_hist] int32 with row m belonging to sampled position m: the window is
* history[m][hist_off .. hist_off + hist_len), clamped to the row. Token ids in it are GLOBAL
* vocabulary ids; a stage over a vocabulary shard subtracts its `vocab_off` parameter.
*
* `penalty_last_n` and `dry_penalty_last_n` window the TAIL of that span: 0 turns the stage off
* for the row, a negative value takes the whole span, and n > 0 takes the last n tokens -- the
* meaning llama.cpp gives `repeat_last_n` and `dry_penalty_last_n`.
*
* `dry_rep_limit` is the longest repeat DRY may count for the row, fixed by the most recent
* sequence breaker in the DRY window (llama.cpp's `rep_limit`), or 0 when no breaker occurs there
* and repeats are not limited. The breakers themselves are resolved against the vocabulary on the
* host, which is also where that limit is found; see `sample_dry`'s optional `breakers` operand
* for the other half. */
typedef struct RadSampleParams {
uint64_t seed; /* the request's seed */
uint64_t pos; /* output position: the RNG's second coordinate */
float temp;
float top_p;
float min_p;
float typical_p;
float rep_penalty;
float freq_penalty;
float pres_penalty;
float xtc_probability;
float xtc_threshold;
float dry_multiplier;
float dry_base;
int32_t top_k;
int32_t penalty_last_n;
int32_t dry_allowed_length;
int32_t dry_penalty_last_n;
int32_t hist_off; /* start of the window within this row's own history row */
int32_t hist_len;
int32_t mask_row; /* row into the bitmask plane, or -1 when unconstrained */
int32_t flags; /* RAD_SP_* */
int32_t dry_rep_limit; /* the breaker-imposed repeat limit, 0 when there is none */
} RadSampleParams;
/* The row is uploaded as an array and addressed as 24 words by every plugin, so its size is fixed
* and every byte of it is a named field. */
#ifdef __cplusplus
static_assert(sizeof(RadSampleParams) == 96, "RadSampleParams is 96 bytes on the wire");
static_assert(offsetof(RadSampleParams, dry_rep_limit) + sizeof(int32_t) == sizeof(RadSampleParams),
"RadSampleParams must pack without a tail hole");
#endif
/* THE RANDOM DRAW IS SPECIFIED, not left to a library, because the same stream has to come out of
* a host reference, a device kernel and a rerun (spec §17). splitmix64 over
* (seed * golden ratio + pos), taking 24 bits as a float in [0, 1) -- exactly f32's mantissa, so
* the draw is representable without a double anywhere in the chain.
*
* INDEPENDENT DRAWS AT ONE POSITION TAKE INDEPENDENT STREAMS, and a stream is the request's seed
* XORed with a key before the draw: `rad_sample_uniform01(seed ^ key, pos)`. The pick draws on the
* seed itself. XTC's "does it fire" coin has its own key, so a row whose XTC fired is not a row
* whose pick is correlated with that fact; speculative acceptance and its residual draw have
* theirs. Every implementation of a stage takes its key from here. */
#define RAD_SAMPLE_KEY_PICK 0x0ull
#define RAD_SAMPLE_KEY_XTC 0x58544311ull
#define RAD_SAMPLE_KEY_ACCEPT 0x41435054ull
#define RAD_SAMPLE_KEY_RESID 0x52534944ull
static inline uint64_t rad_sample_splitmix64(uint64_t z) {
z += 0x9E3779B97F4A7C15ull;
z = (z ^ (z >> 30)) * 0xBF58476D1CE4E5B9ull;
z = (z ^ (z >> 27)) * 0x94D049BB133111EBull;
return z ^ (z >> 31);
}
static inline float rad_sample_uniform01(uint64_t seed, uint64_t pos) {
const uint64_t z = rad_sample_splitmix64(seed * 0x9E3779B97F4A7C15ull + pos);
return (float)(uint32_t)(z >> 40) * (1.0f / 16777216.0f);
}
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif /* RAD_SAMPLE_H */
+363
View File
@@ -0,0 +1,363 @@
/* rad_types.h -- the primitive vocabulary shared by the core, the plugins and the tools.
*
* Pure C. Everything here crosses an .so boundary, so nothing in this file may be a C++ type,
* have a non-trivial layout, or depend on a compiler flag. See spec.md §2.
*/
#ifndef RAD_TYPES_H
#define RAD_TYPES_H
#include <stdint.h>
#include <stddef.h>
#include <string.h>
#ifdef __cplusplus
extern "C" {
#endif
/* ------------------------------------------------------------------ status */
/* Zero is success. Negative is failure, and the value names the class of failure so a caller
* can report something better than "it returned -1". A kernel returning negative at issue is a
* bug in selection, not a runtime condition -- spec.md §17. */
enum {
RAD_OK = 0,
RAD_E_SHAPE = -1, /* geometry this instantiation does not serve */
RAD_E_DTYPE = -2,
RAD_E_ALIGN = -3, /* pointer or stride alignment the kernel requires */
RAD_E_STRIDE = -4, /* non-contiguous where contiguity is required */
RAD_E_SCRATCH = -5, /* scratch buffer absent or too small */
RAD_E_NOMEM = -6,
RAD_E_NOKERNEL = -7, /* nothing in the hierarchy resolved */
RAD_E_NOSCHEMA = -8, /* op name has no declared schema */
RAD_E_SCHEMA = -9, /* params do not satisfy the op's schema */
RAD_E_ABI = -10, /* plugin ABI version mismatch */
RAD_E_DUPLICATE = -11, /* two plugins claim the same architecture id / op schema */
RAD_E_INVAL = -12,
RAD_E_IO = -13,
RAD_E_FORMAT = -14, /* container is not a .rad, or is a version we do not read */
RAD_E_DEVICE = -15, /* the device layer refused or faulted */
RAD_E_STATE = -16, /* called in the wrong phase */
RAD_E_NOTFOUND = -17,
RAD_E_UNSUPPORTED = -18,
RAD_E_FULL = -19, /* a pool, arena or table is exhausted */
RAD_E_CANCELLED = -20
};
/* ------------------------------------------------------------------ the helpers, INLINE
*
* WHY EVERY FREE FUNCTION IN THIS HEADER IS A DEFINITION AND NOT A DECLARATION.
*
* A plugin links these headers and nothing of the engine's. A function merely DECLARED here and
* defined inside the core is therefore not linkable from a plugin, which is the only caller that
* wants it -- and whether it happens to resolve at dlopen time is a property of the HOST, not of
* the ABI: a host that links the core with ENABLE_EXPORTS/-rdynamic exports the symbol and one
* that does not fails the plugin under RTLD_NOW. A capability that depends on a link flag of
* whoever dlopens you is not a capability.
*
* So they are `static inline` and the plugin compiles its own. That makes them part of the ABI
* BY VALUE rather than by linkage: a plugin carries the dtype table it was built against. That
* is the correct trade here, and RAD_ABI_VERSION is what enforces it -- the loader refuses a
* plugin built against a different one, by name, with both versions printed.
*
* Everything here is pure, small and total. Nothing allocates, nothing has state, and nothing
* may ever acquire either. */
static inline const char* rad_strerror(int status) {
switch (status) {
case RAD_OK: return "ok";
case RAD_E_SHAPE: return "shape this kernel does not serve";
case RAD_E_DTYPE: return "dtype this kernel does not serve";
case RAD_E_ALIGN: return "alignment the kernel requires was not met";
case RAD_E_STRIDE: return "non-contiguous operand where contiguity is required";
case RAD_E_SCRATCH: return "scratch buffer absent or too small";
case RAD_E_NOMEM: return "out of memory";
case RAD_E_NOKERNEL: return "no kernel resolved";
case RAD_E_NOSCHEMA: return "op has no declared schema";
case RAD_E_SCHEMA: return "parameters do not satisfy the op schema";
case RAD_E_ABI: return "plugin ABI version mismatch";
case RAD_E_DUPLICATE: return "duplicate registration";
case RAD_E_INVAL: return "invalid argument";
case RAD_E_IO: return "io error";
case RAD_E_FORMAT: return "container format error";
case RAD_E_DEVICE: return "device error";
case RAD_E_STATE: return "called in the wrong phase";
case RAD_E_NOTFOUND: return "not found";
case RAD_E_UNSUPPORTED: return "unsupported";
case RAD_E_FULL: return "pool or table exhausted";
case RAD_E_CANCELLED: return "cancelled";
default: return "unknown error";
}
}
/* ------------------------------------------------------------------ dtypes */
/* The core understands dtypes. Spec §19.6 asked whether it had to; it does -- libref has to
* interpret a tensor to compute on it, rad-kbench has to compare two of them elementwise, the
* buffer planner has to size a buffer from its shape, and rad-convert has to write bytes. An
* opaque dtype would push all four back into the plugin, which is the opposite of the point.
*
* The enum is open at the top: values >= RAD_DT_PLUGIN_BASE are kernel-plugin private, sized by
* the plugin's own layout hook, and never interpreted by the core. That is where a format
* invented for one kernel lives (spec §4.3) without the core learning about it. */
enum {
RAD_DT_INVALID = 0,
/* float */
RAD_F32 = 1,
RAD_F16 = 2,
RAD_BF16 = 3,
RAD_F8E4M3 = 4,
RAD_F8E5M2 = 5,
/* integer */
RAD_I8 = 8,
RAD_U8 = 9,
RAD_I16 = 10,
RAD_I32 = 11,
RAD_I64 = 12,
RAD_U32 = 13,
RAD_BOOL = 14,
/* SUB-BYTE CODES AND THE EXPONENT SCALE. The element count is the count of LOGICAL elements
* and the byte size comes from rad_dtype_bits(), which is why it is expressed in bits. They
* pack along a row, lowest bits first -- element 2j of a 4-bit row in bits 0-3 of byte j --
* and a row starts on a byte (rad_encoding.h). What a code MEANS is its encoding's business;
* these say only how many bits it is and whether it is signed. */
RAD_I4 = 16, /* two's complement, -8..7 */
RAD_I2 = 17, /* two's complement, -2..1 */
RAD_FP4E2M1 = 18, /* OCP FP4: 1-2-1, no inf or nan, max 6 */
RAD_U4 = 19, /* 0..15 */
RAD_U2 = 20, /* 0..3 */
RAD_E8M0 = 21, /* OCP E8M0: 2^(e-127), 0xFF is nan -- an MX block's shared scale */
RAD_U1 = 22, /* a bit: a sign plane, a binary code */
RAD_I3 = 23,
RAD_U3 = 24,
RAD_I5 = 25,
RAD_U5 = 26,
RAD_I6 = 27, /* also the K-quants' 6-bit scale with its offset removed */
RAD_U6 = 28,
RAD_I7 = 29,
RAD_U7 = 30,
RAD_U9 = 31, /* 9- to 12-bit unsigned: lattice grid indices (IQ3_S, IQ2_S, IQ1_S) */
RAD_U10 = 32,
RAD_U11 = 33,
RAD_U12 = 34,
RAD_FP6E2M3 = 35, /* OCP FP6: 1-2-3, bias 1, no inf or nan, max 7.5 */
RAD_FP6E3M2 = 36, /* OCP FP6: 1-3-2, bias 3, no inf or nan, max 28 */
RAD_U16 = 37,
RAD_DT_PLUGIN_BASE = 256
};
/* THE DTYPE TABLE, and it lives in the header for the reason the block above rad_strerror gives.
*
* Sub-byte formats carry their packed width here. A shared scale is never folded into a code's
* width: it is a plane of its own (rad_encoding.h), so every width below is exact. */
typedef struct RadDtRow { uint32_t dt; const char* name; int bits; } RadDtRow;
static const RadDtRow rad_dt_table[] = {
{ RAD_F32, "f32", 32 },
{ RAD_F16, "f16", 16 },
{ RAD_BF16, "bf16", 16 },
{ RAD_F8E4M3, "fp8_e4m3", 8 },
{ RAD_F8E5M2, "fp8_e5m2", 8 },
{ RAD_I8, "i8", 8 },
{ RAD_U8, "u8", 8 },
{ RAD_I16, "i16", 16 },
{ RAD_I32, "i32", 32 },
{ RAD_I64, "i64", 64 },
{ RAD_U32, "u32", 32 },
{ RAD_BOOL, "bool", 8 },
{ RAD_I4, "i4", 4 },
{ RAD_I2, "i2", 2 },
{ RAD_FP4E2M1, "fp4_e2m1", 4 },
{ RAD_U4, "u4", 4 },
{ RAD_U2, "u2", 2 },
{ RAD_E8M0, "e8m0", 8 },
{ RAD_U1, "u1", 1 },
{ RAD_I3, "i3", 3 },
{ RAD_U3, "u3", 3 },
{ RAD_I5, "i5", 5 },
{ RAD_U5, "u5", 5 },
{ RAD_I6, "i6", 6 },
{ RAD_U6, "u6", 6 },
{ RAD_I7, "i7", 7 },
{ RAD_U7, "u7", 7 },
{ RAD_U9, "u9", 9 },
{ RAD_U10, "u10", 10 },
{ RAD_U11, "u11", 11 },
{ RAD_U12, "u12", 12 },
{ RAD_FP6E2M3, "fp6_e2m3", 6 },
{ RAD_FP6E3M2, "fp6_e3m2", 6 },
{ RAD_U16, "u16", 16 },
};
enum { RAD_DT_TABLE_N = (int)(sizeof(rad_dt_table) / sizeof(rad_dt_table[0])) };
/* Bits per logical element. Returns 0 for a plugin-private dtype -- the plugin sizes those. */
static inline int rad_dtype_bits(uint32_t dtype) {
for (int i = 0; i < RAD_DT_TABLE_N; ++i)
if (rad_dt_table[i].dt == dtype) return rad_dt_table[i].bits;
return 0;
}
static inline const char* rad_dtype_name(uint32_t dtype) {
for (int i = 0; i < RAD_DT_TABLE_N; ++i)
if (rad_dt_table[i].dt == dtype) return rad_dt_table[i].name;
return dtype >= RAD_DT_PLUGIN_BASE ? "plugin-private" : "invalid";
}
/* RAD_DT_INVALID if unknown. The alternate spellings are the ones that appear in checkpoints and
* in kernel dtype strings; a converter reading safetensors meets every one of them. */
static inline uint32_t rad_dtype_parse(const char* name) {
if (!name) return RAD_DT_INVALID;
for (int i = 0; i < RAD_DT_TABLE_N; ++i)
if (strcmp(rad_dt_table[i].name, name) == 0) return rad_dt_table[i].dt;
if (!strcmp(name, "float32") || !strcmp(name, "fp32")) return RAD_F32;
if (!strcmp(name, "float16") || !strcmp(name, "fp16") || !strcmp(name, "half")) return RAD_F16;
if (!strcmp(name, "bfloat16")) return RAD_BF16;
if (!strcmp(name, "e4m3") || !strcmp(name, "fp8")) return RAD_F8E4M3;
if (!strcmp(name, "e5m2")) return RAD_F8E5M2;
if (!strcmp(name, "int8")) return RAD_I8;
if (!strcmp(name, "int32")) return RAD_I32;
return RAD_DT_INVALID;
}
/* Byte size of n elements, rounding up. 0 if the dtype is plugin-private. */
static inline int64_t rad_dtype_bytes(uint32_t dtype, int64_t n) {
const int bits = rad_dtype_bits(dtype);
if (bits == 0) return 0;
return ((int64_t)bits * n + 7) / 8;
}
/* ------------------------------------------------------------------ tensors */
enum { RAD_MAX_RANK = 6 };
/* Strides are in ELEMENTS, not bytes -- the convention that survives contact with sub-byte
* dtypes, where a byte stride would be fractional. */
typedef struct RadTensor {
void* data;
uint32_t dtype;
uint32_t rank;
int64_t shape [RAD_MAX_RANK];
int64_t stride[RAD_MAX_RANK];
} RadTensor;
static inline int64_t rad_tensor_numel(const RadTensor* t) {
if (!t || t->rank == 0) return 0;
int64_t n = 1;
for (uint32_t i = 0; i < t->rank; ++i) n *= t->shape[i];
return n;
}
/* A rank-0 tensor and a tensor whose only non-unit axes are already dense are both contiguous.
* The unit-extent test matters: a shape-1 axis may carry any stride at all and still describe the
* same bytes, so demanding the packed value there rejects tensors that are in fact dense. */
static inline int rad_tensor_is_contiguous(const RadTensor* t) {
if (!t || t->rank == 0) return 1;
int64_t acc = 1;
for (int i = (int)t->rank - 1; i >= 0; --i) {
if (t->shape[i] != 1 && t->stride[i] != acc) return 0;
acc *= t->shape[i];
}
return 1;
}
/* Fill strides for a dense row-major tensor whose shape and rank are already set. */
static inline void rad_tensor_pack(RadTensor* t) {
if (!t || t->rank == 0) return;
int64_t acc = 1;
for (int i = (int)t->rank - 1; i >= 0; --i) { t->stride[i] = acc; acc *= t->shape[i]; }
}
/* ------------------------------------------------------------------ parameters */
/* An op's parameters are named scalars: the geometry the selector matches constraints against.
* A parameter may be a fixed value or a RANGE, which is what turns one declared op into a
* bucket table (spec §2.2). At most one parameter per op may be ranged. */
enum { RAD_P_INT = 1, RAD_P_STR = 2, RAD_P_RANGE = 3, RAD_P_F64 = 4 };
typedef struct RadParam {
const char* key;
int kind; /* RAD_P_INT | RAD_P_STR | RAD_P_RANGE | RAD_P_F64 */
long long ival; /* RAD_P_INT, and the low bound of RAD_P_RANGE */
long long ihi; /* RAD_P_RANGE: the high bound, inclusive */
const char* sval; /* RAD_P_STR */
double dval; /* RAD_P_F64 -- eps, rope theta, an attention scale. Carried as a
* double rather than round-tripped through a "%.9g" string, which is
* exact for an IEEE single but unreadable in a graph dump. Constraints
* do not match on a float: a tolerance is not a predicate, and a kernel
* that cares about eps to that precision is a kernel with a bug. */
} RadParam;
/* Builders. RAD_PARAMS below wraps these into a positional list. */
#define RAD_INT(k, v) ((RadParam){ (k), RAD_P_INT, (long long)(v), 0, 0, 0.0 })
#define RAD_STR(k, v) ((RadParam){ (k), RAD_P_STR, 0, 0, (v), 0.0 })
#define RAD_F64(k, v) ((RadParam){ (k), RAD_P_F64, 0, 0, 0, (double)(v) })
#define RAD_RANGE(k, lo, hi) ((RadParam){ (k), RAD_P_RANGE, (long long)(lo), (long long)(hi), 0, 0.0 })
/* ------------------------------------------------------------------ constraints */
/* A kernel's necessary condition on a geometry. Deliberately NOT sufficient: strides,
* contiguity, alignment and buffer sizes are properties of a call rather than of a model, and
* they stay in the entry point, which still rejects what it cannot run -- spec §2.1. */
enum { RAD_C_EQ = 0, RAD_C_LE = 1, RAD_C_GE = 2, RAD_C_DIV = 3, RAD_C_IN = 4 };
typedef struct RadConstraint {
const char* key;
int op;
long long ival; /* EQ / LE / GE / DIV */
const char* sval; /* IN: space-separated set of admissible strings */
} RadConstraint;
#define RAD_C(k, o, v) { (k), (o), (long long)(v), 0 }
#define RAD_CEQ(k, v) { (k), RAD_C_EQ, (long long)(v), 0 }
#define RAD_CLE(k, v) { (k), RAD_C_LE, (long long)(v), 0 }
#define RAD_CGE(k, v) { (k), RAD_C_GE, (long long)(v), 0 }
#define RAD_CDIV(k, v) { (k), RAD_C_DIV, (long long)(v), 0 }
#define RAD_CIN(k, s) { (k), RAD_C_IN, 0, (s) }
/* ------------------------------------------------------------------ handles */
/* Opaque, dense, small. A handle is an index into a core-owned table; zero is never a valid
* handle, so a zeroed struct is an unset one and a failed decl_* is falsy. */
typedef uint32_t rad_weight;
typedef uint32_t rad_buf;
typedef uint32_t rad_op;
/* A KV group handle. It lives here with the other handles because a declaration in rad_builder.h
* carries one: a derived buffer names the KV group its derivation is about. */
typedef uint32_t rad_kvgroup;
#define RAD_NULL_HANDLE 0u
/* ------------------------------------------------------------------ streams */
/* Opaque to the core in the sense that it never dereferences one. On a card it is a queue of the
* engine's own, NOT a hipStream_t: a kernel plugin launches onto it with hipLaunchKernel (and so
* <<<>>>), hipMemcpyAsync, hipMemcpy2DAsync and hipMemsetAsync, which the engine answers itself,
* and hands it to nothing else in HIP (docs/PLUGIN.md, "What a launch may do"). Under the host
* backend it is a queue the host kernels ignore. */
typedef void* RadStream;
enum { RAD_MAX_KPARAMS = 24, RAD_KPARAM_BLOB = 256 };
typedef struct RadLaunchDesc {
/* The entry symbol, as the launch API takes it. A template instantiation resolves to its own
* symbol, which is the point: `heads` picking a different instantiation moves the FUNCTION,
* not just an argument, and a node whose function moved has to be rebuilt rather than
* updated. The runtime compares this across steps and recaptures when it changes. */
const void* func;
uint32_t grid[3];
uint32_t block[3];
uint32_t shared_bytes;
uint32_t n_params;
/* Pointers to the argument values, in the kernel's declared order -- the `kernelParams`
* convention, so slot i is parameter i and the runtime can rewrite exactly the ones that
* moved. */
void* params[RAD_MAX_KPARAMS];
/* The width of each slot, which the runtime needs for two things it cannot otherwise do:
* compare a slot against the previous step's to see whether it moved, and recognise a slot
* that holds an OPERAND ADDRESS by matching its value against the operands it just passed in.
* That second one is what lets a replay update ten pointers without re-entering the shim --
* the mapping is inferred, so no kernel has to declare it and no out-of-tree author has to
* know it exists. */
uint16_t param_size[RAD_MAX_KPARAMS];
/* Where the values live. The shim writes into this and points `params` here. */
unsigned char blob[RAD_KPARAM_BLOB];
} RadLaunchDesc;
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif /* RAD_TYPES_H */