Simple Algorithm
Deep Learning · Emergence · 26 min

Pointer, Copy & Monotonic Attention

Attending to positions in order to copy, point and align online.

Ordinary attention reads the input to help choose an output word. Three ideas give the same weights a different job: they become the output itself, a pointer to an input position; they let a model copy a rare name that no vocabulary contains; and, constrained to move only forward, they let a model transcribe or translate while the input is still arriving. Each changes what the attention distribution means, and each comes with an exact formula worth deriving.

What you’ll learn

  • Formulate pointer networks, whose output distribution is attention over input positions, and explain how they handle output vocabularies that grow with the input and where they stop generalizing.
  • Derive the pointer-generator mixture and its coverage loss, contrast it with CopyNet's shared normalization, and compute the final probability of a copied word.
  • Derive the expected alignment of hard monotonic attention, its linear-time recursion and its parallel closed form, and extend it to chunkwise and multihead monotonic attention.
  • Relate copying with attention to induction heads in transformers, and explain why a fixed-size state cannot copy long inputs.

Attention as the output: pointer networks

Some outputs are positions in the input: the vertices of a convex hull, a tour through cities, a sorted order, the span of a document that answers a question. A softmax over a fixed vocabulary cannot index the positions of an input whose length is not fixed in advance. Vinyals, Fortunato and Jaitly (2015) noticed that attention already computes a distribution over input positions, and made it the output. In a pointer network the encoder states e1,…,en\mathbf e_1,\dots,\mathbf e_n of the nn inputs and the decoder state di\mathbf d_i give

uji=v⊤tanh⁡(W1ej+W2di),p(Ci=j∣C1,…,Ci−1,P)=softmax⁡(ui)j,j=1,…,nu^i_j=\mathbf v^\top\tanh\big(W_1\mathbf e_j+W_2\mathbf d_i\big),\qquad p(C_i=j\mid C_1,\dots,C_{i-1},\mathcal P)=\softmax(\mathbf u^i)_j,\qquad j=1,\dots,n
Bahdanau's additive scores, used directly as the output distribution instead of being blended into a context vector. The output "vocabulary" is the set of input positions, so its size grows with the input. The decoder's next input is the chosen element PCi\mathcal P_{C_i} itself, and each output step costs O(n)\order{n}.

Training is ordinary maximum likelihood on reference sequences of positions, with teacher forcing. On planar convex hulls, a fixed-vocabulary encoder–decoder can only be used at the input size it was trained on; a pointer network trained on 5 to 50 points runs on any size:

Model (trained on nn)Tested on nnExact hullArea covered
LSTM encoder–decoder (50)501.9%fails
with attention (50)5038.9%99.7%
Pointer network (50)5072.6%99.9%
Pointer network (5–50)100 / 200 / 50050.3% / 22.1% / 1.3%99.9% / 99.9% / 99.2%
Vinyals et al. (2015), Table 1. "Exact" requires every vertex, in order; "area" is the fraction of the true hull covered by the predicted polygon, reported as failing when more than 1% of outputs are not simple polygons. Beyond the training sizes the polygons stay good while exact answers fade, mostly through near-collinear points.

On the traveling salesman problem, pointer networks trained on optimal tours of 5 to 20 cities produced near-optimal tours up to about 30 cities and broke down by 40 to 50, and beam search had to be restricted to valid tours, since unconstrained decoding sometimes repeated or skipped a city. Later work trained pointer networks with reinforcement learning, rewarding short tours instead of imitating reference tours (Bello et al., 2016), and an attention-based successor trained this way came close to optimal tours for up to 100 cities (Kool, van Hoof & Welling, 2019).

Check your understanding

What determines the number of classes in a pointer network's output distribution at a given step?

  1. The size of a vocabulary fixed before training
  2. The decoder's hidden size
  3. The number of elements in the current input
  4. The number of outputs produced so far
Show the answer

C. The number of elements in the current input

The softmax runs over the scores u1i,…,uniu^i_1,\dots,u^i_n, one per input element, so a 37-point input gives 37 classes and a 500-point input 500. That is what lets one trained model handle every input size.

Copying: mixing generation with pointing

Summaries and translations must reproduce names, numbers and rare words, which a closed vocabulary either lacks or models badly. A copy mechanism keeps the generator's softmax over the vocabulary and adds a pointer over the source tokens w1,…,wnw_1,\dots,w_n, so that any word in the input can be produced.

Predict before you look

At one step pgen=0.3p_{\text{gen}}=0.3. The name "Okonkwo" is not in the vocabulary, and it appears twice in the source, with attention weights 0.50.5 and 0.20.2. What is P(Okonkwo)P(\text{Okonkwo})?

Show the answer

0.49

