Additive attention, introduced by Bahdanau and colleagues in 2015 for neural machine translation, directly targets the information bottleneck of recurrent sequence-to-sequence models.
A recurrent encoder must compress the entire source sequence into one fixed-width hidden state. As length grows, that vector carries an unbounded number of token dependencies, and gradients attenuate across long horizons.
The remedy is content-based addressing: at each decoding step, let the decoder query every encoder hidden state and form a soft alignment, rather than routing all source information through a single bottleneck vector.
The Bahdanau mechanism scores the compatibility between the decoder state at step t and each encoder hidden state h-j, using a one-layer feedforward network instead of a bare dot product.
Formally, the score e-t-j equals a learned vector v transposed, times the hyperbolic tangent of W-one acting on the previous decoder state plus W-two acting on encoder state h-j. It quantifies how well source position j aligns with decoding step t.
Softmax over the scores produces the attention weights alpha-t-j, a normalized distribution over source positions. Each weight expresses how strongly encoder state j should contribute to the current decoding step.
The context vector c-t is the weighted sum of encoder hidden states under alpha. Because this combination is fully differentiable, gradients propagate through the alignment itself, and the entire architecture trains end-to-end by backpropagation.
Three components, then: an additive score function, softmax normalization, and a weighted-sum context vector. Together they grant the decoder selective, position-dependent access to the entire source sequence.
Here is the PyTorch realization of the additive score, showing how directly the equations map onto tensor operations in a modern framework.
We apply tanh to the sum of the projected decoder state and the projected encoder outputs, then take the inner product with the learned vector v. The parameters W-one, W-two, and v are optimized jointly with the rest of the network.
Additive attention eliminated the fixed-vector bottleneck and established soft, content-based alignment as a design principle, the direct ancestor of the scaled dot-product attention at the heart of the Transformer.
Clarification: Compatibility scores require both query and key indices. Normalize over keys for a fixed decoder query.
Equations, code and original cards
Introduction to Additive (Bahdanau) Attention
• Motivation: break the RNN fixed-vector bottleneck
• Content-based soft alignment over encoder states
• RNNs compress variable-length input into one hidden state
We now formalize additive attention, the scoring mechanism introduced by Bahdanau et al. for neural machine translation. Unlike dot-product attention, it computes compatibility through a learned feedforward network rather than a bilinear form.
The mechanism operates on three learned projections of the input: the query, key, and value vectors. The query encodes what the decoder currently seeks; keys index what each encoder position offers; values carry the content to be aggregated.
These projections are affine transformations of the input matrix X by learned weight matrices W-Q, W-K, and W-V, so Q equals X W-Q, K equals X W-K, and V equals X W-V. The projection dimensions are hyperparameters, typically smaller than the model dimension.
Compatibility scores come from a one-hidden-layer network: project query and key into a shared space, sum them, apply a hyperbolic tangent nonlinearity, then map to a scalar. The nonlinearity is essential, since without it the score collapses to a bilinear form.
Formally, the score e-i-j equals v transpose times the hyperbolic tangent of W-Q q-i plus W-K k-j. The learned vector v reduces the hidden representation to a scalar logit measuring how relevant key j is to query i.
Softmax normalization over j converts these logits into attention weights: positive, summing to one, a categorical distribution over input positions. The context vector is then the convex combination of values under this distribution, a differentiable approximation to hard selection.
The PyTorch implementation vectorizes this with broadcasting: expand queries and keys along orthogonal axes, sum, apply tanh, contract with v, then softmax over the key dimension. Note this materializes the full n-by-n score matrix, which is quadratic in sequence length.
To summarize: additive attention computes scores through a learned nonlinear transformation rather than an inner product, at higher computational cost per score. This expressivity was historically important, though scaled dot-product attention later proved more hardware-efficient at large model scale.
Equations, code and original cards
Mathematical Formulation of Additive Attention
Bahdanau et al. 2015: Scoring via a Learned Feedforward Network
Query, Key, Value Projections
• Q = X W_Q: what the decoder seeks
• K = X W_K: what each position offers
• V = X W_V: content to aggregate
Additive Score Function
• e_{ij} = v^T \tanh(W_Q q_i + W_K k_j)
• One-hidden-layer MLP; tanh prevents collapse to bilinear form
• Softmax over j yields a categorical distribution over positions
import torch.nn.functional as FQ = X @ W_QK = X @ W_KV = X @ W_Ve = v.T @ torch.tanh(Q[:, None, :] @ W_Q + K[None, :, :] @ W_K)alpha = F.softmax(e, dim=-1)output = alpha @ V
Moment 03 / 08
Gradient Derivations and Loss Functions
We now make additive attention trainable: exact gradients, stable normalization, and losses matched to the objective.
For Bahdanau style additive attention, the score is a hyperbolic tangent of projected query and key; backpropagation therefore passes through that nonlinearity before reaching the projections.
The Jacobian with respect to the query, key, and value matrices factors into three terms: upstream error from the context vector, the attention weight gradient, and the local derivative of every projection and tanh unit.
The key object is the derivative of the loss with respect to each attention weight; through softmax it becomes the upstream gradient times the softmax Jacobian, namely the diagonal matrix of weights minus their outer product.
In PyTorch, build scores, apply softmax over keys, form the context as weights times values, then call backward; autograd accumulates exactly those Jacobian vector products.
Use cross entropy for tokens, mean squared error for regression, or an auxiliary attention penalty; clip gradient norm and normalize layers to keep optimization conditioned.
Equations, code and original cards
Gradients Through Additive Attention
• Score gradients: backpropagate through tanh projections of query and key
• Softmax Jacobian: diagonal attention weights minus their outer product
• Loss coupling: cross entropy, regression error, or auxiliary attention penalties
# PyTorch: autograd through Bahdanau additive attentionscore = torch.tanh(Q @ W_q + K @ W_k.transpose(-1, -2) + b)attn = torch.softmax(score, dim=-1) # softmax Jacobian is implicitcontext = attn @ V; loss.backward() # accumulates dQ, dK, dV
Moment 04 / 08
Interactive Attention Heatmap Visualization
Read this additive attention heatmap as Bahdanau compatibility: rows are softmax distributions over learned query-key scores for each token.
As you vary token scale you are changing positional resolution and embedding norms; that shifts the logits like an inverse temperature and blurs or sharpens attention flow.
Raising intensity saturates the colormap toward high-probability edges, exposing dominant key interactions instead of uniform background mass.
Swap the query token and watch the row renormalize: the learned scorer assigns larger logits to relevant keys, then causal masking, when enabled, forbids attention to future positions.
Equations, code and original cards
Moment 05 / 08
Implementation Details: Python and PyTorch
Let's implement additive attention, Bahdanau et al. 2015, in PyTorch. This is where the alignment model stops being notation and becomes tensors, shapes, and a forward pass you can debug.
We begin with three linear projections for queries, keys, and values. Each is a learned affine map from the model dimension into the hidden attention space, no bias needed if you prefer parameter economy.
Concretely, the query is W-q applied to the decoder state, and the key is W-k applied to each encoder hidden state. These projections are what make the compatibility function learnable rather than fixed.
The energy score is v transpose times the hyperbolic tangent of the projected query plus the projected key. The tanh nonlinearity is what lets this MLP-style scorer capture interactions a dot product cannot.
The context vector is then the softmax-weighted sum of the value vectors over all encoder positions. The softmax normalizes the energies into a distribution, so the output is a convex combination of values.
Here is the module. Note the structure: projections in the constructor, scoring and aggregation in forward. That separation is what makes the mechanism inspectable and easy to ablate.
This modularity pays off when you integrate attention into an encoder-decoder or swap in scaled dot-product scoring later. Keep initialization, masking, and gradient flow in mind as you write your own.
Equations, code and original cards
Implementation Details: Python and PyTorch
Additive (Bahdanau) Attention: From Equations to Tensors
• Learned projections: W_q, W_k, W_v
• Energy: vᵀ tanh(W_q q + W_k k)
• Softmax weights → convex combination of values
• Modular nn.Module: init vs. forward
Q = W_q \times X, \quad K = W_k \times X, \quad V = W_v \times X
We now turn to advanced optimizations for additive attention: linear-time approximations, hybrid scoring functions, and the IO-aware kernels that dominate recent efficient-attention research.
First, memory and computation optimizations. The quadratic cost of attention, order n squared in sequence length, is the scaling bottleneck; linear approximations attack it directly.
Kernel methods such as the Performer replace the softmax with random feature maps, reducing cost to order n times d, at the price of approximation error.
Hybrid models interpolate between additive and scaled dot-product scoring, combining the bounded gradients of the additive form with the expressiveness of bilinear similarity.
The formulation on the slide mixes both scores through a learned gate, letting each head interpolate between additive and bilinear compatibility during training.
FlashAttention, due to Dao and colleagues, takes a different route: it keeps the exact quadratic algorithm but reorganizes it to be IO-aware through tiling and kernel fusion.
The key insight: attention is memory-bound, so tiles are processed in on-chip SRAM and the full attention matrix never touches high-bandwidth memory.
The snippet shows the fused kernel called from PyTorch: query, key, and value tensors go in directly, with dropout and causal masking handled inside.
In summary, linear approximations cut asymptotic cost, hybrids trade stability against expressiveness, and IO-aware kernels deliver exact attention at several-fold wall-clock speedups.
Clarification: The original expression was not a valid additive attention equation. Label this as an illustrative mixture, not a standard algorithm.
Equations, code and original cards
Advanced Techniques and Optimizations
Linear Approximations, Hybrid Scoring, and IO-Aware Kernels
• IO-aware exact attention (Dao et al. 2022): tiling keeps blocks in SRAM, never materializing the $n \times n$ matrix in HBM
• Fused kernels with online softmax: 2–4× wall-clock speedup, $O(n)$ memory instead of $O(n^2)$
• Fused-kernel invocation via the flash-attn library:
from flash_attn import flash_attn_func
out = flash_attn_func(q, k, v, dropout_p=0.1, causal=True)
Moment 07 / 08
Research Trends and Open Questions
Today we survey research trends and open questions in additive attention and transformer architectures, emphasizing efficiency, alignment, and the directions shaping work through 2026.
We begin with the influential results and groups defining this area: alignment objectives such as DPO after Rafailov and colleagues, and efficiency gains from FlashAttention and grouped-query attention.
Next, the mathematical substrate: the attention kernel as Q K transpose scaled by the square root of d-k, and reference implementations that turn these identities into fused, IO-aware kernels.
We then examine sparse and adaptive attention, which prune the quadratic all-pairs cost toward near-linear scaling while preserving perplexity and retrieval accuracy.
Finally, open questions: compute-optimal scaling beyond Chinchilla's twenty-tokens-per-parameter rule, mechanistic interpretability of the residual stream, and robust length generalization.
Together these trajectories define where inductive bias, sample efficiency, and systems co-design will drive the next generation of sequence models.
Equations, code and original cards
Research Trends and Open Questions
• Influential results and groups, 2024 to 2026
• Alignment objectives and efficiency gains
• Sparse, adaptive, and linear-time attention
• Open problems in scaling and interpretability
Mathematical Foundations and Reference Kernels
Moment 08 / 08
Knowledge Check: Additive Attention
Time to check your understanding of additive attention, the Bahdanau-style scoring function where a learned feed-forward layer computes compatibility between query and key. Work through each question on your own, reasoning from the mechanism we just derived.
When you finish, we will walk through the results together, focusing on the alignment scores and how the softmax weights form the context vector, so any gaps get resolved before we move on.
Equations, code and original cards
MAKE IT YOURS
Explain the change.
References, scope & corrections
Research snapshots in the source material are not a claim of current state of the art. The reference review corrects identified errors; it is not exhaustive certification of every historical statement. Source code snippets are examples, not a tested production training system.