Deep Learning Notes-6: Transformer and Graph Neural Networks
Deep Learning Notes-6, covering the Transformer attention mechanism (self-attention, multi-head attention, positional encoding), language models (GPT/BERT), and graph neural networks (message passing, graph convolution, graph attention). Corresponds to Chapters 12-13 of "Deep Learning: Foundations and Concepts".
Part 6/8 of the series ← Previous | Next | Glossary
It is recommended to read Parts 1-5 first, especially Part 5 on CNNs (to understand the convolution→attention evolution) and Part 4 on residual connections. This part covers the Transformer attention mechanism, why it is stronger than RNNs, and how graph neural networks handle non-grid data.
Chapter 12 Transformer
Attention
Attention is the core concept of the Transformer model. It allows a neural network, when processing sequential data, to dynamically assign different importance weights to different inputs. These weights themselves also depend on the input data, enabling the model to capture dependencies within the sequence.
Unlike the fixed weights in traditional neural networks, the weights of the attention mechanism are data-dependent, i.e., they are computed dynamically based on the current input.
Consider the following two sentences:
- I swam across the river to get to the other bank.
- I walked across the road to get cash from the bank.
The same word “bank” has different meanings in different contexts (river bank vs. bank/financial institution). The model needs to determine its correct meaning based on the other words in the context (such as “swam”, “river”, “cash”).
This shows that when processing a word, the model should “attend to” other words in the sequence that are relevant to it. The degree of attention (weight) depends on the input sequence itself.
- Traditional word embeddings: each word is mapped to a fixed vector (e.g., “bank” is always the same vector), and cannot distinguish polysemous words.
- The goal of the Transformer: through the attention mechanism, map words into a new representation space, so that the same word obtains different vector representations in different contexts.
- In the first sentence, the representation of “bank” will be close to “water”.
- In the second sentence, the representation of “bank” will be close to “money”.
The input to the Transformer is a set of vectors , where .
- Each vector is called a token.
- In NLP, a token can be a word, a subword, or a character.
- In images, a token can be an image patch.
- In protein sequences, a token can be an amino acid.
- Each element of the vector is called a feature.
- The vector dimension is , and the sequence length is .
We organize the inputs into an matrix :
Therefore the basic unit of a Transformer is a function that transforms the input matrix into an output matrix , keeping the dimension unchanged:
Multiple such layers can be stacked to form a deep network. Each layer has its own learnable parameters (weights and biases), trained via gradient descent.
A Transformer layer consists of two main stages:
- Attention mechanism: mix information from different tokens along the column direction (feature dimension).
- Per-row transformation: perform feature transformation within each row (each token).
Attention Coefficients
Imagine that while reading an article, in order to understand a certain sentence, you need to “attend to” certain parts of the article. The attention mechanism is what enables machine learning to do the same.
Goal: map the input vectors to output vectors , so that the representation of is richer.
Key idea: the output vector depends not only on the corresponding input (a single input vector), but also on all the other inputs (the overall meaning). The degree of dependence is controlled by the attention weight .
Define each output vector as a linear combination of the input vectors:
The attention weights should satisfy:
- Non-negativity: (to avoid positive-negative cancellation)
- Normalization: (to ensure the weights sum to 1)
These two constraints mean that , i.e., the weights form a “partition of unity”.
- If and (when ), then , and the input is unchanged.
- In general, is a weighted average of all input vectors, with the weights determined by the input data.
In summary, the attention mechanism enables the model to focus on important parts of the input sequence by dynamically allocating weights.
Suppose we have 3 input vectors:
- (e.g., describing a “cat”)
- (e.g., describing a “dog”)
- (e.g., describing an “animal”)
We want to compute the output vector :
Suppose the attention coefficients are:
- (50% attention to itself)
- (30% attention to the second input)
- (20% attention to the third input)
Then:
The focus can also be adjusted dynamically:
- may focus more on the “cat” information ()
- may focus more on the “dog” information ()
- may focus more on the overall concept ()
Self-Attention
How are the attention weights computed?
First, through an information retrieval analogy:
- Key: describes the attributes of an item (e.g., a movie’s genre, actors).
- Value: the item itself (e.g., the movie file).
- Query: the user’s preference (e.g., the genre they want to watch).
The system finds the best match by comparing the Query and the Key, and returns the corresponding Value.
In the Transformer, however:
- Value: the input vector is used directly as the Value.
- Key: the input vector is also used as the Key.
- Query: the input vector is used as the Query for the output .
This is called “self-attention” because the Query, Key, and Value all come from the same input sequence.
To compute the similarity between Query and Key . A simple method is the dot product; a larger dot product indicates that the two words are more related:
Use the Softmax function to convert the dot product into normalized attention weights:
Softmax ensures the non-negativity and normalization of the weights.
Organize all attention weights into an matrix:
where means taking the exponential of each element of the matrix , and then normalizing each row.
The output matrix is:
Suppose the input sequence has 3 words:
Compute the similarity matrix:
Apply Softmax to each row to get the attention weights:
Finally compute the final output Y.
Network Parameters
The above self-attention mechanism has no learnable parameters, so it cannot learn from data. Moreover, all features have the same weight when computing similarity.
Solution: apply a linear transformation to the inputs, introducing learnable weight matrices.
Definitions:
- Query matrix:
- Key matrix:
- Value matrix:
where are learnable weight matrices.
Dimension notes:
- and have dimensions , ensuring that and have the same number of columns so that the dot product can be computed.
- has dimensions , determining the dimension of the output vector.
- Usually set , to keep the input and output dimensions consistent, which facilitates stacking layers and using residual connections.
The final self-attention output is:
Scaled Self-Attention
Problem: when is large, the variance of the dot product becomes very large (about ), causing the input to the Softmax function to become too large, pushing it into the saturated region where the gradient is very small, which harms training.
Solution: scale the dot product result by dividing by .
The final self-attention formula is:
Multi-Head Attention
A single attention head may only capture one type of dependency (such as syntactic or semantic relations).
Solution: use multiple parallel attention heads, each learning a different projection space, thereby capturing different types of patterns.
Define heads:
- The output of the -th head is:
- where:
- Each head has its own independent learnable parameters .
Concatenate the outputs of all heads:
The dimension is .
Then project back to the original dimension via a linear transformation :
where has dimensions .
Usually set , so that the concatenated dimension is exactly .

