# tensor

Functional tensors over pluggable backends: the public API (`tensor.agc`), a
pure-Agentica **reference** backend that is the oracle, and the **libtorch
(CPU, eager)** backend behind `extern module "torch"` and a thin C++ layer over
libtorch's C++ API (as `tch-rs` is, in spirit), and the **ggml** backend (CPU
and Vulkan) behind `extern module "ggml"`, which runs a traced function as one
compiled graph. The contract is [`DESIGN.md`](https://www.agentica-lang.com/ml/tensor/design/index.md).

libtorch is a **system dependency**, never vendored and never downloaded by
this repository: `tools/build-torch.sh` finds it through `TORCH_DIR`, or in
`/opt/libtorch`, `/usr/local/libtorch`, `/usr/lib/libtorch`, `$HOME/opt/libtorch`
or `$HOME/libtorch`, or last as a system package (Debian's `libtorch-dev`, with
its headers in `/usr/include/torch` and its libraries in the multiarch
folder), and the module is
`optional = true` in `agentica.toml`, so a checkout without libtorch still
checks, formats and tests. `Tensor.available(Tensor.Backend.Torch(Tensor.Device.Cpu))`
answers whether this machine has it, and the dispatch arm answers
`error("backend not available")` when it does not.

- `src/tensor.agc` — the public API. Every op returns `Result` (`error`, never a
  halt), validates shape/dtype/backend/device before it dispatches
  (`DESIGN.md` §9), and dispatches by value over the `Backend` arms: four
  compute backends (`Reference`, `Torch`, `Ggml`, `Xla`), the `Trace` recorder
  that records a node instead of computing (§7, §10).
- `src/trace.agc` — tracing and gradients: `value_and_grad`, `grad`, `eval` and
  `eval_many` (several outputs, one evaluation) call a function written against
  `tensor.agc` with tensors of the `Trace` backend, derive the gradient graph
  with the same ops and run it on a real backend (`DESIGN.md` §10).
  `compile` and `run` trace and lower a function once, for inputs of fixed
  shapes, and run it many times.
  `src/graph.agc` is the recording side the `Trace` arms call.
- `src/stablehlo.agc` — `Trace.stablehlo`: the traced graph as StableHLO text for XLA and IREE; the goldens are
  in `train/test/fixtures/stablehlo/` (`DESIGN.md` §12).
- `src/reference.agc` — the reference backend, pure Agentica over
  `List[Float]`; the oracle every other backend is checked against.
- `src/torch.agc` — the libtorch backend: the §3.1 primitives libtorch
  expresses, per-op checks, and one `Native.arena` per call (§8).
- `src/native.agc` — the FFI boundary and nothing else: `resource
  TensorHandle` and the `compute def` calls. The generated header
  `native/torch_native.h` comes from this file (native-gen).
- `src/torch_dtypes.agc`, `src/torch_shapes.agc` — the dtype codes that cross
  to C, the conversions between a storage double and a `Values`, and the shape
  arithmetic a reduction needs.
- `native/torch.c` — the thin C++ layer: one libtorch call per function, the
  checks that keep libtorch's implicit behaviour (broadcasting, wrapping) from
  leaking, and the `error` text. libtorch has no C API, so this is C++ in a
  `.c` file: the build table names no compiler, so `CC` selects the driver.
- `tools/build-torch.sh` — finds libtorch and prints the exports the build
  table cannot name (`TORCH_DIR`, `CC` with the rpath, `CPLUS_INCLUDE_PATH`,
  `LIBRARY_PATH`, `LD_LIBRARY_PATH`). Without a libtorch it exits 1 and says
  what it looked for.
- `src/ggml.agc`, `src/ggml_native.agc`, `native/ggml.c` — the ggml backend
  (CPU and Vulkan): creation, upload and readback over the pinned
  `third_party/ggml`; see "The ggml backend" below.
- `src/lower.agc`, `native/ggml_graph.c` — `Trace.evaluate` on `Ggml`: the
  traced graph lowered to one ggml graph, with the structural cache.
- `tools/build-engine.sh` — builds ggml (CPU, or CPU + Vulkan) into a cache
  shared by every worktree and prints its exports; CI runs it.
- `src/xla.agc`, `src/xla_device.agc`, `src/xla_native.agc`, `native/xla.c` — the XLA backend (CPU, or a NeuronCore):
  XLA's PJRT plugin loaded with `dlopen`, a `Trace.compile` emitted as
  StableHLO and compiled once; see "The XLA backend" below.
  `native/pjrt_c_api.h` is the PJRT header, vendored with its notice.
- `tools/install_xla.agc` — downloads the pinned XLA plugin of our release into
  the ml cache.
- `xla-commit` — the openxla/xla commit the `XLA plugin` workflow builds.
  Pushing the tag `xla-<its first 12 characters>` builds the plugin for Linux
  x86_64 and aarch64 (and macOS arm64, experimental) and publishes a GitHub
  Release with the plugins, `pjrt_c_api.h`, the licenses and `SHA256SUMS`.
- `tools/xla/` — what that workflow runs after it builds the XLA PJRT CPU
  plugin: `smoke.c` loads the plugin and creates a client,
  `collect-licenses.sh` gathers the licenses of what it links. The x86_64
  plugin needs a CPU with AVX.
- `tools/bench.agc` — the numbers in "What the dependency costs", reproducible.
- `tools/bench-ggml.agc` — the data and the init of the training benchmark (`benchmarks/README.md`).
- `test/` — the unit tests of the reference backend, the libtorch conformance
  suite (`test/torch_*_test.agc`) that runs the same public call on both
  backends and compares, and the property tests (`test/prop_*_test.agc`, with
  `prop`, a test-group dependency). Without libtorch the comparison asserts
  that absence and the rest runs on the reference.

The native module lives in this package rather than in a `torch/` of its own
because a `resource` is nominal to the `extern module` block that declares it:
`Tensor.handle` has to name `TensorHandle`, and the `Backend.Torch` arm has to
call the module, so both have to be declared here (`DESIGN.md` §1, §2, §7).

## What is implemented, and what is not

`DESIGN.md` §3.1 names 52 primitives. Both backends compute them: the
**reference computes all 52**, and the **libtorch backend implements 51** and
answers `error("<op> is not implemented on the torch backend yet (see tensor/README.md)")` for the
other one, so the gap is an error naming the op, never a wrong number. Every
implemented one is checked against the reference on the same inputs, values and
shape/dtype, plus its error paths.

| §3.1 group | Implemented on libtorch | Not implemented |
|---|---|---|
| Creation (7) | `zeros`, `ones`, `empty`, `full`, `like`, `arange`, `scalar_to_tensor` | — |
| Elementwise (17) | `add`, `sub`, `mul`, `div`, `neg`, `exp`, `log`, `sqrt`, `pow`, `relu`, `sigmoid`, `tanh`, `gelu_tanh_approx`, `eq`, `lt`, `where`, `clamp` | — |
| Reductions (4) | `sum`, `mean`, `max`, `argmax` (each with `axes` and `keep_dims`) | — |
| Linear algebra (3) | `matmul`, `transpose`, `batch_matmul` | — |
| Attention (3) | `permute`, `attention` (grouped heads, additive mask, `scale`), `rope` (`neox` or paired, `dims`, `inverse`) | — |
| Shape (9) | `reshape`, `squeeze`, `unsqueeze`, `slice`, `concat`, `stack`, `broadcast_to`, `gather`, `scatter_add` | — |
| Convolution/pooling (5) | `conv1d` (`stride`, `padding`), `avg_pool1d` (`kernel`, `stride`, `padding`), `conv2d` (`stride`, `padding`, `groups`), `max_pool2d` and `avg_pool2d` (`kernel`, `stride`, `padding`) | — |
| Movement (4) | `to_dtype`, `copy`, `contiguous` | `to_device` |

Plus the host-crossing functions §4 names, `from_list`, `from_file`,
`from_bytes` and `to_list` (readback), which are not primitives, `append_file`, which appends
the values of an `F32` tensor to a file, and `convert_file`, which
writes a range of floats of one file into another as another float format.
`gelu_erf`, the exact GELU, is outside §3.1: it runs on every backend for
inference, and `Trace` records it without a gradient.

Why that one is out:

- **`to_device`** would only move a tensor to the one device libtorch serves
  here, which is the identity: it serves `Device.Cpu` only.

`conv1d`/`avg_pool1d` take the window `DESIGN.md` §3.1 admits and no more:
`stride` ≥ 1 and `padding` ≥ 0, no dilation, no groups. `avg_pool1d` also caps
`padding` at half the kernel, because that is the window the libtorch kernel
admits; the cap lives in the public wrapper, so the reference and libtorch
refuse exactly the same windows. `conv2d`, `max_pool2d` and `avg_pool2d` take
`[N, C, H, W]` only, the same `stride` and `padding` on both axes, and
`max_pool2d` and `avg_pool2d` cap `padding` at half the kernel too; `conv2d`'s
weight is `[C_out, C_in / groups, KH, KW]`. `conv1d` takes `[C_in, L]` or
`[N, C_in, L]` against a `[C_out, C_in, K]` weight, and `avg_pool1d` takes
`[C, L]` or `[N, C, L]`; both answer the input's leading axes plus the new
length, and both refuse an empty input, a window wider than the padded input
and a channel-count mismatch.

Reduction `axes` are a **set**, and the wrapper hands every backend the
ascending order (`tensor.agc`, `normalize_axes_option`). `argmax` numbers the
position inside a reduced block by the order of its axes, and the two backends
walk a tensor differently, so a literal `some([2, 0])` would break a tie on
different elements. Sorting in the one place both backends share fixes it:
`argmax(x, some([2, 0]))` and `argmax(x, some([0, 2]))` are the same call
(`test/torch_reductions_test.agc` pins the tie and the numbering).

Limits of what crosses the boundary:

- shapes, dtypes and devices cross as `List[Int]`, an `Int` code and nothing
  (CPU only); there is no struct over the boundary, so the wrapper is the one
  that knows both metadata and handles. A `List` of handles does not cross
  either, which is why native `concat` joins **two** tensors and
  `src/torch.agc` folds: concatenation along one axis is associative, so the
  fold answers exactly what one call would.
- readback crosses as storage doubles: `I64` values past 2^53 lose precision
  on the way out. Relatedly, `arange` past an int dtype's width diverges by
  side — libtorch's conversion wraps (200 into `I8` reads back `-56`) while the
  reference refuses to read it back at all; `test/torch_creation_test.agc`
  pins both.

## Local setup

libtorch 2.4.1+cpu (the shared-library CPU release) is what this package was
built against, and the numbers below were measured on. CI tests Ubuntu's
`libtorch-dev` (2.9.1 today; Debian's 2.6.0 passes too), so 2.4.1 to 2.9 works:

```sh
# https://download.pytorch.org/libtorch/cpu/libtorch-cxx11-abi-shared-with-deps-2.4.1%2Bcpu.zip
unzip libtorch-cxx11-abi-shared-with-deps-2.4.1+cpu.zip -d "$HOME/opt"
export TORCH_DIR="$HOME/opt/libtorch"
eval "$(sh tools/build-torch.sh)"   # in the shell that runs agentica
# --max-steps N: a test file's step budget is N x (its tests + 1), 1000000 by
# default; CI passes 10000000 to every member, and the tests here need under 1M.
agentica test --max-steps 10000000  # builds the module on first use
agentica tools/bench.agc
```

`eval "$(sh tools/build-torch.sh)"` is what makes the build possible:
`agentica.toml` can name `.c` sources, `-D` defines and `-l` names, and nothing
else, so the C++ driver (`CC`), libtorch's headers (`CPLUS_INCLUDE_PATH`) and
its libraries (`LIBRARY_PATH`) come from the environment. The build cache key
includes those three variables, so a shell without them builds nothing and
warns.

Without libtorch the package still works: `agentica check`, `agentica fmt
--check` and `agentica test` run, the run prints

```text
warning: native module torch not built: the C compiler failed with status 1; the package runs without it
```

The compiler error above it is one line, `no libtorch found` and how to find it: `native/torch.c` stops before it includes a header of its own.

and every conformance test takes its `Conform.absent()` path, which asserts
that `Tensor.available(...)` is false and that the dispatch arm answers an
`error` instead of halting. `agentica test` reports those as passed, so
**that warning line is the signal that the conformance comparison did NOT
run**.

## The ggml backend

`Backend.Ggml(Device.Cpu)` is ggml's CPU backend and
`Backend.Ggml(Device.Vulkan(i))` the Vulkan device `i` (on this machine, the
Vega iGPU through RADV). ggml is the pinned submodule `third_party/ggml`, built
here and never vendored:

```sh
git -C .. submodule update --init third_party/ggml
eval "$(sh tools/build-engine.sh | grep '^export ')"          # CPU only, about a minute cold
eval "$(JOBS=2 sh tools/build-engine.sh vulkan | grep '^export ')"   # CPU + Vulkan, about 25 minutes cold
eval "$(sh tools/build-torch.sh)"   # optional, after it: both modules then build with g++
agentica test --max-steps 10000000
```

The script runs on Linux x86_64 and aarch64 (it writes a GNU ld linker script)
and fails early elsewhere. On x86_64 the flags pin AVX2; on aarch64 ggml is
built for the CPU the script runs on (`GGML_NATIVE=ON`: NEON, and SVE and i8mm
where the CPU has them), and the cache key names that CPU, so build on the
machine that runs it (an entry copied to another CPU is a miss). The Vulkan
build is x86_64 only. The Vulkan build needs the Vulkan headers and loader, `glslc` and
`SPIRV-Headers` (`libvulkan-dev`, `glslc`, `spirv-headers`, or a Vulkan SDK in
`$VULKAN_SDK` or `$HOME/.local/vulkan-sdk/usr`); the script lists what is
missing. The exports are `C_INCLUDE_PATH`, `CPLUS_INCLUDE_PATH` (g++ ignores
the first) and `LIBRARY_PATH`. The last one points at the cache entry, where the
script writes `libtensor_ggml.a`: a linker script naming ggml's archives, plus
`ggml-vulkan` and the Vulkan loader for the Vulkan entry. `agentica.toml` links
that one name, so one build table serves both entries, and `native/ggml.c` finds
Vulkan through ggml's backend registry at run time, so it has no `#ifdef`.
The entry lives outside the checkout, in
`${AGENTICA_ML_CACHE:-${XDG_CACHE_HOME:-$HOME/.cache}/agentica-ml}/ggml/<key>/`,
and the key is the ggml commit, the action, a hash of the cmake flags and a
hash of the compiler versions. Every worktree of the same pin finds the entry
and compiles nothing (the Vulkan shaders are the slow part, and the entry
holds them already compiled); a new commit, other flags or another compiler is
a new entry, built through `ccache` when it is installed. `ENGINE_REBUILD=1`
forces a rebuild, and removing the folder is always safe.
The package cache keys a module on those paths, and the key holds the ggml
commit, so a bump of the pin links a new module with no manual cleanup.

### A fresh AWS c8g (Graviton4, Ubuntu 24.04 arm64)

CPU only; no GPU or Vulkan. The same steps run in CI on GitHub's
`ubuntu-26.04-arm` runner (the `ggml-arm64` job).

```sh
sudo apt-get update
sudo apt-get install -y build-essential cmake git ccache curl

cd ~
git clone https://github.com/agentica-lang/ml
git -C ml submodule update --init third_party/ggml

# The Agentica release that tensor/AGENTICA_VERSION names: the linux-arm64
# archive, whose sha256 is the third column of that file.
read -r v _ sha < ml/tensor/AGENTICA_VERSION
curl -fsSLO "https://github.com/agentica-lang/agentica/releases/download/$v/agentica-$v-linux-arm64.tar.gz"
echo "$sha  agentica-$v-linux-arm64.tar.gz" | sha256sum -c -
tar xzf "agentica-$v-linux-arm64.tar.gz"
export PATH="$PWD/agentica-$v-linux-arm64/bin:$PATH"

cd ~/ml/tensor
eval "$(sh tools/build-engine.sh | grep '^export ')"    # the CI runner (4 vCPUs) takes about 20 seconds
agentica install
TENSOR_REQUIRE_GGML=1 agentica test --max-steps 10000000
```

`TENSOR_REQUIRE_GGML=1` makes a ggml that did not build fail the tests. To
see what the CPU offers ggml, run `grep -m1 Features /proc/cpuinfo` (a
Graviton4 lists `sve`, `sve2`, `i8mm` and `bf16`). `JOBS=n` sets the build
parallelism.

What it does: `zeros`, `ones`, `empty`, `full`, `like`, `arange`,
`scalar_to_tensor`, `from_list`, `to_list` and `to_device` eagerly, plus
`stop_grad` (the identity). Every other op answers an error naming it and
pointing at `Trace`: ggml is fast only when a whole computation is one graph.
`Trace.eval`, `Trace.eval_many`, `Trace.value_and_grad` and `Trace.grad` on
`Ggml` tensors lower the whole traced graph, forward and backward, to one ggml
graph and run it
(`DESIGN.md` §7). The graph is cached by its structure (ops, shapes, dtypes,
integer parameters), not by the values of its inputs, constants or fills, so a
training loop that retraces every step compiles once. Inputs are read in place
and outputs written into fresh tensors, with no copy. The ops lowered are those
of an MLP and softmax cross-entropy with their gradients, plus `slice`,
`gather` and `scatter_add`, and attention's `permute`, `batch_matmul`, `rope` and `attention` (the list is in §7); a `gather` or `scatter_add` index outside the rows, any
other op, a dtype `F32` does not hold exactly and an output that is not
finite are errors. Vulkan multiplies in fp16 by default, which is about 1.7 times
faster for the products of a model and changes gradients by up to about 10 % at
MLP sizes; `Tensor.vulkan_fp16(false)`, before any other ggml call (a CPU one, or
`Tensor.available` of a Vulkan device, included), switches the whole process to exact `F32`
`mul_mat` (on a build without Vulkan it changes nothing), and the checks against
Hugging Face and whisper.cpp do. ggml
holds `F32` and `I32`; `Bool`, `I8`, `I16` and `U8` are held as `F32`, which is
exact for them; `F64` and `I64` are refused, `F16` and the quantized dtypes (`Q8_0`, `Q4_K`, `Q6_K`) are held only as a weight from `from_file` (or an `F16` cache), and a rank above 4 is refused. A
fill is made in C, so it has no `List.repeat` cap. Vulkan buffer operations
(allocate, write, read, free) run under one lock, so tasks can share a device.
`Device.Vulkan(i)` counts only devices that are not a CPU (a software rasterizer
is skipped).

`test/ggml_test.agc` round-trips every creation call against the reference on
the CPU backend and on Vulkan device 0, and runs two tasks on one Vulkan device.
`test/ggml_compile_test.agc` checks the value and every gradient of a small MLP
and of the cross-entropy against the reference within 1e-6 (relative to the
largest value) on the CPU backend and on Vulkan, that a retrace with new values
compiles nothing, `slice`, `gather` and `scatter_add` (an index outside the rows is an error),
`concat` and `stack` on every axis, `test/ggml_attention_test.agc` (`attention` over grouped heads, masks and the causal flag, `rope`, `permute`, `batch_matmul` and the backward of attention, node by node with `Trace.diff`), `test/conv2d_test.agc` (`conv2d` with stride, padding and groups, `max_pool2d` and `avg_pool2d`, forward and gradients, against a Python peer in doubles on every backend), the ops of Whisper's forward (`conv1d`,
`gelu_erf`, layer norm, softmax, masked attention) and the refusals. `test/ggml_turns_test.agc`, in a process of its own, that a
graph without fills does not write into the buffer the shared allocator freed
when a larger graph grew it. `test/threads_test.agc` checks, in processes of its own, that `TENSOR_THREADS` sets the threads of the CPU backend and a bad value leaves the default. `test/ggml_vulkan_mlp_test.agc` checks the
benchmark's 784 → 512 → 512 → 10 model at batch 256 on Vulkan with
`Tensor.vulkan_fp16(false)` against ggml's CPU backend within 1.5e-6 (local only;
`TENSOR_VULKAN_TOL` overrides the bound on another device), and
`test/ggml_fp16_test.agc`, in a process of its own, that the default (fp16)
moves it further than that but within 0.1. Without
the module, or without a Vulkan device, they assert the absent state instead or
pass. With `TENSOR_REQUIRE_GGML` set (CI sets it for this package) a missing
module fails the checks instead of passing them. Run the tests with
`GGML_VK_DISABLE_F16` unset: a value set to anything makes the process `F32`
(`ggml_fp16_test.agc` checks the fp16 default).

