Skip to content

Language models, retrieval, prompting, and language adaptation · Encoder–decoder and multilingual models · LNG022 · Architecture

Bahdanau attention neural machine translation

Replaces a single encoder bottleneck with a learned soft alignment between each generated token and encoder states.

Explained here Component demo, not a trained model CodeSplash's own run

In CodeSplash

Documented in the Academy only. There's no Set up button.

Availability
Explained here
Code example
Component demo, not a trained model
Who ran it
CodeSplash's own run
CodeSplash's run
The reference's example ran in Python and R here, and they agree.
The reference's record
Python: The chapter's authors report running it; there is no record for this entry alone. R: Reviewed but not run: R wasn't available to the reference's authors.

Purpose

Replaces a single encoder bottleneck with a learned soft alignment between each generated token and encoder states. It is useful for translation and other sequence transduction problems where different outputs depend on different source positions.

Question / objective

Which source positions are most useful for producing each target token?

Architecture / computational structure

A recurrent encoder/decoder is coupled to additive attention scoring and a weighted context vector. Learned recurrent, alignment, embedding, and output weights are parameters; alignment width and decoding controls are hyperparameters.

Assumptions

Soft attention distributes weight across available states but does not prove causal explanation or linguistic alignment.

Formula / computational definition

eti=v⊤tanh⁡(Wsst−1+Whhi),αti=eeti∑jeetj,ct=∑iαtihi.e_{ti}=v^\top\tanh(W_ss_{t-1}+W_hh_i),\quad \alpha_{ti}=\frac{e^{e_{ti}}}{\sum_j e^{e_{tj}}},\quad c_t=\sum_i\alpha_{ti}h_i.

e_ti=v^T tanh(W_s s_(t-1)+W_h h_i); alpha_ti=softmax_i(e_ti); c_t=sum_i alpha_ti h_i. The decoder predicts y_t using c_t, previous output, and decoder state; all components learn through conditional cross-entropy.

Parameters and notation

Learned parameters: identified in the architecture subsection. Hyperparameters, design and inference choices: Encoder and decoder widths, alignment dimension, vocabulary, padding masks, recurrent depth, and generation controls.

Fitting, fine-tuning, and adaptation

Train parallel sequences end to end with target-token cross-entropy, correct source masks, and teacher forcing. Adapt the decoder/head first or fine-tune the full network with smaller learning rates. Validate alignment behavior descriptively and measure translation errors; attention maps do not establish explanations.

How to use and calibrate

Examine translation quality, long-sentence degradation, attention heatmaps as diagnostics, and ablations against a no-attention recurrent baseline. Use development data for settings and an independent test set for the final estimate. Report uncertainty across examples or seeds when the evaluation design supports it; model scores and self-assessments are not automatically calibrated probabilities of correctness.

Example application

Generate a translation while visualizing the source positions receiving attention at each step.

Interpretation / pitfalls

Watch out

Missing padding masks and inconsistent sequence lengths corrupt both optimization and visualizations. The code below isolates one stated component; successful execution does not validate model quality or reproduce the cited experiment.

Python and R code examples

Full implementation route: Implement additive attention with tensor linear layers and softmax in PyTorch or R torch. The included native array example calculates a single alignment-weighted context; full recurrent training requires an encoder, decoder, data, and optimizer.

Example scope: Additive-attention weighted context with simplified supplied alignment scores.

Dependencies: Python 3 standard library; base R; shared setup above. No model downloads or external services.

Validation: Python component executed in the combined example script; R counterpart supplied but not runtime-tested here. All numbers are synthetic.

Python and R

The reference's own programs, shown as written. A component demo shows one central piece of the method; it doesn't train a full model.

Python

Component demo, not a trained model — Additive-attention weighted context with simplified supplied alignment scores.

Shared setup for this chapter
import math

def softmax(xs):
    m = max(xs)
    es = [math.exp(x-m) for x in xs]
    return [e/sum(es) for e in es]

def dot(a, b):
    return sum(x*y for x, y in zip(a, b))

def matvec(matrix, vector):
    return [dot(row, vector) for row in matrix]

def meanvec(rows):
    return [sum(row[j] for row in rows)/len(rows) for j in range(len(rows[0]))]

def sigmoid(x):
    return 1/(1+math.exp(-x))

def nll(probabilities):
    return -sum(math.log(p) for p in probabilities)
states = [[1,0],[0,1],[0.5,0.5]]
scores = [math.tanh(h[0]+0.3*h[1]) for h in states]
alpha = softmax(scores)
context = [sum(a*h[j] for a,h in zip(alpha,states)) for j in range(2)]
print(alpha, context)
R

Component demo, not a trained model — Additive-attention weighted context with simplified supplied alignment scores.

Shared setup for this chapter
softmax <- function(x) {
  shifted <- exp(x-max(x))
  shifted/sum(shifted)
}
states <- rbind(c(1,0), c(0,1), c(0.5,0.5))
scores <- tanh(drop(states %*% c(1,0.3)))
alpha <- softmax(scores)
print(list(attention=alpha, context=colSums(states*alpha)))

Sources

From the CodeSplash reference, entry LNG022.