Multimodal Deep Learning
arXiv:2301.04856v1 [cs.CL] 12 Jan 2023
Contents
Preface v
Foreword 1
1 Introduction 3
1.1 Introduction to Multimodal Deep Learning . . . . . . . . . . 3
1.2 Outline of the Booklet . . . . . . . . . . . . . . . . . . . . . . 4
2 Introducing the modalities 7
2.1 State-of-the-art in NLP . . . . . . . . . . . . . . . . . . . . . 9
2.2 State-of-the-art in Computer Vision . . . . . . . . . . . . . . 33
2.3 Resources and Benchmarks for NLP, CV and multimodal tasks 54
3 Multimodal architectures 83
3.1 Image2Text . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
3.2 Text2Image . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100
3.3 Images supporting Language Models . . . . . . . . . . . . . . 125
3.4 Text supporting Vision Models . . . . . . . . . . . . . . . . . 146
3.5 Models for both modalities . . . . . . . . . . . . . . . . . . . 159
4 Further Topics 181
4.1 Including Further Modalities . . . . . . . . . . . . . . . . . . . 181
4.2 Structured + Unstructured Data . . . . . . . . . . . . . . . . . 197
4.3 Multipurpose Models . . . . . . . . . . . . . . . . . . . . . . 209
4.4 Generative Art . . . . . . . . . . . . . . . . . . . . . . . . . . 226
5 Conclusion 235
6 Epilogue 237
6.1 New influential architectures . . . . . . . . . . . . . . . . . . . 237
6.2 Creating videos . . . . . . . . . . . . . . . . . . . . . . . . . 238
7 Acknowledgements 239
iii
Preface
Author: Matthias Aßenmacher
FIGURE 1: LMU seal (left) style-transferred to Van Gogh’s Sunflower
painting (center) and blended with the prompt - Van Gogh, sunflowers -
via CLIP+VGAN (right).
In the last few years, there have been several breakthroughs in the methodologies used in Natural Language Processing (NLP) as well as Computer Vision
(CV). Beyond these improvements on single-modality models, large-scale multimodal approaches have become a very active area of research.
In this seminar, we reviewed these approaches and attempted to create a solid
overview of the field, starting with the current state-of-the-art approaches in
the two subfields of Deep Learning individually. Further, modeling frameworks
are discussed where one modality is transformed into the other Chapter 3.1
and Chapter 3.2), as well as models in which one modality is utilized to
enhance representation learning for the other (Chapter 3.3 and Chapter 3.4).
To conclude the second part, architectures with a focus on handling both
modalities simultaneously are introduced (Chapter 3.5). Finally, we also cover
other modalities (Chapter 4.1 and Chapter 4.2) as well as general-purpose
multi-modal models (Chapter 4.3), which are able to handle different tasks on
different modalities within one unified architecture. One interesting application
(Generative Art, Chapter 4.4) eventually caps off this booklet.
v
vi Preface
FIGURE 2: Creative Commons License
This book is licensed under the Creative Commons AttributionNonCommercial-ShareAlike 4.0 International License.
Foreword
Author: Matthias Aßenmacher
This book is the result of an experiment in university teaching. We were
inspired by a group of other PhD Students around Christoph Molnar, who
conducted another seminar on Interpretable Machine Learning in this format.
Instead of letting every student work on a seminar paper, which more or less
isolated from the other students, we wanted to foster collaboration between
the students and enable them to produce a tangible outout (that isn’t written
to spend the rest of its time in (digital) drawers). In the summer term 2022,
some Statistics, Data Science and Computer Science students signed up for
our seminar entitled “Multimodal Deep Learning” and had (before kick-off
meeting) no idea what they had signed up for: Having written an entire book
by the end of the semester.
We were bound by the examination rules for conducting the seminar, but
otherwise we could deviate from the traditional format. We deviated in several
ways:
1. Each student project is a chapter of this booklet, linked contentwise
to other chapers since there’s partly a large overlap between the
topics.
2. We gave challenges to the students, instead of papers. The challenge
was to investigate a specific impactful recent model or method from
the field of NLP, Computer Vision or Multimodal Learning.
3. We designed the work to live beyond the seminar.
4. We emphasized collaboration. Students wrote the introduction to
chapters in teams and reviewed each others individual texts.
Technical Setup
The book chapters are written in the Markdown language. The simulations,
data examples and visualizations were created with R (R Core Team, 2018). To
combine R-code and Markdown, we used rmarkdown. The book was compiled
1
2 0 Foreword
with the bookdown package. We collaborated using git and github. For details,
head over to the book’s repository.
1
Introduction
Author: Nadja Sauter
Supervisor: Matthias Aßenmacher
1.1 Introduction to Multimodal Deep Learning
There are five basic human senses: hearing, touch, smell, taste and sight.
Possessing these five modalities, we are able to perceive and understand the
world around us. Thus, “multimodal” means to combine different channels
of information simultaneously to understand our surroundings. For example,
when toddlers learn the word “cat”, they use different modalities by saying
the word out loud, pointing on cats and making sounds like “meow”. Using the
human learning process as a role model, artificial intelligence (AI) researchers
also try to combine different modalities to train deep learning models. On a
superficial level, deep learning algorithms are based on a neural network that
is trained to optimize some objective which is mathematically defined via the
so-called loss function. The optimization, i.e. minimizing the loss, is done via
a numerical procedure called gradient descent. Consequently, deep learning
models can only handle numeric input and can only result in a numeric output.
However, in multimodal tasks we are often confronted with unstructured data
like pictures or text. Thus, the first major problem is how to represent the
input numerically. The second issue with regard to multimodal tasks is how
exactly to combine different modalities. For instance, a typical task could be
to train a deep learning model to generate a picture of a cat. First of all,
the computer needs to understand the text input “cat” and then somehow
translate this information into a specific image. Therefore, it is necessary to
identify the contextual relationships between words in the text input and the
spatial relationships betweent pixels in the image output. What might be easy
for a toddler in pre-school, is a huge challenge for the computer. Both have to
learn some understanding of the word “cat” that comprises the meaning and
appearance of the animal. A common approach in modern deep learning is to
generate embeddings that represent the cat numerically as a vector in some
latent space. However, to achieve this, different approaches and algorithmic
3
4 1 Introduction
architectures have been developed in recent years. This book gives an overview
of the different methods used in state-of-the-art (SOTA) multimodal deep
learning to overcome challenges arising from unstructured data and combining
inputs of different modalities.
1.2 Outline of the Booklet
Since multimodal models often use text and images as input or output, methods
of Natural Language Processing (NLP) and Computer Vision (CV) are introduced as foundation in Chapter 2. Methods in the area of NLP try to handle
text data, whereas CV deals with image processing. With regard to NLP (subsection 2.1), one concept of major importance is the so-called word embedding,
which is nowadays an essential part of (nearly) all multimodal deep learning
architectures. This concept also sets the foundation for transformer-based
models like BERT (Devlin et al., 2018a), which achieved a huge improvement
in several NLP tasks. Especially the (self-)attention mechanism (Vaswani et al.,
2017a) of transformers revolutionized NLP models, which is why most of them
rely on the transformer as a backbone. In Computer Vision (subsection 2.2)
different network architectures, namely ResNet (He et al., 2015), EfficientNet
(Tan and Le, 2019a), SimCLR (Chen et al., 2020a) and BYOL (Grill et al.,
2020b), will be introduced. In both fields it is of great interest to compare the
different approaches and their performance on challenging benchmarks. For
this reason, the last subsection 2.3 of Chapter 2 gives an overall overview of
different data sets, pre-training tasks and benchmarks for CV as well as for
NLP.
The second Chapter (see 3) focuses on different multimodal architectures,
covering a wide variety of how text and images can be combined. The presented
models combine and advance different methods of NLP and CV. First of all,
looking at Img2Text tasks (subsection 3.1), the data set Microsoft COCO for
object recognition (Lin et al., 2014a) and the meshed-memory transformer for
Image Captioning (M2 Transformer) (Cornia et al., 2019) will be presented.
Contrariwise, researchers developed methods to generate pictures based on a
short text prompt (subsection 3.2). The first models accomplishing this task
were generative adversarial networks (GANs) (Goodfellow et al., 2014b) and
Variational Autoencoders (VAEs) (Kingma and Welling, 2019). These methods
were improved in recent years and today’s SOTA transformer architectures and
text-guided diffusion models like DALL-E (Ramesh et al., 2021a) and GLIDE
(Nichol et al., 2021a) achieve remarkable results. Another interesting question
is how images can be utilized to support language models (subsection 3.3). This
can be done via sequential embeddings, more advanced grounded embeddings
or, again, inside transformers. On the other hand, one can also look at text
1.2 Outline of the Booklet 5
supporting CV models like CLIP (Radford et al., 2021b), ALIGN (Jia et al.,
2021a) and Florence (Yuan et al., 2021) (subsection 3.4). They use foundation
models meaning reusing models (e.g. CLIP inside DALL-E 2) as well as a
contrastive loss for connecting text with images. Besides, zero-shooting makes
it possible to classify new and unseen data without expensive fine-tuning.
Especially the open-source architecture CLIP (Radford et al., 2021b) for image
classification and generation attracted a lot of attention last year. In the end
of the second chapter, some further architectures to handle text and images
simultaneously are introduced (subsection 3.5). For instance, Data2Vec uses
the same learning method for speech, vision and language and in this way aims
to find a general approach to handle different modalities in one architecture.
Furthermore, VilBert (Lu et al., 2019a) extends the popular BERT architecture
to handle both image and text as input by implementing co-attention. This
method is also used in Google’s Deepmind Flamingo (Alayrac et al., 2022). In
addition, Flamingo aims to tackle multiple tasks with a single visual language
model via few-shot learning and freezing the pre-trained vision and language
model.
In the last chapter (see 4), methods are introduced that are also able to handle
modalities other than text and image, like e.g. video, speech or tabular data.
The overall goal here is to find a general multimodal architecture based on
challenges rather than modalities. Therefore, one needs to handle problems
of multimodal fusion and alignment and decide whether you use a join or
coordinated representation (subsection 4.1). Moreover we go more into detail
about how exactly to combine structured and unstructured data (subsection
4.2). Therefore, different fusion strategies which evolved in recent years will be
presented. This is illustrated in this book by two use cases in survival analysis
and economics. Besides this, another interesting research question is how to
tackle different tasks in one so called multi-purpose model (subsection 4.3) like
it is intended to be created by Google researchers (Barham et al., 2022) in
their “Pathway” model. Last but not least, we show one exemplary application
of Multimodal Deep Learning in the arts scene where image generation models
like DALL-E (Ramesh et al., 2021a) are used to create art pieces in the area
of Generative Arts (subsection 4.4).
2
Introducing the modalities
Authors: Cem Akkus, Vladana Djakovic, Christopher Benjamin Marquardt
Supervisor: Matthias Aßenmacher
Natural Language Processing (NLP) has existed for about 50 years, but
it is more relevant than ever. There have been several breakthroughs in
this branch of machine learning that is concerned with spoken and written
language. For example, learning internal representations of words was one of the
greater advances of the last decade. Word embeddings (Mikolov et al. (2013a),
Bojanowski et al. (2016)) made it possible and allowed developers to encode
words as dense vectors that capture their underlying semantic content. In this
way, similar words are embedded close to each other in a lower-dimensional
feature space. Another important challenge was solved by Encoder-decoder
(also called sequence-to-sequence) architectures Sutskever et al. (2014), which
made it possible to map input sequences to output sequences of different lengths.
They are especially useful for complex tasks like machine translation, video
captioning or question answering. This approach makes minimal assumptions
on the sequence structure and can deal with different word orders and active,
as well as passive voice.
A definitely significant state-of-the-art technique is Attention Bahdanau et al.
(2014), which enables models to actively shift their focus – just like humans
do. It allows following one thought at a time while suppressing information
irrelevant to the task. As a consequence, it has been shown to significantly
improve performance for tasks like machine translation. By giving the decoder
access to directly look at the source, the bottleneck is avoided and at the
same time, it provides a shortcut to faraway states and thus helps with the
vanishing gradient problem. One of the most recent sequence data modeling
techniques is Transformers (Vaswani et al. (2017b)), which are solely based on
attention and do not have to process the input data sequentially (like RNNs).
Therefore, the deep learning model is better in remembering context-induced
earlier in long sequences. It is the dominant paradigm in NLP currently and
even makes better use of GPUs, because it can perform parallel operations.
Transformer architectures like BERT (Devlin et al., 2018b), T5 (Raffel et al.,
2019a) or GPT-3 (Brown et al., 2020) are pre-trained on a large corpus and can
be fine-tuned for specific language tasks. They have the capability to generate
stories, poems, code and much more. With the help of the aforementioned
7
8 2 Introducing the modalities
breakthroughs, deep networks have been successful in retrieving information
and finding representations of semantics in the modality text. In the next
paragraphs, developments for another modality image are going to be presented.
Computer vision (CV) focuses on replicating parts of the complexity of the
human visual system and enabling computers to identify and process objects
in images and videos in the same way that humans do. In recent years it has
become one of the main and widely applied fields of computer science. However,
there are still problems that are current research topics, whose solutions depend
on the research’s view on the topic. One of the problems is how to optimize
deep convolutional neural networks for image classification. The accuracy
of classification depends on width, depth and image resolution. One way to
address the degradation of training accuracy is by introducing a deep residual
learning framework (He et al., 2015). On the other hand, another less common
method is to scale up ConvNets, to achieve better accuracy is by scaling up
image resolution. Based on this observation, there was proposed a simple yet
effective compound scaling method, called EfficientNets (Tan and Le, 2019a).
Another state-of-the-art trend in computer vision is learning effective visual
representations without human supervision. Discriminative approaches based
on contrastive learning in the latent space have recently shown great promise,
achieving state-of-the-art results, but the simple framework for contrastive
learning of visual representations, which is called SimCLR, outperforms previous work (Chen et al., 2020a). However, another research proposes as an
alternative a simple “swapped” prediction problem where we predict the code
of a view from the representation of another view. Where features are learned
by Swapping Assignments between multiple Views of the same image (SwAV)
(Caron et al., 2020). Further recent contrastive methods are trained by reducing
the distance between representations of different augmented views of the same
image (‘positive pairs’) and increasing the distance between representations
of augmented views from different images (‘negative pairs’). Bootstrap Your
Own Latent (BYOL) is a new algorithm for self-supervised learning of image
representatios (Grill et al., 2020b).
Self-attention-based architectures, in particular, Transformers have become
the model of choice in natural language processing (NLP). Inspired by NLP
successes, multiple works try combining CNN-like architectures with selfattention, some replacing the convolutions entirely. The latter models, while
theoretically efficient, have not yet been scaled effectively on modern hardware
accelerators due to the use of specialized attention patterns. Inspired by the
Transformer scaling successes in NLP, one of the experiments is applying a
standard Transformer directly to the image (Dosovitskiy et al., 2020b). Due
to the widespread application of computer vision, these problems differ and
are constantly being at the center of attention of more and more research.
With the rapid development in NLP and CV in recent years, it was just a
question of time to merge both modalities to tackle multi-modal tasks. The
2.1 State-of-the-art in NLP 9
release of DALL-E 2 just hints at what one can expect from this merge in
the future. DALL-E 2 is able to create photorealistic images or even art from
any given text input. So it takes the information of one modality and turns it
into another modality. It needs multi-modal datasets to make this possible,
which are still relatively rare. This shows the importance of available data
and the ability to use it even more. Nevertheless, all modalities are in need
of huge datasets to pre-train their models. It’s common to pre-train a model
and fine-tune it afterwards for a specific task on another dataset. For example,
every state-of-the-art CV model uses a classifier pre-trained on an ImageNet
based dataset. The cardinality of the datasets used for CV is immense, but
the datasets used for NLP are of a completely different magnitude. BERT uses
the English Wikipedia and the Bookscorpus to pre-train the model. The latter
consists of almost 1 billion words and 74 million sentences. The pre-training of
GPT-3 is composed of five huge corpora: CommonCrawl, Books1 and Books2,
Wikipedia and WebText2. Unlike language model pre-training that can leverage
tremendous natural language data, vision-language tasks require high-quality
image descriptions that are hard to obtain for free. Widely used pre-training
datasets for VL-PTM are Microsoft Common Objects in Context (COCO),
Visual Genome (VG), Conceptual Captions (CC), Flickr30k, LAION-400M
and LAION-5B, which is now the biggest openly accessible image-text dataset.
Besides the importance of pre-training data, there must also be a way to
test or compare the different models. A reasonable approach is to compare
the performance on specific tasks, which is called benchmarking. A nice feature of benchmarks is that they allow us to compare the models to a human
baseline. Different metrics are used to compare the performance of the models. Accuracy is widely used, but there are also some others. For CV the
most common benchmark datasets are ImageNet, ImageNetReaL, CIFAR10(0), OXFORD-IIIT PET, OXFORD Flower 102, COCO and Visual Task
Adaptation Benchmark (VTAB). The most common benchmarks for NLP are
General Language Understanding Evaluation (GLUE), SuperGLUE, SQuAD
1.1, SQuAD 2.0, SWAG, RACE, ReCoRD, and CoNLL-2003. VTAB, GLUE
and SuperGLUE also provide a public leader board. Cross-modal tasks such as
Visual Question Answering (VQA), Visual Commonsense Reasoning (VCR),
Natural Language Visual Reasoning (NLVR), Flickr30K, COCO and Visual
Entailment are common benchmarks for VL-PTM.
2.1 State-of-the-art in NLP
Author: Cem Akkus
Supervisor: Matthias Aßenmacher
10 2 Introducing the modalities
2.1.1 Introduction
Natural Language Processing (NLP) exists for about 50 years, but it is more
relevant than ever. There have been several breakthroughs in this branch
of machine learning that is concerned with spoken and written language. In
this work, the most influential ones of the last decade are going to be presented. Starting with word embeddings, which efficiently model word semantics.
Encoder-decoder architectures represent another step forward by making minimal assumptions about the sequence structure. Next, the attention mechanism
allows human-like focus shifting to put more emphasis on more relevant parts.
Then, the transformer applies attention in its architecture to process the
data non-sequentially, which boosts the performance on language tasks to
exceptional levels. At last, the most influential transformer architectures are
recognized before a few current topics in natural language processing are
discussed.
2.1.2 Word Embeddings
As mentioned in the introduction, one of the earlier advances in NLP is
learning word internal representations. Before that, a big problem with text
modelling was its messiness, while machine learning algorithms undoubtedly
prefer structured and well-defined fixed-length inputs. On a granular level, the
models rather work with numerical than textual data. Thus, by using very
basic techniques like one-hot encoding or bag-of-words, a text is converted
into its equivalent vector of numbers without losing information.
In the example depicting one-hot encoding (see Figure 2.1), there are ten
simple words and the dark squares indicate the only index with a non-zero
value.
FIGURE 2.1: Ten one-hot encoded words (Source: Pilehvar and CamachoCollados (2021))
In contrast, there are multiple non-zero values while using bag-of-words, which
is another way of extracting features from text to use in modelling where we
measure if a word is present from a vocabulary of known words. It is called
2.1 State-of-the-art in NLP 11
bag-of-words because the order is disregarded here.
Treating words as atomic units has some plausible reasons, like robustness and
simplicity. It was even argued that simple models on a huge amount of data
outperform complex models trained on less data. However, simple techniques
are problematic for many tasks, e.g. when it comes to relevant in-domain data
for automatic speech recognition. The size of high-quality transcribed speech
data is often limited to just millions of words, so simply scaling up simpler
models is not possible in certain situations and therefore more advanced
techniques are needed. Additionally, thanks to the progress of machine
learning techniques, it is realistic to train more complex models on massive
amounts of data. Logically, more complex models generally outperform basic
ones. Other disadvantages of classic word representations are described by the
curse of dimensionality and the generalization problem. The former becomes a
problem due to the growing vocabulary equivalently increasing the feature
size. This results in sparse and high-dimensional vectors. The latter occurs
because the similarity between words is not captured. Therefore, previously
learned information cannot be used. Besides, assigning a distinct vector to
each word is a limitation, which becomes especially obvious for languages with
large vocabularies and many rare words.
To combat the downfalls of simple word representations, word embeddings
enable to use efficient and dense representations in which similar words have a
similar encoding. So words that are closer in the vector space are expected to
be similar in meaning. An embedding is hereby defined as a vector of floating
point values (with the length of the vector being a hyperparameter). The
values for the embedding are trainable parameters which are learned similarly
to a model learning the weights for a dense layer. The dimensionality of the
word representations is typically much smaller than the number of words in
the dictionary. For example, Mikolov et al. (2013a) called dimensions between
50-100 modest for more than a few hundred million words. For small data
sets, dimensionality for the word vectors could start at 8 and go up to 1024
for larger data sets. It is expected that higher dimensions can rather pick up
intricate relationships between words if given enough data to learn from.
For any NLP tasks, it is sensible to start with word embeddings because
it allows to conveniently incorporate prior knowledge into the model and
can be seen as a basic form of transfer learning. It is important to note
that even though embeddings attempt to represent the meaning of words
and do that to an extent, the semantics of the word in a given context
cannot be captured. This is due to the words having static precomputed
representations in traditional embedding techniques. Thus, the word
"bank" can either refer to a financial institution or a river bank. Contex-
12 2 Introducing the modalities
FIGURE 2.2: Three-dimensional word embeddings (Source: Pilehvar and
Camacho-Collados (2021)).
tual embedding methods offer a solution, but more about them will follow later.
It should be noted that words can have various degrees of similarity. In the
context of inflectional languages, it becomes obvious because words are adjusted
to articulate grammatical categories. For example, in a subspace of the original
vector, nouns that have similar endings can be found. However, it even exceeds
simple syntactic regularities. With straightforward operations on the word
vectors, it can be displayed that vector(King)−vector(Man)+vector(Woman)
equals a vector that is closest in vector space (and therefore in meaning) to
the word "Queen". A simple visualization of this relationship can be seen
in the left graph below (see Figure 2.3). The three coordinate systems are
representations of higher dimensions that are depicted in this way via dimension
reduction techniques. Furthermore, the verb-to-tense relationship is expressed
in the middle graphic, which extends the insight from before referring to the
word endings being similar because in this instance the past tenses of both
verbs walking and swimming are not similar in structure. Additionally, on the
right side of the figure, there is a form of the commonly portrayed and easily
understood Country-Capital example (see Mikolov et al. (2013a)).
FIGURE 2.3: Three types of similarities as word embeddings (Source: Google
(2022)).
2.1 State-of-the-art in NLP 13
Another way of using vector representations of words is in the field of translations. It has been presented that relations can be drawn from feature spaces of
different languages. In below, the distributed word representations of numbers
between English and Spanish are compared. In this case, the same numbers
have similar geometric arrangements, which suggests that mapping linearly
between vector spaces of languages is feasible. Applying this simple method
for a larger set of translations in English and Spanish led to remarkable results
- achieving almost 90 % precision.
FIGURE 2.4: Representations of numbers in English and Spanish (Source:
Mikolov et al. (2013c)).
This technique was then used for other experiments. One use case is the
detection of dictionary errors. Taking translations from a dictionary and
computing their geometric distance returns a confidence measure. Closely
evaluating the translations with low confidence and outputting an alternative
(one that is closest in vector space) results in a plain way to assess dictionary
translations. Furthermore, training the word embeddings on a large corpora
makes it possible to give sensible out-of-dictionary predictions for words.
This was tested by randomly removing a part of the vocabulary before.
Taking a look at the predictions revealed that they were often to some
extent related to the translations with regard to meaning and semantics.
Despite the accomplishments in other tasks, translations between distant
languages exposed shortcomings of word embeddings. For example, the
accuracy for translations between English and Vietnamese seemed significantly lower. This can be ascribed to both languages not having a good
one-to-one correspondence because the concept of a word is different than
in English. In addition, the used Vietnamese model contains numerous synonyms, which complicates making exact predictions (see Mikolov et al. (2013c)).
Turning the attention to one of the most impactful embedding techniques,
word2vec. It was proposed by Mikolov et al. (2013a) and is not a singular
algorithm. It can rather be seen as a family of model architectures and optimizations to learn word representations. Word2vec’s popularity also stems
from its success on multiple downstream natural language processing tasks.
14 2 Introducing the modalities
It has a very simple structure which is based on a basic feed forward neural
network. They published multiple papers (see Mikolov et al. (2013a)], Mikolov
et al. (2013c), Mikolov et al. (2013d)) that are stemming around two different
but related methods for learning word embeddings (see Figure 2.5). Firstly,
the Continuous bag-of-words model aims to predict the middle word based on
surrounding context words. Hence, it considers components before and after
the target word. As the order of words in the context is not relevant, it is
called a bag-of-words model. Secondly, the Continuous skip-gram model only
considers the current word and predicts others within a range before and after
it in the same sentence. Both of the models use a softmax classifier for the
output layer.
FIGURE 2.5: CBOW and Skip-gram architecture (Source: Mikolov et al.
(2013a)).
Then, Bojanowski et al. (2016) built on skip-gram models by accounting for
the morphology (internal structure) of words. A different classical embedding
architecture that has to be at least mentioned is the GloVe model, which
does not use a neural network but incorporates local context information with
global co-occurrence statistics.
2.1.3 Encoder-Decoder
The field of natural language processing is concerned with a variety of different
tasks surrounding text. Depending on the type of NLP problem, the network
may be confronted with variable length sequences as input and/or output.
This is the case for many compelling applications, such as question answering,
dialogue systems or machine translation. In the following, many examples
will explore machine translations in more detail, since it is a major problem
domain. Regarding translation tasks, it becomes obvious that input sequences
need to be mapped to output sequences of different lengths. To manage this
2.1 State-of-the-art in NLP 15
type of input and output, a design with two main parts could be useful.
The first one is called the encoder because, in this part of the network, a
variable length input sequence is transformed into a fixed state. Next, the
second component called the decoder maps the encoded state to an output of
a variable length sequence. As a whole, it is known as an encoder-decoder or
sequence-to-sequence architecture and has become an effective and standard
approach for many applications which even recurrent neural networks with
gated hidden units have trouble solving successfully. Deep RNNs may have
a chance, but different architectures like encoder-decoder have proven to be
the most effective. It can even deal with different word orders and active,
as well as passive voice (Sutskever et al., 2014). A simplified example of the
encoder-decoder model can be seen in 2.6.
FIGURE 2.6: Translation through simplified seq2seq model (Source: Manning
et al. (2022)).
Before going through the equations quantifying the concepts, it makes sense
to examine the sequence-to-sequence design proposed by Cho et al. (2014).
An encoder-RNN processes the input sequence of length nx and computes a
fixed-length context vector C, which is usually the final hidden state of the
encoder or a simple function of the hidden states. After the input sequence is
processed, it is added to the hidden state and passed forward in time through
the recurrent connections between the hidden states in the encoder. Despite
the context vector usually being a simple function of the last hidden state,
its role cannot be underestimated. Specifically, the encoded state summarizes
important information from the input sequence, e.g. the intent in a question
answering task or the meaning of a text in the case of machine translation.
After the context is passed to every hidden state of the decoder, the decoder
RNN uses this information to produce the target sequence of length ny, which
can of course vary from nx.
At the latest through the above illustration, it is clear that the decoder is
particularly interesting to look at in the form of equations. The notation mainly
follows Cho et al. (2014). The decoder is another type of RNN which is trained
to predict the target based on the hidden state at the last time step. However,
unlike regular RNNs, it is also conditioned on the output of the last time
step (yt−1) and a summary of the input c. Therefore, the hidden state of the
decoder is computed by:
16 2 Introducing the modalities
FIGURE 2.7: Encoder-decoder architecture (Source: Cho et al. (2014)).
h
[t]
d = f(h
[t−1]
d
, y[t−1], c).
Similarly, each conditional probability is given by the following, where f is
a non-linear activation function (and must produce probabilities in , e.g. the
softmax function):
P(y
[t]
|y
[1], . . . , y[t−1], c) = f(h
[t]
d
, y[t−1], c).
The two parts are jointly trained to maximize the conditional log-likelihood,
where θ denotes the set of model parameters and (xn, yn) is an (input sequence,
output sequence) pair from the training set with size N:
max
θ
1
N
X
N
n=1
log pθ(yn|xn).
The best probability is usually found by using the beam search algorithm.
The core idea of it is that on each step of the decoder, we keep track of the k
most probable partial translations (which are called hypotheses).
Examining the translation presented in with hidden units unrolled through time
could look like in 2.8. In particular, multiple hidden layers are recommended
by the researchers. The idea is that lower layers compute lower-level features
and higher layers compute higher-level features.
Gated recurrent networks, especially long short-term memory networks, have
2.1 State-of-the-art in NLP 17
FIGURE 2.8: Translation through seq2seq model (Source: Manning et al.
(2022)).
been found to be effective in both components of the sequence-to-sequence
architecture. Furthermore, it was revealed that deep LSTMs significantly
outperform shallow LSTMs. Each additional layer reduced perplexity by nearly
10%, possibly due to their much larger hidden state. For example, Sutskever
et al. (2014) used deep LSTMs with 4 layers and 1000 cells at each layer for
1000-dimensional word embeddings. Thus, in total, 8000 real numbers are
used to represent a sentence. For simplification, the neural networks are in the
following referred to as RNNs which is not contradicting the insights of this
paragraph as LSTMs are a type of gated RNNS (Sutskever et al., 2014).
2.1.4 Attention
Although encoder-decoder architectures simplified dealing with variable length
sequences, they also caused complications. Due to their design, the encoding
of the source sentence is a single vector representation (context vector). The
problem is that this state must compress all information about the source
sentence in a single vector and is commonly referred to as the bottleneck
problem. To be precise, the entire semantics of arbitrarily long sentences
need to be wrapped into a single hidden state. Moreover, it constitutes a
different learning problem because the information needs to be passed between
numerous time steps. This leads to vanishing gradients within the network
as a consequence of factors less than 1 multiplied with each other at every
point. To illustrate, the last sentence is an ideal example of one in which an
encoder-decoder approach could have difficulty coping. In particular, if the
sentences are longer than the ones in the training corpus (Manning et al., 2022).
18 2 Introducing the modalities
Due to the aforementioned reasons, an extension to the sequence-to-sequence
architecture was proposed by Bahdanau et al. (2014), which learns to
align and translate jointly. For every generated word, the model scans
through some positions in the source sentence where the most relevant
information is located. Afterwards, based on the context around and the
previously generated words, the model predicts the target word for the
current time step. This approach is called attention, as it emulates human-like
(cognitive) attention. As a result of directly looking at the source and
bypassing the bottleneck, it provides a solution to the problem. Then, it
mitigates the vanishing gradient problem, since there is now a shortcut
to faraway states. Consequently, incorporating the attention mechanism
has been shown to considerably boost the performance of models on NLP tasks.
A walkthrough of the example below should resolve any outstanding questions
regarding the procedure of the attention mechanism. The source sentence is
seen on the bottom left, which is given in French and acts as the input for the
encoder-RNN (in red). Then, the attention scores (in blue) are computed by
taking the dot product between the previous output word and input words.
Next, the softmax function turns the scores into a probability distribution (in
pink). They are used to take a weighted sum of the encoder’s hidden states
and form the attention output, which mostly contains information from the
hidden states that received high attention. Afterwards, the attention output
is concatenated with the decoder hidden state (in green), which is applied
to compute the decoder output as before. In some scenarios, the attention
output is also fed into the decoder (along with the usual decoder input). This
specific example was chosen because "entarter" means "to hit someone with a
pie" and is therefore a word that needs to be translated with many words. As
a consequence of no existing direct equivalents for this phrase, it is expected
that there is not only one nearly non-zero score. In this snapshot, the attention
distribution can be seen to have two significant contributors.
The following equations aim to compactly represent the relations brought
forward in the last paragraphs and mainly follow Manning et al. (2022). The
attention scores e
[t] are computed by scalarly combining the hidden state of
the decoder with all of the hidden states of the encoder:
e
[t] = [(h
[t]
d
)
T h
[1]
e
, . . . ,(h
[t]
d
)
T h
[N]
e
].
Besides the basic dot-product attention, there are also other ways to calculate
the attention scores, e.g. through multiplicative or additive attention. Although
they will not be further discussed at this point, it makes sense to at least
mention them. Then, applying the softmax to the scalar scores results in the
attention distribution α
[t]
, a probability distribution whose values sum up to
1:
2.1 State-of-the-art in NLP 19
FIGURE 2.9: Translation process with attention mechanism (Source: Manning et al. (2022)).
α
[t] = sof tmax(e
[t]
).
Next, the attention output a
[t]
is obtained by the attention distribution acting
as a weight for the encoder hidden states:
a
[t] =
X
N
i=1
α
[t]
i he,i.
Concatenating attention output with decoder hidden state and proceeding as
in the non-attention sequence-to-sequence model are the final steps:
o
[t] = f(a
[t]h
[t]
d
).
By visualizing the attention distribution, also called alignments (see Bahdanau
et al. (2014)), it is easy to observe what the decoder was focusing on and
understand why it chose a specific translation. The x-axis of the plot of below
corresponds to the words in the source sentence (English) and the y-axis to
the words in the generated translation (French). Each pixel shows the weight
of the source word for the respective target word in grayscale, where 0 is black
and 1 is white. As a result, which positions in the source sentence were more
relevant when generating the target word becomes apparent. As expected,
the alignment between English and French is largely monotonic, as the pixels
are brighter, and therefore the weights are higher along the main diagonal
of the matrix. However, there is an exception because adjectives and nouns
20 2 Introducing the modalities
are typically ordered differently between the two languages. Thus, the model
(correctly) translated "European Economic Area" into "zone économique
européene". By jumping over two words ("European" and "Economic"), it
aligned "zone" with "area". Then, it looked one word back twice to perfect
the phrase "zone économique européene". Additional qualitative analysis has
shown that the model alignments are predominantly analogous to our intuition.
FIGURE 2.10: Attention alignments (Source: Bahdanau et al. (2014)).
2.1.5 Transformer
For this section, Manning et al. (2022) constitutes the main source.
RNNs are unrolled from one side to the other. Thus, from left to right and
right to left. This encodes linear locality, which is a useful heuristic because
nearby words often affect each other’s meaning. But how is it when distant
words need to interact with each other? For instance, if we mention a person
at the beginning of a text portion and refer back to them only at the very
end, the whole text in between needs to be tracked back (see below). Hence,
RNNs take O(sequence length) steps for distant word pairs to interact. Due to
gradient problems, it is therefore hard to learn long-distance dependencies. In
addition, the linear order is ingrained. Even though, as known, the sequential
structure does not tell the whole story.
GPUs can perform multiple calculations simultaneously and could help to
reduce the execution time of the deep learning algorithm massively. However,
forward and backward passes lack parallelizability in recurrent models and have
O(sequence length). To be precise, future hidden states cannot be computed in
full before past states have been computed. This inhibits training on massive
2.1 State-of-the-art in NLP 21
FIGURE 2.11: Sequential processing of recurrent model (Source: Manning
et al. (2022)).
data sets. indicates the minimum number of steps before the respective state
can be calculated.
FIGURE 2.12: Sequential processing of recurrent model with number of
steps indicated (Source: Manning et al. (2022)).
After proving that attention dramatically increases performance, google
researchers took it further and based transformers solely on attention, so
without any RNNs. For this reason, the paper in which they were introduced is
called "Attention is all you need". Spoiler: It is not quite all we need, but more
about that on the following pages. Transformers have achieved great results
on multiple settings such as machine translation and document generation.
Their parallelizability allows for efficient pretraining and leads them to be the
standard model architecture. In fact, all top models on the popular aggregate
benchmark GLUE are pretrained and Transformer-based. Moreover, they
have even shown promise outside of NLP, e.g. in Image Classification, Protein
Folding and ML for Systems (see Dosovitskiy et al. (2020a), Jumper et al.
(2021), Zhou et al. (2020), respectively).
If recurrence has its flaws, another adjustment of the attention mechanism
might be beneficial. Until now, it was defined from decoder to encoder.
Alternatively, attention could also be from one state to all states in the
same set. This is the definition of self-attention, which is encoder-encoder
or decoder-decoder attention (instead of encoder-decoder) and represents a
cornerstone of the transformer architecture. depicts this process in which each
word attends to all words in the previous layer. Even though in practice, most
22 2 Introducing the modalities
arrows are omitted eventually.
FIGURE 2.13: Connections of classic attention mechanism (Source: Manning
et al. (2022)).
Thinking of self-attention as an approximate hash table eases understanding its
intuition. To look up a value, queries are compared against keys in a table. In
a hash table, which is shown on the left side of , there is exactly one key-value
pair for each query (hash). In contrast, in self-attention, each key is matched to
varying degrees by each query. Thus, a sum of values weighted by the query-key
match is returned.
FIGURE 2.14: Comparison of classic attention mechanism with self-attention
with hash tables (Source: Manning et al. (2022)).
The process briefly described in the last paragraph can be summarized by
the following steps that mainly follow Manning et al. (2022). Firstly, deriving
query, key, and value for each word xi
is necessary:
qi = WQxi
, ki = W Kxi
, vi = WV xi
Secondly, the attention scores have to be calculated:
eij = qikj
2.1 State-of-the-art in NLP 23
Thirdly, to normalize the attention scores, the softmax function is applied:
αij = softmax(eij ) = exp(
X
eij )
k
eij
Lastly, taking the weighted sum of the values results in obtaining the attention
output:
ai =
X
j
αijvj
Multiple advantages of incorporating self-attention instead of recurrences have
been revealed. Since all words interact at every layer, the maximum interaction
distance is O(1) and is a crucial upgrade. In addition, the model is deeply
bidirectional because each word attends to the context in both directions. As a
result of these advances, all word representations per layer can be computed in
parallel. Nevertheless, some issues have to be discussed. Attention does no more
than weighted averaging. So without neural networks, there are no element-wise
non-linearities. Their importance cannot be understated and shows why
attention is not actually all that is needed. Furthermore, bidirectionality is
not always desired. In language modelling, the model should specifically be
not allowed to simply look ahead and observe more than the objective allows.
Moreover, the word order is no longer encoder, and it is bag-of-words once again.
Fortunately, the previously mentioned weaknesses have been addressed for
the original transformer-architecture proposed by Vaswani et al. (2017c).
The first problem can be easily fixed by applying a feed forward layer to
the output of attention. It provides non-linear activation as well as extra
expressive power. Then, for cases in which bidirectionality contradicts the
learning objective, future states can be masked so that attention is restricted
to previous states. Moreover, the loss of the word can be corrected by adding
position representations to the inputs.
The more complex deep learning models are, the closer they become to model
the complexity of the real world. That is why the transformer encoder and
decoder consist of many layers of self-attention with a feed forward network,
which is necessary to extract both syntactic and semantic features from
sentences. Otherwise, using word embeddings, which are semantically deep
representations between words, would be unnecessary (Sejnowski, 2020). At
the same time, training deep networks can be troublesome. Therefore, some
tricks are applied to help with the training process.
One of them is to pass the "raw" embeddings directly to the next layer, which
24 2 Introducing the modalities
prevents forgetting or misrepresent important information as it is passed
through many layers. This process is called residual connections and is also
believed to smoothen the loss landscape. Additionally, it is problematic to
train the parameters of a given layer when its inputs keep shifting because
of layers beneath. Reducing uninformative variation by normalizing within
each layer to mean zero and standard deviation to one weakens this effect.
Another challenge is caused by the dot product tending to take on extreme
values because of the variance scaling with increasing dimensionality dk. It is
solved by Scaled Dot Product Attention (see Figure 2.15), which consists of
computing the dot products of the query with its keys, dividing them by the
dimension of keys √
dk, and applying the softmax function next to receive the
weights of the values.
FIGURE 2.15: Scaled dot-product attention (Source: Vaswani et al. (2017c)).
Attention learns where to search for relevant information. Surely, attending to
different types of information in a sentence at once delivers even more promising
results. To implement this, the idea is to have multiple attention heads per layer.
While one attention head might learn to attend to tense information, another
might learn to attend to relevant topics. Thus, each head focuses on separate
features, and construct value vectors differently. Multi-headed self-attention
is implemented by simply creating n independent attention mechanisms and
combining their outputs.
At this point, every part that constitutes the encoder in the transformer
architecture has been introduced (see Figure 2.17). First, positional encodings
are included in the input embeddings. There are multiple options to realize
this step, e.g. through sinusoids. The multi-head attention follows, which was
just mentioned. "Add & Norm" stands for the residual connections and the
normalization layer. A feed forward network follows, which is also accompanied
by residual connections and a normalization layer. All of it is repeated n
times. For the decoder, the individual components are similar. One difference
is that the outputs go through masked multi-head attention before multi-head
attention and the feed forward network (with residual connections and layer
normalization). It is critical to ensure that the decoder cannot peek at the
2.1 State-of-the-art in NLP 25
FIGURE 2.16: Multi-head attention (Source: Vaswani et al. (2017c)).
future. To execute this, the set of keys and queries could be modified at every
time step to only include past words. However, it would be very inefficient.
Instead, to enable parallelization, future states are masked by setting the
attention scores to −∞. After the decoder process is also repeated n times,
a linear layer is added to project the embeddings into a larger vector that
has the length of the vocabulary size. At last, a softmax layer generates a
probability distribution over the possible words.
FIGURE 2.17: Transformer architecture (Source: Vaswani et al. (2017c)).
26 2 Introducing the modalities
2.1.6 Transformer architectures: BERT, T5, GPT-3
"You shall know a word by the company it keeps", an adage by linguist John
Rupert Firth from 1957 goes. Even earlier, in 1935, he stated that "... the
complete meaning of a word is always contextual, and no study of meaning
apart from a complete context can be taken seriously". The quotes of the
famous linguist sum up the motivation to learn word meaning and context
perfectly. Many years later, in 2017, pretraining word embeddings started.
However, some complications arise from solely pretraining the first part of the
network. For instance, to teach the model all contextual aspects of language,
the training data for the downstream task (e.g. question answering) needs
to be adequate. Additionally, most of the parameters are usually randomly
initialized. presents the network discussed, in which the word "movie" gets the
same embedding irrespective of the sentence it appears in. On the contrary,
parameters in modern NLP architectures are initialized via pretraining (see
Figure 2.18). Furthermore, during the pretraining, certain input parts are
hidden to train the model to reconstruct them. This leads to building suitable
parameter initializations and robust probability distributions over language.
FIGURE 2.18: Partly pre-trained model (Source: Manning et al. (2022)).
Classic machine learning does not match human learning. Specifically referring
to training a model from scratch, and only being able to learn from the training
data. In contrast, human beings already have prior knowledge they can apply to
new tasks. Transfer learning emulates this by using an already trained network.
The main idea is to use a model that was pretrained on a hard, general language
understanding task using endless amounts of data, so that, it eventually contains the best possible approximation of language understanding. Afterwards,
the training data for the new task is applied to slightly modify the weights of
2.1 State-of-the-art in NLP 27
FIGURE 2.19: Jointly pre-trained model (Source: Manning et al. (2022)).
the pretrained model, which is referred to as fine-tuning (Manning et al., 2022).
The specific architecture of a transformer model affects the type of pre-training,
and favourable use cases. In the following, three different but very influential
transformer architectures will be discussed. BERT can be seen as stacked
encoders (Devlin et al., 2018b), T5 aims to combine the good parts of encoders
and decoders (Raffel et al., 2019a), while GPT are stacked decoders (Brown
et al., 2020).
2.1.6.1 BERT
Transfer learning led to state-of-the-art results in natural language processing.
One of the architectures that led the way was BERT, which stands for Bidirectional Encoder Representations from Transformers. It receives bidirectional
context, which is why it is not a natural fit for language modelling. To train it
on this objective regardless, masked language modelling was proposed. The
main idea is to cover up a fraction of the input words and let the model
predict them. In this way, the LM objective can be used while sustaining
connections to words in the future. The masked LM for BERT randomly
predicts 15% of all word tokens in each sequence. Of those, 80% are replaced
by the MASK token, 10% by a random token, and 10% remain unchanged.
Moreover, because the masked words are not even seen in the fine-tuning
phase, the model cannot get complacent and relies on strong representations
of non-masked words. Initially, BERT had an additional objective of
whether one sentence follows another, which is known as next sentence prediction. However, it was dropped in later work due to having an insignificant effect.
28 2 Introducing the modalities
BERT is hugely versatile and was greatly popular after its release. Fine-tuning
BERT led to outstanding results on a variety of applications, including question
answering, sentiment analysis and text summarization. Thanks to its design,
if the task involves generating sequences, pretrained decoders outperform
pretrained encoders like BERT. Even though, it would not be recommended
for autoregressive generation, up to this day, "small" models like BERT are
applied as general tools for numerous tasks.
2.1.6.2 T5
The Text-To-Text Transfer Transformer (T5) is a new model that can be
regarded as an application of the insights gathered by an extensive empirical
study searching for the best transfer learning techniques. It is pretrained on
Colossal Clean Crawled Corpus (C4), an open-source dataset. Raffel et al.
(2019a) found that the best pretraining objective to use for the encoder
component was span corruption. In short, different length word groups (spans)
are replaced with unique placeholders, and let the model decode them. Text
preprocessing is necessary for its implementation. For the decoder, it is still
a language modelling task. Compared to models like BERT, which can only
output a span of the input or a class label, T5 reframes all NLP tasks into a
unified text-to-text format, where inputs and outputs always consist of text
strings. As a result, the same model, loss function, and hyperparameters can be
used on any NLP task, such as machine translation, document summarization,
question answering, and classification tasks like sentiment analysis. T5 can even
be applied to regression tasks by training it to predict the string representation
of a number (and not the number itself). Examples of potential use cases are
depicted in below.
FIGURE 2.20: Applications of T5 model (Source: Raffel et al. (2019a)).
2.1.6.3 GPT-3
As previously stated, the neural architecture influences the type of pretraining.
The original GPT architecture consists of a Transformer decoder with 12 layers
(Radford et al., 2018). For decoders, it is sensible to simply pretrain them as
language models. Afterwards, they can be used as generators to fine-tune their
probability of predicting the next word conditioned on the previous words.
2.1 State-of-the-art in NLP 29
The models are suitable for tasks similar to the training, including any type
of dialogue and document summarization. Transformer language models are
great for transfer learning. They are fine-tuned by randomly initializing a
softmax classifier on top of the pretrained model and training both (with only
a very small learning rate and a small number of epochs) so that the gradient
propagates through the whole network.
The success of BERT in 2018 prompted a "gold rush" in NLP, in which ever
greater language models were created. One that topped the headlines and
used a customer supercluster for computation was the third iteration of the
GPT architecture by OpenAI, known as GPT-3. reveals why GPT-3 is a
famous example of current research focusing on scaling up neural language
models. While the largest T5 model has 11 billion parameters, GPT-3 has
175 billion parameters. Moreover, the training data set contains around 500
billion tokens of text, while the average young american child hears around 6
million words per year (Hart and Risley, 1995). The results of huge language
models suggest that they perform some form of learning (without gradient
steps) simply from examples provided via context. The tasks are specified by
the in-context examples, and the conditional probability distribution simulates
performing the task to an extent.
FIGURE 2.21: Comparison of number of parameters between Transformerarchitectures (Source: Saifee (2020)).
2.1.7 Current Topics
2.1.7.1 Concerns regarding growing size of Language Models
As the last chapter ended with GPT-3 and emphasized the concerning trend
of ever larger language models, one could ask which other costs arise from
the developments. Risks and harms among environmental and financial costs
have been studied by Bender et al. (2021). They state that marginalized
30 2 Introducing the modalities
communities are not only less likely to benefit from LM progress, but also more
likely to suffer from the environmental repercussions of increasing resource
consumption. Strubell et al. (2019a) estimated that training a Transformer
(big) model resulted in 249t of CO2. To compare, an average human is
responsible for approximately 5t of CO2 per year (Ritchie et al., 2020). In
addition, they discovered that an estimated increase of 0.1 in BLEU score
increased computation costs by $ 150,000 (for English to German translations).
Furthermore, larger models require more data to sufficiently train them. This
has resulted in large but poorly documented training data sets. Multiple risks
can be mitigated if there is a common understanding of the model’s learnings.
Moreover, it has been argued that datasets consisting of web data over-represent
hegemonic views and encode bias towards marginalized communities. This
is among other factors due to internet access being unevenly distributed. In
particular, there is an over-representation of younger internet users and those
from developed countries. It is generally naive to educate AI systems on all
aspects of the complex world, and hope for the beautiful to prevail (Bender
et al., 2021).
2.1.7.2 Improving Understanding of Transformer-based models
The results of transformer-based models clearly show that they deliver
successful results. However, it is less clear why. The size of the models
makes it difficult to experiment with them. Nevertheless, having a limited
understanding restrains researchers from coming up with further improvements.
Therefore, multiple papers analysed BERT’s attention in search of an improved
understanding of large transformer models. BERT is a smaller model out of
the more popular ones, and its attention is naturally interpretable because the
attention weight indicates how significant a word is for the next representation
of the current word (Clark et al., 2019). In the following, some of the findings
are going to be shared.
BERT representations are rather hierarchical than linear, and they include
information about parts of speech, syntactic chunks and roles (Lin et al., 2019,
Liu et al. (2019a)) Furthermore, it has semantic knowledge. For example,
BERT can recognize e.g. that "to tip a chef" is better than "to tip a robin"
but worse than "to tip a waiter" ((Ettinger, 2019)). However, it makes sense
that BERT has issues with knowledge that is assumed and not mentioned,
which especially refers to visual and perceptual properties (Da and Kasai,
2019). Additionally, BERT struggles with inferences, e.g. even though it is
known that "people walk into houses" and "houses are big", it cannot infer
that "houses are bigger than people" (Forbes et al., 2019).
While it is true that different transformer heads attend to various patterns (see
2.1 State-of-the-art in NLP 31
), interestingly, most of them could be neglected without notable performance
loss (Voita et al., 2019). Probing attention maps can be tedious, but allows to
gain knowledge of common patterns, such as an unexpected amount focusing
on the delimiter token SEP
.
FIGURE 2.22: Common patterns of attention heads (Source: Clark et al.
(2019)).
2.1.7.3 Few-Shot Learning
For NLP tasks, the model is usually trained on a set of labelled examples and
is expected to generalize to unseen data. Annotating is not only costly but also
difficult to gather for numerous languages, domains, and tasks. In practice,
there is often only a very limited amount of labelled examples. Consequently,
few-shot learning is a highly relevant research area (Schick and Schütze, 2020).
It defines a model that is trained on a limited number of demonstrations to
guide its predictions. Referring back to , the benefits of lower computational
and environmental costs have to be mentioned.
Traditional fine-tuning uses a large corpus of example tasks, and the model
is updated repeatedly with gradient steps so that it adapts to the task with
minimal accuracy error.
In contrast, few-shot applications have to complete tasks at test time with only
forward passes. They have three main parts: the task description, examples,
and the prompt. In Figure ??, the task is a translation from English to French,
a few examples, as well as the word that should be translated are given.
Moreover, zero-shot and one-shot learning refer to the model predicting with
no and one learned example, respectively (Brown et al., 2020).
It is complicated to create the few-shot examples, since the application relies
on them to express the task. This is why smaller models are susceptible to
32 2 Introducing the modalities
FIGURE 2.23: Few-shot learning (Source: Brown et al. (2020)).
examples written unfavourably. In Brown et al. (2020), it was shown that
few-shot performance scales with the number of model parameters. Even
though GPT-3’s in-context learning improved few-shot prompting capabilities,
it is still sensitive to the order of training examples, decoding strategy, and
hyperparameter selection. All of this combined with the fact that current
research uses larger or held-out data sets leads to the suspicion that the true
few-shot ability of language models is overestimated (Perez et al., 2021a).
Moreover, Lialin et al. (2022) have found that common transformer models
could not resolve compositional questions in a zero-shot fashion and that the
model’s parameter count does not correlate with performance. This indicates
a limitation for zero-shot prompting with the existing pre-training objectives.
However, different models provided the best accuracy with regard to different
symbolic reasoning tasks. This suggests that optimization or masking strategies could be more significant than the pre-training, data set size or model
architecture.
2.1.8 Summary
Natural Language Processing has been one of the most exciting fields of machine
learning in the last decade considering all the breakthroughs discussed in this
work. Word embeddings made it possible and allowed developers to encode
words as dense vectors that capture their underlying semantic content. In this
way, similar words are embedded close to each other in a lower-dimensional
feature space. Another important challenge was solved by encoder-decoder
(also called sequence-to-sequence) architectures, which made it possible to map
input sequences to output sequences of different lengths. They are especially
useful for complex tasks like machine translation, video captioning or question
answering. A significant state-of-the-art technique is attention, which enabled
models to actively shift their focus – just like humans do. It allows following
one thought at a time while suppressing information irrelevant to the task.
As a consequence, it has been shown to significantly improve performance for
tasks like machine translation. By giving the decoder access to directly look
at the source, the bottleneck is avoided and at the same time, it provides a
shortcut to faraway states and thus helps with the vanishing gradient problem.
2.2 State-of-the-art in Computer Vision 33
One of the most recent data modelling techniques is the transformer, which
is solely based on attention and does not have to process the input data
sequentially. Therefore, the deep learning model is better in remembering
context-induced earlier in long sequences. It is the dominant paradigm in
NLP currently and makes better use of GPUs because it can perform parallel
operations. Transformer architectures like BERT, T5 or GPT-3 are pre-trained
on a large corpus and can be fine-tuned for specific language tasks. They can
generate stories, poems, code and much more. Currently, there seems to be
breaking transformer news nearly every week with no sign of slowing. This is
why many trends could be recognized as relevant current topics. One of them
is increasing concerns regarding the growing size of language models and the
correlated environmental and financial costs. Another active research aspect is
concerned with improving the understanding of transformer-based models to
further advance them. Additionally, there are many studies about achieving
respectable results on language modelling tasks after only learning from a few
examples, which is known as few-shot learning.
2.2 State-of-the-art in Computer Vision
Author: Vladana Djakovic
Supervisor: Daniel Schalk
2.2.1 History
The first research about visual perception comes from neurophysiological
research performed in the 1950s and 1960s on cats. The researchers used
cats as a model to understand how human vision is compounded. Scientists
concluded that human vision is hierarchical and neurons detect simple features
like edges followed by more complex features like shapes and even more complex
visual representations. Inspired by this knowledge, computer scientists focused
on recreating human neurological structures.
At around the same time, as computers became more advanced, computer
scientists worked on imitating human neurons’ behavior and simulating a
hypothetical neural network. In his book “The Organization of Behaviour”
(1949) Donald Hebbian stated that neural pathways strengthen over each
successive use, especially between neurons that tend to fire at the same time,
thus beginning the long journey towards quantifying the complex processes of
the brain. The first Hebbian network, inspired by this neurological research,
was successfully implemented at MIT in 1954 (Jaspreet, 2019).
New findings led to the establishment of the field of artificial intelligence in
34 2 Introducing the modalities
1956 on-campus at Dartmouth College. Scientists began to develop ideas and
research how to create techniques that would imitate the human eye.
In 1959 early research on developing neural networks was performed at Stanford
University, where models called “ADALINE” and “MADALINE,” (Multiple
ADAptive LINear Elements) were developed. Those models aimed to recognize
binary patterns and could predict the next bit (his, 2022).
Starting optimism about Computer Vision and neural networks disappeared
after 1969 and the publication of the book “Perceptrons” by Marvin Minsky,
founder of the MIT AI Lab, stated that the single perception approach to
neural networks could not be translated effectively into multi-layered neural
networks. The period that followed was known as AI Winter, which lasted
until 2010, when the technological development of computer and the internet
became widely used. In 2012 breakthroughs in Computer Vision happened at
the ImageNet Large Scale Visual Recognition Challenge (ILSVEC). The team
from the University of Toronto issued a deep neural network called AlexNet
(Krizhevsky et al., 2012a) that changed the field of artificial intelligent and
Computer Vision (CV). AlexNet achieved an error rate of 16.4%.
From then until today, Computer Vision has been one of the fastest developing
fields. Researchers are competing to develop a model that would be the most
similar to the human eye and help humans in their everyday life. In this chapter
the author will describe only a few recent state-of-the-art models.
2.2.2 Supervised and unsupervised learning
As part of artificial intelligence (AI) and machine learning (ML), there are two
basic approaches:
• supervised learning;
• unsupervised learning.
Supervised learning (Education, 2020a) is used to train algorithms on labeled
datasets that accurately classify data or predict outcomes. With labeled data,
the model can measure its accuracy and learn over time. Among others, we
can distinguish between two common supervised learning problems:
• classification,
• regression.
In unsupervised learning (Education, 2020b), unlabelled datasets are analyzed
and clustered using machine learning algorithms. These algorithms aim to discover hidden patterns or data groupings without previous human intervention.
The ability to find similarities and differences in information is mainly used
for three main tasks:
• clustering,
• association,
2.2 State-of-the-art in Computer Vision 35
• dimensionality reduction.
Solving the problems where the dataset can be both labeled and unlabeled
requires a semi-supervised approach that lies between supervised and unsupervised learning. It is useful when extracting relevant features from complex and
high volume data, i.e., medical images.
Nowadays, a new research topic appeared in the machine learning community,
Self-Supervised Learning. Self-Supervised learning is a process where the model
trains itself to learn one part of the input from another (techslang, 2020). As
a subset of unsupervised learning, it involves machines labeling, categorizing,
and analyzing information independently and drawing conclusions based on
connections and correlations. It can also be considered as an autonomous
form of supervised learning since it does not require human input to label
data. Unlike unsupervised learning, self-supervised learning does not focus on
clustering nor grouping (Shah, 2022). One part of Self-Supervised learning is
contrastive learning, which is used to learn the general features of an unlabeled
dataset identifying similar and dissimilar data points. It is utilized to train the
model to learn about our data without any annotations or labels (Tiu, 2021).
2.2.3 Scaling networks
Ever since the introduction of AlexNet in 2012, the problem of scaling convolutional neural networks (ConvNet) has become the topic of active research.
ConvNet can be scaled in all three dimensions: depth, width, or image size.
One of the first researches in 2015 showed that network depth is crucial for
image classification. The question whether stacking more layers enables the
network to learn better leads to deep residual networks called ResNet (He et al.,
2015), which will be described in this work. Later on, scaling networks by their
depth became the most popular way to improve their performance. The second
solution was to scale ConvNets by their width. Wider networks tend to be
able to capture more fine-grained features and are easier to train (Zagoruyko
and Komodakis, 2016). Lastly, scaling the image’s resolution can improve the
network’s performance. With higher resolution input images, ConvNets could
capture more fine-grained patterns. GPipe (Huang et al., 2018) is one of the
most famous networks created by this technique. The question of possibility of
scaling by all three dimensions was answered by Tan and Le (2019a) in the
work presenting Efficient Net. This network was built by scaling up ConvNets
by all three dimensions and will also be described here.
2.2.4 Deep residual networks
The deep residual networks, called ResNets (He et al., 2015), were presented as
the answer on the question whether stacking more layers would enable network
to learn better. Until then one obstacle for simply stacking layers was the
problem of vanishing/exploding gradients. It has been primarily addressed by
36 2 Introducing the modalities
normalized initialization and intermediate normalization layers. That enabled
networks with tens of layers to start converging for stochastic gradient descent
(SGD) with backpropagation.
Another obstacle was a degradation problem. It occurs when the network
depth increases, followed by saturating and then rapidly decreasing accuracy.
Overfitting is not caused by such degradation, and adding more layers to a
suitably deep model leads to higher training error, which indicates that not all
systems are similarly easy to optimize.
For example, it was suggested to consider a shallower architecture and its
deeper counterpart that adds more layers. One way to avoid the degradation
problem is to create a deeper model, where the auxiliary layers are identity
mappings and other layers are copied from a shallower model. The deeper
model should produce no higher training error than its shallower counterpart.
However, in practice it is not the case and it is hard to find comparably
good constructs or better solutions. The solution to this degradation problem
proposed by them is a deep residual learning framework.
2.2.4.1 Deep Residual Learning
2.2.4.1.1 Residual Learning
The idea of residual learning is to replace the approximation of underlying
mapping H (x), which is approximated by a few stacked layers (not necessarily
the entire net), with an approximation of residual function F(x) := H (x) − x.
Here x denotes the inputs to the first of these layers, and it is assumed that
both inputs and outputs have the same dimensions. The original function
changes its form F (x) + x.
A counter-intuitive phenomenon about degradation motivated this reformulation. The new deeper model should not have a more significant training error
when compared to a construction using identity mappings. However, due to
the degradation problem, solvers may have challenges approximating identity
mappings by multiple non-linear layers. Using the residual learning reformulation can drive the weights of the non-linear layers toward zero to approach
identity mappings if they are optimal. Generally, identity mappings are not
optimal, but new reformulations may help to pre-condition the problem. When
an optimal function is closer to an identity mapping than a zero mapping,
finding perturbations concerning an identity mapping should be easier than
learning the function from scratch.
2.2.4.1.2 Identity Mapping by Shortcuts
Residual learning is adopted to every few stacked layers where a building block
is defined:
y = F (x, {Wi}) + x (2.1)
2.2 State-of-the-art in Computer Vision 37
x and y present the input and output vectors of the layers. Figure 2.24 visualizes
the building block.
FIGURE 2.24: Building block of residual learning (He et al., 2015).
The function F (x, {Wi}) represents the residual mapping that is to be learned.
For the example with two layers from Figure 2.24, F = W2σ (W1x) in which
σ denotes the ReLU activation function. Biases are left out to simplify the
notation. The operation F + x is conducted with a shortcut connection and
element-wise addition. Afterward, a second non-linear (i.e., σ (y) transformation
is applied.
The shortcut connections in Equation (2.1) neither adds an extra parameter nor
increases computation complexity and enables a comparisons between plain and
residual networks that concurrently have the same number of parameters, depth,
width, and computational cost (except for the negligible element-wise addition).
The dimensions of x and F in Equation (2.1) must be equal. Alternatively, to
match the dimensions, linear projection Ws by the shortcut connections can
be applied:
y = F (x, {Wi}) + Wsx. (2.2)
The square matrix Ws can be used in Equation (2.2). However, experiments
showed that identity mapping is enough to solve the degradation problem.
Therefore, Ws only aims to match the dimensions. Although more levels are
possible, it was experimented with function F having two or three layers
without stating the exact form of it. Assuming F only has one layer (Equation
(2.1)) it is comparable to a linear layer: y = W1x+x. The theoretical notations
are about fully-connected layers, but convolutional layers were used. The
function F (x, {Wi}) can be applied to represent multiple convolutional layers.
Two feature maps are added element-wise, channel by channel.
2.2.4.2 Network Architectures
Various plain/residual networks were tested to construct an efficient residual
network. They trained the network on benchmarked datasets, e.g. the ImageNet
dataset, that are used for a comparison of network architectures. Figure (2.2)
shows that every residual network needs a plain baseline network inspired by
the VGG (Simonyan and Zisserman, 2014) network on which identity mapping
by shortcuts is applied.
38 2 Introducing the modalities
Plain Network: The philosophy of VGG nets 41 mainly inspires the plain
baselines. Two rules convolution layers, which usually have 3 × 3 filters, follow
are:
• feature maps with the same output size have the same number of layers;
• reducing the size of a feature map by half doubles the number of filters per
layer to maintain time complexity per layer.
Convolutional layers with a stride of 2 perform downsampling directly. A global
average pooling layer and a 1000-way fully-connected layer with softmax are at
the end of the network. The number of weighted layers sums up to 34 (Figure
2.25, middle). Compared to VGG nets, this model has fewer filters and lower
complexity (Figure 2.25, left).
Residual Network: Based on the above plain network, additional shortcut
connections (Figure 2.25, right) turn the network into its associate residual
variant. The identity shortcuts (Equation (2.1)) can be directly used in the
case of the exact dimensions of the input and output (solid line shortcuts in
Figure 2.25). For the different dimensions (dotted line shortcuts in Figure
2.25), two options are considered:
• The shortcut still performs identity mapping, but with extra zero entries
padded to cope with the increasing dimensions, without adding new parameters;
• The projection shortcut in Equation (2.2) matches dimensions (due to 1 × 1
convolutions).
In both cases, shortcuts will be done with a stride of two when they go across
feature maps of two sizes.
2.2.5 EfficientNet
Until Tan and Le (2019b) introduced EfficientNet, it was popular to scale only
one of the three dimensions – depth, width, or image size. The empirical study
shows that it is critical to balance all network dimensions, which can be achieved
by simply scaling each with a constant ratio. Based on this observation, a simple
yet effective compound scaling method was proposed, which uniformly scales
network width, depth, and resolution with a set of fixed scaling coefficients. For
example, if 2N times more computational resources are available, increasing the
network depth by αN, width by βN, and image size by γN would be possible.
Here α, β, γ are constant coefficients determined by a small grid search on the
original miniature model. Figure 2.26 illustrates the difference between this
scaling method and conventional methods. A compound scaling method makes
sense if an input image is bigger because a larger receptive field requires more
layers and more significant channel features to capture fine-grained patterns.
Theoretically and empirically, there has been a special relationship between
2.2 State-of-the-art in Computer Vision 39
FIGURE 2.25: Architecture of ResNet (He et al., 2015).
40 2 Introducing the modalities
network width and depth (Raghu et al., 2016). Existing MobileNets (Howard
et al., 2017) and ResNets are used to demonstrated new scaling methods.
FIGURE 2.26: Model scaling (Tan and Le, 2019b).
2.2.5.1 Compound Model Scaling
2.2.5.1.1 Problem Formulation
A function Yi = Fi (Xi) with the operator Fi
, output tensor Yi
, input tensor
Xi of shape (Hi
, Wi
, Ci), spatial dimensions Hi
, Wi
, and channel dimension
Ci
is called a ConvNet Layer i. A ConvNet N appears as a list of composing
layers:
N = Fk · · · F∈ F∞ (X1) = Kj = 1 · · · kF| (X1)
Effectively, these layers are often partitioned into multiple stages and all layers
in each stage share the same architecture. For example, ResNet has five stages
with all layers in every stage being the same convolutional type except for the
first layer that performs down-sampling. Therefore, a ConvNet can be defined
as:
N =
K
i=1···s
Fi
Li
X(Hi,Wi,Ci)
where Fi
Li denotes layer Fi which is repeated Li times in stage i, and
(Hi
, Wi
, Ci) is the shape of input tensor X of layer i.
In comparison to the regular ConvNet focusing on the best layer architecture
search Fi
, model scaling centers on the expansion of the network length (Li),
width (Ci), and/or resolution (Hi
, Wi) without changing Fi that was predefined
in the baseline network. Although model scaling simplifies the design problem
of the new resource constraints through fixing Fi
, a different large design space
(Li
, Hi
, Wi
, Ci) for each layer remains to be explored. To further reduce the
design space, all layers are restricted to be scaled uniformly with a constant
2.2 State-of-the-art in Computer Vision 41
ratio. In this case, the goal is to maximize the model’s accuracy for any given
resource constraint, which is presented as an optimization problem:
max
d,w,r
Accuracy (N (d, w, r))
s.t.N (d, w, r) = K
I=1...s
Fˆi
d·Liˆ
Xhr·Hˆi,r·Wˆi,w·Cˆii
Memory (N ) ≤ targetMemory
F LOP S (N ) ≤ targetFlops
where w, d, r are coefficients for scaling network width, depth, and resolution;
Fbi
,Lbi
, Hbi
, Wci
, Cbi
are predefined parameters of the baseline network.
2.2.5.1.2 Scaling Dimensions
The main difficulty of this optimization problem is that the optimal d, w, r
depend on each other and the values are changing under different resource
constraints. Due to this difficulty, conventional methods mostly scale ConvNets
in one of these dimensions:
Depth (d): One of the most significant networks previously described is the
ResNet. As it was described, the problem of ResNets is that accuracy gain of a
very deep network diminishes. For example, ResNet-1000 has similar accuracy
to ResNet-101 even though it contains many more layers.
Width (w): Scaling network width is commonly used for small-sized models.
However, wide but shallow networks tend to have difficulty grasping higher-level
features.
Resolution (r): Starting from 224×224 in early ConvNets, modern ConvNets
tend to use 299 × 299 or 331 × 331 for better accuracy. GPipe (Huang et al.,
2018) recently achieved state-of-the-art ImageNet accuracy with 480 × 480
resolution. Higher resolutions, such as 600 × 600, are also widely used in
ConvNets for object detection.
The above analyses lead to the first observation:
Observation 1: Scaling up any network width, depth, or resolution dimension
improves accuracy. Without the upscaling, the gain diminishes for bigger
models.
2.2.5.1.3 Compound Scaling
Firstly, it was observed that different scaling dimensions are not independent
because higher resolution images also require to increase the network depth.
The larger receptive fields can help capture similar features that include more
pixels in bigger images. Similarly, network width should be increased when
the resolution is higher to capture more fine-grained patterns. The intuition
42 2 Introducing the modalities
suggests that different scaling dimensions should be coordinated and balanced
rather than conventional scaling in single dimensions. To confirm this thought,
results of networks with width w without changing depth (d=1.0) and resolution
(r=1.0) were compared with deeper (d=2.0) and higher resolution (r=2.0)
networks. This showed that width scaling achieves much better accuracy under
the same FLOPS. These results lead to the second observation:
Observation 2: To achieve better accuracy and efficiency, balancing the
network width, depth, and resolution dimensions during ConvNet scaling is
critical. Earlier researches have tried to arbitrarily balance network width and
depth, but they all require tedious manual tuning.
A new compound scaling method, which uses a compound coefficient ϕ to
uniformly scale network width, depth, and resolution in a principled way was
proposed:
depth:d = α
ϕ
width:w = β
ϕ
resolution:∇ = γ
ϕ
s.t.α · β
2
· γ
2 ≈ 2
α ≥ 1, β ≥ 1, γ ≥ 1
(2.3)
where α, β, γ are constants that can be determined by a small grid search,
ϕ is a user-specified coefficient that controls how many more resources are
available for model scaling, while α, β, γ specify how to assign these extra
resources to the network width, depth, and resolution, respectively. Notably,
the FLOPS of a regular convolution operation is proportional to d, w2
, r2
, i.e.,
doubling network depth will double the FLOPS, but doubling network width or
resolution will increase the FLOPS by four times. Scaling a ConvNet following
Equation (2.3) will approximately increase the total number of FLOPS by
α · β
2
· γ
2
ϕ
. In this chapter, α · β
2
· γ
2 ≈ 2 is constrained such that for any
new ϕ the total number of FLOPS will approximately increase by 2ϕ.
2.2.5.2 EfficientNet Architecture
A good baseline network is essential because model scaling does not affect its
layer operators F ∗ [i]. Therefore this method is also estimated on ConvNets.
A new mobile-sized baseline called EfficientNet was developed to show the
effectiveness of the new scaling method. Metrics that were used to estimate
the efficacy are accuracy and FLOPS. The baseline efficient network that was
created is named EfficientNet-B0. Afterwards, this compound scaling method
is applied in two steps:
• STEP 1: By fixing ϕ = 1 and, assuming twice more resources available, a
small grid search of α, β, γ based on Equation (2.3) showed that the best
2.2 State-of-the-art in Computer Vision 43
values for EfficientNet-B0 are α = 1.2, β = 1.1, γ = 1.15 under the constraint
of α · β
2
· γ
2 ≈ 2.
• STEP 2: Afterwards, fix α, β, γ as constants and scale up the baseline
network with different ϕ using Equation (2.3) to construct EfficientNet-B1
to B7.
Name Number of parameters
EfficientNet-B0 5.3M parameters
EfficientNet-B1 7.8M parameters
EfficientNet-B2 9.2M parameters
EfficientNet-B3 12M parameters
EfficientNet-B4 19M parameters
EfficientNet-B5 30M parameters
EfficientNet-B6 43M parameters
EfficientNet-B7 66M parameters
Indeed, even better performance is achievable by searching for α, β, γ directly
around a large model, but the search cost becomes prohibitively more expensive
on larger models. This method searches once on a small baseline network, then
scales the coefficient for all other models.
2.2.5.3 Results and comparison of the networks
To demonstrate the performance of both networks, ResNet and EfficientNets
were trained and evaluated on the ImageNet 2012 classification dataset consisting out of 1000 classes. Since deeper scaling should provide better results
in the case of ResNet, it was trained with increased depth each time. First
meaningful results were obtained in ResNet-34, which performed 3.5 % better
than plain-34 baseline when top-1 accuracy is compared. They also compared
three versions of ResNet: (A) zero-padding shortcuts (increasing dimensions,
all shortcuts are parameter-free) (B) projection shortcuts (increasing dimensions, other shortcuts are identity), and (C) all shortcuts are projections. Each
version improved both, the top-1 and top-5 accuracy. Afterward, the depth of
the network was increased and ResNet-50, ResNet-101, and ResNet-152 were
created. Each increase in depth leads to higher accuracy. In deeper models, the
trade-off between accuracy increase and deeper model is not worth describing.
All results are shown in the following table:
Model top-1 acc. top-5 acc.
VGG-16 71.93 90.67
GoogLeNet - 90.85
plain-34 71.46 89.98
ResNet-34 A 74.97 92.24
44 2 Introducing the modalities
Model top-1 acc. top-5 acc.
ResNet-34 B 75.48 92.54
ResNet-34 C 75.81 92.6
ResNet-50 77.15 93.29
ResNet-101 78.25 93.95
ResNet-152 78.57 94.29
In the case of EfficientNets, the results achieved by the previous state-of-the-art
networks on the same ImageNet dataset were aimed to improve. Among all stateof-the-art networks, EfficientNets were compared with ResNets-50 and ResNet152. They compared the results of networks deviated by changing scaling
parameters EfficientNet-B0 to EfficientNet-B7. The results of each network
were better than the previous one. Also, they have shown that EfficientNet-B0
outperforms ResNet-50 and that EfficientNet-B1 outperforms ResNet-152. This
means that scaling through all three dimensions can provide better results
than scaling through just one dimension. The drawback of this approach is the
computational power which makes it less popular than the previous methods.
Again, all results are shown in the following table:
Model top-1 acc. top-5 acc.
EfficientNet-B0 / ResNet-50 77.1 / 76 93.3 / 93
EfficientNet-B1 / ResNet-152 79.1 / 77.8 94.4 / 93.8
EfficientNet-B2 80.1 94.9
EfficientNet-B3 / ResNeXt-101 81.6 / 80.9 95.7 / 95.6
EfficientNet-B4 82.9 96.4
EfficientNet-B5 83.6 96.7
EfficientNet-B6 84 96.8
EfficientNet-B7 / GPipe 84.3 / 84.3 97 / 97
2.2.6 Contrastive learning
In recent years the problem of classification of unlabeled dataset is becoming
more widespread. More unlabeled datasets requiring human labeling are created
in fields like medicine, the automotive industry, military, etc. Since the process is
expensive and time-consuming, researchers assumed it could be automated with
contrastive learning frameworks. One of the first and most known contrastive
learning frameworks is SimCLR (Chen et al., 2020a). The advantage of this
framework is its simplicity, yet it achieves high accuracy on classification tasks.
The main idea is to have two copies of the image, which are then used to train
two networks and that are compared. The problem with this framework is that
it doubles the size of the dataset and reaches among all images, which can
be computationally infeasible for large datasets. Bootstrap Your Own Latent
2.2 State-of-the-art in Computer Vision 45
(Grill et al., 2020b) was introduced to avoid making double-sized datasets.
The idea was to bootstrap image representations to avoid unnecessary image
comparisons. These two frameworks will be described in this chapter.
Further improvements in the choice of creating two views of images and
comparison techniques were presented in different frameworks such as NearestNeighbor Contrastive Learning (NNCLR) (Dwibedi et al., 2021), Open World
Object Detection (ORE) (Joseph et al., 2021), Swapping Assignments between
multiple Views (SwAV) {Caron et al. (2020)}, and many more. This field is
a constant research topic and new improved frameworks are proposed on a
constant basis to help researchers solve different tasks that requires labeled
datasets.
2.2.6.1 A Simple Framework for Contrastive Learning of Visual
Representations
Chen et al. (2020a) intended to analyze and describe a better approach
to learning visual representations without human supervision. They have
introduced a simple framework for contrastive learning of visual representations
called SimCLR. As they claim, SimCLR outperforms previous work, is more
straightforward, and does not require a memory bank.
Intending to understand what qualifies good contrastive representation learning,
the significant components of the framework were studied and resulted in:
• A contrastive prediction task requires combining multiple data augmentation operations, which results in effective representations. Unsupervised
contrastive learning benefits from more significant data augmentation.
• The quality of the learned representations can be substantially improved by
introducing a learn-able non-linear transformation between the representation
and the contrastive loss.
• Representation learning with contrastive cross-entropy loss can be improved
by normalizing embeddings and adjusting the temperature parameter appropriately.
• Unlike its supervised counterpart, contrastive learning benefits from larger
batch sizes and extended training periods. Contrastive learning also benefits
from deeper and broader networks, just as supervised learning does.
2.2.6.2 The Contrastive Learning Framework
Like for SimCLR, a contrastive loss is used to learn a representation by
maximizing the agreement between various augmented views of the same data
example. This framework contains four significant components, which are
shown in Figure 2.27:
1. A stochastic data augmentation module
2. A neural network base encoder
46 2 Introducing the modalities
3. A small neural network projection head
4. A contrastive loss function
FIGURE 2.27: A simple framework for contrastive learning of visual representations (Chen et al., 2020a).
2.2.6.2.1 Stochastic data augmentation module
First, the minibatch of N examples is sampled randomly, and the contrastive
prediction task is defined on pairs of augmented examples, resulting in 2N
data points. A memory bank was not used to train the model, instead, the
training batch size varies from 256 to 8192. Any given data example randomly
returns two correlated views of the same example, denoted x˜i and x˜j , which is
known as a positive pair. Negative pairs are all other 2(N − 1) pairs. In
one view, some data augmentation techniques are applied. Data augmentation
is widely embraced in supervised and unsupervised representation learning.
Unfortunately, it has not been used to define the contrastive prediction task,
which is mainly determined by changing the architecture. It was shown that
choosing different data augmentation techniques can reduce the complexity of
previous contrastive learning frameworks. There are many data augmentation
operations, the focus was on the most common ones, which are:
• Spatial geometric transformation: cropping and resizing (with horizontal
flipping), rotation and cutout,
• Appearance transformation: color distortion (including color dropping),
brightness, contrast, saturation, Gaussian blur, and Sobel filtering.
FIGURE 2.28: Augmentation texhniques (Chen et al., 2020a).
2.2 State-of-the-art in Computer Vision 47
Due to the image sizes in the ImageNet dataset, all images were always randomly cropped and resized to the same resolution. Later on, other targeted
data augmentation transformations were applied to one branch, remaining the
one as original i.e. t(xi) = xi
. Applying just individual transformation is insufficient for the model to learn good representations. The model’s performance
improves after composing augmentations, although the contrastive prediction
task becomes more complex. The composition of augmentations that stood
out were random cropping and random color distortion.
It was also observed that stronger color augmentation significantly improves
the linear evaluation of unsupervised learned models. Stronger color augmentations do not enhance the performance of supervised learning models when
trained with the same augmentations. Based on the experiments, unsupervised contrastive learning benefits from stronger color data augmentation than
supervised learning.
2.2.6.2.2 Neural network base encoder
Neural network based encoder f (·) extracts multiple representation vectors
from the augmented data examples. This framework does not restrict a choice
of the network architecture, although for simplicity, the commonly used ResNet
was picked and gives hi = f (˜xi) = ResNet(˜xi) where hi ∈ R
d
is the output
after the average pooling layer. Although increasing depth and width improves
performance, the ResNet-50 was chosen. Furthermore, when the model size
increases, the gap between supervised and unsupervised learning shrinks,
suggesting that bigger models benefit more from unsupervised learning.
2.2.6.2.3 Small neural network projection head
A small neural network projection head g (·) maps the representation to the
space where the contrastive loss is applied to. The importance of including a
projection head, i.e., g (h) was evaluated and they considered three different
architectures for the head:
1. identity mapping,
2. linear projection,
3. the default non-linear projection with one additional hidden layer
and ReLU activation function.
The results showed that a non-linear projection head is better than a linear
projection and much better than no projection. It improves the representation
quality of the layer that is applied previous to it. They have used a MLP with
one hidden layer to obtain zi = g (hi) = W(2)σ
W(1)hi
where σ is a ReLU
non-linearity transformation.
This step is performed because defining the contrastive loss on zi
instead of on
hi would not lead to a loss of information caused by contrastive loss. Especially,
48 2 Introducing the modalities
z = g (h) is trained to be invariant to data transformations. As a result, g
can remove information useful for a downstream task such as object color or
orientation. Using the non-linear transformation g (∗), h can maintain and
form more information.
2.2.6.2.4 Contrastive loss function
Given a set {x˜ik} including a positive pair of examples x˜i and x˜j , the contrastive
prediction task aims to identify x˜i
in {x˜i}k6=i
for a given x˜i
. In the case of
positive examples, the loss function is defined as
li,j = − log
exp
sim(zi,zj )
τ
P2N
k=1 I[k6=i] exp
sim(zi,zk)
τ
where I[k6=i] ∈ {0, 1} is an indicator function, τ denotes a temperature parameter and sim (u,v) =
u
T v
kukkvk
is a dot product between l2 and normalized
u, v.
The final loss is calculated across all positive pairs, both (i, j) and (j, i), in
a mini-batch. It was named NT-Xent, the normalized temperature-scaled
cross-entropy loss.
The NT-Xent loss was compared against other commonly used contrastive loss
functions, such as logistic loss and margin loss. Gradient analysis shows that
l2 normalization, cosine similarity, and temperature together effectively weight
different examples and a suitable temperature can make the model learn from
hard negatives. The advantage of NT-Xent is that it weights the negatives by
their relative hardness. Without normalization and proper temperature scaling
the performance is significantly worse. Also, the contrastive task accuracy is
higher, but the resulting representation is worse under linear evaluation.
2.2.6.3 Bootstrap Your Own Latent
The fundamental idea of contrastive learning is to create pairs of images
on which the framework would be trained. Creating negative pairs relies on
large batch sizes, memory banks, or customized mining strategies which can
be challenging in larger datasets. Grill et al. (2020b) wanted to create a
new approach that would achieve better performance than other contrastive
methods without using negative pairs. A solution they have introduced is a
method called Bootstrap Your Own Latent (BYOL). The idea was to bootstrap
representations of images. As a result, BYOL is more robust to the choice of
image augmentations. Furthermore, BYOL has two neural networks, called
online and target network, who interact and learn from each other. Using an
augmented view of an image, BYOL trains its online network to predict the
target network’s representation of another augmented view. This approach
achieved state-of-the-art results when trained on the ImageNet dataset under
2.2 State-of-the-art in Computer Vision 49
the linear evaluation protocol. Additionally, compared to SimCLR, a strong
contrastive baseline, BYOL suffers from much less performance drop when
only random crops are used to augment images.
2.2.6.3.1 Description of the method
BYOL aims to learn a representation of yθ. It uses two neural networks: online
and the target network to achieve that. The online network is determined by a
set of weights θ and consists of:
• an encoder fθ,
• a projector gθ,
• a predictor qθ.
FIGURE 2.29: Bootstrap Your Own Latent (Grill et al., 2020b).
The target network has the same architecture as the online network but
uses different weights ξ. It provides the regression targets to train the online
network, and its parameters ξ are an exponential moving average of the online
parameters θ. Precisely, given a target decay rate τ ∈ [0, 1], after each training
step, the following update
ξ ← τ ξ + (1 − τ )θ
is performed. Firstly, an image is sampled uniformly from D from which two
distributions of image augmentations T and T
0 are created. BYOL applies
respectively two image augmentations t ∼ T and t
0 ∼ T 0
creating two augmented views v , t(x) and v
0 , t
0
(x). First augmented view v is used for
the online network and result in the output yθ , fθ(v) and afterwards the
projection zθ , gθ(y). Similarly, from the second augmented view v
0
the target
network outputs y
0
ξ , fξ(v
0
) and the target projection z
0
ξ , gξ(y
0
). Later on
output a prediction of qθ (zθ) of z
0
ξ
and `2-normalize both qθ (zθ) and z
0
ξ
to
qθ (zθ) , qθ (zθ) / kqθ (zθ)k2
and z¯
0
ξ , z
0
ξ/
z
0
ξ
2
.
The predictor is only applied to the online pipeline, making the architecture
asymmetric between the online and target pipeline. Lastly, the following mean
50 2 Introducing the modalities
squared error between the normalized predictions and target projections is
defined:
Lθ,ξ ,
qθ (zθ) − z¯
0
ξ
2
2
= 2 − 2 ·
D
qθ (zθ), z0
ξ
E
kqθ (zθ)k2
·
z
0
ξ
2
The loss is symmetrized Lθ,ξ by using v
0
for the online network and v for the
target network separately to calculate Leθ,ξ. At each training step, a stochastic
optimization step is applied to minimize L
BYOL
θ,ξ = Lθ,ξ + Leθ,ξ with respect to
θ only but not ξ. BYOL’s dynamics are summarized as
θ ← optimizer
θ, ∇θL
BYOL
θ,ξ , η
.
where η is a learning rate. At the end of the training, only the encoder fθ is
used.
2.2.6.4 Comparison of contrastive learning frameworks
Of all frameworks, SimCLR is the most popular due to its simplicity. The
ResNet-50 in 3 different hidden layer widths (width multipliers of 1×, 2×,
and 4×) were used and trained for 1000 epochs each. The accuracy of these
frameworks on the ImageNet dataset with few labels improved when the width
of ResNet-50 increases. For SimCLR with ResNet-50 top-1 accuracy is 69.3
and top-5 accuracy is 89, while for ResNet-50(4x) top-1 accuracy is 85.8 and
top-5 accuracy is 92.6. These results are comparable with supervised methods.
The BYOL framework was built to improve the results of SimCLR. It was
also stated that the accuracy for the baseline ResNet-50 is 74.3 and 91.6 for
top-1 accuracy and top-5 accuracy. When using ResNet-50(4x), an increase in
accuracy to 78.6 and 94.2 for top-1 and top-5 is observed, respectively. More
information about performance can be found in following table:
Model Architecture Param (M) top-1 acc. top-5 acc.
SimCLR ResNet-50 24 69.3 89.0
SimCLR ResNet-50 (2x) 94 74.2 93.0
SimCLR ResNet-50 (4x) 375 76.5 93.2
BYOL ResNet-50 24 74.3 91.6
BYOL ResNet-50 (x2) 94 77.4 93.6
BYOL ResNet-50 (x4) 375 78.6 94.2
BYOL ResNet-200 (x2) 250 79.6 94.8
2.2 State-of-the-art in Computer Vision 51
2.2.7 Transformers in Computer Vision
Since the first appearance of the Transformers architecture in 2017 ?, it has
become an irreplaceable part of all-natural language processing (NLP) models.
The main advantage of Transformers is that they can be trained on a large text
corpus and then fine-tuned on a smaller task-specific dataset. This enabled
model training of unspecified size with more than 100B parameters.
However, computer vision still relied on convolutional architectures. With
datasets constantly growing and the diversity of the fields computer vision tasks
could be applied to, researchers wanted to implement Transformers architecture
in the CV field. Some works aim for combining CNN-like architectures with
self-attention (Wang and Li, 2018). Others attempted to replace convolutions
entirely, e.g. Ramachandran et al. (2019). Due to specialized attention patterns,
the problem was that they have not yet been scaled effectively on modern
hardware accelerators. Therefore, in large-scale image recognition, classic
ResNet-like architectures are still state-of-the-art.
In 2021 the Google research Brain Team published the paper “An image is worth
16 × 16 words” where they introduced new Transformers-based architecture
for CV called Vision Transformers (ViT) (Dosovitskiy et al., 2020c). Based
on the success of Transformer in NLP scaling, they aimed to apply standard
Transformer directly to images with little as possible changes to the existing
architecture. The image is split into patches and linear embeddings of these
patches are provided as inputs to the Transformer. These patches are the same
as tokens (e.g. words) in NLP. The model is trained for image classification in
a supervised learning fashion.
2.2.7.1 Vision Transformers
Brain Team wanted to create simple but universally scalable architecture to
follow the original Transformers architecture.
2.2.7.1.1 Method
Compared to NLP, with 1-dimensional token embedding input for the Transformer, images are 2-dimensional objects. Firstly, images needed to be represented differently to imitate original architectures as close as possible. For
that reason image x ∈ R
H×W×C is reshaped into a sequence of flattened
2-dimensional patches xp ∈ R
N×(P
2
·C)
, where (H, W) is the resolution of the
original image, C is the number of channels, (P, P) is the resolution of each
image patch, and N = HW/P2
is the resulting number of patches, also the
Transformer’s effective input sequence length. The Transformer input through
all layers is a fixed vector of size D. The first step is to flatten the patches, usually 16 × 16 and map them to D dimensions with a trainable linear projection
to create patch embeddings.
52 2 Introducing the modalities
FIGURE 2.30: Vision Transformer (Dosovitskiy et al., 2020c).
z0 =
xclass ; x
1
pE; x
2
pE; · · · ; x
N
p E
+ Epos, E ∈ R(P
2
·C)×D, Epos ∈ R
(N+1)×D
To this sequence of “patch embeddings”, a prefix learnable [class] token, like in
BERT, is usually added. This token z
0
0 = xclass tells the model to classify the
image and increases the dimension of vector z. Also, the state of this token
at the output of the Transformer encoder
z
0
L
, on which the layernorm is
applied, serves as the image representation y.
y = LN
z
0
L
Furthermore, it is the only one to which the classification head is attached
to during pre-training and fine-tuning. The classification head during pretraining is compiled of MLP with one hidden layer and a single linear layer at
a fine-tuning time. Position embedding, a standard learnable 1-dimensional
position embedding, are attached to the patch embeddings, serving as input to
the encoder. The standard Transformer encoder consists of alternating layers
of multiheaded self-attention and MLP blocks. After each block, a residual
connection is applied.
z
0
` = MSA (LN (z`−1)) + z`−1, ` = 1 . . . L
z` = MLP (LN (z
0
`
)) + z
0
`
, ` = 1 . . . L
Vision Transformer has a significantly lower inductive bias than CNNs in imagespecific information. VIT only has local and translational equivariant MLP
layers, while the self-attention layers are global. A 2-dimensional neighborhood
structure is used sparingly: the image is cut into patches at the beginning
2.3 State-of-the-art in Computer Vision 53
and the position embeddings are resized as needed at the fine-tuning time.
Alternatively, the input sequence can consist of a CNN’s feature map on which
the patch embedding projection is applied. Vision Transformers are pre-trained
on large datasets and fine-tuned to (smaller) downstream tasks. For fine-tuning,
a projection head is removed and a zero-initialized D × K feedforward layer is
attached with K being the number of downstream classes. It is also beneficial
to use higher resolution then in pre-training. Also ViT can handle arbitrary
sequence lengths but the pre-trained position embeddings can become sufficient.
It is necessary to point out that resolution adjustment and patch extraction are
the only points at which an inductive bias about the 2-dimensional structure
of the images is manually injected into the Vision Transformers
2.2.7.1.2 Experiments
Similarly to BERT models, multiple versions of the model at various scales were
created. They have created Base = “B”, Large = “L”, Huge = “H” versions
of ViT, with 12, 24 and 32 layers and 86M, 307M and 632M parameters
respectively.
To explore the model scalability, the previous mentioned dataset ImageNet
was used. In addition, ViT was compared against a slightly modified ResNet
called “ResNet(BiT)”. The batch Normalization layer was replaced with Group
Normalization and used standardized convolutions. Another network that it
was compared to was Noisy Student (Xie et al., 2019), a large EfficientNet.
Experiments showed that ViT Hughe with 14×14 input patch size outperformed
both CNN-based networks with an accuracy of 88.5%, whereas ResNet BiT had
87.54% and Noisy Student 88.4%. It is worth mentioning that ViT Large with
16 × 16 input patch size had 87.76% accuracy on the same dataset. Another
thing worth pointing out is that ViT outperforms CNN-based architectures
on all larger datasets yet performs slightly worse than CNN networks on a
smaller dataset.
2.2.8 Conclusion
In this chapter, the authors presented some of the current state-of-the-art
approaches in Computer Vision. Nowadays, when technology is advancing each
day, creating networks that would imitate human brain is more challenging. Still,
the networks presented in this chapter are highly accurate and creating network
which can out-perform them is challenging. Furthermore, it is noticeable that
the application of CV is dictating the development of networks and frameworks
which help humans with their everyday tasks.
54 2 Introducing the modalities
2.3 Resources and Benchmarks for NLP, CV and multimodal tasks
Author: Christopher Marquardt
Supervisor: Christian Heumann
When we see athletes perform in their sports we only see the results of their
hard work prior or till to the event. Most of the time they casually talk about
their off-season, but everybody knows the results are made in the off-season.
Same goes for the models we will see in the later chapters. We are just interested
in the results, but why and how does the model come to these results? It has
to learn to some key fundamentals of the modality to achieve these results. But
how do they get them to perform in such a way or even better? It’s possible to
build better architectures and/or use more and new data to achieve this. New
data by hand is easy to get but this new data results in a new problem. New
data has to be carefully labeled by humans, which can be very expensive by
the amount of data. Models which learn from labeled data use the supervised
learning strategy. This learning strategy is a bottleneck for future progress,
because of the given reason.
But the need for labeling the data isn’t the only problem. Let’s visit the athlete
analogy again. Imagine a professional football player has to participate in a
professional ski race. He will not be able to compete with the others, because
they are trained only to do ski races. Here see the other problem. Models
which use supervised learning have shown to perform very well on the task
they are trained to do. This means models which learn on carefully labeled
data only perform very well on this specific task, but poor on others. Also it’s
not possible to label everything in the world.
So the goal is to generate more generalist models which can perform well
on different tasks without the need of huge labeled data. Humans are able
to perform well on different tasks in a short amount of time. Humans, for
example, only need a small amount of hours to learn how to drive a car,
even without supervision. On the other hand fully automated driving AI
need thousand of hours of data to drive a car. Why do humans learn so fast
compared to machines? Humans don’t rely on labeled data, because most
of the time humans learn by observation. By this humans generate a basic
knowledge of how the world works, which also called common sense. This
enables us to learn so much faster compared to machines. Meta AI (Yann and
Ishan, 2021) believes that self-supervised learning is one of the most promising
ways to generate background knowledge and some sort of common sense in AI
systems. By self-supervised learning one means a supervised learning algorithm,
but it doesn’t need an external supervisor. Self-supervised pre-training differs
2.3 Resources and Benchmarks for NLP, CV and multimodal tasks 55
between the modalities, which means there is not an approach which works in
all modalities. The following chapter will inspect on the one hand pre-training
resources and the use of them and on the other hand also the benchmarks
which are used for Natural Language Processing (NLP), Computer Vision (CV)
and ,the combination of both, vision language pre-trained models (VL-PTM).
2.3.1 Datasets
After pointing out that pre-training is very important, one might ask how do
the datasets look and how do the different modalities pre-train? At first we
will inspect the former one and focus afterwards on the use of the resources.
As one might expect NLP models pre-train on text, CV models pre-train on
images and VL-PTM pre-train on text image pairs, which can somehow be
seen as a combination of NLP and CV. But CV models mostly used labeled
data like a picture of a dog with the corresponding single label “dog”. MML
datasets can contain several sentences of text which correspond to the given
image.
Even if the datasets might be completely different, the procedure to get the
data is mostly the same for all of them, because the data is crafted from the
internet. This can lead to a problem, since by using this method the resulting
dataset might be noisy. One approach for the VL-PTM, for example, is to
use CommonCrawl and extract the image plus the alt of an image. The alt is
an alternate text for an image, if the image cannot be displayed or for visual
impaired people. This seems like a reasonable approach, but the alt is often
not very informative about what’s in the image.
Another difference between the modalities is the cardinality of the pre-training
data. It’s easy to realize that text is by far easiest to crawl from the internet.
This results in huge high-quality massive text data. Some magnitudes smaller
are the datasets for CV. Since VL-PTM are pretty new compared to the other
modalities it still relatively small, but growing fast. A small downer is that
some of the datasets are not public available. The big companies like to keep
their models and used datasets private, which hinders the reproducibility, but
there are also real open AI competitors like LAION and Eleuther in the field.
The next chapter will provide some of the most used pre-training datasets.
2.3.1.1 Natural Language Processing Datasets
2.3.1.1.1 Common Crawl
As already mentioned, extracting text from the internet is rather easy. More
precisely there is a non-profit organization, called Common Crawl, which does
exactly this. They provide copies of the internet to researchers, companies and
individuals at no cost for the purpose of research and analysis. The Common
Crawl corpus contains petabytes of data collected since 2008. Every month,
Common Crawl releases a snapshot of the web obtained by randomly exploring
56 2 Introducing the modalities
and sampling URLs. It contains raw web page data, extracted metadata and
text extractions. The advantages of Common Crawl come along with their
disadvantages. The text is from diverse domains but with varying quality
of data. To handle the raw nature of the datasets one often has to use a
well-designed extraction and filter to use the datasets appropriately (Gao et al.,
2020). GPT-3 ,for example, uses a filtered version of Common Crawl, which
consists of 410 billion tokens (Brown et al., 2020). So data for NLP is freely
available but one needs to use well-designed extraction and filtering to really
use the dataset.
2.3.1.1.2 The Pile
Recent work (Rosset, 2020) showed that diversity in training datasets improves
general cross-domain knowledge and downstream generalization capability
for language models. The Pile (Gao et al., 2020) was introduced to address
exactly these results. The Pile contains 22 sub-datasets, including established
NLP datasets, but also several newly introduced ones. The size of the 22
sub-datasets, which can be categorized roughly into five categories, pile up to
around 825 GB of data. The following treemap shows the distribution of the
dataset.
While only 13% of the world’s population speaks English, the vast majority of
NLP research is done on English. Gao et al. (2020) followed this trend, but did
not explicitly filtered out other languages when collecting our the data. This
leads to the fact that roughly 95% of the Pile is English. Also EuroParl (Koehn,
2005), a multilingual parallel corpus introduced for machine translation, is
included in the Pile. To train GPT-2 Open AI collected data from WebText.
WebText is an internet dataset created by scraping URLs extracted from
2.3 Resources and Benchmarks for NLP, CV and multimodal tasks 57
Reddit submissions with a minimum score for quality, but sadly it was never
released to the public. Independent researchers reproduced the pipeline and
released the resulting dataset, called OpenWebTextCorpus (Gokaslan and
Cohen, 2019) (OWT). Eleuther created an enhanced version of the original
OWT Corpus called OpenWebText2. It covers all Reddit submissions from
2005 up until April 2020. It covers content from multiple languages, document
metadata, multiple dataset versions, and open source replication code.
They also explicitly included a dataset of mathematical problems (DeepMind
Mathematics) to improve the mathematical ability of language models trained
on the Pile. An ArXiv dataset was in included in the hopes that it will be
a source of high quality text and math knowledge, and benefit potential
downstream applications to research in these areas and also because arXiv
papers are written in LaTeX. Training a language model to be able to generate
papers written in LaTeX could be a huge benefit to the research community.
Since CC needs further steps, due to the raw nature of CC, to really use is.
Pile-CC is Common Crawl-based dataset, which can be used directly. It yields
higher quality output than directly using the WET files. These were only some
of the 22 included datasets. A more detailed description of the sub-dataset
and the reasons why these were included can be found in the corresponding
paper (Gao et al., 2020).
2.3.1.1.3 Multilingual Datasets
Another pre-cleaned version of CC is CC-100 (Wenzek et al., 2019). They
present a pipeline to create curated monolingual corpora in more than 100
languages. A filter, which covers the data based on their distance to Wikipedia,
is used and this improves the quality of the resulting dataset. However, its
English portion is much smaller than the Pile. But a multilingual dataset
might help a low-resource language acquire extra knowledge from other languages. Perhaps the most multilingual corpus publicly available, containing
30k sentences in over 900 languages, is the Bible corpus (Mayer and Cysouw,
2014). Till now all datasets were freely available and almost directly usable.
The next one is not public available for some reasons.
To provide mT5 (Xue et al., 2020), which is multilingual pre-trained text-totext transformer, a suitable pre-training dataset, Google Research designed a
dataset including more than 100 languages. The dataset is called mC4 (Xue
et al., 2020). Since some languages are relatively scarce on the internet, they
used all of the 71 monthly web scrapes released so far by Common Crawl.
It contains 6.6 billion pages and 6.3 trillion tokens. A smaller version of the
mC4 is also used by Google Research. The smaller dataset C4 (Colossal Clean
Common Crawl) was explicitly designed to be English only. The C4 dataset is
a collection of about 750GB of English-language text sourced from the public
Common Crawl web.
58 2 Introducing the modalities
Most of the datasets used in NLP are derived entirely from Common Crawl
and Rosset (2020) came to the result, that the current best practice in training
large-scale language models involve using both large web scrapes and more
targeted, higher-quality datasets, which the Pile directly addresses.
2.3.1.1.4 BooksCorpus
The last dataset for NLP is the BooksCorpus dataset (Zhu et al., 2015). The
BooksCorpus uses books from yet unplished authors from the web. Only books
with more than 20k words were included to filter out shorter, noisier stories.
This results in around 11k books from 16 different genres. So more than 74
million sentences can be used in pre-training. BooksCorpus contains a sample
of books from a distributor of indie ebooks. Sadly a datasheet about the
BooksCorpus was not releasd with the corresponing paper.
Frankly, there was just an paragraph about the content and the extraction
inside the paper (Zhu et al., 2015). Bandy and Vincent (2021) addressed
exactly this short coming. They provided a retrospective datasheet about
the BooksCorpus. Some of their major concerns were copyright violations,
duplicate books, skewed genre representation, potentially skewed religious
representation and also problematic content (18+ content). Little harm can
be expected if an informed adults reads books with these concers, but how
does a language model contribute to for example well-documented gender
discrimination if it trains on these books.
Since BookCorpus is no longer distributed, one has to visit the distributor of
the indie ebooks and collect a own version of the BookCorpus. This is one of
the user-based dataset, besides to the datasets of the Pile.
2.3.1.2 Computer Vision Dataset
2.3.1.2.1 ImageNet
The next inspected modality is CV. Almost every state-of-the-art CV model
uses a classifier pre-trained on an ImageNet based dataset. ImageNet uses
the hierarchical structure of WordNet (Fellbaum, 2010). At the release of
ImageNet-1k the amount of classes was unheard at this time point. Datasets
like CIFAR-10 (Krizhevsky et al., 2009) and CIFAR-100 (Krizhevsky et al.,
2009) had 10 or 100 classes, but ImageNet1k had 1000 different classes and this
was not the only major improvement. They also increased the resolution from
32×32 to 256×256. In all, there are roughly 1.2 million training images, 50,000
validation images, and 150,000 testing images. The ImageNet-1k dataset is a
subset of the ImageNet dataset (Deng et al., 2009). The full ImageNet dataset
is also called ImageNet-21k. It consists of more than 14 million images, divided
in almost 22k classes. Because of this some paper described it as ImageNet-22k.
Those two dataset do not only differ by the amount of classes, but also by
the type of labels. The labels of ImageNet-21k are not mutually exclusive.
2.3 Resources and Benchmarks for NLP, CV and multimodal tasks 59
Because of this the pre-training wiht ImageNet-1k is far more popular. Also
the ImageNet-21k dataset lacks an official train-validation split, which is just
another reason why ImageNet-1k is more popular. The raw dataset ImageNet21k is around 1.3 terabyte (TB). It’s also nice, that the the dataset of ImageNet
are open available. The next dataset is in contrast to this, because it’s not
freely available.
2.3.1.2.2 Joint-Foto-Tree (JFT) & Entity-Foto-Tree (EFT)
The Joint-Foto-Tree (JFT) 300M is one of the follow up version of the JFT
dataset (Hinton et al., 2015b). Given the name it consists of 300 million images
and on average each image has 1.26 labels. The whole datasets has around 375
million labels. These labels can be divided into 18291 classes. These categories
form a rich hierarchy with the maximum depth of hierarchy being 12 and
maximum number of child for parent node being 2876 (Sun et al., 2017). For
example there are labels for 1165 types of animals and 5720 types of vehicles.
The work states that approximately 20% of the labels in this dataset are noisy
(Sun et al., 2017), because the labels are generated automatically.
It also provides the fact, that the distribution is heavily long-tailed, which
means that some of the classes have less than 100 images. There is also an
extendend version of the JFT dataset.
It’s called Entity-Foto-Tree (EFT), because the class labels are physical entities
organized in a tree-like hierarchy, which contains 20 diversified verticals and
consists of 100k classes. It’s even rarely used in practice by Google because of
the intolerable large model size and the slow training speed (Gao et al., 2017).
Honestly, nobody really knows what is inside these datasets, except Google
and they never published a datasheet about it.
These datasets are often used for image classification, but localization-sensitive
tasks like object detection and semantic segmentation are also of interest in
CV.
2.3.1.2.3 Objects365
Objects365 (Shao et al., 2019) is a large-scale object detection and semantic
segmentation freely available dataset. It contains 365 object categories with over
600K training images. More than 10 million, high-quality bounding boxes are
manually labeled through a three-step, carefully designed annotation pipeline.
The ImageNet datasets also contain bounding boxes, but compared Object365
dataset the number of boxes per image is about 15.8 vs 1.1 (Deng et al., 2009).
They collected images mainly from Flicker to make the image sources more
diverse. All the images conform to licensing for research purposes. The dataset
also builds on a tree-like hierarchy with eleven super-categories (human and
related accessories, living room, clothes, kitchen, instrument, transportation,
bathroom, electronics, food (vegetables), office supplies, and animal). Further
60 2 Introducing the modalities
they proposed 442 categories which widely exists in daily lives. As some of
the object categories are rarely found, they first annotate all 442 categories
in the first 100K images and then they selected the most frequent 365 object
categories as their target objects.
To enable compatibility with the existing object detection benchmarks, the
365 categories include the categories defined in Microsoft Common Objects in
Context (COCO) (Lin et al., 2014b), which is described in the next paragraph.
2.3.1.2.4 Microsoft Common Objects in Context (COCO)
Microsoft decided to employed a novel pipeline for gathering data with extensive
use of Amazon Mechanical Turk. Their goal was to create a non-iconic image
collection. Iconic-object images have a single large object in the centered
of the image. By this they provide high quality object instances, but they
also lack information of contextual important and non-canonical viewpoints
(Lin et al., 2014b). Recent work showed that non-iconic images are better
at generalizing (Torralba and Efros, 2011). They mostly used Flickr images,
because they tend to have fewer iconic images. This results in a collection
of 328,000 images. After getting the images they used workers on Amazon’s
Mechanical Turk for the annotation. The workers got a list with 91 categories
and 11 super-categories. At first a worker had to decide if a super-category
(e.g. animal) was present or not. If it was present he had to class the animal
into the appropriate subordinate category (dog, cat, mouse). This greatly
reduces the time needed to classify the various categories and took the workers
about 20k hours to complete. After this the workers had also to do instance
spotting and instance segmentation. For the instance segmentation the workers
had to complete a training task until their segmentation adequately matched
the ground truth. Only 1 in 3 workers passed this training stage. At the end
they added five written captions to each image in the dataset, which is called
Microsoft Common Objects in Context.
At the end they utilized more than 70,000 worker hours to collect a amount of
annotated object instances, which were gathered to drive the advancement of
segmentation algorithms and others tasks. COCO is a dataset which can be
used in CV and also in multi-modal models, because of the image-text pairs.
2.3.1.3 Multi Modal Datasets
The Pile is an attempt from Eleuther to mimic the dataset used for GPT-3
and LAION wants to achieve something similiar. Open AI collected more than
250 million text-images pairs from the internet to train CLIP and DALLE. This dataset does include parts of COCO, Conceptual Captions and a
filtered subset of the Yahoo Flickr Creative Commons 100 Million Dataset
(YFCC100M). YFCC100M contains of a total of 100 million media objects.
The collection provides a comprehensive snapshot of how photos and videos
were taken, described, and shared over the years, from the inception of Flickr
2.3 Resources and Benchmarks for NLP, CV and multimodal tasks 61
in 2004 until early 2014. Also this dataset was never published, even though
the used data is freely available. To address this shortcoming, LAION created
the LAION-400M.
2.3.1.3.1 LAION 400M & 5B
LAION-400M (Schuhmann et al., 2021a) consists of 400 million image-text
pairs. They used Common Crawl and parsed out all HTML IMG tags containing
an alt-text attribute. As already mentioned these alt-texts can sometimes be
very uninformative. So they used CLIP to compute embeddings of the image
and alt-text and droped all samples with a similarity below 0.3. The dataset
also contains the CLIP embedding and kNN indices. Schuhmann et al. (2021a)
describes the procedure to create the dataset in an open manner. They also
ran DALLE-pytroch, an open-source replication of DALL-E, on a subset of
LAION-400M and produced samples of sufficient quality. This opens the road
for large-scale training and research of language-vision models, which was
previously not possible for everyone. It still is difficult, because of the large
amount of data, but at least it’s theoretically possible for everyone. LAION400M is also known as crawling@home (C@H), because they started as a small
group and used only their own computers at the beginning, which is like the
fight of David versus Goliath.
End of March 2022 the team of LAION released a 14× bigger than LAION400M dataset called LAION-5B. It consists of 5.85 billion CLIP-filtered imagetext pairs. A paper about the dataset is right now in progress, but the dataset is
already available to download if you have enough space. The size of the dataset
is about 240 TB in 384 or 80 TB in 224. Due to the nature of the extraction 2,3
billion contain English language, 2,2 billion samples from 100+ other languages
and they also provide a search demo. At the moment LAION-5B is the biggest
openly accessible image-text dataset.
The amount of image-text pairs in LAION-400M or LAION-5B seems incomparable to COCO, but one has to keep in mind, that the text in the COCO
dataset is gathered in a high-quality manner. The COCO dataset is still used,
because of the high quality, even though it was created 2014.
2.3.1.3.2 Localized Narratives
Localized Narratives choose a new form of connecting vision and language in
multi-modal image annotations (Pont-Tuset et al., 2020). They asked annotators to describe an image with their voice while simultaneously hovering
their mouse over the region they are describing. This synchronized approach
enable them to determine the image location of every single word in the
description. Since the automatic speech recognition still results in imperfect
transcription, an additional transcription of the voice stream is needed to
get the written word. The manual transcription step might be skipped in the
future if automatic speech recognition improves and this would result in an
62 2 Introducing the modalities
even more effective approach. They collected Localized Narratives for, the
earlier introduced, COCO (Lin et al., 2014b) dataset, ADE20K (Zhou et al.,
2017), Flickr30k & 32k datasets (Young et al., 2014) and 671k images of Open
Images(Kuznetsova et al., 2020).
Localized Narratives can be used in many different multi-modal tasks, since it
incorporates four synchronized modalities (Image, Text, Speech, Grounding).
Another difference is that the captions are longer than in most previous datasets
(Krishna et al., 2017; Kuznetsova et al., 2020; Lin et al., 2014b) and models
like Imagen (Saharia et al., 2022a) and Parti (Yu et al., 2022a) work well with
long prompts. Beside to that the 849k images with Localized Narratives are
publicly available (Website, 2020).
2.3.1.3.3 WuDaoMM
English is the most spoken language on the world, but Mandarin Chinese
is on the second place and also increasing steadily. So we will also present
a large-scale Chinese multi-modal dataset WuDaoMM (Yuan et al., 2022).
Totally it consists of 650 million image-text pair samples but, they released a
base version dataset containing about 5 million image-text pairs. WuDaoMM
base includes 19 categories and 5 million high-quality images, which can be
used for most of Chinese vision-language model pre-training. They designed
two acquisition strategies according to the correlation types between text and
image. Their collection included data with weak relations, by this they mean
that the texts don’t have tp precisely describe their corresponding images to be
retained, and data with strong relations. These strong relation image-text pairs
were found on professional websites. Most of these images are reviewed for
relevance, content, and sensitivity when they are uploaded. The WuDaoMMbase dataset is a balanced sub-dataset composed of each major category of
the strong-correlated dataset, which is sufficient to support the research and
use of current mainstream pre-training models.
2.3.1.3.4 Wikipedia Image Text (WIT)
The Wikipedia Image Text (WIT) dataset ends this chapter. Most dataset
are only in English and this lack of language coverage also impedes research
in the multilingual mult-imodal space. To address these challenges and to
advance in research on multilingual, multimodal learning they presented WIT
(Srinivasan et al., 2021). They used Wikipedia articles and Wikimedia image
link to extract multiple different texts associated with an image. Additionally
a rigorous filtering was used to retain high quality image-text associations.
This results in a dataset, which contains more than 37.6 million image-text
sets and spans 11.5 million unique images. Due to the multi-modal coverage of
Wikipedia, they provide unique multilingual coverage – with more than 12K
examples in each of the 108 languages and 53 languages have more than 100K
image-text pairs.
2.3 Resources and Benchmarks for NLP, CV and multimodal tasks 63
Another thing which is worth pointing out, is that they could leverage
Wikipedia’s editing, verification and correction mechanism,to ensure a highquality bar. This curation can be seen an huge difference compared to the web
crawls used to create other existing datasets. At the end they even verified
the curated quality of the WIT dataset via an extensive human-annotation
process with an overwhelming majority of 98.5% judging the randomly sampled
image-text associations favorably.
These datasets were just some of the more used dataset. Some of them are
public available while some others are not public available. Normally each
dataset comes with a paper, which describes the procedure way more detailed
than this chapter. This chapter gives just a small insight into the different
datasets and wants to raise the interest into the corresponding papers. Papers
with code delivers research papers with code implementations by the authors
or community. One can get information about the State-of-the-Art model for
every modality and down-task. They also provide available datasets for all
possible tasks.
Datasets are crucial for research and exploration as, rather obviously, data is
required for performing experiments, analyzing designs, and building applications. A particular problem is that the collected data is often not made publicly
available. While this sometimes is out of necessity due to the proprietary or
sensitive nature of the data, this is certainly not always the case. A public
dataset with clearly marked licenses that do not overly impose restrictions on
how the data is used, such as those offered by CC, would therefore be suitable
for use by both academia and industry. But one has to keep in mind that an
effective dataset is a catalyst and accelerator for technological development
(Yuan et al., 2022). This may be a reason, why the big companies don’t share
their datasets, but there are also some other reasons. Another reason might be
the bias which is included in the datastes.
2.3.1.4 Bias In Datasets
Internet access itself is not evenly distributed, which results in a narrow Internet
participation. So internet data overrepresents younger users and those from
developed countries. User-generated content sites present themselves as open
to anyone, but there are factors including moderation practices which make
them less welcoming to specific sub-populations. Take the training data of
GPT-2 as an example. It is sourced by scraping outbound links from Reddit,
and Pew Internet Research’s 2016 (MICHAEL BARTHEL and MITCHELL,
2016) survey reveals 67% of Reddit users in the United States are men, and
64% between ages 18 and 29. Sheng et al. (2019) shedded lights on some of
the gender bias. They used OpenAI’s GPT-2 to generate text given different
prompts. Some of the examples can be seen in the next table.
64 2 Introducing the modalities
Prompt Generated text
The man worked as a car salesman at the local Wal-Mart
The woman worked
as
a prostitute under the name of Hariya
The Black man
worked as
a pimp for 15 years
The White man
worked as
a police officer, a judge, a prosecutor, a prosecutor, and
the president of the United States
The gay person was
known for
his love of dancing, but he also did drugs
The straight person
was known for
his ability to find his own voice and to speak clearly
Datasets obviously encode the social bias that surrounds us, and models trained
on that data may expose the bias in their decisions. The predictions of the
models are based on what the model learned from so we habe to be aware of
this bias.
Dhamala et al. (2021) introduced the Bias in Open-Ended Language Generation Dataset (BOLD), a large-scale dataset that consists of 23,679 English
text generation prompts for bias benchmarking across five domains: profession,
gender, race, religion, and political ideology. They also proposed new automated metrics for toxicity, psycholinguistic norms, and text gender polarity to
measure social biases in open-ended text generation from multiple angles. An
examination of text generated from three popular language models (BERT,
GPT-2, CTRL) revealed that the majority of these models exhibit a large
social bias across all domains. It was also shown that GPT-2 conform more
to social biases than BERT and GPT-3 was trained on filtered version of the
Common Crawl dataset, developed by training a classifier to pick out those
documents that are most similar to the ones used in GPT-2’s training data.
So very likely the same goes for GPT-3. These biases don’t only persist in the
NLP datasets, they can also be found in other modalites.
There exists the so called WordNet Effect which leads to some bias in the CV
datasets. This effects emerges because WordNet includes words that can be
perceived as pejorative or offensive. N*****r and wh**e are just two examples
which can be found in WordNet. Prabhu and Birhane (2020) investigated
problematic practices and the consequences of large scale vision datasets.
Broad issues such as the question of consent and justice as well as specific
concerns such as the inclusion of verifiably pornographic images in datasets
were revealed. Two days after the publication of the paper (Prabhu and Birhane,
2020), the TinyImages was withdrawn, because of their findings. Torralba,
Fergus, Freeman, the creator of TinyImages, also argued that the offensive
images were a consequence of the automated data collection procedure that
relied on nouns from WordNet. MS-Celeb (Guo et al., 2016) was also retracted
2.3 Resources and Benchmarks for NLP, CV and multimodal tasks 65
for the same reasons. It would be very surprising if these kinds of problems
where not present in other databases for this kind of research, especially as we
get to extremely dataset sizes. Despite retractions, datasets like TinyImages
and MS-Celeb remain widely available through file sharing websites.
Even if LAION-400M opened the road for large-scale training and research of
language-vision models for everyone, their curation pipeline involves CLIP. One
might argue, that this approach will potentially generate CLIP-like models and
it is known that CLIP inherits various biases (Radford et al., 2021a). Birhane
et al. (2021) found that the LAION-400M dataset contains, troublesome and
explicit images and text pairs of rape, pornography, malign stereotypes, racist
and ethnic slurs, and other extremely problematic content and you can be
pretty sure that the same holds for LAION-5B, as it uses the same curation
pipeline. This shows even more that large institutions should open up their
datasets to both internal and external audits in a thoughtful manner. We
have to fully understand the risks of using such datasets and this is not
achievable by the used approach. Despite all these concerns, the next chapters
will demonstrate how the different datasets are used, but it is important to
keep these concerns in mind.
2.3.2 Pre-Training Tasks
Yann LeCun and Ishan Misra suggest in their blogpost that supervised pretraining is gone because of the already mentioned reasons at the beginning and
the future will be self-supervised pre-training (Yann and Ishan, 2021). Meta AI
wants to create a background knowledge in the models that can approximate
the common sense of humans. This suggestion is even more reasonable, because
recent work (Mineault, 2021) also showed that a self-supervised or a unsupervised pre-training approach is biologically more plausible than supervised
methods. This why neuroscientists are taking interest in unsupervised and
self-supervised deep neural networks in order to explain how the brain works
(Zhuang et al., 2021).
Self-supervised learning (SSL) is also called predictive learning. This comes by
the nature of the process. The general technique of self-supervised learning
is to predict any unobserved or hidden part (or property) of the input from
any observed or unhidden part of the input (Yann and Ishan, 2021). Models
like BERT try to predict between known intervals and GPT-3 predicts the
future, given the past. A part of a sentence is hidden and the model tries to
predict the hidden words from the remaining ones. Predicting missing parts of
the input is one of the more standard tasks for SSL pre-training. To complete
a sentence with missing parts the system has to learn how to represent the
meaning of words, the syntactic role of words, and the meaning of entire texts.
These missing parts tasks are easy to implement in NLP compared to CV. In
NLP the solution space is finite, because one estimates a distribution from,
66 2 Introducing the modalities
a before specified, dictionary. In CV the solution space is infinite, because it
is not possible to explicitly represent all the possible frames and associate a
prediction score to them (Yann and Ishan, 2021).
Meta AI proposed an unified view of self-supervised method. They say an
energy-based model (EBM) is a system that, given two inputs, x and y, tells
us how incompatible they are with each other (Yann and Ishan, 2021). If the
energy is high, x and y are deemed incompatible; if it is low, they are deemed
compatible.
The idea sounds simple, but it is difficult to achieve this. An usual approach
is to take an image and create an augmented version of the image. By this
approach the energy has to be low, because it’s from save picture. For example
one can gray scale the image. By this we say the model the color does not
matter. Bromley et al. (1993) proposed this kind of approach under the name
Siamese networks. The difficulty is to make sure that the networks produce
high energy, i.e. different embedding vectors, when x and y are different images.
The problem is that these Siamese networks tend to collapse. When a collapse
occurs, the energy is not higher for nonmatching x and y than it is for matching
x and y. So the networks ignore their input and produce the same embeddings.
This lead to so called contrastive methods. The method used to train NLP
systems by masking or substituting some input words belongs to the category
of contrastive methods. Contrastive methods are based on the simple idea
of constructing pairs of x and y that are not compatible, and adjusting the
parameters of the model so that the corresponding output energy is large. The
problem is that they are very inefficient to train. For a contrastive methods
one needs so called hard negatives. These are images that are similar to image
x but different enough to still produce a high energy. This is a major issue
of contrastive methods. So Self-supervised representation learning relies on
negative samples to prevent collapsing to trivial solutions.
So the best idea is to get rid of the hard negatives and BYOL (Grill et al.,
2020a) is one approach that achieved exactly this. They create two slightly
different variants of an image by applying two random augmentations, like a
random crop, a horizontal flip, a color jitter or a blur. A big difference to the
Siamese network is that they use different parameters in the encoder. They
use so called online and target parameters. The target parameters are never
learned, they are just copied over from the online parameters, but they use an
exponential moving average. So it’s some kind of a lagged version of the online
parameters. BYOL achieves to learn a representation of an image, without
using negative pairs, just by predicting previous versions of its outputs.
Still they say, that BYOL remains dependent on existing sets of augmentations
and these augmentations require human intention and automating the search
for these augmentations would be an important next step, if this is even
possible (Grill et al., 2020a).
2.3 Resources and Benchmarks for NLP, CV and multimodal tasks 67
He et al. (2022) recently came very close to the MLM pre-training used in
BERT with their masked autoencoder (MAE). They leveraged transformers
and autoencoders for self-supervised pre-training. An autoencoder is an encoder
that maps the observed signal to a latent representation, and a decoder that
reconstructs the original signal from the latent representation. The MAE is a
form of denoising autoencoding exactly like the MLM. Their approach is to
divide an image into, for example, 16 × 16 patches. Then remove 75% of the
patches and just use the remaining 25% in their huge encoder. Important to
add is that the position embeddings are also used in the encoder. The input of
the decoder is again the full set of tokens consisting of the unmasked and the
masked tokens. So the MAE has to reconstruct the input by predicting the pixel
values for each masked patch. Autoencoding pursues a conceptually different
direction compared to BYOl or DINO, which are based on augmentation.
Still their reconstructions look kind of blury, but the learned representations
are already very rich. Interesting to note is also that BERT removes only 15%
of the data where MAE removes 75% of the data.
Dual encoder models like CLIP (Radford et al., 2021a) and ALIGN (Jia et al.,
2021b) demonstrated in the past that contrastive objectives on noisy image-text
pairs can lead to strong image and text representations. One thing to mention
is, that contrastive objectives are easier to implement in vision-language models
(VLM) than in CV. This comes from the fact that VLM use image-text pairs.
As a dual encoder CLIP encodes the image and text and by construction
the text which corresponds to the image or vice versa achieves the highest
similarity and the other texts will have a lower similarity. So one already has
some hard negatives already available and don’t has to search for some.
Through the SSL the models already learned a good representation of the given
input, but fine-tuning models leads to even better results. This chapter will
just provide an rough sketch, since fine-tuning heavily depends on the model
and the down-stream task. Also fine-tuning will be shown in later chapters.
Fine-tuning means updating the weights of a pre-trained model by training
on a supervised (labeled) dataset to a specific down-task. A huge amount of
data is needed to fine-tune a model. This is also the main disadvantage of
fine-tuning, because one needs new large dataset for every possible down-task.
After pre-training and fine-tuning the models there is a need to compare the
models, because one always seeks to find the best model among all competitors.
This need lead to the creation of datasets for test purposes which are often
called benchmarks.
2.3.3 Benchmarks
As models got better over time, because of bigger datasets or better pre-training
tasks, it’s important to create and use new benchmarks. Interestingly there
are also benchmark, which rely only on Zero-Shot performance. Zero-shot
68 2 Introducing the modalities
learning (ZSL) is a problem in machine learning, where during test time, a
model observes samples from classes not observed during training. So it has to
complete a task without having received any training examples. By this the
model has to generalize on a novel category of samples.
But the most common approach is to use a part of the datasets which was not
used to train the model. To make this possible the pre-training datasets are
divided into training, test and validation sets. It’s clear that the models must
not be tested on the training data.
This splitting results in so called held-out data, but Rajpurkar et al. (2018)
showed, that this held-out datasets are often not comprehensive, and contain
the same biases as the training data. Recht et al. (2019) also proposed that
these held-out datasets may overestimate the real-world performance.
Something to consider is also that pre-training on large internet datasets may
lead to the unintentional overlap of pre-training and down-tasks. Because of
this studies (Radford et al., 2021a, Yu et al. (2022a), Brown et al. (2020))
conducted a de-duplication analysis. CLIP analysis resulted in a median overlap
of 2.2% and an average overlap of 3.2%, but they also observed that the overall
accuracy is rarely shifted by more than 0.1% (Radford et al., 2021a). Mahajan
et al. (2018), Kolesnikov et al. (2019) also came to the similar results, but it’s
still something to keep in mind.
Some of the already mentioned datasets like COCO and the ImageNet versions
are often used for CV or VLM. Almost every state-of-the-art CV model uses
a classifier pre-trained on an ImageNet based dataset and benchmarked on
the validation sets of the dataset. A another small downer is that the models
of the big companies are usually trained on different datasets, but at least
compared on the same benchmarks. So the comparison seems a bit odd. Maybe
the better performance of the models comes from the different pre-training
datasets.
2.3.3.1 Natural Language Processing Benchmarks
2.3.3.1.1 (Super)GLUE
The goal of NLP is the development of general and robust natural language
understanding systems. Through SSL models gain a good “understanding”
of language in general. To benchmark this good “understanding” General
Language Understanding Evaluation (GLUE) was created. It’s a collection
of nine different task datasets. These datasets can be divided into the SingleSentence Tasks, Similarity and Paraphrase Tasks and Inference Tasks.
The Single-Sentence Tasks consist of the Corpus of Linguistic Acceptability
(CoLA) and The Stanford Sentiment Treebank (SST-2). Each example in the
CoLA is a sequence of words annotated with whether it is a grammatical English
2.3 Resources and Benchmarks for NLP, CV and multimodal tasks 69
sentence. SST-2 uses sentences from movie reviews and human annotations of
their sentiment. The task is to predict the sentiment of a given sentence.
For the Similarity and Paraphrase Tasks the Microsoft Research Paraphrase
Corpus (MRPC), Quora Question Pairs (QQP) and the Semantic Textual
Similarity Benchmark (STS-B) are used. MRPC is a corpus of sentence pairs
automatically extracted from online news sources, with human annotations for
whether the sentences in the pair are semantically equivalent. The model has
to predict if sentence B is a paraphrase of sentence A. The STS-B sub-task
dataset consist of a collection of sentence pairs drawn from news headlines,
video and image captions, and natural language inference data. Each pair is
human-annotated with a similarity score from 1 to 5. The task for the model is
to predict these similarity scores. QQP is a collection of question pairs from the
community question-answering website Quora. Here the model has to predict
if a pair of questions are semantically equivalent.
Lastly The Multi-Genre Natural Language Inference Corpus (MNLI), the
Stanford Question Answering Dataset (QNLI), The Recognizing Textual
Entailment (RTE) dataset and the Winograd Schema Challenge (WNLI) are
used in the Inference Tasks. WNLI is a crowdsourced collection of sentence
pairs with textual entailment annotations. The task is to predict whether
the premise entails the hypothesis (entailment), contradicts the hypothesis
(contradiction), or neither (neutral). QNLI is a question-answering dataset
consisting of question-paragraph pairs, where one of the sentences in the
paragraph contains the answer to the corresponding question. The task
is to determine whether the context sentence contains the answer to the
question. RTE comes from a series of annual textual entailment challenges.
WNLI is a reading comprehension task in which a system must read a
sentence with a pronoun and select the referent of that pronoun from a list
of choices. In the following table is a short summary of all GLUE tasks.
A nice topping is that GLUE also provides a leaderboard with a human
benchmark. So the models can compete against each other and a human
70 2 Introducing the modalities
benchmark. After a short period of time the models started to surpass the
human benchmark, which lead to creation of SuperGLUE.
SuperGLUE also consists of a public leaderboard built around eight language
understanding tasks, drawing on existing data, accompanied by a single-number
performance metric, and an analysis toolkit. SuperGLUE surpassed GLUE
because of more challenging tasks, more diverse task formats, comprehensive
human baslines, improved code support and refinded usage rules. The following
figure gives a short summary of the SuperGLUE tasks.
FIGURE 2.31: taken from https://mccormickml.com
The GLUE and SuperGLUE tasks are more or less reduced to a classification
problem. One might argue if this is really General Language Understanding,
but we will see other benchmarks which try evaluate that in an other way.
However it’s also of interest to check if the models understand what they
2.3 Resources and Benchmarks for NLP, CV and multimodal tasks 71
are reading. The act of understanding what you are reading is called reading
comprehension (RC). RC requires both understanding of natural language and
knowledge about the world.
2.3.3.1.2 Stanford Question Answering Dataset (SQuAD) (1.0 & 2.0)
Rajpurkar et al. (2016) introduced the Stanford Question Answering Dataset
(SQuAD), a large reading comprehension dataset on Wikipedia articles with
human annotated question-answer pairs. SQuAD contains 107,785 questionanswer pairs on 536 articles and it does not provide a list of answer choices
for each question. The model must select the answer from all possible spans
in the passage, thus needing to cope with a fairly large number of candidates.
The problem is that the it’s guaranteed that the answer exist in the context
document.
To address this weakness Rajpurkar et al. (2018) presented SQuAD 2.0, the
latest version of SQuAD. SQuAD 2.0 combines existing SQuAD data with
over 50,000 unanswerable questions written adversarially by crowdworkers to
look similar to answerable ones.
Rajpurkar et al. (2018) contribution to NLP is not that they provide a deeper
glimpse into the workings of QA systems, they also facilitated the creation
of more non-English datasets. Korean, Russian, Italian, Spanish, French and
Arabic versions of SQuAD exist around the world. XQuAD, MLQA and TyDi
are multilingual question-answering datasets. XQuAD is a subset of SQuAD
translated into 10 different language by professional translators. These kinds
of resources are crucial in ensuring that the societal benefits of NLP can also
be felt by speakers of lower resourced languages.
2.3.3.1.3 Beyond the Imitation Game Benchmark (BIG-bench)
The mentioned ones are rather old compared to Beyond the Imitation Game
Benchmark (BIG-bench) (Srivastava et al., 2022). It’s a collaborative benchmark intended to probe large language models and extrapolate their future
capabilities. BIG-bench already contains more than 200 tasks. They claim
that current language-modeling benchmarks are insufficient to satisfy our need
to understand the behavior of language models and to predict their future
behavior. They mainly provide three reasons for that. One of them is the
short useful lifespans. When human-equivalent performance is reached for
these benchmarks, they are often either discontinued. One might call this
“challenge-solve-and-replace” evaluation dynamic.
To prevent this they encourage new task submissions and literally everybody
can submit a task to BIG-Bench. So they call BIG-bench a living benchmark.
The review of the tasks is based on ten criteria. It includes for example
“Justification”. One has to give background motivating why this is an important
capability of large language models to quantify. With the inclusion of small tasks
72 2 Introducing the modalities
they want to improve the diversity of topics covered and enable domain experts
to contribute tasks without the difficulties of distributed human labeling.
Another reason for the insufficients is because the others benachmarks are
narrowly targeted, and because their targets are often ones that language
models are already known to perform. So it’s not possible to identify new
and unexpected capabilities that language models may develop with increased
scale, or to characterize the breadth of current capabilities.
Finally, many current benchmarks use data collected through human labeling
that is not performed by experts or by the task authors. Their benchmark tasks
are primarily intended to evaluate pre-trained models, without task-specific
fine-tuning. By focusing on such tasks in the zero- and few-shot evaluation
setting, it becomes possible to provide meaningful scores for even those tasks
with a very small number of examples.
The “everybody can submit” strategy also leads to inclusion a variety of
tasks covering non-English languages. Till now the large language models, like
GPT-3 and PaLM, perform poorly on BIG-bench relative to expert humans,
which is maybe a good sign for the future. But superhuman performance on
SuperGLUE benchmark was achieved in less than 18 months after it was
produced.
2.3.3.1.4 WMT
There is a family of datasets which is the most popular datasets used to
benchmark machine translation systems. Workshop on Machine Translation
(WMT) is the main event for machine translation and machine translation
research. This conference is held annually. WMT includes competitions on
different aspects of machine translation. These competitions are known as
shared tasks. Typically, the task organisers provide datasets and instructions.
Then teams can submit their output of their models. The submissions are
ranked with human evaluation.
Most of the models are evaluated on bi-lingual translation like English-toGerman, but there are also tri-linguar tasks like using English to improve
Russian-to-Chinese machine translation. One of the most popular NLP metrics
is called the Bleu Score and this metric is also used in the WMT tasks. It
is based on the idea that the closer the predicted sentence is to the humangenerated target sentence, the better it is. Bleu Scores are between 0 and 1,
but a score of 0.6 or 0.7 is considered the best you can achieve.
Problematic is that Bowman and Dahl (2021) claim that the evaluation for
many natural language understanding (NLU) tasks are broken. They claim that
unreliable and biased systems score so highly on standard benchmarks that
there is little room for researchers who develop better systems to demonstrate
their improvements. They provide four criteria to handle this:
2.3 Resources and Benchmarks for NLP, CV and multimodal tasks 73
1. Good performance on the benchmark should imply robust in-domain
performance on the task
2. Benchmark examples should be accurately and unambiguously annotated
3. Benchmarks should offer adequate statistical power
4. Benchmarks should reveal plausibly harmful social biases in systems,
and should not incentivize the creation of biased systems
Building new benchmarks that improve upon these four axes is likely to be
quite difficult.
2.3.3.1.5 CheckList
Inspired by principles of behavioral testing in software engineering, Ribeiro et al.
(2020) introduced CheckList, a model-agnostic and task-agnostic methodology
for testing NLP models. CheckList includes a matrix of general linguistic
capabilities and test types that facilitate comprehensive test ideas, as well as
a software tool to generate a large and diverse number of test cases quickly.
To break down potential capability failures into specific behaviors, CheckList
introduces three different test types. A Minimum Functionality test (MFT),
inspired by unit tests in software engineering, is a collection of simple examples
to check a behavior within a capability. An Invariance test (INV) is when
label-preserving perturbations to inputs are applied and the model prediction
are expected to remain the same. A Directional Expectation test (DIR) is
similar, except that the label is expected to change in a certain way.
Tests created with CheckList can be applied to any model, making it easy to
incorporate in current benchmarks or evaluation pipelines and CheckList is
open source. Their goal was to create a benchmark which goes beyond just
accuracy on held-out data.
2.3.3.2 Computer Vision Benchmarks
CV models try to answer visual tasks. A visual task is a task which can be solved
only by visual input. Often visual task can be solved as a binary classification
problem, which is called image classification, but there are also numerous other
applications for CV. This chapter will focus on image classification, semantic
segmentation and object detection with their usual benchmarks datasets.
2.3.3.2.1 ImageNet Versions
It’s not only common to pre-train your model on ImageNet datasets it’s also
common to benchmark the models on them. There are many different variants
of ImageNet. There is ImageNet-R, a version with non-natural images such
as art, cartoons and sketches, or ImageNet-A, which is a a more challenging
version because they use adversarial images (Goodfellow et al., 2014d), or
ImageNet-V2 (Recht et al., 2019). The last was created to check whether
74 2 Introducing the modalities
there is an over-fitting on the classic pre-training ImageNet dataset. They
followed the creation process of the original dataset and tested to what extent
current classification models generalize to new data. Recht et al. (2019) found
accuracy drops for all models and suggested that these drops are not caused
by adaptivity, but by the models’ inability to generalize to slightly “harder”
images than those found in the original test sets.
The goal of image classification is to classify the image by assigning a label.
Typically, Image Classification refers to images in which only one object
appears. To asses the performance one mainly uses Top-1 accuracy, the model’s
answer with highest probability must be exactly the expected answer, or Top-5
accuracy. Top-5 accuracy means that any of five highest probability answers
must match the expected answer. Beyer et al. (2020) tried to answer the
question “Are we done with ImageNet?” in their paper. Many images of the
ImageNet dataset contain a clear view on a single object of interest: for these, a
single label is an appropriate description of their content. However many other
images contain multiple, similarly prominent objects, limiting the relevance of
a single label (Beyer et al., 2020). In these cases, the ImageNet label is just
one of many equally valid descriptions of the image and as a result an image
classifier can be penalized for producing a correct description that happens to
not coincide with that chosen by the ImageNet label.
In short a single label per image is not sufficient in many cases. They concluded
yes and no as an answert to the question “Are we done with ImageNet?”. The
shortcomings of ImageNet labels and their accuracy were identified and they
provided a new ImageNet validation set ReaL (Beyer et al., 2020) (“Reassessed
Labels”) and also a new metric, called ReaL accuracy (Beyer et al., 2020). The
ReaL accuracy measures the precision of the model’s top-1 prediction, which
is deemed correct if it is included in the set of labels. these findings suggested
that although the original set of labels may be nearing the end of their useful
life, ImageNet and its ReaL labels can readily benchmark progress in visual
recognition for the foreseeable future.
An addition of a localization tasks to the classification tasks results into object
detection. It is used to analyze more realistic cases, like mentioned above, in
which multiple objects may or may not exist in an image. The location of an
object is typically represented by a bounding box.
2.3.3.2.2 MS-COCO & Object365
In the recent years, the Microsoft COCO dataset or the Object365 data have
become the standards to evaluate object detection algorithms, but it’s also
possible to use a ImageNet dataset. The primary challenge metric is called mean
Average Precision (mAP) at Intersection over Union (IoU) =.50:.05:.95. The
IoU is the intersection of the predicted and ground truth boxes divided by the
union of the predicted and ground truth boxes. IoU, also called Jaccard Index,
values range from 0 to 1. Where 0 means no overlap and 1 means perfect overlap.
2.3 Resources and Benchmarks for NLP, CV and multimodal tasks 75
But how is precision captured in the context of object detection? Precision is
known as the ratio of T rue P ositive/(T rue P ositive +F alse P ositive). With
the help of the IoU threshold, it’s possible to decide whether the prediction is
True Positive(TP), False Positive(FP), or False Negative(FN). The example
below shows predictions with IoU threshold α set at 0.5.
The .50:.05:.95 means that one uses 10 IoU thresholds of
{0.50, 0.55, 0.60, . . . , 0.95}. COCO uses this as primary metric, because
it rewards detectors with better localization (Mircosoft, 2019).
Object detection and image segmentation are both tasks which are concerned
with localizing objects of interest in an image, but in contrast to object detection
image segmentation focuses on pixel-level grouping of different semantics.
Image segmentation can be splitted into various tasks including instance
segmentation, panoptic segmentation, and semantic segmentation. Instance
segmentation is a task that requires the identification and segmentation of
individual instance in an image. Semantic segmentation is a task that requires
segmenting all the pixels in the image based on their class label. Panoptic
segmentation is a combination of semantic and instance segmentation. The
task is to classify all the pixels belonging to a class label, but also identify
what instance of class they belong to. Panoptic and instance segmentation is
often done on COCO.
2.3.3.2.3 ADE20k
Semantic segmentation can be done one ADE20K(Zhou et al., 2017). ADE
are the first three letters of the name Adela Barriuso, who single handedly
annotated the entire dataset and 20K is a reference to being roughly 20,000
images in the dataset. This dataset shows a high annotation complexity, because
any image in ADE20K contains at least five objects, and the maximum number
of object instances per image reaches 273. To asses the performance of a model
on the ADE20K dataset one uses the mean IoU. It indicates the IoU between
the predicted and ground-truth pixels, averaged over all the classes.
In contrast to the object detection task, the definition of TP, FP, and FN is
slightly different as it is not based on a predefined threshold. TP is now the
76 2 Introducing the modalities
area of intersection between Ground Truth and segmentation mask. FP is the
predicted area outside the Ground Truth. FN is the number of pixels in the
Ground Truth area that the model failed to predict. The calculation of IoU is
the same as in object detection tasks. It’s the intersection of the predicted and
ground truth boxes aka. TP divided by the union of the predicted and ground
truth boxes, which is essentially T P + F N + F P. A example is shown down
below.
FIGURE 2.32: taken from https://learnopencv.com
2.3.3.3 Multi-Modal Benchmarks
Visual understanding goes well beyond object recognition or semantic segmentation. With one glance at an image, a human can effortlessly imagine the
world beyond the pixels. This is emphasized by the quote “a picture says more
then a thousand words”. High-order of cognition and commonsense reasoning
about the world is required to infer people’s actions, goals, and mental states.
To answer visual understanding tasks a models needs to leverage more than
one modality.
2.3.3.3.1 Visual Commonsense Reasoning (VCR)
Visual understanding tasks require seamless integration between recognition
and cognition and this task can be formalize as Visual Commonsense Reasoning
(VCR). Zellers et al. (2019) introduce a new dataset called VCR. It consists
of 290k multiple choice QA problems derived from 110k movie scenes. The
key recipe for generating non-trivial and high-quality problems at scale is
Adversarial Matching. Incorrect choices are obtained via maximum-weight
bipartite matching between queries and responses. This matching transforms
rich annotations into multiple choice questions with minimal bias. VCR casted
as a four-way multiple choice task.
The underlying scenes come from the Large Scale Movie Description Challenge
and YouTube movie clips and they searched for interesting an diverse situations to ensure this they trained and applied an “interestingnes filter”. The
most interesting images were passed to Workers of Amazon Mechanical Turk.
Additional context in form of video caption was given to the worker. After
2.3 Resources and Benchmarks for NLP, CV and multimodal tasks 77
reading this they had to propose one to three questions about the image. For
each question, they had to provide a reasonable answer and a rationale. This
results is an underlying dataset with high agreement and diversity of reasoning.
Almost every answer and rationale is unique. To make these cognition-level
questions simple to ask, and to avoid the clunkiness of referring expressions,
VCR’s language integrates object tags ([person2]) and explicitly excludes referring expressions (‘the woman on the right.’). These object tags are detected
from Mask-RCNN. The following types of questions are in the benchmarks:
38% Explanation (‘Why is [person11] wearing sunglasses inside?’), 24% Activity (’What are [person1] and person[2] doing¿‘), 13% Temporal (”What will
[person6] do after unpacking the groceries?“), 8% Mental, 7% Role, 5% Scene,
5% Hypothetical.
So in this setup, a model is provided a question, and has to pick the best answer
out of four choices. Only one of the four is correct. If the model answered
correctly a new question, along with the correct answer, is provided. Now the
model has to justify it by picking the best rationale out of four choices. The
first part is called Question Answering (Q → A) and the second part Answer
Justification (QA → R). They combine both parts into a Q → AR metric, in
which a model only gets a question right if it answers correctly and picks the
right rationale. If it gets either the answer or the rationale wrong, the entire
prediction will be wrong. Models are evaluated in terms of accuracy.
The results at the release were that humans find VCR easy (over 90% accuracy),
and state-of-the-art vision models struggle ( 45%). At the moment of writing,
the best model achieves 85.5 in (Q → A), 87.5 in (QA → R) and 74.9 in
Q → AR. So the models are closing the gap but VCR is still far from solved.
An “simpler” approach to evaluate vision-language models is to ask questions
without reasoning about an image.
2.3.3.3.2 Visual Question Answering 1.0 & 2.0 (VQA)
For this reason Antol et al. (2015) created an open-ended answering task
and a multiple-choice task. Their dataset contains roughly 250k images, 760k
questions, and 10M answers. 204k images are taken from the MS COCO
dataset but also newly created created datasets are used. Three questions
were collected for each image or scene. Each question was answered by ten
subjects along with their confidence. The dataset contains over 760K questions
with around 10M answers. “what”-, “how”-, “is”- questions are mainly used in
the benchmark. But they had major flaws in their creation. An model which
blindly answering “yes” without reading the rest of the question or looking at
the associated image results in a VQA accuracy of 87% or the most common
sport answer “tennis” was the correct answer for 41% of the questions starting
with “What sport is”, and “2” is the correct answer for 39% of the questions
starting with “How many” (Antol et al., 2015).
78 2 Introducing the modalities
Zhang et al. (2016b) pointed out a particular ‘visual priming bias’ in the VQA
dataset. Zhang et al. (2016b) showed that language provides a strong prior that
can result in good superficial performance, without the underlying models truly
understanding the visual content. Zhang et al. (2016b) collected a balanced
dataset containing pairs of complementary scenes to reduce or eliminate the
strong prior of the language. Goyal et al. (2017) did the same and made a
second iteration of the Visual Question Answering Dataset and Challenge
(VQA v2.0). Goyal et al. (2017) balanced the popular VQA dataset (Antol
et al., 2015) by collecting complementary images such that every question in
balanced dataset is associated with not just a single image, but rather a pair
of similar images that result in two different answers to the question. The
dataset is by construction more balanced than the original VQA dataset and
has approximately twice the number of image-question pairs.
2.3.3.4 GQA
Hudson and Manning (2019) introduced the GQA dataset for real-world visual
reasoning and compositional question answering. It consists of 113K images
and 22M questions of assorted types and varying compositionality degrees, measuring performance on an array of reasoning skills such as object and attribute
recognition, transitive relation tracking, spatial reasoning, logical inference
and comparisons. They also proposed Consistency, Validity and Plausibility
as new measures to get more insight into models’ behavior and performance.
Consistency measures responses consistency across different questions. To
achieve a high consistency a model may require deeper understanding of the
question semantics in context of the image. The validity metric checks whether
a given answer is in the question scope, e.g. responding some color to a color
question. The plausibility score goes a step further, measuring whether the
answer is reasonable, or makes sense, given the question (e.g. elephant usually
do not eat pizza).
They even made a comparison between GQA and VQA 2.0. They came to
the conclusion that the questions of GQA are objective, unambiguous, more
compositional and can be answered from the images only, potentially making
this benchmark more controlled and convenient for making research progress
on. Conversely, VQA questions tend to be a bit more ambiguous and subjective,
at times with no clear and conclusive answer. Finally, we can see that GQA
provides more questions for each image and thus covers it more thoroughly
than VQA.
2.3.3.4.1 Generative Benchmarks
Almost everybody is talking right now about generative models like DALL-E2,
Imagen, Parti. It seems like every month a new one is presented. But how can
we compare these models? Automatic image quality and automatic image-text
alignment are two reasonable evaluation metrics. Fréchet Inception Distance
2.3 Resources and Benchmarks for NLP, CV and multimodal tasks 79
(FID) can be used as primary automated metric for measuring image quality.
The Frechet Inception Distance compares the distribution of generated images
with the distribution of real images that were used to train the generator.
A small value is wanted, as it’s a distance measure. Text-image fit can be
captured through automated captioning evaluation. For this an image output
by the model is captioned with a model, which is able to do image captioning.
The similarity of the input prompt and the generated caption is then assessed
via BLEU, CIDEr, METEOR and SPICE and also human evaluation is done.
Here different generative models are used with the same prompts and the
human is asked to choose which output is a higher quality image and which
is a better match to the input prompt. One always has to keep in mind, that
the images of the generative models are always “cherry picked”. They do not
typically represent, for example, a single shot interaction in which the model
directly produces such an image. To make this clear, Yu et al. (2022a) showed
their way of growing the cherry tree.
FIGURE 2.33: taken from Parti Paper
80 2 Introducing the modalities
2.3.3.4.2 PartiPrompts, DrawBench, Localized Narratives
In a sense, this is a form of model whispering as one stretches such models to
their limits. Besides to that they also present PartiPrompts (P2) which is a set
of over 1600 (English) prompts curated to measure model capabilities across a
variety of categories and controlled dimensions of difficulty. P2 prompts can
be simple, but can also be complex, such as 67-word description they created
for Vincent van Gogh’s The Starry Night. DrawBench is a similar dataset.
Also the Localized Narratives dataset from the dataset section consists of long
prompts and though it can also be used as a benchmark for generative models.
Current benchmarks give a good perspective on model performance on a wide
range of V&L tasks, but the field is only starting to assess why models perform
so well and whether models learn specific capabilities that span multiple V&L
tasks.
2.3.3.4.3 FOIL it!
Shekhar et al. (2017) proposed an automatic method for creating a large dataset
of real images with minimal language bias and some diagnostic abilities. They
extended the MS-COCO dataset and created FOIL-COCO. FOIL stands for
“Find One mismatch between Image and Language caption” and consists
of images associated with incorrect captions. The captions are produced by
introducing one single error (or ‘foil’) per caption in existing, human-annotated
data. So each datapoint FOIL-COCO can be described as triplet consisting of
an image, original and foil caption. Their data generation process consists of
four main steps:
1. Generation of replacement word pairs
2. Splitting of replacement pairs into training and testing
3. Generation of foil captions
4. Mining the hardest foil caption for each image
The models are evaluated on three different tasks. The first one is Correct
vs. foil classification. Given an image and a caption, the model is asked to mark
whether the caption is correct or wrong. The aim is to understand whether
LaVi models can spot mismatches between their coarse representations of
language and visual input. The second task is Foil word detection. Given an
image and a foil caption, the model has to detect the foil word. The aim is
to evaluate the understanding of the system at the word level. The last task
Foil word correction. Given an image, a foil caption and the foil word, the
model has to detect the foil and provide its correction. The aim is to check
whether the system’s visual representation is fine-grained enough to be able
to extract the information necessary to correct the error. Their hypothesis is
that systems which, like humans, deeply integrate the language and vision
modalities, should spot foil captions quite easily.
2.3 Resources and Benchmarks for NLP, CV and multimodal tasks 81
2.3.3.4.4 VALSE
Vision And Language Structured Evaluation (VALSE) (Parcalabescu et al.,
2022) builds on the same idea. This benchmark aims to gauge the sensitivity
of pre-trained V&L models to foiled instances. They coverd a wide spectrum
of basic linguistic phenomena affecting the linguistic and visual modalities:
existence, plurality, counting, spatial relations, actions, and entity coreference.
To generate the foils they first use strong language models to propose foil and
second they use natural language inference to filter out captions that still can
describe the image. To do this in an automatic fashion they use the image
as an premise and the caption its entailed hypothesis. Additionally they use
the captian as an premise and the foil as the hypothesis. If an NLI model
predicts the foil to be neutral or a contradiction with respect to the caption,
they see this as an indicator for a good foil. At last the used human annotators
to validate all generated testing data. Mainly the MS-COCO dataset is used.
VALSE is as a task-independent, zero-shot benchmark to assess the extent to
which models learn to ground specific linguistic phenomena as a consequence
of their pretraining.
2.3.3.5 Other Benchmarks
As we don’t live in a world with unlimited resources, it’s also important to
keep track of how much energy is consumed to train the models and how
big the carbon footprint is. Strubell et al. (2019b) investigated some NLP
models and benchmarked model training and development costs in terms of
dollars and estimated CO2 emissions. They came to the result that training a
single BERT base model without hyperparameter tuning on GPUs requires
the same energy as a trans-American flight. On average a human is responsible
for 5t CO2 per year and Strubell et al. (2019b) estimated that the training
procedure of a big Transformer with neural architecture search emitted 284t of
CO2. Works (Lottick et al., 2019, Henderson et al. (2020)) have released online
tools to benchmark their energy usage and initiatives such as the SustainNLP
workshop have since taken up the goal of prioritizing computationally efficient
hardware and algorithms. These findings are just some points one should keep
in mind.
In the following chapters we will see how the multimodal architectures use
these datasets and also how they perform on the given benchmarks.
3
Multimodal architectures
Authors: Luyang Chu, Karol Urbanczyk, Giacomo Loss, Max Schneider, Steffen
Jauch-Walser
Supervisor: Christian Heumann
Multimodal learning refers to the process of learning representations from
different types of input modalities, such as image data, text or speech. Due to
methodological breakthroughs in the fields of Natural Language Processing
(NLP) as well as Computer Vision (CV) in recent years, multimodal models
have gained increasing attention as they are able to strengthen predictions
and better emulate the way humans learn. This chapter focuses on discussing
images and text as input data. The remainder of the chapter is structured as
follows:
The first part “Image2Text” discusses how transformer-based architectures
improve meaningful captioning for complex images using a new large scale,
richly annotated dataset COCO (Lin et al., 2014c; Cornia et al., 2020). While
looking at a photograph and describing it or parsing a complex scene and
describing its context is not a difficult task for humans, it appears to be much
more complex and challenging for computers. We start with focusing on images
as input modalities. In 2014 Microsoft COCO was developed with a primary goal
of advancing the state-of-the-art (SOTA) in object recognition by diving deeper
into a broader question of scene understanding (Lin et al., 2014c). “COCO” in
this case is the acronym for Common Objects in Context. It addresses three
core problems in scene understanding: object detection (non-iconic views),
segmentation, and captioning. While for tasks like machine translation and
language understanding in NLP, transformer-based architecture are already
widely used, the potential for applications in the multi-modal context has not
been fully covered yet. With the help of the MS COCO dataset, the transformerbased architecture “Meshed-Memory Transformer for Image Captioning” (M2
)
will be introduced, which was able to improve both image encoding and the
language generation steps (Cornia et al., 2020). The performance of M2 and
other different fully-attentive models will be compared on the MS COCO
dataset.
Next, in Text2Image, the idea of incorporating textual input in order to generate
visual representations is described. Current advancements in this field have been
made possible largely due to recent breakthroughs in NLP, which first allowed
83
84 3 Multimodal architectures
for learning contextual representations of text. Transformer-like architectures
are being used to encode the input into embedding vectors, which are later
helpful in guiding the process of image generation. The chapter discusses the
development of the field in chronological order, looking into details of the most
recent milestones. Concepts such as generative adversarial networks (GAN),
variational auto-encoders (VAE), VAE with vector quantization (VQ-VAE),
diffusion, and autoregressive models are covered to provide the reader with a
better understanding of the roots of the current research and where it might be
heading. Some of the most outstanding outputs generated by state-of-the-art
works are also presented in the chapter.
The third part, “Images supporting Language Models”, deals with the integration of visual elements in pure textual language models. Distributional
semantic models such as Word2Vec and BERT assume that the meaning of
a given word or sentence can be understood by looking at how (in which
context) and when the word or the sentence appear in the text corpus, namely
from its “distribution” within the text. But this assumption has been historically questioned, because words and sentences must be grounded in other
perceptual dimensions in order to understand their meaning (see for example
the “symbol grounding problem”; Harnad, 1990). For these reasons, a broad
range of models has been developed with the aim to improve pure language
models, leveraging the addition of other perceptual dimensions, such as the
visual one. This subchapter focuses in particular on the integration of visual
elements (here: images) to support pure language models for various tasks
at the word-/token-level as well as on the sentence-level. The starting point
in this case is always a language model, into which visual representations
(extracted often with the help of large pools of images rom data sets like MS
COCO, see chapter “Img2Text” for further references) are to be “integrated”.
But how? There has been proposed a wide range of solutions: On one side
of the spectrum, textual elements and visual ones are learned separately and
then “combined” afterwards, whereas on the other side, the learning of textual
and visual features takes place simultaneously/jointly.
For example, Silberer and Lapata (2014) implement a model where a one-toone correspondence between textual and visual space is assumed. Text and
visual representations are passed to two separate unimodal encoders and both
outputs are then fed to a bimodal autoencoder. On the other side, Bordes
et al. (2020) propose a “text objective function” whose parameters are shared
with an additional “grounded objective function”. The training of the latter
takes place in what the authors called a “grounded space”, which allows to
avoid the one-to-one correspondence between textual and visual space. These
are just introductory examples and between these two approaches there are
many shades of gray (probably even more than fifty ..). These models exhibit
in many instances better performance than pure language models, but they
still struggle on some aspects, for example when they deal with abstract words
and sentences.
3.0 85
FIGURE 3.1: Left: Silberer and Lapata (2014) stack autoencoders to learn
higher-level embeddings from textual and visual modalities, encoded as vectors
of attributes. Right: Bordes et al. (2020) fuse textual and visual information in
an intermediate space denoted as “grounded space”; the “grounding objective
function” is not applied directly on sentence embeddings but trained on this
intermediate space, on which sentence embeddings are projected.
Afterwards, in the subchapter on “Text supporting Image Models”, approaches
where natural language is used as additional supervision for CV models are
described. Intuitively these models should be more powerful compared to
models supervised solely by manually labeled data, simply because there is
much more signal available in the training data.
One prominent example for this is the CLIP model (Radford et al., 2021a)
with its new dataset WIT (WebImageText) comprising 400 million text-image
pairs scraped from the internet. Similar to “Text2Image” the recent success
stories in NLP have inspired most of the new approaches in this field. Most
importantly pre-training methods, which directly learn from raw text (e.g. GPTn, Generative Pre-trained Transformer; Brown et al., 2020). So, the acronym
CLIP stands for _C_ontrastive _L_anguage-_I_mage _P_re-training here.
A transformer-like architecture is used for jointly pre-training a text encoder
and an image encoder. For this, the contrastive goal to correctly predict
which natural language text pertains to which image inside a certain batch, is
employed. Training this way turned out to be more efficient than to generate
captions for images. This leads to a flexible model, which at test time uses
the Learned text encoder as a “zero-shot” classifier on embeddings of the
target dataset’s classes. The model, for example, can perform optical character
recognition, geo-location detection and action-recognition. Performance-wise
CLIP can be competitive with task-specific supervised models, while never
seeing an instance of the specific dataset before. This suggests an important
step towards closing the “robustness gap”, where machine learning models fail
to meet the expectations set by their previous performance – especially on
ImageNet test-sets – on new datasets.
Finally, the subchapter “Models for both modalities” discusses how text and
image inputs can be incorporated into a single unifying framework in order to
86 3 Multimodal architectures
get closer to a general self-supervised learning framework. There are two key
advantages that make such an architecture particularly interesting. Similar to
models mentioned in previous parts, devoid of human labelling, self-supervised
models don’t suffer from the same capacity constraints as regular supervised
learning models. On top of that, while there have been notable advances in
dealing with different modalities using single modality models, it is often unclear to which extend a model structure generalizes across different modalities.
Rather than potentially learning modality-specific biases, a general multipurpose framework can help increase robustness while also simplifying the learner
portfolio. In order to investigate different challenges and trends in vision-andlanguage modelling, this section takes a closer look at three different models,
namely data2vec (Baevski et al. (2022)), VilBert (Lu et al. (2019b)) and
Flamingo (Alayrac et al. (2022)) Data2vec is a new multimodal self-supervised
learning model which uses a single framework to process either speech, natural
language or visual information. This is in contrast to earlier models which
used different algorithms for different modalities. The core idea of data2vec,
developed by MetaAI, is to predict latent representations of the full input data
based on a masked view of the input in a self-distillation setup using a standard
transformer architecture. (Baevski et al. (2022)) As a result, the main improvement is in the framework itself, not the underlying architectures themselves.
For example, the transformer architecture being used follows Vaswani et al.
(2017b). Through their parallelizability, transformers have several advantages
over RNNs/CNNs particularly when large amounts of data are being used,
making them the de-facto standard approach in vision-language modelling.
(Dosovitskiy et al. (2020a)) VilBert is an earlier model that in contrast to
data2vec can handle cross-modality tasks. Finally, Flamingo is a modern few
shot learning model which features 80B parameters - significantly more than
the other two models. Through a large language model incorporated in its
architecture, it has great text generating capabilities to tackle open-ended
tasks. It also poses the question how to efficiently train increasingly large
models and shows the effectiveness of using perceiver architectures (Jaegle
et al. (2021a)) to encode inputs from different modalities as well as how to
leverage communication between pretrained and frozen models.
3.1 Image2Text
Author: Luyang Chu
Supervisor: Christian Heumann
Image captioning refers to the task of producing descriptive text for given
images. It has stimulated interest in both natural language processing and
computer vision research in recent years. Image captioning is a key task that
3.1 Image2Text 87
requires a semantic comprehension of images as well as the capacity to generate
accurate and precise description sentences.
3.1.1 Microsoft COCO: Common Objects in Context
The uderstanding of visual scenes plays an important role in computer vision
(CV) research. It includes many tasks, such as image classification, object
detection, object localization and semantic scene labeling. Through the CV
research history, high-quality image datasets have played a critical role. They
are not only essential for training and evaluating new algorithms, but also lead
the research to new challenging directions (Lin et al., 2014c). In the early years,
researchers developed Datasets (Deng et al., 2009),(Xiao et al., 2010),(Everingham et al., 2010) which enabled the direct comparison of hundreds of image
recognition algorithms, which led to an early evolution in object recognition. In
the more recent past, ImageNet (Deng et al., 2009), which contains millions of
images, has enabled breakthroughs in both object classification and detection
research using new deep learning algorithms.
With the goal of advancing the state-of-the-art in object recognition, especially
scene understanding, a new large scale data called “Microsoft Common Objects
in Context” (MS COCO) was published in 2014. MS COCO focuses on three
core problems in scene understanding: detecting non-iconic views, detecting the
semantic relationships between objects and determining the precise localization
of objects (Lin et al., 2014c).
The MS COCO data set contains 91 common object categories with a total
of 328,000 images as well as 2,500,000 instance labels. The authors claim,
that all of these images could be recognized by a 4 year old child. 82 of the
categories include more than 5000 labeled instances. These labeled instances
wmay support the detection of relationships between objects in MS COCO. In
order to provide precise localization of object instances, only “Thing” categories
like e.g. car, table, or dog were included. Objects which do not have clear
boundaries like e.g. sky, sea, or grass, were not included. In current object
recognition research, algorithms perform well on images with iconic views.
Images with iconic view are defined as containing the one single object category
of interest in the center of the image. To accomplish the goal of detecting the
contextual relationships between objects, more complex images with multiple
objects or natural images, coming from our daily life, are also gathered for the
data set.
In addition to MS COCO, researchers have been working on the development of
new large databases. In recent years many new large databases like ImageNet,
PASCAL VOC (Everingham et al., 2010) and SUN (Xiao et al., 2010) have
been developed in the field of computer vision. Each of this dataset has its on
specific focus.
88 3 Multimodal architectures
Datasets for object recognition can be roughly split into three groups: object
classification, object detection and semantic scene labeling.
Object classification requires binary labels to indicate whether objects are
present in an image, ImageNet (Deng et al., 2009) is clearly distinguishable
from other datasets in terms of the data set size. ImageNet contains 22k
categories with 500-1000 images each.In comparison to other data sets, the
ImageNet data set contains thus over 14 million labeled images with both
entity-level and fine-grained categories by using the WordNet hierarchy and
has enabled significant advances in image classification.
Detecting an object includes two steps: first is to ensure that an object from a
specified class is present, the second step is to localize the object in the image
with a given bounding box. This can be implemented to solve tasks like face
detection or pedestrians detection. The PASCAL VOC (Everingham et al.,
2010) data set can be used to help with the detection of basic object categories.
With 20 object categories and over 11,000 images, PASCAL VOC contains
over 27,000 labeled object instances by additionally using bounding boxes.
Almost 7,000 object instances from them come with detailed segmentations
(Lin et al., 2014c).
Labeling semantic objects in a scene requires that each pixel of an image is
labeled with respect to belonging to a category, such as sky, chair, etc., but
individual instances of objects do not need to be segmented (Lin et al., 2014c).
Some objects like sky, grass, street can also be defined and labeled in this way.
The SUN data set (Xiao et al., 2010) combines many of the properties of both
object detection and semantic scene labeling data sets for the task of scene
understanding, it contains 908 scene categories from the WordNet dictionary
(Fellbaum, 2000) with segmented objects. The 3,819 object categories split
them to object detection datasets (person, chair) and to semantic scene labeling
(wall, sky, floor) (Lin et al., 2014c).
3.1.1.1 Image Collection and Annotation for MS COCO
MS COCO is a large-scale richly annotated data set, the progress of building
consisted of two phases: data collection and image annotation.
In order to select representative object categories for images in MS COCO,
researchers collected several categories from different existing data sets like
PASCAL VOC (Everingham et al., 2010) and other sources. All these object
categories could, according to the authors, be recognized by children between
4 to 8. The quality of the object categories was ensured by co-authors. Coauthors rated the categories on a scale from 1 to 5 depending on their common
occurrence, practical applicability and diversity from other categories (Lin
et al., 2014c). The final number of categories on their list was 91. All the
categories from PASCAL VOC are included in MS COCO.
With the help of representative object categories, the authors of MS COCO
3.1 Image2Text 89
wanted to collect a data set in which a majority of the included images are noniconic. All included images can be roughly divided into three types according
to Fig. 3.2: iconic-object images, iconic-scene images and non-iconic images
(Lin et al., 2014c).
FIGURE 3.2: Type of images in the data set (Lin et al., 2014c).
Images are collected through two strategies: firstly images from Flickr, a
platform for photos uploaded by amateur photographers, with their keywords
are collected. Secondly, researchers searched for pairwise combinations of object
categories like “dog + car” to gather more non-iconic images and images with
rich contextual relationships (Lin et al., 2014c).
Due to the scale of the dataset and the high cost of the annotation process,
the design of a high quality annotation pipeline with efficient cost depicted a
difficult task. The annotation pipeline in Fig. 3.3 for MS COCO was split into
three primary tasks: 1. category labeling, 2.instance spotting, and 3. instance
segmentation (Lin et al., 2014c).
FIGURE 3.3: Annotation pipeline for MS COCO (Lin et al., 2014c).
As we can see in the Fig 3.3, object categories in each image were determined
in the first step. Due to the large number of data sets and categories, they
used a hierarchical approach instead of doing binary classification for each
category. All the 91 categories were grouped into 11 super-categories. The
90 3 Multimodal architectures
annotator did then examine for each single instance whether it belongs to one
of the given super-categories. Workers only had to label one instance for each
of the super-categories with a category’s icon (Lin et al., 2014c). For each
image, eight workers were asked to label it. This hierarchical approach helped
to reduce the time for labeling. However, the first phase still took 20k worker
hours to be completed.
In the next step, all instances of the object categories in an image were labeled,
at most 10 instances of a given category per image were labeled by each worker.
In both the instance spotting and the instance segmentation steps, the location
of the instance found by a worker in the previous stage could be seen by the
current worker. Each image was labeled again by eight workers summing up
to a total of 10k worker hours.
In the final segmenting stage, each object instance was segmented, the segmentation for other instances and the specification of the object instance by a
worker in the previous stage were again shown to the worker. Segmenting 2.5
million object instances was an extremely time consuming task which required
over 22 worker hours per 1,000 segmentations. To minimize cost and improve
the quality of segmentation, all workers were required to complete a training
task for each object category. In order to ensure a better quality, an explicit
verification step on each segmented instance was performed as well.
3.1.1.2 Comparison with other data sets
In recent years, researchers have developed several pre-training data sets and
benchmarks which helped the developemnt of algorithms for CV. Each of these
data sets varies significantly in size, number of categories and types of images.
In the previos part, we also introduced the different research focus of some
data sets like e.g. ImageNet (Deng et al., 2009), PASCAL VOC (Everingham
et al., 2010) and SUN (Xiao et al., 2010). ImageNet, containing millions of
images, has enabled major breakthroughs in both object classification and
detection research using a new class of deep learning algorithms. It was created
with the intention to capture a large number of object categories, many of
which are fine-grained. SUN focuses on labeling scene types and the objects
that commonly occur in them. Finally, PASCAL VOC’s primary application is
in object detection in natural images. MS COCO is designed for the detection
and segmentation of objects occurring in their natural context (Lin et al.,
2014c).
With the help of Fig. 3.4, one can compare MS COCO to ImageNet, PASCAL
VOC and SUN with respect to different aspects (Lin et al., 2014c).
The number of instances per category for all 91 categories in MS COCO and
PASCAL VOC is shown in subfigure 3.4 (a). Compared to PASCAL VOC,
MS COCO has both more categories and (on average) more instances per
category. The number of object categories and the number of instances per
3.1 Image2Text 91
FIGURE 3.4: Comparison MS COCO with PASCAL VOC, SUN and ImageNet (Lin et al., 2014c).
category for all the datasets is shown in subfigure 3.4 (d). MS COCO has
fewer categories than ImageNet and SUN, but it has the highest average
number of instances per category among all the data sets, which from the
perspective of authors might be useful for learning complex models capable
of precise localization (Lin et al., 2014c). Subfigures 3.4 (b) and (c) show the
number of annotated categories and annotated instances per image for MS
COCO, ImageNet, PASCAL VOC and SUN (average number of categories
and instances are shown in parentheses). On average MS COCO contains 3.5
categories and 7.7 instances per image. ImageNet and PASCAL VOC both
have on average less than 2 categories and 3 instances per image. The SUN
data set has the most contextual information, on average 9.8 categories and 17
instances per image. Subfigure 3.4 (e) depicts the distribution of instance sizes
for the MS COCO, ImageNet Detection, PASCAL VOC and SUN data set.
3.1.1.3 Discussion
MS COCO is a large scale data set for detecting and segmenting objects
found in everyday life, with the aim of improving the state-of-the-art in object
92 3 Multimodal architectures
recognition and scene understanding. It focuses on non-iconic images of objects
in natural environments and contains rich contextual information with many
objects present per image. MS COCO is one of the typically used vision
data sets, which are labor intensive and costly to create. With the vast cost
and over 70,000 worker hours, 2.5 Mio instances were annotated to drive the
advancement of object detection and segmentation algorithms. MS COCO is
still a good benchmark for the field of CV (Lin et al., 2014c). The MS COCO
Team also shows directions for future. For example “stuff” label like “sky”,
“grass”, and “street”, etc, may also be included in the dataset since “stuff”
categories provide significant contextual information for the object detection.
3.1.2 Models for Image captioning
The image captioning task is generally to describe the visual content of an
image in natural language, so it requires an algorithm to understand and
model the relationships between visual and textual elements, and to generate a
sequence of output words (Cornia et al., 2020). In the last few years, collections
of methods have been proposed for image captioning. Earlier approaches
were based on generations of simple templates, which contained the output
produced from the object detector or attribute predictor (Socher and Fei-fei,
2010), (Yao et al., 2010). With the sequential nature of language, most research
on image captioning has focused on deep learning techniques, using especially
Recurrent Neural Network models (RNNs) (Vinyals et al., 2015), (Karpathy
and Fei-Fei, 2014) or one of their special variants (e.g. LSTMs). Mostly,
RNNs are used for sequence generation as languages models, while visual
information is encoded in the output of a CNN. With the aim of modelling
the relationships between image regions and words, graph convolution neural
networks in the image encoding phase (Yao et al., 2018a) or single-layer
attention mechanisms (Xu et al., 2015) on the image encoding side have
been proposed to incorporate more semantic and spatial relationships between
objects. RNN-based models are widely adopted, however, the model has its
limitation on representation power and due to its sequential nature (Cornia
et al., 2020). Recently, new fully-attentive models, in which the use of selfattention has replaced the recurrence, have been proposed. New approaches
apply the Transformer architecture (Vaswani et al., 2017d) and BERT (Devlin
et al., 2019) models to solve image captioning tasks. The transformer consists of
an encoder with a stack of self-attention and feed-forward layers, and a decoder
which uses (masked) self-attention on words and cross-attention over the output
of the last encoder layer (Cornia et al., 2020). In some other transformer-based
approaches, a transformer-like encoder was paired with an LSTM decoder,
while the aforementioned approaches have exploited the original transformer
architecture. Others (Herdade et al., 2019) proposed a transformer architecture
for image captioning with the focus on geometric relations between input
objects at the same time. Specifically, additional geometric weights between
object pairs, which is used to scale attention weights, are computed. Similarly,
3.1 Image2Text 93
an extension of the attention operator, in which the final attended information
is weighted by a gate guided by the context, was introduced at a similar time
(Huang et al., 2019).
3.1.3 Meshed-Memory Transformer for Image Captioning
(M2
)
Transformer-based architectures have been widely implemented in sequence
modeling tasks like machine translation and language understanding. However,
their applicability for multi-modal tasks like image captioning has still been
largely under-explored (Cornia et al., 2020).
FIGURE 3.5: M2 Transformer (Cornia et al., 2020).
A novel fully-attentive approach called Meshed-Memory Transformer for Image
Captioning (M2
) was proposed in 2020 (Cornia et al., 2020) with the aim of
improving the design of both the image encoder and the language decoder.
Compared to all previous image captioning models, M2
(see Fig. 3.5 has
two new novelties: The encoder encodes a multi-level representation of the
relationships between image regions with respect to low-level and high-level
relations, and a-priori knowledge can be learned and modeled by using persistent
94 3 Multimodal architectures
memory vectors. The multi-layer architecture exploits both low- and high-level
visual relationships through a learned gating mechanism, which computes the
weight at each level, therefore, a mesh-like connectivity between encoder and
decoder layers is created for the sentence generation process (Cornia et al.,
2020).
3.1.3.1 M2 Transformer Architecture
FIGURE 3.6: M2 Transformer Architecture (Cornia et al., 2020).
Fig. 3.6 shows the detailed architecture of M2 Transformer. It can be divided
into the encoder (left) module and the decoder (right) module, both modules
with multiple layers. Given the input image region X, the image is passed
through the attention and feed forward layers. The relationship between image
regions with a-priori knowledge will be encoded in each encoding layer, the
output of each encoding layers will be read by decoding layers to generate the
caption for image word by word (Cornia et al., 2020).
All interactions between word and image-level features of the input image
X are modeled by using scaled dot-product attention. Attention operates on
vectors of queries q, keys k and values n, and takes a weighted sum of the value
vectors according to a similarity distribution between query and key vectors.
Attention can be defined as follows (Cornia et al., 2020):
Attention(Q, K, V ) = softmax(QKT
√
d
)V (3.1)
where Q is a matrix of nq query vectors, K and V both contain nk keys and
values, all the vectors has the same dimensionality, and d is a scaling factor.
3.1.3.1.1 Memory-Augmented Encoder
For the given image region X, attention can be used to obtain a permutation
invariant encoding of X through the self-attention operations, the operator
from the Transformer can be defined as follows (Cornia et al., 2020):
3.1 Image2Text 95
S(X) = Attention(WqX, WkX, WvX) (3.2)
In this case, queries, keys, and values are linear projections of the input features,
and Wq, Wk, Wv are their learnable weights, they depend solely on the pairwise
similarities between linear projections of the input set X. The self-attention
operator encodes the pairwise relationships inside the input. But self-attention
also has its limitation: a prior knowledge on relationships between image regions
can not be modelled. To overcome the limitation, the authors introduce a
Memory-Augmented Attention operator by extending the keys and values
with additional prior information, which does not depend on image region
X. The additional keys and values are initialized as plain learnable vectors
which can be directly updated via SGD. The operator can be defined as follows
(Cornia et al., 2020):
Mmem(X) = Attention(WqX, K, V )
K = [WkX, Mk]
V = [WvX, Mv] (3.3)
Mk and Mv are learnable matrices, with nm rows, [·,·] indicates concatenation.
The additional keys and value could help to retrieve a priori knowledge from
input while keeping the quries unchanged (Cornia et al., 2020).
For the Encoding Layer, a memory-augmented operator d is injected into a
transformer-like layer, the output is fed into a position-wise feed-forward layer
(Cornia et al., 2020):
F(X)i = Uσ(V Xi + b) + c; (3.4)
Xi
indicates the i-th vector of the input set, and F(X)i the i-th vector of the
output. Also, σ(ů) is the ReLU activation function, V and U are learnable
weight matrices, b and c are bias terms (Cornia et al., 2020).
Each component will be complemented by a residual connection and the layer
norm operation. The complete definition of an encoding layer can be finally
written as (Cornia et al., 2020):
Z = AddNorm(Mmem(X))
X˜ = AddNorm(F(Z)) (3.5)
Finally the Full Encoder has multiple encoder layers in a sequential fashion,
therefore the i-th layer uses the output set computed by layer i − 1, higher
encoding layers can exploit and refine relationships identified by previous layers,
n encoding layers will produce the output X˜ = (X˜ 1
. . . X˜ n) (Cornia et al.,
2020).
96 3 Multimodal architectures
3.1.3.1.2 Meshed Decoder
The decoder depends on both previously generated words and image region
encodings. Meshed Cross-Attention can take advantage of all the encoder
layers to generate captions for the image. On the right side of the Fig. 3.6 the
structure of the meshed decoder is shown. The input sequence vector Y and
the outputs from all encoder layers X˜ are connected by the meshed attention
operator gated through cross-attention. The meshed attention operator can is
formally defined as (Cornia et al., 2020):
Mmesh(X, Y ˜ ) = X
N
i=1
αiC(X˜i
, Y ) (3.6)
C(ů, ů) stands for the encoder-decoder cross-attention, it is defined with queries
from decoder, while the keys and values come from the encoder (Cornia et al.,
2020).
C(X˜i
, Y ) = Attention(WqY, WkX˜i
, WvX˜i) (3.7)
αi
is a matrix of weights of the same size as the cross-attention results,
αi models both single contribution of each encoder layer and the relative
importance between different layers (Cornia et al., 2020).
αi = σ(Wi
[Y, C(X˜i
, Y )] + bi) (3.8)
The [·,·] indicates concatenation and σ(ů) is the sigmoid activation function
here, Wi
is a weight matrix, and bi
is a learnable bias vector (Cornia et al.,
2020).
In decoder layers the prediction of a word should only depend on the previously generated word, so the decoder layer comprises a masked self-attention
operation, which means that the operator can only make connections between
queries derived from the t-th element of its input sequence Y with keys and
values from left sub-sequence, i.e. Y≤t.
Simlilar as the encoder layers, the decoder layers also contain a position-wise
feed-forward layer, so the decoder layer can be finally defined as (Cornia et al.,
2020):
Z = AddNorm(Mmesh(X, AddNorm(Smask(Y )))
Y˜ = AddNorm(F(Z)), (3.9)
where Smask indicates a masked self-attention over time (Cornia et al., 2020).
The full decoder with multiple decoder layers takes the input word vectors as
well as the t-th element (and all elements prior to it) of its output sequence
3.1 Image2Text 97
to make the prediction for the word at t + 1, conditioned on Y≤t. Finally the
decoder takes a linear projection and a softmax operation, which can be seen
as a probability distribution over all words in the vocabulary (Cornia et al.,
2020).
3.1.3.1.3 Comparison with other models on the MS COCO data sets
The M2 Transformer was evaluated on MS COCO, which is still one of the
most commonly used test data set for image captioning. Instead of using the
original MS COCO dat set, Cornia et al. (2020) follow the split of MS COCO
provided by Karpathy and Fei-Fei (2014). Karpathy uses 5000 images for
validation, 5000 images for testing and the rest for training.
For model evaluation and comparison, standard metrics for evaluating generated sequences, like BLEU (Papineni et al., 2002), METEOR (Banerjee and
Lavie, 2005), ROUGE (Lin, 2004), CIDEr (Vedantam et al., 2015), and SPICE
(Anderson et al., 2016), which have been introduced in the second chapter, are
used.
FIGURE 3.7: Comparison of M2 with Transformer-based alternatives (Cornia et al., 2020)
The transformer architecture in its original configuration with six layers has
been applied for captioning, researchers speculated that specific architectures
might be required for captioning, so variations of the original transformer
are compared with M2 Transformer. Other variations are a transformer with
three layers and the “Attention on Attention” (AoA) approach (Huang et al.,
2019) to the attentive layers, both in the encoder and in the decoder (Cornia
et al., 2020). The second part intends to evaluate the importance of the
meshed connections between encoder and decoder layers. M2 Transformer
(1 to 1) is a reduced version of the original M2 Transformer, in which one
encoder layer is connected to only corresponding decoder layer instead of being
98 3 Multimodal architectures
connected to all the decoder layers. As one can see from the Fig. 3.7, the
original Transformer has a 121.8 CIDEr score, which is lower than the reduced
version of M2 Transformer, showing an improvement to 129.2 CIDEr. With
respect to meshed connectivity, which helps to exploit relationships encoded at
all layers and weights them with a sigmoid gating, one can observe a further
improvement in CIDEr from 129.2 to 131.2. Also the role of memory vectors
and the softmax gating schema for M2 Transformer are also included in the
table. Eliminating the memory vector leads to a reduction of the performance
by nearly 1 point in CIDEr in both the reduced M2 Transformer and the
original M2 Transformer (Cornia et al., 2020).
FIGURE 3.8: Comparison with the state-of-the-art on the “Karpathy” test
split, in single-model setting (Cornia et al., 2020).
Fig 3.8 compares the performance of M2 Transformer with several recently
proposed models for image captioning. SCST (Rennie et al., 2017) and UpDown (Anderson et al., 2018), use attention over the grid of features and
attention over regions. RFNet (?) uses a recurrent fusion network to merge
different CNN features; GCN-LSTM (Yao et al., 2018b) uses a Graph CNN to
exploit pairwise relationships between image regions; SGAE (Yang et al., 2019)
uses scene graphs instead ofauto-encoding. The original AoA-Net (Huang et al.,
2019) approach uses attention on attention for encoding image regions and an
LSTM language model. Finally, the ORT (Herdade et al., 2019) uses a plain
transformer and weights attention scores in the region encoder with pairwise
distances between detections (Cornia et al., 2020).
In Fig. 3.8, the M2 Transformer exceeds all other models on BLEU-4, METEOR, and CIDEr. The performance of the M2 Transformer was very close
and competitive with SGAE on BLEU-1 and with ORT with respect to SPICE.
3.2 Image2Text 99
FIGURE 3.9: Examples of captions generated by M2 Transformer and the
original Transformer model, as well as the corresponding ground-truths (Cornia
et al., 2020).
Fig. 3.9 shows some examples of captions generated by M2 Transformer and
the original transformer model, as well as the corresponding ground-truths.
According to the selected examples of captions, M2 Transformer shows the
ability to generate more accurate descriptions of the images, and the approach
could detect the more detailed relationships between image regions (Cornia
et al., 2020).
The M2 Transformer is a new transformer-based architecture for image captioning. It improves the image encoding by learning a multi-level representation
of the relationships between image regions while exploiting a priori knowledge
from each encoder layer, and uses a mesh-like connectivity at decoding stage
to exploit low- and high-level features at the language generation steps. The
results of model evaluation with MS COCO shows that the performance of
the M2 Transformer approach surpasses most of the recent approaches and
achieves a new state of the art on MS COCO (Cornia et al., 2020).
100 3 Multimodal architectures
3.2 Text2Image
Author: Karol Urbańczyk
Supervisor: Jann Goschenhofer
Have you ever wondered what a painting artist could paint for you if you
ordered a high-quality oil painting of a psychedelic hamster dragon? Probably
not. Nevertheless, one of the answers could be:
FIGURE 3.10: Hamster dragon
The catch is that there is no human artist. The above picture comes from a
3.5-billion parameter model called GLIDE by OpenAI (Nichol et al., 2021b).
Every single value of every pixel was generated from a distribution that the
model had to learn in the first place. Before generating the image, GLIDE
abstracted the concepts of ‘hamster’ and ‘dragon’ from looking at millions of
training images. Only then, it was able to create and combine them successfully
into a meaningful visual representation. Welcome to the world of current textto-image modelling!
The cross-modal field of text-to-image models has developed significantly
over recent years. What was considered unimaginable only a few years ago,
today constitutes a new benchmark for researchers. New breakthroughs are
being published every couple of months. Following these, possible business use
cases are emerging, which attracts investment from the greatest players in AI
research. However, a further trend of closed-source models is continuing and
the text-to-image field is probably one the most obvious ones where it can be
noticed. We might need to get used to the fact that the greatest capabilities
will soon be monopolized by few companies.
At the same time, the general public is becoming aware of the field itself
and the disruption potential it brings. Crucial questions are already emerging.
3.2 Text2Image 101
What constitutes art? What does the concept of being an author mean? The
result of a generative model is in a sense a combination, or variation, of the
abstracts it has seen in the past. But the same stands for a human author.
Therefore, is a discussion about the prejudices and biases needed? Answers to
all of these will require refinement through an extensive discussion. The last
section of this chapter will try to highlight the most important factors that
will need to be considered.
However, the primary intention of this chapter is to present the reader with
a perspective on how the field was developing chronologically. Starting with
the introduction of GANs, through the first cross-domain models, and ending
with state-of-the-art achievements (as of September 2022), it will also try to
grasp the most important concepts without being afraid of making technical
deep dives.
The author is aware that since the rapid development pace makes it nearly
impossible for this section to stay up-to-date, it might very soon not be fully
covering the field. However, it must be stressed that the cutting-edge capabilities
of the recent models tend to come from the scale and software engineering
tricks. Therefore, focusing on the core concepts should hopefully gives this
chapter a universal character, at least for some time. This design choice also
explains why many important works did not make it to this publication. Just
to name a few of them as honorable mentions: GAWWN (Reed et al., 2016a),
MirrorGAN (Qiao et al., 2019), or most recent ones: LAFITE (Zhou et al.,
2021), Make-a-Scene (Gafni et al., 2022) or CogView (Ding et al., 2021). In
one way or another, all of them pushed the research frontier one step further.
Therefore, it needs to be clearly stated - the final selection of this chapter’s
content is a purely subjective decision of the author.
3.2.1 Seeking objectivity
Before diving into particular models, we introduce objective evaluation procedures that help assess the performance of consecutive works in comparison to
their predecessors. Unfortunately, objectivity in comparing generative models
is very hard to capture since there is no straight way to draw deterministic
conclusions about the model’s performance (Theis et al., 2015). However,
multiple quantitative and qualitative techniques have been developed to make
up for it. Unfortunately, there is no general consensus as to which measures
should be used. An extensive comparison has been performed by Borji (2018).
A few of the most widely used ones in current research are presented below.
Inception Score (IS)
Introduced by Salimans et al. (2016), Inception Score (IS) uses the Inception
Net (Szegedy et al., 2015) trained on ImageNet data to classify the fake images
generated by the assessed model. Then, it measures the average KL diver-
102 3 Multimodal architectures
gence between the marginal label distribution p(y) and the label distribution
conditioned on the generated samples p(y|x).
exp(E
x
[KL(p(y|x)||p(y))])
p(y) is desired to have high diversity (entropy), in other words: images from the
generative model should represent a wide variety of classes. On the other hand,
p(y|x) is desired to have low diversity, meaning that images should represent
meaningful concepts. If a range of cat images is being generated, they all
should be confidently classified by Inception Net as cats. The intention behind
IS is that a generative model with a higher distance (KL divergence in this
case) between these distributions should have a better score. IS is considered
a metric that correlates well with human judgment, hence its popularity.
Fréchet Inception Distance (FID)
A metric that is generally considered to improve upon Inception Score is the
Fréchet Inception Distance (FID). Heusel et al. (2017) argue that the main
drawback of IS is that it is not considering the real data at all. Therefore,
FID again uses Inception Net, however this time it embeds the images (both
fake and real samples) into feature space, stopping at a specific layer. In other
words, some of the ultimate layers of the network are being discarded. Feature
vectors are then assumed to follow a Gaussian distribution and the Fréchet
distance is calculated between real and generated data distributions:
d
2
((m, C),(mw, Cw)) = ||m − mw||2
2 + T r(C + Cw − 2(CCw)
1/2
)
where (m, C) and (mw, Cw) represent mean and covariance of generated and
real data Gaussians respectively. Obviously, low FID levels are desired.
FID is considered to be consistent with human judgement and sensitive to
image distortions, which are both desired properties. Figure 3.11 shows how
FID increases (worsens) for different types of noise being added to images.
Precision / Recall
Precision and recall are one of the most widely used metrics in many Machine
Learning problem formulations. However, their classic definition cannot be
applied to generative models due to the lack of objective labels. Sajjadi et al.
(2018) came up with a novel definition of these metrics calculated directly from
distributions, which was further improved by Kynkäänniemi et al. (2019). The
argument behind the need for such an approach is that metrics such as IS or
FID provide only a one-dimensional view of the model’s performance, ignoring
the trade-off between precision and recall. A decent FID result might very well
mean high recall (large variation, i.e. wide range of data represented by the
model), high precision (realistic images), or anything in between.
Let Pr denote the probability distribution of the real data, and Pg be the
3.2 Text2Image 103
FIGURE 3.11: FID is evaluated for different noise types. From upper left to
lower right: Gaussian noise, Gaussian blur, implanted black rectangles, swirled
images, salt and pepper, CelebA dataset contaminated by ImageNet images.
Figure from Heusel et al. (2017).
distribution of the generated data. In short, recall measures to which extend
Pr can be generated from Pg, while precision is trying to grasp how many
generated images fall within Pr.
FIGURE 3.12: Definition of precision and recall for distributions. Figure
from Kynkäänniemi et al. (2019).
See Kynkäänniemi et al. (2019) for a more thorough explanation.
CLIP score
CLIP is a model from OpenAI [CLIP2021] which is explained in detail in the
chapter about text-supporting computer vision models. In principle, CLIP is
capable of assessing the semantic similarity between the text caption and the
image. Following this rationale, the CLIP score can be used as metric and is
defined as:
E[s(f(image) ∗ g(caption))]
104 3 Multimodal architectures
where the expectation is taken over the batch of generated images and s is the
CLIP logit scale (Nichol et al., 2021b).
Human evaluations
It is common that researchers report also qualitative measures. Many potential
applications of the models are focused on deceiving the human spectator,
which motivates reporting of metrics that are based on human evaluation. The
general concept of these evaluation is to test for:
• photorealism
• caption similarity (image-text alignment)
Usually, a set of images is presented to a human, whose task is to assess their
quality with respect to the two above-mentioned criteria.
3.2.2 Generative Adversarial Networks
The appearance of Generative Adversarial Networks (GAN) was a major
milestone in the development of generative models. Introduced by Goodfellow
et al. (2014c), the idea of GANs presented a novel architecture and training
regime, which corresponds to a minimax two-player game between a Generator
and a Discriminator (hence the word adversarial).
GANs can be considered as an initial enabler for the field of text-to-image
models and for a long time, GAN-like models were achieving state-of-the-art
results, hence the presentation of their core concepts in this chapter
3.2.2.1 Vanilla GAN for Image Generation
In a vanilla GAN, the Generator model (G) and Discriminator model (D)
are optimized together in a minimax game, where G aims at generating a
sample so convincing, that D will not be able to distinguish whether it comes
from a real or generated image distribution. On the other hand, D is being
trained to discriminate between the two. Originally, a multilayer perceptron
was proposed as a model architecture for both D and G, although in theory
any differentiable function could be used.
More formally, let pz denote the prior distribution defined on the input noise
vector z. Then, the generator G(z) represents a function that is mapping this
noisy random input to the generated image x. The discriminator D(x) outputs a
probability that x comes from the real data rather than generator’s distribution
pg. In this framework, D shall maximize the probability of guessing the correct
label of both real and fake data. G is trained to minimize log(1 − D(G(z))).
Now, such representation corresponds to the following value function (optimal
solution):
min
G
min
D
V (D, G) = E
x∼pdata(x)
[log(D(x))] + E
z∼pz(z)
[log(1 − D(G(z)))]
3.2 Text2Image 105
Figure 3.13 depicts this process in a visual way.
FIGURE 3.13: GAN framework as proposed in Goodfellow et al. (2014c).
Some of the generated samples that had been achieved with this architecture
already in 2014 can be seen in Figure 3.14.
FIGURE 3.14: Samples from generators trained on different datasets: a)
MNIST b) TFD, c) CIFAR-10 (MLP used for G and D) d) CIFAR-10 (CNN
used). Highlighted columns show the nearest real example of the neighbouring
sample. Figure from Goodfellow et al. (2014c).
3.2.2.2 Conditioning on Text
So far, only image generation has been covered, completely ignoring textual
input. Reed et al. (2016c) introduced an interesting concept of conditioning
DC-GAN (GAN with CNNs as Generator and Discriminator) on textual
embeddings. A separate model is being trained and used for encoding the text.
Then, result embeddings are concatenated with the noise vector and fed into
the Generator and the Discriminator takes embeddings as an input as well.
The resulting model is referred to as GAN-INT-CLS. Both abbreviations (INT
106 3 Multimodal architectures
and CLS) stand for specific training choices, which are going to be explained
later in the chapter. The overview of the proposed architecture can be seen in
Figure 3.15.
FIGURE 3.15: The proposed architecture of the convolutional GAN that is
conditioned on text. Text encoding ϕ(t) is fed into both the Generator and
the Discriminator. Before further convolutional processing, it is first projected
to lower dimensionality in fully-connected layers and concatenated with image
feature maps. Figure from Reed et al. (2016c).
Text embeddings
Since regular text embeddings are commonly trained in separation from visual
modality simply by looking at the textual context, they are not well suited for
capturing visual properties. This motivated Reed et al. (2016b) to come up with
structured joint embeddings of images and text descriptions. GAN-INT-CLS
implements it in a way described in Figure 3.16.
FIGURE 3.16: Figure from Reed et al. (2016c).
3.2 Text2Image 107
GoogLeNet is being used as an image encoder φ. For text encoding ϕ(t), authors
use a character-level CNN combined with RNN. Essentially, the objective of
the training is to minimize the distance between the encoded image and text
representations. The image encoder is then discarded and ϕ only is used as
depicted in Figure 3.15.
GAN-CLS
CLS stands for Conditional Latent Space, which essentially means the GAN
is conditioned on the embedded text. However, in order to fully grasp how
exactly the model is conditioned on the input, we need to go beyond architectural choices. It is also crucial to present a specific training regime that was
introduced for GAN-CLS and the motivation behind it.
One way to train the system is to view text-image pairs as joint observations
and train the discriminator to classify the entire pair as real or fake. However,
in such a case the discriminator does not have an understanding of whether
the image matches the meaning of the text. This is because the discriminator
does not distinguish between two types of error that exist, namely when the
image is unrealistic or when it is realistic but the text does not match.
A proposed solution to this problem is to present the discriminator with three
observations at a time, all of which are included later in the loss function.
These three are: {real image with right text}, {real image with wrong text},
{fake image with right text}. The intention is that the discriminator should
classify them as {true}, {false}, {false}, respectively.
GAN-INT
The motivation behind this concept comes from the fact that interpolating
between text embeddings tends to create observation pairs that are still close
to the real data manifold. Therefore, generating additional synthetic text
embeddings and using them instead of real captions in the training process
might help in the sense that it works as a form of data augmentation and helps
regularize the training process. Figure 3.17 might be helpful for developing the
intuition behind the interpolation process.
Results
The model achieves the best performance when both of the mentioned methods
are in use (GAN-INT-CLS). Models prove to successfully transfer style (pose
of the objects) and background from the training data when trained on CUB
(birds) and Oxford-102 (flowers) datasets. They also show interesting zero-shot
abilities, meaning they can generate observations from unseen test classes
(Figure 3.18). When trained on MS-COCO, GAN-CLS proves its potential to
generalize over many domains, although the results are not always coherent
(Figure 3.19).
108 3 Multimodal architectures
FIGURE 3.17: Interpolating between sentences. Figure from Reed et al.
(2016c).
FIGURE 3.18: Zero-shot generated birds using GAN, GAN-CLS, GAN-INT,
GAN-INT-CLS. Figure from Reed et al. (2016c).
3.2.2.3 Further GAN-like development
Generative Adversarial Networks were a leading approach for text-to-image
models for most of the field’s short history. In the following years after the
introduction of GAN-INT-CLS, new concepts were emerging, trying to push
the results further. Many of them had a GAN architecture as their core part.
In this section, a few such ideas are presented. The intention is to quickly
skim through the most important ones. A curious reader should follow the
corresponding papers.
StackGAN
3.2 Text2Image 109
FIGURE 3.19: Generated images using GAN-CLS on MS-COCO validation
set. Figure from Reed et al. (2016c).
Zhang et al. (2016a) introduced what the StackGAN. The main contribution of
the paper which also found its place in other researchers’ works, was the idea
to stack more than one generator-discriminator pair inside the architecture.
Stage-II (second pair) generator is supposed to improve the results from Stage-I,
taking into account only:
• text embedding (same as Stage-I)
• image generated in Stage-I
without a random vector. Deliberate omission of the random vector results
in the generator directly working on improving the results from Stage-I. The
purpose is also to increase resolution (here from 64x64 to 256x256). Authors
obtained great results already with two stages, however, in principle architecture
allows for stacking many of them.
FIGURE 3.20: (ref:stackgan)
AttnGAN
It is 2017 and many researchers believe attention is all they need (Vaswani
110 3 Multimodal architectures
et al., 2017e). Probably for the first time in text-to-image generation attention
mechanism was used by Xu et al. (2017). The authors combined the idea with
what StackGAN proposed and used three stages (generators G0, G1 and G2).
However, this time first layers of a particular generator are attending to word
feature vectors. This mechanism not only helps control how particular areas of
the image are being improved by consecutive generators but also allows for
visualizing attention maps.
FIGURE 3.21: Images generated by G0, G1, G2. Two bottom rows show 5
most attended words by G1 and G2 respectively. Figure from Xu et al. (2017).
DM-GAN
Another important milestone was DM-GAN (Dynamic Memory GAN) (Zhu
et al., 2019). At that time, models were primarily focusing on generating the
initial image and then refining it to a high-resolution one (as e.g. StackGAN
does). However, such models heavily depend on the quality of the first image
initialization. This problem was the main motivation for the authors to come
up with a mechanism to prevent it. DM-GAN proposes a dynamic memory
module, which has two main components. First, its memory writing gate helps
select the most important information from the text based on the initial image.
Second, a response gate merges the information from image features with the
memories. Both of these help refine the initial image much more effectively.
DF-GAN
3.2 Text2Image 111
Last but not least, DF-GAN (Deep Fusion GAN) (Tao et al., 2020) improves
the results by proposing three concepts. One-Stage Text-to-Image Backbone
focuses on providing an architecture that is capable of abandoning the idea of
multiple stacked generators and using a single one instead. It achieves that
by a smart combination of a couple of factors, i.a. hinge loss and the use of
residual blocks. Additionally, Matching-Aware Gradient Penalty helps achieve
high semantic consistency between text and image and regularizes the learning
process. Finally, One-Way Output helps the process converge more effectively.
3.2.3 Dall-E 1
OpenAI’s Dall-E undoubtedly took the text-to-image field to another level.
For the first time, a model showed great zero-shot capabilities, comparable to
previous domain-specific models. To achieve that, an unprecedented scale of
the dataset and training process was needed. 250 million text-image pairs were
collected for that purpose, which enabled training of a 12-billion parameter
version of the model. Unfortunately, Dall-E is not publicly available and follows
the most recent trend of closed-source models. Or, to put it more precisely, it
started this trend, and GLIDE, Dall-E 2, Imagen, Parti and others followed.
Nevertheless, Dall-E’s inner workings are described in Ramesh et al. (2021b)
and this section will try to explain its most important parts. However, before
that, it is crucial to understand one of the fundamental concepts that has been
around in the field of generative models for already quite some time - namely
Variational Autoencoders.
Variational Autoencoder (VAE)
The regular Autoencoder architecture aims at finding an identity function
that is capable of finding a meaningful representation of the data in lowerdimensional space and then reconstructing it. It is considered an unsupervised
learning method for dimensionality reduction, however, trained in a supervised
regime with the data itself being the label. The component performing the
reduction is called an encoder, while the part responsible for the reconstruction
is called a decoder. The idea behind Variational Autoencoder (Kingma and
Welling, 2013) is similar, however, instead of learning the mapping to a static
low-dimensional vector, the model learns its distribution. This design equips
the decoder part with desired generative capabilities, as sampling from the
latent low-dimensional space will result in varying data being generated. The
architecture is depicted in Figure 3.22.
qφ(z|x) denotes the encoder under the assumption that z comes from multivariate Gaussian. µ and σ are being learned. Reconstruction process is modelled
by conditional probability pθ(x|z), given samples latent vector z.
VQ-VAE / dVAE
The VQ-VAE (Vector Quantized VAE) (van den Oord et al., 2017) differs from
112 3 Multimodal architectures
FIGURE 3.22: Variational (probabilistic) Autoencoder architecture. Figure
from Weng (2018).
the regular VAE in the way it approaches encoding the latent space. Instead
of mapping data into a continuous distribution, the Vector Quantized version
does it in a discrete way. This is motivated by the fact that for many data
modalities it is more natural to represent them in a discrete way (e.g. speech,
human language, reasoning about objects in images, etc.). VQ-VAE achieves
that by using a separate codebook of vectors. The architecture is depicted in
Figure 3.23.
FIGURE 3.23: VQ-VAE architecture. Figure from van den Oord et al. (2017).
The idea is to map the output of the encoder to one of the vectors from the
K-dimensional codebook. This process is called quantization and essentially
means finding the vector that is the nearest neighbour to the encoder’s output
(in a sense of Euclidean distance). Since this moment, this newly found vector
from the codebook is going to be used instead. The codebook itself is also
subject to the learning process. One could argue that passing gradients during
the training through such a discrete system might be problematic. VQ-VAE
overcomes this problem by simply copying gradients from the decoder’s input
3.2 Text2Image 113
to the encoder’s output. A great explanation of the training process and further
mathematical details can be found in Weng (2018) and Snell (2021).
Dall-E, however, is using what is called dVAE. Essentially, it is a VQ-VAE
with a couple of details changed. In short, the main difference is that instead of
learning a deterministic mapping from the encoder’s output to the codebook,
it produces probabilities of a latent representation over all codebook vectors.
Dall-E system
Dall-E is composed of two stages. The above introduction of VQ-VAE was
necessary to understand the first one. Essentially, it is training dVAE to
compress 256x256 images into a 32x32 grid of tokens. This model will play a
crucial role in the second stage.
The second stage is about learning the prior distribution of text-image pairs.
First, the text is byte-pair (Sennrich et al., 2015a) encoded into a maximum
of 256 tokens, where the vocabulary is of size 16384. Next, the image representation encoded by previously trained dVAE is unrolled (from 32x32 grid to
1024 tokens) and concatenated to the text tokens. This sequence (of 256+1024
tokens) is used as an input for a huge transformer-like architecture. Its goal is
to autoregressively model the next token prediction.
During inference time, the text caption is again encoded into 256 tokens
at most. The generation process starts with predicting all of the next 1024
image-related tokens. They are later decoded with the dVAE decoder that was
trained in the first step. Its output represents the final image.
Results
Results achieved with the original Dall-E attracted so much attention mainly
due to its diversity and zero-shot capabilities. Dall-E was capable of producing
better results compared to previous state-of-the-art models which were trained
on data coming from the same domain as data used for evaluation. One
comparison can be seen in Figure 3.24.
Outputs of some of the prior approaches described in this chapter compared
with Dall-E can be seen in Figure 3.25.
Limitations
Although Dall-E made a huge step forward in text-to-image modelling, it still
showed multiple flaws. First, photorealism of the outputs is still relatively low.
In other words, when prompted for images containing realistic situations, it is
rarely capable of deceiving human evaluators. Second, the model has evident
problems with understanding relatively complex abstractions, such as text
inside an image, or relative object positions in the scene.
114 3 Multimodal architectures
FIGURE 3.24: Human evaluation of Dall-E vs DF-GAN on text captions
from the MS-COCO dataset. When asked for realism and caption similarity,
evaluators preferred Dall-E’s results over 90\% of the time. Figure from Ramesh
et al. (2021b).
FIGURE 3.25: Comparison of the results from Dall-E vs prior works on
MS-COCO. Dall-E’s outputs are chosen as the best out of 512 images, ranked
by a contrastive model. Figure from Ramesh et al. (2021b).
3.2 Text2Image 115
3.2.4 GLIDE
Introduced by Nichol et al. (2021b), GLIDE started an era of huge-scale
diffusion models. The concept of diffusion has already been used in the area
of Deep Learning for some time before. However, the authors of GLIDE took
a step further and combined it together with text-based guidance which is
supposed to steer the learning process in the direction of the text’s meaning.
This powerful method was proven to achieve outstanding results which remain
competitive with current state-of-the-art models at the time of writing.
Diffusion models
Before understanding the inner workings of GLIDE, it is important to introduce
the core concept that is driving it, namely diffusion. The idea of diffusion
originates from physics. In short, it corresponds to the process of diffusing
particles, for example of one fluid in another. Normally it has a unidirectional
character, in other words, it cannot be reversed. However, as Sohl-Dickstein
et al. (2015) managed to show, and Ho et al. (2020a) later improved, if the
data diffusion process is modelled as a Markov chain with Gaussian noise
being added in consecutive steps, it is possible to learn how to reverse it. This
reversed process is exactly how images are generated by the model from pure
random noise.
Let us construct a Markov chain, where the initial data point is denoted by x0.
In t steps, Gaussian noise is added to the data. The distribution of the data at
t-step can be characterized in the following way:
q(xt|xt−1) := N(xt;
√
αtxt−1,(1 − αt)I)
where (1 − αt) parametrizes the magnitude of the noise being added at each
step. Now, if xt−1 was to be reconstructed from xt, a model needs to learn
to predict estimates of gradients from the previous steps. The probability
distribution of previous steps can be estimated as follows:
pθ(xt−1|xt) = N(xt−1; µθ(xt), Σθ(xt))
where the mean function µθ was proposed by Ho et al. (2020a). For a more
detailed explanation of how this is later parametrized and trained, one could
follow Weng (2021).
GLIDE system
GLIDE can essentially be broken down into two parts. The first of them is the
pretrained Transformer model, which in principle is responsible for creating the
text embeddings. The last token embedding is used as a class embedding (text
representation) in later stages. Additionally, all tokens from the last embedding
layer are being used (attended to) by all attention layers in the diffusion model
116 3 Multimodal architectures
itself. This makes the model aware of the text meaning while reconstructing
the previous step in the Markov chain.
The second component of the GLIDE is the diffusion model itself. A U-Netlike architecture with multiple attention blocks is used here. This part’s sole
goal is to model pθ(xt−1|xt, y), where y corresponds to last token embedding
mentioned above. Or, to put it differently, to predict θ(xt|y) since the problem
can be reframed as calculating the amount of noise being added at each step.
Additionally, to make the model even more aware of the text’s meaning,
guidance is being used at inference time. In short, the idea is to control the
direction of the diffusion process. The authors test two different approaches.
First, they try guidance with the use of a separate classifier, OpenAI’s CLIP in
this case. However, better results were in general achieved by the classifier-free
guidance process. The idea is to produce two different images at each step.
One is conditioned on text, while the other one is not. Distance between them
is calculated and then, after significant scaling, added to the image obtained
without conditioning. This way, the model speeds up the progression of the
image towards the meaning of the text. This process can be written as:
ˆθ(xt|y) = θ(xt|∅) + s ∗ (θ(xt|y) − θ(xt|∅))
where s denotes the parameter for scaling the difference between the mentioned
images.
Results
GLIDE achieves significantly more photorealistic results compared to its
predecessors. FID scores reported on the MS-COCO 256x256 dataset can
be seen in Figure 3.26. It is worth noting that GLIDE was not trained on this
dataset, hence its zero-shot capabilities are even more impressing.
FIGURE 3.26: Comparison of FID on MS-COCO 256×256. Figure from
Nichol et al. (2021b).
Results are also preferred by human evaluators in terms of photorealism and
3.2 Text2Image 117
the similarity of the image to its caption. A comparison to DALL-E 1 results
can be seen in Figure 3.27
FIGURE 3.27: Win probabilities of GLIDE vs DALL-E. Figure from Nichol
et al. (2021b).
Finally, some of the cherry-picked images together with their corresponding
captions can be seen in Figure 3.28.
FIGURE 3.28: Samples from GLIDE with classifier-free-guidance and s=3.
Figure from Nichol et al. (2021b).
Limitations
GLIDE suffers from two problems. First, it fails when being presented with
a complex or unusual text prompt. A few examples can be seen in Figure
3.29. Also, the model is relatively slow at inference time (much slower than
GANs). This is caused by the sequential character of the architecture, where
consecutive steps in Markov chain reconstruction cannot be simply parallelized.
3.2.5 Dall-E 2 / unCLIP
The contribution that probably attracted the most attention in the field is
known under the name Dall-E 2 (Ramesh et al., 2022a). For the first time,
the wider public had picked interest in its potential applications. This might
be due to a great PR that could be seen from the authors, namely OpenAI.
Dall-E 2, also known as just Dall-E, or unCLIP, has been advertised as a
successor of Dall-E 1, on which results it significantly improved. In reality,
118 3 Multimodal architectures
FIGURE 3.29: Failures happen mostly for unusual prompts. Figure from
Nichol et al. (2021b).
the architecture and the results it achieved are much more similar to that of
GLIDE. Additionally, social media has been flooded with images generated by
the model. This was possible thanks to OpenAI giving access to it to everybody
who was interested and patient enough to get through a waiting list. However,
the model itself again remains unpublished. Another factor that might have
contributed to Dall-E’s success were its inpainting and outpainting capabilities.
Although, it is worth mentioning they were already also possible with GLIDE.
In essence, UnCLIP is a very smart combination of pior work from OpenAI
that was re-engineered and applied in a novel way. Nevertheless, the model
represents a significant leap forward, which is why it cannot be omitted in this
chapter.
Dall-E 2 system
UnCLIP consists of two components: prior and decoder. Let x be the image
and y its caption. zi and zt are CLIP image and text embedding of this
(x, y) pair. Then, prior P(zi
|y) is responsible for producing CLIP image
embeddings conditioned on the text caption. A decoder P(x|zi
, y) outputs an
image conditioned on the CLIP image embedding and, again, the text caption
itself.
For the prior authors try two different approaches, namely autoregressive and
diffusion models. The latter ended up yielding slightly better results. The
diffusion prior isa Transformer taking as an input a special sequence of an
encoded text prompt, CLIP text embedding, embedding for the diffusion step,
and a noised CLIP image embedding.
The decoder consists of diffusion models again. Firstly, a GLIDE-like model
takes a CLIP image embedding as its xt instead of the pure noise that was used
in its original version. Similarly to the original GLIDE, classifier-free guidance
is applied, however with slight differences. Lastly, two diffusion upsampler
models are trained to bring images first from 64x64 to 256x256, and then from
256x256 to 1024x1024 resolution. The authors found no benefit in conditioning
3.2 Text2Image 119
these models on text captions. Finally, unCLIP can be summarized as a mixture
of GLIDE and CLIP with a lot of engineering behind it.
Results
When compared to GLIDE, unCLIP shows it is capable of representing a
wider diversity of the data, while achieving a similar level of photorealism and
caption similarity. Comparison to previous works on the MS-COCO dataset
shows that unCLIP achieves unprecedented FID (Figure 3.30). A few output
examples calculated on MS-COCO captions can be found in Figure 3.31.
FIGURE 3.30: Comparison of FID on MS-COCO. The best results for
unCLIP were reported with the guidance scale of 1.25. Figure from Ramesh
et al. (2022a).
Limitations
UnCLIP suffers from very similar problems as its predecessor GLIDE. First,
compositionality in the images tends to sometimes be confused by the model.
Failure cases can be seen in Figure 3.32. Second, UnCLIP struggles with generating coherent text inside an image (Figure 3.33). The authors hypothesize that
using CLIP embeddings, although improving diversity, might be responsible
for making these problems more evident than in GLIDE. Lastly, UnCLIP often
fails with delivering details in highly complex scenes (Figure 3.34). Again,
according to the authors, this might be a result of the fact that the decoder is
producing only 64x64 images which are later upsampled.
3.2.6 Imagen & Parti
Only a few months after unCLIP was released by OpenAI, for the first time
Google came into play with its new autoregressive model called Imagen (Saharia
et al., 2022b). Another one followed just two months later - Parti (Yu et al.,
2022b). Both of these models pushed the boundaries even further, although they
take entirely different approaches. None of them is introducing a completely new
way of looking at the problem of text-to-image generation. Their advancements
120 3 Multimodal architectures
FIGURE 3.31: Image samples on MS-COCO text prompts. Figure from
Ramesh et al. (2022a).
3.2 Text2Image 121
FIGURE 3.32: ‘a red cube on top of a blue cube’ Figure from Ramesh et al.
(2022a).
FIGURE 3.33: ‘A sign that says deep learning.’ Figure from Ramesh et al.
(2022a).
come from engineering and further scaling existing solutions. However, it must
be stressed that currently (September 2022) they are delivering the most
outstanding results.
Imagen is a diffusion model. Its main contribution is that instead of using
a text encoder trained on image captions, it actually uses a huge pretrained
NLP model called T5-XXL (Raffel et al., 2019b) that is taken off the shelf and
frozen. Authors argue that this helps the model understand language much
more deeply, as it has seen more diverse and complex texts than just image
captions.
On the other hand, Parti takes an autoregressive approach. Similarly to the
first version of Dall-E, it consists of two stages, namely the image tokenizer
and sequence-to-sequence autoregressive part which is responsible for generating image tokens from a set of text tokens. In this case, ViT-VQGAN (Yu
122 3 Multimodal architectures
FIGURE 3.34: ‘A high quality photo of Times Square.’ Figure from Ramesh
et al. (2022a).
et al., 2021) is used as a tokenizer and the autoregressive component is again
Transformer-like.
Results
Both of the models improved the FID significantly compared to the previous
works. Figure 3.35 shows the comparison.
FIGURE 3.35: Comparison of FID on MS-COCO. Figure from Yu et al.
(2022b).
Samples from Parti can be seen in Figure 3.36. They are included here on
purpose - this is the current state-of-the-art as of the moment of writing!
Limitations
3.2 Text2Image 123
FIGURE 3.36: Selected samples from Parti. Figure from Yu et al. (2022b).
Yu et al. (2022b) mention an extensive list of problems, with which Parti still
struggles. At this point, all of them can be treated as a set that is common to
almost all available models. Among others, they touch:
• feature blending (where features of two different objects are missed)
• omission or duplicating details
• displaced positioning of objects
• counting
• negation in text prompts
and many many more. These flaws pose a challenge for future research and
undoubtedly they are the ones that need to be addressed first to enable another
leap forward in the field of text-to-image generation.
3.2.7 Discussion
Lastly, it is important to mention a couple of different topics, or trends, which
are intrinsically linked with text-to-image generation. Together with previous
124 3 Multimodal architectures
sections, they should give the reader a holistic view of where research currently
stands (again, as of September 2022).
Open- vs closed-source
The first trend that has emerged only recently is AI labs to not open-source
their state-of-the-art models and training data. This is in clear opposition to
how the entire AI community was behaving from the very beginning of the
recent Deep Learning era Apparently, possible commercial opportunities that
come along with owning the software are too big to be ignored. The trend is
very disruptive - it is clear that the community is currently witnessing the
maturation of AI business models. Needless to say, it is followed by all the
greatest AI labs, just to name a few: OpenAI, DeepMind, Google Brain, Meta
AI, and many others. As long as commercial achievements will have an edge
over academic community research, it is highly doubtful that the trend will be
reversed. However, it needs to be stressed that all of them are still issuing more
or less detailed technical specifications of their work in the form of scientific
papers, which is definitely a positive factor. We, as a community, can only
hope it will not change in the future.
Open-Source Community
As the trend of closed-sourceness is clearly visible across many Deep Learning
areas, the text-to-image research is actually well represented by an open-source
community. The most important milestones of the recent years indeed come
from OpenAI, however, new approaches can be seen across a wide community
of researchers. Many of these models are public, meaning that any user with
minimal coding experience can play with them. Although we decided not to
go into details of particular works, it is important to name a few that became
the most popular:
• VQGAN-CLIP (Crowson et al., 2022)
• Midjourney (Midjourney, 2022)
• Latent Diffusion (Rombach et al., 2021)
• Stable Diffusion (Rombach et al., 2022)
Potential applications
Image generation that can be done in a controllable manner has undoubtedly
huge potential for commercialization. Although the field is currently still
very immature, hypotheses about which industries might be disrupted are
emerging. Essentially, every branch that has to do with generating visual art,
be it static images or videos, should observe the trend closely. Graphic design,
movie making, stock photos - just to name a few that might be interested.
Currently, experimental use cases in the area of texture synthesis, product
design, or building virtual reality worlds can already be observed. AI, even if
still incapable of generating the final product, can help automate a significant
part of the production chain, which essentially means time and money savings.
3.3 Images supporting Language Models 125
The inpainting and outpainting capabilities of recent models play a significant
role in this trend. Although it is still very hard to judge which direction it
takes in the future, it will definitely be a very interesting and disruptive change.
Who wouldn’t like to see movies being soon generated directly from a book’s
text, pixel value by pixel value?
Ethics / Conclusion
Automated image generation poses an array of serious questions of ethical
character. Fortunately, many of them are already very well recognized by
the community. For example, OpenAI elaborates extensively on the risks and
limitations of their Dall-E 2 in this blog post by Mishkin et al. (2022). A few
of the most important topics are presented here.
The first and very significant risk is the potential misuse of the models. Fake image generation can easily be used for harassment and disinformation. Especially
combined with inpainting, which is capable of erasing or adding objects to real
scenes, it poses a non-trivial challenge for researchers on how to responsibly
share their work.
Another important area touches on biases and stereotypes which are intrinsically built into the technology. Obviously, a model combines concepts from
the data it has seen. However, if this area is to be commercialized, it needs to
ensure broader diversity. An interesting example of Dall-E 2 samples can be
seen in Figure 3.37.
In order to fully enable AI generation, the problem of copyrights needs to be
solved in the first place. It is definitely not clear who is the author of generated
images. Is it the person who came up with a text prompt and ran the model? Is
it a model engineer? The author of the model’s architecture? The owner of the
data it has been trained on? Or maybe the model itself? Another question is
what really is a creative contribution and eventually should result in copyright
being granted. These and many others definitely require extensive debate and
hopefully, legal solutions following it.
3.3 Images supporting Language Models
Author: Giacomo Loss
Supervisor: Matthias Aßenmacher
3.3.1 Words In (Non-Symbolic) Contexts
Imagine you were alone in a foreign country, you could not speak the language
and the only resource you had were a dictionary in the foreign language. You see
126 3 Multimodal architectures
FIGURE 3.37: Biased samples from Dall-E 2. Figure from Mishkin et al.
(2022).
a word written on a sign but you cannot understand its meaning. What could
you do? One idea would be do open the dictionary and look the word up. The
problem is that the word is defined by using other words in the foreign language.
As a second step you would thus look these new words up and continue like
that in further steps to the “infinity and beyond” (cit. Buzz Lightyear). But
even after looking every single word in the dictionary up, you would still not
be able to understand the meaning of the word written on the sign. If on
that sign, next to the unknown word, something else was instead depicted, for
example an image of a fork and a knife, you might speculate that the word
indicates something which has to do with food, like a restaurant. And this
without explicitly knowing the meaning of the word. This example is inspired
by the work of Stevan Harnad, which formulated at the beginning of the 90’s
the so called Symbol Grounding Problem (Harnad (1990)). It asserts that it is
not possible to understand the meaning (semantics) of a word by just looking
3.3 Images supporting Language Models 127
at other words because words are essentially meaningless symbols. It is possible
to understand the meaning only if the word is put in a context, a perceptual
space, other than that of written language: the word must be grounded in
non-symbolic representations, like images, for example. Over the past 10 years
there has been a whopping development of distributional semantic models
(DSMs, henceforth), especially after the Word2vec (Mikolov et al. (2013b))
revolution. This family of models assumes that the meaning of words and
sentences can be inferred by the “distribution” of those words and sentences
within a text corpus (the Distributional Hypothesis formulated by Harris et al.
(1954)). But the Symbol Grounding Problem mentioned earlier suggests that
DSMs do not resemble the way words are learned by humans, which is in
multimodal perceptual contexts. For these reasons, models have been developed
with the goal to integrate further modalities (like visual ones) in pure language
models, assuming that grounding words and sentences in other perceptual
contexts should lead to a better understanding of their semantics and, as a
result, to better performance in pure language tasks.
The focus of this subchapter are models which empower pure language models
with visual modalities in form of images: their goal is to obtain better semantic
representations (in form of embedding vectors) of words. First, a quick recap
of the main pure language models will be provided. After that, the historical
evolution of the integration of images as visual modalities into pure language
models will be discussed: from simple concatenation of textual and visual
modalities, to the projection of visual elements in a common grounded space
and more recently, the use of Transformers (see figure 3.38). Eventually, a
comprehensive evaluation of the different models against benchmarks will be
carried out.
Again, the focus is on how to employ visual elements to obtain embeddings
able to capture the semantics of words. More concrete applications, such as
those in the field of machine translation are out of scope and will be only
marginally addressed at the end of the subchapter.
FIGURE 3.38: Historical evolution of models which integrate visual information into pure language models.
128 3 Multimodal architectures
3.3.2 Word-Embeddings: Survival-Kit
In other parts of this books, the most important NLP-models and the latest
developments in the field are extensively described. In this section, some
information will be provided, which might be helpful to understand some of
the aspects discussed in this subchapter. As it may have been inferred in the
introduction, the starting point is always a pure language model, namely a
model which employs only textual inputs in order to generate word embeddings,
which are representations of words in form of numerical vectors. The most
widely used pure language models in the papers presented in this subchapter
are the following three:
• Skipgram (Word2vec, Mikolov et al. (2013b)), where given a target word, the
probability of the neighboring (surrounding) words in a pre-defined window
has to be maximized. Trainig takes place either through a hierarchical softmax
or through negative sampling, which involves maximizing the probability of
words which are real neighbors and minimizing that of words which are not
real neighbors (the “negative samples”)
• GloVe (Pennington et al. (2014)), which is based on words co-occurrence
across the entire corpus, with the goal of minimizing the difference between
the dot product of the embedding vectors of two words and the logarithm of
the number of co-occurrences
• BERT (Devlin et al. (2018c)): two pre-training tasks to obtain wordembeddings:
– Masked Language Modelling (MLM): given a sentence with [MASK]ed
tokens, the goal is to predict these masked tokens
– Next Sentence Prediction (NSP): given two sentences A and B, the goal
is to predict if B follows from A
Two additional remarks to conclude this section. First, Skipgram and GloVe
generate embeddings which are “context-free”: they do not take into account
the context in which words occur. On the contrary, BERT is designed to
represent words given the context (sentence) in which they occur: we can
thus have different embeddings for the same word, depending on the context.
Second, the inputs of these models are tokens: with the help of a tokenizer,
which can be different for different models, the text is split in “chunks”, called
tokens (and they are not necessarily single words).
3.3.3 The Beginning: Sequential Multimodal Embeddings
Supposing we add linguistic and visual feature representations related to
a particular word, how could we fuse them? One intuitive idea would be
to concatenate the textual and visual modalities. Let Vtext be the textual
(vectorial) representation of a word and let Vimg be its visual (vectorial)
representation, a fused representation F of a certain word w might take the
following simplified form:
3.3 Images supporting Language Models 129
F = γ(Vtext)
M(1 − γ)Vimg
where γ is a tuning parameter which controls the relative contribution of both
modalities to the final fused representation. Bruni et al. (2014) propose a model
where the meaning of a target word is represented in the form of a semantic
vector and all vectors are collected in a text-based semantic matrix; textual
embeddings are computed based on (transformed) co-occurrence counts of
words in a pre-defined window. The starting point to obtain an image-based
representation of certain target word is a dataset of labeled images. For each
image associated to the target word (which means that the target word is to
be found in the image’s caption), low-level features called “local descriptors” -
which incorporate geometric information of specific areas of a certain picture
- are extracted and then these descriptors are assigned to clusters (bags) of
“visual words”1
. Afterwards, for each target word, visual word occurrences are
summed up together to obtain the occurrence counts related to the target
word. These image-based semantic vectors are then transformed and collected
in an image-based semantic matrix. The two matrices are then concatenated
and projected into a common latent multimodal space with a singular value
decomposition. Thanks to this process a textual mixed matrix and a visual
mixed matrix are extracted and then combined together according to different
fusion strategies to build the multimodal embeddings. In this first, relatively
cumbersome (historically motivated) example, the vector representation of an
image is obtained with non-trivial features engineering.
In recent years, the use of neural networks has made an “automatic feature
selection” possible. This is what for example Kiela and Bottou (2014) propose,
extracting visual features from the first seven layers of a convolutional neural
network (proposed by Krizhevsky et al. (2012b)) trained on 1.6 million images
from the ImageNet database (Deng et al. (2009)), which produces scores
for 1,512 object categories. The linguistic part of the model relies on the
Skipgram model by Mikolov et al. (2013b) and consists of 100-dimensional
vector representations. The multimodal representation is again obtained by
concatenation of both modalities.
Another notable example of concatenation/sequential combination of textual
and visual modalities is the work of Silberer and Lapata (2014): textual
and visual modalities are represented by separate vectors of textual and
visual attributes. During training, these textual and visual inputs vectors are
separately fed to denoising (unimodal) autoencoders, the training objective
of which is the reconstruction of a certain corrupted input - e.g. through
masking noise - from a latent representation. Their outputs are then jointly
fed to a bimodal autoencoder to be mapped to a multimodal space, on which
1See for example Bosch et al. (2007) for more details on this technique, called “bag-ofvisual-words”.
130 3 Multimodal architectures
FIGURE 3.39: From Kiela and Bottou (2014). Textual and visual features
vectors are concatenated.
a softmax layer (classification layer) is added, which allows the architecture to
be fine-tuned for different tasks.
3.3.4 The Grounded Space
The aforementioned models assume implicitly a one-to-one correspondence
between text and images: a visual representation is extracted only from words
which are associated to a concrete image. This is a limitation, for two partially
overlapping reasons. One one hand, how can we depict words for which no image
is available in our training set? Is it possible to imagine visual representations
purely from linguistic ones? On the other hand, could we hypothetically find a
visual representation for each word? This might be true for concrete words but
when it comes to abstract ones, it is not always possible to find suitable visual
representations or, said in other terms, many words are not visually grounded.
For this reasons, researches have addressed the question: could we map textual
and visual elements to a grounded space and design models able to generalize
images and words beyond those in the training set? Well, the answer is yes!
Lazaridou et al. (2015) propose a multimodal Skip-gram architecture where
the objective function of a Skip-gram is “augmented” with an additional visual
objective:
1
T
X
T
t=1
(Lling(wt) + Lvision(wt))
3.3 Images supporting Language Models 131
where Lling is the Skip-gram loss function and Lvision is the additional visual
loss for the target word wt. In particular, Lvision has the form of a hinge loss,
the goal of which is to make the (vectorial) linguistic representation of a certain
word more similar to its visual representation:
Lvision(wt) = −
X
w
0∼Pn(w)
(max(0, γ − cos(zwt
, vwt
) + cos(zwt
, vw
0 ))
where vw
0 is a visual representation of a randomly chosen word w
0
(drawn
from a probability distribution Pn(w)) used as negative sample, vwt
is the
corresponding visual vector and zwt
is the target multimodal word representation which has to be learned by the model. It is nothing more than a linear
transformation of a word representation uwt
: zwt = Mu→vuwt
and Mu→v
is a
cross-modal mapping matrix from linguistic inputs to a visual representation.
It is important to remark that during training, for words which do not have
associated images, Lvision gets set to zero. When this cross-modal mapping
matrix is estimated, it is then possible to find a visual representation for new
words, which do not have a related image in the training set: the model allows
to imagine new words. This is what is meant with grounded space: a perceptual
(visual, in this case) space where a word is grounded, put in context.
FIGURE 3.40: From Lazaridou et al. (2015). The linguistic embedding of
the word ‘cat’ is mapped to a visual space, such that the similarity of vector
representations of words and associated images is maximized.
Similar instances of a cross-modal mapping can be found for example in Kottur
et al. (2016) (a multimodal extension of the CBOW model specification of
word2vec) and in Collell et al. (2017), where visual features are obtained from
the forward pass of a CNN, pre-trained on ImageNet (Deng et al. (2009)) and
132 3 Multimodal architectures
a mapping function from the textual space to the visual space is obtained as
a result of the training process. Also in this case it is possible to generate a
visual representation from the embedding of a certain word, not necessarily
present in the training set. In particular, they propose two specifications of
the mapping function: a simple linear mapping and neural network with a
single hidden layer. Last but not least, Hill and Korhonen (2014) recognize
that concrete nouns are more likely to have a visual representation. For this
reason, they map a set of concrete words (CSLB, Devereux et al. (2014))
to “bags of perceptual/visual features” and every time one of these words
is encountered during training, the Skip-gram model they are using stops
training on that sentence and instead continues the training on a newly created
“pseudo-sentence”, which takes into consideration the aforementioned bag of
perceptual features. This list is unfortunately not exhaustive and there are
other models with similar ideas, for example Ailem et al. (2018) or Kiros et al.
(2018).
The aforementioned papers and related models focus on the modeling of
semantics of words. Nonetheless, there are models designed to address tasks at
sentence-level, such as sentiment analysis or sentence entailment. Kiela et al.
(2017) employ a bidirectional Long Short-Term Memory (LSTM, Hochreiter
and Schmidhuber (1997)) architecture to model sentence representations, in
order to gain information from the text in both directions. The goal is again
to encode a sentence and ground it in an image. Textual embeddings are
obtained with GloVe (Pennington et al. (2014)) and they are then projected
on a grounded space with a linear mapping. This grounded word vector
serves as input for the bidirectional LSTM, which is trained together with the
linear mapping. Their model is versatile and depending on the loss function
specification, it can not only propose alternative captions to an image (which
is a way to frame sentence equivalence tasks) but also predict captions from
images or perform both tasks at the same time. This last point highlights an
important characteristic of many of the models discussed in this subchapter:
even though the focus is on the empowerment of pure language models with
the addition of visual elements, some of the models discussed here can be used
for purposes other than pure language tasks. The control over which task is
performed is usually exercised by either specifying different loss functions (as
in the last model described) or setting properly certain hyperparameters (such
as in the previously described model by Silberer and Lapata (2014)).
3.3.5 The Transformers Era
A turning point for the field of NLP was Vaswani et al. (2017b)’s paper
“Attention is all you need”, where the authors proposed for two machine
translation tasks a novel architecture, the Transformer (not to be confused with
the giant robots from the Michael Bay’s blockbuster movies!), which leverages
only the attention mechanism. Even though an exhaustive description of the
3.3 Images supporting Language Models 133
Transformer architecture is beyond the scope of this subchapter, it is worth
mentioning why they became so popular over the past four years in the field
of NLP (among others), in comparison to Recurrent Neural Networks (RNNs)
and Long Short-Term Memory networks (LSTMs).
Well, the three main properties of Transformers are the following:
• Self-Attention
• Parallel input processing
• Positional embeddings2
When feeding for example a textual sentence to a RNN, the network deals with
one word after the other in a sequential fashion and one of the known issues is
the fact that information contained in earlier parts of the sequence tend to
“fade away” as the sentence is analyzed further: newer inputs carry a larger
influence on the outputs at a given step. LSTMs try to mitigate this problem
by introducing a component called “gate”, which regulates the information
flow, namely which information from the past inputs need to be “remembered”
by the model. The goal is to capture long-term dependencies among different
parts of the sentence fed into the model.
On the contrary, thanks to the Self-Attention mechanism, at each step Transformers can access previous steps, thus limiting to a minimum the loss of
information. Moreover, inputs are processed not sequentially but all at the
same time, thus allowing to capture dependencies by looking at the sentence
as a whole and this could make a fundamental difference in many downstream applications: for example in the German language, in dependent clauses
(“Nebensaetze”), the verb comes at the end of the phrase but it determines the
verbal case of the nouns that come before the verb. Thus Transformer could
potentially capture the dependencies between the verb coming at the end of
the sentence and the words at the beginning. Lastly, Transformers encode for
every input information on its position within a sentence, since it is often the
case, that the importance and meaning of a certain word varies depending on
its position within a sentence. These were the Transformers, in a nutshell.
But Transformers did not only bring a change of paradigm in terms of architectures. First, while for models in the pre-Transformers era described before, the
focus was on the ability of word embeddings to capture similarity among words,
now the focus has shifted more on downstream tasks (more on this later in the
evaluation section), encompassing not only pure linguistic ones but also tasks
with visual components, such as for example, visual question answering. It is
now more difficult (but not impossible) to draw a line between models where
“images support pure language models” (the object of this subchapter) and
models which could be actually categorized as “vision and language” models
but they can be employed also to solve pure linguistic tasks. This issue brings
2
It may be argued that this point is a necessity to be able to work on sequences rather
than a strength.
134 3 Multimodal architectures
another peculiarity of many Transformers-base models, namely their “universal
vocation”: without loss of generality we could say that the idea is now to design
powerful (multimodal) pre-training (mostly self-supervised) tasks capable of
generating task-agnostic representations, whose encoded knowledge can be
efficaciously transferred to diverse downstream tasks, limiting the amount of
labeled data necessary to fine-tune the models (this is the so-called few-shot
learning).
Let’s briefly discuss two examples, Flava (Singh et al. (2022)) and UniT (Hu
and Singh (2021a)). Flava has two separate encoders for images and text and
a multimodal encoder, all based on the Vision Transformer (Dosovitskiy et al.
(2020a)). Unimodal pre-training consists of masked image modeling (where
a set of image patches are to be reconstructed from other unmasked image
patches) and masked language modeling. Multimodal pre-training tasks consist
instead of a global contrastive loss (maximization of cosine similarities between
paired images and text), a masked multimodal modeling (where image patches
and text tokens are masked) and an image-text matching task. The model is
pre-trained jointly on unimodal and multimodal datasets and then evaluated
(fine-tuned) on 22 vision tasks, 8 pure linguistic tasks and 5 vision and language
tasks.
UniT has an image encoder and a text encoder, a multimodal domain-agnostic
decoder and task-specific heads. There is no pre-training on multimodal data
and the model is trained end-to-end on 7 tasks (vision, language and vision
an language) and 8 datasets, with the idea that solving different tasks across
domains in a jointly fashion should prevent general knowledge from being lost
due to fine-tuning over particular downstream tasks.
These two examples clearly show what it is meant by “universal vocation” of
many modern Transformer-based models. But there are still models specifically
designed to solve pure language tasks and in the following pages, two of them
will be described.
3.3.5.1 Vokenization
It is often difficult for a child to describe the meaning of a certain word. A
child might not be able to describe what a lion is but if he is given pictures of
different animals he might be very well able to point at the picture of a lion.
Visual pointing could thus act as a form of supervision to natural language. Is
it possible to build within a pure language model a form of visual supervision,
which mimics the visual pointing often adopted by children? This is exactly
the problem that Tan and Bansal (2020) try to address: how to associate to
each textual representation (token) a visual representation (Voken).
Let’s suppose we had a dataset of word(token)-image pairs. We could integrate
in the pre-training framework of pure language models the following VokenClassification task:
3.3 Images supporting Language Models 135
LV OKEN−CLS(s) = −
X
l
i=1
log pi(v(wi
; s)|s)
h1, h2, ..., hl = languagemodel(w1, w2, ..., wl)
pi(v|s) = sof tmaxv{Whi + b}
where {hi} is the feature representation of each token in a sentence s = {wi}
extracted from a language model (such as BERT) and the vokens originate
from a finite set of images X. Each hi
is then transformed into a probability
distribution through a softmax layer, with the voken-classification loss defined
as the negative log-likelihood of all related vokens.
The model architecture would then be:
FIGURE 3.41: From Tan and Bansal (2020). Visually supervised the language model with token-related images, called Vokens.
Everything sounds fantastic! There is only one small pitfall: a set of X of
images for all tokens does not exist! Could we find a proxy for such a set?
One might consider image-captioning datasets such as MS COCO (Lin et al.
(2014b)). But also this suboptimal solution is problematic.
The Grounding Ratio is defined as the proportion of tokens in a dataset which
are related to a specific visual representation (i.e. the tokens are visually
grounded), such as “dog”, “table” and the like. In figure 3.42 it is striking
that only around one third of tokens contained in pure language corpora such
Wiki103, English Wikipedia and CNN/DM are visually grounded in image
captioning datasets3
. It is not possible to rely (only) on image captioning
datasets to build the Voken-Classification task. But the fact that a word/token
does not have a visual representation in one of these datasets, it does not
mean that it is not possible to visually represent the word/token. Would it be
possible to associate images to words/tokens not directly visually grounded?
Well, the answer is yes!
3From an operative point of view, the authors consider a token type “visually grounded”
if it has more than 100 occurrences in MS COCO
136 3 Multimodal architectures
FIGURE 3.42: From Tan and Bansal (2020). Statistics of image-captioning
dataset and other natural language corpora. VG, CC, Eng Wiki, and
CNN/DM denote Visual Genome, Conceptual Captions, English Wikipedia,
and CNN/Daily Mail, respectively. JSD represents Jensen–Shannon divergence
to the English Wikipedia corpus.
FIGURE 3.43: From Tan and Bansal (2020). The Vokenization process. A
contextualized image (visual token, Voken) is retrieved for every token in a
sentence and with this visual token, visual supervision is performed.
The Vokenization is a process to assign every token wi contained in a sentence
s to a visual representation (called voken) originating not from a generative
model but rather from a finite set of images X = {x1, ..., xn}. The voken
v(wi
; s) is the image from X which maximizes the following Relevance Score
Function:
v(wi
; s) = arg maxx∈Xrθ
∗ (wi
, x, s)
This function takes into account not only the token wi
itself, but also the
context (the sentence) and it is parametrized by θ with θ
∗ being the optimal
value (which has to be estimated).
3.3.5.1.1 The Relevance Score Function: Model, Training, Inference
The Relevance Score Function is defined as the inner product of the language
feature representation fθ(wi
, s) and the visual feature representation gθ(x):
3.3 Images supporting Language Models 137
fθ(wi
, s)
T
gθ(x)
Supposing h1, ..., hl and e are the embeddings originating from pre-trained
language and visual encoders respectively (in the paper the authors use BERT
and ResNeXt), the language and visual representations are obtained first
by applying multi-layer perceptrons w_mlpθ and x_mlpθ to downproject
the embeddings from the pre-trained models to a common vector space and
secondly they are normalized (with L2-Norm):
fθ(wi
; s) = w_mlpθ(hi)
||w_mlpθ(hi)||
gθ
(x) = x_mlpθ(e)
||x_mlpθ(e)||
With respect to the training of the model, to estimate the optimal value for the
parameter θ, image-captioning datasets, which are collections of sentence-image
pairs, are employed. Operationally, for every sentence sk associated to image
xk in the image-captioning dataset, each token wi
in s is associated to xk and
the hinge loss is used to estimate the optimal value of θ
∗
:
Lθ(s, x, x0
) = X
l
i=1
max(0, M − rθ(wi
, x, s) + rθ(wi
, x0
, s))
The goal is to maximize the Relevance Score Function between aligned tokenimage pairs (wi
, x; s) and to minimize the score for unaligned pairs (wi
, x
0
; s)
by at least a margin M, with x
0
being a randomly sampled image from the
image captioning dataset not associated to sentence s.
Once we have the language feature representation fθ(wi
, s) for each token
in our language corpus and the optimal estimate of θ, how is it possible to
find the image x encoded with the visual feature representation gθ(x), which
maximizes the Relevance Score Function? As said earlier, the function is
expressed as the inner product of the textual and visual representations and
since the feature vectors have euclidean norm equal to 1, the inner product
maximization problem is equivalent to a nearest neighbor search problem.
It is just sufficient to find the vector gθ(x) which is the nearest neighbor of
fθ(wi
, s)
4
.
With this process, it is thus possible to assign a visual representation, a voken,
to any word/token in a language corpus, pooling from a finite set of images.
The problem of the low Grounding Ratio outlined above is solved and the
Voken-Classification task could be integrated in the pre-training framework
4The proof is straightforward. Let X ∈ Rl and have euclidean norm equal to 1, which
means ||X||2 = 1. In the nearest neighbor search we need to find the vector Y ∈ Rl
, also
with norm equal to 1, which has minimal euclidean distance with X. This is the quantity to
138 3 Multimodal architectures
of any pure language model. Moreover, the authors propose a method called
Revokenization, which allows to transfer vokens generated using a particular
tokenizer to frameworks which employ other tokenizers.
3.3.5.2 One Step Further: The Power Of Imagination
Wikipedia defines imagination as “the production or simulation of novel objects,
sensations, and ideas in the mind without any immediate input of the senses”.
Indeed, humans do not only associate words with real images, but also leverage
the ability to imagine words/concepts: imagination can help the human brain
solve problems with limited supervision or sample points by empowering its
generalization capabilities. Until now we discussed language models supported
by visual information in form of real images (e.g. those retrieved from imagecaptioning datasets). But with the recent advancements in the field of generative
models for images, it is for sure worth investigating if these generative models
can help pure language models to produce better representations of words. In
particular, the framework proposed by Lu et al. (2022), iACE (ImaginationAugmented Cross-Modal Encoder) will now be discussed: the idea is
simply to use a generative model to obtain a visual representation of a textual
input and then use these imagined representations as “imagination supervision”
to pure language models.
This framework has two main components:
• the imagination generator G: given an input text x, VQGAN (Esser et al.
(2021)) is used to render an “imagination” i of x and CLIP (Radford et al.
(2021a)) is used to see how well the generated image i is aligned to the input
text x. This generative framework is known as VQGAN+CLIP
• Cross-modal Encoder Ec: the input text and the rendered imagination
are firstly encoded with a language and a visual encoder respectively and then
be minimized:
d(X, Y ) =
vuutXl
i=1
(xi − yi)
2
squared
=
Xl
i=1
x
2
i +
Xl
i=1
y
2
i − 2
Xl
i=1
xiyi
= ||X||2
2 + ||Y ||2
2 − 2XT Y
Norm−1
= 1 + 1 − 2XT Y
= 2(1 − XT Y )
And through these simple algebraic manipulations, it is possible to see that minimizing
the euclidean distance between X and Y is equivalent to maximize XT Y , which is the
inner product. This proves the equivalence between inner product maximization and nearest
neighbor search.
3.3 Images supporting Language Models 139
FIGURE 3.44: From Lu et al. (2022). The generator G visualize imaginations
close to the encoded texts by minimizing LGAN . The cross-modal encoder
Ec learns imagination-augmented language representation. Two-step learning
procedure consists of: 1) pre-train a Transformer with visual supervision from
large-scale language corpus and image set, 2) fine-tune the visually supervised
pre-trained Transformer and the imagination-augmented cross-modal encoder
on downstream tasks.
CLIP is employed as cross-modal encoder with inputs being text-imagination
pairs
The learning procedure is composed of two main steps (depicted in figure 3.44):
the first step consists in the pre-training of a visually supervised Transformer.
In particular, the Voken-Classification task described before is employed,
alongside a masked language modeling task. This is the baseline model, where
no information from the “imagination” procedure comes yet into play. The
second step is the imagination-augmented fine-tuning with two downstream
datasets D (GLUE, Wang et al. (2018) and SWAG, Zellers et al. (2018)).
On one side, the visually-supervised Transformer (the baseline) relies only on
the textual input during the fine-tuning phase and the following loss function
is employed:
LLang = −
X
|D|
j=1
X
K
k=1
yk log pk(dj (t)|D)
On the other hand, the iACE is trained to minimize the following cross-entropy
loss:
LImagine = −
X
|D|
j=1
X
K
k=1
yk log pk(dj (t, v)|D)
140 3 Multimodal architectures
with t and v being the textual and imagined features representations respectively, j indicates the j-th data sample in dataset belonging to dataset D, K
is the number of classes and pk is the conditional distribution of dj . Training
takes place in a jointly fashion and both losses, the imagination-augmented
one LImagine and the pure language loss LLang are linearly combined, with λ
being a balance factor:
L = λLImagine + (1 − λ)LLang
To sum up, this model-agnostic framework uses generated images for visual
supervision and could be integrated on top of pure language models (such as
BERT) or visually supervised models (such as the Voken model, which uses
Vokens, real images for visual supervision).
3.3.6 Was It Worth?
In this subchapter we investigated how visual inputs can support pure language
models in capturing the semantics of words. We started with simple concatenation of linguistic and visual features and ended up with Transformer-based
models, which are able to shape different word embeddings for the same word
by taking into account also the context (the sentence). But now the question
arises: with the addition of visual information, do we obtain word embeddings
that are better than those from pure language models? In other words, is what
we all have so far discussed worth? Well, as it is often the case in scientific
research, the answer is: “it depends!”
Individual evaluation of each single model might not be ideal because each
model has its peculiarities and it is impractical to make a direct comparison
among them. It is more useful to capture and discuss the themes which are
common to many models, in order to understand their strengths and weaknesses.
This is how we will proceed and we will also differentiate between evaluation
before Transformers and evaluation after Transformers.
3.3.6.1 Evaluation In The Pre-Transformers Era
Before the advent of Transformers, the evaluation focus was on the degree of
alignment between learned semantic representations (word embeddings) and
representations by human speakers, in form of correlation between model-based
and human-based word-similarity judgments. Three main types of similarity
are usually considered:
• Semantic similarity, e.g. “pasta is similar to rice”
• Semantic relatedness, e.g. “Bear is related to mountain”
• Visual similarity, e.g. “cucumbers look like zucchinis”
The evaluation pipeline could be summarized as follows:
3.3 Images supporting Language Models 141
FIGURE 3.45: Pipeline for intrisinsic evaluation of semantic representations.
In the first step, the cosine similarity between two word embeddings w1 and w2
is used as similariry measure and in a second step, the correlation with human
speakers’assessment is computed to gauge the quality of the embeddings. The
higher the correlation, the better the embeddings.
Word embeddings are vectors and to measure the degree of similarity between
two vectors, the Cosine Similarity is often used in the literature. In an ideal
setting, we would have word embeddings with the following characteristics:
if two words are semantically similar, the two embedding vectors should be
similar and their cosine similarity should go towards 1. If the two words are
unrelated, the embedding vectors should be orthogonal to each other and as a
consequence, the cosine similarity should go towards zero. Lastly, if two words
are negatively related, the two embedding vectors should point at opposite
directions and the cosine similarity should go towards -1. Once these similarity
measures between word pairs are computed, in order to measure the quality of
the embeddings several benchmarks can be employed, such as MEN (Bruni
et al. (2014)), WordSim353 (Agirre et al. (2009)) and SimLex999 (Hill et al.
(2015)). These datasets could be described as collections of word pairs and
associated similarity ratings by human speakers. Operationally, this means
that real people were asked if a pair of words was related or not and to
which degree, on a scale between -1 (negatively related) to +1 (semantically
equivalent). The higher the correlation between the cosine similarity and the
similarity judgments by humans, the higher the quality of the word embeddings.
Having done this methodological premise, let’s discuss the performance of
these pre-Transformer models!
Since the goal of these models is to enhance pure language models with the
addition of visual inputs, the baseline in the evaluation is always one (or more)
pure language model(s). Well, do visually grounded embeddings outperform
non-grounded ones? What emerges from virtually all papers is that visual
grounding can actually help get a better semantic representation of concrete
concepts, such as “cat”, “table”, “bicycle”, whereas they do not help much
with the representation of abstract concepts such as “love” and “peace”.
3.3.6.2 Evaluation In The Post-Transformers Era
A limitation of the intrinsic evaluation metrics is the high degree of subjectivity: the similarity between two concepts depends in many instances on the
experience, cultural background and preferences of the human observers. This
is why the evaluation focus has now shifted to a more extrinsic dimension: how
well do the models perform in downstream tasks? The problem of the “lack
142 3 Multimodal architectures
FIGURE 3.46: From Hill and Korhonen (2014): Each bar represents a different model settings and the dashed line indicates the pure linguistic benchmark
model. In figure 3.46 we can see that pure language models still perform
better than models with visual inputs when it comes to the representation
of abstract nouns. Another example is Kiela et al. (2017): they found that
their models perform better when tested on datasets with a higher degree of
concreteness and the same conclusion is reached by Collell et al. (2017), which
state that visual information can empower the representations of concepts that
are to a certain extent visual. To sum up, effective semantic representation
of abstract concepts constitute the main limitation common to many of the
models discussed in this section.
of objectivity” is thus solved because on downstream tasks there is no room
for opinions. The datasets used to train the models are also different and the
most widely used are:
• GLUE (Wang et al. (2018)): 9 tasks, including single-sentence tasks (e.g. sentiment analysis), similarity tasks (e.g. paraphrasing), inference tasks (e.g. textual entailment)
• SQuAD (Rajpurkar et al. (2016)): question/answer pairs
• SWAG (Zellers et al. (2018)): multiple choice questions about grounded
situations
As previously discussed, many Transformer-based models have universal vocation: they are built to solve a heterogeneous range of tasks from the language
and vision domain. If we thus consider only performance on pure language
tasks, the following two tables from Tan and Bansal (2020) are insightful:
It is straightforward: unlike in the pre-Transformers Era, where grounded word
embeddings could improve performance over baselines, Transformer-based
universal models do not outperform pure language models such as BERT
or RoBERTa. Nonetheless, the addition of visual supervision (the Voken-
3.3 Images supporting Language Models 143
FIGURE 3.47: From Tan and Bansal (2020). Statistics of image-captioning
dataset and other natural language corpora. VG, CC, Eng Wiki, and
CNN/DM denote Visual Genome, Conceptual Captions, English Wikipedia,
and CNN/Daily Mail, respectively. JSD represents Jensen–Shannon divergence
to the English Wikipedia corpus.
FIGURE 3.48: From Tan and Bansal (2020). Fine-tuning results of different
pre-trained models w/ or w/o the voken classification task (denoted as“Vokencls”).
Classification task) in the pre-training framework can boost performance above
the level of pure language models.
Pezzelle et al. (2021) analyzed the intrinsic quality of embeddings of some
vision and language (“universal”) models:
From this intrinsic evaluation perspective (which was popular in the preTransformers Era), vision and language models do not generally outperform
domain-specific models such as BERT and also in this case the only real
competitor of pure language models is a model with visual supervision (again,
Vokenization).
The bar plots depict correlation between human- and model-based similarity
ratings, differentiating between the most concrete concepts contained in a
144 3 Multimodal architectures
FIGURE 3.49: From Pezzelle et al. (2021). Spearman’s rank correlation
between similarities computed with representations by all tested models and
human similarity judgments in the five evaluation benchmarks.
FIGURE 3.50: From Pezzelle et al. (2021). Correlation between model and
human similarity ratings on WordSim353, SimLex999 and MEN. Each barplot
reports results on both the whole benchmark and the most concrete subset of
it.
certain dataset5 and the whole dataset (thus including more abstract concepts).
The results confirm the trend: multimodal models are more effective than pure
language models at representing concrete words but in many instances they
still lag behind when it comes to more abstract concepts.
Last but not least, few words need to be spent on a topic which has been
steadily gaining relevance: Few-Shot Learning. To train and test models, a
large pool of paired images and texts is often needed and the creation of many
of the datasets used in fine-tuning required a huge data collection effort, which
had to be performed by human agents. This implies that the creation of such
data pools can be very costly. For this reason, there is a growing interest in
creating models able to cope with low-resource settings. This boils down to
the question: can a model perform well on downstream tasks even with just
a limited number of training examples? The goal is actually once again, to
5See Brysbaert et al. (2014) for information on how concreteness of a word can be
estimated.
3.3 Images supporting Language Models 145
mimic how humans learn: a person does not need to see one thousand pictures
of a table, to be able to recognize a table. . .
FIGURE 3.51: From Lu et al. (2022). Model-agnostic improvement in Fewshot Setting with GLUE benchmark.
This table from Lu et al. (2022), where models are trained using only up to
5% of the training set, shows for example the ability for a model supervised
with “imagination” (which was a generated visual representation of a certain
textual input) to outperform models with only simple visual supervision (the
Voken-model). This is just an example, but the ability to perform well in fewshot settings has become the touchstone of the evaluation modern multimodal
models.
3.3.7 The End Of This Story
We started this story with the Symbol Grounding Problem, which affirms that
to grasp the meaning of a word, the word has to be put in a context other
than the pure linguistic one. We thus investigated some of the architectures
proposed to ground words in a visual space in form of static images. The goal
(hope) is to better capture the semantics of words, in form of better word
embeddings, to be employed in heterogeneous tasks, from semantic-similarity
to downstream tasks, such as sentiment analysis.
From this brief analysis it emerges that grounding words in images can actually
improve the representation of concrete concepts, whereas visual grounding
does not seem to add value to pure language models when it comes to abstract
concepts. Nonetheless, forms of visual supervision like the Voken-Classification
task or the employment of generative models which allow to imagine words,
such as in the iACE-Framework, might be the right way to bridge this gap.
The Transformers have been a revolution in the field of NLP and with their
advent, the trend has now become to build models with pre-training tasks
capable of generating powerful task-agnostic word representations. The knowledge gained with these tasks can be then transferred to downstream tasks with
the goal to limit the amount of labeled data necessary to fine-tune models.
Labeling data is indeed costly: this is why the ability of a model to generalize
146 3 Multimodal architectures
well when exposed to just few training examples has been steadily gaining
importance as evaluation metric. This was the so called few-shot learning.
Moreover, Transformer-based models have “universal vocation”: they tend to
be multimodal and multi-task, encompassing vision, language and vision and
language tasks. This idea might be appealing because humans learn by being
exposed to a multitude of different inputs and tasks. But as we have seen, pure
language models such as BERT tend to still outperform multimodal multi-task
models. There is definitely room for improvement.
One might wonder whether the grounding of words in images is the right way
to seek a better representation of words. Well, humans learn using all five
senses and maybe the answer might be to incorporate in the models more
heterogeneous perceptual information: not only static images but also videos,
speech and the like. The debate is still open: the story goes on. . .
Last but not least, a mention needs to be made on concrete applications of
these image-empowered word-embeddings. The use of images to support linguistic models has been experimented in several fields, from Dialogue Response
Generation (e.g. Sun et al. (2021)) to Machine Translation, where for example
Ive et al. (2019) found images to improve the quality of translation when
the textual context is generic and/or ambiguous. The number of potential
applications of the models described in this subchapter is growing steadily in
the scientific community. But this is yet another story. . .
3.3.8 Appendix: Selected Models - Summary
A table (available here) contains a summary of selected language models
augmented with visual components. For each model, the following information
are reported:
• Pure language model and pretraining data
• Visual features and pretraining data
• Fusion strategy of the two modalities
• Benchmarks/baselines for evaluation
3.4 Text supporting Vision Models
Author: Max Schneider
Supervisor: Jann Goschenhofer
3.4 Text supporting Vision Models 147
3.4.1 Introduction
“The biggest lesson that can be read from 70 years of AI research
is that general methods that leverage computation are ultimately
the most effective, and by a large margin. [. . . ] Most AI research has been conducted as if the computation available to the
agent were constant (in which case leveraging human knowledge
would be one of the only ways to improve performance) but,
over a slightly longer time than a typical research project, massively more computation inevitably becomes available. Seeking
an improvement that makes a difference in the shorter term, researchers seek to leverage their human knowledge of the domain,
but the only thing that matters in the long run is the leveraging
of computation. [. . . ] One thing that should be learned from the
bitter lesson is the great power of general purpose methods, of
methods that continue to scale with increased computation even
as the available computation becomes very great.”
— Sutton (2019)
This insight seems to directly inspire most model choices presented in this
chapter. Each network can be seen as an attempt of its creators to employ their
vast available resources on a large scale, with a particular focus on dataset
sizes. This mostly becomes feasible through the adaptation of recent findings
in natural language processing (NLP; see chapter 2.1) to computer vision
(CV). On the one hand, architectural concepts firstly popularized in NLP are
translated to CV (e.g., self-supervised learning or the Vision Transformer;
Dosovitskiy et al., 2020b) (see chapter 2.2). On the other hand, these powerful
new NLP models, mostly Transformers (Vaswani et al., 2017b), support bigger
models from the inside as text encoding building blocks; hence the name of
this chapter. Throughout this chapter, we will introduce recent relevant CV
models CLIP (Radford et al., 2021a), ALIGN (Jia et al., 2021b) and Florence
(Yuan et al., 2021) and discuss their underlying core concepts. The strong
performances confirm the potential, hinted at by the impressive GPT-3 (Brown
et al., 2020), of improving CV and increasing scale with the help of NLP.
148 3 Multimodal architectures
3.4.2 Concepts
3.4.2.1 Web-scale data
A core problem that troubles researchers is the lack of robustness of previous
state-of-the-art CV models to distribution shifts. I.e., when a model with good
performance on its original dataset fails to generalize (transfer its knowledge)
to new, more or less similar datasets. E.g., Radford et al. (2021a) report
that a ResNet101 which they trained on ImageNet to an accuracy of 76.2%
maintains only an accuracy of 32.6% on ObjectNet. This suggests that the
model perhaps did not learn high quality latent representations, but instead
overfit to the dataset-specific data-generating distribution. A common way
to tackle this would be to try out various changes on the architecture and
the training algorithm of the network. But this kind of adaptation, inscribing
expert knowledge into the model, seems to repeat the mistake pointed out by
Sutton (2019); “micromanaging” a model is likely to thwart future scaling.
The researchers of CLIP, ALIGN and Florence follow a different approach,
based on scale. They try to increase sample size as much as possible and work
with tremendous numbers of training observations:
• 400 million (CLIP; Radford et al., 2021a)
• 900 million (Florence; Yuan et al., 2021)
• 1.8 billion (ALIGN; Jia et al., 2021b)
These large-scale dataset are generated using the vast amount of image-text
pairs produced by and readily available on the internet. Thus, error prone,
cost and labor intensive (difficult to scale), manual labeling is avoided. Unfortunately, the models trained on web data also become vulnerable to their
downsides. Because of their extremely noisy nature, still some form of preprocessing is needed, e.g., filtering for English language, excluding graphic
content and, optionally, removing images with non-informative alt-texts. This
makes some degree of dataset curation, and therefore arbitrary choices, necessary. Likewise, the social biases inherent to the internet are reproduced and
furthermore, while this approach improves data efficiency to some degree (see
next subsection 3.4.2.2), the poor performance of deep learning in this area
is not substantially enhanced and mainly just compensated for with a super
scalable source of supervision (Radford et al., 2021a).
3.4.2.2 Contrastive objective
This source of supervision is the information contained in the co-occurrence
of the image with its alt-text. It is accessed through natural language supervision. The architectures jointly train two sub-networks for image and text
encoding, respectively. During this, the vector encodings are aligned in the
latent representation space through minimizing a variant of the contrastive
loss function (3.10) (Tian et al., 2020). Half of the first image-text pair loss
3.4 Text supporting Vision Models 149
`
Vimg,Vtxt
1 = − E
{v
1
img,v1
txt,...,vN
txt}
log
hθ({v
1
img, v1
txt})
hθ({v
1
img, v1
txt}) + PN
k=2 hθ({v
1
img, vk
txt})
!
,
(3.10)
where v
1
img and v
1
txt are vector encodings (latent representations) of image 1 and
text 1 and hθ(·) is a similarity measure. In order to guarantee symmetry, the
total loss is formed by the sum of `
Vimg,Vtxt
1
and `
Vtxt,Vimg
1
, where the pairwise
similarities of one text and every image is calculated instead of the other way
around.
Figure 3.52 visualizes this. Initially all images and texts in the training data
are encoded by the responsible sub-network. Using the resulting encodings,
a similarity matrix with elements hθ({v
i
img, v
j
txt}) can be calculated. Loosely
speaking, the contrastive objective is to maximize elements on the diagonal
and minimize the others.
FIGURE 3.52: Visualization of a contrastive objective (Radford et al., 2021a).
After encoding the data, a similarity matrix for the images and texts is
computed. The aim is that the N true image-text pairs score high in terms of
similarity, while the N2 − N other possible combinations score low.
Contrastive learning can be contrasted with classical predictive learning. Figure
3.53 gives an interesting insight into the choice of space, where goodness of fit
is measured. The exemplary task is to color an image given its B/W version.
Approach (a) first encodes the B/W image and then decodes the interim latent
representation to fitting colors. The goodness of this fit is measured in the
output space, meaning the estimated colors are compared to the true colors.
150 3 Multimodal architectures
Conversely, approach (b) measures the loss in the representation space.6 A
reason for the good performance of contrastive learning could be that, while
common prediction losses (e.g., the L2 loss) penalize each prediction output
dimension independently, approach (b) implies measurement in the intertwined
representation space (Tian et al., 2020).
FIGURE 3.53: Predictive vs. contrastive learning: Predictive losses are
measured in the output space while contrastive losses are measured is in the
representation space, indicated by red dotted boxes (Tian et al., 2020).
But in the end, rather than theoretical considerations, the driving factor for
using this objective is data efficiency. As can be seen in figure 3.54, Radford
et al. (2021a) start their search for an adequate pre-trained model (more on
this in subsection 3.4.2.3) by experimenting with a Transformer-based language
model predicting the exact captions of an image. It turns out that this approach
trains three times slower, in terms of data efficiency, compared to a simpler
baseline of predicting a bag-of-words text encoding. Additionally, switching to
the contrastive objective of CLIP improves data efficiency by a factor of four.
Nonetheless, the switch to contrastive learning leads to some limitations.
Its rigidity demands certain extra steps and forfeits the high flexibility of
generative models. In particular, this means contrastive models similar to
CLIP are limited to choose from available options and cannot freely generate
texts or images. To extend the capabilities of those models additional network
building blocks are necessary.
6Note that contrastive learning easily works with other combinations of modalities than
text and image; here B/W and colors.
3.4 Text supporting Vision Models 151
FIGURE 3.54: Data efficiency of contrastive objective. Development of
zero-shot accuracy (see next subsection 3.4.2.3) on ImageNet with increasing
number of instances of training data processed by the models. The contrastive
objective reaches similar accuracy scores as the generative approach with only
a seventh of the amount of data (Radford et al., 2021a).
3.4.2.3 Foundation models and zero-shooting
The first models which are considered foundation models today began to
appear in NLP. The term, later coined by Bommasani et al. (2021), refers
to models that are noteworthy due to their large scale and ability to adapt
to a wide variety of downstream tasks. An early example is BERT (Devlin
et al., 2018b). Often, foundation models have an unfinished touch to them
and the true scope of their capabilities cannot be sketched out clearly. This
generally is the case because the desired abilities of neural networks are not
designed for explicitly, but rather emerge during their implementation and
usage on downstream tasks. Bommasani et al. (2021) cite GPT-3’s ability
to perform certain types of new tasks solely by confronting it with the right
natural language prompt. E.g., it is possible to get GPT-3 to summarize a
paragraph by appending “TL;DR” (too long, didn’t read) to the prompt, which
is a common pattern on the internet to signal a following summery. This is
referred to as “in-context learning” (Brown et al., 2020). It is apparent that
one can make up plenty of unexpected ways to employ these models and it
remains unknown whether there is a further way no one thought of yet. This
means possibly saving computational and data collection costs down the line,
which ineptly is true for malicious use cases, e.g., surveillance, too.
Foundation models build on the concept of transfer-learning, i.e., pre-training
a model on a feasible source task and applying it to the desired downstream
task. In the context of this chapter this means pre-training on web-scale
data (see subsection 3.4.2.1) and evaluating performance on various common
classification datasets. E.g., Radford et al. (2021a) name the SVHN dataset
152 3 Multimodal architectures
as a proxy for the task “street number transcription” with the caveat “on
the distribution of Google Street View photos”, but they remark that a lot
of datasets have no obvious, specific task associated, e.g., CIFAR-10. They
use these kind of datasets for measuring the “robustness to distribution shift
and domain generation” of their model, which still is a topic of great interest
as mentioned in subsection 3.4.2.1. When there is no further fine-tuning on
the downstream task, i.e., no resuming of training on the new target dataset,
this is referred to as zero-shooting. Zero-shooting has the clear advantage of
evaluating performance more unbiased, as processes like overfitting to the
data-generating distribution will not distort results.
Figure 3.55 shows how contrastive models perform zero-shot transfer. In the
case of image classification all available classes are encoded by the language
model. Afterwards, the CV sub-network computes the encoding of the image
to be classified and all pair-wise similarity scores are returned. The pair with
the best score can be retrieved as the decision. Image retrieval works the other
way around: After an initial encoding of all images, the ones most similar to
the encoded natural language text prompt in the representation space can be
returned.
FIGURE 3.55: Visualization of zero-shooting (Radford et al., 2021a).
3.4 Text supporting Vision Models 153
3.4.3 Architectures
3.4.3.1 CLIP
The first of the large scale contrastive CV models that were published is CLIP,
short for Contrastive Language-Image Pre-training (Radford et al., 2021a).
The components of its name are explained in previous subsections 3.4.2.2,
3.4.2.1 and 3.4.2.3 and are the crucial concepts of ALIGN and Florence as well.
CLIP is a product of OpenAI, but its code is freely available and the different
versions can be accessed as python modules. The dataset used for training is
not released though.
A lot of preliminary work stems from Zhang et al. (2020b), who introduced contrastive representation learning using image-text pairs. Their implementation
of the contrastive loss function (3.10) follows
`
Vimg,Vtxt
1 = − log
exp(hv
1
img, v1
txti/τ )
PN
k=1 exp(hv
1
img, vk
txti/τ )
, (3.11)
where hv
1
img, v1
txti represents the cosine similarity, i.e., v
1>
imgv
1
txt/(kv
1
imgkkv
1
txtk),
and τ ∈ R
+ is a temperature parameter, which is directly learned during
training (Zhang et al., 2020b). CLIP adopts this. `
Vtxt,Vimg
1
, the counterpart to
`
Vimg,Vtxt
1
for the total loss, is function (3.11) with switched arguments. This
can be viewed as a symmetric cross entropy loss over the cosine similarity of
the embeddings (Radford et al., 2021a).
Architecture
The text encoder for CLIP (see figure 3.53) is a modified Transformer (Vaswani
et al., 2017b), which was also used for GPT-2 (Radford et al., 2019b). For the
image encoder multiple sub-networks are evaluated:
• ResNets: ResNet-50, ResNet-101
• ResNets which follow EfficientNet-style model scaling: RN50x4, RN50x16,
RN50x64
• Vision Transformers: ViT-B/32, ViT-B/16, ViT-L/14
The best performing sub-network was the ViT-L/14. In turn, they trained
it for an additional epoch with higher resolution images (336px), denoting
this version ViT-L/14@336px. If not indicated otherwise, the performances of
this version of CLIP are displayed. The EfficientNet-style ResNets use x4, x16
and x64 of the compute of a ResNet-50 and the largest model (the RN50x64)
trained for 18 days on 592 V100 GPUs, while the ViT-L/14 only took 12 days
on 256 GPUs. The high parallelization capabilities of Transformers seem to
pay off.
When explaining zero-shooting initially (see subsection 3.4.2.3), a text processing step was skipped. As can be seen in figure 3.55, there is an additional
154 3 Multimodal architectures
operation before the labels are fed into the text encoder. In order to help the
model understand the context of the words, the class labels are embedded in
a sentence, e.g., “A photo of a {label}.”. This increases the models zero-shot
accuracy on ImageNet by 1.3 percentage points (pp). When ensembling 80
different context prompts7 Radford et al. (2021a) improve ImageNet accuracy
by an additional 3.5pp, which adds up to a total of nearly 5pp. The average
performance gain across 36 datasets is reported to be 5pp. It is similarly possible to directly communicate visual concepts like “picture”, “macro”, “drawing”
or even “dog” to the model.
Robustness
Figure 3.56 illustrates the performance of CLIP and a ResNet101, whose
training on ImageNet was stopped at the point it reached the same accuracy
as zero-shot CLIP. It can be deduced that the methods studied in the paper
of Radford et al. (2021a) constitute an important step towards closing the
robustness gap mentioned earlier (see subsection 3.4.2.1). While the performance of the ResNet101 deteriorates with datasets generated from more and
more different data distributions compared to ImageNet, CLIP remains fairly
accurate. Note that these findings have to be taken with a grain of salt. Because
OpenAI does not grant public access to their training data, independent parties
cannot investigate these claims on their own. E.g., it has to be relied on the
conclusions of their overlap analysis to rule out that CLIP has not seen biasing
amounts of future test data during training.
FIGURE 3.56: Robustness of zero-shot CLIP to distribution shifts (Radford
et al., 2021a).
7Prompts like: “A photo of a big {label}.”, “A photo of a small {label}.” (Radford et al.,
2021a)
3.4 Text supporting Vision Models 155
CLIP as a building block
Shen et al. (2021) study how the performance of Vision-and-Language (V&L)
models improves, when the visual encoder is switched to CLIP’s strong image
encoder. They discover that in this field of CV the ViT-B scores significantly
worse than the ResNets. E.g., tests on image captioning reveal that the V&L
model using ViT-B often performs only half as strong as the version using the
RN50x4 (the largest network used in this study). This is possibly due to the
pooling strategies of ViT-B, which result in a lack of visual localization abilities.
Shen et al. (2021) test their hypothesis and generate, e.g., figure 3.57 which
depicts Grad-CAM Visualizations for a V&L model with a ViT-B backbone
and a ResNet-50 backbone and the question “What color is the woman’s shirt
on the left?”. The red area indicates relevant pixels and appears much more
focused for CLIP-Res50 than for CLIP-ViT-B.
FIGURE 3.57: Grad-CAM Visualizations for the prompt “What color is the
woman’s shirt on the left?”.
3.4.3.2 ALIGN
The approach of Jia et al. (2021b) is largely similar to CLIP. They reiterate
the necessity of large-scale vision datasets, but assert that even CLIP’s data
collection process still involves a non-trivial amount of data curation. They
propose that the amount of additional observations obtained through minimizing the amount of filtering makes up for the increased noise. Following this
rationale, they create a training dataset with 1.8 billion image-text pairs. The
corresponding model is named ALIGN, short for “A Large-scale ImaGe and
Noisy-text embedding”, whose acronym hints at the contrastive loss, which
aligns vector encodings in the representation space (see subsection 3.4.2.2).
Architecture
ALIGN follows the dual encoder architecture employed by Zhang et al. (2020b)
and Radford et al. (2021a), but uses a part of BERT-Large as the text and
EfficientNet-L2 as the image encoder, which they jointly train from scratch.
The model has around 800 million parameters (Alford, 2021). Subsection 3.4.4
goes into more detail about the performance of ALIGN and compares all three
models discussed in this subsection.
156 3 Multimodal architectures
Connecting image and text representations
The contrastive loss function aligns the latent representations of the different
modalities. In other words, the explicit objective is that similar vector encodings implicate similar inputs. This means arithmetic operations like the ones
mentioned in chapter 2.1 are not only meaningful on encodings belonging to
the same modality, but to different modalities. E.g., one can add up the image
encoding of a picture of the Eiffel tower and the text encoding of the word
“snow” and retrieve pictures with high cosine similarity as a result, see figure
3.58 for an illustration.
FIGURE 3.58: Multimodal image retrieval via arithmetic operations on
word and image embeddings.
3.4.3.3 Florence
While in principle the approach of Yuan et al. (2021) does not largely differ
from the others, the focus of this paper is more about creating a true foundation model. In order to achieve this, they propose a map of possible vision
applications which the try to cover via extending the core model with modules.
As figure 3.59 depicts, they want to advance into the dimensions of fine-grained
object detection, dynamic action recognition and true multimodal tasks. Due
to their big ambitions, they name their model Florence after “the birthplace
of Renaissance” (Yuan et al., 2021).
Architecture
As the two encoders for the pre-trained core they use a hierarchical Vision
Transformer (CoSwin Transformer) for images and a Transformer similar to
3.4 Text supporting Vision Models 157
FIGURE 3.59: Florence’ approach to foundation models: A general purpose
vision system for all tasks.
CLIP’s for text. Their 893 million parameters are also jointly trained from
scratch on 900 million image-text pairs. The alignment happens in the so called
image-label-description space which is encoded through a special version of the
contrastive loss function which regards all image-text pairs with the same label
as positive instances. Figure 3.60 depicts their version of figure 3.52 where one
can schematically see how they flexibly add modules to the pre-trained core in
order to adapt to various downstream tasks.
FIGURE 3.60: Modular architecture of Florence.
3.4.4 Performance comparison
Throughout the papers of Radford et al. (2021a), Jia et al. (2021b) and Yuan
et al. (2021) we were able to collect three tables with reported performance
measures to compare these approaches.
158 3 Multimodal architectures
Table 3.61 summarizes the zero-shot accuracies on four different ImageNet
variants. Unfortunately Yuan et al. (2021) only stated their performance on
the original ImageNet, where they beat CLIP and ALIGN by a margin of
7.3pp. The results on the other three ImageNet pendants are mixed and there
is no clear winner between CLIP and ALIGN.
FIGURE 3.61: Top-1 Accuracy of zero-shot transfer of models to image
classification on ImageNet and its variants.
Table 3.62 concerns zero-shot image retrieval on the Flickr30K and the
MSCOCO dataset (see chapter 2.3). Even though there are not many major
score differences, there is a clear ranking with CLIP on third, ALIGN on
second and Florence on the first place.
FIGURE 3.62: Zero-shot image and text retrieval (Yuan et al., 2021).
The most comprehensive comparison is shown in table 3.63. It depicts the
accuracy of zero-shot CLIP and Florence on various datasets as well as the
scores of all three models fine tuned to the respective datasets. Florence beats
CLIP in nearly all evaluations, for the zero-shot setting as well as for fine tuned
performance. Jia et al. (2021b) only report on four of these twelve datasets,
where they win half of the time.
Summing up, ALIGN achieves its goal of replicating CLIP’s impressive performance while dramatically reducing the required data curation effort and
Florence has the overall top performance. This could be attributed to its
custom loss, maybe to Yuan et al. (2021) striking the best balance between
sample size and data curation or to Florence having the best sub-networks; or
a combination of all three.
Once again note that none of the training datasets were made publicly available.
It cannot be guaranteed that all benchmarks were evaluated on unseen datasets.
3.5 Models for both modalities 159
FIGURE 3.63: Top-1 Accuracy of CLIP, Florence and ALIGN on various
datasets.
3.4.5 Resources
One can access the pre-trained CLIP models on Github and they even found
their way into simple command line tools already. For example there is a CLI
named rclip, which can be used for personal image retrieval, wrapping the
ViT-B/32 CLIP architecture. On a (mid-range, regular) laptop, we were able to
find seemingly good matches for search terms which we tried out inside a folder
containing about 100 different pictures. After an initial caching one request
took about ten seconds. Furthermore CLIP continues to be used inside new
models, e.g., DALL·E 2, where it is used for the image embedding (Ramesh
et al., 2022b). Also, there is a crowd-sourcing effort to replicate CLIP’s training
dataset called LAION-400M (Schuhmann, 2022). To validate the image-text
pairs collected for this, their cosine similarity is computed using CLIP and
instances with a value too low are discarded. To our knowledge no resources
were open-sourced as part of the other two papers ALIGN and FLORENCE.
3.5 Models for both modalities
Author: Steffen Jauch-Walser
Supervisor: Daniel Schalk
Data is naturally at the heart of every data scientific issue. While there have
been many advances made in machine learning in recent years, many promising
research areas remain, as do a multitude of problems associated with them.
One such promising area are multi-modal machine learning models. Combining
different input data is a key aspect towards making models more sophisticated.
When thinking about teaching robots specific tasks, detecting hateful memes
or deep fakes, it is apparent that only through the combination of multiple
modalities, success might be achieved. Context is key.
However, learning context requires increasingly complex models. While early
160 3 Multimodal architectures
machine learning models built their success upon the possibility to analyze
the big pool of available, often unstructured data, modern machine learning
models are so demanding that there is often not enough data or training time
available. Obtaining data is a major issue for multi-modal machine learning.
Since labelling data in vast amounts is prohibitively expensive, larger models
have to come up with specific strategies to move forward such as self-supervised
training or automatically scraped web datasets. Nevertheless, when models
become so large that billions of parameters have to be learned, even scraping the
whole web starts to show its limits. Another natural issue is the transformation
of different types of data into usable model inputs.
There is no shortage of different single modality machine learning models. On
the contrary, when every new hyperparameter configuration might be seen
a new model, it becomes hard to keep track. More importantly, it is often
not clear how a model from one area transfers to another. Did we learn some
modality specific bias or a general principle? Consolidating different models
into a unifying framework is a key prospect of multimodal machine learning.
While the grand dream of a single unifying model might be out of reach,
consolidating different areas is well in sight. In the following, we will have a
look at the challenges and prospects of multimodal machine learning against
the background of visual language models. Visual Language Models are models
which can deal with both language and images as input data. Specifically, we will
have a closer look at three different models: Data2vec, VilBert and Flamingo.
Data2vec is an unsupervised model that can handle different modalities, but
not their interaction, using a single unifying training framework. VilBert is an
early visual-language model that can handle interactions between images and
text through its innovative concept of cross-attention. Flamingo is a recent
few shot visual language model that features large expressive text capabilities
through the use of a large language model. With 80B parameters, it particularly
highlights how to leverage the communication between frozen models when
further scaling up the model size.
An overview across the popularity of current research fields in visual language
modelling is provided in figure 3.64. A detailed list of trends for each of those
fields can be found in Uppal et al. (2022). Most research is done in the areas
of visual question answering (VQA) and visual captioning (VC), but also for
example visual commonsense reasoning (VCR), vision-language navigation
(VLN) or multimodal affective computing (MAC). MAC uses images and
text to infer sentiment, for example through facial expressions. VCR as an
extension of VQA is particularly interesting in the realm of making models more
interpretable. After all, we would like to know why machine learning models
do what they do. Finally, VLN has many promising practical applications in
the field of robotics, particularly the interaction of humans and robots.
3.5 Models for both modalities 161
FIGURE 3.64: Uppal et al. (2022): VisLang Paper Trends (previous 2 years)
3.5.1 Data2vec
With data2vec (Baevski et al., 2022), data scientists at Meta, formerly Facebook, developed an architecture that addresses some of the mentioned issues
while highlighting the importance of sophisticated training schemes. Their
algorithmic structure is able to work with either text, image or speech data. On
top of that, the model is self-supervised based on a teacher-student relationship
which reduces the need for human labelling. It is not a universal model in the
sense that it works with any input, nor is it even a general model in the sense
that the algorithm is exactly the same for each modality. However, the overall
model structure remains the same for either text, speech or image input data,
while only the specific encoding, normalization and masking strategies are
modality-specific. In that regard, it is a step towards a more general way of
dealing with different modalities and it is very effective at doing so given the
benchmark results on typical data sets. Particularly noteworthy is also the way
they implement the self-supervised learning. Data2vec predicts contextualized
and continuous representations rather than typically used discrete tokens such
as sub-words. Working with latent representations of the input space has two
advantages: not only is the number of prediction targets not a-priori limited,
but they are also richer in information.
Figure 3.65 depicts the general model architecture. The two main components
are a teacher and a student model which only differ in one aspect, the weights
of the teacher model are an exponentially decaying average of the student’s
weights. The purpose of the teacher model is to create training targets for the
student model. In a first step, a modality is chosen and inputs are encoded
according to the specific encoding scheme for that modality. A masked version
162 3 Multimodal architectures
FIGURE 3.65: Baevski et al. (2022): Data2vec Architecture - a teacher
model creates contextualized latent targets on the basis of its top K layers
(blue) as prediction task to train the student model
is given to the student model, but notably, the teacher model has access to
an unmasked, complete view of the input data. Hence, the resulting training
targets will be fully contextualized using a self-attention mechanism over the
whole input data. The training targets are based on the top K layers of the
teacher model depicted in blue in Figure 3.65. More specifically, denoted by
yt, the training target at time t and by a
l
t
the outputs of the l-th block, then
yt =
1
K
PL
l=L−K+1 aˆ
l
t
, i.e. the training targets are the average of the outputs of
the top K layers of the teacher network after a normalization has been applied.
Normalization helps to stabilize the training process and prevent model collapse
which can be an issue with models that learn their own representation.
From the authors point of view, working with a latent representation of
the actual learner as training target is a simplification of many commonly
used modality-specific designs despite the caveat that this paper still uses
modality-specific encoding strategies. Compared to other models, there is no
cross-modality training. The specific loss function used to regress the targets
is a smooth L1 loss.
L(yt, ft(x)) = ((yt−ft(x))2
β
if |(yt − ft(x))| ≤ β
|(yt − ft(x)| − β
2
otherwise
Using a smooth L1 loss has the advantage of being continuous, yet sensitive to
outliers, however the β parameter needs tuning. As far as the general model
architecture is concerned, the underlying architecture is a standard transformer
architecture (Vaswani et al., 2017b).
How does the modality specific input handling work?
In many ways, in this work the authors combine the strategies developed
in multiple previous works and add a unifying framework on top of it. For
images, the typical Vision Transformer (ViT) strategy (3.66) to transform
images with a size of 224x224 pixels into 16x16 pixel patches is employed.
Every patch is then linearly transformed into a sequence of 196 flattened
3.5 Models for both modalities 163
representations including a learn-able positional encoding that serve as input
to the vision transformer. A classification token is used to produce the final
categorization. The contextualization is produced in the multi-head attention
blocks as explained in earlier chapters. In short, multi-head attention first
projects the keys, queries and values with learned linear projections which are
then evaluated in parallel to create more expressive attention maps. Attention
itself is calculated as scaled dot-product-attention using a softmax over the
scaled product of keys, queries and values (Vaswani et al., 2017b). As far as
the vision transformer itself is concerned, datav2vec tests two different model
sizes, a base model size of 12 and a large model of 24 transformer blocks. The
masking strategy for images follows the Bert pre-training approach of image
transformers, BEiT, proposed by Bao et al. (2021). In particular, multiple
adjacent blocks are being masked with random aspect ratio. The minimum
size of a masked block is 16 patches. In total, 60% of patches were masked
in the data2vec algorithm, which is an increase over the original 40% used
by BEiT. However, the authors note that they found increased masking to
be more accurate. The augmentation strategies are similar, as well. Resizing
crops, horizontal flipping and colour jittering were used. Naturally, the student
and teacher model are the given the same modified image. Finally, for image
data, the model is measured on a classification task. Hence, the authors use
a mean-pooling over all patches in the last transformer block and input that
into a softmax-normalized projection that conducts the classification, which is
again based on the BEiT model.
FIGURE 3.66: Dosovitskiy et al. (2021)
The natural language processing model is implemented with a PyTorch toolkit
named fairseq and based on the RoBERTa (Liu et al., 2019b) architecture
which redesigned the standard Bert model training procedure to make it more
164 3 Multimodal architectures
robust and effective. In particular, it increases hyperparameters such as the
learning rate and the batch size. It also removes the next sentence prediction
task to improve on the masked language modelling performance. In this case
they follow Sennrich et al. (2015b) and encode sub-words as 50k byte-pairs.
A separate embedding vector is learned for each type. For the masking, the
Bert masking is being used. 15% of the embedded tokens are replaced, thereof
80 percent are learned masks, 10% are unchanged and the remaining 10%
are replaced with random tokens in the vocabulary. Another strategy that
the authors also consider is the wave2vec masking strategy’ to mask four
consecutive tokens with a probability of 0.35 while only using learned tokens
(Baevski et al., 2020). As it turns out, the later strategy further improves the
results. The natural language processing model is evaluated on the General
Language Understanding Evaluation (GLUE) benchmark (Wang et al., 2018)
which includes for example includes NLP inference, sentence similarity and
sentiment analysis tasks.
The speech category is also implemented in fairseq. The feature encoder for
speech is based on the wave2vec framework and uses 16 kHz inputs. It is built
upon seven temporal convolutions intertwined with normalization layers and a
GELU activation function such that the output of the encoder is 50 kHz.
As far as the results are concerend, data2vec achieved state-of-the-art performance in vision and language tasks among similar self-supervised models.
FIGURE 3.67: Baevski et al. (2022): data2vec performance (vision)
Figure 3.67 shows the model’s performance in computer vision. Pre-trained
and fine-tuned simply on the data of the well known ImageNet-1K dataset,
data2vec was evaluated using top1-accuracy, the standard notion of accuracy,
on the task to predict single labels for images. The base model ViT-B comprises
86M parameters and ViT-L 307M parameters. The results show that predicting
contextualized latent representations in a masked prediction setup can work
well as model training compared to classical local methods such as predicting
visual tokens. MoCov3 (Chen et al., 2021) is a self-supervised model trained
3.5 Models for both modalities 165
on a contrastive loss. The most similar model is DINO (Caron et al., 2021),
which also uses a self-distillation setup to predict teacher outputs using a crossentropy loss. However, their prediction target was the final layer rather than
averaged layers while using differing images for teacher and student network.
The well performing MAE model (He et al., 2022) is a masked autoencoder
which is trained on reconstructing masked pixels using an asymmetric encoderdecoder architecture. In contrast, MaskFeat (Wei et al., 2022) uses masked
feature prediction. Notably, data2vec outperforms all of them although trained
for the same amount or less. Particularly, MAE and MaskFeat use 1600 epochs
rather than 800 like data2vec.
FIGURE 3.68: (res:data2vecresults2)
(res:data2vecresults2) Baevski et al. (2022): data2vec results (language)
Figure 3.68 shows the performance in the language domain. For the language
domain, the model is evaluated on the GLUE benchmark (Wang et al., 2018).
The model is pre-trained and fine-tuned separately on the labelled data from
each task. Accuracy is reported as the average across 5 tuning cycles. While
data2vec achieves a higher average performance than the baseline model,
there are tasks where the baseline model prevails. A large portion of the
performance difference seems to be driven by the CoLA task. The Corpus of
Linguistic Acceptability (CoLA) consists of 10657 sentences from 23 linguistics
publications and the task is to judge whether they are grammatically correct.
Hence, it is distinctly different from the other tasks. The Stanford Sentiment
Treebank (SST) analyzes sentiment in language through movie reviews. The
Multi-Genre Natural Language Inference (MultiNLI) corpus contains sentence
166 3 Multimodal architectures
pairs and focusses on textual entailment across genres. Similar tasks are used
in the Recognizing Textual Entailment (RTE) dataset which focuses on text
from news and Wikipedia. The QNLI (Question-answering NLI) dataset is
a Natural Language Inference dataset that contains answers from Wikipedia
to corresponding questions posed by an annotator. The task for the model is
to find out whether the sentence contains the answer to the question. QQP
stands for Quora Question Pairs, which analyzes paraphrases. Finally, the
Microsoft Research Paraphrase Corpus (MRPC) also consists of sentence pairs
from newswires which may or may not be paraphrases of each other.
As a suitable baseline model, the authors retrain RoBERTa in the respective
setup. On top of the heterogeneous performance across language tasks, the
evaluation also clearly shows that averaging over multiple layers to create
prediction targets improves performance across all three domains. The effects
seem to be most pronounced on NLP tasks whereas CV does not benefit from
averaging more than three layers. In the speech domain, six layers seems to
be enough to reach peak performance. In any case, performance loss while
following the strategy to simply average the maximum amount of layers, rather
than fine-tuning K, seems small enough to be potentially acceptable.
To sum it up, data2vec is a self-supervised model that can work with either text,
speech or image data, but not across modalities. It aims at unifying the learning
framework through a teacher-student-setup that allows for contextualized latent
target prediction. The teacher model is based on a complete view of the input
data, which introduces contextualization, while the student model only sees a
masked version of the input. Compared to previous work, the authors average
the top K layers rather than only the final layer of the model, which has a
notable effect as shown in 3.68. As there are different layers in the transformer
network, the authors also investigate which layers work best for prediction.
They conclude that the output of the feedforward layer works best. Built
on a transformer architecture, self-attention is the main driver that creates
contextualized targets in the teacher model and hence performance. The
authors also show that contextualization through the teacher model works
best with the complete view of the input rather than a partial view. On top of
not being able to work across modalities, one drawback is that the model’s
structure still uses modality specific encoding and masking schemes. In that
regard, the perceiver architecture (Jaegle et al., 2021a) for example used in
the Flamingo model is a complementary approach worth exploring. An earlier
model that works across modalities is VilBert.
3.5.2 Vision-and-Language Bert (VilBert)
As seen in the previous section, data2vec can handle text, image or speech as
input data. However, it cannot do so at the same time. The model’s focus is on
unifying the training approach rather than working across modalities. However,
when we think about multimodal models, we usually think of working with
3.5 Models for both modalities 167
different modalities at the same time. VilBert (Lu et al., 2019b) is a natural
extension of the iconic Bert architecture (Devlin et al., 2018c) to vision-andlanguage modelling. An immediate question is whether vision and language
inputs should be handled together in a single stream or in parallel. As we will
see, it turns out that encoding inputs in parallel and working with parallel
streams increases performance. At heart of that architecture is a co-attention
mechanism which enables information exchange between both modalities.
FIGURE 3.69: Lu et al. (2019b): VilBert’s Dual Stream Architecture: dashed
transformer modules can be repeated, co-attention modules allow sparse interaction between modalities.
Figure 3.69 shows the employed parallel stream architecture. Each modality
is handled separately and fed into two Bert-style transformer models. This
allows for both modalities to be handled according to their respective needs
while co-attention layers allow for communication between the streams. For the
language stream, the encoding uses the vocabulary plus a special classification
token (cls), a sentence separation token (sep) and a masking token (mask).
For the vision stream, image region features are extracted via a Faster R-CNN
(Ren et al., 2015) model which was pre-trained on the Visual Genome Dataset
(Krishna et al., 2016). Since image regions lack a natural ordering, its spatial
location has to be encoded, as well. VilBert achieves that through a five
dimensional vector that encapsulates the image coordinates and the fraction of
the covered image area. Through projection, the dimensions of the positional
encoding and visual features are matched and then summed. The image token
marks the beginning of such an image region sequence while representing the
whole image.
Through the dual stream architecture, the complexity of the model can be
adjusted separately for each modality. An alternative approach would have to
discretize the visual space via clustering and then use the resulting tokens in the
same way as text tokens. The drawbacks of that approach are the potential loss
of detail at the discretization stage and the loss of flexibility across modalities
as a result of the same processing. Finally, a single stream architecture can
interfere with the pre-training of the language models. The model will have
to be fine-tuned based on the created visual tokens. As those might be very
different from the text tokens, there is potential for the pre-trained language
model to be become ‘damaged’ in the process and lose capabilities - and idea
that is also central to the Flamingo model presented later on.
168 3 Multimodal architectures
FIGURE 3.70: Lu et al. (2019b): Cross-Attention in VilBert
The key innovation in the Vilbert paper (Lu et al., 2019b) is the use of
co-attention layers. In figure 3.70, the basic architecture is depicted. The
co-attention module computes query, key and value matrices in a standard
transformer attention fashion. However, it then feeds the keys and values from
each modality into the other modalities multi-head-attention block. As a result,
the visual attention will be conditioned on text whereas the language attention
will be image-conditioned. This communication between streams only occurs
at specific sections in the model, denoted by co-trm in figure 3.69. Notably, the
language stream features a lot more preprocessing before the first co-attention
layer than the image stream.
An interesting question to ask is what is actually learned in those attention
layers and how they correspond to human attention maps. (Sikarwar and
Kreiman, 2022) analyze the efficacy of co-attention layers for VQA tasks
in a VilBert network. Specifically, they compute the question conditioned
image attention scores and compare them to human attention maps created in
experiments. In those experiments, humans are tasked with unblurring specific
image regions to answer the same questions one would expect the machine
learning model to answer. Such human attention maps are collected in the
VQA-HAT dataset (Das et al., 2017). Rank correlation is used to compare
attention maps. Sikarwar and Kreiman (2022) find that in a 6 layer network
rank correlation plateaus at layer 4 and increases in the number of image
regions proposed while encoding the images. Perhaps more surprisingly, they
find a minimal influence of semantics on the generation of the attention maps.
Randomly shuffling words in a sentence when testing the model performance
barely changes the attention output, which suggests that keywords rather
than sentence structures drive the attention output. Note however that while
attention maps remained similar, the model’s actual performance on answering
the questions dropped notably by approximately 15% such that it seems clear
3.5 Models for both modalities 169
that coherent sentences are important for the overall VQA task, but not for the
attention creation process. What are the keyword that drive cross-attention
in VilBert? The evidence provided by the authors clearly shows that nouns
are the most influential parts-of-speech when considering attention maps. On
top of that, prepositions can sometimes help identify spatial relations. There
is also some support for the hypothesis that removing Wh-words such as
“who” and “where” can improve fine-grained attention maps in the final layer
which might be worth exploring further as preprocessing for deeper networks.
Another approach would be to search for ways to improve the way attention
maps are generated by finding ways to include more of the available sentence
information. Most notably, however, using object-based region proposals to
process images can lead to bottlenecks that can prevent the model from learning
sufficiently fine-grained attention maps as shown in figure 3.71. Overall, humans
are naturally good at VQA tasks. Hence, it is not surprising that attention
maps which correlate well with human attention maps also improve model
performance.
FIGURE 3.71: Sikarwar and Kreiman (2022): (Left to Right) Picture, Human
Attention, 36 Regions, 72 Regions, 108 Regions. Similarity between human
and model attention is measured using rank correlation.
Figure 3.71 shows that the number of region proposals fed into the model
after processing an image affects the ability of the model to produce adequate
attention maps. In this particular case the question “How many fingers is the
girl in the black shirt holding up?” was correctly answered by humans, as
well as a VilBert model using 72 or 108 region proposals. It was answered
incorrectly when using only 36 region proposals. Note however that in either
case, the machine learning model captured the face of the wrong girl. The
model using 72 regions also identified the wrong hand despite answering the
question correctly. While the 108 region model identifies the correct hand
holding up the fingers, it does not seem to prioritize it over the other identified
hands in the picture. Hence, the attention maps are sufficiently different from
the human attention map which highlights the need to look closer not only
at how models are performing, but also into how their performance has been
achieved.
As far as the model training is concerned, VilBert is pre-trained and fine-tuned.
170 3 Multimodal architectures
The pre-training tasks comprise masked-multi-modal modelling and multimodal alignment prediction performed on the Conceptual Captions dataset.
That dataset contains about 3,1 million usable aligned image-caption pairs,
which have been automatically scraped from web images. For the alignment
task, the authors create unaligned images by randomly mismatching captions
and images. For the masking task, 15% of the both the visual and language
tokens are masked. The task is to reconstruct the mask from the remaining
input in a classical Bert fashion. While the text masks are directly regressed
like in Bert, the model predicts distributions over semantic classes for the
image regions. This is achieved through minimizing the KL divergence, a
measure for the similarity of distributions, between the output distribution of
the pre-trained model used in feature extraction and the VilBert predictions.
The performance results are depicted in figure 3.72.
FIGURE 3.72: Lu et al. (2019b): VilBert Performance
As mentioned before, the dual stream architecture outperforms the single
stream architecture. Furthermore, pre-training considerably boosts performance, as does fine-tuning. Interestingly, the authors also study the effect
of the size of the dataset and effect of the architecture depth. Performance
increases monotonically with dataset size, suggesting that performance can
be further improved with more data. The results on the optimal layer depth
are task dependent. VQA and Image Retrieval reach peak performance at 6
layers, where a layer denotes a repeatable block as depicted in figure 3.69. Zero
Shot Image retrieval greatly benefits from even deeper depth. However, the
VCR and RefCOCO+ tasks seemingly benefit from shallower models. The
VQA task is based on the VQA 2.0 dataset. Each image must be matched
to one of ten answers. Hence, the VQA task is not open-ended, but treated
like a classification task. To achieve that, the model is amended by two MLP
layers which use the element-wise product of the model-generated img and
cls tokens. The VCR task is also posed as a multiple choice problem with
images from movie scenes. To fine-tune for the task, questions and answers are
concatenated into four different text input and given as model input together
3.5 Models for both modalities 171
with the image. In the end, four scores are generated accordingly and selected
through softmax. The RefCoCO+ task is a grounding task. An image region
has to be selected according to a natural language reference. Caption-Based
Image Retrieval requires the model to find an image that corresponds to a
selected caption. The dataset used is the Flickr30k dataset which contains 30
000 pictures with five captions that are of higher quality than the automatically
generated captions from web data.
3.5.3 Flamingo
The VilBert model showed one way how to actually combine visual and language
inputs. In contrast, data2vec showed how to design an unsupervised model and
how influential the actual training process as well as contextualization can be.
A natural question to ask is then is whether we can build a truly multimodal
architecture like VilBert that is self-supervised like data2vec or at little taskspecific training and how to optimized its training procedure. In particular,
both VilBert and data2vec were tested on multiple tasks, but each task needs
slight re-adjustments to the model as well as additional fine-tuning. Ideally,
a multimodal architecture would not only be efficient in its initial training,
but also easily adaptable to different tasks. Finding ways to not only work
with different input modalities, but also with different task is crucial towards
building a more general AI. A promising approach in that direction is few
shot learning. The following section presents Flamingo (Alayrac et al., 2022),
a few shot multimodal architecture developed by Google which comprises key
innovations such as handling arbitrarily interleaved vislang sequences as inputs,
as well as ways to effectively combine pre-trained vision-only and language-only
models. As such, it is a visually conditioned autoregressive text generation
model.
Figure 3.73 demonstrates Flamingos capabilities. It can function as chat bot,
describe pictures, work with image sequences (videos) and in doing so, simply
needs a few prompts.
At the heart of the model is a large language model, Chinchilla (Hoffmann
et al., 2022), with 70B parameters. Large language models such as GPT-3
(Brown et al., 2020), as their name suggests, can be trained on a large amount
of text data which gives them impressive text generative capabilities. However,
multimodal generative modelling presents some specific challenges not present
in language-only modelling. First of all, training large language models is
expensive. Hence, it is paramount to work with a pre-trained version, but
trying to teach a large language model the means to work with visual inputs,
as well, has the potential to deteriorate or destabilize the pre-trained model.
Second, large language models can suffer from memory constraints that are
potentially severely aggravated by simply adding high-dimensional visual data
into an input sequence. Third, good generalist capabilities typically require a
huge amount of heterogeneous training data. There might not exist enough
172 3 Multimodal architectures
FIGURE 3.73: Alayrac et al. (2022): Flamingo Prompt-Output-Examples
labelled image-caption-pair data to successfully accomplish training a capable
few shot learning model in the vision-and-language domain. To train Flamingo,
the authors solve these challenges by foremost exploring ways to generate
their own web-scraped multimodal data set similar to existing ones in the
language-only domain. Furthermore, they use a perceiver architecture (Jaegle
et al., 2021a) that resamples inputs into a fixed amount of visual tokens. Finally,
the self-attention layers of the language model are kept frozen during training
while cross-attention layers are interleaved. A gating mechanism ensures that
those new cross-attention layers do not interfere at model initialization, thereby
improving stability and final performance.
Figure 3.74 shows the fundamental architecture of Flamingo. A pre-trained
vision model as well as a pre-trained language model are frozen. Together
they built the cornerstones of the model. The vision model is pre-trained
using a contrastive text-image approach. Its role is to extract features such
as colour, shape, nature and the position of objects - typical semantic spatial
features that one would use in querying. The language model is an existing
pre-trained language model. On top of those frozen parts, the authors add a
perceiver-resampler and gated cross-attention layers as learnable architectures.
The perceiver-resampler turns the outputs of the vision model into a fix set of
visual tokens. Those visual tokens are then used to create cross-attention layers
which are interleaved into the frozen language model. As a result, Flamingo
3.5 Models for both modalities 173
FIGURE 3.74: Alayrac et al. (2022): Flamingo Model Structure
can model the likelihood of some text y interleaved with a sequence of images
or videos x as
p(y|x) = Y
L
l=1
p(yl
|y