### Step time through `Trace`

A step of `Train.fit` is one graph that the loop retraces, differentiates and lowers every step (about 1 to 3 ms in Agentica, in which gap the iGPU drops to its lowest clock, so the next graph runs slower; that gap is the price of retracing, which keeps `Trace` the only API), or one `Trace.compile` of the whole step run again and again. `benchmarks/README.md` has the times against PyTorch and JAX.

## The XLA backend

`Backend.Xla(Device.Cpu)` runs a traced function through XLA on the CPU. The
native module (`native/xla.c`) builds with every install, links nothing of XLA,
and loads XLA's PJRT plugin with `dlopen` at the first use. Install the plugin
once, from `tensor/`:

```sh
agentica tools/install_xla.agc
```

It downloads the plugin of this machine from our release (`Xla.RELEASE`,
built by the `XLA plugin` workflow, see `xla-commit`), checks its sha256 and
keeps it in `${AGENTICA_ML_CACHE:-~/.cache/agentica-ml}/xla/<sha256>/`. The
release has Linux x86_64 and aarch64 only (CI runs x86_64; aarch64 is
untested); 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. On AWS Inferentia2 and Trainium,
`AGENTICA_ML_NEURON_PLUGIN` loads Neuron's plugin instead and the devices are
`Device.Neuron(i)`, one per NeuronCore: see the site's "XLA on AWS Neuron" page
(`site/content/tensor/neuron.md`).

