Skip to content

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: u⋅v=∑iuivi=∥u∥∥v∥cos⁡θu \cdot v = \sum_i u_i v_i = \lVert u \rVert \lVert v \rVert \cos\theta; 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 P−1APP^{-1}AP; 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 ∑f(x)⊙g\sum f(x) \odot g. Read more: 3.3 Oracles, golden and differential tests, gradcheck as a test in Software Engineering
  • central differences: the numerical derivative (f(x+ϵ)−f(x−ϵ))/2ϵ(f(x + \epsilon) - f(x - \epsilon))/2\epsilon, 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 j≤qoff+ij \le q_{\text{off}} + i; 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, and concat scores, and state how they relate.
  • Split concat’s weight into a cached key half and a per-step query half.
  • Compute the attentional state h~=tanh⁡(Wc[c;h])\tilde h = \tanh(W_c [c ; h]) with the context first, and explain why the dot score is left unscaled.
SymbolMeaningType / shape
ddwidth of both the decoder state and the keysint
hhthe query: the decoder state after this stepfloat32[B, d]
ksk_sthe encoder output at source position ssfloat32[B, S, d]
WaW_ascore_proj.weight: [d,d][d, d] for general, [d,2d][d, 2d] for concatfloat32
vvv.weight, concat onlyfloat32[1, d]
WcW_ccombine.weightfloat32[d, 2d]
ese_s, asa_s, ccscore, weight, context, as in Bahdanau attention
h~\tilde hthe attentional state tanh⁡(Wc[c;h])\tanh(W_c [c ; h])float32[B, d]

Luong keeps Bahdanau’s masked read and changes two things: the score function, and when the decoder asks. Bahdanau reads with st−1s_{t-1} and feeds the context into the cell. Luong runs the cell first to get hth_t, then reads with hth_t, then combines:

ht=cell([yt−1;h~t−1],ht−1),ct=∑sasks,h~t=tanh⁡(Wc[ct;ht]),logitst=Woh~t+bo.h_t = \mathrm{cell}([y_{t-1} ; \tilde h_{t-1}], h_{t-1}), \quad c_t = \sum_s a_s k_s, \quad \tilde h_t = \tanh(W_c [c_t ; h_t]), \quad \text{logits}_t = W_o \tilde h_t + b_o .

With hth_t as the query, the decoder has already absorbed yt−1y_{t-1} when it decides where to look. The decoder does the cell and the output layer; this module provides the scores, the read, and h~\tilde h. 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 −∞-\infty, exact zero weights, an empty row reads nothing. So forward is Bahdanau’s three lines with a different scores.

Luong proposes three score functions, which differ in parameters and cost:

Scoreese_sParameters
doth⋅ksh \cdot k_snone
generalh⋅(Waks)h \cdot (W_a k_s)WaW_a [d,d][d, d]
concatv⋅tanh⁡(Wa[h;ks])v \cdot \tanh(W_a [h ; k_s])WaW_a [d,2d][d, 2d], vv

A dot product is the cheapest score that couples query and key. h⋅ksh \cdot k_s is large when they point the same way, and it needs no parameters, but it requires hh and ksk_s to live in the same dd-dimensional space, which is why the module has a single width dd.

general adds a learned change of basis: h⋅(Waks)h \cdot (W_a k_s) compares the two in a learned metric. With Wa=IW_a = I it is dot. Since h⊤Wak≠h⊤Wa⊤kh^\top W_a k \ne h^\top W_a^\top k unless WaW_a is symmetric, which side carries WaW_a 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.

Each score has a per-sentence part that can be cached. For concat, the matrix splits: Wa[h;ks]=Whh+WkksW_a [h ; k_s] = W_h h + W_k k_s, where WhW_h is the first dd columns of WaW_a and WkW_k the last dd. So WkksW_k k_s is computed once per sentence (project_keys), and each step adds WhhW_h h. The tanh⁡\tanh is applied after the sum, so it must stay per step. For general, project_keys is WaksW_a k_s; for dot, it is the keys themselves.