Information flow of multi-head attention
Transformer Layer
Multi-head self-attention is the core of the Transformer. To build a deep network, multiple layers need to be stacked.
To improve training, residual connections (see Chapter 9 - Residual Connections) and Layer Normalization (Layer Normalization, which independently normalizes the feature vector of each token to stabilize training) are introduced:
Let the output of multi-head attention be , then the result after adding the residual connection and layer normalization is:
This ensures that even if the attention layer learns nothing (), information can still pass through the residual path .
“Pre-normalization” can also be used:
The output of the attention layer is a linear combination of the input vectors (via the attention weights), which limits its expressiveness.
To introduce nonlinear transformations, a Multi-Layer Perceptron (MLP) is usually added after the attention layer:
- For example, a two-layer fully connected network, using the ReLU activation function in between.
- Residual connections and layer normalization are also used.

A complete Transformer layer: the input goes through multi-head self-attention (with residual and normalization) to get , then goes through the MLP (a multi-layer network, with residual and normalization) to get the final output , containing two sub-layers:
- Multi-head self-attention sub-layer (highlighting relations)
- Receives input .
- Computes the multi-head attention output .
- Applies the residual connection: . (stabilizes representation)
- Applies layer normalization: .
Input X → multi-head self-attention → Y(X) → residual connection + layer normalization → Z
- Feed-forward neural network sub-layer (enriching representation)
- Receives the output from the previous step.
- Performs a nonlinear transformation via a fully connected MLP. The usual structure is: where typically has dimensions (, e.g., 4 times), and has dimensions , ensuring the output dimension matches the input.
- Applies the residual connection: .
- Applies layer normalization: .
Z → MLP → MLP(Z) → residual connection + layer normalization → final output X̃
The final output has the same dimension as the input , which is .
By stacking multiple such Transformer layers, a deep network can be built:
where is the initial input (usually word embeddings plus positional encoding), and is the final representation, which can be used for downstream tasks (such as classification, generation, etc.).
Positional Encoding
The self-attention mechanism has a key property: it is permutation invariant or order-independent.
From the formula , it can be seen that the computation depends only on the dot products and linear combinations between vectors. If we arbitrarily reorder the rows of the input sequence (i.e., the tokens), as long as we apply the same permutation to , the final output will be the result of the same permutation.
However, in most sequence tasks (especially NLP), order is crucial. For example, “the cat chases the mouse” and “the mouse chases the cat” have completely different meanings. A standard self-attention layer cannot distinguish between these two cases.
To enable the model to exploit sequence order, positional information (the index of a token in the sequence) must be explicitly injected into the input. (Add a “position label” to the words)
The most common method is positional encoding: Add the positional encoding vector to the input embedding vector of the -th token:
In matrix form, add the positional encoding matrix to the input matrix :
where is an matrix, and the -th row is the encoding vector for position .
The positional encoding vector must satisfy:
- Uniqueness: each position has a unique encoding.
- Learnable or deterministic: the encoding can be a learnable parameter or a predefined function.
Sine/cosine encoding:
Use sine and cosine functions of different frequencies to generate . For position and dimension :
where .
Characteristics:
- Deterministic: the encoding is precomputed and not learnable.
- Periodicity: different dimensions have different wavelengths (controlled by ).
- Relative position: the model can relatively easily learn the relationship between and (e.g., via a linear transformation), which helps capture relative positional information.

