tensor — design
The contract of tensor/: the types, the backend interface, the traced graph
and its gradients. Section numbers are cited from the code, so they keep their
gaps.
References: ml#1 (goals and the grad-in-Agentica decision), agentica#1091 (native arenas; see §8), and agentica#1918 (opaque native resources that can live in data and cross modules; closed without them, see §1).
1. Goals and scope #
- Training and inference.
tensor/andnn/(forward) run overreference(the pure Agentica oracle), libtorch (eager), and ggml and XLA (compiled traces, §7);train/(losses, SGD/Adam, a training loop) and the tracedgrad/value_and_gradit needs sit on the same primitives (§10). - Every backend is forward-only.
gradlives in Agentica over a traced graph (ml#1 key decision, as Nx does), so per-backend autograd is out. - The backend interface is small, and one shared conformance suite checks every backend against the reference (§11).
tensor/declares the native module of every backend it dispatches to (torch,ggmlandxla). ATensorcarries the backend's handle, and a native handle is aresource: resources are nominal to theextern moduleblock that declares them and cannot cross into another module, soHandle(§2) can only name a handle type declared in this package, and theTorcharm of §7 can only call a module declared here. The module isoptionalinagentica.toml, so a machine without libtorch still checks, formats and tests with the arm answeringerror("backend not available");Tensor.available/1answers the same question before a call does. The cost is thattensor/ships the thin layer of each backend and its build table. agentica#1918 asked for a resource that crosses modules and was closed without it: a resource is still nominal to its block. Agentica's answer is a data type generic over the handle (Tensor[H],Ops[H]) that the backend fills in (native-modules.mdof its programming skill).tensor/does not use it, so the backends stay in this package.
2. Types #
Dtype = F32 | F16 | BF16 | F64 | I8 | I16 | I32 | I64 | U8 | Bool | Q8_0 | Q4_K | Q6_K # the last three: quantized weights of ggml only (§7)
Device = Cpu | Vulkan(Int) | Neuron(Int) # enum; Vulkan(i): ggml's device i
Shape = List[Int] # static ints, row-major C-order
Values = Float(Float) | Int(Int) | Bool(Bool) # enum, dtype-tagged
Backend = Reference | Torch(Device) | Trace | Ggml(Device) | Xla(Device) # enum, see §7, §10
Handle = Native(TensorHandle) | Plain(Data) | Traced(Node)
| Ggml(ggml TensorHandle) | Xla(Buffer) # enum, see §2, §8, §10
Tensor = { shape: Shape, dtype: Dtype, backend: Backend, handle: Handle }Devicenames where a backend computes:Cpu,Vulkan(i), the Vulkan deviceiin ggml's numbering, orNeuron(i), an AWS NeuronCore.Backend.Torch(Device),Backend.Ggml(Device)and every backend function take the device explicitly (§4).TorchandReferenceserveCpuonly;GgmlservesCpuandVulkan;XlaservesCpuor, underAGENTICA_ML_NEURON_PLUGIN, everyNeuron(i)the process sees (§7).Tensorvalues are immutable; every op returns a newTensor. A training step returns new parameters.handleisNative(TensorHandle)on the libtorch backend (astruct NAME_state *+ thread-safeNAME_FREE, C data only, never terms; valid only during the call, never stored),Ggml(TensorHandle)on the ggml backend (the resource ofextern module "ggml"insrc/ggml_native.agc: a ggml context and the backend buffer of one tensor on its device),Xla(Buffer)on XLA (a PJRT buffer,src/xla_native.agc), andPlain(Data)onreference, whereDatais plain Agentica data.TensorHandleis the resource theextern module "torch"block ofsrc/native.agcdeclares: a resource is nominal to its block, so the handle type has to be the concrete one and it has to live in this package (§7). A backend that only reads a handle it did not make answerserror, never a stopped task. This follows the repo's FFI rules (extern moduleis the only source of signatures; native-gen regenerates the header; blocking work iscompute defon the compute pool;List/Mapcross via cursors/builders).- Dtype rule: numeric compute is
F32;F16andF64weights are converted to it on load (§6, lossy forF64), except the half and quantized (Q8_0,Q4_K,Q6_K) weights that ggml keeps as they are (§7). Two kinds of non-F32compute tensors are required by the op set itself:Boolmasks (eq,lt, the condition ofwhere) and integer index tensors (gatherindices,argmaxoutput). The other table entries are checkpoint dtypes only (§6), kept as indices or masks at runtime; the table grows only when a consumer requirement (§5) or conformance demands it. - No operator overloading:
Tensor.add(a, b)plus pipes (t |> Tensor.add(other) |> Tensor.relu()).
3. Primitives vs derived ops (the split) #
Primitives are the only functions a backend implements. Everything else is derived: pure Agentica code over primitives, shared by all backends and therefore tested once.
3.1 Primitives (the backend contract, 52 ops) #
Creation: zeros, ones, empty, full, like, arange, scalar_to_tensor.
Elementwise: add, sub, mul, div, neg, exp, log, sqrt, pow, relu, sigmoid, tanh, gelu_tanh_approx, eq, lt, where, clamp.
Every transcendental here refuses NaN and infinite input, except that exp(-inf) is 0
(a masked score). On libtorch the check is one aminmax reduction, and exp flushes a denormal result to 0 on purpose:
an input below -87.33 in F32 (-708.39 in F64) gives 0, where the reference keeps a denormal and libtorch is 3 to
10 times slower computing one. A raw exp below that edge then feeds log a 0 (an error on libtorch, a finite number on the reference), and
a ratio of two such values is 0 / 0 (an error on div).
Reductions: sum, mean, max, argmax (each with axes: Optional[List[Int]],
keep_dims: Bool).
Linear algebra: matmul, transpose, batch_matmul (plain dot is derived).
Attention: permute, attention, rope. permute(t, axes) is the general axis
permutation (transpose reverses every axis). attention(q, k, v, mask?, scale?) is softmax(scale q kᵀ + mask) v over [batch, heads, q_len, dim],
with grouped-query attention when the kv heads divide the heads; the mask is
additive (finite or -inf; q, k, v and the mask are never NaN, and a query whose
every key is -inf is an error on every backend), and causal: true is the
wrapper's, which builds the causal mask from arange and lt (it needs no more
queries than keys). rope(x, positions, base, dims, neox, inverse) is the
rotary embedding of x [..., seq, width]. They are primitives so that ggml and
libtorch can use their fused kernels, and so that the graph has one node where
the per-head loop had a hundred; each has a backward rule over the primitives
(§10.3).
Shape: reshape, squeeze, unsqueeze, slice, concat, stack, broadcast_to, gather, scatter_add (embedding lookup and beam gather need gather, and its
backward rule needs scatter_add(indices, updates, rows), which adds the rows
of updates into rows zero rows at indices; everything fancier is
derived).
set_rows(cache, rows, positions) is the one op that writes: a copy of cache
with its rows at the (distinct) positions replaced, on every backend but
ggml. In a function run on ggml (Trace.run) it writes the cache where it
lies, which makes the cache an input that no other node reads, the result an
output, and the output the very tensor given: the tensor is consumed, even by
a run that fails (a position out of range is found after the write, and is
clamped into the cache), and it is not checked for finite values. The cache
must be F32. Trace.eval writes a copy and leaves the cache alone. The
check is at lowering, naming the nodes, so a KV cache is not copied at every
step of a generation. On XLA a function compiled by Trace.compile writes in
place where the same holds, and copies otherwise (§7). It has no gradient.
top_ids(x, k) (the ids of the k largest of a float vector, I32 [k], or of
each row of a matrix, [rows, k]) is a node ggml_top_k runs on the device,
so a decoder can read back k logits and their ids and not the whole
vocabulary, and a router picks the experts of every token in the graph; the ids
are in no order on ggml, and the derived top_k stays on the host. It has no
gradient.
expert_matmul(weights, x, ids) (the core of a mixture of experts: for each
token and each of its uses, the product of the expert ids[t, u] of
weights [experts, rows, inner], a checkpoint's layout, with x[t, u], or
x[t, 0] when x has one use) is one node, which ggml runs as
ggml_mul_mat_id with the weights as they are (CPU and Vulkan). Every other
backend that computes runs a loop over the pairs, which reads the ids on the
host (slow, and the reference is the oracle). An id outside the experts is an
error: the reference finds it at the call, ggml counts it as it does for a
gather and run refuses the answer. F32 only. XLA has no lowering. It has no
gradient. On Vulkan it is checked with vulkan_fp16(false). With fp16 on, Granite MoE 1B-A400M's logits (14 to 28 at the top) gap
Hugging Face's by 0.34, and Qwen3-0.6B's (dense) by 0.028 (transformers/DESIGN.md). It is the router: fp16 flips
the top-k of the experts in 1.0% of the pairs of a token and a layer (67 of 6552), and with the F32 run's ids fed in
the gap is 0.01 to 0.05. expert_matmul is as exact as matmul per product (relative rms 2e-4 in fp16, 5e-7 off).
gated_delta_rule(q, k, v, g, beta, state) (the linear attention of Qwen3.5: per head a [width, width] state that
decays by exp(g) and learns k (beta * (v - state k))^T at every token; the answers are state q / sqrt(width), so
the op scales q and a caller does not) is one node, which ggml runs as ggml_gated_delta_net (CPU, and Vulkan for
widths 16, 32, 64 and 128) with the state in its layout, [heads, value, key]. Every other backend that computes runs
it token by token over the ops of this module (slow for a long sequence; the reference is the oracle). The node
answers the answers and the final state packed in one tensor ([tokens + width, heads * width]), which
gated_delta_rule slices apart. F32 only, the same width for q, k and v, and a token with g = 0 and
beta = 0 leaves the state as it was, so a padded prompt keeps the state of its last real token. g is normally at
most 0 (it is not checked). XLA has no lowering. It has no gradient.
Normalization support: rsqrt, mean_var are not primitives. layer_norm
and rms_norm are derived (§3.2) on every backend that computes, but a trace
records each as one node, layer_norm or rms_norm, so that ggml can run it
as one norm (a trace of a transformer step holds a dozen of them, each 10
nodes composed); the gradient has a rule of its own, checked against a central
difference.
The same holds for the update of Adam: adam_step(p, g, m, v, hyper) is derived
(adam_composed) and a trace of F32 tensors of rank 3 or less records two
kinds of node, AdamStep (whose recorded shape is the three new tensors
stacked, which only the trace and the reference hold) and one AdamPart per
new tensor. ggml runs AdamStep as ggml_opt_step_adamw (hyper is that op's 7
numbers), which updates its arguments in place and asserts that its weight is
a parameter: the lowering works on a copy of the weight and marks it by hand (a
copy is not a leaf, which ggml_set_param needs; nothing else reads the flag,
no backward pass is built). The weight is always a copy, since the loss and the
gradients read it. The moments are copies too, each a tensor of its own (the
Vulkan backend binds each as a buffer and aborts on a misaligned offset, so they
are not slices of one), except in a function compiled by Trace.compile when
both are inputs that no other node reads, not outputs, and the two parts for
them are outputs (adam_donors): then they are updated where they lie, and
their results are the input tensors (Trace.donated), consumed like the cache
of a set_rows, even by a run that fails. The first moment is not checked for
finite values (a non-finite one reaches the new weight through the update,
which is checked); the second is, since an infinite one leaves the weight finite
and frozen. Trace.eval and eval_many never donate. It has no gradient (a
gradient through the Adam update of Optim.step is an error). A StableHLO
module has no node for it: Trace.stablehlo writes the composition of ops that
adam_step is on the other backends.
Convolution/pooling: conv1d, avg_pool1d (stride and padding; no dilation or
groups), and over [N, C, H, W] conv2d (stride, padding and groups, one value
for both axes), max_pool2d and avg_pool2d (a square window; no dilation).
Random: none (dropout is identity at inference).
Movement: to_dtype, to_device, copy, contiguous.
Deliberately missing: softmax, silu, beam search — all derived (§3.2). layer_norm and rms_norm are derived too, and a trace
keeps each as one node. The exact (erf) GELU is gelu_erf, outside this
set; Trace records it as one node and differentiates it.
3.2 Derived ops (pure Agentica, backend-agnostic) #
Built only from §3.1, in tensor/ (generic) or nn/ (model-shaped):
softmax(x, axis) = div(exp(sub(x, max)), sum(...))with max-subtraction.layer_norm(x),rms_norm(x)frommean,pow,sqrtanddivcompositions over §3.1 (novar/rsqrtprimitive is needed).geluis the user-facing name ofgelu_tanh_approx(§3.1); theerfform cannot be expressed over §3.1, sogelu_erfis an op of its own: the reference sums a series forerf(to about 1e-14), libtorch callstorch::gelu.siluderives fromsigmoidandmul.dot(a, b)asreshape+matmul;linear(x, w, b?, out_in),embedding(ids, table)viamatmul/gather. Without_in,wis[out, in]and the product isx wᵀ: libtorch'slinearreadswas it is, and the trace records a transpose that ggml's lowering folds intomul_mat.multi_head_attention(q, k, v, heads, mask?)over[batch, seq, width]: a wrapper overattention. The width splits into heads byreshape+permute, and the answer joins back the same way. A mask that is not[q_len, k_len]is widened to[batch, heads, q_len, k_len].greedy_step(logits, temperature?):divby temperature,softmax,argmax.beam_searchis an Agentica loop overgather+top_k, andtop_kis a derived sort/select loop.dropout(x, p)at inference is identity (kept fornn/API symmetry).
An op that is neither in §3.1 nor expressible above at acceptable cost enters §3.1 only through §5, the consumer checklist.
4. API shape #
Tensor.zeros(shape, dtype, backend) -> Result[Tensor]
Tensor.from_list(data: List[Values], shape, dtype, backend)
-> Result[Tensor]
Tensor.from_file(path, offset, shape, format, backend, dtype)
-> Result[Tensor] # F32/F16/BF16/Q8_0/Q4_K/Q6_K bytes of a file, read in C
Tensor.from_bytes(data: Bytes, shape, format, backend)
-> Result[Tensor] # the same values from bytes in memory (an image's pixels)
Tensor.to_list(t) -> Result[List[Values]] # host readback, tests + decode loop
Tensor.append_file(t, path) -> Result[Void] # the F32 values appended to a file, written in C
Tensor.shape(t) -> Shape # no native call
Tensor.dtype(t) -> Dtype # no native call
Tensor.backend(t) -> Backend # no native callconvert_fileis how weights are written (hub/writes GGUF with it): the same chunked, threaded read asfrom_file(ff_each), each chunk rounded to the target format and written withpwriteat its place in an existing file, so a checkpoint converts with no tensor and no list in memory. Same format on both sides is a byte copy (nothing is rounded, a NaN keeps its payload). It lives in the ggml module (native/ggml.c), the one that compilesfloat_file.hfor conversion; F16 refuses a value beyond 65504 as the half load does.append_fileis how a tensor in memory is written (hub/writes safetensors with it): the backend copies theF32values to host bytes and appends them to a file that exists (ff_append), so no value crosses as a list. Appending needs no offset, and it is the one positional write the reference can do in Agentica (File.open(path, "append")).from_bytesisfrom_filefor bytes that are in memory (the pixels of an image): libtorch and ggml widen them in C, the reference and XLA decode them in Agentica, and the result is alwaysF32.FloatFormat.U8(code 4 offloat_file.h) is its own: one byte per value, widened to0..255: the samples of an image cross into the backend as bytes (a quarter of the size), and the backend widens them to anF32host buffer and uploads that, so the device holdsF32. The file readers andconvert_filerefuse it.from_fileis how weights load: the backend reads the byte range itself (native/float_file.h:preadinto the tensor's own memory, F16 and BF16 widened in chunks) and no value crosses as a list. The tensor isF32, the compute dtype (§2), or withdtype: F16a half weight or withdtype: Q8_0,Q4_KorQ6_Ka quantized weight (ggml only, §7). A range of one of those formats loads asF32on every backend, as ggml dequantizes it;convert_filedoes not take it; a short file, a bad offset or a missing file is anerror, checked in C against the size of the file.Referencereads the bytes in Agentica (File.seekandFile.read_bytes,src/file_range.agc) and decodes them there, which is slow on a large file. ggml takes it through one host copy on Vulkan.- The ggml CPU backend runs one thread per physical core (
native/ggml.c), not per hardware thread: ggml's threads spin while they wait, so a second thread on a core only adds stalls when the machine is busy.TENSOR_THREADS=n(a positive integer, at most ggml's 512) sets it;Lower.cpu_threads()says what a process got. TENSOR_LOAD=agentica(an environment variable) makes the native backends take the Agentica read too: Agentica reads the range and passes theBytesto the nativefrom_bytes, which reads them in place (an_get_bytes, no copy on entry) and widens them into the backend buffer with the same code aspread's. It is for small models, where the read in Agentica costs little: it is slower and peaks higher than the nativepread, which stays the default.- Every fallible op returns
Result; shape/dtype mismatches areerror, never a halt. Introspection is free (fields, no FFI round-trip). - Device is explicit, never a global: dispatch is by value (
t.backend), not by global config, soreference(oracle) andtorchcan check each other in the same process. A backend value carries its device (Backend.Torch(Device.Cpu));Backend.Referencehas none. Batch lives in the shape, not in a global either. The process-wide settings areTensor.vulkan_fp16(on by default), because ggml fixes it per process, andAGENTICA_ML_NEURON_PLUGIN, because XLA loads one PJRT plugin per process and that plugin decides its device (§7). - Backend-module functions take the device as an explicit first argument
(
Torch.matmul(device, a, b)): dispatch unpacks it from the backend value (§7) and the tensor keeps no second copy of it.
5. Requirements the API must satisfy (consumer checklist) #
The clients of tensor/ (asr/, hub/-loaded checkpoints) bound what
§3.1–§4 must support. A pre-trained transformer needs:
- Positional information via
arange + gatherorfull + add(no dedicated primitive). - N blocks of:
layer_norm→ multi-head self-attention (§3.2) →layer_norm→ MLP (linear,gelu,linear). - A 1-D convolution stem, which is why
conv1d/avg_pool1dare primitives (§5 is the gate, not a minimum for every client). - Autoregressive decode: masked self-attention and cross-attention, output
head
linear→softmax→argmax(greedy) with optional temperature; beam search is the Agentica loop of §3.2. The decode loop runs in Agentica; the backend never holds it. - Weights come from a checkpoint (§6). Training (
train/, §10) runs on the same primitives.
A client proves these are met by reproducing, on reference, the output its
reference implementation gives for the same input.
6. Checkpoint requirements (weights in, no code execution) #
- safetensors is the checkpoint format (8-byte LE length, UTF-8 JSON
header with
dtype,shape,data_offsetsplus optional__metadata__, contiguous little-endian C-order buffer, no strides). No code runs at load; that property is the reason for choosing it. - Numeric tensors are converted to
F32on load (lossy forF64; ggml may keep a half or quantized weight, §7), while integer index tensors andBoolmasks keep their dtype because the op set needs them (§2). - The reader and the sharded index are
hub/(hub/DESIGN.md), which reads GGUF files too.
7. Backend dispatch #
A Backend enum value is carried by each Tensor, with dispatch
by case to one backend module per variant, each sharing the §3.1 signature
set:
r: Result[Tensor] = case a.backend
Backend.Reference -> Reference.matmul(a, b) # src/reference.agc
Backend.Torch(device) -> Torch.matmul(device, a, b) # src/torch.agc
Backend.Trace -> ok(Graph.record(Op.Matmul, [a, b], shape, a.dtype)) # §10
Backend.Ggml(_) -> Ggml.compiled_only("matmul") # src/ggml.agc
Backend.Xla(_) -> Xla.compiled_only("matmul") # src/xla.agc
end- The
caseis checked and exhaustive over all five variants, which is the property this shape buys: two compute backends (Reference,Torch), theTracerecorder (it records a node instead of computing, §10.1), and the compiled-onlyGgmlandXla. - The
Torcharm callssrc/torch.agc, which calls thecompute defs ofextern module "torch"(src/native.agc). Both files live in this package, and they have to: the arm needs the module's signatures, and the arm's argument is aTensorwhoseHandle.Nativenames the module's resource type, which is nominal to that block. The alternatives are ruled out by that same property — a table ofFnvalues injected by a backend package still has to name the handle type in its signature, and a third package owning the dispatch still has to carry both backends' handles in one type. An untyped handle (anIntinto a registry) would break §8, where ownership, arena closing andRUNTIME-NATIVE-CLOSEDall key on the resource value. A handle that stays nominal is why the module stays here (§1). - The module is
optional = trueand built fromnative/torch.con first use, with libtorch found by the environment (tools/build-torch.sh). Where it is not built,Backend.Torch(device)answerserror("backend not available")andTensor.available(Backend.Torch(device))isfalse, so a caller can choose a backend without catching that error. - Why this shape: Agentica is static and already checks before running
(no
defnmacros as inNx.Defn); an enum +casekeeps dispatch visible to the checker and letsreferenceandtorchcoexist by value in one process for oracle comparison. The considered alternative — a struct of functions per backend (object-style interface) — cannot carry a native handle across the package boundary while a resource is nominal to its block (§1). - The libtorch backend is one
extern modulewith a thin C layer (C++ astch-rsdoes), declared as[native.torch]. Heavy third parties (ML engines, models) enter only as pinned git submodules underthird_party/, never vendored. Ggmlhas no eager ops. A Vulkan dispatch costs about 2 ms, so ggml is fast only when a whole computation is one compiled graph (the ggml-graph spike). Its arms create tensors (zeros,ones,empty,full,like,arange,scalar_to_tensor,from_list), read them back (to_list), copy them between devices (to_device) and passstop_gradthrough; every other primitive answersGgml.compiled_only(op), anerrorthat names the op and points atTrace. Running each op as a one-node graph would work, but it is a slow path nobody should train on, so it is not offered.- A trace on
Ggmlis one compiled graph (src/lower.agc,native/ggml_graph.c).Trace.evaluatesends every node the outputs reach to the C layer in id order and runs the result as one ggml graph; it never callsTensor.*(§10.3). Inputs and lifted constants are leaves bound on every call, and aFullis a one-element leaf whose value is set on every call. So a compiled graph depends on the ops, shapes, dtypes, integer parameters and on which fills are zero (awherewith a zero branch lowers without it), and that string is the key of a process-wide cache: a retrace of the same function with new data, constants or fill values compiles nothing. The cache holds 32 graphs and evicts the least recently used one nobody runs. A graph that will not run again (eval_manywithkeepfalse) takes no slot and is dropped after its run.Trace.compiledoes the tracing and the lowering (Lower.program: the nodes, the key, where each leaf's tensor comes from, the fills) once, andTrace.runisLower.executeover it: it acquires the graph by the key it already has, sends the nodes only when the cache lost the graph or another run holds it, binds the leaves (an input by its position, a constant to the tensor it was traced with) and runs.Trace.evaluateis the same two steps for one call. - Kept constants. A run of a compiled function leaves its constants bound
to its pinned graph (
ggml_keep), so the next run binds only its inputs (ggml_resume). The graph holds a count on the memory of every tensor it points at, so no run reads freed memory. Only a constant that is read in place is kept: an input, the cache aset_rowswrites and anI32constant (a converted copy) are bound by every run. The kept leaves of a graph are one set, the constants of the program of one pin: for any other programggml_resumeends the set and that program binds every leaf, so two functions that share a graph never read each other's weights. The set ends when its pin ends, when one of its tensors is closed (the memory then goes as before, and the next run is the error that names the leaf), when a kept leaf is bound again and when the graph is destroyed; a graph without a pin keeps nothing. The comment ofstruct portinnative/ggml_graph.chas the rules and the locks. - No copies in or out. For one run only, an
F32leaf points at the caller's tensor and anF32output at a fresh tensor the run writes (or at one that exists,Trace.run'sinto); after the run the graph points at nothing again but its kept constants, so the cache keeps no other caller tensor alive. Only anI32leaf or output is copied, converted through a buffer of the graph's own when the run starts (bindtouches no device); a smallI32tensor made byfrom_listkeeps its values on the host for that, until a run writes it. AnF32output that is a contiguous result of an op is that op's own memory, bound to the caller's tensor, with no copy (anadam_step's weight and moments are views of the copy it updates, which is bound); a leaf, a view at an offset or a reshaped view, a half and a node returned twice are copied. A cached graph owns its fills and its finiteness checks; the intermediates live in one allocator per device that every graph shares, planned again only when another graph ran last: the graph that ran last keeps its allocation, and only the views of its leaves and outputs follow what the run bound. That allocator keeps the largest buffer any graph needed until the process ends. - Layers across the device and the CPU (ml#310). A leaf in host memory
(
Ggml(Cpu)) bound to a graph of a Vulkan device makes the graph mixed. Pinned host memory for a weight does not work:ggml_backend_vk_device_supports_buftrefuses any buffer type that is not a Vulkan one, and the Vulkan sync code casts the buffer of every source to its own. So a mixed graph goes throughggml_backend_schedover the device and the CPU, as llama.cpp does for-ngl.placegives each node that is not a view a side, by the first rule that applies: (1) the CPU when any operand's memory is in host memory (a view looks through to its source), a weight, a cache or any other tensor, whatever else the node reads (a long prompt's activations outweigh a weight, and copying the weight on each run is what a CPU layer avoids); (2) the device when a product or a row lookup reads a matrix that lives there (a weight, however small); (3) the side with most operand bytes (the operands that earlier nodes computed, and the device leaves of 64 KiB or more), a device leaf below 64 KiB that is not such a matrix (a norm weight, a position, a mask) counting for nothing; (4) on a tie, the side of the product of a matrix that the node reads, so the residual stream follows the layer it passes through whatever the order of the operands, else the CPU when an operand was computed there. A node that nothing decides (a table made of constants) takes the side of its consumers, from the end of the graph back, and the device when they are on both sides or it has none.placethen checks that the backend of that side runs the op, and keeps the sides until a leaf changes sides (placedis set only when every node has one, so a failedplaceis tried again on the next call). The key of the graph does not say where the leaves are, so two placements share an entry and each run places itself by the tensors bound.compute_mixedgives every node its backend withggml_backend_sched_set_tensor_backend, lets the scheduler split the graph and copy the activations where the sides meet, and puts back the sources and the order of the nodes (the scheduler rewrites the sources to its copies, and the Vulkan backend reorders the nodes, so both are saved by pointer). The intermediates are the scheduler's own, and the plain allocator's plan is forgotten. One scheduler serves all the mixed graphs of a device, socompute_mixedreserves its memory for the graph that runs when another one ran last (sched_planned); without it the allocator would reuse another graph's offsets and alias live intermediates. Its tables hold the nodes, the leaves and the copies of the split inputs, sized from the graph's own count (sched_need). A mixed graph has two allocators, the scheduler's and the plaingallocr, and a graph uses one or the other for a run. The arrays that a mixed graph needs (leaf_side, the saved nodes and sources, the sides) are made by the firstplacethat finds a leaf in host memory, so a graph with no leaf there pays nothing; a device graph whose leaves are all in host memory is mixed too, and counts as a scheduler run (mixed_runs);graph_runscounts every attempt at a graph execution, plain or mixed. Threads: every graph compute, mixed or not, holds the device lock, and no other code computes on the shared CPU backend (the tensors move without it), so no task can compute on it while the scheduler does.ggml_outputmakes an output on the side of the node that writes it, so a KV cache of a CPU layer is a CPU tensor;output_intotakes a tensor on that side only. Aset_rowsinto a cache on the CPU runs there and writes it in place. A graph whose leaves are all in device memory never calls the scheduler, andggml_runruns it exactly as before. - The checks of a mixed graph (ml#312).
compilemakes the finiteness sum of each output where the output is, and the 1-float copies of the sums intochecks(device memory) after all of them. A copy after each output would be a one-node device split between every two layers on the CPU; the sums stay early so that each output's value is not kept alive to the end of the graph, as on an all-device graph. - Tensor memory. It is a refcounted
tg_storage: the handle holds one count, and a bind takes another. The graph lets go of its counts when the run ends, or at the end of the lease if the run never happens (a failed bind, say); the count of a kept constant goes when its set ends. So closing a handle in the middle of a run frees the memory after the run, never under it. AnI32output inintokeeps the tensor it copies back to by the same count.output_intorefuses a tensor that is another port of the same run (an input, a constant or another output). - Pins.
Trace.compilepins its graph (ggml_pin, aPinresource):free_slotskips an entry withpins > 0, so eviction never takes it. The count is undercache_lockalone, and the free hook of aPintakes that lock and never waits for the device lock. A graph that has no slot (all 32 are in use or pinned) gets a pin that holds nothing and runs as an ordinary graph, so a compile never fails for want of a slot. The pin ends with the task that made it, or atTrace.close. - Locks. Builds, runs and Vulkan buffer operations hold one device lock, so CPU and Vulkan graphs run one at a time (enough for one iGPU; a lock per device can come later). The cache's own lock is held briefly, and a free hook (a lease, a tensor) takes only that one: what it must free under the device lock is queued for the lock's next holder, so no task's free waits for a graph to finish.
- Half weights.
Tensor.from_file(..., dtype: F16)on ggml keeps a weight in 16 bits (GGML_TYPE_F16): the load converts a chunk at a time, with one thread per run of whole chunks (the cores the process may use, at most 8; each thread reads its run withpreadand writes its own part of the tensor; a run stops once an earlier one has failed), and fails on a value beyond 65504, naming the first such element in file order, never clips it; a value too small for F16, from a BF16 file for instance, becomes a subnormal or zero. A trace takes a half weight as an input or a constant, and the lowering accepts anF16node only as that leaf or its transpose, as the second operand ofmatmul(solinear), or as the first ofgather(soembedding). The rows of thatgatherstayF16in the trace, as on every backend, and ggml has widened them toF32already: onlyto_dtypetoF32may take them.ggml_mul_matreads the weight with theF32activations and answersF32. Every other use of a half weight is an error naming the op, before anything compiles, except the KV cache oftransformers:to_dtype(x, F16)makes anF16node (OP_CAST, which may be an output),set_rowswritesF32rows into anF16input in place (ggml rounds them),attentiontakes anF16key and value (flash attention reads them as they are, the products read them inmul_mat), andto_dtype(input, F32)widens anF16input. Asliceof the cache goes into anattentionand nowhere else: when it starts at the first element, flash attention reads it as a view of the cache (the first rows of every head, no copy), which is how a decode step reads only the rows in use. Agatherof the cache that aset_rowswrote reads its rows by index, widened toF32(ggml_get_rows), whichto_dtypealone takes: how a paged cache reads a sequence's rows from its pool. A half weight is for inference:Trace.value_and_gradandgradrefuse one (so doesgradientsfor aConstantone; anF16tensor of another backend keeps its gradient). Other paths are not guarded: a gradient graph that needs anF16fill, the zeros of a weight the output does not reach, ends in the lowering error, andgradientsof anInputhalf weight that only feedslinearormatmulreturns anF32gradient. Uselinear(..., out_in: true)with a checkpoint's[out, in]weight: without it the lowering transposes (copies) the half weight on every run. - Half weights on XLA.
Tensor.from_file(..., dtype: F16)andfrom_list(..., F16)onBackend.Xlakeep the weight in a PJRTF16buffer (native/xla.c: the file is read and widened in C, and a value beyond 65504 is an error naming its element, as on ggml;from_listrefuses the same, an infinity included, and keeps a NaN). The load widens the range toF32first, so for the length of one load a tensor takes 6 bytes a value (4 ofF32and 2 ofF16);storerounds from the double, once. The rules of the ggml paragraph above (anF16node only as the weight of a product or the table of a lookup, or a cache) are ggml's lowering; on XLA anF16tensor is an ordinary one: an op onF16operands computes in half and answersF16, andto_dtypewidens it. StableHLO has no mixed-typedot_general, so the emitter (src/stablehlo.agc) converts eachF16operand of a node whose result isF32(amatmul, agather, anattention) with astablehlo.convertinside the program, and the weight stays 16 bits as an argument. On a NeuronCore the compiler would fold the convert of a product's operand into a product in half precision (about 1e-3 off), so there the operand of a product (matmul,batch_matmul,expert_matmul,attention) and ato_dtypetoF32widen by the bits instead (XlaDevice.half_by_bits?; not under--auto-castother thannone, which makes the products half anyway); agatherkeeps the convert. AnF16result (atransposeor asliceof a weight) is left as it is.Trace.value_and_gradrefuses anF16weight on XLA as on ggml. Whether XLA's CPU plugin fuses the convert into the product or makes anF32copy of the weight on each run is not measured here (the memory numbers belong to the benchmark of ml#390). XLA, ggml and Torch holdBF16weights loaded withfrom_file(..., dtype: BF16). ABF16file read asBF16keeps the stored values, including signed zero, infinities and NaNs. On ggml and Torch the loader copies those words directly. Their F32 products widen BF16 weights during compute, and an embedding reads the selected rows before widening. These conversions can allocate F32 temporaries; for that reasonhub'sweights: BF16keeps the matrices of a modelF16on ggml (ml#444). On XLA, any other source (from_list, anF32orF16file) rounds to nearest even once from the double, and a value beyond 3.3895313892515355e38, an infinity included, is an error naming its element; a NaN stays. On the CUDA plugin, Qwen3-0.6B's decode step fuses the converts of its block matrices into the loops that read them, but converts the tied head (the token table) into anF32buffer of 622 MB on every step before the cuBLAS product, so the peak device memory falls by less than the weights do (benchmarks/README.md). StableHLO spells itbf16, and the emitter widens aBF16operand of anF32result as it widens anF16one: a product converts the weight, a lookup gathers the rows first and converts only them, andattentionreadsBF16keys and values with anF32query. - Quantized weights.
Tensor.from_file(..., format: Q8_0, dtype: Q8_0)on ggml keeps the blocks of a Q8_0 file as they are (GGML_TYPE_Q8_0: 34 bytes for 32 values, about a quarter ofF32; the range is copied, nothing is converted).Q4_KandQ6_Kare the same with ggml's super-blocks of 256 values (144 and 210 bytes: about a seventh and a fifth ofF32), one type per tensor: a file mixes them, andhub/keeps each at the type it stores. It is a rank-2 weight whose rows hold whole blocks, and a trace uses it where it uses a half weight (a leaf, the weight ofmatmulandlinear, the table ofgatherandembedding, no gradient, no output), with one more rule: a product reads it only aslinear(..., out_in: true)does, in place (a quantized transpose would need blocks along the other axis, somatmulby the weight itself and any other op are an error naming the op). ggml reads the weight withF32activations and answersF32; its CPU kernels round the activations of the product to Q8_0 blocks (the same rounding llama.cpp does) and Vulkan's to Q8_1 or F16, so the result 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, not toF32's 1e-7. The K types round the activations to blocks of 256 (Q8_K, whose scale is a binary32), so the CPU bound isamax / 254of a block of 256, and Vulkan's has its rounding to F16 on top.gatherof the table is exact (ggml widens the rows).to_listof a quantized weight dequantizes it. A Q8_0 file of another backend or ofweights: F32is read asF32, which is exact (a binary16 scale times a byte has 19 significant bits). A Q4_K or Q6_K one is dequantized by the same float32 operations as ggml's (native/float_file.h, and in doubles onReference), and the tests against the officialggufpackage's dequantizer on random blocks find the same values on every backend. - What a half weight costs. The weight rounds once, at load. The
activations of the product stay
F32on ggml's CPU backend and on Vulkan at the F32 choice (1e-7 from a double-precision sum). With fp16, the Vulkan default, Vulkan computes the product in fp16, as it does for anF32weight, so a half-weight result is good to about 2^-11 relative per product on any backend, and an activation beyond 65504 overflows.F32is the exact path and the default. - The lowering computes in
F32.Bool(0/1) and integers up to 32 bits are exact there below 2^24; a node ofF64orI64, anF16node that is not a half weight (below), an integerdiv, ato_dtypethat is not exact inF32, an integer fill orarangebeyond 2^24, anarangethat counts down, atransposeabove rank 2, a tensor with no elements and an op without a lowering are errors naming the node, given before anything compiles; anI32value beyond 2^24 is an error when it is copied in or out. Lowered:add,sub,mul,div,neg,exp,log,relu,sqrt,sigmoid,tanh,matmul,transpose,reshape,squeeze,unsqueeze,broadcast_to,sum,meanandmaxover a leading or trailing block of axes,stop_grad,copy,contiguous,arange,slice,concatandstackon any axis,conv1d(anF32im2col and one matmul; ggml's ownconv_1dmakes the im2colF16),conv2d(ggml's directF32kernel, on the CPU and on Vulkan;groupsabove 1 run one convolution for each group of channels),max_pool2dandavg_pool2d(ggml_pool_2d),gelu_tanh_approx(x * sigmoid(2 * sqrt(2 / pi) * (x + 0.044715 * x^3))inF32frommul,add,scale, andsigmoid, avoidingggml_gelu'sF16lookup table rounding on the CPU),gelu_erf,gather(ggml'sget_rowsover the source as rows, its indices clamped to them; an index outside the rows is an error after the run, counted in the graph; a source of more than 2^24 rows is an error),scatter_add(ggml'sget_rows_back, with the same index check and the same 2^24 limit; its cost isO(k width)on the CPU, but the Vulkan shader runs one thread per cell of the answer and loops over allkindices, so there it isO(rows k width). On Vulkan inF32mode (the fp16 mode rounds the updates in the matmul for a chunk of more than 8 columns, the most that ggml-Vulkan's always-float mat-vec kernel takes: 1e5 becomes infinity), withkbelow the rows, up to 32768 and with room in the graph, the lowering instead gives each update row the sum of the rows that name its index, by one matmul with thek x kmask of equal indices (O(k^2 width), exact: it adds only the rows of one index), and writes those sums into zero rows withset_rows(the rows of one index write the same sum). Anything else keepsget_rows_back.TENSOR_SCATTER_ADD=get_rows_backkeeps ggml's kernel, for the benchmark (tools/bench-scatter.agc). The masked matmul is a stopgap, not the floor: it beatsget_rows_backfrom about 10000 rows up, and runningscatter_addon the CPU would be faster still (revisit with the sched executor of #85). The long-term fix is an upstream Vulkan kernel forGGML_OP_GET_ROWS_BACKwith one thread per (index, column), which would make this lowering unneeded), andpermute(aggml_permuteand a copy),batch_matmul(mul_matover the batch axes) andrope(ggml_rope_ext, with the sequence axis swapped to ggml's third; its positions areI32, as every integer here, and a rank above 4 is an error),attention(oneflash_attn_extthat reads q, k and v as the views they are, with the scale and anF16mask, inF32accumulation: the pinned ggml takes an unpadded mask andF32k and v on CPU and Vulkan. The lowering sends it a node when the mask is absent or is built fromfulls of 0 and of a value from F32's lowest to -65504 (the causal and the padded masks), whichF16holds exactly, the large ones clamped to -65504; a mask of any other values, a width that Vulkan has no kernel for (not a multiple of 8), a backend without the op and, on Vulkan with the fp16 products (the default), a query of more than one row (the fp16 products beat the F32 kernel over many queries) use twomul_matand onesoft_max_extas before:mul_matrepeats the kv heads over a group of query heads, andsoft_max_exttakes the scale and the mask. A query with every key hidden by those fills gives the softmax of its scores on the flash path, not their mean). A scale and a base cross as the bits of a double and must fit anF32.eq,ltandwhereemulated inF32arithmetic (eqas1 - step(|a - b|), exact for integers below 2^24 and true when an operand is NaN;whereasc·x + (1 - c)·y, exact only when both branches are finite): enough for an MLP and softmax cross-entropy with their gradients, for a training step and its batch, and for Whisper's forward (asr/). An output that holds an infinity or a NaN is an error, and so is a finite one whose sum overflowsF32(the check is the sum of its rows; the CPU adds in double and Vulkan inF32, so the edge differs:exp(80)over 10 000 values fires on both). A graph has at most 512 outputs. - Vulkan computes
mul_matin fp16 by default (the owner's decision, ml#148): ggml readsGGML_VK_DISABLE_F16once per process, when it first enumerates its devices, and the C layer sets it (only when exactF32was asked for) before its first registry call (any ggml call, a CPU one, orTensor.availableof a Vulkan device, included; aGGML_VK_DISABLE_F16the user exported and novulkan_fp16call keep F32).Tensor.vulkan_fp16(false)before that opts out to exactF32mul_mat, process-wide (it is ggml's choice per process, not per tensor, the one exception to §4's "never a global"); a different choice after it is an error, and on a build without Vulkan or without the module it changes nothing. fp16 is faster for the products (about 1.8× for a large one in ggml's own perf test:benchmarks/README.md, fp16), 1.1–1.5× from batch 256 to 4096 in the spike, and changes gradients by up to about 10 % at MLP sizes (the spike's run B). It does not keep the ids of Hugging Face's greedygenerate, so every check against Hugging Face or whisper.cpp choosesF32first: the tools throughLoad.vulkan_fp16_from_env()(VULKAN_FP16=1runs a check in fp16), the tests of the packages through theirsupport.agc. - The ggml module is
[native.ggml],optional = true, built fromnative/ggml.candnative/ggml_graph.cagainst the pinnedthird_party/ggml, whichtools/build-engine.shbuilds CPU-only (CI) or with Vulkan (local), into a cache outside the checkout. The build table names one library, a linker script that script writes, so one table links either entry; the C layer finds Vulkan devices through ggml's backend registry at run time.Tensor.available(Backend.Ggml(device))istruewhen the module is built and, forVulkan(i), ggml sees devicei; it opens no device. ggml storesF32andI32;Bool,I8,I16andU8are stored asF32(exact for them),F64,I64and a rank above 4 are refused, andF16and the quantized dtypes are stored only as a half or quantized weight (§7). Xlais compiled-only too, on the CPU or a NeuronCore. It runs a trace through XLA, loaded at run time:native/xla.copens the PJRT plugin withdlopenand callsGetPjrtApi, so nothing of XLA is linked or built here. The plugin is our own build of openxla/xla at the commit intensor/xla-commit(Linux x86_64 and aarch64; CI tests x86_64 only): theXLA pluginworkflow builds it, and the tagxla-<first 12 characters of the commit>publishes it as a GitHub Release of this repository withpjrt_c_api.h, the licenses of what it links andSHA256SUMS. We redistribute it (the plugin is Apache-2.0, and the licenses of what it links go with it).tools/install_xla.agcdownloads the plugin of the machine from that release, checks it against the sha256 pinned insrc/xla.agc, and keeps it in the ml cache. Both that table andxla-commitchange together (test/xla_pin_test.agcchecks the tag).native/pjrt_c_api.his vendored (openxla/xla@dd6381370d6f, PJRT 0.81, Apache-2.0, its notice inside), so the module builds with no download and a missing plugin is an error at run time that names the install step; this is the one header that breaks the rule above that third parties enter only as submodules. A tensor is a PJRT buffer; eagerly the backend creates tensors, reads them back and passesstop_gradthrough, and every other primitive answersXla.compiled_only(op).Trace.compileemits the function as StableHLO (§12) and compiles it once;Trace.runruns it, with the constants after the inputs. The process loads one plugin: our CPU plugin servesDevice.Cpu, and AWS's Neuron plugin, named byAGENTICA_ML_NEURON_PLUGIN(src/xla_device.agc), servesDevice.Neuron(i)for each coreNEURON_RT_VISIBLE_CORESshows (Tensor.xla_devices). A buffer lives on one device, a program is compiled with no device of its own (a portable program,compile_portable_executable) and runs on the device of its call (execute_device), where its arguments must be; a plugin that refuses a portable program compiles one per device (a device assignment in its options) from then on, andto_devicecopies between them. A tracedto_devicelowers only to the program's own device. A program has the flags of Neuron's compiler of its phase (Trace.Phase:Prompt,Decode,Any;src/xla_device.agc): Neuron's plugin readsNEURON_CC_FLAGSforneuronx-ccand keys its own compile cache by them (whether at each compile is still to be checked on inf2), so a compile with other flags than the opened ones sets the variable under a lock and puts it back after; the base of every phase is the variable as it was when the plugin opened. A CPU plugin reads no such flags and the environment is left alone. The cache of the process keys a program by its text and its flags, and by its device only where programs are not portable. The scratchpad page (NEURON_SCRATCHPAD_PAGE_SIZE) is read by Neuron's runtime when the plugin opens;Xla.scratchpadsets it before then, and every program's flags carry it.AGENTICA_ML_XLA_CPU_DEVICES=n, a test knob, asks our CPU plugin fornhost devices, so a test loads it as the override and runsNeuron(0)andNeuron(1)on one machine. The site pagetensor/neuronis the guide. A compiled program goes in a cache of the process keyed by its text, flags and device (32 programs, the least recently used one that nobody holds leaves first), soevaluate, which compiles for each call, compiles a retraced function once, andTrace.closelets go of the program as it ends a ggml pin: a run afterwards finds it in the cache or compiles it again. The moments that anadam_stepupdates in place (the rule of ggml'sadam_donors), and the cache of aset_rowsthat is an input no other node reads, not an output, with theset_rowslisted once among the outputs (Lower.row_donors), are aliased to their outputs (tf.aliasing_output), so XLA writes them over the old ones: the run consumes those inputs and answers new tensors (Trace.donatedis false), and every other input is kept. A cache that fails the rule is copied, asTrace.evaldoes, and so is an aliased input whose tensor is also passed at another position of the run. As on ggml, the aliased inputs are consumed even by a run that fails, such as a position outside the cache (ml#491). A run holds its inputs only while it runs.Train.fitruns on XLA as on ggml, the batch gathered in the step. XLA storesF32,F64,I32,I64,I16,I8,U8andBool;F16and the quantized dtypes are refused (no half or quantized weights).
8. Tensor lifetime #
agentica#1091 (native arenas) semantics, which this section builds on:
Native.arena do ... end takes no block parameter, runs the block, returns
its value, and at block end closes newest-first every native resource and
owned buffer the task opened inside — except what the return value reaches
(struct fields, enum payloads, Result/List/Map items; lambda captures do
not keep). A kept view keeps its buffer; kept resources keep their up
links. Inner arenas hand kept resources to the enclosing arena; try failure
ends the block normally; panic/cancel ends the task, which already closes
everything newest-first.
In-flight compute def arguments are held until the call returns (same path
as Native.close); use-after-close is RUNTIME-NATIVE-CLOSED, never UB;
Task.spawn_owning transfers ownership, anything else crossing tasks is
documented-not-refused.
Usage for tensors:
- Intermediates die at a known point instead of waiting for the GC (a 1 GB
native tensor looks like any other
resourceto the GC; a step makes thousands of them). Each op ofsrc/torch.agcopens an arena of its own and returns the tensor it made as the block's value, so the arena keeps that tensor. The libtorch ops areAN_FRESH(Agentica 0.37.0,native/torch.c): a handle owns itstorch::Tensor, and a view holds its base by libtorch's refcount, never through another handle's state, so the arena keeps the result alone and the intermediates it came from still close. A caller that runs a step nests those calls in one arena of its own, and can return a tensor out of it (test/torch_lifetime_test.agc).Handle.Ggmlis not fresh: a traced node refers to its arguments. Trace.evaluateon a backend that computes opens an arena per node and closes a value after its last reader (the inputs, the outputs, the constants and the answers ofstop_gradandto_devicestay), so a run holds the live edge of its graph, not every node: MiniLM on libtorch, oneTrace.evalof 16 sentences of 64 tokens leaves nothing behind, where it kept 660 MB per call. The Adam step of a computing backend (adam_eager) is one native pass on libtorch for anF32weight (Torch.adam_step: the three outputs stacked in one allocation, rounded as the composition does, within 1e-6 of it; the weight, first moment and second moment it returns are views that share that one 3x allocation, which is freed with the last of them). Any other dtype, and every other backend, runs the composition one statement at a time in an arena of its own, so the word table of MiniLM does not hold nine coefficients at once.Torch.memoryreads the bytes of the live libtorch storages fortest/torch_memory_test.agc.- Only the returned
Tensor(s) leave the arena; views keep their buffers through the rule above, so there is no explicitkeepcall. Handle.Ggmlfollows the same rules: each creation call ofsrc/ggml.agcopens its own arena, and the resource owns one ggml context and one backend buffer, freed together by its free hook. The device itself is opened once per process and never closed: a buffer only needs its device's buffer type, which lives as long as the process. Every Vulkan buffer operation (allocate, write, read, free) runs under one lock in the C layer, so tasks on one device never overlap a transfer; a free hook never waits for it and leaves the free to the next holder (§7).fit's training step is one program, compiled once per batch shape (Trace.compile,train/DESIGN.md): it reads the parameters and the optimizer state in place and writes the new ones into freshHandle.Ggmltensors, except Adam's moments, which are updated where they lie (§3.1).compute defkernels only push data or return a resource; the loop lives in Agentica and the native side never calls back (existing FFI invariant).
9. Shape/dtype validation #
- Validate eagerly at call time in the Agentica wrapper, before dispatch:
ranks, dimension sizes, dtype legality, and broadcast compatibility return
errorwithout touching native code. Backends may re-check cheaply but must not be the only check (the reference oracle defines correctness, including the error cases). - Trace time reuses the same predicates (§10.1).
- Conformance covers values plus shapes, dtypes, and error cases on every
backend, bit-for-bit against
referencewhere the dtype is exact.
10. Training: tracing and grad #
- Functions trace to a graph of §3.1 primitives;
grad/value_and_gradare computed in Agentica over that graph (ml#1 key decision). Backends stay forward-only: no per-backend autograd. - Nothing in §3.1–§4 assumes training, but a differentiable primitive
declares its backward rule in Agentica (the end of §10.3 lists the ones still
without): the trace records the ops, and the
rule lives in
tensor/, not in a backend.nn/(forward-only layers overtensor/) andtrain/(losses, SGD/Adam, a training loop) build on them. - Op admission rule: an op that a backward rule needs enters §3.1; adding one
is a breaking change to the backend interface.
stop_grad/detach is not one: it is a wrapper-level op with no backend primitive (§10.3). - The backward rule of a differentiable primitive — an
F32-output arithmetic, reduction, linalg, shape, movement, conv or pooling op — is expressible over §3.1 itself; an op whose rule needs more admits that op (§3.1). Creation, comparison and index ops cut the trace instead:zeros,ones,empty,full,arangeandscalar_to_tensorbuild a value from shape/dtype arguments;like(t)reads onlyt's metadata (shape, dtype, backend), ignoring its value, so it needs no rule either;eq,ltandargmaxgiveBool/integer values.stop_gradcuts the trace too.
10.1 How a function is traced (decided) #
Agentica has no macros (§7), so nothing rewrites a function the way defn
does. A function is traced by calling it with tracer values through the same
API, as Nx does with its Expr backend: Backend.Trace is an arm of
every dispatch case, and a tensor on it holds Handle.Traced(Node) instead
of storage. Trace.value_and_grad(params, &loss) calls loss with Trace
tensors; each Tensor.* call runs the wrapper's checks (§9) as it always does
and then records a node, so trace time and eager time share every shape and
dtype check by construction.
Why this and not the alternatives:
- One API.
nn/layers and the derived ops of §3.2 (softmax,layer_norm, attention) are written once, overTensor.*, and run eagerly for inference (no node per op, no trace) or traced for training. - A separate traced API (
Trace.addover a type of its own) was the first version and is rejected: every derived op and everynn/layer would be written twice, and its shape checks would be a second copy of §9. - A layer generic over an ops record (
Ops[T]ofFnfields, run onTensoror on a node type) also writes a layer once, but every call becomeso.matmul.call(x, w)and the derived ops would be rewritten in that style; the tracer arm gets the same for free.
The price:
- An op on a traced tensor that has no backward rule cannot be refused by the
checker. Every op of §3.1 records a node, so any traced function runs
forward; a gradient that has to pass through an op with no rule makes
gradientsanswererror("<op> has no backward rule yet"), at run time. - An eager tensor and a traced one never mix (
same_backend): a tensor from outside the function enters withTrace.constant(t), explicitly. BackendandHandlecarry a variant that no compute backend handles; a backend that reads a handle answerserroronTraced.- A traced tensor has no values, so host readback and control flow that
depends on data cannot be traced:
to_list,top_k,beam_search, a decode loop,if x > 0. They stay outside the traced function. - A new op costs five places: its
Tracearm, itsOpvariant and itsop_name,applyandvjparms. The compiler enforces all of them (exhaustivecase). - The shape a
Tracearm records is a second copy of the backend's shape inference;evaluatechecks every computed shape and dtype against the recorded one and answers an error naming the op and node. - A
Constantholds its tensor, so a graph with a native constant is tied to the task that owns that handle (§8). fis traced again on every call (each training step).
10.2 The graph (decided) #
- A node is
Node { id, op, args }behind a traced tensor, whose ownshapeanddtypeare the node's. Its arguments are traced tensors. The graph of a function is what its output reaches; there is no graph object and no mutable tape. idis aRef(Ref.new()insrc/graph.agc), the rolemake_refplays in Nx: two uses of a value are one node, and since an argument is always made before its user andRefs sort by creation, sorting byidis a topological order.- Leaves are
Input(an argument of the traced function),Constant(t)(a lifted tensor: data, labels) andFull(value)(zeros,ones,full,like,scalar_to_tensoronTrace). - Every argument of
value_and_grad/gradis differentiated; what is not a parameter enters as aConstant.
10.3 Gradients (decided) #
gradients(out, wrt)is a graph transformation: it returns traced tensors built withTensor.*, so each backward rule is a composition of §3.1 primitives (reluusesltandwhere;broadcast_tousessumwithkeep_dimsandreshape). The gradient graph can be evaluated, inspected or compiled like any other, andwrtmay name any node, not only an input.- Cotangents flow only into arguments on a path to
wrt; awrtnode the output does not reach gets zeros. A node that is not float (eq,lt,argmax,arange, an integerto_dtype) carries no gradient, so comparisons and index ops cut it, and so does the condition ofwhere.relu's derivative at0is0. evaluateruns a graph on the inputs' backend, computing each node once; a lifted constant must live on that backend. A backend that computes op by op (Reference,Torch) runs it through the publicTensor.*calls. A backend that compiles (Ggml,Xla) runs the whole graph as one program of its own and does not go throughTensor.*(§7), so it supports the ops its lowering knows and answers an error naming any other.value_and_gradevaluates the output and its gradients in one pass, so the backward reads the forward values it shares;eval_manyevaluates every tensor a traced function answers in one pass (a training step: the loss, the new parameters and the optimizer state). Backends stay forward-only.- The rules are the
vjpoftrace.agc, one arm per op.copy,contiguousandto_devicetoCpuare the identity (every backend that computes is onCpu; a move across devices answers an error). Each rule is tested against a central difference of the traced function on the reference backend. On libtorch, the forward ops of a 2-layer MLP's gradient graph are run and compared with the reference. - A parity suite runs every op of §3.1 traced (
Trace.eval) and eagerly over good and bad inputs: both fail, or both give the same shape, dtype and values, and the shape and dtype a trace records are the eager ones. stop_grad(t)is a wrapper-level op with no backend primitive: the wrapper answerstitself on every backend that computes and, onTrace, records a node whose rule is zero.softmaxsubtracts its maximum through it: the shift cancels out of the value, so it needs no gradient.- Rules with a choice in them:
sqrtis infinite at0;gelu_erfisPhi(x) + x phi(x), withPhi(x)read back asgelu_erf(x) / x(0.5at0);gatherisscatter_addofctat the indices, so a repeated index sums its rows;scatter_addgives its updates thegatherofct(the indices have no gradient);maxsends the cotangent to the positions that hold the maximum and splits it evenly between ties, asjax.numpy.maxandtorch.amaxdo. With the rules,softmax,layer_norm,rms_norm,silu,gelu,embeddingandmulti_head_attentionare differentiable. permute(the inverse permutation),rope(the same rotation turned the other way,inverse; the positions have no gradient) andattention. The backward ofattentionrecomputes the probabilities fromq,kand the mask, once for each of the three arguments it feeds (the graph does not share the scores between them), folds the query heads of a group into the rows of the scores ([B, H, Sq, D]as[B, Hkv, H/Hkv * Sq, D]) so every product is a rank-4batch_matmuland the kv heads are never repeated, and gives the maskdscoressummed over the batch and head axes it broadcast. Each is checked against a central difference, with grouped heads, a mask per head and the causal flag, and on ggml against the reference node by node (test/ggml_attention_test.agc).conv2d,max_pool2dandavg_pool2d(src/windows.agc): every step is an op of §3.1 on at most four axes, so every backend runs them. The gradient of the input of a convolution is a convolution ofctspread with zeros by the stride and padded bykernel - 1 - padding, with the weight flipped and its channel axes swapped; the gradient of the weight is a convolution of the input, its batch and channel axes swapped, with the spreadctas the weight (a padding of the kernel or more is an error).avg_pool2dis that convolution on every plane with a kernel of1 / kernel^2.max_pool2dsendsctto the first position of a window that holds the maximum, in row-major order as libtorch does (not the even split ofmax), by taking each of thekernel * kerneloffsets of the windows in turn. The weight gradient puts the batch in the channel axis of a convolution, which ggml's CPU kernel (a 16 MiB buffer, so(KW * KH * C_in + C_out) * 4bytes must fit, elseerror) cannot take for a big batch, so the rule cuts the batch in chunks and adds their answers. Each is checked against a Python peer on every backend (test/conv2d_test.agc).- Still open: rules for
pow,clamp,batch_matmul,to_dtypebetween float dtypes (a precision cast),conv1dandavg_pool1d; the rule ofwhere's condition for gradients of gradients; and how an evaluation's intermediate tensors map onto the arenas of §8 (today they live untilevaluatereturns).
11. Conformance #
referenceis the oracle. One shared suite runs on every backend: values, shapes, dtypes, and error paths.- Every backend is checked against
referencethrough that one suite, so a backend is correct by construction or not at all. - The reference stores every value as a
Float,F32included (ml#265, measured on Agentica 0.39). AList[Float]keeps 8 raw bytes per item, but aList[Float32]is a list of tagged 16-byte values (a binary32 held in a double), and there is no 4-byte list. Peak RSS of a program that builds 10 million items: 125 MB forFloat, 445 MB forFloat32(49 MB is the runtime). Decoding the 25 million floats of a 100 MBfrom_filerange: 7.5 s and 419 MB withFloat, 9.0 s and 1185 MB withFloat32(the checkpoint values are binary32 already, so the widening loses nothing). A 256 x 256matmulloop: 0.50 s withFloat, 0.59 s withFloat32(binary32acc), 0.75 s withFloat32items widened for aFloatacc.Bytesis the one 4-byte store, and reading an item withBinary.read_f32_lemakes that loop 8.7 s. SoFloat32storage would use about 3.5 times the memory and run 20 to 40% slower. Rounding every op to binary32 would not make the oracle closer to ggml either (ggml sums in blocks, not in the order of the loop) and would cost it digits: a dot product of 4096 items rounded at each step is off the double one by up to 7e-5 (1.6e-5 at 1024), against tolerances of 1e-4 to 1e-3. So the reference keeps doubles. Revisit it when Agentica has a packedFloat32list.
12. StableHLO #
Trace.stablehlo(specs, f)tracesfonce, asTrace.compiledoes, and writes the traced outputs as one StableHLO module (src/stablehlo.agc), a second lowering of the graph beside the ggml one (§7). The text knows no backend and no runtime, so XLA through PJRT and IREE can read it.Xla(§7) compiles it.- The module is one
func.func public @main. Its arguments are the inputs, in the order ofspecs, then the tensors lifted withTrace.constant, in the order of their nodes;Module.constantsholds those tensors, so a run gives them as arguments like any other. It returns the outputsfanswered. A constant is an argument, not a literal, so a batch is not in the text. - Shapes are static. The
Tensor.*wrappers take exact shapes, so an elementwise op needs no implicit broadcast:broadcast_toisstablehlo.broadcast_in_dim, whose operand axes align with the trailing axes of the result, and an op that has a scalar (gelu, the mean's count) holds it as a splat constant of the shape. - The ops covered are the ones of an MLP forward and of the
fitstep:add,sub,mul,div,neg,exp,log,sqrt,tanh,relu,gelu_tanh_approx,matmul(dot_general, contracting[1]with[0]),transpose,reshape,broadcast_to,sum,mean,max(areducefrom0or-inf, then areshapeforkeep_dims),eq,lt,where(select),arange(iota),slice,full,stop_grad,gather(astablehlo.gatherof whole rows; XLA would clamp an index outside the rows, so forXlathe program also answers a flag that one is, and the run is then the error the reference gives; a compare that cannot be true for the dtype (below 0 forU8, at or above the rows when they are past its maximum) is left out) andadam_step(the ops of its composed form over the 7 numbers, its three results stacked; a part is aslice), and the shape and dtype ops of a transformer step:sigmoid(logistic),pow(power),clamp,to_dtype(convert; a boolean is a compare with 0, and a float to an integer truncates, as the reference does),permute(transpose),concat(concatenate),stack(areshapeof each, thenconcatenate),squeezeandunsqueeze(reshape),batch_matmul(dot_generalwith the leading axes as batching dimensions) andargmax(the reduced axes moved last and flattened, the maximum, then the smallest index of the positions that hold it: a tie keeps the lowest, as the reference does; a block with a NaN has no maximum that equals any value, so its answer isblock, out of range, and is not defined),layer_normandrms_norm(a mean of the squares over the last axis, asqrtand a division, aslayer_norm_composedandrms_norm_composedwrite them; the sums run in the dtype ofx, and onlyF32is used so far),gelu_erf(CHLO'serf, which XLA lowers) andrope(the cosines and sines of the angles are written in the program from constant frequencies and the positions; the pairs(i, i + dims/2)or(2i, 2i + 1)are rotated;inversenegates the sines),attention(the keys and values are repeated for their group of heads, adot_generalwith the batch and the heads as batching dimensions gives the scores, then the scale, the mask broadcast to the scores, the softmax as the maximum,expand a sum, and a seconddot_general; a key in another dtype than the query is converted; a query whose keys are all-infgives a NaN row there, where the reference refuses it with an error),scatter_add(astablehlo.scatterthat adds into zeros; a duplicate index sums, and an index outside the rows is clamped into them first, because it faults a NeuronCore:checkedcovers it as it does agather, and in the text of an unchecked program,Trace.stablehlo, such an index adds into the nearest row where XLA would drop it;set_rowsis clamped the same way) andtop_ids(chlo.top_k, which XLA lowers to its TopK, since Neuron's compiler builds no generic sort: the firstkids, the lowest index of equal values first, as the reference does; a float-0.0is made0.0first, so it ties with0.0, and a NaN ranks above every number). The text depends on the device (XlaDevice.half_by_bits?): on a NeuronCore a half weight that a product reads is widened by its bits (§7). Any other op is an error naming it. A program checks no values: ato_dtypeout of the range of its integer type wraps, apowwith a base at or below 0 gives what XLA gives (a NaN): the reference refuses these with an error, and only the index of agatheror ascatter_addis checked (checked). The backward rules ofpow,clamp,batch_matmulandto_dtypedo not exist yet (trace.agc), so a gradient does not pass through them on any backend; the backward ofattentionis written withbatch_matmul, which it uses forward only. The quantized dtypes have no MLIR element type;Boolisi1,U8isui8. Train.stablehlo(loss, params, batch, optimizer)is the step offit, asfittraces it: the arguments are the parameters, the optimizer's moments, then the inputs of the step (Optim.step_inputs: SGD's learning rate as a rank-0 tensor, Adam's 7 numbers as a rank-1 tensor, AdamW's two rows of them), whose Adam update is the composition ofTensor.adam_step(no node), then the batch. One program is every step: the host computes the numbers from the step count and the schedule, asfitpasses them on ggml, and feeds the outputs (the loss, the new parameters and moments) back in.- Goldens.
train/test/fixtures/stablehlo/NAME.mliris the emitted text of each case (train/tools/stablehlo_cases.agc): CI compares it, which finds a change and says nothing of correctness.NAME.golden.jsonholds the arguments and the outputs IREE (CPU) gave for that text, three chained runs for the fit step; CI checks that the reference backend, andfititself, reach the same values withinF32drift. IREE is local tooling only:make iree-venvinstalls the pinned official wheels in.venv-iree/, andmake iree-goldensrewrites the snapshots and the goldens.iree-compilealso rejects a text that is not valid StableHLO, which is a failure of the emitter.