Attention and Augmented Recurrent Neural Networks
=================================================

 dt-byline {
 font-size: 12px;
 line-height: 18px;
 display: block;
 border-top: 1px solid rgba(0, 0, 0, 0.1);
 border-bottom: 1px solid rgba(0, 0, 0, 0.1);
 color: rgba(0, 0, 0, 0.5);
 padding-top: 12px;
 padding-bottom: 12px;
 }
 dt-article.centered dt-byline {
 text-align: center;

 }
 dt-byline a,
 dt-article dt-byline a {
 text-decoration: none;
 border-bottom: none;
 }
 dt-article dt-byline a:hover {
 text-decoration: underline;
 border-bottom: none;
 }
 dt-byline .authors {
 text-align: left;
 }
 dt-byline .name {
 display: inline;
 text-transform: uppercase;
 }
 dt-byline .affiliation {
 display: inline;
 }
 dt-byline .date {
 display: block;
 text-align: left;
 }
 dt-byline .year, dt-byline .month {
 display: inline;
 }
 dt-byline .citation {
 display: block;
 text-align: left;
 }
 dt-byline .citation div {
 display: inline;
 }

 @media(min-width: 768px) {
 dt-byline {
 }
 }

 @media(min-width: 1080px) {
 dt-byline {
 border-bottom: none;
 margin-bottom: 70px;
 }

 dt-byline a:hover {
 color: rgba(0, 0, 0, 0.9);
 }

 dt-byline .authors {
 display: inline-block;
 }

 dt-byline .author {
 display: inline-block;
 margin-right: 12px;
 /\*padding-left: 20px;\*/
 /\*border-left: 1px solid #ddd;\*/
 }

 dt-byline .affiliation {
 display: block;
 }

 dt-byline .author:last-child {
 margin-right: 0;
 }

 dt-byline .name {
 display: block;
 }

 dt-byline .date {
 border-left: 1px solid rgba(0, 0, 0, 0.1);
 padding-left: 15px;
 margin-left: 15px;
 display: inline-block;
 }
 dt-byline .year, dt-byline .month {
 display: block;
 }

 dt-byline .citation {
 border-left: 1px solid rgba(0, 0, 0, 0.15);
 padding-left: 15px;
 margin-left: 15px;
 display: inline-block;
 }
 dt-byline .citation div {
 display: block;
 }
 }

[Chris Olah](http://colah.github.io)
[Google Brain](http://g.co/brain)

[Shan Carter](http://shancarter.com)
[Google Brain](http://g.co/brain)

Sept. 8
2016

[Citation:
Olah & Carter, 2016](#citation)

Recurrent neural networks are one of the staples of deep learning, allowing neural networks to work with sequences of data like text, audio and video. They can be used to boil a sequence down into a high-level understanding, to annotate sequences, and even to generate new sequences from scratch!

rnn

x0
y0
x1
y1
x2
y2
x3
y3

One cell...

can be used over...

and over...

and over...

x4
y4

again.

The basic RNN design struggles with longer sequences, but a special variant—[“long short-term memory” networks](http://colah.github.io/posts/2015-08-Understanding-LSTMs/) [1]—can even work with these. Such models have been found to be very powerful, achieving remarkable results in many tasks including translation, voice recognition, and image captioning. As a result, recurrent neural networks have become very widespread in the last few years.

As this has happened, we’ve seen a growing number of attempts to augment RNNs with new properties. Four directions stand out as particularly exciting:

[![](assets/rnn_preview_ntm.svg)
**Neural Turing Machines** have external memory that they can read and write to.](#neural-turing-machines)
[![](assets/rnn_preview_ai.svg)
**Attentional Interfaces** allow RNNs to focus on parts of their input.](#attentional-interfaces)
[![](assets/rnn_preview_act.svg)
**Adaptive Computation Time** allows for varying amounts of computation per step.](#adaptive-computation-time)
[![](assets/rnn_preview_np.svg)
**Neural Programmers** can call functions, building programs as they run.](#neural-programmer)

 #previews a {
 text-decoration: none;
 overflow: hidden;
 margin-bottom: 12px;
 display: block;
 border-bottom: 1px solid rgba(0, 0, 0, 0.1);
 margin-bottom: 12px;
 padding-bottom: 12px;

 }
 #previews figcaption {
 margin-left: 100px;
 }
 #previews svg, #previews img {
 width: 80px;
 float: left;
 }

 @media(min-width: 768px) {
 #previews {
 overflow: hidden;
 margin-top: 48px;
 margin-bottom: 48px;
 }
 #previews figcaption {
 margin-left: 0;
 }
 #previews figcaption b {
 display: block;
 }
 #previews figcaption b span {
 display: block;
 }
 #previews a {
 position: relative;
 float: left;
 width: 19%;
 margin-right: 3.6%;
 padding-right: 3.6%;
 border-right: 1px solid rgba(0, 0, 0, 0.05);
 border-bottom: none;
 margin-bottom: 0;
 padding-bottom: 0;
 }
 #previews a:last-child {
 margin-right: 0;
 padding-right: 0;
 border-right: 0;
 }
 #previews svg, #previews img {
 margin-bottom: 18px;
 display: block;
 width: 100%;
 float: none;
 }
 }

 @media(min-width: 1024px) {
 #previews {
 margin-top: 90px;
 margin-bottom: 90px;
 }
 }

Individually, these techniques are all potent extensions of RNNs, but the really striking thing is that they can be combined, and seem to just be points in a broader space. Further, they all rely on the same underlying trick—something called attention—to work.

Our guess is that these “augmented RNNs” will have an important role to play in extending deep learning’s capabilities over the coming years.

---

Neural Turing Machines
----------------------

Neural Turing Machines [2] combine a RNN with an external memory bank. Since vectors are the natural language of neural networks, the memory is an array of vectors:

rnn

Memory is an array of vectors.

Network A writes and reads from this memory each step.

x0

y0

x1

y1

x2

y2

x3

y3

But how does reading and writing work? The challenge is that we want to make them differentiable. In particular, we want to make them differentiable with respect to the location we read from or write to, so that we can learn where to read and write. This is tricky because memory addresses seem to be fundamentally discrete. NTMs take a very clever solution to this: every step, they read and write everywhere, just to different extents.

As an example, let’s focus on reading. Instead of specifying a single location, the RNN outputs an “attention distribution” that describes how we spread out the amount we care about different memory positions. As such, the result of the read operation is a weighted sum.

rnn

attention

memory

The RNN gives an attention distribution which describe how we spread out the amount we care about different memory positions.

The read result is a weighted sum.

Similarly, we write everywhere at once to different extents. Again, an attention distribution describes how much we write at every location. We do this by having the new value of a position in memory be a convex combination of the old memory content and the write value, with the position between the two decided by the attention weight.

rnn

attention

old memory

new memory

write value

The RNN gives an attention distribution, describing how much we should change each memory position towards the write value.

Instead of writing to one location, we write everywhere, just to different extents.

