Lecture 3 · 深度网络的归因 · Attribution for Deep Networks

Trustworthy Machine Learning · Lecture 03。个人学习讲义与配套实验,按主题整理并持续修订。

课程源码 ZIP ↓

个人整理的学习笔记,非官方讲义;课程来源与整理说明见课程介绍。配套示例未逐一运行验证。

本篇目录

对应 Maps to:Stanford CS329T Spring 2022 Weeks 2–3 —— 4 月 12 日的 “Explanations” 讲座(Integrated Gradients、internal explanations、Influence-Directed Explanations、influence paths & patterns)、Lab 3(Saliency maps、Integrated Gradients、attribution in NLP)、HW2 Part II(gradient-based attribution in vision models、influence-directed explanations、attribution method evaluation);阅读材料 Sundararajan, Taly & Yan, “Axiomatic Attribution for Deep Networks”(ICML 2017)、Leino et al., “Influence-Directed Explanations for Deep Convolutional Networks”(2018)、Wang et al., “Interpreting Interpretations: Organizing Attribution Methods by Criteria”(2020)、Ghorbani et al., “Towards Automatic Concept-based Explanations”(2019)。Fall 2023 Lecture 12 “Interpretability”(Anupam Datta、John Mitchell、Ankur Taly:IG、VQA 的 “Did the model understand the question?”、internal influence、influence patterns for BERT、evaluating attributions)。 配套代码 Code:code/lecture03/(PyTorch,CPU;5 个脚本 + 2 个工具模块,每个脚本 2–18 秒) 预计阅读时间:3 小时(含运行代码)


0. 本讲导航 · How to read this lecture

0.1 Learning goals

After this lecture you should be able to:

  1. Explain why model-agnostic Shapley values do not scale to deep networks, and why almost every deep-network attribution method is built on gradients.
  2. 区分 sensitivity(敏感度) 和 contribution(贡献):saliency map 回答”动一点会怎样”,gradient × input 和 IG 回答”这个输入贡献了多少”;并能用一个例子说明梯度为什么会饱和(saturation)。
  3. State the axioms behind Integrated Gradients — sensitivity, implementation invariance, completeness, linearity, symmetry preservation — explain which methods violate which, and relate IG to the Aumann–Shapley cost-sharing method and to the Shapley value of Lecture 2.
  4. 在一个带捷径(shortcut)的图像模型上,用归因把捷径找出来,并用 completeness 把归因读成一本”账”;知道基线(baseline)怎样决定”和什么比”。
  5. Evaluate attributions critically: deletion / insertion curves and their off-manifold problem, sanity checks by randomization, and why “agrees with human intuition” is not the same as “faithful to the model”.
  6. 解释内部影响(distributional influence、conductance、influence paths、TCAV / ACE)在问什么,以及在文本模型上怎样做 IG、怎样用归因检验”模型真的读懂了吗”(VQA 的例子)。

0.2 先修与本讲范围 Prerequisites & scope

默认你已经会 Assumed本讲省略或只简单提到 Omitted / brief
第 1 讲 §5.1:线性模型的贡献 θjx~j\theta_j\tilde x_j 与 completenessFriedman(2004)唯一性定理的完整证明(只讲直觉)
第 2 讲:Shapley 值的四条公理与”基线 / 移除特征”的含义(本讲只引用结论)LRP 的各种传播规则(只讲 LRP-0)、Grad-CAM、XRAI 等可视化方法
反向传播、CNN 的卷积 / pooling、logit 与 softmaxattention 权重能不能当解释(只在 §7.5 提一句)
PyTorch 基础:张量、autograd、训练循环(代码注释会解释第一次出现的写法)mechanistic interpretability(circuits、sparse autoencoders)
训练数据归因(influence functions)—— 第 4 讲

0.3 本讲地图 Map

§1  从 Shapley 到梯度:为什么深度网络需要专门的方法           ← 代码 01 演示 2
§2  梯度:saliency、gradient × input、饱和                      ← 代码 01 演示 1、代码 02 演示 2
§3  Integrated Gradients:公理、路径、Riemann 和、
    implementation invariance、DeepLIFT / LRP、SmoothGrad      ← 代码 01 演示 1–4
§4  用归因找出图像模型的捷径(X 光笔迹的图像版)               ← 代码 02 演示 1、3、4
§5  基线:和什么比?                                           ← 代码 03 演示 3
§6  怎样评估归因:deletion / insertion、sanity checks、准则      ← 代码 03 演示 1–3
§7  内部影响:distributional influence、conductance、
    influence paths、概念(TCAV / ACE)                         ← 代码 04
§8  文本上的 IG;"模型读懂问题了吗?"                           ← 代码 05
§9  局限与注意事项;§10–14 小结、误区、练习、延伸阅读、下一讲

0.4 Notation

