Lecture Note: Multimodal Transformer - Part 2

11-777 Multimodal Machine Learning CMU Fall 2023
Instructor: Dr. Louis-Philippe Morency | Co-lecturer: Dr. Paul Pu Liang
Author: Yi-Jing Sie

Overview

Transformers were originally built for language, but their self-attention mechanism generalizes well beyond text. The multimodal Transformers discussed in the previous post remains its Transformer architecture when processing multimodal data, such as texts and images, where image region representations are typically generated through the following methods:

  • Extracting visual features (pooled ROI features) for detected objects from a pre-trained region-based object detection network such as Faster R-CNN.
  • Employing The Facet library from iMotions to extract visual
    features.

This post walks through how the Transformer Encoder has been adapted to process images directly. It starts with the Vision Transformers (ViT), the breakthrough model that treats an image as a sequence of patches and learns visual representations through a Transformer encoder with minimal modifications. It then extends to Vision-Language Transformers such as ViLT, ALBEF, and VLC, which use ViT to encode images into visual tokens and fuse them with word tokens within a shared Transformer architecture. Finally, it covers Video Transformers such as VideoBERT and ActBERT, which directly process sequences of frames rather than ViT-based image patches.

From Convolutions to Self-Attention

Convolutions and self-attention share one strength: both can be computed in parallel across positions, unlike recurrent models. But they trade off different weaknesses. A convolution uses a small, static kernel, so capturing long-range dependencies requires stacking many layers. Self-attention instead lets every position dynamically weight every other position in a single layer, which gives it long-range context immediately, but it has no inductive bias toward locality the way a convolutional kernel does.

The inductive biases of locality and weight sharing in CNNs assume that useful visual features are local and translation invariant, allowing the same/fixed convolutional filters to be applied across the entire image.

From Convolutions to Self-Attention

Self-attention can be formulated as a form of convolution. For each target pixel, its query is compared against the keys of its neighboring pixels to see how well they match, and the resulting softmax attention weights act as dynamic convolution kernel weights, combining the corresponding values of its neighboring pixels into a contextualized output.

However, without extra information, attention has no sense of where each neighbor sits relative to the query. The standard fix is a 2D relative position embedding that gets added directly into the computation, so attention scores reflect both content similarity and spatial offset.

Vision Transformer (ViT)

Vision Transformer (ViT) removes standard convolutions entirely and instead relies on self-attention as dynamic convolution kernels to contextualize each pixel with all the other pixels dynamically. It first splits an image into fixed-size patches (e.g., 16×16). Each patch is flattened and linearly projected into an embedding vector, to which a learnable position embedding is added. Similar to BERT’s [class] token, a learnable [class] token is prepended to the sequence, and the whole sequence is then processed by a standard Transformer encoder. Finally, the output representation of the [class] token is passed to an MLP head for image classification.

Grid Image

Large-Scale Pre-training

According to the paper, early experiments with ViT showed that, without large-scale pre-training and only trained on mid-sized datasets such as ImageNet, it lagged behind comparably-sized ResNets by a few percentage points in accuracy. The authors attributed this gap to the lack of inductive biases inherent to CNN, such as translation invariance and locality. ViT outperformed ResNets only after being pretrained or trained on large-scale datasets (14M - 300M images).

Grid Image

What ViT Learns

Interpretability studies of trained ViT models show a few consistent patterns:

  • The learned patch embeddings resemble the low-level edge features that also emerge in the first layers of trained CNNs.
  • The learned position embeddings encode distance between patches in terms of similarity. A given patch's position embedding is most similar to the embeddings of near patches.
  • Attention heads specialize across layers. In the earliest Transformer layers, some heads attend only to nearby patches, while others already capture long-range dependencies by attending to distant patches. In deeper layers, most heads attend globally across the entire image.

Masked Autoencoders (MAE)

Masked Autoencoders (MAE) applies a BERT-style masking objective to ViT. A large random subset of patches (e.g., 75%) is masked, and only the remaining small set of visible patches is passed into the ViT encoder. A lightweight transformer decoder, used only during pretraining, takes the full set of encoded patches and the masked tokens as input and reconstructs the original image. The model is trained using a reconstruction loss over the entire image.
According to the authors' experiments, the pretrained encoder exhibits the following behavior on downstream tasks as the masking ratio varies:

  • Fine-Tuning: Accuracy stays relatively flat across a wide range of masking ratios and peaks at approximately 60% masking ratio.
  • Linear-Probing (Freezing the Encoder and Training Only a Linear Layer): Accuracy is poor at low masking ratios but improves as the masking ratio increases, peaking at around 70–75% masking.

Because so few patches are visible during pretraining, the encoder is forced to learn genuinely holistic representations rather than relying on nearby pixels.

Grid Image

Vision-Language Transformers

Vision-Language Transformers must decide how to represent images before fusing them with text. This section introduces some models that use ViT to encode images into visual tokens before combining them with word tokens.

Vision-and-Language Transformer (ViLT)

ViLT (≈ BERT + ViT) encodes an input image into visual patch tokens using ViT and processes them together with word tokens in a shared Transformer Encoder architecture. Its pretraining objectives include image-text matching, masked language modeling, and word-patch alignment via optimal transport, which encourages individual words to align with the image regions they describe.

Grid Image

ALign-the-image-and-text-representations-BEfore-Fusing (ALBEF)

