""" grounding_diff_text.py — Visual Influence Analysis (Label Mask vs Random Text Mask Divergence) ================================================================================================ For each sample: 1. MT forward pass (label tokens masked) → hs_label [num_layers, D] 2. RT forward pass (random equal-count text tokens masked) → hs_rand [num_layers, D] 3. Per-layer divergence: D[i] = 1 - cosine(hs_label[i], hs_rand[i]) 4. Save mean divergence across all samples: shape [num_layers] This directly measures how differently the model processes label-masked vs randomly-masked text inputs. A large divergence means the label tokens are distinctly important to the model. Supported models : qwen2_5vl, qwen3vl, medgemma, llava, llava_med, huatuogpt_vision Supported datasets: VGMED, COCO ────────────────────────────────────────────────────────────────────────────────── 【中文总览 / 整体说明】 ────────────────────────────────────────────────────────────────────────────────── 本脚本是 grounding_mask_text.py 的"随机对照实验"版本。 背景动机(为什么需要这个脚本): grounding_mask_text.py 做的事情是:对比"完整输入(VL)的前向"与"把label token清零之后(MT) 的前向"之间的隐藏状态差异(divergence)。如果这个divergence很大,研究者会倾向于解读为 "label token对模型很重要,把它mask掉会显著改变模型的内部表征"。 但这个解读存在一个混淆因素(confound):模型的隐藏状态本来就会因为"任意位置的token被 清零"这种扰动而发生变化——这种变化可能只是因为"输入被改动了"这一事实本身,而不是因为 被改动的恰好是label token。换句话说,mask_text观测到的divergence,可能只是"扰动任意 token都会产生的伪效应(artifact)",而不是label token真的有特殊地位的证据。 为了排除这个混淆因素,本脚本设计了一个随机对照组: - MT前向:依然是把label token清零(与mask_text脚本中的MT完全一致的操作)。 - RT前向(Random Text,本脚本独有):不再使用完整未mask的输入做对比,而是随机挑选 "与label token数量相同、但内容随机、且不包含真实label token"的其他文本token,把 它们清零,作为对照。 - 然后计算 MT 和 RT 两次前向之间的逐层余弦距离,作为"divergence"。 这样一来,MT和RT这两次前向"扰动的token数量"是完全相等的,唯一的区别就是"被扰动的是 不是label token"。如果两者差异很大,说明label token确实特殊(它被mask掉之后产生的 隐藏状态,和随便mask掉同样数量的其他token产生的隐藏状态很不一样);如果两者差异很小, 说明mask_text.py里观测到的"VL vs MT"的divergence,很可能主要是"扰动操作本身"造成的, 而不是label token的特殊重要性造成的。 注意一个关键区别:grounding_mask_text.py对比的是"未mask的VL" vs "label被mask的MT"; 而本脚本对比的是两个"都被mask了"的前向(MT vs RT),只是mask的token集合不同。这是 设计上故意为之的,目的就是控制"是否发生了mask扰动"这个变量,只让"mask的是不是label" 这一个变量发生变化。 最终产出:每一层(layer)一个divergence数值,跨样本取平均后得到shape=[num_layers]的 张量并保存为.pt文件。divergence数值的含义是:在该层,"mask掉label token"与"mask掉 等量随机文本token"两种扰动方式下,模型隐藏状态的不相似程度(1-余弦相似度,并截断到 非负)。数值越大,说明该层对"被mask的具体是什么token"越敏感,从而越能支持"label token 具有特殊重要性"这一结论;数值越小,说明该层对"mask哪个token"不敏感,原始mask_text的 发现在该层可能更多是扰动伪效应。 ────────────────────────────────────────────────────────────────────────────────── """ import argparse import os import random import warnings import numpy as np import torch import torch.nn.functional as F from tqdm import tqdm warnings.filterwarnings("ignore") # 从同目录下的measure_attention.py导入共享工具函数: # - get_dataset_paths / load_questions:读取VGMED或COCO数据集的jsonl标注文件路径与样本列表 # - get_num_layers:获取当前backend模型的transformer层数 # - infer_model_type / load_backend:根据model_path自动识别模型类型(qwen/medgemma/llava等) # 并加载对应的模型、processor/tokenizer,统一封装进backend字典里 # - process_input_image_and_qs_xxx:针对不同模型,把(图像路径, 问题文本)预处理成模型forward # 所需的input_ids/inputs,并定位图像token在序列中的起止位置(pos, pos_end) # 这些函数与grounding_mask_text.py共用同一套实现,保证两个对照实验脚本的输入预处理逻辑一致, # 这样两者算出来的divergence才具有可比性。 from measure_attention import ( get_dataset_paths, get_num_layers, 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, render_masked_text_image, ) # ── hidden-state extraction ─────────────────────────────────────────────────────── # 【函数说明】从某一次forward返回的hidden_states元组中,抽取"最后一个token"在每一层 # 的隐藏向量,并堆叠成形如[num_layers, hidden_dim]的张量。 # 之所以只取最后一个token:在这类自回归VLM的设定下,最后一个token(通常是即将生成答案 # 前的位置)的隐藏状态被视为模型对"整段输入(图像+问题)"信息整合后的汇总表征,最适合用来 # 比较"换了不同mask策略后,模型对同一个问题的理解/表征发生了多大变化"。 # hidden_states[1:]跳过的是第0个元素(embedding层输出,即输入嵌入本身,不算"transformer层" # 的输出),所以返回的张量第0维大小才等于num_hidden_layers。 # 输入:hidden_states —— 模型forward返回的tuple,每个元素形状大致为[batch, seq_len, hidden_dim] # 输出:torch.Tensor,shape=[num_layers, hidden_dim],已detach、转为float32(脱离计算图,方便后续cosine计算与保存) 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"前向封装(注意:本文件中实际调用的都是带mask的版本, # 见下方_forward_hidden_masked_llava_med;这个函数在当前主流程里似乎未被直接使用,更像是 # 历史遗留/与mask_text.py保持接口对称而保留的工具函数,仅做forward+取隐藏状态,不做任何mask)。 # 输入:input_ids、imgs(预处理后的图像张量)、model # 输出:该次forward每层最后一个token的隐藏状态,shape=[num_layers, hidden_dim] 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) # ── label → token indices ───────────────────────────────────────────────────────── # 【函数说明】在input_ids序列中定位label字符串对应的token下标集合。 # 实现思路:因为同一个label字符串在不同分词上下文里可能被tokenizer编码成不同的token id # 序列(例如句首/句中、有无前导空格、大小写不同),所以这里穷举了4种候选写法 # [原样, 前面加空格, 小写, 小写+前导空格]分别编码,然后在input_ids_list中做"子序列匹配", # 任何一种候选匹配上的位置都会被加入found这个集合(用set是为了自动去重,避免多个候选 # 写法命中同一段位置时重复计数)。 # 这个函数与grounding_mask_text.py中查找label token的逻辑保持一致,这一点很重要: # 本脚本的MT前向(mask label)必须mask出与mask_text.py完全相同的token集合,否则两个 # 脚本的对照结果就不可比了。 # 输入:input_ids_list(int列表,完整token序列)、label(字符串)、tokenizer # 输出:label token在序列中的下标集合(set[int]),如果一个label没有任何候选匹配成功, # 返回空集合(调用处会因len(label_set)==0导致后续随机采样n=0,相当于不mask任何token, # 但理论上主流程已经用`label not in question`提前过滤掉了这种样本,正常不会发生)。 def _find_label_token_indices(input_ids_list, label, tokenizer): candidates = [label, " " + label, label.lower(), " " + label.lower()] found = set() for cand in candidates: label_ids = tokenizer.encode(cand, add_special_tokens=False) if not label_ids: continue n = len(label_ids) for i in range(len(input_ids_list) - n + 1): if input_ids_list[i:i + n] == label_ids: for j in range(n): found.add(i + j) return found # 【函数说明】仅用于LLaVA-Med/HuatuoGPT这两种模型:它们的input_ids里图像只用单个 # IMAGE_TOKEN_INDEX占位符表示,真正forward时这一个占位符会在模型内部被展开成多个 # (576个)视觉embedding。这导致"在input_ids里数出来的下标"和"展开后真正喂进embedding # hook的下标"不是一一对应的——展开之后,原本位于img_pos之后的文本token,其在"展开后 # 序列"中的实际位置都要整体左移1位(因为1个占位符变成了576个视觉token,多出来的部分 # 会把后面的文本顶到更后面,所以要先把input_ids里的下标减1,再去推算它在展开后大序列 # 里对应的偏移;这里减1的本质是"补偿占位符本身只占1个位置,而不是576个位置"的差异, # 配合_make_emb_hook里对输出embedding张量的下标操作)。 # 不适用于LLaVA(HF LlavaProcessor):它的input_ids本身就已经包含576个真实的图像token # 条目(没有"1个占位符展开成576个"这一步),所以在input_ids中找到的下标已经是展开后 # 的绝对位置,应该直接用_random_non_label_text_indices(不做调整),和qwen/medgemma # 的处理方式相同。 def _adjust_text_indices_for_image_placeholder(indices, img_pos): """LLaVA-Med/HuatuoGPT only: these use a single IMAGE_TOKEN_INDEX placeholder in input_ids that gets expanded into multiple visual embeddings internally, so text token positions after img_pos are shifted left by 1 relative to input_ids. Does NOT apply to LLaVA (HF LlavaProcessor): there, input_ids already contains 576 real image-token entries (no placeholder expansion), so indices found in input_ids are already correct absolute positions -- use _random_non_label_text_indices (no adjustment) instead, same as qwen/medgemma.""" return [i - 1 if i > img_pos else i for i in indices] # 【函数说明】在input_ids序列中定位sample["question"]原始文本(即q_type后缀指令 # 追加之前的那段"纯问题")对应的token下标区间[start, end)。 # 为什么需要这个:随机对照组的候选池不应该是"整条input_ids减去label/图像token", # 那样会把chat模板的系统提示词("You are a helpful assistant")、特殊token # (<|im_start|>等)、以及q_type追加的固定指令("Please output 'yes' or 'no'...") # 都当成候选——这些不是"问题内容"的一部分,是每个样本都一样的模板/指令文本, # 随机抽到它们跟抽到"问题里的实词"在语义上完全不对等,会让"随机文本"这个对照组 # 不够干净。所以候选池要严格限定在sample["question"]这段原始文本本身。 # 输入:ids_list(完整token id序列)、question_raw(sample["question"]原始文本, # 不含q_type追加的指令后缀)、tokenizer # 输出:(start, end)元组,问题文本对应的token下标区间;如果question_raw作为 # 子串完全没在解码结果里出现(理论上不应该发生,因为它本来就是prompt的 # 一部分),返回None,调用处按候选不足处理,跳过该样本。 def _find_question_token_span(ids_list, question_raw, tokenizer, img_span=None): """ 中文说明(为什么改用"解码后按字符串匹配",而不是"重新编码后按token序列匹配"): 最初的实现是把question_raw单独tokenizer.encode()编码成token id序列,再去 ids_list里做精确子序列匹配。这个思路有一个致命缺陷:question_raw在真正的 prompt里紧挨着chat模板的角色标记(比如"<|im_start|>user\n\n {question_raw}..."),BPE分词器在这类模板边界处的切分方式,跟"把 question_raw单独拿出来tokenize"很可能不完全一致——哪怕只是开头第一个 token切法不同,就会导致整段精确匹配(以及"跳过第一个token"的兜底匹配) 双双失败,函数返回None,调用方把该样本直接跳过。这在实测中曾导致 diff_text.py对某些分词器(Qwen、HuatuoGPT-Vision)几乎每一个样本都在这一步 就return None——而且是在真正调用模型前向之前就失败,所以整个跑起来 "快得不正常"(比如13962个样本几秒钟就"跑完",Skipped(other error)=100%), 根本没有触发任何一次真正的GPU推理。 现在改成完全不同的思路:不再尝试"重新编码"question_raw去猜测它在原始 tokenize结果里长什么样,而是反过来——把ids_list里每一个token单独解码 (tokenizer.decode([tid])),拼接还原出完整文本,再用最朴素的Python字符串 查找(str.find)去定位question_raw这段文字出现在哪个字符区间,最后把 这个字符区间映射回对应的token下标范围。字符串层面的子串匹配完全不受 "BPE在不同上下文里怎么切分"这件事影响——不管某个词的token边界在句子中间 还是句子开头合并方式变没变,解码出来的文字内容本身是确定的、不会变的。 这样从根本上避免了"重新编码后tokenize不出same token序列"这一类问题, 不需要再靠"容忍第一个token对不上"这种脆弱的兜底去碰运气。 另一个必须注意的坑:LLaVA-Med/HuatuoGPT-Vision/LLaVA这类图像token在 ids_list里占据实际位置的后端,不能指望"decode图像token会抛异常"来 识别它们——这个假设并不可靠,因为是否抛异常取决于具体tokenizer实现: - HuatuoGPT-Vision的-200:实测会让某些(Rust fast实现的)tokenizer 抛OverflowError,可以被下面的try/except捕获。 - LLaVA-Med的-200:其tokenizer走的是老式SentencePiece/慢速Python 实现(load_pretrained_model加载的LlamaTokenizer),对同样的-200 不一定抛异常——很可能被内部的取模/环绕逻辑悄悄映射成词表里某个 真实token并"成功"decode出内容,不会走except分支,却会把无意义的 文字混进full_text,污染字符串匹配(和下面LLaVA 32000是同一种 故障模式)。 - LLaVA的32000:这是LLaVA-1.5词表大小本身的边界值,被挪用做图像 占位符,是一个合法token id,decode必定"成功"(不抛异常),但 decode出来的内容对文本重建毫无意义,同样会污染full_text。 所以不再依赖"try/except能不能兜住"这种因tokenizer实现而异、不可靠的 检测方式,而是让调用方(本来就知道图像token占据哪些位置)显式传入 img_span=(start, end),函数内部对这个区间强制视为空字符串,不管 decode本身会不会报错、decode出来是什么——统一、确定地把图像token排除在 "文本重建"之外。try/except依然保留作为通用兜底(应对其他不可预见的 decode失败情况),但不再是图像token这件事本身的检测手段。 第三个坑(比图像token这个更根本、影响更大):一开始"逐token单独调用 tokenizer.decode([tid])"这个做法,对LLaVA/LLaVA-Med这类基于 SentencePiece的tokenizer(LLaMA/Vicuna系)是错的,会导致100%的样本 都在这一步失败(实测:LLaVA跑diff_text.py时,加了上面的img_span 保护之后,[skip:question_span=None]依然是100%命中,一个样本都过不了, 证明问题不在图像token,而在别的地方)。 根本原因:SentencePiece把"一个新词开头前面有空格"编码成词内部自带的 "▁"标记(比如" the"这个词,实际token是"▁the"),decode的时候 "▁"->" "。但SentencePiece的decode实现(sp_model.decode_pieces)会把 传进来的这一批token当作"一整段独立文本的开头"来处理,如果这一整段 只有1个token(就是这里"逐token单独decode"的做法),那么这个token 即便本来是"▁the"这种带前导空格标记的token,也会被当成"这段文本的 第一个词",其前导空格被自动去掉——这在SentencePiece的设计里是合理的 (避免一句话开头多出一个空格),但套用到"给每个token单独发起一次 decode调用"这个场景下,就意味着——不管这个token在原始序列里是不是 紧跟在某个词后面、本来就该有空格——只要它是"这一次独立decode调用"里 唯一的token,它的前导空格永远会被丢弃。结果是:整条序列逐token decode再拼接后,几乎所有词与词之间的空格全部消失("Does the image contain a truck?"被重建成类似"Doestheimagecontainatruck?"这种连写 文本),而question_raw本身是带正常空格的,自然永远无法在这样一段 "全部单词连在一起"的字符串里被find()到,导致100%的样本都在 char_start==-1这一步失败并return None。 这个问题不会影响Qwen这类BPE/tiktoken风格的fast tokenizer——它们把 "前导空格"编码进token本身的字节表示里(比如"Ġthe",Ġ就是空格的 字节级表示),解码单个token时直接原样转换,不依赖"是不是整段文本的 开头"这种上下文判断,所以逐token单独decode不会丢空格。这也是为什么 HuatuoGPT-Vision/Qwen系列不需要这个修复、只有LLaVA/LLaVA-Med这两个 SentencePiece系后端会中招的原因。 修复方式:不再对每个token发起独立的decode调用,而是维护一个 "从头到当前token为止的累积token列表"(running_ids),每次把新token 追加进去后,对整个累积列表做一次decode,取本次decode结果相对于 上一次结果"新增出来的那一段"作为这个token的文本片段。这样 SentencePiece在decode时始终能看到"这个token前面还有其它token"这个 上下文,"▁"->" "的转换就不会被误判成"整段文本的开头"而被吞掉, 单词之间的空格能被正确保留。图像token区间(img_span)内的位置不加入 running_ids(相当于从"要decode的文本"里完全抠掉,而不是保留占位再 置空字符串)——这样图像token既不会被误decode出无意义内容,也不会 因为占用了running_ids里的一个位置而干扰后续文本token的上下文。 """ fragments = [] running_ids = [] prev_text = "" for i, tid in enumerate(ids_list): if img_span is not None and img_span[0] <= i < img_span[1]: fragments.append("") continue running_ids.append(tid) try: cur_text = tokenizer.decode(running_ids) except Exception: cur_text = prev_text fragments.append(cur_text[len(prev_text):]) prev_text = cur_text full_text = "".join(fragments) char_start = full_text.find(question_raw) if char_start == -1: char_start = full_text.find(question_raw.strip()) if char_start == -1: return None char_end = char_start + len(question_raw) offsets = [] cursor = 0 for frag in fragments: offsets.append((cursor, cursor + len(frag))) cursor += len(frag) tok_start = tok_end = None for i, (s, e) in enumerate(offsets): if tok_start is None and e > char_start: tok_start = i if s < char_end: tok_end = i + 1 if tok_start is None or tok_end is None: return None return tok_start, tok_end # 【函数说明:随机对照组的核心实现,所有后端通用】 # 在"纯问题"文本对应的token区间[q_start, q_end)里,找一段与label token数量完全 # 相同(n个)、且不与label token重叠的"连续"token片段,作为RT(Random Text)前向 # 要mask掉的token集合。 # # 为什么必须是"连续的一段",而不是"分散抽取n个不相邻的token":这跟 # grounding_diff_region.py里_random_multi_rect_indices的设计思路完全对称——label # 本身在文本里天然是一个连续的短语/词(比如"aorta"就是紧挨着的1个或几个token), # 如果随机对照组是从问题各处分散抽取的孤立token(彼此之间被其它未mask的词隔开), # 那么"被mask的是一个连续短语"和"被mask的是几个不相邻的孤立词"这两种情况,对模型 # 的影响机制可能本就不同(前者破坏的是一段连续语义,后者更像是多处零散的局部 # 缺失),这本身就是一个混淆变量。要求随机对照区域和label同样是"连续的一段 # 长度为n的token",才能让"mask的是不是label本身"成为两组之间唯一的实质性差异—— # 这正是本脚本最初的设计目标(见文件顶部总览),只是早期实现里遗漏了"连续"这个 # 约束,后来在区域版脚本里先修正了,这里同步补上。 # # 候选池限定在question_span内(而不是整条ids_list减去图像/label token),是为了 # 保证随机对照组抽到的都是"问题内容里的实词",不会抽到chat模板/系统提示词/q_type # 追加指令这些每个样本都一样的模板文本——见_find_question_token_span的说明。 # # 如何保证"数量相等":调用处永远传入 n = len(label_set),让MT前向(mask label_set) # 和RT前向(mask rand_indices)被清零的token数量严格相等。 # # 坐标系:本函数在"原始input_ids坐标系"(即ids_list本身的下标)里采样,对所有 # 后端一视同仁。对llava_med/huatuogpt_vision这两个用单占位符表示图像的后端, # 调用方在拿到这里的采样结果后,还需要额外调用 # _adjust_text_indices_for_image_placeholder做"减1"调整,才能得到真正传给 # embedding hook的展开后坐标——这跟label_indices的处理方式完全对称(label_indices # 同样是先在原始坐标系找到,再按需adjust)。 # # 输入:ids_list(完整token id列表,本函数未直接使用,保留是为了跟其它同类函数 # 签名一致)、label_set(label token下标集合,原始坐标)、question_span # (_find_question_token_span算出的(q_start, q_end)区间)、n(要mask的数量, # 等于label token数) # 输出:长度为n、下标连续的list(原始input_ids坐标系);候选不足时返回None def _random_non_label_text_indices(ids_list, label_set, question_span, n): q_start, q_end = question_span if n == 0: return [] candidates = [] for start in range(q_start, q_end - n + 1): run = range(start, start + n) if not any(i in label_set for i in run): candidates.append(start) if not candidates: return None start = random.choice(candidates) return list(range(start, start + n)) # ── masked forward ──────────────────────────────────────────────────────────────── # 【函数说明】构造一个forward hook闭包,挂在embedding层(get_input_embeddings())的输出上, # 把mask_indices指定的那些token位置的embedding向量整体清零(置为0.0),从而实现"屏蔽某些 # token对后续所有transformer层的影响"的效果——这是本脚本"mask"操作的真正落地方式:不是在 # input_ids层面删除token,而是在embedding输出层面把对应位置的向量清零,保持序列长度不变, # 只是让模型在该位置"看不到"原始token的语义信息(清零后的embedding不携带该token的语义)。 # output.ndim==2 / 否则(通常是3维[batch, seq_len, hidden_dim])两个分支分别处理"无batch维" # 和"有batch维"两种embedding输出形状,兼容不同模型实现的embedding层返回值形态。 # 注意.clone():必须先克隆输出张量再修改,否则会就地修改原始embedding输出,可能引发 # autograd或其他hook的副作用问题。 # 输入:mask_indices —— 要清零的token下标列表(MT前向传label_set,RT前向传rand_indices) # 输出:一个符合register_forward_hook签名的hook函数(module, args, output) -> output def _make_emb_hook(mask_indices): def _hook(module, args, output): output = output.clone() if output.ndim == 2: for idx in mask_indices: if idx < output.shape[0]: output[idx, :] = 0.0 else: for idx in mask_indices: if idx < output.shape[1]: output[:, idx, :] = 0.0 return output return _hook # 【函数说明】qwen2_5vl/qwen3vl/medgemma/llava通用的"带mask的前向":先把_make_emb_hook # 注册到embedding层上,做一次完整的forward(开启output_hidden_states以便取每层隐藏状态), # 最后在finally块里移除hook(避免hook状态泄漏到下一次forward,比如紧接着的另一次mask # 调用如果忘记移除旧hook,会导致两次mask叠加生效)。 # 本函数在get_sample_hidden_states中被调用两次:一次传label_set得到hs_label(MT前向), # 一次传rand_indices得到hs_rand(RT前向)——这就是本脚本的核心对比双胞胎。 # 输入:inputs(processor处理好的模型输入字典)、model、mask_indices(要清零的token下标) # 输出:该次forward每层最后一个token的隐藏状态,shape=[num_layers, hidden_dim] def _forward_hidden_masked(inputs, model, mask_indices): handles = [model.get_input_embeddings().register_forward_hook(_make_emb_hook(mask_indices))] 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专用的"带mask的前向",逻辑与_forward_hidden_masked完全一样,只是 # LLaVA-Med的模型forward签名是model(input_ids, images=imgs, ...)而不是model(**inputs, ...), # 所以单独写一个版本以匹配其调用接口。 def _forward_hidden_masked_llava_med(input_ids, imgs, model, mask_indices): handles = [model.get_input_embeddings().register_forward_hook(_make_emb_hook(mask_indices))] 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专用的"带mask的前向"。这里需要重新走一遍HuatuoGPT自己的 # 输入预处理流程(input_moderation -> insert_image_placeholder -> get_conv_without_history # -> preprocess),因为HuatuoGPT的bot封装没有像qwen/medgemma那样统一暴露processor接口, # 必须复用bot自身的方法链才能得到正确的input_ids和image_tensors。 # 之所以每次调用都重新跑一遍预处理(而不是像其它分支一样预处理一次复用两次),是因为 # HuatuoGPT分支在get_sample_hidden_states里就是分别为MT、RT各自调用了一次本函数(见下方 # btype == "huatuogpt_vision"分支),传入相同的text/image_path,重复预处理两次,逻辑上 # 等价但效率上略有冗余(每次都要重新moderation+tokenize),这是与其它模型分支实现风格不 # 一致的地方,但不影响结果正确性。 # 输入:text(问题文本)、image_path、backend(含bot对象)、mask_indices(要清零的token下标, # 已经过_adjust_text_indices_for_image_placeholder调整为展开后的绝对位置) # 输出:该次forward每层最后一个token的隐藏状态,shape=[num_layers, hidden_dim] def _forward_hidden_masked_huatuo(text, image_path, backend, mask_indices): 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_input_embeddings().register_forward_hook(_make_emb_hook(mask_indices))] 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 ───────────────────────────────────────────────────────── # 【函数说明:单样本处理主流程】 # 对单个样本完整执行一次"MT前向 vs RT前向"的对照实验,返回两组隐藏状态供后续计算divergence。 # # 整体步骤(六个分支:qwen2_5vl/qwen3vl、medgemma、llava、llava_med、huatuogpt_vision, # 分支结构基本平行,只是各模型的预处理函数/输入格式不同): # 1. 拼接问题文本:根据q_type在原始question后追加任务提示语(localization任务要求输出 # yes/no,attribute任务要求输出单词或短语)——这与评测时模型实际看到的提示语保持一致, # 确保这里测的是"模型在真实推理设置下"对label/随机token的敏感度,不是脱离任务上下文 # 单独测的。 # 2. 用对应模型的process_input_image_and_qs_xxx函数,把(图像, 问题)转成模型输入,并得到 # input_ids列表以及图像token的区间(pos, pos_end)。 # 3. 用_find_label_token_indices在input_ids里定位label对应的token下标集合(label_set)。 # 4. 用_random_non_label_text_indices(_for_image_placeholder)随机采样等量、不重叠、 # 排除图像区间的文本token下标(rand_indices)作为对照组。如果候选不足返回None,则 # 整个样本被跳过(return None)。 # 5. 分别用label_set和rand_indices两套mask下标各做一次带mask的前向,得到hs_label(MT) # 和hs_rand(RT)两组逐层隐藏状态。 # 6. 任何步骤出错(比如找不到图像token区间、tokenizer解析异常等)都会被外层try/except # 捕获,打印warning并返回None,保证单个坏样本不会中断整个数据集的遍历。 # # 返回前用min(hs_label.shape[0], hs_rand.shape[0])对齐两者的层数——理论上MT和RT用的是 # 同一个模型、同一次forward配置,层数应该天然相等,这里取min只是防御性写法,防止某些 # 模型在不同前向间返回的hidden_states层数有细微差异时导致后续stack/cosine计算报错。 # # 输入: # sample —— 单条jsonl样本字典,需包含image/question/label/bbox(或original_bboxes)等字段 # data_path —— 图像文件所在根目录 # dataset —— "VGMED"或"COCO"(当前函数体内未直接用到,但保留参数是为了和 # get_sample_attention等同名函数签名保持一致,便于代码维护/复用习惯) # backend —— load_backend返回的字典,包含模型、processor/tokenizer等 # layers —— 层下标的range对象(当前函数体内同样未直接使用,层数信息实际由 # hidden_states自身的长度决定;layers参数更多是签名上的占位,留作以后 # 若要支持"只计算部分层"时使用,目前是全量计算所有层) # q_type —— "localization"或"attribute",决定问题末尾追加的提示语 # 输出: # 成功时返回 (hs_label, hs_rand) 元组,各自shape=[num_layers, hidden_dim] # 失败/候选不足时返回 None 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) question_raw = sample.get("question", "") label = sample.get("label", "") 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"] try: # qwen系列:input_ids中图像token已是展开后的真实位置(无占位符问题), # 直接用_random_non_label_text_indices即可,下标不需要额外调整。 # len(label_set)既是MT要mask的数量,也作为n传给随机采样函数,保证RT和MT # 清零的token数量严格一致。随机采样限定在"纯问题"(question_raw,不含 # q_type追加指令)对应的token区间内——见_find_question_token_span的说明, # 避免抽到chat模板/系统提示词/指令后缀这些非"问题内容"的token。 if btype in {"qwen2_5vl", "qwen3vl"}: inputs, _, token_shape, new_size, pos, pos_end = \ process_input_image_and_qs_qwen(image_path, question, backend) tokenizer = backend["processor"].tokenizer ids_list = inputs["input_ids"].reshape(-1).tolist() label_set = _find_label_token_indices(ids_list, label, tokenizer) question_span = _find_question_token_span(ids_list, question_raw, tokenizer) if question_span is None: return None rand_indices = _random_non_label_text_indices(ids_list, label_set, question_span, len(label_set)) if rand_indices is None: return None hs_label = _forward_hidden_masked(inputs, backend["model"], list(label_set)) hs_rand = _forward_hidden_masked(inputs, backend["model"], rand_indices) # 这几个后端image token在ids_list里就是真实展开的,label_set/rand_indices # 本身就是ids_list坐标系下的下标,供render_masked_text_image渲染时不需要 # 额外调整,直接原样复用。 viz_label_indices, viz_rand_indices, viz_pos, viz_pos_end = label_set, rand_indices, pos, pos_end elif btype == "medgemma": inputs, _, token_shape, new_size, pos, pos_end = \ process_input_image_and_qs_medgemma(image_path, question, backend) tokenizer = backend["processor"].tokenizer ids_list = inputs["input_ids"].reshape(-1).tolist() label_set = _find_label_token_indices(ids_list, label, tokenizer) question_span = _find_question_token_span(ids_list, question_raw, tokenizer) if question_span is None: return None rand_indices = _random_non_label_text_indices(ids_list, label_set, question_span, len(label_set)) if rand_indices is None: return None hs_label = _forward_hidden_masked(inputs, backend["model"], list(label_set)) hs_rand = _forward_hidden_masked(inputs, backend["model"], rand_indices) viz_label_indices, viz_rand_indices, viz_pos, viz_pos_end = label_set, rand_indices, pos, pos_end elif btype == "llava": inputs, _, token_shape, new_size, pos, pos_end, _pad_offset, _frame_size = \ process_input_image_and_qs_llava(image_path, question, backend) tokenizer = backend["processor"].tokenizer ids_list = inputs["input_ids"].reshape(-1).tolist() # HF LlavaProcessor already expands the image into 576 real token # entries in input_ids (no single-placeholder expansion), so indices # found here are already correct absolute positions -- same handling # as qwen/medgemma above, no -1 adjustment. label_set = _find_label_token_indices(ids_list, label, tokenizer) label_indices = list(label_set) question_span = _find_question_token_span(ids_list, question_raw, tokenizer, img_span=(pos, pos_end)) if question_span is None: return None rand_indices = _random_non_label_text_indices(ids_list, label_set, question_span, len(label_set)) if rand_indices is None: return None hs_label = _forward_hidden_masked(inputs, backend["model"], label_indices) hs_rand = _forward_hidden_masked(inputs, backend["model"], rand_indices) viz_label_indices, viz_rand_indices, viz_pos, viz_pos_end = label_set, rand_indices, pos, pos_end # llava_med:input_ids用单个IMAGE_TOKEN_INDEX占位符表示图像,所以label_indices # 和rand_indices都需要经过"占位符展开"下标调整(_adjust_text_indices_for_ # image_placeholder)才能正确对应到embedding hook实际操作的展开后序列位置。 # rand_indices现在和label_indices走完全对称的两步:先在原始坐标系(ids_list # 本身)里,限定在question_span范围内采样,再统一做展开坐标调整——这样 # 调整前的原始下标本来就是采样结果本身,不需要再额外"反推"回原始坐标 # (对比早期实现:那时候是先在错误的排除区间里采样再调整,可视化时还得把 # 调整后的结果反推回去,现在两步顺序理清楚后不再需要这一步反推)。 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) tokenizer = backend["tokenizer"] ids_list = input_ids.reshape(-1).tolist() label_set = _find_label_token_indices(ids_list, label, tokenizer) label_indices = _adjust_text_indices_for_image_placeholder(list(label_set), pos) question_span = _find_question_token_span(ids_list, question_raw, tokenizer, img_span=(pos, pos + 1)) if question_span is None: return None rand_raw = _random_non_label_text_indices(ids_list, label_set, question_span, len(label_set)) if rand_raw is None: return None rand_indices = _adjust_text_indices_for_image_placeholder(rand_raw, pos) hs_label = _forward_hidden_masked_llava_med(input_ids, imgs, backend["model"], label_indices) hs_rand = _forward_hidden_masked_llava_med(input_ids, imgs, backend["model"], rand_indices) # label_set/rand_raw都已经是"调整前"的原始ids_list坐标,直接用于渲染。 # ids_list里图像只占pos这一个位置(不是pos_end-pos那么多个,pos_end是 # "假设展开后"的虚拟终点),所以折叠""的区间是[pos, pos+1)。 viz_label_indices = label_set viz_rand_indices = rand_raw viz_pos, viz_pos_end = pos, pos + 1 # huatuogpt_vision:同样是单占位符模型(占位符token id固定为-200,这是HuatuoGPT # 自身预处理约定的特殊id,下面用`next(... if t == -200)`从input_ids里查找它的位置), # 图像区间长度固定为HUATUO_NUM_IMG_TOKENS(=576个patch token)。这个分支没有复用 # process_input_image_and_qs_xxx系列函数,而是直接调用bot自身的预处理方法链, # 与_forward_hidden_masked_huatuo内部的预处理步骤完全一致(即这里又重复跑了一次 # 相同的预处理,只是为了取得ids_list用来定位label/随机token下标;真正forward时 # _forward_hidden_masked_huatuo还会再重新跑一次预处理)。 elif btype == "huatuogpt_vision": from measure_attention import HUATUO_NUM_IMG_TOKENS, HUATUO_PATCHES 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) pos_end = img_pos + HUATUO_NUM_IMG_TOKENS label_set = _find_label_token_indices(ids_list, label, bot.tokenizer) label_indices = _adjust_text_indices_for_image_placeholder(list(label_set), img_pos) question_span = _find_question_token_span(ids_list, question_raw, bot.tokenizer, img_span=(img_pos, img_pos + 1)) if question_span is None: return None rand_raw = _random_non_label_text_indices(ids_list, label_set, question_span, len(label_set)) if rand_raw is None: return None rand_indices = _adjust_text_indices_for_image_placeholder(rand_raw, img_pos) hs_label = _forward_hidden_masked_huatuo(question, image_path, backend, label_indices) hs_rand = _forward_hidden_masked_huatuo(question, image_path, backend, rand_indices) tokenizer = bot.tokenizer viz_label_indices = label_set viz_rand_indices = rand_raw viz_pos, viz_pos_end = img_pos, img_pos + 1 else: raise ValueError(f"Unknown backend type: {btype}") # 任何分支内部出现异常(比如某个样本的图片缺失、tokenizer解析失败、找不到图像token # 区间等),都在这里统一兜底捕获:打印警告但不让单个坏样本中断整个数据集的批量处理。 # traceback.print_exc()把完整堆栈打到stderr(跟grounding_mask_region.py/ # grounding_diff_region.py的做法保持一致),方便定位到底是哪一行、哪个函数 # 触发的异常,而不是只看到异常信息本身这一行文字。 # 内层再包一层try/except:防止异常信息本身(比如包含终端编码打印不出来的字符) # 导致这两行打印自己也抛异常——那样"本该被优雅跳过"的错误反而会变成让整个 # 脚本崩溃的未捕获异常,彻底违背这里try/except想要的效果。 except Exception as e: try: import traceback traceback.print_exc() print(f"[Warning] Skipping {image_name}: {e}") except Exception: print(f"[Warning] Skipping {image_name}: ") return None # 防御性对齐:理论上MT前向和RT前向用的是同一个模型、同样的forward配置,层数应该相等; # 这里取min只是为了避免极端情况下两次前向返回的hidden_states长度不一致导致后续 # torch堆叠/余弦计算报错。 num_layers = min(hs_label.shape[0], hs_rand.shape[0]) viz_info = { "ids_list": ids_list, "tokenizer": tokenizer, "label_indices": viz_label_indices, "rand_indices": viz_rand_indices, "pos": viz_pos, "pos_end": viz_pos_end, } return hs_label[:num_layers], hs_rand[:num_layers], viz_info # ── divergence ──────────────────────────────────────────────────────────────────── # 【函数说明:本脚本的核心度量指标】 # 逐层计算hs_label(MT前向,label token被mask)与hs_rand(RT前向,等量随机文本token被mask) # 之间的余弦距离 D[i] = 1 - cosine_similarity(hs_label[i], hs_rand[i])。 # dim=-1表示在hidden_dim维度上计算余弦相似度,对hs_label/hs_rand这种shape=[num_layers, # hidden_dim]的张量,结果是shape=[num_layers]的逐层divergence。 # .clamp(min=0.0)把可能出现的负值(余弦相似度>1时由浮点误差导致1-cos<0,或者理论上 # 不应发生但数值上可能出现的情况)截断为0,保证divergence始终非负,语义上更符合 # "距离"的定义。 # 输入:hs_label、hs_rand —— 形状相同的[num_layers, hidden_dim]张量 # 输出:shape=[num_layers]的逐层divergence张量。数值越大表示该层"mask label"与 # "mask随机等量文本"产生的隐藏状态差异越大,即label token在该层的处理上越"特殊"。 def compute_divergence_per_layer(hs_label: torch.Tensor, hs_rand: torch.Tensor) -> torch.Tensor: return (1.0 - F.cosine_similarity(hs_label, hs_rand, dim=-1)).clamp(min=0.0) # ── save ────────────────────────────────────────────────────────────────────────── # 【函数说明】把跨样本平均后的逐层divergence张量(mean_div, shape=[num_layers])保存到 # {output_root}/{model_name}/diff_text/{dataset}_{q_type}_mean_divergence_per_layer.pt。 # 目录里专门用"diff_text"子目录区分本脚本(随机文本对照组)与grounding_mask_text.py # 等其它实验的输出,避免文件名/路径冲突,方便后续脚本分别加载两组结果做对比分析。 def save_divergences(output_root, model_name, dataset, q_type, mean_div): save_path = os.path.join(output_root, model_name, "diff_text") 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_text.py的参数集合基本一致, # 唯一本脚本特有的是--seed(随机种子,默认42),用于控制随机对照组采样的可复现性 # (在main()里通过random.seed(args.seed)生效,作用于_random_non_label_text_indices # 系列函数内部调用的random.sample)。 # 其余参数:--dataset/--q_type决定加载哪个数据集与任务类型的问题模板;--model_path/ # --model_type/--model_base_path决定加载哪个模型;--vgmed_root/--coco_root/ # --coco_annotation_root是各数据集所需的路径(按数据集做了必填校验);--output_root # 是结果保存根目录。 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 label/random-token-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 ───────────────────────────────────────────────────────────────────────── # 【函数说明:脚本主入口】 # 整体流程: # 1. 解析参数,设置随机种子(random.seed(args.seed))——这一步决定了后续所有样本的 # 随机对照token采样是否可复现。注意这是在加载模型/遍历样本之前就调用的,所以 # 只要数据集遍历顺序和样本数量不变,固定seed就能复现完全相同的随机对照组结果。 # 2. 根据model_path推断/指定模型类型,加载backend(need_attn=False,因为本脚本只需要 # hidden_states,不需要attention矩阵,可以用更快的sdpa attention实现而不强制eager)。 # 3. 加载数据集问题列表,并确定模型层数(layers)。 # 4. 遍历每个样本,先做几道前置过滤(必须有bbox标注、必须有question文本、label必须 # 真实出现在question里——这一条尤其关键,因为如果label根本没出现在问题文本中, # _find_label_token_indices会返回空集合,导致label_set为空、随机采样n=0,使得 # MT和RT两次前向都变成"不mask任何token"的无意义对照,所以这里提前过滤掉这类样本), # 再调用get_sample_hidden_states拿到(hs_label, hs_rand),计算逐层divergence并 # 累积到all_divergences列表中。 # 5. 所有样本处理完后,把all_divergences堆叠成[num_samples, num_layers]的数组, # 在样本维度(axis=0)上取均值,得到最终shape=[num_layers]的mean_div,即"该模型在 # 该数据集/任务类型下,每一层的平均divergence"——这就是本脚本最终要回答的问题的 # 数值答案:每一层"mask label"与"mask等量随机文本"的差异有多大。 # 6. 打印统计信息(跳过了多少样本、各类跳过原因),并保存mean_div到.pt文件。 def main(): args = parse_args() if args.hf_home: os.environ["HF_HOME"] = args.hf_home 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) 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 = 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): # 前置过滤1:样本必须有bbox标注(bbox或original_bboxes二者之一),因为本脚本 # 的样本筛选逻辑与mask_text/attention系列脚本保持一致(即便本脚本本身并不 # 直接使用bbox信息计算divergence,过滤条件统一是为了让不同实验脚本处理的是 # 同一批样本子集,便于横向对比结果)。 if not (sample.get("bbox") or sample.get("original_bboxes")): skip_no_bbox += 1 continue # 前置过滤2:样本必须有问题文本,否则无法构造模型输入。 if not sample.get("question", ""): skip_no_question += 1 continue # 前置过滤3(关键):label必须真实地以子串形式出现在question文本里。如果label # 不在question中,_find_label_token_indices几乎肯定找不到任何匹配,label_set # 会是空集合,导致后续随机采样n=0,MT/RT两次前向都变成"什么都不mask",使本次 # 对照实验失去意义——这里提前过滤掉这类样本,保证后面统计的divergence都来自 # "确实mask了至少1个真实label token"的有效对照。 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_label, hs_rand, viz_info = result div = compute_divergence_per_layer(hs_label, hs_rand) all_divergences.append(div.cpu().numpy()) # 抽样保存"label词(红)+随机对照词(蓝)"标记图片,供人工确认label token # 是否真的对应了sample["label"]这个词、随机词是否落在了不同的位置上—— # 光看divergence数值完全看不出mask对不对(历史上正是因为没有这类检查, # llava_med/huatuogpt_vision的随机采样bug才一直没被发现)。 if args.visualize and visualized_count < args.visualize_limit: visualized_count += 1 image_name = sample["image"] stem = os.path.splitext(os.path.basename(image_name))[0] save_path = os.path.join( args.output_root, model_name, "diff_text", "masks", args.dataset, args.q_type, f"{stem}.png", ) render_masked_text_image( viz_info["ids_list"], viz_info["tokenizer"], viz_info["label_indices"], viz_info["rand_indices"], viz_info["pos"], viz_info["pos_end"], 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 # 把所有样本的逐层divergence堆叠成[num_samples, num_layers]的二维数组, # 在样本维度(axis=0)上取平均,得到最终的"每层平均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_text/{args.dataset}_{args.q_type}_mean_divergence_per_layer.pt") if __name__ == "__main__": main()