agentleFS
90184479018447/julia-pro-p/skills/julia-graph-neural-networks/SKILL.md

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.

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
  1. Very specific:

    Create graphs with GNNGraph:

    line 12
  2. Very specific:

    Use MLDatasets for canonical graph benchmarks (Cora, CiteSeer, PubMed, OGB-arXiv, ZINC, QM9).

    line 171

≈ “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.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

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 edges

Built-in GNN Layers

LayerDescriptionKey Parameters
GCNConvGraph Convolutional Networkin => out
GATConvGraph Attention Networkin => out, heads
SAGEConvGraphSAGE (sampling + aggregation)in => out, aggr
GINConvGraph Isomorphism Networknn (MLP)
EdgeConvDynamic Edge Convolutionnn (MLP)
GatedGraphConvGated Graph Neural Networkout, 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
end

Link 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)
end

Graph 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:

PackageLayerUse when
GNNGraphsData structureBuilding, batching, querying graphs. Provides GNNGraph, heterogeneous graphs (GNNHeteroGraph), temporal graphs (TemporalSnapshotsGNNGraph). No NN code.
GNNlibLow-level kernelsWriting custom message-passing layers. Provides propagate, aggregation primitives, sparse-matrix message kernels. Framework-agnostic.
GNNLuxLux-native layer collectionHigh-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 @gnn env, GNNLux/GNNGraphs/GNNlib are DEV overrides tracking the GraphNeuralNetworks.jl monorepo master (commit 493a3f8), not released versions. API details in this skill may drift from the last tagged release -- verify against the installed @gnn environment 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 |> gpu

GNNLux 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 GNNLux model in a Turing.@model, sample posterior over node embeddings or weights. For multimodal posteriors (expected with deep GNNs), use Pigeons. See consensus-mcmc-pigeons.
  • Graph Neural ODE — replace stacked GNN layers with a continuous-depth ODEProblem whose RHS is a single GNN layer; integrate with OrdinaryDiffEq and train through SciMLSensitivity adjoints. Useful for irregular time-step temporal graphs.
  • Equivariant primitives — EquivariantTensors.jl provides E(3)-equivariant tensor operations for molecular GNNs. If a named architecture has no Julia package, call that library from Julia with PythonCall.jl rather than starting a second training stack.
  • Plain message passing — GNNLux and GNNGraphs are the production path for GCN, GAT, and SAGE.

Composition with neighboring skills

  • Julia neural networks — Lux fundamentals: setup, (ps, st) plumbing, training loops. See julia-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 - Full Lux.Training.TrainState training loop, custom propagate message passing, end-to-end molecular property prediction example

Checklist

  • Picked the layer (GNNGraphs data, GNNLux high-level, GNNlib custom kernels) that matches the task
  • Used GNNGraph for graph construction with node/edge features
  • Started with GCNConv before trying more complex layers
  • Used GNNChain for sequential GNN architectures and GlobalPool for graph-level tasks
  • Used batch/unbatch for mini-batch training
  • Loaded benchmark datasets via MLDatasets; encoded labels with OneHotArrays
  • Added dropout and skip connections for deeper GNNs
  • Profiled with @benchmark to identify message-passing bottlenecks
  • Verified GPU code path on a small graph before scaling up

Download now (ZIP)

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
What did you use it for? e.g. Reviewing pull requests in a Rails app

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.