What runs: `Trace.compile` emits the function as StableHLO (`Trace.stablehlo`,
`DESIGN.md` §12) and XLA compiles it once; `Trace.run` runs it. `Trace.eval`,
`eval_many` and `value_and_grad` compile the graph for each call, through a
cache of the process keyed by the text, so a retraced function compiles once.
`Train.fit` runs on XLA; the moments of an `adam_step` are updated in place, so
a run consumes them. The ops are the ones the StableHLO emitter covers (an MLP,
its gradients and an SGD or Adam step written with them); any other is an error
naming it. Eagerly, `Xla` only creates tensors, reads them back and passes
`stop_grad` through, as `Ggml` does: every other op is an error naming the op.

## CI

`.github/workflows/ci.yml` has one generic job per package folder. It runs
`agentica check`, `agentica fmt --check`, the native-gen `--check` of
`native/torch_native.h`, and `agentica test` on the pinned Agentica. That job
does **not** install libtorch (a 473 MB `libtorch_cpu.so` plus 51 MB of
headers; the repository never downloads it). So:

- That job proves that the package checks and formats, that the committed
  header is the one native-gen makes from `src/native.agc`, and that the suite
  runs green with the module absent.
- The `torch` job installs Ubuntu's `libtorch-dev` (a system package; its
  version is printed in the job log), builds `native/torch.c` and runs the whole
  suite with `TENSOR_REQUIRE_TORCH=1`, so a module that did not build fails the
  torch tests instead of passing them as absent. It proves that the C++ compiles
  against that libtorch and that the values agree with the reference. It runs,
  in parallel with the packages, when `tensor/` or the workflow changes
  (`tools/plan.py` decides). The line coverage of `src/torch.agc`, `src/torch_dtypes.agc` and
  `src/native.agc` is counted from this job (`tools/coverage_check.py --only
  libtorch`), not from the package job.
