123 std::unique_ptr<SamplerFactory> factory);
200 const std::string& text)
const override;
288 return ctx_ !=
nullptr
289 ?
static_cast<int>(llama_memory_seq_pos_max(llama_get_memory(
ctx_), 0))
343 const std::vector<Message>& messages,
445 const std::vector<Message>& messages,
453 const std::vector<Message>& messages,
455 std::atomic<bool>& cancel)
override;
458 const std::vector<Message>& messages,
460 std::function<
void(std::string_view token)> on_token,
461 std::atomic<bool>& cancel)
override;
477 const std::vector<Message>& messages,
479 std::function<
void(std::string_view token)> on_token,
480 std::atomic<bool>& cancel)
override;
495 const std::vector<std::vector<Message>>& requests,
496 const std::vector<GenerationParams>& params,
497 std::atomic<bool>& cancel)
override;
534 const std::vector<Message>& messages,
536 std::function<
void(std::string_view token)> on_token,
537 std::atomic<bool>& cancel,
540 const std::string& draft_path);
562 const std::vector<Message>& messages,
564 std::function<
void(std::string_view token)> on_token,
565 std::atomic<bool>& cancel,
566 const std::string& head_path,
579 const std::string& prompt,
588 int n_tokens)
override;
614 std::vector<uint8_t>& buffer)
const override;
629 const std::vector<uint8_t>& buffer)
override;
707 const std::string& text,
bool add_special)
const;
715 std::string
detokenize(llama_token token)
const;
725 const std::vector<Message>& messages,
744 const std::vector<Message>& messages,
754 const std::vector<Message>& messages)
const;
771 const std::vector<llama_token>&
tokens,
773 std::function<
void(std::string_view)> on_token,
774 std::atomic<bool>* cancel);
795 std::function<
void(std::string_view)> on_token,
796 std::atomic<bool>* cancel);
815 std::vector<llama_token>
out;
830 const std::vector<std::vector<llama_token>>& toks,
831 const std::vector<GenerationParams>& params,
833 std::atomic<bool>& cancel);
837 const std::vector<GenerationParams>& params);
840 const std::vector<llama_token>& seq0,
844 std::vector<BatchSeq>& seqs,
845 const std::vector<std::vector<llama_token>>& toks,
849 std::atomic<bool>& cancel);
854 std::vector<BatchSeq>& seqs);
877 std::string& generated,
878 std::function<
void(std::string_view)>& on_token,
879 const std::vector<std::string>& stop);
908 const std::vector<Message>& messages);
920 const std::vector<llama_token>&
tokens,
921 const std::string& system_prompt,
922 const std::vector<Message>& messages,
936 const std::vector<llama_token>&
tokens,
937 const std::string& system_prompt,
938 const std::vector<Message>& messages,
975 const std::vector<llama_token>&
tokens,
int start_offset);
986 const std::vector<llama_token>&
tokens);
997 const std::vector<llama_token>&
tokens,
1017 const std::vector<Message>& messages,
1049 const float* logits,
1113 const std::vector<Message>& messages,
1115 std::function<
void(std::string_view token)> on_token,
1116 std::atomic<bool>* cancel);
1206 const std::function<
void(std::string_view)>& on_token,
1207 const std::string& head_path,
int n_max);
1219 const std::string& prompt,
1220 const std::vector<::mtmd_bitmap*>& bitmaps,
1221 std::string& err_msg);
1239 std::function<
void(std::string_view token)> on_token,
1240 std::atomic<bool>* cancel,
1241 const std::chrono::steady_clock::time_point& t0);
1249 const std::vector<Message>& messages,
1265 const std::vector<Message>& messages,
1267 std::atomic<bool>& cancel);
1275 const std::vector<Message>& messages,
1277 std::function<
void(std::string_view token)> on_token,
1278 std::atomic<bool>& cancel);
Concrete base class for inference backends (80% logic).
const ModelConfig & config() const
Stored model config.
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 ¶ms) 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 ¶ms, 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 ¶ms)
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 > ¶ms, 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 ¶ms) 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 ¶ms)
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 ¶ms) 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 ¶ms)
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 ¶ms, 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 ¶ms, std::function< void(std::string_view token)> on_token, std::atomic< bool > *cancel, const std::chrono::steady_clock::time_point &t0)
Sample tokens until stop / max_tokens / cancel.
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 ¶ms, const std::function< void(std::string_view)> &on_token, const std::string &head_path, int n_max)
Validate MTP run preconditions (gh#108, fail-fast/fail-loud).
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 ¶ms, 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 ¶ms)
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 ¶ms)
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 ¶ms) 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 ¶ms, 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 ¶ms)
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 ¶ms) 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 ¶ms, 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 ¶ms, std::function< void(std::string_view token)> on_token, std::atomic< bool > &cancel, const std::string &head_path, int n_max)
Speculative generation via a target-owned MTP head (gh#106).
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 > ¶ms, 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 > ¶ms)
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 ¶ms, 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 ¶ms, 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.
Pure-virtual per-generation sampler used by the decode loop.
entropic_error_t
Error codes returned by all C API functions.
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.
Result of a single generation call.
Per-sequence state for the gh#98 multi-seq batched decode.
int pos
Next KV position to write.
std::string finish
Finish reason.
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.
bool active
Still generating?
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.
Prompt caching configuration.
Abstract Tokenizer seam for backend testability (v2.3.10).