Skip to main content
The optimizer API provides a complete training loop abstraction on top of GGML’s computation graph primitives. It manages graph construction, gradient accumulation, loss computation, and parameter updates in a unified interface.
This module is maintained by Johannes Gäßler. The high-level functions (ggml_opt_epoch, ggml_opt_fit) are designed to be copied and adapted directly into user code.

Enums

ggml_opt_loss_type

Controls how the scalar loss value is derived from the model outputs.

ggml_opt_build_type

Controls how much of the computation graph is built.

ggml_opt_optimizer_type

Optimizer parameters

ggml_opt_optimizer_params

Holds hyperparameters for both supported optimizers. Only the fields for the active optimizer type are used.
AdamW fields:
float
Learning rate. Controls the step size at each parameter update. Typical values: 1e-4 to 1e-2.
float
Exponential decay rate for the first moment estimate. Default: 0.9.
float
Exponential decay rate for the second moment estimate. Default: 0.999.
float
Small constant added to the denominator for numerical stability. Default: 1e-8.
float
Weight decay coefficient. Set to 0.0f to disable. Decoupled weight decay as in the AdamW paper.
SGD fields:
float
Learning rate.
float
Weight decay.

ggml_opt_get_optimizer_params callback

A function pointer called before each backward pass to obtain the current optimizer hyperparameters. Use this to implement learning rate schedules. Two built-in implementations are provided:
  • ggml_opt_get_default_optimizer_params — returns hard-coded default values; ignores userdata.
  • ggml_opt_get_constant_optimizer_params — casts userdata to struct ggml_opt_optimizer_params * and returns it directly.

ggml_opt_params

Configuration struct for creating an optimization context.
ggml_backend_sched_t
required
Backend scheduler used to build and execute the forward and backward graphs.
struct ggml_context *
When set alongside inputs and outputs, graphs are allocated statically once and reused. When NULL, a new graph is built for each evaluation.
struct ggml_tensor *
Input tensor. The second dimension is interpreted as the batch size (number of datapoints).
struct ggml_tensor *
Output tensor. Must have shape [ne_label, ndata_batch] when labels are used.
enum ggml_opt_loss_type
required
Which loss function to minimize.
enum ggml_opt_build_type
required
Whether to build a forward-only, gradient, or full optimization graph.
int32_t
Number of gradient accumulation steps before each optimizer parameter update. Set to 1 for standard SGD/AdamW without accumulation.
ggml_opt_get_optimizer_params
Callback invoked before each backward pass to retrieve the current optimizer hyperparameters.
enum ggml_opt_optimizer_type
required
Which optimizer to use (ADAMW or SGD).
Get a params struct with sensible defaults using:

Context lifecycle

Creates and initializes an optimization context.
struct ggml_opt_params
required
Configuration for the optimizer. Use ggml_opt_default_params to start from sensible defaults.
Returns a new context. Free with ggml_opt_free.
Destroys an optimization context and releases all associated memory.
ggml_opt_context_t
required
The context to free.
Zeroes gradients, resets the loss accumulator, and optionally resets optimizer state (e.g. Adam moment estimates).
ggml_opt_context_t
required
The context to reset.
bool
required
When true, also resets the optimizer’s internal state (first/second moment estimates for AdamW). Pass false to only zero gradients and the loss.

Tensor accessors

These functions return pointers to the internal tensors managed by the optimization context.
When not using static graphs, these pointers become invalid after the next call to ggml_opt_alloc.
Returns the input tensor of the forward graph.
Returns the output tensor of the forward graph.
Returns the labels tensor used to compute the loss.
Returns the scalar tensor that holds the current loss value after ggml_opt_eval.

Optimization result

ggml_opt_result_t accumulates statistics (loss, accuracy, number of datapoints) across multiple evaluation steps.
Creates a new, empty result object.
Free with ggml_opt_result_free.
Writes the total number of datapoints processed into *ndata.
ggml_opt_result_t
required
The result to query.
int64_t *
required
Output: number of datapoints.
Writes the accumulated loss and its standard uncertainty into the output pointers.
ggml_opt_result_t
required
The result to query.
double *
required
Output: mean loss over all datapoints.
double *
Output: standard uncertainty of the loss estimate. Pass NULL to ignore.
Writes classification accuracy and its standard uncertainty into the output pointers.
ggml_opt_result_t
required
The result to query.
double *
required
Output: fraction of correctly classified datapoints in [0, 1].
double *
Output: standard uncertainty. Pass NULL to ignore.

Low-level computation

These functions give you fine-grained control over graph allocation and evaluation. Use them when ggml_opt_epoch or ggml_opt_fit do not offer enough flexibility.
Sets the graph, inputs, and outputs for the next call to ggml_opt_alloc. Required when not using static graphs.
ggml_opt_context_t
required
The optimization context.
struct ggml_context *
required
The context containing temporarily allocated compute tensors.
struct ggml_cgraph *
required
The forward computation graph.
struct ggml_tensor *
required
Input tensor in gf.
struct ggml_tensor *
required
Output tensor in gf.
Allocates the next graph for evaluation. Must be called exactly once before each call to ggml_opt_eval.
ggml_opt_context_t
required
The optimization context.
bool
required
When true, the backward graph (for gradient computation and parameter update) is allocated in addition to the forward graph.
Executes the allocated graph. Performs a forward pass, increments the result, and (if the backward graph was allocated) performs the backward pass.
ggml_opt_context_t
required
The optimization context.
ggml_opt_result_t
Result object to increment with the statistics from this evaluation. Pass NULL to discard statistics.

High-level training API

ggml_opt_epoch_callback

A callback invoked after each batch evaluation during ggml_opt_epoch.
A built-in implementation ggml_opt_epoch_callback_progress_bar prints a progress bar to stderr.
Runs one epoch: trains on the front portion of the dataset and evaluates on the back portion.
ggml_opt_context_t
required
The optimization context.
ggml_opt_dataset_t
required
The dataset to iterate over.
ggml_opt_result_t
Result object incremented during the training portion. Pass NULL to discard.
ggml_opt_result_t
Result object incremented during the validation portion. Pass NULL to discard.
int64_t
required
Datapoint index that separates training (indices [0, idata_split)) from validation (indices [idata_split, ndata)).
ggml_opt_epoch_callback
Called after each training batch. Pass NULL for no callback.
ggml_opt_epoch_callback
Called after each validation batch. Pass NULL for no callback.
Fits the model to a dataset over multiple epochs. This is the highest-level training entry point.
ggml_backend_sched_t
required
Backend scheduler used to build and run the compute graphs.
struct ggml_context *
required
Context containing temporarily allocated tensors for the forward pass.
struct ggml_tensor *
required
Input tensor with shape [ne_datapoint, ndata_batch].
struct ggml_tensor *
required
Output tensor. Must have shape [ne_label, ndata_batch] when labels are used.
ggml_opt_dataset_t
required
Dataset containing training data and optionally labels.
enum ggml_opt_loss_type
required
The loss function to minimize.
enum ggml_opt_optimizer_type
required
Which optimizer to use.
ggml_opt_get_optimizer_params
required
Callback to retrieve optimizer hyperparameters. The userdata passed is a pointer to the current epoch number (int64_t *).
int64_t
required
Number of times to iterate over the full dataset.
int64_t
required
Number of datapoints per logical optimizer step. Must be a multiple of the physical batch size (second dimension of inputs/outputs).
float
required
Fraction of the dataset reserved for validation. Must be in [0.0, 1.0). Pass 0.0 to skip validation.
bool
required
When true, suppresses all progress output to stderr.