- The release the numbers of this README were measured on is libtorch 2.4.1+cpu
  at `$HOME/opt/libtorch`; the `torch` job tests whatever version Ubuntu's
  `libtorch-dev` is (2.9.1 today).
- CI **does** build ggml's CPU backend (`tools/build-engine.sh`, the
  workflow's engine step), so `native/ggml.c` compiles and the ggml CPU
  checks run there; `TENSOR_REQUIRE_GGML=1` makes a module that did not build
  fail them. The `ggml-arm64` job does the same on `ubuntu-26.04-arm`, with the
  linux-arm64 Agentica archive. Vulkan runs locally only: no hosted runner has a
  device.
- The `xla` job installs the XLA plugin (cached by its sha256) and runs the XLA
  tests with `TENSOR_REQUIRE_XLA=1`, in parallel with the packages, when
  `tensor/`, `train/`, a package they depend on or the workflow changes.

## Tolerances, and why

`test/torch_support.agc` compares against the reference with

```text
|a - b| <= 1e-7                       absolute, for values near zero
|a - b| <= 1e-7 * (|a| + |b|)         relative, above that
a == b                                when either side is not finite
```

and requires exact equality for integer and `Bool` values, and exact shape and
dtype equality.

The property tests (`test/prop_oracle_test.agc`) use the same tolerance, and 1e-6
relative for `exp`, `tanh`, `sigmoid`, `silu`, `log`, `sqrt`, `pow`, `softmax`
and the norms: libtorch's vectorised math may be an ulp or two (1.2e-7 each)
from the correctly rounded value.

