Skip to content

Self-Attention and Positional Encoding

In deep learning, we often use CNNs or RNNs to encode sequences. Now with attention mechanisms in mind, imagine feeding a sequence of tokens into an attention mechanism such that at every step, each token has its own query, keys, and values. Here, when computing the value of a token's representation at the next layer, the token can attend (via its query vector) to any other's token (matching based on their key vectors). Using the full set of query-key compatibility scores, we can compute, for each token, a representation by building the appropriate weighted sum over the other tokens. Because every token is attending to each other token (unlike the case where decoder steps attend to encoder steps), such architectures are typically described as self-attention models [196], [142], and elsewhere described as intra-attention model [197], [198], [199]. In this section, we will discuss sequence encoding using self-attention, including using additional information for the sequence order.

julia
using Pkg; Pkg.activate("../../d2lai")
using LinearAlgebra
using d2lai
using Flux 
using Downloads
using StatsBase
using Plots
using CUDA, cuDNN
  Activating project at `/workspace/workspace/d2l-julia/d2lai`

Self-Attention

Given a sequence of input tokens x1,,xn where any xiRd (1in), its self-attention outputs a sequence of the same length y1,,yn, where

yi=f(xi,(x1,x1),,(xn,xn))Rd

according to the definition of attention pooling in :eqref:eq_attention_pooling. Using multi-head attention, the following code snippet computes the self-attention of a tensor with shape (batch size, number of time steps or sequence length in tokens, d). The output tensor has the same shape.

julia
num_hiddens, num_heads = 100, 5
attention = d2lai.MultiHeadedAttention(num_hiddens, num_heads, 0.5)
batch_size, num_queries, valid_lens = 2, 4, [3, 2]
X = ones(num_hiddens, num_queries, batch_size)
out, attention_weights = attention(X, X, X, valid_lens)
@assert size(out) == (num_hiddens, num_queries, batch_size)

Comparing CNNs, RNNs, and Self-Attention

Let's compare architectures for mapping a sequence of n tokens to another one of equal length, where each input or output token is represented by a d-dimensional vector. Specifically, we will consider CNNs, RNNs, and self-attention. We will compare their computational complexity, sequential operations, and maximum path lengths. Note that sequential operations prevent parallel computation, while a shorter path between any combination of sequence positions makes it easier to learn long-range dependencies within the sequence [165].

Comparing CNN (padding tokens are omitted), RNN, and self-attention architectures.

Let's regard any text sequence as a "one-dimensional image". Similarly, one-dimensional CNNs can process local features such as n-grams in text. Given a sequence of length n, consider a convolutional layer whose kernel size is k, and whose numbers of input and output channels are both d. The computational complexity of the convolutional layer is O(knd2). As Figure shows, CNNs are hierarchical, so there are O(1) sequential operations and the maximum path length is O(n/k). For example, x1 and x5 are within the receptive field of a two-layer CNN with kernel size 3 in Figure.

When updating the hidden state of RNNs, multiplication of the d×d weight matrix and the d-dimensional hidden state has a computational complexity of O(d2). Since the sequence length is n, the computational complexity of the recurrent layer is O(nd2). According to Figure, there are O(n) sequential operations that cannot be parallelized and the maximum path length is also O(n).

In self-attention, the queries, keys, and values are all n×d matrices. Consider the scaled dot product attention in :eqref:eq_softmax_QK_V, where an n×d matrix is multiplied by a d×n matrix, then the output n×n matrix is multiplied by an n×d matrix. As a result, the self-attention has a O(n2d) computational complexity. As we can see from Figure, each token is directly connected to any other token via self-attention. Therefore, computation can be parallel with O(1) sequential operations and the maximum path length is also O(1).

All in all, both CNNs and self-attention enjoy parallel computation and self-attention has the shortest maximum path length. However, the quadratic computational complexity with respect to the sequence length makes self-attention prohibitively slow for very long sequences.

Positional Encoding

Unlike RNNs, which recurrently process tokens of a sequence one-by-one, self-attention ditches sequential operations in favor of parallel computation. Note that self-attention by itself does not preserve the order of the sequence. What do we do if it really matters that the model knows in which order the input sequence arrived?

The dominant approach for preserving information about the order of tokens is to represent this to the model as an additional input associated with each token. These inputs are called positional encodings, and they can either be learned or fixed a priori. We now describe a simple scheme for fixed positional encodings based on sine and cosine functions [142].

