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:
objectScore 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.
- 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
candidateandbase.
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'¶
encodervalue 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:
PluginOptionsOptions of the
embedding_cosinevalue function.- encoder: str¶
Sentence-transformers model name, or
model_statesfor the pooled input or last-layer states of the explained model (the pre-0.7 behaviour).
- allow_hash_embeddings: bool¶
Let
model_statesscore 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:
objectCosine similarity between sentence embeddings of two answers.
With a sentence
encoder(defaultall-MiniLM-L6-v2, extramllm-shap[semantic]) both answers are embedded from their text, soexplainandreanalyzeagree. Withencoder: model_statesit compares the static or contextual embeddings the backend attaches to each record (explanation.embedding_mode); built without acontextit defaults to that mode, so records carry their own vectors.- options_model¶
Options accepted from
explanation.plugin_options.alias of
EmbeddingOptions
- 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.
- 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:
objectScore 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 coalitionS(itsGenerationRecord.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
- info: ClassVar[ValueInfo] = ValueInfo(value_range=(-inf, 0.0), reads_base=False, needs=('logprobs',), extra_model='', cost='text', higher_is_better=True)¶
- score(base: GenerationResult, candidate: GenerationResult) float[source]¶
Return the mean token logprob of
candidate.- Raises:
LogprobsUnavailableError – If
candidatecarries no logprobs.
- class mllm_shap.value.logprob.LogprobValue(context: PluginContext | None = None)[source]¶
Bases:
SelfLogprobValueDeprecated name of
SelfLogprobValue, kept for one minor version.It measures confidence in the coalition’s own answer and ignores \(y_N\); use
tf_logprobfor fidelity to the full-input answer.
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
continuationheld byresult.- Raises:
BackendUnavailableError – If the generation carries no such score.
- class mllm_shap.value.teacher_forced.TeacherForcedValue[source]¶
Bases:
objectShared declarations of value functions that score
y_Nby forcing.- options_model¶
Accepts no
explanation.plugin_options.alias of
PluginOptions
- 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:
PluginOptionsOptions of the
tf_logprobvalue 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:
TeacherForcedValueScore \(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: sumdrops the \(1/\ell\) factor.- options_model¶
Options accepted from
explanation.plugin_options.alias of
TfLogprobOptions
- 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
baseundercandidate.
- class mllm_shap.value.teacher_forced.TfJsdOptions(*, top_k: int = 20)[source]¶
Bases:
PluginOptionsOptions of the
tf_jsdvalue 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.teacher_forced.TfJsdValue(context: PluginContext | None = None)[source]¶
Bases:
TeacherForcedValueScore \(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_ktokens plus one bucket for the remaining mass, so the divergence is exact oncetop_kcovers the vocabulary and a lower bound otherwise.- options_model¶
Options accepted from
explanation.plugin_options.alias of
TfJsdOptions
- info: ClassVar[ValueInfo] = ValueInfo(value_range=(-inf, 0.0), reads_base=True, needs=('teacher_forcing',), extra_model='', cost='forward', higher_is_better=True)¶
- 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:
PluginOptionsOptions of the
contrastivevalue 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.contrastive.ContrastiveValue(context: PluginContext)[source]¶
Bases:
TeacherForcedValueScore \(v(S) = \log p(t \mid x_S) - \log p(f \mid x_S)\).
\(t\) and \(f\) are the
targetandfoilcontinuations; 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
- 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:
PluginOptionsOptions of the
label_marginvalue 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.contrastive.LabelMarginValue(context: PluginContext)[source]¶
Bases:
ContrastiveValueScore \(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
- 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:
PluginOptionsOptions of the
bertscorevalue 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.bertscore.BertScoreValue(context: PluginContext | None = None, encoder: TokenEncoder | None = None)[source]¶
Bases:
objectScore \(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)¶
- 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:
PluginOptionsOptions of the
nli_logoddsvalue 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.nli.NliLogOddsValue(context: PluginContext | None = None, model: NliModel | None = None)[source]¶
Bases:
objectScore 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)¶
- 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:
PluginOptionsOptions of the
semascorevalue 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.semascore.SemaScoreValue(context: PluginContext | None = None, encoder: WordEncoder | None = None)[source]¶
Bases:
objectScore 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)¶
- 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:
PluginOptionsOptions of the
speech_bertscorevalue 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.SpeechBertScoreValue(context: PluginContext | None = None, encoder: SpeechEncoder | None = None)[source]¶
Bases:
objectScore \(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)¶
- 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:
PluginOptionsOptions of the
transcribedadapter.- 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:
objectScore 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_pathis 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)¶
- 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:
PluginOptionsOptions of the
judge_gradevalue 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.judge.JudgeGradeValue(context: PluginContext, judge: GenerativeBackend | None = None)[source]¶
Bases:
objectScore \(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
samplesgraded 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 atmax_coalitionsdistinct 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)¶
- 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_coalitionsandallow_large_judgeis false.
- score(base: GenerationResult, candidate: GenerationResult) float[source]¶
Return the cached expected grade of
candidate.- Raises:
ConfigError – If
preparehas not graded this pair.
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:
ProtocolMap texts to one vector each.
- class mllm_shap.value.encoders.TokenEncoder(*args, **kwargs)[source]¶
Bases:
ProtocolMap texts to one matrix of unit-length token vectors each.
- mllm_shap.value.encoders.load_sentence_encoder(name: str) SentenceEncoder[source]¶
Load a sentence-transformers model once per process.
- Raises:
BackendUnavailableError – If
sentence-transformersis 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
layeras token vectors.- Raises:
BackendUnavailableError – If
transformersis not installed.
- class mllm_shap.value.encoders.WordEncoder(*args, **kwargs)[source]¶
Bases:
ProtocolMap word lists to one contextual vector per word.
- 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
transformersis not installed.
- class mllm_shap.value.encoders.NliModel(*args, **kwargs)[source]¶
Bases:
ProtocolScore entailment between premise and hypothesis.
- 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
transformersis not installed.
- class mllm_shap.value.encoders.SpeechEncoder(*args, **kwargs)[source]¶
Bases:
ProtocolMap a waveform file to unit-length frame vectors.
- class mllm_shap.value.encoders.Recognizer(*args, **kwargs)[source]¶
Bases:
ProtocolTranscribe a waveform file.
- 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
layerframes.- Raises:
BackendUnavailableError – If
transformersis 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
transformersis 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:
PluginOptionsOptions of the
reference_wervalue 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.wer.ReferenceWerValue(context: PluginContext | None = None)[source]¶
Bases:
objectScore
1 - min(1, WER)of a coalition’s answer against a reference.With
referenceset,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;
Nonescores against the base generation.
- score(base: GenerationResult, candidate: GenerationResult) float[source]¶
Return
1 - min(1, WER)ofcandidateagainst 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
textonly.explainandreanalyzeboth score records built here, so a value function sees the same inputs whether the text came from a backend or an archive.contextual_embeddinghashestextwith a separator so it differs fromembedding; it takes no prompt or snapshot id, which a backend sees for the rendered coalition andreanalyzenever sees.- Parameters:
text – Generated text.
context_id – Deprecated and ignored; passing it emits a
DeprecationWarning. It saltedcontextual_embeddinguntil 0.1.18, which made backend records differ fromreanalyze.