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:
Deadcode committed 2026-10-20 21:05:16 +02:00
1 parent 685ec5bd85
commit 4246a1dd04
124 files changed
+14326 -387

No files matched your search

+150 -27
View File
@@ -1,5 +1,6 @@
#include "text/tokenizer.h"
#include "text/tokenizer_bpe.h"
#include "text/tokenizer_grapheme.h"
#include "text/tokenizer_nfc.h"
#include "text/tokenizer_regex.h"
#include "text/unicode_norm.h"
@@ -388,6 +389,8 @@ struct TokEncoder {
/* Split, a regex Replace, ByteLevel with use_regex, and the character-class
* pre-tokenisers; `re2` is BertPreTokenizer's punctuation after its whitespace split. */
std::unique_ptr<TokRegex> re, re2;
/* Precompiled: the decoded character map. */
std::unique_ptr<PrecompiledMap> pmap;
};
std::vector<Step> norm, pre;
uint32_t kind = RAD_TOK_BPE;
@@ -403,6 +406,12 @@ struct TokEncoder {
TokTable text; /* token text -> lowest id */
TokTable raw; /* raw bytes a byte-level token stands for -> id */
int32_t byte_sym[256]; /* raw byte -> id of its byte-level character */
/* BPE's end-of-word suffix (RAD_PRE_END_OF_WORD), empty without one. A word's last symbol
* is its text with the suffix: `raw_eow` holds the tokens ending in it by the raw bytes
* before it, and `byte_sym_eow` a byte's character with it. */
std::string eow;
TokTable raw_eow;
int32_t byte_sym_eow[256];
int32_t byte_tok[256]; /* raw byte -> id of "<0xNN>" */
MergeTable merges;
std::vector<uint8_t> types;
@@ -419,6 +428,10 @@ struct TokEncoder {
std::unique_ptr<std::atomic<uint8_t>[]> self_merges;
SpecialMatcher specials;
/* The added tokens matched in the normalised text (RAD_PRE_ADDED_NORMALIZED); `specials`
* holds the rest. */
SpecialMatcher nspecials;
bool has_nspecials = false;
mutable SegmentCache cache;
int build(const VocabBuild& b, const std::vector<int32_t>& special);
@@ -443,11 +456,19 @@ int TokEncoder::build(const VocabBuild& b, const std::vector<int32_t>& special)
for (const VocabStep& s : b.steps) {
if (step_is_norm(s.kind)) {
Step st{ s, nullptr, nullptr };
Step st{ s, nullptr, nullptr, nullptr };
if (s.kind == RAD_NORM_REPLACE && (s.flags & 1)) RAD_TRY(compile(s.arg0, "Replace", &st.re));
if (s.kind == RAD_NORM_PRECOMPILED) {
st.pmap = std::make_unique<PrecompiledMap>();
std::string why;
if (st.pmap->load(s.arg0, &why) < 0) {
RAD_ERR("vocab: the Precompiled normaliser's map: %s", why.c_str());
return RAD_E_FORMAT;
}
}
norm.push_back(std::move(st));
} else if (step_is_pre(s.kind)) {
Step st{ s, nullptr, nullptr };
Step st{ s, nullptr, nullptr, nullptr };
if (s.kind == RAD_PRE_SPLIT) RAD_TRY(compile(s.arg0, "Split", &st.re));
if (s.kind == RAD_PRE_WHITESPACE) {
RAD_TRY(compile(s.flags == kPreWhitespace ? k_word_runs : k_space_runs,
@@ -462,6 +483,7 @@ int TokEncoder::build(const VocabBuild& b, const std::vector<int32_t>& special)
if (s.flags & 2) RAD_TRY(compile(k_gpt2_pattern, "ByteLevel", &st.re));
}
if (s.kind == RAD_PRE_BYTE_FALLBACK) byte_fallback = true;
if (s.kind == RAD_PRE_END_OF_WORD) eow = s.arg0;
if (s.kind == RAD_PRE_METASPACE && s.iarg == 1) prepend_first = true;
pre.push_back(std::move(st));
}
@@ -469,7 +491,7 @@ int TokEncoder::build(const VocabBuild& b, const std::vector<int32_t>& special)
if (kind == RAD_TOK_BPE) {
for (size_t k = pre.size(); k-- > 0; ) {
const uint32_t sk = pre[k].step.kind;
if (sk == RAD_PRE_BYTE_FALLBACK) continue;
if (sk == RAD_PRE_BYTE_FALLBACK || sk == RAD_PRE_END_OF_WORD) continue;
if (sk == RAD_PRE_BYTELEVEL) defer_bytelevel = (int)k;
break;
}
@@ -490,12 +512,20 @@ int TokEncoder::build(const VocabBuild& b, const std::vector<int32_t>& special)
const char buf[7] = { '<', '0', 'x', hex[c >> 4], hex[c & 15], '>', 0 };
byte_tok[c] = text.find(buf);
byte_sym[c] = text.find(a.to_utf8[c]);
byte_sym_eow[c] = eow.empty() ? -1 : text.find(a.to_utf8[c] + eow);
}
if (defer_bytelevel >= 0) {
raw.reserve(n);
std::string r;
for (size_t i = 0; i < n; ++i)
if (!b.tokens[i].empty() && byte_decode_strict(b.tokens[i], &r)) raw.insert(r, (int32_t)i);
for (size_t i = 0; i < n; ++i) {
const std::string& t = b.tokens[i];
if (t.empty()) continue;
if (!eow.empty() && t.size() > eow.size() &&
t.compare(t.size() - eow.size(), eow.size(), eow) == 0 &&
byte_decode_strict(t.substr(0, t.size() - eow.size()), &r))
raw_eow.insert(r, (int32_t)i);
if (byte_decode_strict(t, &r)) raw.insert(r, (int32_t)i);
}
}
/* Keyed by the pair as the vocab lists it; the lowest rank wins a duplicate. A symbol's id is
@@ -511,7 +541,17 @@ int TokEncoder::build(const VocabBuild& b, const std::vector<int32_t>& special)
merges.insert((int32_t)l, (int32_t)rr, (uint32_t)r, text.find(cat));
}
specials.build(special, b.tokens, b.types);
/* Each matcher keeps the priority order of `special` (longest first). */
std::vector<int32_t> raw_special, norm_special;
for (int32_t id : special) {
bool normalized = false;
for (const VocabStep& s : b.steps)
normalized |= s.kind == RAD_PRE_ADDED_NORMALIZED && s.iarg == id;
(normalized ? norm_special : raw_special).push_back(id);
}
specials.build(raw_special, b.tokens, b.types);
nspecials.build(norm_special, b.tokens, b.types);
has_nspecials = !norm_special.empty();
self_merges.reset(new std::atomic<uint8_t>[n]());
/* A byte-level BPE never looks text up by its mapped spelling once `raw` exists. */
if (defer_bytelevel >= 0) text = TokTable();
@@ -541,8 +581,8 @@ int Vocab::load(VocabBuild b) {
* so a vocabulary that declares one does not load. */
for (const VocabStep& s : b_.steps) {
const uint32_t k = s.kind;
if ((k >= RAD_NORM_NFC && k <= RAD_NORM_PREPEND) ||
(k >= RAD_PRE_BYTELEVEL && k <= RAD_PRE_BYTE_FALLBACK) ||
if ((k >= RAD_NORM_NFC && k <= RAD_NORM_PRECOMPILED) ||
(k >= RAD_PRE_BYTELEVEL && k <= RAD_PRE_ADDED_NORMALIZED) ||
(k >= RAD_DEC_BYTELEVEL && k <= RAD_DEC_BYTE_FALLBACK))
continue;
RAD_ERR("vocab: %s is not implemented", step_describe(s).c_str());
@@ -570,6 +610,19 @@ int Vocab::load(VocabBuild b) {
if (s.kind == RAD_DEC_STRIP && fused) fused_strip = true;
}
}
/* A token matched in the normalised text is one of the vocabulary's added tokens, spelt as
* the step says. */
for (const VocabStep& s : b_.steps) {
if (s.kind != RAD_PRE_ADDED_NORMALIZED) continue;
const int32_t id = (int32_t)s.iarg;
if (s.iarg < 0 || s.iarg >= (int64_t)b_.tokens.size() || s.arg0.empty() ||
b_.tokens[(size_t)id] != s.arg0 ||
(!b_.types.empty() && b_.types[(size_t)id] != RAD_TT_CONTROL &&
b_.types[(size_t)id] != RAD_TT_USER_DEFINED)) {
RAD_ERR("vocab: %s names no added token of that spelling", step_describe(s).c_str());
return RAD_E_FORMAT;
}
}
if (b_.types.empty()) b_.types.assign(b_.tokens.size(), (uint8_t)RAD_TT_NORMAL);
if (b_.types.size() != b_.tokens.size()) {
RAD_ERR("vocab: %zu tokens but %zu token types", b_.tokens.size(), b_.types.size());
@@ -781,6 +834,8 @@ std::string step_describe(const VocabStep& s) {
return fmt("Replace(%s '%s' -> '%s')", (s.flags & 1) ? "regex" : "literal",
s.arg0.c_str(), s.arg1.c_str());
case RAD_NORM_PREPEND: return fmt("Prepend('%s')", s.arg0.c_str());
case RAD_NORM_PRECOMPILED:
return fmt("Precompiled(%zu base64 bytes)", s.arg0.size());
case RAD_PRE_BYTELEVEL:
return fmt("ByteLevel(add_prefix_space=%d use_regex=%d)",
(s.flags & 1) ? 1 : 0, (s.flags & 2) ? 1 : 0);
@@ -806,6 +861,9 @@ std::string step_describe(const VocabStep& s) {
case RAD_PRE_DIGITS:
return fmt("Digits(individual=%d)", (s.flags & 1) ? 1 : 0);
case RAD_PRE_BYTE_FALLBACK: return "ByteFallback";
case RAD_PRE_END_OF_WORD: return fmt("EndOfWordSuffix('%s')", s.arg0.c_str());
case RAD_PRE_ADDED_NORMALIZED:
return fmt("AddedNormalized('%s' = %lld)", s.arg0.c_str(), (long long)s.iarg);
case RAD_DEC_BYTELEVEL: return "decode ByteLevel";
case RAD_DEC_METASPACE:
return fmt("decode Metaspace('%s' prepend=%lld)", s.arg0.c_str(), (long long)s.iarg);
@@ -839,7 +897,13 @@ void apply_norm(std::string& text, const TokEncoder::Step& st) {
std::vector<uint32_t> cpts = unicode_cpts_from_utf8(text);
std::string out;
out.reserve(text.size());
for (uint32_t c : cpts) out += unicode_cpt_to_utf8(unicode_tolower(c));
/* HuggingFace lowercases a character at a time with Rust's char::to_lowercase, whose
* one unconditional mapping to two characters is U+0130 (I with dot above) to
* "i" U+0307; every other character maps to one. */
for (uint32_t c : cpts) {
if (c == 0x130) out += "i\xcc\x87";
else out += unicode_cpt_to_utf8(unicode_tolower(c));
}
text.swap(out);
break;
}
@@ -868,6 +932,7 @@ void apply_norm(std::string& text, const TokEncoder::Step& st) {
}
break;
case RAD_NORM_PREPEND: text = s.arg0 + text; break;
case RAD_NORM_PRECOMPILED: text = st.pmap->normalize(text); break;
}
}
@@ -1055,7 +1120,8 @@ private:
void bpe_word(const TokEncoder& e, std::string_view w, std::vector<int32_t>& out,
EncodeScratch& sc) {
const bool raw = e.defer_bytelevel >= 0;
const TokTable& table = raw ? e.raw : e.text;
const bool eow = !e.eow.empty();
const TokTable& table = raw ? (eow ? e.raw_eow : e.raw) : e.text;
/* A user-defined token is taken whole: added tokens must round-trip, and the merge table was
* never fitted over them, so re-merging can give a different sequence.
@@ -1065,7 +1131,9 @@ void bpe_word(const TokEncoder& e, std::string_view w, std::vector<int32_t>& out
* different split of a rare word). The raw-byte table finds the same entry by its byte
* spelling. A control entry is never taken whole: reaching here means the caller asked for
* it to be read as text. */
const int32_t whole = table.find(w);
/* With an end-of-word suffix the whole word is its text and the suffix: `raw_eow` is keyed
* without it, the text table with it. */
const int32_t whole = eow && !raw ? table.find(std::string(w) + e.eow) : table.find(w);
if (whole >= 0 && (e.types[whole] == RAD_TT_USER_DEFINED ||
(e.ignore_merges && e.types[whole] != RAD_TT_CONTROL))) {
out.push_back(whole);
@@ -1083,10 +1151,13 @@ void bpe_word(const TokEncoder& e, std::string_view w, std::vector<int32_t>& out
if (raw) {
for (size_t i = 0; i < n; ++i)
syms.push_back({ (uint32_t)i, 1, e.byte_sym[(unsigned char)w[i]] });
if (eow) syms.back().id = e.byte_sym_eow[(unsigned char)w[n - 1]];
} else {
for (size_t i = 0; i < n; ) {
const size_t len = std::min(unicode_len_utf8(w[i]), n - i);
syms.push_back({ (uint32_t)i, (uint32_t)len, table.find(w.substr(i, len)) });
syms.push_back({ (uint32_t)i, (uint32_t)len,
eow && i + len == n ? table.find(std::string(w.substr(i, len)) + e.eow)
: table.find(w.substr(i, len)) });
i += len;
}
}
@@ -1103,9 +1174,12 @@ void bpe_word(const TokEncoder& e, std::string_view w, std::vector<int32_t>& out
/* Miss: decompose into byte tokens, spelt per the chain. Under ByteLevel each byte is its
* own mapped codepoint, so the piece splits at codepoint boundaries; under byte fallback
* a byte is "<0xNN>". */
const bool last = s.start + s.len == n;
if (raw) {
for (unsigned char c : str) {
const int32_t b = e.byte_sym[c];
for (size_t k = 0; k < str.size(); ++k) {
const unsigned char c = (unsigned char)str[k];
const int32_t b = eow && last && k + 1 == str.size() ? e.byte_sym_eow[c]
: e.byte_sym[c];
if (b >= 0) out.push_back(b);
else RAD_WARN("tokenizer: no token for byte-level piece '%s'",
alphabet().to_utf8[c].c_str());
@@ -1113,7 +1187,9 @@ void bpe_word(const TokEncoder& e, std::string_view w, std::vector<int32_t>& out
} else if (e.bytelevel) {
for (size_t k = 0; k < str.size(); ) {
const size_t m = std::min(unicode_len_utf8(str[k]), str.size() - k);
const int32_t b = e.text.find(str.substr(k, m));
const int32_t b = eow && last && k + m == str.size()
? e.text.find(std::string(str.substr(k, m)) + e.eow)
: e.text.find(str.substr(k, m));
if (b >= 0) out.push_back(b);
else RAD_WARN("tokenizer: no token for byte-level piece '%s'",
std::string(str.substr(k, m)).c_str());
@@ -1142,9 +1218,13 @@ void bpe(const TokEncoder& e, const Pieces& p, std::vector<int32_t>& out, Encode
if (w.empty()) continue;
/* A one-byte word of a byte-level vocab is that byte's token; the lookup and the merge
* would both land on byte_sym. A missing one takes the warning path in bpe_word. */
if (raw && w.size() == 1 && e.byte_sym[(unsigned char)w[0]] >= 0) {
out.push_back(e.byte_sym[(unsigned char)w[0]]);
continue;
if (raw && w.size() == 1) {
const int32_t b = e.eow.empty() ? e.byte_sym[(unsigned char)w[0]]
: e.byte_sym_eow[(unsigned char)w[0]];
if (b >= 0) {
out.push_back(b);
continue;
}
}
if (w.size() > WordCache::kMaxKey) { bpe_word(e, w, out, sc); continue; }
const uint64_t h = tok_hash(w);
@@ -1259,13 +1339,10 @@ void wordpiece(const Vocab& v, const TokEncoder& e, const Pieces& p, std::vector
}
}
/* One segment -- the text between two special tokens -- through the whole chain. `at_start`:
* the segment begins the text (see apply_metaspace). */
int encode_segment(const Vocab& v, const TokEncoder& e, std::string_view seg,
std::vector<int32_t>& out, EncodeScratch& sc, WordCache& words, bool at_start) {
/* Normalised text in `sc.p.buf` through the pre-tokenisers and the model. */
int encode_normalized(const Vocab& v, const TokEncoder& e, std::vector<int32_t>& out,
EncodeScratch& sc, WordCache& words, bool at_start) {
Pieces& p = sc.p;
p.buf.assign(seg.data(), seg.size());
for (const TokEncoder::Step& st : e.norm) apply_norm(p.buf, st);
if (p.buf.size() > (size_t)(UINT32_MAX / 8)) {
RAD_ERR("tokenizer: a %zu-byte segment is past what one encode can index", p.buf.size());
return RAD_E_INVAL;
@@ -1302,6 +1379,12 @@ int encode_segment(const Vocab& v, const TokEncoder& e, std::string_view seg,
case RAD_PRE_BYTE_FALLBACK:
/* Declares how an unknown piece is encoded, not a split; bpe_word handles it. */
break;
case RAD_PRE_END_OF_WORD:
/* Declares how a word's last symbol is spelt, not a split; bpe_word handles it. */
break;
case RAD_PRE_ADDED_NORMALIZED:
/* Cut out by encode_segment before the pre-tokenisers run. */
break;
}
}
@@ -1323,8 +1406,45 @@ int encode_segment(const Vocab& v, const TokEncoder& e, std::string_view seg,
return RAD_OK;
}
/* One segment -- the text between two special tokens -- through the whole chain. `at_start`:
* the segment begins the text (see apply_metaspace). The added tokens matched in the normalised
* text are cut out of it after the normalisers, under the same `parse_special` rule as the raw
* ones, and each piece between them goes through the rest of the chain on its own. */
int encode_segment(const Vocab& v, const TokEncoder& e, std::string_view seg,
std::vector<int32_t>& out, EncodeScratch& sc, WordCache& words, bool at_start,
bool parse_special) {
Pieces& p = sc.p;
p.buf.assign(seg.data(), seg.size());
for (const TokEncoder::Step& st : e.norm) apply_norm(p.buf, st);
if (!e.has_nspecials) return encode_normalized(v, e, out, sc, words, at_start);
const std::string norm = p.buf;
std::vector<SpecialFrag> frags;
e.nspecials.split(norm, parse_special, frags);
for (const SpecialFrag& f : frags) {
if (f.id >= 0) { out.push_back(f.id); continue; }
if (f.len == 0) continue;
p.buf.assign(norm, f.off, f.len);
RAD_TRY(encode_normalized(v, e, out, sc, words, at_start && f.off == 0));
}
return RAD_OK;
}
} /* namespace */
int vocab_normalize(const std::vector<VocabStep>& steps, std::string* text) {
for (const VocabStep& s : steps) {
if (!step_is_norm(s.kind)) continue;
TokEncoder::Step st{ s, nullptr, nullptr };
if (s.kind == RAD_NORM_REPLACE && (s.flags & 1)) {
std::string why;
if (TokRegex::compile(s.arg0, &st.re, &why) < 0) return RAD_E_UNSUPPORTED;
}
apply_norm(*text, st);
}
return RAD_OK;
}
/* ================================================================== encode */
int Tokenizer::init(std::shared_ptr<const Vocab> v) {
@@ -1372,14 +1492,17 @@ int Tokenizer::encode(std::string_view text, std::vector<int32_t>& out,
/* The cache is keyed on the segment's bytes, so a segment whose ids also depend on
* starting the text bypasses it. */
const bool at_start = f.off == 0;
if (!use_cache_ || seg.size() < kSegmentCacheMin || (at_start && e.prepend_first)) {
RAD_TRY(encode_segment(*v_, e, seg, out, sc, words, at_start));
/* A segment's ids also depend on parse_special when added tokens are matched in its
* normalised text; the cache holds only the parse_special form. */
if (!use_cache_ || seg.size() < kSegmentCacheMin || (at_start && e.prepend_first) ||
(e.has_nspecials && !parse_special)) {
RAD_TRY(encode_segment(*v_, e, seg, out, sc, words, at_start, parse_special));
continue;
}
const uint64_t h = tok_hash(seg);
if (e.cache.lookup(seg, h, out)) continue;
const size_t start = out.size();
RAD_TRY(encode_segment(*v_, e, seg, out, sc, words, at_start));
RAD_TRY(encode_segment(*v_, e, seg, out, sc, words, at_start, parse_special));
e.cache.insert(seg, h, out.data() + start, out.size() - start);
}
+4
View File
@@ -337,6 +337,10 @@ int vocab_serialize(const VocabBuild& in, StringSink& strings, uint64_t section_
int vocab_deserialize(const void* file_base, uint64_t file_bytes,
const RadVocabHeader* h, VocabBuild& out);
/* `text` through the normaliser steps of `steps` (the others are skipped), as the encoder runs
* them. RAD_E_UNSUPPORTED when a Replace pattern does not compile. */
int vocab_normalize(const std::vector<VocabStep>& steps, std::string* text);
/* Human-readable one-liner for a step, for --debug-graph and for the convert log. */
std::string step_describe(const VocabStep& s);
+210
View File
@@ -0,0 +1,210 @@
/* tokenizer_grapheme.cpp -- extended grapheme clusters and the precompiled normaliser
* (tokenizer_grapheme.h). */
#include "text/tokenizer_grapheme.h"
#include "rad_internal.h"
#include <algorithm>
#include <cstring>
namespace rad {
namespace {
enum Gcb : uint32_t { kOther, kCR, kLF, kControl, kExtend, kZWJ, kRI, kPrepend, kSpacingMark,
kL, kV, kT, kLV, kLVT };
enum InCB : uint32_t { kInNone, kInLinker, kInConsonant, kInExtend };
uint32_t lookup(const ucd::GbRange* r, size_t n, uint32_t c) {
size_t lo = 0, hi = n;
while (lo < hi) {
const size_t mid = (lo + hi) / 2;
if (r[mid].last < c) lo = mid + 1;
else hi = mid;
}
return lo < n && r[lo].first <= c ? r[lo].v : 0;
}
uint32_t gcb(uint32_t c) { return lookup(ucd::k_gcb, ucd::k_gcb_n, c); }
bool pict(uint32_t c) { return lookup(ucd::k_ext_pict, ucd::k_ext_pict_n, c) != 0; }
uint32_t incb(uint32_t c) { return lookup(ucd::k_incb, ucd::k_incb_n, c); }
/* One codepoint off well-formed UTF-8 at `p`, its byte length in *len. A byte that starts no
* well-formed sequence is taken alone. */
uint32_t utf8_at(const unsigned char* p, size_t left, size_t* len) {
const unsigned char b = p[0];
auto cont = [&](size_t k) { return k < left && (p[k] & 0xC0) == 0x80; };
if (b < 0x80) { *len = 1; return b; }
if ((b & 0xE0) == 0xC0 && cont(1)) { *len = 2; return ((b & 0x1Fu) << 6) | (p[1] & 0x3Fu); }
if ((b & 0xF0) == 0xE0 && cont(1) && cont(2)) {
*len = 3;
return ((b & 0x0Fu) << 12) | ((p[1] & 0x3Fu) << 6) | (p[2] & 0x3Fu);
}
if ((b & 0xF8) == 0xF0 && cont(1) && cont(2) && cont(3)) {
*len = 4;
return ((b & 0x07u) << 18) | ((p[1] & 0x3Fu) << 12) | ((p[2] & 0x3Fu) << 6) |
(p[3] & 0x3Fu);
}
*len = 1;
return 0xFFFD;
}
int b64_value(char c) {
if (c >= 'A' && c <= 'Z') return c - 'A';
if (c >= 'a' && c <= 'z') return c - 'a' + 26;
if (c >= '0' && c <= '9') return c - '0' + 52;
if (c == '+') return 62;
if (c == '/') return 63;
return -1;
}
} /* namespace */
/* UAX #29's rules GB3 to GB13 in their order, the lookbehind of GB9c (a conjunct's consonant,
* linker and consonant), GB11 (an emoji ZWJ sequence) and GB12/13 (regional indicator pairs)
* carried as state from the cluster's start, where no such sequence can be cut. */
size_t grapheme_end(const uint32_t* cps, size_t n, size_t i) {
uint32_t prev = gcb(cps[i]);
/* The text so far ends in Extended_Pictographic Extend*; and did before `prev`. */
bool ep = pict(cps[i]), ep_before = false;
/* Regional indicators ending at `prev`. */
int ri = prev == kRI ? 1 : 0;
/* GB9c: 0 nothing, 1 a consonant then Extend/Linker without a linker, 2 with one. */
int conj = 0;
{
const uint32_t in = incb(cps[i]);
conj = in == kInConsonant ? 1 : 0;
}
size_t j = i + 1;
for (; j < n; ++j) {
const uint32_t c = cps[j], cur = gcb(c);
bool join;
if (prev == kCR && cur == kLF) join = true; /* GB3 */
else if (prev == kControl || prev == kCR || prev == kLF) join = false; /* GB4 */
else if (cur == kControl || cur == kCR || cur == kLF) join = false; /* GB5 */
else if (prev == kL && (cur == kL || cur == kV || cur == kLV || cur == kLVT)) join = true;
else if ((prev == kLV || prev == kV) && (cur == kV || cur == kT)) join = true; /* GB7 */
else if ((prev == kLVT || prev == kT) && cur == kT) join = true; /* GB8 */
else if (cur == kExtend || cur == kZWJ) join = true; /* GB9 */
else if (cur == kSpacingMark) join = true; /* GB9a */
else if (prev == kPrepend) join = true; /* GB9b */
else if (conj == 2 && incb(c) == kInConsonant) join = true; /* GB9c */
else if (prev == kZWJ && ep_before && pict(c)) join = true; /* GB11 */
else if (prev == kRI && cur == kRI && (ri & 1)) join = true; /* GB12/13 */
else join = false;
if (!join) break;
ep_before = ep;
ep = pict(c) || (ep && cur == kExtend);
ri = cur == kRI ? ri + 1 : 0;
const uint32_t in = incb(c);
if (in == kInConsonant) conj = 1;
else if (in == kInLinker && conj >= 1) conj = 2;
else if (in == kInExtend && conj >= 1) { /* kept */ }
else conj = 0;
prev = cur;
}
return j;
}
/* ================================================================== the precompiled map */
/* The charsmap is a little-endian u32 byte count of the trie, the trie's u32 units (Darts' double
* array), then the replacement strings, each NUL-terminated. */
int PrecompiledMap::load(std::string_view b64, std::string* why) {
std::string raw;
raw.reserve(b64.size() / 4 * 3);
uint32_t acc = 0;
int bits = 0;
for (char ch : b64) {
if (ch == '=') break;
const int v = b64_value(ch);
if (v < 0) {
if (why) *why = "the precompiled charsmap is not base64";
return RAD_E_FORMAT;
}
acc = (acc << 6) | (uint32_t)v;
bits += 6;
if (bits >= 8) {
bits -= 8;
raw.push_back((char)((acc >> bits) & 0xFF));
}
}
if (raw.size() < 4) {
if (why) *why = "the precompiled charsmap is shorter than its header";
return RAD_E_FORMAT;
}
uint32_t tbytes = 0;
std::memcpy(&tbytes, raw.data(), 4);
if (tbytes % 4 || (size_t)tbytes > raw.size() - 4 || tbytes == 0) {
if (why) *why = "the precompiled charsmap's trie does not fit it";
return RAD_E_FORMAT;
}
trie_.resize(tbytes / 4);
std::memcpy(trie_.data(), raw.data() + 4, tbytes);
blob_.assign(raw.data() + 4 + tbytes, raw.size() - 4 - tbytes);
return RAD_OK;
}
bool PrecompiledMap::transform(std::string_view s, std::string_view* out) const {
auto offset = [](uint32_t u) { return (u >> 10) << ((u & (1u << 9)) >> 6); };
auto label = [](uint32_t u) { return u & ((1u << 31) | 0xFFu); };
auto leaf = [](uint32_t u) { return ((u >> 8) & 1u) != 0; };
auto value = [](uint32_t u) { return u & ((1u << 31) - 1); };
size_t pos = 0;
uint32_t unit = trie_[0];
pos ^= offset(unit);
for (unsigned char c : s) {
if (c == 0) break;
pos ^= c;
if (pos >= trie_.size()) return false;
unit = trie_[pos];
if (label(unit) != c) return false;
pos ^= offset(unit);
if (pos >= trie_.size()) return false;
if (leaf(unit)) {
const size_t at = value(trie_[pos]);
if (at >= blob_.size()) return false;
const size_t end = blob_.find('\0', at);
*out = std::string_view(blob_).substr(at, (end == std::string::npos ? blob_.size()
: end) - at);
return true;
}
}
return false;
}
/* HuggingFace's Precompiled::normalize: a cluster under six bytes goes whole to its shortest
* mapped prefix's replacement when it has one; otherwise each character goes to its own, or
* stays. */
std::string PrecompiledMap::normalize(std::string_view text) const {
std::vector<uint32_t> cps;
std::vector<size_t> at;
cps.reserve(text.size());
at.reserve(text.size() + 1);
const unsigned char* p = (const unsigned char*)text.data();
for (size_t k = 0; k < text.size();) {
size_t len = 1;
cps.push_back(utf8_at(p + k, text.size() - k, &len));
at.push_back(k);
k += len;
}
at.push_back(text.size());
std::string out;
out.reserve(text.size());
std::string_view rep;
for (size_t i = 0; i < cps.size();) {
const size_t e = grapheme_end(cps.data(), cps.size(), i);
const std::string_view g = text.substr(at[i], at[e] - at[i]);
if (g.size() < 6 && transform(g, &rep)) {
out.append(rep);
} else {
for (size_t k = i; k < e; ++k) {
const std::string_view ch = text.substr(at[k], at[k + 1] - at[k]);
if (transform(ch, &rep)) out.append(rep);
else out.append(ch);
}
}
i = e;
}
return out;
}
} /* namespace rad */
+56
View File
@@ -0,0 +1,56 @@
/* tokenizer_grapheme.h -- extended grapheme clusters (UAX #29) and SentencePiece's precompiled
* normaliser, which walks its text by them.
*
* HuggingFace tokenizers' `Precompiled` normaliser (a SentencePiece model's `precompiled_charsmap`,
* T5's among them) takes the text one extended grapheme cluster at a time: a cluster shorter than
* six bytes is replaced whole by the mapping of its shortest mapped prefix, if it has one;
* otherwise each of its characters is replaced by its own mapping or kept. The cluster
* boundaries are therefore part of the result, and they are Unicode 16.0.0's, the version the
* reference's segmentation crate implements (tools/gen_grapheme_ucd.py writes the tables).
*/
#pragma once
#include <cstddef>
#include <cstdint>
#include <string>
#include <string_view>
#include <vector>
namespace rad {
namespace ucd {
/* A run of codepoints [first, last] holding one value of a property. */
struct GbRange { uint32_t first, last; uint32_t v; };
/* Grapheme_Cluster_Break, values in tools/gen_grapheme_ucd.py's GCB order (0 is Other). */
extern const GbRange k_gcb[];
extern const size_t k_gcb_n;
/* Extended_Pictographic (v 1). */
extern const GbRange k_ext_pict[];
extern const size_t k_ext_pict_n;
/* Indic_Conjunct_Break: 1 Linker, 2 Consonant, 3 Extend (absent: None). */
extern const GbRange k_incb[];
extern const size_t k_incb_n;
} /* namespace ucd */
/* The end of the extended grapheme cluster that starts at `cps[i]`: the index one past its last
* codepoint. `i < n`. */
size_t grapheme_end(const uint32_t* cps, size_t n, size_t i);
/* SentencePiece's precompiled character map: a double-array trie over UTF-8 source strings, each
* leaf the offset of its NUL-terminated replacement in a string blob. */
class PrecompiledMap {
public:
/* `charsmap_b64` is tokenizer.json's `precompiled_charsmap` as it stands, base64. RAD_OK, or
* RAD_E_FORMAT with `why` for a map that does not decode or whose trie points outside it. */
int load(std::string_view charsmap_b64, std::string* why);
bool ready() const { return !trie_.empty(); }
/* The normalised text, as HuggingFace's Precompiled normaliser writes it. */
std::string normalize(std::string_view text) const;
private:
/* The replacement of the shortest mapped prefix of `s`, or false when no prefix is mapped. */
bool transform(std::string_view s, std::string_view* out) const;
std::vector<uint32_t> trie_;
std::string blob_;
};
} /* namespace rad */
File diff suppressed because it is too large. Load diff
+83 -15
View File
@@ -9,6 +9,7 @@
* vocab_serialize() into the .rad's vocab section, and back.
*/
#include "text/tokenizer.h"
#include "text/tokenizer_grapheme.h"
#include "text/tokenizer_regex.h"
#include "text/gguf.h"
@@ -164,6 +165,21 @@ int read_normalizer(const json& n, std::vector<VocabStep>& out, const char* orig
out.push_back(s);
return RAD_OK;
}
if (t == "Precompiled") {
/* SentencePiece's precompiled character map (T5's), kept base64 as the file carries it
* and decoded at load (tokenizer_grapheme.h). */
s.kind = RAD_NORM_PRECOMPILED;
s.arg0 = str_or(n, "precompiled_charsmap", "");
PrecompiledMap pm;
std::string why;
if (s.arg0.empty() || pm.load(s.arg0, &why) < 0) {
RAD_ERR("%s: Precompiled normalizer: %s", origin,
s.arg0.empty() ? "no precompiled_charsmap" : why.c_str());
return RAD_E_FORMAT;
}
out.push_back(s);
return RAD_OK;
}
if (t == "Prepend") {
s.kind = RAD_NORM_PREPEND;
s.arg0 = str_or(n, "prepend", "");
@@ -385,12 +401,10 @@ int read_model(const json& m, VocabBuild& out, const char* origin, uint64_t id_l
if (type == "BPE") {
out.kind = RAD_TOK_BPE;
out.ignore_merges = bool_or(m, "ignore_merges", false);
/* Subword affixes change what every merge produces, and dropout makes encoding random;
* the encoder implements neither. */
for (const char* k : { "continuing_subword_prefix", "end_of_word_suffix" }) {
const std::string v = str_or(m, k, "");
if (!v.empty()) return refuse_value(origin, (std::string("BPE ") + k).c_str(), v);
}
/* A continuation prefix changes what every merge produces, and dropout makes encoding
* random; the encoder implements neither. */
const std::string prefix = str_or(m, "continuing_subword_prefix", "");
if (!prefix.empty()) return refuse_value(origin, "BPE continuing_subword_prefix", prefix);
if (const json* d = get(m, "dropout"); d && d->is_number() && d->get<double>() > 0.0)
return refuse_value(origin, "BPE dropout", d->dump());
RAD_TRY(read_text_to_id("BPE"));
@@ -434,6 +448,18 @@ int read_model(const json& m, VocabBuild& out, const char* origin, uint64_t id_l
return RAD_E_UNSUPPORTED;
}
/* The end-of-word suffix (CLIP's "</w>") is a model property in tokenizer.json but a step
* here, as byte fallback is below: it changes the symbols a word starts as. */
if (type == "BPE") {
const std::string eow = str_or(m, "end_of_word_suffix", "");
if (!eow.empty()) {
VocabStep s;
s.kind = RAD_PRE_END_OF_WORD;
s.arg0 = eow;
out.steps.push_back(s);
}
}
/* Byte fallback is a model property in tokenizer.json but a step here: it changes what the
* encoder does on a miss. */
if (bool_or(m, "byte_fallback", false)) {
@@ -472,12 +498,17 @@ int read_model(const json& m, VocabBuild& out, const char* origin, uint64_t id_l
* The encoder matches an added token against the raw text, exactly as written. HuggingFace's
* AddedToken flags each change that: `single_word` matches only between word boundaries,
* `normalized` matches against the normalised text (the same thing when there is no normaliser),
* and `lstrip` / `rstrip` take the whitespace beside a match into it. Most files spell out every
* and `lstrip` / `rstrip` take the whitespace beside a match into it. A normalised token becomes a
* RAD_PRE_ADDED_NORMALIZED step, placed first among the pre-tokenisers (so `<|StartOfText|>` under
* a Lowercase is CLIP's `<|startoftext|>`); one whose spelling the normaliser itself changes would
* be matched by that changed spelling, which is refused. Most files spell out every
* flag, so a flag is refused only at a value that changes the result. lstrip and rstrip would
* also refuse released models (Phi-3's chat markers carry rstrip), and the container has no field
* to carry them, so they are warned about instead. */
int read_added(const json& arr, VocabBuild& out, const char* origin, uint64_t id_limit,
bool has_normalizer) {
const std::vector<VocabStep>& norm) {
const bool has_normalizer = !norm.empty();
std::vector<VocabStep> matched_normalized;
if (!arr.is_array()) return RAD_OK;
std::string stripped;
for (const json& e : arr) {
@@ -500,14 +531,27 @@ int read_added(const json& arr, VocabBuild& out, const char* origin, uint64_t id
const bool special = bool_or(e, "special", false);
if (bool_or(e, "single_word", false))
return refuse_value(origin, "added token single_word=true on", content);
if (has_normalizer && bool_or(e, "normalized", false))
return refuse_value(origin, "added token normalized=true (under a normalizer) on",
content);
if (has_normalizer && bool_or(e, "normalized", false)) {
std::string n = content;
if (vocab_normalize(norm, &n) != RAD_OK || n != content)
return refuse_value(origin, "added token normalized=true (under a normalizer that "
"changes its spelling) on", content);
if (!content.empty()) {
VocabStep st;
st.kind = RAD_PRE_ADDED_NORMALIZED;
st.arg0 = content;
st.iarg = (int64_t)id;
matched_normalized.push_back(st);
}
}
if (bool_or(e, "lstrip", false) || bool_or(e, "rstrip", false))
stripped += (stripped.empty() ? "" : " ") + content;
out.tokens[id] = content;
out.types[id] = special ? (uint8_t)RAD_TT_CONTROL : (uint8_t)RAD_TT_USER_DEFINED;
}
/* Ahead of the other pre-tokenisers, after the normalisers. */
out.steps.insert(out.steps.begin() + (std::ptrdiff_t)norm.size(), matched_normalized.begin(),
matched_normalized.end());
if (!stripped.empty())
RAD_WARN("%s: added tokens %s take the whitespace beside them in HuggingFace (lstrip / "
"rstrip); this tokenizer keeps it as text, so prompts with whitespace next to "
@@ -544,8 +588,11 @@ void read_config_json(const std::string& dir, VocabBuild& out) {
auto it = id_of.find(text);
return it == id_of.end() ? -1 : it->second;
};
out.bos = token_id("bos_token");
out.eos = token_id("eos_token");
/* An id the post-processor already gave (interpret_tokenizer_json) stays when the config
* names no such token. */
const int32_t bos = token_id("bos_token"), eos = token_id("eos_token");
if (bos >= 0 || out.bos < 0) out.bos = bos;
if (eos >= 0 || out.eos < 0) out.eos = eos;
out.pad = token_id("pad_token");
out.unk = out.unk >= 0 ? out.unk : token_id("unk_token");
out.sep = token_id("sep_token");
@@ -622,7 +669,7 @@ int interpret_tokenizer_json(const json& j, uint64_t id_limit, const char* origi
out.steps.insert(out.steps.end(), dec.begin(), dec.end());
if (const json* a = get(j, "added_tokens"))
RAD_TRY(read_added(*a, out, origin, id_limit, !norm.empty()));
RAD_TRY(read_added(*a, out, origin, id_limit, norm));
/* The model's unknown token, by text. The encoder emits it for text no token covers, which
* HuggingFace does too; tokenizer_config.json's unk_token, read later, agrees or is absent. */
@@ -654,7 +701,28 @@ int interpret_tokenizer_json(const json& j, uint64_t id_limit, const char* origi
* Only a special token before and/or after the sequence is read. The config's
* add_bos_token / add_eos_token, read later, win where present. */
if (const json* pp = get(j, "post_processor")) {
if (str_or(*pp, "type", "") == "TemplateProcessing") {
const std::string ppt = str_or(*pp, "type", "");
/* RobertaProcessing and BertProcessing frame a sequence as `cls $A sep`; they name the
* two tokens, which stand for BOS and EOS where the config names none (CLIP's). */
if (ppt == "RobertaProcessing" || ppt == "BertProcessing") {
auto framing = [&](const char* k) -> int32_t {
const json* v = get(*pp, k);
int32_t id = -1;
if (!v || !v->is_array() || v->size() != 2 || !read_id((*v)[1], out.tokens.size(), &id))
return -1;
return id;
};
const int32_t cls = framing("cls"), sep = framing("sep");
if (cls < 0 || sep < 0) {
RAD_ERR("%s: %s names no [token, id] cls and sep in the vocabulary", origin,
ppt.c_str());
return RAD_E_FORMAT;
}
out.bos = cls;
out.eos = sep;
out.add_bos = out.add_eos = true;
}
if (ppt == "TemplateProcessing") {
const json* single = get(*pp, "single");
if (single && single->is_array() && !single->empty()) {
auto special = [](const json& e) -> bool { return e.is_object() && e.contains("SpecialToken"); };