include/entropic/inference/backend.h

← API

include/entropic/inference/backend.h

entropic::InferenceBackend

Concrete base class for inference backends (80% logic).

Derived by entropic::LlamaCppBackend.

virtual entropic::InferenceBackend::~InferenceBackend()=default

bool entropic::InferenceBackend::load(const ModelConfig &config)

Load model into CPU RAM (COLD → WARM).

Acquires transition_mutex_. No-op if already WARM/ACTIVE.

Parameters
  • config — Model configuration (path, context length, GPU layers, etc.).
  • config — Validated model config.
Returns
  • true on success.
  • true on success, false on failure.

bool entropic::InferenceBackend::activate()

Promote to GPU (WARM → ACTIVE).

Loads first if COLD.

Returns
  • true on success.
  • true on success, false on failure.

void entropic::InferenceBackend::deactivate()

Release GPU layers (ACTIVE → WARM).

No-op if not ACTIVE. No-op if not ACTIVE.

void entropic::InferenceBackend::unload()

Full unload (→ COLD).

Releases all RAM + VRAM. Idempotent. The base half of teardown: fires ON_MODEL_UNLOAD, delegates the resource release to do_unload(), and lands the state machine in COLD. Safe to call on a backend whose load failed, and safe to call twice.

bool entropic::InferenceBackend::load_and_activate(const ModelConfig &config)

Bring a model to ACTIVE in as few file reads as possible.

