Backends

Backend plugin implementations.

@domain backends @see [[knowledge/architecture/backends]]

Mock

Mock backend exports.

@domain backends @see [[knowledge/architecture/backends]] @tested-by [[tests/backends/test_mock.py]] @tested-by [[tests/backends/test_mock_audio.py]] @tested-by [[tests/backends/test_mock_image.py]]

Deterministic mock backend for CI-safe E2E tests.

@domain backends @see [[knowledge/architecture/backends]] @tested-by [[tests/backends/test_mock.py]]

class mllm_shap.backends.mock.backend.MockBackend(context: PluginContext | None = None, *, model_id: str = 'mock')[source]

Bases: object

Hash-based generative backend with no external model dependencies.

options_model

Accepts no explanation.plugin_options.

alias of PluginOptions

property model_id: str

Return the backend model identifier.

async generate(snapshot: ConversationSnapshot, generation: GenerationConfig) → GenerationRecord[source]

Return deterministic generation output for snapshot.

property cost_counters: CostCounters

Return the cumulative model work; words stand for tokens, time is zero.

property forces_continuations: bool

Always true; scores are deterministic functions of the prompt.

async score_continuations(snapshot: ConversationSnapshot, continuations: Sequence[str], top_k: int = 0) → list[ForcedScore][source]

Score continuations under a hash-derived next-token distribution.

Each continuation word is one of MOCK_VOCAB tokens; the distribution at every position depends on the prompt and the words before it, so different coalition prompts give different scores.

mllm_shap.backends.mock.backend.MOCK_VOCAB = 8

Size of the mock backend’s next-token vocabulary.

Deterministic mock backend that hears the voiced runs of audio parts.

@domain backends @see [[knowledge/architecture/backends]] @tested-by [[tests/backends/test_mock_audio.py]]

mllm_shap.backends.mock.audio.SILENCE = 0.01

Largest absolute amplitude (of full scale 1) that counts as silence.

mllm_shap.backends.mock.audio.MIN_GAP_S = 0.01

Shortest silence that separates two voiced runs; shorter dips (zero crossings) stay inside one run.

class mllm_shap.backends.mock.audio.MockAudioBackend(context: PluginContext | None = None, *, model_id: str = 'mock')[source]

Bases: MockBackend

Echo text words and answer one token per voiced run of every audio part.

A run’s token hashes its 16-bit samples, so silencing or cutting a run drops exactly its token and leaves the others unchanged. 16-bit PCM WAV decodes with the standard library; other formats need the audio extra.

async generate(snapshot: ConversationSnapshot, generation: GenerationConfig) → GenerationRecord[source]

Return the heard words of snapshot, at most max_new_tokens.

Replay from run archives

Deterministic mock backend that sees the coloured squares of images.

@domain backends @see [[knowledge/architecture/backends]] @tested-by [[tests/backends/test_mock_image.py]]

mllm_shap.backends.mock.image.MIN_SATURATION = 100

Smallest channel spread (max minus min, of 255) that makes a pixel coloured; white, black, grey and the mean fill of a mostly white image stay below it.

mllm_shap.backends.mock.image.MIN_PIXELS = 64

Pixels of one exact colour a square needs to be seen (an 8 by 8 patch).

class mllm_shap.backends.mock.image.MockImageBackend(context: PluginContext | None = None, *, model_id: str = 'mock')[source]

Bases: MockBackend

Echo text words and answer one token per visible coloured square of an image.

A square is every pixel of one exact saturated colour; it is seen while at least MIN_PIXELS of them remain. Painting a square’s cell with any fill drops exactly its token, so grid players over one square per cell have closed form Shapley values. Images need the image extra.

async generate(snapshot: ConversationSnapshot, generation: GenerationConfig) → GenerationRecord[source]

Return the seen words of snapshot, at most max_new_tokens.

Replay from run archives

Replay backend plugin.

@domain backends @see [[knowledge/architecture/backends]] @tested-by [[tests/backends/test_replay.py]]

Answer coalitions from run archives instead of a model.

Rows are looked up by coalition key, which fixes the snapshot, players, absence policy, model id and generation settings, so a replay run must use the config of the archived run apart from the estimator, budget, seed and value function. A coalition that is not archived raises ReplayMissError, unless a fallback backend is configured to compute it.

@domain backends @see [[knowledge/architecture/backends]] @tested-by [[tests/backends/test_replay.py]]

