Skip to main content
All operations take a struct ggml_context * as their first argument and return a struct ggml_tensor * representing the result. Operations do not perform any computation — they record a node in the computation graph. Computation only happens when ggml_graph_compute() or ggml_graph_compute_with_ctx() is called. Most operations have an _inplace variant that writes results back into the first tensor operand, returning a view of it.

ggml_add

Element-wise addition a + b. b is broadcast to the shape of a when necessary.

ggml_add1

Adds the scalar value held in tensor b to every element of a.

ggml_sub

Element-wise subtraction a - b.

ggml_mul

Element-wise multiplication a * b (Hadamard product). b is broadcast to the shape of a.

ggml_div

Element-wise division a / b.

ggml_sqr

Element-wise square .

ggml_sqrt

Element-wise square root √a.

ggml_abs

Element-wise absolute value |a|.

ggml_neg

Element-wise negation -a.

ggml_log

Element-wise natural logarithm ln(a).

ggml_exp

Element-wise exponential eᵃ.

ggml_sin / ggml_cos

Element-wise trigonometric functions.

ggml_scale

Multiplies every element of a by the scalar s. Equivalent to a * s.

ggml_clamp

Clamps every element of a to [min, max]. Operates in-place and returns a view of a.

ggml_mul_mat

Matrix multiplication. a is the weight matrix (k columns, n rows) and b is the input (k columns, m rows — transposed internally). The result is n columns by m rows.
  • a: [ne03, ne02, n, k]
  • b: [ne03*x, ne02*y, m, k]
  • result: [ne03*x, ne02*y, m, n]
a may be quantized; b must be F32 or F16.

ggml_mul_mat_set_prec

Overrides the accumulation precision of a ggml_mul_mat result tensor. Set to GGML_PREC_F32 for higher-precision accumulation (useful for models like Phi-2).

ggml_mul_mat_id

Indirect matrix multiplication. Selects one of the weight matrices from as using the row indices in ids, then multiplies by b. Used in mixture-of-experts routing.

ggml_out_prod

Outer product. a is [m, n], b is [p, n], result is [m, p].

ggml_relu

Rectified linear unit: max(0, a) element-wise.

ggml_leaky_relu

Leaky ReLU: a >= 0 ? a : negative_slope * a.

ggml_gelu

Gaussian Error Linear Unit. Uses the standard approximation based on tanh.

ggml_gelu_erf

GELU computed using the error function (erf) when available. Some backends may fall back to the Abramowitz and Stegun approximation.

ggml_gelu_quick

Faster GELU approximation.

ggml_silu

Sigmoid Linear Unit: a * sigmoid(a).

ggml_silu_back

Backward pass of SiLU. Returns dx given x and dy.

ggml_sigmoid

Logistic sigmoid: 1 / (1 + exp(-a)).

ggml_tanh

Hyperbolic tangent.

ggml_elu

Exponential Linear Unit: a >= 0 ? a : exp(a) - 1.

ggml_hardswish / ggml_hardsigmoid

  • hardswish(x) = x * relu6(x + 3) / 6
  • hardsigmoid(x) = relu6(x + 3) / 6

Gated linear units

ggml provides fused GLU variants that split or gate the activation in a single op:

ggml_norm

Layer normalization along rows. Subtracts the row mean and divides by the row standard deviation. eps is added to the variance before taking the square root for numerical stability.

ggml_rms_norm

Root mean square normalization along rows. Divides each row by its RMS. Commonly used in LLaMA-style transformers.

ggml_l2_norm

L2 normalization along rows. Divides each row by its L2 norm. Used in RWKV v7.

ggml_group_norm

Group normalization along ne0 * ne1 / n_groups channels. Commonly used in image models such as Stable Diffusion.
int
required
Number of channel groups to normalize over.
float
required
Small constant added to the variance for numerical stability.

ggml_flash_attn_ext

