Archived
radiance 1.0.0
This commit is contained in:
commit
ae74a8aebf
616 files changed
+338692
No files matched your search
@@ -0,0 +1,238 @@
|
||||
#include "text/chat.h"
|
||||
#include "text/tokenizer.h"
|
||||
|
||||
/* The lifted headers live here and nowhere else in core/. See chat.h for why. */
|
||||
#include "llama/common/chat.h"
|
||||
/* For jinja::enable_debug only -- see RADIANCE_DEBUG_JINJA below. */
|
||||
#include "llama/common/jinja/runtime.h"
|
||||
#include "shim/log.h"
|
||||
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstdlib>
|
||||
|
||||
namespace rad {
|
||||
|
||||
using ojson = nlohmann::ordered_json;
|
||||
|
||||
|
||||
struct ChatTemplate::Impl {
|
||||
common_chat_templates_ptr tmpls;
|
||||
ChatCaps caps;
|
||||
std::string src;
|
||||
bool add_bos = false, add_eos = false;
|
||||
};
|
||||
|
||||
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. */
|
||||
return
|
||||
"{%- for message in messages -%}\n"
|
||||
" {{- '<|im_start|>' + message.role + '\n' + message.content + '<|im_end|>\n' -}}\n"
|
||||
"{%- endfor -%}\n"
|
||||
"{%- if add_generation_prompt -%}\n"
|
||||
" {{- '<|im_start|>assistant\n' -}}\n"
|
||||
"{%- endif -%}";
|
||||
}
|
||||
|
||||
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. */
|
||||
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. */
|
||||
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. */
|
||||
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. */
|
||||
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());
|
||||
impl_->tmpls.reset();
|
||||
return RAD_E_FORMAT;
|
||||
}
|
||||
if (!impl_->tmpls) return RAD_E_FORMAT;
|
||||
|
||||
impl_->src = src;
|
||||
impl_->add_bos = add_bos;
|
||||
impl_->add_eos = add_eos;
|
||||
|
||||
const std::map<std::string, bool> m = common_chat_templates_get_caps(impl_->tmpls.get());
|
||||
auto get = [&](const char* k, bool dflt) {
|
||||
auto it = m.find(k);
|
||||
return it == m.end() ? dflt : it->second;
|
||||
};
|
||||
impl_->caps.tools = get("supports_tools", true);
|
||||
impl_->caps.tool_calls = get("supports_tool_calls", true);
|
||||
impl_->caps.system_role = get("supports_system_role", true);
|
||||
impl_->caps.parallel_tool_calls = get("supports_parallel_tool_calls", true);
|
||||
impl_->caps.preserve_reasoning = get("supports_preserve_reasoning", false);
|
||||
impl_->caps.string_content = get("supports_string_content", true);
|
||||
impl_->caps.typed_content = get("supports_typed_content", false);
|
||||
impl_->caps.object_arguments = get("supports_object_arguments", false);
|
||||
|
||||
RAD_INFO("chat: template loaded (%zu bytes)%s; tools=%d tool_calls=%d system=%d thinking=%d",
|
||||
src.size(), fallback ? " [ChatML fallback]" : "",
|
||||
(int)impl_->caps.tools, (int)impl_->caps.tool_calls,
|
||||
(int)impl_->caps.system_role,
|
||||
(int)common_chat_templates_support_enable_thinking(impl_->tmpls.get()));
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
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. */
|
||||
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());
|
||||
}
|
||||
|
||||
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. */
|
||||
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. */
|
||||
static size_t json_depth(const ojson& root) {
|
||||
std::vector<std::pair<const ojson*, size_t>> todo{ { &root, 1 } };
|
||||
size_t deepest = 0;
|
||||
while (!todo.empty()) {
|
||||
const auto [j, d] = todo.back();
|
||||
todo.pop_back();
|
||||
if (!j->is_structured()) continue;
|
||||
deepest = std::max(deepest, d);
|
||||
for (const auto& c : *j) todo.push_back({ &c, d + 1 });
|
||||
}
|
||||
return deepest;
|
||||
}
|
||||
|
||||
int ChatTemplate::apply(const ojson& messages, const ojson& tools, const ChatOptions& opt,
|
||||
ChatPrompt* out) const {
|
||||
if (!ready()) {
|
||||
RAD_ERR("chat: apply() before load()");
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
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. */
|
||||
{
|
||||
const ojson schema = opt.json_schema.empty()
|
||||
? ojson()
|
||||
: ojson::parse(opt.json_schema, nullptr, /*allow_exceptions=*/false);
|
||||
if (json_depth(tools) > kMaxSchemaDepth || json_depth(schema) > kMaxSchemaDepth) {
|
||||
out->error = "a tool or response schema nests more than " +
|
||||
std::to_string(kMaxSchemaDepth) + " levels deep";
|
||||
RAD_WARN("chat: %s", out->error.c_str());
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
}
|
||||
|
||||
common_chat_templates_inputs in;
|
||||
try {
|
||||
in.messages = common_chat_msgs_parse_oaicompat(messages);
|
||||
if (!tools.is_null() && 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. */
|
||||
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");
|
||||
out->error = "this model's chat template declares no tool support";
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
|
||||
in.grammar = opt.grammar;
|
||||
in.json_schema = opt.json_schema;
|
||||
in.add_generation_prompt = opt.add_generation_prompt;
|
||||
in.use_jinja = true;
|
||||
in.parallel_tool_calls = opt.parallel_tool_calls;
|
||||
in.enable_thinking = opt.enable_thinking;
|
||||
in.chat_template_kwargs = opt.template_kwargs;
|
||||
in.add_bos = opt.add_bos || impl_->add_bos;
|
||||
in.add_eos = opt.add_eos || impl_->add_eos;
|
||||
in.reasoning_format = common_reasoning_format_from_name(opt.reasoning_format);
|
||||
|
||||
common_chat_params p;
|
||||
try {
|
||||
p = common_chat_templates_apply(impl_->tmpls.get(), in);
|
||||
} catch (const std::exception& e) {
|
||||
RAD_ERR("chat: template refused the request: %s", e.what());
|
||||
out->error = e.what();
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
|
||||
out->prompt = std::move(p.prompt);
|
||||
out->generation_prompt = std::move(p.generation_prompt);
|
||||
out->grammar = std::move(p.grammar);
|
||||
out->grammar_lazy = p.grammar_lazy;
|
||||
out->preserved_tokens = std::move(p.preserved_tokens);
|
||||
out->additional_stops = std::move(p.additional_stops);
|
||||
out->supports_thinking = p.supports_thinking;
|
||||
out->thinking_start_tag = std::move(p.thinking_start_tag);
|
||||
out->thinking_end_tag = std::move(p.thinking_end_tag);
|
||||
out->format = (int)p.format;
|
||||
out->parser = std::move(p.parser);
|
||||
out->grammar_triggers.clear();
|
||||
for (const common_grammar_trigger& t : p.grammar_triggers)
|
||||
out->grammar_triggers.push_back({ (int)t.type, t.value });
|
||||
|
||||
RAD_DEBUG("chat: rendered %zu bytes, format %s, grammar %zu bytes%s, %zu extra stop(s)",
|
||||
out->prompt.size(), common_chat_format_name(p.format),
|
||||
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. */
|
||||
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());
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
} /* namespace rad */
|
||||
@@ -0,0 +1,136 @@
|
||||
/* 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:
|
||||
*
|
||||
* 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.
|
||||
*
|
||||
* 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.
|
||||
*/
|
||||
#pragma once
|
||||
#include "rad_internal.h"
|
||||
|
||||
#include <map>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include <nlohmann/json_fwd.hpp>
|
||||
|
||||
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. */
|
||||
struct ChatCaps {
|
||||
bool tools = true;
|
||||
bool tool_calls = true;
|
||||
bool system_role = true;
|
||||
bool parallel_tool_calls = true;
|
||||
bool preserve_reasoning = false;
|
||||
bool string_content = true;
|
||||
bool typed_content = false;
|
||||
bool object_arguments = false;
|
||||
|
||||
};
|
||||
|
||||
struct ChatOptions {
|
||||
bool add_generation_prompt = true;
|
||||
bool enable_thinking = true;
|
||||
bool parallel_tool_calls = false;
|
||||
std::string tool_choice = "auto"; /* auto | none | required */
|
||||
std::string reasoning_format = "auto"; /* none | auto | deepseek | deepseek-legacy */
|
||||
std::string grammar; /* a user-supplied GBNF, or empty */
|
||||
std::string json_schema; /* response_format json_schema, or empty */
|
||||
bool add_bos = false;
|
||||
bool add_eos = false;
|
||||
std::map<std::string, std::string> template_kwargs;
|
||||
};
|
||||
|
||||
/* Everything the scheduler and the sampler need for one request, produced in one pass. */
|
||||
struct ChatPrompt {
|
||||
std::string prompt;
|
||||
std::string generation_prompt; /* the assistant prefix already inside `prompt` */
|
||||
|
||||
std::string grammar; /* GBNF; empty when the request is unconstrained */
|
||||
bool grammar_lazy = false;
|
||||
/* Triggers for a lazy grammar: the grammar starts applying only once one of these is seen.
|
||||
* Kept as (type, text) so the sampler can tell a literal word from a pattern. */
|
||||
struct GrammarTrigger { int type; std::string value; };
|
||||
std::vector<GrammarTrigger> grammar_triggers;
|
||||
|
||||
std::vector<std::string> preserved_tokens; /* must survive the sampler's bans */
|
||||
std::vector<std::string> additional_stops;
|
||||
|
||||
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. */
|
||||
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. */
|
||||
std::string error;
|
||||
};
|
||||
|
||||
class ChatTemplate {
|
||||
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. */
|
||||
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. */
|
||||
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. */
|
||||
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. */
|
||||
static const char* chatml_source();
|
||||
|
||||
private:
|
||||
struct Impl;
|
||||
std::unique_ptr<Impl> impl_;
|
||||
};
|
||||
|
||||
} /* namespace rad */
|
||||
@@ -0,0 +1,712 @@
|
||||
#include "text/chatfmt.h"
|
||||
#include "text/chat.h"
|
||||
|
||||
#include "rad_builder.h"
|
||||
|
||||
/* The analyser and the grammar builder, at load and admission time only -- never while a reply
|
||||
* is being read. */
|
||||
#include "llama/common/chat.h"
|
||||
#include "llama/common/chat-auto-parser.h"
|
||||
#include "llama/common/json-schema-to-grammar.h"
|
||||
#include "shim/log.h"
|
||||
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstddef>
|
||||
#include <cstring>
|
||||
#include <functional>
|
||||
#include <map>
|
||||
#include <set>
|
||||
|
||||
namespace rad {
|
||||
|
||||
using ojson = nlohmann::ordered_json;
|
||||
|
||||
namespace {
|
||||
|
||||
bool is_ws(unsigned char c) { return c == ' ' || (c >= '\t' && c <= '\r'); }
|
||||
|
||||
std::string trim_ws(const std::string& s) {
|
||||
size_t a = 0, b = s.size();
|
||||
while (a < b && is_ws((unsigned char)s[a])) ++a;
|
||||
while (b > a && is_ws((unsigned char)s[b - 1])) --b;
|
||||
return s.substr(a, b - a);
|
||||
}
|
||||
|
||||
/* `inner` occurs inside `outer` somewhere other than at its start. */
|
||||
bool occurs_inside(const std::string& inner, const std::string& outer) {
|
||||
return !inner.empty() && outer.size() > inner.size() && outer.find(inner, 1) != std::string::npos;
|
||||
}
|
||||
|
||||
bool starts_with(const std::string& s, const std::string& p) {
|
||||
return s.size() >= p.size() && s.compare(0, p.size(), p) == 0;
|
||||
}
|
||||
|
||||
std::string show(const std::string& s) { return nlohmann::json(s).dump(); }
|
||||
|
||||
} /* namespace */
|
||||
|
||||
/* ================================================================== 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;
|
||||
};
|
||||
|
||||
if (!f.reasoning_open.empty() && f.reasoning_close.empty())
|
||||
return no("reasoning_open " + show(f.reasoning_open) + " has no reasoning_close");
|
||||
if (f.has_reasoning() && trim_ws(f.reasoning_close).empty())
|
||||
return no("reasoning_close is only whitespace");
|
||||
if ((uint32_t)f.reasoning_in_prompt > (uint32_t)ChatThink::Never)
|
||||
return no("reasoning_in_prompt is not a RAD_CHAT_THINK_* value");
|
||||
|
||||
if (!f.has_tools()) {
|
||||
for (const std::string* s : { &f.section_open, &f.section_close, &f.call_separator,
|
||||
&f.call_open, &f.call_close, &f.name_suffix, &f.call_end,
|
||||
&f.arg_prefix, &f.arg_name_suffix, &f.arg_value_prefix,
|
||||
&f.arg_value_suffix })
|
||||
if (!s->empty()) return no("tool-call delimiters are set but name_prefix is empty");
|
||||
if (!f.reasoning_breaks.empty()) return no("reasoning_breaks without tool calls");
|
||||
if (!f.triggers.empty()) return no("grammar triggers without tool calls");
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
if (!f.section_open.empty() || !f.section_close.empty())
|
||||
return no("a section around all calls (section_open/section_close) is not read by the "
|
||||
"streaming parser");
|
||||
if (!f.call_separator.empty())
|
||||
return no("a separator between calls (call_separator " + show(f.call_separator) +
|
||||
") is not read by the streaming parser; tagged calls separate on whitespace");
|
||||
if (f.call_open.empty() && !f.call_close.empty())
|
||||
return no("call_close without call_open");
|
||||
if (f.name_suffix.empty() || trim_ws(f.name_suffix).empty())
|
||||
return no("name_suffix must end the function name with something besides whitespace");
|
||||
if (is_ws((unsigned char)f.name_suffix[0]))
|
||||
return no("name_suffix " + show(f.name_suffix) + " may not begin with whitespace");
|
||||
if (f.call_end.empty()) return no("call_end is empty: a call must close with its own tag");
|
||||
if (f.arg_prefix.empty()) return no("arg_prefix is empty");
|
||||
if (f.arg_value_suffix.empty()) return no("arg_value_suffix is empty");
|
||||
if (f.arg_name_suffix.empty() && f.arg_value_prefix.empty())
|
||||
return no("nothing ends an argument name: arg_name_suffix and arg_value_prefix are empty");
|
||||
if (!f.arg_name_suffix.empty() && !f.arg_value_prefix.empty())
|
||||
return no("arg_name_suffix and arg_value_prefix are both set; the streaming parser reads "
|
||||
"one delimiter between an argument's name and its value");
|
||||
if (f.string_value != ChatValue::Raw && f.string_value != ChatValue::Cdata)
|
||||
return no("string_value must be RAD_CHAT_VALUE_RAW or RAD_CHAT_VALUE_CDATA");
|
||||
if ((uint32_t)f.other_value > (uint32_t)ChatValue::Json)
|
||||
return no("other_value is not a RAD_CHAT_VALUE_* value");
|
||||
|
||||
/* A wrapped format's content is scanned for the wrapper's core and for name_prefix alone,
|
||||
* which opens a call written without its wrapper; the two must not be confusable. */
|
||||
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))
|
||||
return no("call_open " + show(f.call_open) + " and name_prefix " +
|
||||
show(f.name_prefix) + " cannot be told apart");
|
||||
}
|
||||
const std::string opener = f.call_open.empty() ? f.name_prefix : f.call_open;
|
||||
for (const std::string& b : f.reasoning_breaks)
|
||||
if (b != opener)
|
||||
return no("reasoning break " + show(b) + " is not the call opener " + show(opener));
|
||||
if (!f.reasoning_breaks.empty() && !f.has_reasoning())
|
||||
return no("reasoning_breaks without a reasoning block");
|
||||
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. */
|
||||
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))
|
||||
return no("reasoning break " + show(b) + " overlaps reasoning_close " +
|
||||
show(close));
|
||||
}
|
||||
/* 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. */
|
||||
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))
|
||||
return no("arg_prefix " + show(f.arg_prefix) + " and call_end " + show(f.call_end) +
|
||||
" cannot be told apart");
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ================================================================== the plugin's declaration */
|
||||
|
||||
int chat_format_from_abi(const RadChatFormat* in, ChatFormat* out, std::string* why) {
|
||||
if (!in || !out) {
|
||||
if (why) *why = "no format";
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (in->struct_size < offsetof(RadChatFormat, name) + sizeof(in->name)) {
|
||||
if (why) *why = "struct_size " + std::to_string(in->struct_size) + " is too small";
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
RadChatFormat c;
|
||||
std::memset(&c, 0, sizeof c);
|
||||
std::memcpy(&c, in, std::min<size_t>(in->struct_size, sizeof c));
|
||||
|
||||
auto s = [](const char* p) { return p ? std::string(p) : std::string(); };
|
||||
auto list = [](const char* const* v, uint32_t n, std::vector<std::string>* o) {
|
||||
o->clear();
|
||||
for (uint32_t i = 0; v && i < n; ++i)
|
||||
if (v[i]) o->emplace_back(v[i]);
|
||||
};
|
||||
|
||||
ChatFormat f;
|
||||
f.name = s(c.name);
|
||||
f.reasoning_open = s(c.reasoning_open);
|
||||
f.reasoning_close = s(c.reasoning_close);
|
||||
list(c.reasoning_breaks, c.n_reasoning_breaks, &f.reasoning_breaks);
|
||||
f.reasoning_in_prompt = (ChatThink)c.reasoning_in_prompt;
|
||||
f.section_open = s(c.section_open);
|
||||
f.section_close = s(c.section_close);
|
||||
f.call_separator = s(c.call_separator);
|
||||
f.call_open = s(c.call_open);
|
||||
f.call_close = s(c.call_close);
|
||||
f.name_prefix = s(c.name_prefix);
|
||||
f.name_suffix = s(c.name_suffix);
|
||||
f.call_end = s(c.call_end);
|
||||
f.arg_prefix = s(c.arg_prefix);
|
||||
f.arg_name_suffix = s(c.arg_name_suffix);
|
||||
f.arg_value_prefix = s(c.arg_value_prefix);
|
||||
f.arg_value_suffix = s(c.arg_value_suffix);
|
||||
f.string_value = (ChatValue)c.string_value;
|
||||
f.other_value = (ChatValue)c.other_value;
|
||||
f.value_newlines = c.value_newlines != 0;
|
||||
list(c.triggers, c.n_triggers, &f.triggers);
|
||||
*out = std::move(f);
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ================================================================== the template's format */
|
||||
|
||||
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;
|
||||
tools_refused->clear();
|
||||
const std::string src = jinja.empty() ? std::string(ChatTemplate::chatml_source()) : jinja;
|
||||
|
||||
ChatFormat f;
|
||||
f.name = "template";
|
||||
try {
|
||||
common_chat_template tmpl(src, bos, eos);
|
||||
|
||||
/* A template llama.cpp reads with a hand-written handler is one the analysis never
|
||||
* describes, and its markers would be read as if it had. */
|
||||
autoparser::generation_params probe;
|
||||
probe.messages = ojson::array({ ojson{ { "role", "user" }, { "content", "hi" } } });
|
||||
probe.add_generation_prompt = true;
|
||||
if (common_chat_try_specialized_template(tmpl, src, probe)) {
|
||||
*why = "the chat template is one llama.cpp reads with a hand-written handler, whose "
|
||||
"reply format the template analysis does not describe";
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
|
||||
autoparser::autoparser a;
|
||||
a.analyze_template(tmpl);
|
||||
|
||||
if (a.reasoning.mode != autoparser::reasoning_mode::NONE && !a.reasoning.end.empty()) {
|
||||
f.reasoning_open = a.reasoning.start;
|
||||
f.reasoning_close = a.reasoning.end;
|
||||
}
|
||||
if (a.content.mode != autoparser::content_mode::PLAIN) {
|
||||
*why = "the template wraps its answer in content markers, which the streaming parser "
|
||||
"does not read";
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
|
||||
const auto& t = a.tools;
|
||||
const bool calls = t.format.mode != autoparser::tool_format::NONE &&
|
||||
a.jinja_caps.supports_tool_calls;
|
||||
std::string refuse;
|
||||
if (calls) {
|
||||
if (t.format.mode == autoparser::tool_format::JSON_NATIVE)
|
||||
refuse = "the template writes each call as a JSON object";
|
||||
else if (t.format.mode == autoparser::tool_format::TAG_WITH_JSON)
|
||||
refuse = "the template writes a call's arguments as one JSON object inside a tag";
|
||||
else if (t.call_id.pos != autoparser::call_id_position::NONE)
|
||||
refuse = "the template writes a call id";
|
||||
else if (!t.arguments.start.empty() || !t.arguments.end.empty())
|
||||
refuse = "the template wraps a call's arguments in " + show(t.arguments.start) +
|
||||
" .. " + show(t.arguments.end);
|
||||
else if (!t.arguments.separator.empty())
|
||||
refuse = "the template separates arguments with " + show(t.arguments.separator);
|
||||
}
|
||||
if (calls && refuse.empty()) {
|
||||
ChatFormat c = f;
|
||||
c.section_open = t.format.section_start;
|
||||
c.section_close = t.format.section_end;
|
||||
c.call_open = t.format.per_call_start;
|
||||
c.call_close = t.format.per_call_end;
|
||||
c.name_prefix = t.function.name_prefix;
|
||||
c.name_suffix = t.function.name_suffix;
|
||||
c.call_end = t.function.close;
|
||||
c.arg_prefix = t.arguments.name_prefix;
|
||||
c.arg_name_suffix = t.arguments.name_suffix;
|
||||
c.arg_value_prefix = t.arguments.value_prefix;
|
||||
c.arg_value_suffix = t.arguments.value_suffix;
|
||||
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. */
|
||||
const std::string& marker = !t.format.section_start.empty() ? t.format.section_start
|
||||
: t.format.per_call_start;
|
||||
if (!marker.empty()) {
|
||||
c.triggers.push_back(marker);
|
||||
if (c.has_reasoning()) c.reasoning_breaks.push_back(marker);
|
||||
}
|
||||
std::string bad;
|
||||
if (chat_format_check(c, &bad) == RAD_OK) f = std::move(c);
|
||||
else refuse = bad;
|
||||
}
|
||||
if (!refuse.empty()) *tools_refused = refuse;
|
||||
} catch (const std::exception& e) {
|
||||
*why = std::string("the chat template could not be analysed: ") + e.what();
|
||||
return RAD_E_FORMAT;
|
||||
}
|
||||
*out = std::move(f);
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
std::string chat_format_describe(const ChatFormat& f) {
|
||||
std::string s = f.name + ":";
|
||||
if (f.has_reasoning())
|
||||
s += " reasoning " + show(f.reasoning_open) + ".." + show(f.reasoning_close);
|
||||
else
|
||||
s += " no reasoning";
|
||||
if (f.has_tools()) {
|
||||
s += "; calls " + show(f.call_open) + show(f.name_prefix) + "NAME" + show(f.name_suffix) +
|
||||
" " + show(f.arg_prefix) + "ARG" + show(f.arg_name_suffix) + show(f.arg_value_prefix) +
|
||||
"VALUE" + show(f.arg_value_suffix) + " " + show(f.call_end) + show(f.call_close);
|
||||
if (!f.triggers.empty()) {
|
||||
s += "; grammar on";
|
||||
for (const std::string& t : f.triggers) s += " " + show(t);
|
||||
} else {
|
||||
s += "; no grammar";
|
||||
}
|
||||
} else {
|
||||
s += "; no tool calls";
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
std::vector<std::string> chat_format_markers(const ChatFormat& f) {
|
||||
std::vector<std::string> out;
|
||||
for (const std::string* s : { &f.reasoning_open, &f.reasoning_close, &f.section_open,
|
||||
&f.section_close, &f.call_open, &f.call_close, &f.name_prefix,
|
||||
&f.name_suffix, &f.call_end, &f.arg_prefix, &f.arg_name_suffix,
|
||||
&f.arg_value_prefix, &f.arg_value_suffix }) {
|
||||
const std::string t = trim_ws(*s);
|
||||
if (!t.empty() && std::find(out.begin(), out.end(), t) == out.end()) out.push_back(t);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/* ================================================================== 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. */
|
||||
namespace {
|
||||
|
||||
struct G {
|
||||
enum K : uint8_t { Eps, Lit, Seq, Alt, Rep, Leaf, Wrap } k = Eps;
|
||||
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{}; }
|
||||
G lit(const std::string& s) { G g; g.k = G::Lit; g.s = s; return g; }
|
||||
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. */
|
||||
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;
|
||||
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));
|
||||
else g.kids.push_back(std::move(p));
|
||||
}
|
||||
return g;
|
||||
}
|
||||
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;
|
||||
}
|
||||
G opt(G child) { return rep(std::move(child), 0, 1); }
|
||||
|
||||
const G& effective(const G& g) { return g.k == G::Wrap ? effective(g.kids[0]) : g; }
|
||||
|
||||
std::string render(const G& g);
|
||||
|
||||
std::string render_rep_suffix(int min, int max) {
|
||||
if (min == 0 && max == 1) return "?";
|
||||
if (min == 0 && max == -1) return "*";
|
||||
if (min == 1 && max == -1) return "+";
|
||||
if (max == -1) return "{" + std::to_string(min) + ",}";
|
||||
if (min == max) return min == 1 ? "" : "{" + std::to_string(min) + "}";
|
||||
return "{" + std::to_string(min) + "," + std::to_string(max) + "}";
|
||||
}
|
||||
|
||||
std::string render(const G& g) {
|
||||
switch (g.k) {
|
||||
case G::Eps: return "";
|
||||
case G::Lit: return gbnf_format_literal(g.s);
|
||||
case G::Leaf: return g.s;
|
||||
case G::Wrap: return render(g.kids[0]);
|
||||
case G::Seq: {
|
||||
std::string s;
|
||||
for (const G& c : g.kids) {
|
||||
const std::string r = render(c);
|
||||
if (r.empty()) continue;
|
||||
if (!s.empty()) s += " ";
|
||||
const G& e = effective(c);
|
||||
if (e.k == G::Seq || e.k == G::Alt) s += "(" + r + ")";
|
||||
else s += r;
|
||||
}
|
||||
return s;
|
||||
}
|
||||
case G::Alt: {
|
||||
std::string s;
|
||||
for (const G& c : g.kids) {
|
||||
if (!s.empty()) s += " | ";
|
||||
const std::string r = render(c);
|
||||
if (effective(c).k == G::Alt) s += "(" + r + ")";
|
||||
else s += r;
|
||||
}
|
||||
return s;
|
||||
}
|
||||
case G::Rep: {
|
||||
std::string r = render(g.kids[0]);
|
||||
const G& e = effective(g.kids[0]);
|
||||
if (e.k == G::Seq || e.k == G::Alt) r = "(" + r + ")";
|
||||
return r + render_rep_suffix(g.min, g.max);
|
||||
}
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
/* A character in a GBNF class, escaped as the vendored generator escapes it. */
|
||||
std::string class_char(uint32_t c) {
|
||||
if (c == '-' || c == ']' || c == '[' || c == '\\') return std::string("\\") + (char)c;
|
||||
if (c == '\n') return "\\n";
|
||||
if (c == '\t') return "\\t";
|
||||
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]; }
|
||||
return s;
|
||||
}
|
||||
|
||||
std::vector<uint32_t> codepoints(const std::string& s) {
|
||||
std::vector<uint32_t> out;
|
||||
for (size_t i = 0; i < s.size();) {
|
||||
const unsigned char c = (unsigned char)s[i];
|
||||
uint32_t cp = c;
|
||||
size_t n = 1;
|
||||
if (c >= 0xF0) { cp = c & 0x07; n = 4; }
|
||||
else if (c >= 0xE0) { cp = c & 0x0F; n = 3; }
|
||||
else if (c >= 0xC0) { cp = c & 0x1F; n = 2; }
|
||||
if (i + n > s.size()) break;
|
||||
for (size_t k = 1; k < n; ++k) cp = (cp << 6) | ((unsigned char)s[i + k] & 0x3F);
|
||||
out.push_back(cp);
|
||||
i += n;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/* A rule name as the vendored builder spells it: every run of characters outside
|
||||
* [a-zA-Z0-9-] becomes one '-'. */
|
||||
std::string rule_name(const std::string& s) {
|
||||
std::string out;
|
||||
bool run = false;
|
||||
for (char ch : s) {
|
||||
const bool ok = (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') ||
|
||||
(ch >= '0' && ch <= '9') || ch == '-';
|
||||
if (ok) { out += ch; run = false; }
|
||||
else if (!run) { out += '-'; run = true; }
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
std::string utf8(const std::vector<uint32_t>& cps) {
|
||||
std::string s;
|
||||
for (uint32_t c : cps) {
|
||||
if (c < 0x80) s += (char)c;
|
||||
else if (c < 0x800) { s += (char)(0xC0 | (c >> 6)); s += (char)(0x80 | (c & 0x3F)); }
|
||||
else if (c < 0x10000) {
|
||||
s += (char)(0xE0 | (c >> 12)); s += (char)(0x80 | ((c >> 6) & 0x3F));
|
||||
s += (char)(0x80 | (c & 0x3F));
|
||||
} else {
|
||||
s += (char)(0xF0 | (c >> 18)); s += (char)(0x80 | ((c >> 12) & 0x3F));
|
||||
s += (char)(0x80 | ((c >> 6) & 0x3F)); s += (char)(0x80 | (c & 0x3F));
|
||||
}
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
/* "Any text not containing one of these", as a repetition over the trie of the delimiters:
|
||||
* for each proper prefix, that prefix followed by a character that does not continue it. */
|
||||
std::string until_pattern(const std::vector<std::string>& delims) {
|
||||
if (delims.empty()) return ".*";
|
||||
struct Node { std::map<uint32_t, size_t> kids; bool word = false; };
|
||||
std::vector<Node> t(1);
|
||||
for (const std::string& d : delims) {
|
||||
size_t cur = 0;
|
||||
for (uint32_t c : codepoints(d)) {
|
||||
auto it = t[cur].kids.find(c);
|
||||
if (it == t[cur].kids.end()) {
|
||||
t.emplace_back();
|
||||
t[cur].kids[c] = t.size() - 1;
|
||||
cur = t.size() - 1;
|
||||
} else {
|
||||
cur = it->second;
|
||||
}
|
||||
}
|
||||
t[cur].word = true;
|
||||
}
|
||||
std::string pattern;
|
||||
std::vector<uint32_t> prefix;
|
||||
std::function<void(size_t)> walk = [&](size_t n) {
|
||||
if (!t[n].word && !t[n].kids.empty()) {
|
||||
std::string cls;
|
||||
for (const auto& kv : t[n].kids) cls += class_char(kv.first);
|
||||
if (!pattern.empty()) pattern += " | ";
|
||||
if (!prefix.empty()) pattern += gbnf_format_literal(utf8(prefix)) + " [^" + cls + "]";
|
||||
else pattern += "[^" + cls + "]";
|
||||
}
|
||||
for (const auto& kv : t[n].kids) {
|
||||
prefix.push_back(kv.first);
|
||||
walk(kv.second);
|
||||
prefix.pop_back();
|
||||
}
|
||||
};
|
||||
walk(0);
|
||||
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. */
|
||||
void add_json_rules(const common_grammar_builder& b) {
|
||||
b.add_rule("json-array", "\"[\" space (\"]\" | json-value (\",\" space json-value)* space "
|
||||
"\"]\") space");
|
||||
b.add_rule("json-bool", "(\"true\" | \"false\") space");
|
||||
b.add_rule("json-null", "\"null\" space");
|
||||
b.add_rule("json-number", "\"-\"? (\"0\" | [1-9] [0-9]*) (\".\" [0-9]+)? ((\"e\" | \"E\") "
|
||||
"[+-]? [0-9]+)? space");
|
||||
b.add_rule("json-object", "\"{\" space (\"}\" | json-string space \":\" space json-value "
|
||||
"(space \",\" space json-string space \":\" space json-value)* "
|
||||
"space \"}\") space");
|
||||
b.add_rule("json-string", "\"\\\"\" ( [^\"\\\\] | \"\\\\\" ( [\"\\\\/ bfnrt] | \"u\" "
|
||||
"[0-9a-fA-F]{4} ) )* \"\\\"\" space");
|
||||
b.add_rule("json-value", "json-object | json-array | json-string | json-number | json-bool | "
|
||||
"json-null");
|
||||
}
|
||||
|
||||
G optspace(const std::string& tag) {
|
||||
size_t a = 0, b = tag.size();
|
||||
while (a < b && is_ws((unsigned char)tag[a])) ++a;
|
||||
while (b > a && is_ws((unsigned char)tag[b - 1])) --b;
|
||||
std::vector<G> parts{ eps() };
|
||||
for (size_t i = 0; i < a; ++i) parts.push_back(opt(lit(std::string(1, tag[i]))));
|
||||
parts.push_back(lit(tag.substr(a, b - a)));
|
||||
for (size_t i = b; i < tag.size(); ++i) parts.push_back(opt(lit(std::string(1, tag[i]))));
|
||||
return seq(std::move(parts));
|
||||
}
|
||||
|
||||
/* The reasoning block as the vendored generator builds it. */
|
||||
G reasoning_expr(const ChatFormat& f, const std::vector<std::string>& breaks) {
|
||||
const std::string end = trim_ws(f.reasoning_close);
|
||||
if (!breaks.empty()) {
|
||||
std::vector<std::string> stops{ end };
|
||||
stops.insert(stops.end(), breaks.begin(), breaks.end());
|
||||
G unclosed = seq({ wrap(leaf(until_pattern(stops))), eps() });
|
||||
G closed = seq({ wrap(leaf(until_pattern({ end }))), optspace(f.reasoning_close) });
|
||||
if (!f.reasoning_open.empty())
|
||||
return opt(alt({ seq({ optspace(f.reasoning_open), unclosed }),
|
||||
seq({ optspace(f.reasoning_open), closed }) }));
|
||||
return opt(alt({ unclosed, closed }));
|
||||
}
|
||||
if (!f.reasoning_open.empty())
|
||||
return opt(seq({ optspace(f.reasoning_open), wrap(leaf(until_pattern({ end }))),
|
||||
optspace(f.reasoning_close) }));
|
||||
return opt(seq({ wrap(leaf(until_pattern({ end }))), optspace(f.reasoning_close) }));
|
||||
}
|
||||
|
||||
} /* namespace */
|
||||
|
||||
int chat_format_grammar(const ChatFormat& f, const ChatGrammarRequest& req, ChatGrammar* out,
|
||||
std::string* why) {
|
||||
*out = ChatGrammar{};
|
||||
const ojson none;
|
||||
const ojson& tools = req.tools ? *req.tools : none;
|
||||
const bool has_tools = f.has_tools() && tools.is_array() && !tools.empty();
|
||||
const bool has_rf = req.json_schema && req.json_schema->is_object() && !req.json_schema->empty();
|
||||
if (!has_rf && !(has_tools && !f.triggers.empty())) return RAD_OK;
|
||||
|
||||
const std::string opener = f.call_open.empty() ? f.name_prefix : f.call_open;
|
||||
std::vector<std::string> breaks;
|
||||
if (has_tools && req.extract_reasoning && f.has_reasoning()) breaks = f.reasoning_breaks;
|
||||
|
||||
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;
|
||||
const auto& fn = tool.at("function");
|
||||
auto schema = fn.contains("parameters") ? fn.at("parameters") : ojson::object();
|
||||
b.resolve_refs(schema);
|
||||
}
|
||||
if (has_rf) {
|
||||
auto schema = *req.json_schema;
|
||||
b.resolve_refs(schema);
|
||||
}
|
||||
|
||||
if (has_rf) {
|
||||
/* The whole reply: what follows the generation prompt, the reasoning block, and
|
||||
* the document, fenced or not. */
|
||||
b.add_rule("response-format", b.add_schema("response-format-schema",
|
||||
*req.json_schema));
|
||||
add_json_rules(b);
|
||||
std::string gp = req.generation_prompt;
|
||||
if (f.has_reasoning() && !f.reasoning_open.empty()) {
|
||||
const size_t at = gp.find(f.reasoning_open);
|
||||
if (at != std::string::npos) gp = gp.substr(0, at);
|
||||
}
|
||||
std::vector<G> root{ gp.empty() ? eps() : lit(gp), space() };
|
||||
if (f.has_reasoning() && req.extract_reasoning) root.push_back(reasoning_expr(f, breaks));
|
||||
root.push_back(space());
|
||||
root.push_back(alt({ seq({ lit("```json"), space(), rule_ref("response-format"), space(),
|
||||
lit("```") }),
|
||||
rule_ref("response-format") }));
|
||||
b.add_rule("root", render(seq(std::move(root))));
|
||||
return;
|
||||
}
|
||||
|
||||
/* The lazy call grammar: only what follows a trigger. */
|
||||
const std::string name_end = f.arg_name_suffix.empty() ? f.arg_value_prefix
|
||||
: f.arg_name_suffix;
|
||||
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;
|
||||
const auto& fn = tool.at("function");
|
||||
const std::string name = fn.at("name");
|
||||
auto params = fn.contains("parameters") ? fn.at("parameters") : ojson::object();
|
||||
const auto properties = params.contains("properties") ? params.at("properties")
|
||||
: ojson::object();
|
||||
std::set<std::string> required;
|
||||
if (params.contains("required")) params.at("required").get_to(required);
|
||||
common_schema_info info;
|
||||
info.resolve_refs(params);
|
||||
|
||||
std::vector<G> req_arms, opt_arms;
|
||||
for (const auto& [pname, pschema] : properties.items()) {
|
||||
G value;
|
||||
if (f.other_value != ChatValue::Json || info.resolves_to_string(pschema)) {
|
||||
value = wrap(rule_ref("until-suffix"));
|
||||
} else {
|
||||
typed = true;
|
||||
const std::string sch = b.add_schema(
|
||||
"tool-" + name + "-arg-" + pname + "-schema", pschema);
|
||||
value = alt({ seq({ wrap(leaf(sch)), space() }), wrap(rule_ref("until-suffix")) });
|
||||
}
|
||||
G arm = wrap(seq({ wrap(seq({ lit(f.arg_prefix), wrap(lit(pname)),
|
||||
lit(f.arg_name_suffix) })),
|
||||
lit(f.arg_value_prefix), value,
|
||||
wrap(lit(f.arg_value_suffix)) }));
|
||||
const std::string rule = rule_name("tool-" + name + "-arg-" + pname);
|
||||
b.add_rule(rule, render(arm));
|
||||
(required.count(pname) ? req_arms : opt_arms).push_back(rule_ref(rule));
|
||||
}
|
||||
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. */
|
||||
if (!any.empty()) {
|
||||
G arm = wrap(seq({ wrap(seq({ lit(f.arg_prefix),
|
||||
wrap(leaf(until_pattern({ name_end }))),
|
||||
lit(f.arg_name_suffix) })),
|
||||
lit(f.arg_value_prefix), wrap(rule_ref("until-suffix")),
|
||||
wrap(lit(f.arg_value_suffix)) }));
|
||||
const std::string rule = rule_name("tool-" + name + "-arg-undeclared");
|
||||
b.add_rule(rule, render(arm));
|
||||
any.push_back(rule_ref(rule));
|
||||
}
|
||||
G any_arg = alt(any);
|
||||
G args = eps();
|
||||
if (!req_arms.empty()) args = seq({ any_arg, rep(seq({ space(), any_arg }), 0, -1) });
|
||||
else if (!opt_arms.empty()) args = seq({ eps(), rep(seq({ space(), any_arg }), 0, -1) });
|
||||
|
||||
G open = wrap(seq({ lit(f.name_prefix), wrap(lit(name)), lit(f.name_suffix) }));
|
||||
G func = seq({ open, eps(), space(), args, space(), wrap(lit(f.call_end)) });
|
||||
b.add_rule(rule_name("tool-" + name), render(func));
|
||||
choices.push_back(rule_ref(rule_name("tool-" + name)));
|
||||
}
|
||||
if (typed) add_json_rules(b);
|
||||
if (!choices.empty()) b.add_rule("until-suffix", until_pattern({ f.arg_value_suffix }));
|
||||
|
||||
G choice = alt(choices);
|
||||
G calls;
|
||||
if (!f.call_open.empty()) {
|
||||
G wrapped = seq({ lit(f.call_open), space(), choice, space(), lit(f.call_close) });
|
||||
calls = req.parallel_tool_calls
|
||||
? seq({ wrapped, rep(seq({ space(), wrapped }), 0, -1), space() })
|
||||
: seq({ wrapped, space() });
|
||||
} else {
|
||||
G next = seq({ space(), opt(wrap(leaf(until_pattern({ opener })))), choice });
|
||||
calls = req.parallel_tool_calls
|
||||
? seq({ lit(""), space(), choice, rep(next, 0, -1), space(), lit("") })
|
||||
: seq({ lit(""), space(), choice, space(), lit("") });
|
||||
}
|
||||
b.add_rule("tool-call", render(calls));
|
||||
b.add_rule("root", "tool-call");
|
||||
});
|
||||
} catch (const std::exception& e) {
|
||||
if (why) *why = e.what();
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
out->lazy = !has_rf;
|
||||
if (out->lazy) out->trigger_words = f.triggers;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
} /* namespace rad */
|
||||
@@ -0,0 +1,175 @@
|
||||
/* 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.
|
||||
*
|
||||
* 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.
|
||||
* 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;
|
||||
* 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.
|
||||
*
|
||||
* THE FAMILY THIS DESCRIBES is the tagged one, which covers every model this engine serves:
|
||||
*
|
||||
* 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.
|
||||
*
|
||||
* The analyser also recognises formats outside this family (a JSON object per call, JSON
|
||||
* arguments inside a tag, 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. */
|
||||
#pragma once
|
||||
#include "rad_internal.h"
|
||||
|
||||
#include <nlohmann/json_fwd.hpp>
|
||||
|
||||
#include <cstdint>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
struct RadChatFormat;
|
||||
|
||||
namespace rad {
|
||||
|
||||
/* How a value is written between its delimiters. The numbering is the ABI's (RAD_CHAT_VALUE_*). */
|
||||
enum class ChatValue : uint32_t {
|
||||
Raw = 0, /* the text, verbatim */
|
||||
Cdata = 1, /* the text, unless wrapped in <![CDATA[ ]]>, which is punctuation and removed */
|
||||
Json = 2, /* a JSON value; text that does not parse as one is taken raw */
|
||||
};
|
||||
|
||||
/* 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. */
|
||||
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 */
|
||||
};
|
||||
|
||||
struct ChatFormat {
|
||||
std::string name; /* for logs: "plugin:<arch>" or "template" */
|
||||
|
||||
/* ------------------------------------------------------------------ reasoning
|
||||
* A block runs from `reasoning_open` to `reasoning_close`. Whitespace at either end of either
|
||||
* tag is optional when matching, so "<think>\n" also matches "<think>". An empty close means
|
||||
* the format has no reasoning block. An empty open with a close means the reply starts in one
|
||||
* 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. */
|
||||
std::vector<std::string> reasoning_breaks;
|
||||
ChatThink reasoning_in_prompt = ChatThink::FromPrompt;
|
||||
|
||||
/* ------------------------------------------------------------------ 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 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). */
|
||||
std::string call_open, call_close;
|
||||
std::string name_prefix, name_suffix; /* "<function=", ">\n" */
|
||||
std::string call_end; /* "</function>\n" */
|
||||
|
||||
std::string arg_prefix; /* "<parameter=" */
|
||||
std::string arg_name_suffix; /* ">\n" (MiniCPM: empty, the value prefix ends it) */
|
||||
std::string arg_value_prefix; /* "" (MiniCPM: "\">") */
|
||||
std::string arg_value_suffix; /* "</parameter>\n" */
|
||||
|
||||
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. */
|
||||
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. */
|
||||
std::vector<std::string> triggers;
|
||||
|
||||
bool has_reasoning() const { return !reasoning_close.empty(); }
|
||||
bool has_tools() const { return !name_prefix.empty(); }
|
||||
};
|
||||
|
||||
/* 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. */
|
||||
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. */
|
||||
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. */
|
||||
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);
|
||||
|
||||
/* Human-readable one-liner for the startup log. */
|
||||
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 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. */
|
||||
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" */
|
||||
};
|
||||
|
||||
struct ChatGrammar {
|
||||
std::string text; /* empty when the request is unconstrained */
|
||||
bool lazy = false;
|
||||
std::vector<std::string> trigger_words;
|
||||
};
|
||||
|
||||
/* 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. */
|
||||
std::vector<std::string> chat_format_markers(const ChatFormat& f);
|
||||
|
||||
} /* namespace rad */
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,185 @@
|
||||
/* chatparse.h -- reading a model's reply back 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.
|
||||
*
|
||||
* It is driven by a ChatFormat (chatfmt.h) and built from three pieces:
|
||||
*
|
||||
* * 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.
|
||||
*
|
||||
* 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()).
|
||||
*
|
||||
* 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.
|
||||
*
|
||||
* 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:
|
||||
*
|
||||
* * 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
|
||||
* its type is known. A value that stops being JSON part-way is streamed as text from there.
|
||||
*
|
||||
* Streaming emits in the reply's order; a call's arguments are streamed as they are parsed. */
|
||||
#pragma once
|
||||
#include "rad_internal.h"
|
||||
|
||||
#include <nlohmann/json_fwd.hpp>
|
||||
|
||||
#include <cstdint>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <vector>
|
||||
|
||||
namespace rad {
|
||||
|
||||
struct ChatFormat;
|
||||
|
||||
/* One increment of a parsed reply. Consecutive increments of the same kind are merged. */
|
||||
struct ReplyEvent {
|
||||
enum Kind : uint8_t {
|
||||
Reasoning, /* text: a reasoning delta */
|
||||
Content, /* text: a content delta */
|
||||
CallBegin, /* text: the function name; `call` is the new call's index */
|
||||
CallArgs, /* text: an arguments delta for call `call` */
|
||||
CallEnd, /* call `call` closed */
|
||||
};
|
||||
Kind kind = Content;
|
||||
uint32_t call = 0;
|
||||
std::string text;
|
||||
};
|
||||
|
||||
struct ReplyCall {
|
||||
std::string name;
|
||||
std::string arguments; /* JSON text, as the OpenAI API carries it */
|
||||
bool closed = false;
|
||||
};
|
||||
|
||||
/* A reply, taken apart. After finish() it is the whole reply; before, what has been emitted. */
|
||||
struct ReplyMessage {
|
||||
std::string content;
|
||||
std::string reasoning;
|
||||
std::vector<ReplyCall> calls;
|
||||
};
|
||||
|
||||
/* What held bytes are waiting on, by kind. See the header comment for the bound on each. */
|
||||
struct ReplyHeld {
|
||||
size_t delimiter = 0; /* a possible delimiter prefix, and an unfinished UTF-8 sequence */
|
||||
size_t space = 0; /* whitespace that may yet be trimmed */
|
||||
size_t structure = 0; /* a tag name being read, or a JSON value awaiting its type */
|
||||
};
|
||||
|
||||
/* The per-request inputs. */
|
||||
struct ReplyOptions {
|
||||
/* The assistant prefix the template already rendered. It decides whether the reply starts
|
||||
* inside a reasoning block (ChatFormat::reasoning_in_prompt). */
|
||||
std::string generation_prompt;
|
||||
/* reasoning_format "none" keeps a reasoning block inline in the content. */
|
||||
bool extract_reasoning = true;
|
||||
/* The request's tools, OpenAI-shaped; null or empty parses no calls, and call syntax in the
|
||||
* reply is then content. Read once, when the parser is created. */
|
||||
const nlohmann::ordered_json* tools = nullptr;
|
||||
bool parallel_tool_calls = true;
|
||||
/* 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. */
|
||||
std::vector<std::string> terminators;
|
||||
};
|
||||
|
||||
class ReplyStream;
|
||||
|
||||
/* A format compiled once: its automata and its delimiters. Shared by every request. */
|
||||
class ReplyFormat {
|
||||
public:
|
||||
~ReplyFormat();
|
||||
/* RAD_OK, or RAD_E_UNSUPPORTED with *why when chat_format_check refuses the format. */
|
||||
static int compile(const ChatFormat& f, std::shared_ptr<const ReplyFormat>* out,
|
||||
std::string* why);
|
||||
const ChatFormat& format() const;
|
||||
|
||||
struct Impl;
|
||||
const Impl& impl() const { return *impl_; }
|
||||
private:
|
||||
ReplyFormat();
|
||||
std::unique_ptr<Impl> impl_;
|
||||
};
|
||||
|
||||
/* One request's parser: the format bound to the tools the request sent and the prompt it
|
||||
* rendered. Immutable once made; each choice opens its own stream from it. */
|
||||
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. */
|
||||
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. */
|
||||
size_t hold_bound() const;
|
||||
|
||||
struct Impl;
|
||||
const Impl& impl() const { return *impl_; }
|
||||
private:
|
||||
ReplyParser();
|
||||
std::unique_ptr<Impl> impl_;
|
||||
};
|
||||
|
||||
class ReplyStream {
|
||||
public:
|
||||
~ReplyStream();
|
||||
|
||||
/* Append bytes. The increments they complete are appended to *out (which may be null). */
|
||||
void feed(std::string_view bytes, std::vector<ReplyEvent>* out);
|
||||
/* The reply is complete. Whatever was held is resolved and emitted. Idempotent. */
|
||||
void finish(std::vector<ReplyEvent>* out);
|
||||
|
||||
const ReplyMessage& message() const;
|
||||
/* False once the reply left the format's grammar and was read by a recovery rule. */
|
||||
bool strict() const;
|
||||
ReplyHeld held() const;
|
||||
|
||||
struct Impl;
|
||||
private:
|
||||
friend class ReplyParser;
|
||||
ReplyStream();
|
||||
std::unique_ptr<Impl> impl_;
|
||||
};
|
||||
|
||||
/* Parse a complete reply in one call. */
|
||||
ReplyMessage reply_parse(const ReplyParser& p, std::string_view text, bool* strict = nullptr);
|
||||
|
||||
} /* namespace rad */
|
||||
@@ -0,0 +1,458 @@
|
||||
#include "text/gguf.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cerrno>
|
||||
#include <cstdint>
|
||||
#include <cstring>
|
||||
#include <fcntl.h>
|
||||
#include <sys/mman.h>
|
||||
#include <sys/stat.h>
|
||||
#include <unistd.h>
|
||||
|
||||
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. */
|
||||
static const GgufDtype k_dtypes[] = {
|
||||
{ 1, 4, "f32" }, /* 0 */
|
||||
{ 1, 2, "f16" }, /* 1 */
|
||||
{ 32, 18, "q4_0" }, /* 2 */
|
||||
{ 32, 20, "q4_1" }, /* 3 */
|
||||
{ 0, 0, nullptr }, /* 4 removed */
|
||||
{ 0, 0, nullptr }, /* 5 removed */
|
||||
{ 32, 22, "q5_0" }, /* 6 */
|
||||
{ 32, 24, "q5_1" }, /* 7 */
|
||||
{ 32, 34, "q8_0" }, /* 8 */
|
||||
{ 32, 36, "q8_1" }, /* 9 */
|
||||
{ 256, 84, "q2_K" }, /* 10 */
|
||||
{ 256, 110, "q3_K" }, /* 11 */
|
||||
{ 256, 144, "q4_K" }, /* 12 */
|
||||
{ 256, 176, "q5_K" }, /* 13 */
|
||||
{ 256, 210, "q6_K" }, /* 14 */
|
||||
{ 256, 292, "q8_K" }, /* 15 */
|
||||
{ 256, 66, "iq2_xxs" }, /* 16 */
|
||||
{ 256, 74, "iq2_xs" }, /* 17 */
|
||||
{ 256, 98, "iq3_xxs" }, /* 18 */
|
||||
{ 256, 50, "iq1_s" }, /* 19 */
|
||||
{ 32, 18, "iq4_nl" }, /* 20 */
|
||||
{ 256, 110, "iq3_s" }, /* 21 */
|
||||
{ 256, 82, "iq2_s" }, /* 22 */
|
||||
{ 256, 136, "iq4_xs" }, /* 23 */
|
||||
{ 1, 1, "i8" }, /* 24 */
|
||||
{ 1, 2, "i16" }, /* 25 */
|
||||
{ 1, 4, "i32" }, /* 26 */
|
||||
{ 1, 8, "i64" }, /* 27 */
|
||||
{ 1, 8, "f64" }, /* 28 */
|
||||
{ 256, 56, "iq1_m" }, /* 29 */
|
||||
{ 1, 2, "bf16" }, /* 30 */
|
||||
{ 0, 0, nullptr }, /* 31 removed */
|
||||
{ 0, 0, nullptr }, /* 32 removed */
|
||||
{ 0, 0, nullptr }, /* 33 removed */
|
||||
{ 256, 54, "tq1_0" }, /* 34 */
|
||||
{ 256, 66, "tq2_0" }, /* 35 */
|
||||
{ 0, 0, nullptr }, /* 36 removed */
|
||||
{ 0, 0, nullptr }, /* 37 removed */
|
||||
{ 0, 0, nullptr }, /* 38 removed */
|
||||
{ 32, 17, "mxfp4" }, /* 39 */
|
||||
{ 64, 36, "nvfp4" }, /* 40 */
|
||||
{ 128, 18, "q1_0" }, /* 41 */
|
||||
{ 32, 34, "rad4_q8" }, /* 42 */
|
||||
{ 32, 20, "rad4_q4" }, /* 43 */
|
||||
{ 256, 144, "rad4_q4k"}, /* 44 */
|
||||
};
|
||||
static const size_t k_n_dtypes = sizeof(k_dtypes) / sizeof(k_dtypes[0]);
|
||||
|
||||
const GgufDtype* gguf_dtype(uint32_t t) {
|
||||
if (t >= k_n_dtypes || k_dtypes[t].blck == 0) return nullptr;
|
||||
return &k_dtypes[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. */
|
||||
switch (t) {
|
||||
case 0: return RAD_F32;
|
||||
case 1: return RAD_F16;
|
||||
case 24: return RAD_I8;
|
||||
case 25: return RAD_I16;
|
||||
case 26: return RAD_I32;
|
||||
case 27: return RAD_I64;
|
||||
case 30: return RAD_BF16;
|
||||
default: return RAD_DT_INVALID;
|
||||
}
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ 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. */
|
||||
namespace {
|
||||
struct Cursor {
|
||||
const uint8_t* p = nullptr;
|
||||
uint64_t off = 0, end = 0;
|
||||
|
||||
bool raw(void* dst, size_t n) {
|
||||
if (n > end - off) return false;
|
||||
std::memcpy(dst, p + off, n);
|
||||
off += n;
|
||||
return true;
|
||||
}
|
||||
template <class T> bool pod(T* v) { return raw(v, sizeof(T)); }
|
||||
|
||||
bool str(std::string* out) {
|
||||
uint64_t n = 0;
|
||||
if (!pod(&n)) return false;
|
||||
if (n > end - off) return false;
|
||||
out->assign(reinterpret_cast<const char*>(p + off), (size_t)n);
|
||||
off += n;
|
||||
return true;
|
||||
}
|
||||
bool skip(uint64_t n) {
|
||||
if (n > end - off) return false;
|
||||
off += n;
|
||||
return true;
|
||||
}
|
||||
};
|
||||
|
||||
size_t gguf_scalar_bytes(uint32_t t) {
|
||||
switch (t) {
|
||||
case GGUF_U8: case GGUF_I8: case GGUF_BOOL: return 1;
|
||||
case GGUF_U16: case GGUF_I16: return 2;
|
||||
case GGUF_U32: case GGUF_I32: case GGUF_F32: return 4;
|
||||
case GGUF_U64: case GGUF_I64: case GGUF_F64: return 8;
|
||||
default: return 0; /* STR and ARR are not fixed-width */
|
||||
}
|
||||
}
|
||||
|
||||
/* 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. */
|
||||
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. */
|
||||
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. */
|
||||
bool read_scalar(Cursor& c, uint32_t t, GgufKV& kv) {
|
||||
switch (t) {
|
||||
case GGUF_U8: { uint8_t v; if (!c.pod(&v)) return false; kv.i.push_back(v); return true; }
|
||||
case GGUF_I8: { int8_t v; if (!c.pod(&v)) return false; kv.i.push_back(v); return true; }
|
||||
case GGUF_BOOL: { int8_t v; if (!c.pod(&v)) return false; kv.i.push_back(v ? 1 : 0); return true; }
|
||||
case GGUF_U16: { uint16_t v; if (!c.pod(&v)) return false; kv.i.push_back(v); return true; }
|
||||
case GGUF_I16: { int16_t v; if (!c.pod(&v)) return false; kv.i.push_back(v); return true; }
|
||||
case GGUF_U32: { uint32_t v; if (!c.pod(&v)) return false; kv.i.push_back(v); return true; }
|
||||
case GGUF_I32: { int32_t v; if (!c.pod(&v)) return false; kv.i.push_back(v); return true; }
|
||||
case GGUF_U64: { uint64_t v; if (!c.pod(&v)) return false; kv.i.push_back((int64_t)v); return true; }
|
||||
case GGUF_I64: { int64_t v; if (!c.pod(&v)) return false; kv.i.push_back(v); return true; }
|
||||
case GGUF_F32: { float v; if (!c.pod(&v)) return false; kv.f.push_back(v); return true; }
|
||||
case GGUF_F64: { double v; if (!c.pod(&v)) return false; kv.f.push_back(v); return true; }
|
||||
case GGUF_STR: { std::string s; if (!c.str(&s)) return false; kv.s.push_back(std::move(s)); return true; }
|
||||
default: return false;
|
||||
}
|
||||
}
|
||||
} /* namespace */
|
||||
|
||||
/* ------------------------------------------------------------------ open */
|
||||
GgufFile::~GgufFile() { close(); }
|
||||
|
||||
void GgufFile::close() {
|
||||
if (base_) {
|
||||
::munmap(const_cast<uint8_t*>(base_), (size_t)file_bytes_);
|
||||
base_ = nullptr;
|
||||
}
|
||||
kv_.clear();
|
||||
tensors_.clear();
|
||||
kv_index_.clear();
|
||||
tensor_index_.clear();
|
||||
file_bytes_ = 0;
|
||||
data_off_ = 0;
|
||||
version_ = 0;
|
||||
alignment_ = 32;
|
||||
path_.clear();
|
||||
}
|
||||
|
||||
int GgufFile::open(const char* path) {
|
||||
close();
|
||||
path_ = path ? path : "";
|
||||
|
||||
int fd = ::open(path_.c_str(), O_RDONLY);
|
||||
if (fd < 0) {
|
||||
RAD_ERR("gguf: open %s: %s", path_.c_str(), std::strerror(errno));
|
||||
return RAD_E_IO;
|
||||
}
|
||||
struct stat st{};
|
||||
if (::fstat(fd, &st) != 0 || st.st_size <= 0) {
|
||||
::close(fd);
|
||||
RAD_ERR("gguf: stat %s: %s", path_.c_str(), std::strerror(errno));
|
||||
return RAD_E_IO;
|
||||
}
|
||||
void* m = ::mmap(nullptr, (size_t)st.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
|
||||
::close(fd); /* the mapping keeps its own reference; the fd is not needed */
|
||||
if (m == MAP_FAILED) {
|
||||
RAD_ERR("gguf: mmap %s (%lld bytes): %s", path_.c_str(),
|
||||
(long long)st.st_size, std::strerror(errno));
|
||||
return RAD_E_IO;
|
||||
}
|
||||
base_ = static_cast<const uint8_t*>(m);
|
||||
file_bytes_ = (uint64_t)st.st_size;
|
||||
|
||||
Cursor c{ base_, 0, file_bytes_ };
|
||||
|
||||
char magic[4] = { 0, 0, 0, 0 };
|
||||
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;
|
||||
}
|
||||
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;
|
||||
}
|
||||
/* 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. */
|
||||
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;
|
||||
}
|
||||
/* 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. */
|
||||
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;
|
||||
}
|
||||
|
||||
kv_.reserve(reserve_hint(n_kv));
|
||||
for (uint64_t k = 0; k < n_kv; ++k) {
|
||||
GgufKV e;
|
||||
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;
|
||||
}
|
||||
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;
|
||||
}
|
||||
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;
|
||||
}
|
||||
/* 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. */
|
||||
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;
|
||||
}
|
||||
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;
|
||||
}
|
||||
}
|
||||
e.type = t;
|
||||
if (t == GGUF_STR) e.s.reserve(reserve_hint(n));
|
||||
else if (t == GGUF_F32 || t == GGUF_F64) e.f.reserve(reserve_hint(n));
|
||||
else e.i.reserve(reserve_hint(n));
|
||||
|
||||
for (uint64_t j = 0; j < n; ++j) {
|
||||
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;
|
||||
}
|
||||
}
|
||||
/* Later duplicates lose. GGUF does not forbid them and a rewriter can leave one behind;
|
||||
* the first is the one every other reader takes. */
|
||||
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) {
|
||||
alignment_ = (uint64_t)al;
|
||||
}
|
||||
|
||||
tensors_.reserve(reserve_hint(n_tensors));
|
||||
for (uint64_t t = 0; t < n_tensors; ++t) {
|
||||
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;
|
||||
}
|
||||
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;
|
||||
}
|
||||
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;
|
||||
}
|
||||
}
|
||||
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;
|
||||
}
|
||||
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.",
|
||||
path_.c_str(), ti.name.c_str(), ti.ggml_type);
|
||||
close();
|
||||
return RAD_E_FORMAT;
|
||||
}
|
||||
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;
|
||||
}
|
||||
/* 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. */
|
||||
uint64_t nelem = 1;
|
||||
bool wraps = false;
|
||||
for (int d = 0; d < 4; ++d)
|
||||
wraps |= __builtin_mul_overflow(nelem, (uint64_t)ti.ne[d], &nelem);
|
||||
wraps |= nelem > (uint64_t)INT64_MAX;
|
||||
wraps |= __builtin_mul_overflow(nelem / (uint64_t)dt->blck, (uint64_t)dt->block_bytes,
|
||||
&ti.bytes);
|
||||
if (wraps) {
|
||||
RAD_ERR("gguf: %s: tensor '%s' has dimensions %lld x %lld x %lld x %lld, whose size "
|
||||
"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;
|
||||
}
|
||||
if (!tensor_index_.count(ti.name)) tensor_index_[ti.name] = tensors_.size();
|
||||
tensors_.push_back(std::move(ti));
|
||||
}
|
||||
|
||||
data_off_ = align_up((int64_t)c.off, (int64_t)alignment_);
|
||||
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;
|
||||
}
|
||||
/* 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. */
|
||||
for (const GgufTensor& ti : tensors_) {
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
RAD_DEBUG("gguf: %s v%u, %zu KVs, %zu tensors, data at +%llu, align %llu",
|
||||
path_.c_str(), version_, kv_.size(), tensors_.size(),
|
||||
(unsigned long long)data_off_, (unsigned long long)alignment_);
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ lookup */
|
||||
const GgufKV* GgufFile::find(std::string_view key) const {
|
||||
auto it = kv_index_.find(std::string(key));
|
||||
return it == kv_index_.end() ? nullptr : &kv_[it->second];
|
||||
}
|
||||
|
||||
const GgufTensor* GgufFile::tensor(std::string_view name) const {
|
||||
auto it = tensor_index_.find(std::string(name));
|
||||
return it == tensor_index_.end() ? nullptr : &tensors_[it->second];
|
||||
}
|
||||
|
||||
bool GgufFile::get_i64(std::string_view key, int64_t* out) const {
|
||||
const GgufKV* e = find(key);
|
||||
if (!e || e->i.empty()) return false;
|
||||
*out = e->i[0];
|
||||
return true;
|
||||
}
|
||||
|
||||
bool GgufFile::get_f64(std::string_view key, double* out) const {
|
||||
const GgufKV* e = find(key);
|
||||
if (!e || e->f.empty()) return false;
|
||||
*out = e->f[0];
|
||||
return true;
|
||||
}
|
||||
|
||||
bool GgufFile::get_str(std::string_view key, std::string* out) const {
|
||||
const GgufKV* e = find(key);
|
||||
if (!e || e->s.empty()) return false;
|
||||
*out = e->s[0];
|
||||
return true;
|
||||
}
|
||||
|
||||
bool GgufFile::get_strs(std::string_view key, std::vector<std::string>* out) const {
|
||||
const GgufKV* e = find(key);
|
||||
if (!e || e->type != GGUF_STR) return false;
|
||||
*out = e->s;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool GgufFile::get_i64s(std::string_view key, std::vector<int64_t>* out) const {
|
||||
const GgufKV* e = find(key);
|
||||
if (!e || e->i.empty()) return false;
|
||||
*out = e->i;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool GgufFile::get_f32s(std::string_view key, std::vector<float>* out) const {
|
||||
const GgufKV* e = find(key);
|
||||
if (!e || e->f.empty()) return false;
|
||||
out->assign(e->f.begin(), e->f.end());
|
||||
return true;
|
||||
}
|
||||
|
||||
const void* GgufFile::tensor_data(const GgufTensor& t) const {
|
||||
if (!base_) return nullptr;
|
||||
if (t.offset > file_bytes_ - data_off_ || t.bytes > file_bytes_ - data_off_ - t.offset)
|
||||
return nullptr;
|
||||
return base_ + data_off_ + t.offset;
|
||||
}
|
||||
|
||||
} /* namespace rad */
|
||||
@@ -0,0 +1,133 @@
|
||||
/* gguf.h -- a reader for the GGUF container, and nothing else.
|
||||
*
|
||||
* 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.
|
||||
*
|
||||
* 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 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.
|
||||
*/
|
||||
#pragma once
|
||||
#include "rad_internal.h"
|
||||
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <unordered_map>
|
||||
#include <vector>
|
||||
|
||||
namespace rad {
|
||||
|
||||
/* GGUF's own value type numbering. These are wire values -- fixed by the format, not by us. */
|
||||
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. */
|
||||
struct GgufKV {
|
||||
std::string key;
|
||||
uint32_t type = GGUF_U8; /* for an array, the ELEMENT type; GGUF_ARR never appears here */
|
||||
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. */
|
||||
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. */
|
||||
struct GgufTensor {
|
||||
std::string name;
|
||||
uint32_t ggml_type = 0;
|
||||
uint32_t n_dims = 0;
|
||||
int64_t ne[4] = { 1, 1, 1, 1 }; /* GGUF is fixed at 4 dims, unused ones are 1 */
|
||||
uint64_t offset = 0;
|
||||
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. */
|
||||
struct GgufDtype {
|
||||
int blck; /* logical elements per stored block */
|
||||
size_t block_bytes; /* bytes per stored block */
|
||||
const char* name;
|
||||
};
|
||||
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. */
|
||||
uint32_t gguf_to_rad_dtype(uint32_t ggml_type);
|
||||
|
||||
class GgufFile {
|
||||
public:
|
||||
GgufFile() = default;
|
||||
~GgufFile();
|
||||
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. */
|
||||
int open(const char* path);
|
||||
void close();
|
||||
bool is_open() const { return base_ != nullptr; }
|
||||
|
||||
uint32_t version() const { return version_; }
|
||||
uint64_t alignment() const { return alignment_; }
|
||||
uint64_t data_off() const { return data_off_; } /* file offset of the tensor blob */
|
||||
uint64_t file_bytes() const { return file_bytes_; }
|
||||
const void* base() const { return base_; } /* the mmap, or null */
|
||||
const std::string& path() const { return path_; }
|
||||
|
||||
const std::vector<GgufKV>& kv() const { return kv_; }
|
||||
const std::vector<GgufTensor>& tensors() const { return tensors_; }
|
||||
|
||||
const GgufKV* find(std::string_view key) const;
|
||||
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. */
|
||||
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;
|
||||
bool get_strs(std::string_view key, std::vector<std::string>* out) const;
|
||||
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. */
|
||||
const void* tensor_data(const GgufTensor& t) const;
|
||||
|
||||
private:
|
||||
std::string path_;
|
||||
const uint8_t* base_ = nullptr;
|
||||
uint64_t file_bytes_ = 0;
|
||||
uint32_t version_ = 0;
|
||||
uint64_t alignment_ = 32;
|
||||
uint64_t data_off_ = 0;
|
||||
|
||||
std::vector<GgufKV> kv_;
|
||||
std::vector<GgufTensor> tensors_;
|
||||
std::unordered_map<std::string, size_t> kv_index_;
|
||||
std::unordered_map<std::string, size_t> tensor_index_;
|
||||
};
|
||||
|
||||
} /* namespace rad */
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,313 @@
|
||||
/* 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.
|
||||
*
|
||||
* 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 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):
|
||||
* - 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.
|
||||
*/
|
||||
#pragma once
|
||||
#include "rad_internal.h"
|
||||
|
||||
#include <cstdint>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <unordered_map>
|
||||
#include <unordered_set>
|
||||
#include <vector>
|
||||
|
||||
namespace rad {
|
||||
|
||||
class GgufFile;
|
||||
struct TokEncoder;
|
||||
|
||||
/* ================================================================== the mutable vocab */
|
||||
|
||||
/* 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. */
|
||||
struct VocabStep {
|
||||
uint32_t kind = 0;
|
||||
uint32_t flags = 0;
|
||||
std::string arg0, arg1;
|
||||
int64_t iarg = 0;
|
||||
};
|
||||
|
||||
/* 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; }
|
||||
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. */
|
||||
struct VocabBuild {
|
||||
uint32_t kind = RAD_TOK_BPE;
|
||||
|
||||
std::vector<std::string> tokens; /* id -> text, in the vocab's own encoding */
|
||||
std::vector<float> scores; /* unigram only; empty otherwise */
|
||||
std::vector<uint8_t> types; /* RAD_TT_*; empty means all RAD_TT_NORMAL */
|
||||
std::vector<std::pair<uint32_t, uint32_t>> merges; /* BPE, in rank order */
|
||||
|
||||
std::vector<VocabStep> steps; /* the whole declared chain, in order */
|
||||
|
||||
int32_t bos = -1, eos = -1, eot = -1, pad = -1, unk = -1, sep = -1;
|
||||
bool add_bos = false, add_eos = false;
|
||||
|
||||
std::string chat_template;
|
||||
|
||||
/* Diagnostics only: what rad-convert thought it was reading. Not baked. */
|
||||
std::string source;
|
||||
};
|
||||
|
||||
/* ================================================================== the loaded vocab */
|
||||
|
||||
class Vocab {
|
||||
public:
|
||||
int load(VocabBuild b); /* takes ownership; RAD_OK or negative */
|
||||
bool ready() const { return ready_; }
|
||||
|
||||
uint32_t kind() const { return b_.kind; }
|
||||
int32_t n_tokens() const { return (int32_t)b_.tokens.size(); }
|
||||
|
||||
const std::string& text(int32_t id) const;
|
||||
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. */
|
||||
const std::vector<int32_t>& eog() const { return eog_; }
|
||||
|
||||
/* -1 when the exact text is not a token. */
|
||||
int32_t find(std::string_view text) const;
|
||||
/* BPE merge rank of the pair, or -1. */
|
||||
int32_t merge_rank(std::string_view left, std::string_view right) const;
|
||||
|
||||
int32_t bos() const { return b_.bos; }
|
||||
int32_t eos() const { return b_.eos; }
|
||||
int32_t eot() const { return b_.eot; }
|
||||
int32_t unk() const { return b_.unk; }
|
||||
int32_t pad() const { return b_.pad; }
|
||||
bool add_bos() const { return b_.add_bos; }
|
||||
bool add_eos() const { return b_.add_eos; }
|
||||
const std::string& chat_template() const { return b_.chat_template; }
|
||||
|
||||
const std::vector<VocabStep>& steps() const { return b_.steps; }
|
||||
const std::vector<int32_t>& special_ids() const { return special_; }
|
||||
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. */
|
||||
int32_t token_byte(int32_t id) const;
|
||||
|
||||
private:
|
||||
VocabBuild b_;
|
||||
bool ready_ = false;
|
||||
std::unordered_map<std::string, int32_t> text_to_id_;
|
||||
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. */
|
||||
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. */
|
||||
std::shared_ptr<TokEncoder> enc_;
|
||||
friend class Tokenizer;
|
||||
friend class Detokenizer;
|
||||
};
|
||||
|
||||
/* ================================================================== encode */
|
||||
|
||||
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. */
|
||||
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. */
|
||||
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. */
|
||||
std::string piece(int32_t id, bool render_special = false) 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.
|
||||
*
|
||||
* 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. */
|
||||
static constexpr size_t kSegmentCacheMin = 64;
|
||||
static constexpr size_t kSegmentCacheDefault = size_t(64) << 20;
|
||||
void set_segment_cache(bool on) { use_cache_ = on; }
|
||||
struct CacheStats {
|
||||
uint64_t hits = 0, misses = 0;
|
||||
size_t entries = 0, bytes = 0, limit = 0;
|
||||
};
|
||||
CacheStats cache_stats() const;
|
||||
void set_cache_limit(size_t bytes) const;
|
||||
void clear_cache() const;
|
||||
|
||||
private:
|
||||
std::shared_ptr<const Vocab> v_;
|
||||
bool use_cache_ = true;
|
||||
};
|
||||
|
||||
/* ================================================================== 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. */
|
||||
std::string utf8_sanitize(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>".
|
||||
*
|
||||
* 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. */
|
||||
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. */
|
||||
Detokenizer(std::shared_ptr<const Vocab> v, std::vector<std::string> stops = {},
|
||||
bool render_special = false, const std::vector<std::string>& preserved = {});
|
||||
|
||||
std::string push(int32_t token);
|
||||
std::string flush();
|
||||
|
||||
/* True once a stop string has been seen. The text before it has already been returned; the
|
||||
* stop string itself and anything after it never is. */
|
||||
bool stopped() const { return stopped_; }
|
||||
const std::string& stop_hit() const { return stop_hit_; }
|
||||
|
||||
/* 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. */
|
||||
const std::string& text() const { return all_; }
|
||||
|
||||
void reset();
|
||||
|
||||
private:
|
||||
std::shared_ptr<const Vocab> v_;
|
||||
std::vector<std::string> stops_;
|
||||
bool render_special_ = false;
|
||||
std::unordered_set<int32_t> preserved_; /* control ids this stream renders anyway */
|
||||
std::string pending_; /* decoded but not yet safe to emit */
|
||||
std::string all_; /* everything, for the caller's record */
|
||||
bool stopped_ = false;
|
||||
std::string stop_hit_;
|
||||
size_t max_stop_ = 0;
|
||||
bool first_ = true;
|
||||
|
||||
size_t safe_prefix() const; /* how much of pending_ can be released */
|
||||
};
|
||||
|
||||
/* ================================================================== 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. */
|
||||
struct StringSink {
|
||||
virtual ~StringSink() = default;
|
||||
virtual rad_stroff intern(std::string_view s) = 0;
|
||||
};
|
||||
|
||||
/* 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. */
|
||||
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. */
|
||||
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". */
|
||||
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. */
|
||||
int vocab_deserialize(const void* file_base, uint64_t file_bytes,
|
||||
const RadVocabHeader* h, VocabBuild& out);
|
||||
|
||||
/* Human-readable one-liner for a step, for --debug-graph and for the convert log. */
|
||||
std::string step_describe(const VocabStep& s);
|
||||
|
||||
} /* namespace rad */
|
||||
@@ -0,0 +1,185 @@
|
||||
#include "text/tokenizer_bpe.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <queue>
|
||||
|
||||
namespace rad {
|
||||
|
||||
/* ================================================================== TokTable */
|
||||
|
||||
void TokTable::reserve(size_t n) {
|
||||
size_t cap = 16;
|
||||
while (cap < n * 2) cap <<= 1;
|
||||
if (cap <= slots_.size()) return;
|
||||
std::vector<Slot> old;
|
||||
old.swap(slots_);
|
||||
slots_.assign(cap, Slot{});
|
||||
mask_ = cap - 1;
|
||||
for (const Slot& s : old) {
|
||||
if (s.id < 0) continue;
|
||||
const uint64_t h = tok_hash(keys_.data() + s.off, s.len);
|
||||
size_t i = h & mask_;
|
||||
while (slots_[i].id >= 0) i = (i + 1) & mask_;
|
||||
slots_[i] = s;
|
||||
}
|
||||
}
|
||||
|
||||
void TokTable::grow() { reserve(std::max<size_t>(16, (n_ + 1) * 2)); }
|
||||
|
||||
bool TokTable::insert(std::string_view key, int32_t id) {
|
||||
if ((n_ + 1) * 2 > slots_.size()) grow();
|
||||
const uint64_t h = tok_hash(key);
|
||||
const uint32_t tag = (uint32_t)(h >> 32);
|
||||
for (size_t i = h & mask_;; i = (i + 1) & mask_) {
|
||||
Slot& s = slots_[i];
|
||||
if (s.id < 0) {
|
||||
s.off = (uint32_t)keys_.size();
|
||||
s.len = (uint32_t)key.size();
|
||||
s.id = id;
|
||||
s.tag = tag;
|
||||
keys_.append(key.data(), key.size());
|
||||
++n_;
|
||||
return true;
|
||||
}
|
||||
if (s.tag == tag && s.len == key.size() &&
|
||||
std::memcmp(keys_.data() + s.off, key.data(), key.size()) == 0)
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
int32_t TokTable::find(std::string_view key) const {
|
||||
if (slots_.empty()) return -1;
|
||||
const uint64_t h = tok_hash(key);
|
||||
const uint32_t tag = (uint32_t)(h >> 32);
|
||||
for (size_t i = h & mask_;; i = (i + 1) & mask_) {
|
||||
const Slot& s = slots_[i];
|
||||
if (s.id < 0) return -1;
|
||||
if (s.tag == tag && s.len == key.size() &&
|
||||
std::memcmp(keys_.data() + s.off, key.data(), key.size()) == 0)
|
||||
return s.id;
|
||||
}
|
||||
}
|
||||
|
||||
/* ================================================================== MergeTable */
|
||||
|
||||
void MergeTable::reserve(size_t n) {
|
||||
size_t cap = 16;
|
||||
while (cap < n * 2) cap <<= 1;
|
||||
if (cap <= slots_.size()) return;
|
||||
std::vector<Slot> old;
|
||||
old.swap(slots_);
|
||||
slots_.assign(cap, Slot{});
|
||||
mask_ = cap - 1;
|
||||
for (const Slot& s : old) {
|
||||
if (s.key == kEmpty) continue;
|
||||
size_t i = mix(s.key) & mask_;
|
||||
while (slots_[i].key != kEmpty) i = (i + 1) & mask_;
|
||||
slots_[i] = s;
|
||||
}
|
||||
}
|
||||
|
||||
void MergeTable::grow() { reserve(std::max<size_t>(16, (n_ + 1) * 2)); }
|
||||
|
||||
bool MergeTable::insert(int32_t l, int32_t r, uint32_t rank, int32_t merged) {
|
||||
if (l < 0 || r < 0) return false;
|
||||
if ((n_ + 1) * 2 > slots_.size()) grow();
|
||||
const uint64_t key = ((uint64_t)(uint32_t)l << 32) | (uint32_t)r;
|
||||
for (size_t i = mix(key) & mask_;; i = (i + 1) & mask_) {
|
||||
Slot& s = slots_[i];
|
||||
if (s.key == key) return false;
|
||||
if (s.key == kEmpty) {
|
||||
s.key = key;
|
||||
s.rank = rank;
|
||||
s.merged = merged;
|
||||
++n_;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* ================================================================== the merge */
|
||||
|
||||
namespace {
|
||||
|
||||
void merge_linear(std::vector<BpeSym>& syms, const MergeTable& merges) {
|
||||
uint32_t rank[kBpeLinearMax];
|
||||
int32_t merged[kBpeLinearMax];
|
||||
size_t len = syms.size();
|
||||
for (size_t i = 0; i + 1 < len; ++i) rank[i] = merges.find(syms[i].id, syms[i + 1].id, &merged[i]);
|
||||
rank[len - 1] = UINT32_MAX;
|
||||
for (;;) {
|
||||
uint32_t best = UINT32_MAX;
|
||||
size_t bi = 0;
|
||||
for (size_t i = 0; i + 1 < len; ++i) {
|
||||
if (rank[i] < best) { best = rank[i]; bi = i; }
|
||||
}
|
||||
if (best == UINT32_MAX) break;
|
||||
syms[bi].len += syms[bi + 1].len;
|
||||
syms[bi].id = merged[bi];
|
||||
/* The right symbol and the pair it started are gone; the pairs either side of the new
|
||||
* symbol are recomputed. */
|
||||
for (size_t k = bi + 1; k + 1 < len; ++k) {
|
||||
syms[k] = syms[k + 1];
|
||||
rank[k] = rank[k + 1];
|
||||
merged[k] = merged[k + 1];
|
||||
}
|
||||
--len;
|
||||
if (bi > 0) rank[bi - 1] = merges.find(syms[bi - 1].id, syms[bi].id, &merged[bi - 1]);
|
||||
rank[bi] = bi + 1 < len ? merges.find(syms[bi].id, syms[bi + 1].id, &merged[bi]) : UINT32_MAX;
|
||||
}
|
||||
syms.resize(len);
|
||||
}
|
||||
|
||||
void merge_heap(std::vector<BpeSym>& syms, const MergeTable& merges) {
|
||||
struct Node { int32_t prev, next; uint32_t ver; bool alive; };
|
||||
struct Cand {
|
||||
uint32_t rank, left, right, vl, vr;
|
||||
int32_t merged;
|
||||
/* priority_queue is a max-heap: the pair that should come out first compares greatest. */
|
||||
bool operator<(const Cand& o) const {
|
||||
return rank != o.rank ? rank > o.rank : left > o.left;
|
||||
}
|
||||
};
|
||||
const size_t n = syms.size();
|
||||
std::vector<Node> node(n);
|
||||
for (size_t i = 0; i < n; ++i)
|
||||
node[i] = { (int32_t)i - 1, i + 1 < n ? (int32_t)(i + 1) : -1, 0, true };
|
||||
std::priority_queue<Cand> heap;
|
||||
auto offer = [&](int32_t l, int32_t r) {
|
||||
if (l < 0 || r < 0) return;
|
||||
int32_t m = -1;
|
||||
const uint32_t rank = merges.find(syms[l].id, syms[r].id, &m);
|
||||
if (rank == UINT32_MAX) return;
|
||||
heap.push({ rank, (uint32_t)l, (uint32_t)r, node[l].ver, node[r].ver, m });
|
||||
};
|
||||
for (size_t i = 0; i + 1 < n; ++i) offer((int32_t)i, (int32_t)(i + 1));
|
||||
while (!heap.empty()) {
|
||||
const Cand c = heap.top();
|
||||
heap.pop();
|
||||
Node& l = node[c.left];
|
||||
Node& r = node[c.right];
|
||||
if (!l.alive || !r.alive || l.ver != c.vl || r.ver != c.vr) continue;
|
||||
syms[c.left].len += syms[c.right].len;
|
||||
syms[c.left].id = c.merged;
|
||||
l.next = r.next;
|
||||
if (r.next >= 0) node[r.next].prev = (int32_t)c.left;
|
||||
r.alive = false;
|
||||
++r.ver;
|
||||
++l.ver;
|
||||
offer(l.prev, (int32_t)c.left);
|
||||
offer((int32_t)c.left, l.next);
|
||||
}
|
||||
size_t w = 0;
|
||||
for (size_t i = 0; i < n; ++i) if (node[i].alive) syms[w++] = syms[i];
|
||||
syms.resize(w);
|
||||
}
|
||||
|
||||
} /* namespace */
|
||||
|
||||
void bpe_merge(std::vector<BpeSym>& syms, const MergeTable& merges, bool force_heap) {
|
||||
if (syms.size() < 2) return;
|
||||
if (syms.size() <= kBpeLinearMax && !force_heap) merge_linear(syms, merges);
|
||||
else merge_heap(syms, merges);
|
||||
}
|
||||
|
||||
} /* namespace rad */
|
||||
@@ -0,0 +1,110 @@
|
||||
/* 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.
|
||||
*/
|
||||
#pragma once
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <cstring>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <vector>
|
||||
|
||||
namespace rad {
|
||||
|
||||
/* 64-bit hash of a byte string: eight bytes a round, a multiply-xorshift finish. */
|
||||
inline uint64_t tok_hash(const void* data, size_t n) {
|
||||
const uint8_t* p = static_cast<const uint8_t*>(data);
|
||||
uint64_t h = 0x9E3779B97F4A7C15ull ^ (n * 0xC2B2AE3D27D4EB4Full);
|
||||
while (n >= 8) {
|
||||
uint64_t w;
|
||||
std::memcpy(&w, p, 8);
|
||||
h = (h ^ w) * 0xFF51AFD7ED558CCDull;
|
||||
h ^= h >> 32;
|
||||
p += 8;
|
||||
n -= 8;
|
||||
}
|
||||
if (n) {
|
||||
uint64_t w = 0;
|
||||
std::memcpy(&w, p, n);
|
||||
h = (h ^ w) * 0xC4CEB9FE1A85EC53ull;
|
||||
}
|
||||
h ^= h >> 29;
|
||||
h *= 0xBF58476D1CE4E5B9ull;
|
||||
h ^= h >> 32;
|
||||
return h;
|
||||
}
|
||||
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. */
|
||||
class TokTable {
|
||||
public:
|
||||
void reserve(size_t n);
|
||||
bool insert(std::string_view key, int32_t id); /* false when the key was present */
|
||||
int32_t find(std::string_view key) const;
|
||||
size_t size() const { return n_; }
|
||||
|
||||
private:
|
||||
struct Slot { uint32_t off = 0, len = 0; int32_t id = -1; uint32_t tag = 0; };
|
||||
std::vector<Slot> slots_;
|
||||
std::string keys_;
|
||||
size_t n_ = 0;
|
||||
size_t mask_ = 0;
|
||||
void grow();
|
||||
};
|
||||
|
||||
/* (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:
|
||||
void reserve(size_t n);
|
||||
bool insert(int32_t l, int32_t r, uint32_t rank, int32_t merged);
|
||||
/* rank, or UINT32_MAX when the pair does not merge. */
|
||||
uint32_t find(int32_t l, int32_t r, int32_t* merged) const {
|
||||
if (l < 0 || r < 0 || slots_.empty()) return UINT32_MAX;
|
||||
const uint64_t key = ((uint64_t)(uint32_t)l << 32) | (uint32_t)r;
|
||||
for (size_t i = mix(key) & mask_;; i = (i + 1) & mask_) {
|
||||
const Slot& s = slots_[i];
|
||||
if (s.key == key) { *merged = s.merged; return s.rank; }
|
||||
if (s.key == kEmpty) return UINT32_MAX;
|
||||
}
|
||||
}
|
||||
size_t size() const { return n_; }
|
||||
|
||||
private:
|
||||
static constexpr uint64_t kEmpty = ~0ull;
|
||||
struct Slot { uint64_t key = kEmpty; uint32_t rank = 0; int32_t merged = -1; };
|
||||
static uint64_t mix(uint64_t k) {
|
||||
k ^= k >> 33;
|
||||
k *= 0xFF51AFD7ED558CCDull;
|
||||
k ^= k >> 33;
|
||||
return k;
|
||||
}
|
||||
std::vector<Slot> slots_;
|
||||
size_t n_ = 0, mask_ = 0;
|
||||
void grow();
|
||||
};
|
||||
|
||||
/* One symbol of a word being merged: a byte span of the word and the id its text spells, or -1
|
||||
* when it spells no token (it then merges with nothing). */
|
||||
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. */
|
||||
void bpe_merge(std::vector<BpeSym>& syms, const MergeTable& merges, bool force_heap = false);
|
||||
|
||||
} /* namespace rad */
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,129 @@
|
||||
#include "text/tokenizer_nfc.h"
|
||||
#include "text/unicode_norm.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstring>
|
||||
#include <vector>
|
||||
|
||||
namespace rad {
|
||||
|
||||
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. */
|
||||
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);
|
||||
}
|
||||
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 */
|
||||
for (uint32_t c = 0x11A8; c <= 0x11C2; ++c) set(not_yes_, c); /* Hangul T, composes after LV */
|
||||
for (size_t i = 0; i < k_ccc_n; ++i)
|
||||
for (uint32_t c = k_ccc[i].first; c <= k_ccc[i].last; ++c) set(marked_, c);
|
||||
}
|
||||
|
||||
/* Normalise `text` in place; false when it was already NFC and is untouched. */
|
||||
bool apply(std::string& text) const {
|
||||
const uint8_t* p = (const uint8_t*)text.data();
|
||||
const size_t n = text.size();
|
||||
std::string out;
|
||||
size_t copied = 0; /* text[0, copied) is in `out` */
|
||||
size_t boundary = 0; /* start of the last boundary codepoint seen */
|
||||
uint32_t last = 0; /* combining class of the previous codepoint */
|
||||
for (size_t i = 0; i < n; ) {
|
||||
if (i + 8 <= n) {
|
||||
uint64_t w;
|
||||
std::memcpy(&w, p + i, 8);
|
||||
if (!(w & 0x8080808080808080ull)) { last = 0; boundary = i + 7; i += 8; continue; }
|
||||
}
|
||||
uint32_t len, ccc;
|
||||
const int k = classify(p + i, n - i, &len, &ccc);
|
||||
if (k == kBoundary) { last = 0; boundary = i; i += len; continue; }
|
||||
if (k == kKeep && !(ccc != 0 && last > ccc)) { last = ccc; i += len; continue; }
|
||||
/* Something NFC may change: normalise from the boundary before it to the next one. */
|
||||
size_t end = i + len;
|
||||
while (end < n) {
|
||||
uint32_t l2, c2;
|
||||
if (classify(p + end, n - end, &l2, &c2) == kBoundary) break;
|
||||
end += l2;
|
||||
}
|
||||
const size_t start = std::max(boundary, copied);
|
||||
out.append(text, copied, start - copied);
|
||||
out += unorm_utf8(text.substr(start, end - start), false, true);
|
||||
copied = end;
|
||||
boundary = end;
|
||||
last = 0;
|
||||
i = end;
|
||||
}
|
||||
if (copied == 0) return false;
|
||||
out.append(text, copied, std::string::npos);
|
||||
text.swap(out);
|
||||
return true;
|
||||
}
|
||||
|
||||
private:
|
||||
enum { kBoundary, kKeep, kChange };
|
||||
static constexpr uint32_t kInvalidLen = UINT32_MAX;
|
||||
static constexpr size_t kWords = (0x110000 + 63) / 64;
|
||||
static void set(std::vector<uint64_t>& b, uint32_t c) { b[c >> 6] |= 1ull << (c & 63); }
|
||||
static bool get(const std::vector<uint64_t>& b, uint32_t c) { return (b[c >> 6] >> (c & 63)) & 1; }
|
||||
|
||||
/* kBoundary: a well-formed codepoint with class 0 and NFC_QC Yes. kKeep: well-formed, NFC_QC
|
||||
* Yes, a nonzero class (in `ccc`) the caller checks for order. kChange: anything else; an
|
||||
* invalid byte reports a length of 1 and kInvalidLen in `ccc`. */
|
||||
int classify(const uint8_t* p, size_t n, uint32_t* len, uint32_t* ccc) const {
|
||||
const uint32_t b = p[0];
|
||||
*ccc = 0;
|
||||
if (b < 0x80) { *len = 1; return kBoundary; }
|
||||
uint32_t c;
|
||||
auto cont = [&](size_t k) { return k < n && (p[k] & 0xC0) == 0x80; };
|
||||
if (b >= 0xC2 && b < 0xE0 && cont(1)) {
|
||||
c = ((b & 0x1F) << 6) | (p[1] & 0x3F);
|
||||
*len = 2;
|
||||
} else if (b >= 0xE0 && b < 0xF0 && cont(1) && cont(2)) {
|
||||
c = ((b & 0x0F) << 12) | ((p[1] & 0x3F) << 6) | (p[2] & 0x3F);
|
||||
*len = 3;
|
||||
if (c < 0x800 || (c >= 0xD800 && c <= 0xDFFF)) { *len = 1; *ccc = kInvalidLen; return kChange; }
|
||||
} else if (b >= 0xF0 && b < 0xF5 && cont(1) && cont(2) && cont(3)) {
|
||||
c = ((b & 0x07) << 18) | ((p[1] & 0x3F) << 12) | ((p[2] & 0x3F) << 6) | (p[3] & 0x3F);
|
||||
*len = 4;
|
||||
if (c < 0x10000 || c > 0x10FFFF) { *len = 1; *ccc = kInvalidLen; return kChange; }
|
||||
} else {
|
||||
*len = 1;
|
||||
*ccc = kInvalidLen;
|
||||
return kChange;
|
||||
}
|
||||
if (get(not_yes_, c)) { *ccc = get(marked_, c) ? unorm_ccc(c) : 0; return kChange; }
|
||||
if (!get(marked_, c)) return kBoundary;
|
||||
*ccc = unorm_ccc(c);
|
||||
return *ccc ? kKeep : kBoundary;
|
||||
}
|
||||
|
||||
std::vector<uint64_t> not_yes_; /* NFC_QC is No or Maybe */
|
||||
std::vector<uint64_t> marked_; /* canonical combining class is not 0 */
|
||||
};
|
||||
|
||||
} /* namespace */
|
||||
|
||||
bool tok_nfc(std::string& text) {
|
||||
static const NfcQuick q;
|
||||
return q.apply(text);
|
||||
}
|
||||
|
||||
} /* namespace rad */
|
||||
@@ -0,0 +1,13 @@
|
||||
/* 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. */
|
||||
#pragma once
|
||||
#include <string>
|
||||
|
||||
namespace rad {
|
||||
|
||||
/* Normalise `text` in place. False when it was already NFC and has not been touched. */
|
||||
bool tok_nfc(std::string& text);
|
||||
|
||||
} /* namespace rad */
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,91 @@
|
||||
/* tokenizer_regex.h -- the pre-tokeniser pattern compiler.
|
||||
*
|
||||
* 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:
|
||||
*
|
||||
* - 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.
|
||||
*
|
||||
* 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.
|
||||
*/
|
||||
#pragma once
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <vector>
|
||||
|
||||
namespace rad {
|
||||
|
||||
/* [begin, end) in bytes. */
|
||||
struct TokSpan { uint32_t begin, end; };
|
||||
|
||||
class TokRegex {
|
||||
public:
|
||||
~TokRegex();
|
||||
|
||||
/* RAD_OK, or RAD_E_UNSUPPORTED with `why` saying which construct at which byte. */
|
||||
static int compile(std::string_view pattern, std::unique_ptr<TokRegex>* out, std::string* why);
|
||||
|
||||
/* Every match Oniguruma's find_iter reports over `text`, appended in order. `text` must be
|
||||
* canonical UTF-8 (utf8_is_canonical); the tokeniser canonicalises before it splits. */
|
||||
void find_iter(std::string_view text, std::vector<TokSpan>& out) const;
|
||||
|
||||
/* The end of the leftmost-first match anchored at byte `pos`, or -1 when there is none. */
|
||||
int64_t match_at(std::string_view text, size_t pos) const;
|
||||
|
||||
const std::string& pattern() const { return pattern_; }
|
||||
size_t n_states() const;
|
||||
size_t n_classes() const;
|
||||
|
||||
private:
|
||||
TokRegex() = default;
|
||||
struct Dfa;
|
||||
std::string pattern_;
|
||||
std::unique_ptr<Dfa> dfa_;
|
||||
};
|
||||
|
||||
/* HuggingFace's SplitDelimiterBehavior, in the order VocabStep::iarg carries it. */
|
||||
enum TokSplitBehavior {
|
||||
TOK_SPLIT_REMOVED = 0, TOK_SPLIT_ISOLATED = 1, TOK_SPLIT_MERGED_PREV = 2,
|
||||
TOK_SPLIT_MERGED_NEXT = 3, TOK_SPLIT_CONTIGUOUS = 4,
|
||||
};
|
||||
|
||||
/* 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. */
|
||||
void tok_split(const TokRegex& re, std::string_view text, int behavior, bool invert,
|
||||
std::vector<TokSpan>& out, std::vector<TokSpan>& scratch);
|
||||
|
||||
/* NormalizedString::replace with a regex: every match replaced by `content`, verbatim. */
|
||||
void tok_replace(const TokRegex& re, std::string_view text, std::string_view content,
|
||||
std::string& out);
|
||||
|
||||
/* True when `s` decodes to codepoints and re-encodes to the same bytes under the tokeniser's
|
||||
* decoder: no invalid or truncated sequence, no overlong form, nothing above U+10FFFF. */
|
||||
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. */
|
||||
void utf8_canonicalize(std::string_view s, std::string& out);
|
||||
|
||||
} /* namespace rad */
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,49 @@
|
||||
/* 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)`.
|
||||
*/
|
||||
#pragma once
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
|
||||
namespace rad {
|
||||
namespace ucd {
|
||||
|
||||
/* General category, in the generator's order. */
|
||||
enum Gc : uint8_t {
|
||||
Lu, Ll, Lt, Lm, Lo, Mn, Mc, Me, Nd, Nl, No,
|
||||
Pc, Pd, Ps, Pe, Pi, Pf, Po, Sm, Sc, Sk, So,
|
||||
Zs, Zl, Zp, Cc, Cf, Cs, Co, Cn,
|
||||
kGcCount
|
||||
};
|
||||
|
||||
/* A run of one category, from `first` to the next run's `first`. */
|
||||
struct GcRun { uint32_t first; uint32_t gc; };
|
||||
struct CpRange { uint32_t first, last; };
|
||||
struct ScriptTable { const char* name; const CpRange* ranges; size_t n; };
|
||||
|
||||
extern const GcRun k_gc_runs[];
|
||||
extern const size_t k_gc_runs_n;
|
||||
extern const CpRange k_white_space[]; /* \s */
|
||||
extern const size_t k_white_space_n;
|
||||
extern const CpRange k_digit[]; /* \d */
|
||||
extern const size_t k_digit_n;
|
||||
extern const CpRange k_word[]; /* \w as an atom, and the word test of \b */
|
||||
extern const size_t k_word_n;
|
||||
extern const CpRange k_word_class[]; /* \w inside a bracket class */
|
||||
extern const size_t k_word_class_n;
|
||||
extern const ScriptTable k_scripts[];
|
||||
extern const size_t k_scripts_n;
|
||||
/* Case-folding orbits: each is its length followed by its members. */
|
||||
extern const uint32_t k_case_orbits[];
|
||||
extern const size_t k_case_orbits_n;
|
||||
/* Codepoints that (?i) also matches against a multi-codepoint sequence. */
|
||||
extern const uint32_t k_case_multi[];
|
||||
extern const size_t k_case_multi_n;
|
||||
|
||||
} /* namespace ucd */
|
||||
} /* namespace rad */
|
||||
@@ -0,0 +1,161 @@
|
||||
#include "text/unicode_norm.h"
|
||||
#include "llama/src/unicode.h"
|
||||
|
||||
#include <algorithm>
|
||||
|
||||
namespace rad {
|
||||
|
||||
/* Hangul, per UAX #15. 11172 syllables that would otherwise be 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. */
|
||||
size_t lo = 0, hi = k_ccc_n;
|
||||
while (lo < hi) {
|
||||
size_t mid = (lo + hi) / 2;
|
||||
if (cpt < k_ccc[mid].first) hi = mid;
|
||||
else if (cpt > k_ccc[mid].last) lo = mid + 1;
|
||||
else return k_ccc[mid].ccc;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
static const DecompRow* decomp_row(uint32_t cpt) {
|
||||
size_t lo = 0, hi = k_decomp_rows_n;
|
||||
while (lo < hi) {
|
||||
size_t mid = (lo + hi) / 2;
|
||||
if (cpt < k_decomp_rows[mid].cpt) hi = mid;
|
||||
else if (cpt > k_decomp_rows[mid].cpt) lo = mid + 1;
|
||||
else return &k_decomp_rows[mid];
|
||||
}
|
||||
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. */
|
||||
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]);
|
||||
if (ccc_i == 0) continue;
|
||||
size_t j = i;
|
||||
while (j > 0) {
|
||||
const uint32_t ccc_p = unorm_ccc(v[j - 1]);
|
||||
if (ccc_p == 0 || ccc_p <= ccc_i) break;
|
||||
std::swap(v[j], v[j - 1]);
|
||||
--j;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void unorm_decompose(std::vector<uint32_t>& cpts, bool compat) {
|
||||
std::vector<uint32_t> out;
|
||||
out.reserve(cpts.size() + cpts.size() / 4);
|
||||
for (uint32_t c : cpts) {
|
||||
if (c - k_s_base < k_s_count) { /* Hangul syllable */
|
||||
const uint32_t s = c - k_s_base;
|
||||
out.push_back(k_l_base + s / k_n_count);
|
||||
out.push_back(k_v_base + (s % k_n_count) / k_t_count);
|
||||
const uint32_t t = s % k_t_count;
|
||||
if (t) out.push_back(k_t_base + t);
|
||||
continue;
|
||||
}
|
||||
const DecompRow* r = decomp_row(c);
|
||||
/* The pool holds fully-expanded sequences, so this is one lookup and not a fixed point.
|
||||
* 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);
|
||||
if (!r || len == 0) { out.push_back(c); continue; }
|
||||
for (uint32_t i = 0; i < len; ++i) out.push_back(k_decomp_pool[off + i]);
|
||||
}
|
||||
canonical_order(out);
|
||||
cpts.swap(out);
|
||||
}
|
||||
|
||||
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. */
|
||||
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;
|
||||
}
|
||||
if (a - k_s_base < k_s_count && (a - k_s_base) % k_t_count == 0 &&
|
||||
b - k_t_base < k_t_count && b != k_t_base) {
|
||||
*out = a + (b - k_t_base);
|
||||
return true;
|
||||
}
|
||||
size_t lo = 0, hi = k_compose_n;
|
||||
while (lo < hi) {
|
||||
size_t mid = (lo + hi) / 2;
|
||||
const ComposeRow& r = k_compose[mid];
|
||||
if (a < r.a || (a == r.a && b < r.b)) hi = mid;
|
||||
else if (a > r.a || (a == r.a && b > r.b)) lo = mid + 1;
|
||||
else { *out = r.c; return true; }
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/* Canonical composition, UAX #15 D117. Input must already be in NFD/NFKD order. */
|
||||
void unorm_compose(std::vector<uint32_t>& cpts) {
|
||||
if (cpts.empty()) return;
|
||||
std::vector<uint32_t> out;
|
||||
out.reserve(cpts.size());
|
||||
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. */
|
||||
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. */
|
||||
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;
|
||||
continue; /* last_ccc unchanged: the pair collapsed */
|
||||
}
|
||||
out.push_back(c);
|
||||
if (ccc == 0) { starter = out.size() - 1; have_starter = true; }
|
||||
last_ccc = ccc;
|
||||
}
|
||||
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. */
|
||||
bool ascii = true;
|
||||
for (unsigned char ch : in) { if (ch >= 0x80) { ascii = false; break; } }
|
||||
if (ascii) return in;
|
||||
|
||||
std::vector<uint32_t> cpts = unicode_cpts_from_utf8(in);
|
||||
unorm_decompose(cpts, compat);
|
||||
if (compose) unorm_compose(cpts);
|
||||
std::string out;
|
||||
out.reserve(in.size());
|
||||
for (uint32_t c : cpts) out += unicode_cpt_to_utf8(c);
|
||||
return out;
|
||||
}
|
||||
|
||||
} /* namespace rad */
|
||||
@@ -0,0 +1,47 @@
|
||||
/* 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.
|
||||
*/
|
||||
#pragma once
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace rad {
|
||||
|
||||
/* One codepoint's decomposition. `off_*`/`len_*` index k_decomp_pool; a zero `len` means the
|
||||
* codepoint has no decomposition of that kind and stands for itself. */
|
||||
struct DecompRow { uint32_t cpt, off_c, len_c, off_k, len_k; };
|
||||
struct ComposeRow { uint32_t a, b, c; };
|
||||
struct CccRow { uint32_t first, last; uint32_t ccc; };
|
||||
|
||||
extern const uint32_t k_decomp_pool[];
|
||||
extern const size_t k_decomp_pool_n;
|
||||
extern const DecompRow k_decomp_rows[];
|
||||
extern const size_t k_decomp_rows_n;
|
||||
extern const ComposeRow k_compose[];
|
||||
extern const size_t k_compose_n;
|
||||
extern const CccRow k_ccc[];
|
||||
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. */
|
||||
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. */
|
||||
std::string unorm_utf8(const std::string& in, bool compat, bool compose);
|
||||
|
||||
} /* namespace rad */
|
||||
File diff suppressed because it is too large.
Load diff
Reference in new issue
Block a user