Reach ACTIVE in as few whole-file reads as possible (gh#148). From COLD this is ONE whole-file read, straight into the residency the config asks for (gh#148). It used to be load() then activate(): the first read placed every layer on the CPU with n_gpu_layers = 0, and the second immediately threw that model away and read the whole file again with the configured split. One cold activation, two whole-file reads of a file that can be 13 GB. From WARM it promotes, which IS still a reload — llama.cpp ties offloading to the model load (design decision #19), so a WARM model cannot re-place its layers without being read again. That path is what keep_warm buys and is deliberately unchanged. From COLD: ONE read, straight into the residency config asks for. Before v2.13.0 this was load() + activate(), which read the whole file with n_gpu_layers = 0, discarded that model, and read the whole file again with the configured split — two reads of a file that can be 13 GB, for one cold activation. From WARM: promotion, which IS still a reload (design decision #19 — llama.cpp ties offloading to the model load). That is the path keep_warm buys and it is deliberately unchanged. Holds transition_mutex_ across the whole decision, so the state cannot change between choosing a path and taking it.

Parameters
  • config — Model configuration (path, context length, gpu_layers).
  • config — Model config.
Returns
  • true when the backend is ACTIVE afterwards.
  • true when ACTIVE afterwards.

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

Generate a complete response.

Requires ACTIVE state.

Parameters
  • messages — Conversation history.
  • params — Generation parameters.
Returns
  • GenerationResult with content, token count, timing. Returns error result if not ACTIVE.
  • GenerationResult (error result if not ACTIVE).

GenerationResult entropic::InferenceBackend::generate(const std::vector< Message > &messages, const GenerationParams &params, std::atomic< bool > &cancel)

Generate a complete response with cancellation support.

Generate with cancel support. gh#81 (v2.4.2): the no-cancel generate overload above runs to max_tokens or natural stop with no path to honor a mid-decode interrupt. The engine's loop-top interrupt check can then take a full generation cycle to fire — observed ~60s on qwen3_6_a3b at max_tokens=400. This overload mirrors generate_streaming's contract: the backend polls cancel per token (latency: one token) and returns a result with finish_reason="cancelled" and error_code=ENTROPIC_ERROR_CANCELLED when cancellation lands. Requires ACTIVE state. (gh#81, v2.4.2)

Parameters
  • messages — Conversation history.
  • params — Generation parameters.
  • cancel — Atomic flag — when true, subclass must stop decoding.
  • cancel — Atomic cancel flag forwarded to the subclass decode loop.
Returns
  • GenerationResult.
  • GenerationResult with generation_time_ms stamped; an ENTROPIC_ERROR_INVALID_STATE result when the backend is not ACTIVE.

GenerationResult entropic::InferenceBackend::generate_streaming(const std::vector< Message > &messages, const GenerationParams &params, std::function< void(std::string_view token)> on_token, std::atomic< bool > &cancel)

Generate with per-token streaming callback.

Streaming generation. Requires ACTIVE state.

Parameters
  • messages — Conversation history.
  • params — Generation parameters.
  • on_token — Called for each token (valid only during callback).
  • cancel — Set to true to abort. Latency: one token.
  • on_token — Per-token callback.
  • cancel — Atomic cancel flag forwarded to the subclass decode loop.
Returns
  • GenerationResult with final content and timing.
  • GenerationResult with generation_time_ms stamped; an ENTROPIC_ERROR_INVALID_STATE result when the backend is not ACTIVE.

GenerationResult entropic::InferenceBackend::generate_speculative(const std::vector< Message > &messages, const GenerationParams &params, std::function< void(std::string_view token)> on_token, std::atomic< bool > &cancel)

Generate via the speculative-decoding kernel (v2.1.11).

Public entry point for speculative-decoding streaming. Public wrapper around do_generate_speculative. Validates ACTIVE state, then delegates to the subclass override. Backends that do not implement the kernel return ENTROPIC_ERROR_NOT_SUPPORTED — the orchestrator falls back to generate_streaming in that case. Mirrors generate_streaming: validates ACTIVE state then delegates to the subclass override. Stamps generation_time_ms. Returns the subclass's NOT_SUPPORTED on stub backends — caller falls back to generate_streaming.

Parameters
  • messages — Conversation history.
  • params — Generation parameters.
  • on_token — Per-accepted-token callback.
  • cancel — Cancellation flag.
Returns
GenerationResult.

GenerationResult entropic::InferenceBackend::complete(const std::string &prompt, const GenerationParams &params)

Raw text completion without chat template.

Raw text completion. Requires ACTIVE state.

Parameters
  • prompt — Raw prompt string (no chat formatting).
  • params — Generation parameters.
  • prompt — Raw prompt string.
Returns
GenerationResult.

LogprobResult entropic::InferenceBackend::evaluate_logprobs(const int32_t *tokens, int n_tokens)

Evaluate per-token log-probabilities for a token sequence.

Evaluate per-token log-probabilities. Requires ACTIVE state. The 80% logic: state check, input validation, eval_mutex_, perplexity computation from raw logprobs, and logging. Delegates to do_evaluate_logprobs() for backend-specific batch/decode work.

Parameters
  • tokens — Array of token IDs to evaluate.
  • n_tokens — Number of tokens in the array (minimum 2).
  • tokens — Array of token IDs.
  • n_tokens — Number of tokens (minimum 2).
Returns
  • LogprobResult with per-token logprobs and perplexity.
  • LogprobResult whose perplexity equals exp(-mean(logprobs)) and total_logprob the sum; deterministic across repeated calls. Rejected for fewer than 2 tokens or a non-ACTIVE model.
Throws
  • std::runtime_error — if model is not ACTIVE.
  • std::runtime_error — if n_tokens < 2.
  • std::runtime_error — on state/input errors.

float entropic::InferenceBackend::compute_perplexity(const int32_t *tokens, int n_tokens)

Compute perplexity for a token sequence.

Convenience method — calls evaluate_logprobs() and returns only the perplexity value. Convenience wrapper — calls evaluate_logprobs() and returns only the perplexity value.

Parameters
  • tokens — Array of token IDs.
  • n_tokens — Number of tokens (minimum 2).
Returns
Perplexity as exp(-mean(logprobs)).

ModelState entropic::InferenceBackend::state() const

Current lifecycle state (lock-free read).

Returns
Current ModelState value.

bool entropic::InferenceBackend::is_active() const

True when state is ACTIVE.

Returns
true if state is ACTIVE, false otherwise.

bool entropic::InferenceBackend::is_loaded() const

True when state is WARM or ACTIVE.

Returns
true if state is WARM or ACTIVE, false if COLD.

int entropic::InferenceBackend::count_tokens(const std::string &text) const

Count tokens using model's tokenizer.

Count tokens. Exact if loaded, estimate if COLD.

Parameters
  • text — Text to tokenize.
Returns
  • Exact count if loaded, len/4 estimate if COLD.
  • Token count.

virtual std::vector< int32_t > entropic::InferenceBackend::tokenize_text(const std::string &text) const

Tokenize text to token IDs.

Parameters
  • text — Input text.
Returns
Token ID vector (empty if COLD or error).

int entropic::InferenceBackend::context_length() const

Model's context window size.

Returns
Maximum context length in tokens.

virtual void entropic::InferenceBackend::clear_prompt_cache()

Invalidate any backend-owned prompt/KV caches.

Called when identity or prompt-prefix inputs change so stale cached prefixes are never served against the new system prompt. Default is a no-op for backends with no cache. (P1-7, 2.0.6-rc16)

virtual std::string entropic::InferenceBackend::tool_call_close_marker() const

The tool-call CLOSE marker for the active chat format (gh#103).

Returns the string that terminates a single tool call in the model's native format (e.g. "</tool_call>"), or "" when there is no reliable marker (no tools staged / content-only format). The orchestrator appends it to GenerationParams.stop for tiers in "sequential" tool_call_mode so the decode loop halts at the FIRST closed tool call (one tool/turn). Default "" → no stop injected (batch behavior). Backends that own a native tool-call format override this. (gh#103)

Returns
Close marker, or empty if none applies.

const ModelConfig & entropic::InferenceBackend::config() const

Stored model config.

Returns
Const reference to the ModelConfig used for this backend.

bool entropic::InferenceBackend::supports(BackendCapability cap) const

Query whether this backend supports a capability.

Query backend capability. Base class returns false for all capabilities. Subclasses override do_supports() to declare their capabilities. Lock-free — no state transitions involved. Delegates to do_supports().

Parameters
  • cap — Capability to query.
Returns
  • true if supported.
  • true if supported; the base default declares nothing, so an unimplemented backend under-promises rather than over-promises.

std::vector< BackendCapability > entropic::InferenceBackend::capabilities() const

Get all supported capabilities as a vector.

Get all supported capabilities. Convenience method. Iterates BackendCapability enum, calls supports() on each. Iteration is bounded by the _COUNT sentinel rather than a hardcoded length, so a capability appended to the enum is enumerated here without a second edit — the sentinel is what makes the sweep exhaustive.

Returns
  • Vector of capabilities this backend supports.
  • Vector of every capability index below _COUNT for which supports() is true; the sentinel is never included.

BackendInfo entropic::InferenceBackend::info() const

Get backend metadata.

Base class returns a default-constructed BackendInfo with name from do_backend_name(). Subclasses override do_info() to populate architecture, quantization, memory usage, etc. Delegates to do_info().

Returns
  • BackendInfo populated from model metadata after load(). Returns default (empty) info with name only if COLD.
  • BackendInfo with at least name populated; the remaining fields come from model metadata read after load.

virtual std::string entropic::InferenceBackend::active_tool_grammar() const

The tool-call GBNF the last render derived, if any (gh#154).

The second grammar source (the first being GenerationParams::grammar). It never appears on the params, so a caller holding only the params cannot tell whether the decode was constrained — the orchestrator asks the backend instead, and builds GenerationResult::grammar from both. Base returns "" — a backend that stages no tools has no such grammar, which is the honest answer rather than a stub.

Returns
Render-derived tool-call GBNF, or "" when none is staged.

bool entropic::InferenceBackend::save_state(int seq_id, std::vector< uint8_t > &buffer) const

Save model state to buffer.

Save model state. For transformers: saves KV cache state for the sequence. For recurrent: saves hidden state. Requires ACTIVE.

Parameters
  • seq_id — Sequence identifier (0 for single-sequence backends).
  • buffer — Output buffer. Caller owns the returned data.
  • seq_id — Sequence identifier.
  • buffer — Caller-owned output buffer.
Returns
  • true on success. false if not ACTIVE or unsupported.
  • true on success; false when the backend is not ACTIVE or does not support the operation.

bool entropic::InferenceBackend::restore_state(int seq_id, const std::vector< uint8_t > &buffer)

Restore model state from buffer.

Restore model state. Requires ACTIVE.

Parameters
  • seq_id — Sequence identifier to restore into.
  • buffer — Previously saved state buffer.
  • seq_id — Sequence identifier.
  • buffer — Previously saved state.
Returns
  • true on success. false if incompatible or unsupported.
  • true on success; false when the backend is not ACTIVE or does not support the operation.

bool entropic::InferenceBackend::clear_state(int seq_id=-1)

Clear/reset model state for a sequence.

Clear model state. For transformers: clears KV cache. For recurrent: resets hidden state to initial values. Requires WARM or ACTIVE.

Parameters
  • seq_id — Sequence identifier (-1 for all sequences).
  • seq_id — Sequence ID, or -1 to clear every sequence.
Returns
  • true on success.
  • true on success; false when the model is COLD or the backend does not support the operation.

GenerationResult entropic::InferenceBackend::generate_seq(int seq_id, const std::vector< Message > &messages, const GenerationParams &params)

Generate with explicit sequence ID.

Default: ignores seq_id, delegates to generate(). Requires ACTIVE.

Parameters
  • seq_id — Sequence identifier for multi-sequence backends.
  • messages — Conversation history.
  • params — Generation parameters.
  • seq_id — Sequence identifier.
Returns
GenerationResult with seq_id set.

GenerationResult entropic::InferenceBackend::generate_streaming_seq(int seq_id, const std::vector< Message > &messages, const GenerationParams &params, std::function< void(std::string_view token)> on_token, std::atomic< bool > &cancel)

Streaming generation with explicit sequence ID.

Streaming generation with sequence ID. Requires ACTIVE.

Parameters
  • seq_id — Sequence identifier.
  • messages — Conversation history.
  • params — Generation parameters.
  • on_token — Per-token callback.
  • cancel — Cancellation flag.
Returns
GenerationResult with seq_id set.

std::vector< GenerationResult > entropic::InferenceBackend::generate_batch(const std::vector< std::vector< Message > > &requests, const std::vector< GenerationParams > &params, std::atomic< bool > &cancel)

Generate N independent same-prefix requests together.

Same-prefix batch generation. For traffic where N requests share a large verbatim prompt prefix and differ only in a short suffix (e.g. NPC agents per game tick): the shared prefix is prefilled once and fanned out to N sequences, then the suffixes + outputs are decoded in batched forward passes, each sampled under its own request's grammar. Requires ACTIVE state. Requires ACTIVE state. (gh#98, v2.8.0)

Parameters
  • requests — Per-request message lists (all sharing a prefix).
  • params — Per-request generation params (each may carry its grammar).
  • cancel — Cooperative cancel flag.
  • requests — Per-request message lists.
  • params — Per-request generation params.
  • cancel — Atomic cancel flag forwarded to the batch decode loop.
Returns
  • One GenerationResult per request, in input order.
  • One result per request (single error result if not ACTIVE).

virtual void entropic::InferenceBackend::forget_session_kv(const std::string &session_key)

Drop one session's resident KV and release its slot (gh#165).

Called when a session's conversation is REPLACED wholesale (entropic_session_context_set), so the restored history cannot decode against a prefix the conversation it replaced left in the cache. The session's next turn costs a cold prefill, which is exactly what an LRU-evicted session already costs. Default is a no-op: a backend with no per-session KV has nothing to forget, and every mock therefore needs no override (decision #32 — new methods carry a default implementation).

Parameters
  • session_key — Session whose KV to drop; "" is the default session.