Skip to content
E
Educatum

In a transformer-based sequence-to-sequence model, describe the primary functions of the encoder and decoder and how information flows between them during both training and inference.

Curated by Educatum AI teamLast updated:
Transformer Models
Direct Answer

In a sequence-to-sequence Transformer, the encoder applies bidirectional self-attention across the entire source sequence in parallel to produce contextualized memory hidden states. The decoder uses causal (masked) self-attention over target tokens combined with cross-attention (querying the encoder's final hidden states as keys and values) to generate the target sequence—processed in parallel via teacher forcing during training and autoregressively step-by-step with KV caching during inference.

Study Card: Encoder-Decoder in Transformer-based Sequence-to-Sequence Models

Direct Answer

A sequence-to-sequence Transformer (e.g., the original Vaswani et al. architecture, T5, BART, MarianMT) separates source understanding from conditional target generation:

  • Encoder Function: Takes the full source sequence X=(x1,…,xS)X = (x_1, \dots, x_S) and applies stacked blocks of bidirectional self-attention and feed-forward layers. Every source token attends to all other source tokens simultaneously, producing a sequence of contextualized hidden states Henc∈RS×dH_{\text{enc}} \in \mathbb{R}^{S \times d} (called memory).
  • Decoder Function & Cross-Attention Flow: Takes previously produced target tokens Y<tY_{<t} and runs three sublayers per block:
    1. Causal (Masked) Self-Attention: A lower-triangular attention mask prevents position tt from attending to future target positions >t> t.
    2. Encoder-Decoder Cross-Attention: Target representations form the queries (QQ), while the encoder’s final hidden states HencH_{\text{enc}} supply both keys and values (K,VK, V), routing source information selectively to each decoding position.
    3. Feed-Forward Network: Projects hidden states to next-token logits via the LM head.
  • Training vs. Inference Information Flow:
    • Training (Teacher Forcing): The encoder computes HencH_{\text{enc}} once. The entire shifted target sequence ([<BOS>, y_1, ..., y_{T-1}]) is passed into the decoder in parallel, because the causal self-attention mask prevents future token leakage while cross-entropy loss is computed over all positions simultaneously.
    • Inference (Autoregressive Decoding): The encoder runs once on the source sequence to produce HencH_{\text{enc}} (whose cross-attention K,VK, V projections can be cached). The decoder starts with <BOS> and generates one token at a time (greedy, sampling, or beam search), feeding each predicted token back as the next input and caching self-attention keys/values (KV cache) to avoid redundant recomputation.

Key Terms

  • Bidirectional Self-Attention (Encoder): Allows every source token to attend to both left and right source context in parallel.
  • Causal Self-Attention Mask (Decoder): Masks future target positions (−∞-\infty before softmax) so autoregressive causality holds during parallel teacher-forced training.
  • Cross-Attention: Bridges encoder and decoder using decoder hidden states as queries (QQ) and encoder final hidden states as keys and values (K,VK, V).
  • Teacher Forcing: Supplying ground-truth shifted target tokens to the decoder during training so all time steps train in a single parallel pass.
  • KV Caching: Storing encoder cross-attention K,VK, V and prior decoder self-attention K,VK, V states across autoregressive decoding steps.

Example

When translating "Hello, how are you?" into "Bonjour, comment allez-vous ?", the encoder runs once over all 6 source tokens to build HencH_{\text{enc}}. During training, the decoder receives [<BOS>, Bonjour, ,, comment, allez, -, vous, ?] all at once under a causal mask, predicting [Bonjour, ,, comment, allez, -, vous, ?, <EOS>] in parallel. During inference, the decoder begins from [<BOS>], cross-attends to HencH_{\text{enc}} to emit "Bonjour", appends "Bonjour", and repeats autoregressively until <EOS> is generated.

Code Implementation

import torch
import torch.nn as nn

torch.manual_seed(0)

class Seq2SeqTransformerDemo(nn.Module):
    def __init__(self, vocab_size=100, d_model=64, nhead=4, num_layers=2):
        super().__init__()
        self.embed = nn.Embedding(vocab_size, d_model)
        self.transformer = nn.Transformer(
            d_model=d_model,
            nhead=nhead,
            num_encoder_layers=num_layers,
            num_decoder_layers=num_layers,
            dim_feedforward=128,
            batch_first=True,
        )
        self.lm_head = nn.Linear(d_model, vocab_size)

    def forward_train(self, src_ids, tgt_input_ids):
        """Parallel teacher-forced forward pass using a causal target mask."""
        T = tgt_input_ids.size(1)
        causal_mask = nn.Transformer.generate_square_subsequent_mask(T, device=src_ids.device)
        memory = self.transformer.encoder(self.embed(src_ids))  # (B, S, D)
        dec_out = self.transformer.decoder(
            self.embed(tgt_input_ids), memory, tgt_mask=causal_mask
        )
        return self.lm_head(dec_out)  # (B, T, V)

    @torch.no_grad()
    def greedy_decode(self, src_ids, bos_id=1, eos_id=2, max_len=6):
        """Autoregressive inference: encode source once, decode token by token."""
        memory = self.transformer.encoder(self.embed(src_ids))
        ys = torch.full((src_ids.size(0), 1), bos_id, dtype=torch.long, device=src_ids.device)
        for _ in range(max_len):
            causal_mask = nn.Transformer.generate_square_subsequent_mask(ys.size(1), device=ys.device)
            dec_out = self.transformer.decoder(self.embed(ys), memory, tgt_mask=causal_mask)
            next_tok = self.lm_head(dec_out[:, -1, :]).argmax(dim=-1, keepdim=True)
            ys = torch.cat([ys, next_tok], dim=1)
            if (next_tok == eos_id).all():
                break
        return ys

model = Seq2SeqTransformerDemo()
src = torch.randint(3, 100, (2, 5))
tgt_in = torch.tensor([[1, 12, 25, 30], [1, 44, 18, 9]])

# Training (parallel)
logits = model.forward_train(src, tgt_in)
print("Training logits shape:", logits.shape)  # (2, 4, 100)

# Inference (autoregressive)
generated = model.greedy_decode(src)
print("Generated token IDs shape:", generated.shape)

# Note: For production pretrained Seq2Seq (e.g., T5 or MarianMT), use AutoModelForSeq2SeqLM:
# from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
# tok = AutoTokenizer.from_pretrained("Helsinki-NLP/opus-mt-en-fr")
# mt = AutoModelForSeq2SeqLM.from_pretrained("Helsinki-NLP/opus-mt-en-fr")
# out_ids = mt.generate(**tok("Hello, how are you?", return_tensors="pt"), num_beams=4)
  • Exposure Bias: Mismatch between training (ground-truth prefix via teacher forcing) and inference (model-generated prefix).
  • Beam Search & Nucleus Sampling: Decoding algorithms balancing likelihood and diversity over autoregressive steps.
  • T5 & BART: Modern pre-trained encoder-decoder Transformers using span corruption and denoising objectives.
  • Decoder-Only vs. Encoder-Decoder: Trade-offs between unified causal LLMs and dedicated bidirectional encoding + cross-attention.
View all →

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