Generative backends

A backend answers the base prompt and every coalition prompt; the rest of a run is the same for all. Each implements GenerativeBackend; backend.kind picks one.

Built-in backends

kind

Extra

Use when

mock

(core)

Tests, CI and offline demos; no model involved

mock_audio

(core)

Audio runs in tests and demos (Audio input)

mock_image

[image]

Image runs in tests and demos (Image input)

replay

(core)

Answers from run archives you already paid for

api

[api]

OpenAI-compatible HTTP servers (OpenAI, vLLM, LM Studio’s server mode, proxies)

lmstudio

[lmstudio]

Local models through the LM Studio SDK, with automatic download

transformers

[transformers]

Hugging Face models in-process, with prefix-cache reuse; audio and vision models take audio and image parts

Top-level backend keys apply to every backend (Configuration); backend-specific keys go under backend.options, validated by that backend.

Speakers and logprobs

Chat templates have no speaker slot, so a message with a speaker is sent as "<speaker>: <text>" under its role. A message emptied by delete is sent empty, without the name.

self_logprob (Using value functions) needs each generated token’s log probability:

kind

Token logprobs

transformers

Always: log-softmax of the raw logits at each generated token, end-of-sequence included, with or without the KV cache

api

Requests "logprobs": true and reads choices[0].logprobs.content[*].logprob (OpenAI, LM Studio’s /v1); None when the server omits them

lmstudio

None: the SDK returns no logprobs; use api with LM Studio’s server

mock, mock_audio

None

Teacher-forced value functions (tf_logprob, tf_jsd, contrastive) need SupportsTeacherForcing: transformers (one forward pass per continuation) and mock (hash-derived distributions). Chat servers return no prompt logprobs, so api and lmstudio raise ConfigError before generating.

Mock

MockBackend returns a hash of the rendered prompt and model id: fast and deterministic, so guides and tests use it. Its text means nothing, so attributions test the plumbing, not a model.

backend:
  kind: mock
  model_id: stub

Replay

ReplayBackend answers coalitions from run archives, so any estimator, budget, seed or value function runs on a table you already paid for. Reuse the archived run’s config and change only those settings: rows are found by coalition key (input, players, absence policy, model id, generation settings). A coalition no archive holds raises ReplayMissError unless fallback names a live backend. Teacher-forced scores come from the archive too.

backend:
  kind: replay
  model_id: stub
  options:
    archives: [runs/exact-table]
    fallback: {kind: mock, model_id: stub}

Worked run: Replay archived coalitions and read the cost of a run.

HTTP API

ApiBackend posts to {api_host}/chat/completions. At temperature: 0.0 it caches up to 1024 responses by request body: identical coalition prompts cost one call. It opens at most explanation.max_inflight connections.

backend:
  kind: api
  model_id: gpt-4o-mini
  api_host: https://api.openai.com/v1
  timeout_s: 120
  max_retries: 3

generation:
  temperature: 0.0

timeout_s bounds each request. Timeouts, refused connections and HTTP 408, 429, 500, 502, 503 and 504 are retried up to max_retries times, backing off from 0.5 s, doubling to at most 8 s (or the server’s Retry-After). Other error statuses, non-JSON responses and exhausted retries raise BackendUnavailableError. CI tests mock the HTTP transport.

LM Studio

LmStudioBackend drives a running LM Studio through its SDK. model_id is matched against downloaded models exactly (after normalization), then as prefix of the last / segment, then as substring. Several matches at one stage raise BackendUnavailableError listing them. With no match and auto_download on, it searches the hub (hub_search or model_id) and downloads the quantization variant. The MLX runtime takes no concurrent requests per model, so serialize_generate (default on) runs one generate at a time. Connection failures (OSError, SDK websocket errors) are retried once; ValueError and TypeError propagate.

backend:
  kind: lmstudio
  model_id: qwen2-500m-instruct
  options:
    quantization: Q4_K_M
    auto_download: true
    serialize_generate: true

Key

Type

Default

Meaning

backend.options.hub_search

str | null

null

Repository search term used to download the model; defaults to model_id.

backend.options.quantization

str

"Q4_K_M"

GGUF quantization to download when the model is not already local.

backend.options.auto_download

