Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions GNNGraphs/src/GNNGraphs.jl
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,7 @@ export add_nodes,
perturb_edges,
remove_nodes,
ppr_diffusion,
pad_graph,
# from MLUtils.jl
batch,
unbatch,
Expand Down
4 changes: 2 additions & 2 deletions GNNGraphs/src/convert.jl
Original file line number Diff line number Diff line change
Expand Up @@ -128,15 +128,15 @@ end
function _to_coo_graph(g::GNNGraph{<:SPARSE_T})
s, t, v = findnz(g.graph)
return GNNGraph((s, t, v), g.num_nodes, g.num_edges, g.num_graphs,
g.graph_indicator, g.ndata, g.edata, g.gdata)
g.graph_indicator, g.ndata, g.edata, g.gdata; graph_sizes = g.graph_sizes)
end

function _to_coo_graph(g::GNNGraph{<:ADJMAT_T})
A = g.graph
s, t, _ = _findnz_idx(A)
v = _edge_values(A, s, t)
return GNNGraph((s, t, v), g.num_nodes, g.num_edges, g.num_graphs,
g.graph_indicator, g.ndata, g.edata, g.gdata)
g.graph_indicator, g.ndata, g.edata, g.gdata; graph_sizes = g.graph_sizes)
end

### CONVERT TO ADJACENCY MATRIX ################
Expand Down
30 changes: 21 additions & 9 deletions GNNGraphs/src/gnngraph.jl
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,8 @@ as well, unless explicitly set by the keyword arguments
A `GNNGraph` can also represent multiple graphs batched together
(see [`MLUtils.batch`](@ref) or [`SparseArrays.blockdiag`](@ref)).
The field `g.graph_indicator` contains the graph membership
of each node.
of each node, and `g.graph_sizes` the number of nodes in each graph.
Both are `nothing` for a single graph.

`GNNGraph`s are always directed graphs, therefore each edge is defined
by a source node and a target node (see [`edge_index`](@ref)).
Expand Down Expand Up @@ -110,13 +111,17 @@ struct GNNGraph{T <: Union{COO_T, ADJMAT_T}} <: AbstractGNNGraph{T}
num_edges::Int
num_graphs::Int
graph_indicator::Union{Nothing, AVecI} # vector of ints or nothing
graph_sizes::Union{Nothing, AVecI} # number of nodes in each graph, or nothing
ndata::DataStore
edata::DataStore
gdata::DataStore
is_coalesced::Bool # only for :coo, true if the graph is coalesced, i.e., no multi edges and indices ordered by target, then source
end

# GNNGraph constructor setting the is_coalesced field to false.
# GNNGraph constructor setting the is_coalesced field to false and deriving the
# graph_sizes field from the graph indicator. graph_sizes duplicates the graph indicator,
# but its length is the number of graphs, which makes the number of graphs part of the
# array shapes seen by compilers like Reactant.
# Callers pass an already validated `graph_indicator`; checking it here breaks Enzyme
# on Julia 1.13 (see test/enzyme.jl).
function GNNGraph(graph::T,
Expand All @@ -126,9 +131,16 @@ function GNNGraph(graph::T,
graph_indicator::Union{Nothing, AVecI},
ndata::DataStore,
edata::DataStore,
gdata::DataStore) where {T <: Union{COO_T, ADJMAT_T}}
gdata::DataStore,
is_coalesced::Bool = false;
graph_sizes = _graph_sizes(graph_indicator, num_graphs)) where {T <: Union{COO_T, ADJMAT_T}}
return GNNGraph{T}(graph, num_nodes, num_edges, num_graphs,
graph_indicator, ndata, edata, gdata, false)
graph_indicator, graph_sizes, ndata, edata, gdata, is_coalesced)
end

_graph_sizes(graph_indicator::Nothing, num_graphs) = nothing
function _graph_sizes(graph_indicator::AVecI, num_graphs)
return _scatter(+, ones_like(graph_indicator), graph_indicator, num_graphs)
end

