Repository: pytorch
Issue: reduce_scatter_tensor with strided inputs produces corrupted results
Labels: oncall: distributed,triaged

### 🐛 Describe the bug

Consider the following piece of code:

```python
# run me with
# torchrun --nproc_per_node=2 repro.py
import os

import torch
from torch import distributed as dist


def sync_print(*args, **kwargs):
    kwargs.setdefault("flush", True)
    rank = dist.get_rank()
    world_size = dist.get_world_size()

    for turn in range(world_size):
        dist.barrier()
        if rank == turn:
            print(f"[{rank}/{world_size}]", *args, **kwargs)
            if turn == world_size - 1:
                print(**kwargs)
        dist.barrier()


def reduce_scatter_into(inp):
    batch, *shape = inp.shape
    world_size = dist.get_world_size()
    assert not batch % world_size

    out = torch.zeros(
        [batch // world_size] + shape,
        dtype=inp.dtype,
        device=inp.device,
    )
    dist.reduce_scatter_tensor(out, inp)

    return out


def get_zeros_with_custom_stride(stride, size=6):
    world_size = dist.get_world_size()

    if stride == 0:
        data = 1 + torch.arange(world_size * 4).float().cuda()
        data = data[0].expand((world_size * size))
    elif stride > 1:
        data = 1 + torch.arange(world_size * size * stride).float().cuda()
        data = data[::stride]
    else:
        assert stride == 1
        data = torch.zeros(world_size * size).float().cuda()

    data[:] = 0
    return data


def main():
    torch.cuda.set_device(
        int(os.environ["LOCAL_RANK"]),
    )
    dist.init_process_group(
        backend="nccl",
        world_size=int(os.environ["WORLD_SIZE"]),
        rank=int(os.environ["RANK"]),
    )

    for stride in [0, 1, 2, 3]:
        inp = get_zeros_with_custom_stride(stride)

        out = reduce_scatter_into(inp)
        sync_print(f"stride={inp.stride()}: {inp.cpu().tolist()} -> {out.cpu().tolist()}")

    dist.destroy_process_group()


if __name__ == "__main__":
    main()
```

It runs the `reduce_scatter_tensor` function on an input filled with zeros with different strides (0, 1, 2 and 3 in this example). Here are the outputs:

```
[0/2] stride=(0,): [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0] -> [0.0, 4.0, 6.0, 8.0, 10.0, 12.0]
[1/2] stride=(0,): [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0] -> [14.0, 16.0, 0.0, 0.0, 0.0, 0.0]

[0/2] stride=(1,): [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0] -> [0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
[1/2] stride=(1,): [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0] -> [0.0, 0.0, 0.0, 0.0, 0.0, 0.0]

[0/2] stride=(2,): [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0] -> [0.0, 4.0, 0.0, 8.0, 0.0, 12.0]
[1/2] stride=(2,): [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0] -> [0.0, 16.0, 0.0, 20.0, 0.0, 24.0]

[0/2] stride=(3,): [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0] -> [0.0, 4.0, 6.0, 0.0, 10.0, 12.0]
[1/2] stride=(3,): [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0] -> [0.0, 16.0, 18.0, 0.0, 22.0, 24.0]
```

As you can see, only the `stride=1` case gives the expected results. All other results seem to be naively interpreting the tensor as if it was contiguous. The non-zero values are leaking from the original "unstrided" `arange` tensor. The `stride=0` case is actually even reading uninitialized out-of-bounds memory past the end of the array.

### Versions

I was able to replicate this in torch `1.13.1`, `2.3.0` and nightly `2.4.0.dev20240605+cu121`.

<details>
<summary>Here's the information for version `2.3.0`</summary>

