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 &params, 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

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
lines 3806–3806◇ if (grammar_sources_collide(params.grammar, tool_grammar))lines 3807–3812logger->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.");lines 3814–3814const auto source = resolve_grammar_source(params.grammar, tool_grammar);lines 3818–3818◇ if (is_request_grammar(source))lines 3819–3819cps.grammar = common_grammar(COMMON_GRAMMAR_TYPE_USER, params.grammar);lines 3820–3820elselines 3820–3820◇ if (source == GrammarSource::tool_call)lines 3825–3826cps.grammar = common_grammar(COMMON_GRAMMAR_TYPE_TOOL_CALLS, tool_grammar);lines 3827–3827cps.grammar_lazy = tool_grammar_lazy;lines 3835–3835cps.generation_prompt = generation_prompt;lines 3843–3846logger->info( "Tool-call grammar applied: {} bytes, lazy={}, prefill={} bytes", tool_grammar.size(), tool_grammar_lazy, generation_prompt.size());lines 3847–3847elselines 3847–3847◇ if (!tool_grammar.empty())lines 3851–3855logger->warn( "Tool-call grammar ({} bytes) NOT applied — an explicit request " "grammar takes precedence. Tool calls are not structurally " "enforced this turn.", tool_grammar.size());

Requirements

REQ-INFER-008

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

Show on the map →

Called by do_load_active, load_gpu_model

Calls mmap_load_mode, parse_split_mode

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
lines 381–381llama_model_params m = llama_model_default_params();lines 382–382m.n_gpu_layers = cfg.gpu_layers;lines 383–383m.load_mode = mmap_load_mode(cfg.use_mlock);lines 384–384m.split_mode = parse_split_mode(cfg.split_mode);lines 388–388m.main_gpu = cfg.main_gpu;lines 391–391m.tensor_buft_overrides = moe.data();lines 392–392return m;

Requirements

REQ-INFER-027

do_generate_streaming_text_only

GenerationResult entropic::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)

Text-only streaming generation (extracted from streaming).

src/inference/llama_cpp_backend.cpp:3698

Show on the map →

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 moretokenize

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
lines 3704–3704auto t0 = entropic::log::now();lines 3705–3705auto prompt = render_prompt(messages, params);lines 3706–3706auto tokens = tokenize(prompt, true);lines 3707–3707auto sys = extract_system_prompt(messages);lines 3708–3709logger->info("Stream: {} input tokens, max_tokens={}", tokens.size(), params.max_tokens);lines 3710–3710log_sampler_config(params);lines 3713–3713auto sampler = create_sampler(params);lines 3714–3714◇ if (!sampler)lines 3714–3714return sampler_init_error(t0);lines 3715–3715◇ if (!run_prefill_cached(tokens, sys, messages, params))lines 3716–3716return prefill_error();lines 3718–3718GenerationResult result;lines 3719–3719std::string generated;lines 3720–3720int n_generated = 0;lines 3721–3721const auto stop = effective_stop(params);lines 3722–3722◇ while (n_generated < params.max_tokens)lines 3723–3723◇ if (cancel.load(std::memory_order_acquire))lines 3724–3724result.finish_reason = "cancelled";lines 3725–3725result.error_code = ENTROPIC_ERROR_CANCELLED;lines 3726–3726break;lines 3728–3729auto status = step_token( *sampler, generated, on_token, stop);lines 3730–3730◇ if (status == "continue")lines 3730–3730++n_generated;lines 3731–3731elselines 3732–3733result.finish_reason = (status == "error") ? "error" : "stop";lines 3734–3734◇ if (status == "error")lines 3735–3735result.error_code = ENTROPIC_ERROR_GENERATE_FAILED;lines 3737–3737break;lines 3740–3741finalize_generation(result, generated, n_generated, params, t0, last_prefill_tokens_);lines 3742–3742return result;

Requirements

REQ-INFER-005

do_generate_text_only

GenerationResult entropic::LlamaCppBackend::do_generate_text_only(const std::vector< Message > &messages, const GenerationParams &params)

Text-only batch generation (extracted from do_generate).

src/inference/llama_cpp_backend.cpp:3516

