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
@@ -362,6 +362,16 @@ ABI_FIELD(RadGenBatch, mode_src)
|
||||
ABI_FIELD(RadGenBatch, mode_ccu)
|
||||
ABI_FIELD(RadGenBatch, n_mode_h)
|
||||
ABI_FIELD(RadGenBatch, mode_rope_f)
|
||||
ABI_FIELD(RadGenBatch, n_aux)
|
||||
ABI_FIELD(RadGenBatch, aux_ids)
|
||||
ABI_FIELD(RadGenBatch, aux_cu)
|
||||
ABI_FIELD(RadGenBatch, sigma_prev)
|
||||
ABI_FIELD(RadGenBatch, timestep)
|
||||
ABI_FIELD(RadGenBatch, sampler)
|
||||
ABI_FIELD(RadGenBatch, step)
|
||||
ABI_FIELD(RadGenBatch, size_px)
|
||||
ABI_FIELD(RadGenBatch, entry_h)
|
||||
ABI_FIELD(RadGenBatch, tokens_h)
|
||||
ABI_STRUCT(RadGeneratorDecl)
|
||||
ABI_FIELD(RadGeneratorDecl, name)
|
||||
ABI_FIELD(RadGeneratorDecl, layout)
|
||||
@@ -403,6 +413,21 @@ ABI_FIELD(RadGeneratorDecl, pad_token)
|
||||
ABI_FIELD(RadGeneratorDecl, cfg_original)
|
||||
ABI_FIELD(RadGeneratorDecl, default_negative)
|
||||
ABI_FIELD(RadGeneratorDecl, ref_shrink_only)
|
||||
ABI_FIELD(RadGeneratorDecl, aux_max_tokens)
|
||||
ABI_FIELD(RadGeneratorDecl, sigma_grid)
|
||||
ABI_FIELD(RadGeneratorDecl, min_tokens)
|
||||
ABI_FIELD(RadGeneratorDecl, aux_tokens)
|
||||
ABI_FIELD(RadGeneratorDecl, beta_start)
|
||||
ABI_FIELD(RadGeneratorDecl, beta_end)
|
||||
ABI_FIELD(RadGeneratorDecl, train_steps)
|
||||
ABI_FIELD(RadGeneratorDecl, beta_schedule)
|
||||
ABI_FIELD(RadGeneratorDecl, zero_snr)
|
||||
ABI_FIELD(RadGeneratorDecl, samplers)
|
||||
ABI_FIELD(RadGeneratorDecl, default_sampler)
|
||||
ABI_FIELD(RadGeneratorDecl, default_scheduler)
|
||||
ABI_FIELD(RadGeneratorDecl, chunk_tokens)
|
||||
ABI_FIELD(RadGeneratorDecl, chunk_bos)
|
||||
ABI_FIELD(RadGeneratorDecl, chunk_eos)
|
||||
ABI_STRUCT(RadKVGroupBatch)
|
||||
ABI_FIELD(RadKVGroupBatch, group)
|
||||
ABI_FIELD(RadKVGroupBatch, slot_mapping)
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
/* abi_layout_table.h -- every abi/ struct's size and field offsets at RAD_ABI_VERSION 24 and
|
||||
/* abi_layout_table.h -- every abi/ struct's size and field offsets at RAD_ABI_VERSION 25 and
|
||||
* RAD_FORMAT_VER 2, as { type, field, offset, size } rows ("" is the struct itself). A snapshot
|
||||
* of the headers on x86-64 Linux, which abi_layout_test.cpp holds the layout to; regenerate it
|
||||
* from the test's printout only together with a version bump. */
|
||||
@@ -315,7 +315,7 @@
|
||||
{ "RadFuseStep", "n_p", 584, 4 },
|
||||
{ "RadFuseStep", "from", 588, 32 },
|
||||
{ "RadFuseStep", "n_from", 620, 4 },
|
||||
{ "RadGenBatch", "", 0, 320 },
|
||||
{ "RadGenBatch", "", 0, 400 },
|
||||
{ "RadGenBatch", "rows", 0, 8 },
|
||||
{ "RadGenBatch", "src", 8, 8 },
|
||||
{ "RadGenBatch", "rope", 16, 8 },
|
||||
@@ -359,7 +359,17 @@
|
||||
{ "RadGenBatch", "mode_ccu", 296, 8 },
|
||||
{ "RadGenBatch", "n_mode_h", 304, 8 },
|
||||
{ "RadGenBatch", "mode_rope_f", 312, 8 },
|
||||
{ "RadGeneratorDecl", "", 0, 296 },
|
||||
{ "RadGenBatch", "n_aux", 320, 8 },
|
||||
{ "RadGenBatch", "aux_ids", 328, 8 },
|
||||
{ "RadGenBatch", "aux_cu", 336, 8 },
|
||||
{ "RadGenBatch", "sigma_prev", 344, 8 },
|
||||
{ "RadGenBatch", "timestep", 352, 8 },
|
||||
{ "RadGenBatch", "sampler", 360, 8 },
|
||||
{ "RadGenBatch", "step", 368, 8 },
|
||||
{ "RadGenBatch", "size_px", 376, 8 },
|
||||
{ "RadGenBatch", "entry_h", 384, 8 },
|
||||
{ "RadGenBatch", "tokens_h", 392, 8 },
|
||||
{ "RadGeneratorDecl", "", 0, 376 },
|
||||
{ "RadGeneratorDecl", "name", 0, 8 },
|
||||
{ "RadGeneratorDecl", "layout", 8, 4 },
|
||||
{ "RadGeneratorDecl", "tmpl_text", 16, 8 },
|
||||
@@ -400,6 +410,21 @@
|
||||
{ "RadGeneratorDecl", "cfg_original", 276, 4 },
|
||||
{ "RadGeneratorDecl", "default_negative", 280, 8 },
|
||||
{ "RadGeneratorDecl", "ref_shrink_only", 288, 4 },
|
||||
{ "RadGeneratorDecl", "aux_max_tokens", 296, 8 },
|
||||
{ "RadGeneratorDecl", "sigma_grid", 304, 4 },
|
||||
{ "RadGeneratorDecl", "min_tokens", 308, 4 },
|
||||
{ "RadGeneratorDecl", "aux_tokens", 312, 4 },
|
||||
{ "RadGeneratorDecl", "beta_start", 320, 8 },
|
||||
{ "RadGeneratorDecl", "beta_end", 328, 8 },
|
||||
{ "RadGeneratorDecl", "train_steps", 336, 4 },
|
||||
{ "RadGeneratorDecl", "beta_schedule", 340, 4 },
|
||||
{ "RadGeneratorDecl", "zero_snr", 344, 4 },
|
||||
{ "RadGeneratorDecl", "samplers", 348, 4 },
|
||||
{ "RadGeneratorDecl", "default_sampler", 352, 4 },
|
||||
{ "RadGeneratorDecl", "default_scheduler", 356, 4 },
|
||||
{ "RadGeneratorDecl", "chunk_tokens", 360, 4 },
|
||||
{ "RadGeneratorDecl", "chunk_bos", 364, 4 },
|
||||
{ "RadGeneratorDecl", "chunk_eos", 368, 4 },
|
||||
{ "RadKVGroupBatch", "", 0, 72 },
|
||||
{ "RadKVGroupBatch", "group", 0, 4 },
|
||||
{ "RadKVGroupBatch", "slot_mapping", 8, 8 },
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
*
|
||||
* Checked: a C translation unit (abi_c_test.c, strict C11) lays every struct out as C++ does; every
|
||||
* struct's listed fields account for its size, so the list in abi_layout_rows.h is complete; and
|
||||
* the layout agrees with the table below, taken at RAD_ABI_VERSION 24 and RAD_FORMAT_VER 2. Under
|
||||
* the layout agrees with the table below, taken at RAD_ABI_VERSION 25 and RAD_FORMAT_VER 2. Under
|
||||
* those versions a listed field may not move or change size, an ABI struct may only grow by fields
|
||||
* past its old end, and an on-disk struct may not change at all. The table is a snapshot of the
|
||||
* headers: nothing else states the layout. When it disagrees the test prints the live table.
|
||||
@@ -57,8 +57,8 @@ std::vector<Row> cpp_rows() {
|
||||
};
|
||||
}
|
||||
|
||||
/* The layout at RAD_ABI_VERSION 24 / RAD_FORMAT_VER 2 (see the file header). */
|
||||
constexpr uint32_t kTableAbi = 24, kTableFormat = 2;
|
||||
/* The layout at RAD_ABI_VERSION 25 / RAD_FORMAT_VER 2 (see the file header). */
|
||||
constexpr uint32_t kTableAbi = 25, kTableFormat = 2;
|
||||
const AbiRow kTable[] = {
|
||||
#include "abi_layout_table.h"
|
||||
};
|
||||
|
||||
@@ -128,6 +128,12 @@ struct RadBuilder {
|
||||
RadGeneratorDecl generator{};
|
||||
std::string generator_name;
|
||||
|
||||
/* Adapter key names (rad_lora_root, rad_lora_alias): (native, spellings), and each alias as
|
||||
* (native, from, to, from_lo, from_hi, to_lo). */
|
||||
std::vector<std::pair<std::string, std::string>> lora_roots;
|
||||
struct LoraAliasRec { std::string native, from, to; int64_t from_lo, from_hi, to_lo; };
|
||||
std::vector<LoraAliasRec> lora_aliases;
|
||||
|
||||
/* What rad_weight_encoding answers: the first entry whose key the source name contains. Empty
|
||||
* means no model, so every weight is plain in its declared dtype. */
|
||||
std::vector<std::pair<std::string, RadEncoding>> encs;
|
||||
@@ -269,6 +275,19 @@ extern "C" int rad_declare_generator(RadBuilder* b, const RadGeneratorDecl* d) {
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* Recorded: a generator's adapter key names. */
|
||||
extern "C" int rad_lora_root(RadBuilder* b, const char* native, const char* spellings) {
|
||||
if (!b || !native || !*native) return RAD_E_INVAL;
|
||||
b->lora_roots.push_back({ native, spellings ? spellings : "" });
|
||||
return RAD_OK;
|
||||
}
|
||||
extern "C" 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 || !native || !from || !to) return RAD_E_INVAL;
|
||||
b->lora_aliases.push_back({ native, from, to, from_lo, from_hi, to_lo });
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* Recorded: gemma4's prefill overlap names the buffers its second lane reduces in place. */
|
||||
extern "C" int rad_buf_concurrent(RadBuilder* b, rad_buf buf) {
|
||||
if (!b || !buf) return RAD_E_INVAL;
|
||||
@@ -482,6 +501,8 @@ extern "C" int rad_memset_async(void* dst, int value, int64_t bytes, RadStream s
|
||||
#include "../arch/embgemma2/embgemma2.cpp"
|
||||
/* Qwen-Image 2.1: a generator conditioned by Qwen3-VL. */
|
||||
#include "../arch/qwenimage21/qwenimage21.cpp"
|
||||
/* Anima: a cross-attention generator conditioned through two tokenizers. */
|
||||
#include "../arch/anima/anima.cpp"
|
||||
/* GLM-5.3-Flash: its connection, router, attention and cache blocks, and the plugin. */
|
||||
#include <arch/rad_block_mhc.h>
|
||||
#include <arch/rad_block_glm_router.h>
|
||||
@@ -8428,6 +8449,30 @@ TEST(qwenimage21_declares_a_generator_with_one_shared_modulation) {
|
||||
|
||||
/* Every collective follows --tp-wire: exact unless the lossy wire was accepted, and the floor
|
||||
* under which a message stays exact is the deployment's. */
|
||||
/* The DiT's adapter names: one root before any GEMM, and every alias lands on a checkpoint tensor
|
||||
* the plugin maps, with the gate half of ComfyUI's `gate_up` on `gate_layer`. */
|
||||
TEST(qwenimage21_names_its_adapter_keys_onto_mapped_tensors) {
|
||||
MetaKV mk = qimg_meta();
|
||||
RadBuilder b;
|
||||
const RadBuildCtx ctx = qimg_ctx(0, 1);
|
||||
REQUIRE_EQ(qwenimage21::declare(&b, mk.meta(), &ctx), RAD_OK);
|
||||
REQUIRE_EQ(b.lora_roots.size(), (size_t)1);
|
||||
CHECK_EQ(b.lora_roots[0].first, std::string("transformer."));
|
||||
CHECK(b.lora_roots[0].second.find("lora_unet_") != std::string::npos);
|
||||
std::set<std::string> srcs;
|
||||
for (const RecMap& m : b.maps) for (const std::string& x : m.src) srcs.insert(x);
|
||||
REQUIRE_EQ(b.lora_aliases.size(), (size_t)2);
|
||||
for (const auto& a : b.lora_aliases) {
|
||||
std::string to = a.native + a.to;
|
||||
const size_t h = to.find('#');
|
||||
if (h != std::string::npos) to.replace(h, 1, "0");
|
||||
CHECK(srcs.count(to + ".weight"));
|
||||
}
|
||||
CHECK(b.lora_aliases[0].to.find("gate_layer") != std::string::npos);
|
||||
CHECK_EQ(b.lora_aliases[0].from_lo, (int64_t)0);
|
||||
CHECK_EQ(b.lora_aliases[1].from_lo, b.lora_aliases[0].from_hi);
|
||||
}
|
||||
|
||||
TEST(qwenimage21_collectives_follow_the_tp_wire) {
|
||||
MetaKV mk = qimg_meta();
|
||||
for (int lossy : { 0, 1 }) {
|
||||
@@ -8473,6 +8518,314 @@ TEST(qwenimage21_generator_passes_lint_clean) {
|
||||
}
|
||||
}
|
||||
|
||||
/* ==================================================================== anima */
|
||||
|
||||
namespace {
|
||||
|
||||
/* Anima's text encoder (Qwen3-0.6B-Base) as the container's config states it; the DiT, adapter
|
||||
* and VAE are the plugin's own constants. */
|
||||
MetaKV anima_meta(const char* variant) {
|
||||
RadModelMeta m{};
|
||||
m.arch_id = "anima"; m.name = "test-anima"; m.quant = "";
|
||||
m.n_layers = 28; m.n_embd = 1024; m.n_head = 16; m.n_head_kv = 8; m.head_dim = 128;
|
||||
m.n_ff = 3072; m.n_vocab = 151936; m.n_ctx_train = 32768;
|
||||
m.rms_eps = 1e-6f; m.rope_theta = 1e6f; m.rope_scale = 1.0f;
|
||||
MetaKV k(m);
|
||||
k.set("num_hidden_layers", "28").set("hidden_size", "1024").set("anima.variant", variant);
|
||||
return k;
|
||||
}
|
||||
|
||||
RadBuildCtx anima_ctx() {
|
||||
RadBuildCtx c = build_ctx(0, 1);
|
||||
c.max_tok = 2 * (4096 + 512);
|
||||
c.max_seqs = 4;
|
||||
return c;
|
||||
}
|
||||
|
||||
/* A JOINT_STEP pass as the driver lays one out for Anima: COND over a prompt of `nq` Qwen3 tokens
|
||||
* (padded to 512) and `nt` T5 ids, DENOISE over `entries` entries of 512 context rows and `ni`
|
||||
* image rows each, or DECODE of a 64 x 64 picture. */
|
||||
struct AnimaKit {
|
||||
std::vector<int32_t> tok, pos, cu, src, lane, flags, pair, aux, aux_cu, valid_cu;
|
||||
std::vector<int32_t> img_cu, img_rows, mode_cu, mode_rows, mode_src, mode_ccu;
|
||||
std::vector<int64_t> n_mode;
|
||||
std::vector<uint32_t> seed;
|
||||
std::vector<float> sigma, sigma_next, cfg, rope_f, mode_rope_f;
|
||||
RadGenBatch g{};
|
||||
RadBatch b{};
|
||||
};
|
||||
|
||||
std::unique_ptr<AnimaKit> anima_pass(int pass, int64_t nq = 12, int64_t nt = 9, int64_t ni = 16,
|
||||
int64_t entries = 1) {
|
||||
auto k = std::make_unique<AnimaKit>();
|
||||
RadGenBatch& g = k->g;
|
||||
RadBatch& b = k->b;
|
||||
b.gen = pass;
|
||||
b.gen_b = &k->g;
|
||||
if (pass == RAD_GEN_PASS_COND) {
|
||||
for (int64_t i = 0; i < 512; ++i) {
|
||||
k->tok.push_back(i < nq ? (int32_t)(100 + i) : 151643);
|
||||
k->pos.push_back(i < nq ? (int32_t)i : 1);
|
||||
}
|
||||
for (int64_t i = 0; i < nt; ++i) k->aux.push_back((int32_t)(3 + i));
|
||||
k->aux_cu = { 0, (int32_t)nt };
|
||||
k->valid_cu = { 0, (int32_t)nq };
|
||||
k->cu = { 0, 512 };
|
||||
k->lane = { 0, 1 };
|
||||
k->sigma = { 0.0f };
|
||||
b.n_tok = 512;
|
||||
b.n_seq = 1;
|
||||
b.token_ids = k->tok.data();
|
||||
b.positions = k->pos.data();
|
||||
b.cu_seqlens = k->cu.data();
|
||||
g.rows = 512;
|
||||
g.n_pad = (int32_t)(512 - nq);
|
||||
g.valid_cu = k->valid_cu.data();
|
||||
g.n_lane = 2;
|
||||
g.lane = k->lane.data();
|
||||
g.lane_h = k->lane.data();
|
||||
g.branch = 1;
|
||||
g.sigma = k->sigma.data();
|
||||
g.n_aux = nt;
|
||||
g.aux_ids = k->aux.data();
|
||||
g.aux_cu = k->aux_cu.data();
|
||||
return k;
|
||||
}
|
||||
if (pass == RAD_GEN_PASS_DECODE) {
|
||||
k->cu = { 0, 16 };
|
||||
b.n_tok = 16;
|
||||
b.n_seq = 1;
|
||||
b.cu_seqlens = k->cu.data();
|
||||
g.dec_lane = 1;
|
||||
g.dec_height = g.dec_width = 64;
|
||||
return k;
|
||||
}
|
||||
const int64_t S = entries, N = S * (512 + ni);
|
||||
k->cu.push_back(0);
|
||||
k->img_cu.push_back(0);
|
||||
for (int64_t s = 0; s < S; ++s) {
|
||||
k->mode_cu.push_back((int32_t)(s * (512 + ni)));
|
||||
k->mode_cu.push_back((int32_t)(s * (512 + ni) + 512));
|
||||
k->mode_cu.push_back((int32_t)(s * (512 + ni) + 512));
|
||||
for (int64_t r = 0; r < 512; ++r) k->src.push_back((int32_t)(s * 512 + r));
|
||||
for (int64_t r = 0; r < ni; ++r) {
|
||||
k->src.push_back((int32_t)(-1 - (s * ni + r)));
|
||||
k->img_rows.push_back((int32_t)(s * (512 + ni) + 512 + r));
|
||||
}
|
||||
k->cu.push_back((int32_t)((s + 1) * (512 + ni)));
|
||||
k->img_cu.push_back((int32_t)((s + 1) * ni));
|
||||
k->lane.push_back((int32_t)(s / 2));
|
||||
k->pair.push_back(S > 1 ? (s % 2 ? -2 : (int32_t)(s + 1)) : -1);
|
||||
}
|
||||
k->mode_cu.push_back((int32_t)N);
|
||||
for (int64_t s = 0; s < S; ++s)
|
||||
for (int64_t r = 0; r < 512; ++r) {
|
||||
k->mode_rows.push_back((int32_t)(s * (512 + ni) + r));
|
||||
k->mode_src.push_back((int32_t)(s * 512 + r));
|
||||
}
|
||||
for (int64_t s = 0; s < S; ++s)
|
||||
for (int64_t r = 0; r < ni; ++r) {
|
||||
k->mode_rows.push_back((int32_t)(s * (512 + ni) + 512 + r));
|
||||
k->mode_src.push_back((int32_t)(-1 - (s * ni + r)));
|
||||
}
|
||||
k->n_mode = { 512 * S, 0, ni * S };
|
||||
for (int m = 0; m < 3; ++m)
|
||||
for (int64_t s = 0; s <= S; ++s)
|
||||
k->mode_ccu.push_back((int32_t)(s * (m == 0 ? 512 : m == 1 ? 0 : ni)));
|
||||
k->rope_f.assign((size_t)(4 * N), 0.0f);
|
||||
k->mode_rope_f.assign((size_t)(4 * N), 0.0f);
|
||||
k->tok.assign((size_t)N, 0);
|
||||
k->pos.assign((size_t)N, 0);
|
||||
k->sigma.assign((size_t)S, 0.75f);
|
||||
k->sigma_next.assign((size_t)S, 0.5f);
|
||||
k->cfg.assign((size_t)S, 4.0f);
|
||||
k->flags.assign((size_t)S, RAD_GEN_F_FIRST);
|
||||
k->seed.assign((size_t)(2 * S), 7u);
|
||||
b.n_tok = N;
|
||||
b.n_seq = S;
|
||||
b.token_ids = k->tok.data();
|
||||
b.positions = k->pos.data();
|
||||
b.cu_seqlens = k->cu.data();
|
||||
g.src = k->src.data();
|
||||
g.n_img = ni * S;
|
||||
g.img_cu = k->img_cu.data();
|
||||
g.img_rows = k->img_rows.data();
|
||||
g.mode_cu = k->mode_cu.data();
|
||||
g.rope_f = k->rope_f.data();
|
||||
g.mode_rows = k->mode_rows.data();
|
||||
g.mode_src = k->mode_src.data();
|
||||
g.mode_ccu = k->mode_ccu.data();
|
||||
g.n_mode_h = k->n_mode.data();
|
||||
g.mode_rope_f = k->mode_rope_f.data();
|
||||
g.sigma = k->sigma.data();
|
||||
g.sigma_next = k->sigma_next.data();
|
||||
g.cfg = k->cfg.data();
|
||||
g.pair = k->pair.data();
|
||||
g.lane = k->lane.data();
|
||||
g.lane_dh = k->lane.data();
|
||||
g.flags = k->flags.data();
|
||||
g.seed = k->seed.data();
|
||||
return k;
|
||||
}
|
||||
|
||||
/* The linears a LoRA for Anima names: every DiT block's attention, MLP and modulation linears
|
||||
* and the text encoder's. */
|
||||
bool anima_lora_target(const std::string& w) {
|
||||
for (const char* t : { "attn_qkv", "attn_output", "cross_q", "cross_k", "cross_v",
|
||||
"cross_output", "mlp_layer1", "mlp_layer2", ".mod_", "ffn_gate_up",
|
||||
"ffn_down" })
|
||||
if (has(w, t) && !has(w, ".scale")) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
} /* namespace */
|
||||
|
||||
/* A JOINT_STEP generator that reads a second tokenizer, pads an empty prompt to one token and
|
||||
* samples on ComfyUI's simple schedule; the variant sets its defaults and the DiT keys' prefix is
|
||||
* the checkpoint's, `model.diffusion_model.` here and `net.` for Base. */
|
||||
TEST(anima_declares_a_two_tokenizer_generator_under_the_checkpoints_prefix) {
|
||||
const RadEncoding plain = rad_enc_plain(RAD_BF16);
|
||||
RadBuildCtx ctx = anima_ctx();
|
||||
MetaKV mk = anima_meta("aesthetic");
|
||||
RadBuilder b;
|
||||
b.encs = { { "dit.t_norm.mdm", plain }, { "dit.blk.0.attn_qkv", plain } };
|
||||
REQUIRE_EQ(anima::declare(&b, mk.meta(), &ctx), RAD_OK);
|
||||
CHECK_EQ(b.logits, (rad_buf)0);
|
||||
CHECK_EQ(b.generator_name, std::string("anima-aesthetic"));
|
||||
const RadGeneratorDecl& d = b.generator;
|
||||
CHECK_EQ(d.layout, (int32_t)RAD_GEN_LAYOUT_JOINT_STEP);
|
||||
CHECK_EQ(d.aux_tokens, 1);
|
||||
CHECK_EQ(d.aux_max_tokens, (int64_t)512);
|
||||
CHECK_EQ(d.min_tokens, 1);
|
||||
CHECK_EQ(d.pad_multiple, 512);
|
||||
CHECK_EQ(d.cond_rows, (int64_t)512);
|
||||
CHECK_EQ(d.sigma_grid, 1000);
|
||||
CHECK_EQ(d.shift, 3.0);
|
||||
CHECK_EQ(d.dyn_shift, 0);
|
||||
CHECK_EQ(d.cfg_original, 0);
|
||||
CHECK_EQ(d.default_steps, (int64_t)30);
|
||||
CHECK_EQ(d.default_cfg, 4.0);
|
||||
CHECK_EQ(d.latent_channels, (int64_t)64);
|
||||
CHECK(b.kv_groups.empty());
|
||||
const RecMap* q = find_map(b, "dit.blk.27.attn_qkv.weight");
|
||||
REQUIRE(q != nullptr);
|
||||
REQUIRE_EQ(q->src.size(), (size_t)3);
|
||||
CHECK_EQ(q->src[0], std::string("model.diffusion_model.blocks.27.self_attn.q_proj.weight"));
|
||||
const RecMap* te = find_map(b, "te.blk.3.ffn_gate_up.weight");
|
||||
REQUIRE(te != nullptr);
|
||||
CHECK_EQ(te->src[1], std::string("model.layers.3.mlp.up_proj.weight"));
|
||||
/* The patch embedding over its first 64 columns, the final linear's rows in eight pieces. */
|
||||
const RecMap* xe = find_map(b, "dit.x_embed.weight");
|
||||
REQUIRE(xe != nullptr);
|
||||
CHECK_EQ(xe->mode, (int)RAD_MAP_COLS);
|
||||
int final_maps = 0;
|
||||
for (const auto& m : b.maps)
|
||||
if (m.declared == "dit.final.weight") { ++final_maps; CHECK_EQ(m.mode, (int)RAD_MAP_ROWS); }
|
||||
CHECK_EQ(final_maps, 8);
|
||||
/* The DiT's rotary: 22, 21 and 21 pairs, NeoX, over (frame, row, column). */
|
||||
int axial = 0;
|
||||
for (const auto& o : b.ops)
|
||||
if (o.op == "qk_norm_rope" && pstr(&o, "mode") == "axial") {
|
||||
CHECK_EQ(pstr(&o, "sections"), std::string("22 21 21"));
|
||||
++axial;
|
||||
}
|
||||
CHECK_EQ(axial, 28);
|
||||
|
||||
MetaKV turbo = anima_meta("turbo");
|
||||
RadBuilder bt;
|
||||
bt.encs = { { "dit.t_norm.mdm", plain } };
|
||||
REQUIRE_EQ(anima::declare(&bt, turbo.meta(), &ctx), RAD_OK);
|
||||
CHECK_EQ(bt.generator_name, std::string("anima-turbo"));
|
||||
CHECK_EQ(bt.generator.default_steps, (int64_t)10);
|
||||
CHECK_EQ(bt.generator.default_cfg, 1.0);
|
||||
|
||||
MetaKV base = anima_meta("base");
|
||||
RadBuilder bb;
|
||||
bb.encs = { { "dit.t_norm.net", plain } };
|
||||
REQUIRE_EQ(anima::declare(&bb, base.meta(), &ctx), RAD_OK);
|
||||
const RecMap* nq = find_map(bb, "dit.blk.0.mlp_layer1.weight");
|
||||
REQUIRE(nq != nullptr);
|
||||
CHECK_EQ(nq->src[0], std::string("net.blocks.0.mlp.layer1.weight"));
|
||||
|
||||
/* Neither spelling, or an unknown variant, is refused. */
|
||||
RadBuilder none;
|
||||
CHECK(anima::declare(&none, mk.meta(), &ctx) < 0);
|
||||
MetaKV odd = anima_meta("deluxe");
|
||||
RadBuilder bo;
|
||||
bo.encs = { { "dit.t_norm.mdm", plain } };
|
||||
CHECK(anima::declare(&bo, odd.meta(), &ctx) < 0);
|
||||
}
|
||||
|
||||
/* Every linear a LoRA for Anima names is read by a plain GEMM a runtime LoRA can follow: gemm_nt
|
||||
* in a bf16 container, gemm_nt_q without rotated parts in a block-fp8 one, its activation a
|
||||
* separate op. */
|
||||
TEST(anima_lora_targets_are_plain_gemms) {
|
||||
const RadEncoding plain = rad_enc_plain(RAD_BF16);
|
||||
const auto fp8 = rad_enc_affine(RAD_F8E4M3, RAD_BF16, 128, 128);
|
||||
RadBuildCtx ctx = anima_ctx();
|
||||
MetaKV mk = anima_meta("base");
|
||||
for (bool q : { false, true }) {
|
||||
RadBuilder b;
|
||||
b.encs = { { "dit.t_norm.net", plain } };
|
||||
if (!q) b.encs.push_back({ "dit.blk.0.attn_qkv", plain });
|
||||
if (q)
|
||||
for (const char* t : { "attn_qkv", "attn_output", "cross_q", "cross_k", "cross_v",
|
||||
"cross_output", "mlp_layer1", "mlp_layer2", "ffn_gate_up",
|
||||
"ffn_down" })
|
||||
b.encs.push_back({ t, fp8 });
|
||||
REQUIRE_EQ(anima::declare(&b, mk.meta(), &ctx), RAD_OK);
|
||||
int targets = 0;
|
||||
for (const auto& o : b.ops)
|
||||
for (rad_weight w : o.w) {
|
||||
const std::string& n = b.weights[w - 1].name;
|
||||
if (!anima_lora_target(n)) continue;
|
||||
++targets;
|
||||
const bool ok = o.op == "gemm_nt" || (q && o.op == "gemm_nt_q" &&
|
||||
pint(&o, "pb1") <= 0 && pint(&o, "pb2") <= 0);
|
||||
if (!ok) fprintf(stderr, " '%s' read by %s\n", n.c_str(), o.op.c_str());
|
||||
CHECK(ok);
|
||||
CHECK(o.op != "gemm_nt_bias");
|
||||
}
|
||||
/* 28 blocks of 8 linears (two views a block-fp8 one) and 6 modulation linears; 28 text
|
||||
* encoder layers of 4. */
|
||||
CHECK(targets >= 28 * (8 + 6) + 28 * 4);
|
||||
}
|
||||
}
|
||||
|
||||
/* The three passes the core drives (a conditioning with its T5 ids, denoising one image or a
|
||||
* guided pair, decoding one) lint clean in a bf16 and a block-fp8 container. */
|
||||
TEST(anima_generator_passes_lint_clean) {
|
||||
const RadEncoding plain = rad_enc_plain(RAD_BF16);
|
||||
const auto fp8 = rad_enc_affine(RAD_F8E4M3, RAD_BF16, 128, 128);
|
||||
RadBuildCtx ctx = anima_ctx();
|
||||
MetaKV mk = anima_meta("aesthetic");
|
||||
for (bool q : { false, true }) {
|
||||
RadBuilder b;
|
||||
b.encs = { { "dit.t_norm.mdm", plain } };
|
||||
if (!q) b.encs.push_back({ "dit.blk.0.attn_qkv", plain });
|
||||
if (q) b.encs.push_back({ "attn_qkv", fp8 }), b.encs.push_back({ "attn_output", fp8 }),
|
||||
b.encs.push_back({ "cross_", fp8 }), b.encs.push_back({ "mlp_layer", fp8 }),
|
||||
b.encs.push_back({ "ffn_", fp8 });
|
||||
REQUIRE_EQ(anima::declare(&b, mk.meta(), &ctx), RAD_OK);
|
||||
for (const auto& k : { anima_pass(RAD_GEN_PASS_COND, 12, 9),
|
||||
anima_pass(RAD_GEN_PASS_COND, 3, 40),
|
||||
anima_pass(RAD_GEN_PASS_DENOISE, 12, 9, 16, 1),
|
||||
anima_pass(RAD_GEN_PASS_DENOISE, 12, 9, 16, 2),
|
||||
anima_pass(RAD_GEN_PASS_DECODE) }) {
|
||||
RadCtx c{ .b = &b, .batch = &k->b, .rank = 0, .world = 1 };
|
||||
anima::step(&c, &k->b);
|
||||
CHECK(c.step_fail.empty());
|
||||
if (!c.step_fail.empty()) fprintf(stderr, " %s\n", c.step_fail.c_str());
|
||||
CHECK(!c.issues.empty());
|
||||
CHECK_LINT(b, &c);
|
||||
}
|
||||
const auto tok = kit(b, { 1 }, {});
|
||||
RadCtx c{ .b = &b, .batch = &tok->b, .rank = 0, .world = 1 };
|
||||
anima::step(&c, &tok->b);
|
||||
CHECK(!c.step_fail.empty());
|
||||
}
|
||||
}
|
||||
|
||||
/* ======================================================== the conventional vocabulary */
|
||||
|
||||
namespace {
|
||||
|
||||
@@ -180,6 +180,78 @@ TEST(a_plain_tensor_is_its_own_encoding_and_reads_back_as_itself) {
|
||||
CHECK_EQ(std::memcmp(raw.data(), (const uint8_t*)ck.find("a.weight")->data + 32, 16), 0);
|
||||
}
|
||||
|
||||
/* A single-file SDXL checkpoint (Stability's sgm layout) is read under the names its adapters use:
|
||||
* the UNet and CLIP ViT-L as they are, OpenCLIP bigG in transformers' names with its fused
|
||||
* in_proj split into q/k/v rows and its (in, out) text_projection transposed, the VAE decoder in
|
||||
* diffusers' names with up blocks counted the other way, a v_pred marker as the prediction type,
|
||||
* and bigG's dimensions as the model's. */
|
||||
TEST(a_single_file_sdxl_checkpoint_is_read_in_its_adapters_names) {
|
||||
const std::string g = "conditioner.embedders.1.model.";
|
||||
T proj{ g + "text_projection", "F32", { 2, 3 }, {} };
|
||||
proj.bytes.resize(6 * 4);
|
||||
for (int i = 0; i < 6; ++i) rad_store_f32(proj.bytes.data(), RAD_F32, i, (float)i);
|
||||
const std::string dir = fresh_dir();
|
||||
const std::string file = dir + "/sdxl.safetensors";
|
||||
write_shard(file, {
|
||||
bf16("model.diffusion_model.label_emb.0.0.weight", { 2, 4 }, 1.0f),
|
||||
bf16("conditioner.embedders.0.transformer.text_model.final_layer_norm.weight", { 4 }, 2.0f),
|
||||
bf16(g + "transformer.resblocks.3.attn.in_proj_weight", { 6, 4 }, 0.0f),
|
||||
bf16(g + "transformer.resblocks.3.attn.in_proj_bias", { 6 }, 0.0f),
|
||||
bf16(g + "transformer.resblocks.3.mlp.c_fc.weight", { 8, 4 }, 3.0f),
|
||||
bf16(g + "transformer.resblocks.3.ln_2.bias", { 4 }, 4.0f),
|
||||
bf16(g + "ln_final.weight", { 4 }, 5.0f),
|
||||
bf16(g + "token_embedding.weight", { 16, 4 }, 0.0f),
|
||||
bf16(g + "transformer.resblocks.0.ln_1.weight", { 4 }, 0.0f),
|
||||
bf16(g + "transformer.resblocks.0.mlp.c_fc.weight", { 8, 4 }, 0.0f),
|
||||
bf16(g + "positional_embedding", { 77, 4 }, 6.0f),
|
||||
proj,
|
||||
bf16("first_stage_model.decoder.up.0.block.2.nin_shortcut.weight", { 4, 8, 1, 1 }, 7.0f),
|
||||
bf16("first_stage_model.decoder.up.3.upsample.conv.bias", { 4 }, 8.0f),
|
||||
bf16("first_stage_model.decoder.mid.attn_1.proj_out.weight", { 4, 4, 1, 1 }, 9.0f),
|
||||
bf16("first_stage_model.encoder.conv_in.weight", { 4, 3, 3, 3 }, 10.0f),
|
||||
T{ "v_pred", "F32", { 0 }, {} },
|
||||
});
|
||||
Checkpoint ck;
|
||||
REQUIRE_EQ(ck.open(file), RAD_OK);
|
||||
CHECK_EQ(ck.meta().arch, std::string("sdxl"));
|
||||
REQUIRE(ck.meta().get("sdxl.prediction") != nullptr);
|
||||
CHECK_EQ(std::string(ck.meta().get("sdxl.prediction")), std::string("v"));
|
||||
/* The typed dimensions are bigG's: its width, vocabulary and feed-forward off its tensors,
|
||||
* its layers counted from 0 while they run on. */
|
||||
CHECK_EQ(ck.meta().m.n_embd, (int64_t)4);
|
||||
CHECK_EQ(ck.meta().m.n_vocab, (int64_t)16);
|
||||
CHECK_EQ(ck.meta().m.n_ff, (int64_t)8);
|
||||
CHECK_EQ(ck.meta().m.n_layers, (int64_t)1);
|
||||
CHECK(ck.find("model.diffusion_model.label_emb.0.0.weight") != nullptr);
|
||||
CHECK(ck.find("conditioner.embedders.0.transformer.text_model.final_layer_norm.weight") != nullptr);
|
||||
const std::string t = "conditioner.embedders.1.transformer.";
|
||||
const std::string l = t + "text_model.encoder.layers.3.";
|
||||
const SrcTensor* q = ck.find(l + "self_attn.q_proj.weight");
|
||||
const SrcTensor* v = ck.find(l + "self_attn.v_proj.weight");
|
||||
const SrcTensor* vb = ck.find(l + "self_attn.v_proj.bias");
|
||||
REQUIRE(q && v && vb);
|
||||
CHECK(q->shape == std::vector<int64_t>({ 2, 4 }));
|
||||
/* v is rows 4..5 of in_proj: elements 16..23, each its index (mod 64) in bf16. */
|
||||
CHECK_EQ(rad_load_f32(v->data, RAD_BF16, 0), 16.0f);
|
||||
CHECK_EQ(rad_load_f32(vb->data, RAD_BF16, 1), 5.0f);
|
||||
CHECK(ck.find(g + "transformer.resblocks.3.attn.in_proj_weight") == nullptr);
|
||||
CHECK(ck.find(l + "mlp.fc1.weight") != nullptr);
|
||||
CHECK(ck.find(l + "layer_norm2.bias") != nullptr);
|
||||
CHECK(ck.find(t + "text_model.final_layer_norm.weight") != nullptr);
|
||||
CHECK(ck.find(t + "text_model.embeddings.position_embedding.weight") != nullptr);
|
||||
const SrcTensor* p = ck.find(t + "text_projection.weight");
|
||||
REQUIRE(p != nullptr);
|
||||
CHECK(p->shape == std::vector<int64_t>({ 3, 2 }));
|
||||
/* P^T: element (j, i) is P(i, j) = 3 i + j. */
|
||||
for (int j = 0; j < 3; ++j)
|
||||
for (int i = 0; i < 2; ++i)
|
||||
CHECK_EQ(rad_load_f32(p->data, RAD_F32, j * 2 + i), (float)(3 * i + j));
|
||||
CHECK(ck.find("vae.decoder.up_blocks.3.resnets.2.conv_shortcut.weight") != nullptr);
|
||||
CHECK(ck.find("vae.decoder.up_blocks.0.upsamplers.0.conv.bias") != nullptr);
|
||||
CHECK(ck.find("vae.decoder.mid_block.attentions.0.to_out.0.weight") != nullptr);
|
||||
CHECK(ck.find("first_stage_model.encoder.conv_in.weight") != nullptr);
|
||||
}
|
||||
|
||||
/* Block-scaled FP8 is one weight of two planes; each value is its code times the scale of the
|
||||
* block containing it along both axes. */
|
||||
TEST(block_fp8_is_the_codes_and_their_scale_plane) {
|
||||
@@ -2735,4 +2807,82 @@ TEST(a_companion_folder_is_read_under_its_name) {
|
||||
CHECK_EQ(mget("codec.decoder_config.dim"), std::string("7"));
|
||||
}
|
||||
|
||||
namespace {
|
||||
|
||||
/* A RAD_MAP_ROWS or RAD_MAP_COLS map: source k starts at index[k] and spans rows[k]. */
|
||||
RadNameMap ranged(const char* declared, int mode, std::vector<const char*> src,
|
||||
std::vector<int> index, std::vector<int64_t> rows) {
|
||||
RadNameMap m = map(declared, mode, std::move(src), std::move(index));
|
||||
for (size_t i = 0; i < rows.size(); ++i) m.src_rows[i] = rows[i];
|
||||
return m;
|
||||
}
|
||||
|
||||
} /* namespace */
|
||||
|
||||
/* A column range of the last dimension, in every leading slice; a range past the end is
|
||||
* refused. */
|
||||
TEST(a_column_range_is_those_columns_of_every_row) {
|
||||
const std::string dir = write_checkpoint({ bf16("x.weight", { 3, 5 }, 0.0f) }, kConfig);
|
||||
Checkpoint ck;
|
||||
REQUIRE_EQ(ck.open(dir), RAD_OK);
|
||||
Program prog;
|
||||
prog.name_map.push_back(ranged("xc", RAD_MAP_COLS, { "x.weight" }, { 1 }, { 3 }));
|
||||
prog.name_map.push_back(ranged("far", RAD_MAP_COLS, { "x.weight" }, { 3 }, { 3 }));
|
||||
CkptWeight w;
|
||||
std::string why;
|
||||
REQUIRE_EQ(ckpt_resolve(ck, prog, "xc", false, &w, &why), RAD_OK);
|
||||
CHECK(!w.trivial);
|
||||
REQUIRE_EQ(w.rank, (uint32_t)2);
|
||||
CHECK_EQ(w.shape[0], (int64_t)3);
|
||||
CHECK_EQ(w.shape[1], (int64_t)3);
|
||||
std::vector<float> f(9);
|
||||
REQUIRE_EQ(ckpt_rows_f32(w, 0, 3, f.data(), &why), RAD_OK);
|
||||
for (int r = 0; r < 3; ++r)
|
||||
for (int c = 0; c < 3; ++c) CHECK_EQ(f[(size_t)(r * 3 + c)], (float)(r * 5 + 1 + c));
|
||||
CHECK_EQ(ckpt_resolve(ck, prog, "far", false, &w, &why), (int)RAD_E_SHAPE);
|
||||
}
|
||||
|
||||
/* Row pieces declared over several maps of one name join in declaration order, so a permutation
|
||||
* of a weight's rows can be stated one row at a time. */
|
||||
TEST(row_pieces_over_several_maps_join_in_order) {
|
||||
const std::string dir = write_checkpoint({ bf16("w", { 4, 3 }, 0.0f) }, kConfig);
|
||||
Checkpoint ck;
|
||||
REQUIRE_EQ(ck.open(dir), RAD_OK);
|
||||
Program prog;
|
||||
prog.name_map.push_back(ranged("p", RAD_MAP_ROWS, { "w" }, { 2 }, { 1 }));
|
||||
prog.name_map.push_back(ranged("p", RAD_MAP_ROWS, { "w", "w" }, { 0, 3 }, { 1, 1 }));
|
||||
CkptWeight w;
|
||||
std::string why;
|
||||
REQUIRE_EQ(ckpt_resolve(ck, prog, "p", false, &w, &why), RAD_OK);
|
||||
CHECK_EQ(w.shape[0], (int64_t)3);
|
||||
CHECK_EQ(w.shape[1], (int64_t)3);
|
||||
std::vector<float> f(9);
|
||||
REQUIRE_EQ(ckpt_rows_f32(w, 0, 3, f.data(), &why), RAD_OK);
|
||||
const int order[3] = { 2, 0, 3 };
|
||||
for (int r = 0; r < 3; ++r)
|
||||
for (int c = 0; c < 3; ++c) CHECK_EQ(f[(size_t)(r * 3 + c)], (float)(order[r] * 3 + c));
|
||||
}
|
||||
|
||||
/* A release split into single files merges them under their own names; a name two files share
|
||||
* is refused. The metadata and tokenizer come from the directory set before open(). */
|
||||
TEST(single_files_merge_by_name_and_read_their_metadata_elsewhere) {
|
||||
const std::string dir = fresh_dir();
|
||||
write_shard(dir + "/dit.safetensors", { bf16("net.a", { 2, 2 }, 1.0f) });
|
||||
write_shard(dir + "/te.safetensors", { bf16("model.b", { 2, 2 }, 2.0f) });
|
||||
write_shard(dir + "/dup.safetensors", { bf16("net.a", { 2, 2 }, 3.0f) });
|
||||
const std::string meta = fresh_dir();
|
||||
write_file(meta + "/config.json", "{\"model_type\":\"qwen3\",\"hidden_size\":64}");
|
||||
write_file(meta + "/tokenizer.json", "{}");
|
||||
Checkpoint ck;
|
||||
ck.set_meta_dir(meta);
|
||||
REQUIRE_EQ(ck.open(dir + "/dit.safetensors"), RAD_OK);
|
||||
REQUIRE_EQ(ck.add_file(dir + "/te.safetensors"), RAD_OK);
|
||||
CHECK(ck.find("net.a") != nullptr);
|
||||
CHECK(ck.find("model.b") != nullptr);
|
||||
CHECK(ck.add_file(dir + "/dup.safetensors") < 0);
|
||||
const char* mt = ck.meta().get("model_type");
|
||||
CHECK_EQ(std::string(mt ? mt : ""), std::string("qwen3"));
|
||||
CHECK_EQ(ck.tok_dir(), meta);
|
||||
}
|
||||
|
||||
RAD_TEST_MAIN()
|
||||
+14
-3
@@ -22,6 +22,7 @@
|
||||
#include <sstream>
|
||||
#include <cstdio>
|
||||
#include <string>
|
||||
#include <sys/stat.h>
|
||||
#include <unistd.h>
|
||||
#include <cstring>
|
||||
#include <vector>
|
||||
@@ -129,7 +130,8 @@ TEST(the_kl_mode_records_or_scores_and_says_which_input_it_lacks) {
|
||||
|
||||
/* Runtime LoRA: the adapters reach their fields in order, the targets as sorted leaf names, and a
|
||||
* combination that would size slots no adapter uses, or name an adapter that is not served, is
|
||||
* refused by name. */
|
||||
* refused by name. A text model's slot count against its adapters, and its targets, are checked
|
||||
* at startup, where the engine knows whether the model generates text. */
|
||||
TEST(the_lora_flags_reach_their_fields_and_refuse_what_serves_no_adapter) {
|
||||
Config c;
|
||||
CHECK_OK(parse({ "--lora", "b=/ad/b", "--lora", "a=/ad/a", "--max-loras", "3",
|
||||
@@ -144,6 +146,15 @@ TEST(the_lora_flags_reach_their_fields_and_refuse_what_serves_no_adapter) {
|
||||
Config d;
|
||||
CHECK_OK(parse({}, &d));
|
||||
CHECK(!d.lora.enabled());
|
||||
CHECK_EQ(d.lora.rank(false), 16);
|
||||
CHECK_EQ(d.lora.rank(true), 64);
|
||||
Config e;
|
||||
const std::string dir = radtest::tmp_path("loradir");
|
||||
mkdir(dir.c_str(), 0755);
|
||||
CHECK_OK(parse({ "--lora-dir", dir.c_str() }, &e));
|
||||
CHECK(e.lora.enabled());
|
||||
CHECK_EQ(e.lora.slots(), 2);
|
||||
CHECK_EQ(e.lora.rank(true), 64);
|
||||
|
||||
auto refused = [](std::initializer_list<const char*> v, const char* why) {
|
||||
int st = RAD_OK;
|
||||
@@ -157,10 +168,9 @@ TEST(the_lora_flags_reach_their_fields_and_refuse_what_serves_no_adapter) {
|
||||
refused({ "--lora", "/ad/a" }, "NAME=PATH");
|
||||
refused({ "--lora", "a=" }, "NAME=PATH");
|
||||
refused({ "--lora", "a=/x", "--lora", "a=/y" }, "names the adapter 'a' twice");
|
||||
refused({ "--lora", "a=/x", "--lora", "b=/y", "--max-loras", "1" }, "fewer adapters");
|
||||
refused({ "--max-lora-rank", "32" }, "--max-lora-rank sizes runtime LoRA slots");
|
||||
refused({ "--lora-target-modules", "q_proj" }, "--lora-target-modules sizes");
|
||||
refused({ "--max-loras", "2" }, "names no module an adapter may target");
|
||||
refused({ "--lora-dir", "/no/such/dir" }, "is not a directory");
|
||||
refused({ "--lora", "a=/x", "--lora-target-modules", "self_attn.q_proj" }, "leaf names");
|
||||
refused({ "--lora", "a=/x", "--lora-target-modules", ".*proj" }, "leaf names");
|
||||
refused({ "--lora", "a=/x", "--lora-target-modules", " , " }, "names no module");
|
||||
@@ -454,6 +464,7 @@ const std::map<std::string, std::vector<std::string>>& legal_values() {
|
||||
{ "--kld-corpus", { "/c.jsonl", "--kld-record", "/r" } },
|
||||
{ "--kld-out", { "/o.json", "--kld-ref", "/r" } },
|
||||
{ "--lora", { "a=/adapters/a" } },
|
||||
{ "--lora-dir", { "/" } },
|
||||
{ "--max-loras", { "2", "--lora-target-modules", "q_proj" } },
|
||||
{ "--max-lora-rank", { "32", "--lora", "a=/adapters/a" } },
|
||||
{ "--lora-target-modules", { "q_proj,v_proj", "--max-loras", "1" } },
|
||||
|
||||
@@ -0,0 +1,585 @@
|
||||
/* gen_lora_test.cpp -- runtime LoRA for generators: adapter files in every spelling and kind
|
||||
* (core/lora/adapter.h), their keys mapped through a generator's declared names, stacked at
|
||||
* strengths, packed per rank; and the request fields that name them (core/server/loras.h).
|
||||
*
|
||||
* Host only, no kernel plugin: the Program is made by the core Builder over an empty Registry, as
|
||||
* lora_test.cpp makes its own, with the generator's names declared through the builder (the calls
|
||||
* rad_lora_root / rad_lora_alias make). The reference is the test's own dense delta of every
|
||||
* checkpoint module, placed by model semantics -- which rows of which tensor a rank's declared
|
||||
* weight holds -- never by anything adapter.cpp or lora.cpp computes.
|
||||
*/
|
||||
#include "rad_test.h"
|
||||
|
||||
#include "build/rad_build.h"
|
||||
#include "lora/adapter.h"
|
||||
#include "lora/lora.h"
|
||||
#include "plugin/registry.h"
|
||||
#include "rad_plugin.h"
|
||||
#include "server/loras.h"
|
||||
|
||||
#include <arch/rad_arch.h>
|
||||
#include <arch/rad_fp8.h>
|
||||
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <fstream>
|
||||
#include <map>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <sys/stat.h>
|
||||
|
||||
using namespace rad;
|
||||
namespace AR = rad::arch;
|
||||
using ojson = nlohmann::ordered_json;
|
||||
|
||||
namespace {
|
||||
|
||||
Registry& empty_registry() {
|
||||
static Registry r;
|
||||
return r;
|
||||
}
|
||||
|
||||
float val(uint32_t seed, uint64_t i) {
|
||||
uint64_t x = (uint64_t)seed * 0x9E3779B97F4A7C15ull + i * 0xBF58476D1CE4E5B9ull + 1;
|
||||
x ^= x >> 31; x *= 0x94D049BB133111EBull; x ^= x >> 29;
|
||||
return (float)((double)(x >> 11) / (double)(1ull << 53) - 0.5) * 0.5f;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ safetensors */
|
||||
struct TW {
|
||||
std::string name, dtype;
|
||||
std::vector<int64_t> shape;
|
||||
std::vector<float> v; /* written as dtype */
|
||||
};
|
||||
void write_st(const std::string& path, const std::vector<TW>& ts) {
|
||||
ojson h = ojson::object();
|
||||
std::vector<std::vector<uint8_t>> bytes;
|
||||
uint64_t off = 0;
|
||||
for (const TW& t : ts) {
|
||||
std::vector<uint8_t> b;
|
||||
if (t.dtype == "I64") { const int64_t v = 4; b.resize(8); std::memcpy(b.data(), &v, 8); }
|
||||
for (float f : t.v) {
|
||||
if (t.dtype == "F32") { uint8_t x[4]; std::memcpy(x, &f, 4); b.insert(b.end(), x, x + 4); }
|
||||
else {
|
||||
const uint16_t u = t.dtype == "F16" ? rad_f32_to_f16(f) : rad_f32_to_bf16(f);
|
||||
uint8_t x[2]; std::memcpy(x, &u, 2); b.insert(b.end(), x, x + 2);
|
||||
}
|
||||
}
|
||||
h[t.name] = { { "dtype", t.dtype }, { "shape", t.shape },
|
||||
{ "data_offsets", { off, off + b.size() } } };
|
||||
off += b.size();
|
||||
bytes.push_back(std::move(b));
|
||||
}
|
||||
h["__metadata__"] = { { "format", "pt" } };
|
||||
std::string s = h.dump();
|
||||
while (s.size() % 8) s += ' ';
|
||||
std::ofstream f(path, std::ios::binary);
|
||||
const uint64_t n = s.size();
|
||||
f.write((const char*)&n, 8);
|
||||
f.write(s.data(), (std::streamsize)s.size());
|
||||
for (const auto& b : bytes) f.write((const char*)b.data(), (std::streamsize)b.size());
|
||||
}
|
||||
/* A tensor of seeded values, and the values as the file holds them. */
|
||||
TW tensor(const std::string& name, const std::string& dt, std::vector<int64_t> shape, uint32_t seed,
|
||||
float mul = 1.0f) {
|
||||
TW t{ name, dt, shape, {} };
|
||||
int64_t n = 1;
|
||||
for (int64_t d : shape) n *= d;
|
||||
for (int64_t i = 0; i < n; ++i) {
|
||||
float f = val(seed, (uint64_t)i) * mul;
|
||||
if (dt == "F16") f = rad_f16_to_f32(rad_f32_to_f16(f));
|
||||
else if (dt == "BF16") f = rad_bf16_to_f32(rad_f32_to_bf16(f));
|
||||
t.v.push_back(f);
|
||||
}
|
||||
return t;
|
||||
}
|
||||
TW scalar(const std::string& name, float f) { return TW{ name, "F32", {}, { f } }; }
|
||||
|
||||
/* ------------------------------------------------------------------ dense helpers */
|
||||
struct Dense {
|
||||
int64_t N = 0, K = 0;
|
||||
std::vector<double> d;
|
||||
void add(const Dense& o, double w) {
|
||||
if (d.empty()) { N = o.N; K = o.K; d.assign(o.d.size(), 0.0); }
|
||||
for (size_t i = 0; i < d.size(); ++i) d[i] += w * o.d[i];
|
||||
}
|
||||
};
|
||||
Dense mul(const std::vector<float>& B, const std::vector<float>& A, int64_t N, int64_t r, int64_t K,
|
||||
double s) {
|
||||
Dense o{ N, K, std::vector<double>((size_t)(N * K), 0.0) };
|
||||
for (int64_t n = 0; n < N; ++n)
|
||||
for (int64_t j = 0; j < r; ++j)
|
||||
for (int64_t k = 0; k < K; ++k)
|
||||
o.d[(size_t)(n * K + k)] += s * (double)B[(size_t)(n * r + j)] * A[(size_t)(j * K + k)];
|
||||
return o;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ the generator */
|
||||
/* A two-block DiT under "transformer.", as an image generator's plugin declares one: a fused
|
||||
* [q|k|v] (row parts, ROW), the output (COL), a SwiGLU re-laid from one checkpoint tensor whose
|
||||
* value half comes first (RAD_MAP_ROWS: the gate half moved first), the down projection (COL); a
|
||||
* text encoder's linear outside the root; and a DiT weight a fused GEMM reads. */
|
||||
const int64_t kD = 128, kHD = 32, kNH = 8, kF = 512, kQ = kNH * kHD;
|
||||
|
||||
RadModelMeta gen_meta() {
|
||||
RadModelMeta m{};
|
||||
m.arch_id = "gentest"; m.name = "lora-test-gen"; m.quant = "fp8_e4m3";
|
||||
m.n_layers = 2; m.n_embd = kD; m.n_head = kNH; m.n_head_kv = kNH; m.head_dim = kHD;
|
||||
m.n_ff = kF; m.n_vocab = 512; m.n_ctx_train = 1024;
|
||||
m.rms_eps = 1e-5f; m.rope_theta = 1e4f; m.rope_scale = 1.0f;
|
||||
return m;
|
||||
}
|
||||
|
||||
OpInfo gemm_op(const char* name, int64_t N, int64_t K, const char* dtype, int64_t hi,
|
||||
std::vector<rad_weight> w, std::vector<int32_t> opd) {
|
||||
OpInfo o;
|
||||
o.op = name;
|
||||
o.base.set_i("N", N);
|
||||
o.base.set_i("K", K);
|
||||
o.base.set_i("group", AR::RAD_FP8_BLOCK);
|
||||
o.base.set_s("dtype", dtype);
|
||||
o.ranged_key = "M";
|
||||
o.range_lo = 1;
|
||||
o.range_hi = hi;
|
||||
o.weights = std::move(w);
|
||||
o.weight_opd = std::move(opd);
|
||||
return o;
|
||||
}
|
||||
void push_op(Builder& b, OpInfo o) {
|
||||
o.index = (int32_t)b.program().ops.size();
|
||||
b.program().ops.push_back(std::move(o));
|
||||
}
|
||||
|
||||
int linear(Builder& b, AR::Names& nm, const AR::Geom& g, const char* base, int64_t N, int64_t K,
|
||||
int shard, int layer, std::initializer_list<const char*> src,
|
||||
std::initializer_list<int64_t> parts = {}, bool mapped = false,
|
||||
const char* op = "gemm_nt_q") {
|
||||
AR::LinearFP8 lin{};
|
||||
AR::ActFP8 act{};
|
||||
lin.mapped = mapped;
|
||||
const int st = lin.declare((RadBuilder*)&b, nm, g, base, N, K, shard, AR::grp_layer(layer), src,
|
||||
act, 0, 0, parts);
|
||||
if (st < 0 || !lin.w || !lin.ws) return st < 0 ? st : RAD_E_INVAL;
|
||||
push_op(b, gemm_op(op, N, K, "fp8a8", g.max_tok, { lin.w, lin.ws }, { 2, 3 }));
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
RadBuildCtx ctx_for(int rank, int world) {
|
||||
RadBuildCtx c{};
|
||||
c.rank = rank;
|
||||
c.world_size = world;
|
||||
c.max_tok = 256;
|
||||
c.max_seqs = 8;
|
||||
c.max_ctx = 1024;
|
||||
c.scope = "";
|
||||
return c;
|
||||
}
|
||||
|
||||
/* Where a declared weight's rows on one rank come from: (checkpoint module, its full rows) per
|
||||
* row of y, and the full K columns of x. */
|
||||
struct Truth {
|
||||
std::vector<std::pair<std::string, int64_t>> rows;
|
||||
std::vector<int64_t> cols;
|
||||
};
|
||||
|
||||
int build_gen(int rank, int world, Program* out, std::map<std::string, Truth>* truth) {
|
||||
const RadModelMeta meta = gen_meta();
|
||||
const RadBuildCtx ctx = ctx_for(rank, world);
|
||||
AR::Geom g{};
|
||||
RAD_ARCH_TRY(AR::geom_from(g, &meta, &ctx, "bf16", RAD_BF16));
|
||||
Builder b(empty_registry(), meta, ctx);
|
||||
b.program().generator.layout = RAD_GEN_LAYOUT_JOINT_STEP;
|
||||
RAD_ARCH_TRY(AR::lora_names((RadBuilder*)&b, "transformer.", AR::kLoraDiffusionSpellings,
|
||||
{ { "blocks.#.attn.qkv", "transformer_blocks.#.attn.to_q", 0, kQ, 0 },
|
||||
{ "blocks.#.attn.qkv", "transformer_blocks.#.attn.to_k", kQ, 2 * kQ, 0 },
|
||||
{ "blocks.#.attn.qkv", "transformer_blocks.#.attn.to_v", 2 * kQ, 3 * kQ, 0 },
|
||||
{ "blocks.#.attn.out_proj", "transformer_blocks.#.attn.to_out.0" },
|
||||
{ "blocks.#.mlp.fc1", "transformer_blocks.#.ff.net.0.proj", 0, kF, kF },
|
||||
{ "blocks.#.mlp.fc1", "transformer_blocks.#.ff.net.0.proj", kF, 2 * kF, 0 },
|
||||
{ "blocks.#.mlp.fc2", "transformer_blocks.#.ff.net.2" } }));
|
||||
AR::Names nm("");
|
||||
const int64_t qr = g.q_dim(), fr = g.n_ff;
|
||||
for (int l = 0; l < 2; ++l) {
|
||||
const std::string P = "transformer.transformer_blocks." + std::to_string(l) + ".";
|
||||
auto ck = [&](const char* leaf) { return nm.ckpt("%s%s.weight", P.c_str(), leaf); };
|
||||
RAD_ARCH_TRY(linear(b, nm, g, nm.f("dit.%d.qkv", l), 3 * qr, kD, RAD_SHARD_ROW, l,
|
||||
{ ck("attn.to_q"), ck("attn.to_k"), ck("attn.to_v") }, { qr, qr, qr }));
|
||||
RAD_ARCH_TRY(linear(b, nm, g, nm.f("dit.%d.o", l), kD, qr, RAD_SHARD_COL, l,
|
||||
{ ck("attn.to_out.0") }));
|
||||
const char* fsrc = ck("ff.net.0.proj");
|
||||
RAD_ARCH_TRY(AR::map_rows((RadBuilder*)&b, nm.f("dit.%d.gate_up.weight", l),
|
||||
{ { fsrc, (int)kF, kF }, { fsrc, 0, kF } }));
|
||||
RAD_ARCH_TRY(linear(b, nm, g, nm.f("dit.%d.gate_up", l), 2 * fr, kD, RAD_SHARD_ROW, l,
|
||||
{ fsrc }, { fr, fr }, true));
|
||||
RAD_ARCH_TRY(linear(b, nm, g, nm.f("dit.%d.down", l), kD, fr, RAD_SHARD_COL, l,
|
||||
{ ck("ff.net.2") }));
|
||||
|
||||
Truth q, o, gu, dn;
|
||||
const char* part[3] = { "attn.to_q", "attn.to_k", "attn.to_v" };
|
||||
for (const char* p : part)
|
||||
for (int64_t i = rank * qr; i < (rank + 1) * qr; ++i) q.rows.push_back({ P + p, i });
|
||||
for (int64_t k = 0; k < kD; ++k) q.cols.push_back(k);
|
||||
for (int64_t i = 0; i < kD; ++i) o.rows.push_back({ P + "attn.to_out.0", i });
|
||||
for (int64_t k = rank * qr; k < (rank + 1) * qr; ++k) o.cols.push_back(k);
|
||||
for (int64_t i = rank * fr; i < (rank + 1) * fr; ++i) gu.rows.push_back({ P + "ff.net.0.proj", kF + i });
|
||||
for (int64_t i = rank * fr; i < (rank + 1) * fr; ++i) gu.rows.push_back({ P + "ff.net.0.proj", i });
|
||||
for (int64_t k = 0; k < kD; ++k) gu.cols.push_back(k);
|
||||
for (int64_t i = 0; i < kD; ++i) dn.rows.push_back({ P + "ff.net.2", i });
|
||||
for (int64_t k = rank * fr; k < (rank + 1) * fr; ++k) dn.cols.push_back(k);
|
||||
const std::string L = std::to_string(l);
|
||||
(*truth)["dit." + L + ".qkv.weight"] = q;
|
||||
(*truth)["dit." + L + ".o.weight"] = o;
|
||||
(*truth)["dit." + L + ".gate_up.weight"] = gu;
|
||||
(*truth)["dit." + L + ".down.weight"] = dn;
|
||||
}
|
||||
/* Outside the root: a text encoder's projection. */
|
||||
RAD_ARCH_TRY(linear(b, nm, g, "te.0.q", kD, kD, RAD_SHARD_NONE, 0,
|
||||
{ "text_encoder.layers.0.q_proj.weight" }));
|
||||
/* Under the root, read by a fused GEMM: it stays the base. */
|
||||
RAD_ARCH_TRY(linear(b, nm, g, "dit.fused", kD, kD, RAD_SHARD_NONE, 0,
|
||||
{ "transformer.proj_out.weight" }, {}, false, "gemm_nt_q_swiglu"));
|
||||
*out = std::move(b.program());
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
std::string new_dir(const std::string& name) {
|
||||
const std::string d = radtest::tmp_path(name);
|
||||
mkdir(d.c_str(), 0755);
|
||||
return d;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ the adapter files */
|
||||
/* Two files, every spelling and kind, and the dense delta of every checkpoint module they reach
|
||||
* (strength 1). File 1: kohya LoRA on block 0's fused qkv; ComfyUI LoRA on block 0's fc1 (gate
|
||||
* half first); PEFT LoRA on block 1's down projection under the checkpoint's own name; LoHa on
|
||||
* block 1's out_proj; a full delta on block 0's fc2; a module of no model; a bias delta. File 2:
|
||||
* LoKr on block 1's qkv; a bare-keyed LoRA on block 0's qkv, stacking with file 1's. */
|
||||
struct Files {
|
||||
std::string f1, f2;
|
||||
std::map<std::string, Dense> d1, d2; /* by checkpoint module, full rows */
|
||||
};
|
||||
|
||||
void place(std::map<std::string, Dense>* m, const std::string& mod, int64_t N_full, const Dense& d,
|
||||
int64_t from_lo, int64_t n, int64_t to_lo) {
|
||||
Dense& t = (*m)[mod];
|
||||
if (t.d.empty()) { t.N = N_full; t.K = d.K; t.d.assign((size_t)(N_full * d.K), 0.0); }
|
||||
for (int64_t r = 0; r < n; ++r)
|
||||
for (int64_t k = 0; k < d.K; ++k)
|
||||
t.d[(size_t)((to_lo + r) * d.K + k)] += d.d[(size_t)((from_lo + r) * d.K + k)];
|
||||
}
|
||||
|
||||
Files make_files() {
|
||||
Files f;
|
||||
const std::string dir = new_dir("genlora");
|
||||
const std::string B0 = "transformer.transformer_blocks.0.", B1 = "transformer.transformer_blocks.1.";
|
||||
std::vector<TW> ts;
|
||||
{ /* kohya LoRA, rank 8, alpha 4: qkv of block 0 */
|
||||
TW dn = tensor("lora_unet_blocks_0_attn_qkv.lora_down.weight", "F16", { 8, kD }, 1);
|
||||
TW up = tensor("lora_unet_blocks_0_attn_qkv.lora_up.weight", "BF16", { 3 * kQ, 8 }, 2);
|
||||
const Dense d = mul(up.v, dn.v, 3 * kQ, 8, kD, 4.0 / 8.0);
|
||||
place(&f.d1, B0 + "attn.to_q", kQ, d, 0, kQ, 0);
|
||||
place(&f.d1, B0 + "attn.to_k", kQ, d, kQ, kQ, 0);
|
||||
place(&f.d1, B0 + "attn.to_v", kQ, d, 2 * kQ, kQ, 0);
|
||||
ts.push_back(dn); ts.push_back(up);
|
||||
TW al{ "lora_unet_blocks_0_attn_qkv.alpha", "I64", {}, {} }; /* as kohya writes some */
|
||||
ts.push_back(al);
|
||||
}
|
||||
{ /* ComfyUI LoRA, rank 4, no alpha: fc1 of block 0, [gate; up] */
|
||||
TW a = tensor("diffusion_model.blocks.0.mlp.fc1.lora_A.weight", "BF16", { 4, kD }, 3);
|
||||
TW b = tensor("diffusion_model.blocks.0.mlp.fc1.lora_B.weight", "F32", { 2 * kF, 4 }, 4);
|
||||
const Dense d = mul(b.v, a.v, 2 * kF, 4, kD, 1.0);
|
||||
place(&f.d1, B0 + "ff.net.0.proj", 2 * kF, d, 0, kF, kF);
|
||||
place(&f.d1, B0 + "ff.net.0.proj", 2 * kF, d, kF, kF, 0);
|
||||
ts.push_back(a); ts.push_back(b);
|
||||
}
|
||||
{ /* PEFT LoRA under the checkpoint's own name, rank 6, alpha 12 */
|
||||
TW a = tensor(B1 + "ff.net.2.lora_A.default.weight", "F32", { 6, kF }, 5);
|
||||
TW b = tensor(B1 + "ff.net.2.lora_B.default.weight", "F32", { kD, 6 }, 6);
|
||||
place(&f.d1, B1 + "ff.net.2", kD, mul(b.v, a.v, kD, 6, kF, 12.0 / 6.0), 0, kD, 0);
|
||||
ts.push_back(a); ts.push_back(b); ts.push_back(scalar(B1 + "ff.net.2.alpha", 12.0f));
|
||||
}
|
||||
{ /* LoHa, ranks 4 and 3, alpha 2: out_proj of block 1 */
|
||||
const std::string k = "diffusion_model.blocks.1.attn.out_proj.";
|
||||
TW w1a = tensor(k + "hada_w1_a", "F32", { kD, 4 }, 7), w1b = tensor(k + "hada_w1_b", "F32", { 4, kQ }, 8);
|
||||
TW w2a = tensor(k + "hada_w2_a", "F32", { kD, 3 }, 9), w2b = tensor(k + "hada_w2_b", "F32", { 3, kQ }, 10);
|
||||
const Dense p1 = mul(w1a.v, w1b.v, kD, 4, kQ, 1.0), p2 = mul(w2a.v, w2b.v, kD, 3, kQ, 1.0);
|
||||
Dense d{ kD, kQ, std::vector<double>(p1.d.size()) };
|
||||
for (size_t i = 0; i < d.d.size(); ++i) d.d[i] = 0.5 * p1.d[i] * p2.d[i];
|
||||
place(&f.d1, B1 + "attn.to_out.0", kD, d, 0, kD, 0);
|
||||
ts.insert(ts.end(), { w1a, w1b, w2a, w2b, scalar(k + "alpha", 2.0f) });
|
||||
}
|
||||
{ /* a full delta: fc2 of block 0 */
|
||||
TW df = tensor("diffusion_model.blocks.0.mlp.fc2.diff", "F32", { kD, kF }, 11, 0.1f);
|
||||
Dense d{ kD, kF, std::vector<double>(df.v.begin(), df.v.end()) };
|
||||
place(&f.d1, B0 + "ff.net.2", kD, d, 0, kD, 0);
|
||||
ts.push_back(df);
|
||||
}
|
||||
ts.push_back(tensor("diffusion_model.nowhere.lora_A.weight", "F32", { 2, 8 }, 12));
|
||||
ts.push_back(tensor("diffusion_model.nowhere.lora_B.weight", "F32", { 8, 2 }, 13));
|
||||
ts.push_back(tensor("diffusion_model.blocks.0.mlp.fc2.diff_b", "F32", { kD }, 14));
|
||||
f.f1 = dir + "/one.safetensors";
|
||||
write_st(f.f1, ts);
|
||||
|
||||
ts.clear();
|
||||
{ /* LoKr: w1 [3, 2] full, w2 = w2_a [kQ, 4] @ w2_b [4, kD / 2], alpha 8 (scale 8 / 4) */
|
||||
const std::string k = "lora_unet_blocks_1_attn_qkv.";
|
||||
TW w1 = tensor(k + "lokr_w1", "F32", { 3, 2 }, 15);
|
||||
TW w2a = tensor(k + "lokr_w2_a", "F32", { kQ, 4 }, 16), w2b = tensor(k + "lokr_w2_b", "F32", { 4, kD / 2 }, 17);
|
||||
const Dense w2 = mul(w2a.v, w2b.v, kQ, 4, kD / 2, 1.0);
|
||||
Dense d{ 3 * kQ, kD, std::vector<double>((size_t)(3 * kQ * kD)) };
|
||||
for (int64_t i1 = 0; i1 < 3; ++i1)
|
||||
for (int64_t j1 = 0; j1 < 2; ++j1)
|
||||
for (int64_t i2 = 0; i2 < kQ; ++i2)
|
||||
for (int64_t j2 = 0; j2 < kD / 2; ++j2)
|
||||
d.d[(size_t)((i1 * kQ + i2) * kD + j1 * (kD / 2) + j2)] =
|
||||
2.0 * w1.v[(size_t)(i1 * 2 + j1)] * w2.d[(size_t)(i2 * (kD / 2) + j2)];
|
||||
place(&f.d2, B1 + "attn.to_q", kQ, d, 0, kQ, 0);
|
||||
place(&f.d2, B1 + "attn.to_k", kQ, d, kQ, kQ, 0);
|
||||
place(&f.d2, B1 + "attn.to_v", kQ, d, 2 * kQ, kQ, 0);
|
||||
ts.insert(ts.end(), { w1, w2a, w2b, scalar(k + "alpha", 8.0f) });
|
||||
}
|
||||
{ /* bare keys, rank 8: qkv of block 0, stacked on file 1's */
|
||||
TW a = tensor("blocks.0.attn.qkv.lora_A.weight", "BF16", { 8, kD }, 18);
|
||||
TW b = tensor("blocks.0.attn.qkv.lora_B.weight", "BF16", { 3 * kQ, 8 }, 19);
|
||||
const Dense d = mul(b.v, a.v, 3 * kQ, 8, kD, 1.0);
|
||||
place(&f.d2, B0 + "attn.to_q", kQ, d, 0, kQ, 0);
|
||||
place(&f.d2, B0 + "attn.to_k", kQ, d, kQ, kQ, 0);
|
||||
place(&f.d2, B0 + "attn.to_v", kQ, d, 2 * kQ, kQ, 0);
|
||||
ts.push_back(a); ts.push_back(b);
|
||||
}
|
||||
f.f2 = dir + "/two.safetensors";
|
||||
write_st(f.f2, ts);
|
||||
return f;
|
||||
}
|
||||
|
||||
/* A packed slot's product, [N_r, K_r]. */
|
||||
std::vector<double> slot_delta(const lora::Site& s, const lora::PackedSite& p) {
|
||||
std::vector<double> d((size_t)(s.N_r * s.K_r), 0.0);
|
||||
for (int64_t y = 0; y < s.N_r; ++y) {
|
||||
for (int64_t j = 0; j < s.R; ++j) {
|
||||
const double b = rad_bf16_to_f32(p.b[(size_t)(y * s.R + j)]);
|
||||
if (b == 0.0) continue;
|
||||
for (int64_t k = 0; k < s.K_r; ++k)
|
||||
d[(size_t)(y * s.K_r + k)] += b * rad_bf16_to_f32(p.a[(size_t)(j * s.K_r + k)]);
|
||||
}
|
||||
for (int64_t k = 0; k < s.K_r; ++k) d[(size_t)(y * s.K_r + k)] *= p.scale[(size_t)y];
|
||||
}
|
||||
return d;
|
||||
}
|
||||
|
||||
} /* namespace */
|
||||
|
||||
/* ================================================================== the files */
|
||||
TEST(adapter_files_group_by_module_and_refuse_what_they_cannot_reproduce) {
|
||||
const Files f = make_files();
|
||||
lora::AdapterFile a;
|
||||
std::string err;
|
||||
REQUIRE_EQ(a.open(f.f1, &err), RAD_OK);
|
||||
CHECK_EQ(a.modules().size(), (size_t)6);
|
||||
CHECK_EQ(a.skipped().size(), (size_t)1);
|
||||
CHECK_EQ(std::string(a.kind_name()), std::string("LoRA"));
|
||||
const std::string dir = new_dir("genlora_bad");
|
||||
write_st(dir + "/dora.safetensors", { tensor("m.lora_A.weight", "F32", { 2, 4 }, 1),
|
||||
tensor("m.lora_B.weight", "F32", { 4, 2 }, 2),
|
||||
tensor("m.dora_scale", "F32", { 4, 1 }, 3) });
|
||||
CHECK_EQ(a.open(dir + "/dora.safetensors", &err), (int)RAD_E_UNSUPPORTED);
|
||||
CHECK(err.find("DoRA") != std::string::npos);
|
||||
write_st(dir + "/half.safetensors", { tensor("m.lora_A.weight", "F32", { 2, 4 }, 1) });
|
||||
CHECK_EQ(a.open(dir + "/half.safetensors", &err), (int)RAD_E_FORMAT);
|
||||
}
|
||||
|
||||
/* A delta given as an operator truncates to its best rank-r form: exact at or above its rank, and
|
||||
* otherwise keeping what the sketch says it keeps. */
|
||||
TEST(truncation_is_exact_within_the_rank_and_honest_past_it) {
|
||||
const int64_t N = 96, K = 80;
|
||||
std::vector<float> D((size_t)(N * K));
|
||||
/* rank 12 */
|
||||
std::vector<float> U((size_t)(N * 12)), V((size_t)(12 * K));
|
||||
for (size_t i = 0; i < U.size(); ++i) U[i] = val(21, i);
|
||||
for (size_t i = 0; i < V.size(); ++i) V[i] = val(22, i);
|
||||
const Dense ref = mul(U, V, N, 12, K, 1.0);
|
||||
for (size_t i = 0; i < D.size(); ++i) D[i] = (float)ref.d[i];
|
||||
lora::Delta d;
|
||||
d.N = N; d.K = K; d.rank_bound = std::min(N, K);
|
||||
d.apply = [&](const float* X, int64_t l, float* Y) {
|
||||
for (int64_t n = 0; n < N; ++n)
|
||||
for (int64_t j = 0; j < l; ++j) {
|
||||
double a = 0;
|
||||
for (int64_t k = 0; k < K; ++k) a += (double)D[(size_t)(n * K + k)] * X[k * l + j];
|
||||
Y[n * l + j] = (float)a;
|
||||
}
|
||||
};
|
||||
d.apply_t = [&](const float* Y, int64_t l, float* X) {
|
||||
for (int64_t k = 0; k < K; ++k)
|
||||
for (int64_t j = 0; j < l; ++j) {
|
||||
double a = 0;
|
||||
for (int64_t n = 0; n < N; ++n) a += (double)D[(size_t)(n * K + k)] * Y[n * l + j];
|
||||
X[k * l + j] = (float)a;
|
||||
}
|
||||
};
|
||||
std::vector<float> B, A;
|
||||
double kept = 0;
|
||||
lora::truncate(d, 16, &B, &A, &kept);
|
||||
const Dense got = mul(B, A, N, 16, K, 1.0);
|
||||
double e = 0, t = 0;
|
||||
for (size_t i = 0; i < got.d.size(); ++i) { e += std::pow(got.d[i] - ref.d[i], 2); t += ref.d[i] * ref.d[i]; }
|
||||
CHECK(e / t < 1e-8);
|
||||
CHECK_NEAR(kept, 1.0, 1e-6);
|
||||
/* rank 6 of a rank-12 matrix: what is lost is what the report says is lost */
|
||||
lora::truncate(d, 6, &B, &A, &kept);
|
||||
const Dense g6 = mul(B, A, N, 6, K, 1.0);
|
||||
e = 0;
|
||||
for (size_t i = 0; i < g6.d.size(); ++i) e += std::pow(g6.d[i] - ref.d[i], 2);
|
||||
CHECK(kept < 0.99 && kept > 0.2);
|
||||
CHECK_NEAR(1.0 - e / t, kept, 0.02);
|
||||
}
|
||||
|
||||
/* ================================================================== the names */
|
||||
TEST(keys_resolve_through_spellings_aliases_and_kohya) {
|
||||
Program P;
|
||||
std::map<std::string, Truth> truth;
|
||||
REQUIRE_EQ(build_gen(0, 1, &P, &truth), RAD_OK);
|
||||
std::vector<lora::Site> sites;
|
||||
std::string err;
|
||||
REQUIRE_EQ(lora::build_sites(P, { "*" }, 16, &sites, &err), RAD_OK);
|
||||
/* 2 blocks x 4 weights; the text encoder's and the fused GEMM's are not sites */
|
||||
CHECK_EQ(sites.size(), (size_t)8);
|
||||
for (const lora::Site& s : sites) CHECK(s.weight.rfind("dit.", 0) == 0 && s.weight != "dit.fused.weight");
|
||||
const lora::KeyMap km(P, sites);
|
||||
std::string why;
|
||||
auto one = [&](const std::string& k) { return km.resolve(k, &why); };
|
||||
std::vector<lora::Target> t = one("lora_unet_blocks_1_attn_qkv");
|
||||
REQUIRE_EQ(t.size(), (size_t)3);
|
||||
CHECK_EQ(t[1].module, std::string("transformer.transformer_blocks.1.attn.to_k"));
|
||||
CHECK_EQ(t[1].from_lo, kQ);
|
||||
CHECK_EQ(t[1].from_hi, 2 * kQ);
|
||||
t = one("diffusion_model.blocks.0.mlp.fc2");
|
||||
REQUIRE_EQ(t.size(), (size_t)1);
|
||||
CHECK_EQ(t[0].module, std::string("transformer.transformer_blocks.0.ff.net.2"));
|
||||
t = one("transformer.transformer_blocks.0.attn.to_out.0");
|
||||
REQUIRE_EQ(t.size(), (size_t)1);
|
||||
t = one("lora_unet_transformer_blocks_0_attn_to_out_0");
|
||||
REQUIRE_EQ(t.size(), (size_t)1);
|
||||
CHECK_EQ(t[0].module, std::string("transformer.transformer_blocks.0.attn.to_out.0"));
|
||||
t = one("blocks.1.mlp.fc1");
|
||||
CHECK_EQ(t.size(), (size_t)2);
|
||||
CHECK(one("diffusion_model.proj_out").empty());
|
||||
CHECK(why.find("no adapter path") != std::string::npos);
|
||||
CHECK(one("text_encoder.layers.0.q_proj").empty());
|
||||
CHECK(one("diffusion_model.blocks.7.attn.qkv").empty());
|
||||
}
|
||||
|
||||
/* ================================================================== stacked, packed */
|
||||
/* Packed compact, as the engine packs a generator's slot: every pool's product is the dense delta,
|
||||
* and its ranks are taken from 0. */
|
||||
TEST(stacked_adapters_of_every_kind_pack_to_their_dense_delta_on_every_rank) {
|
||||
const Files f = make_files();
|
||||
auto a1 = std::make_shared<lora::AdapterFile>(), a2 = std::make_shared<lora::AdapterFile>();
|
||||
std::string err;
|
||||
REQUIRE_EQ(a1->open(f.f1, &err), RAD_OK);
|
||||
REQUIRE_EQ(a2->open(f.f2, &err), RAD_OK);
|
||||
const double w1 = 0.8, w2 = -0.5;
|
||||
std::map<std::string, Dense> want;
|
||||
for (const auto& [k, d] : f.d1) want[k].add(d, w1);
|
||||
for (const auto& [k, d] : f.d2) want[k].add(d, w2);
|
||||
const int R = 24;
|
||||
for (int world : { 1, 2 }) {
|
||||
for (int rank = 0; rank < world; ++rank) {
|
||||
Program P;
|
||||
std::map<std::string, Truth> truth;
|
||||
REQUIRE_EQ(build_gen(rank, world, &P, &truth), RAD_OK);
|
||||
std::vector<lora::Site> sites;
|
||||
std::vector<std::string> pools;
|
||||
REQUIRE_EQ(lora::build_sites(P, { "*" }, R, &sites, &err, &pools), RAD_OK);
|
||||
const lora::KeyMap km(P, sites);
|
||||
std::map<std::string, lora::Composite> comp;
|
||||
lora::ComposeReport rep;
|
||||
const int cs = lora::compose(km, { { "one", a1, w1 }, { "two", a2, w2 } }, R, &comp, &rep, &err);
|
||||
if (cs != RAD_OK) fprintf(stderr, " world %d rank %d: %s\n", world, rank, err.c_str());
|
||||
REQUIRE_EQ(cs, RAD_OK);
|
||||
CHECK_EQ(rep.unplaced.size(), (size_t)1);
|
||||
CHECK_EQ(rep.skipped.size(), (size_t)1);
|
||||
/* block 0's fc2 (a full delta, rank 128) is the one module past rank 24 */
|
||||
CHECK_EQ(rep.modules - rep.exact, (int64_t)1);
|
||||
CHECK_EQ(rep.worst_module, std::string("transformer.transformer_blocks.0.ff.net.2"));
|
||||
const std::map<std::string, lora::AdModule> mods = lora::as_modules(comp, km);
|
||||
lora::AdapterInfo info;
|
||||
std::vector<lora::PackedSite> packed;
|
||||
const int ps = lora::pack_modules(sites, R, mods, &info, &packed, &err, /*compact=*/true);
|
||||
if (ps != RAD_OK) fprintf(stderr, " world %d rank %d: %s\n", world, rank, err.c_str());
|
||||
REQUIRE_EQ(ps, RAD_OK);
|
||||
REQUIRE_EQ(packed.size(), pools.size());
|
||||
for (size_t p = 0; p < pools.size(); ++p) {
|
||||
const lora::Site* sp = nullptr;
|
||||
for (const lora::Site& x : sites) if (x.pool == (int32_t)p && !sp) sp = &x;
|
||||
REQUIRE(sp != nullptr);
|
||||
const lora::Site& s = *sp;
|
||||
const Truth& t = truth.at(s.weight);
|
||||
/* compact: the ranks taken from 0, within the pool's R */
|
||||
const lora::PackedSite& pk = packed[(size_t)s.pool];
|
||||
CHECK(pk.empty || (pk.r_used > 0 && pk.r_used <= s.R));
|
||||
for (int64_t y = 0; y < s.N_r && !pk.empty; ++y)
|
||||
for (int64_t j = pk.r_used; j < s.R; ++j)
|
||||
CHECK_EQ(pk.b[(size_t)(y * s.R + j)], (uint16_t)0);
|
||||
REQUIRE_EQ((int64_t)t.rows.size(), s.N_r);
|
||||
REQUIRE_EQ((int64_t)t.cols.size(), s.K_r);
|
||||
const std::vector<double> got = slot_delta(s, packed[(size_t)s.pool]);
|
||||
double e = 0, tot = 0, mx = 0;
|
||||
bool truncated = false;
|
||||
for (int64_t y = 0; y < s.N_r; ++y) {
|
||||
const auto& [mod, row] = t.rows[(size_t)y];
|
||||
truncated = truncated || mod == "transformer.transformer_blocks.0.ff.net.2";
|
||||
auto it = want.find(mod);
|
||||
for (int64_t k = 0; k < s.K_r; ++k) {
|
||||
const double ref = it == want.end() ? 0.0
|
||||
: it->second.d[(size_t)(row * it->second.K + t.cols[(size_t)k])];
|
||||
const double g = got[(size_t)(y * s.K_r + k)];
|
||||
e += (g - ref) * (g - ref);
|
||||
tot += ref * ref;
|
||||
mx = std::max(mx, std::fabs(g - ref) / (std::fabs(ref) + 1e-3));
|
||||
}
|
||||
}
|
||||
const double rel = tot > 0 ? std::sqrt(e / tot) : std::sqrt(e);
|
||||
if (rel > (truncated ? 0.9 : 0.01))
|
||||
fprintf(stderr, " world %d rank %d %s: relative error %.4g\n", world, rank,
|
||||
s.weight.c_str(), rel);
|
||||
/* bf16 factors hold a delta to ~0.5%; the truncated one to what its rank keeps */
|
||||
CHECK(rel <= (truncated ? 0.9 : 0.01));
|
||||
if (truncated && world == 1)
|
||||
CHECK_NEAR(1.0 - rel * rel, rep.worst_kept, 0.03);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* ================================================================== the request fields */
|
||||
TEST(requests_name_adapters_in_a_field_or_in_prompt_tags) {
|
||||
std::vector<std::pair<std::string, double>> out;
|
||||
std::string field, why;
|
||||
std::string prompt = "a cat, <lora:pixel art:0.7>, sitting <lora:detail>";
|
||||
nlohmann::json body = { { "loras", { "style", "ink:0.5", { { "name", "x:y" }, { "weight", 2 } } } } };
|
||||
REQUIRE_EQ(server::parse_loras(body, &prompt, &out, &field, &why), RAD_OK);
|
||||
REQUIRE_EQ(out.size(), (size_t)5);
|
||||
CHECK_EQ(out[0].first, std::string("style"));
|
||||
CHECK_EQ(out[0].second, 1.0);
|
||||
CHECK_EQ(out[1].first, std::string("ink"));
|
||||
CHECK_EQ(out[1].second, 0.5);
|
||||
CHECK_EQ(out[2].first, std::string("x:y"));
|
||||
CHECK_EQ(out[2].second, 2.0);
|
||||
CHECK_EQ(out[3].first, std::string("pixel art"));
|
||||
CHECK_NEAR(out[3].second, 0.7, 1e-12);
|
||||
CHECK_EQ(out[4].first, std::string("detail"));
|
||||
CHECK_EQ(prompt, std::string("a cat, sitting"));
|
||||
body = { { "lora", { { "a", 0.25 }, { "b", 1 } } } };
|
||||
prompt = "p";
|
||||
REQUIRE_EQ(server::parse_loras(body, &prompt, &out, &field, &why), RAD_OK);
|
||||
CHECK_EQ(out.size(), (size_t)2);
|
||||
body = { { "loras", { 3 } } };
|
||||
CHECK_EQ(server::parse_loras(body, &prompt, &out, &field, &why), (int)RAD_E_INVAL);
|
||||
CHECK_EQ(field, std::string("loras"));
|
||||
}
|
||||
|
||||
RAD_TEST_MAIN()
|
||||
@@ -88,6 +88,29 @@ TEST(the_schedule_is_diffusers_flow_match_euler) {
|
||||
CHECK_EQ(gen::schedule(d, {}, 0, 64).size(), (size_t)d.default_steps + 1);
|
||||
}
|
||||
|
||||
/* A schedule off a table of timesteps is ComfyUI's `simple` scheduler over its discrete flow
|
||||
* sampling (1000 timesteps, shift 3, multiplier 1): the sigmas below are what ComfyUI hands its
|
||||
* sampler, as f32. */
|
||||
TEST(a_sigma_grid_is_comfyui_simple_schedule) {
|
||||
RadGeneratorDecl d = decl_base();
|
||||
d.dyn_shift = 0; d.shift_terminal = 0; d.shift = 3.0;
|
||||
d.sigma_grid = 1000;
|
||||
const double want30[] = { 1, 0.988752544, 0.976987481, 0.964285672, 0.951353252, 0.937781036,
|
||||
0.923076987, 0.908050597, 0.892220497, 0.87499994, 0.857326388,
|
||||
0.838624299, 0.818181813, 0.797094703, 0.774661541, 0.75,
|
||||
0.724405408, 0.697002113, 0.666666687, 0.634948134, 0.600719392,
|
||||
0.5625, 0.522164285, 0.478201658, 0.428571463, 0.375562221,
|
||||
0.317034721, 0.25, 0.177248672, 0.095505625, 0 };
|
||||
const std::vector<float> s = gen::schedule(d, {}, 30, 4096);
|
||||
REQUIRE_EQ(s.size(), (size_t)31);
|
||||
for (size_t i = 0; i < s.size(); ++i) CHECK_NEAR(s[i], want30[i], 1e-8);
|
||||
const double want7[] = { 1, 0.94771713, 0.882716119, 0.800373137, 0.69268024, 0.54580152,
|
||||
0.333592534, 0 };
|
||||
const std::vector<float> s7 = gen::schedule(d, {}, 7, 1024);
|
||||
REQUIRE_EQ(s7.size(), (size_t)8);
|
||||
for (size_t i = 0; i < s7.size(); ++i) CHECK_NEAR(s7[i], want7[i], 1e-8);
|
||||
}
|
||||
|
||||
/* A fixed schedule is taken as declared (with shift 1), then closed with 0. */
|
||||
TEST(a_fixed_schedule_is_used_as_declared) {
|
||||
RadGeneratorDecl d = decl_base();
|
||||
@@ -96,6 +119,146 @@ TEST(a_fixed_schedule_is_used_as_declared) {
|
||||
CHECK_EQ(s[0], 0.9f); CHECK_EQ(s[1], 0.5f); CHECK_EQ(s[2], 0.125f); CHECK_EQ(s[3], 0.0f);
|
||||
}
|
||||
|
||||
/* ================================================================== a discrete-time schedule */
|
||||
/* Stable Diffusion XL's: 1000 timesteps, scaled-linear betas 0.00085..0.012. */
|
||||
RadGeneratorDecl decl_discrete() {
|
||||
RadGeneratorDecl d = decl_base();
|
||||
d.train_steps = 1000;
|
||||
d.beta_schedule = RAD_GEN_BETAS_SCALED_LINEAR;
|
||||
d.beta_start = 0.00085;
|
||||
d.beta_end = 0.012;
|
||||
d.samplers = (1u << RAD_GEN_SAMPLER_COUNT) - 1;
|
||||
d.default_steps = 5;
|
||||
return d;
|
||||
}
|
||||
|
||||
/* Each scheduler places five sigmas as ComfyUI's ModelSamplingDiscrete does (reference values
|
||||
* from its schedulers over the same table), and each sigma is conditioned at the timestep
|
||||
* ComfyUI picks for it. The table's ends are SDXL's sigma_min and sigma_max. */
|
||||
TEST(a_discrete_schedule_is_comfyuis) {
|
||||
const RadGeneratorDecl d = decl_discrete();
|
||||
gen::DiscreteTable t;
|
||||
std::string why;
|
||||
REQUIRE_EQ(gen::discrete_table(d, &t, &why), (int)RAD_OK);
|
||||
CHECK_NEAR(t.sigma_min(), 0.0291671585, 1e-8);
|
||||
CHECK_NEAR(t.sigma_max(), 14.6146412, 2e-5);
|
||||
struct Want { int32_t sched; double s[5]; int32_t ts[5]; };
|
||||
const Want want[] = {
|
||||
{ RAD_GEN_SCHED_NORMAL, { 14.6146402, 4.08608103, 1.61558032, 0.695149541, 0.0291671604 },
|
||||
{ 999, 749, 500, 250, 0 } },
|
||||
{ RAD_GEN_SCHED_KARRAS, { 14.6146431, 4.79653454, 1.27410078, 0.247949973, 0.0291671772 },
|
||||
{ 999, 786, 427, 59, 0 } },
|
||||
{ RAD_GEN_SCHED_EXPONENTIAL,
|
||||
{ 14.6146402, 3.08897638, 0.652891755, 0.137996376, 0.0291671604 },
|
||||
{ 999, 681, 233, 20, 0 } },
|
||||
{ RAD_GEN_SCHED_SGM_UNIFORM,
|
||||
{ 14.6146402, 5.09240818, 2.27973056, 1.16286457, 0.571188867 },
|
||||
{ 999, 799, 599, 400, 200 } },
|
||||
{ RAD_GEN_SCHED_SIMPLE, { 14.6146412, 5.08776331, 2.27646303, 1.16057837, 0.569284916 },
|
||||
{ 999, 799, 599, 399, 199 } },
|
||||
};
|
||||
for (const Want& w : want) {
|
||||
const std::vector<float> s = gen::schedule_discrete(d, t, w.sched, 0);
|
||||
REQUIRE_EQ(s.size(), (size_t)6);
|
||||
for (int i = 0; i < 5; ++i) {
|
||||
CHECK_NEAR(s[(size_t)i], w.s[i], 2e-6 * w.s[i] + 1e-7);
|
||||
CHECK_EQ(t.timestep(s[(size_t)i]), w.ts[i]);
|
||||
}
|
||||
CHECK_EQ(s[5], 0.0f);
|
||||
CHECK_EQ(std::string(gen::scheduler_name(w.sched)).empty(), false);
|
||||
CHECK_EQ(gen::scheduler_id(gen::scheduler_name(w.sched)), w.sched);
|
||||
}
|
||||
/* Zero terminal SNR keeps the smallest sigma and makes the largest ComfyUI's 4518.76. */
|
||||
RadGeneratorDecl z = d;
|
||||
z.zero_snr = 1;
|
||||
gen::DiscreteTable tz;
|
||||
REQUIRE_EQ(gen::discrete_table(z, &tz, &why), (int)RAD_OK);
|
||||
CHECK_NEAR(tz.sigma_min(), 0.0291671585, 1e-8);
|
||||
CHECK_NEAR(tz.sigma_max(), 4518.76367, 0.01);
|
||||
CHECK_EQ(gen::sampler_id("dpmpp_2m"), (int32_t)RAD_GEN_SAMPLER_DPMPP_2M);
|
||||
CHECK_EQ(gen::sampler_id("ddim"), (int32_t)-1);
|
||||
}
|
||||
|
||||
/* A discrete-time model's step carries, per entry, its sigmas (the one before included), the
|
||||
* timestep, the request's sampler, the step, the image's size, and on the host the entry's
|
||||
* conditioning rows, size and branch; the conditioning pass carries its tokens on the host. */
|
||||
TEST(a_discrete_step_carries_its_sampler_and_each_entrys_geometry) {
|
||||
Program prog;
|
||||
prog.generator = decl_discrete();
|
||||
RadGeneratorDecl& d = prog.generator;
|
||||
d.layout = RAD_GEN_LAYOUT_JOINT_STEP;
|
||||
d.latent_scale = 8;
|
||||
d.cond_rows = 2 * 77;
|
||||
d.rope_hw_scale = 1.0;
|
||||
d.chunk_tokens = 75;
|
||||
d.chunk_bos = 49406;
|
||||
d.chunk_eos = 49407;
|
||||
d.pad_token = 49407;
|
||||
prog.ctx.max_tok = 4096;
|
||||
prog.ctx.max_seqs = 8;
|
||||
prog.kv_groups.emplace_back();
|
||||
gen::Driver drv;
|
||||
REQUIRE_EQ(drv.init(prog, nullptr, { gen::Driver::RankIO{} }), (int)RAD_OK);
|
||||
auto r = std::make_unique<gen::Request>();
|
||||
r->width = 64;
|
||||
r->height = 32;
|
||||
r->steps = 3;
|
||||
r->sampler = RAD_GEN_SAMPLER_DPMPP_2M;
|
||||
r->scheduler = RAD_GEN_SCHED_KARRAS;
|
||||
r->pos.tokens.assign(77, 5);
|
||||
r->has_neg = true;
|
||||
r->neg.tokens.assign(77, 6);
|
||||
r->cfg = 6.0f;
|
||||
r->ticket = std::make_shared<gen::Ticket>();
|
||||
std::string why;
|
||||
REQUIRE_EQ(drv.submit(std::move(r), &why), (int)RAD_OK);
|
||||
const RadBatch* b = drv.next(0);
|
||||
REQUIRE(b != nullptr);
|
||||
REQUIRE_EQ(b->gen, (int32_t)RAD_GEN_PASS_COND);
|
||||
REQUIRE(b->gen_b->tokens_h != nullptr);
|
||||
CHECK_EQ(b->gen_b->tokens_h[76], (int32_t)5);
|
||||
CHECK_OK(drv.done());
|
||||
REQUIRE(drv.next(1) != nullptr);
|
||||
CHECK_OK(drv.done());
|
||||
gen::DiscreteTable t;
|
||||
REQUIRE_EQ(gen::discrete_table(d, &t, &why), (int)RAD_OK);
|
||||
const std::vector<float> s = gen::schedule_discrete(d, t, RAD_GEN_SCHED_KARRAS, 3);
|
||||
for (int step = 0; step < 3; ++step) {
|
||||
b = drv.next(2 + step);
|
||||
REQUIRE(b != nullptr);
|
||||
REQUIRE_EQ(b->gen, (int32_t)RAD_GEN_PASS_DENOISE);
|
||||
const RadGenBatch* G = b->gen_b;
|
||||
REQUIRE_EQ(b->n_seq, (int64_t)2);
|
||||
CHECK_EQ(b->n_tok, (int64_t)(2 * (77 + 32)));
|
||||
for (int e = 0; e < 2; ++e) {
|
||||
CHECK_EQ(G->sigma[e], s[(size_t)step]);
|
||||
CHECK_EQ(G->sigma_next[e], s[(size_t)step + 1]);
|
||||
CHECK_EQ(G->sigma_prev[e], step ? s[(size_t)step - 1] : 0.0f);
|
||||
CHECK_EQ(G->timestep[e], (float)t.timestep(s[(size_t)step]));
|
||||
CHECK_EQ(G->sampler[e], (int32_t)RAD_GEN_SAMPLER_DPMPP_2M);
|
||||
CHECK_EQ(G->step[e], (int32_t)step);
|
||||
CHECK_EQ(G->size_px[2 * e], 32.0f);
|
||||
CHECK_EQ(G->size_px[2 * e + 1], 64.0f);
|
||||
CHECK_EQ(G->entry_h[4 * e], (int32_t)77);
|
||||
CHECK_EQ(G->entry_h[4 * e + 1], (int32_t)32);
|
||||
CHECK_EQ(G->entry_h[4 * e + 2], (int32_t)64);
|
||||
CHECK_EQ(G->entry_h[4 * e + 3], (int32_t)e);
|
||||
}
|
||||
CHECK_OK(drv.done());
|
||||
}
|
||||
/* A sampler the model does not serve is refused at submit. */
|
||||
d.samplers = 1u << RAD_GEN_SAMPLER_EULER;
|
||||
gen::Driver drv2;
|
||||
REQUIRE_EQ(drv2.init(prog, nullptr, { gen::Driver::RankIO{} }), (int)RAD_OK);
|
||||
auto r2 = std::make_unique<gen::Request>();
|
||||
r2->width = 64;
|
||||
r2->height = 32;
|
||||
r2->sampler = RAD_GEN_SAMPLER_EULER_ANCESTRAL;
|
||||
r2->pos.tokens.assign(77, 5);
|
||||
r2->ticket = std::make_shared<gen::Ticket>();
|
||||
CHECK_EQ(drv2.submit(std::move(r2), &why), (int)RAD_E_INVAL);
|
||||
}
|
||||
|
||||
/* ================================================================== the sequence */
|
||||
/* An h x w image at frame `pos`: every row at that frame, height and width centred on zero. */
|
||||
TEST(image_rotary_positions_centre_the_grid_on_its_frame) {
|
||||
@@ -422,4 +585,65 @@ TEST(the_joint_layout_carries_the_conditioning_in_every_step) {
|
||||
CHECK_OK(drv.done());
|
||||
}
|
||||
|
||||
/* A generator that reads its prompt through a second tokenizer (RadGeneratorDecl::aux_tokens):
|
||||
* each branch's COND pass carries that branch's ids and {0, n} on the device, and no other pass
|
||||
* does; a branch with none, or more than declared, is refused at submission. */
|
||||
TEST(a_second_tokenizers_ids_ride_in_each_conditioning) {
|
||||
Program prog;
|
||||
prog.generator = decl_base();
|
||||
RadGeneratorDecl& d = prog.generator;
|
||||
d.layout = RAD_GEN_LAYOUT_JOINT_STEP;
|
||||
d.cond_rows = 16;
|
||||
d.pad_multiple = 16;
|
||||
d.pad_token = 99;
|
||||
d.aux_tokens = 1;
|
||||
d.aux_max_tokens = 6;
|
||||
prog.ctx.max_tok = 2048;
|
||||
prog.ctx.max_seqs = 8;
|
||||
prog.kv_groups.emplace_back();
|
||||
gen::Driver drv;
|
||||
REQUIRE_EQ(drv.init(prog, nullptr, { gen::Driver::RankIO{} }), (int)RAD_OK);
|
||||
auto mk = [](std::vector<int32_t> aux, std::vector<int32_t> neg_aux) {
|
||||
auto r = std::make_unique<gen::Request>();
|
||||
r->width = 64;
|
||||
r->height = 64;
|
||||
r->pos.tokens = { 1, 2, 3 };
|
||||
r->pos.aux = std::move(aux);
|
||||
r->has_neg = true;
|
||||
r->neg.tokens = { 5 };
|
||||
r->neg.aux = std::move(neg_aux);
|
||||
r->cfg = 4.0f;
|
||||
r->ticket = std::make_shared<gen::Ticket>();
|
||||
return r;
|
||||
};
|
||||
std::string why;
|
||||
CHECK_EQ(drv.submit(mk({ 7, 8 }, {}), &why), (int)RAD_E_INVAL);
|
||||
CHECK(has(why, "second tokenizer"));
|
||||
CHECK_EQ(drv.submit(mk({ 1, 2, 3, 4, 5, 6, 7 }, { 1 }), &why), (int)RAD_E_INVAL);
|
||||
REQUIRE_EQ(drv.submit(mk({ 7, 8, 1 }, { 1 }), &why), (int)RAD_OK);
|
||||
|
||||
const RadBatch* b = drv.next(0);
|
||||
REQUIRE(b != nullptr);
|
||||
REQUIRE_EQ(b->gen, (int32_t)RAD_GEN_PASS_COND);
|
||||
const RadGenBatch* G = b->gen_b;
|
||||
REQUIRE_EQ(G->n_aux, (int64_t)3);
|
||||
CHECK_EQ(G->aux_ids[0], (int32_t)7);
|
||||
CHECK_EQ(G->aux_ids[2], (int32_t)1);
|
||||
CHECK_EQ(G->aux_cu[0], (int32_t)0);
|
||||
CHECK_EQ(G->aux_cu[1], (int32_t)3);
|
||||
CHECK_OK(drv.done());
|
||||
b = drv.next(1);
|
||||
REQUIRE(b != nullptr);
|
||||
REQUIRE_EQ(b->gen_b->n_aux, (int64_t)1);
|
||||
CHECK_EQ(b->gen_b->aux_ids[0], (int32_t)1);
|
||||
CHECK_EQ(b->gen_b->aux_cu[1], (int32_t)1);
|
||||
CHECK_OK(drv.done());
|
||||
b = drv.next(2);
|
||||
REQUIRE(b != nullptr);
|
||||
REQUIRE_EQ(b->gen, (int32_t)RAD_GEN_PASS_DENOISE);
|
||||
CHECK_EQ(b->gen_b->n_aux, (int64_t)0);
|
||||
CHECK(b->gen_b->aux_ids == nullptr);
|
||||
CHECK_OK(drv.done());
|
||||
}
|
||||
|
||||
RAD_TEST_MAIN()
|
||||
@@ -169,6 +169,78 @@ TEST(usage_counts_each_pictures_tokens_in_every_branch) {
|
||||
CHECK(s.last().has_neg);
|
||||
}
|
||||
|
||||
/* A model that reads its prompt through a second tokenizer gets the user's prompt as that tokenizer
|
||||
* encodes it, in each branch, and a prompt longer than it reads is refused under `prompt`. A
|
||||
* prompt shorter than the model's minimum after the fixed prefix is padded with its padding token
|
||||
* (an empty prompt is one, and is not turned into " " first). */
|
||||
TEST(a_second_tokenizer_and_a_minimum_prompt_reach_the_generator) {
|
||||
Images s;
|
||||
s.img.inf.aux_tokens = true;
|
||||
s.img.inf.aux_max_tokens = 4;
|
||||
s.img.inf.min_tokens = 2;
|
||||
s.img.inf.pad_token = 9;
|
||||
s.gen({ { "prompt", "ab" }, { "negative_prompt", "c" }, { "true_cfg_scale", 4.0 } });
|
||||
REQUIRE(!s.img.got.empty());
|
||||
CHECK(s.last().pos.aux == std::vector<int32_t>({ 100 + 'a', 100 + 'b', 1 }));
|
||||
CHECK(s.last().neg.aux == std::vector<int32_t>({ 100 + 'c', 1 }));
|
||||
/* "c" is one token after the prefix, padded to two. */
|
||||
const gen::Branch& n = s.last().neg;
|
||||
REQUIRE((int64_t)n.tokens.size() - n.n_drop == 2);
|
||||
CHECK_EQ(n.tokens[(size_t)n.n_drop], (int32_t)'c');
|
||||
CHECK_EQ(n.tokens.back(), (int32_t)9);
|
||||
s.gen({ { "prompt", "" } });
|
||||
const gen::Branch& p = s.last().pos;
|
||||
REQUIRE((int64_t)p.tokens.size() - p.n_drop == 2);
|
||||
CHECK_EQ(p.tokens[(size_t)p.n_drop], (int32_t)9);
|
||||
CHECK(p.aux == std::vector<int32_t>({ 1 }));
|
||||
/* An empty negative prompt stays empty for such a model: all padding. */
|
||||
s.gen({ { "prompt", "x" }, { "negative_prompt", "" }, { "true_cfg_scale", 4.0 } });
|
||||
const gen::Branch& e = s.last().neg;
|
||||
REQUIRE((int64_t)e.tokens.size() - e.n_drop == 2);
|
||||
CHECK_EQ(e.tokens[(size_t)e.n_drop], (int32_t)9);
|
||||
CHECK(e.aux == std::vector<int32_t>({ 1 }));
|
||||
const json longp = s.gen({ { "prompt", "abcd" } }, 400);
|
||||
CHECK_EQ(str_at(longp["error"], "param"), std::string("prompt"));
|
||||
}
|
||||
|
||||
/* A discrete-time model takes `sampler` and `scheduler` by ComfyUI's names, defaulting to its
|
||||
* own, and refuses one it does not serve; a flow-matching model refuses both. A prompt read in
|
||||
* windows reaches the generator cut into runs between their markers, each padded to the window,
|
||||
* after the template's fixed prefix, and a prompt that fills its last window exactly takes no
|
||||
* empty one after it. */
|
||||
TEST(a_discrete_model_takes_its_sampler_and_reads_the_prompt_in_windows) {
|
||||
Images s;
|
||||
const json flow = s.gen({ { "prompt", "x" }, { "sampler", "euler" } }, 400);
|
||||
CHECK_EQ(str_at(flow["error"], "param"), std::string("sampler"));
|
||||
s.img.inf.samplers = (1u << RAD_GEN_SAMPLER_EULER) | (1u << RAD_GEN_SAMPLER_DPMPP_2M);
|
||||
s.img.inf.default_sampler = RAD_GEN_SAMPLER_EULER;
|
||||
s.img.inf.default_scheduler = RAD_GEN_SCHED_NORMAL;
|
||||
s.img.inf.chunk_tokens = 4;
|
||||
s.img.inf.chunk_bos = 2;
|
||||
s.img.inf.chunk_eos = 3;
|
||||
s.img.inf.chunk_pad = 9;
|
||||
s.gen({ { "prompt", "abcdefghij" } });
|
||||
REQUIRE(!s.img.got.empty());
|
||||
CHECK_EQ(s.last().sampler, (int32_t)RAD_GEN_SAMPLER_EULER);
|
||||
CHECK_EQ(s.last().scheduler, (int32_t)RAD_GEN_SCHED_NORMAL);
|
||||
const std::vector<int32_t> want = { '<', 's', '>', 2, 'a', 'b', 'c', 'd', 3,
|
||||
2, 'e', 'f', 'g', 'h', 3, 2, 'i', 'j', 3, 9, 9 };
|
||||
CHECK(s.last().pos.tokens == want);
|
||||
CHECK_EQ(s.last().pos.n_drop, (int32_t)3);
|
||||
s.gen({ { "prompt", "x" }, { "sampler", "dpmpp_2m" }, { "scheduler", "karras" } });
|
||||
CHECK_EQ(s.last().sampler, (int32_t)RAD_GEN_SAMPLER_DPMPP_2M);
|
||||
CHECK_EQ(s.last().scheduler, (int32_t)RAD_GEN_SCHED_KARRAS);
|
||||
/* A prompt that fills a window takes no second one. */
|
||||
s.gen({ { "prompt", "abcd" } });
|
||||
const std::vector<int32_t> one = { '<', 's', '>', 2, 'a', 'b', 'c', 'd', 3 };
|
||||
CHECK(s.last().pos.tokens == one);
|
||||
const json bad = s.gen({ { "prompt", "x" }, { "sampler", "euler_ancestral" } }, 400);
|
||||
CHECK_EQ(str_at(bad["error"], "param"), std::string("sampler"));
|
||||
CHECK(bad["error"]["supported"] == json::array({ "euler", "dpmpp_2m" }));
|
||||
const json badk = s.gen({ { "prompt", "x" }, { "scheduler", "ddim_uniform" } }, 400);
|
||||
CHECK_EQ(str_at(badk["error"], "param"), std::string("scheduler"));
|
||||
}
|
||||
|
||||
/* `background: auto` keeps an edited picture's transparency and is opaque otherwise; a mask must
|
||||
* be the first picture's size. */
|
||||
/* A model whose card states guidance as cond + s (cond - uncond) and guides by default (Krea 2):
|
||||
|
||||
+4
-3
@@ -1032,8 +1032,9 @@ TEST(a_transformed_or_rotated_weight_is_not_a_site) {
|
||||
CHECK(has(lora::explain_module(b.program(), t, "model.layers.0.self_attn.q_proj"), "perm"));
|
||||
}
|
||||
|
||||
/* Adapters serve the token steps of a model that writes logits: declare refuses a generator, an
|
||||
* embedding model and a program with no logits by name, and lets a text model through. */
|
||||
/* Adapters serve the token steps of a model that writes logits, or a generator that names its
|
||||
* adapter keys: declare refuses a generator that names none, an embedding model and a program with
|
||||
* no logits by name, and lets a text model through. */
|
||||
TEST(declare_refuses_a_model_that_does_not_generate_text) {
|
||||
const RadModelMeta meta = llama_meta();
|
||||
const RadBuildCtx ctx = ctx_for(0, 1);
|
||||
@@ -1044,7 +1045,7 @@ TEST(declare_refuses_a_model_that_does_not_generate_text) {
|
||||
d.cfg = &cfg;
|
||||
d.targets = { "q_proj" };
|
||||
const struct { const char* what; void (*set)(Program&); } kinds[] = {
|
||||
{ "is an image, audio or video generator",
|
||||
{ "declares no adapter key names",
|
||||
[](Program& p) { p.logits_buf = 1; p.generator.layout = 1; } },
|
||||
{ "makes embeddings", [](Program& p) { p.pooled_buf = 1; } },
|
||||
{ "declares no logits", [](Program&) {} },
|
||||
|
||||
@@ -0,0 +1,115 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Writes tests/precompiled_golden.h: expected outputs for precompiled_test.cpp.
|
||||
|
||||
- Unicode 16.0.0's GraphemeBreakTest.txt cases, each a codepoint sequence and the boundaries
|
||||
UAX #29 puts in it (core/text/tokenizer_grapheme.h's grapheme_end);
|
||||
- a small SentencePiece character map and what HuggingFace `tokenizers`' Precompiled normaliser
|
||||
makes of a set of strings through it, clusters that map whole and clusters that do not among
|
||||
them (PrecompiledMap::normalize).
|
||||
|
||||
The map below was built with sentencepiece 0.2 from the rules
|
||||
A -> a, U+FF21 -> A, U+FF41 -> a, e U+0301 -> U+00E9, LF -> space, U+2160 -> I
|
||||
and is kept as base64 so regenerating needs only `tokenizers` (0.23.3 produced the current file):
|
||||
|
||||
python3 tests/mk_precompiled_goldens.py GraphemeBreakTest.txt > tests/precompiled_golden.h
|
||||
"""
|
||||
import base64
|
||||
import sys
|
||||
|
||||
import tokenizers
|
||||
from tokenizers import normalizers
|
||||
|
||||
CHARSMAP = (
|
||||
"AAQAAAAsAAAKDQAAAAAAgAYAAIDMAAIAgQ0AAAgAAICFvAIAoAUAAAQAAIC8nAIAvRACAKEFAAACAACAgTUAAA4AAAARAA"
|
||||
"AAEAAAABMAAAASAAAAFQAAABQAAAAXAAAAFgAAABkAAAAYAAAAGwAAABoAAAAdAAAAHAAAAB8AAAAeAAAAIQAAACAAAAAj"
|
||||
"AAAAIgAAACUAAAAkAAAAJwAAACYAAAApAAAAKAAAACsAAAAqAAAALQAAACwAAAAvAAAALgAAADEAAAAwAAAAMwAAADIAAA"
|
||||
"A1AAAANAAAADcAAAA2AAAAOQAAADgAAAA7AAAAOgAAAD0AAAA8AAAAPwAAAD4AAABBAAAAQAAAAEMAAABCAAAARQAAAEQA"
|
||||
"AABHAAAARgAAAEkAAABIAAAAQSUBAEoAAABNAAAATAAAAE8AAABOAAAAUQAAAFAAAABTAAAAUgAAAFUAAABUAAAAVwAAAF"
|
||||
"YAAABZAAAAWAAAAFsAAABaAAAAXQAAAFwAAABfAAAAXgAAAGEAAABgAAAAYwAAAGIAAABlAAAAZAAAAGcAAABmAAAAaQAA"
|
||||
"AGgAAABrAAAAagAAAG0AAABsAAAAZZgCAG4AAABxAAAAcAAAAHMAAAByAAAAdQAAAHQAAAB3AAAAdgAAAHkAAAB4AAAAew"
|
||||
"AAAHoAAAB9AAAAfAAAAH8AAAB+AAAAgQAAAIAAAACDAAAAggAAAIUAAACEAAAAhwAAAIYAAACJAAAAiAAAAIsAAACKAAAA"
|
||||
"jQAAAIwAAACPAAAAjgAAAJEAAACQAAAAkwAAAJIAAACVAAAAlAAAAJcAAACWAAAAmQAAAJgAAACbAAAAmgAAAJ0AAACcAA"
|
||||
"AAnwAAAJ4AAAChAAAAoAAAAKMAAACiAAAApQAAAKQAAACnAAAApgAAAKkAAACoAAAAqwAAAKoAAACtAAAArAAAAK8AAACu"
|
||||
"AAAAsQAAALAAAACzAAAAsgAAALUAAAC0AAAAtwAAALYAAAC5AAAAuAAAALsAAAC6AAAAvQAAALwAAAC/AAAAvgAAAMEAAA"
|
||||
"DAAAAAwwAAAMIAAADFAAAAxAAAAMcAAADGAAAAyQAAAMgAAADLAAAAygAAAM0AAADMAAAAzwAAAM4AAADRAAAA0AAAANMA"
|
||||
"AADSAAAA1QAAANQAAADXAAAA1gAAANkAAADYAAAA2wAAANoAAADdAAAA3AAAAN8AAADeAAAA4QAAAOAAAADjAAAA4gAAAO"
|
||||
"9IAQDkAAAA5wAAAOYAAADpAAAA4qwBAOsAAADqAAAA7QAAAOwAAADvAAAA7gAAAPEAAADwAAAA8wAAAPIAAAD1AAAA9AAA"
|
||||
"APcAAAD2AAAA+QAAAPgAAAD7AAAA+gAAAP0AAAD8AAAA/wAAAP4AAAAgAEEASQBhAMOpAA=="
|
||||
)
|
||||
|
||||
INPUTS = [
|
||||
"", "plain ascii", "A big Apple", "Abc a", "line one\nline two\n",
|
||||
"café", "éé", "Áx", "Á", "Ⅰ Ⅰ́",
|
||||
"é vs é", "1️⃣ keycap", "\U0001F469\U0001F4BB",
|
||||
"\U0001F1EF\U0001F1F5\U0001F1FA", "각 jamo", "\r\nCRLF\r\n",
|
||||
"क्ष conjunct", "ab", "tab\there", "กำ thai",
|
||||
"ẍ̈̈̈", "Ä̈",
|
||||
]
|
||||
|
||||
|
||||
def cstr(s):
|
||||
out = '"'
|
||||
prev_hex = False
|
||||
for b in s.encode("utf-8"):
|
||||
c = chr(b)
|
||||
if c == '"':
|
||||
out += '\\"'; prev_hex = False
|
||||
elif c == "\\":
|
||||
out += "\\\\"; prev_hex = False
|
||||
elif 0x20 <= b < 0x7F:
|
||||
if prev_hex and c in "0123456789abcdefABCDEF":
|
||||
out += '" "'
|
||||
out += c; prev_hex = False
|
||||
else:
|
||||
out += "\\x%02x" % b; prev_hex = True
|
||||
return out + '"'
|
||||
|
||||
|
||||
def grapheme_cases(path):
|
||||
"""(codepoints, bitmask of the positions a cluster starts at, beyond the first)."""
|
||||
cases = []
|
||||
for line in open(path, encoding="utf-8"):
|
||||
line = line.split("#", 1)[0].strip()
|
||||
if not line:
|
||||
continue
|
||||
toks = line.split()
|
||||
cps, mask = [], 0
|
||||
for t in toks[1:-1]:
|
||||
if t in ("÷", "×"):
|
||||
if t == "÷":
|
||||
mask |= 1 << len(cps)
|
||||
continue
|
||||
cps.append(int(t, 16))
|
||||
cases.append((cps, mask))
|
||||
return cases
|
||||
|
||||
|
||||
def main():
|
||||
pc = normalizers.Precompiled(base64.b64decode(CHARSMAP))
|
||||
w = sys.stdout.write
|
||||
w("/* precompiled_golden.h -- GENERATED by mk_precompiled_goldens.py from tokenizers %s and "
|
||||
"the\n * Unicode 16.0.0 GraphemeBreakTest.txt; do not edit. */\n" % tokenizers.__version__)
|
||||
w("#pragma once\n#include <cstdint>\n\n")
|
||||
w("static const char* kPcCharsmap =\n")
|
||||
for i in range(0, len(CHARSMAP), 96):
|
||||
w(" \"%s\"\n" % CHARSMAP[i:i + 96])
|
||||
w(" ;\n\n")
|
||||
w("struct PcCase { const char* in; const char* out; };\n")
|
||||
w("static const PcCase kPcCases[] = {\n")
|
||||
for s in INPUTS:
|
||||
w(" { %s, %s },\n" % (cstr(s), cstr(pc.normalize_str(s))))
|
||||
w("};\n\n")
|
||||
cases = grapheme_cases(sys.argv[1])
|
||||
w("/* A cluster starts at codepoint i (i > 0) where bit i of `starts` is set. */\n")
|
||||
w("struct GbCase { uint32_t cp[8]; uint32_t n; uint32_t starts; };\n")
|
||||
w("static const GbCase kGbCases[] = {\n")
|
||||
for cps, mask in cases:
|
||||
if len(cps) > 8:
|
||||
continue
|
||||
w(" { { %s }, %d, 0x%x },\n" % (", ".join("0x%X" % c for c in cps), len(cps),
|
||||
mask & ~1))
|
||||
w("};\n")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -246,6 +246,104 @@ def metaspace_specials(scheme):
|
||||
"vocab": vocab, "merges": [[MS, "H"], ["H", "i"], [MS + "H", "i"]]}}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------- CLIP-shaped
|
||||
|
||||
CLIP_SPLIT = r"""'s|'t|'re|'ve|'m|'ll|'d|[\p{L}]+|[\p{N}]|[^\s\p{L}\p{N}]+"""
|
||||
|
||||
|
||||
def gpt2_alphabet():
|
||||
"""GPT-2's byte -> character map, in CLIP's vocabulary order."""
|
||||
bs = list(range(ord("!"), ord("~") + 1)) + list(range(ord("\xa1"), ord("\xac") + 1)) + \
|
||||
list(range(ord("\xae"), ord("\xff") + 1))
|
||||
cs = bs[:]
|
||||
n = 0
|
||||
for b in range(256):
|
||||
if b not in bs:
|
||||
bs.append(b)
|
||||
cs.append(256 + n)
|
||||
n += 1
|
||||
return [chr(c) for c in cs]
|
||||
|
||||
|
||||
CLIP_TRAIN = ("a photo of a cat, a painting of a dog, best quality, masterpiece, 1girl, solo, "
|
||||
"looking at viewer, it's a photograph of the mountains at sunset, don't stop, "
|
||||
"highly detailed digital art, portrait of an astronaut riding a horse, ") * 3
|
||||
|
||||
|
||||
def clip_like():
|
||||
"""CLIP ViT-L/14's tokenizer.json with its vocabulary cut down: the real normaliser, Split,
|
||||
ByteLevel, RobertaProcessing and decoder, the 512 byte tokens with and without the "</w>"
|
||||
end-of-word suffix in CLIP's order, and merges trained here (most frequent pair, then the
|
||||
smallest) over a few prompts, each merged token's id 512 + its rank as in CLIP's own file."""
|
||||
from tokenizers import normalizers, pre_tokenizers, Regex
|
||||
norm = normalizers.Sequence([normalizers.NFC(), normalizers.Replace(Regex(r"\s+"), " "),
|
||||
normalizers.Lowercase()])
|
||||
pre = pre_tokenizers.Sequence([
|
||||
pre_tokenizers.Split(Regex(CLIP_SPLIT), behavior="removed", invert=True),
|
||||
pre_tokenizers.ByteLevel(add_prefix_space=False)])
|
||||
alpha = gpt2_alphabet()
|
||||
vocab = alpha + [c + "</w>" for c in alpha]
|
||||
words = {}
|
||||
for w, _ in pre.pre_tokenize_str(norm.normalize_str(CLIP_TRAIN)):
|
||||
sym = tuple(list(w[:-1]) + [w[-1] + "</w>"])
|
||||
words[sym] = words.get(sym, 0) + 1
|
||||
merges = []
|
||||
for _ in range(160):
|
||||
pairs = {}
|
||||
for sym, n in words.items():
|
||||
for a, b in zip(sym, sym[1:]):
|
||||
pairs[(a, b)] = pairs.get((a, b), 0) + n
|
||||
if not pairs:
|
||||
break
|
||||
best = min(pairs, key=lambda k: (-pairs[k], k))
|
||||
merges.append(best)
|
||||
vocab.append(best[0] + best[1])
|
||||
nw = {}
|
||||
for sym, n in words.items():
|
||||
out, i = [], 0
|
||||
while i < len(sym):
|
||||
if i + 1 < len(sym) and (sym[i], sym[i + 1]) == best:
|
||||
out.append(sym[i] + sym[i + 1])
|
||||
i += 2
|
||||
else:
|
||||
out.append(sym[i])
|
||||
i += 1
|
||||
nw[tuple(out)] = nw.get(tuple(out), 0) + n
|
||||
words = nw
|
||||
bos, eos = len(vocab), len(vocab) + 1
|
||||
vocab += ["<|startoftext|>", "<|endoftext|>"]
|
||||
return {
|
||||
"added_tokens": [
|
||||
{"id": bos, "content": "<|startoftext|>", "single_word": False, "lstrip": False,
|
||||
"rstrip": False, "normalized": True, "special": True},
|
||||
{"id": eos, "content": "<|endoftext|>", "single_word": False, "lstrip": False,
|
||||
"rstrip": False, "normalized": False, "special": True}],
|
||||
"normalizer": {"type": "Sequence", "normalizers": [
|
||||
{"type": "NFC"}, {"type": "Replace", "pattern": {"Regex": r"\s+"}, "content": " "},
|
||||
{"type": "Lowercase"}]},
|
||||
"pre_tokenizer": {"type": "Sequence", "pretokenizers": [
|
||||
{"type": "Split", "pattern": {"Regex": CLIP_SPLIT}, "behavior": "Removed",
|
||||
"invert": True},
|
||||
{"type": "ByteLevel", "add_prefix_space": False, "trim_offsets": True}]},
|
||||
"post_processor": {"type": "RobertaProcessing", "sep": ["<|endoftext|>", eos],
|
||||
"cls": ["<|startoftext|>", bos], "trim_offsets": False,
|
||||
"add_prefix_space": False},
|
||||
"decoder": {"type": "ByteLevel", "add_prefix_space": True, "trim_offsets": True},
|
||||
"model": {"type": "BPE", "dropout": None, "unk_token": "<|endoftext|>",
|
||||
"continuing_subword_prefix": "", "end_of_word_suffix": "</w>",
|
||||
"fuse_unk": False, "vocab": {t: i for i, t in enumerate(vocab)},
|
||||
"merges": [a + " " + b for a, b in merges]},
|
||||
}
|
||||
|
||||
|
||||
CLIP_TEXTS = ["a photo of a cat", "1girl, solo, masterpiece, best quality, (absurdres:1.2), "
|
||||
"looking_at_viewer, hatsune_miku", "A Photograph of the Mountains, it's DON'T stop",
|
||||
"1024x1024 2.5 v1.0", "Café naïve 東京タワー 서울 🍣👩👩👧 İstanbul ΣΊΣΥΦΟΣ",
|
||||
" many spaces\t\ttabs\n\nnewlines ", "...!!!??? ((()))[[]]", "", "a",
|
||||
"<|startoftext|>a cat<|endoftext|>", "x<|StartOfText|>y", "a</w>b catcat",
|
||||
"photographphotograph", "it'sit's'll"]
|
||||
|
||||
|
||||
SPECIAL_TEXTS = ["Hi", "[INST]Hi", "[INST] Hi", "Hi[INST]Hi", "<s>Hi", "Hi Hi[INST]Hi"]
|
||||
|
||||
GEMMA_TEXTS = ["hello", " hello", "hello world", "hello world", "the cat", "\nthe\n\ncat",
|
||||
@@ -341,6 +439,30 @@ def main():
|
||||
print(" return v;")
|
||||
print("}")
|
||||
print()
|
||||
c = clip_like()
|
||||
tok = Tokenizer.from_str(json.dumps(c))
|
||||
print("const char* const kClipLike = R\"JSON(%s)JSON\";" % json.dumps(c, ensure_ascii=False))
|
||||
print()
|
||||
print("const std::vector<EncodeGolden>& clip_goldens() {")
|
||||
print(" static const std::vector<EncodeGolden> v = {")
|
||||
for t in CLIP_TEXTS:
|
||||
a = tok.encode(t, add_special_tokens=False).ids
|
||||
b = tok.encode(t, add_special_tokens=True).ids
|
||||
print(" { %s, %s, %s }," % (cstr(t), ids_cpp(a), ids_cpp(b)))
|
||||
print(" };")
|
||||
print(" return v;")
|
||||
print("}")
|
||||
print()
|
||||
print("/* The decode of every CLIP golden with special tokens skipped, as HF reports it. */")
|
||||
print("const std::vector<const char*>& clip_decoded() {")
|
||||
print(" static const std::vector<const char*> v = {")
|
||||
for t in CLIP_TEXTS:
|
||||
print(" %s," % cstr(tok.decode(tok.encode(t, add_special_tokens=True).ids,
|
||||
skip_special_tokens=True)))
|
||||
print(" };")
|
||||
print(" return v;")
|
||||
print("}")
|
||||
print()
|
||||
print("/* END generated by mk_tokenizer_goldens.py */")
|
||||
|
||||
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,103 @@
|
||||
/* precompiled_test.cpp -- extended grapheme clusters and SentencePiece's precompiled normaliser
|
||||
* (core/text/tokenizer_grapheme.h) against Unicode's own test file and HuggingFace tokenizers'
|
||||
* Precompiled normaliser (goldens: mk_precompiled_goldens.py). */
|
||||
#include "rad_test.h"
|
||||
#include "text/tokenizer.h"
|
||||
#include "text/tokenizer_grapheme.h"
|
||||
|
||||
#include "precompiled_golden.h"
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
using namespace rad;
|
||||
|
||||
/* Every case of Unicode 16.0.0's GraphemeBreakTest.txt: the clusters grapheme_end walks out of the
|
||||
* sequence start where the file breaks it. */
|
||||
TEST(grapheme_clusters_follow_uax29) {
|
||||
int bad = 0;
|
||||
for (const GbCase& g : kGbCases) {
|
||||
uint32_t starts = 0;
|
||||
for (size_t i = 0; i < g.n;) {
|
||||
if (i) starts |= 1u << i;
|
||||
const size_t e = grapheme_end(g.cp, g.n, i);
|
||||
if (e <= i || e > g.n) { ++bad; break; }
|
||||
i = e;
|
||||
}
|
||||
if (starts != g.starts) {
|
||||
if (++bad <= 5) {
|
||||
std::string s;
|
||||
for (uint32_t k = 0; k < g.n; ++k) s += fmt(" %04X", g.cp[k]);
|
||||
fprintf(stderr, " [%s ] starts 0x%x, want 0x%x\n", s.c_str(), starts, g.starts);
|
||||
}
|
||||
}
|
||||
}
|
||||
CHECK_EQ(bad, 0);
|
||||
CHECK(sizeof kGbCases / sizeof kGbCases[0] > 1000);
|
||||
}
|
||||
|
||||
/* A cluster under six bytes goes whole to its shortest mapped prefix's replacement (a combining
|
||||
* accent after a mapped letter is dropped); otherwise each character goes to its own. */
|
||||
TEST(precompiled_normaliser_matches_tokenizers) {
|
||||
PrecompiledMap pm;
|
||||
std::string why;
|
||||
REQUIRE_EQ(pm.load(kPcCharsmap, &why), (int)RAD_OK);
|
||||
for (const PcCase& c : kPcCases) {
|
||||
const std::string got = pm.normalize(c.in);
|
||||
if (got != c.out) fprintf(stderr, " '%s' -> '%s', want '%s'\n", c.in, got.c_str(), c.out);
|
||||
CHECK(got == c.out);
|
||||
}
|
||||
}
|
||||
|
||||
TEST(precompiled_map_refuses_what_does_not_decode) {
|
||||
PrecompiledMap pm;
|
||||
std::string why;
|
||||
CHECK_EQ(pm.load("not base64!", &why), RAD_E_FORMAT);
|
||||
CHECK_EQ(pm.load("AAA=", &why), RAD_E_FORMAT);
|
||||
/* A trie byte count past the map's end. */
|
||||
CHECK_EQ(pm.load("AAEAAA==", &why), RAD_E_FORMAT);
|
||||
CHECK(!pm.ready());
|
||||
}
|
||||
|
||||
/* The normaliser inside a Unigram vocabulary, as T5's tokenizer.json declares it: Precompiled,
|
||||
* a right Strip and a Replace of space runs, then Metaspace. With no tokenizer_config.json beside
|
||||
* it the end token's id is unset, so encoding adds none (HuggingFace's ids: the same pieces, then
|
||||
* </s>). */
|
||||
TEST(precompiled_runs_in_a_tokenizer_json_chain) {
|
||||
const std::string json = std::string(R"({
|
||||
"version": "1.0", "added_tokens": [
|
||||
{"id": 0, "content": "<pad>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": false, "special": true},
|
||||
{"id": 1, "content": "</s>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": false, "special": true},
|
||||
{"id": 2, "content": "<unk>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": false, "special": true}],
|
||||
"normalizer": {"type": "Sequence", "normalizers": [
|
||||
{"type": "Precompiled", "precompiled_charsmap": ")") + kPcCharsmap + R"("},
|
||||
{"type": "Strip", "strip_left": false, "strip_right": true},
|
||||
{"type": "Replace", "pattern": {"Regex": " {2,}"}, "content": "▁"}]},
|
||||
"pre_tokenizer": {"type": "Metaspace", "replacement": "▁", "prepend_scheme": "first", "split": true},
|
||||
"post_processor": {"type": "TemplateProcessing",
|
||||
"single": [{"Sequence": {"id": "A", "type_id": 0}}, {"SpecialToken": {"id": "</s>", "type_id": 0}}],
|
||||
"pair": [{"Sequence": {"id": "A", "type_id": 0}}, {"SpecialToken": {"id": "</s>", "type_id": 0}}],
|
||||
"special_tokens": {"</s>": {"id": "</s>", "ids": [1], "tokens": ["</s>"]}}},
|
||||
"decoder": {"type": "Metaspace", "replacement": "▁", "prepend_scheme": "always", "split": true},
|
||||
"model": {"type": "Unigram", "unk_id": 2, "vocab": [
|
||||
["<pad>", 0.0], ["</s>", 0.0], ["<unk>", 0.0], ["▁", -2.0], ["▁a", -3.0], ["a", -4.0],
|
||||
["▁big", -3.0], ["b", -5.0], ["i", -5.0], ["g", -5.0], ["▁apple", -3.0], ["p", -5.0],
|
||||
["l", -5.0], ["e", -5.0], ["é", -5.0], ["▁café", -3.0], ["c", -5.0], ["f", -5.0]]}
|
||||
})";
|
||||
VocabBuild vb;
|
||||
REQUIRE_EQ(parse_tokenizer_json_buf(json, "t5-like", vb), (int)RAD_OK);
|
||||
auto v = std::make_shared<Vocab>();
|
||||
REQUIRE_EQ(v->load(std::move(vb)), (int)RAD_OK);
|
||||
Tokenizer tok;
|
||||
REQUIRE_EQ(tok.init(v), (int)RAD_OK);
|
||||
std::vector<int32_t> ids;
|
||||
REQUIRE_EQ(tok.encode("A big Apple", ids, true, true), (int)RAD_OK);
|
||||
CHECK(ids == std::vector<int32_t>({ 4, 6, 10 }));
|
||||
ids.clear();
|
||||
/* The fullwidth A normalises to an A the vocabulary lacks, and the decomposed accent to the
|
||||
* piece it holds. */
|
||||
REQUIRE_EQ(tok.encode("\xef\xbc\xa1 cafe\xcc\x81", ids, true, true), (int)RAD_OK);
|
||||
CHECK(ids == std::vector<int32_t>({ 3, 2, 15 }));
|
||||
}
|
||||
|
||||
RAD_TEST_MAIN()
|
||||
@@ -511,6 +511,74 @@ static void test_codes() {
|
||||
checked);
|
||||
}
|
||||
|
||||
/* lora_expand_mm (the generators' expand): t rounded to bf16 and summed on the WMMA in its own
|
||||
* order, so each output is held to the double sum over bf16(t) within one rounding of y plus the
|
||||
* f32 sum's bound; base rows and everything outside the slice untouched, bit for bit. Mixed slots
|
||||
* in a tile, an odd M and N, R not a multiple of 32, every y dtype, aligned and not. */
|
||||
static void test_expand_mm() {
|
||||
std::mt19937 rng(41);
|
||||
struct Sh { int M, N, R, S; uint32_t ydt; bool al; int base_pct; };
|
||||
const Sh shapes[] = {
|
||||
{ 1, 20, 16, 1, RAD_BF16, true, 0 },
|
||||
{ 64, 64, 32, 1, RAD_BF16, true, 0 },
|
||||
{ 130, 300, 48, 2, RAD_BF16, false, 20 },
|
||||
{ 77, 9216, 192, 1, RAD_BF16, true, 0 }, /* a fused qkv, one adapter */
|
||||
{ 200, 1000, 64, 3, RAD_F32, false, 30 },
|
||||
{ 65, 257, 24, 2, RAD_F16, true, 10 },
|
||||
{ 512, 2048, 128, 1, RAD_BF16, true, 0 },
|
||||
};
|
||||
int64_t worst_n = 0;
|
||||
double worst = 0;
|
||||
for (const Sh& sh : shapes) {
|
||||
const std::vector<int32_t> slot = rand_slots(rng, sh.M, sh.S, sh.base_pct);
|
||||
Expand E = make_expand(rng, sh.M, sh.N, sh.R, sh.S, sh.ydt, slot, sh.al);
|
||||
std::vector<uint8_t> got;
|
||||
if (run_expand(E, r4d_rad_lora_expand_mm, &got) != RAD_OK) {
|
||||
fail("expand_mm", fmt("rc (M %d N %d R %d)", sh.M, sh.N, sh.R));
|
||||
continue;
|
||||
}
|
||||
const size_t e = esz(sh.ydt), ny = (size_t)E.yoff + (size_t)sh.M * E.ldy;
|
||||
int64_t bad_base = 0, bad_val = 0;
|
||||
for (size_t i = 0; i < ny; ++i) {
|
||||
const long long q = (long long)i - E.yoff;
|
||||
const int m = q < 0 ? -1 : (int)(q / E.ldy), n = q < 0 ? -1 : (int)(q % E.ldy);
|
||||
const int sl = m >= 0 && m < sh.M ? slot[(size_t)m] : -1;
|
||||
if (m < 0 || m >= sh.M || n >= sh.N || sl < 0 || sl >= sh.S) {
|
||||
bad_base += std::memcmp(&got[i * e], &E.y0[i * e], e) != 0;
|
||||
continue;
|
||||
}
|
||||
double acc = 0, terms = 0;
|
||||
for (int j = 0; j < sh.R; ++j) {
|
||||
const double tv = rad_bf16_to_f32(rad_f32_to_bf16(E.t[(size_t)m * sh.R + j]));
|
||||
const double bv = rad_bf16_to_f32(E.lb[((size_t)sl * sh.N + n) * sh.R + j]);
|
||||
acc += tv * bv;
|
||||
terms += std::fabs(tv * bv);
|
||||
}
|
||||
const double sc = E.sc[(size_t)sl * sh.N + n];
|
||||
const double y0 = lora_cases::get(sh.ydt, E.y0.data(), i);
|
||||
const double want = y0 + sc * acc;
|
||||
const double g = lora_cases::get(sh.ydt, got.data(), i);
|
||||
if (std::isnan(y0)) { bad_val += !std::isnan(g); continue; }
|
||||
const double ulp = sh.ydt == RAD_BF16 ? std::ldexp(1.0, -8)
|
||||
: sh.ydt == RAD_F16 ? std::ldexp(1.0, -10) : std::ldexp(1.0, -23);
|
||||
const double tol = std::fabs(want) * ulp + sc * terms * (sh.R + 2) * std::ldexp(1.0, -24) +
|
||||
1e-30;
|
||||
const double r = std::fabs(g - want) / tol;
|
||||
worst = std::max(worst, r);
|
||||
if (r > 1.0) ++bad_val;
|
||||
++worst_n;
|
||||
}
|
||||
if (bad_base)
|
||||
fail("expand_mm", fmt("touched %lld base-row / outside bytes (M %d N %d R %d %s)",
|
||||
(long long)bad_base, sh.M, sh.N, sh.R, rad_dtype_name(sh.ydt)));
|
||||
if (bad_val)
|
||||
fail("expand_mm", fmt("%lld outputs outside the bound (M %d N %d R %d %s)",
|
||||
(long long)bad_val, sh.M, sh.N, sh.R, rad_dtype_name(sh.ydt)));
|
||||
}
|
||||
std::printf("lora expand_mm: %zu shapes, %lld outputs, worst |err|/bound %.3f\n",
|
||||
sizeof(shapes) / sizeof(shapes[0]), (long long)worst_n, worst);
|
||||
}
|
||||
|
||||
int main() {
|
||||
LaunchFn rs = nullptr, re = nullptr;
|
||||
load_libref(&rs, &re);
|
||||
@@ -532,6 +600,7 @@ int main() {
|
||||
test_invariance();
|
||||
test_all_base();
|
||||
test_codes();
|
||||
test_expand_mm();
|
||||
std::printf("lora tiled rows: %d failure(s)\n", g_fails);
|
||||
return (T.fails != 0 || g_fails != 0) ? 1 : 0;
|
||||
}
|
||||
+193
-3
@@ -939,7 +939,7 @@ TEST(op_vocabulary) {
|
||||
"dequant",
|
||||
"gemm_nt", "gemm_nt_bias", "gemm_nt_q", "gemm_nt_q_bias", "grid_embed",
|
||||
/* Runtime LoRA's two halves, issued by the core beside a trunk GEMM. */
|
||||
"lora_shrink", "lora_expand",
|
||||
"lora_shrink", "lora_expand", "lora_expand_mm",
|
||||
"grid_embed_aa",
|
||||
"attn_paged", "attn_dense", "kv_store", "rope", "rope_table", "qk_norm_rope", "qsa_block_key",
|
||||
/* The rest of the QSA indexer and DFlash2's convolution: not fusions, so a model that
|
||||
@@ -958,9 +958,12 @@ TEST(op_vocabulary) {
|
||||
/* The image generator's (arch/qwenimage21): a DiT's modulation and gates, the per-lane
|
||||
* sampler state, the VAE's convolutions and shortcuts, attention over a cached prefix. */
|
||||
"ln_mod", "gate_add", "timestep_embed", "gather_rows2", "lane_gather", "lane_store",
|
||||
"randn_lanes", "flow_euler", "chan_affine", "conv2d_nhwc", "l2norm_chan", "d2s_add",
|
||||
"s2d_avg_add", "to_rgba8", "gelu_tanh", "scatter_add_rows", "attn_prefix_self",
|
||||
"randn_lanes", "flow_euler", "chan_affine", "conv2d_nhwc", "im2col_nhwc", "l2norm_chan",
|
||||
"d2s_add", "s2d_avg_add", "to_rgba8", "gelu_tanh", "scatter_add_rows", "attn_prefix_self",
|
||||
"ln_mod_quant_fp8",
|
||||
/* SDXL's (arch/sdxl): CLIP-L's activation and the k-diffusion sampler over a
|
||||
* discrete-time denoiser. */
|
||||
"gelu_quick", "kd_input", "kd_step",
|
||||
/* The music generator's (arch/minimaxmusic3): the codec's convolutions and activation, the
|
||||
* guided frame sampler and the frame embeddings, the window states of the latent
|
||||
* denoiser, and the index helpers that feed them. */
|
||||
@@ -5554,6 +5557,136 @@ TEST(flow_euler_guides_previews_and_repaints_as_stated) {
|
||||
CHECK_EQ(state.at(8), 7.0f); CHECK_EQ(state.at(9), 8.0f);
|
||||
}
|
||||
|
||||
/* kd_input: entry 0's first step fills its lane with the seed's stream times sqrt(1 + sigma^2)
|
||||
* and writes x / sqrt(sigma^2 + 1) to its rows and its pair's (entry 1, pair -2, writes nothing of
|
||||
* its own); entry 2 reads its lane as it is. */
|
||||
TEST(kd_input_starts_the_lane_and_scales_by_c_in) {
|
||||
const int64_t n = 2, st = 2;
|
||||
const uint64_t seed = 0xabcdef12345ull;
|
||||
T sg(RAD_F32, {3}); sg.f({3, 3, 1});
|
||||
T pair(RAD_I32, {3}); pair.n({1, -2, -1});
|
||||
T lane(RAD_I32, {3}); lane.n({0, 1, 2});
|
||||
T fl(RAD_I32, {3}); fl.n({1, 0, 0});
|
||||
T sd(RAD_U32, {3, 2}); sd.n({(int64_t)(seed & 0xffffffffu), (int64_t)(seed >> 32), 0, 0, 5, 0});
|
||||
T cu(RAD_I32, {4}); cu.n({0, 2, 4, 5});
|
||||
T state(RAD_F32, {3 * st, n}); state.f({0, 0, 0, 0, 7, 7, 7, 7, 4, -2, 9, 9});
|
||||
T y(RAD_F32, {5, n});
|
||||
A a; a.t(sg).t(pair).t(lane).t(fl).t(sd).t(cu).t(state).t(y).i("M", 5).i("n", n)
|
||||
.i("stride", st).s("dtype", "f32");
|
||||
CHECK_OK(run("kd_input", a));
|
||||
const float init = std::sqrt(1.0f + 9.0f), cin = 1.0f / std::sqrt(9.0f + 1.0f);
|
||||
for (int64_t k = 0; k < 2; ++k)
|
||||
for (int64_t c = 0; c < n; ++c) {
|
||||
const float x0 = rad_philox_normal(seed, (uint64_t)(k * n + c)) * init;
|
||||
CHECK_EQ(state.at(k * n + c), x0);
|
||||
CHECK_EQ(y.at(k * n + c), x0 * cin);
|
||||
CHECK_EQ(y.at((2 + k) * n + c), x0 * cin);
|
||||
CHECK_EQ(state.at((st + k) * n + c), 7.0f); /* the parked entry's lane */
|
||||
}
|
||||
CHECK_NEAR(y.at(8), 4.0f / std::sqrt(2.0f), 1e-6); CHECK_NEAR(y.at(9), -2.0f / std::sqrt(2.0f), 1e-6);
|
||||
/* A repaint is refused. */
|
||||
T fl2(RAD_I32, {3}); fl2.n({2, 0, 0});
|
||||
A b; b.t(sg).t(pair).t(lane).t(fl2).t(sd).t(cu).t(state).t(y).i("M", 5).i("n", n)
|
||||
.i("stride", st).s("dtype", "f32");
|
||||
CHECK_EQ(run("kd_input", b), RAD_E_UNSUPPORTED);
|
||||
}
|
||||
|
||||
/* kd_step, one element an entry: Euler guided against a parked entry with a preview; Euler
|
||||
* ancestral at sigma_next 0 and above it; DPM++ 2M's first step, its second-order step and its
|
||||
* last step; and a v-prediction model. */
|
||||
TEST(kd_step_denoises_guides_and_steps_each_sampler) {
|
||||
const int64_t n = 1, st = 1;
|
||||
/* entry: 0 euler guided, 1 parked, 2 ancestral to 0, 3 ancestral, 4 dpm first, 5 dpm second,
|
||||
* 6 dpm last */
|
||||
T o(RAD_F32, {7, n}); o.f({0.5f, 0.25f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f});
|
||||
T sg(RAD_F32, {7}); sg.f({2, 2, 2, 2, 2, 2, 2});
|
||||
T sgn(RAD_F32, {7}); sgn.f({1, 1, 0, 1, 1, 1, 0});
|
||||
T sgp(RAD_F32, {7}); sgp.f({0, 0, 0, 0, 0, 4, 4});
|
||||
T cfg(RAD_F32, {7}); cfg.f({3, 1, 1, 1, 1, 1, 1});
|
||||
T pair(RAD_I32, {7}); pair.n({1, -2, -1, -1, -1, -1, -1});
|
||||
T lane(RAD_I32, {7}); lane.n({0, 1, 2, 3, 4, 5, 6});
|
||||
T fl(RAD_I32, {7}); fl.n({4, 0, 0, 0, 1, 0, 0});
|
||||
T sd(RAD_U32, {7, 2}); sd.n({0, 0, 0, 0, 0, 0, 77, 0, 0, 0, 0, 0, 0, 0});
|
||||
T smp(RAD_I32, {7}); smp.n({0, 0, 1, 1, 2, 2, 2});
|
||||
T stp(RAD_I32, {7}); stp.n({0, 0, 0, 5, 0, 1, 2});
|
||||
T cu(RAD_I32, {8}); cu.n({0, 1, 2, 3, 4, 5, 6, 7});
|
||||
T state(RAD_F32, {7, n}); state.f({2, 9, 2, 2, 2, 2, 2});
|
||||
T hist(RAD_F32, {7, n}); hist.f({0, 0, 0, 0, 0, 0.5f, 0});
|
||||
T prev(RAD_F32, {7, n});
|
||||
A a; a.t(o).t(sg).t(sgn).t(sgp).t(cfg).t(pair).t(lane).t(fl).t(sd).t(smp).t(stp).t(cu)
|
||||
.t(state).t(hist).t(prev).i("M", 7).i("n", n).i("stride", st).s("pred", "eps")
|
||||
.s("dtype", "f32");
|
||||
CHECK_OK(run("kd_step", a));
|
||||
/* D = x - sigma o: 1 for the positive entry, 1.5 for its negative, guided 1.5 + 3 (1 - 1.5) =
|
||||
* 0; Euler: x + (1 - 2)(2 - 0) / 2 = 1. */
|
||||
CHECK_EQ(prev.at(0), 0.0f);
|
||||
CHECK_EQ(state.at(0), 1.0f);
|
||||
CHECK_EQ(hist.at(0), 0.0f);
|
||||
CHECK_EQ(state.at(1), 9.0f); /* parked */
|
||||
CHECK_EQ(state.at(2), 1.0f); /* ancestral to 0: D */
|
||||
{
|
||||
/* sigma_up = min(1, sqrt(1 (4 - 1) / 4)) = sqrt(0.75), sigma_down = sqrt(1 - 0.75). */
|
||||
const float sup = std::sqrt(0.75f), sdown = std::sqrt(1.0f - sup * sup);
|
||||
const float d = (2.0f - 1.0f) / 2.0f;
|
||||
const float want = 2.0f + d * (sdown - 2.0f) + rad_philox_normal_s(77, 6, 0) * sup;
|
||||
CHECK_NEAR(state.at(3), want, 1e-6);
|
||||
}
|
||||
/* DPM++ 2M: h = ln 2, so x' = x / 2 - expm1(-ln 2) D = 1 + 0.5 D' with D = 1. */
|
||||
CHECK_NEAR(state.at(4), 1.5f, 1e-6);
|
||||
/* r = (ln 4 - ln 2) / ln 2 = 1: D' = 1.5 D - 0.5 hist = 1.25. */
|
||||
CHECK_NEAR(state.at(5), 1.625f, 1e-6);
|
||||
CHECK_EQ(state.at(6), 1.0f); /* to sigma 0: D */
|
||||
CHECK_EQ(hist.at(5), 1.0f);
|
||||
|
||||
/* v-prediction at sigma 1: D = x / 2 - o / sqrt(2), so o = sqrt(2) at x = 2 gives D = 0, and
|
||||
* Euler to 0 lands on it. */
|
||||
T ov(RAD_F32, {1, 1}); ov.f({std::sqrt(2.0f)});
|
||||
T s1(RAD_F32, {1}); s1.f({1});
|
||||
T z1(RAD_F32, {1}); z1.f({0});
|
||||
T c1(RAD_F32, {1}); c1.f({1});
|
||||
T p1(RAD_I32, {1}); p1.n({-1});
|
||||
T l1(RAD_I32, {1}); l1.n({0});
|
||||
T f1(RAD_I32, {1}); f1.n({0});
|
||||
T d1(RAD_U32, {1, 2}); d1.n({0, 0});
|
||||
T m1(RAD_I32, {1}); m1.n({0});
|
||||
T cu1(RAD_I32, {2}); cu1.n({0, 1});
|
||||
T x1(RAD_F32, {1, 1}); x1.f({2});
|
||||
T h1(RAD_F32, {1, 1});
|
||||
A b; b.t(ov).t(s1).t(z1).t(z1).t(c1).t(p1).t(l1).t(f1).t(d1).t(m1).t(m1).t(cu1).t(x1).t(h1)
|
||||
.i("M", 1).i("n", 1).i("stride", 1).s("pred", "v").s("dtype", "f32");
|
||||
CHECK_OK(run("kd_step", b));
|
||||
CHECK_NEAR(x1.at(0), 0.0f, 1e-6);
|
||||
|
||||
/* An unknown sampler is refused, and so is a preview without its operand. */
|
||||
T bad(RAD_I32, {1}); bad.n({3});
|
||||
A c; c.t(ov).t(s1).t(z1).t(z1).t(c1).t(p1).t(l1).t(f1).t(d1).t(bad).t(m1).t(cu1).t(x1).t(h1)
|
||||
.i("M", 1).i("n", 1).i("stride", 1).s("pred", "v").s("dtype", "f32");
|
||||
CHECK_EQ(run("kd_step", c), RAD_E_UNSUPPORTED);
|
||||
T f4(RAD_I32, {1}); f4.n({4});
|
||||
A d; d.t(ov).t(s1).t(z1).t(z1).t(c1).t(p1).t(l1).t(f4).t(d1).t(m1).t(m1).t(cu1).t(x1).t(h1)
|
||||
.i("M", 1).i("n", 1).i("stride", 1).s("pred", "v").s("dtype", "f32");
|
||||
CHECK_EQ(run("kd_step", d), RAD_E_INVAL);
|
||||
}
|
||||
|
||||
/* gelu_quick rounds the scaled input and the sigmoid to y's dtype before the product. */
|
||||
TEST(gelu_quick_rounds_like_torch_in_bf16) {
|
||||
T x(RAD_BF16, {1, 3}); x.f({1.0f, -2.0f, 0.375f});
|
||||
T y(RAD_BF16, {1, 3});
|
||||
A a; a.t(x).t(y).i("M", 1).i("n", 3).s("dtype", "bf16");
|
||||
CHECK_OK(run("gelu_quick", a));
|
||||
for (int i = 0; i < 3; ++i) {
|
||||
const float v = x.at(i);
|
||||
const float t = round_dt(RAD_BF16, 1.702f * v);
|
||||
const float s = round_dt(RAD_BF16, 1.0f / (1.0f + std::exp(-t)));
|
||||
CHECK_EQ(y.at(i), round_dt(RAD_BF16, v * s));
|
||||
}
|
||||
T xf(RAD_F32, {1, 1}); xf.f({0.5f});
|
||||
T yf(RAD_F32, {1, 1});
|
||||
A b; b.t(xf).t(yf).i("M", 1).i("n", 1).s("dtype", "f32");
|
||||
CHECK_OK(run("gelu_quick", b));
|
||||
CHECK_EQ(yf.at(0), 0.5f * (1.0f / (1.0f + std::exp(-0.851f))));
|
||||
}
|
||||
|
||||
/* chan_affine: lists are bf16 values; fma is bf16(bf16(x * mul) + add) and inv its inverse. */
|
||||
TEST(chan_affine_reads_bf16_lists_and_inverts) {
|
||||
T x(RAD_BF16, {1, 3}); x.f({1, 1, 1});
|
||||
@@ -5628,6 +5761,56 @@ TEST(conv2d_nhwc_pads_and_upsamples) {
|
||||
for (int i = 0; i < 16; ++i) CHECK_EQ(y2.at(i), want[i]);
|
||||
}
|
||||
|
||||
/* im2col_nhwc: its rows times the weight read as [cout, cin k k] are conv2d_nhwc, at both paddings
|
||||
* of a stride-2 conv, the upsample and a 1x1, with x at a row pitch. Small integers keep every sum
|
||||
* exact, so the two orders of accumulation agree to the bit. */
|
||||
TEST(im2col_nhwc_times_the_weight_is_the_convolution) {
|
||||
struct Case { const char* pad; int64_t cin, cout, k, stride, up, H, W; };
|
||||
for (const Case& c : { Case{ "same", 3, 4, 3, 1, 1, 5, 6 }, Case{ "same", 2, 3, 3, 2, 1, 7, 5 },
|
||||
Case{ "down", 3, 2, 3, 2, 1, 6, 8 }, Case{ "same", 2, 3, 3, 1, 2, 3, 4 },
|
||||
Case{ "same", 5, 2, 1, 1, 1, 4, 3 } }) {
|
||||
const bool down = !std::strcmp(c.pad, "down");
|
||||
const int64_t Hv = c.H * c.up, Wv = c.W * c.up, pads = down ? 1 : 2 * (c.k / 2);
|
||||
const int64_t Ho = (Hv + pads - c.k) / c.stride + 1, Wo = (Wv + pads - c.k) / c.stride + 1;
|
||||
const int64_t KK = c.cin * c.k * c.k, ld = c.W * c.cin + 3;
|
||||
std::vector<float> xv((size_t)(c.H * ld)), wv((size_t)(c.cout * KK)), bv((size_t)c.cout);
|
||||
for (size_t i = 0; i < xv.size(); ++i) xv[i] = (float)((int)(i * 7 % 11) - 5);
|
||||
for (size_t i = 0; i < wv.size(); ++i) wv[i] = (float)((int)(i * 5 % 7) - 3);
|
||||
for (size_t i = 0; i < bv.size(); ++i) bv[i] = (float)i - 1.0f;
|
||||
T xbuf(RAD_F32, {c.H, ld}); xbuf.f(xv);
|
||||
T x = xbuf;
|
||||
x.t.shape[1] = c.W * c.cin; /* [H, W cin] at a row pitch of ld */
|
||||
T w(RAD_F32, {c.cout, c.cin, c.k, c.k}); w.f(wv);
|
||||
T w2(RAD_F32, {c.cout, KK}); w2.f(wv);
|
||||
T b(RAD_F32, {c.cout}); b.f(bv);
|
||||
T y(RAD_F32, {Ho, Wo * c.cout});
|
||||
A a; a.t(x).t(w).t(b).t(y).i("M", Ho * Wo).i("cin", c.cin).i("cout", c.cout).i("k", c.k)
|
||||
.i("stride", c.stride).s("pad", c.pad).i("up", c.up).s("dtype", "f32");
|
||||
CHECK_OK(run("conv2d_nhwc", a));
|
||||
T u(RAD_F32, {Ho * Wo, KK});
|
||||
A d; d.t(x).t(u).i("M", Ho * Wo).i("cin", c.cin).i("k", c.k).i("stride", c.stride)
|
||||
.s("pad", c.pad).i("up", c.up).s("dtype", "f32");
|
||||
CHECK_OK(run("im2col_nhwc", d));
|
||||
T g(RAD_F32, {Ho * Wo, c.cout});
|
||||
A e; e.t(u).t(w2).t(b).tnull().t(g).i("M", Ho * Wo).i("N", c.cout).i("K", KK)
|
||||
.s("dtype", "f32");
|
||||
CHECK_OK(run("gemm_nt_bias", e));
|
||||
for (int64_t i = 0; i < Ho * Wo * c.cout; ++i) CHECK_EQ(g.at(i), y.at(i));
|
||||
/* Spot the column order: (ci, i, j), the weight's own. */
|
||||
const int64_t oy = Ho - 1, ox = 0, ci = c.cin - 1, i = c.k - 1, j = 0;
|
||||
const int64_t iy = oy * c.stride + i - (down ? 0 : c.k / 2);
|
||||
const int64_t ix = ox * c.stride + j - (down ? 0 : c.k / 2);
|
||||
const float want = iy < 0 || iy >= Hv || ix < 0 || ix >= Wv
|
||||
? 0.0f : xv[(size_t)((iy / c.up) * ld + (ix / c.up) * c.cin + ci)];
|
||||
CHECK_EQ(u.at((oy * Wo + ox) * KK + (ci * c.k + i) * c.k + j), want);
|
||||
}
|
||||
/* y must be exactly the output pixels. */
|
||||
T x(RAD_F32, {3, 3}), y(RAD_F32, {8, 9});
|
||||
A a; a.t(x).t(y).i("M", 8).i("cin", 1).i("k", 3).i("stride", 1).s("pad", "same").i("up", 1)
|
||||
.s("dtype", "f32");
|
||||
CHECK_EQ(run("im2col_nhwc", a), RAD_E_SHAPE);
|
||||
}
|
||||
|
||||
/* l2norm_chan: each pixel to unit L2, times sqrt(n), times gamma, then the optional silu; an
|
||||
* all-zero pixel stays zero (the 1e-12 floor). */
|
||||
TEST(l2norm_chan_normalises_each_pixel) {
|
||||
@@ -7797,6 +7980,7 @@ std::vector<Geo> geometries() {
|
||||
.s("dtype", "fp8a8")),
|
||||
G("lora_shrink", "M", 3, a.i("M", R).i("K", 40).i("R", 8).i("S", 2).s("dtype", "f32")),
|
||||
G("lora_expand", "M", 3, a.i("M", R).i("N", 20).i("R", 8).i("S", 2).s("dtype", "f32")),
|
||||
G("lora_expand_mm", "M", 3, a.i("M", R).i("N", 20).i("R", 8).i("S", 2).s("dtype", "f32")),
|
||||
G("attn_paged", "q_len", 3, a.i("q_len", R).i("head_dim", 8).i("gqa", 2).i("block_size", 4)
|
||||
.i("causal", 1).i("window", 0).s("q_dtype", "f32")
|
||||
.s("kv_dtype", "f32").i("n_head", 4).i("ctx", 9)),
|
||||
@@ -7886,15 +8070,21 @@ std::vector<Geo> geometries() {
|
||||
G("lane_store", "M", 4, a.i("M", R).i("n", 8).i("stride", 8).s("dtype", "bf16")),
|
||||
G("randn_lanes", "M", 4, a.i("M", R).i("n", 8).i("stride", 4).s("dtype", "bf16")),
|
||||
G("flow_euler", "M", 4, a.i("M", R).i("n", 8).i("stride", 4).s("dtype", "bf16")),
|
||||
G("kd_input", "M", 4, a.i("M", R).i("n", 4).i("stride", 4).s("dtype", "bf16")),
|
||||
G("kd_step", "M", 4, a.i("M", R).i("n", 4).i("stride", 4).s("pred", "eps")
|
||||
.s("dtype", "bf16")),
|
||||
G("chan_affine", "M", 2, a.i("M", R).i("n", 3).s("mul", "1 2 3").s("add", "0 1 2")
|
||||
.s("mode", "fma").s("dtype", "bf16")),
|
||||
G("conv2d_nhwc", "M", 16, a.i("M", R).i("cin", 2).i("cout", 3).i("k", 3).i("stride", 1)
|
||||
.s("pad", "same").i("up", 1).s("dtype", "bf16")),
|
||||
G("im2col_nhwc", "M", 16, a.i("M", R).i("cin", 2).i("k", 3).i("stride", 1)
|
||||
.s("pad", "same").i("up", 1).s("dtype", "bf16")),
|
||||
G("l2norm_chan", "M", 3, a.i("M", R).i("n", 8).s("act", "silu").s("dtype", "f32")),
|
||||
G("d2s_add", "M", 16, a.i("M", R).i("cin", 4).i("cout", 2).i("ft", 1).s("dtype", "bf16")),
|
||||
G("s2d_avg_add", "M", 16, a.i("M", R).i("cin", 2).i("cout", 4).i("ft", 1).s("dtype", "bf16")),
|
||||
G("to_rgba8", "M", 3, a.i("M", R).i("n", 8).s("dtype", "f32")),
|
||||
G("gelu_tanh", "M", 3, a.i("M", R).i("n", 8).s("dtype", "f32")),
|
||||
G("gelu_quick", "M", 3, a.i("M", R).i("n", 8).s("dtype", "f32")),
|
||||
G("scatter_add_rows", "M", 3, a.i("M", R).i("n", 8).s("dtype", "f32")),
|
||||
G("attn_prefix_self", "q_len", 3, a.i("q_len", R).i("head_dim", 8).i("gqa", 2)
|
||||
.i("block_size", 4).i("causal", 1).s("q_dtype", "bf16")
|
||||
|
||||
+35
-2
@@ -918,7 +918,7 @@ TEST(raw_operand_carries_the_pointer_and_refuses_an_offset) {
|
||||
* lora_shrink and lora_expand over its own activation, output and rows, but only on a step that
|
||||
* has an adapter row (RadBatch::lora_slot non-null). A step without one, or a draft pass, issues
|
||||
* the gemm alone, the pass an engine without adapters runs; an encoder pass reaching a site is
|
||||
* refused by name. */
|
||||
* refused by name; a generator pass runs its one slot in every row. */
|
||||
static int k_gemm (const RadArgs* a, RadStream s) { return record("gemm", a, s); }
|
||||
static int k_shrink(const RadArgs* a, RadStream s) { return record("shrink", a, s); }
|
||||
static int k_expand(const RadArgs* a, RadStream s) { return record("expand", a, s); }
|
||||
@@ -933,6 +933,7 @@ TEST(adapter_ops_follow_a_lora_site_only_on_a_step_with_an_adapter_row) {
|
||||
const rad_buf ps = f.add_buffer("lora.scale", RAD_F32, 2, 8, 1536);
|
||||
const rad_buf t0 = f.add_buffer("lora.t0", RAD_F32, 16, 4, 2048);
|
||||
const rad_buf t1 = f.add_buffer("lora.t1", RAD_F32, 16, 4, 2304);
|
||||
const rad_buf rows = f.add_buffer("lora.rows", RAD_I32, 32, 1, 2560); /* [S * 16] */
|
||||
const rad_op g = f.add_op("gemm_nt", "M", { 64 }, { k_gemm }, { "gemm" }, &g_gemm_schema, { w });
|
||||
const rad_op sh = f.add_op("lora_shrink", "M", { 64 }, { k_shrink }, { "shrink" }, nullptr, {});
|
||||
const rad_op ex = f.add_op("lora_expand", "M", { 64 }, { k_expand }, { "expand" }, nullptr, {});
|
||||
@@ -955,6 +956,8 @@ TEST(adapter_ops_follow_a_lora_site_only_on_a_step_with_an_adapter_row) {
|
||||
scr.R = 4;
|
||||
scr.lane[0] = t0; scr.lane[1] = t1;
|
||||
f.P.lora_t.push_back(scr);
|
||||
f.P.lora_rows = rows;
|
||||
f.P.lora_rows_n = 16;
|
||||
CHECK_OK(f.start());
|
||||
|
||||
auto body = [&](Ctx& c) {
|
||||
@@ -1002,8 +1005,38 @@ TEST(adapter_ops_follow_a_lora_site_only_on_a_step_with_an_adapter_row) {
|
||||
c.issue(g, opd, 3, RAD_N_BATCH);
|
||||
});
|
||||
CHECK_EQ(s, RAD_E_UNSUPPORTED);
|
||||
CHECK(std::strstr(f.ctx.step_error(), "encoder or generator pass") != nullptr);
|
||||
CHECK(std::strstr(f.ctx.step_error(), "encoder pass") != nullptr);
|
||||
CHECK_EQ(names(), std::string("gemm"));
|
||||
|
||||
/* A generator pass runs one slot in every row, whatever the gemm's rows are: its slot operand
|
||||
* is that slot's run of the slot-row table; with no slot, the gemm alone. */
|
||||
f.batch.enc = 0;
|
||||
f.batch.gen = RAD_GEN_PASS_DENOISE;
|
||||
f.batch.lora_slot = nullptr;
|
||||
f.ctx.set_gen_lora_slot(-1);
|
||||
g_rec.clear();
|
||||
CHECK_OK(f.step(4, 4, body));
|
||||
CHECK_EQ(names(), std::string("gemm"));
|
||||
f.ctx.set_gen_lora_slot(1);
|
||||
g_rec.clear();
|
||||
CHECK_OK(f.step(4, 5, body));
|
||||
REQUIRE_EQ(names(), std::string("gemm shrink expand"));
|
||||
CHECK(g_rec[1].t[2].data == (void*)((char*)f.ctx.buf_ptr(rows) + 1 * 16 * 4));
|
||||
CHECK_EQ(g_rec[1].t[2].shape[0], (int64_t)4);
|
||||
CHECK(g_rec[2].t[1].data == g_rec[1].t[2].data);
|
||||
/* Rows past the slot table's run are issued in chunks of it, each over its own rows. */
|
||||
f.P.lora_rows_n = 3;
|
||||
g_rec.clear();
|
||||
CHECK_OK(f.step(4, 6, body));
|
||||
REQUIRE_EQ(names(), std::string("gemm shrink expand shrink expand"));
|
||||
CHECK_EQ(g_rec[1].t[0].shape[0], (int64_t)3);
|
||||
CHECK_EQ(g_rec[3].t[0].shape[0], (int64_t)1);
|
||||
CHECK(g_rec[3].t[0].data == (void*)((char*)g_rec[1].t[0].data + 3 * 4 * 2)); /* x row 3 */
|
||||
CHECK(g_rec[4].t[4].data == (void*)((char*)g_rec[2].t[4].data + 3 * 8 * 2)); /* y row 3 */
|
||||
CHECK(g_rec[3].t[2].data == (void*)((char*)f.ctx.buf_ptr(rows) + 1 * 3 * 4));
|
||||
f.P.lora_rows_n = 16;
|
||||
f.ctx.set_gen_lora_slot(-1);
|
||||
f.batch.gen = 0;
|
||||
}
|
||||
|
||||
/* Site is a property of the weights (spec §5.1). A domain with no kernel in some band is refused,
|
||||
|
||||
@@ -594,6 +594,14 @@ struct FakeImageGen : IImageGen {
|
||||
}
|
||||
int64_t queued() const override { return 0; }
|
||||
int64_t running() const override { return 0; }
|
||||
/* The second tokenizer: one id a byte, then 1 (an end token). */
|
||||
int encode_aux(const std::string& text, std::vector<int32_t>* out) const override {
|
||||
if (!inf.aux_tokens) return RAD_E_UNSUPPORTED;
|
||||
out->clear();
|
||||
for (unsigned char c : text) out->push_back(100 + c);
|
||||
out->push_back(1);
|
||||
return RAD_OK;
|
||||
}
|
||||
};
|
||||
|
||||
/* An audio generator that finishes every request on submit: `windows` windows of `per_window`
|
||||
|
||||
@@ -88,13 +88,14 @@ TEST(the_shipped_architectures_load_with_distinct_selection_keys) {
|
||||
CHECK(keys.emplace(std::make_pair(p.arch_id, p.arch_quant), p.name).second);
|
||||
}
|
||||
const std::set<std::pair<std::string, std::string>> want = {
|
||||
{ "breeze", "" }, { "embeddinggemma2", "" }, { "flux3", "" }, { "flux3distilled", "" },
|
||||
{ "anima", "" }, { "breeze", "" }, { "embeddinggemma2", "" }, { "flux3", "" },
|
||||
{ "flux3distilled", "" },
|
||||
{ "gemma3", "" }, { "gemma4", "" },
|
||||
{ "gemma4", "compressed-tensors" }, { "glm5next", "" }, { "lfm2", "" }, { "llama", "" },
|
||||
{ "llama", "fp8_e4m3" }, { "qwen35", "" },
|
||||
{ "qwen35", "fp8_e4m3" }, { "qwen35", "w8a8_fwht128" }, { "qwen35moe", "fp8_e4m3" },
|
||||
{ "qwen3asr", "" }, { "krea2", "" }, { "ltx2", "" }, { "minimaxh3", "" },
|
||||
{ "minimaxmusic3", "" }, { "qwen4exp", "" }, { "qwenimage21", "" } };
|
||||
{ "minimaxmusic3", "" }, { "qwen4exp", "" }, { "qwenimage21", "" }, { "sdxl", "" } };
|
||||
std::set<std::pair<std::string, std::string>> got;
|
||||
for (const auto& [k, name] : keys) got.insert(k);
|
||||
if (got != want)
|
||||
|
||||
+138
-32
@@ -869,6 +869,40 @@ struct TestStrings : StringSink {
|
||||
};
|
||||
} /* namespace */
|
||||
|
||||
namespace {
|
||||
|
||||
/* `in` through the .rad's vocab section and back into `out`. */
|
||||
int round_trip(const VocabBuild& in, VocabBuild* out) {
|
||||
TestStrings strings;
|
||||
std::vector<uint8_t> section;
|
||||
/* Lay the file out as rad-convert does: header, string blob, vocab section. The serialiser
|
||||
* writes absolute offsets, so the section must know where it lands before it is written, and
|
||||
* it lands 8-aligned, as the writer places it, because the reader takes the header as a typed
|
||||
* pointer into the file. */
|
||||
const uint64_t str_off = sizeof(RadFileHeader);
|
||||
RAD_TRY(vocab_serialize(in, strings, 0, section)); /* pass 1: sizes only */
|
||||
const uint64_t sec_off = (str_off + strings.blob.size() + 7) & ~(uint64_t)7;
|
||||
|
||||
TestStrings strings2;
|
||||
section.clear();
|
||||
RAD_TRY(vocab_serialize(in, strings2, sec_off, section));
|
||||
|
||||
std::vector<uint8_t> file(sec_off + section.size(), 0);
|
||||
RadFileHeader* fh = reinterpret_cast<RadFileHeader*>(file.data());
|
||||
fh->magic = RAD_MAGIC;
|
||||
fh->version = RAD_FORMAT_VER;
|
||||
fh->str_off = str_off;
|
||||
fh->str_bytes = strings2.blob.size();
|
||||
fh->vocab_off = sec_off;
|
||||
fh->vocab_bytes = section.size();
|
||||
std::memcpy(file.data() + str_off, strings2.blob.data(), strings2.blob.size());
|
||||
std::memcpy(file.data() + sec_off, section.data(), section.size());
|
||||
return vocab_deserialize(file.data(), file.size(),
|
||||
reinterpret_cast<const RadVocabHeader*>(file.data() + sec_off), *out);
|
||||
}
|
||||
|
||||
} /* namespace */
|
||||
|
||||
TEST(vocab_section_round_trip) {
|
||||
VocabBuild in;
|
||||
in.kind = RAD_TOK_BPE;
|
||||
@@ -885,35 +919,8 @@ TEST(vocab_section_round_trip) {
|
||||
VocabStep s2; s2.kind = RAD_PRE_BYTELEVEL; s2.flags = 2; in.steps.push_back(s2);
|
||||
VocabStep s3; s3.kind = RAD_DEC_BYTELEVEL; in.steps.push_back(s3);
|
||||
|
||||
TestStrings strings;
|
||||
std::vector<uint8_t> section;
|
||||
/* Lay the file out as rad-convert does: header, string blob, vocab section. The serialiser
|
||||
* writes absolute offsets, so the section must know where it lands before it is written, and
|
||||
* it lands 8-aligned, as the writer places it, because the reader takes the header as a typed
|
||||
* pointer into the file. */
|
||||
const uint64_t str_off = sizeof(RadFileHeader);
|
||||
CHECK_OK(vocab_serialize(in, strings, 0, section)); /* pass 1: sizes only */
|
||||
const uint64_t sec_off = (str_off + strings.blob.size() + 7) & ~(uint64_t)7;
|
||||
|
||||
TestStrings strings2;
|
||||
section.clear();
|
||||
CHECK_OK(vocab_serialize(in, strings2, sec_off, section));
|
||||
|
||||
std::vector<uint8_t> file(sec_off + section.size(), 0);
|
||||
RadFileHeader* fh = reinterpret_cast<RadFileHeader*>(file.data());
|
||||
fh->magic = RAD_MAGIC;
|
||||
fh->version = RAD_FORMAT_VER;
|
||||
fh->str_off = str_off;
|
||||
fh->str_bytes = strings2.blob.size();
|
||||
fh->vocab_off = sec_off;
|
||||
fh->vocab_bytes = section.size();
|
||||
std::memcpy(file.data() + str_off, strings2.blob.data(), strings2.blob.size());
|
||||
std::memcpy(file.data() + sec_off, section.data(), section.size());
|
||||
|
||||
VocabBuild out;
|
||||
CHECK_OK(vocab_deserialize(file.data(), file.size(),
|
||||
reinterpret_cast<const RadVocabHeader*>(file.data() + sec_off),
|
||||
out));
|
||||
CHECK_OK(round_trip(in, &out));
|
||||
|
||||
CHECK_EQ(out.kind, in.kind);
|
||||
CHECK(out.tokens == in.tokens);
|
||||
@@ -985,7 +992,7 @@ TEST(parse_tokenizer_json_chain) {
|
||||
* interpreted rather than hashed. */
|
||||
TEST(parse_tokenizer_json_refuses_unknown_components) {
|
||||
const char* js = R"JSON({
|
||||
"normalizer": { "type": "Precompiled", "precompiled_charsmap": "AAAA" },
|
||||
"normalizer": { "type": "StripAccents" },
|
||||
"pre_tokenizer": { "type": "ByteLevel" },
|
||||
"model": { "type": "BPE", "vocab": {"a": 0}, "merges": [] }
|
||||
})JSON";
|
||||
@@ -995,7 +1002,7 @@ TEST(parse_tokenizer_json_refuses_unknown_components) {
|
||||
|
||||
/* A step the tokenizer does not run is refused at load, not passed over on every encode. */
|
||||
TEST(a_vocab_with_an_unknown_step_does_not_load) {
|
||||
for (uint32_t kind : { 9u, 39u, 70u, 200u }) {
|
||||
for (uint32_t kind : { 10u, 41u, 70u, 200u }) {
|
||||
VocabBuild vb;
|
||||
vb.kind = RAD_TOK_BPE;
|
||||
vb.tokens = { "a" };
|
||||
@@ -1498,7 +1505,7 @@ TEST(decompose_and_compose_are_inverses_over_the_canonical_forms) {
|
||||
|
||||
namespace {
|
||||
|
||||
/* BEGIN generated by mk_tokenizer_goldens.py (tokenizers 0.23.2) */
|
||||
/* BEGIN generated by mk_tokenizer_goldens.py (tokenizers 0.23.3) */
|
||||
|
||||
struct DecodeGolden { const char* fixture; std::vector<int32_t> ids; const char* text; };
|
||||
struct PretokGolden { const char* name; const char* json; std::vector<int32_t> ids; };
|
||||
@@ -1676,6 +1683,49 @@ const std::vector<std::pair<const char*, EncodeGolden>>& metaspace_special_golde
|
||||
return v;
|
||||
}
|
||||
|
||||
const char* const kClipLike = R"JSON({"added_tokens": [{"id": 620, "content": "<|startoftext|>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": true, "special": true}, {"id": 621, "content": "<|endoftext|>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": false, "special": true}], "normalizer": {"type": "Sequence", "normalizers": [{"type": "NFC"}, {"type": "Replace", "pattern": {"Regex": "\\s+"}, "content": " "}, {"type": "Lowercase"}]}, "pre_tokenizer": {"type": "Sequence", "pretokenizers": [{"type": "Split", "pattern": {"Regex": "'s|'t|'re|'ve|'m|'ll|'d|[\\p{L}]+|[\\p{N}]|[^\\s\\p{L}\\p{N}]+"}, "behavior": "Removed", "invert": true}, {"type": "ByteLevel", "add_prefix_space": false, "trim_offsets": true}]}, "post_processor": {"type": "RobertaProcessing", "sep": ["<|endoftext|>", 621], "cls": ["<|startoftext|>", 620], "trim_offsets": false, "add_prefix_space": false}, "decoder": {"type": "ByteLevel", "add_prefix_space": true, "trim_offsets": true}, "model": {"type": "BPE", "dropout": null, "unk_token": "<|endoftext|>", "continuing_subword_prefix": "", "end_of_word_suffix": "</w>", "fuse_unk": false, "vocab": {"!": 0, "\"": 1, "#": 2, "$": 3, "%": 4, "&": 5, "'": 6, "(": 7, ")": 8, "*": 9, "+": 10, ",": 11, "-": 12, ".": 13, "/": 14, "0": 15, "1": 16, "2": 17, "3": 18, "4": 19, "5": 20, "6": 21, "7": 22, "8": 23, "9": 24, ":": 25, ";": 26, "<": 27, "=": 28, ">": 29, "?": 30, "@": 31, "A": 32, "B": 33, "C": 34, "D": 35, "E": 36, "F": 37, "G": 38, "H": 39, "I": 40, "J": 41, "K": 42, "L": 43, "M": 44, "N": 45, "O": 46, "P": 47, "Q": 48, "R": 49, "S": 50, "T": 51, "U": 52, "V": 53, "W": 54, "X": 55, "Y": 56, "Z": 57, "[": 58, "\\": 59, "]": 60, "^": 61, "_": 62, "`": 63, "a": 64, "b": 65, "c": 66, "d": 67, "e": 68, "f": 69, "g": 70, "h": 71, "i": 72, "j": 73, "k": 74, "l": 75, "m": 76, "n": 77, "o": 78, "p": 79, "q": 80, "r": 81, "s": 82, "t": 83, "u": 84, "v": 85, "w": 86, "x": 87, "y": 88, "z": 89, "{": 90, "|": 91, "}": 92, "~": 93, "¡": 94, "¢": 95, "£": 96, "¤": 97, "¥": 98, "¦": 99, "§": 100, "¨": 101, "©": 102, "ª": 103, "«": 104, "¬": 105, "®": 106, "¯": 107, "°": 108, "±": 109, "²": 110, "³": 111, "´": 112, "µ": 113, "¶": 114, "·": 115, "¸": 116, "¹": 117, "º": 118, "»": 119, "¼": 120, "½": 121, "¾": 122, "¿": 123, "À": 124, "Á": 125, "Â": 126, "Ã": 127, "Ä": 128, "Å": 129, "Æ": 130, "Ç": 131, "È": 132, "É": 133, "Ê": 134, "Ë": 135, "Ì": 136, "Í": 137, "Î": 138, "Ï": 139, "Ð": 140, "Ñ": 141, "Ò": 142, "Ó": 143, "Ô": 144, "Õ": 145, "Ö": 146, "×": 147, "Ø": 148, "Ù": 149, "Ú": 150, "Û": 151, "Ü": 152, "Ý": 153, "Þ": 154, "ß": 155, "à": 156, "á": 157, "â": 158, "ã": 159, "ä": 160, "å": 161, "æ": 162, "ç": 163, "è": 164, "é": 165, "ê": 166, "ë": 167, "ì": 168, "í": 169, "î": 170, "ï": 171, "ð": 172, "ñ": 173, "ò": 174, "ó": 175, "ô": 176, "õ": 177, "ö": 178, "÷": 179, "ø": 180, "ù": 181, "ú": 182, "û": 183, "ü": 184, "ý": 185, "þ": 186, "ÿ": 187, "Ā": 188, "ā": 189, "Ă": 190, "ă": 191, "Ą": 192, "ą": 193, "Ć": 194, "ć": 195, "Ĉ": 196, "ĉ": 197, "Ċ": 198, "ċ": 199, "Č": 200, "č": 201, "Ď": 202, "ď": 203, "Đ": 204, "đ": 205, "Ē": 206, "ē": 207, "Ĕ": 208, "ĕ": 209, "Ė": 210, "ė": 211, "Ę": 212, "ę": 213, "Ě": 214, "ě": 215, "Ĝ": 216, "ĝ": 217, "Ğ": 218, "ğ": 219, "Ġ": 220, "ġ": 221, "Ģ": 222, "ģ": 223, "Ĥ": 224, "ĥ": 225, "Ħ": 226, "ħ": 227, "Ĩ": 228, "ĩ": 229, "Ī": 230, "ī": 231, "Ĭ": 232, "ĭ": 233, "Į": 234, "į": 235, "İ": 236, "ı": 237, "IJ": 238, "ij": 239, "Ĵ": 240, "ĵ": 241, "Ķ": 242, "ķ": 243, "ĸ": 244, "Ĺ": 245, "ĺ": 246, "Ļ": 247, "ļ": 248, "Ľ": 249, "ľ": 250, "Ŀ": 251, "ŀ": 252, "Ł": 253, "ł": 254, "Ń": 255, "!</w>": 256, "\"</w>": 257, "#</w>": 258, "$</w>": 259, "%</w>": 260, "&</w>": 261, "'</w>": 262, "(</w>": 263, ")</w>": 264, "*</w>": 265, "+</w>": 266, ",</w>": 267, "-</w>": 268, ".</w>": 269, "/</w>": 270, "0</w>": 271, "1</w>": 272, "2</w>": 273, "3</w>": 274, "4</w>": 275, "5</w>": 276, "6</w>": 277, "7</w>": 278, "8</w>": 279, "9</w>": 280, ":</w>": 281, ";</w>": 282, "<</w>": 283, "=</w>": 284, "></w>": 285, "?</w>": 286, "@</w>": 287, "A</w>": 288, "B</w>": 289, "C</w>": 290, "D</w>": 291, "E</w>": 292, "F</w>": 293, "G</w>": 294, "H</w>": 295, "I</w>": 296, "J</w>": 297, "K</w>": 298, "L</w>": 299, "M</w>": 300, "N</w>": 301, "O</w>": 302, "P</w>": 303, "Q</w>": 304, "R</w>": 305, "S</w>": 306, "T</w>": 307, "U</w>": 308, "V</w>": 309, "W</w>": 310, "X</w>": 311, "Y</w>": 312, "Z</w>": 313, "[</w>": 314, "\\</w>": 315, "]</w>": 316, "^</w>": 317, "_</w>": 318, "`</w>": 319, "a</w>": 320, "b</w>": 321, "c</w>": 322, "d</w>": 323, "e</w>": 324, "f</w>": 325, "g</w>": 326, "h</w>": 327, "i</w>": 328, "j</w>": 329, "k</w>": 330, "l</w>": 331, "m</w>": 332, "n</w>": 333, "o</w>": 334, "p</w>": 335, "q</w>": 336, "r</w>": 337, "s</w>": 338, "t</w>": 339, "u</w>": 340, "v</w>": 341, "w</w>"Line truncated
|
||||
|
||||
const std::vector<EncodeGolden>& clip_goldens() {
|
||||
static const std::vector<EncodeGolden> v = {
|
||||
{ "a photo of a cat", { 320, 608, 513, 320, 555 }, { 620, 320, 608, 513, 320, 555, 621 } },
|
||||
{ "1girl, solo, masterpiece, best quality, (absurdres:1.2), looking_at_viewer, hatsune_miku", { 272, 576, 267, 614, 267, 594, 267, 554, 611, 267, 263, 64, 65, 82, 84, 81, 67, 81, 68, 338, 281, 272, 269, 273, 8, 267, 593, 318, 514, 318, 619, 267, 71, 64, 83, 615, 324, 318, 76, 72, 74, 340 }, { 620, 272, 576, 267, 614, 267, 594, 267, 554, 611, 267, 263, 64, 65, 82, 84, 81, 67, 81, 68, 338, 281, 272, 269, 273, 8, 267, 593, 318, 514, 318, 619, 267, 71, 64, 83, 615, 324, 318, 76, 72, 74, 340, 621 } },
|
||||
{ "A Photograph of the Mountains, it's DON'T stop", { 320, 609, 513, 618, 598, 267, 524, 528, 568, 529, 616 }, { 620, 320, 609, 513, 618, 598, 267, 524, 528, 568, 529, 616, 621 } },
|
||||
{ "1024x1024 2.5 v1.0", { 272, 271, 273, 275, 343, 272, 271, 273, 275, 273, 269, 276, 341, 272, 269, 271 }, { 620, 272, 271, 273, 275, 343, 272, 271, 273, 275, 273, 269, 276, 341, 272, 269, 271, 621 } },
|
||||
{ "Caf\xc3\xa9 na\xc3\xafve \xe6\x9d\xb1\xe4\xba\xac\xe3\x82\xbf\xe3\x83\xaf\xe3\x83\xbc \xec\x84\x9c\xec\x9a\xb8 \xf0\x9f\x8d\xa3\xf0\x9f\x91\xa9\xe2\x80\x8d\xf0\x9f\x91\xa9\xe2\x80\x8d\xf0\x9f\x91\xa7 \xc4\xb0stanbul \xce\xa3\xce\x8a\xce\xa3\xce\xa5\xce\xa6\xce\x9f\xce\xa3", { 66, 64, 69, 127, 358, 77, 64, 127, 107, 85, 324, 162, 251, 109, 160, 118, 105, 159, 224, 123, 159, 225, 107, 159, 225, 376, 168, 226, 250, 168, 248, 372, 172, 253, 235, 96, 172, 253, 239, 102, 158, 222, 235, 172, 253, 239, 102, 158, 222, 235, 172, 253, 239, 356, 328, 136, 485, 517, 64, 77, 65, 84, 331, 139, 225, 138, 107, 139, 225, 139, 227, 139, 228, 138, 123, 139, 481 }, { 620, 66, 64, 69, 127, 358, 77, 64, 127, 107, 85, 324, 162, 251, 109, 160, 118, 105, 159, 224, 123, 159, 225, 107, 159, 225, 376, 168, 226, 250, 168, 248, 372, 172, 253, 235, 96, 172, 253, 239, 102, 158, 222, 235, 172, 253, 239, 102, 158, 222, 235, 172, 253, 239, 356, 328, 136, 485, 517, 64, 77, 65, 84, 331, 139, 225, 138, 107, 139, 225, 139, 227, 139, 228, 138, 123, 139, 481, 621 } },
|
||||
{ " many spaces\t\ttabs\n\nnewlines ", { 76, 64, 77, 344, 82, 79, 64, 66, 68, 338, 518, 65, 338, 77, 68, 86, 75, 512, 68, 338 }, { 620, 76, 64, 77, 344, 82, 79, 64, 66, 68, 338, 518, 65, 338, 77, 68, 86, 75, 512, 68, 338, 621 } },
|
||||
{ "...!!!??? ((()))[[]]", { 13, 13, 13, 0, 0, 0, 30, 30, 286, 7, 7, 7, 8, 8, 8, 58, 58, 60, 316 }, { 620, 13, 13, 13, 0, 0, 0, 30, 30, 286, 7, 7, 7, 8, 8, 8, 58, 58, 60, 316, 621 } },
|
||||
{ "", { }, { 620, 621 } },
|
||||
{ "a", { 320 }, { 620, 320, 621 } },
|
||||
{ "<|startoftext|>a cat<|endoftext|>", { 620, 320, 555, 621 }, { 620, 620, 320, 555, 621, 621 } },
|
||||
{ "x<|StartOfText|>y", { 343, 620, 344 }, { 620, 343, 620, 344, 621 } },
|
||||
{ "a</w>b catcat", { 320, 27, 270, 342, 285, 321, 66, 64, 83, 555 }, { 620, 320, 27, 270, 342, 285, 321, 66, 64, 83, 555, 621 } },
|
||||
{ "photographphotograph", { 525, 78, 577, 71, 609 }, { 620, 525, 78, 577, 71, 609, 621 } },
|
||||
{ "it'sit's'll", { 524, 528, 524, 528, 6, 75, 331 }, { 620, 524, 528, 524, 528, 6, 75, 331, 621 } },
|
||||
};
|
||||
return v;
|
||||
}
|
||||
|
||||
/* The decode of every CLIP golden with special tokens skipped, as HF reports it. */
|
||||
const std::vector<const char*>& clip_decoded() {
|
||||
static const std::vector<const char*> v = {
|
||||
"a</w>photo</w>of</w>a</w>cat</w>",
|
||||
"1</w>girl</w>,</w>solo</w>,</w>masterpiece</w>,</w>best</w>quality</w>,</w>(</w>absurdres</w>:</w>1</w>.</w>2</w>),</w>looking</w>_</w>at</w>_</w>viewer</w>,</w>hatsune</w>_</w>miku</w>",
|
||||
"a</w>photograph</w>of</w>the</w>mountains</w>,</w>it</w>'s</w>don</w>'t</w>stop</w>",
|
||||
"1</w>0</w>2</w>4</w>x</w>1</w>0</w>2</w>4</w>2</w>.</w>5</w>v</w>1</w>.</w>0</w>",
|
||||
"caf\xc3\xa9</w>na\xc3\xafve</w>\xe6\x9d\xb1\xe4\xba\xac\xe3\x82\xbf\xe3\x83\xaf\xe3\x83\xbc</w>\xec\x84\x9c\xec\x9a\xb8</w>\xf0\x9f\x8d\xa3\xf0\x9f\x91\xa9\xe2\x80\x8d\xf0\x9f\x91\xa9\xe2\x80\x8d\xf0\x9f\x91\xa7</w>i</w>\xcc\x87</w>stanbul</w>\xcf\x83\xce\xaf\xcf\x83\xcf\x85\xcf\x86\xce\xbf\xcf\x83</w>",
|
||||
"many</w>spaces</w>tabs</w>newlines</w>",
|
||||
"...!!!???</w>((()))[[]]</w>",
|
||||
"",
|
||||
"a</w>",
|
||||
"a</w>cat</w>",
|
||||
"x</w>y</w>",
|
||||
"a</w></</w>w</w>></w>b</w>catcat</w>",
|
||||
"photographphotograph</w>",
|
||||
"it</w>'s</w>it</w>'s</w>'ll</w>",
|
||||
};
|
||||
return v;
|
||||
}
|
||||
|
||||
/* END generated by mk_tokenizer_goldens.py */
|
||||
|
||||
} /* namespace */
|
||||
@@ -1794,6 +1844,58 @@ TEST(the_gemma_shaped_tokenizer_encodes_as_huggingface) {
|
||||
CHECK_EQ(k, gemma_decoded().size());
|
||||
}
|
||||
|
||||
/* CLIP's shape (Stable Diffusion's text encoders): an NFC / whitespace-collapse / Lowercase
|
||||
* normaliser, a Split that keeps letter runs, single digits and punctuation runs, ByteLevel, BPE
|
||||
* whose word-final symbols carry the "</w>" suffix, RobertaProcessing `<|startoftext|> $A
|
||||
* <|endoftext|>`, and `<|startoftext|>` matched in the normalised text (so `<|StartOfText|>` is it
|
||||
* too). Encoded with and without the framing and decoded, against HuggingFace. */
|
||||
TEST(the_clip_shaped_tokenizer_encodes_as_huggingface) {
|
||||
VocabBuild vb;
|
||||
REQUIRE(parse_tokenizer_json_buf(kClipLike, "clip_like", vb) >= 0);
|
||||
CHECK(vb.add_bos);
|
||||
CHECK(vb.add_eos);
|
||||
CHECK_EQ(vb.bos, 620);
|
||||
CHECK_EQ(vb.eos, 621);
|
||||
/* Served as a container holds it: the suffix and the normalised added token are steps. */
|
||||
VocabBuild baked;
|
||||
REQUIRE(round_trip(vb, &baked) == RAD_OK);
|
||||
auto v = std::make_shared<Vocab>();
|
||||
REQUIRE(v->load(std::move(baked)) >= 0);
|
||||
Tokenizer t;
|
||||
CHECK_OK(t.init(v));
|
||||
size_t k = 0;
|
||||
for (const EncodeGolden& g : clip_goldens()) {
|
||||
std::vector<int32_t> plain, special;
|
||||
CHECK_OK(t.encode(g.text, plain, /*add_special=*/false, /*parse_special=*/true));
|
||||
CHECK_OK(t.encode(g.text, special, /*add_special=*/true, /*parse_special=*/true));
|
||||
CHECK(plain == g.ids);
|
||||
/* A text opening with the BOS token gets a second one, as in HuggingFace: CLIP's BOS
|
||||
* is matched in the normalised text, after Tokenizer::encode decides on adding one. */
|
||||
CHECK(special == g.with_special);
|
||||
if (plain != g.ids) {
|
||||
std::string got;
|
||||
for (int32_t id : plain) got += std::to_string(id) + ",";
|
||||
fprintf(stderr, " \"%s\": %s\n", g.text, got.c_str());
|
||||
}
|
||||
CHECK_EQ(t.decode(g.with_special), std::string(clip_decoded()[k]));
|
||||
CHECK_EQ(streamed(v, g.with_special), std::string(clip_decoded()[k]));
|
||||
++k;
|
||||
}
|
||||
CHECK_EQ(k, clip_decoded().size());
|
||||
|
||||
/* A token matched in the normalised text follows parse_special as the raw ones do, through
|
||||
* the segment cache as well: the same long text with it off and then on. */
|
||||
std::string text;
|
||||
for (int i = 0; i < 30; ++i) text += "a photo of a cat <|StartOfText|> ";
|
||||
for (int pass = 0; pass < 2; ++pass) {
|
||||
std::vector<int32_t> off, on;
|
||||
CHECK_OK(t.encode(text, off, false, /*parse_special=*/false));
|
||||
CHECK_OK(t.encode(text, on, false, /*parse_special=*/true));
|
||||
CHECK_EQ(std::count(off.begin(), off.end(), 620), (ptrdiff_t)0);
|
||||
CHECK_EQ(std::count(on.begin(), on.end(), 620), (ptrdiff_t)30);
|
||||
}
|
||||
}
|
||||
|
||||
/* Metaspace's "first" scheme prepends the replacement only where the text starts: a segment after
|
||||
* a special token ("[INST]Hi", "<s>Hi") has a non-zero original offset in HuggingFace and gets
|
||||
* none, where "always" gives every segment one. Encoded through the segment cache both cold and
|
||||
@@ -1851,7 +1953,6 @@ TEST(parse_tokenizer_json_refuses_values_it_cannot_honour) {
|
||||
bpe(ws, R"(, "decoder": {"type": "Sequence", "decoders": [{"type": "Fuse"},)"
|
||||
R"( {"type": "Strip", "content": " ", "start": 1, "stop": 0},)"
|
||||
R"( {"type": "Strip", "content": " ", "start": 1, "stop": 0}]})"),
|
||||
bpe(ws, "", R"(, "end_of_word_suffix": "</w>")"),
|
||||
bpe(ws, "", R"(, "continuing_subword_prefix": "##")"),
|
||||
bpe(ws, "", R"(, "dropout": 0.1)"),
|
||||
bpe(ws, added(R"("single_word": true, "lstrip": false, "rstrip": false, "normalized": false)")),
|
||||
@@ -1878,6 +1979,11 @@ TEST(parse_tokenizer_json_refuses_values_it_cannot_honour) {
|
||||
bpe(ws, R"(, "decoder": {"type": "Sequence", "decoders": [{"type": "Fuse"},)"
|
||||
R"( {"type": "Strip", "content": " ", "start": 1, "stop": 0}]})"),
|
||||
bpe(ws, "", R"(, "dropout": null, "continuing_subword_prefix": null, "end_of_word_suffix": null)"),
|
||||
bpe(ws, "", R"(, "continuing_subword_prefix": "", "end_of_word_suffix": "</w>")"),
|
||||
/* Lower case already, so the Lowercase normaliser leaves its spelling alone. */
|
||||
bpe(ws, R"(, "normalizer": {"type": "Lowercase"}, "added_tokens": [{"id": 3, "content": "x",)"
|
||||
R"( "special": true, "single_word": false, "lstrip": false, "rstrip": false,)"
|
||||
R"( "normalized": true}])"),
|
||||
};
|
||||
for (const std::string& js : accepted) {
|
||||
VocabBuild vb;
|
||||
|
||||
Reference in new issue
Block a user