class mllm_shap.backends.replay.backend.ReplayOptions(*, archives: list[str], fallback: dict[str, object] | None = None)[source]

Bases: PluginOptions

Options of the replay backend.

archives: list[str]

Run archive folders to read; rows of earlier folders win on equal keys.

fallback: dict[str, object] | None

backend settings (kind, model_id, …) of a live backend that computes coalitions missing from the archives.

model_config = {'extra': 'forbid', 'frozen': True, 'strict': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class mllm_shap.backends.replay.backend.ReplayBackend(context: PluginContext)[source]

Bases: object

Serve archived coalition generations; compute misses with a fallback.

options_model

Accepts no explanation.plugin_options; settings are backend.options.

alias of PluginOptions

property model_id: str

Return the model id recorded in the archives.

property has_fallback: bool

Return whether missing coalitions are computed by a live backend.

archived_row(coalition_key: str) → CoalitionRecord | None[source]

Return the archived row of coalition_key, if any.

archived_base(snapshot_id: str) → tuple[str, CoalitionRecord | None] | None[source]

Return the archived base text and grand-coalition row of a snapshot.

async generate(snapshot: ConversationSnapshot, generation: GenerationConfig) → GenerationResult[source]

Delegate to the fallback; archived coalitions never reach this call.

property forces_continuations: bool

Always true; archived rows carry their teacher-forced scores.

async score_continuations(snapshot: ConversationSnapshot, continuations: Sequence[str], top_k: int = 0) → list[ForcedScore][source]

Delegate to a teacher-forcing fallback; archived rows are read directly.

async aclose() → None[source]

Close the fallback backend, if any.

OpenAI-compatible HTTP API

OpenAI-compatible HTTP API backend plugin.

@domain backends @see [[knowledge/architecture/backends]] @tested-by [[tests/backends/test_api.py]]

OpenAI-compatible HTTP generative backend.

@domain backends @see [[knowledge/architecture/backends]] @tested-by [[tests/backends/test_api.py]]

mllm_shap.backends.api.backend.RESPONSE_CACHE_SIZE = 1024

Maximum deterministic responses kept in memory per backend instance.

mllm_shap.backends.api.backend.RETRYABLE_STATUS = frozenset({408, 429, 500, 502, 503, 504})

HTTP status codes treated as transient and retried.

mllm_shap.backends.api.backend.MAX_RETRY_DELAY_S = 8.0

Upper bound of the exponential backoff between retries.

mllm_shap.backends.api.backend.OPENAI_API_HOST = 'api.openai.com'

The only host that receives OPENAI_API_KEY.

class mllm_shap.backends.api.backend.ApiBackend(context: PluginContext, transport: Any | None = None)[source]

Bases: object

Generate text through an OpenAI-compatible /chat/completions endpoint.

options_model

Accepts no explanation.plugin_options.

alias of PluginOptions

property model_id: str

Return the configured remote model identifier.

property returns_logprobs: bool

Always true; requests ask for logprobs, servers that omit them give None.

async generate(snapshot: ConversationSnapshot, generation: GenerationConfig) → GenerationRecord[source]

Generate assistant text for snapshot via the HTTP API.

async aclose() → None[source]

Close the underlying HTTP client.

Chat-completions request and response helpers.

@domain backends @see [[knowledge/architecture/backends]] @tested-by [[tests/backends/test_api.py]]

mllm_shap.backends.api.payload.snapshot_to_api_messages(snapshot: ConversationSnapshot, order: Literal['legacy', 'in_order'] = 'legacy') → list[dict[str, Any]][source]

Convert snapshot to chat messages with audio and image parts.

A message with media sends text parts, one base64 WAV part per AudioPart and one data-URI part per ImagePart in order (text first under legacy); non-WAV audio is re-encoded (audio extra), and images other than PNG or JPEG are re-encoded as PNG (image extra).

mllm_shap.backends.api.payload.build_chat_payload(model_id: str, messages: list[dict[str, Any]], generation: GenerationConfig) → dict[str, Any][source]

Build an OpenAI-style chat-completions JSON body that asks for logprobs.

mllm_shap.backends.api.payload.payload_cache_key(payload: dict[str, Any]) → str[source]

Return a stable SHA256 key for deterministic request deduplication.

mllm_shap.backends.api.payload.extract_message_content(data: dict[str, Any]) → str[source]

Parse assistant text from a chat-completions JSON response.

mllm_shap.backends.api.payload.extract_logprobs(data: dict[str, Any]) → tuple[float, ...] | None[source]

Return choices[0].logprobs.content[*].logprob, or None when absent.

Servers that ignore the logprobs request field (or send another shape) give None; the logprob value function then refuses the record.

LM Studio

LM Studio backend plugin.

@domain backends @see [[knowledge/architecture/backends]] @tested-by [[tests/backends/test_lmstudio.py]]

LM Studio generative backend.

@domain backends @see [[knowledge/architecture/backends]] @tested-by [[tests/backends/test_lmstudio.py]]

mllm_shap.backends.lmstudio.backend.IMAGE_HANDLES = 64

Uploaded image handles kept for reuse; masked coalitions upload new images, so only the recent ones (the unmasked image above all) come back.

class mllm_shap.backends.lmstudio.backend.LmStudioBackend(context: PluginContext)[source]

Bases: object

Generate text through a local LM Studio API server.

options_model

Accepts no explanation.plugin_options.

alias of PluginOptions

property options: LmStudioOptions

Return the validated LM Studio options.

property model_id: str

Return the configured LM Studio model identifier.

async generate(snapshot: ConversationSnapshot, generation: GenerationConfig) → GenerationRecord[source]

Generate assistant text for snapshot via LM Studio.

async aclose() → None[source]

Close the underlying LM Studio client connection.

Convert conversation snapshots to LM Studio chat contexts.

@domain backends @see [[knowledge/architecture/backends]] @tested-by [[tests/backends/test_lmstudio_chat.py]]

mllm_shap.backends.lmstudio.chat.snapshot_to_chat(snapshot: ConversationSnapshot, chat_factory: Any, image_handle: Callable[[ImagePart], Any] | None = None) → Any[source]

Build an LM Studio chat object from snapshot turns.

A user message’s images go in as image_handle(part) file handles after its text, the only order the SDK takes.

Raises:

ValueError – If a non-user message has an image, or an image comes without image_handle.

Resolve and download LM Studio models through the lmstudio SDK.

@domain backends @see [[knowledge/architecture/backends]] @tested-by [[tests/backends/test_lmstudio_models.py]]

mllm_shap.backends.lmstudio.models.normalize_model_token(value: str) → str[source]

Normalize a model identifier for fuzzy comparison.

mllm_shap.backends.lmstudio.models.match_downloaded_model_key(downloaded: Sequence[Any], model_id: str) → str | None[source]

Return the downloaded model_key for model_id, if any.

Candidates are tried in three stages, each on normalized names: an exact match, then a key whose last / segment starts with model_id, then a key containing model_id. The first stage with a single match wins.

Raises:

BackendUnavailableError – If a stage matches more than one key.

mllm_shap.backends.lmstudio.models.pick_search_result(results: Sequence[Any], model_id: str) → Any[source]

Choose the best repository search hit for model_id.

Raises:

BackendUnavailableError – If there are no hits or none is flagged exact or has a name matching model_id.

mllm_shap.backends.lmstudio.models.pick_download_option(options: Sequence[Any], quantization: str) → Any[source]

Choose a repository download option for the requested quantization.

async mllm_shap.backends.lmstudio.models.resolve_model_key(client: Any, model_id: str, options: LmStudioOptions) → str[source]

Return a loadable LM Studio model key, downloading when configured.

Settings of the LM Studio backend read from BackendConfig.options.

@domain backends @see [[knowledge/architecture/backends]] @tested-by [[tests/backends/test_lmstudio_options.py]]

class mllm_shap.backends.lmstudio.options.LmStudioOptions(*, hub_search: str | None = None, quantization: str = 'Q4_K_M', auto_download: bool = True, serialize_generate: bool = True, audio: Literal['refuse', 'transcript'] = 'refuse')[source]

Bases: BaseModel

LM Studio settings accepted under backend.options.

model_config = {'extra': 'forbid', 'frozen': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

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

quantization: str

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

auto_download: bool

Download missing models through the LM Studio repository API.

serialize_generate: bool

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

audio: Literal['refuse', 'transcript']

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

mllm_shap.backends.lmstudio.options.parse_lmstudio_options(options: Mapping[str, object]) → LmStudioOptions[source]

Validate backend.options for the LM Studio backend.

Raises:

ConfigError – If an option is unknown or has the wrong type.

Hugging Face transformers

Hugging Face transformers text backend.

@domain backends @see [[knowledge/architecture/backends]]

Hugging Face language model backend for text and, with a processor, audio.

@domain backends @see [[knowledge/architecture/backends]] @tested-by [[tests/backends/test_transformers_text.py]]

class mllm_shap.backends.transformers.text.TransformersTextBackend(context: PluginContext)[source]

Bases: object

Generate text with a local Hugging Face language model.

A checkpoint AutoModelForCausalLM cannot load (or any backend.options.model_class) loads its own class with AutoProcessor and also takes audio parts (see audio.processor_inputs).

options_model

Accepts no explanation.plugin_options.

alias of PluginOptions

property model_id: str

Return the configured Hugging Face model identifier.

property batch_size: int

Return the teacher-forced batch size (backend.options.batch_size).

property returns_logprobs: bool

Always true; every record carries its generated tokens’ logprobs.

property dtype: Literal['auto', 'float32', 'float16', 'bfloat16']

Return the configured weight dtype (backend.options.dtype).

property kv_cache_hits: int

Return the number of prefix-cache hits during this backend lifetime.

property kv_cache_reused_tokens: int

Return the prompt tokens served from cached prefixes, summed over hits.

set_kv_cache_enabled(enabled: bool, max_entries: int) → None[source]

Enable or disable prefix-cache reuse, keeping at most max_entries.

Omni models never reuse prefixes: their thinker positions do not survive cropping.

async generate(snapshot: ConversationSnapshot, generation: GenerationConfig) → GenerationRecord[source]

Generate assistant text for snapshot with optional prefix caching.

Raises:

ValueError – If snapshot has audio or images and the model has no processor.

property forces_continuations: bool

Always true; audio prompts need a model loaded with a processor.

async score_continuations(snapshot: ConversationSnapshot, continuations: Sequence[str], top_k: int = 0) → list[ForcedScore][source]

Score each continuation with one forward pass, without generating.

The continuation is tokenized on its own and appended to the chat prompt, whose processor features (audio) go into the same pass; top_k adds the most probable next tokens per position.

Raises:

ValueError – If snapshot has audio or images and the model has no processor.

async aclose() → None[source]

Release loaded model references.

property cost_counters: CostCounters

Return the cumulative model work since the backend was created.

mllm_shap.backends.transformers.text.collate_inputs(torch: Any, rows: list[dict[str, Any]], pad_id: int) → dict[str, Any][source]

Left-pad ids and masks to one width and stack the other tensors of rows.

A key such as input_features is stacked over the rows that carry it, in row order, which is the order of their audio tokens.

Audio parts for a Hugging Face processor: waveforms, rates and template parts.

@domain backends @see [[knowledge/architecture/backends]] @tested-by [[tests/backends/test_transformers_audio.py]]

mllm_shap.backends.transformers.audio.waveform(part: AudioPart, rate: int) → NDArray[float32][source]

Return part decoded to a mono waveform at rate.

mllm_shap.backends.transformers.audio.audio_template_part(samples: NDArray[float32], rate: int, processor: Any) → dict[str, Any][source]

Return a chat-template audio part; mistral-common takes base64 WAV.

mllm_shap.backends.transformers.audio.sampling_rate(processor: Any) → int[source]

Return the sample rate of the processor’s audio component.

mllm_shap.backends.transformers.audio.is_mistral_common(processor: Any) → bool[source]

Return whether the tokenizer is mistral-common’s (Voxtral).

mllm_shap.backends.transformers.audio.template_has_audio(processor: Any) → bool[source]

Return whether the processor’s chat template takes audio parts.

mllm_shap.backends.transformers.audio.template_mentions(processor: Any, word: str) → bool[source]

Return whether the processor’s or tokenizer’s chat template contains word.

Image parts for a Hugging Face processor.

@domain backends @see [[knowledge/architecture/backends]] @tested-by [[tests/backends/test_transformers_image.py]]

mllm_shap.backends.transformers.image.image_template_part(part: ImagePart) → dict[str, Any][source]

Return a chat-template image part holding part as an RGB Pillow image.

mllm_shap.backends.transformers.image.template_has_image(processor: Any) → bool[source]

Return whether the processor’s chat template takes image parts.

Conversation snapshot helpers for Hugging Face chat templates.

@domain backends @see [[knowledge/architecture/backends]] @tested-by [[tests/backends/test_transformers_chat.py]]

mllm_shap.backends.transformers.chat.render_prompt(tokenizer: Any, messages: list[dict[str, str]]) → str[source]

Render chat messages to a model prompt string.

Embedding helpers for the transformers text backend.

@domain backends @see [[knowledge/architecture/backends]]

mllm_shap.backends.transformers.embeddings.static_embedding(model: Any, token_ids: list[int]) → tuple[float, ...][source]

Mean-pool input embeddings for generated token ids.

mllm_shap.backends.transformers.embeddings.contextual_embedding(model: Any, token_ids: list[int]) → tuple[float, ...][source]

Mean-pool the final hidden state for generated token ids.

Settings of the transformers backend read from BackendConfig.options.

@domain backends @see [[knowledge/architecture/backends]]

mllm_shap.backends.transformers.options.TorchDtype

Weight dtypes accepted by backend.options.dtype.

alias of Literal[‘auto’, ‘float32’, ‘float16’, ‘bfloat16’]

class mllm_shap.backends.transformers.options.TransformersOptions(*, revision: str | None = None, dtype: Literal['auto', 'float32', 'float16', 'bfloat16']='auto', model_class: str | None = None, batch_size: Annotated[int, ~pydantic.types.Strict(strict=True), ~annotated_types.Ge(ge=1)] = 1, batch_wait_ms: Annotated[float, ~annotated_types.Ge(ge=0)] = 5.0, attn_implementation: str | None = None, processor_kwargs: dict[str, ~typing.Any]=<factory>)[source]

Bases: BaseModel

Transformers settings accepted under backend.options.

model_config = {'extra': 'forbid', 'frozen': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

revision: str | None

Hub revision to load (branch, tag or commit hash); pin a commit hash for reproducible runs. None loads the default branch.

dtype: Literal['auto', 'float32', 'float16', 'bfloat16']

Weight dtype; auto picks bfloat16 on accelerators that support it, float16 on other accelerators and float32 on CPU.

model_class: str | None

transformers class to load with the checkpoint’s processor, for example Gemma3nForConditionalGeneration. None uses AutoModelForCausalLM when it knows the checkpoint, else the checkpoint’s architecture.

batch_size: int

Teacher-forced sequences scored in one padded forward pass. Concurrent score_continuations calls are collected up to this many sequences; 1 scores each prompt on its own. The scheduler runs at least this many coalitions at once.

batch_wait_ms: float

Longest wait for a batch to fill before a smaller one runs.

attn_implementation: str | None

Attention kernel passed to from_pretrained (eager, sdpa, …); None keeps the model’s default. Granite Speech on Apple MPS needs eager: its projector fails under the default kernel.

processor_kwargs: dict[str, Any]

Extra arguments of the processor call for audio and image prompts, such as max_pixels; recorded in the manifest and, when set, hashed into the coalition keys, so archives written with other values do not replay.

mllm_shap.backends.transformers.options.parse_transformers_options(options: Mapping[str, object]) → TransformersOptions[source]

Validate backend.options for the transformers backend.

Raises:

ConfigError – If an option is unknown or has the wrong value.

Model inputs for audio and image language models through a Hugging Face processor.

@domain backends @see [[knowledge/architecture/backends]] @tested-by [[tests/backends/test_transformers_audio.py]] @tested-by [[tests/backends/test_transformers_image.py]]

mllm_shap.backends.transformers.processor.Item = str | NDArray[numpy.float32] | mllm_shap.domain.conversation.ImagePart

One part a processor receives (text, a waveform or an image).

mllm_shap.backends.transformers.processor.processor_inputs(processor: Any, snapshot: ConversationSnapshot, order: Literal['legacy', 'in_order'] = 'legacy', processor_kwargs: Mapping[str, Any] | None = None) → Any[source]

Encode snapshot with its audio and images for processor.

Images, and audio for a processor whose chat template mentions audio, go in as structured chat-template parts (a mistral-common tokenizer, as in Voxtral, has an implicit template and takes each clip as base64 WAV); otherwise each audio part becomes processor.audio_token in the rendered prompt and the waveforms go to processor(text=..., audio=...). Parts follow order (message_parts, media first under legacy); an audio part left empty by masking is dropped. processor_kwargs (max_pixels, say) go to the processor call.

Raises:

ValueError – If snapshot has an image and the processor’s chat template takes none.