Using value functions

A value function scores a coalition’s output against the base generation \(y_N\) (the full prompt’s output): the payoff \(v(S)\). explanation.value_fn names it. Each built-in declares its contract:

value_fn

Range

Reads \(y_N\)

Needs

Extra model

Cost per coalition

Direction

bertscore

[-1, 1]

yes

Hugging Face encoder (default roberta-large)

one encoder pass

higher is better

contrastive

[-inf, inf]

no

teacher_forcing

one forward pass

higher is better

embedding_cosine

[-1, 1]

yes

embeddings

sentence-transformers encoder (default all-MiniLM-L6-v2)

one encoder pass

higher is better

judge_grade

[1, 5]

yes

judge

judge model (any backend; logits preferred)

one judge call

higher is better

label_margin

[-inf, inf]

no

teacher_forcing

one forward pass

higher is better

logprob

[-inf, 0]

no

logprobs

string work

higher is better

nli_logodds

[-13.8155, 13.8155]

yes

Hugging Face NLI model (default deberta-large-mnli)

one encoder pass

higher is better

reference_wer

[0, 1]

yes

string work

higher is better

self_logprob

[-inf, 0]

no

logprobs

string work

higher is better

semascore

[0, 1]

yes

Hugging Face encoder (default roberta-base)

one encoder pass

higher is better

speech_bertscore

[-1, 1]

yes

audio

WavLM-style speech encoder (default wavlm-large)

one encoder pass

higher is better

tf_jsd

[-inf, 0]

yes

teacher_forcing

one forward pass

higher is better

tf_logprob

[-inf, 0]

yes

teacher_forcing

one forward pass

higher is better

tfidf_cosine

[0, 1]

yes

string work

higher is better

transcribed

[-inf, inf]

yes

audio

speech recognizer (default whisper-base) plus the wrapped one

one encoder pass

higher is better

Cost is work per coalition beyond generation; teacher-forced functions generate no coalition answers. A function the backend cannot serve raises ConfigError before any generation.

TF-IDF cosine

from mllm_shap import GenerationRecord, TfIdfCosineValue

base = GenerationRecord(
    text="hello world",
    text_token_rows=((1, 0), (0, 1)),
)
candidate = GenerationRecord(
    text="hello there",
    text_token_rows=((1, 0), (2, 3)),
)

value_fn = TfIdfCosineValue()
value_fn.fit((base, candidate))
utility = value_fn.score(base, candidate)
print(round(utility, 4))

Output

0.3361

fit() runs once on all of the run’s (or archive’s) outputs, so coalitions share the IDF weights.

Embedding similarity

from mllm_shap import CosineEmbeddingValue, GenerationRecord
from mllm_shap.domain.enums import EmbeddingMode

base = GenerationRecord(text="base", embedding=(1.0, 0.0))
candidate = GenerationRecord(text="candidate", embedding=(0.9, 0.1))

value_fn = CosineEmbeddingValue(embedding_mode=EmbeddingMode.STATIC)
similarity = value_fn.score(base, candidate)
print(round(similarity, 4))

Output

0.9939

The default encoder, sentence-transformers all-MiniLM-L6-v2 (extra semantic), embeds both answers’ text, so any backend works and reanalyze matches explain. encoder: model_states uses the explained model’s pooled states, static or contextual per explanation.embedding_mode:

explanation:
  value_fn: embedding_cosine
  embedding_mode: contextual
  plugin_options:
    embedding_cosine: {encoder: model_states}

Pooled states, untrained for similarity, rank answer pairs poorly; hence the default. Only transformers has them: the mean of the output tokens’ input embeddings (static) or last hidden state (contextual). Other backends would give meaningless 8-dimensional hash vectors, so the run raises ConfigError unless plugin_options.embedding_cosine.allow_hash_embeddings is set (tests only). Archives store text only, so reanalyze in model_states mode scores hash vectors and differs from explain.

Self-confidence: self_logprob

from mllm_shap import GenerationRecord, SelfLogprobValue

candidate = GenerationRecord(text="answer", logprobs=(-0.1, -0.2, -0.3))
utility = SelfLogprobValue().score(candidate, candidate)
print(round(utility, 4))

Output

-0.2