(a) In the figure, the horizontal axis represents the different components of the embedding vector r_n, and the vertical axis represents the position in the sequence. The vector element values at position n and position m are both given by the intersections of the corresponding sine and cosine curves with the horizontal gray lines. (b) Heat map of the positional encoding vectors defined by the above equation for the first N=200 positions with L=30, where the dimension is D=100
Learnable positional encoding
A simpler method is to treat the positional encoding as a learnable parameter. Initialize an matrix ( is the maximum sequence length supported by the model), where each row corresponds to the encoding vector of a position. During training, these vectors are optimized together as model parameters.
This method usually performs well in practice and is simple to implement.
When becomes , when computing the Query, Key, and Value:
The positional information is encoded into . Therefore, when computing the attention weights , the dot product depends not only on the semantics of and , but also on their positions and . This enables the model to distinguish sequences with different orders.
Each token of the input sequence is added a position-dependent vector, and then this augmented sequence representation is fed into the first Transformer layer.
Natural Language
Natural language (such as English, Chinese) is essentially a sequence of symbols. A sentence can be viewed as an ordered list composed of words and punctuation marks, which are usually separated by spaces. For example: ["The", "cat", "sat", "on", "the", "mat", "."]
This sequentiality is the core of language understanding. Changing the word order usually changes the meaning of the sentence, or even makes it meaningless. For example:
"The cat chased the dog."(the cat chases the dog)"The dog chased the cat."(the dog chases the cat)"Chased cat the dog the."(grammatically incorrect, hard to understand)
Therefore, models that process language must be able to capture and exploit long-range dependencies in the sequence, such as the dependency between the subject and the verb, even when they are far apart.
one-hot encoding: One-hot encoding maps each word to a vector of length equal to the vocabulary size, where only one element is 1 and the rest are 0. For example, for a vocabulary of size 10, the one-hot encoding of the word “cat” is: [0, 0, 1, 0, 0, 0, 0, 0, 0, 0]. Each word occupies an independent dimension in the vocabulary.
Word Embeddings
One-hot encoding suffers from high dimensionality (when the vocabulary is large) and the inability to capture relationships between words. Word embeddings solve these problems by mapping words to low-dimensional dense vectors.
- Embedding matrix definition: Let the embedding space dimension be D and the vocabulary size be K, then the embedding matrix E has dimensions . For a one-hot encoded input vector , its corresponding embedding vector is: Since is a one-hot vector, is essentially the corresponding column vector of the matrix E.
- Word2vec model:
- A method that learns word embeddings through a two-layer neural network, based on self-supervised learning (generating training samples from unlabeled text).
- Two variants:
- Continuous Bag of Words (CBOW): uses the context words in a window as input to predict the center word (a “fill-in-the-blank” task).
- Skip-gram: uses the center word as input to predict the context words in the window.

