AI Wiki中文/EN

PixelCNN: which pixels may the model see?

PixelCNN

Build a masked image distribution, check every causal dependency and locate a blind spot.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

Can the network still copy a hidden target?

Take a 2×3 binary teaching image and generate it left to right, top to bottom. When predicting the middle pixel of the second row, the whole first row and the second row’s left pixel already exist. The current and right pixels do not. An ordinary convolution reads nearby positions and can easily feed the target or a future answer into its predictor.

PixelCNN masks convolution weights to restrict each output to earlier pixels in the chosen order. Training can provide the whole image at once because the network blocks forbidden connections internally. Generation must feed sampled pixels back into later predictions. Sections 3.4–3.5 of Pixel Recurrent Neural Networks describe both masking and the PixelCNN architecture; the paper’s title does not mean it contains only recurrent networks.

The prerequisites are convolution, autoregressive models and binary cross-entropy. We start with a complete binary-image probability model, then distinguish RGB channels, gated dual stacks and PixelCNN++.

Computed masks, reachable pixels, training losses and exact image probabilities reveal the difference between past and visible inputs.
Computed masks, reachable pixels, training losses and exact image probabilities reveal the difference between past and visible inputs.

The order defines the condition; the mask enforces it

Flatten the image into DD variables. A binary model emits a logit lil_i for each pixel, with sigmoid giving its conditional probability of one:

pθ(x)=∏i=1Dpθ(xi∣x<i),pθ(xi=1∣x<i)=σ(li).p_\theta(x)=\prod_{i=1}^{D}p_\theta(x_i\mid x_{<i}),\qquad p_\theta(x_i=1\mid x_{<i})=\sigma(l_i).

If every lil_i depends only on x<ix_{<i}, the joint normalizes. Sum over the final pixel’s two values; its conditional sums to one. Repeat for the preceding pixel until all factors disappear. If a predictor sees its own target, multiplying sigmoid-derived scores need not yield a valid joint distribution.

Color images also require an ordering within each spatial location. The original RGB masks condition channels in R, G, B order:

p(Ri,Gi,Bi∣x<i)=p(Ri∣x<i)p(Gi∣x<i,Ri)p(Bi∣x<i,Ri,Gi).p(R_i,G_i,B_i\mid x_{<i})=p(R_i\mid x_{<i})p(G_i\mid x_{<i},R_i)p(B_i\mid x_{<i},R_i,G_i).

Predicting G can therefore use the current R, and predicting B can use R and G. The binary rule that the first-layer center is zero cannot be extended indiscriminately to every RGB channel connection; restrictions depend on input and output channel groups. The original architecture uses a 256-class softmax per color, while the binary version uses sigmoid.

A removes the target; B reuses valid features

These 3×3 masks apply to a single binary channel, with their center aligned to the target. A one permits a connection:

MA=(111100000),MB=(111110000).M_A=\begin{pmatrix}1&1&1\\1&0&0\\0&0&0\end{pmatrix},\qquad M_B=\begin{pmatrix}1&1&1\\1&1&0\\0&0&0\end{pmatrix}.

Use A in the first layer to exclude the current input. Subsequent hidden layers may use B, reading a same-position hidden feature that the first layer has already kept free of the current and future targets. A two-layer example is:

h(1)=tanh⁡((2x−1)∗(WA⊙MA)+bA),h(2)=tanh⁡(h(1)∗(WB⊙MB)+bB),l=h(2)wo+bo.h^{(1)}=\tanh((2x-1)*(W_A\odot M_A)+b_A),\quad h^{(2)}=\tanh(h^{(1)}*(W_B\odot M_B)+b_B),\quad l=h^{(2)}w_o+b_o.

Here ∗* denotes the convolution-style cross-correlation implemented below; ⊙\odot broadcasts spatial masks over channel weights. Binary inputs become −1 and +1, while padding is zero, distinct from either valid pixel value. The code has two hidden channels and a pointwise output head. The original paper instead uses a 7×7 first layer, more 3×3 layers and other architectural choices; see Table 1.

The loss and gradients must respect the mask

Let nonnegative image weights wnw_n sum to one; an ordinary dataset mean uses 1/N1/N. Negative log likelihood and its logit derivative are:

J=∑nwn∑i=1D[softplus⁡(lni)−xnilni],∂J∂lni=wn[σ(lni)−xni].J=\sum_n w_n\sum_{i=1}^{D}[\operatorname{softplus}(l_{ni})-x_{ni}l_{ni}],\qquad \frac{\partial J}{\partial l_{ni}}=w_n[\sigma(l_{ni})-x_{ni}].

