Repository: pytorch
Issue: Unexpected type cast from DTensor to Tensor when applying SequenceParallel on RMSNorm.
Labels: oncall: distributed

### 🐛 Describe the bug

I am using Sequence parallel for my RMS implementation in LLaMA torchtune. During the forward pass, layer 0 propagates successfully, but layer 1 encountered a weird bug where if I print out the type and shape and placements of output and self.scale, it is displaying the desired configs ([b, s, d] tensor and a [d] tensor, both of type DTensor, one sharded along the sequence dimension (Shard(1)), and one is replicated). But during the multiplication, the stack traces suggests that the output tensor was casted to Tensor somewhere during the execution.

My reference RMSNorm implementation is here:

```
class RMSNorm(nn.Module):
    def __init__(self, dim: int, eps: float = 1e-6):
        """
        Initialize the RMSNorm normalization layer.

        Args:
            dim (int): The dimension of the input tensor.
            eps (float, optional): A small value added to the denominator for numerical stability. Default is 1e-6.

        Attributes:
            eps (float): A small value added to the denominator for numerical stability.
            weight (nn.Parameter): Learnable scaling parameter.

        """
        super().__init__()
        self.eps = eps
        self.scale = nn.Parameter(torch.ones(dim))

    def _norm(self, x):
        """
        Apply the RMSNorm normalization to the input tensor.

        Args:
            x (torch.Tensor): The input tensor.

        Returns:
            torch.Tensor: The normalized tensor.

        """
        return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)

    def forward(self, x):
        """
        Forward pass through the RMSNorm layer.

        Args:
            x (torch.Tensor): The input tensor.

        Returns:
            torch.Tensor: The output tensor after applying RMSNorm.

        """
        output = self._norm(x.float()).type_as(x)
        print(f"x_norm local shape is {output.to_local().shape}, placement is {output.placements}, type is {type(output)}")
        print(f"scale locals shape is {self.scale.to_local().shape}, placement is {self.scale.placements}, type is {type(self.scale)}, scale dimension is {self.scale.numel()}")
        return output * self.scale
```

and it prints out the following output:

> x_norm local shape is torch.Size([2, 140, 4096]), placement is (Shard(dim=1),), type is <class 'torch.distributed.tensor.DTensor'>
> scale locals shape is torch.Size([4096]), placement is (Replicate(),), type is <class 'torch.distributed.tensor.DTensor'>, scale dimension is 4096

However the stack following stack traces (the call to _try_replicate_spec_for_scalar_tensor) suggest that a DTensor became Tensor somewhere in the middle since this function is only invoked if it passes a type test (isinstance(arg, torch.Tensor)). I printed out the arg and it says it is a tensor of shape [2, 140, 4096], suggesting that the output DTensor was casted to a Tensor somewhere in the middle.