Word2vec model: left is the bag-of-words model, right is the skip-gram model
- Semantic properties of word embeddings:
- Semantically related words are closer in the embedding space (e.g., “Paris” and “London”).
- Supports simple vector arithmetic, for example:
- Application methods:
- As a pretrained layer, the pretrained embedding matrix can be fixed, or used as a learnable layer in end-to-end training (the initial values can be random or use the pretrained matrix).
Tokenization
A fixed vocabulary cannot handle out-of-vocabulary words or spelling errors, while character-level processing loses word structure and is computationally expensive.
- Goal: combine the advantages of word-level and character-level processing, converting text into tokens (groups of characters, which may contain complete words, word fragments, or single characters).
- Byte Pair Encoding (BPE):
- Process: starting from individual characters, iteratively merge the most frequent adjacent token pairs (without merging across words), until a preset number of tokens is reached.

- As shown in the figure, first merge “pe” (appears 4 times, excluding “Pe""), then merge “ck” (appears 3 times), and so on.
- Process: starting from individual characters, iteratively merge the most frequent adjacent token pairs (without merging across words), until a preset number of tokens is reached.
- Advantages: handles out-of-vocabulary words, preserves word structure, and supports multimodal (e.g., code) processing.
Bag of Words Model
- Joint distribution assumption: assume that words in the sequence are independent, and the joint distribution decomposes as: completely ignoring word order (hence the name “bag of words”).
- Text classification application:
- Naive Bayes classifier: assumes words are independent within each class, and the class-conditional probability is:
- Posterior probability computation:
- Smoothing: when a word appears in the test set but not in training, its probability would be 0; smoothing (e.g., uniformly assigning small probabilities) is needed to avoid this.
Autoregressive Models
- Joint distribution decomposition: considering word order, decompose the joint distribution into a product of conditional probabilities:
- n-gram model:
- Simplified assumption: the conditional probability depends only on the previous L words (e.g., L=1 is bigram, L=2 is trigram).
- Example (L=2):
- Limitations:
- Parameter explosion: as L grows, the size of the probability table grows exponentially (difficult to exceed trigram).
- Long-range dependencies: cannot capture long-distance inter-word relations, and the generated text may be incoherent.
- Hidden Markov Model (HMM): passes long-range information through latent variables, but has limited capacity (depends on the latent state chain).
Recurrent Neural Networks (RNN)
- Motivation: solve the problems of variable sequence length and parameter sharing, supporting equivariance (the same word has consistent semantics at different positions).
- Structure:
- Introduce a hidden state ; the input is the current word and the previous hidden state , and the output is the current word and the new hidden state .

- Weights are shared across sequence positions, as shown in the figure (the initial hidden state is usually set to an all-zero vector).
- Introduce a hidden state ; the input is the current word and the previous hidden state , and the output is the current word and the new hidden state .
- Machine translation example:
- Encoder: processes the input sequence (e.g., English) and compresses it into a hidden state .
- Decoder: starting from and the token, generates the output sequence (e.g., Dutch) until the token, as shown in the figure below.

- Autoregressive property: each output word is used as the next input, similar to the autoregressive formula above.
Backpropagation Through Time
- Training method: compute gradients via backpropagation, with the error function being cross-entropy (the output uses softmax activation).
- Problems:
- Vanishing/exploding gradients: during training on long sequences, gradients decay or explode after passing through many steps.
- Poor long-range dependency: the input sequence must be compressed into a fixed-length , and long sequences easily lose information (bottleneck problem).
- Improved models:
- LSTM (Long Short-Term Memory) and GRU (Gated Recurrent Unit): enhance long-range information retention through gating mechanisms.
- Limitations:
- Poor parallel computation: sequence processing depends on previous steps, and cannot efficiently utilize GPUs.
- Still limited by the ability to model long-range dependencies.
Transformer Language Models
Divided into three categories by input-output form:
- Encoder model: input a sequence, output a fixed vector (e.g., sentiment analysis).
- Decoder model: input a vector, output a sequence (e.g., text generation).
- Sequence-to-sequence model: both input and output are sequences (e.g., translation).
Decoder Transformer
- GPT model: Generative Pretrained Transformer, an autoregressive model whose goal is to learn the conditional probability .
- Architecture:
- Input: token sequence (including positional encoding).
- Output: obtain the token probability distribution via linear transformation + softmax:

