Skip to content

call dist.nn.all_reduce then compute loss with torch.logdet().sum() raise grad Tensors must be contiguous error #144060

@ultranity

Description

@ultranity

🐛 Describe the bug

BG: error when verifying #58005, where batch computations like torch.logdet and torch.sum will raise Error: grad Tensors must be contiguous error

repoduce code:

import torch
import torch.distributed as dist
import torch.distributed.nn
from functools import partial
def worker(gpu, USE_NN_REDUCE = 0):
    dist.init_process_group(
        backend="nccl", init_method="tcp://localhost:12345", world_size=2, rank=gpu
    )
    torch.cuda.set_device(gpu)
    torch.manual_seed(gpu)
    torch.cuda.manual_seed_all(gpu)
    x = torch.randn((2, 2, 3), device='cuda', requires_grad=True)
    xx = torch.nn.functional.normalize(x, p=2, dim=-1)
    cov = torch.stack([W.T.matmul(W) for W in xx])
    if USE_NN_REDUCE:
        cov=dist.nn.all_reduce(cov)
    else:
        dist.all_reduce(cov)
    print("Value after all_reduce:", cov)
    y = torch.logdet(torch.ones((3,3), device=gpu)+ 0.1*cov).sum()
    #y = sum([torch.logdet(torch.ones((3,3), device=gpu)+ 0.1*cov[i]) for i in range(2)])
    y.backward()
    print(f"{USE_NN_REDUCE=}, {gpu=}, {y=}, {x.grad=}")

nn_worker = partial(worker, USE_NN_REDUCE=1)
def local():
    torch.manual_seed(0)
    torch.cuda.manual_seed_all(0)
    x0 = torch.randn((2, 2, 3), device='cuda')
    torch.manual_seed(1)
    torch.cuda.manual_seed_all(1)
    x1 =  torch.randn((2, 2, 3), device='cuda')
    x = torch.cat([x0, x1], dim=1)
    x = x.requires_grad_()
    xx = torch.nn.functional.normalize(x, p=2, dim=-1)
    xx_all_reduce = torch.stack([W.T.matmul(W) for W in xx])
    print(f"truth: xx_all_reduce={xx_all_reduce}")
    y = torch.logdet(torch.ones((3,3), device='cuda')+ 0.1*xx_all_reduce).sum()
    y.backward()
    print(f"truth: {y=}")
    print(f"truth: grad={x.grad}")

if __name__ == "__main__":
    #dist.init_process_group(backend="nccl")
    # if dist.get_rank()==0:
    #     local()
    # worker(dist.get_rank())
    # nn_worker(dist.get_rank())
    local()
    torch.multiprocessing.spawn(worker, nprocs=2)
    torch.multiprocessing.spawn(nn_worker, nprocs=2)

Traceback:

  File "torch/multiprocessing/spawn.py", line 90, in _wrap
    fn(i, *args)
  File "test_reduce.py", line 22, in worker
    y.backward()
  File "torch/_tensor.py", line 581, in backward
    torch.autograd.backward(
  File "torch/autograd/__init__.py", line 347, in backward
    enginerun_backward(
  File "torch/autograd/graph.py", line 825, in enginerun_backward
    return Variable._execution_engine.run_backward(  # Calls into the C++ engine to run the backward pass
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "torch/autograd/function.py", line 307, in apply
    return user_fn(self, *args)
           ^^^^^^^^^^^^^^^^^^^^
  File "torch/distributed/nn/functional.py", line 452, in backward
    return (None, None) + (_AllReduce.apply(ctx.op, ctx.group, grad_output),)
                           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "torch/autograd/function.py", line 575, in apply
    return super().apply(*args, **kwargs)  # type: ignore[misc]
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "torch/distributed/nn/functional.py", line 447, in forward
    dist.all_reduce(tensor, op=op, group=group)
  File "torch/distributed/c10d_logger.py", line 83, in wrapper
    return func(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^
  File "torch/distributed/distributed_c10d.py", line 2501, in all_reduce
    work = group.allreduce([tensor], opts)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
ValueError: Tensors must be contiguous

we can bypass the error by alt L20 y = torch.logdet(torch.ones((3,3), device=gpu)+ 0.1*cov).sum()
to L21 y = sum([torch.logdet(torch.ones((3,3), device=gpu)+ 0.1*cov[i]) for i in range(2)])
or y=torch.stack([torch.logdet(torch.ones((3,3), device=gpu)+ 0.1*cov[i]) for i in range(2)]).sum()

but it indicates there maybe some error similar with issue #73515

Versions

PyTorch version: 2.5.1+cu124
Is debug build: False
CUDA used to build PyTorch: 12.4
ROCM used to build PyTorch: N/A

OS: Ubuntu 20.04.5 LTS (x86_64)
GCC version: (Ubuntu 9.4.0-1ubuntu1~20.04.2) 9.4.0
Clang version: Could not collect
CMake version: version 3.30.5
Libc version: glibc-2.31

Python version: 3.12.4 | packaged by conda-forge | (main, Jun 17 2024, 10:23:07) [GCC 12.3.0] (64-bit runtime)
Python platform: Linux-5.4.0-125-generic-x86_64-with-glibc2.31
Is CUDA available: True
CUDA runtime version: 12.4.99
CUDA_MODULE_LOADING set to: LAZY
GPU models and configuration:
GPU 0: NVIDIA H800
GPU 1: NVIDIA H800
GPU 2: NVIDIA H800
GPU 3: NVIDIA H800
GPU 4: NVIDIA H800
GPU 5: NVIDIA H800
GPU 6: NVIDIA H800
GPU 7: NVIDIA H800

Nvidia driver version: 560.35.03
cuDNN version: Probably one of the following:
/usr/lib/x86_64-linux-gnu/libcudnn.so.9.5.1
/usr/lib/x86_64-linux-gnu/libcudnn_adv.so.9.5.1
/usr/lib/x86_64-linux-gnu/libcudnn_cnn.so.9.5.1
/usr/lib/x86_64-linux-gnu/libcudnn_engines_precompiled.so.9.5.1
/usr/lib/x86_64-linux-gnu/libcudnn_engines_runtime_compiled.so.9.5.1
/usr/lib/x86_64-linux-gnu/libcudnn_graph.so.9.5.1
/usr/lib/x86_64-linux-gnu/libcudnn_heuristic.so.9.5.1
/usr/lib/x86_64-linux-gnu/libcudnn_ops.so.9.5.1
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
Byte Order: Little Endian
Address sizes: 52 bits physical, 57 bits virtual
CPU(s): 224
On-line CPU(s) list: 0-223
Thread(s) per core: 2
Core(s) per socket: 56
Socket(s): 2
NUMA node(s): 2
Vendor ID: GenuineIntel
CPU family: 6
Model: 143
Model name: Intel(R) Xeon(R) Platinum 8480+
Stepping: 8
Frequency boost: enabled
CPU MHz: 3000.019
CPU max MHz: 2001.0000
CPU min MHz: 800.0000
BogoMIPS: 4000.00
Virtualization: VT-x
L1d cache: 5.3 MiB
L1i cache: 3.5 MiB
L2 cache: 224 MiB
L3 cache: 210 MiB
NUMA node0 CPU(s): 0-55,112-167
NUMA node1 CPU(s): 56-111,168-223
Vulnerability Itlb multihit: Not affected
Vulnerability L1tf: Not affected
Vulnerability Mds: Not affected
Vulnerability Meltdown: Not affected
Vulnerability Mmio stale data: Not affected
Vulnerability Spec store bypass: Mitigation; Speculative Store Bypass disabled via prctl and seccomp
Vulnerability Spectre v1: Mitigation; usercopy/swapgs barriers and __user pointer sanitization
Vulnerability Spectre v2: Mitigation; Enhanced IBRS, IBPB conditional, RSB filling
Vulnerability Srbds: Not affected
Vulnerability Tsx async abort: Not affected
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 ds_cpl vmx smx est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid dca sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch cpuid_fault epb cat_l3 cat_l2 cdp_l3 invpcid_single cdp_l2 ssbd mba ibrs ibpb stibp ibrs_enhanced tpr_shadow vnmi flexpriority ept vpid ept_ad fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid cqm rdt_a avx512f avx512dq rdseed adx smap avx512ifma clflushopt clwb intel_pt avx512cd sha_ni avx512bw avx512vl xsaveopt xsavec xgetbv1 xsaves cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local avx512_bf16 wbnoinvd dtherm ida arat pln pts avx512vbmi umip pku ospke waitpkg avx512_vbmi2 gfni vaes vpclmulqdq avx512_vnni avx512_bitalg tme avx512_vpopcntdq rdpid cldemote movdiri movdir64b md_clear pconfig flush_l1d arch_capabilities

Versions of relevant libraries:
[pip3] lovely-numpy==0.2.13
[pip3] mypy-extensions==1.0.0
[pip3] numpy==1.26.3
[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] pytorch-benchmark==0.3.6
[pip3] pytorch-lightning==2.3.1
[pip3] pytorch-memlab==0.3.0
[pip3] pytorch-triton==3.0.0
[pip3] torch==2.5.1+cu124
[pip3] torch-fidelity==0.3.0
[pip3] torch-flops==0.3.5
[pip3] torchaudio==2.5.1
[pip3] torchdata==0.7.1
[pip3] torchmetrics==1.6.0
[pip3] torchshow==0.5.1
[pip3] torchvision==0.20.1
[pip3] triton==3.1.0
[conda] lovely-numpy 0.2.13 pypi_0 pypi
[conda] numpy 1.26.3 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] pytorch-benchmark 0.3.6 pypi_0 pypi
[conda] pytorch-lightning 2.3.1 pypi_0 pypi
[conda] pytorch-memlab 0.3.0 pypi_0 pypi
[conda] pytorch-triton 3.0.0 pypi_0 pypi
[conda] torch 2.5.1+cu124 pypi_0 pypi
[conda] torch-fidelity 0.3.0 pypi_0 pypi
[conda] torch-flops 0.3.5 pypi_0 pypi
[conda] torchaudio 2.5.1 pypi_0 pypi
[conda] torchdata 0.10.1 pypi_0 pypi
[conda] torchmetrics 1.6.0 pypi_0 pypi
[conda] torchshow 0.5.1 pypi_0 pypi
[conda] torchvision 0.20.1 pypi_0 pypi
[conda] triton 3.1.0 pypi_0 pypi

cc @H-Huang @awgu @kwen2501 @wanchaol @fegin @fduwjj @wz337 @wconstab @d4l3k @c-p-i-o

Metadata

Metadata

Assignees

Labels

oncall: distributedAdd this issue/PR to distributed oncall triage queuetriagedThis issue has been looked at a team member, and triaged and prioritized into an appropriate module

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions