Protocols

Protocol contracts for pipeline plugins.

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

Generative backend protocol.

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

class mllm_shap.protocols.backend.GenerationResult(*args, **kwargs)[source]

Bases: Protocol

Minimal generation output consumed by value functions.

property text: str

Return the generated text payload.

class mllm_shap.protocols.backend.GenerativeBackend(*args, **kwargs)[source]

Bases: Protocol

Execute model generation for a masked conversation snapshot.

property model_id: str

Return the backend model identifier.

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

Generate model output for the given snapshot.

class mllm_shap.protocols.backend.ReportsCost(*args, **kwargs)[source]

Bases: Protocol

Backend that counts its model work.

property cost_counters: CostCounters

Return the cumulative counters since the backend was created.

class mllm_shap.protocols.backend.ReplaySource(*args, **kwargs)[source]

Bases: Protocol

Backend that answers coalitions from archived rows.

property has_fallback: bool

Return whether a live backend computes coalitions that are not archived.

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

Return the archived row of a 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.

class mllm_shap.protocols.backend.SupportsKvCache(*args, **kwargs)[source]

Bases: Protocol

Backend that can reuse prompt-prefix KV state across coalitions.

property kv_cache_hits: int

Return the cumulative number of prefix-cache hits.

property kv_cache_reused_tokens: int

Return the cumulative number of prompt tokens served from the cache.

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

Turn prefix-cache reuse on or off and cap the number of cached prefixes.

class mllm_shap.protocols.backend.SupportsLogprobs(*args, **kwargs)[source]

Bases: Protocol

Backend whose records carry GenerationRecord.logprobs.

The logprob value function requires it; a record that still arrives without logprobs (a server that omits them) raises LogprobsUnavailableError when scored.

property returns_logprobs: bool

Return whether generated records include token logprobs.

class mllm_shap.protocols.backend.SupportsTeacherForcing(*args, **kwargs)[source]

Bases: Protocol

Backend that scores fixed continuations under a prompt without generating.

Value functions that declare needs_teacher_forcing require it. mock and transformers (text and audio prompts) implement it; lmstudio and api do not, because chat servers do not return prompt logprobs.

property forces_continuations: bool

Return whether score_continuations() is available.

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

Return one ForcedScore each.

With top_k above zero each score also holds the top_k most probable next tokens at every continuation position.

class mllm_shap.protocols.backend.SupportsAclose(*args, **kwargs)[source]

Bases: Protocol

Backend holding resources (clients, models) released by aclose.

async aclose() → None[source]

Release backend resources.

Estimator strategy protocols.

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

class mllm_shap.protocols.estimator.EstimatorStrategy(*args, **kwargs)[source]

Bases: Protocol

Sample coalitions and turn their payoffs into attributions.

property name: str

Return the registered estimator identifier.

bind_snapshot(snapshot: ConversationSnapshot) → None[source]

Attach the conversation snapshot under explanation.

sample_masks(player_set: PlayerSet, budget_fraction: float, include_minimal_masks: bool, seed: int) → Iterator[CoalitionMask][source]

Yield coalition masks to evaluate for the player set.

estimate_attributions(masks: Sequence[CoalitionMask], payoffs: Sequence[float], aggregator: EstimandAggregator) → list[float][source]

Aggregate evaluated coalitions into per-player attributions.

class mllm_shap.protocols.estimator.ProvidesStandardErrors(*args, **kwargs)[source]

Bases: Protocol

Estimator that reports the standard error of its raw values.

standard_errors(masks: Sequence[CoalitionMask], payoffs: Sequence[float], aggregator: EstimandAggregator) → list[float][source]

Return one standard error per player for the values of the same inputs.

class mllm_shap.protocols.estimator.TwoPhaseEstimator(*args, **kwargs)[source]

Bases: Protocol

Estimator that allocates a second sampling phase from first-phase payoffs.

begin_allocation(masks: Sequence[CoalitionMask], payoffs: Sequence[float]) → None[source]

Consume phase-one payoffs and plan phase two.

sample_allocation_masks() → Iterator[CoalitionMask][source]

Yield phase-two coalition masks.

Estimand aggregation protocol.

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

class mllm_shap.protocols.estimand.EstimandAggregator(*args, **kwargs)[source]

Bases: Protocol

Aggregate coalition payoffs into per-player attributions.

property estimand: Estimand

Return the estimand label produced by this aggregator.

coalition_weight(coalition_size: int, num_players: int) → float[source]

Return coalition weight for the given size excluding the focal player.

aggregate(masks: Sequence[Sequence[bool]], payoffs: Sequence[float]) → list[float][source]

Aggregate coalition samples into per-player attribution values.

Value function protocol.

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

class mllm_shap.protocols.value.ValueInfo(value_range: tuple[float, float], reads_base: bool, needs: tuple[str, ...] = (), extra_model: str = '', cost: str = 'text', higher_is_better: bool = True)[source]

Bases: object

What a value function measures and costs; every built-in declares one.

Declared as the class attribute info; docs/theory/value_functions.rst lists it and a test checks every built-in has it.

value_range: tuple[float, float]

Lowest and highest possible score (-inf / inf when unbounded).

reads_base: bool

Whether the score depends on the full-input answer \(y_N\).

needs: tuple[str, ...]

Capabilities required of the backend or archive, from logprobs, embeddings, teacher_forcing, judge and audio.

extra_model: str

Model the value function loads besides the explained one; empty for none.

cost: str

