Repository: pytorch
Issue: Default optimizer options are ignored in the C++ API
Labels: module: cpp,module: optimizer,triaged,actionable

### 🐛 Describe the bug

This standalone C++ program creates an optimizer with 3 param groups of a single tensor each. The tensor are initialized to 1. It also has default options that set the learning rate to 0, and the param groups are not setting their learning rate. It then computes a backward pass and runs an optimization step, printing the tensors modified by the optimizer:
```
#include <torch/torch.h>
#include <iostream>

using namespace torch;

int main() {
  Tensor input = torch::ones({1, 3});
  Tensor w = torch::ones({2, 3});
  Tensor b = torch::ones({1, 2});
  Tensor output;

  input.set_requires_grad(true);
  w.set_requires_grad(true);
  b.set_requires_grad(true);   

  std::vector<optim::OptimizerParamGroup> param_groups;

  // Param group for input tensor
  auto *input_adam_opts = new optim::AdamOptions();
  input_adam_opts->weight_decay(0.11);
  optim::OptimizerOptions *input_opts = input_adam_opts;
  param_groups.push_back(
    optim::OptimizerParamGroup(
      std::vector<Tensor>({input}),
      std::unique_ptr<optim::OptimizerOptions>(input_opts)
    )
  );

  // Param group for w tensor
  auto *w_adam_opts = new optim::AdamOptions();
  w_adam_opts->weight_decay(0.22);
  optim::OptimizerOptions *w_opts = w_adam_opts;
  param_groups.push_back(
    optim::OptimizerParamGroup(
      std::vector<Tensor>({w}),
      std::unique_ptr<optim::OptimizerOptions>(w_opts)
    )
  );

  // Param group for b tensor
  auto *b_adam_opts = new optim::AdamOptions();
  b_adam_opts->weight_decay(0.33);
  optim::OptimizerOptions *b_opts = b_adam_opts;
  param_groups.push_back(
    optim::OptimizerParamGroup(
      std::vector<Tensor>({b}),
      std::unique_ptr<optim::OptimizerOptions>(b_opts)
    )
  );

  // Default options and optimizer creation
  optim::AdamOptions default_opts;
  default_opts.lr(0);
  auto optimizer = optim::Adam(param_groups, default_opts);

  output = at::linear(input, w, b);
  Tensor outgrad = torch::ones({1, 2});
  output.backward(outgrad);

  optimizer.step();
  std::cout << "input:" << std::endl;
  std::cout << input << "\n";
  std::cout << "w:" << std::endl;
  std::cout << w << "\n";
  std::cout << "b:" << std::endl;
  std::cout << b << "\n";

  std::cout << "\n";

  std::vector<torch::optim::OptimizerParamGroup> retrieved_param_groups = 
    optimizer.param_groups();

  auto *group_0_opts = static_cast<torch::optim::AdamOptions*>(
    &(retrieved_param_groups[0].options())
  );
  std::cout << "input weight decay:\n";
  std::cout << group_0_opts->weight_decay() <<"\n";
  std::cout << "input learning rate:\n";
  std::cout << group_0_opts->lr() <<"\n";

  std::cout << "\n";

  auto *group_1_opts = static_cast<torch::optim::AdamOptions*>(
    &(retrieved_param_groups[1].options())
  );
  std::cout << "w weight decay:\n";
  std::cout << group_1_opts->weight_decay() <<"\n";
  std::cout << "w learning rate:\n";
  std::cout << group_1_opts->lr() <<"\n";

  std::cout << "\n";

  auto *group_2_opts = static_cast<torch::optim::AdamOptions*>(
    &(retrieved_param_groups[2].options())
  );
  std::cout << "b weight decay:\n";
  std::cout << group_2_opts->weight_decay() <<"\n";
  std::cout << "b learning rate:\n";
  std::cout << group_2_opts->lr() <<"\n";
}
```

The output is:
```
input:
 0.9990  0.9990  0.9990
[ CPUFloatType{1,3} ]
w:
 0.9990  0.9990  0.9990
 0.9990  0.9990  0.9990
[ CPUFloatType{2,3} ]
b:
 0.9990  0.9990
[ CPUFloatType{1,2} ]

input weight decay:
0.11
input learning rate:
0.001

w weight decay:
0.22
w learning rate:
0.001

b weight decay:
0.33
b learning rate:
0.001
```

So it can be seen that setting the learning rate to 0 in the default options is ignored, the tensor have changed after the step. And retrieving the param group options shows that they are using a learning rate of 0.001.

### Versions

