AttnGAN: Fine-Grained Text to Image Generation with Attentional Generative Adversarial Networks

Tao Xu, Pengchuan Zhang, Qiuyuan Huang, Han Zhang, Zhe Gan, Xiaolei Huang, Xiaodong He

Introduction

Automatically generating images according to natural language descriptions is a fundamental problem in many applications, such as art generation and computer-aided design. It also drives research progress in multimodal learning and inference across vision and language, which is one of the most active research areas in recent years

Most recently proposed text-to-image synthesis methods are based on Generative Adversarial Networks (GANs) . A commonly used approach is to encode the whole text description into a global sentence vector as the condition for GAN-based image generation . Although impressive results have been presented, conditioning GAN only on the global sentence vector lacks important fine-grained information at the word level, and prevents the generation of high quality images. This problem becomes even more severe when generating complex scenes such as those in the COCO dataset .

To address this issue, we propose an Attentional Generative Adversarial Network (AttnGAN) that allows attention-driven, multi-stage refinement for fine-grained text-to-image generation. The overall architecture of the AttnGAN is illustrated in Figure 2. The model consists of two novel components. The first component is an attentional generative network, in which an attention mechanism is developed for the generator to draw different sub-regions of the image by focusing on words that are most relevant to the sub-region being drawn (see Figure 1). More specifically, besides encoding the natural language description into a global sentence vector, each word in the sentence is also encoded into a word vector. The generative network utilizes the global sentence vector to generate a low-resolution image in the first stage. In the following stages, it uses the image vector in each sub-region to query word vectors by using an attention layer to form a word-context vector. It then combines the regional image vector and the corresponding word-context vector to form a multimodal context vector, based on which the model generates new image features in the surrounding sub-regions. This effectively yields a higher resolution picture with more details at each stage. The other component in the AttnGAN is a Deep Attentional Multimodal Similarity Model (DAMSM). With an attention mechanism, the DAMSM is able to compute the similarity between the generated image and the sentence using both the global sentence level information and the fine-grained word level information. Thus, the DAMSM provides an additional fine-grained image-text matching loss for training the generator.

The contribution of our method is threefold. (i) An Attentional Generative Adversarial Network is proposed for synthesizing images from text descriptions. Specifically, two novel components are proposed in the AttnGAN, including the attentional generative network and the DAMSM. (ii) Comprehensive study is carried out to empirically evaluate the proposed AttnGAN. Experimental results show that the AttnGAN significantly outperforms previous state-of-the-art GAN models. (iii) A detailed analysis is performed through visualizing the attention layers of the AttnGAN. For the first time, it is demonstrated that the layered conditional GAN is able to automatically attend to relevant words to form the condition for image generation.

Related Work

Generating high resolution images from text descriptions, though very challenging, is important for many practical applications such as art generation and computer-aided design. Recently, great progress has been achieved in this direction with the emergence of deep generative models . Mansimov et al. built the alignDRAW model, extending the Deep Recurrent Attention Writer (DRAW) to iteratively draw image patches while attending to the relevant words in the caption. Nguyen et al. proposed an approximate Langevin approach to generate images from captions. Reed et al. used conditional PixelCNN to synthesize images from text with a multi-scale model structure. Compared with other deep generative models, Generative Adversarial Networks (GANs) have shown great performance for generating sharper samples . Reed et al. first showed that the conditional GAN was capable of synthesizing plausible images from text descriptions. Their follow-up work also demonstrated that GAN was able to generate better samples by incorporating additional conditions (e.g., object locations). Zhang et al. stacked several GANs for text-to-image synthesis and used different GANs to generate images of different sizes. However, all of their GANs are conditioned on the global sentence vector, missing fine-grained word level information for image generation.

The attention mechanism has recently become an integral part of sequence transduction models. It has been successfully used in modeling multi-level dependencies in image captioning , image question answering and machine translation . Vaswani et al. also demonstrated that machine translation models could achieve state-of-the-art results by solely using an attention model. In spite of these progress, the attention mechanism has not been explored in GANs for text-to-image synthesis yet. It is worth mentioning that the alignDRAW also used LAPGAN to scale the image to a higher resolution. However, the GAN in their framework was only utilized as a post-processing step without attention. To our knowledge, the proposed AttnGAN for the first time develops an attention mechanism that enables GANs to generate fine-grained high quality images via multi-level (e.g., word level and sentence level) conditioning.

Attentional Generative Adversarial Network