Show on the map →

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
lines 3520–3520auto t0 = entropic::log::now();lines 3521–3521std::string prompt = render_prompt(messages, params);lines 3522–3522auto tokens = tokenize(prompt, true);lines 3523–3523std::string sys = extract_system_prompt(messages);lines 3525–3526logger->info("Generate: {} input tokens, max_tokens={}", tokens.size(), params.max_tokens);lines 3527–3527log_sampler_config(params);lines 3530–3530auto sampler = create_sampler(params);lines 3531–3531◇ if (!sampler)lines 3531–3531return sampler_init_error(t0);lines 3533–3533◇ if (!run_prefill_cached(tokens, sys, messages, params))lines 3534–3534return prefill_error();lines 3537–3537GenerationResult result;lines 3538–3538std::string generated;lines 3539–3539int n_generated = 0;lines 3540–3540std::function<void(std::string_view)> no_cb = nullptr;lines 3541–3541const auto stop = effective_stop(params);lines 3543–3543◇ while (n_generated < params.max_tokens)lines 3544–3545auto status = step_token( *sampler, generated, no_cb, stop);lines 3546–3546◇ if (status == "continue")lines 3546–3546++n_generated;lines 3547–3547elselines 3548–3549result.finish_reason = (status == "error") ? "error" : "stop";lines 3550–3550◇ if (status == "error")lines 3551–3551result.error_code = ENTROPIC_ERROR_GENERATE_FAILED;lines 3553–3553break;lines 3557–3558finalize_generation(result, generated, n_generated, params, t0, last_prefill_tokens_);lines 3559–3559return result;
GenerationResult entropic::LlamaCppBackend::do_generate_text_only(const std::vector< Message > &messages, const GenerationParams &params, std::atomic< bool > &cancel)

Text-only batch generation with per-token cancel poll.

src/inference/llama_cpp_backend.cpp:3607

Show on the map →

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
lines 3612–3612auto t0 = entropic::log::now();lines 3613–3613std::string prompt = render_prompt(messages, params);lines 3614–3614auto tokens = tokenize(prompt, true);lines 3615–3615std::string sys = extract_system_prompt(messages);lines 3617–3618logger->info("Generate (cancellable): {} input tokens, max_tokens={}", tokens.size(), params.max_tokens);lines 3619–3619log_sampler_config(params);lines 3621–3621auto sampler = create_sampler(params);lines 3622–3622◇ if (!sampler)lines 3622–3622return sampler_init_error(t0);lines 3624–3624◇ if (!run_prefill_cached(tokens, sys, messages, params))lines 3625–3625return prefill_error();lines 3628–3628GenerationResult result;lines 3629–3629std::string generated;lines 3630–3630int n_generated = 0;lines 3631–3631std::function<void(std::string_view)> no_cb = nullptr;lines 3633–3633const auto stop = effective_stop(params);lines 3634–3634◇ while (n_generated < params.max_tokens)lines 3635–3635◇ if (cancel.load(std::memory_order_acquire))lines 3636–3636result.finish_reason = "cancelled";lines 3637–3637result.error_code = ENTROPIC_ERROR_CANCELLED;lines 3638–3638break;lines 3640–3641auto status = step_token( *sampler, generated, no_cb, stop);lines 3642–3642◇ if (status == "continue")lines 3642–3642++n_generated;lines 3643–3643elselines 3644–3645result.finish_reason = (status == "error") ? "error" : "stop";lines 3646–3646◇ if (status == "error")lines 3647–3647result.error_code = ENTROPIC_ERROR_GENERATE_FAILED;lines 3649–3649break;lines 3653–3654finalize_generation(result, generated, n_generated, params, t0, last_prefill_tokens_);lines 3655–3655return result;

Requirements

REQ-INFER-005

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

Show on the map →

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
lines 616–617const ExpertOffloadOverrides moe(config.cpu_moe_layers, ggml_backend_cpu_buffer_type());lines 618–618llama_model_params mparams = build_load_mparams(config, moe);lines 620–620model_ = load_tier_model(config.path.c_str(), mparams);lines 621–621◇ if (model_ == nullptr)lines 624–628last_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";lines 629–629return false;lines 632–632bind_model_handles();lines 633–633◇ if (!expert_offload_admits(config))lines 633–633return false;lines 634–637logger->info("Model loaded into target residency: gpu_layers={}, " "{} tokens in vocab, recurrent={}", config.gpu_layers, llama_vocab_n_tokens(vocab_), is_recurrent_);lines 638–638return finish_activation();

Requirements

REQ-INFER-002 REQ-INFER-027

do_supports

bool entropic::LlamaCppBackend::do_supports(BackendCapability cap) const override

Declare llama.cpp backend capabilities.

src/inference/llama_cpp_backend.cpp:5267

Show on the map →

Called by none

