Repository: pytorch
Issue: ChainedScheduler fail on CosineAnnealingWarmRestarts
Labels: module: optimizer,triaged,module: LrScheduler

### 🐛 Describe the bug

Trying to reproduce a learning rate scheduler as below, happen to find anomaly chaining CosineAnnealingWarmRestarts with MultiStepLR in either order, as contrasted by chaining CosineAnnealingLR with MultiStepLR in either order.

<img src="https://github.com/pytorch/pytorch/assets/12207447/9eccc60f-434e-483e-81b6-1567c846dc8d" height="300">

A minimal code to reproduce the bug:
```import torch.optim

def chainCosRestart_w_MultiStep():
    cos_restart_scheduler = torch.optim.lr_scheduler.CosineAnnealingWarmRestarts(optimizer, T_0=50*n_batches, T_mult=1, eta_min=1e-12)
    multi_step_scheduler = torch.optim.lr_scheduler.MultiStepLR(optimizer, milestones=[1, 2, 3], gamma=0.1)
    chained_scheduler = torch.optim.lr_scheduler.ChainedScheduler([cos_restart_scheduler, multi_step_scheduler])
    learning_rates = []
    for _ in range(10):
        optimizer.step()
        learning_rates.append(optimizer.param_groups[0]['lr'])
        chained_scheduler.step()
    return learning_rates

def chainMultiStep_w_CosRestart():
    cos_restart_scheduler = torch.optim.lr_scheduler.CosineAnnealingWarmRestarts(optimizer, T_0=50*n_batches, T_mult=1, eta_min=1e-12)
    multi_step_scheduler = torch.optim.lr_scheduler.MultiStepLR(optimizer, milestones=[1, 2, 3], gamma=0.1)
    chained_scheduler = torch.optim.lr_scheduler.ChainedScheduler([multi_step_scheduler,cos_restart_scheduler])
    learning_rates = []
    for _ in range(10):
        optimizer.step()
        learning_rates.append(optimizer.param_groups[0]['lr'])
        chained_scheduler.step()
    return learning_rates

def chainMultiStep_w_CosAnneal():
    cos_anneal_scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=50*n_batches, eta_min=1e-12)
    multi_step_scheduler = torch.optim.lr_scheduler.MultiStepLR(optimizer, milestones=[1, 2, 3], gamma=0.1)
    chained_scheduler = torch.optim.lr_scheduler.ChainedScheduler([multi_step_scheduler,cos_anneal_scheduler])
    learning_rates = []
    for _ in range(10):
        optimizer.step()
        learning_rates.append(optimizer.param_groups[0]['lr'])
        chained_scheduler.step()
    return learning_rates

def chainCosAnneal_w_MultiStep():
    cos_anneal_scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=50*n_batches, eta_min=1e-12)
    multi_step_scheduler = torch.optim.lr_scheduler.MultiStepLR(optimizer, milestones=[1, 2, 3], gamma=0.1)
    chained_scheduler = torch.optim.lr_scheduler.ChainedScheduler([cos_anneal_scheduler,multi_step_scheduler])
    learning_rates = []
    for _ in range(10):
        optimizer.step()
        learning_rates.append(optimizer.param_groups[0]['lr'])
        chained_scheduler.step()
    return learning_rates
    

if __name__ == '__main__':
    n_batches = 300
    optimizer = torch.optim.Adam([torch.randn(3, requires_grad=True)], lr=0.001, weight_decay=0.0001)
    learning_rates = chainCosRestart_w_MultiStep()
    # MultiStep added weird effect: [0.001, 9.999999890337731e-05, 9.999999561350923e-05, 9.999999013039594e-05, 0.0009999998245403766, 0.0009999997258443476, 0.0009999996052158764, 0.0009999994626549683, 0.0009999992981616298, 0.0009999991117358679]
    learning_rates = chainMultiStep_w_CosRestart()
    # MultiStep does not work at all: [0.001, 0.000999999989033773, 0.0009999999561350922, 0.0009999999013039593, 0.0009999998245403766, 0.0009999997258443476, 0.0009999996052158764, 0.0009999994626549683, 0.0009999992981616298, 0.0009999991117358679]
    learning_rates = chainMultiStep_w_CosAnneal()
    # Works as expected: [0.001, 9.999999890337731e-05, 9.999999561350957e-06, 9.999999013040174e-07, 9.999998245405116e-07, 9.999997258445811e-07, 9.999996052162305e-07, 9.99999462655465e-07, 9.999992981622906e-07, 9.999991117367148e-07]
    learning_rates = chainCosAnneal_w_MultiStep()
    # Works as expected: [0.001, 9.999999890337731e-05, 9.999999561350928e-06, 9.999999013039653e-07, 9.999998245404595e-07, 9.99999725844529e-07, 9.999996052161784e-07, 9.999994626554128e-07, 9.999992981622385e-07, 9.999991117366627e-07]```

 

