30#include <speculative.h>
32#include <mtmd-helper.h>
34#include <nlohmann/json.hpp>
55bool ends_with(
const std::string& text,
const std::string& suffix) {
56 return text.size() >= suffix.size()
57 && text.compare(text.size() - suffix.size(), suffix.size(), suffix) == 0;
68bool check_stop_sequences(
69 const std::string& text,
70 const std::vector<std::string>& stop_sequences)
72 for (
const auto& stop : stop_sequences) {
73 if (!stop.empty() && ends_with(text, stop)) {
86GenerationResult prefill_error() {
89 r.error_message =
"Prefill decode failed";
90 r.finish_reason =
"error";
100void log_sampler_config(
const GenerationParams& params) {
101 logger->info(
"Sampler: temp={:.2f}, top_k={}, top_p={:.2f}, "
102 "repeat_penalty={:.2f}, thinking={}",
103 params.temperature, params.top_k, params.top_p,
104 params.repeat_penalty, params.enable_thinking);
114void finalize_result(GenerationResult& result,
115 std::chrono::steady_clock::time_point start_time)
120 if (result.token_count > 0 && result.generation_time_ms > 0.0) {
121 result.throughput_tok_s =
122 static_cast<double>(result.token_count)
123 / result.generation_time_ms * 1000.0;
125 logger->info(
"Generated: {} tokens, finish={}, {:.0f}ms, "
127 result.token_count, result.finish_reason,
128 result.generation_time_ms, result.throughput_tok_s);
129 logger->info(
"Content:\n{}", result.content);
151void finalize_generation(GenerationResult& result,
152 const std::string& generated,
int n_generated,
153 const GenerationParams& params,
154 std::chrono::steady_clock::time_point t0)
156 if (n_generated >= params.max_tokens
157 && result.finish_reason.empty()) {
158 result.finish_reason =
"length";
160 result.content = generated;
161 result.token_count = n_generated;
162 finalize_result(result, t0);
177GenerationResult sampler_init_error(
178 std::chrono::steady_clock::time_point t0)
182 r.error_message =
"Sampler factory not initialized";
183 r.finish_reason =
"error";
184 finalize_result(r, t0);
197ggml_type parse_kv_cache_type(
const std::string& s) {
198 static const std::pair<const char*, ggml_type> kTable[] = {
199 {
"f16", GGML_TYPE_F16},
200 {
"f32", GGML_TYPE_F32},
201 {
"bf16", GGML_TYPE_BF16},
202 {
"q8_0", GGML_TYPE_Q8_0},
203 {
"q4_0", GGML_TYPE_Q4_0},
205 for (
const auto& [name, type] : kTable) {
206 if (s == name) {
return type; }
208 logger->warn(
"Unknown cache_type '{}' — defaulting to f16", s);
209 return GGML_TYPE_F16;
221llama_split_mode parse_split_mode(
const std::string& s) {
222 if (s.empty()) {
return LLAMA_SPLIT_MODE_LAYER; }
223 static const std::pair<const char*, llama_split_mode> kTable[] = {
224 {
"none", LLAMA_SPLIT_MODE_NONE},
225 {
"layer", LLAMA_SPLIT_MODE_LAYER},
226 {
"row", LLAMA_SPLIT_MODE_ROW},
228 for (
const auto& [name, mode] : kTable) {
229 if (s == name) {
return mode; }
231 logger->warn(
"Unknown split_mode '{}' — defaulting to layer", s);
232 return LLAMA_SPLIT_MODE_LAYER;
246 llama_model_params m = llama_model_default_params();
250 m.split_mode = parse_split_mode(cfg.
split_mode);
274 llama_model_params mparams = llama_model_default_params();
275 mparams.n_gpu_layers = 0;
276 mparams.use_mmap =
true;
292 logger->info(
"Model loaded (CPU): {} tokens in vocab, recurrent={}",
322 llama_context_params c = llama_context_default_params();
324 c.n_batch =
static_cast<uint32_t
>(cfg.
n_batch);
328 c.n_ubatch =
static_cast<uint32_t
>(cfg.
n_ubatch);
332 : std::thread::hardware_concurrency();
334 ? LLAMA_FLASH_ATTN_TYPE_ENABLED
335 : LLAMA_FLASH_ATTN_TYPE_DISABLED;
347 c.n_seq_max =
static_cast<uint32_t
>(cfg.
n_parallel);
409 llama_model_params mparams = build_load_mparams(
config());
411 if (!
config().tensor_split.empty()) {
413 logger->warn(
"tensor_split not yet implemented, ignoring");
427 model_ = llama_model_load_from_file(
config().path.c_str(), mparams);
434 last_error_ =
"Failed to reload model with GPU layers "
436 +
", gpu_layers=" + std::to_string(
config().gpu_layers)
437 +
") — check llama_ggml.log in the engine's log_dir "
438 "for the underlying llama.cpp/CUDA error";
454 llama_context_params cparams = build_cparams(
config());
456 ctx_ = llama_init_from_model(
model_, cparams);
462 logger->info(
"Context created: n_ctx={}, n_batch={}, "
463 "flash_attn={}, type_k={}, type_v={}",
472 logger->info(
"Prompt cache initialized: max_bytes={}",
491 if (
config().mmproj_path.empty()) {
495 auto ctx_params = mtmd_context_params_default();
498 ? LLAMA_FLASH_ATTN_TYPE_ENABLED
499 : LLAMA_FLASH_ATTN_TYPE_DISABLED;
500 ctx_params.print_timings =
false;
504 logger->error(
"mtmd_init_from_file failed for {} — "
505 "continuing in text-only mode",
506 config().mmproj_path.string());
511 logger->info(
"mmproj loaded from {} — vision={}",
569 if (
ctx_ ==
nullptr) {
570 last_error_ =
"MTP setup requires an ACTIVE target context";
573 if (head_path.empty()) {
576 last_error_ =
"MTP requires speculative.draft.path (the head GGUF); "
580 llama_model_params mparams = llama_model_default_params();
582 mparams.use_mmap =
true;
585 llama_context_params cparams = build_cparams(
config());
586 cparams.ctx_type = LLAMA_CONTEXT_TYPE_MTP;
587 cparams.ctx_other =
ctx_;
588 cparams.n_rs_seq = 0;
594 logger->info(
"MTP head ready: {} (n_max={}, ctx_other=target, "
597 last_error_ =
"MTP head setup failed: " + head_path;
664 llama_model_params mparams = llama_model_default_params();
665 mparams.n_gpu_layers = 0;
666 mparams.use_mmap =
true;
669 model_ = llama_model_load_from_file(
config().path.c_str(), mparams);
678 logger->error(
"Failed to reload CPU model during deactivate "
679 "(path={}); backend left unloaded until next activate",
713 std::unique_ptr<Tokenizer> tokenizer)
734 std::unique_ptr<SamplerFactory> factory)
789 const std::string& text,
bool add_special)
const
796 auto ids =
tokenizer_->tokenize(text, add_special);
799 return {ids.begin(), ids.end()};
815 return tokenizer_->detokenize(
static_cast<int32_t
>(token));
827 return static_cast<int>(
tokens.size());
838 const std::string& text)
const {
863 int n_vocab = llama_vocab_n_tokens(
vocab_);
870 auto* mem = llama_get_memory(
ctx_);
871 llama_memory_clear(mem,
true);
873 for (
int i = 0; i < n_tokens; i++) {
874 llama_token tok =
tokens[i];
875 llama_batch batch = llama_batch_get_one(&tok, 1);
876 int rc = llama_decode(
ctx_, batch);
878 llama_memory_clear(mem,
true);
879 throw std::runtime_error(
"llama_decode failed at logprob pos");
881 if (i < n_tokens - 1) {
882 const float* logits = llama_get_logits_ith(
ctx_, -1);
884 logits,
tokens[i + 1], n_vocab);
890 for (
float lp : result.
logprobs) { sum += lp; }
893 -sum /
static_cast<float>(result.
n_logprobs));
895 llama_memory_clear(mem,
true);
953 float max_logit = logits[0];
954 for (
int v = 1; v < n_vocab; v++) {
955 if (logits[v] > max_logit) {
956 max_logit = logits[v];
959 float sum_exp = 0.0f;
960 for (
int v = 0; v < n_vocab; v++) {
961 sum_exp += std::exp(logits[v] - max_logit);
963 float log_sum_exp = max_logit + std::log(sum_exp);
964 return logits[next_token] - log_sum_exp;
977 const std::vector<Message>& messages) {
978 std::vector<llama_chat_message> chat_msgs;
979 chat_msgs.reserve(messages.size());
980 for (
const auto& msg : messages) {
981 chat_msgs.push_back({msg.role.c_str(), msg.content.c_str()});
1000 const std::vector<Message>& messages) {
1001 std::vector<common_chat_msg> out;
1002 out.reserve(messages.size());
1003 for (
const auto& msg : messages) {
1006 cm.content = msg.content;
1007 out.push_back(std::move(cm));
1027 const std::string& tools_json) {
1028 std::vector<common_chat_tool> out;
1029 if (tools_json.empty()) {
return out; }
1030 auto arr = nlohmann::json::parse(tools_json,
nullptr,
false);
1031 if (!arr.is_array()) {
return out; }
1032 for (
const auto& t : arr) {
1033 common_chat_tool ct;
1034 ct.name = t.value(
"name",
"");
1035 ct.description = t.value(
"description",
"");
1036 if (t.contains(
"inputSchema")) {
1037 ct.parameters = t[
"inputSchema"].dump();
1039 if (!ct.name.empty()) { out.push_back(std::move(ct)); }
1061 auto j = nlohmann::json::parse(cc.arguments,
nullptr,
false);
1062 if (j.is_object()) {
1063 for (
auto it = j.begin(); it != j.end(); ++it) {
1065 it->is_string() ? it->get<std::string>() : it->dump();
1092 const std::vector<Message>& messages,
1094 const std::vector<common_chat_tool>& tools) {
1095 if (model ==
nullptr) {
return std::nullopt; }
1096 auto tmpls = common_chat_templates_init(model,
"");
1097 std::optional<common_chat_params> out;
1099 common_chat_templates_inputs inputs;
1101 inputs.add_generation_prompt =
true;
1102 inputs.use_jinja =
true;
1104 inputs.tools = tools;
1105 if (!tools.empty()) {
1106 inputs.tool_choice = COMMON_CHAT_TOOL_CHOICE_AUTO;
1109 out = common_chat_templates_apply(tmpls.get(), inputs);
1110 }
catch (
const std::exception& e) {
1111 logger->warn(
"jinja chat template apply failed ({}); "
1112 "falling back to low-level template", e.what());
1126 const std::vector<Message>& messages) {
1127 std::string fallback;
1128 for (
const auto& msg : messages) {
1129 fallback += msg.role +
": " + msg.content +
"\n";
1155 const std::vector<Message>& messages,
1159 return rendered ? rendered->prompt
1176 const std::vector<Message>& messages,
1194 logger->info(
"Active tools staged for common_chat render: {} bytes",
1211 const std::vector<Message>& messages,
1230 prompt = rendered->prompt;
1231 logger->info(
"render_with_tools: format={}, {} tool(s), captured "
1289 const std::size_t before = p.
stop.size();
1291 if (p.
stop.size() > before) {
1292 logger->info(
"Sequential tier: tool-call close marker injected "
1293 "post-render (gh#105) — hard-stop at first tool call");
1324 static const std::string kOpen =
"<|channel>";
1325 static const std::string kClose =
"<channel|>";
1326 bool stripped =
false;
1327 bool truncated_unclosed =
false;
1329 while ((pos = content.find(kOpen)) != std::string::npos) {
1331 std::size_t end = content.find(kClose, pos + kOpen.size());
1332 if (end == std::string::npos) { truncated_unclosed =
true; }
1333 std::size_t span_end =
1334 (end == std::string::npos) ? content.size() : end + kClose.size();
1335 if (reasoning_out !=
nullptr) {
1336 std::size_t inner = pos + kOpen.size();
1337 std::size_t inner_end =
1338 (end == std::string::npos) ? content.size() : end;
1339 reasoning_out->append(content, inner, inner_end - inner);
1341 content.erase(pos, span_end - pos);
1344 std::size_t nb = content.find_first_not_of(
" \t\r\n");
1345 content.erase(0, nb == std::string::npos ? content.size() : nb);
1347 if (truncated_unclosed && content.empty()) {
1348 logger->warn(
"strip_thinking_channels: generation hit max_tokens "
1349 "while still inside a <|channel> reasoning block — no "
1350 "answer was ever produced, so content is empty (not a "
1351 "parse error). Raise max_tokens or investigate why this "
1352 "config/prompt doesn't converge within budget.");
1374 const std::string& raw)
const
1384 common_chat_parser_params pp;
1389 auto msg = common_chat_parse(raw,
false, pp);
1394 for (
const auto& tc : msg.tool_calls) {
1400 }
catch (
const std::exception& e) {
1401 logger->warn(
"common_chat_parse failed ({}); raw kept as content",
1421 const std::vector<Message>& messages)
const
1425 int n = llama_chat_apply_template(
1426 nullptr, chat_msgs.data(), chat_msgs.size(),
1429 logger->error(
"llama_chat_apply_template failed (size query)");
1433 std::vector<char> buf(
static_cast<size_t>(n + 1));
1434 int written = llama_chat_apply_template(
1435 nullptr, chat_msgs.data(), chat_msgs.size(),
1436 true, buf.data(),
static_cast<int32_t
>(buf.size()));
1438 logger->error(
"llama_chat_apply_template failed (render)");
1442 return std::string(buf.data(),
static_cast<size_t>(written));
1485 llama_memory_clear(llama_get_memory(
ctx_),
true);
1488 const int n_tokens =
static_cast<int>(
tokens.size());
1490 for (
int i = 0; i < n_tokens; i += n_batch) {
1491 int chunk = std::min(n_batch, n_tokens - i);
1492 std::vector<llama_token> slice(
1494 llama_batch batch = llama_batch_get_one(
1495 slice.data(),
static_cast<int32_t
>(chunk));
1496 if (llama_decode(
ctx_, batch) != 0) {
1497 logger->error(
"Prefill decode failed at offset {}", i);
1523 std::string& generated,
1524 std::function<
void(std::string_view)>& on_token,
1525 const std::vector<std::string>& stop)
1527 llama_token new_token = sampler.
sample();
1529 if (new_token == llama_vocab_eos(
vocab_)
1530 || llama_vocab_is_eog(
vocab_, new_token)) {
1537 on_token(std::string_view(piece));
1539 if (check_stop_sequences(generated, stop)) {
1543 llama_token tok = new_token;
1544 llama_batch single = llama_batch_get_one(&tok, 1);
1545 return (llama_decode(
ctx_, single) == 0) ?
"continue" :
"error";
1563 const std::vector<llama_token>&
tokens,
1565 std::function<
void(std::string_view)> on_token,
1566 std::atomic<bool>* cancel)
1607 std::function<
void(std::string_view)> on_token,
1608 std::atomic<bool>* cancel)
1611 std::string generated;
1612 int n_generated = 0;
1616 bool cancelled = cancel && cancel->load(std::memory_order_acquire);
1623 auto status =
step_token(sampler, generated, on_token, stop);
1624 if (status ==
"continue") {
1627 result.
finish_reason = (status ==
"error") ?
"error" :
"stop";
1628 if (status ==
"error") {
1665 llama_pos pos, llama_seq_id seq,
bool want_logits) {
1670 b.logits[k] = want_logits ? 1 : 0;
1680 std::vector<BatchSeq>& seqs,
1681 const std::vector<GenerationParams>& params) {
1682 for (std::size_t i = 0; i < seqs.size(); ++i) {
1685 if (ls ==
nullptr) {
return false; }
1688 seqs[i].max_tokens = params[i].max_tokens;
1699 std::vector<BatchSeq>& seqs,
const std::vector<llama_token>& seq0,
1700 std::size_t shared) {
1701 std::vector<llama_token> prefix(
1702 seq0.begin(), seq0.begin() +
static_cast<long>(shared));
1704 auto* mem = llama_get_memory(
ctx_);
1705 for (std::size_t i = 1; i < seqs.size(); ++i) {
1706 llama_memory_seq_cp(mem, 0, seqs[i].seq_id, 0,
1707 static_cast<llama_pos
>(shared));
1709 for (
auto& s : seqs) { s.pos =
static_cast<int>(shared); }
1722 std::vector<BatchSeq>& seqs,
1723 const std::vector<std::vector<llama_token>>& toks,
1724 std::size_t shared) {
1729 for (
const auto& t : toks) {
1730 total +=
static_cast<int>(t.size() - std::min(shared, t.size()));
1732 llama_batch batch = llama_batch_init(total, 0,
1733 static_cast<int32_t
>(seqs.size()));
1735 for (std::size_t i = 0; i < seqs.size(); ++i) {
1736 int len =
static_cast<int>(toks[i].size());
1737 for (
int p =
static_cast<int>(shared); p < len; ++p) {
1740 if (p == len - 1) { seqs[i].logits_idx = k; }
1747 bool ok = (llama_decode(
ctx_, batch) == 0);
1748 llama_batch_free(batch);
1758 for (
auto& s : seqs) {
1759 if (!s.active) {
continue; }
1763 llama_token tok = llama_sampler_sample(s.chain,
ctx_, s.logits_idx);
1764 if (llama_vocab_is_eog(
vocab_, tok)) {
1769 s.out.push_back(tok);
1771 if (s.n_gen >= s.max_tokens) { s.active =
false; s.finish =
"length"; }
1786 std::vector<BatchSeq>& seqs,
int max_steps, std::atomic<bool>& cancel) {
1787 llama_batch batch = llama_batch_init(
static_cast<int32_t
>(seqs.size()), 0,
1788 static_cast<int32_t
>(seqs.size()));
1789 for (
int step = 0; step < max_steps; ++step) {
1790 if (cancel.load(std::memory_order_acquire)) {
break; }
1793 for (
auto& s : seqs) {
1794 if (!s.active) {
continue; }
1800 if (k == 0) {
break; }
1803 if (llama_decode(
ctx_, batch) != 0) {
break; }
1805 llama_batch_free(batch);
1814 std::vector<BatchSeq>& seqs) {
1815 std::vector<GenerationResult> out;
1816 out.reserve(seqs.size());
1817 for (
auto& s : seqs) {
1822 out.push_back(std::move(r));
1833 for (std::size_t i = 1; i < seqs.size(); ++i) {
1850 const std::vector<std::vector<llama_token>>& toks,
1851 const std::vector<GenerationParams>& params,
1853 std::atomic<bool>& cancel)
1855 const std::size_t n = toks.size();
1856 std::vector<BatchSeq> seqs(n);
1859 return std::vector<GenerationResult>(
1863 for (
const auto& p : params) { max_steps = std::max(max_steps, p.max_tokens); }
1865 llama_memory_clear(llama_get_memory(
ctx_),
true);
1875 : std::vector<GenerationResult>(
1879 logger->info(
"gh#98 batch: requests={} prefix.tokens_shared={} "
1880 "prefix.tokens_saved={} total_prefill_tokens={} gen_decodes={}",
1904 const std::vector<std::vector<Message>>& requests,
1905 const std::vector<GenerationParams>& params,
1906 std::atomic<bool>& cancel)
1908 const std::size_t n = requests.size();
1909 std::vector<std::vector<llama_token>> toks(n);
1910 for (std::size_t i = 0; i < n; ++i) {
1914 std::size_t total_suffix = 0;
1915 for (
const auto& t : toks) { total_suffix += t.size() - shared; }
1919 total_suffix,
config().n_batch)) {
1935 const std::vector<Message>& messages)
1937 for (
const auto& msg : messages) {
1938 if (msg.role ==
"system") {
1958 const std::vector<llama_token>&
tokens,
int start_offset)
1960 int total =
static_cast<int>(
tokens.size());
1961 if (start_offset >= total) {
return true; }
1963 int n_batch = llama_n_batch(
ctx_);
1964 int n_remaining = total - start_offset;
1966 for (
int off = 0;
off < n_remaining;
off += n_batch) {
1967 int chunk = std::min(n_batch, n_remaining -
off);
1968 llama_batch batch = llama_batch_get_one(
1969 const_cast<llama_token*
>(
tokens.data())
1970 + start_offset +
off,
1972 if (llama_decode(
ctx_, batch) != 0) {
1973 logger->error(
"Decode chunk failed (start={}, off={}, "
1974 "chunk={})", start_offset,
off, chunk);
1999 const std::vector<llama_token>&
tokens)
2001 auto* mem = llama_get_memory(
ctx_);
2002 llama_memory_clear(mem,
true);
2004 size_t restored = llama_state_seq_set_data(
2006 if (restored == 0) {
2007 logger->warn(
"KV state restore failed, falling back to full prefill");
2027 const CacheKey& key,
int prefix_tokens)
2029 size_t state_size = llama_state_seq_get_size(
ctx_, 0);
2030 if (state_size == 0) {
2034 std::vector<uint8_t> buf(state_size);
2035 size_t written = llama_state_seq_get_data(
2036 ctx_, buf.data(), buf.size(), 0);
2038 buf.resize(written);
2052 const std::vector<Message>& messages,
2055 std::vector<Message> sys_msgs;
2056 for (
const auto& msg : messages) {
2057 if (msg.role ==
"system") {
2058 sys_msgs.push_back(msg);
2061 if (sys_msgs.empty()) {
2066 auto sys_tokens =
tokenize(sys_prompt,
true);
2067 return static_cast<int>(sys_tokens.size());
2092 const std::vector<llama_token>&
tokens,
2096 int total =
static_cast<int>(
tokens.size());
2097 if (prefix_tokens <= 0 || prefix_tokens >= total) {
2104 std::vector<llama_token> prefix(
2135 const std::vector<llama_token>&
tokens,
2136 const std::string& system_prompt,
2137 const std::vector<Message>& messages,
2149 auto t_pre = entropic::log::now();
2176 logger->info(
"Prefill (gh#96): {} tokens / {:.1f} ms decoded this turn",
2204 auto* mem = llama_get_memory(
ctx_);
2205 long pos_max =
static_cast<long>(llama_memory_seq_pos_max(mem, 0));
2213 llama_memory_seq_rm(mem, 0,
static_cast<llama_pos
>(cut), -1);
2218 logger->info(
"Warm-keep: reused {} resident tokens, decoded {} "
2219 "delta (of {} total)", cut,
tokens.size() - cut,
2259 const std::vector<llama_token>&
tokens,
2260 const std::string& system_prompt,
2261 const std::vector<Message>& messages,
2266 && !system_prompt.empty();
2268 if (!cache_enabled) {
2273 system_prompt,
config().path.string());
2276 if (cached !=
nullptr) {
2278 logger->info(
"Prompt cache HIT: {} bytes, {} prefix tokens",
2284 logger->warn(
"Cache restore failed, falling back to full prefill");
2286 logger->info(
"Prompt cache MISS: processing full prompt");
2302bool any_image_in(
const std::vector<Message>& messages) {
2303 for (
const auto& m : messages) {
2304 if (
has_images(m.content_parts)) {
return true; }
2321std::vector<Message> strip_image_parts(
2322 const std::vector<Message>& messages) {
2323 std::vector<Message> out = messages;
2324 for (
auto& m : out) {
2325 if (m.content_parts.empty()) {
continue; }
2327 m.content_parts.clear();
2349std::vector<Message> substitute_image_markers(
2350 const std::vector<Message>& messages,
2351 ::mtmd_context* ctx,
2352 std::vector<::mtmd_bitmap*>& bitmaps_out) {
2353 std::vector<Message> out;
2354 out.reserve(messages.size());
2355 const std::string marker = mtmd_default_marker();
2356 for (
const auto& m : messages) {
2359 if (m.content_parts.empty()) {
2360 copy.content = m.content;
2361 out.push_back(std::move(copy));
2365 for (
const auto& p : m.content_parts) {
2370 ::mtmd_bitmap* bm =
nullptr;
2371 if (!p.image_path.empty()) {
2372 bm = mtmd_helper_bitmap_init_from_file(
2373 ctx, p.image_path.c_str(),
false).bitmap;
2375 if (bm ==
nullptr) {
return {}; }
2376 bitmaps_out.push_back(bm);
2379 copy.content = std::move(built);
2380 out.push_back(std::move(copy));
2398 const std::string& prompt,
2399 const std::vector<::mtmd_bitmap*>& bitmaps,
2400 std::string& err_msg)
2402 llama_memory_clear(llama_get_memory(
ctx_),
true);
2403 ::mtmd_input_text mt{prompt.c_str(),
true,
true};
2404 auto* chunks = mtmd_input_chunks_init();
2405 std::vector<const ::mtmd_bitmap*> bm_cptrs(
2406 bitmaps.begin(), bitmaps.end());
2407 int32_t tok_rc = mtmd_tokenize(
2408 mtmd_ctx_, chunks, &mt, bm_cptrs.data(), bm_cptrs.size());
2410 mtmd_input_chunks_free(chunks);
2411 err_msg =
"mtmd_tokenize failed (rc="
2412 + std::to_string(tok_rc) +
")";
2415 llama_pos new_n_past = 0;
2416 int32_t eval_rc = mtmd_helper_eval_chunks(
2418 static_cast<int32_t
>(
config().n_batch),
2420 mtmd_input_chunks_free(chunks);
2422 err_msg =
"mtmd_helper_eval_chunks failed (rc="
2423 + std::to_string(eval_rc) +
")";
2426 logger->info(
"Multimodal prefill complete: n_past={}", new_n_past);
2442 std::function<
void(std::string_view token)> on_token,
2443 std::atomic<bool>* cancel,
2444 const std::chrono::steady_clock::time_point& t0)
2453 finalize_result(result, t0);
2456 std::string generated;
2457 int n_generated = 0;
2460 if (cancel !=
nullptr
2461 && cancel->load(std::memory_order_acquire)) {
2467 *sampler, generated, on_token, stop);
2468 if (status ==
"continue") { ++n_generated;
continue; }
2469 result.
finish_reason = (status ==
"error") ?
"error" :
"stop";
2470 if (status ==
"error") {
2475 finalize_generation(result, generated, n_generated, params, t0);
2485 const std::vector<Message>& messages,
2487 std::function<
void(std::string_view token)> on_token,
2488 std::atomic<bool>* cancel)
2490 auto t0 = entropic::log::now();
2492 std::vector<::mtmd_bitmap*> bitmaps;
2493 auto marked = substitute_image_markers(
2495 if (marked.empty()) {
2496 for (
auto* b : bitmaps) { mtmd_bitmap_free(b); }
2500 "mtmd_helper_bitmap_init_from_file failed";
2504 logger->info(
"Multimodal generate: {} images, prompt={} chars, max_tokens={}",
2505 bitmaps.size(), prompt.size(), params.
max_tokens);
2506 std::string prefill_err;
2508 for (
auto* b : bitmaps) { mtmd_bitmap_free(b); }
2536 const std::vector<Message>& messages,
2539 if (!any_image_in(messages)) {
2545 logger->warn(
"Image content present but model has no vision "
2546 "capability — stripping image parts");
2556 const std::vector<Message>& messages,
2559 auto t0 = entropic::log::now();
2564 logger->info(
"Generate: {} input tokens, max_tokens={}",
2566 log_sampler_config(params);
2570 if (!sampler) {
return sampler_init_error(t0); }
2573 return prefill_error();
2577 std::string generated;
2578 int n_generated = 0;
2579 std::function<void(std::string_view)> no_cb =
nullptr;
2584 *sampler, generated, no_cb, stop);
2585 if (status ==
"continue") { ++n_generated; }
2588 (status ==
"error") ?
"error" :
"stop";
2589 if (status ==
"error") {
2596 finalize_generation(result, generated, n_generated, params, t0);
2611 const std::vector<Message>& messages,
2613 std::atomic<bool>& cancel)
2615 if (!any_image_in(messages)) {
2621 logger->warn(
"Image content present but model has no vision "
2622 "capability — stripping image parts");
2637 const std::vector<Message>& messages,
2639 std::atomic<bool>& cancel)
2641 auto t0 = entropic::log::now();
2646 logger->info(
"Generate (cancellable): {} input tokens, max_tokens={}",
2648 log_sampler_config(params);
2651 if (!sampler) {
return sampler_init_error(t0); }
2654 return prefill_error();
2658 std::string generated;
2659 int n_generated = 0;
2660 std::function<void(std::string_view)> no_cb =
nullptr;
2664 if (cancel.load(std::memory_order_acquire)) {
2670 *sampler, generated, no_cb, stop);
2671 if (status ==
"continue") { ++n_generated; }
2674 (status ==
"error") ?
"error" :
"stop";
2675 if (status ==
"error") {
2682 finalize_generation(result, generated, n_generated, params, t0);
2697 const std::vector<Message>& messages,
2699 std::function<
void(std::string_view token)> on_token,
2700 std::atomic<bool>& cancel)
2702 if (!any_image_in(messages)) {
2704 messages, params, on_token, cancel);
2709 logger->warn(
"Image content present but model has no vision "
2710 "capability — stripping image parts");
2712 strip_image_parts(messages), params, on_token, cancel);
2721 const std::vector<Message>& messages,
2723 std::function<
void(std::string_view token)> on_token,
2724 std::atomic<bool>& cancel)
2726 auto t0 = entropic::log::now();
2730 logger->info(
"Stream: {} input tokens, max_tokens={}",
2732 log_sampler_config(params);
2736 if (!sampler) {
return sampler_init_error(t0); }
2738 return prefill_error();
2741 std::string generated;
2742 int n_generated = 0;
2745 if (cancel.load(std::memory_order_acquire)) {
2751 *sampler, generated, on_token, stop);
2752 if (status ==
"continue") { ++n_generated; }
2755 (status ==
"error") ?
"error" :
"stop";
2756 if (status ==
"error") {
2762 finalize_generation(result, generated, n_generated, params, t0);
2779 const std::vector<Message>& ,
2781 std::function<
void(std::string_view)> ,
2782 std::atomic<bool>& )
2787 "LlamaCppBackend speculative requires an explicit draft "
2788 "backend handle — orchestrator dispatches via "
2789 "generate_speculative_with_draft";
2808common_params_sampling to_common_sampling(
2810 common_params_sampling cps;
2812 cps.top_k = params.
top_k;
2813 cps.top_p = params.
top_p;
2825 for (
auto& [tok, val] : params.logit_bias) {
2826 cps.logit_bias.push_back({tok, val});
2828 if (params.
seed >= 0) {
2829 cps.seed =
static_cast<uint32_t
>(params.
seed);
2843 cps.samplers = {COMMON_SAMPLER_TYPE_PENALTIES,
2844 COMMON_SAMPLER_TYPE_TOP_K,
2845 COMMON_SAMPLER_TYPE_TOP_P};
2846 if (params.
min_p > 0.0f) {
2847 cps.samplers.push_back(COMMON_SAMPLER_TYPE_MIN_P);
2850 cps.samplers.push_back(COMMON_SAMPLER_TYPE_TEMPERATURE);
2852 cps.min_p = params.
min_p;
2853 cps.dry_multiplier = 0.0f;
2854 cps.top_n_sigma = -1.0f;
2874bool spec_prefill_minus_last(
2875 llama_context* ctx,
const std::vector<llama_token>&
tokens) {
2876 int total =
static_cast<int>(
tokens.size()) - 1;
2877 if (total <= 0) {
return true; }
2878 int n_batch = llama_n_batch(ctx);
2879 for (
int off = 0;
off < total;
off += n_batch) {
2880 int chunk = std::min(n_batch, total -
off);
2881 llama_batch batch = llama_batch_get_one(
2882 const_cast<llama_token*
>(
tokens.data()) +
off, chunk);
2883 if (llama_decode(ctx, batch) != 0) {
return false; }
2895 r.error_code = code;
2896 r.error_message = std::move(msg);
2897 r.finish_reason =
"error";
2911 common_speculative* spec =
nullptr;
2912 common_sampler* smpl =
nullptr;
2913 llama_context* ctx_tgt =
nullptr;
2914 llama_context* ctx_dft =
nullptr;
2915 llama_batch batch_tgt{};
2916 bool batch_initialized =
false;
2917 llama_seq_id seq_id = 0;
2919 llama_token id_last = 0;
2920 std::vector<llama_token> prompt_tgt;
2921 std::vector<llama_token> draft;
2922 std::string generated;
2924 int n_generated = 0;
2927 bool has_eos =
false;
2928 std::string finish_reason;
2930 std::string error_message;
2939 bool use_ckpt_tgt =
false;
2940 bool use_ckpt_dft =
false;
2941 common_prompt_checkpoint ckpt;
2951 if (state.spec) { common_speculative_free(state.spec); }
2952 if (state.smpl) { common_sampler_free(state.smpl); }
2953 if (state.batch_initialized) {
2954 llama_batch_free(state.batch_tgt);
2965 common_batch_clear(state.batch_tgt);
2966 common_batch_add(state.batch_tgt, state.id_last,
2967 state.n_past, {state.seq_id},
true);
2968 int pos = state.n_past + 1;
2969 for (
auto draft_token : state.draft) {
2970 common_batch_add(state.batch_tgt, draft_token, pos,
2971 {state.seq_id},
true);
2985 int rc_tgt = llama_decode(state.ctx_tgt, state.batch_tgt);
2987 logger->error(
"Speculative target decode failed: rc={}, "
2988 "n_past={}, draft_size={}",
2989 rc_tgt, state.n_past, state.draft.size());
2991 state.error_message =
"target llama_decode failed";
2992 state.finish_reason =
"error";
2995 int rc_dft = llama_decode(state.ctx_dft, state.batch_tgt);
2997 logger->error(
"Speculative draft decode failed: rc={}, "
2998 "n_past={}, draft_size={}",
2999 rc_dft, state.n_past, state.draft.size());
3001 state.error_message =
"draft llama_decode failed";
3002 state.finish_reason =
"error";
3015 auto& dp = common_speculative_get_draft_params(
3016 state.spec, state.seq_id);
3019 dp.n_past = state.n_past;
3020 dp.id_last = state.id_last;
3021 dp.prompt = &state.prompt_tgt;
3022 dp.result = &state.draft;
3023 common_speculative_draft(state.spec);
3024 return static_cast<int>(state.draft.size());
3042 const llama_vocab* vocab,
int max_tokens,
3043 std::function<
void(std::string_view)>& on_token,
3044 std::atomic<bool>& cancel)
3047 state.prompt_tgt.push_back(state.id_last);
3049 state.n_generated++;
3050 if (llama_vocab_is_eog(vocab,
id)) {
3051 state.has_eos =
true;
3052 state.finish_reason =
"stop";
3055 const std::string piece =
3056 common_token_to_piece(state.ctx_tgt,
id);
3057 state.generated += piece;
3058 if (on_token) { on_token(piece); }
3063 if (check_stop_sequences(state.generated, state.
stop)) {
3064 state.finish_reason =
"stop";
3066 }
else if (cancel.load(std::memory_order_acquire)) {
3068 state.finish_reason =
"cancelled";
3070 }
else if (state.n_generated >= max_tokens) {
3071 state.finish_reason =
"length";
3090 state.ckpt.update_pos(
3091 static_cast<int64_t
>(state.prompt_tgt.size()),
3092 llama_memory_seq_pos_min(
3093 llama_get_memory(state.ctx_tgt), state.seq_id),
3094 llama_memory_seq_pos_max(
3095 llama_get_memory(state.ctx_tgt), state.seq_id));
3096 if (state.use_ckpt_dft) {
3097 state.ckpt.update_dft(state.ctx_dft, state.seq_id,
3098 LLAMA_STATE_SEQ_FLAGS_PARTIAL_ONLY
3099 | LLAMA_STATE_SEQ_FLAGS_ON_DEVICE);
3110 if (state.use_ckpt_tgt && !state.draft.empty()) {
3111 state.ckpt.update_tgt(state.ctx_tgt, state.seq_id,
3112 LLAMA_STATE_SEQ_FLAGS_PARTIAL_ONLY
3113 | LLAMA_STATE_SEQ_FLAGS_ON_DEVICE);
3124 constexpr auto flags = LLAMA_STATE_SEQ_FLAGS_PARTIAL_ONLY
3125 | LLAMA_STATE_SEQ_FLAGS_ON_DEVICE;
3126 if (state.use_ckpt_dft) {
3127 state.ckpt.load_dft(state.ctx_dft, state.seq_id, flags);
3129 llama_memory_seq_rm(llama_get_memory(state.ctx_dft),
3130 state.seq_id, state.ckpt.pos_max + 1, -1);
3144 std::vector<llama_token>& ids) {
3145 constexpr auto flags = LLAMA_STATE_SEQ_FLAGS_PARTIAL_ONLY
3146 | LLAMA_STATE_SEQ_FLAGS_ON_DEVICE;
3147 state.draft = std::move(ids);
3148 state.ckpt.load_tgt(state.ctx_tgt, state.seq_id, flags);
3149 llama_memory_seq_rm(llama_get_memory(state.ctx_tgt),
3150 state.seq_id, state.ckpt.pos_max + 1, -1);
3151 state.ckpt.load_dft(state.ctx_dft, state.seq_id, flags);
3152 llama_memory_seq_rm(llama_get_memory(state.ctx_dft),
3153 state.seq_id, state.ckpt.pos_max + 1, -1);
3154 state.prompt_tgt.resize(
static_cast<size_t>(state.ckpt.n_tokens));
3155 state.n_past =
static_cast<int>(state.prompt_tgt.size());
3157 common_sampler_free(state.smpl);
3158 state.smpl = smpl_save;
3186 llama_memory_seq_rm(llama_get_memory(state.ctx_tgt),
3187 state.seq_id, state.n_past, -1);
3188 llama_memory_seq_rm(llama_get_memory(state.ctx_dft),
3189 state.seq_id, state.n_past, -1);
3200 const std::vector<llama_token>& ids,
3201 const llama_vocab* vocab,
int max_tokens,
3202 std::function<
void(std::string_view)>& on_token,
3203 std::atomic<bool>& cancel) {
3205 for (
auto id : ids) {
3207 state,
id, vocab, max_tokens, on_token, cancel);
3208 if (!signal.empty()) { stop =
true;
break; }
3236 if (!state.draft.empty()) {
3237 return static_cast<int>(state.draft.size());
3253 const llama_vocab* vocab,
3255 std::function<
void(std::string_view)>& on_token,
3256 std::atomic<bool>& cancel)
3262 common_sampler* smpl_save =
nullptr;
3263 if (state.use_ckpt_tgt) {
3264 smpl_save = common_sampler_clone(state.smpl);
3266 auto ids = common_sampler_sample_and_accept_n(
3267 state.smpl, state.ctx_tgt, state.draft);
3268 int accepted =
static_cast<int>(ids.size()) - 1;
3269 if (accepted < 0) { accepted = 0; }
3273 if (state.use_ckpt_tgt
3274 &&
static_cast<int>(ids.size()) - 1
3275 <
static_cast<int>(state.draft.size())) {
3279 if (smpl_save) { common_sampler_free(smpl_save); }
3281 common_speculative_accept(state.spec, state.seq_id, accepted);
3282 state.n_drafted += draft_size_before;
3283 state.n_accepted += accepted;
3289 state.n_past +=
static_cast<int>(ids.size());
3292 state, ids, vocab, max_tokens, on_token, cancel);
3293 state.draft.clear();
3311 bool target_active,
bool draft_active,
3312 llama_context* ctx_tgt, llama_context* ctx_dft) {
3319 const llama_model* model_tgt = llama_get_model(ctx_tgt);
3320 int cap_tgt = common_context_can_seq_rm(ctx_tgt);
3321 int cap_dft = common_context_can_seq_rm(ctx_dft);
3322 logger->info(
"Speculative seq_rm capability: target={}, draft={} "
3323 "(0=NO, 1=PART, 2=FULL)", cap_tgt, cap_dft);
3324 if (!target_active || !draft_active) {
3325 err =
"speculative requires ACTIVE target + draft";
3326 }
else if (llama_model_is_recurrent(model_tgt)
3327 || llama_model_is_hybrid(model_tgt)) {
3328 err =
"speculative refused: architecture (target is "
3329 "recurrent or hybrid; see proposal Implementation "
3331 }
else if (cap_tgt == COMMON_CONTEXT_SEQ_RM_TYPE_NO
3332 || cap_dft == COMMON_CONTEXT_SEQ_RM_TYPE_NO) {
3335 err =
"speculative kernel requires at least FULL seq_rm "
3336 "(target/draft reported NO seq_rm at all)";
3372 const std::string& draft_path) {
3373 auto common_sampling = to_common_sampling(params);
3374 state.smpl = common_sampler_init(model_tgt, common_sampling);
3375 if (!state.smpl) {
return "common_sampler_init failed"; }
3377 common_params_speculative spec_params;
3378 spec_params.types = {COMMON_SPECULATIVE_TYPE_DRAFT_SIMPLE};
3379 spec_params.draft.n_max = (n_draft_max > 0) ? n_draft_max : 16;
3380 spec_params.draft.ctx_tgt = state.ctx_tgt;
3381 spec_params.draft.ctx_dft = state.ctx_dft;
3385 spec_params.draft.mparams.path = draft_path;
3386 state.spec = common_speculative_init(spec_params, 1);
3388 common_sampler_free(state.smpl);
3389 state.smpl =
nullptr;
3390 return "common_speculative_init failed";
3393 common_speculative_begin(state.spec, state.seq_id, state.prompt_tgt);
3394 state.batch_tgt = llama_batch_init(llama_n_batch(state.ctx_tgt), 0, 1);
3395 state.batch_initialized =
true;
3399 state.use_ckpt_tgt = common_context_can_seq_rm(state.ctx_tgt)
3400 == COMMON_CONTEXT_SEQ_RM_TYPE_FULL;
3401 state.use_ckpt_dft = common_context_can_seq_rm(state.ctx_dft)
3402 == COMMON_CONTEXT_SEQ_RM_TYPE_FULL;
3413 const std::vector<llama_token>&
tokens,
3415 const std::string& draft_path) {
3416 state.id_last =
tokens.back();
3417 state.prompt_tgt.assign(
tokens.begin(),
tokens.end() - 1);
3418 state.n_past =
static_cast<int>(
tokens.size()) - 1;
3420 llama_memory_clear(llama_get_memory(state.ctx_tgt),
true);
3421 llama_memory_clear(llama_get_memory(state.ctx_dft),
true);
3423 if (!spec_prefill_minus_last(state.ctx_tgt,
tokens)
3424 || !spec_prefill_minus_last(state.ctx_dft,
tokens)) {
3425 return "speculative prefill failed";
3428 state, model_tgt, params, n_draft_max, draft_path);
3439 std::function<
void(std::string_view)>& on_token,
3440 std::atomic<bool>& cancel) {
3441 while (state.n_generated < max_tokens) {
3442 if (cancel.load(std::memory_order_acquire)) {
3444 state.finish_reason =
"cancelled";
3448 on_token, cancel)) {
3452 if (state.finish_reason.empty()) {
3453 state.finish_reason = (state.n_generated >= max_tokens)
3454 ?
"length" :
"stop";
3471 std::chrono::steady_clock::time_point t0) {
3473 result.
content = state.generated;
3483 entropic::log::elapsed_ms(t0, entropic::log::now());
3491 if (state.n_drafted > 0) {
3492 const float accept_rate =
3493 static_cast<float>(state.n_accepted)
3494 /
static_cast<float>(state.n_drafted);
3495 logger->info(
"Speculative: generated={}, drafted={}, "
3496 "accepted={}, accept_rate={:.3f}",
3497 state.n_generated, state.n_drafted,
3498 state.n_accepted, accept_rate);
3545 llama_context* ctx_tgt, llama_context* ctx_dft, llama_model* model_tgt,
3547 std::function<
void(std::string_view)>& on_token,
3548 std::atomic<bool>& cancel,
int n_draft_max,
3549 const std::string& draft_path,
3550 std::chrono::steady_clock::time_point t0) {
3552 state.ctx_tgt = ctx_tgt;
3553 state.ctx_dft = ctx_dft;
3555 n_draft_max, draft_path);
3556 if (!init_err.empty()) {
3559 std::move(init_err));
3572 const std::vector<Message>& messages,
3574 std::function<
void(std::string_view)> on_token,
3575 std::atomic<bool>& cancel,
3578 const std::string& draft_path)
3580 auto t0 = entropic::log::now();
3585 if (!pre_err.empty()) {
3587 (pre_err.find(
"requires ACTIVE") != std::string::npos)
3590 result = spec_error(code, std::move(pre_err));
3596 "speculative prompt must have at least 2 tokens");
3598 logger->info(
"Speculative: {} input tokens, max_tokens={}, "
3603 cancel, n_draft_max, draft_path, t0);
3635 auto& dp = common_speculative_get_draft_params(state.spec, state.seq_id);
3638 dp.n_past = state.n_past;
3639 dp.id_last = state.id_last;
3640 dp.prompt = &state.prompt_tgt;
3641 dp.result = &state.draft;
3642 common_speculative_draft(state.spec);
3643 return static_cast<int>(state.draft.size());
3657bool mtp_decode_and_process(SpeculativeRunState& state) {
3659 if (llama_decode(state.ctx_tgt, state.batch_tgt) != 0) {
3661 state.error_message =
"MTP target decode failed";
3662 state.finish_reason =
"error";
3665 if (!common_speculative_process(state.spec, state.batch_tgt)) {
3667 state.error_message =
"common_speculative_process failed";
3668 state.finish_reason =
"error";
3680bool mtp_accept_round(
3681 SpeculativeRunState& state,
int n_max,
const llama_vocab* vocab,
3682 int max_tokens, std::function<
void(std::string_view)>& on_token,
3683 std::atomic<bool>& cancel) {
3684 int drafted = mtp_run_draft(state, n_max);
3685 if (!mtp_decode_and_process(state)) {
return false; }
3686 auto ids = common_sampler_sample_and_accept_n(
3687 state.smpl, state.ctx_tgt, state.draft);
3688 int accepted =
static_cast<int>(ids.size()) - 1;
3689 if (accepted < 0) { accepted = 0; }
3696 common_speculative_accept(state.spec, state.seq_id, accepted);
3698 state.n_drafted += drafted;
3699 state.n_accepted += accepted;
3702 state.n_past +=
static_cast<int>(ids.size());
3704 state, ids, vocab, max_tokens, on_token, cancel);
3705 state.draft.clear();
3718bool mtp_process_chunk(SpeculativeRunState& state,
int off,
int chunk) {
3719 common_batch_clear(state.batch_tgt);
3720 for (
int j = 0; j < chunk; ++j) {
3721 common_batch_add(state.batch_tgt, state.prompt_tgt[
off + j],
3722 off + j, {state.seq_id},
false);
3724 if (llama_decode(state.ctx_tgt, state.batch_tgt) != 0) {
return false; }
3725 return common_speculative_process(state.spec, state.batch_tgt);
3735bool mtp_prefill_and_seed(SpeculativeRunState& state) {
3736 int total =
static_cast<int>(state.prompt_tgt.size());
3737 if (total == 0) {
return true; }
3738 int n_batch = llama_n_batch(state.ctx_tgt);
3739 for (
int off = 0;
off < total;
off += n_batch) {
3740 int chunk = std::min(n_batch, total -
off);
3741 if (!mtp_process_chunk(state,
off, chunk)) {
return false; }
3755std::string mtp_init_decoder(
3756 SpeculativeRunState& state, llama_model* model_tgt,
3757 const GenerationParams& params,
int n_max) {
3758 auto common_sampling = to_common_sampling(params);
3759 state.smpl = common_sampler_init(model_tgt, common_sampling);
3760 if (!state.smpl) {
return "common_sampler_init failed"; }
3761 common_params_speculative sp;
3762 sp.types = {COMMON_SPECULATIVE_TYPE_DRAFT_MTP};
3763 sp.draft.n_max = n_max;
3764 sp.draft.ctx_tgt = state.ctx_tgt;
3765 sp.draft.ctx_dft = state.ctx_dft;
3766 state.spec = common_speculative_init(sp, 1);
3768 common_sampler_free(state.smpl);
3769 state.smpl =
nullptr;
3770 return "common_speculative_init (MTP) failed";
3772 state.batch_tgt = llama_batch_init(llama_n_batch(state.ctx_tgt), 0, 1);
3773 state.batch_initialized =
true;
3786std::string mtp_init_run(
3787 SpeculativeRunState& state, llama_model* model_tgt,
3788 const std::vector<llama_token>&
tokens,
3789 const GenerationParams& params,
int n_max) {
3790 state.id_last =
tokens.back();
3791 state.prompt_tgt.assign(
tokens.begin(),
tokens.end() - 1);
3792 state.n_past =
static_cast<int>(
tokens.size()) - 1;
3793 llama_memory_clear(llama_get_memory(state.ctx_tgt),
true);
3794 auto err = mtp_init_decoder(state, model_tgt, params, n_max);
3795 if (!err.empty()) {
return err; }
3796 if (!mtp_prefill_and_seed(state)) {
return "MTP prefill/process failed"; }
3797 common_speculative_begin(state.spec, state.seq_id, state.prompt_tgt);
3807 SpeculativeRunState& state,
int n_max,
const llama_vocab* vocab,
3808 int max_tokens, std::function<
void(std::string_view)>& on_token,
3809 std::atomic<bool>& cancel) {
3810 while (state.n_generated < max_tokens) {
3811 if (cancel.load(std::memory_order_acquire)) {
3813 state.finish_reason =
"cancelled";
3816 if (!mtp_accept_round(state, n_max, vocab, max_tokens,
3817 on_token, cancel)) {
3821 if (state.finish_reason.empty()) {
3822 state.finish_reason = (state.n_generated >= max_tokens)
3823 ?
"length" :
"stop";
3832GenerationResult mtp_run_from_tokens(
3833 llama_context* ctx_tgt, llama_context* ctx_dft, llama_model* model_tgt,
3834 const std::vector<llama_token>&
tokens,
const GenerationParams& params,
3835 std::function<
void(std::string_view)>& on_token,
3836 std::atomic<bool>& cancel,
int n_max,
3837 const std::vector<std::string>& stop,
3838 std::chrono::steady_clock::time_point t0) {
3839 SpeculativeRunState state;
3840 state.ctx_tgt = ctx_tgt;
3841 state.ctx_dft = ctx_dft;
3843 auto init_err = mtp_init_run(state, model_tgt,
tokens, params, n_max);
3844 if (!init_err.empty()) {
3847 std::move(init_err));
3849 mtp_run_loop(state, n_max, llama_model_get_vocab(model_tgt),
3850 params.max_tokens, on_token, cancel);
3874 const std::function<
void(std::string_view)>& on_token,
3875 const std::string& head_path,
int n_max) {
3879 static_cast<bool>(on_token));
3882 "MTP requires an ACTIVE target");
3883 }
else if (!reason.empty()) {
3889 "speculative.n_draft+1 (" + std::to_string(1 +
mtp_n_max_)
3890 +
") exceeds n_batch (" + std::to_string(llama_n_batch(
ctx_))
3891 +
"); reduce n_draft or raise n_batch");
3907 const std::vector<Message>& messages,
3909 std::function<
void(std::string_view)> on_token,
3910 std::atomic<bool>& cancel,
3911 const std::string& head_path,
3914 auto t0 = entropic::log::now();
3924 "MTP prompt must have at least 2 tokens");
3926 logger->info(
"MTP: {} input tokens, max_tokens={}, n_max={}",
3942 const std::string& prompt,
3945 auto t0 = entropic::log::now();
3949 logger->info(
"Complete: {} input tokens, max_tokens={}",
3951 log_sampler_config(params);
3953 finalize_result(result, t0);
3979 int idx =
static_cast<int>(cap);
3981 if (idx < 0 || idx >= count) {
3988 static constexpr bool always[] = {
3989 false,
false,
true,
true,
true,
true,
3990 false,
true,
true,
false,
false,
true,
3995 bool result = always[idx];
4028 bi.
name =
"llama.cpp";
4029#if defined(ENTROPIC_BACKEND_CUDA)
4031#elif defined(ENTROPIC_BACKEND_VULKAN)
4046 char desc[256] = {};
4047 llama_model_desc(
model_, desc,
sizeof(desc));
4061 if (
ctx_ ==
nullptr) {
4064 auto mem = llama_get_memory(
ctx_);
4066 llama_memory_clear(mem,
true);
4068 llama_memory_seq_rm(mem, seq_id, -1, -1);
4090 int seq_id, std::vector<uint8_t>& buffer)
const {
4091 if (
ctx_ ==
nullptr) {
return false; }
4092 size_t sz = llama_state_seq_get_size(
4093 ctx_,
static_cast<llama_seq_id
>(seq_id));
4094 if (sz == 0) {
return false; }
4096 size_t written = llama_state_seq_get_data(
4097 ctx_, buffer.data(), sz,
4098 static_cast<llama_seq_id
>(seq_id));
4099 return written == sz;
4117 int seq_id,
const std::vector<uint8_t>& buffer) {
4118 if (
ctx_ ==
nullptr || buffer.empty()) {
return false; }
4119 size_t result = llama_state_seq_set_data(
4120 ctx_, buffer.data(), buffer.size(),
4121 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.
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).
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_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)
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)
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.
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 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.
@ 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::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)
Shared common_chat render core for both template paths (gh#87).
static std::string concat_messages_fallback(const std::vector< Message > &messages)
Plain "role: content" join used when templating fails.
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 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 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)
Public entry point for the speculative-decoding kernel.
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 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)
Initialize the kernel state: clear KV, prefill, sampler, speculative context, batch,...
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...
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)
Initialize speculative run state (prefill + sampler + decoder).
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 repeat_penalty
Repetition penalty.
float temperature
Sampling temperature.
float frequency_penalty
Frequency-penalty term in llama.cpp's penalties sampler (gh#23 MVP item 3).
float presence_penalty
Presence-penalty term in llama.cpp's penalties sampler (gh#23 MVP item 2).
bool enable_thinking
Enable <think> blocks (false if reasoning_budget == 0)
float min_p
Min-p nucleus sampling threshold (gh#23 MVP item 1).
int max_tokens
Maximum tokens to generate.
float top_p
Nucleus sampling threshold.
int seed
RNG seed for reproducible sampling.
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
gh#96 (v2.7.5) warm-keep / incremental-prefill decision logic.