Repository: pytorch
Issue: [Optim][Dynamo] Tensor unproperly assigned in Adagrad optimizer in dynamo
Labels: module: optimizer,triaged,oncall: pt2,module: dynamo,release notes: optim,module: pt2 optimizer

### 🐛 Describe the bug

I am testing the function of optimizer using torch dynamo, I found that there is a small problem in Adagrad, **state["step"]** was assigned to CPU while other parameters are assigned to CUDA. And I tested other models, only Adagrad behaves like that. You can see the detailed analyse below in **Error logs**

You can find the state of "step" under torch/optim/adagrad.py from master in line 97

```
        for group in self.param_groups:
            for p in group["params"]:
                state = self.state[p]
                state["step"] = (
                    torch.zeros(
                        (),
                        dtype=_get_scalar_dtype(is_fused=group["fused"]),
                        device=p.device,
                    )
                    if group["fused"]
                    else torch.tensor(0.0, dtype=_get_scalar_dtype()) # LINE 97
                )
                init_value = (
                    complex(initial_accumulator_value, initial_accumulator_value)
                    if torch.is_complex(p)
                    else initial_accumulator_value
                )
                state["sum"] = torch.full_like(
                    p, init_value, memory_format=torch.preserve_format
                )
```
It looks like so in 2.3.1:
```
        for group in self.param_groups:
            for p in group["params"]:
                state = self.state[p]
                state["step"] = torch.tensor(0.0, dtype=_get_scalar_dtype()) # Here
                init_value = (
                    complex(initial_accumulator_value, initial_accumulator_value)
                    if torch.is_complex(p)
                    else initial_accumulator_value
                )
                state["sum"] = torch.full_like(
                    p, init_value, memory_format=torch.preserve_format
                )
```

Here is the similar code in ASGD in pytorch 2.3.1:
```
    def __setstate__(self, state):
        super().__setstate__(state)
        for group in self.param_groups:
            group.setdefault("foreach", None)
            group.setdefault("maximize", False)
            group.setdefault("differentiable", False)
            group.setdefault("capturable", False)
            for p in group["params"]:
                p_state = self.state.get(p, [])
                if len(p_state) != 0:
                    if not torch.is_tensor(p_state['step']):
                        step_val = float(p_state["step"])
                        p_state["step"] = torch.tensor(step_val, dtype=_get_scalar_dtype(), device=p.device) #Similar code
                    if not torch.is_tensor(p_state["eta"]):
                        p_state["eta"] = torch.tensor(p_state["eta"], dtype=_get_scalar_dtype(), device=p.device)
                    if not torch.is_tensor(p_state["mu"]):
                        p_state["mu"] = torch.tensor(p_state["mu"], dtype=_get_scalar_dtype(), device=p.device)
```

You can find that there is no device info in Adagrad.

To fix it, just add p.device info.

```
p_state["step"] = torch.tensor(step_val, dtype=_get_scalar_dtype(), device=p.device)

s["step"] = torch.tensor(float(s["step"]), dtype=_get_scalar_dtype(), device=p.device)
```

You can see the analyse below, if you agree with my change, I will update a PR (from pytorch 2.0 to master) to change the code later.


### Error logs

**LOGS of Adagrad, from the _DispatchKeySet(CPU...)_ in the last 2 lines, you can find that the scalar 'step' was assigned to CPU, others were assigned to CUDA:**
```
V0815 10:33:35.436159 140588284983104 torch/_dynamo/guards.py:1085] [2/1] [__guards] check_tensor(L['self'].param_groups[0]['params'][0], Parameter, DispatchKeySet(CUDA, BackendSelect, ADInplaceOrView, AutogradCUDA), torch.float32, device=0, requires_grad=True, size=[2, 2], stride=[2, 1])  # has_sparse_grad, has_complex = self._init_group(group, params_with_grad, grads, state_sums, state_steps)  # optim/adagrad.py:119 in step```

...

V0815 10:33:35.441536 140588284983104 torch/_dynamo/guards.py:1085] [2/1] [__guards] check_tensor(L['self'].state[list(L['self'].state.keys())[0]]['sum'], Tensor, DispatchKeySet(CUDA, BackendSelect, ADInplaceOrView, AutogradCUDA), torch.float32, device=0, requires_grad=False, size=[2, 2], stride=[2, 1])  # has_sparse_grad, has_complex = self._init_group(group, params_with_grad, grads, state_sums, state_steps)  # optim/adagrad.py:119 in step```

...

V0815 10:33:35.443946 140588284983104 torch/_dynamo/guards.py:1085] [2/1] [__guards] check_tensor(L['self'].state[list(L['self'].state.keys())[0]]['step'], Tensor, DispatchKeySet(CPU, BackendSelect, ADInplaceOrView, AutogradCPU), torch.float32, device=None, requires_grad=False, size=[], stride=[])  # has_sparse_grad, has_complex = self._init_group(group, params_with_grad, grads, state_sums, state_steps)  # optim/adagrad.py:119 in step```

...


V0815 10:33:35.446371 140588284983104 torch/_dynamo/guards.py:1085] [2/1] [__guards] check_tensor(L['self'].state[list(L['self'].state.keys())[8]]['step'], Tensor, DispatchKeySet(CPU, BackendSelect, ADInplaceOrView, AutogradCPU), torch.float32, device=None, requires_grad=False, size=[], stride=[])  # has_sparse_grad, has_complex = self._init_group(group, params_with_grad, grads, state_sums, state_steps)  # optim/adagrad.py:119 in step
V0815 10:33:35.446728 140588284983104 torch/_dynamo/guards.py:1085] [2/1] [__guards] check_tensor(L['self'].state[list(L['self'].state.keys())[9]]['step'], Tensor, DispatchKeySet(CPU, BackendSelect, ADInplaceOrView, AutogradCPU), torch.float32, device=None, requires_grad=False, size=[], stride=[])  # has_sparse_grad, has_complex = self._init_group(group, params_with_grad, grads, state_sums, state_steps)  # optim/adagrad.py:119 in step
```

**LOGS of ASGD,you can find that the scalar 'step' was assigned to CUDA:**
```
V0815 11:12:47.959811 139832451274560 torch/_dynamo/guards.py:1085] [2/1] [__guards] check_tensor(L['self'].param_groups[0]['params'][1], Parameter, DispatchKeySet(CUDA, BackendSelect, ADInplaceOrView, AutogradCUDA), torch.float32, device=0, requires_grad=True, size=[2, 2], stride=[2, 1])  # has_complex = self._init_group(group, params_with_grad, grads, mus, axs, etas, state_steps)  # optim/asgd.py:117 in step

...

V0815 11:12:47.962426 139832451274560 torch/_dynamo/guards.py:1085] [2/1] [__guards] check_tensor(L['self'].param_groups[0]['params'][0].grad, Tensor, DispatchKeySet(CUDA, BackendSelect, ADInplaceOrView, AutogradCUDA), torch.float32, device=0, requires_grad=False, size=[2, 2], stride=[2, 1])  # has_complex = self._init_group(group, params_with_grad, grads, mus, axs, etas, state_steps)  # optim/asgd.py:117 in step

...

V0815 11:12:47.964913 139832451274560 torch/_dynamo/guards.py:1085] [2/1] [__guards] check_tensor(L['self'].state[list(L['self'].state.keys())[0]]['ax'], Tensor, DispatchKeySet(CUDA, BackendSelect, ADInplaceOrView, AutogradCUDA), torch.float32, device=0, requires_grad=False, size=[2, 2], stride=[2, 1])  # has_complex = self._init_group(group, params_with_grad, grads, mus, axs, etas, state_steps)  # optim/asgd.py:117 in step
V0815 11:12:47.965153 139832451274560 torch/_dynamo/guards.py:1085] [2/1] [__guards] check_tensor(L['self'].state[list(L['self'].state.keys())[0]]['mu'], Tensor, DispatchKeySet(CUDA, BackendSelect, ADInplaceOrView, AutogradCUDA), torch.float32, device=0, requires_grad=False, size=[], stride=[])  # has_complex = 

...

V0815 11:12:47.969633 139832451274560 torch/_dynamo/guards.py:1085] [2/1] [__guards] check_tensor(L['self'].state[list(L['self'].state.keys())[0]]['eta'], Tensor, DispatchKeySet(CUDA, BackendSelect, ADInplaceOrView, AutogradCUDA), torch.float32, device=0, requires_grad=False, size=[], stride=[])  # has_complex = self._init_group(group, params_with_grad, grads, mus, axs, etas, state_steps)  # optim/asgd.py:117 in step

...

V0815 11:12:47.971733 139832451274560 torch/_dynamo/guards.py:1085] [2/1] [__guards] check_tensor(L['self'].state[list(L['self'].state.keys())[9]]['eta'], Tensor, DispatchKeySet(CUDA, BackendSelect, ADInplaceOrView, AutogradCUDA), torch.float32, device=0, requires_grad=False, size=[], stride=[])  # has_complex = self._init_group(group, params_with_grad, grads, mus, axs, etas, state_steps)  # optim/asgd.py:117 in step
V0815 11:12:47.971964 139832451274560 torch/_dynamo/guards.py:1085] [2/1] [__guards] check_tensor(L['self'].state[list(L['self'].state.keys())[0]]['step'], Tensor, DispatchKeySet(CUDA, BackendSelect, ADInplaceOrView, AutogradCUDA), torch.float32, device=0, requires_grad=False, size=[], stride=[])  # has_complex = self._init_group(group, params_with_grad, grads, mus, axs, etas, state_steps)  # optim/asgd.py:117 in step

...

V0815 11:12:47.974065 139832451274560 torch/_dynamo/guards.py:1085] [2/1] [__guards] check_tensor(L['self'].state[list(L['self'].state.keys())[9]]['step'], Tensor, DispatchKeySet(CUDA, BackendSelect, ADInplaceOrView, AutogradCUDA), torch.float32, device=0, requires_grad=False, size=[], stride=[])  # has_complex = self._init_group(group, params_with_grad, grads, mus, axs, etas, state_steps)  # optim/asgd.py:117 in step
```

Personally I think that ASGD is the right implementation, although there is no error in adagrad now, it does not behave as expected. 

### Minified repro

```
import torch
import torch.nn as nn
import torch.optim as optim
import logging
torch._logging.set_logs(dynamo = logging.DEBUG, inductor = logging.DEBUG, bytecode = True, aot_graphs = True)


# Set Manual Seed
torch.manual_seed(seed=2024)
torch.cuda.manual_seed(seed=2024)

class SimpleLinearModel(nn.Module):
    def __init__(self, input_size, output_size):
        super(SimpleLinearModel, self).__init__()
        self.linear = nn.Linear(input_size, output_size)

    def forward(self, x):
        return self.linear(x)

input_size = 10
output_size = 1


model_graph = SimpleLinearModel(input_size, output_size).cuda()
criterion_graph = nn.MSELoss().cuda()
inputs_graph = torch.randn(5, input_size).cuda()
targets_graph = torch.randn(5, output_size).cuda()
optimizer_graph = optim.Adagrad(model_graph.parameters(), lr=0.01,foreach=False)


def opt_eager():
    optimizer_graph.step()
opt_graph = torch.compile(opt_eager, backend='inductor', fullgraph=False)