- Training method:
- Self-supervised learning: take a sequence from unlabeled text and train with as the target.
- Parallel processing: split the sequence into multiple subsequences (e.g., “I swam across the river” is split into “I swam” → “across”, “I swam across” → “the river”, etc.).
- Masked attention (causal attention): ensure that when predicting , only previous tokens are attended to, as shown in the figure below (attention weights in the red region are set to 0).

- Sequence processing:
- Padding token : unifies sequences of different lengths, and the attention of is ignored via masking.
- Generation process: each time sample the next token and add it to the sequence, looping until the token.
Sampling Strategies
- Greedy search: each time select the token with the highest probability; deterministic but may not be the optimal sequence.
- Beam search:
- Keep the B best hypotheses (beam width B), each time expand to , then filter out B.
- Needs length normalization (to avoid bias toward short sequences); computational cost is .
- Random sampling:
- Top-K sampling: sample from the K tokens with the highest probability according to normalized probabilities.
- Top-p sampling (nucleus sampling): sample from the set of tokens whose cumulative probability reaches the threshold p.
- Temperature parameter: adjusts the softmax distribution: approaches greedy, T=1 is the original distribution, tends toward uniform.
- Problems: greedy/beam search may repeat sequences, random sampling may generate meaningless text (human text has lower probability but is more reasonable).
Encoder Transformer
- BERT model: Bidirectional Encoder Representations, pretrained and then fine-tuned to adapt to downstream tasks.
- Pretraining method:
- Randomly select 15% of tokens to replace with (80%), a random word (10%), or keep the original word (10%), training the model to predict the original word.
- Bidirectionality: allows attending to both preceding and following tokens, without needing to shift the input right or use masking, as shown in the structure below.

- Fine-tuning:
- Classification tasks: use the output of the first , followed by a linear layer + softmax.
- Token-level tasks: use all outputs, followed by a shared linear layer + softmax.
- Limitation: low training efficiency (only some tokens are targets), and cannot generate sequences.
Sequence-to-Sequence Transformer
- Application: e.g., translation (input English, output Dutch), combining an encoder and a decoder.
- Cross-attention: the decoder’s Query comes from the generated sequence, and the Key and Value come from the encoder’s output .
- Overall architecture: as shown in the figure below, the encoder processes the input sequence, and the decoder combines the encoder’s output through cross-attention to generate the target sequence.

Large Language Models (LLMs)
- Scale: parameters reach the trillion level (e.g., GPT-4), relying on large-scale text data and parallel computation (GPU clusters).
- Training paradigm:
- Self-supervised pretraining: learn language patterns on massive unlabeled text.
- Fine-tuning: adapt to downstream tasks via a small amount of labeled data (transfer learning).
- Low-Rank Adaptation (LoRA):
- Freeze the pretrained model weights, add low-rank matrices () and (), and the output is ().
- After fine-tuning, merge weights: , reducing the number of parameters (e.g., by 1/10000).
- Prompt engineering: guide the model to complete tasks by designing input prompts (e.g., “translate: …”), supporting few-shot learning.
- RLHF: optimize model outputs via Reinforcement Learning from Human Feedback (e.g., ChatGPT).
Multimodal Transformer
- Core: convert different modalities (text, image, audio, etc.) into tokens, and process them uniformly with a Transformer.
Vision Transformer
- Image tokenization:
- Split the image into non-overlapping patches (e.g., ), and flatten them into vectors.
- Or use a small CNN for downsampling to generate tokens.
- Architecture: as shown in the figure below, add a and learnable positional encoding, and output the classification result through the encoder.
- Characteristics: weak inductive bias (relies on data to learn image geometric properties), requires more training data, but may achieve higher accuracy.

Generative Image Transformer
- Autoregressive generation: predict pixels in raster scan order (reading order), with the joint distribution decomposed as:
- Discrete representation:
- Vector Quantization (VQ): approximate pixel patches with a codebook , , solving the blurriness problem of continuous-value generation.
- ImageGPT: maps pixels to a discrete color codebook and uses a Transformer to learn next-token prediction.
Audio Data Processing
- Mel Spectrogram: convert the audio waveform into a time-frequency matrix (perceptually uniform frequency division).
- Audio classification:
- Split the mel spectrogram into patches, generate tokens, and feed them into the Transformer encoder.
- Use the output for classification results, outperforming CNNs (which excel at long-range dependencies).
Text-to-Speech

