Paper commentary
Generative Image Inpainting with Contextual Attention
Contextual attention lets a feed-forward network borrow pixels from known regions
- Problem Convolutional inpainting networks fill large holes with blurry textures and distorted shapes that clash with surrounding areas. Convolution reaches distant context only slowly, through many stacked layers.
- Method Contextual attention is a layer that uses known background patches as convolution filters. It softmax-weights their matches and deconvolves them into the hole, unlike hallucination-only pathways.
- Results On the Places2 validation set, the full model reached 8.6% l1 error, against 16.1% for PatchMatch.
Why convolution struggles with distant context
Learned inpainting usually casts the task as a conditional generation problem, in which an encoder-decoder network fills the hole while adversarial training pushes the fill to agree with the known pixels. Such networks still tend to leave boundary artifacts, distorted structures and blurry texture that clash with the areas around the hole.
The explanation offered is that a convolution only sees a local window, so information from far away has to travel through many stacked layers before it can reach a hole pixel.
Patch-copying methods take the opposite route: they copy background patches into the hole, which suits repeated textures but cannot invent content that is absent from the background. Optimization-based synthesis can match textures to known regions, but the optimization is slow, and the introduction cites minutes per 512×512 image on GPUs for that approach.
The question is therefore whether one feed-forward network can both hallucinate new structure and explicitly borrow features from known positions, without iterative optimization.
An improved two-stage baseline
The baseline starts from the Iizuka et al. network and keeps its input convention: the corrupted image, with the hole pixels set to white, is paired with a binary mask that marks the hole. Training uses 256×256 inputs with a rectangular missing region, and a trained model accepts images of other sizes with several holes at test time.
The main structural change is a coarse-to-fine split. A first network produces a rough estimate of the missing content, and a second network takes that estimate and refines it. Only the coarse network is trained with the reconstruction loss alone; the refinement network is trained with reconstruction and GAN losses, and the authors argue that the refinement network, which sees a more complete scene, learns better features.
The network is also made thinner and deeper than the one in Iizuka et al., with fewer parameters.
Several layer-level choices are changed: mirror padding is used in all convolution layers, batch normalization is removed because it was found to weaken color coherence, and ELUs replace ReLUs. The output is limited by clipping the filter values rather than by tanh or sigmoid, and global and local features are kept separate for the GAN training instead of being concatenated.
The authors report that the baseline converges faster than Iizuka et al. and gives more accurate results, and that the image blending step is no longer needed.
Adversarial and reconstruction losses
The adversarial part uses WGAN-GP, a Wasserstein GAN with a gradient penalty, attached to both the global and the local outputs of the refinement network. The critic objective takes the form \(\min_G \max_{D \in \mathcal{D}} \mathbb{E}_{x\sim P_r}[D(x)] - \mathbb{E}_{\tilde{x}\sim P_g}[D(\tilde{x})]\), where \(\mathcal{D}\) is the set of 1-Lipschitz functions and \(\tilde{x} = G(z)\).
The gradient penalty is evaluated on points interpolated between real and generated samples, and for inpainting it is multiplied by the complement of the mask so that only hole pixels are penalized. The penalty weight λ is set to 10 in all experiments.
The reconstruction term is a pixel-wise l1 loss, used instead of the mean-square error of Iizuka et al., and it shares the l1 distance with the Wasserstein ground distance, which the authors argue makes the combined objective easier to optimize. The reconstruction term regresses the hole towards the single ground-truth image, while the critics learn to match a distribution of plausible fills.
The spatially discounted reconstruction loss gives each pixel a weight γ raised to the power l, where l is the distance from that pixel to the nearest known pixel. The value γ is set to 0.99 in all experiments, so pixels near the hole border carry more weight than pixels at its center. The authors explain this choice by arguing that border pixels are less ambiguous than center pixels, and they report that the discounted loss is more effective than other weighting schemes for large holes.
The contextual attention layer
The layer first extracts 3×3 patches from the background and reshapes them as convolution filters, so that the features of the foreground are matched against them with convolution. Matching uses cosine similarity, the inner product of the normalized foreground feature \(f_{x,y}\) and the normalized background feature \(b_{x',y'}\), written \(s_{x,y,x',y'}\).
The similarities for each foreground position are turned into weights with a scaled softmax taken over the background positions, \(s^*_{x,y,x',y'} = \mathrm{softmax}_{x',y'}(\lambda s_{x,y,x',y'})\), where λ is a constant. In implementation this is a convolution followed by a channel-wise softmax, so the attention for every hole pixel is computed in one pass.
The hole is then reconstructed by reusing the extracted background patches as deconvolution filters, and where patches overlap the pixel values are averaged. Because the matching and the reconstruction are both convolutions, the layer is differentiable and fully convolutional, so it can be trained inside a deep model and tested at arbitrary resolutions.
Attention propagation encourages neighbouring foreground positions to attend to neighbouring background positions. It sums the attention scores along a window of offsets from −k to k, first left-right and then top-down, with kernel size k. The authors argue that this coherence matters because a shift in the foreground is likely to correspond to an equal shift in the background, and they report that propagation improves inpainting at test time and gives richer gradients during training.
Memory is a practical limit: a 64×64 hole in a 128×128 feature map yields 12,288 background convolution filters. Two options reduce this cost: extracting background patches with strides, and downscaling the foreground before matching and upscaling the attention map after propagation.
Full model and one training iteration
On top of the coarse result, the full model runs two encoders in parallel: a bottom one that hallucinates content with layer-by-layer dilated convolution, and a top one that attends to background features through the contextual attention layer. The outputs of the two encoders are aggregated and passed to a single decoder that produces the final output.
For training, a raw image x is corrupted to z = x ⊙ m with a random binary mask m, and the generator receives the concatenation of z and m. The generator output x′ is pasted back into the unmasked area, giving \(\tilde{x} = z + x' \odot (1-m)\). Input and output values are linearly scaled to [−1, 1] in all experiments.
Each generator update is preceded by five critic iterations. In each of them a batch is sampled, masks are generated, and the two critics are updated on x, x̃ and an interpolated sample x̂ = (1−t)x + t x̃ with t drawn uniformly from [0, 1]. The generator is then updated with the spatially discounted l1 loss and the two adversarial critic losses.
Places2 reconstruction and TV metrics
Table 1 reports mean l1 error, mean l2 error, PSNR and TV loss on the Places2 validation set, and the authors present these values for reference only.
For the l1 error, which is lower-is-better, the full model reached 8.6%, the baseline model 9.4% and PatchMatch 16.1%. The l2 error follows the same order, at 2.1% for the full model, 2.4% for the baseline model and 3.9% for PatchMatch.
For PSNR, which is higher-is-better, the full model scored 18.91, the baseline model 18.15 and PatchMatch 16.62.
For TV loss, which is lower-is-better, PatchMatch scored 25.0%, the full model 25.3% and the baseline model 25.7%, so the copying method has the smoothest output on this measure. The authors summarize the pattern as learning-based methods doing better on the l1, l2 and PSNR measures, while direct patch copying gives the lower TV loss.
Visual comparisons on Places2 and other datasets
The baseline model is compared with Iizuka et al. using the result images copied from the Iizuka et al. paper, which carries image blending, while the baseline output is used without post-processing. On this visual comparison the baseline produces results that are comparable to those of Iizuka et al.
On complex Places2 scenes the full model and the baseline were compared on test images of size 512×680, using direct outputs of the trained models. The full model leverages surrounding textures and structures and produces more realistic fills with fewer artifacts than the baseline model.
The attention maps are read as evidence that the model borrows information from surrounding areas for the hole, which the authors interpret as awareness of contextual structure. Example results and attention maps for CelebA faces, DTD textures and ImageNet are shown as samples of the full model, with more results in the supplementary material.
Attention and GAN loss ablations
Contextual attention is compared with appearance flow and with a spatial transformer network in the same framework, where appearance flow is implemented by replacing the attention layer with a convolution that predicts 2-D pixel offsets. For a very different test pair, appearance flow returned very similar attention maps, which the authors suggest may mean the network is stuck in a bad local minimum.
The spatial transformer produced poor inpainting, which the authors attribute to its global affine transformation being too coarse.
Training with DCGAN sometimes collapsed to a limited set of modes, shown on Places2 and CelebA, while WGAN-GP training did not show this collapse. The authors also tried LSGAN and report that its results were worse, and they describe WGAN-GP as giving faster and more stable convergence.
Reconstruction and extra loss ablations
The l1 reconstruction loss was removed from the refinement network, which was trained with adversarial losses only, and the authors judge this insufficient. They note that the reconstruction loss tends to make results blurry, but they regard it as essential because it helps capture content structure and regularizes GAN training.
Perceptual loss, style loss computed on VGG features, and total variation loss were tested, and they gave no noticeable improvement in this framework, so they are not used.
Model size, runtime and training cost
The full model has 2.9M parameters, which the authors describe as roughly half the size of the model proposed in Iizuka et al.
On average the full model runs at 0.2 seconds per frame on a GPU and 1.5 seconds per frame on a CPU for 512×512 images, with a GTX 1080 Ti and a Xeon E5-2697 v3.
For Places2 training, the authors report 11,520 GPU-hours on K80 for Iizuka et al. and 120 GPU-hours on GTX 1080 for the baseline model, which they describe as almost 100 times faster. These are figures from different hardware and reports, not a measurement under the same conditions.
Limitations
The Inception score is not used because inpainting mostly fills background regions rather than generating a variety of object classes. Reconstruction-error metrics are imperfect because many plausible fills differ from the original content, so Table 1 is given only for reference.
The quantitative table covers only the Places2 validation set, while CelebA, CelebA-HQ, DTD and ImageNet appear as visual samples or in the appendix.
The timing given for the optimization-based approach of Yang et al. is taken from the introduction's description and was not measured in this paper. Very high-resolution inpainting is named as future work and is not tested here.
Paper info
- Authors
- Jiahui Yu, Zhe Lin, Jimei Yang, Xiaohui Shen, Xin Lu, Thomas S. Huang
- Venue
- arXiv · Preprint
- First published
- 2018-1-24
- Added
- 2026-11-12
- Updated
- 2018-3-21
- Version
- v2
- arXiv
- 1801.07892
- Category
- cs.CV · cs.GR
- Original paper terms
- arXiv non-exclusive 1.0
- What we show
- Paper info and commentary
AI commentary is a separate explanation from the original paper and may contain errors. The original paper and figures follow each source's terms of use and any rights noted separately.
Quote from the paper
Jiahui Yu, Zhe Lin, Jimei Yang, Xiaohui Shen, Xin Lu, Thomas S. Huang (2018). Generative Image Inpainting with Contextual Attention. arXiv:1801.07892v2. https://arxiv.org/abs/1801.07892v2
BibTeX
@misc{yu2018generative,
title = {{Generative Image Inpainting with Contextual Attention}},
author = {Jiahui Yu and Zhe Lin and Jimei Yang and Xiaohui Shen and Xin Lu and Thomas S. Huang},
year = {2018},
eprint = {1801.07892},
archivePrefix = {arXiv},
url = {https://arxiv.org/abs/1801.07892v2}
}