```
PyTorch version: 2.3.0+cu121
Is debug build: False
CUDA used to build PyTorch: 12.1
ROCM used to build PyTorch: N/A

OS: Ubuntu 22.04.3 LTS (x86_64)
GCC version: (Ubuntu 11.4.0-1ubuntu1~22.04) 11.4.0
Clang version: Could not collect
CMake version: version 3.22.1
Libc version: glibc-2.35

Python version: 3.10.12 (main, Nov 20 2023, 15:14:05) [GCC 11.4.0] (64-bit runtime)
Python platform: Linux-5.4.0-166-generic-x86_64-with-glibc2.35
Is CUDA available: True
CUDA runtime version: 12.1.105
CUDA_MODULE_LOADING set to: LAZY
GPU models and configuration: 
GPU 0: NVIDIA A40
GPU 1: NVIDIA A40
GPU 2: NVIDIA A40
GPU 3: NVIDIA A40
GPU 4: NVIDIA A40
GPU 5: NVIDIA A40
GPU 6: NVIDIA A40
GPU 7: NVIDIA A40
GPU 8: NVIDIA A40
GPU 9: NVIDIA A40

Nvidia driver version: 535.113.01
cuDNN version: Probably one of the following:
/usr/lib/x86_64-linux-gnu/libcudnn.so.8.9.0
/usr/lib/x86_64-linux-gnu/libcudnn_adv_infer.so.8.9.0
/usr/lib/x86_64-linux-gnu/libcudnn_adv_train.so.8.9.0
/usr/lib/x86_64-linux-gnu/libcudnn_cnn_infer.so.8.9.0
/usr/lib/x86_64-linux-gnu/libcudnn_cnn_train.so.8.9.0
/usr/lib/x86_64-linux-gnu/libcudnn_ops_infer.so.8.9.0
/usr/lib/x86_64-linux-gnu/libcudnn_ops_train.so.8.9.0
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:                      46 bits physical, 48 bits virtual
Byte Order:                         Little Endian
CPU(s):                             64
On-line CPU(s) list:                0-63
Vendor ID:                          GenuineIntel
Model name:                         Intel(R) Xeon(R) Gold 6226R CPU @ 2.90GHz
CPU family:                         6
Model:                              85
Thread(s) per core:                 2
Core(s) per socket:                 16
Socket(s):                          2
Stepping:                           7
CPU max MHz:                        3900.0000
CPU min MHz:                        1200.0000
BogoMIPS:                           5800.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 pni pclmulqdq dtes64 monitor 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 cdp_l3 invpcid_single intel_ppin 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 mpx rdt_a avx512f avx512dq rdseed adx smap clflushopt clwb intel_pt avx512cd avx512bw avx512vl xsaveopt xsavec xgetbv1 xsaves cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local dtherm ida arat pln pts pku ospke avx512_vnni md_clear flush_l1d arch_capabilities
Virtualization:                     VT-x
L1d cache:                          1 MiB (32 instances)
L1i cache:                          1 MiB (32 instances)
L2 cache:                           32 MiB (32 instances)
L3 cache:                           44 MiB (2 instances)
NUMA node(s):                       2
NUMA node0 CPU(s):                  0-15,32-47
NUMA node1 CPU(s):                  16-31,48-63
Vulnerability Gather data sampling: Vulnerable
Vulnerability Itlb multihit:        KVM: Vulnerable
Vulnerability L1tf:                 Not affected
Vulnerability Mds:                  Not affected
Vulnerability Meltdown:             Not affected
Vulnerability Mmio stale data:      Vulnerable
Vulnerability Retbleed:             Vulnerable
Vulnerability Spec store bypass:    Vulnerable
Vulnerability Spectre v1:           Vulnerable: __user pointer sanitization and usercopy barriers only; no swapgs barriers
Vulnerability Spectre v2:           Vulnerable, IBPB: disabled, STIBP: disabled, PBRSB-eIBRS: Vulnerable
Vulnerability Srbds:                Not affected
Vulnerability Tsx async abort:      Mitigation; TSX disabled

Versions of relevant libraries:
[pip3] numpy==1.26.4
[pip3] torch==2.3.0
[pip3] triton==2.3.0
[conda] Could not collect
```

</details>

cc @mrshenli @pritamdamania87 @zhaojuanmao @satgera @gqchen @aazzolini @osalpekar @jiayisuse @H-Huang @kwen2501 @awgu @penguinwu @fegin @XilunWu @wanchaol @fduwjj @wz337 @tianyu-l @wconstab @yf225 @chauhang @d4l3k