Vall-E
- Vall-E model:
- Speech tokenization: convert speech into discrete tokens using vector quantization.
- Input: text tokens + a few speech tokens of the target speaker, output the corresponding speech tokens, as shown in the figure above.
- Advantage: can imitate a new speaker’s voice with only a few seconds of samples.
Vision and Language Transformer
- Data: e.g., LAION400M (text-image pairs), supporting text-to-image generation, image-to-text generation, etc.
- Parti model: encoder-decoder architecture, input text tokens, output image tokens (vector-quantized patches).
- CM3Leon model:
- Training data: HTML documents containing text and images.
- Supports multi-tasks such as text-image generation, image editing, and caption generation.
Exercise 1
There is a in the attention formula; what happens if we don’t divide?
When the dimension is large, the dot product value of and becomes very large, and softmax is directly “saturated” — the output is all 0s and 1s, and the gradient is almost zero, so training gets stuck. Dividing by brings the values back into a reasonable range so that softmax can work normally.
Where is multi-head attention better than single-head? Give an example?
A single head can only learn one kind of relation, while multiple heads can learn several at the same time. For example, in “The cat that sat on the mat is black”, one head might focus on cat→is (syntax), another head on cat→black (semantics), and another head on cat→mat (position). Concatenated together, the information is much richer than with a single head.
Exercise 2
RNNs inherently know the order of words, while Transformers need to add positional encoding separately. Why?
An RNN reads word by word; the hidden state at step naturally contains the information of “there are words before”. The Transformer’s self-attention processes all words at once — it only looks at “who is similar to whom”, completely ignoring order. Without positional encoding, “the cat chases the dog” and “the dog chases the cat” look exactly the same to it.
Chapter 12 Summary
One-sentence version:
- Attention mechanism: lets the model dynamically decide “where to look”, understood through the information retrieval analogy of Q/K/V — the better the query matches the key, the greater the weight of the corresponding value
- Self-attention: Q, K, and V all come from the same sequence, solving the disambiguation problem of whether “bank” means a river bank or a financial institution
- Multi-head attention: multiple attention heads run in parallel, each capturing a different type of dependency (syntax, semantics, etc.), then concatenate and project
- Positional encoding: add position labels to tokens, solving the “permutation invariant” shortcoming of self-attention — without it, “the cat chases the dog” and “the dog chases the cat” cannot be distinguished
- Transformer layer: attention sub-layer (mixing inter-token relations) + feed-forward sub-layer (enriching each token’s representation), stabilized by residual connections and layer normalization
- Three major architectures: encoder (BERT, bidirectional understanding), decoder (GPT, autoregressive generation), Seq2Seq (translation, etc., connected by cross-attention)
Knowledge map:
Self-attention (Q/K/V + Softmax) ↓ introduce learnable parametersScaled self-attention (÷√D_k to prevent saturation) ↓ parallel multiple groupsMulti-head attention → concatenate + linear projection ↓ add residual connection + layer normalization + feed-forward MLPTransformer layer → stack L layers → deep network ↓ add positional encoding (sine/learnable) ├── Encoder (BERT): bidirectional, masked language model ├── Decoder (GPT): autoregressive, causal attention └── Seq2Seq: encoder + decoder + cross-attentionChapter 13 Graph Neural Networks
Sequences (1D) and images (2D grids) are special cases of structured data, while more general structured data can be described by a Graph — composed of nodes and edges, where both nodes and edges can be associated with data (e.g., atom types in a molecule, travel time in a railway network).
Graph-Based Machine Learning
- Node prediction: predict node attributes (e.g., classify document topics based on hyperlinks between web pages).
- Edge prediction (graph completion): predict whether an edge exists (e.g., completing unobserved interactions in a protein-protein interaction network).
- Graph prediction (regression/classification): predict properties of an entire graph (e.g., the water solubility of a molecule), where the training data is a set of multiple independent graphs.
- Inductive learning and transductive learning:
- Inductive learning: training and test graphs/nodes are independent (e.g., predicting the properties of a new molecule).
- Transductive learning: the entire graph structure is known, but only some nodes are labeled, and the labels of the remaining nodes are predicted (e.g., distinguishing real humans from bots in a social network).
- Graph representation learning: learn an effective internal representation of the graph for downstream tasks (e.g., pretrain a molecule foundation model, then fine-tune it for specific tasks).
Basic Concepts and Notation of Graphs
- Definition of a graph: a graph , where is the node set and is the edge set. Node indices , an edge connects node and node , and the neighbor set of node is denoted .
- Node data: the attributes of each node are represented by a -dimensional vector , and all node data form an matrix (row is ).
Adjacency Matrix
An matrix , where if there is an edge between node and , otherwise 0. For an undirected graph, is symmetric with .
- Problem: the adjacency matrix depends on the node ordering, whereas the properties of a graph should be independent of the node ordering.