As shown in Figure 2, the proposed Attentional Generative Adversarial Network (AttnGAN) has two novel components: the attentional generative network and the deep attentional multimodal similarity model. We will elaborate each of them in the rest of this section.

Current GAN-based models for text-to-image generation typically encode the whole-sentence text description into a single vector as the condition for image generation, but lack fine-grained word level information. In this section, we propose a novel attention model that enables the generative network to draw different sub-regions of the image conditioned on words that are most relevant to those sub-regions.

As shown in Figure 2, the proposed attentional generative network has mm generators (G0,G1,...,Gm−1G_{0},G_{1},...,G_{m-1}), which take the hidden states (h0,h1,...,hm−1h_{0},h_{1},...,h_{m-1}) as input and generate images of small-to-large scales (x^0,x^1,...,x^m−1\hat{x}_{0},\hat{x}_{1},...,\hat{x}_{m-1}). Specifically,

Here, zz is a noise vector usually sampled from a standard normal distribution. e‾\overline{e} is a global sentence vector, and ee is the matrix of word vectors. FcaF^{ca} represents the Conditioning Augmentation that converts the sentence vector e‾\overline{e} to the conditioning vector. FiattnF^{attn}_{i} is the proposed attention model at the ithi^{th} stage of the AttnGAN. FcaF^{ca}, FiattnF^{attn}_{i}, FiF_{i}, and GiG_{i} are modeled as neural networks.

To generate realistic images with multiple levels (i.e., sentence level and word level) of conditions, the final objective function of the attentional generative network is defined as

Here, λ\lambda is a hyperparameter to balance the two terms of Eq. (3). The first term is the GAN loss that jointly approximates conditional and unconditional distributions . At the ithi^{th} stage of the AttnGAN, the generator GiG_{i} has a corresponding discriminator DiD_{i}. The adversarial loss for GiG_{i} is defined as

where the unconditional loss determines whether the image is real or fake while the conditional loss determines whether the image and the sentence match or not.

Alternately to the training of GiG_{i}, each discriminator DiD_{i} is trained to classify the input into the class of real or fake by minimizing the cross-entropy loss defined by

where xix_{i} is from the true image distribution pdataip_{data_{i}} at the ithi^{th} scale, and x^i\hat{x}_{i} is from the model distribution pGip_{G_{i}} at the same scale. Discriminators of the AttnGAN are structurally disjoint, so they can be trained in parallel and each of them focuses on a single image scale.

The second term of Eq. (3), LDAMSM\mathcal{L}_{DAMSM}, is a word level fine-grained image-text matching loss computed by the DAMSM, which will be elaborated in Subsection 3.2.

2 Deep Attentional Multimodal Similarity Model

The DAMSM learns two neural networks that map sub-regions of the image and words of the sentence to a common semantic space, thus measures the image-text similarity at the word level to compute a fine-grained loss for image generation.

The attention-driven image-text matching score is designed to measure the matching of an image-sentence pair based on an attention model between the image and the text.

We first calculate the similarity matrix for all possible pairs of words in the sentence and sub-regions in the image by

Then, we build an attention model to compute a region-context vector for each word (query). The region-context vector cic_{i} is a dynamic representation of the image’s sub-regions related to the ithi^{th} word of the sentence. It is computed as the weighted sum over all regional visual vectors, i.e.,

Here, γ1\gamma_{1} is a factor that determines how much attention is paid to features of its relevant sub-regions when computing the region-context vector for a word.

Finally, we define the relevance between the ithi^{th} word and the image using the cosine similarity between cic_{i} and eie_{i}, i.e., R(ci,ei)=(ciTei)/(∣∣ci∣∣∣∣ei∣∣)R(c_{i},e_{i})=(c_{i}^{T}e_{i})/(||c_{i}||||e_{i}||). Inspired by the minimum classification error formulation in speech recognition (see, e.g., ), the attention-driven image-text matching score between the entire image (QQ) and the whole text description (DD) is defined as

where γ2\gamma_{2} is a factor that determines how much to magnify the importance of the most relevant word-to-region-context pair. When γ2→∞\gamma_{2}\to\infty, R(Q,D)R(Q,D) approximates to max⁡i=1T−1R(ci,ei)\max_{i=1}^{T-1}R(c_{i},e_{i}).

The DAMSM loss is designed to learn the attention model in a semi-supervised manner, in which the only supervision is the matching between entire images and whole sentences (a sequence of words). Similar to , for a batch of image-sentence pairs {(Qi,Di)}i=1M\{(Q_{i},D_{i})\}_{i=1}^{M}, the posterior probability of sentence DiD_{i} being matching with image QiQ_{i} is computed as

