Archived
radiance 1.10.0
LoRA for image and video generators: - civitai and Hugging Face adapter files as published: kohya, ComfyUI and diffusers/PEFT key names; LoRA, LoCon, LoHa, LoKr and full-weight diffs; DoRA, OFT and Tucker are refused by name - stacked per request with a strength each, through the `loras` field or <lora:name:strength> tags in the prompt; --lora-dir serves every file in a directory, GET /v1/loras lists them, and --max-loras / --max-lora-rank size the slots on the card (generators default to rank 64) - Krea 2, Qwen-Image 2.1, FLUX.3 [klein], MiniMax H3, LTX-2.5, Anima and SDXL New models: - Anima (base, aesthetic and turbo): Cosmos-Predict2 DiT with the Qwen3-0.6B text encoder and the Qwen-Image VAE, on one card - Stable Diffusion XL and its single-file finetunes (Illustrious, NoobAI including V-Pred, Pony), read as civitai ships them, with the Euler, Euler a and DPM++ 2M samplers Recipes: - q38-27b-mxfp4-df2: any bf16 Qwen3.8-27B or finetune at MXFP4 with the DFlash2 drafter - Krea 2 finetunes from civitai: scripts/krea2_native.py reads Krea's own key names, and krea-2-fp8-unscaled keeps a plain-fp8 file's codes exactly Changes: --max-num-batched-tokens defaults to 2048 (was 8192). Plugin ABI 25: out-of-tree plugins must be rebuilt.
This commit is contained in:
1 parent
685ec5bd85
commit
4246a1dd04
124 files changed
+14326
-387
No files matched your search
+232
-7
@@ -628,6 +628,191 @@ int Checkpoint::open_diffusers() {
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* A single-file Stable Diffusion XL checkpoint in Stability's (sgm) layout, the form SDXL and its
|
||||
* finetunes (Illustrious, NoobAI, Pony and the rest) are published in: one safetensors holding
|
||||
*
|
||||
* model.diffusion_model.* the UNet, under the names it is trained and adapted
|
||||
* (LoRA) under, kept as they are;
|
||||
* conditioner.embedders.0.transformer.* CLIP ViT-L's text model, already in transformers'
|
||||
* CLIPTextModel names, kept;
|
||||
* conditioner.embedders.1.model.* OpenCLIP ViT-bigG's text tower in open_clip's names,
|
||||
* read as transformers' CLIPTextModelWithProjection
|
||||
* under conditioner.embedders.1.transformer.: each
|
||||
* block's fused in_proj split into q/k/v_proj (row
|
||||
* views, nothing copied), c_fc / c_proj as fc1 / fc2,
|
||||
* ln_1 / ln_2 / ln_final as layer_norm1 / layer_norm2 /
|
||||
* final_layer_norm, and the (in, out) text_projection
|
||||
* transposed into a linear's (out, in)
|
||||
* `text_projection.weight`;
|
||||
* first_stage_model.* the VAE, its decoder read in diffusers' AutoencoderKL
|
||||
* names under vae. (its 1 x 1 attention convolutions
|
||||
* keep their rank-4 shape).
|
||||
*
|
||||
* A `v_pred` tensor marks a v-prediction model and `ztsnr` one trained to a zero terminal SNR
|
||||
* (ComfyUI's convention): they become the `sdxl.prediction` and `sdxl.zero_snr` keys. The
|
||||
* architecture is `sdxl`. The checkpoint holds no tokenizer; rad-convert takes CLIP's with
|
||||
* --tokenizer. */
|
||||
int Checkpoint::open_sgm() {
|
||||
kind_ = SafeT;
|
||||
RAD_TRY(add_shard(path_));
|
||||
bool vpred = false, zsnr = false;
|
||||
std::vector<SrcTensor> add;
|
||||
std::vector<std::string> drop;
|
||||
auto rename = [&](const SrcTensor& t, const std::string& name) {
|
||||
SrcTensor v = t;
|
||||
v.name = name;
|
||||
add.push_back(std::move(v));
|
||||
drop.push_back(t.name);
|
||||
};
|
||||
const std::string g_old = "conditioner.embedders.1.model.";
|
||||
const std::string g_new = "conditioner.embedders.1.transformer.";
|
||||
const std::string tm = g_new + "text_model.";
|
||||
const std::string v_old = "first_stage_model.";
|
||||
for (const SrcTensor& t : tensors_) {
|
||||
const std::string& n = t.name;
|
||||
if (n == "v_pred") { vpred = true; continue; }
|
||||
if (n == "ztsnr") { zsnr = true; continue; }
|
||||
if (n.rfind(g_old, 0) == 0) {
|
||||
const std::string r = n.substr(g_old.size());
|
||||
if (r == "token_embedding.weight") {
|
||||
rename(t, tm + "embeddings.token_embedding.weight");
|
||||
} else if (r == "positional_embedding") {
|
||||
rename(t, tm + "embeddings.position_embedding.weight");
|
||||
} else if (r.rfind("ln_final.", 0) == 0) {
|
||||
rename(t, tm + "final_layer_norm." + r.substr(std::strlen("ln_final.")));
|
||||
} else if (r == "text_projection") {
|
||||
/* x @ P in open_clip; a linear's weight is P^T. */
|
||||
if (t.shape.size() != 2 || !t.data ||
|
||||
(t.rad_dtype != RAD_F16 && t.rad_dtype != RAD_BF16 && t.rad_dtype != RAD_F32)) {
|
||||
RAD_ERR("%s: '%s' is not a 2-D float matrix", path_.c_str(), n.c_str());
|
||||
return RAD_E_FORMAT;
|
||||
}
|
||||
const int64_t a = t.shape[0], b = t.shape[1];
|
||||
const int64_t es = rad_dtype_bytes(t.rad_dtype, 1);
|
||||
owned_.push_back(std::make_unique<uint8_t[]>((size_t)(a * b * es)));
|
||||
uint8_t* dst = owned_.back().get();
|
||||
const uint8_t* src = (const uint8_t*)t.data;
|
||||
for (int64_t i = 0; i < a; ++i)
|
||||
for (int64_t j = 0; j < b; ++j)
|
||||
std::memcpy(dst + (size_t)((j * a + i) * es),
|
||||
src + (size_t)((i * b + j) * es), (size_t)es);
|
||||
SrcTensor v = t;
|
||||
v.name = g_new + "text_projection.weight";
|
||||
v.shape = { b, a };
|
||||
v.data = dst;
|
||||
add.push_back(std::move(v));
|
||||
drop.push_back(n);
|
||||
} else if (r.rfind("transformer.resblocks.", 0) == 0) {
|
||||
/* transformer.resblocks.N.<rest> */
|
||||
const size_t p0 = std::strlen("transformer.resblocks.");
|
||||
const size_t dot = r.find('.', p0);
|
||||
if (dot == std::string::npos) continue;
|
||||
const std::string layer = tm + "encoder.layers." + r.substr(p0, dot - p0) + ".";
|
||||
const std::string rest = r.substr(dot + 1);
|
||||
if (rest == "attn.in_proj_weight" || rest == "attn.in_proj_bias") {
|
||||
const bool w = rest == "attn.in_proj_weight";
|
||||
if (t.shape.empty() || t.shape[0] % 3 || !t.data) {
|
||||
RAD_ERR("%s: '%s' does not split into q, k and v", path_.c_str(),
|
||||
n.c_str());
|
||||
return RAD_E_FORMAT;
|
||||
}
|
||||
const int64_t d = t.shape[0] / 3, rb = t.bytes / t.shape[0];
|
||||
const char* part[3] = { "q_proj", "k_proj", "v_proj" };
|
||||
for (int k = 0; k < 3; ++k) {
|
||||
SrcTensor v = t;
|
||||
v.name = layer + "self_attn." + part[k] + (w ? ".weight" : ".bias");
|
||||
v.shape[0] = d;
|
||||
v.bytes = rb * d;
|
||||
v.data = (const uint8_t*)t.data + (size_t)(k * d * rb);
|
||||
add.push_back(std::move(v));
|
||||
}
|
||||
drop.push_back(n);
|
||||
} else {
|
||||
static const std::pair<const char*, const char*> kMap[] = {
|
||||
{ "attn.out_proj.", "self_attn.out_proj." }, { "ln_1.", "layer_norm1." },
|
||||
{ "ln_2.", "layer_norm2." }, { "mlp.c_fc.", "mlp.fc1." },
|
||||
{ "mlp.c_proj.", "mlp.fc2." } };
|
||||
for (const auto& [from, to] : kMap)
|
||||
if (rest.rfind(from, 0) == 0) {
|
||||
rename(t, layer + to + rest.substr(std::strlen(from)));
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (n.rfind(v_old + "decoder.", 0) == 0 || n.rfind(v_old + "post_quant_conv.", 0) == 0) {
|
||||
/* diffusers' convert_ldm_vae_checkpoint, the decoder's half. */
|
||||
std::string r = n.substr(v_old.size());
|
||||
auto sub = [&](const std::string& from, const std::string& to) {
|
||||
const size_t at = r.find(from);
|
||||
if (at != std::string::npos) r.replace(at, from.size(), to);
|
||||
};
|
||||
sub("decoder.mid.block_1.", "decoder.mid_block.resnets.0.");
|
||||
sub("decoder.mid.block_2.", "decoder.mid_block.resnets.1.");
|
||||
sub("decoder.mid.attn_1.norm.", "decoder.mid_block.attentions.0.group_norm.");
|
||||
sub("decoder.mid.attn_1.q.", "decoder.mid_block.attentions.0.to_q.");
|
||||
sub("decoder.mid.attn_1.k.", "decoder.mid_block.attentions.0.to_k.");
|
||||
sub("decoder.mid.attn_1.v.", "decoder.mid_block.attentions.0.to_v.");
|
||||
sub("decoder.mid.attn_1.proj_out.", "decoder.mid_block.attentions.0.to_out.0.");
|
||||
sub("decoder.norm_out.", "decoder.conv_norm_out.");
|
||||
if (r.rfind("decoder.up.", 0) == 0) {
|
||||
/* up.i runs at the i-th resolution from the bottom of the encoder's pyramid;
|
||||
* up_blocks count in the order the decoder runs them. */
|
||||
const size_t p0 = std::strlen("decoder.up."), dot = r.find('.', p0);
|
||||
if (dot == std::string::npos) continue;
|
||||
const int i = std::atoi(r.substr(p0, dot - p0).c_str());
|
||||
std::string rest = r.substr(dot + 1);
|
||||
if (rest.rfind("block.", 0) == 0) rest = "resnets." + rest.substr(6);
|
||||
else if (rest.rfind("upsample.", 0) == 0) rest = "upsamplers.0." + rest.substr(9);
|
||||
r = "decoder.up_blocks." + std::to_string(3 - i) + "." + rest;
|
||||
}
|
||||
sub(".nin_shortcut.", ".conv_shortcut.");
|
||||
rename(t, "vae." + r);
|
||||
}
|
||||
}
|
||||
for (const std::string& n : drop) index_.erase(n);
|
||||
for (SrcTensor& v : add) {
|
||||
if (index_.count(v.name)) {
|
||||
RAD_ERR("%s: '%s' is read from two tensors", path_.c_str(), v.name.c_str());
|
||||
return RAD_E_FORMAT;
|
||||
}
|
||||
index_.emplace(v.name, tensors_.size());
|
||||
tensors_.push_back(std::move(v));
|
||||
}
|
||||
meta_.arch = "sdxl";
|
||||
const size_t slash = path_.find_last_of('/');
|
||||
meta_.name = slash == std::string::npos ? path_ : path_.substr(slash + 1);
|
||||
meta_.kv("sdxl.prediction", vpred ? "v" : "eps");
|
||||
meta_.kv("sdxl.zero_snr", zsnr ? "1" : "0");
|
||||
/* The typed dimensions are the conditioning network's, OpenCLIP bigG's text tower (as a
|
||||
* diffusers pipeline's are its text encoder's), read off its tensors. */
|
||||
{
|
||||
RadModelMeta& m = meta_.m;
|
||||
const SrcTensor* tok = find(tm + "embeddings.token_embedding.weight");
|
||||
const SrcTensor* fc1 = find(tm + "encoder.layers.0.mlp.fc1.weight");
|
||||
int64_t layers = 0;
|
||||
while (find(tm + "encoder.layers." + std::to_string(layers) + ".layer_norm1.weight"))
|
||||
++layers;
|
||||
if (!tok || tok->shape.size() != 2 || !fc1 || fc1->shape.size() != 2 || !layers) {
|
||||
RAD_ERR("%s: OpenCLIP bigG's text tower is incomplete", path_.c_str());
|
||||
return RAD_E_FORMAT;
|
||||
}
|
||||
m.n_layers = layers;
|
||||
m.n_embd = tok->shape[1];
|
||||
m.head_dim = 64;
|
||||
m.n_head = m.n_head_kv = m.n_embd / 64;
|
||||
m.n_ff = fc1->shape[0];
|
||||
m.n_vocab = tok->shape[0];
|
||||
m.n_ctx_train = 77;
|
||||
m.rms_eps = 1e-5f;
|
||||
m.rope_theta = 10000.0f;
|
||||
m.rope_scale = 1.0f;
|
||||
}
|
||||
meta_.finish();
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int Checkpoint::open_safetensors(const std::string& path) {
|
||||
kind_ = SafeT;
|
||||
/* One shard, an index, or the directory holding either, as one namespace. */
|
||||
@@ -644,15 +829,29 @@ int Checkpoint::open_safetensors(const std::string& path) {
|
||||
return open_diffusers();
|
||||
if (is_file) {
|
||||
shards.push_back(path);
|
||||
/* A single-file Stable Diffusion XL checkpoint, as Stability and every SDXL finetune
|
||||
* ship one: read by its own importer. */
|
||||
SafeTensorsFile probe;
|
||||
if (probe.open(path) == RAD_OK) {
|
||||
bool unet = false, bigg = false;
|
||||
for (const auto& t : probe.tensors()) {
|
||||
unet = unet || t.name == "model.diffusion_model.label_emb.0.0.weight";
|
||||
bigg = bigg ||
|
||||
t.name.rfind("conditioner.embedders.1.model.transformer.resblocks.", 0) == 0;
|
||||
}
|
||||
if (unet && bigg) return open_sgm();
|
||||
}
|
||||
} else {
|
||||
RAD_TRY(shard_list(dir_, is_index ? path : dir_ + "/model.safetensors.index.json",
|
||||
is_index, &shards, &owner));
|
||||
}
|
||||
for (const auto& sh : shards) RAD_TRY(add_shard(sh, "", owner.empty() ? nullptr : &owner));
|
||||
|
||||
RAD_TRY(meta_from_config_json(dir_, &meta_));
|
||||
RAD_TRY(meta_merge_generation_config(dir_, &meta_));
|
||||
RAD_TRY(meta_merge_preprocessor_configs(dir_, &meta_));
|
||||
const std::string& md = meta_dir_.empty() ? dir_ : meta_dir_;
|
||||
RAD_TRY(meta_from_config_json(md, &meta_));
|
||||
RAD_TRY(meta_merge_generation_config(md, &meta_));
|
||||
RAD_TRY(meta_merge_preprocessor_configs(md, &meta_));
|
||||
if (!meta_dir_.empty() && !path_exists(dir_ + "/tokenizer.json")) tok_dir_ = meta_dir_;
|
||||
if (!is_file && !is_index) RAD_TRY(add_companions());
|
||||
/* FP8's block, where the checkpoint states one. */
|
||||
if (const char* bs = meta_.get("quantization_config.weight_block_size")) {
|
||||
@@ -1301,6 +1500,17 @@ int Checkpoint::add_draft(const std::string& dir, const std::string& prefix) {
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int Checkpoint::add_file(const std::string& path) {
|
||||
if (kind_ != SafeT) {
|
||||
RAD_ERR("%s is merged into a safetensors checkpoint's namespace; %s is not one",
|
||||
path.c_str(), path_.c_str());
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
RAD_TRY(add_shard(path));
|
||||
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];
|
||||
@@ -1565,8 +1775,9 @@ static int resolve_wnorm(Checkpoint& ck, const RadNameMap& m, bool optional, Ckp
|
||||
}
|
||||
|
||||
/* RAD_MAP_TRANSPOSE (src[0] [.., a, b] read as [.., b, a]), RAD_MAP_EMA (src[0] the embedding
|
||||
* sums [bins, ...], src[1] the cluster usage [bins]; each row over max(usage, 1e-5)) and
|
||||
* RAD_MAP_TAP (one index of one dimension of src[0]), computed in f32 into `derived`. */
|
||||
* sums [bins, ...], src[1] the cluster usage [bins]; each row over max(usage, 1e-5)), RAD_MAP_TAP
|
||||
* (one index of one dimension of src[0]) and RAD_MAP_COLS (one column range of src[0]), computed in
|
||||
* f32 into `derived`. */
|
||||
static int resolve_derived(Checkpoint& ck, const std::vector<const RadNameMap*>& maps,
|
||||
bool optional, CkptWeight* out, std::string* why) {
|
||||
auto refuse = [&](int rc, std::string msg) {
|
||||
@@ -1630,7 +1841,21 @@ static int resolve_derived(Checkpoint& ck, const std::vector<const RadNameMap*>&
|
||||
return refuse(RAD_E_FORMAT, "'" + a->name + "' cannot be read as f32");
|
||||
out->rank = (uint32_t)rank;
|
||||
for (size_t i = 0; i < rank; ++i) out->shape[i] = a->shape[i];
|
||||
if (m.mode == RAD_MAP_TAP) {
|
||||
if (m.mode == RAD_MAP_COLS) {
|
||||
const int64_t cb = a->shape[rank - 1], c0 = m.src_index[0], nc = m.src_rows[0];
|
||||
if (c0 < 0 || nc <= 0 || c0 + nc > cb)
|
||||
return refuse(RAD_E_SHAPE, "columns [" + std::to_string(c0) + ", " +
|
||||
std::to_string(c0 + nc) + ") of '" + a->name + "', which "
|
||||
"has " + std::to_string(cb));
|
||||
const int64_t outer = n / cb;
|
||||
out->derived.resize((size_t)(outer * nc));
|
||||
for (int64_t o = 0; o < outer; ++o)
|
||||
std::memcpy(&out->derived[(size_t)(o * nc)], &src[(size_t)(o * cb + c0)],
|
||||
(size_t)nc * sizeof(float));
|
||||
out->shape[rank - 1] = nc;
|
||||
out->why = "it is columns [" + std::to_string(c0) + ", " + std::to_string(c0 + nc) +
|
||||
") of '" + a->name + "', at convert -- a recipe rule stores it";
|
||||
} else if (m.mode == RAD_MAP_TAP) {
|
||||
const int d = m.concat_dim;
|
||||
if (d < 0 || (size_t)d >= rank || rank < 3)
|
||||
return refuse(RAD_E_SHAPE, "'" + a->name + "' has rank " + std::to_string(rank) +
|
||||
@@ -1709,7 +1934,7 @@ int ckpt_resolve(Checkpoint& ck, const Program& prog, const std::string& name, b
|
||||
if (maps.front()->mode == RAD_MAP_WNORM)
|
||||
return resolve_wnorm(ck, *maps.front(), optional, out, why);
|
||||
if (maps.front()->mode == RAD_MAP_TRANSPOSE || maps.front()->mode == RAD_MAP_EMA ||
|
||||
maps.front()->mode == RAD_MAP_TAP)
|
||||
maps.front()->mode == RAD_MAP_TAP || maps.front()->mode == RAD_MAP_COLS)
|
||||
return resolve_derived(ck, maps, optional, out, why);
|
||||
struct Src1 { const char* name; int index; int64_t rows; };
|
||||
std::vector<Src1> srcs;
|
||||
|
||||
@@ -120,6 +120,14 @@ public:
|
||||
* borrows the target's embedding and head, so it goes into the target's container with its
|
||||
* tensors and config.json keys under `draft.`. */
|
||||
int add_draft(const std::string& dir, const std::string& prefix);
|
||||
/* Merge one more safetensors file, its tensor names kept: a release that ships its networks
|
||||
* as separate single files (ComfyUI's split_files: a diffusion model, a text encoder and a
|
||||
* VAE). A name already present is refused. */
|
||||
int add_file(const std::string& path);
|
||||
/* Before open(): read config.json, generation_config.json and the tokenizer from `dir` rather
|
||||
* than from beside the checkpoint, for a single-file checkpoint that ships none of them (the
|
||||
* text encoder's repository describes such a release). */
|
||||
void set_meta_dir(const std::string& dir) { meta_dir_ = dir; }
|
||||
|
||||
const SrcTensor* find(const std::string& n) const;
|
||||
const std::vector<SrcTensor>& tensors() const { return tensors_; }
|
||||
@@ -177,12 +185,13 @@ private:
|
||||
const std::unordered_map<std::string, std::string>* owner = nullptr);
|
||||
int open_safetensors(const std::string& path);
|
||||
int open_diffusers();
|
||||
int open_sgm();
|
||||
int add_companions();
|
||||
int open_gguf(const std::string& path);
|
||||
void detect_import();
|
||||
|
||||
enum Kind { None, Gguf, SafeT } kind_ = None;
|
||||
std::string path_, dir_, tok_dir_;
|
||||
std::string path_, dir_, tok_dir_, meta_dir_;
|
||||
GgufFile gguf_;
|
||||
MetaOwn meta_;
|
||||
std::vector<std::unique_ptr<SafeTensorsFile>> shards_;
|
||||
@@ -249,7 +258,7 @@ struct CkptWeight {
|
||||
* (the values change), so a recipe rule stores it. */
|
||||
bool wnorm = false;
|
||||
std::vector<float> wnorm_scale;
|
||||
/* A weight computed from its sources at resolve (RAD_MAP_TRANSPOSE, RAD_MAP_EMA): its f32
|
||||
/* A weight computed from its sources at resolve (RAD_MAP_TRANSPOSE, EMA, TAP, COLS): its f32
|
||||
* values in the logical shape, which ckpt_rows_f32 serves. Not trivial, so a recipe rule
|
||||
* stores it. */
|
||||
std::vector<float> derived;
|
||||
|
||||
+90
-51
@@ -40,6 +40,7 @@ void RadFile::close() {
|
||||
hdr_ = nullptr; meta_ = nullptr; dir_ = nullptr; planes_ = nullptr; encs_ = nullptr;
|
||||
prof_ = nullptr;
|
||||
vocab_ = VocabSection{};
|
||||
aux_vocab_ = VocabSection{};
|
||||
groups_.clear();
|
||||
by_name_.clear();
|
||||
path_.clear();
|
||||
@@ -197,6 +198,9 @@ int RadFile::validate() {
|
||||
if (!need(span_n(hdr_->prof_off, hdr_->prof_count, sizeof(RadFileProfile)),
|
||||
"the expert profile")) return RAD_E_FORMAT;
|
||||
if (!need(span_ok(hdr_->vocab_off, hdr_->vocab_bytes), "the vocab section")) return RAD_E_FORMAT;
|
||||
if (!need(span_ok(hdr_->reserved[RAD_HDR_AUX_VOCAB_OFF],
|
||||
hdr_->reserved[RAD_HDR_AUX_VOCAB_BYTES]), "the second vocab section"))
|
||||
return RAD_E_FORMAT;
|
||||
if (!need(span_ok(hdr_->data_off, hdr_->data_bytes), "the data blob")) return RAD_E_FORMAT;
|
||||
|
||||
if (hdr_->data_bytes && (hdr_->data_off % RAD_ALIGN_POOL) != 0) {
|
||||
@@ -312,22 +316,29 @@ int RadFile::validate() {
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- vocab */
|
||||
if (hdr_->vocab_bytes >= sizeof(RadVocabHeader)) {
|
||||
/* The section is read in place through typed pointers, so the header and every array must
|
||||
* be aligned to their element (the writer guarantees it). */
|
||||
if (hdr_->vocab_off % alignof(RadVocabHeader) != 0) {
|
||||
RAD_ERR("%s: the vocab section starts at %llu, which is not %zu-aligned", path_.c_str(),
|
||||
(unsigned long long)hdr_->vocab_off, alignof(RadVocabHeader));
|
||||
/* The vocab section, and the second one a generator may read its prompt through: the same
|
||||
* layout, each checked against its own extent. */
|
||||
auto read_vocab = [&](uint64_t voff, uint64_t vbytes, const char* what,
|
||||
VocabSection* out) -> int {
|
||||
if (vbytes == 0) return RAD_OK;
|
||||
if (vbytes < sizeof(RadVocabHeader)) {
|
||||
RAD_ERR("%s: the %s section is %llu bytes, shorter than its own header (%zu)",
|
||||
path_.c_str(), what, (unsigned long long)vbytes, sizeof(RadVocabHeader));
|
||||
return RAD_E_FORMAT;
|
||||
}
|
||||
const RadVocabHeader* v = (const RadVocabHeader*)(base_ + hdr_->vocab_off);
|
||||
/* The section is read in place through typed pointers, so the header and every array must
|
||||
* be aligned to their element (the writer guarantees it). */
|
||||
if (voff % alignof(RadVocabHeader) != 0) {
|
||||
RAD_ERR("%s: the %s section starts at %llu, which is not %zu-aligned", path_.c_str(),
|
||||
what, (unsigned long long)voff, alignof(RadVocabHeader));
|
||||
return RAD_E_FORMAT;
|
||||
}
|
||||
const RadVocabHeader* v = (const RadVocabHeader*)(base_ + voff);
|
||||
/* Offset 0 means an optional array is absent (scores are unigram-only; types default to
|
||||
* normal). Nothing real lives at file offset 0. */
|
||||
auto arr_ok = [&](uint64_t off, uint64_t bytes, size_t align) {
|
||||
return bytes == 0 || off == 0 ||
|
||||
(off >= hdr_->vocab_off &&
|
||||
off - hdr_->vocab_off <= hdr_->vocab_bytes &&
|
||||
bytes <= hdr_->vocab_bytes - (off - hdr_->vocab_off) &&
|
||||
(off >= voff && off - voff <= vbytes && bytes <= vbytes - (off - voff) &&
|
||||
off % align == 0);
|
||||
};
|
||||
const uint64_t nt = v->n_tokens, nm = v->n_merges, ns = v->n_steps;
|
||||
@@ -336,47 +347,50 @@ int RadFile::validate() {
|
||||
!arr_ok(v->tok_type_off, nt, 1) ||
|
||||
!arr_ok(v->merge_off, nm * 2 * sizeof(uint32_t), alignof(uint32_t)) ||
|
||||
!arr_ok(v->step_off, ns * sizeof(RadVocabStep), alignof(RadVocabStep))) {
|
||||
RAD_ERR("%s: the vocab section's arrays do not fit inside it, or one is not aligned "
|
||||
"to its element", path_.c_str());
|
||||
RAD_ERR("%s: the %s section's arrays do not fit inside it, or one is not aligned to its "
|
||||
"element",
|
||||
path_.c_str(), what);
|
||||
return RAD_E_FORMAT;
|
||||
}
|
||||
vocab_.h = v;
|
||||
vocab_.tok_text = (nt && v->tok_text_off) ? (const rad_stroff*)(base_ + v->tok_text_off) : nullptr;
|
||||
vocab_.tok_score = (nt && v->tok_score_off) ? (const float*)(base_ + v->tok_score_off) : nullptr;
|
||||
vocab_.tok_type = (nt && v->tok_type_off) ? (const uint8_t*)(base_ + v->tok_type_off) : nullptr;
|
||||
vocab_.merges = (nm && v->merge_off) ? (const uint32_t*)(base_ + v->merge_off) : nullptr;
|
||||
vocab_.steps = (ns && v->step_off) ? (const RadVocabStep*)(base_ + v->step_off) : nullptr;
|
||||
VocabSection& vs = *out;
|
||||
vs.h = v;
|
||||
vs.tok_text = (nt && v->tok_text_off) ? (const rad_stroff*)(base_ + v->tok_text_off) : nullptr;
|
||||
vs.tok_score = (nt && v->tok_score_off) ? (const float*)(base_ + v->tok_score_off) : nullptr;
|
||||
vs.tok_type = (nt && v->tok_type_off) ? (const uint8_t*)(base_ + v->tok_type_off) : nullptr;
|
||||
vs.merges = (nm && v->merge_off) ? (const uint32_t*)(base_ + v->merge_off) : nullptr;
|
||||
vs.steps = (ns && v->step_off) ? (const RadVocabStep*)(base_ + v->step_off) : nullptr;
|
||||
|
||||
if (vocab_.tok_text)
|
||||
if (vs.tok_text)
|
||||
for (uint64_t i = 0; i < nt; ++i)
|
||||
if (!str_ok(vocab_.tok_text[i])) {
|
||||
RAD_ERR("%s: vocab token %llu points outside the string blob", path_.c_str(),
|
||||
(unsigned long long)i);
|
||||
if (!str_ok(vs.tok_text[i])) {
|
||||
RAD_ERR("%s: %s token %llu points outside the string blob", path_.c_str(),
|
||||
what, (unsigned long long)i);
|
||||
return RAD_E_FORMAT;
|
||||
}
|
||||
if (vocab_.steps)
|
||||
if (vs.steps)
|
||||
for (uint64_t i = 0; i < ns; ++i)
|
||||
if (!str_ok(vocab_.steps[i].arg0) || !str_ok(vocab_.steps[i].arg1)) {
|
||||
RAD_ERR("%s: vocab step %llu points outside the string blob", path_.c_str(),
|
||||
if (!str_ok(vs.steps[i].arg0) || !str_ok(vs.steps[i].arg1)) {
|
||||
RAD_ERR("%s: %s step %llu points outside the string blob", path_.c_str(), what,
|
||||
(unsigned long long)i);
|
||||
return RAD_E_FORMAT;
|
||||
}
|
||||
if (vocab_.merges)
|
||||
if (vs.merges)
|
||||
for (uint64_t i = 0; i < nm * 2; ++i)
|
||||
if (vocab_.merges[i] >= nt) {
|
||||
RAD_ERR("%s: merge %llu names token %u of %llu", path_.c_str(),
|
||||
(unsigned long long)(i / 2), vocab_.merges[i], (unsigned long long)nt);
|
||||
if (vs.merges[i] >= nt) {
|
||||
RAD_ERR("%s: %s merge %llu names token %u of %llu", path_.c_str(), what,
|
||||
(unsigned long long)(i / 2), vs.merges[i], (unsigned long long)nt);
|
||||
return RAD_E_FORMAT;
|
||||
}
|
||||
if (!str_ok(v->chat_template)) {
|
||||
RAD_ERR("%s: the chat template offset is outside the string blob", path_.c_str());
|
||||
RAD_ERR("%s: the %s section's chat template offset is outside the string blob",
|
||||
path_.c_str(), what);
|
||||
return RAD_E_FORMAT;
|
||||
}
|
||||
} else if (hdr_->vocab_bytes != 0) {
|
||||
RAD_ERR("%s: the vocab section is %llu bytes, shorter than its own header (%zu)",
|
||||
path_.c_str(), (unsigned long long)hdr_->vocab_bytes, sizeof(RadVocabHeader));
|
||||
return RAD_E_FORMAT;
|
||||
}
|
||||
return RAD_OK;
|
||||
};
|
||||
RAD_TRY(read_vocab(hdr_->vocab_off, hdr_->vocab_bytes, "vocab", &vocab_));
|
||||
RAD_TRY(read_vocab(hdr_->reserved[RAD_HDR_AUX_VOCAB_OFF],
|
||||
hdr_->reserved[RAD_HDR_AUX_VOCAB_BYTES], "second vocab", &aux_vocab_));
|
||||
|
||||
return RAD_OK;
|
||||
}
|
||||
@@ -956,6 +970,29 @@ int RadWriter::check_complete() const {
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* A serialised vocab section's arrays rebased from section-relative to file offsets. */
|
||||
static void rebase_vocab(std::vector<uint8_t>& blob, uint64_t at) {
|
||||
auto* vh = (RadVocabHeader*)blob.data();
|
||||
if (vh->tok_text_off) vh->tok_text_off += at;
|
||||
if (vh->tok_score_off) vh->tok_score_off += at;
|
||||
if (vh->tok_type_off) vh->tok_type_off += at;
|
||||
if (vh->merge_off) vh->merge_off += at;
|
||||
if (vh->step_off) vh->step_off += at;
|
||||
}
|
||||
|
||||
int RadWriter::set_aux_vocab_section(const void* blob, int64_t bytes) {
|
||||
std::vector<uint8_t> keep;
|
||||
keep.swap(vocab_blob_);
|
||||
const bool had = have_vocab_;
|
||||
const int s = set_vocab_section(blob, bytes);
|
||||
keep.swap(vocab_blob_);
|
||||
have_vocab_ = had;
|
||||
if (s < 0) return s;
|
||||
aux_vocab_blob_.assign((const uint8_t*)blob, (const uint8_t*)blob + bytes);
|
||||
have_aux_vocab_ = true;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int RadWriter::set_vocab_section(const void* blob, int64_t bytes) {
|
||||
if (!began_ || sealed_) return RAD_E_STATE;
|
||||
if (!blob || bytes < (int64_t)sizeof(RadVocabHeader)) {
|
||||
@@ -1049,6 +1086,10 @@ void RadWriter::layout(RadFileHeader* hp) {
|
||||
h.enc_count = encs_.size();
|
||||
h.vocab_off = (uint64_t)place8((int64_t)vocab_blob_.size());
|
||||
h.vocab_bytes= have_vocab_ ? vocab_blob_.size() : 0;
|
||||
if (have_aux_vocab_) {
|
||||
h.reserved[RAD_HDR_AUX_VOCAB_OFF] = (uint64_t)place8((int64_t)aux_vocab_blob_.size());
|
||||
h.reserved[RAD_HDR_AUX_VOCAB_BYTES] = aux_vocab_blob_.size();
|
||||
}
|
||||
h.prof_off = (uint64_t)place8((int64_t)(prof_.size() * sizeof(RadFileProfile)));
|
||||
h.prof_count = prof_.size();
|
||||
|
||||
@@ -1095,14 +1136,8 @@ int RadWriter::finish() {
|
||||
* aligned within the blob, so alignment is preserved. */
|
||||
for (auto& e : dir_) e.offset += h.data_off;
|
||||
for (auto& p : planes_) p.offset += h.data_off;
|
||||
if (have_vocab_) {
|
||||
auto* vh = (RadVocabHeader*)vocab_blob_.data();
|
||||
if (vh->tok_text_off) vh->tok_text_off += h.vocab_off;
|
||||
if (vh->tok_score_off) vh->tok_score_off += h.vocab_off;
|
||||
if (vh->tok_type_off) vh->tok_type_off += h.vocab_off;
|
||||
if (vh->merge_off) vh->merge_off += h.vocab_off;
|
||||
if (vh->step_off) vh->step_off += h.vocab_off;
|
||||
}
|
||||
if (have_vocab_) rebase_vocab(vocab_blob_, h.vocab_off);
|
||||
if (have_aux_vocab_) rebase_vocab(aux_vocab_blob_, h.reserved[RAD_HDR_AUX_VOCAB_OFF]);
|
||||
|
||||
int st = RAD_OK;
|
||||
int64_t at = 0;
|
||||
@@ -1120,6 +1155,9 @@ int RadWriter::finish() {
|
||||
emit(planes_.data(), (int64_t)(planes_.size() * sizeof(RadFilePlane)), (int64_t)h.plane_off);
|
||||
emit(encs_.data(), (int64_t)(encs_.size() * sizeof(RadEncoding)), (int64_t)h.enc_off);
|
||||
if (have_vocab_) emit(vocab_blob_.data(), (int64_t)vocab_blob_.size(), (int64_t)h.vocab_off);
|
||||
if (have_aux_vocab_)
|
||||
emit(aux_vocab_blob_.data(), (int64_t)aux_vocab_blob_.size(),
|
||||
(int64_t)h.reserved[RAD_HDR_AUX_VOCAB_OFF]);
|
||||
emit(prof_.data(), (int64_t)(prof_.size() * sizeof(RadFileProfile)), (int64_t)h.prof_off);
|
||||
if (st < 0) { RAD_ERR("%s: %s", path_.c_str(), std::strerror(errno)); abort(); return st; }
|
||||
|
||||
@@ -1249,6 +1287,10 @@ int RadWriter::finish_append() {
|
||||
h.enc_count = encs_.size();
|
||||
h.vocab_off = (uint64_t)place8((int64_t)vocab_blob_.size());
|
||||
h.vocab_bytes= have_vocab_ ? vocab_blob_.size() : 0;
|
||||
if (have_aux_vocab_) {
|
||||
h.reserved[RAD_HDR_AUX_VOCAB_OFF] = (uint64_t)place8((int64_t)aux_vocab_blob_.size());
|
||||
h.reserved[RAD_HDR_AUX_VOCAB_BYTES] = aux_vocab_blob_.size();
|
||||
}
|
||||
h.prof_off = (uint64_t)place8((int64_t)(prof_.size() * sizeof(RadFileProfile)));
|
||||
h.prof_count = prof_.size();
|
||||
|
||||
@@ -1264,14 +1306,8 @@ int RadWriter::finish_append() {
|
||||
if (!dir_abs_[i])
|
||||
for (uint32_t k = 0; k < dir_[i].n_planes; ++k)
|
||||
planes_[dir_[i].plane_first + k].offset += (uint64_t)append_base_;
|
||||
if (have_vocab_) {
|
||||
auto* vh = (RadVocabHeader*)vocab_blob_.data();
|
||||
if (vh->tok_text_off) vh->tok_text_off += h.vocab_off;
|
||||
if (vh->tok_score_off) vh->tok_score_off += h.vocab_off;
|
||||
if (vh->tok_type_off) vh->tok_type_off += h.vocab_off;
|
||||
if (vh->merge_off) vh->merge_off += h.vocab_off;
|
||||
if (vh->step_off) vh->step_off += h.vocab_off;
|
||||
}
|
||||
if (have_vocab_) rebase_vocab(vocab_blob_, h.vocab_off);
|
||||
if (have_aux_vocab_) rebase_vocab(aux_vocab_blob_, h.reserved[RAD_HDR_AUX_VOCAB_OFF]);
|
||||
|
||||
int st = RAD_OK;
|
||||
auto put = [&](const void* p, int64_t bytes, uint64_t at) {
|
||||
@@ -1283,6 +1319,9 @@ int RadWriter::finish_append() {
|
||||
put(planes_.data(), (int64_t)(planes_.size() * sizeof(RadFilePlane)), h.plane_off);
|
||||
put(encs_.data(), (int64_t)(encs_.size() * sizeof(RadEncoding)), h.enc_off);
|
||||
if (have_vocab_) put(vocab_blob_.data(), (int64_t)vocab_blob_.size(), h.vocab_off);
|
||||
if (have_aux_vocab_)
|
||||
put(aux_vocab_blob_.data(), (int64_t)aux_vocab_blob_.size(),
|
||||
h.reserved[RAD_HDR_AUX_VOCAB_OFF]);
|
||||
put(prof_.data(), (int64_t)(prof_.size() * sizeof(RadFileProfile)), h.prof_off);
|
||||
if (st >= 0 && ::ftruncate(fd_out_, (off_t)off) != 0) st = RAD_E_IO;
|
||||
/* Make everything durable before the new header names it. */
|
||||
|
||||
@@ -141,6 +141,8 @@ public:
|
||||
|
||||
/* ------------------------------------------------------------ vocab and profile */
|
||||
VocabSection vocab() const { return vocab_; }
|
||||
/* The second vocab section, or an empty one (RAD_HDR_AUX_VOCAB_OFF in rad_format.h). */
|
||||
VocabSection aux_vocab() const { return aux_vocab_; }
|
||||
int64_t profile_count() const { return (int64_t)hdr_->prof_count; }
|
||||
const RadFileProfile* profile() const { return prof_; }
|
||||
|
||||
@@ -161,7 +163,7 @@ private:
|
||||
const RadFileProfile* prof_ = nullptr;
|
||||
uint64_t str_bytes_ = 1;
|
||||
|
||||
VocabSection vocab_;
|
||||
VocabSection vocab_, aux_vocab_;
|
||||
std::vector<ExpertGroup> groups_;
|
||||
std::unordered_map<std::string_view, int64_t> by_name_;
|
||||
};
|
||||
@@ -244,6 +246,8 @@ public:
|
||||
/* The serialised vocab section. Its internal offsets must be section-relative (serialise with
|
||||
* section_file_off 0); finish() rebases them, as it does the directory. */
|
||||
int set_vocab_section(const void* blob, int64_t bytes);
|
||||
/* The second vocab section (RAD_HDR_AUX_VOCAB_OFF), serialised the same way. */
|
||||
int set_aux_vocab_section(const void* blob, int64_t bytes);
|
||||
|
||||
void add_profile(int32_t layer, int32_t expert, float share);
|
||||
|
||||
@@ -301,6 +305,8 @@ private:
|
||||
/* The vocab section, assembled in memory and appended verbatim. */
|
||||
std::vector<uint8_t> vocab_blob_;
|
||||
bool have_vocab_ = false;
|
||||
std::vector<uint8_t> aux_vocab_blob_;
|
||||
bool have_aux_vocab_ = false;
|
||||
|
||||
int64_t blob_bytes_ = 0; /* the blob's reserved length */
|
||||
|
||||
|
||||
Reference in new issue
Block a user