SandHouse
Pages and contents

Transformers

TL;DR

The first section describes the matrix mathematics of the transformer, which is the leading architectural component for deep learning on modern hardware. In a transformer, data is broken up into tokens. We want to map to a latent space where each token is influenced by the surrounding data (the context). There are different types of relationships in the data which are learned and broken down into heads.

The second section covers how transformers can be described as a graph, summarizing the work of Chaitanya K. Joshi https://arxiv.org/pdf/2506.22084.

Self Attention

Transformers were introduced as a method for natural language processing in order to cope with 2 central problems

1. Handling text and sharing parameters for passages of variable length
2. Contain connections between word representations that depend on the words themselves

The mathematics of dot-product self-attention satisfies both of those properties.

A standard neural network layer f[𝐱]takes a vector input 𝐱 and applies a non-linear transformation such as ReLU

f[𝐱]=ReLU[𝛃+𝐖𝐱]

A self attention block sa[𝐗]:ℝDΓ—N→ℝDΓ—Ntakes N inputs 𝐗=𝐱1,...,𝐱Nand returns Noutput vectors of the same size. In the context of NLP, each input represents a word embedding vector or word fragment.

First, a set of values are computed for each input. The weights in this equation depend on a similarity measure between the values of 𝐱mand the other inputs.

𝐯m=Ξ²v+𝐖v𝐱m

Then the nth output is described by the attention that 𝐱mpays to 𝐱n. Note that the same weights and biases Ξ²mβˆˆβ„D,𝐖mβˆˆβ„DΓ—Dare applied to each vector 𝐱mβˆˆπ—.

Next we compute two more linear transformations to the input, called the queries and keys.

\mathbf{q}_m = \beta_q + \mathbf{W}_q \mathbf{x}_m \\ \mathbf{k}_m = \beta_k + \mathbf{W}_k \mathbf{x}_m

The β€œattention weights” factor is the dot product between the nth query vector and the mth key vector, which describes their embedded similarity. This equation answers: How much does a given query align with every key in the context window?

an,m=softmax[πͺn⋅𝐀mdk]

We then get a weighted sum of values describing how much a value should influence the final representation. The output for token nis

san[𝐱n]=βˆ‘m=1Nam,n𝐯m

Hence, self-attention can be thought of as routing the values in different proportions to create each output. Below is the matrix form that includes each token.

Attention[𝐗]=softmax[𝐐𝐊Tdk]𝐕
[image: 2026-07-02_16-47-15.png]

Multi-Head Attention

While a single self-attention mechanism is effective, it limits the network's ability to focus on multiple different aspects of the input simultaneously. Multi-Head Attention projects the queries, keys, and values into H different lower-dimensional subspaces h, allowing the model to attend to information from multiple representation subspaces in parallel.

If a model's embedding dimension is 512 and it has 8 heads, it creates 8 separate 64-dimensional spaces. Because each head has its own unique set of weight matrices 𝐖Q,𝐖K,𝐖V, each head learns to project the tokens into a completely different geometric space. For a given head h:

Attentionh[𝐗]=Softmax[𝐊hT𝐐hDh]𝐕h

The outputs of all h heads are vertically concatenated and projected via an output weight matrix 𝐖O:

MhSa[𝐗]=𝐖O(Attentionh1[𝐗]T,...,AttentionhH[𝐗]T)T

Positional Encoding

Dot-product self-attention is permutation invariant, meaning the sentence β€œI ate the sandwich” would be transformed the same as β€œThe sandwich ate me.” To mitigate this, a Positional Encoding vector 𝐩m is added to each input embedding 𝐱m to inject sequence order:

𝐱m←𝐱m+𝐩m

The Transformer Block

A standard Encoder Block consists of two primary sub-layers, each wrapped by a Residual Connection and followed by Layer Normalization:

1. Multi-Head Self-Attention:
$$
\mathbf{Z} = \mathrm{LayerNorm}(\mathbf{X} + \mathrm{MultiHead}(\mathbf{X}, \mathbf{X}, \mathbf{X}))
$$
2. Position-wise Feed-Forward Network (FFN):
$$
\mathbf{X}_{\text{out}} = \mathrm{LayerNorm}(\mathbf{Z} + \mathrm{FFN}(\mathbf{Z}))
$$
Where FFN(𝐱)=max⁑(0,𝐱𝐖1+b1)𝐖2+b2

[image: 2026-07-02_21-36-58.png]

The FFN or MLP component projects each token’s representation to a higher dimension (typically 4 Γ— d), applies a non-linear activation function, and then projects back to the original dimension d. It is worth remarking that this token-wise MLP contains significantly more learnable parameters than the attention mechanism.

Transformers are Graph Neural Networks

RNNs vs Transformers

At a high level, deep neural networks compress statistical and semantic information about data into a list of numbers, called a latent representation or embedding. Models are trained by optimizing a loss function that measures how well the model’s representations perform on a task of interest, such as predicting some properties of the input data.

For some time, Recurrent Neural Networks (RNNs) were the leading architecture choice for NLP because of the sequential nature of text. A latent embedding for a word is passed along to the next word, influencing its embedding. This compressed many characters into a fixed vector, which is difficult to scale well.

Transformers take this idea further, by building embedded representations for each word in parallel, which are dependent on the β€œimportance” of each word with respect to each other word.

[image: 2026-07-04_00-54-36.png]