"use strict";
(function() {

 function appendArrowhead(selection) {
 selection.append("marker")
 .attr("id", "arrowhead")
 .attr("viewBox", "0 -5 10 10")
 .attr("refX", 5)
 .attr("refY", 0)
 .attr("markerWidth", 10)
 .attr("markerHeight", 10)
 .attr("orient", "auto")
 .append("path")
 .attr("d", "M0,-5L5,0L0,5")
 .style("fill", "none")
 .style("stroke", "grey");
 }

 var vectorScale = d3.scaleLinear()
 .domain([0, 1])
 .range([-14, 14]);

 var memoryData = [
 {x: 0.9, y: 0.9},
 {x: 0.8, y: 0.8},
 {x: 0.1, y: 0.9},
 {x: 0.4, y: 0.2},
 {x: 0.2, y: 0.2},
 {x: 0.4, y: 0.3},
 {x: 0.1, y: 0.5}
 ];

 var writeData = {x: 0.9, y: 0};

 //
 // Read
 //
 var nodeWidth = 36;
 var readHtml = d3.selectAll("#rnn-read");
 var svg = readHtml.select("svg");
 var result = svg.select("#read-result").style("opacity", 0);
 var resultBBox = result.node().getBBox();
 var memory = svg.selectAll("#memory use");
 var memoryBBox = svg.select("#memory").node().getBBox();
 var attention = svg.selectAll("#attention use");
 var attentionBBox = svg.select("#attention").node().getBBox();
 var path = svg.selectAll("#paths path");

 appendArrowhead(svg);
 var resultArrow = svg.append("line")
 .attr("class", "result-line")
 .attr("marker-end", "url(#arrowhead)")
 .style("stroke", "grey");

 memory.data(memoryData)
 .each(function(d, i) {
 this.style.opacity = 0;
 d.top = memoryBBox.y;
 d.left = memoryBBox.x + nodeWidth \* i;
 d.width = nodeWidth;
 });

 var memoryVectors = svg.selectAll(".vector")
 .data(memoryData)
 .enter().append("line")
 .attr("class", "vector")
 .attr("transform", function(d) {
 return `translate(${d.left + d.width / 2 - vectorScale(d.x) / 2}, ${d.top + d.width / 2 - vectorScale(d.y) / 2})`
 })
 .attr("x2", function(d) { return vectorScale(d.x); })
 .attr("y2", function(d) { return vectorScale(d.y); })
 .attr("marker-end", "url(#arrowhead)")
 .style("stroke", "grey");

 function updateReadAttention(data) {
 attention.data(data)
 .style("opacity", function(d) { return d + 0.05; });

 path.data(data)
 .style("stroke-opacity", function(d) { return d + 0.1; });

 var resultX = d3.sum(memoryData, function(d, i) { return d.x \* data[i]; }) / d3.sum(data);
 var resultY = d3.sum(memoryData, function(d, i) { return d.y \* data[i]; }) / d3.sum(data);

 resultArrow
 .attr("transform",`translate(${resultBBox.x + resultBBox.width / 2 - vectorScale(resultX) / 2}, ${resultBBox.y + resultBBox.width / 2 - vectorScale(resultY) / 2})`)
 .attr("x2", function(d) { return vectorScale(resultX); })
 .attr("y2", function(d) { return vectorScale(resultY); });
 }

 var length = memory.size();
 var attentionData = d3.range(length).map(function() { return Math.random(); });
 updateReadAttention(attentionData);

 readHtml.on("mousemove", function() {
 var data = [];
 attention.each(function() {
 var bbox = this.getBoundingClientRect()
 var distance = Math.abs(bbox.left - d3.event.clientX + bbox.width / 2);
 data.push(Math.exp(-distance / 25));
 });
 data = data.map(function(d) { return d / d3.sum(data); });
 updateReadAttention(data);
 });

 var initReadData = d3.range(attention.size()).map(function(d) { return Math.exp(-d); });
 initReadData = initReadData.map(function(d) { return d / d3.sum(initReadData); });
 updateReadAttention(initReadData);

 //
 // Write
 //

 var writeHtml = d3.selectAll("#rnn-write");
 var writeSvg = writeHtml.select("svg");
 var writeMemory = writeSvg.selectAll("#memory use");
 var writeMemoryBBox = writeSvg.select("#memory").node().getBBox();
 var writeNewMemory = writeSvg.selectAll("#new-memory use");
 var writeNewMemoryBBox = writeSvg.select("#new-memory").node().getBBox();
 var writeAttention = writeSvg.selectAll("#attention use");
 var writeAttentionBBox = writeSvg.select("#attention").node().getBBox();
 var writePath = writeSvg.selectAll("#paths path");
 var writeResult = writeSvg.select("#write-result").style("opacity", 0);
 var writeResultBBox = writeResult.node().getBBox();
 var newMemoryData = memoryData.map(function(){ return {}; });

 appendArrowhead(writeSvg);
 var writeArrow = writeSvg.append("line")
 .attr("class", "write-line")
 .attr("marker-end", "url(#arrowhead)")
 .style("stroke", "grey")
 .attr("transform", "translate(" + (writeResultBBox.x + writeResultBBox.width / 2 - vectorScale(writeData.x) / 2) + ", " + (writeResultBBox.y + writeResultBBox.width / 2 - vectorScale(writeData.y) / 2) + ")")
 .attr("x2", vectorScale(writeData.x))
 .attr("y2", vectorScale(writeData.y));

 writeMemory.data(memoryData)
 .each(function(d, i) {
 this.style.opacity = 0;
 d.top = writeMemoryBBox.y;
 d.left = writeMemoryBBox.x + i \* nodeWidth;
 d.width = nodeWidth;
 });

 var writeMemoryVectors = writeSvg.selectAll(".vector")
 .data(memoryData)
 .enter().append("line")
 .attr("class", "vector")
 .attr("transform", function(d) {
 return "translate(" + (d.left + d.width / 2 - vectorScale(d.x) / 2) + ", " + (d.top + d.width / 2 - vectorScale(d.y) / 2) + ")";
 })
 .attr("x2", function(d) { return vectorScale(d.x); })
 .attr("y2", function(d) { return vectorScale(d.y); })
 .attr("marker-end", "url(#arrowhead)")
 .style("stroke", "grey");

 writeNewMemory.data(newMemoryData)
 .each(function(d, i) {
 this.style.opacity = 0;
 d.top = writeNewMemoryBBox.y;
 d.left = writeNewMemoryBBox.x + i \* nodeWidth;
 d.width = nodeWidth;
 });

 var writeNewMemoryVectors = writeSvg.selectAll(".new-vector")
 .data(newMemoryData)
 .enter().append("line")
 .attr("class", "new-vector")
 .attr("marker-end", "url(#arrowhead)")
 .style("stroke", "grey");

 function updateWriteAttention(data) {
 newMemoryData.forEach(function(d, i) {
 d.x = (memoryData[i].x + writeData.x \* data[i]) / (1 + data[i]);
 d.y = (memoryData[i].y + writeData.y \* data[i]) / (1 + data[i]);
 });
 writeNewMemoryVectors
 .attr("transform", function(d) {
 return "translate(" + (d.left + d.width / 2 - vectorScale(d.x) / 2) + ", " + (d.top + d.width / 2 - vectorScale(d.y) / 2) + ")";
 })
 .attr("x2", function(d) { return vectorScale(d.x); })
 .attr("y2", function(d) { return vectorScale(d.y); });

 writeAttention.data(data)
 .style("opacity", function(d) { return d + 0.05; });

 writePath.data(data)
 .style("stroke-opacity", function(d) { return d + 0.1; });
 }

 writeHtml.on("mousemove", function() {
 var data = [];
 writeAttention.each(function() {
 var bbox = this.getBoundingClientRect()
 var distance = Math.abs(bbox.left - d3.event.clientX + bbox.width / 2);
 data.push(Math.exp(-distance / 25));
 });
 data = data.map(function(d) { return d / d3.sum(data); });
 updateWriteAttention(data);
 });

 var initWriteData = d3.range(writeAttention.size()).map(function(d) { return Math.exp(-d); });
 initWriteData = initWriteData.map(function(d) { return d / d3.sum(initWriteData); });
 updateWriteAttention(initWriteData);

})();

