Command line¶
The mllm-shap command explains prompts without Python, from the
ExplainRunner YAML configuration (Configuration) and a JSON snapshot.
mllm-shap config --example > config.yaml # commented YAML skeleton
mllm-shap config --check config.yaml # validate a configuration
mllm-shap explain --config config.yaml --snapshot snapshot.json --out result.json
mllm-shap explain --config config.yaml --snapshot snapshot.json \
--render token_bar --png result.png
mllm-shap reanalyze --config config.yaml --archive runs/<run_id>
mllm-shap plugins # registered plugins per group
mllm-shap plan --players 20 --range 2 --target-error 0.1 # budget for an error
--log-level info (debug, info, warning, error, any case) before the
command prints stage events on stderr (Runtime core).
Exit |
Meaning |
|---|---|
|
Success |
|
Invalid argument, configuration, snapshot or archive, or an unreadable input file |
|
Backend unavailable: missing extra, unreachable server, refused connection |
Any other error is a bug and shows its traceback. The snippets call
mllm_shap.cli.main(), the command’s entry point, in one working directory.
Snapshot JSON¶
A snapshot lists turns of ordered messages, each with role user, assistant or
system, one text and an optional one-line "speaker" when people share a role. The
id derives from the content (speaker included), so a file always maps to the same run;
set one explicitly with a top-level "snapshot_id".
to_json() and
from_json() write and read it:
from pathlib import Path
from mllm_shap import ConversationSnapshot, Message, Role, Turn
snapshot = ConversationSnapshot.from_turns((
Turn(
messages=(
Message(role=Role.USER, text="Why is the sky blue", speaker="ana"),
)
),
))
Path("snapshot.json").write_text(snapshot.to_json(), encoding="utf-8")
print(Path("snapshot.json").read_text(encoding="utf-8"))
restored = ConversationSnapshot.from_json(Path("snapshot.json").read_text())
print("same snapshot:", restored == snapshot)
Output
{
"turns": [
{
"messages": [
{
"role": "user",
"text": "Why is the sky blue",
"speaker": "ana"
}
]
}
]
}
same snapshot: True
A message with audio or several parts has a "content" list instead of "text". An
audio part names a file in "path" (relative to the snapshot) or holds base64 bytes in
"data":
{"turns": [{"messages": [{"role": "user", "content": [
{"type": "text", "text": "I had that curiosity beside me at this moment"},
{"type": "audio", "path": "voices_sp0307.wav", "sample_rate": 16000}
]}]}]}
Audio needs a backend that hears it: Audio input.
Explain¶
mllm-shap config --example prints a skeleton that runs on the mock backend; point
backend at a real model. explain writes JSON to --out (or stdout), keys in
fixed order: values, labels (per player: text, character span, speaker, display
label), base_value, grand_value, estimand, metrics, manifest,
perf:
import json
from mllm_shap.cli import EXAMPLE_CONFIG, main
Path("config.yaml").write_text(EXAMPLE_CONFIG, encoding="utf-8")
code = main([
"explain",
"--config", "config.yaml",
"--snapshot", "snapshot.json",
"--out", "result.json",
])
result = json.loads(Path("result.json").read_text(encoding="utf-8"))
print("exit code:", code)
print("keys:", list(result))
for label, value in zip(result["labels"], result["values"], strict=True):
print(f"{label['text']:>5} {value:+.4f}")
print("sum == grand - base:", round(sum(result["values"]), 9)
== round(result["grand_value"] - result["base_value"], 9))
Output
exit code: 0
keys: ['values', 'labels', 'base_value', 'grand_value', 'estimand', 'metrics', 'manifest', 'perf']
Why +0.2000
is +0.2000
the +0.2000
sky +0.2000
blue +0.2000
sum == grand - base: True
--render token_text or token_bar with --png also saves a chart
(Visualization, extra viz).
Reanalyze¶
reanalyze rescores an archived run without the model; edit value_fn or
normalizer first. The archive is at explanation.archive.path (./runs/{run_id}
in the skeleton). Without a snapshot, labels carry player ids only:
run_dir = Path("runs") / result["manifest"]["run_id"]
rescored_config = EXAMPLE_CONFIG.replace(
"normalizer: identity", "normalizer: abs_sum"
)
Path("abs_sum.yaml").write_text(rescored_config, encoding="utf-8")
main([
"reanalyze",
"--config", "abs_sum.yaml",
"--archive", str(run_dir),
"--out", "rescored.json",
])
rescored = json.loads(Path("rescored.json").read_text(encoding="utf-8"))
print("backend calls:", rescored["metrics"]["executed"])
print("abs_sum values:", [round(value, 4) for value in rescored["values"]])
print("label:", rescored["labels"][0])
Output
backend calls: 0
abs_sum values: [0.2, 0.2, 0.2, 0.2, 0.2]
label: {'player_id': '9319b488c2a98329:0:0:0', 'text': None, 'message_index': None, 'start': None, 'end': None, 'speaker': None, 'label': None, 'part': None, 'region': None}
Archives store text only, so embedding_cosine with encoder: model_states scores
hash embeddings on reanalysis. The manifest’s embedding_source says what the explain
run scored: none, hash (text-derived vectors) or backend (transformers
embeddings, named by embedding_model). Reanalyzing a backend run with an embedding
value function logs a WARNING since values will differ; --strict exits with 2
instead. A missing, unreadable or older manifest or database also exits with 2.
Plugins¶
plugins lists every registered plugin, built-in or entry point (Extending mllm-shap):
main(["plugins"])
Output
mllm_shap.estimators: complementary, exact, kernel_banzhaf, leverage, lime, loo, mc, neyman_cc, permutation, proxy
mllm_shap.estimands: banzhaf, beta_shapley, shapley, weighted_banzhaf
mllm_shap.value_fns: bertscore, contrastive, embedding_cosine, judge_grade, label_margin, logprob, nli_logodds, reference_wer, self_logprob, semascore, speech_bertscore, tf_jsd, tf_logprob, tfidf_cosine, transcribed
mllm_shap.normalizers: abs_sum, identity, min_max, power_shift
mllm_shap.backends: api, lmstudio, mock, mock_audio, mock_image, replay, transformers
mllm_shap.partitions: image_boxes, image_grid, messages, sentences, sgpa_segments, tokens, uniform_segments
mllm_shap.absence_policies: delete, infill, neutral, pad
mllm_shap.renderers: token_bar, token_text
Notebook: Command line: mllm-shap runs every subcommand with its exit code.