Numerics extras
Scientific work defines VECMAT_USE_F64 before the include. -DVECMAT_USE_F64=ON does that for this build's tests and benchmarks; it does not drop name32.
GEMM
BLAS-style dense multiply C = alpha * op(A) * op(B) + beta * C. Row-major and column-major layouts.
vm_/gemm vm_/gemm_ ref vm_(optional bias and/or ReLU)gemm_ ex vm_/gemm_ batch vm_(shared-gemm_ strided_ batch Bpacks once)vm_unfolds an NCHW image into a GEMM-ready panelim2col
Packed ukernel, TLS pack workspace MC=NC=KC=128, persistent thread pool. When N spans more than one NC panel and one KC slice of packed A fits in 4 MiB, that slice is packed once and reused across those panels. One NC panel packs A with that panel. A larger slice is packed again for each NC panel. The 4 MiB ceiling is fixed. Per-CPU MC/NC/KC stay a vendor backend. The default tile is 8×8, and a registered backend keeps it. With no backend, AVX-512 uses 16×14 and AVX2 uses 12×8 when that kernel was compiled and that ISA is selected. vm_ can force 8×8, the scalar 4×4 tile, a compiled wide tile, or a registered shape. (0, 0) restores the automatic choice. An unavailable shape is rejected and the previous choice stays. Cap threads with vm_ or VECMAT_GEMM_THREADS. fp16 and bf16 are optional widths, off by default. See doc/fp16.md and doc/bf16.md. This is not a BLAS.
Contract: vm_ matches vm_ for trans / no-trans, row / col, odd sizes, beta ≠ 0, and batch shared-B, on a size band of about 32–512.
Column-major C = A * B for square panels:
vm_gemm(C, n, A, n, B, n, n, n, n, 1.0f, 0.0f, false, false, VM_LAYOUT_COL_MAJOR);
Contiguous arrays
Scalar loops on length-n buffers. n <= 0 does not read. An elementwise result may exactly alias an input. vm_, vm_, vm_, vm_, vm_, and vm_ use AVX2 or NEON when the runtime CPU has it; the scalar path remains the fallback. vm_ is one rounding through VECMAT_ (fma / fmaf). vm_ is y += alpha * x, a multiply then an add (not fused). Sums and dots use Neumaier compensation. vm_ and vm_ are compiled once and are not width-remapped; the dot widens each factor before the multiply.
vm_,array_ add vm_,array_ sub vm_,array_ mul vm_,array_ div vm_,array_ fma vm_axpy vm_is elementwisearray_ silu y = x * sigmoid(x), withsigmoid(x) = 1 / (1 + exp(-x))throughVECMAT_. A null pointer orEXP n <= 0returns false and does not write. On a finite input the result differs from the same steps in IEEE-754 double by less than16 * VECMAT_absolute.EPSILON * (1 + |x|) +infstays+inf.-infand a NaN yield a NaN. Scalar only: no SIMD path, fp16, bf16, or device op.vm_is the Euclidean norm, scaled so a finite result does not overflow earlynrm2 vm_is the Neumaier sum of absolute valuesasum vm_returnsrsqrt_ array 1 / sqrt(x)for each element using a real square root then a divide (not a cheap estimate). Ordinary positive numbers are accurate to within 2 ULP;+0→+inf,−0→−inf,+inf→+0, and any negative number →NaN.vm_,sum_ compensated vm_,dot_ compensated vm_,sum_ f32f64 vm_dot_ f32f64 vm_ignores NaNs. The minimum ofarray_ minmax ±0is−0and the maximum is+0vm_is the orthorhombic minimum image ofperiodic_ delta_ ortho a − bonvector3arrays, ties-to-even, in[-L/2, L/2]vm_folds awrap_ ortho vector3array into[0, L)
VECMAT_ is remainder / remainderf. These are not a force field. They do not change vm_ or vm_.
Softmax
include/. Row-major. The last dimension is the contiguous row. CPU only, f32 and f64. No fp16, bf16, or device op.
vm_ writes rows independent rows of cols. Each row subtracts its max, divides by temperature, exponentiates with VECMAT_, and divides by the sum. temperature must be greater than 0. Callers pass 1 when they do not scale.
vm_ is the square case, rows == cols. On row i, column j > i is −∞ before that softmax: it does not enter the max, and it is written as +0. A non-square pair returns false and does not write.
A null pointer, a non-positive size, or a temperature that is not greater than 0 (zero, negative, or NaN) returns false and does not write. The output may exactly alias the input. 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_ absolute, and the row sums to 1 within 16 * cols * VECMAT_ absolute.
vm_float_t y[6]; const vm_float_t x[6] = { 0.0f, 1.0f, 2.0f, 1.0f, 1.0f, 1.0f }; const bool ok = vm_softmax(y, x, 2, 3, 1.0f);
RMSNorm
include/. Row-major. The last dimension is the contiguous row. CPU only, f32 and f64. Scalar. No fp16, bf16, SIMD path, or device op. Forward only.
vm_ normalizes each row of cols:
y = (v / sqrt(mean(v^2) + epsilon)) * w
v is x, or x + residual when residual is set. w has length cols and is shared by every row. w NULL skips the scale. epsilon is the caller's value and must be greater than 0. residual NULL skips the fused add. When residual is set, that sum is written through residual_out when that pointer is set. residual_out may exactly alias residual. When residual is NULL, residual_out is not read or written. y may exactly alias x.
A null y or x, a non-positive size, or an epsilon that is not greater than 0 (zero, negative, or NaN) returns false and does not write. On finite inputs whose squares, their sum, and the root stay finite, each output differs from the same steps in IEEE-754 double by less than 32 * cols * VECMAT_ absolute. A written residual_out stays within that bound of x + residual.
vm_float_t y[6]; const vm_float_t x[6] = { 1.0f, 2.0f, 3.0f, 0.0f, 1.0f, -1.0f }; const vm_float_t w[3] = { 1.0f, 0.5f, 2.0f }; const bool ok = vm_rmsnorm(y, x, w, NULL, NULL, 2, 3, 1.0e-5f);
SoA geometry
include/ batches independent 3-vectors held as a structure of arrays. vm_ / vm_ are borrowed views of three unit-stride component pointers; they carry no size, ownership, padding, or SIMD width, and the component arrays must not overlap. vm_, vm_, vm_, and vm_ take n vectors; n <= 0 is a no-op. Products and sums are separate roundings in the scalar order, never fused, so the AVX2 and NEON paths match the scalar loop bit for bit. Cross loads every component before it stores, so its output view may exactly equal an input view. Accuracy is an absolute bound, 16 eps × the sum of the absolute terms, not a ULP claim. This does not change vector3 normalization.
Dense linear algebra
Heap vm_ (M×N, column-major). LU with partial pivoting, Householder QR, thin one-sided Jacobi SVD, Cholesky. Scale-aware cutoffs tol = n * VECMAT_. Rank-deficient work returns false (an ok flag), not a silent NaN. Integer matNi_inverse is truncated, not modular inverse — the declaration says so.
vm_mat A = vm_mat_alloc(3, 3); vm_mat_set(&A, 0, 0, 2.0); vm_mat_set(&A, 1, 1, 2.0); vm_mat_set(&A, 2, 2, 2.0); vm_mat inv; bool ok = vm_mat_inverse(&inv, &A); vm_mat_free(&A); vm_mat_free(&inv);
3×3 factorizations
mat3_ returns false on a singular matrix (scale-aware cutoff). mat3_ is the analytical symmetric 3×3 eigensolve, eigenvalues sorted ascending, eigenvectors on request. mat3_ is the polar decomposition F = R U (Newton on C = Fᵀ F). A reflection is a failure.
Dense spectral primitives
vm_,matvec vm_— dense matvec (symmetric reads the lower triangle)symv vm_—gemv y = alpha * op(A) * x + beta * y, with an optional transpose.beta == 0does not readyvm_—ger A += alpha * x * yᵀ.alpha == 0does not read or writevm_— Jacobi symmetric eigensolve, eigenvalues descending,syev Aoverwrittenvm_— unnormalized graph Laplacianlaplacian L = D − Avm_— thin wrapper for the leading k eigenpairssyev_ topk
Gaussian ensembles
include/. vm_ and vm_ overwrite caller-owned column-major matrices. Real and imaginary parts of a GUE matrix are two vm_ values. The entry variances below are fixed.
vm_ is one uint64_t counter. vm_ stores the seed and advances splitmix64 once (state becomes seed + 0x9E3779B97F4A7C15), so seed 0 is valid. A null pointer is ignored. Draws use that generator. Each Box–Muller pair consumes two splitmix64 outputs. The uniform is the top 53 bits with the low bit set, times 2⁻⁵³, an exact value in (0, 1). The pair is evaluated in IEEE-754 double and rounded into vm_. frexp, ldexp, and sqrt are the libm calls. The logarithm and the sine/cosine are power series. The same seed yields the same bits on every IEEE-754 platform.
Entries are drawn across the upper triangle, including the diagonal, one row at a time. The lower triangle is written from those draws. A partner left over at the end of a call is discarded.
vm_— one square matrix. Diagonal N(0, 2). Off-diagonal N(0, 1).goe vm_— two square matrices of equal order. Diagonal real N(0, 1). Diagonal imag 0. Off-diagonal real and imag each N(0, 1/2). Real part symmetric, imaginary part skew.gue
A null rng, a null matrix, a null data pointer, a non-square, rows < 1, or two GUE orders that differ returns false and leaves the buffers and the generator unchanged.
vm_rng rng; vm_rng_seed(&rng, 1); vm_mat A = vm_mat_alloc(4, 4); bool ok = vm_goe(&A, &rng); vm_mat_free(&A);
Spectral spacing
include/. Nearest-neighbor spacing and a coarse pair correlation on an ascending eigenvalue buffer. These functions do not sort and do not allocate. The caller owns every buffer.
The mean spacing is the mean of λ[i+1] − λ[i]. Unfolding divides by that one number, ξ_i = λ_i / mean. Local unfolding is not done.
vm_— that mean. A null pointer,nn_ spacing_ mean n < 2, a non-finite value, a descent, a non-finite sum, or a zero mean returns NaN.vm_— divide each spacing by the mean and count into a caller buffer ofnn_ spacing_ hist binsfloats. Biniis[s_min + i w, s_min + (i+1) w)withw = (s_max − s_min) / bins, and the last bin includess_max. Counts are raw, not a density. A spacing outside[s_min, s_max]is skipped. Requiress_min < s_maxandbins > 0. Failure returns false and does not write the buffer.vm_— counts unordered pairs whose unfolded distance lies inpair_ correlation [s − 0.25, s + 0.25)and returnscount / (n * 0.5). The window is fixed. A Poisson spectrum is near 1.s < 0returns NaN. This is a coarse check, not a literatureR_2estimator.
A zero or non-finite mean spacing makes the histogram fail and the pair correlation return NaN. The same is true of a descent: the buffer is not sorted into order.
const vm_float_t ev[] = {0.0f, 1.0f, 3.0f, 6.0f}; const vm_float_t mean = vm_nn_spacing_mean(ev, 4); vm_float_t hist[4]; const bool ok = vm_nn_spacing_hist(ev, 4, 0.0f, 2.0f, hist, 4); const vm_float_t pair = vm_pair_correlation(ev, 4, 1.0f);
Lanczos
include/ is a real-symmetric eigensolver. No complex Hermitian path, no shift-invert, no block Lanczos, and no device op.
vm_— implicitly restarted Lanczos, full reorthogonalization.lanczos mis the Krylov length, withk <= m <= n. The projected tridiagonal is solved withvm_.syev whichisVM_orLANCZOS_ LARGEST VM_. Returned eigenvalues stay inLANCZOS_ SMALLEST vm_'s descending order on that end. The start vector is deterministic.syev vm_callslanczos_ dense vm_, so only the lower triangle is read.symv vm_callslanczos_ sparse vm_. The CSR matrix is the operator as stored.spmv eigenvectorsNULL skips the vectors. Otherwise the matrix isn × k, columns. Each column is unit length and its largest-magnitude entry is positive.infomay be NULL. It is avm_:ksp_ info itersis the restarts performed,rel_resis the worst residual||Au − λu|| / max(|λ|, ||T||, ε)of the returned pairs, andokmatches the bool result.||T||is the max absolute row sum of the projected tridiagonal.- A bad
k,m, ortol(tol <= 0or NaN) returns false.
Sparse systems
vm_— square CSR from tripletsspmat vm_,spmv vm_(SPD),cg vm_(nonsymmetric)bicgstab - Left preconditioners: Jacobi, SSOR (ω = 1), IC(0) (falls back to Jacobi on pivot breakdown)
vm_reportsksp_ info iters,rel_res,ok- Relative residual is
||r|| / max(||b||, ε)
Time integration and grid primitives
vm_,euler_ semi vm_,verlet vm_/rk2 vm_,rk4 vm_cfl_ dt vm_— symplectic Euler onrigid_ step (x, v, q, ω)- MAC operators and an assembled 5-/7-point Laplacian
Semi-implicit Euler on one particle. x, v, and a are length n.
vm_float_t x[3] = {0.0f, 1.0f, 0.0f}; vm_float_t v[3] = {1.0f, 0.0f, 0.0f}; const vm_float_t a[3] = {0.0f, -9.81f, 0.0f}; vm_euler_semi(x, v, a, 3, 1.0f / 60.0f);
Computer graphics (core)
Clip-space helpers
Build projection and view matrices for different graphics APIs and depth conventions.
Perspective projections — camera frustum matrices (radians; _deg if FOV is in degrees). The unsuffixed mat4_ / mat4_ / mat4_ helpers also take radians. Use mat4_ (and friends) for degrees:
mat4_/perspective_ clip mat4_perspective_ clip_ deg mat4_/perspective_ rh_ no mat4_perspective_ rh_ no_ deg mat4_/perspective_ rh_ zo mat4_perspective_ rh_ zo_ deg mat4_/perspective_ lh_ zo mat4_perspective_ lh_ zo_ deg mat4_/perspective_ lh_ no mat4_perspective_ lh_ no_ deg
Orthographic projections — parallel projection matrices from frustum bounds:
Look-at view matrices — world-to-view transforms from eye, target, and up:
Look-from-direction view matrices — the same basis as look-at, but the camera aims along a direction (FPS / fly camera, no target point):
mat4_/look_ from_ dir mat4_look_ from_ dir_ clip mat4_/look_ from_ dir_ rh mat4_look_ from_ dir_ lh quat_/look quat_— orientation whose local −Z (RH) or +Z (LH) aims along the directionlook_ clip quat_— shortest rotation taking one vector onto anotherfrom_ to
Infinite / reverse-Z projections — infinite far plane, optionally with reversed depth (near → 1, infinity → 0 on ZO):
mat4_stays historic OpenGLperspective_ infinite RH_NOmat4_— infinite and any clip convention (perspective_ infinite_ clip *_ZOis infinite and zero-to-one)mat4_— modern-engine preset: infinite + RH + ZO + reversed depthinfinite_ reverse_ z mat4_— same mapping for the other clip conventionsinfinite_ reverse_ z_ clip
Viewport, world ↔ window — NDC to a pixel box and back. Geometric vec3_ (onto a direction) is unchanged:
mat4_/viewport mat4_viewport_ depth vec3_/world_ to_ window vec3_window_ to_ world vec3_/world_ to_ window_ clip vec3_window_ to_ world_ clip
Frustum planes — six planes of an existing projection * view matrix. Inside each plane is ax + by + cz + d >= 0. Order is left, right, bottom, top, near, far. Pass the same vm_ the projection was built with (*_NO keeps near at z = -w, *_ZO keeps near at z = 0). normalize makes (a, b, c) a unit normal.
mat4_/frustum_ planes mat4_frustum_ planes_ ptr vm_— point test, boundary counts as insidefrustum_ contains vm_—frustum_ aabb VM_,FRUSTUM_ INSIDE VM_, orFRUSTUM_ CROSSING VM_FRUSTUM_ OUTSIDE
Affine inverse and normal matrices — skip the 4×4 adjugate when the transform is [A t; 0 1]:
mat4_— invert the 3×3 linear part and apply it to the translationinverse_ affine mat3_/normal mat4_— inverse-transpose of the 3×3 for transforming normalsnormal
Clip conventions — handedness + depth range selectors used by the *_clip helpers:
VM_— right-handed, clip z inCLIP_ RH_ NO [-1, 1](OpenGL-style)VM_— right-handed, clip z inCLIP_ RH_ ZO [0, 1](Vulkan-style)VM_— left-handed, clip z inCLIP_ LH_ ZO [0, 1](Direct3D-style)VM_— left-handed, clip z inCLIP_ LH_ NO [-1, 1]
A Vulkan-style camera is a projection times a view. Angles are radians; VM_ converts a degree literal.
const vector3 eye = vec3(0.0f, 1.6f, 4.0f); const vector3 at = vec3(0.0f, 1.0f, 0.0f); const vector3 up = vec3(0.0f, 1.0f, 0.0f); const matrix4 view = mat4_look_at_rh(eye, at, up); const matrix4 proj = mat4_perspective_rh_zo(VM_DEG(60.0), 16.0f / 9.0f, 0.1f, 200.0f); const matrix4 view_proj = mat4_mul(proj, view);
Rotation helpers
Build 4×4 rotation matrices from axis angles in radians (mat4_ / mat4_ / mat4_ / mat4_).
Use *_deg or VM_ when the angle is in degrees: