Repository: pyg-team/pytorch_geometric
Pull request: Add extra condition to `GraphUNet` edge weights assert
Closes #9741.

This PR adds an extra condition to the assert to ensure that the user-given edge weights are a 1D vector. 2D matrices make the adjacency matrix multiplication fail as described in the issue above.

Problem statement:
GraphUNet adjacency - matrix RuntimeError: expand is unsupported for SparseCsr tensors
### 🐛 Describe the bug

It looks like the adjacency matrix cannot be multiplied by itself because it is a sparse tensor as opposed to when the edge weights aren't given and are given a one for all edges. Changing the tensor multiplication function used here should fix the issue, but I still haven't managed to make it work. I would really appreciate some help.

```python
  File "/home/eneko/GitHub/tmima/tmima/training/model.py", line 108, in forward
    x = self.down_convs[0](x, edge_index, edge_weight)
  File "/home/eneko/GitHub/tmima/tmima/training/model.py", line 117, in torch_dynamo_resume_in_forward_at_108
    edge_index, edge_weight = self.augment_adj(edge_index, edge_weight, x.size(0))
  File "/home/eneko/GitHub/tmima/tmima/training/model.py", line 149, in augment_adj
    edge_index, edge_weight = remove_self_loops(edge_index, edge_weight)
  File "/home/eneko/GitHub/tmima/tmima/training/model.py", line 151, in torch_dynamo_resume_in_augment_adj_at_149
    adj = to_torch_csr_tensor(edge_index, edge_weight, size=(num_nodes, num_nodes))
  File "/home/eneko/GitHub/tmima/tmima/training/model.py", line 152, in torch_dynamo_resume_in_augment_adj_at_151
    adj = (adj @ adj).to_sparse_coo()
RuntimeError: expand is unsupported for SparseCsr tensors
```

See how `edge_attr` is passed to the GraphUNet in the following example to reproduce:

```python
class GraphModel(torch.nn.Module):
    def __init__(self, config):
        super().__init__()
        self.config = config

        self.unet = GraphUNet(
            in_channels=1,
            hidden_channels=self.config["hidden_channels"],
            out_channels=2,
            depth=self.config["depth"],
            sum_res=True,
        )

    def forward(self, x, edge_index, edge_attr):
        x = self.unet(x, edge_index, edge_attr)
        x = softmax(x)
        return x
```

### Versions

