PixelCNN:模型究竟可以看哪些像素
PixelCNN
构造掩码图像分布,逐位检查因果依赖,找出加深网络也补不上的盲区。
pixelcnn把目标像素遮住,网络还会不会抄答案
拿一张2×3的二值教学图,按从左到右、从上到下的顺序生成。预测第二行中间像素时,第一行已经全部生成,第二行左边也已生成。当前像素和右边像素尚未出现。普通卷积会读取周围位置,很容易把目标本身或未来答案送进预测器。
PixelCNN用卷积权重上的掩码限制信息流,让每个输出只依赖顺序中的较早像素。训练时可以一次提供整张图,因为网络内部负责阻断不允许的连接;生成时却需要把前一步抽出的像素送回去。Pixel Recurrent Neural Networks的第3.4—3.5节同时介绍掩码和其中的PixelCNN架构,论文题名并不意味着它只包含循环网络。
先掌握卷积、自回归模型和二元交叉熵。本题从二值图的完整概率模型开始,再区分RGB通道、门控双栈与PixelCNN++。
顺序决定条件,掩码决定能否遵守
把图像展开成个变量。二值版本为每个像素产生一个logit ,经sigmoid变成取1的条件概率:
若每个只依赖,联合就归一化:先对最后一个像素的两个值求和,它的条件概率之和为1;再对倒数第二个求和,逐步消去所有因子。若预测器看到了自己的目标,即使每个输出都是sigmoid,乘起来也不一定是合法联合分布。
真实彩色图还有同一位置的通道顺序。原论文的RGB掩码按R、G、B依次条件化:
因此,预测G时可以看当前位置的R,预测B时可以看R和G。不能把二值例子的“首层中心为零”不加区别地推广到所有RGB通道连接;需要按输入和输出的通道组施加限制。原架构对每个颜色给256类softmax,二值版本才用sigmoid。
A层阻断目标,B层复用合法特征
下面是单个二值通道的3×3掩码,中心对准当前待预测位置。1表示允许连接:
A用于第一层,不能读取当前输入。B用于后续隐藏层,可以读取同位隐藏特征,因为第一层已经确保该特征不包含当前或未来目标。两层网络的例子为:
表示这里实现的卷积式互相关,表示把空间掩码广播到通道权重。输入0、1先映射到−1、+1,补边设0,使补边不同于两个合法像素值。代码使用两通道隐藏层与逐位置输出头;原论文则用7×7首层、更多3×3层及其他架构设置,Table 1可用于对照。
损失与梯度都要遵守掩码
设为非负图像权重,和为1;普通数据均值可取。负对数似然和logit导数为:
softplus是,代码用logaddexp避免直接指数溢出。给定某层输出导数、输入特征,卷积权重导数为输入与导数的乘积累加,再乘掩码:
这里为相对空间偏移,为输入/输出通道,越界输入按补边处理。被掩掉的权重对输出无影响,其梯度也必须为0。仅在显示图形上画一个遮罩、计算中仍使用原权重,不会阻断信息泄漏。
二值图有个标量。将每图nats转成每像素bits时:
对RGB评价还必须说明分母是像素数还是标量通道数,不能看到“bits”就把不同归一化成绩放在一起。
为什么增加深度仍有盲区
在一张5×5图上考察位置,坐标从0开始。它的过去包括,但3×3 A/B堆叠无法把这个位置的信息传过来。反向追踪路径时,每向上走一行最多向右走一列;同一行只能向左或停留。从到要求仅上移一行却右移三列,因而不可达。加深可以扩大其他区域,却补不上这一处盲区。
Conditional PixelCNN第2.1—2.2节用门控激活及垂直/水平双栈处理这些限制。门控单元形式为:
垂直栈读取上方行,水平栈读取当前行左侧,并接收垂直栈的信息。方向不能随意反转:把水平栈反馈给垂直栈可能让未来位置的信息回流。有效感受野仍受具体深度和卷积范围限制;“去掉这一几何盲区”不等于有限网络自动看到整幅大图。本文代码只实现基本A/B掩码,不把门控或双栈画出来就算已经实现。
枚举全部图像,检查概率和泄漏
六个二值像素共有64种图像,足够全部枚举。我们定义一个原创合成目标:当前像素的logit取左邻与上邻中心化值的加权和。不存在的邻居贡献0:
这样可以直接计算64种图像的真实概率,将它们作为训练权重,而不依赖抽样数据集。保存下面程序为pixelcnn.py,在Python 3.12与NumPy 1.26.4下运行,无数据或模型下载。
"""Original two-layer binary PixelCNN: 2x3 images, 61 stored parameters, exact population training."""
import itertools
import json
import numpy as np
MASK_A = np.array([[1, 1, 1], [1, 0, 0], [0, 0, 0]], float)
MASK_B = MASK_A.copy(); MASK_B[1, 1] = 1
IMAGES = np.array(list(itertools.product([0., 1.], repeat=6))).reshape(64, 2, 3)
def sigmoid(x):
return np.exp(-np.logaddexp(0, -np.asarray(x, float)))
def unpack(p):
p = np.asarray(p, float)
if p.shape != (61,) or not np.isfinite(p).all() or np.max(abs(p)) > 20:
raise ValueError('Expected 61 finite parameters with absolute value <= 20.')
return p[:18].reshape(3, 3, 1, 2), p[18:20], p[20:56].reshape(3, 3, 2, 2), p[56:58], p[58:60], p[60]
def patches(x):
n, h, w, c = x.shape
pad = np.pad(x, ((0, 0), (1, 1), (1, 1), (0, 0)))
return np.stack([pad[:, i:i+h, j:j+w] for i in range(3) for j in range(3)], axis=3).reshape(n, h, w, 3, 3, c)
def convolution(x, weight, bias, mask):
patch = patches(x)
return np.einsum('nxyijc,ijco->nxyo', patch, weight*mask[:, :, None, None])+bias, patch
def backward(delta, patch, weight, mask):
n, h, w = delta.shape[:3]; c = weight.shape[2]
dw = np.einsum('nxyijc,nxyo->ijco', patch, delta)*mask[:, :, None, None]
dp = np.zeros((n, h+2, w+2, c))
for i in range(3):
for j in range(3):
dp[:, i:i+h, j:j+w] += np.einsum('nxyo,co->nxyc', delta, weight[i, j]*mask[i, j])
return dp[:, 1:-1, 1:-1], dw, delta.sum(axis=(0, 1, 2))
def forward(p, x=IMAGES):
x = np.asarray(x, float)
if (x.ndim != 3 or x.shape[1:] != (2, 3) or not 1 <= len(x) <= 256
or not np.isin(x, [0, 1]).all()):
raise ValueError('Expected 1..256 binary images of shape (2,3).')
wa, ba, wb, bb, wo, bo = unpack(p)
first, pa = convolution((2*x-1)[..., None], wa, ba, MASK_A)
h1 = np.tanh(first)
second, pb = convolution(h1, wb, bb, MASK_B)
h2 = np.tanh(second)
return h2 @ wo + bo, (h1, h2, pa, pb)
def objective(p, x=IMAGES, weights=None):
logits, (h1, h2, pa, pb) = forward(p, x)
x = np.asarray(x, float)
if weights is None:
weights = np.ones(len(x))/len(x)
weights = np.asarray(weights, float)
if (weights.shape != (len(x),) or not np.isfinite(weights).all()
or (weights < 0).any() or not np.isclose(weights.sum(), 1, rtol=0, atol=1e-12)):
raise ValueError('Expected nonnegative normalized image weights.')
per_image = (np.logaddexp(0, logits)-x*logits).sum(axis=(1, 2))
delta = (sigmoid(logits)-x)*weights[:, None, None]
wa, ba, wb, bb, wo, bo = unpack(p)
dwo, dbo = np.einsum('nxy,nxyc->c', delta, h2), delta.sum()
dh1, dwb, dbb = backward(delta[..., None]*wo*(1-h2*h2), pb, wb, MASK_B)
_, dwa, dba = backward(dh1*(1-h1*h1), pa, wa, MASK_A)
grad = np.concatenate((dwa.ravel(), dba, dwb.ravel(), dbb, dwo, [dbo]))
return float(weights @ per_image), grad
def density(p):
logits, _ = forward(p)
return np.exp(-(np.logaddexp(0, logits)-IMAGES*logits).sum(axis=(1, 2)))
def target_density():
logits = np.zeros_like(IMAGES)
logits[:, :, 1:] += 2*(2*IMAGES[:, :, :-1]-1)
logits[:, 1:, :] += .8*(2*IMAGES[:, :-1, :]-1)
return np.exp(-(np.logaddexp(0, logits)-IMAGES*logits).sum(axis=(1, 2)))
def initial():
return np.random.default_rng(12).normal(0, .15, 61)
def fit(steps=400, rate=.1):
if isinstance(steps, bool) or not isinstance(steps, int) or not 0 <= steps <= 2000 or not 0 < rate <= .2:
raise ValueError('Use 0..2000 integer steps and rate in (0,.2].')
p = initial(); weights = target_density(); history = [objective(p, weights=weights)[0]]
for i in range(steps):
_, grad = objective(p, weights=weights)
p -= rate*grad
if (i+1) % 100 == 0 or i+1 == steps:
history.append(objective(p, weights=weights)[0])
return p, history
def sample(p, count=8, seed=12):
if isinstance(count, bool) or not isinstance(count, int) or not 1 <= count <= 256:
raise ValueError('Sample count must be an integer in 1..256.')
rng = np.random.default_rng(seed); x = np.zeros((count, 2, 3))
for i in range(6):
row, col = divmod(i, 3)
logits, _ = forward(p, x)
x[:, row, col] = rng.random(count) < sigmoid(logits[:, row, col])
return x.astype(int)
def receptive(depth=2, location=(4, 1), shape=(5, 5)):
"""Backward reachability: B hidden layers followed by one A input layer."""
if isinstance(depth, bool) or not isinstance(depth, int) or not 1 <= depth <= 20:
raise ValueError('Depth must be an integer in 1..20.')
if (len(shape) != 2 or len(location) != 2 or
any(not isinstance(v, int) for v in (*shape, *location)) or
not all(1 <= v <= 20 for v in shape) or
not all(0 <= location[k] < shape[k] for k in range(2))):
raise ValueError('Use a valid location within a grid of at most 20x20.')
nodes = {location}
for layer in range(depth):
mask = MASK_A if layer == depth-1 else MASK_B
nodes = {(r+u-1, c+v-1) for r, c in nodes for u, v in np.argwhere(mask)
if 0 <= r+u-1 < shape[0] and 0 <= c+v-1 < shape[1]}
return sorted((int(r), int(c)) for r, c in nodes)
def demo():
p, history = fit(); weights = target_density()
return dict(nats_per_image=history, bits_per_pixel=[v/(6*np.log(2)) for v in history],
target_entropy_nats=float(-weights @ np.log(weights)), mass=float(density(p).sum()),
samples=sample(p).tolist(), reachable_depth_8=receptive(8),
setting='Binary 2x3 synthetic population; basic A/B masks, no RGB, gates, dual stacks or PixelCNN++.')
if __name__ == '__main__':
print(json.dumps(demo(), indent=2, allow_nan=False))
网络存储61个标量:首层18权重和2偏置,第二层36权重和2偏置,输出头2权重和1偏置。掩码使26个权重槽无效,剩35个有效标量。训练400步、学习率0.1,精确目标交叉熵从4.185528降到2.718718 nats/image,即最后约0.653713 bits/pixel。目标分布的熵是2.710494,仍低于模型交叉熵;没有把尚存的差距说成完美拟合。
最终64图概率之和在浮点精度内为1。检查不只看这个总和:还对所有图像逐位翻转输入,核对当前及更早输出完全不变;对61个参数逐一有限差分;独立标量卷积核对向量化计算;故意把首层换成B时则能构造泄漏反例。采样使用种子12,按六个位置依次计算概率和抽值。
若一层输入输出通道为,核边长、像素数、batch大小,朴素卷积成本为。这里显式存patch,占空间。深度为时累计各层成本。简单祖先采样每个像素重跑全网,需要次前向;训练时单次前向却能评估所有位置。缓存可减少重复计算,但不消除顺序依赖。
概率精确,不代表生成速度或样本质量都理想
PixelCNN可以逐条件精确计算已给图像的离散概率,但采样有顺序成本,局部结构也限制依赖范围。更低NLL评价的是所定义的离散图像分布,不保证人的视觉偏好同步改善。这里的二值小图没有自然图像纹理,更不能拿0.653713与彩色图像论文指标直接比较。
OpenAI的固定PixelCNN++源码展示位移卷积和双路结构;它是后续变体,不是2016基本PixelCNN的同一实现。核读的model.py第1—63行、关联nn.py位移函数和README开头支持这一架构对照;本题没有复现它的完整密度输出、训练或性能。选择哪种路线,要结合观测建模、依赖范围和实际采样预算,而不只看仓库名称。
用反例测试自己的掩码理解
- 为什么第一层不能对当前二值输入用B掩码,而第二层可以对同位隐藏特征用B?
答案:第一层的当前输入就是答案,B的中心连接会直接读取它。第二层的同位特征已由A层排除当前/未来输入,只汇总较早信息,因此中心连接安全。前提必须通过整个网络的信息路径检查。
- 全部参数为0时,每张2×3二值图的概率、每图NLL与bits/pixel分别是多少?
答案:每个条件概率为1/2,联合为,NLL为,bits/pixel为1。64个相等概率之和为1,可作为归一化和单位检查。
- 预测时,在生成顺序上是否已经可用?为什么20层3×3 A/B网络仍可能看不到它?
答案:上一行已全部生成,所以它属于过去。反向路径只上移一行时最多向右一列,无法到达右侧三列处;增加只允许向上/左的层也无法先上移再返回,因而该点不可达。
- 在RGB版本中,预测当前G值时是否应屏蔽当前R值?若把二值掩码直接复制到所有通道会怎样?
答案:按R→G→B的顺序,R已经生成,可以作为G的条件。把二值空间中心禁令复制到全部通道会过度屏蔽合法条件,降低模型可用信息;反过来无条件放开全部当前通道则可能读取G或B答案。必须按通道顺序细分。
从基本掩码到门控与后续实现
van den Oord、Kalchbrenner与Kavukcuoglu的2016论文包含PixelRNN及PixelCNN,第3.4—3.5节与Table 1是本题基本掩码的来源。Conditional Image Generation with PixelCNN Decoders首投2016-06-16,本题所读v2为2016-06-18,核读门控与盲区部分。
PixelCNN++仓库固定于2020-01-28提交bbc1568。许可证开头声明MIT与Apache 2.0;本次只核读前27行,架构材料仅供链接比较,没有复制源码或执行上游训练。论文的图像基准与仓库README的性能自述都没有被写成本项目复现。
后续可沿生成模型比较似然与采样的不同任务,或在目录中继续VAE,观察潜变量如何改变生成模型的计算结构。
先判断,再看解释
B型隐藏层可以安全读取同一空间位置吗?
学习目标
- 解释空间掩码与RGB通道掩码。
- 推导掩码卷积梯度与归一化。
- 测量精确似然并检查答案泄漏。
- 区分普通、门控及PixelCNN++架构。
先修与延伸
查看知识关联图 →参考文献
- Pixel Recurrent Neural Networks: masked convolutions and PixelCNN
Aäron van den Oord; Nal Kalchbrenner; Koray Kavukcuoglu · 2016 - Conditional Image Generation with PixelCNN Decoders (v2): gates and blind spot
Aäron van den Oord; Nal Kalchbrenner; Oriol Vinyals; Lasse Espeholt; Alex Graves; Koray Kavukcuoglu · 2016 - PixelCNN++ author implementation: shifted stacks at bbc1568
OpenAI and PixelCNN++ contributors · 2020
版本1 · 编写状态: 已完成记录中的技术复核
查看技术检查记录(AI)
Codex · 2026-09-13 · Single AI author checked scoped PixelRNN2016 masks, Conditional PixelCNN v2 gates/blind spots and fixed PixelCNN++ stack code. Nine paired equations and four explained exercises; original binary two-layer model, all61 stored gradients,64-state normalization and causal flips. Not RGB, gated or PixelCNN++ replication.
- 核验61存储梯度含26被掩槽、独立标量卷积、64状态目标/模型归一化、穷举逐位因果翻转、400步总体训练及从(4,1)看不到(3,4)的盲区。
- 每题四张计算SVG绑定真实双语MDX;四题组15项数值/几何和24组语言/宽度及四字体检查通过,实际查看8张代表截图。VAE标题draw改estimate,原图保留、数据不变。冻结前检查普通正文AST;完整文章页面验收另记,不称独立人工审校。
核对的来源位置:
- Pixel Recurrent Neural Networks: masked convolutions and PixelCNN · Read Sections3.4–3.5 and Table1 architecture vicinity; inspected PDF page4. Scope includes RGB mask distinctions and parallel evaluation/sequential generation; no image benchmark replication.
- Conditional Image Generation with PixelCNN Decoders (v2): gates and blind spot · Read Section2 factorization and2.1–2.2 gates/dual stacks; inspected PDF page3. First2016-06-16, v2 dated2016-06-18. No full conditional experiments or model replication.
- PixelCNN++ author implementation: shifted stacks at bbc1568 · Read model.py lines1–63, nn.py lines300–329 and README opening. Commit2020-01-28. LICENSE opening declares both MIT and Apache2.0; only its first27 lines reviewed. Comparison only, no copying or upstream execution.
相关主题