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: PluginOptions

Options of the tokens and messages partitions.

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 messages partition (same fields as tokens).

class mllm_shap.masking.partitions.TokenPartitioner(context: PluginContext | None = None)[source]

Bases: object

Partition a snapshot into whitespace-delimited text tokens.

options_model

Options accepted from explanation.plugin_options.

alias of RolesOptions

roles

Roles whose tokens become players.

property name: str

Return the registered partition identifier.

partition(snapshot: ConversationSnapshot) → PlayerSet[source]

Derive ordered token players and their spans from the snapshot text.

Tokens of messages whose role is not in roles are 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: object

Partition 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.

property name: str

Return the registered partition identifier.

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 of text, 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: object

Partition 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.

property name: str

Return the registered partition identifier.

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>" with n the 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 + 1 edges cutting length into near-equal grid pieces.

The last piece also takes the remainder below one grid step.

Raises:

ValueError – If length holds fewer than count grid 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: PluginOptions

Options of the image_grid partition.

rows: int

Grid rows per image.

cols: int

Grid columns per image.

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.

question: bool

Also make each word of a message with an image a player.

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: PluginOptions

Options of the image_boxes partition.

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).

background: bool

Add one player for the pixels no box covers.

question: bool

Also make each word of the image’s message a player.

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: object

Cut every image into a grid of cells, one player each.

Each player’s span carries its cell as region and its image as part; 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

property name: str

Return the registered partition identifier.

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_px steps than rows or columns.

class mllm_shap.masking.partitions.ImageBoxPartitioner(context: PluginContext | None = None)[source]

Bases: object

Make 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

property name: str

Return the registered partition identifier.

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 of snapshot.

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 snapshot with each span replaced by its replacement text.

None deletes a span together with the whitespace that separated it from its neighbours, so deleting b from "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. Image region spans carry no text and are skipped.

Raises:

ValueError – If spans and replacements differ 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: PluginOptions

Options of the pad absence policy.

placeholder: str

Placeholder text inserted for absent players.

image_fill: Literal['grey', 'mean', 'blur', 'noise']

What absent image regions show (image extra).

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: PluginOptions

Options of the neutral absence policy.

fill_char: str

Single character repeated to match each absent player’s length.

image_fill: Literal['grey', 'mean', 'blur', 'noise']

What absent image regions show (image extra).

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: object

Remove absent players from the rendered conversation.

options_model

Accepts no explanation.plugin_options.

alias of PluginOptions

property name: str

Return the registered absence-policy identifier.

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: object

Replace 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.

image_fill: Literal['grey', 'mean', 'blur', 'noise']

What absent image regions show.

property name: str

Return the registered absence-policy identifier.

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: object

Replace 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.

image_fill: Literal['grey', 'mean', 'blur', 'noise']

What absent image regions show.

property name: str

Return the registered absence-policy identifier.

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: Protocol

Fill the mask tokens of a text with words.

property mask_token: str

Return the token that marks a word to fill.

fill(text: str) → list[str][source]

Return one word per occurrence of mask_token, in order.

class mllm_shap.masking.infill.InfillOptions(*, model: str = 'roberta-base', revision: str | None = None, image_fill: Literal['grey', 'mean', 'blur', 'noise'] = 'grey')[source]

Bases: PluginOptions

Options of the infill absence policy.

model: str

Hugging Face masked language model that supplies the fills.

revision: str | None

Hub revision of the model; pin a commit hash for reproducible fills.

image_fill: Literal['grey', 'mean', 'blur', 'noise']

What absent image regions show (image extra).

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: object

Fill masks with the top word of a Hugging Face masked language model.

property mask_token: str

Return the model tokenizer’s mask token.

fill(text: str) → list[str][source]

Return the most probable non-special word at each mask, in one pass.

class mllm_shap.masking.infill.InfillPolicy(context: PluginContext | None = None, filler: MaskFiller | None = None)[source]

Bases: object

Replace absent players with the fills of a masked language model.

options_model

Options accepted from explanation.plugin_options.

alias of InfillOptions

property name: str

Return the registered absence-policy identifier.

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 with samples.

Each span edits the clip its part names.

Silencing keeps the audio’s length and timing; cutting joins what is left. Spans without samples and 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.

alias of tuple[int, int, int, int]

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 blur fill 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 data is 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 region of every absent image player with fill.

fill=None is the delete policy: it drops an image whose players are all absent and cover it whole. Images without absent players keep their bytes.

Raises:

ValueError – If fill is None and 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: object

Shared view over a conversation snapshot and coalition mask.

base: ConversationSnapshot

Underlying snapshot shared across coalition evaluations.

players: PlayerSet

Ordered players aligned with the coalition mask.

mask: CoalitionMask

Presence mask selecting which players remain in the coalition.

policy_name: str

Registered absence-policy identifier used to render the view.

property base_snapshot_id: str

Return the shared base snapshot identifier.

property mask_hash: int

Return a stable hash for the coalition mask.

class mllm_shap.masking.builder.MaskBuilder(policy: AbsencePolicy, policy_options: Mapping[str, object] | None = None)[source]

Bases: object

Build masked snapshot views without copying the base conversation.

property policy_name: str

Return the configured absence-policy identifier.

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 snapshot across 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: object

Packed bit representation of one boolean mask.

words: bytes

Little-endian packed bytes encoding the boolean mask.

n_bits: int

Original number of bits (mask length) before packing.

class mllm_shap.masking.codec.MaskCodec[source]

Bases: object

Encode 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.

static hash_mask(mask: Sequence[bool] | NDArray[bool]) → int[source]

Return a process-independent 64-bit hash over packed mask bytes.

Mask-space utilities for explainable feature indexing.

@domain masking @see [[knowledge/architecture/masking]] @tested-by [[tests/masking/test_space.py]]

class mllm_shap.masking.space.MaskSpace(explainable_mask: tuple[bool, ...], target_length: int)[source]

Bases: object

Describe explainable feature positions inside a full coalition mask.

explainable_mask: tuple[bool, ...]

Boolean flags selecting explainable feature positions from the full mask.

target_length: int

Total length of the full coalition mask including fixed positions.

property n_features: int

Return the number of explainable features.

materialize(split: CoalitionMask | Sequence[bool]) → tuple[bool, ...][source]

Project a split over explainable positions back to the full mask.