Calls config, is_recurrent

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
lines 5268–5268int idx = static_cast<int>(cap);lines 5269–5269int count = static_cast<int>(BackendCapability::_COUNT);lines 5270–5270◇ if (idx < 0 || idx >= count)lines 5271–5271return false;lines 5277–5281static constexpr bool always[] = { false, false, true, true, true, true, false, true, true, false, false, true, false, // AUDIO — dynamic only (mtmd_support_audio) };lines 5284–5284bool result = always[idx];lines 5285–5285◇ if (!result)lines 5286–5294result = (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());lines 5296–5296return result;

Requirements

REQ-TYPE-004

do_unload

void entropic::LlamaCppBackend::do_unload() override

Full unload — free all resources, clear prompt cache.

src/inference/llama_cpp_backend.cpp:1094

Show on the map →

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
lines 1096–1096std::lock_guard<std::mutex> lk(mtp_mutex_);lines 1106–1106parse_params_valid_ = false;lines 1107–1107parse_chat_format_ = 0;lines 1108–1108parse_generation_prompt_.clear();lines 1109–1109parse_parser_.clear();lines 1112–1112tool_grammar_.clear();lines 1113–1113tool_grammar_lazy_ = false;lines 1114–1114◇ if (prompt_cache_)lines 1115–1115prompt_cache_->clear();lines 1118–1118teardown_mtp_draft();lines 1123–1123sampler_factory_.reset();lines 1126–1126tokenizer_.reset();lines 1128–1128◇ if (mtmd_ctx_ != nullptr)lines 1129–1129mtmd_free(mtmd_ctx_);lines 1130–1130mtmd_ctx_ = nullptr;lines 1131–1131has_vision_ = false;lines 1133–1133◇ if (ctx_)lines 1134–1134llama_free(ctx_);lines 1135–1135ctx_ = nullptr;lines 1137–1137invalidate_all_resident_kv();lines 1138–1138◇ if (model_)lines 1139–1139llama_model_free(model_);lines 1140–1140model_ = nullptr;lines 1142–1142vocab_ = nullptr;

Requirements

REQ-INFER-002

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

Show on the map →

Called by mtp_guard, setup_mtp_draft

Calls none

Source · 3 lines
static int effective_n_draft(int n_max) {
    return (n_max > 0) ? n_max : 16;
}
Activity · 1 steps
lines 864–864return (n_max > 0) ? n_max : 16;

Requirements

REQ-INFER-015

effective_stop

std::vector< std::string > entropic::LlamaCppBackend::effective_stop(const GenerationParams &params) const

params.stop + the sequential tool-call close marker, if applicable.

src/inference/llama_cpp_backend.cpp:1818

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
lines 1820–1820GenerationParams p = params;lines 1821–1821const std::size_t before = p.stop.size();lines 1822–1822append_sequential_stop(p, tool_call_close_marker());lines 1823–1823◇ if (p.stop.size() > before)lines 1824–1825logger->info("Sequential tier: tool-call close marker injected " "post-render (gh#105) — hard-stop at first tool call");lines 1827–1827return p.stop;

Requirements

REQ-INFER-013

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

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
lines 663–663const int n_layer = llama_model_n_layer(model_);lines 664–665const std::string why = expert_offload_load_refusal( config.cpu_moe_layers, n_layer, model_expert_count(model_));lines 666–666◇ if (why.empty())lines 667–667◇ if (config.cpu_moe_layers > 0)lines 674–679logger->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);lines 681–681return true;lines 684–684last_error_ = "cpu_moe_layers refused: " + why;lines 685–685logger->error("{}", last_error_);lines 686–686tokenizer_.reset();lines 687–687llama_model_free(model_);lines 688–688model_ = nullptr;lines 689–689vocab_ = nullptr;lines 690–690return false;

Requirements

REQ-INFER-027

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
lines 3079–3079const int slot = residency_.forget_session(session_key);lines 3080–3080◇ if (slot == kNoSessionSlot)lines 3080–3080return;lines 3081–3081◇ if (ctx_ != nullptr)lines 3082–3083llama_memory_seq_rm(llama_get_memory(ctx_), static_cast<llama_seq_id>(slot), -1, -1);lines 3085–3086logger->info("Session '{}' KV dropped from slot {} (context restored)", session_key, slot);

Requirements

REQ-LOOP-010

generate_after_prefill