Pvocab=0P_{\text{vocab}}=0, so only the copy term counts, and the attention on both occurrences adds up: (1−0.3)×(0.5+0.2)=0.49(1-0.3)\times(0.5+0.2)=0.49. A model with a closed vocabulary could at best output an unknown-word token here.

DerivationWhat the mixture does in training
  1. ∑wP(w)=pgen∑wPvocab(w)+(1−pgen)∑i=1nait=pgen+(1−pgen)=1\sum_wP(w)=p_{\text{gen}}\sum_wP_{\text{vocab}}(w)+(1-p_{\text{gen}})\sum_{i=1}^na^t_i=p_{\text{gen}}+(1-p_{\text{gen}})=1

    The mixture is a distribution over the extended vocabulary, since both components are:

  2. ∂log⁡P(w∗)∂pgen=Pvocab(w∗)−∑i:wi=w∗aitP(w∗)\frac{\partial\log P(w^*)}{\partial p_{\text{gen}}}=\frac{P_{\text{vocab}}(w^*)-\sum_{i:w_i=w^*}a^t_i}{P(w^*)}

    Differentiate the log-likelihood of the target word w∗w^* with respect to the switch. It moves toward whichever component explains the target better:

  3. P(w∗)=(1−pgen)∑i: wi=w∗ait(w∗∉V)P(w^*)=(1-p_{\text{gen}})\sum_{i:\,w_i=w^*}a^t_i\qquad(w^*\notin\mathcal V)

    For an out-of-vocabulary target the first term vanishes, so training lowers pgenp_{\text{gen}} and pushes attention onto the target's occurrences. See et al. report that pgenp_{\text{gen}} rose from about 0.300.30 to 0.530.53 during training, but averaged only 0.170.17 at test time: without word-by-word supervision the model mostly copies.

Two other designs. CopyNet (Gu, Lu, Li & Li, 2016) scores generating each vocabulary word, ψg(v)=v⊤Wost\psi_g(v)=\mathbf v^\top W_o\mathbf s_t, and copying each source position, ψc(xj)=tanh⁡(hj⊤Wc) st\psi_c(x_j)=\tanh(\mathbf h_j^\top W_c)\,\mathbf s_t, and normalizes both kinds of score with a single shared softmax, so the two modes compete directly instead of being weighed by a separate switch. The pointer sentinel model of Merity, Xiong, Bradbury and Socher (2017), a language model, appends a "sentinel" to the pointer's softmax over recent words; the weight the sentinel receives becomes the share handed to the vocabulary softmax.

Coverage. Attention models repeat themselves, attending again and again to the same source span. See et al. keep a coverage vector, the attention accumulated so far, ct=∑t′<tat′\mathbf c^t=\sum_{t'<t}\mathbf a^{t'}, feed it into the attention scores, eit=v⊤tanh⁡(Whhi+Wsst+wccit+b)e^t_i=\mathbf v^\top\tanh(W_h\mathbf h_i+W_s\mathbf s_t+\mathbf w_cc^t_i+b), and add a loss on the overlap between new and old attention:

Lt=−log⁡P(wt∗)+λ∑imin⁡(ait, cit),0≤∑imin⁡(ait,cit)≤∑iait=1.\loss_t=-\log P(w^*_t)+\lambda\sum_i\min\big(a^t_i,\,c^t_i\big),\qquad0\le\sum_i\min(a^t_i,c^t_i)\le\sum_ia^t_i=1.

The penalty is zero exactly when the new attention avoids every position already covered. It targets repetition without demanding that every source word be covered, which suits summaries; coverage penalties for translation instead reward each source word's total attention up to one, as in the decoding penalty of Wu et al. (2016).

Monotonic attention: attending online

Soft attention needs the whole input before the first output and costs O(T)\order{T} per output step. Simultaneous translation and online speech recognition need the opposite: emit while the input streams in, with the attended position only moving forward, as in Alignment-Free Training: CTC & Transducers. Monotonic attention (Raffel, Luong, Liu, Weiss & Eck, 2017) makes the attention itself such a scan.

