Source code for mllm_shap.masking.partitions

"""Player partition plugins: tokens, sentences, whole messages and image regions.

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

import math
import re
from typing import TYPE_CHECKING, ClassVar, Final

import numpy as np
from pydantic import Field

from ..domain.conversation import ConversationSnapshot, ImagePart, Message
from ..domain.enums import RoleName
from ..domain.players import PlayerSet, PlayerSpan
from ..protocols.plugin import PluginOptions
from .image import Box, decode_image
from .tokens import token_spans

if TYPE_CHECKING:
    from ..plugins.context import PluginContext


[docs] class RolesOptions(PluginOptions): """Options of the ``tokens`` and ``messages`` partitions.""" roles: list[RoleName] = Field(default=["user", "assistant", "system"]) """Roles whose text becomes players; other messages are always present."""
MessagesOptions = RolesOptions """Options of the ``messages`` partition (same fields as ``tokens``).""" def _roles(context: "PluginContext | None") -> frozenset[str]: roles = RolesOptions().roles if context is not None: roles = context.option("roles", roles) return frozenset(roles)
[docs] class TokenPartitioner: """Partition a snapshot into whitespace-delimited text tokens.""" options_model: ClassVar[type[PluginOptions]] = RolesOptions """Options accepted from ``explanation.plugin_options``.""" def __init__(self, context: "PluginContext | None" = None) -> None: """Read option ``roles`` from ``context``; every role by default.""" self.roles = _roles(context) """Roles whose tokens become players.""" @property def name(self) -> str: """Return the registered partition identifier.""" return "tokens"
[docs] def partition(self, snapshot: ConversationSnapshot) -> PlayerSet: """Derive ordered token players and their spans from the snapshot text. Tokens of messages whose role is not in :attr:`roles` are no players and stay present in every coalition; player ids do not depend on the filter. """ messages = snapshot.messages() pairs = tuple( (player_id, span) for player_id, span in token_spans(snapshot) if messages[span.message_index].role.value in self.roles ) if not pairs: msg = "snapshot must contain at least one explainable token" raise ValueError(msg) return PlayerSet( player_ids=tuple(player_id for player_id, _ in pairs), spans=tuple(span for _, span in pairs), )
_PARAGRAPH_RE = re.compile(r"(?:[^\n]|\n(?!\s*\n))+") _TOKEN_RE = re.compile(r"\S+") _SENTENCE_RE = re.compile(r"\S.*?(?:[.!?]+(?=\s|$)|$)", re.DOTALL)
[docs] class SentencePartitioner: """Partition a snapshot into sentences, never crossing a blank line.""" options_model: ClassVar[type[PluginOptions]] = RolesOptions """Options accepted from ``explanation.plugin_options``.""" def __init__(self, context: "PluginContext | None" = None) -> None: """Read option ``roles`` from ``context``; every role by default.""" self.roles = _roles(context) """Roles whose sentences become players.""" @property def name(self) -> str: """Return the registered partition identifier.""" return "sentences"
[docs] def partition(self, snapshot: ConversationSnapshot) -> PlayerSet: """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}``. """ ids: list[str] = [] spans: list[PlayerSpan] = [] index = 0 for turn_index, turn in enumerate(snapshot.turns): for local_index, message in enumerate(turn.messages): if message.role.value in self.roles: for number, (start, end) in enumerate( sentence_bounds(message.text) ): ids.append( f"{snapshot.snapshot_id}:{turn_index}:{local_index}:{number}" ) spans.append( PlayerSpan( message_index=index, start=start, end=end, text=message.text[start:end], speaker=message.speaker, ) ) index += 1 if not spans: msg = "snapshot must contain at least one explainable sentence" raise ValueError(msg) return PlayerSet(player_ids=tuple(ids), spans=tuple(spans))
[docs] def sentence_bounds(text: str) -> list[tuple[int, int]]: """Return the ``[start, end)`` range of every sentence of ``text``, in order.""" bounds = [] for paragraph in _PARAGRAPH_RE.finditer(text): offset = paragraph.start() for sentence in _SENTENCE_RE.finditer(paragraph.group()): end = offset + sentence.end() while end > offset + sentence.start() and text[end - 1].isspace(): end -= 1 bounds.append((offset + sentence.start(), end)) return bounds
LABEL_PREVIEW_CHARS: Final[int] = 30 """Characters of the message text shown in a message player's label."""
[docs] class MessagePartitioner: """Partition a snapshot into one player per non-empty message.""" options_model: ClassVar[type[PluginOptions]] = RolesOptions """Options accepted from ``explanation.plugin_options``.""" def __init__(self, context: "PluginContext | None" = None) -> None: """Read option ``roles`` from ``context``; every role by default.""" self.roles = _roles(context) """Roles whose messages become players.""" @property def name(self) -> str: """Return the registered partition identifier.""" return "messages"
[docs] def partition(self, snapshot: ConversationSnapshot) -> PlayerSet: """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. """ ids: list[str] = [] spans: list[PlayerSpan] = [] index = 0 for turn_index, turn in enumerate(snapshot.turns): for local_index, message in enumerate(turn.messages): if message.text and message.role.value in self.roles: ids.append(f"{snapshot.snapshot_id}:{turn_index}:{local_index}") spans.append(_message_span(index, message)) index += 1 if not spans: msg = "snapshot must contain at least one non-empty message to explain" raise ValueError(msg) return PlayerSet(player_ids=tuple(ids), spans=tuple(spans))
def _message_span(index: int, message: Message) -> PlayerSpan: head = message.role.value if message.speaker is not None: head += f"/{message.speaker}" preview = message.text[:LABEL_PREVIEW_CHARS] if len(message.text) > LABEL_PREVIEW_CHARS: preview += "…" return PlayerSpan( message_index=index, start=0, end=len(message.text), text=message.text, speaker=message.speaker, label=f"{head} {index + 1}: {preview}", )
[docs] def snapped_edges( length: int, count: int, grid: int, what: str, steps_of: str ) -> list[int]: """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. """ steps = length // grid if count > steps: msg = f"{count} {what} need more than the {steps} {steps_of}" raise ValueError(msg) return [round(k * steps / count) * grid for k in range(count)] + [length]
[docs] class ImageGridOptions(PluginOptions): """Options of the ``image_grid`` partition.""" rows: int = Field(default=2, ge=1) """Grid rows per image.""" cols: int = Field(default=3, ge=1) """Grid columns per image.""" snap_px: int = Field(default=28, ge=1) """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 = False """Also make each word of a message with an image a player."""
[docs] class ImageBoxOptions(PluginOptions): """Options of the ``image_boxes`` partition.""" boxes: dict[str, list[list[float]]] = Field(min_length=1) """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 = True """Add one player for the pixels no box covers.""" question: bool = False """Also make each word of the image's message a player."""
[docs] class ImageGridPartitioner: """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: ClassVar[type[PluginOptions]] = ImageGridOptions """Options accepted from ``explanation.plugin_options``.""" def __init__(self, context: "PluginContext | None" = None) -> None: """Read the options from ``context`` when given.""" self._options = ImageGridOptions() if context is not None: self._options = ImageGridOptions.model_validate(context.options) @property def name(self) -> str: """Return the registered partition identifier.""" return "image_grid"
[docs] def partition(self, snapshot: ConversationSnapshot) -> PlayerSet: """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. """ options = self._options ids: list[str] = [] spans: list[PlayerSpan] = [] for prefix, index, message, images in _image_messages(snapshot): if options.question: _add_words(ids, spans, prefix, index, message) for part, image in enumerate(images): height, width = decode_image(image.data()).shape[:2] step = f"{options.snap_px} px steps of the image" xs = snapped_edges( width, options.cols, options.snap_px, "columns", f"{step} width" ) ys = snapped_edges( height, options.rows, options.snap_px, "rows", f"{step} height" ) name = f"image {part + 1} " if len(images) > 1 else "" for row in range(options.rows): for col in range(options.cols): ids.append(f"{prefix}:i{part}:{row}:{col}") box = (xs[col], ys[row], xs[col + 1], ys[row + 1]) label = f"{name}r{row + 1}c{col + 1}" spans.append(_image_span(index, message, label, (box,), part)) if not ids: msg = "image_grid needs a message with an ImagePart" raise ValueError(msg) return PlayerSet(player_ids=tuple(ids), spans=tuple(spans))
[docs] class ImageBoxPartitioner: """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: ClassVar[type[PluginOptions]] = ImageBoxOptions """Options accepted from ``explanation.plugin_options``.""" def __init__(self, context: "PluginContext | None" = None) -> None: """Read the required ``boxes`` option from ``context``.""" options = {} if context is None else dict(context.options) self._options = ImageBoxOptions.model_validate(options) @property def name(self) -> str: """Return the registered partition identifier.""" return "image_boxes"
[docs] def partition(self, snapshot: ConversationSnapshot) -> PlayerSet: """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. """ found = next(iter(_image_messages(snapshot)), None) if found is None: msg = "image_boxes needs a message with an ImagePart" raise ValueError(msg) prefix, index, message, images = found ids: list[str] = [] spans: list[PlayerSpan] = [] if self._options.question: _add_words(ids, spans, prefix, index, message) height, width = decode_image(images[0].data()).shape[:2] regions = _box_regions(self._options.boxes, width, height) if not self._options.background: regions.pop("background") for name, region in regions.items(): ids.append(f"{prefix}:i0:{name}") spans.append(_image_span(index, message, name, region, 0)) return PlayerSet(player_ids=tuple(ids), spans=tuple(spans))
def _image_messages( snapshot: ConversationSnapshot, ) -> list[tuple[str, int, Message, list[ImagePart]]]: """Return ``(id prefix, message index, message, images)`` per image message.""" found = [] message_index = 0 for turn_index, turn in enumerate(snapshot.turns): for local_index, message in enumerate(turn.messages): images = [p for p in message.content if isinstance(p, ImagePart)] if images: prefix = f"{snapshot.snapshot_id}:{turn_index}:{local_index}" found.append((prefix, message_index, message, images)) message_index += 1 return found def _add_words( ids: list[str], spans: list[PlayerSpan], prefix: str, index: int, message: Message ) -> None: for token, word in enumerate(_TOKEN_RE.finditer(message.text)): ids.append(f"{prefix}:w{token}") spans.append( PlayerSpan(index, word.start(), word.end(), word.group(), message.speaker) ) def _image_span( index: int, message: Message, label: str, region: tuple[Box, ...], part: int ) -> PlayerSpan: return PlayerSpan( message_index=index, start=0, end=0, text="", speaker=message.speaker, label=label, region=region, part=part, ) def _box_regions( boxes: dict[str, list[list[float]]], width: int, height: int ) -> dict[str, tuple[Box, ...]]: """Return each category's disjoint boxes, sorted by name, then ``background``. Raises: ValueError: If a box does not have four corners with left < right and top < bottom. """ clipped: dict[str, list[Box]] = {} for name, corners in boxes.items(): clipped[name] = [] for box in corners: if len(box) != 4 or not (box[0] < box[2] and box[1] < box[3]): msg = ( f"box {box} of {name!r} needs [left, top, right, bottom] " "with left < right and top < bottom" ) raise ValueError(msg) left = min(max(math.floor(box[0]), 0), width) top = min(max(math.floor(box[1]), 0), height) right = min(max(math.ceil(box[2]), 0), width) bottom = min(max(math.ceil(box[3]), 0), height) clipped[name].append((left, top, right, bottom)) xs = sorted({ 0, width, *(b[i] for bs in clipped.values() for b in bs for i in (0, 2)), }) ys = sorted({ 0, height, *(b[i] for bs in clipped.values() for b in bs for i in (1, 3)), }) area = np.outer(np.diff(ys), np.diff(xs)) cover = {} for name, rects in clipped.items(): cells = np.zeros(area.shape, dtype=bool) for left, top, right, bottom in rects: cells[ ys.index(top) : ys.index(bottom), xs.index(left) : xs.index(right) ] = True cover[name] = cells owner = np.full(area.shape, "", dtype=object) for name in sorted(cover, key=lambda n: (int(area[cover[n]].sum()), n)): owner[(owner == "") & cover[name]] = name names = [*sorted(cover), "background"] return { name: _merged_boxes(owner == ("" if name == "background" else name), xs, ys) for name in names } def _merged_boxes(cells: np.ndarray, xs: list[int], ys: list[int]) -> tuple[Box, ...]: """Return the cells marked in ``cells`` as boxes, adjacent cells of a row merged.""" boxes: list[Box] = [] for row in range(cells.shape[0]): col = 0 while col < cells.shape[1]: if not cells[row, col]: col += 1 continue start = col while col < cells.shape[1] and cells[row, col]: col += 1 boxes.append((xs[start], ys[row], xs[col], ys[row + 1])) return tuple(boxes)