Repository: pytorch
Issue: OneCycleLR's state_dict includes a full reference to the optimizer
Labels: module: optimizer,triaged,needs design,module: LrScheduler

### 🐛 Describe the bug

When reading PyTorch documentation (and the base `LRScheduler` class's implementation of `state_dict`), it is clear that the intention behind a learning rate scheduler's `state_dict` method is that it should _NOT_ include the optimizer.

However, the `OneCycleLR` does include (indirectly) a reference to the optimizer in its `state_dict`. This can be reproduced with this snippet of code:

```python
import os
import tempfile

import torch


def main():
    """Main."""
    model = torch.nn.Linear(3, 5)
    optimizer = torch.optim.SGD(model.parameters(), lr=1e-5)
    lr_scheduler = torch.optim.lr_scheduler.OneCycleLR(
        optimizer=optimizer, max_lr=1e-5, total_steps=123
    )

    _, f = tempfile.mkstemp()
    try:
        torch.save(lr_scheduler.state_dict(), f)
        # Evidently, when saving (and therefore, reloading) the LRS's state, the "anneal_func"
        # is serialized as a bound method of the optimizer. This means it has a reference, via
        # `__self__`, to the optimizer instance. This in turn means that the _entire_ optimizer
        # object itself is pickled into the state - which means so is its reference to the
        # optimizer!
        lr_state = torch.load(f)

        print(lr_state["anneal_func"].__self__.optimizer.param_groups)
    finally:
        os.remove(f)


if __name__ == "__main__":
    main()
```

# Suggestion for a fix.

Override the `OneCycleLR.state_dict` to change how it serializes the `anneal_func`.

### Versions

The snippet of code was run using the `pytorch/pytorch:2.0.1-cuda11.7-cudnn8-runtime` docker container.

```
Python version: 3.10.11 (main, Apr 20 2023, 19:02:41) [GCC 11.2.0] (64-bit runtime)
Python platform: Linux-5.4.0-66-generic-x86_64-with-glibc2.31
Is CUDA available: False
CUDA runtime version: No CUDA
CUDA_MODULE_LOADING set to: N/A
GPU models and configuration: No CUDA
Nvidia driver version: No CUDA
cuDNN version: No CUDA
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:                   46 bits physical, 48 bits virtual
CPU(s):                          16
On-line CPU(s) list:             0-15
Thread(s) per core:              2
Core(s) per socket:              8
Socket(s):                       1
NUMA node(s):                    1
Vendor ID:                       GenuineIntel
CPU family:                      6
Model:                           85
Model name:                      Intel(R) Core(TM) i7-9800X CPU @ 3.80GHz
Stepping:                        4
CPU MHz:                         1200.245
CPU max MHz:                     4500.0000
CPU min MHz:                     1200.0000
BogoMIPS:                        7599.80
Virtualization:                  VT-x
L1d cache:                       256 KiB
L1i cache:                       256 KiB
L2 cache:                        8 MiB
L3 cache:                        16.5 MiB
NUMA node0 CPU(s):               0-15
Vulnerability Itlb multihit:     KVM: Mitigation: Split huge pages
Vulnerability L1tf:              Mitigation; PTE Inversion; VMX conditional cache flushes, SMT vulnerable
Vulnerability Mds:               Mitigation; Clear CPU buffers; SMT vulnerable
Vulnerability Meltdown:          Mitigation; PTI
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; Full generic retpoline, IBPB conditional, IBRS_FW, STIBP conditional, RSB filling
Vulnerability Srbds:             Not affected
Vulnerability Tsx async abort:   Mitigation; Clear CPU buffers; SMT vulnerable
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 monitor ds_cpl vmx 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 cdp_l3 invpcid_single pti ssbd mba ibrs ibpb stibp tpr_shadow vnmi flexpriority ept vpid ept_ad 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 xsaves 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 md_clear flush_l1d

Versions of relevant libraries:
[pip3] numpy==1.24.3
[pip3] torch==2.0.1
[pip3] torchaudio==2.0.2
[pip3] torchdata==0.6.1
[pip3] torchelastic==0.2.2
[pip3] torchtext==0.15.2
[pip3] torchvision==0.15.2
[pip3] triton==2.0.0
[conda] blas                      1.0                         mkl
[conda] ffmpeg                    4.3                  hf484d3e_0    pytorch
[conda] mkl                       2023.1.0         h6d00ec8_46342
[conda] mkl-service               2.4.0           py310h5eee18b_1
[conda] mkl_fft                   1.3.6           py310h1128e8f_1
[conda] mkl_random                1.2.2           py310h1128e8f_1
[conda] numpy                     1.24.3          py310h5f9d8c6_1
[conda] numpy-base                1.24.3          py310hb5e798b_1
[conda] pytorch                   2.0.1           py3.10_cuda11.7_cudnn8.5.0_0    pytorch
[conda] pytorch-cuda              11.7                 h778d358_5    pytorch
[conda] pytorch-mutex             1.0                        cuda    pytorch
[conda] torchaudio                2.0.2               py310_cu117    pytorch
[conda] torchdata                 0.6.1                     py310    pytorch
[conda] torchelastic              0.2.2                    pypi_0    pypi
[conda] torchtext                 0.15.2                    py310    pytorch
[conda] torchtriton               2.0.0                     py310    pytorch
[conda] torchvision               0.15.2              py310_cu117    pytorch```

cc @vincentqb @jbschlosser @albanD @janeyx99 @crcrpar