where γ3\gamma_{3} is a smoothing factor determined by experiments. In this batch of sentences, only DiD_{i} matches the image QiQ_{i}, and treat all other M−1M-1 sentences as mismatching descriptions. Following , we define the loss function as the negative log posterior probability that the images are matched with their corresponding text descriptions (ground truth), i.e.,

where P(Qi∣Di)=exp⁡(γ3R(Qi,Di))∑j=1Mexp⁡(γ3R(Qj,Di))P(Q_{i}|D_{i})=\frac{\exp(\gamma_{3}R(Q_{i},D_{i}))}{\sum_{j=1}^{M}{\exp(\gamma_{3}R(Q_{j},D_{i}))}} is the posterior probability that sentence DiD_{i} is matched with its corresponding image QiQ_{i}. If we redefine Eq. (10) by R(Q,D)=\big{(}\overline{v}^{T}\overline{e}\big{)}/\big{(}||\overline{v}||||\overline{e}||\big{)} and substitute it to Eq. (11), (12) and (13), we can obtain loss functions L1s\mathcal{L}^{s}_{1} and L2s\mathcal{L}^{s}_{2} (where ‘s’ stands for ‘‘sentence’’) using the sentence vector e‾\overline{e} and the global image vector v‾\overline{v}.

Based on experiments on a held-out validation set, we set the hyperparameters in this section as: γ1=5\gamma_{1}=5, γ2=5\gamma_{2}=5, γ3=10\gamma_{3}=10 and M=50M=50. Our DAMSM is pretrained We also finetuned the DAMSM with the whole network, however the performance was not improved. by minimizing LDAMSM\mathcal{L}_{DAMSM} using real image-text pairs. Since the size of images for pretraining DAMSM is not limited by the size of images that can be generated, real images of size 299×\times299 are utilized. In addition, the pretrained text-encoder in the DAMSM provides visually-discriminative word vectors learned from image-text paired data for the attentional generative network. In comparison, conventional word vectors pretrained on pure text data are often not visually-discriminative, e.g., word vectors of different colors, such as red, blue, yellow, etc., are often clustered together in the vector space, due to the lack of grounding them to the actual visual signals.

In sum, we propose two novel attention models, the attentional generative network and the DAMSM, which play different roles in the AttnGAN. (i) The attention mechanism in the generative network (see Eq. 2) enables the AttnGAN to automatically select word level condition for generating different sub-regions of the image. (ii) With an attention mechanism (see Eq. 9), the DAMSM is able to compute the fine-grained text-image matching loss LDAMSM\mathcal{L}_{DAMSM}. It is worth mentioning that, LDAMSM\mathcal{L}_{DAMSM} is applied only on the output of the last generator Gm−1G_{m-1}, because the eventual goal of the AttnGAN is to generate large images by the last generator. We tried to apply LDAMSM\mathcal{L}_{DAMSM} on images of all resolutions generated by (G0,G1,...,Gm−1G_{0},G_{1},...,G_{m-1}). However, the performance was not improved but the computational cost was increased.

Experiments

Extensive experimentation is carried out to evaluate the proposed AttnGAN. We first study the important components of the AttnGAN, including the attentional generative network and the DAMSM. Then, we compare our AttnGAN with previous state-of-the-art GAN models for text-to-image synthesis .

Datasets. Same as previous text-to-image methods , our method is evaluated on CUB and COCO datasets. We preprocess the CUB dataset according to the method in . Table 1 lists the statistics of datasets.

Evaluation. Following Zhang et al. , we use the inception score as the quantitative evaluation measure. Since the inception score cannot reflect whether the generated image is well conditioned on the given text description, we propose to use R-precision, a common evaluation metric for ranking retrieval results, as a complementary evaluation metric for the text-to-image synthesis task. If there are RR relevant documents for a query, we examine the top RR ranked retrieval results of a system, and find that rr are relevant, and then by definition, the R-precision is r/R{r}/{R}. More specifically, we conduct a retrieval experiment, i.e., we use generated images to query their corresponding text descriptions. First, the image and text encoders learned in our pretrained DAMSM are utilized to extract global feature vectors of the generated images and the given text descriptions. And then, we compute cosine similarities between the global image vectors and the global text vectors. Finally, we rank candidate text descriptions for each image in descending similarity and find the top rr relevant descriptions for computing the R-precision. To compute the inception score and the R-precision, each model generates 30,000 images from randomly selected unseen text descriptions. The candidate text descriptions for each query image consist of one ground truth (i.e., R=1R=1) and 99 randomly selected mismatching descriptions.

