Value functions

Coalition utility scoring plugins.

@domain value @see [[knowledge/architecture/value]]

Frozen-corpus TF-IDF cosine value function.

@domain value @see [[knowledge/architecture/value]] @tested-by [[tests/value/test_tfidf.py]]

class mllm_shap.value.tfidf.TfIdfCosineValue(context: PluginContext | None = None)[source]

Bases: object

Score generations with cosine similarity of frozen TF-IDF vectors.

options_model

alias of PluginOptions

info: ClassVar[ValueInfo] = ValueInfo(value_range=(0.0, 1.0), reads_base=True, needs=(), extra_model='', cost='text', higher_is_better=True)

Accepts no explanation.plugin_options.

property name: str

Return the registered value-function identifier.

fit(corpus: Sequence[GenerationRecord]) → None[source]

Freeze inverse document frequency weights from corpus.

score(base: GenerationResult, candidate: GenerationResult) → float[source]

Return TF-IDF cosine similarity between candidate and base.

Embedding-cosine value function.

@domain value @see [[knowledge/architecture/value]] @tested-by [[tests/value/test_embedding.py]]

mllm_shap.value.embedding.MODEL_STATES = 'model_states'

encoder value that scores the explained model’s own pooled states.

mllm_shap.value.embedding.DEFAULT_ENCODER = 'all-MiniLM-L6-v2'

Sentence-transformers model scored by default, as in MExGen and llmSHAP.

class mllm_shap.value.embedding.EmbeddingOptions(*, encoder: str = 'all-MiniLM-L6-v2', allow_hash_embeddings: bool = False)[source]

Bases: PluginOptions

Options of the embedding_cosine value function.

encoder: str

Sentence-transformers model name, or model_states for the pooled input or last-layer states of the explained model (the pre-0.7 behaviour).

allow_hash_embeddings: bool

Let model_states score the 8-dimensional hash vectors of backends without model states (mock, LM Studio, API); they carry no meaning.

