radiance 1.7.0

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

No files matched your search

+412 -318
View File
File diff suppressed because it is too large. Load diff
+79 -74
View File
@@ -1,25 +1,24 @@
/* checkpoint.h -- a safetensors or GGUF checkpoint as a source of logical weights.
*
* A checkpoint is read twice in this engine: by rad-convert, which writes a container from it, and
* by the loader, which serves a checkpoint whose encoding is trivial directly (spec §4.3). Both
* need the same three things, and this is the one copy of each:
* Read by rad-convert (to write a container) and by the loader (to serve a checkpoint with
* trivial encodings directly, spec §4.3). Both need:
*
* - the tensors, as one row-major namespace however many shards and drafters they came in;
* - the model's metadata, from config.json (and its siblings) or the GGUF header;
* - a LOGICAL WEIGHT for a declared name: the tensors the architecture plugin's name map
* resolves it to -- concatenations, alternatives and expert slices included -- with the
* encoding they already are when that encoding is trivial, and the rows of it on demand.
* - the tensors, as one row-major namespace across shards and drafters;
* - the metadata, from config.json and its siblings or the GGUF header;
* - the logical weight for a declared name: the tensors the plugin's name map resolves it to
* (concatenations, alternatives, expert slices), with their encoding when trivial, and its rows
* on demand.
*
* Trivial is the set spec §4.3 names: plain f32, f16 and bf16 (GGUF's too), block-scaled FP8,
* where `X.weight_scale_inv` is the scale plane of `X.weight`, and MXFP4 as AMD Quark ships it
* (`X.weight` U8 codes, `X.weight_scale` U8 exponents), which is `fp4_e2m1*e8m0[1x32]` byte for
* byte. Anything else is a weight whose served form needs quantisation work, which a recipe does
* ahead of time -- or, for a published GPTQ-packed release (AutoRound, GPTQ), an IMPORT: the
* shipped integer codes and group scales re-laid as an encoding the kernels read, at convert time.
* Trivial (spec §4.3): plain f32, f16 and bf16 (GGUF's too); FP8 with a block or per-row scale
* plane (`X.weight_scale_inv`, or `X.weight_scale`); and MXFP4 as AMD Quark ships it (`X.weight`
* U8 codes, `X.weight_scale` U8 exponents), byte for byte `fp4_e2m1*e8m0[1x32]`. Anything else
* needs a recipe ahead of time, or for a published release in a form listed under
* Checkpoint::Import an import: the shipped codes and scales re-laid, or decoded for a recipe, at
* convert time.
*
* AN IMPORTED QUANTISATION IS STATED WEIGHT BY WEIGHT. The checkpoint's quantisation descriptor
* (`auto-round`, `gptq`, `quark`) names the tool that made it, not a served form, so no
* architecture plugin claims it; the plugin is chosen as Checkpoint::imports() describes.
* An imported quantisation's descriptor (`auto-round`, `gptq`, `quark`, `compressed-tensors`,
* `paroquant`) names the tool, not a served form, so no plugin claims it; Checkpoint::imports()
* describes how the plugin is chosen.
*/
#pragma once
#include "../rad_internal.h"
@@ -39,9 +38,8 @@ namespace rad {
class Program;
/* ================================================================== tensors */
/* One shape convention from here on: ROW-MAJOR, shape[0] slowest. GGUF stores ne[] fastest-first,
* so it is reversed on the way in. Getting this backwards transposes every matrix in the model
* and produces fluent wrong output, so it is done exactly once, in Checkpoint::open. */
/* Shapes are row-major, shape[0] slowest. GGUF stores ne[] fastest-first, so Checkpoint::open
* reverses it, once; getting it wrong transposes every matrix. */
struct SrcTensor {
std::string name;
uint32_t ggml = 0;
@@ -49,18 +47,18 @@ struct SrcTensor {
std::vector<int64_t> shape; /* row-major */
const void* data = nullptr;
int64_t bytes = 0;
/* GPTQ-PACKED (auto_gptq's layout, which AutoRound's `auto_round:auto_gptq` export shares):
* `data` is the qweight's int32 words [K * bits / 32, N], each packing 32 / bits codes along
* K from the low bits up, stored unsigned with the zero point 2^(bits-1). The tensor this
* describes is the logical [N, K] code matrix, `rad_dtype` RAD_I4 or RAD_I8; `gptq_group` is
* the K columns one row of its scale tensor covers. 0 for any other tensor. */
/* GPTQ-packed (auto_gptq's layout, shared by AutoRound's `auto_round:auto_gptq` export):
* `data` is the qweight's int32 words [K * bits / 32, N], each packing 32 / bits codes along K
* from the low bits up, unsigned with zero point 2^(bits-1). The tensor described is the
* logical [N, K] code matrix, `rad_dtype` RAD_I4 or RAD_I8; `gptq_group` is the K columns one
* scale row covers. 0 for other tensors. */
int32_t gptq_bits = 0;
int64_t gptq_group = 0;
/* CT-INT4 (compressed-tensors' pack-quantized int4, symmetric): `data` is X.weight_packed's
* int32 words [N, K / 8], eight codes a word along K from the low bits up, stored unsigned with
* the zero point 8. The tensor this describes is the logical [N, K] code matrix, `rad_dtype`
* RAD_I4; `ct_group` is the K columns one scale of X.weight_scale [N, K / group] covers. 0 for
* any other tensor. */
/* CT-INT4 (compressed-tensors' symmetric pack-quantized int4): `data` is X.weight_packed's
* int32 words [N, K / 8], eight codes per word along K from the low bits up, unsigned with zero
* point 8. The tensor described is the logical [N, K] code matrix, `rad_dtype` RAD_I4;
* `ct_group` is the K columns one scale of X.weight_scale [N, K / group] covers. 0 for other
* tensors. */
int64_t ct_group = 0;
/* ParoQuant's int5-bitplane (Import::ParoI5): `data` is the AWQ-packed low nibbles qweight
* [K, N/8] and the tensor described is the logical [N, K] u5 code matrix; `aux` are the fifth-bit
@@ -85,13 +83,13 @@ struct MetaOwn {
RadModelMeta m{};
void kv(const std::string& k, const std::string& v) { keys.push_back(k); vals.push_back(v); }
/* A key given LAST that must also WIN: a lookup takes the first row with the key, so
* appending a key the checkpoint already set would write both and read the old one. */
/* Set a key that must win over an existing one: lookups take the first row with a key, so
* kv() would leave the old value in effect. */
void set(const std::string& k, const std::string& v);
bool has(const std::string& k) const;
const char* get(const std::string& k) const; /* null when absent */
/* Republish the pointers RadModelMeta carries. Every kv()/set() may move the strings, so this
* runs after the last of them and before `m` is read. */
/* Republish RadModelMeta's pointers. kv()/set() may move the strings, so call this after the
* last of them and before reading `m`. */
void finish();
};
@@ -110,13 +108,12 @@ public:
Checkpoint(const Checkpoint&) = delete;
Checkpoint& operator=(const Checkpoint&) = delete;
/* A .gguf, a .safetensors, a model.safetensors.index.json, or the directory holding one --
* and the metadata beside it. */
/* A .gguf, a .safetensors, a model.safetensors.index.json, or the directory holding one,
* plus the metadata beside it. */
int open(const std::string& path);
/* A SECOND checkpoint, merged into this one's namespace and metadata under `prefix`: a
* drafter that ships as its own repository (DFlash2) borrows the target's embedding and head,
* so it belongs in the target's container, its tensors under `draft.` and its config.json
* under `draft.` keys. */
/* Merge a second checkpoint under `prefix`: a drafter shipped as its own repository (DFlash2)
* borrows the target's embedding and head, so it goes into the target's container with its
* tensors and config.json keys under `draft.`. */
int add_draft(const std::string& dir, const std::string& prefix);
const SrcTensor* find(const std::string& n) const;
@@ -131,37 +128,40 @@ public:
MetaOwn& meta() { return meta_; }
const MetaOwn& meta() const { return meta_; }
/* Sub-tensor `index` of a STACKED tensor -- dim 0 of a rank >= 2 tensor -- as a view, owned
* here so every pointer handed out stays valid for the checkpoint's life. Null, with the
* reason logged, when there is no such slice. */
/* Sub-tensor `index` along dim 0 of a stacked (rank >= 2) tensor, as a view owned here and
* valid for the checkpoint's life. Null, with the reason logged, if there is no such slice. */
const SrcTensor* slice(const SrcTensor& st, int index, const char* declared);
/* FP8's block, from quantization_config.weight_block_size; 128x128 when it says nothing. */
int64_t fp8_block_rows() const { return fp8_br_; }
int64_t fp8_block_cols() const { return fp8_bc_; }
/* THE CHECKPOINT'S QUANTISATION, IMPORTED WEIGHT BY WEIGHT, or None. Read from
* quantization_config at open: AutoRound's `auto_round:auto_gptq` export and GPTQ's own (v1,
* the zero point stored less one) are Gptq; Quark's MXFP4 (fp4 weights, per_group 32, e8m0
* scales, no per-layer overrides) is QuarkMx; ParoQuant's MXFP4 (`paroquant_mxfp4`: Quark's
* codes and exponents in a ROTATED basis, with the rotations beside them) is ParoMx. A quantisation of one of those tools in a form
* this does not read stays None, with the reason in import_refusal(). */
/* Its quantization_config keys are then renamed `imported_quantization_config.*`: they
* describe the tool, not a served format, and a plugin reads the latter there. */
enum class Import { None, Gptq, QuarkMx, CtInt4, ParoMx, ParoI5, ParoI4 };
/* The checkpoint's quantisation imported weight by weight, or None; read from
* quantization_config at open. Gptq: AutoRound's `auto_round:auto_gptq` export and GPTQ v1
* (zero point stored less one). QuarkMx: Quark's MXFP4 (fp4 weights, per_group 32, e8m0
* scales, no per-layer overrides). ParoMx: ParoQuant's `paroquant_mxfp4` (Quark's codes and
* exponents in a rotated basis, rotations beside them). CtInt4, Nvfp4, CtFp8:
* compressed-tensors' pack-quantized int4, a release with an nvfp4-pack-quantized group, and
* one whose groups are all float-quantized FP8 (detect_import). In an Nvfp4 or CtFp8 release
* every weight without the NVFP4 tensors reads stock, so FP8 and bf16 linears beside the
* NVFP4 ones read by their own form. An unreadable form of these stays None, with the reason
* in import_refusal(). The quantization_config keys are then renamed
* `imported_quantization_config.*`, since they describe the tool, not a served format. */
enum class Import { None, Gptq, QuarkMx, CtInt4, ParoMx, ParoI5, ParoI4, Nvfp4, CtFp8 };
Import imports() const { return import_; }
const std::string& import_refusal() const { return import_why_; }
/* The pieces an imported weight is read from, as views owned here: for `name` (a `.weight`)
* the GPTQ-packed codes and their scale tensor, or Quark's codes and exponents as their RAD
* dtypes. RAD_E_NOTFOUND when the checkpoint ships `name` as an ordinary tensor or not at
* all; another error, with `why`, when it ships an imported form this cannot read. */
/* The pieces an imported `name` (a `.weight`) is read from, as views owned here: GPTQ-packed
* codes and their scales, Quark's codes and exponents as RAD dtypes, or NVFP4's codes as fp4
* beside an f32 scale plane derived from the e4m3 scales and the global scale. RAD_E_NOTFOUND
* when `name` is an ordinary tensor or absent; another error, with `why`, for an unreadable
* imported form. */
int import_piece(const std::string& name, const SrcTensor** codes, const SrcTensor** scale,
std::string* why);
private:
/* `owner`, when the checkpoint has an index, is its weight_map: a tensor the index places in
* another shard is not read from this one. */
/* `owner` is the index's weight_map, if any: a tensor it places in another shard is skipped
* here. */
int add_shard(const std::string& p, const std::string& prefix = "",
const std::unordered_map<std::string, std::string>* owner = nullptr);
int open_safetensors(const std::string& path);
@@ -178,11 +178,14 @@ private:
std::unordered_map<std::string, size_t> index_;
std::unordered_map<std::string, size_t> index_shard_; /* name -> shards_ position */
std::deque<SrcTensor> sliced_; /* views; a deque never moves what it holds */
/* Bytes a view's data points at when they are derived, not mapped (NVFP4's f32 scale
* plane); they live as long as the views. */
std::vector<std::unique_ptr<uint8_t[]>> owned_;
int64_t fp8_br_ = 128, fp8_bc_ = 128;
Import import_ = Import::None;
std::string import_why_;
int64_t ct_group_ = 0; /* CtInt4: the group every weight's config states */
/* import_piece's answers by name, so a weight resolved twice reads one pair of views. */
/* import_piece's answers by name, so a weight resolved twice reuses its views. */
std::unordered_map<std::string, std::pair<const SrcTensor*, const SrcTensor*>> imported_;
};
@@ -197,18 +200,20 @@ struct CkptWeight {
uint32_t rank = 0;
int64_t shape[RAD_MAX_RANK] = {0}; /* the logical shape */
int64_t rows = 0, cols = 0; /* its [rows, cols] view (rad_enc_view) */
/* The encoding the pieces ARE, when it is trivial; `why` says what is not when it is not. */
/* `enc` is the pieces' encoding when trivial; otherwise `why` says what is not. */
bool trivial = false;
/* GPTQ-PACKED PIECES, read into `enc` (`i4` or `i8` codes, bf16 scales a 128 of K) by
* ckpt_plane_rows: the codes transposed and offset to signed, the f16 scales rounded to bf16.
* Not trivial -- the rounding means the numbers are not served as shipped -- so the loader
* refuses one and rad-convert keeps it in `enc`, as it keeps a trivial weight. */
/* Imported pieces, read into `enc` by ckpt_plane_rows and ckpt_rows_f32. GPTQ-packed: `i4` or
* `i8` codes transposed and offset to signed, f16 scales rounded to bf16 per 128 of K.
* NVFP4: fp4 codes beside the f32 scale e4m3 / global per 16 of K. Not trivial (the scales
* are changed or derived), so the loader refuses it; rad-convert writes it as `enc` or
* quantises it by a recipe rule. A non-trivial FP8 weight may also state `enc` when it
* still reads piece by piece (a row join ending inside a scale block); one that cannot be
* read leaves `enc` unstated, and ckpt_rows_f32 refuses it with `why`. */
bool imported = false;
/* PAROQUANT MXFP4, IMPORTED (Import::ParoMx): `imported` too, so the loader refuses it and
* rad-convert writes it plane by plane through ckpt_plane_rows. Planes 0 and 1 are Quark's
* codes and exponents byte for byte; the rest are the "givens" transform's tables, built here
* from `pq_pairs`/`pq_theta`/`pq_scale`, one set per piece (a piece is a row PART: gate and up,
* or q, k and v, each rotated on its own). */
/* ParoQuant MXFP4 (Import::ParoMx), also `imported`: written plane by plane through
* ckpt_plane_rows. Planes 0 and 1 are Quark's codes and exponents byte for byte; the rest are
* the "givens" transform's tables, built from `pq_pairs`/`pq_theta`/`pq_scale`, one set per
* piece (a row part: gate and up, or q, k and v, each rotated separately). */
bool paro = false;
std::vector<const SrcTensor*> pq_pairs, pq_theta, pq_scale;
RadEncoding enc{};
@@ -230,17 +235,17 @@ std::string ckpt_tensor_of(const SrcTensor& t);
bool ckpt_reads_any(const CkptWeight& w, const std::unordered_set<std::string>& names,
std::unordered_set<std::string>* hit = nullptr);
/* One (part, group) of a ParoQuant rotation as its dense matrix: `S` stages of 64 pairs, the pair's two
* group-local columns `ia`/`ib` and angle `th`, stage-major; out[j * 128 + i] (f16) is output j for the
* unit vector e_i. It is the "givens" encoding's "t.dense" table, row for row. */
/* One (part, group) of a ParoQuant rotation as a dense matrix: `S` stages of 64 pairs, each with
* group-local columns `ia`/`ib` and angle `th`, stage-major; out[j * 128 + i] (f16) is output j for
* unit vector e_i. This is the "givens" encoding's "t.dense" table. */
void paro_compose_dense(int64_t S, const int32_t* ia, const int32_t* ib, const float* th, uint16_t* out);
/* Logical rows [r0, r0 + nr) of `w` as f32 [nr, cols], whatever the pieces are stored as: a
* plain float widened, FP8 times its block scale, a GGUF block type dequantised. */
int ckpt_rows_f32(const CkptWeight& w, int64_t r0, int64_t nr, float* out, std::string* why);
/* Rows [r0, r0 + nr) of plane `k` of a TRIVIAL or IMPORTED `w`, in the plane's own elements, dense
* into `dst`: the bytes a container entry holds for it. */
/* Rows [r0, r0 + nr) of plane `k` of a trivial or imported `w`, in the plane's own elements, dense
* into `dst`: the bytes a container entry holds. */
int ckpt_plane_rows(const CkptWeight& w, int k, int64_t r0, int64_t nr, void* dst,
std::string* why);
+18 -28
View File
@@ -102,9 +102,8 @@ Rd plane(const EncodedView& v, int idx) {
return r;
}
/* The tables of one row part of a "givens" weight, read once: the cosine and sine of every angle
* and the pairs as indices, so undoing a row is arithmetic and not a table walk. A decode asks for
* the part its row falls in, and rows of one part follow each other. */
/* One row part's "givens" tables, read once (pairs as indices, cos and sin of every angle) and
* reused while consecutive rows stay in the same part. */
struct GivensPart {
int64_t part = -1;
int64_t S = 0;
@@ -199,9 +198,8 @@ int enc_decode_rows(const EncodedView& v, int64_t row0, int64_t n, float* out, s
const bool plain = rad_enc_is(&e, "plain");
const bool affine = rad_enc_is(&e, "affine");
if (!plain && !affine) {
/* A QUANTISER'S OWN SCHEME, read by the quantiser that wrote it -- whichever loaded one
* answers for it (abi/rad_quant.h). The weight is described as far as the caller knows it:
* a [rows, cols] view and the planes from their starts. */
/* A quantiser's own scheme, decoded by whichever loaded quantiser accepts it
* (abi/rad_quant.h), given a [rows, cols] view and the plane starts. */
std::vector<RadQuantDecodeFn> fns;
{
std::lock_guard<std::mutex> lk(g_dec_mu);
@@ -266,12 +264,9 @@ int enc_decode_rows(const EncodedView& v, int64_t row0, int64_t n, float* out, s
}
std::vector<float> tmp(perm ? (size_t)v.cols : 0);
GivensPart gv;
/* THE COMMON FORM, A ROW AT A TIME: codes with no codebook, sign, zero or minimum and at most
* one scale level -- int4 experts, fp8 rows, a fixed-scale table. The element walk below
* resolves every element's dtype and its scale's index through a switch and two divisions,
* and on a Flash-Next conversion that walk is a third of the convert; here the codes' dtype is
* resolved once a row and the scale read once a group. The same products, so the same
* floats. */
/* Fast path for the common form (no codebook, sign, zero or minimum; at most one scale level,
* e.g. int4 experts, fp8 rows): dtype resolved once per row and the scale read once per group,
* instead of per element (a third of a Flash-Next conversion). Same products, same floats. */
const bool direct = V <= 1 && !table && !signs && !zero && mins.empty() && scales.size() <= 1;
for (int64_t i = 0; i < n; ++i) {
@@ -368,10 +363,8 @@ int enc_selection_logical(const RadEncoding& e, const int* sel, int n_sel, const
rad_store_f32(out, dt, i * c + j, rad_load_f32(src + i * rb, p.dtype, j));
return RAD_OK;
}
/* CODES AND THE SCALAR CODEBOOK THEY INDEX, without the scale: each code as its table entry.
* It is what a kernel that folds the scale itself reads -- the codes view of a w4nla8h expert
* -- and the entries are the values the reference multiplies, where the raw indices would be
* other numbers. */
/* Codes with the scalar codebook they index, without the scale: each code as its table entry,
* as read by a kernel that applies the scale itself (a w4nla8h expert's codes view). */
if (n_sel == 2 && !std::strcmp(e.plane[sel[0]].role, "codes") &&
!std::strcmp(e.plane[sel[1]].role, "table") && e.plane[sel[0]].kind == RAD_PLANE_TILED &&
e.plane[sel[0]].block[0] == 1 && e.plane[sel[0]].block[1] == 1 &&
@@ -394,14 +387,11 @@ int enc_selection_logical(const RadEncoding& e, const int* sel, int n_sel, const
}
return RAD_OK;
}
/* A SCALE AND THE LEVELS ABOVE IT, without the codes: each first-level scale times every level
* that covers it. It is what a kernel that takes its scales as an operand of their own reads
* where the encoding states them in two levels -- the scale view of a w4nl64a8h expert, an
* E4M3 scale a (row, 64 of K) under one fixed f32 -- and the product is the scale the
* reference multiplies, where the first level on its own is that scale off by the second. One
* element a first-level scale, in that plane's extents. A level has to cover whole
* first-level blocks -- the whole weight, or a block a multiple of the first's -- or a scale
* would straddle two of its elements and have no one product. */
/* A scale with the levels above it, without codes: each first-level scale times every level
* covering it, one element per first-level scale. Read by a kernel taking scales as their own
* operand when the encoding has two levels (a w4nl64a8h expert: an E4M3 scale per (row, 64 of
* K) under one f32). Each level must cover whole first-level blocks, or a product would be
* ambiguous. */
if (n_sel >= 2 && !std::strcmp(e.plane[sel[0]].role, "scale")) {
bool chain = true;
for (int k = 0; k < n_sel && chain; ++k) {
@@ -447,8 +437,8 @@ int enc_selection_logical(const RadEncoding& e, const int* sel, int n_sel, const
if (n_sel != e.n_planes)
return refuse("it takes " + std::to_string(n_sel) + " of its encoding's " +
std::to_string(e.n_planes) + " planes, which decode to nothing on their own");
/* The logical rows from the first selected plane and its block height; the columns are what
* is left of `n`, since a codes plane of vector codes does not carry them. */
/* Logical rows from the first plane and its block height; columns are what remains of `n`,
* since a vector-code plane does not carry them. */
const RadEncPlane& p0 = e.plane[sel[0]];
const int64_t r = rows[0] * (p0.kind == RAD_PLANE_TILED && p0.block[0] > 0 ? p0.block[0] : 1);
if (r <= 0 || n % r)
@@ -481,7 +471,7 @@ int enc_plane_rect(const RadEncPlane& p, int64_t rows, int64_t cols, int64_t r0,
lo, hi, extent);
return false;
}
if (b <= 0) { /* one element covers the whole extent: every slice has it */
if (b <= 0) { /* one element covers the whole extent; every slice has it */
*e0 = 0;
*en = pext;
return true;
@@ -498,7 +488,7 @@ int enc_plane_rect(const RadEncPlane& p, int64_t rows, int64_t cols, int64_t r0,
PlaneRect r;
if (!cut(r0, r1, rows, p.block[0], pr, &r.row0, &r.rows, "rows")) return RAD_E_SHAPE;
if (!cut(c0, c1, cols, p.block[1], pc, &r.col0, &r.cols, "columns")) return RAD_E_SHAPE;
/* A slice is copied as bytes, so a packed plane's cut has to land on a byte. */
/* Slices are copied as bytes, so a packed plane's cut must fall on a byte. */
const int bits = rad_dtype_bits(p.dtype);
if (bits > 0 && (r.col0 * bits) % 8 != 0) {
if (why) *why = fmt("column %lld of the ", r.col0) + rad_dtype_name(p.dtype) + " '" +
+25 -31
View File
@@ -1,11 +1,9 @@
/* encoding.h -- the core's half of a weight encoding: decoding one to f32, and cutting a plane for
/* encoding.h -- the core's half of a weight encoding: decoding to f32, and cutting a plane for
* tensor parallelism. The encoding itself is abi/rad_encoding.h; spec.md §4.1.
*
* The core decodes the two schemes it defines, "plain" and "affine", under every transform the
* ABI names, and nothing else: a quantiser that invents a scheme decodes it (abi/rad_quant.h). The
* decoder is what the oracle checks a kernel through, what rad-convert measures a quantiser's
* error with, and what a weight is read back through to be quantised again -- three consumers
* that must agree on what a stored weight means, which is why there is one of it.
* The core decodes its two schemes, "plain" and "affine", under every ABI transform; a quantiser
* that defines another scheme supplies its decoder (abi/rad_quant.h). The oracle, rad-convert's
* error measurement and re-quantisation all decode through this one implementation.
*/
#pragma once
#include "../rad_internal.h"
@@ -34,23 +32,22 @@ struct EncodedView {
void enc_view(const RadEncoding& e, int64_t rows, int64_t cols, const void* const* data,
EncodedView* v);
/* Decode logical rows [row0, row0 + n) into `out`, f32 [n, cols]. Returns RAD_OK, or
* RAD_E_UNSUPPORTED for a scheme the core does not decode (with `why` saying which), RAD_E_SHAPE
* when a transform does not fit the row, or RAD_E_FORMAT for a malformed encoding or a code its
* codebook has no entry for -- a corrupt file, said so, rather than a read past a table. */
/* Decode logical rows [row0, row0 + n) into `out`, f32 [n, cols]. RAD_OK; RAD_E_UNSUPPORTED for
* a scheme nobody decodes (`why` names it); RAD_E_SHAPE when a transform does not fit the row;
* RAD_E_FORMAT for a malformed encoding or a code outside its codebook (rather than a read past
* the table). */
int enc_decode_rows(const EncodedView& v, int64_t row0, int64_t n, float* out,
std::string* why = nullptr);
/* THE DECODERS FOR SCHEMES THE CORE DOES NOT DEFINE: quantisers' own (RadQuantDecodeFn). The
* plugin loader adds each loaded quantiser's and removes them when it unloads; enc_decode_rows
* asks them in that order for any scheme but plain and affine. */
/* Decoders for schemes the core does not define (RadQuantDecodeFn), registered by the plugin
* loader per quantiser; enc_decode_rows asks them in order for any scheme but plain and affine. */
void enc_add_decoder(RadQuantDecodeFn fn);
void enc_remove_decoder(RadQuantDecodeFn fn);
/* The unnormalised Sylvester Walsh-Hadamard transform of `n` values in place, `n` a power of two.
* The butterfly keeps (a + b) in the lower index and (a - b) in the upper, which is H_n in
* natural (Sylvester) order -- the transform libr4d's r4d_fwht_wave computes in registers, and the
* one an "fwhtN" encoding names. H_n is symmetric and H_n H_n = n I. */
/* Unnormalised Walsh-Hadamard transform of `n` values in place, `n` a power of two. The butterfly
* keeps (a + b) in the lower index and (a - b) in the upper: H_n in natural (Sylvester) order, as
* libr4d's r4d_fwht_wave computes and an "fwhtN" encoding names. H_n is symmetric and
* H_n H_n = n I. */
void fwht_inplace(float* v, int64_t n);
/* The canonical spelling of an encoding (rad_enc_format), as a string. */
@@ -58,15 +55,13 @@ std::string enc_name(const RadEncoding& e);
/* ================================================================== a selection, as a reader reads it
*
* The `n_sel` planes of `e` a declaration selects (RadWeightDecl::planes) -- plane `sel[k]` at
* `data[k]`, dense [rows[k], cols[k]] in its own elements -- as `n` elements of dtype `dt` at
* `out`: the tensor a reference implementation reads where a kernel reads the stored form. One
* plane is converted element by element (a bf16 scale plane into an f32 reference, codes as their
* values); codes with the scalar codebook they index, each code as its table entry; a scale with
* the levels of its chain above it, each scale as their product; the whole encoding is decoded.
* RAD_OK, or RAD_E_SHAPE with `why` when the planes do not make that tensor -- part of an
* encoding, which decodes to nothing on its own, or extents that disagree with `n`; or the
* decoder's own refusal. */
* The `n_sel` planes of `e` a declaration selects (RadWeightDecl::planes; plane `sel[k]` at
* `data[k]`, dense [rows[k], cols[k]] in its own elements) as `n` elements of dtype `dt` at `out`:
* the tensor a reference implementation reads in place of the stored form. A single plane converts
* element by element; codes with their scalar codebook become table entries; a scale with its
* chain's higher levels becomes their product; the whole encoding is decoded. RAD_OK, or
* RAD_E_SHAPE with `why` when the planes do not form that tensor (an incomplete encoding, or
* extents disagreeing with `n`), or the decoder's refusal. */
int enc_selection_logical(const RadEncoding& e, const int* sel, int n_sel, const int64_t* rows,
const int64_t* cols, const void* const* data, uint32_t dt, int64_t n,
void* out, std::string* why);
@@ -78,11 +73,10 @@ struct PlaneRect {
int64_t col0 = 0, cols = 0;
};
/* The part of plane `p` that covers logical rows [r0, r1) and columns [c0, c1) of a [rows, cols]
* weight. Refused, with `why`, when a bound would split one of the plane's blocks -- a scale that
* covers rows two ranks own between them belongs to neither, and taking it twice gives each a
* plane that decodes to the right numbers for the wrong rows. The weight's own end is never a
* split: a last block may be short. */
/* The part of plane `p` covering logical rows [r0, r1) and columns [c0, c1) of a [rows, cols]
* weight. Refused, with `why`, when a bound would split one of the plane's blocks (a scale shared
* by two ranks' rows belongs to neither). The weight's end never splits: a last block may be
* short. */
int enc_plane_rect(const RadEncPlane& p, int64_t rows, int64_t cols, int64_t r0, int64_t r1,
int64_t c0, int64_t c1, PlaneRect* out, std::string* why);
+40 -43
View File
@@ -1,8 +1,5 @@
/* imatrix.cpp -- the two llama.cpp imatrix formats and the small GGUF walker the newer one needs.
*
* Little-endian only, like everything else here. Every read is bounds-checked against the mapping
* before it happens: an imatrix is a file a user was handed by somebody else, and the quantiser
* that consumes it runs unattended for an hour.
* Little-endian only. Every read is bounds-checked against the mapping: the file is untrusted.
*/
#include "imatrix.h"
@@ -16,7 +13,7 @@
namespace rad {
namespace {
/* GGUF's value type tags. Only what a walker needs to know how far to step. */
/* GGUF's value type tags, enough to know how far to step. */
enum : uint32_t {
GT_U8 = 0, GT_I8 = 1, GT_U16 = 2, GT_I16 = 3, GT_U32 = 4, GT_I32 = 5, GT_F32 = 6,
GT_BOOL = 7, GT_STR = 8, GT_ARR = 9, GT_U64 = 10, GT_I64 = 11, GT_F64 = 12
@@ -48,8 +45,7 @@ struct Cursor {
if (out) out->assign((const char*)q, (size_t)n);
return true;
}
/* Step over a value of any type without interpreting it. Arrays recurse, which is how
* imatrix.datasets (an array of strings) is skipped when we do not want it. */
/* Step over a value of any type without interpreting it; arrays recurse. */
bool skip_value(uint32_t type) {
switch (type) {
case GT_U8: case GT_I8: case GT_BOOL: return take(1);
@@ -154,8 +150,7 @@ int ImatrixFile::read_legacy(const uint8_t* p, uint64_t n) {
return RAD_E_FORMAT;
}
/* Copied, not pointed at: the legacy layout puts floats at an offset that depends on the
* name length, so nothing in the file is guaranteed 4-byte aligned. */
/* Copied: legacy float offsets depend on the name length, so they may be unaligned. */
owned_.emplace_back((size_t)nval);
std::memcpy(owned_.back().data(), vp, (size_t)nval * sizeof(float));
@@ -173,9 +168,8 @@ int ImatrixFile::read_legacy(const uint8_t* p, uint64_t n) {
RAD_ERR("%s: truncated before the first entry", path_.c_str());
return RAD_E_FORMAT;
}
/* The legacy format cannot express per-expert data at all, and a MoE quantised against it
* weights every expert by the layer's aggregate. Say so once rather than let the quality
* difference show up as an unexplained regression. */
/* The legacy format has no per-expert data, so a MoE quantised with it weights every expert by
* the layer's aggregate; warn once. */
RAD_WARN("%s is the legacy imatrix format: it has no per-expert dimension, so every expert in "
"a layer will be weighted by the layer's aggregate activations. Re-collect with a "
"current llama.cpp for per-expert importance.", path_.c_str());
@@ -234,10 +228,8 @@ int ImatrixFile::read_gguf(const uint8_t* p, uint64_t n) {
}
if (!c.ok) { RAD_ERR("%s: truncated in the KV block", path_.c_str()); return RAD_E_FORMAT; }
/* THE TENSOR COUNT IS A NUMBER FROM THE FILE, and it sizes an allocation. Every tensor info
* is at least a name length, a dimension count, a type and an offset -- 24 bytes -- so a count
* the rest of the file cannot hold is refused here rather than handed to reserve(), where it
* is a multi-exabyte request that ends the process. */
/* The tensor count comes from the file and sizes an allocation. Each tensor info is at least
* 24 bytes, so refuse a count the file cannot hold before reserve(). */
constexpr uint64_t kMinInfoBytes = 8 + 4 + 4 + 8;
if (n_tensors > (uint64_t)(c.end - c.p) / kMinInfoBytes) {
RAD_ERR("%s: the header declares %llu tensors, and the %llu bytes after the KV block "
@@ -274,9 +266,8 @@ int ImatrixFile::read_gguf(const uint8_t* p, uint64_t n) {
return RAD_E_FORMAT;
}
/* Join `<base>.in_sum2` with `<base>.counts`. Insertion order defines entries() order, so a
* report over the file reads in the order the collector wrote it. `held` is how many floats
* each half actually spans in the file, parallel to entries_, for the extent checks below. */
/* Join `<base>.in_sum2` with `<base>.counts`, in file order. `held` (parallel to entries_) is
* how many floats each half spans in the file, for the extent checks below. */
std::unordered_map<std::string, size_t> by_base;
struct Held { uint64_t sum2 = 0, counts = 0; };
std::vector<Held> held;
@@ -292,9 +283,8 @@ int ImatrixFile::read_gguf(const uint8_t* p, uint64_t n) {
continue;
}
/* The element count is a product of four numbers from the file, so it is bounded by the
* data section BEFORE each multiply: a product that wraps can come out small, pass the
* bounds test below and be read at its declared extent. */
/* The element count is a product of four file values; bound it by the data section before
* each multiply so it cannot wrap. */
uint64_t numel = 1;
bool fits = true;
for (uint64_t d : t.dims) if (d == 0) numel = 0;
@@ -332,16 +322,14 @@ int ImatrixFile::read_gguf(const uint8_t* p, uint64_t n) {
}
}
/* THE QUERIES INDEX BY WHAT THE ENTRY CLAIMS, so the claim has to fit what the file holds.
* `importance` reads cols floats at expert * cols and `count` reads counts[expert] for every
* expert below n_expert -- both taken from the .in_sum2 dims -- so a .counts shorter than the
* expert count, or an .in_sum2 whose trailing dims multiply to less than cols x n_expert,
* would be read past its own extent. */
/* The queries index by the entry's claimed dims (from .in_sum2): `importance` reads cols floats
* at expert * cols and `count` reads counts[expert]. Check both halves actually hold that
* much. */
std::vector<ImatrixEntry> kept;
kept.reserve(entries_.size());
for (size_t k = 0; k < entries_.size(); ++k) {
ImatrixEntry& e = entries_[k];
/* An entry with counts and no values is a collector bug, not something to weight by. */
/* Counts without values is a collector bug. */
if (!e.sum2 || e.cols <= 0) {
RAD_WARN("%s: '%s' has counts but no .in_sum2 -- dropped", path_.c_str(),
e.name.c_str());
@@ -379,21 +367,9 @@ bool ImatrixFile::importance(const std::string& name, int64_t expert,
const float* src = e->sum2 + expert * e->cols;
/* NORMALISED TO MEAN 1, and that is the whole of it.
*
* The row is NOT divided by the expert's activation count first, although that looks like a way
* to say "an expert that saw ten times the tokens is not ten times as important". The division
* cannot do that: the result is a single expert's row scaled to mean 1, and a uniform divisor
* applied to every column of that row is removed exactly by the scaling that follows it. What
* it can do is flush small columns to zero against a large count, and an all-zero row then
* takes the degenerate branch below -- so its only effect would be to lose weights.
*
* Popularity ACROSS experts is a different question and has its own query, `count`, which
* reports the raw number for exactly this reason.
*
* Mean 1 is what makes a weighted error comparable with an unweighted one, and therefore what
* makes the quantiser's error report mean the same thing with and without an imatrix. A
* degenerate (all-zero) row falls back to uniform weights rather than to NaN. */
/* Normalise to mean 1 only. Dividing by the expert's count first would be undone by the
* normalisation and could only flush small columns to zero. Popularity across experts is
* `count`'s job. An all-zero row falls back to uniform weights rather than NaN. */
out->resize((size_t)e->cols);
std::memcpy(out->data(), src, (size_t)e->cols * sizeof(float));
double sum = 0.0;
@@ -406,6 +382,27 @@ bool ImatrixFile::importance(const std::string& name, int64_t expert,
return true;
}
bool ImatrixFile::importance_for(const std::string& weight, int64_t cols,
std::vector<float>* out) const {
std::string base = weight;
if (base.size() > 7 && base.compare(base.size() - 7, 7, ".weight") == 0)
base.resize(base.size() - 7);
int64_t expert = 0;
if (!find(base)) {
/* `<stem>.<expert>`: the last component must be a plain decimal index. */
const size_t dot = base.find_last_of('.');
if (dot == std::string::npos || dot + 1 == base.size()) return false;
for (size_t i = dot + 1; i < base.size(); ++i) {
if (base[i] < '0' || base[i] > '9' || expert > ((int64_t)1 << 40)) return false;
expert = expert * 10 + (base[i] - '0');
}
base.resize(dot);
}
const ImatrixEntry* e = find(base);
if (!e || e->cols != cols) return false;
return importance(base, expert, out);
}
double ImatrixFile::count(const std::string& name, int64_t expert) const {
const ImatrixEntry* e = find(name);
if (!e || !e->counts || expert < 0 || expert >= e->n_expert) return 0.0;
+29 -32
View File
@@ -1,30 +1,24 @@
/* imatrix.h -- llama.cpp's importance matrix, both of the formats it has written.
/* imatrix.h -- llama.cpp's importance matrix, in both formats it has written.
*
* An imatrix is a per-column activation second moment, collected over a calibration set. It does
* two jobs here and they are unrelated:
* An imatrix is a per-column activation second moment over a calibration set. Two unrelated uses:
*
* - the QUANTISER weights its per-block error by it, so bits go where the activations are
* (spec §4.3);
* - the CONVERTER derives the expert-popularity profile from its activation counts, which is
* what the placement planner warm-starts from (spec §5.3). That is a warm start and not a
* policy: imatrix popularity is not decode popularity, and the heat engine re-ranks from real
* routing within a few dispatches regardless.
* - the quantiser weights its per-block error by it, so bits go where activations are
* (spec §4.5);
* - the converter derives the expert-popularity profile from its counts, the planner's warm
* start (spec §5.3). Only a warm start: the heat engine re-ranks from real routing within a
* few dispatches.
*
* Two formats, because llama.cpp has written two and both are in the wild:
* Formats:
*
* LEGACY a flat little-endian binary: int32 n_entries, then per entry
* int32 name_len, char[name_len], int32 ncall, int32 nval, float[nval].
* The values are SUMS OF SQUARES ALREADY DIVIDED BY ncall by the writer in some
* versions and not in others, which is exactly why the newer format exists.
* GGUF a GGUF v3 container whose tensors are `<name>.in_sum2` (f32 [cols] or [cols,n_expert])
* and `<name>.counts` (f32 [1] or [1,n_expert]), plus `imatrix.chunk_count`,
* `imatrix.chunk_size` and `imatrix.datasets` in the KV block. Per-expert data is a
* second dimension, which the legacy format could not express at all.
* legacy flat little-endian binary: int32 n_entries, then per entry int32 name_len,
* char[name_len], int32 ncall, int32 nval, float[nval]. Whether values are already
* divided by ncall varies by writer version.
* GGUF a GGUF v3 container with tensors `<name>.in_sum2` (f32 [cols] or [cols,n_expert]) and
* `<name>.counts` (f32 [1] or [1,n_expert]), plus `imatrix.chunk_count`,
* `imatrix.chunk_size` and `imatrix.datasets`. Only this format has per-expert data.
*
* The GGUF walker below is local rather than core/text's. That is deliberate: the imatrix is a
* file format and core/format owns file formats, the walker is a hundred lines, and coupling the
* quantiser's input to the tokeniser component's reader would join two things with no other
* relationship. It also has to sit beside the legacy reader, which is not GGUF at all.
* The GGUF walker is local rather than core/text's: it is small, and keeps the quantiser's input
* independent of the tokeniser's reader.
*/
#pragma once
#include "../rad_internal.h"
@@ -35,9 +29,8 @@
namespace rad {
/* `sum2` and `counts` point into the mapped file for a GGUF imatrix, at whatever offset its
* general.alignment put them -- which may be 1 -- so they are read with memcpy, never in place.
* importance() and count() do that. */
/* For a GGUF imatrix, `sum2` and `counts` point into the mapping at general.alignment (possibly 1),
* so importance() and count() read them with memcpy, never in place. */
struct ImatrixEntry {
std::string name; /* the checkpoint tensor name, suffix stripped */
const float* sum2 = nullptr; /* [n_expert][cols], expert-major and contiguous */
@@ -67,13 +60,17 @@ public:
bool is_gguf() const { return gguf_; }
const std::string& path() const { return path_; }
/* Column importance for one expert, NORMALISED TO MEAN 1. The normalisation is what makes a
* weighted error comparable with an unweighted one, and therefore what makes a quantiser's
* error report mean the same thing with and without an imatrix. Returns false if the tensor
* is absent, the expert is out of range, or the entry carries no values. */
/* Column importance for one expert, normalised to mean 1 so weighted and unweighted errors are
* comparable. False if the tensor is absent, the expert out of range, or no values. */
bool importance(const std::string& name, int64_t expert, std::vector<float>* out) const;
/* Raw activation count for one expert -- the popularity signal, unnormalised. 0 if absent. */
/* importance() for a weight as the converter names it. The imatrix uses GGUF names without the
* `.weight` suffix and keeps a MoE layer's experts as one entry, so `blk.5.ffn_down.weight` is
* entry `blk.5.ffn_down` (expert 0) and an expert slice `blk.5.ffn_down_exps.9.weight` is
* expert 9 of `blk.5.ffn_down_exps`. False when no entry matches or its width is not `cols`. */
bool importance_for(const std::string& weight, int64_t cols, std::vector<float>* out) const;
/* Raw activation count for one expert (the popularity signal). 0 if absent. */
double count(const std::string& name, int64_t expert) const;
private:
@@ -87,8 +84,8 @@ private:
std::string path_, dataset_;
int64_t chunk_count_ = 0, chunk_size_ = 0;
/* The legacy format's floats are not aligned in the file and are followed by no counts, so
* they are copied out rather than pointed at. GGUF payloads are pointed at. */
/* Legacy floats are unaligned in the file, so they are copied out; GGUF payloads are pointed
* at. */
std::vector<std::vector<float>> owned_;
std::vector<ImatrixEntry> entries_;
std::unordered_map<std::string, size_t> index_;
+14 -14
View File
@@ -1,10 +1,6 @@
/* machine_key.cpp -- the machine half of the tuning cache key.
*
* Separate from tunecache.cpp on purpose: the cache is pure file I/O and must stay linkable and
* testable without a device layer, while this needs one. It is also the only part of the key that
* can be wrong in a way that is invisible -- a cache measured on another card is not a slower
* answer, it is a wrong one -- so it names everything that changes the answer and nothing that
* does not.
/* machine_key.cpp -- the machine half of the tuning cache key. Separate from tunecache.cpp, which
* is pure file I/O and must link without a device layer. A cache from another machine gives wrong
* answers, so the key names everything that changes the answer and nothing else.
*/
#include "tunecache.h"
@@ -15,10 +11,12 @@ namespace rad {
std::string rad_machine_key() {
RadDeviceProps p{};
const int n = rad_dev_count();
return rad_machine_key_of(n, n > 0 && rad_dev_props(0, &p) >= 0 ? &p : nullptr);
}
/* The host backend is a supported configuration and not a degraded one, so it gets a real key
* rather than a placeholder: host kernels tune too, and their answer depends on the CPU. */
if (n <= 0 || rad_dev_props(0, &p) < 0) {
std::string rad_machine_key_of(int n, const RadDeviceProps* dev) {
/* No device to name at all. */
if (n <= 0 || !dev) {
#if defined(__x86_64__)
return "host-x86_64";
#elif defined(__aarch64__)
@@ -28,10 +26,12 @@ std::string rad_machine_key() {
#endif
}
/* Device count matters because a collective's variant depends on how many peers there are,
* and those rows share this file. Card name is included, arch is not enough: two boards of the
* same architecture can differ in clocks and memory width. */
std::string name = p.is_host_backend ? "host" : p.name;
/* Device count, because a collective's variant depends on the peer count; card name, because
* boards of one arch differ in clocks and memory width. The host backend's device name is the
* CPU model, which host kernels' tuning depends on (an AVX2 part's answer is not an AVX-512
* part's), so its key is `host-x<N>-<cpu model>`. */
const RadDeviceProps& p = *dev;
std::string name = p.name;
for (char& c : name)
if (!((c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z')))
c = '_';
+88
View File
@@ -0,0 +1,88 @@
/* quantise.cpp -- see quantise.h. */
#include "quantise.h"
#include <algorithm>
#include <vector>
namespace rad {
int quantise_weight(const RadQuantizerInfo& q, const RadParam* params, int n_params,
const RadQuantWeight& qw, const RadEncoding& enc, int64_t band_bytes,
const QuantIo& io, std::string* why) {
auto refuse = [&](int rc, std::string m) {
if (why) *why = std::move(m);
return rc;
};
/* The movement group and the importance are known now; the encoding chosen without them must
* not change. */
{
RadEncoding again{};
if (q.encoding(params, n_params, &qw, &again) != RAD_OK || !rad_enc_equal(&again, &enc))
return refuse(RAD_E_STATE,
std::string(q.name) + " answers with another encoding once it is told "
"the weight's movement group, and declare could not tell it that. An "
"encoding may depend on the weight's name and shape, not on where it is "
"placed.");
}
const int64_t R = qw.rows, C = qw.cols;
int64_t rb = q.row_block ? q.row_block(params, n_params, &qw) : 0;
if (rb <= 0 || rb > R) rb = R;
int64_t blk = rb;
if (rb < R) {
const int64_t want = std::max<int64_t>(1, band_bytes / std::max<int64_t>(C * 4, 1));
blk = std::max<int64_t>(rb, want - want % rb);
if (blk > R) blk = R;
}
const int np = enc.n_planes;
std::vector<int64_t> prow_bytes((size_t)np), pband((size_t)np);
std::vector<std::vector<uint8_t>> whole((size_t)np), band((size_t)np);
bool misaligned = false;
for (int k = 0; k < np; ++k) {
const RadEncPlane& p = enc.plane[k];
int64_t pr = 0, pc = 0;
rad_enc_plane_dims(&p, R, C, &pr, &pc);
prow_bytes[(size_t)k] = rad_enc_row_bytes(p.dtype, pc);
const bool banded = p.kind == RAD_PLANE_TILED && p.block[0] > 0;
pband[(size_t)k] = banded ? p.block[0] : 0;
if (banded && blk < R && blk % p.block[0]) misaligned = true;
if (!banded) whole[(size_t)k].assign((size_t)(pr * prow_bytes[(size_t)k]), 0);
}
if (misaligned)
return refuse(RAD_E_SHAPE, fmt("%s takes %lld rows a call, which splits a block of its "
"own encoding's scales", q.name, (long long)rb));
std::vector<float> f, ref;
for (int64_t r0 = 0; r0 < R; r0 += blk) {
const int64_t n = std::min(blk, R - r0);
f.resize((size_t)(n * C));
std::string w1;
if (io.read(r0, n, f.data(), &w1) != RAD_OK) return refuse(RAD_E_FORMAT, w1);
if (io.band) ref = f; /* a quantiser may rotate its input in place */
std::vector<void*> ptr((size_t)np);
for (int k = 0; k < np; ++k) {
if (!pband[(size_t)k]) { ptr[(size_t)k] = whole[(size_t)k].data(); continue; }
const int64_t rows_k = (n + pband[(size_t)k] - 1) / pband[(size_t)k];
band[(size_t)k].assign((size_t)(rows_k * prow_bytes[(size_t)k]), 0);
ptr[(size_t)k] = band[(size_t)k].data();
}
const int st = q.quantize(params, n_params, &qw, f.data(), r0, n, ptr.data());
if (st != RAD_OK)
return refuse(st, fmt("%s could not quantise rows [%lld, %lld): %s", q.name,
(long long)r0, (long long)(r0 + n), rad_strerror(st)));
for (int k = 0; k < np; ++k) {
if (!pband[(size_t)k]) continue;
if (io.write(k, (r0 / pband[(size_t)k]) * prow_bytes[(size_t)k],
band[(size_t)k].data(), (int64_t)band[(size_t)k].size()) != RAD_OK)
return refuse(RAD_E_IO, fmt("writing plane %d of rows [%lld, %lld) failed", k,
(long long)r0, (long long)(r0 + n)));
}
if (io.band) io.band(r0, n, ref.data(), (const void* const*)ptr.data());
}
for (int k = 0; k < np; ++k)
if (!pband[(size_t)k] &&
io.write(k, 0, whole[(size_t)k].data(), (int64_t)whole[(size_t)k].size()) != RAD_OK)
return refuse(RAD_E_IO, fmt("writing plane %d failed", k));
return RAD_OK;
}
} /* namespace rad */
+46
View File
@@ -0,0 +1,46 @@
/* quantise.h -- one weight through a quantiser plugin, as rad-convert writes it.
*
* The loop asks the quantiser for its rows per call, hands it bands of a multiple of that near
* `band_bytes` of f32 (so a table of tens of GB streams and a GPTQ weight, whose row block is 0, is
* passed whole), writes each row-banded plane per band, and holds whole-tensor planes (a codebook, a
* per-tensor scale) until the last call. rad-convert writes a container through it, and the
* quantiser tests (tests/quant_fixture.h) run the same loop into memory, so the tests exercise the
* path every container is made by.
*/
#pragma once
#include "../rad_internal.h"
#include "rad_encoding.h"
#include "rad_quant.h"
#include <functional>
#include <string>
namespace rad {
/* The band rad-convert quantises at: 64 MiB of f32 rows. */
constexpr int64_t kQuantBandBytes = (int64_t)64 << 20;
struct QuantIo {
/* Rows [r0, r0 + n) of the source weight as f32 [n, cols]. RAD_OK, or a failure with *why. */
std::function<int(int64_t r0, int64_t n, float* out, std::string* why)> read;
/* `bytes` of plane `k`, at byte `off` within that plane. RAD_OK, or a failure. */
std::function<int(int k, int64_t off, const void* data, int64_t bytes)> write;
/* Optional, after each quantise call: the band's source rows as read, before the quantiser
* changed them in place, and the planes that call wrote (a row-banded plane's rows for this
* band, a whole plane from its start), as a decoder takes them over `n` rows. */
std::function<void(int64_t r0, int64_t n, const float* src, const void* const* planes)> band;
};
/* Quantise `qw` under quantiser `q` and its `params` into `enc`, the encoding the quantiser answered
* when the weight was planned. Returns RAD_OK, or with the reason in *why:
* RAD_E_STATE given `qw`'s movement group and importance, the quantiser answers another
* encoding than the one planned;
* RAD_E_SHAPE its row block splits a block of its own encoding's scales;
* RAD_E_FORMAT the read failed;
* RAD_E_IO a write failed;
* otherwise the quantiser's own refusal. */
int quantise_weight(const RadQuantizerInfo& q, const RadParam* params, int n_params,
const RadQuantWeight& qw, const RadEncoding& enc, int64_t band_bytes,
const QuantIo& io, std::string* why);
} /* namespace rad */
+109 -135
View File
@@ -1,8 +1,6 @@
/* radfile.cpp -- the .rad reader and writer.
*
* Two halves of one decision. Everything the reader assumes on the hot path, the writer proves
* while writing and the reader re-proves at open. The pair is in one file so a change to the
* layout cannot land on only one side.
/* radfile.cpp -- the .rad reader and writer. Everything the reader assumes on the hot path, the
* writer checks while writing and the reader re-checks at open; one file, so a layout change
* touches both.
*/
#include "radfile.h"
@@ -73,28 +71,22 @@ int RadFile::read_at(void* dst, int64_t bytes, int64_t off) const {
}
void RadFile::drop_blob_cache() const {
if (!base_ || !hdr_ || fd_ < 0) return;
const int64_t tables = (int64_t)hdr_->data_off < size_ ? (int64_t)hdr_->data_off : size_;
if (tables >= size_) return;
/* The process's mapping first, then the cache behind it: a page still mapped here is one the
* kernel has to unmap before it can drop it, and doing it in the other order leaves the
* fadvise with nothing to free. */
/* Unmap first, then drop the cache: the kernel cannot drop a page still mapped here. */
::madvise(base_ + tables, (size_t)(size_ - tables), MADV_DONTNEED);
::posix_fadvise(fd_, (off_t)tables, (off_t)(size_ - tables), POSIX_FADV_DONTNEED);
}
/* Advisory, and deliberately NOT paired with an madvise: the load reads with pread and never
* maps these pages, so there is nothing of ours to unmap -- and the one region that IS read
* through the mapping, the n-gram table on Tier::Mapped, is never handed to this. */
/* Advisory, with no madvise: the load reads with pread and never maps these pages. The one region
* read through the mapping (a Tier::Mapped table) is never passed here. */
void RadFile::drop_range(int64_t off, int64_t bytes) const {
if (fd_ < 0 || bytes <= 0) return;
::posix_fadvise(fd_, (off_t)off, (off_t)bytes, POSIX_FADV_DONTNEED);
}
int RadFile::open(const char* path) {
close();
if (!path || !*path) return RAD_E_INVAL;
path_ = path;
@@ -119,31 +111,15 @@ int RadFile::open(const char* path) {
int s = validate();
if (s < 0) { close(); return s; }
/* THE TABLES ARE WANTED NOW; THE BLOB IS READ ONCE, FRONT TO BACK.
*
* THE ADVICE IS DELIBERATELY ASYMMETRIC AND MUST STAY THAT WAY.
*
* MADV_WILLNEED over the whole file asks the kernel to pull every byte into the page cache.
* That is right for a container that fits in RAM and ruinous for one that does not: it becomes
* a readahead storm that evicts the pages it just read and never settles, and the weight load
* collapses to a small fraction of disk bandwidth with the host thread spinning inside
* hipMemcpyAsync waiting on a copy engine starved for source pages. The tables are small and
* read immediately and in full, so they keep WILLNEED; the blob gets NO advice at all.
*
* MADV_SEQUENTIAL is the obvious replacement for the blob and is worse than silence: it widens
* the readahead window and drops pages behind the read pointer, and the load is not one
* stream. It reads a layer's gate_up experts, then that layer's down experts, then the
* scales -- three cursors over three regions -- so "behind" for one of them is "just about to
* be read" for another, and every page is fetched, dropped, and fetched again. Default
* readahead is what this copy loop is fastest under.
*
* The Tier::Mapped weights re-advise their own range MADV_RANDOM once the planner has spoken
* (engine_bringup.cpp); a later madvise over a sub-range wins for that sub-range, so leaving
* the blob unadvised here does not take that away. */
/* The advice is deliberately asymmetric; keep it so. The tables are small and read at once,
* so they get MADV_WILLNEED. The blob gets no advice: WILLNEED on a container larger than RAM
* becomes a readahead storm that evicts what it just read and starves the load, and
* MADV_SEQUENTIAL drops pages behind the pointer, which hurts when several cursors read
* different regions. Tier::Mapped weights later advise their own range MADV_RANDOM
* (engine_bringup.cpp), which wins for that sub-range. */
const int64_t tables = (int64_t)hdr_->data_off < size_ ? (int64_t)hdr_->data_off : size_;
::madvise(base_, (size_t)tables, MADV_WILLNEED);
/* A container extended in place (RadWriter::begin_append) keeps its tables PAST the blob;
* they are wanted now just the same. */
/* A container extended in place (RadWriter::begin_append) keeps its tables past the blob. */
const int64_t blob_end = (int64_t)(hdr_->data_off + hdr_->data_bytes);
if ((int64_t)hdr_->str_off >= blob_end && blob_end < size_)
::madvise(base_ + (blob_end & ~(int64_t)(RAD_ALIGN_UNIT - 1)),
@@ -153,13 +129,18 @@ int RadFile::open(const char* path) {
by_name_.reserve((size_t)hdr_->dir_count * 2);
for (int64_t i = 0; i < (int64_t)hdr_->dir_count; ++i)
by_name_.emplace(std::string_view(str(dir_[i].name)), i);
if (!by_name_.emplace(std::string_view(str(dir_[i].name)), i).second) {
RAD_ERR("%s: '%s' is in the directory twice (rows %lld and %lld); a lookup by name "
"would serve only the first", path, str(dir_[i].name),
(long long)by_name_[std::string_view(str(dir_[i].name))], (long long)i);
close();
return RAD_E_FORMAT;
}
return RAD_OK;
}
/* Every offset and count in the header is attacker-shaped input until this function has run.
* Nothing below this point re-checks, so nothing below this point may be reached without it. */
/* Every header offset and count is untrusted until this has run; nothing later re-checks. */
int RadFile::validate() {
hdr_ = (const RadFileHeader*)base_;
@@ -184,11 +165,9 @@ int RadFile::validate() {
auto span_ok = [&](uint64_t off, uint64_t bytes) {
return bytes == 0 ? off <= n : (off <= n && bytes <= n - off);
};
/* A TABLE IS CHECKED BY ITS COUNT, NEVER BY count * sizeof. Every count in the header is
* uint64 and attacker-shaped, so the product wraps: meta_count = 0x0AAAAAAAAAAAAAAB times
* 24 bytes is 8, span_ok passes, and the loop below -- which iterates meta_count, not the
* byte span -- walks 7.6e17 rows off the end of the mapping. Divide into the space that is
* left instead, where nothing can wrap. */
/* Check tables by count, never by count * sizeof: an untrusted uint64 count can wrap the
* product (0x0AAAAAAAAAAAAAAB * 24 == 8) while the loops iterate the count. Divide into the
* remaining space instead. */
auto span_n = [&](uint64_t off, uint64_t count, uint64_t elem) {
if (count == 0) return off <= n;
return off <= n && count <= (n - off) / elem;
@@ -251,9 +230,8 @@ int RadFile::validate() {
}
}
/* An encoding the core cannot read is refused here, by its index, rather than handed to a
* kernel's layout hook as if it meant something: rad_enc_valid() is the whole contract of the
* struct -- roles, chains, plane kinds and core dtypes. */
/* Refuse an encoding the core cannot read here, by index, rather than pass it to a layout
* hook. rad_enc_valid() checks the whole struct: roles, chains, plane kinds, core dtypes. */
for (uint64_t i = 0; i < hdr_->enc_count; ++i) {
RadEncoding e;
std::memcpy(&e, &encs_[i], sizeof e);
@@ -313,8 +291,8 @@ int RadFile::validate() {
(unsigned long long)hdr_->plane_count, enc.n_planes);
return RAD_E_FORMAT;
}
/* EVERY PLANE IS EXACTLY ITS ENCODING'S SIZE AND INSIDE ITS ENTRY. That is what lets a
* reader slice a plane by arithmetic and a mover treat the entry as one span. */
/* Every plane is exactly its encoding's size and inside its entry, so readers slice planes
* by arithmetic and the mover treats the entry as one span. */
int64_t rows = 0, cols = 0;
rad_enc_view(e.rank, e.shape, &rows, &cols);
for (uint32_t k = 0; k < e.n_planes; ++k) {
@@ -335,18 +313,16 @@ int RadFile::validate() {
/* ---------------------------------------------------------------- vocab */
if (hdr_->vocab_bytes >= sizeof(RadVocabHeader)) {
/* THE SECTION IS READ IN PLACE through typed pointers, so the header and every array have
* to sit on their element's alignment, which is where the writer puts them. A file that
* does not is damaged, and reading it anyway is a misaligned load for every field. */
/* The section is read in place through typed pointers, so the header and every array must
* be aligned to their element (the writer guarantees it). */
if (hdr_->vocab_off % alignof(RadVocabHeader) != 0) {
RAD_ERR("%s: the vocab section starts at %llu, which is not %zu-aligned", path_.c_str(),
(unsigned long long)hdr_->vocab_off, alignof(RadVocabHeader));
return RAD_E_FORMAT;
}
const RadVocabHeader* v = (const RadVocabHeader*)(base_ + hdr_->vocab_off);
/* Offset 0 means the array is absent -- an optional one (scores are unigram-only, types
* default to normal) simply is not written. Nothing real can live at file offset 0, so
* the sentinel is unambiguous. */
/* Offset 0 means an optional array is absent (scores are unigram-only; types default to
* normal). Nothing real lives at file offset 0. */
auto arr_ok = [&](uint64_t off, uint64_t bytes, size_t align) {
return bytes == 0 || off == 0 ||
(off >= hdr_->vocab_off &&
@@ -405,13 +381,9 @@ int RadFile::validate() {
return RAD_OK;
}
/* Re-derive the fixed stride and refuse a container that does not have one.
*
* This is where the format's central claim is checked. `base + id * stride` is what the mover and
* the expert kernels do on the critical path, and they do it without a bounds test, so the claim
* has to be true before anything is handed a pointer. A file whose experts within a layer differ
* in shape or format is REFUSED here rather than read with a table walk: reading it slowly would
* quietly return exactly the property the format exists to provide. */
/* Re-derive each layer's fixed expert stride and refuse a container without one. The mover and
* expert kernels compute `base + id * stride` with no bounds test, so this must hold before any
* pointer is handed out. */
int RadFile::index_experts() {
const int64_t n = (int64_t)hdr_->dir_count;
int64_t i = 0;
@@ -432,7 +404,7 @@ int RadFile::index_experts() {
g.layer = layer;
g.first_index = i;
/* Expert 0 establishes the shape of every expert in this layer. */
/* Expert 0 defines the layout of every expert in this layer. */
int64_t j = i;
while (j < n && dir_[j].layer == layer && dir_[j].expert == 0) ++j;
g.n_slot = (int32_t)(j - i);
@@ -462,8 +434,8 @@ int RadFile::index_experts() {
}
g.unit_bytes = unit_end - g.base;
/* Every further expert must agree, byte for byte, with expert 0's internal layout, and
* must sit exactly one stride further along. */
/* Every further expert must match expert 0's internal layout exactly and sit one stride
* further along. */
int32_t e_id = 1;
while (j < n && dir_[j].layer == layer && dir_[j].expert >= 0) {
if (dir_[j].expert != e_id) {
@@ -559,9 +531,9 @@ int RadWriter::begin(const char* path) {
fd_out_ = ::open(path_.c_str(), O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0644);
if (fd_out_ < 0) { RAD_ERR("%s: %s", path_.c_str(), std::strerror(errno)); return RAD_E_IO; }
/* The data blob is spilled beside the target and spliced in at finish(). The tables in front
* of it cannot be sized until every weight has been added, and the blob is the model -- a
* 1.5 GB checkpoint is not going to be staged in RAM so the header can be back-patched. */
/* The blob is spilled beside the target and spliced in at finish() (unless sealed): the
* tables in front cannot be sized until every weight is added, and the blob is not held in
* RAM. */
fd_spill_ = ::open(spill_path_.c_str(), O_RDWR | O_CREAT | O_TRUNC | O_CLOEXEC, 0600);
spill_base_ = 0;
if (fd_spill_ < 0) {
@@ -576,8 +548,8 @@ int RadWriter::begin(const char* path) {
void RadWriter::abort() {
if (append_) {
/* The file is the caller's container, not ours to unlink: put its header back -- a no-op
* unless finish_append() failed inside that last write -- and cut the tail off. */
/* The file is the caller's container: restore its header (a no-op unless finish_append()
* failed in that write) and truncate the tail. */
if (fd_out_ >= 0) {
(void)!::pwrite(fd_out_, &old_hdr_, sizeof old_hdr_, 0);
(void)!::ftruncate(fd_out_, (off_t)old_size_);
@@ -598,9 +570,8 @@ void RadWriter::abort() {
/* ------------------------------------------------------------------ append in place */
/* The processes other than this one that hold the file open or mapped. /proc/<pid>/fd for an open
* descriptor and /proc/<pid>/maps for a mapping whose descriptor was closed; a process this user
* cannot inspect is not counted, which is the same reach the caller has over that process. */
/* Other processes holding the file open (/proc/<pid>/fd) or mapped (/proc/<pid>/maps). Processes
* this user cannot inspect are not counted. */
static std::vector<long> other_users(dev_t dev, ino_t ino) {
std::vector<long> who;
DIR* d = ::opendir("/proc");
@@ -661,8 +632,8 @@ int RadWriter::begin_append(const char* path, const RadFile& old) {
::close(fd_out_); fd_out_ = -1;
return RAD_E_IO;
}
/* The file `old` describes, unchanged since it was read: its header, byte for byte, and its
* length. Anything else and the directory being carried over names somebody else's bytes. */
/* The file must be unchanged since `old` read it (header bytes and length), or the carried-over
* directory would name the wrong bytes. */
if (::pread(fd_out_, &old_hdr_, sizeof old_hdr_, 0) != (ssize_t)sizeof old_hdr_ ||
std::memcmp(&old_hdr_, &old.header(), sizeof old_hdr_) != 0 ||
(int64_t)st.st_size != old.size()) {
@@ -686,7 +657,6 @@ int RadWriter::begin_append(const char* path, const RadFile& old) {
spill_base_ = append_base_;
if (fd_spill_ < 0) {
RAD_ERR("%s: %s", path, std::strerror(errno));
if (fd_spill_ >= 0) ::close(fd_spill_);
::close(fd_out_);
fd_out_ = fd_spill_ = -1;
return RAD_E_IO;
@@ -698,8 +668,11 @@ int RadWriter::begin_append(const char* path, const RadFile& old) {
int64_t RadWriter::add_existing(const Weight& w, const RadFile& old, const RadFileEntry& e) {
if (!began_ || !append_) return RAD_E_STATE;
/* The bytes and the encoding are the old entry's; what the entry SAYS about where it came from
* and which unit it moves with is the caller's, as a fresh write would record it. */
if (w.name.empty() || names_.count(w.name)) {
RAD_ERR("'%s': the container already holds a weight of this name", w.name.c_str());
return RAD_E_INVAL;
}
/* Bytes and encoding are the old entry's; provenance and movement group are the caller's. */
RadFileEntry n = e;
n.name = intern(w.name);
n.quantizer = intern(w.quantizer);
@@ -715,13 +688,13 @@ int64_t RadWriter::add_existing(const Weight& w, const RadFile& old, const RadFi
}
dir_.push_back(n);
dir_abs_.push_back(1);
names_.insert(w.name);
return (int64_t)dir_.size() - 1;
}
uint32_t RadWriter::intern_encoding(const RadEncoding& e) {
/* Zeroed before it is copied in, so the padding and the unused plane slots of a table row
* are zeros and two converts of one checkpoint compare equal byte for byte -- and compared
* in that form, so stray bytes in a caller's unused slots do not make a second row. */
/* Zero first so padding and unused plane slots are zeros: two converts of one checkpoint are
* byte-identical, and stray bytes in a caller's unused slots do not create a second row. */
RadEncoding c;
std::memset(&c, 0, sizeof c);
std::memcpy(c.scheme, e.scheme, sizeof c.scheme);
@@ -766,9 +739,8 @@ void RadWriter::add_profile(int32_t layer, int32_t expert, float share) {
prof_.push_back(p);
}
/* Movement-unit bookkeeping. A unit is one (layer, expert) pair for a routed expert -- its
* gate/up/down are adjacent because the unit of transfer is an expert, not a tensor -- and one
* weight for everything else. */
/* Movement-unit bookkeeping. A unit is a (layer, expert) pair for a routed expert (its gate/up/down
* slots adjacent, since an expert is the unit of transfer) and one weight for everything else. */
int RadWriter::check_unit_invariant(const Weight& w, uint64_t off, uint64_t bytes) {
const bool new_unit = (w.layer != cur_layer_ || w.expert != cur_expert_);
if (new_unit) { cur_layer_ = w.layer; cur_expert_ = w.expert; }
@@ -823,13 +795,16 @@ int RadWriter::check_unit_invariant(const Weight& w, uint64_t off, uint64_t byte
w.name.c_str(), w.layer, w.expert, w.slot, grp_slot_seen_ - 1);
return RAD_E_INVAL;
}
/* The reader addresses at most this many slots an expert (RadFile::ExpertGroup::slot_off). */
constexpr int32_t kMaxSlots = (int32_t)(sizeof RadFile::ExpertGroup{}.slot_off /
sizeof RadFile::ExpertGroup{}.slot_off[0]);
if (w.slot >= kMaxSlots) {
RAD_ERR("'%s': layer %d expert %d has more than %d slots, which the directory cannot "
"address", w.name.c_str(), w.layer, w.expert, kMaxSlots);
return RAD_E_INVAL;
}
/* Expert 0 defines the shape of a unit; every later expert must match it slot for slot. The
* offset arithmetic above cannot catch a size mismatch on its own: an oversized expert still
* lands at the right base, and only the NEXT one is displaced -- so an oversized LAST expert
* passes every offset check and leaves a container whose base + id*stride runs off the end of
* the group. Refusing here means the writer stops while the operator still has the checkpoint
* open and can fix the manifest. */
/* Every later expert must match expert 0 slot for slot (see grp_slot_bytes_ in radfile.h). */
if (grp_n_expert_ == 1) {
grp_slot_bytes_.push_back(bytes);
} else if ((size_t)w.slot < grp_slot_bytes_.size() && grp_slot_bytes_[(size_t)w.slot] != bytes) {
@@ -847,6 +822,10 @@ int RadWriter::check_unit_invariant(const Weight& w, uint64_t off, uint64_t byte
int64_t RadWriter::add_weight(const Weight& w) {
if (!began_ || sealed_) return RAD_E_STATE;
if (w.name.empty() || w.rank == 0 || w.rank > RAD_MAX_RANK) return RAD_E_INVAL;
if (names_.count(w.name)) {
RAD_ERR("'%s': the container already holds a weight of this name", w.name.c_str());
return RAD_E_INVAL;
}
if (!rad_enc_valid(&w.enc)) {
RAD_ERR("'%s': its encoding is not one the core can read", w.name.c_str());
return RAD_E_INVAL;
@@ -864,10 +843,9 @@ int64_t RadWriter::add_weight(const Weight& w) {
return RAD_E_INVAL;
}
/* Every entry starts on a movement-unit boundary. That costs up to 4 KiB of padding per
* matrix -- tens of megabytes on a large MoE -- and buys a transfer that never straddles a
* page needlessly. Its planes follow at RAD_ALIGN_SUB, a cacheline on the architectures in
* scope: SoA, so a code plane stays dense and a scale plane is its own stream. */
/* Every entry starts on a movement-unit boundary (up to 4 KiB padding per matrix, tens of MB on
* a large MoE) so a transfer never straddles a page needlessly. Planes follow at RAD_ALIGN_SUB
* (a cacheline here), structure-of-arrays: codes stay dense and scales are their own stream. */
int64_t rows = 0, cols = 0;
rad_enc_view(w.rank, w.shape, &rows, &cols);
const uint64_t off = (uint64_t)align_up(blob_bytes_, RAD_ALIGN_UNIT);
@@ -913,6 +891,7 @@ int64_t RadWriter::add_weight(const Weight& w) {
dir_.push_back(e);
dir_abs_.push_back(0);
names_.insert(w.name);
return (int64_t)dir_.size() - 1;
}
@@ -958,10 +937,9 @@ int RadWriter::write_plane(int64_t idx, int k, int64_t off, const void* data, in
return RAD_OK;
}
/* EVERY RESERVED BYTE WAS WRITTEN. A plane left short is a hole of zeros the reader cannot tell
* from codes -- a quantiser that returned early, a block loop with an off-by-one -- so the file is
* refused here, naming the weight, rather than written. Counted, not tracked by range: writes that
* overlapped would pass, and no producer here writes a byte twice. */
/* Every reserved byte must have been written; a short plane would be zeros indistinguishable from
* codes. Counted, not range-tracked: overlapping writes would pass, but no producer writes a byte
* twice. */
int RadWriter::check_complete() const {
for (size_t i = 0; i < dir_.size(); ++i) {
if (dir_abs_[i]) continue;
@@ -985,8 +963,7 @@ int RadWriter::set_vocab_section(const void* blob, int64_t bytes) {
(long long)bytes, sizeof(RadVocabHeader));
return RAD_E_INVAL;
}
/* Sanity, here rather than at open: the reader would refuse this file, and a converter that
* writes a file its own reader refuses has wasted an hour of somebody's time. */
/* Check now what the reader would refuse at open, before a long convert is wasted. */
const RadVocabHeader* h = (const RadVocabHeader*)blob;
auto fits = [&](uint64_t off, uint64_t n) {
return n == 0 || (off <= (uint64_t)bytes && n <= (uint64_t)bytes - off);
@@ -1114,9 +1091,8 @@ int RadWriter::finish() {
if (sealed_) h = hdr_;
else layout(&h);
/* Blob-relative to absolute. Both tables were built with offsets into the spill file, which
* is exactly the blob, so one add each. data_off is 2 MiB-aligned and every entry was already
* 4 KiB-aligned inside the blob, so the alignments survive the shift. */
/* Blob-relative to absolute: one add each. data_off is 2 MiB-aligned and entries are 4 KiB-
* aligned within the blob, so alignment is preserved. */
for (auto& e : dir_) e.offset += h.data_off;
for (auto& p : planes_) p.offset += h.data_off;
if (have_vocab_) {
@@ -1153,42 +1129,36 @@ int RadWriter::finish() {
at = (int64_t)h.data_off;
}
/* SEALED, THE BLOB IS ALREADY HERE: every plane went to its final offset. The length is set
* explicitly because the blob's tail may be alignment the planes never wrote. */
/* Sealed: every plane is already at its final offset. Set the length explicitly, since the
* blob's tail may be unwritten alignment. A failure of either leaves a file that is short or
* not durable, so it fails the write rather than report a container that is not there. */
if (sealed_) {
if (::ftruncate(fd_out_, (off_t)h.file_bytes) != 0 || ::fsync(fd_out_) != 0)
if (::ftruncate(fd_out_, (off_t)h.file_bytes) != 0 || ::fsync(fd_out_) != 0) {
RAD_ERR("%s: %s", path_.c_str(), std::strerror(errno));
abort();
return RAD_E_IO;
}
::close(fd_out_); fd_out_ = -1;
::close(fd_spill_); fd_spill_ = -1;
began_ = false;
return RAD_OK;
}
/* Splice the spill in. copy_file_range stays in the kernel and reflinks on a filesystem that
* can, which on btrfs/xfs makes a 1.5 GB blob nearly free; the read/write fallback is there
* because tmpfs and older kernels cannot. The spill is exactly the blob's length: every
* reserved byte was written, and the last of them is the last plane's last byte. */
/* Splice the spill in with copy_file_range (in-kernel, reflinked on btrfs/xfs), falling back
* to read/write where unsupported (tmpfs, older kernels). The spill is exactly the blob's
* length. */
if (::lseek(fd_spill_, 0, SEEK_SET) < 0) {
RAD_ERR("%s: %s", spill_path_.c_str(), std::strerror(errno)); abort(); return RAD_E_IO;
}
/* ============================== THE SPILL IS FREED AS IT IS COPIED ==============================
*
* A naive splice needs TWICE THE CONTAINER free, because the spill stays whole until the copy
* finishes and is only then unlinked. At container sizes in the hundreds of gigabytes that is
* the difference between a convert that fits on the disk and one that runs for half an hour,
* writes every weight, and then dies on the splice with ENOSPC.
*
* Punching a hole in the spill behind the copy gives the blocks back to the filesystem
* IMMEDIATELY, so the peak is one container plus a grain rather than two containers. ext4,
* xfs and btrfs all support it; where it is not supported fallocate fails and the copy
* proceeds exactly as it would without this. It is not an optimisation of the copy -- the
* bytes still move -- it is a bound on peak disk use. */
/* The spill is freed as it is copied. Otherwise the splice needs twice the container's size
* free (hundreds of GB) until the spill is unlinked. Punching holes behind the copy (ext4, xfs,
* btrfs) returns blocks immediately, bounding peak disk use to one container plus a grain;
* where unsupported, fallocate fails and the copy proceeds unchanged. */
int64_t left = blob_bytes_;
int64_t done = 0, punched = 0;
auto punch_behind = [&](bool final_grain) {
#if defined(__linux__) && defined(FALLOC_FL_PUNCH_HOLE)
/* 256 MiB at a time: enough that the syscall is noise against the copy, small enough that
* the residual peak overhead is negligible beside the container itself. */
/* 256 MiB grains: the syscall is negligible against the copy, as is the residual peak. */
const int64_t grain = 256ll << 20;
const int64_t len = done - punched;
if (len <= 0 || (!final_grain && len < grain)) return;
@@ -1201,8 +1171,8 @@ int RadWriter::finish() {
#if defined(__linux__) && defined(SYS_copy_file_range)
while (left > 0) {
/* AN EXPLICIT INPUT OFFSET, so the punch below knows where the copy has reached and the
* read() fallback can pick up from the same place. */
/* An explicit input offset, so the punch and the read() fallback know where the copy
* reached. */
loff_t oi = (loff_t)done;
ssize_t n = (ssize_t)syscall(SYS_copy_file_range, fd_spill_, &oi,
fd_out_, (loff_t*)nullptr, (size_t)left, 0u);
@@ -1232,7 +1202,11 @@ int RadWriter::finish() {
}
punch_behind(true);
if (::fsync(fd_out_) != 0) { RAD_ERR("%s: fsync: %s", path_.c_str(), std::strerror(errno)); }
if (::fsync(fd_out_) != 0) {
RAD_ERR("%s: fsync: %s", path_.c_str(), std::strerror(errno));
abort();
return RAD_E_IO;
}
::close(fd_out_); fd_out_ = -1;
::close(fd_spill_); fd_spill_ = -1;
::unlink(spill_path_.c_str());
@@ -1240,8 +1214,8 @@ int RadWriter::finish() {
return RAD_OK;
}
/* The new weights are already past the old end (write_plane() put them there); what is left is the
* tables and, last, the header. */
/* The new weights are already past the old end (write_plane()); write the tables, then the
* header last. */
int RadWriter::finish_append() {
blob_bytes_ = align_up(blob_bytes_, RAD_ALIGN_UNIT);
const int64_t blob_end = append_base_ + blob_bytes_;
@@ -1278,8 +1252,8 @@ int RadWriter::finish_append() {
h.prof_off = (uint64_t)place8((int64_t)(prof_.size() * sizeof(RadFileProfile)));
h.prof_count = prof_.size();
/* The blob is the old one and the new weights after it: one span, still pool-aligned at its
* start, with the old tail's padding inside it. */
/* The blob spans the old blob and the new weights, still pool-aligned at its start, with the
* old tail's padding inside. */
h.data_off = old_data_off_;
h.data_bytes = (uint64_t)(blob_end - (int64_t)old_data_off_);
h.file_bytes = (uint64_t)off;
@@ -1311,12 +1285,12 @@ int RadWriter::finish_append() {
if (have_vocab_) put(vocab_blob_.data(), (int64_t)vocab_blob_.size(), h.vocab_off);
put(prof_.data(), (int64_t)(prof_.size() * sizeof(RadFileProfile)), h.prof_off);
if (st >= 0 && ::ftruncate(fd_out_, (off_t)off) != 0) st = RAD_E_IO;
/* Everything the new header names is durable before the header names it. */
/* Make everything durable before the new header names it. */
if (st >= 0 && ::fsync(fd_out_) != 0) st = RAD_E_IO;
if (st < 0) { RAD_ERR("%s: %s", path_.c_str(), std::strerror(errno)); abort(); return st; }
/* The way back: the old header and the old length. The old tables are still where that
* header points, so writing it back and truncating restores the file byte for byte. */
/* The way back: the old header and length. The old tables are still where that header
* points, so restoring it and truncating recovers the file byte for byte. */
{
const std::string bak = path_ + ".pre-append";
const std::string tmp = bak + ".tmp";
+77 -128
View File
@@ -1,23 +1,17 @@
/* radfile.h -- the .rad reader and writer.
/* radfile.h -- the .rad reader and writer, implementing exactly the format frozen in
* abi/rad_format.h. The writer and reader live together so they cannot disagree.
*
* The container is frozen in abi/rad_format.h; this file implements exactly it and adds
* nothing to the on-disk shape. What lives here is the two halves that must never disagree: the
* writer that produces a layout and the reader that maps it.
*
* The reader is an mmap and an index build, and then it is done. Every invariant a reader relies
* on is CHECKED AT OPEN rather than asserted at use:
* The reader mmaps and builds an index. Every invariant is checked at open, not at use:
*
* - every offset and count is bounds-checked against the mapped length, so a truncated or
* corrupt file is RAD_E_FORMAT with a message and not a SIGSEGV three components later;
* - every rad_stroff lands inside a string blob whose last byte is NUL, so str() is a plain
* pointer and never a scan;
* - the expert directory's fixed stride is RE-DERIVED and verified, so
* `base + id * stride` on the critical path is arithmetic somebody already proved.
* corrupt file is RAD_E_FORMAT with a message, not a later SIGSEGV;
* - every rad_stroff lands inside a NUL-terminated string blob, so str() is a plain pointer;
* - the expert directory's fixed stride is re-derived and verified, so `base + id * stride` on
* the critical path is safe.
*
* The cost of the last one, stated plainly: a container whose experts within a layer are not all
* the same shape and format is REFUSED, not read slowly. Addressing by arithmetic is the format's
* reason to exist; a file that cannot be addressed that way is not a .rad, and reading it with a
* table walk would silently give back the property the whole design was paying for.
* Consequently a container whose experts within a layer differ in shape or format is refused:
* addressing by arithmetic is the format's purpose. So is one that names a weight twice, since
* find() could return only one of them.
*/
#pragma once
#include "../rad_internal.h"
@@ -26,31 +20,24 @@
#include <string>
#include <string_view>
#include <unordered_map>
#include <unordered_set>
#include <vector>
namespace rad {
/* ================================================================== vocab */
/* The MUTABLE side of the vocab -- VocabBuild, the tokenizer.json interpreter and the serialiser
* that turns one into a RadVocabHeader -- belongs to core/text, because interpreting a declared
* normaliser chain is that component's whole job (spec §12). What belongs here is the container's
* half of the contract, and it is two things:
/* The vocab's mutable side (VocabBuild, the tokenizer.json interpreter, the serialiser) belongs to
* core/text (spec §12). The container's half of the contract:
*
* RadWriter::intern_string() so the vocab section's strings go into the .rad's ONE string
* blob rather than a second one nobody else can read;
* RadWriter::set_vocab_section() so the serialised bytes are placed and rebased by the writer
* that owns every other offset in the file.
* RadWriter::intern_string() the vocab's strings go into the .rad's single string blob;
* RadWriter::set_vocab_section() the writer places and rebases the serialised bytes like every
* other offset.
*
* core/text's `StringSink` is the interface that joins them, and rad-convert supplies the two-line
* adapter. Keeping VocabBuild out of this header is what stops two definitions of it existing.
* core/text's `StringSink` joins them; rad-convert supplies the adapter.
*
* The read-back view below is the container's own: pointers into the mapping, already
* bounds-checked at open. core/text's vocab_deserialize() copies out of it. */
/* NOT named VocabView: core/sample/vocab_view.h declares an ABSTRACT CLASS of that name in this
* same namespace, and two definitions of one name are an ODR violation the moment one translation
* unit includes both -- which core/engine.cpp does, because it loads the container and drives the
* sampler. This one is the container's read-back view of the vocab SECTION; the other is what the
* sampler needs to know about a vocabulary. Different things, deliberately different names. */
* The read-back view below holds pointers into the mapping, bounds-checked at open;
* vocab_deserialize() copies out of it. Not named VocabView, which core/sample/vocab_view.h
* declares in this namespace (an ODR clash in any unit including both). */
struct VocabSection {
const RadVocabHeader* h = nullptr;
const rad_stroff* tok_text = nullptr; /* [n_tokens] */
@@ -69,8 +56,7 @@ public:
RadFile(const RadFile&) = delete;
RadFile& operator=(const RadFile&) = delete;
/* mmap, validate, index. Returns RAD_OK, or RAD_E_IO / RAD_E_FORMAT with the reason logged at
* Error naming the field that failed -- a bad container is diagnosed here or nowhere. */
/* mmap, validate, index. RAD_OK, or RAD_E_IO / RAD_E_FORMAT with the failing field logged. */
int open(const char* path);
void close();
bool is_open() const { return base_ != nullptr; }
@@ -80,44 +66,22 @@ public:
const uint8_t* base() const { return base_; }
int64_t size() const { return size_; }
/* Drop the blob from the page cache and from this process's page tables.
*
* A container larger than RAM cannot be traversed twice without this. When the weight load
* walks the whole file once per rank, the second walk meets a page cache that is entirely the
* first walk's pages: nothing it needs is resident, and the readahead it triggers evicts the
* pages it is about to want. The load then makes no forward progress while the device sits
* idle behind a stream of NVMe reads that are immediately thrown away.
*
* Only the blob: the tables are small, read constantly, and wanted resident for the life of
* the process. Advisory in both directions -- if the kernel declines, the load is exactly as
* it was. */
/* Drop the blob from the page cache and this process's page tables, so a container larger
* than RAM does not leave the cache full of pages nothing will read. Only the blob: the tables
* are small and read constantly. Advisory; the kernel may decline. */
void drop_blob_cache() const;
/* Drop one range of the blob behind a cursor that will not come back for it.
*
* The weight load reads the container once, front to back, and nothing re-reads a window it
* has finished with -- but buffered reads leave every one of those bytes in the page cache,
* and on a container larger than RAM that turns into reclaim pressure the read itself then
* waits on, so the sweep rate decays as it advances. Dropping each window as it is consumed
* holds the rate flat.
*
* THE PRECONDITION IS ONE CURSOR. Drop-behind is wrong with several cursors over one file,
* because what one discards is what another is about to want -- the same reason a sequential
* access hint is worse than silence in that arrangement. This call is correct only for a
* single cursor moving in one direction with no revisits, where the pages are genuinely
* dead. */
/* Drop one range of the blob behind a single forward cursor. A buffered front-to-back read of
* a container larger than RAM otherwise builds reclaim pressure that slows the read itself.
* Correct only for one cursor moving in one direction with no revisits; with several, one
* would drop what another is about to read. */
void drop_range(int64_t off, int64_t bytes) const;
/* Read `bytes` at `off` into `dst` with pread, bypassing the mapping entirely.
*
* The load phase wants this and not the mapping. An async copy whose source is pageable
* memory is staged by the HIP runtime through its own pinned buffer, and that path degrades
* without bound as a load proceeds: even with the source pages already resident, a single
* small hipMemcpyAsync can block for seconds. Reading into a pinned buffer the loader owns
* makes the device copy a real DMA from pinned memory, which has none of that behaviour.
*
* Returns RAD_OK, or RAD_E_IO with the reason logged. Short reads are retried; EINTR is not
* an error. */
/* pread `bytes` at `off` into `dst`, bypassing the mapping. For loads: an async copy from
* pageable memory goes through the HIP runtime's own staging, which degrades as a load
* proceeds (a small hipMemcpyAsync can block for seconds even with resident pages); reading
* into the loader's pinned buffer makes the copy a real DMA. RAD_OK, or RAD_E_IO with the
* reason logged; short reads and EINTR are retried. */
int read_at(void* dst, int64_t bytes, int64_t off) const;
/* Strings. Offset 0 is the empty string; every offset was bounds-checked at open. */
@@ -138,8 +102,8 @@ public:
const RadFileEntry* find(std::string_view name) const;
const uint8_t* data(const RadFileEntry& e) const { return base_ + e.offset; }
/* An entry's encoding and its planes, in the encoding's order. Every plane was checked at open
* to be exactly the size its encoding and the entry's shape say. */
/* An entry's encoding and its planes in encoding order; each plane's size was checked at
* open. */
const RadEncoding& encoding(const RadFileEntry& e) const { return encs_[e.enc]; }
const RadFilePlane& plane(const RadFileEntry& e, int k) const {
return planes_[e.plane_first + (uint64_t)k];
@@ -149,9 +113,8 @@ public:
const RadEncoding& encoding_at(int64_t i) const { return encs_[i]; }
/* ------------------------------------------------------------ fixed-stride addressing */
/* One layer's experts. All of them share a shape and a format, which is what makes
* addr = base + id * stride
* O(1) arithmetic with no table walk on the critical path (spec §4.1). Verified at open. */
/* One layer's experts, all of one shape and format, so addr = base + id * stride with no table
* walk on the critical path (spec §4.2). Verified at open. */
struct ExpertGroup {
int32_t layer = -1;
int32_t n_expert = 0;
@@ -160,7 +123,7 @@ public:
uint64_t base = 0; /* file offset of expert 0's first byte */
uint64_t stride = 0; /* bytes between consecutive experts, aligned */
uint64_t unit_bytes = 0; /* payload of one expert: every slot's every plane */
/* Per-slot displacement from an expert's base. Fixed across experts by construction. */
/* Per-slot offset from an expert's base, the same for every expert. */
uint64_t slot_off[8] = {0};
uint64_t slot_bytes[8] = {0};
};
@@ -168,8 +131,7 @@ public:
int64_t group_count() const { return (int64_t)groups_.size(); }
const ExpertGroup* group_for_layer(int32_t layer) const;
/* The whole point of the format, in one line each. No bounds check on the hot path: the
* caller has the group and therefore has n_expert and n_slot. */
/* No bounds check on the hot path: the caller has the group's n_expert and n_slot. */
const uint8_t* expert_ptr(const ExpertGroup& g, int32_t expert, int32_t slot) const {
return base_ + g.base + (uint64_t)expert * g.stride + g.slot_off[slot];
}
@@ -205,21 +167,18 @@ private:
};
/* ================================================================== writer */
/* Streaming, because the blob is the model: a 100 GB checkpoint cannot be staged in RAM to be
* re-sorted at the end. The tables (strings, directory, planes, encodings, vocab, profile) ARE held
* in memory -- a 512-expert 48-layer model is ~50k directory rows, which is megabytes.
/* Streaming writer: the blob is never held in RAM (a checkpoint may be 100 GB). The tables
* (strings, directory, planes, encodings, vocab, profile) are in memory; ~50k directory rows for a
* 512-expert 48-layer model is megabytes.
*
* A WEIGHT IS RESERVED, THEN WRITTEN. add_weight() places the entry and every plane of its
* encoding in the blob and returns its index; write_plane() fills any part of any plane, in any
* order, at its position. That is what a quantiser needs -- it produces a block of rows of EVERY
* plane at once -- and what a 51 GB table needs, whose codes are produced a block at a time
* without the whole ever existing anywhere. finish() refuses a plane left short.
* A weight is reserved, then written: add_weight() places the entry and every plane and returns
* its index; write_plane() fills any part of any plane in any order. A quantiser produces rows of
* every plane at once, and a 51 GB table is produced block by block. finish() refuses a plane left
* short.
*
* The consequence, and it is a real constraint on callers: WEIGHTS MUST BE ADDED IN MOVEMENT-UNIT
* ORDER. An expert's slots must be added consecutively, and a layer's experts must be added
* consecutively and identically shaped. The writer verifies it and refuses with RAD_E_INVAL naming
* the offending pair, rather than producing a file whose stride is a lie. rad-convert sorts its
* manifest before it starts writing; that sort is over the manifest, not over the bytes.
* Callers must add weights in movement-unit order: an expert's slots consecutively, and a layer's
* experts consecutively with identical shapes. The writer verifies this and refuses with
* RAD_E_INVAL naming the offending pair. rad-convert sorts its manifest before writing.
*/
class RadWriter {
public:
@@ -252,23 +211,16 @@ public:
int32_t layer = -1, expert = -1, slot = 0;
};
/* APPEND IN PLACE: extend the container `old` (opened at `path`) with new weights, without
* copying the ones it already holds.
/* Append in place: extend container `old` (opened at `path`) with new weights without copying
* the existing ones. Offsets are absolute, so new bytes go past the end, followed by fresh
* tables naming both the old weights (at their offsets, via add_existing()) and the new; the
* header is rewritten last. Until then the file is its old self with an unreachable tail;
* afterwards the old tables are dead bytes. finish() leaves `<path>.pre-append` (the old
* header and length) to restore it.
*
* A container is a header, its tables, and the blob, and every offset in them is absolute, so
* nothing forces a new weight to live anywhere but past the end. The new weights' bytes are
* written there, then a fresh set of tables that names both the old weights -- at the offsets
* they already have, through add_existing() -- and the new ones, and the header is rewritten
* last. Until that one write the file is its old self with a tail the old header does not
* reach; after it, the old tables are dead bytes in front of the blob. finish() also leaves
* `<path>.pre-append`: the old header and length, which is all it takes to put the file back.
*
* It is what makes adding a component to a 120 GB container a gigabyte of I/O instead of a
* 120 GB copy the disk may not have room for. A new EXPERT weight is refused: a layer's experts
* are written consecutively at a fixed stride, and an appended one cannot join its layer.
*
* The caller must be the file's only user. A process that has it mapped reads the header
* through its mapping, and a header that changes under it names tables it never validated. */
* New expert weights are refused: a layer's experts sit at a fixed stride and cannot be
* extended. The caller must be the file's only user, since a process mapping it would see the
* header change under it. */
int begin_append(const char* path, const RadFile& old);
/* A weight `old` already holds, recorded at the offsets it has there. Its encoding and planes
* are the old entry's; its name, provenance and movement group are `w`'s. */
@@ -276,7 +228,7 @@ public:
/* Reserve the weight and every plane of its encoding. Returns the directory index, or a
* negative status: an invalid encoding, a shape it cannot cover, a movement-unit order the
* stride cannot hold. */
* stride cannot hold, a name the container already holds. */
int64_t add_weight(const Weight& w);
/* Reserve and write in one call: `planes[k]` is plane k's whole bytes. */
int64_t add_weight(const Weight& w, const void* const* planes);
@@ -285,26 +237,23 @@ public:
int write_plane(int64_t idx, int k, int64_t off, const void* data, int64_t bytes);
int64_t plane_bytes(int64_t idx, int k) const;
/* Intern into the .rad's single string blob. Public because the vocab section's writer lives
* in core/text and has to put its token text somewhere the reader can find it; core/text's
* StringSink is the one-method interface rad-convert adapts onto this. */
/* Intern into the .rad's single string blob. Public for core/text's vocab writer (via
* StringSink). */
rad_stroff intern_string(std::string_view s) { return intern(s); }
/* The serialised vocab section. Its internal offsets must be SECTION-RELATIVE (serialise with
* a section_file_off of 0); finish() rebases them once it knows where the section lands, the
* same way it rebases the directory. */
/* The serialised vocab section. Its internal offsets must be section-relative (serialise with
* section_file_off 0); finish() rebases them, as it does the directory. */
int set_vocab_section(const void* blob, int64_t bytes);
void add_profile(int32_t layer, int32_t expert, float share);
/* FIX THE LAYOUT AND WRITE THE BLOB WHERE IT STAYS. Once every weight, the metadata, the vocab
* section and the profile are in, the tables' sizes -- and so the blob's offset -- are known:
* after seal() a plane write lands in the target itself and finish() writes the tables in
* front of it, with no spill and no 100 GB copy. A table changed after it fails finish(). A
* writer that is not sealed spills the blob and splices it in at finish(). */
/* Fix the layout once every weight, the metadata, the vocab section and the profile are in, so
* the blob's offset is known: afterwards plane writes land in the target directly and
* finish() writes the tables in front, with no spill and no copy. Changing a table afterwards
* fails finish(). An unsealed writer spills the blob and splices it in at finish(). */
int seal();
/* Writes the header and every table, then -- unsealed -- splices the spilled blob in at a
/* Writes the header and every table, then (if unsealed) splices the spilled blob in at a
* 2 MiB boundary. */
int finish();
@@ -326,8 +275,8 @@ private:
RadFileHeader hdr_{}; /* the sealed layout */
/* Append mode (begin_append). New bytes go at `append_base_`, the old length rounded up to a
* pool boundary; an entry recorded by add_existing() is already absolute and is flagged so
* finish() does not rebase it. */
* pool boundary; add_existing() entries are already absolute and flagged so finish() does not
* rebase them. */
int finish_append();
int check_complete() const;
bool append_ = false;
@@ -346,6 +295,8 @@ private:
std::vector<int64_t> written_; /* parallel to planes_ */
std::vector<RadEncoding> encs_;
std::vector<RadFileProfile> prof_;
/* Every weight name added, since a name is looked up and must find one entry. */
std::unordered_set<std::string> names_;
/* The vocab section, assembled in memory and appended verbatim. */
std::vector<uint8_t> vocab_blob_;
@@ -353,21 +304,19 @@ private:
int64_t blob_bytes_ = 0; /* the blob's reserved length */
/* Movement-unit bookkeeping, so the fixed stride is a property the writer PROVES. */
/* Movement-unit bookkeeping, so the writer verifies the fixed stride. */
int32_t cur_layer_ = -2, cur_expert_ = -2;
int32_t grp_layer_ = -2;
int32_t grp_n_slot_ = 0, grp_slot_seen_ = 0, grp_n_expert_ = 0;
uint64_t grp_first_off_ = 0, grp_expert_off_ = 0, grp_stride_ = 0;
/* Expert 0's per-slot payload. ExpertGroup promises slot_off[] and slot_bytes[] are fixed
* across the experts of a layer "by construction", and this is where that is constructed:
* an expert whose slot differs in size is refused at ITS OWN add_weight, not at the next
* one's. The offset check alone cannot see it -- an oversized LAST expert lands at the right
* base and simply overruns past base + n*stride. */
/* Expert 0's per-slot payload, which enforces ExpertGroup's fixed slot_off[]/slot_bytes[]: an
* expert whose slot differs in size is refused at its own add_weight. The offset check alone
* misses an oversized last expert, which starts at the right base and overruns. */
std::vector<uint64_t> grp_slot_bytes_;
};
/* ================================================================== helpers for the tools */
/* "layer 12 / expert 7" and friends, so rad-info and every diagnostic name a unit the same way. */
/* "layer 12 / expert 7" etc., so every diagnostic names a unit the same way. */
std::string rad_unit_name(int32_t layer, int32_t expert);
} /* namespace rad */
+65 -2
View File
@@ -1,8 +1,11 @@
/* recipe.cpp -- see recipe.h. */
#include "recipe.h"
#include "../plugin/registry.h"
#include <algorithm>
#include <cctype>
#include <cerrno>
#include <cmath>
#include <cstdlib>
namespace rad {
@@ -34,8 +37,8 @@ bool recipe_glob(const char* p, const char* n) {
namespace {
/* `$NAME` and `${NAME}` from the environment. An unset name is refused: a recipe that silently
* quantises against an empty calibration directory is a recipe that did something else. */
/* Expand `$NAME` and `${NAME}` from the environment. An unset name is refused rather than
* expanded to empty (e.g. an empty calibration directory). */
bool expand(const std::string& in, std::string* out, std::string* why) {
out->clear();
for (size_t i = 0; i < in.size(); ++i) {
@@ -159,6 +162,66 @@ const RecipeRule* Recipe::match(const std::string& name) const {
return nullptr;
}
int CompiledRule::build(const RecipeRule& r, const Registry& reg, std::string* why) {
rule = &r;
const Registry::QuantRow* row = reg.quantizer(r.quantizer);
if (!row || !row->info) {
std::string have;
for (const auto& qr : reg.quantizers())
if (qr.info) have += std::string(have.empty() ? "" : ", ") + qr.info->name;
*why = r.origin + ": no quantiser '" + r.quantizer + "' is loaded (" +
(have.empty() ? std::string("none are -- is $RADIANCE_HOME/quantizers there?")
: "loaded: " + have) + ")";
return RAD_E_NOTFOUND;
}
q = row->info;
keys.reserve(r.options.size());
vals.reserve(r.options.size());
for (const auto& [k, v] : r.options) {
const RadQuantOption* opt = nullptr;
for (int i = 0; i < q->n_options; ++i)
if (k == q->options[i].key) opt = &q->options[i];
if (!opt) {
std::string takes;
for (int i = 0; i < q->n_options; ++i)
takes += std::string(i ? ", " : "") + q->options[i].key;
*why = r.origin + ": " + q->name + " takes no option '" + k + "' (it takes " + takes +
")";
return RAD_E_INVAL;
}
char* end = nullptr;
errno = 0;
if (opt->type == RAD_P_INT) {
const long long x = std::strtoll(v.c_str(), &end, 10);
if (v.empty() || !end || *end || errno == ERANGE) {
*why = r.origin + ": " + k + "=" + v + " is not a whole number";
return RAD_E_INVAL;
}
keys.push_back(k);
vals.push_back(v);
params.push_back(RAD_INT(nullptr, x));
} else if (opt->type == RAD_P_F64) {
const double x = std::strtod(v.c_str(), &end);
if (v.empty() || !end || *end || errno == ERANGE || !std::isfinite(x)) {
*why = r.origin + ": " + k + "=" + v + " is not a number";
return RAD_E_INVAL;
}
keys.push_back(k);
vals.push_back(v);
params.push_back(RAD_F64(nullptr, x));
} else {
keys.push_back(k);
vals.push_back(v);
params.push_back(RAD_STR(nullptr, nullptr));
}
}
for (size_t i = 0; i < params.size(); ++i) {
params[i].key = keys[i].c_str();
if (params[i].kind == RAD_P_STR) params[i].sval = vals[i].c_str();
}
return RAD_OK;
}
std::string Recipe::text() const {
std::string s;
for (const RecipeRule& r : rules_) {
+34 -9
View File
@@ -1,18 +1,18 @@
/* recipe.h -- which quantiser makes which weight, for rad-convert (spec §4.4).
*
* A recipe is ordered rules from a logical weight name to a quantiser and its options. The first
* rule whose pattern matches a weight decides it; a weight no rule matches keeps the checkpoint's
* encoding. Two spellings, one rule each:
* A recipe is ordered rules from a logical weight name to a quantiser and options; the first match
* decides, and an unmatched weight keeps the checkpoint's encoding. Two spellings:
*
* in a file PATTERN QUANTISER key=value key=value ... # a comment
* on the command PATTERN=QUANTISER:key=value,key=value
*
* A pattern is a glob over the whole name: `*` is any run of characters (dots included), `?` is
* one. `$NAME` or `${NAME}` in an option is the environment's, expanded when the rule is read, so
* one recipe serves every machine and the container records what it was actually given.
* A pattern is a glob over the whole name: `*` matches any run (dots included), `?` one
* character. `$NAME` or `${NAME}` in an option is expanded from the environment when the rule is
* read, so the container records the actual values.
*/
#pragma once
#include "../rad_internal.h"
#include "rad_quant.h"
#include <string>
#include <utility>
@@ -20,13 +20,15 @@
namespace rad {
class Registry;
struct RecipeRule {
std::string pattern, quantizer;
std::vector<std::pair<std::string, std::string>> options; /* in the order written */
std::string origin; /* "file:12" or "--quant" */
/* The options as one canonical string, `key=value` comma-separated and sorted by key: what a
* container entry records and what --reuse compares, however the rule spelled them. */
/* The options as one canonical string (`key=value`, comma-separated, sorted by key), as a
* container entry records and --reuse compares them. */
std::string options_text() const;
};
@@ -45,11 +47,34 @@ public:
const std::vector<RecipeRule>& rules() const { return rules_; }
bool empty() const { return rules_.empty(); }
/* Every rule in the file spelling, one a line, options expanded: what the container records. */
/* Every rule in the file spelling, one per line, options expanded, as the container records. */
std::string text() const;
private:
std::vector<RecipeRule> rules_;
};
/* A rule with its quantiser resolved and its options typed by the quantiser's own option table,
* so a misspelt key or a value of the wrong type is refused before declare. Integers are decimal
* (the container records the text, and --reuse compares it, so `010` must mean what it reads as);
* an empty value or one that is not finite is refused.
*
* The RadParam strings point into `keys` and `vals`, so a compiled rule is built in place and never
* copied or moved. */
struct CompiledRule {
const RecipeRule* rule = nullptr;
const RadQuantizerInfo* q = nullptr;
std::vector<std::string> keys, vals;
std::vector<RadParam> params;
CompiledRule() = default;
CompiledRule(const CompiledRule&) = delete;
CompiledRule& operator=(const CompiledRule&) = delete;
/* RAD_OK; RAD_E_NOTFOUND when no loaded quantiser has the rule's name (the message lists the
* ones that are); RAD_E_INVAL for an option the quantiser does not take or a value its type
* refuses. The reason, with the rule's origin, is in *why. */
int build(const RecipeRule& r, const Registry& reg, std::string* why);
};
} /* namespace rad */
+26 -30
View File
@@ -1,19 +1,17 @@
/* --rope-scaling, over a container's free-form metadata.
/* rope_override.h -- --rope-scaling, applied to a container's free-form metadata at load.
*
* Static YaRN is read by the architecture (arch/common/rad_arch.h, yarn_from) out of the model's
* own keys: `text_config.rope_parameters.`, `rope_parameters.`, `text_config.rope_scaling.`,
* `rope_scaling.`, in that order, the FIRST of them that names a rotary type being the one that
* counts; a DFlash2 drafter reads `draft.rope_parameters.` / `draft.rope_scaling.` on its own. A
* container converted without YaRN therefore needs a reconvert to get it -- or these keys rewritten
* when it is loaded, which is all this does. The architecture then resolves the result exactly as
* it would a converted container, so there is one reader and one set of checks.
* The architecture reads static YaRN (arch/common/rad_arch.h, yarn_from) from the first of
* `text_config.rope_parameters.`, `rope_parameters.`, `text_config.rope_scaling.`, `rope_scaling.`
* that names a rotary type; a DFlash2 drafter reads `draft.rope_parameters.` /
* `draft.rope_scaling.`. These functions rewrite those keys so a container gains YaRN without
* reconversion, and the architecture's one reader and checks apply.
*
* The rewrite goes into the object the reader would take, not beside it. A Qwen3.8 container says
* `text_config.rope_parameters.rope_type = default`; a YaRN written under `rope_parameters.` would
* sit behind that and never be read.
* The rewrite targets the object the reader takes: a Qwen3.8 container says
* `text_config.rope_parameters.rope_type = default`, so YaRN under `rope_parameters.` would be
* ignored.
*
* Pure functions over two parallel string vectors, so they are tested without an engine
* (tests/yarn_test.cpp holds them to yarn_from). */
* Pure functions over parallel string vectors, tested without an engine (tests/yarn_test.cpp
* checks them against yarn_from). */
#pragma once
#include <algorithm>
@@ -32,8 +30,7 @@ struct RopeSpec {
int64_t orig = 0; /* 0: the container's own trained length */
};
/* "yarn:FACTOR[:ORIG]" with FACTOR > 1 and ORIG > 0, or "none"; empty is Keep. False for anything
* else, so a typo is refused where it was typed. */
/* "yarn:FACTOR[:ORIG]" with FACTOR > 1 and ORIG > 0, or "none"; empty is Keep. False otherwise. */
inline bool rope_spec_parse(const char* s, RopeSpec* out) {
RopeSpec r;
if (!s || !*s) { *out = r; return true; }
@@ -88,7 +85,7 @@ struct RopeKeys {
}
};
/* The reader's order -- yarn_from's, kept in step with it. */
/* The reader's search order; must match yarn_from's. */
inline std::vector<std::string> rope_homes(const char* group) {
if (!*group)
return { "text_config.rope_parameters.", "rope_parameters.", "text_config.rope_scaling.",
@@ -96,8 +93,8 @@ inline std::vector<std::string> rope_homes(const char* group) {
return { std::string(group) + "rope_parameters.", std::string(group) + "rope_scaling." };
}
/* The object the reader takes and the key that names its type, or empty strings when no object
* names one (the model's rotary is then the default). */
/* The object the reader takes and the key naming its type; empty when none names one (the default
* rotary). */
inline void rope_authoritative(const RopeKeys& kv, const char* group, std::string* home,
std::string* type_key) {
home->clear();
@@ -127,9 +124,9 @@ inline RopeResolved rope_resolve(std::vector<std::string>& k, std::vector<std::s
return r;
}
/* Apply SPEC to one rotary group ("" the target, "draft." a DFlash2 drafter). `trained` is the
* group's own trained length, the default ORIG. Returns false, with *why set, when the group's
* rotary is one this flag does not stack YaRN over (linear position interpolation, say). */
/* Apply `spec` to one rotary group ("" the target, "draft." a DFlash2 drafter). `trained` is the
* group's trained length, the default ORIG. False, with *why, when the group's rotary type is one
* YaRN is not stacked over (e.g. linear interpolation). */
inline bool rope_override_group(std::vector<std::string>& k, std::vector<std::string>& v,
const RopeSpec& spec, const char* group, int64_t trained,
std::string* why) {
@@ -154,8 +151,8 @@ inline bool rope_override_group(std::vector<std::string>& k, std::vector<std::st
: "rope_parameters.";
tk = home + "rope_type";
}
/* A checkpoint's own YaRN keeps its trained length unless one is given; anything that was
* tied to its old factor goes, so the reader derives it for the new one. */
/* An existing YaRN keeps its trained length unless one is given; keys tied to the old factor
* are erased so the reader derives them for the new one. */
int64_t orig = spec.orig;
if (!orig && type == "yarn")
if (const std::string* o = kv.get(home + "original_max_position_embeddings"))
@@ -176,13 +173,12 @@ inline bool rope_override_group(std::vector<std::string>& k, std::vector<std::st
return true;
}
/* THE ROTARY AS A CACHED KEY DEPENDS ON IT: every key with a path component naming `rope` or
* `rotary` -- rope_parameters.*, rope_scaling.*, rope_theta, partial_rotary_factor, their
* text_config. and draft. forms, a GGUF's <arch>.rope.* -- as key=value, sorted, after
* --rope-scaling has been applied. A persisted prefix store is fingerprinted with it: a container
* converted from the same checkpoint with YaRN has the same name and the same shapes, and its
* stock-rotated keys (and QSA block keys) read back under YaRN would be attended to at the wrong
* angles. Key order and unrelated keys do not change it. */
/* The rotary's identity: every key with a path component containing `rope` or `rotary`
* (rope_parameters.*, rope_scaling.*, rope_theta, partial_rotary_factor, their text_config. and
* draft. forms, a GGUF's <arch>.rope.*) as sorted key=value, after --rope-scaling. A persisted
* prefix store is fingerprinted with it, since the same container with YaRN has identical names and
* shapes but cached keys would be at the wrong angles. Key order and unrelated keys do not
* matter. */
inline std::string rope_identity(const std::vector<std::string>& k,
const std::vector<std::string>& v) {
auto names_rotary = [](const std::string& key) {
+16 -27
View File
@@ -1,9 +1,6 @@
/* safetensors.cpp -- the reader, and the small JSON scanner it needs.
*
* The scanner is not a general JSON parser and does not try to be. safetensors headers are one
* flat object of objects with three known keys, so a scanner that understands strings, arrays of
* integers and nested braces is sufficient and is auditable in one sitting. Anything it does not
* understand is an error naming the byte offset, never a guess.
/* safetensors.cpp -- the reader and its small JSON scanner. Not a general JSON parser: the header
* is one flat object of objects with three known keys, so strings, integer arrays and nested braces
* suffice. Anything else is an error naming the byte offset.
*/
#include "safetensors.h"
@@ -33,8 +30,8 @@ struct Scan {
return false;
}
/* A JSON string with the escapes that actually occur in these files. \u is decoded to UTF-8
* because a tensor name is a key we will compare against. */
/* A JSON string with the escapes that occur in these files; \u is decoded to UTF-8 because
* tensor names are compared. */
bool str(std::string* out, const char* base) {
ws();
if (p >= end || *p != '"') return fail("expected a string", base);
@@ -57,14 +54,10 @@ struct Scan {
char hex[5] = { p[0], p[1], p[2], p[3], 0 };
unsigned cp = (unsigned)std::strtoul(hex, nullptr, 16);
p += 4;
/* A SURROGATE PAIR IS ONE CODEPOINT, AND ENCODING THE HALVES SEPARATELY IS
* NOT UTF-8. JSON has no way to write a codepoint above U+FFFF except as a
* \uD800-\uDBFF \uDC00-\uDFFF pair, and emitting three bytes for each half
* produces CESU-8: it round-trips through this reader but compares unequal to
* the same name written directly, which is what a tensor name is compared for.
* The halves are joined here; an unpaired surrogate is left to the default
* three-byte path rather than rejected, because a name is data to be matched
* and not text to be validated. */
/* Join a surrogate pair (\uD800-\uDBFF \uDC00-\uDFFF) into one codepoint;
* encoding the halves separately is CESU-8, which compares unequal to the same
* name in UTF-8. An unpaired surrogate takes the three-byte path rather than
* being rejected: names are matched, not validated. */
if (cp >= 0xD800 && cp < 0xDC00 && end - p >= 6 && p[0] == '\\' &&
p[1] == 'u') {
char lo_hex[5] = { p[2], p[3], p[4], p[5], 0 };
@@ -108,7 +101,7 @@ struct Scan {
return true;
}
/* Skip one value of any type, so an unknown key inside a tensor object is survivable. */
/* Skip one value of any type, so unknown keys in a tensor object are tolerated. */
bool skip(const char* base) {
ws();
if (p >= end) return fail("truncated", base);
@@ -129,7 +122,7 @@ struct Scan {
}
};
/* safetensors names its dtypes; we name ours. The table is the only place the two meet. */
/* safetensors dtype names to RAD dtypes. */
uint32_t st_dtype(const std::string& s) {
if (s == "BF16") return RAD_BF16;
if (s == "F16") return RAD_F16;
@@ -143,8 +136,7 @@ uint32_t st_dtype(const std::string& s) {
if (s == "BOOL") return RAD_BOOL;
if (s == "F8_E4M3") return RAD_F8E4M3;
if (s == "F8_E5M2") return RAD_F8E5M2;
/* F64 and F8_E8M0 have no RAD_ equivalent. Reported by name at use rather than mapped to
* something close, because "close" here is a silently wrong number. */
/* F64 and F8_E8M0 have no RAD_ equivalent; refused by name at use rather than approximated. */
return RAD_DT_INVALID;
}
@@ -274,13 +266,10 @@ int SafeTensorsFile::open(const std::string& path) {
t.bytes = (uint64_t)(off_end - off_begin);
t.data = data_base + t.offset;
/* THE SHAPE HAS TO DESCRIBE THE SPAN. Every reader of a tensor walks it by shape and
* dtype -- numel() elements from `data` -- and not by data_offsets, so a shape that
* claims more than the span reads the next tensor's bytes, or past the mapping into a
* SIGBUS. The extents are bounded before each multiply because they are numbers from
* the file, and a product that wraps can come out equal to the span. An empty shape is a
* scalar, one element. A dtype this reader does not know is not sized here; every
* consumer refuses it by name. */
/* The shape must match the span: readers walk numel() elements from `data`, not
* data_offsets, so an oversized shape reads the next tensor or past the mapping. Extents
* are untrusted, so bound each multiply against wrap. An empty shape is a scalar. Unknown
* dtypes are not sized here; consumers refuse them by name. */
int64_t elems = 1;
bool shape_ok = true;
for (int64_t d : t.shape) if (d < 0) shape_ok = false; else if (d == 0) elems = 0;
+6 -11
View File
@@ -1,13 +1,8 @@
/* safetensors.h -- an 8-byte length, a JSON object, and a blob.
/* safetensors.h -- an 8-byte header length, a JSON object mapping tensor name to {dtype, shape,
* data_offsets}, and raw little-endian bytes. A small fixed-shape parser rather than a dependency,
* since the converter must run wherever a checkpoint lands.
*
* Written rather than depended on. The whole format is a header length, one JSON object mapping
* tensor name to {dtype, shape, data_offsets}, and raw little-endian bytes; the parser below is
* two hundred lines and it does not need to be a general JSON parser, because the document's shape
* is fixed. A dependency here would be a dependency in the converter, which is the one tool that
* has to run on a machine that has just been handed a checkpoint.
*
* mmap, no copy. A 46-shard model is opened one shard at a time, so peak RSS stays bounded
* regardless of model size.
* Shards are mmapped, not copied.
*/
#pragma once
#include "../rad_internal.h"
@@ -59,8 +54,8 @@ private:
std::unordered_map<std::string, size_t> index_;
};
/* model.safetensors.index.json -> { tensor name: shard filename }. A single-file checkpoint has
* no index; the caller falls back to opening model.safetensors directly. */
/* model.safetensors.index.json -> { tensor name: shard filename }. A single-file checkpoint has no
* index; the caller then opens model.safetensors. */
int st_load_index(const std::string& index_path,
std::unordered_map<std::string, std::string>* out);
+21 -23
View File
@@ -16,15 +16,15 @@ int weight_share(const WeightInfo& w, const RadEncoding& enc, uint32_t rank, con
int64_t R = 0, C = 0;
rad_enc_view(rank, shape, &R, &C);
/* THE VIEW THE DECLARATION IS IN: one plane's own extents, or the logical ones for several. A
* shard is cut in it, because that is the space the plugin declared its share and its stacked
* parts in -- a block-fp8 scale plane's parts are 1/128 of its weight's. */
/* The shard is cut in the view the declaration uses: one plane's own extents, or the logical
* ones for several planes. That is where the plugin declared its share and stacked parts; a
* block-fp8 scale plane's parts are 1/128 of its weight's. */
const bool single = w.n_sel == 1;
const bool whole = world <= 1 || w.decl.shard == RAD_SHARD_NONE;
/* A RESHAPE: one whole plane of single elements, a byte or more each, declared under another
* shape of the same count (decl_weight admits it). Its row-major bytes are the same, so the
* entry is seen the way the declaration sees it. A shard of one would be a different cut, and
* a sub-byte row pads, so neither is a reshape. */
/* A reshape: one whole plane of single elements (a byte or more each) declared under another
* shape with the same element count, which decl_weight admits. The row-major bytes are
* identical, so the entry takes the declared shape. A shard would be a different cut and a
* sub-byte row pads, so neither is a reshape. */
if (single && whole) {
const RadEncPlane& p0 = enc.plane[w.sel[0]];
if (p0.kind == RAD_PLANE_TILED && p0.block[0] == 1 && p0.block[1] == 1 &&
@@ -42,13 +42,11 @@ int weight_share(const WeightInfo& w, const RadEncoding& enc, uint32_t rank, con
if (whole) {
view.push_back({ 0, VR, 0, VC });
} else {
/* A sharded weight is a projection matrix in almost every case, and refusing anything
* else is better than guessing which dimension a rank owns -- with TWO exceptions that
* are not guesses. A rank-1 weight sharded by ROW is a contiguous slice of a vector, one
* value per head, and the head count is what the world size divides; in the [1, n] view
* that is a column cut. And a weight whose inner dimensions are all 1 is the matrix of its
* first and last -- a depthwise conv kernel [C, 1, K] is [C, K] -- so its rows are the
* ones the view already has. */
/* A sharded weight must be a matrix; anything else is refused rather than guessing which
* dimension a rank owns, with two exceptions. A rank-1 weight sharded by ROW is a
* contiguous slice of a per-head vector, which is a column cut in the [1, n] view. A
* weight whose inner dimensions are all 1 is the matrix of its first and last (a
* depthwise conv kernel [C, 1, K] is [C, K]). */
uint32_t mat = rank;
for (uint32_t i = 1; i + 1 < rank; ++i)
if (shape[i] == 1) --mat;
@@ -69,14 +67,14 @@ int weight_share(const WeightInfo& w, const RadEncoding& enc, uint32_t rank, con
(long long)c0, (long long)c1, (long long)VC));
view.push_back({ 0, VR, c0, c1 });
} else {
/* CONTIGUOUS WITHIN EACH STACKED PART. The weight may be several projections
* concatenated along dim 0 -- [gate|up], or the delta net's [q|k|v] -- and a rank owns
* a slice of EACH of them, not a contiguous slice of the stack. The parts are THIS
* RANK'S rows, so a part is `world` times as many rows in the entry. */
/* Contiguous within each stacked part. The weight may be several projections
* concatenated along dim 0 ([gate|up], the delta net's [q|k|v]), and a rank owns a
* slice of each, not a contiguous slice of the stack. Declared parts are this rank's
* rows, so a part has `world` times as many rows in the entry. */
const int np = w.decl.n_row_parts > 1 ? w.decl.n_row_parts : 1;
if (w.n_part_spans > 0) {
/* PER-PART SPANS: the plugin stated each stacked part's rows in the container
* and this rank's [lo, hi) of it, so the parts need not be equal. */
/* Per-part spans: the plugin states each stacked part's rows in the container
* and this rank's [lo, hi) of it, so parts may differ in size. */
if (w.n_part_spans != np)
return refuse(fmt("%d per-part spans for %d stacked parts", w.n_part_spans, np));
int64_t sum = 0, soff = 0;
@@ -142,13 +140,13 @@ int weight_share(const WeightInfo& w, const RadEncoding& enc, uint32_t rank, con
if (enc_plane_rect(p, R, C, q.r0, q.r1, q.c0, q.c1, &pq, &m) != RAD_OK)
return refuse(m);
}
/* A plane every slice carries whole -- a table, a per-tensor scale -- is the same
* rectangle for every stacked part, and is taken once. */
/* A plane every slice carries whole (a table, a per-tensor scale) yields the same
* rectangle for every stacked part; take it once. */
if (pq.row0 == last.row0 && pq.rows == last.rows && pq.col0 == last.col0 &&
pq.cols == last.cols)
continue;
last = pq;
/* A share is copied as bytes, so both of its column ends have to land on one. */
/* A share is copied as bytes, so both column ends must fall on a byte boundary. */
if ((pq.col0 * bits) % 8 || ((pq.col0 + pq.cols) * bits % 8 && pq.col0 + pq.cols != pc))
return refuse(fmt("columns [%lld, %lld) of the %s '%s' plane do not fall on whole "
"bytes", (long long)pq.col0, (long long)(pq.col0 + pq.cols),
+8 -8
View File
@@ -1,14 +1,14 @@
/* share.h -- which bytes of a container entry one rank's declaration takes.
*
* A container entry is a logical weight's planes, whole and canonical (rad_format.h). A rank
* declares a VIEW of it (RadWeightDecl::source/planes) and, under tensor parallelism, only its
* share: a ROW shard is rows of every selected plane and a COL shard is columns, each cut on the
* plane's own block boundary and refused where a block would be split (spec §4.3). This is that
* arithmetic, and nothing else -- the loader turns its rectangles into reads.
* A container entry holds a logical weight's planes, whole and canonical (rad_format.h). A rank
* declares a view of it (RadWeightDecl::source/planes) and, under tensor parallelism, only its
* share: a ROW shard takes rows of every selected plane, a COL shard takes columns. Each cut falls
* on the plane's own block boundary and is refused where it would split a block (spec §4.3). This
* is only the arithmetic; the loader turns the rectangles into reads.
*
* Pure, so a test can hold it to the shapes tensor parallelism actually produces: a stacked
* [gate|up] whose every part is split, an uneven span, a block-fp8 scale plane cut at 1/128 of
* its weight's rows, a per-tensor scale every rank carries whole.
* Pure, so tests can cover the shapes tensor parallelism produces: a stacked [gate|up] with every
* part split, an uneven span, a block-fp8 scale plane cut at 1/128 of its weight's rows, and a
* per-tensor scale every rank carries whole.
*/
#pragma once
#include "../rad_core.h"
+3 -3
View File
@@ -19,9 +19,9 @@ int table_copy_fill(const RadFile& file, const uint8_t* src, int64_t n, int64_t
if (!why || !src || !buf || n <= 0) return RAD_E_INVAL;
const int64_t huge = (int64_t)2 << 20;
/* A reader per hardware thread up to sixteen, each reading its own contiguous span in pieces of
* 64 MiB: a drive serves sixteen queued reads at full rate, and the span keeps each reader's
* reads sequential on the file. */
/* One reader per hardware thread up to 16, each reading its own contiguous span in 64 MiB
* pieces: a drive serves 16 queued reads at full rate, and spans keep each reader
* sequential. */
const int nt = (int)std::max(1u, std::min(16u, std::thread::hardware_concurrency()));
const int64_t piece = (int64_t)64 << 20;
const int64_t span = ((n + nt - 1) / nt + huge - 1) & ~(huge - 1);
+13 -16
View File
@@ -1,16 +1,13 @@
/* table_copy.h -- a container table copied into host memory (--ngram-placement ram): locked memory
* for the host gather, made here, or pinned memory a card reads, which the caller allocates and
* table_copy_fill fills. What follows is about the locked copy; the read and the check are both's.
* for the host gather (made here), or pinned memory a card reads (allocated by the caller, filled
* by table_copy_fill). Both share the read and the check.
*
* A COPY IN HUGE PAGES, NOT THE MAPPING LOCKED. Faulting a container's mapping in costs a fault every
* 4 KiB page and leaves every row behind a 4 KiB translation, so a gather of scattered rows walks
* the page tables on nearly every row; an anonymous MADV_HUGEPAGE region covers thousands of rows a
* page. The region is locked as each page is first touched (MLOCK_ONFAULT), so nothing filled is
* swapped out while the rest fills; it is read from the container by parallel positional reads, the
* container's pages dropped behind them so the table is not held twice; and it is checked against
* the mapping before anyone is handed it, because a wrong offset would serve every row from the
* wrong place without an error. A host kernel reads an address no file backs as the memory it is
* (libavx's table_file), so no plugin takes part. */
* The locked copy uses huge pages rather than locking the mapping: the mapping costs a fault per
* 4 KiB page and a TLB walk on nearly every scattered row, while a MADV_HUGEPAGE region covers
* thousands of rows per page. It is locked on first touch (MLOCK_ONFAULT); filled by parallel
* positional reads, dropping the container's pages behind so the table is not held twice; and
* checked against the mapping before use, since a wrong offset would silently serve wrong rows.
* A host kernel reads an address no file backs as plain memory (libavx's table_file). */
#pragma once
#include "radfile.h"
@@ -25,17 +22,17 @@ struct TableCopy {
size_t bytes = 0; /* the mapping's length: the table rounded up to 2 MiB */
};
/* Copies [src, src + n) of `file`'s mapping, which lies at file offset `foff`, into a new locked
* region. RAD_OK with `out` filled, or a refusal with `why` saying what failed and nothing held. */
/* Copy [src, src + n) of `file`'s mapping (file offset `foff`) into a new locked region. RAD_OK with
* `out` filled, or an error with `why` and nothing held. */
int table_copy_make(const RadFile& file, const uint8_t* src, int64_t n, int64_t foff,
TableCopy* out, std::string* why);
/* The read and the check table_copy_make makes, into [dst, dst + n) the caller allocated: pinned
* memory a card reads in place, when a device kernel gathers the table (--ngram-placement ram). */
/* table_copy_make's read and check, into caller-allocated [dst, dst + n): pinned memory a card
* reads in place when a device kernel gathers the table. */
int table_copy_fill(const RadFile& file, const uint8_t* src, int64_t n, int64_t foff,
uint8_t* dst, std::string* why);
/* Unlocks and unmaps it; a copy never made is a no-op. */
/* Unlock and unmap; a no-op for a copy never made. */
void table_copy_free(TableCopy* c);
} /* namespace rad */
+31 -28
View File
@@ -1,11 +1,13 @@
/* tunecache.cpp -- read and write the tuning cache. The format is documented in tunecache.h and
* that comment is the specification; this file must not drift from it.
/* tunecache.cpp -- read and write the tuning cache. tunecache.h's format description is the
* specification.
*/
#include "tunecache.h"
#include <cstdlib>
#include <algorithm>
#include <cerrno>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <ctime>
#include <sys/stat.h>
@@ -15,8 +17,7 @@
namespace rad {
namespace {
/* Whitespace only. See the note at its caller: rad_util.cpp's split_ws also splits on commas,
* which is right for a constraint set and wrong for every line of this file. */
/* Split on spaces and tabs only; split_ws also splits on commas (see the caller). */
std::vector<std::string_view> split_ws_only(std::string_view s) {
std::vector<std::string_view> out;
size_t i = 0;
@@ -49,17 +50,15 @@ std::string TuneCache::now_iso8601() {
}
std::string TuneCache::canon_geometry(const Geometry& g) {
/* Sorted by key so the same shape spells the same however the plugin ordered its params.
* Geometry::str() is for humans and preserves declaration order; this one is a key. */
/* Sorted by key, so the spelling is independent of parameter order (unlike Geometry::str()). */
std::vector<std::string> kv;
const RadParam* p = g.params();
for (int i = 0; i < g.n_params(); ++i) {
if (p[i].kind == RAD_P_STR)
kv.push_back(fmt("%s=%s", p[i].key, p[i].sval ? p[i].sval : ""));
else if (p[i].kind == RAD_P_F64)
/* %.17g so the key round-trips a double exactly. A float parameter is eps or a rope
* theta; two shapes that differ only in eps are the same shape to a tuner, but they
* are still different keys and a lossy spelling would silently merge them. */
/* %.17g round-trips a double exactly, so keys differing only in eps or rope theta
* stay distinct. */
kv.push_back(fmt("%s=%.17g", p[i].key, p[i].dval));
else
kv.push_back(fmt("%s=%lld", p[i].key, p[i].ival));
@@ -92,8 +91,7 @@ std::vector<std::pair<std::string, int64_t>> TuneCache::parse_choice(std::string
if (eq != std::string_view::npos && eq > 0) {
const std::string key(tok.substr(0, eq));
const std::string val(tok.substr(eq + 1));
/* strtoll rather than stoll: a malformed value is a dropped pair, not an exception on
* a path whose whole contract is that a bad cache cannot stop a server. */
/* strtoll, not stoll: a malformed value drops the pair instead of throwing. */
char* end = nullptr;
const long long v = std::strtoll(val.c_str(), &end, 10);
if (end && *end == '\0' && !val.empty()) out.emplace_back(key, (int64_t)v);
@@ -133,41 +131,43 @@ int TuneCache::load(const std::string& home, const std::string& machine) {
const std::string path = path_for(home, machine);
FILE* f = ::fopen(path.c_str(), "rb");
if (!f) {
/* No cache is the normal state of a fresh install and not a failure: a plugin's first
* axis carries its own default, so nothing is broken, only untuned. */
/* No cache is normal on a fresh install: every axis has a default. */
if (errno == ENOENT) return RAD_OK;
RAD_WARN("%s: %s", path.c_str(), std::strerror(errno));
return RAD_E_IO;
}
char line[4096];
/* getline, not a fixed buffer: a row longer than any buffer would otherwise be split, and its
* tail read as a row of its own with a truncated geometry. */
char* line = nullptr;
size_t cap = 0;
ssize_t got = 0;
int lineno = 0, bad = 0;
bool saw_magic = false;
while (::fgets(line, sizeof line, f)) {
while ((got = ::getline(&line, &cap, f)) >= 0) {
++lineno;
std::string_view s(line);
std::string_view s(line, (size_t)got);
while (!s.empty() && (s.back() == '\n' || s.back() == '\r')) s.remove_suffix(1);
if (s.empty() || s[0] == '#') continue;
/* SPLIT ON WHITESPACE ONLY, NOT ON COMMAS. `split_ws` treats a comma as a separator too --
* it is shared with the constraint parser, where "bf16 fp16,fp32" is one set -- and a
* tuned choice is comma-separated by construction ("mb=2,npw=4,sk=8"). Splitting on commas
* here turns one field into three and shifts `us` onto a timestamp, which parses as zero
* and is then dropped as malformed, so every row with more than one axis disappears. It
* disappears SILENTLY, because a cache that cannot be read is by design survivable. */
/* Split on whitespace only: `split_ws` also splits on commas (for constraint sets), but a
* choice is comma-separated ("mb=2,npw=4,sk=8"), and splitting it would shift the fields
* and silently drop every multi-axis row. */
auto tok = split_ws_only(s);
/* A line of blanks is a blank line, and every branch below reads tok[0]. */
/* A whitespace-only line; every branch below reads tok[0]. */
if (tok.empty()) continue;
if (!saw_magic) {
if (tok.size() != 2 || tok[0] != "radtune") {
RAD_WARN("%s:%d: not a rad-tune cache (expected 'radtune 2')", path.c_str(), lineno);
std::free(line);
::fclose(f);
return RAD_E_FORMAT;
}
if (tok[1] != "2") {
RAD_WARN("%s: cache format version %.*s, this build reads 2 -- ignoring the cache",
path.c_str(), (int)tok[1].size(), tok[1].data());
std::free(line);
::fclose(f);
return RAD_E_FORMAT;
}
@@ -188,14 +188,18 @@ int TuneCache::load(const std::string& home, const std::string& machine) {
r.plugin = std::string(tok[1]);
r.choice = std::string(tok[2]) == "-" ? std::string() : std::string(tok[2]);
r.us = std::strtod(std::string(tok[3]).c_str(), nullptr);
r.measured = std::string(tok[4]);
/* save() writes an empty date as "-", as it does an empty choice. */
r.measured = tok[4] == "-" ? std::string() : std::string(tok[4]);
for (size_t i = 5; i < tok.size(); ++i) {
if (i > 5) r.geom += ' ';
r.geom.append(tok[i]);
}
if (r.us <= 0.0) { ++bad; continue; }
/* Not `r.us <= 0`: that holds for neither nan nor inf, and a row timed as either would
* win or lose every comparison. */
if (!(r.us > 0.0) || !std::isfinite(r.us)) { ++bad; continue; }
put(r);
}
std::free(line);
::fclose(f);
if (!saw_magic) {
@@ -218,8 +222,7 @@ int TuneCache::save(const std::string& home) const {
return RAD_E_IO;
}
/* Write-then-rename, so an interrupted rad-tune leaves the previous cache intact rather than
* a half-file the selector will warn about on every start. */
/* Write then rename, so an interrupted rad-tune leaves the previous cache intact. */
const std::string tmp = path + ".tmp";
FILE* f = ::fopen(tmp.c_str(), "wb");
if (!f) { RAD_ERR("%s: %s", tmp.c_str(), std::strerror(errno)); return RAD_E_IO; }
@@ -228,7 +231,7 @@ int TuneCache::save(const std::string& home) const {
::fprintf(f, "machine %s\n", machine_.c_str());
::fprintf(f, "# kernel plugin choice us measured geometry\n");
/* Sorted, so the file is stable across runs and a diff shows what actually moved. */
/* Sorted, so the file is stable across runs and diffs show real changes. */
std::vector<const TuneRow*> v;
v.reserve(rows_.size());
for (const auto& r : rows_) v.push_back(&r);
+34 -42
View File
@@ -1,19 +1,16 @@
/* tunecache.h -- the ONE tuning cache. rad-tune writes it, the selector reads it at declare.
/* tunecache.h -- the single tuning cache: rad-tune writes it, the selector reads it at declare.
*
* Constraint matching finds a kernel that is CORRECT for a geometry. Within one kernel there are
* usually many tile configurations and the right one is a property of the shape and the machine
* (spec §15). This file is the whole of the mechanism, and it is deliberately one file and one
* format: the alternative is every plugin inventing its own tuning tool and its own file, and the
* engine being unable to say why a shape is slow.
* Constraint matching finds a kernel that is correct for a geometry; within a kernel the best tile
* configuration depends on the shape and the machine (spec §15). One cache and one format for all
* plugins, so the engine can always say how a shape was tuned.
*
* ================================================================= THE FORMAT
* ================================================================= the format
*
* $RADIANCE_HOME/tune/<machine>.tune
*
* One file per machine, because "which machine" is the coarsest key and a cache measured on
* another card is not a slower answer, it is a wrong one. UTF-8 text, LF-terminated, because a
* human has to be able to read it, diff it, delete one line of it, and check it into a repo
* beside a deployment. It is small: one row per (kernel, shape) the declared graph asks for.
* One file per machine (a cache from another card is wrong, not just slow). UTF-8 text,
* LF-terminated, so it can be read, diffed, edited and versioned. One row per (kernel, shape) the
* declared graph asks for.
*
* line 1 `radtune 2` magic and format version
* line 2 `machine <machine-key>` must equal the reader's own key
@@ -22,27 +19,23 @@
*
* kernel RadKernelInfo.name, the entry point. No spaces.
* plugin RadPluginInfo.name that supplied it. No spaces.
* choice the TUNED AXES that won, `key=value` comma separated and sorted by key -- for
* example `mb=3,npw=4,sk=8`. `-` for a kernel with nothing to tune. It is a point
* in the space RadTunable declares, not a name out of a list: a name would tie the
* cache to a spelling the library happens to use this release, and a library is
* free to add an axis or widen one between builds. An axis the reader no longer
* declares is ignored on lookup; one it declares and the row omits falls back to
* that axis`s default, so a cache written before an axis existed still helps.
* choice the winning tuned axes, `key=value` comma separated, sorted by key (e.g.
* `mb=3,npw=4,sk=8`); `-` for a kernel with nothing to tune. A point in the
* RadTunable space, not a variant name, so libraries may add or widen axes. An axis
* no longer declared is ignored on lookup; a declared axis the row omits takes its
* default.
* us median microseconds per launch, `%.6f`.
* measured ISO-8601 UTC, e.g. `2026-09-04T09:11:02Z`. --debug-graph prints it, because the
* age of a measurement -- taken before a driver or library changed underneath it --
* answers a large share of the questions a slow shape produces.
* geometry the resolved parameters, `key=value` sorted by key, space separated. Ranges are
* ALREADY COLLAPSED to the band's upper bound -- a bucket table row is what was
* measured, so a bucket table row is what is keyed.
* measured ISO-8601 UTC, e.g. `2026-09-04T09:11:02Z`; --debug-graph prints it, since a
* measurement may predate a driver or library change.
* geometry the resolved parameters, `key=value` sorted by key, space separated, with ranges
* collapsed to the band's upper bound (a bucket table row is what was measured).
*
* The lookup key is (kernel, plugin, geometry). Not the op: two kernels can serve one op and they
* tune independently. A row whose kernel no longer exists is kept on rewrite and
* ignored on lookup, so downgrading a plugin does not throw away the measurements.
* The lookup key is (kernel, plugin, geometry), not the op: kernels serving one op tune
* independently. Rows for missing kernels are kept on rewrite and ignored on lookup, so a plugin
* downgrade keeps the measurements.
*
* A missing file is not an error. Every RadTunable carries its own `deflt`, so an untuned install
* is fast rather than broken (spec §15), and this cache only ever moves a shape off those defaults.
* A missing file is not an error: every RadTunable has its own `deflt` (spec §15), and the cache
* only moves shapes off those defaults.
*/
#pragma once
#include "../rad_internal.h"
@@ -62,8 +55,8 @@ struct TuneRow {
class TuneCache {
public:
/* Missing file -> RAD_OK with an empty cache. Malformed line -> skipped with a Warn naming
* the line number; a cache is an optimisation and a typo in it must not stop a server. */
/* Missing file: RAD_OK, empty. Malformed line: skipped with a warning naming it; a bad cache
* must not stop a server. */
int load(const std::string& radiance_home, const std::string& machine);
int save(const std::string& radiance_home) const;
@@ -77,17 +70,15 @@ public:
const std::vector<TuneRow>& rows() const { return rows_; }
bool empty() const { return rows_.empty(); }
/* `key=value` sorted by key, space separated. The canonical spelling of a shape; every
* component that keys on one must go through here or two of them will disagree. */
/* `key=value` sorted by key, space separated: the canonical spelling of a shape. Every
* component keying on shapes must use it. */
static std::string canon_geometry(const Geometry& g);
/* THE `choice` COLUMN, both directions. One spelling, in one place, because the tuner writes
* it and the selector reads it and a disagreement between them is a cache that silently never
* hits. `key=value` comma separated, sorted by key. */
/* The `choice` column in both directions (`key=value` comma separated, sorted by key), shared
* by tuner and selector so the cache always hits. */
static std::string canon_choice(const std::vector<std::pair<std::string, int64_t>>& c);
/* Unparseable pairs are DROPPED, not an error: an axis this reader does not understand is the
* forward-compatibility case tunecache.h's header promises, and the caller filters by the keys
* its kernel actually declares anyway. */
/* Unparseable pairs are dropped, not an error (forward compatibility); the caller filters by
* its kernel's declared keys anyway. */
static std::vector<std::pair<std::string, int64_t>> parse_choice(std::string_view s);
static std::string path_for(const std::string& radiance_home, const std::string& machine);
@@ -104,9 +95,10 @@ private:
std::unordered_map<std::string, size_t> index_;
};
/* The machine half of the key. Derived from the device layer, so it changes when the card does.
* Lives beside the cache and not inside it, because the cache is pure file I/O and testable
* without a device. */
/* The machine half of the key, from the device layer (machine_key.cpp), kept apart so the cache
* stays pure file I/O. */
std::string rad_machine_key();
/* The key for `n` devices, the first described by `dev` (null when there is none to describe). */
std::string rad_machine_key_of(int n, const RadDeviceProps* dev);
} /* namespace rad */