Skip to content

Make add_self_loops differentiable wrt edge weights - #750

Merged
CarloLucibello merged 1 commit into
masterfrom
cl/add-self-loops-grad
Nov 29, 2026
Merged

CarloLucibello merged 1 commit into
masterfrom
cl/add-self-loops-grad

Conversation

@CarloLucibello

Copy link
Copy Markdown
Member

add_self_loops was marked @non_differentiable (and had a matching @zero_derivative rule in the Mooncake extension). As a result, layers that add self loops by default (GCNConv, SGConv, TAGConv with use_edge_weight = true) silently returned a nothing gradient for edge weights stored in the graph, with both Zygote and Mooncake.

Now only the edge-index computation (_add_self_loops_index) is excluded from AD, so gradients reach the edge weights of COO graphs and the adjacency matrix of dense/sparse graphs. For Mooncake, A + I on adjacency-matrix graphs moves into a helper with its own rules (zero derivative for integer matrices, identity pullback for dense float matrices), since Mooncake can't trace the GPU kernel. The GNNHeteroGraph method stays non-differentiable for now.

User-facing change (GNNGraphs): add_self_loops is differentiable w.r.t. edge weights, so edge weights stored in the graph can be trained through GCNConv, SGConv and TAGConv with the default add_self_loops = true.

Tests compare Zygote and Mooncake against finite differences for the three layers, and check add_self_loops directly on COO and dense graphs, CPU and CUDA. The new tests fail on master.

Supersedes #738. Related to #443.

🧔‍♂️🤖 Assisted by Claude Sonnet 5.5

`add_self_loops` was marked non-differentiable, so the gradient of edge weights
stored in the graph was silently dropped by layers that add self loops by default
(GCNConv, SGConv, TAGConv with `use_edge_weight = true`), for both Zygote and Mooncake.
Only the edge index computation is now excluded from AD.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
@CarloLucibello
CarloLucibello merged commit 6a9ec35 into master Nov 29, 2026
10 of 11 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant