MIT 6.7960 — Lecture 6

Transformers

§ CNN Limitations

One limitation of CNNs is that they are not well-suited for modeling long-distance relationships.

Question: How many birds are in this image?

We'll introduce three architectural innovations to fix these problems.

§ Tokens

Definition. A token is just a vector of neurons. Connotatively, a token is an encapsulated bundle of information. You can tokenize anything, whether it's image, text, or audio data.

Here are some details on how tokenization is implemented; the general principle, though is that the details do not matter.

Notably, a very simple tokenization method generally suffices, because the NN on tokens, itself, can learn some of the more interesting relationships between those tokens.

Here's how tokens look when used as nodes in a neural network (at left).

The linear portions of the NN work how you would expect them to.

The nonlinear mappings from individual tokens to individual tokens are implemented not with a ReLU\mathrm{ReLU}, but with an NN! (Meta.)

§ Query-Key-Value Attention

Currently, the architecture of NN has no way of identifying which tokens are relevant and which tokens are not. We would like our NN architecture to weight our tokens based on how relevant they are to the query.

One way to implement this is via query-key-value attention.

§ Self-Attention

One can also consider self-attention—instead of computing the relevance between input and image, we compute the relevance between some data and itself.

Notably, the map from Tin\mathbf{T}_{\mathrm{in}} to Tout\mathbf{T}_{\mathrm{out}} looks like:

Tout=softmax(QinKin⊤m)⏟AVin\mathbf{T}_{\mathrm{out}} = \underbrace{\mathrm{softmax}\left( \frac{\mathbf{Q}_{\mathrm{in}}\mathbf{K}_{\mathrm{in}}^{\top}}{\sqrt{m}} \right)}_{\mathbf{A}} \mathbf{V}_{\mathrm{in}}

where mm is the query/key dimension. Note that A\mathbf{A} is normalized so that each of its rows sum to 11, so every output token is a weighted average of all the value tokens; the weight on vj\mathbf{v}_j in output token ii is Aij∝exp⁡(qi⊤kj/m)\mathbf{A}_{ij} \propto \exp(\mathbf{q}_i^{\top}\mathbf{k}_j / \sqrt{m}).

Below, the learned projections happen to make each bird-head patch attend to the other bird-head patches.

Definition. There's also multihead self-attention (MSA), in which we concatenate kk different attempts at self-attention tokenwise, then project back down with a matrix WMSA\mathbf{W}_{\mathtt{MSA}}.

§ Transformer Architecture

Putting together multihead self-attention (MSA) with multi-layer perceptrons (MLPs), we get a transformer!

The code for a transformer is extremely simple, too.

# x: input data (RGB image)
# K: tokenization patch size
# d: token/query/key/value dimensionality (setting these all as the same)
# L : number of layers
# W_q_T, W_k_T, W_v_T : transposed query/key/value projection matrices
# mlp: tokenwise mlps

# tokenize input image
T = tokenize(x, K) # 3 x Hx W image --> N xd array of token code vectors

# run tokens through all L layers
for l in range(L):

    # attention layer
    Q, K, V = nn.matmul(nn.layernorm(T), [W_q_T[l], W_k_T[l], W_v_T[l]])
    # nn.matmul does matrix multiplication
    A = nn.softmax(nn.matmul(Q,K.transpose())/sqrt(d), dim=-1)
    T = nn.matmul(A, V) + T # note residual connection

    # tokenwise mlp
    T = mlp[l](nn.layernorm(T)) + T # note residual connection

# T now contains the output token representation computed by the transformer

§ Positional Encodings

One observation about the transformer architecture is that it is permutation equivariant.

Fθ(π(Tin))=π(Fθ(Tin))    and    attn(π(Tin))=π(attn(Tin))    for any MLP Fθ  and any MSA attn.F_{\theta}(\pi(\mathbf{T}_{\mathrm{in}})) = \pi(F_{\theta}(\mathbf{T}_{\mathrm{in}})) ~~~ \text{ and } ~~~ \textsc{attn}(\pi(\mathbf{T}_{\mathrm{in}})) = \pi(\textsc{attn}(\mathbf{T}_{\mathrm{in}})) ~~~ \text{ for any MLP } F_{\theta} ~ \text{ and any MSA } \textsc{attn}.

But we actually don't want permutation equivariance, because that implies that it may be difficult for models to learn about forms of data that care about position. The fix, naturally, is to add position to each of our tokens.

There is some nuance concerning how, exactly, we encode position. For images, for example, we might encode position by the Fourier coefficients associated with that position.

Similarly, positional encodings of points on a sphere might use spherical harmonics.

Positional encodings of nodes in a graph are given by the eigenvectors of its Laplacian. (Details omitted.)

§ Autoregressive Models (GPT, Claude)

Recall that LLMs like GPT generate text by “predicting the next word”.

GPT's means of prediction is basically just a transformer. The only distinction is that the attention matrix must forbid some tokens attending to tokens that occur in the future. To implement this, it suffices to mask A\mathbf{A} like so:

More generally, here's how the causal self-attention relationships look for autoregressive image-to-text architectures.

We call this cross-modality attention, because attention occurs between data in both text and image modalities.