diff --git a/GNNGraphs/src/gnnheterograph/query.jl b/GNNGraphs/src/gnnheterograph/query.jl index 831e654eb..3ffe42006 100644 --- a/GNNGraphs/src/gnnheterograph/query.jl +++ b/GNNGraphs/src/gnnheterograph/query.jl @@ -89,3 +89,20 @@ function graph_indicator(g::GNNHeteroGraph, node_t::Symbol) end return gi end + +""" + edge_features(g::GNNHeteroGraph) + +Return the edge features of `g`, which must have a single edge type +(e.g. a subgraph returned by [`edge_type_subgraph`](@ref)) with at most one edge feature array. +Return `nothing` if there are no edge features. +""" +function edge_features(g::GNNHeteroGraph) + length(g.etypes) == 1 || + throw(ArgumentError("Multiple edge types, access edge features directly through `g.edata[edge_t]`")) + edata = get(g.edata, only(g.etypes), nothing) + (edata === nothing || isempty(edata)) && return nothing + length(edata) == 1 || + throw(ArgumentError("Multiple edge feature arrays, access them directly through `g.edata[edge_t]`")) + return first(values(edata)) +end diff --git a/GNNGraphs/test/gnnheterograph.jl b/GNNGraphs/test/gnnheterograph.jl index 7b389c207..43355d079 100644 --- a/GNNGraphs/test/gnnheterograph.jl +++ b/GNNGraphs/test/gnnheterograph.jl @@ -187,6 +187,20 @@ end @test g2.num_edges[(:A, :to, :A)] === g1.num_edges[(:A, :to, :A)] + g1.num_nodes[(:A)] end +@testitem "edge_features" begin + et = (:A, :to, :B) + eindex = ([1, 2, 2], [3, 1, 2]) + e = rand(Float32, 2, 3) + @test edge_features(GNNHeteroGraph(et => eindex; edata = Dict(et => e))) === e + @test edge_features(GNNHeteroGraph(et => eindex)) === nothing + g = GNNHeteroGraph(et => eindex; edata = Dict(et => (a = e, b = e))) + @test_throws ArgumentError edge_features(g) + + g = rand_bipartite_heterograph((2, 3), 4; edata = Dict(et => rand(2, 4), (:B, :to, :A) => rand(2, 4))) + @test_throws ArgumentError edge_features(g) + @test edge_features(edge_type_subgraph(g, et)) === g.edata[et].e +end + ## Cannot test this because DataStore is not an ordered collection ## Uncomment when/if it will be based on OrderedDict # @testset "show" begin diff --git a/GNNLux/docs/src/api/conv.md b/GNNLux/docs/src/api/conv.md index ae106648a..d7d6384ce 100644 --- a/GNNLux/docs/src/api/conv.md +++ b/GNNLux/docs/src/api/conv.md @@ -30,7 +30,7 @@ The table below lists all graph convolutional layers implemented in the *GNNLux. | [`GMMConv`](@ref) | | | ✓ | | | | [`GraphConv`](@ref) | ✓ | | | ✓ | ✓ | | [`MEGNetConv`](@ref) | | | ✓ | | | -| [`NNConv`](@ref) | | | ✓ | | | +| [`NNConv`](@ref) | | | ✓ | ✓ | | | [`ResGatedGraphConv`](@ref) | | | | ✓ | ✓ | | [`SAGEConv`](@ref) | ✓ | | | ✓ | ✓ | | [`SGConv`](@ref) | ✓ | | | | ✓ | diff --git a/GNNLux/test/layers/conv.jl b/GNNLux/test/layers/conv.jl index a44e0df77..75e49dcb5 100644 --- a/GNNLux/test/layers/conv.jl +++ b/GNNLux/test/layers/conv.jl @@ -193,6 +193,17 @@ end @test st′.nn.layer_2.running_mean != st.nn.layer_2.running_mean y′, st″ = l(g2, x, e, ps, st′) @test typeof(st″) == typeof(st) + + # bipartite (xj, xi) input matches the homogeneous layer on the graph with nodes [A; B] + l = NNConv(n_in => n_out, Dense(n_in_edge => n_out * n_in), tanh) + ps, st = LuxCore.setup(rng, l) + s, t = [1, 1, 2], [1, 2, 3] + gb = GNNHeteroGraph((:A, :to, :B) => (s, t); num_nodes = Dict(:A => 2, :B => 3)) + xA, xB = randn(rng, Float32, n_in, 2), randn(rng, Float32, n_in, 3) + eb = randn(rng, Float32, n_in_edge, 3) + yb, _ = l(gb, (xA, xB), eb, ps, st) + yu, _ = l(GNNGraph(s, 2 .+ t, num_nodes = 5), hcat(xA, xB), eb, ps, st) + @test yb ≈ yu[:, 3:end] end @testset "GMMConv" begin diff --git a/GNNlib/src/layers/conv.jl b/GNNlib/src/layers/conv.jl index cec87d8e3..7224c0e46 100644 --- a/GNNlib/src/layers/conv.jl +++ b/GNNlib/src/layers/conv.jl @@ -262,11 +262,12 @@ end ####################### NNConv ###################################### -function nn_conv(l, g::GNNGraph, x::AbstractMatrix, e) +function nn_conv(l, g::AbstractGNNGraph, x, e) check_num_nodes(g, x) + xj, xi = expand_srcdst(g, x) message = Fix1(nn_conv_message, l) - m = propagate(message, g, l.aggr, xj = x, e = e) - return l.σ.(l.weight * x .+ m .+ l.bias) + m = propagate(message, g, l.aggr, xj = xj, e = e) + return l.σ.(l.weight * xi .+ m .+ l.bias) end function nn_conv_message(l, xi, xj, e) diff --git a/GraphNeuralNetworks/Project.toml b/GraphNeuralNetworks/Project.toml index eff1c2b24..c5c6b1139 100644 --- a/GraphNeuralNetworks/Project.toml +++ b/GraphNeuralNetworks/Project.toml @@ -24,7 +24,7 @@ Statistics = "10745b16-79ce-11e8-11f9-7d13ad32a3b2" ChainRulesCore = "1" ConcreteStructs = "0.2.3" Flux = "0.16.0" -GNNGraphs = "1.4" +GNNGraphs = "1.7" GNNlib = "1.5" LinearAlgebra = "1" MLUtils = "0.4" diff --git a/GraphNeuralNetworks/docs/src/api/conv.md b/GraphNeuralNetworks/docs/src/api/conv.md index fc89b8f48..7831e1aaa 100644 --- a/GraphNeuralNetworks/docs/src/api/conv.md +++ b/GraphNeuralNetworks/docs/src/api/conv.md @@ -31,7 +31,7 @@ The table below lists all graph convolutional layers implemented in the *GraphNe | [`GMMConv`](@ref) | | | ✓ | | | | [`GraphConv`](@ref) | ✓ | | | ✓ | ✓ | | [`MEGNetConv`](@ref) | | | ✓ | | | -| [`NNConv`](@ref) | | | ✓ | | | +| [`NNConv`](@ref) | | | ✓ | ✓ | | | [`ResGatedGraphConv`](@ref) | | | | ✓ | ✓ | | [`SAGEConv`](@ref) | ✓ | | | ✓ | ✓ | | [`SGConv`](@ref) | ✓ | | | | ✓ | diff --git a/GraphNeuralNetworks/src/layers/conv.jl b/GraphNeuralNetworks/src/layers/conv.jl index 2bbba36b9..4fec0b81f 100644 --- a/GraphNeuralNetworks/src/layers/conv.jl +++ b/GraphNeuralNetworks/src/layers/conv.jl @@ -703,6 +703,18 @@ For convenience, also functions returning a single `(out*in, num_edges)` matrix - `bias`: Add learnable bias. - `init`: Weights' initializer. +# Forward + + (::NNConv)(g, x, e = edge_features(g)) -> AbstractMatrix + +Takes as input a graph `g`, node features `x` and edge features `e` of size `(num_edge_features, num_edges)`. +If `e` is not given, the edge features stored in `g` are used. +`x` is either a matrix of size `(in, num_nodes)` or, for bipartite graphs +(e.g. a relation of a heterogeneous graph in [`HeteroGraphConv`](@ref)), a tuple `(xj, xi)` +of source and target node features: ``W`` acts on the targets `xi`, the edge-conditioned +weights on the sources `xj`. Returns a matrix of size `(out, num_nodes)` +(`(out, num_target_nodes)` for tuple input). + # Examples: ```julia @@ -746,7 +758,11 @@ function NNConv(ch::Pair{Int, Int}, nn, σ = identity; aggr = +, bias = true, return NNConv(W, b, nn, σ, aggr) end -(l::NNConv)(g, x, e) = GNNlib.nn_conv(l, g, x, e) +function (l::NNConv)(g, x, e = edge_features(g)) + e === nothing && + throw(ArgumentError("NNConv requires edge features: pass them as `l(g, x, e)` or store them in the graph's `edata`")) + return GNNlib.nn_conv(l, g, x, e) +end (l::NNConv)(g::GNNGraph) = GNNGraph(g, ndata = l(g, node_features(g), edge_features(g))) diff --git a/GraphNeuralNetworks/src/layers/heteroconv.jl b/GraphNeuralNetworks/src/layers/heteroconv.jl index 7666ac8e8..8af130b86 100644 --- a/GraphNeuralNetworks/src/layers/heteroconv.jl +++ b/GraphNeuralNetworks/src/layers/heteroconv.jl @@ -18,6 +18,9 @@ have to be aggregated using the `aggr` function. The default is to sum the outpu * `x::Union{NamedTuple,Dict}`: The input node features. The keys are node types and the values are node feature tensors. +Layers needing edge features (e.g. [`NNConv`](@ref)) read them from each relation's `edata`, +via [`edge_features`](@ref) on the subgraph returned by [`edge_type_subgraph`](@ref). + # Examples ```jldoctest diff --git a/GraphNeuralNetworks/test/layers/heteroconv.jl b/GraphNeuralNetworks/test/layers/heteroconv.jl index 5614fcbd1..aaa130226 100644 --- a/GraphNeuralNetworks/test/layers/heteroconv.jl +++ b/GraphNeuralNetworks/test/layers/heteroconv.jl @@ -218,4 +218,41 @@ @test dx.A ≈ ndx[1].A rtol=1e-3 @test dx.B ≈ ndx[1].B rtol=1e-3 end + + @testset "NNConv" begin + nA, nB, din, dout, de = 2, 3, 4, 2, 5 + sAB, tAB = [1, 1, 2, 2], [1, 2, 2, 3] + sBA, tBA = [1, 3, 3], [1, 1, 2] + eAB, eBA = rand(Float32, de, 4), rand(Float32, de, 3) + g = GNNHeteroGraph(((:A, :to, :B) => (sAB, tAB), (:B, :to, :A) => (sBA, tBA)); + num_nodes = Dict(:A => nA, :B => nB), + edata = Dict((:A, :to, :B) => eAB, (:B, :to, :A) => eBA)) + x = (A = rand(Float32, din, nA), B = rand(Float32, din, nB)) + lAB = NNConv(din => dout, Dense(de => dout * din), tanh) + lBA = NNConv(din => dout, Dense(de => dout * din), tanh) + layers = HeteroGraphConv((:A, :to, :B) => lAB, (:B, :to, :A) => lBA) + + # reference: homogeneous NNConv on graphs whose nodes are [A nodes; B nodes] + gAB = GNNGraph(sAB, nA .+ tAB, num_nodes = nA + nB) + gBA = GNNGraph(nA .+ sBA, tBA, num_nodes = nA + nB) + function ref(lAB, lBA, x) + xAB = hcat(x.A, x.B) + return (A = lBA(gBA, xAB, eBA)[:, 1:nA], B = lAB(gAB, xAB, eAB)[:, (nA + 1):end]) + end + y = layers(g, x) + yref = ref(lAB, lBA, x) + @test y.A ≈ yref.A + @test y.B ≈ yref.B + + loss(y) = sum(abs2, y.A) + sum(abs2, y.B) + grad, dx = gradient((m, x) -> loss(m(g, x)), layers, x) + gradAB, gradBA, dxref = gradient((lAB, lBA, x) -> loss(ref(lAB, lBA, x)), lAB, lBA, x) + @test grad.layers[1].weight ≈ gradAB.weight + @test grad.layers[1].nn.weight ≈ gradAB.nn.weight + @test grad.layers[2].bias ≈ gradBA.bias + @test dx.A ≈ dxref.A + @test dx.B ≈ dxref.B + + @test_throws ArgumentError layers(rand_bipartite_heterograph((nA, nB), 4), x) + end end