Skip to main content
ggml provides two built-in optimizers: AdamW and SGD. Both are configured through the ggml_opt_optimizer_params struct and supplied to the optimizer context via a callback.

Optimizer types

AdamW is the recommended default for most deep learning tasks. It maintains per-parameter first and second moment estimates and applies decoupled weight decay.
AdamW requires two additional momentum tensors (m and v) per trainable parameter tensor. This increases memory usage relative to SGD.

Optimizer params callbacks

The optimizer does not read ggml_opt_optimizer_params directly. Instead, it calls a ggml_opt_get_optimizer_params callback before each backward pass, allowing you to change hyperparameters dynamically during training (for example, to implement a learning rate schedule).
The userdata pointer carries arbitrary context to the callback. When using ggml_opt_fit, userdata is a pointer to the current epoch number (int64_t *).

Built-in callbacks

Use ggml_opt_get_constant_optimizer_params when you want to supply fixed hyperparameters without writing a custom callback:

Custom learning rate schedule

Because ggml_opt_fit passes a pointer to the current epoch as userdata, you can implement epoch-dependent schedules:
When using ggml_opt_epoch directly (instead of ggml_opt_fit), you are responsible for calling your callback and passing userdata. The epoch pointer convention only applies to ggml_opt_fit.

ggml_opt_params struct

ggml_opt_params configures the full optimization context, including backend, loss, build type, and optimizer.
Use ggml_opt_default_params to get a struct with sensible defaults, then override individual fields:

Context lifecycle

ggml_opt_reset with optimizer = false clears accumulated gradients and resets the loss scalar without discarding the optimizer’s internal momentum state. Pass true to perform a full reset, which is equivalent to starting a fresh training run with the same graph.