Which part of the photo decided the answer?

Goal: ask a vision language model yes-or-no questions about real photos, then show which regions of each photo pushed its answer toward “Yes” or “No”.

Why it matters: an answer about an image can be right for the wrong reason. Greying out each region and re-scoring the answer shows what the model looked at: the small sign that says OPEN, the umbrellas that tell it is raining, or the cat’s face that rules out a dog.

Prerequisites: uv sync --extra transformers --extra image --extra viz. The first run downloads Qwen/Qwen2.5-VL-3B-Instruct (about 7.5 GB). Each 36-cell explanation takes about three minutes on one A100.

Output: each answer, the regions that carry it, and a heatmap over the photo.

from pathlib import Path

import matplotlib.pyplot as plt
from huggingface_hub.utils import disable_progress_bars
from transformers.utils.logging import disable_progress_bar

import mllm_shap
from mllm_shap import (
    ConversationSnapshot,
    ExplainConfig,
    ExplainRunner,
    ImagePart,
    Message,
    Role,
    TextPart,
    TransformersTextBackend,
    Turn,
)
from mllm_shap.plugins import PluginContext
from mllm_shap.viz import plot_image_players

disable_progress_bars()
disable_progress_bar()
print("mllm-shap", mllm_shap.__version__)
mllm-shap 0.11.1

The game

image_grid cuts a photo into 6 by 6 cells, each a player; an absent cell is painted grey (pad with image_fill: grey). label_margin scores how much more likely the model makes “Yes” than “No” (teacher-forced log-odds), so a red cell pushes toward “Yes”, a blue one toward “No”, and nothing is generated per coalition. 36 players have 2^36 coalitions, so Leverage SHAP estimates the values from 600 of them.

MODEL_ID = "Qwen/Qwen2.5-VL-3B-Instruct"
REVISION = "66285546d2b821cf421d4f5eb2576359d3770cd3"
YES_NO = " Answer yes or no."


def config(players: str = "image_grid", **options: object) -> ExplainConfig:
    grid = players == "image_grid"
    return ExplainConfig.model_validate({
        "backend": {
            "kind": "transformers",
            "model_id": MODEL_ID,
            "options": {"revision": REVISION, "dtype": "bfloat16", "batch_size": 8},
        },
        "generation": {"max_new_tokens": 8},
        "explanation": {
            "archive": {"path": ""},
            "players": players,
            "absence_policy": "pad",
            "estimator": "leverage" if grid else "exact",
            **({"budget": {"evaluations": 600}} if grid else {}),
            "value_fn": "label_margin",
            "plugin_options": {
                players: {"rows": 6, "cols": 6, **options} if grid else options,
                "pad": {"image_fill": "grey"},
                "label_margin": {"target": "Yes", "labels": ["Yes", "No"]},
            },
        },
    })


backend = TransformersTextBackend(PluginContext(config=config()))
def ask(photo: str, question: str) -> tuple[ImagePart, ConversationSnapshot]:
    picture = ImagePart(Path(photo))
    message = Message(role=Role.USER, content=(picture, TextPart(question + YES_NO)))
    return picture, ConversationSnapshot.from_turns((Turn(messages=(message,)),))


async def explain(
    photo: str, question: str, players: str = "image_grid", **options: object
):
    picture, snapshot = ask(photo, question)
    run_config = config(players, **options)
    answer = await backend.generate(snapshot, run_config.generation)
    output = await ExplainRunner(run_config, backend=backend).explain(snapshot)
    result = output.result
    print("model answer:", answer.text.strip())
    print(f"log-odds of Yes: {result.grand_value:+.2f} with the photo,", end=" ")
    print(f"{result.base_value:+.2f} with it greyed out")
    pairs = zip(output.player_set.spans, result.values, strict=True)
    ranked = sorted(pairs, key=lambda pair: -abs(pair[1]))
    for span, value in ranked[:4]:
        print(f"  {span.display_label:12} {value:+.2f}")
    return picture, snapshot, output


def heatmap(picture, output, skip=()):
    pairs = [
        (span, value)
        for span, value in zip(
            output.player_set.spans, output.result.values, strict=True
        )
        if span.region and span.display_label not in skip
    ]
    plot_image_players(picture, [s for s, _ in pairs], [v for _, v in pairs])
    plt.show()

Finding a small object in a busy scene

Graffiti, buildings, trees and, in the lower right, a man walking a small dog. Asked whether there is a dog, the model says yes, and two cells carry almost all of that answer: the ones holding the walker and his dog.

street = await explain("photo_street_dog.jpg", "Is there a dog in this picture?")
model answer: Yes.
log-odds of Yes: +4.00 with the photo, -2.75 with it greyed out
  r5c6         +4.13
  r5c5         +1.28
  r3c2         +0.26
  r6c6         +0.26
heatmap(street[0], street[2])
../_images/73d63d37333c995af9a8891aa1618f207e84ecbb5d148e254184326ab0bba3be.png

Is the answer grounded in the right evidence?

“Is the shop open?” The model says yes, and the credit sits on the small red OPEN sign in the door, not on the large neon lettering or the window display.

