Masking¶
Coalition masking codecs, views, and absence policies.
@domain masking @see [[knowledge/architecture/masking]]
Player partition plugins: tokens, sentences, whole messages and image regions.
@domain masking @see [[knowledge/architecture/masking]] @tested-by [[tests/masking/test_partitions.py]]
- class mllm_shap.masking.partitions.RolesOptions(*, roles: list[Literal['user', 'assistant', 'system']] = ['user', 'assistant', 'system'])[source]¶
Bases:
PluginOptionsOptions of the
tokensandmessagespartitions.- roles: list[Literal['user', 'assistant', 'system']]¶
Roles whose text becomes players; other messages are always present.
- model_config = {'extra': 'forbid', 'frozen': True, 'strict': True}¶
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- mllm_shap.masking.partitions.MessagesOptions¶
Options of the
messagespartition (same fields astokens).
- class mllm_shap.masking.partitions.TokenPartitioner(context: PluginContext | None = None)[source]¶
Bases:
objectPartition a snapshot into whitespace-delimited text tokens.
- options_model¶
Options accepted from
explanation.plugin_options.alias of
RolesOptions
- roles¶
Roles whose tokens become players.
- partition(snapshot: ConversationSnapshot) PlayerSet[source]¶
Derive ordered token players and their spans from the snapshot text.
Tokens of messages whose role is not in
rolesare no players and stay present in every coalition; player ids do not depend on the filter.
- class mllm_shap.masking.partitions.SentencePartitioner(context: PluginContext | None = None)[source]¶
Bases:
objectPartition a snapshot into sentences, never crossing a blank line.
- options_model¶
Options accepted from
explanation.plugin_options.alias of
RolesOptions
- roles¶
Roles whose sentences become players.
- partition(snapshot: ConversationSnapshot) PlayerSet[source]¶
Derive one player per sentence of the selected roles.
A sentence ends at
.,!or?before whitespace or at the end of its paragraph. Player ids are{snapshot_id}:{turn}:{message}:{sentence}.
- mllm_shap.masking.partitions.sentence_bounds(text: str) list[tuple[int, int]][source]¶
Return the
[start, end)range of every sentence oftext, in order.
- mllm_shap.masking.partitions.LABEL_PREVIEW_CHARS: Final[int] = 30¶
Characters of the message text shown in a message player’s label.
- class mllm_shap.masking.partitions.MessagePartitioner(context: PluginContext | None = None)[source]¶
Bases:
objectPartition a snapshot into one player per non-empty message.
- options_model¶
Options accepted from
explanation.plugin_options.alias of
RolesOptions
- roles¶
Roles whose messages become players.
- partition(snapshot: ConversationSnapshot) PlayerSet[source]¶
Make each selected message a player whose span is its whole text.
Player ids are
{snapshot_id}:{turn}:{message}; labels read"<role>[/<speaker>] <n>: <first 30 characters>"withnthe 1-based message position.
- mllm_shap.masking.partitions.snapped_edges(length: int, count: int, grid: int, what: str, steps_of: str) list[int][source]¶
Return
count + 1edges cuttinglengthinto near-equalgridpieces.The last piece also takes the remainder below one
gridstep.- Raises:
ValueError – If
lengthholds fewer thancountgrid steps.
- class mllm_shap.masking.partitions.ImageGridOptions(*, rows: Annotated[int, Ge(ge=1)] = 2, cols: Annotated[int, Ge(ge=1)] = 3, snap_px: Annotated[int, Ge(ge=1)] = 28, question: bool = False)[source]¶
Bases:
PluginOptionsOptions of the
image_gridpartition.- snap_px: int¶
Pixel step of the cell edges, the processor’s patch size times its merge (28 for Qwen2.5-VL, 32 for Qwen3-Omni); cells may differ in size.
- 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.masking.partitions.ImageBoxOptions(*, boxes: Annotated[dict[str, list[list[float]]], MinLen(min_length=1)], background: bool = True, question: bool = False)[source]¶
Bases:
PluginOptionsOptions of the
image_boxespartition.- boxes: dict[str, list[list[float]]]¶
Boxes
[left, top, right, bottom]in pixels of each category in the first image, rounded outward to whole pixels (COCO’s[x, y, w, h]needs converting).
- 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.masking.partitions.ImageGridPartitioner(context: PluginContext | None = None)[source]¶
Bases:
objectCut every image into a grid of cells, one player each.
Each player’s span carries its cell as
regionand its image aspart; ids are{snapshot_id}:{turn}:{message}:i{part}:{row}:{col}, and question words get...:w{token}.- options_model¶
Options accepted from
explanation.plugin_options.alias of
ImageGridOptions
- partition(snapshot: ConversationSnapshot) PlayerSet[source]¶
Return the grid cells of every image (and question words) as players.
- Raises:
ValueError – If no message has an image, or an image has fewer
snap_pxsteps than rows or columns.
- class mllm_shap.masking.partitions.ImageBoxPartitioner(context: PluginContext | None = None)[source]¶
Bases:
objectMake each box category of the first image a player, plus the background.
A category covers the union of its boxes; where categories overlap, the one with the smaller area wins, so every pixel belongs to exactly one player. Ids are
{snapshot_id}:{turn}:{message}:i0:{category}.- options_model¶
Options accepted from
explanation.plugin_options.alias of
ImageBoxOptions
- partition(snapshot: ConversationSnapshot) PlayerSet[source]¶
Return one player per category (and the background) of the first image.
- Raises:
ValueError – If no message has an image, or a box has bad corners.
Two-level players: sentence groups (paragraphs or messages) and their members.
@domain masking @see [[knowledge/architecture/masking]] @tested-by [[tests/masking/test_hierarchy.py]]
- mllm_shap.masking.hierarchy.PREVIEW_CHARS = 30¶
Characters of the group text shown in its label.
- mllm_shap.masking.hierarchy.group_players(snapshot: ConversationSnapshot, players: PlayerSet, group_by: Literal['paragraph', 'message']) list[list[int]][source]¶
Return the player indices of each group, in text order.
A group is a paragraph (text between blank lines) of one message, or a whole message.
- mllm_shap.masking.hierarchy.coarse_player_set(snapshot: ConversationSnapshot, players: PlayerSet, groups: Sequence[Sequence[int]]) PlayerSet[source]¶
Return one player per group, spanning its first to its last member.
- mllm_shap.masking.hierarchy.refined_player_set(players: PlayerSet, groups: Sequence[Sequence[int]], kept: Sequence[int]) PlayerSet[source]¶
Return the members of the kept groups; other text stays present.
Whitespace token spans and span-based snapshot rendering.
@domain masking @see [[knowledge/architecture/masking]] @tested-by [[tests/masking/test_tokens.py]]
- mllm_shap.masking.tokens.token_spans(snapshot: ConversationSnapshot) tuple[tuple[str, PlayerSpan], ...][source]¶
Return
(player_id, span)for every whitespace token ofsnapshot.Player ids have the form
{snapshot_id}:{turn}:{message}:{token}.
- mllm_shap.masking.tokens.render_spans(snapshot: ConversationSnapshot, spans: Sequence[PlayerSpan], replacements: Sequence[str | None]) ConversationSnapshot[source]¶
Rebuild
snapshotwith each span replaced by its replacement text.Nonedeletes a span together with the whitespace that separated it from its neighbours, so deletingbfrom"a b c"gives"a c". Text no span covers is kept as is. Each text part is rendered in place, so media between text parts keep their position; a span that crosses two text parts merges the message’s text into one part. Imageregionspans carry no text and are skipped.- Raises:
ValueError – If
spansandreplacementsdiffer in length, or a span does not match the snapshot text.
Absence policies for rendering masked conversation snapshots.
@domain masking @see [[knowledge/architecture/masking]] @tested-by [[tests/masking/test_policies.py]]
- class mllm_shap.masking.policies.PadOptions(*, placeholder: str = '[MASK]', image_fill: Literal['grey', 'mean', 'blur', 'noise'] = 'grey')[source]¶
Bases:
PluginOptionsOptions of the
padabsence policy.- 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.masking.policies.NeutralOptions(*, fill_char: str = '_', image_fill: Literal['grey', 'mean', 'blur', 'noise'] = 'grey')[source]¶
Bases:
PluginOptionsOptions of the
neutralabsence policy.- 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.masking.policies.DeletePolicy(context: PluginContext | None = None)[source]¶
Bases:
objectRemove absent players from the rendered conversation.
- options_model¶
Accepts no
explanation.plugin_options.alias of
PluginOptions
- apply(snapshot: ConversationSnapshot, players: PlayerSet, mask: CoalitionMask) ConversationSnapshot[source]¶
Drop absent players (text, and audio samples) keeping the message structure.
The empty coalition keeps every message with empty player text (v(empty)).
- class mllm_shap.masking.policies.PadPolicy(context: PluginContext | None = None, placeholder: str = '[MASK]', image_fill: Literal['grey', 'mean', 'blur', 'noise'] = 'grey')[source]¶
Bases:
objectReplace absent players with a fixed mask placeholder.
- options_model¶
Options accepted from
explanation.plugin_options.alias of
PadOptions
- placeholder¶
Placeholder text inserted for absent players.
- apply(snapshot: ConversationSnapshot, players: PlayerSet, mask: CoalitionMask) ConversationSnapshot[source]¶
Substitute absent players with
placeholder; silence their audio.
- class mllm_shap.masking.policies.NeutralPolicy(context: PluginContext | None = None, fill_char: str = '_', image_fill: Literal['grey', 'mean', 'blur', 'noise'] = 'grey')[source]¶
Bases:
objectReplace absent players with neutral fillers that preserve their width.
- options_model¶
Options accepted from
explanation.plugin_options.alias of
NeutralOptions
- fill_char¶
Single character repeated to match each absent player’s length.
- apply(snapshot: ConversationSnapshot, players: PlayerSet, mask: CoalitionMask) ConversationSnapshot[source]¶
Substitute width-matched fillers for absent players; silence their audio.
Infill absence policy: absent words are replaced by a masked language model’s fill.
Each absent player becomes one mask token per word. The model then fills every mask of a message in one forward pass, taking the most probable word at each position, so the same coalition always renders the same text. Fills are cached per masked text.
@domain masking @see [[knowledge/architecture/masking]] @tested-by [[tests/masking/test_infill.py]]
- class mllm_shap.masking.infill.MaskFiller(*args, **kwargs)[source]¶
Bases:
ProtocolFill the mask tokens of a text with words.
- class mllm_shap.masking.infill.InfillOptions(*, model: str = 'roberta-base', revision: str | None = None, image_fill: Literal['grey', 'mean', 'blur', 'noise'] = 'grey')[source]¶
Bases:
PluginOptionsOptions of the
infillabsence policy.- 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.masking.infill.HfMaskedLmFiller(model_id: str, revision: str | None = None)[source]¶
Bases:
objectFill masks with the top word of a Hugging Face masked language model.
- class mllm_shap.masking.infill.InfillPolicy(context: PluginContext | None = None, filler: MaskFiller | None = None)[source]¶
Bases:
objectReplace absent players with the fills of a masked language model.
- options_model¶
Options accepted from
explanation.plugin_options.alias of
InfillOptions
- apply(snapshot: ConversationSnapshot, players: PlayerSet, mask: CoalitionMask) ConversationSnapshot[source]¶
Fill absent words with the model’s choice; silence audio, paint images.
Render audio players: cut or silence absent samples, hide alignment transcripts.
@domain masking @see [[knowledge/architecture/masking]] @tested-by [[tests/alignment/test_sgpa_players.py]]
- mllm_shap.masking.audio.render_audio(snapshot: ConversationSnapshot, spans: Sequence[PlayerSpan], present: Sequence[bool], cut: bool) ConversationSnapshot[source]¶
Remove (
cut) or silence the samples of absent players withsamples.Each span edits the clip its
partnames.Silencing keeps the audio’s length and timing; cutting joins what is left. Spans without
samplesand messages without absent audio are untouched.
- mllm_shap.masking.audio.hide_text(snapshot: ConversationSnapshot, message_indices: Sequence[int]) ConversationSnapshot[source]¶
Drop the text parts of the messages at
message_indices(turns flattened).
Image bytes to pixels and back; render image players by filling absent regions.
@domain masking @see [[knowledge/architecture/masking]] @tested-by [[tests/masking/test_image_masking.py]]
- mllm_shap.masking.image.Box¶
Pixel box
(left, top, right, bottom), right and bottom exclusive.
- mllm_shap.masking.image.ImageFill¶
Fill of absent image regions (mid-grey, the image’s mean colour, a blurred copy of the image, or noise seeded by the image bytes).
alias of
Literal[‘grey’, ‘mean’, ‘blur’, ‘noise’]
- mllm_shap.masking.image.BLUR_FRACTION = 0.0625¶
Gaussian blur radius of the
blurfill as a fraction of the longer side.
- mllm_shap.masking.image.decode_image(data: bytes) NDArray[uint8][source]¶
Decode encoded image bytes to an
(height, width, 3)RGB array.- Raises:
ValueError – If
datais not an image Pillow can read.
- mllm_shap.masking.image.encode_png(pixels: NDArray[uint8]) bytes[source]¶
Encode an
(height, width, 3)RGB array as PNG bytes, the same every time.
- mllm_shap.masking.image.render_images(snapshot: ConversationSnapshot, spans: Sequence[PlayerSpan], present: Sequence[bool], fill: Literal['grey', 'mean', 'blur', 'noise'] | None) ConversationSnapshot[source]¶
Paint the
regionof every absent image player withfill.fill=Noneis thedeletepolicy: it drops an image whose players are all absent and cover it whole. Images without absent players keep their bytes.- Raises:
ValueError – If
fillisNoneand a region player covers only part of its image, which cannot be cut out.
View-based masked snapshots with structural sharing.
@domain masking @see [[knowledge/architecture/masking]] @tested-by [[tests/masking/test_builder.py]]
- class mllm_shap.masking.builder.MaskedSnapshot(base: ConversationSnapshot, players: PlayerSet, mask: CoalitionMask, policy_name: str)[source]¶
Bases:
objectShared view over a conversation snapshot and coalition mask.
- base: ConversationSnapshot¶
Underlying snapshot shared across coalition evaluations.
- mask: CoalitionMask¶
Presence mask selecting which players remain in the coalition.
- class mllm_shap.masking.builder.MaskBuilder(policy: AbsencePolicy, policy_options: Mapping[str, object] | None = None)[source]¶
Bases:
objectBuild masked snapshot views without copying the base conversation.
- property policy_options: Mapping[str, object]¶
Return the policy’s non-default options, which coalition keys hash.
- view(snapshot: ConversationSnapshot, players: PlayerSet, mask: CoalitionMask) MaskedSnapshot[source]¶
Create a masked view that shares
snapshotacross coalitions.
- render(masked: MaskedSnapshot) ConversationSnapshot[source]¶
Materialize a coalition-specific conversation snapshot.
Packed bitset encoding and stable hashing for coalition masks.
@domain masking @see [[knowledge/architecture/masking]] @tested-by [[tests/masking/test_codec.py]]
- class mllm_shap.masking.codec.PackedMask(words: bytes, n_bits: int)[source]¶
Bases:
objectPacked bit representation of one boolean mask.
- class mllm_shap.masking.codec.MaskCodec[source]¶
Bases:
objectEncode and decode boolean masks to packed bytes.
- static normalize(mask: Sequence[bool] | NDArray[bool]) NDArray[bool][source]¶
Normalize incoming mask to a 1D boolean array.
- static pack(mask: Sequence[bool] | NDArray[bool]) PackedMask[source]¶
Pack a mask into little-endian bytes.
- static unpack(packed: PackedMask) tuple[bool, ...][source]¶
Unpack bytes back to a boolean tuple.
Mask-space utilities for explainable feature indexing.
@domain masking @see [[knowledge/architecture/masking]] @tested-by [[tests/masking/test_space.py]]