Replay archived coalitions and read the cost of a run¶
Business context: the model calls are the expensive part of an explanation. Replay turns one paid-for table of coalitions into any number of free experiments, and the cost counters tell you what each run actually used.
Goal: run an exact explanation once and archive it, then run other estimators, budgets and seeds from the archive with zero model calls, see what happens when a coalition is missing and how a fallback backend fills it, and read forward sequences, tokens and device seconds from perf.
Prerequisites: mllm-shap, Python 3.12 or newer; seconds on a laptop. The mock backend counts words as tokens and reports zero device time; the transformers backend measures both.
Theory: Backends and pipeline.
import tempfile
from pathlib import Path
from mllm_shap import (
ConversationSnapshot,
ExplainConfig,
ExplainRunner,
Message,
ReplayMissError,
Role,
Turn,
)
Pay once: an exact run with an archive¶
Technical: the archive keeps every coalition’s generation (and, for teacher-forced value functions, its forced scores). perf reports the model work of the run: how many sequences went through the model, the prompt and generated tokens, and the device seconds.
WORK = Path(tempfile.mkdtemp(prefix="replay-"))
snapshot = ConversationSnapshot.from_turns(
(Turn(messages=(Message(role=Role.USER, text="one two three four five six"),)),)
)
def config(archive, backend=None, **explanation):
return ExplainConfig.model_validate(
{
"backend": backend or {"kind": "mock", "model_id": "stub"},
"generation": {"max_new_tokens": 4},
"explanation": {
"absence_policy": "pad",
"value_fn": "tf_logprob",
"archive": {"path": str(archive)},
**explanation,
},
}
)
table = WORK / "exact-table"
paid = await ExplainRunner(config(table, estimator="exact")).explain(snapshot)
print("coalitions executed:", paid.metrics.executed)
print("cost:", paid.perf)
coalitions executed: 63
cost: PerfSummary(total_ms=36.9090661406517, generation_ms=11.379921808838844, scoring_ms=0.0772085040807724, aggregation_ms=0.4422999918460846, forward_sequences=65, prompt_tokens=646, generated_tokens=4, device_seconds=0.0)
Spend nothing: any estimator, budget and seed from the archive¶
Technical: backend.kind: replay reads the archived rows by coalition key, so keep the archived run’s input, players, absence policy, model id and generation settings and change only the estimator, budget, seed or value function. Every row is a cache hit: executed is zero and perf reports no model work.
replay = {"kind": "replay", "model_id": "stub", "options": {"archives": [str(table)]}}
for seed in (1, 2, 3):
run = await ExplainRunner(
config(WORK / f"replay-{seed}", replay, estimator="mc",
budget={"fraction": 0.4}, seed=seed)
).explain(snapshot)
print(
f"mc seed {seed}: executed {run.metrics.executed}, "
f"sequences {run.perf.forward_sequences}, top {max(range(6), key=lambda i: abs(run.result.values[i]))}"
)
exact_again = await ExplainRunner(
config(WORK / "replay-exact", replay, estimator="exact")
).explain(snapshot)
print("exact through replay equals the live run:",
list(exact_again.result.values) == list(paid.result.values))
mc seed 1: executed 0, sequences 0, top 4
mc seed 2: executed 0, sequences 0, top 5
mc seed 3: executed 0, sequences 0, top 1
exact through replay equals the live run: True
A missing coalition, and a fallback¶
Technical: an archive of a sampled run does not hold every coalition. Without a fallback the run stops before the model is touched and names the coalition (players present as 1); with fallback set to a live backend, only the missing coalitions are computed.
partial = WORK / "partial"
await ExplainRunner(
config(partial, estimator="mc", budget={"fraction": 0.3})
).explain(snapshot)
strict = {"kind": "replay", "model_id": "stub", "options": {"archives": [str(partial)]}}
try:
await ExplainRunner(config(WORK / "strict", strict, estimator="exact")).explain(snapshot)
except ReplayMissError as error:
print("refused:", str(error)[:110])
lenient = {
"kind": "replay",
"model_id": "stub",
"options": {
"archives": [str(partial)],
"fallback": {"kind": "mock", "model_id": "stub"},
},
}
filled = await ExplainRunner(config(WORK / "lenient", lenient, estimator="exact")).explain(snapshot)
print("computed by the fallback:", filled.metrics.executed, "of", filled.metrics.requested)
print("values equal the live exact run:",
[round(v, 9) for v in filled.result.values] == [round(v, 9) for v in paid.result.values])
refused: coalition 110000 (players present as 1) of snapshot '89c0759a4f87b805' is not in the replay archives; archive
computed by the fallback: 45 of 64
values equal the live exact run: True
Batching on a real model¶
Technical: with the transformers backend, backend.options.batch_size scores teacher-forced value functions and generates greedy answers in padded batches, and perf then shows the device time saved. It needs the transformers extra and a model, so it is shown here as configuration only; the gpu-marked tests run it on a tiny model.
batched = ExplainConfig.model_validate(
{
"backend": {
"kind": "transformers",
"model_id": "hf-internal-testing/tiny-random-gpt2",
"options": {"dtype": "float32", "batch_size": 16, "batch_wait_ms": 5.0},
},
"explanation": {"value_fn": "tf_logprob", "archive": {"path": ""}},
}
)
print(batched.backend.options)
{'dtype': 'float32', 'batch_size': 16, 'batch_wait_ms': 5.0}