There is still something the decoder lacks. Without help, the decoder at step tt does not know what it attended to at step t−1t - 1. Luong’s input feeding concatenates h~t−1\tilde h_{t-1} to the next input embedding, with h~0=0\tilde h_0 = 0. 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 tt reaches the attention of step t−1t - 1.

The attentional state h~=tanh⁡(Wc[c;h])\tilde h = \tanh(W_c [c ; h]) 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 h~\tilde h 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 1/d1/\sqrt{d}. Luong’s dot score is unscaled, and scaling would change every weight. The scale is the transformer’s addition.

Take d=2d = 2, the dot score, h=(1,0)h = (1, 0), and keys k1=(1,0)k_1 = (1, 0), k2=(0,1)k_2 = (0, 1), k3=(2,0)k_3 = (2, 0), the third being padding.

  1. Scores: h⋅k=(1,0,2)h \cdot k = (1, 0, 2); after the mask, (1,0,−∞)(1, 0, -\infty).
  2. Weights: e1/(e1+1)=0.731059e^1 / (e^1 + 1) = 0.731059 and 1/(e+1)=0.2689411 / (e + 1) = 0.268941, then 0.
  3. Context: c=0.731059(1,0)+0.268941(0,1)=(0.731059,0.268941)c = 0.731059 (1, 0) + 0.268941 (0, 1) = (0.731059, 0.268941).
  4. With Wc=[I  I]W_c = [I \; I] (so Wc[c;h]=c+hW_c [c ; h] = c + h): h~=tanh⁡(1.731059,0.268941)=(0.939181,0.262640)\tilde h = \tanh(1.731059, 0.268941) = (0.939181, 0.262640).
  5. With Wc=[I  0]W_c = [I \; 0] instead, h~=tanh⁡(c)=(tanh⁡0.731059,tanh⁡0.268941)\tilde h = \tanh(c) = (\tanh 0.731059, \tanh 0.268941): the context half is the first dd columns.

A correct solution reproduces steps 1 to 4 exactly and gives tanh⁡(c)\tanh(c) in step 5. Note that the scores in step 1 are exactly (1,0,2)(1, 0, 2); a scaled score would give different weights.

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.

Parameters depend on the score; combine (WcW_c) 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]
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))

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 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.

Per step, dot and general cost O(BSd)O(B S d) for the scores, with general’s O(BSd2)O(B S d^2) projection paid once per sentence. concat costs O(Bd2)O(B d^2) for WhhW_h h plus O(BSd)O(B S d) for the tanh⁡\tanh and vv. Bahdanau’s per-step cost without caching would be O(BSd2)O(B S d^2).

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 hth_t as the query, the decoder has already absorbed yt−1y_{t-1} when it decides where to look; with st−1s_{t-1}, 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 dd, so for large dd the softmax saturates and gradients vanish. That is acceptable at seq2seq widths, and it is exactly the problem the transformer’s 1/d1/\sqrt{d} fixes.

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 h~\tilde h 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:

CaseKind of checkChecksWhy it matters downstream
hand example: dotunitsteps 1 to 4 of the hand examplepins down the read
hand example attentional orderunitWc=[I  0]W_c = [I \; 0] gives tanh⁡(c)\tanh(c)context first, as Luong trained it
matches torchgoldeneach score: weights, context, h~\tilde h, and every gradient against torchthe decoder trains through this
gradcheck of every input and parametergradcheckfloat64 central differences, each score, a padded rowevery parameter learns
general with identity is dotpropertygeneral with Wa=IW_a = I equals dotthe relation between the scores
general is not symmetricunitWaW_a, not Wa⊤W_a^\topcheckpoints load the right way round
concat projection splits the weightpropertyproject_keys and the score equal v⋅tanh⁡(Wa[h;k])v \cdot \tanh(W_a [h ; k])the per-sentence cache is exact
masked weights are exactly zeropropertyexact zeros, no gradient, an empty row reads nothingpadding is never read
dot is not scaledunitscores exactly (1,0,2)(1, 0, 2)the scaled score belongs to the transformer
parameter names and shapesuniteach score’s keys and shapes, combine last, query_fromthe safetensors keys of Luong checkpoints
validationboundaryunknown score, wrong widths, wrong maskwiring bugs fail loudly

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:

