diff --git a/GNNLux/Project.toml b/GNNLux/Project.toml index 893b2782c..fce31f55d 100644 --- a/GNNLux/Project.toml +++ b/GNNLux/Project.toml @@ -25,7 +25,7 @@ GNNlib = {path = "../GNNlib"} [compat] ConcreteStructs = "0.2.3" -GNNGraphs = "1.4" +GNNGraphs = "1.7" GNNlib = "1.5" Lux = "1" LuxCore = "1" diff --git a/GNNLux/docs/src/api/conv.md b/GNNLux/docs/src/api/conv.md index d7d6384ce..f79ffea17 100644 --- a/GNNLux/docs/src/api/conv.md +++ b/GNNLux/docs/src/api/conv.md @@ -27,7 +27,7 @@ The table below lists all graph convolutional layers implemented in the *GNNLux. | [`GatedGraphConv`](@ref) | ✓ | | | ✓ | ✓ | | [`GCNConv`](@ref) | ✓ | ✓ | | ✓ | | | [`GINConv`](@ref) | ✓ | | | ✓ | ✓ | -| [`GMMConv`](@ref) | | | ✓ | | | +| [`GMMConv`](@ref) | | | ✓ | ✓ | | | [`GraphConv`](@ref) | ✓ | | | ✓ | ✓ | | [`MEGNetConv`](@ref) | | | ✓ | | | | [`NNConv`](@ref) | | | ✓ | ✓ | | diff --git a/GNNLux/src/layers/conv.jl b/GNNLux/src/layers/conv.jl index 6a7be0664..7acc31e57 100644 --- a/GNNLux/src/layers/conv.jl +++ b/GNNLux/src/layers/conv.jl @@ -1409,18 +1409,16 @@ end Graph mixture model convolution layer from the paper [Geometric deep learning on graphs and manifolds using mixture model CNNs](https://arxiv.org/abs/1611.08402) Performs the operation ```math -\mathbf{x}_i' = \mathbf{x}_i + \frac{1}{|N(i)|} \sum_{j\in N(i)}\frac{1}{K}\sum_{k=1}^K \mathbf{w}_k(\mathbf{e}_{j\to i}) \odot \Theta_k \mathbf{x}_j +\mathbf{x}_i' = \sigma\left(\frac{1}{|N(i)|} \sum_{j\in N(i)}\frac{1}{K}\sum_{k=1}^K w_k(\mathbf{e}_{j\to i}) \, \Theta_k \mathbf{x}_j + \mathbf{b}\right) ``` -where ``w^a_{k}(e^a)`` for feature `a` and kernel `k` is given by +where the weight ``w_k`` of kernel `k` is given by ```math -w^a_{k}(e^a) = \exp(-\frac{1}{2}(e^a - \mu^a_k)^T (\Sigma^{-1})^a_k(e^a - \mu^a_k)) +w_k(\mathbf{e}) = \exp\left(-\frac{1}{2}(\mathbf{e} - \boldsymbol{\mu}_k)^T \Sigma_k^{-1}(\mathbf{e} - \boldsymbol{\mu}_k)\right) ``` -``\Theta_k, \mu^a_k, (\Sigma^{-1})^a_k`` are learnable parameters. +with diagonal ``\Sigma_k^{-1}``. ``\Theta_k, \boldsymbol{\mu}_k, \Sigma_k^{-1}`` are learnable parameters. -The input to the layer is a node feature array `x` of size `(num_features, num_nodes)` and -edge pseudo-coordinate array `e` of size `(num_features, num_edges)` -The residual ``\mathbf{x}_i`` is added only if `residual=true` and the output size is the same -as the input size. +The residual ``\mathbf{x}_i`` is added to the output only if `residual=true` and the output size +is the same as the input size. # Arguments @@ -1434,6 +1432,17 @@ as the input size. - `init_bias`: Bias initializer. Default `zeros32`. - `use_bias`: Add learnable bias. Default `true`. +# Forward + + (::GMMConv)(g, x, [e], ps, st) + +Takes as input a graph `g`, a node feature matrix `x` of size `(in, num_nodes)`, an edge +pseudo-coordinate matrix `e` of size `(ein, num_edges)`, which defaults to the edge features +stored in `g`, and the parameters and state of the layer. Returns a node feature matrix of +size `(out, num_nodes)` and the state. For bipartite graphs, such as a relation of a +heterogeneous graph, `x` can be a tuple `(xj, xi)` of source and target node features, +and the output has one column per target node. + # Examples ```julia @@ -1506,7 +1515,9 @@ function LuxCore.parameterlength(l::GMMConv) return n end -function (l::GMMConv)(g::GNNGraph, x, e, ps, st) +(l::GMMConv)(g, x, ps, st) = l(g, x, edge_features(g), ps, st) + +function (l::GMMConv)(g::AbstractGNNGraph, x, e, ps, st) dense_x = StatefulLuxLayer{true}(l.dense_x, ps.dense_x, _getstate(st, :dense_x)) m = (; ps.mu, ps.sigma_inv, dense_x, l.σ, l.ch, l.K, l.residual, bias = _getbias(ps)) return GNNlib.gmm_conv(m, g, x, e), st @@ -1515,7 +1526,7 @@ end function Base.show(io::IO, l::GMMConv) (nin, ein), out = l.ch print(io, "GMMConv((", nin, ",", ein, ")=>", out) - l.σ == identity || print(io, ", σ=", l.dense_s.σ) + l.σ == identity || print(io, ", σ=", l.σ) print(io, ", K=", l.K) print(io, ", residual=", l.residual) l.use_bias == true || print(io, ", use_bias=false") diff --git a/GNNLux/test/layers/conv.jl b/GNNLux/test/layers/conv.jl index 75e49dcb5..972c9e372 100644 --- a/GNNLux/test/layers/conv.jl +++ b/GNNLux/test/layers/conv.jl @@ -211,6 +211,18 @@ end e = randn(rng, Float32, ein_dims, g.num_edges) l = GMMConv((in_dims, ein_dims) => out_dims, tanh; K = 2, residual = false) test_lux_layer(rng, l, g, x; outputsize=(out_dims,), e) + + # bipartite subgraph with edge features read from the graph, + # against the same graph with the union of the nodes + ps, st = LuxCore.setup(rng, l) + hg = rand_bipartite_heterograph(rng, (4, 6), 12; + edata = Dict((:A, :to, :B) => randn(rng, Float32, ein_dims, 12))) + sg = edge_type_subgraph(hg, (:A, :to, :B)) + xA, xB = randn(rng, Float32, in_dims, 4), randn(rng, Float32, in_dims, 6) + y, _ = l(sg, (xA, xB), ps, st) + s, t = edge_index(sg) + gu = GNNGraph(s, t .+ 4; num_nodes = 10, edata = edge_features(sg)) + @test y ≈ l(gu, hcat(xA, xB), ps, st)[1][:, 5:10] end @testset "ResGatedGraphConv" begin diff --git a/GNNlib/src/layers/conv.jl b/GNNlib/src/layers/conv.jl index 7224c0e46..8297734dc 100644 --- a/GNNlib/src/layers/conv.jl +++ b/GNNlib/src/layers/conv.jl @@ -388,12 +388,16 @@ end ####################### GMMConv ###################################### -function gmm_conv(l, g::GNNGraph, x::AbstractMatrix, e::AbstractMatrix) +function gmm_conv(l, g::AbstractGNNGraph, x, e::AbstractMatrix) (nin, ein), out = l.ch #Notational Simplicity - @assert (ein == size(e)[1]&&g.num_edges == size(e)[2]) "Pseudo-cordinate dimension is not equal to (ein,num_edge)" + check_num_nodes(g, x) + check_num_edges(g, e) + @assert ein == size(e, 1) "Pseudo-coordinate dimension $(size(e, 1)) is not equal to ein = $ein" + + xj, xi = expand_srcdst(g, x) - num_edges = g.num_edges + num_edges = size(e, 2) w = reshape(e, (ein, 1, num_edges)) mu = reshape(l.mu, (ein, l.K, 1)) @@ -401,7 +405,7 @@ function gmm_conv(l, g::GNNGraph, x::AbstractMatrix, e::AbstractMatrix) w = w .* reshape(l.sigma_inv .^ 2, (ein, l.K, 1)) w = exp.(sum(w, dims = 1)) # (1, K, num_edge) - xj = reshape(l.dense_x(x), (out, l.K, :)) # (out, K, num_nodes) + xj = reshape(l.dense_x(xj), (out, l.K, :)) # (out, K, num_nodes) m = propagate(e_mul_xj, g, mean, xj = xj, e = w) m = dropdims(mean(m, dims = 2), dims = 2) # (out, num_nodes) @@ -409,8 +413,8 @@ function gmm_conv(l, g::GNNGraph, x::AbstractMatrix, e::AbstractMatrix) m = l.σ.(m .+ l.bias) if l.residual - if size(x, 1) == size(m, 1) - m += x + if size(xi, 1) == size(m, 1) + m += xi else # see the note in `cg_conv`: keep `@warn` out of the AD path to # avoid the Julia 1.12 codegen segfault (FluxML/Zygote.jl#1662). @@ -423,6 +427,10 @@ function gmm_conv(l, g::GNNGraph, x::AbstractMatrix, e::AbstractMatrix) return m end +function gmm_conv(l, g::AbstractGNNGraph, x, ::Nothing) + throw(ArgumentError("GMMConv requires edge pseudo-coordinates `e`, but none were given and the graph has no edge features")) +end + ####################### SGCConv ###################################### # this layer is not stable enough to be supported by GNNHeteroGraph type diff --git a/GraphNeuralNetworks/docs/src/api/conv.md b/GraphNeuralNetworks/docs/src/api/conv.md index 7831e1aaa..f0bdc6e6d 100644 --- a/GraphNeuralNetworks/docs/src/api/conv.md +++ b/GraphNeuralNetworks/docs/src/api/conv.md @@ -28,7 +28,7 @@ The table below lists all graph convolutional layers implemented in the *GraphNe | [`GatedGraphConv`](@ref) | ✓ | | | ✓ | ✓ | | [`GCNConv`](@ref) | ✓ | ✓ | | ✓ | | | [`GINConv`](@ref) | ✓ | | | ✓ | ✓ | -| [`GMMConv`](@ref) | | | ✓ | | | +| [`GMMConv`](@ref) | | | ✓ | ✓ | | | [`GraphConv`](@ref) | ✓ | | | ✓ | ✓ | | [`MEGNetConv`](@ref) | | | ✓ | | | | [`NNConv`](@ref) | | | ✓ | ✓ | | diff --git a/GraphNeuralNetworks/src/layers/conv.jl b/GraphNeuralNetworks/src/layers/conv.jl index 4fec0b81f..7e5d190e5 100644 --- a/GraphNeuralNetworks/src/layers/conv.jl +++ b/GraphNeuralNetworks/src/layers/conv.jl @@ -1125,18 +1125,16 @@ end Graph mixture model convolution layer from the paper [Geometric deep learning on graphs and manifolds using mixture model CNNs](https://arxiv.org/abs/1611.08402) Performs the operation ```math -\mathbf{x}_i' = \mathbf{x}_i + \frac{1}{|N(i)|} \sum_{j\in N(i)}\frac{1}{K}\sum_{k=1}^K \mathbf{w}_k(\mathbf{e}_{j\to i}) \odot \Theta_k \mathbf{x}_j +\mathbf{x}_i' = \sigma\left(\frac{1}{|N(i)|} \sum_{j\in N(i)}\frac{1}{K}\sum_{k=1}^K w_k(\mathbf{e}_{j\to i}) \, \Theta_k \mathbf{x}_j + \mathbf{b}\right) ``` -where ``w^a_{k}(e^a)`` for feature `a` and kernel `k` is given by +where the weight ``w_k`` of kernel `k` is given by ```math -w^a_{k}(e^a) = \exp(-\frac{1}{2}(e^a - \mu^a_k)^T (\Sigma^{-1})^a_k(e^a - \mu^a_k)) +w_k(\mathbf{e}) = \exp\left(-\frac{1}{2}(\mathbf{e} - \boldsymbol{\mu}_k)^T \Sigma_k^{-1}(\mathbf{e} - \boldsymbol{\mu}_k)\right) ``` -``\Theta_k, \mu^a_k, (\Sigma^{-1})^a_k`` are learnable parameters. +with diagonal ``\Sigma_k^{-1}``. ``\Theta_k, \boldsymbol{\mu}_k, \Sigma_k^{-1}`` are learnable parameters. -The input to the layer is a node feature array `x` of size `(num_features, num_nodes)` and -edge pseudo-coordinate array `e` of size `(num_features, num_edges)` -The residual ``\mathbf{x}_i`` is added only if `residual=true` and the output size is the same -as the input size. +The residual ``\mathbf{x}_i`` is added to the output only if `residual=true` and the output size +is the same as the input size. # Arguments @@ -1149,6 +1147,16 @@ as the input size. - `init`: Weights' initializer. Default `glorot_uniform`. - `residual`: Residual connection. Default `false`. +# Forward + + (::GMMConv)(g::AbstractGNNGraph, x, e = edge_features(g)) -> AbstractMatrix + +Takes as input a graph `g`, a node feature matrix `x` of size `(in, num_nodes)` and +an edge pseudo-coordinate matrix `e` of size `(ein, num_edges)`, which defaults to the +edge features stored in `g`. Returns a node feature matrix of size `(out, num_nodes)`. +For bipartite graphs, such as the relations of a [`HeteroGraphConv`](@ref), `x` can be +a tuple `(xj, xi)` of source and target node features, and the output has one column per target node. + # Examples ```julia @@ -1194,14 +1202,14 @@ function GMMConv(ch::Pair{NTuple{2, Int}, Int}, GMMConv(mu, sigma_inv, b, σ, ch, K, dense_x, residual) end -(l::GMMConv)(g::GNNGraph, x, e) = GNNlib.gmm_conv(l, g, x, e) +(l::GMMConv)(g::AbstractGNNGraph, x, e = edge_features(g)) = GNNlib.gmm_conv(l, g, x, e) (l::GMMConv)(g::GNNGraph) = GNNGraph(g, ndata = l(g, node_features(g), edge_features(g))) function Base.show(io::IO, l::GMMConv) (nin, ein), out = l.ch print(io, "GMMConv((", nin, ",", ein, ")=>", out) - l.σ == identity || print(io, ", σ=", l.dense_s.σ) + l.σ == identity || print(io, ", σ=", l.σ) print(io, ", K=", l.K) print(io, ", residual=", l.residual) print(io, ")") diff --git a/GraphNeuralNetworks/test/layers/heteroconv.jl b/GraphNeuralNetworks/test/layers/heteroconv.jl index aaa130226..fe9a5bc38 100644 --- a/GraphNeuralNetworks/test/layers/heteroconv.jl +++ b/GraphNeuralNetworks/test/layers/heteroconv.jl @@ -255,4 +255,42 @@ @test_throws ArgumentError layers(rand_bipartite_heterograph((nA, nB), 4), x) end + + @testset "GMMConv" begin + ein = 3 + et1, et2 = (:A, :to, :B), (:B, :to, :A) + g = rand_bipartite_heterograph((2, 3), 6; + edata = Dict(et1 => rand(Float32, ein, 6), et2 => rand(Float32, ein, 6))) + # different feature sizes per node type: the residual must use the target features + x = (A = rand(Float32, 4, 2), B = rand(Float32, 3, 3)) + l1 = GMMConv((4, ein) => 3, tanh; K = 2, residual = true) + l2 = GMMConv((3, ein) => 2; K = 3) + layers = HeteroGraphConv(et1 => l1, et2 => l2) + y = layers(g, x) + + function gmm_ref(l, (s, t), xj, xi, e) + (nin, _), out = l.ch + Θ = reshape(l.dense_x.weight, out, l.K, nin) + h = zeros(Float32, out, size(xi, 2)) + for i in axes(h, 2) + nbrs = findall(==(i), t) + for n in nbrs, k in 1:l.K + w = exp(-sum(abs2, (e[:, n] .- l.mu[:, k]) .* l.sigma_inv[:, k]) / 2) + h[:, i] .+= w .* (Θ[:, k, :] * xj[:, s[n]]) ./ (l.K * length(nbrs)) + end + end + h = l.σ.(h .+ l.bias) + return l.residual ? h .+ xi : h + end + @test y.B ≈ gmm_ref(l1, edge_index(g, et1), x.A, x.B, g.edata[et1].e) + @test y.A ≈ gmm_ref(l2, edge_index(g, et2), x.B, x.A, g.edata[et2].e) + + loss(x) = sum(abs2, layers(g, x).A) + sum(abs2, layers(g, x).B) + dx = gradient(loss, x)[1] + _, (ndx,) = finitediff_withgradient(loss, x) + @test dx.A ≈ ndx.A rtol=1e-3 + @test dx.B ≈ ndx.B rtol=1e-3 + + @test_throws ArgumentError layers(hg, x) + end end