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¶
|
Extra |
Use when |
|---|---|---|
|
(core) |
Tests, CI and offline demos; no model involved |
|
(core) |
Audio runs in tests and demos (Audio input) |
|
|
Image runs in tests and demos (Image input) |
|
(core) |
Answers from run archives you already paid for |
|
|
OpenAI-compatible HTTP servers (OpenAI, vLLM, LM Studio’s server mode, proxies) |
|
|
Local models through the LM Studio SDK, with automatic download |
|
|
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:
|
Token logprobs |
|---|---|
|
Always: log-softmax of the raw logits at each generated token, end-of-sequence included, with or without the KV cache |
|
Requests |
|
None: the SDK returns no logprobs; use |
|
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 |
|---|---|---|---|
|
|
|
Repository search term used to download the model; defaults to |
|
|
|
GGUF quantization to download when the model is not already local. |
|
|
|
Download missing models through the LM Studio repository API. |
|
|
|
Serialize |
|
|
|
What to do with audio parts, which the LM Studio SDK cannot send. |
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) picksbfloat16where supported, elsefloat16on accelerators andfloat32on CPU;float32,float16,bfloat16force one.revision: Hub revision; a commit hash makes runs reproducible.batch_size(default 1) andbatch_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.
Setup |
Result |
|---|---|
One H100 PCIe, |
5.15 prompts/s at batch 32, 0.54 at batch 1 (9.5 times) |
One A100 40 GB, |
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 |
|---|---|
|
Bearer token the |
|
Sent only when |
|
TOML file whose |
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.