GenerationResult entropic::LlamaCppBackend::generate_after_prefill(Sampler &sampler, const GenerationParams &params, 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

Show on the map →

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
lines 2215–2215GenerationResult result;lines 2216–2216std::string generated;lines 2217–2217int n_generated = 0;lines 2218–2218const auto stop = effective_stop(params);lines 2220–2220◇ while (n_generated < params.max_tokens)lines 2221–2221bool cancelled = cancel && cancel->load(std::memory_order_acquire);lines 2222–2222◇ if (cancelled)lines 2223–2223result.finish_reason = "cancelled";lines 2224–2224result.error_code = ENTROPIC_ERROR_CANCELLED;lines 2225–2225break;lines 2228–2228auto status = step_token(sampler, generated, on_token, stop);lines 2229–2229◇ if (status == "continue")lines 2230–2230++n_generated;lines 2231–2231elselines 2232–2232result.finish_reason = (status == "error") ? "error" : "stop";lines 2233–2233◇ if (status == "error")lines 2234–2234result.error_code = ENTROPIC_ERROR_GENERATE_FAILED;lines 2236–2236break;lines 2240–2240mark_length_finish(result, n_generated, params.max_tokens);lines 2259–2259result.content = entropic::mcp::sanitize_utf8(generated);lines 2260–2260result.token_count = n_generated;lines 2261–2261return result;

Requirements

REQ-INFER-005

generate_mtp

GenerationResult entropic::LlamaCppBackend::generate_mtp(const std::vector< Message > &messages, const GenerationParams &params, 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

Show on the map →

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 morespec_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
lines 5175–5175auto t0 = entropic::log::now();lines 5176–5176std::lock_guard<std::mutex> lk(mtp_mutex_);lines 5177–5177GenerationResult result = mtp_guard(params, on_token, head_path, n_max);lines 5178–5178◇ if (result.error_code != ENTROPIC_OK)lines 5179–5179return result;lines 5181–5181bind_session_slot(params);lines 5182–5182auto tokens = tokenize(render_prompt(messages, params), true);lines 5183–5183◇ if (tokens.size() < 2)lines 5184–5185return spec_error(ENTROPIC_ERROR_GENERATE_FAILED, "MTP prompt must have at least 2 tokens");lines 5188–5188const int reuse_cut = mtp_reuse_cut(tokens);lines 5189–5189◇ if (reuse_cut == 0)lines 5190–5190invalidate_all_resident_kv();lines 5192–5193logger->info("MTP: {} input tokens, reusing {}, max_tokens={}, n_max={}", tokens.size(), reuse_cut, params.max_tokens, mtp_n_max_);lines 5194–5199auto 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);lines 5202–5202last_prefill_tokens_ = mtp_result.prefill_tokens;lines 5203–5203◇ if (mtp_result.error_code == ENTROPIC_OK)lines 5207–5207residency_.set_resident(active_slot_, tokens);lines 5208–5208elselines 5209–5209invalidate_resident_kv();lines 5211–5211return mtp_result;

Requirements

REQ-INFER-005 REQ-INFER-015

generate_multimodal

GenerationResult entropic::LlamaCppBackend::generate_multimodal(const std::vector< Message > &messages, const GenerationParams &params, 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

Show on the map →

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
lines 3408–3408auto t0 = entropic::log::now();lines 3409–3409invalidate_all_resident_kv();lines 3410–3410std::vector<::mtmd_bitmap*> bitmaps;lines 3411–3412auto marked = substitute_image_markers( messages, mtmd_ctx_, bitmaps);lines 3413–3413◇ if (marked.empty())lines 3414–3414◇ for (auto* b : bitmaps)lines 3414–3414mtmd_bitmap_free(b);lines 3415–3415GenerationResult err;lines 3416–3416err.error_code = ENTROPIC_ERROR_IMAGE_LOAD_FAILED;lines 3417–3418err.error_message = "mtmd_helper_bitmap_init_from_file failed";lines 3419–3419return err;lines 3421–3421auto prompt = render_prompt(marked, params);lines 3422–3423logger->info("Multimodal generate: {} images, prompt={} chars, max_tokens={}", bitmaps.size(), prompt.size(), params.max_tokens);lines 3424–3424log_rendered_markers(prompt, bitmaps.size());lines 3425–3425std::string prefill_err;lines 3426–3426auto rc = mtmd_prefill(prompt, bitmaps, prefill_err);lines 3427–3427◇ for (auto* b : bitmaps)lines 3427–3427mtmd_bitmap_free(b);lines 3428–3428◇ if (rc != ENTROPIC_OK)lines 3429–3429GenerationResult err;lines 3430–3430err.error_code = rc;lines 3431–3431err.error_message = std::move(prefill_err);lines 3432–3432return err;lines 3434–3434return run_sampling_loop(params, on_token, cancel, t0);

Requirements

REQ-INFER-025

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

Show on the map →

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
lines 716–717const ExpertOffloadOverrides moe(config().cpu_moe_layers, ggml_backend_cpu_buffer_type());lines 718–718llama_model_params mparams = build_load_mparams(config(), moe);lines 720–720◇ if (!config().tensor_split.empty())lines 722–722logger->warn("tensor_split not yet implemented, ignoring");lines 729–729tokenizer_.reset();lines 730–730◇ if (model_ != nullptr)lines 731–731llama_model_free(model_);lines 732–732model_ = nullptr;lines 733–733vocab_ = nullptr;lines 736–736model_ = load_tier_model(config().path.c_str(), mparams);lines 737–737◇ if (model_ == nullptr)lines 743–747last_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";lines 748–748return false;lines 751–751bind_model_handles();lines 752–752return expert_offload_admits(config());

Requirements

REQ-INFER-027

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
lines 1445–1445std::vector<common_chat_tool> out;lines 1446–1446◇ if (tools_json.empty())lines 1446–1446return out;lines 1447–1447auto arr = nlohmann::json::parse(tools_json, nullptr, false);lines 1448–1448◇ if (!arr.is_array())lines 1448–1448return out;lines 1449–1449◇ for (const auto& t : arr)lines 1450–1450common_chat_tool ct;lines 1451–1451ct.name = t.value("name", "");lines 1452–1452ct.description = t.value("description", "");lines 1453–1453◇ if (t.contains("inputSchema"))lines 1454–1454ct.parameters = t["inputSchema"].dump();lines 1456–1456◇ if (!ct.name.empty())lines 1456–1456out.push_back(std::move(ct));lines 1458–1458return out;

Requirements

REQ-INFER-009

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
lines 410–410char arch[64] = {0};lines 411–412◇ if (llama_model_meta_val_str(model, "general.architecture", arch, sizeof(arch)) < 0)lines 413–413return 0;lines 415–415const std::string key = std::string(arch) + ".expert_count";lines 416–416char value[32] = {0};lines 417–418◇ if (llama_model_meta_val_str(model, key.c_str(), value, sizeof(value)) < 0)lines 419–419return 0;lines 421–421return std::atoi(value);

Requirements

REQ-INFER-027

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
lines 3294–3294++kv_full_clear_count_;lines 3295–3295llama_memory_clear(llama_get_memory(ctx_), true);lines 3301–3304::mtmd_input_text mt{.text = prompt.c_str(), .text_len = prompt.size(), .add_special = true, .parse_special = true};lines 3305–3305auto* chunks = mtmd_input_chunks_init();lines 3306–3307std::vector<const ::mtmd_bitmap*> bm_cptrs( bitmaps.begin(), bitmaps.end());lines 3308–3309int32_t tok_rc = mtmd_tokenize( mtmd_ctx_, chunks, &mt, bm_cptrs.data(), bm_cptrs.size());lines 3310–3310◇ if (tok_rc != 0)lines 3311–3311mtmd_input_chunks_free(chunks);lines 3312–3313err_msg = "mtmd_tokenize failed (rc=" + std::to_string(tok_rc) + ")";lines 3314–3314return ENTROPIC_ERROR_GENERATE_FAILED;lines 3316–3316llama_pos new_n_past = 0;lines 3317–3320int32_t eval_rc = mtmd_helper_eval_chunks( mtmd_ctx_, ctx_, chunks, 0, 0, static_cast<int32_t>(config().n_batch), true, &new_n_past);lines 3321–3321mtmd_input_chunks_free(chunks);lines 3322–3322◇ if (eval_rc != 0)lines 3323–3324err_msg = "mtmd_helper_eval_chunks failed (rc=" + std::to_string(eval_rc) + ")";lines 3325–3325return ENTROPIC_ERROR_GENERATE_FAILED;lines 3327–3327logger->info("Multimodal prefill complete: n_past={}", new_n_past);lines 3328–3328return ENTROPIC_OK;

Requirements

REQ-INFER-025

mtp_guard

GenerationResult entropic::LlamaCppBackend::mtp_guard(const GenerationParams &params, 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

Show on the map →

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
lines 5082–5082GenerationResult r;lines 5083–5085std::string reason = mtp_unsupported_reason( params.temperature, !params.grammar.empty(), static_cast<bool>(on_token));lines 5086–5086◇ if (!is_active())lines 5087–5088r = spec_error(ENTROPIC_ERROR_INVALID_STATE, "MTP requires an ACTIVE target");lines 5089–5089elselines 5089–5089◇ if (!reason.empty())lines 5090–5090r = spec_error(ENTROPIC_ERROR_SPECULATIVE_INCOMPATIBLE_CONFIG, reason);lines 5091–5091elselines 5091–5091◇ if (1 + effective_n_draft(n_max) > llama_n_batch(ctx_))lines 5104–5108r = 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");lines 5109–5109elselines 5109–5109◇ if (!setup_mtp_draft(head_path, n_max))lines 5110–5110r = spec_error(ENTROPIC_ERROR_LOAD_FAILED, last_error_);lines 5112–5112return r;

Requirements

REQ-INFER-015

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

Show on the map →

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
lines 1937–1937CommonChatResult result;lines 1941–1941◇ if (!parse_params_valid_)lines 1942–1942result.content = raw;lines 1943–1943return result;lines 1945–1945common_chat_parser_params pp;lines 1946–1946pp.format = static_cast<common_chat_format>(parse_chat_format_);lines 1947–1947pp.generation_prompt = parse_generation_prompt_;lines 1948–1948pp.parser.load(parse_parser_);lines 1949–1967try { 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; }lines 1968–1968return result;

Requirements

REQ-INFER-009

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
lines 2888–2888GenerationResult r;lines 2889–2889r.finish_reason = "error";lines 2890–2890◇ if (!prefill_refusal_.empty())lines 2891–2891r.error_code = ENTROPIC_ERROR_EVAL_CONTEXT_FULL;lines 2892–2892r.error_message = prefill_refusal_;lines 2893–2893return r;lines 2895–2895r.error_code = ENTROPIC_ERROR_GENERATE_FAILED;lines 2896–2896r.error_message = "Prefill decode failed";lines 2897–2897return r;

Requirements

REQ-INFER-026

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

Show on the map →

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
lines 2862–2862ContextFit fit;lines 2863–2863fit.prompt_tokens = static_cast<int>(tokens.size());lines 2864–2864fit.context_length = config().context_length;lines 2865–2865◇ if (!context_fit_overflows(fit))lines 2866–2866prefill_refusal_.clear();lines 2867–2867return false;lines 2869–2869fit.tool_bytes = active_tools_json_.size();lines 2870–2870fit.tool_count = staged_tool_count(active_tools_json_);lines 2871–2872fit.tool_tokens = static_cast<int>(tokenize(active_tools_json_, false).size());lines 2873–2874fit.system_tokens = static_cast<int>(tokenize(system_prompt, false).size());lines 2875–2875prefill_refusal_ = context_overflow_message(fit);lines 2876–2876logger->error("{}", prefill_refusal_);lines 2877–2877return true;

Requirements

REQ-INFER-026

render_common_chat

static std::optional< common_chat_params > entropic::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)

Shared common_chat render core for both template paths (gh#87).

src/inference/llama_cpp_backend.cpp:1513

Show on the map →

Called by apply_chat_template, render_with_tools

Calls to_common_chat

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
lines 1519–1519◇ if (model == nullptr)lines 1519–1519return std::nullopt;lines 1520–1520auto tmpls = common_chat_templates_init(model, "");lines 1521–1521std::optional<common_chat_params> out;lines 1522–1522◇ if (tmpls)lines 1523–1523common_chat_templates_inputs inputs;lines 1524–1524inputs.messages = to_common_chat(messages);lines 1525–1525inputs.add_generation_prompt = true;lines 1526–1526inputs.use_jinja = true;lines 1527–1527inputs.enable_thinking = params.enable_thinking;lines 1528–1528inputs.tools = tools;lines 1529–1529◇ if (!tools.empty())lines 1534–1536inputs.tool_choice = require_tool_call ? COMMON_CHAT_TOOL_CHOICE_REQUIRED : COMMON_CHAT_TOOL_CHOICE_AUTO;lines 1538–1543try { 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()); }lines 1545–1545return out;

Requirements

REQ-INFER-009

render_prompt

std::string entropic::LlamaCppBackend::render_prompt(const std::vector< Message > &messages, const GenerationParams &params)

Generation render seam: common_chat-with-tools or legacy (gh#87).

src/inference/llama_cpp_backend.cpp:1607

Show on the map →

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
lines 1611–1611◇ if (!active_tools_json_.empty())lines 1612–1612return render_with_tools(messages, params);lines 1614–1614have_chat_params_ = false;lines 1615–1615return apply_chat_template(messages, params);

Requirements

REQ-INFER-009

render_with_tools

std::string entropic::LlamaCppBackend::render_with_tools(const std::vector< Message > &messages, const GenerationParams &params)

Render messages through common_chat WITH the active tools.

src/inference/llama_cpp_backend.cpp:1698

Show on the map →

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
lines 1702–1702have_chat_params_ = false;lines 1703–1703auto tools = mcp_tools_to_common_chat(active_tools_json_);lines 1704–1705auto rendered = render_common_chat(model_, messages, params, tools, require_tool_call_);lines 1706–1706std::string prompt;lines 1707–1707◇ if (rendered)lines 1708–1708last_chat_format_ = static_cast<int>(rendered->format);lines 1709–1709last_generation_prompt_ = rendered->generation_prompt;lines 1710–1710last_parser_ = rendered->parser;lines 1711–1711have_chat_params_ = true;lines 1715–1715parse_chat_format_ = last_chat_format_;lines 1716–1716parse_generation_prompt_ = last_generation_prompt_;lines 1717–1717parse_parser_ = last_parser_;lines 1718–1718parse_params_valid_ = true;lines 1722–1722tool_grammar_ = tool_grammar_for(*rendered, require_tool_call_);lines 1723–1723tool_grammar_lazy_ = rendered->grammar_lazy;lines 1724–1724prompt = rendered->prompt;lines 1725–1728logger->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_);lines 1734–1734◇ if (require_tool_call_ && tool_grammar_.empty())lines 1735–1741logger->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_);lines 1743–1743elselines 1751–1751◇ if (!params.enable_thinking)lines 1752–1758logger->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).");lines 1760–1760prompt = apply_chat_template_lowlevel(messages);lines 1762–1762return prompt;

