Archived
Merge branch 'main' into fix-stage-drain
This commit is contained in:
commit
bcdc89eded
43 files changed
+3197
-157
No files matched your search
@@ -287,6 +287,7 @@ int meta_from_gguf(GgufFile& g, MetaOwn* out) {
|
||||
/* Dimensions come from GGUF's `<arch>.<field>` keys, so one plugin covers a family; other keys
|
||||
* pass through in the free-form list. */
|
||||
const std::string a = out->arch;
|
||||
if (a == "hy_v3") out->arch = "hyv3";
|
||||
auto gi = [&](const char* suffix, int64_t dflt) -> int64_t {
|
||||
int64_t v = 0;
|
||||
return g.get_i64(a + "." + suffix, &v) ? v : dflt;
|
||||
@@ -353,6 +354,36 @@ int meta_from_gguf(GgufFile& g, MetaOwn* out) {
|
||||
std::vector<std::string> toks;
|
||||
if (g.get_strs("tokenizer.ggml.tokens", &toks)) m.n_vocab = (int64_t)toks.size();
|
||||
if (m.n_vocab == 0) m.n_vocab = gi("vocab_size", 0);
|
||||
if (a == "hy_v3") {
|
||||
/* GGUF keeps reserved vocabulary rows beyond the tokenizer string array. The model matrices
|
||||
* are authoritative for the row count (Hy-Memory has 120832 rows and 120818 strings). */
|
||||
const GgufTensor* emb = g.tensor("token_embd.weight");
|
||||
if (emb && emb->n_dims >= 2) m.n_vocab = emb->ne[1];
|
||||
|
||||
int64_t gating = 0, norm = 0;
|
||||
double route_scale = 1.0;
|
||||
g.get_i64("hy_v3.expert_gating_func", &gating);
|
||||
g.get_i64("hy_v3.expert_weights_norm", &norm);
|
||||
g.get_f64("hy_v3.expert_weights_scale", &route_scale);
|
||||
const int64_t expert_width = gi("expert_feed_forward_length", 0);
|
||||
const int64_t shared_width = gi("expert_shared_feed_forward_length", 0);
|
||||
out->kv("qk_norm", g.tensor("blk.0.attn_q_norm.weight") &&
|
||||
g.tensor("blk.0.attn_k_norm.weight") ? "1" : "0");
|
||||
out->kv("moe_router_use_sigmoid", gating == 2 ? "1" : "0");
|
||||
out->kv("moe_router_enable_expert_bias", g.tensor("blk.1.exp_probs_b") ? "1" : "0");
|
||||
out->kv("enable_moe_fp32_combine", shared_width > 0 ? "1" : "0");
|
||||
out->kv("route_norm", norm ? "1" : "0");
|
||||
out->kv("router_scaling_factor", fmt("%.17g", route_scale));
|
||||
out->kv("first_k_dense_replace", g.tensor("blk.0.ffn_gate.weight") &&
|
||||
g.tensor("blk.1.ffn_gate_inp.weight") ? "1" : "0");
|
||||
out->kv("num_shared_experts", shared_width > 0 ? "1" : "0");
|
||||
out->kv("expert_hidden_dim", fmt("%lld", (long long)expert_width));
|
||||
out->kv("moe_intermediate_size", fmt("%lld", (long long)(2 * expert_width)));
|
||||
out->kv("num_experts", fmt("%lld", (long long)m.n_expert));
|
||||
out->kv("num_experts_per_tok", fmt("%lld", (long long)m.n_expert_used));
|
||||
out->kv("attention_bias", "0");
|
||||
out->kv("mlp_bias", "0");
|
||||
}
|
||||
|
||||
/* Everything else, stringified, for the plugin. Arrays are summarised (small integer arrays
|
||||
* spelled out); tokenizer keys are skipped, since the vocab has its own section. */
|
||||
@@ -859,6 +890,33 @@ int Checkpoint::open_safetensors(const std::string& path) {
|
||||
RAD_TRY(add_companions());
|
||||
RAD_TRY(add_torch_files());
|
||||
}
|
||||
/* HYV3's FP8 release indexes its static per-layer K/V cache descales as scalar F32 tensors in
|
||||
* kv_cache_scales.safetensors. They are runtime attention parameters, not model weights; carry
|
||||
* them through metadata so the architecture can bake them into kv_store and descale operands. */
|
||||
if (meta_.arch == "hyv3") {
|
||||
for (int64_t l = 0; l < meta_.m.n_layers; ++l) {
|
||||
for (const char* which : {"k", "v"}) {
|
||||
const std::string source = "model.layers." + std::to_string(l) +
|
||||
".self_attn." + which + "_cache.scale";
|
||||
const SrcTensor* t = find(source);
|
||||
if (!t) continue;
|
||||
if (t->rad_dtype != RAD_F32 || !t->data || t->bytes < 4 ||
|
||||
(!t->shape.empty() && t->numel() != 1)) {
|
||||
RAD_ERR("%s: HYV3 KV cache scale must be a scalar F32", source.c_str());
|
||||
return RAD_E_FORMAT;
|
||||
}
|
||||
float scale = 0.0f;
|
||||
std::memcpy(&scale, t->data, sizeof scale);
|
||||
if (!std::isfinite(scale) || scale <= 0.0f) {
|
||||
RAD_ERR("%s: HYV3 KV cache scale must be positive and finite", source.c_str());
|
||||
return RAD_E_FORMAT;
|
||||
}
|
||||
char value[32];
|
||||
std::snprintf(value, sizeof value, "%.9g", (double)scale);
|
||||
meta_.set("hyv3.kv_cache." + std::to_string(l) + "." + which + "_scale", value);
|
||||
}
|
||||
}
|
||||
}
|
||||
/* FP8's block, where the checkpoint states one. */
|
||||
if (const char* bs = meta_.get("quantization_config.weight_block_size")) {
|
||||
long long r = 0, c = 0;
|
||||
@@ -2302,9 +2360,9 @@ namespace {
|
||||
/* ---------------------------------------------------------------- GGUF block types
|
||||
*
|
||||
* ggml block types decodable to f32. Their geometry lives in core/text; decoding lives here, where
|
||||
* weights are read. K-quants are refused rather than half-implemented. */
|
||||
* weights are read. Q4_K and Q6_K are the K-quants this HYV3 GGUF adapter needs. */
|
||||
enum { GGML_F32 = 0, GGML_F16 = 1, GGML_Q4_0 = 2, GGML_Q4_1 = 3, GGML_Q5_0 = 6, GGML_Q5_1 = 7,
|
||||
GGML_Q8_0 = 8, GGML_BF16 = 30 };
|
||||
GGML_Q8_0 = 8, GGML_Q4_K = 12, GGML_Q6_K = 14, GGML_BF16 = 30 };
|
||||
|
||||
int ggml_rows_f32(uint32_t type, const uint8_t* p, int64_t n, float* dst) {
|
||||
auto half = [&](const uint8_t* q) { uint16_t h; std::memcpy(&h, q, 2); return rad_f16_to_f32(h); };
|
||||
@@ -2357,6 +2415,45 @@ int ggml_rows_f32(uint32_t type, const uint8_t* p, int64_t n, float* dst) {
|
||||
}
|
||||
}
|
||||
return RAD_OK;
|
||||
case GGML_Q4_K:
|
||||
for (int64_t b = 0; b < n / 256; ++b, p += 144) {
|
||||
const float d = half(p), dmin = half(p + 2);
|
||||
const uint8_t* scales = p + 4;
|
||||
const uint8_t* qs = p + 16;
|
||||
for (int j = 0; j < 8; ++j) {
|
||||
uint32_t sc, mn;
|
||||
if (j < 4) {
|
||||
sc = scales[j] & 63u;
|
||||
mn = scales[j + 4] & 63u;
|
||||
} else {
|
||||
sc = (scales[j + 4] & 15u) | ((uint32_t)(scales[j - 4] >> 6) << 4);
|
||||
mn = (scales[j + 4] >> 4) | ((uint32_t)(scales[j] >> 6) << 4);
|
||||
}
|
||||
const float ds = d * (float)sc, ms = dmin * (float)mn;
|
||||
for (int l = 0; l < 32; ++l) {
|
||||
const int v = j * 32 + l;
|
||||
const uint8_t q = qs[32 * (v / 64) + v % 32];
|
||||
const int code = (v % 64) < 32 ? q & 15 : q >> 4;
|
||||
dst[b * 256 + v] = ds * (float)code - ms;
|
||||
}
|
||||
}
|
||||
}
|
||||
return RAD_OK;
|
||||
case GGML_Q6_K:
|
||||
for (int64_t b = 0; b < n / 256; ++b, p += 210) {
|
||||
const uint8_t* ql = p;
|
||||
const uint8_t* qh = p + 128;
|
||||
const int8_t* scales = (const int8_t*)(p + 192);
|
||||
const float d = half(p + 208);
|
||||
for (int k = 0; k < 256; ++k) {
|
||||
const int n128 = k / 128, t = (k % 128) / 32, l = k % 32;
|
||||
const uint8_t lo = ql[64 * n128 + l + 32 * (t & 1)];
|
||||
const int code = (int)((t < 2 ? lo & 15 : lo >> 4) |
|
||||
(((qh[32 * n128 + l] >> (2 * t)) & 3) << 4));
|
||||
dst[b * 256 + k] = d * (float)scales[k / 16] * (float)(code - 32);
|
||||
}
|
||||
}
|
||||
return RAD_OK;
|
||||
default:
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
|
||||
+4
-3
@@ -119,10 +119,11 @@ int Driver::init(const Program& prog, IKVManager* kv, const std::vector<RankIO>&
|
||||
kv_ = kv;
|
||||
ranks_ = ranks;
|
||||
table_ = DiscreteTable{};
|
||||
if (decl_.cond_opts & ~(uint32_t)RAD_GEN_COND_REBALANCE) {
|
||||
if (decl_.cond_opts & ~(uint32_t)(RAD_GEN_COND_REBALANCE | RAD_GEN_COND_REBALANCE_PRESET)) {
|
||||
RAD_ERR("image generator: '%s' declares conditioning options 0x%x, and this engine knows "
|
||||
"only RAD_GEN_COND_REBALANCE (0x%x)", decl_.name ? decl_.name : "",
|
||||
(unsigned)decl_.cond_opts, (unsigned)RAD_GEN_COND_REBALANCE);
|
||||
"only RAD_GEN_COND_REBALANCE (0x%x) and its preset (0x%x)",
|
||||
decl_.name ? decl_.name : "", (unsigned)decl_.cond_opts, (unsigned)RAD_GEN_COND_REBALANCE,
|
||||
(unsigned)RAD_GEN_COND_REBALANCE_PRESET);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
if (discrete()) {
|
||||
|
||||
+25
-7
@@ -65,7 +65,7 @@ struct ImgReq {
|
||||
std::string background = "auto", format = "png", quality = "auto";
|
||||
int32_t compression = -1;
|
||||
bool stream = false;
|
||||
bool rebalance = false;
|
||||
int32_t rebalance = 0; /* RadGenBatch::cond_opts: RAD_GEN_COND_REBALANCE and its preset */
|
||||
std::vector<mm::FrameRGBA> images;
|
||||
bool has_mask = false;
|
||||
mm::FrameRGBA mask;
|
||||
@@ -397,15 +397,33 @@ HttpResponse Server::handle_images(const HttpRequest& req, bool edit) {
|
||||
r.seed = (uint64_t)body["seed"].get<int64_t>();
|
||||
r.seed_given = body["seed"].is_number_unsigned() || body["seed"].get<int64_t>() != -1;
|
||||
}
|
||||
/* The conditioning at the plugin's fixed rebalance gains (Krea 2: its text taps at
|
||||
* ConditioningKrea2Rebalance's defaults). `false` is accepted everywhere. */
|
||||
/* The conditioning at the plugin's fixed rebalance gains (Krea 2: its text taps). true or
|
||||
* "legacy" ConditioningKrea2Rebalance's defaults; "balanced", "detail", "subtle" the
|
||||
* comfyui-krea2-conditioning presets at the taps' RMS, on a model that declares presets
|
||||
* (RAD_GEN_COND_REBALANCE_PRESET). `false` is accepted everywhere. */
|
||||
if (body.contains("rebalance") && !body["rebalance"].is_null()) {
|
||||
if (!body["rebalance"].is_boolean())
|
||||
return error_response(err_bad("rebalance", "expected true or false"), req.peer);
|
||||
r.rebalance = body["rebalance"].get<bool>();
|
||||
const json& rb = body["rebalance"];
|
||||
static const char* const kPresets[] = { "legacy", "balanced", "detail", "subtle" };
|
||||
bool ok = rb.is_boolean();
|
||||
if (ok) r.rebalance = rb.get<bool>() ? RAD_GEN_COND_REBALANCE : 0;
|
||||
else if (rb.is_string())
|
||||
for (int i = 0; i < 4; ++i)
|
||||
if (rb.get<std::string>() == kPresets[i]) {
|
||||
r.rebalance = RAD_GEN_COND_REBALANCE | (i << RAD_GEN_COND_REBALANCE_PRESET_SHIFT);
|
||||
ok = true;
|
||||
}
|
||||
if (!ok)
|
||||
return error_response(err_bad("rebalance", "expected true, false, \"legacy\", "
|
||||
"\"balanced\", \"detail\" or \"subtle\""),
|
||||
req.peer);
|
||||
if (r.rebalance && !(info.cond_opts & RAD_GEN_COND_REBALANCE))
|
||||
return error_response(err_unsupported("rebalance", "this model has no rebalance"),
|
||||
req.peer);
|
||||
if ((r.rebalance & RAD_GEN_COND_REBALANCE_PRESET) &&
|
||||
!(info.cond_opts & RAD_GEN_COND_REBALANCE_PRESET))
|
||||
return error_response(err_unsupported("rebalance", "this model's rebalance has no "
|
||||
"presets; use true"),
|
||||
req.peer);
|
||||
}
|
||||
if (str("negative_prompt", &r.negative) < 0)
|
||||
return error_response(err_bad("negative_prompt", "expected a string"), req.peer);
|
||||
@@ -539,7 +557,7 @@ HttpResponse Server::handle_images(const HttpRequest& req, bool edit) {
|
||||
g->scheduler = r.scheduler;
|
||||
g->seed = r.seed;
|
||||
g->previews = r.previews;
|
||||
g->cond_opts = r.rebalance ? RAD_GEN_COND_REBALANCE : 0;
|
||||
g->cond_opts = r.rebalance;
|
||||
/* The driver guides as uncond + cfg (cond - uncond); a card's cond + s (cond - uncond) is
|
||||
* that at s + 1. */
|
||||
g->cfg = (float)(info.cfg_original ? r.cfg + 1.0 : r.cfg);
|
||||
|
||||
+36
-8
@@ -173,15 +173,34 @@ int chat_format_check(const ChatFormat& f, std::string* why) {
|
||||
return reasoning_anywhere_check(f, why);
|
||||
}
|
||||
|
||||
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.section_open.empty() != f.section_close.empty())
|
||||
return no("section_open and section_close must be set together");
|
||||
if (!f.section_open.empty()) {
|
||||
const std::string so = trim_ws(f.section_open), sc = trim_ws(f.section_close);
|
||||
if (so.empty() || sc.empty()) return no("section_open/section_close may not be whitespace");
|
||||
if (so != f.section_open || sc != f.section_close)
|
||||
return no("section_open/section_close must not have surrounding whitespace");
|
||||
if (confusable(so, sc))
|
||||
return no("section_open " + show(so) + " and section_close " + show(sc) +
|
||||
" cannot be told apart");
|
||||
for (const std::string* d : { &f.reasoning_open, &f.reasoning_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 }) {
|
||||
if (!d->empty() && confusable(so, trim_ws(*d)))
|
||||
return no("section_open " + show(so) + " overlaps delimiter " + show(*d));
|
||||
if (!d->empty() && confusable(sc, trim_ws(*d)))
|
||||
return no("section_close " + show(sc) + " overlaps delimiter " + show(*d));
|
||||
}
|
||||
}
|
||||
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");
|
||||
const bool object = f.object_args();
|
||||
if (object && !f.section_open.empty())
|
||||
return no("section-wrapped object arguments are not supported");
|
||||
/* Without a suffix the name ends at what follows it: the object's `{`, or a tagged call's
|
||||
* first argument or close. */
|
||||
if (!f.name_suffix.empty()) {
|
||||
@@ -238,9 +257,10 @@ int chat_format_check(const ChatFormat& f, std::string* why) {
|
||||
show(f.name_prefix) + " cannot be told apart");
|
||||
}
|
||||
const std::string opener = f.call_open.empty() ? f.name_prefix : f.call_open;
|
||||
const std::string section_opener = trim_ws(f.section_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 (b != opener && (section_opener.empty() || b != section_opener))
|
||||
return no("reasoning break " + show(b) + " is not a call or section opener");
|
||||
if (!f.reasoning_breaks.empty() && !f.has_reasoning())
|
||||
return no("reasoning_breaks without a reasoning block");
|
||||
for (const std::string& t : f.triggers)
|
||||
@@ -432,6 +452,8 @@ std::string chat_format_describe(const ChatFormat& f) {
|
||||
(f.reasoning_anywhere ? " anywhere" : "");
|
||||
else
|
||||
s += " no reasoning";
|
||||
if (f.has_tools() && !f.section_open.empty())
|
||||
s += "; section " + show(f.section_open) + ".." + show(f.section_close);
|
||||
if (f.has_tools() && f.object_args()) {
|
||||
s += "; calls " + show(f.call_open) + show(f.name_prefix) + "NAME" + show(f.name_suffix) +
|
||||
" {OBJECT";
|
||||
@@ -912,11 +934,17 @@ int chat_format_grammar(const ChatFormat& f, const ChatGrammarRequest& req, Chat
|
||||
? seq({ wrapped, rep(seq({ space(), wrapped }), 0, -1), space() })
|
||||
: seq({ wrapped, space() });
|
||||
} else {
|
||||
G next = seq({ space(), opt(wrap(leaf(until_pattern({ opener })))), choice });
|
||||
/* Section-wrapped dialects contain only calls and whitespace. In particular,
|
||||
* inter-call prose must not consume a section close and admit later calls. */
|
||||
G next = f.section_open.empty()
|
||||
? seq({ space(), opt(wrap(leaf(until_pattern({ opener })))), choice })
|
||||
: seq({ space(), choice });
|
||||
calls = req.parallel_tool_calls
|
||||
? seq({ lit(""), space(), choice, rep(next, 0, -1), space(), lit("") })
|
||||
: seq({ lit(""), space(), choice, space(), lit("") });
|
||||
? seq({ choice, rep(next, 0, -1), space() })
|
||||
: seq({ choice, space() });
|
||||
}
|
||||
if (!f.section_open.empty())
|
||||
calls = seq({ lit(f.section_open), space(), calls, space(), lit(f.section_close) });
|
||||
b.add_rule("tool-call", render(calls));
|
||||
if (req.require_call) {
|
||||
/* Nothing after the calls: a complete grammar admits only the end of the turn,
|
||||
|
||||
+1
-1
@@ -104,7 +104,7 @@ struct ChatFormat {
|
||||
/* ------------------------------------------------------------------ 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 */
|
||||
std::string section_open, section_close; /* around the complete list of calls */
|
||||
/* Between two calls, beyond whitespace (a JSON-array format would use ", "). Tagged calls are
|
||||
* self-delimiting. Not read yet, must be empty. */
|
||||
std::string call_separator;
|
||||
|
||||
+124
-20
@@ -720,12 +720,15 @@ struct ReplyFormat::Impl {
|
||||
ChatFormat f;
|
||||
/* Each tag split into its core and the whitespace around it that is optional to match. */
|
||||
std::string open_core, open_trail, close_core, close_trail, ns_core, ns_trail, end_core,
|
||||
end_trail, co_core, co_trail;
|
||||
end_trail, co_core, co_trail, section_open_core, section_close_core;
|
||||
/* What begins a call in content. First the format's own opener: call_open's core, or
|
||||
* name_prefix when calls are not wrapped. A wrapped format also takes name_prefix alone,
|
||||
* second, since models often write a call without its wrapper; a wrapper written without
|
||||
* its trailing whitespace is read too. */
|
||||
std::vector<std::string> openers;
|
||||
std::vector<std::string> openers, text_markers;
|
||||
size_t section_open_hit = (size_t)-1, section_close_hit = (size_t)-1;
|
||||
size_t think_open_hit = (size_t)-1, think_close_hit = (size_t)-1;
|
||||
size_t body_section_close_hit = (size_t)-1;
|
||||
/* What ends an argument name: arg_name_suffix and arg_value_prefix, back to back. */
|
||||
std::string name_end;
|
||||
/* The same two, whitespace-trimmed. A loose call is one the grammar never opened, so it was
|
||||
@@ -792,6 +795,16 @@ int ReplyFormat::compile(const ChatFormat& f, std::shared_ptr<const ReplyFormat>
|
||||
split_ws(f.call_open, &m.co_core, &m.co_trail);
|
||||
if (f.call_open.empty()) m.openers = { f.name_prefix };
|
||||
else m.openers = { m.co_core, f.name_prefix };
|
||||
m.text_markers = m.openers;
|
||||
if (!f.section_open.empty()) {
|
||||
std::string section_trail;
|
||||
split_ws(f.section_open, &m.section_open_core, §ion_trail);
|
||||
split_ws(f.section_close, &m.section_close_core, §ion_trail);
|
||||
m.section_open_hit = m.text_markers.size();
|
||||
m.text_markers.push_back(m.section_open_core);
|
||||
m.section_close_hit = m.text_markers.size();
|
||||
m.text_markers.push_back(m.section_close_core);
|
||||
}
|
||||
m.name_end = f.arg_name_suffix + f.arg_value_prefix;
|
||||
m.object = f.has_tools() && f.object_args();
|
||||
m.name_open = f.has_tools() && !m.object && f.name_suffix.empty();
|
||||
@@ -808,15 +821,16 @@ int ReplyFormat::compile(const ChatFormat& f, std::shared_ptr<const ReplyFormat>
|
||||
m.think_breaks.build(b);
|
||||
}
|
||||
if (f.reasoning_anywhere && f.has_reasoning()) {
|
||||
std::vector<std::string> t;
|
||||
if (f.has_tools()) t = m.openers;
|
||||
std::vector<std::string> t = m.text_markers;
|
||||
m.think_open_hit = t.size();
|
||||
t.push_back(m.open_core);
|
||||
m.think_close_hit = t.size();
|
||||
t.push_back(m.close_core);
|
||||
m.text_think.build(t);
|
||||
m.think_only.build({ m.open_core, m.close_core });
|
||||
}
|
||||
if (m.object) {
|
||||
m.text.build(m.openers);
|
||||
m.text.build(m.text_markers);
|
||||
std::string trail;
|
||||
split_ws(f.call_close, &m.cc_core, &trail);
|
||||
std::vector<std::string> bare{ ",", "}", "]" }, key{ ":", ",", "}" };
|
||||
@@ -851,7 +865,7 @@ int ReplyFormat::compile(const ChatFormat& f, std::shared_ptr<const ReplyFormat>
|
||||
m.obj_bare.build(bare);
|
||||
m.obj_key.build(key);
|
||||
} else if (f.has_tools()) {
|
||||
m.text.build(m.openers);
|
||||
m.text.build(m.text_markers);
|
||||
m.arg_name.build({ m.name_end });
|
||||
m.value.build({ f.arg_value_suffix });
|
||||
std::string trail;
|
||||
@@ -864,11 +878,17 @@ int ReplyFormat::compile(const ChatFormat& f, std::shared_ptr<const ReplyFormat>
|
||||
return a.find(b) == std::string::npos && b.find(a) == std::string::npos;
|
||||
};
|
||||
if (!apart(m.cc_core, f.arg_prefix) || !apart(m.cc_core, m.end_core)) m.cc_core.clear();
|
||||
if (m.cc_core.empty()) m.junk.build({ f.arg_prefix, m.end_core });
|
||||
else m.junk.build({ f.arg_prefix, m.end_core, m.cc_core });
|
||||
std::vector<std::string> junk{ f.arg_prefix, m.end_core };
|
||||
if (!m.cc_core.empty()) junk.push_back(m.cc_core);
|
||||
if (!m.section_close_core.empty()) {
|
||||
m.body_section_close_hit = junk.size();
|
||||
junk.push_back(m.section_close_core);
|
||||
}
|
||||
m.junk.build(junk);
|
||||
}
|
||||
const std::string* const delims[] = { &f.reasoning_open, &f.reasoning_close, &f.call_open,
|
||||
&f.call_close, &f.name_prefix, &f.name_suffix,
|
||||
const std::string* const delims[] = { &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, &m.name_end,
|
||||
&f.arg_value_suffix, &f.object_string_open,
|
||||
&f.object_string_close };
|
||||
@@ -1139,6 +1159,11 @@ struct ReplyStream::Impl {
|
||||
St st;
|
||||
bool strict = true, finished = false, fed_tail = false;
|
||||
bool post_call = false; /* content after a call */
|
||||
bool section_active = false;
|
||||
size_t section_calls_at_open = 0;
|
||||
/* The last completed inner call is not executable until another call starts or the outer
|
||||
* section closes. Deferring CallEnd keeps truncation consistent with the one-shot parse. */
|
||||
size_t pending_section_call = (size_t)-1;
|
||||
|
||||
/* delimiter scan */
|
||||
uint16_t ds = 0;
|
||||
@@ -1413,6 +1438,40 @@ struct ReplyStream::Impl {
|
||||
return p + 1;
|
||||
}
|
||||
|
||||
void complete_section_call() {
|
||||
if (pending_section_call == (size_t)-1) return;
|
||||
msg.calls[pending_section_call].closed = true;
|
||||
event(ReplyEvent::CallEnd, (uint32_t)pending_section_call, {});
|
||||
pending_section_call = (size_t)-1;
|
||||
}
|
||||
|
||||
void open_section() {
|
||||
if (section_active) { lenient(); return; }
|
||||
section_active = true;
|
||||
section_calls_at_open = calls;
|
||||
}
|
||||
|
||||
void close_section() {
|
||||
if (!section_active) { lenient(); return; }
|
||||
if (calls == section_calls_at_open) lenient();
|
||||
complete_section_call();
|
||||
section_active = false;
|
||||
}
|
||||
|
||||
/* A section close before call_end leaves the last call incomplete: it must never be exposed
|
||||
* as an executable tool call. Keep its bytes available to content_with_open_call(). */
|
||||
void abandon_call_at_section_close() {
|
||||
lenient();
|
||||
if (cur == 2) publish(2, true);
|
||||
cur = -1;
|
||||
section_active = false;
|
||||
post_call = false;
|
||||
ds = 0;
|
||||
hold.clear();
|
||||
lhold.clear();
|
||||
st = St::Text;
|
||||
}
|
||||
|
||||
/* The call opener has matched at `att`; whether a call follows is decided below. */
|
||||
void begin_attempt(St from) {
|
||||
origin = from;
|
||||
@@ -1472,6 +1531,7 @@ struct ReplyStream::Impl {
|
||||
}
|
||||
|
||||
void begin_call(bool exact) {
|
||||
complete_section_call();
|
||||
if (!exact || tool < 0) lenient();
|
||||
if (!P.opt.parallel_tool_calls && calls > 0) lenient();
|
||||
if (cur >= 0) publish(cur, false);
|
||||
@@ -1810,8 +1870,12 @@ struct ReplyStream::Impl {
|
||||
args_out(close);
|
||||
}
|
||||
publish(2, true);
|
||||
msg.calls.back().closed = true;
|
||||
event(ReplyEvent::CallEnd, (uint32_t)msg.calls.size() - 1, {});
|
||||
if (section_active) {
|
||||
pending_section_call = msg.calls.size() - 1;
|
||||
} else {
|
||||
msg.calls.back().closed = true;
|
||||
event(ReplyEvent::CallEnd, (uint32_t)msg.calls.size() - 1, {});
|
||||
}
|
||||
cur = -1;
|
||||
lpos = 0;
|
||||
lhold.clear();
|
||||
@@ -1984,9 +2048,19 @@ struct ReplyStream::Impl {
|
||||
p = scan(d, p, e, &hit, [this](const char* q, size_t n) { think_out(q, n); });
|
||||
if (hit == 0) { trail = 0; st = St::ThinkCloseWs; }
|
||||
else if (hit > 0) {
|
||||
att = d.pattern(hit);
|
||||
att_at = here(p) - att.size();
|
||||
begin_attempt(St::Think);
|
||||
const std::string& marker = d.pattern(hit);
|
||||
if (!F.section_open_core.empty() && marker == F.section_open_core) {
|
||||
open_section();
|
||||
st = St::Text;
|
||||
} else if (!F.section_open_core.empty() && !section_active) {
|
||||
/* A call-looking tag cannot bypass the required outer section, including
|
||||
* when it appears in an unclosed reasoning block. */
|
||||
think_out(marker.data(), marker.size());
|
||||
} else {
|
||||
att = marker;
|
||||
att_at = here(p) - att.size();
|
||||
begin_attempt(St::Think);
|
||||
}
|
||||
}
|
||||
return p;
|
||||
}
|
||||
@@ -2004,14 +2078,35 @@ struct ReplyStream::Impl {
|
||||
}
|
||||
p = scan(*text_dfa, p, e, &hit, [this](const char* q, size_t n) { text_out(q, n); });
|
||||
if (hit < 0) return p;
|
||||
if (P.anywhere && !P.calls) {
|
||||
if (hit == 0) { trail = 0; st = St::ThinkOpenWs; }
|
||||
else lenient(); /* A reasoning close with no block open. */
|
||||
return p;
|
||||
}
|
||||
if ((size_t)hit < n_open) {
|
||||
att_at = here(p) - F.openers[(size_t)hit].size();
|
||||
begin_text_attempt(hit);
|
||||
} else if ((size_t)hit == n_open) {
|
||||
if (!F.section_open_core.empty() && !section_active) {
|
||||
/* The call-looking tag is ordinary content outside the required wrapper. */
|
||||
const std::string& marker = F.text_markers[(size_t)hit];
|
||||
text_out(marker.data(), marker.size());
|
||||
} else {
|
||||
att_at = here(p) - F.openers[(size_t)hit].size();
|
||||
begin_text_attempt(hit);
|
||||
}
|
||||
} else if ((size_t)hit == F.section_open_hit) {
|
||||
open_section();
|
||||
} else if ((size_t)hit == F.section_close_hit) {
|
||||
if (!section_active) {
|
||||
lenient();
|
||||
const std::string& marker = F.text_markers[(size_t)hit];
|
||||
text_out(marker.data(), marker.size());
|
||||
} else {
|
||||
close_section();
|
||||
}
|
||||
} else if ((size_t)hit == F.think_open_hit) {
|
||||
/* A reasoning block opens again, later in the reply. */
|
||||
trail = 0;
|
||||
st = St::ThinkOpenWs;
|
||||
} else {
|
||||
} else if ((size_t)hit == F.think_close_hit) {
|
||||
/* Its close with no block open: not part of the answer. */
|
||||
lenient();
|
||||
}
|
||||
@@ -2153,10 +2248,12 @@ struct ReplyStream::Impl {
|
||||
const std::string& ap = F.f.arg_prefix;
|
||||
const std::string& fc = F.end_core;
|
||||
const std::string& cc = F.cc_core;
|
||||
const std::string& sc = F.section_close_core;
|
||||
const bool a_ok = extends(ap, c);
|
||||
const bool f_ok = extends(fc, c);
|
||||
const bool c_ok = wrapped && extends(cc, c);
|
||||
if (!a_ok && !f_ok && !c_ok) {
|
||||
const bool s_ok = !sc.empty() && extends(sc, c);
|
||||
if (!a_ok && !f_ok && !c_ok && !s_ok) {
|
||||
lenient();
|
||||
st = St::Junk;
|
||||
ds = 0;
|
||||
@@ -2171,6 +2268,7 @@ struct ReplyStream::Impl {
|
||||
if (a_ok && lpos == ap.size()) { start_arg(); return p + 1; }
|
||||
if (f_ok && lpos == fc.size()) { finish_call_strictness(); end_core_done(); return p + 1; }
|
||||
if (c_ok && lpos == cc.size()) { end_call_at_close(); return p + 1; }
|
||||
if (s_ok && lpos == sc.size()) { abandon_call_at_section_close(); return p + 1; }
|
||||
return p + 1;
|
||||
}
|
||||
|
||||
@@ -2251,6 +2349,8 @@ struct ReplyStream::Impl {
|
||||
p = scan(F.junk, p, e, &hit, [this](const char* q, size_t n) { text_out(q, n); });
|
||||
if (hit == 0) start_arg();
|
||||
else if (hit == 1) end_core_done();
|
||||
else if (hit >= 0 && (size_t)hit == F.body_section_close_hit)
|
||||
abandon_call_at_section_close();
|
||||
else if (hit == 2 && wrapped) end_call_at_close();
|
||||
else if (hit == 2) text_out(F.cc_core.data(), F.cc_core.size());
|
||||
return p;
|
||||
@@ -2804,6 +2904,10 @@ struct ReplyStream::Impl {
|
||||
default:
|
||||
break;
|
||||
}
|
||||
if (section_active) {
|
||||
lenient();
|
||||
section_active = false;
|
||||
}
|
||||
hold.clear();
|
||||
ds = 0;
|
||||
if (!think_text) think_pend.clear();
|
||||
|
||||
Reference in new issue
Block a user