I have built from source using commit `23c0d2689e4b49858787adc6ca2c5032ac221b96`. This is the `cmake` command:

```
cmake \
	-DCMAKE_BUILD_TYPE=Release \
	-DBUILD_PYTHON=False \
	-DCMAKE_INSTALL_PREFIX=$home_dir/torch \
	-DTORCH_BUILD_VERSION=2.6.0a0+git23c0d26 \
	-DUSE_NUMPY=False \
```

This is the output of the `collect_env.py` script:

```
PyTorch version: N/A
Is debug build: N/A
CUDA used to build PyTorch: N/A
ROCM used to build PyTorch: N/A

OS: Ubuntu 24.04.1 LTS (x86_64)
GCC version: (Ubuntu 13.2.0-23ubuntu4) 13.2.0
Clang version: Could not collect
CMake version: version 3.31.1
Libc version: glibc-2.39

Python version: 3.12.3 (main, Nov  6 2024, 18:32:19) [GCC 13.2.0] (64-bit runtime)
Python platform: Linux-6.8.0-49-generic-x86_64-with-glibc2.39
Is CUDA available: N/A
CUDA runtime version: Could not collect
CUDA_MODULE_LOADING set to: N/A
GPU models and configuration: GPU 0: NVIDIA GeForce GTX 1650
Nvidia driver version: 550.120
cuDNN version: Could not collect
HIP runtime version: N/A
MIOpen runtime version: N/A
Is XNNPACK available: N/A

CPU:
Architecture:                         x86_64
CPU op-mode(s):                       32-bit, 64-bit
Address sizes:                        39 bits physical, 48 bits virtual
Byte Order:                           Little Endian
CPU(s):                               16
On-line CPU(s) list:                  0-15
Vendor ID:                            GenuineIntel
Model name:                           Intel(R) Core(TM) i9-9980HK CPU @ 2.40GHz
CPU family:                           6
Model:                                158
Thread(s) per core:                   2
Core(s) per socket:                   8
Socket(s):                            1
Stepping:                             13
CPU(s) scaling MHz:                   85%
CPU max MHz:                          5000.0000
CPU min MHz:                          800.0000
BogoMIPS:                             4800.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 monitor ds_cpl vmx est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch cpuid_fault epb ssbd ibrs ibpb stibp ibrs_enhanced tpr_shadow flexpriority ept vpid ept_ad fsgsbase tsc_adjust sgx bmi1 avx2 smep bmi2 erms invpcid mpx rdseed adx smap clflushopt intel_pt xsaveopt xsavec xgetbv1 xsaves dtherm ida arat pln pts hwp hwp_notify hwp_act_window hwp_epp vnmi sgx_lc md_clear flush_l1d arch_capabilities
Virtualization:                       VT-x
L1d cache:                            256 KiB (8 instances)
L1i cache:                            256 KiB (8 instances)
L2 cache:                             2 MiB (8 instances)
L3 cache:                             16 MiB (1 instance)
NUMA node(s):                         1
NUMA node0 CPU(s):                    0-15
Vulnerability Gather data sampling:   Mitigation; Microcode
Vulnerability Itlb multihit:          KVM: Mitigation: VMX disabled
Vulnerability L1tf:                   Not affected
Vulnerability Mds:                    Not affected
Vulnerability Meltdown:               Not affected
Vulnerability Mmio stale data:        Mitigation; Clear CPU buffers; 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:                  Mitigation; Microcode
Vulnerability Tsx async abort:        Mitigation; TSX disabled

Versions of relevant libraries:
[pip3] numpy==1.26.3
[pip3] nvidia-cublas-cu11==11.11.3.6
[pip3] nvidia-cuda-cupti-cu11==11.8.87
[pip3] nvidia-cuda-nvrtc-cu11==11.8.89
[pip3] nvidia-cuda-runtime-cu11==11.8.89
[pip3] nvidia-cudnn-cu11==9.1.0.70
[pip3] nvidia-cufft-cu11==10.9.0.58
[pip3] nvidia-curand-cu11==10.3.0.86
[pip3] nvidia-cusolver-cu11==11.4.1.48
[pip3] nvidia-cusparse-cu11==11.7.5.86
[pip3] nvidia-nccl-cu11==2.20.5
[pip3] nvidia-nvtx-cu11==11.8.86
[pip3] torch==2.4.1+cu118
[pip3] torchaudio==2.4.1+cu118
[pip3] torchvision==0.19.1+cu118
[pip3] triton==3.0.0
[conda] Could not collect
```

cc @vincentqb @jbschlosser @albanD @janeyx99 @crcrpar