Softplus is log⁡(1+el)\log(1+e^l); logaddexp avoids directly overflowing the exponential. For layer-output derivative Δ\Delta and input features XX, each convolution-weight gradient sums products of inputs and output derivatives, then applies the mask:

∂J∂Wuvco=Muv∑n,r,sXn,r+u,s+v,c Δn,r,s,o,∂tanh⁡t∂t=1−tanh⁡2t.\frac{\partial J}{\partial W_{uvco}}=M_{uv}\sum_{n,r,s}X_{n,r+u,s+v,c}\,\Delta_{n,r,s,o},\qquad \frac{\partial\tanh t}{\partial t}=1-\tanh^2t.

Here u,vu,v are relative spatial offsets and c,oc,o input/output channels; out-of-bounds inputs use padding. A masked weight has no effect on output and must have zero gradient. Drawing a visual mask while still using the unmasked weights in computation does not prevent leakage.

Our binary image contains D=6D=6 scalars. Convert nats per image to bits per pixel using:

bpp⁡=NLL⁡imageDlog⁡2,D=6.\operatorname{bpp}=\frac{\operatorname{NLL}_{\rm image}}{D\log2},\qquad D=6.

For RGB evaluations, also specify whether the denominator counts pixels or scalar channels. Metrics labeled in bits can still use incompatible normalizations.

Why depth alone leaves a blind spot

On a 5×5 image, consider location (4,1)(4,1) with zero-based coordinates. Its past includes (3,4)(3,4), but a stack of 3×3 A/B masks cannot transmit that location’s input. Tracing a path backward, moving up one row allows at most one column to the right; within a row, the path can only move left or stay. Reaching (3,4)(3,4) requires moving up one row but right three columns. Additional depth expands other regions without filling this blind spot.

Conditional PixelCNN Sections 2.1–2.2 use gated activations and vertical/horizontal stacks to address these limitations. The gated unit is:

y=tanh⁡(Wf∗x)⊙σ(Wg∗x).y=\tanh(W_f*x)\odot\sigma(W_g*x).

The vertical stack reads rows above. The horizontal stack reads the current row’s earlier positions and receives vertical-stack information. Reversing this direction can let future information return through the vertical stack. Receptive extent still depends on depth and filter size; removing this geometric blind spot does not make a finite network cover an arbitrarily large image. The code below implements basic A/B masks only; describing gates or dual stacks is not implementing them.

Enumerate every image and test probability and leakage

Six binary pixels give 64 images, small enough to enumerate completely. Define an original synthetic target whose current logit is a weighted sum of centered left and upper neighbors; a missing neighbor contributes zero:

P∗(x)=∏i=16σ(li∗)xi[1−σ(li∗)]1−xi,li∗=2(2xleft−1)+0.8(2xabove−1).P_*(x)=\prod_{i=1}^{6}\sigma(l_i^*)^{x_i}[1-\sigma(l_i^*)]^{1-x_i},\quad l_i^*=2(2x_{\rm left}-1)+0.8(2x_{\rm above}-1).

This determines exact probabilities for all 64 images, which become training weights rather than a sampled dataset. Save the following as pixelcnn.py and run it with Python 3.12 and NumPy 1.26.4. No data or model download is needed.