\(v(S)\) is the mean log probability of the tokens generated for \(S\), in \((-\infty, 0]\); empty output scores 0. It ignores \(y_N\), so a confident unrelated answer scores high; tf_logprob measures fidelity. The alias logprob warns for one minor version. Backends without SupportsLogprobs (mock, lmstudio) raise ConfigError; a record without logprobs raises LogprobsUnavailableError; reanalyze refuses archives without them (Generative backends).

Teacher-forced scores

One forward pass scores a fixed continuation under each coalition prompt:

  • tf_logprob: \(v(S) = \frac1\ell\sum_t \log p(y_{N,t} \mid y_{N,<t}, x_S)\), the target of Captum, ContextCite and TextGenSHAP. reduce: sum drops \(1/\ell\).

  • tf_jsd: \(v(S) = -\sum_t \mathrm{JSD}(P_N \Vert P_S)\) over next-token distributions along \(y_N\), so \(v(N) = 0\). top_k (default 20) candidates per position are kept, the rest bucketed.

  • contrastive: \(v(S) = \log p(t \mid x_S) - \log p(f \mid x_S)\) for options target and foil, such as " I can't" against " Sure".

  • label_margin: \(v(S) = \log p(t \mid x_S) - \log \sum_{l \ne t} p(l \mid x_S)\) for a target among labels (" yes", " no"); with two labels it equals contrastive.

explanation:
  value_fn: contrastive
  plugin_options:
    contrastive: {target: " I can't", foil: " Sure"}

They need SupportsTeacherForcing (transformers with text or audio, mock). Scores are archived, so reanalyze reproduces explain. rescore() scores another value function’s archive from its masks, with forward passes only:

import asyncio
import tempfile
from pathlib import Path

from mllm_shap import (
    ConversationSnapshot, ExplainConfig, ExplainRunner, Message, Role, Turn,
)

snapshot = ConversationSnapshot.from_turns(
    (Turn((Message(role=Role.USER, text="Cancel my old phone plan today"),)),)
)

def config(value_fn: str, archive: str = "") -> ExplainConfig:
    return ExplainConfig.model_validate({
        "backend": {"kind": "mock", "model_id": "mock"},
        "explanation": {
            "value_fn": value_fn,
            "absence_policy": "delete",
            "archive": {"path": archive},
        },
    })

with tempfile.TemporaryDirectory() as tmp:
    text_run = ExplainRunner(config("tfidf_cosine", f"{tmp}/{{run_id}}")).explain_sync(
        snapshot
    )
    rescored = asyncio.run(
        ExplainRunner(config("tf_logprob")).rescore(snapshot, Path(tmp) / text_run.run_id)
    )
print("backend generate calls:", rescored.metrics.executed)
print("values:", [round(v, 3) for v in rescored.result.values])

Output

backend generate calls: 0
values: [0.14, 0.059, -0.073, 0.067, -0.051, 0.056]

Semantic scores from encoders

  • bertscore: BERTScore F1 of greedy token matching against \(y_N\) (encoder, layer, optional baseline), batched per instance; the best text-only stand-in for log probability.

  • nli_logodds: \(v(S) = \log\frac{p}{1-p}\), \(p\) the geometric mean of both entailment directions; catches negation that similarity misses. question is prepended to both answers.

  • semascore: per aligned transcript segment, cosine of contextual word vectors times one minus character error, weighted by closeness to reference.

Encoders load lazily (extra semantic) and are recorded in the manifest. A toy encoder:

import numpy as np
from mllm_shap import BertScoreValue, GenerationRecord

class Axes:
    vectors = {"cat": (1.0, 0.0), "dog": (0.0, 1.0), "pet": (0.6, 0.8)}

    def encode(self, texts):
        return [np.array([self.vectors[w] for w in t.split()]) for t in texts]

value_fn = BertScoreValue(encoder=Axes())
score = value_fn.score(GenerationRecord(text="cat dog"), GenerationRecord(text="pet"))
print(round(score, 4))

Output

0.7467

Spoken answers

speech_bertscore matches WavLM frames of both answers’ audio greedily by cosine (precision), so recordings need not align (extra audio-semantic). transcribed transcribes both answers with a fixed recognizer and scores the text with a wrapped value function, ignoring how they sound:

explanation:
  value_fn: transcribed
  plugin_options:
    transcribed: {value_fn: bertscore, recognizer: openai/whisper-base}

