Runtime core¶
The layer under ExplainRunner: archives, dedup, scheduler, logging,
telemetry, benchmarks. Most users only set explanation.archive, dedup and
max_inflight. Snippets share one namespace; design: Runtime core.
Run archives¶
An archive is a directory with manifest.json, the base generation and one row per
coalition output in archive.sqlite. load()
reads them back:
from pathlib import Path
from mllm_shap import (
ConversationSnapshot,
ExplainConfig,
ExplainRunner,
Message,
Role,
Turn,
)
from mllm_shap.runtime import RunArchive
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": "mock"},
"explanation": {
"estimator": "exact",
"absence_policy": "delete",
"archive": {"path": "runs/{run_id}"},
},
})
output = ExplainRunner(config).explain_sync(snapshot)
root = Path("runs") / output.run_id
print("files:", sorted(path.name for path in root.iterdir()))
with RunArchive.load(root) as archive:
print("base:", repr(archive.read_base_generation()[:19]))
for record in list(archive.history_lazy())[:3]:
print(record.record_id, repr(record.generation_text[:19]))
Output
files: ['archive.sqlite', 'base_generation.txt', 'manifest.json']
base: '9fe1 0f35 d389 9747'
1 '305a 3f1d f172 895d'
2 'd64a adcd 1c76 d8e4'
3 '8591 0a55 2e72 40fe'
Re-running the same config and snapshot targets the same directory;
open() never appends, so it raises
ArchiveExistsError. on_exists: overwrite clears the old
archive first:
from mllm_shap.errors import ArchiveExistsError
try:
ExplainRunner(config).explain_sync(snapshot)
except ArchiveExistsError as error:
print(type(error).__name__)
overwrite = config.model_copy(
update={
"explanation": config.explanation.model_copy(
update={"archive": config.explanation.archive.model_copy(
update={"on_exists": "overwrite"},
)},
),
},
)
again = ExplainRunner(overwrite).explain_sync(snapshot)
print("same run id:", again.run_id == output.run_id)
Output
ArchiveExistsError
same run id: True
Run manifest¶
Archive rows hold generated text, token logprobs, teacher-forced scores and the audio
path of a spoken answer (SQLite, WAL journal). The manifest’s schema_version must
equal MANIFEST_SCHEMA_VERSION and the database’s
PRAGMA user_version ARCHIVE_SCHEMA_VERSION, or
load() raises
ManifestVersionError (for example, archives of 0.1.17 or
earlier); re-run explain to rebuild them. The manifest records:
Field |
Meaning |
|---|---|
|
Manifest format and the package version that wrote it |
|
Run identifier and the explained snapshot |
|
How payoffs were sampled, scored and aggregated |
|
How the prompt was partitioned and masked; |
|
Which backend and model generated the outputs |
|
Value function settings: encoder, layer, model, library version |
|
|
|
Full |
reanalyze() (How a run works) reproduces explain with
the same value function. It raises ArchiveIncompleteError for a
failed run’s archive, one missing the grand or empty coalition, a full-budget archive
missing rows, or one whose manifest ExplainRunner did not write.
Coalition dedup keys¶
A coalition key hashes everything that decides a generation
(Runtime core). With dedup.enabled: auto (on at any temperature) a
repeated coalition is generated once per run and repeats share its payoff:
from mllm_shap.pipeline.config import DedupConfig, GenerationConfig
from mllm_shap.runtime import build_coalition_key, dedup_enabled
generation = GenerationConfig(temperature=0.0)
key = build_coalition_key(
snapshot_id="snap-1",
player_ids=("snap-1:0:0:0", "snap-1:0:0:1"),
mask_present=(True, False),
absence_policy="delete",
model_id="mock",
generation=generation,
)
print(dedup_enabled(DedupConfig(enabled="auto"), generation), key[:12])
Output
True ec7d60731ab2
generation.num_samples: 4 (temperature above 0) draws each coalition four times,
each with its own key and row (draw 0 keeps the single-draw key). A coalition’s value is
the mean of its draws, so efficiency holds for the mean game. Such archives cannot be
reanalyzed.
The scheduler¶
Illustrative. One job’s path through InferenceScheduler;
each grey box and the backend call increments the counter it names.¶
Nine jobs over three distinct keys cost three backend calls:
import asyncio
from mllm_shap.masking.codec import MaskCodec
from mllm_shap.runtime import (
CoalitionDedupRegistry,
CoalitionJob,
HotResultStore,
InferenceScheduler,
)
packed = MaskCodec.pack((True, False, True))
async def generate(prompt: ConversationSnapshot) -> str:
return prompt.turns[0].messages[0].text
scheduler = InferenceScheduler(
max_inflight=2,
generation=GenerationConfig(temperature=0.0),
store=HotResultStore(),
dedup=CoalitionDedupRegistry(),
)
jobs = [
CoalitionJob(
coalition_key=f"key-{index % 3}",
snapshot_id=snapshot.snapshot_id,
snapshot=snapshot,
absence_policy="delete",
mask_words=packed.words,
mask_n_bits=packed.n_bits,
model_id="mock",
)
for index in range(9)
]
metrics = asyncio.run(scheduler.run(jobs, generate))
print(metrics)
Output
SchedulerMetrics(requested=9, executed=3, deduplicated=0, cache_hits=6, kv_cache_hits=0, kv_cache_reused_tokens=0)
Counts passed to progress= add up over all runs of one scheduler: Neyman’s second
phase calls on_coalitions_planned again with the larger total.
run_iter() takes any iterable and
creates coroutines only as slots free up, so an exact run never holds all \(2^n\)
jobs in memory:
from mllm_shap import ExactEstimator
from mllm_shap.masking import MaskBuilder, PadPolicy, TokenPartitioner
players = TokenPartitioner().partition(snapshot)
builder = MaskBuilder(PadPolicy())
def job_stream():
for mask in ExactEstimator.iter_masks(players):
packed = MaskCodec.pack(mask.present)
yield CoalitionJob(
coalition_key=packed.words.hex(),
snapshot_id=snapshot.snapshot_id,
snapshot=builder.render(builder.view(snapshot, players, mask)),
absence_policy="pad",
mask_words=packed.words,
mask_n_bits=packed.n_bits,
model_id="mock",
)
streaming = InferenceScheduler(
max_inflight=4,
generation=GenerationConfig(temperature=0.0),
store=HotResultStore(),
)
metrics = asyncio.run(streaming.run_iter(job_stream(), generate, total=64))
print(metrics.requested, metrics.executed)
Output
64 64
Failures¶
Jobs share one asyncio.TaskGroup. When generate raises, the other jobs are
cancelled and the first exception is re-raised unwrapped (no ExceptionGroup), so
except RuntimeError works; nothing partial is returned:
async def flaky(prompt: ConversationSnapshot) -> str:
if "[MASK]" in prompt.turns[0].messages[0].text:
msg = "backend refused a masked prompt"
raise RuntimeError(msg)
return "ok"
failing = InferenceScheduler(
max_inflight=2,
generation=GenerationConfig(temperature=0.0),
store=HotResultStore(),
)
try:
asyncio.run(failing.run_iter(job_stream(), flaky, total=64))
except RuntimeError as error:
print("raised:", error)
Output
raised: backend refused a masked prompt
Logging¶
Importing mllm_shap leaves the host’s logging alone. Opt in with
configure_logging():
import mllm_shap
mllm_shap.configure_logging(level="INFO") # plain lines on stderr
mllm_shap.configure_logging(level="INFO", json=True) # one JSON object per line
mllm_shap.configure_logging("config/logging.example.toml") # a [tool.logging] file
Without arguments it applies [tool.logging] of the nearest pyproject.toml.
MLLM_SHAP_LOGGING_CONFIG names a TOML file applied on import; start from
config/logging.example.toml. At INFO the logger mllm_shap.pipeline.orchestrator
reports each stage once:
Event |
Message |
|---|---|
Run start |
|
Base generation |
|
Coalitions scheduled |
|
Run end |
|
DEBUG adds HTTP retries and skipped plugin entry points.
mllm_shap.backends.lmstudio.models logs LM Studio downloads at INFO.
Telemetry and progress¶
InMemoryObservabilitySink records one
SpanRecord (name, duration) per stage; any
CoalitionProgress receives coalition counts:
from mllm_shap import InMemoryObservabilitySink
class CountingProgress:
def __init__(self) -> None:
self.planned: list[int] = []
self.finished = 0
def on_coalitions_planned(self, total: int) -> None:
self.planned.append(total)
def on_coalition_finished(self, done: int, total: int) -> None:
self.finished = done
sink = InMemoryObservabilitySink()
progress = CountingProgress()
ExplainRunner(overwrite, telemetry=sink, progress=progress).explain_sync(snapshot)
print("stages:", [span.name for span in sink.spans])
print("planned:", progress.planned, "finished:", progress.finished)
Output
stages: ['orchestrator.generate_base', 'estimator.sample_masks', 'orchestrator.schedule', 'orchestrator.score', 'orchestrator.aggregate', 'orchestrator.run']
planned: [64] finished: 64
A tqdm progress bar:
from tqdm import tqdm
class TqdmProgress:
def __init__(self) -> None:
self.bar = tqdm(total=0, unit="coalition")
def on_coalitions_planned(self, total: int) -> None:
self.bar.total = total
self.bar.refresh()
def on_coalition_finished(self, done: int, total: int) -> None:
self.bar.update(done - self.bar.n)
ExplainRunner(config, progress=TqdmProgress()).explain_sync(snapshot)
Callbacks run synchronously on the event loop; keep them cheap.
Benchmarks¶
tests/benchmarks/ (pytest-benchmark) covers dedup keys, mask packing, 10k-row
archive round trips, prefix-cache lookups, exact, stratified and complementary
aggregation, a 1 000-job scheduler, TF-IDF scoring and a mock end-to-end run.
make bench # run them and write .pytest_benchmark/benchmark.json
make bench-regression # fail when a median is >25% slower than baseline.json
tests/benchmarks/baseline.json: 2026-10-12, Apple M4 (10 cores, 16 GB RAM), macOS
26.5.1 (Darwin 25.5.0), CPython 3.12.12. On other hardware record a local baseline first.
make check skips benchmarks; a weekly CI workflow runs make bench and keeps the
report. Run make bench-regression before changing hot paths in runtime/,
masking/ or estimation/.
Notebook: Runtime archive, deduplication, and async scheduling.