Skip to content
E
Educatum

Discuss the role of cross-attention in transformer-based encoder-decoder models and how it facilitates the generation of output sequences based on information from the input sequence.

Curated by Educatum AI teamLast updated:
Transformer Models
Direct Answer

Cross-attention bridges the encoder and decoder in sequence-to-sequence Transformers by projecting decoder hidden states into queries (Q) and encoder outputs into keys (K) and values (V). Unlike causal decoder self-attention, cross-attention uses only a source padding mask so every decoding step can dynamically retrieve context from any non-padded input position. Because encoder outputs stay fixed during generation, cross-attention keys and values can be cached once per sequence to accelerate autoregressive decoding.

Study Card: Cross-Attention in Transformer Encoder-Decoder Models

Direct Answer

In Transformer encoder-decoder architectures (such as the original Transformer, T5, BART, and Whisper), cross-attention connects the two halves of the model so the autoregressive decoder can condition every generated token on the full encoded input sequence.

Each decoder layer applies three sub-layers: causal masked self-attention over previously generated target tokens, multi-head cross-attention over the encoder’s final representations Henc∈RLsrc×dmodelH_{\text{enc}} \in \mathbb{R}^{L_{\text{src}} \times d_{\text{model}}}, and a feed-forward network. Within each head, queries come from the decoder hidden states Hdec∈RLtgt×dmodelH_{\text{dec}} \in \mathbb{R}^{L_{\text{tgt}} \times d_{\text{model}}} while keys and values come from the encoder:

Q=HdecWQ,K=HencWK,V=HencWVQ = H_{\text{dec}} W_Q, \qquad K = H_{\text{enc}} W_K, \qquad V = H_{\text{enc}} W_V

CrossAttn(Q,K,V)=softmax(QKTdk+Mpad)V\text{CrossAttn}(Q, K, V) = \text{softmax}\left(\frac{Q K^T}{\sqrt{d_k}} + M_{\text{pad}}\right)V

Two architectural properties are critical:

  1. Source padding mask only (no causal mask): Unlike decoder self-attention, cross-attention allows each target step to attend bidirectionally to all non-padded source tokens (MpadM_{\text{pad}} masks only source <PAD> positions).
  2. Static encoder KV caching: Since HencH_{\text{enc}} never changes across autoregressive output steps, KK and VV for cross-attention are projected once per input sequence and reused across all decoding steps, saving substantial inference compute.

Key Terms

  • Encoder: Processes the entire source sequence bidirectionally into contextualized states HencH_{\text{enc}}.
  • Decoder: Autoregressively predicts output tokens conditioned on previous outputs and encoder states.
  • Cross-Attention: Multi-head attention where queries originate in the decoder (LtgtL_{\text{tgt}}) and keys/values originate in the encoder (LsrcL_{\text{src}}).
  • Self-Attention: Attention where queries, keys, and values all originate from the same sequence.
  • Cross-Attention KV Cache: Caching precomputed encoder key/value projections once before decoding rather than recomputing them at every generated token.

Example

Consider English-to-French translation of "The black cat sat on the mat":

  • Even though French word order flips adjective placement ("Le chat noir..."), cross-attention does not enforce monotonic left-to-right alignment.
  • When generating "chat", the decoder’s query vector aligns strongly with the encoder keys around "cat" while attending lightly to "the"; on the very next token "noir", cross-attention shifts weight back onto "black".
  • In Whisper speech-to-text, audio frames (Lsrc=1500L_{\text{src}} = 1500) serve as keys/values while text tokens query the acoustic frames via cross-attention.

Code Implementation

import torch
import torch.nn as nn


class MultiHeadCrossAttention(nn.Module):
    def __init__(self, d_model, num_heads):
        super().__init__()
        assert d_model % num_heads == 0, "d_model must be divisible by num_heads"
        self.num_heads = num_heads
        self.d_k = d_model // num_heads

        self.W_q = nn.Linear(d_model, d_model)  # Decoder hidden states -> queries
        self.W_k = nn.Linear(d_model, d_model)  # Encoder hidden states -> keys
        self.W_v = nn.Linear(d_model, d_model)  # Encoder hidden states -> values
        self.W_o = nn.Linear(d_model, d_model)

    def forward(self, dec_hidden, enc_hidden, src_pad_mask=None):
        """
        Args:
            dec_hidden: (batch_size, seq_len_q, d_model)
            enc_hidden: (batch_size, seq_len_k, d_model)
            src_pad_mask: Optional boolean/0-1 mask broadcastable to
                          (batch_size, 1, 1, seq_len_k), where 1=valid, 0=pad.
        """
        batch_size = dec_hidden.size(0)

        q = self.W_q(dec_hidden).view(batch_size, -1, self.num_heads, self.d_k).transpose(1, 2)
        k = self.W_k(enc_hidden).view(batch_size, -1, self.num_heads, self.d_k).transpose(1, 2)
        v = self.W_v(enc_hidden).view(batch_size, -1, self.num_heads, self.d_k).transpose(1, 2)

        scores = torch.matmul(q, k.transpose(-1, -2)) / (self.d_k ** 0.5)
        if src_pad_mask is not None:
            scores = scores.masked_fill(src_pad_mask == 0, float("-inf"))

        attn_weights = torch.softmax(scores, dim=-1)  # (batch_size, num_heads, seq_len_q, seq_len_k)
        context = torch.matmul(attn_weights, v)       # (batch_size, num_heads, seq_len_q, d_k)

        context = context.transpose(1, 2).contiguous().view(batch_size, -1, self.num_heads * self.d_k)
        return self.W_o(context), attn_weights


torch.manual_seed(0)
batch_size, seq_len_q, seq_len_k, d_model, num_heads = 2, 5, 7, 512, 8
dec_hidden = torch.randn(batch_size, seq_len_q, d_model)
enc_hidden = torch.randn(batch_size, seq_len_k, d_model)
src_mask = torch.tensor([[1, 1, 1, 1, 1, 0, 0], [1, 1, 1, 1, 1, 1, 1]]).unsqueeze(1).unsqueeze(1)

cross_attn = MultiHeadCrossAttention(d_model, num_heads)
output, weights = cross_attn(dec_hidden, enc_hidden, src_pad_mask=src_mask)

print("Output shape:", output.shape)        # (2, 5, 512)
print("Attn weights shape:", weights.shape) # (2, 8, 5, 7)
assert torch.allclose(weights[0, :, :, 5:], torch.zeros_like(weights[0, :, :, 5:]))
  • Causal Self-Attention vs. Cross-Attention: Causal self-attention applies a lower-triangular future mask within the decoder; cross-attention attends across encoder tokens without causal restriction.
  • Encoder-Decoder vs. Decoder-Only LLMs: T5/BART/Whisper rely on cross-attention; GPT/LLaMA pack prompt and completion into one sequence using causal self-attention.
  • Multimodal Conditioning: Cross-attention also injects image/text embeddings (CLIP/T5 tokens) into diffusion UNets/DiTs and VLMs like Flamingo.
  • KV Cache Optimization: Cross-attention KV caches remain fixed across generated tokens, whereas decoder self-attention KV caches grow linearly with generated length.
View all →

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