PitfallSymptomHow the solution avoids it
Wc[h;c]W_c [h ; c] instead of Wc[c;h]W_c [c ; h]Luong-trained weights decode garbageattentional concatenates [context, query], context first
general with Wa⊤W_a^\topthe bilinear form is transposedgeneral projects the keys with score_proj(keys), i.e. WaksW_a k_s, and dots with hh
masking after the softmaxreal weights do not sum to 1masked_fill(..., -np.inf) on the scores, then the softmax
scaling the dot score by 1/d1/\sqrt{d}every weight differs from Luong’sdot scores are the raw matmul of keys and query
concat precomputing with the query half of WaW_athe cached keys are multiplied by the wrong columnsproject_keys uses weight[:, d:] (the key half); scores uses weight[:, :d] for the query
masking with −109-10^9an empty row reads padding uniformlyfills with -np.inf, never a finite number
h~\tilde h without the tanhthe attentional state is unboundedF.tanh(self.combine(...))

The encoder-decoder steps first, attends with the new state, and feeds h~\tilde h 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 d\sqrt{d}, over many heads, and the model zoo has Luong rows.

Each piece has a production descendant:

This pieceProduction equivalentWhat it addsWhere to look
dot scoreF.scaled_dot_product_attentionthe 1/d1/\sqrt{d} scale, heads, causal masks, fused kernelsscaled dot-product attention; FlashAttention
input feedingthe attentional decoder of OpenNMTthe same input_feed option, with coverage and copy attentionOpenNMT-py onmt/decoders/decoder.py (InputFeedRNNDecoder)
general scorebilinear attention in readers and parsersthe biaffine scorer of dependency parsersDozat and Manning, “Deep Biaffine Attention” (2017)
local attentionLuong’s local-p attentionreads a window around a predicted position: cost per step independent of SSLuong et al. 2015, section 3.2; sliding-window attention
  • 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.
  • dot score: h⋅ksh \cdot k_s, the parameter-free score between a query and a key of the same width.
  • general score: the bilinear score h⋅(Waks)h \cdot (W_a k_s).
  • concat score: v⋅tanh⁡(Wa[h;ks])v \cdot \tanh(W_a [h ; k_s]), Bahdanau’s network with one matrix on the concatenation.
  • attentional state: h~=tanh⁡(Wc[c;h])\tilde h = \tanh(W_c [c ; h]), what the output layer reads.
  • input feeding: concatenating h~t−1\tilde h_{t-1} to the next decoder input so the decoder remembers where it looked.
  • Luong keeps Bahdanau’s masked read and changes two things: the score function, and when the decoder asks, after its recurrent step.
  • dot is h⋅ksh \cdot k_s, general the bilinear h⋅(Waks)h \cdot (W_a k_s) (with Wa=IW_a = I it is dot), concat a hidden layer on [h;ks][h ; k_s].
  • concat’s weight splits into a key half, cached per sentence, and a query half, computed per step.
  • The attentional state h~=tanh⁡(Wc[c;h])\tilde h = \tanh(W_c [c ; h]), 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 1/d1/\sqrt{d} is the transformer’s change.
  1. Why does general with Wa=IW_a = I give exactly dot, and why does Wa⊤W_a^\top give something different?
    AnswerWith $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.
  2. 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.
  3. In step 5 of the worked example, why does Wc=[I  0]W_c = [I \; 0] give tanh⁡(c)\tanh(c) and not tanh⁡(h)\tanh(h)?
    Answer`attentional` concatenates `[context, query]`, so the first $d$ columns of $W_c$ multiply $c$. With $[I \; 0]$ only the context passes through.
  4. 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)`.
  5. Why is the dot score not divided by d\sqrt{d} here?
    AnswerLuong'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.