Repository: pytorch
Issue: `to()` Method Does Not Move Internal Components of Sparse Tensors
Labels: module: sparse,triaged

### 🐛 Describe the bug

**Description:**
In PyTorch 2.4, calling `.to(device)` on an `nn.Module` that contains sparse CSR tensors does not move the internal components of the sparse tensors (e.g., `crow_indices`, `col_indices`, `values`) to the specified device, while it was the case in PyTorch 2.2. This causes potential device mismatch errors.

**Minimal Working Example:**

```python
import torch
import torch.nn as nn

class SparseLayer(nn.Module):
    def __init__(self):
        super(SparseLayer, self).__init__()
        sparse_tensor = torch.empty(5, 5, device='cpu').uniform_(-1, 1).to_sparse_csr()
        self.matrix = nn.Parameter(sparse_tensor)

    def forward(self, x):
        pass

if __name__ == "__main__":
    # Create an instance of the SparseLayer
    layer = SparseLayer()

    # Move the layer to GPU
    layer = layer.to('cuda')

    # Check the device of the matrix and its internals after moving to GPU
    print("After moving to CUDA:")
    print(f"Matrix device: {layer.matrix.device}")
    print(f"Matrix crow_indices device: {layer.matrix.crow_indices().device}")
    print(f"Matrix col_indices device: {layer.matrix.col_indices().device}")
    print(f"Matrix values device: {layer.matrix.values().device}")

    # Now, move the layer back to CPU
    layer = layer.to('cpu')

    # Check the device of the matrix and its internals after moving back to CPU
    print("\nAfter moving back to CPU:")
    print(f"Matrix device: {layer.matrix.device}")
    print(f"Matrix crow_indices device: {layer.matrix.crow_indices().device}")
    print(f"Matrix col_indices device: {layer.matrix.col_indices().device}")
    print(f"Matrix values device: {layer.matrix.values().device}")

    # Manually move the sparse matrix back to CUDA and check its internals
    layer.matrix = nn.Parameter(layer.matrix.to('cuda'))

    print("\nAfter manually moving matrix to CUDA:")
    print(f"Matrix device: {layer.matrix.device}")
    print(f"Matrix crow_indices device: {layer.matrix.crow_indices().device}")
    print(f"Matrix col_indices device: {layer.matrix.col_indices().device}")
    print(f"Matrix values device: {layer.matrix.values().device}")
```

**Expected Behavior:**
- When calling `layer.to(device)`, the sparse tensor and all of its internal components (e.g., `crow_indices`, `col_indices`, `values`) should be moved to the specified device.

**Observed Behavior:**
- The code `layer.to('cuda')` moves the sparse tensor to the GPU, but not its internal components on PyTorch 2.4, while the internal components were moved in PyTorch 2.2. Manually moving the matrix to GPU with `nn.Parameter(layer.matrix.to('cuda'))` moves all the internals to the GPU. These different behaviors are prone to making errors.

### Versions

PyTorch version: 2.4.1+cu121                                                                                                                                     
Is debug build: False                                                                                                                                            
CUDA used to build PyTorch: 12.1                                                                                                                                 
ROCM used to build PyTorch: N/A                                                                                                                                  
                                                                                                                                                                 
OS: Debian GNU/Linux 12 (bookworm) (x86_64)                                                                                                                      
GCC version: (Debian 12.2.0-14) 12.2.0                                                                                                                           
Clang version: Could not collect                                                                                                                                 
CMake version: version 3.25.1
Libc version: glibc-2.36

Python version: 3.11.2 (main, May  2 2024, 11:59:08) [GCC 12.2.0] (64-bit runtime)
Python platform: Linux-6.1.0-23-amd64-x86_64-with-glibc2.36
Is CUDA available: True
CUDA runtime version: 11.8.89
CUDA_MODULE_LOADING set to: LAZY
GPU models and configuration: 
GPU 0: NVIDIA A100-PCIE-40GB
GPU 1: NVIDIA A100-PCIE-40GB

Nvidia driver version: 535.183.01
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):                               32 
On-line CPU(s) list:                  0-31
Vendor ID:                            GenuineIntel
Model name:                           Intel(R) Xeon(R) Silver 4215R CPU @ 3.20GHz
CPU family:                           6
Model:                                85 
Thread(s) per core:                   2
Core(s) per socket:                   8
Socket(s):                            2
Stepping:                             7
BogoMIPS:                             6400.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 sys
call 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_fa
ult 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:                            512 KiB (16 instances)
L1i cache:                            512 KiB (16 instances)
L2 cache:                             16 MiB (16 instances)
L3 cache:                             22 MiB (2 instances)
NUMA node(s):                         2
NUMA node0 CPU(s):                    0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30 
NUMA node1 CPU(s):                    1,3,5,7,9,11,13,15,17,19,21,23,25,27,29,31 
Vulnerability Gather data sampling:   Vulnerable: No microcode
Vulnerability Itlb multihit:          KVM: Mitigation: VMX disabled
Vulnerability L1tf:                   Not affected
Vulnerability Mds:                    Not affected
Vulnerability Meltdown:               Not affected
Vulnerability Mmio stale data:        Vulnerable: Clear CPU buffers attempted, no microcode; SMT vulnerable
Vulnerability Reg file data sampling: Not affected
Vulnerability Retbleed:               Mitigation; Enhanced IBRS
Vulnerability Spec rstack overflow:   Not affected
Vulnerability Spec store bypass:      Mitigation; Speculative Store Bypass disabled via prctl
Vulnerability Spectre v1:             Mitigation; usercopy/swapgs barriers and __user pointer sanitization
Vulnerability Spectre v2:             Mitigation; Enhanced / Automatic IBRS; IBPB conditional; RSB filling; PBRSB-eIBRS SW sequence; BHI SW loop, KVM SW loop
Vulnerability Srbds:                  Not affected
Vulnerability Tsx async abort:        Mitigation; TSX disabled

Versions of relevant libraries:
[pip3] numpy==2.1.1
[pip3] torch==2.4.1
[pip3] torchaudio==2.4.1
[pip3] torchvision==0.19.1
[pip3] triton==3.0.0
[conda] No relevant packages

cc @alexsamardzic @nikitaved @pearu @cpuhrsch @amjames @bhosmer @jcaip