tahamajs's picture
download
raw
21 kB
#!/usr/bin/env python3
"""
Script to enhance the GNN notebook with comprehensive IEEE-format markdown explanations
"""
import json
import sys
def create_gat_markdown():
"""Create comprehensive GAT markdown content"""
return """## 4. GAT: Graph Attention Networks <a id="section4"></a>
### 4.1 Motivation and Theoretical Foundation
**Graph Attention Networks (GAT)** [5] address a fundamental limitation of GCN: all neighbors contribute equally to a node's representation. In real-world graphs, not all connections are equally important. GAT introduces an attention mechanism that learns to weight neighbor contributions adaptively.
**Key Innovation:**
Instead of fixed normalization weights (like GCN), GAT computes attention coefficients that:
- Are learned from data
- Can assign different importance to different neighbors
- Provide interpretability through attention weights
### 4.2 Mathematical Formulation - Complete Description
**Single-head Attention:**
The GAT layer update for node $v$ is:
$$h_v^{(l+1)} = \\sigma\\left(\\sum_{u \\in \\mathcal{N}(v)} \\alpha_{vu} \\mathbf{W}^{(l)} h_u^{(l)}\\right)$$
**Attention Coefficient Computation:**
The attention coefficients $\\alpha_{vu}$ are computed in three steps:
**Step 1: Compute Attention Logits**
$$e_{vu} = \\text{LeakyReLU}\\left(\\mathbf{a}^T \\left[\\mathbf{W}h_v \\,||\\, \\mathbf{W}h_u\\right]\\right)$$
Where:
- $\\mathbf{W} \\in \\mathbb{R}^{f' \\times f}$: Shared weight matrix for feature transformation
- $\\mathbf{a} \\in \\mathbb{R}^{2f'}$: Learnable attention vector
- $||$: Concatenation operation
- $\\text{LeakyReLU}$: LeakyReLU activation with negative slope 0.2
**Step 2: Normalize with Softmax**
$$\\alpha_{vu} = \\text{softmax}_u(e_{vu}) = \\frac{\\exp(e_{vu})}{\\sum_{k \\in \\mathcal{N}(v)} \\exp(e_{vk})}$$
This ensures: $\\sum_{u \\in \\mathcal{N}(v)} \\alpha_{vu} = 1$
**Step 3: Aggregate Weighted Features**
$$h_v^{(l+1)} = \\sigma\\left(\\sum_{u \\in \\mathcal{N}(v)} \\alpha_{vu} \\mathbf{W}h_u^{(l)}\\right)$$
### 4.3 Multi-Head Attention Mechanism
To stabilize learning and increase model capacity, GAT employs multi-head attention:
**Multi-Head Aggregation:**
$$h_v^{(l+1)} = \\Big|\\Big|_{k=1}^K \\sigma\\left(\\sum_{u \\in \\mathcal{N}(v)} \\alpha_{vu}^k \\mathbf{W}^k h_u^{(l)}\\right)$$
Where:
- $K$: Number of attention heads
- $||$: Concatenation of head outputs
- $\\alpha_{vu}^k$: Attention coefficient for head $k$
- $\\mathbf{W}^k$: Weight matrix for head $k$
**For Final Layer (Average Instead of Concatenate):**
$$h_v^{(L)} = \\sigma\\left(\\frac{1}{K}\\sum_{k=1}^K \\sum_{u \\in \\mathcal{N}(v)} \\alpha_{vu}^k \\mathbf{W}^k h_u^{(L-1)}\\right)$$
### 4.4 Intuitive Understanding
**Attention Mechanism Analogy:**
Think of attention like a student studying from multiple textbooks:
- **GCN**: Gives equal time to all books (fixed weights)
- **GAT**: Spends more time on important books (learned weights)
**Attention Score Interpretation:**
High $\\alpha_{vu}$ means:
- Node $u$ is highly relevant to node $v$
- Information from $u$ is important for $v$'s representation
- Strong semantic connection between $u$ and $v$
### 4.5 Advantages Over GCN
**1. Adaptive Neighborhood Aggregation:**
- GCN: $\\frac{1}{\\sqrt{deg(u) \\cdot deg(v)}}$ (fixed)
- GAT: $\\alpha_{vu}$ (learned from data)
**2. Variable Neighbor Importance:**
- Can handle heterogeneous neighborhoods
- Focuses on relevant connections
- Reduces noise from irrelevant neighbors
**3. Inductive Learning:**
- Attention computed on-the-fly
- No dependence on global graph structure
- Generalizes to unseen nodes/graphs
**4. Interpretability:**
- Attention weights provide insights
- Can visualize which connections matter
- Useful for explainable AI applications
### 4.6 Computational Complexity
**Time Complexity per Layer:**
$$O(|\\mathcal{E}| \\cdot K \\cdot f' + |\\mathcal{V}| \\cdot K \\cdot f \\cdot f')$$
Where:
- $K$: Number of attention heads
- $f$: Input dimension
- $f'$: Output dimension per head
- $|\\mathcal{E}|$: Number of edges
- $|\\mathcal{V}|$: Number of nodes
**Breakdown:**
1. Feature transformation: $O(|\\mathcal{V}| \\cdot K \\cdot f \\cdot f')$
2. Attention computation: $O(|\\mathcal{E}| \\cdot K \\cdot f')$
3. Aggregation: $O(|\\mathcal{E}| \\cdot K \\cdot f')$
### 4.7 Advantages and Limitations
**Advantages:**
✅ **Adaptive Weighting**: Learns neighbor importance
✅ **Interpretability**: Attention weights are interpretable
✅ **Robustness**: Multi-head attention increases stability
✅ **Inductive**: No global graph structure needed
✅ **Expressiveness**: More powerful than GCN
**Limitations:**
❌ **Computational Cost**: More expensive than GCN (~2-3x)
❌ **Memory**: Stores attention weights for all edges
❌ **Training Time**: Slower convergence in some cases
### References:
[5] Veličković, P., et al. (2018). "Graph Attention Networks." ICLR."""
def create_graphsage_markdown():
"""Create comprehensive GraphSAGE markdown content"""
return """## 5. GraphSAGE: Sample and Aggregate <a id="section5"></a>
### 5.1 Theoretical Foundation and Motivation
**GraphSAGE** (SAmple and aggreGatE) [6] was designed to address scalability challenges in GNNs. Unlike GCN and GAT which require the entire graph during training, GraphSAGE enables:
- **Inductive learning**: Generalize to completely unseen nodes
- **Mini-batch training**: Process subsets of the graph
- **Scalability**: Handle graphs with millions/billions of nodes
**Key Innovation:**
Instead of using all neighbors, GraphSAGE samples a fixed-size neighborhood at each layer, making computation independent of node degree.
### 5.2 Mathematical Formulation - Complete Description
The GraphSAGE algorithm consists of three main steps:
**Step 1: Sample Neighbors**
For each node $v$, sample a fixed-size set of neighbors:
$$\\mathcal{N}_S(v) \\subset \\mathcal{N}(v), \\quad |\\mathcal{N}_S(v)| = S$$
Where $S$ is a predefined sample size (e.g., 10-25 neighbors).
**Step 2: Aggregate Neighbor Features**
Aggregate features from sampled neighbors using an aggregation function:
$$h_{\\mathcal{N}(v)}^{(l)} = \\text{AGGREGATE}_l\\left(\\{h_u^{(l-1)}, \\forall u \\in \\mathcal{N}_S(v)\\}\\right)$$
**Step 3: Combine with Self Features**
Concatenate aggregated neighborhood with node's own features and apply transformation:
$$h_v^{(l)} = \\sigma\\left(\\mathbf{W}^{(l)} \\cdot \\text{CONCAT}\\left(h_v^{(l-1)}, h_{\\mathcal{N}(v)}^{(l)}\\right)\\right)$$
**Step 4: L2 Normalization (Optional)**
$$h_v^{(l)} \\leftarrow \\frac{h_v^{(l)}}{\\|h_v^{(l)}\\|_2}$$
This normalization improves performance in many tasks.
### 5.3 Aggregation Functions
GraphSAGE supports multiple aggregation strategies:
**1. Mean Aggregator:**
$$h_{\\mathcal{N}(v)}^{(l)} = \\frac{1}{|\\mathcal{N}_S(v)|} \\sum_{u \\in \\mathcal{N}_S(v)} h_u^{(l-1)}$$
- **Pros**: Simple, efficient, differentiable
- **Cons**: Loses information about set structure
**2. Max Pooling Aggregator:**
$$h_{\\mathcal{N}(v)}^{(l)} = \\max_{u \\in \\mathcal{N}_S(v)} \\sigma\\left(\\mathbf{W}_{\\text{pool}} h_u^{(l-1)} + b\\right)$$
- **Pros**: Captures diverse features, element-wise max
- **Cons**: May lose information from average neighbors
**3. LSTM Aggregator:**
$$h_{\\mathcal{N}(v)}^{(l)} = \\text{LSTM}\\left(\\{h_u^{(l-1)}, \\forall u \\in \\pi(\\mathcal{N}_S(v))\\}\\right)$$
Where $\\pi$ is a random permutation.
- **Pros**: Most expressive, can capture complex patterns
- **Cons**: Not permutation invariant, computationally expensive
**4. GCN Aggregator:**
$$h_v^{(l)} = \\sigma\\left(\\mathbf{W}^{(l)} \\cdot \\text{MEAN}\\left(\\{h_v^{(l-1)}\\} \\cup \\{h_u^{(l-1)}, \\forall u \\in \\mathcal{N}_S(v)\\}\\right)\\right)$$
- **Pros**: Combines simplicity of mean with proven effectiveness
- **Cons**: Similar to GCN but with sampling
### 5.4 Neighborhood Sampling Strategy
**Fixed-Size Sampling:**
At each layer $l$, sample $S_l$ neighbors:
```
Layer 1: Sample S_1 neighbors (e.g., 25)
Layer 2: Sample S_2 neighbors for each Layer 1 neighbor (e.g., 10)
Total nodes: 1 + S_1 + S_1 * S_2 = 1 + 25 + 250 = 276
```
**Uniform Sampling:**
- Each neighbor has equal probability: $p_u = \\frac{1}{|\\mathcal{N}(v)|}$
- Simple but doesn't consider importance
**Importance Sampling:**
- Weight by edge features or node centrality
- $p_u \\propto \\text{importance}(u, v)$
- More sophisticated but requires additional computation
### 5.5 Inductive Learning Capability
**Why GraphSAGE is Inductive:**
1. **No Global Graph Structure**: Doesn't use global adjacency matrix
2. **Local Computation**: Only depends on node features and local topology
3. **Shared Parameters**: Same weights applied to all nodes
4. **On-the-fly Aggregation**: Can compute embeddings for new nodes
**Transductive vs Inductive:**
- **Transductive (GCN)**: Requires retraining for new nodes
- **Inductive (GraphSAGE)**: Directly computes embeddings for new nodes
**Applications:**
- Evolving graphs (social networks, citation networks)
- Large graphs where not all nodes seen during training
- Cross-graph generalization
### 5.6 Computational Complexity
**Time Complexity per Node:**
$$O\\left(\\prod_{l=1}^L S_l \\cdot d \\cdot f\\right)$$
Where:
- $L$: Number of layers
- $S_l$: Sample size at layer $l$
- $d, f$: Feature dimensions
**Example (2-layer, S_1=25, S_2=10):**
- Computation per node: $O(250 \\cdot d \\cdot f)$
- Independent of total graph size!
**Space Complexity:**
$$O\\left(\\sum_{l=1}^L \\prod_{k=1}^l S_k \\cdot d_l\\right)$$
**Key Advantage:**
Complexity is independent of graph size, enabling scalability to billion-node graphs.
### 5.7 Mini-Batch Training
GraphSAGE enables efficient mini-batch training:
```python
for batch in data_loader:
# Sample computational graph for batch
sampled_nodes, sampled_edges = sample_neighborhood(batch)
# Forward pass only on sampled subgraph
embeddings = model(sampled_nodes, sampled_edges)
# Compute loss and backpropagate
loss = criterion(embeddings, labels)
loss.backward()
```
**Benefits:**
- Constant memory usage per batch
- Can train on graphs larger than GPU memory
- Faster iteration time
### 5.8 Advantages and Limitations
**Advantages:**
✅ **Scalability**: Handles billion-node graphs
✅ **Inductive**: Generalizes to unseen nodes
✅ **Mini-batch Training**: Efficient memory usage
✅ **Flexible Aggregation**: Multiple aggregator choices
✅ **Fast Inference**: Fixed computation per node
✅ **Cross-Graph**: Can generalize across different graphs
**Limitations:**
❌ **Sampling Variance**: Stochastic results from sampling
❌ **Information Loss**: May miss important distant neighbors
❌ **Hyperparameter Tuning**: Sample sizes need tuning
❌ **Neighbor Distribution**: Performance depends on sampling strategy
❌ **Training Time**: May need more epochs due to sampling
### 5.9 Implementation Considerations
**Key Design Choices:**
1. **Sample Sizes ($S_l$):**
- First layer: 10-25 neighbors
- Deeper layers: 5-10 neighbors
- Larger samples → better accuracy but slower
2. **Number of Layers:**
- 2-3 layers typical
- Each layer expands receptive field exponentially
3. **Aggregator Selection:**
- Mean: Fast, works well in practice
- Max: Good for diverse neighborhoods
- LSTM: Most expressive but slowest
4. **L2 Normalization:**
- Often improves performance
- Particularly helpful for similarity tasks
5. **Batch Size:**
- Larger batches → more stable gradients
- Limited by GPU memory and sampling
### References:
[6] Hamilton, W. L., et al. (2017). "Inductive Representation Learning on Large Graphs." NeurIPS.
[7] Chen, J., et al. (2018). "FastGCN: Fast Learning with Graph Convolutional Networks via Importance Sampling." ICLR."""
def create_rgcn_markdown():
"""Create comprehensive R-GCN markdown content"""
return """## 6. R-GCN: Relational Graph Convolutional Networks <a id="section6"></a>
### 6.1 Motivation for Multi-Relational Graphs
**R-GCN** [7] is specifically designed for **multi-relational graphs** like Knowledge Graphs, where:
- Edges have different types/relations
- Each relation has different semantics
- Different relations require different transformations
**Problem with Standard GCN/GAT:**
- Treat all edges identically
- Cannot distinguish "employed_by" from "lives_in" from "friend_of"
- Lose crucial relational information
**R-GCN Solution:**
Use relation-specific transformations while maintaining parameter efficiency.
### 6.2 Mathematical Formulation - Complete Description
The R-GCN layer performs relation-specific message passing:
$$h_v^{(l+1)} = \\sigma\\left(\\sum_{r \\in \\mathcal{R}} \\sum_{u \\in \\mathcal{N}_v^r} \\frac{1}{c_{v,r}} \\mathbf{W}_r^{(l)} h_u^{(l)} + \\mathbf{W}_0^{(l)} h_v^{(l)}\\right)$$
**Components Explained:**
1. **Relation Set** $\\mathcal{R}$:
- Set of all relation types in the graph
- e.g., {employed_by, lives_in, friend_of, ...}
2. **Relation-Specific Neighborhoods** $\\mathcal{N}_v^r$:
- Neighbors of $v$ connected by relation $r$
- $\\mathcal{N}_v^r = \\{u : (u, r, v) \\in \\mathcal{G}\\}$
3. **Relation-Specific Weights** $\\mathbf{W}_r^{(l)} \\in \\mathbb{R}^{d_{l+1} \\times d_l}$:
- Separate transformation for each relation
- Captures relation-specific patterns
4. **Normalization Constant** $c_{v,r}$:
- Typically: $c_{v,r} = |\\mathcal{N}_v^r|$ (neighbor count)
- Prevents numerical instability
5. **Self-Loop Transformation** $\\mathbf{W}_0^{(l)}$:
- Separate weight for self-connections
- Preserves node's own information
### 6.3 Parameter Growth Problem
**Challenge:**
With $|\\mathcal{R}|$ relations, we need $|\\mathcal{R}| + 1$ weight matrices per layer:
$$\\text{Parameters} = (|\\mathcal{R}| + 1) \\times d_l \\times d_{l+1}$$
For Knowledge Graphs with hundreds/thousands of relations, this becomes impractical!
**Example:**
- 500 relations
- Hidden dim: 128
- Parameters per layer: $501 \\times 128 \\times 128 = 8.2M$ parameters
### 6.4 Regularization Strategies
R-GCN offers two regularization methods to control parameters:
**1. Basis Decomposition:**
Express each relation weight as a linear combination of basis matrices:
$$\\mathbf{W}_r^{(l)} = \\sum_{b=1}^B a_{rb}^{(l)} \\mathbf{V}_b^{(l)}$$
Where:
- $\\mathbf{V}_b^{(l)} \\in \\mathbb{R}^{d_{l+1} \\times d_l}$: Basis matrices (learned)
- $a_{rb}^{(l)} \\in \\mathbb{R}$: Combination coefficients (learned)
- $B$: Number of basis matrices (e.g., B=30)
**Parameters:**
- Without regularization: $(|\\mathcal{R}| + 1) \\times d_l \\times d_{l+1}$
- With basis: $B \\times d_l \\times d_{l+1} + |\\mathcal{R}| \\times B$
**Savings Example:**
- 500 relations, d=128, B=30
- Original: 8.2M parameters
- With basis: $30 \\times 128 \\times 128 + 500 \\times 30 = 506K$ parameters
- **16x reduction!**
**2. Block-Diagonal Decomposition:**
Restrict weight matrices to block-diagonal form:
$$\\mathbf{W}_r^{(l)} = \\text{diag}(\\mathbf{B}_{r,1}^{(l)}, \\mathbf{B}_{r,2}^{(l)}, ..., \\mathbf{B}_{r,B}^{(l)})$$
Where each block $\\mathbf{B}_{r,b}^{(l)} \\in \\mathbb{R}^{(d_{l+1}/B) \\times (d_l/B)}$
**Properties:**
- Forces sparse interactions between dimensions
- More parameter efficient than basis decomposition
- May lose some expressiveness
### 6.5 Knowledge Graph Specific Features
**Link Prediction Task:**
R-GCN is commonly used for link prediction in KGs:
$$\\text{score}(h, r, t) = \\sigma(e_h^T \\mathbf{R}_r e_t)$$
Where:
- $e_h, e_t$: Embeddings from R-GCN encoder
- $\\mathbf{R}_r$: Relation-specific scoring matrix
- $\\sigma$: Activation function
**Entity Classification:**
Predict entity types using R-GCN features:
$$p(\\text{type} | v) = \\text{softmax}(\\mathbf{W}_{\\text{class}} h_v^{(L)})$$
**Knowledge Graph Completion:**
Given incomplete triple $(h, r, ?)$ or $(?, r, t)$:
1. Encode entities with R-GCN
2. Score all candidates
3. Rank by score
### 6.6 Handling Highly Multi-Relational Graphs
**Strategies for Thousands of Relations:**
1. **Relation Clustering:**
- Group similar relations
- Share weights within clusters
- Reduces effective number of relation types
2. **Relation Embeddings:**
- Learn low-dimensional relation embeddings
- Use embeddings to generate weights
- $\\mathbf{W}_r = f(\\text{emb}(r))$
3. **Hierarchical Relations:**
- Exploit relation hierarchies
- Share parameters across hierarchy levels
- e.g., "teaches" and "mentors" share base weights
4. **Adaptive Basis:**
- Learn which relations share basis
- Sparse combination coefficients
- Attention over basis matrices
### 6.7 Computational Complexity
**Time Complexity per Layer:**
$$O\\left(|\\mathcal{E}| \\cdot d_l \\cdot d_{l+1} + |\\mathcal{R}| \\cdot B \\cdot d_l \\cdot d_{l+1}\\right)$$
With basis decomposition (B << |R|):
$$O\\left(|\\mathcal{E}| \\cdot d_l \\cdot d_{l+1} + B \\cdot d_l \\cdot d_{l+1}\\right)$$
**Key Insight:**
Main cost is message passing $(|\\mathcal{E}| \\cdot d_l \\cdot d_{l+1})$, not relation-specific transformations!
**Space Complexity:**
$$O(|\\mathcal{V}| \\cdot d_l + B \\cdot d_l \\cdot d_{l+1} + |\\mathcal{E}|)$$
### 6.8 Advantages and Limitations
**Advantages:**
✅ **Multi-Relational**: Explicitly models relation types
✅ **Knowledge Graphs**: Designed for KG reasoning
✅ **Parameter Efficient**: Basis decomposition scales well
✅ **Expressive**: Captures relation-specific patterns
✅ **End-to-End**: Joint learning of entity and relation representations
✅ **Interpretable**: Relation-specific weights provide insights
**Limitations:**
❌ **Complexity**: More complex than GCN/GAT
❌ **Parameter Tuning**: Need to choose num_bases carefully
❌ **Training Time**: Slower than simpler GNNs
❌ **Sparse Relations**: May overfit rare relations
❌ **Memory**: Stores relation-specific information
### 6.9 Implementation Considerations
**Key Design Choices:**
1. **Number of Bases (B):**
- Too few: Underfitting, relations can't be distinguished
- Too many: Overfitting, high parameter count
- Rule of thumb: $B \\approx \\sqrt{|\\mathcal{R}|}$ or 20-50
2. **Normalization:**
- Node-degree normalization: $c_{v,r} = |\\mathcal{N}_v^r|$
- Symmetric normalization: $c_{v,r} = \\sqrt{|\\mathcal{N}_v^r| \\cdot |\\mathcal{N}_u^r|}$
3. **Self-Loops:**
- Always include self-loop transformation
- Critical for preserving node information
4. **Relation Sampling:**
- For very large KGs, sample relations per batch
- Reduces memory and computation
5. **Regularization:**
- L2 regularization on basis coefficients
- Dropout on node features
- Careful not to overregularize rare relations
### References:
[7] Schlichtkrull, M., et al. (2018). "Modeling Relational Data with Graph Convolutional Networks." ESWC.
[8] Vashishth, S., et al. (2020). "Composition-based Multi-Relational Graph Convolutional Networks." ICLR."""
# Load the notebook
notebook_path = "/Users/tahamajs/Documents/uni/Sysmem2_in_AI/ComputerAssignments/CA10_knowledge_graphs/notebooks/02_Graph_Neural_Networks.ipynb"
print("📖 Loading notebook...")
with open(notebook_path, "r", encoding="utf-8") as f:
notebook = json.load(f)
print(f"✅ Loaded notebook with {len(notebook['cells'])} cells")
# Find and replace markdown cells
cell_count = 0
for i, cell in enumerate(notebook["cells"]):
if cell["cell_type"] == "markdown":
source = (
"".join(cell["source"])
if isinstance(cell["source"], list)
else cell["source"]
)
# Check if this is the GAT section
if (
"## 4. GAT: Graph Attention Networks" in source
and "Motivation and Theoretical Foundation" not in source
):
print(f"📝 Enhancing GAT section (cell {i})...")
cell["source"] = create_gat_markdown().split("\n")
cell_count += 1
# Check if this is the GraphSAGE section
elif (
"## 5. GraphSAGE" in source
and "Theoretical Foundation and Motivation" not in source
):
print(f"📝 Enhancing GraphSAGE section (cell {i})...")
cell["source"] = create_graphsage_markdown().split("\n")
cell_count += 1
# Check if this is the R-GCN section
elif (
"## 6. R-GCN: Relational" in source
and "Motivation for Multi-Relational" not in source
):
print(f"📝 Enhancing R-GCN section (cell {i})...")
cell["source"] = create_rgcn_markdown().split("\n")
cell_count += 1
print(f"\n✅ Enhanced {cell_count} sections")
# Save the enhanced notebook
print("💾 Saving enhanced notebook...")
with open(notebook_path, "w", encoding="utf-8") as f:
json.dump(notebook, f, indent=2, ensure_ascii=False)
print("✅ Notebook enhanced successfully!")
print(f"📍 Saved to: {notebook_path}")

Xet Storage Details

Size:
21 kB
·
Xet hash:
0e079e5ab802c4ad5e3db79ca8c2c6e10701b74c01cd6df5a3135bda6f14db95

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.