Given attributions as a tuple of tensors (one per modality), measures what fraction of the globally most-important features belongs to each modality. Helps diagnose whether a multimodal model relies predominantly on one modality over others.

modality_topk_fraction

modality_topk_fraction(
    attributions: tuple[Tensor, ...] | list[tuple[Tensor, ...]],
    feature_mask: tuple[Tensor, ...] | None = None,
    modality_names: list[str] | None = None,
    k_fractions: Sequence[float] = (0.05, 0.1, 0.2),
    reduce_mode: str = "sum",
    multi_target: bool = False,
    return_dict: bool = True,
) -> dict | Tensor | list[Tensor]

Fraction of the global top-k attribution mass contributed by each modality.

Given attributions for multiple modalities (e.g. text and image), measures which modality owns the most important features at various top-k thresholds. Useful for diagnosing modality dominance in multimodal models.

Parameters:

  • attributions

    (tuple[Tensor, ...] or list[tuple[Tensor, ...]]) –

    Attribution tensors, one per modality, each of shape (batch_size, n_features_i). For multi-target mode, pass a list of such tuples.

  • feature_mask

    (tuple[Tensor, ...] or None, default: None ) –

    Optional feature group masks of the same shape as attributions, used to pool raw features into semantic units (e.g. tokens into words). If None, each feature is its own group.

  • modality_names

    (list[str] or None, default: None ) –

    Human-readable names for each modality, used as dict key suffixes when return_dict=True. Defaults to ["modality_0", "modality_1", ...].

  • k_fractions

    (Sequence[float], default: (0.05, 0.1, 0.2) ) –

    Top-k thresholds expressed as fractions of total feature groups. Default: (0.05, 0.10, 0.20).

  • reduce_mode

    (str, default: 'sum' ) –

    Pooling mode for feature groups. "sum" sums attributions within each group; "weighted_sum" weights by min_group_size / group_size, penalising larger groups. Default: "sum".

  • multi_target

    (bool, default: False ) –

    If True, attributions must be a list of tuples, one per target. Default: False.

  • return_dict

    (bool, default: True ) –

    If True, return a flat dict keyed by "score_k{frac}_{name}" per (k_fraction, modality) pair, each value of shape (batch_size,). If False, return a tensor of shape (batch_size, n_k_fractions, n_modalities). Default: True.

Returns:

  • dict | Tensor | list[Tensor]

    dict or Tensor or list[Tensor]: Attribution mass fractions per modality at each k threshold.

Example

import torch text_attr = torch.randn(2, 50) img_attr = torch.randn(2, 100) result = modality_topk_fraction( ... (text_attr, img_attr), ... modality_names=["text", "image"], ... k_fractions=[0.05, 0.10, 0.20], ... ) list(result.keys()) ['score_text', 'score_image']

Source code in torchxai/metrics/diagnosis/modality_topk_fraction.py
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
def modality_topk_fraction(
    attributions: tuple[Tensor, ...] | list[tuple[Tensor, ...]],
    feature_mask: tuple[Tensor, ...] | None = None,
    modality_names: list[str] | None = None,
    k_fractions: Sequence[float] = (0.05, 0.10, 0.20),
    reduce_mode: str = "sum",
    multi_target: bool = False,
    return_dict: bool = True,
) -> dict | Tensor | list[Tensor]:
    """Fraction of the global top-k attribution mass contributed by each modality.

    Given attributions for multiple modalities (e.g. text and image), measures which modality
    owns the most important features at various top-k thresholds. Useful for diagnosing modality
    dominance in multimodal models.

    Args:
        attributions (tuple[Tensor, ...] or list[tuple[Tensor, ...]]): Attribution tensors, one
            per modality, each of shape ``(batch_size, n_features_i)``. For multi-target mode,
            pass a list of such tuples.
        feature_mask (tuple[Tensor, ...] or None): Optional feature group masks of the same shape
            as ``attributions``, used to pool raw features into semantic units (e.g. tokens into
            words). If ``None``, each feature is its own group.
        modality_names (list[str] or None): Human-readable names for each modality, used as dict
            key suffixes when ``return_dict=True``. Defaults to ``["modality_0", "modality_1", ...]``.
        k_fractions (Sequence[float]): Top-k thresholds expressed as fractions of total feature
            groups. Default: ``(0.05, 0.10, 0.20)``.
        reduce_mode (str): Pooling mode for feature groups. ``"sum"`` sums attributions within
            each group; ``"weighted_sum"`` weights by ``min_group_size / group_size``, penalising
            larger groups. Default: ``"sum"``.
        multi_target (bool): If ``True``, ``attributions`` must be a list of tuples, one per
            target. Default: ``False``.
        return_dict (bool): If ``True``, return a flat dict keyed by
            ``"score_k{frac}_{name}"`` per (k_fraction, modality) pair, each value of shape
            ``(batch_size,)``. If ``False``, return a tensor of shape
            ``(batch_size, n_k_fractions, n_modalities)``. Default: ``True``.

    Returns:
        dict or Tensor or list[Tensor]: Attribution mass fractions per modality at each k threshold.

    Example:
        >>> import torch
        >>> text_attr = torch.randn(2, 50)
        >>> img_attr  = torch.randn(2, 100)
        >>> result = modality_topk_fraction(
        ...     (text_attr, img_attr),
        ...     modality_names=["text", "image"],
        ...     k_fractions=[0.05, 0.10, 0.20],
        ... )
        >>> list(result.keys())
        ['score_text', 'score_image']
    """
    is_list = isinstance(attributions, list)
    if multi_target:
        assert is_list, "attributions must be a list of tuples when multi_target=True"
    if not is_list:
        attributions = [attributions]  # type: ignore

    n_modalities = len(attributions[0])
    names = (
        modality_names
        if modality_names is not None
        else [f"modality_{i}" for i in range(n_modalities)]
    )
    assert len(names) == n_modalities, (
        f"modality_names length {len(names)} must match n_modalities {n_modalities}"
    )

    scores = [
        _modality_topk_fraction_per_target(
            attrs,
            feature_mask=feature_mask,
            k_fractions=k_fractions,
            reduce_mode=reduce_mode,
        )
        for attrs in attributions
    ]  # list of [batch_size, n_k_fractions, n_modalities]

    if not is_list:
        scores = scores[0]

    if return_dict:
        if isinstance(scores, list):
            # multi_target: scores is list of [batch_size, n_k_fractions, n_modalities]
            return {
                f"score_{name}": [s[:, :, j].mean(dim=1) for s in scores]
                for j, name in enumerate(names)
            }
        else:
            # single target: scores is [batch_size, n_k_fractions, n_modalities]
            return {
                f"score_{name}": scores[:, :, j].mean(dim=1)
                for j, name in enumerate(names)
            }

    return scores