Skip to main content
ggml supports automatic differentiation through reverse-mode (backpropagation). Every operation that has a differentiable implementation provides both a forward function and a backward function. The backward function computes the adjoint of each input tensor given the adjoint of the output.

How it works

  1. Forward pass — define the function and compute its value.
  2. Backward pass — ggml automatically builds gradient nodes that propagate the loss gradient back through every operation in the graph.
  3. Read gradients — retrieve the gradient tensor for any parameter after computation.

Marking trainable parameters

Call ggml_set_param to mark a tensor as a trainable parameter. This sets GGML_TENSOR_FLAG_PARAM on the tensor and tells the autodiff engine to compute gradients for it.
ggml_set_param does not allocate a gradient tensor immediately. Gradient storage is allocated when you call ggml_build_backward_expand.

Full example: f(x) = a·x² + b

This example is taken directly from the ggml.h header comments.

Define the function

Build forward and backward graphs

Set values and compute

Read gradients

ggml_build_backward_expand

  • ctx — the context used to allocate gradient tensors
  • cgraph — a forward graph previously built with ggml_build_forward_expand; must have been created with grads = true
  • grad_accs — array of ggml_tensor * with one entry per output node in the forward graph; pass NULL entries to have ggml allocate gradient accumulator tensors automatically
After this call, the graph contains both forward and backward nodes. Calling ggml_graph_compute will execute them in the correct order.

Accessing gradients

ggml_graph_get_grad returns NULL for tensors that are not reachable by any parameter in the graph (i.e., tensors where no gradient flows).

Gradient accumulation

ggml supports accumulating gradients across multiple forward/backward passes before applying an optimizer step — useful for simulating larger batch sizes.
ggml_graph_reset zeroes gradient accumulators and sets the loss gradient seed to 1.0. Call it once at the start of each accumulation window.

Loss tensors

Mark the final scalar output as a loss to signal the optimizer:
Multiple loss tensors sum together. The backward pass seeds these tensors with gradient 1.0 automatically.

High-level training API

For training workloads, ggml-opt.h provides a higher-level interface that manages forward/backward graph construction, gradient accumulation, and optimizer steps:
See ggml-opt.h for the full API.