S-exp GPU
All pages
Docs · Models and optimizersMarkdown

Precision and numerics

defrun :precision is :f32 or :bf16. Under :bf16 the compiler rewrites the graphs: activations and matmuls run in bf16, trained parameters stay f32 master weights, and nodes annotated as numerically sensitive run in f32. The file states what is sensitive; the compiler does the casting.

bf16 is for what a product reads. In the objective and in every evaluation pass, what comes after the last product (the loss, its sums and metrics, an evaluation's reads) computes in f32 on the product's bf16 result, with no annotation. A sum over hundreds of positions keeps its digits: rounded to bf16, a chunk's summed log-likelihood near 200 would move in steps of 1, and training would learn that rounding. Moving or selecting bf16 values there (transpose, slice, gather, max) hands them on as they are, and a (with-numerics (:precision :bf16)) region there still rounds. A bias, scale, or activation applied to one product result with product-independent operands is part of that product's bf16 result. Arithmetic that combines two product results, or reads a product through two paths such as (- logits (logsumexp logits)), follows the f32 rule after the last product. A value is after the last product when no matmul, convolution, matrix-scan, element-scan, scan, or branch reads it, directly or through other values. A parameter read only there reads its f32 master. Generators keep the dtypes their outputs were given.

On GPUs of compute capability 8.0 and 9.0 (A100, H100), an f32 matrix product may run as three TF32 tensor-core products accumulated in f32, a little less accurate per product, where the run measures that faster; the lowering report's F32 product lines and the run's choices name it. --deterministic keeps the ordinary f32 product, and NVIDIA_TF32_OVERRIDE=0 in the environment keeps TF32 out of every f32 product and f32 attention. A recorded TF32 choice the override rules out stops the run with E-CHOICE-001.

Float kind conversion

(cast x :float) converts an integer or boolean tensor to the default float representation, F32. An existing float tensor is returned unchanged, preserving its width, including F64 and BF16. Inside high-precision, the conversion keeps the value at F64 accuracy for subsequent high-precision arithmetic, without rounding through F32. (cast x :f32) requests F32 rounding explicitly.

:dtype :float on zeros, ones, full, normal and uniform selects their default F32 dtype. These constructors retain F32 rounding inside high-precision. Loader field dtypes, defrun :precision, matmul :out and iota :dtype require physical dtype keywords.

Explicit F64 tensors

An explicit :f64 tensor keeps F64 arithmetic, outputs, observations and gradients under either run precision policy; :sensitivity :high and a surrounding bf16 region do not narrow it. Use an explicit cast to return to F32 or BF16. Under :bf16, (cast w :f64) of an F32 parameter reads its F32 master weight, not the BF16 copy its uses before the last product read.

CUDA may fuse an F32 multiply and addition into one rounding operation within a validated error bound. Each contraction preserves a finite result when the separate multiply and addition have a finite result. Arithmetic feeding a comparison or integer result keeps separate multiply/add rounding, because even a small rounding change can change a mask or index.

CUDA fuses F64 row programs, last-axis reductions and their derivatives included, with no flag or custom kernel. F64 autodiff accumulates each product contribution with fma, keeping the product's low bits until the addition; F32 and BF16 accumulation do not. explain --json reports numerics.f64_nodes separately, and finite-update guards use the F64 limit for F64 proposals. The derivative of asinh stays finite for large F32 and F64 inputs whose square would overflow.

Lorentz-model geometry, such as distances and Busemann values, needs only these ordinary operations. Rationalize small differences before computing them, and cast spatial coordinates to F64 first when their F32 input rounding is acceptable but F32 arithmetic is not.

CUDA also recognizes rank-two products of F32 tensors widened to F64 by cast, transposes on either side included, when the casts and transposes are used only by the product:

(matmul (cast x :f64) (transpose (cast y :f64) [1 0]))

On A100 and H100 such a product may run on F64 tensor cores or as an integer residue decomposition instead of the casts and an ordinary F64 GEMM. The run measures each method, conversion included, and takes another only when it saves at least 5%. The choice depends on the shape, orientation, device, libraries and binary; it appears in the lowering report and the checkpoint, and --deterministic keeps the ordinary F64 GEMM (determinism). The residue method checks every input on every call: a dot product of exactly representable rows is the exact result rounded once to F64, and inexact, tiny, subnormal or nonfinite inputs are corrected or summed in compensated F64 rather than rounded away. Inputs already in F64 keep the ordinary implementation.

An eligible product has M and N divisible by four and K divisible by eight and at most 131064, and fits the tile and 2 GiB temporary-storage limits; other shapes keep the ordinary implementation. Timing uses normal inputs, so inputs with a wider exponent spread need more corrections and can run slower than measured.

high-precision

(high-precision
  (- (+ x 1e-9) x))

(high-precision body...) asks for F64 arithmetic on floating computations in its body, including functions it calls, under either run precision policy. CPU and CUDA support it; Metal does not support F64. Existing input rounding is preserved: widening an F32 tensor cannot recover digits it has already lost.

The form keeps the declared tensor dtypes, so an F32 expression still composes with F32 code. A value is converted back to that dtype when an ordinary operation reads it, or when it becomes a graph output or metric. Directly connected high-precision computations retain their F64 values, including across separate scopes. Use an explicit (cast value :f64) to keep an F64 result, or (cast value :f32) to round it deliberately.

Scalar literals used in arithmetic are read at F64 precision. Tensor constructors such as full and normal keep their requested dtype, including their default F32 dtype, and casts to physical dtypes keep their stated rounding. The :float kind conversion respects the scope's accuracy requirement. Integer and boolean computations retain their types.

Nested high-precision forms have the same effect as one. A surrounding or nested with-numerics does not weaken the accuracy requirement. with-numerics (:sensitivity :high) by itself still requests F32, not F64. matrix-scan, element-scan and top-k do not support F64; compute them outside high-precision.

with-numerics

(defun rms-norm (x &key (eps 1e-6))
  (* x
     (with-numerics (:sensitivity :high)
       (rsqrt (+ (mean (* x x) :axes [-1] :keepdims true) eps)))))

(with-numerics (:sensitivity :high) body...) annotates every node created while the body is evaluated. Under :bf16 such a node computes in f32 and its output stays f32, an f32 island until the value meets a bf16 tensor again. Above, the mean of squares and its reciprocal square root are f32 while the normalized activation comes back as bf16, as PyTorch's F.rms_norm returns its input's dtype. Under :f32 the annotation changes nothing.

matmul into an island

A bf16 matmul rounds its product to bf16 on store, and a sensitive node that reads it reads that rounded value, as PyTorch's autocast does. When the island needs the sum before rounding, ask for it:

(let ((v (matmul x w :out :f32)))               ; bf16 operands, f32 result
  (with-numerics (:sensitivity :high) (exp-map v)))

:out :f32 keeps the bf16 operands and the bf16 GEMM's speed and stores its f32 accumulator, an island like (cast x :f32). A matmul inside the island instead casts its operands up and runs a much slower f32 GEMM. The gradient reaches the operands as bf16, so the backward products stay bf16. On f32 operands :out :f32 changes no value. The interpreter and Metal hold bf16 values in f32 and round only at a cast, so there the unrounded product is what they already compute.

bf16 regions

(defun project (x w)
  (with-numerics (:precision :bf16)
    (matmul x w)))

(with-numerics (:precision :bf16) body...) is the reverse: every node created in the body computes in bf16 under either policy. Its float inputs are cast down, a parameter's once, as under :bf16; its products and stores round to bf16; and under :f32 its output is cast back up where a node outside the region reads it. A run can stay :f32 and put its products on tensor cores one region at a time.

The innermost form wins. A (:sensitivity :high) inside a region is an f32 island in it, which is how the library's marks keep softmax in f32 when a region calls it; a region inside a sensitive form clears the sensitivity for its own body. A region computes in bf16 even where every value it reads is f32, so a region around a whole model is not quite the :bf16 policy: that keeps a value f32 until it meets a parameter.

A region adds no choice that can vary between runs: its dtypes are fixed when the file compiles and it rounds nearest-even on every device. Fixed dtypes do not guarantee identical bits across runs; see determinism.

stop-gradient leaves its input's dtype and bits unchanged, whatever marks surround it; use a cast or mark the producing computation to change precision.

gradient

(gradient y x) (tensors) appends its backward nodes before the precision policy runs, so under :bf16 they are lowered like the forward, each value rounding to bf16 on store. The training backward is differentiated from the lowered graph instead, so the two need not agree bit for bit. Each backward node carries the marks of the forward node it differentiates, so the backward of a sensitive node is an f32 island too, and a with-numerics around the call stamps its marks on every node the call appends:

(with-numerics (:sensitivity :high) (gradient energy x))

computes the whole sweep in f32 under :bf16, though energy was not.

high-precision also applies to derivatives. Backward computations inherit the accuracy of the computations they differentiate; placing gradient inside high-precision requests F64 arithmetic for the whole sweep. The explicit gradient and the training backward can differ by F64 rounding.

Parameters

(defparam w init :numerics :high) keeps a parameter's uses in f32: the master weight is read directly instead of through a cast down. See models.

A frozen parameter (:trainable false) has no master weight. When every use of an f32 one is cast down to bf16, it is stored as bf16, rounded once when it is made or loaded: the same bits from half the memory. Under :bf16 that is any frozen parameter no sensitive node, nothing after the last product, no :numerics :high, no optimizer update and no buffer reads; under :f32, one read only inside (with-numerics (:precision :bf16)) regions, such as a teacher whose forward pass is one region. A use as (cast (stop-gradient p) :bf16) counts as a cast down. A frozen parameter read in f32 anywhere, including as a stopped output or observation, stays f32.

Update graphs are never precision-lowered: an optimizer reads every parameter in its declared dtype, so a frozen f32 parameter an update reads is stored f32, while the forward pass under :bf16 reads its rounded copy. explain counts each parameter at the size it is stored, and so does memory admission.

What the standard library marks

logsumexp, softmax, cross-entropy, softcap, the reciprocal square root of rms-norm and the statistics of batch-norm in sexpgpu/nn carry :sensitivity :high, and matrix-scan, with linear-scan through it, computes in f32, so a :bf16 run keeps them f32 without the file saying anything.

Seeing it

explain reports where the precision policy keeps f32, the lines after the last product as after last product, and under :f32 the lines of its bf16 regions. It counts float nodes carrying high-precision and :sensitivity :high in the training and evaluation graphs. Nonzero counts print beside the dtype counts. --json always includes numerics.high_precision_nodes and numerics.sensitive_nodes, including zeros. An explicit F64 cast alone does not count as a high-precision requirement.

--json also always carries numerics.ir_output_bounds, the worst float graph output per accuracy class under the IR rewrite laws. A class without float graph outputs is null; a present class has epsilon, retained_bits and bits_lost. Null epsilon means unbounded, while bit counts remain finite. Zero error retains 24 default-accuracy bits or 53 high-accuracy bits with zero lost. Text shows these bounds only for nonzero or unbounded IR spend.

CUDA product lines report conditional coefficients times C=S/R, the absolute-term-sum scale divided by the oracle-output scale. The line does not establish C or the law's finiteness, representability and accumulator conditions. Store-choice coefficients cover the product, excluding epilogue arithmetic; residue coefficients do not assume exact packing. Neither these coefficients nor IR-law bounds give a whole-plan error total. See explain for the reporting scope and scale definitions.

A cast to the same dtype is the identity. Arithmetic on values cast to bf16 computes in bf16 under either policy and rounds on store, as in a region. newton-schulz in sexpgpu/optim iterates in bf16 under either precision and returns f32. element-scan computes its body in f32; outer values keep their rounding before they enter it (element scans).

Determinism describes numerical agreement and the choices that can vary between runs.

Related: defrun, tensor operations.