Extending mllm-shap¶
Every stage of a run is a plugin looked up by name in a PluginRegistry.
The snippets share one namespace.
Optional extras¶
pip install mllm-shap # core only (no torch)
pip install "mllm-shap[transformers]" # Hugging Face text backend
pip install "mllm-shap[lmstudio]" # LM Studio SDK backend
pip install "mllm-shap[api]" # OpenAI-compatible HTTP backend
pip install "mllm-shap[viz]" # matplotlib token attribution charts
pip install "mllm-shap[proxy]" # scikit-learn: the ProxySHAP estimator
pip install "mllm-shap[infill]" # masked language model of the infill policy
pip install "mllm-shap[interactions]" # shapiq: exact pairwise interactions
pip install "mllm-shap[audio]" # audio decoding and alignment
pip install "mllm-shap[semantic]" # encoders of embedding_cosine, bertscore,
# nli_logodds and semascore
pip install "mllm-shap[audio-semantic]" # speech_bertscore and transcribed
pip install "mllm-shap[image]" # image players and fills
How plugins are built¶
A plugin is registered as a factory: a callable taking a
PluginContext and returning the plugin, usually a class
whose __init__ takes the context. The context carries:
config: the run’s validatedExplainConfig.options:explanation.plugin_options["<group>/<name>"]or["<name>"], else empty.option()reads one with a typed default. Withoptions_modelset to aPluginOptionssubclass, unknown keys and wrong types raiseConfigError; without it options pass unchecked.registry: the registry that built the plugin.
A custom value function with options¶
Share of the base generation’s words a coalition output keeps, ignoring words shorter
than option min_length:
from mllm_shap import (
ConversationSnapshot,
ExplainConfig,
ExplainRunner,
Message,
PluginGroup,
PluginRegistry,
Role,
Turn,
)
from mllm_shap.plugins import PluginContext, register_builtin_plugins
from mllm_shap.protocols.backend import GenerationResult
from mllm_shap.protocols.plugin import PluginOptions
class VocabularyOverlapOptions(PluginOptions):
min_length: int = 1
class VocabularyOverlapValue:
options_model = VocabularyOverlapOptions
def __init__(self, context: PluginContext) -> None:
self._min_length = context.option("min_length", 1)
@property
def name(self) -> str:
return "vocab_overlap"
def _words(self, result: GenerationResult) -> set[str]:
return {w for w in result.text.split() if len(w) >= self._min_length}
def score(self, base: GenerationResult, candidate: GenerationResult) -> float:
reference = self._words(base)
if not reference:
return 0.0
return len(reference & self._words(candidate)) / len(reference)
registry = PluginRegistry()
register_builtin_plugins(registry)
registry.register(PluginGroup.VALUE_FNS, "vocab_overlap", VocabularyOverlapValue)
snapshot = ConversationSnapshot.from_turns((
Turn(messages=(Message(role=Role.USER, text="Cancel my old phone plan today"),)),
))
config = ExplainConfig.model_validate({
"backend": {"kind": "mock", "model_id": "stub"},
"explanation": {
"estimator": "exact",
"value_fn": "vocab_overlap",
"absence_policy": "pad",
"archive": {"path": ""},
"plugin_options": {"vocab_overlap": {"min_length": 4}},
},
})
output = ExplainRunner(config, registry=registry).explain_sync(snapshot)
print(tuple(round(value, 4) for value in output.result.values))
Output
(0.1667, 0.1667, 0.1667, 0.1667, 0.1667, 0.1667)
It satisfies ValueFunction. Add fit(corpus)
(FittableValueFunction) to see all of a run’s outputs
before scoring, as tfidf_cosine does.
A custom backend¶
A backend needs a model_id property and an async generate(snapshot, generation)
returning an object with text.
generation_record_from_text() builds the record
built-in value functions expect. This one answers with the prompt reversed:
from mllm_shap.pipeline.config import GenerationConfig
from mllm_shap.value.generation_records import generation_record_from_text
class ReverseBackend:
def __init__(self, context: PluginContext) -> None:
self._model_id = context.config.backend.model_id
@property
def model_id(self) -> str:
return self._model_id
async def generate(
self, snapshot: ConversationSnapshot, generation: GenerationConfig
) -> GenerationResult:
words = " ".join(m.text for t in snapshot.turns for m in t.messages)
reply = " ".join(reversed(words.split()))[: generation.max_new_tokens]
return generation_record_from_text(reply)
registry.register(PluginGroup.BACKENDS, "reverse", ReverseBackend)
reverse_config = config.model_copy(
update={"backend": config.backend.model_copy(update={"kind": "reverse"})}
)
output = ExplainRunner(reverse_config, registry=registry).explain_sync(snapshot)
print(tuple(round(value, 4) for value in output.result.values))
Output
(0.25, 0.0, 0.0, 0.25, 0.25, 0.25)
A backend holding clients or models may implement async aclose()
(SupportsAclose); the runner calls it after each run.
Backend settings go under backend.options.
A custom estimator¶
An estimator picks coalitions and aggregates their payoffs with the run’s estimand. This one scores the full prompt and each prompt missing one player, giving the occlusion score \(v(N) - v(N \setminus \{i\})\):
from collections.abc import Iterator, Sequence
from mllm_shap import CoalitionMask, PlayerSet
from mllm_shap.protocols.estimand import EstimandAggregator
class LeaveOneOutEstimator:
def __init__(self, context: PluginContext | None = None) -> None:
_ = context
@property
def name(self) -> str:
return "leave_one_out"
def bind_snapshot(self, snapshot: ConversationSnapshot) -> None:
_ = snapshot
def sample_masks(
self,
player_set: PlayerSet,
budget_fraction: float,
include_minimal_masks: bool,
seed: int,
) -> Iterator[CoalitionMask]:
n = player_set.num_players
yield CoalitionMask.from_sequence((True,) * n)
for i in range(n):
yield CoalitionMask.from_sequence(tuple(j != i for j in range(n)))
def estimate_attributions(
self,
masks: Sequence[CoalitionMask],
payoffs: Sequence[float],
aggregator: EstimandAggregator,
) -> list[float]:
return aggregator.aggregate([mask.present for mask in masks], payoffs)
registry.register(PluginGroup.ESTIMATORS, "leave_one_out", LeaveOneOutEstimator)
loo_config = reverse_config.model_copy(
update={
"explanation": reverse_config.explanation.model_copy(
update={"estimator": "leave_one_out"},
),
},
)
output = ExplainRunner(loo_config, registry=registry).explain_sync(snapshot)
print("coalitions:", output.metrics.requested)
print(tuple(round(value, 4) for value in output.result.values))
Output
coalitions: 8
(0.25, 0.0, 0.0, 0.25, 0.25, 0.25)
The runner adds the empty coalition for base_value: \(n + 2 = 8\) coalitions for
6 players. Leave-one-out values need not add up. An estimator that needs payoffs before
drawing more implements TwoPhaseEstimator, as
neyman_cc does.
A custom partitioner¶
A partitioner decides what a player is; here each message, as for one retrieved passage per message:
from mllm_shap import PlayerSpan
class MessagePartitioner:
def __init__(self, context: PluginContext | None = None) -> None:
_ = context
@property
def name(self) -> str:
return "messages"
def partition(self, snapshot: ConversationSnapshot) -> PlayerSet:
messages = snapshot.messages()
return PlayerSet(
player_ids=tuple(
f"{snapshot.snapshot_id}:{index}" for index in range(len(messages))
),
spans=tuple(
PlayerSpan(index, 0, len(message.text), message.text)
for index, message in enumerate(messages)
),
)
passages = ConversationSnapshot.from_turns((
Turn(messages=(
Message(role=Role.SYSTEM, text="Refunds take 14 days."),
Message(role=Role.SYSTEM, text="Shipping is free over 50 EUR."),
Message(role=Role.USER, text="How long do refunds take?"),
)),
))
print(MessagePartitioner().partition(passages).num_players)
Output
3
Register it under PluginGroup.PARTITIONS. A
PlayerSpan names a message (turns flattened) and a
character range. Absence policies edit exactly those ranges, so every partitioner works
with every policy.
Testing a plugin¶
Test a plugin as the pipeline uses it: register, resolve by name, check behaviour.
context = PluginContext(config=config, registry=registry)
value_fn = registry.resolve(PluginGroup.VALUE_FNS, "vocab_overlap", context)
base = generation_record_from_text("refund issued today")
print(value_fn.score(base, generation_record_from_text("refund issued")))
Output
0.6666666666666666
resolve passes the plugin’s plugin_options entry, validated against
options_model: the plugin sees min_length: 4.
Publishing plugins¶
Declare plugins under project.entry-points in pyproject.toml;
ExplainRunner loads every group’s entry points into its default
registry:
[project.entry-points."mllm_shap.value_fns"]
vocab_overlap = "my_package.values:VocabularyOverlapValue"
Group |
Purpose |
|---|---|
|
Coalition sampling strategies ( |
|
Payoff aggregation ( |
|
Coalition scoring utilities ( |
|
Post-aggregation scaling ( |
|
Player definitions ( |
|
Masked snapshot rendering ( |
|
Model inference connectors ( |
|
Attribution visualization ( |
Taken names are skipped, so a third-party plugin never silently replaces a built-in;
registry.register(..., replace=True) replaces on purpose.
API: Plugins, Protocols. Every config key: Configuration. Notebook: Plugins: registry, context and options.