Requirements

REQ-INFER-009

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 &params)

Run prefill with prompt cache integration.

src/inference/llama_cpp_backend.cpp:2921

Show on the map →

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
lines 2934–2934last_prefill_tokens_ = 0;lines 2935–2935last_input_tokens_ = static_cast<int>(tokens.size());lines 2941–2941◇ if (refuse_over_context(tokens, system_prompt))lines 2942–2942return false;lines 2950–2950◇ if (ctx_ == nullptr)lines 2951–2951logger->error("Prefill requested with no context (not ACTIVE)");lines 2952–2952return false;lines 2954–2954auto t_pre = entropic::log::now();lines 2955–2955bool ok;lines 2956–2956◇ if (is_hybrid_ || is_recurrent_)lines 2964–2964ok = run_prefill(tokens);lines 2965–2965invalidate_resident_kv();lines 2966–2966elselines 2970–2970ok = try_warm_reuse(tokens);lines 2971–2971◇ if (!ok)lines 2972–2972ok = prefill_dispatch(tokens, system_prompt, messages, params);lines 2973–2973◇ if (ok)lines 2974–2974residency_.set_resident(active_slot_, tokens);lines 2975–2975elselines 2976–2976invalidate_resident_kv();lines 2980–2980last_prefill_ms_ = entropic::log::elapsed_ms(t_pre, entropic::log::now());lines 2981–2982logger->info("Prefill (gh#96): {} tokens / {:.1f} ms decoded this turn", last_prefill_tokens_, last_prefill_ms_);lines 2983–2983return ok;

Requirements

REQ-INFER-026

run_sampling_loop

GenerationResult entropic::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)

Sample tokens until stop / max_tokens / cancel.

src/inference/llama_cpp_backend.cpp:3347

Show on the map →

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
lines 3353–3353GenerationResult result;lines 3355–3355auto sampler = create_sampler(params);lines 3356–3356◇ if (!sampler)lines 3357–3357result.error_code = ENTROPIC_ERROR_GENERATE_FAILED;lines 3358–3358result.error_message = "Sampler factory not initialized";lines 3359–3359result.finish_reason = "error";lines 3360–3360finalize_result(result, t0);lines 3361–3361return result;lines 3363–3363std::string generated;lines 3364–3364int n_generated = 0;lines 3365–3365const auto stop = effective_stop(params);lines 3366–3366◇ while (n_generated < params.max_tokens)lines 3367–3368◇ if (cancel != nullptr && cancel->load(std::memory_order_acquire))lines 3369–3369result.finish_reason = "cancelled";lines 3370–3370result.error_code = ENTROPIC_ERROR_CANCELLED;lines 3371–3371break;lines 3373–3374auto status = step_token( *sampler, generated, on_token, stop);lines 3375–3375◇ if (status == "continue")lines 3375–3375++n_generated;lines 3375–3375continue;lines 3376–3376result.finish_reason = (status == "error") ? "error" : "stop";lines 3377–3377◇ if (status == "error")lines 3378–3378result.error_code = ENTROPIC_ERROR_GENERATE_FAILED;lines 3380–3380break;lines 3382–3383finalize_generation(result, generated, n_generated, params, t0, last_prefill_tokens_);lines 3384–3384return result;

