Entropic 2.14.3
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// gh#144 (v2.12.0): per-session KV residency bookkeeping.
33#include "session_residency.h"
34
35#include <llama.h>
36
37#include <atomic>
38#include <chrono>
39#include <cstdint>
40#include <functional>
41#include <memory>
42#include <mutex>
43#include <string>
44#include <vector>
45
46// Forward-declare libmtmd's opaque types at file scope so they
47// resolve to ::mtmd_context / ::mtmd_bitmap (not entropic::mtmd_*)
48// when referenced inside the class body. Full types live in
49// extern/llama.cpp/tools/mtmd/mtmd.h and are only included from
50// the implementation file. (v2.1.8, gh#37/v1.9.11 Phase 5)
51extern "C" {
52struct mtmd_context;
53struct mtmd_bitmap;
54}
55
56namespace entropic {
57
58
69public:
84 ~LlamaCppBackend() override;
85
105 void inject_tokenizer_for_test(std::unique_ptr<Tokenizer> tokenizer);
106
126 std::unique_ptr<SamplerFactory> factory);
127
140 return sampler_factory_.get();
141 }
142
157
167
179 void forget_session_kv(const std::string& session_key) override;
180
200
214
225 void clear_prompt_cache() override {
226 if (prompt_cache_) { prompt_cache_->clear(); }
227 }
228
235 std::vector<int32_t> tokenize_text(
236 const std::string& text) const override;
237
238 /* ── llama.cpp handle accessors (v1.9.2) ────────────── */
239
247
255
273
284
299 double last_prefill_ms() const { return last_prefill_ms_; }
300
307 int last_input_tokens() const { return last_input_tokens_; }
308
323 int kv_pos_max() const {
324 return ctx_ != nullptr
325 ? static_cast<int>(llama_memory_seq_pos_max(llama_get_memory(ctx_), 0))
326 : -1;
327 }
328
351 static std::uint64_t model_file_loads();
352
358 static void reset_model_file_loads();
359
360 /* ── gh#87 (v2.7.0): common_chat tool-call render + parse ── */
361
372 std::vector<ToolCall> tool_calls;
373 std::string content;
374 std::string reasoning_content;
375 };
376
391 void set_active_tools(const std::string& tools_json);
392
400
413 bool require_tool_call() const { return require_tool_call_; }
414
421 const std::string& active_tools_json() const { return active_tools_json_; }
422
439 std::string render_with_tools(
440 const std::vector<Message>& messages,
441 const GenerationParams& params);
442
459 CommonChatResult parse_response(const std::string& raw) const;
460
474
492 bool common_chat_parse_reliable() const;
493
510 std::string tool_call_close_marker() const override;
511
528 std::vector<std::string> effective_stop(
529 const GenerationParams& params) const;
530
531protected:
532 /* ── Lifecycle overrides ─────────────────────────────── */
533
534 bool do_load(const ModelConfig& config) override;
535 bool do_activate() override;
536
551 bool do_load_active(const ModelConfig& config) override;
552 void do_deactivate() override;
553 void do_unload() override;
554
555 /* ── Generation overrides ────────────────────────────── */
556
558 const std::vector<Message>& messages,
559 const GenerationParams& params) override;
560
566 const std::vector<Message>& messages,
568 std::atomic<bool>& cancel) override;
569
571 const std::vector<Message>& messages,
573 std::function<void(std::string_view token)> on_token,
574 std::atomic<bool>& cancel) override;
575
590 const std::vector<Message>& messages,
592 std::function<void(std::string_view token)> on_token,
593 std::atomic<bool>& cancel) override;
594
607 std::vector<GenerationResult> do_generate_batch(
608 const std::vector<std::vector<Message>>& requests,
609 const std::vector<GenerationParams>& params,
610 std::atomic<bool>& cancel) override;
611
612public:
619 std::string active_tool_grammar() const override { return tool_grammar_; }
620
655 const std::vector<Message>& messages,
657 std::function<void(std::string_view token)> on_token,
658 std::atomic<bool>& cancel,
659 LlamaCppBackend& draft,
660 int n_draft_max,
661 const std::string& draft_path);
662
683 const std::vector<Message>& messages,
685 std::function<void(std::string_view token)> on_token,
686 std::atomic<bool>& cancel,
687 const std::string& head_path,
688 int n_max);
689
696 bool mtp_active() const { return mtp_draft_ctx_ != nullptr; }
697
698protected:
700 const std::string& prompt,
701 const GenerationParams& params) override;
702
703 int do_count_tokens(const std::string& text) const override;
704
705 /* ── Evaluation override (v1.9.10) ──────────────────── */
706
708 const int32_t* tokens,
709 int n_tokens) override;
710
711 /* ── Capability overrides (v1.9.13) ──────────────────── */
712
713 bool do_supports(BackendCapability cap) const override;
714 std::string do_backend_name() const override;
715 BackendInfo do_info() const override;
716 bool do_clear_state(int seq_id) override;
717
718 /* ── State save/load override (gh#23 MVP item 13, v2.3.25) ── */
719
734 bool do_save_state(int seq_id,
735 std::vector<uint8_t>& buffer) const override;
736
749 bool do_restore_state(int seq_id,
750 const std::vector<uint8_t>& buffer) override;
751
752 /* ── llama.cpp handles ───────────────────────────────── */
753
754 llama_model* model_ = nullptr;
755 llama_context* ctx_ = nullptr;
756 const llama_vocab* vocab_ = nullptr;
760 double last_prefill_ms_ = 0.0;
773
782
786
793 std::string prefill_refusal_;
794
795 /* ── gh#106 (v2.9.0): MTP draft head (target-owned, shared-KV) ── */
798 std::string mtp_head_path_;
799 int mtp_n_max_ = 16;
800 std::mutex mtp_mutex_;
801
802 /* ── v2.3.10 seam: tokenizer abstraction ─────────────── */
803
811 std::unique_ptr<Tokenizer> tokenizer_;
812
813 /* ── v2.3.10 seam: sampler abstraction ───────────────── */
814
822 std::unique_ptr<SamplerFactory> sampler_factory_;
823
824 /* ── Prompt cache ───────────────────────────────────── */
825
827 std::unique_ptr<PromptCache> prompt_cache_;
828
829 /* ── gh#87 (v2.7.0): common_chat tool-call render/parse state ─ */
830
831 std::string active_tools_json_;
832 // LIVE capture — overwritten by EVERY render (incl. a toolless interleave
833 // like the constitutional validator's critique). Serves has_common_chat_
834 // params() / tool_call_close_marker() — "what THIS render produced".
837 std::string last_parser_;
838 bool have_chat_params_ = false;
839 // gh#105 (v2.8.3): "sticky last-tooled" parse snapshot — written ONLY by a
840 // successful render_with_tools, NEVER cleared by a toolless render. The
841 // engine RE-parses the main output (engine.cpp:543) AFTER the validator's
842 // toolless critique render; parse_response/common_chat_parse_reliable read
843 // THIS so that interleave can't clobber the main call's parser → no more
844 // zero-tool-call extraction with constitutional validation on.
847 std::string parse_parser_;
848 bool parse_params_valid_ = false;
849
850 /* ── gh#134 (v2.10.4): the render's tool-call grammar ──────────────
851 * common_chat_templates_apply derives a GBNF from the staged tool
852 * schemas and returns it alongside the prompt. Before v2.10.4 the
853 * render result was harvested for prompt/format/generation_prompt/parser
854 * and the grammar was DISCARDED, so a tools-staged tier decoded
855 * completely unconstrained — and tool_choice REQUIRED (upstream's
856 * "must emit a tool call", which sets grammar_lazy=false so the grammar
857 * binds from the first token) would have been inert.
858 *
859 * Applied as COMMON_GRAMMAR_TYPE_TOOL_CALLS, NOT _USER: upstream's
860 * common_grammar_needs_prefill() is true for tool-call grammars, which
861 * must have generation_prompt prefilled into the grammar sampler because
862 * the model's output begins mid-template. The USER type skips prefill and
863 * would reject from token one.
864 */
869 bool require_tool_call_ = false;
870
871 std::string tool_grammar_;
872 bool tool_grammar_lazy_ = false;
873 /* Triggers (rendered->grammar_triggers) are NOT stored here: the type
874 * common_grammar_trigger lives in llama.cpp's common.h, and this header
875 * deliberately keeps vendor types out — note parse_parser_ holds the PEG
876 * arena as a serialized std::string for the same reason. Triggers only
877 * matter when grammar_lazy is true; the gh#134 target (tool_choice
878 * REQUIRED) sets lazy=false, so eager binding needs none. Lazy support
879 * must carry them across this boundary in serialized form. */
880
881 /* ── Internal helpers ────────────────────────────────── */
882
890 std::vector<llama_token> tokenize(
891 const std::string& text, bool add_special) const;
892
899 std::string detokenize(llama_token token) const;
900
908 std::string apply_chat_template(
909 const std::vector<Message>& messages,
910 const GenerationParams& params) const;
911
927 std::string render_prompt(
928 const std::vector<Message>& messages,
929 const GenerationParams& params);
930
938 const std::vector<Message>& messages) const;
939
955 const std::vector<llama_token>& tokens,
957 std::function<void(std::string_view)> on_token,
958 std::atomic<bool>* cancel);
959
977 Sampler& sampler,
979 std::function<void(std::string_view)> on_token,
980 std::atomic<bool>* cancel);
981
990 struct BatchSeq {
991 std::unique_ptr<Sampler> sampler;
992 llama_sampler* chain = nullptr;
994 int pos = 0;
995 int logits_idx = -1;
996 int n_gen = 0;
997 int max_tokens = 0;
998 bool active = true;
999 std::vector<llama_token> out;
1000 std::string finish = "stop";
1001 };
1002
1013 std::vector<GenerationResult> run_batched_decode(
1014 const std::vector<std::vector<llama_token>>& toks,
1015 const std::vector<GenerationParams>& params,
1016 std::size_t shared,
1017 std::atomic<bool>& cancel);
1018
1020 bool prepare_batch_seqs(std::vector<BatchSeq>& seqs,
1021 const std::vector<GenerationParams>& params);
1023 bool prefill_shared_and_fanout(std::vector<BatchSeq>& seqs,
1024 const std::vector<llama_token>& seq0,
1025 std::size_t shared);
1028 std::vector<BatchSeq>& seqs,
1029 const std::vector<std::vector<llama_token>>& toks,
1030 std::size_t shared);
1032 void run_batch_gen_loop(std::vector<BatchSeq>& seqs, int max_steps,
1033 std::atomic<bool>& cancel);
1035 void sample_batch_active(std::vector<BatchSeq>& seqs);
1037 std::vector<GenerationResult> build_batch_results(
1038 std::vector<BatchSeq>& seqs);
1040 void release_temp_seqs(std::vector<BatchSeq>& seqs);
1041
1048 bool run_prefill(const std::vector<llama_token>& tokens);
1049
1059 std::string step_token(
1060 Sampler& sampler,
1061 std::string& generated,
1062 std::function<void(std::string_view)>& on_token,
1063 const std::vector<std::string>& stop);
1064
1082 std::unique_ptr<Sampler> create_sampler(
1083 const GenerationParams& params) const;
1084
1091 static std::string extract_system_prompt(
1092 const std::vector<Message>& messages);
1093
1112 bool run_prefill_cached(
1113 const std::vector<llama_token>& tokens,
1114 const std::string& system_prompt,
1115 const std::vector<Message>& messages,
1116 const GenerationParams& params);
1117
1132 bool refuse_over_context(const std::vector<llama_token>& tokens,
1133 const std::string& system_prompt);
1134
1150
1161 bool prefill_dispatch(
1162 const std::vector<llama_token>& tokens,
1163 const std::string& system_prompt,
1164 const std::vector<Message>& messages,
1165 const GenerationParams& params);
1166
1179 bool try_warm_reuse(const std::vector<llama_token>& tokens);
1180
1192
1199
1208 bool decode_tokens_into_slot(const std::vector<llama_token>& tokens,
1209 int start_offset, int slot);
1210
1217
1224 int mtp_reuse_cut(const std::vector<llama_token>& tokens) const;
1225
1233 bool decode_tokens_from(
1234 const std::vector<llama_token>& tokens, int start_offset);
1235
1244 const CacheEntry* cached,
1245 const std::vector<llama_token>& tokens);
1246
1256 const std::vector<llama_token>& tokens,
1257 int prefix_tokens,
1258 const CacheKey& key);
1259
1266 void save_prefix_to_cache(const CacheKey& key, int prefix_tokens);
1267
1276 const std::vector<Message>& messages,
1277 const GenerationParams& params);
1278
1279 /* ── Evaluation helpers (v1.9.10) ───────────────────── */
1280
1287
1293 void release_temp_seq_id(llama_seq_id seq_id);
1294
1307 static float extract_token_logprob(
1308 const float* logits,
1310 int n_vocab);
1311
1312 std::mutex seq_id_mutex_;
1313 std::vector<llama_seq_id> free_seq_ids_;
1319
1320 /* ── Architecture detection (v1.9.13) ──────────────── */
1321
1327 bool is_recurrent_ = false;
1328 bool is_hybrid_ = false;
1329
1335 bool is_recurrent() const;
1336
1337 /* ── Vision / multimodal (v1.9.11 Phases 5–7 + v2.1.8) ── */
1338
1347
1350 bool has_vision_ = false;
1351
1372 const std::vector<Message>& messages,
1373 const GenerationParams& params,
1374 std::function<void(std::string_view token)> on_token,
1375 std::atomic<bool>* cancel);
1376
1383
1394 bool load_gpu_model();
1395
1407 void bind_model_handles();
1408
1424
1435 bool finish_activation();
1436
1448
1463 bool setup_mtp_draft(const std::string& head_path, int n_max);
1464
1474 bool build_mtp_head(const std::string& head_path);
1475
1484 void teardown_mtp_draft();
1485
1493 void reload_model_cpu_only();
1494
1505 const GenerationParams& params,
1506 const std::function<void(std::string_view)>& on_token,
1507 const std::string& head_path, int n_max);
1508
1519 const std::string& prompt,
1520 const std::vector<::mtmd_bitmap*>& bitmaps,
1521 std::string& err_msg);
1522
1538 const GenerationParams& params,
1539 std::function<void(std::string_view token)> on_token,
1540 std::atomic<bool>* cancel,
1541 const std::chrono::steady_clock::time_point& t0);
1542
1549 const std::vector<Message>& messages,
1550 const GenerationParams& params);
1551
1565 const std::vector<Message>& messages,
1566 const GenerationParams& params,
1567 std::atomic<bool>& cancel);
1568
1575 const std::vector<Message>& messages,
1576 const GenerationParams& params,
1577 std::function<void(std::string_view token)> on_token,
1578 std::atomic<bool>& cancel);
1579};
1580
1581} // namespace entropic
Concrete base class for inference backends (80% logic).
Definition backend.h:69
const ModelConfig & config() const
Stored model config.
Definition backend.h:334
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.
SessionResidency< llama_token > residency_
gh#144 (v2.12.0): per-sequence warm-keep residency.
int kv_full_clear_count_
gh#158: whole-KV-cache clears since activation.
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).
static std::uint64_t model_file_loads()
Whole-file loads of a tier model in this process (gh#148).
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 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.
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).
int active_slot_
Sequence slot the current generation is bound to (gh#144).
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_.
bool finish_activation()
Context + sampler + mmproj, shared by both activation paths.
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).
void invalidate_all_resident_kv()
Drop EVERY slot's warm-keep record (gh#144, v2.12.0).
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.
static void reset_model_file_loads()
Reset the whole-file load counter (gh#148, test surface).
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 bind_model_handles()
Bind vocab, tokenizer and architecture flags to model_.
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.
int kv_full_clear_count() const
How many times the WHOLE KV cache has been cleared (gh#158).
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...
void bind_session_slot(const GenerationParams &params)
Bind this generation to its session's sequence slot (gh#144).
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.
int mtp_reuse_cut(const std::vector< llama_token > &tokens) const
How much of an MTP prompt is already resident (gh#144).
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 expert_offload_admits(const ModelConfig &config)
Refuse a loaded model that cannot honour cpu_moe_layers.
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.
GenerationResult prefill_error() const
Build the error result for a prefill that did not run.
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.
void forget_session_kv(const std::string &session_key) override
Drop one session's resident KV and release its slot (gh#165).
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.
bool decode_tokens_into_slot(const std::vector< llama_token > &tokens, int start_offset, int slot)
Decode a token run into an explicit sequence slot (gh#144).
PromptCacheConfig prompt_cache_config_
Cache config (v1.8.3)
int parse_chat_format_
Last TOOLED render's format.
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+)
std::string prefill_refusal_
v2.13.0: why the last prefill refused to run ("" = it ran).
std::string active_tool_grammar() const override
The tool-call GBNF captured by the last render (gh#154).
~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).
bool do_load_active(const ModelConfig &config) override
COLD → ACTIVE in ONE whole-file read (gh#148).
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
Per-session llama sequence slots and their resident tokens.
int * cancel
Consumer's cancel flag, nullable.
Definition engine.cpp:4074
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.
@ optional
optional: every escape asks the host's path approver
Host-memory KV cache state storage with LRU eviction.
Abstract Sampler seam for backend testability (v2.3.10).
gh#144: which llama sequence holds which session's KV, purely.
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:389
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:348
Abstract Tokenizer seam for backend testability (v2.3.10).