🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Sequence-to-Sequence Models: Encoder-Decoder Architecture

Natural Language ProcessingSequence-to-Sequence Models: Encoder-Decoder ArchitectuređŸŸĸ Free Lesson

Sequence-to-Sequence Models: Encoder-Decoder Architecture

What You'll Learn

  • 1Write the recurrent encoder and decoder equations for a fixed length bottleneck
  • 2Derive Bahdanau alignment weights and the context vector they produce
  • 3Explain teacher forcing, exposure bias, and the scheduled sampling schedule
  • 4Compute attention distributions and per token cross entropy by hand

An encoder compresses a source sequence into one vector and a decoder expands it into a target sequence, but a single fixed length vector caps quality once sentences grow past that capacity. This lesson derives the recurrent encoder-decoder equations, Bahdanau attention with its alignment distribution, and the teacher forcing objective that keeps training stable, then measures what attention actually buys.

Recurrent Encoder-Decoder

Sutskever, Vinyals, and Le (2014) showed that a deep LSTM with the source reversed beats phrase based systems on WMT 2014, and Cho et al. (2014) framed the same idea as learning to map a source to a fixed context vector. The encoder runs a recurrent cell over source tokens :

The decoder conditions on the final state and previously emitted tokens:

Both directions of the source feed the initial decoder state, so the vector carries the whole meaning of a sentence that might hold 40 or 50 tokens. That is the information bottleneck: once exceeds the capacity the cell can retain, BLEU drops and the gradient through time thins out, because every output token depends on a path that crosses all encoder steps.

Bahdanau Attention

Bahdanau, Cho, and Bengio (2015) replaced the single vector with a per step context vector built from alignment scores. For decoder step and source position :

The scores become a distribution that sums to one over the source length:

and the context vector is the weighted sum of encoder states:

Luong and Manning (2015) simplified the score to a dot product , which avoids two weight matrices and parallelizes across positions.

VariantScore functionCost per stepSource of context
Bahdanau 2015additive, bidirectional encoder
Luong dot 2015previous decoder layer
Luong general 2015learned projection
Transformer 2017scaled dot product per headall positions at once

Teacher Forcing and Exposure Bias

Training feeds the gold previous token so the decoder learns one consistent distribution per position:

At inference the decoder sees its own output, so any early mistake changes every later condition and errors compound. Scheduled sampling mixes the two with a schedule that decays the probability of using the model own prediction:

where is the probability of taking the model output in epoch out of total epochs, so the first epoch trains on gold tokens and the last epoch trains on free running output.

Worked Examples

Worked Code

python
import numpy as np

def softmax(x):
    e = np.exp(x - x.max())
    return e / e.sum()

def bahdanau_attention(decoder_state, encoder_states, W_h, W_s, v):
    energy = np.tanh(encoder_states @ W_h + decoder_state @ W_s) @ v
    alpha = softmax(energy)
    context = alpha @ encoder_states
    return alpha, context

d_model, d_ctx = 4, 3
rng = np.random.default_rng(0)
encoder_states = rng.normal(size=(5, d_ctx))
decoder_state = rng.normal(size=d_ctx)
W_h = rng.normal(size=(d_ctx, d_model)) * 0.1
W_s = rng.normal(size=(d_ctx, d_model)) * 0.1
v = rng.normal(size=(d_model,)) * 0.1

alpha, context = bahdanau_attention(decoder_state, encoder_states, W_h, W_s, v)
print("alpha:", np.round(alpha, 3), "sum:", round(float(alpha.sum()), 3))
print("context:", np.round(context, 3))
python
import torch
import torch.nn as nn

class Encoder(nn.Module):
    def __init__(self, vocab, emb, hidden):
        super().__init__()
        self.embed = nn.Embedding(vocab, emb)
        self.rnn = nn.LSTM(emb, hidden, batch_first=True, bidirectional=True)

    def forward(self, src):
        out, state = self.rnn(self.embed(src))
        return out, state

