Build PixelCNN mask A and mask B with colour channel ordering

Why it matters Autoregressive image models such as PixelCNN and the masked convs in early audio models depend on these masks.

PixelCNN generates an image one pixel and one colour at a time, so each conv must only see pixels above and to the left, and earlier colours at the current pixel.

Write pixelcnn_mask(k, c_in, c_out, mask_type). Return a (c_out, c_in, k, k) float mask of 0s and 1s, with k odd and c_in, c_out divisible by 3. Channels are split into 3 colour groups in order R, G, B: channel c of a layer with C channels is in group c // (C / 3). Spatially, with centre m = k // 2: positions in rows above m are 1, positions in row m left of column m are 1, positions right of or below the centre are 0. At the centre, output channel o connects to input channel c if group(c) < group(o) for mask "A", or group(c) <= group(o) for mask "B".

Signaturedef pixelcnn_mask(k, c_in, c_out, mask_type)

Example

pixelcnn_mask(3, 3, 3, "A")[1, 0] (G output from R input) is [[1, 1, 1], [1, 1, 0], [0, 0, 0]], and [0, 0] (R from R) has 0 in the centre too.

Understand the idea

PixelCNN writes an image like text: pixel by pixel from the top-left, and within a pixel first red, then green, then blue. To train it in parallel, every conv filter is masked so a prediction can never look at anything that comes later in that order. It is like a crossword solver who may only use answers already filled in above and to the left.

Tiny example: a 3 x 3 filter. The whole top row is allowed, the left cell of the middle row is allowed, the rest is blocked. At the centre, the green output may see red (earlier colour), not green or blue. With mask A even red may not see red; mask B, used in deeper layers, lets each colour see its own earlier features.

Rule: allowed(o, c, u, v) = u < m or (u == m and v < m) or (u == m and v == m and group(c) < group(o) for A, <= for B).

Masked convolutions also appear in WaveNet-style audio models and in image compression entropy models.

Shapes and data flow

mask (c_out, c_in, k, k); groups of c_in/3 and c_out/3 channels
solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks the hidden tests with Pro.

  • Sample 1: examplepixelcnn_mask(3, 3, 3, 'A')[1, 0]
  • Sample 2: centre table Apixelcnn_mask(3, 6, 3, 'A')[:, :, 1, 1]