DerivationTraining through the expected alignment
  1. αi,j=pi,j∑k=1jαi−1,k∏l=kj−1(1−pi,l)\alpha_{i,j}=p_{i,j}\sum_{k=1}^{j}\alpha_{i-1,k}\prod_{l=k}^{j-1}\big(1-p_{i,l}\big)

    Sampled stops cannot be backpropagated through, so training uses the expected context ∑jαi,jhj\sum_j\alpha_{i,j}\mathbf h_j. The scan for step ii starts at kk with probability αi−1,k\alpha_{i-1,k}, passes k,…,j−1k,\dots,j-1 without stopping and stops at jj:

  2. qi,j=(1−pi,j−1) qi,j−1+αi−1,j,αi,j=pi,j qi,jq_{i,j}=(1-p_{i,j-1})\,q_{i,j-1}+\alpha_{i-1,j},\qquad\alpha_{i,j}=p_{i,j}\,q_{i,j}

    Pulling out the last factor of each product gives a linear recursion over jj, with qi,j=αi,j/pi,jq_{i,j}=\alpha_{i,j}/p_{i,j} the probability that the scan reaches position jj:

  3. αi,j=pi,j Πi,j∑k≤jαi−1,kΠi,k\alpha_{i,j}=p_{i,j}\,\Pi_{i,j}\sum_{k\le j}\frac{\alpha_{i-1,k}}{\Pi_{i,k}}

    With the exclusive cumulative product Πi,j=∏l<j(1−pi,l)\Pi_{i,j}=\prod_{l<j}(1-p_{i,l}), every product above is a ratio Πi,j/Πi,k\Pi_{i,j}/\Pi_{i,k}, which gives a closed form computable in parallel over jj with a cumulative product and a cumulative sum (the division needs care when Π\Pi underflows):

  4. ∑j=1Tαi,j≤1,pi,j∈{0,1} ⟹ expected and hard attention coincide\sum_{j=1}^T\alpha_{i,j}\le1,\qquad p_{i,j}\in\{0,1\}\ \Longrightarrow\ \text{expected and hard attention coincide}

    The weights sum to at most one; the remainder is the probability that the scan stops nowhere. Training with the expectation matches the hard scan used at test time only if every pi,jp_{i,j} is near 00 or 11, so Raffel et al. add Gaussian noise before the sigmoid during training, which drives the energies to large magnitudes.

Check your understanding

At the first output step the scan starts at position 1 (α0,1=1\alpha_{0,1}=1), and p1,j=0.5p_{1,j}=0.5 for j=1,2,3j=1,2,3. What is α1,3\alpha_{1,3}, the probability of attending to position 3?

  1. 0.50.5
  2. 1/31/3
  3. 0.250.25
  4. 0.1250.125
Show the answer

D. 0.1250.125

The scan must pass positions 1 and 2 and stop at 3: (1−0.5)(1−0.5)(0.5)=0.125(1-0.5)(1-0.5)(0.5)=0.125. The weights over positions 1, 2, 3 are 0.5,0.25,0.1250.5,0.25,0.125, and the remaining 0.1250.125 is the chance of stopping nowhere among these three.

Hard monotonic attention reads one encoder state per output, which is too rigid where a few frames together determine a token. Monotonic chunkwise attention (MoChA; Chiu & Raffel, 2018) lets the hard scan choose where to stop, then applies soft attention over the chunk of ww states ending there; w=1w=1 recovers hard monotonic attention, and the expected version is computed with moving sums. In online speech recognition MoChA matched an offline soft-attention model with chunks of only two encoder states.

Simultaneous translation needs more freedom, because word order differs between languages. MILk (Arivazhagan et al., 2019) lets a hard monotonic head decide when to read more of the source and a soft head attend to everything read so far, and monotonic multihead attention (Ma, Pino, Cross, Puzon & Gu, 2020) brings the scan into every encoder–decoder attention head of a transformer, with losses that control the latency of the heads. All of these trade quality against delay, and how to measure latency fairly is itself part of the research.

Copying in transformers, and what a fixed state cannot copy

A decoder-only transformer needs no special copy mechanism: its attention can read any earlier token. Trained language models implement copying with two heads in different layers. A previous-token head writes into each position information about the token before it. An induction head then uses the current token as a query against those shifted keys, so it attends to the position just after an earlier occurrence of the current token, and its output weights copy that token forward: [A][B]…[A]→[B][A][B]\dots[A]\to[B]. The attention pattern is the pointer and the copy is a linear map, a pointer network assembled from two attention layers (Olsson et al., 2022).

Olsson et al. found that induction heads form abruptly early in training, at the same time as a jump in the models' ability to use their context, and argued with several lines of evidence that they may implement much of in-context learning; the evidence is most direct for small attention-only models. Copying by attention has a price that pointer networks share: every earlier token stays available, in a cache that grows with the input. A model that compresses the input into a state of fixed size, such as an RNN without attention or a state space model, cannot copy arbitrarily long strings, however it is trained; Hybrid Models & the Limits of Fixed-Size Memory proves this and measures the gap.

