# Map a function over tensor lanes

`(vmap function :in-axes 0)` returns a function. Each call applies it to the
lanes of its arguments and stacks each output tensor along a new leading axis.

```sh
sexpgpu probe --expr '((vmap (lambda (x) (* x x))) (+ (cast (iota [3]) :float) 1.0))' --max-elements 100
```

The result is `[1.0 4.0 9.0]`. `:in-axes` is a static integer axis (negative
axes count from the end), or a list/vector with one axis or `nil` per argument.
`nil` shares that entire argument. All mapped tensor leaves must have the same
static extent. A scalar axis maps every leaf of every argument; an axis per
argument applies to every leaf of that argument's tree. At least one tensor
argument must be mapped so the extent can be inferred.

Arguments and results may be tensor/list/vector/plist trees. Results keep their
structure, keys and shared leaves, with one leading lane dimension on each leaf.
Integer and boolean leaves are supported. Several return values stack
separately. Zero lanes produce empty tensors with the declared output shapes.

`vmap` composes with [grad](https://sx.041.io/docs/grad.md), [vjp](https://sx.041.io/docs/vjp.md), [jvp](https://sx.041.io/docs/jvp.md), nested
`vmap` and [scan](https://sx.041.io/docs/tensors.md#scan), including `vmap` of `grad` through a scan
body. Captured tensors are shared. Reporting effects and state declarations
inside the function are refused with `E-TRANSFORM-003`. The function is traced
once; there is no host function evaluation per lane or training step.

Every random draw inside the function, including a named `:stream` draw, gets
independent values keyed by logical lane. Repeating a named draw through the
same map gives the same noise lane by lane. Nested maps add a key per level; map
lanes and scan trips use distinct key namespaces. Physical batch cuts and rank
counts do not change the logical lane's draw. Draws outside the mapped function
keep their ordinary values. To share noise, draw it outside:

```sx
(let ((noise (normal [] :stream "shared")))
  ((vmap (lambda (x) (+ x noise))) (zeros [4])))
```

Rewriting a batched model as `vmap` of a per-example function changes which
noise values it draws, not their distribution.

`E-VMAP-001` names an invalid signature, axis specification or missing mapped
argument; `E-VMAP-002` names an invalid axis or unequal mapped extents;
`E-VMAP-003` names an output or captured input that cannot be stacked or shared.
Use a tensor tree result, matching static extents and `nil` for shared
arguments.

---

SexpGPU documentation. Every page: https://sx.041.io/llms.txt
