Skip to content

Commit 1a77508

Browse files
i-AmoghAmoghCarloLucibelloclaude
authored
feat: Add NNConv support for HeteroGraphConv (#654)
* Adding NNConv support for HeteroGraphConv * Refactoring * Aligning with changes in GMMConv * Make edge_features(::GNNHeteroGraph) throw on ambiguous input and test it `@error` only logs and returns `nothing`; throw an `ArgumentError` instead when the graph has several edge types or several edge feature arrays. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * NNConv: clear error without edge features, document bipartite input, test values - `(l::NNConv)(g, x, e = edge_features(g))` throws an `ArgumentError` when no edge features are given nor stored in `g`. - Document the `(xj, xi)` tuple input and the default `e` in the NNConv docstring, and how HeteroGraphConv layers get their edge features. - Check the hetero NNConv output and its Zygote gradients against the homogeneous NNConv on graphs whose nodes are the union of src and dst nodes (also in GNNLux, for the tuple input), instead of only sizes. - Revert a stray whitespace change in the GCNConv hetero test. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Require GNNGraphs 1.7, mark NNConv as heterograph-capable in docs The Flux NNConv falls back to `edge_features(::GNNHeteroGraph)`, new in GNNGraphs 1.7. (The GraphNeuralNetworks 1.2.0-DEV bump and the GNNlib 1.5 compat in both frontends already came with #697.) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Amogh <defalt@Amoghs-MacBook-Air.local> Co-authored-by: CarloLucibello <carlo.lucibello@gmail.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 4acaf6d commit 1a77508

10 files changed

Lines changed: 106 additions & 7 deletions

File tree

‎GNNGraphs/src/gnnheterograph/query.jl‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -89,3 +89,20 @@ function graph_indicator(g::GNNHeteroGraph, node_t::Symbol)
8989
end
9090
return gi
9191
end
92+
93+
"""
94+
edge_features(g::GNNHeteroGraph)
95+
96+
Return the edge features of `g`, which must have a single edge type
97+
(e.g. a subgraph returned by [`edge_type_subgraph`](@ref)) with at most one edge feature array.
98+
Return `nothing` if there are no edge features.
99+
"""
100+
function edge_features(g::GNNHeteroGraph)
101+
length(g.etypes) == 1 ||
102+
throw(ArgumentError("Multiple edge types, access edge features directly through `g.edata[edge_t]`"))
103+
edata = get(g.edata, only(g.etypes), nothing)
104+
(edata === nothing || isempty(edata)) && return nothing
105+
length(edata) == 1 ||
106+
throw(ArgumentError("Multiple edge feature arrays, access them directly through `g.edata[edge_t]`"))
107+
return first(values(edata))
108+
end

‎GNNGraphs/test/gnnheterograph.jl‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -187,6 +187,20 @@ end
187187
@test g2.num_edges[(:A, :to, :A)] === g1.num_edges[(:A, :to, :A)] + g1.num_nodes[(:A)]
188188
end
189189

190+
@testitem "edge_features" begin
191+
et = (:A, :to, :B)
192+
eindex = ([1, 2, 2], [3, 1, 2])
193+
e = rand(Float32, 2, 3)
194+
@test edge_features(GNNHeteroGraph(et => eindex; edata = Dict(et => e))) === e
195+
@test edge_features(GNNHeteroGraph(et => eindex)) === nothing
196+
g = GNNHeteroGraph(et => eindex; edata = Dict(et => (a = e, b = e)))
197+
@test_throws ArgumentError edge_features(g)
198+
199+
g = rand_bipartite_heterograph((2, 3), 4; edata = Dict(et => rand(2, 4), (:B, :to, :A) => rand(2, 4)))
200+
@test_throws ArgumentError edge_features(g)
201+
@test edge_features(edge_type_subgraph(g, et)) === g.edata[et].e
202+
end
203+
190204
## Cannot test this because DataStore is not an ordered collection
191205
## Uncomment when/if it will be based on OrderedDict
192206
# @testset "show" begin

‎GNNLux/docs/src/api/conv.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ The table below lists all graph convolutional layers implemented in the *GNNLux.
3030
| [`GMMConv`](@ref) | | | ✓ | | |
3131
| [`GraphConv`](@ref) | ✓ | | | ✓ | ✓ |
3232
| [`MEGNetConv`](@ref) | | | ✓ | | |
33-
| [`NNConv`](@ref) | | | ✓ | | |
33+
| [`NNConv`](@ref) | | | ✓ | ✓ | |
3434
| [`ResGatedGraphConv`](@ref) | | | | ✓ | ✓ |
3535
| [`SAGEConv`](@ref) | ✓ | | | ✓ | ✓ |
3636
| [`SGConv`](@ref) | ✓ | | | | ✓ |

‎GNNLux/test/layers/conv.jl‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -193,6 +193,17 @@ end
193193
@test st′.nn.layer_2.running_mean != st.nn.layer_2.running_mean
194194
y′, st″ = l(g2, x, e, ps, st′)
195195
@test typeof(st″) == typeof(st)
196+
197+
# bipartite (xj, xi) input matches the homogeneous layer on the graph with nodes [A; B]
198+
l = NNConv(n_in => n_out, Dense(n_in_edge => n_out * n_in), tanh)
199+
ps, st = LuxCore.setup(rng, l)
200+
s, t = [1, 1, 2], [1, 2, 3]
201+
gb = GNNHeteroGraph((:A, :to, :B) => (s, t); num_nodes = Dict(:A => 2, :B => 3))
202+
xA, xB = randn(rng, Float32, n_in, 2), randn(rng, Float32, n_in, 3)
203+
eb = randn(rng, Float32, n_in_edge, 3)
204+
yb, _ = l(gb, (xA, xB), eb, ps, st)
205+
yu, _ = l(GNNGraph(s, 2 .+ t, num_nodes = 5), hcat(xA, xB), eb, ps, st)
206+
@test yb ≈ yu[:, 3:end]
196207
end
197208

198209
@testset "GMMConv" begin

‎GNNlib/src/layers/conv.jl‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -262,11 +262,12 @@ end
262262

263263
####################### NNConv ######################################
264264

265-
function nn_conv(l, g::GNNGraph, x::AbstractMatrix, e)
265+
function nn_conv(l, g::AbstractGNNGraph, x, e)
266266
check_num_nodes(g, x)
267+
xj, xi = expand_srcdst(g, x)
267268
message = Fix1(nn_conv_message, l)
268-
m = propagate(message, g, l.aggr, xj = x, e = e)
269-
return l.σ.(l.weight * x .+ m .+ l.bias)
269+
m = propagate(message, g, l.aggr, xj = xj, e = e)
270+
return l.σ.(l.weight * xi .+ m .+ l.bias)
270271
end
271272

272273
function nn_conv_message(l, xi, xj, e)

‎GraphNeuralNetworks/Project.toml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ Statistics = "10745b16-79ce-11e8-11f9-7d13ad32a3b2"
2424
ChainRulesCore = "1"
2525
ConcreteStructs = "0.2.3"
2626
Flux = "0.16.0"
27-
GNNGraphs = "1.4"
27+
GNNGraphs = "1.7"
2828
GNNlib = "1.5"
2929
LinearAlgebra = "1"
3030
MLUtils = "0.4"

‎GraphNeuralNetworks/docs/src/api/conv.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ The table below lists all graph convolutional layers implemented in the *GraphNe
3131
| [`GMMConv`](@ref) | | | ✓ | | |
3232
| [`GraphConv`](@ref) | ✓ | | | ✓ | ✓ |
3333
| [`MEGNetConv`](@ref) | | | ✓ | | |
34-
| [`NNConv`](@ref) | | | ✓ | | |
34+
| [`NNConv`](@ref) | | | ✓ | ✓ | |
3535
| [`ResGatedGraphConv`](@ref) | | | | ✓ | ✓ |
3636
| [`SAGEConv`](@ref) | ✓ | | | ✓ | ✓ |
3737
| [`SGConv`](@ref) | ✓ | | | | ✓ |

‎GraphNeuralNetworks/src/layers/conv.jl‎

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -703,6 +703,18 @@ For convenience, also functions returning a single `(out*in, num_edges)` matrix
703703
- `bias`: Add learnable bias.
704704
- `init`: Weights' initializer.
705705
706+
# Forward
707+
708+
(::NNConv)(g, x, e = edge_features(g)) -> AbstractMatrix
709+
710+
Takes as input a graph `g`, node features `x` and edge features `e` of size `(num_edge_features, num_edges)`.
711+
If `e` is not given, the edge features stored in `g` are used.
712+
`x` is either a matrix of size `(in, num_nodes)` or, for bipartite graphs
713+
(e.g. a relation of a heterogeneous graph in [`HeteroGraphConv`](@ref)), a tuple `(xj, xi)`
714+
of source and target node features: ``W`` acts on the targets `xi`, the edge-conditioned
715+
weights on the sources `xj`. Returns a matrix of size `(out, num_nodes)`
716+
(`(out, num_target_nodes)` for tuple input).
717+
706718
# Examples:
707719
708720
```julia
@@ -746,7 +758,11 @@ function NNConv(ch::Pair{Int, Int}, nn, σ = identity; aggr = +, bias = true,
746758
return NNConv(W, b, nn, σ, aggr)
747759
end
748760

749-
(l::NNConv)(g, x, e) = GNNlib.nn_conv(l, g, x, e)
761+
function (l::NNConv)(g, x, e = edge_features(g))
762+
e === nothing &&
763+
throw(ArgumentError("NNConv requires edge features: pass them as `l(g, x, e)` or store them in the graph's `edata`"))
764+
return GNNlib.nn_conv(l, g, x, e)
765+
end
750766

751767
(l::NNConv)(g::GNNGraph) = GNNGraph(g, ndata = l(g, node_features(g), edge_features(g)))
752768

‎GraphNeuralNetworks/src/layers/heteroconv.jl‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,9 @@ have to be aggregated using the `aggr` function. The default is to sum the outpu
1818
* `x::Union{NamedTuple,Dict}`: The input node features. The keys are node types and the
1919
values are node feature tensors.
2020
21+
Layers needing edge features (e.g. [`NNConv`](@ref)) read them from each relation's `edata`,
22+
via [`edge_features`](@ref) on the subgraph returned by [`edge_type_subgraph`](@ref).
23+
2124
# Examples
2225
2326
```jldoctest

‎GraphNeuralNetworks/test/layers/heteroconv.jl‎

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -218,4 +218,41 @@
218218
@test dx.A ≈ ndx[1].A rtol=1e-3
219219
@test dx.B ≈ ndx[1].B rtol=1e-3
220220
end
221+
222+
@testset "NNConv" begin
223+
nA, nB, din, dout, de = 2, 3, 4, 2, 5
224+
sAB, tAB = [1, 1, 2, 2], [1, 2, 2, 3]
225+
sBA, tBA = [1, 3, 3], [1, 1, 2]
226+
eAB, eBA = rand(Float32, de, 4), rand(Float32, de, 3)
227+
g = GNNHeteroGraph(((:A, :to, :B) => (sAB, tAB), (:B, :to, :A) => (sBA, tBA));
228+
num_nodes = Dict(:A => nA, :B => nB),
229+
edata = Dict((:A, :to, :B) => eAB, (:B, :to, :A) => eBA))
230+
x = (A = rand(Float32, din, nA), B = rand(Float32, din, nB))
231+
lAB = NNConv(din => dout, Dense(de => dout * din), tanh)
232+
lBA = NNConv(din => dout, Dense(de => dout * din), tanh)
233+
layers = HeteroGraphConv((:A, :to, :B) => lAB, (:B, :to, :A) => lBA)
234+
235+
# reference: homogeneous NNConv on graphs whose nodes are [A nodes; B nodes]
236+
gAB = GNNGraph(sAB, nA .+ tAB, num_nodes = nA + nB)
237+
gBA = GNNGraph(nA .+ sBA, tBA, num_nodes = nA + nB)
238+
function ref(lAB, lBA, x)
239+
xAB = hcat(x.A, x.B)
240+
return (A = lBA(gBA, xAB, eBA)[:, 1:nA], B = lAB(gAB, xAB, eAB)[:, (nA + 1):end])
241+
end
242+
y = layers(g, x)
243+
yref = ref(lAB, lBA, x)
244+
@test y.A ≈ yref.A
245+
@test y.B ≈ yref.B
246+
247+
loss(y) = sum(abs2, y.A) + sum(abs2, y.B)
248+
grad, dx = gradient((m, x) -> loss(m(g, x)), layers, x)
249+
gradAB, gradBA, dxref = gradient((lAB, lBA, x) -> loss(ref(lAB, lBA, x)), lAB, lBA, x)
250+
@test grad.layers[1].weight ≈ gradAB.weight
251+
@test grad.layers[1].nn.weight ≈ gradAB.nn.weight
252+
@test grad.layers[2].bias ≈ gradBA.bias
253+
@test dx.A ≈ dxref.A
254+
@test dx.B ≈ dxref.B
255+
256+
@test_throws ArgumentError layers(rand_bipartite_heterograph((nA, nB), 4), x)
257+
end
221258
end

0 commit comments

Comments
 (0)