### Versions

```Collecting environment information...
PyTorch version: 2.3.1
Is debug build: False
CUDA used to build PyTorch: 12.1
ROCM used to build PyTorch: N/A

OS: Ubuntu 20.04.4 LTS (x86_64)
GCC version: (Ubuntu 9.4.0-1ubuntu1~20.04.2) 9.4.0
Clang version: Could not collect
CMake version: Could not collect
Libc version: glibc-2.31

Python version: 3.12.3 | packaged by conda-forge | (main, Apr 15 2024, 18:38:13) [GCC 12.3.0] (64-bit runtime)
Python platform: Linux-5.15.0-107-generic-x86_64-with-glibc2.31
Is CUDA available: True
CUDA runtime version: 11.3.58
CUDA_MODULE_LOADING set to: LAZY
GPU models and configuration: 
GPU 0: NVIDIA GeForce RTX 3090
GPU 1: NVIDIA GeForce RTX 3090
GPU 2: NVIDIA GeForce RTX 3090
GPU 3: NVIDIA GeForce RTX 3090

Nvidia driver version: 535.171.04
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
Address sizes:                      46 bits physical, 57 bits virtual
CPU(s):                             80
On-line CPU(s) list:                0-79
Thread(s) per core:                 2
Core(s) per socket:                 20
Socket(s):                          2
NUMA node(s):                       2
Vendor ID:                          GenuineIntel
CPU family:                         6
Model:                              106
Model name:                         Intel(R) Xeon(R) Silver 4316 CPU @ 2.30GHz
Stepping:                           6
CPU MHz:                            900.000
CPU max MHz:                        3400.0000
CPU min MHz:                        800.0000
BogoMIPS:                           4600.00
Virtualization:                     VT-x
L1d cache:                          1.9 MiB
L1i cache:                          1.3 MiB
L2 cache:                           50 MiB
L3 cache:                           60 MiB
NUMA node0 CPU(s):                  0-19,40-59
NUMA node1 CPU(s):                  20-39,60-79
Vulnerability Gather data sampling: Mitigation; Microcode
Vulnerability Itlb multihit:        Not affected
Vulnerability L1tf:                 Not affected
Vulnerability Mds:                  Not affected
Vulnerability Meltdown:             Not affected
Vulnerability Mmio stale data:      Mitigation; Clear CPU buffers; SMT vulnerable
Vulnerability Retbleed:             Not affected
Vulnerability Spec rstack overflow: 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; PBRSB-eIBRS SW sequence; BHI Syscall hardening, KVM SW loop
Vulnerability Srbds:                Not affected
Vulnerability Tsx async abort:      Not affected
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 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

Versions of relevant libraries:
[pip3] numpy==1.26.4
[pip3] pytorch-lightning==2.2.2
[pip3] torch==2.3.1
[pip3] torchaudio==2.3.1
[pip3] torchmetrics==1.4.0.post0
[pip3] torchvision==0.18.1
[conda] blas                      1.0                         mkl    https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/conda-forge
[conda] libblas                   3.9.0            16_linux64_mkl    https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/conda-forge
[conda] libcblas                  3.9.0            16_linux64_mkl    https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/conda-forge
[conda] liblapack                 3.9.0            16_linux64_mkl    https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/conda-forge
[conda] libopenvino-pytorch-frontend 2024.1.0             he02047a_7    https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/conda-forge
[conda] mkl                       2022.1.0           hc2b9512_224    https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main
[conda] numpy                     1.26.4          py312heda63a1_0    https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/conda-forge
[conda] pytorch                   2.3.1           py3.12_cuda12.1_cudnn8.9.2_0    pytorch
[conda] pytorch-cuda              12.1                 ha16c6d3_5    pytorch
[conda] pytorch-lightning         2.2.2              pyhd8ed1ab_0    conda-forge
[conda] pytorch-mutex             1.0                        cuda    pytorch
[conda] torchaudio                2.3.1               py312_cu121    pytorch
[conda] torchmetrics              1.4.0.post0        pyhd8ed1ab_0    conda-forge
[conda] torchvision               0.18.1              py312_cu121    pytorch```


cc @vincentqb @jbschlosser @albanD @janeyx99 @crcrpar