llama_cpp_backend.cpp¶
src/inference/llama_cpp_backend.cpp
@file llama_cpp_backend.cpp @brief LlamaCppBackend implementation — direct llama.cpp C API.
Owners: @tvanfossen
apply_grammar_source
static void entropic::anonymous_namespace{llama_cpp_backend.cpp}::apply_grammar_source(common_params_sampling &cps, const GenerationParams ¶ms, const std::string &tool_grammar, bool tool_grammar_lazy, const std::string &generation_prompt)Resolve which grammar constrains this decode and apply it.
src/inference/llama_cpp_backend.cpp:3790
Called by to_common_sampling
Calls grammar_sources_collide, is_request_grammar, resolve_grammar_source
Source · 68 lines
static void apply_grammar_source(
common_params_sampling& cps,
const GenerationParams& params,
const std::string& tool_grammar,
bool tool_grammar_lazy,
const std::string& generation_prompt) {
// gh#108 (v2.10.0): propagate GBNF grammar to the MTP sampler chain so
// grammar-constrained tiers are correctly enforced under speculative.mtp.
//
// gh#134 (v2.10.4): a SECOND grammar source now reaches here — the
// tool-call GBNF common_chat_templates_apply derives from the staged tool
// schemas, which was previously discarded at the render. Precedence is
// fail-loud rather than a silent pick: an explicit request grammar
// alongside a tool-derived one is a config error, because the two
// constrain the output to different languages and quietly honouring one
// would make the other's absence undiagnosable.
if (grammar_sources_collide(params.grammar, tool_grammar)) {
logger->error(
"Both a request grammar and a tool-call grammar are active. These "
"constrain decoding to different languages and cannot compose; the "
"request grammar is being used and the staged tools will NOT be "
"structurally enforced. Drop one: clear params.grammar to let the "
"tool schemas constrain, or unstage tools to use your grammar.");
}
const auto source = resolve_grammar_source(params.grammar, tool_grammar);
// gh#154: ask the predicate, not the enum value. `tier` is a
// request-side source that differs only in REPORTING, and comparing
// against `request` alone would silently stop applying it.
if (is_request_grammar(source)) {
cps.grammar = common_grammar(COMMON_GRAMMAR_TYPE_USER, params.grammar);
} else if (source == GrammarSource::tool_call) {
// TOOL_CALLS, not USER: common_grammar_needs_prefill() is true for this
// type, so the sampler prefills generation_prompt into the grammar —
// required because the model's output starts mid-template. The USER
// type skips prefill and the grammar would reject from token one.
cps.grammar = common_grammar(COMMON_GRAMMAR_TYPE_TOOL_CALLS,
tool_grammar);
cps.grammar_lazy = tool_grammar_lazy;
// REQUIRED, not optional: common_sampler_init only prefills when
// generation_prompt is non-empty (sampling.cpp:268, :285). Without it
// the grammar sampler never accepts the tokens the chat template
// already placed in the prompt, so it starts mid-rule and rejects the
// very first sampled token — surfacing as GENERATE_FAILED with empty
// content rather than as a grammar error. Measured exactly that on
// gemma4 before this line existed.
cps.generation_prompt = generation_prompt;
// gh#138: the ONLY observable that the tool-call grammar is in force.
// The orchestration line reports params.grammar, which is the REQUEST
// grammar — it prints "unconstrained" even when this grammar is
// active, so a consumer reading logs cannot tell the difference
// between "tool grammar applied" and "nothing constrained the
// decode". INFO, not DEBUG: this is the diagnostic that would have
// answered gh#138 from the reporter's own logs.
logger->info(
"Tool-call grammar applied: {} bytes, lazy={}, prefill={} bytes",
tool_grammar.size(), tool_grammar_lazy,
generation_prompt.size());
} else if (!tool_grammar.empty()) {
// Tools were staged and a grammar derived, but the request grammar
// won the precedence rule — say so rather than letting the tool
// grammar vanish silently.
logger->warn(
"Tool-call grammar ({} bytes) NOT applied — an explicit request "
"grammar takes precedence. Tool calls are not structurally "
"enforced this turn.",
tool_grammar.size());
}
}Activity · 14 steps
Requirements
build_load_mparams
llama_model_params entropic::anonymous_namespace{llama_cpp_backend.cpp}::build_load_mparams(const entropic::ModelConfig &cfg, const entropic::ExpertOffloadOverrides &moe)Build llama_model_params for GPU model load.
src/inference/llama_cpp_backend.cpp:378
Source · 16 lines
llama_model_params build_load_mparams(
const entropic::ModelConfig& cfg,
const entropic::ExpertOffloadOverrides& moe) {
llama_model_params m = llama_model_default_params();
m.n_gpu_layers = cfg.gpu_layers;
m.load_mode = mmap_load_mode(cfg.use_mlock);
m.split_mode = parse_split_mode(cfg.split_mode);
// gh#23 MVP item 7 (v2.3.19): main_gpu. Effective when split_mode
// is "none" (pin) or "row" (small-tensor placement). 0 keeps
// pre-v2.3.19 load bit-for-bit.
m.main_gpu = cfg.main_gpu;
// gh#153 #42(iii) (v2.13.0, EXPERIMENTAL): routed-expert tensors to the
// host so attention and its KV keep the VRAM. nullptr when off.
m.tensor_buft_overrides = moe.data();
return m;
}Activity · 7 steps
Requirements
do_generate_streaming_text_only
GenerationResult entropic::LlamaCppBackend::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).
src/inference/llama_cpp_backend.cpp:3698
Called by do_generate_streaming
Calls create_sampler, effective_stop, extract_system_prompt, finalize_generation, log_sampler_config, now, on_token, prefill_error, render_prompt, run_prefill_cached, sampler_init_error, step_token 1 more
tokenize
Source · 46 lines
GenerationResult LlamaCppBackend::do_generate_streaming_text_only(
const std::vector<Message>& messages,
const GenerationParams& params,
std::function<void(std::string_view token)> on_token,
std::atomic<bool>& cancel)
{
auto t0 = entropic::log::now();
auto prompt = render_prompt(messages, params);
auto tokens = tokenize(prompt, true);
auto sys = extract_system_prompt(messages);
logger->info("Stream: {} input tokens, max_tokens={}",
tokens.size(), params.max_tokens);
log_sampler_config(params);
// v2.3.10: Sampler seam.
auto sampler = create_sampler(params);
if (!sampler) { return sampler_init_error(t0); }
if (!run_prefill_cached(tokens, sys, messages, params)) {
return prefill_error();
}
GenerationResult result;
std::string generated;
int n_generated = 0;
const auto stop = effective_stop(params); // gh#105: per-call sequential marker
while (n_generated < params.max_tokens) {
if (cancel.load(std::memory_order_acquire)) {
result.finish_reason = "cancelled";
result.error_code = ENTROPIC_ERROR_CANCELLED;
break;
}
auto status = step_token(
*sampler, generated, on_token, stop);
if (status == "continue") { ++n_generated; }
else {
result.finish_reason =
(status == "error") ? "error" : "stop";
if (status == "error") {
result.error_code = ENTROPIC_ERROR_GENERATE_FAILED;
}
break;
}
}
finalize_generation(result, generated, n_generated, params, t0,
last_prefill_tokens_);
return result;
}Activity · 30 steps
Requirements
do_generate_text_only
GenerationResult entropic::LlamaCppBackend::do_generate_text_only(const std::vector< Message > &messages, const GenerationParams ¶ms)
Text-only batch generation (extracted from do_generate).
src/inference/llama_cpp_backend.cpp:3516
Called by do_generate
Calls create_sampler, effective_stop, extract_system_prompt, finalize_generation, log_sampler_config, now, prefill_error, render_prompt, run_prefill_cached, sampler_init_error, step_token, tokenize
Source · 45 lines
GenerationResult LlamaCppBackend::do_generate_text_only(
const std::vector<Message>& messages,
const GenerationParams& params)
{
auto t0 = entropic::log::now();
std::string prompt = render_prompt(messages, params);
auto tokens = tokenize(prompt, true);
std::string sys = extract_system_prompt(messages);
logger->info("Generate: {} input tokens, max_tokens={}",
tokens.size(), params.max_tokens);
log_sampler_config(params);
// v2.3.10: Sampler seam.
auto sampler = create_sampler(params);
if (!sampler) { return sampler_init_error(t0); }
if (!run_prefill_cached(tokens, sys, messages, params)) {
return prefill_error();
}
GenerationResult result;
std::string generated;
int n_generated = 0;
std::function<void(std::string_view)> no_cb = nullptr;
const auto stop = effective_stop(params); // gh#105: per-call sequential marker
while (n_generated < params.max_tokens) {
auto status = step_token(
*sampler, generated, no_cb, stop);
if (status == "continue") { ++n_generated; }
else {
result.finish_reason =
(status == "error") ? "error" : "stop";
if (status == "error") {
result.error_code = ENTROPIC_ERROR_GENERATE_FAILED;
}
break;
}
}
finalize_generation(result, generated, n_generated, params, t0,
last_prefill_tokens_);
return result;
}Activity · 27 steps
GenerationResult entropic::LlamaCppBackend::do_generate_text_only(const std::vector< Message > &messages, const GenerationParams ¶ms, std::atomic< bool > &cancel)
Text-only batch generation with per-token cancel poll.
src/inference/llama_cpp_backend.cpp:3607
Called by none
Calls create_sampler, effective_stop, extract_system_prompt, finalize_generation, log_sampler_config, now, prefill_error, render_prompt, run_prefill_cached, sampler_init_error, step_token, tokenize
Source · 50 lines
GenerationResult LlamaCppBackend::do_generate_text_only(
const std::vector<Message>& messages,
const GenerationParams& params,
std::atomic<bool>& cancel)
{
auto t0 = entropic::log::now();
std::string prompt = render_prompt(messages, params);
auto tokens = tokenize(prompt, true);
std::string sys = extract_system_prompt(messages);
logger->info("Generate (cancellable): {} input tokens, max_tokens={}",
tokens.size(), params.max_tokens);
log_sampler_config(params);
auto sampler = create_sampler(params);
if (!sampler) { return sampler_init_error(t0); }
if (!run_prefill_cached(tokens, sys, messages, params)) {
return prefill_error();
}
GenerationResult result;
std::string generated;
int n_generated = 0;
std::function<void(std::string_view)> no_cb = nullptr;
const auto stop = effective_stop(params); // gh#105: per-call sequential marker
while (n_generated < params.max_tokens) {
if (cancel.load(std::memory_order_acquire)) {
result.finish_reason = "cancelled";
result.error_code = ENTROPIC_ERROR_CANCELLED;
break;
}
auto status = step_token(
*sampler, generated, no_cb, stop);
if (status == "continue") { ++n_generated; }
else {
result.finish_reason =
(status == "error") ? "error" : "stop";
if (status == "error") {
result.error_code = ENTROPIC_ERROR_GENERATE_FAILED;
}
break;
}
}
finalize_generation(result, generated, n_generated, params, t0,
last_prefill_tokens_);
return result;
}Activity · 31 steps
Requirements
do_load_active
bool entropic::LlamaCppBackend::do_load_active(const ModelConfig &config) override
COLD → ACTIVE in ONE whole-file read (gh#148).
src/inference/llama_cpp_backend.cpp:614
Called by none
Calls bind_model_handles, build_load_mparams, config, expert_offload_admits, finish_activation, llama_vocab_n_tokens, load_tier_model
Source · 26 lines
bool LlamaCppBackend::do_load_active(const ModelConfig& config) {
// Outlives the load below — llama.cpp borrows the pattern strings.
const ExpertOffloadOverrides moe(config.cpu_moe_layers,
ggml_backend_cpu_buffer_type());
llama_model_params mparams = build_load_mparams(config, moe);
model_ = load_tier_model(config.path.c_str(), mparams);
if (model_ == nullptr) {
// llama.cpp returns null with no error string — the reason (OOM,
// CUDA init failure, GGUF parse error) is only in ggml's log stream.
last_error_ = "Failed to load model into target residency "
"(path=" + config.path.string()
+ ", gpu_layers=" + std::to_string(config.gpu_layers)
+ ") — check llama_ggml.log in the engine's log_dir "
"for the underlying llama.cpp/CUDA error";
return false;
}
bind_model_handles();
if (!expert_offload_admits(config)) { return false; }
logger->info("Model loaded into target residency: gpu_layers={}, "
"{} tokens in vocab, recurrent={}",
config.gpu_layers, llama_vocab_n_tokens(vocab_),
is_recurrent_);
return finish_activation();
}Activity · 11 steps
Requirements
do_supports
bool entropic::LlamaCppBackend::do_supports(BackendCapability cap) const override
Declare llama.cpp backend capabilities.
src/inference/llama_cpp_backend.cpp:5267
Source · 31 lines
bool LlamaCppBackend::do_supports(BackendCapability cap) const {
int idx = static_cast<int>(cap);
int count = static_cast<int>(BackendCapability::_COUNT);
if (idx < 0 || idx >= count) {
return false;
}
// Static capabilities: true = always supported. Length must equal
// BackendCapability::_COUNT — trailing entries get appended as new
// capabilities are introduced (gh#53 added AUDIO at index 12).
static constexpr bool always[] = {
false, false, true, true, true, true,
false, true, true, false, false, true,
false, // AUDIO — dynamic only (mtmd_support_audio)
};
// Dynamic capabilities override the static table
bool result = always[idx];
if (!result) {
result = (cap == BackendCapability::KV_CACHE && !is_recurrent())
|| (cap == BackendCapability::HIDDEN_STATE && is_recurrent())
|| (cap == BackendCapability::VISION
&& !config().mmproj_path.empty())
|| (cap == BackendCapability::AUDIO
&& mtmd_ctx_ != nullptr
&& mtmd_support_audio(mtmd_ctx_))
|| (cap == BackendCapability::SPECULATIVE_DECODING
&& !is_recurrent());
}
return result;
}Activity · 9 steps
Requirements
do_unload
void entropic::LlamaCppBackend::do_unload() override
Full unload — free all resources, clear prompt cache.
src/inference/llama_cpp_backend.cpp:1094
Called by ~LlamaCppBackend
Calls clear, invalidate_all_resident_kv, teardown_mtp_draft
Source · 50 lines
void LlamaCppBackend::do_unload() {
// gh#108 (v2.9.1): serialise vs in-flight generate_mtp (see do_deactivate).
std::lock_guard<std::mutex> lk(mtp_mutex_);
// gh#108 (v2.10.3): invalidate the sticky parse snapshot. parse_params_valid_
// was set once by a tooled render (gh#105) and never cleared by anything —
// not render_prompt (which clears only have_chat_params_), not unload. If a
// backend instance were reused across a load of a different GGUF, the stale
// PEG arena would survive AND parse_chat_format_ would still report the old
// family, so common_chat_parse_reliable() would answer true and parse the
// new model's output with the previous model's parser. Clearing here makes
// that unreachable by construction rather than by luck of instance reuse.
parse_params_valid_ = false;
parse_chat_format_ = 0;
parse_generation_prompt_.clear();
parse_parser_.clear();
// gh#134 (v2.10.4): same reasoning — a reused backend must not apply the
// previous model's tool-call grammar to a new model's decode.
tool_grammar_.clear();
tool_grammar_lazy_ = false;
if (prompt_cache_) {
prompt_cache_->clear();
}
// gh#106 (v2.9.0): MTP head borrows ctx_ — free it before the context.
teardown_mtp_draft();
// v2.3.10: sampler factory borrows ctx_ + vocab_ — release it
// BEFORE the context/model are freed below so the borrow never
// points into freed memory. (do_deactivate normally releases
// this earlier; this reset is the WARM→COLD safety net.)
sampler_factory_.reset();
// v2.3.10: tokenizer borrows vocab_ — release it BEFORE the model
// is freed so the borrow never points into freed memory.
tokenizer_.reset();
// v2.1.8: mtmd must be freed before the underlying llama_model.
if (mtmd_ctx_ != nullptr) {
mtmd_free(mtmd_ctx_);
mtmd_ctx_ = nullptr;
has_vision_ = false;
}
if (ctx_) {
llama_free(ctx_);
ctx_ = nullptr;
}
invalidate_all_resident_kv(); // gh#96: KV is gone with the context
if (model_) {
llama_model_free(model_);
model_ = nullptr;
}
vocab_ = nullptr;
}Activity · 24 steps
Requirements
effective_n_draft
static int entropic::effective_n_draft(int n_max)
Draft-window size setup_mtp_draft will actually use (gh#106).
src/inference/llama_cpp_backend.cpp:863
Source · 3 lines
static int effective_n_draft(int n_max) {
return (n_max > 0) ? n_max : 16;
}Activity · 1 steps
Requirements
effective_stop
std::vector< std::string > entropic::LlamaCppBackend::effective_stop(const GenerationParams ¶ms) const
params.stop + the sequential tool-call close marker, if applicable.
src/inference/llama_cpp_backend.cpp:1818
Called by do_generate_streaming_text_only, do_generate_text_only, generate_after_prefill, generate_mtp, run_sampling_loop
Source · 11 lines
std::vector<std::string> LlamaCppBackend::effective_stop(
const GenerationParams& params) const {
GenerationParams p = params;
const std::size_t before = p.stop.size();
append_sequential_stop(p, tool_call_close_marker());
if (p.stop.size() > before) {
logger->info("Sequential tier: tool-call close marker injected "
"post-render (gh#105) — hard-stop at first tool call");
}
return p.stop;
}Activity · 6 steps
Requirements
expert_offload_admits
bool entropic::LlamaCppBackend::expert_offload_admits(const ModelConfig &config)
Refuse a loaded model that cannot honour cpu_moe_layers .
src/inference/llama_cpp_backend.cpp:662
Called by do_load_active, load_gpu_model
Calls config, expert_offload_load_refusal, model_expert_count
Source · 30 lines
bool LlamaCppBackend::expert_offload_admits(const ModelConfig& config) {
const int n_layer = llama_model_n_layer(model_);
const std::string why = expert_offload_load_refusal(
config.cpu_moe_layers, n_layer, model_expert_count(model_));
if (why.empty()) {
if (config.cpu_moe_layers > 0) {
// The engagement signal. A knob that silently places nothing
// measures as "the technique does not help", so say what was
// asked for and point at the numbers that prove it landed:
// llama.cpp's own `load_tensors:` buffer-size lines shift from
// the device buffer to CPU_Mapped, and at DEBUG it names every
// tensor it overrode.
logger->info("[expert-offload] EXPERIMENTAL: experts of the "
"first {} of {} layers -> host; attention, KV, "
"router, dense/shared FFN and norms follow "
"gpu_layers={}. Confirm placement in "
"llama_ggml.log ('load_tensors:' buffer sizes).",
config.cpu_moe_layers, n_layer, config.gpu_layers);
}
return true;
}
last_error_ = "cpu_moe_layers refused: " + why;
logger->error("{}", last_error_);
tokenizer_.reset();
llama_model_free(model_);
model_ = nullptr;
vocab_ = nullptr;
return false;
}Activity · 13 steps
Requirements
forget_session_kv
void entropic::LlamaCppBackend::forget_session_kv(const std::string &session_key) override
Drop one session's resident KV and release its slot (gh#165).
src/inference/llama_cpp_backend.cpp:3078
Source · 10 lines
void LlamaCppBackend::forget_session_kv(const std::string& session_key) {
const int slot = residency_.forget_session(session_key);
if (slot == kNoSessionSlot) { return; }
if (ctx_ != nullptr) {
llama_memory_seq_rm(llama_get_memory(ctx_),
static_cast<llama_seq_id>(slot), -1, -1);
}
logger->info("Session '{}' KV dropped from slot {} (context restored)",
session_key, slot);
}Activity · 6 steps
Requirements
generate_after_prefill
GenerationResult entropic::LlamaCppBackend::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).
src/inference/llama_cpp_backend.cpp:2209
Called by decode_loop
Calls effective_stop, mark_length_finish, on_token, sanitize_utf8, step_token
Source · 54 lines
GenerationResult LlamaCppBackend::generate_after_prefill(
Sampler& sampler,
const GenerationParams& params,
std::function<void(std::string_view)> on_token,
std::atomic<bool>* cancel)
{
GenerationResult result;
std::string generated;
int n_generated = 0;
const auto stop = effective_stop(params); // gh#105: per-call sequential marker
while (n_generated < params.max_tokens) {
bool cancelled = cancel && cancel->load(std::memory_order_acquire);
if (cancelled) {
result.finish_reason = "cancelled";
result.error_code = ENTROPIC_ERROR_CANCELLED;
break;
}
auto status = step_token(sampler, generated, on_token, stop);
if (status == "continue") {
++n_generated;
} else {
result.finish_reason = (status == "error") ? "error" : "stop";
if (status == "error") {
result.error_code = ENTROPIC_ERROR_GENERATE_FAILED;
}
break;
}
}
mark_length_finish(result, n_generated, params.max_tokens); // v2.14.6
// gh#136 (4th type_error.316 recurrence): sanitize at INGRESS, where model
// bytes first become a std::string, rather than at each of the ~18 .dump()
// sites downstream. gh#112/113 were closed as "permanent closure of the
// 316 family", then gh#114, gh#118, gh#132 and gh#136 each patched one more
// egress. The exits keep multiplying; the entries do not. Guarding here
// makes every downstream dump safe by construction, and a NEW .dump()
// anywhere cannot reintroduce the bug.
//
// Once at finalization, never per-token: a multi-byte codepoint can split
// across token boundaries and per-token sanitize would corrupt valid
// output (see the same reasoning at response_generator.cpp:360, which has
// guarded the streaming accumulator this way since v2.1.1).
//
// Safe for raw_content consumers: raw_content is a COPY of content
// (orchestrator.cpp:514), and sanitize only replaces bytes that are
// ALREADY invalid UTF-8 — which cannot form part of any valid JSON token,
// so the gh#88 envelope recovery and fenced-JSON fallbacks are unaffected.
result.content = entropic::mcp::sanitize_utf8(generated);
result.token_count = n_generated;
return result;
}Activity · 22 steps
Requirements
generate_mtp
GenerationResult entropic::LlamaCppBackend::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).
src/inference/llama_cpp_backend.cpp:5167
Called by SCENARIO, TEST_CASE, TEST_CASE, run_mtp_qat_mobile, timed_run, try_mtp_route
Calls active_tool_grammar, bind_session_slot, effective_stop, invalidate_all_resident_kv, invalidate_resident_kv, mtp_guard, mtp_reuse_cut, mtp_run_from_tokens, now, on_token, render_prompt, set_resident 2 more
spec_error, tokenize
Source · 46 lines
GenerationResult LlamaCppBackend::generate_mtp(
const std::vector<Message>& messages,
const GenerationParams& params,
std::function<void(std::string_view)> on_token,
std::atomic<bool>& cancel,
const std::string& head_path,
int n_max)
{
auto t0 = entropic::log::now();
std::lock_guard<std::mutex> lk(mtp_mutex_); // serialise vs teardown
GenerationResult result = mtp_guard(params, on_token, head_path, n_max);
if (result.error_code != ENTROPIC_OK) {
return result;
}
bind_session_slot(params);
auto tokens = tokenize(render_prompt(messages, params), true);
if (tokens.size() < 2) {
return spec_error(ENTROPIC_ERROR_GENERATE_FAILED,
"MTP prompt must have at least 2 tokens");
}
const int reuse_cut = mtp_reuse_cut(tokens);
if (reuse_cut == 0) {
invalidate_all_resident_kv(); // cold run: nothing survives the clear
}
logger->info("MTP: {} input tokens, reusing {}, max_tokens={}, n_max={}",
tokens.size(), reuse_cut, params.max_tokens, mtp_n_max_);
auto mtp_result = mtp_run_from_tokens(
ctx_, mtp_draft_ctx_, model_, tokens, params,
on_token, cancel, mtp_n_max_,
effective_stop(params), t0, // gh#108: honor stops
active_tool_grammar(), tool_grammar_lazy_, // gh#134; v2.14.6
parse_generation_prompt_, reuse_cut);
// gh#144 (v2.12.0): publish it so last_prefill_tokens() is meaningful
// under speculative.mtp, exactly as it is on the plain decode path.
last_prefill_tokens_ = mtp_result.prefill_tokens;
if (mtp_result.error_code == ENTROPIC_OK) {
// Record what this slot now holds so the NEXT turn can match against
// it. Only on success: a failed run leaves the KV in a state we did
// not author and must not claim to know.
residency_.set_resident(active_slot_, tokens);
} else {
invalidate_resident_kv();
}
return mtp_result;
}Activity · 20 steps
Requirements
generate_multimodal
GenerationResult entropic::LlamaCppBackend::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).
src/inference/llama_cpp_backend.cpp:3402
Called by do_generate, do_generate_streaming
Calls invalidate_all_resident_kv, log_rendered_markers, mtmd_prefill, now, on_token, render_prompt, run_sampling_loop, substitute_image_markers
Source · 34 lines
GenerationResult LlamaCppBackend::generate_multimodal(
const std::vector<Message>& messages,
const GenerationParams& params,
std::function<void(std::string_view token)> on_token,
std::atomic<bool>* cancel)
{
auto t0 = entropic::log::now();
invalidate_all_resident_kv(); // gh#96: mtmd_prefill mutates seq 0 out-of-band
std::vector<::mtmd_bitmap*> bitmaps;
auto marked = substitute_image_markers(
messages, mtmd_ctx_, bitmaps);
if (marked.empty()) {
for (auto* b : bitmaps) { mtmd_bitmap_free(b); }
GenerationResult err;
err.error_code = ENTROPIC_ERROR_IMAGE_LOAD_FAILED;
err.error_message =
"mtmd_helper_bitmap_init_from_file failed";
return err;
}
auto prompt = render_prompt(marked, params);
logger->info("Multimodal generate: {} images, prompt={} chars, max_tokens={}",
bitmaps.size(), prompt.size(), params.max_tokens);
log_rendered_markers(prompt, bitmaps.size());
std::string prefill_err;
auto rc = mtmd_prefill(prompt, bitmaps, prefill_err);
for (auto* b : bitmaps) { mtmd_bitmap_free(b); }
if (rc != ENTROPIC_OK) {
GenerationResult err;
err.error_code = rc;
err.error_message = std::move(prefill_err);
return err;
}
return run_sampling_loop(params, on_token, cancel, t0);
}Activity · 24 steps
Requirements
load_gpu_model
bool entropic::LlamaCppBackend::load_gpu_model()
Load the GGUF model onto the GPU (do_activate step 1).
src/inference/llama_cpp_backend.cpp:714
Called by do_activate
Calls bind_model_handles, build_load_mparams, config, expert_offload_admits, load_tier_model
Source · 40 lines
bool LlamaCppBackend::load_gpu_model() {
// Outlives the load below — llama.cpp borrows the pattern strings.
const ExpertOffloadOverrides moe(config().cpu_moe_layers,
ggml_backend_cpu_buffer_type());
llama_model_params mparams = build_load_mparams(config(), moe);
if (!config().tensor_split.empty()) {
// TODO: parse tensor_split string into float array for multi-GPU
logger->warn("tensor_split not yet implemented, ignoring");
}
// tokenizer_ borrows the old vocab_; reset it before the free so the
// borrow never dangles. Then free the WARM model and null the
// handles so a failed reload below leaves the backend in a clean,
// recoverable state rather than a dangling one.
tokenizer_.reset();
if (model_ != nullptr) {
llama_model_free(model_);
model_ = nullptr;
vocab_ = nullptr;
}
model_ = load_tier_model(config().path.c_str(), mparams);
if (model_ == nullptr) {
// llama.cpp returns null with no error string — the actual
// reason (OOM, CUDA init failure, GGUF parse error, etc.) only
// surfaces in ggml's log stream. Point the operator at it so
// multi-handle GPU failures (gh#58 v2.2.7 follow-up) are
// diagnosable without source-diving llama.cpp.
last_error_ = "Failed to reload model with GPU layers "
"(path=" + config().path.string()
+ ", gpu_layers=" + std::to_string(config().gpu_layers)
+ ") — check llama_ggml.log in the engine's log_dir "
"for the underlying llama.cpp/CUDA error";
return false;
}
bind_model_handles();
return expert_offload_admits(config());
}Activity · 15 steps
Requirements
mcp_tools_to_common_chat
static std::vector< common_chat_tool > entropic::mcp_tools_to_common_chat(const std::string &tools_json)
Convert entropic MCP tool JSON to common_chat_tool defs (gh#87).
src/inference/llama_cpp_backend.cpp:1443
Source · 17 lines
static std::vector<common_chat_tool> mcp_tools_to_common_chat(
const std::string& tools_json) {
std::vector<common_chat_tool> out;
if (tools_json.empty()) { return out; }
auto arr = nlohmann::json::parse(tools_json, nullptr, false);
if (!arr.is_array()) { return out; }
for (const auto& t : arr) {
common_chat_tool ct;
ct.name = t.value("name", "");
ct.description = t.value("description", "");
if (t.contains("inputSchema")) {
ct.parameters = t["inputSchema"].dump();
}
if (!ct.name.empty()) { out.push_back(std::move(ct)); }
}
return out;
}Activity · 15 steps
Requirements
model_expert_count
int entropic::anonymous_namespace{llama_cpp_backend.cpp}::model_expert_count(const llama_model *model).expert_count from a loaded model's GGUF metadata.
src/inference/llama_cpp_backend.cpp:409
Source · 14 lines
int model_expert_count(const llama_model* model) {
char arch[64] = {0};
if (llama_model_meta_val_str(model, "general.architecture",
arch, sizeof(arch)) < 0) {
return 0;
}
const std::string key = std::string(arch) + ".expert_count";
char value[32] = {0};
if (llama_model_meta_val_str(model, key.c_str(),
value, sizeof(value)) < 0) {
return 0;
}
return std::atoi(value);
}Activity · 8 steps
Requirements
mtmd_prefill
entropic_error_t entropic::LlamaCppBackend::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.
src/inference/llama_cpp_backend.cpp:3289
Source · 41 lines
entropic_error_t LlamaCppBackend::mtmd_prefill(
const std::string& prompt,
const std::vector<::mtmd_bitmap*>& bitmaps,
std::string& err_msg)
{
++kv_full_clear_count_; // gh#158: see kv_full_clear_count()
llama_memory_clear(llama_get_memory(ctx_), true);
// v2.14.6: designated, not positional. A pin bump inserted `text_len`
// second, so the old `{text, true, true}` compiled as text_len=1 /
// parse_special=false: mtmd tokenized ONE character, found no media
// marker, and every image generate failed (rc=2). Naming the fields
// turns the next layout change into a compile error.
::mtmd_input_text mt{.text = prompt.c_str(),
.text_len = prompt.size(),
.add_special = true,
.parse_special = true};
auto* chunks = mtmd_input_chunks_init();
std::vector<const ::mtmd_bitmap*> bm_cptrs(
bitmaps.begin(), bitmaps.end());
int32_t tok_rc = mtmd_tokenize(
mtmd_ctx_, chunks, &mt, bm_cptrs.data(), bm_cptrs.size());
if (tok_rc != 0) {
mtmd_input_chunks_free(chunks);
err_msg = "mtmd_tokenize failed (rc="
+ std::to_string(tok_rc) + ")";
return ENTROPIC_ERROR_GENERATE_FAILED;
}
llama_pos new_n_past = 0;
int32_t eval_rc = mtmd_helper_eval_chunks(
mtmd_ctx_, ctx_, chunks, 0, 0,
static_cast<int32_t>(config().n_batch),
true, &new_n_past);
mtmd_input_chunks_free(chunks);
if (eval_rc != 0) {
err_msg = "mtmd_helper_eval_chunks failed (rc="
+ std::to_string(eval_rc) + ")";
return ENTROPIC_ERROR_GENERATE_FAILED;
}
logger->info("Multimodal prefill complete: n_past={}", new_n_past);
return ENTROPIC_OK;
}Activity · 18 steps
Requirements
mtp_guard
GenerationResult entropic::LlamaCppBackend::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).
src/inference/llama_cpp_backend.cpp:5078
Called by generate_mtp
Calls effective_n_draft, is_active, mtp_unsupported_reason, on_token, setup_mtp_draft, spec_error
Source · 36 lines
GenerationResult LlamaCppBackend::mtp_guard(
const GenerationParams& params,
const std::function<void(std::string_view)>& on_token,
const std::string& head_path, int n_max) {
GenerationResult r; // ENTROPIC_OK by default → proceed
std::string reason = mtp_unsupported_reason(
params.temperature, !params.grammar.empty(),
static_cast<bool>(on_token));
if (!is_active()) {
r = spec_error(ENTROPIC_ERROR_INVALID_STATE,
"MTP requires an ACTIVE target");
} else if (!reason.empty()) {
r = spec_error(ENTROPIC_ERROR_SPECULATIVE_INCOMPATIBLE_CONFIG, reason);
} else if (1 + effective_n_draft(n_max) > llama_n_batch(ctx_)) {
// Bound-check BEFORE setup_mtp_draft allocates. Ordering this the
// other way made the guard's ANSWER depend on process history: an
// out-of-envelope window (e.g. n_draft=100000) is still handed to
// setup_mtp_draft, whose allocation SUCCEEDS in a fresh process —
// so the guard fell through and returned the correct
// SPECULATIVE_INCOMPATIBLE_CONFIG — but FAILS after a prior MTP
// session, returning LOAD_FAILED for the same config. Same input,
// two different typed errors, decided by allocator state. Measured
// as `5 == 54` when a second MTP case ran in one process.
//
// Must use the same normalisation setup_mtp_draft applies, or the
// check disagrees with the value actually used.
r = spec_error(ENTROPIC_ERROR_SPECULATIVE_INCOMPATIBLE_CONFIG,
"speculative.n_draft+1 ("
+ std::to_string(1 + effective_n_draft(n_max))
+ ") exceeds n_batch (" + std::to_string(llama_n_batch(ctx_))
+ "); reduce n_draft or raise n_batch");
} else if (!setup_mtp_draft(head_path, n_max)) {
r = spec_error(ENTROPIC_ERROR_LOAD_FAILED, last_error_);
}
return r;
}Activity · 14 steps
Requirements
parse_response
LlamaCppBackend::CommonChatResult entropic::LlamaCppBackend::parse_response(const std::string &raw) const
Parse a raw model emission via the last captured render params.
src/inference/llama_cpp_backend.cpp:1934
Called by TEST_CASE, TEST_CASE, TEST_CASE, TEST_CASE, TEST_CASE, run_variant, try_template_parse, verify_family_common_chat
Calls coerce_string_typed_args, keep_dropped_tool_text, strip_thinking_channels, to_entropic_tool_call
Source · 36 lines
LlamaCppBackend::CommonChatResult LlamaCppBackend::parse_response(
const std::string& raw) const
{
CommonChatResult result;
// gh#105: decode from the sticky last-TOOLED snapshot (parse_*), NOT the
// live capture — a toolless validator render between the main generation
// and this re-parse would have cleared the live params.
if (!parse_params_valid_) {
result.content = raw;
return result;
}
common_chat_parser_params pp;
pp.format = static_cast<common_chat_format>(parse_chat_format_);
pp.generation_prompt = parse_generation_prompt_;
pp.parser.load(parse_parser_); // mandatory — see header
try {
auto msg = common_chat_parse(raw, /*is_partial=*/false, pp);
result.content = msg.content;
result.reasoning_content = msg.reasoning_content;
// gh#106: Gemma 4 QAT reasoning channels common_chat doesn't parse.
strip_thinking_channels(result.content, &result.reasoning_content);
for (const auto& tc : msg.tool_calls) {
result.tool_calls.push_back(to_entropic_tool_call(tc));
}
// gh#90: gemma <|"|> string-escape loses type through PEG_GEMMA4 —
// restore string typing for params the staged schema declares string.
coerce_string_typed_args(result.tool_calls, active_tools_json_);
// v2.14.6: a call span the parser could not read must not vanish.
keep_dropped_tool_text(raw, result);
} catch (const std::exception& e) {
logger->warn("common_chat_parse failed ({}); raw kept as content",
e.what());
result.content = raw;
}
return result;
}Activity · 10 steps
Requirements
prefill_error
GenerationResult entropic::LlamaCppBackend::prefill_error() const
Build the error result for a prefill that did not run.
src/inference/llama_cpp_backend.cpp:2887
Source · 12 lines
GenerationResult LlamaCppBackend::prefill_error() const {
GenerationResult r;
r.finish_reason = "error";
if (!prefill_refusal_.empty()) {
r.error_code = ENTROPIC_ERROR_EVAL_CONTEXT_FULL;
r.error_message = prefill_refusal_;
return r;
}
r.error_code = ENTROPIC_ERROR_GENERATE_FAILED;
r.error_message = "Prefill decode failed";
return r;
}Activity · 9 steps
Requirements
refuse_over_context
bool entropic::LlamaCppBackend::refuse_over_context(const std::vector< llama_token > &tokens, const std::string &system_prompt)
Refuse this turn when its prompt cannot fit the tier context.
src/inference/llama_cpp_backend.cpp:2858
Called by run_prefill_cached
Calls config, context_fit_overflows, context_overflow_message, staged_tool_count, tokenize
Source · 21 lines
bool LlamaCppBackend::refuse_over_context(
const std::vector<llama_token>& tokens,
const std::string& system_prompt)
{
ContextFit fit;
fit.prompt_tokens = static_cast<int>(tokens.size());
fit.context_length = config().context_length;
if (!context_fit_overflows(fit)) {
prefill_refusal_.clear();
return false;
}
fit.tool_bytes = active_tools_json_.size();
fit.tool_count = staged_tool_count(active_tools_json_);
fit.tool_tokens =
static_cast<int>(tokenize(active_tools_json_, false).size());
fit.system_tokens =
static_cast<int>(tokenize(system_prompt, false).size());
prefill_refusal_ = context_overflow_message(fit);
logger->error("{}", prefill_refusal_);
return true;
}Activity · 13 steps
Requirements
render_common_chat
static std::optional< common_chat_params > entropic::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).
src/inference/llama_cpp_backend.cpp:1513
Source · 34 lines
static std::optional<common_chat_params> render_common_chat(
llama_model* model,
const std::vector<Message>& messages,
const GenerationParams& params,
const std::vector<common_chat_tool>& tools,
bool require_tool_call) {
if (model == nullptr) { return std::nullopt; }
auto tmpls = common_chat_templates_init(model, "");
std::optional<common_chat_params> out;
if (tmpls) {
common_chat_templates_inputs inputs;
inputs.messages = to_common_chat(messages);
inputs.add_generation_prompt = true;
inputs.use_jinja = true;
inputs.enable_thinking = params.enable_thinking; // gh#86
inputs.tools = tools;
if (!tools.empty()) {
// gh#134 (v2.10.4): was hardcoded AUTO, so a mandatory-tool tier
// could always answer in prose. REQUIRED makes upstream build the
// tool-call grammar eagerly (grammar_lazy=false), which the
// sampler now actually applies — see to_common_sampling.
inputs.tool_choice = require_tool_call
? COMMON_CHAT_TOOL_CHOICE_REQUIRED
: COMMON_CHAT_TOOL_CHOICE_AUTO;
}
try {
out = common_chat_templates_apply(tmpls.get(), inputs);
} catch (const std::exception& e) {
logger->warn("jinja chat template apply failed ({}); "
"falling back to low-level template", e.what());
}
}
return out;
}Activity · 15 steps
Requirements
render_prompt
std::string entropic::LlamaCppBackend::render_prompt(const std::vector< Message > &messages, const GenerationParams ¶ms)
Generation render seam: common_chat-with-tools or legacy (gh#87).
src/inference/llama_cpp_backend.cpp:1607
Called by do_generate_batch, do_generate_streaming_text_only, do_generate_text_only, generate_mtp, generate_multimodal, generate_speculative_with_draft
Calls apply_chat_template, render_with_tools
Source · 10 lines
std::string LlamaCppBackend::render_prompt(
const std::vector<Message>& messages,
const GenerationParams& params)
{
if (!active_tools_json_.empty()) {
return render_with_tools(messages, params);
}
have_chat_params_ = false;
return apply_chat_template(messages, params);
}Activity · 4 steps
Requirements
render_with_tools
std::string entropic::LlamaCppBackend::render_with_tools(const std::vector< Message > &messages, const GenerationParams ¶ms)
Render messages through common_chat WITH the active tools.
src/inference/llama_cpp_backend.cpp:1698
Called by TEST_CASE, TEST_CASE, render_prompt, run_variant
Calls apply_chat_template_lowlevel, mcp_tools_to_common_chat, render_common_chat, tool_grammar_for
Source · 66 lines
std::string LlamaCppBackend::render_with_tools(
const std::vector<Message>& messages,
const GenerationParams& params)
{
have_chat_params_ = false;
auto tools = mcp_tools_to_common_chat(active_tools_json_);
auto rendered = render_common_chat(model_, messages, params, tools,
require_tool_call_);
std::string prompt;
if (rendered) {
last_chat_format_ = static_cast<int>(rendered->format);
last_generation_prompt_ = rendered->generation_prompt;
last_parser_ = rendered->parser;
have_chat_params_ = true;
// gh#105: snapshot this TOOLED render for the engine's later re-parse.
// A toolless interleave (validator critique) clears have_chat_params_
// but NOT this snapshot, so parse_response still decodes the main call.
parse_chat_format_ = last_chat_format_;
parse_generation_prompt_ = last_generation_prompt_;
parse_parser_ = last_parser_;
parse_params_valid_ = true;
// gh#134 (v2.10.4): keep the tool-call grammar the render derived from
// the staged schemas. Discarding it is why tools-staged tiers decode
// unconstrained today.
tool_grammar_ = tool_grammar_for(*rendered, require_tool_call_);
tool_grammar_lazy_ = rendered->grammar_lazy;
prompt = rendered->prompt;
logger->info("render_with_tools: format={}, {} tool(s), captured "
"parser ({} bytes), grammar ({} bytes, lazy={})",
last_chat_format_, tools.size(), last_parser_.size(),
tool_grammar_.size(), tool_grammar_lazy_);
// gh#138: the silent failure a consumer cannot see. A tier asking for
// tool_choice=REQUIRED whose render yields no grammar is unconstrained
// — the flag is set, tools are staged, and nothing enforces the call.
// Loud, because the alternative is what gh#138 actually experienced:
// prose-only turns with no diagnostic anywhere.
if (require_tool_call_ && tool_grammar_.empty()) {
logger->error(
"require_tool_call is set for this tier but the chat template "
"derived NO tool-call grammar from {} staged tool(s) "
"(format={}). The turn will decode unconstrained and may end "
"in prose with no tool call. This template may not support "
"tool_choice=REQUIRED.",
tools.size(), last_chat_format_);
}
} else {
// gh#137: this fallback CANNOT honor enable_thinking — the low-level
// llama_chat_apply_template API has no slot for it. Saying so is the
// difference between a diagnosable config problem and a mystery: a
// tier that set enable_thinking:false still reasons here, and on
// gemma4 the whole generation can be one unterminated <|channel>
// block, which the reasoning strip then correctly reduces to zero
// characters. The consumer sees "0 chars, 0 tool calls" and no cause.
if (!params.enable_thinking) {
logger->warn(
"Falling back to the low-level chat template, which cannot "
"honor enable_thinking:false — this tier WILL still emit "
"reasoning, and a generation that is entirely reasoning is "
"stripped to empty content. The jinja render was unavailable "
"for this turn (no tools staged, or the template could not be "
"applied).");
}
prompt = apply_chat_template_lowlevel(messages);
}
return prompt;
}Activity · 24 steps
Requirements
run_prefill_cached
bool entropic::LlamaCppBackend::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.
src/inference/llama_cpp_backend.cpp:2921
Called by do_generate_streaming_text_only, do_generate_text_only
Calls elapsed_ms, invalidate_resident_kv, now, prefill_dispatch, refuse_over_context, run_prefill, set_resident, try_warm_reuse
Source · 64 lines
bool LlamaCppBackend::run_prefill_cached(
const std::vector<llama_token>& tokens,
const std::string& system_prompt,
const std::vector<Message>& messages,
const GenerationParams& params)
{
// gh#96 (v2.7.5): count tokens actually pushed through llama_decode during
// prefill this turn. run_prefill / decode_tokens_from accumulate into
// last_prefill_tokens_; a prompt-cache HIT restores the system prefix
// without a decode, so this counts the re-decoded post-system remainder —
// the per-turn waste that climbs today and should collapse to the appended
// delta once warm-keep reuse lands. (llama_perf n_p_eval proved unreliable
// across the state-restore boundary, so we count the decodes directly.)
last_prefill_tokens_ = 0;
last_input_tokens_ = static_cast<int>(tokens.size()); // gh#97
// v2.13.0: a prompt that cannot fit is refused HERE, before llama_decode
// is called even once. Proceeding is what produced the release-gate
// symptom: chunked decode failures every turn, a cache restore that
// could not land, and an empty-turn allowance spent on a prompt no
// retry could shrink.
if (refuse_over_context(tokens, system_prompt)) {
return false;
}
// A prefill without a context cannot succeed, and saying so is cheaper
// than dereferencing null inside llama_get_memory further down. Both
// branches below reach llama.cpp, so the check belongs here rather than
// in either one. Production never arrives un-ACTIVE (the base class
// gates generate()); this is what lets the CPU unit tier drive the
// decode path at all.
if (ctx_ == nullptr) {
logger->error("Prefill requested with no context (not ACTIVE)");
return false;
}
auto t_pre = entropic::log::now();
bool ok;
if (is_hybrid_ || is_recurrent_) {
// gh#97 (v2.7.6): hybrid/recurrent (SSM) memory rejects the partial
// seq_rm warm-keep needs (state can't be partially erased at the tail),
// and the prompt-cache restore lands non-contiguous cells — both desync
// KV positions (pos_max inflates → eventual decode slot-failure with the
// cache mostly empty). Plain full prefill (clear + contiguous decode) is
// the only correct path for these archs at this llama.cpp pin. Mirrors
// the speculative-decoding guard. Forfeits the gh#96 reuse for them.
ok = run_prefill(tokens);
invalidate_resident_kv();
} else {
// gh#96 warm-keep: reuse the resident KV prefix + decode only the delta;
// fall back to a cold prefill (clear + system-prefix cache) when reuse
// is off, the prefix diverged, or the KV was mutated out-of-band.
ok = try_warm_reuse(tokens);
if (!ok) {
ok = prefill_dispatch(tokens, system_prompt, messages, params);
if (ok) {
residency_.set_resident(active_slot_, tokens);
} else {
invalidate_resident_kv();
}
}
}
last_prefill_ms_ = entropic::log::elapsed_ms(t_pre, entropic::log::now());
logger->info("Prefill (gh#96): {} tokens / {:.1f} ms decoded this turn",
last_prefill_tokens_, last_prefill_ms_);
return ok;
}Activity · 23 steps
Requirements
run_sampling_loop
GenerationResult entropic::LlamaCppBackend::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.
src/inference/llama_cpp_backend.cpp:3347
Called by generate_multimodal
Calls create_sampler, effective_stop, finalize_generation, finalize_result, on_token, step_token
Source · 39 lines
GenerationResult LlamaCppBackend::run_sampling_loop(
const GenerationParams& params,
std::function<void(std::string_view token)> on_token,
std::atomic<bool>* cancel,
const std::chrono::steady_clock::time_point& t0)
{
GenerationResult result;
// v2.3.10: Sampler seam.
auto sampler = create_sampler(params);
if (!sampler) {
result.error_code = ENTROPIC_ERROR_GENERATE_FAILED;
result.error_message = "Sampler factory not initialized";
result.finish_reason = "error";
finalize_result(result, t0);
return result;
}
std::string generated;
int n_generated = 0;
const auto stop = effective_stop(params); // gh#105: per-call sequential marker
while (n_generated < params.max_tokens) {
if (cancel != nullptr
&& cancel->load(std::memory_order_acquire)) {
result.finish_reason = "cancelled";
result.error_code = ENTROPIC_ERROR_CANCELLED;
break;
}
auto status = step_token(
*sampler, generated, on_token, stop);
if (status == "continue") { ++n_generated; continue; }
result.finish_reason = (status == "error") ? "error" : "stop";
if (status == "error") {
result.error_code = ENTROPIC_ERROR_GENERATE_FAILED;
}
break;
}
finalize_generation(result, generated, n_generated, params, t0,
last_prefill_tokens_);
return result;
}Activity · 26 steps
Requirements
set_active_tools
void entropic::LlamaCppBackend::set_active_tools(const std::string &tools_json)
Stage tool definitions for the next common_chat render (gh#87).
src/inference/llama_cpp_backend.cpp:1629
Called by SCENARIO, TEST_CASE, TEST_CASE, TEST_CASE, TEST_CASE, TEST_CASE, TEST_CASE, verify_family_common_chat
Calls none
Source · 5 lines
void LlamaCppBackend::set_active_tools(const std::string& tools_json) {
active_tools_json_ = tools_json;
logger->info("Active tools staged for common_chat render: {} bytes",
tools_json.size());
}Activity · 2 steps
Requirements
teardown_mtp_draft
void entropic::LlamaCppBackend::teardown_mtp_draft()
Free the MTP head context + model (gh#106 lifecycle).
src/inference/llama_cpp_backend.cpp:838
Source · 11 lines
void LlamaCppBackend::teardown_mtp_draft() {
if (mtp_draft_ctx_ != nullptr) {
llama_free(mtp_draft_ctx_);
mtp_draft_ctx_ = nullptr;
}
if (mtp_draft_model_ != nullptr) {
llama_model_free(mtp_draft_model_);
mtp_draft_model_ = nullptr;
}
mtp_head_path_.clear();
}Activity · 7 steps
Requirements
to_common_chat
static std::vector< common_chat_msg > entropic::to_common_chat(const std::vector< Message > &messages)
Convert engine messages to common_chat_msg (gh#86, v2.6.1).
src/inference/llama_cpp_backend.cpp:1411
Source · 17 lines
static std::vector<common_chat_msg> to_common_chat(
const std::vector<Message>& messages) {
std::vector<common_chat_msg> out;
out.reserve(messages.size());
size_t calls = 0;
size_t responses = 0;
for (const auto& msg : messages) {
out.push_back(to_common_chat_msg(msg));
calls += out.back().tool_calls.size();
responses += out.back().role == "tool" ? 1 : 0;
}
if (calls + responses > 0) {
logger->info("[chat] history: {} tool call(s), {} tool response(s) "
"rendered as native turns", calls, responses);
}
return out;
}Activity · 11 steps
Requirements
to_common_sampling
common_params_sampling entropic::anonymous_namespace{llama_cpp_backend.cpp}::to_common_sampling(const GenerationParams ¶ms, const std::string &tool_grammar, bool tool_grammar_lazy, const std::string &generation_prompt)Map entropic GenerationParams → common_params_sampling.
src/inference/llama_cpp_backend.cpp:3885
Called by mtp_init_decoder, spec_init_sampler_and_decoder
Calls apply_grammar_source
Source · 54 lines
common_params_sampling to_common_sampling(
const GenerationParams& params,
const std::string& tool_grammar,
bool tool_grammar_lazy,
const std::string& generation_prompt) {
common_params_sampling cps;
cps.temp = params.temperature;
apply_grammar_source(cps, params, tool_grammar, tool_grammar_lazy,
generation_prompt);
cps.top_k = params.top_k;
cps.top_p = params.top_p;
cps.penalty_repeat = params.repeat_penalty;
// gh#23 MVP items 2 + 3 (v2.3.14 + v2.3.15): wire presence +
// frequency penalty into common-sampling. Counterparts of the
// 3rd + 4th args to `llama_sampler_init_penalties` in the plain
// decode path. Default 0.0f on both preserves bit-for-bit
// speculative output.
cps.penalty_freq = params.frequency_penalty;
cps.penalty_present = params.presence_penalty;
// gh#23 MVP item 4 (v2.3.16): forward logit_bias to common-sampling.
// Empty (default) leaves the speculative chain bit-for-bit
// identical to pre-v2.3.16.
for (auto& [tok, val] : params.logit_bias) {
cps.logit_bias.push_back({tok, val});
}
if (params.seed >= 0) {
cps.seed = static_cast<uint32_t>(params.seed);
}
cps.no_perf = true;
// Mirror entropic's standard sampler chain ordering so the
// speculative path produces output bit-identical to plain decode
// (the v2.1.11 correctness contract). Entropic's `create_sampler`
// builds: penalties → top_k → top_p → min_p → temperature → dist,
// AND SKIPS the temperature sampler when temp == 0 (greedy mode).
// common_sampler appends an extended-temperature sampler that
// differs subtly from "no temp at all" — we omit it for temp=0
// to match entropic exactly. min_p (v2.3.10, gh#23) appended only
// when caller opted in (params.min_p > 0); 0.0 preserves the
// pre-v2.3.10 chain shape bit-for-bit. Other extended filters
// (top_n_sigma, dry, xtc, typical_p) remain stripped.
cps.samplers = {COMMON_SAMPLER_TYPE_PENALTIES,
COMMON_SAMPLER_TYPE_TOP_K,
COMMON_SAMPLER_TYPE_TOP_P};
if (params.min_p > 0.0f) {
cps.samplers.push_back(COMMON_SAMPLER_TYPE_MIN_P);
}
if (params.temperature > 0.0f) {
cps.samplers.push_back(COMMON_SAMPLER_TYPE_TEMPERATURE);
}
cps.min_p = params.min_p;
cps.dry_multiplier = 0.0f;
cps.top_n_sigma = -1.0f;
return cps;
}Activity · 22 steps
Requirements
tool_call_close_marker
std::string entropic::LlamaCppBackend::tool_call_close_marker() const override
Tool-call close marker for the captured chat format (gh#103).
src/inference/llama_cpp_backend.cpp:1792
Source · 7 lines
std::string LlamaCppBackend::tool_call_close_marker() const {
// last_chat_format_ is stored as int (the captured common_chat_format).
return have_chat_params_
? close_marker_for_format(
static_cast<common_chat_format>(last_chat_format_))
: "";
}Activity · 1 steps
Requirements
tool_grammar_for
static std::string entropic::tool_grammar_for(const common_chat_params &rendered, bool require_tool_call)
The render's tool-call grammar, with the Gemma 4 REQUIRED root fixed.
src/inference/llama_cpp_backend.cpp:1651
Called by render_with_tools
Calls gbnf_root_line, gemma4_required_root_fixed_shape, patch_gemma4_required_root
Source · 22 lines
static std::string tool_grammar_for(const common_chat_params& rendered,
bool require_tool_call) {
std::string grammar = rendered.grammar;
const bool gemma4_required = require_tool_call && !grammar.empty()
&& rendered.format == COMMON_CHAT_FORMAT_PEG_GEMMA4;
if (gemma4_required) {
std::string patched = entropic::patch_gemma4_required_root(grammar);
if (patched != grammar) {
logger->info("Gemma 4 REQUIRED tool grammar: root rewritten to "
"'{}' (mirrors llama.cpp f072b10371)",
entropic::gemma4_required_root_fixed_shape());
grammar = std::move(patched);
} else {
logger->warn("Gemma 4 REQUIRED tool grammar: root is not the "
"expected pre-f072b10371 shape, so it is left "
"unpatched (a newer llama.cpp pin may already carry "
"f072b10371). Root line found: '{}'",
entropic::gbnf_root_line(grammar));
}
}
return grammar;
}Activity · 10 steps
Requirements
~LlamaCppBackend
entropic::LlamaCppBackend::~LlamaCppBackend() override
Free llama.cpp + mtmd resources on destruction.
src/inference/llama_cpp_backend.cpp:1038
The index is older than this file: the lines it records no longer hold this function. Refresh the index to bundle its body.