tensor
tensor is the tensor library: arrays of numbers with a shape, and ops on them, such as add, matmul and softmax. Every op returns a new tensor, and no tensor changes in place.
Example #
Add a 2 by 2 tensor of numbers and a tensor of ones:
import Tensor from "pkg/tensor/tensor"
def main() -> Void
a = Tensor.floats([1.0, 2.0, 3.0, 4.0], [2, 2]).unwrap!
b = Tensor.ones([2, 2]).unwrap!
c = Tensor.add(a, b).unwrap!
puts(Tensor.to_list(c).unwrap!)
end[Values.Float(2.0), Values.Float(3.0), Values.Float(4.0), Values.Float(5.0)]Every op returns a Result. A shape, dtype or backend mismatch is an error, not a halt.
There is no operator overloading and no implicit broadcasting. Write Tensor.add(a, b), and widen a size-1 axis with Tensor.broadcast_to first.
Create and read #
A tensor has a shape, a dtype (its number type, such as F32, a 32-bit float) and a backend (where its values are computed).
zeros,ones,empty,full,like,arange(integer dtypes only),scalar_to_tensor.floats(values, shape, backend)makes anF32tensor from aList[Float].floats32(values, shape, backend)makes one from aList[Float32], which Agentica stores at 4 bytes an item. ggml, XLA and libtorch takeFloats across their native calls, sofloats32widens the list for them (one transient copy of 8 bytes an item).from_list(values, shape, dtype, backend)takes aList[Values]with one value per element ofshape.ValuesisFloat,IntorBool.from_file(path, offset, shape, format, backend, dtype)makes anF32tensor from the little-endian floats that start at byteoffsetof a file.formatisFloatFormat.F32(the default),F16,BF16,Q8_0,Q4_KorQ6_K. AQ8_0range is ggml's blocks of 32 values (34 bytes: a binary16 scale and 32 signed bytes), and it loads asF32on every backend, each value the scale times the byte, as ggml dequantizes it (exact).Q4_KandQ6_Kare ggml's blocks of 256 values (144 and 210 bytes), dequantized toF32by the same float32 operations as ggml's (the tests find the values of the officialggufpackage's dequantizer on random blocks, on every backend). libtorch and ggml read the file themselves, so the weights never become a list.Referencereads it in Agentica, which is slow on a large file. With the environment variableTENSOR_LOAD=agentica, libtorch and ggml take the bytes from an Agentica read instead (File.seekandFile.read_bytes), which is slower and uses more memory, for small models. A short file, a bad offset or a missing file gives anerror.from_bytes(data, shape, format, backend)makes anF32tensor fromBytesthat hold exactly its values asformatwrites them (little-endian,FloatFormat.F32by default), the same valuesfrom_filemakes of a range of a file. It is for bytes that are in memory, such as the pixels of an image.FloatFormat.U8takes one byte for each value and gives it as0.0..255.0, so the samples of aU8image cross into the backend as bytes, a quarter of the size ofF32ones, and the backend widens them toF32; it is forfrom_bytesonly, andfrom_fileandconvert_filerefuse it. libtorch and ggml read them in C, so no value becomes a list;ReferenceandXladecode them in Agentica. Adataof another size gives anerror. The libtorch andXlaarms offrom_bytesare not tested in CI, as those offrom_fileare not.from_file(..., dtype: Dtype.F16)makes a half weight: the ggml backend keeps the values in 16 bits, converted at load fromF32,F16orBF16, which halves the memory and the bandwidth of a weight and speeds up the decoding that streams it. A value beyond 65504 is anerrorthat names its element; a value too small for F16 (a BF16 one, for instance) becomes a subnormal or zero. Only ggml and XLA hold one (any other backend gives anerrornaming the option). On ggml a trace may use it only as the weight ofmatmulandlinear(uselinear(..., out_in: true)with a checkpoint's[out, in]weight, or every run copies the transposed weight) and as the table ofgatherandembedding, whose rows stayF16in the trace and are widened withto_dtype(rows, F32). Any other use on ggml is anerrornaming the op (anF16output is allowed only for the cache below). On XLA anF16tensor is an ordinary one: an op onF16operands computes in half and answersF16, a product or a lookup of anF16weight by anF32input is computed inF32(the program widens the weight where it reads it, and the buffer stays 16 bits), andto_dtype(x, F32)widens anyF16tensor.from_listrounds to nearest even and refuses a value beyond 65504, an infinity included, naming its element; a NaN stays a NaN. Widening anF16input withto_dtype(x, F32)runs, a half weight passed as an input included (the lowering cannot tell it from a cache): it makes a fullF32copy on every run; a half weight that is a constant of the function is refused. It is for inference:value_and_gradrefuses a half weight, on ggml and on XLA.matmulanswersF32and the activations stayF32too (on ggml CPU and on Vulkan at its default, within 1e-7 of an exact sum); withTensor.vulkan_fp16(true)the product runs in fp16 (about 2e-3 off on outputs of 0.4, and an activation beyond 65504 overflows), as it does for anF32weight, and a CPU kernel that rounds activations to F16 would be good to 2^-11 relative per product.F32stays the default and the exact path.from_file(..., dtype: Dtype.BF16)makes a BF16 weight on ggml, Torch or XLA. A BF16 file keeps its values, including signed zero, infinities and NaNs. F32 and F16 files round to nearest even, and values outside the finite BF16 range are rejected. Products with F32 activations widen the weight during compute. A lookup can widen just the selected rows. Stored weights use half the bytes of F32, and conversions can allocate F32 temporaries.from_file(..., format: FloatFormat.Q8_0, dtype: Dtype.Q8_0)makes a quantized weight: the ggml backend keeps the blocks of the Q8_0 file as they are, about a quarter of the memory ofF32;format: Q4_K, dtype: Q4_Kandformat: Q6_K, dtype: Q6_Kkeep a seventh and a fifth.packed?(dtype)is true for these dtypes and forF16. It is a rank-2 weight whose rows hold whole blocks (32 values, or 256 for the K types), and any other backend or anotherformatgives anerror. A trace uses it as a half weight is used (the weight oflinear, the table ofgatherandembedding, no gradient, never an output), andlinearmust be called without_in: true: amatmulby the weight itself is anerror, since its transpose would copy blocks. The rows ofembeddingcome out exact. ggml rounds the activations of a product to Q8_0 blocks (llama.cpp does the same), so the answer is good to the half step of that rounding and of its scale's rounding to F16,amax * (1 / 254 + 2^-11)of a block of 32 activations per product, and not toF32's 1e-7; with a K type the blocks hold 256 activations and the scale is a binary32, so the step isamax / 254of a block of 256.to_listof one dequantizes it.append_file(t, path)appends the values of theF32tensort, row-major and little-endian, to a file that exists: the bytes thatfrom_filereads back withFloatFormat.F32, for writing a checkpoint. libtorch and ggml write from C, so no value becomes a list;Referenceencodes them in Agentica (slow on a large tensor, and every NaN is written as the canonical one). A tensor of another dtype or a missing file gives anerror.convert_file(src, src_offset, src_format, count, dst, dst_offset, dst_format)writes thecountfloats ofsrc_formatthat start at bytesrc_offsetof one file into the existing filedstasdst_format(F32,F16orBF16), for writing a checkpoint. C does it in chunks on several threads, so no tensor and no list exists. The same format is a copy of the bytes; a narrower one rounds to nearest even, and a value beyond 65504 is anerrorforF16. It needs the ggml module and works on files only, whatever the backend.dtypedefaults toF32andbackendtoReferenceinzeros,ones,fullandfrom_list.to_list(t)reads a tensor back as aList[Values].shape,dtypeandbackendread the fields of a tensor, with no call to a backend.
Ops #
- Elementwise, one value at a time, floats only:
add,sub,mul,div,neg,exp,log,sqrt,pow,relu,sigmoid,tanh,gelu_tanh_approx,gelu_erf,clamp. - Comparisons:
eqandlt(floats or integers) give1.0or0.0.where(cond, a, b)selects with aBooltensor. - Reductions:
sum,mean,max,argmax, each withaxes(nonefor every axis, or a list) andkeep_dims.argmaxgivesI64. - Matrix products:
matmul(rank 2),transpose(reverses every axis),batch_matmul(rank 2 or more, one batch shape). - Axes:
permute(t, axes)puts input axisaxes[i]at output axisi. - Attention:
attention(q, k, v, mask: none, scale: none, causal: false)issoftmax(scale * q k^T + mask) vover[batch, heads, q_len, head_dim]tensors.kandvmay have fewer heads, as long as they divide the heads ofq(grouped-query attention). The mask is added to the scores and is[q_len, k_len]or[batch, heads, q_len, k_len], with1allowed forbatchandheads; it takes finite values and-inf, and it has a gradient.causal: truehides the keys after each query, with the last query on the last key, so it needsq_len <= k_len. A query with every key at-inf, or aNaNanywhere, is an error on every backend: to hide a padding position use a large finite negative number, as Hugging Face does. What a query whose every key is hidden by such a number returns is unspecified: the mean ofvonReferenceand in the fallback of ggml, the softmax of its scores on ggml's flash attention. OnReference,q_len * k_lenof the causal mask stops at 1,048,576. The scale defaults to1 / sqrt(head_dim). - Rotary embedding:
rope(x, positions, base: 10000.0, dims: none, neox: true, inverse: false)turns the firstdimscolumns of each row ofx([..., seq, width]) in pairs by the anglepositions[row] * base^(-2i/dims).neoxpairs columniwithi + dims/2, andneox: falsepairs2iwith2i + 1.positionsis an integer vector with one position per row, shared by every batch and head, andinverse: trueturns the pairs back. - Shape:
reshape,squeeze,unsqueeze,slice,concat,stack,broadcast_to,gather(rows at integer indices),top_ids(x, k)(the ids of theklargest of a float vector,I32[k], or of each row of a matrix,[rows, k]: descending on the reference, in no order on ggml, where it is one device node and only the ids cross to the host; the derivedtop_kreads the whole vector),set_rows(cache, rows, positions)(a copy ofcache[..., rows, width]with its rowspositions[i]replaced, the positions distinct; seeTrace.run),scatter_add(indices, updates, rows)(the inverse ofgather: it adds the rows ofupdatesintorowszero rows, and a repeated index sums its rows). - Convolution:
conv1d(stride and padding; no dilation or groups),avg_pool1d. For images of[N, C, H, W]:conv2d(input, weight, stride: 1, padding: 0, groups: 1)with a[C_out, C_in / groups, KH, KW]weight, andmax_pool2d(input, kernel, stride: 1, padding: 0)andavg_pool2d(the divisor is alwayskernel * kernel). The stride and the padding are the same on both axes, the padding of a pool is at most half the kernel, and there is no dilation. Their gradients work on every backend; the gradient of aconv2dneeds a padding smaller than the kernel, andmax_pool2dsends the gradient to the first maximum of a window. XLA has no lowering for the convolutions, as forconv1d. On the ggml CPU backend aconv2dwhose(KW * KH * C_in + C_out) * 4bytes (per group) do not fit in 16 MiB is anerror, because ggml's kernel works in a buffer of that size (its gradient cuts a big batch in chunks to stay under it); Vulkan has no such limit. Amax_pool2dof ggml starts from-FLT_MAX, so a window ofNaNor-infgives different answers on the backends: do not rely on them. - Movement and dtype:
to_dtype,to_device,copy,contiguous,stop_grad. - Mixture of experts:
expert_matmul(weights, x, ids)multiplies, for each tokentand each useu,x[t, u]([tokens, uses, inner], or one use[tokens, 1, inner]shared by all of them) by the matrixweights[ids[t, u]]ofweights[experts, rows, inner], withidsanI32[tokens, uses](fromtop_ids, say), and gives[tokens, uses, rows].F32only, no gradient. ggml runs it as oneggml_mul_mat_idnode (CPU and Vulkan); the other backends that compute loop over the pairs, and XLA has no lowering. An id outside the experts is anerror.pkg/nn/moehas the block. - Linear attention:
gated_delta_rule(q, k, v, g, beta, state)is the gated delta rule of Qwen3.5 over[tokens, heads, width]tensors (qandkalready L2-normalized), withgandbetaof[tokens, heads]and astateof[heads, width, width](value axis first) that it updates token by token and gives back with the answers, as aDeltaRulewithoutandstate. The op scalesqby1 / sqrt(width)itself, so do not scale it again. A token withg = 0andbeta = 0leaves the state as it was.F32only, no gradient. ggml runs it as oneggml_gated_delta_netnode (CPU, and Vulkan for widths 16, 32, 64 and 128); the other backends that compute run the recurrence token by token, which is slow for a long sequence, and XLA has no lowering. - Sorting and decoding:
top_k(x, k)gives theklargest values of a rank-1 float tensor, descending, as aTopKwithvaluesandindices(I64). Ties keep an unspecified order, and a non-finite value is anerror.beam_search(logits, width)reads[steps, vocab]logits and gives thewidthbest token rows asI64 [width, steps], best first. It ranks each path by the sum of its logits, with no softmax and no end token, andwidthis from 1 tovocab. - Optimizer kernel:
adam_step(p, g, m, v, hyper)is the update of Adam and AdamW, whichtrain/'sOptimuses (you callOptim, not this). It gives the new[p, m, v]from a weight, its gradient, the two moments andhyper, a rank-1 tensor of 7 numbers (the learning rate,beta1,beta2,eps, the weight decay,1 / (1 - beta1^t)and1 / (1 - beta2^t)). In a trace ofF32tensors of rank 3 or less, ggml runs it as oneggml_opt_step_adamwnode, on copies of the arguments inTrace.evalandTrace.eval_many; elsewhere it is a composition of the ops above, which is also whatTrace.stablehlowrites for the node. In a function compiled byTrace.compileit writes the momentsmandvin place when they are inputs that no other node reads (once each, not outputs) and their two results are outputs:Trace.runthen gives back those very tensors, with the new values, so the tensors given are consumed (even when the run fails), as forset_rows;Trace.donated(compiled)says which outputs are such inputs. The weight is never written. It has no gradient. - Built from the above:
softmax,gelu(the tanh form),silu,softplus,l2_norm(x, eps)(x / sqrt(sum(x * x) + eps)over the last axis),dot,linear,embedding,multi_head_attention(over[batch, seq, width], it isattentionbetween a split and a join of the heads).layer_normandrms_normare built from them too, but a trace records each as one node, so ggml runs one norm (ggml's Vulkan backend can fuse the product by a weight after an rms norm) and the gradient has a rule of its own.greedy_step(logits, temperature: none)takes the argmax of rank-1 logits; atemperatureabove 0 scales them first.dropout(x, p)is the identity at inference, andpmust lie in0..1.
Backends #
Torch runs on libtorch, the C++ library under PyTorch. Ggml runs on ggml, a small tensor library in C. Xla runs on XLA, the compiler under JAX.
| Backend | Where it computes | Needs |
|---|---|---|
Backend.Reference | Agentica code over lists of floats; the answer the tests trust, and the other backends are checked against it | nothing |
Backend.Torch(Device.Cpu) | libtorch (2.4.1 to 2.9), one op at a time | libtorch (optional) |
Backend.Ggml(Device.Cpu) | ggml on the CPU | the ggml module (optional) |
Backend.Ggml(Device.Vulkan(i)) | ggml on Vulkan device i, counted over the devices that are not a CPU | a ggml build with Vulkan |
Backend.Xla(Device.Cpu) | XLA on the CPU, a compiled function at a time | the XLA plugin, installed below (Linux x86_64 and aarch64) |
Backend.Xla(Device.Neuron(i)) | XLA on an AWS NeuronCore, a compiled function at a time | Neuron's plugin, named by AGENTICA_ML_NEURON_PLUGIN (XLA on AWS Neuron) |
Backend.Trace | nothing: it records a graph of the ops, see below | nothing |
A device is where the values are computed. Reference and Torch serve Device.Cpu only, and Device.Neuron is for Xla only.
A tensor carries its backend, so tensors on different backends can live in one program. An op over tensors on two backends is an error.
Tensor.available(backend) says whether a backend works on this machine. A backend needs its native module (compiled C or C++ code). Without it, the backend answers error("backend not available").
Torch has 51 of the 52 primitives (the basic ops). to_device answers an error that names the op.
On Ggml, a direct call to an op is an eager call: it runs the op right away. Eager calls only create, read and copy tensors. Every other op is an error that points to Trace, because ggml is fast when a whole computation is one graph.
Tensor.to_device(t, Device.Vulkan(0)) moves a ggml tensor to another ggml device.
Tensor.device_memory(backend) gives the Tensor.DeviceMemory(free, total) in bytes of the device a ggml backend runs on (ggml_backend_dev_memory): the card for Ggml(Device.Vulkan(i)), the RAM of the host for Ggml(Device.Cpu). It opens no backend and allocates nothing. Another backend, a Vulkan device that is not there or a build without the ggml module is an error naming device_memory. On a card that shares memory with the host (an iGPU) the numbers are what the driver lends, and free falls as other programs take memory, so it is a reading of the moment. Placement.fit and Placement.budget of the transformers page turn it into a layers_on_device.
A graph on a Vulkan device may also read tensors on Ggml(Device.Cpu), which is how a model puts some layers on the CPU (layers_on_device of the transformers page). Such a graph runs through ggml's backend scheduler over the two backends: a node that reads any tensor on the CPU (a weight, a cache) runs on the CPU, a product or a row lookup that reads a matrix on the device (a weight, however small) runs on the device, any other node where most of its operands are, a tie going to the side of the product that the node reads, so the residual stream follows the layer it passes through whatever the order of the operands (a node that nothing decides, such as a table of constants, goes where its consumers are, so the residual stream of a layer on the CPU stays there), the activations are copied where the two sides meet, and an output made by a node on the CPU is a Ggml(Cpu) tensor, so a KV cache whose layer is on the CPU stays in host memory and is written there, in place. Binding a tensor on the CPU to a graph on a Vulkan device used to be an error and now selects this path. A graph whose tensors are all on the device never uses the scheduler and runs as before. On a CPU-only machine, or for a model on the CPU, there is nothing to mix. The activations cross the bus once per boundary between the two sides, which costs little on an iGPU that shares the memory of the host and more on a discrete card; the layers on the CPU run at CPU speed. A weight in the pinned host memory of the card is not an option: ggml's Vulkan backend refuses buffers that are not its own.
Xla works like Ggml: eager calls only create and read tensors, and every other op is an error that names it. Trace.compile turns the function into StableHLO and XLA compiles it once, and Trace.run runs it. Trace.eval, eval_many and value_and_grad compile for each call, and a cache of the last 32 programs makes a function traced again compile once. As on ggml, the moments that adam_step updates in place are written over: on XLA the run consumes them, so read the new ones it returns. XLA comes as a plugin that the package loads when it first needs it and never links. Install it once, from the tensor folder:
agentica tools/install_xla.agcIt downloads the plugin of your machine from the release of agentica-lang/ml that the package pins (our build of XLA's PJRT CPU plugin, with the licenses of what it links), checks its sha256 and keeps it in ~/.cache/agentica-ml/xla/ (or under AGENTICA_ML_CACHE). The release has the plugin for Linux on x86_64 and aarch64 only, and CI tests x86_64 only; macOS and Windows are not supported yet. On x86_64 the plugin needs a CPU with AVX. On any other system, and before the install, Tensor.available(Backend.Xla(Device.Cpu)) is false and an op answers an error that names the install step.
The ggml CPU backend runs a graph on one thread per physical core of the machine, not per hardware thread: its threads wait for each other by spinning, so a second thread on a core adds stalls when the machine is busy. On Linux the cores are the ones this process may use (a cpuset limits them; a CPU quota does not). Set the environment variable TENSOR_THREADS to a positive integer, at most 512 (ggml's limit), to choose the number; any other value leaves the default.
Tracing and gradients #
The matrix product of two tensors on the reference backend, and the gradient of a sum of it. The Trace call runs the function once and gives the value and the gradient together:
import Tensor from "pkg/tensor/tensor"
import Trace from "pkg/tensor/trace"
def main() -> Void
a = Tensor.floats([1.0, 2.0, 3.0, 4.0], [2, 2]).unwrap!
b = Tensor.floats([5.0, 6.0, 7.0, 8.0], [2, 2]).unwrap!
puts(Tensor.to_list(Tensor.matmul(a, b).unwrap!).unwrap!)
both = Trace.value_and_grad([a]) do |ps|
Tensor.sum(try Tensor.matmul(ps[0], Trace.constant(b)))
end
result = both.unwrap!
puts(Tensor.to_list(result.value).unwrap!)
puts(Tensor.to_list(result.grads[0]).unwrap!)
end[Values.Float(19.0), Values.Float(22.0), Values.Float(43.0), Values.Float(50.0)]
[Values.Float(134.0)]
[Values.Float(11.0), Values.Float(15.0), Values.Float(11.0), Values.Float(15.0)]Trace runs a function on Trace tensors. They record a graph instead of computing, and the graph then runs on a real backend.
Trace.eval(args, f)gives the value offon the backend ofargs.Trace.grad(args, f)gives the gradient of a scalar function for each argument.Trace.gradients(out, wrt)is the same step on traced tensors: it gives the gradient graph of the traced scalaroutfor each traced tensor ofwrt, and zeros for a tensoroutdoes not depend on.Trace.value_and_grad(args, f)givesvalueandgradsfrom one evaluation.Trace.eval_many(args, f)gives several tensors from one evaluation:fanswers aListof tensors, and onGgmlthey are one compiled graph.Trace.constant(t)adds a tensor from outside, such as data or labels, to the trace. No gradient is taken for it.Trace.node_count(outs)gives the number of distinct nodes thatoutsreach, which is what one evaluation computes.Trace.compile(specs, f)tracesfonce and gives aCompiledfunction.Trace.run(compiled, args)runs it any number of times and gives whateval_manygives, without tracingfor planning the graph again.
Trace.eval and eval_many trace f and plan the graph on every call, then reuse the compiled ggml graph by its structure. Trace.compile does that work once:
specslists each input's shape, dtype and backend (Trace.spec_of(t)takes them from a tensor).fgets one traced input per spec and answers aListof tensors.- Whatever changes between runs must be an input: the parameters of a training step, a KV cache. A tensor that
fbrings in withTrace.constantis fixed: every run reads the same tensor. So is the value of afullinf. - A constant must stay open while any task may run the
Compiledfunction. A run that starts after its owner closed a constant is anerrorthat names the leaf. A run that already bound it keeps its memory until the run ends, so a close in the middle of a run does not break that run. runchecks its arguments against the specs, one tensor per spec. A different shape, dtype, backend or count is anerrornaming the input. It never compiles another graph; make oneCompiledfor each shape.- On ggml the graph lives in the process-wide cache of 32 graphs (least recently used out), and
compilepins it there: the cache does not evict it while the pin lives. The pin belongs to the task that calledcompileand ends with that task or atTrace.close(compiled); a function that no longer runs should be closed, or its pin takes a slot until its task ends. TheCompiledstill runs after the pin ends, and a run that finds its graph evicted builds it again. A run that finds its graph in use by another task sends the nodes again and compiles another copy, though it still does not tracefor plan the graph. When no slot is free (every graph is in use or pinned),compilepins nothing and the function runs as an ordinary graph, asevalandeval_manydo.Trace.close_constants(compiled)also closes the constants the function read from outside its inputs (for a function that owns them, such as a log-mel graph's filters): a run after it is an error naming a closed constant. Trace.run(compiled, args, into)writes the outputs thatintonames into tensors that exist (one entry per output,nonefor a new tensor), so a loop that feeds an output back as the next input allocates nothing: the tensor has the output's shape, dtype and backend, is not an input or a constant of the run or another output (that is anerror), is not closed, and is overwritten by the run.set_rowsin a function run on ggml writes the cache in place. The cache must be an input of the function that no other node reads, the result of theset_rowsmust be an output, and an input is not also an output; a function that breaks one of these does not compile, and the error names the node.Trace.runthen gives back the very tensor it was given as that output, with the rows written: the tensor given is consumed, whoever holds it sees the new rows (and nothing else may use it after). The cache is consumed even when the run fails: a position outside the cache is found after the write, and the rows are clamped into it. The cache must beF32, orF16(the key-value cache oftransformers): the rows areF32and ggml rounds them toF16as it writes them, within 2^-11 relative (a value beyond 65504 becomes infinite, as in llama.cpp);to_dtype(x, F16)makes anF16tensor on ggml,to_dtype(cache, F32)widens anF16input, andattentionreads anF16key and value (with anF32query) without a copy.Trace.evalandeval_manyare functional: they write a copy and leave the cache alone.intocannot name a tensor for such an output, and the cache cannot be given for two inputs. On every other backend the result is a new tensor and the cache is not written.set_rowshas no gradient.- A cached ggml graph owns no weights and no data: it is the structure (ops, shapes, dtypes), and a run binds tensors to it. A
Compiledfunction leaves its constants bound to its pinned graph between runs, so a run binds only its inputs; closing a constant, or the pin, unbinds them. ACompiledfunction holds only whatfbrought in withTrace.constant, so a function that takes its weights as inputs (the encoder blocks ofasr/do) serves any checkpoint of the same shapes, and one that closes over its weights as constants belongs to those tensors. fmay computeTrace.gradientsand the update of the parameters, so a training step (forward, backward and update) is oneCompiledfunction that answers the loss and the new parameters.- Several tasks may run one
Compiledfunction. - On
ReferenceandTorchthe traced graph is kept and evaluated node by node on every run.
Finding a parity bug #
When two backends give different results, Trace.diff(args, a, b, f) finds the first node where they disagree. It traces f once, runs the graph on the backends a and b (args are copied to a backend only when they live elsewhere), and compares every node that the result of f reaches:
d = try Trace.diff(args, Tensor.Backend.Reference, Tensor.Backend.Torch(Tensor.Device.Cpu)) do |xs|
Tensor.exp(try Tensor.add(xs[0], xs[1]))
endd.firstis the first node, in graph order, whose output is outside the tolerance while its inputs are within, ornone. It is aNodeDiff: thenodeid,op,shape,dtype, the shapes of its arguments (inputs),max_absandmax_rel(the largest absolute and relative gap over its elements) andwithin.d.nodescounts the nodes compared, andd.worstlists the five with the largestmax_abs.- A float element agrees when
|a - b| <= atol + rtol * max(|a|, |b|); the defaults arertol: 0.0001andatol: 0.000001, andTrace.diff(args, a, b, rtol: 0.001) do ... endchanges them. Integers andBools must be equal. A non-finite value that the other side does not have is an infinite gap. - On
Ggmlthe nodes run 400 at a time, to stay under the 512 outputs of one graph, and each slice runs its ancestors again from the inputs.ReferenceandTorchrun all the nodes at once. - The comparison runs on the host, so it is slow on big activations.
- An op that overflows to infinity on
ReferenceorTorchmakes the next node anerror, anddiffreturns it. - Everything
fneeds from outside must be an argument. ATrace.constantlives on one backend, and running it on the other is anerror.
A backward rule tells how to get the gradient of an op. These ops have no backward rule, so the gradient is an error that names the op: pow, clamp, to_dtype, batch_matmul, conv1d, avg_pool1d, and a to_device across devices.
On Ggml, Trace.eval, eval_many, grad and value_and_grad compile the whole graph, forward and backward, into one ggml graph. See How it works.
StableHLO #
Trace.stablehlo(specs, f) traces f once, over inputs of the shapes and dtypes of specs, and gives a Module: text is a StableHLO program that XLA (through PJRT) and IREE read, and constants are the tensors that f brought in with Trace.constant.
- The program is one
@mainthat takes the inputs, then the constants, and returns the tensorsfanswered. Shapes are static. - It covers the ops of an MLP forward and of a training step:
add,sub,mul,div,neg,exp,log,sqrt,tanh,relu,gelu_tanh_approx,matmul,transpose,reshape,broadcast_to,sum,mean,max,eq,lt,where,arange,slice,full,stop_grad,gatherandadam_step(as the ops it composes). Another op is anerrorthat names it. Train.stablehlo(loss, params, batch, optimizer)gives the step offitas one program: the arguments are the parameters, the optimizer's moments, the inputs of the step (Optim.step_inputs(state): SGD's learning rate as a rank-0 tensor, Adam's 7 numbers as a rank-1 tensor, AdamW's two such rows), then the batch; the results are the loss, the new parameters and the new moments. Feed the results back in, with the inputs of the next step, to train.- The repository checks the text against snapshots, and the reference backend against the outputs IREE gave for the same text (
make iree-goldensmakes them; IREE is not needed to run the tests).
Dtypes and fp16 #
DtypehasF32(the dtype that ops compute in),F16,F64,I8,I16,I32,I64,U8,Bool,Q8_0,Q4_KandQ6_K(the quantized weights of ggml, fromfrom_fileonly).ReferencecomputesF16andF64exactly, in doubles (64-bit floats).- ggml holds
F32andI32as they are.Bool,I8,I16andU8are held asF32, which is exact for them.F64andI64are refused on ggml, andF16and the quantized dtypes are held only as a half or a quantized weight fromfrom_file, except anF16cache (to_dtype(x, F16), written byset_rows, read byattention, whole or as asliceof it, and widened byto_dtype). A slice that starts at the first element is read by flash attention where it is, with no copy. - XLA holds
F32,F16,F64,I32,I64,I16,I8,U8andBool. The quantized dtypes are refused, so there are no quantized weights on XLA.from_file,from_bytesandfrom_listmake anF16weight, which a product or a lookup reads asF32: the values are rounded to F16 once, at load. - Vulkan products run in fp16 (16-bit floats) by default, which is faster for the products of a model (up to about 1.8 times on a large one,
benchmarks/README.md). They are not exact against Hugging Face: the greedy ids of a model can differ.Tensor.vulkan_fp16(false)makes them run in exactF32for the whole process. Call it before any other ggml call (availableof a Vulkan device included). A later change is an error. AGGML_VK_DISABLE_F16exported by the user, with no call, keepsF32. Gradients change by up to about 10 % at MLP sizes with fp16.
Limits #
- Exact integers:
F32holds integers exactly up to 2^24 (16 777 216). On ggml, anI32value beyond that, or anarangeor fill beyond it, is an error, not a wrong number. - Output cap: one ggml graph returns at most 512 outputs.
value_and_gradreturns the value and one gradient per argument, so ggml takes at most 511 arguments. - Rank: ggml holds tensors of rank 4 at most.
- Positions: on ggml, the
positionsofropeare any integer dtype butI64, which is refused. ggml turns by an angle it makes inF32, so at positions in the thousands it is a few 1e-4 off the reference. - Gather: on ggml, the source of a
gather, the answer of ascatter_addand the cache of aset_rowsand a row of atop_idshold at most 2^24 rows, because its integer indices are exact inF32only below that. - Non-finite values:
exp,log,sqrt,pow,sigmoid,tanhandgelu_tanh_approxrefuseNaNand infinite inputs, except thatexp(-inf)is0. A ggml output that is not finite, or whose sum overflowsF32(exp(80)over 10 000 values), is an error, except the cache thatset_rowswrites in place and the first moment thatadam_stepwrites in place, which are not checked (the second moment is, and the new weight). - Integers: an integer overflow is an error, never a wrap-around. On libtorch, readback of
I64past 2^53 loses precision. - Speed:
Referenceis for checks. On one machine, a 64 x 64 matmul took about 6.6 ms onReferenceand 33 µs on libtorch (tensor/README.md).
How it works #
- libtorch and ggml are not in this repository, and they are never vendored.
tensor/README.mdhas the setup. - On
Ggml, a traced function becomes one ggml graph, forward and backward. The graph is cached by its structure, so a retrace with new values compiles nothing. - ggml maps the ops of an MLP and of softmax cross-entropy, with their gradients, to its own graph ops. It does the same for
slice,gatherandscatter_add, and for attention:attentionis one flash attention kernel when the mask is absent or made of fills (0 and a large negative number, as the causal and the padded masks are), and two matrix products and one softmax otherwise;ropeis ggml's rotary embedding.tensor/DESIGN.md§7 has the list.
More #
tensor/README.md has the setup, the coverage table and the tolerances. tensor/DESIGN.md is the contract.
- Guide tensor
- Design tensor — design
- XLA on AWS Neuron