Archived
radiance 1.7.0
- every model serves without a GPU: libavx covers every op, so `--kernels libavx` alone serves every shipped container - Qwen3-ASR (zivius): speech to text on /v1/audio/transcriptions and live over /v1/realtime - /v1/messages works with Claude Code as it ships (gearwave00001) - a long agent conversation keeps its cached history when the client rewrites its last turn (manueloverride) - a stream's first event goes out with the first token, so llama-benchy measures prefill right - opt-in --prefill-interleave (Smellyyyy, baKon) and --prefill-span (keptn42) - four-rank TP releases the link early; four-rank selftests and docs/TP4.md (goodman-b) - NVFP4 and FP8 compressed-tensors imports (devmilan); tools/rad-export for finetunes and LoRA adapters (baKon) - many fixes, among them lost tokens on stop strings under concurrency, keep-alive, MiniCPM5 tool arguments and the CPU's vision and audio encoders - plugin ABI 17 and changed op schemas: out-of-tree plugins must be rebuilt
This commit is contained in:
1 parent
b068190326
commit
1e968f6e1d
739 files changed
+128447
-84632
No files matched your search
+251
-355
@@ -1,7 +1,6 @@
|
||||
/* rad_abi.h -- the plugin ABI. This file and rad_types.h are the whole contract between the
|
||||
* engine and an .so it loads. Everything is C: C++ across an .so boundary is a standing
|
||||
* invitation to a mismatch that manifests as corruption three frames later, and this boundary is
|
||||
* exactly where a user is expected to substitute their own build. See spec.md §2.
|
||||
/* rad_abi.h -- the plugin ABI. This file and rad_types.h are the contract between the engine and
|
||||
* an .so it loads. The interface is plain C: C++ across an .so boundary invites ABI mismatches,
|
||||
* and this is the boundary where users substitute their own builds. See spec.md §2.
|
||||
*/
|
||||
#ifndef RAD_ABI_H
|
||||
#define RAD_ABI_H
|
||||
@@ -13,27 +12,26 @@
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
/* Bumped whenever anything a plugin compiles against changes shape -- this header, rad_types.h,
|
||||
/* Bumped whenever anything a plugin compiles against changes shape: this header, rad_types.h,
|
||||
* rad_builder.h, rad_runtime.h, rad_device.h, rad_encoding.h, rad_quant.h or rad_sample.h. Every
|
||||
* kind of plugin reports it. A plugin that does not report exactly this is refused at load, by
|
||||
* name, with both versions printed. An OPTIONAL export added beside the existing ones
|
||||
* (rad_plugin_reference, say) is not a change of shape: a plugin without it is read as answering
|
||||
* the default. */
|
||||
#define RAD_ABI_VERSION 16u
|
||||
* kind of plugin reports it, and a plugin that does not report exactly this version is refused at
|
||||
* load with both versions printed. A new optional export (e.g. rad_plugin_reference) is not a
|
||||
* change of shape: a plugin without it gets the default. */
|
||||
#define RAD_ABI_VERSION 17u
|
||||
|
||||
/* ================================================================== plugin identity */
|
||||
/* RAD_PLUGIN_QUANT is a quantiser plugin: rad_quant.h is its whole contract. */
|
||||
/* One value per plugin, not flags (QUANT is 3). RAD_PLUGIN_QUANT is a quantiser plugin:
|
||||
* rad_quant.h is its whole contract. */
|
||||
enum { RAD_PLUGIN_KERNEL = 1, RAD_PLUGIN_ARCH = 2, RAD_PLUGIN_QUANT = 3 };
|
||||
|
||||
typedef struct RadPluginInfo {
|
||||
uint32_t kind; /* RAD_PLUGIN_KERNEL | RAD_PLUGIN_ARCH | RAD_PLUGIN_QUANT */
|
||||
uint32_t kind; /* one of RAD_PLUGIN_KERNEL, _ARCH, _QUANT */
|
||||
const char* name; /* "libr4d", "libref", "qwen3_dense_bf16" */
|
||||
const char* version;
|
||||
const char* description;
|
||||
/* The devices this build of the plugin can run on, as the backend spells an architecture in
|
||||
* RadDeviceProps::arch. "host" for a library of CPU kernels, which run anywhere; "" for a
|
||||
* plugin that claims nothing. Several architectures may be listed, separated by spaces or
|
||||
* commas, for a binary built to cover more than one. */
|
||||
/* The devices this build can run on, spelled as RadDeviceProps::arch. "host" for a library of
|
||||
* CPU kernels, which run anywhere; "" for a plugin that claims nothing. A binary built for
|
||||
* several architectures lists them separated by spaces or commas. */
|
||||
const char* build_target;
|
||||
} RadPluginInfo;
|
||||
|
||||
@@ -43,8 +41,8 @@ const RadPluginInfo* rad_plugin_info(void);
|
||||
|
||||
/* ================================================================== execution domain */
|
||||
/* A CPU kernel is an ordinary kernel with domain RAD_DOMAIN_HOST, resolved through the same
|
||||
* hierarchy and the same constraints. Declare resolves both domains where both exist, so the
|
||||
* core can change execution site at runtime without re-resolving -- spec §5.1. */
|
||||
* hierarchy and constraints. Declare resolves both domains where both exist, so the core can
|
||||
* change execution site at runtime without re-resolving (spec §2.1). */
|
||||
enum { RAD_DOMAIN_DEVICE = 0, RAD_DOMAIN_HOST = 1, RAD_N_DOMAINS = 2 };
|
||||
|
||||
/* ================================================================== kernel arguments */
|
||||
@@ -60,9 +58,8 @@ typedef struct RadArgs {
|
||||
int world_size;
|
||||
} RadArgs;
|
||||
|
||||
/* Read a parameter by key. Definitions, not declarations: a plugin links the ABI headers and
|
||||
* nothing of the engine's, so a function declared here and defined in the core would be
|
||||
* unlinkable from the plugins that are its only callers. See the note in rad_types.h. */
|
||||
/* Read a parameter by key. Inline definitions, because a plugin links only the ABI headers and
|
||||
* nothing of the engine's. See the note in rad_types.h. */
|
||||
static inline int rad_args_geti(const RadArgs* a, const char* key, long long* out) {
|
||||
if (!a || !key) return 0;
|
||||
for (int i = 0; i < a->n_p; ++i)
|
||||
@@ -82,95 +79,44 @@ static inline const char* rad_args_gets(const RadArgs* a, const char* key) {
|
||||
}
|
||||
|
||||
/* ================================================================== kernel hooks */
|
||||
/* init/fini exist because some kernels have per-instance state that must be established once and
|
||||
* not per launch -- libr4d's all-reduce needs its peer signal buffers and IPC handles set up
|
||||
* across ranks before the first call, and a kernel that JITs or loads a config table wants
|
||||
* somewhere to do it that is not the hot path.
|
||||
/* init/fini hold per-instance state that is set up once rather than per launch: libr4d's
|
||||
* all-reduce exchanges peer signal buffers and IPC handles across ranks before the first call,
|
||||
* and a kernel that JITs or loads a config table does it here, off the hot path.
|
||||
*
|
||||
* init is called once per RESOLVED INSTANCE (one op, one band, one domain), after selection and
|
||||
* before load, with the frozen geometry. It returns an opaque pointer handed back in
|
||||
* RadArgs.instance, or null. A negative status aborts startup. */
|
||||
* init is called once per resolved instance (one op, one band, one domain), after selection and
|
||||
* before load, with the frozen geometry. The pointer it returns (or null) is handed back in
|
||||
* RadArgs.instance. A negative status aborts startup. */
|
||||
typedef int (*RadInitFn) (const RadParam* p, int n_p, int rank, int world_size,
|
||||
void** out_instance);
|
||||
typedef void (*RadFiniFn) (void* instance);
|
||||
|
||||
/* The launch. Must not allocate and must not synchronise. Returns RAD_OK or negative; a negative
|
||||
* return aborts the step and fails the requests in it, naming the kernel and the geometry. A launch
|
||||
* return aborts the step and fails its requests, naming the kernel and the geometry. A launch
|
||||
* handed `link_gate` may return RAD_LINK_ENDED instead of RAD_OK (rad_kernel_collective). */
|
||||
typedef int (*RadLaunchFn) (const RadArgs* a, RadStream stream);
|
||||
|
||||
/* ================================================================== the described launch */
|
||||
/* A KERNEL THAT DESCRIBES ITS LAUNCH INSTEAD OF PERFORMING IT, so the runtime can turn one
|
||||
* description into either a dispatch or a graph node update.
|
||||
*
|
||||
* WHY THIS EXISTS. The engine re-issues a fixed op sequence every step: the topology is identical
|
||||
* from step to step and only a few of the dispatches carry an operand that moved. The cost of
|
||||
* launching a graph is roughly flat in the number of nodes, while submitting the same dispatches
|
||||
* one at a time is linear in it, so replaying such a sequence as a graph is cheaper. What a
|
||||
* `launch` hook cannot support is the UPDATE: it performs the dispatch itself, marshalling its own
|
||||
* arguments, so nothing above it knows which argument slot holds which operand -- and a node update
|
||||
* needs exactly that slot. `describe` reports the dispatch instead of performing it.
|
||||
*
|
||||
* IT IS OPTIONAL. `launch` remains the required entry point and every kernel that only implements
|
||||
* it keeps working unchanged -- it simply never becomes a graph node, and a sequence containing
|
||||
* one is submitted the ordinary way. Implement `describe` for a kernel that is issued repeatedly
|
||||
* with a stable shape; there is nothing to gain on one that runs once.
|
||||
*
|
||||
* THE TRAP, AND THE ONE WAY TO AVOID IT. `launch` and `describe` must dispatch the SAME kernel
|
||||
* with the SAME arguments, and nothing can check that for you: a divergence is not a crash, it is
|
||||
* a wrong number produced only on the graph path, only after a capture, and it will read as a
|
||||
* numerics bug anywhere but here. Do NOT write the two bodies twice. Write the shape arithmetic
|
||||
* once and let it emit into a sink that is either a stream or a descriptor -- libr4d does this
|
||||
* with one macro, and an out-of-tree plugin should do the same.
|
||||
*
|
||||
* ALLOCATION-FREE, like `launch`. The runtime owns the RadLaunchDesc storage and keeps it alive
|
||||
* for as long as the node exists, so the shim writes its argument VALUES into `blob` and points
|
||||
* `params[i]` at them. Pointing `params[i]` at anything else is legal only if that storage
|
||||
* outlives the graph -- a string literal or the instance state does, a local does not. */
|
||||
|
||||
/* Fill `out[0..cap)` with the dispatches this call WOULD perform and write how many to `n_out`.
|
||||
* Most kernels emit one; a split-K kernel and its finisher emit two. Returns RAD_E_FULL without
|
||||
* writing anything if `cap` is too small, so the runtime can retry with a bigger array; returns
|
||||
* RAD_OK having written `*n_out` otherwise. Must not allocate, must not synchronise and must not
|
||||
* touch the device -- it is called at capture time, off the step path, and again whenever the
|
||||
* runtime needs to know whether an argument moved.
|
||||
*
|
||||
* IT DESCRIBES A KERNEL DISPATCH AND ONLY THAT. An op whose work is a memory copy -- libr4d's
|
||||
* `cast` is a hipMemcpy2DAsync, not a launch -- has nothing to put in a RadLaunchDesc and should
|
||||
* leave `describe` null. A graph can hold copy nodes, but expressing one would need a second
|
||||
* descriptor shape, and the ops that want it are the ops a graph saves least on.
|
||||
*
|
||||
* IT TAKES THE STREAM, because some launches depend on which one they are going onto: libr4d's
|
||||
* split-K GEMM takes its arrival counter from a per-stream pool, so a description made without
|
||||
* the stream would name a different counter than the launch would have used -- a divergence of
|
||||
* exactly the kind the paragraph above says nothing can check for you. The runtime passes the
|
||||
* stream the dispatch will actually run on, which for a graph node is the stream the graph is
|
||||
* launched on. */
|
||||
typedef int (*RadDescribeFn)(const RadArgs* a, RadStream s, RadLaunchDesc* out,
|
||||
int cap, int* n_out);
|
||||
|
||||
/* Bytes of scratch one launch of this shape needs. Null means none. Called at declare with the
|
||||
* band's upper bound, so the arena is sized for the worst step. */
|
||||
typedef int64_t (*RadScratchFn)(const RadArgs* a);
|
||||
|
||||
/* ================================================================== weight layout
|
||||
*
|
||||
* WHAT A KERNEL STORES FOR A WEIGHT, GIVEN WHAT THE WEIGHT IS. spec.md §4.1, §4.3.
|
||||
* What a kernel stores for a weight, given the weight's encoding. spec.md §4.1, §4.3.
|
||||
*
|
||||
* A container holds each weight's ENCODING -- its codes, scales and zero points as canonical planes
|
||||
* (rad_encoding.h) -- and nothing shaped for a kernel. The kernel that reads a weight says here
|
||||
* what it wants instead, and the loader turns one into the other when the model loads. Lossless,
|
||||
* always: a relayout moves bits and derives nothing a reader of the planes could not derive -- a
|
||||
* fragment order, a scale repeated into a row's tail, a reference exponent that is a row's
|
||||
* maximum. Choosing numbers is a quantiser's job (rad_quant.h); a kernel that did it here would
|
||||
* make the served numbers depend on which library loaded the container. So a kernel library may
|
||||
* change every layout it has and no container is converted again. */
|
||||
* A container holds each weight's encoding (codes, scales and zero points as canonical planes,
|
||||
* rad_encoding.h) and nothing shaped for a kernel. The kernel that reads a weight describes the
|
||||
* form it wants here, and the loader converts when the model loads. The conversion is lossless: a
|
||||
* relayout moves bits and derives only what a reader of the planes could derive (a fragment order,
|
||||
* a scale repeated into a row's tail, a reference exponent that is a row's maximum). Choosing
|
||||
* numbers is the quantiser's job (rad_quant.h); a kernel doing it here would make the served
|
||||
* numbers depend on which library loaded the container. So a kernel library may change any layout
|
||||
* without containers being converted again. */
|
||||
typedef struct RadLayout {
|
||||
const char* tag; /* stable name of the arrangement, for messages and for checking
|
||||
* that every kernel reading one weight wants the same bytes */
|
||||
uint32_t dtype; /* the stored dtype, possibly a plugin-private one */
|
||||
uint32_t rank;
|
||||
int64_t shape[RAD_MAX_RANK]; /* the STORED shape, which may differ from the logical one */
|
||||
int64_t shape[RAD_MAX_RANK]; /* the stored shape, which may differ from the logical one */
|
||||
int64_t align; /* byte alignment the stored base must satisfy */
|
||||
int64_t bytes; /* total, including any padding the layout implies */
|
||||
} RadLayout;
|
||||
@@ -178,93 +124,103 @@ typedef struct RadLayout {
|
||||
/* Describe what this kernel stores for operand `operand` of the given geometry.
|
||||
*
|
||||
* `enc` is the weight's encoding and `sel[i]` the index into `enc->plane` of planes[i], the planes
|
||||
* this operand takes, in the order the declaration named them (RadWeightDecl::planes). Each plane
|
||||
* is THIS RANK'S SLICE, dense: rank 2, [rows, cols] in the plane's own elements, every row starting
|
||||
* on a byte and rad_dtype_bytes(dtype, cols) long. Here the planes carry their geometry and a null
|
||||
* `data`.
|
||||
* this operand takes, in RadWeightDecl::planes order. Each plane is this rank's slice, dense: rank
|
||||
* 2, [rows, cols] in the plane's own elements, every row starting on a byte and
|
||||
* rad_dtype_bytes(dtype, cols) long. Here the planes carry their geometry and a null `data`.
|
||||
*
|
||||
* RAD_OK `out` describes the stored form, and `relayout` will produce it.
|
||||
* RAD_E_UNSUPPORTED stored as it is: the one selected plane, its bytes unchanged -- what most
|
||||
* weights are, and what a kernel with no hook at all gets. Only such a weight
|
||||
* can be read where it lies in the container (the file and mapped tiers).
|
||||
* RAD_E_DTYPE THE KERNEL DOES NOT READ THIS ENCODING -- an fp8 GEMM handed int4, a
|
||||
* rotated weight to a kernel that does not rotate its activation. A
|
||||
* declare-time error that names the weight, the encoding and the kernel.
|
||||
* RAD_E_SHAPE the planes selected, or their extents, are not what the kernel reads. */
|
||||
* RAD_E_UNSUPPORTED stored as is: the one selected plane, bytes unchanged. This is most
|
||||
* weights, and what a kernel with no hook gets. Only such a weight can be
|
||||
* read where it lies in the container (the file and mapped tiers).
|
||||
* RAD_E_DTYPE the kernel does not read this encoding (an fp8 GEMM handed int4, a rotated
|
||||
* weight to a kernel that does not rotate its activation). A declare-time
|
||||
* error naming the weight, the encoding and the kernel.
|
||||
* RAD_E_SHAPE the selected planes, or their extents, are not what the kernel reads. */
|
||||
typedef int (*RadLayoutFn)(const RadParam* p, int n_p, int operand, const RadEncoding* enc,
|
||||
const int* sel, const RadTensor* planes, int n_planes,
|
||||
RadLayout* out);
|
||||
|
||||
/* Write the stored form `layout` described into `dst`, `dst_bytes` long, from the planes, which
|
||||
* now carry their bytes. Pure host code, run by the loader -- on a pool, behind the read of the
|
||||
* container, so it has to keep pace with the disk. */
|
||||
* now carry their bytes. Pure host code, run by the loader on a pool behind the container read,
|
||||
* so it has to keep pace with the disk. */
|
||||
typedef int (*RadRelayoutFn)(const RadParam* p, int n_p, int operand, const RadEncoding* enc,
|
||||
const int* sel, const RadTensor* planes, int n_planes, void* dst,
|
||||
int64_t dst_bytes);
|
||||
|
||||
/* ...AND BACK: recover the planes from a stored form. `planes` arrive with their geometry and a
|
||||
/* The inverse: recover the planes from a stored form. `planes` arrive with their geometry and a
|
||||
* buffer each.
|
||||
*
|
||||
* WHY THE INVERSE HAS TO EXIST, stated from the failure it prevents. A tool that checks a kernel
|
||||
* against the oracle holds the STORED bytes -- what the kernel reads -- and libref reads canonical
|
||||
* planes. Handed the stored bytes it computes a correct answer to a permuted question, and the
|
||||
* comparison is then between two unrelated tensors: a relative error of the size two independent
|
||||
* draws give, reported against a kernel that is in fact correct. Only the plugin knows its
|
||||
* permutation, so only the plugin can undo it. A kernel that relayouts and supplies no inverse is
|
||||
* not a fault -- it is simply not checkable against a dense oracle, and the tools say so BY NAME
|
||||
* rather than guessing. */
|
||||
* A tool checking a kernel against the oracle holds the stored bytes, but libref reads canonical
|
||||
* planes; given the stored bytes it answers a permuted question, and the comparison reports an
|
||||
* error the size of two unrelated tensors against a correct kernel. Only the plugin knows its
|
||||
* permutation. A kernel that relayouts without an inverse is not at fault, only not checkable
|
||||
* against a dense oracle, and the tools report it by name. */
|
||||
typedef int (*RadUnrelayoutFn)(const RadParam* p, int n_p, int operand, const RadEncoding* enc,
|
||||
const int* sel, const void* src, int64_t src_bytes,
|
||||
const RadTensor* planes, int n_planes);
|
||||
|
||||
/* ================================================================== operand description */
|
||||
/* HOW BIG IS OPERAND i OF THIS OP, AND WHAT MAY BE IN IT.
|
||||
/* How big operand i of an op is, and what values it may hold.
|
||||
*
|
||||
* An op's schema names its operands and their roles but not their extents, because the extents
|
||||
* are not derivable from the parameters in general -- the run phase supplies them at issue. So a
|
||||
* tool that wants to CALL an op cold, which is what a correctness check and a benchmark both do,
|
||||
* has to size its buffers somehow. A hand-written table inside `tools/` cannot serve that: it
|
||||
* covers only the ops someone wrote a row for and skips the rest, it cannot be extended without
|
||||
* patching the engine, and it is a place where a tool knows something about an op.
|
||||
* A schema names operands and their roles but not their extents, which are in general not
|
||||
* derivable from the parameters (the run phase supplies them at issue). A tool that calls an op
|
||||
* cold, such as a correctness check or a benchmark, asks the kernel through this hook instead of
|
||||
* keeping its own table of ops.
|
||||
*
|
||||
* The kernel is the component that knows. This hook asks it.
|
||||
*
|
||||
* WHAT IS IN AN OPERAND MATTERS AS MUCH AS HOW BIG IT IS, and that is why this carries a fill
|
||||
* domain rather than only a shape. A gated-delta-net `g` is an intra-chunk cumulative sum of
|
||||
* log-decays: non-increasing and never positive, because every decay the scan forms is
|
||||
* e^{g_i - g_j} with j <= i and that is <= 1 only because g is monotone. Feed it normals and the
|
||||
* ORACLE overflows to 2e38 while the kernel does something else, and the comparison then measures
|
||||
* the test rather than the kernel. The same is true of a sigmoid gate, of a lower-triangular
|
||||
* factor, and of every index operand: a KV slot indexes n_blocks * block_size positions and a
|
||||
* block-table entry indexes n_blocks, and drawing either from the wrong range tests the kernel's
|
||||
* out-of-range handling and calls the result correctness. */
|
||||
* The fill domain matters as much as the shape. A gated-delta-net `g` is an intra-chunk cumulative
|
||||
* sum of log-decays: non-increasing and never positive, since each decay e^{g_i - g_j} with j <= i
|
||||
* is <= 1 only because g is monotone. Fed normals, the oracle overflows to 2e38 and the comparison
|
||||
* measures the test rather than the kernel. The same holds for a sigmoid gate, a lower-triangular
|
||||
* factor and every index operand: a KV slot indexes n_blocks * block_size positions and a
|
||||
* block-table entry n_blocks, and a draw outside that range tests out-of-range handling instead. */
|
||||
enum {
|
||||
RAD_FILL_NORMAL = 0, /* standard normals -- the default for a float operand */
|
||||
RAD_FILL_SIGMOID = 1, /* (0, 1): a gate */
|
||||
RAD_FILL_GATE_CUMSUM = 2, /* non-increasing and <= 0, reset every `fill_chunk` rows */
|
||||
RAD_FILL_TRI_LOWER = 3, /* zero above the diagonal within a `fill_chunk` block */
|
||||
RAD_FILL_INDEX = 4, /* integers; see idx_max / idx_const / the IDX flags */
|
||||
/* UNIT L2 NORM ALONG THE LAST DIMENSION. The gated-delta-net key is normalised by the
|
||||
* model's own qk_norm before it reaches the solve, and the solve inverts I + tril(beta k k^T,
|
||||
* -1): drawn as unit normals over a 128-wide head that matrix has off-diagonals a hundred
|
||||
* times too large, its inverse is enormous, and two implementations summing an
|
||||
* ill-conditioned product in different orders disagree by however ill-conditioned it is. What
|
||||
* that reports is the condition number of the TEST. Same correction as SIGMOID and
|
||||
* GATE_CUMSUM above: put the operand in the domain the op is only ever handed. */
|
||||
/* Unit L2 norm along the last dimension. The gated-delta-net key is normalised by qk_norm
|
||||
* before the solve, which inverts I + tril(beta k k^T, -1). With unit normals over a 128-wide
|
||||
* head the off-diagonals are ~100x too large, the matrix is ill-conditioned, and two
|
||||
* summation orders disagree by its condition number. Like SIGMOID and GATE_CUMSUM, this puts
|
||||
* the operand in the domain the op is actually given. */
|
||||
RAD_FILL_UNIT_ROW = 5,
|
||||
/* The samplers' `params` plane: [rows, 24] 32-bit words, each row a RadSampleParams
|
||||
* (rad_sample.h) as a request sets it, its flags agreeing with its fields. Drawn as numbers,
|
||||
* the integer fields and `flags` are bit patterns (a window is all or nothing, a mask row is
|
||||
* never in range, each flag is a coin toss) and XTC's threshold is past any probability, so
|
||||
* the mask and XTC stages do nothing and the others act on a random part of the rows.
|
||||
* Row 0 switches every stage on; every other row switches each stage on or leaves it at its
|
||||
* identity at random, and a minority is greedy. `fill_chunk` is the width of the op's history
|
||||
* plane (0 when it has none: the window is then empty) and `idx_max` the row count of its
|
||||
* bitmask plane (0 when it has none: `mask_row` is then -1). A tool that does not know the
|
||||
* value draws normals. */
|
||||
RAD_FILL_SAMPLE_PARAMS = 6,
|
||||
};
|
||||
|
||||
enum {
|
||||
/* An OPTIONAL operand this geometry does not pass. One entry per schema operand is still
|
||||
* emitted -- that count is what catches a hook that has drifted from its schema -- so absence
|
||||
* needs a spelling, and a null RadTensor.data is what the ABI already means by it. */
|
||||
/* An optional operand this geometry does not pass. One entry per schema operand is still
|
||||
* emitted, since that count catches a hook that drifted from its schema; a null
|
||||
* RadTensor.data marks the absence. */
|
||||
RAD_OPD_F_ABSENT = 1u << 0,
|
||||
/* A SCATTER DESTINATION: no value may repeat. Two tokens drawn onto one slot make the store a
|
||||
* race, and two implementations resolve it differently -- so the comparison would measure the
|
||||
* scheduler. A read-side index (a gather row, a block-table entry) may repeat and does. */
|
||||
/* A scatter destination: no value may repeat. Two tokens on one slot make the store a race
|
||||
* that two implementations resolve differently. A read-side index (a gather row, a
|
||||
* block-table entry) may repeat. */
|
||||
RAD_OPD_F_IDX_UNIQUE = 1u << 1,
|
||||
/* CUMULATIVE SEQUENCE LENGTHS, [0, ..., T]. Not a draw: it is the batch's shape. */
|
||||
/* Cumulative sequence lengths, [0, ..., T]: the batch's shape, not a draw. */
|
||||
RAD_OPD_F_IDX_CU = 1u << 2,
|
||||
/* A routing histogram's offsets, [0, ..., idx_max - 1]: non-decreasing, first 0, last the row
|
||||
* count, each bucket a run of random length (moe_scatter's `expert_offset`). A uniform draw is
|
||||
* a malformed histogram that two correct implementations may read differently. Additive:
|
||||
* RAD_ABI_VERSION does not move, and a tool that does not know the flag draws as before. */
|
||||
RAD_OPD_F_IDX_PREFIX = 1u << 3,
|
||||
/* A token history, [rows, width] ids in [0, idx_max): each row repeats itself as generated
|
||||
* text does, drawing on a few ids spread over the range and copying runs of its own earlier
|
||||
* tokens. A uniform draw over a vocabulary never repeats, so a frequency penalty never counts
|
||||
* past one and DRY (which penalises the token that would extend a repeated suffix) never
|
||||
* finds a repeat. Additive, as IDX_PREFIX: a tool that does not know the flag draws uniform
|
||||
* ids. */
|
||||
RAD_OPD_F_IDX_HISTORY = 1u << 4,
|
||||
};
|
||||
|
||||
typedef struct RadOpdDesc {
|
||||
@@ -273,14 +229,15 @@ typedef struct RadOpdDesc {
|
||||
int64_t shape[RAD_MAX_RANK];
|
||||
|
||||
uint32_t fill; /* RAD_FILL_* */
|
||||
int64_t fill_chunk; /* the reset width for GATE_CUMSUM and TRI_LOWER */
|
||||
/* The reset width for GATE_CUMSUM and TRI_LOWER; the history plane's width for
|
||||
* SAMPLE_PARAMS. */
|
||||
int64_t fill_chunk;
|
||||
|
||||
/* RAD_FILL_INDEX only. `idx_max` is the EXCLUSIVE upper bound of the draw; 0 means "the
|
||||
* leading extent of the previous operand", which is the common case and saves every gather
|
||||
* from restating it. `idx_const` >= 0 makes every element that value rather than a draw --
|
||||
* `seqused` is the one that needs it, because a random context length shorter than the query
|
||||
* makes a causal attention read a prefix that does not exist, which both implementations
|
||||
* would then agree about while neither computed what the model asks for. */
|
||||
/* RAD_FILL_INDEX only, except that SAMPLE_PARAMS reads `idx_max` as its bitmask plane's row
|
||||
* count. `idx_max` is the exclusive upper bound of the draw; 0 means the leading extent of the
|
||||
* previous operand, the common case for a gather. `idx_const` >= 0 sets every element to that
|
||||
* value instead of drawing. `seqused` needs it: a random context length shorter than the query
|
||||
* makes causal attention read a prefix that does not exist. */
|
||||
int64_t idx_max;
|
||||
int64_t idx_const; /* -1 to draw */
|
||||
|
||||
@@ -288,95 +245,75 @@ typedef struct RadOpdDesc {
|
||||
} RadOpdDesc;
|
||||
|
||||
/* Fill `out` for operand `operand` of this op at this geometry. `p`/`n_p` is the resolved
|
||||
* parameter list, exactly as `launch` would receive it. Return RAD_OK, or RAD_E_UNSUPPORTED when
|
||||
* this geometry does not carry what the description needs -- a caller SKIPS AND COUNTS that
|
||||
* rather than guessing an extent, because a tool that invents one tests the kernel's bounds
|
||||
* handling and calls the result correctness.
|
||||
* parameter list, exactly as `launch` would receive it. Returns RAD_OK, or RAD_E_UNSUPPORTED when
|
||||
* this geometry lacks what the description needs; a caller skips and counts that instead of
|
||||
* guessing an extent.
|
||||
*
|
||||
* Pure host code, no device memory, no side effects: it is called before anything is allocated. */
|
||||
typedef int (*RadShapeFn)(const RadParam* p, int n_p, int operand, RadOpdDesc* out);
|
||||
|
||||
|
||||
/* ================================================================== tunable instantiation */
|
||||
/* A KERNEL IS A FAMILY, NOT AN IMPLEMENTATION. Tile sizes, split counts, waves per block: which
|
||||
* member of the family is fastest is a property of the shape and the machine, and the only way to
|
||||
* know is to measure it on the machine (spec §15). A library declares the AXES here and the core
|
||||
* takes the cross product.
|
||||
/* A kernel is a family: tile sizes, split counts, waves per block. Which member is fastest
|
||||
* depends on the shape and the machine and must be measured there (spec §15). A library declares
|
||||
* the axes here and the core takes their cross product. Axes rather than a list of named
|
||||
* combinations, because a hand-enumerated list has holes (a shape with 40 rows of work runs a
|
||||
* 64-row tile), and because it keeps the tuning policy out of the launch adapter, where an
|
||||
* out-of-tree author could not write it.
|
||||
*
|
||||
* AXES, NOT A LIST OF PRE-NAMED COMBINATIONS. Hand-enumerating the interesting points of a
|
||||
* multi-axis space -- "wv1_sk8_mb3_npw4" and its twenty-odd siblings -- leaves HOLES, and a hole
|
||||
* costs step time silently: a ladder that skips a value runs the next tile up, so a shape with
|
||||
* forty rows of work gets a sixty-four-row tile. A cross product has no holes.
|
||||
*
|
||||
* It also keeps the tuning LAW out of the launch adapter, where it would be C++ -- ladders, caps,
|
||||
* a hand-written picker -- that an out-of-tree author cannot write.
|
||||
*
|
||||
* THE CHOSEN VALUES ARRIVE AS ORDINARY PARAMETERS. There is no variant index: once the core has
|
||||
* picked a point in the space it appends the choices to RadArgs::p, and the kernel reads `sk` with
|
||||
* the same rad_args_geti() it reads `M` with. One way in, for a value the caller supplied and a
|
||||
* value the tuner chose. */
|
||||
* The chosen values arrive as ordinary parameters appended to RadArgs::p, with no variant index:
|
||||
* the kernel reads `sk` with the same rad_args_geti() it reads `M` with. */
|
||||
typedef struct RadTunable {
|
||||
const char* key; /* the kernel's own name for the axis: "sk", "bm", "npw" */
|
||||
const int64_t* values; /* legal values, ascending; the core tries exactly these */
|
||||
int n_values;
|
||||
/* WHAT RUNS WHEN THIS MACHINE HAS NO MEASUREMENT FOR THIS INSTANTIATION -- a fresh install, a
|
||||
* shape nobody tuned, a cache from another card. There is no fallback beneath it, so it must
|
||||
* be a value the kernel can actually launch: the loader CHECKS that it appears in `values`
|
||||
* and refuses the plugin by name if it does not. */
|
||||
/* The value used when this machine has no measurement for this instantiation (a fresh
|
||||
* install, an untuned shape, a cache from another card). There is no fallback beneath it, so
|
||||
* it must be launchable: the loader checks it appears in `values` and refuses the plugin by
|
||||
* name if not. */
|
||||
int64_t deflt;
|
||||
const char* doc; /* what the axis does, for the tuner's report */
|
||||
} RadTunable;
|
||||
|
||||
/* IS THIS COMBINATION LEGAL AT THIS GEOMETRY? Cross-axis rules live here rather than in the axis
|
||||
* lists, because they are exactly what a product of independent lists cannot say: libr4d's skinny
|
||||
* GEMM needs `wv * sk * 32` inside the block bound AND `K % (sk * unit) == 0`, and neither is a
|
||||
* property of `sk` alone.
|
||||
/* Whether a combination is legal at this geometry. Cross-axis rules live here because independent
|
||||
* axis lists cannot express them: libr4d's skinny GEMM needs `wv * sk * 32` inside the block bound
|
||||
* and `K % (sk * unit) == 0`.
|
||||
*
|
||||
* `p` is the resolved geometry, `choice` the candidate as key/value parameters. Pure host code,
|
||||
* called before anything is allocated, once per candidate.
|
||||
* called once per candidate before anything is allocated.
|
||||
*
|
||||
* Returns 1 for legal and 0 for SKIP -- which is not an error. A kernel may serve a subset of its
|
||||
* own cross product, and the tuner reports a skipped candidate as skipped rather than as a
|
||||
* failure. Null means every combination is legal. */
|
||||
* Returns 1 for legal and 0 for skip, which is not an error: a kernel may serve a subset of its
|
||||
* cross product, and the tuner reports the candidate as skipped. Null means every combination is
|
||||
* legal. */
|
||||
typedef int (*RadTuneValidFn)(const RadParam* p, int n_p, const RadParam* choice, int n_choice);
|
||||
/* ================================================================== op schemas */
|
||||
/* A parameter is supplied by the caller (REQUIRED), may be (OPTIONAL), or is supplied by the
|
||||
* KERNEL (DERIVED).
|
||||
/* A parameter is supplied by the caller (REQUIRED), may be supplied (OPTIONAL), or is supplied by
|
||||
* the kernel (DERIVED).
|
||||
*
|
||||
* DERIVED exists because of a circularity that block_size makes concrete. Spec §7.2 says the
|
||||
* paged block size comes from the resolved attention kernel and not from a core constant --
|
||||
* libr4d is compiled for 16 and rejects anything else. But a constraint whose key the geometry
|
||||
* does not carry does NOT hold (libr4d's rule, and the reason its two-shot all-reduce rows have
|
||||
* to precede the one-shot ones), so a kernel constrained to block_size == 16 can never be
|
||||
* selected by a query that omits block_size -- and the resolution the answer was to be read off
|
||||
* never happens.
|
||||
* DERIVED breaks a circularity. The paged block size comes from the resolved attention kernel, not
|
||||
* a core constant (spec §7.2; libr4d is compiled for 16). But a constraint whose key the geometry
|
||||
* does not carry does not hold (which is also why libr4d's two-shot all-reduce rows must precede
|
||||
* the one-shot ones), so a kernel constrained to block_size == 16 could never be selected by a
|
||||
* query that omits block_size.
|
||||
*
|
||||
* So: constraints on a DERIVED parameter are SKIPPED during matching, and once a kernel wins,
|
||||
* its RAD_C_EQ value for that key is written into the resolved geometry. A caller that supplies
|
||||
* one anyway pins it, and it matches normally -- which is how an operator forces a block size
|
||||
* and gets a refusal by name rather than a silent substitution. A kernel with no EQ on a derived
|
||||
* key leaves it unset, and rad_kv_block_size() reports that rather than returning zero. */
|
||||
* So constraints on a DERIVED parameter are skipped during matching, and the winning kernel's
|
||||
* RAD_C_EQ value for that key is written into the resolved geometry. A caller that supplies one
|
||||
* pins it and it matches normally, so a forced block size is refused by name rather than silently
|
||||
* substituted. A kernel with no EQ on a derived key leaves it unset, and rad_kv_block_size()
|
||||
* reports that rather than returning zero. */
|
||||
enum { RAD_OPTIONAL = 0, RAD_REQUIRED = 1, RAD_DERIVED = 2 };
|
||||
|
||||
/* WHAT A PARAMETER MEANS TO THE CORE, when the core has to act on one it did not invent.
|
||||
*
|
||||
* Almost none of them: a parameter is a key the plugin and the kernel agree on and the core
|
||||
* carries it opaquely, which is the whole reason a third party can add an op. The exception is
|
||||
* the SEQUENCE CHUNK. A linear-state scan tiles the token stream, its kernel is compiled for one
|
||||
* tile length, and the SCHEDULER has to cut its steps on a multiple of that or a chunk straddles
|
||||
* a sequence boundary -- so the core does need to find that one number in a geometry it otherwise
|
||||
* does not read.
|
||||
*
|
||||
* The schema is where that number is named, and the alternative is worse: a core that found it by
|
||||
* SPELLING would carry a list of likely keys ("chunk", "chunk_size", "state_chunk", ...) inside
|
||||
* the scheduler, which makes the core the thing you edit to add a kernel that spells it
|
||||
* differently. Declaring the role costs a field and keeps the core free of that vocabulary. */
|
||||
/* RAD_PROLE_CAPACITY is a count the kernel is handed as a BOUND and never writes past its
|
||||
* operands for: it launches, loops and writes by the extents of the tensors it is given. That is
|
||||
* what lets the activation arena be declared again at a smaller step (RadBuildCtx::shape_probe) --
|
||||
* the kernel keeps the geometry it was selected with, including the real declare's value here,
|
||||
* while its buffers are the smaller step's -- so it is the KERNEL's claim to make, and a fixed
|
||||
* parameter that differs between the two declares without it refuses the smaller size. */
|
||||
/* What a parameter means to the core. The core carries almost every parameter opaquely, which is
|
||||
* what lets a third party add an op. The exception is the sequence chunk: a linear-state scan is
|
||||
* compiled for one tile length, and the scheduler must cut its steps on a multiple of it or a
|
||||
* chunk straddles a sequence boundary. The schema names that role so the core does not have to
|
||||
* find the parameter by guessing its spelling. */
|
||||
/* RAD_PROLE_CAPACITY marks a count the kernel is handed as a bound and never writes past its
|
||||
* operands for: it launches, loops and writes by the extents of the tensors it is given. That lets
|
||||
* the activation arena be declared again at a smaller step (RadBuildCtx::shape_probe) while the
|
||||
* kernel keeps the geometry it was selected with, including the real declare's value here. It is
|
||||
* the kernel's claim to make; without it, a fixed parameter that differs between the two declares
|
||||
* refuses the smaller size. */
|
||||
enum { RAD_PROLE_NONE = 0, RAD_PROLE_SEQ_CHUNK = 1, RAD_PROLE_CAPACITY = 2 };
|
||||
|
||||
typedef struct RadParamSpec {
|
||||
@@ -386,13 +323,12 @@ typedef struct RadParamSpec {
|
||||
int role; /* RAD_PROLE_*; 0 for every parameter the core does not interpret */
|
||||
} RadParamSpec;
|
||||
|
||||
/* Positional operand roles. The core needs to know which operands are weights (so issue can
|
||||
* resolve a handle and wait on the mover) and which are written (so the buffer planner can
|
||||
* compute liveness). It does not need to know anything else about them. */
|
||||
/* RAD_OPD_WTAB is a weight operand whose issue names a RUN of weights rather than one -- a MoE
|
||||
* layer's experts -- and the kernel is handed a device array of pointers. It is a role of its own
|
||||
* and not a flag on RAD_OPD_WEIGHT so that a tool reading the schema knows the operand is not a
|
||||
* plane it can describe with one shape: see RAD_WTAB in rad_runtime.h. */
|
||||
/* Positional operand roles. The core needs to know only which operands are weights (issue resolves
|
||||
* a handle and waits on the mover) and which are written (the buffer planner computes liveness). */
|
||||
/* RAD_OPD_WTAB is a weight operand whose issue names a run of weights (a MoE layer's experts);
|
||||
* the kernel is handed a device array of pointers. It is a separate role, not a flag on
|
||||
* RAD_OPD_WEIGHT, so a tool reading the schema knows the operand is not one plane it can describe
|
||||
* with one shape: see RAD_WTAB in rad_runtime.h. */
|
||||
enum { RAD_OPD_IN = 0, RAD_OPD_OUT = 1, RAD_OPD_INOUT = 2, RAD_OPD_WEIGHT = 3,
|
||||
RAD_OPD_WTAB = 4 };
|
||||
|
||||
@@ -412,46 +348,31 @@ typedef struct RadOpSchema {
|
||||
|
||||
/* ================================================================== declared fusions
|
||||
*
|
||||
* WHAT CHAIN OF CONVENTIONAL OPS DOES THIS KERNEL COMPUTE?
|
||||
* Which chain of conventional ops a kernel computes.
|
||||
*
|
||||
* The obvious design is for a kernel library to advertise that "kernel A can be used to fuse B
|
||||
* and C", and for the engine to apply that repeatedly until the graph converges. spec.md §2.3
|
||||
* refuses the second half -- "a fusion rewriter is a compiler, and a compiler is the thing whose output nobody can
|
||||
* predict" -- and the declare phase keeps nothing a rewriter could work on in any case: `Program`
|
||||
* holds no operand edges. The Builder computes them, collapses each buffer's whole use-set to a
|
||||
* `first_def`/`last_use` pair with reads and writes MERGED, and discards the rest when it returns.
|
||||
* This is a declaration, not a rewriter. spec.md §2.3 rules out a fusion rewriter, and the
|
||||
* declare phase keeps nothing one could work on: `Program` holds no operand edges, and the Builder
|
||||
* collapses each buffer's use-set to a `first_def`/`last_use` pair with reads and writes merged.
|
||||
* "Op A's output is op B's only input" is not recoverable from that, which is also why
|
||||
* `--debug-graph` declines to print an edge it cannot prove.
|
||||
* `--debug-graph` prints no edge it cannot prove. Fusion stays a selection: the architecture asks
|
||||
* for the fused op and emits the sequence when nothing serves it (rad_op_resolved in
|
||||
* rad_builder.h is the idiom for a banded or optional fusion).
|
||||
*
|
||||
* So this is a DECLARATION, not a rewriter. Fusion stays a selection: the architecture asks for
|
||||
* the fused op and emits the sequence when nothing serves it (spec.md 2.3, and rad_op_resolved in
|
||||
* rad_builder.h, which is the idiom an out-of-tree plugin needs for a banded or optional fusion).
|
||||
* What the declaration adds is that the EQUIVALENCE becomes machine-readable instead of prose in a
|
||||
* kernel row -- "byte-identical to the two ops it replaces" -- and prose cannot be checked. It
|
||||
* buys three things:
|
||||
* The declaration makes the equivalence machine-readable, which gives:
|
||||
* - an oracle: a fused kernel with no libref counterpart is checked against its chain run on the
|
||||
* same plugin's unfused rows, and the answer should be byte-identical;
|
||||
* - an advisory in --debug-graph: these declared ops form a chain some kernel can run in one
|
||||
* launch, and why it did not fire;
|
||||
* - the per-library fusion-claim count in rad-kbench's report.
|
||||
*
|
||||
* AN ORACLE, which is the one that matters. A fused kernel with no libref counterpart can only
|
||||
* be skipped by name, and such skips dominate what a coverage run reports on a model built out
|
||||
* of fusions. A fused kernel that declares its chain can instead be checked against that chain
|
||||
* run out of the SAME plugin's unfused rows -- which is precisely the claim the row makes, and
|
||||
* a stronger test than a tolerance against ref, because the answer should be BYTE-IDENTICAL.
|
||||
* It is a hook rather than a table because a step's geometry is not always derivable from the
|
||||
* fused op's: `qk_norm_rope_gate` replaces an `rmsnorm` at M = T * n_head, a product that is not
|
||||
* in its parameter list.
|
||||
*
|
||||
* AN ADVISORY in --debug-graph: these N declared ops are a chain some kernel says it can do in
|
||||
* one launch, and here is why it did not fire.
|
||||
*
|
||||
* A COVERAGE METRIC, which spec.md:19 lists.
|
||||
*
|
||||
* WHY A HOOK AND NOT A TABLE. A step's geometry is not the fused op's geometry and is not always
|
||||
* derivable by a caller: `qk_norm_rope_gate` replaces an `rmsnorm` at M = T * n_head, and nothing
|
||||
* in the fused op's parameter list is that product. The kernel is the component that knows, which
|
||||
* is the same argument RadShapeFn and RadLayoutFn already make.
|
||||
*
|
||||
* OPERAND WIRING. Every operand of every step is either an operand of the FUSED kernel or a
|
||||
* TEMPORARY the chain passes between its own steps. A temporary needs no description here: it is
|
||||
* sized and typed by the step's own `opd_shape`, which every kernel that wants to be checked this
|
||||
* way already publishes. Note how often no temporary is needed at all -- the fp8 folds still WRITE
|
||||
* their intermediate when `out_bf16` is passed, precisely so the fused and unfused forms leave the
|
||||
* same buffers behind. */
|
||||
* Operand wiring: every operand of every step is either an operand of the fused kernel or a
|
||||
* temporary passed between steps. A temporary needs no description here; the step op's own
|
||||
* `opd_shape` sizes and types it. Often none is needed: the fp8 folds still write their
|
||||
* intermediate when `out_bf16` is passed, so the fused and unfused forms leave the same buffers. */
|
||||
enum {
|
||||
RAD_FUSE_NONE = -1, /* this step does not pass that optional operand */
|
||||
};
|
||||
@@ -465,12 +386,11 @@ enum { RAD_MAX_FUSE_OPD = 16, RAD_MAX_FUSE_PARAMS = 12, RAD_MAX_FUSE_TMP = 8 };
|
||||
|
||||
typedef struct RadFuseStep {
|
||||
const char* op; /* a conventional op name -- see docs/OPS.md */
|
||||
RadParam p[RAD_MAX_FUSE_PARAMS]; /* this STEP's geometry, not the fused one's */
|
||||
RadParam p[RAD_MAX_FUSE_PARAMS]; /* this step's geometry, not the fused one's */
|
||||
int n_p;
|
||||
/* One entry per operand of `op`, in its schema's order: an operand index of the fused kernel,
|
||||
* RAD_FUSE_TMP(t), or RAD_FUSE_NONE. The count is checked against the step op's schema, so a
|
||||
* hook that drifts from the vocabulary is a diagnosable error rather than a silent misfire --
|
||||
* the same rule RadShapeFn's operand count follows, and for the same reason. */
|
||||
* hook that drifts from the vocabulary is a diagnosable error (as with RadShapeFn). */
|
||||
int16_t from[RAD_MAX_FUSE_OPD];
|
||||
int n_from;
|
||||
} RadFuseStep;
|
||||
@@ -478,34 +398,22 @@ typedef struct RadFuseStep {
|
||||
/* Describe step `step` of the chain this kernel replaces, for this geometry and variant.
|
||||
*
|
||||
* RAD_OK `out` is filled; ask again with step + 1.
|
||||
* RAD_E_NOTFOUND `step` is past the end. This is how a caller learns the chain's LENGTH,
|
||||
* and it is why there is no count beside the hook: the chain may differ with
|
||||
* the geometry (an `rmsnorm_quant_fp8` with a residual replaces `rmsnorm_add`
|
||||
* and without one replaces `rmsnorm`).
|
||||
* RAD_E_UNSUPPORTED this geometry or variant has no unfused equivalent in the vocabulary. An
|
||||
* honest answer, and the right one wherever a fusion computes something the
|
||||
* conventional ops cannot express between them.
|
||||
* RAD_E_NOTFOUND `step` is past the end. This is how a caller learns the chain's length,
|
||||
* which may differ with the geometry (an `rmsnorm_quant_fp8` with a residual
|
||||
* replaces `rmsnorm_add`, without one `rmsnorm`).
|
||||
* RAD_E_UNSUPPORTED this geometry or variant has no unfused equivalent in the vocabulary.
|
||||
*
|
||||
* A chain must be EXACT, not approximate. A kernel that is merely close to the sequence it names
|
||||
* should publish no hook at all: the whole value of the declaration is that a caller may
|
||||
* substitute one for the other and compare the bytes. */
|
||||
/* WHICH OPTIONAL OPERANDS THIS CALL PASSES, one bit per operand of the FUSED op, bit i set when
|
||||
* operand i is present.
|
||||
* A chain must be exact. A kernel that is merely close to a sequence publishes no hook, because
|
||||
* callers substitute one for the other and compare the bytes. */
|
||||
/* `present` has bit i set when operand i of the fused op is passed. The chain can depend on an
|
||||
* operand, not only on a parameter: `rmsnorm_quant_fp8` replaces `add` -> `rmsnorm` ->
|
||||
* `quant_act_fp8` given a residual and `rmsnorm` -> `quant_act_fp8` without. Inferring presence
|
||||
* from the plugin's own RadShapeFn is right for a checker calling the kernel cold but wrong for a
|
||||
* caller holding a real issue, such as the graph dump. `RAD_FUSE_NONE` cannot express it, since
|
||||
* the operands that vary are the step's required ones.
|
||||
*
|
||||
* THIS IS NOT DECORATION: without it the chain is not answerable at all.
|
||||
* `rmsnorm_quant_fp8` replaces `add` -> `rmsnorm` -> `quant_act_fp8` when it is given a residual
|
||||
* and `rmsnorm` -> `quant_act_fp8` when it is not: THE CHAIN LENGTH ITSELF depends on an operand,
|
||||
* not on a parameter. Without this the hook has to infer presence, and the only honest inference
|
||||
* available is "whatever this plugin's own RadShapeFn publishes" -- which is right for a checker
|
||||
* calling the kernel cold, since that is where its buffers came from, and WRONG for a caller
|
||||
* holding a real issue, which is what the graph dump has. A fold with no residual would be
|
||||
* described as three steps and the advisory would be a lie.
|
||||
*
|
||||
* Nor could `RAD_FUSE_NONE` express it: the operands that vary are the step's REQUIRED ones.
|
||||
*
|
||||
* RAD_FUSE_PRESENT_ALL is what a caller passes when it does not know, and it means exactly "answer
|
||||
* for every operand your description says exists". That is a contract rather than a coupling: the
|
||||
* hook may then assume its own RadShapeFn, and a caller that knows better says so. */
|
||||
* RAD_FUSE_PRESENT_ALL means the caller does not know: answer for every operand your RadShapeFn
|
||||
* says exists. */
|
||||
#define RAD_FUSE_PRESENT_ALL ((uint64_t)~0ull)
|
||||
#define RAD_FUSE_HAS(mask, i) (((mask) >> (i)) & 1ull)
|
||||
|
||||
@@ -522,13 +430,13 @@ typedef struct RadKernelInfo {
|
||||
const char* dtypes;
|
||||
|
||||
int domain; /* RAD_DOMAIN_DEVICE | RAD_DOMAIN_HOST */
|
||||
int priority; /* higher wins WITHIN THIS PLUGIN; ties break on declaration order */
|
||||
int priority; /* higher wins within this plugin; ties break on declaration order */
|
||||
|
||||
const RadConstraint* constraints; int n_constraints;
|
||||
|
||||
/* The axes of this kernel's instantiation space, and the cross-axis legality test. Null/0
|
||||
* means one implementation with nothing to tune, which is the common case and costs nothing:
|
||||
* the core appends no choices and the kernel reads no tuned key. See RadTunable. */
|
||||
/* The axes of this kernel's instantiation space and the cross-axis legality test. Null/0
|
||||
* means one implementation with nothing to tune (the common case): the core appends no
|
||||
* choices and the kernel reads no tuned key. See RadTunable. */
|
||||
const RadTunable* tunables; int n_tunables;
|
||||
RadTuneValidFn tune_valid;
|
||||
|
||||
@@ -538,37 +446,30 @@ typedef struct RadKernelInfo {
|
||||
RadScratchFn scratch;
|
||||
RadLayoutFn layout;
|
||||
RadRelayoutFn relayout;
|
||||
/* How to size and fill each operand, for a tool that calls this kernel cold. Null means this
|
||||
* kernel cannot describe itself and every tool that needs a buffer for it skips it BY NAME
|
||||
* rather than guessing. libref supplies it for the whole conventional vocabulary, so an
|
||||
* op that stays inside docs/OPS.md is describable even when the kernel under test is not. */
|
||||
/* How to size and fill each operand, for a tool that calls this kernel cold. Null means tools
|
||||
* that need a buffer for it skip it by name. libref supplies it for the whole conventional
|
||||
* vocabulary, so an op in docs/OPS.md is describable even when the kernel under test is not. */
|
||||
RadShapeFn opd_shape;
|
||||
/* The inverse of `relayout`, for a tool holding the stored bytes rather than the planes.
|
||||
* Null means this kernel's stored form cannot be read back, and a dense oracle therefore has
|
||||
* nothing to compare against -- which is a skip, named, and not a failure. */
|
||||
/* The inverse of `relayout`, for a tool holding the stored bytes rather than the planes. Null
|
||||
* means the stored form cannot be read back, so a dense oracle has nothing to compare
|
||||
* against: a named skip, not a failure. */
|
||||
RadUnrelayoutFn unrelayout;
|
||||
/* The chain of conventional ops this kernel computes in one launch, or null for a kernel that
|
||||
* is not a fusion. Non-null is also the fusion-coverage metric's numerator: it is a kernel
|
||||
* saying "I stand in for these, and you may check me against them". */
|
||||
RadFuseFn replaces;
|
||||
/* Optional. The same dispatch, described rather than performed, so a repeatedly issued
|
||||
* sequence can be replayed as a graph. Null means this kernel is always submitted
|
||||
* individually, which is correct and merely slower. See RadDescribeFn for the one trap.
|
||||
/* The chain of conventional ops this kernel computes in one launch, or null if it is not a
|
||||
* fusion. Non-null also counts in rad-kbench's fusion-claim column.
|
||||
*
|
||||
* LAST IN THE STRUCT ON PURPOSE. Every kernel table in this tree is a POSITIONAL aggregate
|
||||
* initialiser -- `{..., nullptr, nullptr, r4d_rad_embed_lookup, nullptr, ...}` -- so a field
|
||||
* inserted anywhere else silently shifts every initialiser after it, and `nullptr` converts
|
||||
* to any function pointer type, so part of that shift would compile. Append here. */
|
||||
RadDescribeFn describe;
|
||||
* Keep this field last. Kernel tables are positional aggregate initialisers
|
||||
* (`{..., nullptr, nullptr, r4d_rad_embed_lookup, nullptr, ...}`), so a field inserted
|
||||
* anywhere else shifts every later initialiser, and since `nullptr` converts to any function
|
||||
* pointer type, part of that shift would still compile. Append new fields after this one. */
|
||||
RadFuseFn replaces;
|
||||
} RadKernelInfo;
|
||||
|
||||
/* ================================================================== kernel plugin exports */
|
||||
/* Every kernel plugin exports the whole set. The schemas come first: the first plugin in
|
||||
* hierarchy order to declare an op fixes its schema, and a later plugin declaring the same op
|
||||
* name with a different schema is refused at load with both plugins named. Since arguments are
|
||||
* positional, two disagreeing schemas would make the same call mean different things depending
|
||||
* on which plugin won selection, and that is not a diagnosable failure -- it is silent
|
||||
* numerical garbage (spec §2.3). */
|
||||
/* Every kernel plugin exports the whole set. The first plugin in hierarchy order to declare an op
|
||||
* fixes its schema; a later plugin declaring the same op name with a different schema is refused
|
||||
* at load with both plugins named. Arguments are positional, so disagreeing schemas would make
|
||||
* the same call mean different things depending on which plugin won selection, silently
|
||||
* (spec §2.3). */
|
||||
int rad_kernel_schema_count(void);
|
||||
const RadOpSchema* rad_kernel_schema_at(int i);
|
||||
int rad_kernel_count(void);
|
||||
@@ -577,59 +478,54 @@ const RadKernelInfo* rad_kernel_at(int i);
|
||||
/* Optional. Called once after the plugin is loaded and before any selection, and once at
|
||||
* shutdown. A plugin with no global state need not export them.
|
||||
*
|
||||
* THE SYMBOL NAMES ARE `rad_plugin_open` and `rad_plugin_close`. The types are named here so a
|
||||
* plugin can declare them with the right signature; the loader resolves them by those exact
|
||||
* names, and a plugin that spells them differently is silently never initialised.
|
||||
* The symbol names are `rad_plugin_open` and `rad_plugin_close`; the types exist so a plugin can
|
||||
* declare them with the right signature. The loader resolves those exact names, so a plugin that
|
||||
* spells them differently is silently never initialised.
|
||||
*
|
||||
* `rad_plugin_open` answering RAD_E_UNSUPPORTED DECLINES this machine: the plugin is unloaded and
|
||||
* the rest of the installation carries on, which is how one installation ships libraries for
|
||||
* several cards. Any other negative status refuses the plugin as an error. A kernel library does
|
||||
* not need to decline a card its device code was not built for -- the loader reads that out of
|
||||
* the code objects it carries and leaves its device kernels out on its own. */
|
||||
* `rad_plugin_open` returning RAD_E_UNSUPPORTED declines this machine: the plugin is unloaded and
|
||||
* the rest of the installation carries on, so one installation can ship libraries for several
|
||||
* cards. Any other negative status refuses the plugin as an error. A kernel library need not
|
||||
* decline a card its device code was not built for: the loader reads that from the code objects
|
||||
* and leaves those device kernels out itself. */
|
||||
typedef int (*RadPluginOpenFn) (void);
|
||||
typedef void (*RadPluginCloseFn)(void);
|
||||
|
||||
/* Optional, and a promise about kernel `i` of rad_kernel_at: nonzero means every launch of it
|
||||
* reads and writes no memory but its operands and the scratch it was handed -- no allocation it
|
||||
* keeps for itself, no counter it keeps between launches -- so two launches may run at the same
|
||||
* time on one device whenever their operands and scratch do not overlap. The engine then lets a
|
||||
* launch start before the independent ones in front of it on its queue have finished. A plugin
|
||||
* that does not export the symbol, or answers 0, has every launch ordered behind everything
|
||||
* before it, which is always correct. The symbol name is `rad_kernel_concurrent`. */
|
||||
/* Optional promise about kernel `i` of rad_kernel_at: nonzero means every launch reads and writes
|
||||
* only its operands and the scratch it was handed (no allocation it keeps, no counter kept between
|
||||
* launches), so two launches may run at once on one device when their operands and scratch do not
|
||||
* overlap. The engine then lets such a launch start before independent earlier launches on its
|
||||
* queue finish. Without the symbol, or with 0, every launch is ordered behind everything before
|
||||
* it, which is always correct. Symbol name: `rad_kernel_concurrent`. */
|
||||
typedef int (*RadKernelConcurrentFn)(int i);
|
||||
|
||||
/* Optional, and a promise about kernel `i` of rad_kernel_at: nonzero means it is a COLLECTIVE --
|
||||
* its launches exchange data with the other ranks' cards, so the interconnect carries their bytes
|
||||
* for as long as they run and the step waits on it. The engine then keeps its own bulk traffic on
|
||||
* the same links (weights it streams onto the card while the card computes) out of their way for
|
||||
* that time. A plugin that does not export the symbol, or answers 0, has only the conventional
|
||||
* `all_reduce` op treated as one. The symbol name is `rad_kernel_collective`.
|
||||
/* Optional promise about kernel `i` of rad_kernel_at: nonzero means it is a collective. Its
|
||||
* launches exchange data with the other ranks' cards, so the interconnect carries their bytes
|
||||
* while they run and the step waits on it. The engine keeps its own bulk traffic on those links
|
||||
* (weights streamed to the card during compute) out of the way for that time. Without the symbol,
|
||||
* or with 0, only the conventional `all_reduce` op is treated as a collective. Symbol name:
|
||||
* `rad_kernel_collective`.
|
||||
*
|
||||
* 2 promises more: every launch of the kernel ends that time itself, as soon as the last byte the
|
||||
* other ranks send this card for it has landed -- a kernel that reduces after the exchange has the
|
||||
* link to spare for the rest of its run. The engine then hands each launch it holds the link for
|
||||
* the parameter `link_gate`, the address of a 64-bit word in memory the kernel reaches at system
|
||||
* scope; a launch without it holds nothing and has nothing to end. The kernel reads the word on
|
||||
* the device as it starts -- not the host in the launch call, where the hold has not taken effect
|
||||
* yet -- and, once those bytes have landed, takes one off it with a system-scope atomic if it was
|
||||
* odd; an even word it leaves alone. A launch that did so returns RAD_LINK_ENDED; any other
|
||||
* success is RAD_OK, and the engine then ends the hold behind the launch, so a path that does not
|
||||
* know the word is always safe. */
|
||||
* 2 promises more: each launch ends the link hold itself as soon as the last byte the other ranks
|
||||
* send this card for it has landed, so a kernel that reduces after the exchange frees the link for
|
||||
* the rest of its run. The engine then passes each launch it holds the link for the parameter
|
||||
* `link_gate`, the address of a 64-bit word the kernel reaches at system scope; a launch without
|
||||
* it holds nothing. The kernel reads the word on the device as it starts (not on the host in the
|
||||
* launch call, where the hold is not yet in effect) and, once those bytes have landed, decrements
|
||||
* it with a system-scope atomic if it was odd; an even word it leaves alone. A launch that
|
||||
* decremented returns RAD_LINK_ENDED. Any other success returns RAD_OK and the engine ends the
|
||||
* hold behind the launch, so a path that ignores the word is always safe. */
|
||||
typedef int (*RadKernelCollectiveFn)(int i);
|
||||
#define RAD_LINK_ENDED 1
|
||||
|
||||
/* Optional: nonzero declares this kernel library a REFERENCE implementation -- written to be
|
||||
* plainly correct rather than fast. Three things follow, for any library that says so and for no
|
||||
* other, whatever it is called:
|
||||
/* Optional: nonzero declares this kernel library a reference implementation, written to be
|
||||
* plainly correct rather than fast. For any library that says so, whatever its name:
|
||||
* - the loader ranks it below every unnamed kernel library, because a reference matches every
|
||||
* op it declares and would otherwise answer for them ahead of the library serving the card
|
||||
* (naming it in --kernels still puts it where it is named, and a --kernels list that does
|
||||
* not name it leaves it out);
|
||||
* op it declares and would otherwise win over the library serving the card (naming it in
|
||||
* --kernels still places it where named, and a --kernels list that omits it leaves it out);
|
||||
* - the engine refuses to serve a model with an op only a reference library implements, unless
|
||||
* told to with --debug-accept-reference-kernels;
|
||||
* given --debug-accept-reference-kernels;
|
||||
* - rad-kbench checks every other library against it.
|
||||
* A plugin that does not export the symbol, or answers 0, is an ordinary library. The symbol name
|
||||
* is `rad_plugin_reference`. */
|
||||
* Without the symbol, or with 0, it is an ordinary library. Symbol name: `rad_plugin_reference`. */
|
||||
typedef int (*RadPluginReferenceFn)(void);
|
||||
|
||||
#ifdef __cplusplus
|
||||
|
||||
+385
-404
File diff suppressed because it is too large.
Load diff
+9
-11
@@ -1,10 +1,9 @@
|
||||
/* 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.
|
||||
/* rad_device.h -- the device layer. Deliberately thin: everything above it is written once, and
|
||||
* every backend implements 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).
|
||||
* The host backend is a full backend. It lets the core, scheduler, planner, tokeniser, server and
|
||||
* libref be built and tested without an accelerator, and RAD_DOMAIN_HOST kernels run on it when the
|
||||
* planner puts a layer on the CPU (spec §5.1).
|
||||
*/
|
||||
#ifndef RAD_DEVICE_H
|
||||
#define RAD_DEVICE_H
|
||||
@@ -19,12 +18,11 @@ 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.
|
||||
/* Everything the engine knows about a device. Nothing above this layer names a vendor, product or
|
||||
* instruction set: the scheduler, planner and budgets learn the machine from these fields at run
|
||||
* time. Hardware knowledge belongs in kernel libraries, which declare the devices they serve.
|
||||
*
|
||||
* Every field carries whatever the backend reports, in the backend's own vocabulary. */
|
||||
* Every field carries what 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
|
||||
|
||||
+32
-33
@@ -1,24 +1,24 @@
|
||||
/* rad_encoding.h -- what a stored weight's numbers ARE, independently of how any kernel wants them
|
||||
/* rad_encoding.h -- what a stored weight's numbers are, independent 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 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 applied before quantisation. It is a
|
||||
* property of the model: choosing one is lossy and can be expensive (GPTQ needs 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,
|
||||
* applied when the model loads (rad_abi.h). A container holds encodings only, so a kernel library
|
||||
* can change any layout 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.
|
||||
* An encoding is data rather than an enum value, so a quantiser plugin can invent one without the
|
||||
* core knowing it. The core can size, slice and place any encoding from this struct alone, and
|
||||
* decodes every encoding of the one scheme it defines, "affine". That scheme covers the common
|
||||
* formats: 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.
|
||||
* 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]
|
||||
@@ -30,25 +30,24 @@
|
||||
* 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.
|
||||
* 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) 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. A kernel that wants its nibbles permuted for its own unpack does so in its relayout.
|
||||
*
|
||||
* ===================================================================== THE AFFINE SCHEME
|
||||
*
|
||||
* The planes are found by ROLE, and only "codes" is required. A weight element decodes as
|
||||
* 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
|
||||
* 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 = 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
|
||||
* 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
|
||||
* 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
|
||||
@@ -59,23 +58,23 @@
|
||||
* ===================================================================== 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.
|
||||
* 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
|
||||
* "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 activation is rotated by the unnormalised H_N 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.
|
||||
* GPTQ's act-order, which quantises the columns in a different order than stored.
|
||||
* "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.
|
||||
* A weight whose row PARTS were rotated independently (a fused gate_up, a fused
|
||||
* A weight whose row parts were rotated independently (a fused gate_up, a fused
|
||||
* q|k|v: each projection has its own rotation) carries P parts: TABLE "t.part" i32
|
||||
* [1 x P] holds the END ROW (exclusive) of each part, and the other tables stack the
|
||||
* [1 x P] holds the end row (exclusive) of each part, and the other tables stack the
|
||||
* parts in order -- t.pairs and t.angle S rows a part (P*S rows), t.scale one row a
|
||||
* part (P rows). Without "t.part" the weight is one part. The stages of a part are
|
||||
* applied in table order, and a part's pairs address columns of the whole row.
|
||||
@@ -233,8 +232,8 @@ static inline int64_t rad_enc_givens_parts(const RadEncoding* e) {
|
||||
e->plane[i].extent[1] >= 1 ? e->plane[i].extent[1] : 0;
|
||||
}
|
||||
|
||||
/* 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. */
|
||||
/* Byte-for-byte equality. Valid because the strings are always zero-padded, so memcmp sees only
|
||||
* meaningful bytes. */
|
||||
static inline int rad_enc_equal(const RadEncoding* a, const RadEncoding* b) {
|
||||
return a && b && memcmp(a, b, sizeof *a) == 0;
|
||||
}
|
||||
|
||||
+10
-10
@@ -1,6 +1,6 @@
|
||||
/* 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
|
||||
* 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)
|
||||
@@ -13,8 +13,8 @@
|
||||
* 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. */
|
||||
* There is one format version. A file in any other is refused with an instruction to convert
|
||||
* again, so there is a single reader with a single set of invariants. */
|
||||
#ifndef RAD_FORMAT_H
|
||||
#define RAD_FORMAT_H
|
||||
|
||||
@@ -74,7 +74,7 @@ typedef struct RadFileKV {
|
||||
enum { RAD_KV_F64 = 100 };
|
||||
|
||||
/* ------------------------------------------------------------------ weight directory */
|
||||
/* One LOGICAL weight: what a declaration's `source` names (RadWeightDecl). Fixed stride, so an
|
||||
/* 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 {
|
||||
@@ -84,7 +84,7 @@ typedef struct RadFileEntry {
|
||||
|
||||
uint32_t enc; /* index into the encoding table */
|
||||
uint32_t rank;
|
||||
int64_t shape[RAD_MAX_RANK]; /* the LOGICAL shape */
|
||||
int64_t shape[RAD_MAX_RANK]; /* the logical shape */
|
||||
|
||||
int32_t layer; /* RadWeightGroup, flattened: the movement unit */
|
||||
int32_t expert;
|
||||
@@ -105,9 +105,9 @@ typedef struct RadFilePlane {
|
||||
} 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. */
|
||||
/* Derived from the imatrix's activation counts. A warm start, not a policy (spec §5.3): a
|
||||
* calibration set routes differently from decoding, so this gives only a small residency hit-rate
|
||||
* gain over starting cold. */
|
||||
typedef struct RadFileProfile {
|
||||
int32_t layer;
|
||||
int32_t expert;
|
||||
@@ -116,8 +116,8 @@ typedef struct RadFileProfile {
|
||||
} 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). */
|
||||
/* rad-convert interprets tokenizer.json and bakes the result here, rather than hashing the file
|
||||
* against a hardcoded enum as 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. */
|
||||
|
||||
+3
-3
@@ -1,9 +1,9 @@
|
||||
#ifndef RAD_PHILOX_H
|
||||
#define RAD_PHILOX_H
|
||||
|
||||
/* Counter-based Gaussian noise, the one definition every kernel library computes it by, so an
|
||||
* image's starting latent is a function of its seed and of nothing else: not the batch it shares a
|
||||
* pass with, not the rank count, not the order its rows are visited in.
|
||||
/* Counter-based Gaussian noise, the single definition every kernel library uses, so an image's
|
||||
* starting latent depends only on its seed: not on the batch it shares a pass with, the rank
|
||||
* count, or the order its rows are visited in.
|
||||
*
|
||||
* Element e of a seed's stream is Philox4x32-10 at counter (e / 4, 0) keyed by the 64-bit seed,
|
||||
* its four words made uniform in (0, 1) as ((w >> 8) + 0.5) * 2^-24 and paired by Box-Muller --
|
||||
|
||||
@@ -0,0 +1,197 @@
|
||||
/* rad_planes.h -- the joined form of a weight operand that takes several planes, for kernels that
|
||||
* read the planes as the container stores them. spec.md §4.3.
|
||||
*
|
||||
* A weight can be declared over several planes of one stored tensor (RadWeightDecl::planes:
|
||||
* "scale,zero", "codes,table", or every plane of an fp8 lm head), and it reaches a kernel as one
|
||||
* operand, so something has to say where each plane lies. A kernel that wants the planes
|
||||
* rearranged for its own reads says so in its layout hook (rad_abi.h, RadLayoutFn). One that reads
|
||||
* them unchanged uses this form instead:
|
||||
*
|
||||
* [header][entry 0][entry 1]... padded to RAD_PLANES_ALIGN
|
||||
* plane 0 dense rows, padded to RAD_PLANES_ALIGN
|
||||
* plane 1 ...
|
||||
*
|
||||
* The header and the entries describe each selected plane (its role, dtype, block, this rank's
|
||||
* extents and where its bytes start), so a launch finds its planes from the operand alone, without
|
||||
* the encoding. Each plane is the canonical bytes (rad_encoding.h), unchanged: the conversion is a
|
||||
* copy and its inverse is one too.
|
||||
*
|
||||
* A library implements its layout, relayout and unrelayout hooks with the three functions below
|
||||
* and reads at launch with rad_planes_find. Every library that uses this form stores the same bytes
|
||||
* under the same tag, so two such libraries serving different bands of one op read one stored
|
||||
* weight. A selection of one plane is not joined: rad_planes_layout declines it, and the weight is
|
||||
* stored as it is.
|
||||
*
|
||||
* Pure C, header-only, like the rest of abi/.
|
||||
*/
|
||||
#ifndef RAD_PLANES_H
|
||||
#define RAD_PLANES_H
|
||||
|
||||
#include "rad_abi.h"
|
||||
#include "rad_encoding.h"
|
||||
|
||||
#include <string.h>
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
#define RAD_PLANES_TAG "rad.planes"
|
||||
#define RAD_PLANES_MAGIC 0x534e4c50u /* "PLNS" */
|
||||
enum { RAD_PLANES_ALIGN = 64 };
|
||||
|
||||
/* One selected plane. `offset` counts from the start of the joined bytes. */
|
||||
typedef struct RadPlanesEntry {
|
||||
char role[RAD_ENC_STR];
|
||||
uint32_t dtype;
|
||||
uint32_t kind; /* RAD_PLANE_TILED | RAD_PLANE_TABLE */
|
||||
int64_t block[2]; /* the encoding's block (TILED) or extent (TABLE) */
|
||||
int64_t rows, cols; /* this rank's extents of the plane, in its own elements */
|
||||
int64_t row_bytes; /* rad_dtype_bytes(dtype, cols): every row starts on a byte */
|
||||
int64_t offset;
|
||||
} RadPlanesEntry;
|
||||
|
||||
typedef struct RadPlanesHeader {
|
||||
uint32_t magic;
|
||||
int32_t n_planes;
|
||||
char transform[RAD_ENC_STR]; /* the encoding's, for a kernel that checks it */
|
||||
int64_t bytes; /* the whole joined form, padding included */
|
||||
} RadPlanesHeader;
|
||||
|
||||
static inline int64_t rad_planes_round(int64_t n) {
|
||||
return (n + RAD_PLANES_ALIGN - 1) / RAD_PLANES_ALIGN * RAD_PLANES_ALIGN;
|
||||
}
|
||||
|
||||
/* The joined form's entries for the planes a layout hook was handed, and its total size; -1 when
|
||||
* the planes cannot be joined (no planes, more than RAD_ENC_MAX_PLANES, an index outside the
|
||||
* encoding, or a plane with no byte size). */
|
||||
static inline int64_t rad_planes_plan(const RadEncoding* enc, const int* sel,
|
||||
const RadTensor* planes, int n_planes, RadPlanesEntry* e) {
|
||||
int64_t off;
|
||||
int i;
|
||||
if (!enc || !sel || !planes || n_planes < 1 || n_planes > RAD_ENC_MAX_PLANES) return -1;
|
||||
off = rad_planes_round((int64_t)sizeof(RadPlanesHeader) +
|
||||
(int64_t)n_planes * (int64_t)sizeof(RadPlanesEntry));
|
||||
for (i = 0; i < n_planes; ++i) {
|
||||
const RadEncPlane* p;
|
||||
if (sel[i] < 0 || sel[i] >= enc->n_planes) return -1;
|
||||
p = &enc->plane[sel[i]];
|
||||
memset(&e[i], 0, sizeof e[i]);
|
||||
memcpy(e[i].role, p->role, RAD_ENC_STR);
|
||||
e[i].dtype = planes[i].dtype;
|
||||
e[i].kind = p->kind;
|
||||
e[i].block[0] = p->kind == RAD_PLANE_TABLE ? p->extent[0] : p->block[0];
|
||||
e[i].block[1] = p->kind == RAD_PLANE_TABLE ? p->extent[1] : p->block[1];
|
||||
e[i].rows = planes[i].rank >= 2 ? planes[i].shape[0] : 1;
|
||||
e[i].cols = planes[i].rank >= 2 ? planes[i].shape[1]
|
||||
: (planes[i].rank == 1 ? planes[i].shape[0] : 0);
|
||||
e[i].row_bytes = rad_dtype_bytes(e[i].dtype, e[i].cols);
|
||||
if (e[i].rows < 0 || e[i].row_bytes <= 0) return -1;
|
||||
e[i].offset = off;
|
||||
off = rad_planes_round(off + e[i].rows * e[i].row_bytes);
|
||||
}
|
||||
return off;
|
||||
}
|
||||
|
||||
/* RadLayoutFn's answer for the joined form. RAD_E_UNSUPPORTED for a single plane, which is stored
|
||||
* as it is. The stored dtype is the first plane's, so a launch that dispatches on the operand's
|
||||
* dtype still sees the codes' (or the scale's) type; the stored shape is the byte count. */
|
||||
static inline int rad_planes_layout(const RadEncoding* enc, const int* sel, const RadTensor* planes,
|
||||
int n_planes, RadLayout* out) {
|
||||
RadPlanesEntry e[RAD_ENC_MAX_PLANES];
|
||||
int64_t bytes;
|
||||
if (n_planes == 1) return RAD_E_UNSUPPORTED;
|
||||
bytes = rad_planes_plan(enc, sel, planes, n_planes, e);
|
||||
if (bytes < 0 || !out) return RAD_E_SHAPE;
|
||||
memset(out, 0, sizeof *out);
|
||||
out->tag = RAD_PLANES_TAG;
|
||||
out->dtype = planes[0].dtype;
|
||||
out->rank = 1;
|
||||
out->shape[0] = bytes;
|
||||
out->align = RAD_PLANES_ALIGN;
|
||||
out->bytes = bytes;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* RadRelayoutFn: the header, the entries and each plane's rows, copied. The planes are dense, as
|
||||
* the loader hands them. */
|
||||
static inline int rad_planes_relayout(const RadEncoding* enc, const int* sel,
|
||||
const RadTensor* planes, int n_planes, void* dst,
|
||||
int64_t dst_bytes) {
|
||||
RadPlanesEntry e[RAD_ENC_MAX_PLANES];
|
||||
RadPlanesHeader h;
|
||||
uint8_t* d = (uint8_t*)dst;
|
||||
int i;
|
||||
const int64_t bytes = rad_planes_plan(enc, sel, planes, n_planes, e);
|
||||
if (bytes < 0 || !dst || dst_bytes < bytes) return RAD_E_SHAPE;
|
||||
memset(d, 0, (size_t)bytes);
|
||||
memset(&h, 0, sizeof h);
|
||||
h.magic = RAD_PLANES_MAGIC;
|
||||
h.n_planes = n_planes;
|
||||
memcpy(h.transform, enc->transform, RAD_ENC_STR);
|
||||
h.bytes = bytes;
|
||||
memcpy(d, &h, sizeof h);
|
||||
memcpy(d + sizeof h, e, (size_t)n_planes * sizeof e[0]);
|
||||
for (i = 0; i < n_planes; ++i) {
|
||||
if (!planes[i].data && e[i].rows * e[i].row_bytes > 0) return RAD_E_INVAL;
|
||||
if (e[i].rows * e[i].row_bytes > 0)
|
||||
memcpy(d + e[i].offset, planes[i].data, (size_t)(e[i].rows * e[i].row_bytes));
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* RadUnrelayoutFn: the planes back out of the joined form, into the buffers `planes` carry. */
|
||||
static inline int rad_planes_unrelayout(const RadEncoding* enc, const int* sel, const void* src,
|
||||
int64_t src_bytes, const RadTensor* planes, int n_planes) {
|
||||
RadPlanesEntry e[RAD_ENC_MAX_PLANES];
|
||||
const uint8_t* s = (const uint8_t*)src;
|
||||
int i;
|
||||
const int64_t bytes = rad_planes_plan(enc, sel, planes, n_planes, e);
|
||||
if (bytes < 0 || !src || src_bytes < bytes) return RAD_E_SHAPE;
|
||||
for (i = 0; i < n_planes; ++i) {
|
||||
if (!planes[i].data && e[i].rows * e[i].row_bytes > 0) return RAD_E_INVAL;
|
||||
if (e[i].rows * e[i].row_bytes > 0)
|
||||
memcpy(planes[i].data, s + e[i].offset, (size_t)(e[i].rows * e[i].row_bytes));
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ================================================================== reading one at launch */
|
||||
|
||||
/* The joined form's header, or null when `base` does not hold one. */
|
||||
static inline const RadPlanesHeader* rad_planes_header(const void* base) {
|
||||
const RadPlanesHeader* h = (const RadPlanesHeader*)base;
|
||||
if (!h || h->magic != RAD_PLANES_MAGIC || h->n_planes < 1 ||
|
||||
h->n_planes > RAD_ENC_MAX_PLANES)
|
||||
return 0;
|
||||
return h;
|
||||
}
|
||||
|
||||
/* Entry `i`, or null. */
|
||||
static inline const RadPlanesEntry* rad_planes_entry(const void* base, int i) {
|
||||
const RadPlanesHeader* h = rad_planes_header(base);
|
||||
if (!h || i < 0 || i >= h->n_planes) return 0;
|
||||
return (const RadPlanesEntry*)((const uint8_t*)base + sizeof(RadPlanesHeader)) + i;
|
||||
}
|
||||
|
||||
/* The plane with this role: its bytes, and its entry through `out` when given; null when the
|
||||
* joined form has no such plane. */
|
||||
static inline const void* rad_planes_find(const void* base, const char* role,
|
||||
const RadPlanesEntry** out) {
|
||||
const RadPlanesHeader* h = rad_planes_header(base);
|
||||
int i;
|
||||
if (!h || !role) return 0;
|
||||
for (i = 0; i < h->n_planes; ++i) {
|
||||
const RadPlanesEntry* e = rad_planes_entry(base, i);
|
||||
if (strncmp(e->role, role, RAD_ENC_STR) == 0) {
|
||||
if (out) *out = e;
|
||||
return (const uint8_t*)base + e->offset;
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
#ifdef __cplusplus
|
||||
} /* extern "C" */
|
||||
#endif
|
||||
#endif /* RAD_PLANES_H */
|
||||
+136
-115
@@ -2,32 +2,28 @@
|
||||
*
|
||||
* ===================================================================== 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.
|
||||
* A plugin exports the symbols in rad_abi.h and links nothing of radiance's, so it has only the
|
||||
* raw structs. This header supplies the helpers every plugin would otherwise rewrite: an
|
||||
* optional-operand fetch, parameters with defaults, row pitch, and f32<->bf16/f16/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.
|
||||
* Two of them are contracts, not conveniences. 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 cannot be checked against the reference. And an
|
||||
* absent optional operand is a null RadTensor.data, not a short operand count; getting that wrong
|
||||
* silently shifts every later operand 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.
|
||||
* Here: pure, total, header-only functions over the ABI's own types. Nothing allocates, holds
|
||||
* state or calls back into the core, and nothing may start to.
|
||||
*
|
||||
* 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.
|
||||
* Not here: anything that needs the core. Device allocations, streams and builder handles come
|
||||
* from rad_device.h / rad_builder.h / rad_runtime.h, which the host exports; the loader's ABI
|
||||
* check covers them.
|
||||
*
|
||||
* 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.
|
||||
* This header is optional. A plugin that includes only rad_abi.h is complete; this is
|
||||
* convenience plus one shared definition of the rounding.
|
||||
*
|
||||
* Pure C, like the rest of abi/. See spec.md 2.
|
||||
*/
|
||||
@@ -44,9 +40,8 @@ extern "C" {
|
||||
|
||||
/* ================================================================== 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. */
|
||||
* Two families: `launch` and `scratch` get a RadArgs; `layout`, `relayout`, `unrelayout` and
|
||||
* `opd_shape` get a bare (const RadParam*, int) pair with no tensors. */
|
||||
|
||||
static inline const RadParam* rad_param_find(const RadParam* p, int n_p, const char* key) {
|
||||
if (!p || !key) return 0;
|
||||
@@ -55,27 +50,20 @@ static inline const RadParam* rad_param_find(const RadParam* p, int n_p, const c
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* An int parameter, or `dflt` if the key is absent or is not an int.
|
||||
/* An int parameter, or `dflt` if the key is absent or 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. */
|
||||
* A range is deliberately not accepted: by the time a kernel runs, the ranged axis has been
|
||||
* resolved to a value, so a range reaching a launch is a selection bug that returning its low
|
||||
* bound would hide. */
|
||||
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. */
|
||||
/* The same read for a shape hook, the one place a range is legitimate; it reads as its high
|
||||
* bound. `opd_shape` sizes buffers before selection has collapsed anything, so over a banded op it
|
||||
* describes the whole band, and the high end covers the low. */
|
||||
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);
|
||||
@@ -96,9 +84,8 @@ static inline double rad_param_getf(const RadParam* p, int n_p, const char* 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. */
|
||||
/* The dtype a parameter names, parsed. RAD_DT_INVALID if the key is absent or unrecognised, which
|
||||
* a kernel should treat as a refusal. */
|
||||
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));
|
||||
}
|
||||
@@ -121,31 +108,23 @@ static inline double rad_args_getf_or(const RadArgs* a, const char* key, double
|
||||
|
||||
/* ================================================================== operands
|
||||
*
|
||||
* THE ABSENT-OPERAND RULE, WHICH IS THE EASIEST THING IN THIS ABI TO GET WRONG.
|
||||
* The absent-operand rule: an optional operand a call does not pass is a RadTensor whose `data`
|
||||
* is null, not a shorter `n_t`. Operands are positional, so treating absence as a shorter array
|
||||
* would read operand i+1 for operand i and produce wrong numbers without a fault.
|
||||
*
|
||||
* 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. */
|
||||
* There is always one entry per schema operand. This returns null both past the end and for a
|
||||
* null `data`; a caller that sees the former has a schema disagreement, not an absent operand. */
|
||||
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. */
|
||||
/* There is deliberately no rad_arg_out. 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 outputs
|
||||
* are fetched with rad_arg_in too. */
|
||||
|
||||
/* Are the first `n` operands all present? The usual opening line of a launch, where the required
|
||||
* ones are a prefix. */
|
||||
/* Are the first `n` operands all present? For a launch whose required operands 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;
|
||||
@@ -154,8 +133,8 @@ static inline int rad_args_have(const RadArgs* a, int n) {
|
||||
/* ================================================================== 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. */
|
||||
* structural, as a row-owning kernel (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;
|
||||
@@ -167,36 +146,32 @@ 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). */
|
||||
/* The element distance between consecutive rows: the stride of the second-to-last axis (the last
|
||||
* extent when contiguous). 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). */
|
||||
/* Is `p` aligned to `bytes`? The ABI does not promise alignment and a constraint row cannot
|
||||
* express it, so a kernel issuing wide loads checks it in the entry point (rad_types.h). */
|
||||
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.
|
||||
* These define what a result is, so they are stated once here.
|
||||
*
|
||||
* 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.
|
||||
* libref's contract, which 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. A plugin whose bf16 narrowing truncates is off by up to
|
||||
* one ulp on every element and cannot be checked against the reference.
|
||||
*
|
||||
* 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. */
|
||||
* Every conversion is exact when widening and RTNE when narrowing, and keeps subnormals rather
|
||||
* than flushing them: the hardware decodes subnormals, 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;
|
||||
@@ -205,10 +180,9 @@ static inline float rad_bf16_to_f32(uint16_t h) {
|
||||
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. */
|
||||
/* `(u >> 16) & 1` is the tie-break: it adds one more than the halfway point when the surviving
|
||||
* bit is odd, so ties go to even. Overflow carries into 0x7f80, the bf16 infinity. A NaN is forced
|
||||
* quiet so it cannot round into an infinity. */
|
||||
static inline uint16_t rad_f32_to_bf16(float f) {
|
||||
uint32_t u;
|
||||
memcpy(&u, &f, 4);
|
||||
@@ -240,8 +214,8 @@ static inline float rad_f16_to_f32(uint16_t h) {
|
||||
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. */
|
||||
/* RTNE, with subnormals and overflow-to-infinity handled explicitly rather than by a hardware
|
||||
* convert whose rounding mode a caller could have changed. */
|
||||
static inline uint16_t rad_f32_to_f16(float f) {
|
||||
uint32_t u;
|
||||
memcpy(&u, &f, 4);
|
||||
@@ -279,9 +253,9 @@ static inline uint16_t rad_f32_to_f16(float f) {
|
||||
}
|
||||
}
|
||||
|
||||
/* 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. */
|
||||
/* OCP fp8 e4m3 ("e4m3fn"): 1-4-3, bias 7, no infinity, S1111111 is the only NaN, max 448. The
|
||||
* KV-cache and block-scaled weight format, so the attention oracle and every fp8 GEMM depend on
|
||||
* its rounding. */
|
||||
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;
|
||||
@@ -306,9 +280,8 @@ static inline float rad_fp8e4m3_to_f32(uint8_t b) {
|
||||
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. */
|
||||
/* Saturates at 448 rather than overflowing: a NaN for one large activation would spread through
|
||||
* the whole row. 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);
|
||||
@@ -321,10 +294,10 @@ static inline uint8_t rad_f32_to_fp8e4m3(float f) {
|
||||
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. */
|
||||
/* The smallest subnormal is 2^-9, so everything below 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 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;
|
||||
@@ -349,9 +322,12 @@ static inline uint8_t rad_f32_to_fp8e4m3(float f) {
|
||||
}
|
||||
}
|
||||
|
||||
/* 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. */
|
||||
/* 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.
|
||||
*
|
||||
* Narrowing rounds to f16 and then drops the low byte. Every e5m2 tie point is an f16 value, so
|
||||
* the f16 step can move `f` onto a tie but never across one; when it lands on a tie, `f`'s side
|
||||
* of it decides, and only an exact tie goes to even. That makes the result one RTNE of `f`. */
|
||||
static inline float rad_fp8e5m2_to_f32(uint8_t b) {
|
||||
return rad_f16_to_f32((uint16_t)((uint16_t)b << 8));
|
||||
}
|
||||
@@ -360,19 +336,30 @@ 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);
|
||||
/* A NaN keeps its top payload bits and stays quiet; rounding its low byte could carry it out
|
||||
* of the exponent into a zero of the other sign. */
|
||||
if ((h & 0x7fffu) > 0x7c00u) return (uint8_t)(q | 0x02u);
|
||||
if (lo == 0x80u && (h & 0x7c00u) != 0x7c00u) {
|
||||
/* Magnitudes of non-negative floats order as their bit patterns. */
|
||||
float t = rad_f16_to_f32(h);
|
||||
uint32_t uf, ut;
|
||||
memcpy(&uf, &f, 4);
|
||||
memcpy(&ut, &t, 4);
|
||||
uf &= 0x7fffffffu;
|
||||
ut &= 0x7fffffffu;
|
||||
if (uf != ut) return (uint8_t)(uf > ut ? q + 1u : q);
|
||||
}
|
||||
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. */
|
||||
/* OCP FP4 e2m1: 1-2-1, bias 1, no infinity or NaN; all sixteen codes are numbers, max 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. */
|
||||
/* OCP FP6, both forms. No infinity or NaN; e2m3 has bias 1 and max 7.5, e3m2 bias 3 and max 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);
|
||||
@@ -382,7 +369,7 @@ static inline float rad_fp6_to_f32(uint8_t c, int ebits) {
|
||||
return (c & 0x20) ? -mag : mag;
|
||||
}
|
||||
|
||||
/* THE BIT STREAM, for every element narrower than a byte or not a power of two wide.
|
||||
/* 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
|
||||
@@ -444,13 +431,11 @@ static inline float rad_e8m0_to_f32(uint8_t e) {
|
||||
/* ================================================================== 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.
|
||||
* kernel and a converter both need, and the one place the dtype enum and the conversions above
|
||||
* meet. Returns 0 for a dtype it cannot read, which a caller must treat as a refusal, not 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. */
|
||||
* For sub-byte dtypes `i` counts elements from `base`, which is valid only within one row: rows
|
||||
* start on a byte (rad_encoding.h), so a caller crossing rows steps `base` by a row's bytes. */
|
||||
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;
|
||||
@@ -482,10 +467,10 @@ static inline float rad_load_f32(const void* base, uint32_t dtype, int64_t i) {
|
||||
}
|
||||
}
|
||||
|
||||
/* 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. */
|
||||
/* Store the raw code of element `i` of a sub-byte or byte plane (the chosen bit pattern, masked to
|
||||
* the dtype's width), leaving 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' counterpart to 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;
|
||||
@@ -495,6 +480,28 @@ static inline int rad_store_code(void* base, uint32_t dtype, int64_t i, int code
|
||||
return 1;
|
||||
}
|
||||
|
||||
/* `v` rounded to the nearest integer, ties to even, and clamped to [lo, hi]; NaN is 0. Exact and
|
||||
* independent of the rounding mode: a float of magnitude 2^23 or more is already an integer, and
|
||||
* below that its fraction is exact in a double. */
|
||||
static inline double rad_round_even_sat(float v, double lo, double hi) {
|
||||
double d = (double)v, r;
|
||||
if (v != v) return 0.0;
|
||||
if (d >= 8388608.0 || d <= -8388608.0) {
|
||||
r = d;
|
||||
} else {
|
||||
const long long t = (long long)d; /* toward zero */
|
||||
const double f = d - (double)t;
|
||||
long long n = t;
|
||||
if (f > 0.5 || (f == 0.5 && (t & 1))) ++n;
|
||||
else if (f < -0.5 || (f == -0.5 && (t & 1))) --n;
|
||||
r = (double)n;
|
||||
}
|
||||
return r < lo ? lo : (r > hi ? hi : r);
|
||||
}
|
||||
|
||||
/* Store `v` as element `i` of a byte-aligned plane. A float dtype rounds as the narrowings above
|
||||
* do; an integer dtype rounds to nearest, ties to even, and saturates to its range, NaN storing 0.
|
||||
* Sub-byte dtypes are stored with rad_store_code; any other dtype is left unwritten. */
|
||||
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;
|
||||
@@ -502,12 +509,26 @@ static inline void rad_store_f32(void* base, uint32_t dtype, int64_t i, float v)
|
||||
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_I8: ((int8_t*)base)[i] = (int8_t)rad_round_even_sat(v, -128.0, 127.0); break;
|
||||
case RAD_U8: ((uint8_t*)base)[i] = (uint8_t)rad_round_even_sat(v, 0.0, 255.0); break;
|
||||
case RAD_U16:
|
||||
((uint16_t*)base)[i] = (uint16_t)rad_round_even_sat(v, 0.0, 65535.0);
|
||||
break;
|
||||
case RAD_I16:
|
||||
((int16_t*)base)[i] = (int16_t)rad_round_even_sat(v, -32768.0, 32767.0);
|
||||
break;
|
||||
case RAD_I32:
|
||||
((int32_t*)base)[i] = (int32_t)rad_round_even_sat(v, -2147483648.0, 2147483647.0);
|
||||
break;
|
||||
case RAD_U32:
|
||||
((uint32_t*)base)[i] = (uint32_t)rad_round_even_sat(v, 0.0, 4294967295.0);
|
||||
break;
|
||||
case RAD_I64: {
|
||||
/* 2^63 is the first float past the range, so it is compared, not clamped to. */
|
||||
const double r = rad_round_even_sat(v, -9223372036854775808.0, 9223372036854775808.0);
|
||||
((int64_t*)base)[i] = r >= 9223372036854775808.0 ? INT64_MAX : (int64_t)r;
|
||||
break;
|
||||
}
|
||||
case RAD_BOOL: ((uint8_t*)base)[i] = v != 0.0f ? 1u : 0u; break;
|
||||
default: break;
|
||||
}
|
||||
|
||||
+33
-36
@@ -1,23 +1,22 @@
|
||||
/* 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).
|
||||
* 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.
|
||||
* $RADIANCE_HOME/quantizers, and the only place a weight's numbers are chosen: a kernel only
|
||||
* rearranges the planes it is given (rad_abi.h, RadRelayoutFn).
|
||||
*
|
||||
* rad-convert drives quantisers through a RECIPE -- ordered rules from a logical weight name to a
|
||||
* 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.
|
||||
* encoding it would write (`encoding`), lets the architecture plugin declare against that, 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.
|
||||
* Input: the weight's logical name, shape and movement group, and the column importances when the
|
||||
* converter has an imatrix. Other calibration data (a GPTQ Hessian, AutoRound's activations) is an
|
||||
* option the quantiser reads itself (`calib=DIR`); its format is the quantiser's business.
|
||||
*
|
||||
* 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.
|
||||
* Output: the canonical planes only, so every kernel library that accepts the encoding and the
|
||||
* core's own decoder can read it. That is how rad-convert measures the error without knowing the
|
||||
* method.
|
||||
*
|
||||
* Pure C, like the rest of abi/.
|
||||
*/
|
||||
@@ -37,12 +36,12 @@ typedef struct RadQuantWeight {
|
||||
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. */
|
||||
/* The movement group; -1 for none. Also -1 when `encoding` is asked at declare, before the
|
||||
* group exists, so an encoding may depend on the name and shape but not on these; rad-convert
|
||||
* refuses a quantiser whose answer changes 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. */
|
||||
/* The imatrix's column importances for this weight (the second moment of its input, one per
|
||||
* column), or null when the converter has none. Per expert where the imatrix has that form. */
|
||||
const float* importance;
|
||||
} RadQuantWeight;
|
||||
|
||||
@@ -57,22 +56,22 @@ typedef struct RadQuantOption {
|
||||
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. */
|
||||
/* 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 a recipe error reported 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. */
|
||||
* on a multiple of it. 0 means the whole weight in one call, needed for any cross-row decision (a
|
||||
* derived per-tensor scale, a learned rotation, a shared Hessian). 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.
|
||||
* planes. `planes[i]` points at the element row of plane i that covers logical row `row0` (row
|
||||
* row0 / br for a TILED plane of block rows br; the plane's start for a whole-extent or TABLE
|
||||
* plane), 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);
|
||||
@@ -81,12 +80,11 @@ typedef int (*RadQuantizeFn)(const RadParam* o, int n_o, const RadQuantWeight* w
|
||||
* 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
|
||||
* The oracle, rad-kbench and rad-convert's error measurement all read a quantiser's own scheme
|
||||
* 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. */
|
||||
* first answer that is not RAD_E_UNSUPPORTED, so a decoder must return RAD_E_UNSUPPORTED for an
|
||||
* encoding it did not write. `w` names the weight where the caller knows it; a decoder must need
|
||||
* nothing beyond 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);
|
||||
@@ -102,10 +100,9 @@ typedef struct RadQuantizerInfo {
|
||||
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. */
|
||||
/* Every quantiser plugin exports these, beside rad_plugin_abi_version and rad_plugin_info (kind
|
||||
* RAD_PLUGIN_QUANT). Two plugins naming the same quantiser are refused at load, both named, since
|
||||
* a recipe naming it would otherwise give different numbers depending on load order. */
|
||||
int rad_quant_count(void);
|
||||
const RadQuantizerInfo* rad_quant_at(int i);
|
||||
|
||||
|
||||
+183
-214
@@ -1,7 +1,7 @@
|
||||
/* 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.
|
||||
* during declare. There is no capture discipline: the device backend records a pass's dispatch
|
||||
* packets at the queue as they are issued and replays them (core/device/aql.cpp,
|
||||
* core/runtime/ctx.h), so the step function needs no graph-safe form. See spec.md §3.2.
|
||||
*/
|
||||
#ifndef RAD_RUNTIME_H
|
||||
#define RAD_RUNTIME_H
|
||||
@@ -15,12 +15,11 @@ extern "C" {
|
||||
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.
|
||||
/* Built once per step by the core and shared by every layer and KV group; rebuilding it per group
|
||||
* and per layer would make a large share of a decode step host work with the device idle (spec §8).
|
||||
*
|
||||
* 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. */
|
||||
* Every pointer is device memory unless the field name says _h. The host mirrors give the
|
||||
* scheduler and the run phase the bounds without a device read. */
|
||||
enum { RAD_PHASE_PREFILL = 0, RAD_PHASE_DECODE = 1, RAD_PHASE_MIXED = 2 };
|
||||
|
||||
typedef struct RadKVGroupBatch {
|
||||
@@ -30,11 +29,10 @@ typedef struct RadKVGroupBatch {
|
||||
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. */
|
||||
/* State slots per sequence: 1 unless the group's kernel asked for scratch beside the state.
|
||||
* A linear kernel serving speculation cannot commit the state until acceptance is known, so it
|
||||
* keeps the committed state in column 0 and replay scratch in the later columns. The engine
|
||||
* zeroes all of them at admission and otherwise does not look inside. Zero means 1. */
|
||||
int64_t state_index_pitch;
|
||||
int64_t block_size;
|
||||
int64_t max_blocks;
|
||||
@@ -52,21 +50,20 @@ typedef struct RadBatch {
|
||||
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].
|
||||
/* The 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").
|
||||
* A prefill chunk computes hidden states for every token, but the sampler wants only each
|
||||
* sequence's last. The plugin issues gather_rows over these and runs the lm_head only on the
|
||||
* result (docs/OPS.md, "Vocabulary edges"); over all n_tok rows at max_tok 8192 and a 248K
|
||||
* vocab the logits buffer would be 8 GiB instead of 63 MiB.
|
||||
*
|
||||
* 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. */
|
||||
* n_out is 0 for a chunk that finishes no sequence (the middle of a long prefill): no logits
|
||||
* are produced and the lm_head is not run. */
|
||||
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 */
|
||||
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;
|
||||
|
||||
@@ -75,28 +72,27 @@ typedef struct RadBatch {
|
||||
|
||||
/* 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* 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:
|
||||
/* The draft pass. 0 is an ordinary step that runs the trunk; non-zero runs only the draft
|
||||
* head, and the sign gives the kind:
|
||||
*
|
||||
* 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.
|
||||
* r < 0 a history pass: one row per token, gathered from the trunk step's rows
|
||||
* (out_ids). The head attends to its own K and V, which nothing else writes (a
|
||||
* prefill fills only the trunk's layers); this fills them for the positions the
|
||||
* step just committed. When `n_draft_out` is non-zero the pass is also draft round
|
||||
* 1 and ends in the lm_head over the rows `draft_out_ids` names.
|
||||
* r > 1 draft round r, one-based. One row per sequence, reading the head's output from
|
||||
* the round before and ending in the lm_head; it samples 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. */
|
||||
* On any draft pass `token_ids` is already shifted (the head at index i reads the token at
|
||||
* i + 1) by the batch builder, so no kernel or plugin applies the shift. Every other field
|
||||
* keeps its usual meaning. */
|
||||
int32_t draft_pass;
|
||||
|
||||
/* Linear-state checkpointing (spec §7.3): tokens at which the scheduler wants a checkpoint
|
||||
@@ -105,125 +101,112 @@ typedef struct RadBatch {
|
||||
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.
|
||||
/* 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.
|
||||
* Sequences [0, n_seq_decode) carry decode rows and the rest prefill chunks; the scheduler
|
||||
* orders every step that way. A block that treats the two differently issues over each as a
|
||||
* contiguous sub-range of the per-sequence arrays (`cu_seqlens + n_seq_decode`,
|
||||
* `state_index + n_seq_decode * pitch`, ...) with the token operands left at their base. This
|
||||
* works because cu_seqlens holds absolute row offsets, so a kernel reading cu[n] and cu[n+1]
|
||||
* finds the right rows in either sub-array.
|
||||
*
|
||||
* 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.
|
||||
* Without the split a mixed step is prefill-shaped for every sequence, so its decode rows
|
||||
* cannot verify a draft and produce one token instead of several; under interactive load many
|
||||
* steps are mixed.
|
||||
*
|
||||
* 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. */
|
||||
* n_seq_decode == n_seq on a pure decode step and 0 on a pure prefill, so a block that does
|
||||
* not care can ignore these 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. */
|
||||
/* The decode rows are tokens [0, n_tok_decode) and the prefill chunks the rest. A per-token
|
||||
* op cannot derive this, since each decode row is 1 + its own draft count. */
|
||||
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.
|
||||
/* The longest query in each half. max_q_len over a mixed step is the prefill chunk's, and
|
||||
* banding the decode half with it would give eight rows a thousand-row GEMM's band.
|
||||
*
|
||||
* 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. */
|
||||
* Only the decode value is currently read (by the GDN blocks). The prefill value is for a
|
||||
* block whose prefill path bands on a per-sequence query length; the GDN prefill ops band on
|
||||
* the step's total tokens, taken from their operands. */
|
||||
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.
|
||||
/* Draft round 1, carried by the history pass: [n_draft_out] device, indices into this pass's
|
||||
* rows, one per drafting sequence, 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.
|
||||
* Round 1 continues from the last committed position with the token the trunk chose after it.
|
||||
* The history pass already has a row with exactly those inputs: it covers every position the
|
||||
* verify step could have committed and repeats the last committed one past it
|
||||
* (core/sched/advance.h, ADV_HIST). So each drafting sequence's last history row is its
|
||||
* round-1 row, saving a separate pass; the pass ends in the lm_head over those rows, and the
|
||||
* head's wide state there 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).
|
||||
/* The prompt after this step: `n_ahead` more tokens of the last sequence, stored in
|
||||
* `token_ids` right after its n_tok (the next prefill chunk); 0 on every other step (decode,
|
||||
* 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`). */
|
||||
* Nothing is computed on them. They let an op that fetches per-token data from a slow tier
|
||||
* start the next step's reads during this one: the PLE gather reads its rows from the
|
||||
* container file, tens of thousands of random reads per chunk (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.
|
||||
/* The rotary position of every token, which differs from `positions`. `positions` is a
|
||||
* token's index in its sequence (the KV slot, the QSA block and other bookkeeping count in
|
||||
* it). 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 others, and 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.
|
||||
* [3, n_tok] device, component-major: plane c is rope_pos + c * n_tok. Plane 0 alone is a
|
||||
* valid one-component position for every token whose components agree, i.e. every token when
|
||||
* `rope_mixed` is 0, so a kernel reading one position per token can use plane 0 then.
|
||||
*
|
||||
* Null when the program declares no encoder: nothing can move a rotary position away from
|
||||
* the index then, and `positions` is the rotary position. */
|
||||
* Null when the program declares no encoder; `positions` is then 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. */
|
||||
/* Host-side: non-zero when some token on this pass has differing components (an image or
|
||||
* video span is present); a block with a one-component fast path must take the
|
||||
* multi-component path. */
|
||||
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]`.
|
||||
/* Rows that take an encoder's output in place of a token embedding: row i of `mm_embd`
|
||||
* replaces the embedding of this pass's token `mm_rows[i]`. The placeholder ids a media span
|
||||
* holds in `token_ids` are still real ids (a hashed n-gram embedding reads them).
|
||||
*
|
||||
* 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.
|
||||
* Rank 0 holds the rows and every other rank zeros, matching a vocabulary-sharded embedding
|
||||
* lookup where non-owning ranks contribute zero to the following reduction. So a plugin
|
||||
* overwrites its lookup output with these rows before that reduction, whether it is an
|
||||
* all-reduce or folded into the first layer's norm.
|
||||
*
|
||||
* 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. */
|
||||
* On a pass that shifts its tokens (a draft history pass) the rows are shifted with them. 0
|
||||
* rows on every pass without media. */
|
||||
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 a declared encoder (rad_declare_encoder) and nothing
|
||||
* else: no token rows, no KV, no logits. It is that encoder's `modalities` -- RAD_MM_AUDIO
|
||||
* for an audio encoder, the image/video mask for the other -- so a program that declared two
|
||||
* knows which to run. 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.
|
||||
/* The encoder pass. Non-zero `enc` runs a declared encoder (rad_declare_encoder) and nothing
|
||||
* else: no token rows, no KV, no logits. Its value is that encoder's `modalities`
|
||||
* (RAD_MM_AUDIO, or the image/video mask), selecting between two declared encoders. Input is a
|
||||
* list of patches already resized, normalised and cut by the processor; output is the
|
||||
* encoder's declared `out` buffer, one row per `merge` patches, read back after the pass.
|
||||
*
|
||||
* An AUDIO pass's patches are feature frames and its coordinates are 1-D: plane 0 the frame's
|
||||
* index in its clip, plane 1 whether the frame is real (1) or the zero padding that makes the
|
||||
* clip whole output rows (0), plane 2 the clip's real frames and plane 3 its staged ones.
|
||||
* An audio pass's patches are feature frames with 1-D coordinates: plane 0 the frame's index
|
||||
* in its clip, plane 1 whether it takes part in the convolution (1) or is staging the encoder
|
||||
* reads as zero (0), plane 2 the clip's real frames and plane 3 its staged ones. The zero
|
||||
* frames pad a clip staged whole to whole output rows, or, for a clip staged a second at a
|
||||
* time (Qwen3-ASR), align each second to whole rows.
|
||||
*
|
||||
* 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. */
|
||||
* Patches are grouped into segments (one per image, one per temporal group of a video), and
|
||||
* attention runs within a segment. `enc_coord` gives each patch's place in its segment, which
|
||||
* is all a learned position table or a 2-D rotary embedding needs. */
|
||||
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
|
||||
/* [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;
|
||||
@@ -232,15 +215,15 @@ typedef struct RadBatch {
|
||||
|
||||
/* ================================================ image generation */
|
||||
|
||||
/* A GENERATOR PASS (rad_declare_generator): RAD_GEN_PASS_*, and `gen_b` what it carries. 0 on
|
||||
/* A generator pass (rad_declare_generator): RAD_GEN_PASS_*, with `gen_b` its payload. 0 on
|
||||
* every step of a program that declared no generator. */
|
||||
int32_t gen;
|
||||
const struct RadGenBatch* gen_b;
|
||||
} RadBatch;
|
||||
|
||||
/* WHAT A GENERATOR PASS CARRIES beside the step batch's own fields, which keep their meanings:
|
||||
/* What a generator pass carries beside the step batch's own fields, which keep their meanings:
|
||||
*
|
||||
* COND ONE sequence. `token_ids`, `positions` and `rope_pos` are its conditioning prompt, the
|
||||
* COND one sequence. `token_ids`, `positions` and `rope_pos` are its conditioning prompt, the
|
||||
* encoder's input (`enc_*`) is the prompt's reference pictures and `mm_rows` the prompt
|
||||
* rows the encoder's output rows replace, as on any media step. What is here lays out
|
||||
* the generator's sequence over those rows and writes it into the KV group.
|
||||
@@ -255,12 +238,12 @@ typedef struct RadGenBatch {
|
||||
/* Where each row comes from: >= 0 the prompt row of that index (the conditioning network's
|
||||
* output there), < 0 the reference latent row -(1 + src). [rows] */
|
||||
const int32_t* src;
|
||||
/* Rotary positions, three components a row. On a COND pass they are laid out SEGMENT BY
|
||||
* SEGMENT: segment s's [3, length] component-major block starts at element 3 * seg_h[s], so a
|
||||
/* Rotary positions, three components a row. On a COND pass they are laid out segment by
|
||||
* segment: segment s's [3, length] component-major block starts at element 3 * seg_h[s], so a
|
||||
* segment's positions are one dense operand. On a DENOISE pass, [3, n_tok] component-major,
|
||||
* the latent rows'. */
|
||||
const int32_t* rope;
|
||||
/* The sequence in SEGMENTS: rows [seg_h[s], seg_h[s+1]), each a picture (`seg_bidi_h` 1, its
|
||||
/* The sequence in segments: rows [seg_h[s], seg_h[s+1]), each a picture (`seg_bidi_h` 1, its
|
||||
* rows attend to each other both ways) or a run of text (0, causal). A segment is never split
|
||||
* and attends to every segment before it. `seg` is the same offsets on the device; `seg_cu`
|
||||
* is [n_seg, 2], segment s's own cu_seqlens {0, length}, and `seg_start` [n_seg] its first
|
||||
@@ -273,10 +256,10 @@ typedef struct RadGenBatch {
|
||||
const int32_t* seg_start;
|
||||
/* [rows] the KV slot each row is stored at. */
|
||||
const int32_t* slot_mapping;
|
||||
/* PIXELS the decoder's encoder takes: `n_px` blocks of `px` [*, pixel_channels] bf16 in
|
||||
* [-1, 1], block b at pixel px_h[3b], px_h[3b+1] high and px_h[3b+2] wide. The reference
|
||||
* pictures, in prompt order, and -- with `inpaint` -- a last block that is no reference but
|
||||
* the picture being repainted, at the size being made: its latents go to the lanes below. */
|
||||
/* Pixels for the decoder's encoder: `n_px` blocks of `px` [*, pixel_channels] bf16 in
|
||||
* [-1, 1], block b at pixel px_h[3b], px_h[3b+1] high and px_h[3b+2] wide. These are the
|
||||
* reference pictures in prompt order and, with `inpaint`, a last block holding the picture
|
||||
* being repainted at the output size, whose latents go to the lanes below. */
|
||||
int64_t n_px;
|
||||
const void* px;
|
||||
const int32_t* px_h;
|
||||
@@ -294,8 +277,8 @@ typedef struct RadGenBatch {
|
||||
const float* sigma; /* where the entry's latent is */
|
||||
const float* sigma_next; /* where this step takes it */
|
||||
const float* cfg; /* guidance: v = neg + cfg * (pos - neg); 1 without a pair */
|
||||
/* The entry holding this image's NEGATIVE conditioning, or -1 for none; -2 marks an entry
|
||||
* that IS one, whose rows serve another entry's step and whose lane it does not move. */
|
||||
/* The entry holding this image's negative conditioning, or -1 for none; -2 marks an entry
|
||||
* that is one, whose rows serve another entry's step and which does not move its lane. */
|
||||
const int32_t* pair;
|
||||
const int32_t* lane; /* the plugin's lane the image's latent lives in */
|
||||
const int32_t* lane_dh; /* ... the same, host */
|
||||
@@ -320,35 +303,31 @@ enum {
|
||||
|
||||
/* ================================================================== 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. */
|
||||
* as an operand, and RadKVGroupBatch carries the slot mapping and block table but not the pool
|
||||
* base, which belongs to the block manager. handle is the rad_kvgroup and offset is the layer,
|
||||
* since a group's pool holds one cache per bound layer. */
|
||||
/* RAD_OPK_WTAB names a run of consecutively declared weights. A routed MoE layer has no single
|
||||
* base to stride from: its experts are separate movement units (spec §4.2), and after placement
|
||||
* one may be in VRAM, the next streamed over the link and a third on disk. The core resolves each
|
||||
* handle like any weight (residency table, mover event, use note) and hands the kernel a device
|
||||
* array of pointers, one per expert, in declaration order. See RAD_WTAB below for the RadTensor
|
||||
* shape rule. */
|
||||
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 dtype; /* RAD_OPK_RAW only: what the pointer points at (buffers and weights
|
||||
* carry their dtype in the declaration). RAD_DT_INVALID means the
|
||||
* kernel knows it from the schema position, which a specialised
|
||||
* kernel does and libref does not. */
|
||||
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. */
|
||||
int64_t cols; /* 0 = the declared extent; >0 = a column slice of that width, with the
|
||||
* declared width kept as the stride. Lets q, k and v be views of one
|
||||
* fused qkv buffer instead of three buffers and a copy. */
|
||||
} RadOperand;
|
||||
|
||||
#define RAD_B(h) ((RadOperand){ RAD_OPK_BUF, RAD_DT_INVALID, (h), 0, 0, 0, 0 })
|
||||
@@ -358,28 +337,24 @@ typedef struct RadOperand {
|
||||
* 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.
|
||||
/* A weight table: the `n` weights declared at handles h, h+1, ... h+n-1, as a declaration loop
|
||||
* over experts produces (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 kernel receives `RadTensor::data` as a device array of `n` `void*`, entry e pointing at
|
||||
* expert e's first byte. `shape[0]` is n and `stride[0]` is 0; the zero leading stride marks an
|
||||
* axis that must be indexed through the table, not by arithmetic. `dtype` and `shape[1..]` /
|
||||
* `stride[1..]` are one entry's; every weight in the run must agree on them, or the core refuses
|
||||
* the issue by name.
|
||||
*
|
||||
* 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. */
|
||||
* The table is rebuilt only when a pointer changes, so a resident model pays one comparison per
|
||||
* expert per issue and no copy. */
|
||||
#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. */
|
||||
/* A raw pointer to a dense 2-D array, [rows, cols], packed. On a raw operand `cols` is the second
|
||||
* extent, not a column slice (there is no declared width to slice). This is how a two-dimensional
|
||||
* batch field such as the block table, [n_seq, max_blocks], keeps its width. */
|
||||
#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 })
|
||||
@@ -390,31 +365,29 @@ typedef struct 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.
|
||||
* implementation for 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.
|
||||
* `n` is the value of the op's ranged parameter (at most one per op, so this is a single integer
|
||||
* on the hot path). RAD_N_BATCH means the batch's token count, which 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). */
|
||||
* Ops take handles, not pointers, so a weight's location is not fixed at declare; placement
|
||||
* depends on this (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.
|
||||
/* The second lane, for overlapping a collective (or an arm no shard divides) with compute.
|
||||
* `rad_lane` selects the stream later issues launch on (0 or 1); `rad_lane_join(c, from, to)`
|
||||
* orders `to` behind everything already issued on `from` without blocking the host. The runtime
|
||||
* joins lane 1 into lane 0 at the end of every step, so a missing join costs speed, 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. */
|
||||
* Three rules (reasons at Ctx::lane1_ in core): every collective must use the same lane, since
|
||||
* the all-reduce numbers its scratch slots per launch and the ranks must agree; a kernel with a
|
||||
* device-wide arrival counter must key it on the stream (libr4d's split-K GEMM does), or it may
|
||||
* not run here; and every buffer the second lane touches must be named to rad_buf_concurrent,
|
||||
* because the planner packs transients from one linear order. */
|
||||
int rad_lane(RadCtx* c, int lane);
|
||||
int rad_lane_join(RadCtx* c, int from, int to);
|
||||
|
||||
@@ -422,12 +395,9 @@ int rad_lane_join(RadCtx* c, int from, int to);
|
||||
#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. */
|
||||
/* Fail the step with a reason. An architecture block's step() returns void, so this is how it
|
||||
* refuses a batch shape it does not serve; the engine stops with `what` in the message. Returns
|
||||
* the status it set, so a helper can `return rad_step_fail(...)`. */
|
||||
int rad_step_fail(RadCtx* c, const char* what);
|
||||
|
||||
/* ================================================================== run-phase queries */
|
||||
@@ -437,9 +407,9 @@ 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. */
|
||||
* 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). These are device-side buffers the plugin
|
||||
* issues its expert ops against, not host-visible expert ids. */
|
||||
typedef struct RadRouting {
|
||||
const int32_t* expert_ids; /* [n_tok, top_k] device */
|
||||
const float* expert_w; /* [n_tok, top_k] device */
|
||||
@@ -455,22 +425,22 @@ typedef struct RadRouting {
|
||||
* 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. */
|
||||
/* A core-owned device row of at least `n_expert` int32 where a layer's expert counts can be
|
||||
* written in place; the core copies it to the host once at the end of the pass. A router that
|
||||
* writes here and reports this pointer as `expert_count` hands the counts over for free; any other
|
||||
* pointer costs one copy dispatch per 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);
|
||||
|
||||
/* THE NEXT-LAYER EXPERT PREFETCH, at decode. A routed layer names the next routed layer at its router
|
||||
* input; the core applies that layer's router to this layer's input rows, takes the experts the next
|
||||
* layer is likeliest to route that sit in the pinned host pool, and copies them onto the card while
|
||||
* the rest of this layer runs. Just before the next layer's routed GEMMs it points their weight-table
|
||||
* entries at the copies, where the copies have landed and the entries still name the pool slots they
|
||||
* were made from. It changes no result: a copy holds the bytes of its slot. It is on where the
|
||||
* placement keeps experts in a pinned pool and the device backend can spare a DMA engine for it, and
|
||||
* a pass of more than 16 rows makes no prediction; the three calls are no-ops otherwise.
|
||||
/* Next-layer expert prefetch, at decode. At its router input a routed layer names the next routed
|
||||
* layer; the core applies that layer's router to this layer's input rows, picks the experts it is
|
||||
* likeliest to route that sit in the pinned host pool, and copies them to the card while the rest
|
||||
* of this layer runs. Just before the next layer's routed GEMMs it points their weight-table
|
||||
* entries at the copies that have landed, where the entries still name the pool slots copied from.
|
||||
* Results are unchanged: a copy holds its slot's bytes. Active only when placement keeps experts
|
||||
* in a pinned pool and the device backend can spare a DMA engine; a pass of more than 16 rows
|
||||
* makes no prediction. The three calls are no-ops otherwise.
|
||||
*
|
||||
* `parts` names, for each of the next layer's experts, the weights its unit is made of (at most four,
|
||||
* e.g. the gate-up matrix and its scales and the down matrix and its scales), as the routed GEMMs
|
||||
@@ -493,15 +463,14 @@ typedef struct RadPrefetchNext {
|
||||
* stream -- the block must not overwrite them before this layer's routed GEMMs. */
|
||||
int rad_expert_prefetch(RadCtx* c, const RadPrefetchNext* next, rad_buf h, int64_t r0, int64_t rows,
|
||||
int64_t n_embd);
|
||||
/* After this layer's routed down GEMM: the copies cross the link from here, under the next layer's
|
||||
* attention rather than under this layer's own streamed experts. */
|
||||
/* After this layer's routed down GEMM: the copies cross the link from here, overlapping the next
|
||||
* layer's attention rather than this layer's own streamed experts. */
|
||||
int rad_expert_prefetch_mark(RadCtx* c);
|
||||
/* Ahead of `layer`'s routed GEMMs, on every routed layer of every pass. */
|
||||
int rad_expert_prefetch_step(RadCtx* c, int layer);
|
||||
|
||||
/* 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. */
|
||||
/* A weight's pointer, for the rare plugin-private kernel invoked outside the op vocabulary. Waits
|
||||
* on the mover. The weight may move afterwards, so the pointer is valid only within one issue. */
|
||||
void* rad_weight_ptr(RadCtx* c, rad_weight w);
|
||||
void* rad_buf_ptr(RadCtx* c, rad_buf b);
|
||||
|
||||
|
||||
+31
-38
@@ -1,22 +1,17 @@
|
||||
/* rad_sample.h -- the per-sequence sampling row, and why it is part of the ABI.
|
||||
/* rad_sample.h -- the per-sequence sampling row.
|
||||
*
|
||||
* 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.
|
||||
* Every sampler op takes `params` as an operand: an array of the struct below, one row per sampled
|
||||
* position, uploaded once per step. Its layout is therefore a wire format between the core and
|
||||
* every kernel plugin, stated here because a plugin cannot include a core header.
|
||||
*
|
||||
* ============================== 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.
|
||||
* `rep`, `freq`, `pres`, `k` and `p` read like op parameters, and docs/OPS.md names them that way,
|
||||
* but parameters are geometry: the selector matches constraints against them and they are frozen
|
||||
* at declare (spec §2.2). Two requests in one batch with different top_p would need two
|
||||
* resolutions of the same op. So the values are data and travel as an operand. `seed` and
|
||||
* `offset`, which docs/OPS.md gives `sample_pick` as two more operands, are row fields for the
|
||||
* same reason.
|
||||
*
|
||||
* core/sample/sampler.h carries the full schema table this implies; libref implements it.
|
||||
*/
|
||||
@@ -29,16 +24,15 @@
|
||||
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.
|
||||
/* Flags, so a kernel can skip a stage for a sequence with one integer test instead of reading
|
||||
* five floats to find they are the identity.
|
||||
*
|
||||
* 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. */
|
||||
* RAD_SP_GREEDY owns the row's token. `sample_argmax` writes it, and every later candidate stage
|
||||
* (`sample_topk`, the narrowing stages, `sample_merge_topk`, `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 must go through the candidate chain (a split vocabulary, where the
|
||||
* argmax 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 */
|
||||
@@ -51,14 +45,14 @@ enum {
|
||||
/* 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
|
||||
* 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`.
|
||||
* `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 the last n tokens (llama.cpp's
|
||||
* meaning for `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
|
||||
@@ -104,15 +98,14 @@ static_assert(offsetof(RadSampleParams, dry_rep_limit) + sizeof(int32_t) == size
|
||||
"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.
|
||||
/* The random draw is specified here, not left to a library, because a host reference, a device
|
||||
* kernel and a rerun must produce the same stream (spec §13). splitmix64 over
|
||||
* (seed * golden ratio + pos), taking 24 bits as a float in [0, 1): exactly f32's mantissa, so no
|
||||
* double is needed anywhere.
|
||||
*
|
||||
* 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
|
||||
* Independent draws at one position use independent streams: the request's seed XORed with a key,
|
||||
* `rad_sample_uniform01(seed ^ key, pos)`. The pick uses the seed itself. XTC's firing coin has its
|
||||
* own key so the pick is not correlated with it; 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
|
||||
|
||||
+49
-89
@@ -15,9 +15,8 @@ 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. */
|
||||
/* Zero is success. Negative is failure, and the value names its class so a caller can report it.
|
||||
* A kernel returning negative at issue is a selection bug, not a runtime condition (spec.md §17). */
|
||||
enum {
|
||||
RAD_OK = 0,
|
||||
RAD_E_SHAPE = -1, /* geometry this instantiation does not serve */
|
||||
@@ -42,24 +41,19 @@ enum {
|
||||
RAD_E_CANCELLED = -20
|
||||
};
|
||||
|
||||
/* ------------------------------------------------------------------ the helpers, INLINE
|
||||
/* ------------------------------------------------------------------ the helpers, inline
|
||||
*
|
||||
* WHY EVERY FREE FUNCTION IN THIS HEADER IS A DEFINITION AND NOT A DECLARATION.
|
||||
* Every free function in this header is a `static inline` definition, not a declaration. A plugin
|
||||
* links these headers and nothing of the engine's, so a function defined in the core would
|
||||
* resolve at dlopen only if the host happened to export it (ENABLE_EXPORTS/-rdynamic); otherwise
|
||||
* RTLD_NOW fails the plugin.
|
||||
*
|
||||
* 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.
|
||||
* The helpers are therefore part of the ABI by value: a plugin carries the dtype table it was
|
||||
* built against, and RAD_ABI_VERSION enforces the match (the loader refuses a mismatch by name,
|
||||
* with both versions printed).
|
||||
*
|
||||
* 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. */
|
||||
* Everything here is pure, small and total: nothing allocates or holds state, and nothing may
|
||||
* start to. */
|
||||
static inline const char* rad_strerror(int status) {
|
||||
switch (status) {
|
||||
case RAD_OK: return "ok";
|
||||
@@ -88,14 +82,12 @@ static inline const char* rad_strerror(int status) {
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ 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 core understands dtypes (spec §19.6): libref computes on tensors, rad-kbench compares them
|
||||
* elementwise, the buffer planner sizes buffers from shapes, and rad-convert writes bytes.
|
||||
*
|
||||
* 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. */
|
||||
* the plugin's own layout hook and never interpreted by the core. A format invented for one kernel
|
||||
* lives there (spec §19.6). */
|
||||
enum {
|
||||
RAD_DT_INVALID = 0,
|
||||
|
||||
@@ -115,11 +107,10 @@ enum {
|
||||
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. */
|
||||
/* Sub-byte codes and the exponent scale. Element counts are logical elements; byte sizes
|
||||
* come from rad_dtype_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 give only its width and signedness. */
|
||||
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 */
|
||||
@@ -145,10 +136,10 @@ enum {
|
||||
|
||||
RAD_DT_PLUGIN_BASE = 256
|
||||
};
|
||||
/* THE DTYPE TABLE, and it lives in the header for the reason the block above rad_strerror gives.
|
||||
/* The dtype table, in the header for the reason given above rad_strerror.
|
||||
*
|
||||
* 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. */
|
||||
* 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[] = {
|
||||
@@ -202,8 +193,8 @@ static inline const char* rad_dtype_name(uint32_t dtype) {
|
||||
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. */
|
||||
/* RAD_DT_INVALID if unknown. The alternate spellings are those found in checkpoints (safetensors)
|
||||
* and kernel dtype strings. */
|
||||
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)
|
||||
@@ -228,8 +219,8 @@ static inline int64_t rad_dtype_bytes(uint32_t dtype, int64_t n) {
|
||||
/* ------------------------------------------------------------------ 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. */
|
||||
/* Strides are in elements, not bytes, since a byte stride would be fractional for sub-byte
|
||||
* dtypes. */
|
||||
typedef struct RadTensor {
|
||||
void* data;
|
||||
uint32_t dtype;
|
||||
@@ -245,9 +236,8 @@ static inline int64_t rad_tensor_numel(const RadTensor* t) {
|
||||
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. */
|
||||
/* A rank-0 tensor and a tensor whose non-unit axes are dense are both contiguous. A shape-1 axis
|
||||
* may carry any stride and still describe the same bytes, so its stride is not checked. */
|
||||
static inline int rad_tensor_is_contiguous(const RadTensor* t) {
|
||||
if (!t || t->rank == 0) return 1;
|
||||
int64_t acc = 1;
|
||||
@@ -267,8 +257,8 @@ static inline void rad_tensor_pack(RadTensor* t) {
|
||||
|
||||
/* ------------------------------------------------------------------ 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. */
|
||||
* A parameter may be a fixed value or a range, which 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 {
|
||||
@@ -277,11 +267,10 @@ typedef struct RadParam {
|
||||
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. */
|
||||
double dval; /* RAD_P_F64: eps, rope theta, an attention scale. A double rather
|
||||
* than a "%.9g" string, which would be exact for an IEEE single but
|
||||
* unreadable in a graph dump. Constraints never match on a float:
|
||||
* a tolerance is not a predicate. */
|
||||
} RadParam;
|
||||
|
||||
/* Builders. RAD_PARAMS below wraps these into a positional list. */
|
||||
@@ -291,9 +280,9 @@ typedef struct RadParam {
|
||||
#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. */
|
||||
/* 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 the
|
||||
* entry point 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 {
|
||||
@@ -303,13 +292,11 @@ typedef struct RadConstraint {
|
||||
const char* sval; /* IN: space-separated set of admissible strings */
|
||||
} RadConstraint;
|
||||
|
||||
/* A CONSTRAINT ON THE MACHINE rather than on the geometry. A key that starts "device." is matched
|
||||
* against what the engine measured about the ranks' devices at launch, not against the op's
|
||||
* parameters: a capability such as reaching another card's memory belongs to the machine, and
|
||||
* carrying it as a parameter would have every architecture plugin declare it on every op and
|
||||
* every schema grow a field for it. Such a key is in no geometry, so it changes no tuning key
|
||||
* and no selection fold. Where nothing measured it -- a tool selecting without an engine -- it is
|
||||
* absent, and a constraint on an absent key does not hold.
|
||||
/* A constraint on the machine rather than the geometry. A key starting "device." is matched
|
||||
* against what the engine measured about the ranks' devices at launch, not against op parameters,
|
||||
* so architecture plugins and schemas need not carry machine capabilities. Such a key is in no
|
||||
* geometry, so it changes no tuning key and no selection fold. Where nothing measured it (a tool
|
||||
* selecting without an engine) it is absent, and a constraint on an absent key does not hold.
|
||||
*
|
||||
* device.p2p 1 when every rank's device can read and write every other rank's memory
|
||||
* directly; 0 when some pair cannot. One rank has no peer to reach, and is 1. */
|
||||
@@ -329,47 +316,20 @@ typedef struct RadConstraint {
|
||||
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. */
|
||||
/* A KV group handle. Here with the other handles because RadBufDecl in rad_builder.h carries
|
||||
* one. */
|
||||
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. */
|
||||
/* Opaque: the core never dereferences one. On a card it is the engine's own queue, not a
|
||||
* hipStream_t. A kernel plugin may use it only with hipLaunchKernel (and so <<<>>>),
|
||||
* hipMemcpyAsync, hipMemcpy2DAsync and hipMemsetAsync, which the engine implements itself, and
|
||||
* must pass it to nothing else in HIP (docs/PLUGIN.md, "What a launch may do"). Under the host
|
||||
* backend the host kernels ignore it. */
|
||||
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
|
||||
|
||||
+47
-4
@@ -1,10 +1,16 @@
|
||||
#ifndef RAD_YARN_H
|
||||
#define RAD_YARN_H
|
||||
|
||||
/* Static YaRN coefficients. The architecture resolves the correction bounds using
|
||||
* the ORIGINAL training length, never the deployment/table length. Kernels share
|
||||
* the resolved coefficients so direct and table-backed RoPE cannot disagree. */
|
||||
/* Static YaRN coefficients. The architecture resolves the correction bounds from the original
|
||||
* training length, never the deployment or table length. Kernels share the resolved coefficients
|
||||
* so direct and table-backed RoPE cannot disagree.
|
||||
*
|
||||
* C++ gets RadYarn with a member frequency() (callable from HIP device code) and default member
|
||||
* values; C gets the same four-float struct and rad_yarn_frequency(). The two definitions must
|
||||
* compute the same frequencies; tests/abi_layout_test.cpp compares them. */
|
||||
#include "rad_plugin.h"
|
||||
|
||||
#ifdef __cplusplus
|
||||
#include <cmath>
|
||||
|
||||
#if defined(__HIPCC__)
|
||||
@@ -14,7 +20,7 @@
|
||||
#endif
|
||||
|
||||
struct RadYarn {
|
||||
float factor = 0.0f; /* zero: keep the legacy arithmetic exactly */
|
||||
float factor = 0.0f; /* zero: YaRN off, frequency() returns `inv` unchanged */
|
||||
float low = 0.0f;
|
||||
float high = 0.0f;
|
||||
float magnitude = 1.0f;
|
||||
@@ -46,4 +52,41 @@ inline bool rad_yarn_valid(const RadYarn& y) {
|
||||
}
|
||||
|
||||
#undef RAD_YARN_HD
|
||||
|
||||
#else /* C */
|
||||
#include <math.h>
|
||||
|
||||
typedef struct RadYarn {
|
||||
float factor; /* zero: YaRN off, rad_yarn_frequency() returns `inv` unchanged */
|
||||
float low;
|
||||
float high;
|
||||
float magnitude; /* 1 when off */
|
||||
} RadYarn;
|
||||
|
||||
static inline float rad_yarn_frequency(const RadYarn* y, float inv, int i) {
|
||||
float width, ramp, mask;
|
||||
if (y->factor == 0.0f) return inv;
|
||||
width = y->high == y->low ? 0.001f : y->high - y->low;
|
||||
ramp = fminf(1.0f, fmaxf(0.0f, ((float)i - y->low) / width));
|
||||
mask = 1.0f - ramp;
|
||||
return (inv / y->factor) * (1.0f - mask) + inv * mask;
|
||||
}
|
||||
|
||||
static inline RadYarn rad_yarn_args(const RadArgs* a) {
|
||||
RadYarn y = { 0.0f, 0.0f, 0.0f, 1.0f };
|
||||
y.factor = (float)rad_args_getf_or(a, "yarn_factor", 0.0);
|
||||
if (y.factor == 0.0f) return y;
|
||||
y.low = (float)rad_args_getf_or(a, "yarn_low", 0.0);
|
||||
y.high = (float)rad_args_getf_or(a, "yarn_high", 0.0);
|
||||
y.magnitude = (float)rad_args_getf_or(a, "yarn_magnitude", 1.0);
|
||||
return y;
|
||||
}
|
||||
|
||||
static inline int rad_yarn_valid(const RadYarn* y) {
|
||||
return isfinite(y->factor) && (y->factor == 0.0f ||
|
||||
(y->factor >= 1.0f && isfinite(y->low) && isfinite(y->high) && y->high >= y->low &&
|
||||
isfinite(y->magnitude) && y->magnitude > 0.0f));
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif
|
||||
Reference in new issue
Block a user