But how do NTMs decide which positions in memory to focus their attention on? They actually use a combination of two different methods: content-based attention and location-based attention. Content-based attention allows NTMs to search through their memory and focus on places that match what they’re looking for, while location-based attention allows relative movement in memory, enabling the NTM to loop.

rnn

First, the controller gives a query vector and each memory entry is scored for similarity with the query.

The scores are then converted into a distribution using softmax.

Next, we interpolate the attention from the previous time step.

We convolve the attention with a shift filter—this allows the controller to move its focus.

Finally, we sharpen the attention distribution. This final attention distribution is fed to the read or write operation.

The RNN gives an attention distribution, describing how much we should change each memory position towards the write value.

memory

Blue shows high similarity, pink high dissimilarity.

interpolation amount

shift filter

RNN controller

attention mechanism

query vector

attention from previous step

new attention distribution

"use strict";
//
// Data
//

var vectorScale = d3.scaleLinear().domain([0, 1]).range([-14, 14]);

var memoryData = [{ x: 0.4, y: 0.2 }, { x: 0.2, y: 0.2 }, { x: 0.1, y: 0.9 }, { x: 0.9, y: 0.9 }, { x: 0.4, y: 0.3 }];
var interpolationData = [0.3];
var shiftData = [0, 0.2, 0.8];
var previousAttentionData = [0, 0.2, 0, 0.2, 0.6];

//
// DOM
//

var nodeWidth = 36;
var html = d3.selectAll("#rnn-write-detail");
var svg = html.select("svg");
var query = svg.selectAll("#query").style("opacity", 0);
var memory = svg.selectAll("#memory use").style("opacity", 0);
var memoryBBox = svg.select("#memory").node().getBBox();
var shift = svg.selectAll("#shift use");

//
// Render
//

// Store positions of vectors
function cachePositions(selection) {
 selection.each(function (d) {
 var bBox = this.getBBox();
 d.top = bBox.y;
 d.left = bBox.x;
 d.width = bBox.width;
 });
}

// Render new vector lines
function renderVector(selection) {
 selection.attr("transform", function (d) {
 return "translate(" + (d.left + d.width / 2 - vectorScale(d.x) / 2) + ", " + (d.top + d.width / 2 - vectorScale(d.y) / 2) + ")";
 }).attr("x2", function (d) {
 return vectorScale(d.x);
 }).attr("y2", function (d) {
 return vectorScale(d.y);
 }).attr("marker-end", "url(#arrowhead)").style("stroke", "grey");
}

// Memory
memory.data(memoryData);
memory.each(function(d, i) {
 d.top = memoryBBox.y;
 d.left = memoryBBox.x + nodeWidth \* i;
 d.width = nodeWidth;
})
// cachePositions(memory);
var memoryVector = svg.selectAll(".memory-vector").data(memoryData).enter().append("line").attr("class", "memory-vector");
renderVector(memoryVector);

var queryData = [{ x: 0.7, y: 0.8 }];
query.data(queryData);
cachePositions(query);

var queryVector = svg.selectAll(".query-vector").data(queryData).enter().append("line").attr("class", "query-vector");

var clamp = d3.scaleLinear().clamp(true);

function redraw() {

 renderVector(queryVector);

 // Dot
 var dotData = memoryData.map(function (v) {
 return 2 \* (v.x - 0.5) \* 2 \* (queryData[0].x - 0.5) + 2 \* (v.y - 0.5) \* 2 \* (queryData[0].y - 0.5);
 });
 svg.selectAll("#dot use").data(dotData).attr("xlink:href", function (d) {
 return d < 0 ? "#array-negative-value" : "#array-positive-value";
 }).style("opacity", function (d) {
 return Math.abs(d);
 });

 // Softmax
 var expDotData = dotData.map(Math.exp);
 var softmaxData = expDotData.map(function (x) {
 return x / d3.sum(expDotData);
 });
 svg.selectAll("#softmax use").data(softmaxData).style("opacity", function (d) {
 return d;
 });

 // Interpolate
 svg.selectAll("#previous use").data(previousAttentionData).style("opacity", function (d) {
 return d;
 });

 svg.selectAll("#interpolate-amount").data(interpolationData).style("opacity", function (d) {
 return d;
 });

 var interpolateData = previousAttentionData.map(function (d, i) {
 return interpolationData \* d + (1 - interpolationData) \* softmaxData[i];
 });
 svg.selectAll("#interpolate use").data(interpolateData).style("opacity", function (d) {
 return d;
 });

 // Convolve
 shift.data(shiftData).style("opacity", function (d) {
 return d;
 });

 var convolveData = dotData.map(function (x) {
 return 0;
 });
 for (var n in shiftData) {
 for (var i in convolveData) {
 if (i - (1 - n) >= 0) {
 convolveData[i - (1 - n)] += shiftData[n] \* interpolateData[i];
 }
 }
 }
 // = dotData;
 svg.selectAll("#convolve use").data(convolveData).style("opacity", function (d) {
 return d;
 });

 // Sharpen
 var sharpenData = convolveData.map(function (x) {
 return x \* x;
 });
 sharpenData = sharpenData.map(function (x) {
 return x / d3.sum(sharpenData);
 });
 svg.selectAll("#new-attention use").data(sharpenData).style("opacity", function (d) {
 return d;
 });
}

svg.select("#query-hover").on("mousemove", function () {
 var bbox = svg.select("#query").node().getBoundingClientRect();
 var x = d3.event.clientX - bbox.left - bbox.width / 2;
 var y = d3.event.clientY - bbox.top - bbox.height / 2;
 //TODO: this clamping is awkward
 queryData[0].x = clamp((x + 25) / 50);
 queryData[0].y = clamp((y + 25) / 50);
 redraw();
});
svg.select("#interpolate-hover").on("mousemove", function () {
 var bbox = svg.select("#interpolate-amount").node().getBoundingClientRect();
 interpolationData = [Math.max(0, Math.min(1, (d3.event.clientX - bbox.left) / bbox.width))];
 redraw();
});
// .on("mouseout", function() {
// interpolationData = [0.3];
// redraw();
// });

svg.select("#shift-hover").on("mousemove", function () {
 // shiftData = [0, 0.2, 0.8];
 shiftData = [];
 shift.each(function () {
 var bbox = this.getBoundingClientRect();
 var distance = Math.abs(bbox.left - d3.event.clientX + bbox.width / 2);
 shiftData.push(Math.exp(-distance / 25));
 });
 shiftData = shiftData.map(function (d) {
 return d / d3.sum(shiftData);
 });
 redraw();
});
redraw();

This capability to read and write allows NTMs to perform many simple algorithms, previously beyond neural networks. For example, they can learn to store a long sequence in memory, and then loop over it, repeating it back repeatedly. As they do this, we can watch where they read and write, to better understand what they’re doing:

![](assets/NTM-Copy-ReadWrite.svg)
See more experiments in [3]. This figure is based on the Repeat Copy experiment.

They can also learn to mimic a lookup table, or even learn to sort numbers (although they kind of cheat)! On the other hand, they still can’t do many basic things, like add or multiply numbers.

Since the original NTM paper, there have been a number of exciting papers exploring similar directions. The Neural GPU [4] overcomes the NTM’s inability to add and multiply numbers. Zaremba & Sutskever [5] train NTMs using reinforcement learning instead of the differentiable read/writes used by the original. Neural Random Access Machines [6] work based on pointers. Some papers have explored differentiable data structures, like stacks and queues [7, 8]. And memory networks [9, 10] are another approach to attacking similar problems.

In some objective sense, many of the tasks these models can perform—such as learning how to add numbers—aren’t that objectively hard. The traditional program synthesis community would eat them for lunch. But neural networks are capable of many other things, and models like the Neural Turing Machine seem to have knocked away a very profound limit on their abilities.

