Skip to content

to_dense_adj fails when the nodes are not ordered by batch #10534

@jesseangelis

Description

@jesseangelis

🐛 Describe the bug

The function to_dense_adj incorrectly calculates the relative node indices (idx1, idx2) when the input node indices referred to in the edge_index are not sorted by their batch.

The logic for calculating the local node index relies on subtracting the cumulative node count for that batch: idx = node_index - cum_nodes[batch_id]. This subtraction only yields the correct local index if the input node indices are already sorted by batch. When the batch is unsorted, this results in false relative indices, causing the resulting dense adjacency matrix to be incorrect.

Reproducible Example:

from torch
from torch_geometric.utils import to_dense_adj

edge_index = torch.tensor([
    [0, 1, 2, 3],
    [3, 2, 1, 0],
])
batch = torch.tensor([0, 1, 1, 0])
adj = to_dense_adj(edge_index, batch)
print(adj)

# Returns:  tensor([[[0., 0.], [1., 2.]], [[0., 0.], [1., 0.]]])
# Should be:  tensor([[[0., 1.], [1., 0.]], [[0., 1.], [1., 0.]]])


edge_index = torch.tensor([
    [0, 1, 2, 3],
    [3, 2, 1, 0],
])
batch = torch.tensor([0, 1, 1, 0])
edge_attr = torch.tensor([1.0, 3.0, 4.0, 2.0])
adj = to_dense_adj(edge_index, batch, edge_attr)
print(adj)

# Returns:  tensor([[[0., 0.], [3., 5.]],[[0., 0.],[2., 0.]]])
# Should be:  tensor([[[0., 1.], [2., 0.]], [[0., 3.], [4., 0.]]])

Proposed Fix:
The issue can be resolved by explicitly sorting the nodes according to their batch assignment and updating the edge_index to reference the new, sorted node indices before calculating the cumulative sums and relative indices.

The following lines should be inserted after the batch size is determined:

# Ensure the batch is sorted and update edge_index to reflect the new node order:
perm = batch.argsort()
batch = batch[perm]
# Create a map from old index to new, sorted index
new_index_map = torch.empty_like(perm)
new_index_map[perm] = torch.arange(perm.size(0))
# Apply the new index map to the edge indices
edge_index = new_index_map[edge_index]

I will open a PR with this fix implemented.

Versions

PyTorch version: 2.9.1+cpu
Is debug build: False
CUDA used to build PyTorch: None
ROCM used to build PyTorch: N/A

OS: Ubuntu 24.04.2 LTS (x86_64)
GCC version: (Ubuntu 13.3.0-6ubuntu2~24.04) 13.3.0
Clang version: Could not collect
CMake version: Could not collect
Libc version: glibc-2.39

Python version: 3.12.3 (main, Aug 14 2025, 17:47:21) [GCC 13.3.0] (64-bit runtime)
Python platform: Linux-6.8.0-52-generic-x86_64-with-glibc2.39
Is CUDA available: False
CUDA runtime version: No CUDA
CUDA_MODULE_LOADING set to: N/A
GPU models and configuration: No CUDA
Nvidia driver version: No CUDA
cuDNN version: No CUDA
Is XPU available: False
HIP runtime version: N/A
MIOpen runtime version: N/A
Is XNNPACK available: True

