Entropic 2.9.4
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
66public:
81 ~LlamaCppBackend() override;
82
102 void inject_tokenizer_for_test(std::unique_ptr<Tokenizer> tokenizer);
103
123 std::unique_ptr<SamplerFactory> factory);
124
137 return sampler_factory_.get();
138 }
139
152 return allocate_temp_seq_id();
153 }
154
161 void release_temp_seq_id_for_test(llama_seq_id id) {
163 }
164
178
189 void clear_prompt_cache() override {
190 if (prompt_cache_) { prompt_cache_->clear(); }
191 }
192
199 std::vector<int32_t> tokenize_text(
200 const std::string& text) const override;
201
202 /* ── llama.cpp handle accessors (v1.9.2) ────────────── */
203
210 llama_model* llama_model_ptr() { return model_; }
211
218 llama_context* llama_context_ptr() { return ctx_; }
219
237
248
263 double last_prefill_ms() const { return last_prefill_ms_; }
264
271 int last_input_tokens() const { return last_input_tokens_; }
272
287 int kv_pos_max() const {
288 return ctx_ != nullptr
289 ? static_cast<int>(llama_memory_seq_pos_max(llama_get_memory(ctx_), 0))
290 : -1;
291 }
292
293 /* ── gh#87 (v2.7.0): common_chat tool-call render + parse ── */
294
305 std::vector<ToolCall> tool_calls;
306 std::string content;
307 std::string reasoning_content;
308 };
309
324 void set_active_tools(const std::string& tools_json);
325
342 std::string render_with_tools(
343 const std::vector<Message>& messages,
344 const GenerationParams& params);
345
362 CommonChatResult parse_response(const std::string& raw) const;
363
377
395 bool common_chat_parse_reliable() const;
396
413 std::string tool_call_close_marker() const override;
414
431 std::vector<std::string> effective_stop(
432 const GenerationParams& params) const;
433
434protected:
435 /* ── Lifecycle overrides ─────────────────────────────── */
436
437 bool do_load(const ModelConfig& config) override;
438 bool do_activate() override;
439 void do_deactivate() override;
440 void do_unload() override;
441
442 /* ── Generation overrides ────────────────────────────── */
443
445 const std::vector<Message>& messages,
446 const GenerationParams& params) override;
447
453 const std::vector<Message>& messages,
454 const GenerationParams& params,
455 std::atomic<bool>& cancel) override;
456
458 const std::vector<Message>& messages,
459 const GenerationParams& params,
460 std::function<void(std::string_view token)> on_token,
461 std::atomic<bool>& cancel) override;
462
477 const std::vector<Message>& messages,
478 const GenerationParams& params,
479 std::function<void(std::string_view token)> on_token,
480 std::atomic<bool>& cancel) override;
481
494 std::vector<GenerationResult> do_generate_batch(
495 const std::vector<std::vector<Message>>& requests,
496 const std::vector<GenerationParams>& params,
497 std::atomic<bool>& cancel) override;
498
499public:
534 const std::vector<Message>& messages,
535 const GenerationParams& params,
536 std::function<void(std::string_view token)> on_token,
537 std::atomic<bool>& cancel,
538 LlamaCppBackend& draft,
539 int n_draft_max,
540 const std::string& draft_path);
541
562 const std::vector<Message>& messages,
563 const GenerationParams& params,
564 std::function<void(std::string_view token)> on_token,
565 std::atomic<bool>& cancel,
566 const std::string& head_path,
567 int n_max);
568
575 bool mtp_active() const { return mtp_draft_ctx_ != nullptr; }
576
577protected:
579 const std::string& prompt,
580 const GenerationParams& params) override;
581
582 int do_count_tokens(const std::string& text) const override;
583
584 /* ── Evaluation override (v1.9.10) ──────────────────── */
585
587 const int32_t* tokens,
588 int n_tokens) override;
589
590 /* ── Capability overrides (v1.9.13) ──────────────────── */
591
592 bool do_supports(BackendCapability cap) const override;
593 std::string do_backend_name() const override;
594 BackendInfo do_info() const override;
595 bool do_clear_state(int seq_id) override;
596
597 /* ── State save/load override (gh#23 MVP item 13, v2.3.25) ── */
598
613 bool do_save_state(int seq_id,
614 std::vector<uint8_t>& buffer) const override;
615
628 bool do_restore_state(int seq_id,
629 const std::vector<uint8_t>& buffer) override;
630
631 /* ── llama.cpp handles ───────────────────────────────── */
632
633 llama_model* model_ = nullptr;
634 llama_context* ctx_ = nullptr;
635 const llama_vocab* vocab_ = nullptr;
639 double last_prefill_ms_ = 0.0;
640 std::vector<llama_token> resident_tokens_;
641
642 /* ── gh#106 (v2.9.0): MTP draft head (target-owned, shared-KV) ── */
643 llama_model* mtp_draft_model_ = nullptr;
644 llama_context* mtp_draft_ctx_ = nullptr;
645 std::string mtp_head_path_;
646 int mtp_n_max_ = 16;
647 std::mutex mtp_mutex_;
648
649 /* ── v2.3.10 seam: tokenizer abstraction ─────────────── */
650
658 std::unique_ptr<Tokenizer> tokenizer_;
659
660 /* ── v2.3.10 seam: sampler abstraction ───────────────── */
661
669 std::unique_ptr<SamplerFactory> sampler_factory_;
670
671 /* ── Prompt cache ───────────────────────────────────── */
672
674 std::unique_ptr<PromptCache> prompt_cache_;
675
676 /* ── gh#87 (v2.7.0): common_chat tool-call render/parse state ─ */
677
678 std::string active_tools_json_;
679 // LIVE capture — overwritten by EVERY render (incl. a toolless interleave
680 // like the constitutional validator's critique). Serves has_common_chat_
681 // params() / tool_call_close_marker() — "what THIS render produced".
684 std::string last_parser_;
685 bool have_chat_params_ = false;
686 // gh#105 (v2.8.3): "sticky last-tooled" parse snapshot — written ONLY by a
687 // successful render_with_tools, NEVER cleared by a toolless render. The
688 // engine RE-parses the main output (engine.cpp:543) AFTER the validator's
689 // toolless critique render; parse_response/common_chat_parse_reliable read
690 // THIS so that interleave can't clobber the main call's parser → no more
691 // zero-tool-call extraction with constitutional validation on.
694 std::string parse_parser_;
695 bool parse_params_valid_ = false;
696
697 /* ── Internal helpers ────────────────────────────────── */
698
706 std::vector<llama_token> tokenize(
707 const std::string& text, bool add_special) const;
708
715 std::string detokenize(llama_token token) const;
716
724 std::string apply_chat_template(
725 const std::vector<Message>& messages,
726 const GenerationParams& params) const;
727
743 std::string render_prompt(
744 const std::vector<Message>& messages,
745 const GenerationParams& params);
746
754 const std::vector<Message>& messages) const;
755
771 const std::vector<llama_token>& tokens,
772 const GenerationParams& params,
773 std::function<void(std::string_view)> on_token,
774 std::atomic<bool>* cancel);
775
793 Sampler& sampler,
794 const GenerationParams& params,
795 std::function<void(std::string_view)> on_token,
796 std::atomic<bool>* cancel);
797
806 struct BatchSeq {
807 std::unique_ptr<Sampler> sampler;
808 llama_sampler* chain = nullptr;
809 llama_seq_id seq_id = 0;
810 int pos = 0;
811 int logits_idx = -1;
812 int n_gen = 0;
813 int max_tokens = 0;
814 bool active = true;
815 std::vector<llama_token> out;
816 std::string finish = "stop";
817 };
818
829 std::vector<GenerationResult> run_batched_decode(
830 const std::vector<std::vector<llama_token>>& toks,
831 const std::vector<GenerationParams>& params,
832 std::size_t shared,
833 std::atomic<bool>& cancel);
834
836 bool prepare_batch_seqs(std::vector<BatchSeq>& seqs,
837 const std::vector<GenerationParams>& params);
839 bool prefill_shared_and_fanout(std::vector<BatchSeq>& seqs,
840 const std::vector<llama_token>& seq0,
841 std::size_t shared);
844 std::vector<BatchSeq>& seqs,
845 const std::vector<std::vector<llama_token>>& toks,
846 std::size_t shared);
848 void run_batch_gen_loop(std::vector<BatchSeq>& seqs, int max_steps,
849 std::atomic<bool>& cancel);
851 void sample_batch_active(std::vector<BatchSeq>& seqs);
853 std::vector<GenerationResult> build_batch_results(
854 std::vector<BatchSeq>& seqs);
856 void release_temp_seqs(std::vector<BatchSeq>& seqs);
857
864 bool run_prefill(const std::vector<llama_token>& tokens);
865
875 std::string step_token(
876 Sampler& sampler,
877 std::string& generated,
878 std::function<void(std::string_view)>& on_token,
879 const std::vector<std::string>& stop);
880
898 std::unique_ptr<Sampler> create_sampler(
899 const GenerationParams& params) const;
900
907 static std::string extract_system_prompt(
908 const std::vector<Message>& messages);
909
920 const std::vector<llama_token>& tokens,
921 const std::string& system_prompt,
922 const std::vector<Message>& messages,
923 const GenerationParams& params);
924
935 bool prefill_dispatch(
936 const std::vector<llama_token>& tokens,
937 const std::string& system_prompt,
938 const std::vector<Message>& messages,
939 const GenerationParams& params);
940
953 bool try_warm_reuse(const std::vector<llama_token>& tokens);
954
966
975 const std::vector<llama_token>& tokens, int start_offset);
976
985 const CacheEntry* cached,
986 const std::vector<llama_token>& tokens);
987
997 const std::vector<llama_token>& tokens,
998 int prefix_tokens,
999 const CacheKey& key);
1000
1007 void save_prefix_to_cache(const CacheKey& key, int prefix_tokens);
1008
1017 const std::vector<Message>& messages,
1018 const GenerationParams& params);
1019
1020 /* ── Evaluation helpers (v1.9.10) ───────────────────── */
1021
1027 llama_seq_id allocate_temp_seq_id();
1028
1034 void release_temp_seq_id(llama_seq_id seq_id);
1035
1048 static float extract_token_logprob(
1049 const float* logits,
1050 int32_t next_token,
1051 int n_vocab);
1052
1053 std::mutex seq_id_mutex_;
1054 std::vector<llama_seq_id> free_seq_ids_;
1059 llama_seq_id next_temp_seq_id_ = 1;
1060
1061 /* ── Architecture detection (v1.9.13) ──────────────── */
1062
1068 bool is_recurrent_ = false;
1069 bool is_hybrid_ = false;
1070
1076 bool is_recurrent() const;
1077
1078 /* ── Vision / multimodal (v1.9.11 Phases 5–7 + v2.1.8) ── */
1079
1087 ::mtmd_context* mtmd_ctx_ = nullptr;
1088
1091 bool has_vision_ = false;
1092
1113 const std::vector<Message>& messages,
1114 const GenerationParams& params,
1115 std::function<void(std::string_view token)> on_token,
1116 std::atomic<bool>* cancel);
1117
1124
1135 bool load_gpu_model();
1136
1148
1163 bool setup_mtp_draft(const std::string& head_path, int n_max);
1164
1174 bool build_mtp_head(const std::string& head_path);
1175
1184 void teardown_mtp_draft();
1185
1193 void reload_model_cpu_only();
1194
1205 const GenerationParams& params,
1206 const std::function<void(std::string_view)>& on_token,
1207 const std::string& head_path, int n_max);
1208
1219 const std::string& prompt,
1220 const std::vector<::mtmd_bitmap*>& bitmaps,
1221 std::string& err_msg);
1222
1238 const GenerationParams& params,
1239 std::function<void(std::string_view token)> on_token,
1240 std::atomic<bool>* cancel,
1241 const std::chrono::steady_clock::time_point& t0);
1242
1249 const std::vector<Message>& messages,
1250 const GenerationParams& params);
1251
1265 const std::vector<Message>& messages,
1266 const GenerationParams& params,
1267 std::atomic<bool>& cancel);
1268
1275 const std::vector<Message>& messages,
1276 const GenerationParams& params,
1277 std::function<void(std::string_view token)> on_token,
1278 std::atomic<bool>& cancel);
1279};
1280
1281} // 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.
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.
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.
std::string last_parser_
Captured serialized PEG arena.
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.
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:35
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:302
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:148
Prompt caching configuration.
Definition config.h:266
Abstract Tokenizer seam for backend testability (v2.3.10).