Requirements

REQ-INFER-005

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

Show on the map →

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
lines 1630–1630active_tools_json_ = tools_json;lines 1631–1632logger->info("Active tools staged for common_chat render: {} bytes", tools_json.size());

Requirements

REQ-INFER-009

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

Show on the map →

Called by build_mtp_head, do_deactivate, do_unload, setup_mtp_draft

Calls none

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
lines 839–839◇ if (mtp_draft_ctx_ != nullptr)lines 840–840llama_free(mtp_draft_ctx_);lines 841–841mtp_draft_ctx_ = nullptr;lines 843–843◇ if (mtp_draft_model_ != nullptr)lines 844–844llama_model_free(mtp_draft_model_);lines 845–845mtp_draft_model_ = nullptr;lines 847–847mtp_head_path_.clear();

Requirements

REQ-INFER-002

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

Show on the map →

Called by render_common_chat

Calls to_common_chat_msg

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
lines 1413–1413std::vector<common_chat_msg> out;lines 1414–1414out.reserve(messages.size());lines 1415–1415size_t calls = 0;lines 1416–1416size_t responses = 0;lines 1417–1417◇ for (const auto& msg : messages)lines 1418–1418out.push_back(to_common_chat_msg(msg));lines 1419–1419calls += out.back().tool_calls.size();lines 1420–1420responses += out.back().role == "tool" ? 1 : 0;lines 1422–1422◇ if (calls + responses > 0)lines 1423–1424logger->info("[chat] history: {} tool call(s), {} tool response(s) " "rendered as native turns", calls, responses);lines 1426–1426return out;

