How a run works¶
ExplainRunner runs eight stages from snapshot to attributions.
Quick start¶
from mllm_shap import (
ConversationSnapshot,
ExplainConfig,
ExplainRunner,
Message,
Role,
Turn,
)
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",
"estimand": "shapley",
"value_fn": "tfidf_cosine",
"normalizer": "identity",
"absence_policy": "pad",
"archive": {"path": ""},
},
})
output = ExplainRunner(config).explain_sync(snapshot)
print("values:", tuple(round(value, 4) for value in output.result.values))
print("metrics:", output.metrics)
Output
values: (0.1667, 0.1667, 0.1667, 0.1667, 0.1667, 0.1667)
metrics: SchedulerMetrics(requested=64, executed=63, deduplicated=0, cache_hits=1, kv_cache_hits=0, kv_cache_reused_tokens=0)
The eight stages¶
Illustrative. Stages of one run; the archive is a side branch. reanalyze
reads the archive and starts again at stage 7.¶
Partition:
explanation.playerssplits the snapshot into aPlayerSet;tokensmakes one player per whitespace token.Resolve: the registry builds every plugin the config names.
Base generation: the backend answers the full prompt once: the grand coalition’s output, against which every other output is scored.
Sample: the estimator draws masks for the budget and
seed; the runner adds the empty and grand coalitions, sobase_valueandgrand_valueare always known.Render and key: the absence policy builds each masked prompt (Masking views); each gets a dedup key and, for prefix-cache backends, a prefix hash.
Generate:
InferenceSchedulerruns at mostmax_inflightcalls at once, serves repeats from the hot store and archives each output (Runtime core).Score: the value function returns \(v(S)\) per output;
tfidf_cosinefirst fits on all outputs.neyman_ccthen draws phase-two coalitions and repeats stages 5 to 7.Aggregate: estimator and estimand turn payoffs into attributions, the normalizer rescales them, and the run returns an
ExplainRunOutput.
Run output¶
Field |
Meaning |
|---|---|
|
|
|
|
|
Snapshot id prefix plus a digest of the configuration and model id |
|
|
|
|
The counters give a run’s model calls:
Counter |
Meaning |
|---|---|
|
Coalition jobs submitted, one per sampled coalition |
|
Jobs that called the backend |
|
Jobs skipped because the same coalition key already ran |
|
Jobs served from the in-memory hot store (always includes the grand coalition) |
|
Generations that reused a cached prompt prefix ( |
|
Prompt tokens those hits took from the cache |
Archives and reanalysis¶
With explanation.archive.path set (default ./runs/{run_id}) a run writes an
archive (Runtime core). reanalyze() rescores it without
the model, here with another normalizer:
from pathlib import Path
archived = config.model_copy(
update={
"explanation": config.explanation.model_copy(
update={"archive": config.explanation.archive.model_copy(
update={"path": "runs/{run_id}"},
)},
),
},
)
first = ExplainRunner(archived).explain_sync(snapshot)
root = Path("runs") / first.run_id
print("archive files:", sorted(path.name for path in root.iterdir()))
rescored = archived.model_copy(
update={
"explanation": archived.explanation.model_copy(
update={"normalizer": "min_max"},
),
},
)
again = ExplainRunner(rescored).reanalyze(root)
print("explain: ", tuple(round(value, 4) for value in first.result.values))
print("min_max: ", tuple(round(value, 4) for value in again.result.values))
print("backend calls during reanalyze:", again.metrics.executed)
Output
archive files: ['archive.sqlite', 'base_generation.txt', 'manifest.json']
explain: (0.1667, 0.1667, 0.1667, 0.1667, 0.1667, 0.1667)
min_max: (0.1667, 0.1667, 0.1667, 0.1667, 0.1667, 0.1667)
backend calls during reanalyze: 0
It aggregates with the archived estimator and raises
ReanalyzeMismatchError when the runner’s estimator, absence
policy or players differ.
Optional hooks: progress= receives coalition counts, telemetry= times each stage
(Runtime core).
explain and explain_sync¶
explain() is a coroutine;
explain_sync() runs it on a fresh event loop and raises
RuntimeError inside a running loop (Jupyter, async web handlers). Await it there:
output = await ExplainRunner(config).explain(snapshot)
Reusing a backend¶
Each explain call builds and closes its backend. To keep one model or client across
prompts, pass backend= and close it yourself:
from mllm_shap.backends.mock import MockBackend
runner = ExplainRunner(config, backend=MockBackend(model_id="stub"))
prompts = ("Cancel my old phone plan today", "Cancel my plan")
for text in prompts:
prompt = ConversationSnapshot.from_turns((
Turn(messages=(Message(role=Role.USER, text=text),)),
))
values = runner.explain_sync(prompt).result.values
print(text, "->", tuple(round(value, 4) for value in values))
Output
Cancel my old phone plan today -> (0.1667, 0.1667, 0.1667, 0.1667, 0.1667, 0.1667)
Cancel my plan -> (0.3333, 0.3333, 0.3333)
In async code, await runner.aclose() closes an injected backend that holds
resources. Model servers: Generative backends; every key: Configuration.
Notebooks: Explain a conversation with ExplainRunner (one run from snapshot to JSON, every estimator, estimand and hook) and Run archives and reanalyze.