backends

Responsibility

  • Generate assistant text for a rendered snapshot, with the audio and images the model takes, returning a GenerationRecord; optional prefix reuse and embeddings.

Public surface

  • Backends read context.config.backend; generate(snapshot, generation).

  • MockBackend (mock): deterministic text hashed from the snapshot id, each message_chat_text, model id and generation; at most 16 four-character tokens. score_continuations draws an 8-token law per position from the prompt hash.

  • MockAudioBackend (mock_audio): echoes words, then a token per voiced run of each AudioPart (amplitude above SILENCE 0.01, runs split by MIN_GAP_S 0.01 s) (decision). 16-bit WAV decodes with wave, other formats with decode_audio. MockImageBackend (mock_image): a token per square of one saturated colour.

  • ReplayBackend (replay): serves archived rows by coalition key; a miss raises ReplayMissError unless fallback serves it.

  • ApiBackend (api): OpenAI-compatible /chat/completions over httpx, with Timeout(backend.timeout_s) and max_inflight connections.

    • Retries RETRYABLE_STATUS (408, 429, 5xx gateway codes) and transport errors up to backend.max_retries with backoff, honouring Retry-After up to timeout_s. Non-JSON responses raise BackendUnavailableError.

    • snapshot_to_api_messages: a message with media sends text, base64 WAV input_audio and data-URI image_url parts.

    • Sends "logprobs": true; extract_logprobs reads choices[0].logprobs.content[*].logprob, else None; an empty reply gets () (LM Studio sends null), which self_logprob scores 0. returns_logprobs is true (SupportsLogprobs).

    • Caches temperature-0 records in an LRU of RESPONSE_CACHE_SIZE (1024).

    • backend.api_host is required (ConfigError without it; no environment or localhost fallback).

    • Key: MLLM_SHAP_API_KEY, or OPENAI_API_KEY for api.openai.com.

  • LmStudioBackend (lmstudio): local LM Studio server through the lmstudio SDK.

    • LmStudioOptions (hub_search, quantization, auto_download, serialize_generate, audio) come from backend.options; unknown keys raise ConfigError.

    • audio: refuse (default) raises ValueError on audio; transcript sends the text parts and warns once. Images upload once per hash (prepare_image) and attach to their user message.

    • match_downloaded_model_key matches exactly, by last-segment prefix, then by substring; ambiguity raises, as does pick_search_result without a matching hub hit.

    • Retries once on transient connection errors (_is_transient); no logprobs.

  • TransformersTextBackend (transformers): Hugging Face model on CUDA (Compute Unified Device Architecture), MPS (Metal Performance Shaders) or CPU.

    • TransformersOptions: dtype (auto: bfloat16 where supported, else float16, float32 on CPU), revision, model_class, processor_kwargs.

    • A config in MODEL_FOR_CAUSAL_LM_MAPPING loads as text; any other (or model_class) loads its class with AutoProcessor (decision).

    • processor.processor_inputs sends images, and audio when the chat template mentions it, as template parts (base64 WAV for mistral-common); else one audio_token per clip. Empty clips drop; media batch by collate_inputs. Omni models run through their thinker, without prefix cache.

    • One model lock covers encoding, generation, decoding and scoring.

    • With the key-value (KV) cache enabled (SupportsKvCache), _attach_prefix_cache copies and crops the longest cached prefix and runs the uncovered tokens; kv_cache_hits and kv_cache_reused_tokens count the reuse.

    • Embeddings need generation.compute_embeddings.

    • generate returns raw logits (output_logits); _token_logprobs takes their log-softmax at each generated token, end-of-sequence included. returns_logprobs is true. score_continuations: one forward pass over prompt plus continuation (audio prompts with features); optional top-k next tokens.

  • backends/_chat.py: snapshot_has_audio, snapshot_has_image, snapshot_has_media, chat_role, message_chat_text ("<speaker>: <text>" unless the text is empty; speaker rendering), message_parts (per content_order), snapshot_to_chat_messages.

Data flow

  • In: rendered ConversationSnapshot and GenerationConfig from the pipeline orchestrator; PluginContext at construction.

  • Out: GenerationRecord built with value.generation_records.generation_record_from_text(text) (value), with model embeddings when requested; other backends have none, so their records equal those reanalyze builds.

  • Optional dependencies (httpx, lmstudio, torch, torchaudio, transformers) are imported lazily; a missing extra raises BackendUnavailableError (core).

Invariants

  • Media prompts skip the prefix cache; a text model refuses media and lmstudio audio (unless audio: transcript) with ValueError; mock hashes text and the snapshot id only.

  • mock_audio: a run’s token depends on its samples only, so silencing or cutting another run leaves it unchanged.

  • In float32, greedy transformers outputs are identical with the prefix cache on and off, and their logprobs agree within 1e-4; in float16 and bfloat16 they agree up to rounding, and the backend warns once (decision). No prompt token is processed twice.

  • An injected backend is reused across calls and closed by the runner; otherwise one is built and closed per explain().

Known issues

  • None open. Fixed: C06, C08, C15, D02, D04, D05, D07 (Fixed issues).

Tests