Archived
radiance 1.7.0
- every model serves without a GPU: libavx covers every op, so `--kernels libavx` alone serves every shipped container - Qwen3-ASR (zivius): speech to text on /v1/audio/transcriptions and live over /v1/realtime - /v1/messages works with Claude Code as it ships (gearwave00001) - a long agent conversation keeps its cached history when the client rewrites its last turn (manueloverride) - a stream's first event goes out with the first token, so llama-benchy measures prefill right - opt-in --prefill-interleave (Smellyyyy, baKon) and --prefill-span (keptn42) - four-rank TP releases the link early; four-rank selftests and docs/TP4.md (goodman-b) - NVFP4 and FP8 compressed-tensors imports (devmilan); tools/rad-export for finetunes and LoRA adapters (baKon) - many fixes, among them lost tokens on stop strings under concurrency, keep-alive, MiniCPM5 tool arguments and the CPU's vision and audio encoders - plugin ABI 17 and changed op schemas: out-of-tree plugins must be rebuilt
This commit is contained in:
1 parent
b068190326
commit
1e968f6e1d
739 files changed
+128447
-84632
No files matched your search
+29
-45
@@ -1,9 +1,9 @@
|
||||
#include "text/chat.h"
|
||||
#include "text/tokenizer.h"
|
||||
|
||||
/* The lifted headers live here and nowhere else in core/. See chat.h for why. */
|
||||
/* Lifted headers: only this file, chatfmt.cpp and chatparse.cpp include them (see chat.h). */
|
||||
#include "llama/common/chat.h"
|
||||
/* For jinja::enable_debug only -- see RADIANCE_DEBUG_JINJA below. */
|
||||
/* For jinja::enable_debug (RADIANCE_DEBUG_JINJA). */
|
||||
#include "llama/common/jinja/runtime.h"
|
||||
#include "shim/log.h"
|
||||
|
||||
@@ -16,7 +16,6 @@ namespace rad {
|
||||
|
||||
using ojson = nlohmann::ordered_json;
|
||||
|
||||
|
||||
struct ChatTemplate::Impl {
|
||||
common_chat_templates_ptr tmpls;
|
||||
ChatCaps caps;
|
||||
@@ -28,9 +27,8 @@ ChatTemplate::ChatTemplate() : impl_(std::make_unique<Impl>()) {}
|
||||
ChatTemplate::~ChatTemplate() = default;
|
||||
|
||||
const char* ChatTemplate::chatml_source() {
|
||||
/* Byte-identical to CHATML_TEMPLATE_SRC in the lift. Duplicated rather than exported because
|
||||
* exporting it would mean editing the lifted header; the string is stable upstream, and if it
|
||||
* ever moves this is the single place that has to follow it. */
|
||||
/* Byte-identical to CHATML_TEMPLATE_SRC in the lift, copied so the lifted header stays
|
||||
* unedited. Keep in sync on a vendor refresh. */
|
||||
return
|
||||
"{%- for message in messages -%}\n"
|
||||
" {{- '<|im_start|>' + message.role + '\n' + message.content + '<|im_end|>\n' -}}\n"
|
||||
@@ -42,35 +40,29 @@ const char* ChatTemplate::chatml_source() {
|
||||
|
||||
int ChatTemplate::load(const std::string& jinja_source, const std::string& bos,
|
||||
const std::string& eos, bool add_bos, bool add_eos) {
|
||||
/* The vendored files' LOG_DBG goes to stderr behind this switch. It has to be set HERE, where
|
||||
* the template is first touched: the auto-parser analyses the template inside apply() and
|
||||
* again when the reply format is derived (chatfmt.cpp), and a switch set any later comes too
|
||||
* late to trace a format the analyzer could not crack. */
|
||||
/* Gates the vendored LOG_DBG to stderr. Set here, where the template is first touched,
|
||||
* because the auto-parser analyses it in apply() and again in chatfmt.cpp; any later is too
|
||||
* late to trace a format the analyzer could not handle. */
|
||||
rad_vendor_log::verbose() = (int)log_level() >= (int)Log::Debug;
|
||||
|
||||
/* THE TEMPLATE ENGINE'S OWN TRACE, and there is no other way to get at this one.
|
||||
* common_chat_templates_init runs a capability PROBE: it renders the template with a
|
||||
* synthetic tool and a synthetic tool call and watches which values were read. It SWALLOWS
|
||||
* every exception -- "ignore exceptions during capability analysis" -- so a template that
|
||||
* genuinely has no tool support and a template that THROWS on the probe both arrive here as
|
||||
* tools=0, and the difference is the difference between a model that cannot call tools and a
|
||||
* gap in the engine. Loud: every statement of every render, the serving ones included. */
|
||||
/* The template engine's own trace. The capability probe in common_chat_templates_init
|
||||
* swallows every exception, so a template without tool support and one that throws on the
|
||||
* probe both report tools=0; this trace tells them apart. Very verbose: it logs every
|
||||
* statement of every render, serving ones included. */
|
||||
if (const char* dbg = std::getenv("RADIANCE_DEBUG_JINJA"); dbg && *dbg && *dbg != '0')
|
||||
jinja::enable_debug(true);
|
||||
|
||||
const bool fallback = jinja_source.empty();
|
||||
if (fallback) {
|
||||
/* A model with no template is a model whose prompt format we are guessing. ChatML is the
|
||||
* best guess there is and it is still a guess, so it is said out loud once rather than
|
||||
* discovered later from output that reads fine and is formatted wrong. */
|
||||
/* ChatML is only a guess at the prompt format, so warn once. */
|
||||
RAD_WARN("chat: the model declares no chat template; falling back to ChatML. "
|
||||
"If the model was not trained on ChatML its replies will be subtly wrong.");
|
||||
}
|
||||
const std::string src = fallback ? std::string(chatml_source()) : jinja_source;
|
||||
|
||||
try {
|
||||
/* model = nullptr: everything common_chat_templates_init() would read off a llama_model
|
||||
* is passed in as an override instead. See vendor/shim/llama.h. */
|
||||
/* model = nullptr: what would be read off a llama_model is passed in as overrides
|
||||
* (vendor/shim/llama.h). */
|
||||
impl_->tmpls = common_chat_templates_init(nullptr, src, bos, eos);
|
||||
} catch (const std::exception& e) {
|
||||
RAD_ERR("chat: template did not compile: %s", e.what());
|
||||
@@ -106,9 +98,8 @@ int ChatTemplate::load(const std::string& jinja_source, const std::string& bos,
|
||||
}
|
||||
|
||||
int ChatTemplate::load_from_vocab(const Vocab& v) {
|
||||
/* The template references bos_token and eos_token by TEXT, not by id, so what goes in is the
|
||||
* piece -- and a control token's piece is its literal spelling, which is what Vocab::text()
|
||||
* returns for it. */
|
||||
/* Templates reference bos_token/eos_token by text; Vocab::text() returns a control token's
|
||||
* literal spelling. */
|
||||
const std::string bos = v.bos() >= 0 ? v.text(v.bos()) : std::string();
|
||||
const std::string eos = v.eos() >= 0 ? v.text(v.eos()) : std::string();
|
||||
return load(v.chat_template(), bos, eos, v.add_bos(), v.add_eos());
|
||||
@@ -118,16 +109,14 @@ bool ChatTemplate::ready() const { return impl_ && impl_->tmpls != nullptr; }
|
||||
const ChatCaps& ChatTemplate::caps() const { return impl_->caps; }
|
||||
const std::string& ChatTemplate::source() const { return impl_->src; }
|
||||
|
||||
/* HOW DEEPLY A CLIENT'S SCHEMA MAY NEST, in objects and arrays. The tools' parameter schemas and
|
||||
* a response format's schema reach the JSON-schema converter, which recurses once per level and
|
||||
* names each rule after its whole path, so its output grows with the square of the depth; a few
|
||||
* thousand levels exhaust the memory or the stack of the thread rendering the request. At this
|
||||
* depth it still converts in tens of milliseconds, far deeper than a schema describing data
|
||||
* nests. grammar.cpp bounds the same converter on the path that bypasses the template. */
|
||||
/* Maximum nesting (objects and arrays) of a client's tool or response schema. The JSON-schema
|
||||
* converter recurses once per level and names each rule after its full path, so its output grows
|
||||
* with the square of the depth; a few thousand levels exhaust memory or the rendering thread's
|
||||
* stack. 512 still converts in tens of milliseconds. grammar.cpp bounds the same converter on the
|
||||
* path that bypasses the template. */
|
||||
static constexpr size_t kMaxSchemaDepth = 512;
|
||||
|
||||
/* Walked with an explicit stack, because the values it exists to catch are the ones too deep to
|
||||
* recurse over. */
|
||||
/* Iterative, because the values it must catch are too deep to recurse over. */
|
||||
static size_t json_depth(const ojson& root) {
|
||||
std::vector<std::pair<const ojson*, size_t>> todo{ { &root, 1 } };
|
||||
size_t deepest = 0;
|
||||
@@ -149,8 +138,8 @@ int ChatTemplate::apply(const ojson& messages, const ojson& tools, const ChatOpt
|
||||
}
|
||||
if (!out) return RAD_E_INVAL;
|
||||
|
||||
/* Checked before either schema reaches the converter. The response format arrives as text;
|
||||
* one that does not parse is left for the template to refuse in its own words. */
|
||||
/* Checked before either schema reaches the converter. A response format that does not parse
|
||||
* is left for the template to refuse. */
|
||||
{
|
||||
const ojson schema = opt.json_schema.empty()
|
||||
? ojson()
|
||||
@@ -166,19 +155,17 @@ int ChatTemplate::apply(const ojson& messages, const ojson& tools, const ChatOpt
|
||||
common_chat_templates_inputs in;
|
||||
try {
|
||||
in.messages = common_chat_msgs_parse_oaicompat(messages);
|
||||
if (!tools.is_null() && tools.is_array() && !tools.empty())
|
||||
if (tools.is_array() && !tools.empty())
|
||||
in.tools = common_chat_tools_parse_oaicompat(tools);
|
||||
in.tool_choice = common_chat_tool_choice_parse_oaicompat(opt.tool_choice);
|
||||
} catch (const std::exception& e) {
|
||||
/* A malformed request, not a broken engine. It must come back as a 400 rather than as a
|
||||
* throw through the request loop. */
|
||||
/* A malformed request: return a 400, never throw through the request loop. */
|
||||
RAD_WARN("chat: request did not parse: %s", e.what());
|
||||
out->error = e.what();
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (!in.tools.empty() && !impl_->caps.tools) {
|
||||
RAD_WARN("chat: the model's template declares no tool support; refusing the request "
|
||||
"rather than dropping the tools silently");
|
||||
RAD_WARN("chat: the model's template declares no tool support; request refused");
|
||||
out->error = "this model's chat template declares no tool support";
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
@@ -228,11 +215,8 @@ int ChatTemplate::apply(const ojson& messages, const ojson& tools, const ChatOpt
|
||||
out->grammar.size(), out->grammar_lazy ? " (lazy)" : "",
|
||||
out->additional_stops.size());
|
||||
if ((int)log_level() >= (int)Log::Trace) {
|
||||
/* THE PROMPT ITSELF, at Trace and nowhere else. A chat endpoint that answers fluently in
|
||||
* the wrong format looks exactly like a chat endpoint that works, and the only way to tell
|
||||
* the two apart is to read what the template actually produced -- control tokens included,
|
||||
* which is why this prints the raw bytes rather than the detokenised form. It is at Trace
|
||||
* because it is user content and does not belong in an ordinary server log. */
|
||||
/* The rendered prompt as raw bytes, control tokens included, for checking the template's
|
||||
* output format. Trace only, because it is user content. */
|
||||
RAD_TRACE("chat: prompt <<<%s>>>", out->prompt.c_str());
|
||||
if (!out->grammar.empty()) RAD_TRACE("chat: grammar <<<%s>>>", out->grammar.c_str());
|
||||
for (const auto& s : out->additional_stops) RAD_TRACE("chat: extra stop <<<%s>>>", s.c_str());
|
||||
|
||||
+32
-45
@@ -1,22 +1,19 @@
|
||||
/* chat.h -- rendering a message list to a prompt, and what the template can do.
|
||||
*
|
||||
* This is a thin face over the lifted `common_chat_*` API (vendor/llama/common/chat.*, jinja/,
|
||||
* see vendor/UPSTREAM). It does three things the lift does not:
|
||||
* A thin layer over the lifted `common_chat_*` API (vendor/llama/common/chat.*, jinja/, see
|
||||
* vendor/UPSTREAM). It adds three things:
|
||||
*
|
||||
* 1. ERRORS ARE VALUES. Upstream throws -- a bad template, a message the template rejects, a
|
||||
* malformed OAI request are all std::runtime_error, and a throw crossing the server's
|
||||
* request loop is not a failure mode this project accepts. Everything here returns a
|
||||
* negative RAD_E_* and logs once.
|
||||
* 2. It takes the template out of the .rad instead of out of a llama_model. RadVocabHeader
|
||||
* carries the chat template, the BOS/EOS spellings and the add_bos/add_eos flags, which is
|
||||
* exactly the four things common_chat_templates_init() would otherwise read off a model.
|
||||
* 3. It keeps the lifted headers out of the rest of core/. Only chat.cpp, chatfmt.cpp and
|
||||
* chatparse.cpp include them, the last only to resolve schema types when a request's tools
|
||||
* are bound, so a vendor refresh cannot ripple into the server.
|
||||
* 1. Errors are values. Upstream throws std::runtime_error for a bad template, a rejected
|
||||
* message or a malformed OAI request; a throw must not cross the server's request loop, so
|
||||
* everything here returns a negative RAD_E_* and logs once.
|
||||
* 2. The template comes from the .rad, not a llama_model. RadVocabHeader carries the chat
|
||||
* template, the BOS/EOS spellings and the add_bos/add_eos flags, the four things
|
||||
* common_chat_templates_init() would otherwise read off a model.
|
||||
* 3. The lifted headers stay out of the rest of core/. Only chat.cpp, chatfmt.cpp and
|
||||
* chatparse.cpp include them (the last only to resolve schema types for bound tools), so a
|
||||
* vendor refresh cannot ripple into the server.
|
||||
*
|
||||
* Messages and tools arrive as OpenAI-shaped JSON, because that is what the server has and the
|
||||
* lift already knows how to read it. Converting to a struct here and back inside would be a
|
||||
* translation nobody asked for.
|
||||
* Messages and tools are OpenAI-shaped JSON, which is what the server has and what the lift reads.
|
||||
*/
|
||||
#pragma once
|
||||
#include "rad_internal.h"
|
||||
@@ -32,10 +29,9 @@ namespace rad {
|
||||
|
||||
class Vocab;
|
||||
|
||||
/* What the template supports, PROBED rather than assumed -- jinja/caps.cpp renders the template
|
||||
* against synthetic inputs and watches what it does with them (spec §12, "template capability
|
||||
* probe"). The server reports this on /props, and the message adapter uses it to decide whether
|
||||
* to hand the template a string content or a typed content array. */
|
||||
/* What the template supports, probed rather than assumed: jinja/caps.cpp renders the template
|
||||
* against synthetic inputs and watches what it reads (spec §12, "template capability probe").
|
||||
* Reported on /props; the message adapter uses it to choose string or typed-array content. */
|
||||
struct ChatCaps {
|
||||
bool tools = true;
|
||||
bool tool_calls = true;
|
||||
@@ -45,7 +41,6 @@ struct ChatCaps {
|
||||
bool string_content = true;
|
||||
bool typed_content = false;
|
||||
bool object_arguments = false;
|
||||
|
||||
};
|
||||
|
||||
struct ChatOptions {
|
||||
@@ -81,22 +76,16 @@ struct ChatPrompt {
|
||||
bool supports_thinking = false;
|
||||
std::string thinking_start_tag, thinking_end_tag;
|
||||
|
||||
/* The auto-parser's own verdict on this render: `format` is a common_chat_format value and
|
||||
* deliberately opaque here, `parser` the PEG grammar it derived. The engine reads replies
|
||||
* with chatparse.h instead; these are kept for the differential tests that compare the two. */
|
||||
/* The auto-parser's verdict on this render: `format` is an opaque common_chat_format value,
|
||||
* `parser` the PEG grammar it derived. The engine parses replies with chatparse.h; these are
|
||||
* kept for the differential tests that compare the two. */
|
||||
int format = 0;
|
||||
std::string parser;
|
||||
|
||||
/* WHY THE TEMPLATE REFUSED, in the template's own words.
|
||||
*
|
||||
* A jinja `raise_exception` carries the one sentence that says what the caller got wrong --
|
||||
* "Unexpected reasoning effort high. Supported types are xhigh (default), medium, and low."
|
||||
* -- and it is carried out to the caller here rather than only into the log, so a 400 names
|
||||
* the field at fault instead of saying only that the template refused the request. Filled
|
||||
* only on a failure return; empty otherwise.
|
||||
*
|
||||
* It is the TEMPLATE'S text and therefore model-controlled, not attacker-controlled: it comes
|
||||
* from the container's own jinja, which the operator chose along with the weights. */
|
||||
/* Why the template refused, in its own words (a jinja `raise_exception` message such as
|
||||
* "Unexpected reasoning effort high. Supported types are ..."), so a 400 names the field at
|
||||
* fault. Set only on a failure return. The text comes from the container's jinja, so it is
|
||||
* model-controlled, not attacker-controlled. */
|
||||
std::string error;
|
||||
};
|
||||
|
||||
@@ -105,29 +94,27 @@ public:
|
||||
ChatTemplate();
|
||||
~ChatTemplate();
|
||||
|
||||
/* Compile a Jinja source. `bos`/`eos` are the token TEXTS, which templates reference as
|
||||
* `bos_token` / `eos_token`. An empty source loads the ChatML fallback and says so at Warn:
|
||||
* a model with no template is a model whose prompt format we are guessing, and guessing
|
||||
* quietly is how a chat endpoint produces fluent nonsense. */
|
||||
/* Compile a Jinja source. `bos`/`eos` are the token texts, which templates reference as
|
||||
* `bos_token` / `eos_token`. An empty source loads the ChatML fallback with a Warn, since the
|
||||
* prompt format is then a guess. */
|
||||
int load(const std::string& jinja_source, const std::string& bos, const std::string& eos,
|
||||
bool add_bos = false, bool add_eos = false);
|
||||
/* The same, from a loaded vocab: template, bos text, eos text and the add flags all come off
|
||||
* RadVocabHeader. This is the path the engine uses. */
|
||||
/* The same, with template, bos/eos text and add flags taken from the vocab's RadVocabHeader.
|
||||
* The engine uses this path. */
|
||||
int load_from_vocab(const Vocab& v);
|
||||
|
||||
bool ready() const;
|
||||
const ChatCaps& caps() const;
|
||||
const std::string& source() const;
|
||||
|
||||
/* Render. `messages` and `tools` are OpenAI-shaped JSON (`tools` may be null or an empty
|
||||
* array). Returns RAD_OK, or RAD_E_INVAL when the request does not parse, or
|
||||
* RAD_E_UNSUPPORTED when the template refuses what was asked of it -- a system message to a
|
||||
* template with no system role, tools to a template that has none. */
|
||||
/* Render. `messages` and `tools` are OpenAI-shaped JSON (`tools` may be null or empty).
|
||||
* Returns RAD_OK, RAD_E_INVAL when the request does not parse, or RAD_E_UNSUPPORTED when the
|
||||
* template refuses it (e.g. a system message without a system role, or tools without tool
|
||||
* support). */
|
||||
int apply(const nlohmann::ordered_json& messages, const nlohmann::ordered_json& tools,
|
||||
const ChatOptions& opt, ChatPrompt* out) const;
|
||||
|
||||
/* ChatML, the fallback. Named rather than inlined so the server can report which template it
|
||||
* is running. */
|
||||
/* The ChatML fallback, named so the server can report which template it runs. */
|
||||
static const char* chatml_source();
|
||||
|
||||
private:
|
||||
|
||||
+77
-90
@@ -3,8 +3,8 @@
|
||||
|
||||
#include "rad_builder.h"
|
||||
|
||||
/* The analyser and the grammar builder, at load and admission time only -- never while a reply
|
||||
* is being read. */
|
||||
/* The analyser and grammar builder, used at load and admission only, never while reading a
|
||||
* reply. */
|
||||
#include "llama/common/chat.h"
|
||||
#include "llama/common/chat-auto-parser.h"
|
||||
#include "llama/common/json-schema-to-grammar.h"
|
||||
@@ -44,6 +44,12 @@ bool starts_with(const std::string& s, const std::string& p) {
|
||||
return s.size() >= p.size() && s.compare(0, p.size(), p) == 0;
|
||||
}
|
||||
|
||||
/* Two delimiters an automaton scanning for both cannot report in start order: one begins or
|
||||
* occurs inside the other. */
|
||||
bool confusable(const std::string& a, const std::string& b) {
|
||||
return starts_with(a, b) || starts_with(b, a) || occurs_inside(a, b) || occurs_inside(b, a);
|
||||
}
|
||||
|
||||
std::string show(const std::string& s) { return nlohmann::json(s).dump(); }
|
||||
|
||||
int refuse(std::string* why, const std::string& s) {
|
||||
@@ -56,11 +62,11 @@ bool object_byte(unsigned char c) {
|
||||
return c == 0 || std::isalnum(c) || is_ws(c) || std::strchr("-+._'\"{}[],:", (int)c) != nullptr;
|
||||
}
|
||||
|
||||
/* An argument object, as the streaming parser reads it (chatparse.cpp). Where a key or a value
|
||||
* may begin, it tells three literals apart by their first bytes: a dialect string's opener, and
|
||||
* the call's close and end, which a reply that leaves its object unclosed writes there. None may
|
||||
* begin another. A bare word ends at the object's punctuation or at the call's close; one
|
||||
* automaton finds both in the order they start only when the close holds none of it. */
|
||||
/* Checks an argument object against how chatparse.cpp reads it. Where a key or value may begin,
|
||||
* the parser tells three literals apart by their first bytes: the dialect's string opener, and
|
||||
* the call's close and end (a reply that leaves its object unclosed writes them there). None may
|
||||
* begin another. A bare word ends at the object's punctuation or the call's close; one automaton
|
||||
* reports both in start order only if the close contains no punctuation. */
|
||||
int object_check(const ChatFormat& f, std::string* why) {
|
||||
const std::string& so = f.object_string_open;
|
||||
const std::string& sc = f.object_string_close;
|
||||
@@ -90,16 +96,15 @@ int object_check(const ChatFormat& f, std::string* why) {
|
||||
return refuse(why, show(*s) + " both opens an object string and closes the call");
|
||||
}
|
||||
for (size_t i = 0; i < lits.size(); ++i)
|
||||
for (size_t j = 0; j < lits.size(); ++j)
|
||||
if (i != j && (starts_with(lits[i], lits[j]) || occurs_inside(lits[j], lits[i])))
|
||||
return refuse(why, show(lits[j]) + " and " + show(lits[i]) + " cannot be told "
|
||||
for (size_t j = i + 1; j < lits.size(); ++j)
|
||||
if (confusable(lits[i], lits[j]))
|
||||
return refuse(why, show(lits[i]) + " and " + show(lits[j]) + " cannot be told "
|
||||
"apart inside an argument object");
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* Content is scanned for a later reasoning block's opener and for a stray close beside the call
|
||||
* openers, in one automaton, which reports them in the order they start only when none occurs
|
||||
* inside another or begins it. */
|
||||
/* Content is scanned for a later reasoning opener, a stray close and the call openers in one
|
||||
* automaton, which reports them in start order only if none begins or occurs inside another. */
|
||||
int reasoning_anywhere_check(const ChatFormat& f, std::string* why) {
|
||||
if (!f.reasoning_anywhere) return RAD_OK;
|
||||
std::vector<std::string> d = { trim_ws(f.reasoning_open), trim_ws(f.reasoning_close) };
|
||||
@@ -108,9 +113,9 @@ int reasoning_anywhere_check(const ChatFormat& f, std::string* why) {
|
||||
d.push_back(f.name_prefix);
|
||||
}
|
||||
for (size_t i = 0; i < d.size(); ++i)
|
||||
for (size_t j = 0; j < d.size(); ++j)
|
||||
if (i != j && (starts_with(d[i], d[j]) || occurs_inside(d[j], d[i])))
|
||||
return refuse(why, show(d[j]) + " and " + show(d[i]) + " cannot be told apart in "
|
||||
for (size_t j = i + 1; j < d.size(); ++j)
|
||||
if (confusable(d[i], d[j]))
|
||||
return refuse(why, show(d[i]) + " and " + show(d[j]) + " cannot be told apart in "
|
||||
"content, which a reasoning block may open anywhere in");
|
||||
return RAD_OK;
|
||||
}
|
||||
@@ -120,10 +125,7 @@ int reasoning_anywhere_check(const ChatFormat& f, std::string* why) {
|
||||
/* ================================================================== validity */
|
||||
|
||||
int chat_format_check(const ChatFormat& f, std::string* why) {
|
||||
auto no = [&](const std::string& s) {
|
||||
if (why) *why = s;
|
||||
return RAD_E_UNSUPPORTED;
|
||||
};
|
||||
auto no = [why](const std::string& s) { return refuse(why, s); };
|
||||
|
||||
if (!f.reasoning_open.empty() && f.reasoning_close.empty())
|
||||
return no("reasoning_open " + show(f.reasoning_open) + " has no reasoning_close");
|
||||
@@ -202,8 +204,7 @@ int chat_format_check(const ChatFormat& f, std::string* why) {
|
||||
if (!f.call_open.empty()) {
|
||||
const std::string co = trim_ws(f.call_open);
|
||||
if (co.empty()) return no("call_open is only whitespace");
|
||||
if (starts_with(co, f.name_prefix) || starts_with(f.name_prefix, co) ||
|
||||
occurs_inside(co, f.name_prefix) || occurs_inside(f.name_prefix, co))
|
||||
if (confusable(co, f.name_prefix))
|
||||
return no("call_open " + show(f.call_open) + " and name_prefix " +
|
||||
show(f.name_prefix) + " cannot be told apart");
|
||||
}
|
||||
@@ -216,25 +217,22 @@ int chat_format_check(const ChatFormat& f, std::string* why) {
|
||||
for (const std::string& t : f.triggers)
|
||||
if (t.empty()) return no("an empty grammar trigger");
|
||||
|
||||
/* The delimiter sets scanned together must be read in the order they START, which an
|
||||
* automaton reports correctly only when no delimiter occurs inside another. */
|
||||
/* Delimiters scanned together must be reported in start order, which an automaton does only
|
||||
* when no delimiter occurs inside another. */
|
||||
if (f.has_reasoning()) {
|
||||
const std::string close = trim_ws(f.reasoning_close);
|
||||
for (const std::string& b : f.reasoning_breaks)
|
||||
if (occurs_inside(close, b) || occurs_inside(b, close) || starts_with(b, close) ||
|
||||
starts_with(close, b))
|
||||
if (confusable(close, b))
|
||||
return no("reasoning break " + show(b) + " overlaps reasoning_close " +
|
||||
show(close));
|
||||
}
|
||||
if (!object) {
|
||||
/* Inside a call the next tag is an argument or the close, and the close is recognised by
|
||||
* its core as well: the whitespace around it is optional when a reply leaves the
|
||||
* format. */
|
||||
/* Inside a call the next tag is an argument or the close. The close also matches by its
|
||||
* trimmed core, since a reply that strays from the format may drop its whitespace. */
|
||||
const std::string end = trim_ws(f.call_end);
|
||||
if (end.empty()) return no("call_end is only whitespace");
|
||||
for (const std::string* e : { &f.call_end, &end })
|
||||
if (starts_with(f.arg_prefix, *e) || starts_with(*e, f.arg_prefix) ||
|
||||
occurs_inside(f.arg_prefix, *e) || occurs_inside(*e, f.arg_prefix))
|
||||
if (confusable(f.arg_prefix, *e))
|
||||
return no("arg_prefix " + show(f.arg_prefix) + " and call_end " +
|
||||
show(f.call_end) + " cannot be told apart");
|
||||
}
|
||||
@@ -299,9 +297,9 @@ int chat_format_from_abi(const RadChatFormat* in, ChatFormat* out, std::string*
|
||||
int chat_format_from_template(const std::string& jinja, const std::string& bos,
|
||||
const std::string& eos, ChatFormat* out,
|
||||
std::string* tools_refused, std::string* why) {
|
||||
std::string dummy;
|
||||
if (!tools_refused) tools_refused = &dummy;
|
||||
if (!why) why = &dummy;
|
||||
std::string refused_unused, why_unused;
|
||||
if (!tools_refused) tools_refused = &refused_unused;
|
||||
if (!why) why = &why_unused;
|
||||
tools_refused->clear();
|
||||
const std::string src = jinja.empty() ? std::string(ChatTemplate::chatml_source()) : jinja;
|
||||
|
||||
@@ -367,10 +365,9 @@ int chat_format_from_template(const std::string& jinja, const std::string& bos,
|
||||
c.string_value = ChatValue::Cdata;
|
||||
c.other_value = ChatValue::Json;
|
||||
c.value_newlines = true;
|
||||
/* What opens a call is what both the lazy grammar waits for and what ends an
|
||||
* unclosed reasoning block -- the section or per-call opener. A format with neither
|
||||
* gets no grammar and no break: its calls open with the function name prefix, which
|
||||
* a model also writes in prose. */
|
||||
/* The section or per-call opener both triggers the lazy grammar and ends an
|
||||
* unclosed reasoning block. A format with neither gets no grammar and no break,
|
||||
* since its calls open with the name prefix, which a model also writes in prose. */
|
||||
const std::string& marker = !t.format.section_start.empty() ? t.format.section_start
|
||||
: t.format.per_call_start;
|
||||
if (!marker.empty()) {
|
||||
@@ -437,11 +434,10 @@ std::vector<std::string> chat_format_markers(const ChatFormat& f) {
|
||||
|
||||
/* ================================================================== grammar
|
||||
*
|
||||
* The grammar is built as an expression tree and rendered by the rules the vendored PEG-to-GBNF
|
||||
* pass uses, so a format derived from a template yields the same text the vendored generator
|
||||
* produces for it: sequences and alternations are flattened as they are built, a sequence or
|
||||
* alternation nested in a sequence is parenthesised, only an alternation nested in an
|
||||
* alternation is, and a repeated sequence or alternation is. */
|
||||
* The grammar is an expression tree rendered by the vendored PEG-to-GBNF rules, so a
|
||||
* template-derived format yields the same text as the vendored generator. Sequences and
|
||||
* alternations flatten as they are built. Parentheses go around a sequence or alternation inside
|
||||
* a sequence, an alternation inside an alternation, and a repeated sequence or alternation. */
|
||||
namespace {
|
||||
|
||||
struct G {
|
||||
@@ -449,7 +445,6 @@ struct G {
|
||||
std::string s; /* Lit: the text; Leaf: rendered GBNF */
|
||||
std::vector<G> kids;
|
||||
int min = 0, max = -1;
|
||||
bool compound = false; /* Leaf/Wrap: renders like a sequence for parenthesising */
|
||||
};
|
||||
|
||||
G eps() { return G{}; }
|
||||
@@ -458,26 +453,21 @@ G leaf(const std::string& s) { G g; g.k = G::Leaf; g.s = s; return g; }
|
||||
G space() { return leaf("space"); }
|
||||
G rule_ref(const std::string& name) { return leaf(name); }
|
||||
|
||||
/* A tag or an atomic around a node: it renders as the node, is parenthesised as the node would
|
||||
* be, but a sequence built around it does not flatten into it. */
|
||||
/* A tag or atomic around a node: renders and parenthesises as the node, but an enclosing
|
||||
* sequence does not flatten into it. */
|
||||
G wrap(G inner) { G g; g.k = G::Wrap; g.kids.push_back(std::move(inner)); return g; }
|
||||
|
||||
G seq(std::vector<G> parts) {
|
||||
G g; g.k = G::Seq;
|
||||
/* A sequence or alternation of `parts`, a part of the same kind spliced in flat. */
|
||||
G flat(G::K k, std::vector<G> parts) {
|
||||
G g; g.k = k;
|
||||
for (G& p : parts) {
|
||||
if (p.k == G::Seq) for (G& c : p.kids) g.kids.push_back(std::move(c));
|
||||
else g.kids.push_back(std::move(p));
|
||||
}
|
||||
return g;
|
||||
}
|
||||
G alt(std::vector<G> parts) {
|
||||
G g; g.k = G::Alt;
|
||||
for (G& p : parts) {
|
||||
if (p.k == G::Alt) for (G& c : p.kids) g.kids.push_back(std::move(c));
|
||||
if (p.k == k) for (G& c : p.kids) g.kids.push_back(std::move(c));
|
||||
else g.kids.push_back(std::move(p));
|
||||
}
|
||||
return g;
|
||||
}
|
||||
G seq(std::vector<G> parts) { return flat(G::Seq, std::move(parts)); }
|
||||
G alt(std::vector<G> parts) { return flat(G::Alt, std::move(parts)); }
|
||||
G rep(G child, int min, int max) {
|
||||
G g; g.k = G::Rep; g.min = min; g.max = max; g.kids.push_back(std::move(child)); return g;
|
||||
}
|
||||
@@ -542,10 +532,9 @@ std::string class_char(uint32_t c) {
|
||||
if (c == '\r') return "\\r";
|
||||
if (c >= 0x20 && c <= 0x7E) return std::string(1, (char)c);
|
||||
static const char* hex = "0123456789ABCDEF";
|
||||
std::string s;
|
||||
if (c <= 0xFF) { s = "\\x"; for (int i = 1; i >= 0; --i) s += hex[(c >> (4 * i)) & 15]; }
|
||||
else if (c <= 0xFFFF) { s = "\\u"; for (int i = 3; i >= 0; --i) s += hex[(c >> (4 * i)) & 15]; }
|
||||
else { s = "\\U"; for (int i = 7; i >= 0; --i) s += hex[(c >> (4 * i)) & 15]; }
|
||||
const int digits = c <= 0xFF ? 2 : c <= 0xFFFF ? 4 : 8;
|
||||
std::string s = digits == 2 ? "\\x" : digits == 4 ? "\\u" : "\\U";
|
||||
for (int i = digits - 1; i >= 0; --i) s += hex[(c >> (4 * i)) & 15];
|
||||
return s;
|
||||
}
|
||||
|
||||
@@ -636,10 +625,9 @@ std::string until_pattern(const std::vector<std::string>& delims) {
|
||||
return "(" + pattern + ")*";
|
||||
}
|
||||
|
||||
/* The rules the vendored generator emits for its generic JSON parser whenever an argument or a
|
||||
* document is typed by a schema. Nothing references them -- the schema's own rules do the
|
||||
* constraining -- but the vendored grammar carries them, and so does this one, so the two can be
|
||||
* compared byte for byte. */
|
||||
/* The generic JSON rules the vendored generator emits whenever a schema types an argument or
|
||||
* document. Nothing references them (the schema's own rules constrain), but they are emitted so
|
||||
* the output compares byte for byte with the vendored grammar. */
|
||||
void add_json_rules(const common_grammar_builder& b) {
|
||||
b.add_rule("json-array", "\"[\" space (\"]\" | json-value (\",\" space json-value)* space "
|
||||
"\"]\") space");
|
||||
@@ -656,12 +644,10 @@ void add_json_rules(const common_grammar_builder& b) {
|
||||
"json-null");
|
||||
}
|
||||
|
||||
/* THE ARGUMENT OBJECT of the object family, in its dialect: JSON, or strings between the
|
||||
* declared delimiters and keys written bare. As llama.cpp's own Gemma 4 grammar does, it fixes
|
||||
* the syntax and leaves the values to the model: a tool's schema says what JSON a value must be,
|
||||
* and the dialect is not JSON, so the schema converter has nothing to say about it. Whitespace
|
||||
* goes where the dialect's writers put it -- after a separator and inside the brackets -- and
|
||||
* nowhere else. */
|
||||
/* The object family's argument object in its dialect: JSON, or strings between the declared
|
||||
* delimiters and bare keys. Like llama.cpp's Gemma 4 grammar, it fixes the syntax and leaves
|
||||
* values unconstrained, since a tool's schema describes JSON and the dialect is not JSON.
|
||||
* Whitespace is allowed only after a separator and inside the brackets. */
|
||||
void add_object_rules(const common_grammar_builder& b, const ChatFormat& f) {
|
||||
const std::string& so = f.object_string_open;
|
||||
if (!so.empty())
|
||||
@@ -672,10 +658,10 @@ void add_object_rules(const common_grammar_builder& b, const ChatFormat& f) {
|
||||
b.add_rule("obj-string", "\"\\\"\" ( [^\"\\\\] | \"\\\\\" ( [\"\\\\/ bfnrt] | \"u\" "
|
||||
"[0-9a-fA-F]{4} ) )* \"\\\"\"");
|
||||
b.add_rule("obj-number", "\"-\"? (\"0\" | [1-9] [0-9]*) (\".\" [0-9]+)? ([eE] [+-]? [0-9]+)?");
|
||||
/* A dialect with strings of its own still gets a value in Python's quotes, `'...'`, which
|
||||
* is how Gemma 4 writes arguments it was handed as JSON (measured). Refused, the model
|
||||
* takes the next token the grammar allows -- a `-` -- and every such string becomes a
|
||||
* number; the parser reads the quoted text verbatim but for an escaped quote. */
|
||||
/* A dialect with its own strings also admits Python-quoted `'...'` values, which Gemma 4
|
||||
* writes for arguments it was given as JSON. Without this the model takes the next allowed
|
||||
* token, `-`, and the string becomes a number. The parser reads the quoted text verbatim
|
||||
* except for an escaped quote. */
|
||||
const char* sq = so.empty() ? "" : " | obj-sqstring";
|
||||
if (!so.empty()) b.add_rule("obj-sqstring", "\"'\" ( [^'\\\\] | \"\\\\\" [^\\x00] )* \"'\"");
|
||||
b.add_rule("obj-value", std::string("obj-object | obj-array | obj-string") + sq +
|
||||
@@ -728,6 +714,11 @@ G reasoning_expr(const ChatFormat& f, const std::vector<std::string>& breaks) {
|
||||
|
||||
} /* namespace */
|
||||
|
||||
bool chat_function_tool(const ojson& tool) {
|
||||
return tool.is_object() && tool.contains("type") && tool.at("type") == "function" &&
|
||||
tool.contains("function");
|
||||
}
|
||||
|
||||
int chat_format_grammar(const ChatFormat& f, const ChatGrammarRequest& req, ChatGrammar* out,
|
||||
std::string* why) {
|
||||
*out = ChatGrammar{};
|
||||
@@ -751,9 +742,7 @@ int chat_format_grammar(const ChatFormat& f, const ChatGrammarRequest& req, Chat
|
||||
try {
|
||||
out->text = build_grammar([&](const common_grammar_builder& b) {
|
||||
for (const auto& tool : tools) {
|
||||
if (!tool.is_object() || !tool.contains("type") || tool.at("type") != "function" ||
|
||||
!tool.contains("function"))
|
||||
continue;
|
||||
if (!chat_function_tool(tool)) continue;
|
||||
const auto& fn = tool.at("function");
|
||||
auto schema = fn.contains("parameters") ? fn.at("parameters") : ojson::object();
|
||||
b.resolve_refs(schema);
|
||||
@@ -796,9 +785,7 @@ int chat_format_grammar(const ChatFormat& f, const ChatGrammarRequest& req, Chat
|
||||
std::vector<G> choices;
|
||||
bool typed = false;
|
||||
for (const auto& tool : tools) {
|
||||
if (!tool.is_object() || !tool.contains("type") || tool.at("type") != "function" ||
|
||||
!tool.contains("function"))
|
||||
continue;
|
||||
if (!chat_function_tool(tool)) continue;
|
||||
const auto& fn = tool.at("function");
|
||||
const std::string name = fn.at("name");
|
||||
if (!req.only_tool.empty() && name != req.only_tool) continue;
|
||||
@@ -824,11 +811,11 @@ int chat_format_grammar(const ChatFormat& f, const ChatGrammarRequest& req, Chat
|
||||
|
||||
std::vector<G> req_arms, opt_arms;
|
||||
for (const auto& [pname, pschema] : properties.items()) {
|
||||
/* An optional argument no value satisfies -- `false`, or the `not` of a schema
|
||||
* every value satisfies, an Arktype or TypeBox `never` -- is one no call
|
||||
* writes, so it gets no arm; a model that writes it anyway reaches the
|
||||
* undeclared arm below. The template path does the same (vendor/patches/0012,
|
||||
* 0014); required, it goes through the schema and is refused there by name. */
|
||||
/* An optional argument no value satisfies (`false`, or the `not` of an
|
||||
* always-true schema, e.g. Arktype or TypeBox `never`) gets no arm; a model
|
||||
* that writes it reaches the undeclared arm. The template path does the same
|
||||
* (vendor/patches/0012, 0014). A required one goes through the schema and is
|
||||
* refused there by name. */
|
||||
if (!required.count(pname) && info.unsatisfiable(pschema)) continue;
|
||||
G value;
|
||||
if (f.other_value != ChatValue::Json || info.resolves_to_string(pschema)) {
|
||||
@@ -849,8 +836,8 @@ int chat_format_grammar(const ChatFormat& f, const ChatGrammarRequest& req, Chat
|
||||
}
|
||||
std::vector<G> any = req_arms;
|
||||
any.insert(any.end(), opt_arms.begin(), opt_arms.end());
|
||||
/* The generic arm for an undeclared name. A tool that declares no parameters
|
||||
* takes no arguments at all, so its arm is never reached and not emitted. */
|
||||
/* The generic arm for an undeclared name; not emitted for a tool that declares
|
||||
* no parameters, since it takes no arguments. */
|
||||
if (!any.empty()) {
|
||||
G arm = wrap(seq({ wrap(seq({ lit(f.arg_prefix),
|
||||
wrap(leaf(until_pattern({ name_end }))),
|
||||
@@ -892,8 +879,8 @@ int chat_format_grammar(const ChatFormat& f, const ChatGrammarRequest& req, Chat
|
||||
}
|
||||
b.add_rule("tool-call", render(calls));
|
||||
if (req.require_call) {
|
||||
/* The calls and nothing after them: a complete grammar admits only the end of
|
||||
* the turn, so the reply stops at the last call's closer. */
|
||||
/* Nothing after the calls: a complete grammar admits only the end of the turn,
|
||||
* so the reply stops at the last call's closer. */
|
||||
std::vector<G> root = whole_reply();
|
||||
root.push_back(rule_ref("tool-call"));
|
||||
b.add_rule("root", render(seq(std::move(root))));
|
||||
|
||||
+73
-81
@@ -1,59 +1,51 @@
|
||||
/* chatfmt.h -- how a model spells a turn: reasoning, tool calls, arguments. As DATA.
|
||||
/* chatfmt.h -- how a model spells a turn (reasoning, tool calls, arguments), as data.
|
||||
*
|
||||
* Everything the engine knows about a model's reply syntax is in one plain struct, ChatFormat,
|
||||
* and everything that depends on that syntax is DERIVED from it: the streaming reply parser
|
||||
* (chatparse.h), the lazy tool-call grammar and the literal words that trigger it (below), and the
|
||||
* tokens the decoder must render as text so the parser can see the structure. A new model is
|
||||
* supported by stating its format once.
|
||||
* Everything the engine knows about a model's reply syntax is in one struct, ChatFormat, and
|
||||
* everything that depends on it is derived from it: the streaming reply parser (chatparse.h), the
|
||||
* lazy tool-call grammar and its trigger words, and the tokens the decoder must render as text so
|
||||
* the parser can see the structure.
|
||||
*
|
||||
* TWO PRODUCERS, IN ORDER OF PRECEDENCE.
|
||||
* Two producers, in order of precedence:
|
||||
*
|
||||
* 1. The architecture plugin, through the optional `rad_arch_chat_format` export
|
||||
* (abi/rad_builder.h). A plugin that knows its model's syntax says so and nothing is guessed.
|
||||
* (abi/rad_builder.h).
|
||||
* 2. Analysis of the chat template. llama.cpp's differential analyser renders the template with
|
||||
* and without a reasoning block, a call and its arguments, and diffs the renders to find the
|
||||
* delimiters (vendor/llama/common/chat-diff-analyzer.cpp). Its derived MARKERS are read here;
|
||||
* delimiters (vendor/llama/common/chat-diff-analyzer.cpp). Its derived markers are read here;
|
||||
* its PEG parser is not used.
|
||||
*
|
||||
* If neither yields a format the parser can run, the model still chats -- the reply is content --
|
||||
* but a request that sends tools is refused, naming why. There is no second parser to fall back
|
||||
* to: a reply format the engine cannot describe is a reply it cannot read, and saying so at
|
||||
* admission is better than returning a call as prose.
|
||||
* If neither yields a format the parser can run, the model still chats (the reply is content) but
|
||||
* a request with tools is refused, naming why. There is no fallback parser.
|
||||
*
|
||||
* THE FAMILY THIS DESCRIBES is the tagged one, which covers every model this engine serves:
|
||||
* Tagged family:
|
||||
*
|
||||
* Qwen3.6 / Qwen3.8 <tool_call>\n<function=NAME>\n<parameter=ARG>\nVALUE\n</parameter>\n
|
||||
* </function>\n</tool_call>
|
||||
* MiniCPM5 <function name="NAME"><param name="ARG">VALUE</param></function>
|
||||
*
|
||||
* A call's name is written between a prefix and a suffix and it ends with its own close; each
|
||||
* argument is a name between a prefix and a suffix and a value ending at its own suffix; calls may
|
||||
* be wrapped one by one. Arguments are typed by the tool's JSON schema: a string-typed argument is
|
||||
* the raw text (optionally CDATA-wrapped), any other type is JSON, and text that does not parse as
|
||||
* JSON is taken raw -- a model writing into an XML tag writes Python as often as JSON.
|
||||
* A call's name sits between a prefix and a suffix and the call ends with its own close; each
|
||||
* argument is a name between a prefix and a suffix, then a value ending at its own suffix; calls
|
||||
* may be wrapped one by one. Arguments are typed by the tool's JSON schema: a string-typed one is
|
||||
* raw text (optionally CDATA-wrapped), any other type is JSON, and text that does not parse as
|
||||
* JSON is taken raw, since models often write Python literals into a tag.
|
||||
*
|
||||
* THE OBJECT FAMILY writes a call as its name and one object holding the arguments
|
||||
* (ChatArgs::Object):
|
||||
* Object family (ChatArgs::Object): a call is its name and one object holding the arguments.
|
||||
*
|
||||
* Gemma 4 <|tool_call>call:NAME{key:<|"|>text<|"|>,n:3}<tool_call|>
|
||||
*
|
||||
* The object is JSON or a dialect of it -- strings between two declared delimiters with their
|
||||
* text verbatim, keys written bare -- and the arguments a client receives are that object in
|
||||
* JSON. Here the values carry their own types, so no schema is consulted to read them; a bare
|
||||
* word that is no JSON literal or number is read as a string, as a typed argument that is not
|
||||
* JSON is in the tagged family.
|
||||
* The object is JSON or a dialect of it (strings verbatim between two declared delimiters, bare
|
||||
* keys), and the client receives it as JSON. Values carry their own types, so no schema is
|
||||
* consulted; a bare word that is not a JSON literal or number is read as a string.
|
||||
*
|
||||
* The analyser also recognises formats outside these families (a JSON object per call with its
|
||||
* name inside it, call ids). For those chat_format_from_template keeps the reasoning split and
|
||||
* names why tool calls are refused, and a model that needs one gets it by adding the shape to the
|
||||
* parser, not by a fallback. */
|
||||
* The analyser also recognises formats outside these families (a JSON object per call with the
|
||||
* name inside it, call ids). For those, chat_format_from_template keeps the reasoning split and
|
||||
* names why tool calls are refused; supporting one means adding the shape to the parser. */
|
||||
#pragma once
|
||||
#include "rad_internal.h"
|
||||
|
||||
#include <nlohmann/json_fwd.hpp>
|
||||
|
||||
#include <cstdint>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
@@ -70,10 +62,10 @@ enum class ChatValue : uint32_t {
|
||||
|
||||
/* Whether the reply starts inside a reasoning block. The numbering is the ABI's. */
|
||||
enum class ChatThink : uint32_t {
|
||||
/* Search the rendered generation prompt for `reasoning_open`: whatever follows its first
|
||||
* occurrence is the start of the reply's own text. A template that opens the block for the
|
||||
* model (Qwen writes "<think>\n" at the end of the prompt) and one that closes it again when
|
||||
* thinking is off ("<think>\n\n</think>\n\n") are both read correctly this way. */
|
||||
/* Search the rendered generation prompt for `reasoning_open`; what follows its first
|
||||
* occurrence is the start of the reply's text. Handles both a template that opens the block
|
||||
* for the model (Qwen ends the prompt with "<think>\n") and one that closes it again when
|
||||
* thinking is off ("<think>\n\n</think>\n\n"). */
|
||||
FromPrompt = 0,
|
||||
Always = 1, /* the reply is inside a reasoning block from its first byte */
|
||||
Never = 2, /* the model opens its own block, if any */
|
||||
@@ -95,35 +87,34 @@ struct ChatFormat {
|
||||
* and the close ends it. */
|
||||
std::string reasoning_open;
|
||||
std::string reasoning_close;
|
||||
/* Literals that end an UNCLOSED block when a call starts there. A model that forgets to close
|
||||
* its reasoning and goes straight to a call must not have the call swallowed as reasoning.
|
||||
* Must name the call opener (`call_open`) when non-empty. */
|
||||
/* Literals that end an unclosed block when a call starts there, so a model that skips the
|
||||
* close and goes straight to a call does not have the call read as reasoning. When non-empty,
|
||||
* must include the call opener (`call_open`). */
|
||||
std::vector<std::string> reasoning_breaks;
|
||||
ChatThink reasoning_in_prompt = ChatThink::FromPrompt;
|
||||
/* A block may also open later in the reply -- after the answer, between calls -- and is read
|
||||
* as reasoning there; a close with no block open is dropped. Gemma 4 writes an empty block
|
||||
* after its answer now and then, and a lone close. Needs `reasoning_open`. */
|
||||
/* A block may also open later in the reply (after the answer, between calls) and is read as
|
||||
* reasoning there; a close with no block open is dropped. Gemma 4 sometimes writes an empty
|
||||
* block after its answer, or a lone close. Needs `reasoning_open`. */
|
||||
bool reasoning_anywhere = false;
|
||||
|
||||
/* ------------------------------------------------------------------ tool calls
|
||||
* `name_prefix` is what opens a call (after `call_open`, when there is one). Empty means the
|
||||
* format has no tool calls. */
|
||||
std::string section_open, section_close; /* around ALL calls; not read yet, must be empty */
|
||||
/* Between two calls beyond whitespace. Tagged calls are self-delimiting, so this is empty;
|
||||
* a JSON-array format would say ", ". Not read yet, must be empty. */
|
||||
std::string section_open, section_close; /* around all calls; not read yet, must be empty */
|
||||
/* Between two calls, beyond whitespace (a JSON-array format would use ", "). Tagged calls are
|
||||
* self-delimiting. Not read yet, must be empty. */
|
||||
std::string call_separator;
|
||||
/* Around EACH call: "<tool_call>\n", "</tool_call>". When set, a call written without it --
|
||||
* name_prefix alone -- is still read as a call, leniently (chatparse.h). */
|
||||
/* Around each call: "<tool_call>\n", "</tool_call>". When set, a call written without it
|
||||
* (name_prefix alone) is still read as a call (chatparse.h). */
|
||||
std::string call_open, call_close;
|
||||
/* "<function=", ">\n". In the object family name_suffix may be empty: the name then ends
|
||||
* where the object begins, at its `{`. */
|
||||
/* "<function=", ">\n". In the object family name_suffix may be empty; the name then ends at
|
||||
* the object's `{`. */
|
||||
std::string name_prefix, name_suffix;
|
||||
std::string call_end; /* "</function>\n"; may be empty for an object */
|
||||
|
||||
/* How the arguments are written. Object: the arg_* fields below are empty, and these three
|
||||
* describe the object's dialect -- a string delimiter besides JSON's `"`, between which the
|
||||
* text is verbatim ("<|\"|>" twice for Gemma 4; empty for JSON strings only), and whether a
|
||||
* key may be written bare. */
|
||||
/* How the arguments are written. For Object the arg_* fields below are empty and these three
|
||||
* describe the dialect: a string delimiter besides JSON's `"` with verbatim text between
|
||||
* ("<|\"|>" twice for Gemma 4; empty for JSON strings only), and whether keys may be bare. */
|
||||
ChatArgs args_form = ChatArgs::Tagged;
|
||||
std::string object_string_open, object_string_close;
|
||||
bool object_bare_keys = false;
|
||||
@@ -135,13 +126,13 @@ struct ChatFormat {
|
||||
|
||||
ChatValue string_value = ChatValue::Cdata; /* a string-typed argument: Raw or Cdata */
|
||||
ChatValue other_value = ChatValue::Json; /* any other type: Json */
|
||||
/* One newline at each end of a value is punctuation: the template writes the value on its own
|
||||
* lines, and exactly the first and last newline belong to the tags. A tag that ends with its
|
||||
* newline (Qwen's `>\n`) has written the first one already, and the value starts after it. */
|
||||
/* One newline at each end of a value belongs to the tags, since the template writes the
|
||||
* value on its own lines. A tag that ends with its newline (Qwen's `>\n`) has already
|
||||
* consumed the first one. */
|
||||
bool value_newlines = true;
|
||||
|
||||
/* The literal words that start constrained decoding of a call. Empty means no lazy grammar:
|
||||
* the reply is unconstrained and the parser reads whatever arrives. */
|
||||
/* Literal words that start constrained decoding of a call. Empty means no lazy grammar: the
|
||||
* reply is unconstrained. */
|
||||
std::vector<std::string> triggers;
|
||||
|
||||
bool has_reasoning() const { return !reasoning_close.empty(); }
|
||||
@@ -150,22 +141,22 @@ struct ChatFormat {
|
||||
};
|
||||
|
||||
/* Can the streaming parser run this format? RAD_OK, or RAD_E_UNSUPPORTED with *why naming the
|
||||
* field. A format with no tool calls is valid (reasoning split only); a format with tool calls
|
||||
* must describe them completely enough that every delimiter is unambiguous. */
|
||||
* field. A format without tool calls is valid (reasoning split only); one with tool calls must
|
||||
* make every delimiter unambiguous. */
|
||||
int chat_format_check(const ChatFormat& f, std::string* why);
|
||||
|
||||
/* The plugin's declaration, copied out of the ABI struct. Fields past the plugin's
|
||||
* `struct_size` read as their zero. Returns RAD_E_INVAL with *why when the struct is unusable. */
|
||||
/* Copy the plugin's declaration out of the ABI struct. Fields past the plugin's `struct_size`
|
||||
* read as zero. RAD_E_INVAL with *why when the struct is unusable. */
|
||||
int chat_format_from_abi(const RadChatFormat* in, ChatFormat* out, std::string* why);
|
||||
|
||||
/* Derive the format from a chat template by the vendored differential analysis.
|
||||
*
|
||||
* RAD_OK with *out filled. A template whose tool calls the analysis found but this family cannot
|
||||
* express still yields its reasoning split, with the tool fields empty and *tools_refused saying
|
||||
* why -- the model chats, and a request with tools is refused with that sentence. RAD_E_UNSUPPORTED
|
||||
* with *why when the template routes to one of llama.cpp's hand-written handlers, whose formats
|
||||
* the analysis does not describe at all; RAD_E_FORMAT when the template does not compile. An
|
||||
* empty source is the ChatML fallback, which has neither reasoning nor calls. */
|
||||
* RAD_OK with *out filled. If the analysis finds tool calls this family cannot express, the
|
||||
* reasoning split is still returned with the tool fields empty and *tools_refused saying why;
|
||||
* requests with tools are then refused with that sentence. RAD_E_UNSUPPORTED with *why when the
|
||||
* template routes to one of llama.cpp's hand-written handlers, which the analysis does not
|
||||
* describe; RAD_E_FORMAT when the template does not compile. An empty source is the ChatML
|
||||
* fallback, which has neither reasoning nor calls. */
|
||||
int chat_format_from_template(const std::string& jinja, const std::string& bos,
|
||||
const std::string& eos, ChatFormat* out,
|
||||
std::string* tools_refused, std::string* why);
|
||||
@@ -175,21 +166,19 @@ std::string chat_format_describe(const ChatFormat& f);
|
||||
|
||||
/* ================================================================== grammar
|
||||
*
|
||||
* The GBNF that constrains a reply to the format, generated from the description. For a tool
|
||||
* request it is LAZY: the reply is free until one of `triggers` appears, and from there the
|
||||
* grammar admits the call syntax with each argument constrained by its schema. For a response
|
||||
* format, and for a request that requires a call, it is the whole reply. Rule names and structure
|
||||
* follow the vendored generator so the two produce the same grammar for a template-analysed
|
||||
* format. */
|
||||
* The GBNF that constrains a reply to the format. For a tool request it is lazy: the reply is free
|
||||
* until one of `triggers` appears, then the grammar admits the call syntax with each argument
|
||||
* constrained by its schema. For a response format, or a request that requires a call, it covers
|
||||
* the whole reply. Rule names and structure follow the vendored generator, so both produce the
|
||||
* same grammar for a template-analysed format. */
|
||||
struct ChatGrammarRequest {
|
||||
const nlohmann::ordered_json* tools = nullptr; /* the request's tools, or null */
|
||||
const nlohmann::ordered_json* json_schema = nullptr; /* a response format's schema, or null */
|
||||
std::string generation_prompt;
|
||||
bool parallel_tool_calls = true;
|
||||
bool extract_reasoning = true; /* reasoning_format != "none" */
|
||||
/* tool_choice "required" or a named function: the grammar is the whole reply rather than lazy,
|
||||
* the reasoning block and then the calls with nothing after them, and `only_tool` (when set)
|
||||
* narrows the calls to that one function. */
|
||||
/* tool_choice "required" or a named function: the grammar covers the whole reply (reasoning,
|
||||
* then calls, nothing after), and `only_tool` when set restricts calls to that function. */
|
||||
bool require_call = false;
|
||||
std::string only_tool;
|
||||
};
|
||||
@@ -200,15 +189,18 @@ struct ChatGrammar {
|
||||
std::vector<std::string> trigger_words;
|
||||
};
|
||||
|
||||
/* A tool the grammar and the reply parser both read, {"type":"function","function":{...}}; both
|
||||
* skip any other. */
|
||||
bool chat_function_tool(const nlohmann::ordered_json& tool);
|
||||
|
||||
/* RAD_OK, or RAD_E_INVAL with *why when a tool or schema cannot be expressed. */
|
||||
int chat_format_grammar(const ChatFormat& f, const ChatGrammarRequest& req, ChatGrammar* out,
|
||||
std::string* why);
|
||||
|
||||
/* The markers the decoder must render as text for the parser to see them: a format built from
|
||||
* control tokens reaches the parser with its structure gone otherwise, because the decoder
|
||||
* suppresses control tokens. Every non-empty delimiter, whitespace-trimmed, deduplicated, in the
|
||||
* order the vendored analyser lists them -- a marker that is not a single token is harmless, the
|
||||
* decoder only compares it with the spellings of control tokens. */
|
||||
/* The markers the decoder must render as text so the parser sees them; the decoder otherwise
|
||||
* suppresses control tokens, and a format built from them would lose its structure. Every
|
||||
* non-empty delimiter, whitespace-trimmed and deduplicated, in the vendored analyser's order. A
|
||||
* multi-token marker is fine: the decoder only compares markers with control-token spellings. */
|
||||
std::vector<std::string> chat_format_markers(const ChatFormat& f);
|
||||
|
||||
} /* namespace rad */
|
||||
+200
-214
@@ -1,14 +1,15 @@
|
||||
#include "text/chatparse.h"
|
||||
#include "text/chatfmt.h"
|
||||
|
||||
/* Bind time only: the schema resolution that decides which arguments are strings. The same
|
||||
* function the grammar generator uses, so the parser and the grammar never disagree about a
|
||||
* type. Nothing from vendor/ runs while a reply is being read. */
|
||||
/* Bind time only: the schema resolution that decides which arguments are strings. The grammar
|
||||
* generator uses the same function, so parser and grammar agree on every type. Nothing from
|
||||
* vendor/ runs while a reply is read. */
|
||||
#include "llama/common/json-schema-to-grammar.h"
|
||||
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
#include <cctype>
|
||||
#include <cstring>
|
||||
#include <deque>
|
||||
#include <set>
|
||||
@@ -29,15 +30,14 @@ inline bool is_blank(unsigned char c) { return c == ' ' || c == '\n' || c == '\r
|
||||
|
||||
/* ================================================================== delimiter automaton
|
||||
*
|
||||
* A deterministic Aho-Corasick automaton over a handful of delimiters. The state is the longest
|
||||
* suffix of the text scanned so far that is a prefix of some delimiter, so its depth is exactly
|
||||
* how many trailing bytes might still become one -- the bytes a streaming scan must hold -- and a
|
||||
* state whose string IS a delimiter is a match.
|
||||
* A deterministic Aho-Corasick automaton over a few delimiters. The state is the longest suffix
|
||||
* of the scanned text that is a prefix of some delimiter, so its depth is the number of trailing
|
||||
* bytes a streaming scan must hold, and a state whose string is a delimiter is a match.
|
||||
*
|
||||
* That last step is exact only because chat_format_check refuses delimiter sets in which one
|
||||
* delimiter occurs inside another at a non-zero offset. Then a match ends at the first byte where
|
||||
* any delimiter completes, and no earlier-starting match can still be in progress: the automaton
|
||||
* reports matches in the order of their START, which is the order the grammar reads them in. */
|
||||
* Reporting matches this way is exact only because chat_format_check refuses delimiter sets in
|
||||
* which one delimiter occurs inside another at a non-zero offset. A match then ends at the first
|
||||
* byte where any delimiter completes with no earlier-starting match in progress, so matches come
|
||||
* out in start order, the order the grammar reads them. */
|
||||
class Dfa {
|
||||
public:
|
||||
void build(const std::vector<std::string>& pats) {
|
||||
@@ -132,19 +132,18 @@ private:
|
||||
* format's grammar accepts as a JSON-typed argument, quirks included, because the answer decides
|
||||
* whether the argument is typed or text:
|
||||
*
|
||||
* * no whitespace before the value, any whitespace after it and inside it;
|
||||
* * a number may not be followed by a character that could have continued it -- `01`, `1.`,
|
||||
* `1-` are not numbers -- while `true` and `null` may be followed by anything;
|
||||
* * a raw control character fails a string, as the schema's string rule refuses one and JSON
|
||||
* has none: a client's JSON parser rejects a raw newline in a string. Any escape but the
|
||||
* JSON ones fails it too.
|
||||
* * no whitespace before the value, any whitespace after and inside it;
|
||||
* * a number may not be followed by a character that could have continued it (`01`, `1.`, `1-`
|
||||
* are not numbers), while `true` and `null` may be followed by anything;
|
||||
* * a raw control character or a non-JSON escape fails a string, as the schema's string rule
|
||||
* does (a client's JSON parser rejects a raw newline in a string).
|
||||
*
|
||||
* A value accepted here is still checked whole by a JSON parser before it is written as JSON
|
||||
* (json_value_done): the grammar admits a few spellings a client cannot read.
|
||||
* An accepted value is still checked whole by a JSON parser before it is written as JSON
|
||||
* (json_value_done), since the grammar admits a few spellings a client cannot read.
|
||||
*
|
||||
* push() answers More while the bytes are still a JSON value or its trailing whitespace, Fail at
|
||||
* the first byte that cannot be, and Done at the first byte after a complete value -- which is
|
||||
* NOT consumed. */
|
||||
* push() returns More while the bytes are still a JSON value or its trailing whitespace, Fail at
|
||||
* the first byte that cannot be, and Done at the first byte after a complete value, which is not
|
||||
* consumed. */
|
||||
class JsonScan {
|
||||
public:
|
||||
enum Res : uint8_t { More, Fail, Done };
|
||||
@@ -305,8 +304,8 @@ private:
|
||||
/* ================================================================== JSON text helpers */
|
||||
|
||||
/* A string's JSON encoding without its quotes, byte for byte what nlohmann::json::dump writes:
|
||||
* the two-character escapes where JSON has one, \u00XX in lower-case hex for the other control
|
||||
* characters, and everything else -- DEL and UTF-8 included -- verbatim. */
|
||||
* two-character escapes where JSON has one, \u00XX in lower-case hex for other control
|
||||
* characters, and everything else (DEL and UTF-8 included) verbatim. */
|
||||
void json_escape_into(std::string& out, const char* p, size_t n) {
|
||||
static const char hex[] = "0123456789abcdef";
|
||||
const char* run = p;
|
||||
@@ -340,8 +339,8 @@ std::string json_quote(std::string_view s) {
|
||||
return out;
|
||||
}
|
||||
|
||||
/* How many trailing bytes of `s` from `from` on form an unfinished UTF-8 sequence. A delta
|
||||
* becomes a JSON string on the wire, and half a code point there is a malformed payload. */
|
||||
/* How many trailing bytes of `s` (from `from` on) form an unfinished UTF-8 sequence. A delta
|
||||
* becomes a JSON string on the wire, where half a code point is malformed. */
|
||||
size_t utf8_tail(const std::string& s, size_t from) {
|
||||
const size_t n = s.size();
|
||||
for (size_t back = 1; back <= 3 && back <= n - from; ++back) {
|
||||
@@ -356,8 +355,8 @@ size_t utf8_tail(const std::string& s, size_t from) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* The value transforms the format's grammar applies, on a whole value. Used for values short
|
||||
* enough to be held entire and for the held ends of long ones. */
|
||||
/* The grammar's value transforms, on a whole value: used for values short enough to hold entire
|
||||
* and for the held ends of long ones. */
|
||||
std::string_view strip_leading_newline(std::string_view v) {
|
||||
if (!v.empty() && v.front() == '\n') v.remove_prefix(1);
|
||||
else if (v.size() >= 2 && v[0] == '\r' && v[1] == '\n') v.remove_prefix(2);
|
||||
@@ -378,16 +377,10 @@ constexpr std::string_view kCdClose = "]]>";
|
||||
constexpr std::string_view kFenceOpen = "```json";
|
||||
constexpr std::string_view kFenceClose = "```";
|
||||
|
||||
/* A CDATA section is punctuation, not content, and its two ends are stripped independently. A
|
||||
* value still arriving holds back what could yet become the opener, and a trailing `]` or `]]`
|
||||
* that could be the start of the closer. */
|
||||
void unwrap_cdata(std::string_view& v, bool partial) {
|
||||
if (v.size() < kCdOpen.size()) {
|
||||
if (partial && !v.empty() && kCdOpen.compare(0, v.size(), v) == 0) v = std::string_view();
|
||||
return;
|
||||
}
|
||||
if (v.compare(0, kCdOpen.size(), kCdOpen) != 0) return;
|
||||
v.remove_prefix(kCdOpen.size());
|
||||
/* A CDATA section is punctuation, not content; its two ends are stripped independently. A value
|
||||
* still arriving holds back what could become the opener, and a trailing `]` or `]]` that could
|
||||
* start the closer. */
|
||||
void strip_cdata_close(std::string_view& v, bool partial) {
|
||||
if (v.size() >= kCdClose.size() &&
|
||||
v.compare(v.size() - kCdClose.size(), kCdClose.size(), kCdClose) == 0) {
|
||||
v.remove_suffix(kCdClose.size());
|
||||
@@ -399,8 +392,18 @@ void unwrap_cdata(std::string_view& v, bool partial) {
|
||||
v.remove_suffix(hold);
|
||||
}
|
||||
|
||||
/* The name of an argument, as the grammar reads it: one leading whitespace character and every
|
||||
* trailing one are not part of it. */
|
||||
void unwrap_cdata(std::string_view& v, bool partial) {
|
||||
if (v.size() < kCdOpen.size()) {
|
||||
if (partial && !v.empty() && kCdOpen.compare(0, v.size(), v) == 0) v = std::string_view();
|
||||
return;
|
||||
}
|
||||
if (v.compare(0, kCdOpen.size(), kCdOpen) != 0) return;
|
||||
v.remove_prefix(kCdOpen.size());
|
||||
strip_cdata_close(v, partial);
|
||||
}
|
||||
|
||||
/* An argument name as the grammar reads it: without one leading whitespace character and all
|
||||
* trailing ones. */
|
||||
std::string_view trim_arg_name(std::string_view v) {
|
||||
if (!v.empty() && is_ws((unsigned char)v.front())) v.remove_prefix(1);
|
||||
while (!v.empty() && is_ws((unsigned char)v.back())) v.remove_suffix(1);
|
||||
@@ -414,28 +417,28 @@ std::string_view trim_trailing_ws(std::string_view v) {
|
||||
|
||||
/* ================================================================== an argument value
|
||||
*
|
||||
* The bytes of one value as the delimiters bound it, turned into its JSON encoding in the
|
||||
* arguments object. Two encodings: a STRING (quoted, escaped) and RAW JSON text, which is either
|
||||
* a value that parsed as JSON or a non-string argument that did not.
|
||||
* One value's bytes, as the delimiters bound them, turned into its JSON encoding in the arguments
|
||||
* object: a string (quoted, escaped), or raw JSON text (a value that parsed as JSON, or a
|
||||
* non-string argument that did not).
|
||||
*
|
||||
* A NON-STRING ARGUMENT THAT DID NOT PARSE IS MADE JSON, never passed through: the arguments
|
||||
* object is the one thing a client parses, and a single bare token in it makes the whole call
|
||||
* unreadable -- the server then cannot report it as a call at all. The grammar admits text for a
|
||||
* typed argument, and what these models write there is Python: `True`, `False`, `None`, and
|
||||
* single-quoted containers. A scalar is held while it could still be a Python literal -- `True`
|
||||
* as true, `False`, `None` as null -- or a JSON number or literal, up to kScalar bytes, and is
|
||||
* then written as that; anything else, or anything longer, streams as a JSON string of its text.
|
||||
* An empty one is null. A CONTAINER -- its first byte after at most a few blanks is `[` or `{` --
|
||||
* is held whole, because whether it is JSON once its quotes are normalised to double ones and its
|
||||
* Python literals to JSON's is known only at its end: a trailing comma, a bare word, an escape
|
||||
* JSON has not or a missing bracket each leave it no JSON, and then it is a JSON string of its
|
||||
* text. A value the reply was cut off inside is written as it arrived: it has no end to read it
|
||||
* to, and the call it is in is not complete. A value the JSON reader ACCEPTED (json_value_done)
|
||||
* is written as it is.
|
||||
* A non-string argument that did not parse is converted to JSON, never passed through: one bare
|
||||
* token makes the client's arguments object unparseable, and the call cannot be reported at all.
|
||||
* The grammar admits text for a typed argument, and models write Python there: `True`, `False`,
|
||||
* `None` and single-quoted containers.
|
||||
*
|
||||
* The transforms touch only the ends of a value -- one newline at each end, the CDATA opener and
|
||||
* closer -- so the middle streams straight through and only a short head and tail are held: the
|
||||
* first kHead bytes until the head is decided, and the last kTail after that. */
|
||||
* * Scalar: held while it could still be a Python literal (`True` as true, `False`, `None` as
|
||||
* null) or a JSON number or literal, up to kScalar bytes, then written as that. Anything
|
||||
* else, or longer, streams as a JSON string of its text. An empty value is null.
|
||||
* * Container (first byte after at most four blanks is `[` or `{`): held whole, because only at
|
||||
* its end is it known whether it is JSON once its quotes and Python literals are normalised.
|
||||
* If it is not, it becomes a JSON string of its text.
|
||||
* * A value the reply was cut off inside is written as it arrived, since there is no end to
|
||||
* read and its call is incomplete. A value the JSON scanner accepted (json_value_done) is
|
||||
* written as is.
|
||||
*
|
||||
* The transforms touch only the ends (one newline at each end, the CDATA opener and closer), so
|
||||
* the middle streams through and only the first kHead bytes (until the head is decided) and the
|
||||
* last kTail are held. */
|
||||
class ValueOut {
|
||||
public:
|
||||
enum Mode : uint8_t { String, Raw };
|
||||
@@ -484,18 +487,7 @@ public:
|
||||
if (cdata_) unwrap_cdata(v, partial);
|
||||
} else {
|
||||
if (trail_) v = strip_trailing_newline(v);
|
||||
if (opened_) {
|
||||
if (v.size() >= kCdClose.size() &&
|
||||
v.compare(v.size() - kCdClose.size(), kCdClose.size(), kCdClose) == 0) {
|
||||
v.remove_suffix(kCdClose.size());
|
||||
} else if (partial) {
|
||||
size_t hold = 0;
|
||||
while (hold + 1 < kCdClose.size() && v.size() > hold &&
|
||||
v[v.size() - 1 - hold] == ']')
|
||||
++hold;
|
||||
v.remove_suffix(hold);
|
||||
}
|
||||
}
|
||||
if (opened_) strip_cdata_close(v, partial);
|
||||
}
|
||||
emit(v.data(), v.size(), out);
|
||||
if (mode_ == Raw && !json_) {
|
||||
@@ -660,10 +652,10 @@ private:
|
||||
|
||||
/* ================================================================== the answer text
|
||||
*
|
||||
* Content is trimmed at the end: trailing spaces and newlines, then one turn terminator. Trimming
|
||||
* the END of a stream means holding what might be the end -- the trailing whitespace, and a
|
||||
* terminator or the part of one that has arrived -- until something that is not whitespace
|
||||
* follows it. The terminator automaton tracks the longest suffix that could still become one. */
|
||||
* Content is trimmed at the end: trailing spaces and newlines, then one turn terminator. On a
|
||||
* stream that means holding the trailing whitespace and any whole or partial terminator until a
|
||||
* non-whitespace byte follows. The terminator automaton tracks the longest suffix that could
|
||||
* still become one. */
|
||||
class ContentOut {
|
||||
public:
|
||||
void init(const Dfa* terms, const std::vector<std::string>* list) { terms_ = terms; list_ = list; }
|
||||
@@ -729,43 +721,43 @@ struct ReplyFormat::Impl {
|
||||
/* Each tag split into its core and the whitespace around it that is optional to match. */
|
||||
std::string open_core, open_trail, close_core, close_trail, ns_core, ns_trail, end_core,
|
||||
end_trail, co_core, co_trail;
|
||||
/* What begins a call in content. The first is the format's own opener: call_open's core, or
|
||||
/* What begins a call in content. First the format's own opener: call_open's core, or
|
||||
* name_prefix when calls are not wrapped. A wrapped format also takes name_prefix alone,
|
||||
* second: a model writes the call without its wrapper often enough that its calls must not
|
||||
* be lost to it, and a wrapper written without its trailing whitespace is read too. */
|
||||
* second, since models often write a call without its wrapper; a wrapper written without
|
||||
* its trailing whitespace is read too. */
|
||||
std::vector<std::string> openers;
|
||||
std::string name_end; /* what ends an argument name */
|
||||
/* The same two, whitespace-trimmed. A loose call is one the grammar never opened, so the
|
||||
* model wrote it unconstrained, and its argument tags are read with the whitespace around
|
||||
* them optional -- as its name and its close are. */
|
||||
/* The same two, whitespace-trimmed. A loose call is one the grammar never opened, so it was
|
||||
* written unconstrained; its argument tags, like its name and close, are read with their
|
||||
* surrounding whitespace optional. */
|
||||
std::string name_end_core, value_core;
|
||||
/* call_close's core, when it can be told apart from what else may follow inside a call: a
|
||||
* wrapped call whose own close is missing is ended by its wrapper's. */
|
||||
/* call_close's core, when distinct from what else may follow inside a call, so a wrapped
|
||||
* call missing its own close is ended by its wrapper's. */
|
||||
std::string cc_core;
|
||||
Dfa think, think_breaks, text, arg_name, value, junk, arg_name_loose, value_loose;
|
||||
size_t longest = 0; /* the longest delimiter */
|
||||
|
||||
/* THE OBJECT FAMILY. `object`: a call's arguments are one object; `ns_object`: the object's
|
||||
* own `{` is what ends the name (name_suffix empty), and ns_core is "{". */
|
||||
/* Object family. `object`: a call's arguments are one object. `ns_object`: the object's own
|
||||
* `{` ends the name (name_suffix empty), and ns_core is "{". */
|
||||
bool object = false, ns_object = false;
|
||||
/* Where a key or a value may begin, besides the object's punctuation: the dialect string's
|
||||
* opener, and the call's close and end -- a reply that leaves its object unclosed writes them
|
||||
* there. Read anchored, by their first bytes (chat_format_check keeps them apart). */
|
||||
/* Where a key or value may begin, besides the object's punctuation: the dialect string's
|
||||
* opener, and the call's close and end (written there by a reply that leaves its object
|
||||
* unclosed). Matched anchored, by first byte; chat_format_check keeps them distinct. */
|
||||
enum : uint8_t { LitString, LitClose, LitEnd };
|
||||
std::vector<std::string> obj_lits;
|
||||
std::vector<uint8_t> obj_lit_kind;
|
||||
/* A dialect string runs to its close. A bare value ends at `,` `}` `]` and a bare key at `:`
|
||||
* `,` `}` -- patterns 0..2 -- or at the call's close or end, which follow at the indices
|
||||
* below (-1: none). */
|
||||
* `,` `}` (patterns 0..2), or at the call's close or end, whose pattern indices are below
|
||||
* (-1: none). */
|
||||
Dfa obj_str, obj_bare, obj_key;
|
||||
/* A value the model opened with a plain `"` -- or `'` (obj_sqstr) -- in a dialect that has
|
||||
* strings of its own: read as that dialect's strings are, verbatim, to a quote the object's
|
||||
* syntax goes on after. Patterns: the quote, the escaped quote, the dialect's string close,
|
||||
* the call's close (if any). */
|
||||
/* A value opened with a plain `"` (or `'`, obj_sqstr) in a dialect with strings of its own:
|
||||
* read verbatim, like the dialect's strings, up to a quote after which the object's syntax
|
||||
* continues. Patterns: the quote, the escaped quote, the dialect's string close, the call's
|
||||
* close (if any). */
|
||||
Dfa obj_qstr, obj_sqstr;
|
||||
int bare_cc = -1, bare_ce = -1, key_cc = -1, key_ce = -1;
|
||||
|
||||
/* REASONING ANYWHERE: content is scanned for a later block's opener and a stray close too,
|
||||
/* reasoning_anywhere: content is also scanned for a later block's opener and a stray close,
|
||||
* after the call openers (text_think) or alone when the request has no calls (think_only). */
|
||||
Dfa text_think, think_only;
|
||||
};
|
||||
@@ -931,9 +923,9 @@ ReasoningMarkers ReplyParser::reasoning() const {
|
||||
if (!F.f.has_reasoning()) return m;
|
||||
m.open = F.open_core;
|
||||
m.close = F.close_core;
|
||||
/* `tail` starts at the opener when the prompt holds one, and a prompt that also closed the
|
||||
* block -- thinking turned off -- leaves the reply after it. With no opener at all the stream
|
||||
* starts in the block (after_lead). */
|
||||
/* `tail` starts at the opener when the prompt holds one; a prompt that also closed the block
|
||||
* (thinking off) leaves the reply after it. With no opener the stream starts in the block
|
||||
* (after_lead). */
|
||||
const std::string& t = impl_->tail;
|
||||
m.starts_open = F.open_core.empty() ||
|
||||
(!t.empty() && t.find(F.close_core, F.open_core.size()) == std::string::npos);
|
||||
@@ -945,9 +937,7 @@ ReasoningMarkers ReplyParser::reasoning() const {
|
||||
static int bind_tools(const ReplyFormat::Impl& F, const ojson& tools, ReplyParser::Impl* P,
|
||||
std::string* why) {
|
||||
for (const auto& tool : tools) {
|
||||
if (!tool.is_object() || !tool.contains("type") || tool.at("type") != "function" ||
|
||||
!tool.contains("function"))
|
||||
continue;
|
||||
if (!chat_function_tool(tool)) continue;
|
||||
try {
|
||||
const auto& func = tool.at("function");
|
||||
Tool t;
|
||||
@@ -961,8 +951,8 @@ static int bind_tools(const ReplyFormat::Impl& F, const ojson& tools, ReplyParse
|
||||
info.resolve_refs(params);
|
||||
std::vector<std::string> optional;
|
||||
for (const auto& [pname, pschema] : properties.items()) {
|
||||
/* An optional argument no value satisfies has no arm in the grammar, which reads
|
||||
* it by the undeclared arm, as text (chatfmt.cpp); so does the parser. */
|
||||
/* An optional argument no value satisfies has no grammar arm and is read by the
|
||||
* undeclared arm as text (chatfmt.cpp); the parser does the same. */
|
||||
if (!required.count(pname) && info.unsatisfiable(pschema)) continue;
|
||||
Param p;
|
||||
p.typed = F.f.other_value == ChatValue::Json && !info.resolves_to_string(pschema);
|
||||
@@ -973,9 +963,9 @@ static int bind_tools(const ReplyFormat::Impl& F, const ojson& tools, ReplyParse
|
||||
} else {
|
||||
optional.push_back(pname);
|
||||
}
|
||||
/* A name the argument's own delimiter could end early would be read as a
|
||||
* different name. An object's keys are delimited by its own punctuation, and
|
||||
* one that holds it is written as a string. */
|
||||
/* A name its own delimiter could end early would be read as a different name.
|
||||
* Object keys are delimited by the object's punctuation instead, and a key
|
||||
* containing it is written as a string. */
|
||||
const std::string probe = pname + F.name_end;
|
||||
if (!F.object && probe.find(F.name_end) != pname.size()) {
|
||||
*why = "parameter '" + pname + "' of tool '" + t.name + "' contains '" +
|
||||
@@ -1121,8 +1111,8 @@ struct ReplyStream::Impl {
|
||||
}
|
||||
}
|
||||
|
||||
/* What content is scanned with: the call openers when calls are on, then -- reasoning
|
||||
* anywhere -- a later block's opener and a stray close. Null: content is every byte. */
|
||||
/* What content is scanned with: the call openers when calls are on, then (reasoning_anywhere)
|
||||
* a later block's opener and a stray close. Null when every byte is content. */
|
||||
const Dfa* text_dfa = nullptr;
|
||||
size_t n_open = 0;
|
||||
|
||||
@@ -1144,12 +1134,12 @@ struct ReplyStream::Impl {
|
||||
size_t lpos = 0, trail = 0;
|
||||
/* a call being opened */
|
||||
St origin = St::Text;
|
||||
/* LOOSE: opened by what the format's grammar does not open a call with -- name_prefix alone,
|
||||
* or call_open without its trailing whitespace. Such an opener is also ordinary text often
|
||||
* enough ("the `<function=f>` syntax") that it becomes a call only once what follows the
|
||||
* name tag is an argument or the call's close; until then it is held, and if it is not a
|
||||
* call it is content, as the grammar says, and the reply is still within it. WRAPPED: the
|
||||
* call was opened with call_open, so its close is followed by call_close. */
|
||||
/* `loose`: opened by something the grammar does not open a call with (name_prefix alone, or
|
||||
* call_open without its trailing whitespace). Such an opener is also ordinary text often
|
||||
* enough ("the `<function=f>` syntax") that it becomes a call only once an argument or the
|
||||
* call's close follows the name tag. Until then it is held; if it is not a call it is
|
||||
* content, as the grammar says, and the reply stays strict. `wrapped`: opened with
|
||||
* call_open, so its close is followed by call_close. */
|
||||
bool loose = false, wrapped = false;
|
||||
size_t tag_end = 0; /* where a loose call's name tag ends in `att` */
|
||||
bool name_lt = false; /* a loose call's argument name holds a '<' */
|
||||
@@ -1168,23 +1158,23 @@ struct ReplyStream::Impl {
|
||||
size_t vs_pos = 0;
|
||||
bool fenced = false;
|
||||
|
||||
/* THE ARGUMENT OBJECT being read: its open brackets, whether a key (rather than a value) is
|
||||
* being read, a separator read but not yet written -- it is written only once the next
|
||||
* member shows the object goes on, so a trailing one never reaches the JSON -- whether the
|
||||
* container was just opened, and whether a key's `:` went out with no value yet. */
|
||||
/* The argument object being read: its open brackets; whether a key (not a value) is being
|
||||
* read; a separator read but not yet written (written only once the next member shows the
|
||||
* object continues, so a trailing one never reaches the JSON); whether the container was
|
||||
* just opened; and whether a key's `:` went out with no value yet. */
|
||||
std::vector<char> ostack;
|
||||
bool okey = false, ocomma = false, ofirst = false, vpending = false;
|
||||
/* A bare value's first bytes, to tell at its end whether it was a JSON number or literal --
|
||||
* which the grammar admits -- or a word read as a string, which it does not. */
|
||||
/* A bare value's first bytes, to tell at its end whether it was a JSON number or literal
|
||||
* (which the grammar admits) or a word read as a string (which it does not). */
|
||||
std::string bare_txt;
|
||||
/* A JSON string's escape being read -- the backslash, and a "u" escape's four hex digits,
|
||||
* in vheld -- and a high surrogate's escape, held until the low one shows it is a pair. */
|
||||
/* A high surrogate's escape, held until the low one shows it is a pair. The escape being
|
||||
* read (the backslash and a "u" escape's four hex digits) is in vheld. */
|
||||
std::string jhi;
|
||||
/* INSIDE A STRING: its trailing run of whitespace, closing brackets and quotes, held -- the
|
||||
* brackets are the object's own if the call's close follows (srun) -- the quotes and
|
||||
* backticks it has written (nq, nb), the bytes after a plain quote while they decide what it
|
||||
* was (qtail), and how a plain-quoted value writes its quotes: 0 not yet seen, 1 as \" (one
|
||||
* is unescaped), 2 as they are. */
|
||||
/* Inside a string: `srun` holds its trailing run of whitespace, closing brackets and quotes
|
||||
* (the brackets are the object's own if the call's close follows); `nq`, `nb`, `ns` count the
|
||||
* double quotes, backticks and single quotes it has written; `qtail` holds the bytes after a
|
||||
* plain quote while they decide what it was; `qmode` is how a plain-quoted value writes its
|
||||
* quotes: 0 not yet seen, 1 as \" (one is unescaped), 2 as they are. */
|
||||
std::string srun, qtail;
|
||||
size_t nq = 0, nb = 0, ns = 0;
|
||||
uint8_t qmode = 0;
|
||||
@@ -1194,9 +1184,9 @@ struct ReplyStream::Impl {
|
||||
size_t sent_r = 0, sent_c = 0, sent_a = 0;
|
||||
int cur = -1; /* the channel last published: 0 r, 1 c, 2 args */
|
||||
|
||||
/* bytes to read again, ahead of the rest. Bytes read again are always the last ones read,
|
||||
* so each segment knows where its first byte is in the stream: the generation prompt's tail,
|
||||
* then the reply. */
|
||||
/* Bytes to read again, ahead of the rest. They are always the last bytes read, so each
|
||||
* segment knows its first byte's position in the stream (the generation prompt's tail, then
|
||||
* the reply). */
|
||||
struct Seg { const char* p; size_t n; size_t at; };
|
||||
std::vector<Seg> stack;
|
||||
const char* seg_p = nullptr; /* the segment being read */
|
||||
@@ -1206,6 +1196,7 @@ struct ReplyStream::Impl {
|
||||
size_t here(const char* p) const { return seg_at + (size_t)(p - seg_p); }
|
||||
std::deque<std::string> owned;
|
||||
std::string refeed;
|
||||
size_t reread = 0; /* every byte ever queued in refeed */
|
||||
|
||||
void lenient() { strict = false; }
|
||||
|
||||
@@ -1324,7 +1315,10 @@ struct ReplyStream::Impl {
|
||||
return p;
|
||||
}
|
||||
|
||||
void read_again(std::string_view bytes) { refeed.append(bytes); }
|
||||
void read_again(std::string_view bytes) {
|
||||
refeed.append(bytes);
|
||||
reread += bytes.size();
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------ calls */
|
||||
|
||||
@@ -1373,8 +1367,8 @@ struct ReplyStream::Impl {
|
||||
}
|
||||
}
|
||||
|
||||
/* The whitespace a loose opener may be followed by: whatever sorts at or below a space, as a
|
||||
* model's stray control characters do. */
|
||||
/* Whitespace after a loose opener: any byte at or below a space, which covers a model's stray
|
||||
* control characters. */
|
||||
static bool loose_ws(unsigned char c) { return c <= ' '; }
|
||||
|
||||
/* Not a call after all: the opener's first byte is text of the region it was found in, and
|
||||
@@ -1432,14 +1426,13 @@ struct ReplyStream::Impl {
|
||||
|
||||
/* ------------------------------------------------------------ the argument object
|
||||
*
|
||||
* The object of the object family, read as it streams and written as JSON as it is read:
|
||||
* brackets and separators as they come, a key as soon as its `:` shows it is one, a string
|
||||
* as its bytes arrive, and a bare value as the tagged family writes a typed one (ValueOut,
|
||||
* Raw): held while it could still be a literal or a number, else a string. What the dialect
|
||||
* spells otherwise -- its string delimiters, its bare keys -- is respelled; what leaves it
|
||||
* -- a missing separator, a trailing one, a bracket of the wrong kind, an object the call's
|
||||
* close cuts off -- is repaired locally and said so (strict). The arguments a closed call
|
||||
* reports are JSON whatever was written. */
|
||||
* The object family's argument object, read as it streams and written as JSON as it is read:
|
||||
* brackets and separators as they come, a key once its `:` shows it is one, a string as its
|
||||
* bytes arrive, and a bare value like a typed tagged value (ValueOut, Raw): held while it
|
||||
* could still be a literal or a number, else a string. Dialect spellings (string delimiters,
|
||||
* bare keys) are respelled. Departures from the dialect (a missing or trailing separator, a
|
||||
* mismatched bracket, an object cut off by the call's close) are repaired locally and clear
|
||||
* strict(). A closed call's arguments are always JSON. */
|
||||
|
||||
void obj_out(std::string_view s) {
|
||||
if (s.empty()) return;
|
||||
@@ -1512,8 +1505,7 @@ struct ReplyStream::Impl {
|
||||
|
||||
/* A bare value ended: one that is no JSON number or literal was read by the recovery rule. */
|
||||
void bare_done() {
|
||||
std::string_view v(bare_txt);
|
||||
while (!v.empty() && is_ws((unsigned char)v.back())) v.remove_suffix(1);
|
||||
const std::string_view v = trim_trailing_ws(bare_txt);
|
||||
const bool json = bare_txt.size() < kBareKeep && !v.empty() &&
|
||||
(v == "true" || v == "false" || v == "null" ||
|
||||
((v[0] == '-' || (v[0] >= '0' && v[0] <= '9')) &&
|
||||
@@ -1549,9 +1541,10 @@ struct ReplyStream::Impl {
|
||||
else end_core_done();
|
||||
}
|
||||
|
||||
/* A JSON string's text goes out as it is, its escapes checked: one JSON has not is the
|
||||
* backslash and the letter as text, a raw control character is escaped, and a surrogate
|
||||
* escape that is not half of a pair is U+FFFD -- a client's JSON parser refuses all three. */
|
||||
/* A JSON string's text goes out as is, with its escapes checked, since a client's JSON parser
|
||||
* refuses all three of: a non-JSON escape (written as the backslash and letter as text), a
|
||||
* raw control character (escaped), and a surrogate escape that is not half of a pair
|
||||
* (written as U+FFFD). */
|
||||
void jstr_char(const char* q, size_t n) {
|
||||
if (n == 0) return;
|
||||
if (!jhi.empty()) { lenient(); jhi.clear(); obj_out("\\ufffd"); }
|
||||
@@ -1610,9 +1603,9 @@ struct ReplyStream::Impl {
|
||||
}
|
||||
}
|
||||
|
||||
/* Where the held run stops being text: the closers after it close every open bracket of the
|
||||
* object, innermost first, as the model writes them before the call's close -- read from the
|
||||
* end, the last closes the outermost. npos: they do not. */
|
||||
/* Where the held run stops being text: the closers after that point close every open bracket
|
||||
* of the object, innermost first, as a model writes them before the call's close (read from
|
||||
* the end, the last closes the outermost). npos if they do not. */
|
||||
size_t run_cut() const {
|
||||
size_t i = srun.size(), k = 0;
|
||||
while (i > 0 && k < ostack.size()) {
|
||||
@@ -1625,15 +1618,11 @@ struct ReplyStream::Impl {
|
||||
return k == ostack.size() && k > 0 ? i : std::string::npos;
|
||||
}
|
||||
|
||||
static bool starts(std::string_view a, std::string_view b) {
|
||||
return a.size() >= b.size() && a.compare(0, b.size(), b) == 0;
|
||||
}
|
||||
|
||||
/* The call's close in a string whose held run closes the whole object: the model left the
|
||||
* string open (measured: the close delimiter at p=0.86, `}` at p=0.08), and this is where
|
||||
* the call ends -- as vLLM's and HF's Gemma 4 parsers end it, at the first `}<tool_call|>`.
|
||||
* The closers are the object's. A quote or backtick just before them that leaves the string
|
||||
* with an odd count of its kind was the string's close, written in the wrong spelling. */
|
||||
* string open (here it writes the close delimiter with p=0.86, `}` with p=0.08), and the call
|
||||
* ends here, as vLLM's and HF's Gemma 4 parsers end it at the first `}<tool_call|>`. The
|
||||
* closers are the object's. A quote or backtick just before them that leaves an odd count of
|
||||
* its kind in the string was the string's close in the wrong spelling. */
|
||||
void cut_begin() {
|
||||
const size_t cut = run_cut();
|
||||
if (cut == std::string::npos) { str_flush(); str_emit(F.cc_core.data(), F.cc_core.size()); return; }
|
||||
@@ -1647,7 +1636,7 @@ struct ReplyStream::Impl {
|
||||
}
|
||||
str_emit(srun.data(), keep);
|
||||
srun.clear();
|
||||
if (!jhi.empty()) jhi.clear();
|
||||
jhi.clear();
|
||||
obj_out(okey ? "\":null" : "\"");
|
||||
vpending = false;
|
||||
ocomma = false;
|
||||
@@ -1655,9 +1644,8 @@ struct ReplyStream::Impl {
|
||||
end_call();
|
||||
}
|
||||
|
||||
/* After a plain quote in a plain-quoted value: 0 not yet known, 1 it closed the value -- the
|
||||
* object goes on with a member, an element, its closers and the call's close -- 2 it was
|
||||
* text. */
|
||||
/* After a plain quote in a plain-quoted value: 0 not yet known; 1 it closed the value (the
|
||||
* object goes on with a member, an element, its closers or the call's close); 2 it was text. */
|
||||
int q_verdict() const {
|
||||
const std::string& q = qtail;
|
||||
if (q.size() > kLookKeep) return 2;
|
||||
@@ -1670,8 +1658,8 @@ struct ReplyStream::Impl {
|
||||
const std::string& so = F.f.object_string_open;
|
||||
std::string_view r(q.data() + i, n - i);
|
||||
if (!F.cc_core.empty()) {
|
||||
if (starts(r, F.cc_core)) return 1;
|
||||
if (starts(F.cc_core, r)) return 0;
|
||||
if (r.starts_with(F.cc_core)) return 1;
|
||||
if (std::string_view(F.cc_core).starts_with(r)) return 0;
|
||||
}
|
||||
if (top == 0 || q[i] != ',') return 2;
|
||||
++i;
|
||||
@@ -1679,8 +1667,8 @@ struct ReplyStream::Impl {
|
||||
if (i == n) return 0;
|
||||
r = std::string_view(q.data() + i, n - i);
|
||||
const unsigned char c = (unsigned char)q[i];
|
||||
if (starts(r, so)) return 1;
|
||||
if (starts(so, r)) return 0;
|
||||
if (r.starts_with(so)) return 1;
|
||||
if (std::string_view(so).starts_with(r)) return 0;
|
||||
if (ostack[top - 1] == '{') {
|
||||
if (!(std::isalpha(c) || c == '_')) return 2;
|
||||
while (i < n && (std::isalnum((unsigned char)q[i]) || q[i] == '_')) ++i;
|
||||
@@ -1713,9 +1701,8 @@ struct ReplyStream::Impl {
|
||||
}
|
||||
|
||||
/* The core of call_end has matched. The whitespace the format writes after it is part of the
|
||||
* tag, so the call closes when that has arrived too -- a reply that ends in between leaves the
|
||||
* call open, as the grammar does -- and a reply that goes straight on without it has closed
|
||||
* the call all the same. */
|
||||
* tag, so the call closes once that arrives too (a reply that ends in between leaves the call
|
||||
* open, as the grammar does); a reply that goes straight on without it still closes the call. */
|
||||
void end_core_done() {
|
||||
trail = 0;
|
||||
if (F.end_trail.empty() || loose) end_call();
|
||||
@@ -1750,9 +1737,9 @@ struct ReplyStream::Impl {
|
||||
else after_loose_call();
|
||||
}
|
||||
|
||||
/* The wrapper's close inside a wrapped call, whose own close is missing: it ends the call
|
||||
* and the wrapper both. Read leniently -- the grammar requires call_end first -- but as the
|
||||
* close it is, or the next call's arguments would be read into this one. */
|
||||
/* The wrapper's close inside a wrapped call whose own close is missing ends both the call and
|
||||
* the wrapper. Lenient, since the grammar requires call_end first, but it must be read as a
|
||||
* close or the next call's arguments would be read into this one. */
|
||||
void end_call_at_close() {
|
||||
lenient();
|
||||
end_call();
|
||||
@@ -1848,6 +1835,11 @@ struct ReplyStream::Impl {
|
||||
return F.f.value_newlines && (ne.empty() || ne.back() != '\n');
|
||||
}
|
||||
|
||||
/* `lit` continues the literal held in lhold (lpos bytes) with `c`. */
|
||||
bool extends(const std::string& lit, char c) const {
|
||||
return lpos < lit.size() && lit[lpos] == c && lit.compare(0, lpos, lhold) == 0;
|
||||
}
|
||||
|
||||
void begin_value_out(ValueOut::Mode m, bool json = false) {
|
||||
val.begin(m, cdata(), lead_newline(), F.f.value_newlines, scratch, json);
|
||||
}
|
||||
@@ -1861,20 +1853,13 @@ struct ReplyStream::Impl {
|
||||
st = St::ValText;
|
||||
}
|
||||
|
||||
/* A JSON-typed value that parsed and then met its suffix: the value is the JSON text and the
|
||||
* whitespace after it. What a client's JSON parser takes is a little narrower than what
|
||||
* JsonScan reads as the grammar's JSON -- a number past a double's range (`1e400`), an
|
||||
* unpaired UTF-16 surrogate escape, a vertical tab or form feed after the value -- and such a
|
||||
* value is read by the grammar's other arm, as text, so the arguments stay JSON. */
|
||||
/* A JSON-typed value that parsed and then met its suffix: the JSON text and the whitespace
|
||||
* after it. A client's JSON parser is slightly stricter than JsonScan's reading of the
|
||||
* grammar's JSON (a number past a double's range such as `1e400`, an unpaired UTF-16
|
||||
* surrogate escape, a vertical tab or form feed after the value). Such a value is read by the
|
||||
* grammar's other arm, as text, so the arguments stay JSON. */
|
||||
void json_value_done(std::string_view text) {
|
||||
if (!nlohmann::json::accept(text)) {
|
||||
begin_value_out(ValueOut::Raw);
|
||||
val.add(text.data(), text.size(), scratch);
|
||||
val.finish(false, scratch);
|
||||
flush_scratch();
|
||||
return;
|
||||
}
|
||||
begin_value_out(ValueOut::Raw, /*json=*/true);
|
||||
begin_value_out(ValueOut::Raw, /*json=*/nlohmann::json::accept(text));
|
||||
val.add(text.data(), text.size(), scratch);
|
||||
val.finish(false, scratch);
|
||||
flush_scratch();
|
||||
@@ -2035,8 +2020,8 @@ struct ReplyStream::Impl {
|
||||
att.push_back(c);
|
||||
const std::string& ap = F.f.arg_prefix;
|
||||
const std::string& fc = F.end_core;
|
||||
const bool a_ok = lpos < ap.size() && ap[lpos] == c && ap.compare(0, lpos, lhold) == 0;
|
||||
const bool f_ok = lpos < fc.size() && fc[lpos] == c && fc.compare(0, lpos, lhold) == 0;
|
||||
const bool a_ok = extends(ap, c);
|
||||
const bool f_ok = extends(fc, c);
|
||||
if (!a_ok && !f_ok) { fail_attempt(); return p + 1; }
|
||||
lhold.push_back(c);
|
||||
++lpos;
|
||||
@@ -2051,9 +2036,9 @@ struct ReplyStream::Impl {
|
||||
}
|
||||
|
||||
case St::OpenPeekArg: {
|
||||
/* The first argument's name, which is where prose that merely looks like a call
|
||||
* shows itself: a name that runs into a tag is no name. On one that closes, the call
|
||||
* is read -- the bytes after the name tag replayed through the call itself. */
|
||||
/* The first argument's name is where prose that only looks like a call shows itself:
|
||||
* a name that runs into a tag is no name. Once the name closes, the call is read by
|
||||
* replaying the bytes after the name tag through it. */
|
||||
const char c = *p;
|
||||
att.push_back(c);
|
||||
lhold.push_back(c);
|
||||
@@ -2084,10 +2069,9 @@ struct ReplyStream::Impl {
|
||||
const std::string& ap = F.f.arg_prefix;
|
||||
const std::string& fc = F.end_core;
|
||||
const std::string& cc = F.cc_core;
|
||||
const bool a_ok = lpos < ap.size() && ap[lpos] == c && ap.compare(0, lpos, lhold) == 0;
|
||||
const bool f_ok = lpos < fc.size() && fc[lpos] == c && fc.compare(0, lpos, lhold) == 0;
|
||||
const bool c_ok = wrapped && lpos < cc.size() && cc[lpos] == c &&
|
||||
cc.compare(0, lpos, lhold) == 0;
|
||||
const bool a_ok = extends(ap, c);
|
||||
const bool f_ok = extends(fc, c);
|
||||
const bool c_ok = wrapped && extends(cc, c);
|
||||
if (!a_ok && !f_ok && !c_ok) {
|
||||
lenient();
|
||||
st = St::Junk;
|
||||
@@ -2251,8 +2235,7 @@ struct ReplyStream::Impl {
|
||||
p = scan(F.obj_key, p, e, &hit, [this](const char* q, size_t n) { name.append(q, n); });
|
||||
if (hit < 0) return p;
|
||||
if (hit <= 2) {
|
||||
std::string_view k(name);
|
||||
while (!k.empty() && is_ws((unsigned char)k.back())) k.remove_suffix(1);
|
||||
const std::string_view k = trim_trailing_ws(name);
|
||||
if (k.empty()) lenient();
|
||||
obj_sep();
|
||||
std::string out = json_quote(k);
|
||||
@@ -2321,9 +2304,9 @@ struct ReplyStream::Impl {
|
||||
return p + 1;
|
||||
}
|
||||
if ((c == '"' || c == '\'') && !F.f.object_string_open.empty()) {
|
||||
/* Measured on Gemma 4: such a quote -- `"`, or `'` as Python and JavaScript
|
||||
* write strings -- is followed by the text verbatim, or with only its quotes
|
||||
* escaped, never JSON's other escapes. */
|
||||
/* Gemma 4 follows such a quote (`"`, or `'` as Python and JavaScript write
|
||||
* strings) with the text verbatim, or with only its quotes escaped, never with
|
||||
* JSON's other escapes. */
|
||||
obj_sep();
|
||||
vpending = false;
|
||||
lenient();
|
||||
@@ -2581,12 +2564,11 @@ struct ReplyStream::Impl {
|
||||
st = St::ArgName;
|
||||
}
|
||||
|
||||
/* The reply ended inside an argument name. A name is only a name once it is closed -- except
|
||||
* that where the format writes nothing between a name and its value's own prefix
|
||||
* (arg_name_suffix empty), the grammar's opening tag for a DECLARED argument is complete as
|
||||
* soon as the declared name is: the reply `<param name="path` already carries the key. The
|
||||
* first declared name in the grammar's order that the text spells, followed by at most part
|
||||
* of the value prefix, is the key. */
|
||||
/* The reply ended inside an argument name. A name counts only once closed, except where the
|
||||
* format writes nothing between a name and its value prefix (arg_name_suffix empty): there
|
||||
* the grammar's opening tag for a declared argument is complete once the declared name is,
|
||||
* so `<param name="path` already carries the key. The key is the first declared name, in
|
||||
* grammar order, that the text spells followed by at most part of the value prefix. */
|
||||
void finish_arg_name() {
|
||||
const Tool* t = cur_tool();
|
||||
if (!t || !F.f.arg_name_suffix.empty()) return;
|
||||
@@ -2668,7 +2650,7 @@ struct ReplyStream::Impl {
|
||||
}
|
||||
|
||||
/* The reply ended inside a loose opener, so it was never a call: its bytes are content, read
|
||||
* again from its second byte -- which may hold another opener, and so on. */
|
||||
* again from the second byte (which may hold another opener, and so on). */
|
||||
bool in_loose_attempt() const {
|
||||
switch (st) {
|
||||
case St::OpenWs: case St::OpenPrefix: case St::OpenName: case St::OpenPeek:
|
||||
@@ -2680,19 +2662,21 @@ struct ReplyStream::Impl {
|
||||
}
|
||||
|
||||
void finish_all() {
|
||||
/* The reply ended while a close was being decided: it was one. */
|
||||
while (st == St::ObjQLook) {
|
||||
q_done(true);
|
||||
/* Reads the bytes a decision queued to be read again. */
|
||||
auto rerun = [this] {
|
||||
std::string again = std::move(refeed);
|
||||
refeed.clear();
|
||||
run(again, fed >= again.size() ? fed - again.size() : 0);
|
||||
};
|
||||
/* The reply ended while a close was being decided: it was one. */
|
||||
while (st == St::ObjQLook) {
|
||||
q_done(true);
|
||||
rerun();
|
||||
}
|
||||
if (st == St::ObjStr || st == St::ObjQStr) str_flush();
|
||||
while (in_loose_attempt()) {
|
||||
fail_attempt();
|
||||
std::string again = std::move(refeed);
|
||||
refeed.clear();
|
||||
run(again, fed >= again.size() ? fed - again.size() : 0);
|
||||
rerun();
|
||||
}
|
||||
switch (st) {
|
||||
case St::OpenWs: case St::OpenPrefix: case St::OpenName: case St::OpenTail:
|
||||
@@ -2787,6 +2771,8 @@ std::string ReplyStream::content_with_open_call(std::string_view reply) const {
|
||||
|
||||
bool ReplyStream::strict() const { return impl_->strict; }
|
||||
|
||||
size_t ReplyStream::reread() const { return impl_->reread; }
|
||||
|
||||
ReplyHeld ReplyStream::held() const {
|
||||
const Impl& m = *impl_;
|
||||
ReplyHeld h;
|
||||
@@ -2795,9 +2781,9 @@ ReplyHeld ReplyStream::held() const {
|
||||
const size_t lhold = m.st == St::OpenPeekArg ? 0 : m.lhold.size();
|
||||
h.delimiter = m.hold.size() + lhold + m.val.held() + m.content.held_other() +
|
||||
(m.msg.reasoning.size() - m.sent_r) + (m.msg.content.size() - m.sent_c) +
|
||||
(m.msg.calls.empty() ? 0 : m.msg.calls.back().arguments.size() - m.sent_a);
|
||||
(m.msg.calls.empty() ? 0 : m.msg.calls.back().arguments.size() - m.sent_a) +
|
||||
m.srun.size() + m.qtail.size();
|
||||
h.space = m.content.held_space() + m.think_pend.size();
|
||||
h.delimiter += m.srun.size() + m.qtail.size();
|
||||
h.structure = m.att.size() + m.name.size() + m.vheld.size() + m.val.held_container() +
|
||||
m.jhi.size();
|
||||
return h;
|
||||
|
||||
+63
-63
@@ -1,55 +1,52 @@
|
||||
/* chatparse.h -- reading a model's reply back as it streams: reasoning, content, tool calls.
|
||||
/* chatparse.h -- reading a model's reply as it streams: reasoning, content, tool calls.
|
||||
*
|
||||
* ONE PASS, ONE PARSER. A reply is fed as it is generated, in pieces of any size, and every byte
|
||||
* is examined a bounded number of times: the whole reply costs O(its length), whether it arrives
|
||||
* in one piece or one byte at a time. Nothing is re-parsed, nothing is matched with a regular
|
||||
* expression, and there is no second pass that repairs what the first one missed -- the malformed
|
||||
* shapes a model actually writes are states of this machine, not fallbacks around it.
|
||||
* One pass, one parser. A reply is fed in pieces of any size as it is generated, and each byte is
|
||||
* examined a bounded number of times, so the whole reply costs O(length) however it is split.
|
||||
* Nothing is re-parsed, nothing is matched with a regular expression, and there is no repair
|
||||
* pass: the malformed shapes models actually write are states of this machine.
|
||||
*
|
||||
* It is driven by a ChatFormat (chatfmt.h) and built from three pieces:
|
||||
* Driven by a ChatFormat (chatfmt.h), it has three parts:
|
||||
*
|
||||
* * DELIMITER RECOGNITION is a deterministic Aho-Corasick automaton over the delimiters that can
|
||||
* end the current region -- "</think>" and the call opener inside reasoning, the call opener
|
||||
* in content, the value suffix inside a value. In the automaton's root state the scan skips
|
||||
* straight to the next byte that can begin a delimiter (memchr for the common one-byte case),
|
||||
* so a long run of prose or file content costs a memchr and a copy.
|
||||
* * THE TAG STRUCTURE is a transducer over those regions: call opener, name, arguments, close.
|
||||
* * A JSON-TYPED ARGUMENT is recognised by an incremental JSON scanner with an explicit stack.
|
||||
* * Delimiter recognition: a deterministic Aho-Corasick automaton over the delimiters that can
|
||||
* end the current region ("</think>" and the call opener in reasoning, the call opener in
|
||||
* content, the value suffix in a value). In the root state the scan skips to the next byte
|
||||
* that can begin a delimiter (memchr for the common one-byte case), so a long run of prose
|
||||
* costs a memchr and a copy.
|
||||
* * Tag structure: a transducer over those regions (call opener, name, arguments, close).
|
||||
* * JSON-typed arguments: an incremental JSON scanner with an explicit stack.
|
||||
*
|
||||
* WHAT IT PRODUCES is exactly what the format's grammar says the reply means, including the
|
||||
* places where the grammar is lenient on purpose: an argument the schema does not declare is
|
||||
* still an argument, a non-string argument that is not valid JSON is taken as text, a reasoning
|
||||
* block the model never closed ends where a call begins, prose before, between and after calls is
|
||||
* content. Where the reply leaves the grammar altogether -- a call to a function that is not a
|
||||
* tool, text inside a call, a missing close -- it recovers locally and says so (strict()).
|
||||
* The output is what the format's grammar says the reply means, including where the grammar is
|
||||
* deliberately lenient: an undeclared argument is still an argument, a non-string argument that
|
||||
* is not valid JSON is text, an unclosed reasoning block ends where a call begins, and prose
|
||||
* before, between and after calls is content. Where the reply leaves the grammar (a call to a
|
||||
* function that is not a tool, text inside a call, a missing close) it recovers locally and
|
||||
* clears strict().
|
||||
*
|
||||
* That includes a call written WITHOUT its wrapper. In a format whose calls are wrapped (Qwen's
|
||||
* `<tool_call>\n`) the grammar, and constrained decoding with it, begins only at the wrapper, so a
|
||||
* call the model writes as a bare `<function=NAME>`, or with the wrapper run straight into it, is
|
||||
* unconstrained -- and it is the one most likely to be lost. In content, name_prefix alone and
|
||||
* call_open without its trailing whitespace also open a call, with every tag's surrounding
|
||||
* whitespace optional inside it. Because such an opener is also ordinary text, it becomes a call
|
||||
* only once the name tag is closed and an argument or the call's close follows; until then it is
|
||||
* held (a bounded number of bytes), and if it is not a call it is content.
|
||||
* Unwrapped calls. In a wrapped format (Qwen's `<tool_call>\n`) the grammar, and so constrained
|
||||
* decoding, starts only at the wrapper, so a call written as a bare `<function=NAME>`, or with the
|
||||
* wrapper run into it, is unconstrained and the most likely to be lost. In content, name_prefix
|
||||
* alone and call_open without its trailing whitespace also open a call, with every tag's
|
||||
* surrounding whitespace optional inside it. Because such an opener is also ordinary text, it
|
||||
* becomes a call only once the name tag is closed and an argument or the call's close follows;
|
||||
* until then it is held (a bounded number of bytes), and if it is not a call it is content.
|
||||
*
|
||||
* THE STREAMING CONTRACT: what has been emitted is final. A delta is never taken back, so every
|
||||
* emitted prefix of content, reasoning or arguments is a prefix of the finished value, and the
|
||||
* concatenated deltas ARE the finished values. That forces some bytes to be held until their
|
||||
* meaning is known, and the holds are bounded:
|
||||
* Streaming contract: what has been emitted is final. A delta is never retracted, so the
|
||||
* concatenated deltas are the finished content, reasoning and arguments. Bytes whose meaning is
|
||||
* not yet known are held, within these bounds:
|
||||
*
|
||||
* * a possible delimiter prefix -- at most the longest delimiter, less one byte;
|
||||
* * an unfinished UTF-8 sequence -- at most three bytes, because a delta goes into a JSON string;
|
||||
* * whitespace whose fate depends on what follows -- the trailing whitespace of content, which
|
||||
* is trimmed if nothing follows it, and the whitespace that opens a reasoning block, which is
|
||||
* dropped if the block holds nothing else;
|
||||
* * a tag's own name while it is being read, since a name is only a name once it is closed;
|
||||
* * a JSON-typed argument value until its closing delimiter: `30` and `30 seconds` differ from
|
||||
* their first byte (a number, or the string "30 seconds"), so the value is emitted whole once
|
||||
* * a possible delimiter prefix: at most the longest delimiter less one byte;
|
||||
* * an unfinished UTF-8 sequence: at most three bytes, since a delta goes into a JSON string;
|
||||
* * whitespace that depends on what follows: content's trailing whitespace (trimmed if nothing
|
||||
* follows) and the whitespace opening a reasoning block (dropped if the block holds nothing
|
||||
* else);
|
||||
* * a tag's name while it is read, since it is a name only once closed;
|
||||
* * a JSON-typed argument value until its closing delimiter. `30` and `30 seconds` differ from
|
||||
* the first byte (a number, or the string "30 seconds"), so the value is emitted whole once
|
||||
* its type is known. A value that stops being JSON part-way is streamed as text from there,
|
||||
* except a container (`[`, `{`), which is held to its end: only there is it known whether
|
||||
* it is JSON once its Python quoting is normalised, or the JSON string of its text.
|
||||
* except a container (`[`, `{`), which is held to its end: only then is it known whether it
|
||||
* is JSON once its Python quoting is normalised, or becomes the JSON string of its text.
|
||||
*
|
||||
* Streaming emits in the reply's order; a call's arguments are streamed as they are parsed. */
|
||||
* Events are emitted in reply order; a call's arguments stream as they are parsed. */
|
||||
#pragma once
|
||||
#include "rad_internal.h"
|
||||
|
||||
@@ -83,9 +80,9 @@ struct ReplyCall {
|
||||
std::string name;
|
||||
std::string arguments; /* JSON text, as the OpenAI API carries it */
|
||||
bool closed = false;
|
||||
/* Where the call's text begins in the reply, and the content up to it: `content_at` bytes
|
||||
* of the message's content and the untrimmed whitespace held after them. What the content
|
||||
* is when the call is read as text (ReplyStream::content_with_open_call). */
|
||||
/* Where the call's text begins in the reply (`at`), and the content before it: `content_at`
|
||||
* bytes of the message's content plus the untrimmed whitespace held after them. Used to read
|
||||
* the call back as text (ReplyStream::content_with_open_call). */
|
||||
size_t at = 0;
|
||||
size_t content_at = 0;
|
||||
std::string content_held;
|
||||
@@ -119,16 +116,16 @@ struct ReplyOptions {
|
||||
/* A response_format was requested: the reply is one JSON document, optionally fenced as
|
||||
* ```json ... ```, and the document is the content. */
|
||||
bool response_format = false;
|
||||
/* The model's turn terminators. The decoder renders one only when the format needs it, and
|
||||
* one left on the end of content is not part of the answer. */
|
||||
/* The model's turn terminators. The decoder renders one only when the format needs it; one
|
||||
* left at the end of content is not part of the answer. */
|
||||
std::vector<std::string> terminators;
|
||||
};
|
||||
|
||||
class ReplyStream;
|
||||
|
||||
/* The reasoning block as one request's reply meets it: its markers with the optional whitespace
|
||||
* around them trimmed, and whether the reply starts inside it -- the generation prompt opened it,
|
||||
* or the format has no opener. Empty `close` is a format with no reasoning block. */
|
||||
/* The reasoning block as one request's reply sees it: the markers with their optional
|
||||
* surrounding whitespace trimmed, and whether the reply starts inside the block (the generation
|
||||
* prompt opened it, or the format has no opener). An empty `close` means no reasoning block. */
|
||||
struct ReasoningMarkers {
|
||||
std::string open, close;
|
||||
bool starts_open = false;
|
||||
@@ -155,19 +152,19 @@ private:
|
||||
class ReplyParser {
|
||||
public:
|
||||
~ReplyParser();
|
||||
/* RAD_OK, or RAD_E_INVAL with *why when a tool cannot be read unambiguously in this format --
|
||||
* a function or parameter name containing the delimiter that ends it -- and
|
||||
* RAD_E_UNSUPPORTED when the request sends tools and the format has no tool calls. */
|
||||
/* RAD_OK; RAD_E_INVAL with *why when a tool cannot be read unambiguously in this format (a
|
||||
* function or parameter name containing the delimiter that ends it); RAD_E_UNSUPPORTED when
|
||||
* the request sends tools and the format has no tool calls. */
|
||||
static int create(std::shared_ptr<const ReplyFormat> fmt, const ReplyOptions& opt,
|
||||
std::shared_ptr<const ReplyParser>* out, std::string* why);
|
||||
std::unique_ptr<ReplyStream> open() const;
|
||||
const ChatFormat& format() const;
|
||||
/* The most bytes ReplyHeld::delimiter can reach for this request: a delimiter or terminator
|
||||
* prefix in each place one can be pending at once, a value's undecided head, and an
|
||||
* unfinished UTF-8 sequence on each output. A constant of the format, not of the reply. */
|
||||
/* Upper bound on ReplyHeld::delimiter for this request: a delimiter or terminator prefix in
|
||||
* each place one can be pending at once, a value's undecided head, and an unfinished UTF-8
|
||||
* sequence per output. Depends on the format, not the reply. */
|
||||
size_t hold_bound() const;
|
||||
/* Read from the generation prompt exactly as a stream's first bytes are, so a reply this
|
||||
* says starts in the block is one the stream reads as reasoning from its first byte. */
|
||||
/* Read from the generation prompt the same way a stream reads its first bytes, so a reply
|
||||
* this says starts in the block is read as reasoning from its first byte. */
|
||||
ReasoningMarkers reasoning() const;
|
||||
|
||||
struct Impl;
|
||||
@@ -187,14 +184,17 @@ public:
|
||||
void finish(std::vector<ReplyEvent>* out);
|
||||
|
||||
const ReplyMessage& message() const;
|
||||
/* After finish(): the content were the last call text, when the reply ended inside that call
|
||||
* -- the content before it, then the call as `reply` (every byte fed) spells it, trimmed at
|
||||
* the end as content is. A call that never closed cannot be reported as a call, and its text
|
||||
* is what the model wrote. The message's content when the last call closed, or there is none. */
|
||||
/* After finish(): the content with the last call read as text. If the reply ended inside an
|
||||
* unclosed call, that is the content before the call followed by the call as `reply` (every
|
||||
* byte fed) spells it, end-trimmed like content, since an unclosed call cannot be reported as
|
||||
* a call. Otherwise (last call closed, or no calls) the message's content. */
|
||||
std::string content_with_open_call(std::string_view reply) const;
|
||||
/* False once the reply left the format's grammar and was read by a recovery rule. */
|
||||
bool strict() const;
|
||||
ReplyHeld held() const;
|
||||
/* Bytes queued so far to be read a second time. Each step of the parser consumes a byte or
|
||||
* queues bytes again, so it takes at most as many steps as the bytes fed plus these. */
|
||||
size_t reread() const;
|
||||
|
||||
struct Impl;
|
||||
private:
|
||||
|
||||
+73
-77
@@ -12,10 +12,9 @@
|
||||
namespace rad {
|
||||
|
||||
/* ------------------------------------------------------------------ dtype geometry */
|
||||
/* Transcribed from ggml.c `type_traits` at llama.cpp 06938ac12 by running ggml_blck_size() and
|
||||
* ggml_type_size() over the whole enum, so it is the values the producer actually used rather
|
||||
* than the values the format documentation claims. Rows 42..44 are local to that checkout and
|
||||
* are carried so a file written by it is readable; upstream stops at 41. */
|
||||
/* Produced by running ggml_blck_size() and ggml_type_size() over the whole enum at llama.cpp
|
||||
* 06938ac12, so these are the values the producer used, not the documented ones. Rows 42..44 are
|
||||
* local to that checkout and kept so files it wrote stay readable; upstream stops at 41. */
|
||||
static const GgufDtype k_dtypes[] = {
|
||||
{ 1, 4, "f32" }, /* 0 */
|
||||
{ 1, 2, "f16" }, /* 1 */
|
||||
@@ -71,9 +70,8 @@ const GgufDtype* gguf_dtype(uint32_t t) {
|
||||
}
|
||||
|
||||
uint32_t gguf_to_rad_dtype(uint32_t t) {
|
||||
/* Only the types whose bytes mean the same thing on both sides. Everything block-quantised
|
||||
* is deliberately absent: reinterpreting a q4_K block as RAD_I4 would produce a tensor that
|
||||
* loads and computes and is wrong, which is the failure mode this project exists to remove. */
|
||||
/* Block-quantised types are deliberately absent: a q4_K block reinterpreted as RAD_I4 would
|
||||
* load and compute, and be wrong. */
|
||||
switch (t) {
|
||||
case 0: return RAD_F32;
|
||||
case 1: return RAD_F16;
|
||||
@@ -87,9 +85,8 @@ uint32_t gguf_to_rad_dtype(uint32_t t) {
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ cursor */
|
||||
/* A bounds-checked forward cursor over the mmap. Every read returns false at the end of the
|
||||
* file instead of faulting, because a truncated GGUF is a thing that happens to people and
|
||||
* "SIGSEGV in the loader" is not a diagnosis. */
|
||||
/* A bounds-checked forward cursor over the mmap. Reads return false at the end of the file
|
||||
* instead of faulting, so a truncated GGUF gets an error message, not a SIGSEGV. */
|
||||
namespace {
|
||||
struct Cursor {
|
||||
const uint8_t* p = nullptr;
|
||||
@@ -128,15 +125,13 @@ size_t gguf_scalar_bytes(uint32_t t) {
|
||||
}
|
||||
}
|
||||
|
||||
/* The smallest a KV and a tensor record can be encoded in, which is what a count in the header is
|
||||
* checked against: a key or name length and a type, then one value byte, or a dimension count
|
||||
* and an offset. */
|
||||
/* Smallest encodings of a KV (key length, type, one value byte) and a tensor record (name length,
|
||||
* dimension count, type, offset). The header's counts are checked against them. */
|
||||
constexpr uint64_t kMinKvBytes = sizeof(uint64_t) + sizeof(uint32_t) + 1;
|
||||
constexpr uint64_t kMinTensorBytes = sizeof(uint64_t) + 2 * sizeof(uint32_t) + sizeof(uint64_t);
|
||||
|
||||
/* A count read from the file sizes a reservation only up to a point. Past it the table grows as
|
||||
* entries are actually read, so its memory follows the file's content rather than what the file
|
||||
* claims about it. */
|
||||
/* Caps a reservation sized by a count from the file. Past the cap the table grows as entries are
|
||||
* read, so memory follows the file's content, not its claims. */
|
||||
size_t reserve_hint(uint64_t n) { return (size_t)std::min<uint64_t>(n, 1u << 16); }
|
||||
|
||||
/* Widen one fixed-width scalar into the KV's integer or float lane. */
|
||||
@@ -202,6 +197,11 @@ int GgufFile::open(const char* path) {
|
||||
}
|
||||
base_ = static_cast<const uint8_t*>(m);
|
||||
file_bytes_ = (uint64_t)st.st_size;
|
||||
/* Every refusal from here on unmaps the file. */
|
||||
auto fail = [this] {
|
||||
close();
|
||||
return RAD_E_FORMAT;
|
||||
};
|
||||
|
||||
Cursor c{ base_, 0, file_bytes_ };
|
||||
|
||||
@@ -209,32 +209,28 @@ int GgufFile::open(const char* path) {
|
||||
uint64_t n_tensors = 0, n_kv = 0;
|
||||
if (!c.raw(magic, 4) || !c.pod(&version_) || !c.pod(&n_tensors) || !c.pod(&n_kv)) {
|
||||
RAD_ERR("gguf: %s is too short to hold a header", path_.c_str());
|
||||
close();
|
||||
return RAD_E_FORMAT;
|
||||
return fail();
|
||||
}
|
||||
if (std::memcmp(magic, "GGUF", 4) != 0) {
|
||||
RAD_ERR("gguf: %s is not a GGUF file (magic %02x%02x%02x%02x)", path_.c_str(),
|
||||
(unsigned)(uint8_t)magic[0], (unsigned)(uint8_t)magic[1],
|
||||
(unsigned)(uint8_t)magic[2], (unsigned)(uint8_t)magic[3]);
|
||||
close();
|
||||
return RAD_E_FORMAT;
|
||||
return fail();
|
||||
}
|
||||
/* v1 laid its counts out as 32-bit and nothing produces it any more; v2 and v3 differ only
|
||||
* in the sign of a tensor dimension, which we read as int64 either way. */
|
||||
/* v1 used 32-bit counts and is no longer produced. v2 and v3 differ only in the signedness
|
||||
* of a tensor dimension, which is read as int64 either way. */
|
||||
if (version_ < 2 || version_ > 3) {
|
||||
RAD_ERR("gguf: %s is version %u; this reader handles 2 and 3", path_.c_str(), version_);
|
||||
close();
|
||||
return RAD_E_FORMAT;
|
||||
return fail();
|
||||
}
|
||||
/* Both counts index heap tables, so a corrupt one has to be refused before it is trusted as
|
||||
* a loop bound. What is left of the file has to hold every entry at its smallest encoding. */
|
||||
/* Both counts bound loops that fill heap tables, so refuse them unless the rest of the file
|
||||
* can hold every entry at its smallest encoding. */
|
||||
const uint64_t rest = c.end - c.off;
|
||||
if (n_kv > rest / kMinKvBytes || n_tensors > rest / kMinTensorBytes) {
|
||||
RAD_ERR("gguf: %s declares %llu KVs and %llu tensors in %llu bytes", path_.c_str(),
|
||||
(unsigned long long)n_kv, (unsigned long long)n_tensors,
|
||||
(unsigned long long)file_bytes_);
|
||||
close();
|
||||
return RAD_E_FORMAT;
|
||||
return fail();
|
||||
}
|
||||
|
||||
kv_.reserve(reserve_hint(n_kv));
|
||||
@@ -243,39 +239,33 @@ int GgufFile::open(const char* path) {
|
||||
uint32_t t = 0;
|
||||
if (!c.str(&e.key) || !c.pod(&t)) {
|
||||
RAD_ERR("gguf: %s: truncated in KV %llu", path_.c_str(), (unsigned long long)k);
|
||||
close();
|
||||
return RAD_E_FORMAT;
|
||||
return fail();
|
||||
}
|
||||
uint64_t n = 1;
|
||||
if (t == GGUF_ARR) {
|
||||
e.is_array = true;
|
||||
if (!c.pod(&t) || !c.pod(&n)) {
|
||||
RAD_ERR("gguf: %s: truncated array header for '%s'", path_.c_str(), e.key.c_str());
|
||||
close();
|
||||
return RAD_E_FORMAT;
|
||||
return fail();
|
||||
}
|
||||
if (t == GGUF_ARR) {
|
||||
RAD_ERR("gguf: %s: '%s' is an array of arrays, which GGUF does not define",
|
||||
path_.c_str(), e.key.c_str());
|
||||
close();
|
||||
return RAD_E_FORMAT;
|
||||
return fail();
|
||||
}
|
||||
/* Every element has a smallest encoding -- its width, or a string's length prefix --
|
||||
* so a bogus count is caught here, against what is left of the file, rather than
|
||||
* after a reserve sized by it has exhausted memory. A type with no encoding at all
|
||||
* fails on its first element, so it is refused before anything is sized for it. */
|
||||
/* Each element takes at least its width (a string, its length prefix), so a bogus
|
||||
* count is refused against the remaining bytes before anything is reserved for it.
|
||||
* An undefined element type is refused here for the same reason. */
|
||||
const size_t w = t == GGUF_STR ? sizeof(uint64_t) : gguf_scalar_bytes(t);
|
||||
if (!w) {
|
||||
RAD_ERR("gguf: %s: '%s' is an array of type %u, which GGUF does not define",
|
||||
path_.c_str(), e.key.c_str(), t);
|
||||
close();
|
||||
return RAD_E_FORMAT;
|
||||
return fail();
|
||||
}
|
||||
if (n > (c.end - c.off) / w) {
|
||||
RAD_ERR("gguf: %s: '%s' claims %llu elements, past the end of the file",
|
||||
path_.c_str(), e.key.c_str(), (unsigned long long)n);
|
||||
close();
|
||||
return RAD_E_FORMAT;
|
||||
return fail();
|
||||
}
|
||||
}
|
||||
e.type = t;
|
||||
@@ -287,20 +277,25 @@ int GgufFile::open(const char* path) {
|
||||
if (!read_scalar(c, t, e)) {
|
||||
RAD_ERR("gguf: %s: truncated value %llu of '%s' (type %u)", path_.c_str(),
|
||||
(unsigned long long)j, e.key.c_str(), t);
|
||||
close();
|
||||
return RAD_E_FORMAT;
|
||||
return fail();
|
||||
}
|
||||
}
|
||||
/* Later duplicates lose. GGUF does not forbid them and a rewriter can leave one behind;
|
||||
* the first is the one every other reader takes. */
|
||||
/* The first of duplicate keys wins, as in other readers. GGUF does not forbid
|
||||
* duplicates and a rewriter can leave one behind. */
|
||||
if (!kv_index_.count(e.key)) kv_index_[e.key] = kv_.size();
|
||||
kv_.push_back(std::move(e));
|
||||
}
|
||||
|
||||
/* The alignment KV moves the data section, so it has to be read before the directory's
|
||||
* offsets mean anything. 32 is the format's default. */
|
||||
int64_t al = 0;
|
||||
if (get_i64("general.alignment", &al) && al > 0 && (al & (al - 1)) == 0) {
|
||||
/* general.alignment moves the data section, so it is read before the directory's offsets.
|
||||
* The format's default is 32. A value that is not one integer power of two is refused, as
|
||||
* ggml's reader refuses it: no writer places the data section by it, and falling back to
|
||||
* the default would read every tensor from the wrong bytes. */
|
||||
if (const GgufKV* a = find("general.alignment")) {
|
||||
const int64_t al = !a->is_array && a->type != GGUF_BOOL && a->i.size() == 1 ? a->i[0] : 0;
|
||||
if (al <= 0 || (al & (al - 1)) != 0) {
|
||||
RAD_ERR("gguf: %s: general.alignment is not a power of two", path_.c_str());
|
||||
return fail();
|
||||
}
|
||||
alignment_ = (uint64_t)al;
|
||||
}
|
||||
|
||||
@@ -309,47 +304,39 @@ int GgufFile::open(const char* path) {
|
||||
GgufTensor ti;
|
||||
if (!c.str(&ti.name) || !c.pod(&ti.n_dims)) {
|
||||
RAD_ERR("gguf: %s: truncated in tensor %llu", path_.c_str(), (unsigned long long)t);
|
||||
close();
|
||||
return RAD_E_FORMAT;
|
||||
return fail();
|
||||
}
|
||||
if (ti.n_dims > 4) {
|
||||
RAD_ERR("gguf: %s: tensor '%s' has %u dimensions; GGUF allows 4",
|
||||
path_.c_str(), ti.name.c_str(), ti.n_dims);
|
||||
close();
|
||||
return RAD_E_FORMAT;
|
||||
return fail();
|
||||
}
|
||||
for (uint32_t d = 0; d < ti.n_dims; ++d) {
|
||||
if (!c.pod(&ti.ne[d]) || ti.ne[d] < 0) {
|
||||
RAD_ERR("gguf: %s: tensor '%s' has a bad dimension %u", path_.c_str(),
|
||||
ti.name.c_str(), d);
|
||||
close();
|
||||
return RAD_E_FORMAT;
|
||||
return fail();
|
||||
}
|
||||
}
|
||||
if (!c.pod(&ti.ggml_type) || !c.pod(&ti.offset)) {
|
||||
RAD_ERR("gguf: %s: truncated type/offset for '%s'", path_.c_str(), ti.name.c_str());
|
||||
close();
|
||||
return RAD_E_FORMAT;
|
||||
return fail();
|
||||
}
|
||||
const GgufDtype* dt = gguf_dtype(ti.ggml_type);
|
||||
if (!dt) {
|
||||
RAD_ERR("gguf: %s: tensor '%s' has dtype %u, which this build does not know. "
|
||||
"Refusing rather than guessing its byte size.",
|
||||
RAD_ERR("gguf: %s: tensor '%s' has dtype %u, which this build does not know",
|
||||
path_.c_str(), ti.name.c_str(), ti.ggml_type);
|
||||
close();
|
||||
return RAD_E_FORMAT;
|
||||
return fail();
|
||||
}
|
||||
if (ti.ne[0] % dt->blck != 0) {
|
||||
RAD_ERR("gguf: %s: tensor '%s' row is %lld elements, not a multiple of the %s block "
|
||||
"of %d", path_.c_str(), ti.name.c_str(), (long long)ti.ne[0], dt->name,
|
||||
dt->blck);
|
||||
close();
|
||||
return RAD_E_FORMAT;
|
||||
return fail();
|
||||
}
|
||||
/* The product of four file-supplied dimensions, and its size in bytes, can each wrap --
|
||||
* to a small tensor that passes the bounds check below while its dimensions say it is
|
||||
* vast. Both are checked, and the count also has to fit the signed type every consumer
|
||||
* of `ne` computes it in. */
|
||||
/* The product of four file-supplied dimensions and its byte size can each wrap to a
|
||||
* small value that passes the bounds check below. Check both, and that the element
|
||||
* count fits int64, the type consumers of `ne` compute it in. */
|
||||
uint64_t nelem = 1;
|
||||
bool wraps = false;
|
||||
for (int d = 0; d < 4; ++d)
|
||||
@@ -362,10 +349,14 @@ int GgufFile::open(const char* path) {
|
||||
"does not fit in 64 bits", path_.c_str(), ti.name.c_str(),
|
||||
(long long)ti.ne[0], (long long)ti.ne[1], (long long)ti.ne[2],
|
||||
(long long)ti.ne[3]);
|
||||
close();
|
||||
return RAD_E_FORMAT;
|
||||
return fail();
|
||||
}
|
||||
if (!tensor_index_.count(ti.name)) tensor_index_[ti.name] = tensors_.size();
|
||||
/* A second entry under one name could never be looked up. */
|
||||
if (tensor_index_.count(ti.name)) {
|
||||
RAD_ERR("gguf: %s: tensor '%s' is listed twice", path_.c_str(), ti.name.c_str());
|
||||
return fail();
|
||||
}
|
||||
tensor_index_[ti.name] = tensors_.size();
|
||||
tensors_.push_back(std::move(ti));
|
||||
}
|
||||
|
||||
@@ -373,19 +364,24 @@ int GgufFile::open(const char* path) {
|
||||
if (data_off_ > file_bytes_) {
|
||||
RAD_ERR("gguf: %s: data section starts at %llu, past the end of a %llu-byte file",
|
||||
path_.c_str(), (unsigned long long)data_off_, (unsigned long long)file_bytes_);
|
||||
close();
|
||||
return RAD_E_FORMAT;
|
||||
return fail();
|
||||
}
|
||||
/* Every tensor must lie inside the file. Checking it once here is what lets tensor_data()
|
||||
* hand out a raw pointer without every caller re-deriving the bound. */
|
||||
/* Every tensor must lie inside the file, so tensor_data() can hand out raw pointers, and
|
||||
* start on the file's alignment, as ggml's reader requires, so those pointers are aligned
|
||||
* for the vector loads of whatever reads them. */
|
||||
for (const GgufTensor& ti : tensors_) {
|
||||
if (ti.offset % alignment_ != 0) {
|
||||
RAD_ERR("gguf: %s: tensor '%s' starts at +%llu, off the file's %llu-byte alignment",
|
||||
path_.c_str(), ti.name.c_str(), (unsigned long long)ti.offset,
|
||||
(unsigned long long)alignment_);
|
||||
return fail();
|
||||
}
|
||||
if (ti.offset > file_bytes_ - data_off_ ||
|
||||
ti.bytes > file_bytes_ - data_off_ - ti.offset) {
|
||||
RAD_ERR("gguf: %s: tensor '%s' (%llu bytes at +%llu) leaves the file",
|
||||
path_.c_str(), ti.name.c_str(),
|
||||
(unsigned long long)ti.bytes, (unsigned long long)ti.offset);
|
||||
close();
|
||||
return RAD_E_FORMAT;
|
||||
return fail();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+27
-37
@@ -1,18 +1,15 @@
|
||||
/* gguf.h -- a reader for the GGUF container, and nothing else.
|
||||
/* gguf.h -- a reader for the GGUF container.
|
||||
*
|
||||
* spec §12 lists `ggml/src/gguf.cpp` as a lift, but that file is a reader, a writer and a
|
||||
* ggml_context builder welded together: it fills `struct ggml_tensor`, calls `ggml_blck_size`,
|
||||
* and pulls in `ggml.h` for both. Taking it whole would mean taking ggml, which §12 says
|
||||
* explicitly we do not. So the reader is rewritten here under our own name -- the wire format is
|
||||
* a header, a KV table, a tensor directory and a padded blob, and that is a page of code -- and
|
||||
* `vendor/UPSTREAM` records the file it was read from rather than copied from.
|
||||
* A rewrite of `ggml/src/gguf.cpp` (spec §12), not a lift: that file is also a writer and a
|
||||
* ggml_context builder (it fills `struct ggml_tensor` and needs `ggml.h`), and §12 excludes ggml.
|
||||
* The format is a header, a KV table, a tensor directory and a padded data blob. `vendor/UPSTREAM`
|
||||
* records the file it was written against.
|
||||
*
|
||||
* What we keep from upstream is the one thing that is genuinely data rather than code: the block
|
||||
* geometry of every ggml dtype, without which a tensor's byte size cannot be computed. That table
|
||||
* is transcribed from `ggml_blck_size`/`ggml_type_size` and is marked as such below.
|
||||
* The only thing taken from upstream is data: the block geometry of every ggml dtype, needed to
|
||||
* compute a tensor's byte size (GgufDtype).
|
||||
*
|
||||
* The file is mmapped whole and never copied. rad-convert walks the directory, reads what it
|
||||
* wants through `tensor_data()`, and writes the .rad; nothing here interprets tensor CONTENT.
|
||||
* The file is mmapped whole and never copied. rad-convert walks the directory, reads tensors
|
||||
* through `tensor_data()` and writes the .rad; nothing here interprets tensor content.
|
||||
*/
|
||||
#pragma once
|
||||
#include "rad_internal.h"
|
||||
@@ -24,34 +21,29 @@
|
||||
|
||||
namespace rad {
|
||||
|
||||
/* GGUF's own value type numbering. These are wire values -- fixed by the format, not by us. */
|
||||
/* GGUF's value type numbering (wire values, fixed by the format). */
|
||||
enum GgufType {
|
||||
GGUF_U8 = 0, GGUF_I8 = 1, GGUF_U16 = 2, GGUF_I16 = 3, GGUF_U32 = 4, GGUF_I32 = 5,
|
||||
GGUF_F32 = 6, GGUF_BOOL = 7, GGUF_STR = 8, GGUF_ARR = 9, GGUF_U64 = 10,
|
||||
GGUF_I64 = 11, GGUF_F64 = 12
|
||||
};
|
||||
|
||||
/* One metadata entry.
|
||||
*
|
||||
* A scalar is stored as a one-element vector, so a caller reading `tokenizer.ggml.tokens` and a
|
||||
* caller reading `general.name` write the same code and neither branches on `is_array`. The cost
|
||||
* is one heap allocation per scalar KV at open, against a KV table that is a few hundred rows;
|
||||
* the benefit is that the every-caller path has no special case in it, and a special case in a
|
||||
* metadata reader is where a truncated vocab comes from. */
|
||||
/* One metadata entry. A scalar is stored as a one-element vector, so callers read scalars and
|
||||
* arrays the same way without branching on `is_array`. */
|
||||
struct GgufKV {
|
||||
std::string key;
|
||||
uint32_t type = GGUF_U8; /* for an array, the ELEMENT type; GGUF_ARR never appears here */
|
||||
uint32_t type = GGUF_U8; /* for an array, the element type; never GGUF_ARR */
|
||||
bool is_array = false;
|
||||
|
||||
/* Populated according to `type`: integers and bools widen into `i`, floats into `f`,
|
||||
* strings into `s`. The other two stay empty. */
|
||||
/* By `type`: integers and bools widen into `i`, floats into `f`, strings into `s`. The
|
||||
* other two stay empty. */
|
||||
std::vector<int64_t> i;
|
||||
std::vector<double> f;
|
||||
std::vector<std::string> s;
|
||||
};
|
||||
|
||||
/* One tensor directory row. `offset` is from the start of the data section, which is where GGUF
|
||||
* puts it; `data_off() + offset` is the file offset, and `tensor_data()` does that arithmetic. */
|
||||
/* One tensor directory row. `offset` is relative to the data section; the file offset is
|
||||
* `data_off() + offset` (see `tensor_data()`). */
|
||||
struct GgufTensor {
|
||||
std::string name;
|
||||
uint32_t ggml_type = 0;
|
||||
@@ -61,9 +53,9 @@ struct GgufTensor {
|
||||
uint64_t bytes = 0; /* computed from ne and the block geometry */
|
||||
};
|
||||
|
||||
/* Block geometry for a ggml dtype. Transcribed from ggml.c's `type_traits` at llama.cpp
|
||||
* 06938ac12 -- see vendor/UPSTREAM. `blck` of 0 marks a removed or unknown type, and a tensor
|
||||
* carrying one is refused at open rather than silently mis-sized. */
|
||||
/* Block geometry for a ggml dtype, transcribed from ggml.c's `type_traits` at llama.cpp
|
||||
* 06938ac12 (vendor/UPSTREAM). `blck` 0 marks a removed or unknown type; open() refuses a tensor
|
||||
* of that type rather than mis-size it. */
|
||||
struct GgufDtype {
|
||||
int blck; /* logical elements per stored block */
|
||||
size_t block_bytes; /* bytes per stored block */
|
||||
@@ -71,9 +63,8 @@ struct GgufDtype {
|
||||
};
|
||||
const GgufDtype* gguf_dtype(uint32_t ggml_type); /* null if out of range */
|
||||
|
||||
/* Map a ggml dtype onto RAD_* where the two agree exactly. Returns RAD_DT_INVALID for the
|
||||
* k-quants and the iq-quants: those have no RAD_* equivalent, and rad-convert has to dequantise
|
||||
* or refuse rather than reinterpret the bytes. */
|
||||
/* Map a ggml dtype onto RAD_* where the bytes agree exactly. RAD_DT_INVALID for block-quantised
|
||||
* types (k-quants, iq-quants), which rad-convert must dequantise or refuse, never reinterpret. */
|
||||
uint32_t gguf_to_rad_dtype(uint32_t ggml_type);
|
||||
|
||||
class GgufFile {
|
||||
@@ -83,8 +74,8 @@ public:
|
||||
GgufFile(const GgufFile&) = delete;
|
||||
GgufFile& operator=(const GgufFile&) = delete;
|
||||
|
||||
/* RAD_OK, or a negative RAD_E_*: RAD_E_IO if the file will not open or map,
|
||||
* RAD_E_FORMAT if the magic, version, or directory does not hold together. */
|
||||
/* RAD_OK, RAD_E_IO if the file will not open or map, or RAD_E_FORMAT if the magic, version
|
||||
* or directory is invalid. */
|
||||
int open(const char* path);
|
||||
void close();
|
||||
bool is_open() const { return base_ != nullptr; }
|
||||
@@ -103,8 +94,7 @@ public:
|
||||
const GgufTensor* tensor(std::string_view name) const;
|
||||
|
||||
/* Typed reads. Each returns false and leaves *out untouched when the key is absent or holds
|
||||
* the wrong shape of value -- absence and a type mismatch are the same thing to a caller that
|
||||
* has a default, and the ones that do not have a default check the return. */
|
||||
* the wrong kind of value; a caller with a default treats both the same. */
|
||||
bool get_i64(std::string_view key, int64_t* out) const;
|
||||
bool get_f64(std::string_view key, double* out) const;
|
||||
bool get_str(std::string_view key, std::string* out) const;
|
||||
@@ -112,8 +102,8 @@ public:
|
||||
bool get_i64s(std::string_view key, std::vector<int64_t>* out) const;
|
||||
bool get_f32s(std::string_view key, std::vector<float>* out) const;
|
||||
|
||||
/* A pointer into the mmap. Null if the tensor's extent leaves the file, which is a corrupt
|
||||
* container rather than a caller error -- open() already refused those, so this is belt. */
|
||||
/* A pointer into the mmap, or null if the tensor's extent leaves the file (a corrupt
|
||||
* container, which open() already refuses). */
|
||||
const void* tensor_data(const GgufTensor& t) const;
|
||||
|
||||
private:
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
/* token_view.h -- the sampler's VocabView over a real vocabulary (sample/vocab_view.h). */
|
||||
#pragma once
|
||||
#include "sample/vocab_view.h"
|
||||
#include "text/tokenizer.h"
|
||||
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace rad {
|
||||
|
||||
class TokenView final : public VocabView {
|
||||
public:
|
||||
/* Pieces are built once (token_piece returns a reference), saving a string per candidate per
|
||||
* grammar step on the step path.
|
||||
*
|
||||
* They come from piece(), not Vocab::text(): text() is the vocab's own encoding (for
|
||||
* byte-level BPE the GPT-2 alphabet, where a space is 'Ġ'), while piece() runs the decoder
|
||||
* chain and yields the output bytes vocab_view.h asks for. With text() every grammar would
|
||||
* forbid tokens containing spaces or newlines. Special tokens are rendered, because an empty
|
||||
* piece would satisfy any grammar position. */
|
||||
int init(std::shared_ptr<const Vocab> v) {
|
||||
v_ = std::move(v);
|
||||
RAD_TRY(tok_.init(v_));
|
||||
pieces_.resize((size_t)v_->n_tokens());
|
||||
for (int32_t i = 0; i < v_->n_tokens(); ++i)
|
||||
pieces_[(size_t)i] = tok_.piece(i, /*render_special=*/true);
|
||||
return RAD_OK;
|
||||
}
|
||||
int32_t n_tokens() const override { return v_ ? v_->n_tokens() : 0; }
|
||||
const std::string& token_piece(int32_t id) const override {
|
||||
static const std::string kEmpty;
|
||||
return (id >= 0 && (size_t)id < pieces_.size()) ? pieces_[(size_t)id] : kEmpty;
|
||||
}
|
||||
bool is_eog(int32_t id) const override { return v_ && v_->is_eog(id); }
|
||||
int tokenize(const std::string& s, std::vector<int32_t>* out) const override {
|
||||
return out ? tok_.encode(s, *out, /*add_special=*/false, /*parse_special=*/false)
|
||||
: RAD_E_INVAL;
|
||||
}
|
||||
int tokenize_special(const std::string& s, std::vector<int32_t>* out) const override {
|
||||
return out ? tok_.encode(s, *out, /*add_special=*/false, /*parse_special=*/true)
|
||||
: RAD_E_INVAL;
|
||||
}
|
||||
const Tokenizer& tok() const { return tok_; }
|
||||
|
||||
private:
|
||||
std::shared_ptr<const Vocab> v_;
|
||||
Tokenizer tok_;
|
||||
std::vector<std::string> pieces_;
|
||||
};
|
||||
|
||||
} /* namespace rad */
|
||||
+423
-381
File diff suppressed because it is too large.
Load diff
+121
-118
@@ -1,30 +1,24 @@
|
||||
/* tokenizer.h -- the tokeniser, driven by the step chain baked into the .rad.
|
||||
*
|
||||
* spec §12: "The tokenizer is the one place llama.cpp's answer is Python." Their vocab is
|
||||
* GGUF-shaped, the tokenizer.json -> vocab mapping lives in convert_hf_to_gguf.py, and at RUNTIME
|
||||
* they identify the pre-tokeniser by HASHING tokenizer.json against a hardcoded enum. An
|
||||
* unrecognised model therefore gets the default split, and the symptom of that is plausible text
|
||||
* with wrong token boundaries -- the hardest kind of wrong to notice, because nothing crashes and
|
||||
* the perplexity moves by a few percent.
|
||||
* spec §12. llama.cpp identifies a pre-tokeniser at runtime by hashing tokenizer.json against a
|
||||
* hardcoded enum, so an unrecognised model silently gets the default split: plausible text with
|
||||
* wrong token boundaries. Here the chain is declared instead. rad-convert reads tokenizer.json's
|
||||
* normalizer / pre_tokenizer / decoder sections and emits them as RadVocabStep rows, which this
|
||||
* file executes in order. A chain that cannot be expressed fails at convert time with the step
|
||||
* named.
|
||||
*
|
||||
* So the chain is DECLARED rather than recognised. rad-convert reads tokenizer.json's
|
||||
* normalizer / pre_tokenizer / decoder sections and emits them as RadVocabStep rows; this file
|
||||
* executes those rows in order. A model nobody has ever seen tokenises correctly if its
|
||||
* tokenizer.json is honest, and a model whose chain we cannot express fails at CONVERT time with
|
||||
* the step named, which is a diagnosis rather than a silent 2% regression.
|
||||
* A `Split` step's regex is compiled at load (tokenizer_regex.h) into a DFA that reproduces what
|
||||
* HuggingFace tokenizers' Oniguruma reports, over Oniguruma's own Unicode tables. A pattern
|
||||
* outside that dialect does not load; the refusal names the construct and there is no fallback
|
||||
* matcher.
|
||||
*
|
||||
* A `Split` step is a regex, and it is COMPILED at load (tokenizer_regex.h) into a DFA that
|
||||
* reproduces what HuggingFace tokenizers' Oniguruma reports for it, over Oniguruma's own Unicode
|
||||
* tables. A pattern outside the dialect that compiler implements does not load: the refusal names
|
||||
* the construct, and there is no second matcher behind it.
|
||||
*
|
||||
* What is lifted from llama.cpp (06938ac12, MIT -- see vendor/UPSTREAM):
|
||||
* Lifted from llama.cpp (06938ac12, MIT -- see vendor/UPSTREAM):
|
||||
* - the byte-level alphabet and the unicode category tables the non-regex steps read
|
||||
* (vendor/llama/src/unicode*)
|
||||
* - the shape of the BPE bigram queue and the UGM Viterbi (src/llama-vocab.cpp)
|
||||
* The last of those is re-expressed here rather than vendored: llama-vocab.cpp is welded to
|
||||
* llama_model_loader, GGML_ASSERT and the llama_vocab class, so it is a file we would have had
|
||||
* to modify heavily, and spec §12 says such a file belongs in core/ under our own name.
|
||||
* The latter is re-expressed rather than vendored: llama-vocab.cpp depends on
|
||||
* llama_model_loader, GGML_ASSERT and llama_vocab, and spec §12 puts a heavily modified file in
|
||||
* core/ under our own name.
|
||||
*/
|
||||
#pragma once
|
||||
#include "rad_internal.h"
|
||||
@@ -46,10 +40,10 @@ struct TokEncoder;
|
||||
|
||||
/* One row of the declared chain, in the form rad-convert builds and the .rad bakes.
|
||||
*
|
||||
* `kind` is a RAD_NORM_* / RAD_PRE_* / RAD_DEC_* value from rad_format.h and its numeric range
|
||||
* says which of the three chains the row belongs to, so the three are ONE list in declared order
|
||||
* and no reader has to reassemble them. Per-kind meaning of flags/args is documented at
|
||||
* `step_describe()` in tokenizer.cpp; it is the contract rad-convert writes against. */
|
||||
* `kind` is a RAD_NORM_* / RAD_PRE_* / RAD_DEC_* value from rad_format.h; its numeric range says
|
||||
* which of the three chains the row belongs to, so all three are one list in declared order.
|
||||
* The per-kind meaning of flags/args is documented at `step_describe()` in tokenizer.cpp, the
|
||||
* contract rad-convert writes against. */
|
||||
struct VocabStep {
|
||||
uint32_t kind = 0;
|
||||
uint32_t flags = 0;
|
||||
@@ -57,6 +51,22 @@ struct VocabStep {
|
||||
int64_t iarg = 0;
|
||||
};
|
||||
|
||||
/* RAD_PRE_WHITESPACE's flags: which of HuggingFace's whitespace pre-tokenisers the step is.
|
||||
* Whitespace is 0, so a container written before the other two had flags reads as what it ran. */
|
||||
enum : uint32_t {
|
||||
kPreWhitespace = 0, /* the matches of \w+|[^\w\s]+, the rest removed */
|
||||
kPreWhitespaceSplit = 1, /* split on whitespace, removed */
|
||||
kPreBert = 2 /* WhitespaceSplit, then every punctuation character isolated */
|
||||
};
|
||||
|
||||
/* RAD_DEC_REPLACE's flags: 0 is a plain Replace of arg0 by arg1 in every token. The others are the
|
||||
* HuggingFace decoders converted to it, which also read the token's place in the list. */
|
||||
enum : uint32_t {
|
||||
kDecWordPiece = 1, /* arg0 is the continuation prefix; other words join with a space */
|
||||
kDecWordPieceCleanup = 2, /* with kDecWordPiece: WordPiece's `cleanup` of spaced punctuation */
|
||||
kDecBpeSuffix = 4 /* arg0 is the end-of-word suffix: a space, none after the last */
|
||||
};
|
||||
|
||||
/* Kind ranges, matching the enum blocks in rad_format.h. */
|
||||
inline bool step_is_norm(uint32_t k) { return k >= 1 && k < 32; }
|
||||
inline bool step_is_pre (uint32_t k) { return k >= 32 && k < 64; }
|
||||
@@ -64,10 +74,9 @@ inline bool step_is_dec (uint32_t k) { return k >= 64 && k < 96; }
|
||||
|
||||
/* Everything the tokeniser needs, in a form that can be built, inspected, written and read.
|
||||
*
|
||||
* The engine could bind directly to the mmapped .rad and save copying 248K token strings, and
|
||||
* deliberately does not: one construction path means the tokeniser that rad-convert tests with is
|
||||
* byte-for-byte the tokeniser the server runs. The cost is a few megabytes and a few tens of
|
||||
* milliseconds at load, against a model measured in gigabytes -- which is not a cost. */
|
||||
* The engine copies this out of the mmapped .rad instead of binding to it, so rad-convert and the
|
||||
* server share one construction path and run byte-for-byte the same tokeniser. The copy costs a
|
||||
* few megabytes and a few tens of milliseconds at load. */
|
||||
struct VocabBuild {
|
||||
uint32_t kind = RAD_TOK_BPE;
|
||||
bool ignore_merges = false; /* BPE: a whole pre-token in the vocab is not merged */
|
||||
@@ -87,9 +96,9 @@ struct VocabBuild {
|
||||
/* Diagnostics only: what rad-convert thought it was reading. Not baked. */
|
||||
std::string source;
|
||||
|
||||
/* The ids the checkpoint's generation_config.json names as eos_token_id, which the container
|
||||
* carries as metadata (`generation.eos_token_id`) rather than in the vocabulary section. The
|
||||
* engine fills it from there before load(); not baked. */
|
||||
/* generation_config.json's eos_token_id ids, carried as container metadata
|
||||
* (`generation.eos_token_id`) rather than in the vocab section. The engine fills them before
|
||||
* load(); not baked. */
|
||||
std::vector<int32_t> eos_ids;
|
||||
};
|
||||
|
||||
@@ -107,10 +116,9 @@ public:
|
||||
uint8_t type(int32_t id) const;
|
||||
float score(int32_t id) const;
|
||||
bool is_eog(int32_t id) const; /* eos, eot, or a declared extra */
|
||||
/* Every one of them, by id. The server needs the SPELLINGS: a chat format can fold the turn
|
||||
* terminator into its last marker, so the decoder has to render it for the reply parser --
|
||||
* and then whatever the parser did not consume has to come back off the content, because a
|
||||
* terminator is never something the user asked to read. */
|
||||
/* All end-of-generation ids. The server needs their spellings: a chat format can fold the
|
||||
* turn terminator into its last marker, so the decoder renders it for the reply parser, and
|
||||
* whatever the parser does not consume is stripped from the content. */
|
||||
const std::vector<int32_t>& eog() const { return eog_; }
|
||||
|
||||
/* -1 when the exact text is not a token. */
|
||||
@@ -132,7 +140,8 @@ public:
|
||||
const VocabBuild& build() const { return b_; }
|
||||
|
||||
/* The byte a RAD_TT_BYTE token stands for, or -1. Both spellings are recognised: SPM's
|
||||
* "<0xF0>" and byte-level BPE's single mapped codepoint. */
|
||||
* "<0xF0>" and byte-level BPE's single mapped codepoint. Under a ByteFallback decoder a NORMAL
|
||||
* "<0xNN>" token is a byte too. */
|
||||
int32_t token_byte(int32_t id) const;
|
||||
|
||||
private:
|
||||
@@ -142,12 +151,11 @@ private:
|
||||
std::unordered_map<uint64_t, int32_t> merge_rank_; /* (lhs id << 32 | rhs id) -> rank */
|
||||
std::vector<int32_t> special_; /* ids the pre-splitter must isolate */
|
||||
std::vector<int32_t> byte_of_; /* id -> byte, or -1 */
|
||||
/* Every token that ends a generation, not just the one the header had room for. Built in
|
||||
* load(); see the comment there for why a container's `eos` alone is not the whole set. */
|
||||
/* Every token that ends a generation, not just the header's `eos`; see load(). */
|
||||
std::vector<int32_t> eog_;
|
||||
/* The chain compiled for encoding: the Split DFAs, the flat token and merge tables, the
|
||||
* special-token matcher and the segment cache. Built in load(), shared by every Tokenizer
|
||||
* over this vocab and by every copy of it. */
|
||||
/* The chain compiled for encoding: Split DFAs, flat token and merge tables, special-token
|
||||
* matcher and segment cache. Built in load(); shared by every Tokenizer over this vocab and
|
||||
* every copy of it. */
|
||||
std::shared_ptr<TokEncoder> enc_;
|
||||
friend class Tokenizer;
|
||||
friend class Detokenizer;
|
||||
@@ -159,38 +167,44 @@ class Tokenizer {
|
||||
public:
|
||||
int init(std::shared_ptr<const Vocab> v);
|
||||
|
||||
/* `add_special` prepends BOS / appends EOS as the vocab declares. `parse_special` lets
|
||||
* control tokens in the raw text be recognised as themselves -- which the server wants for a
|
||||
* rendered chat template and must NOT have for user content, because otherwise a user can
|
||||
* type "<|im_start|>system" and reach the system role. */
|
||||
/* `add_special` prepends BOS / appends EOS as the vocab declares. `parse_special` recognises
|
||||
* control tokens in the raw text. Use it for a rendered chat template, never for user
|
||||
* content, or a user can type "<|im_start|>system" and reach the system role. */
|
||||
int encode(std::string_view text, std::vector<int32_t>& out,
|
||||
bool add_special, bool parse_special) const;
|
||||
|
||||
/* Non-streaming detokenise. The streaming one is Detokenizer below and it is the one the
|
||||
* server uses; this exists for tests, logging and the /v1/completions echo path. */
|
||||
/* Non-streaming detokenise, for tests, logging and the /v1/completions echo path. The server
|
||||
* streams through Detokenizer. */
|
||||
std::string decode(const std::vector<int32_t>& ids, bool render_special = false) const;
|
||||
|
||||
/* One token's text after the decoder chain. Does not resolve partial UTF-8 -- that is
|
||||
* exactly what Detokenizer is for. */
|
||||
/* One token's text after the decoder chain, as it reads in the middle of a text. Partial
|
||||
* UTF-8 is not resolved; Detokenizer does that. */
|
||||
std::string piece(int32_t id, bool render_special = false) const;
|
||||
|
||||
/* Where a token sits in the list being decoded. HuggingFace's decoders read it: Metaspace
|
||||
* drops the first token's replacement characters instead of turning them into spaces,
|
||||
* WordPiece joins every token but the first with a space, and BPEDecoder drops the last
|
||||
* token's suffix instead of turning it into a space. Special tokens left out of the text do
|
||||
* not count. */
|
||||
struct At {
|
||||
bool first = false;
|
||||
bool last = false;
|
||||
};
|
||||
std::string piece_at(int32_t id, bool render_special, At at) const;
|
||||
|
||||
const Vocab& vocab() const { return *v_; }
|
||||
|
||||
/* THE SEGMENT CACHE. encode() cuts its text at special tokens before anything else touches
|
||||
* it, and every piece between two of them is normalised, pre-tokenised and merged on its own:
|
||||
* no step of the chain reads across a special token, and none reads anything but the piece
|
||||
* (a Metaspace "first" prepend, a ByteLevel prefix space and every normaliser apply to each
|
||||
* piece as if it were the whole text). A piece's ids are therefore a function of its bytes
|
||||
* and the vocab alone, and a cache from the bytes to the ids returns exactly what encoding
|
||||
* them again would. That is what makes a re-sent conversation cost only what is new in it: an
|
||||
* agent's history arrives as the same pieces between the same `<|im_start|>` markers, turn
|
||||
* after turn.
|
||||
/* Segment cache. encode() first cuts the text at special tokens, and each piece between them
|
||||
* is normalised, pre-tokenised and merged on its own: no step reads across a special token,
|
||||
* and a ByteLevel prefix space and every normaliser treat each piece as the whole text. A
|
||||
* piece's ids are therefore a function of its bytes and the vocab, so a re-sent conversation
|
||||
* only pays for its new pieces. The one exception is a Metaspace "first" prepend, which as in
|
||||
* HuggingFace applies only to the piece that starts the text; that piece is not cached.
|
||||
*
|
||||
* The cache belongs to the vocab, so every Tokenizer over it shares it. It is keyed on the
|
||||
* whole piece (the hash only picks the bucket), bounded in bytes with least-recently-used
|
||||
* eviction, and locked for concurrent encodes. Pieces under kSegmentCacheMin bytes are not
|
||||
* cached: re-encoding them costs less than the lookup. `set_segment_cache(false)` makes this
|
||||
* Tokenizer bypass it, which is how the tests and rad-tokcheck compare the two. */
|
||||
* The cache belongs to the vocab and is shared by every Tokenizer over it. It is keyed on the
|
||||
* whole piece (the hash only picks the bucket), bounded in bytes with LRU eviction, and locked
|
||||
* for concurrent encodes. Pieces under kSegmentCacheMin bytes are cheaper to re-encode than to
|
||||
* look up. `set_segment_cache(false)` bypasses it, for tests and rad-tokcheck to compare. */
|
||||
static constexpr size_t kSegmentCacheMin = 64;
|
||||
static constexpr size_t kSegmentCacheDefault = size_t(64) << 20;
|
||||
void set_segment_cache(bool on) { use_cache_ = on; }
|
||||
@@ -209,42 +223,32 @@ private:
|
||||
|
||||
/* ================================================================== streaming decode */
|
||||
|
||||
/* Replace every byte that is not part of a well-formed UTF-8 sequence with U+FFFD, and leave
|
||||
* everything else alone. A byte-fallback vocab can emit a byte that no continuation completes --
|
||||
* `<0xC1>` is a lead byte for an encoding that is overlong and therefore never legal -- and the
|
||||
* generated text goes straight into a JSON string, where an invalid byte is not a mojibake
|
||||
* character but a 500: nlohmann::json::dump throws type_error.316 on it and the client gets an
|
||||
* engine error instead of the model's answer. Sanitising is the only option that keeps the
|
||||
* response: the bytes cannot be held back (nothing will complete them) and dropping them silently
|
||||
* would hide that the model produced something undecodable. Well-formed input is returned byte for
|
||||
* byte, so this is a no-op on every normal completion. */
|
||||
/* Replace every byte that is not part of a well-formed UTF-8 sequence with U+FFFD; well-formed
|
||||
* input is returned unchanged. A byte-fallback vocab can emit a byte no continuation completes
|
||||
* (`<0xC1>` only starts overlong, never-legal encodings), and nlohmann::json::dump throws
|
||||
* type_error.316 on it, failing the whole response. Such bytes cannot be held back, and dropping
|
||||
* them would hide that the model produced something undecodable. */
|
||||
std::string utf8_sanitize(std::string_view s);
|
||||
/* How much of `s` is well-formed UTF-8 from its start, by the same rules: what a JSON string can
|
||||
* carry of a byte-level token that ends inside a character. */
|
||||
/* Length of the well-formed UTF-8 prefix of `s`, by the same rules: how much of a byte-level
|
||||
* token that ends inside a character a JSON string can carry. */
|
||||
size_t utf8_valid_prefix(std::string_view s);
|
||||
|
||||
|
||||
/* Byte-level BPE emits partial UTF-8 sequences -- a single token can be one byte of a
|
||||
* three-byte codepoint -- and a stop string can straddle a chunk boundary. Both are buffered
|
||||
* until they resolve (spec §12). Emitting either one early is a visible bug: the first puts a
|
||||
* replacement character in the user's stream, the second leaks "</to" before the server notices
|
||||
* it was "</tool_call>".
|
||||
/* Streaming detokeniser (spec §12). Byte-level BPE emits partial UTF-8 (one token can be one byte
|
||||
* of a three-byte codepoint), and a stop string can straddle a chunk boundary; both are buffered
|
||||
* until they resolve, so the stream never shows a stray U+FFFD or leaks "</to" of "</tool_call>".
|
||||
*
|
||||
* The contract: push() returns text that is FINAL. It will never be retracted, it is always
|
||||
* WELL-FORMED UTF-8, and it is never a prefix of a stop string. Whatever is still ambiguous stays
|
||||
* inside until a later push resolves it or flush() gives up on it. A sequence that turns out to be
|
||||
* malformed rather than merely unfinished -- a byte-fallback vocab can emit one -- leaves as
|
||||
* U+FFFD (utf8_sanitize above) instead of as raw bytes, since the raw bytes cannot be put into a
|
||||
* JSON string and would cost the client the whole response. */
|
||||
* Contract: push() returns final text. It is never retracted, always well-formed UTF-8, and never
|
||||
* a prefix of a stop string. Ambiguous text stays inside until a later push resolves it or
|
||||
* flush() gives up on it. A sequence that is malformed rather than unfinished leaves as U+FFFD
|
||||
* (utf8_sanitize), since raw invalid bytes cannot go into a JSON string. */
|
||||
class Detokenizer {
|
||||
public:
|
||||
Detokenizer() = default;
|
||||
/* `preserved` is the tokens that must reach the caller as TEXT even though they are CONTROL.
|
||||
* A tool-calling format is MADE of them -- MiniCPM5 writes its calls with `<function`,
|
||||
* `<param`, `</param>`, `</function>`, every one a control token -- so suppressing them the
|
||||
* way a control token is normally suppressed hands the reply parser the arguments with the
|
||||
* structure removed, and the call comes back to the client as prose. The chat template says
|
||||
* which ones it needs (common_chat_params::preserved_tokens); nothing else is unsuppressed. */
|
||||
/* `preserved`: control tokens rendered as text anyway. Some tool-call formats are built from
|
||||
* control tokens (MiniCPM5: `<function`, `<param`, `</param>`, `</function>`); suppressing
|
||||
* them would strip the call's structure and hand the reply parser prose. The chat template
|
||||
* names them (common_chat_params::preserved_tokens); nothing else is unsuppressed. */
|
||||
Detokenizer(std::shared_ptr<const Vocab> v, std::vector<std::string> stops = {},
|
||||
bool render_special = false, const std::vector<std::string>& preserved = {});
|
||||
|
||||
@@ -256,25 +260,20 @@ public:
|
||||
bool stopped() const { return stopped_; }
|
||||
const std::string& stop_hit() const { return stop_hit_; }
|
||||
|
||||
/* STOP STRINGS ARE THE ANSWER'S, NOT THE REASONING'S. A generation that starts inside its
|
||||
* reasoning block is matched against its stop strings only after `marker` -- the block's
|
||||
* closer -- has been generated, and only in the text after it. Otherwise a stop string the
|
||||
* model happens to write while thinking ends the request with the reasoning cut short and no
|
||||
* answer at all: a few-shot harness that stops on "Q:" loses every reply whose reasoning
|
||||
* restates the question. "" = match from the first token, the behaviour of every request that
|
||||
* does not start in a block. */
|
||||
/* Stop strings apply to the answer, not the reasoning. For a generation that starts inside its
|
||||
* reasoning block, stops are matched only in the text after `marker` (the block's closer).
|
||||
* Otherwise a stop string written while thinking (e.g. a few-shot "Q:") ends the request with
|
||||
* no answer. "" matches from the first token. */
|
||||
void defer_stops_until(std::string marker) {
|
||||
arm_after_ = std::move(marker);
|
||||
armed_ = arm_after_.empty();
|
||||
arm_scanned_ = 0;
|
||||
}
|
||||
|
||||
/* Everything pushed so far, stop string included. The scheduler wants this to decide whether
|
||||
* a request finished on a stop or on a length limit. */
|
||||
/* Everything pushed so far, stop string included; the scheduler uses it to tell a stop from
|
||||
* a length limit. */
|
||||
const std::string& text() const { return all_; }
|
||||
|
||||
void reset();
|
||||
|
||||
private:
|
||||
std::shared_ptr<const Vocab> v_;
|
||||
std::vector<std::string> stops_;
|
||||
@@ -285,7 +284,14 @@ private:
|
||||
bool stopped_ = false;
|
||||
std::string stop_hit_;
|
||||
size_t max_stop_ = 0;
|
||||
bool first_ = true;
|
||||
bool first_ = true; /* no token has counted as the first yet */
|
||||
/* A Strip after Fuse in the decoder chain strips the text as a whole: up to `strip_left_`
|
||||
* copies of `strip_` at its start. */
|
||||
std::string strip_;
|
||||
int strip_left_ = 0;
|
||||
/* BPEDecoder turns a suffix into a space except on the last token, which a stream cannot
|
||||
* know, so a trailing space is held until the next token and dropped by flush(). */
|
||||
bool hold_space_ = false;
|
||||
std::string arm_after_; /* see defer_stops_until */
|
||||
bool armed_ = true;
|
||||
size_t arm_scanned_ = 0; /* how far into all_ the search for arm_after_ has reached */
|
||||
@@ -297,9 +303,9 @@ private:
|
||||
|
||||
/* ================================================================== sources and sinks */
|
||||
|
||||
/* rad-convert owns the .rad's single string blob; the vocab section only needs to intern into
|
||||
* it. Passing the interner rather than a blob keeps the two writers from disagreeing about who
|
||||
* owns offset 0. */
|
||||
/* rad-convert owns the .rad's single string blob; the vocab section only interns into it.
|
||||
* Passing the interner rather than a blob keeps the two writers from disagreeing about who owns
|
||||
* offset 0. */
|
||||
struct StringSink {
|
||||
virtual ~StringSink() = default;
|
||||
virtual rad_stroff intern(std::string_view s) = 0;
|
||||
@@ -307,27 +313,24 @@ struct StringSink {
|
||||
|
||||
/* Build a VocabBuild from a HuggingFace tokenizer.json.
|
||||
*
|
||||
* This is the function spec §12 is about: it INTERPRETS the declared normalizer / pre_tokenizer /
|
||||
* decoder chain instead of hashing the file. Returns RAD_OK, or a negative RAD_E_*; in
|
||||
* particular RAD_E_UNSUPPORTED when the file declares a component we cannot express as a
|
||||
* RadVocabStep, with the component named in the log. Failing there is the point -- a chain we
|
||||
* cannot express must not become a chain we silently approximate. */
|
||||
* Interprets the declared normalizer / pre_tokenizer / decoder chain (spec §12). Returns RAD_OK
|
||||
* or a negative RAD_E_*, notably RAD_E_UNSUPPORTED, with the component named in the log, for a
|
||||
* component that has no RadVocabStep form. Such a chain is refused, never approximated. */
|
||||
int parse_tokenizer_json(const char* path, VocabBuild& out);
|
||||
/* Same, from an in-memory buffer, for a tokenizer.json that arrived some other way. */
|
||||
int parse_tokenizer_json_buf(std::string_view json, const char* origin, VocabBuild& out);
|
||||
|
||||
/* Build a VocabBuild from a GGUF's tokenizer.ggml.* metadata.
|
||||
*
|
||||
* GGUF has no declared chain -- it has `tokenizer.ggml.pre`, a name llama.cpp derived by hashing
|
||||
* the original tokenizer.json. So this reconstructs the chain from that name against a table of
|
||||
* the ones we know, and returns RAD_E_UNSUPPORTED for a name we do not, rather than falling back
|
||||
* to a default split. That refusal is the whole difference from llama.cpp's behaviour, and it is
|
||||
* why converting from the original tokenizer.json is the preferred path. */
|
||||
* GGUF has no declared chain, only `tokenizer.ggml.pre`, a name llama.cpp derived by hashing the
|
||||
* original tokenizer.json. The chain is reconstructed from a table of known names; an unknown
|
||||
* name returns RAD_E_UNSUPPORTED instead of a default split. Converting from tokenizer.json is
|
||||
* the preferred path. */
|
||||
int vocab_from_gguf(const GgufFile& g, VocabBuild& out);
|
||||
|
||||
/* Serialise into the .rad's vocab section. `section_file_off` is where rad-convert will place
|
||||
* the section; every offset written into the RadVocabHeader is absolute from the start of the
|
||||
* file, per rad_format.h's rule that "every offset is from the start of the file". */
|
||||
* the section; every offset in the RadVocabHeader is absolute from the start of the file, per
|
||||
* rad_format.h. */
|
||||
int vocab_serialize(const VocabBuild& in, StringSink& strings, uint64_t section_file_off,
|
||||
std::vector<uint8_t>& section_out);
|
||||
/* Read it back. `file_base` is the mmapped .rad; `h` points inside it. */
|
||||
|
||||
+16
-16
@@ -1,15 +1,15 @@
|
||||
/* tokenizer_bpe.h -- the tables and the merge loop under Tokenizer's BPE.
|
||||
*
|
||||
* The merge is the textbook one and the one every reference implements: repeatedly merge the
|
||||
* adjacent pair with the lowest merge rank, the leftmost pair on a tie, until no adjacent pair
|
||||
* has a rank. It is kept rather than replaced by a linear-time encoder (GitHub's `bpe` crate)
|
||||
* because those are exact only for vocabularies whose every token re-encodes to itself, and a
|
||||
* vocabulary is not checked for that; this loop is exact for all of them. What makes it fast is
|
||||
* what it runs on: symbols are token ids, a rank lookup is one probe of an open-addressed table
|
||||
* keyed by the id pair, and a word of up to kLinearMax symbols is merged by a scan over a small
|
||||
* array instead of a heap, which for the four-to-eight-symbol words of real text is several times
|
||||
* cheaper. Long words take the heap. Both pick the same pair at every step -- lowest rank, then
|
||||
* lowest position -- so they produce the same merges.
|
||||
* The merge is the textbook one every reference implements: repeatedly merge the adjacent pair
|
||||
* with the lowest merge rank, leftmost on a tie, until no adjacent pair has a rank. Linear-time
|
||||
* encoders (GitHub's `bpe` crate) are exact only for vocabularies whose every token re-encodes to
|
||||
* itself, which is not checked; this loop is exact for all of them.
|
||||
*
|
||||
* Symbols are token ids, and a rank lookup is one probe of an open-addressed table keyed by the
|
||||
* id pair. Words of up to kBpeLinearMax symbols are merged by scanning a small array, several
|
||||
* times cheaper than a heap for the 4-8 symbol words of real text; longer words use the heap.
|
||||
* Both pick the same pair at every step (lowest rank, then lowest position), so they produce the
|
||||
* same merges.
|
||||
*/
|
||||
#pragma once
|
||||
#include <cstddef>
|
||||
@@ -45,9 +45,9 @@ inline uint64_t tok_hash(const void* data, size_t n) {
|
||||
}
|
||||
inline uint64_t tok_hash(std::string_view s) { return tok_hash(s.data(), s.size()); }
|
||||
|
||||
/* Byte string -> id, open-addressed, keys packed in one buffer. FIRST INSERT WINS, which is the
|
||||
* rule every lookup in the tokeniser follows: when two ids spell the same text, the lower one is
|
||||
* the one the merge table and every published count refer to. */
|
||||
/* Byte string -> id, open-addressed, keys packed in one buffer. First insert wins, as for every
|
||||
* lookup in the tokeniser: when two ids spell the same text, the merge table and every published
|
||||
* count refer to the lower one. */
|
||||
class TokTable {
|
||||
public:
|
||||
void reserve(size_t n);
|
||||
@@ -64,7 +64,7 @@ private:
|
||||
void grow();
|
||||
};
|
||||
|
||||
/* (left id, right id) -> (rank, id of the merged text or -1). FIRST INSERT WINS here too: a
|
||||
/* (left id, right id) -> (rank, id of the merged text or -1). First insert wins here too: a
|
||||
* duplicated merge keeps its lowest rank. */
|
||||
class MergeTable {
|
||||
public:
|
||||
@@ -103,8 +103,8 @@ struct BpeSym { uint32_t start, len; int32_t id; };
|
||||
/* Words up to this many symbols are merged by linear scan; longer ones by heap. */
|
||||
constexpr size_t kBpeLinearMax = 64;
|
||||
|
||||
/* Merge `syms` in place until no adjacent pair has a rank. `force_heap` exists for the test that
|
||||
* holds the two strategies to the same answer. */
|
||||
/* Merge `syms` in place until no adjacent pair has a rank. `force_heap` lets a test check that
|
||||
* both strategies agree. */
|
||||
void bpe_merge(std::vector<BpeSym>& syms, const MergeTable& merges, bool force_heap = false);
|
||||
|
||||
} /* namespace rad */
|
||||
+277
-236
@@ -1,11 +1,11 @@
|
||||
/* tokenizer_json.cpp -- reading a vocab in, and writing it into the .rad.
|
||||
*
|
||||
* Three sources and one sink:
|
||||
* parse_tokenizer_json() the HuggingFace file, interpreted rather than hashed. This is the
|
||||
* preferred path and the one spec §12 is about.
|
||||
* vocab_from_gguf() GGUF metadata, where the chain has already been lost and has to be
|
||||
* reconstructed from `tokenizer.ggml.pre`, a name llama.cpp derived by
|
||||
* hashing the original tokenizer.json.
|
||||
* parse_tokenizer_json() the HuggingFace file, interpreted rather than hashed; the preferred
|
||||
* path (spec §12).
|
||||
* vocab_from_gguf() GGUF metadata, where the chain is lost and is reconstructed from
|
||||
* `tokenizer.ggml.pre`, a name llama.cpp derived by hashing the
|
||||
* original tokenizer.json.
|
||||
* vocab_serialize() into the .rad's vocab section, and back.
|
||||
*/
|
||||
#include "text/tokenizer.h"
|
||||
@@ -25,21 +25,61 @@ using json = nlohmann::json;
|
||||
|
||||
namespace {
|
||||
|
||||
/* HuggingFace's SplitDelimiterBehavior, in the order our iarg encodes. */
|
||||
/* HuggingFace's SplitDelimiterBehavior, in the order our iarg encodes; -1 for another name. */
|
||||
int behavior_from_name(const std::string& s) {
|
||||
if (s == "Removed") return 0;
|
||||
if (s == "Isolated") return 1;
|
||||
if (s == "MergedWithPrevious") return 2;
|
||||
if (s == "MergedWithNext") return 3;
|
||||
if (s == "Contiguous") return 4;
|
||||
return 1; /* Isolated is the default in every tokenizer.json that omits it */
|
||||
return -1;
|
||||
}
|
||||
|
||||
/* Metaspace's prepend scheme, in the order our iarg encodes; -1 for another name. */
|
||||
int prepend_scheme_from_name(const std::string& s) {
|
||||
if (s == "never") return 0;
|
||||
if (s == "first") return 1;
|
||||
if (s == "always") return 2;
|
||||
return 2;
|
||||
return -1;
|
||||
}
|
||||
|
||||
/* A field value the tokenizer has no encoding for: guessing one would change the token
|
||||
* boundaries, so the vocabulary is refused like an unknown step. */
|
||||
int refuse_value(const char* origin, const char* field, const std::string& v) {
|
||||
RAD_ERR("%s: %s '%s' is not supported", origin, field, v.c_str());
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
|
||||
/* Merges read by token text into ids: a pair naming a text that is not a token is dropped and
|
||||
* counted, since some vocabs ship merges over strings that are not tokens. */
|
||||
struct MergeIds {
|
||||
std::unordered_map<std::string, uint32_t> id_of;
|
||||
size_t dropped = 0;
|
||||
|
||||
explicit MergeIds(const std::vector<std::string>& tokens) {
|
||||
id_of.reserve(tokens.size() * 2);
|
||||
for (size_t i = 0; i < tokens.size(); ++i) id_of.emplace(tokens[i], (uint32_t)i);
|
||||
}
|
||||
void add(const std::string& l, const std::string& r, VocabBuild& out) {
|
||||
auto li = id_of.find(l), ri = id_of.find(r);
|
||||
if (li == id_of.end() || ri == id_of.end()) { ++dropped; return; }
|
||||
out.merges.emplace_back(li->second, ri->second);
|
||||
}
|
||||
/* The "a b" spelling, split at the first space. */
|
||||
void add_spaced(const std::string& s, VocabBuild& out) {
|
||||
const size_t sp = s.find(' ');
|
||||
if (sp == std::string::npos) { ++dropped; return; }
|
||||
add(s.substr(0, sp), s.substr(sp + 1), out);
|
||||
}
|
||||
};
|
||||
|
||||
/* A Metaspace step over U+2581 that always prepends it, as a SentencePiece vocab reads. */
|
||||
VocabStep metaspace(uint32_t kind) {
|
||||
VocabStep s;
|
||||
s.kind = kind;
|
||||
s.arg0 = "\xe2\x96\x81";
|
||||
s.iarg = 2;
|
||||
return s;
|
||||
}
|
||||
|
||||
const json* get(const json& o, const char* k) {
|
||||
@@ -58,9 +98,9 @@ bool bool_or(const json& o, const char* k, bool dflt) {
|
||||
return v && v->is_boolean() ? v->get<bool>() : dflt;
|
||||
}
|
||||
|
||||
/* A regex a step carries is compiled HERE as well as when the vocab loads, so that rad-convert
|
||||
* refuses a pattern outside the compiler's dialect with the construct named, instead of writing a
|
||||
* container no engine will load. */
|
||||
/* A step's regex is compiled here as well as at vocab load, so rad-convert refuses an
|
||||
* unsupported pattern with the construct named instead of writing a container that cannot
|
||||
* load. */
|
||||
int check_regex(const std::string& pat, const char* what, const char* origin) {
|
||||
std::unique_ptr<TokRegex> re;
|
||||
std::string why;
|
||||
@@ -84,9 +124,9 @@ bool read_pattern(const json& o, std::string* pat, bool* is_regex) {
|
||||
return false;
|
||||
}
|
||||
|
||||
/* A token id out of the file, which indexes the token table as soon as it is read: a negative
|
||||
* one, or one that is not an integer, writes outside it, and a huge one sizes it. `limit` is
|
||||
* one past the largest id accepted (see parse_tokenizer_json_buf). */
|
||||
/* A token id from the file. It indexes the token table as soon as it is read, so a negative or
|
||||
* non-integer id would write outside it and a huge one would size it. `limit` is one past the
|
||||
* largest id accepted (see parse_tokenizer_json_buf). */
|
||||
bool read_id(const json& v, uint64_t limit, int32_t* out) {
|
||||
if (!v.is_number_integer()) return false;
|
||||
if (!v.is_number_unsigned() && v.get<int64_t>() < 0) return false;
|
||||
@@ -143,9 +183,8 @@ int read_normalizer(const json& n, std::vector<VocabStep>& out, const char* orig
|
||||
out.push_back(s);
|
||||
return RAD_OK;
|
||||
}
|
||||
/* Everything else is refused BY NAME rather than ignored. An ignored normaliser is a
|
||||
* tokeniser that runs, produces different boundaries, and says nothing -- exactly the
|
||||
* failure this component exists to remove (spec §12). */
|
||||
/* Anything else is refused by name: ignoring a normaliser silently changes token boundaries
|
||||
* (spec §12). */
|
||||
RAD_ERR("%s: normalizer '%s' has no RadVocabStep. Refusing rather than approximating it; "
|
||||
"add a RAD_NORM_* for it if a model needs it.", origin, t.c_str());
|
||||
return RAD_E_UNSUPPORTED;
|
||||
@@ -176,8 +215,8 @@ int read_pretok(const json& n, std::vector<VocabStep>& out, const char* origin)
|
||||
return RAD_E_FORMAT;
|
||||
}
|
||||
if (!is_regex) {
|
||||
/* A literal delimiter is a regex with every metacharacter escaped. Doing the escape
|
||||
* at convert time keeps the runtime with one kind of Split instead of two. */
|
||||
/* A literal delimiter becomes a regex with every metacharacter escaped, so the
|
||||
* runtime has one kind of Split. */
|
||||
std::string q;
|
||||
for (char c : s.arg0) {
|
||||
if (std::strchr("\\^$.|?*+()[]{}", c)) q += '\\';
|
||||
@@ -187,7 +226,9 @@ int read_pretok(const json& n, std::vector<VocabStep>& out, const char* origin)
|
||||
}
|
||||
s.kind = RAD_PRE_SPLIT;
|
||||
s.flags = bool_or(n, "invert", false) ? 1u : 0u;
|
||||
s.iarg = behavior_from_name(str_or(n, "behavior", "Isolated"));
|
||||
const std::string bh = str_or(n, "behavior", "Isolated");
|
||||
s.iarg = behavior_from_name(bh);
|
||||
if (s.iarg < 0) return refuse_value(origin, "Split behavior", bh);
|
||||
RAD_TRY(check_regex(s.arg0, "Split", origin));
|
||||
out.push_back(s);
|
||||
return RAD_OK;
|
||||
@@ -195,7 +236,9 @@ int read_pretok(const json& n, std::vector<VocabStep>& out, const char* origin)
|
||||
if (t == "Metaspace") {
|
||||
s.kind = RAD_PRE_METASPACE;
|
||||
s.arg0 = str_or(n, "replacement", "\xe2\x96\x81");
|
||||
s.iarg = prepend_scheme_from_name(str_or(n, "prepend_scheme", "always"));
|
||||
const std::string ps = str_or(n, "prepend_scheme", "always");
|
||||
s.iarg = prepend_scheme_from_name(ps);
|
||||
if (s.iarg < 0) return refuse_value(origin, "Metaspace prepend_scheme", ps);
|
||||
s.flags = bool_or(n, "split", true) ? 1u : 0u;
|
||||
/* The pre-0.14 spelling: add_prefix_space instead of prepend_scheme. */
|
||||
if (!get(n, "prepend_scheme")) s.iarg = bool_or(n, "add_prefix_space", true) ? 2 : 0;
|
||||
@@ -203,13 +246,17 @@ int read_pretok(const json& n, std::vector<VocabStep>& out, const char* origin)
|
||||
return RAD_OK;
|
||||
}
|
||||
if (t == "Whitespace" || t == "WhitespaceSplit" || t == "BertPreTokenizer") {
|
||||
s.kind = RAD_PRE_WHITESPACE;
|
||||
s.kind = RAD_PRE_WHITESPACE;
|
||||
s.flags = t == "Whitespace" ? kPreWhitespace
|
||||
: t == "WhitespaceSplit" ? kPreWhitespaceSplit : kPreBert;
|
||||
out.push_back(s);
|
||||
return RAD_OK;
|
||||
}
|
||||
if (t == "Punctuation") {
|
||||
s.kind = RAD_PRE_PUNCTUATION;
|
||||
s.iarg = behavior_from_name(str_or(n, "behavior", "Isolated"));
|
||||
const std::string bh = str_or(n, "behavior", "Isolated");
|
||||
s.iarg = behavior_from_name(bh);
|
||||
if (s.iarg < 0) return refuse_value(origin, "Punctuation behavior", bh);
|
||||
out.push_back(s);
|
||||
return RAD_OK;
|
||||
}
|
||||
@@ -219,8 +266,7 @@ int read_pretok(const json& n, std::vector<VocabStep>& out, const char* origin)
|
||||
out.push_back(s);
|
||||
return RAD_OK;
|
||||
}
|
||||
RAD_ERR("%s: pre_tokenizer '%s' has no RadVocabStep. Refusing rather than falling back to a "
|
||||
"default split -- a default split is llama.cpp's failure mode, not ours.",
|
||||
RAD_ERR("%s: pre_tokenizer '%s' is not supported; no RAD_PRE_* step implements it",
|
||||
origin, t.c_str());
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
@@ -241,7 +287,9 @@ int read_decoder(const json& n, std::vector<VocabStep>& out, const char* origin)
|
||||
if (t == "Metaspace") {
|
||||
s.kind = RAD_DEC_METASPACE;
|
||||
s.arg0 = str_or(n, "replacement", "\xe2\x96\x81");
|
||||
s.iarg = prepend_scheme_from_name(str_or(n, "prepend_scheme", "always"));
|
||||
const std::string ps = str_or(n, "prepend_scheme", "always");
|
||||
s.iarg = prepend_scheme_from_name(ps);
|
||||
if (s.iarg < 0) return refuse_value(origin, "Metaspace prepend_scheme", ps);
|
||||
if (!get(n, "prepend_scheme")) s.iarg = bool_or(n, "add_prefix_space", true) ? 2 : 0;
|
||||
out.push_back(s);
|
||||
return RAD_OK;
|
||||
@@ -274,20 +322,22 @@ int read_decoder(const json& n, std::vector<VocabStep>& out, const char* origin)
|
||||
return RAD_OK;
|
||||
}
|
||||
if (t == "WordPiece") {
|
||||
/* WordPiece's decoder is a Replace of the continuation prefix plus a leading strip.
|
||||
* Expressing it as the two steps it is keeps the runtime free of a per-model branch. */
|
||||
/* A Replace of the continuation prefix that also joins words with a space, as
|
||||
* HuggingFace's WordPiece decoder does (kDecWordPiece). `cleanup` defaults to true. */
|
||||
VocabStep r;
|
||||
r.kind = RAD_DEC_REPLACE;
|
||||
r.arg0 = str_or(n, "prefix", "##");
|
||||
r.arg1 = "";
|
||||
r.kind = RAD_DEC_REPLACE;
|
||||
r.arg0 = str_or(n, "prefix", "##");
|
||||
r.flags = kDecWordPiece | (bool_or(n, "cleanup", true) ? kDecWordPieceCleanup : 0u);
|
||||
out.push_back(r);
|
||||
return RAD_OK;
|
||||
}
|
||||
if (t == "BPEDecoder") {
|
||||
/* The end-of-word suffix becomes a space, except on the last token (kDecBpeSuffix). */
|
||||
VocabStep r;
|
||||
r.kind = RAD_DEC_REPLACE;
|
||||
r.arg0 = str_or(n, "suffix", "</w>");
|
||||
r.arg1 = " ";
|
||||
r.kind = RAD_DEC_REPLACE;
|
||||
r.arg0 = str_or(n, "suffix", "</w>");
|
||||
r.arg1 = " ";
|
||||
r.flags = kDecBpeSuffix;
|
||||
out.push_back(r);
|
||||
return RAD_OK;
|
||||
}
|
||||
@@ -305,9 +355,8 @@ int read_model(const json& m, VocabBuild& out, const char* origin, uint64_t id_l
|
||||
return RAD_E_FORMAT;
|
||||
}
|
||||
|
||||
/* {text: id}, the BPE and WordPiece shape. The ids are dense, but nothing guarantees the
|
||||
* JSON order matches the id order, so each is placed by id -- which is why every one is
|
||||
* checked before the table is sized from them. */
|
||||
/* {text: id}, the BPE and WordPiece shape. JSON order need not match id order, so each
|
||||
* entry is placed by id; every id is checked before the table is sized from them. */
|
||||
auto read_text_to_id = [&](const char* kind) -> int {
|
||||
if (!vocab->is_object()) {
|
||||
RAD_ERR("%s: %s vocab is not an object of {text: id}", origin, kind);
|
||||
@@ -336,6 +385,14 @@ 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);
|
||||
}
|
||||
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"));
|
||||
} else if (type == "Unigram") {
|
||||
out.kind = RAD_TOK_UNIGRAM;
|
||||
@@ -354,8 +411,7 @@ int read_model(const json& m, VocabBuild& out, const char* origin, uint64_t id_l
|
||||
out.scores.push_back(e[1].get<float>());
|
||||
}
|
||||
out.types.assign(out.tokens.size(), (uint8_t)RAD_TT_NORMAL);
|
||||
/* The encoder emits this id for text no piece covers, so one that names no token would
|
||||
* put an id outside the vocabulary into the output. */
|
||||
/* The encoder emits this id for uncovered text, so it must name a token. */
|
||||
const json* u = get(m, "unk_id");
|
||||
if (u && !read_id(*u, out.tokens.size(), &out.unk)) {
|
||||
RAD_ERR("%s: Unigram unk_id %.64s is not an id in its %zu-token vocab", origin,
|
||||
@@ -364,6 +420,13 @@ int read_model(const json& m, VocabBuild& out, const char* origin, uint64_t id_l
|
||||
}
|
||||
} else if (type == "WordPiece") {
|
||||
out.kind = RAD_TOK_WORDPIECE;
|
||||
/* The encoder spells continuations "##" and takes words of up to 100 characters,
|
||||
* HuggingFace's defaults. */
|
||||
const std::string prefix = str_or(m, "continuing_subword_prefix", "##");
|
||||
if (prefix != "##") return refuse_value(origin, "WordPiece continuing_subword_prefix", prefix);
|
||||
if (const json* mc = get(m, "max_input_chars_per_word");
|
||||
mc && !(mc->is_number_integer() && mc->get<int64_t>() == 100))
|
||||
return refuse_value(origin, "WordPiece max_input_chars_per_word", mc->dump());
|
||||
RAD_TRY(read_text_to_id("WordPiece"));
|
||||
} else {
|
||||
RAD_ERR("%s: model type '%s' is not implemented (BPE, Unigram and WordPiece are)",
|
||||
@@ -371,8 +434,8 @@ int read_model(const json& m, VocabBuild& out, const char* origin, uint64_t id_l
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
|
||||
/* Byte fallback is a property of the MODEL in tokenizer.json and a step for us, because it
|
||||
* changes what the encoder does on a miss and the encoder is where the miss happens. */
|
||||
/* 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)) {
|
||||
VocabStep s;
|
||||
s.kind = RAD_PRE_BYTE_FALLBACK;
|
||||
@@ -381,52 +444,42 @@ int read_model(const json& m, VocabBuild& out, const char* origin, uint64_t id_l
|
||||
|
||||
if (type != "BPE") return RAD_OK;
|
||||
|
||||
/* Merges. Two spellings in the wild: ["a b", ...] and [["a","b"], ...]. The second exists
|
||||
* because a token can contain a space. */
|
||||
/* Merges come as ["a b", ...] or, since a token can contain a space, [["a","b"], ...]. */
|
||||
const json* merges = get(m, "merges");
|
||||
if (!merges || !merges->is_array()) return RAD_OK;
|
||||
|
||||
std::unordered_map<std::string, uint32_t> id_of;
|
||||
id_of.reserve(out.tokens.size() * 2);
|
||||
for (size_t i = 0; i < out.tokens.size(); ++i) id_of.emplace(out.tokens[i], (uint32_t)i);
|
||||
|
||||
size_t dropped = 0;
|
||||
MergeIds ids(out.tokens);
|
||||
out.merges.reserve(merges->size());
|
||||
for (const json& e : *merges) {
|
||||
std::string l, r;
|
||||
if (e.is_array() && e.size() == 2 && e[0].is_string() && e[1].is_string()) {
|
||||
l = e[0].get<std::string>();
|
||||
r = e[1].get<std::string>();
|
||||
} else if (e.is_string()) {
|
||||
const std::string s = e.get<std::string>();
|
||||
const size_t sp = s.find(' ');
|
||||
if (sp == std::string::npos) { ++dropped; continue; }
|
||||
l = s.substr(0, sp);
|
||||
r = s.substr(sp + 1);
|
||||
} else {
|
||||
++dropped;
|
||||
continue;
|
||||
}
|
||||
auto li = id_of.find(l), ri = id_of.find(r);
|
||||
if (li == id_of.end() || ri == id_of.end()) { ++dropped; continue; }
|
||||
out.merges.emplace_back(li->second, ri->second);
|
||||
if (e.is_array() && e.size() == 2 && e[0].is_string() && e[1].is_string())
|
||||
ids.add(e[0].get<std::string>(), e[1].get<std::string>(), out);
|
||||
else if (e.is_string())
|
||||
ids.add_spaced(e.get<std::string>(), out);
|
||||
else
|
||||
++ids.dropped;
|
||||
}
|
||||
if (dropped) {
|
||||
/* Every dropped merge is a merge the tokeniser will not make, so the boundary moves.
|
||||
* It is a warning rather than an error only because a handful of vocabs genuinely ship
|
||||
* merges over strings they never added as tokens. */
|
||||
/* A dropped merge moves token boundaries; only a warning, as MergeIds says why. */
|
||||
if (ids.dropped)
|
||||
RAD_WARN("%s: %zu of %zu merges reference text that is not in the vocab and were "
|
||||
"dropped; token boundaries may differ from the reference tokeniser",
|
||||
origin, dropped, merges->size());
|
||||
}
|
||||
origin, ids.dropped, merges->size());
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* Added tokens override the model vocab and may extend past it. `special` decides whether the
|
||||
* pre-splitter treats them as control (isolated even when parse_special is off is NOT the rule --
|
||||
* see Tokenizer::encode) or as user-defined. */
|
||||
int read_added(const json& arr, VocabBuild& out, const char* origin, uint64_t id_limit) {
|
||||
/* Added tokens override the model vocab and may extend past it. `special` makes a token control
|
||||
* (isolated only when parse_special is on; see Tokenizer::encode) rather than user-defined.
|
||||
*
|
||||
* 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
|
||||
* 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) {
|
||||
if (!arr.is_array()) return RAD_OK;
|
||||
std::string stripped;
|
||||
for (const json& e : arr) {
|
||||
const json* idv = get(e, "id");
|
||||
const json* cv = get(e, "content");
|
||||
@@ -443,17 +496,28 @@ int read_added(const json& arr, VocabBuild& out, const char* origin, uint64_t id
|
||||
out.types.resize(id + 1, (uint8_t)RAD_TT_NORMAL);
|
||||
if (out.kind == RAD_TOK_UNIGRAM) out.scores.resize(id + 1, 0.0f);
|
||||
}
|
||||
out.tokens[id] = cv->get<std::string>();
|
||||
out.types[id] = bool_or(e, "special", false) ? (uint8_t)RAD_TT_CONTROL
|
||||
: (uint8_t)RAD_TT_USER_DEFINED;
|
||||
const std::string content = cv->get<std::string>();
|
||||
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 (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;
|
||||
}
|
||||
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 "
|
||||
"them tokenise differently", origin, stripped.c_str());
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* tokenizer_config.json is where the ids live. tokenizer.json holds the vocab and the chain but
|
||||
* not which token is BOS, so a convert that reads only tokenizer.json produces a vocab that
|
||||
* cannot start a sequence. Reading the sibling is opportunistic: absent, the ids stay -1 and
|
||||
* rad-convert can fill them from elsewhere. */
|
||||
/* tokenizer_config.json names the special tokens; tokenizer.json does not say which is BOS.
|
||||
* The sibling is optional: when it is absent the ids stay -1 and rad-convert can fill them from
|
||||
* elsewhere. */
|
||||
void read_config_json(const std::string& dir, VocabBuild& out) {
|
||||
const std::string path = dir + "tokenizer_config.json";
|
||||
std::ifstream f(path);
|
||||
@@ -493,8 +557,8 @@ void read_config_json(const std::string& dir, VocabBuild& out) {
|
||||
const json* ct = get(c, "chat_template");
|
||||
if (ct && ct->is_string()) out.chat_template = ct->get<std::string>();
|
||||
else if (ct && ct->is_array() && !ct->empty()) {
|
||||
/* The multi-template form: a list of {name, template}. The one named "default" wins,
|
||||
* else the first, which is what every renderer does. */
|
||||
/* The multi-template form, a list of {name, template}: "default" wins, else the first,
|
||||
* as renderers do. */
|
||||
for (const json& e : *ct) {
|
||||
if (str_or(e, "name", "") == "default") { out.chat_template = str_or(e, "template", ""); break; }
|
||||
}
|
||||
@@ -503,13 +567,9 @@ void read_config_json(const std::string& dir, VocabBuild& out) {
|
||||
}
|
||||
|
||||
|
||||
/* THE TEMPLATE MAY NOT BE IN tokenizer_config.json AT ALL. Recent transformers versions write it
|
||||
* to a standalone chat_template.jinja and omit the key, so a checkpoint saved by one of those
|
||||
* converts with NO template at all unless this sibling is read -- and the only symptom is the
|
||||
* server answering /v1/chat/completions with 501, a long way from the cause.
|
||||
*
|
||||
* The file wins where it exists, which is what transformers itself does; in a checkpoint that
|
||||
* carries both, the config key is the superseded copy. */
|
||||
/* Recent transformers versions write the template to a standalone chat_template.jinja and omit
|
||||
* the config key; without it, /v1/chat/completions answers 501. The file wins over the config
|
||||
* key, as in transformers. */
|
||||
void read_chat_template_file(const std::string& dir, VocabBuild& out) {
|
||||
const std::string path = dir + "chat_template.jinja";
|
||||
std::ifstream f(path);
|
||||
@@ -544,10 +604,9 @@ int interpret_tokenizer_json(const json& j, uint64_t id_limit, const char* origi
|
||||
}
|
||||
RAD_TRY(read_model(*model, out, origin, id_limit));
|
||||
|
||||
/* Order matters and it is the file's order: normaliser, then pre-tokeniser, then decoder.
|
||||
* They land in one list because that is what RadVocabHeader holds, and the kind ranges keep
|
||||
* them separable. read_model may already have pushed a ByteFallback step, which belongs
|
||||
* with the pre-tokenisers; it is re-sorted below. */
|
||||
/* One list, as RadVocabHeader holds it: normaliser, pre-tokeniser, then decoder steps, each
|
||||
* in file order; the kind ranges keep them separable. A ByteFallback step pushed by
|
||||
* read_model belongs with the pre-tokenisers and is moved there. */
|
||||
std::vector<VocabStep> pre_from_model;
|
||||
pre_from_model.swap(out.steps);
|
||||
|
||||
@@ -562,15 +621,38 @@ int interpret_tokenizer_json(const json& j, uint64_t id_limit, const char* origi
|
||||
out.steps.insert(out.steps.end(), pre.begin(), pre.end());
|
||||
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));
|
||||
if (const json* a = get(j, "added_tokens"))
|
||||
RAD_TRY(read_added(*a, out, origin, id_limit, !norm.empty()));
|
||||
|
||||
/* WHAT `add_special_tokens` ADDS, when the file says it in its post-processor rather than in
|
||||
* tokenizer_config.json. HuggingFace's encode runs the post-processor, so a TemplateProcessing
|
||||
* whose single-sequence template is `<bos> $A <eos>` IS the model's add-BOS-and-EOS rule --
|
||||
* Gemma states it there and nowhere else, and an embedding model fed its input without the
|
||||
* <eos> it was trained to pool over computes a different vector. Only the two shapes that map
|
||||
* onto add_bos / add_eos are read: one special token before the sequence, one after. The
|
||||
* config's own add_bos_token / add_eos_token, read later, win where present. */
|
||||
/* 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. */
|
||||
if (out.unk < 0) {
|
||||
const std::string unk = str_or(*model, "unk_token", "");
|
||||
for (size_t i = 0; !unk.empty() && i < out.tokens.size(); ++i)
|
||||
if (out.tokens[i] == unk) { out.unk = (int32_t)i; break; }
|
||||
}
|
||||
|
||||
/* A Strip after Fuse strips the decoded text as a whole. Its start can be stripped as text
|
||||
* streams; its end cannot be taken back once streamed, and two of them would interleave. */
|
||||
{
|
||||
bool fused = false, stripped = false;
|
||||
for (const VocabStep& s : dec) {
|
||||
if (s.kind == RAD_DEC_FUSE) fused = true;
|
||||
if (s.kind != RAD_DEC_STRIP || !fused) continue;
|
||||
if ((s.iarg >> 32) != 0 || stripped) {
|
||||
RAD_ERR("%s: a Strip decoder after Fuse that strips the end of the text, or a "
|
||||
"second one, is not supported", origin);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
stripped = true;
|
||||
}
|
||||
}
|
||||
|
||||
/* What `add_special_tokens` adds, when the post-processor says it. HuggingFace's encode runs
|
||||
* the post-processor, so a TemplateProcessing single template `<bos> $A <eos>` is the model's
|
||||
* add-BOS/EOS rule; Gemma states it only there, and an embedding model pools over that <eos>.
|
||||
* 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 json* single = get(*pp, "single");
|
||||
@@ -604,15 +686,13 @@ int parse_tokenizer_json_buf(std::string_view text, const char* origin, VocabBui
|
||||
out = VocabBuild{};
|
||||
out.source = origin;
|
||||
|
||||
/* NO ID PAST THE SIZE OF THE FILE. Ids are dense, so a vocabulary that names one beyond the
|
||||
* number of bytes listing it would leave more ids unused than the file has bytes; bounding
|
||||
* them by it is what bounds the token table they size to a multiple of the input, whatever
|
||||
* the ids claim. */
|
||||
/* No id may exceed the file size in bytes. Ids are dense, so a valid file never needs a
|
||||
* larger one, and the bound keeps the token table proportional to the input. */
|
||||
const uint64_t id_limit = text.size();
|
||||
|
||||
/* A value of the wrong JSON type throws out of nlohmann on the first get<>() that meets it.
|
||||
* The reader checks the shapes that decide what is written where; this turns any other one
|
||||
* into the refusal it is rather than into std::terminate in the converter. */
|
||||
/* nlohmann throws on the first get<>() of a value with the wrong JSON type. The reader checks
|
||||
* the shapes that decide where things are written; this turns any other mismatch into a
|
||||
* format error instead of std::terminate. */
|
||||
try {
|
||||
return interpret_tokenizer_json(j, id_limit, origin, out);
|
||||
} catch (const json::exception& e) {
|
||||
@@ -654,73 +734,71 @@ namespace {
|
||||
|
||||
/* `tokenizer.ggml.pre` -> the pre-tokeniser regex list.
|
||||
*
|
||||
* These are llama.cpp's ADAPTED patterns, copied verbatim from llm_tokenizer_bpe's constructor
|
||||
* (06938ac12). Copying rather than deriving is deliberate: the adaptation llama.cpp applied is
|
||||
* part of the pattern's identity for a GGUF -- gpt-4o's `((?=[\p{L}])([^a-z]))*` is not o200k's
|
||||
* `[\p{Lu}\p{Lt}\p{Lm}\p{Lo}\p{M}]*`, and a GGUF tokenises the way llama.cpp runs it. They
|
||||
* llama.cpp's adapted patterns, copied verbatim from llm_tokenizer_bpe's constructor
|
||||
* (06938ac12). They are copied, not derived, because a GGUF tokenises the way llama.cpp runs
|
||||
* it: gpt-4o's `((?=[\p{L}])([^a-z]))*` is not o200k's `[\p{Lu}\p{Lt}\p{Lm}\p{Lo}\p{M}]*`. They
|
||||
* go through the same compiler as a tokenizer.json pattern.
|
||||
*
|
||||
* The one exception is kimi-k2. llama.cpp spells it `\p{Han}+` and uses that string only as the
|
||||
* key of a hand-written splitter approximating Kimi-K2's real pattern; as a regex it would split
|
||||
* Han runs and nothing else. The entry is the real pattern, from the model's tokenization_kimi.py,
|
||||
* which is what that splitter was written to stand in for.
|
||||
* Exception: kimi-k2. llama.cpp's `\p{Han}+` is only the key of a hand-written splitter that
|
||||
* approximates Kimi-K2's pattern; as a regex it would split only Han runs. The entry here is the
|
||||
* real pattern from the model's tokenization_kimi.py.
|
||||
*
|
||||
* The list is not exhaustive and does not try to be. A GGUF whose `pre` is not here is REFUSED,
|
||||
* with the instruction to convert from tokenizer.json instead -- which is the path that does not
|
||||
* depend on this table at all. */
|
||||
* The list is not exhaustive. A GGUF whose `pre` is missing is refused, with the advice to
|
||||
* convert from tokenizer.json. */
|
||||
struct PreEntry { const char* name; const char* regex[4]; bool byte_encode; };
|
||||
|
||||
/* The patterns several entries share. */
|
||||
constexpr const char* kGpt2 =
|
||||
"'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)";
|
||||
constexpr const char* kLlama3 =
|
||||
"(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])|[^\\r\\n\\p{L}\\p{N}]?\\p{L}+|\\p{N}{1,3}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+";
|
||||
constexpr const char* kQwen2 =
|
||||
"(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])|[^\\r\\n\\p{L}\\p{N}]?\\p{L}+|\\p{N}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+";
|
||||
constexpr const char* kGpt4o =
|
||||
"[^\\r\\n\\p{L}\\p{N}]?((?=[\\p{L}])([^a-z]))*((?=[\\p{L}])([^A-Z]))+(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])?|[^\\r\\n\\p{L}\\p{N}]?((?=[\\p{L}])([^a-z]))+((?=[\\p{L}])([^A-Z]))*(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])?|\\p{N}{1,3}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n/]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+";
|
||||
constexpr const char* kLines = "[^\\n]+|[\\n]+";
|
||||
|
||||
const PreEntry k_pre[] = {
|
||||
{ "default", {
|
||||
"[\\p{P}\\$\\+<=>\\^~\\|]+",
|
||||
"'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)",
|
||||
"\\p{N}+",
|
||||
"[0-9][0-9][0-9]" }, true },
|
||||
{ "llama3", { "(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])|[^\\r\\n\\p{L}\\p{N}]?\\p{L}+|\\p{N}{1,3}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+" }, true },
|
||||
{ "llama-bpe", { "(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])|[^\\r\\n\\p{L}\\p{N}]?\\p{L}+|\\p{N}{1,3}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+" }, true },
|
||||
{ "llama-v3", { "(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])|[^\\r\\n\\p{L}\\p{N}]?\\p{L}+|\\p{N}{1,3}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+" }, true },
|
||||
{ "falcon3", { "(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])|[^\\r\\n\\p{L}\\p{N}]?\\p{L}+|\\p{N}{1,3}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+" }, true },
|
||||
{ "pixtral", { "(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])|[^\\r\\n\\p{L}\\p{N}]?\\p{L}+|\\p{N}{1,3}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+" }, true },
|
||||
{ "lfm2", { "(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])|[^\\r\\n\\p{L}\\p{N}]?\\p{L}+|\\p{N}{1,3}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+" }, true },
|
||||
{ "dbrx", { "(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])|[^\\r\\n\\p{L}\\p{N}]?\\p{L}+|\\p{N}{1,3}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+" }, true },
|
||||
{ "smaug-bpe", { "(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])|[^\\r\\n\\p{L}\\p{N}]?\\p{L}+|\\p{N}{1,3}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+" }, true },
|
||||
{ "glm4", { "(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])|[^\\r\\n\\p{L}\\p{N}]?\\p{L}+|\\p{N}{1,3}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+" }, true },
|
||||
{ "chatglm-bpe", { "(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])|[^\\r\\n\\p{L}\\p{N}]?\\p{L}+|\\p{N}{1,3}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+" }, true },
|
||||
|
||||
{ "gpt-2", { "'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)" }, true },
|
||||
{ "phi-2", { "'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)" }, true },
|
||||
{ "mpt", { "'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)" }, true },
|
||||
{ "olmo", { "'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)" }, true },
|
||||
{ "jais", { "'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)" }, true },
|
||||
{ "trillion", { "'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)" }, true },
|
||||
{ "granite-docling", { "'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)" }, true },
|
||||
|
||||
{ "starcoder", { "\\p{N}", "'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)" }, true },
|
||||
{ "refact", { "\\p{N}", "'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)" }, true },
|
||||
{ "command-r", { "\\p{N}", "'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)" }, true },
|
||||
{ "smollm", { "\\p{N}", "'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)" }, true },
|
||||
{ "codeshell", { "\\p{N}", "'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)" }, true },
|
||||
{ "exaone", { "\\p{N}", "'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)" }, true },
|
||||
{ "minerva-7b",{ "\\p{N}", "'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)" }, true },
|
||||
|
||||
{ "qwen2", { "(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])|[^\\r\\n\\p{L}\\p{N}]?\\p{L}+|\\p{N}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+" }, true },
|
||||
{ "stablelm2", { "(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])|[^\\r\\n\\p{L}\\p{N}]?\\p{L}+|\\p{N}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+" }, true },
|
||||
{ "deepseek-r1-qwen", { "(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])|[^\\r\\n\\p{L}\\p{N}]?\\p{L}+|\\p{N}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+" }, true },
|
||||
{ "hunyuan", { "(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])|[^\\r\\n\\p{L}\\p{N}]?\\p{L}+|\\p{N}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+" }, true },
|
||||
{ "solar-open", { "(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])|[^\\r\\n\\p{L}\\p{N}]?\\p{L}+|\\p{N}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+" }, true },
|
||||
{ "grok-2", { "(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])|[^\\r\\n\\p{L}\\p{N}]?\\p{L}+|\\p{N}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+" }, true },
|
||||
|
||||
{ "qwen35", { "(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])|[^\\r\\n\\p{L}\\p{N}]?[\\p{L}\\p{M}]+|\\p{N}| ?[^\\s\\p{L}\\p{M}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+" }, true },
|
||||
|
||||
{ "gpt-4o", { "[^\\r\\n\\p{L}\\p{N}]?((?=[\\p{L}])([^a-z]))*((?=[\\p{L}])([^A-Z]))+(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])?|[^\\r\\n\\p{L}\\p{N}]?((?=[\\p{L}])([^a-z]))+((?=[\\p{L}])([^A-Z]))*(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])?|\\p{N}{1,3}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n/]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+" }, true },
|
||||
{ "llama4", { "[^\\r\\n\\p{L}\\p{N}]?((?=[\\p{L}])([^a-z]))*((?=[\\p{L}])([^A-Z]))+(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])?|[^\\r\\n\\p{L}\\p{N}]?((?=[\\p{L}])([^a-z]))+((?=[\\p{L}])([^A-Z]))*(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])?|\\p{N}{1,3}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n/]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+" }, true },
|
||||
{ "tekken", { "[^\\r\\n\\p{L}\\p{N}]?((?=[\\p{L}])([^a-z]))*((?=[\\p{L}])([^A-Z]))+|[^\\r\\n\\p{L}\\p{N}]?((?=[\\p{L}])([^a-z]))+((?=[\\p{L}])([^A-Z]))*|\\p{N}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n/]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+" }, true },
|
||||
|
||||
{ "default", { "[\\p{P}\\$\\+<=>\\^~\\|]+", kGpt2, "\\p{N}+", "[0-9][0-9][0-9]" }, true },
|
||||
{ "llama3", { kLlama3 }, true },
|
||||
{ "llama-bpe", { kLlama3 }, true },
|
||||
{ "llama-v3", { kLlama3 }, true },
|
||||
{ "falcon3", { kLlama3 }, true },
|
||||
{ "pixtral", { kLlama3 }, true },
|
||||
{ "lfm2", { kLlama3 }, true },
|
||||
{ "dbrx", { kLlama3 }, true },
|
||||
{ "smaug-bpe", { kLlama3 }, true },
|
||||
{ "glm4", { kLlama3 }, true },
|
||||
{ "chatglm-bpe", { kLlama3 }, true },
|
||||
{ "gpt-2", { kGpt2 }, true },
|
||||
{ "phi-2", { kGpt2 }, true },
|
||||
{ "mpt", { kGpt2 }, true },
|
||||
{ "olmo", { kGpt2 }, true },
|
||||
{ "jais", { kGpt2 }, true },
|
||||
{ "trillion", { kGpt2 }, true },
|
||||
{ "granite-docling", { kGpt2 }, true },
|
||||
{ "starcoder", { "\\p{N}", kGpt2 }, true },
|
||||
{ "refact", { "\\p{N}", kGpt2 }, true },
|
||||
{ "command-r", { "\\p{N}", kGpt2 }, true },
|
||||
{ "smollm", { "\\p{N}", kGpt2 }, true },
|
||||
{ "codeshell", { "\\p{N}", kGpt2 }, true },
|
||||
{ "exaone", { "\\p{N}", kGpt2 }, true },
|
||||
{ "minerva-7b", { "\\p{N}", kGpt2 }, true },
|
||||
{ "qwen2", { kQwen2 }, true },
|
||||
{ "stablelm2", { kQwen2 }, true },
|
||||
{ "deepseek-r1-qwen", { kQwen2 }, true },
|
||||
{ "hunyuan", { kQwen2 }, true },
|
||||
{ "solar-open", { kQwen2 }, true },
|
||||
{ "grok-2", { kQwen2 }, true },
|
||||
{ "qwen35", { "(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])|[^\\r\\n\\p{L}\\p{N}]?[\\p{L}\\p{M}]+|\\p{N}| ?[^\\s\\p{L}\\p{M}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+" }, true },
|
||||
{ "gpt-4o", { kGpt4o }, true },
|
||||
{ "llama4", { kGpt4o }, true },
|
||||
{ "tekken", { "[^\\r\\n\\p{L}\\p{N}]?((?=[\\p{L}])([^a-z]))*((?=[\\p{L}])([^A-Z]))+|[^\\r\\n\\p{L}\\p{N}]?((?=[\\p{L}])([^a-z]))+((?=[\\p{L}])([^A-Z]))*|\\p{N}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n/]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+" }, true },
|
||||
{ "seed-coder", { "(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])|[^\\r\\n\\p{L}\\p{N}]?\\p{L}+|\\p{N}{1}| ?[^\\s\\p{L}\\p{N}\\r\\n]+|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+" }, true },
|
||||
{ "kimi-k2", { "[\\p{Han}]+|[^\\r\\n\\p{L}\\p{N}]?[\\p{Lu}\\p{Lt}\\p{Lm}\\p{Lo}\\p{M}&&[^\\p{Han}]]*[\\p{Ll}\\p{Lm}\\p{Lo}\\p{M}&&[^\\p{Han}]]+(?i:'s|'t|'re|'ve|'m|'ll|'d)?|[^\\r\\n\\p{L}\\p{N}]?[\\p{Lu}\\p{Lt}\\p{Lm}\\p{Lo}\\p{M}&&[^\\p{Han}]]+[\\p{Ll}\\p{Lm}\\p{Lo}\\p{M}&&[^\\p{Han}]]*(?i:'s|'t|'re|'ve|'m|'ll|'d)?|\\p{N}{1,3}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+" }, true },
|
||||
{ "kimi-k2", { "[\\p{Han}]+|[^\\r\\n\\p{L}\\p{N}]?[\\p{Lu}\\p{Lt}\\p{Lm}\\p{Lo}\\p{M}&&[^\\p{Han}]]*[\\p{Ll}\\p{Lm}\\p{Lo}\\p{M}&&[^\\p{Han}]]+(?i:'s|'t|'re|'ve|'m|'ll|'d)?|[^\\r\\n\\p{L}\\p{N}]?[\\p{Lu}\\p{Lt}\\p{Lm}\\p{Lo}\\p{M}&&[^\\p{Han}]]+[\\p{Ll}\\p{Lm}\\p{Lo}\\p{M}&&[^\\p{Han}]]*(?i:'s|'t|'re|'ve|'m|'ll|'d)?|\\p{N}{1,3}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+" }, true },
|
||||
{ "whitespace", { "\\S+" }, false },
|
||||
{ "gemma4", { "[^\\n]+|[\\n]+" }, false },
|
||||
{ "sarvam-moe", { "[^\\n]+|[\\n]+" }, false },
|
||||
{ "gemma4", { kLines }, false },
|
||||
{ "sarvam-moe", { kLines }, false },
|
||||
};
|
||||
|
||||
} /* namespace */
|
||||
@@ -772,8 +850,7 @@ int vocab_from_gguf(const GgufFile& g, VocabBuild& out) {
|
||||
const PreEntry* e = nullptr;
|
||||
for (const PreEntry& p : k_pre) if (pre == p.name) { e = &p; break; }
|
||||
if (!e) {
|
||||
/* This is the refusal spec §12 asks for. llama.cpp would fall back to `default` here
|
||||
* and produce plausible text with wrong boundaries; we would rather not run. */
|
||||
/* Refused per spec §12; llama.cpp falls back to `default` and splits wrongly. */
|
||||
RAD_ERR("gguf: tokenizer.ggml.pre = '%s' is not in this build's table, and guessing "
|
||||
"would give a silently different split. Convert from the model's "
|
||||
"tokenizer.json instead, which needs no table.", pre.c_str());
|
||||
@@ -797,85 +874,49 @@ int vocab_from_gguf(const GgufFile& g, VocabBuild& out) {
|
||||
out.steps.push_back(d);
|
||||
} else {
|
||||
/* SPM-shaped BPE: the vocab is raw UTF-8 with U+2581 for space. */
|
||||
VocabStep s;
|
||||
s.kind = RAD_PRE_METASPACE;
|
||||
s.arg0 = "\xe2\x96\x81";
|
||||
s.iarg = 2;
|
||||
out.steps.push_back(s);
|
||||
VocabStep d;
|
||||
d.kind = RAD_DEC_METASPACE;
|
||||
d.arg0 = "\xe2\x96\x81";
|
||||
d.iarg = 2;
|
||||
out.steps.push_back(d);
|
||||
out.steps.push_back(metaspace(RAD_PRE_METASPACE));
|
||||
out.steps.push_back(metaspace(RAD_DEC_METASPACE));
|
||||
}
|
||||
|
||||
std::vector<std::string> merges;
|
||||
g.get_strs("tokenizer.ggml.merges", &merges);
|
||||
std::unordered_map<std::string, uint32_t> id_of;
|
||||
id_of.reserve(out.tokens.size() * 2);
|
||||
for (size_t i = 0; i < out.tokens.size(); ++i) id_of.emplace(out.tokens[i], (uint32_t)i);
|
||||
|
||||
size_t dropped = 0;
|
||||
MergeIds ids(out.tokens);
|
||||
out.merges.reserve(merges.size());
|
||||
for (const std::string& m : merges) {
|
||||
const size_t sp = m.find(' ');
|
||||
if (sp == std::string::npos) { ++dropped; continue; }
|
||||
auto l = id_of.find(m.substr(0, sp));
|
||||
auto r = id_of.find(m.substr(sp + 1));
|
||||
if (l == id_of.end() || r == id_of.end()) { ++dropped; continue; }
|
||||
out.merges.emplace_back(l->second, r->second);
|
||||
}
|
||||
if (dropped)
|
||||
RAD_WARN("gguf: %zu of %zu merges dropped (a half is not a token); token boundaries "
|
||||
"may differ from the reference tokeniser", dropped, merges.size());
|
||||
for (const std::string& m : merges) ids.add_spaced(m, out);
|
||||
if (ids.dropped)
|
||||
RAD_WARN("gguf: %zu of %zu merges dropped (one side of the merge is not a token); "
|
||||
"token boundaries may differ from the reference tokeniser",
|
||||
ids.dropped, merges.size());
|
||||
} else if (model == "llama") {
|
||||
out.kind = RAD_TOK_BPE;
|
||||
/* SPM proper: whitespace escaped to U+2581, byte fallback for the rest. Expressed as
|
||||
* steps so the runtime has no per-model branch. */
|
||||
VocabStep m;
|
||||
m.kind = RAD_PRE_METASPACE;
|
||||
m.arg0 = "\xe2\x96\x81";
|
||||
m.iarg = 2;
|
||||
out.steps.push_back(m);
|
||||
/* SPM: whitespace escaped to U+2581, byte fallback for the rest, expressed as steps so
|
||||
* the runtime has no per-model branch. */
|
||||
out.steps.push_back(metaspace(RAD_PRE_METASPACE));
|
||||
VocabStep bf;
|
||||
bf.kind = RAD_PRE_BYTE_FALLBACK;
|
||||
out.steps.push_back(bf);
|
||||
VocabStep d;
|
||||
d.kind = RAD_DEC_METASPACE;
|
||||
d.arg0 = "\xe2\x96\x81";
|
||||
d.iarg = 2;
|
||||
out.steps.push_back(d);
|
||||
RAD_WARN("gguf: '%s' is a SentencePiece vocab and this build tokenises it as BPE over the "
|
||||
"same pieces. That is right for the vocabs that ship as GGUF today and it is "
|
||||
"not the SPM bigram algorithm; convert from tokenizer.json to be sure.",
|
||||
out.steps.push_back(metaspace(RAD_DEC_METASPACE));
|
||||
RAD_WARN("gguf: '%s' is a SentencePiece vocab, tokenised as BPE over its pieces rather "
|
||||
"than by the SPM bigram algorithm; convert from tokenizer.json for an exact match",
|
||||
model.c_str());
|
||||
} else if (model == "t5") {
|
||||
out.kind = RAD_TOK_UNIGRAM;
|
||||
VocabStep m;
|
||||
m.kind = RAD_PRE_METASPACE;
|
||||
m.arg0 = "\xe2\x96\x81";
|
||||
m.iarg = 2;
|
||||
out.steps.push_back(m);
|
||||
VocabStep d;
|
||||
d.kind = RAD_DEC_METASPACE;
|
||||
d.arg0 = "\xe2\x96\x81";
|
||||
d.iarg = 2;
|
||||
out.steps.push_back(d);
|
||||
out.steps.push_back(metaspace(RAD_PRE_METASPACE));
|
||||
out.steps.push_back(metaspace(RAD_DEC_METASPACE));
|
||||
} else if (model == "bert") {
|
||||
out.kind = RAD_TOK_WORDPIECE;
|
||||
VocabStep n;
|
||||
n.kind = RAD_NORM_LOWERCASE;
|
||||
out.steps.push_back(n);
|
||||
/* BertPreTokenizer and the WordPiece decoder, as a BERT tokenizer.json declares them. */
|
||||
VocabStep w;
|
||||
w.kind = RAD_PRE_WHITESPACE;
|
||||
w.kind = RAD_PRE_WHITESPACE;
|
||||
w.flags = kPreBert;
|
||||
out.steps.push_back(w);
|
||||
VocabStep p;
|
||||
p.kind = RAD_PRE_PUNCTUATION;
|
||||
p.iarg = 1;
|
||||
out.steps.push_back(p);
|
||||
VocabStep d;
|
||||
d.kind = RAD_DEC_REPLACE;
|
||||
d.arg0 = "##";
|
||||
d.kind = RAD_DEC_REPLACE;
|
||||
d.arg0 = "##";
|
||||
d.flags = kDecWordPiece | kDecWordPieceCleanup;
|
||||
out.steps.push_back(d);
|
||||
} else {
|
||||
RAD_ERR("gguf: tokenizer.ggml.model = '%s' is not implemented", model.c_str());
|
||||
@@ -906,8 +947,8 @@ int vocab_serialize(const VocabBuild& in, StringSink& strings, uint64_t off,
|
||||
if (in.tokens.size() > UINT32_MAX || in.merges.size() > UINT32_MAX ||
|
||||
in.steps.size() > UINT32_MAX) return RAD_E_INVAL;
|
||||
|
||||
/* Every string goes into the file's one blob and only its offset is stored here, per
|
||||
* rad_format.h. That is what makes the section fixed-stride and mmap-walkable. */
|
||||
/* Strings go into the file's one blob and only their offsets are stored here (rad_format.h),
|
||||
* so the section is fixed-stride and mmap-walkable. */
|
||||
std::vector<rad_stroff> tok_off(in.tokens.size());
|
||||
for (size_t i = 0; i < in.tokens.size(); ++i) tok_off[i] = strings.intern(in.tokens[i]);
|
||||
|
||||
@@ -935,8 +976,9 @@ int vocab_serialize(const VocabBuild& in, StringSink& strings, uint64_t off,
|
||||
h.flags = in.ignore_merges ? RAD_VOCAB_IGNORE_MERGES : 0;
|
||||
out.resize(sizeof(RadVocabHeader), 0);
|
||||
|
||||
/* Each array is aligned to its own element so a mapped reader can point a typed pointer at
|
||||
* it. RAD_ALIGN_SUB would be enough for the container's rules; 8 is what the types need. */
|
||||
/* Each array is aligned to its element type so a mapped reader can use a typed pointer.
|
||||
* The largest alignment needed is 8; the container's own rule would only require
|
||||
* RAD_ALIGN_SUB. */
|
||||
auto place = [&](size_t align, const void* p, size_t bytes) -> uint64_t {
|
||||
pad_to(out, (size_t)off, align);
|
||||
const uint64_t at = off + out.size();
|
||||
@@ -972,9 +1014,8 @@ int vocab_deserialize(const void* file_base, uint64_t file_bytes, const RadVocab
|
||||
const char* strs = nullptr;
|
||||
uint64_t str_bytes = 0;
|
||||
{
|
||||
/* The string blob's extent comes from the file header, which sits at offset 0. Reading
|
||||
* it here rather than taking it as an argument keeps the caller from having to keep the
|
||||
* two in sync. */
|
||||
/* The string blob's extent is read from the file header at offset 0 rather than passed
|
||||
* in, so the caller cannot pass a mismatched one. */
|
||||
if (file_bytes < sizeof(RadFileHeader)) return RAD_E_FORMAT;
|
||||
const RadFileHeader* fh = reinterpret_cast<const RadFileHeader*>(base);
|
||||
if (fh->str_off + fh->str_bytes > file_bytes) return RAD_E_FORMAT;
|
||||
|
||||
+13
-13
@@ -11,25 +11,25 @@ namespace {
|
||||
|
||||
/* NFC, applied only where it can change something.
|
||||
*
|
||||
* UAX #15's quick check: a codepoint whose NFC_QC is Yes and whose combining class is 0 is a
|
||||
* BOUNDARY -- nothing before it can compose with it or reorder across it, and nothing it becomes
|
||||
* can reach back past it -- so normalising the text between two boundaries on its own gives exactly
|
||||
* the bytes normalising the whole text gives there. The text is scanned for the codepoints that
|
||||
* are not boundaries (NFC_QC No or Maybe, a mark out of canonical order, anything not strictly
|
||||
* well-formed), and only the stretch from the boundary before each one to the boundary after it
|
||||
* goes through unorm_utf8; everything else is already NFC and is copied. The properties are
|
||||
* derived from the same tables unorm_utf8 runs on -- "No" is a codepoint NFC does not leave alone
|
||||
* by itself, "Maybe" is one that can compose with what precedes it -- so the scan agrees with that
|
||||
* implementation rather than with some other one. Invalid bytes are never at a boundary, so the
|
||||
* decoder's replacement of them happens inside a normalised stretch, byte for byte as it does when
|
||||
* the whole text is normalised. */
|
||||
* UAX #15 quick check: a codepoint with NFC_QC Yes and combining class 0 is a boundary. Nothing
|
||||
* before it can compose with it or reorder across it, and nothing it becomes reaches back past
|
||||
* it, so normalising the text between two boundaries alone gives the same bytes as normalising
|
||||
* the whole text. The scan finds the non-boundary codepoints (NFC_QC No or Maybe, a mark out of
|
||||
* canonical order, ill-formed UTF-8) and runs unorm_utf8 only from the boundary before each one
|
||||
* to the boundary after it; the rest is copied. The properties are derived from the tables
|
||||
* unorm_utf8 uses ("No": NFC changes the codepoint on its own; "Maybe": it can compose with what
|
||||
* precedes it), so the scan agrees with that implementation. Invalid bytes are never boundaries,
|
||||
* so their replacement happens inside a normalised stretch, exactly as for the whole text. */
|
||||
class NfcQuick {
|
||||
public:
|
||||
NfcQuick() : not_yes_(kWords, 0), marked_(kWords, 0) {
|
||||
for (size_t i = 0; i < k_decomp_rows_n; ++i) {
|
||||
const DecompRow& r = k_decomp_rows[i];
|
||||
if (r.len_c == 0) continue;
|
||||
if (unorm_nfc({ r.cpt }) != std::vector<uint32_t>{ r.cpt }) set(not_yes_, r.cpt);
|
||||
std::vector<uint32_t> v{ r.cpt };
|
||||
unorm_decompose(v, false);
|
||||
unorm_compose(v);
|
||||
if (v != std::vector<uint32_t>{ r.cpt }) set(not_yes_, r.cpt);
|
||||
}
|
||||
for (size_t i = 0; i < k_compose_n; ++i) set(not_yes_, k_compose[i].b);
|
||||
for (uint32_t c = 0x1161; c <= 0x1175; ++c) set(not_yes_, c); /* Hangul V, composes after L */
|
||||
|
||||
@@ -1,13 +1,12 @@
|
||||
/* tokenizer_nfc.h -- NFC for the tokeniser's normaliser chain, applied only where it can change
|
||||
* something. Byte for byte what unorm_utf8(text, false, true) returns; see tokenizer_nfc.cpp for
|
||||
* why normalising the stretches around the codepoints that are not NFC boundaries is the same as
|
||||
* normalising the whole text. */
|
||||
* something. The result is byte for byte unorm_utf8(text, false, true); tokenizer_nfc.cpp explains
|
||||
* why normalising only the stretches around non-boundary codepoints is equivalent. */
|
||||
#pragma once
|
||||
#include <string>
|
||||
|
||||
namespace rad {
|
||||
|
||||
/* Normalise `text` in place. False when it was already NFC and has not been touched. */
|
||||
/* Normalise `text` in place. Returns false when it was already NFC and is untouched. */
|
||||
bool tok_nfc(std::string& text);
|
||||
|
||||
} /* namespace rad */
|
||||
@@ -241,8 +241,7 @@ struct Flags { bool i = false, m = false, x = false; };
|
||||
|
||||
/* Recursive descent over the pattern's codepoints. Every refusal goes through fail(), which
|
||||
* records the first reason and makes every caller unwind; the message names the construct and
|
||||
* the byte where it starts, because "unsupported pattern" alone sends the reader to a
|
||||
* 200-character regex with no idea where to look. */
|
||||
* the byte where it starts. */
|
||||
class Parser {
|
||||
public:
|
||||
explicit Parser(std::string_view pat) : pat_(pat) {}
|
||||
@@ -345,8 +344,8 @@ private:
|
||||
return add(n);
|
||||
}
|
||||
|
||||
/* `(?imx-imx)` with no colon. Oniguruma reads the REST of the enclosing group -- every `|`
|
||||
* after it included -- as one group with the new flags, so `a(?i)b|c` is `a(?i:b|c)` and not
|
||||
/* `(?imx-imx)` with no colon. Oniguruma reads the rest of the enclosing group, every later `|`
|
||||
* included, as one group with the new flags: `a(?i)b|c` is `a(?i:b|c)`, not
|
||||
* `a(?i:b)|(?i:c)`. The caller parses that rest as a nested alternation. */
|
||||
bool try_inline_flags(const Flags& f, Flags* g) {
|
||||
if (peek() != '(' || peek(1) != '?') return false;
|
||||
@@ -727,7 +726,7 @@ private:
|
||||
|
||||
/* `[` already consumed. Oniguruma's classes: a leading `^`, nested classes as union, `&&` as
|
||||
* intersection, `-` literal at either end. Under `(?i)` the class is closed over the case
|
||||
* orbits BEFORE it is negated, which is what makes `(?i:[^a-z])` exclude 'A'. */
|
||||
* orbits before it is negated, so `(?i:[^a-z])` excludes 'A'. */
|
||||
bool parse_class(const Flags& f, CpSet* out) {
|
||||
const size_t at = start_;
|
||||
const bool neg = peek() == '^';
|
||||
@@ -944,7 +943,7 @@ inline uint32_t decode_canon(const uint8_t* p, uint32_t* len) {
|
||||
struct TokRegex::Dfa {
|
||||
static constexpr uint32_t kMatch = 0x80000000u;
|
||||
|
||||
/* States are named by their ROW OFFSET, state * ncls, so the inner loop indexes the table
|
||||
/* States are named by their row offset, state * ncls, so the inner loop indexes the table
|
||||
* with one add. The dead state is row 0. */
|
||||
uint32_t ncls = 0;
|
||||
std::vector<uint32_t> trans; /* row + class -> next row | kMatch */
|
||||
@@ -1107,11 +1106,10 @@ int TokRegex::compile(std::string_view pattern, std::unique_ptr<TokRegex>* out,
|
||||
*
|
||||
* A DFA state is the ordered list of NFA states reached by consuming the last codepoint
|
||||
* (before their epsilon closure), plus what is remembered of that codepoint. The closure is
|
||||
* taken on the TRANSITION, when the next codepoint's class is known, so a lookahead is
|
||||
* decided exactly. Walking the closure in priority order, reaching MATCH means a match ends
|
||||
* here and every thread after it is dropped: a lower-priority thread can never produce the
|
||||
* match a backtracking engine would report once a higher one has matched. The threads before
|
||||
* it survive, and a later match from one of them replaces this one. */
|
||||
* taken on the transition, when the next codepoint's class is known, so a lookahead is
|
||||
* decided exactly. Walking the closure in priority order, reaching MATCH records a match and
|
||||
* drops every lower-priority thread, which a backtracking engine would never reach. Higher-
|
||||
* priority threads survive, and a later match from one of them replaces this one. */
|
||||
std::vector<uint32_t> mark(nfa.size(), 0), mark2(nfa.size(), 0);
|
||||
uint32_t stamp = 0, stamp2 = 0;
|
||||
std::vector<int> stack, chars, next_kernel;
|
||||
@@ -1186,12 +1184,13 @@ int TokRegex::compile(std::string_view pattern, std::unique_ptr<TokRegex>* out,
|
||||
d->trans.resize((size_t)kernels.size() * d->ncls, 0);
|
||||
d->eoi_match.resize(kernels.size(), 0);
|
||||
if (s == 0) continue;
|
||||
/* A copy: intern() may reallocate `kernels`. Row s of `trans` exists from the resize
|
||||
* above, and the states intern() adds get theirs on their own iteration. */
|
||||
const std::vector<int> kernel = kernels[s];
|
||||
const uint32_t lb = lbs[s];
|
||||
for (uint32_t c = 0; c < d->ncls; ++c) {
|
||||
const bool m = closure(kernel, lb, (int)c, &next_kernel);
|
||||
const uint32_t t = intern(next_kernel, uses_behind ? lb_after[c] : 0);
|
||||
d->trans.resize((size_t)kernels.size() * d->ncls, 0);
|
||||
d->trans[(size_t)s * d->ncls + c] = t | (m ? Dfa::kMatch : 0);
|
||||
}
|
||||
d->eoi_match[s] = closure(kernel, lb, -1, nullptr) ? 1 : 0;
|
||||
@@ -1234,7 +1233,7 @@ int64_t TokRegex::match_at(std::string_view text, size_t pos) const {
|
||||
|
||||
void TokRegex::find_iter(std::string_view text, std::vector<TokSpan>& out) const {
|
||||
/* Oniguruma's iteration as the `onig` crate drives it: search from the end of the previous
|
||||
* match for the leftmost position with a match; an EMPTY match exactly at the end of the
|
||||
* match for the leftmost position with a match; an empty match exactly at the end of the
|
||||
* previous one is skipped by advancing one codepoint and searching again. */
|
||||
const uint8_t* s = (const uint8_t*)text.data();
|
||||
const size_t n = text.size();
|
||||
@@ -1400,8 +1399,8 @@ void utf8_canonicalize(std::string_view str, std::string& out) {
|
||||
out += (char)(0x80 | ((c >> 6) & 0x3F));
|
||||
out += (char)(0x80 | (c & 0x3F));
|
||||
};
|
||||
/* unicode_cpts_from_utf8's rules, the decoder the rest of the chain uses: a lead byte with
|
||||
* the continuations it announces decodes (overlong forms and surrogates included), anything
|
||||
/* unicode_cpts_from_utf8's rules, as used by the rest of the chain: a lead byte followed by
|
||||
* the continuations it announces decodes (overlong forms and surrogates included); anything
|
||||
* else is one U+FFFD per byte. */
|
||||
for (size_t i = 0; i < n; ) {
|
||||
const uint8_t b = p[i];
|
||||
|
||||
+20
-22
@@ -2,27 +2,26 @@
|
||||
*
|
||||
* A tokenizer.json `Split` carries a regex in Oniguruma's Ruby syntax, and HuggingFace tokenizers
|
||||
* runs it through Oniguruma's backtracking matcher. This compiles the same pattern into a DFA over
|
||||
* codepoint classes and reproduces what that matcher reports, match for match:
|
||||
* codepoint classes that reports the same matches:
|
||||
*
|
||||
* - Unicode properties are Oniguruma's own (tokenizer_ucd.h), so `\p{L}`, `\s`, `\w` and the
|
||||
* `(?i)` orbits mean exactly what they mean there.
|
||||
* - Alternation is leftmost-FIRST, not leftmost-longest: the DFA carries its NFA threads in
|
||||
* priority order and a match cuts every thread below it, which is the backtracking order
|
||||
* without the backtracking (the construction RE2 and regex-automata use). Greedy and lazy
|
||||
* quantifiers are the same priority order read the other way.
|
||||
* - Lookaround of ONE codepoint (`\s+(?!\S)`, `(?=[\p{L}])`, `(?<=x)`), `^`, `$`, `\A`, `\z`,
|
||||
* `\b` and `\B` are assertions on the neighbouring codepoints. The DFA carries what it needs
|
||||
* of the previous codepoint in its state and decides a lookahead on the transition that reads
|
||||
* the next one, so a match is reported one transition late, when that codepoint is known.
|
||||
* - find_iter reproduces Oniguruma's iteration exactly, empty matches included: a match is
|
||||
* reported at the leftmost position where one exists, and an empty match at the end of the
|
||||
* previous match is skipped by one codepoint, as the `onig` crate does.
|
||||
* `(?i)` orbits mean what they mean there.
|
||||
* - Alternation is leftmost-first, not leftmost-longest: the DFA carries its NFA threads in
|
||||
* priority order and a match cuts every lower thread, giving backtracking order without
|
||||
* backtracking (the RE2 / regex-automata construction). Lazy quantifiers reverse the priority.
|
||||
* - One-codepoint lookaround (`\s+(?!\S)`, `(?=[\p{L}])`, `(?<=x)`), `^`, `$`, `\A`, `\z`, `\b`
|
||||
* and `\B` are assertions on the neighbouring codepoints. The state carries what it needs of
|
||||
* the previous codepoint, and a lookahead is decided on the transition that reads the next
|
||||
* one, so a match is reported one transition late.
|
||||
* - find_iter follows Oniguruma's iteration, empty matches included: each match is the leftmost
|
||||
* one, and an empty match at the end of the previous match is skipped by one codepoint, as
|
||||
* the `onig` crate does.
|
||||
*
|
||||
* Anything else is REFUSED at compile time with the construct named: backreferences, atomic
|
||||
* Anything else is refused at compile time with the construct named: backreferences, atomic
|
||||
* groups and possessive quantifiers, lookaround wider than one codepoint, unbounded repetition of
|
||||
* something that can match empty, `(?i)` over a character that folds to several (U+00DF against
|
||||
* "ss"), and properties the tables do not carry. There is no second matcher to fall back to; a
|
||||
* pattern either compiles to this or the vocabulary does not load.
|
||||
* something that can match empty, `(?i)` over a character that folds to several (U+00DF vs "ss"),
|
||||
* and properties the tables do not carry. There is no fallback matcher; a pattern that does not
|
||||
* compile fails the vocabulary load.
|
||||
*/
|
||||
#pragma once
|
||||
#include <cstddef>
|
||||
@@ -69,8 +68,7 @@ enum TokSplitBehavior {
|
||||
};
|
||||
|
||||
/* NormalizedString::split: the non-empty pieces of `text` that `behavior` keeps, appended to
|
||||
* `out` as spans of `text`. `scratch` is reused between calls to keep the hot path free of
|
||||
* allocation. */
|
||||
* `out` as spans of `text`. `scratch` is reused between calls to avoid allocation. */
|
||||
void tok_split(const TokRegex& re, std::string_view text, int behavior, bool invert,
|
||||
std::vector<TokSpan>& out, std::vector<TokSpan>& scratch);
|
||||
|
||||
@@ -83,9 +81,9 @@ void tok_replace(const TokRegex& re, std::string_view text, std::string_view con
|
||||
bool utf8_is_canonical(std::string_view s);
|
||||
|
||||
/* Append that round trip of `s` to `out`: each byte that does not start a decodable sequence
|
||||
* becomes U+FFFD, an overlong form becomes its shortest one. These are the rules of
|
||||
* unicode_cpts_from_utf8, the decoder the normalisers and the other pre-tokenisers use, so a
|
||||
* Split sees the same text they do. */
|
||||
* becomes U+FFFD, and an overlong form becomes its shortest one. These are the rules of
|
||||
* unicode_cpts_from_utf8, the decoder the normalisers and other pre-tokenisers use, so a Split
|
||||
* sees the same text they do. */
|
||||
void utf8_canonicalize(std::string_view s, std::string& out);
|
||||
|
||||
} /* namespace rad */
|
||||
@@ -1,10 +1,9 @@
|
||||
/* tokenizer_ucd.h -- the Unicode properties a pre-tokeniser pattern can name.
|
||||
*
|
||||
* The tables are generated (tools/gen_tokenizer_ucd.cpp) by asking Oniguruma, the engine
|
||||
* HuggingFace tokenizers matches Split patterns with, what each property contains. A pattern in a
|
||||
* tokenizer.json means whatever it means THERE, so that is the one definition this compiler has:
|
||||
* the general categories at Oniguruma's Unicode version, its `\s`, `\d` and `\w`, its scripts, and
|
||||
* its case-folding orbits for `(?i)`.
|
||||
* The tables are generated (tools/gen_tokenizer_ucd.cpp) by querying Oniguruma, the engine
|
||||
* HuggingFace tokenizers matches Split patterns with. A tokenizer.json pattern means what it means
|
||||
* there, so Oniguruma is the only definition used: its general categories at its Unicode version,
|
||||
* its `\s`, `\d` and `\w`, its scripts, and its case-folding orbits for `(?i)`.
|
||||
*/
|
||||
#pragma once
|
||||
#include <cstddef>
|
||||
|
||||
+11
-28
@@ -5,15 +5,14 @@
|
||||
|
||||
namespace rad {
|
||||
|
||||
/* Hangul, per UAX #15. 11172 syllables that would otherwise be 11172 table rows. */
|
||||
/* Hangul syllables are (de)composed arithmetically per UAX #15 instead of with 11172 table rows. */
|
||||
static constexpr uint32_t k_s_base = 0xAC00, k_l_base = 0x1100, k_v_base = 0x1161,
|
||||
k_t_base = 0x11A7, k_l_count = 19, k_v_count = 21, k_t_count = 28,
|
||||
k_n_count = k_v_count * k_t_count, /* 588 */
|
||||
k_s_count = k_l_count * k_n_count; /* 11172 */
|
||||
|
||||
uint32_t unorm_ccc(uint32_t cpt) {
|
||||
/* Binary search over runs. Class 0 is the common case and is not in the table, so the
|
||||
* miss path is the fast path -- which is what a run of ASCII wants. */
|
||||
/* Binary search over runs. Class 0, the common case, is not in the table. */
|
||||
size_t lo = 0, hi = k_ccc_n;
|
||||
while (lo < hi) {
|
||||
size_t mid = (lo + hi) / 2;
|
||||
@@ -35,9 +34,8 @@ static const DecompRow* decomp_row(uint32_t cpt) {
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
/* Canonical ordering: a stable sort of each run of non-starters by combining class. Written as
|
||||
* an insertion sort over the run rather than std::stable_sort because the runs are almost always
|
||||
* length 0 or 1 and the comparison is the whole cost. */
|
||||
/* Canonical ordering: a stable sort of each run of non-starters by combining class. Insertion
|
||||
* sort rather than std::stable_sort, because runs are almost always of length 0 or 1. */
|
||||
static void canonical_order(std::vector<uint32_t>& v) {
|
||||
for (size_t i = 1; i < v.size(); ++i) {
|
||||
const uint32_t ccc_i = unorm_ccc(v[i]);
|
||||
@@ -65,7 +63,7 @@ void unorm_decompose(std::vector<uint32_t>& cpts, bool compat) {
|
||||
continue;
|
||||
}
|
||||
const DecompRow* r = decomp_row(c);
|
||||
/* The pool holds fully-expanded sequences, so this is one lookup and not a fixed point.
|
||||
/* The pool holds fully expanded sequences, so one lookup suffices (no fixed-point loop).
|
||||
* A row with only a canonical decomposition serves the K forms too. */
|
||||
const uint32_t off = (compat && r && r->len_k) ? r->off_k : (r ? r->off_c : 0);
|
||||
const uint32_t len = (compat && r && r->len_k) ? r->len_k : (r ? r->len_c : 0);
|
||||
@@ -77,7 +75,7 @@ void unorm_decompose(std::vector<uint32_t>& cpts, bool compat) {
|
||||
}
|
||||
|
||||
static bool compose_pair(uint32_t a, uint32_t b, uint32_t* out) {
|
||||
/* Hangul first: arithmetic beats a lookup and it is the only algorithmic composition. */
|
||||
/* Hangul, the only algorithmic composition, is computed before the table lookup. */
|
||||
if (a - k_l_base < k_l_count && b - k_v_base < k_v_count) {
|
||||
*out = k_s_base + ((a - k_l_base) * k_v_count + (b - k_v_base)) * k_t_count;
|
||||
return true;
|
||||
@@ -106,16 +104,15 @@ void unorm_compose(std::vector<uint32_t>& cpts) {
|
||||
out.push_back(cpts[0]);
|
||||
size_t starter = 0; /* index in `out` of the last starter */
|
||||
uint32_t last_ccc = unorm_ccc(cpts[0]);
|
||||
/* A leading non-starter is not a starter and can never be a composition target; marking it
|
||||
* with a ccc that blocks everything is how the standard says to say that. */
|
||||
/* A leading non-starter is never a composition target (the standard treats it as blocked). */
|
||||
bool have_starter = (last_ccc == 0);
|
||||
|
||||
for (size_t i = 1; i < cpts.size(); ++i) {
|
||||
const uint32_t c = cpts[i];
|
||||
const uint32_t ccc = unorm_ccc(c);
|
||||
uint32_t composed = 0;
|
||||
/* Blocked when a character of equal or greater combining class already sits between the
|
||||
* starter and this one -- that is the whole of the blocking rule. */
|
||||
/* Blocked when a character of equal or greater combining class sits between the starter
|
||||
* and this one. */
|
||||
const bool blocked = (last_ccc != 0 && last_ccc >= ccc) || (ccc == 0 && last_ccc != 0);
|
||||
if (have_starter && !blocked && compose_pair(out[starter], c, &composed)) {
|
||||
out[starter] = composed;
|
||||
@@ -128,23 +125,9 @@ void unorm_compose(std::vector<uint32_t>& cpts) {
|
||||
cpts.swap(out);
|
||||
}
|
||||
|
||||
std::vector<uint32_t> unorm_nfd(const std::vector<uint32_t>& in) {
|
||||
std::vector<uint32_t> v = in; unorm_decompose(v, false); return v;
|
||||
}
|
||||
std::vector<uint32_t> unorm_nfkd(const std::vector<uint32_t>& in) {
|
||||
std::vector<uint32_t> v = in; unorm_decompose(v, true); return v;
|
||||
}
|
||||
std::vector<uint32_t> unorm_nfc(const std::vector<uint32_t>& in) {
|
||||
std::vector<uint32_t> v = in; unorm_decompose(v, false); unorm_compose(v); return v;
|
||||
}
|
||||
std::vector<uint32_t> unorm_nfkc(const std::vector<uint32_t>& in) {
|
||||
std::vector<uint32_t> v = in; unorm_decompose(v, true); unorm_compose(v); return v;
|
||||
}
|
||||
|
||||
std::string unorm_utf8(const std::string& in, bool compat, bool compose) {
|
||||
/* ASCII is in every normalisation form already, and it is most of every prompt. Skipping the
|
||||
* decode/normalise/encode round trip for it is the difference between normalisation costing
|
||||
* nothing and costing a pass over the prompt. */
|
||||
/* ASCII is unchanged by every normalisation form and is most of every prompt, so pure-ASCII
|
||||
* text skips the decode/normalise/encode round trip. */
|
||||
bool ascii = true;
|
||||
for (unsigned char ch : in) { if (ch >= 0x80) { ascii = false; break; } }
|
||||
if (ascii) return in;
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
/* unicode_norm.h -- NFC / NFD / NFKC / NFKD over codepoint vectors.
|
||||
*
|
||||
* The four forms are declared steps in a HuggingFace normaliser chain, so the tokeniser has to
|
||||
* be able to run them or a model that declares one gets silently different token boundaries --
|
||||
* the exact failure class spec §12 exists to remove. llama.cpp has no equivalent, so this is
|
||||
* ours; the tables it reads live in unicode_norm_data.cpp and say there how they were made.
|
||||
* The four forms are declared steps in a HuggingFace normaliser chain; a model that declares one
|
||||
* and is tokenised without it gets silently different token boundaries (spec §12). llama.cpp has
|
||||
* no equivalent. The tables live in unicode_norm_data.cpp, which documents how they were made.
|
||||
*/
|
||||
#pragma once
|
||||
#include <cstddef>
|
||||
@@ -30,18 +29,12 @@ extern const size_t k_ccc_n;
|
||||
|
||||
uint32_t unorm_ccc(uint32_t cpt);
|
||||
|
||||
/* In place, on codepoints. `compat` selects the K forms, `compose` selects the C forms, so the
|
||||
* four public names below are the four corners of that square. */
|
||||
/* In place, on codepoints. `compat` selects the K forms; following with unorm_compose gives the
|
||||
* C forms. */
|
||||
void unorm_decompose(std::vector<uint32_t>& cpts, bool compat);
|
||||
void unorm_compose(std::vector<uint32_t>& cpts);
|
||||
|
||||
std::vector<uint32_t> unorm_nfd (const std::vector<uint32_t>& in);
|
||||
std::vector<uint32_t> unorm_nfkd(const std::vector<uint32_t>& in);
|
||||
std::vector<uint32_t> unorm_nfc (const std::vector<uint32_t>& in);
|
||||
std::vector<uint32_t> unorm_nfkc(const std::vector<uint32_t>& in);
|
||||
|
||||
/* UTF-8 in, UTF-8 out. The tokeniser's step chain works on strings, so this is the form it
|
||||
* calls; the codepoint forms above are what the tests pin. */
|
||||
/* UTF-8 in and out: the form the tokeniser's string-based step chain calls. */
|
||||
std::string unorm_utf8(const std::string& in, bool compat, bool compose);
|
||||
|
||||
} /* namespace rad */
|
||||
Reference in new issue
Block a user