Faithfulness checks, margins and pairwise interactions¶
Business context: an explanation is only useful if removing what it ranks first really changes the answer, if the check is not graded by the explainer itself, and if you can see which words work together rather than alone.
Goal: score a ranking with removal metrics (deletion and insertion curves, comprehensiveness, sufficiency, normalised AOPC, win rates against random sets, flip and restore sizes), see the circularity warning, use label_margin for a closed answer and read pairwise k-SII interactions.
Prerequisites: mllm-shap and the interactions extra (uv sync --extra interactions), Python 3.12 or newer; seconds on a laptop. Runs use the mock backend, so only the toy-game numbers are meaningful.
Theory: Value functions and choosing an estimator.
import numpy as np
from mllm_shap import (
ConversationSnapshot,
ExplainConfig,
ExplainRunner,
Message,
Role,
Turn,
compute_removal_metrics,
explain_interactions,
removal_metrics,
)
Removal metrics on a game with a known cause¶
Technical: the game v(S) = Σ wᵢ xᵢ has a known best ranking, the weights. compute_removal_metrics evaluates the coalitions of removal_plan (the top-k removed or kept alone, plus seeded random sets of the same size) and returns the curves and scores. The win rate is 1 when the ranking beats every random set and about 0.5 on average for shuffled rankings.
N = 10
weights = np.random.default_rng(1).uniform(-1.0, 2.0, N)
def game(present):
return float(weights @ np.asarray(present, dtype=float))
good = compute_removal_metrics(weights, game, random_sets=30, seed=0)
shuffler = np.random.default_rng(2)
shuffled_runs = [
compute_removal_metrics(shuffler.permutation(weights), game, random_sets=30, seed=s)
for s in range(20)
]
shuffled = shuffled_runs[0]
for name, metrics in (("true weights", good), ("one shuffle", shuffled)):
print(
f"{name:13s} win rate {metrics.deletion_win_rate:.2f} | "
f"AOPC {metrics.aopc:.2f} | comprehensiveness(3) {metrics.comprehensiveness(3):.2f} | "
f"sufficiency(3) {metrics.sufficiency(3):.2f}"
)
print(
"mean win rate over 20 shuffles:",
round(float(np.mean([m.deletion_win_rate for m in shuffled_runs])), 2),
)
print("deletion curve of the true ranking:", np.round(good.deletion_values, 2))
true weights win rate 0.99 | AOPC 1.03 | comprehensiveness(3) 5.18 | sufficiency(3) 0.13
one shuffle win rate 0.68 | AOPC 0.67 | comprehensiveness(3) 2.41 | sufficiency(3) 2.90
mean win rate over 20 shuffles: 0.45
deletion curve of the true ranking: [ 5.31 3.46 1.62 0.13 -0.52 -1.05 -1.32 -1.55 -1.48 -0.92 0. ]
Flip and restore sizes for a closed answer¶
Technical: with a threshold (0 for label_margin) the metrics report the smallest removal that flips the decision and the smallest kept set that restores it. Here the decision holds while player 0, or both players 1 and 2, are present.
def decision(present):
return 1.0 if present[0] or (present[1] and present[2]) else -1.0
for name, ranking in (("right order", [3.0, 2.0, 1.0]), ("wrong order", [1.0, 2.0, 3.0])):
metrics = compute_removal_metrics(ranking, decision, threshold=0.0)
print(f"{name}: flip size {metrics.flip_size}, restore size {metrics.restore_size}")
right order: flip size 2, restore size 1
wrong order: flip size 3, restore size 2
Score a real run, and the circularity warning¶
Technical: removal_metrics runs the same evaluation through the pipeline with config’s backend, value function and absence policy. Pass the explanation’s config as explained_with: if the evaluation reuses its value function and absence policy, circular is true and a warning is logged, because the check then favours the explainer by construction. label_margin scores a target label against the other labels of a closed answer; with two labels it equals contrastive.
snapshot = ConversationSnapshot.from_turns(
(Turn(messages=(Message(role=Role.USER, text="alpha beta gamma delta epsilon"),)),)
)
def config(value_fn, **options):
return ExplainConfig.model_validate(
{
"backend": {"kind": "mock", "model_id": "stub"},
"generation": {"max_new_tokens": 4},
"explanation": {
"estimator": "exact",
"absence_policy": "delete",
"value_fn": value_fn,
"archive": {"path": ""},
"plugin_options": {value_fn: options} if options else {},
},
}
)
explain_config = config(
"label_margin", target="alpha", labels=["alpha", "beta", "gamma"]
)
explained = await ExplainRunner(explain_config).explain(snapshot)
print("label_margin attributions:", np.round(explained.result.values, 3))
same = await removal_metrics(
explain_config, snapshot, explained.result.values, random_sets=5,
explained_with=explain_config,
)
other = await removal_metrics(
config("tf_logprob"), snapshot, explained.result.values, random_sets=5,
explained_with=explain_config,
)
print("same value function -> circular:", same.circular)
print("other value function -> circular:", other.circular, "| win rate", other.deletion_win_rate)
label_margin attributions: [-0.218 -0.437 -0.523 -0.107 0.984]
same value function -> circular: True
other value function -> circular: False | win rate 0.5
Pairwise interactions¶
Technical: explain_interactions scores all 2^n coalitions through the pipeline (so an archive or the replay backend answers repeats) and returns the order-2 k-SII matrix through shapiq. A positive entry means two words are worth more together than their separate values add up to. It needs the full table, so it is for short inputs; index="FSII" gives Faith-SHAP.
pairs = await explain_interactions(
config("tf_logprob"), snapshot
)
print("index:", pairs.index, "| players:", len(pairs.player_ids))
for first, second, value in pairs.top(3):
print(f" {first} x {second}: {value:+.4f}")
index: k-SII | players: 5
alpha x delta: +0.4502
alpha x epsilon: +0.3327
beta x epsilon: -0.1906