model_config = {'extra': 'forbid', 'frozen': True, 'strict': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class mllm_shap.value.embedding.CosineEmbeddingValue(context: PluginContext | None = None, embedding_mode: EmbeddingMode = EmbeddingMode.STATIC, provider: EmbeddingProvider | None = None, encoder: SentenceEncoder | None = None)[source]

Bases: object

Cosine similarity between sentence embeddings of two answers.

With a sentence encoder (default all-MiniLM-L6-v2, extra mllm-shap[semantic]) both answers are embedded from their text, so explain and reanalyze agree. With encoder: model_states it compares the static or contextual embeddings the backend attaches to each record (explanation.embedding_mode); built without a context it defaults to that mode, so records carry their own vectors.

options_model

Options accepted from explanation.plugin_options.

alias of EmbeddingOptions

registered_name: ClassVar[str] = 'embedding_cosine'

Registered value-function identifier.

info: ClassVar[ValueInfo] = ValueInfo(value_range=(-1.0, 1.0), reads_base=True, needs=('embeddings',), extra_model='sentence-transformers encoder (default all-MiniLM-L6-v2)', cost='encoder', higher_is_better=True)
allow_hash_embeddings

Whether hash vectors of a backend without model states may be scored.

property name: str

Return the registered value-function identifier.

property needs_embeddings: bool

True only for encoder: model_states, which reads backend vectors.

manifest_info() → dict[str, str][source]

Return the encoder and its library version for the run manifest.

score(base: GenerationResult, candidate: GenerationResult) → float[source]

Return the cosine similarity of the two embedding vectors.

Self-confidence value function from generated-token logprobs.

@domain value @see [[knowledge/architecture/value]] @tested-by [[tests/value/test_logprob.py]]

class mllm_shap.value.logprob.SelfLogprobValue(context: PluginContext | None = None)[source]

Bases: object

Score a coalition by the model’s confidence in its own generation.

v(S) is the mean natural-log probability of the tokens the backend generated for coalition S (its GenerationRecord.logprobs), so it lies in (-inf, 0]; an empty generation scores 0. The base generation is not read: v(N) is the base generation’s own mean logprob.

options_model

Accepts no explanation.plugin_options.

alias of PluginOptions

registered_name: ClassVar[str] = 'self_logprob'

Registered value-function identifier.

info: ClassVar[ValueInfo] = ValueInfo(value_range=(-inf, 0.0), reads_base=False, needs=('logprobs',), extra_model='', cost='text', higher_is_better=True)
property name: str

Return the registered value-function identifier.

property needs_logprobs: bool

Always true; scoring reads GenerationRecord.logprobs.

score(base: GenerationResult, candidate: GenerationResult) → float[source]

Return the mean token logprob of candidate.

Raises:

LogprobsUnavailableError – If candidate carries no logprobs.

class mllm_shap.value.logprob.LogprobValue(context: PluginContext | None = None)[source]

Bases: SelfLogprobValue

Deprecated name of SelfLogprobValue, kept for one minor version.

It measures confidence in the coalition’s own answer and ignores \(y_N\); use tf_logprob for fidelity to the full-input answer.

registered_name: ClassVar[str] = 'logprob'

Registered value-function identifier.

Teacher-forced value functions: log probability and Jensen-Shannon shift of y_N.

@domain value @see [[knowledge/architecture/value]] @tested-by [[tests/value/test_teacher_forced.py]]

mllm_shap.value.teacher_forced.forced_for(result: GenerationResult, continuation: str, value_fn: str) → ForcedScore[source]

Return the teacher-forced score of continuation held by result.

Raises:

BackendUnavailableError – If the generation carries no such score.

class mllm_shap.value.teacher_forced.TeacherForcedValue[source]

Bases: object

Shared declarations of value functions that score y_N by forcing.

options_model

Accepts no explanation.plugin_options.

alias of PluginOptions

registered_name: ClassVar[str]

Registered value-function identifier.

property name: str

Return the registered value-function identifier.

property needs_teacher_forcing: bool

Always true; scoring reads GenerationRecord.forced.

property reads_candidate_text: bool

Always false; coalition answers are never generated.

property forced_top_k: int

Return how many next-token candidates per position to request.

forced_continuations(base: GenerationResult) → tuple[str, ...][source]

Return the base answer \(y_N\) as the continuation to score.

class mllm_shap.value.teacher_forced.TfLogprobOptions(*, reduce: Literal['mean', 'sum'] = 'mean')[source]

Bases: PluginOptions

Options of the tf_logprob value function.

reduce: Literal['mean', 'sum']

Average (default) or add the log probabilities of the answer tokens.

model_config = {'extra': 'forbid', 'frozen': True, 'strict': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class mllm_shap.value.teacher_forced.TfLogprobValue(context: PluginContext | None = None)[source]

Bases: TeacherForcedValue

Score \(v(S) = \frac1\ell\sum_t \log p(y_{N,t} \mid y_{N,<t}, x_S)\).

The full-input answer \(y_N\) is scored under the coalition prompt \(x_S\) by one forward pass; no coalition answer is generated. An empty \(y_N\) scores 0. reduce: sum drops the \(1/\ell\) factor.

options_model

Options accepted from explanation.plugin_options.

alias of TfLogprobOptions

registered_name: ClassVar[str] = 'tf_logprob'

Registered value-function identifier.

info: ClassVar[ValueInfo] = ValueInfo(value_range=(-inf, 0.0), reads_base=True, needs=('teacher_forcing',), extra_model='', cost='forward', higher_is_better=True)
reduce

Whether token log probabilities are averaged or added.

score(base: GenerationResult, candidate: GenerationResult) → float[source]

Return the teacher-forced log probability of base under candidate.

class mllm_shap.value.teacher_forced.TfJsdOptions(*, top_k: int = 20)[source]

Bases: PluginOptions

Options of the tf_jsd value function.

top_k: int

Next-token candidates kept per position; the rest is one bucket.

model_config = {'extra': 'forbid', 'frozen': True, 'strict': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class mllm_shap.value.teacher_forced.TfJsdValue(context: PluginContext | None = None)[source]

Bases: TeacherForcedValue

Score \(v(S) = -\sum_t \mathrm{JSD}(P_N(\cdot) \Vert P_S(\cdot))\).

\(P_N\) and \(P_S\) are the next-token distributions at each position of \(y_N\) under the full prompt and the coalition prompt, so \(v(N) = 0\) and each position costs at most \(\log 2\). Each distribution is its top_k tokens plus one bucket for the remaining mass, so the divergence is exact once top_k covers the vocabulary and a lower bound otherwise.

options_model

Options accepted from explanation.plugin_options.

alias of TfJsdOptions

registered_name: ClassVar[str] = 'tf_jsd'

Registered value-function identifier.

info: ClassVar[ValueInfo] = ValueInfo(value_range=(-inf, 0.0), reads_base=True, needs=('teacher_forcing',), extra_model='', cost='forward', higher_is_better=True)
property forced_top_k: int

Return the configured top_k.

score(base: GenerationResult, candidate: GenerationResult) → float[source]

Return minus the summed Jensen-Shannon divergence over the answer.

Contrastive log-odds of a target answer against a foil or a label set.

@domain value @see [[knowledge/architecture/value]] @tested-by [[tests/value/test_teacher_forced.py]]

class mllm_shap.value.contrastive.ContrastiveOptions(*, target: str, foil: str)[source]

Bases: PluginOptions

Options of the contrastive value function.

target: str

Continuation whose probability the explanation raises, such as "I can't".

foil: str

Alternative continuation it is weighed against, such as "Sure".

model_config = {'extra': 'forbid', 'frozen': True, 'strict': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class mllm_shap.value.contrastive.ContrastiveValue(context: PluginContext)[source]

Bases: TeacherForcedValue

Score \(v(S) = \log p(t \mid x_S) - \log p(f \mid x_S)\).

\(t\) and \(f\) are the target and foil continuations; each probability is the product of its token probabilities under the coalition prompt, from one forward pass per continuation. The base generation is not read.

options_model

Options accepted from explanation.plugin_options.

alias of ContrastiveOptions

registered_name: ClassVar[str] = 'contrastive'

Registered value-function identifier.

info: ClassVar[ValueInfo] = ValueInfo(value_range=(-inf, inf), reads_base=False, needs=('teacher_forcing',), extra_model='', cost='forward', higher_is_better=True)
target

Continuation raised by the explanation.

foil

Continuation it is contrasted with.

forced_continuations(base: GenerationResult) → tuple[str, ...][source]

Return the target and the foil.

score(base: GenerationResult, candidate: GenerationResult) → float[source]

Return the log-odds of the target against the foil.

class mllm_shap.value.contrastive.LabelMarginOptions(*, target: str, labels: list[str])[source]

Bases: PluginOptions

Options of the label_margin value function.

target: str

Label whose probability the explanation raises.

labels: list[str]

Every label of the task, including target; at least two, all distinct.

model_config = {'extra': 'forbid', 'frozen': True, 'strict': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class mllm_shap.value.contrastive.LabelMarginValue(context: PluginContext)[source]

Bases: ContrastiveValue

Score \(v(S) = \log p(t \mid x_S) - \log \sum_{l \ne t} p(l \mid x_S)\).

The target label against the combined probability of the other labels of a closed-answer task, each label scored by one forward pass. With two labels it equals contrastive.

options_model

Options accepted from explanation.plugin_options.

alias of LabelMarginOptions

registered_name: ClassVar[str] = 'label_margin'

Registered value-function identifier.

target

Label raised by the explanation.

labels

Every label of the task.

forced_continuations(base: GenerationResult) → tuple[str, ...][source]

Return the target followed by the other labels.

score(base: GenerationResult, candidate: GenerationResult) → float[source]

Return the log-odds of the target against the other labels.

BERTScore F1 between a coalition answer and the full-input answer.

@domain value @see [[knowledge/architecture/value]] @tested-by [[tests/value/test_semantic.py]]

class mllm_shap.value.bertscore.BertScoreOptions(*, encoder: str = 'roberta-large', layer: int = 17, baseline: float | None = None, revision: str = 'main')[source]

Bases: PluginOptions

Options of the bertscore value function.

encoder: str

Hugging Face encoder whose hidden states are matched.

layer: int

Hidden layer used (17 is the reference package’s choice for roberta-large).

baseline: float | None

Baseline F1 of unrelated pairs; the score becomes (F1 - b) / (1 - b).

revision: str

Hub revision of the model; pin a commit to reproduce runs.

model_config = {'extra': 'forbid', 'frozen': True, 'strict': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class mllm_shap.value.bertscore.BertScoreValue(context: PluginContext | None = None, encoder: TokenEncoder | None = None)[source]

Bases: object

Score \(v(S) = F_1\) of greedy token matching against \(y_N\).

Recall averages, over \(y_N\) tokens, the best cosine similarity to a token of \(y_S\); precision does the reverse; \(F_1\) is their harmonic mean (Zhang et al., 2020). Special tokens are dropped and no IDF weighting is applied, as in the reference package’s default. The pipeline calls fit() so all answers of an instance are encoded in batches.

options_model

Options accepted from explanation.plugin_options.

alias of BertScoreOptions

info: ClassVar[ValueInfo] = ValueInfo(value_range=(-1.0, 1.0), reads_base=True, needs=(), extra_model='Hugging Face encoder (default roberta-large)', cost='encoder', higher_is_better=True)
property name: str

Return the registered value-function identifier.

manifest_info() → dict[str, str][source]

Return encoder, layer, baseline and library version for the manifest.

fit(corpus: Sequence[GenerationRecord]) → None[source]

Encode every distinct answer of the run in batches.

score(base: GenerationResult, candidate: GenerationResult) → float[source]

Return the (optionally rescaled) BERTScore F1 of candidate.

Bidirectional entailment log-odds between a coalition answer and the full one.

@domain value @see [[knowledge/architecture/value]] @tested-by [[tests/value/test_semantic.py]]

class mllm_shap.value.nli.NliOptions(*, model: str = 'microsoft/deberta-large-mnli', question: str | None = None, revision: str = 'main')[source]

Bases: PluginOptions

Options of the nli_logodds value function.

model: str

Hugging Face natural-language-inference model.

question: str | None

Prepended to both answers so entailment is judged in context.

revision: str

Hub revision of the model; pin a commit to reproduce runs.

model_config = {'extra': 'forbid', 'frozen': True, 'strict': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class mllm_shap.value.nli.NliLogOddsValue(context: PluginContext | None = None, model: NliModel | None = None)[source]

Bases: object

Score the log-odds that the two answers entail each other.

With \(p_\to\) the probability that \(y_N\) entails \(y_S\) and \(p_\leftarrow\) the reverse, \(p = \sqrt{p_\to p_\leftarrow}\) and \(v(S) = \log\frac{p}{1-p}\), as the Log NLI score of MExGen. A negated answer scores low where similarity scores stay high. The pipeline calls fit() so all pairs of an instance are scored in batches.

options_model

Options accepted from explanation.plugin_options.

alias of NliOptions

info: ClassVar[ValueInfo] = ValueInfo(value_range=(-13.815510557964274, 13.815510557964274), reads_base=True, needs=(), extra_model='Hugging Face NLI model (default deberta-large-mnli)', cost='encoder', higher_is_better=True)
property name: str

Return the registered value-function identifier.

manifest_info() → dict[str, str][source]

Return the NLI model and question for the run manifest.

fit(corpus: Sequence[GenerationRecord]) → None[source]

Score every answer pair of the run in batches.

score(base: GenerationResult, candidate: GenerationResult) → float[source]

Return the log-odds of mutual entailment.

SeMaScore: segment-aligned, importance-weighted meaning score for transcripts.

@domain value @see [[knowledge/architecture/value]] @tested-by [[tests/value/test_semantic.py]]

mllm_shap.value.semascore.align_segments(reference: Sequence[str], hypothesis: Sequence[str]) → list[tuple[tuple[int, int], tuple[int, int]]][source]

Align two word lists into segment pairs of half-open word spans.

A word-level edit-distance path is cut into matches (one word on each side) and runs of consecutive errors, which form one segment so a split or merged word (two words against one) is compared as a unit. A run that inserts or deletes only has an empty span on one side.

class mllm_shap.value.semascore.SemaScoreOptions(*, reference: str | None = None, encoder: str = 'roberta-base', revision: str = 'main')[source]

Bases: PluginOptions

Options of the semascore value function.

reference: str | None

Target transcript; None scores against the full-input answer.

encoder: str

Hugging Face encoder of contextual word vectors.

revision: str

Hub revision of the model; pin a commit to reproduce runs.

model_config = {'extra': 'forbid', 'frozen': True, 'strict': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class mllm_shap.value.semascore.SemaScoreValue(context: PluginContext | None = None, encoder: WordEncoder | None = None)[source]

Bases: object

Score a transcript by aligned segments weighted by their importance.

For each aligned segment pair \((g_i, h_i)\) the segment score is \(\cos(e_{g_i}, e_{h_i})(1 - \mathrm{MER}_i)\), with \(\mathrm{MER}_i\) the character edit distance over the longer segment, and its weight is \(\alpha_i = \max(0, \cos(e_{g_i}, e_y))\), the segment’s closeness to the whole reference (Sasindran et al., 2024). \(v(S) = \sum_i \alpha_i \mathrm{SS}_i / \sum_i \alpha_i\). Word vectors are the mean of the sub-word states of the encoder’s last layer. An empty reference scores 1 for an empty hypothesis and 0 otherwise.

options_model

Options accepted from explanation.plugin_options.

alias of SemaScoreOptions

info: ClassVar[ValueInfo] = ValueInfo(value_range=(0.0, 1.0), reads_base=True, needs=(), extra_model='Hugging Face encoder (default roberta-base)', cost='encoder', higher_is_better=True)
property name: str

Return the registered value-function identifier.

manifest_info() → dict[str, str][source]

Return the encoder for the run manifest.

fit(corpus: Sequence[GenerationRecord]) → None[source]

Encode every distinct answer of the run in batches.

score(base: GenerationResult, candidate: GenerationResult) → float[source]

Return the importance-weighted segment score of candidate.

Speech value functions: SpeechBERTScore on audio and the transcription adapter.

@domain value @see [[knowledge/architecture/value]] @tested-by [[tests/value/test_speech.py]]

class mllm_shap.value.speech.SpeechBertScoreOptions(*, encoder: str = 'microsoft/wavlm-large', layer: int = 14, revision: str = 'main')[source]

Bases: PluginOptions

Options of the speech_bertscore value function.

encoder: str

Self-supervised speech model whose frames are matched.

layer: int

Hidden layer used; scores depend on it, so it is recorded in the manifest.

revision: str

Hub revision of the model; pin a commit to reproduce runs.

model_config = {'extra': 'forbid', 'frozen': True, 'strict': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class mllm_shap.value.speech.SpeechBertScoreValue(context: PluginContext | None = None, encoder: SpeechEncoder | None = None)[source]

Bases: object

Score \(v(S)\) as the SpeechBERTScore precision of the spoken answer.

Every frame of the coalition’s audio takes its best cosine match among the frames of the full-input answer’s audio, and \(v(S)\) is the mean (Saeki et al., 2024). The two recordings need not align or share a length. Records must carry audio_path.

options_model

Options accepted from explanation.plugin_options.

alias of SpeechBertScoreOptions

info: ClassVar[ValueInfo] = ValueInfo(value_range=(-1.0, 1.0), reads_base=True, needs=('audio',), extra_model='WavLM-style speech encoder (default wavlm-large)', cost='encoder', higher_is_better=True)
property name: str

Return the registered value-function identifier.

manifest_info() → dict[str, str][source]

Return the encoder and layer for the run manifest.

score(base: GenerationResult, candidate: GenerationResult) → float[source]

Return the mean best-match cosine of candidate’s frames.

class mllm_shap.value.speech.TranscribedOptions(*, value_fn: str, recognizer: str = 'openai/whisper-base', inner_options: dict[str, object]=<factory>)[source]

Bases: PluginOptions

Options of the transcribed adapter.

value_fn: str

Text value function applied to the transcripts, such as bertscore.

recognizer: str

Hugging Face speech-recognition model that transcribes both answers.

inner_options: dict[str, object]

plugin_options of the wrapped value function.

model_config = {'extra': 'forbid', 'frozen': True, 'strict': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class mllm_shap.value.speech.TranscribedValue(context: PluginContext, recognizer: Recognizer | None = None)[source]

Bases: object

Score spoken answers by transcribing them and applying a text value function.

It answers content-only questions: the fixed recogniser removes how the answer sounds. The wrapped function sees records whose text is the transcript (audio_path is dropped), and is fitted on the transcripts when it needs it.

options_model

Options accepted from explanation.plugin_options.

alias of TranscribedOptions

info: ClassVar[ValueInfo] = ValueInfo(value_range=(-inf, inf), reads_base=True, needs=('audio',), extra_model='speech recognizer (default whisper-base) plus the wrapped one', cost='encoder', higher_is_better=True)
property name: str

Return the registered value-function identifier.

manifest_info() → dict[str, str][source]

Return the recognizer and wrapped value function for the manifest.

fit(corpus: Sequence[GenerationRecord]) → None[source]

Transcribe every answer, then fit the wrapped value function on them.

score(base: GenerationResult, candidate: GenerationResult) → float[source]

Return the wrapped value function on the two transcripts.

Expected-grade value function from a judge model’s score probabilities.

@domain value @see [[knowledge/architecture/value]] @tested-by [[tests/value/test_judge.py]]

mllm_shap.value.judge.GRADES = ('1', '2', '3', '4', '5')

Scores the judge may give.

class mllm_shap.value.judge.JudgeOptions(*, backend: str, model_id: str, backend_options: dict[str, object]=<factory>, samples: int = 20, allow_large_judge: bool = False, max_coalitions: int = 2000)[source]

Bases: PluginOptions

Options of the judge_grade value function.

backend: str

Registered backend kind of the judge, such as transformers.

model_id: str

Judge model name passed to that backend.

backend_options: dict[str, object]

backend.options of the judge backend.

samples: int

Graded generations averaged when the judge backend returns no logits.

allow_large_judge: bool

Allow more than max_coalitions distinct answers per run.

max_coalitions: int

Distinct answers above which the judge refuses to run.

model_config = {'extra': 'forbid', 'frozen': True, 'strict': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class mllm_shap.value.judge.JudgeGradeValue(context: PluginContext, judge: GenerativeBackend | None = None)[source]

Bases: object

Score \(v(S) = \sum_g g\,p(g)\) for a judge’s grade distribution.

A judge model is asked how well \(y_S\) preserves the meaning of \(y_N\) on a 1 to 5 scale. With a judge backend that scores continuations, \(p(g)\) is its probability of each digit, renormalised over 1 to 5; otherwise samples graded generations are averaged. The result is continuous, so it has few ties (G-Eval), but it carries the judge’s position and length biases and costs a model call per coalition: it is a reference for small subsets, guarded at max_coalitions distinct answers.

options_model

Options accepted from explanation.plugin_options.

alias of JudgeOptions

info: ClassVar[ValueInfo] = ValueInfo(value_range=(1.0, 5.0), reads_base=True, needs=('judge',), extra_model='judge model (any backend; logits preferred)', cost='judge', higher_is_better=True)
property name: str

Return the registered value-function identifier.

manifest_info() → dict[str, str][source]

Return the judge backend and model for the run manifest.

async prepare(base: GenerationRecord, corpus: Sequence[GenerationRecord]) → None[source]

Grade every distinct answer of the run against the base answer.

Raises:

ConfigError – If the run has more distinct answers than max_coalitions and allow_large_judge is false.

score(base: GenerationResult, candidate: GenerationResult) → float[source]

Return the cached expected grade of candidate.

Raises:

ConfigError – If prepare has not graded this pair.

async aclose() → None[source]

Release the judge backend.

Lazy loaders of the sentence and token encoders behind semantic value functions.

@domain value @see [[knowledge/architecture/value]] @tested-by [[tests/value/test_semantic.py]]

mllm_shap.value.encoders.AUDIO_EXTRA = "pip install 'mllm-shap[audio-semantic]'"

Install hint shown when a speech encoder library is missing.

mllm_shap.value.encoders.SEMANTIC_EXTRA = "pip install 'mllm-shap[semantic]'"

Install hint shown when an encoder library is missing.

class mllm_shap.value.encoders.SentenceEncoder(*args, **kwargs)[source]

Bases: Protocol

Map texts to one vector each.

encode(texts: Sequence[str]) → NDArray[floating][source]

Return an (len(texts), dim) array.

class mllm_shap.value.encoders.TokenEncoder(*args, **kwargs)[source]

Bases: Protocol

Map texts to one matrix of unit-length token vectors each.

encode(texts: Sequence[str]) → list[NDArray[floating]][source]

Return an (n_tokens, dim) array per text, special tokens removed.

mllm_shap.value.encoders.load_sentence_encoder(name: str) → SentenceEncoder[source]

Load a sentence-transformers model once per process.

Raises:

BackendUnavailableError – If sentence-transformers is not installed.

mllm_shap.value.encoders.load_token_encoder(name: str, layer: int, revision: str = 'main') → TokenEncoder[source]

Load a Hugging Face encoder and expose layer layer as token vectors.

Raises:

BackendUnavailableError – If transformers is not installed.

class mllm_shap.value.encoders.WordEncoder(*args, **kwargs)[source]

Bases: Protocol

Map word lists to one contextual vector per word.

encode(sentences: Sequence[Sequence[str]]) → list[NDArray[floating]][source]

Return an (n_words, dim) array per sentence.

mllm_shap.value.encoders.load_word_encoder(name: str, revision: str = 'main') → WordEncoder[source]

Load a Hugging Face encoder that pools sub-words into word vectors.

Raises:

BackendUnavailableError – If transformers is not installed.

class mllm_shap.value.encoders.NliModel(*args, **kwargs)[source]

Bases: Protocol

Score entailment between premise and hypothesis.

entailment(pairs: Sequence[tuple[str, str]]) → list[float][source]

Return P(premise entails hypothesis) for each pair.

mllm_shap.value.encoders.load_nli_model(name: str, revision: str = 'main') → NliModel[source]

Load a Hugging Face sequence-classification NLI model.

Raises:

BackendUnavailableError – If transformers is not installed.

class mllm_shap.value.encoders.SpeechEncoder(*args, **kwargs)[source]

Bases: Protocol

Map a waveform file to unit-length frame vectors.

encode(path: str) → NDArray[floating][source]

Return an (n_frames, dim) array.

class mllm_shap.value.encoders.Recognizer(*args, **kwargs)[source]

Bases: Protocol

Transcribe a waveform file.

transcribe(path: str) → str[source]

Return the spoken words.

mllm_shap.value.encoders.load_speech_encoder(name: str, layer: int, revision: str = 'main') → SpeechEncoder[source]

Load a self-supervised speech model and expose layer layer frames.

Raises:

BackendUnavailableError – If transformers is not installed.

mllm_shap.value.encoders.load_recognizer(name: str, revision: str = 'main') → Recognizer[source]

Load a Hugging Face speech-recognition pipeline.

Raises:

BackendUnavailableError – If transformers is not installed.

Word error rate against a reference text as a coalition value.

@domain value @see [[knowledge/architecture/value]] @tested-by [[tests/value/test_wer.py]]

mllm_shap.value.wer.word_error_rate(reference: str, hypothesis: str) → float[source]

Return word-level edit distance over the reference’s word count.

Words are lowercased runs of letters, digits, _ and ', so case and punctuation do not count. An empty reference gives 0 for an empty hypothesis and 1 otherwise.

class mllm_shap.value.wer.ReferenceWerOptions(*, reference: str | None = None)[source]

Bases: PluginOptions

Options of the reference_wer value function.

reference: str | None

Target text, such as a transcript; None uses the full coalition’s answer.

model_config = {'extra': 'forbid', 'frozen': True, 'strict': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class mllm_shap.value.wer.ReferenceWerValue(context: PluginContext | None = None)[source]

Bases: object

Score 1 - min(1, WER) of a coalition’s answer against a reference.

With reference set, v(S) measures how correct the answer is (a transcription task); without it, how close it stays to the full answer. Values lie in [0, 1].

options_model

Options accepted from explanation.plugin_options.

alias of ReferenceWerOptions

info: ClassVar[ValueInfo] = ValueInfo(value_range=(0.0, 1.0), reads_base=True, needs=(), extra_model='', cost='text', higher_is_better=True)
reference

Target text; None scores against the base generation.

property name: str

Return the registered value-function identifier.

score(base: GenerationResult, candidate: GenerationResult) → float[source]

Return 1 - min(1, WER) of candidate against the target.

Build generation records from generated text for value-function scoring.

@domain value @see [[knowledge/architecture/value]] @tested-by [[tests/value/test_generation_records.py]]

mllm_shap.value.generation_records.EMBED_DIM: Final[int] = 8

Dimension of the deterministic hash embedding used by mock and archive paths.

mllm_shap.value.generation_records.generation_record_from_text(text: str, context_id: str | None = None) → GenerationRecord[source]

Build a record whose token rows and embeddings derive from text only.

explain and reanalyze both score records built here, so a value function sees the same inputs whether the text came from a backend or an archive. contextual_embedding hashes text with a separator so it differs from embedding; it takes no prompt or snapshot id, which a backend sees for the rendered coalition and reanalyze never sees.

Parameters:
  • text – Generated text.

  • context_id – Deprecated and ignored; passing it emits a DeprecationWarning. It salted contextual_embedding until 0.1.18, which made backend records differ from reanalyze.

mllm_shap.value.generation_records.stable_token_id(token: str) → int[source]

Return a process-independent 56-bit id for token.

mllm_shap.value.generation_records.hash_embedding(payload: str) → tuple[float, ...][source]

Map payload to a fixed-size float vector in [-1, 1] via SHA-256.