符号含义
x∈Rnx \in \mathbb{R}^n,x′x'输入(一张图的 256 个像素、一句话的词向量……);基线(baseline),“什么都没有”的参照输入
F(x)F(x)被解释的量(quantity of interest):某一类的 logit,或”支持真实类别的 logit”
γ(α)=x′+α(x−x′)\gamma(\alpha) = x' + \alpha(x - x')从基线到输入的直线路径,α∈[0,1]\alpha \in [0, 1]
Ai(x;x′)A_i(x; x')第 ii 个输入分量的归因(attribution);IGi\mathrm{IG}_i 是 Integrated Gradients
h=body(x)h = \mathrm{body}(x),F=head(h)F = \mathrm{head}(h)把网络在某个隐藏层切成两段;hjh_j 是一个隐藏单元
mmRiemann 和的步数
Model S / Model C本讲的两个小 CNN:S 在”水印 ≈ 标签”的数据上训练(shortcut),C 在”水印与标签无关”的数据上训练(control)

0.5 关于数字 · About the numbers

讲义里所有实验数字都来自配套代码的实际输出(固定随机种子,PyTorch 单线程,同一台机器上重复运行逐字相同)。数据全部由程序生成:一个”横线 vs 竖线”的 16 × 16 图像世界(synthetic_images.py),一个小影评世界(05_text_ig.py)。我们知道每个世界的”真相”——哪个特征是故意放进去的捷径——所以能检查归因说得对不对。数字只说明机制,不代表任何真实系统。和计划不一致的结果都记录在代码 README 的”关于实验结果”里。


1. 从 Shapley 到梯度 · Why deep networks need their own methods

1.1 Where we are

第 1 讲 §5.1 看到,对线性模型 z=θ0+∑jθjx~jz = \theta_0 + \sum_j \theta_j\tilde x_j,每个特征的贡献就是 θjx~j\theta_j\tilde x_j,加起来正好等于 logit 减去”平均申请人”的 logit(completeness)。第 2 讲把这件事推广到任意模型:把特征看成合作博弈的玩家,Shapley 值是唯一满足 efficiency、symmetry、dummy、additivity 四条公理的分配方式;而”一个特征缺席”要用某个基线或某个分布来定义。

So for any model we already have a principled answer. Why does a deep network need anything else?

1.2 The cost problem

The Shapley value of feature ii averages its marginal contribution over all 2n−12^{n-1} subsets of the other features (equivalently, over all n!n! orderings). For tabular models with a dozen features this is fine. For a deep network the inputs are pixels or tokens. Even the tiny 16 × 16 images of this lecture have n=256n = 256 (code 01, demo 2):

quantityvalue
feature subsets 22562^{256}≈1077.1\approx 10^{77.1}
orderings 256!256!≈10506.9\approx 10^{506.9}
forward passes per sampled ordering257
gradient calls for Integrated Gradientsmm ≈ 20–300, independent of nn

Sampling helps (Lecture 2), but each sampled ordering still costs n+1n + 1 forward passes, and the variance is high when nn is large. There is a second, subtler problem that the IG paper points out: Shapley-style computations evaluate the network on mixtures of the input and the baseline (half the pixels from the image, half black), which may look like nothing the network has seen in training; the network’s response there may be an artifact.

深度网络有一样东西是黑盒模型没有的:梯度。一次反向传播就能得到输出对全部 nn 个输入的偏导数,代价约等于一次前向传播,与 nn 无关。几乎所有深度网络专用的归因方法都在回答同一个问题:怎样用梯度构造一个”好的”归因?——什么叫”好”,正是 §3 的公理要回答的。

1.3 A taxonomy · 四个问题定位一种方法

Spring 2022 的讲座用四个问题给每种解释方法定位:

问题可能的答案本讲的例子
1. 解释什么输出?预测分数、分类结果、loss;“A 类相对 B 类”的比较logit;“支持真实类别的 logit”;HW2 里”weasel vs polecat”的比较
2. 用什么输入来解释?特征 / 像素 / token;内部神经元;神经元之间的路径§2–§6 输入;§7 神经元、路径
3. 需要什么访问权限?model-agnostic(只能查询)vs model-specific(能拿到梯度)QII / SHAP / LIME 是前者;本讲全部是后者(gradient-based)
4. 在什么阶段解释?post hoc(训练后)vs 训练时就内置本讲全部 post hoc

QII / SHAP 回答 (prediction, features, agnostic, post hoc);IG 换成了 gradient-based;influence-directed explanations 把”输入”扩展到神经元;influence paths 再扩展到路径。课程的思路是:沿着这几个维度逐步放松,每一步都问”新方法满足哪些原则”。

1.4 本讲的故事:X 光笔迹的图像版

第 1 讲 §1.4 讲过:一个从 X 光片判断癌症的模型准确率很高,归因却显示它最看重的像素落在放射科医生留下的笔迹上。本讲在一个”知道真相”的合成世界里重演这个故事(synthetic_images.py):

  • 16 × 16 灰度图,背景噪声 N(0,0.32)\mathcal{N}(0, 0.3^2);图中有一根 4–6 像素长的短线,竖线 = 类别 1,横线 = 类别 0——这是我们希望模型学会的。
  • 左上角 3 × 3 可能有一个亮块(“水印”,像片子上的笔迹或医院标签)。在 Model S 的训练数据里,竖线图 95% 带水印、横线图只有 5% 带;在 Model C 的训练数据里,水印出现与否和标签无关。两个模型结构、初始化、训练步数完全相同。

代码 02 演示 1 的排行榜:

modelval(同一条数据管线)clean(部署:没有水印)flipped(水印含义反转)
Model S0.9710.7660.571
Model C0.9130.9100.922
规则”有水印 → 竖线”0.9500.4950.048

和第 1 讲的 officer_flag 一模一样:验证集来自同一条数据管线,共享同一个泄露,排行榜选出了 S;“只看水印猜”的规则(0.950)甚至比老老实实学短线的 C 还准。现实中你只有第一列。本讲的问题是:不看部署数据,归因能不能把这个问题找出来?(§4 回答:能,而且能定量。)


2. 梯度:局部敏感度 · Gradients as local sensitivity

2.1 Saliency maps

The oldest gradient-based explanation (Baehrens et al. 2010; Simonyan, Vedaldi & Zisserman 2014) is the saliency map:

Si(x)=∣∂F(x)∂xi∣S_i(x) = \left|\frac{\partial F(x)}{\partial x_i}\right|

It answers a local question: if I nudge pixel ii a tiny bit, how much does the score move? One backward pass gives the whole map. The Lab 3 slide puts it as “compute the local gradient of pre-softmax scores w.r.t. the input” — and asks why pre-softmax? Two reasons. First, softmax couples the classes: the gradient of a class probability also contains “make the other classes less likely”, which mixes in evidence about other classes. Second, probabilities saturate. Code 02, demo 2 walks along the straight line from a black image to 200 watermarked vertical-bar images under Model S:

αmean p(α)p(\alpha)mean logitmean ∥∇p∥\lVert\nabla p\rVertmean ∥∇logit∥\lVert\nabla \mathrm{logit}\rVert
0.00.311−0.790.09940.46
0.20.312−0.790.29491.36
0.40.6010.440.88233.95
0.60.8672.140.50855.12
0.80.9503.670.27576.48
1.00.9694.970.20967.88

Per image, the gradient of pp at the actual input is a median 5.1% of its largest value along the path, and below 10% for 62% of the images; the logit’s gradient is largest at the input itself (median ratio 1.000). The more confident the model, the flatter pp is at xx, and the less a gradient taken at xx can see. That is why everything in this lecture explains logits.

注意第一行:α 很小时(图像几乎全黑)分数和梯度都很小,模型”什么都看不见”——这就是 Fall 2023 第 12 讲那张示意图里 “baseline → uninteresting gradients → interesting gradients → saturation” 的左半段。只在终点求梯度的方法,只能看到右端那一小段。

2.2 Gradient × input:从敏感度到贡献

对线性模型 F(x)=∑iwixi+bF(x) = \sum_i w_i x_i + b,梯度就是 ww,gradient × input xi ∂F/∂xi=wixix_i\,\partial F/\partial x_i = w_i x_i 正是第 1 讲里的”贡献”。对深度网络,梯度是”在 xx 附近的局部系数”,乘上输入就是”局部线性近似下的贡献”。

两者的区别在这个任务上非常具体。代码 02 演示 3 统计了 400 张带水印的图上,各种归因有多大比例落在水印的 9 个像素上(面积只占 3.5%):Model S 的 saliency 只有 0.078,gradient × input 有 0.215,IG 有 0.350(完整表格在 §4.1)。为什么差这么多?Saliency 度量敏感度:模型对背景里每一个噪声像素都有一点敏感,256 个像素加起来,就把水印”稀释”了。乘上输入后度量的是贡献:背景噪声值小、贡献就小,亮的水印贡献大。两种问题都合理,但”模型依赖了什么”是贡献的问题。

2.3 Saturation:有影响的特征,梯度却是 0

Gradient × input still uses only the gradient at the input, so it inherits saturation. The IG paper’s one-line example is f(x)=1−ReLU(1−x)f(x) = 1 - \mathrm{ReLU}(1 - x) with baseline x′=0x' = 0 and input x=2x = 2: the output goes from 0 to 1 entirely because of xx, yet ff is flat for x>1x > 1, so the gradient — and gradient × input — is exactly 0 (code 01, demo 1a). The paper calls the violated property Sensitivity(a): if the input and baseline differ in one feature and the outputs differ, that feature should get non-zero attribution.

HW2 的书面题 13 给了一个两维的版本:F(x1,x2)=min⁡(2x1+3x2, 1)F(x_1, x_2) = \min(2x_1 + 3x_2,\ 1),基线 (0,0)(0, 0),输入 (2,1)(2, 1)。代码 01 演示 1b:

methodx1x_1x2x_2sum
gradient at xx0.0000.0000.000
gradient × input0.0000.0000.000
occlusion(一次只把一个特征换成基线)0.0000.0000.000
Integrated Gradients0.5710.4291.000

没有这两个特征 F=0F = 0,有了它们 F=1F = 1,可三种”直觉”方法都说它们不重要。梯度为 0 是因为 2x1+3x2=7>12x_1 + 3x_2 = 7 > 1,函数已经顶到天花板;occlusion 为 0 是因为两个特征互相冗余:去掉 x1x_1 后 3x2=33x_2 = 3 仍 ≥ 1,去掉 x2x_2 后 2x1=42x_1 = 4 也 ≥ 1(这就是第 2 讲里”一次改一个特征”在交互时失败的那种情形)。深度网络里到处都是这种饱和:ReLU 关闭、sigmoid / softmax 顶到 1、max-pool 只选一个。Fall 2023 的讲座用 ImageNet 的”fireboat”图展示了它的后果:在输入处的梯度图看起来像噪声,真正起作用的区域反而不突出。

2.4 Other backward rules: DeconvNet and guided backprop

A family of methods modifies how the backward pass goes through ReLUs to get “cleaner” pictures. DeconvNet (Zeiler & Fergus 2014) passes a signal through a ReLU only if the backward signal is positive; guided backpropagation (Springenberg et al. 2015) requires both the forward activation and the backward signal to be positive. The pictures look sharper, but the IG paper (Appendix B) shows both break Sensitivity: in the network f(x1,x2)=ReLU(ReLU(x1)−1−ReLU(x2))f(x_1, x_2) = \mathrm{ReLU}(\mathrm{ReLU}(x_1) - 1 - \mathrm{ReLU}(x_2)), the output decreases as x2x_2 grows, yet the backward signal arriving at ReLU(x2)\mathrm{ReLU}(x_2) is always negative and gets cut. Code 01, demo 4 confirms: guided backprop gives x2x_2 exactly 0. §6.4 will show the other side of “looks cleaner”: some of these methods barely depend on the model’s weights at all (Adebayo et al. 2018).


3. Integrated Gradients

3.1 定义与直觉 Definition and intuition

梯度的问题是”只看终点”。IG 的修法很直接:沿一条从基线到输入的路径,把一路上的梯度都加起来。

IGi(x;x′)=(xi−xi′)∫01∂F(x′+α(x−x′))∂xi dα\mathrm{IG}_i(x; x') = (x_i - x'_i)\int_0^1 \frac{\partial F\big(x' + \alpha(x - x')\big)}{\partial x_i}\,d\alpha

为什么这样定义?把 g(α)=F(γ(α))g(\alpha) = F(\gamma(\alpha)) 看成一元函数,由链式法则 g′(α)=∑i∂F∂xi(γ(α)) (xi−xi′)g'(\alpha) = \sum_i \frac{\partial F}{\partial x_i}(\gamma(\alpha))\,(x_i - x'_i)。微积分基本定理给出

