radiance 1.0.0

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

No files matched your search

+887
View File
@@ -0,0 +1,887 @@
/* checkpoint.cpp -- see checkpoint.h. */
#include "checkpoint.h"
#include "rad_plugin.h"
#include <nlohmann/json.hpp>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <fstream>
#include <map>
namespace rad {
/* ================================================================== metadata */
void MetaOwn::set(const std::string& k, const std::string& v) {
for (size_t i = 0; i < keys.size(); ++i)
if (keys[i] == k) { vals[i] = v; return; }
kv(k, v);
}
bool MetaOwn::has(const std::string& k) const {
return std::find(keys.begin(), keys.end(), k) != keys.end();
}
const char* MetaOwn::get(const std::string& k) const {
for (size_t i = 0; i < keys.size(); ++i)
if (keys[i] == k) return vals[i].c_str();
return nullptr;
}
void MetaOwn::finish() {
kp.clear();
vp.clear();
for (auto& s : keys) kp.push_back(s.c_str());
for (auto& s : vals) vp.push_back(s.c_str());
m.arch_id = arch.c_str();
m.name = name.c_str();
m.quant = quant.c_str();
m.n_kv = (int)keys.size();
m.kv_key = kp.data();
m.kv_val = vp.data();
}
/* ---------------------------------------------------------------- config.json
*
* A safetensors checkpoint carries its architecture and its dimensions in config.json, and both
* have to reach the plugin: RadModelMeta's typed fields are what declare sizes everything from, so
* an unparsed config means a graph built on zeros. Parsing it is the core's job and not the
* architecture plugin's, because the plugin is handed RadModelMeta and never sees the file.
*
* Two shapes exist and both are handled. A text-only model puts its dimensions at the top level; a
* multimodal one nests them under `text_config` and puts the tower under `vision_config`. The
* nested case is not a special case here: EVERY key is flattened into the free-form list with a
* dotted path, and the typed fields are then read from `text_config.X` falling back to `X`. So a
* plugin that wants `vision_config.depth` finds it under exactly that name whatever the nesting.
*/
static void flatten_json(const nlohmann::json& j, const std::string& prefix, MetaOwn* out) {
for (auto it = j.begin(); it != j.end(); ++it) {
const std::string key = prefix.empty() ? it.key() : prefix + "." + it.key();
const nlohmann::json& v = it.value();
if (v.is_object()) flatten_json(v, key, out);
else if (v.is_boolean()) out->kv(key, v.get<bool>() ? "1" : "0");
else if (v.is_number_integer()) out->kv(key, fmt("%lld", (long long)v.get<int64_t>()));
else if (v.is_number()) out->kv(key, fmt("%.17g", v.get<double>()));
else if (v.is_string()) out->kv(key, v.get<std::string>());
else if (v.is_array()) {
/* An array of scalars becomes a space-separated string: mrope_section "11 11 10",
* layer_types "linear_attention full_attention ...". A plugin splits it. Arrays of
* objects are not flattened -- nothing in a config uses one for a dimension. */
std::string s;
bool ok = true;
for (const auto& e : v) {
if (!s.empty()) s += ' ';
if (e.is_number_integer()) s += fmt("%lld", (long long)e.get<int64_t>());
else if (e.is_number()) s += fmt("%.17g", e.get<double>());
else if (e.is_string()) s += e.get<std::string>();
else { ok = false; break; }
}
if (ok) out->kv(key, s);
}
}
}
/* A SECOND config.json, flattened under a prefix and nothing else.
*
* None of meta_from_config_json's typed extraction applies: a drafter's `num_hidden_layers` is 5
* and the target's is 64, and writing the drafter's into RadModelMeta would size the trunk from
* the draft head. So the whole of it goes into the free-form table with `draft.` in front, which
* is where an architecture plugin reads a dimension the struct does not name anyway. The
* `text_config` aliasing is deliberately not repeated -- a drafter is a text model by
* construction, and aliasing here would collide with the target's bare keys. */
int meta_merge_config_json(const std::string& dir, const std::string& prefix, MetaOwn* out) {
const std::string path = dir + "/config.json";
std::ifstream f(path);
if (!f) {
RAD_ERR("%s: no config.json. A draft checkpoint carries its own geometry there -- the "
"block size it was trained for, which trunk layers it reads, the selector's rank "
"-- and none of it is derivable from the target.", dir.c_str());
return RAD_E_NOTFOUND;
}
nlohmann::json j;
try { f >> j; }
catch (const std::exception& e) { RAD_ERR("%s: %s", path.c_str(), e.what()); return RAD_E_FORMAT; }
flatten_json(j, prefix, out);
return RAD_OK;
}
/* ---------------------------------------------------------------- generation_config.json
*
* HOW THE CHECKPOINT SAYS IT WANTS TO BE SAMPLED, carried into the container so that serving it
* does not depend on a file nobody copied. It is a separate file from config.json because it is a
* separate thing: config.json is the architecture and is required, this is the sampler and is
* advisory, and a checkpoint that omits it is read without complaint.
*
* It matters more than "advisory" suggests. A model tuned against a truncated tail and served
* without one will occasionally draw a token from far down its distribution, and end-of-turn is
* one such token -- so the visible symptom is not bad prose, it is a reply that stops early.
*
* Flattened under `generation.` rather than merged into the bare keys: `temperature` and `top_k`
* are common enough words that a bare spelling would collide with an architecture that happens to
* use one, and the prefix is what tells a reader which file a value came from. */
int meta_merge_generation_config(const std::string& dir, MetaOwn* out) {
const std::string path = dir + "/generation_config.json";
std::ifstream f(path);
if (!f) return RAD_OK; /* absent is not an error; nothing is written */
nlohmann::json j;
try { f >> j; }
catch (const std::exception& e) {
RAD_WARN("%s: %s; no sampling defaults are carried", path.c_str(), e.what());
return RAD_OK;
}
if (!j.is_object()) {
RAD_WARN("%s: not a JSON object; no sampling defaults are carried", path.c_str());
return RAD_OK;
}
flatten_json(j, "generation", out);
return RAD_OK;
}
/* ---------------------------------------------------------------- the preprocessor configs
*
* HOW AN IMAGE AND A VIDEO BECOME PATCHES, carried for the reason the sampling defaults are:
* serving the model must not depend on a file nobody copied. The engine's processor (core/mm)
* reads the pixel bands, the normalisation and the frame rate from here; the geometry the encoder
* itself needs is already in config.json's vision_config. Flattened under their own prefixes --
* `size.shortest_edge` means two different things in the two files. Absent is not an error: a
* text model has neither. */
int meta_merge_preprocessor_configs(const std::string& dir, MetaOwn* out) {
static const struct { const char* file; const char* prefix; } kFiles[] = {
{ "preprocessor_config.json", "preprocessor" },
{ "video_preprocessor_config.json", "video_preprocessor" },
};
for (const auto& f : kFiles) {
const std::string path = dir + "/" + f.file;
std::ifstream in(path);
if (!in) continue;
nlohmann::json j;
try { in >> j; }
catch (const std::exception& e) {
RAD_WARN("%s: %s; it is not carried", path.c_str(), e.what());
continue;
}
if (j.is_object()) flatten_json(j, f.prefix, out);
}
return RAD_OK;
}
int meta_from_config_json(const std::string& dir, MetaOwn* out) {
const std::string path = dir + "/config.json";
std::ifstream f(path);
if (!f) {
RAD_ERR("%s: no config.json. A safetensors checkpoint carries its architecture and its "
"dimensions there; without it nothing can be sized.", dir.c_str());
return RAD_E_NOTFOUND;
}
nlohmann::json j;
try { f >> j; }
catch (const std::exception& e) {
RAD_ERR("%s: %s", path.c_str(), e.what());
return RAD_E_FORMAT;
}
flatten_json(j, "", out);
/* Alias text_config.X to a bare X wherever no bare X already exists.
*
* A multimodal checkpoint nests the language model's dimensions under `text_config` and a
* text-only one does not; that nesting is the ONLY difference between the two files. The
* struct fields below already prefer the prefixed spelling, but the free-form key/value table
* is handed to the plugin verbatim, so without this a plugin reading `partial_rotary_factor`
* finds nothing on exactly the checkpoints that have a vision tower -- and the failure is at
* declare, after the architecture has already been matched. One rule, applied once here, is
* better than every plugin having to know what a vision tower does to its config.
*
* The bare key wins where both exist: a top-level value is the file's own answer, and the
* prefixed one is the aliased fallback. */
{
const size_t n = out->keys.size();
for (size_t i = 0; i < n; ++i) {
const std::string& k = out->keys[i];
if (k.rfind("text_config.", 0) != 0) continue;
const std::string bare = k.substr(12);
bool have = false;
for (size_t j2 = 0; j2 < n; ++j2) if (out->keys[j2] == bare) { have = true; break; }
if (!have) out->kv(bare, out->vals[i]);
}
}
auto gs = [&](const char* k) -> const char* { return out->get(k); };
/* text_config first, then the top level: the nesting is the only difference between a
* multimodal config and a text one, and every field below appears in exactly one of the two. */
auto gi = [&](const char* k, int64_t dflt) -> int64_t {
const char* v = gs((std::string("text_config.") + k).c_str());
if (!v) v = gs(k);
return v ? strtoll(v, nullptr, 10) : dflt;
};
auto gf = [&](const char* k, double dflt) -> double {
const char* v = gs((std::string("text_config.") + k).c_str());
if (!v) v = gs(k);
return v ? strtod(v, nullptr) : dflt;
};
/* HuggingFace's model_type is the architecture id, minus the underscores its naming convention
* uses and GGUF's does not: `qwen3_5` and GGUF's `qwen35` are the same architecture, and a
* plugin should not have to claim both spellings. */
if (const char* mt = gs("model_type")) {
out->arch.clear();
for (const char* p = mt; *p; ++p) if (*p != '_') out->arch += *p;
}
if (const char* nm = gs("_name_or_path")) out->name = nm;
RadModelMeta& m = out->m;
m.n_layers = gi("num_hidden_layers", 0);
m.n_embd = gi("hidden_size", 0);
m.n_head = gi("num_attention_heads", 0);
m.n_head_kv = gi("num_key_value_heads", m.n_head);
/* Read head_dim; do NOT derive it. On qwen35 it is 256 while hidden_size/num_attention_heads
* is 213, and a derived value makes every downstream shape silently wrong. */
m.head_dim = gi("head_dim", m.n_head ? m.n_embd / m.n_head : 0);
/* ...AND A ROUTED CHECKPOINT HAS NO `intermediate_size` AT ALL. A routed config states
* `moe_intermediate_size` (one expert's width) and `shared_expert_intermediate_size` and
* nothing else, so reading only the dense spelling leaves n_ff at zero -- and geom_from refuses
* a model with a zero feed-forward width by name, which reads as a broken container rather
* than as an unread key. The per-expert width is what a GEMM sees, so it is what n_ff means;
* the shared expert's is its own key and the plugin reads it from the free-form table. */
m.n_ff = gi("intermediate_size", gi("moe_intermediate_size", 0));
m.n_vocab = gi("vocab_size", 0);
m.n_ctx_train = gi("max_position_embeddings", 0);
m.n_expert = gi("num_experts", gi("num_local_experts", 0));
m.n_expert_used = gi("num_experts_per_tok", 0);
m.n_expert_shared = gi("shared_expert_intermediate_size", 0) ? 1 : 0;
m.rms_eps = (float)gf("rms_norm_eps", 1e-6);
m.rope_theta = (float)gf("rope_parameters.rope_theta", gf("rope_theta", 10000.0));
m.rope_scale = (float)gf("rope_scaling.factor", 1.0);
/* The quantisation descriptor, which with the architecture selects the plugin (spec §2.4).
* "fp8" plus its format, so qwen35_fp8 and qwen35_bf16 are told apart by the checkpoint
* rather than by a flag. */
if (const char* qm = gs("quantization_config.quant_method")) {
out->quant = qm;
if (const char* fm = gs("quantization_config.fmt")) { out->quant += "_"; out->quant += fm; }
}
out->finish();
return RAD_OK;
}
int meta_from_gguf(GgufFile& g, MetaOwn* out) {
if (!g.get_str("general.architecture", &out->arch)) {
RAD_ERR("the GGUF has no general.architecture, so no architecture plugin can be chosen");
return RAD_E_FORMAT;
}
g.get_str("general.name", &out->name);
/* Dimensions come from metadata, so one plugin covers every size in a family. The keys are
* GGUF's `<arch>.<field>` convention; anything the struct does not name is passed through in
* the free-form KV list, which the core never interprets. */
const std::string a = out->arch;
auto gi = [&](const char* suffix, int64_t dflt) -> int64_t {
int64_t v = 0;
return g.get_i64(a + "." + suffix, &v) ? v : dflt;
};
auto gf = [&](const char* suffix, double dflt) -> double {
double v = 0;
return g.get_f64(a + "." + suffix, &v) ? v : dflt;
};
RadModelMeta& m = out->m;
m.n_layers = gi("block_count", 0);
m.n_embd = gi("embedding_length", 0);
m.n_head = gi("attention.head_count", 0);
m.n_head_kv = gi("attention.head_count_kv", m.n_head);
m.head_dim = gi("attention.key_length", m.n_head ? m.n_embd / m.n_head : 0);
m.n_ff = gi("feed_forward_length", 0);
m.n_ctx_train = gi("context_length", 0);
m.n_expert = gi("expert_count", 0);
m.n_expert_used = gi("expert_used_count", 0);
m.n_expert_shared= gi("expert_shared_count", 0);
m.rms_eps = (float)gf("attention.layer_norm_rms_epsilon", 1e-6);
m.rope_theta = (float)gf("rope.freq_base", 10000.0);
m.rope_scale = (float)gf("rope.scaling.factor", 1.0);
std::vector<std::string> toks;
if (g.get_strs("tokenizer.ggml.tokens", &toks)) m.n_vocab = (int64_t)toks.size();
if (m.n_vocab == 0) m.n_vocab = gi("vocab_size", 0);
/* Everything else, verbatim and stringified. A plugin reads what it needs; the core never
* interprets these. Arrays are summarised rather than expanded -- a 151k-token array in a
* key/value list is not metadata, it is the vocab, and the vocab has its own section. */
for (const GgufKV& kv : g.kv()) {
if (kv.key.rfind("tokenizer.", 0) == 0) continue;
std::string v;
if (kv.is_array) {
v = fmt("[%zu values]", kv.type == GGUF_STR ? kv.s.size()
: !kv.i.empty() ? kv.i.size() : kv.f.size());
if (kv.type != GGUF_STR && kv.i.size() <= 8 && !kv.i.empty()) {
v.clear();
for (size_t j = 0; j < kv.i.size(); ++j)
v += fmt("%s%lld", j ? "," : "", (long long)kv.i[j]);
}
} else if (!kv.s.empty()) v = kv.s.front();
else if (!kv.f.empty() && kv.type == GGUF_F32) v = fmt("%g", kv.f.front());
else if (!kv.f.empty() && kv.type == GGUF_F64) v = fmt("%g", kv.f.front());
else if (!kv.i.empty()) v = fmt("%lld", (long long)kv.i.front());
if (v.size() > 240) v.resize(240);
out->kv(kv.key, v);
}
/* THE DESCRIPTOR A SAFETENSORS RELEASE WOULD CARRY. A float file -- all F32 (0), mostly F16
* (1) or mostly BF16 (32), the vectors F32 either way -- is an unquantised checkpoint and
* selects the plugin a bf16 release does. Any other file type names its quantisation, which no
* plugin serves as it stands. */
int64_t ftype = 0;
const bool typed = g.get_i64("general.file_type", &ftype);
out->quant = !typed || ftype == 0 || ftype == 1 || ftype == 32
? std::string() : fmt("gguf_ftype_%lld", (long long)ftype);
out->finish();
return RAD_OK;
}
/* ================================================================== the checkpoint */
int Checkpoint::open_gguf(const std::string& path) {
RAD_TRY(gguf_.open(path.c_str()));
kind_ = Gguf;
for (const GgufTensor& t : gguf_.tensors()) {
SrcTensor s;
s.name = t.name;
s.ggml = t.ggml_type;
s.rad_dtype = gguf_to_rad_dtype(t.ggml_type);
/* GGUF is fastest-first; everything from here on is row-major. */
for (int d = (int)t.n_dims - 1; d >= 0; --d) s.shape.push_back(t.ne[d]);
s.data = gguf_.tensor_data(t);
s.bytes = (int64_t)t.bytes;
if (!s.data) {
RAD_ERR("%s: '%s' has no readable extent", path.c_str(), t.name.c_str());
return RAD_E_FORMAT;
}
index_.emplace(s.name, tensors_.size());
tensors_.push_back(std::move(s));
}
return meta_from_gguf(gguf_, &meta_);
}
int Checkpoint::add_shard(const std::string& p, const std::string& prefix) {
shards_.push_back(std::make_unique<SafeTensorsFile>());
RAD_TRY(shards_.back()->open(p));
for (const auto& t : shards_.back()->tensors()) {
if (t.dtype == RAD_DT_INVALID) {
RAD_ERR("%s: '%s' has dtype %s, which has no RAD equivalent", p.c_str(),
t.name.c_str(), t.dtype_str.c_str());
return RAD_E_DTYPE;
}
SrcTensor s;
s.name = prefix + t.name;
s.rad_dtype = t.dtype;
s.shape = t.shape; /* safetensors is already row-major */
s.data = t.data;
s.bytes = (int64_t)t.bytes;
index_.emplace(s.name, tensors_.size());
tensors_.push_back(std::move(s));
}
return RAD_OK;
}
namespace {
/* Every shard an index names, once each and in name order, or the one model.safetensors. */
int shard_list(const std::string& dir, const std::string& index, bool index_given,
std::vector<std::string>* out) {
std::unordered_map<std::string, std::string> map;
const int s = st_load_index(index, &map);
if (s == RAD_OK) {
for (auto& [t, f] : map)
if (std::find(out->begin(), out->end(), f) == out->end()) out->push_back(f);
std::sort(out->begin(), out->end());
for (auto& f : *out) f = dir + "/" + f;
return RAD_OK;
}
if (s != RAD_E_NOTFOUND || index_given) return s;
out->push_back(dir + "/model.safetensors");
return RAD_OK;
}
} /* namespace */
int Checkpoint::open_safetensors(const std::string& path) {
kind_ = SafeT;
/* One shard, an index, or the directory holding either: one namespace whichever it is. */
std::vector<std::string> shards;
const bool is_index = path.size() > 10 && path.compare(path.size() - 10, 10, "index.json") == 0;
const bool is_file = path.size() > 12 &&
path.compare(path.size() - 12, 12, ".safetensors") == 0;
if (is_file) {
shards.push_back(path);
} else {
RAD_TRY(shard_list(dir_, is_index ? path : dir_ + "/model.safetensors.index.json",
is_index, &shards));
}
for (const auto& sh : shards) RAD_TRY(add_shard(sh));
RAD_TRY(meta_from_config_json(dir_, &meta_));
RAD_TRY(meta_merge_generation_config(dir_, &meta_));
RAD_TRY(meta_merge_preprocessor_configs(dir_, &meta_));
/* FP8's block, where the checkpoint states one. */
if (const char* bs = meta_.get("quantization_config.weight_block_size")) {
long long r = 0, c = 0;
if (std::sscanf(bs, "%lld %lld", &r, &c) == 2 && r > 0 && c > 0) {
fp8_br_ = r;
fp8_bc_ = c;
}
}
meta_.finish();
return RAD_OK;
}
int Checkpoint::open(const std::string& path) {
path_ = path;
const bool gguf = path.size() > 5 && path.compare(path.size() - 5, 5, ".gguf") == 0;
dir_ = path;
const size_t slash = path.find_last_of('/');
auto ends = [&](const char* s) {
const size_t n = std::strlen(s);
return path.size() > n && path.compare(path.size() - n, n, s) == 0;
};
const bool is_file = gguf || ends(".safetensors") || ends("index.json");
if (is_file) dir_ = slash == std::string::npos ? "." : path.substr(0, slash);
return gguf ? open_gguf(path) : open_safetensors(path);
}
int Checkpoint::add_draft(const std::string& dir, const std::string& prefix) {
if (kind_ != SafeT) {
RAD_ERR("a drafter is merged into a safetensors target's namespace; %s is not one",
path_.c_str());
return RAD_E_UNSUPPORTED;
}
RAD_TRY(meta_merge_config_json(dir, prefix.empty() || prefix.back() != '.'
? prefix
: prefix.substr(0, prefix.size() - 1), &meta_));
std::vector<std::string> shards;
RAD_TRY(shard_list(dir, dir + "/model.safetensors.index.json", false, &shards));
for (const auto& sh : shards) RAD_TRY(add_shard(sh, prefix));
meta_.finish();
return RAD_OK;
}
const SrcTensor* Checkpoint::find(const std::string& n) const {
auto it = index_.find(n);
return it == index_.end() ? nullptr : &tensors_[it->second];
}
/* ONE EXPERT'S SLICE OF A STACKED TENSOR, AS A VIEW.
*
* Slicing dim 0 of a row-major tensor is an offset and a shorter shape -- nothing is copied, so
* the 512 declared weights of a MoE layer read 512 disjoint windows of the same mapped bytes.
*
* IT IS ALSO EXACT FOR A BLOCK-QUANTISED SOURCE, and that is not luck: ggml packs blocks along the
* ROW, and a dim-0 slice is a whole number of rows, so a sub-tensor is a whole number of blocks.
* `bytes % shape[0] == 0` therefore holds for every dtype and the division is the real byte count
* rather than an estimate of one. A slice along any other dimension would not have that property
* and is not offered. */
const SrcTensor* Checkpoint::slice(const SrcTensor& st, int index, const char* declared) {
if (st.shape.size() < 2) {
RAD_ERR("'%s' asks for sub-tensor %d of '%s', which has rank %zu. Only a STACKED tensor "
"-- rank 2 or more, with the stack on dim 0 -- has sub-tensors to take.",
declared, index, st.name.c_str(), st.shape.size());
return nullptr;
}
const int64_t n = st.shape[0];
if (index < 0 || index >= n) {
RAD_ERR("'%s' asks for sub-tensor %d of '%s', which holds %lld of them",
declared, index, st.name.c_str(), (long long)n);
return nullptr;
}
if (!st.data || st.bytes <= 0 || st.bytes % n != 0) {
RAD_ERR("'%s': '%s' is %lld byte(s) over %lld sub-tensor(s), which does not divide -- the "
"slice would straddle two of them",
declared, st.name.c_str(), (long long)st.bytes, (long long)n);
return nullptr;
}
SrcTensor v;
/* The name carries the index because every diagnostic below this point prints it, and
* "experts.gate_up_proj" said 512 times for 512 different weights cannot be read. */
v.name = st.name + "[" + std::to_string(index) + "]";
v.ggml = st.ggml;
v.rad_dtype = st.rad_dtype;
v.shape.assign(st.shape.begin() + 1, st.shape.end());
v.bytes = st.bytes / n;
v.data = (const uint8_t*)st.data + (size_t)index * (size_t)v.bytes;
sliced_.push_back(std::move(v));
return &sliced_.back();
}
/* ================================================================== logical weights */
namespace {
/* FP8's scale plane is a companion tensor: `X.weight` is scaled by `X.weight_scale_inv`. */
std::string scale_name(const std::string& codes) { return codes + "_scale_inv"; }
} /* namespace */
int ckpt_resolve(Checkpoint& ck, const Program& prog, const std::string& name, bool optional,
CkptWeight* out, std::string* why) {
auto refuse = [&](int rc, std::string m) {
if (why) *why = std::move(m);
return rc;
};
*out = CkptWeight{};
out->name = name;
/* EVERY map for the name, in declaration order. A CONCAT map may be declared in several
* calls -- the ABI's `src[8]` against a 128-shard tensor -- and they join end to end; every
* other repeat was refused at declare, so more than one implies CONCAT. */
std::vector<const RadNameMap*> maps;
for (const auto& nm : prog.name_map)
if (nm.declared && name == nm.declared) maps.push_back(&nm);
if (maps.empty()) return refuse(RAD_E_NOTFOUND, "the name map has no entry for it");
struct Src1 { const char* name; int index; };
std::vector<Src1> srcs;
for (const RadNameMap* pm : maps)
for (int k = 0; k < pm->n_src; ++k) srcs.push_back({ pm->src[k], pm->src_index[k] });
out->concat_dim = maps.front()->concat_dim;
/* THE MODE DECIDES WHAT SEVERAL SOURCES MEAN.
*
* RAD_MAP_CONCAT all of them, joined -- gate and up into gate_up.
* RAD_MAP_COPY ALTERNATIVES, first present wins: a tied lm_head is output.weight where
* the checkpoint ships one and the embedding where it does not.
*
* Treating a COPY's alternatives as a concatenation is silently wrong in both directions: a
* checkpoint holding both writes the head at twice its rows, and one holding only the
* embedding fails at the missing first source instead of falling back to it. */
const bool alternatives = maps.front()->mode == RAD_MAP_COPY && srcs.size() > 1;
for (const Src1& s1 : srcs) {
const SrcTensor* st = ck.find(s1.name);
const SrcTensor* sc = st ? ck.find(scale_name(s1.name)) : nullptr;
/* A SUB-TENSOR INDEX IS TAKEN, never ignored: ignoring it gives every expert a copy of
* the whole stack, in a model that loads and answers. Its scale plane is stacked the same
* way and sliced at the same index. */
if (st && s1.index >= 0) {
st = ck.slice(*st, s1.index, name.c_str());
if (!st) return refuse(RAD_E_SHAPE, "a sub-tensor it names is not there");
if (sc && !(sc = ck.slice(*sc, s1.index, name.c_str())))
return refuse(RAD_E_SHAPE, "its scale plane cannot be sliced at the same index");
}
if (!st) {
if (alternatives) continue;
if (optional) { out->pieces.clear(); break; }
return refuse(RAD_E_NOTFOUND, std::string("it needs checkpoint tensor '") + s1.name +
"', which is not in " + ck.path());
}
out->pieces.push_back(st);
out->scales.push_back(sc);
if (alternatives) break;
}
if (out->pieces.empty()) {
if (optional) return refuse(RAD_E_NOTFOUND, "none of its tensors is in the checkpoint");
std::string tried;
for (size_t k = 0; k < srcs.size(); ++k) tried += (k ? " or " : "") + std::string(srcs[k].name);
return refuse(RAD_E_NOTFOUND, "it needs one of " + tried + ", and " + ck.path() +
" holds none of them");
}
/* THE LOGICAL SHAPE: the pieces joined along concat_dim, every other extent agreeing. */
const SrcTensor& p0 = *out->pieces[0];
const int d = out->concat_dim;
if (p0.shape.empty() || p0.shape.size() > RAD_MAX_RANK || d < 0 || d >= (int)p0.shape.size())
return refuse(RAD_E_SHAPE, "'" + p0.name + "' cannot be joined along dim " +
std::to_string(d));
out->rank = (uint32_t)p0.shape.size();
for (uint32_t i = 0; i < out->rank; ++i) out->shape[i] = p0.shape[i];
for (size_t k = 1; k < out->pieces.size(); ++k) {
const SrcTensor& pk = *out->pieces[k];
bool fits = pk.shape.size() == p0.shape.size();
for (uint32_t i = 0; fits && i < out->rank; ++i)
if ((int)i != d && pk.shape[i] != p0.shape[i]) fits = false;
if (!fits)
return refuse(RAD_E_SHAPE, "'" + pk.name + "' and '" + p0.name +
"' do not join along dim " + std::to_string(d));
out->shape[d] += pk.shape[(size_t)d];
}
rad_enc_view(out->rank, out->shape, &out->rows, &out->cols);
/* THE ENCODING THE PIECES ARE, when it is trivial (spec §4.3). */
const uint32_t dt = p0.rad_dtype;
bool same = true, scaled = true, unscaled = true;
for (size_t k = 0; k < out->pieces.size(); ++k) {
if (out->pieces[k]->rad_dtype != dt) same = false;
if (out->scales[k]) unscaled = false; else scaled = false;
}
if (dt == RAD_DT_INVALID) {
out->why = std::string("'") + p0.name + "' is a GGUF " +
(gguf_dtype(p0.ggml) ? gguf_dtype(p0.ggml)->name : "block") + " tensor";
} else if (!same) {
out->why = "its pieces are stored in different dtypes";
} else if ((dt == RAD_F8E4M3 || dt == RAD_F8E5M2) && scaled) {
/* BLOCK-SCALED FP8, byte for byte: the codes and the scale plane are the planes of
* `fp8_e4m3*bf16[128x128]` (whatever the scale's own dtype). Joined only along rows, and
* only where each piece but the last fills its last row block -- a scale covering the
* tail of one piece and the head of the next belongs to neither. */
const int64_t br = ck.fp8_block_rows(), bc = ck.fp8_block_cols();
const uint32_t sdt = out->scales[0]->rad_dtype;
out->trivial = true;
if (d != 0 && out->pieces.size() > 1) {
out->trivial = false;
out->why = "its FP8 pieces are joined along a column, across their scale blocks";
}
for (size_t k = 0; k < out->pieces.size() && out->trivial; ++k) {
const SrcTensor& pk = *out->pieces[k];
const SrcTensor& sk = *out->scales[k];
int64_t r = 0, c = 0;
rad_enc_view((uint32_t)pk.shape.size(), pk.shape.data(), &r, &c);
const int64_t want_r = (r + br - 1) / br, want_c = (c + bc - 1) / bc;
int64_t sr = 0, scl = 0;
rad_enc_view((uint32_t)sk.shape.size(), sk.shape.data(), &sr, &scl);
if (sk.rad_dtype != sdt || sr != want_r || scl != want_c) {
out->trivial = false;
out->why = "'" + sk.name + "' is not the [" + std::to_string(want_r) + ", " +
std::to_string(want_c) + "] " + std::to_string(br) + "x" +
std::to_string(bc) + " scale plane of '" + pk.name + "'";
} else if (k + 1 < out->pieces.size() && r % br) {
out->trivial = false;
out->why = "'" + pk.name + "' ends inside a scale block, so the next piece's "
"scales cannot follow it";
}
}
if (out->trivial) {
rad_enc_clear(&out->enc);
rad_enc_copy_str(out->enc.scheme, "affine");
rad_enc_add_plane(&out->enc, "codes", dt, 1, 1);
rad_enc_add_plane(&out->enc, "scale", sdt, br, bc);
}
} else if (!unscaled) {
out->why = "some of its pieces carry a scale plane and some do not";
} else if (dt == RAD_F8E4M3 || dt == RAD_F8E5M2) {
out->why = "it is FP8 with no scale plane beside it";
} else {
out->trivial = rad_dtype_bits(dt) >= 8;
if (out->trivial) out->enc = rad_enc_plain(dt);
else out->why = std::string("it is ") + rad_dtype_name(dt);
}
return RAD_OK;
}
namespace {
/* ---------------------------------------------------------------- GGUF block types
*
* The ggml block types a weight can be read from as f32. Their GEOMETRY is core/text's -- that is
* what sizes a tensor -- and decoding one is content, so the short table is here, where a weight
* is read. The K-quants are refused by name rather than half-implemented: a super-block scale read
* wrong is a model that talks and is wrong. */
enum { GGML_F32 = 0, GGML_F16 = 1, GGML_Q4_0 = 2, GGML_Q4_1 = 3, GGML_Q5_0 = 6, GGML_Q5_1 = 7,
GGML_Q8_0 = 8, GGML_BF16 = 30 };
int ggml_rows_f32(uint32_t type, const uint8_t* p, int64_t n, float* dst) {
auto half = [&](const uint8_t* q) { uint16_t h; std::memcpy(&h, q, 2); return rad_f16_to_f32(h); };
switch (type) {
case GGML_Q8_0:
for (int64_t b = 0; b < n / 32; ++b, p += 34) {
const float d = half(p);
for (int j = 0; j < 32; ++j) dst[b * 32 + j] = d * (float)(int8_t)p[2 + j];
}
return RAD_OK;
case GGML_Q4_0:
for (int64_t b = 0; b < n / 32; ++b, p += 18) {
const float d = half(p);
for (int j = 0; j < 16; ++j) {
dst[b * 32 + j] = d * (float)((p[2 + j] & 0x0F) - 8);
dst[b * 32 + j + 16] = d * (float)((p[2 + j] >> 4) - 8);
}
}
return RAD_OK;
case GGML_Q4_1:
for (int64_t b = 0; b < n / 32; ++b, p += 20) {
const float d = half(p), m = half(p + 2);
for (int j = 0; j < 16; ++j) {
dst[b * 32 + j] = d * (float)(p[4 + j] & 0x0F) + m;
dst[b * 32 + j + 16] = d * (float)(p[4 + j] >> 4) + m;
}
}
return RAD_OK;
case GGML_Q5_0:
for (int64_t b = 0; b < n / 32; ++b, p += 22) {
const float d = half(p);
uint32_t qh; std::memcpy(&qh, p + 2, 4);
for (int j = 0; j < 16; ++j) {
const int lo = (int)((p[6 + j] & 0x0F) | (((qh >> j) & 1u) << 4)) - 16;
const int hi = (int)((p[6 + j] >> 4) | (((qh >> (j + 16)) & 1u) << 4)) - 16;
dst[b * 32 + j] = d * (float)lo;
dst[b * 32 + j + 16] = d * (float)hi;
}
}
return RAD_OK;
case GGML_Q5_1:
for (int64_t b = 0; b < n / 32; ++b, p += 24) {
const float d = half(p), m = half(p + 2);
uint32_t qh; std::memcpy(&qh, p + 4, 4);
for (int j = 0; j < 16; ++j) {
const int lo = (int)((p[8 + j] & 0x0F) | (((qh >> j) & 1u) << 4));
const int hi = (int)((p[8 + j] >> 4) | (((qh >> (j + 16)) & 1u) << 4));
dst[b * 32 + j] = d * (float)lo + m;
dst[b * 32 + j + 16] = d * (float)hi + m;
}
}
return RAD_OK;
default:
return RAD_E_UNSUPPORTED;
}
}
/* Where flat element `i` of the joined tensor lives: which piece, and the element in it. A join
* along dim d repeats, for each index of the dims before d, every piece's [d..] extent in turn. */
struct Joined {
std::vector<int64_t> inner; /* each piece's elements per outer index */
int64_t total_inner = 0;
int n = 0;
void init(const std::vector<const SrcTensor*>& pieces, int d) {
n = (int)pieces.size();
inner.assign((size_t)n, 1);
total_inner = 0;
for (int k = 0; k < n; ++k) {
for (size_t i = (size_t)d; i < pieces[(size_t)k]->shape.size(); ++i)
inner[(size_t)k] *= pieces[(size_t)k]->shape[i];
total_inner += inner[(size_t)k];
}
}
/* Visit [a, b) as runs that lie in one piece: f(piece, element in it, count, at). */
template <class F> int walk(int64_t a, int64_t b, F f) const {
while (a < b) {
const int64_t o = a / total_inner;
int64_t w = a % total_inner, k = 0;
while (w >= inner[(size_t)k]) w -= inner[(size_t)k++];
const int64_t run = std::min<int64_t>(b - a, inner[(size_t)k] - w);
const int rc = f((int)k, o * inner[(size_t)k] + w, run);
if (rc < 0) return rc;
a += run;
}
return RAD_OK;
}
};
/* `n` elements of a stored-dtype piece from element `e`, as f32. */
int piece_f32(const SrcTensor& t, int64_t e, int64_t n, float* out) {
if (t.rad_dtype == RAD_DT_INVALID) {
/* a GGUF block type: whole rows only, and a row is whole blocks */
const int64_t cols = t.shape.back();
if (cols <= 0 || e % cols || n % cols) return RAD_E_SHAPE;
const int64_t rows = t.numel() / cols, rb = t.bytes / (rows ? rows : 1);
return ggml_rows_f32(t.ggml, (const uint8_t*)t.data + (e / cols) * rb, n, out);
}
const uint8_t* p = (const uint8_t*)t.data;
switch (t.rad_dtype) {
case RAD_F32:
std::memcpy(out, (const float*)t.data + e, (size_t)n * 4);
return RAD_OK;
case RAD_BF16: {
/* The top half of an f32, so a shift -- and a loop the compiler vectorises, which the
* per-element dtype switch below is not. Most of a checkpoint is this. */
const uint16_t* q = (const uint16_t*)t.data + e;
for (int64_t i = 0; i < n; ++i) {
const uint32_t u = (uint32_t)q[i] << 16;
std::memcpy(out + i, &u, 4);
}
return RAD_OK;
}
case RAD_F16: case RAD_F8E4M3: case RAD_F8E5M2:
case RAD_I8: case RAD_U8: case RAD_I16: case RAD_I32: case RAD_U32: case RAD_U16:
for (int64_t i = 0; i < n; ++i) out[i] = rad_load_f32(p, t.rad_dtype, e + i);
return RAD_OK;
default:
return RAD_E_UNSUPPORTED;
}
}
} /* namespace */
int ckpt_rows_f32(const CkptWeight& w, int64_t r0, int64_t nr, float* out, std::string* why) {
auto refuse = [&](int rc, std::string m) {
if (why) *why = std::move(m);
return rc;
};
if (r0 < 0 || nr < 0 || r0 + nr > w.rows) return refuse(RAD_E_SHAPE, "rows out of range");
Joined j;
j.init(w.pieces, w.concat_dim);
/* the runs come in order, so the cursor is the elements already written */
int64_t at = 0;
const int rc = j.walk(r0 * w.cols, (r0 + nr) * w.cols, [&](int k, int64_t e, int64_t n) {
const int s = piece_f32(*w.pieces[(size_t)k], e, n, out + at);
at += n;
return s;
});
if (rc < 0)
return refuse(rc, "'" + w.pieces[0]->name + "' is stored in a form that cannot be read "
"as f32 (" + (w.pieces[0]->rad_dtype == RAD_DT_INVALID
? std::string(gguf_dtype(w.pieces[0]->ggml)
? gguf_dtype(w.pieces[0]->ggml)->name
: "?")
: std::string(rad_dtype_name(w.pieces[0]->rad_dtype))) +
")");
/* FP8 IS ITS CODE TIMES ITS BLOCK'S SCALE: the pieces are joined along rows, so logical row
* r is in the piece whose rows cover it, and its scales are that piece's. */
if (!w.scales.empty() && w.scales[0]) {
const int64_t br = w.enc.n_planes > 1 ? w.enc.plane[1].block[0] : 128;
const int64_t bc = w.enc.n_planes > 1 ? w.enc.plane[1].block[1] : 128;
int64_t base = 0;
for (size_t k = 0; k < w.pieces.size(); ++k) {
const SrcTensor& pk = *w.pieces[k];
const SrcTensor& sk = *w.scales[k];
int64_t pr = 0, pc = 0;
rad_enc_view((uint32_t)pk.shape.size(), pk.shape.data(), &pr, &pc);
const int64_t sc = (pc + bc - 1) / bc;
for (int64_t r = std::max(r0, base); r < std::min(r0 + nr, base + pr); ++r)
for (int64_t c = 0; c < w.cols; ++c)
out[(r - r0) * w.cols + c] *=
rad_load_f32(sk.data, sk.rad_dtype, ((r - base) / br) * sc + c / bc);
base += pr;
}
}
return RAD_OK;
}
int ckpt_plane_rows(const CkptWeight& w, int k, int64_t r0, int64_t nr, void* dst,
std::string* why) {
auto refuse = [&](int rc, std::string m) {
if (why) *why = std::move(m);
return rc;
};
if (!w.trivial || k < 0 || k >= w.enc.n_planes)
return refuse(RAD_E_STATE, "not a plane of a trivial encoding");
const std::vector<const SrcTensor*>& src = k == 0 ? w.pieces : w.scales;
int64_t pr = 0, pc = 0;
rad_enc_plane_dims(&w.enc.plane[k], w.rows, w.cols, &pr, &pc);
if (r0 < 0 || nr < 0 || r0 + nr > pr) return refuse(RAD_E_SHAPE, "plane rows out of range");
const uint32_t dt = w.enc.plane[k].dtype;
const int64_t eb = rad_dtype_bits(dt) / 8;
uint8_t* o = (uint8_t*)dst;
if (k == 0) {
/* the codes: the pieces joined, bytes as they are */
Joined j;
j.init(src, w.concat_dim);
return j.walk(r0 * pc, (r0 + nr) * pc, [&](int p, int64_t e, int64_t n) {
std::memcpy(o, (const uint8_t*)src[(size_t)p]->data + e * eb, (size_t)(n * eb));
o += n * eb;
return RAD_OK;
});
}
/* an FP8 scale plane: the pieces' scale rows one after another */
int64_t base = 0;
for (const SrcTensor* s : src) {
int64_t sr = 0, scl = 0;
rad_enc_view((uint32_t)s->shape.size(), s->shape.data(), &sr, &scl);
const int64_t lo = std::max(r0, base), hi = std::min(r0 + nr, base + sr);
if (hi > lo) {
std::memcpy(o, (const uint8_t*)s->data + (lo - base) * scl * eb,
(size_t)((hi - lo) * scl * eb));
o += (hi - lo) * scl * eb;
}
base += sr;
}
return RAD_OK;
}
} /* namespace rad */
+159
View File
@@ -0,0 +1,159 @@
/* 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:
*
* - 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.
*
* Trivial is the set spec §4.3 names: plain f32, f16 and bf16 (GGUF's too), and block-scaled
* FP8, where `X.weight_scale_inv` is the scale plane of `X.weight`. Anything else is a weight
* whose served form needs quantisation work, which a recipe does ahead of time.
*/
#pragma once
#include "../rad_internal.h"
#include "../rad_core.h"
#include "safetensors.h"
#include "../text/gguf.h"
#include <deque>
#include <memory>
#include <string>
#include <unordered_map>
#include <vector>
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. */
struct SrcTensor {
std::string name;
uint32_t ggml = 0;
uint32_t rad_dtype = RAD_DT_INVALID; /* INVALID: a GGUF block type */
std::vector<int64_t> shape; /* row-major */
const void* data = nullptr;
int64_t bytes = 0;
int64_t numel() const {
int64_t n = 1;
for (int64_t d : shape) n *= d;
return shape.empty() ? 0 : n;
}
};
/* ================================================================== metadata */
/* The model's metadata as RadModelMeta, with the strings it points at owned here. */
struct MetaOwn {
std::string arch, name, quant;
std::vector<std::string> keys, vals;
std::vector<const char*> kp, vp;
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. */
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. */
void finish();
};
int meta_from_config_json(const std::string& dir, MetaOwn* out);
int meta_merge_config_json(const std::string& dir, const std::string& prefix, MetaOwn* out);
int meta_merge_generation_config(const std::string& dir, MetaOwn* out);
int meta_merge_preprocessor_configs(const std::string& dir, MetaOwn* out);
int meta_from_gguf(GgufFile& g, MetaOwn* out);
/* ================================================================== the checkpoint */
class Checkpoint {
public:
Checkpoint() = default;
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. */
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. */
int add_draft(const std::string& dir, const std::string& prefix);
const SrcTensor* find(const std::string& n) const;
const std::vector<SrcTensor>& tensors() const { return tensors_; }
bool is_gguf() const { return kind_ == Gguf; }
GgufFile& gguf() { return gguf_; }
const std::string& path() const { return path_; }
const std::string& dir() const { return dir_; } /* where config.json and tokenizer.json sit */
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. */
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_; }
private:
int add_shard(const std::string& p, const std::string& prefix = "");
int open_safetensors(const std::string& path);
int open_gguf(const std::string& path);
enum Kind { None, Gguf, SafeT } kind_ = None;
std::string path_, dir_;
GgufFile gguf_;
MetaOwn meta_;
std::vector<std::unique_ptr<SafeTensorsFile>> shards_;
std::vector<SrcTensor> tensors_;
std::unordered_map<std::string, size_t> index_;
std::deque<SrcTensor> sliced_; /* views; a deque never moves what it holds */
int64_t fp8_br_ = 128, fp8_bc_ = 128;
};
/* ================================================================== logical weights */
/* A declared weight's source, as the name map resolves it: pieces joined along `concat_dim`, and
* for block-scaled FP8 each piece's scale plane beside it. */
struct CkptWeight {
std::string name; /* the logical (declared) name */
std::vector<const SrcTensor*> pieces; /* the codes, in concatenation order */
std::vector<const SrcTensor*> scales; /* FP8 only: one a piece */
int concat_dim = 0;
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. */
bool trivial = false;
RadEncoding enc{};
std::string why;
};
/* Resolve `name` through `prog`'s name map. RAD_OK; RAD_E_NOTFOUND when the name map has no entry
* for it yet (declare may add one later) or, for an optional weight, none of its tensors is
* there; anything else with the reason in `why`. */
int ckpt_resolve(Checkpoint& ck, const Program& prog, const std::string& name, bool optional,
CkptWeight* out, std::string* why);
/* 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 `w`, in the plane's own elements, dense into
* `dst`: the bytes a container entry holds for it. */
int ckpt_plane_rows(const CkptWeight& w, int k, int64_t r0, int64_t nr, void* dst,
std::string* why);
} /* namespace rad */
+414
View File
@@ -0,0 +1,414 @@
/* encoding.cpp -- decoding a weight encoding to f32 and cutting its planes. See encoding.h, and
* abi/rad_encoding.h for what each plane means. */
#include "encoding.h"
#include "rad_plugin.h"
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <mutex>
#include <vector>
namespace rad {
void enc_view(const RadEncoding& e, int64_t rows, int64_t cols, const void* const* data,
EncodedView* v) {
v->enc = e;
v->rows = rows;
v->cols = cols;
for (int i = 0; i < RAD_ENC_MAX_PLANES; ++i) v->plane[i] = PlaneView{};
for (int i = 0; i < e.n_planes && i < RAD_ENC_MAX_PLANES; ++i) {
PlaneView& p = v->plane[i];
rad_enc_plane_dims(&e.plane[i], rows, cols, &p.rows, &p.cols);
p.row_bytes = rad_enc_row_bytes(e.plane[i].dtype, p.cols);
p.data = data ? data[i] : nullptr;
}
}
void fwht_inplace(float* v, int64_t n) {
for (int64_t h = 1; h < n; h <<= 1)
for (int64_t i = 0; i < n; i += h << 1)
for (int64_t j = i; j < i + h; ++j) {
const float a = v[j], b = v[j + h];
v[j] = a + b;
v[j + h] = a - b;
}
}
std::string enc_name(const RadEncoding& e) {
char buf[512];
rad_enc_format(&e, buf, sizeof buf);
return buf;
}
namespace {
std::string fmt(const char* f, long long a = 0, long long b = 0, long long c = 0) {
char m[256];
std::snprintf(m, sizeof m, f, a, b, c);
return m;
}
/* A plane and the means to read element (i, j) of it as f32. */
struct Rd {
const PlaneView* v = nullptr;
const RadEncPlane* d = nullptr;
explicit operator bool() const { return v != nullptr; }
float at(int64_t i, int64_t j) const {
return rad_load_f32((const uint8_t*)v->data + i * v->row_bytes, d->dtype, j);
}
/* The element of a TILED plane covering logical (r, c). */
float cover(int64_t r, int64_t c) const {
return at(d->block[0] > 0 ? r / d->block[0] : 0, d->block[1] > 0 ? c / d->block[1] : 0);
}
};
/* Row `r` of a code plane as f32, its dtype resolved once for the row rather than per element.
* The values are rad_load_f32's: the same nibble order, the same sign extension. */
void codes_row(const Rd& p, int64_t r, int64_t n, float* out) {
const uint8_t* b = (const uint8_t*)p.v->data + r * p.v->row_bytes;
switch (p.d->dtype) {
case RAD_I4:
for (int64_t i = 0; i < n; ++i) {
const int c = (b[i >> 1] >> ((i & 1) * 4)) & 15;
out[i] = (float)((c ^ 8) - 8);
}
return;
case RAD_U4:
for (int64_t i = 0; i < n; ++i) out[i] = (float)((b[i >> 1] >> ((i & 1) * 4)) & 15);
return;
case RAD_I8:
for (int64_t i = 0; i < n; ++i) out[i] = (float)(int8_t)b[i];
return;
case RAD_U8:
for (int64_t i = 0; i < n; ++i) out[i] = (float)b[i];
return;
case RAD_F8E4M3:
for (int64_t i = 0; i < n; ++i) out[i] = rad_fp8e4m3_to_f32(b[i]);
return;
default:
for (int64_t i = 0; i < n; ++i) out[i] = rad_load_f32(b, p.d->dtype, i);
return;
}
}
Rd plane(const EncodedView& v, int idx) {
Rd r;
if (idx >= 0) {
r.v = &v.plane[idx];
r.d = &v.enc.plane[idx];
}
return r;
}
/* Undo a "givens" transform on one row in place: w = v . G_S^T ... G_1^T . D^-1. */
int givens_inverse(const EncodedView& v, float* row, std::string* why) {
const Rd pairs = plane(v, rad_enc_find(&v.enc, "t.pairs"));
const Rd angle = plane(v, rad_enc_find(&v.enc, "t.angle"));
const Rd scale = plane(v, rad_enc_find(&v.enc, "t.scale"));
const int64_t S = pairs.v->rows, K = v.cols;
if (pairs.v->cols != K || angle.v->rows != S || angle.v->cols != K / 2 || (K & 1) ||
(scale && (scale.v->rows != 1 || scale.v->cols != K))) {
if (why) *why = fmt("a givens transform's tables do not fit a %lld-column row", K);
return RAD_E_SHAPE;
}
for (int64_t s = S - 1; s >= 0; --s)
for (int64_t p = 0; p < K / 2; ++p) {
const int64_t a = (int64_t)pairs.at(s, 2 * p), b = (int64_t)pairs.at(s, 2 * p + 1);
if (a < 0 || a >= K || b < 0 || b >= K || a == b) {
if (why) *why = fmt("givens stage %lld pairs columns %lld and %lld", s, a, b);
return RAD_E_SHAPE;
}
const double t = angle.at(s, p), c = std::cos(t), sn = std::sin(t);
const double x = row[a], y = row[b];
row[a] = (float)(c * x - sn * y);
row[b] = (float)(sn * x + c * y);
}
if (scale)
for (int64_t k = 0; k < K; ++k) row[k] /= scale.at(0, k);
return RAD_OK;
}
} /* namespace */
namespace {
std::mutex g_dec_mu;
std::vector<RadQuantDecodeFn> g_decoders;
} // namespace
void enc_add_decoder(RadQuantDecodeFn fn) {
if (!fn) return;
std::lock_guard<std::mutex> lk(g_dec_mu);
g_decoders.push_back(fn);
}
void enc_remove_decoder(RadQuantDecodeFn fn) {
std::lock_guard<std::mutex> lk(g_dec_mu);
g_decoders.erase(std::remove(g_decoders.begin(), g_decoders.end(), fn), g_decoders.end());
}
int enc_decode_rows(const EncodedView& v, int64_t row0, int64_t n, float* out, std::string* why) {
const RadEncoding& e = v.enc;
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. */
std::vector<RadQuantDecodeFn> fns;
{
std::lock_guard<std::mutex> lk(g_dec_mu);
fns = g_decoders;
}
RadQuantWeight w{};
w.name = "";
w.rank = 2;
w.shape[0] = v.rows;
w.shape[1] = v.cols;
w.rows = v.rows;
w.cols = v.cols;
w.layer = w.expert = -1;
const void* planes[RAD_ENC_MAX_PLANES] = {};
for (int k = 0; k < e.n_planes && k < RAD_ENC_MAX_PLANES; ++k) planes[k] = v.plane[k].data;
for (RadQuantDecodeFn fn : fns) {
const int st = fn(&e, &w, planes, row0, n, out);
if (st == RAD_E_UNSUPPORTED) continue;
if (st != RAD_OK && why)
*why = "the quantiser that decodes scheme '" + std::string(e.scheme) +
"' refused: " + rad_strerror(st);
return st;
}
if (why) *why = "scheme '" + std::string(e.scheme) + "' is a quantiser's own, and no "
"loaded quantiser decodes it; the core decodes only plain and affine";
return RAD_E_UNSUPPORTED;
}
if (!rad_enc_valid(&e)) {
if (why) *why = "the encoding " + enc_name(e) + " is not well formed";
return RAD_E_FORMAT;
}
const int64_t fw = rad_enc_fwht(&e);
if (fw > 0 && v.cols % fw != 0) {
if (why) *why = fmt("an fwht%lld transform does not divide a %lld-column row", fw, v.cols);
return RAD_E_SHAPE;
}
if (row0 < 0 || n < 0 || row0 + n > v.rows) return RAD_E_SHAPE;
const Rd codes = plane(v, 0);
const Rd grid = plane(v, rad_enc_find(&e, "grid"));
const Rd table = plane(v, rad_enc_find(&e, "table"));
const Rd signs = plane(v, rad_enc_find(&e, "signs"));
const Rd zero = plane(v, rad_enc_find(&e, "zero"));
std::vector<Rd> scales, mins;
for (int lv = 0;; ++lv) {
const int i = rad_enc_find_level(&e, "scale", lv);
if (i < 0) break;
scales.push_back(plane(v, i));
}
for (int lv = 0;; ++lv) {
const int i = rad_enc_find_level(&e, "min", lv);
if (i < 0) break;
mins.push_back(plane(v, i));
}
const int64_t V = rad_enc_code_width(&e);
const bool perm = !std::strcmp(e.transform, "perm");
const bool giv = !std::strcmp(e.transform, "givens");
const Rd pm = plane(v, perm ? rad_enc_find(&e, "t.perm") : -1);
if (perm && (pm.v->rows != 1 || pm.v->cols != v.cols)) {
if (why) *why = fmt("a perm transform's table is not one entry a column (%lld)", v.cols);
return RAD_E_SHAPE;
}
std::vector<float> tmp(perm ? (size_t)v.cols : 0);
/* 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. */
const bool direct = V <= 1 && !table && !signs && !zero && mins.empty() && scales.size() <= 1;
for (int64_t i = 0; i < n; ++i) {
const int64_t r = row0 + i;
float* o = out + i * v.cols;
if (direct) {
codes_row(codes, r, v.cols, o);
if (!scales.empty()) {
const Rd& s = scales[0];
const int64_t bc = s.d->block[1] > 0 ? s.d->block[1] : v.cols;
const int64_t sr = s.d->block[0] > 0 ? r / s.d->block[0] : 0;
for (int64_t c0 = 0; c0 < v.cols; c0 += bc) {
const float k = s.at(sr, s.d->block[1] > 0 ? c0 / bc : 0);
const int64_t c1 = std::min(c0 + bc, v.cols);
for (int64_t c = c0; c < c1; ++c) o[c] *= k;
}
}
}
for (int64_t c = 0; !direct && c < v.cols; ++c) {
float q;
if (V > 1) {
const int64_t code = (int64_t)codes.at(r, c / V);
if (code < 0 || code >= grid.v->rows) {
if (why) *why = fmt("row %lld: code %lld is outside a %lld-entry grid", r, code,
grid.v->rows);
return RAD_E_FORMAT;
}
q = grid.at(code, c % V);
} else {
q = codes.at(r, c);
if (table) {
const int64_t code = (int64_t)q;
if (code < 0 || code >= table.v->cols) {
if (why) *why = fmt("row %lld: code %lld is outside a %lld-entry table", r,
code, table.v->cols);
return RAD_E_FORMAT;
}
q = table.at(0, code);
}
}
if (signs && signs.cover(r, c) != 0.0f) q = -q;
if (zero) q -= zero.cover(r, c);
for (const Rd& s : scales) q *= s.cover(r, c);
if (!mins.empty()) {
float m = 1.0f;
for (const Rd& s : mins) m *= s.cover(r, c);
q -= m;
}
o[c] = q;
}
if (fw > 0) {
for (int64_t g = 0; g < v.cols; g += fw) fwht_inplace(o + g, fw);
} else if (perm) {
for (int64_t c = 0; c < v.cols; ++c) {
const int64_t to = (int64_t)pm.at(0, c);
if (to < 0 || to >= v.cols) {
if (why) *why = fmt("perm sends column %lld to %lld", c, to);
return RAD_E_FORMAT;
}
tmp[(size_t)to] = o[c];
}
std::memcpy(o, tmp.data(), (size_t)v.cols * sizeof(float));
} else if (giv) {
const int st = givens_inverse(v, o, why);
if (st != RAD_OK) return st;
}
}
return RAD_OK;
}
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) {
auto refuse = [&](std::string m) {
if (why) *why = std::move(m);
return RAD_E_SHAPE;
};
if (n_sel < 1 || n_sel > e.n_planes) return refuse("no planes are selected");
if (n_sel == 1) {
const RadEncPlane& p = e.plane[sel[0]];
const int64_t r = rows[0], c = cols[0];
if (r * c != n)
return refuse("its plane holds " + std::to_string(r * c) + " elements and the reader "
"wants " + std::to_string(n));
const int64_t rb = rad_enc_row_bytes(p.dtype, c);
const uint8_t* src = (const uint8_t*)data[0];
if (p.dtype == dt && rb == rad_dtype_bytes(dt, c)) {
std::memcpy(out, src, (size_t)(r * rb));
return RAD_OK;
}
for (int64_t i = 0; i < r; ++i)
for (int64_t j = 0; j < c; ++j)
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. */
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 &&
e.plane[sel[1]].kind == RAD_PLANE_TABLE && e.plane[sel[1]].extent[0] == 1) {
const RadEncPlane& pc = e.plane[sel[0]];
const RadEncPlane& pt = e.plane[sel[1]];
const int64_t r = rows[0], c = cols[0], entries = pt.extent[1];
if (r * c != n)
return refuse("its codes hold " + std::to_string(r * c) + " elements and the reader "
"wants " + std::to_string(n));
const int64_t rb = rad_enc_row_bytes(pc.dtype, c);
const uint8_t* src = (const uint8_t*)data[0];
for (int64_t i = 0; i < r; ++i)
for (int64_t j = 0; j < c; ++j) {
const int64_t code = (int64_t)rad_load_f32(src + i * rb, pc.dtype, j);
if (code < 0 || code >= entries)
return refuse("code " + std::to_string(code) + " indexes a table of " +
std::to_string(entries));
rad_store_f32(out, dt, i * c + j, rad_load_f32(data[1], pt.dtype, code));
}
return RAD_OK;
}
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. */
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)
return refuse("its planes do not tile the " + std::to_string(n) +
" elements the reader wants");
const int64_t c = n / r;
const void* d[RAD_ENC_MAX_PLANES] = {};
for (int k = 0; k < n_sel; ++k) d[sel[k]] = data[k];
EncodedView v;
enc_view(e, r, c, d, &v);
std::vector<float> f((size_t)n);
const int rc = enc_decode_rows(v, 0, r, f.data(), why);
if (rc != RAD_OK) return rc;
for (int64_t i = 0; i < n; ++i) rad_store_f32(out, dt, i, f[(size_t)i]);
return RAD_OK;
}
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) {
int64_t pr = 0, pc = 0;
rad_enc_plane_dims(&p, rows, cols, &pr, &pc);
if (p.kind == RAD_PLANE_TABLE) { /* every slice carries the whole table */
*out = PlaneRect{ 0, pr, 0, pc };
return RAD_OK;
}
auto cut = [&](int64_t lo, int64_t hi, int64_t extent, int64_t b, int64_t pext,
int64_t* e0, int64_t* en, const char* axis) -> bool {
if (lo < 0 || hi > extent || lo > hi) {
if (why) *why = std::string(axis) + fmt(" [%lld, %lld) is outside the weight's %lld",
lo, hi, extent);
return false;
}
if (b <= 0) { /* one element covers the whole extent: every slice has it */
*e0 = 0;
*en = pext;
return true;
}
if (lo % b != 0 || (hi % b != 0 && hi != extent)) {
if (why) *why = std::string(axis) + fmt(" [%lld, %lld) splits ", lo, hi) + "the '" +
p.role + fmt("' plane's %lld-wide blocks", b);
return false;
}
*e0 = lo / b;
*en = (hi + b - 1) / b - lo / b;
return true;
};
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. */
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) + " '" +
p.role + "' plane is not on a byte";
return RAD_E_SHAPE;
}
*out = r;
return RAD_OK;
}
} /* namespace rad */
+88
View File
@@ -0,0 +1,88 @@
/* encoding.h -- the core's half of a weight encoding: decoding one 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.
*/
#pragma once
#include "../rad_internal.h"
#include "rad_encoding.h"
#include "rad_quant.h"
#include <string>
namespace rad {
/* One whole plane of a weight, canonical: row-major, `row_bytes` a row. */
struct PlaneView {
const void* data = nullptr;
int64_t rows = 0, cols = 0; /* elements */
int64_t row_bytes = 0;
};
/* The planes of an encoding over a [rows, cols] weight, in the encoding's order. */
struct EncodedView {
RadEncoding enc{};
int64_t rows = 0, cols = 0; /* the logical view */
PlaneView plane[RAD_ENC_MAX_PLANES];
};
/* Fill `v`'s plane geometry for a weight of [rows, cols] in `e`, pointing plane i at `data[i]`. */
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. */
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. */
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. */
void fwht_inplace(float* v, int64_t n);
/* The canonical spelling of an encoding (rad_enc_format), as a string. */
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; 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. */
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);
/* ================================================================== slicing */
/* A rectangle of a plane, in that plane's elements. */
struct PlaneRect {
int64_t row0 = 0, rows = 0;
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. */
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);
} /* namespace rad */
+417
View File
@@ -0,0 +1,417 @@
/* 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.
*/
#include "imatrix.h"
#include <cerrno>
#include <cstring>
#include <fcntl.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <unistd.h>
namespace rad {
namespace {
/* GGUF's value type tags. Only what a walker needs 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
};
constexpr uint32_t GGML_TYPE_F32 = 0;
struct Cursor {
const uint8_t* p;
const uint8_t* end;
bool ok = true;
bool take(uint64_t n, const void** out = nullptr) {
if (!ok || (uint64_t)(end - p) < n) { ok = false; return false; }
if (out) *out = p;
p += n;
return true;
}
template <class T> bool get(T* out) {
const void* q = nullptr;
if (!take(sizeof(T), &q)) return false;
std::memcpy(out, q, sizeof(T));
return true;
}
bool str(std::string* out) {
uint64_t n = 0;
if (!get(&n)) return false;
const void* q = nullptr;
if (!take(n, &q)) return false;
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. */
bool skip_value(uint32_t type) {
switch (type) {
case GT_U8: case GT_I8: case GT_BOOL: return take(1);
case GT_U16: case GT_I16: return take(2);
case GT_U32: case GT_I32: case GT_F32: return take(4);
case GT_U64: case GT_I64: case GT_F64: return take(8);
case GT_STR: return str(nullptr);
case GT_ARR: {
uint32_t et = 0; uint64_t n = 0;
if (!get(&et) || !get(&n)) return false;
for (uint64_t i = 0; i < n && ok; ++i) if (!skip_value(et)) return false;
return ok;
}
default: ok = false; return false;
}
}
};
} /* namespace */
ImatrixFile::~ImatrixFile() { close(); }
void ImatrixFile::close() {
if (map_) ::munmap(map_, (size_t)map_bytes_);
if (fd_ >= 0) ::close(fd_);
map_ = nullptr; map_bytes_ = 0; fd_ = -1;
gguf_ = false;
entries_.clear(); index_.clear(); owned_.clear();
dataset_.clear(); path_.clear();
chunk_count_ = chunk_size_ = 0;
}
int ImatrixFile::open(const std::string& path) {
close();
path_ = path;
fd_ = ::open(path.c_str(), O_RDONLY | O_CLOEXEC);
if (fd_ < 0) { RAD_ERR("%s: %s", path.c_str(), std::strerror(errno)); return RAD_E_IO; }
struct stat st{};
if (::fstat(fd_, &st) != 0) { RAD_ERR("%s: %s", path.c_str(), std::strerror(errno));
close(); return RAD_E_IO; }
map_bytes_ = (uint64_t)st.st_size;
if (map_bytes_ < 8) {
RAD_ERR("%s: %llu bytes -- too short to be an imatrix", path.c_str(),
(unsigned long long)map_bytes_);
close();
return RAD_E_FORMAT;
}
void* m = ::mmap(nullptr, (size_t)map_bytes_, PROT_READ, MAP_PRIVATE, fd_, 0);
if (m == MAP_FAILED) { RAD_ERR("%s: mmap: %s", path.c_str(), std::strerror(errno));
close(); return RAD_E_IO; }
map_ = (uint8_t*)m;
int s;
if (std::memcmp(map_, "GGUF", 4) == 0) { gguf_ = true; s = read_gguf(map_, map_bytes_); }
else { gguf_ = false; s = read_legacy(map_, map_bytes_); }
if (s < 0) { close(); return s; }
for (size_t i = 0; i < entries_.size(); ++i) index_.emplace(entries_[i].name, i);
RAD_INFO("imatrix %s: %s, %zu tensor(s)%s", path.c_str(), gguf_ ? "gguf" : "legacy",
entries_.size(),
chunk_count_ ? fmt(", %lld chunks of %lld", (long long)chunk_count_,
(long long)chunk_size_).c_str() : "");
return RAD_OK;
}
/* ------------------------------------------------------------------ legacy */
int ImatrixFile::read_legacy(const uint8_t* p, uint64_t n) {
Cursor c{ p, p + n };
int32_t n_entries = 0;
if (!c.get(&n_entries) || n_entries <= 0 || n_entries > (1 << 20)) {
RAD_ERR("%s: not a legacy imatrix (entry count %d)", path_.c_str(), n_entries);
return RAD_E_FORMAT;
}
owned_.reserve((size_t)n_entries);
entries_.reserve((size_t)n_entries);
for (int32_t i = 0; i < n_entries; ++i) {
int32_t name_len = 0;
if (!c.get(&name_len) || name_len < 0 || (uint64_t)name_len > (uint64_t)(c.end - c.p)) {
RAD_ERR("%s: entry %d has a %d-byte name, which does not fit", path_.c_str(), i,
name_len);
return RAD_E_FORMAT;
}
const void* np = nullptr;
if (!c.take((uint64_t)name_len, &np)) break;
std::string name((const char*)np, (size_t)name_len);
int32_t ncall = 0, nval = 0;
if (!c.get(&ncall) || !c.get(&nval) || nval < 0) {
RAD_ERR("%s: entry '%s' is truncated", path_.c_str(), name.c_str());
return RAD_E_FORMAT;
}
const void* vp = nullptr;
if (!c.take((uint64_t)nval * sizeof(float), &vp)) {
RAD_ERR("%s: entry '%s' claims %d values, which run past the end of the file",
path_.c_str(), name.c_str(), nval);
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. */
owned_.emplace_back((size_t)nval);
std::memcpy(owned_.back().data(), vp, (size_t)nval * sizeof(float));
ImatrixEntry e;
e.name = std::move(name);
e.sum2 = owned_.back().data();
e.counts = nullptr;
e.cols = nval;
e.n_expert = 1;
e.ncall = ncall;
entries_.push_back(std::move(e));
}
if (!c.ok && entries_.empty()) {
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. */
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());
return RAD_OK;
}
/* ------------------------------------------------------------------ gguf */
int ImatrixFile::read_gguf(const uint8_t* p, uint64_t n) {
Cursor c{ p + 4, p + n };
uint32_t version = 0;
uint64_t n_tensors = 0, n_kv = 0;
if (!c.get(&version) || !c.get(&n_tensors) || !c.get(&n_kv)) {
RAD_ERR("%s: truncated GGUF header", path_.c_str());
return RAD_E_FORMAT;
}
if (version != 3) {
RAD_ERR("%s: GGUF version %u; this reader handles 3", path_.c_str(), version);
return RAD_E_FORMAT;
}
uint64_t alignment = 32; /* GGUF's default when general.alignment is absent */
for (uint64_t i = 0; i < n_kv; ++i) {
std::string key;
uint32_t type = 0;
if (!c.str(&key) || !c.get(&type)) {
RAD_ERR("%s: truncated at KV %llu", path_.c_str(), (unsigned long long)i);
return RAD_E_FORMAT;
}
if (key == "general.alignment" && type == GT_U32) {
uint32_t a = 0;
if (!c.get(&a)) break;
if (a == 0 || (a & (a - 1)) != 0) {
RAD_ERR("%s: general.alignment is %u, which is not a power of two", path_.c_str(), a);
return RAD_E_FORMAT;
}
alignment = a;
} else if (key == "imatrix.chunk_count" && type == GT_U32) {
uint32_t v = 0; if (!c.get(&v)) break; chunk_count_ = v;
} else if (key == "imatrix.chunk_size" && type == GT_U32) {
uint32_t v = 0; if (!c.get(&v)) break; chunk_size_ = v;
} else if (key == "imatrix.datasets" && type == GT_ARR) {
uint32_t et = 0; uint64_t cnt = 0;
if (!c.get(&et) || !c.get(&cnt)) break;
for (uint64_t k = 0; k < cnt && c.ok; ++k) {
if (et == GT_STR) { std::string s; if (!c.str(&s)) break;
if (dataset_.empty()) dataset_ = s; }
else if (!c.skip_value(et)) break;
}
} else if (!c.skip_value(type)) {
RAD_ERR("%s: KV '%s' has type %u, which this walker does not know how to step over",
path_.c_str(), key.c_str(), type);
return RAD_E_FORMAT;
}
}
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. */
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 "
"cannot hold that many tensor infos", path_.c_str(),
(unsigned long long)n_tensors, (unsigned long long)(c.end - c.p));
return RAD_E_FORMAT;
}
struct Info { std::string name; std::vector<uint64_t> dims; uint32_t type; uint64_t off; };
std::vector<Info> infos;
infos.reserve((size_t)n_tensors);
for (uint64_t i = 0; i < n_tensors; ++i) {
Info t{};
uint32_t nd = 0;
if (!c.str(&t.name) || !c.get(&nd) || nd > 4) {
RAD_ERR("%s: truncated or malformed tensor info %llu", path_.c_str(),
(unsigned long long)i);
return RAD_E_FORMAT;
}
t.dims.resize(nd);
for (uint32_t d = 0; d < nd; ++d) if (!c.get(&t.dims[d])) break;
if (!c.get(&t.type) || !c.get(&t.off)) {
RAD_ERR("%s: truncated tensor info for '%s'", path_.c_str(), t.name.c_str());
return RAD_E_FORMAT;
}
infos.push_back(std::move(t));
}
const uint64_t here = (uint64_t)(c.p - p);
const uint64_t data_start = (here + alignment - 1) / alignment * alignment;
if (data_start > n) {
RAD_ERR("%s: the data section starts past the end of the file", path_.c_str());
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. */
std::unordered_map<std::string, size_t> by_base;
struct Held { uint64_t sum2 = 0, counts = 0; };
std::vector<Held> held;
const uint64_t data_floats = (n - data_start) / sizeof(float);
for (const Info& t : infos) {
const bool is_sum2 = t.name.size() > 8 && t.name.compare(t.name.size() - 8, 8, ".in_sum2") == 0;
const bool is_counts = t.name.size() > 7 && t.name.compare(t.name.size() - 7, 7, ".counts") == 0;
if (!is_sum2 && !is_counts) continue;
if (t.type != GGML_TYPE_F32) {
RAD_WARN("%s: '%s' is ggml type %u, not f32 -- ignored", path_.c_str(),
t.name.c_str(), t.type);
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. */
uint64_t numel = 1;
bool fits = true;
for (uint64_t d : t.dims) if (d == 0) numel = 0;
for (uint64_t d : t.dims) {
if (numel == 0) break;
if (numel > data_floats / d) { fits = false; break; }
numel *= d;
}
const uint64_t bytes = numel * sizeof(float);
if (!fits || t.off > n - data_start || bytes > n - data_start - t.off) {
RAD_ERR("%s: '%s' runs past the end of the file", path_.c_str(), t.name.c_str());
return RAD_E_FORMAT;
}
const float* fp = (const float*)(p + data_start + t.off);
std::string base = t.name.substr(0, t.name.size() - (is_sum2 ? 8 : 7));
auto it = by_base.find(base);
if (it == by_base.end()) {
ImatrixEntry e;
e.name = base;
by_base.emplace(base, entries_.size());
it = by_base.find(base);
entries_.push_back(std::move(e));
held.emplace_back();
}
ImatrixEntry& e = entries_[it->second];
if (is_sum2) {
e.sum2 = fp;
e.cols = t.dims.empty() ? 0 : (int64_t)t.dims[0];
e.n_expert = t.dims.size() > 1 ? (int64_t)t.dims[1] : 1;
held[it->second].sum2 = numel;
} else {
e.counts = fp;
held[it->second].counts = numel;
}
}
/* 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. */
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. */
if (!e.sum2 || e.cols <= 0) {
RAD_WARN("%s: '%s' has counts but no .in_sum2 -- dropped", path_.c_str(),
e.name.c_str());
continue;
}
if (e.n_expert < 1 || (uint64_t)e.cols > held[k].sum2 / (uint64_t)e.n_expert) {
RAD_WARN("%s: '%s.in_sum2' claims %lld column(s) for %lld expert(s) and holds %llu "
"value(s) -- dropped", path_.c_str(), e.name.c_str(), (long long)e.cols,
(long long)e.n_expert, (unsigned long long)held[k].sum2);
continue;
}
if (e.counts && held[k].counts < (uint64_t)e.n_expert) {
RAD_WARN("%s: '%s.counts' holds %llu value(s) for %lld expert(s) -- ignored, so this "
"tensor contributes no expert profile", path_.c_str(), e.name.c_str(),
(unsigned long long)held[k].counts, (long long)e.n_expert);
e.counts = nullptr;
}
kept.push_back(std::move(e));
}
entries_ = std::move(kept);
return RAD_OK;
}
/* ------------------------------------------------------------------ queries */
const ImatrixEntry* ImatrixFile::find(const std::string& name) const {
auto it = index_.find(name);
return it == index_.end() ? nullptr : &entries_[it->second];
}
bool ImatrixFile::importance(const std::string& name, int64_t expert,
std::vector<float>* out) const {
const ImatrixEntry* e = find(name);
if (!e || !e->sum2 || e->cols <= 0 || expert < 0 || expert >= e->n_expert) return false;
if (!out) return true;
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. */
out->resize((size_t)e->cols);
std::memcpy(out->data(), src, (size_t)e->cols * sizeof(float));
double sum = 0.0;
for (float v : *out) sum += (double)v;
const double mean = sum / (double)e->cols;
if (!(mean > 0.0)) { std::fill(out->begin(), out->end(), 1.0f); return true; }
const float inv = (float)(1.0 / mean);
for (float& v : *out) v *= inv;
return true;
}
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;
float v = 0.0f;
std::memcpy(&v, e->counts + expert, sizeof v);
return (double)v;
}
} /* namespace rad */
+97
View File
@@ -0,0 +1,97 @@
/* imatrix.h -- llama.cpp's importance matrix, both of the 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:
*
* - 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.
*
* Two formats, because llama.cpp has written two and both are in the wild:
*
* 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.
*
* 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.
*/
#pragma once
#include "../rad_internal.h"
#include <string>
#include <unordered_map>
#include <vector>
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. */
struct ImatrixEntry {
std::string name; /* the checkpoint tensor name, suffix stripped */
const float* sum2 = nullptr; /* [n_expert][cols], expert-major and contiguous */
const float* counts = nullptr; /* [n_expert], or null in the legacy format */
int64_t cols = 0;
int64_t n_expert = 1; /* 1 for a dense tensor */
int64_t ncall = 0; /* legacy only: calls folded into sum2 */
};
class ImatrixFile {
public:
ImatrixFile() = default;
~ImatrixFile();
ImatrixFile(const ImatrixFile&) = delete;
ImatrixFile& operator=(const ImatrixFile&) = delete;
/* Sniffs the magic and picks a reader. RAD_E_FORMAT if it is neither. */
int open(const std::string& path);
void close();
const ImatrixEntry* find(const std::string& name) const;
const std::vector<ImatrixEntry>& entries() const { return entries_; }
const std::string& dataset() const { return dataset_; }
int64_t chunk_count() const { return chunk_count_; }
int64_t chunk_size() const { return chunk_size_; }
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. */
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. */
double count(const std::string& name, int64_t expert) const;
private:
int read_legacy(const uint8_t* p, uint64_t n);
int read_gguf(const uint8_t* p, uint64_t n);
int fd_ = -1;
uint8_t* map_ = nullptr;
uint64_t map_bytes_ = 0;
bool gguf_ = false;
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. */
std::vector<std::vector<float>> owned_;
std::vector<ImatrixEntry> entries_;
std::unordered_map<std::string, size_t> index_;
};
} /* namespace rad */
+45
View File
@@ -0,0 +1,45 @@
/* 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.
*/
#include "tunecache.h"
#include <cstring>
namespace rad {
std::string rad_machine_key() {
RadDeviceProps p{};
const int n = rad_dev_count();
/* 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) {
#if defined(__x86_64__)
return "host-x86_64";
#elif defined(__aarch64__)
return "host-aarch64";
#else
return "host-unknown";
#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;
for (char& c : name)
if (!((c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z')))
c = '_';
while (name.size() > 1 && name.back() == '_') name.pop_back();
if (name.empty()) name = "unknown";
const char* arch = p.arch[0] ? p.arch : "host";
return fmt("%s-x%d-%s", arch, n, name.c_str());
}
} /* namespace rad */
File diff suppressed because it is too large. Load diff
+373
View File
@@ -0,0 +1,373 @@
/* radfile.h -- the .rad reader and writer.
*
* 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:
*
* - 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.
*
* 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.
*/
#pragma once
#include "../rad_internal.h"
#include <functional>
#include <string>
#include <string_view>
#include <unordered_map>
#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:
*
* 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.
*
* 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.
*
* 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. */
struct VocabSection {
const RadVocabHeader* h = nullptr;
const rad_stroff* tok_text = nullptr; /* [n_tokens] */
const float* tok_score= nullptr; /* [n_tokens] or null */
const uint8_t* tok_type = nullptr; /* [n_tokens] or null */
const uint32_t* merges = nullptr; /* [n_merges][2] or null */
const RadVocabStep* steps = nullptr; /* [n_steps] or null */
explicit operator bool() const { return h != nullptr; }
};
/* ================================================================== reader */
class RadFile {
public:
RadFile() = default;
~RadFile();
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. */
int open(const char* path);
void close();
bool is_open() const { return base_ != nullptr; }
const char* path() const { return path_.c_str(); }
const RadFileHeader& header() const { return *hdr_; }
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. */
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. */
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. */
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. */
const char* str(rad_stroff off) const {
return (const char*)(base_ + hdr_->str_off + (off < str_bytes_ ? off : 0));
}
/* ------------------------------------------------------------ metadata */
int64_t meta_count() const { return (int64_t)hdr_->meta_count; }
const RadFileKV& meta_at(int64_t i) const { return meta_[i]; }
bool get_i(const char* key, int64_t* out) const;
bool get_f(const char* key, double* out) const;
const char* get_s(const char* key, const char* dflt = nullptr) const;
/* ------------------------------------------------------------ weight directory */
int64_t entry_count() const { return (int64_t)hdr_->dir_count; }
const RadFileEntry& entry(int64_t i) const { return dir_[i]; }
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. */
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];
}
const uint8_t* data(const RadFilePlane& p) const { return base_ + p.offset; }
int64_t encoding_count() const { return (int64_t)hdr_->enc_count; }
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. */
struct ExpertGroup {
int32_t layer = -1;
int32_t n_expert = 0;
int32_t n_slot = 0; /* gate/up/down = 3 */
int64_t first_index= 0; /* directory index of (expert 0, slot 0) */
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. */
uint64_t slot_off[8] = {0};
uint64_t slot_bytes[8] = {0};
};
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. */
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];
}
const RadFileEntry& expert_entry(const ExpertGroup& g, int32_t expert, int32_t slot) const {
return dir_[g.first_index + (int64_t)expert * g.n_slot + slot];
}
/* ------------------------------------------------------------ vocab and profile */
VocabSection vocab() const { return vocab_; }
int64_t profile_count() const { return (int64_t)hdr_->prof_count; }
const RadFileProfile* profile() const { return prof_; }
private:
int validate();
int index_experts();
std::string path_;
uint8_t* base_ = nullptr;
int64_t size_ = 0;
int fd_ = -1;
const RadFileHeader* hdr_ = nullptr;
const RadFileKV* meta_ = nullptr;
const RadFileEntry* dir_ = nullptr;
const RadFilePlane* planes_ = nullptr;
const RadEncoding* encs_ = nullptr;
const RadFileProfile* prof_ = nullptr;
uint64_t str_bytes_ = 1;
VocabSection vocab_;
std::vector<ExpertGroup> groups_;
std::unordered_map<std::string_view, int64_t> by_name_;
};
/* ================================================================== 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.
*
* 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.
*
* 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.
*/
class RadWriter {
public:
RadWriter() = default;
~RadWriter();
RadWriter(const RadWriter&) = delete;
RadWriter& operator=(const RadWriter&) = delete;
int begin(const char* path);
void abort(); /* discard, unlink both the target and the spill -- or, in
* append mode, cut the file back to its old length */
void set_arch(std::string_view s) { arch_ = s; }
void set_model_name(std::string_view s) { model_ = s; }
void set_quant(std::string_view s) { quant_ = s; }
void set_recipe(std::string_view s) { recipe_ = s; }
void set_created_by(std::string_view s) { created_by_ = s; }
void meta_i(std::string_view k, int64_t v);
void meta_f(std::string_view k, double v);
void meta_s(std::string_view k, std::string_view v);
struct Weight {
std::string name; /* the logical weight's name */
std::string quantizer; /* "" for the checkpoint's own planes */
std::string options; /* "k=v,k=v", sorted by key */
RadEncoding enc{};
uint32_t rank = 0;
int64_t shape[RAD_MAX_RANK] = {0}; /* logical */
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.
*
* 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. */
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. */
int64_t add_existing(const Weight& w, const RadFile& old, const RadFileEntry& e);
/* 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. */
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);
/* `bytes` of plane `k` of weight `idx`, at byte `off` within the plane. */
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. */
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. */
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(). */
int seal();
/* Writes the header and every table, then -- unsealed -- splices the spilled blob in at a
* 2 MiB boundary. */
int finish();
int64_t data_bytes() const { return blob_bytes_; }
int64_t weight_count() const { return (int64_t)dir_.size(); }
private:
rad_stroff intern(std::string_view s);
void layout(RadFileHeader* h);
uint32_t intern_encoding(const RadEncoding& e);
int check_unit_invariant(const Weight& w, uint64_t off, uint64_t unit_bytes);
std::string path_, spill_path_;
int fd_out_ = -1, fd_spill_ = -1;
int64_t spill_base_ = 0; /* where blob offset 0 is in fd_spill_: 0, append_base_ or
* the sealed data_off */
bool began_ = false;
bool sealed_ = false, late_ = false;
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. */
int finish_append();
int check_complete() const;
bool append_ = false;
int64_t old_size_ = 0, append_base_ = 0;
uint64_t old_data_off_ = 0;
RadFileHeader old_hdr_{};
std::vector<uint8_t> dir_abs_;
std::string arch_, model_, quant_, recipe_, created_by_;
std::string strblob_{std::string(1, '\0')};
std::unordered_map<std::string, rad_stroff> strmap_;
std::vector<RadFileKV> meta_;
std::vector<RadFileEntry> dir_;
std::vector<RadFilePlane> planes_;
std::vector<int64_t> written_; /* parallel to planes_ */
std::vector<RadEncoding> encs_;
std::vector<RadFileProfile> prof_;
/* The vocab section, assembled in memory and appended verbatim. */
std::vector<uint8_t> vocab_blob_;
bool have_vocab_ = false;
int64_t blob_bytes_ = 0; /* the blob's reserved length */
/* Movement-unit bookkeeping, so the fixed stride is a property the writer PROVES. */
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. */
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. */
std::string rad_unit_name(int32_t layer, int32_t expert);
} /* namespace rad */
+172
View File
@@ -0,0 +1,172 @@
/* recipe.cpp -- see recipe.h. */
#include "recipe.h"
#include <algorithm>
#include <cctype>
#include <cstdlib>
namespace rad {
std::string RecipeRule::options_text() const {
std::vector<std::pair<std::string, std::string>> o = options;
std::sort(o.begin(), o.end());
std::string s;
for (const auto& [k, v] : o) {
if (!s.empty()) s += ',';
s += k + "=" + v;
}
return s;
}
bool recipe_glob(const char* p, const char* n) {
/* Iterative, with one backtrack point: the last `*` and where it was tried from. */
const char *star = nullptr, *retry = nullptr;
while (*n) {
if (*p == '*') { star = p++; retry = n; continue; }
if (*p && (*p == '?' || *p == *n)) { ++p; ++n; continue; }
if (!star) return false;
p = star + 1;
n = ++retry;
}
while (*p == '*') ++p;
return *p == 0;
}
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. */
bool expand(const std::string& in, std::string* out, std::string* why) {
out->clear();
for (size_t i = 0; i < in.size(); ++i) {
if (in[i] != '$') { out->push_back(in[i]); continue; }
size_t b = i + 1, e;
const bool braced = b < in.size() && in[b] == '{';
if (braced) {
e = in.find('}', ++b);
if (e == std::string::npos) { *why = "an unclosed ${ in '" + in + "'"; return false; }
} else {
e = b;
while (e < in.size() && (std::isalnum((unsigned char)in[e]) || in[e] == '_')) ++e;
}
const std::string name = in.substr(b, e - b);
if (name.empty()) { *why = "a bare $ in '" + in + "'"; return false; }
const char* v = std::getenv(name.c_str());
if (!v) { *why = "$" + name + " is not set"; return false; }
out->append(v);
i = braced ? e : e - 1;
}
return true;
}
bool add_option(RecipeRule* r, const std::string& kv, std::string* why) {
const size_t eq = kv.find('=');
if (eq == std::string::npos || eq == 0) {
*why = "'" + kv + "' is not key=value";
return false;
}
std::string v;
if (!expand(kv.substr(eq + 1), &v, why)) return false;
for (const auto& o : r->options)
if (o.first == kv.substr(0, eq)) {
*why = "option '" + o.first + "' given twice";
return false;
}
r->options.emplace_back(kv.substr(0, eq), v);
return true;
}
} /* namespace */
int Recipe::add_text(const std::string& text, const std::string& origin, std::string* why) {
size_t at = 0;
int line = 0;
while (at <= text.size()) {
size_t nl = text.find('\n', at);
if (nl == std::string::npos) nl = text.size();
std::string l = text.substr(at, nl - at);
at = nl + 1;
++line;
const size_t hash = l.find('#');
if (hash != std::string::npos) l.resize(hash);
std::vector<std::string> words;
size_t i = 0;
while (i < l.size()) {
while (i < l.size() && std::isspace((unsigned char)l[i])) ++i;
const size_t s = i;
while (i < l.size() && !std::isspace((unsigned char)l[i])) ++i;
if (i > s) words.push_back(l.substr(s, i - s));
}
if (words.empty()) continue;
const std::string where = origin + ":" + std::to_string(line);
if (words.size() < 2) {
if (why) *why = where + ": a rule is PATTERN QUANTISER [key=value ...]";
return RAD_E_FORMAT;
}
RecipeRule r;
r.pattern = words[0];
r.quantizer = words[1];
r.origin = where;
for (size_t k = 2; k < words.size(); ++k) {
std::string w;
if (!add_option(&r, words[k], &w)) {
if (why) *why = where + ": " + w;
return RAD_E_FORMAT;
}
}
rules_.push_back(std::move(r));
}
return RAD_OK;
}
int Recipe::add_flag(const std::string& spec, std::string* why) {
const size_t eq = spec.find('=');
if (eq == std::string::npos || eq == 0) {
if (why) *why = "--quant '" + spec + "': PATTERN=QUANTISER[:key=value,...]";
return RAD_E_FORMAT;
}
RecipeRule r;
r.pattern = spec.substr(0, eq);
r.origin = "--quant";
const std::string rest = spec.substr(eq + 1);
const size_t colon = rest.find(':');
r.quantizer = rest.substr(0, colon);
if (r.quantizer.empty()) {
if (why) *why = "--quant '" + spec + "' names no quantiser";
return RAD_E_FORMAT;
}
if (colon != std::string::npos) {
const std::string opts = rest.substr(colon + 1);
size_t at = 0;
while (at <= opts.size()) {
size_t c = opts.find(',', at);
if (c == std::string::npos) c = opts.size();
std::string w;
if (c > at && !add_option(&r, opts.substr(at, c - at), &w)) {
if (why) *why = "--quant '" + spec + "': " + w;
return RAD_E_FORMAT;
}
at = c + 1;
}
}
rules_.push_back(std::move(r));
return RAD_OK;
}
const RecipeRule* Recipe::match(const std::string& name) const {
for (const RecipeRule& r : rules_)
if (recipe_glob(r.pattern.c_str(), name.c_str())) return &r;
return nullptr;
}
std::string Recipe::text() const {
std::string s;
for (const RecipeRule& r : rules_) {
s += r.pattern + " " + r.quantizer;
for (const auto& [k, v] : r.options) s += " " + k + "=" + v;
s += "\n";
}
return s;
}
} /* namespace rad */
+55
View File
@@ -0,0 +1,55 @@
/* 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:
*
* 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.
*/
#pragma once
#include "../rad_internal.h"
#include <string>
#include <utility>
#include <vector>
namespace rad {
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. */
std::string options_text() const;
};
/* Does `name` match glob `pattern`? */
bool recipe_glob(const char* pattern, const char* name);
class Recipe {
public:
/* Rules from a recipe file's text, appended. RAD_OK, or RAD_E_FORMAT with the line in `why`. */
int add_text(const std::string& text, const std::string& origin, std::string* why);
/* One rule in the command-line spelling, appended. */
int add_flag(const std::string& spec, std::string* why);
/* The rule that decides `name`, or null when none matches. */
const RecipeRule* match(const std::string& name) const;
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. */
std::string text() const;
private:
std::vector<RecipeRule> rules_;
};
} /* namespace rad */
+373
View File
@@ -0,0 +1,373 @@
/* 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.
*/
#include "safetensors.h"
#include <cerrno>
#include <cstdint>
#include <cstdlib>
#include <cstring>
#include <fcntl.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <unistd.h>
namespace rad {
namespace {
/* ------------------------------------------------------------------ a scanner, not a parser */
struct Scan {
const char* p;
const char* end;
std::string err;
void ws() { while (p < end && (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r')) ++p; }
bool eat(char c) { ws(); if (p < end && *p == c) { ++p; return true; } return false; }
bool peek(char c) { ws(); return p < end && *p == c; }
bool fail(const char* what, const char* base) {
if (err.empty()) err = fmt("%s at byte %lld of the header", what, (long long)(p - base));
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. */
bool str(std::string* out, const char* base) {
ws();
if (p >= end || *p != '"') return fail("expected a string", base);
++p;
out->clear();
while (p < end && *p != '"') {
if (*p != '\\') { out->push_back(*p++); continue; }
if (++p >= end) return fail("string ends inside an escape", base);
switch (*p++) {
case '"': out->push_back('"'); break;
case '\\': out->push_back('\\'); break;
case '/': out->push_back('/'); break;
case 'b': out->push_back('\b'); break;
case 'f': out->push_back('\f'); break;
case 'n': out->push_back('\n'); break;
case 'r': out->push_back('\r'); break;
case 't': out->push_back('\t'); break;
case 'u': {
if (end - p < 4) return fail("truncated \\u escape", base);
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. */
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 };
const unsigned lo = (unsigned)std::strtoul(lo_hex, nullptr, 16);
if (lo >= 0xDC00 && lo < 0xE000) {
cp = 0x10000u + ((cp - 0xD800u) << 10) + (lo - 0xDC00u);
p += 6;
}
}
if (cp < 0x80) out->push_back((char)cp);
else if (cp < 0x800) {
out->push_back((char)(0xC0 | (cp >> 6)));
out->push_back((char)(0x80 | (cp & 0x3F)));
} else if (cp < 0x10000) {
out->push_back((char)(0xE0 | (cp >> 12)));
out->push_back((char)(0x80 | ((cp >> 6) & 0x3F)));
out->push_back((char)(0x80 | (cp & 0x3F)));
} else {
out->push_back((char)(0xF0 | (cp >> 18)));
out->push_back((char)(0x80 | ((cp >> 12) & 0x3F)));
out->push_back((char)(0x80 | ((cp >> 6) & 0x3F)));
out->push_back((char)(0x80 | (cp & 0x3F)));
}
break;
}
default: return fail("unknown escape", base);
}
}
if (p >= end) return fail("unterminated string", base);
++p;
return true;
}
bool i64(int64_t* out, const char* base) {
ws();
const char* s = p;
if (p < end && (*p == '-' || *p == '+')) ++p;
if (p >= end || *p < '0' || *p > '9') return fail("expected an integer", base);
while (p < end && *p >= '0' && *p <= '9') ++p;
*out = std::strtoll(std::string(s, p - s).c_str(), nullptr, 10);
return true;
}
/* Skip one value of any type, so an unknown key inside a tensor object is survivable. */
bool skip(const char* base) {
ws();
if (p >= end) return fail("truncated", base);
if (*p == '"') { std::string t; return str(&t, base); }
if (*p == '{' || *p == '[') {
const char open = *p, close = (open == '{') ? '}' : ']';
int depth = 0;
while (p < end) {
if (*p == '"') { std::string t; if (!str(&t, base)) return false; continue; }
if (*p == open) ++depth;
else if (*p == close && --depth == 0) { ++p; return true; }
++p;
}
return fail("unbalanced brackets", base);
}
while (p < end && *p != ',' && *p != '}' && *p != ']') ++p;
return true;
}
};
/* safetensors names its dtypes; we name ours. The table is the only place the two meet. */
uint32_t st_dtype(const std::string& s) {
if (s == "BF16") return RAD_BF16;
if (s == "F16") return RAD_F16;
if (s == "F32") return RAD_F32;
if (s == "I8") return RAD_I8;
if (s == "U8") return RAD_U8;
if (s == "I16") return RAD_I16;
if (s == "I32") return RAD_I32;
if (s == "I64") return RAD_I64;
if (s == "U32") return RAD_U32;
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. */
return RAD_DT_INVALID;
}
} /* namespace */
SafeTensorsFile::~SafeTensorsFile() { close(); }
void SafeTensorsFile::close() {
if (map_) ::munmap(map_, (size_t)map_bytes_);
if (fd_ >= 0) ::close(fd_);
map_ = nullptr; map_bytes_ = 0; fd_ = -1;
tensors_.clear(); index_.clear(); metadata_.clear(); path_.clear();
}
int SafeTensorsFile::open(const std::string& path) {
close();
path_ = path;
fd_ = ::open(path.c_str(), O_RDONLY | O_CLOEXEC);
if (fd_ < 0) { RAD_ERR("%s: %s", path.c_str(), std::strerror(errno)); return RAD_E_IO; }
struct stat st{};
if (::fstat(fd_, &st) != 0) { RAD_ERR("%s: %s", path.c_str(), std::strerror(errno));
close(); return RAD_E_IO; }
map_bytes_ = (uint64_t)st.st_size;
if (map_bytes_ < 8) {
RAD_ERR("%s: %llu bytes -- too short to be safetensors", path.c_str(),
(unsigned long long)map_bytes_);
close();
return RAD_E_FORMAT;
}
void* m = ::mmap(nullptr, (size_t)map_bytes_, PROT_READ, MAP_PRIVATE, fd_, 0);
if (m == MAP_FAILED) { RAD_ERR("%s: mmap: %s", path.c_str(), std::strerror(errno));
close(); return RAD_E_IO; }
map_ = (uint8_t*)m;
uint64_t hlen = 0;
std::memcpy(&hlen, map_, 8);
if (hlen == 0 || hlen > map_bytes_ - 8) {
RAD_ERR("%s: header length %llu does not fit in a %llu-byte file", path.c_str(),
(unsigned long long)hlen, (unsigned long long)map_bytes_);
close();
return RAD_E_FORMAT;
}
const uint8_t* data_base = map_ + 8 + hlen;
const uint64_t data_bytes = map_bytes_ - 8 - hlen;
const char* base = (const char*)map_ + 8;
Scan sc{ base, base + hlen, {} };
if (!sc.eat('{')) { RAD_ERR("%s: the header is not a JSON object", path.c_str());
close(); return RAD_E_FORMAT; }
while (!sc.peek('}')) {
std::string name;
if (!sc.str(&name, base) || !sc.eat(':')) {
RAD_ERR("%s: %s", path.c_str(), sc.err.empty() ? "malformed header" : sc.err.c_str());
close();
return RAD_E_FORMAT;
}
if (name == "__metadata__") {
const char* s = sc.p;
if (!sc.skip(base)) { RAD_ERR("%s: %s", path.c_str(), sc.err.c_str());
close(); return RAD_E_FORMAT; }
metadata_.assign(s, sc.p - s);
if (!sc.eat(',')) break;
continue;
}
if (!sc.eat('{')) { RAD_ERR("%s: '%s' is not an object", path.c_str(), name.c_str());
close(); return RAD_E_FORMAT; }
StTensor t;
t.name = name;
int64_t off_begin = -1, off_end = -1;
while (!sc.peek('}')) {
std::string key;
if (!sc.str(&key, base) || !sc.eat(':')) {
RAD_ERR("%s: malformed entry for '%s'", path.c_str(), name.c_str());
close();
return RAD_E_FORMAT;
}
if (key == "dtype") {
if (!sc.str(&t.dtype_str, base)) { RAD_ERR("%s: %s", path.c_str(), sc.err.c_str());
close(); return RAD_E_FORMAT; }
t.dtype = st_dtype(t.dtype_str);
} else if (key == "shape") {
if (!sc.eat('[')) { RAD_ERR("%s: '%s'.shape is not an array", path.c_str(),
name.c_str()); close(); return RAD_E_FORMAT; }
while (!sc.peek(']')) {
int64_t d;
if (!sc.i64(&d, base)) { RAD_ERR("%s: %s", path.c_str(), sc.err.c_str());
close(); return RAD_E_FORMAT; }
t.shape.push_back(d);
if (!sc.eat(',')) break;
}
if (!sc.eat(']')) { RAD_ERR("%s: '%s'.shape is unterminated", path.c_str(),
name.c_str()); close(); return RAD_E_FORMAT; }
} else if (key == "data_offsets") {
if (!sc.eat('[') || !sc.i64(&off_begin, base) || !sc.eat(',') ||
!sc.i64(&off_end, base) || !sc.eat(']')) {
RAD_ERR("%s: '%s'.data_offsets is not [begin, end]", path.c_str(),
name.c_str());
close();
return RAD_E_FORMAT;
}
} else if (!sc.skip(base)) {
RAD_ERR("%s: %s", path.c_str(), sc.err.c_str());
close();
return RAD_E_FORMAT;
}
if (!sc.eat(',')) break;
}
if (!sc.eat('}')) { RAD_ERR("%s: entry for '%s' is unterminated", path.c_str(),
name.c_str()); close(); return RAD_E_FORMAT; }
if (off_begin < 0 || off_end < off_begin || (uint64_t)off_end > data_bytes) {
RAD_ERR("%s: '%s' spans [%lld, %lld) of a %llu-byte data section -- truncated",
path.c_str(), name.c_str(), (long long)off_begin, (long long)off_end,
(unsigned long long)data_bytes);
close();
return RAD_E_FORMAT;
}
t.offset = (uint64_t)off_begin;
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. */
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;
for (int64_t d : t.shape) {
if (!shape_ok || elems == 0) break;
if (elems > INT64_MAX / d) { shape_ok = false; break; }
elems *= d;
}
const int64_t want = shape_ok && t.dtype != RAD_DT_INVALID
? (elems > INT64_MAX / 64 ? -1 : rad_dtype_bytes(t.dtype, elems))
: 0;
if (!shape_ok || want < 0 ||
(t.dtype != RAD_DT_INVALID && (uint64_t)want != t.bytes)) {
std::string sh;
for (size_t k = 0; k < t.shape.size(); ++k)
sh += (k ? ", " : "") + std::to_string(t.shape[k]);
RAD_ERR("%s: '%s' is %s [%s], which is not the %llu bytes its data_offsets span. The "
"header disagrees with its own data; the file is damaged or was written by a "
"tool that does not follow the format -- fetch or export it again.",
path.c_str(), name.c_str(), t.dtype_str.c_str(), sh.c_str(),
(unsigned long long)t.bytes);
close();
return RAD_E_FORMAT;
}
index_.emplace(t.name, tensors_.size());
tensors_.push_back(std::move(t));
if (!sc.eat(',')) break;
}
if (!sc.eat('}')) {
RAD_ERR("%s: the header object is unterminated", path.c_str());
close();
return RAD_E_FORMAT;
}
RAD_DEBUG("%s: %zu tensor(s), %s of data", path.c_str(), tensors_.size(),
humanb((int64_t)data_bytes).c_str());
return RAD_OK;
}
const StTensor* SafeTensorsFile::find(const std::string& name) const {
auto it = index_.find(name);
return it == index_.end() ? nullptr : &tensors_[it->second];
}
int st_load_index(const std::string& path, std::unordered_map<std::string, std::string>* out) {
if (!out) return RAD_E_INVAL;
out->clear();
FILE* f = ::fopen(path.c_str(), "rb");
if (!f) {
if (errno == ENOENT) return RAD_E_NOTFOUND;
RAD_ERR("%s: %s", path.c_str(), std::strerror(errno));
return RAD_E_IO;
}
std::string buf;
char chunk[65536];
size_t n;
while ((n = ::fread(chunk, 1, sizeof chunk, f)) > 0) buf.append(chunk, n);
::fclose(f);
/* One key matters: "weight_map". Find it, then read the flat string->string object. */
size_t at = buf.find("\"weight_map\"");
if (at == std::string::npos) {
RAD_ERR("%s: no \"weight_map\" object", path.c_str());
return RAD_E_FORMAT;
}
at = buf.find('{', at);
if (at == std::string::npos) { RAD_ERR("%s: weight_map is not an object", path.c_str());
return RAD_E_FORMAT; }
const char* base = buf.data();
Scan sc{ buf.data() + at, buf.data() + buf.size(), {} };
if (!sc.eat('{')) return RAD_E_FORMAT;
while (!sc.peek('}')) {
std::string k, v;
if (!sc.str(&k, base) || !sc.eat(':') || !sc.str(&v, base)) {
RAD_ERR("%s: %s", path.c_str(), sc.err.empty() ? "malformed weight_map"
: sc.err.c_str());
return RAD_E_FORMAT;
}
out->emplace(std::move(k), std::move(v));
if (!sc.eat(',')) break;
}
RAD_DEBUG("%s: %zu tensor(s) across the shards", path.c_str(), out->size());
return RAD_OK;
}
} /* namespace rad */
+67
View File
@@ -0,0 +1,67 @@
/* safetensors.h -- an 8-byte length, a JSON object, and a blob.
*
* 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.
*/
#pragma once
#include "../rad_internal.h"
#include <string>
#include <unordered_map>
#include <vector>
namespace rad {
struct StTensor {
std::string name;
uint32_t dtype = RAD_DT_INVALID; /* RAD_* ; RAD_DT_INVALID if unrecognised */
std::string dtype_str; /* as written, for the diagnostic */
std::vector<int64_t> shape;
uint64_t offset = 0; /* relative to the data section */
uint64_t bytes = 0;
const uint8_t* data = nullptr;
int64_t numel() const {
if (shape.empty()) return 0;
int64_t n = 1;
for (int64_t d : shape) n *= d;
return n;
}
};
class SafeTensorsFile {
public:
SafeTensorsFile() = default;
~SafeTensorsFile();
SafeTensorsFile(const SafeTensorsFile&) = delete;
SafeTensorsFile& operator=(const SafeTensorsFile&) = delete;
int open(const std::string& path);
void close();
const StTensor* find(const std::string& name) const;
const std::vector<StTensor>& tensors() const { return tensors_; }
const std::string& metadata() const { return metadata_; }
const std::string& path() const { return path_; }
private:
int fd_ = -1;
uint8_t* map_ = nullptr;
uint64_t map_bytes_ = 0;
std::string path_, metadata_;
std::vector<StTensor> tensors_;
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. */
int st_load_index(const std::string& index_path,
std::unordered_map<std::string, std::string>* out);
} /* namespace rad */
+162
View File
@@ -0,0 +1,162 @@
/* share.cpp -- which bytes of a container entry one rank's declaration takes. See share.h. */
#include "share.h"
#include "encoding.h"
namespace rad {
int64_t PlaneShare::dense_bytes() const { return rows * rad_enc_row_bytes(dtype, cols); }
int weight_share(const WeightInfo& w, const RadEncoding& enc, uint32_t rank, const int64_t* shape,
int world, int index, PlaneShare out[RAD_ENC_MAX_PLANES], std::string* why) {
auto refuse = [&](const std::string& m) {
if (why) *why = m;
return RAD_E_SHAPE;
};
if (w.n_sel < 1 || w.n_sel > RAD_ENC_MAX_PLANES) return refuse("no planes selected");
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. */
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. */
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 &&
rad_dtype_bits(p0.dtype) >= 8 && R * C == w.sel_rows[0] * w.sel_cols[0]) {
R = w.sel_rows[0];
C = w.sel_cols[0];
}
}
int64_t VR = R, VC = C;
if (single) rad_enc_plane_dims(&enc.plane[w.sel[0]], R, C, &VR, &VC);
struct VRect { int64_t r0, r1, c0, c1; };
std::vector<VRect> view;
const bool span = w.shard_hi > 0;
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. */
uint32_t mat = rank;
for (uint32_t i = 1; i + 1 < rank; ++i)
if (shape[i] == 1) --mat;
if (mat > 2 || (rank == 1 && w.decl.shard == RAD_SHARD_COL))
return refuse(fmt("a %s shard of a rank-%u weight is not defined; declare it "
"RAD_SHARD_NONE", w.decl.shard == RAD_SHARD_ROW ? "ROW" : "COL",
rank));
const bool cols = w.decl.shard == RAD_SHARD_COL || rank == 1;
if (cols) {
int64_t c0 = w.shard_lo, c1 = w.shard_hi;
if (!span) {
if (VC % world) return refuse(fmt("%lld columns do not divide by %d ranks",
(long long)VC, world));
c0 = (int64_t)index * (VC / world);
c1 = c0 + VC / world;
}
if (c1 > VC) return refuse(fmt("the column span [%lld, %lld) is outside %lld",
(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. */
const int np = w.decl.n_row_parts > 1 ? w.decl.n_row_parts : 1;
if (span) {
if (VR % np) return refuse(fmt("%lld rows do not divide into %d parts",
(long long)VR, np));
const int64_t cpart = VR / np;
if (w.shard_hi > cpart)
return refuse(fmt("the row span [%lld, %lld) of each of %d part(s) does not "
"fit the entry's %lld rows", (long long)w.shard_lo,
(long long)w.shard_hi, np, (long long)VR));
for (int g = 0; g < np; ++g)
view.push_back({ g * cpart + w.shard_lo, g * cpart + w.shard_hi, 0, VC });
} else {
if (VR % world) return refuse(fmt("%lld rows do not divide by %d ranks",
(long long)VR, world));
const int64_t per = VR / world;
if (np == 1) {
view.push_back({ index * per, (index + 1) * per, 0, VC });
} else {
int64_t sum = 0;
for (int g = 0; g < np; ++g) sum += w.decl.row_parts[g];
if (sum != per)
return refuse(fmt("%d declared row parts sum to %lld, and the rank's share "
"of %lld rows at %d ranks is %lld", np, (long long)sum,
(long long)VR, world, (long long)per));
int64_t soff = 0;
for (int g = 0; g < np; ++g) {
const int64_t take = w.decl.row_parts[g];
view.push_back({ soff + index * take, soff + (index + 1) * take, 0, VC });
soff += take * world;
}
}
}
}
}
for (int k = 0; k < w.n_sel; ++k) {
const RadEncPlane& p = enc.plane[w.sel[k]];
PlaneShare& s = out[k];
s = PlaneShare{};
s.dtype = p.dtype;
int64_t pr = 0, pc = 0;
rad_enc_plane_dims(&p, R, C, &pr, &pc);
s.row_bytes = rad_enc_row_bytes(p.dtype, pc);
const int bits = rad_dtype_bits(p.dtype) > 0 ? rad_dtype_bits(p.dtype)
: 8 * (int)rad_dtype_bytes(p.dtype, 1);
PlaneRect last{ -1, -1, -1, -1 };
for (const VRect& q : view) {
PlaneRect pq;
if (single) {
pq = PlaneRect{ q.r0, q.r1 - q.r0, q.c0, q.c1 - q.c0 };
} else {
std::string m;
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. */
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. */
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),
rad_dtype_name(p.dtype), p.role));
if (!s.rects.empty() && pq.cols != s.cols)
return refuse("the share's parts differ in width");
PlaneShare::Rect r;
r.row0 = pq.row0;
r.rows = pq.rows;
r.byte0 = pq.col0 * bits / 8;
r.bytes = rad_enc_row_bytes(p.dtype, pq.cols);
s.rects.push_back(r);
s.rows += pq.rows;
s.cols = pq.cols;
}
if (s.rows != w.sel_rows[k] || s.cols != w.sel_cols[k])
return refuse(fmt("this rank's share of the '%s' plane is [%lld, %lld] and the "
"declaration says [%lld, %lld]", p.role, (long long)s.rows,
(long long)s.cols, (long long)w.sel_rows[k],
(long long)w.sel_cols[k]));
}
return RAD_OK;
}
} /* namespace rad */
+40
View File
@@ -0,0 +1,40 @@
/* 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.
*
* 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.
*/
#pragma once
#include "../rad_core.h"
#include <string>
#include <vector>
namespace rad {
/* One plane's share, as the rectangles of the plane that make it, in the order they lie end to
* end at the destination. A rectangle is `rows` rows from `row0`, and of each row the `bytes`
* bytes from `byte0`; a row of the plane is `row_bytes` long in the file. */
struct PlaneShare {
struct Rect { int64_t row0 = 0, rows = 0, byte0 = 0, bytes = 0; };
std::vector<Rect> rects;
uint32_t dtype = RAD_DT_INVALID;
int64_t rows = 0, cols = 0; /* the share's extents, in the plane's elements */
int64_t row_bytes = 0;
int64_t dense_bytes() const; /* the share laid out dense: rows * a row of `cols` */
};
/* This rank's share of every plane `w` selects, from an entry of encoding `enc` and logical
* shape (`rank`, `shape`), at tensor-parallel rank `index` of `world`. RAD_OK, or RAD_E_SHAPE with
* the reason in `why`: an extent that does not divide, a cut that splits a block or a byte, a
* share that is not what the declaration says. */
int weight_share(const WeightInfo& w, const RadEncoding& enc, uint32_t rank, const int64_t* shape,
int world, int index, PlaneShare out[RAD_ENC_MAX_PLANES], std::string* why);
} /* namespace rad */
+267
View File
@@ -0,0 +1,267 @@
/* 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.
*/
#include "tunecache.h"
#include <cstdlib>
#include <algorithm>
#include <cerrno>
#include <cstring>
#include <ctime>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
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. */
std::vector<std::string_view> split_ws_only(std::string_view s) {
std::vector<std::string_view> out;
size_t i = 0;
while (i < s.size()) {
while (i < s.size() && (s[i] == ' ' || s[i] == '\t')) ++i;
size_t j = i;
while (j < s.size() && s[j] != ' ' && s[j] != '\t') ++j;
if (j > i) out.push_back(s.substr(i, j - i));
i = j;
}
return out;
}
} /* namespace */
std::string TuneCache::rel_path(const std::string& machine) {
return "tune/" + machine + ".tune";
}
std::string TuneCache::path_for(const std::string& home, const std::string& machine) {
return home + "/" + rel_path(machine);
}
std::string TuneCache::now_iso8601() {
time_t t = ::time(nullptr);
struct tm g{};
::gmtime_r(&t, &g);
char buf[32];
::strftime(buf, sizeof buf, "%Y-%m-%dT%H:%M:%SZ", &g);
return buf;
}
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. */
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. */
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));
}
std::sort(kv.begin(), kv.end());
std::string out;
for (auto& s : kv) { if (!out.empty()) out += ' '; out += s; }
return out;
}
std::string TuneCache::canon_choice(const std::vector<std::pair<std::string, int64_t>>& c) {
std::vector<std::string> kv;
kv.reserve(c.size());
for (const auto& e : c) kv.push_back(fmt("%s=%lld", e.first.c_str(), (long long)e.second));
std::sort(kv.begin(), kv.end());
std::string out;
for (auto& s : kv) { if (!out.empty()) out += ','; out += s; }
return out;
}
std::vector<std::pair<std::string, int64_t>> TuneCache::parse_choice(std::string_view s) {
std::vector<std::pair<std::string, int64_t>> out;
if (s == "-") return out;
size_t i = 0;
while (i < s.size()) {
size_t comma = s.find(',', i);
if (comma == std::string_view::npos) comma = s.size();
std::string_view tok = s.substr(i, comma - i);
const size_t eq = tok.find('=');
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. */
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);
}
i = comma + 1;
}
return out;
}
std::string TuneCache::index_key(std::string_view k, std::string_view p, std::string_view g) {
std::string s;
s.reserve(k.size() + p.size() + g.size() + 2);
s.append(k); s.push_back('\x1f');
s.append(p); s.push_back('\x1f');
s.append(g);
return s;
}
const TuneRow* TuneCache::find(std::string_view k, std::string_view p, std::string_view g) const {
auto it = index_.find(index_key(k, p, g));
return it == index_.end() ? nullptr : &rows_[it->second];
}
void TuneCache::put(const TuneRow& r) {
std::string key = index_key(r.kernel, r.plugin, r.geom);
auto it = index_.find(key);
if (it != index_.end()) { rows_[it->second] = r; return; }
index_.emplace(std::move(key), rows_.size());
rows_.push_back(r);
}
int TuneCache::load(const std::string& home, const std::string& machine) {
rows_.clear();
index_.clear();
machine_ = 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. */
if (errno == ENOENT) return RAD_OK;
RAD_WARN("%s: %s", path.c_str(), std::strerror(errno));
return RAD_E_IO;
}
char line[4096];
int lineno = 0, bad = 0;
bool saw_magic = false;
while (::fgets(line, sizeof line, f)) {
++lineno;
std::string_view s(line);
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. */
auto tok = split_ws_only(s);
/* A line of blanks is a blank line, and 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);
::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());
::fclose(f);
return RAD_E_FORMAT;
}
saw_magic = true;
continue;
}
if (tok[0] == "machine") {
if (tok.size() >= 2 && std::string(tok[1]) != machine)
RAD_WARN("%s: measured on '%.*s' but this machine is '%s' -- the rows may not "
"describe this card", path.c_str(), (int)tok[1].size(), tok[1].data(),
machine.c_str());
continue;
}
if (tok.size() < 5) { ++bad; continue; }
TuneRow r;
r.kernel = std::string(tok[0]);
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]);
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; }
put(r);
}
::fclose(f);
if (!saw_magic) {
RAD_WARN("%s: empty or missing the 'radtune 2' line", path.c_str());
return RAD_E_FORMAT;
}
if (bad)
RAD_WARN("%s: %d malformed row(s) ignored. A cache is an optimisation; a typo in it must "
"not stop a server.", path.c_str(), bad);
RAD_DEBUG("tune cache %s: %zu row(s)", path.c_str(), rows_.size());
return RAD_OK;
}
int TuneCache::save(const std::string& home) const {
const std::string dir = home + "/tune";
const std::string path = path_for(home, machine_);
if (::mkdir(dir.c_str(), 0755) != 0 && errno != EEXIST) {
RAD_ERR("%s: %s", dir.c_str(), std::strerror(errno));
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. */
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; }
::fprintf(f, "radtune 2\n");
::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. */
std::vector<const TuneRow*> v;
v.reserve(rows_.size());
for (const auto& r : rows_) v.push_back(&r);
std::sort(v.begin(), v.end(), [](const TuneRow* a, const TuneRow* b) {
if (a->kernel != b->kernel) return a->kernel < b->kernel;
if (a->plugin != b->plugin) return a->plugin < b->plugin;
return a->geom < b->geom;
});
for (const TuneRow* r : v) {
if (r->kernel.find(' ') != std::string::npos ||
r->plugin.find(' ') != std::string::npos ||
r->choice.find(' ') != std::string::npos) {
RAD_WARN("tune cache: skipping '%s' -- a name with a space in it cannot be written "
"to a whitespace-delimited row", r->kernel.c_str());
continue;
}
::fprintf(f, "%s %s %s %.6f %s %s\n", r->kernel.c_str(), r->plugin.c_str(),
r->choice.empty() ? "-" : r->choice.c_str(), r->us,
r->measured.empty() ? "-" : r->measured.c_str(), r->geom.c_str());
}
if (::fflush(f) != 0 || ::fclose(f) != 0) {
RAD_ERR("%s: %s", tmp.c_str(), std::strerror(errno));
::unlink(tmp.c_str());
return RAD_E_IO;
}
if (::rename(tmp.c_str(), path.c_str()) != 0) {
RAD_ERR("%s -> %s: %s", tmp.c_str(), path.c_str(), std::strerror(errno));
::unlink(tmp.c_str());
return RAD_E_IO;
}
return RAD_OK;
}
} /* namespace rad */
+112
View File
@@ -0,0 +1,112 @@
/* tunecache.h -- the ONE 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.
*
* ================================================================= 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.
*
* line 1 `radtune 2` magic and format version
* line 2 `machine <machine-key>` must equal the reader's own key
* `#...` comment, ignored
* otherwise `<kernel> <plugin> <choice> <us> <measured> <geometry...>`
*
* 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.
* 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.
*
* 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.
*
* 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.
*/
#pragma once
#include "../rad_internal.h"
#include <string>
#include <utility>
#include <unordered_map>
#include <vector>
namespace rad {
struct TuneRow {
std::string kernel, plugin, choice, geom;
double us = 0.0;
std::string measured; /* ISO-8601 UTC, exactly as written */
};
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. */
int load(const std::string& radiance_home, const std::string& machine);
int save(const std::string& radiance_home) const;
const std::string& machine() const { return machine_; }
void set_machine(std::string m) { machine_ = std::move(m); }
const TuneRow* find(std::string_view kernel, std::string_view plugin,
std::string_view geom) const;
void put(const TuneRow& r);
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. */
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. */
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. */
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);
/* The same path relative to a home, for finding the first home on a search path that has one. */
static std::string rel_path(const std::string& machine);
static std::string now_iso8601();
private:
static std::string index_key(std::string_view kernel, std::string_view plugin,
std::string_view geom);
std::string machine_;
std::vector<TuneRow> rows_;
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. */
std::string rad_machine_key();
} /* namespace rad */