bool

true

Download missing models through the LM Studio repository API.

backend.options.serialize_generate

bool

true

Serialize generate calls (needed for MLX models in LM Studio).

backend.options.audio

"refuse" | "transcript"

"refuse"

What to do with audio parts, which the LM Studio SDK cannot send. refuse raises ValueError; transcript sends the text parts only.

Tests needing LM Studio with qwen2-500m-instruct are marked lms; make check skips them:

uv run pytest -m lms tests/

Hugging Face transformers

TransformersTextBackend loads model_id on first use (AutoModelForCausalLM; audio models: Audio input) on CUDA, Apple MPS or CPU; it needs transformers>=4.56. backend.options:

  • dtype: auto (default) picks bfloat16 where supported, else float16 on accelerators and float32 on CPU; float32, float16, bfloat16 force one.

  • revision: Hub revision; a commit hash makes runs reproducible.

  • batch_size (default 1) and batch_wait_ms (default 5): below.

Prefix cache

With explanation.kv_cache.enabled (off by default) the backend keeps the key/value states of up to kv_cache.max_entries prompt prefixes (all prompt tokens but the last). A coalition prompt copies the longest match, crops it to the shared prefix (DynamicCache.crop), computes the missing tokens and caches the result, so order does not matter. metrics.kv_cache_hits and kv_cache_reused_tokens count reuse. In float32 greedy outputs match with the cache on and off. In float16 and bfloat16 the cached prefix rounds differently, so a near-tied token can flip; the backend warns once.

The cache pays only where prefill is slow. On an A100 40 GB with Qwen2.5-3B-Instruct in float16, an exact run over six messages took 1.5 times longer with it: copying the state costs more than recomputing a short prefix. Output embeddings are computed only for value functions that need them (embedding_cosine with encoder: model_states).

Batching

batch_size above 1 scores teacher-forced value functions and generates greedy answers (temperature: 0) in padded batches, collecting calls until that many wait or batch_wait_ms passes. Batches skip the prefix cache and model-state embeddings; audio prompts batch too. The scheduler runs at least batch_size coalitions at once.

Measured speed-ups

Setup

Result

One H100 PCIe, Qwen2-Audio-7B-Instruct

5.15 prompts/s at batch 32, 0.54 at batch 1 (9.5 times)

One A100 40 GB, Qwen2.5-3B-Instruct, bfloat16: scoring 128 prompts

7.2 s at batch 1, 0.91 s at 8, 0.46 s at 32 (15.6 times), 0.45 s at 64

Same, greedy 48-token answers for 64 prompts

26.1 s, 8.9 s, 4.1 s (6.3 times), 2.0 s (13 times)

Tiny CPU model, 128 prompts

2.7 times faster at 8, 3.6 times at 32

Padding moves float32 scores slightly. On Qwen2.5-3B-Instruct at batch 32, prompts of different lengths differ from one-prompt scores by up to \(4\times 10^{-4}\) for log probabilities up to 22.7 (about \(2\times 10^{-5}\) relative). Identical prompts differ by \(10^{-5}\); a repeated one-prompt run not at all. All 256 coalitions of eight words gave the same greedy text on the tiny model.

The tiny random model loads in seconds; gpu-marked tests use it:

backend:
  kind: transformers
  model_id: hf-internal-testing/tiny-random-gpt2
  options:
    dtype: auto

generation:
  max_new_tokens: 8

explanation:
  max_inflight: 1
  kv_cache:
    enabled: true
uv run pytest -m gpu tests/

Environment variables

Variable

Effect

MLLM_SHAP_API_KEY

Bearer token the api backend sends to any host; wins over OPENAI_API_KEY

OPENAI_API_KEY

Sent only when MLLM_SHAP_API_KEY is unset and backend.api_host is api.openai.com, so an OpenAI key never reaches another server

MLLM_SHAP_LOGGING_CONFIG

TOML file whose [tool.logging] section configures the mllm_shap loggers

Example configurations

config/ holds one runnable file per backend, each opening with what it needs: dev_api.yaml, dev_lmstudio.yaml, dev_transformers.yaml. Extras and writing your own backend: Extending mllm-shap. One prompt on three backends: End-to-end text explainability on real backends.