### Code

There are a number of open source implementations of these models. Open source implementations of the Neural Turing Machine include [Taehoon Kim’s](https://github.com/carpedm20/NTM-tensorflow) (TensorFlow), [Shawn Tan’s](https://github.com/shawntan/neural-turing-machines) (Theano), [Fumin’s](https://github.com/fumin/ntm) (Go), [Kai Sheng Tai’s](https://github.com/kaishengtai/torch-ntm) (Torch), and [Snip’s](https://github.com/snipsco/ntm-lasagne) (Lasagne). Code for the Neural GPU publication was open sourced and put in the [TensorFlow Models repository](https://github.com/tensorflow/models/tree/master/neural_gpu). Open source implementations of Memory Networks include [Facebook’s](https://github.com/facebook/MemNN) (Torch/Matlab), [YerevaNN’s](https://github.com/YerevaNN/Dynamic-memory-networks-in-Theano) (Theano), and [Taehoon Kim’s](https://github.com/carpedm20/MemN2N-tensorflow) (TensorFlow).

---

Attentional Interfaces
----------------------

When I’m translating a sentence, I pay special attention to the word I’m presently translating. When I’m transcribing an audio recording, I listen carefully to the segment I’m actively writing down. And if you ask me to describe the room I’m sitting in, I’ll glance around at the objects I’m describing as I do so.

Neural networks can achieve this same behavior using *attention*, focusing on part of a subset of the information they’re given. For example, an RNN can attend over the output of another RNN. At every time step, it focuses on different positions in the other RNN.

We’d like attention to be differentiable, so that we can learn where to focus. To do this, we use the same trick Neural Turing Machines use: we focus everywhere, just to different extents.

rnn

Network B focuses on different information from network A at every step.

The attention distribution is usually generated with content-based attention. The attending RNN generates a query describing what it wants to focus on. Each item is dot-producted with the query to produce a score, describing how well it matches the query. The scores are fed into a softmax to create the attention distribution.

rnn

The attending RNN generates a query describing what it wants to focus on.

Each item is dot producted with the query to produce a score, describing how well it matches the query. The scores are fed into a softmax to create the attention distribution.

One use of attention between RNNs is translation [11]. A traditional sequence-to-sequence model has to boil the entire input down into a single vector and then expands it back out. Attention avoids this by allowing the RNN processing the input to pass along information about each word it sees, and then for the RNN generating the output to focus on words as they become relevant.

```
0.50, 0.02, 0.04, 0.00, 0.00, 0.00, 0.00, 0.00, 0.01, 0.01, 0.00, 0.00, 0.00, 0.05, 0.05
0.14, 0.89, 0.07, 0.00, 0.00, 0.00, 0.00, 0.00, 0.01, 0.06, 0.00, 0.00, 0.00, 0.02, 0.00
0.02, 0.00, 0.56, 0.00, 0.00, 0.00, 0.00, 0.01, 0.00, 0.00, 0.00, 0.00, 0.00, 0.02, 0.00
0.00, 0.00, 0.01, 0.61, 0.02, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00
0.00, 0.00, 0.02, 0.03, 0.01, 0.21, 0.97, 0.05, 0.00, 0.00, 0.00, 0.00, 0.00, 0.01, 0.00
0.00, 0.00, 0.02, 0.07, 0.25, 0.76, 0.02, 0.04, 0.00, 0.00, 0.00, 0.00, 0.00, 0.02, 0.00
0.02, 0.04, 0.03, 0.27, 0.71, 0.02, 0.00, 0.02, 0.00, 0.00, 0.02, 0.00, 0.00, 0.05, 0.01
0.02, 0.00, 0.07, 0.00, 0.00, 0.00, 0.00, 0.60, 0.40, 0.01, 0.04, 0.00, 0.00, 0.13, 0.01
0.13, 0.02, 0.02, 0.00, 0.01, 0.00, 0.00, 0.23, 0.52, 0.91, 0.07, 0.00, 0.00, 0.10, 0.00
0.04, 0.00, 0.01, 0.00, 0.00, 0.00, 0.00, 0.01, 0.03, 0.00, 0.67, 0.00, 0.00, 0.16, 0.02
0.02, 0.00, 0.04, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.14, 0.96, 0.00, 0.02, 0.07
0.02, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.02, 0.02, 1.00, 0.02, 0.03
0.02, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.01, 0.00, 0.01, 0.00, 0.00, 0.32, 0.11
0.04, 0.00, 0.08, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.01, 0.00, 0.00, 0.04, 0.67
```

output text
network B
network A
input text

Diagram derived from Fig. 3 of [Bahdanau, *et al.* 2014](https://arxiv.org/pdf/1409.0473.pdf)
![](assets/pointer.svg)

 #attentional-ex2 svg {
 width: 100%;
 margin-bottom: 24px;
}
#attentional-ex2 .pointer {
 position: absolute;
 width: 26px;
 height: 26px;
 top: 36px;
 left: -48px;
}
#attentional-ex2 figcaption {
 text-align: center;
}
#attentional-ex2 svg .labels {
 font-size: 12px;
 fill-opacity: 0.5;
}
#attentional-ex2 .background {
 fill: rgb(240, 240, 245);
 fill-opacity: 0.8;
}
#attentional-ex2 .cell .node {
 fill: white;
 fill-opacity: 0.9;
 stroke: black;
 stroke-width: 1px;
 stroke-opacity: 0.25;
 /\*transition: stroke-opacity, 0.2s, linear;\*/
}
#attentional-ex2 .cell:hover .node {
 stroke-opacity: 1;
}
#attentional-ex2 .cell .shadow {
 fill: black;
 fill-opacity: 0.07;
}
#attentional-ex2 .cell text {
 font-size: 13px;
 fill-opacity: 0.6;
 text-anchor: middle;
 alignment-baseline: middle;
}
#attentional-ex2 .cell text.label {
 font-size: 13px;
 /\*fill-opacity: 0.9;\*/
 text-anchor: middle;
 alignment-baseline: middle;
}
#attentional-ex2 .link-group {
 transition: opacity, 0.3s, linear;
}
#attentional-ex2 .link-group .node-highlight {
 transition: stroke-opacity, 0.3s, linear;
 stroke: black;
 stroke-opacity: 0;
 fill: none;
}
#attentional-ex2 .link-group:hover .node-highlight {
 stroke-opacity: 1;
}
#attentional-ex2 .link {
 fill: none;
 stroke: rgb(131, 89, 178);
 stroke-width: 2px;
 pointer-events: none;
}
#attentional-ex2 .arrow {
 stroke: black;
 stroke-opacity: 0.6;
}
#attentional-ex2 .cell:last-child .arrow:first-of-type {
 display: none;
}