CPU:
Architecture: x86_64
CPU op-mode(s): 32-bit, 64-bit
Address sizes: 48 bits physical, 48 bits virtual
Byte Order: Little Endian
CPU(s): 12
On-line CPU(s) list: 0-11
Vendor ID: AuthenticAMD
Model name: AMD Ryzen 5 7530U with Radeon Graphics
CPU family: 25
Model: 80
Thread(s) per core: 2
Core(s) per socket: 6
Socket(s): 1
Stepping: 0
CPU(s) scaling MHz: 80%
CPU max MHz: 4546.0000
CPU min MHz: 400.0000
BogoMIPS: 3992.53
Flags: fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ht syscall nx mmxext fxsr_opt pdpe1gb rdtscp lm constant_tsc rep_good nopl nonstop_tsc cpuid extd_apicid aperfmperf rapl pni pclmulqdq monitor ssse3 fma cx16 sse4_1 sse4_2 movbe popcnt aes xsave avx f16c rdrand lahf_lm cmp_legacy svm extapic cr8_legacy abm sse4a misalignsse 3dnowprefetch osvw ibs skinit wdt tce topoext perfctr_core perfctr_nb bpext perfctr_llc mwaitx cpb cat_l3 cdp_l3 hw_pstate ssbd mba ibrs ibpb stibp vmmcall fsgsbase bmi1 avx2 smep bmi2 erms invpcid cqm rdt_a rdseed adx smap clflushopt clwb sha_ni xsaveopt xsavec xgetbv1 xsaves cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local user_shstk clzero irperf xsaveerptr rdpru wbnoinvd cppc arat npt lbrv svm_lock nrip_save tsc_scale vmcb_clean flushbyasid decodeassists pausefilter pfthreshold avic v_vmsave_vmload vgif v_spec_ctrl umip pku ospke vaes vpclmulqdq rdpid overflow_recov succor smca fsrm debug_swap
Virtualization: AMD-V
L1d cache: 192 KiB (6 instances)
L1i cache: 192 KiB (6 instances)
L2 cache: 3 MiB (6 instances)
L3 cache: 16 MiB (1 instance)
NUMA node(s): 1
NUMA node0 CPU(s): 0-11
Vulnerability Gather data sampling: Not affected
Vulnerability Itlb multihit: Not affected
Vulnerability L1tf: Not affected
Vulnerability Mds: Not affected
Vulnerability Meltdown: Not affected
Vulnerability Mmio stale data: Not affected
Vulnerability Reg file data sampling: Not affected
Vulnerability Retbleed: Not affected
Vulnerability Spec rstack overflow: Vulnerable: Safe RET, no microcode
Vulnerability Spec store bypass: Mitigation; Speculative Store Bypass disabled via prctl
Vulnerability Spectre v1: Mitigation; usercopy/swapgs barriers and __user pointer sanitization
Vulnerability Spectre v2: Mitigation; Retpolines; IBPB conditional; IBRS_FW; STIBP always-on; RSB filling; PBRSB-eIBRS Not affected; BHI Not affected
Vulnerability Srbds: Not affected
Vulnerability Tsx async abort: Not affected

Versions of relevant libraries:
[pip3] numpy==1.26.4
[pip3] onnx==1.17.0
[pip3] onnx-ir==0.1.12
[pip3] onnxruntime==1.23.2
[pip3] onnxscript==0.5.6
[pip3] pytorch-lightning==2.5.6
[pip3] pytorch-memlab==0.3.0
[pip3] torch==2.9.1+cpu
[pip3] torch-geometric==2.8.0
[pip3] torchmetrics==1.8.2
[conda] blas 1.0 mkl
[conda] intel-openmp 2022.0.1 h06a4308_3633
[conda] mkl 2023.2.0 h84fe81f_50496 conda-forge
[conda] mkl-service 2.4.0 py312h5eee18b_1
[conda] mkl_fft 1.3.8 py312h5eee18b_0
[conda] mkl_random 1.2.4 py312hdb19cb5_0
[conda] numpy 1.26.4 py312hc5e2394_0
[conda] numpy-base 1.26.4 py312h0da6c21_0
[conda] nvidia-cublas-cu12 12.8.4.1 pypi_0 pypi
[conda] nvidia-cuda-cupti-cu12 12.8.90 pypi_0 pypi
[conda] nvidia-cuda-nvrtc-cu12 12.8.93 pypi_0 pypi
[conda] nvidia-cuda-runtime-cu12 12.8.90 pypi_0 pypi
[conda] nvidia-cudnn-cu12 9.10.2.21 pypi_0 pypi
[conda] nvidia-cufft-cu12 11.3.3.83 pypi_0 pypi
[conda] nvidia-curand-cu12 10.3.9.90 pypi_0 pypi
[conda] nvidia-cusolver-cu12 11.7.3.90 pypi_0 pypi
[conda] nvidia-cusparse-cu12 12.5.8.93 pypi_0 pypi
[conda] nvidia-cusparselt-cu12 0.7.1 pypi_0 pypi
[conda] nvidia-nccl-cu12 2.27.3 pypi_0 pypi
[conda] nvidia-nvjitlink-cu12 12.8.93 pypi_0 pypi
[conda] nvidia-nvtx-cu12 12.8.90 pypi_0 pypi
[conda] tbb 2021.8.0 hdb19cb5_0
[conda] torch 2.8.0 pypi_0 pypi
[conda] triton 3.4.0 pypi_0 pypi

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions