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:
objectHash-based generative backend with no external model dependencies.
- options_model¶
Accepts no
explanation.plugin_options.alias of
PluginOptions
- 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.
- 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_VOCABtokens; 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:
MockBackendEcho 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
audioextra.- async generate(snapshot: ConversationSnapshot, generation: GenerationConfig) GenerationRecord[source]¶
Return the heard words of
snapshot, at mostmax_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:
MockBackendEcho 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_PIXELSof 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 theimageextra.- async generate(snapshot: ConversationSnapshot, generation: GenerationConfig) GenerationRecord[source]¶
Return the seen words of
snapshot, at mostmax_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:
PluginOptionsOptions of the
replaybackend.- fallback: dict[str, object] | None¶
backendsettings (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:
objectServe archived coalition generations; compute misses with a fallback.
- options_model¶
Accepts no
explanation.plugin_options; settings arebackend.options.alias of
PluginOptions
- 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.
- 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.
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:
objectGenerate text through an OpenAI-compatible
/chat/completionsendpoint.- options_model¶
Accepts no
explanation.plugin_options.alias of
PluginOptions
- 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
snapshotvia the HTTP API.
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
snapshotto chat messages with audio and image parts.A message with media sends text parts, one base64 WAV part per
AudioPartand one data-URI part perImagePartinorder(text first underlegacy); non-WAV audio is re-encoded (audioextra), and images other than PNG or JPEG are re-encoded as PNG (imageextra).
- 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, orNonewhen absent.Servers that ignore the
logprobsrequest field (or send another shape) giveNone; thelogprobvalue 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:
objectGenerate 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.
- async generate(snapshot: ConversationSnapshot, generation: GenerationConfig) GenerationRecord[source]¶
Generate assistant text for
snapshotvia LM Studio.
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
snapshotturns.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_keyformodel_id, if any.Candidates are tried in three stages, each on normalized names: an exact match, then a key whose last
/segment starts withmodel_id, then a key containingmodel_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:
BaseModelLM 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].
- mllm_shap.backends.lmstudio.options.parse_lmstudio_options(options: Mapping[str, object]) LmStudioOptions[source]¶
Validate
backend.optionsfor 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:
objectGenerate text with a local Hugging Face language model.
A checkpoint
AutoModelForCausalLMcannot load (or anybackend.options.model_class) loads its own class withAutoProcessorand also takes audio parts (seeaudio.processor_inputs).- options_model¶
Accepts no
explanation.plugin_options.alias of
PluginOptions
- property dtype: Literal['auto', 'float32', 'float16', 'bfloat16']¶
Return the configured weight dtype (
backend.options.dtype).
- 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
snapshotwith optional prefix caching.- Raises:
ValueError – If
snapshothas 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_kadds the most probable next tokens per position.- Raises:
ValueError – If
snapshothas audio or images and the model has no processor.
- 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_featuresis 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
partdecoded to a mono waveform atrate.
- 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
partas 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:
BaseModelTransformers 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.
Noneloads the default branch.
- dtype: Literal['auto', 'float32', 'float16', 'bfloat16']¶
Weight dtype;
autopicks bfloat16 on accelerators that support it, float16 on other accelerators and float32 on CPU.
- model_class: str | None¶
transformersclass to load with the checkpoint’s processor, for exampleGemma3nForConditionalGeneration.NoneusesAutoModelForCausalLMwhen it knows the checkpoint, else the checkpoint’s architecture.
- batch_size: int¶
Teacher-forced sequences scored in one padded forward pass. Concurrent
score_continuationscalls are collected up to this many sequences;1scores each prompt on its own. The scheduler runs at least this many coalitions at once.
- mllm_shap.backends.transformers.options.parse_transformers_options(options: Mapping[str, object]) TransformersOptions[source]¶
Validate
backend.optionsfor 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
snapshotwith its audio and images forprocessor.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_tokenin the rendered prompt and the waveforms go toprocessor(text=..., audio=...). Parts followorder(message_parts, media first underlegacy); an audio part left empty by masking is dropped.processor_kwargs(max_pixels, say) go to the processor call.- Raises:
ValueError – If
snapshothas an image and the processor’s chat template takes none.