ggml-opt.h. It handles dataset batching, gradient accumulation, forward and backward passes, and optimizer steps — so you can focus on defining your model graph.
Workflow
1
Select a loss type
Choose the loss function that matches your problem. The built-in options cover most supervised learning tasks:Use
MEAN or SUM when your graph already computes a meaningful scalar loss and you only need the optimizer to minimize it.2
Create a dataset
Allocate a dataset and populate its
data and labels tensors with your training samples. See Datasets for full details.3
Build a GGML graph
Define your model as a GGML computation graph with
no_alloc = true. Use two separate contexts:- Parameters context — holds model weights and the
inputstensor. Allocate this statically in your code; its data remains valid throughout training. - Compute context — holds all intermediate tensors. The optimizer reallocates this context automatically; do not read its tensor data directly.
The second dimension of
inputs and outputs is interpreted as the batch size (number of datapoints). Make sure it matches ndata_batch in your dataset batching.4
Fit the model
Call For more control over the loop — custom callbacks, per-batch metrics, or mid-epoch checkpointing — use
ggml_opt_fit to run the full training loop. It handles shuffling, batching, gradient accumulation, validation splits, and epoch reporting.ggml_opt_epoch instead.ggml_opt_fit parameters
Static vs dynamic graph allocation
The optimizer context supports two graph allocation modes:- Static allocation
- Dynamic allocation
Set
ctx_compute, inputs, and outputs on the ggml_opt_params struct before calling ggml_opt_init. The optimizer allocates the forward, gradient, and optimizer graphs once at initialization and reuses them for every evaluation.This is the mode used by ggml_opt_fit. Prefer static allocation when the graph topology is fixed across all batches.Build types
Thebuild_type field on ggml_opt_params controls which graphs the optimizer constructs:
Optimizers
Configure AdamW and SGD, set learning rate schedules, and manage the optimizer context.
Datasets
Initialize datasets, populate tensors, shuffle data, and write custom epoch callbacks.