"""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))

The network stores 61 scalars: 18 first-layer weights and two biases, 36 second-layer weights and two biases, and two output weights plus one bias. Masks disable 26 weight slots, leaving 35 effective scalars. After 400 steps at learning rate 0.1, exact target cross-entropy falls from 4.185528 to 2.718718 nats/image, or about 0.653713 bits/pixel. Target entropy is 2.710494, still below model cross-entropy; the remaining gap is not described as perfect fitting.

The final probabilities sum to one within floating-point precision. Checks go beyond that total: flip every input bit across all images and verify that current and earlier outputs stay unchanged; take finite differences of all 61 parameters; compare vectorized convolution against an independent scalar loop; and demonstrate leakage when the first mask is deliberately changed to B. Seed-12 sampling computes probabilities and draws pixels sequentially at the six positions.

For a layer with Cin,CoutC_{\rm in},C_{\rm out} channels, kernel width kk, DD pixels and batch size NN, naive convolution costs O(NDk2CinCout)O(NDk^2C_{\rm in}C_{\rm out}). Explicitly stored patches here use O(NDk2Cin)O(NDk^2C_{\rm in}) space. Accumulate costs across LL layers. The simple ancestral sampler reruns the network at each pixel, requiring DD forward passes, whereas one training forward pass evaluates all positions. Caching can reduce repeated work without removing sequential dependence.

Exact probability does not settle speed or sample quality

PixelCNN evaluates a supplied image’s discrete probability exactly through conditionals, but sampling has a sequential cost and local structure limits dependencies. Lower NLL measures the specified discrete image distribution; human visual preference need not improve in step. These binary teaching images lack natural-image texture, and 0.653713 cannot be compared directly with color-image paper metrics.

The pinned OpenAI PixelCNN++ code shows shifted convolutions and a two-stream structure. It is a later variant rather than the same implementation as basic 2016 PixelCNN. Reading model.py lines 1–63, related shift functions in nn.py and the README opening supports that architectural comparison; this article does not reproduce its full density output, training or performance. Architecture choice depends on the observation model, dependency range and sampling budget, not merely the repository name.

Test your masks with counterexamples

  1. Why is B unsafe for the current binary input in layer one, but safe for the same-position hidden feature in layer two?

Answer: The first layer’s current input is the answer, and B’s center connection reads it. The second layer’s same-position feature has already passed through A, excluding current and future inputs and summarizing earlier information only. Verify that premise along the whole network’s information paths.

  1. If every parameter is zero, what are each 2×3 image’s probability, NLL and bits/pixel?

Answer: Every conditional is one half, so the joint is 1/641/64, NLL is 6log⁡2≈4.1588836\log2\approx4.158883, and bits/pixel is one. The 64 equal probabilities sum to one, checking both normalization and units.

  1. When predicting (4,1)(4,1), is (3,4)(3,4) already available in generation order? Why can even 20 layers of 3×3 A/B masks miss it?

Answer: The preceding row has been generated, so the point is in the past. A backward path moving up one row can move right at most one column, not three. Additional up/left-only layers cannot move upward and then return downward, so the point remains unreachable.

  1. Should predicting the current G channel exclude the current R value? What happens if the binary mask is copied indiscriminately across channels?

Answer: In R→G→B order, R already exists and may condition G. Copying the binary center prohibition to every channel over-restricts valid dependencies. Conversely, opening all current-channel connections can expose the G or B target. Restrictions must follow channel order.

From basic masks to gates and later implementations

The 2016 paper by van den Oord, Kalchbrenner and Kavukcuoglu includes PixelRNN and PixelCNN; Sections 3.4–3.5 and Table 1 supply the basic-mask reference. Conditional Image Generation with PixelCNN Decoders was first submitted on 2016-06-16; the read v2 is dated 2016-06-18, with reading focused on gates and blind spots.

The PixelCNN++ repository is pinned to commit bbc1568 dated 2020-01-28. Its license opening declares MIT and Apache 2.0; only the first 27 lines were reviewed here. Architectural material is linked for comparison, without copied source or upstream training execution. Neither paper benchmarks nor README performance claims are presented as this project’s replication.

Continue with generative models to compare likelihood and sampling tasks, or find VAE in the catalogue to examine how latent variables change the computation.

Make a prediction, then check

Can a type-B hidden layer read its own spatial position safely?

Choose one answer

Learning objectives

  • Explain spatial and RGB-channel masks.
  • Derive masked-convolution gradients and normalization.
  • Measure exact likelihood and test answer leakage.
  • Distinguish ordinary, gated and PixelCNN++ architectures.

Prerequisites & connections

Explore related knowledge →

References

  1. Pixel Recurrent Neural Networks: masked convolutions and PixelCNN
    Aäron van den Oord; Nal Kalchbrenner; Koray Kavukcuoglu · 2016
  2. 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
  3. PixelCNN++ author implementation: shifted stacks at bbc1568
    OpenAI and PixelCNN++ contributors · 2020

Version1 · Editorial status: Recorded technical checks completed

View technical check record (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.

  • Verified all61 stored gradients including26 masked slots, independent scalar convolutions,64-state target/model normalization, exhaustive single-bit causal flips,400-step population training and the(3,4) blind spot from(4,1).
  • Four computed SVGs per topic bind the exact bilingual MDX. The four-topic group passed15 numeric/geometry checks and24 isolated language/width cases with four fallback fonts; eight representative screenshots were actually inspected. VAE heading changed from draw to estimate; original figures preserved, data unchanged. Literal-prose AST checked before freezing. Full article-page acceptance is separate; no independent human review.

Source locations checked:

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.