julia-graph-neural-networks
Skill0 starsChanged 5 days agoMITView on GitHub
Build graph neural networks in Julia with GraphNeuralNetworks.jl and Lux.jl. Use for GCN, GAT, GraphSAGE, message passing, graph tasks, and mini-batch training.
In this repository55 other files it gives its agents.
- advanced-optimizationSkill
- bayesian-inferenceSkill
- bayesian-pinnSkill
- bayesian-ude-workflowSkill
- catalyst-reactionsSkill
- continuum-mechanics-and-rheologySkill
- control-theorySkill
- creating-julia-appSkill
- debugging-toolkitSkill
- differential-equationsSkill
- differentiationSkill
- equation-discoverySkill
- experiment-trackingSkill
- fem-feaSkill
- julia-languageSkill
- julia-ml-and-dlSkill
- julia-model-deploymentSkill
- julia-paper-implementationSkill
- julia-pro-helpSkill
- julia-pro-modeSkill
- julia-reinforcement-learningSkill
- modeling-toolkitSkill
- neural-pdeSkill
- nonlinear-dynamicsSkill
- numerical-methods-implementationSkill
- package-development-workflowSkill
- performance-tuningSkill
- physical-learning-systemsSkill
- playbook-debugSkill
- playbook-model-validateSkill
- playbook-package-releaseSkill
- playbook-paper-implementSkill
- playbook-perfSkill
- playbook-test-specSkill
- principle-both-sidesSkill
- principle-breakingSkill
- principle-file-is-truthSkill
- principle-gateSkill
- principle-limitsSkill
- principle-loud-failureSkill
- principle-one-stepSkill
- principle-proof-listSkill
- principle-rebuttalSkill
- principle-runtime-surfaceSkill
- principle-three-boundsSkill
- principle-three-clocksSkill
- scientific-visualizationSkill
- sciml-and-diffeqSkill
- setup-julia-proSkill
- signal-processingSkill
- simulation-and-hpcSkill
- statistical-physicsSkill
- symbolic-mathSkill
- web-development-juliaSkill
- zarr-cloud-arraysSkill
The file
We split this skill into the rules it gives an agent
2 rules. About 0 are common, 0 are distinctive, and 2 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈0
Distinctive · estimate
This author's own choices. Worth a look.
2
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 12
Create graphs with GNNGraph:
- Very specific: line 171
Use MLDatasets for canonical graph benchmarks (Cora, CiteSeer, PubMed, OGB-arXiv, ZINC, QM9).
≈ “Common” is an estimate: at least 1 in 5 of the 408,460 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Julia Graph Neural Networks
For the canonical Lux training loop, custom message passing, and a molecular GNN example, read Lux training and message passing.
Graph Construction
Create graphs with GNNGraph:
using GraphNeuralNetworks
# From edge list
src = [1, 1, 2, 3, 3, 4]
dst = [2, 3, 4, 4, 5, 5]
g = GNNGraph(src, dst)
# From adjacency matrix
A = [0 1 1 0; 1 0 0 1; 1 0 0 1; 0 1 1 0]
g = GNNGraph(A)
# From Graphs.jl
using Graphs
lg = barabasi_albert(100, 3)
g = GNNGraph(lg)
# Add node and edge features
g = GNNGraph(src, dst;
ndata=(; x=randn(Float32, 16, 5)), # 16-dim features, 5 nodes
edata=(; w=randn(Float32, 1, 6))) # 1-dim edge weights, 6 edgesBuilt-in GNN Layers
| Layer | Description | Key Parameters |
GCNConv | Graph Convolutional Network | in => out |
GATConv | Graph Attention Network | in => out, heads |
SAGEConv | GraphSAGE (sampling + aggregation) | in => out, aggr |
GINConv | Graph Isomorphism Network | nn (MLP) |
EdgeConv | Dynamic Edge Convolution | nn (MLP) |
GatedGraphConv | Gated Graph Neural Network | out, num_layers |
GCN Example
using GraphNeuralNetworks, Lux, Random
# Build GCN model with GNNChain
model = GNNChain(
GCNConv(16 => 64, relu),
GCNConv(64 => 32, relu),
Dense(32, 7) # Output layer for 7 classes
)
rng = Random.default_rng()
ps, st = Lux.setup(rng, model)
# Forward pass
g = GNNGraph(src, dst; ndata=(; x=randn(Float32, 16, num_nodes)))
y, st = model(g, g.x, ps, st) # y: (7, num_nodes)GAT with Multi-Head Attention
model = GNNChain(
GATConv(16 => 8, heads=4, concat=true), # Output: 32 (8 * 4 heads)
GATConv(32 => 8, heads=1, concat=false), # Output: 8 (single head)
Dense(8, 7)
)GNNLux.jl Explicit-Parameter Integration
For explicit-parameter style consistent with Lux.jl:
using GNNLux
model = GNNChain(
GCNConv(16 => 64, relu),
Dropout(0.5),
GCNConv(64 => 7)
)
ps, st = Lux.setup(rng, model)
y, st = model(g, g.x, ps, st)Task Types
Node Classification
function train_node_classification!(model, g, ps, st, opt_state, train_mask)
(loss, st), grads = Zygote.withgradient(ps) do p
y_hat, st_ = model(g, g.x, p, st)
logitcrossentropy(y_hat[:, train_mask], g.ndata.y[:, train_mask]), st_
end
opt_state, ps = Optimisers.update(opt_state, ps, grads[1])
return ps, st, opt_state, loss
endLink Prediction
function link_score(model, g, ps, st, src, dst)
h, st = model(g, g.x, ps, st)
# Dot product between node embeddings
scores = sum(h[:, src] .* h[:, dst]; dims=1)
return sigmoid.(scores)
endGraph Classification with GlobalPool
model = GNNChain(
GCNConv(16 => 64, relu),
GCNConv(64 => 32, relu),
GlobalPool(mean), # Aggregate node features to graph-level
Dense(32, 2) # Binary graph classification
)Mini-Batching
Batch multiple graphs for efficient training. The canonical batching function is MLUtils.batch (GraphNeuralNetworks re-exports it, but the namespace makes the dependency explicit and works on heterogeneous graph lists too):
using MLUtils
graphs = [rand_graph(n, 2n; ndata=(; x=randn(Float32, 16, n))) for n in [10, 20, 15]]
batched_g = MLUtils.batch(graphs)
# Forward pass on batch (nodes are concatenated, edges re-indexed)
y, st = model(batched_g, batched_g.x, ps, st)
# Unbatch results
individual_graphs = unbatch(batched_g)--mode deep required for the full training loop, custom message passing, and molecular GNN example — see
references/lux-training-and-message-passing.md.
Training and Custom Message Passing
Train with Lux.Training.TrainState + single_train_step! (threads (ps, st) through optimiser updates automatically; remember to flip Lux.testmode/Lux.trainmode around validation when the chain has Dropout or normalisation layers). Implement custom aggregation with GraphNeuralNetworks.propagate(message_fn, g, aggr; xj=x, e=edge_features). A full molecular-property-prediction example (atom embedding → message passing → GlobalPool readout) is in the reference file.
Package layering: GNNGraphs, GNNlib, GNNLux
The Julia GNN ecosystem splits cleanly into three layers — pick the layer that matches your need:
| Package | Layer | Use when |
GNNGraphs | Data structure | Building, batching, querying graphs. Provides GNNGraph, heterogeneous graphs (GNNHeteroGraph), temporal graphs (TemporalSnapshotsGNNGraph). No NN code. |
GNNlib | Low-level kernels | Writing custom message-passing layers. Provides propagate, aggregation primitives, sparse-matrix message kernels. Framework-agnostic. |
GNNLux | Lux-native layer collection | High-level GCN/GAT/SAGE/GIN/GatedGraph layers exposing Lux's explicit (ps, st) interface. Composable inside GNNChain. |
Most application code lives in GNNLux + GNNGraphs. Drop into GNNlib only when an existing layer doesn't fit and you need custom message semantics.
DEV-override note: in the
@gnnenv,GNNLux/GNNGraphs/GNNlibare DEV overrides tracking the GraphNeuralNetworks.jl monorepomaster(commit493a3f8), not released versions. API details in this skill may drift from the last tagged release -- verify against the installed@gnnenvironment rather than published package docs if something doesn't match.
Benchmark datasets
Use MLDatasets for canonical graph benchmarks (Cora, CiteSeer, PubMed, OGB-arXiv, ZINC, QM9). Combine with OneHotArrays for label encoding:
using MLDatasets, OneHotArrays
data = Cora()
g = data[:] # GNNGraph with x, y, train_mask, val_mask, test_mask
y_onehot = onehotbatch(g.y, 1:7) # 7 classes for Cora
# After model forward pass:
preds = onecold(y_hat, 1:7)
accuracy = mean(preds .== g.y)MLDatasets returns ready-to-use GNNGraphs with feature matrices and split masks already attached.
GPU backend portability
GNN training is GPU-portable through CUDA.jl (NVIDIA) and KernelAbstractions.jl (vendor-neutral). Move both the graph and parameters to the device:
using CUDA
g_gpu = g |> gpu
ps_gpu = ps |> gpuGNNLux layers dispatch through KernelAbstractions.jl for the message-passing kernels, so the same code runs on CUDA, ROCm, or oneAPI backends. CPU is the fallback when no GPU is available — useful for development and CI without changing the model code.
Extension sketches
These compose julia-graph-neural-networks with neighboring skills for advanced workflows. Each is a pointer, not a recipe.
- Bayesian GNN — wrap a
GNNLuxmodel in aTuring.@model, sample posterior over node embeddings or weights. For multimodal posteriors (expected with deep GNNs), use Pigeons. Seeconsensus-mcmc-pigeons. - Graph Neural ODE — replace stacked GNN layers with a continuous-depth
ODEProblemwhose RHS is a single GNN layer; integrate withOrdinaryDiffEqand train throughSciMLSensitivityadjoints. Useful for irregular time-step temporal graphs. - Equivariant primitives —
EquivariantTensors.jlprovides E(3)-equivariant tensor operations for molecular GNNs. If a named architecture has no Julia package, call that library from Julia withPythonCall.jlrather than starting a second training stack. - Plain message passing —
GNNLuxandGNNGraphsare the production path for GCN, GAT, and SAGE.
Composition with neighboring skills
- Julia neural networks — Lux fundamentals:
setup,(ps, st)plumbing, training loops. Seejulia-neural-networks. - Differentiation — Zygote (default), Enzyme (faster on large GNNs). See differentiation.
- Julia GPU kernels — custom CUDA / KernelAbstractions kernels for unsupported message-passing patterns. See
julia-gpu-kernels. - Bayesian UDE workflow — pattern for Bayesian neural-physics models, transferable to Bayesian GNNs. See
bayesian-ude-workflow.
Additional Resources
Reference Files
references/lux-training-and-message-passing.md- FullLux.Training.TrainStatetraining loop, custompropagatemessage passing, end-to-end molecular property prediction example
Checklist
- Picked the layer (
GNNGraphsdata,GNNLuxhigh-level,GNNlibcustom kernels) that matches the task - Used
GNNGraphfor graph construction with node/edge features - Started with
GCNConvbefore trying more complex layers - Used
GNNChainfor sequential GNN architectures andGlobalPoolfor graph-level tasks - Used
batch/unbatchfor mini-batch training - Loaded benchmark datasets via
MLDatasets; encoded labels withOneHotArrays - Added dropout and skip connections for deeper GNNs
- Profiled with
@benchmarkto identify message-passing bottlenecks - Verified GPU code path on a small graph before scaling up
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