The reason for a tolerance: the reference computes in doubles, while libtorch
stores and computes `F32`, whose epsilon is 1.19e-7. 1e-7 is one float32 ulp of
slack, no more: a `matmul` that picked the wrong operand, or an `exp` applied
twice, misses it by orders of magnitude.

The third line keeps the tolerance from being vacuous at infinity (`inf - inf`
is `NaN`): `test/torch_elementwise_test.agc` pins `exp(100)`, which is `+inf`
in `F32` and finite in doubles, and asserts that the comparison *fails*.

Where the two backends legitimately disagree and are therefore not asserted:

- **saturation**: `exp` overflows `F32` above ~88.7 and gives `+inf`, while the
  reference saturates at 1e308 in doubles. Both are "finite in, non-finite
  out"; the conformance values stay inside `|x| <= 8`.
- **`F64`/`F16` compute**: the reference keeps those values exact; libtorch
  rounds them through the same 24-bit mantissa when it computes in `F32`. The
  tests use `F32` input, so this never hides behind the tolerance.
- **`I64` readback past 2^53**: the boundary carries doubles; the tests use
  values at 2^53 exactly, which round-trip.

## Lifetimes

`DESIGN.md` §8: one `Native.arena` per call, and one per step when a caller
runs several ops.

- Every op in `src/torch.agc` opens its own `Native.arena` and returns the
  tensor it made as the block's value; the arguments are not its to close.