```
[rank0]: Traceback (most recent call last):
[rank0]:   File "/home/ubuntu/torchtune/recipes/lora_finetune_tp_distributed.py", line 1085, in <module>
[rank0]:     sys.exit(recipe_main())
[rank0]:   File "/home/ubuntu/torchtune/torchtune/config/_parse.py", line 50, in wrapper
[rank0]:     sys.exit(recipe_main(conf))
[rank0]:   File "/home/ubuntu/torchtune/recipes/lora_finetune_tp_distributed.py", line 1079, in recipe_main
[rank0]:     recipe.train()
[rank0]:   File "/home/ubuntu/torchtune/recipes/lora_finetune_tp_distributed.py", line 956, in train
[rank0]:     logits = self._model(tokens_repeated, mask=mask_repeated, input_pos=input_pos_repeated)
[rank0]:   File "/home/ubuntu/anaconda3/envs/torchtune/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1736, in _wrapped_call_impl
[rank0]:     return self._call_impl(*args, **kwargs)
[rank0]:   File "/home/ubuntu/anaconda3/envs/torchtune/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1747, in _call_impl
[rank0]:     return forward_call(*args, **kwargs)
[rank0]:   File "/home/ubuntu/torchtune/torchtune/modules/transformer.py", line 289, in forward
[rank0]:     h = layer(h, freqs_cis = self.freqs_cis, mask=mask, input_pos=input_pos)
[rank0]:   File "/home/ubuntu/anaconda3/envs/torchtune/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1736, in _wrapped_call_impl
[rank0]:     return self._call_impl(*args, **kwargs)
[rank0]:   File "/home/ubuntu/anaconda3/envs/torchtune/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1747, in _call_impl
[rank0]:     return forward_call(*args, **kwargs)
[rank0]:   File "/home/ubuntu/anaconda3/envs/torchtune/lib/python3.10/site-packages/torch/distributed/algorithms/_checkpoint/checkpoint_wrapper.py", line 170, in forward
[rank0]:     return self.checkpoint_fn(  # type: ignore[misc]
[rank0]:   File "/home/ubuntu/anaconda3/envs/torchtune/lib/python3.10/site-packages/torch/_compile.py", line 32, in inner
[rank0]:     return disable_fn(*args, **kwargs)
[rank0]:   File "/home/ubuntu/anaconda3/envs/torchtune/lib/python3.10/site-packages/torch/_dynamo/eval_frame.py", line 632, in _fn
[rank0]:     return fn(*args, **kwargs)
[rank0]:   File "/home/ubuntu/anaconda3/envs/torchtune/lib/python3.10/site-packages/torch/utils/checkpoint.py", line 496, in checkpoint
[rank0]:     ret = function(*args, **kwargs)
[rank0]:   File "/home/ubuntu/anaconda3/envs/torchtune/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1736, in _wrapped_call_impl
[rank0]:     return self._call_impl(*args, **kwargs)
[rank0]:   File "/home/ubuntu/anaconda3/envs/torchtune/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1844, in _call_impl
[rank0]:     return inner()
[rank0]:   File "/home/ubuntu/anaconda3/envs/torchtune/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1790, in inner
[rank0]:     result = forward_call(*args, **kwargs)
[rank0]:   File "/home/ubuntu/torchtune/torchtune/modules/transformer.py", line 76, in forward
[rank0]:     norm_x = self.sa_norm(x)
[rank0]:   File "/home/ubuntu/anaconda3/envs/torchtune/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1736, in _wrapped_call_impl
[rank0]:     return self._call_impl(*args, **kwargs)
[rank0]:   File "/home/ubuntu/anaconda3/envs/torchtune/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1844, in _call_impl
[rank0]:     return inner()
[rank0]:   File "/home/ubuntu/anaconda3/envs/torchtune/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1790, in inner
[rank0]:     result = forward_call(*args, **kwargs)
[rank0]:   File "/home/ubuntu/torchtune/torchtune/modules/rms_norm.py", line 99, in forward
[rank0]:     return output * self.scale
[rank0]:   File "/home/ubuntu/anaconda3/envs/torchtune/lib/python3.10/site-packages/torch/_compile.py", line 32, in inner
[rank0]:     return disable_fn(*args, **kwargs)
[rank0]:   File "/home/ubuntu/anaconda3/envs/torchtune/lib/python3.10/site-packages/torch/_dynamo/eval_frame.py", line 632, in _fn
[rank0]:     return fn(*args, **kwargs)
[rank0]:   File "/home/ubuntu/anaconda3/envs/torchtune/lib/python3.10/site-packages/torch/distributed/tensor/_api.py", line 340, in __torch_dispatch__
[rank0]:     return DTensor._op_dispatcher.dispatch(
[rank0]:   File "/home/ubuntu/anaconda3/envs/torchtune/lib/python3.10/site-packages/torch/distributed/tensor/_dispatch.py", line 215, in dispatch
[rank0]:     local_results = op_call(*local_tensor_args, **op_info.local_kwargs)
[rank0]:   File "/home/ubuntu/anaconda3/envs/torchtune/lib/python3.10/site-packages/torch/_ops.py", line 716, in __call__
[rank0]:     return self._op(*args, **kwargs)
[rank0]:   File "/home/ubuntu/anaconda3/envs/torchtune/lib/python3.10/site-packages/torch/_compile.py", line 32, in inner
[rank0]:     return disable_fn(*args, **kwargs)
[rank0]:   File "/home/ubuntu/anaconda3/envs/torchtune/lib/python3.10/site-packages/torch/_dynamo/eval_frame.py", line 632, in _fn
[rank0]:     return fn(*args, **kwargs)
[rank0]:   File "/home/ubuntu/anaconda3/envs/torchtune/lib/python3.10/site-packages/torch/distributed/tensor/_api.py", line 340, in __torch_dispatch__
[rank0]:     return DTensor._op_dispatcher.dispatch(
[rank0]:   File "/home/ubuntu/anaconda3/envs/torchtune/lib/python3.10/site-packages/torch/distributed/tensor/_dispatch.py", line 166, in dispatch
[rank0]:     op_info = self.unwrap_to_op_info(op_call, args, kwargs)
[rank0]:   File "/home/ubuntu/anaconda3/envs/torchtune/lib/python3.10/site-packages/torch/distributed/tensor/_dispatch.py", line 372, in unwrap_to_op_info
[rank0]:     self._try_replicate_spec_for_scalar_tensor(op_call, arg, mesh)
[rank0]:   File "/home/ubuntu/anaconda3/envs/torchtune/lib/python3.10/site-packages/torch/distributed/tensor/_dispatch.py", line 471, in _try_replicate_spec_for_scalar_tensor
[rank0]:     raise RuntimeError(
[rank0]: RuntimeError: aten.mul.Tensor: got mixed torch.Tensor and DTensor, need to convert all torch.Tensor to DTensor before calling distributed operators!
```

