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.
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 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 (called
memory). - Decoder Function & Cross-Attention Flow: Takes previously produced target tokens and runs three sublayers per block:
- Causal (Masked) Self-Attention: A lower-triangular attention mask prevents position from attending to future target positions .
- Encoder-Decoder Cross-Attention: Target representations form the queries (), while the encoder’s final hidden states supply both keys and values (), routing source information selectively to each decoding position.
- 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 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 (whose cross-attention 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.
- Training (Teacher Forcing): The encoder computes once. The entire shifted target sequence (
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 ( before softmax) so autoregressive causality holds during parallel teacher-forced training.
- Cross-Attention: Bridges encoder and decoder using decoder hidden states as queries () and encoder final hidden states as keys and values ().
- 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 and prior decoder self-attention 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 . 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 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)
Related Concepts
- 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.