Requirements

REQ-INFER-009

to_common_sampling

common_params_sampling entropic::anonymous_namespace{llama_cpp_backend.cpp}::to_common_sampling(const GenerationParams &params, 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

Show on the map →

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
lines 3890–3890common_params_sampling cps;lines 3891–3891cps.temp = params.temperature;lines 3892–3893apply_grammar_source(cps, params, tool_grammar, tool_grammar_lazy, generation_prompt);lines 3894–3894cps.top_k = params.top_k;lines 3895–3895cps.top_p = params.top_p;lines 3896–3896cps.penalty_repeat = params.repeat_penalty;lines 3902–3902cps.penalty_freq = params.frequency_penalty;lines 3903–3903cps.penalty_present = params.presence_penalty;lines 3907–3907◇ for (auto& [tok, val] : params.logit_bias)lines 3908–3908cps.logit_bias.push_back({tok, val});lines 3910–3910◇ if (params.seed >= 0)lines 3911–3911cps.seed = static_cast<uint32_t>(params.seed);lines 3913–3913cps.no_perf = true;lines 3925–3927cps.samplers = {COMMON_SAMPLER_TYPE_PENALTIES, COMMON_SAMPLER_TYPE_TOP_K, COMMON_SAMPLER_TYPE_TOP_P};lines 3928–3928◇ if (params.min_p > 0.0f)lines 3929–3929cps.samplers.push_back(COMMON_SAMPLER_TYPE_MIN_P);lines 3931–3931◇ if (params.temperature > 0.0f)lines 3932–3932cps.samplers.push_back(COMMON_SAMPLER_TYPE_TEMPERATURE);lines 3934–3934cps.min_p = params.min_p;lines 3935–3935cps.dry_multiplier = 0.0f;lines 3936–3936cps.top_n_sigma = -1.0f;lines 3937–3937return cps;

Requirements

REQ-INFER-006 REQ-INFER-008

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
lines 1794–1797return have_chat_params_ ? close_marker_for_format( static_cast<common_chat_format>(last_chat_format_)) : "";

Requirements

REQ-INFER-013

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

Show on the map →

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
lines 1653–1653std::string grammar = rendered.grammar;lines 1654–1655const bool gemma4_required = require_tool_call && !grammar.empty() && rendered.format == COMMON_CHAT_FORMAT_PEG_GEMMA4;lines 1656–1656◇ if (gemma4_required)lines 1657–1657std::string patched = entropic::patch_gemma4_required_root(grammar);lines 1658–1658◇ if (patched != grammar)lines 1659–1661logger->info("Gemma 4 REQUIRED tool grammar: root rewritten to " "'{}' (mirrors llama.cpp f072b10371)", entropic::gemma4_required_root_fixed_shape());lines 1662–1662grammar = std::move(patched);lines 1663–1663elselines 1664–1668logger->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));lines 1671–1671return grammar;

Requirements

REQ-INFER-008

~LlamaCppBackend

entropic::LlamaCppBackend::~LlamaCppBackend() override

Free llama.cpp + mtmd resources on destruction.

src/inference/llama_cpp_backend.cpp:1038

Show on the map →

Called by none

Calls do_unload

The index is older than this file: the lines it records no longer hold this function. Refresh the index to bundle its body.

Requirements

REQ-INFER-002