Entropic 2.11.1
Local-first agentic inference engine
Loading...
Searching...
No Matches
llama_cpp_backend.h
Go to the documentation of this file.
1// SPDX-License-Identifier: Apache-2.0
25#pragma once
26
30
31#include "prompt_cache.h"
32
33#include <llama.h>
34
35#include <atomic>
36#include <chrono>
37#include <cstdint>
38#include <functional>
39#include <memory>
40#include <mutex>
41#include <string>
42#include <vector>
43
44// Forward-declare libmtmd's opaque types at file scope so they
45// resolve to ::mtmd_context / ::mtmd_bitmap (not entropic::mtmd_*)
46// when referenced inside the class body. Full types live in
47// extern/llama.cpp/tools/mtmd/mtmd.h and are only included from
48// the implementation file. (v2.1.8, gh#37/v1.9.11 Phase 5)
49extern "C" {
50struct mtmd_context;
51struct mtmd_bitmap;
52}
53
54namespace entropic {
55
56
67public:
82 ~LlamaCppBackend() override;
83
103 void inject_tokenizer_for_test(std::unique_ptr<Tokenizer> tokenizer);
104
124 std::unique_ptr<SamplerFactory> factory);
125
138 return sampler_factory_.get();
139 }
140
153 return allocate_temp_seq_id();
154 }
155
162 void release_temp_seq_id_for_test(llama_seq_id id) {
164 }
165
179
190 void clear_prompt_cache() override {
191 if (prompt_cache_) { prompt_cache_->clear(); }
192 }
193
200 std::vector<int32_t> tokenize_text(
201 const std::string& text) const override;
202
203 /* ── llama.cpp handle accessors (v1.9.2) ────────────── */
204
211 llama_model* llama_model_ptr() { return model_; }
212
219 llama_context* llama_context_ptr() { return ctx_; }
220
238
249
264 double last_prefill_ms() const { return last_prefill_ms_; }
265
272 int last_input_tokens() const { return last_input_tokens_; }
273
288 int kv_pos_max() const {
289 return ctx_ != nullptr
290 ? static_cast<int>(llama_memory_seq_pos_max(llama_get_memory(ctx_), 0))
291 : -1;
292 }
293
294 /* ── gh#87 (v2.7.0): common_chat tool-call render + parse ── */
295
306 std::vector<ToolCall> tool_calls;
307 std::string content;
308 std::string reasoning_content;
309 };
310
325 void set_active_tools(const std::string& tools_json);
326
333 void set_require_tool_call(bool require) { require_tool_call_ = require; }
334
347 bool require_tool_call() const { return require_tool_call_; }
348
355 const std::string& active_tools_json() const { return active_tools_json_; }
356
373 std::string render_with_tools(
374 const std::vector<Message>& messages,
375 const GenerationParams& params);
376
393 CommonChatResult parse_response(const std::string& raw) const;
394
408
426 bool common_chat_parse_reliable() const;
427
444 std::string tool_call_close_marker() const override;
445
462 std::vector<std::string> effective_stop(
463 const GenerationParams& params) const;
464
465protected:
466 /* ── Lifecycle overrides ─────────────────────────────── */
467
468 bool do_load(const ModelConfig& config) override;
469 bool do_activate() override;
470 void do_deactivate() override;
471 void do_unload() override;
472
473 /* ── Generation overrides ────────────────────────────── */
474
476 const std::vector<Message>& messages,
477 const GenerationParams& params) override;
478
484 const std::vector<Message>& messages,
485 const GenerationParams& params,
486 std::atomic<bool>& cancel) override;
487
489 const std::vector<Message>& messages,
490 const GenerationParams& params,
491 std::function<void(std::string_view token)> on_token,
492 std::atomic<bool>& cancel) override;
493
508 const std::vector<Message>& messages,
509 const GenerationParams& params,
510 std::function<void(std::string_view token)> on_token,
511 std::atomic<bool>& cancel) override;
512
525 std::vector<GenerationResult> do_generate_batch(
526 const std::vector<std::vector<Message>>& requests,
527 const std::vector<GenerationParams>& params,
528 std::atomic<bool>& cancel) override;
529
530public:
565 const std::vector<Message>& messages,
566 const GenerationParams& params,
567 std::function<void(std::string_view token)> on_token,
568 std::atomic<bool>& cancel,
569 LlamaCppBackend& draft,
570 int n_draft_max,
571 const std::string& draft_path);
572
593 const std::vector<Message>& messages,
594 const GenerationParams& params,
595 std::function<void(std::string_view token)> on_token,
596 std::atomic<bool>& cancel,
597 const std::string& head_path,
598 int n_max);
599
606 bool mtp_active() const { return mtp_draft_ctx_ != nullptr; }
607
608protected:
610 const std::string& prompt,
611 const GenerationParams& params) override;
612
613 int do_count_tokens(const std::string& text) const override;
614
615 /* ── Evaluation override (v1.9.10) ──────────────────── */
616
618 const int32_t* tokens,
619 int n_tokens) override;
620
621 /* ── Capability overrides (v1.9.13) ──────────────────── */
622
623 bool do_supports(BackendCapability cap) const override;
624 std::string do_backend_name() const override;
625 BackendInfo do_info() const override;
626 bool do_clear_state(int seq_id) override;
627
628 /* ── State save/load override (gh#23 MVP item 13, v2.3.25) ── */
629
644 bool do_save_state(int seq_id,
645 std::vector<uint8_t>& buffer) const override;
646
659 bool do_restore_state(int seq_id,
660 const std::vector<uint8_t>& buffer) override;
661
662 /* ── llama.cpp handles ───────────────────────────────── */
663
664 llama_model* model_ = nullptr;
665 llama_context* ctx_ = nullptr;
666 const llama_vocab* vocab_ = nullptr;
670 double last_prefill_ms_ = 0.0;
671 std::vector<llama_token> resident_tokens_;
672
673 /* ── gh#106 (v2.9.0): MTP draft head (target-owned, shared-KV) ── */
674 llama_model* mtp_draft_model_ = nullptr;
675 llama_context* mtp_draft_ctx_ = nullptr;
676 std::string mtp_head_path_;
677 int mtp_n_max_ = 16;
678 std::mutex mtp_mutex_;
679
680 /* ── v2.3.10 seam: tokenizer abstraction ─────────────── */
681
689 std::unique_ptr<Tokenizer> tokenizer_;
690
691 /* ── v2.3.10 seam: sampler abstraction ───────────────── */
692
700 std::unique_ptr<SamplerFactory> sampler_factory_;
701
702 /* ── Prompt cache ───────────────────────────────────── */
703
705 std::unique_ptr<PromptCache> prompt_cache_;
706
707 /* ── gh#87 (v2.7.0): common_chat tool-call render/parse state ─ */
708
709 std::string active_tools_json_;
710 // LIVE capture — overwritten by EVERY render (incl. a toolless interleave
711 // like the constitutional validator's critique). Serves has_common_chat_
712 // params() / tool_call_close_marker() — "what THIS render produced".
715 std::string last_parser_;
716 bool have_chat_params_ = false;
717 // gh#105 (v2.8.3): "sticky last-tooled" parse snapshot — written ONLY by a
718 // successful render_with_tools, NEVER cleared by a toolless render. The
719 // engine RE-parses the main output (engine.cpp:543) AFTER the validator's
720 // toolless critique render; parse_response/common_chat_parse_reliable read
721 // THIS so that interleave can't clobber the main call's parser → no more
722 // zero-tool-call extraction with constitutional validation on.
725 std::string parse_parser_;
726 bool parse_params_valid_ = false;
727
728 /* ── gh#134 (v2.10.4): the render's tool-call grammar ──────────────
729 * common_chat_templates_apply derives a GBNF from the staged tool
730 * schemas and returns it alongside the prompt. Before v2.10.4 the
731 * render result was harvested for prompt/format/generation_prompt/parser
732 * and the grammar was DISCARDED, so a tools-staged tier decoded
733 * completely unconstrained — and tool_choice REQUIRED (upstream's
734 * "must emit a tool call", which sets grammar_lazy=false so the grammar
735 * binds from the first token) would have been inert.
736 *
737 * Applied as COMMON_GRAMMAR_TYPE_TOOL_CALLS, NOT _USER: upstream's
738 * common_grammar_needs_prefill() is true for tool-call grammars, which
739 * must have generation_prompt prefilled into the grammar sampler because
740 * the model's output begins mid-template. The USER type skips prefill and
741 * would reject from token one.
742 */
747 bool require_tool_call_ = false;
748
749 std::string tool_grammar_;
750 bool tool_grammar_lazy_ = false;
751 /* Triggers (rendered->grammar_triggers) are NOT stored here: the type
752 * common_grammar_trigger lives in llama.cpp's common.h, and this header
753 * deliberately keeps vendor types out — note parse_parser_ holds the PEG
754 * arena as a serialized std::string for the same reason. Triggers only
755 * matter when grammar_lazy is true; the gh#134 target (tool_choice
756 * REQUIRED) sets lazy=false, so eager binding needs none. Lazy support
757 * must carry them across this boundary in serialized form. */
758
759 /* ── Internal helpers ────────────────────────────────── */
760
768 std::vector<llama_token> tokenize(
769 const std::string& text, bool add_special) const;
770
777 std::string detokenize(llama_token token) const;
778
786 std::string apply_chat_template(
787 const std::vector<Message>& messages,
788 const GenerationParams& params) const;
789
805 std::string render_prompt(
806 const std::vector<Message>& messages,
807 const GenerationParams& params);
808
816 const std::vector<Message>& messages) const;
817
833 const std::vector<llama_token>& tokens,
834 const GenerationParams& params,
835 std::function<void(std::string_view)> on_token,
836 std::atomic<bool>* cancel);
837
855 Sampler& sampler,
856 const GenerationParams& params,
857 std::function<void(std::string_view)> on_token,
858 std::atomic<bool>* cancel);
859
868 struct BatchSeq {
869 std::unique_ptr<Sampler> sampler;
870 llama_sampler* chain = nullptr;
871 llama_seq_id seq_id = 0;
872 int pos = 0;
873 int logits_idx = -1;
874 int n_gen = 0;
875 int max_tokens = 0;
876 bool active = true;
877 std::vector<llama_token> out;
878 std::string finish = "stop";
879 };
880
891 std::vector<GenerationResult> run_batched_decode(
892 const std::vector<std::vector<llama_token>>& toks,
893 const std::vector<GenerationParams>& params,
894 std::size_t shared,
895 std::atomic<bool>& cancel);
896
898 bool prepare_batch_seqs(std::vector<BatchSeq>& seqs,
899 const std::vector<GenerationParams>& params);
901 bool prefill_shared_and_fanout(std::vector<BatchSeq>& seqs,
902 const std::vector<llama_token>& seq0,
903 std::size_t shared);
906 std::vector<BatchSeq>& seqs,
907 const std::vector<std::vector<llama_token>>& toks,
908 std::size_t shared);
910 void run_batch_gen_loop(std::vector<BatchSeq>& seqs, int max_steps,
911 std::atomic<bool>& cancel);
913 void sample_batch_active(std::vector<BatchSeq>& seqs);
915 std::vector<GenerationResult> build_batch_results(
916 std::vector<BatchSeq>& seqs);
918 void release_temp_seqs(std::vector<BatchSeq>& seqs);
919
926 bool run_prefill(const std::vector<llama_token>& tokens);
927
937 std::string step_token(
938 Sampler& sampler,
939 std::string& generated,
940 std::function<void(std::string_view)>& on_token,
941 const std::vector<std::string>& stop);
942
960 std::unique_ptr<Sampler> create_sampler(
961 const GenerationParams& params) const;
962
969 static std::string extract_system_prompt(
970 const std::vector<Message>& messages);
971
982 const std::vector<llama_token>& tokens,
983 const std::string& system_prompt,
984 const std::vector<Message>& messages,
985 const GenerationParams& params);
986
997 bool prefill_dispatch(
998 const std::vector<llama_token>& tokens,
999 const std::string& system_prompt,
1000 const std::vector<Message>& messages,
1001 const GenerationParams& params);
1002
1015 bool try_warm_reuse(const std::vector<llama_token>& tokens);
1016
1028
1036 bool decode_tokens_from(
1037 const std::vector<llama_token>& tokens, int start_offset);
1038
1047 const CacheEntry* cached,
1048 const std::vector<llama_token>& tokens);
1049
1059 const std::vector<llama_token>& tokens,
1060 int prefix_tokens,
1061 const CacheKey& key);
1062
1069 void save_prefix_to_cache(const CacheKey& key, int prefix_tokens);
1070
1079 const std::vector<Message>& messages,
1080 const GenerationParams& params);
1081
1082 /* ── Evaluation helpers (v1.9.10) ───────────────────── */
1083
1089 llama_seq_id allocate_temp_seq_id();
1090
1096 void release_temp_seq_id(llama_seq_id seq_id);
1097
1110 static float extract_token_logprob(
1111 const float* logits,
1112 int32_t next_token,
1113 int n_vocab);
1114
1115 std::mutex seq_id_mutex_;
1116 std::vector<llama_seq_id> free_seq_ids_;
1121 llama_seq_id next_temp_seq_id_ = 1;
1122
1123 /* ── Architecture detection (v1.9.13) ──────────────── */
1124
1130 bool is_recurrent_ = false;
1131 bool is_hybrid_ = false;
1132
1138 bool is_recurrent() const;
1139
1140 /* ── Vision / multimodal (v1.9.11 Phases 5–7 + v2.1.8) ── */
1141
1149 ::mtmd_context* mtmd_ctx_ = nullptr;
1150
1153 bool has_vision_ = false;
1154
1175 const std::vector<Message>& messages,
1176 const GenerationParams& params,
1177 std::function<void(std::string_view token)> on_token,
1178 std::atomic<bool>* cancel);
1179
1186
1197 bool load_gpu_model();
1198
1210
1225 bool setup_mtp_draft(const std::string& head_path, int n_max);
1226
1236 bool build_mtp_head(const std::string& head_path);
1237
1246 void teardown_mtp_draft();
1247
1255 void reload_model_cpu_only();
1256
1267 const GenerationParams& params,
1268 const std::function<void(std::string_view)>& on_token,
1269 const std::string& head_path, int n_max);
1270
1281 const std::string& prompt,
1282 const std::vector<::mtmd_bitmap*>& bitmaps,
1283 std::string& err_msg);
1284
1300 const GenerationParams& params,
1301 std::function<void(std::string_view token)> on_token,
1302 std::atomic<bool>* cancel,
1303 const std::chrono::steady_clock::time_point& t0);
1304
1311 const std::vector<Message>& messages,
1312 const GenerationParams& params);
1313
1327 const std::vector<Message>& messages,
1328 const GenerationParams& params,
1329 std::atomic<bool>& cancel);
1330
1337 const std::vector<Message>& messages,
1338 const GenerationParams& params,
1339 std::function<void(std::string_view token)> on_token,
1340 std::atomic<bool>& cancel);
1341};
1342
1343} // namespace entropic
Concrete base class for inference backends (80% logic).
Definition backend.h:69
const ModelConfig & config() const
Stored model config.
Definition backend.h:320
LlamaCppBackend — common llama.cpp patterns (15% layer).
bool parse_params_valid_
True once a tooled render snapshotted.
int last_gen_decode_calls_
gh#98: batched-decode step count of last batch
bool load_gpu_model()
Load the GGUF model onto the GPU (do_activate step 1).
bool do_load(const ModelConfig &config) override
Load model into CPU RAM (COLD → WARM).
bool do_supports(BackendCapability cap) const override
Declare llama.cpp backend capabilities.
std::vector< GenerationResult > build_batch_results(std::vector< BatchSeq > &seqs)
Detokenize each sequence into a GenerationResult.
std::vector< std::string > effective_stop(const GenerationParams &params) const
params.stop + the sequential tool-call close marker, if applicable.
double last_prefill_ms_
gh#96: prefill wall-clock ms of last generate()
int last_input_tokens_
gh#97: tokenized prompt size of last generate()
GenerationResult decode_loop(const std::vector< llama_token > &tokens, const GenerationParams &params, std::function< void(std::string_view)> on_token, std::atomic< bool > *cancel)
Core decode loop — shared by generate and streaming.
void clear_prompt_cache() override
Drop every cached prefix so the next prefill re-seeds.
bool is_recurrent_
True if loaded model is recurrent (GDN/Mamba/RWKV).
bool try_warm_reuse(const std::vector< llama_token > &tokens)
gh#96 (v2.7.5): try incremental prefill against resident KV.
LogprobResult do_evaluate_logprobs(const int32_t *tokens, int n_tokens) override
Evaluate per-token log-probabilities via sequential decode.
std::string do_backend_name() const override
Return backend name.
bool is_hybrid_
gh#97: attention + recurrent/SSM memory
bool do_save_state(int seq_id, std::vector< uint8_t > &buffer) const override
Capture a sequence's KV cache into a byte buffer.
std::string render_prompt(const std::vector< Message > &messages, const GenerationParams &params)
Generation render seam: common_chat-with-tools or legacy (gh#87).
std::unique_ptr< PromptCache > prompt_cache_
KV prefix cache (v1.8.3)
void teardown_mtp_draft()
Free the MTP head context + model (gh#106 lifecycle).
llama_context * llama_context_ptr()
Get the active llama_context pointer.
void set_require_tool_call(bool require)
Require the next render's decode to emit a tool call (gh#134).
std::string parse_generation_prompt_
Last TOOLED render's gen prompt.
std::vector< GenerationResult > run_batched_decode(const std::vector< std::vector< llama_token > > &toks, const std::vector< GenerationParams > &params, std::size_t shared, std::atomic< bool > &cancel)
Run the gh#98 multi-seq batched decode (v2.8.0).
double last_prefill_ms() const
Wall-clock milliseconds spent in prefill by the last generation.
GenerationResult do_generate(const std::vector< Message > &messages, const GenerationParams &params) override
Generate a complete response using chat template.
void reload_model_cpu_only()
Reload the model CPU-only for the WARM state (do_deactivate tail).
bool mtp_active() const
True when an MTP head context is live against the current ctx_.
std::string render_with_tools(const std::vector< Message > &messages, const GenerationParams &params)
Render messages through common_chat WITH the active tools.
void sample_batch_active(std::vector< BatchSeq > &seqs)
Sample+accept+classify each still-active sequence.
bool common_chat_parse_reliable() const
True iff common_chat parsing is reliable for the last render (gh#87).
void set_prompt_cache_config(const PromptCacheConfig &config)
Set prompt cache configuration.
std::string active_tools_json_
MCP tool defs for next render.
GenerationResult do_complete(const std::string &prompt, const GenerationParams &params) override
Raw text completion without chat template.
int last_prefill_tokens_
gh#96: prompt tokens decoded by last generate()
std::vector< llama_token > tokenize(const std::string &text, bool add_special) const
Tokenize text using model vocabulary.
bool create_inference_context()
Create the llama context + prompt cache (do_activate step 2).
void release_temp_seq_id_for_test(llama_seq_id id)
Release a temp seq_id (test-only seam, gh#98).
const llama_vocab * vocab_
Vocabulary (from model_)
std::string tool_call_close_marker() const override
Tool-call close marker for the captured chat format (gh#103).
bool have_chat_params_
True once a tool render captured params.
int compute_prefix_token_count(const std::vector< Message > &messages, const GenerationParams &params)
Compute token count of system messages only.
std::unique_ptr< SamplerFactory > sampler_factory_
Factory used by the decode loop to build per-generation samplers.
void release_temp_seqs(std::vector< BatchSeq > &seqs)
Release every batch sequence's temp seq_id (seq 0 excluded).
SamplerFactory * sampler_factory_for_test() const
Read the currently-wired SamplerFactory (test-only).
std::string detokenize(llama_token token) const
Detokenize a single token.
void set_active_tools(const std::string &tools_json)
Stage tool definitions for the next common_chat render (gh#87).
void init_mmproj_if_configured()
Initialize the libmtmd context if mmproj is configured.
int last_chat_format_
Captured common_chat_format.
const std::string & active_tools_json() const
Return the tool definitions staged for the current turn.
GenerationResult generate_speculative_with_draft(const std::vector< Message > &messages, const GenerationParams &params, std::function< void(std::string_view token)> on_token, std::atomic< bool > &cancel, LlamaCppBackend &draft, int n_draft_max, const std::string &draft_path)
Speculative-decoding kernel with explicit draft backend.
llama_context * ctx_
Inference context (ACTIVE)
bool run_prefill(const std::vector< llama_token > &tokens)
Run batched prefill on input tokens.
GenerationResult run_sampling_loop(const GenerationParams &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.
llama_seq_id next_temp_seq_id_
gh#98: monotonic high-water for NEW temp seq_ids (the old 1 + size() handed out duplicates when the p...
std::string last_generation_prompt_
Captured generation_prompt.
GenerationResult mtp_guard(const GenerationParams &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).
bool restore_cached_prefix(const CacheEntry *cached, const std::vector< llama_token > &tokens)
Restore KV state from cache and decode remaining tokens.
void save_prefix_to_cache(const CacheKey &key, int prefix_tokens)
Capture seq 0 KV state and store under the given key.
std::vector< int32_t > tokenize_text(const std::string &text) const override
Tokenize text to token IDs using model vocabulary.
int mtp_n_max_
MTP draft window (n_max) of the live head.
bool is_recurrent() const
Check if loaded model is recurrent.
std::string step_token(Sampler &sampler, std::string &generated, std::function< void(std::string_view)> &on_token, const std::vector< std::string > &stop)
Generate one token and append to output.
GenerationResult generate_after_prefill(Sampler &sampler, const GenerationParams &params, std::function< void(std::string_view)> on_token, std::atomic< bool > *cancel)
The post-prefill sampling loop (extracted from decode_loop).
int kv_pos_max() const
Highest occupied KV position in seq 0 right now (live query).
entropic_error_t mtmd_prefill(const std::string &prompt, const std::vector<::mtmd_bitmap * > &bitmaps, std::string &err_msg)
Run mtmd_tokenize + mtmd_helper_eval_chunks on a prompt.
void run_batch_gen_loop(std::vector< BatchSeq > &seqs, int max_steps, std::atomic< bool > &cancel)
Decode all sequences together until each finishes.
bool run_prefill_cached(const std::vector< llama_token > &tokens, const std::string &system_prompt, const std::vector< Message > &messages, const GenerationParams &params)
Run prefill with prompt cache integration.
std::string mtp_head_path_
Path the live mtp_draft_ctx_ was built from.
int last_input_tokens() const
Tokenized prompt size of the last generation (input tokens).
GenerationResult do_generate_text_only(const std::vector< Message > &messages, const GenerationParams &params)
Text-only batch generation (extracted from do_generate).
bool do_restore_state(int seq_id, const std::vector< uint8_t > &buffer) override
Restore a sequence's KV cache from a byte buffer.
std::string apply_chat_template(const std::vector< Message > &messages, const GenerationParams &params) const
Apply chat template to messages.
CommonChatResult parse_response(const std::string &raw) const
Parse a raw model emission via the last captured render params.
bool prefill_batch_suffixes(std::vector< BatchSeq > &seqs, const std::vector< std::vector< llama_token > > &toks, std::size_t shared)
Prefill each request's suffix; set per-seq logits_idx.
std::unique_ptr< Tokenizer > tokenizer_
Tokenizer used by tokenize_text / do_count_tokens / internal tokenize/detokenize.
GenerationResult do_generate_streaming(const std::vector< Message > &messages, const GenerationParams &params, std::function< void(std::string_view token)> on_token, std::atomic< bool > &cancel) override
Streaming generation with per-token callback.
bool has_vision_
Cached mtmd_support_vision(mtmd_ctx_) result.
void inject_tokenizer_for_test(std::unique_ptr< Tokenizer > tokenizer)
Inject a tokenizer for unit testing (v2.3.10).
bool has_common_chat_params() const
True iff the last render captured common_chat parse params (gh#87).
bool decode_tokens_from(const std::vector< llama_token > &tokens, int start_offset)
Decode tokens starting at a given offset.
bool prefill_dispatch(const std::vector< llama_token > &tokens, const std::string &system_prompt, const std::vector< Message > &messages, const GenerationParams &params)
Cache-aware prefill dispatch (gh#96 v2.7.5: extracted body of run_prefill_cached so the wrapper owns ...
void release_temp_seq_id(llama_seq_id seq_id)
Release a temporary sequence ID back to the pool.
std::unique_ptr< Sampler > create_sampler(const GenerationParams &params) const
Build a Sampler for one generation from params.
llama_model * llama_model_ptr()
Get the loaded llama_model pointer.
int do_count_tokens(const std::string &text) const override
Count tokens in text.
::mtmd_context * mtmd_ctx_
libmtmd context, or nullptr if no mmproj loaded.
bool require_tool_call_
gh#134 (v2.10.4): when true the render asks llama.cpp for COMMON_CHAT_TOOL_CHOICE_REQUIRED,...
std::string tool_grammar_
Render-derived tool-call GBNF.
std::string last_parser_
Captured serialized PEG arena.
bool require_tool_call() const
Whether this backend will request REQUIRED on its next render.
GenerationResult 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).
std::mutex seq_id_mutex_
Guards temp seq_id pool (v1.9.10)
bool do_clear_state(int seq_id) override
Clear KV cache or recurrent hidden state.
bool prefill_shared_and_fanout(std::vector< BatchSeq > &seqs, const std::vector< llama_token > &seq0, std::size_t shared)
Prefill shared prefix into seq 0 + seq_cp fan-out.
std::string apply_chat_template_lowlevel(const std::vector< Message > &messages) const
Low-level GGUF template path (gh#86 fallback, v2.6.1).
static float extract_token_logprob(const float *logits, int32_t next_token, int n_vocab)
Extract log-probability for a token from logits.
void do_deactivate() override
Deactivate: free context, reload model CPU-only.
GenerationResult generate_mtp(const std::vector< Message > &messages, const GenerationParams &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).
int last_prefill_tokens() const
Prompt (prefill) tokens actually decoded by the last generation.
bool tool_grammar_lazy_
Arm on trigger vs bind eagerly.
BackendInfo do_info() const override
Populate backend metadata from llama.cpp model.
std::vector< GenerationResult > do_generate_batch(const std::vector< std::vector< Message > > &requests, const std::vector< GenerationParams > &params, std::atomic< bool > &cancel) override
Same-prefix batch generation (gh#98, v2.8.0).
std::string parse_parser_
Last TOOLED render's PEG arena.
bool do_activate() override
Activate model on GPU (WARM → ACTIVE).
bool prepare_batch_seqs(std::vector< BatchSeq > &seqs, const std::vector< GenerationParams > &params)
Build per-request sampler chains + seq ids.
bool build_mtp_head(const std::string &head_path)
Load the MTP head GGUF + create its shared-KV context (gh#106).
bool prefill_and_cache_prefix(const std::vector< llama_token > &tokens, int prefix_tokens, const CacheKey &key)
Two-pass prefill: prefix-only prefill → save → rest.
std::mutex mtp_mutex_
gh#108: serialises MTP head setup/teardown vs in-flight generate_mtp (no deactivate-during-generate U...
llama_seq_id allocate_temp_seq_id()
Allocate a temporary sequence ID for evaluation.
PromptCacheConfig prompt_cache_config_
Cache config (v1.8.3)
int parse_chat_format_
Last TOOLED render's format.
std::vector< llama_token > resident_tokens_
gh#96: tokens resident in KV seq 0 (warm-keep)
llama_model * mtp_draft_model_
MTP head GGUF (separate, trunk-sharing)
void do_unload() override
Full unload — free all resources, clear prompt cache.
llama_model * model_
Loaded model (WARM+)
~LlamaCppBackend() override
Free llama.cpp + mtmd resources on destruction.
void invalidate_resident_kv()
gh#96 (v2.7.5): drop the warm-keep resident-KV record.
std::vector< llama_seq_id > free_seq_ids_
Available temporary seq_ids (v1.9.10)
GenerationResult do_generate_speculative(const std::vector< Message > &messages, const GenerationParams &params, std::function< void(std::string_view token)> on_token, std::atomic< bool > &cancel) override
Speculative streaming via the abstract InferenceBackend interface (kept as NOT_SUPPORTED — see kernel...
GenerationResult do_generate_streaming_text_only(const std::vector< Message > &messages, const GenerationParams &params, std::function< void(std::string_view token)> on_token, std::atomic< bool > &cancel)
Text-only streaming generation (extracted from streaming).
static std::string extract_system_prompt(const std::vector< Message > &messages)
Extract the system prompt from messages.
llama_seq_id allocate_temp_seq_id_for_test()
Allocate a temp seq_id (test-only seam for gh#98).
llama_context * mtp_draft_ctx_
MTP context (ctx_type=MTP, ctx_other=ctx_)
void inject_sampler_factory_for_test(std::unique_ptr< SamplerFactory > factory)
Inject a SamplerFactory for unit testing (v2.3.10).
int last_gen_decode_calls() const
Number of batched generation decodes in the last gh#98 batch.
bool setup_mtp_draft(const std::string &head_path, int n_max)
Lazily build the MTP head context against the live ctx_ (gh#106).
Factory that materializes a Sampler from GenerationParams.
Definition sampler.h:93
Pure-virtual per-generation sampler used by the decode loop.
Definition sampler.h:48
entropic_error_t
Error codes returned by all C API functions.
Definition error.h:37
InferenceBackend concrete base class.
Activate model on GPU (WARM → ACTIVE).
BackendCapability
Capabilities that an inference backend may or may not support.
@ tokens
Gate on generated tokens since the last tool call.
Host-memory KV cache state storage with LRU eviction.
Abstract Sampler seam for backend testability (v2.3.10).
Backend metadata for introspection.
Single cached KV state snapshot.
64-bit hash used as cache lookup key.
Generation parameters for a single inference call.
Definition config.h:313
Result of a single generation call.
Per-sequence state for the gh#98 multi-seq batched decode.
int pos
Next KV position to write.
int logits_idx
Batch cell holding current logits.
std::vector< llama_token > out
Generated tokens.
llama_seq_id seq_id
KV sequence id.
llama_sampler * chain
Borrowed native chain (sampled per-idx)
int max_tokens
Per-request generation cap.
int n_gen
Tokens generated so far.
std::unique_ptr< Sampler > sampler
Owns the per-request chain.
Result of a common_chat parse: native tool calls + split content.
std::vector< ToolCall > tool_calls
Extracted native tool calls.
std::string content
Content with calls + reasoning removed.
std::string reasoning_content
Extracted reasoning/thought block.
Per-token log-probability evaluation result.
Model configuration for a single tier.
Definition config.h:154
Prompt caching configuration.
Definition config.h:272
Abstract Tokenizer seam for backend testability (v2.3.10).