for epoch in range(20):
    print(f">> Epoch {epoch+1} begin")

    # graph optimizer
    optimizer_graph.zero_grad()
    outputs_graph = model_graph(inputs_graph)
    loss_g = criterion_graph(outputs_graph, targets_graph)
    loss_g.backward()
    opt_graph() # opt_eager()
    epoch_graph_loss = round(loss_g.item(), 4)
    print(f'>>>>> Epoch [{epoch+1}/20], graph optimizer loss: {loss_g.item():.4f}')
```

### Versions

Collecting environment information...
PyTorch version: 2.3.1+cu118
Is debug build: False
CUDA used to build PyTorch: 11.8
ROCM used to build PyTorch: N/A

OS: Ubuntu 22.04 LTS (x86_64)
GCC version: (Ubuntu 11.4.0-1ubuntu1~22.04) 11.4.0
Clang version: Could not collect
CMake version: version 3.22.1
Libc version: glibc-2.35

Python version: 3.8.18 (default, Sep 11 2023, 13:40:15)  [GCC 11.2.0] (64-bit runtime)
Python platform: Linux-5.15.0-25-generic-x86_64-with-glibc2.17
Is CUDA available: True
CUDA runtime version: 12.1.66
CUDA_MODULE_LOADING set to: LAZY
GPU models and configuration: 
GPU 0: NVIDIA A800-SXM4-80GB

Nvidia driver version: 535.154.05
cuDNN version: Probably one of the following:
/usr/lib/x86_64-linux-gnu/libcudnn.so.9.1.1
/usr/lib/x86_64-linux-gnu/libcudnn_adv.so.9.1.1
/usr/lib/x86_64-linux-gnu/libcudnn_cnn.so.9.1.1
/usr/lib/x86_64-linux-gnu/libcudnn_engines_precompiled.so.9.1.1
/usr/lib/x86_64-linux-gnu/libcudnn_engines_runtime_compiled.so.9.1.1
/usr/lib/x86_64-linux-gnu/libcudnn_graph.so.9.1.1
/usr/lib/x86_64-linux-gnu/libcudnn_heuristic.so.9.1.1
/usr/lib/x86_64-linux-gnu/libcudnn_ops.so.9.1.1
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, 57 bits virtual
Byte Order:                      Little Endian
CPU(s):                          112
On-line CPU(s) list:             0-111
Vendor ID:                       GenuineIntel
Model name:                      Intel(R) Xeon(R) Gold 6330 CPU @ 2.00GHz
CPU family:                      6
Model:                           106
Thread(s) per core:              2
Core(s) per socket:              28
Socket(s):                       2
Stepping:                        6
CPU max MHz:                     3100.0000
CPU min MHz:                     800.0000
BogoMIPS:                        4000.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 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 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 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:                       2.6 MiB (56 instances)
L1i cache:                       1.8 MiB (56 instances)
L2 cache:                        70 MiB (56 instances)
L3 cache:                        84 MiB (2 instances)
NUMA node(s):                    2
NUMA node0 CPU(s):               0-27,56-83
NUMA node1 CPU(s):               28-55,84-111
Vulnerability Itlb multihit:     Not affected
Vulnerability L1tf:              Not affected
Vulnerability Mds:               Not affected
Vulnerability Meltdown:          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
Vulnerability Srbds:             Not affected
Vulnerability Tsx async abort:   Not affected

Versions of relevant libraries:
[pip3] numpy==1.24.4
[pip3] torch==2.3.1+cu118
[pip3] triton==2.3.1
[conda] numpy                     1.24.4                   pypi_0    pypi
[conda] torch                     2.3.1+cu118              pypi_0    pypi
[conda] triton                    2.3.1                    pypi_0    pypi

cc @vincentqb @jbschlosser @albanD @janeyx99 @crcrpar @ezyang @chauhang @penguinwu @voznesenskym @EikanWang @jgong5 @Guobing-Chen @XiaobingSuper @zhuhaozhe @blzheng @wenzhe-nrv @jiayisunx @chenyang78 @kadeng @amjames @mlazos