Archived
radiance 2.0.0
Radiance becomes a multi-model engine: one process serves several models behind one port, loads each when a request names it, parks it in host memory or restores it from its container, and shares the cards between them (docs/MULTIMODEL.md). The configuration is one YAML file; the command line flags are gone (`radiance --config FILE`, hot reload on SIGHUP). Formats. IQ8R (rotated int8) and IQR-V4 replace FP8 and MXFP4 as whole-model formats, with an int8 KV cache (`kv-cache-dtype: i8`) in place of the fp8 one. Containers whose weights are block FP8, MXFP4, M2XFP4, NVFP4 or ParoQuant are refused at startup by the name of the first such weight. Not served until they have int8 containers: GLM-5.3-Flash, Ornith-1.5, Sage-A1.5, Nemotron-3.5-Bolt-74B, Ling-3.0-flash, drama-3 and Anima's FP8 container; Nemotron-3.5-Bolt-E4B, the Gemma 4 31B DFlash containers and MiniCPM5-2B bf16 serve without their drafter. 1.17.0 serves all of them. Speed. Chained launches for Qwen3.8-27B, Gemma 4, Gemma 3 and the small bf16 models, a new Qwen3.8-Flash-Next container (IQR-V4 experts, int8 trunk) with its decode step and prefill reworked, and a reworked adaptive draft window. Deployment. deploy/compose has two fleet files, tp1.yaml and tp2.yaml, each with its configuration beside it, in place of the per-model files. `host-pool-mib` is a model's host pool in all, split among its ranks. The dashboard is rebuilt: an hour of history kept by the server, each accelerator's memory by model, model states over time. Merged since 1.17.0: Nemotron-3.5-Bolt-74B-A9B by keptn42 (#339); GLM-5.3-Flash on four cards by AnimusNull (#397); chained launches for Flash-Next's decode step (#396) and preempted requests keeping their prefix and place (#405) by mici81; --prefill-interleave auto by Code000 (#410); eight more libr3d kernels and the w4a4 reference by RikshaDriver (#403, #407, #408); libr3d large-BAR and E4M3 decode fixes by neuromanMD (#438, #439); int4/int5 decode tiles by Kezi (#426); attention for Nanbeige 4.3 33B by everplays (#417); expert_stats_report.py by baKon (#431). Fixed: #398, #402, #419, #437 (dschmitz's patch); added the metrics of #392, and multi-model serving as asked for in #367 and #109. Plugin ABI 39: out-of-tree plugins need to be rebuilt. Thanks to @keptn42, @AnimusNull, @mici81, @Code000, @RikshaDriver, @neuromanMD, @Kezi, @everplays, @baKon and @dschmitz.
This commit is contained in:
1 parent
b4c04b6042
commit
ddcb9c69bb
696 files changed
+120770
-56596
No files matched your search
+163
-5
@@ -7,7 +7,7 @@
|
||||
#include "llama/common/jinja/runtime.h"
|
||||
#include "shim/log.h"
|
||||
|
||||
#include <nlohmann/json.hpp>
|
||||
#include "util/json.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <atomic>
|
||||
@@ -15,7 +15,7 @@
|
||||
|
||||
namespace rad {
|
||||
|
||||
using ojson = nlohmann::ordered_json;
|
||||
using ojson = Json;
|
||||
|
||||
struct ChatTemplate::Impl {
|
||||
common_chat_templates_ptr tmpls;
|
||||
@@ -99,6 +99,11 @@ int ChatTemplate::load(const std::string& jinja_source, const std::string& bos,
|
||||
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);
|
||||
impl_->caps.probe_error = common_chat_templates_get_probe_error(impl_->tmpls.get());
|
||||
if (!impl_->caps.tools && !impl_->caps.probe_error.empty())
|
||||
RAD_WARN("chat: the template's tool capability probe failed (%s), so tools are off. A "
|
||||
"template that declares tools and fails here calls something this engine lacks",
|
||||
impl_->caps.probe_error.c_str());
|
||||
|
||||
/* The thinking probe is the first full render, through the reply-format analysis every render
|
||||
* runs. A template that compiles but cannot render a one-message conversation there (it calls
|
||||
@@ -192,6 +197,153 @@ static bool lead_system(const ojson& messages, ojson* out) {
|
||||
return true;
|
||||
}
|
||||
|
||||
/* One thing, several names: an assistant turn's reasoning, replayed with the history.
|
||||
* The templates (and the lifted parser) read `reasoning_content`; vLLM and its router
|
||||
* canonicalise it to `reasoning`, OpenRouter may carry it only in `reasoning_details`,
|
||||
* and Anthropic-shaped histories use a `thinking` field or content part. Fill the
|
||||
* canonical field from whichever spelling a message carries -- with the details' text
|
||||
* preferred over their summary, never both, and encrypted details unrecoverable -- so
|
||||
* the reasoning is rendered (and tokenised) exactly as the turn was generated. Dropped,
|
||||
* the history would differ from the cached prefix at every reasoning turn and the model
|
||||
* would not see its own earlier reasoning. A null `reasoning_content` is absent (the
|
||||
* serializers beside a router emit one routinely), and a non-string alias is not
|
||||
* reasoning text (other APIs use the names for a flag or an effort object) and is left
|
||||
* alone. The same pass rewrites the other spellings the lifted parser refuses: text
|
||||
* parts named for the Responses API, and replayed tool calls left flat or without their
|
||||
* defaults. Returns false when nothing needed changing. */
|
||||
static bool alias_reasoning(const ojson& messages, ojson* out) {
|
||||
if (!messages.is_array()) return false;
|
||||
auto str_of = [](const ojson& o, const char* k) -> std::string {
|
||||
if (!o.is_object()) return "";
|
||||
const auto it = o.find(k);
|
||||
return it != o.end() && it->is_string() ? it->get<std::string>() : "";
|
||||
};
|
||||
auto details_text = [&](const ojson& m) -> std::string {
|
||||
const auto it = m.find("reasoning_details");
|
||||
if (it == m.end()) return "";
|
||||
std::string text, summary;
|
||||
auto take = [&](const ojson& d) {
|
||||
if (!d.is_object()) return;
|
||||
const std::string type = str_of(d, "type");
|
||||
if (type.find("summary") != std::string::npos) summary += str_of(d, "summary");
|
||||
else if (type.find("encrypted") == std::string::npos) text += str_of(d, "text");
|
||||
};
|
||||
if (it->is_array()) for (const ojson& d : *it) take(d);
|
||||
else take(*it);
|
||||
return !text.empty() ? text : summary;
|
||||
};
|
||||
auto is_reasoning_part = [](const std::string& type) {
|
||||
return type == "thinking" || type == "reasoning" || type == "reasoning_text" ||
|
||||
type == "redacted_thinking";
|
||||
};
|
||||
auto part_text = [&](const ojson& p) -> std::string {
|
||||
for (const char* k : { "thinking", "text", "reasoning", "reasoning_content", "summary" }) {
|
||||
const std::string v = str_of(p, k);
|
||||
if (!v.empty()) return v;
|
||||
}
|
||||
const auto c = p.find("content");
|
||||
if (c != p.end() && c->is_string()) return c->get<std::string>();
|
||||
if (c != p.end() && c->is_array()) {
|
||||
std::string t;
|
||||
for (const ojson& q : *c) t += str_of(q, "text");
|
||||
return t;
|
||||
}
|
||||
return "";
|
||||
};
|
||||
auto alias_of = [&](const ojson& m) -> std::string {
|
||||
if (!m.is_object()) return "";
|
||||
std::string v = str_of(m, "reasoning");
|
||||
if (v.empty()) v = str_of(m, "thinking");
|
||||
if (v.empty()) v = details_text(m);
|
||||
if (v.empty()) {
|
||||
const auto c = m.find("content");
|
||||
if (c != m.end() && c->is_array())
|
||||
for (const ojson& p : *c)
|
||||
if (is_reasoning_part(str_of(p, "type"))) v += part_text(p);
|
||||
}
|
||||
return v;
|
||||
};
|
||||
auto needs = [&](const ojson& m) {
|
||||
if (!m.is_object()) return false;
|
||||
const auto rc = m.find("reasoning_content");
|
||||
const bool canonical = rc != m.end() && rc->is_string() &&
|
||||
!rc->get_ref<const std::string&>().empty();
|
||||
if (rc != m.end() && rc->is_null()) return true;
|
||||
if (!canonical && !alias_of(m).empty()) return true;
|
||||
const auto c = m.find("content");
|
||||
if (c != m.end() && c->is_array())
|
||||
for (const ojson& p : *c) {
|
||||
const std::string type = str_of(p, "type");
|
||||
if (type == "input_text" || type == "output_text" || is_reasoning_part(type))
|
||||
return true;
|
||||
}
|
||||
const auto tc = m.find("tool_calls");
|
||||
if (tc != m.end() && tc->is_array())
|
||||
for (const ojson& call : *tc) {
|
||||
if (!call.is_object()) continue;
|
||||
const auto fn = call.find("function");
|
||||
if (!call.contains("type") || fn == call.end() || !fn->is_object() ||
|
||||
!fn->contains("arguments") || fn->at("arguments").is_null())
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
};
|
||||
bool any = false;
|
||||
for (const ojson& m : messages) any = any || needs(m);
|
||||
if (!any) return false;
|
||||
*out = messages;
|
||||
for (ojson& m : *out) {
|
||||
if (!m.is_object() || !needs(m)) continue;
|
||||
std::string extracted;
|
||||
if (auto c = m.find("content"); c != m.end() && c->is_array()) {
|
||||
ojson parts = ojson::array();
|
||||
for (const ojson& p : *c) {
|
||||
const std::string type = str_of(p, "type");
|
||||
if (is_reasoning_part(type)) {
|
||||
extracted += part_text(p);
|
||||
continue;
|
||||
}
|
||||
ojson part = p;
|
||||
if (type == "input_text" || type == "output_text") part["type"] = "text";
|
||||
parts.push_back(std::move(part));
|
||||
}
|
||||
m["content"] = parts.empty() ? ojson("") : std::move(parts);
|
||||
}
|
||||
const auto rc = m.find("reasoning_content");
|
||||
const bool canonical = rc != m.end() && rc->is_string() &&
|
||||
!rc->get_ref<const std::string&>().empty();
|
||||
if (rc != m.end() && rc->is_null()) m.erase("reasoning_content");
|
||||
if (!canonical) {
|
||||
std::string v = alias_of(m);
|
||||
if (v.empty()) v = extracted;
|
||||
if (!v.empty()) m["reasoning_content"] = v;
|
||||
}
|
||||
if (auto tc = m.find("tool_calls"); tc != m.end() && tc->is_array())
|
||||
for (ojson& call : *tc) {
|
||||
if (!call.is_object()) continue;
|
||||
if (!call.contains("type") || call.at("type").is_null())
|
||||
call["type"] = "function";
|
||||
auto fn = call.find("function");
|
||||
if (fn == call.end() || !fn->is_object()) {
|
||||
if (call.contains("name") && call.at("name").is_string()) {
|
||||
ojson f = ojson::object();
|
||||
f["name"] = call.at("name");
|
||||
f["arguments"] = call.contains("arguments") &&
|
||||
!call.at("arguments").is_null()
|
||||
? call.at("arguments")
|
||||
: ojson("{}");
|
||||
call["function"] = std::move(f);
|
||||
call.erase("name");
|
||||
call.erase("arguments");
|
||||
}
|
||||
} else if (!fn->contains("arguments") || fn->at("arguments").is_null()) {
|
||||
(*fn)["arguments"] = "{}";
|
||||
}
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
int ChatTemplate::apply(const ojson& messages, const ojson& tools, const ChatOptions& opt,
|
||||
ChatPrompt* out) const {
|
||||
if (!ready()) {
|
||||
@@ -214,9 +366,12 @@ int ChatTemplate::apply(const ojson& messages, const ojson& tools, const ChatOpt
|
||||
}
|
||||
}
|
||||
|
||||
ojson aliased;
|
||||
const ojson& msgs = alias_reasoning(messages, &aliased) ? aliased : messages;
|
||||
|
||||
common_chat_templates_inputs in;
|
||||
try {
|
||||
in.messages = common_chat_msgs_parse_oaicompat(messages);
|
||||
in.messages = common_chat_msgs_parse_oaicompat(msgs);
|
||||
if (tools.is_array() && !tools.empty())
|
||||
in.tools = common_chat_tools_parse_oaicompat(tools);
|
||||
in.tool_choice = common_chat_tool_choice_parse_oaicompat(opt.tool_choice);
|
||||
@@ -228,7 +383,10 @@ int ChatTemplate::apply(const ojson& messages, const ojson& tools, const ChatOpt
|
||||
}
|
||||
if (!in.tools.empty() && !impl_->caps.tools) {
|
||||
RAD_WARN("chat: the model's template declares no tool support; request refused");
|
||||
out->error = "this model's chat template declares no tool support";
|
||||
out->error = impl_->caps.probe_error.empty()
|
||||
? "this model's chat template declares no tool support"
|
||||
: "this model's chat template failed the tool capability probe: " +
|
||||
impl_->caps.probe_error;
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
|
||||
@@ -257,7 +415,7 @@ int ChatTemplate::apply(const ojson& messages, const ojson& tools, const ChatOpt
|
||||
* merged into one at the head. Anything else the template refuses is the request's. */
|
||||
ojson merged;
|
||||
bool served = false;
|
||||
if (lead_system(messages, &merged)) {
|
||||
if (lead_system(msgs, &merged)) {
|
||||
try {
|
||||
in.messages = common_chat_msgs_parse_oaicompat(merged);
|
||||
p = common_chat_templates_apply(impl_->tmpls.get(), in);
|
||||
|
||||
+6
-2
@@ -23,7 +23,7 @@
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include <nlohmann/json_fwd.hpp>
|
||||
#include "util/json.h"
|
||||
|
||||
namespace rad {
|
||||
|
||||
@@ -41,6 +41,10 @@ struct ChatCaps {
|
||||
bool string_content = true;
|
||||
bool typed_content = false;
|
||||
bool object_arguments = false;
|
||||
/* What the first probe render with tools threw, empty when none did. The probe ignores
|
||||
* exceptions, so a template that calls something the engine lacks reports `tools` false as a
|
||||
* template without tool support does; this is the difference. */
|
||||
std::string probe_error;
|
||||
};
|
||||
|
||||
struct ChatOptions {
|
||||
@@ -111,7 +115,7 @@ public:
|
||||
* Returns RAD_OK, RAD_E_INVAL when the request does not parse, or RAD_E_UNSUPPORTED when the
|
||||
* template refuses it (e.g. a system message without a system role, or tools without tool
|
||||
* support). */
|
||||
int apply(const nlohmann::ordered_json& messages, const nlohmann::ordered_json& tools,
|
||||
int apply(const Json& messages, const Json& tools,
|
||||
const ChatOptions& opt, ChatPrompt* out) const;
|
||||
|
||||
/* The ChatML fallback, named so the server can report which template it runs. */
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
#include "llama/common/json-schema-to-grammar.h"
|
||||
#include "shim/log.h"
|
||||
|
||||
#include <nlohmann/json.hpp>
|
||||
#include "util/json.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cctype>
|
||||
@@ -23,7 +23,7 @@
|
||||
|
||||
namespace rad {
|
||||
|
||||
using ojson = nlohmann::ordered_json;
|
||||
using ojson = Json;
|
||||
|
||||
namespace {
|
||||
|
||||
@@ -47,7 +47,7 @@ bool confusable(const std::string& a, const std::string& b) {
|
||||
return a.starts_with(b) || b.starts_with(a) || occurs_inside(a, b) || occurs_inside(b, a);
|
||||
}
|
||||
|
||||
std::string show(const std::string& s) { return nlohmann::json(s).dump(); }
|
||||
std::string show(const std::string& s) { return Json(s).dump(); }
|
||||
|
||||
int refuse(std::string* why, const std::string& s) {
|
||||
if (why) *why = s;
|
||||
|
||||
+4
-4
@@ -47,7 +47,7 @@
|
||||
#pragma once
|
||||
#include "rad_internal.h"
|
||||
|
||||
#include <nlohmann/json_fwd.hpp>
|
||||
#include "util/json.h"
|
||||
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
@@ -185,8 +185,8 @@ std::string chat_format_describe(const ChatFormat& f);
|
||||
* the whole reply. Rule names and structure follow the vendored generator, so both produce the
|
||||
* same grammar for a template-analysed format. */
|
||||
struct ChatGrammarRequest {
|
||||
const nlohmann::ordered_json* tools = nullptr; /* the request's tools, or null */
|
||||
const nlohmann::ordered_json* json_schema = nullptr; /* a response format's schema, or null */
|
||||
const Json* tools = nullptr; /* the request's tools, or null */
|
||||
const 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" */
|
||||
@@ -204,7 +204,7 @@ struct ChatGrammar {
|
||||
|
||||
/* A tool the grammar and the reply parser both read, {"type":"function","function":{...}}; both
|
||||
* skip any other. */
|
||||
bool chat_function_tool(const nlohmann::ordered_json& tool);
|
||||
bool chat_function_tool(const Json& tool);
|
||||
|
||||
/* RAD_OK, or RAD_E_INVAL with *why when a tool or schema cannot be expressed. */
|
||||
int chat_format_grammar(const ChatFormat& f, const ChatGrammarRequest& req, ChatGrammar* out,
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
* vendor/ runs while a reply is read. */
|
||||
#include "llama/common/json-schema-to-grammar.h"
|
||||
|
||||
#include <nlohmann/json.hpp>
|
||||
#include "util/json.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cctype>
|
||||
@@ -17,7 +17,7 @@
|
||||
|
||||
namespace rad {
|
||||
|
||||
using ojson = nlohmann::ordered_json;
|
||||
using ojson = Json;
|
||||
|
||||
namespace {
|
||||
|
||||
@@ -303,7 +303,7 @@ private:
|
||||
|
||||
/* ================================================================== JSON text helpers */
|
||||
|
||||
/* A string's JSON encoding without its quotes, byte for byte what nlohmann::json::dump writes:
|
||||
/* A string's JSON encoding without its quotes, byte for byte what Json::dump writes:
|
||||
* two-character escapes where JSON has one, \u00XX in lower-case hex for other control
|
||||
* characters, and everything else (DEL and UTF-8 included) verbatim. */
|
||||
void json_escape_into(std::string& out, const char* p, size_t n) {
|
||||
@@ -581,7 +581,7 @@ private:
|
||||
while (!v.empty() && is_ws((unsigned char)v.front())) v.remove_prefix(1);
|
||||
if (v.empty()) out += "null";
|
||||
else if (const char* lit = json_literal(v)) out += lit;
|
||||
else if (nlohmann::json::accept(v)) out.append(v.data(), v.size());
|
||||
else if (Json::accept(v)) out.append(v.data(), v.size());
|
||||
else out += json_quote(scalar_);
|
||||
scalar_.clear();
|
||||
}
|
||||
@@ -592,7 +592,7 @@ private:
|
||||
std::string j;
|
||||
j.reserve(cont_.size() + 8);
|
||||
normalise(cont_, j);
|
||||
if (partial || nlohmann::json::accept(j)) out += j;
|
||||
if (partial || Json::accept(j)) out += j;
|
||||
else out += json_quote(cont_);
|
||||
cont_.clear();
|
||||
}
|
||||
@@ -1667,7 +1667,7 @@ struct ReplyStream::Impl {
|
||||
const bool json = bare_txt.size() < kBareKeep && !v.empty() &&
|
||||
(v == "true" || v == "false" || v == "null" ||
|
||||
((v[0] == '-' || (v[0] >= '0' && v[0] <= '9')) &&
|
||||
nlohmann::json::accept(v)));
|
||||
Json::accept(v)));
|
||||
if (!json) lenient();
|
||||
}
|
||||
|
||||
@@ -2026,7 +2026,7 @@ struct ReplyStream::Impl {
|
||||
* surrogate escape, a vertical tab or form feed after the value). Such a value is read by the
|
||||
* grammar's other arm, as text, so the arguments stay JSON. */
|
||||
void json_value_done(std::string_view text) {
|
||||
begin_value_out(ValueOut::Raw, /*json=*/nlohmann::json::accept(text));
|
||||
begin_value_out(ValueOut::Raw, /*json=*/Json::accept(text));
|
||||
val.add(text.data(), text.size(), scratch);
|
||||
val.finish(false, scratch);
|
||||
flush_scratch();
|
||||
|
||||
@@ -50,7 +50,7 @@
|
||||
#pragma once
|
||||
#include "rad_internal.h"
|
||||
|
||||
#include <nlohmann/json_fwd.hpp>
|
||||
#include "util/json.h"
|
||||
|
||||
#include <cstdint>
|
||||
#include <memory>
|
||||
@@ -111,7 +111,7 @@ struct ReplyOptions {
|
||||
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;
|
||||
const 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. */
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
#include "text/tokenizer.h"
|
||||
#include "text/tokenizer_bpe.h"
|
||||
#include "util/simd.h"
|
||||
#include "text/tokenizer_grapheme.h"
|
||||
#include "text/tokenizer_nfc.h"
|
||||
#include "text/tokenizer_regex.h"
|
||||
@@ -956,6 +957,7 @@ struct EncodeScratch {
|
||||
std::string canon;
|
||||
std::vector<TokSpan> next, found, match;
|
||||
std::vector<BpeSym> syms;
|
||||
BpeMergeScratch merge;
|
||||
};
|
||||
|
||||
/* One Split step over every piece. The output pieces are canonical UTF-8: a piece that is not is
|
||||
@@ -1164,7 +1166,7 @@ void bpe_word(const TokEncoder& e, std::string_view w, std::vector<int32_t>& out
|
||||
i += len;
|
||||
}
|
||||
}
|
||||
bpe_merge(syms, e.merges);
|
||||
bpe_merge(syms, e.merges, sc.merge);
|
||||
if (whole >= 0 && known == 0) {
|
||||
const bool itself = syms.size() == 1 && syms[0].id == whole;
|
||||
e.self_merges[whole].store(itself ? 1 : 2, std::memory_order_relaxed);
|
||||
@@ -1787,7 +1789,9 @@ std::string utf8_sanitize(std::string_view s) {
|
||||
auto flush_good = [&] { out.append(s.data() + good, i - good); good = i; };
|
||||
|
||||
while (i < n) {
|
||||
if ((unsigned char)s[i] < 0x80) { ++i; continue; }
|
||||
/* ASCII is copied verbatim either way, so jump straight to the next non-ASCII byte
|
||||
* (simd::first_non_ascii) instead of testing bytes one at a time. */
|
||||
if ((unsigned char)s[i] < 0x80) { i += simd::first_non_ascii(s.data() + i, n - i); continue; }
|
||||
size_t part = 0;
|
||||
const size_t len = utf8_seq(s, i, &part);
|
||||
if (len) { i += len; continue; }
|
||||
@@ -1804,7 +1808,7 @@ std::string utf8_sanitize(std::string_view s) {
|
||||
size_t utf8_valid_prefix(std::string_view s) {
|
||||
size_t i = 0, part = 0;
|
||||
while (i < s.size()) {
|
||||
if ((unsigned char)s[i] < 0x80) { ++i; continue; }
|
||||
if ((unsigned char)s[i] < 0x80) { i += simd::first_non_ascii(s.data() + i, s.size() - i); continue; }
|
||||
const size_t len = utf8_seq(s, i, &part);
|
||||
if (!len) break;
|
||||
i += len;
|
||||
|
||||
@@ -225,7 +225,7 @@ private:
|
||||
|
||||
/* Replace every byte that is not part of a well-formed UTF-8 sequence with U+FFFD; well-formed
|
||||
* input is returned unchanged. A byte-fallback vocab can emit a byte no continuation completes
|
||||
* (`<0xC1>` only starts overlong, never-legal encodings), and nlohmann::json::dump throws
|
||||
* (`<0xC1>` only starts overlong, never-legal encodings), and Json::dump throws
|
||||
* type_error.316 on it, failing the whole response. Such bytes cannot be held back, and dropping
|
||||
* them would hide that the model produced something undecodable. */
|
||||
std::string utf8_sanitize(std::string_view s);
|
||||
|
||||
+31
-19
@@ -1,7 +1,6 @@
|
||||
#include "text/tokenizer_bpe.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <queue>
|
||||
|
||||
namespace rad {
|
||||
|
||||
@@ -130,32 +129,39 @@ void merge_linear(std::vector<BpeSym>& syms, const MergeTable& merges) {
|
||||
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;
|
||||
}
|
||||
};
|
||||
void merge_heap(std::vector<BpeSym>& syms, const MergeTable& merges, BpeMergeScratch& sc) {
|
||||
using Node = BpeMergeScratch::Node;
|
||||
using Cand = BpeMergeScratch::Cand;
|
||||
const size_t n = syms.size();
|
||||
std::vector<Node> node(n);
|
||||
std::vector<Cand>& heap = sc.heap;
|
||||
heap.clear();
|
||||
/* Bulk-build the initial heap: candidates all carry the nodes' initial version, so they can
|
||||
* be collected before the node array exists, and a word with no merging pair returns without
|
||||
* allocating or initialising it. make_heap is linear where pushing every pair is n log n. */
|
||||
for (size_t i = 0; i + 1 < n; ++i) {
|
||||
int32_t m = -1;
|
||||
const uint32_t rank = merges.find(syms[i].id, syms[i + 1].id, &m);
|
||||
if (rank != UINT32_MAX)
|
||||
heap.push_back({ rank, (uint32_t)i, (uint32_t)(i + 1), 0, 0, m });
|
||||
}
|
||||
if (heap.empty()) return;
|
||||
std::make_heap(heap.begin(), heap.end());
|
||||
std::vector<Node>& node = sc.nodes;
|
||||
node.resize(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 });
|
||||
heap.push_back({ rank, (uint32_t)l, (uint32_t)r, node[l].ver, node[r].ver, m });
|
||||
std::push_heap(heap.begin(), heap.end());
|
||||
};
|
||||
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();
|
||||
const Cand c = heap.front();
|
||||
std::pop_heap(heap.begin(), heap.end());
|
||||
heap.pop_back();
|
||||
Node& l = node[c.left];
|
||||
Node& r = node[c.right];
|
||||
if (!l.alive || !r.alive || l.ver != c.vl || r.ver != c.vr) continue;
|
||||
@@ -176,10 +182,16 @@ void merge_heap(std::vector<BpeSym>& syms, const MergeTable& merges) {
|
||||
|
||||
} /* namespace */
|
||||
|
||||
void bpe_merge(std::vector<BpeSym>& syms, const MergeTable& merges, bool force_heap) {
|
||||
void bpe_merge(std::vector<BpeSym>& syms, const MergeTable& merges, BpeMergeScratch& scratch,
|
||||
bool force_heap) {
|
||||
if (syms.size() < 2) return;
|
||||
if (syms.size() <= kBpeLinearMax && !force_heap) merge_linear(syms, merges);
|
||||
else merge_heap(syms, merges);
|
||||
else merge_heap(syms, merges, scratch);
|
||||
}
|
||||
|
||||
void bpe_merge(std::vector<BpeSym>& syms, const MergeTable& merges, bool force_heap) {
|
||||
BpeMergeScratch scratch;
|
||||
bpe_merge(syms, merges, scratch, force_heap);
|
||||
}
|
||||
|
||||
} /* namespace rad */
|
||||
@@ -103,8 +103,26 @@ 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;
|
||||
|
||||
/* Reusable storage for the heap merge's linked symbols and candidates. Long pre-tokens (URLs,
|
||||
* base64 and other unbroken runs) would otherwise allocate both arrays for every word in a call. */
|
||||
struct BpeMergeScratch {
|
||||
struct Node { int32_t prev, next; uint32_t ver; bool alive; };
|
||||
struct Cand {
|
||||
uint32_t rank, left, right, vl, vr;
|
||||
int32_t merged;
|
||||
/* std::*_heap 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;
|
||||
}
|
||||
};
|
||||
std::vector<Node> nodes;
|
||||
std::vector<Cand> heap;
|
||||
};
|
||||
|
||||
/* Merge `syms` in place until no adjacent pair has a rank. `force_heap` lets a test check that
|
||||
* both strategies agree. */
|
||||
void bpe_merge(std::vector<BpeSym>& syms, const MergeTable& merges, BpeMergeScratch& scratch,
|
||||
bool force_heap = false);
|
||||
void bpe_merge(std::vector<BpeSym>& syms, const MergeTable& merges, bool force_heap = false);
|
||||
|
||||
} /* namespace rad */
|
||||
@@ -13,7 +13,7 @@
|
||||
#include "text/tokenizer_regex.h"
|
||||
#include "text/gguf.h"
|
||||
|
||||
#include <nlohmann/json.hpp>
|
||||
#include "util/json.h"
|
||||
|
||||
#include <cstring>
|
||||
#include <fstream>
|
||||
@@ -22,7 +22,7 @@
|
||||
|
||||
namespace rad {
|
||||
|
||||
using json = nlohmann::json;
|
||||
using json = Json;
|
||||
|
||||
namespace {
|
||||
|
||||
@@ -388,11 +388,16 @@ int read_model(const json& m, VocabBuild& out, const char* origin, uint64_t id_l
|
||||
}
|
||||
max_id = std::max(max_id, id);
|
||||
}
|
||||
/* Two texts on one id: the byte-greatest one holds it, whatever the file's order, as when
|
||||
* the vocab was read through a key-sorted map. */
|
||||
out.tokens.assign((size_t)max_id + 1, std::string());
|
||||
std::vector<bool> taken((size_t)max_id + 1, false);
|
||||
for (auto it = vocab->begin(); it != vocab->end(); ++it) {
|
||||
int32_t id = 0;
|
||||
read_id(it.value(), id_limit, &id);
|
||||
out.tokens[(size_t)id] = it.key();
|
||||
std::string& slot = out.tokens[(size_t)id];
|
||||
if (!taken[(size_t)id] || slot < it.key()) slot = it.key();
|
||||
taken[(size_t)id] = true;
|
||||
}
|
||||
out.types.assign(out.tokens.size(), (uint8_t)RAD_TT_NORMAL);
|
||||
return RAD_OK;
|
||||
@@ -767,7 +772,7 @@ int interpret_tokenizer_json(const json& j, uint64_t id_limit, const char* origi
|
||||
int parse_tokenizer_json_buf(std::string_view text, const char* origin, VocabBuild& out) {
|
||||
json j;
|
||||
try {
|
||||
j = json::parse(text.begin(), text.end());
|
||||
j = json::parse(text);
|
||||
} catch (const std::exception& e) {
|
||||
RAD_ERR("%s: not valid JSON: %s", origin, e.what());
|
||||
return RAD_E_FORMAT;
|
||||
@@ -779,7 +784,7 @@ int parse_tokenizer_json_buf(std::string_view text, const char* origin, VocabBui
|
||||
* larger one, and the bound keeps the token table proportional to the input. */
|
||||
const uint64_t id_limit = text.size();
|
||||
|
||||
/* nlohmann throws on the first get<>() of a value with the wrong JSON type. The reader checks
|
||||
/* Json throws on the first get<>() of a value with the wrong JSON type. The reader checks
|
||||
* the shapes that decide where things are written; this turns any other mismatch into a
|
||||
* format error instead of std::terminate. */
|
||||
try {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
#include "text/tokenizer_nfc.h"
|
||||
#include "text/unicode_norm.h"
|
||||
#include "util/simd.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstring>
|
||||
@@ -47,11 +48,9 @@ public:
|
||||
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; }
|
||||
}
|
||||
/* ASCII codepoints are all boundaries: skip a run at vector width. */
|
||||
const size_t run = simd::first_non_ascii((const char*)p + i, n - i);
|
||||
if (run) { last = 0; boundary = i + run - 1; i += run; 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; }
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
#include "text/tokenizer_regex.h"
|
||||
#include "text/tokenizer_ucd.h"
|
||||
#include "rad_internal.h"
|
||||
#include "util/simd.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstring>
|
||||
@@ -994,6 +995,18 @@ struct TokRegex::Dfa {
|
||||
std::vector<uint32_t> start_after; /* start row after a codepoint of each class */
|
||||
bool uses_behind = false;
|
||||
|
||||
/* The same automaton with rows of 128, for the scan: trans_ascii is indexed by the byte
|
||||
* itself, so an ASCII step is one load in the state chain where the class table needs two
|
||||
* (byte -> class, then row + class). Shipped pre-tokeniser patterns determinise to tens of
|
||||
* states, so the byte table is tens of KiB; past the cap it is left empty and the class
|
||||
* tables serve. trans_cls is `trans` re-encoded to rows of 128 for the non-ASCII steps.
|
||||
* State 0 is the dead row in both encodings. */
|
||||
static constexpr uint32_t kAsciiRowsMax = 512;
|
||||
std::vector<uint32_t> trans_ascii; /* state * 128 + byte -> next state * 128 | kMatch */
|
||||
std::vector<uint32_t> trans_cls; /* state * ncls + class -> next state * 128 | kMatch */
|
||||
uint32_t start_text_a = 0;
|
||||
std::vector<uint32_t> start_after_a;
|
||||
|
||||
uint8_t ascii[128];
|
||||
std::vector<uint16_t> stage1; /* cp >> 8 -> block */
|
||||
std::vector<uint8_t> stage2; /* block * 256 + (cp & 255) -> class */
|
||||
@@ -1243,6 +1256,28 @@ int TokRegex::compile(std::string_view pattern, std::unique_ptr<TokRegex>* out,
|
||||
d->start_text *= d->ncls;
|
||||
for (uint32_t& t : d->start_after) t *= d->ncls;
|
||||
|
||||
/* The byte-indexed copy for the scan (Dfa::trans_ascii), converted once here where the
|
||||
* division back to state ids costs nothing. */
|
||||
if (kernels.size() <= Dfa::kAsciiRowsMax) {
|
||||
const uint32_t ns = (uint32_t)kernels.size(), nc = d->ncls;
|
||||
d->trans_cls.assign((size_t)ns * nc, 0);
|
||||
for (uint32_t s = 0; s < ns; ++s)
|
||||
for (uint32_t c = 0; c < nc; ++c) {
|
||||
const uint32_t t = d->trans[(size_t)s * nc + c];
|
||||
d->trans_cls[(size_t)s * nc + c] =
|
||||
((t & ~Dfa::kMatch) / nc) * 128u | (t & Dfa::kMatch);
|
||||
}
|
||||
d->trans_ascii.assign((size_t)ns * 128, 0);
|
||||
for (uint32_t s = 0; s < ns; ++s)
|
||||
for (uint32_t b = 0; b < 128; ++b)
|
||||
d->trans_ascii[(size_t)s * 128 + b] =
|
||||
d->trans_cls[(size_t)s * nc + d->ascii[b]];
|
||||
d->start_text_a = (d->start_text / nc) * 128u;
|
||||
d->start_after_a.assign(d->start_after.size(), 0);
|
||||
for (size_t c = 0; c < d->start_after.size(); ++c)
|
||||
d->start_after_a[c] = (d->start_after[c] / nc) * 128u;
|
||||
}
|
||||
|
||||
std::unique_ptr<TokRegex> re(new TokRegex());
|
||||
re->pattern_ = std::string(pattern);
|
||||
re->dfa_ = std::move(d);
|
||||
@@ -1254,10 +1289,29 @@ int64_t TokRegex::match_at(std::string_view text, size_t pos) const {
|
||||
const Dfa& d = *dfa_;
|
||||
const uint8_t* s = (const uint8_t*)text.data();
|
||||
const size_t n = text.size();
|
||||
uint32_t state = pos == 0 || !d.uses_behind ? d.start_text : d.start_after[d.prev_class(s, pos)];
|
||||
const uint32_t* trans = d.trans.data();
|
||||
int64_t best = -1;
|
||||
size_t q = pos;
|
||||
if (!d.trans_ascii.empty()) {
|
||||
/* Rows of 128: an ASCII byte indexes its transition directly. */
|
||||
uint32_t state = pos == 0 || !d.uses_behind ? d.start_text_a
|
||||
: d.start_after_a[d.prev_class(s, pos)];
|
||||
const uint32_t* ta = d.trans_ascii.data();
|
||||
const uint32_t* tc = d.trans_cls.data();
|
||||
while (q < n) {
|
||||
uint32_t len, t;
|
||||
const uint32_t b = s[q];
|
||||
if (b < 0x80) { t = ta[state + b]; len = 1; }
|
||||
else { t = tc[(state >> 7) * d.ncls + d.cls_of(decode_canon(s + q, &len))]; }
|
||||
if (t & Dfa::kMatch) best = (int64_t)q;
|
||||
state = t & ~Dfa::kMatch;
|
||||
if (state == 0) return best;
|
||||
q += len;
|
||||
}
|
||||
if (d.eoi_match[state >> 7]) best = (int64_t)n;
|
||||
return best;
|
||||
}
|
||||
uint32_t state = pos == 0 || !d.uses_behind ? d.start_text : d.start_after[d.prev_class(s, pos)];
|
||||
const uint32_t* trans = d.trans.data();
|
||||
while (q < n) {
|
||||
uint32_t len, cls;
|
||||
const uint32_t b = s[q];
|
||||
@@ -1277,6 +1331,74 @@ void TokRegex::find_iter(std::string_view text, std::vector<TokSpan>& out) const
|
||||
/* Oniguruma's iteration as the `onig` crate drives it: search from the end of the previous
|
||||
* match for the leftmost position with a match; an empty match exactly at the end of the
|
||||
* previous one is skipped by advancing one codepoint and searching again. */
|
||||
if (!dfa_->uses_behind) {
|
||||
/* Fused into one walk: the loop re-enters the DFA at every search position exactly as
|
||||
* the match_at loop below does -- same restarts, same rewalks of a dead run's tail,
|
||||
* same empty-match rule -- without a call and a fresh setup per piece, which at a piece
|
||||
* every few bytes was a visible share of splitting. The tag selects the byte-indexed
|
||||
* table (rows of 128) over the class table (rows of ncls); the state encoding differs,
|
||||
* hence the two instantiations. The decision at each death (or at the end of the text)
|
||||
* is the loop below's, word for word: e is what match_at(pos) would have returned. */
|
||||
const Dfa& d = *dfa_;
|
||||
auto run = [&](auto ascii_tag) {
|
||||
constexpr bool Ascii = decltype(ascii_tag)::value;
|
||||
const uint8_t* s = (const uint8_t*)text.data();
|
||||
const size_t n = text.size();
|
||||
const uint32_t* ta = Ascii ? d.trans_ascii.data() : d.trans.data();
|
||||
const uint32_t start = Ascii ? d.start_text_a : d.start_text;
|
||||
size_t pos = 0; /* search start */
|
||||
bool have_prev = false;
|
||||
size_t prev_end = 0;
|
||||
uint32_t state = start;
|
||||
int64_t best = -1; /* match end match_at(pos) would report so far */
|
||||
size_t q = 0; /* walk position */
|
||||
for (;;) {
|
||||
int64_t e;
|
||||
if (q < n) {
|
||||
uint32_t len, t;
|
||||
const uint32_t b = s[q];
|
||||
if (b < 0x80) {
|
||||
t = Ascii ? ta[state + b] : ta[state + d.ascii[b]];
|
||||
len = 1;
|
||||
} else if (Ascii) {
|
||||
t = d.trans_cls[(state >> 7) * d.ncls +
|
||||
d.cls_of(decode_canon(s + q, &len))];
|
||||
} else {
|
||||
t = ta[state + d.cls_of(decode_canon(s + q, &len))];
|
||||
}
|
||||
if (t & Dfa::kMatch) best = (int64_t)q;
|
||||
state = t & ~Dfa::kMatch;
|
||||
if (state != 0) { q += len; continue; }
|
||||
e = best; /* died: match_at(pos) returns here */
|
||||
} else {
|
||||
const uint32_t sid = Ascii ? state >> 7 : state / d.ncls;
|
||||
e = d.eoi_match[sid] ? (int64_t)n : best;
|
||||
}
|
||||
if (e >= 0 && !((size_t)e == pos && have_prev && prev_end == pos)) {
|
||||
out.push_back({ (uint32_t)pos, (uint32_t)e });
|
||||
have_prev = true;
|
||||
prev_end = (size_t)e;
|
||||
if ((size_t)e > pos) {
|
||||
pos = (size_t)e;
|
||||
q = pos;
|
||||
state = start;
|
||||
best = -1;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if (pos == n) break;
|
||||
uint32_t len;
|
||||
decode_canon(s + pos, &len);
|
||||
pos += len;
|
||||
q = pos;
|
||||
state = start;
|
||||
best = -1;
|
||||
}
|
||||
};
|
||||
if (!d.trans_ascii.empty()) run(std::true_type{});
|
||||
else run(std::false_type{});
|
||||
return;
|
||||
}
|
||||
const uint8_t* s = (const uint8_t*)text.data();
|
||||
const size_t n = text.size();
|
||||
size_t pos = 0;
|
||||
@@ -1391,13 +1513,10 @@ bool utf8_is_canonical(std::string_view str) {
|
||||
const size_t n = str.size();
|
||||
size_t i = 0;
|
||||
while (i < n) {
|
||||
if (i + 8 <= n) {
|
||||
uint64_t w;
|
||||
std::memcpy(&w, p + i, 8);
|
||||
if (!(w & 0x8080808080808080ull)) { i += 8; continue; }
|
||||
}
|
||||
/* ASCII is canonical as it stands: jump to the next non-ASCII byte. */
|
||||
i += simd::first_non_ascii((const char*)p + i, n - i);
|
||||
if (i >= n) break;
|
||||
const uint8_t b = p[i];
|
||||
if (b < 0x80) { ++i; continue; }
|
||||
if (b < 0xC2) return false; /* continuation, or overlong C0/C1 */
|
||||
if (b < 0xE0) {
|
||||
if (i + 1 >= n || (p[i + 1] & 0xC0) != 0x80) return false;
|
||||
|
||||
Reference in new issue
Block a user