F(x)−F(x′)=∫01g′(α) dα=∑iIGi(x;x′)F(x) - F(x') = \int_0^1 g'(\alpha)\,d\alpha = \sum_i \mathrm{IG}_i(x; x')

也就是说,IG 是把 F(x)−F(x′)F(x) - F(x') 这笔总账逐项拆开:路径上每走一小步,输出的变化 = 各分量的偏导 × 各分量走的距离,每个分量记下自己那份。在饱和的例子里,路径上 α∈[0,1/7)\alpha \in [0, 1/7) 那一段 FF 还在变(梯度是 (2,3)(2, 3)),之后梯度为 0。于是 x1x_1 得 2⋅2⋅17=472 \cdot 2 \cdot \tfrac17 = \tfrac47,x2x_2 得 1⋅3⋅17=371 \cdot 3 \cdot \tfrac17 = \tfrac37:饱和之前的贡献被完整地记了下来。

基线是”什么都没有”的输入:图像用全黑图,文本用全零词向量(§5、§8)。IG 解释的永远是 F(x)−F(x′)F(x) - F(x'),所以论文建议选一个 F(x′)≈0F(x') \approx 0 的基线,这样归因就近似于”把 F(x)F(x) 分给各个输入”。

3.2 The axioms

Instead of arguing about which heat map “looks right”, the IG paper lists properties an attribution method should have, then asks which methods satisfy them (the list on the Fall 2023 slides):

  • Sensitivity(a). If xx and x′x' differ in one feature and F(x)≠F(x′)F(x) \ne F(x'), that feature gets a non-zero attribution. Violated by gradients, gradient × input, DeconvNet, guided backprop (§2.3–§2.4).
  • Sensitivity(b) (called Dummy by Friedman; “insensitivity” on the slides). If FF does not depend mathematically on a variable, that variable always gets zero.
  • Implementation invariance. Two networks that compute the same function get the same attributions. Gradients satisfy it automatically — the chain rule is exactly the statement that the derivative doesn’t care how you factor the computation. Violated by DeepLIFT and LRP (§3.5).
  • Completeness. ∑iAi(x;x′)=F(x)−F(x′)\sum_i A_i(x; x') = F(x) - F(x'). Completeness implies Sensitivity(a): if only feature ii differs, it must carry the whole difference. This is the property that lets you read attributions as an account, which is what you need when the score is used as a number (the paper’s example: insurance premiums from credit features).
  • Linearity. Attributions of aF1+bF2a F_1 + b F_2 are aa times those of F1F_1 plus bb times those of F2F_2.
  • Symmetry-preserving. If swapping xix_i and xjx_j never changes FF, and the input and baseline have equal values for them, then xix_i and xjx_j get equal attributions.

These are recognizably the Shapley axioms of Lecture 2 transplanted to continuous inputs: completeness ↔ efficiency, Sensitivity(b) ↔ dummy, linearity ↔ additivity, symmetry ↔ symmetry. Implementation invariance is the new one — it is implicit for a black box (which only sees the function) but becomes a real constraint once a method is allowed to look inside.

3.3 Paths, uniqueness, and the relation to Shapley

把直线换成任意一条从 x′x' 到 xx 的光滑路径 γ\gamma,得到 path method:

Aiγ(x)=∫01∂F(γ(α))∂xi dγi(α)dα dαA^\gamma_i(x) = \int_0^1 \frac{\partial F(\gamma(\alpha))}{\partial x_i}\,\frac{d\gamma_i(\alpha)}{d\alpha}\,d\alpha

所有 path method 都满足 implementation invariance(只用到梯度)和 completeness(同样是微积分基本定理)。两个唯一性结论把 IG 钉住了:

  1. Friedman(2004):在成本分摊(cost sharing)的框架里,path methods 是唯一同时满足 implementation invariance、Sensitivity(b)、linearity、completeness 的方法(IG 论文的 Proposition 2 直接引用了这个定理)。
  2. IG 论文 Theorem 1:在所有(单条路径的)path method 里,直线路径是唯一保持对称性的。

经济学里早就有这个方法:IG 就是 cost sharing 里的 Aumann–Shapley 方法(Aumann & Shapley 1974,“非原子博弈”)。直觉是:Shapley 值把每个特征当成一个不可分割的玩家,要么在场、要么缺席;Aumann–Shapley 把每个特征看成由无穷多个”无穷小的玩家”组成,所有特征沿对角线同时、按比例地从基线”长”到输入值。

那 Shapley 值本身是什么路径?沿坐标轴、一次把一个特征从基线值改成输入值的”阶梯路径”,每个特征分到它被改那一步的输出变化——这正是 Shapley 公式里的边际贡献。对全部 n!n! 个顺序取平均就是(以基线为”缺席”值的)Shapley 值;IG 论文称之为 Shapley–Shubik 方法(Remark 5)。代码 01 演示 2 把几种路径放在一起:

FFinputIG(直线)阶梯 x1→x2x_1 \to x_2阶梯 x2→x1x_2 \to x_1Shapley(两者平均)
min⁡(2x1+3x2,1)\min(2x_1 + 3x_2, 1)(2, 1)(0.571, 0.429)(1, 0)(0, 1)(0.5, 0.5)
min⁡(x1,x2)\min(x_1, x_2)(1, 3)(1, 0)(0, 1)(1, 0)(0.5, 0.5)
sigmoid(x1+x2)\mathrm{sigmoid}(x_1 + x_2)(1, 1)(0.190, 0.190)(0.231, 0.150)(0.150, 0.231)(0.190, 0.190)
x1x2x_1 x_2(2, 3)(3, 3)(0, 6)(6, 0)(3, 3)

读这张表:

  • 每一行的所有方法加起来都是 F(x)−F(x′)F(x) - F(x')——它们只在”怎么分”上不同。
  • 单条阶梯路径破坏对称性(sigmoid 那一行:两个对称的特征分到 0.231 和 0.150)。Shapley 靠”对所有顺序取平均”恢复对称;IG 靠”选直线”恢复对称。
  • 两者在 min⁡\min 上分歧最大。min⁡(x1,x2)\min(x_1, x_2) 在 (1,3)(1, 3):沿对角线 x1x_1 一直是较小的那个(“关键变量”),IG 把全部归给它;Shapley 各给一半。IG 论文用的正是这个例子,并坦率地说偏好哪一个”有些主观”。
  • 对乘积这样光滑、对称的函数,两者常常一致。

所以 IG 不是”Shapley 值的近似”,而是同一个公理家族里的另一个成员:多了 implementation invariance 和”连续地放大输入”的视角,少了”把特征当作原子玩家”的视角,换来的是与 nn 无关的计算量。

3.4 Computing IG: Riemann sums and the completeness check

In practice the integral is a sum over mm points on the path. The paper uses the right-endpoint rule

IGi≈(xi−xi′)⋅1m∑k=1m∂F(x′+km(x−x′))∂xi\mathrm{IG}_i \approx (x_i - x'_i)\cdot\frac{1}{m}\sum_{k=1}^{m}\frac{\partial F\big(x' + \tfrac{k}{m}(x - x')\big)}{\partial x_i}

and gives a practical rule: in their experiments 20 to 300 steps were enough to get within 5%, and developers should check that the attributions add up to F(x)−F(x′)F(x) - F(x'), increasing mm if they do not. This check needs no ground truth — it is a free unit test. Code 01, demo 3 runs it on a random 3-layer ReLU network (64 → 128 → 128 → 1, biases σ = 0.5) for 200 inputs; cells are the median relative completeness error, with the fraction of inputs within 5% in parentheses:

steps mmleftrightmidpointtrapezoid
11.1820 (0.04)0.5194 (0.07)0.4456 (0.06)0.5570 (0.06)
40.2864 (0.14)0.2286 (0.16)0.1648 (0.17)0.1641 (0.17)
160.0593 (0.47)0.0617 (0.45)0.0394 (0.57)0.0483 (0.51)
640.0139 (0.76)0.0134 (0.79)0.0096 (0.84)0.0103 (0.86)
2560.0036 (0.94)0.0039 (0.92)0.0027 (0.97)0.0028 (0.96)

Three things to take away:

  1. Error roughly halves when mm doubles — O(1/m)O(1/m). Midpoint and trapezoid help a little but not by orders of magnitude: along the path a ReLU network’s gradient is piecewise constant with many jumps, so the O(1/m2)O(1/m^2) advantage these rules have on smooth functions disappears.
  2. Relative error misleads when F(x)≈F(x′)F(x) \approx F(x'). At 256 midpoint steps, the 6 inputs still above 5% all have ∣F(x)−F(x′)∣≤0.054|F(x) - F(x')| \le 0.054 (median over all inputs: 0.562), with absolute errors at most 0.0036. Check absolute error too.
  3. Gradient × input is 1-step IG. With baseline 0, the right-endpoint rule at m=1m = 1 is exactly x⊙∇F(x)x \odot \nabla F(x) (code: maximum difference 0). With all biases removed, gradient × input is already complete (median error 7.7×10−167.7 \times 10^{-16}): a bias-free ReLU network is positively homogeneous, F(αx)=αF(x)F(\alpha x) = \alpha F(x), so its gradient is the same at every point of the path. Real networks have biases, max-pooling and sigmoids; on the image CNN of §4, ∑i\sum_i gradient × input misses F(x)−F(0)F(x) - F(0) badly (Model C, horizontal images: 7.90 vs 4.93), while 64-step IG has a median relative error of 0.36%.

3.5 Implementation invariance; DeepLIFT and LRP

DeepLIFT(Shrikumar et al. 2017)和 LRP(Bach et al. 2015)是另一类思路:不积分,而是设计一套”反向传播规则”,一次反传就得到满足(或近似满足)completeness 的归因。DeepLIFT 的 Rescale 规则把 ReLU 的导数换成离散梯度:

mReLU=ReLU(z)−ReLU(z′)z−z′m_{\text{ReLU}} = \frac{\mathrm{ReLU}(z) - \mathrm{ReLU}(z')}{z - z'}

(z′z' 是基线输入在同一个神经元上的值),线性层照常乘权重。每一层都满足”贡献之和 = 输出之差”,所以整体满足 completeness,而且离散梯度能跨过平坦区,不受饱和影响。问题是:离散梯度不满足链式法则,结果取决于网络的实现方式。IG 论文附录 B 的一对网络:

f(x)=ReLU(ReLU(x1)−1−ReLU(x2)),g(x)=ReLU(ReLU(x1−1)−ReLU(x2))f(x) = \mathrm{ReLU}\big(\mathrm{ReLU}(x_1) - 1 - \mathrm{ReLU}(x_2)\big), \qquad g(x) = \mathrm{ReLU}\big(\mathrm{ReLU}(x_1 - 1) - \mathrm{ReLU}(x_2)\big)

它们是同一个函数(代码 01 演示 4 在 10 万个随机点上验证了 max⁡∣f−g∣=0\max|f - g| = 0)。在 x=(3,1)x = (3, 1)、基线 (0,0)(0, 0) 处:

methodnetwork ffnetwork gg
gradient at xx(1, −1),Σ = 0(1, −1),Σ = 0
gradient × input(= LRP-0)(3, −1),Σ = 2(3, −1),Σ = 2
guided backprop(1, 0)(1, 0)
DeepLIFT(Rescale)(1.5, −0.5),Σ = 1(2, −1),Σ = 1
Integrated Gradients(1.5, −0.5),Σ = 1(1.5, −0.5),Σ = 1

DeepLIFT 的两组数字与 IG 论文 Figure 7 报告的一致:它满足 completeness,却违反 implementation invariance。为什么这条公理重要?训练可能收敛到同一个函数的不同实现(比如参数冗余时),我们不希望归因因为”碰巧收敛到哪组参数”而改变。

LRP 的最简单规则 LRP-0 把输出按 ajwjk/zka_j w_{jk}/z_k 的比例逐层往回分。可以用归纳法证明,在 ReLU 网络上每一层都有 Rj=aj ∂F/∂ajR_j = a_j\,\partial F/\partial a_j,所以输入层就是 gradient × input(代码 01 演示 4 在随机网络上验证:最大差 4.4×10−164.4\times10^{-16})。Ancona et al.(2018)系统地整理了这类等价关系:很多”规则不同”的方法,在 ReLU 网络上其实是同一个量,或者是 IG 的某种近似。规则类方法的优点是快(一次反传 vs IG 的 mm 次),代价是失去了一部分公理保证。

3.6 SmoothGrad

Gradients of ReLU networks are piecewise constant and jump around from pixel to pixel, so raw gradient maps look noisy. SmoothGrad (Smilkov et al. 2017) averages the gradient over Gaussian-noised copies of the input:

∇F^(x)=1N∑k=1N∇F(x+ϵk),ϵk∼N(0,σ2I)\widehat{\nabla F}(x) = \frac{1}{N}\sum_{k=1}^{N}\nabla F(x + \epsilon_k), \qquad \epsilon_k \sim \mathcal{N}(0, \sigma^2 I)

which is the gradient of FF smoothed by a Gaussian kernel. The authors suggest σ around 10–20% of the input range; code 02 uses σ = 0.3 and N=32N = 32. SmoothGrad trades the “explain this exact point” semantics for stability; it has no completeness, and with too large a σ it averages gradients of other inputs. In our shortcut experiment it behaves like saliency (mark share 0.091 vs saliency’s 0.078 for Model S): smoothing removes noise but does not turn sensitivity into contribution. The same averaging trick can be applied on top of gradient × input or IG.


4. 用归因找出捷径 · Finding the shortcut

4.1 Where does the model look?

回到 §1.4 的两个模型。代码 02 演示 3 对 400 张带水印的图(两类各约一半)计算四种归因,统计三个量:mark share = |归因|落在水印 9 个像素上的比例(面积 3.5%);top-1 = 归因绝对值最大的像素落在水印里的图像比例;bar share = 落在短线像素上的比例(短线平均占面积 1.9%)。

methodS: mark shareS: top-1S: bar shareC: mark shareC: top-1C: bar share
saliency |grad|0.0780.0050.1370.0070.0000.214
gradient × input0.2150.1150.2200.0190.0000.354
Integrated Gradients0.3500.4450.2270.0310.0000.404
SmoothGrad |grad|0.0910.0050.1260.0050.0000.182
  • 四种方法都”看见”了捷径:Model S 的 mark share 是 Model C 的 11–18 倍。IG 最清楚:35% 的 |IG| 落在 3.5% 的面积上,44.5% 的图像”最重要的像素”就在水印里;Model C 只有 3.1%,比面积还小。
  • Model S 也看短线(bar share 0.227):它两样都学了,这与 clean 准确率 0.766 > 0.5 一致。归因不是”非此即彼”的判决,而是一个比例。
  • 敏感度类方法(saliency、SmoothGrad)的比例低得多,原因见 §2.2。

单张图的归因有噪声;把几百张图的归因叠起来更可靠。下面是代码 02 打印的 400 张图的平均 |IG|(字符越重 = 越大;按 99% 分位数截断,这是 Fall 2023 讲座专门强调的可视化细节——归因的分布有长尾,直接按最大值缩放会让大多数像素显示成空白):

Model S: mean |IG|                 Model C: mean |IG|
..##++                             ....::                  ....
##@@@@..                           ------    ....    ..............
@@@@@@..                           ::----    ......................
....                               ..  ..  ........................
              ............                 ..::----====++==++--::..
              ............               ....::::==--========--::::
          ..................  ..         ..::====++##**####**++----
          ......................       ....::++==++****@@%%@@**----
          ......::::............     ......::****@@@@@@@@@@**======
          ....::................     ......::##++@@%%**++**##++**==
          ......................     ......::==++++%%%%##++%%++**++
          ......................         ..::==++++%%**++++**==++==
          ......................         ..::--====**++**++**++++++
          ......................       ....::------**==++++++==----
            ..................       ..  ..::::--==****++**++----::
            ................             ....::::----::::----::::..

左图里最亮的一块在左上角;右图的归因集中在短线可能出现的区域(第 4–15 行、第 4–15 列),左上角只有很淡的痕迹。

4.2 Completeness as accounting

Completeness turns a heat map into a ledger. Code 02, demo 4: the sum of IG over the 9 watermark pixels is “how many logits the watermark is worth” according to IG. Because the world is synthetic, we can also actually remove the watermark and measure how much the logit drops — a counterfactual that real data rarely allows.

modelclassnF(x)−F(0)F(x) - F(0)Σ IGΣ grad×inputIG on markF(x)−F(xno mark)F(x) - F(x_{\text{no mark}})corr
Svertical1865.825.826.054.894.820.91
Shorizontal214−0.59−0.591.58−4.94−4.850.90
Cvertical1863.663.675.58−0.08−0.080.61
Chorizontal2144.934.937.900.080.080.64

(FF = logit for the true class; baseline = black image; 64-step IG with median relative completeness error 0.36%.)

  • For Model S’s vertical images, IG books 4.89 logits to the watermark; erasing it lowers the logit by 4.82 on average, with a per-image correlation of 0.91. Most of the model’s total evidence (5.82) is the watermark.
  • On horizontal images both numbers are about −4.9: the watermark is evidence against the true class, which is why the average total evidence is negative (−0.59) and Model S does so badly on the flipped test set.
  • Model C’s watermark account is ±0.08, matching the counterfactual — attribution and intervention agree that C does not use the shortcut.
  • Σ gradient × input does not balance (+1.58 vs −0.59 for S’s horizontal images: even the sign is wrong).

为什么不直接做”擦掉”实验?因为现实中通常不知道该擦什么,也擦不干净(笔迹下面原来是什么像素?)。正确的分工是:归因先给出可疑区域和一个定量的账目,反事实实验再去验证。另外注意两个数回答的是不同的问题:IG 比较的是”相对全黑图”,擦水印比较的是”相对同一张图的无水印版本”——基线不同,问题就不同(§5)。

4.3 人的角色 · The human in the loop

Fall 2023 讲座给出了一个归因驱动的 debugging workflow:

Build model → 测试准确率好吗? ─否→ 改模型
                    │是
                    ▼
        抽样检查归因 → 看起来对吗? ─是→ 部署(继续监控)
                    │否
                    ▼
   Fix test–train split / Fix data / Fix features / Fix architecture & objective

讲座里的几个真实例子:

  • “Clog”(木屐):一张图被分类为 clog,讲座展示了它的 IG 热图,给出的下一步是”收集更多不同颜色的木屐图片?“——也就是 Fix data。
  • 化学模型的架构 bug(IG 论文 §6.5):一个预测分子活性的图卷积网络里,几个连接不同原子的原子得到了完全相同的归因;追查发现网络架构有 bug,原子与原子对的特征没有被充分卷积(Fix architecture)。
  • X 光上的笔迹(第 1 讲 §1.4)与本讲的水印(Fix data:让水印与标签无关,就是 Model C)。

讲座强调了一个分工:人不擅长预见问题,但擅长理解一个具体解释在真实世界里意味着什么。归因只能说”模型用了左上角”;说”那是医生的笔迹、部署时不会有”的是人。同样,可视化的选择(截断、叠加方式)会决定人能不能看出问题。


5. 基线:和什么比? · Choosing a baseline

5.1 A baseline is a counterfactual

IG explains F(x)−F(x′)F(x) - F(x'), so the baseline is the question: “why this prediction, compared to what?” The IG paper’s advice (§5): pick a baseline whose score is near zero, and that “conveys a complete absence of signal” — the black image for vision, the all-zero embedding for text. It also warns against baselines that are near-zero for the wrong reason: one can construct an adversarial example with a near-zero score for a class, and attributions relative to it would contain the adversary’s artifacts.

Code 03, demo 3 explains Model S on 200 watermarked vertical-bar images with five baselines:

baselineF(x′)F(x')F(x)−F(x′)F(x) - F(x')mean |gap|mark shareIG on markrank corr. with black
black (0)−0.795.760.0130.3694.881.000
blur (5×5)2.082.890.0110.2052.290.801
noise (average of 8)−1.856.810.0080.3324.860.608
training-mean image1.053.910.0110.2592.970.950
white (1)27.94−22.980.0540.0130.130.178

5.2 What the table says

  • No baseline is neutral. The black image has logit −0.79; the training-mean image carries “half a watermark” (its corner averages about 0.5) and scores 1.05; the blurred image still shows a faint watermark and scores 2.08. Each one changes the total being distributed.
  • The blind spot. If xi=xi′x_i = x'_i, then IGi=0\mathrm{IG}_i = 0 no matter what. The white image is about as bright as the watermark, so with a white baseline IG sees almost nothing there (mark share 0.013): an analyst using it would conclude the model ignores the watermark. And the white image is far from “absence of signal” — Model S gives it a logit of 27.94, so IG ends up explaining why xx is less vertical than a white screen.
  • Partial occlusion. The blur and training-mean baselines already contain part of the watermark, so only part of it is credited (0.205, 0.259).
  • Black and noise baselines both expose the shortcut clearly. Averaging over many random baselines (as we did with 8 noise images) is the idea behind “expected gradients” (Erion et al. 2021); it multiplies the cost by the number of baselines.

基线也可以是刻意选的反事实。§4.2 里”同一张图去掉水印”就是一个基线:用它做 IG,输入层的归因只会落在水印上(别处 xi=xi′x_i = x'_i),看起来没什么信息;但在隐藏层上,它精确地回答了”水印的效果流经了哪些神经元”(§7.3)。基线的选择没有标准答案,只有和问题匹配的答案。Sturmfels, Lundberg & Lee(2020)在 Distill 上的文章用交互图比较了常见基线的效果,值得一读。

实用建议(与 IG 论文一致):选一个”没有信号”的基线、检查 F(x′)F(x') 的值、做 completeness 检查;对重要的结论,换两三个基线看它是否稳定。


6. 怎样评估归因 · Evaluating attributions

6.1 Why evaluation is hard

一个归因看起来不对,可能有三个原因:模型本身在用奇怪的东西(这正是我们想发现的);归因方法出了错;或者评估方法引入了假象。IG 论文说,他们能想到的每种经验评估都”无法区分来自数据扰动的假象、模型的问题和归因方法的问题”——这是他们转向公理化的原因。

还有一种常见的评估是和人类的”标准答案”比(比如物体的标注框里有多少归因)。Fall 2023 讲座指出两个问题:归因可能因为网络的推理方式和人不同而”看起来不对”;以及确认偏误(confirmation bias)。本讲的 Model S 是一个尖锐的例子:它的归因有 35% 落在水印上,按”标准答案 = 短线”打分会被判为很差的归因——可它恰恰是忠实的。讲座的原话是:归因的使命是忠实于模型的推理(faithful to the model’s reasoning),不是符合人的直觉。

6.2 Deletion and insertion curves

The most common faithfulness test perturbs the input in attribution order. Deletion (the region-perturbation test of Samek et al. 2017, which grew out of “pixel flipping”; named deletion / insertion by Petsiuk et al. 2018) replaces the top-kk pixels with a fill value and tracks how fast the score drops — a faithful attribution should make it drop fast. Insertion starts from the fill image and restores the top-kk pixels — the score should recover fast. HW2 uses two relatives: Average Drop % (keep only positively attributed pixels, measure the relative score drop) and the Necessity Ordering score from Wang et al. (2020).

Code 03, demo 1 (Model C, 200 clean test images, FF = true-class logit, 4.61 on the originals). Areas under the curve averaged over k∈{0,1,2,3,4,6,8,12,16,24,32,48,64}k \in \{0, 1, 2, 3, 4, 6, 8, 12, 16, 24, 32, 48, 64\}; ± is the standard error over images:

methoddeletion, fill 0 ↓deletion, fill white ↓insertion, fill 0 ↑insertion, fill noise ↑
saliency |grad|0.76 ± 0.075.79 ± 0.533.52 ± 0.222.52 ± 0.21
gradient × input−0.75 ± 0.1210.16 ± 0.366.05 ± 0.234.05 ± 0.23
IG (black)−0.57 ± 0.129.87 ± 0.356.22 ± 0.234.23 ± 0.23
SmoothGrad |grad|0.65 ± 0.065.22 ± 0.503.78 ± 0.232.70 ± 0.22
random order4.15 ± 0.273.22 ± 0.310.07 ± 0.020.00 ± 0.10
bar pixels first(“人类答案”)0.73 ± 0.118.55 ± 0.274.71 ± 0.203.19 ± 0.21
  • With a black fill, every method beats random order by a wide margin: deleting the 2–3 top pixels drops the evidence from 4.6 to below 1, while deleting 64 random pixels (a quarter of the image) only gets it to 2.9. The bar is only 4–6 pixels.
  • Signed methods (gradient × input, IG) push the deletion curve below zero: they remove the supporting pixels first and leave the opposing ones. Absolute-value methods remove both and stall near 0. Gradient × input is lowest on deletion and IG highest on insertion, but each lead is within about one standard error — call it a tie, and compare methods with error bars (Lecture 1, §8).
  • With a white fill the conclusion flips. Deleting the “most important” pixels raises the evidence (white pixels make the bar brighter), and every method — including the human answer — scores worse than random order. White pixels never occurred in training: the metric is measuring the model’s reaction to strange images, not the attribution’s quality. This is the off-manifold problem the IG paper warned about. ROAR (Hooker et al. 2019) addresses it by retraining the model on images with the top pixels removed, at a much higher cost.

The noise and blur fills (full table in the code output) did not change the ranking here; but the lesson stands: a deletion score is meaningless without its fill.

6.3 Necessity, sufficiency, and organizing methods by criteria

Wang, Mardziel, Datta & Fredrikson(2020,“Interpreting Interpretations”)给这些曲线一个逻辑上的解释:deletion 衡量 necessity(必要性)——去掉被标为重要的特征,输出是否就保不住了?insertion 衡量 sufficiency(充分性)——只留下被标为重要的特征,输出是否就能恢复?他们再加上 proportionality(比例性)——归因的大小是否与影响的大小成比例——并定义了对应的量化指标。他们在图像 CNN 上的结论是:有的方法适合按必要性解读,有的适合按充分性解读,没有一个方法在两方面都最好。

这个视角把”哪个归因方法最好”这个问题改写成了”你要它回答哪个问题”。本讲的小实验里两者打成平手,但填充值一变,所有排名都可能改变——评估准则本身也需要说明前提。

6.4 Sanity checks

Adebayo et al. (2018) proposed two randomization tests: model randomization (re-initialize the weights layer by layer from the top, “cascading”) and data randomization (train on shuffled labels). If an attribution map barely changes when the model has learned nothing, it cannot be explaining the model. They found that some popular methods — guided backpropagation among them — produce maps that are largely insensitive to the randomization, and compared such methods to an edge detector, which needs neither a model nor data. Code 03, demo 2 (rank correlation of |attribution| with Model C’s, averaged over 200 images):

modelaccsaliencygrad × inputIGSmoothGrad
Model C itself0.9101.0001.0001.0001.000
same data, different init seed0.8630.5000.6510.6300.619
randomize fc0.4650.3910.6010.5680.409
randomize fc + conv20.5060.2150.5120.4980.220
randomize all layers0.5040.0810.4460.4470.104
trained on shuffled labels0.5150.1100.4520.4750.091
|input| itself as “attribution”—0.1060.5700.5910.063
  • Saliency and SmoothGrad pass: once the model is random, their maps share almost nothing with the trained model’s.
  • Gradient × input and IG keep a rank correlation of about 0.45 with a completely random model — not far below the 0.63–0.65 of an equally good model trained with another seed. The last row shows why: these methods multiply by xx, and ∣x∣|x| alone (bright bar, dark background) already has a 0.57–0.59 rank correlation with Model C’s maps. A map that “looks like the object” may mostly be showing the input.
  • That does not make IG wrong — for the random model it still gives a complete, faithful account of that model. It means “looks plausible” is not evidence of faithfulness, and the sanity check tests “is the attribution sensitive to the model?”, not “is it correct?”.
  • The first row deserves its own sentence: two models with similar accuracy, trained on the same data, agree on attributions only at 0.50–0.65. Attributions explain a model, not a task — the Rashomon effect of Lecture 1, §2.3, seen through the explanation lens.

6.5 Evaluations can share assumptions with the method

最后一个小实验(代码 03 演示 3b):用 deletion 去”评估”三种基线的 IG(Model C,干净图像;数值越低越好):

IG 的基线 \ deletion 的填充值fill = zerofill = blurfill = noise
zero−0.57−0.51−0.44
blur−0.55−0.56−0.43
noise−0.29−0.20−1.45

每一列的最优都在对角线上:IG 解释的是”从基线到 xx“的变化,而”填充值 = 基线”的 deletion 测的正是同一个变化(噪声那一列尤其明显,因为这里 IG 的噪声基线和 deletion 的噪声填充是同一张图)。练习 5 会在线性模型上证明这一点。评估方法和被评估的方法共享同一个假设时,排名就带上了偏向。

评估方式它检验什么主要陷阱
和人类标注比较归因是否符合人的直觉模型可能本来就不按人的方式推理(Model S);确认偏误
Deletion / insertion必要性 / 充分性填充值造成 off-manifold;偏向基线 = 填充值的方法
ROAR(删掉再重训)被删的信息是否真的有用代价高;重训后的模型已经不是原来那个模型
Sanity checks归因是否依赖模型和数据通过了不等于忠实
公理方法在所有模型上的性质公理本身是规范性选择(IG vs Shapley 的分歧)

7. 内部影响 · Internal influence

7.1 Why look inside

Fall 2023 讲座有一页题为 “Feature attributions are pretty shallow”:输入归因说明不了网络怎样组合这些特征、哪些训练数据影响了预测、梯度下降为什么收敛到这里。输入归因在”一小部分输入特征很重要”时最有用。要回答”网络内部用什么概念做决定”,需要把归因的对象从输入换成内部单元。

讲座的例子:一个 Inception 网络把视网膜图像判为糖尿病视网膜病变 5 级,最有影响的内部单元对应视盘和病灶;一个 VGG16 区分”跑车 vs 敞篷车”时,最有影响的神经元对应的概念能泛化到多张图——这是单张图的像素归因给不了的。

7.2 Distributional influence (Leino et al. 2018)

Influence-directed explanations 分两步:先用一个影响度量找出有影响的内部神经元,再用可视化解释它们代表什么。影响度量有三个要素:

  • Quantity of interest:解释哪个输出(某类的分数,或两类分数之差——HW2 里”为什么是 weasel 而不是 polecat”);
  • Distribution of interest(DoI):在哪些输入上平均(一张图;一类图;或从基线到输入的直线插值——HW2 书面题 18 比较了前两种);
  • Slice:在哪一层把网络切开,F=g(h(x))F = g(h(x))。
χj=Ex∼P[∂g∂hj(h(x))]\chi_j = \mathbb{E}_{x \sim P}\left[\frac{\partial g}{\partial h_j}\big(h(x)\big)\right]

即”关心的分布上的平均梯度”;讲座说它是满足一组自然性质的唯一度量。找到影响最大的”专家神经元”后,用它的激活对输入的 saliency map 给它”配图”。

7.3 Conductance

Conductance (Dhamdhere, Sundararajan & Yan 2019) measures how much of the IG attribution flows through a hidden unit along the straight path:

Condj=∫01∂F∂hj(h(γ(α))) d hj(γ(α))dα dα\mathrm{Cond}_j = \int_0^1 \frac{\partial F}{\partial h_j}\big(h(\gamma(\alpha))\big)\,\frac{d\,h_j(\gamma(\alpha))}{d\alpha}\,d\alpha

Summed over all units of a layer that cuts the network, it equals F(x)−F(x′)F(x) - F(x') — completeness holds layer by layer, because every bit of the output change has to pass through that layer. Distributional influence looks only at the slope; conductance is slope × how much the activation actually moved.

Code 04 cuts Model S at conv2 (16 channels × 8 × 8 positions = 1024 units) and uses two baselines on 200 watermarked vertical images. Completeness checks: with the black baseline, Σ conductance = 5.754 vs F(x)−F(0)F(x) - F(0) = 5.760; with the same image minus the watermark as baseline, 4.794 vs 4.801. The second baseline asks precisely “through which units does the watermark’s effect flow?”

channel(a) influence(b) conductance, black baseline(c) conductance, no-mark baseline
156.0993.8010.913
3−4.0080.5990.869
9−1.2490.5660.620
80.1820.6220.540
1−0.5490.4140.418

(Model S’s top 5 channels by column (c); Model C’s column (c) sums to −0.085 — the watermark changes some activations, but the head does not use them.)

The plan was “find the watermark channel and switch it off”. The data said otherwise: the watermark’s 4.79 logits are spread over several channels (the biggest carries 0.91; the top three about half), and channel 15 is also the largest carrier of the total evidence (3.80 of 5.75). Giving each channel a picture (IG of its total activation) did not help either: every channel’s activation draws 35–70% of its attribution from the 3.5%-area watermark, because the watermark is the brightest thing in the image and lights up almost any blob or edge detector.

7.4 Choosing the unit of analysis, and ablation

换一个分析单位,答案立刻变干净:把 (c) 列的 conductance 对 16 个通道求和、按 conv2 的 8 × 8 个位置摊开(代码 04 演示 2),水印的效果只经过左上角的几个位置(例如 (0,0) 位置 1.80、(1,1) 位置 1.93),其余 50 多个位置全部是 0.00。CNN 的卷积在所有位置共享权重,所以在这个模型里,“在哪里”比”哪个通道”更能刻画捷径。这正是 Leino et al. 强调 slice 的原因:影响度量没有错,但选错了单位就解释不出东西。

知道了位置,就可以消融(ablation):把选中单元的激活换成某个固定值。代码 04 演示 3(K = 被替换的单元个数,共 1024 个):

Model S variantvalcleanflipped
不消融0.9710.7660.571
通道 15 的全部 64 个单元 → 00.9140.4950.422
通道 15 的全部 64 个单元 → 训练均值0.9510.5080.356
按 (c) 选 K = 16 个单元 → 00.8320.7670.762
按 (c) 选 K = 16 个单元 → 训练均值0.8900.8870.902
按 (b) 选 K = 16 个单元 → 训练均值0.9150.8780.822
随机 K = 16 个单元 → 训练均值(10 次平均)0.9710.7620.564
(参照)Model C0.9130.9100.922
  • 关掉整个通道 15,模型就认不出竖线了(clean 0.495):这个通道一身多职,关掉它把有用的东西一起关掉了。
  • 按位置选出的 16 个单元替换成 0:三个测试集变得差不多(0.83 / 0.77 / 0.76)——模型不再对水印有反应,但 clean 准确率没有提高,就像在所有图上都”看不到水印”。
  • 替换成训练数据上的平均激活:clean 从 0.766 升到 0.887,接近 Model C。这是计划外的发现。原因是 Model S 学到的不只是”有水印 → 竖线”,还有”没有水印 → 多半是横线”;部署时水印全部消失,它就系统性地偏向横线。替换成平均激活等于”永远假装有半个水印”,抵消了这个偏差,剩下的短线特征其实相当不错。
  • 随机关掉同样多的单元几乎没有影响,说明上面的变化不是”随便关几个都会这样”。

两个教训。第一,“关掉”不是中性操作:替换成 0 还是均值,是隐藏层版本的”基线 / 填充值”问题(§5、§6.2)。第二,内部归因的主要价值是定位;这个”修复”依赖我们知道水印在哪、并且有干净的数据来验证。可靠的修复仍然是回到数据(workflow 的 Fix Data),也就是 Model C。

7.5 Influence paths and patterns

Going one step further, one can attribute along paths through the network. By the chain rule, the gradient of the output with respect to an input is a sum over all paths through the computation graph of products of local derivatives; each path’s term is its share of the influence. Lu, Mardziel, Leino, Fredrikson & Datta (ACL 2020) used this to study subject–verb number agreement in LSTM language models: for “The boys behind the tree …”, the quantity of interest is P(are)−P(is)P(\text{are}) - P(\text{is}), and the influence paths show through which gates and cells the plural subject “boys” reaches the verb across the distracting “tree”. The paths explained misclassifications, and the model could be compressed down to its influential paths without losing much utility. Lu, Wang, Mardziel & Datta (NeurIPS 2021) scaled this to BERT as influence patterns — abstractions over sets of paths through the transformer. They found that a significant portion of BERT’s information flow goes through skip connections rather than attention heads, and that the patterns account for model behavior better than analyses based on attention weights; the 2022 slides summarize the patterns as “copy” and “transfer” operations that carry context across layers. (This is one reason attention weights alone are a poor explanation — the IG paper makes the same point about LSTMs with attention.)

7.6 Concept-based explanations: TCAV and ACE

神经元不一定对应人能理解的概念。TCAV(Kim et al. 2018)反过来:先由人给出一个概念(一组”条纹”图片,或者本讲的”带水印的图片”),在某个隐藏层上训练一个线性分类器区分”概念图像”和”随机图像”,它的法向量就是概念激活向量(CAV)vv。对每个输入计算方向导数 S(x)=∇hF⋅vS(x) = \nabla_h F \cdot v:S>0S > 0 表示”更像这个概念 → 更像这一类”。TCAV 分数是 S>0S > 0 的输入比例。ACE(Ghorbani, Wexler, Zou & Kim 2019)进一步自动化:把图像在多个尺度上切成小块,在激活空间里聚类得到候选概念,再用 TCAV 给它们打分;论文要求概念有意义(meaningfulness)、内部一致(coherency)、对预测重要(importance)。

代码 04 演示 4 用最简单的 CAV(两组图像在 conv2 上的平均激活之差),解释 200 张没有水印的竖线图。每个概念重复 20 次(每次随机抽 100 张概念图、100 张随机图);effect = 方向导数的平均(logit 单位):

modelconceptTCAV mean[min, max]effect mean[min, max]
Smark1.000[1.00, 1.00]2.498[2.23, 2.94]
Svertical bar1.000[1.00, 1.00]1.131[0.87, 1.48]
Srandom (floor)0.586[0.04, 1.00]0.107[−0.21, 0.74]
Cmark0.526[0.01, 0.99]0.032[−0.53, 0.63]
Cvertical bar1.000[1.00, 1.00]1.773[1.28, 2.28]
Crandom (floor)0.525[0.00, 0.99]−0.012[−0.62, 0.53]
  • 被解释的图里根本没有水印,TCAV 仍然发现 Model S 的”竖线”判断对水印方向高度敏感:概念方法问的是”在模型的内部表示里,这个方向意味着什么”,不需要概念出现在当前输入里。这是它和输入归因最大的不同。
  • 单个 TCAV 分数说明不了什么:随机概念的分数从 0.04 到 1.00 都有(这个小网络的 head 几乎是线性的,很多方向在所有输入上符号一致)。我们最初只算了一个 CAV,Model C 的水印分数恰好是 0.000,看起来像一个很强的负向概念;重复 20 次后它和随机概念无法区分。Kim et al. 的做法是训练很多个 CAV、对随机 CAV 做统计检验 —— 和第 1 讲的”噪声地板”同一个道理。这里能区分概念与随机方向的,是”20 次都一样”以及效应大小远超随机方向的范围。

8. 文本上的 IG · Attribution for text

8.1 Tokens are not pixels

Spring 2022 的讲座和 Lab 3 讨论过一个基本问题:梯度要求输入是连续的。图像的整数像素可以当作实数(42 → 42.0);可 token 是离散的编号,“把 good 调大 0.01”没有意义。解决办法是对词向量(embedding)求梯度:IG 从基线词向量积分到输入词向量,得到每个 token 的每个维度一个归因,再对维度求和得到这个 token 的归因。Lab 3 列出了这样做的代价:梯度传不到词向量层之前的任何东西(比如生成词向量的网络、tokenizer 的选择)。

基线怎么选?IG 论文用全零词向量,理由是训练会让不重要的词的词向量范数变小,所以”全零”近似”没有任何词”;论文也承认它不对应任何真实输入(和全黑图不同)。在 PyTorch 里,nn.Embedding(..., padding_idx=0) 的 [PAD] 行固定为零,所以”整句 [PAD]“和”全零词向量”是同一个基线。

8.2 A small review world with a spurious token

代码 05 造了一个小影评世界:每条影评 6–10 个词,含一个情感词(good / great / … 或 bad / boring / …),10% 的情感词前面有 not(情感反转);训练标签有 20% 是噪声;来自某个网站的影评带一个来源标记 “imdb”——训练数据里正面影评 50% 带它,负面只有 5%。模型是一个 Kim(2014)风格的小 CNN(词向量 8 维 → 宽度 2 的卷积 → max-over-time → logit),IG 论文的问题分类实验用的就是这种结构。

test setaccuracy vs true sentiment
same pipeline(imdb 与标签相关)0.961
no imdb tokens0.972
every review negated0.770

只看准确率,一切正常(否定句弱一些:训练里只有 10% 带 not)。单条影评的 IG(基线 = 全零,logit 0.02;completeness 误差中位数 0.0057):

logit +3.26 | quite(-0.02) was(-0.39) imdb(+3.98) very(+0.17) excellent(-0.84) was(+0.33)
logit -1.39 | quite(+0.12) not(-1.78) loved(-0.50) plot(-0.07) a(-0.07) really(+0.89)
logit -1.53 | film(+0.16) is(+0.07) is(+0.16) boring(-2.16) a(-0.15) acting(+0.08) really(+0.28)

第一句是正面影评,几乎全部证据来自 “imdb”,情感词 “excellent” 反而是负的——第一个危险信号。

Baselines for text(代码 05 演示 2):换成 “the the the …”(一个真实但无意义的句子,F(x′)=−0.15F(x') = -0.15),“the” 的归因全部变成 0(盲点),token 排名与全零基线的秩相关只有 0.692;例句里 −0.84 从 “excellent” 挪到了相邻的 “very” 上——宽度为 2 的卷积让相邻两个词发生交互,交互的功劳怎么分,取决于从哪里出发。换成词表平均词向量(F(x′)=0.03F(x') = 0.03),秩相关 0.960。稳健的结论(“imdb” 约 +4,是全句最大的证据)在三个基线下都成立;细节不稳定。

8.3 The global view: an attribution dictionary

Single-example attributions are easy to wave away. Code 05, demo 3 aggregates IG by token type over 1000 same-pipeline test reviews:

tokenmean |IG|mean IGcount
imdb3.766+3.766247
awful2.469−2.450116
poor2.356−2.329101
bad2.185−2.11294
…
good1.082+1.02885
great0.773+0.767113
excellent0.592−0.016122
… fillers (is, a, acting)≈ 0.10≈ 0400+

The most important token for this sentiment model is not a sentiment word: it is the source tag. The IG paper found exactly this kind of thing in a question-classification model: the name “charles” had become a trigger for yes/no questions. The second finding is subtler: negative words get 2.06–2.47, positive words only 0.59–1.08, and “excellent” averages −0.016. The model barely reads positive words; its notion of “positive” looks like “no negative word (plus imdb)”.

8.4 Did the model understand the question?

Mudrakarta, Taly, Sundararajan & Dhamdhere(ACL 2018)用 IG 分析了图像、表格、文本上的问答模型。Fall 2023 讲座的例子是一个视觉问答(VQA)模型(Kazemi & Elqursh 2017,验证集准确率 61.1%):问 “How symmetric are the white bricks on either side of the building?”,答 “very”(正确)。可是把问题改成 “how asymmetric are …”、“how soon are the bricks fading …”、甚至 “how fast are the bricks speaking …”,答案仍然是 “very”。归因解释了原因:“symmetrical” 这个词的归因很小——归因小,预示着模型对这个词的扰动不敏感。论文的几个数字:

  • Overstability:把问题里除了 “color” 以外的词全部删掉,模型仍能达到原准确率的 50% 以上;问题完全为空时还有 44.3%。归因最高的前 6 个词是 “color”、“many”、“what”、“is”、“there”、“how”——模型主要用它们判断答案类型,然后看图。
  • Subject ablation:把问题主语换成一个归因一直很低的名词,原本答对的问题里 75.6% 答案不变。
  • Prefix attack:用模型认为重要的通用词拼出不改变问题含义的前缀(如 “in not a lot of words”),三种前缀合起来把准确率从 61.1% 降到 19%;用模型认为不重要的词拼的前缀(如 “tell me”)只降到 46.9%。

代码 05 演示 4 在小影评模型上做同样的检验:

testresult
(a) 每条影评只保留 2 个词,预测不变的比例按 |IG| 选:0.987;随机选:0.652
(b) 530 条负面影评被判为负面的比例原句 1.000;插入 “imdb” 后 0.043;插入 “plot” 后 1.000
(c) 400 条带 not 的影评not 的 |IG| 占整句中位数 0.460;去掉 not 后 76.7% 的预测反转
(d) 把情感词换成 “plot”正面仍判正面 0.972 → 0.833;负面仍判负面 1.000 → 0.204

(a) 是 overstability:归因说其余的词几乎没用,扰动证实了。(b) 是 prefix attack 的翻版:一个”看起来无害、但模型认为重要”的 token 把 95.7% 的负面影评翻成了正面,而同样无害、模型不在乎的 “plot” 毫无作用。(c) 是一个正面的确认:模型确实(部分地)用 not 做否定。(d) 是 “symmetrical” 的翻版:正面判断基本不依赖正面词,和 §8.3 的词典吻合。准确率 0.96 的模型,可能”对得没有道理”——Mudrakarta et al. 的结论正是:归因可以补充准确率,揭示测试数据本身的弱点。

8.5 Toward LLMs

Fall 2023 讲座最后把这些方法搬到 LLM 上:对开源模型(如 BLOOM),可以做 IG 风格的梯度解释;对闭源模型(GPT-4、PaLM 2、Claude 等)拿不到梯度,只能用扰动。讲座的例子:问 BLOOM “Where did fortune cookies originate?”(可接受的答案是旧金山),它编了一个名叫 “Charles Cook” 的人在美国发明的故事;归因显示 “United States” 和 “invented” 绑在一起,“Cook” 这个姓和 “cookie” 绑在一起。讲座的解读是:模型其实”知道”这个事实,只是前面生成的风格先把它带向了”发明者 / 美国”的说法。对拿不到梯度的模型,讲座介绍了 what-if exploration:在一个有偏序的扰动空间里(比如”只把 he 换成 she”比”he 和 him 都换”更简单),系统地寻找能改变预测的最小扰动(“Local Explanations via Necessity and Sufficiency: Unifying Theory and Practice”,UAI 2021)。一个搜索团队用它调试点击率模型:对查询做 token 删除的 what-if,发现罪魁是词表外(OOV)的 token(如 “water filter ph8” 里的 “ph8”);调高词表的频率阈值、重新训练后问题消失。第 11–12 讲会看到,“回答的哪一部分由检索到的哪一段支持”(groundedness)本质上也是一个归因问题。


9. 局限与注意事项 · Limits and caveats

  • Attributions explain the model, not the world. Model S’s attribution on the watermark is correct — it faithfully reports a bad model. Two equally accurate models can have quite different attributions (rank correlation 0.50–0.65 in §6.4). Never read an attribution as a statement about which features “cause” the label in reality (Lecture 2’s “explanations are not causal” applies here too).
  • Attributions are shallow. They say which inputs mattered for this output relative to this baseline. They do not say how the network combined them, which training examples taught it (Lecture 4), or what it would do on other inputs. They are most useful when a strict subset of inputs matters — a watermark, a source tag, a single question word.
  • Every number has a hidden choice. The baseline (§5), the quantity of interest (logit vs probability, §2.1), the number of steps (§3.4), the fill value of a deletion test (§6.2), the replacement value of an ablation (§7.4), the unit of analysis (§7.4). Report them; check that conclusions survive changing them.
  • Attributions are fragile and can be attacked. Ghorbani, Abid & Zou (2019) showed that small, carefully chosen input perturbations can change saliency and IG maps dramatically while leaving the prediction unchanged; Dombrowski et al. (2019) showed that explanations can be manipulated to look like an arbitrary target map; Kindermans et al. (2019) showed that some methods change under a constant shift of the input that the model itself ignores. And a model can be built to hide its behavior from LIME and SHAP (Slack et al. 2020). Lecture 8 returns to this: an explanation is only as trustworthy as its robustness.
  • Humans are part of the method. Visualization choices change what people see; people see what they expect (confirmation bias). The value of attribution in the debugging workflow comes from people with domain knowledge asking “would this be available at deployment?”.

10. 小结 · Summary

方法问的问题满足不满足 / 陷阱本讲的数字
Saliency |∇F|动一点会怎样(敏感度)implementation invariancesensitivity(饱和);不是贡献mark share 0.078;sanity check 0.081
Gradient × input(= LRP-0)局部线性近似下的贡献implementation invariancecompleteness、sensitivity(饱和)(0, 0) on min(2x₁+3x₂, 1);Σ 与 ΔF 符号都可能相反
Guided backprop / DeconvNet“更好看”的反传—sensitivity;对模型不敏感x₂ 得 0
DeepLIFT(Rescale)离散梯度反传completeness、sensitivityimplementation invariance(1.5, −0.5) vs (2, −1)
Integrated Gradients从基线到 x 的路径积分全部六条公理(唯一的对称 path method)依赖基线;mm 次梯度(4/7, 3/7);mark share 0.350;账目 4.89 vs 实际 4.82
SmoothGrad平滑后的敏感度稳定不完整;σ 的选择mark share 0.091
Conductance / distributional influence内部单元的影响逐层 completeness(conductance)分析单位的选择;消融的替换值5.754 vs 5.760;clean 0.766 → 0.887
TCAV / ACE概念方向的敏感度不需要概念出现在输入里单个分数无意义,需要随机对照S: 1.000 / +2.5;随机 0.04–1.00

Six takeaways:

  1. Gradients are cheap but local. One backward pass gives all nn sensitivities, but a gradient at xx cannot see what happened before the function saturated.
  2. IG = gradients + a path + a baseline. Integrating along the straight line restores sensitivity and gives completeness, while keeping implementation invariance; it is the Aumann–Shapley method, a sibling of the Shapley value.
  3. Completeness makes attributions auditable: check it to choose the number of steps, and read attributions as an account (“the watermark is worth 4.89 logits”) that can be compared with interventions.
  4. The baseline is the question. It decides what “absence” means, creates blind spots, and can quietly bias evaluations.
  5. Evaluate attributions with care: deletion depends on the fill, sanity checks test sensitivity to the model rather than correctness, and agreement with human intuition can penalize the most faithful attribution.
  6. Look inside and across many inputs. Internal influence localizes a shortcut (with the right unit of analysis), concepts test directions instead of pixels, and aggregated attributions over hundreds of inputs expose patterns — a watermark, a source tag, an ignored question word — that single examples hide.

11. 常见误区 · Common pitfalls

  • “The gradient of this pixel is zero, so the pixel doesn’t matter.” The function may have saturated (§2.3). Use a path method.
  • “Saliency and IG disagree, so one of them is buggy.” They answer different questions: sensitivity vs contribution relative to a baseline (§2.2).
  • “IG with 20 steps is standard, so my attributions are accurate.” Check completeness on your model; ReLU networks converge slowly (§3.4), and check absolute error when F(x)≈F(x′)F(x) \approx F(x').
  • “The black image is a neutral baseline.” Its score is not zero, and any pixel equal to the baseline is invisible (§5). Try more than one baseline.
  • “This method wins the deletion benchmark, so it is the most faithful.” The winner can change with the fill value, and methods whose baseline matches the fill have a built-in advantage (§6.2, §6.5).
  • “The attribution highlights the object, so the model reasons correctly.” Maps that multiply by the input can look like the object even for a random model (§6.4); a model with a shortcut can highlight the object and the shortcut (§4.1).
  • “The attribution highlights the watermark, so the attribution method is wrong.” It may be faithfully reporting a model that uses the watermark. Faithfulness to the model is the goal (§6.1).
  • “I found the neuron for X; switching it off removes X.” Units can do several jobs at once, and “switching off” means replacing with some value that may itself be unnatural (§7.4).
  • “TCAV = 1.0, so the concept matters.” Compare against many random concepts and look at effect size (§7.6).

12. 练习 · Exercises

练习 1(HW2 书面题 13:饱和与 IG). F(x1,x2)=min⁡(2x1+3x2, 1)F(x_1, x_2) = \min(2x_1 + 3x_2,\ 1),基线 (0,0)(0, 0),输入 (2,1)(2, 1)。(a) 手算 IG。(b) 计算以基线为”缺席”值的 Shapley 值。(c) 把输入换成 (0.1,0.1)(0.1, 0.1),两种方法的结果还不同吗?为什么?

参考答案

(a) 路径 γ(α)=(2α,α)\gamma(\alpha) = (2\alpha, \alpha),2x1+3x2=7α2x_1 + 3x_2 = 7\alpha,在 α<1/7\alpha < 1/7 时梯度为 (2,3)(2, 3),之后为 0。IG1=2∫01/72 dα=4/7\mathrm{IG}_1 = 2\int_0^{1/7} 2\,d\alpha = 4/7,IG2=1∫01/73 dα=3/7\mathrm{IG}_2 = 1\int_0^{1/7} 3\,d\alpha = 3/7,合计 1。(b) v(∅)=0v(\emptyset) = 0,v({1})=F(2,0)=1v(\{1\}) = F(2, 0) = 1,v({2})=F(0,1)=1v(\{2\}) = F(0, 1) = 1,v({1,2})=1v(\{1, 2\}) = 1,Shapley 值 = 每个特征在两种顺序下边际贡献的平均 = (1+0)/2=0.5(1 + 0)/2 = 0.5 各一半。(c) 2(0.1)+3(0.1)=0.5<12(0.1) + 3(0.1) = 0.5 < 1,整条路径和所有阶梯路径都在线性区,FF 在相关区域是线性的:IG = Shapley = (0.2,0.3)(0.2, 0.3)。两种方法只在非线性(饱和、min / max、交互)处分歧——它们对线性函数都给出 wi(xi−xi′)w_i(x_i - x'_i)。

练习 2(HW2 书面题 14–16:线性模型). 对 CC 类的线性模型 f(x)=Wx+bf(x) = Wx + b,写出第 cc 类分数 fcf_c 的 (a) saliency(不取绝对值的梯度),(b) 基线 0⃗\vec 0 的 IG,(c) gradient × input。(d) completeness 在这里是什么等式?(e) 对线性模型问 influence-directed explanation(内部神经元的影响)有意义吗?

参考答案

(a) ∇xfc=Wc,:\nabla_x f_c = W_{c,:}(第 cc 行),与 xx 无关。(b) 梯度在路径上处处相同,IG=Wc,:⊙x\mathrm{IG} = W_{c,:} \odot x。(c) 同 (b)。(d) ∑iWcixi=fc(x)−fc(0⃗)=fc(x)−bc\sum_i W_{ci}x_i = f_c(x) - f_c(\vec 0) = f_c(x) - b_c:偏置是基线的分数,不分给任何特征。(e) 没有隐藏层,可以切开的”slice”只有输入本身,内部影响退化为输入归因(distributional influence = 平均梯度 = Wc,:W_{c,:})。这也说明了为什么”梯度 = 系数”的直觉在线性模型上完全成立,而深度网络的全部麻烦都来自非线性。

练习 3(公理之间的关系). (a) 证明 completeness 蕴含 Sensitivity(a)。(b) gradient × input 满足 Sensitivity(b) 吗?满足 implementation invariance 吗?(c) DeepLIFT 满足 completeness,为什么还会违反 implementation invariance?用 §3.5 的 gg 网络说明”离散梯度不满足链式法则”。

参考答案

(a) 设 xx 与 x′x' 只在第 ii 个特征上不同,且 F(x)≠F(x′)F(x) \ne F(x')。completeness 给出 ∑jAj=F(x)−F(x′)≠0\sum_j A_j = F(x) - F(x') \ne 0。对 IG(以及任何 path method),xj=xj′x_j = x'_j 的特征沿路径不动,归因为 0(IG 公式里有因子 xj−xj′=0x_j - x'_j = 0);于是 Ai=F(x)−F(x′)≠0A_i = F(x) - F(x') \ne 0,这正是 Sensitivity(a)。(严格地说,completeness 本身只保证”总和不为 0”;“其他特征得 0”来自路径方法的结构,IG 论文 Remark 2 默认了这一点。)

(b) 都满足:若 FF 不依赖 xix_i,则 ∂F/∂xi≡0\partial F/\partial x_i \equiv 0,归因为 0;梯度只依赖函数本身,与实现无关。它违反的是 completeness 和 Sensitivity(a)。

(c) 看 x1x_1 的乘子。网络 gg:h1=ReLU(x1−1)h_1 = \mathrm{ReLU}(x_1 - 1) 在输入处 z=2z = 2、基线处 z′=−1z' = -1,离散梯度 =(2−0)/(2−(−1))=2/3= (2 - 0)/(2 - (-1)) = 2/3;输出 ReLU 的 zz 从 0 变到 1,离散梯度 1;x1x_1 得 3×23×1=23 \times \tfrac23 \times 1 = 2。网络 ff:ReLU(x1)\mathrm{ReLU}(x_1) 从 0 到 3,离散梯度 1;输出 ReLU 的 zz 从 −1-1 变到 1、输出从 0 变到 1,离散梯度 1/21/2;x1x_1 得 3×1×12=1.53 \times 1 \times \tfrac12 = 1.5。同一个函数,“偏置 −1 放在哪一层”改变了中间量在基线处的取值,于是每一段的离散梯度是在不同的区间上算的,乘起来的结果也不同。导数是逐点的,链式法则 ∂f∂g=∂f∂h∂h∂g\frac{\partial f}{\partial g} = \frac{\partial f}{\partial h}\frac{\partial h}{\partial g} 对任何分解都成立,所以只用导数的方法(梯度、IG)不受影响。

练习 4(为什么没有偏置时 IG = gradient × input). 设 FF 是一个没有偏置的 ReLU 网络(线性层 + ReLU,最后一层线性)。(a) 证明 F(αx)=αF(x)F(\alpha x) = \alpha F(x) 对 α>0\alpha > 0 成立。(b) 由此证明 ∇F(αx)=∇F(x)\nabla F(\alpha x) = \nabla F(x),进而基线为 0 时 IG(x)=x⊙∇F(x)\mathrm{IG}(x) = x \odot \nabla F(x)。(c) max-pooling 会破坏这个性质吗?偏置呢?对照代码 01 演示 3 的最后一行和代码 02 演示 4 的 Σ grad×input 一列。

参考答案

(a) ReLU(αz)=α ReLU(z)\mathrm{ReLU}(\alpha z) = \alpha\,\mathrm{ReLU}(z)(α>0\alpha > 0),线性层 W(αa)=αWaW(\alpha a) = \alpha Wa,逐层归纳。(b) 对 F(αx)=αF(x)F(\alpha x) = \alpha F(x) 两边关于 xx 求导:α∇F(αx)=α∇F(x)\alpha\nabla F(\alpha x) = \alpha\nabla F(x)。所以路径上梯度处处相同,积分就是终点的梯度。(c) max-pooling 也是正齐次的(max⁡(αa,αb)=αmax⁡(a,b)\max(\alpha a, \alpha b) = \alpha\max(a, b)),不破坏;偏置破坏它(Wαa+b≠α(Wa+b)W\alpha a + b \ne \alpha(Wa + b))。代码 01 去掉偏置后误差只有 7.7×10−167.7\times10^{-16};代码 02 的 CNN 有偏置,Σ grad×input 与 F(x)−F(0)F(x) - F(0) 可以差很多。

练习 5(deletion 为什么偏爱”基线 = 填充值”). 设 F(x)=w⊤xF(x) = w^\top x(线性),填充值为 bb。(a) 删掉集合 SS 中的像素后,FF 下降多少?(b) 证明:以 bb 为基线的 IG 给出的排序,对任何 kk 都使”删掉前 kk 个之后的 FF“最小。(c) 如果用以 b′≠bb' \ne b 为基线的 IG 排序,(b) 还成立吗?(d) 对非线性的 FF,为什么这个结论只是”偏向”而不是”保证”?

参考答案

(a) F(x)−F(xS←b)=∑i∈Swi(xi−bi)F(x) - F(x_{S \leftarrow b}) = \sum_{i \in S} w_i(x_i - b_i)。(b) 以 bb 为基线时 IGi=wi(xi−bi)\mathrm{IG}_i = w_i(x_i - b_i),正好是删掉 ii 的下降量;按它从大到小删,前 kk 个的下降量之和最大(贪心对可加目标是最优的)。(c) 不一定:以 b′b' 为基线时 IGi=wi(xi−bi′)\mathrm{IG}_i = w_i(x_i - b'_i),与真正的下降量 wi(xi−bi)w_i(x_i - b_i) 排序可以不同。(d) 非线性时删除的效果不可加(交互、饱和),IG 是沿直线的平均斜率,不是”删掉一组像素”的精确效果;但两者共享同一个”缺席 = bb“的假设,所以排名仍然偏向它——代码 03 演示 3b 的对角线就是这个偏向。

练习 6(消融的替换值). 代码 04 演示 3 中,把 16 个”水印单元”替换成 0 时 clean 准确率是 0.767,替换成训练均值时是 0.887。(a) 用”Model S 学到了什么”解释两者的差别。(b) 如果替换成”clean 数据上的平均激活”(clean 里没有水印),你预计更接近哪一个?为什么?(c) 这个问题和 IG 的基线、deletion 的填充值有什么共同点?

参考答案

(a) Model S 学到的是”有水印 → 竖线证据 +4.8”,相应地它的偏置和其他权重被调到”没有水印时偏向横线”(训练数据里没有水印的图 95% 是横线)。替换成 0(或部署时水印消失)让这些单元永远处于”没有水印”的状态,偏向横线的偏差全部暴露;替换成训练均值(约等于”半个水印”)把这部分证据固定成一个常数,恰好抵消了偏差,剩下的短线特征决定分类。(b) 接近替换成 0 的结果:clean 数据上角落单元的平均激活就是”没有水印”的激活。这个预测可以用 README 的”动手改一改”第 5 题验证。(c) 三者都是在问”用什么代表’没有’“。没有中性的答案:每种选择都定义了一个不同的反事实问题,结论必须连同这个选择一起报告。

代码相关的练习(“动手改一改”)见 code/lecture03/README.md。


13. 延伸阅读 · Further reading

本讲的主要来源

  • CS329T Spring 2022 Week 2 “Explanations” slides(Datta & Mitchell)、Lab 3、HW2 Part II;Fall 2023 Lecture 12 “Interpretability” slides(Datta, Mitchell & Taly)。
  • Sundararajan, Taly & Yan, “Axiomatic Attribution for Deep Networks”, ICML 2017(尤其是 §2–§5 和附录 B)。
  • Mudrakarta, Taly, Sundararajan & Dhamdhere, “Did the Model Understand the Question?”, ACL 2018。

梯度类方法与公理

  • Simonyan, Vedaldi & Zisserman, “Deep Inside Convolutional Networks: Visualising Image Classification Models and Saliency Maps”, 2014;Baehrens et al., “How to Explain Individual Classification Decisions”, JMLR 2010。
  • Smilkov et al., “SmoothGrad: Removing Noise by Adding Noise”, 2017。
  • Shrikumar, Greenside & Kundaje, “Learning Important Features Through Propagating Activation Differences”(DeepLIFT),ICML 2017;Bach et al., “On Pixel-Wise Explanations for Non-Linear Classifier Decisions by Layer-Wise Relevance Propagation”, PLOS ONE 2015。
  • Ancona, Ceolini, Öztireli & Gross, “Towards Better Understanding of Gradient-Based Attribution Methods for Deep Neural Networks”, ICLR 2018。
  • Friedman, “Paths and Consistency in Additive Cost Sharing”, International Journal of Game Theory 2004;Aumann & Shapley, Values of Non-Atomic Games, 1974。
  • Sturmfels, Lundberg & Lee, “Visualizing the Impact of Feature Attribution Baselines”, Distill 2020。

评估

  • Adebayo et al., “Sanity Checks for Saliency Maps”, NeurIPS 2018。
  • Wang, Mardziel, Datta & Fredrikson, “Interpreting Interpretations: Organizing Attribution Methods by Criteria”, 2020。
  • Samek et al., “Evaluating the Visualization of What a Deep Neural Network Has Learned”, IEEE TNNLS 2017;Petsiuk, Das & Saenko, “RISE: Randomized Input Sampling for Explanation of Black-box Models”, BMVC 2018;Hooker, Erhan, Kindermans & Kim, “A Benchmark for Interpretability Methods in Deep Neural Networks”(ROAR),NeurIPS 2019。

内部影响与概念

  • Leino, Sen, Datta, Fredrikson & Li, “Influence-Directed Explanations for Deep Convolutional Networks”, International Test Conference 2018。
  • Dhamdhere, Sundararajan & Yan, “How Important Is a Neuron?”, ICLR 2019。
  • Lu, Mardziel, Leino, Fredrikson & Datta, “Influence Paths for Characterizing Subject-Verb Number Agreement in LSTM Language Models”, ACL 2020;Lu, Wang, Mardziel & Datta, “Influence Patterns for Explaining Information Flow in BERT”, NeurIPS 2021。
  • Kim et al., “Interpretability Beyond Feature Attribution: Quantitative Testing with Concept Activation Vectors (TCAV)”, ICML 2018;Ghorbani, Wexler, Zou & Kim, “Towards Automatic Concept-based Explanations”, NeurIPS 2019。

脆弱性(第 8 讲的预告)

  • Ghorbani, Abid & Zou, “Interpretation of Neural Networks Is Fragile”, AAAI 2019;Dombrowski et al., “Explanations Can Be Manipulated and Geometry Is to Blame”, NeurIPS 2019;Kindermans et al., “The (Un)reliability of Saliency Methods”, 2019。

14. 下一讲预告 · Next lecture

Lecture 4:训练数据归因(Training-Data Attribution)。

Fall 2023 讲座列出了四种”解释的对象”:输入特征、神经元激活、训练样本、训练阶段。本讲讲了前两种。可是当 Model S 依赖水印时,更根本的问题是:它是从哪些训练样本里学会的? 第 4 讲把归因的对象换成训练数据:留一法(leave-one-out)的定义与代价,influence functions(Koh & Liang 2017)用一阶近似和 Hessian 逆向量积估计”去掉一个训练样本会怎样”,TracIn 沿训练轨迹累积梯度内积,以及 Fall 2023 第 11 讲(Juhan Bae、Cem Anil)介绍的 LLM 上的 influence functions。你会看到,本讲反复出现的那个问题——“和什么比?“——在那里变成了”和没有这个样本的模型比”。

← 返回课程目录