ALBEF (≈ BERT + ViT + Contrastive Learning) consists of 2 unimodal Transformer encoders and 1 multimodal Transformer encoder. The visual encoder is ViT, while the text encoder is a typical Transformer encoder. The visual and word tokens are fused via cross-modal attention in the multimodal Transformer encoder.
It has 3 pre-training objectives:

  • Masked Language Modeling (MLM): utilizes both the image and the text to predict the masked words.
  • Image-Text Matching (ITM): predicts whether a pair of image and text is positive (matched) or negative (not matched).
  • Image-text contrastive learning (ITC): aligns the visual tokens and word tokens before they are fused by the multimodal Transformer encoder. This brings the two modalities closer in the representation space, making it easier for the following multimodal Transformer encoder to perform cross-modal attention.

In addition, since the image-text pairs used for pre-training are often noisy, such that positive-pairs are usually weakly-correlated, a Momentum Distillation (MoD) model is proposed and used to generate pseudo-targets for both original image and text inputs. Momentum Distillation (MoD) is a momentum version of the base model (2 unimodal Transformer encoders + 1 cross-modal Transformer model ) by taking the moving-average of its parameters. During training, the unimodal encoders from the base model learn to match the pseudo outputs generated by those of the momentum model, providing more reliable supervision despite the noisy image-text pairs.

Grid Image

Training Vision-Language Transformers from Captions Alone (VLC)

Vision-Language from Captions (VLC) extends Masked Autoencoders (MAE) to learn multi-modal representations. It first randomly masks image and word tokens, then concatenates them before feeding them into a shared multimodal Transformer encoder with 3 task-specific decoder heads. The model is pretrained using three objectives:

  • Image-Text Matching (ITM): identifies if the given image-text pairs are aligned.
  • Masked Language Modeling (MLM): predicts the masked word tokens based on both non-masked text and image patches.
  • Masked Image Modeling (MIM): randomly masks image patches to reconstruct the missing pixels based on both non-masked tokens and patches.
Grid Image

Video Transformers

Processing sequences of frames in a video, however, runs into a problem: large-scale, precisely-labeled video-text pairs are far scarcer than image captions. The solution used across this line of work is to lean on weakly-paired data instead, such as instructional videos with automatically generated subtitles.

VideoBERT: A Joint Model for Video and Language Representation Learning

VideoBERT extends BERT to the video domain by representing a sequence of video frames as a sequence of visual words. For each video, it first samples frames at 20 fps to partitions the video into a sequence of non-overlapping 30-frame video clips. Each 30-frame video clip is fed into a pretrained separable 3D CNN (S3D), a video convolution network, to extract a 1024-dimensional feature vector. Hierarchical k-means is then applied to tokenize/cluster all the 1024-dimensional feature vectors into 20,736 discrete clusters, each of which represents a visual token.
These visual tokens are then concatenated with text tokens to form a single input sequence, and the resulting sequence is passed through a pretrained embedding layer to get a sequence of spoken words and visual words, which are then processed by a shared BERT model. The model is pretrained using the following BERT-style objectives:

  • Masked Modeling: A random subset of tokens is masked, and the model is trained to predict the masked tokens. The input sequence may consist of text tokens only, visual words only, or both visual words and text tokens.
  • Next Sentence Prediction: predicts whether the text sentence is temporally aligned with the visual sentence using final hidden state of the [CLS] token.
Grid Image

ActBERT: Learning Global-Local Video-Text Representations

ActBERT builds on VideoBERT by explicitly modeling actions as a separate token type. Its input sequence consists of 3 kinds of token embeddings: word token embedding, action token embeddings, and visual token embeddings.

To obtain action embeddings, the model first extracts verbs from its corresponding text descriptions for all video clips to build an action vocabulary bank. It then pretrains a 3D CNN to classify each video clip based on the actions shown in the corresponding descriptions. Action embeddings are extracted from video clips using the pretrained 3D CNN.
For visual embeddings, ActBERT uses a pretrained Faster R-CNN to generate region proposals. For each region, its normalized bounding-box coordinates are assembled into a vector and passed through an embedding layer to produce a spatial position embedding, which is then added to the corresponding region feature vector to form the visual embedding. Finally, for word embeddings, ActBERT embeds the text descriptions using WordPiece embeddings.

ActBERT uses the proposed TaNgled Transformer (TNT), which consists of 3 Transformers. The 3 Transformers separately process the word, action, and visual token embeddings respectively, while every pair of Transformers is connected through cross-modal interaction, enabling information to be exchanged across them.

There are 4 pretraining objectives for ActBERT :

  • Masked Language Modeling with Global and Local Visual Cues: A random subset of word embeddings is masked, and the model is trained to predict the masked words using unmasked action embeddings and visual embeddings.
  • Masked Action Classification: A random subset of action embeddings is masked, and the model is trained to predict the masked actions using unmasked word embeddings and visual embeddings .
  • Masked Object Classification: A random subset of visual embeddings is masked, and the model is trained to predict the masked visual regions using unmasked word embeddings and action embeddings .
  • Cross-modal Matching: Similar to the Next Sentence Prediction (NSP), this tasks predicts whether the word is temporally aligned with the visual regions using final hidden state of the [CLS] token.
Grid Image

Key Takeaways

ViT formulated Convolution as Self-attention

Self-attention can be formulated as convolution with dynamic-weight kernels.
However, replacing convolutions with self-attention drops the translation invariant convolutions naturally have.


Patch tokens + high-ratio masked pretraining scale efficiently

ViT's patch embedding and MAE's aggressive (~70%) masked reconstruction technique both show that treating an image as a sequence of tokens and then pretraining on large-scale datasets can produce representations that transfer well and scale with compute.


Vision-language and video transformers: Transformer & BERT-style pretraining

Whether combining images and texts (ViLT, ALBEF, VLC) or videos and text descriptions (VideoBERT, ActBERT), the recurring pattern is to first represent inputs as a sequence of token embeddings, feed token embeddings to Transformer model, and pretrain with BERT-style objectives.