Skip to content

Commit 3d96eae

Browse files
Fix GPU scalar indexing in remove_edges and getgraph (#691)
* Fix GPU scalar indexing in remove_edges and getgraph remove_edges (#668): the follow-up to #672 built the keep-mask with `fill_like(edges_to_remove, true)`, which produced a mask of the wrong length (that of `edges_to_remove`, not the number of edges) and wrong eltype (Int instead of Bool) — breaking even the existing CPU tests. Build the mask from `s` with `fill_like(s, true, Bool, length(s))` so it lives on the graph's device and does logical indexing correctly. getgraph (#161): the subgraph extraction uses scalar Dict lookups and comprehensions that can't run on the GPU. Detect a non-CPU device, run the extraction on the CPU, and move the result back to the original device. Also restores the indentation of the commented add_snapshot!/ remove_snapshot! exports mangled by #672, and adds :gpu-tagged regression tests for both functions. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * Reference PR #691 in the changelog entries Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * Make getgraph GPU-native for COO graphs instead of CPU round-trip The first cut fixed getgraph on the GPU by moving the graph to the CPU and back. That works but forces a full device<->host sync and its cost grows with the graph size. Instead, express the COO path (the common case, which has a dense graph_indicator) entirely with scatter/gather/cumsum, which run natively on the GPU: build the node keep-mask from a per-graph boolean lookup, relabel nodes via cumsum and graphs via a scatter, and select edges with `node_mask[s]`. Indexing goes through the integer vectors `kept_nodes`/`kept_edges` (one `findall` each) rather than repeated boolean masks, to keep the number of GPU synchronizations low. Adjacency-matrix graphs still fall back to the CPU: they need submatrix indexing and store `graph_indicator` as a `SparseVector`, neither of which is GPU-friendly. The result stays on the original device and, on real hardware, avoids the host transfer entirely; on large batches it is dramatically faster than the round-trip. The GPU test now covers all graph types (COO native + sparse/dense fallback), node/edge features, weights, and `nmap`. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * docs(AGENTS): document running and reproducing GPU tests Add a local CUDA test command and note the cuDNN / allowscalar(false) setup needed to reproduce a :gpu test item in the REPL — the gotcha being that gpu_device() silently falls back to the CPU when cuDNN isn't loaded. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
1 parent be0253d commit 3d96eae

5 files changed

Lines changed: 128 additions & 30 deletions

File tree

‎AGENTS.md‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,11 @@ Julia ≥ 1.10 is required (some tests, e.g. Mooncake, need ≥ 1.12). Thanks to
3131
julia --project=GraphNeuralNetworks -e 'using Pkg; Pkg.test("GraphNeuralNetworks")'
3232
julia --project=GNNGraphs -e 'using Pkg; Pkg.test("GNNGraphs")'
3333

34+
# Run only the :gpu-tagged items on CUDA (works locally on a CUDA machine, not
35+
# just in CI). The test harness auto-installs the backend (CUDA + cuDNN) and sets
36+
# allowscalar(false); swap in GNN_TEST_AMDGPU / GNN_TEST_Metal for other backends.
37+
GNN_TEST_CPU=false GNN_TEST_CUDA=true julia --project=GNNGraphs -e 'using Pkg; Pkg.test("GNNGraphs")'
38+
3439
# Build docs for one package
3540
julia --project=GNNGraphs/docs GNNGraphs/docs/make.jl
3641

@@ -42,7 +47,8 @@ julia -e 'using JuliaFormatter; format(".")'
4247
Test files define independent `@testitem "..." setup=[TestModule] begin ... end` blocks. `runtests.jl` in each package just calls `@run_package_tests` with a tag filter. Shared fixtures and exports live in each package's `test/test_module.jl` (`TestModule`).
4348

4449
- **Run a single test item**: use the VS Code Julia extension's test-item UI, or filter in `runtests.jl`. Test items are self-contained, so you can also copy one into a REPL after `include("test/test_module.jl")`.
45-
- **GPU tests** are tagged `:gpu`; untagged items are CPU tests. Backend selection is via env vars read in `runtests.jl` and `test_module.jl`: `GNN_TEST_CPU` (default `"true"`), `GNN_TEST_CUDA`, `GNN_TEST_AMDGPU`, `GNN_TEST_Metal`. CPU CI runs untagged items; GPU CI (Buildkite, `.buildkite/pipeline.yml`) sets `GNN_TEST_CPU=false` and a backend var to `true`.
50+
- **GPU tests** are tagged `:gpu`; untagged items are CPU tests. Backend selection is via env vars read in `runtests.jl` and `test_module.jl`: `GNN_TEST_CPU` (default `"true"`), `GNN_TEST_CUDA`, `GNN_TEST_AMDGPU`, `GNN_TEST_Metal`. CPU CI runs untagged items; GPU CI (Buildkite, `.buildkite/pipeline.yml`) sets `GNN_TEST_CPU=false` and a backend var to `true`. `test_module.jl` `Pkg.add`s the backend on demand, so it need not be in `test/Project.toml`.
51+
- **Exercise a `:gpu` item in the REPL**: inside a `@testitem`, `dev = gpu_device(force=true)` and helpers like `AbstractGPUDevice` come from the package's test-module setup (`GraphsTestModule` in GNNGraphs). To reproduce the same environment interactively, load the backend the way the harness does — for CUDA that means `using CUDA, cuDNN` (**cuDNN is required**; without it `gpu_device()` reports "no functional GPU backend" and silently falls back to the CPU) — then set `CUDA.allowscalar(false)` so any accidental scalar indexing errors instead of running slowly (this is what catches most GPU regressions, e.g. graph ops that materialize a CPU mask).
4652

4753
## Adding a new convolutional layer
4854

‎CHANGELOG.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,8 @@ Entries link to the pull request that introduced them.
2626
- Bumped the NNlib and KrylovKit compat bounds ([#687], [#680]).
2727

2828
**Fixed**
29+
- Fixed `remove_edges` triggering scalar indexing on GPU graphs ([#672], [#691]).
30+
- Fixed `getgraph` failing on GPU graphs ([#691]).
2931
- Fixed `remove_self_loops` mutating the input for adjacency-matrix graphs ([#659]).
3032
- Fixed `unbatch` for COO batches containing zero-edge graphs ([#652]).
3133
- Fixed `sample_nbrs` when sampling without replacement ([#648]).
@@ -181,6 +183,7 @@ Lux implementations of the graph convolutional, pooling, and temporal layers
181183
[#652]: https://github.com/JuliaGraphs/GraphNeuralNetworks.jl/pull/652
182184
[#659]: https://github.com/JuliaGraphs/GraphNeuralNetworks.jl/pull/659
183185
[#670]: https://github.com/JuliaGraphs/GraphNeuralNetworks.jl/pull/670
186+
[#672]: https://github.com/JuliaGraphs/GraphNeuralNetworks.jl/pull/672
184187
[#677]: https://github.com/JuliaGraphs/GraphNeuralNetworks.jl/pull/677
185188
[#678]: https://github.com/JuliaGraphs/GraphNeuralNetworks.jl/pull/678
186189
[#679]: https://github.com/JuliaGraphs/GraphNeuralNetworks.jl/pull/679
@@ -190,3 +193,4 @@ Lux implementations of the graph convolutional, pooling, and temporal layers
190193
[#686]: https://github.com/JuliaGraphs/GraphNeuralNetworks.jl/pull/686
191194
[#687]: https://github.com/JuliaGraphs/GraphNeuralNetworks.jl/pull/687
192195
[#690]: https://github.com/JuliaGraphs/GraphNeuralNetworks.jl/pull/690
196+
[#691]: https://github.com/JuliaGraphs/GraphNeuralNetworks.jl/pull/691

‎GNNGraphs/src/GNNGraphs.jl‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -38,9 +38,9 @@ export GNNHeteroGraph,
3838
include("temporalsnapshotsgnngraph.jl")
3939
export TemporalSnapshotsGNNGraph,
4040
add_snapshot,
41-
# add_snapshot!,
41+
# add_snapshot!,
4242
remove_snapshot
43-
# remove_snapshot!
43+
# remove_snapshot!
4444

4545
include("query.jl")
4646
include("gnnheterograph/query.jl")

‎GNNGraphs/src/transform.jl‎

Lines changed: 56 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -123,9 +123,10 @@ function remove_edges(g::GNNGraph{<:COO_T}, edges_to_remove::AbstractVector{<:In
123123
w = get_edge_weight(g)
124124
edata = g.edata
125125

126-
# mask_to_keep = trues(length(s))
127-
mask_to_keep = MLUtils.fill_like(edges_to_remove, true)
128-
126+
# Build the keep-mask on the same device as the graph (see #668): a plain
127+
# `trues(length(s))` lives on the CPU and forces scalar indexing when `s`
128+
# and `edges_to_remove` are on the GPU.
129+
mask_to_keep = fill_like(s, true, Bool, length(s))
129130
mask_to_keep[edges_to_remove] .= false
130131

131132
s = s[mask_to_keep]
@@ -833,42 +834,71 @@ function getgraph(g::GNNGraph, i::AbstractVector{Int}; nmap = false)
833834
end
834835
end
835836

836-
node_mask = g.graph_indicator .∈ Ref(i)
837+
# Adjacency-matrix graphs need submatrix indexing (and store `graph_indicator`
838+
# as a `SparseVector`), neither of which is GPU-friendly, so subgraph them on
839+
# the CPU with the index-map implementation below (#161).
840+
if g.graph isa ADJMAT_T
841+
dev = get_device(g)
842+
if !(dev isa CPUDevice)
843+
res = getgraph(cpu_device()(g), i; nmap)
844+
return nmap ? (dev(res[1]), dev(res[2])) : dev(res)
845+
end
846+
847+
node_mask = g.graph_indicator .∈ Ref(i)
848+
nodes = (1:(g.num_nodes))[node_mask]
849+
graphmap = Dict(v => inew for (inew, v) in enumerate(i))
850+
graph_indicator = [graphmap[v] for v in g.graph_indicator[node_mask]]
837851

838-
nodes = (1:(g.num_nodes))[node_mask]
839-
nodemap = Dict(v => vnew for (vnew, v) in enumerate(nodes))
852+
s, t = edge_index(g)
853+
edge_mask = s .∈ Ref(nodes)
854+
graph = g.graph[nodes, nodes]
840855

841-
graphmap = Dict(i => inew for (inew, i) in enumerate(i))
842-
graph_indicator = [graphmap[i] for i in g.graph_indicator[node_mask]]
856+
ndata = getobs(g.ndata, node_mask)
857+
edata = getobs(g.edata, edge_mask)
858+
gdata = getobs(g.gdata, i)
859+
gnew = GNNGraph(graph,
860+
length(graph_indicator), sum(edge_mask), length(i),
861+
graph_indicator, ndata, edata, gdata)
862+
return nmap ? (gnew, nodes) : gnew
863+
end
864+
865+
# COO graphs (the common case) have a dense `graph_indicator`, so the whole
866+
# routine can be written with gather/scatter/cumsum and run natively on the
867+
# GPU, unlike the earlier `∈`/`Dict` version that forced scalar indexing (#161).
868+
# We index with the integer vectors `kept_nodes`/`kept_edges` (one `findall`
869+
# each) instead of reusing boolean masks, to keep the number of GPU syncs low.
870+
gi = g.graph_indicator
871+
idev = get_device(gi)(i) # selected graph ids, on gi's device
872+
873+
keep_graph = fill_like(gi, false, Bool, g.num_graphs)
874+
keep_graph[idev] .= true
875+
node_mask = keep_graph[gi] # true for nodes of the selected graphs
876+
kept_nodes = findall(node_mask) # new node id -> old node id
877+
new_node_id = cumsum(node_mask) # old node id -> new node id
878+
879+
graphmap = fill_like(gi, 0, Int, g.num_graphs)
880+
graphmap[idev] = 1:length(i) # old graph id -> new graph id
881+
graph_indicator = graphmap[gi[kept_nodes]]
843882

844883
s, t = edge_index(g)
845884
w = get_edge_weight(g)
846-
edge_mask = s .∈ Ref(nodes)
885+
kept_edges = findall(node_mask[s]) # edges kept iff their endpoints are
847886

848-
if g.graph isa COO_T
849-
s = [nodemap[i] for i in s[edge_mask]]
850-
t = [nodemap[i] for i in t[edge_mask]]
851-
w = isnothing(w) ? nothing : w[edge_mask]
852-
graph = (s, t, w)
853-
elseif g.graph isa ADJMAT_T
854-
graph = g.graph[nodes, nodes]
855-
end
887+
s = new_node_id[s[kept_edges]]
888+
t = new_node_id[t[kept_edges]]
889+
w = isnothing(w) ? nothing : w[kept_edges]
856890

857-
ndata = getobs(g.ndata, node_mask)
858-
edata = getobs(g.edata, edge_mask)
891+
ndata = getobs(g.ndata, kept_nodes)
892+
edata = getobs(g.edata, kept_edges)
859893
gdata = getobs(g.gdata, i)
860894

861-
num_edges = sum(edge_mask)
862-
num_nodes = length(graph_indicator)
863-
num_graphs = length(i)
864-
865-
gnew = GNNGraph(graph,
866-
num_nodes, num_edges, num_graphs,
895+
gnew = GNNGraph((s, t, w),
896+
length(kept_nodes), length(kept_edges), length(i),
867897
graph_indicator,
868898
ndata, edata, gdata)
869899

870900
if nmap
871-
return gnew, nodes
901+
return gnew, kept_nodes
872902
else
873903
return gnew
874904
end

‎GNNGraphs/test/transform.jl‎

Lines changed: 59 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -149,7 +149,39 @@ end
149149
g1b, nodemap = getgraph(g1, 1, nmap = true)
150150
@test g1b === g1
151151
@test nodemap == 1:(g1.num_nodes)
152-
end
152+
end
153+
end
154+
155+
@testitem "getgraph GPU" setup=[GraphsTestModule] tags=[:gpu] begin
156+
using .GraphsTestModule
157+
dev = gpu_device(force=true)
158+
159+
# COO graphs are handled natively on the GPU; adjacency-matrix graphs fall
160+
# back to the CPU. Check both against the CPU reference (see #161).
161+
for GRAPH_T in GRAPH_TYPES
162+
gl = [GNNGraph(random_regular_graph(n, 2), ndata = rand(Float32, 4, n),
163+
graph_type = GRAPH_T) for n in [10, 4, 8, 6]]
164+
gl = [GNNGraph(g0, edata = rand(Float32, 2, g0.num_edges)) for g0 in gl]
165+
g = MLUtils.batch(gl)
166+
g_gpu = g |> dev
167+
168+
for (i, want_nmap) in [(2, false), ([1, 3], true), ([2, 3, 4], true)]
169+
ref = getgraph(g, i; nmap = want_nmap)
170+
res = getgraph(g_gpu, i; nmap = want_nmap)
171+
rg, ng = want_nmap ? (ref[1], res[1]) : (ref, res)
172+
173+
@test ng isa GNNGraph{typeof(g_gpu.graph)} # graph type preserved
174+
@test get_device(ng.graph_indicator) isa AbstractGPUDevice
175+
@test ng.num_nodes == rg.num_nodes
176+
@test ng.num_edges == rg.num_edges
177+
@test Array(ng.graph_indicator) == rg.graph_indicator
178+
@test Array(edge_index(ng)[1]) == edge_index(rg)[1]
179+
@test Array(edge_index(ng)[2]) == edge_index(rg)[2]
180+
@test Array(node_features(ng)) ≈ node_features(rg)
181+
@test Array(edge_features(ng)) ≈ edge_features(rg)
182+
want_nmap && @test Array(res[2]) == ref[2]
183+
end
184+
end
153185
end
154186

155187
@testitem "remove_edges" setup=[GraphsTestModule] begin
@@ -190,6 +222,32 @@ end
190222
end
191223
end
192224

225+
@testitem "remove_edges GPU" setup=[GraphsTestModule] tags=[:gpu] begin
226+
using .GraphsTestModule
227+
dev = gpu_device(force=true)
228+
s = [1, 1, 2, 3]
229+
t = [2, 3, 4, 5]
230+
w = Float32[0.1, 0.2, 0.3, 0.4]
231+
g = GNNGraph((s, t, w), graph_type = :coo) |> dev
232+
233+
# index vector on the same device as the graph (see #668)
234+
gnew = remove_edges(g, dev([1, 2, 4]))
235+
@test gnew.num_edges == 1
236+
@test get_device(edge_index(gnew)[1]) isa AbstractGPUDevice
237+
@test Array(edge_index(gnew)[1]) == [2]
238+
@test Array(edge_index(gnew)[2]) == [4]
239+
@test Array(get_edge_weight(gnew)) == Float32[0.3]
240+
241+
# index vector on the CPU while the graph lives on the GPU
242+
gnew = remove_edges(g, [1, 2, 4])
243+
@test gnew.num_edges == 1
244+
@test Array(edge_index(gnew)[1]) == [2]
245+
246+
# probability overload
247+
@test remove_edges(g, 1.0f0).num_edges == 0
248+
@test remove_edges(g, 0.0f0).num_edges == g.num_edges
249+
end
250+
193251
@testitem "add_edges" setup=[GraphsTestModule] begin
194252
using .GraphsTestModule
195253
for GRAPH_T in GRAPH_TYPES

0 commit comments

Comments
 (0)