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
@@ -125,6 +125,9 @@ public:
|
||||
int declare_pooled(rad_buf b);
|
||||
int declare_drafter(const RadDrafterDecl* d);
|
||||
int drafter_shared_kv(int pos_offset);
|
||||
int lora_root(const char* native, const char* spellings);
|
||||
int lora_alias(const char* native, const char* from, const char* to, int64_t from_lo,
|
||||
int64_t from_hi, int64_t to_lo);
|
||||
int declare_encoder(const RadEncoderDecl* d);
|
||||
int declare_generator(const RadGeneratorDecl* d);
|
||||
int declare_audio_generator(const RadAudioGenDecl* d);
|
||||
|
||||
+135
-10
@@ -942,7 +942,7 @@ int Builder::decl_name_map(const RadNameMap* m) {
|
||||
}
|
||||
if (m->mode != RAD_MAP_COPY && m->mode != RAD_MAP_CONCAT && m->mode != RAD_MAP_WNORM &&
|
||||
m->mode != RAD_MAP_ROWS && m->mode != RAD_MAP_TRANSPOSE && m->mode != RAD_MAP_EMA &&
|
||||
m->mode != RAD_MAP_TAP) {
|
||||
m->mode != RAD_MAP_TAP && m->mode != RAD_MAP_COLS) {
|
||||
err(RAD_E_INVAL, "name map for '%s': unknown mode %d", m->declared, m->mode);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
@@ -953,9 +953,11 @@ int Builder::decl_name_map(const RadNameMap* m) {
|
||||
: "the magnitude and the direction", m->n_src);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if ((m->mode == RAD_MAP_TRANSPOSE || m->mode == RAD_MAP_TAP) && m->n_src != 1) {
|
||||
if ((m->mode == RAD_MAP_TRANSPOSE || m->mode == RAD_MAP_TAP || m->mode == RAD_MAP_COLS) &&
|
||||
m->n_src != 1) {
|
||||
err(RAD_E_INVAL, "name map for '%s': a %s map names one source, not %d", m->declared,
|
||||
m->mode == RAD_MAP_TAP ? "tap" : "transpose", m->n_src);
|
||||
m->mode == RAD_MAP_TAP ? "tap" : m->mode == RAD_MAP_COLS ? "column" : "transpose",
|
||||
m->n_src);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
|
||||
@@ -984,14 +986,20 @@ int Builder::decl_name_map(const RadNameMap* m) {
|
||||
m->declared, i, m->src_index[i], (long long)m->src_rows[i]);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (m->mode == RAD_MAP_COLS && (m->src_index[0] < 0 || m->src_rows[0] <= 0)) {
|
||||
err(RAD_E_INVAL, "name map for '%s': the column range starts at %d and holds %lld columns",
|
||||
m->declared, m->src_index[0], (long long)m->src_rows[0]);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
|
||||
/* A CONCAT map may be declared in pieces; any other repeat is an error.
|
||||
/* A CONCAT, ROWS or EMA map may be declared in pieces; any other repeat is an error.
|
||||
*
|
||||
* `src[8]` is the ABI's cap, and a sharded checkpoint exceeds it: Qwen3.8-Flash-Next stores
|
||||
* its n-gram embedding as 128 tensors `...ngram_embedding.shard_K.weight`. Growing the array
|
||||
* would cost ~80 MB of Program (one map per declared weight, ~50K weights). So successive
|
||||
* CONCAT maps for one name extend it in call order, and rad-convert joins their sources end
|
||||
* to end (map_concat_shards() in arch/common/rad_arch.h).
|
||||
* to end (map_concat_shards() in arch/common/rad_arch.h). ROWS maps extend the same way (a
|
||||
* row permutation is one piece a row).
|
||||
*
|
||||
* Other repeats are refused: a lookup built with std::map::emplace would silently keep the
|
||||
* first, so a copy-paste mistake would convert weights from the wrong tensors. */
|
||||
@@ -999,11 +1007,12 @@ int Builder::decl_name_map(const RadNameMap* m) {
|
||||
if (seen != name_map_first_.end()) {
|
||||
const RadNameMap& first = prog_.name_map[seen->second];
|
||||
const bool joins = (c.mode == RAD_MAP_CONCAT && first.mode == RAD_MAP_CONCAT) ||
|
||||
(c.mode == RAD_MAP_EMA && first.mode == RAD_MAP_EMA);
|
||||
(c.mode == RAD_MAP_EMA && first.mode == RAD_MAP_EMA) ||
|
||||
(c.mode == RAD_MAP_ROWS && first.mode == RAD_MAP_ROWS);
|
||||
if (!joins) {
|
||||
err(RAD_E_INVAL, "name map for '%s': declared twice, and only a CONCAT or EMA map may "
|
||||
"be extended -- a repeated COPY map means two sources for one weight, "
|
||||
"and which one wins is not something a declaration can express",
|
||||
err(RAD_E_INVAL, "name map for '%s': declared twice, and only a CONCAT, ROWS or EMA "
|
||||
"map may be extended -- a repeated COPY map means two sources for one "
|
||||
"weight, and which one wins is not something a declaration can express",
|
||||
c.declared);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
@@ -1232,7 +1241,32 @@ int Builder::declare_generator(const RadGeneratorDecl* d) {
|
||||
(long long)d->default_height, (long long)d->max_lanes);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (d->n_sigmas < 0 || (d->n_sigmas > 0 && !d->sigmas) ||
|
||||
if (d->train_steps < 0) {
|
||||
err(RAD_E_INVAL, "declare_generator '%s': train_steps %d is negative", nm,
|
||||
(int)d->train_steps);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (d->train_steps > 0) {
|
||||
/* A discrete-time denoiser: its own schedule, a sampler it serves by default. */
|
||||
const uint32_t all = (1u << RAD_GEN_SAMPLER_COUNT) - 1;
|
||||
if (d->train_steps < 2 || !(d->beta_start > 0) || !(d->beta_end > d->beta_start) ||
|
||||
!(d->beta_end < 1) ||
|
||||
(d->beta_schedule != RAD_GEN_BETAS_SCALED_LINEAR &&
|
||||
d->beta_schedule != RAD_GEN_BETAS_LINEAR) ||
|
||||
d->n_sigmas != 0 || d->default_steps <= 0 || (d->samplers & ~all) || !d->samplers ||
|
||||
d->default_sampler < 0 || d->default_sampler >= RAD_GEN_SAMPLER_COUNT ||
|
||||
!(d->samplers & (1u << d->default_sampler)) || d->default_scheduler < 0 ||
|
||||
d->default_scheduler >= RAD_GEN_SCHED_COUNT ||
|
||||
!(d->default_cfg >= (d->cfg_original ? 0.0 : 1.0))) {
|
||||
err(RAD_E_INVAL, "declare_generator '%s': the discrete-time sampler is incomplete (%d "
|
||||
"timesteps, betas %g..%g kind %d, %lld default steps, samplers 0x%x "
|
||||
"default %d, scheduler %d, %d fixed sigmas, guidance %g)", nm,
|
||||
(int)d->train_steps, d->beta_start, d->beta_end, (int)d->beta_schedule,
|
||||
(long long)d->default_steps, (unsigned)d->samplers, (int)d->default_sampler,
|
||||
(int)d->default_scheduler, (int)d->n_sigmas, d->default_cfg);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
} else if (d->n_sigmas < 0 || (d->n_sigmas > 0 && !d->sigmas) ||
|
||||
(d->n_sigmas == 0 && d->default_steps <= 0) ||
|
||||
!(d->default_cfg >= (d->cfg_original ? 0.0 : 1.0)) ||
|
||||
(d->dyn_shift && (d->max_seq <= d->base_seq || d->base_seq <= 0)) ||
|
||||
@@ -1244,6 +1278,23 @@ int Builder::declare_generator(const RadGeneratorDecl* d) {
|
||||
d->shift_terminal, d->default_cfg);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (d->sigma_grid < 0 || d->min_tokens < 0 || (d->aux_tokens && d->aux_max_tokens <= 0)) {
|
||||
err(RAD_E_INVAL, "declare_generator '%s': sigma_grid %d, min_tokens %d and a second "
|
||||
"tokenizer of at most %lld tokens are not a schedule and a prompt it can "
|
||||
"read", nm, (int)d->sigma_grid, (int)d->min_tokens,
|
||||
(long long)d->aux_max_tokens);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (d->chunk_tokens < 0 ||
|
||||
(d->chunk_tokens > 0 &&
|
||||
(!joint || d->pad_multiple != 0 || d->pad_token < 0 || d->chunk_bos < 0 ||
|
||||
d->chunk_eos < 0 || d->cond_rows % (d->chunk_tokens + 2) != 0))) {
|
||||
err(RAD_E_INVAL, "declare_generator '%s': a prompt in windows of %d tokens needs the joint "
|
||||
"layout without pad_multiple, bos, eos and pad tokens, and cond_rows a "
|
||||
"whole number of windows (cond_rows %lld)", nm, (int)d->chunk_tokens,
|
||||
(long long)d->cond_rows);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
for (int i = 0; i < d->n_sigmas; ++i)
|
||||
if (!(d->sigmas[i] > 0.0 && d->sigmas[i] <= 1.0) ||
|
||||
(i > 0 && !(d->sigmas[i] < d->sigmas[i - 1]))) {
|
||||
@@ -1764,6 +1815,69 @@ int Builder::drafter_shared_kv(int pos_offset) {
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int Builder::lora_root(const char* native, const char* spellings) {
|
||||
if (finished_) {
|
||||
err(RAD_E_STATE, "lora_root after declare finished");
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
if (!native || !*native) {
|
||||
err(RAD_E_INVAL, "lora_root: an empty checkpoint prefix would put every tensor in one "
|
||||
"network; name the prefix the network's tensors share");
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
for (const LoraRoot& r : prog_.lora_roots)
|
||||
if (r.native == native) {
|
||||
err(RAD_E_INVAL, "lora_root '%s' declared twice", native);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
LoraRoot r;
|
||||
r.native = native;
|
||||
std::string cur;
|
||||
for (const char* p = spellings ? spellings : "";; ++p) {
|
||||
if (*p && *p != ' ') { cur += *p; continue; }
|
||||
if (!cur.empty()) r.spellings.push_back(cur == "-" ? std::string() : cur);
|
||||
cur.clear();
|
||||
if (!*p) break;
|
||||
}
|
||||
prog_.lora_roots.push_back(std::move(r));
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int Builder::lora_alias(const char* native, const char* from, const char* to, int64_t from_lo,
|
||||
int64_t from_hi, int64_t to_lo) {
|
||||
if (finished_) {
|
||||
err(RAD_E_STATE, "lora_alias after declare finished");
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
bool root = false;
|
||||
for (const LoraRoot& r : prog_.lora_roots) root = root || (native && r.native == native);
|
||||
if (!root) {
|
||||
err(RAD_E_INVAL, "lora_alias '%s': its root '%s' is not declared (rad_lora_root first)",
|
||||
from ? from : "", native ? native : "");
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (!from || !*from || !to || !*to) {
|
||||
err(RAD_E_INVAL, "lora_alias under '%s': an empty module path", native);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
auto hashes = [](const char* s) { int n = 0; for (; *s; ++s) n += *s == '#'; return n; };
|
||||
if (hashes(from) != hashes(to)) {
|
||||
err(RAD_E_INVAL, "lora_alias '%s' -> '%s': %d index placeholders against %d", from, to,
|
||||
hashes(from), hashes(to));
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (from_lo < 0 || to_lo < 0 || (from_hi != 0 && from_hi <= from_lo)) {
|
||||
err(RAD_E_INVAL, "lora_alias '%s' -> '%s': rows [%lld, %lld) to %lld", from, to,
|
||||
(long long)from_lo, (long long)from_hi, (long long)to_lo);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
LoraAlias a;
|
||||
a.root = native; a.from = from; a.to = to;
|
||||
a.from_lo = from_lo; a.from_hi = from_hi; a.to_lo = to_lo;
|
||||
prog_.lora_aliases.push_back(std::move(a));
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
void Builder::note_v(const char* f, va_list ap) {
|
||||
char msg[1024];
|
||||
vsnprintf(msg, sizeof msg, f ? f : "", ap);
|
||||
@@ -2228,6 +2342,17 @@ int rad_drafter_shared_kv(RadBuilder* b, int pos_offset) {
|
||||
return B(b)->drafter_shared_kv(pos_offset);
|
||||
}
|
||||
|
||||
int rad_lora_root(RadBuilder* b, const char* native, const char* spellings) {
|
||||
if (!b) return RAD_E_INVAL;
|
||||
return B(b)->lora_root(native, spellings);
|
||||
}
|
||||
|
||||
int rad_lora_alias(RadBuilder* b, const char* native, const char* from, const char* to,
|
||||
int64_t from_lo, int64_t from_hi, int64_t to_lo) {
|
||||
if (!b) return RAD_E_INVAL;
|
||||
return B(b)->lora_alias(native, from, to, from_lo, from_hi, to_lo);
|
||||
}
|
||||
|
||||
int rad_declare_encoder(RadBuilder* b, const RadEncoderDecl* d) {
|
||||
if (!b) return RAD_E_INVAL;
|
||||
return B(b)->declare_encoder(d);
|
||||
|
||||
+25
-16
@@ -23,6 +23,7 @@
|
||||
#include <fstream>
|
||||
#include <set>
|
||||
#include <sstream>
|
||||
#include <sys/stat.h>
|
||||
|
||||
namespace rad {
|
||||
|
||||
@@ -103,13 +104,20 @@ static const Flag g_flags[] = {
|
||||
" or host memory (default 3600). 0 keeps it until the memory\n"
|
||||
" is wanted" },
|
||||
|
||||
{ "--lora", "ADAPTER", "NAME=PATH: serve a PEFT LoRA adapter beside the base model,\n"
|
||||
" as model NAME (repeatable). The base stays as it is; each\n"
|
||||
" request picks its adapter by `model`"},
|
||||
{ "--lora", "ADAPTER", "NAME=PATH: serve a LoRA adapter beside the base model\n"
|
||||
" (repeatable). A text model takes a PEFT directory and\n"
|
||||
" serves it as model NAME; an image or video generator takes\n"
|
||||
" a .safetensors file (kohya, ComfyUI, PEFT, LyCORIS) that\n"
|
||||
" a request names in `loras`. The base stays as it is"},
|
||||
{ "--lora-dir", "DIR", "image and video generators: a request may name any\n"
|
||||
" NAME.safetensors under DIR in `loras`, opened when first\n"
|
||||
" asked for"},
|
||||
{ "--max-loras", "N", "adapter slots resident at once (default: the number of\n"
|
||||
" --lora). Each slot holds one adapter's A/B on the card"},
|
||||
{ "--max-lora-rank", "R", "the rank each slot is sized for (default 16); a smaller\n"
|
||||
" adapter is zero-padded, a larger one refused"},
|
||||
" --lora, 2 with --lora-dir alone). A text model's slot holds\n"
|
||||
" one adapter, a generator's one request's combination"},
|
||||
{ "--max-lora-rank", "R", "the rank each slot is sized for (default 16 for a text\n"
|
||||
" model, 64 for a generator); a text model's larger adapter is\n"
|
||||
" refused, a generator's larger combination truncated"},
|
||||
{ "--lora-target-modules", "LIST", "comma-separated HF module leaf names adapters may\n"
|
||||
" target (q_proj,k_proj,...). Default: what the --lora\n"
|
||||
" adapters target. Needed with --max-loras and no --lora"},
|
||||
@@ -520,6 +528,7 @@ int config_parse(int argc, char** argv, Config* c) {
|
||||
}
|
||||
c->lora.adapters.emplace_back(std::string(v, eq), std::string(eq + 1));
|
||||
}
|
||||
else if (S("--lora-dir")) { if (!(v = need(i))) return RAD_E_INVAL; c->lora.dir = v; }
|
||||
else if (S("--max-loras")) { if (!num(0, 64, &c->lora.max_loras)) return RAD_E_INVAL; }
|
||||
else if (S("--max-lora-rank")) { if (!num(1, 512, &c->lora.max_rank)) return RAD_E_INVAL; }
|
||||
else if (S("--lora-target-modules")) {
|
||||
@@ -881,21 +890,18 @@ int config_parse(int argc, char** argv, Config* c) {
|
||||
RAD_ERR("--lora names the adapter '%s' twice", name.c_str());
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (L.max_loras > 0 && L.max_loras < (int)L.adapters.size()) {
|
||||
RAD_ERR("--max-loras %d holds fewer adapters than the %zu that --lora names",
|
||||
L.max_loras, L.adapters.size());
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
const bool rank_given = c->given.count("--max-lora-rank") != 0;
|
||||
if (!L.enabled() && (rank_given || !L.targets.empty())) {
|
||||
RAD_ERR("%s sizes runtime LoRA slots, and there are none: give --lora or --max-loras",
|
||||
rank_given ? "--max-lora-rank" : "--lora-target-modules");
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (L.adapters.empty() && L.max_loras > 0 && L.targets.empty()) {
|
||||
RAD_ERR("--max-loras with no --lora names no module an adapter may target; give "
|
||||
"--lora-target-modules (q_proj,k_proj,v_proj,o_proj,...)");
|
||||
return RAD_E_INVAL;
|
||||
if (!L.dir.empty()) {
|
||||
struct stat sb{};
|
||||
if (stat(L.dir.c_str(), &sb) != 0 || !S_ISDIR(sb.st_mode)) {
|
||||
RAD_ERR("--lora-dir '%s' is not a directory", L.dir.c_str());
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
}
|
||||
if (!c->kld_lora.empty() && !c->kld()) {
|
||||
RAD_ERR("--kld-lora scores through an adapter in KL mode; give --kld-record or "
|
||||
@@ -1019,9 +1025,12 @@ const ShowRow kShow[] = {
|
||||
std::string o;
|
||||
for (const auto& [n, p] : c.lora.adapters) o += (o.empty() ? "" : ", ") + n + "=" + p;
|
||||
return o.empty() ? std::string("none") : o; } },
|
||||
{ "--lora-dir", [](const Config& c) {
|
||||
return c.lora.dir.empty() ? std::string("none") : c.lora.dir; } },
|
||||
{ "--max-loras", [](const Config& c) {
|
||||
return c.lora.enabled() ? num(c.lora.slots()) : std::string("0 (off)"); } },
|
||||
{ "--max-lora-rank", [](const Config& c) { return num(c.lora.max_rank); } },
|
||||
{ "--max-lora-rank", [](const Config& c) {
|
||||
return c.lora.max_rank > 0 ? num(c.lora.max_rank) : std::string("auto (16 text, 64 generator)"); } },
|
||||
{ "--lora-target-modules", [](const Config& c) {
|
||||
std::string o;
|
||||
for (const std::string& t : c.lora.targets) o += (o.empty() ? "" : ",") + t;
|
||||
|
||||
+48
-1
@@ -2113,7 +2113,23 @@ int Engine::run_server() {
|
||||
o.graph_json = [this] { return dump_graph_json(ranks_[0]->program); };
|
||||
/* Per request, from a reading at most a second old (Engine::diagnostics_json). */
|
||||
o.diagnostics_json = [this] { return diagnostics_json(); };
|
||||
if (cfg_.lora.enabled()) {
|
||||
if (cfg_.lora.enabled() && ranks_[0]->program.is_pass_driven()) {
|
||||
/* A generator's request names its adapters in `loras`; `model` stays the model. */
|
||||
o.gen_lora_acquire = [this](const std::vector<std::pair<std::string, double>>& u,
|
||||
int32_t* slot, std::shared_ptr<void>* hold, std::string* note,
|
||||
std::string* e) {
|
||||
std::vector<LoraUse> uses;
|
||||
for (const auto& [n, w] : u) uses.push_back({ n, w });
|
||||
return gen_lora_acquire(uses, slot, hold, note, e);
|
||||
};
|
||||
o.gen_lora_names = [this] { return gen_lora_names(); };
|
||||
o.lora_load = [this](const std::string& n, const std::string& d, std::string* e) {
|
||||
return lora_load(n, d, e);
|
||||
};
|
||||
o.lora_unload = [this](const std::string& n, std::string* e, int* in_flight) {
|
||||
return lora_unload(n, e, in_flight);
|
||||
};
|
||||
} else if (cfg_.lora.enabled()) {
|
||||
/* `model` picks the adapter, and the served model's own name picks the base. */
|
||||
for (const auto& [name, dir] : cfg_.lora.adapters)
|
||||
if (name == o.model_id) {
|
||||
@@ -2347,7 +2363,14 @@ int Engine::run_server() {
|
||||
gen::Driver* drv = nullptr;
|
||||
const mm::Processor* proc = nullptr;
|
||||
server::ImageGenInfo inf;
|
||||
Tokenizer aux;
|
||||
bool has_aux = false;
|
||||
const server::ImageGenInfo& info() const override { return inf; }
|
||||
int encode_aux(const std::string& text, std::vector<int32_t>* out) const override {
|
||||
if (!has_aux) return RAD_E_UNSUPPORTED;
|
||||
out->clear();
|
||||
return aux.encode(text, *out, /*add_special=*/true, /*parse_special=*/true);
|
||||
}
|
||||
int submit(std::unique_ptr<gen::Request> r, std::string* why) override {
|
||||
return drv->submit(std::move(r), why);
|
||||
}
|
||||
@@ -2393,6 +2416,27 @@ int Engine::run_server() {
|
||||
in.cfg_original = gd.cfg_original != 0;
|
||||
in.has_default_negative = pg.gen_str.has_default_negative;
|
||||
in.default_negative = pg.gen_str.default_negative;
|
||||
in.min_tokens = gd.min_tokens;
|
||||
in.pad_token = gd.pad_token;
|
||||
in.aux_tokens = gd.aux_tokens != 0;
|
||||
in.aux_max_tokens = gd.aux_max_tokens;
|
||||
if (in.aux_tokens) {
|
||||
if (!aux_vocab_) {
|
||||
RAD_ERR("images: '%s' reads its prompt through a second tokenizer and %s carries "
|
||||
"none; convert it with rad-convert --tokenizer2", in.name.c_str(),
|
||||
cfg_.model.c_str());
|
||||
return RAD_E_FORMAT;
|
||||
}
|
||||
RAD_TRY(image_bridge.aux.init(aux_vocab_));
|
||||
image_bridge.has_aux = true;
|
||||
}
|
||||
in.samplers = gd.train_steps > 0 ? gd.samplers : 0;
|
||||
in.default_sampler = gd.default_sampler;
|
||||
in.default_scheduler = gd.default_scheduler;
|
||||
in.chunk_tokens = gd.chunk_tokens;
|
||||
in.chunk_bos = gd.chunk_bos;
|
||||
in.chunk_eos = gd.chunk_eos;
|
||||
in.chunk_pad = gd.pad_token;
|
||||
image_bridge.drv = img_gen_;
|
||||
image_bridge.proc = mm_proc.get();
|
||||
d.images = &image_bridge;
|
||||
@@ -2407,6 +2451,9 @@ int Engine::run_server() {
|
||||
(long long)in.default_height, (long long)in.max_tokens, (long long)in.max_refs,
|
||||
in.fixed_schedule ? (std::to_string(in.fixed_steps) + " fixed steps").c_str()
|
||||
: (std::to_string(in.default_steps) + " steps by default").c_str());
|
||||
if (in.samplers)
|
||||
RAD_INFO("images: sampler %s, scheduler %s by default", gen::sampler_name(in.default_sampler),
|
||||
gen::scheduler_name(in.default_scheduler));
|
||||
}
|
||||
|
||||
/* An audio generator's endpoint: the driver's queue, the declared prompt and limits, and the
|
||||
|
||||
@@ -31,6 +31,7 @@
|
||||
#include "text/tokenizer.h"
|
||||
#include "format/radfile.h"
|
||||
#include "format/table_copy.h"
|
||||
#include "lora/adapter.h"
|
||||
#include "lora/slots.h"
|
||||
|
||||
#include <atomic>
|
||||
@@ -155,6 +156,30 @@ public:
|
||||
int lora_acquire(const std::string& name, int32_t* slot, uint64_t* uid,
|
||||
std::shared_ptr<void>* hold);
|
||||
std::vector<std::string> lora_names() const;
|
||||
/* A generator's adapters: a request names one or more adapter files at their strengths, and
|
||||
* gets the slot holding exactly that combination, composed into a free (or the least recently
|
||||
* used idle) slot when none holds it yet. `note` says what the composition left out or
|
||||
* approximated, for the reply. RAD_E_NOTFOUND names an adapter neither --lora nor --lora-dir
|
||||
* provides; RAD_E_FULL means every slot is held by running requests. */
|
||||
struct LoraUse { std::string name; double weight = 1.0; };
|
||||
int gen_lora_acquire(const std::vector<LoraUse>& uses, int32_t* slot,
|
||||
std::shared_ptr<void>* hold, std::string* note, std::string* err);
|
||||
/* The adapter files a generator request may name: --lora's and those under --lora-dir. */
|
||||
std::vector<std::string> gen_lora_names() const;
|
||||
bool gen_lora_enabled() const { return lora_gen_; }
|
||||
private:
|
||||
/* A generator's adapter files by name (--lora, POST /v1/load_lora_adapter, --lora-dir), opened
|
||||
* once and kept mapped; compositions read them when a combination is put in a slot. */
|
||||
int gen_lora_open(const std::string& name, std::shared_ptr<const lora::AdapterFile>* out,
|
||||
std::string* err);
|
||||
int gen_lora_start();
|
||||
/* Every rank's packed bytes into `slot` of its pools, each rank on a stream of its own. */
|
||||
int lora_copy(int slot, const std::vector<std::vector<lora::PackedSite>>& packed,
|
||||
std::string* err);
|
||||
bool lora_gen_ = false;
|
||||
std::unique_ptr<lora::KeyMap> lora_keys_;
|
||||
mutable std::mutex lora_lib_mu_;
|
||||
std::map<std::string, std::pair<std::string, std::shared_ptr<const lora::AdapterFile>>> lora_lib_;
|
||||
private:
|
||||
std::atomic<uint64_t> lora_epoch_{0}; /* step-loop iterations, for slot reuse */
|
||||
lora::SlotTable lora_table_; /* reads lora_epoch_, so declared after it */
|
||||
@@ -216,6 +241,9 @@ private:
|
||||
* which references `vocab_` and must not outlive it. */
|
||||
std::shared_ptr<const Vocab> vocab_;
|
||||
std::unique_ptr<VocabView> vocab_view_;
|
||||
/* The container's second vocabulary (rad-convert --tokenizer2), which an image generator that
|
||||
* declares `aux_tokens` reads its prompt through; null without one. */
|
||||
std::shared_ptr<const Vocab> aux_vocab_;
|
||||
|
||||
/* The chunk geometry, resolved once and shared: the prefix cache needs the checkpoint interval
|
||||
* at configure time and the scheduler the whole geometry at init. Resolving it separately
|
||||
|
||||
@@ -3663,6 +3663,14 @@ int Engine::load_vocab() {
|
||||
auto v = std::make_shared<Vocab>();
|
||||
RAD_TRY(v->load(std::move(vb)));
|
||||
vocab_ = v;
|
||||
if (file_ && file_->aux_vocab()) {
|
||||
VocabBuild ab;
|
||||
RAD_TRY(vocab_deserialize(file_->base(), (uint64_t)file_->size(), file_->aux_vocab().h, ab));
|
||||
auto av = std::make_shared<Vocab>();
|
||||
RAD_TRY(av->load(std::move(ab)));
|
||||
aux_vocab_ = av;
|
||||
RAD_INFO("vocab: a second vocabulary of %d tokens", aux_vocab_->n_tokens());
|
||||
}
|
||||
|
||||
auto view = std::make_unique<TokenView>();
|
||||
RAD_TRY(view->init(vocab_));
|
||||
|
||||
@@ -43,6 +43,8 @@ int Engine::gen_loop() {
|
||||
return fail_loop(st);
|
||||
};
|
||||
while (!stopping_.load(std::memory_order_acquire)) {
|
||||
/* A round of the loop, idle or not: what lets a freed adapter slot cool (lora/slots.h). */
|
||||
lora_epoch_.fetch_add(1, std::memory_order_acq_rel);
|
||||
const RadBatch* b = gen_->next(step);
|
||||
if (!b) {
|
||||
step_batch_.store(nullptr, std::memory_order_release);
|
||||
@@ -52,6 +54,7 @@ int Engine::gen_loop() {
|
||||
}
|
||||
idle = 0;
|
||||
if (const int ps = prepare_release(b); ps < 0) return stop(ps);
|
||||
for (auto& rk : ranks_) rk->ctx.set_gen_lora_slot(gen_->lora_slot());
|
||||
issue_what_.store(kIssueModel, std::memory_order_release);
|
||||
step_batch_.store(b, std::memory_order_release);
|
||||
barrier_->arrive_and_wait(); /* release the ranks */
|
||||
|
||||
+321
-13
@@ -4,16 +4,25 @@
|
||||
* A load packs the adapter for each rank (lora::load_adapter, host only), refuses a module no rank
|
||||
* placed, copies each rank's bytes into the slot on a stream of its own, waits, and only then
|
||||
* publishes the name. A request can name the adapter only after the publish, so no step reads a
|
||||
* slot while it is written. */
|
||||
* slot while it is written.
|
||||
*
|
||||
* A generator keeps its adapter files in a library instead (--lora, --lora-dir, the load
|
||||
* endpoint), and a slot holds one combination of them at given strengths, named by the
|
||||
* combination: the first request that asks for it composes it (lora/adapter.h) into a free slot,
|
||||
* or the least recently used one no request holds, and later ones find it there. */
|
||||
#include "engine_priv.h"
|
||||
#include "lora/lora.h"
|
||||
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
#include <chrono>
|
||||
#include <cmath>
|
||||
#include <cstring>
|
||||
#include <dirent.h>
|
||||
#include <fstream>
|
||||
#include <sstream>
|
||||
#include <sys/stat.h>
|
||||
#include <thread>
|
||||
|
||||
namespace rad {
|
||||
@@ -50,13 +59,41 @@ int read_targets(const std::string& dir, std::set<std::string>* out, std::string
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* A generator's adapter name: a file stem under --lora-dir, possibly in a subdirectory, never
|
||||
* leaving it. */
|
||||
bool valid_name(const std::string& n) {
|
||||
if (n.empty() || n.size() > 200 || n[0] == '/' || n[0] == '.') return false;
|
||||
if (n.find("..") != std::string::npos || n.find("//") != std::string::npos) return false;
|
||||
for (char c : n)
|
||||
if (!(std::isalnum((unsigned char)c) || c == '_' || c == '-' || c == '.' || c == '/' ||
|
||||
c == ' ' || c == '(' || c == ')' || c == '+' || c == ','))
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool is_file(const std::string& p) {
|
||||
struct stat sb{};
|
||||
return stat(p.c_str(), &sb) == 0 && S_ISREG(sb.st_mode);
|
||||
}
|
||||
|
||||
/* The combination's slot name: the adapters sorted by name, each at its strength. */
|
||||
std::string combo_key(const std::vector<Engine::LoraUse>& uses) {
|
||||
std::string k;
|
||||
for (const Engine::LoraUse& u : uses) k += fmt("%s%s*%.6g", k.empty() ? "" : "+", u.name.c_str(), u.weight);
|
||||
return k;
|
||||
}
|
||||
|
||||
} /* namespace */
|
||||
|
||||
int Engine::lora_targets() {
|
||||
if (!cfg_.lora.enabled()) return RAD_OK;
|
||||
lora_targets_ = std::set<std::string>(cfg_.lora.targets.begin(), cfg_.lora.targets.end());
|
||||
if (lora_targets_.empty()) {
|
||||
/* A PEFT directory names its targets; an adapter file (a generator's) and a directory of
|
||||
* them do not, and a generator's default is every plain GEMM under its declared roots. A
|
||||
* text model refuses "*" at declare. */
|
||||
for (const auto& [name, dir] : cfg_.lora.adapters) {
|
||||
if (is_file(dir)) { lora_targets_.insert("*"); continue; }
|
||||
std::string err;
|
||||
const int s = read_targets(dir, &lora_targets_, &err);
|
||||
if (s < 0) {
|
||||
@@ -64,6 +101,7 @@ int Engine::lora_targets() {
|
||||
return s;
|
||||
}
|
||||
}
|
||||
if (cfg_.lora.adapters.empty()) lora_targets_.insert("*");
|
||||
}
|
||||
lora_table_.reset(cfg_.lora.slots(), &lora_epoch_);
|
||||
return RAD_OK;
|
||||
@@ -71,6 +109,12 @@ int Engine::lora_targets() {
|
||||
|
||||
int Engine::lora_start() {
|
||||
if (!cfg_.lora.enabled()) return RAD_OK;
|
||||
lora_gen_ = ranks_[0]->program.is_pass_driven();
|
||||
if (!lora_gen_ && cfg_.lora.slots() < (int)cfg_.lora.adapters.size()) {
|
||||
RAD_ERR("lora: --max-loras %d holds fewer adapters than the %zu that --lora names",
|
||||
cfg_.lora.slots(), cfg_.lora.adapters.size());
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
size_t n_sites = 0;
|
||||
for (const auto& r : ranks_) n_sites += r->program.lora_sites.size();
|
||||
if (n_sites == 0) {
|
||||
@@ -82,7 +126,7 @@ int Engine::lora_start() {
|
||||
}
|
||||
/* Every target is a module some rank carries adapters on. A leaf the model lacks, or holds
|
||||
* only outside the trunk (embedding, lm_head, a tower, the drafter), would target nothing. */
|
||||
{
|
||||
if (!lora_targets_.count("*")) {
|
||||
std::set<std::string> carried;
|
||||
for (const auto& r : ranks_)
|
||||
for (const lora::Site& site : r->lora_sites)
|
||||
@@ -117,9 +161,10 @@ int Engine::lora_start() {
|
||||
for (const std::string& x : lora_targets_) t += (t.empty() ? "" : ",") + x;
|
||||
RAD_INFO("lora: %zu GEMMs over %zu weights carry adapters on rank 0 (%s); %d slots of rank "
|
||||
"%d, %s a slot, %s on the card", P.lora_sites.size(), P.lora_pools.size(), t.c_str(),
|
||||
cfg_.lora.slots(), cfg_.lora.max_rank, humanb(slot_bytes).c_str(),
|
||||
cfg_.lora.slots(), cfg_.lora.rank(lora_gen_), humanb(slot_bytes).c_str(),
|
||||
humanb(slot_bytes * cfg_.lora.slots()).c_str());
|
||||
}
|
||||
if (lora_gen_) return gen_lora_start();
|
||||
for (const auto& [name, dir] : cfg_.lora.adapters) {
|
||||
std::string err;
|
||||
const int s = lora_load(name, dir, &err);
|
||||
@@ -135,6 +180,37 @@ int Engine::lora_load(const std::string& name, const std::string& dir, std::stri
|
||||
std::lock_guard<std::mutex> lk(lora_mu_);
|
||||
if (!cfg_.lora.enabled()) { *err = "the engine was started without adapters"; return RAD_E_STATE; }
|
||||
if (name.empty()) { *err = "an adapter needs a name"; return RAD_E_INVAL; }
|
||||
if (lora_gen_) {
|
||||
/* A generator's adapter goes into the library; a slot takes it when a request asks. */
|
||||
if (!valid_name(name)) { *err = "'" + name + "' is not an adapter name"; return RAD_E_INVAL; }
|
||||
{
|
||||
std::lock_guard<std::mutex> lk2(lora_lib_mu_);
|
||||
if (lora_lib_.count(name)) { *err = "an adapter named '" + name + "' is already loaded"; return RAD_E_INVAL; }
|
||||
}
|
||||
auto f = std::make_shared<lora::AdapterFile>();
|
||||
RAD_TRY(f->open(dir, err));
|
||||
int placed = 0, rank = 0;
|
||||
std::string first;
|
||||
for (const lora::FileModule& m : f->modules()) {
|
||||
std::string why;
|
||||
if (!lora_keys_->resolve(m.key, &why).empty()) { ++placed; continue; }
|
||||
if (first.empty()) first = m.key + ": " + why;
|
||||
}
|
||||
for (const lora::FileModule& m : f->modules())
|
||||
if (m.kind == lora::FileModule::LORA && m.t[0]) rank = std::max(rank, (int)m.t[0]->shape[0]);
|
||||
if (placed == 0) {
|
||||
*err = fmt("none of its %zu modules is a module of this model (%s)", f->modules().size(),
|
||||
first.c_str());
|
||||
return RAD_E_NOTFOUND;
|
||||
}
|
||||
RAD_INFO("lora: '%s' -- %s, %d of %zu modules on this model%s%s%s", name.c_str(),
|
||||
f->kind_name(), placed, f->modules().size(),
|
||||
rank ? fmt(", rank %d", rank).c_str() : "", first.empty() ? "" : "; not placed: ",
|
||||
first.c_str());
|
||||
std::lock_guard<std::mutex> lk2(lora_lib_mu_);
|
||||
lora_lib_[name] = { dir, f };
|
||||
return RAD_OK;
|
||||
}
|
||||
/* A slot that is still cooling (lora/slots.h) is waited for here rather than answered with a
|
||||
* retry: the step loop goes round idle or busy, so the wait is milliseconds, and a hot swap
|
||||
* (unload, then load at once) would otherwise fail under traffic. Only other loads wait on
|
||||
@@ -155,7 +231,7 @@ int Engine::lora_load(const std::string& name, const std::string& dir, std::stri
|
||||
std::vector<lora::AdapterInfo> infos(ranks_.size());
|
||||
std::vector<std::vector<lora::PackedSite>> packed(ranks_.size());
|
||||
for (size_t ri = 0; ri < ranks_.size(); ++ri) {
|
||||
const int s = lora::load_adapter(dir, ranks_[ri]->lora_sites, cfg_.lora.max_rank, &infos[ri],
|
||||
const int s = lora::load_adapter(dir, ranks_[ri]->lora_sites, cfg_.lora.rank(false), &infos[ri],
|
||||
&packed[ri], err);
|
||||
if (s < 0) {
|
||||
if (ranks_.size() > 1) *err = fmt("rank %zu: ", ri) + *err;
|
||||
@@ -167,7 +243,19 @@ int Engine::lora_load(const std::string& name, const std::string& dir, std::stri
|
||||
if (s < 0) return s;
|
||||
}
|
||||
|
||||
/* ---- copy, per rank, on a stream of its own (the compute stream may be recording a pass) */
|
||||
RAD_TRY(lora_copy(slot, packed, err));
|
||||
|
||||
lora_table_.publish(slot, name, dir);
|
||||
const lora::AdapterInfo& a = infos[0];
|
||||
RAD_INFO("lora: '%s' in slot %d -- %zu modules, rank %lld, alpha %g%s, base %s", name.c_str(),
|
||||
slot, a.modules.size(), (long long)a.max_module_rank, a.alpha, a.rslora ? " (rsLoRA)" : "",
|
||||
a.base_model.empty() ? "(unnamed)" : a.base_model.c_str());
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int Engine::lora_copy(int slot, const std::vector<std::vector<lora::PackedSite>>& packed,
|
||||
std::string* err) {
|
||||
/* Each rank on a stream of its own: the compute stream may be recording a pass. */
|
||||
for (size_t ri = 0; ri < ranks_.size(); ++ri) {
|
||||
Rank& r = *ranks_[ri];
|
||||
const Program& P = r.program;
|
||||
@@ -218,12 +306,6 @@ int Engine::lora_load(const std::string& name, const std::string& dir, std::stri
|
||||
return rc;
|
||||
}
|
||||
}
|
||||
|
||||
lora_table_.publish(slot, name, dir);
|
||||
const lora::AdapterInfo& a = infos[0];
|
||||
RAD_INFO("lora: '%s' in slot %d -- %zu modules, rank %lld, alpha %g%s, base %s", name.c_str(),
|
||||
slot, a.modules.size(), (long long)a.max_module_rank, a.alpha, a.rslora ? " (rsLoRA)" : "",
|
||||
a.base_model.empty() ? "(unnamed)" : a.base_model.c_str());
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
@@ -233,11 +315,237 @@ int Engine::lora_acquire(const std::string& name, int32_t* slot, uint64_t* uid,
|
||||
}
|
||||
|
||||
int Engine::lora_unload(const std::string& name, std::string* err, int* in_flight) {
|
||||
return lora_table_.unload(name, in_flight, err);
|
||||
if (!lora_gen_) return lora_table_.unload(name, in_flight, err);
|
||||
/* A generator's adapter leaves the library, and every combination holding it its slot (at
|
||||
* once when idle, after its requests otherwise). */
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(lora_lib_mu_);
|
||||
if (!lora_lib_.erase(name)) {
|
||||
*err = "no adapter named '" + name + "' is loaded";
|
||||
return RAD_E_NOTFOUND;
|
||||
}
|
||||
}
|
||||
*in_flight = 0;
|
||||
for (const std::string& k : lora_table_.names()) {
|
||||
bool uses = false;
|
||||
size_t at = 0;
|
||||
while (at <= k.size()) {
|
||||
const size_t plus = std::min(k.find('+', at), k.size());
|
||||
const std::string part = k.substr(at, plus - at);
|
||||
if (part.substr(0, part.rfind('*')) == name) uses = true;
|
||||
at = plus + 1;
|
||||
}
|
||||
if (!uses) continue;
|
||||
int n = 0;
|
||||
std::string e;
|
||||
lora_table_.unload(k, &n, &e);
|
||||
*in_flight += n;
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
std::vector<std::string> Engine::lora_names() const {
|
||||
return lora_table_.names();
|
||||
return lora_gen_ ? gen_lora_names() : lora_table_.names();
|
||||
}
|
||||
|
||||
/* ================================================================== generator adapters */
|
||||
int Engine::gen_lora_start() {
|
||||
/* Every slot's run of the slot-row table holds its own index (Program::lora_rows). */
|
||||
for (auto& rp : ranks_) {
|
||||
Rank& r = *rp;
|
||||
const Program& P = r.program;
|
||||
if (!P.lora_rows || P.lora_rows_n <= 0) continue;
|
||||
const int S = cfg_.lora.slots();
|
||||
std::vector<int32_t> v((size_t)(S * P.lora_rows_n));
|
||||
for (int s = 0; s < S; ++s)
|
||||
std::fill(v.begin() + (int64_t)s * P.lora_rows_n, v.begin() + (int64_t)(s + 1) * P.lora_rows_n, s);
|
||||
void* d = P.buffers[P.lora_rows].ptr;
|
||||
if (!d || rad_dev_set(r.device) < 0) {
|
||||
RAD_ERR("lora: rank %d: the slot-row table has no address", r.index);
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
RadStream st{};
|
||||
if (rad_stream_create(&st, 0) < 0) return RAD_E_DEVICE;
|
||||
const int rc = rad_memcpy_async(d, v.data(), (int64_t)v.size() * 4, st);
|
||||
const int sy = rad_stream_sync(st);
|
||||
rad_stream_destroy(st);
|
||||
if (rc < 0 || sy < 0) return RAD_E_DEVICE;
|
||||
}
|
||||
lora_keys_ = std::make_unique<lora::KeyMap>(ranks_[0]->program, ranks_[0]->lora_sites);
|
||||
for (const auto& [name, path] : cfg_.lora.adapters) {
|
||||
std::string err;
|
||||
const int s = lora_load(name, path, &err);
|
||||
if (s < 0) {
|
||||
RAD_ERR("lora: adapter '%s' (%s): %s", name.c_str(), path.c_str(), err.c_str());
|
||||
return s;
|
||||
}
|
||||
}
|
||||
if (!cfg_.lora.dir.empty())
|
||||
RAD_INFO("lora: requests may name the %zu adapter files under %s", gen_lora_names().size(),
|
||||
cfg_.lora.dir.c_str());
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int Engine::gen_lora_open(const std::string& name, std::shared_ptr<const lora::AdapterFile>* out,
|
||||
std::string* err) {
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(lora_lib_mu_);
|
||||
auto it = lora_lib_.find(name);
|
||||
if (it != lora_lib_.end()) { *out = it->second.second; return RAD_OK; }
|
||||
}
|
||||
const std::string path = cfg_.lora.dir + "/" + name + ".safetensors";
|
||||
if (cfg_.lora.dir.empty() || !valid_name(name) || !is_file(path)) {
|
||||
*err = "no adapter named '" + name + "'" +
|
||||
(cfg_.lora.dir.empty() ? std::string(" is loaded")
|
||||
: " is loaded or under --lora-dir (GET /v1/loras lists them)");
|
||||
return RAD_E_NOTFOUND;
|
||||
}
|
||||
/* lora_load takes lora_mu_, which the caller holds: open here, as lora_load would. */
|
||||
auto f = std::make_shared<lora::AdapterFile>();
|
||||
RAD_TRY(f->open(path, err));
|
||||
RAD_INFO("lora: '%s' opened from --lora-dir -- %s, %zu modules", name.c_str(), f->kind_name(),
|
||||
f->modules().size());
|
||||
std::lock_guard<std::mutex> lk(lora_lib_mu_);
|
||||
lora_lib_[name] = { path, f };
|
||||
*out = f;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
std::vector<std::string> Engine::gen_lora_names() const {
|
||||
std::set<std::string> n;
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(lora_lib_mu_);
|
||||
for (const auto& [k, v] : lora_lib_) n.insert(k);
|
||||
}
|
||||
if (!cfg_.lora.dir.empty()) {
|
||||
/* Two levels: the directory and its subdirectories, as a UI's lora folder is laid out. */
|
||||
std::vector<std::string> dirs{ "" };
|
||||
for (size_t i = 0; i < dirs.size(); ++i) {
|
||||
const std::string rel = dirs[i];
|
||||
DIR* d = opendir((cfg_.lora.dir + "/" + rel).c_str());
|
||||
if (!d) continue;
|
||||
while (dirent* e = readdir(d)) {
|
||||
const std::string fn = e->d_name;
|
||||
if (fn.empty() || fn[0] == '.') continue;
|
||||
const std::string p = rel + fn;
|
||||
struct stat sb{};
|
||||
if (stat((cfg_.lora.dir + "/" + p).c_str(), &sb) != 0) continue;
|
||||
if (S_ISDIR(sb.st_mode)) { if (rel.empty()) dirs.push_back(p + "/"); continue; }
|
||||
const size_t k = fn.size();
|
||||
if (k > 12 && fn.compare(k - 12, 12, ".safetensors") == 0) {
|
||||
const std::string stem = p.substr(0, p.size() - 12);
|
||||
if (valid_name(stem)) n.insert(stem);
|
||||
}
|
||||
}
|
||||
closedir(d);
|
||||
}
|
||||
}
|
||||
return std::vector<std::string>(n.begin(), n.end());
|
||||
}
|
||||
|
||||
int Engine::gen_lora_acquire(const std::vector<LoraUse>& uses_in, int32_t* slot,
|
||||
std::shared_ptr<void>* hold, std::string* note, std::string* err) {
|
||||
*slot = -1;
|
||||
hold->reset();
|
||||
if (note) note->clear();
|
||||
if (!lora_gen_) { *err = "this model takes no adapters (start it with --lora or --lora-dir)"; return RAD_E_STATE; }
|
||||
/* One entry per adapter, strengths of a repeated name summed; strength 0 is no adapter. */
|
||||
std::map<std::string, double> by;
|
||||
for (const LoraUse& u : uses_in) {
|
||||
if (!std::isfinite(u.weight) || std::fabs(u.weight) > 16.0) {
|
||||
*err = fmt("adapter '%s': strength %g is outside [-16, 16]", u.name.c_str(), u.weight);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
by[u.name] += u.weight;
|
||||
}
|
||||
std::vector<LoraUse> uses;
|
||||
for (const auto& [n, w] : by) if (w != 0.0) uses.push_back({ n, w });
|
||||
if (uses.empty()) return RAD_OK;
|
||||
if (uses.size() > 16) { *err = fmt("%zu adapters in one request; at most 16", uses.size()); return RAD_E_INVAL; }
|
||||
const std::string key = combo_key(uses);
|
||||
uint64_t uid = 0;
|
||||
if (lora_table_.acquire(key, slot, &uid, hold) == RAD_OK) return RAD_OK;
|
||||
|
||||
std::lock_guard<std::mutex> lk(lora_mu_);
|
||||
if (lora_table_.acquire(key, slot, &uid, hold) == RAD_OK) return RAD_OK;
|
||||
const auto t0 = std::chrono::steady_clock::now();
|
||||
std::vector<lora::Strength> ss;
|
||||
for (const LoraUse& u : uses) {
|
||||
lora::Strength s;
|
||||
s.name = u.name;
|
||||
s.weight = u.weight;
|
||||
RAD_TRY(gen_lora_open(u.name, &s.file, err));
|
||||
ss.push_back(std::move(s));
|
||||
}
|
||||
/* A slot: free, or freed from the least recently used combination no request holds. */
|
||||
const auto give_up = std::chrono::steady_clock::now() + std::chrono::seconds(2);
|
||||
int sl = -1;
|
||||
for (;;) {
|
||||
bool cooling = false;
|
||||
const int s = lora_table_.reserve(key, &sl, &cooling, err);
|
||||
if (s >= 0) break;
|
||||
if (s == RAD_E_FULL && !cooling) {
|
||||
std::string ev;
|
||||
if (lora_table_.evict_idle(&ev) == RAD_OK) continue;
|
||||
*err = fmt("all %d adapter slots are held by running requests with other adapters "
|
||||
"(--max-loras); retry when one finishes", cfg_.lora.slots());
|
||||
return RAD_E_FULL;
|
||||
}
|
||||
if (s != RAD_E_FULL || stopping_.load(std::memory_order_acquire) ||
|
||||
std::chrono::steady_clock::now() >= give_up)
|
||||
return s;
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(2));
|
||||
}
|
||||
const int rank = cfg_.lora.rank(true);
|
||||
std::map<std::string, lora::Composite> comp;
|
||||
lora::ComposeReport rep;
|
||||
RAD_TRY(lora::compose(*lora_keys_, ss, rank, &comp, &rep, err));
|
||||
if (rep.modules == 0) {
|
||||
*err = "none of the adapters' modules is a module of this model" +
|
||||
(rep.unplaced.empty() ? std::string() : " (" + rep.unplaced[0] + ")");
|
||||
return RAD_E_NOTFOUND;
|
||||
}
|
||||
const std::map<std::string, lora::AdModule> mods = lora::as_modules(comp, *lora_keys_);
|
||||
std::vector<std::vector<lora::PackedSite>> packed(ranks_.size());
|
||||
for (size_t ri = 0; ri < ranks_.size(); ++ri) {
|
||||
lora::AdapterInfo info;
|
||||
const int s = lora::pack_modules(ranks_[ri]->lora_sites, rank, mods, &info, &packed[ri], err,
|
||||
/*compact=*/true);
|
||||
if (s < 0) {
|
||||
if (ranks_.size() > 1) *err = fmt("rank %zu: ", ri) + *err;
|
||||
return s;
|
||||
}
|
||||
/* Pools past the last one a site names hold nothing (lora_declare's dropped GEMMs). */
|
||||
packed[ri].resize(ranks_[ri]->program.lora_pools.size());
|
||||
}
|
||||
RAD_TRY(lora_copy(sl, packed, err));
|
||||
/* The ranks each pool takes in this slot, before a pass can name the slot (the publish). */
|
||||
for (size_t ri = 0; ri < ranks_.size(); ++ri) {
|
||||
Program& P = ranks_[ri]->program;
|
||||
const size_t S = (size_t)cfg_.lora.slots();
|
||||
for (size_t p = 0; p < P.lora_pools.size() && p < packed[ri].size(); ++p)
|
||||
if (p * S + (size_t)sl < P.lora_rused.size())
|
||||
P.lora_rused[p * S + (size_t)sl] = packed[ri][p].empty ? 0 : (int32_t)packed[ri][p].r_used;
|
||||
}
|
||||
lora_table_.publish(sl, key, "");
|
||||
const double ms = std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - t0).count();
|
||||
std::string n;
|
||||
if (!rep.unplaced.empty())
|
||||
n += fmt("%zu adapter module%s not on this model (%s)", rep.unplaced.size(),
|
||||
rep.unplaced.size() == 1 ? "" : "s", rep.unplaced[0].c_str());
|
||||
if (rep.exact < rep.modules)
|
||||
n += fmt("%s%lld module%s past rank %d were truncated to it, keeping at worst %.1f%% of the "
|
||||
"delta (%s)", n.empty() ? "" : "; ", (long long)(rep.modules - rep.exact),
|
||||
rep.modules - rep.exact == 1 ? "" : "s", rank, 100.0 * rep.worst_kept,
|
||||
rep.worst_module.c_str());
|
||||
RAD_INFO("lora: slot %d <- %s: %lld modules (%lld exact) in %.0f ms%s%s", sl, key.c_str(),
|
||||
(long long)rep.modules, (long long)rep.exact, ms, n.empty() ? "" : "; ", n.c_str());
|
||||
if (note) *note = n;
|
||||
if (lora_table_.acquire(key, slot, &uid, hold) != RAD_OK) {
|
||||
*err = "the combination's slot was taken back before the request could hold it; retry";
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
} /* namespace rad */
|
||||
+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 */
|
||||
|
||||
|
||||
+87
-4
@@ -23,7 +23,7 @@ int64_t ref_tokens_max(const RadGeneratorDecl& d) {
|
||||
}
|
||||
|
||||
struct Sizes {
|
||||
int64_t T = 0, S = 0, EP = 0, PD = 0, R = 0, P = 0, PX = 0, NT = 0, NB = 0;
|
||||
int64_t T = 0, S = 0, EP = 0, PD = 0, R = 0, P = 0, PX = 0, NT = 0, NB = 0, AX = 0;
|
||||
bool joint = false;
|
||||
};
|
||||
|
||||
@@ -43,6 +43,7 @@ Sizes sizes_of(const Program& prog, int64_t block_size) {
|
||||
z.PX = z.R * (ref_tokens_max(d) * s2) + d.max_tokens * s2;
|
||||
z.NT = d.max_tokens;
|
||||
z.NB = block_size > 0 ? (z.P + block_size - 1) / block_size : 0;
|
||||
z.AX = d.aux_tokens ? d.aux_max_tokens : 0;
|
||||
return z;
|
||||
}
|
||||
|
||||
@@ -85,6 +86,12 @@ int64_t carve(const Sizes& z, int64_t pixel_ch, int64_t (*bytes)[2], int n) {
|
||||
{ 0, J * z.T * I }, /* R_MSRC */
|
||||
{ 0, J * 3 * (z.S + 1) * I }, /* R_MCCU */
|
||||
{ 0, J * 4 * z.T * 4 }, /* R_MROPE */
|
||||
{ 0, (z.AX ? z.AX + 2 : 0) * I }, /* R_AUX: a COND's {0, n} and second-tokenizer ids */
|
||||
{ 0, z.S * 4 }, /* R_SIGP */
|
||||
{ 0, z.S * 4 }, /* R_TSTEP */
|
||||
{ 0, z.S * I }, /* R_SAMP */
|
||||
{ 0, z.S * I }, /* R_STEPI */
|
||||
{ 0, 2 * z.S * 4 }, /* R_SIZE */
|
||||
};
|
||||
int64_t off = 0;
|
||||
for (int r = 0; r < n; ++r) {
|
||||
@@ -113,6 +120,14 @@ int Driver::init(const Program& prog, IKVManager* kv, const std::vector<RankIO>&
|
||||
fixed_ = prog.gen_str.sigmas;
|
||||
kv_ = kv;
|
||||
ranks_ = ranks;
|
||||
table_ = DiscreteTable{};
|
||||
if (discrete()) {
|
||||
std::string why;
|
||||
if (discrete_table(decl_, &table_, &why) < 0) {
|
||||
RAD_ERR("image generator: %s", why.c_str());
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
}
|
||||
/* Exactly one paged full-attention KV group, holding the conditioning; none in the joint
|
||||
* layout, where the conditioning rides in the steps. Group handles start at 1 (group 0 is the
|
||||
* null handle); the KV manager and a batch both index by handle. */
|
||||
@@ -216,6 +231,10 @@ int Driver::submit(std::unique_ptr<Request> r, std::string* why) {
|
||||
return no("at most " + std::to_string(d.max_refs) + " pictures a request");
|
||||
for (const Branch* b : { &r->pos, &r->neg }) {
|
||||
if (b == &r->neg && !r->has_neg) continue;
|
||||
if (d.aux_tokens && (b->aux.empty() || (int64_t)b->aux.size() > d.aux_max_tokens))
|
||||
return no("the prompt is " + std::to_string(b->aux.size()) + " tokens to the "
|
||||
"model's second tokenizer, which reads 1.." +
|
||||
std::to_string(d.aux_max_tokens));
|
||||
if ((int64_t)b->tokens.size() > max_tok_)
|
||||
return no("the prompt is " + std::to_string(b->tokens.size()) + " tokens with its "
|
||||
"pictures; a conditioning pass carries " + std::to_string(max_tok_));
|
||||
@@ -235,6 +254,10 @@ int Driver::submit(std::unique_ptr<Request> r, std::string* why) {
|
||||
r->inp_src.h != r->height))
|
||||
return no("the mask's picture is not at the size being made");
|
||||
if (r->previews < 0 || r->previews > 3) return no("partial_images must be 0..3");
|
||||
if (discrete() && (r->sampler < 0 || r->sampler >= RAD_GEN_SAMPLER_COUNT ||
|
||||
!(decl_.samplers & (1u << r->sampler)) || r->scheduler < 0 ||
|
||||
r->scheduler >= RAD_GEN_SCHED_COUNT))
|
||||
return no("the sampler or scheduler is not one this model serves");
|
||||
r->ticket->t_submit_ns = (int64_t)rad_mono_ns();
|
||||
std::lock_guard<std::mutex> lk(mu_);
|
||||
if (closed_) {
|
||||
@@ -373,7 +396,13 @@ int Driver::admit_locked() {
|
||||
release_kv_locked(j);
|
||||
break;
|
||||
}
|
||||
j.sigmas = schedule(decl_, fixed_, r.steps, j.tokens);
|
||||
if (discrete()) {
|
||||
j.sigmas = schedule_discrete(decl_, table_, r.scheduler, r.steps);
|
||||
j.tsteps.clear();
|
||||
for (float sg : j.sigmas) j.tsteps.push_back(sg > 0 ? (float)table_.timestep(sg) : 0.0f);
|
||||
} else {
|
||||
j.sigmas = schedule(decl_, fixed_, r.steps, j.tokens);
|
||||
}
|
||||
const int32_t n_steps = (int32_t)j.sigmas.size() - 1;
|
||||
for (int b = 0; b < j.n_branch; ++b) {
|
||||
Cond& c = j.cond[b];
|
||||
@@ -491,6 +520,16 @@ void Driver::finish_batches(int64_t n_tok, int64_t n_seq, int32_t max_q, int ste
|
||||
G.mode_ccu = nullptr;
|
||||
G.n_mode_h = nullptr;
|
||||
G.mode_rope_f = nullptr;
|
||||
G.n_aux = 0;
|
||||
G.aux_ids = nullptr;
|
||||
G.aux_cu = nullptr;
|
||||
G.sigma_prev = nullptr;
|
||||
G.timestep = nullptr;
|
||||
G.sampler = nullptr;
|
||||
G.step = nullptr;
|
||||
G.size_px = nullptr;
|
||||
G.entry_h = nullptr;
|
||||
G.tokens_h = nullptr;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -529,15 +568,18 @@ const RadBatch* Driver::next(int step) {
|
||||
for (int b = 0; b < j.n_branch; ++b)
|
||||
if (!j.cond[b].encoded) return build_cond(j, b, step);
|
||||
}
|
||||
/* 3. A denoise step over what is in flight, oldest request first. */
|
||||
/* 3. A denoise step over what is in flight, oldest request first, with the oldest one's
|
||||
* adapters: a pass runs one runtime LoRA slot in every row. */
|
||||
std::vector<int32_t> take;
|
||||
int64_t rows = 0, entries = 0;
|
||||
int32_t lora = -2;
|
||||
for (auto& jp : jobs_) {
|
||||
Job& j = *jp;
|
||||
if (!j.admitted || j.failed) continue;
|
||||
bool ready = true;
|
||||
for (int b = 0; b < j.n_branch; ++b) ready = ready && j.cond[b].encoded;
|
||||
if (!ready) continue;
|
||||
if (lora != -2 && j.req->lora_slot != lora) continue;
|
||||
const int32_t n_steps = (int32_t)j.sigmas.size() - 1;
|
||||
for (int32_t l : j.lanes) {
|
||||
const Lane& ln = lanes_[(size_t)l];
|
||||
@@ -548,10 +590,13 @@ const RadBatch* Driver::next(int step) {
|
||||
rows += need;
|
||||
entries += j.n_branch;
|
||||
take.push_back(l);
|
||||
lora = j.req->lora_slot;
|
||||
}
|
||||
}
|
||||
if (take.empty()) return nullptr;
|
||||
return build_denoise(take, step);
|
||||
const RadBatch* b = build_denoise(take, step);
|
||||
pass_.lora_slot = lora;
|
||||
return b;
|
||||
}
|
||||
|
||||
const RadBatch* Driver::batch_for(int rank) const {
|
||||
@@ -704,6 +749,15 @@ const RadBatch* Driver::build_cond(Job& j, int branch, int step) {
|
||||
/* The conditioning is modulated at t = 0. */
|
||||
hptr<float>(R_SIG)[0] = 0.0f;
|
||||
reg_[R_SIG].used = 4;
|
||||
/* The prompt through the second tokenizer, for a model that reads it. */
|
||||
const int64_t n_aux = decl_.aux_tokens ? (int64_t)br.aux.size() : 0;
|
||||
if (n_aux) {
|
||||
int32_t* ax = hptr<int32_t>(R_AUX);
|
||||
ax[0] = 0;
|
||||
ax[1] = (int32_t)n_aux;
|
||||
std::memcpy(ax + 2, br.aux.data(), (size_t)n_aux * 4);
|
||||
reg_[R_AUX].used = (n_aux + 2) * 4;
|
||||
}
|
||||
/* Host-side arrays the plugin reads (segment kinds, pixel blocks, lanes), owned by the driver
|
||||
* for the life of the pass. */
|
||||
host_bidi_ = c.lay.bidi;
|
||||
@@ -758,6 +812,10 @@ const RadBatch* Driver::build_cond(Job& j, int branch, int step) {
|
||||
G.n_lane = (int64_t)host_lanes_.size();
|
||||
G.lane_h = host_lanes_.data();
|
||||
G.lane = G.n_lane ? dptr<int32_t>(ri, R_LANE) : nullptr;
|
||||
G.n_aux = n_aux;
|
||||
G.aux_cu = n_aux ? dptr<int32_t>(ri, R_AUX) : nullptr;
|
||||
G.aux_ids = n_aux ? dptr<int32_t>(ri, R_AUX) + 2 : nullptr;
|
||||
G.tokens_h = hptr<int32_t>(R_TOK);
|
||||
if (joint()) {
|
||||
B.n_kv_groups = 0;
|
||||
B.kv = nullptr;
|
||||
@@ -771,6 +829,7 @@ const RadBatch* Driver::build_cond(Job& j, int branch, int step) {
|
||||
}
|
||||
pass_.kind = RAD_GEN_PASS_COND;
|
||||
pass_.job = j.id;
|
||||
pass_.lora_slot = j.req->lora_slot;
|
||||
pass_.branch = branch;
|
||||
return &out_[0];
|
||||
}
|
||||
@@ -821,6 +880,12 @@ const RadBatch* Driver::build_denoise(const std::vector<int32_t>& take, int step
|
||||
uint32_t* seed = hptr<uint32_t>(R_SEED);
|
||||
int32_t* btab = hptr<int32_t>(R_BT);
|
||||
int32_t* used = hptr<int32_t>(R_USED);
|
||||
float* sigp = hptr<float>(R_SIGP);
|
||||
float* tstep = hptr<float>(R_TSTEP);
|
||||
int32_t* samp = hptr<int32_t>(R_SAMP);
|
||||
int32_t* stepi = hptr<int32_t>(R_STEPI);
|
||||
float* size = hptr<float>(R_SIZE);
|
||||
host_entry_.assign((size_t)(4 * S), 0);
|
||||
int64_t row = 0;
|
||||
cu[0] = 0;
|
||||
pass_.lanes.clear();
|
||||
@@ -866,6 +931,16 @@ const RadBatch* Driver::build_denoise(const std::vector<int32_t>& take, int step
|
||||
cu[i + 1] = (int32_t)row;
|
||||
sig[i] = j.sigmas[(size_t)ln.step];
|
||||
sign[i] = j.sigmas[(size_t)ln.step + 1];
|
||||
sigp[i] = ln.step > 0 ? j.sigmas[(size_t)ln.step - 1] : 0.0f;
|
||||
tstep[i] = discrete() ? j.tsteps[(size_t)ln.step] : 0.0f;
|
||||
samp[i] = j.req->sampler;
|
||||
stepi[i] = ln.step;
|
||||
size[2 * i] = (float)j.req->height;
|
||||
size[2 * i + 1] = (float)j.req->width;
|
||||
host_entry_[(size_t)(4 * i)] = joint() ? (int32_t)c.lay.rows : 0;
|
||||
host_entry_[(size_t)(4 * i + 1)] = j.req->height;
|
||||
host_entry_[(size_t)(4 * i + 2)] = j.req->width;
|
||||
host_entry_[(size_t)(4 * i + 3)] = e.branch;
|
||||
const bool neg = e.branch == 1;
|
||||
cfg[i] = neg ? 0.0f : (j.n_branch > 1 ? j.req->cfg : 1.0f);
|
||||
pair[i] = neg ? -2 : (j.n_branch > 1 ? (int32_t)(i + 1) : -1);
|
||||
@@ -930,6 +1005,8 @@ const RadBatch* Driver::build_denoise(const std::vector<int32_t>& take, int step
|
||||
reg_[R_GROPE].used = 3 * n_tok * 4;
|
||||
}
|
||||
reg_[R_SIG].used = reg_[R_SIGN].used = reg_[R_CFG].used = S * 4;
|
||||
reg_[R_SIGP].used = reg_[R_TSTEP].used = reg_[R_SAMP].used = reg_[R_STEPI].used = S * 4;
|
||||
reg_[R_SIZE].used = 2 * S * 4;
|
||||
reg_[R_PAIR].used = reg_[R_LANE].used = reg_[R_FLAGS].used = S * 4;
|
||||
reg_[R_SEED].used = 2 * S * 4;
|
||||
reg_[R_BT].used = joint() ? 0 : S * pitch * 4;
|
||||
@@ -954,6 +1031,12 @@ const RadBatch* Driver::build_denoise(const std::vector<int32_t>& take, int step
|
||||
G.lane_h = nullptr;
|
||||
G.rope = joint() ? nullptr : dptr<int32_t>(ri, R_GROPE);
|
||||
G.lane_dh = hptr<int32_t>(R_LANE);
|
||||
G.sigma_prev = dptr<float>(ri, R_SIGP);
|
||||
G.timestep = dptr<float>(ri, R_TSTEP);
|
||||
G.sampler = dptr<int32_t>(ri, R_SAMP);
|
||||
G.step = dptr<int32_t>(ri, R_STEPI);
|
||||
G.size_px = dptr<float>(ri, R_SIZE);
|
||||
G.entry_h = host_entry_.data();
|
||||
if (joint()) {
|
||||
G.src = dptr<int32_t>(ri, R_SRC);
|
||||
G.n_img = n_img;
|
||||
|
||||
+11
-1
@@ -60,6 +60,7 @@ public:
|
||||
/* ---------------------------------------------------------- the engine thread */
|
||||
const RadBatch* next(int step) override;
|
||||
const RadBatch* batch_for(int rank) const override;
|
||||
int32_t lora_slot() const override { return pass_.lora_slot; }
|
||||
/* A decode pass's pixels: `image_out` into the pinned image buffer. */
|
||||
const std::vector<Readback>& readbacks() const override { return rb_; }
|
||||
int done() override;
|
||||
@@ -85,6 +86,8 @@ private:
|
||||
int32_t h_lat = 0, w_lat = 0;
|
||||
int64_t tokens = 0;
|
||||
std::vector<float> sigmas;
|
||||
/* A discrete-time model's: each step's timestep, beside `sigmas`. */
|
||||
std::vector<float> tsteps;
|
||||
std::vector<int32_t> lanes;
|
||||
std::vector<std::pair<int32_t, int32_t>> ref_hw;
|
||||
int32_t images_done = 0;
|
||||
@@ -112,13 +115,15 @@ private:
|
||||
bool preview = false;
|
||||
std::vector<int32_t> lanes; /* DENOISE: the lanes it stepped, one per image */
|
||||
std::vector<char> marks; /* ... and whether each was marked for a preview */
|
||||
int32_t lora_slot = -1; /* every image of a pass runs with the same adapters */
|
||||
};
|
||||
|
||||
/* Staging regions: their offsets in the host span and every rank's slab. */
|
||||
struct Region { int64_t off = 0, bytes = 0, used = 0; };
|
||||
enum { R_TOK, R_POS, R_ROPE, R_CU, R_MMROW, R_ENCPIX, R_ENCCRD, R_ENCCU, R_SRC, R_GROPE,
|
||||
R_SEG, R_SLOT, R_PX, R_MASK, R_SIG, R_SIGN, R_CFG, R_PAIR, R_LANE, R_FLAGS, R_SEED,
|
||||
R_BT, R_USED, R_ROPEF, R_ICU, R_IROWS, R_MCU, R_VCU, R_MROWS, R_MSRC, R_MCCU, R_MROPE, R_N };
|
||||
R_BT, R_USED, R_ROPEF, R_ICU, R_IROWS, R_MCU, R_VCU, R_MROWS, R_MSRC, R_MCCU, R_MROPE,
|
||||
R_AUX, R_SIGP, R_TSTEP, R_SAMP, R_STEPI, R_SIZE, R_N };
|
||||
|
||||
int layout_regions();
|
||||
template <class T> T* hptr(int r) const { return reinterpret_cast<T*>(host_ + reg_[r].off); }
|
||||
@@ -147,6 +152,9 @@ private:
|
||||
|
||||
RadGeneratorDecl decl_{};
|
||||
std::vector<double> fixed_;
|
||||
/* A discrete-time model's sigma table (RadGeneratorDecl::train_steps), empty otherwise. */
|
||||
DiscreteTable table_;
|
||||
bool discrete() const { return decl_.train_steps > 0; }
|
||||
int64_t max_tok_ = 0, max_seqs_ = 0, max_enc_ = 0, patch_dim_ = 0;
|
||||
int64_t max_rows_ = 0; /* the longest conditioning sequence */
|
||||
int64_t max_px_ = 0; /* pixels the staging holds */
|
||||
@@ -170,6 +178,8 @@ private:
|
||||
Pass pass_;
|
||||
/* Host arrays a COND pass's plugin reads on the host (RadGenBatch's _h fields). */
|
||||
std::vector<int32_t> host_bidi_, host_px_, host_lanes_;
|
||||
/* A DENOISE pass's per-entry host array (RadGenBatch::entry_h). */
|
||||
std::vector<int32_t> host_entry_;
|
||||
int64_t host_nmode_[3] = { 0, 0, 0 };
|
||||
|
||||
mutable std::mutex mu_;
|
||||
|
||||
@@ -67,6 +67,16 @@ std::vector<float> schedule(const RadGeneratorDecl& d, const std::vector<double>
|
||||
std::vector<float> s;
|
||||
if (!fixed.empty()) {
|
||||
for (double v : fixed) s.push_back((float)v);
|
||||
} else if (d.sigma_grid > 0) {
|
||||
/* ComfyUI's `simple` scheduler: the model's table holds t = k / N for k = 1..N (an f32
|
||||
* quotient), and step i reads entry N - 1 - floor(i N / n), the floor of a Python float. */
|
||||
const int32_t n = steps > 0 ? steps : (int32_t)d.default_steps;
|
||||
const int64_t N = d.sigma_grid;
|
||||
const double ss = (double)N / (double)n;
|
||||
for (int32_t i = 0; i < n; ++i) {
|
||||
const int64_t k = N - (int64_t)((double)i * ss);
|
||||
s.push_back((float)k / (float)N);
|
||||
}
|
||||
} else {
|
||||
const int32_t n = steps > 0 ? steps : (int32_t)d.default_steps;
|
||||
/* np.linspace(1.0, 1 / n, n) in f64, then astype(f32). */
|
||||
@@ -94,6 +104,127 @@ std::vector<float> schedule(const RadGeneratorDecl& d, const std::vector<double>
|
||||
return s;
|
||||
}
|
||||
|
||||
/* ================================================================== a discrete-time schedule */
|
||||
float DiscreteTable::sigma_at(double t) const {
|
||||
const double hi = (double)(log_sigmas.size() - 1);
|
||||
t = t < 0.0 ? 0.0 : t > hi ? hi : t;
|
||||
const size_t lo = (size_t)std::floor(t), up = (size_t)std::ceil(t);
|
||||
const float w = (float)(t - std::floor(t));
|
||||
return std::exp((1.0f - w) * log_sigmas[lo] + w * log_sigmas[up]);
|
||||
}
|
||||
|
||||
int32_t DiscreteTable::timestep(float sigma) const {
|
||||
const float l = std::log(sigma);
|
||||
int32_t best = 0;
|
||||
float bd = std::fabs(l - log_sigmas[0]);
|
||||
for (size_t i = 1; i < log_sigmas.size(); ++i) {
|
||||
const float d = std::fabs(l - log_sigmas[i]);
|
||||
if (d < bd) { bd = d; best = (int32_t)i; }
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
int discrete_table(const RadGeneratorDecl& d, DiscreteTable* out, std::string* why) {
|
||||
const int32_t n = d.train_steps;
|
||||
if (n < 2 || !(d.beta_start > 0) || !(d.beta_end > d.beta_start) || d.beta_end >= 1 ||
|
||||
(d.beta_schedule != RAD_GEN_BETAS_SCALED_LINEAR && d.beta_schedule != RAD_GEN_BETAS_LINEAR)) {
|
||||
if (why) *why = "the discrete schedule needs two or more timesteps and betas rising in (0, 1)";
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
std::vector<double> sig((size_t)n);
|
||||
double abar = 1.0;
|
||||
const bool sq = d.beta_schedule == RAD_GEN_BETAS_SCALED_LINEAR;
|
||||
const double a = sq ? std::sqrt(d.beta_start) : d.beta_start;
|
||||
const double b = sq ? std::sqrt(d.beta_end) : d.beta_end;
|
||||
for (int32_t i = 0; i < n; ++i) {
|
||||
const double v = a + (b - a) * (double)i / (double)(n - 1);
|
||||
abar *= 1.0 - (sq ? v * v : v);
|
||||
sig[(size_t)i] = std::sqrt((1.0 - abar) / abar);
|
||||
}
|
||||
if (d.zero_snr) {
|
||||
/* ComfyUI's rescale_zero_terminal_snr_sigmas: sqrt(abar) shifted to end at 0 and scaled
|
||||
* to keep its start, the last abar then set to a small positive value. */
|
||||
std::vector<double> s((size_t)n);
|
||||
for (int32_t i = 0; i < n; ++i) s[(size_t)i] = std::sqrt(1.0 / (sig[(size_t)i] * sig[(size_t)i] + 1.0));
|
||||
const double s0 = s.front(), sT = s.back();
|
||||
for (int32_t i = 0; i < n; ++i) {
|
||||
double v = (s[(size_t)i] - sT) * (s0 / (s0 - sT));
|
||||
double ab = v * v;
|
||||
if (i == n - 1) ab = 4.8973451890853435e-08;
|
||||
sig[(size_t)i] = std::sqrt((1.0 - ab) / ab);
|
||||
}
|
||||
}
|
||||
out->sigmas.resize((size_t)n);
|
||||
out->log_sigmas.resize((size_t)n);
|
||||
for (int32_t i = 0; i < n; ++i) {
|
||||
out->sigmas[(size_t)i] = (float)sig[(size_t)i];
|
||||
out->log_sigmas[(size_t)i] = (float)std::log(sig[(size_t)i]);
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
std::vector<float> schedule_discrete(const RadGeneratorDecl& d, const DiscreteTable& t,
|
||||
int32_t scheduler, int32_t steps) {
|
||||
const int32_t n = steps > 0 ? steps : (int32_t)d.default_steps;
|
||||
std::vector<float> s;
|
||||
const double smin = t.sigma_min(), smax = t.sigma_max();
|
||||
/* A point i of n evenly spaced from `a` to `b`, both ends included. */
|
||||
auto lin = [](double a, double b, int32_t i, int32_t cnt) {
|
||||
return cnt <= 1 ? a : a + (b - a) * (double)i / (double)(cnt - 1);
|
||||
};
|
||||
switch (scheduler) {
|
||||
case RAD_GEN_SCHED_KARRAS: {
|
||||
const double rho = 7.0, lo = std::pow(smin, 1.0 / rho), hi = std::pow(smax, 1.0 / rho);
|
||||
for (int32_t i = 0; i < n; ++i) s.push_back((float)std::pow(lin(hi, lo, i, n), rho));
|
||||
break;
|
||||
}
|
||||
case RAD_GEN_SCHED_EXPONENTIAL:
|
||||
for (int32_t i = 0; i < n; ++i)
|
||||
s.push_back((float)std::exp(lin(std::log(smax), std::log(smin), i, n)));
|
||||
break;
|
||||
case RAD_GEN_SCHED_SIMPLE: {
|
||||
const double stride = (double)t.sigmas.size() / (double)n;
|
||||
for (int32_t i = 0; i < n; ++i)
|
||||
s.push_back(t.sigmas[t.sigmas.size() - 1 - (size_t)((double)i * stride)]);
|
||||
break;
|
||||
}
|
||||
case RAD_GEN_SCHED_SGM_UNIFORM:
|
||||
case RAD_GEN_SCHED_NORMAL:
|
||||
default: {
|
||||
/* Timesteps from the largest sigma's to the smallest's, evenly spaced; sgm_uniform
|
||||
* spaces n + 1 and drops the last. The model's clock ends at 0. */
|
||||
const double a = (double)t.timestep(t.sigma_max()), b = (double)t.timestep(t.sigma_min());
|
||||
const bool sgm = scheduler == RAD_GEN_SCHED_SGM_UNIFORM;
|
||||
const int32_t cnt = sgm ? n + 1 : n;
|
||||
for (int32_t i = 0; i < n; ++i) s.push_back(t.sigma_at(lin(a, b, i, cnt)));
|
||||
break;
|
||||
}
|
||||
}
|
||||
s.push_back(0.0f);
|
||||
return s;
|
||||
}
|
||||
|
||||
namespace {
|
||||
const char* const kSamplers[RAD_GEN_SAMPLER_COUNT] = { "euler", "euler_ancestral", "dpmpp_2m" };
|
||||
const char* const kScheds[RAD_GEN_SCHED_COUNT] = { "normal", "karras", "exponential",
|
||||
"sgm_uniform", "simple" };
|
||||
} /* namespace */
|
||||
|
||||
const char* sampler_name(int32_t id) {
|
||||
return id >= 0 && id < RAD_GEN_SAMPLER_COUNT ? kSamplers[id] : "";
|
||||
}
|
||||
const char* scheduler_name(int32_t id) {
|
||||
return id >= 0 && id < RAD_GEN_SCHED_COUNT ? kScheds[id] : "";
|
||||
}
|
||||
int32_t sampler_id(const std::string& name) {
|
||||
for (int32_t i = 0; i < RAD_GEN_SAMPLER_COUNT; ++i) if (name == kSamplers[i]) return i;
|
||||
return -1;
|
||||
}
|
||||
int32_t scheduler_id(const std::string& name) {
|
||||
for (int32_t i = 0; i < RAD_GEN_SCHED_COUNT; ++i) if (name == kScheds[i]) return i;
|
||||
return -1;
|
||||
}
|
||||
|
||||
/* ================================================================== the sequence */
|
||||
void image_rope(int32_t pos, int32_t h, int32_t w, int32_t* planes, int64_t n_total) {
|
||||
const int32_t h0 = -(h - h / 2), w0 = -(w - w / 2);
|
||||
|
||||
@@ -48,6 +48,9 @@ struct Branch {
|
||||
std::vector<int32_t> tokens;
|
||||
std::shared_ptr<mm::PromptMedia> media; /* null for a prompt with no pictures */
|
||||
int32_t n_drop = 0;
|
||||
/* The user's prompt through the model's second tokenizer (RadGeneratorDecl::aux_tokens);
|
||||
* empty otherwise. */
|
||||
std::vector<int32_t> aux;
|
||||
};
|
||||
|
||||
/* One finished image, or a preview of one. */
|
||||
@@ -99,6 +102,8 @@ struct Request {
|
||||
float cfg = 1.0f;
|
||||
int32_t width = 0, height = 0; /* pixels, whole multiples of the declared multiple */
|
||||
int32_t steps = 0; /* 0: the model's default (or its fixed schedule) */
|
||||
/* A discrete-time model's sampler and scheduler (RAD_GEN_SAMPLER_*, RAD_GEN_SCHED_*). */
|
||||
int32_t sampler = 0, scheduler = 0;
|
||||
int32_t n = 1;
|
||||
uint64_t seed = 0; /* image i draws its noise from seed + i */
|
||||
int32_t previews = 0; /* partial images per image, 0..3 */
|
||||
@@ -109,6 +114,10 @@ struct Request {
|
||||
bool inpaint = false;
|
||||
Pixels inp_src;
|
||||
std::vector<float> inp_mask;
|
||||
/* The runtime LoRA slot every pass of the request runs with (Engine::gen_lora_acquire), -1
|
||||
* for none, and the hold that keeps the slot's adapters in it until the request is done. */
|
||||
int32_t lora_slot = -1;
|
||||
std::shared_ptr<void> lora_hold;
|
||||
std::shared_ptr<Ticket> ticket;
|
||||
};
|
||||
|
||||
@@ -119,6 +128,31 @@ struct Request {
|
||||
std::vector<float> schedule(const RadGeneratorDecl& d, const std::vector<double>& fixed,
|
||||
int32_t steps, int64_t tokens);
|
||||
|
||||
/* ================================================================== a discrete-time schedule */
|
||||
/* The sigma table of a model trained on discrete timesteps (RadGeneratorDecl::train_steps), as
|
||||
* ComfyUI's ModelSamplingDiscrete builds it: betas in f64, their cumulative product, sigma_t =
|
||||
* sqrt((1 - abar_t) / abar_t), then f32, and the f32 logs. */
|
||||
struct DiscreteTable {
|
||||
std::vector<float> sigmas; /* [train_steps], ascending: sigmas[t] is timestep t's */
|
||||
std::vector<float> log_sigmas;
|
||||
float sigma_min() const { return sigmas.front(); }
|
||||
float sigma_max() const { return sigmas.back(); }
|
||||
/* sigma at a fractional timestep: the logs interpolated linearly, t clamped to the table. */
|
||||
float sigma_at(double t) const;
|
||||
/* The timestep a sigma is conditioned at: the table's nearest in log sigma. */
|
||||
int32_t timestep(float sigma) const;
|
||||
};
|
||||
/* RAD_E_INVAL with `why` for a declaration whose schedule cannot be built. */
|
||||
int discrete_table(const RadGeneratorDecl& d, DiscreteTable* out, std::string* why);
|
||||
/* The n + 1 sigmas `scheduler` places for `steps` (0: the default) steps, the last 0. */
|
||||
std::vector<float> schedule_discrete(const RadGeneratorDecl& d, const DiscreteTable& t,
|
||||
int32_t scheduler, int32_t steps);
|
||||
/* The names a request spells samplers and schedulers by, and their ids (-1: none). */
|
||||
const char* sampler_name(int32_t id);
|
||||
const char* scheduler_name(int32_t id);
|
||||
int32_t sampler_id(const std::string& name);
|
||||
int32_t scheduler_id(const std::string& name);
|
||||
|
||||
/* ================================================================== the generator's sequence */
|
||||
/* One conditioning sequence as the generator sees it (RadGeneratorDecl::layout): the prompt row or
|
||||
* reference latent row behind each row, rotary positions, segments, and the output image's frame. */
|
||||
|
||||
@@ -29,6 +29,8 @@ struct IPassDriver {
|
||||
* `step` is the engine's pass counter, carried into RadBatch::step. */
|
||||
virtual const RadBatch* next(int step) = 0;
|
||||
virtual const RadBatch* batch_for(int rank) const = 0;
|
||||
/* The runtime LoRA slot every row of the staged pass runs with, -1 for none. */
|
||||
virtual int32_t lora_slot() const { return -1; }
|
||||
/* What the staged pass's results are, valid until done(). */
|
||||
virtual const std::vector<Readback>& readbacks() const = 0;
|
||||
/* The pass has run on every rank, its streams are drained and the readbacks have landed. */
|
||||
|
||||
@@ -95,6 +95,11 @@ struct VideoRequest {
|
||||
std::vector<uint8_t> image;
|
||||
/* The decoder (RadVideoGenDecl::decoders) by its index; 0 the model's default. */
|
||||
int32_t decoder = 0;
|
||||
/* The runtime LoRA slot the request's conditioning and denoising passes run with
|
||||
* (Engine::gen_lora_acquire), -1 for none, and the hold that keeps it until the request is
|
||||
* done. */
|
||||
int32_t lora_slot = -1;
|
||||
std::shared_ptr<void> lora_hold;
|
||||
std::shared_ptr<VideoTicket> ticket;
|
||||
};
|
||||
|
||||
|
||||
@@ -809,6 +809,7 @@ const RadBatch* VideoDriver::build_cond(Job& j, int step) {
|
||||
if (j.auto_len) rb_.assign(1, Readback{ decl_.duration_out, 4, duration_host_ });
|
||||
pass_.kind = RAD_GEN_PASS_VCOND;
|
||||
pass_.job = j.id;
|
||||
pass_.lora_slot = j.req->lora_slot;
|
||||
return &out_[0];
|
||||
}
|
||||
|
||||
@@ -858,6 +859,7 @@ const RadBatch* VideoDriver::build_step(Job& j, int step) {
|
||||
for (auto& B : out_) B.gen = RAD_GEN_PASS_VSTEP;
|
||||
pass_.kind = RAD_GEN_PASS_VSTEP;
|
||||
pass_.job = j.id;
|
||||
pass_.lora_slot = j.req->lora_slot;
|
||||
return &out_[0];
|
||||
}
|
||||
|
||||
|
||||
@@ -53,6 +53,7 @@ public:
|
||||
/* ---------------------------------------------------------- the engine thread */
|
||||
const RadBatch* next(int step) override;
|
||||
const RadBatch* batch_for(int rank) const override;
|
||||
int32_t lora_slot() const override { return pass_.lora_slot; }
|
||||
const std::vector<Readback>& readbacks() const override { return rb_; }
|
||||
int done() override;
|
||||
|
||||
@@ -99,6 +100,7 @@ private:
|
||||
int kind = 0;
|
||||
uint64_t job = 0;
|
||||
int32_t n_frames = 0;
|
||||
int32_t lora_slot = -1;
|
||||
};
|
||||
|
||||
/* Staging regions: their offsets in the host span and every rank's slab. */
|
||||
|
||||
@@ -0,0 +1,986 @@
|
||||
/* lora/adapter.cpp -- see adapter.h. Host code only. */
|
||||
#include "adapter.h"
|
||||
|
||||
#include "rad_plugin.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <atomic>
|
||||
#include <cmath>
|
||||
#include <cstdarg>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <map>
|
||||
#include <regex>
|
||||
#include <thread>
|
||||
#include <unordered_map>
|
||||
|
||||
namespace rad {
|
||||
namespace lora {
|
||||
|
||||
namespace {
|
||||
|
||||
#define TRY(x) do { const int s_ = (x); if (s_ < 0) return s_; } while (0)
|
||||
|
||||
std::string fmt(const char* f, ...) __attribute__((format(printf, 1, 2)));
|
||||
std::string fmt(const char* f, ...) {
|
||||
char buf[2048];
|
||||
va_list ap;
|
||||
va_start(ap, f);
|
||||
vsnprintf(buf, sizeof buf, f, ap);
|
||||
va_end(ap);
|
||||
return buf;
|
||||
}
|
||||
|
||||
int fail(std::string* err, int code, const std::string& m) {
|
||||
if (err) *err = m;
|
||||
return code;
|
||||
}
|
||||
|
||||
bool ends_with(const std::string& s, const char* p) {
|
||||
const size_t n = std::strlen(p);
|
||||
return s.size() >= n && s.compare(s.size() - n, n, p) == 0;
|
||||
}
|
||||
|
||||
std::string shape_str(const std::vector<int64_t>& s) {
|
||||
std::string r = "[";
|
||||
for (size_t i = 0; i < s.size(); ++i) r += (i ? ", " : "") + std::to_string(s[i]);
|
||||
return r + "]";
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- tensors as f32 */
|
||||
bool float_dtype(uint32_t dt) { return dt == RAD_BF16 || dt == RAD_F16 || dt == RAD_F32; }
|
||||
|
||||
float elem(const StTensor& t, int64_t i) {
|
||||
switch (t.dtype) {
|
||||
case RAD_BF16: { uint16_t v; std::memcpy(&v, t.data + 2 * i, 2); return rad_bf16_to_f32(v); }
|
||||
case RAD_F16: { uint16_t v; std::memcpy(&v, t.data + 2 * i, 2); return rad_f16_to_f32(v); }
|
||||
default: { float v; std::memcpy(&v, t.data + 4 * i, 4); return v; }
|
||||
}
|
||||
}
|
||||
|
||||
/* A tensor as a row-major matrix [shape[0], product of the rest]. */
|
||||
int as_matrix(const StTensor* t, const char* what, int64_t* rows, int64_t* cols,
|
||||
std::vector<float>* out, std::string* err) {
|
||||
if (!t) return fail(err, RAD_E_FORMAT, fmt("no %s tensor", what));
|
||||
if (!float_dtype(t->dtype))
|
||||
return fail(err, RAD_E_DTYPE, fmt("%s is %s; expected BF16, F16 or F32", t->name.c_str(),
|
||||
t->dtype_str.c_str()));
|
||||
if (t->shape.size() < 2 || !t->data)
|
||||
return fail(err, RAD_E_SHAPE, fmt("%s has shape %s; expected a matrix", t->name.c_str(),
|
||||
shape_str(t->shape).c_str()));
|
||||
*rows = t->shape[0];
|
||||
*cols = t->numel() / (t->shape[0] ? t->shape[0] : 1);
|
||||
if (out) {
|
||||
out->resize((size_t)(*rows * *cols));
|
||||
for (int64_t i = 0; i < *rows * *cols; ++i) (*out)[(size_t)i] = elem(*t, i);
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* The trailing dims past the first two, all 1 (an up projection of a convolution is 1 x 1). */
|
||||
bool trailing_ones(const StTensor* t) {
|
||||
for (size_t i = 2; i < t->shape.size(); ++i) if (t->shape[i] != 1) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
/* One number: shape [] (numel() counts it as no element) or [1], a float or (as some trainers
|
||||
* write an alpha) an integer or F64. */
|
||||
int scalar(const StTensor* t, double* v, std::string* err) {
|
||||
const int64_t n = t->shape.empty() ? 1 : t->numel();
|
||||
if (n != 1 || !t->data)
|
||||
return fail(err, RAD_E_FORMAT, fmt("%s is not one number", t->name.c_str()));
|
||||
if (float_dtype(t->dtype)) {
|
||||
*v = elem(*t, 0);
|
||||
} else if (t->dtype == RAD_I64 && t->bytes >= 8) {
|
||||
int64_t x; std::memcpy(&x, t->data, 8); *v = (double)x;
|
||||
} else if (t->dtype == RAD_I32 && t->bytes >= 4) {
|
||||
int32_t x; std::memcpy(&x, t->data, 4); *v = (double)x;
|
||||
} else if (t->dtype_str == "F64" && t->bytes >= 8) {
|
||||
std::memcpy(v, t->data, 8);
|
||||
} else {
|
||||
return fail(err, RAD_E_FORMAT, fmt("%s is %s, not a number this reader knows",
|
||||
t->name.c_str(), t->dtype_str.c_str()));
|
||||
}
|
||||
return std::isfinite(*v) ? RAD_OK : fail(err, RAD_E_FORMAT, t->name + " is not finite");
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- dense f32 kernels */
|
||||
/* C[m, n] (+)= A[m, k] B[k, n], row-major. */
|
||||
void mm(const float* A, const float* B, float* C, int64_t m, int64_t k, int64_t n, bool add = false) {
|
||||
if (!add) std::fill(C, C + m * n, 0.0f);
|
||||
for (int64_t i = 0; i < m; ++i) {
|
||||
float* c = C + i * n;
|
||||
for (int64_t p = 0; p < k; ++p) {
|
||||
const float a = A[i * k + p];
|
||||
if (a == 0.0f) continue;
|
||||
const float* b = B + p * n;
|
||||
for (int64_t j = 0; j < n; ++j) c[j] += a * b[j];
|
||||
}
|
||||
}
|
||||
}
|
||||
/* C[m, n] (+)= A[k, m]^T B[k, n]. */
|
||||
void mm_tn(const float* A, const float* B, float* C, int64_t m, int64_t k, int64_t n, bool add = false) {
|
||||
if (!add) std::fill(C, C + m * n, 0.0f);
|
||||
for (int64_t p = 0; p < k; ++p) {
|
||||
const float* a = A + p * m;
|
||||
const float* b = B + p * n;
|
||||
for (int64_t i = 0; i < m; ++i) {
|
||||
const float x = a[i];
|
||||
if (x == 0.0f) continue;
|
||||
float* c = C + i * n;
|
||||
for (int64_t j = 0; j < n; ++j) c[j] += x * b[j];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* Orthonormalise the l columns of Y [n, l] in place (modified Gram-Schmidt, twice). A column
|
||||
* that vanishes is left zero. */
|
||||
void orth(float* Y, int64_t n, int64_t l) {
|
||||
std::vector<double> col((size_t)n);
|
||||
for (int64_t j = 0; j < l; ++j) {
|
||||
for (int pass = 0; pass < 2; ++pass)
|
||||
for (int64_t i = 0; i < j; ++i) {
|
||||
double d = 0.0;
|
||||
for (int64_t r = 0; r < n; ++r) d += (double)Y[r * l + i] * Y[r * l + j];
|
||||
for (int64_t r = 0; r < n; ++r) Y[r * l + j] -= (float)(d * Y[r * l + i]);
|
||||
}
|
||||
double nn = 0.0;
|
||||
for (int64_t r = 0; r < n; ++r) nn += (double)Y[r * l + j] * Y[r * l + j];
|
||||
const double inv = nn > 1e-30 ? 1.0 / std::sqrt(nn) : 0.0;
|
||||
for (int64_t r = 0; r < n; ++r) Y[r * l + j] = (float)(Y[r * l + j] * inv);
|
||||
}
|
||||
}
|
||||
|
||||
/* Eigen-decomposition of a symmetric l x l matrix (cyclic Jacobi): eigenvalues in `w`, sorted
|
||||
* descending, and eigenvectors as the columns of V [l, l]. */
|
||||
void sym_eig(std::vector<double> G, int64_t l, std::vector<double>* w, std::vector<double>* V) {
|
||||
V->assign((size_t)(l * l), 0.0);
|
||||
for (int64_t i = 0; i < l; ++i) (*V)[(size_t)(i * l + i)] = 1.0;
|
||||
for (int sweep = 0; sweep < 60; ++sweep) {
|
||||
double off = 0.0, tot = 0.0;
|
||||
for (int64_t i = 0; i < l; ++i)
|
||||
for (int64_t j = 0; j < l; ++j) {
|
||||
const double g = G[(size_t)(i * l + j)];
|
||||
tot += g * g;
|
||||
if (i != j) off += g * g;
|
||||
}
|
||||
if (off <= 1e-24 * (tot > 0 ? tot : 1.0)) break;
|
||||
for (int64_t p = 0; p < l; ++p)
|
||||
for (int64_t q = p + 1; q < l; ++q) {
|
||||
const double gpq = G[(size_t)(p * l + q)];
|
||||
if (std::fabs(gpq) < 1e-300) continue;
|
||||
const double gpp = G[(size_t)(p * l + p)], gqq = G[(size_t)(q * l + q)];
|
||||
const double th = (gqq - gpp) / (2.0 * gpq);
|
||||
const double t = (th >= 0 ? 1.0 : -1.0) / (std::fabs(th) + std::sqrt(th * th + 1.0));
|
||||
const double c = 1.0 / std::sqrt(t * t + 1.0), s = t * c;
|
||||
for (int64_t k = 0; k < l; ++k) {
|
||||
const double gkp = G[(size_t)(k * l + p)], gkq = G[(size_t)(k * l + q)];
|
||||
G[(size_t)(k * l + p)] = c * gkp - s * gkq;
|
||||
G[(size_t)(k * l + q)] = s * gkp + c * gkq;
|
||||
}
|
||||
for (int64_t k = 0; k < l; ++k) {
|
||||
const double gpk = G[(size_t)(p * l + k)], gqk = G[(size_t)(q * l + k)];
|
||||
G[(size_t)(p * l + k)] = c * gpk - s * gqk;
|
||||
G[(size_t)(q * l + k)] = s * gpk + c * gqk;
|
||||
}
|
||||
for (int64_t k = 0; k < l; ++k) {
|
||||
const double vkp = (*V)[(size_t)(k * l + p)], vkq = (*V)[(size_t)(k * l + q)];
|
||||
(*V)[(size_t)(k * l + p)] = c * vkp - s * vkq;
|
||||
(*V)[(size_t)(k * l + q)] = s * vkp + c * vkq;
|
||||
}
|
||||
}
|
||||
}
|
||||
std::vector<int64_t> ord((size_t)l);
|
||||
for (int64_t i = 0; i < l; ++i) ord[(size_t)i] = i;
|
||||
std::sort(ord.begin(), ord.end(), [&](int64_t a, int64_t b) {
|
||||
return G[(size_t)(a * l + a)] > G[(size_t)(b * l + b)];
|
||||
});
|
||||
std::vector<double> V2((size_t)(l * l));
|
||||
w->resize((size_t)l);
|
||||
for (int64_t c = 0; c < l; ++c) {
|
||||
(*w)[(size_t)c] = G[(size_t)(ord[(size_t)c] * l + ord[(size_t)c])];
|
||||
for (int64_t r = 0; r < l; ++r) V2[(size_t)(r * l + c)] = (*V)[(size_t)(r * l + ord[(size_t)c])];
|
||||
}
|
||||
*V = std::move(V2);
|
||||
}
|
||||
|
||||
/* ||B A||_F^2 for B [n, r], A [r, k]: trace((B^T B)(A A^T)). */
|
||||
double lowrank_energy(const std::vector<float>& B, const std::vector<float>& A, int64_t n, int64_t r,
|
||||
int64_t k) {
|
||||
std::vector<double> bb((size_t)(r * r), 0.0), aa((size_t)(r * r), 0.0);
|
||||
for (int64_t i = 0; i < n; ++i)
|
||||
for (int64_t p = 0; p < r; ++p) {
|
||||
const double x = B[(size_t)(i * r + p)];
|
||||
if (x == 0.0) continue;
|
||||
for (int64_t q = 0; q < r; ++q) bb[(size_t)(p * r + q)] += x * B[(size_t)(i * r + q)];
|
||||
}
|
||||
for (int64_t p = 0; p < r; ++p)
|
||||
for (int64_t q = p; q < r; ++q) {
|
||||
double d = 0.0;
|
||||
for (int64_t j = 0; j < k; ++j) d += (double)A[(size_t)(p * k + j)] * A[(size_t)(q * k + j)];
|
||||
aa[(size_t)(p * r + q)] = aa[(size_t)(q * r + p)] = d;
|
||||
}
|
||||
double e = 0.0;
|
||||
for (size_t i = 0; i < bb.size(); ++i) e += bb[i] * aa[i];
|
||||
return e;
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- the key suffixes */
|
||||
struct Suffix {
|
||||
const char* s;
|
||||
int kind; /* FileModule::Kind, or -1 alpha, -2 refused, -3 skipped */
|
||||
int slot;
|
||||
const char* why;
|
||||
};
|
||||
const Suffix kSuffix[] = {
|
||||
{ ".lora_down.weight", FileModule::LORA, 0, nullptr },
|
||||
{ ".lora_up.weight", FileModule::LORA, 1, nullptr },
|
||||
{ ".lora_A.default.weight", FileModule::LORA, 0, nullptr },
|
||||
{ ".lora_B.default.weight", FileModule::LORA, 1, nullptr },
|
||||
{ ".lora_A.weight", FileModule::LORA, 0, nullptr },
|
||||
{ ".lora_B.weight", FileModule::LORA, 1, nullptr },
|
||||
{ ".lora_linear_layer.down.weight", FileModule::LORA, 0, nullptr },
|
||||
{ ".lora_linear_layer.up.weight", FileModule::LORA, 1, nullptr },
|
||||
{ ".lora.down.weight", FileModule::LORA, 0, nullptr },
|
||||
{ ".lora.up.weight", FileModule::LORA, 1, nullptr },
|
||||
{ ".hada_w1_a", FileModule::LOHA, 0, nullptr },
|
||||
{ ".hada_w1_b", FileModule::LOHA, 1, nullptr },
|
||||
{ ".hada_w2_a", FileModule::LOHA, 2, nullptr },
|
||||
{ ".hada_w2_b", FileModule::LOHA, 3, nullptr },
|
||||
{ ".lokr_w1", FileModule::LOKR, 0, nullptr },
|
||||
{ ".lokr_w1_a", FileModule::LOKR, 1, nullptr },
|
||||
{ ".lokr_w1_b", FileModule::LOKR, 2, nullptr },
|
||||
{ ".lokr_w2", FileModule::LOKR, 3, nullptr },
|
||||
{ ".lokr_w2_a", FileModule::LOKR, 4, nullptr },
|
||||
{ ".lokr_w2_b", FileModule::LOKR, 5, nullptr },
|
||||
{ ".diff", FileModule::FULL, 0, nullptr },
|
||||
{ ".alpha", -1, 0, nullptr },
|
||||
{ ".lora_alpha", -1, 0, nullptr },
|
||||
{ ".dora_scale", -2, 0, "a DoRA magnitude, which rescales the base weight's columns" },
|
||||
{ ".lora_magnitude_vector.default.weight", -2, 0, "a DoRA magnitude, which rescales the base "
|
||||
"weight's columns" },
|
||||
{ ".lora_magnitude_vector.weight", -2, 0, "a DoRA magnitude, which rescales the base weight's "
|
||||
"columns" },
|
||||
{ ".lora_magnitude_vector", -2, 0, "a DoRA magnitude, which rescales the base weight's columns" },
|
||||
{ ".hada_t1", -2, 0, "a LoHa Tucker core" },
|
||||
{ ".hada_t2", -2, 0, "a LoHa Tucker core" },
|
||||
{ ".lokr_t2", -2, 0, "a LoKr Tucker core" },
|
||||
{ ".lora_mid.weight", -2, 0, "a LoCon Tucker core" },
|
||||
{ ".oft_blocks", -2, 0, "an OFT rotation" },
|
||||
{ ".oft_diag", -2, 0, "an OFT rotation" },
|
||||
{ ".oft_R.weight", -2, 0, "an OFT rotation" },
|
||||
{ ".boft_R", -2, 0, "a BOFT rotation" },
|
||||
{ ".diff_b", -3, 0, "a bias delta" },
|
||||
{ ".w_norm", -3, 0, "a norm's weight delta" },
|
||||
{ ".b_norm", -3, 0, "a norm's bias delta" },
|
||||
{ ".lora_B.bias", -3, 0, "a bias on lora_B" },
|
||||
{ ".lora_up.bias", -3, 0, "a bias on lora_up" },
|
||||
{ ".set_weight", -2, 0, "a replacement weight" },
|
||||
};
|
||||
|
||||
} /* namespace */
|
||||
|
||||
/* ================================================================== the file */
|
||||
int AdapterFile::open(const std::string& path, std::string* err) {
|
||||
mods_.clear();
|
||||
skipped_.clear();
|
||||
if (st_.open(path) != RAD_OK) return fail(err, RAD_E_IO, path + ": cannot open as safetensors");
|
||||
std::map<std::string, FileModule> by;
|
||||
std::map<std::string, const StTensor*> alphas;
|
||||
for (const StTensor& t : st_.tensors()) {
|
||||
const Suffix* hit = nullptr;
|
||||
for (const Suffix& s : kSuffix)
|
||||
if (ends_with(t.name, s.s) && (!hit || std::strlen(s.s) > std::strlen(hit->s))) hit = &s;
|
||||
if (!hit) {
|
||||
skipped_.push_back({ t.name, "not an adapter tensor" });
|
||||
continue;
|
||||
}
|
||||
const std::string key = t.name.substr(0, t.name.size() - std::strlen(hit->s));
|
||||
if (hit->kind == -2)
|
||||
return fail(err, RAD_E_UNSUPPORTED, fmt("%s: %s is %s; that kind of adapter is not "
|
||||
"served", path.c_str(), t.name.c_str(), hit->why));
|
||||
if (hit->kind == -3) { skipped_.push_back({ t.name, hit->why }); continue; }
|
||||
if (hit->kind == -1) { alphas[key] = &t; continue; }
|
||||
FileModule& m = by[key];
|
||||
if (m.key.empty()) { m.key = key; m.kind = (FileModule::Kind)hit->kind; }
|
||||
else if (m.kind != hit->kind)
|
||||
return fail(err, RAD_E_FORMAT, fmt("%s: module %s mixes adapter kinds", path.c_str(),
|
||||
key.c_str()));
|
||||
if (m.t[hit->slot])
|
||||
return fail(err, RAD_E_FORMAT, fmt("%s: module %s has two %s tensors", path.c_str(),
|
||||
key.c_str(), hit->s));
|
||||
m.t[hit->slot] = &t;
|
||||
}
|
||||
for (auto& [k, a] : alphas) {
|
||||
auto it = by.find(k);
|
||||
if (it == by.end()) { skipped_.push_back({ a->name, "an alpha of no module" }); continue; }
|
||||
it->second.alpha = a;
|
||||
}
|
||||
for (auto& [k, m] : by) {
|
||||
const char* missing = nullptr;
|
||||
switch (m.kind) {
|
||||
case FileModule::LORA:
|
||||
if (!m.t[0] || !m.t[1]) missing = m.t[0] ? "up/B" : "down/A";
|
||||
break;
|
||||
case FileModule::LOHA:
|
||||
if (!m.t[0] || !m.t[1] || !m.t[2] || !m.t[3]) missing = "a hada_w factor";
|
||||
break;
|
||||
case FileModule::LOKR:
|
||||
if (!m.t[0] && !(m.t[1] && m.t[2])) missing = "lokr_w1 (or lokr_w1_a and _b)";
|
||||
else if (!m.t[3] && !(m.t[4] && m.t[5])) missing = "lokr_w2 (or lokr_w2_a and _b)";
|
||||
break;
|
||||
case FileModule::FULL: break;
|
||||
}
|
||||
if (missing)
|
||||
return fail(err, RAD_E_FORMAT, fmt("%s: module %s has no %s", path.c_str(), k.c_str(),
|
||||
missing));
|
||||
mods_.push_back(m);
|
||||
}
|
||||
if (mods_.empty()) return fail(err, RAD_E_FORMAT, path + ": no adapter modules in the file");
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
const char* AdapterFile::kind_name() const {
|
||||
int n[4] = { 0, 0, 0, 0 };
|
||||
for (const FileModule& m : mods_) ++n[m.kind];
|
||||
const int k = (int)(std::max_element(n, n + 4) - n);
|
||||
static const char* const kName[] = { "LoRA", "LoHa", "LoKr", "full" };
|
||||
return kName[k];
|
||||
}
|
||||
|
||||
/* ================================================================== deltas */
|
||||
int module_delta(const FileModule& m, double w, Delta* out, std::string* err) {
|
||||
*out = Delta{};
|
||||
double alpha = 0.0;
|
||||
const bool has_alpha = m.alpha != nullptr;
|
||||
if (has_alpha) TRY(scalar(m.alpha, &alpha, err));
|
||||
|
||||
if (m.kind == FileModule::LORA) {
|
||||
int64_t r = 0, K = 0, N = 0, r2 = 0;
|
||||
std::vector<float> A, B;
|
||||
TRY(as_matrix(m.t[0], "down", &r, &K, &A, err));
|
||||
TRY(as_matrix(m.t[1], "up", &N, &r2, &B, err));
|
||||
if (!trailing_ones(m.t[1]) || r2 != r)
|
||||
return fail(err, RAD_E_SHAPE, fmt("module %s: down %s and up %s are not one rank-%lld "
|
||||
"pair", m.key.c_str(), shape_str(m.t[0]->shape).c_str(),
|
||||
shape_str(m.t[1]->shape).c_str(), (long long)r));
|
||||
const double s = w * (has_alpha && r > 0 ? alpha / (double)r : 1.0);
|
||||
for (float& x : B) x = (float)(x * s);
|
||||
out->N = N; out->K = K; out->r = r; out->rank_bound = r; out->low_rank = true;
|
||||
out->A = std::move(A); out->B = std::move(B);
|
||||
out->energy = lowrank_energy(out->B, out->A, N, r, K);
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
if (m.kind == FileModule::LOHA) {
|
||||
int64_t N1 = 0, r1 = 0, r1b = 0, K1 = 0, N2 = 0, r2 = 0, r2b = 0, K2 = 0;
|
||||
std::vector<float> w1a, w1b, w2a, w2b;
|
||||
TRY(as_matrix(m.t[0], "hada_w1_a", &N1, &r1, &w1a, err));
|
||||
TRY(as_matrix(m.t[1], "hada_w1_b", &r1b, &K1, &w1b, err));
|
||||
TRY(as_matrix(m.t[2], "hada_w2_a", &N2, &r2, &w2a, err));
|
||||
TRY(as_matrix(m.t[3], "hada_w2_b", &r2b, &K2, &w2b, err));
|
||||
if (r1 != r1b || r2 != r2b || N1 != N2 || K1 != K2)
|
||||
return fail(err, RAD_E_SHAPE, fmt("module %s: LoHa factors %s %s %s %s do not pair",
|
||||
m.key.c_str(), shape_str(m.t[0]->shape).c_str(),
|
||||
shape_str(m.t[1]->shape).c_str(),
|
||||
shape_str(m.t[2]->shape).c_str(),
|
||||
shape_str(m.t[3]->shape).c_str()));
|
||||
/* (w1a w1b) o (w2a w2b) = sum over (i, j) of (w1a[:, i] o w2a[:, j]) (w1b[i] o w2b[j]):
|
||||
* exactly rank r1 r2. */
|
||||
const double s = w * (has_alpha && r1 > 0 ? alpha / (double)r1 : 1.0);
|
||||
const int64_t R = r1 * r2, N = N1, K = K1;
|
||||
out->B.assign((size_t)(N * R), 0.0f);
|
||||
out->A.assign((size_t)(R * K), 0.0f);
|
||||
for (int64_t n = 0; n < N; ++n)
|
||||
for (int64_t i = 0; i < r1; ++i)
|
||||
for (int64_t j = 0; j < r2; ++j)
|
||||
out->B[(size_t)(n * R + i * r2 + j)] =
|
||||
(float)(s * w1a[(size_t)(n * r1 + i)] * w2a[(size_t)(n * r2 + j)]);
|
||||
for (int64_t i = 0; i < r1; ++i)
|
||||
for (int64_t j = 0; j < r2; ++j)
|
||||
for (int64_t k = 0; k < K; ++k)
|
||||
out->A[(size_t)((i * r2 + j) * K + k)] = w1b[(size_t)(i * K + k)] * w2b[(size_t)(j * K + k)];
|
||||
out->N = N; out->K = K; out->r = R; out->rank_bound = R; out->low_rank = true;
|
||||
out->energy = lowrank_energy(out->B, out->A, N, R, K);
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
if (m.kind == FileModule::LOKR) {
|
||||
/* kron(w1 [a, b], w2 [c, e]) is [a c, b e]: element (i1 c + i2, j1 e + j2) is
|
||||
* w1[i1, j1] w2[i2, j2]. A convolution's w2 [c, d, kh, kw] flattens to e = d kh kw, which
|
||||
* is the flattened kron of the 4-D tensors. */
|
||||
int64_t a = 0, b = 0, dim = 0;
|
||||
std::vector<float> W1;
|
||||
if (m.t[0]) {
|
||||
TRY(as_matrix(m.t[0], "lokr_w1", &a, &b, &W1, err));
|
||||
} else {
|
||||
int64_t r = 0, r2 = 0;
|
||||
std::vector<float> x, y;
|
||||
TRY(as_matrix(m.t[1], "lokr_w1_a", &a, &r, &x, err));
|
||||
TRY(as_matrix(m.t[2], "lokr_w1_b", &r2, &b, &y, err));
|
||||
if (r != r2) return fail(err, RAD_E_SHAPE, "module " + m.key + ": lokr_w1_a/_b ranks differ");
|
||||
W1.resize((size_t)(a * b));
|
||||
mm(x.data(), y.data(), W1.data(), a, r, b);
|
||||
dim = r;
|
||||
}
|
||||
int64_t c = 0, e = 0, r2 = 0;
|
||||
auto W2 = std::make_shared<std::vector<float>>();
|
||||
auto W2a = std::make_shared<std::vector<float>>();
|
||||
auto W2b = std::make_shared<std::vector<float>>();
|
||||
if (m.t[3]) {
|
||||
TRY(as_matrix(m.t[3], "lokr_w2", &c, &e, W2.get(), err));
|
||||
} else {
|
||||
int64_t rr = 0;
|
||||
TRY(as_matrix(m.t[4], "lokr_w2_a", &c, &r2, W2a.get(), err));
|
||||
TRY(as_matrix(m.t[5], "lokr_w2_b", &rr, &e, W2b.get(), err));
|
||||
if (rr != r2) return fail(err, RAD_E_SHAPE, "module " + m.key + ": lokr_w2_a/_b ranks differ");
|
||||
dim = r2;
|
||||
}
|
||||
const double s = w * (has_alpha && dim > 0 ? alpha / (double)dim : 1.0);
|
||||
for (float& x : W1) x = (float)(x * s);
|
||||
auto w1 = std::make_shared<std::vector<float>>(std::move(W1));
|
||||
const int64_t N = a * c, K = b * e;
|
||||
out->N = N; out->K = K;
|
||||
out->rank_bound = std::min(a, b) * (r2 ? r2 : std::min(c, e));
|
||||
const bool full2 = !W2->empty();
|
||||
/* ||kron(w1, w2)|| = ||w1|| ||w2|| */
|
||||
{
|
||||
double e1 = 0.0;
|
||||
for (float x : *w1) e1 += (double)x * x;
|
||||
double e2 = 0.0;
|
||||
if (full2) for (float x : *W2) e2 += (double)x * x;
|
||||
else e2 = lowrank_energy(*W2a, *W2b, c, r2, e);
|
||||
out->energy = e1 * e2;
|
||||
}
|
||||
/* Column x of X [K, l], as the matrix [b, e]: kron(w1, w2) x = w1 X w2^T, read as [a, c]. */
|
||||
out->apply = [=](const float* X, int64_t l, float* Y) {
|
||||
std::vector<float> xm((size_t)(b * e)), t((size_t)(b * c)), y((size_t)(a * c)), u;
|
||||
for (int64_t col = 0; col < l; ++col) {
|
||||
for (int64_t k = 0; k < K; ++k) xm[(size_t)k] = X[k * l + col];
|
||||
if (full2) {
|
||||
/* t[j1, i2] = sum_j2 xm[j1, j2] w2[i2, j2] */
|
||||
for (int64_t j1 = 0; j1 < b; ++j1)
|
||||
for (int64_t i2 = 0; i2 < c; ++i2) {
|
||||
float d = 0.0f;
|
||||
const float* xr = xm.data() + j1 * e;
|
||||
const float* wr = W2->data() + i2 * e;
|
||||
for (int64_t j2 = 0; j2 < e; ++j2) d += xr[j2] * wr[j2];
|
||||
t[(size_t)(j1 * c + i2)] = d;
|
||||
}
|
||||
} else {
|
||||
u.assign((size_t)(b * r2), 0.0f);
|
||||
for (int64_t j1 = 0; j1 < b; ++j1)
|
||||
for (int64_t p = 0; p < r2; ++p) {
|
||||
float d = 0.0f;
|
||||
const float* xr = xm.data() + j1 * e;
|
||||
const float* wr = W2b->data() + p * e;
|
||||
for (int64_t j2 = 0; j2 < e; ++j2) d += xr[j2] * wr[j2];
|
||||
u[(size_t)(j1 * r2 + p)] = d;
|
||||
}
|
||||
for (int64_t j1 = 0; j1 < b; ++j1)
|
||||
for (int64_t i2 = 0; i2 < c; ++i2) {
|
||||
float d = 0.0f;
|
||||
for (int64_t p = 0; p < r2; ++p) d += u[(size_t)(j1 * r2 + p)] * (*W2a)[(size_t)(i2 * r2 + p)];
|
||||
t[(size_t)(j1 * c + i2)] = d;
|
||||
}
|
||||
}
|
||||
mm(w1->data(), t.data(), y.data(), a, b, c);
|
||||
for (int64_t n = 0; n < N; ++n) Y[n * l + col] = y[(size_t)n];
|
||||
}
|
||||
};
|
||||
/* The transpose: kron(w1, w2)^T y = w1^T Y w2, Y the column as [a, c], read as [b, e]. */
|
||||
out->apply_t = [=](const float* Yin, int64_t l, float* X) {
|
||||
std::vector<float> ym((size_t)(a * c)), t((size_t)(b * c)), x((size_t)(b * e)), u;
|
||||
for (int64_t col = 0; col < l; ++col) {
|
||||
for (int64_t n = 0; n < N; ++n) ym[(size_t)n] = Yin[n * l + col];
|
||||
mm_tn(w1->data(), ym.data(), t.data(), b, a, c); /* [b, c] */
|
||||
if (full2) {
|
||||
mm(t.data(), W2->data(), x.data(), b, c, e);
|
||||
} else {
|
||||
u.assign((size_t)(b * r2), 0.0f);
|
||||
mm(t.data(), W2a->data(), u.data(), b, c, r2);
|
||||
mm(u.data(), W2b->data(), x.data(), b, r2, e);
|
||||
}
|
||||
for (int64_t k = 0; k < K; ++k) X[k * l + col] = x[(size_t)k];
|
||||
}
|
||||
};
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* FULL */
|
||||
int64_t N = 0, K = 0;
|
||||
auto D = std::make_shared<std::vector<float>>();
|
||||
TRY(as_matrix(m.t[0], "diff", &N, &K, D.get(), err));
|
||||
for (float& x : *D) x = (float)(x * w);
|
||||
out->N = N; out->K = K; out->rank_bound = std::min(N, K);
|
||||
out->energy = 0.0;
|
||||
for (float x : *D) out->energy += (double)x * x;
|
||||
out->apply = [D, N, K](const float* X, int64_t l, float* Y) { mm(D->data(), X, Y, N, K, l); };
|
||||
out->apply_t = [D, N, K](const float* Yin, int64_t l, float* X) { mm_tn(D->data(), Yin, X, K, N, l); };
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
void truncate(const Delta& d, int64_t r, std::vector<float>* B, std::vector<float>* A, double* kept) {
|
||||
const int64_t N = d.N, K = d.K;
|
||||
r = std::max<int64_t>(0, std::min({ r, N, K, d.rank_bound > 0 ? d.rank_bound : r }));
|
||||
if (kept) *kept = 1.0;
|
||||
if (d.low_rank && d.r <= r) { *B = d.B; *A = d.A; return; }
|
||||
auto fwd = [&](const float* X, int64_t l, float* Y) {
|
||||
if (!d.low_rank) { d.apply(X, l, Y); return; }
|
||||
std::vector<float> t((size_t)(d.r * l));
|
||||
mm(d.A.data(), X, t.data(), d.r, K, l);
|
||||
mm(d.B.data(), t.data(), Y, N, d.r, l);
|
||||
};
|
||||
auto bwd = [&](const float* Y, int64_t l, float* X) {
|
||||
if (!d.low_rank) { d.apply_t(Y, l, X); return; }
|
||||
std::vector<float> t((size_t)(d.r * l));
|
||||
mm_tn(d.B.data(), Y, t.data(), d.r, N, l);
|
||||
mm_tn(d.A.data(), t.data(), X, K, d.r, l);
|
||||
};
|
||||
const int64_t l = std::min({ r + 8, N, K });
|
||||
/* A fixed sketch: the same adapter composes to the same bytes on every rank and every load. */
|
||||
std::vector<float> Om((size_t)(K * l));
|
||||
uint64_t st = 0x2545F4914F6CDD1Dull ^ (uint64_t)(N * 1315423911ull + K);
|
||||
for (float& x : Om) {
|
||||
st ^= st << 13; st ^= st >> 7; st ^= st << 17;
|
||||
x = (float)((double)(st >> 11) / (double)(1ull << 53) - 0.5);
|
||||
}
|
||||
std::vector<float> Y((size_t)(N * l)), Z((size_t)(K * l));
|
||||
fwd(Om.data(), l, Y.data());
|
||||
orth(Y.data(), N, l);
|
||||
for (int it = 0; it < 2; ++it) {
|
||||
bwd(Y.data(), l, Z.data());
|
||||
orth(Z.data(), K, l);
|
||||
fwd(Z.data(), l, Y.data());
|
||||
orth(Y.data(), N, l);
|
||||
}
|
||||
/* C^T = D^T Q [K, l]; the SVD of C = Q^T D from the eigen-decomposition of C C^T. */
|
||||
bwd(Y.data(), l, Z.data());
|
||||
std::vector<double> G((size_t)(l * l), 0.0);
|
||||
for (int64_t k = 0; k < K; ++k)
|
||||
for (int64_t i = 0; i < l; ++i) {
|
||||
const double x = Z[(size_t)(k * l + i)];
|
||||
if (x == 0.0) continue;
|
||||
for (int64_t j = i; j < l; ++j) G[(size_t)(i * l + j)] += x * Z[(size_t)(k * l + j)];
|
||||
}
|
||||
for (int64_t i = 0; i < l; ++i)
|
||||
for (int64_t j = 0; j < i; ++j) G[(size_t)(i * l + j)] = G[(size_t)(j * l + i)];
|
||||
std::vector<double> w, V;
|
||||
sym_eig(G, l, &w, &V);
|
||||
double tot = 0.0, top = 0.0;
|
||||
for (int64_t i = 0; i < l; ++i) tot += std::max(0.0, w[(size_t)i]);
|
||||
for (int64_t i = 0; i < r; ++i) top += std::max(0.0, w[(size_t)i]);
|
||||
if (d.energy > 0.0) tot = std::max(tot, d.energy);
|
||||
if (kept) *kept = tot > 0.0 ? std::min(1.0, top / tot) : 1.0;
|
||||
B->assign((size_t)(N * r), 0.0f);
|
||||
A->assign((size_t)(r * K), 0.0f);
|
||||
for (int64_t i = 0; i < r; ++i) {
|
||||
const double sg = std::sqrt(std::max(0.0, w[(size_t)i]));
|
||||
if (sg <= 1e-20) continue;
|
||||
/* B[:, i] = Q V[:, i] sigma_i; A[i] = V[:, i]^T C / sigma_i. */
|
||||
for (int64_t n = 0; n < N; ++n) {
|
||||
double acc = 0.0;
|
||||
for (int64_t j = 0; j < l; ++j) acc += (double)Y[(size_t)(n * l + j)] * V[(size_t)(j * l + i)];
|
||||
(*B)[(size_t)(n * r + i)] = (float)(acc * sg);
|
||||
}
|
||||
for (int64_t k = 0; k < K; ++k) {
|
||||
double acc = 0.0;
|
||||
for (int64_t j = 0; j < l; ++j) acc += V[(size_t)(j * l + i)] * Z[(size_t)(k * l + j)];
|
||||
(*A)[(size_t)(i * K + k)] = (float)(acc / sg);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* ================================================================== the key map */
|
||||
namespace {
|
||||
|
||||
std::string underscored(std::string s) {
|
||||
for (char& c : s) if (c == '.') c = '_';
|
||||
return s;
|
||||
}
|
||||
|
||||
std::regex pattern(const std::string& from, bool kohya) {
|
||||
std::string re = "^";
|
||||
for (char c : kohya ? underscored(from) : from) {
|
||||
if (c == '#') re += "([0-9]+)";
|
||||
else if (std::strchr(".^$|()[]{}*+?\\", c)) { re += '\\'; re += c; }
|
||||
else re += c;
|
||||
}
|
||||
return std::regex(re + "$", std::regex::ECMAScript | std::regex::optimize);
|
||||
}
|
||||
|
||||
std::string module_of(const std::string& src) {
|
||||
return ends_with(src, ".weight") ? src.substr(0, src.size() - 7) : std::string();
|
||||
}
|
||||
|
||||
} /* namespace */
|
||||
|
||||
KeyMap::KeyMap(const Program& prog, const std::vector<Site>& sites) : prog_(&prog) {
|
||||
for (const Site& s : sites)
|
||||
for (size_t i = 0; i < s.sources.size(); ++i) {
|
||||
const SiteSource& src = s.sources[i];
|
||||
if (!src.targeted) continue;
|
||||
const size_t at = src.module.find('@');
|
||||
if (at != std::string::npos) {
|
||||
/* A row piece: the module stays adaptable, its rows open (the adapter's say). */
|
||||
Piece p;
|
||||
p.name = src.module;
|
||||
p.lo = std::strtoll(src.module.c_str() + at + 1, nullptr, 10);
|
||||
const size_t plus = src.module.find('+', at);
|
||||
p.n = plus == std::string::npos ? 0 : std::strtoll(src.module.c_str() + plus + 1, nullptr, 10);
|
||||
const std::string real = src.module.substr(0, at);
|
||||
std::vector<Piece>& ps = pieces_[real];
|
||||
bool dup = false;
|
||||
for (const Piece& q : ps) dup = dup || q.name == p.name;
|
||||
if (!dup) ps.push_back(p);
|
||||
adaptable_[real] = { -1, s.K_full > 0 ? s.K_full : -1 };
|
||||
continue;
|
||||
}
|
||||
whole_.insert(src.module);
|
||||
int64_t rows = -1;
|
||||
if (src.part_lo >= 0) {
|
||||
rows = 0;
|
||||
for (int g = src.part_lo; g < src.part_hi; ++g) {
|
||||
const int64_t t = s.part_total[(size_t)g];
|
||||
if (t <= 0) { rows = -1; break; }
|
||||
rows += t;
|
||||
}
|
||||
} else if (s.sources.size() == 1 && s.part_total.size() == 1 && s.part_total[0] > 0) {
|
||||
rows = s.part_total[0];
|
||||
}
|
||||
adaptable_[src.module] = { rows, s.K_full > 0 ? s.K_full : -1 };
|
||||
}
|
||||
for (const LoraRoot& r : prog.lora_roots) {
|
||||
Root R;
|
||||
R.native = r.native;
|
||||
R.spellings = r.spellings;
|
||||
R.spellings.push_back(r.native);
|
||||
std::sort(R.spellings.begin(), R.spellings.end(),
|
||||
[](const std::string& a, const std::string& b) { return a.size() > b.size(); });
|
||||
R.spellings.erase(std::unique(R.spellings.begin(), R.spellings.end()), R.spellings.end());
|
||||
roots_.push_back(std::move(R));
|
||||
}
|
||||
for (const RadNameMap& m : prog.name_map)
|
||||
for (int k = 0; k < m.n_src && k < 8; ++k) {
|
||||
if (!m.src[k]) continue;
|
||||
const std::string mod = module_of(m.src[k]);
|
||||
if (mod.empty()) continue;
|
||||
for (Root& R : roots_) {
|
||||
if (mod.compare(0, R.native.size(), R.native) != 0) continue;
|
||||
if (!adaptable_.count(mod) && !known_.count(mod))
|
||||
known_[mod] = "the base reads it with an op no adapter path follows (a fused "
|
||||
"activation, a rotated input, or not a GEMM)";
|
||||
const std::string u = underscored(mod.substr(R.native.size()));
|
||||
auto it = R.kohya.find(u);
|
||||
if (it == R.kohya.end()) R.kohya[u] = mod;
|
||||
else if (it->second != mod) it->second.clear(); /* ambiguous */
|
||||
}
|
||||
}
|
||||
for (const LoraAlias& a : prog.lora_aliases) {
|
||||
for (size_t ri = 0; ri < roots_.size(); ++ri) {
|
||||
if (roots_[ri].native != a.root) continue;
|
||||
Alias x;
|
||||
x.root = ri;
|
||||
x.from = a.from; x.to = a.to;
|
||||
x.from_lo = a.from_lo; x.from_hi = a.from_hi; x.to_lo = a.to_lo;
|
||||
x.dotted = pattern(a.from, false);
|
||||
x.kohya = pattern(a.from, true);
|
||||
aliases_.push_back(std::move(x));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
int64_t KeyMap::rows(const std::string& module) const {
|
||||
auto it = adaptable_.find(module);
|
||||
return it == adaptable_.end() ? -1 : it->second.first;
|
||||
}
|
||||
const std::vector<KeyMap::Piece>& KeyMap::pieces(const std::string& module) const {
|
||||
static const std::vector<Piece> none;
|
||||
auto it = pieces_.find(module);
|
||||
return it == pieces_.end() ? none : it->second;
|
||||
}
|
||||
int64_t KeyMap::cols(const std::string& module) const {
|
||||
auto it = adaptable_.find(module);
|
||||
return it == adaptable_.end() ? -1 : it->second.second;
|
||||
}
|
||||
|
||||
bool KeyMap::lookup(const Root& r, const std::string& rel, bool kohya, std::vector<Target>* out,
|
||||
std::string* why) const {
|
||||
auto take = [&](const std::string& mod, int64_t lo, int64_t hi, int64_t to) {
|
||||
if (adaptable_.count(mod)) {
|
||||
Target t;
|
||||
t.module = mod; t.from_lo = lo; t.from_hi = hi; t.to_lo = to;
|
||||
out->push_back(t);
|
||||
return true;
|
||||
}
|
||||
auto k = known_.find(mod);
|
||||
if (k != known_.end() && why) *why = mod + ": " + k->second;
|
||||
return false;
|
||||
};
|
||||
if (kohya) {
|
||||
auto it = r.kohya.find(rel);
|
||||
if (it != r.kohya.end()) {
|
||||
if (it->second.empty()) { if (why) *why = "its kohya name matches two modules of the base"; }
|
||||
else if (take(it->second, 0, 0, 0)) return true;
|
||||
}
|
||||
} else if (take(r.native + rel, 0, 0, 0)) {
|
||||
return true;
|
||||
}
|
||||
const size_t ri = (size_t)(&r - roots_.data());
|
||||
for (const Alias& a : aliases_) {
|
||||
if (a.root != ri) continue;
|
||||
std::smatch m;
|
||||
if (!std::regex_match(rel, m, kohya ? a.kohya : a.dotted)) continue;
|
||||
std::string to;
|
||||
size_t g = 1;
|
||||
for (char c : a.to) {
|
||||
if (c == '#' && g < m.size()) to += m[g++].str();
|
||||
else to += c;
|
||||
}
|
||||
take(r.native + to, a.from_lo, a.from_hi, a.to_lo);
|
||||
}
|
||||
return !out->empty();
|
||||
}
|
||||
|
||||
std::vector<Target> KeyMap::resolve(const std::string& key, std::string* why) const {
|
||||
struct Cand { size_t root; size_t len; bool kohya; };
|
||||
std::vector<Cand> cs;
|
||||
for (size_t ri = 0; ri < roots_.size(); ++ri)
|
||||
for (const std::string& sp : roots_[ri].spellings)
|
||||
if (key.compare(0, sp.size(), sp) == 0)
|
||||
cs.push_back({ ri, sp.size(), !sp.empty() && sp.back() == '_' });
|
||||
std::stable_sort(cs.begin(), cs.end(), [](const Cand& a, const Cand& b) { return a.len > b.len; });
|
||||
std::vector<Target> out;
|
||||
std::string first_why;
|
||||
for (const Cand& c : cs) {
|
||||
std::string w;
|
||||
if (lookup(roots_[c.root], key.substr(c.len), c.kohya, &out, &w)) return out;
|
||||
if (first_why.empty()) first_why = w;
|
||||
}
|
||||
if (why) *why = !first_why.empty() ? first_why
|
||||
: cs.empty() ? std::string("its prefix names no network of this model")
|
||||
: std::string("no module of this model is named so");
|
||||
return out;
|
||||
}
|
||||
|
||||
/* ================================================================== composition */
|
||||
namespace {
|
||||
|
||||
struct Part {
|
||||
std::shared_ptr<Delta> d;
|
||||
int64_t from_lo = 0, n = 0, to_lo = 0;
|
||||
};
|
||||
|
||||
} /* namespace */
|
||||
|
||||
int compose(const KeyMap& km, const std::vector<Strength>& ads, int max_rank,
|
||||
std::map<std::string, Composite>* out, ComposeReport* rep, std::string* err) {
|
||||
out->clear();
|
||||
*rep = ComposeReport{};
|
||||
std::map<std::string, std::vector<Part>> by;
|
||||
for (const Strength& s : ads) {
|
||||
if (!s.file) return fail(err, RAD_E_INVAL, "adapter '" + s.name + "' is not open");
|
||||
for (const auto& [t, why] : s.file->skipped()) rep->skipped.push_back(s.name + ": " + t + ": " + why);
|
||||
if (s.weight == 0.0) continue;
|
||||
for (const FileModule& fm : s.file->modules()) {
|
||||
std::string why;
|
||||
const std::vector<Target> ts = km.resolve(fm.key, &why);
|
||||
if (ts.empty()) { rep->unplaced.push_back(s.name + ": " + fm.key + ": " + why); continue; }
|
||||
auto d = std::make_shared<Delta>();
|
||||
std::string e;
|
||||
if (module_delta(fm, s.weight, d.get(), &e) < 0)
|
||||
return fail(err, RAD_E_FORMAT, s.name + ": " + e);
|
||||
for (const Target& t : ts) {
|
||||
Part p;
|
||||
p.d = d;
|
||||
p.from_lo = t.from_lo;
|
||||
p.n = (t.from_hi > 0 ? t.from_hi : d->N) - t.from_lo;
|
||||
p.to_lo = t.to_lo;
|
||||
if (p.n <= 0 || t.from_lo + p.n > d->N)
|
||||
return fail(err, RAD_E_SHAPE, fmt("%s: %s has %lld output rows; the base's alias "
|
||||
"takes rows [%lld, %lld) of it for %s",
|
||||
s.name.c_str(), fm.key.c_str(), (long long)d->N,
|
||||
(long long)t.from_lo, (long long)(t.from_lo + p.n),
|
||||
t.module.c_str()));
|
||||
by[t.module].push_back(p);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
std::vector<std::string> names;
|
||||
for (auto& [k, v] : by) { names.push_back(k); (*out)[k]; }
|
||||
std::vector<std::string> errs(names.size());
|
||||
std::vector<double> kept(names.size(), 1.0);
|
||||
std::vector<char> exact(names.size(), 1);
|
||||
std::atomic<size_t> next{ 0 };
|
||||
auto work = [&]() {
|
||||
for (size_t i; (i = next.fetch_add(1)) < names.size();) {
|
||||
const std::string& mod = names[i];
|
||||
const std::vector<Part>& ps = by.find(mod)->second;
|
||||
Composite& c = out->find(mod)->second;
|
||||
int64_t rows = km.rows(mod), K = km.cols(mod);
|
||||
int64_t extent = 0;
|
||||
for (const Part& p : ps) extent = std::max(extent, p.to_lo + p.n);
|
||||
for (const KeyMap::Piece& pc : km.pieces(mod)) extent = std::max(extent, pc.lo + pc.n);
|
||||
if (rows < 0) rows = extent;
|
||||
if (K < 0) K = ps[0].d->K;
|
||||
bool lr = true;
|
||||
int64_t R = 0, bound = 0;
|
||||
for (const Part& p : ps) {
|
||||
if (p.d->K != K) {
|
||||
errs[i] = fmt("%s: an adapter's delta has %lld input columns, the base's module "
|
||||
"%lld", mod.c_str(), (long long)p.d->K, (long long)K);
|
||||
break;
|
||||
}
|
||||
if (p.to_lo + p.n > rows) {
|
||||
errs[i] = fmt("%s: an adapter's delta reaches row %lld of a module of %lld rows",
|
||||
mod.c_str(), (long long)(p.to_lo + p.n), (long long)rows);
|
||||
break;
|
||||
}
|
||||
lr = lr && p.d->low_rank;
|
||||
R += p.d->low_rank ? p.d->r : 0;
|
||||
bound += p.d->rank_bound;
|
||||
}
|
||||
if (!errs[i].empty()) continue;
|
||||
c.rows = rows; c.K = K;
|
||||
if (lr && R <= max_rank) {
|
||||
/* Side by side: every delta its own block of ranks. */
|
||||
c.r = R;
|
||||
c.B.assign((size_t)(rows * R), 0.0f);
|
||||
c.A.assign((size_t)(R * K), 0.0f);
|
||||
int64_t o = 0;
|
||||
for (const Part& p : ps) {
|
||||
const Delta& d = *p.d;
|
||||
for (int64_t row = 0; row < p.n; ++row)
|
||||
std::memcpy(&c.B[(size_t)((p.to_lo + row) * R + o)],
|
||||
&d.B[(size_t)((p.from_lo + row) * d.r)], (size_t)d.r * 4);
|
||||
std::memcpy(&c.A[(size_t)(o * K)], d.A.data(), (size_t)(d.r * K) * 4);
|
||||
o += d.r;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
/* The sum, as one operator over the module's rows, truncated to the slot's rank. */
|
||||
exact[i] = 0;
|
||||
Delta sum;
|
||||
sum.N = rows; sum.K = K; sum.rank_bound = bound;
|
||||
/* One whole delta's energy is known; a sum's or a row slice's is what the sketch
|
||||
* holds, exact when its rank is within the sketch's. */
|
||||
sum.energy = ps.size() == 1 && ps[0].from_lo == 0 && ps[0].n == ps[0].d->N
|
||||
? ps[0].d->energy : -1.0;
|
||||
sum.apply = [&ps, rows](const float* X, int64_t l, float* Y) {
|
||||
std::fill(Y, Y + rows * l, 0.0f);
|
||||
for (const Part& p : ps) {
|
||||
const Delta& d = *p.d;
|
||||
std::vector<float> y((size_t)(d.N * l));
|
||||
if (d.low_rank) {
|
||||
std::vector<float> t((size_t)(d.r * l));
|
||||
mm(d.A.data(), X, t.data(), d.r, d.K, l);
|
||||
mm(d.B.data(), t.data(), y.data(), d.N, d.r, l);
|
||||
} else {
|
||||
d.apply(X, l, y.data());
|
||||
}
|
||||
for (int64_t row = 0; row < p.n; ++row)
|
||||
for (int64_t j = 0; j < l; ++j)
|
||||
Y[(p.to_lo + row) * l + j] += y[(size_t)((p.from_lo + row) * l + j)];
|
||||
}
|
||||
};
|
||||
sum.apply_t = [&ps, K](const float* Yin, int64_t l, float* X) {
|
||||
std::fill(X, X + K * l, 0.0f);
|
||||
std::vector<float> x((size_t)(K * l));
|
||||
for (const Part& p : ps) {
|
||||
const Delta& d = *p.d;
|
||||
std::vector<float> y((size_t)(d.N * l), 0.0f);
|
||||
for (int64_t row = 0; row < p.n; ++row)
|
||||
for (int64_t j = 0; j < l; ++j)
|
||||
y[(size_t)((p.from_lo + row) * l + j)] = Yin[(p.to_lo + row) * l + j];
|
||||
if (d.low_rank) {
|
||||
std::vector<float> t((size_t)(d.r * l));
|
||||
mm_tn(d.B.data(), y.data(), t.data(), d.r, d.N, l);
|
||||
mm_tn(d.A.data(), t.data(), x.data(), d.K, d.r, l);
|
||||
} else {
|
||||
d.apply_t(y.data(), l, x.data());
|
||||
}
|
||||
for (int64_t k = 0; k < K * l; ++k) X[k] += x[(size_t)k];
|
||||
}
|
||||
};
|
||||
truncate(sum, max_rank, &c.B, &c.A, &kept[i]);
|
||||
c.r = (int64_t)(c.A.size() / (size_t)(K > 0 ? K : 1));
|
||||
/* Kept energy is exact when the sum is low-rank: ||B A||^2 of the parts side by side. */
|
||||
if (lr) {
|
||||
std::vector<float> Bc((size_t)(rows * R), 0.0f), Ac((size_t)(R * K), 0.0f);
|
||||
int64_t o = 0;
|
||||
for (const Part& p : ps) {
|
||||
const Delta& d = *p.d;
|
||||
for (int64_t row = 0; row < p.n; ++row)
|
||||
std::memcpy(&Bc[(size_t)((p.to_lo + row) * R + o)],
|
||||
&d.B[(size_t)((p.from_lo + row) * d.r)], (size_t)d.r * 4);
|
||||
std::memcpy(&Ac[(size_t)(o * K)], d.A.data(), (size_t)(d.r * K) * 4);
|
||||
o += d.r;
|
||||
}
|
||||
const double tot = lowrank_energy(Bc, Ac, rows, R, K);
|
||||
const double got = lowrank_energy(c.B, c.A, rows, c.r, K);
|
||||
kept[i] = tot > 0.0 ? std::min(1.0, got / tot) : 1.0;
|
||||
}
|
||||
}
|
||||
};
|
||||
const unsigned hw = std::max(1u, std::min(16u, std::thread::hardware_concurrency()));
|
||||
std::vector<std::thread> th;
|
||||
for (unsigned t = 1; t < hw && t < names.size(); ++t) th.emplace_back(work);
|
||||
work();
|
||||
for (std::thread& t : th) t.join();
|
||||
for (size_t i = 0; i < names.size(); ++i) {
|
||||
if (!errs[i].empty()) return fail(err, RAD_E_SHAPE, errs[i]);
|
||||
++rep->modules;
|
||||
/* Held exactly: side by side, or an operator whose rank fits (LoKr, LoHa within R). */
|
||||
if (exact[i] || kept[i] >= 0.9999) ++rep->exact;
|
||||
else if (kept[i] < rep->worst_kept) { rep->worst_kept = kept[i]; rep->worst_module = names[i]; }
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
std::map<std::string, AdModule> as_modules(std::map<std::string, Composite>& c, const KeyMap& km) {
|
||||
std::map<std::string, AdModule> m;
|
||||
for (auto& [name, x] : c) {
|
||||
if (x.r <= 0) continue;
|
||||
const std::vector<KeyMap::Piece>& pcs = km.pieces(name);
|
||||
x.tPieces.assign(pcs.size(), StTensor{});
|
||||
x.tA = StTensor{};
|
||||
x.tA.name = name + ".A";
|
||||
x.tA.dtype = RAD_F32;
|
||||
x.tA.dtype_str = "F32";
|
||||
x.tA.shape = { x.r, x.K };
|
||||
x.tA.bytes = x.A.size() * 4;
|
||||
x.tA.data = (const uint8_t*)x.A.data();
|
||||
x.tB = StTensor{};
|
||||
x.tB.name = name + ".B";
|
||||
x.tB.dtype = RAD_F32;
|
||||
x.tB.dtype_str = "F32";
|
||||
x.tB.shape = { x.rows, x.r };
|
||||
x.tB.bytes = x.B.size() * 4;
|
||||
x.tB.data = (const uint8_t*)x.B.data();
|
||||
AdModule a;
|
||||
a.name = name;
|
||||
a.A = &x.tA;
|
||||
a.B = &x.tB;
|
||||
a.rank = x.r;
|
||||
a.alpha = (double)x.r;
|
||||
a.scale = 1.0f;
|
||||
if (pcs.empty() || km.whole(name)) m[name] = a;
|
||||
for (size_t i = 0; i < pcs.size(); ++i) {
|
||||
StTensor& t = x.tPieces[i];
|
||||
t = x.tB;
|
||||
t.name = pcs[i].name + ".B";
|
||||
t.shape = { pcs[i].n, x.r };
|
||||
t.bytes = (uint64_t)(pcs[i].n * x.r) * 4;
|
||||
t.data = (const uint8_t*)(x.B.data() + pcs[i].lo * x.r);
|
||||
AdModule p = a;
|
||||
p.name = pcs[i].name;
|
||||
p.B = &t;
|
||||
m[p.name] = p;
|
||||
}
|
||||
}
|
||||
return m;
|
||||
}
|
||||
|
||||
} /* namespace lora */
|
||||
} /* namespace rad */
|
||||
@@ -0,0 +1,183 @@
|
||||
/* lora/adapter.h -- adapter files as image and video generators receive them, and the bytes of a
|
||||
* slot holding one or several of them at chosen strengths.
|
||||
*
|
||||
* An adapter for a generator is one safetensors file, written by whichever tool trained or
|
||||
* converted it, so the same delta arrives under several spellings:
|
||||
*
|
||||
* LoRA `<m>.lora_down.weight` / `<m>.lora_up.weight` (+ `<m>.alpha`): kohya, ComfyUI;
|
||||
* `<m>.lora_A[.default].weight` / `<m>.lora_B[...]` (+ `.alpha`): PEFT, diffusers, ai-toolkit;
|
||||
* `<m>.lora.down.weight` / `<m>.lora.up.weight`; `<m>.lora_linear_layer.down/up.weight`.
|
||||
* delta = alpha / rank * up @ down; no alpha is a scale of 1. A convolution's down is
|
||||
* [rank, cin, kh, kw] and its up [cout, rank, 1, 1], read as the flattened matrices.
|
||||
* LoHa `<m>.hada_w1_a/_w1_b/_w2_a/_w2_b` (+ alpha): delta = alpha / rank1 *
|
||||
* (w1_a @ w1_b) * (w2_a @ w2_b), elementwise; exactly a rank1 * rank2 product of
|
||||
* row-wise Kronecker factors.
|
||||
* LoKr `<m>.lokr_w1` or `_w1_a`/`_w1_b`, `<m>.lokr_w2` or `_w2_a`/`_w2_b` (+ alpha):
|
||||
* delta = scale * kron(w1, w2), scale alpha / rank of a decomposed factor, else 1.
|
||||
* full `<m>.diff`: the delta itself.
|
||||
*
|
||||
* Every module becomes a Delta, a linear map with its strength folded in. A slot holds, for each
|
||||
* checkpoint module the adapters reach, the sum of the deltas that land there: the low-rank ones
|
||||
* side by side while their ranks fit the slot's rank (exact), otherwise the sum's best rank-R
|
||||
* approximation (a randomized SVD; the fraction of the delta's energy it keeps is reported).
|
||||
*
|
||||
* Where a module lands is the generator's own declaration (rad_lora_root, rad_lora_alias): a
|
||||
* key's prefix names the network, its path the checkpoint module directly or through an alias,
|
||||
* kohya's underscore form matched against the same names. */
|
||||
#pragma once
|
||||
#include "lora.h"
|
||||
#include "../format/safetensors.h"
|
||||
|
||||
#include <functional>
|
||||
#include <map>
|
||||
#include <memory>
|
||||
#include <regex>
|
||||
#include <set>
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
#include <vector>
|
||||
|
||||
namespace rad {
|
||||
namespace lora {
|
||||
|
||||
/* One module of an adapter file, before it is mapped onto the base. */
|
||||
struct FileModule {
|
||||
enum Kind { LORA, LOHA, LOKR, FULL };
|
||||
std::string key; /* the module as the file spells it, tensor suffix removed */
|
||||
Kind kind = LORA;
|
||||
/* LORA: down, up. LOHA: w1_a, w1_b, w2_a, w2_b. LOKR: w1, w1_a, w1_b, w2, w2_a, w2_b.
|
||||
* FULL: diff. */
|
||||
const StTensor* t[6] = {};
|
||||
const StTensor* alpha = nullptr;
|
||||
};
|
||||
|
||||
class AdapterFile {
|
||||
public:
|
||||
/* Opens and groups the file's tensors by module. Refuses a file holding a form whose effect
|
||||
* this engine cannot reproduce (DoRA's magnitude, OFT, Tucker cores), naming it. */
|
||||
int open(const std::string& path, std::string* err);
|
||||
const std::string& path() const { return st_.path(); }
|
||||
const std::vector<FileModule>& modules() const { return mods_; }
|
||||
/* Tensors that change no linear (a trained bias, a norm's weight), with why; reported, not
|
||||
* applied. */
|
||||
const std::vector<std::pair<std::string, std::string>>& skipped() const { return skipped_; }
|
||||
/* The most common kind among the modules, for messages ("LoRA", "LoHa", ...). */
|
||||
const char* kind_name() const;
|
||||
|
||||
private:
|
||||
SafeTensorsFile st_;
|
||||
std::vector<FileModule> mods_;
|
||||
std::vector<std::pair<std::string, std::string>> skipped_;
|
||||
};
|
||||
|
||||
/* A module's delta as a linear map [N, K] with its scale and strength folded in. Low-rank forms
|
||||
* keep their factors (B [N, r] and A [r, K], row-major); the rest are applied as operators to
|
||||
* blocks of `l` column vectors (X [K, l] -> Y [N, l], and the transpose), all f32. */
|
||||
struct Delta {
|
||||
int64_t N = 0, K = 0;
|
||||
int64_t rank_bound = 0;
|
||||
double energy = -1.0; /* ||delta||_F^2, -1 when not known */
|
||||
bool low_rank = false;
|
||||
int64_t r = 0;
|
||||
std::vector<float> B, A;
|
||||
std::function<void(const float* X, int64_t l, float* Y)> apply, apply_t;
|
||||
};
|
||||
|
||||
/* The delta of one module at strength `w`. RAD_E_SHAPE / RAD_E_DTYPE / RAD_E_FORMAT name the
|
||||
* tensor. */
|
||||
int module_delta(const FileModule& m, double w, Delta* out, std::string* err);
|
||||
|
||||
/* Rank-`r` factors of a delta given as an operator (randomized range finder, two power
|
||||
* iterations): B [N, r], A [r, K]. `kept` is the fraction of the squared Frobenius norm kept, of
|
||||
* Delta::energy when known and of what the sketch holds otherwise (1 when the delta's rank is at
|
||||
* most r). */
|
||||
void truncate(const Delta& d, int64_t r, std::vector<float>* B, std::vector<float>* A,
|
||||
double* kept);
|
||||
|
||||
/* Where an adapter module lands in the base: rows [from_lo, from_hi) of its output (from_hi 0 =
|
||||
* all) at rows from `to_lo` of the checkpoint module `module`. */
|
||||
struct Target {
|
||||
std::string module;
|
||||
int64_t from_lo = 0, from_hi = 0, to_lo = 0;
|
||||
};
|
||||
|
||||
/* The generator's key names over one rank's Program and sites. */
|
||||
class KeyMap {
|
||||
public:
|
||||
KeyMap(const Program& prog, const std::vector<Site>& sites);
|
||||
/* The targets of a file's module key; empty with `why` when it lands nowhere adaptable. */
|
||||
std::vector<Target> resolve(const std::string& key, std::string* why) const;
|
||||
/* A checkpoint module's full rows and columns as the sites record them, or -1 when the
|
||||
* declaration leaves them open. */
|
||||
int64_t rows(const std::string& module) const;
|
||||
int64_t cols(const std::string& module) const;
|
||||
/* The row pieces a module is cut into (RAD_MAP_ROWS; core/lora/lora.cpp names each
|
||||
* `<module>@<first row>+<rows>`), empty for a module the sites read whole; and whether a site
|
||||
* also reads it whole. */
|
||||
struct Piece { std::string name; int64_t lo = 0, n = 0; };
|
||||
const std::vector<Piece>& pieces(const std::string& module) const;
|
||||
bool whole(const std::string& module) const { return whole_.count(module) != 0; }
|
||||
|
||||
private:
|
||||
struct Root {
|
||||
std::string native;
|
||||
std::vector<std::string> spellings;
|
||||
std::unordered_map<std::string, std::string> kohya; /* underscored rel -> module */
|
||||
};
|
||||
struct Alias {
|
||||
size_t root;
|
||||
std::string from, to;
|
||||
int64_t from_lo, from_hi, to_lo;
|
||||
std::regex dotted, kohya;
|
||||
};
|
||||
bool lookup(const Root& r, const std::string& rel, bool kohya, std::vector<Target>* out,
|
||||
std::string* why) const;
|
||||
|
||||
const Program* prog_;
|
||||
std::vector<Root> roots_;
|
||||
std::vector<Alias> aliases_;
|
||||
std::unordered_map<std::string, std::pair<int64_t, int64_t>> adaptable_; /* -> rows, cols */
|
||||
std::unordered_map<std::string, std::string> known_; /* module -> why not adaptable */
|
||||
std::unordered_map<std::string, std::vector<Piece>> pieces_;
|
||||
std::set<std::string> whole_;
|
||||
};
|
||||
|
||||
/* One adapter at a strength, for compose(). */
|
||||
struct Strength {
|
||||
std::string name;
|
||||
std::shared_ptr<const AdapterFile> file;
|
||||
double weight = 1.0;
|
||||
};
|
||||
|
||||
/* What compose() did, for the log and the client. */
|
||||
struct ComposeReport {
|
||||
int64_t modules = 0; /* checkpoint modules the slot carries */
|
||||
int64_t exact = 0; /* ... held exactly */
|
||||
double worst_kept = 1.0; /* lowest kept energy among the truncated */
|
||||
std::string worst_module;
|
||||
std::vector<std::string> unplaced; /* "<adapter>: <key>: why" */
|
||||
std::vector<std::string> skipped; /* "<adapter>: <tensor>: why" */
|
||||
};
|
||||
|
||||
/* The factors of a composite, per checkpoint module: B [rows, r] and A [r, K], f32, held by the
|
||||
* caller while the packer reads them. */
|
||||
struct Composite {
|
||||
int64_t rows = 0, K = 0, r = 0;
|
||||
std::vector<float> B, A;
|
||||
StTensor tA, tB;
|
||||
std::vector<StTensor> tPieces; /* B's row ranges, one per piece of the module */
|
||||
};
|
||||
|
||||
/* The sum of the adapters' deltas per checkpoint module, at most `max_rank` each. Unplaced
|
||||
* modules are reported, not refused, as UIs do. RAD_E_SHAPE when a module's shape disagrees with
|
||||
* the base's. */
|
||||
int compose(const KeyMap& km, const std::vector<Strength>& ads, int max_rank,
|
||||
std::map<std::string, Composite>* out, ComposeReport* rep, std::string* err);
|
||||
|
||||
/* The packer's view of a composite (scale 1: the strengths and alphas are folded into B): a
|
||||
* module under its own name where a site reads it whole, and each of its row pieces under the
|
||||
* piece's name. */
|
||||
std::map<std::string, AdModule> as_modules(std::map<std::string, Composite>& c, const KeyMap& km);
|
||||
|
||||
} /* namespace lora */
|
||||
} /* namespace rad */
|
||||
+26
-11
@@ -1,9 +1,14 @@
|
||||
/* lora/config.h -- what runtime LoRA was started with (--lora, --max-loras, --max-lora-rank,
|
||||
* --lora-target-modules). Read by declare (which sites and pools exist), by the adapter manager
|
||||
* (what may be loaded into them) and by nothing else.
|
||||
/* lora/config.h -- what runtime LoRA was started with (--lora, --lora-dir, --max-loras,
|
||||
* --max-lora-rank, --lora-target-modules). Read by declare (which sites and pools exist), by the
|
||||
* adapter manager (what may be loaded into them) and by nothing else.
|
||||
*
|
||||
* Off unless asked for: with no adapter named and no --max-loras, `enabled()` is false, declare
|
||||
* appends nothing, the program has no pool and no extra op, and no step carries an adapter slot. */
|
||||
* Off unless asked for: with no adapter named, no --lora-dir and no --max-loras, `enabled()` is
|
||||
* false, declare appends nothing, the program has no pool and no extra op, and no step carries an
|
||||
* adapter slot.
|
||||
*
|
||||
* A text model's slot holds one adapter; a generator's holds the combination one request asks for
|
||||
* (several adapter files at their strengths, core/lora/adapter.h), so its slots are not tied to
|
||||
* the number of adapters named. */
|
||||
#pragma once
|
||||
#include <string>
|
||||
#include <utility>
|
||||
@@ -12,20 +17,30 @@
|
||||
namespace rad {
|
||||
|
||||
struct LoraConfig {
|
||||
/* NAME=PATH pairs to load at startup, in the order given. */
|
||||
/* NAME=PATH pairs to load at startup, in the order given: a PEFT directory, or for a
|
||||
* generator one .safetensors file. */
|
||||
std::vector<std::pair<std::string, std::string>> adapters;
|
||||
/* Adapter slots resident at once. 0 with adapters named means "as many as were named". */
|
||||
/* A generator's adapter directory: a request may name any NAME.safetensors under it. */
|
||||
std::string dir;
|
||||
/* Adapter slots resident at once. 0: as many as were named, and two with --lora-dir alone. */
|
||||
int max_loras = 0;
|
||||
/* The rank every slot is sized for; an adapter of lower rank is zero-padded into it. */
|
||||
int max_rank = 16;
|
||||
/* The rank every slot is sized for; an adapter of lower rank is zero-padded into it. 0: the
|
||||
* default, kDefaultRank for a text model and kDefaultGenRank for a generator, whose adapter
|
||||
* files run to rank 32 and are stacked. */
|
||||
int max_rank = 0;
|
||||
static constexpr int kDefaultRank = 16, kDefaultGenRank = 64;
|
||||
int rank(bool generator) const {
|
||||
return max_rank > 0 ? max_rank : generator ? kDefaultGenRank : kDefaultRank;
|
||||
}
|
||||
/* HF module leaf names (q_proj, gate_proj, in_proj_qkv, ...) the sites are built for, sorted
|
||||
* and unique. Empty: the union of the startup adapters' target_modules. */
|
||||
std::vector<std::string> targets;
|
||||
|
||||
bool enabled() const { return max_loras > 0 || !adapters.empty(); }
|
||||
bool enabled() const { return max_loras > 0 || !adapters.empty() || !dir.empty(); }
|
||||
int slots() const {
|
||||
const int named = (int)adapters.size();
|
||||
return max_loras > 0 ? (max_loras > named ? max_loras : named) : named;
|
||||
if (max_loras > 0) return max_loras;
|
||||
return named > 0 ? named : (dir.empty() ? 0 : 2);
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
+99
-12
@@ -3,6 +3,7 @@
|
||||
#include "build/rad_build.h"
|
||||
#include "rad_internal.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstring>
|
||||
#include <map>
|
||||
#include <string>
|
||||
@@ -73,23 +74,36 @@ rad_buf decl_persist(Builder& b, const std::string& name, uint32_t dtype, uint32
|
||||
|
||||
} /* namespace */
|
||||
|
||||
/* A generator pass's adapter ops run over at most this many rows at a time: large enough that the
|
||||
* kernels' row tiles are all busy, small enough that `t` for the largest rank is a few MiB. */
|
||||
constexpr int64_t kGenChunk = 8192;
|
||||
|
||||
int lora_declare(Builder& b, const LoraDeclare& d) {
|
||||
if (!d.cfg || !d.cfg->enabled()) return RAD_OK;
|
||||
Program& P = b.program();
|
||||
/* Adapters are chosen per request and applied on the token steps of a model that writes
|
||||
* logits; a generator's passes and an embedding model's requests carry no adapter. */
|
||||
if (P.is_pass_driven() || P.pooled_buf != RAD_NULL_HANDLE ||
|
||||
P.logits_buf == RAD_NULL_HANDLE) {
|
||||
RAD_ERR("lora: runtime LoRA adapters serve a model that generates text, and this one %s",
|
||||
P.is_pass_driven() ? "is an image, audio or video generator"
|
||||
* logits, or on every pass of a generator that names its adapter keys (rad_lora_root); an
|
||||
* embedding model's requests carry no adapter. */
|
||||
const bool gen = P.is_pass_driven();
|
||||
if (gen ? P.lora_roots.empty()
|
||||
: (P.pooled_buf != RAD_NULL_HANDLE || P.logits_buf == RAD_NULL_HANDLE)) {
|
||||
RAD_ERR("lora: runtime LoRA adapters serve a model that generates text, or a generator "
|
||||
"that declares how adapter files name its modules, and this one %s",
|
||||
gen ? "is a generator that declares no adapter "
|
||||
"key names (rad_lora_root)"
|
||||
: P.pooled_buf != RAD_NULL_HANDLE ? "makes embeddings"
|
||||
: "declares no logits");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
if (!gen && d.targets.count("*")) {
|
||||
RAD_ERR("lora: an adapter without adapter_config.json names no target modules, and a "
|
||||
"text model has no default set; give them with --lora-target-modules");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
const int S = d.cfg->slots();
|
||||
const int max_rank = d.cfg->max_rank;
|
||||
const int max_rank = d.cfg->rank(gen);
|
||||
const int64_t max_tok = P.ctx.max_tok;
|
||||
if (S <= 0 || max_rank <= 0 || max_tok <= 0) {
|
||||
if (S <= 0 || max_rank <= 0 || (!gen && max_tok <= 0)) {
|
||||
RAD_ERR("lora: %d slots of rank %d over steps of %lld tokens is not a configuration", S,
|
||||
max_rank, (long long)max_tok);
|
||||
return RAD_E_INVAL;
|
||||
@@ -150,6 +164,26 @@ int lora_declare(Builder& b, const LoraDeclare& d) {
|
||||
}
|
||||
}
|
||||
|
||||
/* ---- a token step's rows are its tokens; a generator pass's are each GEMM's own, issued in
|
||||
* chunks of at most kGenChunk rows (Ctx::issue_lora), so `t` holds one chunk. */
|
||||
int64_t rows = max_tok;
|
||||
if (gen) {
|
||||
rows = 0;
|
||||
for (const lora::Site& x : sites)
|
||||
if (x.gemm > 0 && x.gemm < P.ops.size()) rows = std::max(rows, P.ops[x.gemm].range_hi);
|
||||
rows = std::min<int64_t>(rows, kGenChunk);
|
||||
}
|
||||
|
||||
/* On the real declare, what the adapters cost: the pools are persistent buffers, so the
|
||||
* arena plan (and with it what is left for weights and the KV cache) holds them. */
|
||||
if (d.sites_out) {
|
||||
int64_t slot_bytes = 0;
|
||||
for (const LoraPool& p : P.lora_pools) slot_bytes += 2 * p.R * p.K + 2 * p.N * p.R + 4 * p.N;
|
||||
RAD_INFO("lora: %zu weights carry adapters, %d slots of rank %d, %s a slot on this rank, "
|
||||
"%s in all (--max-loras, --max-lora-rank)", P.lora_pools.size(), S, max_rank,
|
||||
humanb(slot_bytes).c_str(), humanb(slot_bytes * S).c_str());
|
||||
}
|
||||
|
||||
/* ---- t = A.x, one f32 plane per capacity R and lane. Persistent, not transient: the ops that
|
||||
* use it run at the GEMM's position, but the buffer plan would place a transient at the
|
||||
* appended ops' own position, the end of the program, and share its bytes with buffers live
|
||||
@@ -160,7 +194,7 @@ int lora_declare(Builder& b, const LoraDeclare& d) {
|
||||
if (t_by_r.count(x.R)) continue;
|
||||
LoraScratch sc;
|
||||
sc.R = x.R;
|
||||
const int64_t sh[2] = { max_tok, x.R };
|
||||
const int64_t sh[2] = { rows, x.R };
|
||||
for (int l = 0; l < 2; ++l) {
|
||||
sc.lane[l] = decl_persist(b, fmt("lora.t.r%lld.lane%d", (long long)x.R, l), RAD_F32, 2, sh);
|
||||
if (!sc.lane[l]) return RAD_E_STATE;
|
||||
@@ -169,9 +203,21 @@ int lora_declare(Builder& b, const LoraDeclare& d) {
|
||||
P.lora_t.push_back(sc);
|
||||
}
|
||||
|
||||
/* ---- a generator pass's slot operand: elements [s rows, (s + 1) rows) of an [S rows] i32
|
||||
* buffer, every one s (filled when the engine starts adapters) */
|
||||
P.lora_rows = 0;
|
||||
P.lora_rows_n = 0;
|
||||
if (gen && rows > 0) {
|
||||
const int64_t sh[1] = { S * rows };
|
||||
P.lora_rows = decl_persist(b, "lora.slot_rows", RAD_I32, 1, sh);
|
||||
if (!P.lora_rows) return RAD_E_STATE;
|
||||
P.lora_rows_n = rows;
|
||||
}
|
||||
|
||||
/* ---- the two ops behind each targeted GEMM */
|
||||
P.lora_sites.clear();
|
||||
int n_refused = 0;
|
||||
std::vector<char> dropped(sites.size(), 0);
|
||||
for (lora::Site& x : sites) {
|
||||
const uint32_t gh = x.gemm;
|
||||
if (gh == 0 || gh >= P.ops.size()) return RAD_E_STATE;
|
||||
@@ -186,7 +232,15 @@ int lora_declare(Builder& b, const LoraDeclare& d) {
|
||||
const int oa = opd_index(g, "a"), oas = opd_index(g, "a_scale"), oy = opd_index(g, "y");
|
||||
const std::vector<rad_buf> reads = b.op_read_set(gh), writes = b.op_write_set(gh);
|
||||
|
||||
/* A text model's targeted GEMM that cannot carry the ops is refused; a generator's, whose
|
||||
* every plain GEMM is a candidate, stays the base and its modules are reported unplaced. */
|
||||
auto refuse = [&](const std::string& why) {
|
||||
if (gen) {
|
||||
RAD_WARN("lora: op %u '%s' over '%s' carries no adapter: %s", gh, gop.c_str(),
|
||||
x.weight.c_str(), why.c_str());
|
||||
dropped[(size_t)(&x - sites.data())] = 1;
|
||||
return;
|
||||
}
|
||||
RAD_ERR("lora: op %u '%s' over '%s': %s", gh, gop.c_str(), x.weight.c_str(), why.c_str());
|
||||
++n_refused;
|
||||
};
|
||||
@@ -223,9 +277,14 @@ int lora_declare(Builder& b, const LoraDeclare& d) {
|
||||
sp[n_sp++] = RAD_STR("dtype", rad_dtype_name(a_dt));
|
||||
const rad_op hs = b.decl_op("lora_shrink", sp, n_sp, nullptr, 0);
|
||||
|
||||
const RadParam ep[5] = { RAD_RANGE("M", lo, hi), RAD_INT("N", x.N_r), RAD_INT("R", x.R),
|
||||
RAD_INT("S", S), RAD_STR("dtype", rad_dtype_name(y_dt)) };
|
||||
const rad_op he = b.decl_op("lora_expand", ep, 5, nullptr, 0);
|
||||
RadParam ep[5] = { RAD_RANGE("M", lo, hi), RAD_INT("N", x.N_r), RAD_INT("R", x.R),
|
||||
RAD_INT("S", S), RAD_STR("dtype", rad_dtype_name(y_dt)) };
|
||||
/* A generator's passes are many rows of one adapter: its expand runs on the WMMA
|
||||
* (lora_expand_mm) where a library has it. A token step keeps the exact row, whose bytes
|
||||
* do not depend on the batch. */
|
||||
const char* expand_op = gen && b.op_declared("lora_expand_mm") ? "lora_expand_mm"
|
||||
: "lora_expand";
|
||||
const rad_op he = b.decl_op(expand_op, ep, 5, nullptr, 0);
|
||||
if (!hs || !he) {
|
||||
refuse(fmt("no kernel resolves lora_%s for an activation of %s and an output of %s",
|
||||
!hs ? "shrink" : "expand", rad_dtype_name(a_dt), rad_dtype_name(y_dt)));
|
||||
@@ -233,6 +292,28 @@ int lora_declare(Builder& b, const LoraDeclare& d) {
|
||||
}
|
||||
|
||||
LoraIssueSite is;
|
||||
/* A generator's slot packs its ranks from 0 (lora::pack_modules, compact): pairs that read
|
||||
* the first half and quarter of R, so a rank-16 adapter in a slot sized 64 a module costs
|
||||
* a quarter. Multiples of 16, the WMMA's step. */
|
||||
if (gen) {
|
||||
int64_t prev = x.R;
|
||||
for (int v = 0; v < 2; ++v) {
|
||||
const int64_t rv = ((x.R >> (v + 1)) + 15) / 16 * 16;
|
||||
if (rv < 16 || rv >= prev) break;
|
||||
RadParam vs[6];
|
||||
for (int i = 0; i < n_sp; ++i) vs[i] = sp[i];
|
||||
vs[2] = RAD_INT("R", rv);
|
||||
ep[2] = RAD_INT("R", rv);
|
||||
const rad_op vs_op = b.decl_op("lora_shrink", vs, n_sp, nullptr, 0);
|
||||
const rad_op ve_op = b.decl_op(expand_op, ep, 5, nullptr, 0);
|
||||
if (!vs_op || !ve_op) break;
|
||||
P.ops[vs_op].anchor = (int32_t)gh;
|
||||
P.ops[ve_op].anchor = (int32_t)gh;
|
||||
is.shrink_v[v] = vs_op; is.expand_v[v] = ve_op; is.R_v[v] = rv;
|
||||
is.n_v = (int8_t)(v + 1);
|
||||
prev = rv;
|
||||
}
|
||||
}
|
||||
is.gemm = gh; is.shrink = hs; is.expand = he;
|
||||
is.opd_a = (int8_t)oa;
|
||||
is.opd_a_scale = (int8_t)(coded ? oas : -1);
|
||||
@@ -248,7 +329,13 @@ int lora_declare(Builder& b, const LoraDeclare& d) {
|
||||
}
|
||||
if (n_refused) return RAD_E_UNSUPPORTED;
|
||||
|
||||
if (d.sites_out) *d.sites_out = std::move(sites);
|
||||
if (gen) P.lora_rused.assign(P.lora_pools.size() * (size_t)S, 0);
|
||||
if (d.sites_out) {
|
||||
std::vector<lora::Site> kept;
|
||||
for (size_t i = 0; i < sites.size(); ++i)
|
||||
if (!dropped[i]) kept.push_back(std::move(sites[i]));
|
||||
*d.sites_out = std::move(kept);
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
|
||||
+108
-32
@@ -88,8 +88,13 @@ bool excluded_source(const std::string& src) {
|
||||
return false;
|
||||
}
|
||||
|
||||
/* A generator that declared adapter key names (rad_lora_root): its scope is those roots, every
|
||||
* matrix under one of them, and none of the token model's rules below apply. */
|
||||
bool gen_scope(const Program& prog) { return !prog.lora_roots.empty(); }
|
||||
|
||||
const char* excluded_weight(const Program& prog, const WeightInfo& w) {
|
||||
if (w.decl.access == RAD_ACCESS_VOCAB) return "a vocabulary weight (embedding / lm_head)";
|
||||
if (gen_scope(prog)) return w.decl.rank == 2 ? nullptr : "not a matrix";
|
||||
if (w.decl.access == RAD_ACCESS_PER_REQUEST) return "an encoder tower weight (per-request access)";
|
||||
if (prog.meta.n_layers > 0 && w.decl.group.layer >= prog.meta.n_layers)
|
||||
return "a drafter / MTP layer (layer group at or above meta.n_layers)";
|
||||
@@ -121,8 +126,23 @@ void scan_maps(const Program& prog, const std::string& declared,
|
||||
struct MapIndex {
|
||||
std::unordered_map<std::string, std::vector<const RadNameMap*>> by;
|
||||
explicit MapIndex(const Program& prog) {
|
||||
for (const RadNameMap& m : prog.name_map)
|
||||
if (m.declared) by[m.declared].push_back(&m);
|
||||
/* An entry repeated whole (a plugin's encoding probe maps the weight it then declares) is
|
||||
* one entry. */
|
||||
auto same = [](const RadNameMap& a, const RadNameMap& b) {
|
||||
if (a.mode != b.mode || a.n_src != b.n_src || a.concat_dim != b.concat_dim) return false;
|
||||
for (int k = 0; k < a.n_src && k < 8; ++k)
|
||||
if (std::strcmp(a.src[k] ? a.src[k] : "", b.src[k] ? b.src[k] : "") != 0 ||
|
||||
a.src_index[k] != b.src_index[k] || a.src_rows[k] != b.src_rows[k])
|
||||
return false;
|
||||
return true;
|
||||
};
|
||||
for (const RadNameMap& m : prog.name_map) {
|
||||
if (!m.declared) continue;
|
||||
std::vector<const RadNameMap*>& v = by[m.declared];
|
||||
bool dup = false;
|
||||
for (const RadNameMap* x : v) dup = dup || same(*x, m);
|
||||
if (!dup) v.push_back(&m);
|
||||
}
|
||||
}
|
||||
const std::vector<const RadNameMap*>* find(const std::string& d) const {
|
||||
auto it = by.find(d);
|
||||
@@ -130,19 +150,27 @@ struct MapIndex {
|
||||
}
|
||||
};
|
||||
|
||||
/* Is checkpoint tensor `src` an adapter target? A token model: its leaf is in the target list and
|
||||
* it is in the trunk. A generator: it is under a declared root, and its leaf is in the list or the
|
||||
* list is "*". */
|
||||
bool source_targeted(const Program& prog, const TargetSet& targets, const std::string& src) {
|
||||
std::string leaf;
|
||||
if (module_of(src, &leaf).empty()) return false;
|
||||
if (!gen_scope(prog)) return targets.count(leaf) && !excluded_source(src);
|
||||
if (!targets.count("*") && !targets.count(leaf)) return false;
|
||||
for (const LoraRoot& r : prog.lora_roots)
|
||||
if (src.compare(0, r.native.size(), r.native) == 0) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
/* weight_targeted(), over the maps already found. */
|
||||
bool targeted_core(const Program& prog, const WeightInfo& w,
|
||||
const std::vector<const RadNameMap*>& maps, const TargetSet& targets) {
|
||||
if (targets.empty() || maps.empty()) return false;
|
||||
if (excluded_weight(prog, w)) return false;
|
||||
for (const RadNameMap* m : maps)
|
||||
for (int k = 0; k < m->n_src && k < 8; ++k) {
|
||||
if (!m->src[k]) continue;
|
||||
const std::string src = m->src[k];
|
||||
std::string leaf;
|
||||
if (module_of(src, &leaf).empty()) continue;
|
||||
if (targets.count(leaf) && !excluded_source(src)) return true;
|
||||
}
|
||||
for (int k = 0; k < m->n_src && k < 8; ++k)
|
||||
if (m->src[k] && source_targeted(prog, targets, m->src[k])) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -464,40 +492,46 @@ int make_site(const Program& prog, const MapIndex& mi, const TargetSet& targets,
|
||||
if (!maps || maps->empty())
|
||||
return fail(err, RAD_E_NOTFOUND, fmt("weight '%s' has no name-map entry", W.name.c_str()));
|
||||
std::vector<std::string> srcs;
|
||||
/* A row piece of a checkpoint tensor (RAD_MAP_ROWS) is a source of its own, named
|
||||
* `<module>@<first row>+<rows>`: the adapter's B rows it takes are that range of the
|
||||
* module's. */
|
||||
std::vector<std::string> piece;
|
||||
const bool alternatives = maps->size() == 1 && (*maps)[0]->mode == RAD_MAP_COPY &&
|
||||
(*maps)[0]->n_src > 1;
|
||||
for (const RadNameMap* m : *maps)
|
||||
for (int k = 0; k < m->n_src && k < 8; ++k) {
|
||||
if (m->src_index[k] >= 0)
|
||||
const bool rows = m->mode == RAD_MAP_ROWS;
|
||||
if (!rows && m->src_index[k] >= 0)
|
||||
return fail(err, RAD_E_UNSUPPORTED,
|
||||
fmt("weight '%s' is slice %d of the stacked checkpoint tensor %s; a "
|
||||
"LoRA on a stacked (expert) tensor is not supported",
|
||||
W.name.c_str(), m->src_index[k], m->src[k]));
|
||||
srcs.push_back(m->src[k] ? m->src[k] : "");
|
||||
piece.push_back(rows ? fmt("@%d+%lld", m->src_index[k], (long long)m->src_rows[k]) : "");
|
||||
}
|
||||
if (alternatives) {
|
||||
/* COPY with alternatives: the first one the container holds is the weight, and which one
|
||||
* that is is not recorded. Usable only when exactly one alternative is targeted. */
|
||||
std::vector<std::string> hit;
|
||||
for (const std::string& x : srcs) {
|
||||
std::string leaf;
|
||||
if (!module_of(x, &leaf).empty() && targets.count(leaf) && !excluded_source(x))
|
||||
hit.push_back(x);
|
||||
}
|
||||
for (const std::string& x : srcs)
|
||||
if (source_targeted(prog, targets, x)) hit.push_back(x);
|
||||
if (hit.size() != 1)
|
||||
return fail(err, RAD_E_UNSUPPORTED,
|
||||
fmt("weight '%s' is one of %zu alternative checkpoint tensors and %zu of "
|
||||
"them are targeted; which one the container holds is not recorded",
|
||||
W.name.c_str(), srcs.size(), hit.size()));
|
||||
srcs = hit;
|
||||
piece.assign(srcs.size(), "");
|
||||
}
|
||||
int slot = 0;
|
||||
for (const std::string& x : srcs) {
|
||||
for (size_t si = 0; si < srcs.size(); ++si) {
|
||||
const std::string& x = srcs[si];
|
||||
SiteSource ss;
|
||||
std::string leaf;
|
||||
ss.module = module_of(x, &leaf);
|
||||
if (ss.module.empty()) ss.module = x;
|
||||
ss.targeted = !leaf.empty() && targets.count(leaf) && !excluded_source(x);
|
||||
ss.module += piece[si];
|
||||
ss.targeted = source_targeted(prog, targets, x);
|
||||
if (ss.targeted) ss.slot = slot++;
|
||||
s.sources.push_back(ss);
|
||||
}
|
||||
@@ -544,6 +578,8 @@ int make_site(const Program& prog, const MapIndex& mi, const TargetSet& targets,
|
||||
/* ================================================================== predicates */
|
||||
bool weight_targeted(const Program& prog, rad_weight w, const TargetSet& targets) {
|
||||
if (targets.empty() || w == 0 || w >= prog.weights.size()) return false;
|
||||
/* A generator's fused GEMMs are kept: its scope is the plain GEMMs (build_sites). */
|
||||
if (gen_scope(prog)) return false;
|
||||
const WeightInfo& wi = prog.weights[w];
|
||||
if (excluded_weight(prog, wi)) return false;
|
||||
std::vector<const RadNameMap*> maps;
|
||||
@@ -598,7 +634,7 @@ bool op_is_site(const Program& prog, const OpInfo& op, rad_weight* b_out, std::s
|
||||
int find_unsupported_uses(const Program& prog, const TargetSet& targets,
|
||||
std::vector<UnsupportedUse>* out) {
|
||||
if (out) out->clear();
|
||||
if (targets.empty()) return 0;
|
||||
if (targets.empty() || gen_scope(prog)) return 0;
|
||||
const MapIndex mi(prog);
|
||||
int n = 0;
|
||||
for (size_t i = 1; i < prog.ops.size(); ++i) {
|
||||
@@ -642,14 +678,47 @@ int build_sites(const Program& prog, const TargetSet& targets, int max_rank,
|
||||
if (max_rank <= 0) return fail(err, RAD_E_INVAL, fmt("max LoRA rank %d", max_rank));
|
||||
if (targets.empty()) return RAD_OK;
|
||||
const MapIndex mi(prog);
|
||||
/* A generator's weight carries an adapter only when every op reading it is a site over it; one
|
||||
* read elsewhere (a fused GEMM, a non-GEMM op) stays the base everywhere. */
|
||||
std::set<std::string> other_reader;
|
||||
if (gen_scope(prog))
|
||||
for (size_t i = 1; i < prog.ops.size(); ++i) {
|
||||
const OpInfo& op = prog.ops[i];
|
||||
if (op.weights.empty() || !op_live(op)) continue;
|
||||
rad_weight b = 0;
|
||||
const bool site = op_is_site(prog, op, &b, nullptr);
|
||||
for (rad_weight h : op.weights)
|
||||
if (h && h < prog.weights.size() &&
|
||||
(!site || !b || prog.weights[b].source != prog.weights[h].source))
|
||||
other_reader.insert(prog.weights[h].source);
|
||||
}
|
||||
std::map<rad_weight, int32_t> pool_of;
|
||||
std::vector<size_t> first_site;
|
||||
for (size_t i = 1; i < prog.ops.size(); ++i) {
|
||||
rad_weight b = 0;
|
||||
if (!op_live(prog.ops[i]) || !op_is_site(prog, prog.ops[i], &b, nullptr)) continue;
|
||||
if (!targeted_idx(prog, mi, b, targets)) continue;
|
||||
if (other_reader.count(prog.weights[b].source)) continue;
|
||||
if (gen_scope(prog)) {
|
||||
/* Checkpoint tensors copied, joined, transposed or cut into row pieces carry a
|
||||
* generator's adapter; a folded or derived one (weight norm, EMA) stays the base. */
|
||||
bool whole = true;
|
||||
if (const auto* maps = mi.find(prog.weights[b].source))
|
||||
for (const RadNameMap* m : *maps)
|
||||
whole = whole && (m->mode == RAD_MAP_COPY || m->mode == RAD_MAP_CONCAT ||
|
||||
m->mode == RAD_MAP_TRANSPOSE || m->mode == RAD_MAP_ROWS);
|
||||
if (!whole) continue;
|
||||
}
|
||||
Site s;
|
||||
const int st = make_site(prog, mi, targets, max_rank, (uint32_t)i, b, &s, err);
|
||||
if (st < 0 && gen_scope(prog)) {
|
||||
/* A generator's every plain GEMM is a candidate; one whose geometry cannot be told
|
||||
* stays the base, as a fused one does. */
|
||||
RAD_WARN("lora: '%s' carries no adapter: %s", prog.weights[b].name.c_str(),
|
||||
err ? err->c_str() : "");
|
||||
if (err) err->clear();
|
||||
continue;
|
||||
}
|
||||
if (st < 0) return st;
|
||||
auto it = pool_of.find(b);
|
||||
if (it == pool_of.end()) {
|
||||
@@ -729,15 +798,6 @@ std::string explain_module(const Program& prog, const TargetSet& targets, const
|
||||
/* ================================================================== the adapter */
|
||||
namespace {
|
||||
|
||||
struct AdModule {
|
||||
std::string name;
|
||||
const StTensor* A = nullptr;
|
||||
const StTensor* B = nullptr;
|
||||
int64_t rank = 0;
|
||||
double alpha = 0.0;
|
||||
float scale = 0.0f;
|
||||
};
|
||||
|
||||
struct Slot { int32_t pool; int32_t source; };
|
||||
|
||||
} /* namespace */
|
||||
@@ -937,6 +997,12 @@ int load_adapter(const std::string& dir, const std::vector<Site>& sites, int max
|
||||
info->leaves.insert(d == std::string::npos ? am.name : am.name.substr(d + 1));
|
||||
}
|
||||
|
||||
return pack_modules(sites, max_rank, mods, info, packed, err);
|
||||
}
|
||||
|
||||
int pack_modules(const std::vector<Site>& sites, int max_rank,
|
||||
const std::map<std::string, AdModule>& mods, AdapterInfo* info,
|
||||
std::vector<PackedSite>* packed, std::string* err, bool compact) {
|
||||
/* ---- the sites, by pool: the representative of each pool and where its modules sit. */
|
||||
int32_t n_pools = 0;
|
||||
for (const Site& s : sites) {
|
||||
@@ -955,7 +1021,9 @@ int load_adapter(const std::string& dir, const std::vector<Site>& sites, int max
|
||||
}
|
||||
std::unordered_map<std::string, std::vector<Slot>> where;
|
||||
for (int32_t p = 0; p < n_pools; ++p) {
|
||||
if (!rep[(size_t)p]) return fail(err, RAD_E_INVAL, fmt("pool %d has no site", p));
|
||||
/* A pool whose only GEMM could carry no adapter ops (lora_declare drops it) holds
|
||||
* nothing. */
|
||||
if (!rep[(size_t)p]) continue;
|
||||
const Site& s = *rep[(size_t)p];
|
||||
for (size_t i = 0; i < s.sources.size(); ++i)
|
||||
if (s.sources[i].targeted) where[s.sources[i].module].push_back({ p, (int32_t)i });
|
||||
@@ -1001,9 +1069,10 @@ int load_adapter(const std::string& dir, const std::vector<Site>& sites, int max
|
||||
/* ---- pack, pool by pool */
|
||||
packed->resize((size_t)n_pools);
|
||||
for (int32_t p = 0; p < n_pools; ++p) {
|
||||
const Site& s = *rep[(size_t)p];
|
||||
PackedSite& out = (*packed)[(size_t)p];
|
||||
out.pool = p;
|
||||
if (!rep[(size_t)p]) continue;
|
||||
const Site& s = *rep[(size_t)p];
|
||||
out.a.assign((size_t)(s.R * s.K_r), 0);
|
||||
out.b.assign((size_t)(s.N_r * s.R), 0);
|
||||
out.scale.assign((size_t)s.N_r, 0.0f);
|
||||
@@ -1135,12 +1204,19 @@ int load_adapter(const std::string& dir, const std::vector<Site>& sites, int max
|
||||
}
|
||||
|
||||
/* Pack. A: rows t_off.. of the module's block; B: rows y_col.., columns t_off..; scale on
|
||||
* the module's rows. */
|
||||
* the module's rows. Compact: the modules' ranks one after another from 0. */
|
||||
std::vector<int64_t> off(n, 0);
|
||||
int64_t used = 0;
|
||||
for (size_t i = 0; i < n; ++i) {
|
||||
off[i] = compact ? used : (int64_t)s.sources[i].slot * max_rank;
|
||||
if (am[i]) used += am[i]->rank;
|
||||
}
|
||||
out.r_used = compact ? used : s.R;
|
||||
for (size_t i = 0; i < n; ++i) {
|
||||
if (!am[i]) continue;
|
||||
const StTensor& A = *am[i]->A;
|
||||
const int64_t r = am[i]->rank, kc = A.shape[1];
|
||||
const int64_t t0 = (int64_t)s.sources[i].slot * max_rank;
|
||||
const int64_t t0 = off[i];
|
||||
for (int64_t j = 0; j < r; ++j)
|
||||
for (int64_t k = 0; k < s.K_r; ++k)
|
||||
out.a[(size_t)((t0 + j) * s.K_r + k)] = elem_bf16(A, j * kc + s.k_lo + k);
|
||||
@@ -1156,7 +1232,7 @@ int load_adapter(const std::string& dir, const std::vector<Site>& sites, int max
|
||||
if (yr < 0 || yr >= s.N_r)
|
||||
return fail(err, RAD_E_STATE, fmt("weight '%s': a part lands outside y", s.weight.c_str()));
|
||||
for (int64_t j = 0; j < r; ++j)
|
||||
out.b[(size_t)(yr * s.R + sp.t_off + j)] = elem_bf16(B, row * r + j);
|
||||
out.b[(size_t)(yr * s.R + off[i] + j)] = elem_bf16(B, row * r + j);
|
||||
out.scale[(size_t)yr] = am[i]->scale;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -19,12 +19,14 @@
|
||||
#include "../rad_core.h"
|
||||
|
||||
#include <cstdint>
|
||||
#include <map>
|
||||
#include <set>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
namespace rad {
|
||||
struct StTensor;
|
||||
namespace lora {
|
||||
|
||||
/* HF module leaf names, ordered so every caller builds the same set. Empty targets nothing. */
|
||||
@@ -82,6 +84,8 @@ struct PackedSite {
|
||||
std::vector<float> scale; /* [N_r]: the module's alpha/r (alpha/sqrt(r) rsLoRA) on its rows */
|
||||
int32_t pool = -1;
|
||||
bool empty = true; /* no module of this adapter lands in this pool */
|
||||
/* Packed compact (pack_modules): the ranks the modules take, from j = 0; R otherwise. */
|
||||
int64_t r_used = 0;
|
||||
};
|
||||
|
||||
/* What an adapter is, independent of the name it is served under. */
|
||||
@@ -157,6 +161,26 @@ int build_sites(const Program& prog, const TargetSet& targets, int max_rank,
|
||||
int load_adapter(const std::string& dir, const std::vector<Site>& sites, int max_rank,
|
||||
AdapterInfo* info, std::vector<PackedSite>* packed, std::string* err);
|
||||
|
||||
/* One module's factors as the packer reads them: lora_A [rank, K] and lora_B [rows, rank] in any
|
||||
* dtype a safetensors tensor carries (BF16, F16, F32), and the scale its rows run at. `name` is the
|
||||
* module path the base's name map spells (without ".weight"). */
|
||||
struct AdModule {
|
||||
std::string name;
|
||||
const StTensor* A = nullptr;
|
||||
const StTensor* B = nullptr;
|
||||
int64_t rank = 0;
|
||||
double alpha = 0.0;
|
||||
float scale = 0.0f;
|
||||
};
|
||||
|
||||
/* load_adapter's second half, for any source of factors: `mods` (by name) packed into one
|
||||
* PackedSite per pool of `sites`, in the slot layout of the pool's sites. Fills info->modules and
|
||||
* info->absent. `compact`: the modules of a pool take consecutive ranks from j = 0, in source
|
||||
* order, instead of a block of max_rank each, so a pass may run only the first r_used of them. */
|
||||
int pack_modules(const std::vector<Site>& sites, int max_rank,
|
||||
const std::map<std::string, AdModule>& mods, AdapterInfo* info,
|
||||
std::vector<PackedSite>* packed, std::string* err, bool compact = false);
|
||||
|
||||
/* After load_adapter on every rank: refuse a module that no rank placed. With `prog`/`targets`
|
||||
* (any one rank's) the message says why it is not a site (base lacks it, scope, target list, op). */
|
||||
int check_placed(const std::vector<AdapterInfo>& per_rank, std::string* err,
|
||||
|
||||
+16
-1
@@ -60,6 +60,7 @@ uint64_t SlotTable::publish(int slot, const std::string& name, const std::string
|
||||
s.uid = next_uid_++;
|
||||
s.used = true;
|
||||
s.draining = false;
|
||||
s.last_use = ++uses_;
|
||||
return s.uid;
|
||||
}
|
||||
|
||||
@@ -69,10 +70,11 @@ int SlotTable::acquire(const std::string& name, int32_t* slot, uint64_t* uid,
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(mu_);
|
||||
for (size_t i = 0; i < slots_.size() && !u; ++i) {
|
||||
const Slot& x = slots_[i];
|
||||
Slot& x = slots_[i];
|
||||
if (x.uid == 0 || x.draining || x.name != name) continue;
|
||||
u = x.uid;
|
||||
*slot = (int32_t)i;
|
||||
x.last_use = ++uses_;
|
||||
++refs_[u];
|
||||
}
|
||||
}
|
||||
@@ -125,6 +127,19 @@ int SlotTable::unload(const std::string& name, int* in_flight, std::string* err)
|
||||
return RAD_E_NOTFOUND;
|
||||
}
|
||||
|
||||
int SlotTable::evict_idle(std::string* evicted) {
|
||||
std::lock_guard<std::mutex> lk(mu_);
|
||||
Slot* best = nullptr;
|
||||
for (Slot& x : slots_) {
|
||||
if (x.uid == 0 || x.draining || refs_.count(x.uid)) continue;
|
||||
if (!best || x.last_use < best->last_use) best = &x;
|
||||
}
|
||||
if (!best) return RAD_E_FULL;
|
||||
if (evicted) *evicted = best->name;
|
||||
free_slot(*best, " to make room");
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
std::vector<std::string> SlotTable::names() const {
|
||||
std::lock_guard<std::mutex> lk(mu_);
|
||||
std::vector<std::string> out;
|
||||
|
||||
@@ -61,6 +61,10 @@ public:
|
||||
* RAD_E_NOTFOUND: nothing of that name is loaded. */
|
||||
int unload(const std::string& name, int* in_flight, std::string* err);
|
||||
|
||||
/* Free the least recently acquired loaded slot that no request holds, for a load that found
|
||||
* none free; its name in *evicted. RAD_E_FULL when every loaded slot is held. */
|
||||
int evict_idle(std::string* evicted);
|
||||
|
||||
/* The loaded adapters a request may name, in slot order: not the draining ones. */
|
||||
std::vector<std::string> names() const;
|
||||
/* Requests holding the adapter `name` (draining or not), 0 for none or no such adapter. */
|
||||
@@ -73,6 +77,7 @@ private:
|
||||
bool used = false; /* ever held an adapter, so `freed_at` means something */
|
||||
bool draining = false;
|
||||
uint64_t freed_at = 0; /* `epoch` when it was last freed */
|
||||
uint64_t last_use = 0; /* acquire counter at its last acquire or publish */
|
||||
};
|
||||
void free_slot(Slot& s, const char* how); /* under mu_ */
|
||||
void release(uint64_t uid); /* a hold's deleter */
|
||||
@@ -82,6 +87,7 @@ private:
|
||||
std::vector<Slot> slots_;
|
||||
std::map<uint64_t, int> refs_; /* uid -> holds */
|
||||
uint64_t next_uid_ = 1;
|
||||
uint64_t uses_ = 0;
|
||||
const std::atomic<uint64_t>* epoch_ = nullptr;
|
||||
};
|
||||
|
||||
|
||||
+27
-1
@@ -310,6 +310,11 @@ struct LoraIssueSite {
|
||||
int32_t pool = -1; /* index into Program::lora_pools */
|
||||
int32_t t = -1; /* index into Program::lora_t */
|
||||
int64_t R = 0, K = 0, N = 0;
|
||||
/* A generator's narrower pairs: the same pools read to rank R_v[i] < R, the pass taking the
|
||||
* narrowest that holds its slot's ranks (Program::lora_rused). */
|
||||
uint32_t shrink_v[2] = { 0, 0 }, expand_v[2] = { 0, 0 };
|
||||
int64_t R_v[2] = { 0, 0 };
|
||||
int8_t n_v = 0;
|
||||
};
|
||||
/* One targeted weight's adapter slots: A [S, R, K], B [S, N, R] bf16 and the per-column scale
|
||||
* [S, N] f32, persistent buffers, so the arena plan (and with it the KV budget) holds them. */
|
||||
@@ -323,6 +328,16 @@ struct LoraScratch {
|
||||
int64_t R = 0;
|
||||
rad_buf lane[2] = { 0, 0 };
|
||||
};
|
||||
/* A generator's adapter key names (rad_lora_root, rad_lora_alias in rad_builder.h). */
|
||||
struct LoraRoot {
|
||||
std::string native; /* checkpoint prefix of the network's tensors */
|
||||
std::vector<std::string> spellings; /* adapter-side prefixes; "" is a bare key */
|
||||
};
|
||||
struct LoraAlias {
|
||||
std::string root; /* LoraRoot::native it is relative to */
|
||||
std::string from, to; /* module paths, '#' a decimal index */
|
||||
int64_t from_lo = 0, from_hi = 0, to_lo = 0;
|
||||
};
|
||||
|
||||
/* Everything declare produced. The core owns it; the plugin only ever sees handles into it. */
|
||||
class Program {
|
||||
@@ -349,6 +364,17 @@ public:
|
||||
std::vector<LoraIssueSite> lora_sites;
|
||||
std::vector<LoraPool> lora_pools;
|
||||
std::vector<LoraScratch> lora_t;
|
||||
/* A generator's adapter key names: declared by the plugin whether or not adapters are on. A
|
||||
* generator that declares no root carries no adapters. */
|
||||
std::vector<LoraRoot> lora_roots;
|
||||
std::vector<LoraAlias> lora_aliases;
|
||||
/* A generator's pass runs with one adapter in every row: `lora_rows` is [S * lora_rows_n]
|
||||
* i32, run s all s, so a pass's slot operand is run s of it. 0 on a token-step program. */
|
||||
rad_buf lora_rows = 0;
|
||||
int64_t lora_rows_n = 0;
|
||||
/* A generator's slots pack each combination's ranks from j = 0: the ranks pool p takes in
|
||||
* slot s at [p * S + s], 0 for a pool the combination does not reach (no adapter op runs). */
|
||||
std::vector<int32_t> lora_rused;
|
||||
|
||||
/* The declared draft head (rad_declare_drafter). `kind == RAD_DRAFT_NONE` when none, the
|
||||
* normal case: the engine then speculates with the scheduler's prompt-lookup drafter or not at
|
||||
@@ -716,7 +742,7 @@ struct Config {
|
||||
* slower. `on` forces P2P and stops startup naming the refused pairs instead of falling
|
||||
* back. */
|
||||
int p2p = RAD_P2P_AUTO; /* --p2p auto|on|off */
|
||||
int64_t max_tok = 8192; /* --max-num-batched-tokens */
|
||||
int64_t max_tok = 2048; /* --max-num-batched-tokens */
|
||||
/* --busy-prefill-chunk: how much of a step a prefill chunk may take when other work is
|
||||
* pending in it (decode rows, another prefill, a request waiting for admission). -1 = auto:
|
||||
* leave those their rows plus a share for admission, but keep at least the smallest pass the
|
||||
|
||||
@@ -201,6 +201,9 @@ public:
|
||||
/* Call once on the rank thread before its first run_step: the backend's current device is
|
||||
* thread-local, and init may have run on another thread. */
|
||||
int bind_thread();
|
||||
/* The runtime LoRA slot every row of the generator passes that follow runs with, -1 for none
|
||||
* (Ctx::issue_lora). Set by the pass loop before it releases the rank for a pass. */
|
||||
void set_gen_lora_slot(int32_t s) { gen_lora_slot_ = s; }
|
||||
|
||||
/* ---------------------------------------------------------- run-phase queries */
|
||||
const RadBatch* batch() const { return batch_; }
|
||||
@@ -350,6 +353,7 @@ private:
|
||||
int bind_weights();
|
||||
int bind_ops();
|
||||
int issue_lora(rad_op h, const RadOperand* opd, int n_opd, int64_t n);
|
||||
int32_t gen_lora_slot_ = -1;
|
||||
int bind_routing();
|
||||
int bind_profiling();
|
||||
int check_domain(rad_op h, int domain) const;
|
||||
|
||||
+76
-24
@@ -424,17 +424,21 @@ int Ctx::issue(rad_op h, const RadOperand* opd, int n_opd, int64_t n) {
|
||||
* A row-parallel gemm's y is this rank's partial sum and the plugin reduces it after this returns,
|
||||
* so the delta rides the same reduction (B.A.x is linear in x's shards). Nothing is issued on a
|
||||
* step with no adapter row (RadBatch::lora_slot null), which is then the pass an engine without
|
||||
* adapters runs, nor on a draft pass, whose proposals the trunk verifies. An encoder or generator
|
||||
* pass never reaches a site: such a weight is outside the targets' scope rule (core/lora/lora.h),
|
||||
* so reaching one here is refused rather than run without its delta. */
|
||||
* adapters runs, nor on a draft pass, whose proposals the trunk verifies. An encoder pass never
|
||||
* reaches a site: such a weight is outside the targets' scope rule (core/lora/lora.h), so reaching
|
||||
* one here is refused rather than run without its delta.
|
||||
*
|
||||
* A generator's pass runs one adapter in all its rows (gen_lora_slot_, -1 for none), whatever the
|
||||
* rows are -- a stream's tokens, a text encoder's taps, a video's patches -- so its slot operand
|
||||
* is row `slot` of Program::lora_rows, the gemm's first n rows of it. */
|
||||
int Ctx::issue_lora(rad_op h, const RadOperand* opd, int n_opd, int64_t n) {
|
||||
if (!batch_) return RAD_OK;
|
||||
if (batch_->enc != 0 || batch_->gen != 0)
|
||||
const bool gen = batch_->gen != 0;
|
||||
if (batch_->enc != 0)
|
||||
return abort_step_msg(h, RAD_E_UNSUPPORTED,
|
||||
"a LoRA-targeted gemm was issued by an encoder or generator pass, "
|
||||
"which runtime LoRA does not reach; leave its module out of "
|
||||
"--lora-target-modules");
|
||||
if (!batch_->lora_slot || batch_->draft_pass != 0) return RAD_OK;
|
||||
"a LoRA-targeted gemm was issued by an encoder pass, which runtime "
|
||||
"LoRA does not reach; leave its module out of --lora-target-modules");
|
||||
if (gen ? gen_lora_slot_ < 0 : (!batch_->lora_slot || batch_->draft_pass != 0)) return RAD_OK;
|
||||
const OpPlan& p = plans_[h];
|
||||
const LoraIssueSite& s = program_->lora_sites[(size_t)p.lora_site];
|
||||
if (n == RAD_N_BATCH) n = batch_->n_tok;
|
||||
@@ -467,13 +471,15 @@ int Ctx::issue_lora(rad_op h, const RadOperand* opd, int n_opd, int64_t n) {
|
||||
rad_dtype_name(xd.dtype), rad_dtype_name(yd.dtype)));
|
||||
const int64_t yw = yd.rank >= 2 ? yd.shape[yd.rank - 1] : 0;
|
||||
if (yw <= 0) return abort_step_msg(h, RAD_E_STATE, "LoRA site: the gemm's output has no width");
|
||||
if (ya.cols == 0 && ya.offset % yw != 0)
|
||||
/* A token step reads each row's slot at the row the gemm wrote, so the views must name token
|
||||
* rows; a generator pass's one slot holds for any rows. */
|
||||
if (!gen && ya.cols == 0 && ya.offset % yw != 0)
|
||||
return abort_step_msg(h, RAD_E_STATE, "LoRA site: the gemm's output view starts inside a "
|
||||
"row, so its token rows cannot be told");
|
||||
const int64_t r0 = ya.offset / yw;
|
||||
const int64_t r0 = gen ? 0 : ya.offset / yw;
|
||||
/* The activation must start at the same row: shrink reads x's row m and expand writes y's row
|
||||
* m with one slot. */
|
||||
{
|
||||
if (!gen) {
|
||||
const int64_t xw = xd.rank >= 2 ? xd.shape[xd.rank - 1] : 0;
|
||||
if (xw <= 0 || (xa.cols == 0 && xa.offset % xw != 0) || xa.offset / xw != r0)
|
||||
return abort_step_msg(h, RAD_E_STATE, "LoRA site: the gemm's activation and output "
|
||||
@@ -483,26 +489,72 @@ int Ctx::issue_lora(rad_op h, const RadOperand* opd, int n_opd, int64_t n) {
|
||||
(int)op_domain_[s.expand].load(std::memory_order_relaxed) != dom)
|
||||
return abort_step_msg(h, RAD_E_UNSUPPORTED, "LoRA site: the adapter ops were placed in "
|
||||
"another domain than the gemm they follow");
|
||||
if (r0 < 0 || r0 + n > batch_->n_tok)
|
||||
if (!gen && (r0 < 0 || r0 + n > batch_->n_tok))
|
||||
return abort_step_msg(h, RAD_E_STATE,
|
||||
fmt("LoRA site: the gemm wrote rows [%lld, %lld) of a %lld-token step",
|
||||
(long long)r0, (long long)(r0 + n), (long long)batch_->n_tok));
|
||||
if (gen && (!program_->lora_rows || gen_lora_slot_ >= program_->lora_pools[(size_t)s.pool].S))
|
||||
return abort_step_msg(h, RAD_E_STATE,
|
||||
fmt("LoRA site: a generator pass in slot %d of %lld", gen_lora_slot_,
|
||||
(long long)program_->lora_pools[(size_t)s.pool].S));
|
||||
/* Each row's adapter is the step batch's (RadBatch::lora_slot), rewritten in stream order
|
||||
* before each step's kernels, so the pointer this launch records is the one a replay of it
|
||||
* reads. */
|
||||
* reads. A generator pass is never recorded, so its run of the slot table is named directly,
|
||||
* and it runs the pair over chunks of at most lora_rows_n rows: a video's passes run to
|
||||
* hundreds of thousands of rows, and `t` and the slot run are sized for one chunk. */
|
||||
const LoraPool& pool = program_->lora_pools[(size_t)s.pool];
|
||||
const rad_buf t = program_->lora_t[(size_t)s.t].lane[lane_ ? 1 : 0];
|
||||
RadOperand slot = RAD_P_T(batch_->lora_slot + r0, RAD_I32);
|
||||
slot.rows = n;
|
||||
const RadOperand tv = RAD_B_N(t, 0, n);
|
||||
const RadOperand sh[5] = { xa,
|
||||
s.opd_a_scale >= 0 && s.opd_a_scale < n_opd ? opd[s.opd_a_scale]
|
||||
: RAD_NONE,
|
||||
slot, RAD_B(pool.a), tv };
|
||||
int rc = issue_body((rad_op)s.shrink, sh, 5, n);
|
||||
if (rc < 0) return rc;
|
||||
const RadOperand ex[5] = { tv, slot, RAD_B(pool.b), RAD_B(pool.scale), ya };
|
||||
return issue_body((rad_op)s.expand, ex, 5, n);
|
||||
/* A generator's slot holds its ranks from 0 (Program::lora_rused): no pair where it holds
|
||||
* none, the narrowest declared pair that holds them otherwise. */
|
||||
uint32_t sh_op = s.shrink, ex_op = s.expand;
|
||||
int64_t rv = s.R;
|
||||
if (gen) {
|
||||
const size_t ui = (size_t)s.pool * (size_t)pool.S + (size_t)gen_lora_slot_;
|
||||
const int64_t used = ui < program_->lora_rused.size() ? program_->lora_rused[ui] : s.R;
|
||||
if (used <= 0) return RAD_OK;
|
||||
for (int v = 0; v < s.n_v; ++v)
|
||||
if (s.R_v[v] >= used) { sh_op = s.shrink_v[v]; ex_op = s.expand_v[v]; rv = s.R_v[v]; }
|
||||
}
|
||||
RadOperand xs = s.opd_a_scale >= 0 && s.opd_a_scale < n_opd ? opd[s.opd_a_scale]
|
||||
: RAD_NONE;
|
||||
const int64_t step = gen ? program_->lora_rows_n : n;
|
||||
if (step <= 0) return abort_step_msg(h, RAD_E_STATE, "LoRA site: no slot rows");
|
||||
int64_t sw = 0; /* a_scale's row stride, for a chunk past the first */
|
||||
if (n > step && xs.kind != RAD_OPK_NONE) {
|
||||
if (xs.kind != RAD_OPK_BUF || (size_t)xs.handle >= program_->buffers.size())
|
||||
return abort_step_msg(h, RAD_E_UNSUPPORTED, "LoRA site: a generator pass's activation "
|
||||
"scale is not a declared buffer, so its "
|
||||
"rows cannot be chunked");
|
||||
const RadBufDecl& sd = program_->buffers[xs.handle].decl;
|
||||
sw = sd.rank >= 2 ? sd.shape[sd.rank - 1] : 1;
|
||||
}
|
||||
const int64_t xw = xd.rank >= 2 ? xd.shape[xd.rank - 1] : 0;
|
||||
for (int64_t c = 0; c < n; c += step) {
|
||||
const int64_t nc = std::min(step, n - c);
|
||||
RadOperand x = xa, y = ya, a_s = xs;
|
||||
if (c > 0) {
|
||||
x.offset += c * xw;
|
||||
y.offset += c * yw;
|
||||
if (a_s.kind == RAD_OPK_BUF) a_s.offset += c * sw;
|
||||
}
|
||||
if (n > step) {
|
||||
x.rows = nc;
|
||||
y.rows = nc;
|
||||
if (a_s.kind == RAD_OPK_BUF) a_s.rows = nc;
|
||||
}
|
||||
RadOperand slot = gen ? RAD_B(program_->lora_rows) : RAD_P_T(batch_->lora_slot + r0, RAD_I32);
|
||||
if (gen) slot.offset = (int64_t)gen_lora_slot_ * program_->lora_rows_n;
|
||||
slot.rows = nc;
|
||||
RadOperand tv = RAD_B_N(t, 0, nc);
|
||||
if (rv < s.R) tv.cols = rv;
|
||||
const RadOperand sh[5] = { x, a_s, slot, RAD_B(pool.a), tv };
|
||||
int rc = issue_body((rad_op)sh_op, sh, 5, nc);
|
||||
if (rc < 0) return rc;
|
||||
const RadOperand ex[5] = { tv, slot, RAD_B(pool.b), RAD_B(pool.scale), y };
|
||||
rc = issue_body((rad_op)ex_op, ex, 5, nc);
|
||||
if (rc < 0) return rc;
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int Ctx::issue_body(rad_op h, const RadOperand* opd, int n_opd, int64_t n) {
|
||||
|
||||
@@ -599,6 +599,22 @@ struct ImageGenInfo {
|
||||
/* A reference picture is shrunk to `ref_area` only when larger, then centre-cropped to the
|
||||
* size multiple; otherwise resized to `ref_area` at its aspect. */
|
||||
bool ref_shrink_only = false;
|
||||
/* A prompt of fewer tokens after the drop prefix is padded with `pad_token` up to this many
|
||||
* (RadGeneratorDecl::min_tokens); 0: no minimum. */
|
||||
int64_t min_tokens = 0;
|
||||
int32_t pad_token = 0;
|
||||
/* The prompt is also read through the model's second tokenizer (IImageGen::encode_aux), at
|
||||
* most `aux_max_tokens` ids of it. */
|
||||
bool aux_tokens = false;
|
||||
int64_t aux_max_tokens = 0;
|
||||
/* A discrete-time model (RadGeneratorDecl::train_steps): the samplers it serves (1 << id)
|
||||
* and the sampler and scheduler a request gets when it names none. 0 samplers: flow
|
||||
* matching, which takes neither field. */
|
||||
uint32_t samplers = 0;
|
||||
int32_t default_sampler = 0, default_scheduler = 0;
|
||||
/* The prompt in windows (RadGeneratorDecl::chunk_tokens): tokens a window, its markers and
|
||||
* its padding token; 0 for a prompt read whole. */
|
||||
int32_t chunk_tokens = 0, chunk_bos = 0, chunk_eos = 0, chunk_pad = 0;
|
||||
};
|
||||
|
||||
class IImageGen {
|
||||
@@ -612,6 +628,13 @@ public:
|
||||
virtual int picture(const mm::Frame& f, std::shared_ptr<mm::Item>* out, std::string* why) = 0;
|
||||
virtual int64_t queued() const = 0;
|
||||
virtual int64_t running() const = 0;
|
||||
/* The user's prompt through the model's second tokenizer (ImageGenInfo::aux_tokens), with the
|
||||
* special tokens that tokenizer adds; RAD_E_UNSUPPORTED for a model without one. */
|
||||
virtual int encode_aux(const std::string& text, std::vector<int32_t>* out) const {
|
||||
(void)text;
|
||||
(void)out;
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
};
|
||||
|
||||
/* The audio generator (core/gen/audio_driver.h), for a model that makes music or other audio from
|
||||
|
||||
+111
-6
@@ -21,6 +21,7 @@
|
||||
* `.completed` event per image.
|
||||
*/
|
||||
#include "server.h"
|
||||
#include "loras.h"
|
||||
#include "oai.h"
|
||||
|
||||
#include "gen/gen.h"
|
||||
@@ -58,6 +59,7 @@ struct ImgReq {
|
||||
bool has_neg = false;
|
||||
double cfg = 1.0;
|
||||
int32_t w = 0, h = 0, n = 1, steps = 0, previews = 0;
|
||||
int32_t sampler = 0, scheduler = 0;
|
||||
bool seed_given = false;
|
||||
uint64_t seed = 0;
|
||||
std::string background = "auto", format = "png", quality = "auto";
|
||||
@@ -89,6 +91,11 @@ json form_value(const std::string& key, const std::string& v) {
|
||||
if (v == "true" || v == "1") return json(true);
|
||||
if (v == "false" || v == "0") return json(false);
|
||||
}
|
||||
/* `loras` as JSON text, or one adapter's name. */
|
||||
if ((key == "loras" || key == "lora") && !v.empty() && (v[0] == '[' || v[0] == '{')) {
|
||||
json j = json::parse(v, nullptr, false);
|
||||
if (!j.is_discarded()) return j;
|
||||
}
|
||||
return json(v);
|
||||
}
|
||||
|
||||
@@ -235,7 +242,7 @@ HttpResponse Server::handle_images(const HttpRequest& req, bool edit) {
|
||||
"output_compression", "response_format", "stream", "partial_images", "moderation",
|
||||
"style", "user", "input_fidelity", "seed", "negative_prompt", "true_cfg_scale",
|
||||
"guidance_scale",
|
||||
"num_inference_steps", "width", "height",
|
||||
"num_inference_steps", "width", "height", "loras", "lora", "sampler", "scheduler",
|
||||
};
|
||||
for (auto it = body.begin(); it != body.end(); ++it) {
|
||||
bool known = false;
|
||||
@@ -262,7 +269,20 @@ HttpResponse Server::handle_images(const HttpRequest& req, bool edit) {
|
||||
return error_response(err_bad("prompt", "expected a string"), req.peer);
|
||||
if (!body.contains("prompt"))
|
||||
return error_response(err_bad("prompt", "the prompt is required"), req.peer);
|
||||
if (r.prompt.empty()) r.prompt = " ";
|
||||
/* Runtime LoRA adapters: `loras` and <lora:...> tags, which leave the prompt. */
|
||||
std::vector<std::pair<std::string, double>> loras;
|
||||
{
|
||||
std::string field, why;
|
||||
if (parse_loras(body, &r.prompt, &loras, &field, &why) < 0)
|
||||
return error_response(err_bad(field.c_str(), why), req.peer);
|
||||
if (!loras.empty() && !opt_.gen_lora_acquire)
|
||||
return error_response(err_unsupported(field.c_str(), "this server was started without "
|
||||
"adapters (--lora, --lora-dir)"),
|
||||
req.peer);
|
||||
}
|
||||
/* An empty prompt becomes " ", as in the diffusers pipelines, unless the model pads a short
|
||||
* prompt itself (ImageGenInfo::min_tokens), as ComfyUI's tokenizers do. */
|
||||
if (r.prompt.empty() && info.min_tokens == 0) r.prompt = " ";
|
||||
std::string rf;
|
||||
if (str("response_format", &rf) < 0 || (!rf.empty() && rf != "b64_json" && rf != "url"))
|
||||
return error_response(err_bad("response_format", "expected b64_json"), req.peer);
|
||||
@@ -335,6 +355,39 @@ HttpResponse Server::handle_images(const HttpRequest& req, bool edit) {
|
||||
else if (r.quality == "medium") steps = std::max<int64_t>(1, info.default_steps * 3 / 4);
|
||||
}
|
||||
r.steps = (int32_t)steps;
|
||||
/* A discrete-time model's sampler and scheduler, by ComfyUI's names. */
|
||||
{
|
||||
std::string sname, kname;
|
||||
if (str("sampler", &sname) < 0)
|
||||
return error_response(err_bad("sampler", "expected a string"), req.peer);
|
||||
if (str("scheduler", &kname) < 0)
|
||||
return error_response(err_bad("scheduler", "expected a string"), req.peer);
|
||||
if (!info.samplers && (!sname.empty() || !kname.empty()))
|
||||
return error_response(err_unsupported(sname.empty() ? "scheduler" : "sampler",
|
||||
"this model samples with flow-matching Euler "
|
||||
"on its own schedule"), req.peer);
|
||||
r.sampler = info.default_sampler;
|
||||
r.scheduler = info.default_scheduler;
|
||||
if (!sname.empty()) {
|
||||
r.sampler = gen::sampler_id(sname);
|
||||
if (r.sampler < 0 || !(info.samplers & (1u << r.sampler))) {
|
||||
ApiError e = err_bad("sampler", "'" + sname + "' is not a sampler this model serves");
|
||||
for (int32_t i = 0; i < RAD_GEN_SAMPLER_COUNT; ++i)
|
||||
if (info.samplers & (1u << i)) e.supported.push_back(gen::sampler_name(i));
|
||||
return error_response(e, req.peer);
|
||||
}
|
||||
}
|
||||
if (!kname.empty()) {
|
||||
r.scheduler = gen::scheduler_id(kname);
|
||||
if (r.scheduler < 0) {
|
||||
ApiError e = err_bad("scheduler", "'" + kname + "' is not a scheduler this model "
|
||||
"serves");
|
||||
for (int32_t i = 0; i < RAD_GEN_SCHED_COUNT; ++i)
|
||||
e.supported.push_back(gen::scheduler_name(i));
|
||||
return error_response(e, req.peer);
|
||||
}
|
||||
}
|
||||
}
|
||||
/* -1 asks for a random seed, as llama-server and the chat endpoints read it. */
|
||||
if (body.contains("seed") && !body["seed"].is_null()) {
|
||||
if (!body["seed"].is_number_integer())
|
||||
@@ -365,12 +418,12 @@ HttpResponse Server::handle_images(const HttpRequest& req, bool edit) {
|
||||
"..30"), req.peer);
|
||||
}
|
||||
/* Guidance needs a scale past its off value and a negative prompt: the request's (empty
|
||||
* becomes " ", as in the reference pipeline), or the model's own. */
|
||||
* becomes " " as the prompt does), or the model's own. */
|
||||
const bool guided = r.cfg > cfg_off;
|
||||
const bool named_neg = body.contains("negative_prompt") && !body["negative_prompt"].is_null();
|
||||
r.has_neg = guided && (named_neg || info.has_default_negative);
|
||||
if (r.has_neg && !named_neg) r.negative = info.default_negative;
|
||||
else if (r.has_neg && r.negative.empty()) r.negative = " ";
|
||||
else if (r.has_neg && r.negative.empty() && info.min_tokens == 0) r.negative = " ";
|
||||
if (guided && !r.has_neg)
|
||||
return error_response(err_bad(cfg_key, "guidance needs a negative_prompt"), req.peer);
|
||||
|
||||
@@ -470,6 +523,8 @@ HttpResponse Server::handle_images(const HttpRequest& req, bool edit) {
|
||||
g->height = r.h;
|
||||
g->n = r.n;
|
||||
g->steps = r.steps;
|
||||
g->sampler = r.sampler;
|
||||
g->scheduler = r.scheduler;
|
||||
g->seed = r.seed;
|
||||
g->previews = r.previews;
|
||||
/* The driver guides as uncond + cfg (cond - uncond); a card's cond + s (cond - uncond) is
|
||||
@@ -585,6 +640,41 @@ HttpResponse Server::handle_images(const HttpRequest& req, bool edit) {
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
out->n_drop = (int32_t)drop.size();
|
||||
/* The reference tokenizer's minimum length: an empty prompt is padding the model reads. */
|
||||
while ((int64_t)out->tokens.size() - out->n_drop < info.min_tokens)
|
||||
out->tokens.push_back(info.pad_token);
|
||||
if (info.aux_tokens) {
|
||||
if (deps_.images->encode_aux(prompt, &out->aux) < 0) {
|
||||
*err = err_internal("the prompt could not be read by the model's second "
|
||||
"tokenizer");
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
if ((int64_t)out->aux.size() > info.aux_max_tokens) {
|
||||
*err = err_bad("prompt", "the prompt is " + std::to_string(out->aux.size()) +
|
||||
" tokens to this model's second tokenizer, which "
|
||||
"reads at most " +
|
||||
std::to_string(info.aux_max_tokens));
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
}
|
||||
/* A prompt read in windows: runs of at most chunk_tokens after the prefix, each between
|
||||
* its markers and padded to the window. */
|
||||
if (info.chunk_tokens > 0) {
|
||||
const size_t W = (size_t)info.chunk_tokens;
|
||||
std::vector<int32_t> win(out->tokens.begin(), out->tokens.begin() + out->n_drop);
|
||||
const size_t n_body = out->tokens.size() - (size_t)out->n_drop;
|
||||
size_t at = 0;
|
||||
do {
|
||||
const size_t take = std::min(W, n_body - at);
|
||||
win.push_back(info.chunk_bos);
|
||||
win.insert(win.end(), out->tokens.begin() + out->n_drop + (std::ptrdiff_t)at,
|
||||
out->tokens.begin() + out->n_drop + (std::ptrdiff_t)(at + take));
|
||||
win.push_back(info.chunk_eos);
|
||||
win.resize(win.size() + (W - take), info.chunk_pad);
|
||||
at += take;
|
||||
} while (at < n_body);
|
||||
out->tokens = std::move(win);
|
||||
}
|
||||
if ((int64_t)out->tokens.size() > info.max_cond_tokens) {
|
||||
*err = err_bad("prompt", "the prompt is " + std::to_string(out->tokens.size()) +
|
||||
" tokens with its pictures; this deployment conditions on "
|
||||
@@ -600,6 +690,19 @@ HttpResponse Server::handle_images(const HttpRequest& req, bool edit) {
|
||||
return error_response(err, req.peer);
|
||||
}
|
||||
|
||||
/* ---- the adapters' slot, held until the request is done */
|
||||
std::string lora_note;
|
||||
if (!loras.empty()) {
|
||||
std::string why;
|
||||
const int s = opt_.gen_lora_acquire(loras, &g->lora_slot, &g->lora_hold, &lora_note, &why);
|
||||
if (s < 0) {
|
||||
ApiError e = err_bad("loras", why);
|
||||
if (s == RAD_E_NOTFOUND) { e.status = 404; e.type = "not_found_error"; }
|
||||
else if (s != RAD_E_INVAL) { e.status = 503; e.type = "server_error"; }
|
||||
return error_response(e, req.peer);
|
||||
}
|
||||
}
|
||||
|
||||
/* ---- admitted and queued */
|
||||
if (auto no = admit(1, req.peer)) return *no;
|
||||
std::shared_ptr<gen::Ticket> ticket = g->ticket;
|
||||
@@ -613,9 +716,11 @@ HttpResponse Server::handle_images(const HttpRequest& req, bool edit) {
|
||||
return error_response(e, req.peer);
|
||||
}
|
||||
}
|
||||
RAD_INFO("images: %s %dx%d n=%d steps=%d seed=%llu%s%s%s", edit ? "edit" : "generation", r.w,
|
||||
std::string lora_s;
|
||||
for (const auto& [n, w] : loras) lora_s += (lora_s.empty() ? " loras=" : ",") + n + fmt(":%g", w);
|
||||
RAD_INFO("images: %s %dx%d n=%d steps=%d seed=%llu%s%s%s%s", edit ? "edit" : "generation", r.w,
|
||||
r.h, r.n, r.steps, (unsigned long long)r.seed, r.has_neg ? " guided" : "",
|
||||
r.has_mask ? " masked" : "", r.stream ? " streamed" : "");
|
||||
r.has_mask ? " masked" : "", r.stream ? " streamed" : "", lora_s.c_str());
|
||||
|
||||
/* ---- one finished picture to a file */
|
||||
const std::string size_s = std::to_string(r.w) + "x" + std::to_string(r.h);
|
||||
|
||||
@@ -0,0 +1,117 @@
|
||||
/* loras.cpp -- see loras.h. */
|
||||
#include "loras.h"
|
||||
#include "rad_internal.h"
|
||||
|
||||
#include <cmath>
|
||||
#include <cstdlib>
|
||||
|
||||
namespace rad {
|
||||
namespace server {
|
||||
|
||||
namespace {
|
||||
|
||||
/* "name" or "name:strength" (the last ':' splits, so a name may hold one). */
|
||||
bool split_entry(const std::string& s, std::string* name, double* w) {
|
||||
*w = 1.0;
|
||||
const size_t c = s.rfind(':');
|
||||
if (c != std::string::npos && c + 1 < s.size()) {
|
||||
char* end = nullptr;
|
||||
const double v = std::strtod(s.c_str() + c + 1, &end);
|
||||
if (end && *end == '\0' && std::isfinite(v)) {
|
||||
*name = s.substr(0, c);
|
||||
*w = v;
|
||||
return !name->empty();
|
||||
}
|
||||
}
|
||||
*name = s;
|
||||
return !name->empty();
|
||||
}
|
||||
|
||||
} /* namespace */
|
||||
|
||||
int parse_loras(const nlohmann::json& body, std::string* prompt,
|
||||
std::vector<std::pair<std::string, double>>* out, std::string* field,
|
||||
std::string* why) {
|
||||
out->clear();
|
||||
const char* key = body.contains("loras") ? "loras" : "lora";
|
||||
if (body.contains(key) && !body[key].is_null()) {
|
||||
*field = key;
|
||||
const nlohmann::json& v = body[key];
|
||||
auto entry = [&](const nlohmann::json& e) -> bool {
|
||||
std::string name;
|
||||
double w = 1.0;
|
||||
if (e.is_string()) {
|
||||
if (!split_entry(e.get<std::string>(), &name, &w)) return false;
|
||||
} else if (e.is_object()) {
|
||||
if (!e.contains("name") || !e["name"].is_string()) return false;
|
||||
name = e["name"].get<std::string>();
|
||||
for (const char* k : { "weight", "strength", "scale" })
|
||||
if (e.contains(k) && !e[k].is_null()) {
|
||||
if (!e[k].is_number()) return false;
|
||||
w = e[k].get<double>();
|
||||
}
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
if (name.empty() || !std::isfinite(w)) return false;
|
||||
out->push_back({ name, w });
|
||||
return true;
|
||||
};
|
||||
if (v.is_array()) {
|
||||
for (const nlohmann::json& e : v)
|
||||
if (!entry(e)) {
|
||||
*why = "each entry is a name, \"name:strength\" or {\"name\", \"weight\"}";
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
} else if (v.is_object() && !v.contains("name")) {
|
||||
for (auto it = v.begin(); it != v.end(); ++it) {
|
||||
if (!it.value().is_number() || !std::isfinite(it.value().get<double>())) {
|
||||
*why = "a {name: strength} object's strengths are numbers";
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
out->push_back({ it.key(), it.value().get<double>() });
|
||||
}
|
||||
} else if (!entry(v)) {
|
||||
*why = "expected a list of adapters (names, \"name:strength\" or {\"name\", \"weight\"})";
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
}
|
||||
/* <lora:name[:strength]> tags in the prompt. */
|
||||
if (prompt) {
|
||||
std::string p;
|
||||
size_t at = 0;
|
||||
for (;;) {
|
||||
const size_t open = prompt->find("<lora:", at);
|
||||
if (open == std::string::npos) { p += prompt->substr(at); break; }
|
||||
const size_t close = prompt->find('>', open);
|
||||
if (close == std::string::npos) { p += prompt->substr(at); break; }
|
||||
std::string name;
|
||||
double w = 1.0;
|
||||
if (!split_entry(prompt->substr(open + 6, close - open - 6), &name, &w)) {
|
||||
*field = "prompt";
|
||||
*why = "a <lora:...> tag names no adapter";
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
out->push_back({ name, w });
|
||||
p += prompt->substr(at, open - at);
|
||||
at = close + 1;
|
||||
}
|
||||
if (p.size() != prompt->size()) {
|
||||
/* Tidy the gaps the tags leave: runs of spaces, and commas with nothing between. */
|
||||
std::string t;
|
||||
for (char c : p) {
|
||||
if (c == ' ' && (t.empty() || t.back() == ' ')) continue;
|
||||
t += c;
|
||||
}
|
||||
for (size_t k; (k = t.find(", ,")) != std::string::npos;) t.erase(k, 2);
|
||||
for (size_t k; (k = t.find(",,")) != std::string::npos;) t.erase(k, 1);
|
||||
while (!t.empty() && (t[0] == ' ' || t[0] == ',')) t.erase(0, 1);
|
||||
while (!t.empty() && (t.back() == ' ' || t.back() == ',')) t.pop_back();
|
||||
*prompt = t.empty() ? std::string(" ") : t;
|
||||
}
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
} /* namespace server */
|
||||
} /* namespace rad */
|
||||
@@ -0,0 +1,30 @@
|
||||
/* loras.h -- which runtime LoRA adapters an image or video request asks for, and at what strength.
|
||||
*
|
||||
* Two spellings, merged:
|
||||
*
|
||||
* `loras` in the body: a list whose entries are a name, "name:strength", or an object
|
||||
* {"name": ..., "weight" | "strength" | "scale": ...}; or an object {name: strength}.
|
||||
* `lora` is the same field.
|
||||
*
|
||||
* <lora:name> or <lora:name:strength> in the prompt, as Stable Diffusion web UIs write it: the
|
||||
* tag is taken out of the prompt, the text around it kept.
|
||||
*
|
||||
* A strength not given is 1. */
|
||||
#pragma once
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
#include <string>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
namespace rad {
|
||||
namespace server {
|
||||
|
||||
/* RAD_OK with the adapters in `out` (possibly none) and their tags removed from *prompt;
|
||||
* RAD_E_INVAL with `why` for a malformed entry. `field` receives the field the error is about. */
|
||||
int parse_loras(const nlohmann::json& body, std::string* prompt,
|
||||
std::vector<std::pair<std::string, double>>* out, std::string* field,
|
||||
std::string* why);
|
||||
|
||||
} /* namespace server */
|
||||
} /* namespace rad */
|
||||
@@ -132,6 +132,7 @@ void Server::register_routes() {
|
||||
return r;
|
||||
});
|
||||
router_.get ("/v1/models", [this](const HttpRequest& q) { return handle_models(q); });
|
||||
router_.get ("/v1/loras", [this](const HttpRequest& q) { return handle_loras(q); });
|
||||
router_.get ("/v1/models/*id", [this](const HttpRequest& q) { return handle_models(q); });
|
||||
router_.post("/v1/load_lora_adapter", [this](const HttpRequest& q) { return handle_lora_admin(q, true); });
|
||||
router_.post("/v1/unload_lora_adapter", [this](const HttpRequest& q) { return handle_lora_admin(q, false); });
|
||||
@@ -1864,6 +1865,22 @@ HttpResponse Server::handle_models(const HttpRequest& req) {
|
||||
/* Runtime LoRA admin, vLLM's routes and bodies: {"lora_name", "lora_path"} to load, {"lora_name"}
|
||||
* to unload. The path is read on this machine, so without --api-key only a loopback client may
|
||||
* ask, the rule /diagnostics follows. */
|
||||
/* A generator's adapter files: what `loras` and <lora:...> tags may name. */
|
||||
HttpResponse Server::handle_loras(const HttpRequest& req) {
|
||||
using json = nlohmann::json;
|
||||
if (!opt_.gen_lora_names) {
|
||||
ApiError e;
|
||||
e.status = 404;
|
||||
e.type = "not_found_error";
|
||||
e.message = "this server takes no adapters in image or video requests (--lora, --lora-dir)";
|
||||
return error_response(e, req.peer);
|
||||
}
|
||||
json data = json::array();
|
||||
for (const std::string& n : opt_.gen_lora_names()) data.push_back({ { "id", n }, { "object", "lora" } });
|
||||
metrics_.observe_http(200);
|
||||
return HttpResponse::json_body(200, json_dump(json{ { "object", "list" }, { "data", std::move(data) } }));
|
||||
}
|
||||
|
||||
HttpResponse Server::handle_lora_admin(const HttpRequest& req, bool load) {
|
||||
using json = nlohmann::json;
|
||||
auto fail = [&](int status, const char* type, const std::string& msg) {
|
||||
|
||||
@@ -141,6 +141,12 @@ struct ServerOptions {
|
||||
* of an adapter requests still use drains it: RAD_OK with *in_flight > 0 (Engine::lora_unload). */
|
||||
std::function<int(const std::string&, const std::string&, std::string*)> lora_load;
|
||||
std::function<int(const std::string&, std::string*, int*)> lora_unload;
|
||||
/* A generator's adapters (Engine::gen_lora_acquire): the images and videos endpoints' `loras`
|
||||
* and <lora:...> tags get a slot holding that combination, a hold on it and a note on what was
|
||||
* left out; `gen_lora_names` is GET /v1/loras. Unset without adapters. */
|
||||
std::function<int(const std::vector<std::pair<std::string, double>>&, int32_t*,
|
||||
std::shared_ptr<void>*, std::string*, std::string*)> gen_lora_acquire;
|
||||
std::function<std::vector<std::string>()> gen_lora_names;
|
||||
|
||||
std::string api_key;
|
||||
bool cors = true;
|
||||
@@ -240,6 +246,7 @@ private:
|
||||
void realtime_run(RealtimeSession& s, WsConn& ws);
|
||||
bool realtime_loop(RealtimeSession& s, WsConn& ws);
|
||||
HttpResponse handle_models(const HttpRequest& req);
|
||||
HttpResponse handle_loras(const HttpRequest& req);
|
||||
HttpResponse handle_metrics(const HttpRequest& req);
|
||||
std::optional<HttpResponse> refuse_text(const std::string& peer,
|
||||
ApiShape shape = ApiShape::OpenAI);
|
||||
|
||||
+26
-3
@@ -39,6 +39,7 @@
|
||||
* special tokens and the prompt without, so a caller cannot write control tokens into it.
|
||||
*/
|
||||
#include "server.h"
|
||||
#include "loras.h"
|
||||
#include "oai.h"
|
||||
|
||||
#include "gen/video.h"
|
||||
@@ -168,7 +169,9 @@ HttpResponse Server::handle_video_create(const HttpRequest& req) {
|
||||
return error_response(err_bad(p.name, "'" + p.name + "' takes text, not a file"),
|
||||
req.peer);
|
||||
json v = p.data;
|
||||
if (p.name == "target" || p.name == "conditions") {
|
||||
if (p.name == "target" || p.name == "conditions" ||
|
||||
((p.name == "loras" || p.name == "lora") && !p.data.empty() &&
|
||||
(p.data[0] == '[' || p.data[0] == '{'))) {
|
||||
v = json::parse(p.data, nullptr, false);
|
||||
if (v.is_discarded())
|
||||
return error_response(err_bad(p.name, "expected JSON"), req.peer);
|
||||
@@ -183,7 +186,7 @@ HttpResponse Server::handle_video_create(const HttpRequest& req) {
|
||||
static const char* kKnown[] = {
|
||||
"model", "prompt", "seconds", "size", "input_reference", "seed", "num_inference_steps",
|
||||
"task", "target", "conditions", "user", "latent_upscale", "upscale_refine_steps",
|
||||
"negative_prompt", "decoder",
|
||||
"negative_prompt", "decoder", "loras", "lora",
|
||||
/* RadVideoGenBatch::guidance_h's order */
|
||||
"guidance_scale", "stg_scale", "modality_scale", "guidance_rescale",
|
||||
"audio_guidance_scale", "audio_stg_scale", "audio_modality_scale", "audio_guidance_rescale",
|
||||
@@ -210,7 +213,17 @@ HttpResponse Server::handle_video_create(const HttpRequest& req) {
|
||||
if (!has(body, "prompt") || !body["prompt"].is_string() ||
|
||||
body["prompt"].get<std::string>().find_first_not_of(" \t\r\n") == std::string::npos)
|
||||
return bad("prompt", "the prompt is required, as a non-empty string");
|
||||
const std::string prompt = body["prompt"].get<std::string>();
|
||||
std::string prompt = body["prompt"].get<std::string>();
|
||||
/* Runtime LoRA adapters: `loras` and <lora:...> tags, which leave the prompt. */
|
||||
std::vector<std::pair<std::string, double>> loras;
|
||||
{
|
||||
std::string field, why;
|
||||
if (parse_loras(body, &prompt, &loras, &field, &why) < 0) return bad(field.c_str(), why);
|
||||
if (!loras.empty() && !opt_.gen_lora_acquire)
|
||||
return error_response(err_unsupported(field.c_str(), "this server was started without "
|
||||
"adapters (--lora, --lora-dir)"),
|
||||
req.peer);
|
||||
}
|
||||
if (has(body, "input_reference")) {
|
||||
/* JSON: a data URL, as a string or an image_url object. */
|
||||
const json& v = body["input_reference"];
|
||||
@@ -497,6 +510,16 @@ HttpResponse Server::handle_video_create(const HttpRequest& req) {
|
||||
}
|
||||
|
||||
/* ---- admitted and queued: the job holds its place until its file is written */
|
||||
if (!loras.empty()) {
|
||||
std::string why, note;
|
||||
const int s = opt_.gen_lora_acquire(loras, &r->lora_slot, &r->lora_hold, ¬e, &why);
|
||||
if (s < 0) {
|
||||
ApiError e = err_bad("loras", why);
|
||||
if (s == RAD_E_NOTFOUND) { e.status = 404; e.type = "not_found_error"; }
|
||||
else if (s != RAD_E_INVAL) { e.status = 503; e.type = "server_error"; }
|
||||
return error_response(e, req.peer);
|
||||
}
|
||||
}
|
||||
if (auto no = admit(1, req.peer)) return *no;
|
||||
auto j = std::make_shared<VideoJob>();
|
||||
j->id = new_video_id();
|
||||
|
||||
+150
-27
@@ -1,5 +1,6 @@
|
||||
#include "text/tokenizer.h"
|
||||
#include "text/tokenizer_bpe.h"
|
||||
#include "text/tokenizer_grapheme.h"
|
||||
#include "text/tokenizer_nfc.h"
|
||||
#include "text/tokenizer_regex.h"
|
||||
#include "text/unicode_norm.h"
|
||||
@@ -388,6 +389,8 @@ struct TokEncoder {
|
||||
/* Split, a regex Replace, ByteLevel with use_regex, and the character-class
|
||||
* pre-tokenisers; `re2` is BertPreTokenizer's punctuation after its whitespace split. */
|
||||
std::unique_ptr<TokRegex> re, re2;
|
||||
/* Precompiled: the decoded character map. */
|
||||
std::unique_ptr<PrecompiledMap> pmap;
|
||||
};
|
||||
std::vector<Step> norm, pre;
|
||||
uint32_t kind = RAD_TOK_BPE;
|
||||
@@ -403,6 +406,12 @@ struct TokEncoder {
|
||||
TokTable text; /* token text -> lowest id */
|
||||
TokTable raw; /* raw bytes a byte-level token stands for -> id */
|
||||
int32_t byte_sym[256]; /* raw byte -> id of its byte-level character */
|
||||
/* BPE's end-of-word suffix (RAD_PRE_END_OF_WORD), empty without one. A word's last symbol
|
||||
* is its text with the suffix: `raw_eow` holds the tokens ending in it by the raw bytes
|
||||
* before it, and `byte_sym_eow` a byte's character with it. */
|
||||
std::string eow;
|
||||
TokTable raw_eow;
|
||||
int32_t byte_sym_eow[256];
|
||||
int32_t byte_tok[256]; /* raw byte -> id of "<0xNN>" */
|
||||
MergeTable merges;
|
||||
std::vector<uint8_t> types;
|
||||
@@ -419,6 +428,10 @@ struct TokEncoder {
|
||||
std::unique_ptr<std::atomic<uint8_t>[]> self_merges;
|
||||
|
||||
SpecialMatcher specials;
|
||||
/* The added tokens matched in the normalised text (RAD_PRE_ADDED_NORMALIZED); `specials`
|
||||
* holds the rest. */
|
||||
SpecialMatcher nspecials;
|
||||
bool has_nspecials = false;
|
||||
mutable SegmentCache cache;
|
||||
|
||||
int build(const VocabBuild& b, const std::vector<int32_t>& special);
|
||||
@@ -443,11 +456,19 @@ int TokEncoder::build(const VocabBuild& b, const std::vector<int32_t>& special)
|
||||
|
||||
for (const VocabStep& s : b.steps) {
|
||||
if (step_is_norm(s.kind)) {
|
||||
Step st{ s, nullptr, nullptr };
|
||||
Step st{ s, nullptr, nullptr, nullptr };
|
||||
if (s.kind == RAD_NORM_REPLACE && (s.flags & 1)) RAD_TRY(compile(s.arg0, "Replace", &st.re));
|
||||
if (s.kind == RAD_NORM_PRECOMPILED) {
|
||||
st.pmap = std::make_unique<PrecompiledMap>();
|
||||
std::string why;
|
||||
if (st.pmap->load(s.arg0, &why) < 0) {
|
||||
RAD_ERR("vocab: the Precompiled normaliser's map: %s", why.c_str());
|
||||
return RAD_E_FORMAT;
|
||||
}
|
||||
}
|
||||
norm.push_back(std::move(st));
|
||||
} else if (step_is_pre(s.kind)) {
|
||||
Step st{ s, nullptr, nullptr };
|
||||
Step st{ s, nullptr, nullptr, nullptr };
|
||||
if (s.kind == RAD_PRE_SPLIT) RAD_TRY(compile(s.arg0, "Split", &st.re));
|
||||
if (s.kind == RAD_PRE_WHITESPACE) {
|
||||
RAD_TRY(compile(s.flags == kPreWhitespace ? k_word_runs : k_space_runs,
|
||||
@@ -462,6 +483,7 @@ int TokEncoder::build(const VocabBuild& b, const std::vector<int32_t>& special)
|
||||
if (s.flags & 2) RAD_TRY(compile(k_gpt2_pattern, "ByteLevel", &st.re));
|
||||
}
|
||||
if (s.kind == RAD_PRE_BYTE_FALLBACK) byte_fallback = true;
|
||||
if (s.kind == RAD_PRE_END_OF_WORD) eow = s.arg0;
|
||||
if (s.kind == RAD_PRE_METASPACE && s.iarg == 1) prepend_first = true;
|
||||
pre.push_back(std::move(st));
|
||||
}
|
||||
@@ -469,7 +491,7 @@ int TokEncoder::build(const VocabBuild& b, const std::vector<int32_t>& special)
|
||||
if (kind == RAD_TOK_BPE) {
|
||||
for (size_t k = pre.size(); k-- > 0; ) {
|
||||
const uint32_t sk = pre[k].step.kind;
|
||||
if (sk == RAD_PRE_BYTE_FALLBACK) continue;
|
||||
if (sk == RAD_PRE_BYTE_FALLBACK || sk == RAD_PRE_END_OF_WORD) continue;
|
||||
if (sk == RAD_PRE_BYTELEVEL) defer_bytelevel = (int)k;
|
||||
break;
|
||||
}
|
||||
@@ -490,12 +512,20 @@ int TokEncoder::build(const VocabBuild& b, const std::vector<int32_t>& special)
|
||||
const char buf[7] = { '<', '0', 'x', hex[c >> 4], hex[c & 15], '>', 0 };
|
||||
byte_tok[c] = text.find(buf);
|
||||
byte_sym[c] = text.find(a.to_utf8[c]);
|
||||
byte_sym_eow[c] = eow.empty() ? -1 : text.find(a.to_utf8[c] + eow);
|
||||
}
|
||||
if (defer_bytelevel >= 0) {
|
||||
raw.reserve(n);
|
||||
std::string r;
|
||||
for (size_t i = 0; i < n; ++i)
|
||||
if (!b.tokens[i].empty() && byte_decode_strict(b.tokens[i], &r)) raw.insert(r, (int32_t)i);
|
||||
for (size_t i = 0; i < n; ++i) {
|
||||
const std::string& t = b.tokens[i];
|
||||
if (t.empty()) continue;
|
||||
if (!eow.empty() && t.size() > eow.size() &&
|
||||
t.compare(t.size() - eow.size(), eow.size(), eow) == 0 &&
|
||||
byte_decode_strict(t.substr(0, t.size() - eow.size()), &r))
|
||||
raw_eow.insert(r, (int32_t)i);
|
||||
if (byte_decode_strict(t, &r)) raw.insert(r, (int32_t)i);
|
||||
}
|
||||
}
|
||||
|
||||
/* Keyed by the pair as the vocab lists it; the lowest rank wins a duplicate. A symbol's id is
|
||||
@@ -511,7 +541,17 @@ int TokEncoder::build(const VocabBuild& b, const std::vector<int32_t>& special)
|
||||
merges.insert((int32_t)l, (int32_t)rr, (uint32_t)r, text.find(cat));
|
||||
}
|
||||
|
||||
specials.build(special, b.tokens, b.types);
|
||||
/* Each matcher keeps the priority order of `special` (longest first). */
|
||||
std::vector<int32_t> raw_special, norm_special;
|
||||
for (int32_t id : special) {
|
||||
bool normalized = false;
|
||||
for (const VocabStep& s : b.steps)
|
||||
normalized |= s.kind == RAD_PRE_ADDED_NORMALIZED && s.iarg == id;
|
||||
(normalized ? norm_special : raw_special).push_back(id);
|
||||
}
|
||||
specials.build(raw_special, b.tokens, b.types);
|
||||
nspecials.build(norm_special, b.tokens, b.types);
|
||||
has_nspecials = !norm_special.empty();
|
||||
self_merges.reset(new std::atomic<uint8_t>[n]());
|
||||
/* A byte-level BPE never looks text up by its mapped spelling once `raw` exists. */
|
||||
if (defer_bytelevel >= 0) text = TokTable();
|
||||
@@ -541,8 +581,8 @@ int Vocab::load(VocabBuild b) {
|
||||
* so a vocabulary that declares one does not load. */
|
||||
for (const VocabStep& s : b_.steps) {
|
||||
const uint32_t k = s.kind;
|
||||
if ((k >= RAD_NORM_NFC && k <= RAD_NORM_PREPEND) ||
|
||||
(k >= RAD_PRE_BYTELEVEL && k <= RAD_PRE_BYTE_FALLBACK) ||
|
||||
if ((k >= RAD_NORM_NFC && k <= RAD_NORM_PRECOMPILED) ||
|
||||
(k >= RAD_PRE_BYTELEVEL && k <= RAD_PRE_ADDED_NORMALIZED) ||
|
||||
(k >= RAD_DEC_BYTELEVEL && k <= RAD_DEC_BYTE_FALLBACK))
|
||||
continue;
|
||||
RAD_ERR("vocab: %s is not implemented", step_describe(s).c_str());
|
||||
@@ -570,6 +610,19 @@ int Vocab::load(VocabBuild b) {
|
||||
if (s.kind == RAD_DEC_STRIP && fused) fused_strip = true;
|
||||
}
|
||||
}
|
||||
/* A token matched in the normalised text is one of the vocabulary's added tokens, spelt as
|
||||
* the step says. */
|
||||
for (const VocabStep& s : b_.steps) {
|
||||
if (s.kind != RAD_PRE_ADDED_NORMALIZED) continue;
|
||||
const int32_t id = (int32_t)s.iarg;
|
||||
if (s.iarg < 0 || s.iarg >= (int64_t)b_.tokens.size() || s.arg0.empty() ||
|
||||
b_.tokens[(size_t)id] != s.arg0 ||
|
||||
(!b_.types.empty() && b_.types[(size_t)id] != RAD_TT_CONTROL &&
|
||||
b_.types[(size_t)id] != RAD_TT_USER_DEFINED)) {
|
||||
RAD_ERR("vocab: %s names no added token of that spelling", step_describe(s).c_str());
|
||||
return RAD_E_FORMAT;
|
||||
}
|
||||
}
|
||||
if (b_.types.empty()) b_.types.assign(b_.tokens.size(), (uint8_t)RAD_TT_NORMAL);
|
||||
if (b_.types.size() != b_.tokens.size()) {
|
||||
RAD_ERR("vocab: %zu tokens but %zu token types", b_.tokens.size(), b_.types.size());
|
||||
@@ -781,6 +834,8 @@ std::string step_describe(const VocabStep& s) {
|
||||
return fmt("Replace(%s '%s' -> '%s')", (s.flags & 1) ? "regex" : "literal",
|
||||
s.arg0.c_str(), s.arg1.c_str());
|
||||
case RAD_NORM_PREPEND: return fmt("Prepend('%s')", s.arg0.c_str());
|
||||
case RAD_NORM_PRECOMPILED:
|
||||
return fmt("Precompiled(%zu base64 bytes)", s.arg0.size());
|
||||
case RAD_PRE_BYTELEVEL:
|
||||
return fmt("ByteLevel(add_prefix_space=%d use_regex=%d)",
|
||||
(s.flags & 1) ? 1 : 0, (s.flags & 2) ? 1 : 0);
|
||||
@@ -806,6 +861,9 @@ std::string step_describe(const VocabStep& s) {
|
||||
case RAD_PRE_DIGITS:
|
||||
return fmt("Digits(individual=%d)", (s.flags & 1) ? 1 : 0);
|
||||
case RAD_PRE_BYTE_FALLBACK: return "ByteFallback";
|
||||
case RAD_PRE_END_OF_WORD: return fmt("EndOfWordSuffix('%s')", s.arg0.c_str());
|
||||
case RAD_PRE_ADDED_NORMALIZED:
|
||||
return fmt("AddedNormalized('%s' = %lld)", s.arg0.c_str(), (long long)s.iarg);
|
||||
case RAD_DEC_BYTELEVEL: return "decode ByteLevel";
|
||||
case RAD_DEC_METASPACE:
|
||||
return fmt("decode Metaspace('%s' prepend=%lld)", s.arg0.c_str(), (long long)s.iarg);
|
||||
@@ -839,7 +897,13 @@ void apply_norm(std::string& text, const TokEncoder::Step& st) {
|
||||
std::vector<uint32_t> cpts = unicode_cpts_from_utf8(text);
|
||||
std::string out;
|
||||
out.reserve(text.size());
|
||||
for (uint32_t c : cpts) out += unicode_cpt_to_utf8(unicode_tolower(c));
|
||||
/* HuggingFace lowercases a character at a time with Rust's char::to_lowercase, whose
|
||||
* one unconditional mapping to two characters is U+0130 (I with dot above) to
|
||||
* "i" U+0307; every other character maps to one. */
|
||||
for (uint32_t c : cpts) {
|
||||
if (c == 0x130) out += "i\xcc\x87";
|
||||
else out += unicode_cpt_to_utf8(unicode_tolower(c));
|
||||
}
|
||||
text.swap(out);
|
||||
break;
|
||||
}
|
||||
@@ -868,6 +932,7 @@ void apply_norm(std::string& text, const TokEncoder::Step& st) {
|
||||
}
|
||||
break;
|
||||
case RAD_NORM_PREPEND: text = s.arg0 + text; break;
|
||||
case RAD_NORM_PRECOMPILED: text = st.pmap->normalize(text); break;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1055,7 +1120,8 @@ private:
|
||||
void bpe_word(const TokEncoder& e, std::string_view w, std::vector<int32_t>& out,
|
||||
EncodeScratch& sc) {
|
||||
const bool raw = e.defer_bytelevel >= 0;
|
||||
const TokTable& table = raw ? e.raw : e.text;
|
||||
const bool eow = !e.eow.empty();
|
||||
const TokTable& table = raw ? (eow ? e.raw_eow : e.raw) : e.text;
|
||||
|
||||
/* A user-defined token is taken whole: added tokens must round-trip, and the merge table was
|
||||
* never fitted over them, so re-merging can give a different sequence.
|
||||
@@ -1065,7 +1131,9 @@ void bpe_word(const TokEncoder& e, std::string_view w, std::vector<int32_t>& out
|
||||
* different split of a rare word). The raw-byte table finds the same entry by its byte
|
||||
* spelling. A control entry is never taken whole: reaching here means the caller asked for
|
||||
* it to be read as text. */
|
||||
const int32_t whole = table.find(w);
|
||||
/* With an end-of-word suffix the whole word is its text and the suffix: `raw_eow` is keyed
|
||||
* without it, the text table with it. */
|
||||
const int32_t whole = eow && !raw ? table.find(std::string(w) + e.eow) : table.find(w);
|
||||
if (whole >= 0 && (e.types[whole] == RAD_TT_USER_DEFINED ||
|
||||
(e.ignore_merges && e.types[whole] != RAD_TT_CONTROL))) {
|
||||
out.push_back(whole);
|
||||
@@ -1083,10 +1151,13 @@ void bpe_word(const TokEncoder& e, std::string_view w, std::vector<int32_t>& out
|
||||
if (raw) {
|
||||
for (size_t i = 0; i < n; ++i)
|
||||
syms.push_back({ (uint32_t)i, 1, e.byte_sym[(unsigned char)w[i]] });
|
||||
if (eow) syms.back().id = e.byte_sym_eow[(unsigned char)w[n - 1]];
|
||||
} else {
|
||||
for (size_t i = 0; i < n; ) {
|
||||
const size_t len = std::min(unicode_len_utf8(w[i]), n - i);
|
||||
syms.push_back({ (uint32_t)i, (uint32_t)len, table.find(w.substr(i, len)) });
|
||||
syms.push_back({ (uint32_t)i, (uint32_t)len,
|
||||
eow && i + len == n ? table.find(std::string(w.substr(i, len)) + e.eow)
|
||||
: table.find(w.substr(i, len)) });
|
||||
i += len;
|
||||
}
|
||||
}
|
||||
@@ -1103,9 +1174,12 @@ void bpe_word(const TokEncoder& e, std::string_view w, std::vector<int32_t>& out
|
||||
/* Miss: decompose into byte tokens, spelt per the chain. Under ByteLevel each byte is its
|
||||
* own mapped codepoint, so the piece splits at codepoint boundaries; under byte fallback
|
||||
* a byte is "<0xNN>". */
|
||||
const bool last = s.start + s.len == n;
|
||||
if (raw) {
|
||||
for (unsigned char c : str) {
|
||||
const int32_t b = e.byte_sym[c];
|
||||
for (size_t k = 0; k < str.size(); ++k) {
|
||||
const unsigned char c = (unsigned char)str[k];
|
||||
const int32_t b = eow && last && k + 1 == str.size() ? e.byte_sym_eow[c]
|
||||
: e.byte_sym[c];
|
||||
if (b >= 0) out.push_back(b);
|
||||
else RAD_WARN("tokenizer: no token for byte-level piece '%s'",
|
||||
alphabet().to_utf8[c].c_str());
|
||||
@@ -1113,7 +1187,9 @@ void bpe_word(const TokEncoder& e, std::string_view w, std::vector<int32_t>& out
|
||||
} else if (e.bytelevel) {
|
||||
for (size_t k = 0; k < str.size(); ) {
|
||||
const size_t m = std::min(unicode_len_utf8(str[k]), str.size() - k);
|
||||
const int32_t b = e.text.find(str.substr(k, m));
|
||||
const int32_t b = eow && last && k + m == str.size()
|
||||
? e.text.find(std::string(str.substr(k, m)) + e.eow)
|
||||
: e.text.find(str.substr(k, m));
|
||||
if (b >= 0) out.push_back(b);
|
||||
else RAD_WARN("tokenizer: no token for byte-level piece '%s'",
|
||||
std::string(str.substr(k, m)).c_str());
|
||||
@@ -1142,9 +1218,13 @@ void bpe(const TokEncoder& e, const Pieces& p, std::vector<int32_t>& out, Encode
|
||||
if (w.empty()) continue;
|
||||
/* A one-byte word of a byte-level vocab is that byte's token; the lookup and the merge
|
||||
* would both land on byte_sym. A missing one takes the warning path in bpe_word. */
|
||||
if (raw && w.size() == 1 && e.byte_sym[(unsigned char)w[0]] >= 0) {
|
||||
out.push_back(e.byte_sym[(unsigned char)w[0]]);
|
||||
continue;
|
||||
if (raw && w.size() == 1) {
|
||||
const int32_t b = e.eow.empty() ? e.byte_sym[(unsigned char)w[0]]
|
||||
: e.byte_sym_eow[(unsigned char)w[0]];
|
||||
if (b >= 0) {
|
||||
out.push_back(b);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if (w.size() > WordCache::kMaxKey) { bpe_word(e, w, out, sc); continue; }
|
||||
const uint64_t h = tok_hash(w);
|
||||
@@ -1259,13 +1339,10 @@ void wordpiece(const Vocab& v, const TokEncoder& e, const Pieces& p, std::vector
|
||||
}
|
||||
}
|
||||
|
||||
/* One segment -- the text between two special tokens -- through the whole chain. `at_start`:
|
||||
* the segment begins the text (see apply_metaspace). */
|
||||
int encode_segment(const Vocab& v, const TokEncoder& e, std::string_view seg,
|
||||
std::vector<int32_t>& out, EncodeScratch& sc, WordCache& words, bool at_start) {
|
||||
/* Normalised text in `sc.p.buf` through the pre-tokenisers and the model. */
|
||||
int encode_normalized(const Vocab& v, const TokEncoder& e, std::vector<int32_t>& out,
|
||||
EncodeScratch& sc, WordCache& words, bool at_start) {
|
||||
Pieces& p = sc.p;
|
||||
p.buf.assign(seg.data(), seg.size());
|
||||
for (const TokEncoder::Step& st : e.norm) apply_norm(p.buf, st);
|
||||
if (p.buf.size() > (size_t)(UINT32_MAX / 8)) {
|
||||
RAD_ERR("tokenizer: a %zu-byte segment is past what one encode can index", p.buf.size());
|
||||
return RAD_E_INVAL;
|
||||
@@ -1302,6 +1379,12 @@ int encode_segment(const Vocab& v, const TokEncoder& e, std::string_view seg,
|
||||
case RAD_PRE_BYTE_FALLBACK:
|
||||
/* Declares how an unknown piece is encoded, not a split; bpe_word handles it. */
|
||||
break;
|
||||
case RAD_PRE_END_OF_WORD:
|
||||
/* Declares how a word's last symbol is spelt, not a split; bpe_word handles it. */
|
||||
break;
|
||||
case RAD_PRE_ADDED_NORMALIZED:
|
||||
/* Cut out by encode_segment before the pre-tokenisers run. */
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1323,8 +1406,45 @@ int encode_segment(const Vocab& v, const TokEncoder& e, std::string_view seg,
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* One segment -- the text between two special tokens -- through the whole chain. `at_start`:
|
||||
* the segment begins the text (see apply_metaspace). The added tokens matched in the normalised
|
||||
* text are cut out of it after the normalisers, under the same `parse_special` rule as the raw
|
||||
* ones, and each piece between them goes through the rest of the chain on its own. */
|
||||
int encode_segment(const Vocab& v, const TokEncoder& e, std::string_view seg,
|
||||
std::vector<int32_t>& out, EncodeScratch& sc, WordCache& words, bool at_start,
|
||||
bool parse_special) {
|
||||
Pieces& p = sc.p;
|
||||
p.buf.assign(seg.data(), seg.size());
|
||||
for (const TokEncoder::Step& st : e.norm) apply_norm(p.buf, st);
|
||||
if (!e.has_nspecials) return encode_normalized(v, e, out, sc, words, at_start);
|
||||
|
||||
const std::string norm = p.buf;
|
||||
std::vector<SpecialFrag> frags;
|
||||
e.nspecials.split(norm, parse_special, frags);
|
||||
for (const SpecialFrag& f : frags) {
|
||||
if (f.id >= 0) { out.push_back(f.id); continue; }
|
||||
if (f.len == 0) continue;
|
||||
p.buf.assign(norm, f.off, f.len);
|
||||
RAD_TRY(encode_normalized(v, e, out, sc, words, at_start && f.off == 0));
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
} /* namespace */
|
||||
|
||||
int vocab_normalize(const std::vector<VocabStep>& steps, std::string* text) {
|
||||
for (const VocabStep& s : steps) {
|
||||
if (!step_is_norm(s.kind)) continue;
|
||||
TokEncoder::Step st{ s, nullptr, nullptr };
|
||||
if (s.kind == RAD_NORM_REPLACE && (s.flags & 1)) {
|
||||
std::string why;
|
||||
if (TokRegex::compile(s.arg0, &st.re, &why) < 0) return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
apply_norm(*text, st);
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ================================================================== encode */
|
||||
|
||||
int Tokenizer::init(std::shared_ptr<const Vocab> v) {
|
||||
@@ -1372,14 +1492,17 @@ int Tokenizer::encode(std::string_view text, std::vector<int32_t>& out,
|
||||
/* The cache is keyed on the segment's bytes, so a segment whose ids also depend on
|
||||
* starting the text bypasses it. */
|
||||
const bool at_start = f.off == 0;
|
||||
if (!use_cache_ || seg.size() < kSegmentCacheMin || (at_start && e.prepend_first)) {
|
||||
RAD_TRY(encode_segment(*v_, e, seg, out, sc, words, at_start));
|
||||
/* A segment's ids also depend on parse_special when added tokens are matched in its
|
||||
* normalised text; the cache holds only the parse_special form. */
|
||||
if (!use_cache_ || seg.size() < kSegmentCacheMin || (at_start && e.prepend_first) ||
|
||||
(e.has_nspecials && !parse_special)) {
|
||||
RAD_TRY(encode_segment(*v_, e, seg, out, sc, words, at_start, parse_special));
|
||||
continue;
|
||||
}
|
||||
const uint64_t h = tok_hash(seg);
|
||||
if (e.cache.lookup(seg, h, out)) continue;
|
||||
const size_t start = out.size();
|
||||
RAD_TRY(encode_segment(*v_, e, seg, out, sc, words, at_start));
|
||||
RAD_TRY(encode_segment(*v_, e, seg, out, sc, words, at_start, parse_special));
|
||||
e.cache.insert(seg, h, out.data() + start, out.size() - start);
|
||||
}
|
||||
|
||||
|
||||
@@ -337,6 +337,10 @@ int vocab_serialize(const VocabBuild& in, StringSink& strings, uint64_t section_
|
||||
int vocab_deserialize(const void* file_base, uint64_t file_bytes,
|
||||
const RadVocabHeader* h, VocabBuild& out);
|
||||
|
||||
/* `text` through the normaliser steps of `steps` (the others are skipped), as the encoder runs
|
||||
* them. RAD_E_UNSUPPORTED when a Replace pattern does not compile. */
|
||||
int vocab_normalize(const std::vector<VocabStep>& steps, std::string* text);
|
||||
|
||||
/* Human-readable one-liner for a step, for --debug-graph and for the convert log. */
|
||||
std::string step_describe(const VocabStep& s);
|
||||
|
||||
|
||||
@@ -0,0 +1,210 @@
|
||||
/* tokenizer_grapheme.cpp -- extended grapheme clusters and the precompiled normaliser
|
||||
* (tokenizer_grapheme.h). */
|
||||
#include "text/tokenizer_grapheme.h"
|
||||
#include "rad_internal.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstring>
|
||||
|
||||
namespace rad {
|
||||
|
||||
namespace {
|
||||
|
||||
enum Gcb : uint32_t { kOther, kCR, kLF, kControl, kExtend, kZWJ, kRI, kPrepend, kSpacingMark,
|
||||
kL, kV, kT, kLV, kLVT };
|
||||
enum InCB : uint32_t { kInNone, kInLinker, kInConsonant, kInExtend };
|
||||
|
||||
uint32_t lookup(const ucd::GbRange* r, size_t n, uint32_t c) {
|
||||
size_t lo = 0, hi = n;
|
||||
while (lo < hi) {
|
||||
const size_t mid = (lo + hi) / 2;
|
||||
if (r[mid].last < c) lo = mid + 1;
|
||||
else hi = mid;
|
||||
}
|
||||
return lo < n && r[lo].first <= c ? r[lo].v : 0;
|
||||
}
|
||||
|
||||
uint32_t gcb(uint32_t c) { return lookup(ucd::k_gcb, ucd::k_gcb_n, c); }
|
||||
bool pict(uint32_t c) { return lookup(ucd::k_ext_pict, ucd::k_ext_pict_n, c) != 0; }
|
||||
uint32_t incb(uint32_t c) { return lookup(ucd::k_incb, ucd::k_incb_n, c); }
|
||||
|
||||
/* One codepoint off well-formed UTF-8 at `p`, its byte length in *len. A byte that starts no
|
||||
* well-formed sequence is taken alone. */
|
||||
uint32_t utf8_at(const unsigned char* p, size_t left, size_t* len) {
|
||||
const unsigned char b = p[0];
|
||||
auto cont = [&](size_t k) { return k < left && (p[k] & 0xC0) == 0x80; };
|
||||
if (b < 0x80) { *len = 1; return b; }
|
||||
if ((b & 0xE0) == 0xC0 && cont(1)) { *len = 2; return ((b & 0x1Fu) << 6) | (p[1] & 0x3Fu); }
|
||||
if ((b & 0xF0) == 0xE0 && cont(1) && cont(2)) {
|
||||
*len = 3;
|
||||
return ((b & 0x0Fu) << 12) | ((p[1] & 0x3Fu) << 6) | (p[2] & 0x3Fu);
|
||||
}
|
||||
if ((b & 0xF8) == 0xF0 && cont(1) && cont(2) && cont(3)) {
|
||||
*len = 4;
|
||||
return ((b & 0x07u) << 18) | ((p[1] & 0x3Fu) << 12) | ((p[2] & 0x3Fu) << 6) |
|
||||
(p[3] & 0x3Fu);
|
||||
}
|
||||
*len = 1;
|
||||
return 0xFFFD;
|
||||
}
|
||||
|
||||
int b64_value(char c) {
|
||||
if (c >= 'A' && c <= 'Z') return c - 'A';
|
||||
if (c >= 'a' && c <= 'z') return c - 'a' + 26;
|
||||
if (c >= '0' && c <= '9') return c - '0' + 52;
|
||||
if (c == '+') return 62;
|
||||
if (c == '/') return 63;
|
||||
return -1;
|
||||
}
|
||||
|
||||
} /* namespace */
|
||||
|
||||
/* UAX #29's rules GB3 to GB13 in their order, the lookbehind of GB9c (a conjunct's consonant,
|
||||
* linker and consonant), GB11 (an emoji ZWJ sequence) and GB12/13 (regional indicator pairs)
|
||||
* carried as state from the cluster's start, where no such sequence can be cut. */
|
||||
size_t grapheme_end(const uint32_t* cps, size_t n, size_t i) {
|
||||
uint32_t prev = gcb(cps[i]);
|
||||
/* The text so far ends in Extended_Pictographic Extend*; and did before `prev`. */
|
||||
bool ep = pict(cps[i]), ep_before = false;
|
||||
/* Regional indicators ending at `prev`. */
|
||||
int ri = prev == kRI ? 1 : 0;
|
||||
/* GB9c: 0 nothing, 1 a consonant then Extend/Linker without a linker, 2 with one. */
|
||||
int conj = 0;
|
||||
{
|
||||
const uint32_t in = incb(cps[i]);
|
||||
conj = in == kInConsonant ? 1 : 0;
|
||||
}
|
||||
size_t j = i + 1;
|
||||
for (; j < n; ++j) {
|
||||
const uint32_t c = cps[j], cur = gcb(c);
|
||||
bool join;
|
||||
if (prev == kCR && cur == kLF) join = true; /* GB3 */
|
||||
else if (prev == kControl || prev == kCR || prev == kLF) join = false; /* GB4 */
|
||||
else if (cur == kControl || cur == kCR || cur == kLF) join = false; /* GB5 */
|
||||
else if (prev == kL && (cur == kL || cur == kV || cur == kLV || cur == kLVT)) join = true;
|
||||
else if ((prev == kLV || prev == kV) && (cur == kV || cur == kT)) join = true; /* GB7 */
|
||||
else if ((prev == kLVT || prev == kT) && cur == kT) join = true; /* GB8 */
|
||||
else if (cur == kExtend || cur == kZWJ) join = true; /* GB9 */
|
||||
else if (cur == kSpacingMark) join = true; /* GB9a */
|
||||
else if (prev == kPrepend) join = true; /* GB9b */
|
||||
else if (conj == 2 && incb(c) == kInConsonant) join = true; /* GB9c */
|
||||
else if (prev == kZWJ && ep_before && pict(c)) join = true; /* GB11 */
|
||||
else if (prev == kRI && cur == kRI && (ri & 1)) join = true; /* GB12/13 */
|
||||
else join = false;
|
||||
if (!join) break;
|
||||
ep_before = ep;
|
||||
ep = pict(c) || (ep && cur == kExtend);
|
||||
ri = cur == kRI ? ri + 1 : 0;
|
||||
const uint32_t in = incb(c);
|
||||
if (in == kInConsonant) conj = 1;
|
||||
else if (in == kInLinker && conj >= 1) conj = 2;
|
||||
else if (in == kInExtend && conj >= 1) { /* kept */ }
|
||||
else conj = 0;
|
||||
prev = cur;
|
||||
}
|
||||
return j;
|
||||
}
|
||||
|
||||
/* ================================================================== the precompiled map */
|
||||
/* The charsmap is a little-endian u32 byte count of the trie, the trie's u32 units (Darts' double
|
||||
* array), then the replacement strings, each NUL-terminated. */
|
||||
int PrecompiledMap::load(std::string_view b64, std::string* why) {
|
||||
std::string raw;
|
||||
raw.reserve(b64.size() / 4 * 3);
|
||||
uint32_t acc = 0;
|
||||
int bits = 0;
|
||||
for (char ch : b64) {
|
||||
if (ch == '=') break;
|
||||
const int v = b64_value(ch);
|
||||
if (v < 0) {
|
||||
if (why) *why = "the precompiled charsmap is not base64";
|
||||
return RAD_E_FORMAT;
|
||||
}
|
||||
acc = (acc << 6) | (uint32_t)v;
|
||||
bits += 6;
|
||||
if (bits >= 8) {
|
||||
bits -= 8;
|
||||
raw.push_back((char)((acc >> bits) & 0xFF));
|
||||
}
|
||||
}
|
||||
if (raw.size() < 4) {
|
||||
if (why) *why = "the precompiled charsmap is shorter than its header";
|
||||
return RAD_E_FORMAT;
|
||||
}
|
||||
uint32_t tbytes = 0;
|
||||
std::memcpy(&tbytes, raw.data(), 4);
|
||||
if (tbytes % 4 || (size_t)tbytes > raw.size() - 4 || tbytes == 0) {
|
||||
if (why) *why = "the precompiled charsmap's trie does not fit it";
|
||||
return RAD_E_FORMAT;
|
||||
}
|
||||
trie_.resize(tbytes / 4);
|
||||
std::memcpy(trie_.data(), raw.data() + 4, tbytes);
|
||||
blob_.assign(raw.data() + 4 + tbytes, raw.size() - 4 - tbytes);
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
bool PrecompiledMap::transform(std::string_view s, std::string_view* out) const {
|
||||
auto offset = [](uint32_t u) { return (u >> 10) << ((u & (1u << 9)) >> 6); };
|
||||
auto label = [](uint32_t u) { return u & ((1u << 31) | 0xFFu); };
|
||||
auto leaf = [](uint32_t u) { return ((u >> 8) & 1u) != 0; };
|
||||
auto value = [](uint32_t u) { return u & ((1u << 31) - 1); };
|
||||
size_t pos = 0;
|
||||
uint32_t unit = trie_[0];
|
||||
pos ^= offset(unit);
|
||||
for (unsigned char c : s) {
|
||||
if (c == 0) break;
|
||||
pos ^= c;
|
||||
if (pos >= trie_.size()) return false;
|
||||
unit = trie_[pos];
|
||||
if (label(unit) != c) return false;
|
||||
pos ^= offset(unit);
|
||||
if (pos >= trie_.size()) return false;
|
||||
if (leaf(unit)) {
|
||||
const size_t at = value(trie_[pos]);
|
||||
if (at >= blob_.size()) return false;
|
||||
const size_t end = blob_.find('\0', at);
|
||||
*out = std::string_view(blob_).substr(at, (end == std::string::npos ? blob_.size()
|
||||
: end) - at);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/* HuggingFace's Precompiled::normalize: a cluster under six bytes goes whole to its shortest
|
||||
* mapped prefix's replacement when it has one; otherwise each character goes to its own, or
|
||||
* stays. */
|
||||
std::string PrecompiledMap::normalize(std::string_view text) const {
|
||||
std::vector<uint32_t> cps;
|
||||
std::vector<size_t> at;
|
||||
cps.reserve(text.size());
|
||||
at.reserve(text.size() + 1);
|
||||
const unsigned char* p = (const unsigned char*)text.data();
|
||||
for (size_t k = 0; k < text.size();) {
|
||||
size_t len = 1;
|
||||
cps.push_back(utf8_at(p + k, text.size() - k, &len));
|
||||
at.push_back(k);
|
||||
k += len;
|
||||
}
|
||||
at.push_back(text.size());
|
||||
std::string out;
|
||||
out.reserve(text.size());
|
||||
std::string_view rep;
|
||||
for (size_t i = 0; i < cps.size();) {
|
||||
const size_t e = grapheme_end(cps.data(), cps.size(), i);
|
||||
const std::string_view g = text.substr(at[i], at[e] - at[i]);
|
||||
if (g.size() < 6 && transform(g, &rep)) {
|
||||
out.append(rep);
|
||||
} else {
|
||||
for (size_t k = i; k < e; ++k) {
|
||||
const std::string_view ch = text.substr(at[k], at[k + 1] - at[k]);
|
||||
if (transform(ch, &rep)) out.append(rep);
|
||||
else out.append(ch);
|
||||
}
|
||||
}
|
||||
i = e;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
} /* namespace rad */
|
||||
@@ -0,0 +1,56 @@
|
||||
/* tokenizer_grapheme.h -- extended grapheme clusters (UAX #29) and SentencePiece's precompiled
|
||||
* normaliser, which walks its text by them.
|
||||
*
|
||||
* HuggingFace tokenizers' `Precompiled` normaliser (a SentencePiece model's `precompiled_charsmap`,
|
||||
* T5's among them) takes the text one extended grapheme cluster at a time: a cluster shorter than
|
||||
* six bytes is replaced whole by the mapping of its shortest mapped prefix, if it has one;
|
||||
* otherwise each of its characters is replaced by its own mapping or kept. The cluster
|
||||
* boundaries are therefore part of the result, and they are Unicode 16.0.0's, the version the
|
||||
* reference's segmentation crate implements (tools/gen_grapheme_ucd.py writes the tables).
|
||||
*/
|
||||
#pragma once
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <vector>
|
||||
|
||||
namespace rad {
|
||||
|
||||
namespace ucd {
|
||||
/* A run of codepoints [first, last] holding one value of a property. */
|
||||
struct GbRange { uint32_t first, last; uint32_t v; };
|
||||
/* Grapheme_Cluster_Break, values in tools/gen_grapheme_ucd.py's GCB order (0 is Other). */
|
||||
extern const GbRange k_gcb[];
|
||||
extern const size_t k_gcb_n;
|
||||
/* Extended_Pictographic (v 1). */
|
||||
extern const GbRange k_ext_pict[];
|
||||
extern const size_t k_ext_pict_n;
|
||||
/* Indic_Conjunct_Break: 1 Linker, 2 Consonant, 3 Extend (absent: None). */
|
||||
extern const GbRange k_incb[];
|
||||
extern const size_t k_incb_n;
|
||||
} /* namespace ucd */
|
||||
|
||||
/* The end of the extended grapheme cluster that starts at `cps[i]`: the index one past its last
|
||||
* codepoint. `i < n`. */
|
||||
size_t grapheme_end(const uint32_t* cps, size_t n, size_t i);
|
||||
|
||||
/* SentencePiece's precompiled character map: a double-array trie over UTF-8 source strings, each
|
||||
* leaf the offset of its NUL-terminated replacement in a string blob. */
|
||||
class PrecompiledMap {
|
||||
public:
|
||||
/* `charsmap_b64` is tokenizer.json's `precompiled_charsmap` as it stands, base64. RAD_OK, or
|
||||
* RAD_E_FORMAT with `why` for a map that does not decode or whose trie points outside it. */
|
||||
int load(std::string_view charsmap_b64, std::string* why);
|
||||
bool ready() const { return !trie_.empty(); }
|
||||
/* The normalised text, as HuggingFace's Precompiled normaliser writes it. */
|
||||
std::string normalize(std::string_view text) const;
|
||||
|
||||
private:
|
||||
/* The replacement of the shortest mapped prefix of `s`, or false when no prefix is mapped. */
|
||||
bool transform(std::string_view s, std::string_view* out) const;
|
||||
std::vector<uint32_t> trie_;
|
||||
std::string blob_;
|
||||
};
|
||||
|
||||
} /* namespace rad */
|
||||
File diff suppressed because it is too large.
Load diff
@@ -9,6 +9,7 @@
|
||||
* vocab_serialize() into the .rad's vocab section, and back.
|
||||
*/
|
||||
#include "text/tokenizer.h"
|
||||
#include "text/tokenizer_grapheme.h"
|
||||
#include "text/tokenizer_regex.h"
|
||||
#include "text/gguf.h"
|
||||
|
||||
@@ -164,6 +165,21 @@ int read_normalizer(const json& n, std::vector<VocabStep>& out, const char* orig
|
||||
out.push_back(s);
|
||||
return RAD_OK;
|
||||
}
|
||||
if (t == "Precompiled") {
|
||||
/* SentencePiece's precompiled character map (T5's), kept base64 as the file carries it
|
||||
* and decoded at load (tokenizer_grapheme.h). */
|
||||
s.kind = RAD_NORM_PRECOMPILED;
|
||||
s.arg0 = str_or(n, "precompiled_charsmap", "");
|
||||
PrecompiledMap pm;
|
||||
std::string why;
|
||||
if (s.arg0.empty() || pm.load(s.arg0, &why) < 0) {
|
||||
RAD_ERR("%s: Precompiled normalizer: %s", origin,
|
||||
s.arg0.empty() ? "no precompiled_charsmap" : why.c_str());
|
||||
return RAD_E_FORMAT;
|
||||
}
|
||||
out.push_back(s);
|
||||
return RAD_OK;
|
||||
}
|
||||
if (t == "Prepend") {
|
||||
s.kind = RAD_NORM_PREPEND;
|
||||
s.arg0 = str_or(n, "prepend", "");
|
||||
@@ -385,12 +401,10 @@ int read_model(const json& m, VocabBuild& out, const char* origin, uint64_t id_l
|
||||
if (type == "BPE") {
|
||||
out.kind = RAD_TOK_BPE;
|
||||
out.ignore_merges = bool_or(m, "ignore_merges", false);
|
||||
/* Subword affixes change what every merge produces, and dropout makes encoding random;
|
||||
* the encoder implements neither. */
|
||||
for (const char* k : { "continuing_subword_prefix", "end_of_word_suffix" }) {
|
||||
const std::string v = str_or(m, k, "");
|
||||
if (!v.empty()) return refuse_value(origin, (std::string("BPE ") + k).c_str(), v);
|
||||
}
|
||||
/* A continuation prefix changes what every merge produces, and dropout makes encoding
|
||||
* random; the encoder implements neither. */
|
||||
const std::string prefix = str_or(m, "continuing_subword_prefix", "");
|
||||
if (!prefix.empty()) return refuse_value(origin, "BPE continuing_subword_prefix", prefix);
|
||||
if (const json* d = get(m, "dropout"); d && d->is_number() && d->get<double>() > 0.0)
|
||||
return refuse_value(origin, "BPE dropout", d->dump());
|
||||
RAD_TRY(read_text_to_id("BPE"));
|
||||
@@ -434,6 +448,18 @@ int read_model(const json& m, VocabBuild& out, const char* origin, uint64_t id_l
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
|
||||
/* The end-of-word suffix (CLIP's "</w>") is a model property in tokenizer.json but a step
|
||||
* here, as byte fallback is below: it changes the symbols a word starts as. */
|
||||
if (type == "BPE") {
|
||||
const std::string eow = str_or(m, "end_of_word_suffix", "");
|
||||
if (!eow.empty()) {
|
||||
VocabStep s;
|
||||
s.kind = RAD_PRE_END_OF_WORD;
|
||||
s.arg0 = eow;
|
||||
out.steps.push_back(s);
|
||||
}
|
||||
}
|
||||
|
||||
/* Byte fallback is a model property in tokenizer.json but a step here: it changes what the
|
||||
* encoder does on a miss. */
|
||||
if (bool_or(m, "byte_fallback", false)) {
|
||||
@@ -472,12 +498,17 @@ int read_model(const json& m, VocabBuild& out, const char* origin, uint64_t id_l
|
||||
* The encoder matches an added token against the raw text, exactly as written. HuggingFace's
|
||||
* AddedToken flags each change that: `single_word` matches only between word boundaries,
|
||||
* `normalized` matches against the normalised text (the same thing when there is no normaliser),
|
||||
* and `lstrip` / `rstrip` take the whitespace beside a match into it. Most files spell out every
|
||||
* and `lstrip` / `rstrip` take the whitespace beside a match into it. A normalised token becomes a
|
||||
* RAD_PRE_ADDED_NORMALIZED step, placed first among the pre-tokenisers (so `<|StartOfText|>` under
|
||||
* a Lowercase is CLIP's `<|startoftext|>`); one whose spelling the normaliser itself changes would
|
||||
* be matched by that changed spelling, which is refused. Most files spell out every
|
||||
* flag, so a flag is refused only at a value that changes the result. lstrip and rstrip would
|
||||
* also refuse released models (Phi-3's chat markers carry rstrip), and the container has no field
|
||||
* to carry them, so they are warned about instead. */
|
||||
int read_added(const json& arr, VocabBuild& out, const char* origin, uint64_t id_limit,
|
||||
bool has_normalizer) {
|
||||
const std::vector<VocabStep>& norm) {
|
||||
const bool has_normalizer = !norm.empty();
|
||||
std::vector<VocabStep> matched_normalized;
|
||||
if (!arr.is_array()) return RAD_OK;
|
||||
std::string stripped;
|
||||
for (const json& e : arr) {
|
||||
@@ -500,14 +531,27 @@ int read_added(const json& arr, VocabBuild& out, const char* origin, uint64_t id
|
||||
const bool special = bool_or(e, "special", false);
|
||||
if (bool_or(e, "single_word", false))
|
||||
return refuse_value(origin, "added token single_word=true on", content);
|
||||
if (has_normalizer && bool_or(e, "normalized", false))
|
||||
return refuse_value(origin, "added token normalized=true (under a normalizer) on",
|
||||
content);
|
||||
if (has_normalizer && bool_or(e, "normalized", false)) {
|
||||
std::string n = content;
|
||||
if (vocab_normalize(norm, &n) != RAD_OK || n != content)
|
||||
return refuse_value(origin, "added token normalized=true (under a normalizer that "
|
||||
"changes its spelling) on", content);
|
||||
if (!content.empty()) {
|
||||
VocabStep st;
|
||||
st.kind = RAD_PRE_ADDED_NORMALIZED;
|
||||
st.arg0 = content;
|
||||
st.iarg = (int64_t)id;
|
||||
matched_normalized.push_back(st);
|
||||
}
|
||||
}
|
||||
if (bool_or(e, "lstrip", false) || bool_or(e, "rstrip", false))
|
||||
stripped += (stripped.empty() ? "" : " ") + content;
|
||||
out.tokens[id] = content;
|
||||
out.types[id] = special ? (uint8_t)RAD_TT_CONTROL : (uint8_t)RAD_TT_USER_DEFINED;
|
||||
}
|
||||
/* Ahead of the other pre-tokenisers, after the normalisers. */
|
||||
out.steps.insert(out.steps.begin() + (std::ptrdiff_t)norm.size(), matched_normalized.begin(),
|
||||
matched_normalized.end());
|
||||
if (!stripped.empty())
|
||||
RAD_WARN("%s: added tokens %s take the whitespace beside them in HuggingFace (lstrip / "
|
||||
"rstrip); this tokenizer keeps it as text, so prompts with whitespace next to "
|
||||
@@ -544,8 +588,11 @@ void read_config_json(const std::string& dir, VocabBuild& out) {
|
||||
auto it = id_of.find(text);
|
||||
return it == id_of.end() ? -1 : it->second;
|
||||
};
|
||||
out.bos = token_id("bos_token");
|
||||
out.eos = token_id("eos_token");
|
||||
/* An id the post-processor already gave (interpret_tokenizer_json) stays when the config
|
||||
* names no such token. */
|
||||
const int32_t bos = token_id("bos_token"), eos = token_id("eos_token");
|
||||
if (bos >= 0 || out.bos < 0) out.bos = bos;
|
||||
if (eos >= 0 || out.eos < 0) out.eos = eos;
|
||||
out.pad = token_id("pad_token");
|
||||
out.unk = out.unk >= 0 ? out.unk : token_id("unk_token");
|
||||
out.sep = token_id("sep_token");
|
||||
@@ -622,7 +669,7 @@ int interpret_tokenizer_json(const json& j, uint64_t id_limit, const char* origi
|
||||
out.steps.insert(out.steps.end(), dec.begin(), dec.end());
|
||||
|
||||
if (const json* a = get(j, "added_tokens"))
|
||||
RAD_TRY(read_added(*a, out, origin, id_limit, !norm.empty()));
|
||||
RAD_TRY(read_added(*a, out, origin, id_limit, norm));
|
||||
|
||||
/* The model's unknown token, by text. The encoder emits it for text no token covers, which
|
||||
* HuggingFace does too; tokenizer_config.json's unk_token, read later, agrees or is absent. */
|
||||
@@ -654,7 +701,28 @@ int interpret_tokenizer_json(const json& j, uint64_t id_limit, const char* origi
|
||||
* Only a special token before and/or after the sequence is read. The config's
|
||||
* add_bos_token / add_eos_token, read later, win where present. */
|
||||
if (const json* pp = get(j, "post_processor")) {
|
||||
if (str_or(*pp, "type", "") == "TemplateProcessing") {
|
||||
const std::string ppt = str_or(*pp, "type", "");
|
||||
/* RobertaProcessing and BertProcessing frame a sequence as `cls $A sep`; they name the
|
||||
* two tokens, which stand for BOS and EOS where the config names none (CLIP's). */
|
||||
if (ppt == "RobertaProcessing" || ppt == "BertProcessing") {
|
||||
auto framing = [&](const char* k) -> int32_t {
|
||||
const json* v = get(*pp, k);
|
||||
int32_t id = -1;
|
||||
if (!v || !v->is_array() || v->size() != 2 || !read_id((*v)[1], out.tokens.size(), &id))
|
||||
return -1;
|
||||
return id;
|
||||
};
|
||||
const int32_t cls = framing("cls"), sep = framing("sep");
|
||||
if (cls < 0 || sep < 0) {
|
||||
RAD_ERR("%s: %s names no [token, id] cls and sep in the vocabulary", origin,
|
||||
ppt.c_str());
|
||||
return RAD_E_FORMAT;
|
||||
}
|
||||
out.bos = cls;
|
||||
out.eos = sep;
|
||||
out.add_bos = out.add_eos = true;
|
||||
}
|
||||
if (ppt == "TemplateProcessing") {
|
||||
const json* single = get(*pp, "single");
|
||||
if (single && single->is_array() && !single->empty()) {
|
||||
auto special = [](const json& e) -> bool { return e.is_object() && e.contains("SpecialToken"); };
|
||||
|
||||
Reference in new issue
Block a user