Skip to content

Commit 64904d3

Browse files
committed
Add pad_graph and restore mini-batches in the graph classification tutorial
pad_graph pads a graph to fixed numbers of nodes, edges and graphs, so Reactant can compile a model or training step once and reuse it for every mini-batch. The graph classification tutorial goes back to master's mini-batch training, padding each batch and masking the padding graphs out of the loss.
1 parent 77399f7 commit 64904d3

7 files changed

Lines changed: 284 additions & 58 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ Entries link to the pull request that introduced them.
1414

1515
**Added**
1616
- Graphs can be compiled with Reactant.jl: a `GNNGraph` can now be moved to a Reactant device (e.g. `g |> reactant_device()`) and traced. The COO index vectors and the `graph_indicator` of a `GNNGraph` are no longer required to have an `Integer` eltype, so that traced arrays (eltype `TracedRNumber{Int}`) can be stored in them, and a new `Reactant` package extension makes `degree` work inside a trace ([#730]).
17+
- Added `pad_graph`, which pads a graph to given numbers of nodes, edges and graphs, putting the padding in extra graphs. Padding every mini-batch to the same size lets Reactant.jl compile a model or a training step once and reuse it for all batches ([#730]).
1718

1819
## GNNlib.jl — Unreleased (towards 1.5.0)
1920

‎GNNGraphs/src/GNNGraphs.jl‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,7 @@ export add_nodes,
8484
perturb_edges,
8585
remove_nodes,
8686
ppr_diffusion,
87+
pad_graph,
8788
# from MLUtils.jl
8889
batch,
8990
unbatch,

‎GNNGraphs/src/transform.jl‎

Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -564,6 +564,89 @@ function add_nodes(g::GNNGraph{<:COO_T}, n::Integer; ndata = (;))
564564
ndata, g.edata, g.gdata)
565565
end
566566

567+
"""
568+
pad_graph(g::GNNGraph, num_nodes, num_edges, num_graphs = g.num_graphs + 1)
569+
570+
Pad `g` to exactly `num_nodes` nodes, `num_edges` edges and `num_graphs` graphs.
571+
572+
All padding nodes and edges are put in one extra graph, appended after the graphs of `g`.
573+
The padding edges are self-loops on the first padding node. Empty graphs are then
574+
appended until there are `num_graphs` graphs. Node, edge and graph features, and edge
575+
weights, are padded with zeros.
576+
577+
Padding every mini-batch to the same size lets a compiler like Reactant.jl compile a
578+
model, or a training step, once and reuse it for all batches. The original graphs are
579+
the first `g.num_graphs` ones: mask out the others, e.g. in the loss.
580+
581+
Requires `num_graphs > g.num_graphs`, and `num_nodes > g.num_nodes` if edges are added.
582+
583+
# Examples
584+
585+
```jldoctest
586+
julia> g = MLUtils.batch([rand_graph(3, 4), rand_graph(5, 6)])
587+
GNNGraph:
588+
num_nodes: 8
589+
num_edges: 10
590+
num_graphs: 2
591+
592+
julia> gp = pad_graph(g, 10, 12, 4)
593+
GNNGraph:
594+
num_nodes: 10
595+
num_edges: 12
596+
num_graphs: 4
597+
598+
julia> graph_indicator(gp)
599+
10-element Vector{Int64}:
600+
1
601+
1
602+
1
603+
2
604+
2
605+
2
606+
2
607+
2
608+
3
609+
3
610+
```
611+
"""
612+
function pad_graph(g::GNNGraph{<:COO_T}, num_nodes::Integer, num_edges::Integer,
613+
num_graphs::Integer = g.num_graphs + 1)
614+
npad = num_nodes - g.num_nodes
615+
epad = num_edges - g.num_edges
616+
gpad = num_graphs - g.num_graphs
617+
npad >= 0 ||
618+
throw(ArgumentError("cannot pad a graph with $(g.num_nodes) nodes to $num_nodes nodes"))
619+
epad >= 0 ||
620+
throw(ArgumentError("cannot pad a graph with $(g.num_edges) edges to $num_edges edges"))
621+
gpad >= 1 ||
622+
throw(ArgumentError("`num_graphs` must exceed the $(g.num_graphs) graphs of `g`, to make room for the padding graph"))
623+
(epad == 0 || npad >= 1) ||
624+
throw(ArgumentError("padding edges need at least one padding node: `num_nodes` must exceed $(g.num_nodes)"))
625+
626+
s, t, w = edge_index(g)..., get_edge_weight(g)
627+
s = vcat(s, fill_like(s, g.num_nodes + 1, epad))
628+
t = vcat(t, fill_like(t, g.num_nodes + 1, epad))
629+
w = isnothing(w) ? nothing : vcat(w, zeros_like(w, epad))
630+
gi = graph_indicator(g)
631+
gi = vcat(gi, fill_like(gi, g.num_graphs + 1, npad))
632+
633+
return GNNGraph((s, t, w),
634+
num_nodes, num_edges, num_graphs,
635+
gi,
636+
_pad_features(g.ndata, npad),
637+
_pad_features(g.edata, epad),
638+
_pad_features(g.gdata, gpad))
639+
end
640+
641+
function _pad_features(ds::DataStore, n::Integer)
642+
n0 = getn(ds) >= 0 ? getn(ds) : 1
643+
return DataStore(n0 + n, Dict{Symbol, Any}(k => _pad_features(x, n) for (k, x) in ds))
644+
end
645+
646+
function _pad_features(x::AbstractArray, n::Integer)
647+
return cat(x, fill!(similar(x, size(x)[1:(end - 1)]..., n), 0); dims = ndims(x))
648+
end
649+
567650
"""
568651
set_edge_weight(g::GNNGraph, w::AbstractVector)
569652

‎GNNGraphs/test/transform.jl‎

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -414,6 +414,61 @@ end
414414
end
415415
end
416416

417+
@testitem "pad_graph" setup=[GraphsTestModule] begin
418+
using .GraphsTestModule
419+
gs = [rand_graph(n, m, ndata = rand(Float32, 2, n), edata = rand(Float32, 3, m),
420+
gdata = rand(Float32, 4)) for (n, m) in [(3, 4), (5, 6)]]
421+
gs = [set_edge_weight(g, rand(Float32, g.num_edges)) for g in gs]
422+
g = MLUtils.batch(gs)
423+
gp = pad_graph(g, 10, 13, 4)
424+
425+
@test gp.num_nodes == 10
426+
@test gp.num_edges == 13
427+
@test gp.num_graphs == 4
428+
@test graph_indicator(gp) == [1, 1, 1, 2, 2, 2, 2, 2, 3, 3]
429+
s, t = edge_index(gp)
430+
@test s[11:13] == t[11:13] == [9, 9, 9]
431+
@test get_edge_weight(gp) == [get_edge_weight(g); zeros(Float32, 3)]
432+
@test gp.ndata.x == [g.ndata.x zeros(Float32, 2, 2)]
433+
@test gp.edata.e == [g.edata.e zeros(Float32, 3, 3)]
434+
@test gp.gdata.u == [g.gdata.u zeros(Float32, 4, 2)]
435+
436+
# the original graphs are unchanged, and the extra ones are the padding
437+
gsp = MLUtils.unbatch(gp)
438+
@test gsp[1:2] == MLUtils.unbatch(g)
439+
@test gsp[3].num_nodes == 2 && gsp[3].num_edges == 3
440+
@test gsp[4].num_nodes == 0 && gsp[4].num_edges == 0
441+
442+
# a single graph, padded with nodes only
443+
g1 = rand_graph(4, 6)
444+
gp1 = pad_graph(g1, 5, 6)
445+
@test gp1.num_graphs == 2
446+
@test graph_indicator(gp1) == [1, 1, 1, 1, 2]
447+
@test edge_index(gp1) == edge_index(g1)
448+
449+
@test_throws ArgumentError pad_graph(g, 7, 13, 4) # fewer nodes
450+
@test_throws ArgumentError pad_graph(g, 10, 9, 4) # fewer edges
451+
@test_throws ArgumentError pad_graph(g, 10, 13, 2) # no room for the padding graph
452+
@test_throws ArgumentError pad_graph(g, 8, 13, 4) # padding edges without padding nodes
453+
end
454+
455+
@testitem "pad_graph GPU" setup=[GraphsTestModule] tags=[:gpu] begin
456+
using .GraphsTestModule
457+
dev = gpu_device(force=true)
458+
g = MLUtils.batch([rand_graph(n, m, ndata = rand(Float32, 2, n), edata = rand(Float32, 3, m))
459+
for (n, m) in [(3, 4), (5, 6)]])
460+
gp = pad_graph(g, 10, 13, 4)
461+
gp_gpu = pad_graph(g |> dev, 10, 13, 4)
462+
463+
@test get_device(gp_gpu.graph_indicator) isa AbstractGPUDevice
464+
@test get_device(edge_index(gp_gpu)[1]) isa AbstractGPUDevice
465+
@test Array(gp_gpu.graph_indicator) == gp.graph_indicator
466+
@test Array(edge_index(gp_gpu)[1]) == edge_index(gp)[1]
467+
@test Array(edge_index(gp_gpu)[2]) == edge_index(gp)[2]
468+
@test Array(gp_gpu.ndata.x) == gp.ndata.x
469+
@test Array(gp_gpu.edata.e) == gp.edata.e
470+
end
471+
417472
@testitem "remove_self_loops" setup=[GraphsTestModule] begin
418473
using .GraphsTestModule
419474
for GRAPH_T in GRAPH_TYPES

‎GNNLux/docs/src/tutorials/beginner_tutorials/graph_classification.md‎

Lines changed: 58 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -219,55 +219,81 @@ ps, st = Lux.setup(rng, model) |> xdev;
219219

220220
Here, we again make use of the `GCNConv` with $\mathrm{ReLU}(x) = \max(x, 0)$ activation for obtaining localized node embeddings, before we apply our final classifier on top of a graph readout layer.
221221

222-
### Compiling with fixed shapes
222+
### Padding the mini-batches
223223

224224
Reactant compiles a program for fixed array shapes, and `Lux.Training.single_train_step!` compiles the training step once, on its first call, and reuses it for all subsequent calls.
225-
A mini-batch of graphs, however, has a different number of nodes and edges every time, so it cannot be fed to a training step compiled for another mini-batch.
226-
The general solution is to pad every batch to the same size. Since MUTAG is small, here we simply batch all training graphs (and, separately, all test graphs) into one giant graph and perform full-batch training:
225+
A mini-batch of graphs, however, has a different number of nodes and edges every time.
226+
We therefore pad every mini-batch with [`pad_graph`](@ref) to the same number of nodes, edges and graphs: the padding nodes and edges are put in an extra graph, and empty graphs are added until there are `batchsize + 1` graphs.
227+
Our node budget fits a batch of the largest graphs, plus one padding node:
227228

228229
````julia
229-
g_train = MLUtils.batch(train_data[1]) |> xdev
230-
y_train = train_data[2] |> xdev
231-
g_test = MLUtils.batch(test_data[1]) |> xdev
232-
y_test = test_data[2] |> xdev;
230+
batchsize = train_loader.batchsize
231+
max_nodes = batchsize * maximum(g.num_nodes for g in graphs) + 1
232+
max_edges = batchsize * maximum(g.num_edges for g in graphs)
233+
max_graphs = batchsize + 1
234+
235+
function pad_batch(gs, y)
236+
g = MLUtils.batch(gs)
237+
n = g.num_graphs
238+
g = pad_graph(g, max_nodes, max_edges, max_graphs)
239+
y = [Float32.(y) zeros(Float32, size(y, 1), max_graphs - n)]
240+
mask = Float32.((1:max_graphs) .<= n)' # the padding graphs are excluded from the loss
241+
return g, y, mask, n
242+
end;
233243
````
234244

235-
Let's train our network to see how well it performs on the training as well as test set.
236-
For evaluation, we compile the forward pass in inference mode once for each of the two giant graphs:
245+
The labels are padded too, and the `mask` restricts the loss to the original graphs.
246+
Note that the mask is passed to the training step as data, i.e. moved to the device with the other arrays: values that are not device arrays would be fixed when the training step is compiled.
247+
248+
Let's train our network for a few epochs to see how well it performs on the training as well as test set:
237249

238250
````julia
239-
function custom_loss(model, ps, st, (g, x, y))
240-
logitcrossentropy = CrossEntropyLoss(; logits = Val(true))
251+
function custom_loss(model, ps, st, (g, x, y, mask))
252+
logitcrossentropy = CrossEntropyLoss(; logits = Val(true), agg = l -> sum(l .* mask) / sum(mask))
241253
st = Lux.trainmode(st)
242-
ŷ, st = model(g, x, ps, st)
243-
return logitcrossentropy(ŷ, y), st, (;)
254+
ŷ, st = model(g, x, ps, st)
255+
return logitcrossentropy(ŷ, y), st, (;)
244256
end
245257

246-
function eval_loss_accuracy(model_compiled, ps, st, g, y)
247-
ŷ, _ = model_compiled(g, g.x, ps, st)
248-
ŷ, y = cdev((ŷ, y))
258+
function eval_loss_accuracy(model_compiled, ps, st, data_loader)
259+
loss = 0.0
260+
acc = 0.0
261+
ntot = 0
249262
logitcrossentropy = CrossEntropyLoss(; logits = Val(true))
250-
return (loss = round(logitcrossentropy(ŷ, y), digits = 4),
251-
acc = round(mean((ŷ .> 0) .== y) * 100, digits = 2))
263+
for (g, y) in data_loader
264+
g, y, _, n = pad_batch(g, y)
265+
g = xdev(g)
266+
ŷ, _ = model_compiled(g, g.x, ps, st)
267+
ŷ, y = cdev(ŷ)[:, 1:n], y[:, 1:n]
268+
loss += logitcrossentropy(ŷ, y) * n
269+
acc += mean((ŷ .> 0) .== y) * n
270+
ntot += n
271+
end
272+
return (loss = round(loss / ntot, digits = 4),
273+
acc = round(acc * 100 / ntot, digits = 2))
252274
end
253275

254276
function train_model(model, ps, st; epochs = 500, infotime = 100)
255-
st_test = Lux.testmode(st)
256-
model_train = @compile model(g_train, g_train.x, ps, st_test)
257-
model_test = @compile model(g_test, g_test.x, ps, st_test)
277+
g, _, _, _ = pad_batch(first(train_loader)...)
278+
g = xdev(g)
279+
model_compiled = @compile model(g, g.x, ps, Lux.testmode(st))
258280

259281
function report(epoch, ps, st)
260282
st = Lux.testmode(st)
261-
train = eval_loss_accuracy(model_train, ps, st, g_train, y_train)
262-
test = eval_loss_accuracy(model_test, ps, st, g_test, y_test)
283+
train = eval_loss_accuracy(model_compiled, ps, st, train_loader)
284+
test = eval_loss_accuracy(model_compiled, ps, st, test_loader)
263285
@info (; epoch, train, test)
264286
end
265287

266288
train_state = Training.TrainState(model, ps, st, Adam(1.0f-2))
267289
report(0, ps, st)
268290
for epoch in 1:epochs
269-
_, loss, _, train_state = Training.single_train_step!(AutoEnzyme(), custom_loss,
270-
(g_train, g_train.x, y_train), train_state)
291+
for (g, y) in train_loader
292+
g, y, mask, _ = pad_batch(g, y)
293+
g, y, mask = (g, y, mask) |> xdev
294+
_, loss, _, train_state = Training.single_train_step!(AutoEnzyme(), custom_loss,
295+
(g, g.x, y, mask), train_state)
296+
end
271297

272298
epoch % infotime == 0 && report(epoch, train_state.parameters, train_state.states)
273299
end
@@ -278,16 +304,16 @@ ps, st = train_model(model, ps, st);
278304
````
279305

280306
````
281-
[ Info: (epoch = 0, train = (loss = 0.6708f0, acc = 69.33), test = (loss = 0.6849f0, acc = 55.26))
282-
[ Info: (epoch = 100, train = (loss = 0.4564f0, acc = 77.33), test = (loss = 0.5876f0, acc = 73.68))
283-
[ Info: (epoch = 200, train = (loss = 0.4428f0, acc = 78.33), test = (loss = 0.5969f0, acc = 73.68))
284-
[ Info: (epoch = 300, train = (loss = 0.4002f0, acc = 85.33), test = (loss = 0.8212f0, acc = 71.05))
285-
[ Info: (epoch = 400, train = (loss = 0.3546f0, acc = 84.0), test = (loss = 0.7233f0, acc = 75.0))
286-
[ Info: (epoch = 500, train = (loss = 0.3374f0, acc = 85.33), test = (loss = 0.7399f0, acc = 76.32))
307+
[ Info: (epoch = 0, train = (loss = 0.6708, acc = 69.33), test = (loss = 0.6849, acc = 55.26))
308+
[ Info: (epoch = 100, train = (loss = 0.4381, acc = 79.67), test = (loss = 0.6617, acc = 73.68))
309+
[ Info: (epoch = 200, train = (loss = 0.397, acc = 85.0), test = (loss = 0.7596, acc = 68.42))
310+
[ Info: (epoch = 300, train = (loss = 0.3803, acc = 84.67), test = (loss = 0.7549, acc = 69.74))
311+
[ Info: (epoch = 400, train = (loss = 0.3644, acc = 86.33), test = (loss = 0.8114, acc = 72.37))
312+
[ Info: (epoch = 500, train = (loss = 0.3654, acc = 86.0), test = (loss = 0.8797, acc = 71.05))
287313
288314
````
289315

290-
As one can see, our model reaches around **75% test accuracy**.
316+
As one can see, our model reaches around **70% test accuracy**.
291317
Reasons for the fluctuations in accuracy can be explained by the rather small dataset (only 38 test graphs), and usually disappear once one applies GNNs to larger datasets.
292318

293319
## (Optional) Exercise

0 commit comments

Comments
 (0)