Adjacency matrix depends on node ordering
Permutation Invariance and Equivariance
- Permutation matrix: is an matrix with only one 1 in each row and each column, used to represent node reordering. If node is reordered to , then row of is the unit vector .
- Data permutation:
- Node data matrix: with rows reordered along with the nodes.
- Adjacency matrix: (both rows and columns are reordered).
- Network output requirements:
- Graph-level prediction requires permutation invariance: .
- Node-level prediction requires permutation equivariance: (the prediction is reordered synchronously with the nodes).
Neural Message Passing
- Goal: build a network that satisfies permutation equivariance/invariance, supports multi-layer nonlinear transformations, handles variable-length graphs, and is scalable.
- Convolutional Neural Networks (CNN, see Part 5) — an image can be viewed as a special graph (pixels as nodes, adjacent pixels as edges); CNNs aggregate information through local filters, and graph neural networks similarly aggregate information through neighbors.
Graph Convolution and the Message Passing Framework
From CNN to graph convolution:
- filter in CNN: (j is a local pixel).
- Graph convolution modification: aggregate neighbor information, with shared parameters to ensure equivariance: where (neighbor weight) and (self weight) are shared across all nodes.
Message Passing Neural Network:
- Process: each layer is divided into two steps, Aggregate and Update.
- Aggregate: for node n, aggregate the neighbor embeddings:
- Update: combine its own embedding with the aggregation result:
- Initialization: (the initial node embedding is its attributes).
Message Passing
Aggregation Operators
Must satisfy: independent of neighbor order, support a variable number of neighbors, and be differentiable. Common forms:
- Sum: collect information from all neighbor nodes Advantage: preserves neighbor count information; disadvantage: nodes with many neighbors have excessively strong influence.
- Mean: Advantage: normalized; disadvantage: loses neighbor count information.
- Symmetric normalization: balances the neighbor count differences between different nodes.
- Element-wise max/min: take the element-wise max/min of neighbor embeddings, which also satisfies permutation invariance.
- Parametric aggregation: introduce learnable parameters via an MLP (universal approximator): where (neighbor transformation) and (post-aggregation transformation) are shared networks.
Update Operators
The new state of a node = process (aggregated information + the node’s original information)
- Basic form: combine its own embedding with the aggregation result, and update via a nonlinear transformation: where is an activation function (e.g., ReLU), and are weight matrices.
- Simplified form: if and aggregation uses sum, then:
Suppose we have a 3x3 image patch
- CNN: the center pixel 5 will consider the surrounding 1,2,3,4,6,7,8,9
- GNN: the center node 5 only considers directly connected nodes 1,2,6,7
Node/Edge/Graph Classification Implementation
Node classification: (predict the class of each node in the graph)
- Output layer: apply softmax to the final embedding :
- Loss function: cross-entropy loss (only training nodes participate): where is the one-hot target label.
After each node is processed by the GNN, it obtains an embedding vector . Then apply softmax classification to : to get the probabilities of each class.
Edge classification: (predict whether there is an edge between two nodes (relation prediction)) use the similarity of node embeddings:
where is the sigmoid function.
Graph classification: (predict the class of the entire graph)
- Graph representation: aggregate all node final embeddings (ensuring permutation invariance): the aggregation function can be sum, mean, max, etc. (see above), and is the output network.
General Graph Networks
Graph Attention Network
Just as in social life we pay more attention to some friends’ opinions, the Graph Attention Network lets nodes “attend to” more important neighbors.
- Core: use attention coefficients to weight neighbor information and dynamically adjust neighbor importance: where and (attention coefficients).
- Attention coefficient computation:
- Bilinear form: .
- MLP form: .
- Multi-head attention: use H independent attention heads, concatenate the results and project, enhancing expressiveness.
Edge Embeddings and Graph Embeddings
Not only do nodes have features, but the edges connecting nodes also have their own features.
- Edge embedding: introduce the hidden variable for edges, with the update formula: node aggregation is changed to be based on edge embeddings: .
The entire graph has a global feature vector.
- Graph embedding: introduce the global graph embedding , updated by integrating all node and edge information:

(a) edge update, (b) node update, (c) global graph update. The variable being updated is shown in red, while the variables that contribute to the update are shown in blue
Over-smoothing
“He who stays near vermilion gets red; he who stays near ink gets black.” After many rounds of message passing, all nodes become increasingly similar.
Social network rumor-spreading analogy: Imagine a rumor spreading in a social network — in the first round, your direct friends tell you some information; in the second round, information from your friends’ friends also reaches you; in the third round, the fourth round… after many rounds, everyone in the network has “heard roughly the same version”, and the original personalized information (who started the message, who it passed through in between) is completely “averaged out”. The GNN over-smoothing problem is similar: too many layers cause all node embeddings to converge to the same “average value”, losing discriminability.
- Problem: after multiple layers of message passing, node embeddings tend to become similar, limiting network depth.
- Mitigation methods:
- Residual connection (see Part 4): .
- Multi-layer feature fusion: ( is concatenation).
Geometric Deep Learning
- Core: incorporate spatial symmetries (such as rotation/translation invariance of molecules) into the graph network. For example, introduce an atom coordinate embedding () in a molecule model, and use the squared coordinate difference in the update (rotation/translation invariant): ensuring that molecule property prediction is independent of the coordinate system.
Exercise 3
In a social network, nodes are users and edges are friend relations. To predict each user’s interests (node classification), is sum or mean better for the aggregation operator? What about predicting the activity of the entire network (graph classification)?
For node classification, it depends: if “having many friends or not” is itself an important feature (e.g., social butterfly vs. introvert), use sum; otherwise mean is more stable and won’t be disturbed by the number of friends.
For graph classification, you must first “compress” all node representations into a single vector (global pooling), and only then can you make a prediction. Here you must use a permutation-invariant operation (such as sum or mean), because node indices are arbitrarily assigned.
What are the obvious shortcomings of GNNs?
The biggest problem is over-smoothing: with too many layers, the representations of all nodes become identical — because each layer aggregates neighbor information, after several rounds every node has “seen” the entire graph, and the discriminability is lost.
In addition, GNNs inherently cannot distinguish certain graph structures (e.g., a ring and a chain, a GNN might think they are the same), and distant nodes need to stack many layers to “communicate”, but stacking layers leads to over-smoothing. Quite contradictory.
Chapter 13 Summary
One-sentence version:
- Graph data: a more general structure than sequences and images — nodes (entities) + edges (relations), applicable from molecules to social networks
- Message passing: the core operation of GNNs — each round aggregates neighbor information and updates its own state, like “updating your own view by listening to your friends’ opinions”
- Aggregation operators: sum (preserves neighbor count), mean (normalized), max (captures key features), the choice depends on the task
- Permutation invariance/equivariance: graph predictions must not depend on the node index order — graph-level predictions must be invariant, node-level predictions must change synchronously with the nodes
- Graph attention: lets nodes learn “which neighbors to pay more attention to”, like trusting some friends’ opinions more in social life
- Over-smoothing: too many rounds of message passing make all node embeddings converge — mitigated by residual connections and multi-layer feature fusion
Knowledge map:
Graph = nodes + edges (represented by adjacency matrix) ↓ permutation invariance/equivariance constraintsMessage passing framework: aggregate (neighbor info) → update (own state) ├── Graph convolution: neighbor aggregation with shared parameters (analogous to CNN) ├── Graph attention: dynamically weighted neighbors (analogous to Transformer attention) └── General graph network: + edge embedding + global graph embedding ↓ multi-layer stacking → over-smoothing problem → mitigated by residual connection ↓Downstream tasks: node classification / edge prediction / graph classification