Skip to content
E
Educatum

Explain the concept of masked language-image modeling and its role in training multimodal models.

Curated by Educatum AI teamLast updated:
Multimodal Models
Direct Answer

Masked language-image modeling (MLIM) is a self-supervised multimodal pre-training objective that corrupts input text tokens and image patches and trains a joint fusion Transformer to reconstruct them from cross-modal context. Unlike dual-encoder contrastive models, MLIM fuses modalities via shared self-attention or cross-attention before prediction, forcing fine-grained alignment between visual regions and words. Models such as ViLT, FLAVA, and BEiT-3 use MLIM to boost downstream VQA, grounding, and captioning.

Study Card: Masked Language-Image Modeling

Direct Answer

Masked Language-Image Modeling (MLIM) is a self-supervised pre-training paradigm for multimodal vision-language models (such as UNITER, ViLT, ALBEF, FLAVA, and BEiT-3). It generalizes BERT’s Masked Language Modeling and Vision Transformer Masked Image Modeling (MIM) into a joint objective:

  1. Input-Level Masking: A fraction of input text tokens are replaced with [MASK], and a fraction of input image patches are replaced with a learnable [MASK] patch embedding (note: masking happens at the input, never on output hidden states, and vision typically uses higher masking ratios such as 40–75% than text’s ~15% due to visual spatial redundancy).
  2. Multimodal Fusion: Unmasked image patch embeddings and unmasked text embeddings (plus modality-type and positional embeddings) are concatenated or cross-attended inside a shared multimodal Transformer. This cross-modal interaction is essential: the model must read unmasked words to reconstruct missing image patches and inspect visible image regions to predict masked words.
  3. Joint Reconstruction Loss: Prediction heads reconstruct masked text tokens via cross-entropy and masked visual patches via either discrete visual tokens (VQ-VAE/dVAE), momentum teacher features, or normalized pixel patches:

LMLIM=LMLM(masked text∣T~,V~)+λ LMIM(masked patches∣T~,V~)\mathcal{L}_{\text{MLIM}} = \mathcal{L}_{\text{MLM}}(\text{masked text} \mid \tilde{T}, \tilde{V}) + \lambda\,\mathcal{L}_{\text{MIM}}(\text{masked patches} \mid \tilde{T}, \tilde{V})

Key Terms

  • Masked Language Modeling (MLM): Reconstructing masked subword tokens conditioned on surrounding text and paired visual context.
  • Masked Image Modeling (MIM): Reconstructing masked P×PP \times P image patches (or discrete visual tokenizer IDs) conditioned on visible patches and paired text.
  • Multimodal Fusion Encoder: Shared self-attention or cross-attention layers allowing token representations and patch representations to interact deeply.
  • Patch Embedding: Linear projection flattening non-overlapping P×P×CP \times P \times C image patches into Transformer-compatible dmodeld_{\text{model}} vectors.

Example

Consider a 224×224224 \times 224 image split into 16×1616 \times 16 patches (14×14=19614 \times 14 = 196 patches; plus 1 optional [CLS] token = 197 sequence elements in standard ViT) paired with the caption "A black cat sleeps on a red mat":

  • At the input, we mask the word "cat" ([MASK]) and mask ~40% of image patches (≈78\approx 78 patches, or ~29 patches at 15%), including patches covering the red mat.
  • Inside the multimodal fusion Transformer, the [MASK] text token attends to visible patches showing a sleeping black feline and infers "cat", while masked mat patches attend to surrounding floor patches and the text phrase "red mat" to reconstruct visual features.

Code Implementation

import torch
import torch.nn as nn


class MultimodalMaskedModel(nn.Module):
    """Self-contained MLIM model demonstrating input-level masking + joint Transformer fusion."""

    def __init__(self, vocab_size=1000, patch_dim=16 * 16 * 3, d_model=128, nhead=4, num_layers=2):
        super().__init__()
        self.patch_dim = patch_dim
        self.text_embed = nn.Embedding(vocab_size, d_model)
        self.patch_proj = nn.Linear(patch_dim, d_model)

        # Learnable [MASK] vector for patches and modality-type embeddings (0=text, 1=image)
        self.mask_patch_token = nn.Parameter(torch.randn(1, 1, d_model) * 0.02)
        self.modality_embed = nn.Embedding(2, d_model)

        encoder_layer = nn.TransformerEncoderLayer(
            d_model=d_model, nhead=nhead, dim_feedforward=256, batch_first=True
        )
        self.fusion_encoder = nn.TransformerEncoder(encoder_layer, num_layers=num_layers)

        self.text_head = nn.Linear(d_model, vocab_size)
        self.image_head = nn.Linear(d_model, patch_dim)

    def forward(self, masked_token_ids, image_patches, patch_mask):
        """
        Args:
            masked_token_ids: (B, L_text) with MASK_TOKEN_ID at masked positions
            image_patches:    (B, N_patches, patch_dim) flattened non-overlapping patches
            patch_mask:       (B, N_patches) boolean tensor (True = masked patch)
        """
        B, L_text = masked_token_ids.shape
        N_patches = image_patches.size(1)

        txt_emb = self.text_embed(masked_token_ids) + self.modality_embed(
            torch.zeros(B, L_text, dtype=torch.long, device=masked_token_ids.device)
        )
        img_emb = self.patch_proj(image_patches)
        # Replace masked INPUT patches with learnable mask token BEFORE Transformer fusion
        img_emb = torch.where(patch_mask.unsqueeze(-1), self.mask_patch_token.expand(B, N_patches, -1), img_emb)
        img_emb = img_emb + self.modality_embed(
            torch.ones(B, N_patches, dtype=torch.long, device=masked_token_ids.device)
        )

        # Joint multimodal self-attention fuses text tokens and image patches
        fused = self.fusion_encoder(torch.cat([txt_emb, img_emb], dim=1))
        fused_text, fused_image = fused[:, :L_text], fused[:, L_text:]

        text_logits = self.text_head(fused_text)     # (B, L_text, vocab_size)
        patch_preds = self.image_head(fused_image)   # (B, N_patches, patch_dim)
        return text_logits, patch_preds


torch.manual_seed(0)
B, L_text, N_patches, patch_dim = 2, 8, 196, 16 * 16 * 3
MASK_TOKEN_ID = 0

token_ids = torch.randint(1, 1000, (B, L_text))
token_ids[0, 2] = MASK_TOKEN_ID  # Mask a text token at input
patches = torch.randn(B, N_patches, patch_dim)
patch_mask = torch.rand(B, N_patches) < 0.4  # Mask ~40% of image patches at input

model = MultimodalMaskedModel(vocab_size=1000, patch_dim=patch_dim)
text_logits, patch_preds = model(token_ids, patches, patch_mask)

print("Text predictions shape:", text_logits.shape)   # (2, 8, 1000)
print("Image patch predictions shape:", patch_preds.shape)  # (2, 196, 768)
  • CLIP vs. MLIM: CLIP uses independent dual encoders with global contrastive loss (fast retrieval, weak fine-grained localization); MLIM fuses modalities densely for VQA and grounding—often combined in models like FLAVA and ALBEF.
  • BEiT-3 & Discrete Visual Tokenizers: Predicting discrete VQ-VAE/CLIP tokens instead of raw pixel MSE avoids wasting model capacity on high-frequency pixel noise.
  • Visual Question Answering (VQA) & Referring Expression Grounding: Downstream tasks that rely heavily on fine-grained token-to-region alignment learned via MLIM.
  • Image-Text Matching (ITM): Frequently paired with MLIM as a binary cross-modal classification objective using hard negative pairs.
View all →

Try keywords like RoPE, FlashAttention, DPO, or Blind 75.