All pages
Tensor operations
A tensor is a symbolic value: an operation on tensors records a node in the graph being traced and returns a new tensor with a known shape and dtype. Tensors exist only inside a traced function; see how it works.
Shapes, dtypes, broadcasting
- Shapes are vectors of non-negative integers, fixed at compile time.
- Dtypes are
:f32:f64:bf16:i32:i64:bool; anything else isE-DIM-002. - An axis may be negative and counts from the end.
- Broadcasting follows NumPy: right aligned, each dimension equal or 1. Every
broadcast appears as an explicit
broadcastnode insexpgpu ir. + - * / mod pow sqrt exp log min maxand the six comparisons are overloaded: the tensor reading wins when any argument is a tensor, and a number mixed with a tensor becomes a broadcast constant. Plain numbers at the front of an n-ary+ - * /fold first as numbers do, overflow and division by zero included, so(* lr scale tensor)is one constant times the tensor.
Operands of different kinds promote upward: bool to int, int to float. For
example, (* mask x) with a boolean mask and a float tensor means
(* (cast mask :float) x). Mixed where branches use the same rule; its mask
must still be boolean. Comparisons return bool after promoting their operands.
The conversions appear explicitly in sexpgpu ir and respect
high-precision.
Promotion changes kind, never width: :f32 with :f64 or :bf16, and :i32
with :i64, still require an explicit conversion (E-DIM-002). Existing
literal rules stay: (+ count 1.0) keeps an integer count's dtype, while
(+ count 0.5) promotes it to float. Float-to-int conversion is explicit.
Integer division still truncates toward zero and integer reductions retain their
dtype. Two boolean tensors add as OR and multiply as AND; maximum and
minimum do the same. Boolean subtraction is E-DIM-002; use logical-xor for
differing masks. Dividing two boolean tensors produces floats. Boolean sum
counts true elements as :i64; boolean min and max return bool. Unary float
operations still require float inputs.
:f64 is IEEE binary64 on CPU and CUDA; Metal rejects it and the message names
CPU and CUDA. Widen with (cast x :f64) or :dtype :f64 on an initializer;
widening cannot recover bits an F32 input already lost. F64 parameters load
exact values from F64 safetensors. F64 supports arithmetic, reductions, matrix
products, indexing and reverse-mode derivatives; matrix-scan, element-scan
and top-k reject it. Dataset fields keep the loader's dtypes. A random F64
initializer draws the F32 stream and stores it in F64.
Operations
| builtin | keywords | result |
|---|---|---|
(neg x) (rsqrt x) (sin x) (cos x) (tanh x) (abs x) | — | tensor-only unaries; neg and abs also take integers |
(acos x) (asin x) (atan2 y x) | — | angles in radians; acos and asin are NaN outside [-1, 1]; atan2 broadcasts and returns the angle of (x, y) in [-pi, pi] |
(asinh x) | — | inverse hyperbolic sine, with derivative 1 / sqrt(1 + x*x) |
(fma a b c) | — | broadcast floating operands, computing a*b+c with one rounding; its derivatives are b, a, and 1 |
(maximum a b) (minimum a b) | — | elementwise pair, broadcast; max and min of one tensor reduce it instead |
(mod a b) | — | elementwise remainder, broadcast, as mod of numbers: never negative and below the magnitude of b; see mod |
(where mask a b) | — | mask is :bool; all three broadcast to one shape |
(sum x :axes [-1] :keepdims false) | :axes :keepdims | every axis by default; an axis listed twice, also as 1 and -1, is E-DIM-001; (sum xs) over a list of numbers adds them |
(max x :axes [..] :keepdims ..) (min x ...) | :axes :keepdims | the same, the largest or the smallest element; tied elements share the gradient evenly |
(reshape x [..]) | — | same element count and dtype; one -1 infers an extent |
(broadcast-to x [..]) | — | explicit broadcast |
(transpose x [0 2 1 3]) | — | a full permutation |
(slice x axis start stop) | — | non-negative integer bounds, start < stop <= dim |
(concat axis [a b ...]) | — | equal ranks and equal dims off axis |
(matmul a b :out :f32) | :out | batched; leading dims broadcast, inner dims must agree. :out :f32 on bf16 operands keeps the f32 accumulator instead of rounding it, at bf16 matmul speed; f32 is the only :out. See numerics |
(index table ids) | — | rows of [n, rest...] by an integer tensor, giving [ids..., rest...] |
(index-add base ids values) | — | base with each row of values added at the row its id names, repeated ids accumulating: the adjoint of index, so values is [ids..., rest...] |
(gather x idx :axis -1) | :axis | take along one axis; idx is x's shape on every other axis, and the result has idx's shape |
(scatter-add base idx values :axis -1) | :axis | base with values added along one axis at idx, repeated positions accumulating: the adjoint of gather; idx and values have one shape, base's on every other axis |
(matrix-scan a b :axis 0 :reverse false :projective false) | :axis :reverse :projective | h[t] = a[t] @ h[t-1] + b[t] along :axis from h = 0, so h[0] = b[0]; :reverse true runs from the end. a is [.., n, n] and b [.., n, m], floats of one dtype, n at most 16; their leading dims broadcast to one shape and :axis counts among them, so -1 is the one before the matrices. The result has b's shape; computed in f32 under :bf16. See matrix-scan |
(scan body initial sequences :length n) | :length :reverse | general weight-tied tensor recurrence with final state and optional collected outputs; see scan |
(element-scan body initial sequences :axis 0) | :axis :state-axis :reverse | one independent nonlinear recurrence per lane, with f32 inputs and collected states; the state is a scalar, or with :state-axis -1 a vector of at most 16 values the body may reduce; differentiable through initial state and sequences. See nonlinear element scans |
(top-k x k :axis -1) | :axis | two values: the k largest of the float x along :axis, largest first, and their positions as :i32; see top-k |
(qr x) | — | two values: q, x's shape with orthonormal columns, and r [.., n, n], upper triangular with a non-negative diagonal, q r = x; x is f32 or f64 [.., m, n] with m >= n; no derivative; see qr |
(table-scan table symbols :axis -1 :start 0) | :axis :start | the states of the automaton table ([states symbols] of :i32) run over the :i32 symbols along :axis from state :start: h[t] = table[h[t-1], symbols[t]], in symbols' shape; no gradient. See table-scan |
(cast x :float) (cast x :bf16) | — | same shape; :float converts integers and booleans to the default float representation, F32, and preserves any float input unchanged, including F64 and BF16. It respects high-precision. A physical dtype requests that representation; a cast to the same dtype is the identity |
(stop-gradient x) | — | x unchanged in the forward pass, with no derivative through this use; all tensor dtypes. See stop-gradient |
(gradient y x) | — | the gradient of the float scalar y with respect to the float tensor x it is computed from, both traced in the current graph, appended as ordinary nodes; in any graph, so a generator or an evaluation pass can ascend on its own inputs. See gradient |
(iota [n n] :axis 1 :dtype :i32) | :axis :dtype | indices along an axis; :axis 0, :i32 by default; integer dtypes only |
(zeros [..]) (ones [..]) | :dtype | :f32 by default; :dtype :float selects the same default |
(full [..] value) | :dtype | one repeated value; :f32 by default; :dtype :float selects the same default |
(zeros-like x) (ones-like x) | — | x's shape and dtype |
(normal [..]) | :std :mean :dtype :salt :stream | :std 1.0 :mean 0.0 :f32, unsalted, unnamed; :dtype :float selects the default F32 dtype |
(uniform [..]) | :low :high :dtype :salt :stream | :low 0.0 :high 1.0 :f32, unsalted, unnamed; :dtype :float selects the default F32 dtype |
(shape x) (rank x) (dim x axis) (numel x) (dtype x) | — | ordinary values, for compile-time decisions |
The shape helpers are available without an import:
| Form | Meaning |
|---|---|
(einsum "bij,bjk->bik" a b) | Einstein summation; see einsum |
(logical-and a b) (logical-or a b) (logical-xor a b) | elementwise boolean logic, with broadcasting |
(logical-not x) | elementwise boolean negation |
(flip x :axis -1) | reverse one axis; :axes [0 1] reverses several; with neither, reverse all |
(squeeze x) | remove every singleton dimension; :axis -1 or :axes [0 2] selects dimensions, each of extent 1 |
(unsqueeze x :axis 0) | insert a singleton dimension; axis defaults to 0 |
(stack [a b] :axis 0) | concatenate equal-shape, equal-dtype tensors along a new dimension; axis defaults to 0 |
Axes count from zero; negative axes count from the end. For insertion, the valid
positions are -rank-1 through rank: :axis -1 appends a dimension. flip
and squeeze accept either :axis or :axes, never both; :axes [] selects
none. stack needs a nonempty list or vector. These helpers preserve the input
dtype. Invalid helper arguments raise E-EVAL-002 with the expected shape, axis
or dtype and the actual value; unknown keywords suggest the accepted ones.
An index, index-add, gather or scatter-add with any index into an axis
of extent 0 is E-DIM-001 on every device, since no index fits it.
A degenerate spread (:std 0.0, or :low equal to :high) is a constant, not
a random draw. Random streams fold in defrun :seed.
A draw is the same in every call of its graph: every step, every microbatch.
:salt makes it new wherever the salt moves. The salt is one integer, a number
or an integer scalar tensor read when the graph runs, such as
(+ (* (getf ctx :step) 65536) (getf ctx :microbatch)) in a graph that is given
ctx:
(uniform [4] :low -1.0 :high 1.0 :salt (getf ctx :step))Each salt is its own stream, and :salt 0 differs from no salt; see
determinism. A float salt, or a literal salt
beyond 2^53 in magnitude, is E-DIM-002; a salt with more than one element is
E-DIM-001.
:stream names the draw, with a keyword or a string, so that the same draw can
be made in another graph. An unnamed draw is keyed by its graph and its position
in it; a named one by its kind, its name and its shape instead. Two normal
draws with the same name, shape and salt take the same values in any graph, pass
or file: a refactored evaluation reads the noise the old one read, and two
passes can compare on paired noise.
(normal [b n c] :std 0.1 :salt (+ trip 17) :stream :hint)A name fixes the stream, not the variation: with no salt, the draw is the same
in every call, every step and every pass. Salt it by what should move it, as for
an unnamed draw. Within one graph, two draws with the same name, shape and salt
are equal. Another shape, another kind or another name is another stream; the
dtype only rounds the same samples. Equal noise does not make equal outputs:
what the passes compute around the draw still decides their bits. A named draw
takes no position, so adding one moves no unnamed draw. A parameter's
initializer is keyed by its path, and :stream there is E-EVAL-006, as is a
name that is not a keyword or a string. See
determinism.
Reporting operations (metric, diagnostic, tap-gradient, counter) are in
metrics and writing diagnostics, and
guard, assert-finite and count-where in guards. Higher-level
functions (mean, softmax, rms-norm, cross-entropy, attention) are in
sexpgpu/nn.
einsum
The spec uses ASCII letters for axes and -> for output order. Axes missing
from the output are summed. Each label occurs at most once within an operand and
at most once in the output. Shared extents must match or be 1. Operands must
have the same floating dtype; there is no dtype promotion. The result preserves
the operand dtype.
(einsum "bij,bjk->bik" a b) ; batched matrix product
(einsum "bhqd,bhkd->bhqk" q k) ; attention scores
(einsum "bi,ij,bj->b" x w y) ; bilinear form
(einsum "abc,cde->abde" a b) ; contract grouped axes
(einsum "...ij,...jk->...ik" a b) ; broadcast leading dimensions
(einsum "ij->ji" x) ; transpose
(einsum "ij->" x) ; scalar sumAny number of operands is accepted. With no ->, ellipsis dimensions come
first, then labels that occur once, in alphabetical order (uppercase before
lowercase). Ellipses align from the right and can represent zero dimensions. An
explicit output can omit the ellipsis to sum those dimensions. Empty terms
represent scalar operands. Whitespace is ignored.
For a grouped linear map, x has shape [n k in] and weight has shape
[in (* k out)]. A reshape exposes the group's index:
; Before:
(transpose (matmul (transpose x [1 0 2])
(transpose (reshape weight [in k out]) [1 0 2]))
[1 0 2])
; After:
(einsum "nki,iko->nko" x (reshape weight [in k out]))Repeated operand indices, such as "ii->i" for a diagonal, are unsupported
(E-EINSUM-002). Take the diagonal of a square x with a mask first:
(sum (where (= (iota [n n] :axis 0) (iota [n n] :axis 1)) x (zeros-like x))
:axes [-1])Malformed specs, missing operands and absent output labels are E-EINSUM-001.
Rank or extent mismatches are E-EINSUM-003, with the label and sizes that
disagree.
Boolean tensors
The logical- forms require boolean tensors, such as comparisons. Binary forms
broadcast and return boolean tensors; both operands are evaluated. Compile-time
and, or, not, if, when and unless reject tensors with E-FLOW-001,
including a tensor in the final position of and or or.
; Before: test that column c is inside the board.
(> (* (cast (>= c 0) :i32) (cast (< c cc) :i32)) 0)
; After:
(logical-and (>= c 0) (< c cc))Use where to choose tensor values based on a mask. See
truth and staging.
Inferred reshape extents
(reshape x [batch -1]) divides numel x by batch at compile time. There
must be exactly one -1, and the division must be exact. Explicit zero extents
are permitted: reshaping [0 3] to [-1 3] infers 0. A zero known product,
such as [0 -1], is ambiguous and rejected. Multiple inferred extents or a
nondivisible size raise E-DIM-004, showing the input shape, element count and
requested sizes. Other shape-taking forms require nonnegative extents.
For splitting and merging several axes by name, use rearrange,
imported with (require "sexpgpu/axes" rearrange).
mod
(mod a b) takes from a the whole multiple of b at or below it, element by
element, so the result is at least zero and below the magnitude of b whatever
the signs, as mod of numbers is. A number takes the tensor's dtype.
(mod (iota [6] :dtype :i32) 4) ; [0 1 2 3 0 1]
(mod (- (iota [3] :dtype :i32) 2) 3) ; [-2 -1 0] gives [1 2 0]
(mod x 1.0) ; the fractional part, in [0, 1) for a negative x tooA literal 0 divisor is E-EVAL-007. Integers are exact, and an integer
divisor tensor must not hold zero. Floats are exact while the quotient a / b
is below 2^48 in magnitude in :f32 and 2^104 in :f64; past it the result can
fall outside the range. :bf16 operands, and a :bf16 region, compute it in
:f32. For floats, a zero divisor gives NaN, and so do a NaN or infinite
operand, an infinite divisor included, where mod of numbers keeps a finite
dividend. The derivatives are 1 for a and (/ (- r a) b) for b, where r
is the result: minus the number of bs taken out.
top-k
(defun keep-best (pool score) ; pool [n d], score [n]
(multiple-value-bind (best at) (top-k score 32 :axis 0)
(values (index pool at) best))) ; [32 d] rows, best first(top-k x k :axis a) returns two values, both x's shape with axis a cut to
k: the k largest values along it and their positions as :i32. k is an
integer from 1 to the axis's length, else E-DIM-001, as is a rank-0 x. The
order is the same on every device: larger first, every NaN above infinity,
-0.0 equal to 0.0, and equal values by the lower position. k equal to the
axis length sorts it.
The values are (gather x at :axis a), so their gradient reaches only the
chosen elements; the positions have none. Taking rows by the positions (index
on the first axis, gather on any other) makes the model's backward run over
k rows, where a mask over the pool would run it over every row.
qr
(defun refresh (factor basis) ; factor [n n] symmetric, basis [n n]
(qr (matmul factor basis))) ; one power iteration: the next basis(qr x) is the reduced QR decomposition of each matrix of x [.., m, n],
over its last two axes: two values, q in x's shape with orthonormal columns
and r [.., n, n] upper triangular, with (matmul q r) equal to x up to
rounding. Each column of q is signed so r's diagonal is non-negative, which
makes q unique for a matrix of full column rank. x is f32 or f64, else
E-DIM-002; fewer than two axes or m < n is E-DIM-001. Leading axes are a
batch. r's entries below the diagonal are exact zeros.
- A rank-deficient
xstill gives orthonormal columns. The columns past its rank are some orthonormal completion, and rounding decides which. qrcomputes Householder reflections, one column after another, so its time grows withm n^2. An optimizer that refreshes a basis with it pays that on every update.- It has no derivative: a gradient through it is
E-GRAD-006. Wrap its argument instop-gradientto use the result as a constant. An optimizer update is not differentiated, so it needs neither. - On Metal a matrix has at most 4096 columns.
table-scan
(defun parity (bits) ; bits [b t] :i32 of 0 and 1
(let* ((s (+ (iota [2 2] :axis 0) (iota [2 2] :axis 1)))
(flip (where (>= s 2) (- s 2) s))) ; [[0 1] [1 0]]
(table-scan flip bits))) ; [b t]: parity so far(table-scan table symbols :axis a :start s) runs a deterministic automaton
along axis a of symbols, the last by default: the state after each symbol is
table[previous, symbol], starting from state s, 0 by default, and the result
holds every state, in symbols' shape.
tableis[states symbols]; both tensors are:i32, elseE-DIM-002.- A table of another rank or with no symbols, an axis out of range, or a
:startthat is not a state isE-DIM-001. - The states have no gradient; a model reads them through
indexorgather, whose values carry it. - A symbol outside
[0, symbols), or a reached table entry outside[0, states), is refused on CPU and Metal and clamped into range on CUDA, asgatheris.
matrix-scan
(defun delta-rule (k v beta) ; k [b t n], v [b t m], beta [b t 1 1]
(let* ((column (reshape k (append (shape k) [1]))) ; [b t n 1]
(row (reshape k [(dim k 0) (dim k 1) 1 (dim k 2)])) ; [b t 1 n]
(eye (cast (= (iota [(dim k 2) (dim k 2)] :axis 0)
(iota [(dim k 2) (dim k 2)] :axis 1))
:f32))
(write (matmul column (reshape v [(dim v 0) (dim v 1) 1 (dim v 2)]))))
(matrix-scan (- eye (* beta (matmul column row))) (* beta write) :axis 1)))(matrix-scan a b :axis t) carries an n by m state through the first-order
recurrence h[t] = a[t] @ h[t-1] + b[t], one matrix product a step; above, the
delta rule S[t] = (I - beta k k^T) S[t-1] + beta k v^T over [b t n m]. Every
column of h is its own recurrence on the shared a. Both a and b are
differentiable. The prelude's linear-scan is this over
one-by-one matrices, and cumsum in sexpgpu/nn is built on it.
:reverse true runs the recurrence from the last position of :axis to the
first. :reverse and :projective are true or false, default false;
anything else is E-CONTRACT-003.
:projective true is for a product of projective maps, such as a carried Möbius
transformation as a real matrix, whose entries would overflow f32: the running
product of a, from the identity, is divided by its largest magnitude after
every step, and h by the same number. A zero product skips the division. The
result is the ordinary scan's h up to a positive factor per step when b is
zero after its first step; later nonzero writes enter the normalized coordinates
and change that relationship.
- Gradients include every divisor's dependence on
a, for any differentiable readout. Equal largest magnitudes split the divisor's gradient evenly, asmaxdoes. - At a zero product the gradient follows the branch that skips division; it is not a derivative across the discontinuity. A product that cancels to exactly zero only through rounding can take the other branch in the backward pass; a structural zero, every term zero, is exact.
- The projective form costs extra work and storage proportional to
n * nper step. - Rescaling limits product growth. It does not make the carry exact, repair ill-conditioned products, or prevent overflow within a step or in the gradients.
scan
Use scan for a weight-tied cell repeated a fixed number of times:
(scan (lambda (state unused index)
(tanh (+ (matmul state weight) bias)))
initial nil :length rounds)The body takes state, per-iteration inputs, and a scalar integer tensor index.
Tensors closed over by the body, including parameters, are shared across all
iterations. The body is traced once, so the index cannot control Lisp structure;
use dotimes when a compile-time integer decides which forms or shapes to use.
State may be one tensor, a list, a vector or a plist of tensors. Return the same
structure with the same shapes and dtypes. Declare parameters and persistent
state outside the body. Return tensors and report metrics or counters outside
it. Invalid state is E-SCAN-002; declarations and reporting inside the body
are E-SCAN-003.
Pass a tensor, list, vector or plist as the third argument to read sequences.
Each sequence has a leading axis of the same length; the body receives one slice
from each in the same structure. The length is inferred, or checked against
:length when supplied. With nil inputs, supply :length explicitly.
:reverse true visits indices from the end; collected outputs retain their
original index order. Zero iterations return the initial state and empty
collected outputs.
The body can return (values next-state output) to collect outputs along a new
leading iteration axis. The scan returns
(values final-state collected-output); use multiple-value-bind to read both.
Additional returned values are collected in the same way. Nested scans and
gradient are supported. Reverse-mode training adds every iteration's gradient
for shared parameters. Forward-query and forward-credit training do not accept
scans (E-SCAN-004).
Random draws inside a scan vary by index and reproduce during gradient
recomputation. element-scan remains useful for its independent scalar or small
vector lanes; scan carries tensors of arbitrary static shape.
gradient
(defun prepare (batch)
(let* ((x (field batch :x))
(energy (sum (* x x x))))
(list :inputs (+ x (* 0.1 (gradient energy x))) :targets x)))(gradient y x) runs the backward sweep from y to x while the graph is
traced and appends its nodes, so the result is an ordinary tensor of x's shape
and dtype. y must be one float value and x a float tensor y is computed
from; anything else is refused rather than answered with zeros (E-GRAD-001 to
E-GRAD-003). A path blocked by stop-gradient still counts as a dependency,
with derivative zero. A y computed from the gradient a tap-gradient lambda
is given is E-GRAD-004: that gradient is filled in after the training
backward.
Training differentiates through every gradient in the training graph. A
prepare or model that moves its inputs uphill on the student's own score
therefore adds second-order terms to the parameter gradient, and the step pays
for a second backward through the first. Wrap the refined input in
stop-gradient to hold it fixed, or wrap only the inner gradient to keep the
direct input path; see stop-gradient.
The appended nodes carry the numerics of the forward nodes they differentiate,
and a with-numerics around the call overrides them. Under :bf16 the appended
ops are lowered with the forward graph, so each rounds on store; the training
backward is built from the lowered graph instead. See
numerics.
Errors
| code | when |
|---|---|
E-DIM-001 | shapes do not fit; the notes name both operands as you wrote them, with shape and dtype, and any broadcast that would have applied |
E-DIM-002 | dtypes differ, or a keyword is not a dtype |
E-DIM-003 | a tensor was expected |
E-FLOW-001 | compile-time truth on a tensor; use where or the logical- forms. See staging |
E-FLOW-002 | a tensor from another graph; recompute it here |
E-FLOW-003 | a tensor operation with no graph being traced |
E-GRAD-001 | gradient of a y that is not one float value |
E-GRAD-002 | gradient with respect to an integer or boolean x |
E-GRAD-003 | gradient of a y not computed from x |
E-GRAD-004 | gradient of a y computed from a tap-gradient lambda's gradient |
error[E-DIM-001]: matmul: inner dims differ: [2, 16] x [32, 8]
--> bad-shape.sx:7:15
|
7 | (lambda (x) (matmul x weight)))
| ^^^^^^^^^^^^^^^^^
note: operands: `x` [2, 16] f32, `weight` [32, 8] f32stop-gradient
(stop-gradient x) returns x's shape, dtype and value and blocks the
derivative from this result to x. Other uses of x still differentiate, and
so does differentiating with respect to the stopped result itself. This holds
for constants and nested boundaries too. Integer and boolean tensors pass
through unchanged.
A target computed from a trainable prediction can be held fixed for one derivative while its value changes each step:
(defun objective (prediction targets)
(let* ((target (stop-gradient (+ 1.0 (* 0.5 prediction))))
(error (- prediction target)))
(sum (* error error))))At prediction = 0 this loss has gradient -2; without stop-gradient it is
-1.
(stop-gradient (+ x (* rate (gradient energy x)))) holds the whole refined
value fixed. Stopping only the inner gradient keeps the direct derivative
through x:
(+ x (* rate (stop-gradient (gradient energy x))))Every later gradient and the training backward respect the boundary: for
scalar x, (gradient (gradient (stop-gradient x) x) x) is zero. A gradient
result, even a constant one, can be differentiated again with respect to the
same tensor; unrelated tensors still get E-GRAD-003.
stop-gradient does no arithmetic, consumes no random stream, adds no rounding
step under a precision policy, and preserves signed zeros, infinities and NaN
payloads. It does not freeze a parameter or cache the value across steps.
Related: precision and numerics, models.