Repository: pytorch
Issue: DataParallel scatter method split tensor wrong
Labels: module: cuda,triaged,module: data parallel

### 🐛 Describe the bug

I use dataparallel with two gpus. And I found half of tensors changed to zero tensors after scatter method.

```python
from transformers import LlamaModel, LlamaTokenizer
import torch, debugpy

# use debug tool and find the bug
# debugpy.connect(('192.168.1.50', 6789))
# debugpy.wait_for_client()
# debugpy.breakpoint()

text = ["Hello, how are you?", "I'm fine, thanks! And you?", "Not bad", "So bye", "Hello, how are you?", "I'm fine, thanks! And you?", "Not bad", "So bye", "Hello, how are you?", "I'm fine, thanks! And you?", "Not bad", "So bye"]

model = LlamaModel.from_pretrained("daryl149/llama-2-7b-chat-hf")

tokenizer = LlamaTokenizer.from_pretrained("daryl149/llama-2-7b-chat-hf")

model = torch.nn.DataParallel(model, device_ids=[0,1])

tokenizer.pad_token = tokenizer.eos_token

tokens = tokenizer(text, padding="longest", return_tensors="pt")

device = torch.device("cuda:0")

model.to(device)

input_ids = tokens["input_ids"].to(device)
attention_mask = tokens["attention_mask"].to(device)

# debugpy.breakpoint()
# step into this method
output = model.forward(input_ids = input_ids, attention_mask = attention_mask)
```

Debugpy will step into forward method in torch.nn.parallel.data_parallel.py. Code is here.
```python
def forward(self, *inputs, **kwargs):
    with torch.autograd.profiler.record_function("DataParallel.forward"):
        if not self.device_ids:
            return self.module(*inputs, **kwargs)

        for t in chain(self.module.parameters(), self.module.buffers()):
            if t.device != self.src_device_obj:
                raise RuntimeError("module must have its parameters and buffers "
                                   "on device {} (device_ids[0]) but found one of "
                                   "them on device: {}".format(self.src_device_obj, t.device))

        inputs, kwargs = self.scatter(inputs, kwargs, self.device_ids)
        # for forward function without any inputs, empty list and dict will be created
        # so the module can be executed on one device which is the first one in device_ids
        if not inputs and not kwargs:
            inputs = ((),)
            kwargs = ({},)

        if len(self.device_ids) == 1:
            return self.module(*inputs[0], **kwargs[0])
        replicas = self.replicate(self.module, self.device_ids[:len(inputs)])
        outputs = self.parallel_apply(replicas, inputs, kwargs)
        return self.gather(outputs, self.output_device)
```

After "inputs, kwargs = self.scatter(inputs, kwargs, self.device_ids)", kwargs is split into two parts.

![image](https://github.com/pytorch/pytorch/assets/57321011/8d76fe84-5655-4382-87d6-6f6bf1518b2e)

So the bug is that the second kwargs scattered into cuda:1 changed into zero tensors.

### Versions

collect_env.py output

```
Collecting environment information...
PyTorch version: 1.10.2+cu111
Is debug build: False
CUDA used to build PyTorch: 11.1
ROCM used to build PyTorch: N/A

OS: Ubuntu 22.04.2 LTS (x86_64)
GCC version: (Ubuntu 11.4.0-1ubuntu1~22.04) 11.4.0
Clang version: 14.0.0-1ubuntu1.1
CMake version: version 3.22.1
Libc version: glibc-2.35

Python version: 3.9.17 (main, Jul  5 2023, 20:41:20)  [GCC 11.2.0] (64-bit runtime)
Python platform: Linux-5.15.0-78-generic-x86_64-with-glibc2.35
Is CUDA available: True
CUDA runtime version: 11.5.119
CUDA_MODULE_LOADING set to: 
GPU models and configuration: 
GPU 0: NVIDIA A100-SXM4-80GB
GPU 1: NVIDIA A100-SXM4-80GB

Nvidia driver version: 535.86.05
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:                   52 bits physical, 57 bits virtual
Byte Order:                      Little Endian
CPU(s):                          128
On-line CPU(s) list:             0-127
Vendor ID:                       GenuineIntel
Model name:                      Intel(R) Xeon(R) Platinum 8370C CPU @ 2.80GHz
CPU family:                      6
Model:                           106
Thread(s) per core:              2
Core(s) per socket:              32
Socket(s):                       2
Stepping:                        6
CPU max MHz:                     3500.0000
CPU min MHz:                     800.0000
BogoMIPS:                        5600.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 invpcid_single 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 split_lock_detect wbnoinvd dtherm ida arat pln pts avx512vbmi umip pku ospke avx512_vbmi2 gfni vaes vpclmulqdq avx512_vnni avx512_bitalg tme avx512_vpopcntdq la57 rdpid fsrm md_clear pconfig flush_l1d arch_capabilities
Virtualization:                  VT-x
L1d cache:                       3 MiB (64 instances)
L1i cache:                       2 MiB (64 instances)
L2 cache:                        80 MiB (64 instances)
L3 cache:                        96 MiB (2 instances)
NUMA node(s):                    2
NUMA node0 CPU(s):               0-31,64-95
NUMA node1 CPU(s):               32-63,96-127
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 Retbleed:          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, PBRSB-eIBRS SW sequence
Vulnerability Srbds:             Not affected
Vulnerability Tsx async abort:   Not affected

Versions of relevant libraries:
[pip3] numpy==1.25.1
[pip3] torch==1.10.2+cu111
[conda] blas                      1.0                         mkl  
[conda] faiss-cpu                 1.7.4           py3.9_h8c27c75_0_cpu    pytorch
[conda] libfaiss                  1.7.4            h2bc3f7f_0_cpu    pytorch
[conda] mkl                       2023.1.0         h213fc3f_46343  
[conda] mkl-service               2.4.0            py39h5eee18b_1  
[conda] mkl_fft                   1.3.6            py39h417a72b_1  
[conda] mkl_random                1.2.2            py39h417a72b_1  
[conda] numpy                     1.25.1                   pypi_0    pypi
[conda] numpy-base                1.25.2           py39hb5e798b_0  
[conda] torch                     1.10.2+cu111             pypi_0    pypi
```

cc @ptrblck