Suppose that the input representation XRn×d contains the d-dimensional embeddings for n tokens of a sequence. The positional encoding outputs X+P using a positional embedding matrix PRn×d of the same shape, whose element on the ith row and the (2j)th or the (2j+1)th column is

pi,2j=sin(i100002j/d),pi,2j+1=cos(i100002j/d).

:eqlabel:eq_positional-encoding-def

At first glance, this trigonometric function design looks weird. Before we give explanations of this design, let's first implement it in the following PositionalEncoding class.

julia
struct PositionalEncoding{P,D,A} <: AbstractModel 
    dropout::D 
    P::P 
    args::A
end

function PositionalEncoding(num_hiddens::Int, dropout::AbstractFloat, max_len = 1000)
    dropout = Dropout(dropout)
    P = zeros(num_hiddens, max_len, 1)
    X = reshape(collect(1:max_len), 1, :) ./ 10000 .^ ((0:2:num_hiddens-1) / num_hiddens)
    P[1:2:end, :, :] .= sin.(X)
    P[2:2:end, :, :] .= cos.(X)
    PositionalEncoding(dropout, P, (; num_hiddens, dropout, max_len))
end

function (pos::PositionalEncoding)(x)
    device = isa(x, CuArray) ? gpu : cpu
    P_device = pos.P |> device
    pos.dropout(x .+ P_device[:, 1:size(x, 2), :])
end

In the positional embedding matrix P, rows correspond to positions within a sequence and columns represent different positional encoding dimensions. In the example below, we can see that the 6th and the 7th columns of the positional embedding matrix have a higher frequency than the 8th and the 9th columns. The offset between the 6th and the 7th (same for the 8th and the 9th) columns is due to the alternation of sine and cosine functions.

julia
encoding_dim, num_steps = 32, 60
pos_encoding = PositionalEncoding(encoding_dim, 0.3)
X = pos_encoding(zeros(encoding_dim, num_steps, 1))
P = pos_encoding.P[:, 1:size(X, 2), :]
plot(P[6:10, :, 1]', label = reshape(["col $i" for i in 6:10], 1, :), xlabel = "Row Position")

Absolute Positional Information

To see how the monotonically decreased frequency along the encoding dimension relates to absolute positional information, let's print out the binary representations of 0,1,,7. As we can see, the lowest bit, the second-lowest bit, and the third-lowest bit alternate on every number, every two numbers, and every four numbers, respectively.

julia
for i in 0:7
    string.(digits(i, base=2, pad = 3)) |> join |> println
end
000
100
010
110
001
101
011
111

In binary representations, a higher bit has a lower frequency than a lower bit. Similarly, as demonstrated in the heat map below, the positional encoding decreases frequencies along the encoding dimension by using trigonometric functions. Since the outputs are float numbers, such continuous representations are more space-efficient than binary representations.

julia
P_ = Flux.unsqueeze(Flux.unsqueeze(P[:, :, 1], 3), 3)

d2lai.show_heatmaps(P_, "Column (encoding dimension)", "Row (position)")

Relative Positional Information

Besides capturing absolute positional information, the above positional encoding also allows a model to easily learn to attend by relative positions. This is because for any fixed position offset δ, the positional encoding at position i+δ can be represented by a linear projection of that at position i.

This projection can be explained mathematically. Denoting ωj=1/100002j/d, any pair of (pi,2j,pi,2j+1) in :eqref:eq_positional-encoding-def can be linearly projected to (pi+δ,2j,pi+δ,2j+1) for any fixed offset δ:

[cos(δωj)sin(δωj)sin(δωj)cos(δωj)][pi,2jpi,2j+1]=[cos(δωj)sin(iωj)+sin(δωj)cos(iωj)sin(δωj)sin(iωj)+cos(δωj)cos(iωj)]=[sin((i+δ)ωj)cos((i+δ)ωj)]=[pi+δ,2jpi+δ,2j+1],

where the 2×2 projection matrix does not depend on any position index i.

Summary

In self-attention, the queries, keys, and values all come from the same place. Both CNNs and self-attention enjoy parallel computation and self-attention has the shortest maximum path length. However, the quadratic computational complexity with respect to the sequence length makes self-attention prohibitively slow for very long sequences. To use the sequence order information, we can inject absolute or relative positional information by adding positional encoding to the input representations.

Exercises

  1. Suppose that we design a deep architecture to represent a sequence by stacking self-attention layers with positional encoding. What could the possible issues be?

  2. Can you design a learnable positional encoding method?

  3. Can we assign different learned embeddings according to different offsets between queries and keys that are compared in self-attention? Hint: you may refer to relative position embeddings [200], [201].

julia