### Versions

Collecting environment information...
PyTorch version: 2.5.1+cu121
Is debug build: False
CUDA used to build PyTorch: 12.1
ROCM used to build PyTorch: N/A

OS: Ubuntu 22.04.5 LTS (x86_64)
GCC version: (Ubuntu 11.4.0-1ubuntu1~22.04) 11.4.0
Clang version: Could not collect
CMake version: version 3.30.5
Libc version: glibc-2.35

Python version: 3.10.15 (main, Oct  3 2024, 07:27:34) [GCC 11.2.0] (64-bit runtime)
Python platform: Linux-6.8.0-1017-aws-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 A100-SXM4-40GB
GPU 1: NVIDIA A100-SXM4-40GB
GPU 2: NVIDIA A100-SXM4-40GB
GPU 3: NVIDIA A100-SXM4-40GB
GPU 4: NVIDIA A100-SXM4-40GB
GPU 5: NVIDIA A100-SXM4-40GB
GPU 6: NVIDIA A100-SXM4-40GB
GPU 7: NVIDIA A100-SXM4-40GB

Nvidia driver version: 550.127.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:                        46 bits physical, 48 bits virtual
Byte Order:                           Little Endian
CPU(s):                               96
On-line CPU(s) list:                  0-95
Vendor ID:                            GenuineIntel
Model name:                           Intel(R) Xeon(R) Platinum 8275CL CPU @ 3.00GHz
CPU family:                           6
Model:                                85
Thread(s) per core:                   2
Core(s) per socket:                   24
Socket(s):                            2
Stepping:                             7
BogoMIPS:                             5999.99
Flags:                                fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ss ht syscall nx pdpe1gb rdtscp lm constant_tsc arch_perfmon rep_good nopl xtopology nonstop_tsc cpuid aperfmperf tsc_known_freq pni pclmulqdq monitor ssse3 fma cx16 pcid sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand hypervisor lahf_lm abm 3dnowprefetch pti fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid mpx avx512f avx512dq rdseed adx smap clflushopt clwb avx512cd avx512bw avx512vl xsaveopt xsavec xgetbv1 xsaves ida arat pku ospke
Hypervisor vendor:                    KVM
Virtualization type:                  full
L1d cache:                            1.5 MiB (48 instances)
L1i cache:                            1.5 MiB (48 instances)
L2 cache:                             48 MiB (48 instances)
L3 cache:                             71.5 MiB (2 instances)
NUMA node(s):                         2
NUMA node0 CPU(s):                    0-23,48-71
NUMA node1 CPU(s):                    24-47,72-95
Vulnerability Gather data sampling:   Unknown: Dependent on hypervisor status
Vulnerability Itlb multihit:          KVM: Mitigation: VMX unsupported
Vulnerability L1tf:                   Mitigation; PTE Inversion
Vulnerability Mds:                    Vulnerable: Clear CPU buffers attempted, no microcode; SMT Host state unknown
Vulnerability Meltdown:               Mitigation; PTI
Vulnerability Mmio stale data:        Vulnerable: Clear CPU buffers attempted, no microcode; SMT Host state unknown
Vulnerability Reg file data sampling: Not affected
Vulnerability Retbleed:               Vulnerable
Vulnerability Spec rstack overflow:   Not affected
Vulnerability Spec store bypass:      Vulnerable
Vulnerability Spectre v1:             Mitigation; usercopy/swapgs barriers and __user pointer sanitization
Vulnerability Spectre v2:             Mitigation; Retpolines; STIBP disabled; RSB filling; PBRSB-eIBRS Not affected; BHI Retpoline
Vulnerability Srbds:                  Not affected
Vulnerability Tsx async abort:        Not affected