(function() {

var labelsA = [
 "the",
 "agreement",
 "on",
 "the",
 "European",
 "Economic",
 "Area",
 "was",
 "signed",
 "in",
 "August",
 "1992",
 ".",
 "<end>"
];

var labelsB = [
 "l’",
 "accord",
 "sur",
 "la",
 "zone",
 "économique",
 "européenne",
 "a",
 "été",
 "signé",
 "en",
 "août",
 "1992",
 ".",
 "<end>"
];

var data = d3.csvParseRows(d3.select("#attentional-ex2-data").text());
// console.log(data)
var linkData = [];
data.forEach(function(a, ai) {
 a.forEach(function(b, bi) {
 linkData.push({
 ai: +ai,
 bi: +bi,
 v: +data[ai][bi]
 });
 });
});

var nodeMargin = 10;
var networkMargin = 120;

var html = d3.select("#attentional-ex2");
var outerWidth = 984;//html.node().getBoundingClientRect().width;
var outerHeight = 240;//html.node().getBoundingClientRect().height;
var margin = {top: 36, right: nodeMargin, bottom: 24, left: nodeMargin};
var width = outerWidth - margin.left - margin.right;
var height = outerHeight - margin.top - margin.bottom;

var xa = d3.scaleBand()
 .domain(d3.range(labelsA.length))
 .paddingInner(0.5)
 .range([nodeMargin, width - nodeMargin]);

var xb = d3.scaleBand()
 .domain(d3.range(labelsB.length))
 .paddingInner(0.5)
 .range([nodeMargin, width - nodeMargin]);

var nodeSizeA = xa.bandwidth();
var nodeSizeB = xb.bandwidth();

var networkHeightA = nodeSizeA + nodeMargin \* 2;
var networkHeightB = nodeSizeB + nodeMargin \* 2;

var link = function(d) {
 // console.log(nodeSizeB, nodeSizeA, nodeMargin, d.bi, xb(d.bi))
 var p = "M" + (xb(d.bi) + nodeSizeB / 2) + "," + (nodeSizeB + nodeMargin)
 + "C" + (xb(d.bi) + nodeSizeB / 2) + "," + (nodeSizeB + networkMargin / 3 + nodeMargin)
 + " " + (xa(d.ai) + nodeSizeA / 2) + "," + (networkMargin - networkMargin / 3 + nodeMargin)
 + " " + (xa(d.ai) + nodeSizeA / 2) + "," + (networkMargin + nodeMargin);
 // console.log(p);
 return p;
};

html.select("svg .labels")
 .attr("transform", "translate(" + (width + nodeMargin \* 3) + ", 0)");

var svg = html.select("svg")
 .attr("viewBox", "0 0 " + outerWidth + " " + outerHeight)
 .append("g")
 .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

var networkA = svg.append("g")
 .attr("transform", "translate(0, " + networkMargin + ")");

networkA.append("rect")
 .attr("class", "background")
 .attr("width", width)
 .attr("height", nodeSizeA + 2 \* nodeMargin)
 .attr("rx", nodeMargin \* 0.7)
 .attr("ry", nodeMargin \* 0.7);

var cellA = networkA.selectAll(".cell")
 .data(labelsA)
 .enter().append("g")
 .attr("class", "cell")
 .attr("transform", function(d, i) { return "translate(" + xa(i) + ", " + nodeMargin + ")"; })
 .on("mouseover", function(d, i) {
 link.style("display", function(ld) {
 return ld.ai === i ? "" : "none";
 });
 })
 .on("mouseout", function() { link.style("display", ""); });

cellA.append("rect")
 .attr("class", "shadow")
 .attr("transform", "translate(1, 3)")
 .attr("width", nodeSizeA)
 .attr("height", nodeSizeA)
 .attr("rx", 4)
 .attr("ry", 4);

cellA.append("rect")
 .attr("class", "node")
 .attr("width", nodeSizeA)
 .attr("height", nodeSizeA)
 .attr("rx", 4)
 .attr("ry", 4);

cellA.append("line")
 .attr("class", "arrow")
 .attr("marker-start", "url(#edgeArrowheadLeft)")
 .attr("marker-end", "url(#edgeArrowhead)")
 .attr("x1", nodeSizeA + 8)
 .attr("x2", nodeSizeA + nodeMargin + 20)
 .attr("y1", nodeSizeA / 2)
 .attr("y2", nodeSizeA / 2);

cellA.append("line")
 .attr("class", "arrow")
 .attr("marker-end", "url(#edgeArrowhead)")
 .attr("transform", "translate(" + nodeSizeA / 2 + ", 0)")
 .attr("y1", nodeSizeA + nodeMargin \* 2 - 2)
 .attr("y2", nodeSizeA + 4);

cellA.append("text")
 .style("opacity", 0.8)
 .text("A")
 .attr("dx", nodeSizeA / 2)
 .attr("dy", nodeSizeA / 2 + 1);

cellA.append("text")
 .attr("class", "label")
 .attr("dx", nodeSizeA / 2)
 .attr("dy", nodeSizeA + 24 + 8)
 .text(function(d) { return d; });

cellA.append("rect")
 .style("opacity", 0)
 .attr("transform", "translate(-" + ((xa.step() - nodeSizeA) / 2) + ",-" + (nodeMargin + (networkMargin - networkHeightB) / 2) + ")")
 .attr("width", xa.step())
 .attr("height", networkHeightA + (networkMargin - networkHeightA) / 2);

//
// Network B
//

var networkB = svg.append("g");

networkB.append("rect")
 .attr("class", "background")
 .attr("width", width)
 .attr("height", nodeSizeB + 2 \* nodeMargin)
 .attr("rx", nodeMargin \* 0.7)
 .attr("ry", nodeMargin \* 0.7);

var cellB = networkB.selectAll(".cell")
 .data(labelsB)
 .enter().append("g")
 .attr("class", "cell")
 .attr("transform", function(d, i) { return "translate(" + xb(i) + "," + nodeMargin + ")"; })
 .on("mouseover", function(d, i) {
 link.style("display", function(ld) {
 return ld.bi === i ? "" : "none";
 });
 })
 .on("mouseout", function() { link.style("display", ""); });

cellB.append("rect")
 .attr("class", "shadow")
 .attr("transform", "translate(1, 3)")
 .attr("width", nodeSizeB)
 .attr("height", nodeSizeB)
 .attr("rx", 4)
 .attr("ry", 4);

cellB.append("rect")
 .attr("class", "node")
 .attr("width", nodeSizeB)
 .attr("height", nodeSizeB)
 .attr("rx", 4)
 .attr("ry", 4);

cellB.append("line")
 .attr("class", "arrow")
 .attr("marker-end", "url(#edgeArrowhead)")
 .attr("x1", nodeSizeB)
 .attr("x2", nodeSizeB + nodeMargin + 14)
 .attr("y1", nodeSizeB / 2)
 .attr("y2", nodeSizeB / 2);

cellB.append("line")
 .attr("class", "arrow")
 .attr("marker-end", "url(#edgeArrowhead)")
 .attr("transform", "translate(" + nodeSizeB / 2 + ", 0)")
 .attr("y1", 0)
 .attr("y2", -nodeMargin \* 2 + 5);

cellB.append("text")
 .style("opacity", 0.8)
 .text("B")
 .attr("dx", nodeSizeB / 2)
 .attr("dy", nodeSizeB / 2 + 1);

cellB.append("text")
 .attr("class", "label")
 .attr("dx", function(d) { return d === "européenne" ? nodeSizeB / 2 + 15 : nodeSizeB / 2; })
 .attr("dy", - 24 - 5)
 .text(function(d) { return d; });

cellB.append("rect")
 .style("opacity", 0)
 .attr("transform", "translate(-" + ((xb.step() - nodeSizeB) / 2) + ",-" + nodeMargin + ")")
 .attr("width", xb.step())
 .attr("height", networkHeightB + (networkMargin - networkHeightB) / 2);
//
// Links
//
var linkGroup = svg.append("g").attr("class", ".link-group")

var link = linkGroup.selectAll(".link")
 .data(linkData)
 .enter().append("path")
 .attr("class", "link")
 .attr("d", link)
 .style("opacity", function(d) { return d.v; });
//
//
//
// var hoverB = svg.selectAll(".hover-b")
// .data(labelsB)
// .enter().append("rect")
// .attr("class", "hover-b")
// .style("opacity", 0)
// .attr("transform", function(d, i) { return "translate(" + (xb(i) - xb.step() / 4) + ", 0)"; })
// .attr("width", xb.step())
// .attr("height", networkMargin / 2 + nodeSizeB)

})();