Both read GenerationRecord.audio_path, so far set only by custom backends.

Judge reference

judge_grade asks a judge (any backend; options backend, model_id) how well an answer keeps \(y_N\)’s meaning, 1 to 5, and returns the probability-weighted grade, which rarely ties. It reads digit probabilities under teacher forcing, else averages samples generations. One call per distinct answer; above max_coalitions (2000) answers it refuses unless allow_large_judge. Use it on a subset to check cheaper functions.

Word error rate and faithfulness

reference_wer scores correctness against option reference: the exact transcript earns 1, ignoring case and punctuation. word_error_rate() is the bare metric.

deletion_curve() removes the top k players at once, for each k, and rescores the rest; a lower area means the value falls sooner. Use another value function than the explanation’s, or the check is circular. backend= reuses the explained run’s model:

curve = await deletion_curve(wer_config, snapshot, output.result.values)
print(curve.removed, curve.values, round(curve.area, 3))

compute_removal_metrics() takes a payoff function instead. On an additive game over “Cancel my old phone plan today”, the true ranking drops the value at once, the reversed one holds it:

import numpy as np

from mllm_shap import compute_removal_metrics

words = "Cancel my old phone plan today".split()
weights = np.random.default_rng(1).uniform(-1.0, 2.0, len(words))

def game(present):
    return float(weights @ np.asarray(present, dtype=float))

curves = {
    label: compute_removal_metrics(ranking, game)
    for label, ranking in (("true ranking", weights), ("reversed ranking", -weights))
}
for label, metrics in curves.items():
    print(f"{label}: deletion area {metrics.deletion_area:.2f}")

Output

true ranking: deletion area 0.43
reversed ranking: deletion area 3.44
Code for this figure
import matplotlib.pyplot as plt

fig, ax = plt.subplots(figsize=(5.5, 3))
for label, metrics in curves.items():
    ax.plot(metrics.ks, metrics.deletion_values, marker="o", label=label)
ax.set_xlabel("top-k players removed")
ax.set_ylabel("v(S) of the rest")
ax.legend()

Deletion curves of an additive game, weights drawn with seed 1

Two deletion curves over six players. The true ranking falls from 3.9 to near 0 after two removals; the reversed ranking stays near 4 until four removals.

removal_metrics() is the model version (RemovalMetrics): deletion and insertion curves, comprehensiveness, sufficiency, normalised aopc, win rate against size-matched random sets and, with threshold, the smallest flip and restore sets. explained_with flags a circular check. Notebook: Faithfulness checks, margins and pairwise interactions.

Normalizers

Normalizers rescale attributions for display and leave payoffs alone, so base_value and grand_value compare across them. Values add up only under identity.

from mllm_shap import MinMaxNormalizer

raw = [1.0, -2.0, 3.0]
displayed = MinMaxNormalizer().normalize(raw)
print(displayed)

Output

[0.37499999999999994, 0.0, 0.625]

Keys and transforms: Value functions and normalizers; every function and normalizer on one archive: Run archives and reanalyze.

Choosing a value function

By what the backend returns and what the answer looks like:

Use case

Situation

value_fn

Measures

U1

Logits available; fidelity to the explained model

tf_logprob

Mean log probability of \(y_N\) under the coalition prompt

U2

Logits available; shifts among alternative answers

tf_jsd

Jensen-Shannon shift of the next-token distributions over \(y_N\)

U3

Text output only, free-form answers

bertscore

BERTScore F1 of the coalition answer against \(y_N\)

U4

Short factual or yes/no answers

nli_logodds

Entailment log-odds in both directions; catches negation

U5

One decision, such as refusing or choosing an option

contrastive, label_margin

Log-odds of a target continuation against a foil, or against a label set

U6

Speech transcription

semascore

Segment-aligned cosine times one minus character error

U7

Spoken output

speech_bertscore, transcribed

SpeechBERTScore on audio; or any text value function on transcripts

U8

Validation reference on subsets

judge_grade

Expected grade of a judge model; never at dataset scale

Baselines: tfidf_cosine (shared rare words, as TokenSHAP), embedding_cosine, reference_wer, self_logprob. A cheaper function whose attributions correlate above 0.9 with a costlier one can replace it; test that on your data with reanalyze and rescore.