```
PyTorch version: 2.5.0+cu124
Is debug build: False
CUDA used to build PyTorch: 12.4
ROCM used to build PyTorch: N/A

OS: Ubuntu 24.04.1 LTS (x86_64)
GCC version: (Ubuntu 13.2.0-23ubuntu4) 13.2.0
Clang version: Could not collect
CMake version: Could not collect
Libc version: glibc-2.39

Python version: 3.10.0 | packaged by conda-forge | (default, Nov 20 2021, 02:24:10) [GCC 9.4.0] (64-bit runtime)
Python platform: Linux-6.8.0-36-generic-x86_64-with-glibc2.39
Is CUDA available: True
CUDA runtime version: 12.0.140
CUDA_MODULE_LOADING set to: LAZY
GPU models and configuration: GPU 0: NVIDIA GeForce RTX 3090
Nvidia driver version: 550.100
cuDNN version: Could not collect
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:                        39 bits physical, 48 bits virtual
Byte Order:                           Little Endian
CPU(s):                               16
On-line CPU(s) list:                  0-15
Vendor ID:                            GenuineIntel
Model name:                           11th Gen Intel(R) Core(TM) i7-11700KF @ 3.60GHz
CPU family:                           6
Model:                                167
Thread(s) per core:                   2
Core(s) per socket:                   8
Socket(s):                            1
Stepping:                             1
CPU(s) scaling MHz:                   34%
CPU max MHz:                          5000.0000
CPU min MHz:                          800.0000
BogoMIPS:                             7200.00
Flags:                                fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc art arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc cpuid aperfmperf tsc_known_freq pni pclmulqdq dtes64 monitor ds_cpl vmx est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch cpuid_fault epb ssbd ibrs ibpb stibp ibrs_enhanced tpr_shadow flexpriority ept vpid ept_ad fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid mpx avx512f avx512dq rdseed adx smap avx512ifma clflushopt intel_pt avx512cd sha_ni avx512bw avx512vl xsaveopt xsavec xgetbv1 xsaves dtherm ida arat pln pts hwp hwp_notify hwp_act_window hwp_epp hwp_pkg_req vnmi avx512vbmi umip pku ospke avx512_vbmi2 gfni vaes vpclmulqdq avx512_vnni avx512_bitalg avx512_vpopcntdq rdpid fsrm md_clear flush_l1d arch_capabilities
Virtualization:                       VT-x
L1d cache:                            384 KiB (8 instances)
L1i cache:                            256 KiB (8 instances)
L2 cache:                             4 MiB (8 instances)
L3 cache:                             16 MiB (1 instance)
NUMA node(s):                         1
NUMA node0 CPU(s):                    0-15
Vulnerability Gather data sampling:   Mitigation; Microcode
Vulnerability Itlb multihit:          Not affected
Vulnerability L1tf:                   Not affected
Vulnerability Mds:                    Not affected
Vulnerability Meltdown:               Not affected
Vulnerability Mmio stale data:        Mitigation; Clear CPU buffers; SMT vulnerable
Vulnerability Reg file data sampling: Not affected
Vulnerability Retbleed:               Mitigation; Enhanced IBRS
Vulnerability Spec rstack overflow:   Not affected
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; Enhanced / Automatic IBRS; IBPB conditional; RSB filling; PBRSB-eIBRS SW sequence; BHI Syscall hardening, KVM SW loop
Vulnerability Srbds:                  Not affected
Vulnerability Tsx async abort:        Not affected

Versions of relevant libraries:
[pip3] flake8==7.1.1
[pip3] flake8-absolute-import==1.0.0.2
[pip3] flake8-black==0.3.6
[pip3] flake8-docstrings==1.7.0
[pip3] flake8-isort==6.1.1
[pip3] flake8-unused-arguments==0.0.13
[pip3] flake8-use-fstring==1.4
[pip3] mypy-extensions==1.0.0
[pip3] numpy==1.26.4
[pip3] nvidia-cublas-cu12==12.4.5.8
[pip3] nvidia-cuda-cupti-cu12==12.4.127
[pip3] nvidia-cuda-nvrtc-cu12==12.4.127
[pip3] nvidia-cuda-runtime-cu12==12.4.127
[pip3] nvidia-cudnn-cu12==9.1.0.70
[pip3] nvidia-cufft-cu12==11.2.1.3
[pip3] nvidia-curand-cu12==10.3.5.147
[pip3] nvidia-cusolver-cu12==11.6.1.9
[pip3] nvidia-cusparse-cu12==12.3.1.170
[pip3] nvidia-nccl-cu12==2.21.5
[pip3] nvidia-nvjitlink-cu12==12.4.127
[pip3] nvidia-nvtx-cu12==12.4.127
[pip3] torch==2.5.0
[pip3] torch_cluster==1.6.3
[pip3] torch-geometric==2.6.1
[pip3] triton==3.1.0
[conda] numpy                     1.26.4                   pypi_0    pypi
[conda] nvidia-cublas-cu12        12.4.5.8                 pypi_0    pypi
[conda] nvidia-cuda-cupti-cu12    12.4.127                 pypi_0    pypi
[conda] nvidia-cuda-nvrtc-cu12    12.4.127                 pypi_0    pypi
[conda] nvidia-cuda-runtime-cu12  12.4.127                 pypi_0    pypi
[conda] nvidia-cudnn-cu12         9.1.0.70                 pypi_0    pypi
[conda] nvidia-cufft-cu12         11.2.1.3                 pypi_0    pypi
[conda] nvidia-curand-cu12        10.3.5.147               pypi_0    pypi
[conda] nvidia-cusolver-cu12      11.6.1.9                 pypi_0    pypi
[conda] nvidia-cusparse-cu12      12.3.1.170               pypi_0    pypi
[conda] nvidia-nccl-cu12          2.21.5                   pypi_0    pypi
[conda] nvidia-nvjitlink-cu12     12.4.127                 pypi_0    pypi
[conda] nvidia-nvtx-cu12          12.4.127                 pypi_0    pypi
[conda] torch                     2.5.0                    pypi_0    pypi
[conda] torch-cluster             1.6.3                    pypi_0    pypi
[conda] torch-geometric           2.6.1                    pypi_0    pypi
[conda] triton                    3.1.0                    pypi_0    pypi
```

Hints from issue discussion:

Commit message: [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

Patch to review:
diff --git a/torch_geometric/nn/models/graph_unet.py b/torch_geometric/nn/models/graph_unet.py
index b345dcf8324c..2972ba65faa8 100644
--- a/torch_geometric/nn/models/graph_unet.py
+++ b/torch_geometric/nn/models/graph_unet.py
@@ -92,7 +92,8 @@ def forward(
 
         if edge_weight is None:
             edge_weight = x.new_ones(edge_index.size(1))
-        assert edge_weight.size(0) == edge_index.size(1)
+        assert edge_weight.dim() == 1 and edge_weight.size(
+            0) == edge_index.size(1)
 
         x = self.down_convs[0](x, edge_index, edge_weight)
         x = self.act(x)


Code review comments:
diff_hunk: @@ -92,7 +92,8 @@ def forward(
 
         if edge_weight is None:
             edge_weight = x.new_ones(edge_index.size(1))
-        assert edge_weight.size(0) == edge_index.size(1)
+        assert edge_weight.dim() == 1 and edge_weight.size(
+            0) == edge_index.size(1)
path: torch_geometric/nn/models/graph_unet.py
text: @user1:
```suggestion
        assert edge_weight.dim() == 1
        assert edge_weight.size(0) == edge_index.size(1)
```