Versions of relevant libraries:
[pip3] numpy==1.26.3
[pip3] nvidia-cublas-cu12==12.1.3.1
[pip3] nvidia-cuda-cupti-cu12==12.1.105
[pip3] nvidia-cuda-nvrtc-cu12==12.1.105
[pip3] nvidia-cuda-runtime-cu12==12.1.105
[pip3] nvidia-cudnn-cu12==9.1.0.70
[pip3] nvidia-cufft-cu12==11.0.2.54
[pip3] nvidia-curand-cu12==10.3.2.106
[pip3] nvidia-cusolver-cu12==11.4.5.107
[pip3] nvidia-cusparse-cu12==12.1.0.106
[pip3] nvidia-nccl-cu12==2.21.5
[pip3] nvidia-nvjitlink-cu12==12.1.105
[pip3] nvidia-nvtx-cu12==12.1.105
[pip3] torch==2.5.1+cu121
[pip3] torchao==0.1
[pip3] torchaudio==2.5.1+cu121
[pip3] torchtune==0.0.0
[pip3] torchvision==0.20.1+cu121
[pip3] triton==3.1.0
[conda] numpy                     1.26.3                   pypi_0    pypi
[conda] nvidia-cublas-cu12        12.1.3.1                 pypi_0    pypi
[conda] nvidia-cuda-cupti-cu12    12.1.105                 pypi_0    pypi
[conda] nvidia-cuda-nvrtc-cu12    12.1.105                 pypi_0    pypi
[conda] nvidia-cuda-runtime-cu12  12.1.105                 pypi_0    pypi
[conda] nvidia-cudnn-cu12         9.1.0.70                 pypi_0    pypi
[conda] nvidia-cufft-cu12         11.0.2.54                pypi_0    pypi
[conda] nvidia-curand-cu12        10.3.2.106               pypi_0    pypi
[conda] nvidia-cusolver-cu12      11.4.5.107               pypi_0    pypi
[conda] nvidia-cusparse-cu12      12.1.0.106               pypi_0    pypi
[conda] nvidia-nccl-cu12          2.21.5                   pypi_0    pypi
[conda] nvidia-nvjitlink-cu12     12.1.105                 pypi_0    pypi
[conda] nvidia-nvtx-cu12          12.1.105                 pypi_0    pypi
[conda] torch                     2.5.1+cu121              pypi_0    pypi
[conda] torchao                   0.1                      pypi_0    pypi
[conda] torchaudio                2.5.1+cu121              pypi_0    pypi
[conda] torchtune                 0.0.0                    pypi_0    pypi
[conda] torchvision               0.20.1+cu121             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