This kind of attention between RNNs has a number of other applications. It can be used in voice recognition [12], allowing one RNN to process the audio and then have another RNN skim over it, focusing on relevant parts as it generates a transcript.

output text
network B
network A
input audio

```
0.01,0.02,0.01,0.01,0.01,0.01,0.01,0.00,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.00,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01
0.01,0.02,0.01,0.01,0.01,0.01,0.01,0.00,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.00,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01
0.01,0.02,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.00,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01
0.01,0.02,0.01,0.01,0.01,0.01,0.01,0.00,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.00,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01
0.01,0.02,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.00,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01
0.09,0.11,0.01,0.01,0.01,0.01,0.01,0.00,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.00,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01
0.78,0.33,0.04,0.02,0.02,0.01,0.01,0.00,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.00,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01
0.01,0.05,0.61,0.37,0.78,0.07,0.01,0.00,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.00,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01
0.01,0.01,0.05,0.21,0.07,0.74,0.31,0.00,0.01,0.01,0.01,0.02,0.01,0.02,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.00,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01
0.01,0.01,0.01,0.04,0.02,0.02,0.47,0.98,0.02,0.01,0.01,0.02,0.01,0.02,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.00,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01
0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.00,0.96,0.98,0.28,0.02,0.02,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.00,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01
0.01,0.01,0.01,0.02,0.01,0.01,0.01,0.00,0.01,0.01,0.40,0.49,0.61,0.30,0.02,0.02,0.01,0.01,0.01,0.02,0.01,0.01,0.01,0.01,0.00,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01
0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.00,0.01,0.01,0.05,0.07,0.09,0.18,0.96,0.89,0.87,0.54,0.02,0.01,0.01,0.01,0.01,0.01,0.00,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01
0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.02,0.10,0.05,0.13,0.01,0.03,0.05,0.10,0.14,0.32,0.13,0.01,0.02,0.01,0.00,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01
0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.12,0.60,0.04,0.03,0.02,0.02,0.01,0.00,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01
0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.05,0.41,0.66,0.02,0.02,0.01,0.00,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01
0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.94,0.72,0.01,0.00,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01
0.01,0.02,0.01,0.01,0.01,0.01,0.01,0.00,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.04,0.76,0.02,0.01,0.01,0.01,0.01,0.02,0.01,0.01,0.01
0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.00,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.77,0.45,0.66,0.01,0.01,0.01,0.01,0.01,0.01
0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.00,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.04,0.01,0.00,0.02,0.13,0.98,0.97,0.02,0.01,0.01,0.01
0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.00,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.09,0.00,0.01,0.01,0.01,0.02,0.90,0.02,0.01,0.01
0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.00,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.08,0.10,0.01,0.01,0.01,0.03,0.96,0.19,0.01
0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.00,0.13,0.02,0.01,0.01,0.01,0.01,0.60,0.18
0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.00,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.00,0.01,0.01,0.01,0.01,0.01,0.01,0.02,0.60
0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.00,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.02
0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.00,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.00,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01
0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.00,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.00,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01
0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.00,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.00,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01
0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.00,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.00,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01
0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.00,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.00,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01
0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.00,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.00,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01
0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.00,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.00,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01
0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.00,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01
0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.00,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.00,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01
0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.00,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.00,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01
0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.00,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.00,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01
0.01,0.02,0.02,0.02,0.01,0.01,0.01,0.00,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.00,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01
0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.00,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.00,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01

```

![](assets/rnn-attention-waveform-bw.png)

Figure derived from [Chan, *et al.* 2015](https://arxiv.org/pdf/1508.01211.pdf)
![](assets/pointer.svg)

#attentional-ex3 .stage {
 position: relative;
 margin-bottom: 24px;
}
#attentional-ex3 .waveform {
 position: absolute;
 opacity: 0.7;
}
#attentional-ex3 .pointer {
 position: absolute;
 width: 26px;
 height: 26px;
 top: 36px;
 left: -48px;
}
#attentional-ex3 svg {
 z-index: 1;
 position: relative;
 width: 100%;
}
#attentional-ex3 svg .labels {
 font-size: 12px;
 fill-opacity: 0.5;
}
#attentional-ex3 figcaption {
 text-align: center;
}
#attentional-ex3 .background {
 fill: rgb(240, 240, 245);
 fill-opacity: 0.8;
}
#attentional-ex3 .audio-background {
 fill: none;
 stroke: black;
 stroke-opacity: 0.3;
}
#attentional-ex3 .cell .node {
 fill: white;
 fill-opacity: 0.9;
 stroke: black;
 stroke-width: 1px;
 stroke-opacity: 0.15;
}
#attentional-ex3 .cell:hover .node {
 stroke-opacity: 1;
}
#attentional-ex3 .cell .shadow {
 fill: black;
 fill-opacity: 0.07;
}
#attentional-ex3 .cell text {
 font-size: 13px;
 fill-opacity: 0.5;
 text-anchor: middle;
 alignment-baseline: middle;
}
#attentional-ex3 .cell text.label {
 font-size: 15px;
 /\*fill-opacity: 0.8;\*/
 text-anchor: middle;
 alignment-baseline: middle;
}
#attentional-ex3 .cell:last-child text.label {
 font-size: 10px;
}
#attentional-ex3 .link-group {
 transition: opacity, 0.3s, linear;
}
#attentional-ex3 .link-group .node-highlight {
 transition: stroke-opacity, 0.3s, linear;
 stroke: black;
 stroke-opacity: 0;
 fill: none;
}
#attentional-ex3 .link-group:hover .node-highlight {
 stroke-opacity: 1;
}
#attentional-ex3 .link {
 fill: none;
 stroke: rgb(131, 89, 178);
 stroke-width: 2px;
 pointer-events: none;
}
#attentional-ex3 .arrow {
 stroke: black;
 stroke-opacity: 0.3;
}
#attentional-ex3 .cell:last-child .arrow:first-of-type {
 display: none;
}
#attentional-ex3 .tick {
 stroke: black;
 stroke-opacity: 0.2;
}