function GNNGraph(data::D;
Expand Down Expand Up @@ -238,7 +250,7 @@ function GNNGraph(g::GNNGraph; ndata = g.ndata, edata = g.edata, gdata = g.gdata
return GNNGraph(graph,
g.num_nodes, g.num_edges, g.num_graphs,
g.graph_indicator,
ndata, edata, gdata)
ndata, edata, gdata; graph_sizes = g.graph_sizes)
end

"""
Expand All @@ -252,12 +264,12 @@ function Base.copy(g::GNNGraph; deep = false)
GNNGraph(deepcopy(g.graph),
g.num_nodes, g.num_edges, g.num_graphs,
deepcopy(g.graph_indicator),
deepcopy(g.ndata), deepcopy(g.edata), deepcopy(g.gdata))
deepcopy(g.ndata), deepcopy(g.edata), deepcopy(g.gdata); graph_sizes = deepcopy(g.graph_sizes))
else
GNNGraph(g.graph,
g.num_nodes, g.num_edges, g.num_graphs,
g.graph_indicator,
g.ndata, g.edata, g.gdata)
g.ndata, g.edata, g.gdata; graph_sizes = g.graph_sizes)
end
end

Expand Down Expand Up @@ -350,14 +362,14 @@ MLUtils.getobs(g::GNNGraph, i) = getgraph(g, i)
function Base.:(==)(g1::GNNGraph, g2::GNNGraph)
g1 === g2 && return true
for k in fieldnames(typeof(g1))
k === :graph_indicator && continue
k in (:graph_indicator, :graph_sizes) && continue
getfield(g1, k) != getfield(g2, k) && return false
end
return true
end

function Base.hash(g::T, h::UInt) where {T <: GNNGraph}
fs = (getfield(g, k) for k in fieldnames(T) if k !== :graph_indicator)
fs = (getfield(g, k) for k in fieldnames(T) if k ∉ (:graph_indicator, :graph_sizes))
return foldl((h, f) -> hash(f, h), fs, init = hash(T, h))
end

Expand Down
2 changes: 1 addition & 1 deletion GNNGraphs/src/sampling.jl
Original file line number Diff line number Diff line change
Expand Up @@ -203,7 +203,7 @@ function sample_neighbors(g::GNNGraph{<:COO_T}, nodes, K = -1;
gnew = GNNGraph(graph,
g.num_nodes, num_edges, g.num_graphs,
g.graph_indicator,
g.ndata, edata, g.gdata)
g.ndata, edata, g.gdata; graph_sizes = g.graph_sizes)
else
nodes_other = dir == :in ? setdiff(s, nodes) : setdiff(t, nodes)
nodes_all = [nodes; nodes_other]
Expand Down
105 changes: 95 additions & 10 deletions GNNGraphs/src/transform.jl
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ function add_self_loops(g::GNNGraph{<:COO_T})
return GNNGraph((s, t, ew),
g.num_nodes, length(s), g.num_graphs,
g.graph_indicator,
g.ndata, g.edata, g.gdata)
g.ndata, g.edata, g.gdata; graph_sizes = g.graph_sizes)
end

function _add_self_loops_index(s, t, n)
Expand All @@ -40,7 +40,7 @@ function add_self_loops(g::GNNGraph{<:ADJMAT_T})
return GNNGraph(A,
g.num_nodes, num_edges, g.num_graphs,
g.graph_indicator,
g.ndata, g.edata, g.gdata)
g.ndata, g.edata, g.gdata; graph_sizes = g.graph_sizes)
end

"""
Expand All @@ -65,7 +65,7 @@ function remove_self_loops(g::GNNGraph{<:COO_T})
GNNGraph((s, t, w),
g.num_nodes, length(s), g.num_graphs,
g.graph_indicator,
g.ndata, edata, g.gdata)
g.ndata, edata, g.gdata; graph_sizes = g.graph_sizes)
end

function remove_self_loops(g::GNNGraph{<:ADJMAT_T})
Expand All @@ -79,7 +79,7 @@ function remove_self_loops(g::GNNGraph{<:ADJMAT_T})
return GNNGraph(A,
g.num_nodes, num_edges, g.num_graphs,
g.graph_indicator,
g.ndata, g.edata, g.gdata)
g.ndata, g.edata, g.gdata; graph_sizes = g.graph_sizes)
end

