Repository: pytorch
Issue: Uneven Sharding in DTensor Leads to unexpected tensor resolution with `full_tensor`
Labels: oncall: distributed,triaged,actionable,module: dtensor

### 🐛 Describe the bug

Appears related at least to #143372.  tl;dr: DTensor `full_tensor` operations are incorrect if sharding is not even AND if sharding isn't implicitly matching the uneven sharding that DTensor expects.  

I've recently hit this issue - uneven sharding of `DTensor` leads to unexpected results.  As a toy example, a 1D device mesh of size 4 with the following shapes:
- [2,2] on device 0
- [2,3] on device 1
- [2,4] on device 2
- [2,5] on device 3

Each tensor is created with torch.arange(5+rank) + 0.1*rank (to give uneven sizes and to make the decimal place match the rank).

This would have a global shape of (2, 14) when sharding with `placements=Shard(1)`, and strides as (14,1).  It's possible to pass the shape and stride to `DTensor.from_local` without any complaints from pytorch (even with `run_check=True`).  Visualizing the tensor gives 
```
         Col 0-3    Col 4-7    Col 8-11    Col 12-13
-------  ---------  ---------  ----------  -----------
Row 0-1  cuda:0     cuda:1     cuda:2      cuda:3
```

Whereas the correct placement (without any data movement) would be
```
         Col 0-1    Col 2-5     Col 6-9      Col 10-14
-------  ---------  ----------  -----------  -----------
Row 0-1  cuda:0     cuda:1      cuda:2       cuda:3
```

When I call `dtensor.full_tensor()`, it comes together with incorrect results:
```
Rank 0 has global tensor: tensor([[0.0000, 1.0000, 0.0000, 0.0000, 0.1000, 1.1000, 2.1000, 0.0000, 0.2000,
         1.2000, 2.2000, 3.2000, 0.3000, 1.3000],
        [2.0000, 3.0000, 0.0000, 0.0000, 3.1000, 4.1000, 5.1000, 0.0000, 4.2000,
         5.2000, 6.2000, 7.2000, 5.3000, 6.3000]], device='cuda:0') of shape torch.Size([2, 14])
```

To my best estimate, this is using the size that dtensor _expects_ for sharding based on dividing the sharded axis (14) by the number of shards (4): sizes (on axis 1) come out to 4, 4, 4, 2.  Looks like the operation that happens  is creating zero tensors, writing the incoming buffers into the right locations from the right start point, and truncating extra input.

Instead, I would expect (if the global size is correct) the output to be correctly concatenated across dimensions.  Similar to this operation (which works below):
```    
# Correct implementation:
size_list = [0,]*domain_size
# Gather the sizes:
dist.all_gather_object(size_list, local_chunk.shape)
# Create buffers:
output_tensor = [torch.empty(s, device=local_chunk.device) for s in size_list]
# Gather up:
dist.all_gather(output_tensor, local_chunk, group = domain_group)
#Concat:
output_tensor = torch.cat(output_tensor, dim=1)
if rank == 0:
    print(f"Correct output tensor: {output_tensor}")
```

Coming to the point of all of this:
- BUG: The DTensor implementation should raise an error if using `from_local` with `run_check=True`, if the local sharding does not match the sharding DTensor is expecting.
- Feature request: For uneven shardings, `full_tensor` should properly gather and concatenate tensor shards based on actual shapes and not DTensor's implicit shapes.


**Why does this matter / What's the use case?** I'm exploring techniques to use DTensor for domain parallelism on very very very large input data, which relatively small models.  Sharding can start even for regular data (images, volumes) or uneven for irregular (graphs) but some operations  - even on regular data - will produce output that does not distribute evenly.  Even convolutions, with a reasonable choice of kernel and stride and padding, will do this on reasonably shaped images.

Full Reproducer is here:
```
import torch


torch.manual_seed(1234)

import torch.distributed as dist
from torch.distributed import tensor as dist_tensor
from torch.distributed.tensor import debug



if __name__ == "__main__":
    
    mesh_shape = [4,]
    mesh_dim_names = ["domain"]
    
    mesh = dist.device_mesh.init_device_mesh(
            "cuda",
            mesh_shape,
            mesh_dim_names=mesh_dim_names,
        )
    
    # Access the rank easily through the manager:
    rank = dist.get_rank()
    
    
    


    # Make the chunks uneven and with different but predictable values:
    local_chunk = torch.arange(2*(2 + rank), dtype=torch.float32)  + 0.1*rank
    # To make this example not complelely trivial, we have 2D tensors split along one axis
    local_chunk = local_chunk.reshape((2,-1)).cuda().contiguous()
    local_chunk = local_chunk.to(f"cuda:{rank}")
    
    # Create the mesh, per usual:
    domain_mesh = mesh["domain"]

    
    # First, slice the local input based on domain mesh rank:
    domain_group = domain_mesh.get_group()
    domain_rank = dist.get_group_rank(domain_group, rank)
    domain_size = len(dist.get_process_group_ranks(domain_group))


    shape  = (2, 14)
    stride = (14, 1)
    
    
    # Now, we can create the dtensor properly:
    dtensor = dist_tensor.DTensor.from_local(
        local_chunk, 
        device_mesh = domain_mesh, 
        placements = (dist_tensor.Shard(1),),
        run_check=True,
        shape=shape,
        stride=stride
    )
    
    print(dist_tensor.Shard._local_shard_size_on_dim(26, 4, 0))
    
    print(f"Rank {rank} has {dtensor}\n")

    debug.visualize_sharding(dtensor)
    
    full = dtensor.full_tensor()
    
    if rank == 0:
        print(f"Rank {rank} has global tensor: {full} of shape {full.shape}\n")
    
    
    # Correct implementation:
    size_list = [0,]*domain_size
    # Gather the sizes:
    dist.all_gather_object(size_list, local_chunk.shape)
    # Create buffers:
    output_tensor = [torch.empty(s, device=local_chunk.device) for s in size_list]
    # Gather up:
    dist.all_gather(output_tensor, local_chunk, group = domain_group)
    #Concat:
    output_tensor = torch.cat(output_tensor, dim=1)
    if rank == 0:
        print(f"Correct output tensor: {output_tensor}")
```

### Versions

Collecting environment information...
PyTorch version: 2.5.1
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.1) 9.4.0
Clang version: Could not collect
CMake version: Could not collect
Libc version: glibc-2.31

Python version: 3.12.7 | packaged by Anaconda, Inc. | (main, Oct  4 2024, 13:27:36) [GCC 11.2.0] (64-bit runtime)
Python platform: Linux-5.15.0-1032-oracle-x86_64-with-glibc2.31
Is CUDA available: True
CUDA runtime version: Could not collect
CUDA_MODULE_LOADING set to: LAZY
GPU models and configuration:
GPU 0: NVIDIA A100-SXM4-80GB
GPU 1: NVIDIA A100-SXM4-80GB
GPU 2: NVIDIA A100-SXM4-80GB
GPU 3: NVIDIA A100-SXM4-80GB

Nvidia driver version: 535.129.03
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
Byte Order:                      Little Endian
Address sizes:                   48 bits physical, 48 bits virtual
CPU(s):                          256
On-line CPU(s) list:             0-254
Off-line CPU(s) list:            255
Thread(s) per core:              1
Core(s) per socket:              64
Socket(s):                       2
NUMA node(s):                    8
Vendor ID:                       AuthenticAMD
CPU family:                      25
Model:                           1
Model name:                      AMD EPYC 7J13 64-Core Processor
Stepping:                        1
Frequency boost:                 enabled
CPU MHz:                         2550.000
CPU max MHz:                     3673.0950
CPU min MHz:                     1500.0000
BogoMIPS:                        4900.16
Virtualization:                  AMD-V
L1d cache:                       2 MiB
L1i cache:                       2 MiB
L2 cache:                        32 MiB
L3 cache:                        256 MiB
NUMA node0 CPU(s):               0-15,128-143
NUMA node1 CPU(s):               16-31,144-159
NUMA node2 CPU(s):               32-47,160-175
NUMA node3 CPU(s):               48-63,176-191
NUMA node4 CPU(s):               64-79,192-207
NUMA node5 CPU(s):               80-95,208-223
NUMA node6 CPU(s):               96-111,224-239
NUMA node7 CPU(s):               112-127,240-254
Vulnerability Itlb multihit:     Not affected
Vulnerability L1tf:              Not affected
Vulnerability Mds:               Not affected
Vulnerability Meltdown:          Not affected
Vulnerability Mmio stale data:   Not affected
Vulnerability Retbleed:          Not affected
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: Not affected
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 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 pcid sse4_1 sse4_2 x2apic 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 invpcid_single 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 clzero irperf xsaveerptr rdpru wbnoinvd amd_ppin 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

Versions of relevant libraries:
[pip3] numpy==2.0.1
[pip3] nvtx==0.2.10
[pip3] onnx==1.17.0
[pip3] torch==2.5.1
[pip3] torchaudio==2.5.1
[pip3] torchdata==0.10.0
[pip3] torchvision==0.20.1
[pip3] triton==3.1.0
[conda] blas                      1.0                         mkl
[conda] cuda-cudart               12.4.127                      0    nvidia
[conda] cuda-cupti                12.4.127                      0    nvidia
[conda] cuda-libraries            12.4.1                        0    nvidia
[conda] cuda-nvrtc                12.4.127                      0    nvidia
[conda] cuda-nvtx                 12.4.127                      0    nvidia
[conda] cuda-opencl               12.6.77                       0    nvidia
[conda] cuda-runtime              12.4.1                        0    nvidia
[conda] ffmpeg                    4.3                  hf484d3e_0    pytorch
[conda] libcublas                 12.4.5.8                      0    nvidia
[conda] libcufft                  11.2.1.3                      0    nvidia
[conda] libcurand                 10.3.7.77                     0    nvidia
[conda] libcusolver               11.6.1.9                      0    nvidia
[conda] libcusparse               12.3.1.170                    0    nvidia
[conda] libjpeg-turbo             2.0.0                h9bf148f_0    pytorch
[conda] libnvjitlink              12.4.127                      0    nvidia
[conda] mkl                       2023.1.0         h213fc3f_46344
[conda] mkl-service               2.4.0           py312h5eee18b_1
[conda] mkl_fft                   1.3.11          py312h5eee18b_0
[conda] mkl_random                1.2.8           py312h526ad5a_0
[conda] numpy                     2.0.1           py312hc5e2394_1
[conda] numpy-base                2.0.1           py312h0da6c21_1
[conda] nvtx                      0.2.10                   pypi_0    pypi
[conda] pytorch                   2.5.1           py3.12_cuda12.4_cudnn9.1.0_0    pytorch
[conda] pytorch-cuda              12.4                 hc786d27_7    pytorch
[conda] pytorch-mutex             1.0                        cuda    pytorch
[conda] torchaudio                2.5.1               py312_cu124    pytorch
[conda] torchdata                 0.10.0                   pypi_0    pypi
[conda] torchtriton               3.1.0                     py312    pytorch
[conda] torchvision               0.20.1              py312_cu124    pytorch

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