X-LXMERT: Paint, Caption and Answer Questions with Multi-Modal Transformers
Abstract
Mirroring the success of masked language models, vision-and-language counterparts like V ILBERT , L XMERT and U NITER have achieved state of the art performance on a variety of multimodal discriminative tasks like visual question answering and visual grounding.
Recent work has also successfully adapted such models towards the generative task of image captioning.
This begs the question: Can these models go the other way and generate images from pieces of text?
Our analysis of a popular representative from this model family – L XMERT – ﬁnds that it is unable to generate rich and semantically meaningful imagery with its current training setup.
We introduce X-L XMERT , an extension to L XMERT with training reﬁnements including: discretizing visual representations, using uniform masking with a large range of masking ratios and aligning the right pre-training datasets to the right objectives which enables it to paint.
X-L XMERT ’s image generation capabilities rival state of the art generative models while its question answering and captioning abilities remains comparable to L XMERT .
Introduction
The past year has seen a spate of BERT-style (Devlin et al., 2019) transformer-based architectures (Lu et al., 2019; Chen et al., 2019; Li et al., 2019) proposed for vision-and-language tasks.
These models are typically pre-trained on large image captioning corpora, extending ideas from masked language modeling to mask both the image and text modalities and produce state of the art results on a variety of vision and language tasks including visual question answering, visual grounding and image retrieval.
These impressive results as well as recent probing mechanisms (Ilharco et al., 2020) suggest that these models are able to capture a variety of semantics in images including objects, attributes and their relationships and ground these in natural language.
While these models have been extensively evaluated over several discriminative tasks, relatively little attention has been paid to their generative capabilities.
Bidirectional transformer models like
BERT which exploit context preceding and following the current token are not explicitly designed for generation.
Recent work for language-only transformers (Wang and Cho, 2019; Dong et al., 2019;
Liao et al., 2020) adapt these models towards this capability using sampling procedures.
Such techniques have also been adapted successfully for image captioning - inputting an image and sampling the textual side of the model to generate a relevant caption (Zhou et al., 2020).
This begs the question:
Can we go the other way and sample images from input pieces of text?
i.e. Do vision-and-language
BERT models know how to paint?
In this work, we probe the ability of a powerful and popular representative from this family of models - L XMERT (Tan and Bansal, 2019), to produce high ﬁdelity and semantically meaningful images conditioned on captions.
Interestingly, our analysis leads us to the conclusion that L XMERT in its current form does not possess the ability to paintit produces images that have little resemblance to natural images.
This is a somewhat surprising ﬁnding given L XMERT ’s masked training objectives for both modalities and its impressive performance on tasks that seemingly require a similar skill set.
We ﬁnd that this is largely due to the regression training objective used by this family of models to predict masked features on the visual side.
This is in contrast with the textual side, where they predict masked tokens within a large discrete vocabulary using a classiﬁcation objective.
Regressing features in high dimensional spaces is challenging to optimize and introduces noise at inference.
This gets compounded when using iterative sampling procedures to predict the entire set of visual features.
A downstream image generator consuming these predictions isn’t able to recover from this noise even when ﬁne-tuned on L XMERT ’s predictions.
We introduce X-L XMERT that builds upon
L XMERT and enables it to effectively perform discriminative as well as generative tasks.
Our key reﬁnements include: (a) simplifying the visual inputs to use grid features instead of object detection bounding boxes, (b) discretizing visual representations, (c) using uniform masking with a large range of masking ratios to enable the model to predict the entire set of visual clusters at inference time and (d) aligning the right pre-training datasets to the right objectives.
When coupled with our proposed image generator, X-L XMERT is able to generate rich imagery that is semantically consistent with the input captions.
Importantly, X-L XMERT ’s image generation capabilities rival state-of-the-art image generation models (designed only for generation), while its question answering capabilities show little degradation compared to L XMERT .
In summary, we present X-L XMERT , a uniﬁed multimodal transformer model that can answer questions, and also generate captions and images.
Our extensions to enable these capabilities are not tied to L XMERT ’s underlying architecture.
We expect that the entire family of multimodal BERT models can be enhanced with image generative capabilities using our introduced strategy.
Related works Visual-Language transformer models
Recent multi-modal pre-training models show signiﬁcant improvements on a wide range of downstream tasks, including discriminiative (eg., visual question answering) and generation task (eg. image captioning (Zhou et al., 2020)).
Some methods use a single transformer architecture to jointly encode text and image (Li et al., 2019; Su et al., 2019; Alberti et al., 2019; Rahman et al., 2019; Li et al., 2020; Chen et al., 2019; Qi et al., 2020; Huang et al., 2020), while others use two-stream architectures (Lu et al., 2019, 2020; Tan and Bansal, 2019).
These models typically consume object detection features.
We probe this family of models at the task of image generation and present extensions that enable them to reliably generate images.
Sequence generation with undirectional transformer
When generating sequences with conventional transformer language models, it is natural to sample tokens from left to right.
However, since undirectional transformers (eg. BERT) are not trained with a speciﬁc generation order, a line of works has investigated different strategies for sequence generation with undirected models.
Wang and Cho (2019) use Gibbs sampling from an allmask sequence, and Dong et al.
; Bao et al.
(2020) use causal attention during training for leftto-right generation.
Liao et al.
(2020); Mansimov et al.
; Ghazvininejad et al.
(2019) sample masks from a uniform distribution during training for arbitrary order or parallel generation.
We adapt these techniques for grid-based image generation.
Text-to-image synthesis
Synthesizing images from text descriptions continues to be challenging.
Since the pioneering work of Reed et al.
(2016), many methods have adopted GANs (Goodfellow et al., 2014) to generate high-ﬁdelity images.
Nguyen et al.
(2017) generate images that maximizes activation of a pretrained captioning model.
Recent works (Zhang et al., 2017, 2018; Xu et al., 2018; Li et al., 2019) use multi-stage generation, where low-resolution images are initially sampled, then gradually upsampled and improved in later stages.
These models are specialized toward image generation, whereas our model can not just generate images, but also answer questions and generate captions.
Also, our design is modular in nature.
While we use a compact image generator with X-L XMERT , one can also replace it with either of the aforementioned model architectures.
Grid visual representation
Compared to bounding box representations which requires expensive object detection annotations, grid representations of images can be naturally obtained from CNNs.
Jiang et al.
; Huang et al.
(2020) have recently shown that these can be almost as powerful as bounding box representations for VQA.
Grid representation have been widely used in vision tasks, including self-supervised learning (Oord et al., 2018;
Henaff et al., 2019; Trinh et al., 2019;
Gidaris et al., 2020; Noroozi and Favaro, 2016) and image generation (van den Oord et al., 2017; Lin et al., 2019).
We leverage grid visual representations to enable L XMERT to generate images.
RoIFeat
Quantize
[Figure]
UniformMaskFeat +
[Figure]
Agiraffestanding
[Figure]
+
[Figure]
[Figure]
[Figure]
𝐼
[Figure]
v
[Figure]
FeatureMatchingLoss
[Figure]
Over the past year, a large number of transformer based architectures for multimodal data have produced impressive results across a variety of discriminative tasks.
Some of these models have been shown to perform very well at the generative task of
Image Captioning, but little attention has been paid to the reverse generative task: generating images given text.
In this work, we ﬁrst probe one popular representative from this family - L XMERT (Tan and
Bansal, 2019) - in its ability to paint; and propose extensions that enable it to paint.
L XMERT is a cross modality transformer with inputs: image I and text T .
This is represented as the sequence { v 1 , . .
. , v T , CLS , w 1 , . . .
, w T , EOS } where { v i } T i =1 are image region features, {
w j } Tj = are word tokens and CLS and EOS are special tokens.
L XMERT outputs embeddings for each input { h v i } T i =1 , { h w j } Tj =1 and h CLS , h EOS .
h CLS is used as the cross-modality output.
Internally,
L XMERT consists of two types of encoders: single-modality encoders for each modality and a cross-modality encoder using bi-directional cross attention to exchange information and align entities across the modalities.
L XMERT is pretrained on several vision-andlanguage datasets with ﬁve objectives: Masked language modeling (MLM), Masked visual feature regression (MVFR) - reconstructing randomly masked words and regions given the remaining inputs, Masked object classiﬁcation (MOC) - object classiﬁcation on masked image regions, Image-text matching (ITM) - image-caption alignment prediction and Question answering (QA) - answering a question given image input.
After pretraining,
L XMERT is ﬁnetuned for various downstream tasks.
Unless noted, we use the default settings and hyperparameters of L XMERT in our experiments.
Probing LXMERT’s Ability to Paint
In order to probe L XMERT ’s ability to paint, we ﬁrst modify its input image representation to a grid based feature set (Section 4.1) and then pass these to an image generator (Section 4.2).
4. Grid Image Features
Most popular multimodal BERT models use image features extracted from the output of a Faster
R-CNN (Ren et al., 2015) object detector.
The detected objects typically have various locations and sizes.
Passing these features into an image generator poses some challenges: (1) L XMERT is not trained to predict locations of given objects (2) it is not trivial to predict both object classes and their locations simultaneously (3) object detections do not cover backgrounds.
We modify L XMERT to use a uniform N × N grid and use RoI Pooling to extract the grid features.
Note that we use the same detection backbone pretrained on the Visual Genome dataset to maintain parity with the original L XMERT .
Our experiments in Sec 6 show that moving to a grid based input causes very little degradation to downstream QA tasks, a ﬁnding consistent with Jiang et al.
Sampling grid features:
Given text input, we sample predicted visual features { h v i } T i =1 where
T = N
× N is the number of image regions, using
Gibbs sampling in a manner similar to language generation using BERT by Wang and Cho (2019).
4. Image Generation
We use a compact image generator inspired by recent state of the art image synthesis methods leveraging Generative Adversarial Networks (GAN) (Goodfellow et al., 2014).
Its takes as inputs
an
N × N grid of visual features from the pretrained
Faster-RCNN network and generates an image.
As shown in Fig 1, the input grid features are projected through convolutional layers and then passed to an image generator, which consists of multiple residual blocks (Miyato et al., 2018).
Each generator residual block has SPADE layer (Park et al., 2019) which guides generator to outptut high ﬁdelity images given semantic grid layouts.
In our experiments, we use an image generator which takes 8 ×grid features and outputs an 256 × 256 image.
Training the image generator:
The generator is pre-trained using 8 × 8 ground truth Faster-RCNN features, akin to teacher forcing , without any inputs from L XMERT .
We train the generator with the same loss as Park et al.
but replacing the segmentation map with a grid feature map.
Fig. 2(b) shows that our generation architecture can successfully reconstruct images using ground truth pre-trained grid features.
Note that the generator still displays some reconstruction errors compared with modern auto-encoders such as VQVAEv2 (Razavi et al., 2019) primarily due to (1) freezing the encoder backbone in order to match
L XMERT ’s training settings (2) restricting grid features to have a low (and manageable) dimension.
4. Can LXMERT Paint?
Our experiments in Section 6 reveal that L XMERT is unable to produce visual features that can be converted to a meaningful image by a generator.
Figure 2 shows an example.
Recall that the L XMERT loss function includes a regression loss - MVFRthat corresponds to regressing target visual features given the textual and visual context.
Unfortunately, at inference, this loss on the validation set remains high, causing the predicted visual features to be fairly noisy.
In addition, the Gibbs sampling procedure causes this error to propagate over the entire set of features.
The resulting predictions aren’t suitable to be used for downstream image generation.
X-LXMERT
In this section, we present X-L XMERT 1 that extends L XMERT , enabling it to paint, while still maintaining a high performance on discriminative tasks.
X-L XMERT has three key reﬁnements that enable it to paint (Sec 5.1): discretizing visual representations, using uniform masking with a large range of masking ratios, and aligning the right pretraining datasets to the right objectives.
We then leverage Gibbs sampling to generate visual features given textual input (Sec 5.2).
5. From LXMERT to X-LXMERT
Discrete visual representations: We observe that the visual features regressed by L XMERT are not suitable for image generation.
Instead, akin to
VideoBERT (Sun et al., 2019), we ﬁrst create a visual vocabulary using K-mean clustering, approximate the target visual features via a nearest neighbor search, and modify L XMERT to predict the cluster ID for each masked visual token.
A new
Cluster-Centroid Classiﬁcation objective (CCC) is used to replace the previous regression objective with a high cardinality classiﬁcation objective.
Our experiments show that discretizing visual representations results helps in predicting better visual features, stems the propagation of feature noise over sampling iterations and generates rich imagery.
Uniform instead of Bernoulli masking:
Following BERT, L XMERT uses Bernouli sampling (with p = 0 . 15 ) to determine positions of the masked tokens on the visual and textual features.
In order to generate an image from captions, all tokens on the vision side must be masked and predicted.
A low probability Bernouli sampling procedure does not prepare the model well for the generation task, and increasing the probability to very high values leads to poor pre-training.
To resolve this, we use Uniform masking on the vision modality.
X-L XMERT ’s uniform masking ﬁrst samples the masking ratio from a uniform prior distribution ([0,1])
, and then samples the desired number of positions randomly.
This subjects the model to
Agiraffestanding on dirt ground near a tree.
X-LXMERT
X-LXMERT
Agiraffestanding on dirt ground near a tree. Agiraffestanding on dirt ground near a tree.
X-LXMERT         … …
Generator
Original Image
Reconstruction from GT
Sampling from LXMERT
X-LXMERT w/o uniform masking
X-LXMERT (ours)
DM-GAN
Agiraffestanding on dirt ground near a tree.
Caption (a) (b) (c) (d) (e) (f) a variety of masking ratios, and our experiments reveal that this greatly beneﬁts image generation. Updating pre-training data: L XMERT uses a variety of data to pre-train the model: QA data from multiple sources, caption data from C OCO and captions from Visual Genome (VG).
Since
X-L XMERT uses the CCC loss function, predicting visual features given questions like: “What is shown in the image?” is very ambiguous and results in models that cannot predict visual clusters.
Similarly, many captions from VG (e.g., “A bag” or “Glasses on the hair”) tend to describe small regions of the image and not the whole image, which makes them unsuited to train the CCC objective.
X-L XMERT drops QA data and the captions from
VG for its CCC objective for visual cluster prediction.
Removing this data helps signiﬁcantly.
5. Sampling Strategies for X-LXMERT
Given text input, predicting the entire set of visual features in one step does not produce good results.
Instead, we employ Gibbs sampling to iteratively sample features at different spatial locations.
In contrast to text generation, where left-to-right is considered a natural order, there is no natural order for generating images.
The grid sampling process starts with N 2 grids ﬁlled with the MASK special token.
The model then iteratively updates locations either one-by-one or multiple in parallel.
There are several sampling strategies for sampling locations on the square grid, primarily falling into two buckets: auto-regressive and parallel.
Autoregressive sampling
In
each iteration, a grid position is
sampled
masked
and predicted.
Then the corresponding
MASK
token is replaced with the predicted one, and the process is repeated until all locations are updated.
– TL → BR: Positions are sequentially chosen from top-left to bottom-right, similar to PixelRNN (van den Oord et al., 2016).
– Random (Liao et al., 2020):
Positions are selected in random order.
This is repeated K times.
Locations may be updated more than once.
Non-autoregressive sampling In each iteration, multiple positions are sampled, masked with MASK , predicted and then replaced.
– Mask-predict-K (Ghazvininejad et al., 2019):
This requires K sampling steps.
In the ﬁrst iteration, all N 2 locations are updated.
Then, we linearly decay the number of tokens updated per iteration.
For example, for a 2 × 2 grid whereby N 2 = 4 , if K = 4 then (4, 3, 2, 1) positions are updated in each iteration.
Within each iteration, positions with the lowest conﬁdence are updated.
Our experiments show that Mask-Predict-4 consistently produces good results across a variety of generation metrics and we propose using it for X-L XMERT .
Our uniform masking procedure makes the model robust to a varied number of masked locations.
This enables Mask-Predict to work well.
We notice that this sampling usually results in the primary objects being coarsely generated in the beginning followed by the rest of the details and background.
Experiments
We now present an analysis of X-L XMERT for discriminative and generative tasks.
Implementation details are provided in the appendix.
Visual Question Answering
Visual Reasoning
Methods
[Table]
pairwise
[Table]
VQA
[Table] [Table]
StackGAN 8.
[Table]
- - - - - - - - - - - PPGN
[Table]
- - - - - - - - - - - AttnGAN
[Table]
[Table] [Table]
[Table]
L XMERT - - - - - -
[Table]
[Table]
We train and evaluate models using the MS C OCO captioning dataset (Lin et al., 2014). We compare X-L XMERT with L XMERT and state-of-theart text-to-image generation methods: StackGAN (Zhang et al., 2018), PPGN (Nguyen et al., 2017),
AttnGAN (Xu et al., 2018), ControlGAN (Li et al., 2019), and DM-GAN (Zhu et al., 2019).
Image generation is a particularly difﬁcult task to evaluate, due to the variability in acceptable outputs for a given caption, as well as the subjective nature of perceiving image quality.
We present a suite of automated and manual metrics to compare models.
Automated Metrics: Evaluate image quality
We use Inception score (IS) (Salimans et al., 2016) to measure image diversity and Fr´echet Inception
Distance (FID) (Heusel et al., 2017) to measure authenticity; using Inception v3 (Szegedy et al., 2016) as a surrogate net.
Automated Metrics: Evaluate semantics
We use two variants of R-precision (Xu et al., 2018),
R-prec-easy and R-prec-hard to evaluate if the image is well conditioned on the input text.
Given a generated image, a positive caption and negatives,
R-precision measures the retrieval rate for the positive caption using a surrogate multi-modal network.
We use an independent surrogate - ViLBERT-MT (Lu et al., 2020) for this purpose.
R-prec-easy is the variant of R-precision with easy negatives (sampled randomly amongst the caption set).
R-prec-hard is the variant with hard negatives (swapping a word in a caption with another word within the same category, e.g., red ⇒ green).
We choose words from one of 4 categories: nouns (80 C OCO objects),verbs, 10 colors and 10 numbers.
The above automatic metrics, while cheap and reproducible, are noisy because they depend on imperfect surrogate models.
The ultimate measure of quality and semantics for image generation continues to be crowd-sourced human studies.
Human Study: Pairwise preferences
We conduct a human preference evaluations between
X-L XMERT and the best performing model in the automated metrics—DM-GAN.
We measure (1) Semantic preference by showing two image and asking annotators to select the one that best matches the source caption.
(2) Fidelity preference by showing the two images alone and asking which appears more realistic.
Both evaluations also allow a third option (Tie) to be selected.
For each evaluation, 5000 image pairs were used, and 357 unique crowdworkers participated in total (median annotations per worker—17).
Human Study: HUMMUS
The above pairwise test is very useful and widely used to evaluate generative models, but measuring new models becomes challenging, since they must compare to all old models.
To expand human evaluation, we present a novel metric to test semantic consistency between the caption and image inspired by masked token modeling, named - HUmans
Measuring seMantics Using maSking (H UMMUS ).
To compute
H UMMUS , human annotators are shown an image and its caption with a single word masked out.
They are asked to complete the partial caption based on information in the image, and a match is counted only when a majority of annotators supply the correct word.
The total score is reported as a ratio of these successful matches.
The task was run on 2800 image-caption pairs (2289 unique images), with 5 annotators per pair.
A total of 280 unique
[Figure]
while sitting on a couch.
Caption
Original
Ours
[Figure]
grassy [Figure] field with
[Figure]
lot of kites in the air.
A giraffe walking on a road with two cars approaching.
DM-GAN
A large painted clock tower in the middle of town.
Caption
Original
Ours DM-GAN
A woman attempting to ski on a flat hill
A full view of a home office with many computer screens.
[Figure]
crowdworkers completed the task, with a median of 13 images annotated per worker. A high H UMMUS score reveals that the generated images contain the corresponding semantics, well enough to be recognized.
The masked word is chosen from one ofcategories: 80 C OCO nouns, verbs and colors.
6. Evaluating Visual Question Answering
We train and evaluate models for visual question answering using the VQA2.0 (Goyal et al., 2019) and GQA (Hudson and Manning, 2019) datasets, which provide an image and a question and require the model to generate an answer.
6. Evaluating Visual Reasoning
We train and evaluate models for visual reasoning using the NLVR 2 (Suhr et al., 2019) dataset and report numbers on the dev and test-P splits.
The
NLVR 2 dataset requires models to look at two images and determine if an accompanying caption is True or False.
This is a particularly challenging dataset for present day vision and language models.
6. Results
Table 1 provides detailed metrics for X-L XMERT and baselines.
It also provides generation metrics for the original image in the dataset for the corresponding input text.
Note that X-L XMERT and
L XMERT +Grid are the only models that are able to produce results for all tasks.
Image Generation.
As seen, X-L XMERT significantly outperforms L XMERT across all generation metrics.
X-L XMERT even outperforms two specialized generation models, comparable to AttnGAN and ControlGAN.
Our model is lower compared to DM-GAN in terms of automated metric (IS and
FID), however, it is competitive with DM-GAN at semantic metric (R-prec-hard) 2 .
Note that X-L XMERT ’s image generator is much smaller than the one used by DM-GAN (1.7M vs 22.3M parameters).
While the transformer employed in X-L XMERT is large, it is a uniﬁed textual and visual encoder used for multiple tasks and is not ﬁnetuned for image generation.
We expect X-L XMERT ’s image quality to improve further when coupled with a larger image generator such as the one by DM-GAN.
Table 1 also presents H UMMUS scores.
Here we see that the semantics generated by X-L XMERT is on par with DM-GAN and still signiﬁcantly better than L XMERT .
All models are still a distance away from the original image.
H UMMUS matches on the lemmatized forms of masked words to allow for lexical variation, but it misses synonyms and other valid descriptors.
This causes the score for the original image to drop to its reported value.
See the appendix for R-prec-hard and HUMMUS broken down into categories.
Finally we present human pairwise preference scores between X-L XMERT and DM-GAN (its closest competitor).
Here we see that human anno-
A man dances on top of picnic tables while it snows.
A giraffe walking on a road with two cars approaching.
A full view of a home office with many computer screens.
A large painted clock tower in the middle of town.
caption # # # # # # # # # #140 # # # #
[Figure]
In summary, X-L XMERT ’s generation capabilities rival state of the art specialized generation models.
In fact, our human studies demonstrate that X-L XMERT produces better results than even
DM-GAN, its closest competitor.
Our analysis also shows the limitations of current automatic evaluation metric for text-to-image synthesis.
Visual Question Answering
Table 1 compares models on the VQA2.0 and GQA datasets.
Converting L XMERT to use grid inputs causes a slight or no drop, consistent with ﬁndings by Jiang et al.
but hugely simpliﬁes the pipeline.
X-L XMERT shows 1.5 - 2.5% drop on these datasets but note that its numbers are still very competitive.
Visual Reasoning
Table 1 compares models on
NLVR 2 dataset.
Consistent with VQA, grid inputs cause a slight drop.
X-L XMERT shows a roughly 2% drop but retains most of the massive jumps obtained by L XMERT on NLVR 2 compared to the previous generation of models.
Our implementation of X-L XMERT uses a small 8 × 8 grid.
Increasing the grid size will likely shrink gaps in VQA2.0, GQA and NLVR2 datasets as per the recent ﬁndings by Jiang et al.
Ablating X-LXMERT’s sampling strategies
Table 2 shows that X-L XMERT is fairly robust to sampling strategy, particularly for image semantics, with the exception of TL → BR which tends to produce worse results.
This is interesting in that
TL → BR is typically the default strategy used by practitioners.
However, note that the differences between the strategies are quite small.
6. Qualitative examples
Fig 3 shows qualitative examples by X-L XMERT compared to DM-GAN.
While the images lack ﬁne details, they do a reasonable job at preserving high level semantics, as revealed by the metrics.
We do not show images produced by L XMERT since they largely tend to be incomprehensible.
Fig 4 shows intermediately generated images by
X-L XMERT .
Interestingly, the model ﬁrst coarsely generates salient objects (ex. giraffe, monitors) in the caption followed by details and background.
Fig 5 shows captions generated from our model.
For each image, we sample text from X-L XMERT using Gibbs sampling.
We control the samples by providing different preﬁx word into the model.
Those preﬁx words are common starting word such as ‘A’, ‘The’, ‘What’, ‘Where’.
X-L XMERT can produce long meaningful captions as well as questions (like the ones in VQA datasets).
Conclusion
We develop a probing mechanism and ﬁnd that
L XMERT , a powerful vision-and-language trans- former model, is not able to generate meaningful images conditioned on text.
We present
X-L XMERT , a uniﬁed model for image generation, captioning, QA and visual reasoning.
A Qualitative samples
More qualitative samples
In Fig 6, we show more qualitative examples of images generated by
DM-GAN, reconstruction from ground truth clusters, L XMERT , our proposed X-L XMERT with different sampling strategies.
Image generation process animation
In supplementary materials, we attach an animated GIF ﬁle ( generation process.gif ) to demonstrate intermediate image generation process of our model.
We made the ﬁle with intermediate generation results of X-L XMERT with Randomsampling from 4 captions: ‘A man dances on top of picnic tables while it snows.’
, ‘A giraffe walking on a road with two cars approaching.’
, ‘A full view of a home ofﬁce with many computer screens.’
, and ‘A large painted clock tower in the middle of town.’.
B Source code
In supplemantary materials, we provide the source code that is capable of reproducing results in the paper.
However, we will clean it up further, and make it more accessible to researchers after this review period is complete.
C LXMERT / X-LXMERT details
For a fair comparison, we re-implement L XMERT and L XMERT with grid features.
Our models have 226.5M trainable parameters, slightly smaller than 228M of original L XMERT implementation due to weight sharing of MVFR head and MOC head.
We use PyTorch (Paszke et al., 2017) and Huggingface Transformers (Wolf et al., 2019) libraries for implementation.
C. LXMERT Architecture
L XMERT architecture consists of text embedder, object embedder, transformer backbone, and taskspeciﬁc heads.
Text
embedder
A text input is tokenized by
WordPiece Tokenizer (Wu et al., 2016) and special tokens CLS and EOS are concatenated: { CLS , w 1 , . . .
, w T , EOS } .
We use the same vocabulary used in BERT 3 and L XMERT with size 30522.
Text is truncated with maximum token length of 20, including two special tokens.
768-dimensional embedding is learned for each token and position.
Final text embedding is obtained by sum of token embedding and positional embedding.
Object embedder
An input image is resized within minimum length 800 and maximum length 1333 while preserving aspect ratio.
We use Faster
R-CNN trained on Visual Genome to extractbounding boxes from each image 4 .
We take fc feature, which is between RoI-Pool layer and ﬁnal object classiﬁcation head and has 2048 dimension.
This is encoded into 768 dimensional vector followed by layer norm (Ba et al., 2016).
Four bounding box coordinates ( x 0 , x 1 , y 0 , y 1 ) are [0 , 1] -normalized by width and height.
Then they are also encoded into 768 dimensional vectors with fully connected layer followed by layer norm.
Final object embedding is obtained by element-wise average of object and positional feature.
Transformer backbone
Transformer backbone of L XMERT consists of object relation encoder, language encoder and cross modality encoder, which are composed of 9 self-attention layer (Vaswani et al., 2017), 5 self-attention layer, and 5 crossattention layer respectively.
The self-attention layers are same as the ones used in BERT and the dimension of the layers is 768.
Task-speciﬁc heads
L XMERT is pretrained with ﬁve objectives 5 (MLM, MVFR, MOC, ITM, QA) as explained in Sec.
For MLM, MVFR, ITM,
QA task, a task head consisting of two fully connected layers with GeLU activation (Hendrycks and Gimpel, 2016) and layer norm is trained.
For
MOC task, a fully connected layer is applied on ouput of MVFR head, similar to original object detection pipeline 6 .
For MLM, MVFR, MOC tasks, task heads are applied on cross-modal encoder outputs corresponding to masked tokens.
For ITM,
QA tasks, tasks heads are applied on CLS token.
C. X-LXMERT Architecture X-L XMERT
shares most components with
L XMERT , except for minor modiﬁcations below.
A man dances on top of picnic tables while it snows.
Caption
Original
LXMERT
Random
EasyFirst
MaskPredict Reconstruction
Top Left -> Bottom
Right
A full view of a home office with many computer screens.
A giraffe walking on a road with two cars approaching.
A large painted clock tower in the middle of town.
DM-GAN
Object embedder → Grid embedder
We extract 8 × 8 grid features of fc6 layer of Faster
R-CNN, by giving positional information of 8 ×grids into RoI-Pool layer.
Then we quantize these features with nearest neighborhood search from 10,000 cluster centroids.
Remaining are same with object embedder of L XMERT .
MOC, MVFR tasks → CCC task
We replace
MOC, MVFR tasks with CCC task (see Sec. 5.1) for X-L XMERT .
For CCC head, we simply modify the output dimension of fully connected layer used in MOC task to the number of clusters (1600 → 10000).
C. Datasets
For pretraining, we use same datasets used in
L XMERT .
We use vision-and-language datasets whose images come from MS C OCO (Lin et al., 2014) or Visual Genome (Krishna et al., 2016).
Besides the two original captioning datasets, we also aggregate three large image question answering (image QA) datasets: VQA v2.0 (Goyal et al., 2019), GQA balanced version (Hudson and Manning, 2019), and VG-QA (Zhu et al., 2016).
Table 3 shows statistics of the datasets.
Note that
X-L XMERT only uses C OCO captions for CCC task.
C. Visual vocabulary clustering
To create visual vocabularies, we run K-means clustering on Faster R-CNN grid features of C OCO train2014 images.
train2014 has 82783 images, resulting 8 x 8 x 82783 =
5.3M grid features.
We use FAISS (Johnson et al., 2017) library for clustering.
We sample 2.6M features in training data and run 20 iteration, which takes 2 hours.
C. Training
We train L XMERT and X-L XMERT for 20 epochs with mixed precision using Apex 7 (opt-level O1 ).
We use AdamW optimizer (Loshchilov and Hutter, 2019) with ( β 1 , β 2 ) =
(0 . 9 , 0 . 999) and learning rate 1e-5 with 5% linear warmup schedule.
We use gradient clipping with maximum norm 1.
Training L XMERT takes 60 hours with batch size 1280, and training xlxmert takes 40 hours with batch size 920.
We use 4 Titan RTX GPUs ( 4 × 24 GB) for training both models.
C. Finetuning
During ﬁnetuning on VQA/GQA/NLVR 2 , a task head consisting of two fully connected layers with
GeLU activation and layer norm is trained along with pre-trained L XMERT and X-L XMERT .
For
VQA/GQA, the parameters are initialized from pretrained QA head.
We use AdamW optimizer with learning rate 5e-4 .
We train L XMERT and
X-L XMERT for 10 epochs for each task.
For
VQA/GQA/NLVR 2 , ﬁnetuning takes 3/5/1 hours respectively on 4 Titan RTX GPUs ( 4 × 24 GB). [Table]
D Generator details
Our image generation system adopts GAN (Goodfellow et al., 2014) framework and has two networks trained: generator and discriminator.
D. Generator Architecture
Our generator consists of multiple residual blocks following SNGAN (Miyato and Koyama, 2018).
The generator takes (quantized) 8 × 8 grid features of Faster R-CNN as input and outputs 256 ×
RGB images.
We use a generator with 5 residual blocks, where each block bilinearly-upsamples feature map by 2.
We use 32 channels of 3x3 kernel for every convolution layer in residual blocks.
Note that many existing generator architectures (Miyato and Koyama, 2018; Wang et al., 2018;
Karras et al., 2019a,b) have residual blocks starting from higher dimensions (eg. 512, 1024) in lowresolution then gradually decrease the dimension as feature maps are spatial upsampled.
However, we found that using ﬁxed-sized small dimension for all residual blocks makes training more stable.
Each residual block has spatially adaptive instance norm (SPADE)
(Park et al., 2019; Huang and Belongie, 2017) that guides the residual block using spatial information of 8 × 8 grid features.
After each spatially adaptive instance norm, we multiply spatial gaussian noise on feature maps to make model less focus on local texture following StyleGAN (Karras et al., 2019a).
We use spectral normalization (Miyato et al., 2018) after each convolution layer in generator.
Following StyleGAN-v2 (Karras et al., 2019b), we use skip connection for each residual block to generate ﬁnal output.
Our generator has 1.7M trainable parameters.
The detailed architecture of our generator is illustrated at Fig.
D. Discriminator Architecture
Discriminator also consists of multiple residual blocks.
We use a discriminator with 5 residual blocks, where each residual block downsamples feature map by 2.
We use 64 channels of 3x3 kernel for every convolution layer in residual blocks.
We use spectral normalization after each convolution layer in discriminator.
In contrasts to generator, discriminator (1) uses instance norm (Ulyanov et al., 2016) instead of adaptive instance norm, (2) does not gaussian noise multiplication and (3) does not use skip connection.
Output of the 5 residual blocks are 8 × 8 feature map.
Our discriminator have two heads taking these feature maps: (1) adversarial head spatially averaging 8 × 8 feature map and predicting whether input image is from original image domain or not and (2) classiﬁcation head predicting cluster ids of 8 × 8 spatial layouts from input image.
Our discriminator has 0.5M trainable parameters.
The detailed architecture of our discriminator is illustrated at Fig. 8.
D. Dataset
We train our model on C OCO train2014 split, which consits of 82783 images.
D. Training
Our generator and discrminator are trained with 4 losses: (1) hinge adversarial loss (Lim and Ye, 2017; Tran et al., 2017), (2) AC-GAN loss (Odena et al., 2017), (3) discriminator feature match loss (Wang et al., 2018) and (4) perceptual loss (Johnson et al., 2016) following (Park et al., 2019).
Following pix2pixHD (Wang et al., 2018), coefﬁcients for the losses are (1, 1, 10, 10) respectively.
Adversarial loss guides generator to output images close to original images.
The rest of the losses guide generator to output images close to speciﬁc target images using spatial layout inputs.
We use ResNet-50 (He
Visual features
[Figure]
⊕ ⊕ ⊕ ⊕ 3x
Conv 2x Upsample
Spatialcondition
C x H x W 32x8x
Spatialcondition
SPADE
Noise
LeakyReLU(0.2) 2x
Upsample 3x
Conv
SPADE
Noise
LeakyReLU(0.2) 3x
Conv ⊕ 1)
Generator Architecture 2) Generator Resblock
C x 2H x 2W Generated image 3 x 256 x32x8x ⊕ : Element-wise Addition
Resblock
Resblock Resblock
Resblock
Resblock 3x3 Conv 1x1 Conv 3x3 Conv 32x16x 32x32x 32x64x 32x128x 32x256x 32x8x 256x8x 2x
Upsample 1x1 Conv 2x
Upsample 2x Upsample 2x Upsample
Skip connection 3x
Conv 3x3 Conv 3x
Conv 3x
Conv
[Figure]
C x 2H x 2W
LeakyReLU(0.2) 3x
Conv
Instance Norm
LeakyReLU(0.2) 3x
Conv ½ AvgPool ⊕ 1) Discriminator Architecture 2)
Discriminator Resblock
C x H x W ⊕ : Element-wise Addition
Resblock
Resblock Resblock
Resblock
Resblock 32x16x 32x32x 32x64x 32x128x 32x8x ½ AvgPool 1x1 Conv
Input image 3 x
[Figure]
x
[Figure]
Global
[Figure]
3x
[Figure]
[Figure]
Adversarial head
[Figure]
et al., 2016) for perceptual loss.
Detail of losses are explained in Sec.
D.5.
We use Adam optimizer (Kingma and Ba, 2015) with ( β 1 , β 2 ) =
(0 , 0 . 999) and two-time update rule (Heusel et al., 2017) with learning rate of 0.0004 and 0.0001 for generator and discriminator respectively.
We train the image generator forepochs with batch size 96.
Training takes 15 hours on 8 NVIDIA Titan V GPUs ( 8 × 12 GB).
D. Losses
In below equations, ˆ X and X refer to generated image and target image respectively.
Adversarial loss
[Equation]
where D Adv is discriminator adversarial head.
AC-GAN loss
[Equation]
where D cls is discriminator classiﬁcation head.
Discriminator feature match loss
L GFM = (cid:88)
[Equation]
[Equation] where (cid:96) huber
[Equation]
if | x | ≤| x | − 0 .
5 , otherwise and D k is discriminator’s k-th resblock.
Perceptual loss
L GFM − E =
(cid:88)
k
[Equation]
| (5) where E k is ResNet-50 (He et al., 2016)’s
k-th resblock ( conv2 x , conv3 x , conv4 x , conv5 x ).
Total loss
L G = λ adv ∗ L Gadv + λ ACGAN ∗ L ACGAN + λ FM ∗ L GFM +
[Equation]
FM − E ∗ L GFM − E (6)
L D
[Equation]
adv
[Equation]
Dadv
[Equation] (7) where ( λ GAN , λ ACGAN , λ FM , λ FM − E ) =
E Evaluation details E. Image metrics
To calculate image metrics, we follow Xu et al.
(2018) and randomly sample 30000 images from
MS C OCO val2014 split and sample a caption for each image.
Then we generate images from those 30000 captions for each method.
We use subset of these 30000 captions for automatic image evaluation.
Inception Score (IS)
Following Zhu et al.
(2019), we use all 30000 generated images.
We use
OpenAI implementation 8 to calculate IS.
Fr´echet Inception Distance (FID)
Following
Zhu et al.
(2019), we use all 30000 generated images.
We use PyTorch port of ofﬁcial implementation 9 to calculate FID.
R -precision -easy
We use all 30000 generated images.
For R-precision-easy, we sample 99 negative captions for each caption, where all negative captions correspond to different val2014 images.
R-precision-hard
For each R-precision-hard category (noun/verb/color/number), we use 1000 randomly sampled caption that contains a category word.
Then we generate 9 negative captions by swapping the detected category word with another word with same category.
We use POS-tagging with spaCy 10 to ﬁnd category words from a caption.
We present per-category score of R-precision-hard at table 4. [Table]
https://github.com/ mseitzer/pytorch-fid/tree/ 802da3963113b5b5f8154e0e27580ee4c97460ab 10 https://spacy.io/
[Table]
Original Image
[Table] DM [Table] GAN (Zhu et al., 2019)
[Table]
L XMERT
[Table]
X-L XMERT
[Table]
X-L XMERT sampling variations:
Autoregressive
TL → BR
[Table]
Random
[Table]
Random-
[Table]
Easy-First
[Table]
Parallel
Mask-Predict-
[Table]
Mask
[Table]
= X-L XMERT
Mask-Predict-
[Table]
E. Human evaluation
We use Amazon Mechanical Turk 11 for human evaluation.
HUMMUS score
For each H UMMUS category (noun/verb/color), we use 100 randomly sampled images.
Then we mask out words in the same fashion as in R-precision-hard metric.
A total of 280 unique crowdworkers completed the task, with a median of 13 images annotated per worker.
We present per-category score of H UMMUS score at table 5.
Fig 9 shows screenshot of H UMMUS score (noun category) evaluation task.
[Table]
GAN
[Table]
Pairwise preference
For Semantic preference task, we ask annotators (1) ‘Which image best matches the caption?’
with caption.
For Fidelity preference task, we ask annotators ‘Which image looks more realistic?’
without providing the caption.
A total of 357 unique crowdworkers completed the task, with a median of 17 annotations performed per worker.
Fig 10 shows screenshot of Semantic preference evaluation task, and Fig 11 shows screenshot of
Fidelity preference evaluation task.