"""
Expand Down Expand Up @@ -142,7 +142,7 @@ function remove_edges(g::GNNGraph{<:COO_T}, edges_to_remove::AbstractVector{<:In
return GNNGraph((s, t, w),
g.num_nodes, length(s), g.num_graphs,
g.graph_indicator,
g.ndata, edata, g.gdata)
g.ndata, edata, g.gdata; graph_sizes = g.graph_sizes)
end


Expand Down Expand Up @@ -190,7 +190,7 @@ function Base.coalesce(g::GNNGraph{<:COO_T}; aggr = +)
return GNNGraph((s, t, w),
g.num_nodes, num_edges, g.num_graphs,
g.graph_indicator,
g.ndata, edata, g.gdata, true)
g.ndata, edata, g.gdata, true; graph_sizes = g.graph_sizes)
end

"""
Expand Down Expand Up @@ -528,7 +528,7 @@ function to_bidirected(g::GNNGraph{<:COO_T})
g = GNNGraph((snew, tnew, w),
g.num_nodes, length(snew), g.num_graphs,
g.graph_indicator,
g.ndata, edata, g.gdata)
g.ndata, edata, g.gdata; graph_sizes = g.graph_sizes)

return coalesce(g; aggr = mean)
end
Expand All @@ -548,7 +548,7 @@ function to_unidirected(g::GNNGraph{<:COO_T})
g = GNNGraph((snew, tnew, w),
g.num_nodes, g.num_edges, g.num_graphs,
g.graph_indicator,
g.ndata, g.edata, g.gdata)
g.ndata, g.edata, g.gdata; graph_sizes = g.graph_sizes)

return coalesce(g; aggr = mean)
end
Expand Down Expand Up @@ -587,6 +587,91 @@ function add_nodes(g::GNNGraph{<:COO_T}, n::Integer; ndata = (;))
ndata, g.edata, g.gdata)
end

"""
pad_graph(g::GNNGraph, num_nodes, num_edges, num_graphs = g.num_graphs + 1)

Pad `g` to exactly `num_nodes` nodes, `num_edges` edges and `num_graphs` graphs.

All padding nodes and edges are put in one extra graph, appended after the graphs of `g`.
The padding edges are self-loops on the first padding node. Empty graphs are then
appended until there are `num_graphs` graphs. Node, edge and graph features, and edge
weights, are padded with zeros.

Padding every mini-batch to the same size lets a compiler like Reactant.jl compile a
model, or a training step, once and reuse it for all batches. The original graphs are
the first `g.num_graphs` ones: mask out the others, e.g. in the loss. A compiled function
raises an error when called on a graph padded to different sizes, including a different
number of graphs.

Requires `num_graphs > g.num_graphs`, and `num_nodes > g.num_nodes` if edges are added.

# Examples

```jldoctest
julia> g = MLUtils.batch([rand_graph(3, 4), rand_graph(5, 6)])
GNNGraph:
num_nodes: 8
num_edges: 10
num_graphs: 2

julia> gp = pad_graph(g, 10, 12, 4)
GNNGraph:
num_nodes: 10
num_edges: 12
num_graphs: 4

julia> graph_indicator(gp)
10-element Vector{Int64}:
1
1
1
2
2
2
2
2
3
3
```
"""
function pad_graph(g::GNNGraph{<:COO_T}, num_nodes::Integer, num_edges::Integer,
num_graphs::Integer = g.num_graphs + 1)
npad = num_nodes - g.num_nodes
epad = num_edges - g.num_edges
gpad = num_graphs - g.num_graphs
npad >= 0 ||
throw(ArgumentError("cannot pad a graph with $(g.num_nodes) nodes to $num_nodes nodes"))
epad >= 0 ||
throw(ArgumentError("cannot pad a graph with $(g.num_edges) edges to $num_edges edges"))
gpad >= 1 ||
throw(ArgumentError("`num_graphs` must exceed the $(g.num_graphs) graphs of `g`, to make room for the padding graph"))
(epad == 0 || npad >= 1) ||
throw(ArgumentError("padding edges need at least one padding node: `num_nodes` must exceed $(g.num_nodes)"))

