Skip to content

Commit 9cda3cf

Browse files
i-Amoghclaude
andauthored
Add GMMConv support for HeteroGraphConv (#657)
GMMConv accepts a tuple (xj, xi) of source and target node features and reads the edge pseudo-coordinates from the graph when they are not passed, so it can be used in HeteroGraphConv. Also fixes show for GMMConv with a non-identity activation and corrects its docstring formula. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 1a77508 commit 9cda3cf

8 files changed

Lines changed: 106 additions & 29 deletions

File tree

‎GNNLux/Project.toml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ GNNlib = {path = "../GNNlib"}
2525

2626
[compat]
2727
ConcreteStructs = "0.2.3"
28-
GNNGraphs = "1.4"
28+
GNNGraphs = "1.7"
2929
GNNlib = "1.5"
3030
Lux = "1"
3131
LuxCore = "1"

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ The table below lists all graph convolutional layers implemented in the *GNNLux.
2727
| [`GatedGraphConv`](@ref) | ✓ | | | ✓ | ✓ |
2828
| [`GCNConv`](@ref) | ✓ | ✓ | | ✓ | |
2929
| [`GINConv`](@ref) | ✓ | | | ✓ | ✓ |
30-
| [`GMMConv`](@ref) | | | ✓ | | |
30+
| [`GMMConv`](@ref) | | | ✓ | ✓ | |
3131
| [`GraphConv`](@ref) | ✓ | | | ✓ | ✓ |
3232
| [`MEGNetConv`](@ref) | | | ✓ | | |
3333
| [`NNConv`](@ref) | | | ✓ | ✓ | |

‎GNNLux/src/layers/conv.jl‎

Lines changed: 21 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1409,18 +1409,16 @@ end
14091409
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)
14101410
Performs the operation
14111411
```math
1412-
\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
1412+
\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)
14131413
```
1414-
where ``w^a_{k}(e^a)`` for feature `a` and kernel `k` is given by
1414+
where the weight ``w_k`` of kernel `k` is given by
14151415
```math
1416-
w^a_{k}(e^a) = \exp(-\frac{1}{2}(e^a - \mu^a_k)^T (\Sigma^{-1})^a_k(e^a - \mu^a_k))
1416+
w_k(\mathbf{e}) = \exp\left(-\frac{1}{2}(\mathbf{e} - \boldsymbol{\mu}_k)^T \Sigma_k^{-1}(\mathbf{e} - \boldsymbol{\mu}_k)\right)
14171417
```
1418-
``\Theta_k, \mu^a_k, (\Sigma^{-1})^a_k`` are learnable parameters.
1418+
with diagonal ``\Sigma_k^{-1}``. ``\Theta_k, \boldsymbol{\mu}_k, \Sigma_k^{-1}`` are learnable parameters.
14191419
1420-
The input to the layer is a node feature array `x` of size `(num_features, num_nodes)` and
1421-
edge pseudo-coordinate array `e` of size `(num_features, num_edges)`
1422-
The residual ``\mathbf{x}_i`` is added only if `residual=true` and the output size is the same
1423-
as the input size.
1420+
The residual ``\mathbf{x}_i`` is added to the output only if `residual=true` and the output size
1421+
is the same as the input size.
14241422
14251423
# Arguments
14261424
@@ -1434,6 +1432,17 @@ as the input size.
14341432
- `init_bias`: Bias initializer. Default `zeros32`.
14351433
- `use_bias`: Add learnable bias. Default `true`.
14361434
1435+
# Forward
1436+
1437+
(::GMMConv)(g, x, [e], ps, st)
1438+
1439+
Takes as input a graph `g`, a node feature matrix `x` of size `(in, num_nodes)`, an edge
1440+
pseudo-coordinate matrix `e` of size `(ein, num_edges)`, which defaults to the edge features
1441+
stored in `g`, and the parameters and state of the layer. Returns a node feature matrix of
1442+
size `(out, num_nodes)` and the state. For bipartite graphs, such as a relation of a
1443+
heterogeneous graph, `x` can be a tuple `(xj, xi)` of source and target node features,
1444+
and the output has one column per target node.
1445+
14371446
# Examples
14381447
14391448
```julia
@@ -1506,7 +1515,9 @@ function LuxCore.parameterlength(l::GMMConv)
15061515
return n
15071516
end
15081517

1509-
function (l::GMMConv)(g::GNNGraph, x, e, ps, st)
1518+
(l::GMMConv)(g, x, ps, st) = l(g, x, edge_features(g), ps, st)
1519+
1520+
function (l::GMMConv)(g::AbstractGNNGraph, x, e, ps, st)
15101521
dense_x = StatefulLuxLayer{true}(l.dense_x, ps.dense_x, _getstate(st, :dense_x))
15111522
m = (; ps.mu, ps.sigma_inv, dense_x, l.σ, l.ch, l.K, l.residual, bias = _getbias(ps))
15121523
return GNNlib.gmm_conv(m, g, x, e), st
@@ -1515,7 +1526,7 @@ end
15151526
function Base.show(io::IO, l::GMMConv)
15161527
(nin, ein), out = l.ch
15171528
print(io, "GMMConv((", nin, ",", ein, ")=>", out)
1518-
l.σ == identity || print(io, ", σ=", l.dense_s.σ)
1529+
l.σ == identity || print(io, ", σ=", l.σ)
15191530
print(io, ", K=", l.K)
15201531
print(io, ", residual=", l.residual)
15211532
l.use_bias == true || print(io, ", use_bias=false")

‎GNNLux/test/layers/conv.jl‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -211,6 +211,18 @@ end
211211
e = randn(rng, Float32, ein_dims, g.num_edges)
212212
l = GMMConv((in_dims, ein_dims) => out_dims, tanh; K = 2, residual = false)
213213
test_lux_layer(rng, l, g, x; outputsize=(out_dims,), e)
214+
215+
# bipartite subgraph with edge features read from the graph,
216+
# against the same graph with the union of the nodes
217+
ps, st = LuxCore.setup(rng, l)
218+
hg = rand_bipartite_heterograph(rng, (4, 6), 12;
219+
edata = Dict((:A, :to, :B) => randn(rng, Float32, ein_dims, 12)))
220+
sg = edge_type_subgraph(hg, (:A, :to, :B))
221+
xA, xB = randn(rng, Float32, in_dims, 4), randn(rng, Float32, in_dims, 6)
222+
y, _ = l(sg, (xA, xB), ps, st)
223+
s, t = edge_index(sg)
224+
gu = GNNGraph(s, t .+ 4; num_nodes = 10, edata = edge_features(sg))
225+
@test y ≈ l(gu, hcat(xA, xB), ps, st)[1][:, 5:10]
214226
end
215227

216228
@testset "ResGatedGraphConv" begin

‎GNNlib/src/layers/conv.jl‎

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -388,29 +388,33 @@ end
388388

389389
####################### GMMConv ######################################
390390

391-
function gmm_conv(l, g::GNNGraph, x::AbstractMatrix, e::AbstractMatrix)
391+
function gmm_conv(l, g::AbstractGNNGraph, x, e::AbstractMatrix)
392392
(nin, ein), out = l.ch #Notational Simplicity
393393

394-
@assert (ein == size(e)[1]&&g.num_edges == size(e)[2]) "Pseudo-cordinate dimension is not equal to (ein,num_edge)"
394+
check_num_nodes(g, x)
395+
check_num_edges(g, e)
396+
@assert ein == size(e, 1) "Pseudo-coordinate dimension $(size(e, 1)) is not equal to ein = $ein"
397+
398+
xj, xi = expand_srcdst(g, x)
395399

396-
num_edges = g.num_edges
400+
num_edges = size(e, 2)
397401
w = reshape(e, (ein, 1, num_edges))
398402
mu = reshape(l.mu, (ein, l.K, 1))
399403

400404
w = @. -((w - mu)^2) / 2
401405
w = w .* reshape(l.sigma_inv .^ 2, (ein, l.K, 1))
402406
w = exp.(sum(w, dims = 1)) # (1, K, num_edge)
403407

404-
xj = reshape(l.dense_x(x), (out, l.K, :)) # (out, K, num_nodes)
408+
xj = reshape(l.dense_x(xj), (out, l.K, :)) # (out, K, num_nodes)
405409

406410
m = propagate(e_mul_xj, g, mean, xj = xj, e = w)
407411
m = dropdims(mean(m, dims = 2), dims = 2) # (out, num_nodes)
408412

409413
m = l.σ.(m .+ l.bias)
410414

411415
if l.residual
412-
if size(x, 1) == size(m, 1)
413-
m += x
416+
if size(xi, 1) == size(m, 1)
417+
m += xi
414418
else
415419
# see the note in `cg_conv`: keep `@warn` out of the AD path to
416420
# 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)
423427
return m
424428
end
425429

430+
function gmm_conv(l, g::AbstractGNNGraph, x, ::Nothing)
431+
throw(ArgumentError("GMMConv requires edge pseudo-coordinates `e`, but none were given and the graph has no edge features"))
432+
end
433+
426434
####################### SGCConv ######################################
427435

428436
# this layer is not stable enough to be supported by GNNHeteroGraph type

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ The table below lists all graph convolutional layers implemented in the *GraphNe
2828
| [`GatedGraphConv`](@ref) | ✓ | | | ✓ | ✓ |
2929
| [`GCNConv`](@ref) | ✓ | ✓ | | ✓ | |
3030
| [`GINConv`](@ref) | ✓ | | | ✓ | ✓ |
31-
| [`GMMConv`](@ref) | | | ✓ | | |
31+
| [`GMMConv`](@ref) | | | ✓ | ✓ | |
3232
| [`GraphConv`](@ref) | ✓ | | | ✓ | ✓ |
3333
| [`MEGNetConv`](@ref) | | | ✓ | | |
3434
| [`NNConv`](@ref) | | | ✓ | ✓ | |

‎GraphNeuralNetworks/src/layers/conv.jl‎

Lines changed: 18 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1125,18 +1125,16 @@ end
11251125
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)
11261126
Performs the operation
11271127
```math
1128-
\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
1128+
\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)
11291129
```
1130-
where ``w^a_{k}(e^a)`` for feature `a` and kernel `k` is given by
1130+
where the weight ``w_k`` of kernel `k` is given by
11311131
```math
1132-
w^a_{k}(e^a) = \exp(-\frac{1}{2}(e^a - \mu^a_k)^T (\Sigma^{-1})^a_k(e^a - \mu^a_k))
1132+
w_k(\mathbf{e}) = \exp\left(-\frac{1}{2}(\mathbf{e} - \boldsymbol{\mu}_k)^T \Sigma_k^{-1}(\mathbf{e} - \boldsymbol{\mu}_k)\right)
11331133
```
1134-
``\Theta_k, \mu^a_k, (\Sigma^{-1})^a_k`` are learnable parameters.
1134+
with diagonal ``\Sigma_k^{-1}``. ``\Theta_k, \boldsymbol{\mu}_k, \Sigma_k^{-1}`` are learnable parameters.
11351135
1136-
The input to the layer is a node feature array `x` of size `(num_features, num_nodes)` and
1137-
edge pseudo-coordinate array `e` of size `(num_features, num_edges)`
1138-
The residual ``\mathbf{x}_i`` is added only if `residual=true` and the output size is the same
1139-
as the input size.
1136+
The residual ``\mathbf{x}_i`` is added to the output only if `residual=true` and the output size
1137+
is the same as the input size.
11401138
11411139
# Arguments
11421140
@@ -1149,6 +1147,16 @@ as the input size.
11491147
- `init`: Weights' initializer. Default `glorot_uniform`.
11501148
- `residual`: Residual connection. Default `false`.
11511149
1150+
# Forward
1151+
1152+
(::GMMConv)(g::AbstractGNNGraph, x, e = edge_features(g)) -> AbstractMatrix
1153+
1154+
Takes as input a graph `g`, a node feature matrix `x` of size `(in, num_nodes)` and
1155+
an edge pseudo-coordinate matrix `e` of size `(ein, num_edges)`, which defaults to the
1156+
edge features stored in `g`. Returns a node feature matrix of size `(out, num_nodes)`.
1157+
For bipartite graphs, such as the relations of a [`HeteroGraphConv`](@ref), `x` can be
1158+
a tuple `(xj, xi)` of source and target node features, and the output has one column per target node.
1159+
11521160
# Examples
11531161
11541162
```julia
@@ -1194,14 +1202,14 @@ function GMMConv(ch::Pair{NTuple{2, Int}, Int},
11941202
GMMConv(mu, sigma_inv, b, σ, ch, K, dense_x, residual)
11951203
end
11961204

1197-
(l::GMMConv)(g::GNNGraph, x, e) = GNNlib.gmm_conv(l, g, x, e)
1205+
(l::GMMConv)(g::AbstractGNNGraph, x, e = edge_features(g)) = GNNlib.gmm_conv(l, g, x, e)
11981206

11991207
(l::GMMConv)(g::GNNGraph) = GNNGraph(g, ndata = l(g, node_features(g), edge_features(g)))
12001208

12011209
function Base.show(io::IO, l::GMMConv)
12021210
(nin, ein), out = l.ch
12031211
print(io, "GMMConv((", nin, ",", ein, ")=>", out)
1204-
l.σ == identity || print(io, ", σ=", l.dense_s.σ)
1212+
l.σ == identity || print(io, ", σ=", l.σ)
12051213
print(io, ", K=", l.K)
12061214
print(io, ", residual=", l.residual)
12071215
print(io, ")")

‎GraphNeuralNetworks/test/layers/heteroconv.jl‎

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -255,4 +255,42 @@
255255

256256
@test_throws ArgumentError layers(rand_bipartite_heterograph((nA, nB), 4), x)
257257
end
258+
259+
@testset "GMMConv" begin
260+
ein = 3
261+
et1, et2 = (:A, :to, :B), (:B, :to, :A)
262+
g = rand_bipartite_heterograph((2, 3), 6;
263+
edata = Dict(et1 => rand(Float32, ein, 6), et2 => rand(Float32, ein, 6)))
264+
# different feature sizes per node type: the residual must use the target features
265+
x = (A = rand(Float32, 4, 2), B = rand(Float32, 3, 3))
266+
l1 = GMMConv((4, ein) => 3, tanh; K = 2, residual = true)
267+
l2 = GMMConv((3, ein) => 2; K = 3)
268+
layers = HeteroGraphConv(et1 => l1, et2 => l2)
269+
y = layers(g, x)
270+
271+
function gmm_ref(l, (s, t), xj, xi, e)
272+
(nin, _), out = l.ch
273+
Θ = reshape(l.dense_x.weight, out, l.K, nin)
274+
h = zeros(Float32, out, size(xi, 2))
275+
for i in axes(h, 2)
276+
nbrs = findall(==(i), t)
277+
for n in nbrs, k in 1:l.K
278+
w = exp(-sum(abs2, (e[:, n] .- l.mu[:, k]) .* l.sigma_inv[:, k]) / 2)
279+
h[:, i] .+= w .* (Θ[:, k, :] * xj[:, s[n]]) ./ (l.K * length(nbrs))
280+
end
281+
end
282+
h = l.σ.(h .+ l.bias)
283+
return l.residual ? h .+ xi : h
284+
end
285+
@test y.B ≈ gmm_ref(l1, edge_index(g, et1), x.A, x.B, g.edata[et1].e)
286+
@test y.A ≈ gmm_ref(l2, edge_index(g, et2), x.B, x.A, g.edata[et2].e)
287+
288+
loss(x) = sum(abs2, layers(g, x).A) + sum(abs2, layers(g, x).B)
289+
dx = gradient(loss, x)[1]
290+
_, (ndx,) = finitediff_withgradient(loss, x)
291+
@test dx.A ≈ ndx.A rtol=1e-3
292+
@test dx.B ≈ ndx.B rtol=1e-3
293+
294+
@test_throws ArgumentError layers(hg, x)
295+
end
258296
end

0 commit comments

Comments
 (0)