Cost per coalition, one of text (string work), encoder (one small encoder pass), forward (one forward pass of the explained model) and judge (a judge model call).

higher_is_better: bool

Whether a larger score means a coalition answer closer to the full one.

class mllm_shap.protocols.value.ValueFunction(*args, **kwargs)[source]

Bases: Protocol

Score coalition utility relative to a base generation.

property name: str

Return the registered value-function identifier.

score(base: GenerationResult, candidate: GenerationResult) → float[source]

Return utility for candidate relative to base.

class mllm_shap.protocols.value.FittableValueFunction(*args, **kwargs)[source]

Bases: ValueFunction, Protocol

Value function that must see the run’s corpus before it scores.

The pipeline calls fit() with the base generation and every coalition generation before any score() call, in explain and reanalyze.

fit(corpus: Sequence[GenerationRecord]) → None[source]

Freeze corpus statistics used by score().

class mllm_shap.protocols.value.RequiresLogprobs(*args, **kwargs)[source]

Bases: Protocol

Value function that scores GenerationRecord.logprobs.

When needs_logprobs is true the pipeline refuses backends that are not SupportsLogprobs and reanalyze refuses archives whose rows have no logprobs.

property needs_logprobs: bool

Return whether scoring reads logprobs.

class mllm_shap.protocols.value.RequiresEmbeddings(*args, **kwargs)[source]

Bases: Protocol

Value function that scores model embeddings rather than text.

When needs_embeddings is true the pipeline sets GenerationConfig.compute_embeddings for its backend calls, so backends that can (transformers) attach static and contextual embeddings to their records, and scores those records.

property needs_embeddings: bool

Return whether scoring reads embedding or contextual_embedding.

class mllm_shap.protocols.value.RequiresTeacherForcing(*args, **kwargs)[source]

Bases: Protocol

Value function that scores teacher-forced continuations.

When needs_teacher_forcing is true the pipeline refuses backends that are not SupportsTeacherForcing, scores forced_continuations() under every coalition prompt and attaches the results to GenerationRecord.forced. With reads_candidate_text false it also skips generating the coalition answers.

property needs_teacher_forcing: bool

Return whether scoring reads GenerationRecord.forced.

property forced_top_k: int

Return how many next-token candidates per position to request.

property reads_candidate_text: bool

Return whether scoring reads the coalition’s generated text.

forced_continuations(base: GenerationResult) → tuple[str, ...][source]

Return the continuations to score under each coalition prompt.

class mllm_shap.protocols.value.PreparesScores(*args, **kwargs)[source]

Bases: Protocol

Value function that needs asynchronous work, such as a judge model call.

The pipeline awaits prepare() with the base generation and every coalition generation before any score call.

async prepare(base: GenerationRecord, corpus: Sequence[GenerationRecord]) → None[source]

Compute and cache what score reads.

Attribution normalizer protocol.

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

class mllm_shap.protocols.normalizer.Normalizer(*args, **kwargs)[source]

Bases: Protocol

Scale aggregated attributions for presentation without mutating archives.

property name: str

Return the registered normalizer identifier.

normalize(values: Sequence[float]) → list[float][source]

Return presentation-scaled copies of values.

Player partition protocol.

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

class mllm_shap.protocols.partition.PlayerPartitioner(*args, **kwargs)[source]

Bases: Protocol

Partition a conversation snapshot into explainability players.

property name: str

Return the registered partition identifier.

partition(snapshot: ConversationSnapshot) → PlayerSet[source]

Derive ordered players and their spans from the snapshot.

The returned PlayerSet must carry one PlayerSpan per player; absence policies and labels read the spans instead of re-tokenising.

Masking and absence policy protocols.

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

class mllm_shap.protocols.masking.AbsencePolicy(*args, **kwargs)[source]

Bases: Protocol

Render absent players when building a masked snapshot view.

property name: str

Return the registered absence-policy identifier.

apply(snapshot: ConversationSnapshot, players: PlayerSet, mask: CoalitionMask) → ConversationSnapshot[source]

Return a masked snapshot view for coalition evaluation.

Embedding provider protocol.

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

class mllm_shap.protocols.embedding.EmbeddingProvider(*args, **kwargs)[source]

Bases: Protocol

Expose embeddings for value functions that operate in embedding space.

property name: str

Return the registered embedding provider identifier.

embed(generation: GenerationResult) → tuple[float, ...][source]

Return an embedding vector for the generation.

Attribution renderer protocol.

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

class mllm_shap.protocols.renderer.AttributionRenderer(*args, **kwargs)[source]

Bases: Protocol

Render per-player attribution values for human review.

property name: str

Return the registered renderer identifier.

render(labels: Sequence[str], values: Sequence[float], *, estimand: Estimand, title: str | None = None) → Any[source]

Return a visualization artifact for the given labels and values.

Options contract for plugins configured through explanation.plugin_options.

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

class mllm_shap.protocols.plugin.PluginOptions[source]

Bases: BaseModel

Options a plugin accepts; the base class accepts none.

Subclasses declare one field per option. Unknown keys and values of the wrong type are rejected (extra="forbid", strict types; integers are accepted for float fields).

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.protocols.plugin.DeclaresPluginOptions(*args, **kwargs)[source]

Bases: Protocol

Plugin class that declares the options it accepts.

The registry validates explanation.plugin_options for the plugin against options_model before building it. Plugins without the attribute get their options unchecked.

options_model: ClassVar[type[PluginOptions]]

Pydantic model listing the accepted options.