shop = await explain("photo_shop.jpg", "Is the shop open?")
model answer: Yes.
log-odds of Yes: +3.37 with the photo, +0.00 with it greyed out
  r3c3         +2.32
  r4c3         +0.39
  r4c4         +0.19
  r5c2         +0.19
heatmap(shop[0], shop[2])
../_images/b8158644c2cc042cb794906bd26e7370983d9b0b9af281bd1456b4ead0ace543.png

Named regions: one photo, two questions

image_boxes turns labelled boxes into players (plus one for the rest of the picture), so the values answer a direct question: which object mattered? Box coordinates are [left, top, right, bottom] pixels. With the same two boxes, “Is the shop open?” credits the OPEN sign and “Does this shop buy gold?” credits the neon “SCRAP GOLD AND SILVER”.

BOXES = {"open_sign": [[355, 268, 420, 325]], "neon_sign": [[630, 105, 915, 320]]}
open_boxes = await explain(
    "photo_shop.jpg", "Is the shop open?", "image_boxes", boxes=BOXES
)
gold_boxes = await explain(
    "photo_shop.jpg", "Does this shop buy gold?", "image_boxes", boxes=BOXES
)
model answer: Yes.
log-odds of Yes: +3.37 with the photo, +0.00 with it greyed out
  open_sign    +2.29
  background   +1.04
  neon_sign    +0.04
model answer: Yes.
log-odds of Yes: +2.88 with the photo, -0.38 with it greyed out
  neon_sign    +2.73
  background   +0.98
  open_sign    -0.46
heatmap(gold_boxes[0], gold_boxes[2], skip=("background",))
../_images/787ae3e837b5f521cfe5c5837e8b0043aecd440a11e8434d392d688ad117ac78.png

Indirect evidence

“Is it raining?” No raindrops are visible; the model answers yes from the crowd of open umbrellas, and that is where the credit goes.

rain = await explain("photo_umbrellas.jpg", "Is it raining?")
model answer: Yes.
log-odds of Yes: +1.25 with the photo, -2.00 with it greyed out
  r5c3         +0.68
  r6c4         +0.43
  r5c2         +0.37
  r6c2         +0.33
heatmap(rain[0], rain[2])
../_images/f2402f897cf89fda1b6dd2f52eecb11f5534a88647f56eed919e7e7c26dc0e0c.png

Same photo, opposite questions

The traffic light shows red. For “Is the traffic light red?” the lit top lamp carries the yes.

red = await explain("photo_traffic_light.jpg", "Is the traffic light red?")
model answer: Yes.
log-odds of Yes: +1.62 with the photo, -0.50 with it greyed out
  r2c2         +1.25
  r2c3         +0.53
  r1c3         +0.22
  r3c3         +0.21
heatmap(red[0], red[2])
../_images/a415bed43e2472a22b29461751aea578f2f5450b6464db9da91d6506e4009073.png

For “Is the traffic light green?” the model says no: the lit red lamp now counts against, and the unlit lamp further down is what pulls toward yes.

green = await explain("photo_traffic_light.jpg", "Is the traffic light green?")
model answer: No.
log-odds of Yes: -2.37 with the photo, -0.87 with it greyed out
  r4c2         +0.66
  r2c2         -0.62
  r4c3         +0.48
  r2c3         -0.34
heatmap(green[0], green[2])
../_images/de2083695687e8d8398b9f57971fd814a360d5a6ccd81e1f078b5d1da32d38ba.png

Explaining a “No”

“Is there a dog in this picture?” asked of a cat. The model says no, and the cat’s face, its eyes and nose, is the evidence against: those cells are blue.

cat = await explain("photo_cat.jpg", "Is there a dog in this picture?")
model answer: No.
log-odds of Yes: -6.37 with the photo, -2.75 with it greyed out
  r2c2         -0.72
  r4c4         -0.63
  r3c3         -0.51
  r4c3         -0.46
heatmap(cat[0], cat[2])
../_images/928a2a71061ec2e0b7df357a7636fb4887b6266df0607e37b283ea0e12b938eb.png

An attribute, not just an object

“Is the dog’s tongue sticking out?” The credit lands on the tongue, not on the dog as a whole.

tongue = await explain("photo_boxer.jpg", "Is the dog's tongue sticking out?")
model answer: Yes.
log-odds of Yes: +3.37 with the photo, -0.38 with it greyed out
  r4c4         +0.74
  r5c4         +0.61
  r4c3         +0.41
  r3c4         +0.32
heatmap(tongue[0], tongue[2])
../_images/c69be6048cf48b3895acbdb01c70fd283b922a399c4745ffe790fe0b9ab1a144.png

Reading the values

  • Values are log-odds of “Yes” against “No” and add up to the gap between the full photo and the all-grey one (efficiency).

  • A cell is a region, not an object: an object split across cells shares its credit, and a grey patch is itself a signal the model may react to. Compare fills (mean, blur, noise) before trusting a fine pattern.

  • To check that the regions matter, remove them and re-score: image_removal_metrics compares the top cells against random regions of the same area.

Photo credits

All photos are CC0, from Wikimedia Commons):