- A caller that runs a block (a decode step, an inference call) wraps it in one
  `Native.arena`: the intermediates die at the end of the step, newest first.
- `Handle.Native` and `Handle.Plain` coexist in one process, dispatch by value,
  and mixing the two backends is an `error`.

`test/torch_lifetime_test.agc` checks these rules from Agentica's side: a value
that leaves an arena is still readable, an argument is not closed by an op's
arena, and an explicitly `Native.close`d handle reads as closed.

## What the dependency costs

One machine (Linux x86_64, 12 cores), libtorch 2.4.1+cpu from the plain CPU
release; the build numbers are a single `native/torch.c` compile.

| What | Measured |
|---|---|
| libtorch unpacked | 786 MB (lib/ 736 MB, include/ 51 MB; `libtorch_cpu.so` alone 473 MB) |
| clean build of the module | 18.7 s wall, 1.1 GB peak RSS (one `g++` of `native/torch.c`) |
| the module itself | `libtorch.so`, 87 KB |
| first `Native.load("torch")` | ~400 ms (dlopen of libtorch) |

Per-op cost, 2000 rounds each, `tools/bench.agc`, nanoseconds per op (the
torch column includes the free of the tensor the op made):

| op (shape) | reference | torch |
|---|---|---|
| `add [2, 2]` | 2.8 µs | 17 µs |
| `add [64, 64]` | 480 µs | 21 µs |
| `matmul [4, 3]x[3, 2]` | 3.6 µs | 11.5 µs |
| `matmul [64, 64]x[64, 64]` | 6.6 ms | 33 µs |
| `from_list [64, 64]` (4096 values) | 784 µs | 1.6 ms |
| `exp [64, 64]` | 1.43 ms | 72 µs |
| `sum [64, 64]` | 1.13 ms | 20 µs |
| `linear`+`relu` step, `[4, 3]` | 8.0 µs | 37 µs |

What those two columns say:

- **A small op is dominated by the crossing** (~10 µs of arena, resource and
  term work): a step of twenty tiny ops pays ~340 µs before libtorch does any
  work. `DESIGN.md` §8's arena-per-step amortises it.
- **Real work wins outright**: 64×64 mats and transcendentals are 7× to 200×
  faster than the reference.
- **Crossing a big tensor in is the exception**: `from_list [64, 64]` is 2×
  slower than the reference because 4096 values cross as VM terms.
