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

Eight boxes in a row from Partition to Aggregate. Base generation, Generate and Score write the base text, one row per coalition and the manifest to the run archive below. A dashed arrow runs from Score back to Render for neyman_cc.

Illustrative. Stages of one run; the archive is a side branch. reanalyze reads the archive and starts again at stage 7.

  1. Partition: explanation.players splits the snapshot into a PlayerSet; tokens makes one player per whitespace token.

  2. Resolve: the registry builds every plugin the config names.

  3. Base generation: the backend answers the full prompt once: the grand coalition’s output, against which every other output is scored.

  4. Sample: the estimator draws masks for the budget and seed; the runner adds the empty and grand coalitions, so base_value and grand_value are always known.

  5. 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.

  6. Generate: InferenceScheduler runs at most max_inflight calls at once, serves repeats from the hot store and archives each output (Runtime core).

  7. Score: the value function returns \(v(S)\) per output; tfidf_cosine first fits on all outputs. neyman_cc then draws phase-two coalitions and repeats stages 5 to 7.

  8. Aggregate: estimator and estimand turn payoffs into attributions, the normalizer rescales them, and the run returns an ExplainRunOutput.

Run output

Field

Meaning

result

ExplainResult: estimand, per-player values, base_value (\(v(\emptyset)\)) and grand_value (\(v(N)\))

metrics

SchedulerMetrics counters (below)

run_id

Snapshot id prefix plus a digest of the configuration and model id

manifest

RunManifest written to the archive

perf

PerfSummary: wall-clock split between generation, scoring and aggregation, plus model work (forward_sequences, prompt_tokens, generated_tokens, device_seconds) for mock and transformers

The counters give a run’s model calls:

Counter

Meaning

requested

Coalition jobs submitted, one per sampled coalition

executed

Jobs that called the backend

deduplicated

Jobs skipped because the same coalition key already ran

cache_hits

Jobs served from the in-memory hot store (always includes the grand coalition)

kv_cache_hits

Generations that reused a cached prompt prefix (transformers with kv_cache.enabled: true; off by default)

kv_cache_reused_tokens

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.