32#include <speculative.h>
34#include <mtmd-helper.h>
36#include <nlohmann/json.hpp>
57bool ends_with(
const std::string& text,
const std::string& suffix) {
58 return text.size() >= suffix.size()
59 && text.compare(text.size() - suffix.size(), suffix.size(), suffix) == 0;
70bool check_stop_sequences(
71 const std::string& text,
72 const std::vector<std::string>& stop_sequences)
74 for (
const auto& stop : stop_sequences) {
75 if (!stop.empty() && ends_with(text, stop)) {
88GenerationResult prefill_error() {
91 r.error_message =
"Prefill decode failed";
92 r.finish_reason =
"error";
102void log_sampler_config(
const GenerationParams& params) {
103 logger->info(
"Sampler: temp={:.2f}, top_k={}, top_p={:.2f}, "
104 "repeat_penalty={:.2f}, thinking={}",
105 params.temperature, params.top_k, params.top_p,
106 params.repeat_penalty, params.enable_thinking);
116void finalize_result(GenerationResult& result,
117 std::chrono::steady_clock::time_point start_time)
122 if (result.token_count > 0 && result.generation_time_ms > 0.0) {
123 result.throughput_tok_s =
124 static_cast<double>(result.token_count)
125 / result.generation_time_ms * 1000.0;
127 logger->info(
"Generated: {} tokens, finish={}, {:.0f}ms, "
129 result.token_count, result.finish_reason,
130 result.generation_time_ms, result.throughput_tok_s);
131 logger->info(
"Content:\n{}", result.content);
153void finalize_generation(GenerationResult& result,
154 const std::string& generated,
int n_generated,
155 const GenerationParams& params,
156 std::chrono::steady_clock::time_point t0)
158 if (n_generated >= params.max_tokens
159 && result.finish_reason.empty()) {
160 result.finish_reason =
"length";
180 result.token_count = n_generated;
181 finalize_result(result, t0);
196GenerationResult sampler_init_error(
197 std::chrono::steady_clock::time_point t0)
201 r.error_message =
"Sampler factory not initialized";
202 r.finish_reason =
"error";
203 finalize_result(r, t0);
216ggml_type parse_kv_cache_type(
const std::string& s) {
217 static const std::pair<const char*, ggml_type> kTable[] = {
218 {
"f16", GGML_TYPE_F16},
219 {
"f32", GGML_TYPE_F32},
220 {
"bf16", GGML_TYPE_BF16},
221 {
"q8_0", GGML_TYPE_Q8_0},
222 {
"q4_0", GGML_TYPE_Q4_0},
224 for (
const auto& [name, type] : kTable) {
225 if (s == name) {
return type; }
227 logger->warn(
"Unknown cache_type '{}' — defaulting to f16", s);
228 return GGML_TYPE_F16;
240llama_split_mode parse_split_mode(
const std::string& s) {
241 if (s.empty()) {
return LLAMA_SPLIT_MODE_LAYER; }
242 static const std::pair<const char*, llama_split_mode> kTable[] = {
243 {
"none", LLAMA_SPLIT_MODE_NONE},
244 {
"layer", LLAMA_SPLIT_MODE_LAYER},
245 {
"row", LLAMA_SPLIT_MODE_ROW},
247 for (
const auto& [name, mode] : kTable) {
248 if (s == name) {
return mode; }
250 logger->warn(
"Unknown split_mode '{}' — defaulting to layer", s);
251 return LLAMA_SPLIT_MODE_LAYER;
265 llama_model_params m = llama_model_default_params();
269 m.split_mode = parse_split_mode(cfg.
split_mode);
293 llama_model_params mparams = llama_model_default_params();
294 mparams.n_gpu_layers = 0;
295 mparams.use_mmap =
true;
311 logger->info(
"Model loaded (CPU): {} tokens in vocab, recurrent={}",
341 llama_context_params c = llama_context_default_params();
343 c.n_batch =
static_cast<uint32_t
>(cfg.
n_batch);
347 c.n_ubatch =
static_cast<uint32_t
>(cfg.
n_ubatch);
351 : std::thread::hardware_concurrency();
353 ? LLAMA_FLASH_ATTN_TYPE_ENABLED
354 : LLAMA_FLASH_ATTN_TYPE_DISABLED;
366 c.n_seq_max =
static_cast<uint32_t
>(cfg.
n_parallel);
428 llama_model_params mparams = build_load_mparams(
config());
430 if (!
config().tensor_split.empty()) {
432 logger->warn(
"tensor_split not yet implemented, ignoring");
446 model_ = llama_model_load_from_file(
config().path.c_str(), mparams);
453 last_error_ =
"Failed to reload model with GPU layers "
455 +
", gpu_layers=" + std::to_string(
config().gpu_layers)
456 +
") — check llama_ggml.log in the engine's log_dir "
457 "for the underlying llama.cpp/CUDA error";
473 llama_context_params cparams = build_cparams(
config());
475 ctx_ = llama_init_from_model(
model_, cparams);
481 logger->info(
"Context created: n_ctx={}, n_batch={}, "
482 "flash_attn={}, type_k={}, type_v={}",
491 logger->info(
"Prompt cache initialized: max_bytes={}",
510 if (
config().mmproj_path.empty()) {
514 auto ctx_params = mtmd_context_params_default();
517 ? LLAMA_FLASH_ATTN_TYPE_ENABLED
518 : LLAMA_FLASH_ATTN_TYPE_DISABLED;
519 ctx_params.print_timings =
false;
523 logger->error(
"mtmd_init_from_file failed for {} — "
524 "continuing in text-only mode",
525 config().mmproj_path.string());
530 logger->info(
"mmproj loaded from {} — vision={}",
575 return (n_max > 0) ? n_max : 16;
606 if (
ctx_ ==
nullptr) {
607 last_error_ =
"MTP setup requires an ACTIVE target context";
610 if (head_path.empty()) {
613 last_error_ =
"MTP requires speculative.draft.path (the head GGUF); "
617 llama_model_params mparams = llama_model_default_params();
619 mparams.use_mmap =
true;
622 llama_context_params cparams = build_cparams(
config());
623 cparams.ctx_type = LLAMA_CONTEXT_TYPE_MTP;
624 cparams.ctx_other =
ctx_;
625 cparams.n_rs_seq = 0;
631 logger->info(
"MTP head ready: {} (n_max={}, ctx_other=target, "
634 last_error_ =
"MTP head setup failed: " + head_path;
701 llama_model_params mparams = llama_model_default_params();
702 mparams.n_gpu_layers = 0;
703 mparams.use_mmap =
true;
706 model_ = llama_model_load_from_file(
config().path.c_str(), mparams);
715 logger->error(
"Failed to reload CPU model during deactivate "
716 "(path={}); backend left unloaded until next activate",
750 std::unique_ptr<Tokenizer> tokenizer)
771 std::unique_ptr<SamplerFactory> factory)
850 const std::string& text,
bool add_special)
const
857 auto ids =
tokenizer_->tokenize(text, add_special);
860 return {ids.begin(), ids.end()};
876 return tokenizer_->detokenize(
static_cast<int32_t
>(token));
888 return static_cast<int>(
tokens.size());
899 const std::string& text)
const {
924 int n_vocab = llama_vocab_n_tokens(
vocab_);
931 auto* mem = llama_get_memory(
ctx_);
932 llama_memory_clear(mem,
true);
934 for (
int i = 0; i < n_tokens; i++) {
935 llama_token tok =
tokens[i];
936 llama_batch batch = llama_batch_get_one(&tok, 1);
937 int rc = llama_decode(
ctx_, batch);
939 llama_memory_clear(mem,
true);
940 throw std::runtime_error(
"llama_decode failed at logprob pos");
942 if (i < n_tokens - 1) {
943 const float* logits = llama_get_logits_ith(
ctx_, -1);
945 logits,
tokens[i + 1], n_vocab);
951 for (
float lp : result.
logprobs) { sum += lp; }
954 -sum /
static_cast<float>(result.
n_logprobs));
956 llama_memory_clear(mem,
true);
1010 const float* logits,
1014 float max_logit = logits[0];
1015 for (
int v = 1; v < n_vocab; v++) {
1016 if (logits[v] > max_logit) {
1017 max_logit = logits[v];
1020 float sum_exp = 0.0f;
1021 for (
int v = 0; v < n_vocab; v++) {
1022 sum_exp += std::exp(logits[v] - max_logit);
1024 float log_sum_exp = max_logit + std::log(sum_exp);
1025 return logits[next_token] - log_sum_exp;
1038 const std::vector<Message>& messages) {
1039 std::vector<llama_chat_message> chat_msgs;
1040 chat_msgs.reserve(messages.size());
1041 for (
const auto& msg : messages) {
1042 chat_msgs.push_back({msg.role.c_str(), msg.content.c_str()});
1061 const std::vector<Message>& messages) {
1062 std::vector<common_chat_msg> out;
1063 out.reserve(messages.size());
1064 for (
const auto& msg : messages) {
1067 cm.content = msg.content;
1068 out.push_back(std::move(cm));
1088 const std::string& tools_json) {
1089 std::vector<common_chat_tool> out;
1090 if (tools_json.empty()) {
return out; }
1091 auto arr = nlohmann::json::parse(tools_json,
nullptr,
false);
1092 if (!arr.is_array()) {
return out; }
1093 for (
const auto& t : arr) {
1094 common_chat_tool ct;
1095 ct.name = t.value(
"name",
"");
1096 ct.description = t.value(
"description",
"");
1097 if (t.contains(
"inputSchema")) {
1098 ct.parameters = t[
"inputSchema"].dump();
1100 if (!ct.name.empty()) { out.push_back(std::move(ct)); }
1122 auto j = nlohmann::json::parse(cc.arguments,
nullptr,
false);
1123 if (j.is_object()) {
1124 for (
auto it = j.begin(); it != j.end(); ++it) {
1126 it->is_string() ? it->get<std::string>() : it->dump();
1159 const std::vector<Message>& messages,
1161 const std::vector<common_chat_tool>& tools,
1162 bool require_tool_call) {
1163 if (model ==
nullptr) {
return std::nullopt; }
1164 auto tmpls = common_chat_templates_init(model,
"");
1165 std::optional<common_chat_params> out;
1167 common_chat_templates_inputs inputs;
1169 inputs.add_generation_prompt =
true;
1170 inputs.use_jinja =
true;
1172 inputs.tools = tools;
1173 if (!tools.empty()) {
1178 inputs.tool_choice = require_tool_call
1179 ? COMMON_CHAT_TOOL_CHOICE_REQUIRED
1180 : COMMON_CHAT_TOOL_CHOICE_AUTO;
1183 out = common_chat_templates_apply(tmpls.get(), inputs);
1184 }
catch (
const std::exception& e) {
1185 logger->warn(
"jinja chat template apply failed ({}); "
1186 "falling back to low-level template", e.what());
1200 const std::vector<Message>& messages) {
1201 std::string fallback;
1202 for (
const auto& msg : messages) {
1203 fallback += msg.role +
": " + msg.content +
"\n";
1229 const std::vector<Message>& messages,
1234 return rendered ? rendered->prompt
1252 const std::vector<Message>& messages,
1275 logger->info(
"Active tools staged for common_chat render: {} bytes",
1301 const std::vector<Message>& messages,
1326 prompt = rendered->prompt;
1327 logger->info(
"render_with_tools: format={}, {} tool(s), captured "
1328 "parser ({} bytes), grammar ({} bytes, lazy={})",
1338 "require_tool_call is set for this tier but the chat template "
1339 "derived NO tool-call grammar from {} staged tool(s) "
1340 "(format={}). The turn will decode unconstrained and may end "
1341 "in prose with no tool call. This template may not support "
1342 "tool_choice=REQUIRED.",
1355 "Falling back to the low-level chat template, which cannot "
1356 "honor enable_thinking:false — this tier WILL still emit "
1357 "reasoning, and a generation that is entirely reasoning is "
1358 "stripped to empty content. The jinja render was unavailable "
1359 "for this turn (no tools staged, or the template could not be "
1423 const std::size_t before = p.
stop.size();
1425 if (p.
stop.size() > before) {
1426 logger->info(
"Sequential tier: tool-call close marker injected "
1427 "post-render (gh#105) — hard-stop at first tool call");
1458 static const std::string kOpen =
"<|channel>";
1459 static const std::string kClose =
"<channel|>";
1460 bool stripped =
false;
1461 bool truncated_unclosed =
false;
1463 while ((pos = content.find(kOpen)) != std::string::npos) {
1465 std::size_t end = content.find(kClose, pos + kOpen.size());
1466 if (end == std::string::npos) { truncated_unclosed =
true; }
1467 std::size_t span_end =
1468 (end == std::string::npos) ? content.size() : end + kClose.size();
1469 if (reasoning_out !=
nullptr) {
1470 std::size_t inner = pos + kOpen.size();
1471 std::size_t inner_end =
1472 (end == std::string::npos) ? content.size() : end;
1473 reasoning_out->append(content, inner, inner_end - inner);
1475 content.erase(pos, span_end - pos);
1478 std::size_t nb = content.find_first_not_of(
" \t\r\n");
1479 content.erase(0, nb == std::string::npos ? content.size() : nb);
1481 if (truncated_unclosed && content.empty()) {
1482 logger->warn(
"strip_thinking_channels: a <|channel> reasoning block "
1483 "was never closed, so the strip removed the whole "
1484 "generation and content is empty. Not a parse error. The "
1485 "orchestrator reports whether this was a token budget or "
1486 "the model ending its own turn — only it holds "
1487 "finish_reason. gh#137.");
1510 const std::string& raw)
const
1520 common_chat_parser_params pp;
1525 auto msg = common_chat_parse(raw,
false, pp);
1530 for (
const auto& tc : msg.tool_calls) {
1536 }
catch (
const std::exception& e) {
1537 logger->warn(
"common_chat_parse failed ({}); raw kept as content",
1557 const std::vector<Message>& messages)
const
1561 int n = llama_chat_apply_template(
1562 nullptr, chat_msgs.data(), chat_msgs.size(),
1565 logger->error(
"llama_chat_apply_template failed (size query)");
1569 std::vector<char> buf(
static_cast<size_t>(n + 1));
1570 int written = llama_chat_apply_template(
1571 nullptr, chat_msgs.data(), chat_msgs.size(),
1572 true, buf.data(),
static_cast<int32_t
>(buf.size()));
1574 logger->error(
"llama_chat_apply_template failed (render)");
1578 return std::string(buf.data(),
static_cast<size_t>(written));
1621 llama_memory_clear(llama_get_memory(
ctx_),
true);
1624 const int n_tokens =
static_cast<int>(
tokens.size());
1626 for (
int i = 0; i < n_tokens; i += n_batch) {
1627 int chunk = std::min(n_batch, n_tokens - i);
1628 std::vector<llama_token> slice(
1630 llama_batch batch = llama_batch_get_one(
1631 slice.data(),
static_cast<int32_t
>(chunk));
1632 if (llama_decode(
ctx_, batch) != 0) {
1633 logger->error(
"Prefill decode failed at offset {}", i);
1659 std::string& generated,
1660 std::function<
void(std::string_view)>& on_token,
1661 const std::vector<std::string>& stop)
1663 llama_token new_token = sampler.
sample();
1665 if (new_token == llama_vocab_eos(
vocab_)
1666 || llama_vocab_is_eog(
vocab_, new_token)) {
1673 on_token(std::string_view(piece));
1675 if (check_stop_sequences(generated, stop)) {
1679 llama_token tok = new_token;
1680 llama_batch single = llama_batch_get_one(&tok, 1);
1681 return (llama_decode(
ctx_, single) == 0) ?
"continue" :
"error";
1699 const std::vector<llama_token>&
tokens,
1701 std::function<
void(std::string_view)> on_token,
1702 std::atomic<bool>* cancel)
1747 std::function<
void(std::string_view)> on_token,
1748 std::atomic<bool>* cancel)
1751 std::string generated;
1752 int n_generated = 0;
1756 bool cancelled = cancel && cancel->load(std::memory_order_acquire);
1763 auto status =
step_token(sampler, generated, on_token, stop);
1764 if (status ==
"continue") {
1767 result.
finish_reason = (status ==
"error") ?
"error" :
"stop";
1768 if (status ==
"error") {
1796 result.
content = entropic::mcp::sanitize_utf8(generated);
1822 llama_pos pos, llama_seq_id seq,
bool want_logits) {
1827 b.logits[k] = want_logits ? 1 : 0;
1837 std::vector<BatchSeq>& seqs,
1838 const std::vector<GenerationParams>& params) {
1839 for (std::size_t i = 0; i < seqs.size(); ++i) {
1842 if (ls ==
nullptr) {
return false; }
1845 seqs[i].max_tokens = params[i].max_tokens;
1856 std::vector<BatchSeq>& seqs,
const std::vector<llama_token>& seq0,
1857 std::size_t shared) {
1858 std::vector<llama_token> prefix(
1859 seq0.begin(), seq0.begin() +
static_cast<long>(shared));
1861 auto* mem = llama_get_memory(
ctx_);
1862 for (std::size_t i = 1; i < seqs.size(); ++i) {
1863 llama_memory_seq_cp(mem, 0, seqs[i].seq_id, 0,
1864 static_cast<llama_pos
>(shared));
1866 for (
auto& s : seqs) { s.pos =
static_cast<int>(shared); }
1879 std::vector<BatchSeq>& seqs,
1880 const std::vector<std::vector<llama_token>>& toks,
1881 std::size_t shared) {
1886 for (
const auto& t : toks) {
1887 total +=
static_cast<int>(t.size() - std::min(shared, t.size()));
1889 llama_batch batch = llama_batch_init(total, 0,
1890 static_cast<int32_t
>(seqs.size()));
1892 for (std::size_t i = 0; i < seqs.size(); ++i) {
1893 int len =
static_cast<int>(toks[i].size());
1894 for (
int p =
static_cast<int>(shared); p < len; ++p) {
1897 if (p == len - 1) { seqs[i].logits_idx = k; }
1904 bool ok = (llama_decode(
ctx_, batch) == 0);
1905 llama_batch_free(batch);
1915 for (
auto& s : seqs) {
1916 if (!s.active) {
continue; }
1920 llama_token tok = llama_sampler_sample(s.chain,
ctx_, s.logits_idx);
1921 if (llama_vocab_is_eog(
vocab_, tok)) {
1926 s.out.push_back(tok);
1928 if (s.n_gen >= s.max_tokens) { s.active =
false; s.finish =
"length"; }
1943 std::vector<BatchSeq>& seqs,
int max_steps, std::atomic<bool>& cancel) {
1944 llama_batch batch = llama_batch_init(
static_cast<int32_t
>(seqs.size()), 0,
1945 static_cast<int32_t
>(seqs.size()));
1946 for (
int step = 0; step < max_steps; ++step) {
1947 if (cancel.load(std::memory_order_acquire)) {
break; }
1950 for (
auto& s : seqs) {
1951 if (!s.active) {
continue; }
1957 if (k == 0) {
break; }
1960 if (llama_decode(
ctx_, batch) != 0) {
break; }
1962 llama_batch_free(batch);
1971 std::vector<BatchSeq>& seqs) {
1972 std::vector<GenerationResult> out;
1973 out.reserve(seqs.size());
1974 for (
auto& s : seqs) {
1979 out.push_back(std::move(r));
1990 for (std::size_t i = 1; i < seqs.size(); ++i) {
2007 const std::vector<std::vector<llama_token>>& toks,
2008 const std::vector<GenerationParams>& params,
2010 std::atomic<bool>& cancel)
2012 const std::size_t n = toks.size();
2013 std::vector<BatchSeq> seqs(n);
2016 return std::vector<GenerationResult>(
2020 for (
const auto& p : params) { max_steps = std::max(max_steps, p.max_tokens); }
2022 llama_memory_clear(llama_get_memory(
ctx_),
true);
2032 : std::vector<GenerationResult>(
2036 logger->info(
"gh#98 batch: requests={} prefix.tokens_shared={} "
2037 "prefix.tokens_saved={} total_prefill_tokens={} gen_decodes={}",
2061 const std::vector<std::vector<Message>>& requests,
2062 const std::vector<GenerationParams>& params,
2063 std::atomic<bool>& cancel)
2065 const std::size_t n = requests.size();
2066 std::vector<std::vector<llama_token>> toks(n);
2067 for (std::size_t i = 0; i < n; ++i) {
2071 std::size_t total_suffix = 0;
2072 for (
const auto& t : toks) { total_suffix += t.size() - shared; }
2076 total_suffix,
config().n_batch)) {
2092 const std::vector<Message>& messages)
2094 for (
const auto& msg : messages) {
2095 if (msg.role ==
"system") {
2115 const std::vector<llama_token>&
tokens,
int start_offset)
2117 int total =
static_cast<int>(
tokens.size());
2118 if (start_offset >= total) {
return true; }
2120 int n_batch = llama_n_batch(
ctx_);
2121 int n_remaining = total - start_offset;
2123 for (
int off = 0;
off < n_remaining;
off += n_batch) {
2124 int chunk = std::min(n_batch, n_remaining -
off);
2125 llama_batch batch = llama_batch_get_one(
2126 const_cast<llama_token*
>(
tokens.data())
2127 + start_offset +
off,
2129 if (llama_decode(
ctx_, batch) != 0) {
2130 logger->error(
"Decode chunk failed (start={}, off={}, "
2131 "chunk={})", start_offset,
off, chunk);
2156 const std::vector<llama_token>&
tokens)
2158 auto* mem = llama_get_memory(
ctx_);
2159 llama_memory_clear(mem,
true);
2161 size_t restored = llama_state_seq_set_data(
2163 if (restored == 0) {
2164 logger->warn(
"KV state restore failed, falling back to full prefill");
2184 const CacheKey& key,
int prefix_tokens)
2186 size_t state_size = llama_state_seq_get_size(
ctx_, 0);
2187 if (state_size == 0) {
2191 std::vector<uint8_t> buf(state_size);
2192 size_t written = llama_state_seq_get_data(
2193 ctx_, buf.data(), buf.size(), 0);
2195 buf.resize(written);
2209 const std::vector<Message>& messages,
2212 std::vector<Message> sys_msgs;
2213 for (
const auto& msg : messages) {
2214 if (msg.role ==
"system") {
2215 sys_msgs.push_back(msg);
2218 if (sys_msgs.empty()) {
2223 auto sys_tokens =
tokenize(sys_prompt,
true);
2224 return static_cast<int>(sys_tokens.size());
2249 const std::vector<llama_token>&
tokens,
2253 int total =
static_cast<int>(
tokens.size());
2254 if (prefix_tokens <= 0 || prefix_tokens >= total) {
2261 std::vector<llama_token> prefix(
2292 const std::vector<llama_token>&
tokens,
2293 const std::string& system_prompt,
2294 const std::vector<Message>& messages,
2306 auto t_pre = entropic::log::now();
2333 logger->info(
"Prefill (gh#96): {} tokens / {:.1f} ms decoded this turn",
2361 auto* mem = llama_get_memory(
ctx_);
2362 long pos_max =
static_cast<long>(llama_memory_seq_pos_max(mem, 0));
2370 llama_memory_seq_rm(mem, 0,
static_cast<llama_pos
>(cut), -1);
2375 logger->info(
"Warm-keep: reused {} resident tokens, decoded {} "
2376 "delta (of {} total)", cut,
tokens.size() - cut,
2416 const std::vector<llama_token>&
tokens,
2417 const std::string& system_prompt,
2418 const std::vector<Message>& messages,
2423 && !system_prompt.empty();
2425 if (!cache_enabled) {
2430 system_prompt,
config().path.string());
2433 if (cached !=
nullptr) {
2435 logger->info(
"Prompt cache HIT: {} bytes, {} prefix tokens",
2441 logger->warn(
"Cache restore failed, falling back to full prefill");
2443 logger->info(
"Prompt cache MISS: processing full prompt");
2459bool any_image_in(
const std::vector<Message>& messages) {
2460 for (
const auto& m : messages) {
2461 if (
has_images(m.content_parts)) {
return true; }
2478std::vector<Message> strip_image_parts(
2479 const std::vector<Message>& messages) {
2480 std::vector<Message> out = messages;
2481 for (
auto& m : out) {
2482 if (m.content_parts.empty()) {
continue; }
2484 m.content_parts.clear();
2506std::vector<Message> substitute_image_markers(
2507 const std::vector<Message>& messages,
2508 ::mtmd_context* ctx,
2509 std::vector<::mtmd_bitmap*>& bitmaps_out) {
2510 std::vector<Message> out;
2511 out.reserve(messages.size());
2512 const std::string marker = mtmd_default_marker();
2513 for (
const auto& m : messages) {
2516 if (m.content_parts.empty()) {
2517 copy.content = m.content;
2518 out.push_back(std::move(copy));
2522 for (
const auto& p : m.content_parts) {
2527 ::mtmd_bitmap* bm =
nullptr;
2528 if (!p.image_path.empty()) {
2529 bm = mtmd_helper_bitmap_init_from_file(
2530 ctx, p.image_path.c_str(),
false).bitmap;
2532 if (bm ==
nullptr) {
return {}; }
2533 bitmaps_out.push_back(bm);
2536 copy.content = std::move(built);
2537 out.push_back(std::move(copy));
2555 const std::string& prompt,
2556 const std::vector<::mtmd_bitmap*>& bitmaps,
2557 std::string& err_msg)
2559 llama_memory_clear(llama_get_memory(
ctx_),
true);
2560 ::mtmd_input_text mt{prompt.c_str(),
true,
true};
2561 auto* chunks = mtmd_input_chunks_init();
2562 std::vector<const ::mtmd_bitmap*> bm_cptrs(
2563 bitmaps.begin(), bitmaps.end());
2564 int32_t tok_rc = mtmd_tokenize(
2565 mtmd_ctx_, chunks, &mt, bm_cptrs.data(), bm_cptrs.size());
2567 mtmd_input_chunks_free(chunks);
2568 err_msg =
"mtmd_tokenize failed (rc="
2569 + std::to_string(tok_rc) +
")";
2572 llama_pos new_n_past = 0;
2573 int32_t eval_rc = mtmd_helper_eval_chunks(
2575 static_cast<int32_t
>(
config().n_batch),
2577 mtmd_input_chunks_free(chunks);
2579 err_msg =
"mtmd_helper_eval_chunks failed (rc="
2580 + std::to_string(eval_rc) +
")";
2583 logger->info(
"Multimodal prefill complete: n_past={}", new_n_past);
2605 std::function<
void(std::string_view token)> on_token,
2606 std::atomic<bool>* cancel,
2607 const std::chrono::steady_clock::time_point& t0)
2616 finalize_result(result, t0);
2619 std::string generated;
2620 int n_generated = 0;
2623 if (cancel !=
nullptr
2624 && cancel->load(std::memory_order_acquire)) {
2630 *sampler, generated, on_token, stop);
2631 if (status ==
"continue") { ++n_generated;
continue; }
2632 result.
finish_reason = (status ==
"error") ?
"error" :
"stop";
2633 if (status ==
"error") {
2638 finalize_generation(result, generated, n_generated, params, t0);
2658 const std::vector<Message>& messages,
2660 std::function<
void(std::string_view token)> on_token,
2661 std::atomic<bool>* cancel)
2663 auto t0 = entropic::log::now();
2665 std::vector<::mtmd_bitmap*> bitmaps;
2666 auto marked = substitute_image_markers(
2668 if (marked.empty()) {
2669 for (
auto* b : bitmaps) { mtmd_bitmap_free(b); }
2673 "mtmd_helper_bitmap_init_from_file failed";
2677 logger->info(
"Multimodal generate: {} images, prompt={} chars, max_tokens={}",
2678 bitmaps.size(), prompt.size(), params.
max_tokens);
2679 std::string prefill_err;
2681 for (
auto* b : bitmaps) { mtmd_bitmap_free(b); }
2709 const std::vector<Message>& messages,
2712 if (!any_image_in(messages)) {
2718 logger->warn(
"Image content present but model has no vision "
2719 "capability — stripping image parts");
2729 const std::vector<Message>& messages,
2732 auto t0 = entropic::log::now();
2737 logger->info(
"Generate: {} input tokens, max_tokens={}",
2739 log_sampler_config(params);
2743 if (!sampler) {
return sampler_init_error(t0); }
2746 return prefill_error();
2750 std::string generated;
2751 int n_generated = 0;
2752 std::function<void(std::string_view)> no_cb =
nullptr;
2757 *sampler, generated, no_cb, stop);
2758 if (status ==
"continue") { ++n_generated; }
2761 (status ==
"error") ?
"error" :
"stop";
2762 if (status ==
"error") {
2769 finalize_generation(result, generated, n_generated, params, t0);
2784 const std::vector<Message>& messages,
2786 std::atomic<bool>& cancel)
2788 if (!any_image_in(messages)) {
2794 logger->warn(
"Image content present but model has no vision "
2795 "capability — stripping image parts");
2819 const std::vector<Message>& messages,
2821 std::atomic<bool>& cancel)
2823 auto t0 = entropic::log::now();
2828 logger->info(
"Generate (cancellable): {} input tokens, max_tokens={}",
2830 log_sampler_config(params);
2833 if (!sampler) {
return sampler_init_error(t0); }
2836 return prefill_error();
2840 std::string generated;
2841 int n_generated = 0;
2842 std::function<void(std::string_view)> no_cb =
nullptr;
2846 if (cancel.load(std::memory_order_acquire)) {
2852 *sampler, generated, no_cb, stop);
2853 if (status ==
"continue") { ++n_generated; }
2856 (status ==
"error") ?
"error" :
"stop";
2857 if (status ==
"error") {
2864 finalize_generation(result, generated, n_generated, params, t0);
2879 const std::vector<Message>& messages,
2881 std::function<
void(std::string_view token)> on_token,
2882 std::atomic<bool>& cancel)
2884 if (!any_image_in(messages)) {
2886 messages, params, on_token, cancel);
2891 logger->warn(
"Image content present but model has no vision "
2892 "capability — stripping image parts");
2894 strip_image_parts(messages), params, on_token, cancel);
2909 const std::vector<Message>& messages,
2911 std::function<
void(std::string_view token)> on_token,
2912 std::atomic<bool>& cancel)
2914 auto t0 = entropic::log::now();
2918 logger->info(
"Stream: {} input tokens, max_tokens={}",
2920 log_sampler_config(params);
2924 if (!sampler) {
return sampler_init_error(t0); }
2926 return prefill_error();
2929 std::string generated;
2930 int n_generated = 0;
2933 if (cancel.load(std::memory_order_acquire)) {
2939 *sampler, generated, on_token, stop);
2940 if (status ==
"continue") { ++n_generated; }
2943 (status ==
"error") ?
"error" :
"stop";
2944 if (status ==
"error") {
2950 finalize_generation(result, generated, n_generated, params, t0);
2967 const std::vector<Message>& ,
2969 std::function<
void(std::string_view)> ,
2970 std::atomic<bool>& )
2975 "LlamaCppBackend speculative requires an explicit draft "
2976 "backend handle — orchestrator dispatches via "
2977 "generate_speculative_with_draft";
2999static void apply_grammar_source(
3000 common_params_sampling& cps,
3002 const std::string& tool_grammar,
3003 bool tool_grammar_lazy,
3004 const std::string& generation_prompt) {
3017 "Both a request grammar and a tool-call grammar are active. These "
3018 "constrain decoding to different languages and cannot compose; the "
3019 "request grammar is being used and the staged tools will NOT be "
3020 "structurally enforced. Drop one: clear params.grammar to let the "
3021 "tool schemas constrain, or unstage tools to use your grammar.");
3025 cps.grammar = common_grammar(COMMON_GRAMMAR_TYPE_USER, params.
grammar);
3031 cps.grammar = common_grammar(COMMON_GRAMMAR_TYPE_TOOL_CALLS,
3033 cps.grammar_lazy = tool_grammar_lazy;
3041 cps.generation_prompt = generation_prompt;
3050 "Tool-call grammar applied: {} bytes, lazy={}, prefill={} bytes",
3051 tool_grammar.size(), tool_grammar_lazy,
3052 generation_prompt.size());
3053 }
else if (!tool_grammar.empty()) {
3058 "Tool-call grammar ({} bytes) NOT applied — an explicit request "
3059 "grammar takes precedence. Tool calls are not structurally "
3060 "enforced this turn.",
3061 tool_grammar.size());
3091common_params_sampling to_common_sampling(
3092 const GenerationParams& params,
3093 const std::string& tool_grammar,
3094 bool tool_grammar_lazy,
3095 const std::string& generation_prompt) {
3096 common_params_sampling cps;
3097 cps.temp = params.temperature;
3098 apply_grammar_source(cps, params, tool_grammar, tool_grammar_lazy,
3100 cps.top_k = params.top_k;
3101 cps.top_p = params.top_p;
3102 cps.penalty_repeat = params.repeat_penalty;
3108 cps.penalty_freq = params.frequency_penalty;
3109 cps.penalty_present = params.presence_penalty;
3113 for (
auto& [tok, val] : params.logit_bias) {
3114 cps.logit_bias.push_back({tok, val});
3116 if (params.seed >= 0) {
3117 cps.seed =
static_cast<uint32_t
>(params.seed);
3131 cps.samplers = {COMMON_SAMPLER_TYPE_PENALTIES,
3132 COMMON_SAMPLER_TYPE_TOP_K,
3133 COMMON_SAMPLER_TYPE_TOP_P};
3134 if (params.min_p > 0.0f) {
3135 cps.samplers.push_back(COMMON_SAMPLER_TYPE_MIN_P);
3137 if (params.temperature > 0.0f) {
3138 cps.samplers.push_back(COMMON_SAMPLER_TYPE_TEMPERATURE);
3140 cps.min_p = params.min_p;
3141 cps.dry_multiplier = 0.0f;
3142 cps.top_n_sigma = -1.0f;
3162bool spec_prefill_minus_last(
3163 llama_context* ctx,
const std::vector<llama_token>&
tokens) {
3164 int total =
static_cast<int>(
tokens.size()) - 1;
3165 if (total <= 0) {
return true; }
3166 int n_batch = llama_n_batch(ctx);
3167 for (
int off = 0;
off < total;
off += n_batch) {
3168 int chunk = std::min(n_batch, total -
off);
3169 llama_batch batch = llama_batch_get_one(
3170 const_cast<llama_token*
>(
tokens.data()) +
off, chunk);
3171 if (llama_decode(ctx, batch) != 0) {
return false; }
3193 logger->error(
"Speculative decode failed ({}): {}",
3196 r.error_code = code;
3197 r.error_message = std::move(msg);
3198 r.finish_reason =
"error";
3212 common_speculative* spec =
nullptr;
3213 common_sampler* smpl =
nullptr;
3214 llama_context* ctx_tgt =
nullptr;
3215 llama_context* ctx_dft =
nullptr;
3216 llama_batch batch_tgt{};
3217 bool batch_initialized =
false;
3218 llama_seq_id seq_id = 0;
3220 llama_token id_last = 0;
3221 std::vector<llama_token> prompt_tgt;
3222 std::vector<llama_token> draft;
3223 std::string generated;
3225 int n_generated = 0;
3228 bool has_eos =
false;
3229 std::string finish_reason;
3231 std::string error_message;
3240 bool use_ckpt_tgt =
false;
3241 bool use_ckpt_dft =
false;
3242 common_prompt_checkpoint ckpt;
3252 if (state.spec) { common_speculative_free(state.spec); }
3253 if (state.smpl) { common_sampler_free(state.smpl); }
3254 if (state.batch_initialized) {
3255 llama_batch_free(state.batch_tgt);
3266 common_batch_clear(state.batch_tgt);
3267 common_batch_add(state.batch_tgt, state.id_last,
3268 state.n_past, {state.seq_id},
true);
3269 int pos = state.n_past + 1;
3270 for (
auto draft_token : state.draft) {
3271 common_batch_add(state.batch_tgt, draft_token, pos,
3272 {state.seq_id},
true);
3286 int rc_tgt = llama_decode(state.ctx_tgt, state.batch_tgt);
3288 logger->error(
"Speculative target decode failed: rc={}, "
3289 "n_past={}, draft_size={}",
3290 rc_tgt, state.n_past, state.draft.size());
3292 state.error_message =
"target llama_decode failed";
3293 state.finish_reason =
"error";
3296 int rc_dft = llama_decode(state.ctx_dft, state.batch_tgt);
3298 logger->error(
"Speculative draft decode failed: rc={}, "
3299 "n_past={}, draft_size={}",
3300 rc_dft, state.n_past, state.draft.size());
3302 state.error_message =
"draft llama_decode failed";
3303 state.finish_reason =
"error";
3316 auto& dp = common_speculative_get_draft_params(
3317 state.spec, state.seq_id);
3320 dp.n_past = state.n_past;
3321 dp.id_last = state.id_last;
3322 dp.prompt = &state.prompt_tgt;
3323 dp.result = &state.draft;
3324 common_speculative_draft(state.spec);
3325 return static_cast<int>(state.draft.size());
3343 const llama_vocab* vocab,
int max_tokens,
3344 std::function<
void(std::string_view)>& on_token,
3345 std::atomic<bool>& cancel)
3348 state.prompt_tgt.push_back(state.id_last);
3350 state.n_generated++;
3351 if (llama_vocab_is_eog(vocab,
id)) {
3352 state.has_eos =
true;
3353 state.finish_reason =
"stop";
3356 const std::string piece =
3357 common_token_to_piece(state.ctx_tgt,
id);
3358 state.generated += piece;
3359 if (on_token) { on_token(piece); }
3364 if (check_stop_sequences(state.generated, state.
stop)) {
3365 state.finish_reason =
"stop";
3367 }
else if (cancel.load(std::memory_order_acquire)) {
3369 state.finish_reason =
"cancelled";
3371 }
else if (state.n_generated >= max_tokens) {
3372 state.finish_reason =
"length";
3391 state.ckpt.update_pos(
3392 static_cast<int64_t
>(state.prompt_tgt.size()),
3393 llama_memory_seq_pos_min(
3394 llama_get_memory(state.ctx_tgt), state.seq_id),
3395 llama_memory_seq_pos_max(
3396 llama_get_memory(state.ctx_tgt), state.seq_id));
3397 if (state.use_ckpt_dft) {
3398 state.ckpt.update_dft(state.ctx_dft, state.seq_id,
3399 LLAMA_STATE_SEQ_FLAGS_PARTIAL_ONLY
3400 | LLAMA_STATE_SEQ_FLAGS_ON_DEVICE);
3411 if (state.use_ckpt_tgt && !state.draft.empty()) {
3412 state.ckpt.update_tgt(state.ctx_tgt, state.seq_id,
3413 LLAMA_STATE_SEQ_FLAGS_PARTIAL_ONLY
3414 | LLAMA_STATE_SEQ_FLAGS_ON_DEVICE);
3425 constexpr auto flags = LLAMA_STATE_SEQ_FLAGS_PARTIAL_ONLY
3426 | LLAMA_STATE_SEQ_FLAGS_ON_DEVICE;
3427 if (state.use_ckpt_dft) {
3428 state.ckpt.load_dft(state.ctx_dft, state.seq_id, flags);
3430 llama_memory_seq_rm(llama_get_memory(state.ctx_dft),
3431 state.seq_id, state.ckpt.pos_max + 1, -1);
3445 std::vector<llama_token>& ids) {
3446 constexpr auto flags = LLAMA_STATE_SEQ_FLAGS_PARTIAL_ONLY
3447 | LLAMA_STATE_SEQ_FLAGS_ON_DEVICE;
3448 state.draft = std::move(ids);
3449 state.ckpt.load_tgt(state.ctx_tgt, state.seq_id, flags);
3450 llama_memory_seq_rm(llama_get_memory(state.ctx_tgt),
3451 state.seq_id, state.ckpt.pos_max + 1, -1);
3452 state.ckpt.load_dft(state.ctx_dft, state.seq_id, flags);
3453 llama_memory_seq_rm(llama_get_memory(state.ctx_dft),
3454 state.seq_id, state.ckpt.pos_max + 1, -1);
3455 state.prompt_tgt.resize(
static_cast<size_t>(state.ckpt.n_tokens));
3456 state.n_past =
static_cast<int>(state.prompt_tgt.size());
3458 common_sampler_free(state.smpl);
3459 state.smpl = smpl_save;
3487 llama_memory_seq_rm(llama_get_memory(state.ctx_tgt),
3488 state.seq_id, state.n_past, -1);
3489 llama_memory_seq_rm(llama_get_memory(state.ctx_dft),
3490 state.seq_id, state.n_past, -1);
3501 const std::vector<llama_token>& ids,
3502 const llama_vocab* vocab,
int max_tokens,
3503 std::function<
void(std::string_view)>& on_token,
3504 std::atomic<bool>& cancel) {
3506 for (
auto id : ids) {
3508 state,
id, vocab, max_tokens, on_token, cancel);
3509 if (!signal.empty()) { stop =
true;
break; }
3537 if (!state.draft.empty()) {
3538 return static_cast<int>(state.draft.size());
3554 const llama_vocab* vocab,
3556 std::function<
void(std::string_view)>& on_token,
3557 std::atomic<bool>& cancel)
3563 common_sampler* smpl_save =
nullptr;
3564 if (state.use_ckpt_tgt) {
3565 smpl_save = common_sampler_clone(state.smpl);
3567 auto ids = common_sampler_sample_and_accept_n(
3568 state.smpl, state.ctx_tgt, state.draft);
3569 int accepted =
static_cast<int>(ids.size()) - 1;
3570 if (accepted < 0) { accepted = 0; }
3574 if (state.use_ckpt_tgt
3575 &&
static_cast<int>(ids.size()) - 1
3576 <
static_cast<int>(state.draft.size())) {
3580 if (smpl_save) { common_sampler_free(smpl_save); }
3582 common_speculative_accept(state.spec, state.seq_id, accepted);
3583 state.n_drafted += draft_size_before;
3584 state.n_accepted += accepted;
3590 state.n_past +=
static_cast<int>(ids.size());
3593 state, ids, vocab, max_tokens, on_token, cancel);
3594 state.draft.clear();
3612 bool target_active,
bool draft_active,
3613 llama_context* ctx_tgt, llama_context* ctx_dft) {
3620 const llama_model* model_tgt = llama_get_model(ctx_tgt);
3621 int cap_tgt = common_context_can_seq_rm(ctx_tgt);
3622 int cap_dft = common_context_can_seq_rm(ctx_dft);
3623 logger->info(
"Speculative seq_rm capability: target={}, draft={} "
3624 "(0=NO, 1=PART, 2=FULL)", cap_tgt, cap_dft);
3625 if (!target_active || !draft_active) {
3626 err =
"speculative requires ACTIVE target + draft";
3627 }
else if (llama_model_is_recurrent(model_tgt)
3628 || llama_model_is_hybrid(model_tgt)) {
3629 err =
"speculative refused: architecture (target is "
3630 "recurrent or hybrid; see proposal Implementation "
3632 }
else if (cap_tgt == COMMON_CONTEXT_SEQ_RM_TYPE_NO
3633 || cap_dft == COMMON_CONTEXT_SEQ_RM_TYPE_NO) {
3636 err =
"speculative kernel requires at least FULL seq_rm "
3637 "(target/draft reported NO seq_rm at all)";
3673 const std::string& draft_path,
3674 const std::string& tool_grammar,
3675 bool tool_grammar_lazy,
3676 const std::string& generation_prompt) {
3677 auto common_sampling =
3678 to_common_sampling(params, tool_grammar, tool_grammar_lazy,
3680 state.smpl = common_sampler_init(model_tgt, common_sampling);
3681 if (!state.smpl) {
return "common_sampler_init failed"; }
3683 common_params_speculative spec_params;
3684 spec_params.types = {COMMON_SPECULATIVE_TYPE_DRAFT_SIMPLE};
3685 spec_params.draft.n_max = (n_draft_max > 0) ? n_draft_max : 16;
3686 spec_params.draft.ctx_tgt = state.ctx_tgt;
3687 spec_params.draft.ctx_dft = state.ctx_dft;
3691 spec_params.draft.mparams.path = draft_path;
3692 state.spec = common_speculative_init(spec_params, 1);
3694 common_sampler_free(state.smpl);
3695 state.smpl =
nullptr;
3696 return "common_speculative_init failed";
3699 common_speculative_begin(state.spec, state.seq_id, state.prompt_tgt);
3700 state.batch_tgt = llama_batch_init(llama_n_batch(state.ctx_tgt), 0, 1);
3701 state.batch_initialized =
true;
3705 state.use_ckpt_tgt = common_context_can_seq_rm(state.ctx_tgt)
3706 == COMMON_CONTEXT_SEQ_RM_TYPE_FULL;
3707 state.use_ckpt_dft = common_context_can_seq_rm(state.ctx_dft)
3708 == COMMON_CONTEXT_SEQ_RM_TYPE_FULL;
3719 const std::vector<llama_token>&
tokens,
3721 const std::string& draft_path,
3722 const std::string& tool_grammar,
bool tool_grammar_lazy,
3723 const std::string& generation_prompt) {
3724 state.id_last =
tokens.back();
3725 state.prompt_tgt.assign(
tokens.begin(),
tokens.end() - 1);
3726 state.n_past =
static_cast<int>(
tokens.size()) - 1;
3728 llama_memory_clear(llama_get_memory(state.ctx_tgt),
true);
3729 llama_memory_clear(llama_get_memory(state.ctx_dft),
true);
3731 if (!spec_prefill_minus_last(state.ctx_tgt,
tokens)
3732 || !spec_prefill_minus_last(state.ctx_dft,
tokens)) {
3733 return "speculative prefill failed";
3736 state, model_tgt, params, n_draft_max, draft_path,
3737 tool_grammar, tool_grammar_lazy, generation_prompt);
3748 std::function<
void(std::string_view)>& on_token,
3749 std::atomic<bool>& cancel) {
3750 while (state.n_generated < max_tokens) {
3751 if (cancel.load(std::memory_order_acquire)) {
3753 state.finish_reason =
"cancelled";
3757 on_token, cancel)) {
3761 if (state.finish_reason.empty()) {
3762 state.finish_reason = (state.n_generated >= max_tokens)
3763 ?
"length" :
"stop";
3780 std::chrono::steady_clock::time_point t0) {
3799 result.
content = entropic::mcp::sanitize_utf8(state.generated);
3809 entropic::log::elapsed_ms(t0, entropic::log::now());
3817 if (state.n_drafted > 0) {
3818 const float accept_rate =
3819 static_cast<float>(state.n_accepted)
3820 /
static_cast<float>(state.n_drafted);
3821 logger->info(
"Speculative: generated={}, drafted={}, "
3822 "accepted={}, accept_rate={:.3f}",
3823 state.n_generated, state.n_drafted,
3824 state.n_accepted, accept_rate);
3871 llama_context* ctx_tgt, llama_context* ctx_dft, llama_model* model_tgt,
3873 std::function<
void(std::string_view)>& on_token,
3874 std::atomic<bool>& cancel,
int n_draft_max,
3875 const std::string& draft_path,
3876 std::chrono::steady_clock::time_point t0,
3877 const std::string& tool_grammar,
bool tool_grammar_lazy,
3878 const std::string& generation_prompt) {
3880 state.ctx_tgt = ctx_tgt;
3881 state.ctx_dft = ctx_dft;
3883 n_draft_max, draft_path,
3884 tool_grammar, tool_grammar_lazy,
3886 if (!init_err.empty()) {
3889 std::move(init_err));
3902 const std::vector<Message>& messages,
3904 std::function<
void(std::string_view)> on_token,
3905 std::atomic<bool>& cancel,
3908 const std::string& draft_path)
3910 auto t0 = entropic::log::now();
3915 if (!pre_err.empty()) {
3917 (pre_err.find(
"requires ACTIVE") != std::string::npos)
3920 result = spec_error(code, std::move(pre_err));
3926 "speculative prompt must have at least 2 tokens");
3928 logger->info(
"Speculative: {} input tokens, max_tokens={}, "
3933 cancel, n_draft_max, draft_path, t0,
3966 auto& dp = common_speculative_get_draft_params(state.spec, state.seq_id);
3969 dp.n_past = state.n_past;
3970 dp.id_last = state.id_last;
3971 dp.prompt = &state.prompt_tgt;
3972 dp.result = &state.draft;
3973 common_speculative_draft(state.spec);
3974 return static_cast<int>(state.draft.size());
3988bool mtp_decode_and_process(SpeculativeRunState& state) {
3990 if (llama_decode(state.ctx_tgt, state.batch_tgt) != 0) {
3992 state.error_message =
"MTP target decode failed";
3993 state.finish_reason =
"error";
3996 if (!common_speculative_process(state.spec, state.batch_tgt)) {
3998 state.error_message =
"common_speculative_process failed";
3999 state.finish_reason =
"error";
4011bool mtp_accept_round(
4012 SpeculativeRunState& state,
int n_max,
const llama_vocab* vocab,
4013 int max_tokens, std::function<
void(std::string_view)>& on_token,
4014 std::atomic<bool>& cancel) {
4015 int drafted = mtp_run_draft(state, n_max);
4016 if (!mtp_decode_and_process(state)) {
return false; }
4017 auto ids = common_sampler_sample_and_accept_n(
4018 state.smpl, state.ctx_tgt, state.draft);
4019 int accepted =
static_cast<int>(ids.size()) - 1;
4020 if (accepted < 0) { accepted = 0; }
4027 common_speculative_accept(state.spec, state.seq_id, accepted);
4029 state.n_drafted += drafted;
4030 state.n_accepted += accepted;
4033 state.n_past +=
static_cast<int>(ids.size());
4035 state, ids, vocab, max_tokens, on_token, cancel);
4036 state.draft.clear();
4049bool mtp_process_chunk(SpeculativeRunState& state,
int off,
int chunk) {
4050 common_batch_clear(state.batch_tgt);
4051 for (
int j = 0; j < chunk; ++j) {
4052 common_batch_add(state.batch_tgt, state.prompt_tgt[
off + j],
4053 off + j, {state.seq_id},
false);
4055 if (llama_decode(state.ctx_tgt, state.batch_tgt) != 0) {
return false; }
4056 return common_speculative_process(state.spec, state.batch_tgt);
4066bool mtp_prefill_and_seed(SpeculativeRunState& state) {
4067 int total =
static_cast<int>(state.prompt_tgt.size());
4068 if (total == 0) {
return true; }
4069 int n_batch = llama_n_batch(state.ctx_tgt);
4070 for (
int off = 0;
off < total;
off += n_batch) {
4071 int chunk = std::min(n_batch, total -
off);
4072 if (!mtp_process_chunk(state,
off, chunk)) {
return false; }
4086std::string mtp_init_decoder(
4087 SpeculativeRunState& state, llama_model* model_tgt,
4088 const GenerationParams& params,
int n_max,
4089 const std::string& tool_grammar,
4090 bool tool_grammar_lazy,
4091 const std::string& generation_prompt) {
4092 auto common_sampling =
4093 to_common_sampling(params, tool_grammar, tool_grammar_lazy,
4095 state.smpl = common_sampler_init(model_tgt, common_sampling);
4096 if (!state.smpl) {
return "common_sampler_init failed"; }
4097 common_params_speculative sp;
4098 sp.types = {COMMON_SPECULATIVE_TYPE_DRAFT_MTP};
4099 sp.draft.n_max = n_max;
4100 sp.draft.ctx_tgt = state.ctx_tgt;
4101 sp.draft.ctx_dft = state.ctx_dft;
4102 state.spec = common_speculative_init(sp, 1);
4104 common_sampler_free(state.smpl);
4105 state.smpl =
nullptr;
4106 return "common_speculative_init (MTP) failed";
4108 state.batch_tgt = llama_batch_init(llama_n_batch(state.ctx_tgt), 0, 1);
4109 state.batch_initialized =
true;
4122std::string mtp_init_run(
4123 SpeculativeRunState& state, llama_model* model_tgt,
4124 const std::vector<llama_token>&
tokens,
4125 const GenerationParams& params,
int n_max,
4126 const std::string& tool_grammar,
bool tool_grammar_lazy,
4127 const std::string& generation_prompt) {
4128 state.id_last =
tokens.back();
4129 state.prompt_tgt.assign(
tokens.begin(),
tokens.end() - 1);
4130 state.n_past =
static_cast<int>(
tokens.size()) - 1;
4131 llama_memory_clear(llama_get_memory(state.ctx_tgt),
true);
4132 auto err = mtp_init_decoder(state, model_tgt, params, n_max,
4133 tool_grammar, tool_grammar_lazy,
4135 if (!err.empty()) {
return err; }
4136 if (!mtp_prefill_and_seed(state)) {
return "MTP prefill/process failed"; }
4137 common_speculative_begin(state.spec, state.seq_id, state.prompt_tgt);
4147 SpeculativeRunState& state,
int n_max,
const llama_vocab* vocab,
4148 int max_tokens, std::function<
void(std::string_view)>& on_token,
4149 std::atomic<bool>& cancel) {
4150 while (state.n_generated < max_tokens) {
4151 if (cancel.load(std::memory_order_acquire)) {
4153 state.finish_reason =
"cancelled";
4156 if (!mtp_accept_round(state, n_max, vocab, max_tokens,
4157 on_token, cancel)) {
4161 if (state.finish_reason.empty()) {
4162 state.finish_reason = (state.n_generated >= max_tokens)
4163 ?
"length" :
"stop";
4172GenerationResult mtp_run_from_tokens(
4173 llama_context* ctx_tgt, llama_context* ctx_dft, llama_model* model_tgt,
4174 const std::vector<llama_token>&
tokens,
const GenerationParams& params,
4175 std::function<
void(std::string_view)>& on_token,
4176 std::atomic<bool>& cancel,
int n_max,
4177 const std::vector<std::string>& stop,
4178 std::chrono::steady_clock::time_point t0,
4179 const std::string& tool_grammar,
bool tool_grammar_lazy,
4180 const std::string& generation_prompt) {
4181 SpeculativeRunState state;
4182 state.ctx_tgt = ctx_tgt;
4183 state.ctx_dft = ctx_dft;
4185 auto init_err = mtp_init_run(state, model_tgt,
tokens, params, n_max,
4186 tool_grammar, tool_grammar_lazy,
4188 if (!init_err.empty()) {
4191 std::move(init_err));
4193 mtp_run_loop(state, n_max, llama_model_get_vocab(model_tgt),
4194 params.max_tokens, on_token, cancel);
4229 const std::function<
void(std::string_view)>& on_token,
4230 const std::string& head_path,
int n_max) {
4234 static_cast<bool>(on_token));
4237 "MTP requires an ACTIVE target");
4238 }
else if (!reason.empty()) {
4254 "speculative.n_draft+1 ("
4256 +
") exceeds n_batch (" + std::to_string(llama_n_batch(
ctx_))
4257 +
"); reduce n_draft or raise n_batch");
4285 const std::vector<Message>& messages,
4287 std::function<
void(std::string_view)> on_token,
4288 std::atomic<bool>& cancel,
4289 const std::string& head_path,
4292 auto t0 = entropic::log::now();
4302 "MTP prompt must have at least 2 tokens");
4304 logger->info(
"MTP: {} input tokens, max_tokens={}, n_max={}",
4322 const std::string& prompt,
4325 auto t0 = entropic::log::now();
4329 logger->info(
"Complete: {} input tokens, max_tokens={}",
4331 log_sampler_config(params);
4333 finalize_result(result, t0);
4367 int idx =
static_cast<int>(cap);
4369 if (idx < 0 || idx >=
count) {
4376 static constexpr bool always[] = {
4377 false,
false,
true,
true,
true,
true,
4378 false,
true,
true,
false,
false,
true,
4383 bool result = always[idx];
4416 bi.
name =
"llama.cpp";
4417#if defined(ENTROPIC_BACKEND_CUDA)
4419#elif defined(ENTROPIC_BACKEND_VULKAN)
4434 char desc[256] = {};
4435 llama_model_desc(
model_, desc,
sizeof(desc));
4449 if (
ctx_ ==
nullptr) {
4452 auto mem = llama_get_memory(
ctx_);
4454 llama_memory_clear(mem,
true);
4456 llama_memory_seq_rm(mem, seq_id, -1, -1);
4478 int seq_id, std::vector<uint8_t>& buffer)
const {
4479 if (
ctx_ ==
nullptr) {
return false; }
4480 size_t sz = llama_state_seq_get_size(
4481 ctx_,
static_cast<llama_seq_id
>(seq_id));
4482 if (sz == 0) {
return false; }
4484 size_t written = llama_state_seq_get_data(
4485 ctx_, buffer.data(), sz,
4486 static_cast<llama_seq_id
>(seq_id));
4487 return written == sz;
4505 int seq_id,
const std::vector<uint8_t>& buffer) {
4506 if (
ctx_ ==
nullptr || buffer.empty()) {
return false; }
4507 size_t result = llama_state_seq_set_data(
4508 ctx_, buffer.data(), buffer.size(),
4509 static_cast<llama_seq_id
>(seq_id));
ChatAdapter concrete base class.
gh#98 (v2.8.0) same-prefix batch-generation decision logic.
virtual std::vector< GenerationResult > do_generate_batch(const std::vector< std::vector< Message > > &requests, const std::vector< GenerationParams > ¶ms, std::atomic< bool > &cancel)
Subclass same-prefix batch generation (gh#98, v2.8.0).
std::string last_error_
Last error message for diagnostics.
bool is_active() const
True when state is ACTIVE.
ModelState state() const
Current lifecycle state (lock-free read).
const ModelConfig & config() const
Stored model config.
int context_length() const
Model's context window size.
std::atomic< ModelState > state_
State transition slot accessible to subclasses for test-only injection.
LlamaCppBackend — common llama.cpp patterns (15% layer).
bool parse_params_valid_
True once a tooled render snapshotted.
int last_gen_decode_calls_
gh#98: batched-decode step count of last batch
bool load_gpu_model()
Load the GGUF model onto the GPU (do_activate step 1).
bool do_load(const ModelConfig &config) override
Load model into CPU RAM (COLD → WARM).
bool do_supports(BackendCapability cap) const override
Declare llama.cpp backend capabilities.
std::vector< GenerationResult > build_batch_results(std::vector< BatchSeq > &seqs)
Detokenize each sequence into a GenerationResult.
std::vector< std::string > effective_stop(const GenerationParams ¶ms) const
params.stop + the sequential tool-call close marker, if applicable.
double last_prefill_ms_
gh#96: prefill wall-clock ms of last generate()
int last_input_tokens_
gh#97: tokenized prompt size of last generate()
GenerationResult decode_loop(const std::vector< llama_token > &tokens, const GenerationParams ¶ms, std::function< void(std::string_view)> on_token, std::atomic< bool > *cancel)
Core decode loop — shared by generate and streaming.
bool is_recurrent_
True if loaded model is recurrent (GDN/Mamba/RWKV).
bool try_warm_reuse(const std::vector< llama_token > &tokens)
gh#96 (v2.7.5): try incremental prefill against resident KV.
LogprobResult do_evaluate_logprobs(const int32_t *tokens, int n_tokens) override
Evaluate per-token log-probabilities via sequential decode.
std::string do_backend_name() const override
Return backend name.
bool is_hybrid_
gh#97: attention + recurrent/SSM memory
bool do_save_state(int seq_id, std::vector< uint8_t > &buffer) const override
Capture a sequence's KV cache into a byte buffer.
std::string render_prompt(const std::vector< Message > &messages, const GenerationParams ¶ms)
Generation render seam: common_chat-with-tools or legacy (gh#87).
std::unique_ptr< PromptCache > prompt_cache_
KV prefix cache (v1.8.3)
void teardown_mtp_draft()
Free the MTP head context + model (gh#106 lifecycle).
std::string parse_generation_prompt_
Last TOOLED render's gen prompt.
std::vector< GenerationResult > run_batched_decode(const std::vector< std::vector< llama_token > > &toks, const std::vector< GenerationParams > ¶ms, std::size_t shared, std::atomic< bool > &cancel)
Run the gh#98 multi-seq batched decode (v2.8.0).
GenerationResult do_generate(const std::vector< Message > &messages, const GenerationParams ¶ms) override
Generate a complete response using chat template.
void reload_model_cpu_only()
Reload the model CPU-only for the WARM state (do_deactivate tail).
std::string render_with_tools(const std::vector< Message > &messages, const GenerationParams ¶ms)
Render messages through common_chat WITH the active tools.
void sample_batch_active(std::vector< BatchSeq > &seqs)
Sample+accept+classify each still-active sequence.
bool common_chat_parse_reliable() const
True iff common_chat parsing is reliable for the last render (gh#87).
std::string active_tools_json_
MCP tool defs for next render.
GenerationResult do_complete(const std::string &prompt, const GenerationParams ¶ms) override
Raw text completion without chat template.
int last_prefill_tokens_
gh#96: prompt tokens decoded by last generate()
std::vector< llama_token > tokenize(const std::string &text, bool add_special) const
Tokenize text using model vocabulary.
bool create_inference_context()
Create the llama context + prompt cache (do_activate step 2).
const llama_vocab * vocab_
Vocabulary (from model_)
std::string tool_call_close_marker() const override
Tool-call close marker for the captured chat format (gh#103).
bool have_chat_params_
True once a tool render captured params.
int compute_prefix_token_count(const std::vector< Message > &messages, const GenerationParams ¶ms)
Compute token count of system messages only.
std::unique_ptr< SamplerFactory > sampler_factory_
Factory used by the decode loop to build per-generation samplers.
void release_temp_seqs(std::vector< BatchSeq > &seqs)
Release every batch sequence's temp seq_id (seq 0 excluded).
std::string detokenize(llama_token token) const
Detokenize a single token.
void set_active_tools(const std::string &tools_json)
Stage tool definitions for the next common_chat render (gh#87).
void init_mmproj_if_configured()
Initialize the libmtmd context if mmproj is configured.
int last_chat_format_
Captured common_chat_format.
GenerationResult generate_speculative_with_draft(const std::vector< Message > &messages, const GenerationParams ¶ms, std::function< void(std::string_view token)> on_token, std::atomic< bool > &cancel, LlamaCppBackend &draft, int n_draft_max, const std::string &draft_path)
Speculative-decoding kernel with explicit draft backend.
llama_context * ctx_
Inference context (ACTIVE)
bool run_prefill(const std::vector< llama_token > &tokens)
Run batched prefill on input tokens.
GenerationResult run_sampling_loop(const GenerationParams ¶ms, std::function< void(std::string_view token)> on_token, std::atomic< bool > *cancel, const std::chrono::steady_clock::time_point &t0)
Sample tokens until stop / max_tokens / cancel.
llama_seq_id next_temp_seq_id_
gh#98: monotonic high-water for NEW temp seq_ids (the old 1 + size() handed out duplicates when the p...
std::string last_generation_prompt_
Captured generation_prompt.
GenerationResult mtp_guard(const GenerationParams ¶ms, const std::function< void(std::string_view)> &on_token, const std::string &head_path, int n_max)
Validate MTP run preconditions (gh#108, fail-fast/fail-loud).
bool restore_cached_prefix(const CacheEntry *cached, const std::vector< llama_token > &tokens)
Restore KV state from cache and decode remaining tokens.
void save_prefix_to_cache(const CacheKey &key, int prefix_tokens)
Capture seq 0 KV state and store under the given key.
std::vector< int32_t > tokenize_text(const std::string &text) const override
Tokenize text to token IDs using model vocabulary.
int mtp_n_max_
MTP draft window (n_max) of the live head.
bool is_recurrent() const
Check if loaded model is recurrent.
std::string step_token(Sampler &sampler, std::string &generated, std::function< void(std::string_view)> &on_token, const std::vector< std::string > &stop)
Generate one token and append to output.
GenerationResult generate_after_prefill(Sampler &sampler, const GenerationParams ¶ms, std::function< void(std::string_view)> on_token, std::atomic< bool > *cancel)
The post-prefill sampling loop (extracted from decode_loop).
entropic_error_t mtmd_prefill(const std::string &prompt, const std::vector<::mtmd_bitmap * > &bitmaps, std::string &err_msg)
Run mtmd_tokenize + mtmd_helper_eval_chunks on a prompt.
void run_batch_gen_loop(std::vector< BatchSeq > &seqs, int max_steps, std::atomic< bool > &cancel)
Decode all sequences together until each finishes.
bool run_prefill_cached(const std::vector< llama_token > &tokens, const std::string &system_prompt, const std::vector< Message > &messages, const GenerationParams ¶ms)
Run prefill with prompt cache integration.
std::string mtp_head_path_
Path the live mtp_draft_ctx_ was built from.
GenerationResult do_generate_text_only(const std::vector< Message > &messages, const GenerationParams ¶ms)
Text-only batch generation (extracted from do_generate).
bool do_restore_state(int seq_id, const std::vector< uint8_t > &buffer) override
Restore a sequence's KV cache from a byte buffer.
std::string apply_chat_template(const std::vector< Message > &messages, const GenerationParams ¶ms) const
Apply chat template to messages.
CommonChatResult parse_response(const std::string &raw) const
Parse a raw model emission via the last captured render params.
bool prefill_batch_suffixes(std::vector< BatchSeq > &seqs, const std::vector< std::vector< llama_token > > &toks, std::size_t shared)
Prefill each request's suffix; set per-seq logits_idx.
std::unique_ptr< Tokenizer > tokenizer_
Tokenizer used by tokenize_text / do_count_tokens / internal tokenize/detokenize.
GenerationResult do_generate_streaming(const std::vector< Message > &messages, const GenerationParams ¶ms, std::function< void(std::string_view token)> on_token, std::atomic< bool > &cancel) override
Streaming generation with per-token callback.
bool has_vision_
Cached mtmd_support_vision(mtmd_ctx_) result.
void inject_tokenizer_for_test(std::unique_ptr< Tokenizer > tokenizer)
Inject a tokenizer for unit testing (v2.3.10).
bool decode_tokens_from(const std::vector< llama_token > &tokens, int start_offset)
Decode tokens starting at a given offset.
bool prefill_dispatch(const std::vector< llama_token > &tokens, const std::string &system_prompt, const std::vector< Message > &messages, const GenerationParams ¶ms)
Cache-aware prefill dispatch (gh#96 v2.7.5: extracted body of run_prefill_cached so the wrapper owns ...
void release_temp_seq_id(llama_seq_id seq_id)
Release a temporary sequence ID back to the pool.
std::unique_ptr< Sampler > create_sampler(const GenerationParams ¶ms) const
Build a Sampler for one generation from params.
int do_count_tokens(const std::string &text) const override
Count tokens in text.
::mtmd_context * mtmd_ctx_
libmtmd context, or nullptr if no mmproj loaded.
bool require_tool_call_
gh#134 (v2.10.4): when true the render asks llama.cpp for COMMON_CHAT_TOOL_CHOICE_REQUIRED,...
std::string tool_grammar_
Render-derived tool-call GBNF.
std::string last_parser_
Captured serialized PEG arena.
GenerationResult generate_multimodal(const std::vector< Message > &messages, const GenerationParams ¶ms, std::function< void(std::string_view token)> on_token, std::atomic< bool > *cancel)
Multimodal generation core (v1.9.11 Phases 5–7).
std::mutex seq_id_mutex_
Guards temp seq_id pool (v1.9.10)
bool do_clear_state(int seq_id) override
Clear KV cache or recurrent hidden state.
bool prefill_shared_and_fanout(std::vector< BatchSeq > &seqs, const std::vector< llama_token > &seq0, std::size_t shared)
Prefill shared prefix into seq 0 + seq_cp fan-out.
std::string apply_chat_template_lowlevel(const std::vector< Message > &messages) const
Low-level GGUF template path (gh#86 fallback, v2.6.1).
static float extract_token_logprob(const float *logits, int32_t next_token, int n_vocab)
Extract log-probability for a token from logits.
void do_deactivate() override
Deactivate: free context, reload model CPU-only.
GenerationResult generate_mtp(const std::vector< Message > &messages, const GenerationParams ¶ms, std::function< void(std::string_view token)> on_token, std::atomic< bool > &cancel, const std::string &head_path, int n_max)
Speculative generation via a target-owned MTP head (gh#106).
bool tool_grammar_lazy_
Arm on trigger vs bind eagerly.
BackendInfo do_info() const override
Populate backend metadata from llama.cpp model.
std::vector< GenerationResult > do_generate_batch(const std::vector< std::vector< Message > > &requests, const std::vector< GenerationParams > ¶ms, std::atomic< bool > &cancel) override
Same-prefix batch generation (gh#98, v2.8.0).
std::string parse_parser_
Last TOOLED render's PEG arena.
bool do_activate() override
Activate model on GPU (WARM → ACTIVE).
bool prepare_batch_seqs(std::vector< BatchSeq > &seqs, const std::vector< GenerationParams > ¶ms)
Build per-request sampler chains + seq ids.
bool build_mtp_head(const std::string &head_path)
Load the MTP head GGUF + create its shared-KV context (gh#106).
bool prefill_and_cache_prefix(const std::vector< llama_token > &tokens, int prefix_tokens, const CacheKey &key)
Two-pass prefill: prefix-only prefill → save → rest.
std::mutex mtp_mutex_
gh#108: serialises MTP head setup/teardown vs in-flight generate_mtp (no deactivate-during-generate U...
llama_seq_id allocate_temp_seq_id()
Allocate a temporary sequence ID for evaluation.
PromptCacheConfig prompt_cache_config_
Cache config (v1.8.3)
int parse_chat_format_
Last TOOLED render's format.
std::vector< llama_token > resident_tokens_
gh#96: tokens resident in KV seq 0 (warm-keep)
llama_model * mtp_draft_model_
MTP head GGUF (separate, trunk-sharing)
void do_unload() override
Full unload — free all resources, clear prompt cache.
llama_model * model_
Loaded model (WARM+)
~LlamaCppBackend() override
Free llama.cpp + mtmd resources on destruction.
void invalidate_resident_kv()
gh#96 (v2.7.5): drop the warm-keep resident-KV record.
std::vector< llama_seq_id > free_seq_ids_
Available temporary seq_ids (v1.9.10)
GenerationResult do_generate_speculative(const std::vector< Message > &messages, const GenerationParams ¶ms, std::function< void(std::string_view token)> on_token, std::atomic< bool > &cancel) override
Speculative streaming via the abstract InferenceBackend interface (kept as NOT_SUPPORTED — see kernel...
GenerationResult do_generate_streaming_text_only(const std::vector< Message > &messages, const GenerationParams ¶ms, std::function< void(std::string_view token)> on_token, std::atomic< bool > &cancel)
Text-only streaming generation (extracted from streaming).
static std::string extract_system_prompt(const std::vector< Message > &messages)
Extract the system prompt from messages.
llama_context * mtp_draft_ctx_
MTP context (ctx_type=MTP, ctx_other=ctx_)
void inject_sampler_factory_for_test(std::unique_ptr< SamplerFactory > factory)
Inject a SamplerFactory for unit testing (v2.3.10).
bool setup_mtp_draft(const std::string &head_path, int n_max)
Lazily build the MTP head context against the live ctx_ (gh#106).
Sampler adapter that wraps a llama_sampler* chain.
llama_sampler * native_chain() const
Expose the underlying chain for legacy call sites that have not yet been ported to the Sampler API.
static CacheKey make_key(std::string_view prompt_text, std::string_view model_path)
Compute a cache key from prompt text and model path.
Pure-virtual per-generation sampler used by the decode loop.
virtual int32_t sample()=0
Sample one token from the current decode position.
ENTROPIC_EXPORT const char * entropic_error_name(entropic_error_t code)
Get the human-readable name for an error code.
entropic_error_t
Error codes returned by all C API functions.
@ ENTROPIC_ERROR_CANCELLED
Operation cancelled via cancel token.
@ ENTROPIC_ERROR_IMAGE_LOAD_FAILED
Image file could not be read or decoded (v1.9.11)
@ ENTROPIC_ERROR_SPECULATIVE_INCOMPATIBLE_CONFIG
MTP/speculative enabled but the request can't run correctly (temp>0, grammar, tools,...
@ ENTROPIC_ERROR_NOT_SUPPORTED
Capability not supported by this backend (v1.9.13)
@ ENTROPIC_ERROR_GENERATE_FAILED
Generation failed (context overflow, model error)
@ ENTROPIC_ERROR_INVALID_STATE
Operation not valid in current state (e.g., generate before activate)
@ ENTROPIC_ERROR_LOAD_FAILED
Model load failed (corrupt file, OOM, unsupported format)
Which grammar source constrains a decode (gh#134).
LlamaCppBackend — llama.cpp C API integration.
Concrete llama.cpp Sampler + SamplerFactory (v2.3.10 seam impl).
Concrete llama.cpp tokenizer (v2.3.10 seam impl).
spdlog initialization and logger access.
auto now()
Get current time for timing measurements.
ENTROPIC_EXPORT std::shared_ptr< spdlog::logger > get(const std::string &name)
Get or create a named logger.
double elapsed_ms(std::chrono::steady_clock::time_point start, std::chrono::steady_clock::time_point end)
Compute elapsed milliseconds between two time points.
Pure envelope check for the MTP speculative path (gh#108).
Activate model on GPU (WARM → ACTIVE).
@ IMAGE
Image content (local path or data URI)
static GenerationResult spec_run_from_tokens(llama_context *ctx_tgt, llama_context *ctx_dft, llama_model *model_tgt, const std::vector< llama_token > &tokens, const GenerationParams ¶ms, std::function< void(std::string_view)> &on_token, std::atomic< bool > &cancel, int n_draft_max, const std::string &draft_path, std::chrono::steady_clock::time_point t0, const std::string &tool_grammar, bool tool_grammar_lazy, const std::string &generation_prompt)
Public entry point for the speculative-decoding kernel.
BackendCapability
Capabilities that an inference backend may or may not support.
@ SPECULATIVE_DECODING
Speculative decoding compatibility.
@ HIDDEN_STATE
Recurrent hidden state management (save/load/reset)
@ VISION
Vision / multimodal input (v1.9.11)
@ KV_CACHE
KV cache state management (save/load/clear)
@ AUDIO
Audio input via mtmd audio projector (gh#53, v2.3.0)
@ _COUNT
Sentinel — must be last. Used for iteration/array sizing.
GrammarSource resolve_grammar_source(const std::string &request_grammar, const std::string &tool_grammar)
Resolve which grammar wins.
void append_sequential_stop(GenerationParams ¶ms, const std::string &marker)
Append a tool-call close marker to params.stop for sequential mode.
void coerce_string_typed_args(std::vector< ToolCall > &calls, const std::string &tools_json)
gh#90: coerce numeric scalars back to strings for string-typed tool parameters.
bool batch_is_viable(std::size_t n, int n_parallel, std::size_t shared, bool hybrid, std::size_t total_suffix, int n_batch)
Decide whether the same-prefix batch fast-path is safe + worthwhile.
bool has_images(const std::vector< ContentPart > &parts)
Check if content parts contain any image parts.
static int effective_n_draft(int n_max)
Draft-window size setup_mtp_draft will actually use (gh#106).
static bool spec_decode_both(SpeculativeRunState &state)
Decode the speculative batch on both contexts.
@ tokens
Gate on generated tokens since the last tool call.
@ off
Disabled (default) — no thinking-budget gating.
std::string extract_text(const std::vector< ContentPart > &parts)
Extract concatenated text from content parts.
std::string close_marker_for_format(common_chat_format fmt)
Map a resolved common_chat format to its single-tool-call close marker.
static void spec_ckpt_save_tgt(SpeculativeRunState &state)
Snapshot target state right before the target decode of the speculative batch (when use_ckpt_tgt + no...
@ ok
Tool dispatched, returned non-empty content.
std::size_t batch_shared_prefix_len(const std::vector< std::vector< Tok > > &seqs)
Longest shared token prefix across N request sequences (gh#98).
static void spec_trim_rejected_drafts(SpeculativeRunState &state)
Clear any stale KV positions left by rejected draft tokens.
static bool spec_commit_accepted(SpeculativeRunState &state, const std::vector< llama_token > &ids, const llama_vocab *vocab, int max_tokens, std::function< void(std::string_view)> &on_token, std::atomic< bool > &cancel)
Walk accepted ids, emit tokens via callback, update state.
static std::vector< common_chat_tool > mcp_tools_to_common_chat(const std::string &tools_json)
Convert entropic MCP tool JSON to common_chat_tool defs (gh#87).
static std::string spec_emit_token(SpeculativeRunState &state, llama_token id, const llama_vocab *vocab, int max_tokens, std::function< void(std::string_view)> &on_token, std::atomic< bool > &cancel)
Emit on_token for one accepted id, updating state and returning a stop signal when terminating condit...
std::size_t warm_keep_cut(const std::vector< Tok > &resident, const std::vector< Tok > &incoming, long kv_pos_max)
Decide how many resident-KV tokens warm-keep may reuse this turn.
static void spec_rollback_partial(SpeculativeRunState &state, common_sampler *smpl_save, std::vector< llama_token > &ids)
Partial-acceptance rollback: restore both contexts and the sampler to their pre-draft state,...
static void fill_batch_cell(llama_batch &b, int k, llama_token tok, llama_pos pos, llama_seq_id seq, bool want_logits)
Fill one cell of a multi-seq llama_batch.
static std::string spec_check_preconditions(bool target_active, bool draft_active, llama_context *ctx_tgt, llama_context *ctx_dft)
Validate speculative preconditions and reject NO-seq_rm.
bool grammar_sources_collide(const std::string &request_grammar, const std::string &tool_grammar)
Whether both sources are active — a config error worth reporting.
@ request
GenerationParams::grammar (COMMON_GRAMMAR_TYPE_USER)
@ tool_call
Render-derived (COMMON_GRAMMAR_TYPE_TOOL_CALLS, needs prefill)
@ count
Sentinel — MUST remain last.
@ WARM
mmap'd + mlock'd in RAM
@ COLD
On disk only, no RAM consumed.
void strip_thinking_channels(std::string &content, std::string *reasoning_out)
Strip Gemma 4 QAT reasoning channels (<|channel>…<channel|>) from content, accumulating the stripped ...
static std::string concat_messages_fallback(const std::vector< Message > &messages)
Plain "role: content" join used when templating fails.
static std::optional< common_chat_params > render_common_chat(llama_model *model, const std::vector< Message > &messages, const GenerationParams ¶ms, const std::vector< common_chat_tool > &tools, bool require_tool_call)
Shared common_chat render core for both template paths (gh#87).
static std::string spec_init_run(SpeculativeRunState &state, llama_model *model_tgt, const std::vector< llama_token > &tokens, const GenerationParams ¶ms, int n_draft_max, const std::string &draft_path, const std::string &tool_grammar, bool tool_grammar_lazy, const std::string &generation_prompt)
Initialize speculative run state (prefill + sampler + decoder).
static int spec_run_draft(SpeculativeRunState &state)
Trigger draft generation via common_speculative_draft.
static void spec_run_loop(SpeculativeRunState &state, const llama_vocab *vocab, int max_tokens, std::function< void(std::string_view)> &on_token, std::atomic< bool > &cancel)
Run the accept-round loop until completion / EOS / cancel.
std::string mtp_unsupported_reason(float temperature, bool has_grammar, bool streaming)
Reason MTP cannot run for a request, or "" when the envelope is safe.
static std::vector< common_chat_msg > to_common_chat(const std::vector< Message > &messages)
Convert engine messages to common_chat_msg (gh#86, v2.6.1).
static ToolCall to_entropic_tool_call(const common_chat_tool_call &cc)
Map a common_chat_tool_call to entropic's ToolCall (gh#87).
static std::vector< llama_chat_message > to_llama_chat(const std::vector< Message > &messages)
Convert engine messages to llama_chat_message views.
static std::string spec_init_sampler_and_decoder(SpeculativeRunState &state, llama_model *model_tgt, const GenerationParams ¶ms, int n_draft_max, const std::string &draft_path, const std::string &tool_grammar, bool tool_grammar_lazy, const std::string &generation_prompt)
Initialize the kernel state: clear KV, prefill, sampler, speculative context, batch,...
static GenerationResult spec_finalize(SpeculativeRunState &state, std::chrono::steady_clock::time_point t0)
Speculative kernel against an explicit draft backend.
static bool spec_accept_round(SpeculativeRunState &state, const llama_vocab *vocab, int max_tokens, std::function< void(std::string_view)> &on_token, std::atomic< bool > &cancel)
Run one speculative accept round; return false to stop.
static GenerationResult batch_error_result(const std::string &msg)
Build a single error GenerationResult (gh#98 batch failures).
static void spec_build_batch(SpeculativeRunState &state)
Build the target batch [id_last, draft0, ..., draftN-1].
static int spec_prepare_draft(SpeculativeRunState &state)
Drive one accept round: optional draft generation, decode on both contexts, sample-and-accept,...
static void spec_ckpt_save_dft(SpeculativeRunState &state)
Drive one accept round: draft → decode → sample-and-accept → emit tokens.
static void spec_cleanup(SpeculativeRunState &state)
Free everything allocated by the kernel.
static void spec_ckpt_restore_dft(SpeculativeRunState &state)
Restore the draft's pre-draft state so the upcoming target-batch decode on the draft re-fills cleanly...
Backend metadata for introspection.
size_t ram_bytes
RAM consumed by loaded model (bytes). 0 if COLD.
int max_context_length
Maximum context length.
size_t parameter_count
Number of parameters (from model metadata).
std::string architecture
Architecture family of the loaded model.
std::string compute_device
"cuda", "vulkan", "cpu", "npu"
std::string name
Backend identifier (e.g. "llama.cpp", "axcl")
std::string quantization
Quantization type (e.g. "IQ3_XXS", "Q8_0", "fp16").
size_t vram_bytes
VRAM consumed by loaded model (bytes). 0 if COLD.
std::string model_format
"gguf", "axmodel", "onnx", etc.
Single cached KV state snapshot.
std::vector< uint8_t > data
Raw KV cache bytes.
size_t data_size
data.size() for quick byte accounting
int token_count
Prompt tokens covered by this entry.
64-bit hash used as cache lookup key.
Generation parameters for a single inference call.
std::string grammar
GBNF grammar string (empty = unconstrained)
float temperature
Sampling temperature.
bool enable_thinking
Enable <think> blocks (false if reasoning_budget == 0)
int max_tokens
Maximum tokens to generate.
std::vector< std::string > stop
Stop sequences.
Result of a single generation call.
entropic_error_t error_code
Error code (ENTROPIC_OK if no error)
double generation_time_ms
Wall-clock generation time.
int n_drafted
Tokens proposed by the draft/MTP head across all rounds.
int seq_id
Sequence identifier for multi-sequence backends.
double throughput_tok_s
Measured throughput for this generation (tok/s).
std::string finish_reason
Finish reason: "stop", "length", "error".
std::string content
Generated text (cleaned by adapter)
int n_accepted
Draft tokens the target accepted (≤ n_drafted).
std::string error_message
Error description (empty if no error)
int token_count
Generated token count.
Result of a common_chat parse: native tool calls + split content.
std::vector< ToolCall > tool_calls
Extracted native tool calls.
std::string content
Content with calls + reasoning removed.
std::string reasoning_content
Extracted reasoning/thought block.
Per-token log-probability evaluation result.
std::vector< float > logprobs
Log-prob for each token transition (N-1 values)
int n_logprobs
Number of logprob values (n_tokens - 1)
int n_tokens
Number of input tokens.
float total_logprob
Sum of all logprob values.
float perplexity
exp(-mean(logprobs)) — lower = less surprising
std::vector< int32_t > tokens
Input tokens echoed back for verification.
Model configuration for a single tier.
std::filesystem::path mmproj_path
Vision projector GGUF path.
int gpu_layers
GPU offload layers (-1 = all)
int n_ubatch
Physical micro-batch size for prompt processing (gh#23 MVP item 5).
int context_length
Context window size (512–131072)
std::filesystem::path path
Resolved model file path.
float rope_freq_scale
RoPE frequency scaling factor (gh#23 MVP item 10).
int main_gpu
Primary GPU index for model load (gh#23 MVP item 7).
int n_threads
CPU threads (0 = auto-detect)
bool offload_kqv
Offload KQV ops (incl.
int n_parallel
Max parallel sequences per context (gh#23 MVP item 11).
std::string cache_type_k
KV cache key quantization type.
std::string cache_type_v
KV cache value quantization type.
std::string split_mode
Multi-GPU split mode for model load (gh#23 MVP item 6).
int n_batch
Batch size for prompt processing.
bool flash_attn
Enable flash attention.
bool use_mlock
Lock model in system RAM.
float rope_freq_base
RoPE base frequency override (gh#23 MVP item 9).
size_t max_bytes
Maximum cache RAM (512 MB default)
bool log_hits
Log cache hit/miss at INFO level.
bool enabled
Master switch (false = no caching)
bool warm_keep
gh#96 (v2.7.5): keep the prior turn's KV resident and re-decode only the appended delta (warm-keep / ...
Bundles per-kernel-run mutable state to keep the loop body focused on its responsibility (knots: cogn...
std::vector< std::string > stop
gh#108: stop seqs (effective_stop); empty for gh#36
UTF-8 validation + replacement at every system boundary where bytes change ownership.
ENTROPIC_EXPORT std::string sanitize_utf8(std::string_view input)
Replace invalid UTF-8 byte sequences with U+FFFD.
gh#96 (v2.7.5) warm-keep / incremental-prefill decision logic.