10.3 Luong attention and input feeding
Bahdanau’s attention works, but every decoder step runs a hidden layer over every source position, and its query is the state from before the step, so the decoder chooses where to look before it has seen the token it was just given. Luong, Pham, and Manning simplified both: score with a dot product, and attend with the state just computed. They also noticed that the decoder forgets where it looked, and fixed that by feeding the attentional state back into the next step’s input. The dot score is the one the transformer keeps, so this section is the last step before scaled dot-product attention.
Concepts from other sections (9)
This section uses these ideas. Each has a short definition and a link to the section that explains it in full. Tap a dotted term in the text to preview it.
- Dot product: ; it measures how much two vectors point the same way, and it is zero exactly when they are perpendicular. Read more: Chapter 10: Calculus 3 in Mathematics
- exact match: the fraction of hypotheses equal to their reference after stripping white space at both ends. Read more: 10.5 Sequence metrics: exact match, BLEU, chrF
- Change of basis: rewriting a matrix in new coordinates as ; the transformation is the same, only its description changes. Read more: Chapter 9: Linear Algebra in Mathematics
- Gradient check: a comparison of an analytic gradient against the numerical one that reports pass or fail and the element furthest past its allowance. Read more: 10.1 Partial derivatives, gradients, and gradcheck in Mathematics
- Gradcheck: a comparison of a hand-written gradient against central differences of . Read more: 3.3 Oracles, golden and differential tests, gradcheck as a test in Software Engineering
- central differences: the numerical derivative , used as an oracle for analytic gradients. Read more: 6.3 The op library and gradcheck_all
- safetensors: a checkpoint format of an 8-byte header length, a JSON header, and raw little-endian row-major tensor bytes. Read more: 6.1 Byte bigram: counts, logits, safetensors v0
- causal mask: the rule ; each position reads itself and the past. Read more: 11.2 Masks: causal, padding, sliding window, additive
- FlashAttention: attention computed tile by tile with an online softmax, so the score matrix is never stored. Read more: 22.5 FlashAttention forward in C
You need the masked read and length_mask from the previous section, plus Linear and Module from the module system, the op library, the Tensor of the tensor section, and PCG32 from Modular arithmetic, hashing, and PCG32 in Mathematics. Stable numerics in the same book is background for the masked softmax.
The solution is python/tinyllm/seq2seq/luong.py: LuongAttention with the dot, general, and concat scores (project_keys, scores, forward) and attentional, the state that input feeding passes on. It implements the contract course/contracts/py/tinyllm/seq2seq/luong.pyi, and its oracle tests are in test_luong.py. Plugged into the encoder-decoder, a Luong seq2seq reaches an exact match of at least 0.97 on the dates task.
Learning objectives
- Explain how Luong’s step order (attend after the cell) differs from Bahdanau’s, and what input feeding restores.
- Implement the
dot,general, andconcatscores, and state how they relate.- Split
concat’s weight into a cached key half and a per-step query half.- Compute the attentional state with the context first, and explain why the dot score is left unscaled.
Notation
Section titled “Notation”| Symbol | Meaning | Type / shape |
|---|---|---|
| width of both the decoder state and the keys | int | |
| the query: the decoder state after this step | float32[B, d] | |
| the encoder output at source position | float32[B, S, d] | |
score_proj.weight: for general, for concat | float32 | |
v.weight, concat only | float32[1, d] | |
combine.weight | float32[d, 2d] | |
| , , | score, weight, context, as in Bahdanau attention | |
| the attentional state | float32[B, d] |
Attend after the step
Section titled “Attend after the step”Luong keeps Bahdanau’s masked read and changes two things: the score function, and when the decoder asks. Bahdanau reads with and feeds the context into the cell. Luong runs the cell first to get , then reads with , then combines:
With as the query, the decoder has already absorbed when it decides where to look. The decoder does the cell and the output layer; this module provides the scores, the read, and . The class attribute query_from = "current" tells the decoder which order to use.
The read itself is unchanged. Weights must still be a masked softmax over positions and the context a weighted average of keys: padded scores , exact zero weights, an empty row reads nothing. So forward is Bahdanau’s three lines with a different scores.
Three scores
Section titled “Three scores”Luong proposes three score functions, which differ in parameters and cost:
| Score | Parameters | |
|---|---|---|
dot | none | |
general | ||
concat | , |
A dot product is the cheapest score that couples query and key. is large when they point the same way, and it needs no parameters, but it requires and to live in the same -dimensional space, which is why the module has a single width .
general adds a learned change of basis: compares the two in a learned metric. With it is dot. Since unless is symmetric, which side carries is part of the checkpoint format, and weights load only one way round. Writing it as “project the keys, then dot” means the projection is per sentence and each step is still one dot per position.
concat is Bahdanau’s network with one weight matrix on the concatenation.
Precomputing the keys
Section titled “Precomputing the keys”Each score has a per-sentence part that can be cached. For concat, the matrix splits: , where is the first columns of and the last . So is computed once per sentence (project_keys), and each step adds . The is applied after the sum, so it must stay per step. For general, project_keys is ; for dot, it is the keys themselves.
Input feeding
Section titled “Input feeding”There is still something the decoder lacks. Without help, the decoder at step does not know what it attended to at step . Luong’s input feeding concatenates to the next input embedding, with . The model can then avoid translating the same source word twice, a coverage signal for free. It also makes the network deeper in time: the gradient of step reaches the attention of step .
The attentional state mixes the context into the state; it is both what the output layer reads and what input feeding passes on. Context first is Luong’s convention and therefore the checkpoint layout. Feeding into the next input is the decoder’s job; this module only provides attentional.
One last detail sets Luong apart from the transformer: there is no . Luong’s dot score is unscaled, and scaling would change every weight. The scale is the transformer’s addition.
Working it by hand
Section titled “Working it by hand”Take , the dot score, , and keys , , , the third being padding.
- Scores: ; after the mask, .
- Weights: and , then 0.
- Context: .
- With (so ): .
- With instead, : the context half is the first columns.
A correct solution reproduces steps 1 to 4 exactly and gives in step 5. Note that the scores in step 1 are exactly ; a scaled score would give different weights.
Designing the API
Section titled “Designing the API”class LuongAttention(Module): query_from = "current" def __init__(self, d: int, score: Literal["dot", "general", "concat"], rng=None) -> None: ... def project_keys(self, keys: Tensor) -> Tensor: ... # [B, S, d] def scores(self, query: Tensor, keys: Tensor, proj=None) -> Tensor: ... # [B, S], unmasked def forward(self, query, keys, mask, proj=None) -> tuple[Tensor, Tensor]: ... # context, weights def attentional(self, query: Tensor, context: Tensor) -> Tensor: ... # tanh(W_c [c ; h])The interface mirrors AdditiveAttention, so the decoder can hold either; the only additions are the score argument and attentional.
Building it step by step
Section titled “Building it step by step”The parameters
Section titled “The parameters”Parameters depend on the score; combine () is always present and registered last:
class LuongAttention(Module): query_from = "current" # the decoder steps the cell first, then attends with h_t
def __init__(self, d, score, rng=None): # ... (d >= 1, score in SCORES, default rng) if score == "general": self.score_proj = Linear(d, d, bias=False, rng=r) # W_a [d, d] elif score == "concat": self.score_proj = Linear(2 * d, d, bias=False, rng=r) # W_a [d, 2d] self.v = Linear(d, 1, bias=False, rng=r) self.combine = Linear(2 * d, d, bias=False, rng=r) # W_c [d, 2d]The per-sentence part
Section titled “The per-sentence part”def project_keys(self, keys): self._check_keys(keys) if self.score == "dot": return keys # nothing to precompute if self.score == "general": return self.score_proj(keys) # W_a k_s for every position # concat: W_a [h ; k] = W_h h + W_k k, and W_k k does not depend on h. w_k = self.score_proj.weight[:, self.d :] # the key half: last d columns return F.matmul(keys, F.transpose(w_k, 0, 1))The per-step part
Section titled “The per-step part”For dot and general the score is one batched matrix-vector product:
def scores(self, query, keys, proj=None): # ... (shape checks; proj = self.project_keys(keys) if not given) B, S, d = keys.shape if self.score in ("dot", "general"): # One dot product per position: [B, S, d] @ [B, d, 1]. No 1/sqrt(d). e = F.matmul(proj, F.reshape(query, (B, d, 1))) return F.reshape(e, (B, S)) w_h = self.score_proj.weight[:, :d] # the query half: first d columns hq = F.reshape(F.matmul(query, F.transpose(w_h, 0, 1)), (B, 1, d)) e = self.v(F.tanh(proj + hq)) # v . tanh(W_h h + W_k k_s) return F.reshape(e, (B, S))Slicing score_proj.weight with getitem keeps both halves in the graph, so the one [d, 2d] parameter gets its full gradient from both uses.
The read and the attentional state
Section titled “The read and the attentional state”The read is Bahdanau’s, and the attentional state is one line:
def forward(self, query, keys, mask, proj=None): # ... (key and mask checks) e = F.masked_fill(self.scores(query, keys, proj), ~m.astype(bool), -np.inf) a = F.softmax(e, axis=-1) # padded weights exactly 0 ctx = F.matmul(F.reshape(a, (B, 1, S)), keys) return F.reshape(ctx, (B, d)), a
def attentional(self, query, context): # ... (both [B, d]) # Luong's order: the context first, then the decoder state. return F.tanh(self.combine(F.concat([context, query], axis=-1)))The full solution is luong.py.
Why this design
Section titled “Why this design”Per step, dot and general cost for the scores, with general’s projection paid once per sentence. concat costs for plus for the and . Bahdanau’s per-step cost without caching would be .
Why one [d, 2d] matrix for concat and not two Linears? It matches Luong’s formulation and the checkpoint layout (score_proj.weight); splitting by slicing gives the same computation and the same cache without changing the key names.
Why attend after the step? With as the query, the decoder has already absorbed when it decides where to look; with , as in Bahdanau, it chooses before seeing it. Input feeding compensates for what is lost: the next step still sees where this one looked.
The tradeoff is that unscaled dot scores grow with , so for large the softmax saturates and gradients vanish. That is acceptable at seq2seq widths, and it is exactly the problem the transformer’s fixes.
Testing it
Section titled “Testing it”As with Bahdanau attention, the oracle in test_luong.py is the formula in numpy with the module’s own weights from state_dict(): all three scores, the masked softmax, the context, and in float64. It adds the hand-worked numbers, a finite-difference gradient check of the keys, an empty row, and the parameter names, and imports only contract modules.
The full list of behaviors a correct solution must have:
| Case | Kind of check | Checks | Why it matters downstream |
|---|---|---|---|
hand example: dot | unit | steps 1 to 4 of the hand example | pins down the read |
| hand example attentional order | unit | gives | context first, as Luong trained it |
| matches torch | golden | each score: weights, context, , and every gradient against torch | the decoder trains through this |
| gradcheck of every input and parameter | gradcheck | float64 central differences, each score, a padded row | every parameter learns |
general with identity is dot | property | general with equals dot | the relation between the scores |
general is not symmetric | unit | , not | checkpoints load the right way round |
concat projection splits the weight | property | project_keys and the score equal | the per-sentence cache is exact |
| masked weights are exactly zero | property | exact zeros, no gradient, an empty row reads nothing | padding is never read |
dot is not scaled | unit | scores exactly | the scaled score belongs to the transformer |
| parameter names and shapes | unit | each score’s keys and shapes, combine last, query_from | the safetensors keys of Luong checkpoints |
| validation | boundary | unknown score, wrong widths, wrong mask | wiring bugs fail loudly |
What can go wrong
Section titled “What can go wrong”Several Luong bugs give a model that trains fine from scratch but cannot load Luong-trained weights, because the bug is a layout convention rather than a math error:
| Pitfall | Symptom | How the solution avoids it |
|---|---|---|
| instead of | Luong-trained weights decode garbage | attentional concatenates [context, query], context first |
general with | the bilinear form is transposed | general projects the keys with score_proj(keys), i.e. , and dots with |
| masking after the softmax | real weights do not sum to 1 | masked_fill(..., -np.inf) on the scores, then the softmax |
| scaling the dot score by | every weight differs from Luong’s | dot scores are the raw matmul of keys and query |
concat precomputing with the query half of | the cached keys are multiplied by the wrong columns | project_keys uses weight[:, d:] (the key half); scores uses weight[:, :d] for the query |
| masking with | an empty row reads padding uniformly | fills with -np.inf, never a finite number |
without the tanh | the attentional state is unbounded | F.tanh(self.combine(...)) |
Where this leads
Section titled “Where this leads”The encoder-decoder steps first, attends with the new state, and feeds into the next input. Beam search decodes a Luong seq2seq in its tests, whose state carries feed. In the next part, scaled dot-product attention is Luong’s dot divided by , over many heads, and the model zoo has Luong rows.
Each piece has a production descendant:
| This piece | Production equivalent | What it adds | Where to look |
|---|---|---|---|
dot score | F.scaled_dot_product_attention | the scale, heads, causal masks, fused kernels | scaled dot-product attention; FlashAttention |
| input feeding | the attentional decoder of OpenNMT | the same input_feed option, with coverage and copy attention | OpenNMT-py onmt/decoders/decoder.py (InputFeedRNNDecoder) |
general score | bilinear attention in readers and parsers | the biaffine scorer of dependency parsers | Dozat and Manning, “Deep Biaffine Attention” (2017) |
| local attention | Luong’s local-p attention | reads a window around a predicted position: cost per step independent of | Luong et al. 2015, section 3.2; sliding-window attention |
Further reading
Section titled “Further reading”- Luong, Pham, and Manning, “Effective Approaches to Attention-based Neural Machine Translation” (EMNLP 2015), sections 3.1 and 3.3.
- Britz et al., “Massive Exploration of Neural Machine Translation Architectures” (2017), on additive vs multiplicative scores.
Key terms
Section titled “Key terms”- dot score: , the parameter-free score between a query and a key of the same width.
- general score: the bilinear score .
- concat score: , Bahdanau’s network with one matrix on the concatenation.
- attentional state: , what the output layer reads.
- input feeding: concatenating to the next decoder input so the decoder remembers where it looked.
Summary
Section titled “Summary”- Luong keeps Bahdanau’s masked read and changes two things: the score function, and when the decoder asks, after its recurrent step.
dotis ,generalthe bilinear (with it isdot),concata hidden layer on .concat’s weight splits into a key half, cached per sentence, and a query half, computed per step.- The attentional state , context first, is what the output layer reads and what input feeding passes to the next step.
- The plain dot score is not scaled here; scaling by is the transformer’s change.
Review questions
Section titled “Review questions”- Why does
generalwith give exactlydot, and why does give something different?Answer
With $W_a = I$, `project_keys` returns the keys and the score is $h \cdot k_s$. In general $h^\top W_a k \ne h^\top W_a^\top k$ unless $W_a$ is symmetric, so a checkpoint trained with one convention scores differently under the other. - In
concat, why can the key half be precomputed but not the query half?Answer
$W_a [h ; k] = W_h h + W_k k$ is linear before the $\tanh$. $W_k k_s$ depends only on the sentence; $W_h h$ changes every step. The $\tanh$ is applied after the sum, so it must stay per step. - In step 5 of the worked example, why does give and not ?
Answer
`attentional` concatenates `[context, query]`, so the first $d$ columns of $W_c$ multiply $c$. With $[I \; 0]$ only the context passes through. - What would input feeding give at step 1, and where is it set up?
Answer
$\tilde h_0 = 0$. The encoder-decoder's `init_state` creates a zero `feed` when `query_from == "current"`, and each `decode_step` replaces it with the new `attentional(h, ctx)`. - Why is the dot score not divided by here?
Answer
Luong's model is unscaled, and weights trained for it expect raw scores; the worked example's weights $(0.731, 0.269)$ come from scores $(1, 0)$. Scaling is a separate design decision made by the transformer's scaled dot-product attention.