Besides quantitative evaluation, we also qualitatively examine the samples generated by our models. Specifically, we visualize the intermediate results with attention learned by the attention models FattnF^{attn}. As defined in Eq. (2), weights βj,i\beta_{j,i} indicates which words the model attends to when generating a sub-region of the image, and ∑i=0T−1βj,i=1\sum_{i=0}^{T-1}\beta_{j,i}=1. We suppress the less-relevant words for an image’s sub-region via

For better visualization, we fix the word and compute its attention weights with NN different sub-regions of an image, β^0,i,β^1,i,...,β^N−1,i\hat{\beta}_{0,i},\hat{\beta}_{1,i},...,\hat{\beta}_{N-1,i}. We reshape the NN attention weights to N×N\sqrt{N}\times\sqrt{N} pixels, which are then upsampled with Gaussian filters to have the same size as the generated images. Limited by the length of the paper, we only visualize the top-5 most attended words (i.e., words with top-5 highest ∑j=0N−1β^j,i\sum_{j=0}^{N-1}\hat{\beta}_{j,i} values) for each attention model.

In this section, we first quantitatively evaluate the AttnGAN and its variants. The results are shown in Table 2 and Figure 3. Our ‘‘AttnGAN1’’ architecture has one attention model and two generators, while the ‘‘AttnGAN2’’ architecture has two attention models stacked with three generators (see Figure 2). In addition, as illustrated in Figure 4, Figure 5, Figure 6, and Figure 7, we qualitatively examine the images generated by our AttnGAN.

The DAMSM loss. To test the proposed LDAMSM\mathcal{L}_{DAMSM}, we adjust the value of λ\lambda (see Eq. (3)). As shown in Figure 3, a larger λ\lambda leads to a significantly higher R-precision rate on both CUB and COCO datasets. On the CUB dataset, when the value of λ\lambda is increased from 0.1 to 5, the inception score of the AttnGAN1 is improved from 4.19 to 4.35 and the corresponding R-precision rate is increased from 16.55% to 58.65% (see Table 2). On the COCO dataset, by increasing the value of λ\lambda from 0.1 to 50, the AttnGAN1 achieves both high inception score and R-precision rate (see Figure 3). This comparison demonstrates that properly increasing the weight of LDAMSM\mathcal{L}_{DAMSM} helps to generate higher quality images that are better conditioned on given text descriptions. The reason is that the proposed fine-grained image-text matching loss LDAMSM\mathcal{L}_{DAMSM} provides additional supervision (i.e., word level matching information) for training the generator. Moreover, in our experiments, we do not observe any collapsed nonsensical mode in the visualization of AttnGAN-generated images. It indicates that, with extra supervision, the fine-grained image-text matching loss also helps to stabilize the training process of the AttnGAN. In addition, if we replace the proposed DAMSM sub-network with the text encoder used in , on the CUB dataset, the inception score and R-precision drops to 3.98 and 10.37%, respectively (i.e., the ‘‘AttnGAN1, no DAMSM’’ entry in table 2), which further demonstrates the effectiveness of the proposed LDAMSM\mathcal{L}_{DAMSM}.

The attentional generative network. As shown in Table 2 and Figure 3, stacking two attention models in the generative networks not only generates images of a higher resolution (from 128×\times128 to 256×\times256 resolution), but also yields higher inception scores on both CUB and COCO datasets. In order to guarantee the image quality, we find the best value of λ\lambda for each dataset by increasing the value of λ\lambda until the overall inception score is starting to drop on a held-out validation set. ‘‘AttnGAN1’’ models are built for searching the best λ\lambda, based on which a ‘‘AttnGAN2’’ model is built to generate higher resolution images. Due to GPU memory constraints, we did not try the AttnGAN with three attention models. As the result, our final model for CUB and COCO is ‘‘AttnGAN2, λ\lambda=5’’ and ‘‘AttnGAN2, λ\lambda=50’’, respectively. The final λ\lambda of the COCO dataset turns out to be much larger than that of the CUB dataset, indicating that the proposed LDAMSM\mathcal{L}_{DAMSM} is especially important for generating complex scenarios like those in the COCO dataset.

To better understand what has been learned by the AttnGAN, we visualize its intermediate results with attention. As shown in Figure 4, the first stage of the AttnGAN (G0G_{0}) just sketches the primitive shape and colors of objects and generates low resolution images. Since only the global sentence vectors are utilized in this stage, the generated images lack details described by exact words, e.g., the beak and eyes of a bird. Based on word vectors, the following stages (G1G_{1} and G2G_{2}) learn to rectify defects in results of the previous stage and add more details to generate higher-resolution images. Some sub-regions/pixels of G1G_{1} or G2G_{2} images can be inferred directly from images generated by the previous stage. For those sub-regions, the attention is equally allocated to all words and shown to be black in the attention map (see Figure 4). For other sub-regions, which usually have semantic meaning expressed in the text description such as the attributes of objects, the attention is allocated to their most relevant words (bright regions in Figure 4). Thus, those regions are inferred from both word-context features and previous image features of those regions. As shown in Figure 4, on the CUB dataset, the words the, this, bird are usually attended by the FattnF^{attn} models for locating the object; the words describing object attributes, such as colors and parts of birds, are also attended for correcting defects and drawing details. On the COCO dataset, we have similar observations. Since there are usually more than one object in each COCO image, it is more visible that the words describing different objects are attended by different sub-regions of the image, e.g., bananas, kiwi in the bottom-right block of Figure 4. Those observations demonstrate that the AttnGAN learns to understand the detailed semantic meaning expressed in the text description of an image. Another observation is that our second attention model F2attnF^{attn}_{2} is able to attend to some new words that were omitted by the first attention model F1attnF^{attn}_{1} (see Figure 4). It demonstrates that, to provide richer information for generating higher resolution images at latter stages of the AttnGAN, the corresponding attention models learn to recover objects and attributes omitted at previous stages.

Generalization ability. Our experimental results above have quantitatively and qualitatively shown the generalization ability of the AttnGAN by generating images from unseen text descriptions. Here we further test how sensitive the outputs are to changes in the input sentences by changing some most attended words in the text descriptions. Some examples are shown in Figure 5. It illustrates that the generated images are modified according to the changes in the input sentences, showing that the model can catch subtle semantic differences in the text description. Moreover, as shown in Figure 6, our AttnGAN can generate images to reflect the semantic meaning of descriptions of novel scenarios that are not likely to happen in the real world, e.g., a stop sign is floating on top of a lake. On the other hand, we also observe that the AttnGAN sometimes generates images which are sharp and detailed, but are not likely realistic. As examples shown in Figure 7, the AttnGAN creates birds with multiple heads, eyes or tails, which only exist in fairy tales. This indicates that our current method is still not perfect in capturing global coherent structures, which leaves room to improve. To sum up, observations shown in Figure 5, Figure 6 and Figure 7 further demonstrate the generalization ability of the AttnGAN.

2 Comparison with previous methods

We compare our AttnGAN with previous state-of-the-art GAN models for text-to-image generation on CUB and COCO test sets. As shown in Table 3, on the CUB dataset, our AttnGAN achieves 4.36 inception score, which significantly outperforms the previous best inception score of 3.82. More impressively, our AttnGAN boosts the best reported inception score on the COCO dataset from 9.58 to 25.89, a 170.25% improvement relatively. The COCO dataset is known to be much more challenging than the CUB dataset because it consists of images with more complex scenarios. Existing methods struggle in generating realistic high-resolution images on this dataset. Examples in Figure 4 and Figure 6 illustrate that our AttnGAN succeeds in generating 256×\times256 images for various scenarios on the COCO dataset, although those generated images of the COCO dataset are not as photo-realistic as that of the CUB dataset. The experimental results show that, compared to previous state-of-the-art approaches, the AttnGAN is more effective for generating complex scenes due to its novel attention mechanism that catches fine-grained word level and sub-region level information in text-to-image generation.

Conclusions

In this paper, we propose an Attentional Generative Adversarial Network, named AttnGAN, for fine-grained text-to-image synthesis. First, we build a novel attentional generative network for the AttnGAN to generate high quality image through a multi-stage process. Second, we propose a deep attentional multimodal similarity model to compute the fine-grained image-text matching loss for training the generator of the AttnGAN. Our AttnGAN significantly outperforms previous state-of-the-art GAN models, boosting the best reported inception score by 14.14% on the CUB dataset and 170.25% on the more challenging COCO dataset. Extensive experimental results clearly demonstrate the effectiveness of the proposed attention mechanism in the AttnGAN, which is especially critical for text-to-image generation for complex scenes.

References

Supplementary Material

Due to the size limit, more examples are available in the appendix, which can be download from this link.