Fused scaled-dot-product attention with optional ALiBi bias and logit soft-capping. This is the primary attention kernel used by llama.cpp and related projects.Tensor layout:
  • q: [n_embd_k, n_batch, n_head, ne3]
  • k: [n_embd_k, n_kv, n_head_kv, ne3]
  • v: [n_embd_v, n_kv, n_head_kv, ne3]not pre-transposed
  • mask: [n_kv, n_batch, ne32, ne33] — F16 or F32, optional
  • result: [n_embd_v, n_head, n_batch, ne3] — permuted
float
required
Attention scaling factor applied before softmax. Typically 1/sqrt(head_dim).
float
required
Maximum ALiBi slope. Set to 0.0 to disable ALiBi bias.
float
required
Soft-cap applied to logits as tanh(logit / cap) * cap. Set to 0.0 to disable.
Overrides the precision of the flash attention accumulation (e.g. GGML_PREC_F32).

ggml_soft_max_ext

Fused softmax with optional attention mask and ALiBi bias. Computes softmax(a * scale + mask * alibi_slope).

ggml_reshape_1d / _2d / _3d / _4d

Returns a view of a with the specified shape. Total element count must match. a must be contiguous.

ggml_view_1d / _2d / _3d / _4d

Creates a view into a starting at offset bytes. Strides can differ from a, enabling sub-matrix and strided views without copying.

ggml_transpose

Swaps the first two dimensions of a. Equivalent to ggml_permute(ctx, a, 1, 0, 2, 3). Returns a view; no data is copied.

ggml_permute

Arbitrarily reorders the four axes of a. For example, ggml_permute(ctx, a, 2, 1, 0, 3) moves dimension 2 to position 0. Returns a non-contiguous view; no data is copied.

ggml_cont

Makes a contiguous copy of a if it is not already contiguous. Variants ggml_cont_1d through ggml_cont_4d also reshape while making contiguous.

ggml_sum

Reduces all elements to a scalar by summing.

ggml_sum_rows

Sums along dimension 0 (rows). Input shape [a, b, c, d] → output shape [1, b, c, d].

ggml_mean

Computes the mean along rows.

ggml_argmax

Returns the index of the maximum element along each row.

ggml_top_k

Returns the top-k elements per row. The returned indices are not in sorted order.
Use ggml_argsort if you need fully sorted rows.

ggml_argsort

Returns the indices that would sort each row in the given order.

ggml_cumsum

Cumulative sum along the row dimension.

ggml_conv_1d

1D convolution of data b with kernel a.
struct ggml_tensor *
required
Convolution kernel tensor.
struct ggml_tensor *
required
Input data tensor.
int
required
Stride along dimension 0.
int
required
Padding along dimension 0.
int
required
Dilation along dimension 0.

ggml_conv_2d

2D convolution. Implemented via ggml_im2col + ggml_mul_mat.

ggml_get_rows

Gathers rows from a by the integer indices stored in b. Used for token embedding lookup.Result shape: [n_embd, n_rows, ne2, ne3].

ggml_rope

Applies Rotary Position Embedding (RoPE) to a. b is a 1D tensor of position indices.

ggml_rope_ext

Extended RoPE with support for YaRN-style context extension and custom frequency scaling. Use this instead of the deprecated ggml_rope_custom.
struct ggml_tensor *
Optional per-dimension frequency scaling factors. Pass NULL to use default RoPE frequencies.
int
required
Original training context length. Used to compute YaRN correction dimensions.
float
required
Base frequency for the sinusoidal position encoding (e.g. 10000.0).
float
required
YaRN extrapolation factor. Set to 0.0 to disable YaRN.

ggml_cross_entropy_loss

Computes cross-entropy loss between logits a and ground-truth labels b. The result is a scalar tensor. Mark it with ggml_set_loss() to use it as the optimization objective.

ggml_concat

Concatenates a and b along dimension dim.

ggml_repeat

Repeats (tiles) a to match the shape of b. If a already has the same shape as b and is not a parameter tensor, returns a directly.

ggml_repeat_4d

Repeats a to an explicit 4D target shape.

ggml_diag

Constructs a diagonal matrix from vector a.

ggml_diag_mask_inf

Sets elements above the diagonal to -INF. Used to implement causal attention masks.
int
required
Number of past tokens. Columns at or before n_past are not masked.

ggml_diag_mask_zero

Sets elements above the diagonal to 0.