Key takeaways

  • A pointer network uses the attention distribution over input positions as its output distribution, so the output vocabulary grows with the input; on convex hulls it extrapolated in area but not in exactness, and on routing it needed constrained decoding or reinforcement learning.
  • The pointer-generator mixes generation and copying, P(w)=pgenPvocab(w)+(1−pgen)∑i:wi=waiP(w)=p_{\text{gen}}P_{\text{vocab}}(w)+(1-p_{\text{gen}})\sum_{i:w_i=w}a_i, which gives out-of-vocabulary source words probability; CopyNet shares one softmax between the modes, and a coverage loss ∑imin⁡(ait,cit)≤1\sum_i\min(a^t_i,c^t_i)\le1 curbs repetition.
  • Hard monotonic attention scans forward and stops, online and in linear time; it is trained through the expected alignment αi,j=pi,j∑k≤jαi−1,k∏l=kj−1(1−pi,l)\alpha_{i,j}=p_{i,j}\sum_{k\le j}\alpha_{i-1,k}\prod_{l=k}^{j-1}(1-p_{i,l}), with chunkwise (MoChA) and multihead variants for speech and simultaneous translation.
  • Transformers copy with induction heads, pointing past an earlier occurrence through a previous-token head; copying by attention keeps a cache that grows with the input, which fixed-size states cannot match.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

In a pointer-generator network, pgen=0.25p_{\text{gen}}=0.25. The target word is not in the vocabulary, and it occurs once in the source, with attention weight 0.60.6. What probability does the model assign to it?

  1. 00
  2. 0.150.15
  3. 0.450.45
  4. 0.60.6
Show the answer

C. 0.450.45

P(w)=pgenPvocab(w)+(1−pgen)∑i:wi=wai=0.25×0+0.75×0.6=0.45P(w)=p_{\text{gen}}P_{\text{vocab}}(w)+(1-p_{\text{gen}})\sum_{i:w_i=w}a_i=0.25\times0+0.75\times0.6=0.45. The copy term is how an out-of-vocabulary word gets probability at all.

Question 2

The coverage loss at step tt is ∑imin⁡(ait,cit)\sum_i\min(a^t_i,c^t_i), with ct\mathbf c^t the attention summed over earlier steps. When is it zero?

  1. When the new attention puts no weight on any position that earlier attention covered
  2. When every source position has been attended to exactly once by the end
  3. When the attention at step tt is uniform
  4. Never, since attention weights are positive
Show the answer

A. When the new attention puts no weight on any position that earlier attention covered

Each term is zero exactly when ait=0a^t_i=0 or cit=0c^t_i=0, so the loss vanishes when the new attention avoids the covered positions. It penalizes re-attending, the cause of repetition, without requiring full coverage; and it is at most ∑iait=1\sum_ia^t_i=1.

Question 3

Why do Raffel et al. add noise before the sigmoid when training monotonic attention?

  1. To regularize the encoder against overfitting
  2. To push the stopping probabilities toward 0 or 1, so the expected alignment used in training matches the hard scan used at test time
  3. To make the attention weights sum to exactly one
  4. To let the scan move backward when the noise is negative
Show the answer

B. To push the stopping probabilities toward 0 or 1, so the expected alignment used in training matches the hard scan used at test time

Training differentiates through the expected alignment, while test time samples (or thresholds) discrete stops. The two agree when every pi,j∈{0,1}p_{i,j}\in\{0,1\}; noise in the pre-sigmoid activations rewards energies of large magnitude, whose sigmoids saturate.

Question 4

How does an induction head continue the pattern [A][B]…[A][A][B]\dots[A]?

  1. It attends to the earlier [A][A] and copies [A][A] again
  2. It stores every bigram in a fixed-size recurrent state
  3. It uses a copy switch pgenp_{\text{gen}} that it learns from the vocabulary
  4. It uses keys shifted by a previous-token head to attend to the token after the earlier [A][A], namely [B][B], and copies it
Show the answer

D. It uses keys shifted by a previous-token head to attend to the token after the earlier [A][A], namely [B][B], and copies it

A previous-token head writes "the token before me" into each position. The induction head's query (the current [A][A]) matches the position whose predecessor was [A][A], which holds [B][B], and its output weights copy [B][B]: pointing plus copying, built from two attention layers.

Further reading

  • O. Vinyals, M. Fortunato & N. Jaitly, "Pointer networks," NeurIPS (2015).
  • J. Gu, Z. Lu, H. Li & V. O. K. Li, "Incorporating copying mechanism in sequence-to-sequence learning," ACL (2016).
  • A. See, P. J. Liu & C. D. Manning, "Get to the point: Summarization with pointer-generator networks," ACL (2017).
  • C. Raffel, M.-T. Luong, P. J. Liu, R. J. Weiss & D. Eck, "Online and linear-time attention by enforcing monotonic alignments," ICML (2017).
  • C.-C. Chiu & C. Raffel, "Monotonic chunkwise attention," ICLR (2018).
  • C. Olsson, N. Elhage, N. Nanda et al., "In-context learning and induction heads," Transformer Circuits Thread (2022).