Skip to content

Commit 486fa54

Browse files
authored
Add GNNGraphsMooncakeExt.jl (#704)
* Add GNNGraphsMooncakeExt.jl Signed-off-by: Parvm1102 <parvmittal31757@gmail.com> * comments modified and _to_coo_graph removed from the tests Signed-off-by: Parvm1102 <parvmittal31757@gmail.com> --------- Signed-off-by: Parvm1102 <parvmittal31757@gmail.com>
1 parent 67e42ef commit 486fa54

6 files changed

Lines changed: 114 additions & 6 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,10 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
1010
and the packages adhere to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
1111
Entries link to the pull request that introduced them.
1212

13-
## GNNGraphs.jl — Unreleased (towards 1.5.2)
13+
## GNNGraphs.jl — Unreleased (towards 1.6.0)
14+
15+
**Added**
16+
- Added a `Mooncake` package extension, so that Mooncake can differentiate on CUDA through `add_self_loops` and through adjacency-matrix graphs. Float edge weights of adjacency-matrix graphs stay differentiable ([#704]).
1417

1518
**Fixed**
1619
- Enzyme can now differentiate through the adjacency-matrix → COO graph conversion: a new internal keyword-free helper `_to_coo_graph` avoids the union-typed keyword handling of the `GNNGraph(g; graph_type)` constructor and of `to_coo`, which Enzyme's type analysis cannot compile. Together with upstream fixes in Enzyme ≥ 0.13.197 this removes the `EnzymeInternalError` crash on `:dense`/`:sparse` graphs ([#703]).
@@ -230,4 +233,5 @@ Lux implementations of the graph convolutional, pooling, and temporal layers
230233
[#695]: https://github.com/JuliaGraphs/GraphNeuralNetworks.jl/pull/695
231234
[#696]: https://github.com/JuliaGraphs/GraphNeuralNetworks.jl/pull/696
232235
[#703]: https://github.com/JuliaGraphs/GraphNeuralNetworks.jl/pull/703
236+
[#704]: https://github.com/JuliaGraphs/GraphNeuralNetworks.jl/pull/704
233237
[FluxML/Zygote.jl#1662]: https://github.com/FluxML/Zygote.jl/issues/1662

‎GNNGraphs/Project.toml‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
name = "GNNGraphs"
22
uuid = "aed8fd31-079b-4b5a-b342-a13352159b8c"
3-
version = "1.5.2-DEV"
3+
version = "1.6.0-DEV"
44
authors = ["Carlo Lucibello and contributors"]
55

66
[workspace]
@@ -23,10 +23,12 @@ StatsBase = "2913bbd2-ae8a-5f71-8c99-4fb6c76f3a91"
2323

2424
[weakdeps]
2525
CUDA = "052768ef-5323-5732-b1bb-66c8b64840ba"
26+
Mooncake = "da2b9cff-9c12-43a0-ae48-6db2b0edb7d6"
2627
SimpleWeightedGraphs = "47aef6b3-ad0c-573a-a1e2-d07658019622"
2728

2829
[extensions]
2930
GNNGraphsCUDAExt = "CUDA"
31+
GNNGraphsMooncakeExt = "Mooncake"
3032
GNNGraphsSimpleWeightedGraphsExt = "SimpleWeightedGraphs"
3133

3234
[compat]
@@ -38,6 +40,7 @@ KrylovKit = "0.8, 0.9, 0.10"
3840
LinearAlgebra = "1"
3941
MLDataDevices = "1.0"
4042
MLUtils = "0.4"
43+
Mooncake = "0.5.24"
4144
NNlib = "0.9"
4245
NearestNeighbors = "0.4"
4346
Random = "1"
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
module GNNGraphsMooncakeExt
2+
3+
using GNNGraphs
4+
import Mooncake
5+
6+
# Without these rules Mooncake traces into graph-structure code and fails on CUDA:
7+
# host→device index copies in `add_self_loops`, `findall` on `CuArray` in
8+
# `_findnz_idx`, bounds checks in `_edge_values` (Mooncake's CUDA `getindex` rule
9+
# covers only float/complex arrays). No gradient is lost: all three yield integers,
10+
# whose Mooncake tangent is `NoTangent` anyway. Float edge values stay on the AD path.
11+
Mooncake.@zero_derivative Mooncake.DefaultCtx Tuple{typeof(add_self_loops), GNNGraph}
12+
Mooncake.@zero_derivative Mooncake.DefaultCtx Tuple{typeof(GNNGraphs._findnz_idx), Any}
13+
Mooncake.@zero_derivative Mooncake.DefaultCtx Tuple{
14+
typeof(GNNGraphs._edge_values), AbstractMatrix{<:Integer}, Any, Any}
15+
16+
end # module

‎GNNGraphs/src/convert.jl‎

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -80,9 +80,13 @@ end
8080

8181
CRC.@non_differentiable _findnz_idx(A)
8282

83+
# Values of `A` at the extracted edge positions. Linear indexing keeps float edge
84+
# weights differentiable on GPU, unlike `A[nz]` with CartesianIndex.
85+
_edge_values(A::AbstractMatrix, s, t) = vec(A)[s .+ (t .- 1) .* size(A, 1)]
86+
8387
function to_coo(A::ADJMAT_T; dir = :out, num_nodes = nothing, weighted = true)
84-
s, t, nz = _findnz_idx(A)
85-
v = A[nz]
88+
s, t, _ = _findnz_idx(A)
89+
v = _edge_values(A, s, t)
8690
if dir == :in
8791
s, t = t, s
8892
end
@@ -126,8 +130,8 @@ end
126130

127131
function _to_coo_graph(g::GNNGraph{<:ADJMAT_T})
128132
A = g.graph
129-
s, t, nz = _findnz_idx(A)
130-
v = A[nz]
133+
s, t, _ = _findnz_idx(A)
134+
v = _edge_values(A, s, t)
131135
return GNNGraph((s, t, v), g.num_nodes, g.num_edges, g.num_graphs,
132136
g.graph_indicator, g.ndata, g.edata, g.gdata)
133137
end

‎GNNGraphs/test/Project.toml‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ LinearAlgebra = "37e2e46d-f89d-539d-b4ee-838fcccc9c8e"
88
MLDataDevices = "7e8f7934-dd98-4c1a-8fe8-92b47a384d40"
99
MLDatasets = "eb30cadb-4394-5ae3-aed4-317e484a6458"
1010
MLUtils = "f1d291b0-491e-4a28-83b9-f70985020b54"
11+
Mooncake = "da2b9cff-9c12-43a0-ae48-6db2b0edb7d6"
1112
NNlib = "872c559c-99b0-510c-b3b7-b6c96a88d5cd"
1213
Pkg = "44cfe95a-1eb2-52ea-b672-e2afdf69b78f"
1314
Random = "9a3f8284-a2c9-5f02-9a11-845980a1fd5c"
@@ -26,5 +27,6 @@ GNNGraphs = {path = ".."}
2627

2728
[compat]
2829
Enzyme = "0.13.197"
30+
Mooncake = "0.5.24"
2931
NNlib = "0.9.38"
3032
StableRNGs = "1.0.4"

‎GNNGraphs/test/ext/Mooncake.jl‎

Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
@testitem "GNNGraphsMooncakeExt zero-derivative rules" setup=[GraphsTestModule] begin
2+
using .GraphsTestModule
3+
import Mooncake
4+
import NNlib
5+
6+
# Loading Mooncake triggers the extension.
7+
@test Base.get_extension(GNNGraphs, :GNNGraphsMooncakeExt) !== nothing
8+
9+
# Mooncake is only exercised on Julia >= 1.12, as in the other test suites.
10+
if VERSION >= v"1.12"
11+
function mooncake_gradient(f, x)
12+
cache = Mooncake.prepare_gradient_cache(f, x)
13+
_, grads = Mooncake.value_and_gradient!!(cache, f, x)
14+
return grads[2]
15+
end
16+
17+
rng = MersenneTwister(17)
18+
19+
# Gradients through `add_self_loops` (zero-derivative rule).
20+
for graph_type in GRAPH_TYPES
21+
g = rand_graph(rng, 6, 10; graph_type)
22+
x = randn(rng, Float32, 3, g.num_nodes)
23+
loss(x) = sum(abs2, NNlib.gather(x, edge_index(add_self_loops(g))[1]))
24+
gm = mooncake_gradient(loss, x)
25+
@test gm≈gradient(loss, x)[1] rtol=1e-4
26+
@test gm≈ngradient(loss, x)[1] rtol=1e-4
27+
end
28+
29+
# Gradients through `edge_index` on adjacency-matrix graphs.
30+
for graph_type in (:dense, :sparse)
31+
g = rand_graph(rng, 6, 10; graph_type)
32+
x = randn(rng, Float32, 3, g.num_nodes)
33+
loss(x) = sum(abs2, NNlib.gather(x, edge_index(g)[1]))
34+
gm = mooncake_gradient(loss, x)
35+
@test gm≈gradient(loss, x)[1] rtol=1e-4
36+
@test gm≈ngradient(loss, x)[1] rtol=1e-4
37+
end
38+
39+
# Float adjacency: edge weights stay on the AD path.
40+
A = Float32[0 1 0 2; 1 0 3 0; 0 3 0 1; 2 0 1 0]
41+
loss_w(A) = sum(abs2, get_edge_weight(GNNGraph(A, graph_type = :dense)))
42+
gw = mooncake_gradient(loss_w, copy(A))
43+
@test gw≈2 .* A rtol=1e-4
44+
@test gw≈gradient(loss_w, A)[1] rtol=1e-4
45+
end
46+
end
47+
48+
@testitem "GNNGraphsMooncakeExt on GPU" setup=[GraphsTestModule] tags=[:gpu] begin
49+
using .GraphsTestModule
50+
import Mooncake
51+
import NNlib
52+
53+
dev = gpu_device(force = true)
54+
# Mooncake's GPU rules are CUDA-only.
55+
if VERSION >= v"1.12" && dev isa CUDADevice
56+
function mooncake_gradient(f, x)
57+
cache = Mooncake.prepare_gradient_cache(f, x)
58+
_, grads = Mooncake.value_and_gradient!!(cache, f, x)
59+
return grads[2]
60+
end
61+
62+
rng = MersenneTwister(17)
63+
64+
# Without the rules Mooncake errors here instead of returning a gradient.
65+
for graph_type in (:coo, :dense)
66+
g = rand_graph(rng, 6, 10; graph_type)
67+
x = randn(rng, Float32, 3, g.num_nodes)
68+
g_gpu, x_gpu = dev(g), dev(x)
69+
loss(x) = sum(abs2, NNlib.gather(x, edge_index(add_self_loops(g))[1]))
70+
loss_gpu(x) = sum(abs2, NNlib.gather(x, edge_index(add_self_loops(g_gpu))[1]))
71+
@test Array(mooncake_gradient(loss_gpu, x_gpu))≈mooncake_gradient(loss, x) rtol=1e-4
72+
end
73+
74+
# Float adjacency: edge weights stay on the AD path.
75+
A = Float32[0 1 0 2; 1 0 3 0; 0 3 0 1; 2 0 1 0]
76+
loss_w(A) = sum(abs2, get_edge_weight(GNNGraph(A, graph_type = :dense)))
77+
@test Array(mooncake_gradient(loss_w, dev(A)))≈2 .* A rtol=1e-4
78+
end
79+
end

0 commit comments

Comments
 (0)