(function() {

var data = d3.csvParseRows(d3.select("#attentional-ex3-data").text());
var labelsB = ["h","o","w","\_","m","u","c","h","\_","w","o","u","l","d","\_","a","\_","w","o","o","d","c","h","u","c","k","\_","c","h","u","c","k","<end>"];
var labelsA = d3.range(data.length);

var linkData = [];
data.forEach(function(a, ai) {
 a.forEach(function(b, bi) {
 linkData.push({
 ai: +ai,
 bi: +bi,
 v: +data[ai][bi]
 });
 });
});

var nodeMargin = 8;
var networkMargin = 140;
var audioHeight = 60;

var html = d3.select("#attentional-ex3");
var outerWidth = 984; //Math.max(700, html.node().getBoundingClientRect().width);
var outerHeight = 280;
var margin = {top: 36, right: nodeMargin + 80, bottom: 24, left: nodeMargin};
var width = outerWidth - margin.left - margin.right;
var height = outerHeight - margin.top - margin.bottom;

var xa = d3.scaleBand()
 .domain(d3.range(labelsA.length))
 .paddingInner(0.5)
 .range([nodeMargin, width - nodeMargin]);

var xb = d3.scaleBand()
 .domain(d3.range(labelsB.length))
 .paddingInner(0.5)
 .range([nodeMargin, width - nodeMargin]);

var nodeSizeA = xa.bandwidth();
var nodeSizeB = xb.bandwidth();

var networkHeightA = nodeSizeA + nodeMargin \* 2;
var networkHeightB = nodeSizeB + nodeMargin \* 2;

var link = function(d) {
 return "M" + (xb(d.bi) + nodeSizeB / 2) + "," + (nodeSizeB + nodeMargin)
 + "C" + (xb(d.bi) + nodeSizeB / 2) + "," + (nodeSizeB + networkMargin / 3 + nodeMargin)
 + " " + (xa(d.ai) + nodeSizeA / 2) + "," + (networkMargin - networkMargin / 3 + nodeMargin)
 + " " + (xa(d.ai) + nodeSizeA / 2) + "," + (networkMargin + nodeMargin);
};

var svg = html.select("svg")
 .attr("viewBox", "0 0 " + outerWidth + " " + outerHeight)
 .append("g")
 .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

html.select("svg .labels")
 .attr("transform", "translate(" + (width + nodeMargin \* 3) + ", 0)");

var audio = svg.append("g")
 .attr("class", "audio")
 .attr("transform", "translate(0, " + (nodeMargin \* 4 + nodeSizeA + networkMargin) + ")");

//
// Network A
//

var networkA = svg.append("g")
 .attr("transform", "translate(0, " + networkMargin + ")");

networkA.append("rect")
 .attr("class", "background")
 .attr("width", width)
 .attr("height", nodeSizeA + 2 \* nodeMargin)
 .attr("rx", nodeMargin \* 0.7)
 .attr("ry", nodeMargin \* 0.7);

var cellA = networkA.selectAll(".cell")
 .data(labelsA)
 .enter().append("g")
 .attr("class", "cell")
 .attr("transform", function(d, i) { return "translate(" + xa(i) + ", " + nodeMargin + ")"; })
 .on("mouseover", function(d, i) {
 link.style("display", function(ld) {
 return ld.ai === i ? "" : "none";
 });
 })
 .on("mouseout", function() { link.style("display", ""); });

cellA.append("rect")
 .attr("class", "shadow")
 .attr("transform", "translate(1, 3)")
 .attr("width", nodeSizeA)
 .attr("height", nodeSizeA)
 .attr("rx", 4)
 .attr("ry", 4);

cellA.append("rect")
 .attr("class", "node")
 .attr("width", nodeSizeA)
 .attr("height", nodeSizeA)
 .attr("rx", 2)
 .attr("ry", 2);

cellA.append("line")
 .attr("class", "arrow")
 .attr("marker-end", "url(#edgeArrowhead)")
 .attr("x1", nodeSizeA)
 .attr("x2", nodeSizeA + nodeMargin)
 .attr("y1", nodeSizeA / 2)
 .attr("y2", nodeSizeA / 2);

cellA.append("line")
 .attr("class", "arrow")
 .attr("marker-end", "url(#edgeArrowhead)")
 .attr("transform", "translate(" + nodeSizeA / 2 + ", " + nodeSizeA + ")")
 .attr("y1", nodeMargin \* 3)
 .attr("y2", 4);

cellA.append("rect")
 .style("opacity", 0)
 .attr("transform", "translate(-" + ((xa.step() - nodeSizeA) / 2) + ",-" + (nodeMargin + (networkMargin - networkHeightB) / 2) + ")")
 .attr("width", xa.step())
 .attr("height", networkHeightA + (networkMargin - networkHeightA) / 2 + audioHeight + nodeMargin \* 2);

//
// Network B
//

var networkB = svg.append("g");

networkB.append("rect")
 .attr("class", "background")
 .attr("width", width)
 .attr("height", nodeSizeB + 2 \* nodeMargin)
 .attr("rx", nodeMargin \* 0.7)
 .attr("ry", nodeMargin \* 0.7);

var cellB = networkB.selectAll(".cell")
 .data(labelsB)
 .enter().append("g")
 .attr("class", "cell")
 .attr("transform", function(d, i) { return "translate(" + xb(i) + ", " + nodeMargin + ")"; })
 .on("mouseover", function(d, i) {
 link.style("display", function(ld) {
 return ld.bi === i ? "" : "none";
 });
 })
 .on("mouseout", function() { link.style("display", ""); });

cellB.append("rect")
 .attr("class", "shadow")
 .attr("transform", "translate(1, 3)")
 .attr("width", nodeSizeB)
 .attr("height", nodeSizeB)
 .attr("rx", 4)
 .attr("ry", 4);

cellB.append("rect")
 .attr("class", "node")
 .attr("width", nodeSizeB)
 .attr("height", nodeSizeB)
 .attr("rx", 2)
 .attr("ry", 2);

cellB.append("line")
 .attr("class", "arrow")
 .attr("marker-end", "url(#edgeArrowhead)")
 .attr("x1", nodeSizeB)
 .attr("x2", nodeSizeB + nodeMargin)
 .attr("y1", nodeSizeB / 2)
 .attr("y2", nodeSizeB / 2);

cellB.append("line")
 .attr("class", "arrow")
 .attr("marker-end", "url(#edgeArrowhead)")
 .attr("transform", "translate(" + nodeSizeB / 2 + ", 0)")
 .attr("y1", 0)
 .attr("y2", -nodeMargin \* 2);

cellB.append("text")
 .attr("class", "label")
 .attr("dx", nodeSizeB / 2)
 .attr("dy", - nodeMargin \* 2 - 15)
 .text(function(d) { return d; });

cellB.append("rect")
 .style("opacity", 0)
 .attr("transform", "translate(-" + ((xb.step() - nodeSizeB) / 2) + ",-" + nodeMargin + ")")
 .attr("width", xb.step())
 .attr("height", networkHeightB + (networkMargin - networkHeightB) / 2);
//
// Links
//

var linkGroup = svg.append("g").attr("class", ".link-group")

var link = linkGroup.selectAll(".link")
 .data(linkData)
 .enter().append("path")
 .attr("class", "link")
 .attr("d", link)
 .style("opacity", function(d) { return d.v; });

//
// Audio
//

html.select(".waveform")
 .style("left", "1%")
 .style("top", "76%")
 .style("width", "90%")
 .style("height", "20%")

audio.append("rect")
 .attr("class", "audio-background")
 .attr("width", width)
 .attr("height", audioHeight)
 .attr("rx", nodeMargin \* 0.7)
 .attr("ry", nodeMargin \* 0.7);

audio.selectAll(".tick")
 .data(labelsA)
 .enter().append("line")
 .style("display", function(d) { return d == 0 ? "none" : ""; })
 .attr("class", "tick")
 .attr("transform", "translate(-" + (xa.step() - xa.bandwidth()) / 2 + ", " + 0 + ")")
 .attr("x1", function(d) { return xa(d); })
 .attr("x2", function(d) { return xa(d); })
 .attr("y2", audioHeight)

audio.selectAll(".segment")
 .data(labelsA)
 .enter().append("rect")
 .style("opacity", 0)
 .attr("class", "segment")
 .attr("transform", function(d) {
 return "translate(" + ((-xa.step() + xa.bandwidth()) / 2 + xa(d)) + ", " + nodeMargin + ")";
 })
 .attr("width", xa.step())
 .attr("height", audioHeight)

})();

Other uses of this kind of attention include parsing text [13], where it allows the model to glance at words as it generates the parse tree, and for conversational modeling [14], where it lets the model focus on previous parts of the conversation as it generates its response.

Attention can also be used on the interface between a convolutional neural network and an RNN. This allows the RNN to look at different position of an image every step. One popular use of this kind of attention is for image captioning. First, a conv net processes the image, extracting high-level features. Then an RNN runs, generating a description of the image. As it generates each word in the description, the RNN focuses on the conv net’s interpretation of the relevant parts of the image. We can explicitly visualize this:

![](assets/show-attend-tell.png)
Figure from [3]

More broadly, attentional interfaces can be used whenever one wants to interface with a neural network that has a repeating structure in its output.

Attentional interfaces have been found to be an extremely general and powerful technique, and are becoming increasingly widespread.

---

Adaptive Computation Time
-------------------------

Standard RNNs do the same amount of computation for each time step. This seems unintuitive. Surely, one should think more when things are hard? It also limits RNNs to doing O(n) operations for a list of length n.

Adaptive Computation Time [15] is a way for RNNs to do different amounts of computation each step. The big picture idea is simple: allow the RNN to do multiple steps of computation for each time step.

In order for the network to learn how many steps to do, we want the number of steps to be differentiable. We achieve this with the same trick we used before: instead of deciding to run for a discrete number of steps, we have an attention distribution over the number of steps to run. The output is a weighted combination of the outputs of each step.

rnn

For every time step the RNN can do multiple computation steps.

The output is a weighted combination of the computation step outputs.

The process is repeated for each time step.

A special bit is set to denote the first computation step.

There are a few more details, which were left out in the previous diagram. Here’s a complete diagram of a time step with three computation steps.

rnn

That’s a bit complicated, so let’s work through it step by step. At a high-level, we’re still running the RNN and outputting a weighted combination of the states:

rnn

The weight for each step is determined by a “halting neuron.” It’s a sigmoid neuron that looks at the RNN state and gives a halting weight, which we can think of as the probability that we should stop at that step.

rnn

halting neuron

We have a total budget for the halting weights of 1, so we track that budget along the top. When it gets to less than epsilon, we stop.

rnn

When we stop, might have some left over halting budget because we stop when it gets to less than epsilon. What should we do with it? Technically, it’s being given to future steps but we don’t want to compute those, so we attribute it to the last step.

rnn

When training Adaptive Computation Time models, one adds a “ponder cost” term to the cost function. This penalizes the model for the amount of computation it uses. The bigger you make this term, the more it will trade-off performance for lowering compute time.

Adaptive Computation Time is a very new idea, but we believe that it, along with similar ideas, will be very important.

### Code

The only open source implementation of Adaptive Computation Time at the moment seems to be [Mark Neumann’s](https://github.com/DeNeutoy/act-tensorflow) (TensorFlow).

---

Neural Programmer
-----------------

Neural nets are excellent at many tasks, but they also struggle to do some basic things like arithmetic, which are trivial in normal approaches to computing. It would be really nice to have a way to fuse neural nets with normal programming, and get the best of both worlds.

The neural programmer [16] is one approach to this. It learns to create programs in order to solve a task. In fact, it learns to generate such programs *without needing examples of correct programs*. It discovers how to produce programs as a means to the end of accomplishing some task.

The actual model in the paper answers questions about tables by generating SQL-like programs to query the table. However, there are a number of details here that make it a bit complicated, so let’s start by imagining a slightly simpler model, which is given an arithmetic expression and generates a program to evaluate it.

The generated program is a sequence of operations. Each operation is defined to operate on the output of past operations. So an operation might be something like “add the output of the operation 2 steps ago and the output of the operation 1 step ago.” It’s more like a Unix pipe than a program with variables being assigned to and read from.

rnn

The program is generated one operation at a time by a controller RNN. At each step, the controller RNN outputs a probability distribution for what the next operation should be. For example, we might be pretty sure we want to perform addition at the first time step, then have a hard time deciding whether we should multiply or divide at the second step, and so on...

rnn

At each step the controller RNN outputs a probability distribution.

The resulting distribution over operations can now be evaluated. Instead of running a single operation at each step, we do the usual attention trick of running all of them and then average the outputs together, weighted by the probability we ran that operation.

rnn

At each step the controller RNN outputs a probability distribution.

We run all of the operations and average the outputs together.

As long as we can define derivatives through the operations, the program’s output is differentiable with respect to the probabilities. We can then define a loss, and train the neural net to produce programs that give the correct answer. In this way, the Neural Programmer learns to produce programs without examples of good programs. The only supervision is the answer the program should produce.

That’s the core idea of Neural Programmer, but the version in the paper answers questions about tables, rather than arithmetic expressions. There are a few additional neat tricks:

* **Multiple Types:** Many of the operations in the Neural Programmer deal with types other than scalar numbers. Some operations output selections of table columns or selections of cells.  Only outputs of the same type get merged together.
* **Referencing Inputs:** The neural programmer needs to answer questions like “How many cities have a population greater than 1,000,000?” given a table of cities with a population column. To facilitate this, some operations allow the network to reference constants in the question they’re answering, or the names of columns. This referencing happens by attention, in the style of pointer networks [17].

The Neural Programmer isn’t the only approach to having neural networks generate programs. Another lovely approach is the Neural Programmer-Interpreter [18] which can accomplish a number of very interesting tasks, but requires supervision in the form of correct programs.

We think that this general space, of bridging the gap between more traditional programming and neural networks is extremely important. While the Neural Programmer is clearly not the final solution, we think there are a lot of important lessons to be learned from it.

### Code

The more recent version of Neural Programmer for [question answering](https://openreview.net/pdf?id=ry2YOrcge) has been open sourced by its authors and is available as a [TensorFlow Model](https://github.com/tensorflow/models/tree/master/neural_programmer). There is also an implementation of the Neural Programmer-Interpreter by [Ken Morishita](https://github.com/mokemokechicken/keras_npi) (Keras).

---

The Big Picture
---------------

A human with a piece of paper is, in some sense, much smarter than a human without. A human with mathematical notation can solve problems they otherwise couldn’t. Access to computers makes us capable of incredible feats that would otherwise be far beyond us.

In general, it seems like a lot of interesting forms of intelligence are an interaction between the creative heuristic intuition of humans and some more crisp and careful media, like language or equations. Sometimes, the medium is something that physically exists, and stores information for us, prevents us from making mistakes, or does computational heavy lifting. In other cases, the medium is a model in our head that we manipulate. Either way, it seems deeply fundamental to intelligence.

Recent results in machine learning have started to have this flavor, combining the intuition of neural networks with something else. One approach is what one might call “heuristic search.” For example, AlphaGo [19] has a model of how Go works and explores how the game could play out guided by neural network intuition. Similarly, DeepMath [20] uses neural networks as intuition for manipulating mathematical expressions. The “augmented RNNs” we’ve talked about in this article are another approach, where we connect RNNs to engineered media, in order to extend their general capabilities.

Interacting with media naturally involves making a sequence of taking an action, observing, and taking more actions. This creates a major challenge: how do we learn which actions to take? That sounds like a reinforcement learning problem and we could certainly take that approach. But the reinforcement learning literature is really attacking the hardest version of this problem, and its solutions are hard to use. The wonderful thing about attention is that it gives us an easier way out of this problem by partially taking all actions to varying extents. This works because we can design media—like the NTM memory—to allow fractional actions and to be differentiable. Reinforcement learning has us take a single path, and try to learn from that. Attention takes every direction at a fork, and then merges the paths back together.

A major weaknesses of attention is that we have to take every “action” every step. This causes the computational cost to grow linearly as you do things like increase the amount of memory in a Neural Turing Machine. One thing you could imagine doing is having your attention be sparse, so that you only have to touch some memories. However, it’s still challenging because you may want to do things like have your attention depend on the content of the memory, and doing that naively forces you to look at each memory. We’ve seen some initial attempts to attack this problem, such as [21], but it seems like there’s a lot more to be done. If we could really make such sub-linear time attention work, that would be very powerful!

Augmented recurrent neural networks, and the underlying technique of attention, are incredibly exciting. We look forward to seeing what happens next!

Summary: A visual overview of neural attention, and the powerful extensions of neural networks being built on top of it.