Parameter gradient is not moved parameter is moved across devices
Labels: module: docs, module: nn, triaged, actionable, module: correctness (silent)

### 🐛 Describe the bug

TL;DR: if you initialize a parameter, which then becomes part of a registered buffer (e.g. by concatenation), the parameter correctly moves to the device the model is assigned to, but its gradient doesn't. The following minimal snippet below should reproduce: 

```python
import torch
from torch import nn

class LayerWithConcatInConstructor(nn.Module):
    def __init__(self, previous_weights: torch.Tensor):
        super().__init__()
        self.new_weights = nn.parameter.Parameter(torch.randn(1, previous_weights.shape[-1], dtype=previous_weights.dtype))
        self.register_buffer('full_weights', torch.cat([previous_weights, self.new_weights], dim=0))

    def forward(self, x):
        return self.full_weights @ x
    

class LayerWithConcatInForwardPass(nn.Module):
    def __init__(self, previous_weights: torch.Tensor):
        super().__init__()
        self.register_buffer('previous_weights', previous_weights)
        self.new_weights = nn.parameter.Parameter(torch.randn(1, previous_weights.shape[-1], dtype=previous_weights.dtype))

    def forward(self, x):
        return torch.cat([self.previous_weights, self.new_weights], dim=0) @ x  # type: ignore

# Initialize the two layers
prev_weights = torch.randn(1, 10)
x = torch.randn(10)

concat_in_constructor = LayerWithConcatInConstructor(prev_weights.clone().detach())
concat_in_forward = LayerWithConcatInForwardPass(prev_weights.clone().detach())

device = 'cuda:0'

# The version with the concatenation in the forward pass works just fine:
model = concat_in_forward.to(device)
optim = torch.optim.SGD(model.parameters(), lr=0.1)
optim.zero_grad(set_to_none=True)

l = model(x.to(device)).sum()
l.backward()
optim.step()

# The version with the concatenation in the constructor throws an error in the optimizer step because the parameter's gradient is on the CPU:
model = concat_in_constructor.to(device)
optim = torch.optim.SGD(model.parameters(), lr=0.1)
optim.zero_grad(set_to_none=True)

l = model(x.to(device)).sum()
l.backward()
optim.step()  # This will throw a RuntimeError
```

### Versions

PyTorch version: 1.12.1
Is debug build: False
CUDA used to build PyTorch: 11.3
ROCM used to build PyTorch: N/A

OS: CentOS Linux release 7.9.2009 (Core) (x86_64)
GCC version: (GCC) 4.8.5 20150623 (Red Hat 4.8.5-44)
Clang version: 3.4.2 (tags/RELEASE_34/dot2-final)
CMake version: version 2.8.12.2
Libc version: glibc-2.17

Python version: 3.10.8 | packaged by conda-forge | (main, Nov 22 2022, 08:26:04) [GCC 10.4.0] (64-bit runtime)
Python platform: Linux-3.10.0-1160.81.1.el7.x86_64-x86_64-with-glibc2.17
Is CUDA available: True
CUDA runtime version: 11.4.120
CUDA_MODULE_LOADING set to: 
GPU models and configuration: GPU 0: NVIDIA GeForce RTX 2080 Ti
Nvidia driver version: 470.161.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
CPU(s):                44
On-line CPU(s) list:   0-43
Thread(s) per core:    1
Core(s) per socket:    22
Socket(s):             2
NUMA node(s):          2
Vendor ID:             GenuineIntel
CPU family:            6
Model:                 85
Model name:            Intel(R) Xeon(R) Gold 6152 CPU @ 2.10GHz
Stepping:              4
CPU MHz:               1000.012
CPU max MHz:           3700.0000
CPU min MHz:           1000.0000
BogoMIPS:              4200.00
Virtualization:        VT-x
L1d cache:             32K
L1i cache:             32K
L2 cache:              1024K
L3 cache:              30976K
NUMA node0 CPU(s):     0-21
NUMA node1 CPU(s):     22-43
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 aperfmperf eagerfpu 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 epb cat_l3 cdp_l3 invpcid_single ssbd mba rsb_ctxsw ibrs ibpb stibp tpr_shadow vnmi flexpriority ept vpid fsgsbase tsc_adjust bmi1 hle avx2 smep bmi2 erms invpcid rtm cqm mpx rdt_a avx512f avx512dq rdseed adx smap clflushopt clwb intel_pt avx512cd avx512bw avx512vl xsaveopt xsavec xgetbv1 cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local dtherm ida arat pln pts hwp hwp_act_window hwp_epp hwp_pkg_req pku ospke md_clear spec_ctrl intel_stibp flush_l1d arch_capabilities

Versions of relevant libraries:
[pip3] numpy==1.24.1
[pip3] pytorch-lightning==2.0.2
[pip3] torch==1.12.1
[pip3] torchaudio==0.12.1
[pip3] torchmetrics==0.11.4
[pip3] torchvision==0.14.1
[conda] blas                      1.0                         mkl  
[conda] cudatoolkit               11.3.1              h9edb442_11    conda-forge
[conda] ffmpeg                    4.3                  hf484d3e_0    pytorch
[conda] mkl                       2021.4.0           h06a4308_640  
[conda] mkl-service               2.4.0           py310ha2c4b55_0    conda-forge
[conda] mkl_fft                   1.3.1           py310h2b4bcf5_1    conda-forge
[conda] mkl_random                1.2.2           py310h00e6091_0  
[conda] numpy                     1.24.1                   pypi_0    pypi
[conda] numpy-base                1.23.5          py310h8e6c178_0  
[conda] pytorch                   1.12.1          py3.10_cuda11.3_cudnn8.3.2_0    pytorch
[conda] pytorch-lightning         2.0.2                    pypi_0    pypi
[conda] pytorch-mutex             1.0                        cuda    pytorch
[conda] torchaudio                0.12.1              py310_cu113    pytorch
[conda] torchmetrics              0.11.4                   pypi_0    pypi
[conda] torchvision               0.14.1                   pypi_0    pypi

cc @svekars @carljparker @albanD @mruberry @jbschlosser @walterddr @mikaylagawarecki @ezyang @gchanan @zou3519