s, t, w = edge_index(g)..., get_edge_weight(g)
s = vcat(s, fill_like(s, g.num_nodes + 1, epad))
t = vcat(t, fill_like(t, g.num_nodes + 1, epad))
w = isnothing(w) ? nothing : vcat(w, zeros_like(w, epad))
gi = graph_indicator(g)
gi = vcat(gi, fill_like(gi, g.num_graphs + 1, npad))

return GNNGraph((s, t, w),
num_nodes, num_edges, num_graphs,
gi,
_pad_features(g.ndata, npad),
_pad_features(g.edata, epad),
_pad_features(g.gdata, gpad))
end

function _pad_features(ds::DataStore, n::Integer)
n0 = getn(ds) >= 0 ? getn(ds) : 1
return DataStore(n0 + n, Dict{Symbol, Any}(k => _pad_features(x, n) for (k, x) in ds))
end

function _pad_features(x::AbstractArray, n::Integer)
return cat(x, fill!(similar(x, size(x)[1:(end - 1)]..., n), 0); dims = ndims(x))
end

"""
set_edge_weight(g::GNNGraph, w::AbstractVector)

Expand All @@ -600,7 +685,7 @@ function set_edge_weight(g::GNNGraph, w::AbstractVector)
return GNNGraph((s, t, w),
g.num_nodes, g.num_edges, g.num_graphs,
g.graph_indicator,
g.ndata, g.edata, g.gdata)
g.ndata, g.edata, g.gdata; graph_sizes = g.graph_sizes)
end

function SparseArrays.blockdiag(g1::GNNGraph, g2::GNNGraph)
Expand Down Expand Up @@ -1099,5 +1184,5 @@ function ppr_diffusion(g::GNNGraph{<:COO_T}; alpha = 0.85f0)
return GNNGraph((s, t, new_w),
g.num_nodes, length(s), g.num_graphs,
g.graph_indicator,
g.ndata, g.edata, g.gdata)
g.ndata, g.edata, g.gdata; graph_sizes = g.graph_sizes)
end
30 changes: 30 additions & 0 deletions GNNGraphs/test/gnngraph.jl
Original file line number Diff line number Diff line change
Expand Up @@ -434,6 +434,36 @@ end
end
end

@testitem "graph_sizes" setup=[GraphsTestModule] begin
using .GraphsTestModule
@test rand_graph(3, 4).graph_sizes === nothing
for GRAPH_T in GRAPH_TYPES
g = MLUtils.batch([rand_graph(n, m, graph_type = GRAPH_T) for (n, m) in [(3, 4), (5, 6)]])
@test g.graph_sizes == [3, 5]
@test add_self_loops(g).graph_sizes == [3, 5]
@test GNNGraph(g, ndata = rand(2, 8)).graph_sizes == [3, 5]
@test copy(g, deep = true).graph_sizes == [3, 5]
@test getgraph(g, 2).graph_sizes == [5]
end
g = MLUtils.batch([rand_graph(3, 4), rand_graph(5, 6)])
@test pad_graph(g, 10, 12, 4).graph_sizes == [3, 5, 2, 0]
# the nodes of a graph need not be contiguous
g = GNNGraph([1, 2, 3], [2, 3, 4], graph_indicator = [1, 2, 1, 2])
@test g.graph_sizes == [2, 2]
end

@testitem "graph_sizes GPU" setup=[GraphsTestModule] tags=[:gpu] begin
using .GraphsTestModule
dev = gpu_device(force=true)
gs = [rand_graph(3, 4), rand_graph(5, 6)]
g = MLUtils.batch(dev.(gs))
@test get_device(g.graph_sizes) isa AbstractGPUDevice
@test Array(g.graph_sizes) == [3, 5]
@test Array(dev(MLUtils.batch(gs)).graph_sizes) == [3, 5]
@test Array(add_self_loops(g).graph_sizes) == [3, 5]
@test Array(pad_graph(g, 10, 12, 4).graph_sizes) == [3, 5, 2, 0]
end

@testitem "show" begin
# no throw when global data is not an array
g = rand_graph(10, 20, gdata = "ciao")
Expand Down
Loading