include/vecmat/softmax.h file

Stable softmax over the last dimension of a row-major matrix.

CPU only. Callers write the unsuffixed names. VECMAT_SYMBOL selects the 32 or 64 entry point. No device op.

Functions

auto vm_softmax(vm_float_t* out, const vm_float_t* x, int rows, int cols, vm_float_t temperature) -> bool
Softmax of each row.
auto vm_softmax_causal(vm_float_t* out, const vm_float_t* x, int rows, int cols, vm_float_t temperature) -> bool
Causal softmax of a square row-major matrix.

Function documentation

bool vm_softmax(vm_float_t* out, const vm_float_t* x, int rows, int cols, vm_float_t temperature)

Softmax of each row.

Parameters
out Output; length rows * cols. May exactly alias x. Unchanged on failure.
x
rows Row count. Must be positive.
cols Softmax length. Must be positive.
temperature Denominator of the logits. Must be greater than 0.
Returns false when a pointer, a size, or the temperature is invalid.

x and out are row-major, rows by cols, and cols is contiguous. Each row subtracts its max, divides by temperature, exponentiates with VECMAT_EXP, and divides by the sum of those exponentials. Pass temperature 1 to leave the logits unscaled.

A null pointer, rows <= 0, cols <= 0, or a temperature that is not greater than 0 (zero, negative, or NaN) returns false and does not write out. out may exactly alias x. A partial overlap is caller error. No allocation.

On finite inputs whose shifted exponents and row sum stay finite, each output differs from the same steps in IEEE-754 double by less than 32 * cols * VECMAT_EPSILON absolute. The row sums to 1 within 16 * cols * VECMAT_EPSILON absolute.

bool vm_softmax_causal(vm_float_t* out, const vm_float_t* x, int rows, int cols, vm_float_t temperature)

Causal softmax of a square row-major matrix.

Parameters
out Output; length rows * cols. May exactly alias x. Unchanged on failure.
x
rows Row count. Must equal cols and be positive.
cols Column count. Must equal rows and be positive.
temperature Denominator of the logits. Must be greater than 0.
Returns false when a pointer, a size, the shape, or the temperature is invalid.

rows must equal cols. On row i, column j > i is −∞ before the softmax: it does not enter the max, and it is written as +0. The unmasked prefix uses the same max, temperature scale, exp, and normalize as vm_softmax.

A null pointer, a non-positive size, rows != cols, or a temperature that is not greater than 0 returns false and does not write out. out may exactly alias x. No allocation. The finite-input tolerance matches vm_softmax.