class Decoder(nn.Module):
    def __init__(self, vocab, emb, hidden):
        super().__init__()
        self.embed = nn.Embedding(vocab, emb)
        self.attn = nn.Linear(hidden * 3, hidden)
        self.v = nn.Linear(hidden, 1, bias=False)
        self.rnn = nn.LSTM(emb + hidden * 2, hidden, batch_first=True)
        self.out = nn.Linear(hidden, vocab)

    def step(self, token, hidden, enc_out):
        e = torch.tanh(self.attn(torch.cat([
            hidden[0].repeat(enc_out.size(1), 1, 1).permute(1, 0, 2), enc_out], dim=2)))
        alpha = torch.softmax(self.v(e).squeeze(2), dim=1)
        ctx = (alpha.unsqueeze(2) * enc_out).sum(dim=1)
        emb = self.embed(token).unsqueeze(1)
        _, hidden = self.rnn(torch.cat([emb, ctx.unsqueeze(1)], dim=2), hidden)
        return self.out(hidden[0].squeeze(0)), hidden, alpha

Real-World Applications

  • Machine translation: Google Neural Machine Translation (Wu et al., 2016) shipped bidirectional LSTMs with attention, and the alignment weights were read directly as word links.
  • Speech recognition: attention decoders map acoustic frame sequences to text without forcing a monotonic CTC alignment.
  • Code summarization: long method bodies exceed any fixed bottleneck, so attention over the token sequence keeps rare identifiers visible to the decoder.

💡Attention removes the bottleneck

Bahdanau attention replaced one sentence vector with a distribution over encoder states, so translation quality stopped degrading with sentence length, and Luong dot product attention cut the score cost from two matrices to one product.

Common Mistakes

Feeding gold tokens at evaluation time

Fix: Run the model free running during validation, otherwise the measured loss hides exposure bias.

Letting attention read padding positions

Fix: Add a large negative score before the softmax so padded states receive weight zero.

Expecting scheduled sampling to fix search errors

Fix: It only narrows the train and test gap; beam search and length normalization still matter.

Best Practices

  • Mask padded source positions with a large negative constant before the softmax
  • Warm up the learning rate over the first few thousand steps so attention scores do not saturate
  • Report validation loss in free running mode alongside teacher forced loss

Key Takeaways

  • The encoder-decoder bottleneck is a fixed vector c, so quality falls once sentences exceed its capacity
  • Alignment weights come from a softmax over additive energies and sum to one over the source
  • Teacher forcing minimizes cross entropy on gold prefixes while inference conditions on model output
  • Attention turns decoding into per step lookup, which is why later models dropped recurrence entirely

Frequently Asked Questions

Why did attention beat a larger context vector?

Doubling the hidden size doubles parameters but keeps the vector fixed, so long sentences still compress into one slot. Attention keeps one vector per source position and spends compute instead of capacity, which fixed the length collapse at almost no parameter cost.

What is the difference between Bahdanau and Luong attention?

Bahdanau scores with an additive network over the previous decoder state and encoder state, and it computes context from the encoder output. Luong scores with a dot product or a general bilinear form and typically uses the top decoder layer, which is cheaper and feeds the next recurrent step.

Why does exposure bias appear only at inference?

Training conditions every step on the gold prefix, so the decoder never sees its own mistakes. At inference it does, and one wrong token shifts the whole conditional distribution, which is why free running loss is always higher than teacher forced loss.

Interview Questions

Q1: Why is the alignment weight vector a probability distribution?

It comes from a softmax over source positions, so the entries are positive and sum to one, and the context vector is then a convex combination of encoder states.

Q2: How does attention change the gradient path?

Every output step connects to every encoder state in one hop, so gradients do not have to travel through T recurrent transitions, which is what made sentences longer than 30 tokens trainable.

CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-07

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert NLP Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement