Semivalues, new estimators and honest uncertainty¶
Business context: an attribution is only worth acting on if you know how far it can be off and what it cost. This notebook shows the estimands and estimators added after Shapley and Banzhaf, how to attach a standard error to a sampled run, how to stop sampling early and how to ask for a budget instead of guessing one.
Goal: compute Beta Shapley and weighted Banzhaf values, compare permutation and lime with exact values, check that mc intervals cover the truth about 95% of the time, stop a run on its own interval width and plan a budget from a target error.
Prerequisites: mllm-shap and NumPy, Python 3.12 or newer; seconds on a laptop. Runs use the mock backend, so the model outputs are placeholders; the toy game gives exact answers.
Theory: Estimands and choosing an estimator.
import numpy as np
from mllm_shap import (
ConfigError,
ConversationSnapshot,
ExplainConfig,
ExplainRunner,
LimeEstimator,
Message,
MonteCarloEstimator,
PermutationEstimator,
PlayerSet,
PluginContext,
PluginGroup,
Role,
ShapleyAggregator,
Turn,
default_registry,
explain_config_from_yaml,
)
from mllm_shap.estimation.planning import plan_budget
A toy game with known answers¶
Technical: eight players, an additive part plus an airport term, v(S) = a·x + max(c ⊙ x), so Shapley and Banzhaf differ. Its exact values come from the full table of 256 coalitions, so every estimator below can be scored against the truth.
N = 8
rng = np.random.default_rng(0)
singles = rng.uniform(-1.0, 1.0, N)
costs = rng.uniform(1.0, 10.0, N)
PLAYERS = PlayerSet(player_ids=tuple(f"p{i}" for i in range(N)))
def payoff(present):
x = np.asarray(present, dtype=float)
return float(singles @ x + (costs * x).max())
def table():
masks = [tuple(bool((k >> i) & 1) for i in range(N)) for k in range(2**N)]
return masks, [payoff(m) for m in masks]
FULL_MASKS, FULL_PAYOFFS = table()
REGISTRY = default_registry()
def aggregator(name, **options):
# an estimand plugin with its options, resolved like a run resolves it
config = ExplainConfig.model_validate(
{
"backend": {"kind": "mock", "model_id": "stub"},
"explanation": {
"estimator": "exact",
"estimand": name,
"plugin_options": {name: options} if options else {},
},
}
)
context = PluginContext(config=config, registry=REGISTRY)
return REGISTRY.resolve(PluginGroup.ESTIMANDS, name, context)
Beta Shapley and weighted Banzhaf¶
Technical: both keep the marginal contributions of Shapley and Banzhaf and change only the weight of each coalition size. beta_shapley with alpha > beta favours small coalitions (alpha = beta = 1 is Shapley); weighted_banzhaf includes every other player with probability p (p = 0.5 is Banzhaf). On the full table all four are exact; the table below shows how far the weighting moves the values.
estimands = {
"shapley": aggregator("shapley"),
"banzhaf": aggregator("banzhaf"),
"beta_shapley (4, 1)": aggregator("beta_shapley", alpha=4.0, beta=1.0),
"beta_shapley (1, 1)": aggregator("beta_shapley", alpha=1.0, beta=1.0),
"weighted_banzhaf (p=0.3)": aggregator("weighted_banzhaf", p=0.3),
"weighted_banzhaf (p=0.5)": aggregator("weighted_banzhaf", p=0.5),
}
exact = {
name: np.array(agg.aggregate(FULL_MASKS, FULL_PAYOFFS))
for name, agg in estimands.items()
}
for name, values in exact.items():
print(f"{name:26s}", np.round(values[:4], 3), "...")
print(
"beta (1, 1) equals shapley:",
np.allclose(exact["beta_shapley (1, 1)"], exact["shapley"]),
"| p = 0.5 equals banzhaf:",
np.allclose(exact["weighted_banzhaf (p=0.5)"], exact["banzhaf"]),
)
shapley [ 1.317 2.146 0.802 -0.839] ...
banzhaf [ 0.533 1.088 -0.256 -0.959] ...
beta_shapley (4, 1) [ 2.982 4.719 3.264 -0.594] ...
beta_shapley (1, 1) [ 1.317 2.146 0.802 -0.839] ...
weighted_banzhaf (p=0.3) [ 1.401 2.582 1.163 -0.883] ...
weighted_banzhaf (p=0.5) [ 0.533 1.088 -0.256 -0.959] ...
beta (1, 1) equals shapley: True | p = 0.5 equals banzhaf: True
permutation and lime against the exact values¶
Technical: permutation evaluates every prefix of random orderings (and of their reverses with antithetic: true, the default) and works for any estimand. lime fits the reference kernel-weighted ridge surrogate; its coefficients are not Shapley values, so it is compared by rank, not by value. Budgets are in coalitions: 25% of 256 is 64.
def run(estimator, aggregator_, fraction, seed):
masks = list(estimator.sample_masks(PLAYERS, fraction, False, seed))
values = [payoff(m.present) for m in masks]
return np.array(estimator.estimate_attributions(masks, values, aggregator_))
def mean_error(estimator, name, fraction=0.25, seeds=30):
errors = [
np.linalg.norm(run(estimator, estimands[name], fraction, s) - exact[name])
/ np.linalg.norm(exact[name])
for s in range(seeds)
]
return float(np.mean(errors))
plain = PermutationEstimator()
plain.antithetic = False
print("relative L2 error against exact Shapley, 25% budget, 30 seeds")
print(" mc ", round(mean_error(MonteCarloEstimator(), "shapley"), 3))
print(" permutation ", round(mean_error(PermutationEstimator(), "shapley"), 3))
print(" permutation (plain)", round(mean_error(plain, "shapley"), 3))
lime = np.array(run(LimeEstimator(), estimands["shapley"], 0.5, 0))
rank_hit = len(set(np.argsort(-np.abs(lime))[:3]) & set(np.argsort(-np.abs(exact["shapley"]))[:3]))
print("lime top-3 overlap with exact Shapley top-3:", rank_hit, "of 3")
relative L2 error against exact Shapley, 25% budget, 30 seeds
mc 0.158
permutation 0.337
permutation (plain) 0.33
lime top-3 overlap with exact Shapley top-3: 1 of 3
Standard errors that cover¶
Technical: for mc, standard_errors returns the stratified standard error of every value, with a finite-population correction, so value ± 1.96 · stderr is a 95% interval. In a run, set explanation.stderr: true. The check below counts how often the interval contains the exact Shapley value over 300 seeds.
hits = total = 0
for seed in range(300):
mc = MonteCarloEstimator()
masks = list(mc.sample_masks(PLAYERS, 0.25, False, seed))
payoffs_ = [payoff(m.present) for m in masks]
agg = estimands["shapley"]
values = np.array(mc.estimate_attributions(masks, payoffs_, agg))
errors = np.array(mc.standard_errors(masks, payoffs_, agg))
hits += int(np.sum(np.abs(values - exact["shapley"]) <= 1.96 * errors))
total += N
print(f"coverage of the 95% intervals: {hits / total:.1%}")
coverage of the 95% intervals: 94.6%
In a run: stderr, budget.stop and the guards¶
Technical: stderr adds a stderr field to the result and its JSON payload; budget.stop ends mc sampling once every 95% interval is at most max_ci_width wide, or the top k players are the same set at two checks. The budget stays the upper bound. Both are refused for estimators that cannot honour them, and the semivalue estimands only run with mc, exact, permutation, lime or loo.
snapshot = ConversationSnapshot.from_turns(
(Turn(messages=(Message(role=Role.USER, text="a b c d e f g h"),)),)
)
async def explain(**explanation):
config = ExplainConfig.model_validate(
{
"backend": {"kind": "mock", "model_id": "stub"},
"generation": {"max_new_tokens": 4},
"explanation": {
"absence_policy": "pad",
"value_fn": "tf_logprob",
"archive": {"path": ""},
**explanation,
},
}
)
return await ExplainRunner(config).explain(snapshot)
with_errors = await explain(estimator="mc", budget={"fraction": 0.5}, stderr=True)
print("stderr:", np.round(with_errors.result.stderr, 4), "in payload:", "stderr" in with_errors.to_dict())
full = await explain(estimator="mc", budget={"fraction": 1.0})
early = await explain(
estimator="mc",
budget={"fraction": 1.0, "stop": {"top_k_stable": 3, "check_every": 8}},
)
print("coalitions evaluated:", early.metrics.requested, "of", full.metrics.requested)
for bad in (
"{estimator: leverage, stderr: true}",
"{estimator: leverage, estimand: beta_shapley}",
"{estimator: permutation, budget: {fraction: 0.5, stop: {max_ci_width: 0.1}}}",
):
try:
explain_config_from_yaml(f"backend: {{kind: mock, model_id: stub}}\nexplanation: {bad}\n")
except ConfigError as error:
print("refused:", str(error)[:90])
stderr: [0.0433 0.0435 0.0565 0.0443 0.0394 0.0387 0.0363 0.053 ] in payload: True
coalitions evaluated: 40 of 256
refused: explanation.stderr needs estimator 'exact' or 'mc', efficiency 'none' and the 'identity' n
refused: estimand 'beta_shapley' needs estimator 'mc' or 'exact'; got 'leverage'
refused: budget.stop needs estimator 'mc' (max_ci_width) or 'mc' and 'permutation' (top_k_stable)
Asking for a budget¶
Technical: plan_budget inverts the Hoeffding bound of Maleki et al. (2013): for n players, a marginal-contribution range r and a target error ε it returns the random orderings needed and the coalitions they can touch, capped at 2^n. The same numbers come from mllm-shap plan --players N --range R --target-error E. The bound is a worst case, so treat it as an upper estimate; a pilot run gives a tighter range.
for players, target in ((12, 0.2), (20, 0.1), (20, 0.02)):
plan = plan_budget(players, value_range=2.0, target_error=target)
print(
f"n={players:2d} error<={target:<5} -> {plan.orderings:>7} orderings, "
f"{plan.evaluations:>9} coalitions ({plan.per_player:,.0f} per player)"
+ (" [full table is cheaper: use exact]" if plan.exact_is_cheaper else "")
)
n=12 error<=0.2 -> 309 orderings, 3401 coalitions (283 per player)
n=20 error<=0.1 -> 1337 orderings, 25405 coalitions (1,270 per player)
n=20 error<=0.02 -> 33424 orderings, 635058 coalitions (31,753 per player)