""" grounding_diff_region.py — Visual Influence Analysis (Bbox Mask vs Random Mask Divergence) ============================================================================================ For each sample: 1. MR forward pass (bbox region masked) → hs_bbox [num_layers, D] 2. RR forward pass (random equal-size region masked) → hs_rand [num_layers, D] 3. Per-layer divergence: D[i] = 1 - cosine(hs_bbox[i], hs_rand[i]) 4. Save mean divergence across all samples: shape [num_layers] This directly measures how differently the model processes bbox-masked vs randomly-masked inputs. A large divergence means the model treats the bbox region as distinctly important. Supported models : qwen2_5vl, qwen3vl, medgemma, llava, llava_med, huatuogpt_vision Supported datasets: VGMED, COCO ────────────────────────────────────────────────────────────────────────────────── 【中文总览 / 整体说明】 ────────────────────────────────────────────────────────────────────────────────── 本脚本是 grounding_mask_region.py 的"随机对照实验"版本,逻辑上与 grounding_diff_text.py 对 grounding_mask_text.py 的关系完全对称(一个在视觉token上 做对照,一个在文本token上做对照)。 背景动机(为什么需要这个脚本): grounding_mask_region.py 做的事情是:对比"完整输入(VL)的前向"与"把ground-truth bbox对应的视觉token清零之后(MR)的前向"之间的隐藏状态差异(divergence)。如果这个 divergence很大,研究者会倾向于解读为"bbox区域对模型很重要,把它mask掉会显著改变 模型的内部表征"。 但这个解读存在一个混淆因素(confound):模型的隐藏状态本来就会因为"图像中任意一块 同样大小的区域被清零"这种扰动而发生变化——这种变化可能只是因为"输入图像被改动了" 这一事实本身,而不是因为被改动的恰好是bbox所在的区域。换句话说,mask_region观测到 的divergence,可能只是"扰动任意等大小区域都会产生的伪效应(artifact)",而不是bbox 区域真的有特殊地位的证据。 为了排除这个混淆因素,本脚本设计了一个随机对照组: - MR前向(Mask Region):依然是把ground-truth bbox覆盖的视觉token清零(与 mask_region脚本中的MR完全一致的操作)。 - RR前向(Random Region,本脚本独有):不再使用完整未mask的输入做对比,而是 对每一个原始GT bbox,各自在token网格里随机找一个与它自己外包矩形"宽高完全 相同"的连续矩形区域,把它覆盖的token清零,作为对照(见 `_random_multi_rect_indices`:对每个bbox分别算出自己外包矩形的宽w、高h, 在token网格里枚举所有可放置(w x h)矩形且不与任何GT token或其它已选中随机 矩形重叠的位置,随机选一个,所有bbox的随机矩形最后合并起来)。按每个bbox 分别处理而不是对所有bbox合并后的整体外包矩形找一个矩形,是因为如果同一张图 有多个不相连的bbox,合并后的外包矩形会横跨它们之间的空白,尺寸远大于GT 实际占用的token数量。这样RR区域不仅token数量与MR一致,形状(宽高)也完全 一致,唯一变量就是"位置在哪"——如果RR是分散的孤立token而不是连续矩形, 会引入"扰动是连续区域还是零散点"这个新的混淆变量,两者对模型的影响机制可能 本就不同,让实验结论不纯粹。 - 然后计算 MR 和 RR 两次前向之间的逐层余弦距离,作为"divergence"。 这样一来,MR和RR这两次前向"被扰动的token数量"是完全相等的,唯一的区别就是"被扰动 的是不是bbox区域"。如果两者差异很大,说明bbox区域确实特殊(它被mask掉之后产生的 隐藏状态,和随便mask掉同样数量的其他视觉token产生的隐藏状态很不一样);如果两者 差异很小,说明mask_region.py里观测到的"VL vs MR"的divergence,很可能主要是"扰动 操作本身"造成的,而不是bbox区域的特殊重要性造成的。 注意一个关键区别:grounding_mask_region.py对比的是"未mask的VL" vs "bbox被mask的 MR";而本脚本对比的是两个"都被mask了"的前向(MR vs RR),只是mask的token集合不同。 这是设计上故意为之的,目的就是控制"是否发生了mask扰动"这个变量,只让"mask的是不是 bbox区域"这一个变量发生变化。 随机种子(可复现性):main()在解析完--seed参数后调用random.seed(args.seed)(默认 42),全局设定Python内置random模块的种子。由于`_random_multi_rect_indices` 内部使用的正是`random.choice`,只要--seed相同、且样本遍历顺序相同(jsonl文件本身 的行序是固定的),每次运行选出的随机矩形位置就是可复现的。但注意这里用的是 random模块而不是numpy/torch的随机数生成器,所以只受这一个seed控制。 最终产出:每一层(layer)一个divergence数值,跨样本取平均后得到shape=[num_layers] 的张量并保存为.pt文件。divergence数值的含义是:在该层,"mask掉bbox区域视觉token" 与"mask掉等量随机视觉token"两种扰动方式下,模型隐藏状态的不相似程度(1-余弦相似度, 并截断到非负,见compute_divergence_per_layer)。数值越大,说明该层对"被mask的具体 是哪一块区域"越敏感,从而越能支持"bbox区域具有特殊重要性"这一结论;数值越小,说明 该层对"mask哪块区域"不敏感,原始mask_region的发现在该层可能更多是扰动伪效应。 ────────────────────────────────────────────────────────────────────────────────── """ import argparse import os import random import warnings import numpy as np import torch import torch.nn.functional as F from PIL import Image from tqdm import tqdm warnings.filterwarnings("ignore") # 从同目录下的measure_attention.py导入共享工具函数: # - convert_bbox_after_resize / get_tokens_covering_bbox:把原始像素坐标的bbox # 转换到模型实际看到的分辨率/裁剪坐标系,再映射到视觉token网格下标; # - get_dataset_paths / load_questions:读取VGMED/COCO数据集的jsonl标注; # - get_num_layers:从backend的config里读取transformer层数; # - infer_model_type / load_backend:根据model_path自动识别模型类型并加载对应 # 的模型/处理器(这里need_attn统一传False,因为本脚本只需要hidden_states,不需要 # attention矩阵,可以用更快的sdpa attention实现); # - process_input_image_and_qs_*:针对不同模型家族构造输入(图像+问题),并返回 # 视觉token在input_ids序列中的起止位置(pos, pos_end)以及token网格形状等信息; # - uses_xyxy_bbox:判断当前样本的bbox标注是xyxy格式还是xywh格式。 from measure_attention import ( convert_bbox_after_resize, get_dataset_paths, get_num_layers, get_tokens_covering_bbox, infer_model_type, load_backend, load_questions, process_input_image_and_qs_llava, process_input_image_and_qs_llava_med, process_input_image_and_qs_medgemma, process_input_image_and_qs_qwen, tokens_from_absolute_indices, uses_xyxy_bbox, visualize_masked_tokens, ) # ── hidden-state extraction ─────────────────────────────────────────────────────── # 输入:模型forward()返回的out.hidden_states(一个tuple,长度=num_layers+1, # index 0是embedding层输出,之后每个元素是一个transformer层的输出,形状通常是 # [batch, seq_len, hidden_dim])。 # 输出:torch.stack后的张量,形状[num_layers, hidden_dim]——只取"最后一个token" # (也就是模型即将生成答案的那个位置)在每一层的隐藏状态向量。之所以只看最后一个 # token,是因为这是模型"准备给出答案"时刻的表征,最适合衡量"模型对输入的理解/ # 决策"受到了多大扰动。hidden_states[1:]跳过了index 0(embedding层输出),只保留 # 真正经过transformer层处理之后的隐藏状态。 def _get_last_token_hidden_states(hidden_states): return torch.stack( [h.view(-1, h.shape[-1])[-1, :].float().detach() for h in hidden_states[1:]] ) # LLaVA-Med专用的"无mask"前向:直接把input_ids和图像张量喂给模型,拿到每层最后一个 # token的hidden state。注意:在本脚本(diff_region)的主流程里实际上没有任何地方 # 调用这个函数——因为本脚本对比的是MR vs RR两个都被mask过的前向,不需要"原始无mask" # 的基线(这一点与grounding_mask_region.py不同,那边需要hs_vl作为基线)。这个函数 # 的存在更像是从mask_region.py/diff_text.py复制过来的遗留代码,留着没有被实际调用。 def _forward_hidden_llava_med(input_ids, imgs, model): out = model( input_ids, images=imgs, output_attentions=False, output_hidden_states=True, return_dict=True, use_cache=False, ) return _get_last_token_hidden_states(out.hidden_states) # ── bbox → token indices ────────────────────────────────────────────────────────── # 作用:把一个或多个ground-truth bbox(原始图像像素坐标)转换成"该样本在input_ids # 序列中对应的绝对位置下标集合"。 # 输入: # - original_bboxes:原始bbox坐标列表(像素坐标系,xyxy或xywh格式见xyxy_format); # - original_size:原图尺寸(用于换算缩放比例); # - new_size:原图内容映射到的尺寸(对会做padding的模型如LLaVA,这只是内容 # 子矩形的尺寸,需配合pad_offset/frame_size使用,逻辑与convert_bbox_after_resize # 完全一致); # - token_shape:视觉token网格的(行数, 列数),例如Qwen动态网格、LLaVA固定24x24; # - xyxy_format:bbox是不是xyxy格式(否则认为是xywh); # - pos:该样本视觉token区间在input_ids序列中的起始绝对位置(即pos_end-pos才是 # 视觉token总数,序列里pos之前是文本/特殊token); # - pad_offset:pad阶段(缩放前,原图像素单位)加上的(left, top)留白量,非LLaVA # 模型默认(0,0)即无padding; # - frame_size:模型完整输入画面尺寸,token网格真正对应的尺寸,非LLaVA模型默认 # 等于new_size,LLaVA因为有padding,两者不同。 # 输出:(token_set, per_box_coords)二元组: # - token_set:一个set,元素是"绝对序列位置"(pos + 网格内的y*num_cols+x), # 表示所有与任意一个bbox有重叠的视觉token在整条input_ids序列中的下标。用set # 而不是list是因为多个bbox可能覆盖到同一个token,需要去重;同时也方便后面与 # "全部视觉token"做集合减法。 # - per_box_coords:list[list[(x, y)]],每个原始bbox各自覆盖的token网格坐标 # (不合并、不去重),供_random_multi_rect_indices为每个bbox单独找一个同宽高 # 的随机对照矩形用——如果只用合并后的token_set,多个不相连的bbox会让"这块GT # 区域的外包矩形"横跨一大片空白,找出来的随机矩形会比GT实际占用的token数量 # 大得多,破坏"数量相等"这个对照实验的前提。 def _bbox_to_token_set( original_bboxes, original_size, new_size, token_shape, xyxy_format, pos, pad_offset=(0, 0), frame_size=None, ): """ `new_size` is what the original image's content maps to (in frame-pixel units); `pad_offset` is the (left, top) padding added in ORIGINAL-image pixels before scaling, for processors that pad to a square before resizing (e.g. LLaVA, which pads instead of center-cropping so no bbox content is ever discarded). `frame_size` is the TRUE full model input frame the token grid spans -- this equals `new_size` for every model that doesn't pad (the default), but is LARGER than `new_size` for LLaVA specifically, since padding occupies the rest of the frame. Passing `new_size` where `frame_size` is required would make every token index wrong by the padding fraction -- see measure_attention.py's get_sample_attention for the matching logic this mirrors. """ if frame_size is None: frame_size = new_size num_cols = token_shape[1] token_set = set() per_box_coords = [] for bbox in original_bboxes: resized = convert_bbox_after_resize(bbox, original_size, new_size, xyxy_format, pad_offset) toks = get_tokens_covering_bbox(resized, token_shape, frame_size, xyxy_format) per_box_coords.append(toks) for x, y in toks: token_set.add(pos + y * num_cols + x) return token_set, per_box_coords # 这是本脚本"随机对照组"的核心:对每一个原始bbox,各自在token网格里找一个与它 # 自己外包矩形完全同宽高、且不与任何GT token或已选中的其它随机矩形重叠的连续矩形 # 区域,所有随机矩形合并起来,作为RR(Random Region)前向要mask掉的token集合。 # 输入: # - bbox_set:_bbox_to_token_set算出的、所有bbox合并后覆盖的视觉token绝对位置 # 集合(用来判断随机矩形是否与"任意一个"GT bbox重叠); # - per_box_coords:_bbox_to_token_set算出的、每个原始bbox各自覆盖的token网格 # 坐标列表(不合并),用来逐个算出每个bbox自己的外包矩形宽高; # - token_shape:视觉token网格的(行数, 列数),用于枚举矩形能摆放的位置范围; # - pos:该样本视觉token区间的起始绝对位置,把矩形内的(x, y)网格坐标换算成绝对 # 序列位置时要用(pos + y*num_cols + x)。 # 输出:所有随机矩形合并后的绝对位置list,候选位置不存在时(某个bbox在网格里找不到 # 同宽高且不重叠的位置可放)返回None,调用方据此跳过该样本。 # # 为什么要按每个bbox分别找矩形,而不是对"所有bbox合并后的整体外包矩形"找一个矩形: # 如果同一张图有多个不相连的bbox(比如COCO里同一类物体的多个实例),"合并后的整体 # 外包矩形"会横跨这些bbox之间的空白区域,尺寸远大于GT实际占用的token数量——这样 # 随机对照区域mask掉的token数量会明显多于GT区域,破坏"扰动数量相等"这一实验前提。 # 按每个bbox单独处理,保证了:(1) 每个随机矩形的形状(宽高)与它对应的那个GT bbox # 完全一致;(2) 所有随机矩形拼起来的总token数,与GT token总数完全相等(假设各个 # bbox互不重叠——如果多个bbox本身有重叠,因为token_set用set去重,GT侧总数会略小于 # 各bbox宽高之和,这种情况下随机侧总数可能略多一点,是个可接受的边界情况,不影响 # 绝大多数样本)。 # # 为什么要求"同宽高的连续矩形"而不是"数量相等的任意分散token":真实的GT bbox在 # 空间上是一个连续矩形区域,如果随机对照组是分散在图像各处的孤立token点,两者的 # "空间结构"完全不同——分散的孤立token对模型的影响机制(比如打断的是局部连续的 # 视觉信息,还是零散的、几乎不影响周围patch上下文的单点)可能与一整块连续区域 # 完全不同,这本身就会引入额外的混淆变量。要求随机区域与GT bbox形状(宽高)完全 # 一致、只是位置不同,才能让"是否命中目标物体"成为两组之间唯一的实质性差异。 # # 随机性来源于Python内置random模块,其全局种子由main()里的random.seed(args.seed) # 设定,因此只要--seed和数据遍历顺序不变,结果可复现;它不依赖torch/numpy的随机数。 def _content_token_bounds(original_size, new_size, pad_offset, frame_size, token_shape): """ For backends that pad the image to a square before resizing (LLaVA, HuatuoGPT -Vision), part of the token grid corresponds to solid-fill PADDING margins, not real image content. Returns (cx_min, cx_max, cy_min, cy_max) -- the INCLUSIVE token-grid bounds that the real (unpadded) original image content actually covers, computed by running the whole original image through the same bbox-to-token-coordinate pipeline used for GT boxes. For non-padding backends (pad_offset=(0,0), frame_size==new_size), this returns the full grid. 中文说明:对会pad的后端(LLaVA/HuatuoGPT-Vision),token网格里有一部分对应的 是纯色填充的padding边距,不是真实图像内容。这个函数算出"原图真实内容"覆盖 到的token网格范围(闭区间),做法是把整张原图当成一个bbox,套用和GT框 完全相同的坐标转换链路。返回这个范围是为了让_random_multi_rect_indices 在找随机矩形位置时,只在这个"真实内容"范围内找,不会让随机矩形的任何一部分 落到padding区域——如果不这样限制,随机矩形有一部分落在padding里,那部分 在可视化时会被content_box裁掉(视觉上显得比GT框小),更重要的是:mask掉 的那部分token对应的根本不是真实图像信息,跟"随机对照组应该扰动等量真实 图像信息"这个实验前提不符。对没有padding的后端,这个函数直接返回整个网格 范围(pad_offset=(0,0)时,content_box本来就等于整个frame)。 """ num_rows, num_cols = token_shape content_box = convert_bbox_after_resize( (0, 0, original_size[0], original_size[1]), original_size, new_size, True, pad_offset ) content_tokens = get_tokens_covering_bbox(content_box, token_shape, frame_size, True) xs = [x for x, y in content_tokens] ys = [y for x, y in content_tokens] return min(xs), max(xs), min(ys), max(ys) def _random_multi_rect_indices(bbox_set, per_box_coords, token_shape, pos, content_bounds=None): num_rows, num_cols = token_shape if content_bounds is None: content_bounds = (0, num_cols - 1, 0, num_rows - 1) cx_min, cx_max, cy_min, cy_max = content_bounds occupied = set(tokens_from_absolute_indices(bbox_set, pos, num_cols)) chosen = set() for coords in per_box_coords: if not coords: continue xs = [x for x, y in coords] ys = [y for x, y in coords] x_min, x_max = min(xs), max(xs) y_min, y_max = min(ys), max(ys) w = x_max - x_min + 1 h = y_max - y_min + 1 if w > (cx_max - cx_min + 1) or h > (cy_max - cy_min + 1): return None blocked = occupied | chosen candidates = [] # 只在[cx_min, cx_max] x [cy_min, cy_max]这个"真实内容"范围内枚举候选 # 位置,保证矩形的每一个格子都落在真实内容区域,不会碰到padding。 for ry in range(cy_min, cy_max - h + 2): for rx in range(cx_min, cx_max - w + 2): rect = [(rx + dx, ry + dy) for dx in range(w) for dy in range(h)] if not any((x, y) in blocked for x, y in rect): candidates.append((rx, ry)) if not candidates: return None rx, ry = random.choice(candidates) chosen.update((rx + dx, ry + dy) for dx in range(w) for dy in range(h)) return [pos + y * num_cols + x for x, y in chosen] # ── masked forward ──────────────────────────────────────────────────────────────── # 通用的"多模态投影层(mm_projector / multi_modal_projector)输出"hook工厂函数: # 适用于medgemma/llava/llava_med/huatuogpt这几个"视觉编码器输出经过一个projector # 才进入语言模型"的架构。hook会在projector前向之后,把output里属于mask_indices # 指定的视觉token位置整个置零(对应一整个hidden_dim维度清零,而不是部分维度)。 # proj_idx = seq_idx - pos:因为projector的输出张量只包含视觉token(形状大致是 # [batch, num_visual, hidden_dim]),而mask_indices存的是"整条input_ids序列中的 # 绝对位置",需要减去pos换算成projector输出张量内部的相对下标。 # 这个hook与grounding_mask_region.py里的同名函数完全一致(同一种mask机制,只是 # 本脚本会用它分别对bbox_set和rand_indices各跑一次,得到MR和RR两个隐藏状态)。 def _make_proj_hook(mask_indices, pos, pos_end): num_visual = pos_end - pos def _hook(module, args, output): out = output.clone() for seq_idx in mask_indices: proj_idx = seq_idx - pos if 0 <= proj_idx < num_visual and proj_idx < out.shape[1]: out[:, proj_idx, :] = 0.0 return out return _hook # Qwen2.5-VL/Qwen3-VL专用:Qwen的视觉token不经过普通的"projector",而是先过 # vision encoder,再过一个merger模块(把多个patch合并/投影到语言模型的hidden_dim), # 所以这里hook挂在model.model.visual.merger上而不是_make_proj_hook用的 # multi_modal_projector。_zeroed这个一元素list是为了防止该hook在同一次forward中 # 被多次调用时重复处理(保险措施,正常情况下merger在一次forward里只会被调用一次)。 # 输入:inputs(processor构造好的模型输入字典)、model、mask_indices(要清零的 # 绝对序列位置列表,可以是bbox_set也可以是rand_indices)、pos/pos_end(视觉token # 区间)。输出:_get_last_token_hidden_states处理后的[num_layers, hidden_dim]张量。 def _forward_hidden_masked_qwen(inputs, model, mask_indices, pos, pos_end): # hook on merger output to zero visual tokens after full visual encoding _zeroed = [False] def _merger_hook(module, args, output): if not _zeroed[0]: _zeroed[0] = True out = output.clone() num_visual = pos_end - pos for seq_idx in mask_indices: proj_idx = seq_idx - pos if 0 <= proj_idx < num_visual and proj_idx < out.shape[0]: out[proj_idx, :] = 0.0 return out handle = model.model.visual.merger.register_forward_hook(_merger_hook) try: out = model( **inputs, output_attentions=False, output_hidden_states=True, return_dict=True, use_cache=False, ) finally: handle.remove() return _get_last_token_hidden_states(out.hidden_states) # MedGemma专用:在multi_modal_projector输出上挂_make_proj_hook,前向一次后即把 # hook移除(finally块保证即使forward抛异常也会清理,避免hook泄漏影响下一次调用)。 def _forward_hidden_masked_medgemma(inputs, model, mask_indices, pos, pos_end): handles = [model.multi_modal_projector.register_forward_hook( _make_proj_hook(mask_indices, pos, pos_end))] try: out = model(**inputs, output_attentions=False, output_hidden_states=True, return_dict=True, use_cache=False) finally: for h in handles: h.remove() return _get_last_token_hidden_states(out.hidden_states) # LLaVA(HF版LlavaForConditionalGeneration)专用:同样挂在multi_modal_projector上。 def _forward_hidden_masked_llava(inputs, model, mask_indices, pos, pos_end): handles = [model.multi_modal_projector.register_forward_hook( _make_proj_hook(mask_indices, pos, pos_end))] try: out = model(**inputs, output_attentions=False, output_hidden_states=True, return_dict=True, use_cache=False) finally: for h in handles: h.remove() return _get_last_token_hidden_states(out.hidden_states) # LLaVA-Med专用:投影层命名因实现版本不同而不同,做了一个兼容性判断 # (有的版本叫multi_modal_projector,原版LLaVA-Med代码里叫mm_projector,挂在 # model.get_model()返回的内部模型对象上)。输入参数额外多了input_ids和imgs,因为 # LLaVA-Med的前向接口不是用**inputs展开,而是显式传位置参数。 def _forward_hidden_masked_llava_med(input_ids, imgs, model, mask_indices, pos, pos_end): projector = model.multi_modal_projector if hasattr(model, "multi_modal_projector") else model.get_model().mm_projector handles = [projector.register_forward_hook(_make_proj_hook(mask_indices, pos, pos_end))] try: out = model(input_ids, images=imgs, output_attentions=False, output_hidden_states=True, return_dict=True, use_cache=False) finally: for h in handles: h.remove() return _get_last_token_hidden_states(out.hidden_states) # HuatuoGPT-Vision专用:与上面几个函数的区别在于,Huatuo没有统一的processor, # 需要手动走bot自己的预处理流程(input_moderation→插入图像占位符→构造对话→ # tokenize→单独处理图像张量),这一整套与measure_attention.py里_huatuo_run_forward # 的预处理逻辑保持一致,只是这里额外挂了mm_projector的mask hook。 def _forward_hidden_masked_huatuo(text, image_path, backend, mask_indices, pos, pos_end): bot = backend["bot"] text = bot.input_moderation(text) text = bot.insert_image_placeholder(text, 1) conv = bot.get_conv_without_history(text) input_ids = bot.preprocess(conv, return_tensors="pt").unsqueeze(0).to(bot.device) image_tensors = (torch.stack(bot.get_image_tensors([image_path])) .to(dtype=torch.bfloat16).to(bot.device)) handles = [bot.model.get_model().mm_projector.register_forward_hook( _make_proj_hook(mask_indices, pos, pos_end))] try: out = bot.model(input_ids, images=image_tensors, output_attentions=False, output_hidden_states=True, return_dict=True, use_cache=False) finally: for h in handles: h.remove() return _get_last_token_hidden_states(out.hidden_states) # ── per-sample extraction ───────────────────────────────────────────────────────── # 整个脚本的核心调度函数:对单个样本,按模型类型分支处理,最终返回(hs_bbox, hs_rand) # 这一对隐藏状态张量,供外层计算divergence。 # 输入:sample(一条jsonl记录,含image/bbox/question/label等字段)、data_path # (图片所在目录)、dataset("VGMED"或"COCO",用于判断bbox格式)、backend(已加载 # 好的模型与处理器字典)、layers(未在函数体内被使用,是历史遗留参数,保留是为了 # 与measure_attention.py及兄弟脚本签名保持一致)、q_type(影响question末尾追加 # 的指令文本,"attribute"用自由文本回答指令,否则用yes/no指令)。 # 输出:成功时返回(hs_bbox, hs_rand)二元组,形状均为[num_layers, hidden_dim]; # 任意一步出错(包括"非bbox候选token不够、无法采样出等量随机区域"的情况)都返回 # None,由调用方(main)统计为skip_other并跳过该样本。 # 处理流程对每种backend类型都遵循同一个三步模式: # (1) 用process_input_image_and_qs_*构造模型输入,同时拿到视觉token网格形状 # token_shape、预处理后图像尺寸new_size、视觉token在序列中的[pos, pos_end)区间; # (2) 用_bbox_to_token_set把GT bbox映射成bbox_set(绝对序列位置集合),再用 # _random_multi_rect_indices找一个同宽高、不重叠的连续矩形区域rand_indices; # (3) 分别对bbox_set和rand_indices调用对应模型的_forward_hidden_masked_*函数, # 得到MR前向的hs_bbox和RR前向的hs_rand——这两次前向使用完全相同的原始输入 # (inputs/input_ids不变),唯一区别就是hook里清零的token下标集合不同。 def get_sample_hidden_states(sample, data_path, dataset, backend, layers, q_type="localization"): image_name = sample["image"] image_path = os.path.join(data_path, image_name) original_size = Image.open(image_path).size original_bboxes = sample.get("bbox") or sample.get("original_bboxes") question_raw = sample.get("question", "") if q_type == "attribute": question = question_raw + "\nAnswer the question using a single word or phrase." else: question = question_raw + "\nPlease output 'yes' or 'no'(no extra output)." btype = backend["type"] xyxy_format = uses_xyxy_bbox(dataset, image_name) # pad_offset/frame_size默认值同measure_attention.py:只有llava和 # huatuogpt_vision这两个分支会覆盖成非默认值,之后统一用于计算content_box # (给visualize_masked_tokens做token网格->原图像素空间的重采样)。 pad_offset = (0, 0) frame_size = None try: # Qwen2.5-VL / Qwen3-VL分支:process_input_image_and_qs_qwen返回的 # general_inputs(第二个返回值,用_忽略)在本脚本里不需要——那是 # measure_attention.py里给"通用问题baseline"用的,本脚本不做attention归一化, # 不需要这个baseline,只是复用同一个预处理函数省得重复写代码。 if btype in {"qwen2_5vl", "qwen3vl"}: inputs, _, token_shape, new_size, pos, pos_end = \ process_input_image_and_qs_qwen(image_path, question, backend) bbox_set, per_box_coords = _bbox_to_token_set( original_bboxes, original_size, new_size, token_shape, xyxy_format, pos) rand_indices = _random_multi_rect_indices(bbox_set, per_box_coords, token_shape, pos) if rand_indices is None: return None # 用同一份inputs分别跑MR(mask掉bbox_set)和RR(mask掉rand_indices)两次 # 前向,得到的hs_bbox/hs_rand将在外层用于计算逐层divergence。 hs_bbox = _forward_hidden_masked_qwen(inputs, backend["model"], list(bbox_set), pos, pos_end) hs_rand = _forward_hidden_masked_qwen(inputs, backend["model"], rand_indices, pos, pos_end) # MedGemma分支:与Qwen分支同一套三步模式(构造输入→算bbox_set/rand_indices→ # 跑两次masked前向),区别只在于process_input_image_and_qs_medgemma对图像的 # 预处理方式(MedGemma是直接拉伸缩放到固定方形尺寸,没有center-crop)以及 # _forward_hidden_masked_medgemma挂hook的位置(multi_modal_projector)。 elif btype == "medgemma": inputs, _, token_shape, new_size, pos, pos_end = \ process_input_image_and_qs_medgemma(image_path, question, backend) bbox_set, per_box_coords = _bbox_to_token_set( original_bboxes, original_size, new_size, token_shape, xyxy_format, pos) rand_indices = _random_multi_rect_indices(bbox_set, per_box_coords, token_shape, pos) if rand_indices is None: return None hs_bbox = _forward_hidden_masked_medgemma(inputs, backend["model"], list(bbox_set), pos, pos_end) hs_rand = _forward_hidden_masked_medgemma(inputs, backend["model"], rand_indices, pos, pos_end) elif btype == "llava": # LLaVA分支比其他模型多了pad_offset和frame_size:因为LLaVA的图像预处理 # 是"先把原图pad成正方形,再等比缩放到crop_size"(而不是直接resize), # bbox坐标转换必须知道加了多少padding、以及模型完整输入画面的真实尺寸, # 才能正确落到token网格上,这两个值被传给_bbox_to_token_set用于修正bbox # 坐标(具体计算逻辑在measure_attention.py的convert_bbox_after_resize # 和get_sample_attention里)。 inputs, _, token_shape, new_size, pos, pos_end, pad_offset, frame_size = \ process_input_image_and_qs_llava(image_path, question, backend) bbox_set, per_box_coords = _bbox_to_token_set( original_bboxes, original_size, new_size, token_shape, xyxy_format, pos, pad_offset, frame_size) # LLaVA会pad成正方形,token网格里有一部分是padding边距、不是真实 # 图像内容,随机矩形选址必须排除这部分范围(见_content_token_bounds # 和_random_multi_rect_indices的说明),否则随机矩形可能有一部分 # 落在padding里,既会在可视化时被裁掉显得比GT框小,也意味着mask掉 # 的token并非全部对应真实图像信息。 content_bounds = _content_token_bounds( original_size, new_size, pad_offset, frame_size, token_shape) rand_indices = _random_multi_rect_indices( bbox_set, per_box_coords, token_shape, pos, content_bounds) if rand_indices is None: return None hs_bbox = _forward_hidden_masked_llava(inputs, backend["model"], list(bbox_set), pos, pos_end) hs_rand = _forward_hidden_masked_llava(inputs, backend["model"], rand_indices, pos, pos_end) # LLaVA-Med分支:固定336x336输入→24x24=576个视觉token(写死在 # process_input_image_and_qs_llava_med里),不需要pad_offset/frame_size;前向接口 # 用显式的input_ids/imgs位置参数而不是**inputs字典展开,所以这里多带了 # input_ids和imgs两个变量传给_forward_hidden_masked_llava_med。 elif btype == "llava_med": input_ids, _, imgs, token_shape, new_size, pos, pos_end = \ process_input_image_and_qs_llava_med(image_path, question, backend) bbox_set, per_box_coords = _bbox_to_token_set( original_bboxes, original_size, new_size, token_shape, xyxy_format, pos) rand_indices = _random_multi_rect_indices(bbox_set, per_box_coords, token_shape, pos) if rand_indices is None: return None hs_bbox = _forward_hidden_masked_llava_med(input_ids, imgs, backend["model"], list(bbox_set), pos, pos_end) hs_rand = _forward_hidden_masked_llava_med(input_ids, imgs, backend["model"], rand_indices, pos, pos_end) elif btype == "huatuogpt_vision": # HuatuoGPT没有像Qwen/MedGemma/LLaVA那样统一的process_input_image_and_qs_* # 辅助函数,需要在这里手动重复一遍bot的预处理流程,目的只是为了找到图像 # 占位符token(-200)在input_ids里的位置img_pos,从而推算出视觉token区间 # [img_pos, img_pos+HUATUO_NUM_IMG_TOKENS)。注意这里固定使用 # HUATUO_SIZE(336x336)和HUATUO_PATCHES(24x24)这两个写死的常量 # (定义在measure_attention.py),因为Huatuo的视觉编码器输入分辨率固定。 from measure_attention import HUATUO_NUM_IMG_TOKENS, HUATUO_PATCHES, HUATUO_SIZE bot = backend["bot"] text_mod = bot.input_moderation(question) text_mod = bot.insert_image_placeholder(text_mod, 1) conv = bot.get_conv_without_history(text_mod) input_ids_raw = bot.preprocess(conv, return_tensors="pt") ids_list = input_ids_raw.reshape(-1).tolist() img_pos = next(i for i, t in enumerate(ids_list) if t == -200) token_shape = (HUATUO_PATCHES, HUATUO_PATCHES) pos_end = img_pos + HUATUO_NUM_IMG_TOKENS # HuatuoGPT-Vision自己的预处理(HuatuoChatbot.get_image_tensors的 # expand2square)会先把原图pad成正方形再等比缩放到HUATUO_SIZE, # 跟LLaVA是同一种手法,所以bbox坐标转换也需要同样的pad_offset/ # frame_size处理,否则会被当成"纯拉伸"错误地计算(非正方形图片上 # 会静默算错bbox位置)。参见measure_attention.py的 # generate_attention_maps_huatuo。 w_orig, h_orig = original_size square_size = max(w_orig, h_orig) pad_left = (square_size - w_orig) // 2 pad_top = (square_size - h_orig) // 2 scale = HUATUO_SIZE[0] / square_size new_size = (round(w_orig * scale), round(h_orig * scale)) pad_offset = (pad_left, pad_top) frame_size = HUATUO_SIZE pos = img_pos bbox_set, per_box_coords = _bbox_to_token_set( original_bboxes, original_size, new_size, token_shape, xyxy_format, img_pos, pad_offset, frame_size, ) # 同LLaVA分支:HuatuoGPT-Vision也会pad,随机矩形选址要排除padding区域。 content_bounds = _content_token_bounds( original_size, new_size, pad_offset, frame_size, token_shape) rand_indices = _random_multi_rect_indices( bbox_set, per_box_coords, token_shape, pos, content_bounds) if rand_indices is None: return None # 注意:_forward_hidden_masked_huatuo内部会重新走一遍input_moderation→ # insert_image_placeholder→preprocess的流程构造输入(而不是复用上面已经 # 算出的input_ids_raw),这里调用了两次(一次MR一次RR),等价于对同一个 # question+image又预处理了两遍——逻辑上没问题(结果应该完全确定、可复现), # 只是有一点重复计算的开销。 hs_bbox = _forward_hidden_masked_huatuo(question, image_path, backend, list(bbox_set), img_pos, pos_end) hs_rand = _forward_hidden_masked_huatuo(question, image_path, backend, rand_indices, img_pos, pos_end) else: raise ValueError(f"Unknown backend type: {btype}") except Exception as e: # 再包一层try/except:防止异常信息本身(比如包含终端编码打印不出来的 # 字符)导致这两行打印自己也抛异常——那样"本该被优雅跳过"的错误反而会 # 变成让整个脚本崩溃的未捕获异常,彻底违背这里try/except想要的效果。 try: import traceback traceback.print_exc() print(f"[Warning] Skipping {image_name}: {e}") except Exception: print(f"[Warning] Skipping {image_name}: ") return None # 理论上MR和RR两次前向用的是同一个模型、同样数量的transformer层,hs_bbox和 # hs_rand的层数应该天然相等;这里取min并截断只是一个防御性写法,防止个别模型 # 实现在某些边界情况下两次前向返回的hidden_states长度不一致导致后续除0/维度 # 不匹配的错误。 num_layers = min(hs_bbox.shape[0], hs_rand.shape[0]) if frame_size is None: frame_size = new_size # content_box:原图内容在模型完整输入画面里占据的位置,用于 # visualize_masked_tokens把token网格重新采样回原图像素空间(逻辑与 # measure_attention.py的get_sample_attention完全一致)。 content_box = convert_bbox_after_resize( (0, 0, original_size[0], original_size[1]), original_size, new_size, True, pad_offset ) viz_info = { "bbox_indices": list(bbox_set), "rand_indices": rand_indices, "pos": pos, "token_shape": token_shape, "frame_size": frame_size, "content_box": content_box, } return hs_bbox[:num_layers], hs_rand[:num_layers], viz_info # ── divergence ──────────────────────────────────────────────────────────────────── # 计算MR与RR两次前向之间的"逐层divergence":对每一层,取该层最后一个token的隐藏 # 状态向量,计算两者的余弦相似度,再用1减去它得到"距离"(取值范围理论上是[0, 2], # 因为余弦相似度范围是[-1, 1])。.clamp(min=0.0)把负的divergence截断为0——余弦相似度 # 超过1(数值误差)或者两个方向恰好接近导致1-cos稍微为负的极端情况下保险处理, # 同时也让"divergence"在语义上更符合"距离不应为负"的直觉。 # 输入:hs_bbox, hs_rand均为[num_layers, hidden_dim]。 # 输出:[num_layers]的一维张量,每个元素是该层的divergence。 def compute_divergence_per_layer(hs_bbox: torch.Tensor, hs_rand: torch.Tensor) -> torch.Tensor: return (1.0 - F.cosine_similarity(hs_bbox, hs_rand, dim=-1)).clamp(min=0.0) # ── save ────────────────────────────────────────────────────────────────────────── # 把跨样本平均后的divergence张量存到磁盘,路径形如 # {output_root}/{model_name}/diff_region/{dataset}_{q_type}_mean_divergence_per_layer.pt # 子目录名"diff_region"与对照组脚本grounding_mask_region.py使用的"mask_region" # 子目录区分开,避免两个脚本的输出互相覆盖。 def save_divergences(output_root, model_name, dataset, q_type, mean_div): save_path = os.path.join(output_root, model_name, "diff_region") os.makedirs(save_path, exist_ok=True) torch.save(mean_div, f"{save_path}/{dataset}_{q_type}_mean_divergence_per_layer.pt") # ── CLI ─────────────────────────────────────────────────────────────────────────── # 命令行参数定义。与grounding_mask_region.py几乎完全相同,唯一的额外参数是 # --seed(默认42)——这是本脚本(含随机对照组)特有的,mask_region.py没有随机性 # 所以不需要seed参数。这个--seed最终会传给main()里的random.seed(),用来控制 # _random_multi_rect_indices内部random.choice的可复现性。 def parse_args(): parser = argparse.ArgumentParser() parser.add_argument("--dataset", type=str, choices=["VGMED", "COCO"], required=True) parser.add_argument("--q_type", type=str, choices=["localization", "attribute"], required=True) parser.add_argument("--model_path", type=str, required=True) parser.add_argument("--model_base_path", type=str, default=None) parser.add_argument("--model_type", type=str, default="auto", choices=["auto", "qwen2_5vl", "qwen3vl", "medgemma", "llava", "llava_med", "huatuogpt_vision"]) parser.add_argument("--device", type=str, default="cuda:0") parser.add_argument("--huatuo_repo", type=str, default="./HuatuoGPT-Vision") parser.add_argument("--qwen_vl_utils_path", type=str, default=None) parser.add_argument("--vgmed_root", type=str, default=None) parser.add_argument("--coco_root", type=str, default=None) parser.add_argument("--coco_annotation_root", type=str, default=None) parser.add_argument("--output_root", type=str, required=True) parser.add_argument("--hf_home", type=str, default=None) parser.add_argument("--seed", type=int, default=42) parser.add_argument( "--no_visualize", action="store_false", dest="visualize", help="Disable saving GT-region/random-region-highlight sanity-check images " "(on by default)", ) parser.set_defaults(visualize=True) parser.add_argument( "--visualize_limit", type=int, default=50, help="Max number of samples to save highlight images for (default: 50).", ) args = parser.parse_args() if args.dataset == "VGMED" and not args.vgmed_root: parser.error("--vgmed_root is required when --dataset VGMED.") if args.dataset == "COCO": if not args.coco_root: parser.error("--coco_root is required when --dataset COCO.") if not args.coco_annotation_root: parser.error("--coco_annotation_root is required when --dataset COCO.") return args # ── main ───────────────────────────────────────────────────────────────────────── def main(): args = parse_args() if args.hf_home: os.environ["HF_HOME"] = args.hf_home # 在加载模型/读取数据之前就设定全局随机种子,保证后续对每个样本调用 # _random_multi_rect_indices(底层用random.choice)时,只要数据遍历顺序和 # 样本数不变,选出的"随机对照矩形区域"在多次运行之间是完全一致的,便于结果 # 复现和调试对比。 random.seed(args.seed) model_name = os.path.basename(os.path.normpath(args.model_path)) model_type = infer_model_type(args.model_path, args.model_type) # need_attn=False:本脚本只需要hidden_states,不需要attention矩阵,因此可以让 # 底层模型使用更快/更省显存的attention实现(如sdpa),而不必强制切换到eager。 backend = load_backend( args.model_path, args.model_base_path, model_type=model_type, device=args.device, huatuo_repo=args.huatuo_repo, qwen_vl_utils_path=args.qwen_vl_utils_path, need_attn=False, ) input_path, data_path = get_dataset_paths(args) questions = load_questions(input_path) layers = range(get_num_layers(backend)) all_divergences = [] # 四类跳过原因的计数器,用于最后打印诊断信息,帮助判断数据集质量/管线是否正常: # skip_no_bbox:样本没有bbox标注,无法做grounding分析; # skip_no_question:样本没有question字段; # skip_label_not_in_question:label字段不是question文本的子串(数据一致性检查, # 虽然这个检查在本脚本中实际并未使用label去定位任何token,纯粹是过滤可疑样本); # skip_other:get_sample_hidden_states内部出错(包括模型前向异常、或者非bbox # 候选token不足以采样出与bbox等量的随机区域这种正常但无法处理的情况)。 skip_no_bbox = 0 skip_no_question = 0 skip_label_not_in_question = 0 skip_other = 0 visualized_count = 0 with torch.no_grad(): for sample in tqdm(questions): if not (sample.get("bbox") or sample.get("original_bboxes")): skip_no_bbox += 1 continue if not sample.get("question", ""): skip_no_question += 1 continue label = sample.get("label", "") if not label or label not in sample.get("question", ""): skip_label_not_in_question += 1 continue result = get_sample_hidden_states(sample, data_path, args.dataset, backend, layers, args.q_type) if result is None: skip_other += 1 continue hs_bbox, hs_rand, viz_info = result # 逐样本计算[num_layers]的divergence,先搬到cpu转numpy再append,避免 # 显存随样本数线性增长(所有样本算完后才一次性stack成二维数组求平均)。 div = compute_divergence_per_layer(hs_bbox, hs_rand) all_divergences.append(div.cpu().numpy()) # 抽样保存"GT区域(红) + 随机对照区域(蓝)"高亮图,供人工确认两组区域 # 是否互不重叠、GT区域是否真的落在目标物体上——这两点是"随机对照组" # 实验设计成立的前提,光看divergence数值完全看不出坐标算得对不对。 if args.visualize and visualized_count < args.visualize_limit: visualized_count += 1 image_name = sample["image"] image_path = os.path.join(data_path, image_name) original_size = Image.open(image_path).size stem = os.path.splitext(os.path.basename(image_name))[0] save_path = os.path.join( args.output_root, model_name, "diff_region", "masks", args.dataset, args.q_type, f"{stem}.png", ) num_cols = viz_info["token_shape"][1] bbox_tokens = tokens_from_absolute_indices( viz_info["bbox_indices"], viz_info["pos"], num_cols ) rand_tokens = tokens_from_absolute_indices( viz_info["rand_indices"], viz_info["pos"], num_cols ) visualize_masked_tokens( image_path=image_path, original_size=original_size, token_shape=viz_info["token_shape"], frame_size=viz_info["frame_size"], content_box=viz_info["content_box"], primary_tokens=bbox_tokens, secondary_tokens=rand_tokens, save_path=save_path, ) # 跳过统计无论后面有没有成功样本都要打印——之前的写法是"all_divergences为空 # 就直接return",导致全部样本失败时,终端只能看到一行"No samples processed.", # 看不出到底是skip_no_bbox/skip_no_question/skip_label_not_in_question/ # skip_other里哪一类占了大头,排查问题时完全没有线索。现在提前到判断之前打印, # 保证不管成功与否都能看到完整的分类统计。 total_skipped = skip_no_bbox + skip_no_question + skip_label_not_in_question + skip_other print(f"\nTotal in dataset : {len(questions)}") print(f"Skipped (no bbox) : {skip_no_bbox}") print(f"Skipped (no question) : {skip_no_question}") print(f"Skipped (label not in question): {skip_label_not_in_question}") print(f"Skipped (other error) : {skip_other}") print(f"Total skipped : {total_skipped}") print(f"Samples processed : {len(all_divergences)}") if not all_divergences: print("[Error] No samples processed.") return # 把所有样本的[num_layers]向量堆叠成[num_samples, num_layers]矩阵, # 按样本维度(axis=0)求平均,得到最终的[num_layers]"跨样本平均divergence", # 即文件开头总览中说明的"最终产出"。 div_array = np.stack(all_divergences) mean_div = torch.tensor(div_array.mean(axis=0)) print(f"Num layers : {mean_div.shape[0]}") print(f"Mean divergence : {mean_div.numpy()}") save_divergences(args.output_root, model_name, args.dataset, args.q_type, mean_div) print(f"\n[Saved] {args.output_root}/{model_name}/diff_region/{args.dataset}_{args.q_type}_mean_divergence_per_layer.pt") if __name__ == "__main__": main()