Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Chapter 17 — Nx Fundamentals

Nx (Numerical Elixir) brings the computational model of NumPy/JAX/PyTorch to the BEAM while keeping functional semantics. It is the foundation for everything in Part IV.

What if Elixir could describe numerical computation while specialized backends decide how to execute it?

17.1 The Four Abstractions

AbstractionPurposeImplementations / instances
Nx.TensorImmutable multi-dimensional arraystruct wrapping backend-specific data
Nx.DefnNumerical definition (macro)Elixir subset compiled to backend IR
Nx.BackendStorage + op dispatch behaviourNx.BinaryBackend, EXLA.Backend, EMLX.Backend, Torchx.Backend
Nx.ContainerProtocol: what defn can traversetuples, maps, @derive {Nx.Container, containers: [:params]} structs

Nx.Container is the one that confuses newcomers, because the name suggests storage. It is not: storage is Nx.Backend. Nx.Container is the protocol that teaches defn how to walk a data structure holding tensors — a tuple of (weights, bias), a map of named params, a struct. Auto-derived so Axon can pass parameter containers through functions:

defmodule MyParams do
  @derive {Nx.Container, containers: [:w, :b]}
  defstruct w: nil, b: nil
end

Types: tensors carry shape {dims...} and type {:f | :s | :u, bits} — u2/u4/u8…u64, s2/s4…s64, f8/f16/f32/f64, bf16, c64/c128. Shapes can have dynamic (nil) dims for batch size.

Memory model: tensors are immutable; operations return new tensors. The Elixir GC handles tensor structs; the backend manages device memory.

Tensors Are Refc Binaries

Under Nx.BinaryBackend a tensor’s payload is an Erlang binary — a refc binary once it exceeds ~64 bytes. Your Erlang binary instincts carry over:

Erlang conceptNx equivalent (BinaryBackend)
<<1.5:32/float>>Nx.from_binary(bin, {:f, 32})
binary_part/3Nx.slice/3
byte_size/1Nx.byte_size/1

Consequences worth internalizing:

  • No mutation, ever. Nx.add(a, b) reads both payloads and allocates a third — the same aliasing-free discipline as Erlang binaries, scaled to multidimensional data.
  • Refc GC frees large payloads when the last tensor struct referencing them drops out of scope. Long-lived process state holding tensors holds their bytes — budget process memory accordingly.
  • Zero-copy bridges. Nx.to_binary/1 and Nx.from_binary/2 move between BEAM terms and typed tensors without transcoding; this is how Scidata and Ch 21’s persistence layer feed Nx.

17.2 Setup

Everything in this chapter runs in a Livebook cell (or iex after Mix.install has executed once per session):

Mix.install([
  {:nx, "~> 0.13"},
  {:exla, "~> 0.13"}
  # {:emlx, "~> 0.4"}   # Apple Silicon alternative to EXLA — see note
])

First evaluation compiles dependencies (slow); later cells are instant. If you skip a native backend entirely, plain {:nx, "~> 0.13"} alone works everywhere on Nx.BinaryBackend.

Add emlx only on Apple Silicon. Pulling it into a Linux CI job downloads a whole MLX toolchain you will never invoke there, since EXLA covers CPU on every platform (Ch 18).

17.3 Tensor Basics

iex> Nx.tensor([1, 2, 3])
#Nx.Tensor<
  s64[3]
  [1, 2, 3]
>

iex> key = Nx.Random.key(42)
iex> {rand, _new_key} = Nx.Random.uniform(key, shape: {2, 3})
iex> Nx.shape(rand)
{2, 3}

Properties:

iex> x = Nx.tensor([[1, 2, 3], [4, 5, 6]])
iex> Nx.shape(x)   # {2, 3}
iex> Nx.rank(x)    # 2
iex> Nx.type(x)    # {:s, 64}
iex> Nx.size(x)    # 6

Element-wise & broadcasting (NumPy rules — align trailing dims):

a = Nx.tensor([1, 2, 3])
b = Nx.tensor([4, 5, 6])

Nx.add(a, b)        # [5, 7, 9]
Nx.max(a, b)
Nx.exp(a)

matrix = Nx.tensor([[1, 2, 3], [4, 5, 6]])
vector = Nx.tensor([10, 20, 30])
Nx.add(matrix, vector)   # vector broadcast across rows

Nx.add(matrix, 100)      # scalar broadcast

The rule, made concrete: dimensions align from the right; missing or size-1 dims stretch to match; a mismatch where neither side is 1 is an error. Think of broadcasting as the vectorized replacement for the nested list comprehensions you would otherwise write:

# {2, 3}  + {3}    → {2, 3}    row vector onto every row
# {2, 3}  + {2, 1} → {2, 3}    column vector onto every column
# {4, 1, 3} + {2, 3} → {4, 2, 3}   the size-1 dim stretches…
# {4, 3} + {2, 3}    → error       …but 4 vs 2 with no 1 anywhere fails

iex> col = Nx.tensor([[10], [20]])             # shape {2, 1}
iex> Nx.shape(Nx.add(Nx.iota({2, 3}), col))
{2, 3}

Reductions and axes:

x = Nx.tensor([[1, 2, 3], [4, 5, 6]])

Nx.sum(x)             # 21
Nx.sum(x, axes: [0])  # [5, 7, 9]  (collapse rows)
Nx.sum(x, axes: [1])  # [6, 15]    (collapse cols)
Nx.mean(x)
Nx.reduce_max(x)

axes: semantics trip everyone once: the listed axes are collapsed. Summing axes: [0] removes the row dimension; keep_axes: true retains it as size 1, keeping the output broadcast-compatible with the input.

Type Promotion

Mixed-dtype operations promote the weaker side — floats beat integers, wider beats narrower:

ExpressionResult typeWatch out
s64 + f32f32ints lose precision past 2^53
u8 + u8 (element-wise)u8silent wraparound on overflow
f32 + bf16f32bf16 rounds up to f32
int tensor + float scalarfloatscalar adopts tensor family
iex> a = Nx.tensor([200], type: {:u, 8})
iex> Nx.add(a, a)
#=> #Nx.Tensor<u8[1] [144]>   element-wise ops wrap mod 256!
iex> Nx.sum(Nx.tensor([200, 200], type: {:u, 8}))
#=> #Nx.Tensor<u32 400>       but reductions PROMOTE instead — no wrap

Linear algebra:

Nx.dot(a, b)               # matrix multiply
Nx.transpose(a)
Nx.LinAlg.solve(a, b)      # a·x = b without inverse
Nx.LinAlg.svd(a)

Reshape/slice:

x = Nx.iota({2, 3, 4})

Nx.reshape(x, {6, 4})
Nx.slice(x, [0, 0, 0], [1, 2, 4])
x[[0, 1..2, 0]]            # access syntax: int = index, range = slice
Nx.concatenate([t1, t2], axis: 0)
Nx.stack([t1, t2])         # adds new axis

17.4 defn — Compilable Numerical Functions

defn restricts Elixir to a tensor-safe subset that can be JIT-compiled, differentiated, and inspected:

defmodule MathOps do
  import Nx.Defn

  defn relu(x), do: Nx.max(x, 0)

  defn linear(x, w, b), do: Nx.dot(x, w) + b

  defn mlp(x, params) do
    x
    |> linear(params.w1, params.b1)
    |> relu()
    |> linear(params.w2, params.b2)
  end

  defn leaky_relu(x, alpha \\ 0.01), do: Nx.select(x > 0, x, x * alpha)
end

Execution flow:

flowchart LR
    CALL["defn call<br/>f(x, params)"] --> SEEN{"shape/dtype<br/>seen before?"}
    SEEN -->|"no"| TRACE["trace with concrete shapes<br/>→ computation graph"]
    TRACE --> COMP["compile via backend<br/>XLA / MLX / Evaluator"]
    COMP --> CACHE["cache kernel"]
    CACHE --> RUN["run"]
    SEEN -->|"yes"| RUN
    RUN --> NEW["new shape later?<br/>→ recompile (specialized)"]
  1. First call: Nx traces the function with concrete shapes/types → builds computation graph → compiles to backend → caches kernel.
  2. Subsequent calls: reuse the cached kernel (dispatch by shapes/types).
  3. New shape → recompile (shape-specialized).

This is the JIT contract you know from BEAM hot paths, applied to numerics: first hit pays compilation; steady-state dispatch is a cache lookup keyed by shape/type signature.

Compilers: EXLA (production CPU/GPU), EMLX (Apple Silicon), Nx.Defn.Evaluator (pure-Elixir debugging interpreter), Nx.Defn.Debug.

Why a Restricted Language Pays

Tracing a closed subset means the backend sees the whole computation as a graph before executing any of it — the precondition for what makes numerics fast:

  • Kernel fusion: element-wise chains lower into a single pass; intermediates between linear and relu never touch memory.
  • Mechanical autodiff: gradients derive from the graph itself (§17.5).
  • Portability: one expression lowers to XLA, MLX, or the interpreter.

The price: inside defn there is no Enum, no pattern matching on tensor values, no message passing. Branching is Nx.select (elementwise) or Nx.cond (graph-level); loops are Nx.while. When you miss imperative control flow, suspect a vectorized formulation exists — unlearning the recursive-accumulator reflex is most of the migration effort here.

Observability survives compilation via hooks — the io:format of tensor programs, callable even under EXLA. (hook/2 comes from Nx.Defn.Kernel, already in scope via import Nx.Defn; the data passes through unchanged):

defn inspected(x) do
  x
  |> hook(fn t -> IO.inspect(Nx.shape(t), label: "post-linear") end)
  |> relu()
end

Note the anonymous fn: the callback’s return value is ignored and x passes through unchanged. Writing &IO.inspect(Nx.shape(&1), ...) looks equivalent but returns a shape tuple, which reads as if the tensor were being replaced by its shape. It isn’t — but the code misleads every reader including its author.

17.5 Automatic Differentiation

Reverse-mode autodiff over parameter containers (tuples/maps/lists):

defmodule Gradients do
  import Nx.Defn

  defn mse_loss(w, b, x, y) do
    y_pred = Nx.dot(x, w) + b
    Nx.mean((y_pred - y) ** 2)
  end

  defn grad_mse(w, b, x, y) do
    Nx.Defn.grad({w, b}, fn {w, b} -> mse_loss(w, b, x, y) end)
  end
end
  • First arg of grad/2: container holding params — gradients come back in the same structure.
  • Second arg: primal function returning a scalar loss.
  • value_and_grad/2 returns {loss, grads} together — useful for logging.

Minimal autodiff demo:

defmodule MathDemo do
  import Nx.Defn
  defn f(x), do: Nx.sum(x * x)
end

x = Nx.tensor([1.0, 2.0, 3.0])
Nx.Defn.grad(&MathDemo.f/1).(x)
#=> #Nx.Tensor<[f32[3]] [2.0, 4.0, 6.0]>   (df/dx = 2x)

Loss-plus-gradient in one graph traversal — the primitive every custom training loop builds on (compare Ch 19’s CustomTrainer.train_step/5):

loss_and_grad = Nx.Defn.value_and_grad(&MathDemo.f/1)
{loss, grad} = loss_and_grad.(x)

Computing them separately would run the forward pass twice.

Stability: Subtract Before You Exponentiate

Naive Nx.exp(logits) / sum(...) overflows f32 near logit 89 — exp(88.7) is the ceiling of f32. The fix is algebraic, not a bigger dtype:

softmax(x)   = exp(x - max(x)) / sum(exp(x - max(x)))
logsumexp(x) = max(x) + log(sum(exp(x - max(x))))
defn stable_log_softmax(x) do
  Nx.subtract(x, Nx.logsumexp(x, axes: [-1], keep_axes: true))
end

You will rarely write this yourself — Axon losses embed the trick — but recognizing a max-subtraction in library code tells you it is overflow armor, not style.

For per-example maps over a batch, Nx.vectorize/2 is the tool:

defn per_example_loss(t) do
  Nx.vectorize(t, :batch)
end

You rarely need vmap/jacobian because Nx ops are naturally batched — an mlp/2 already runs across a batch dimension, and Axon handles gradients for you.

17.6 Performance Tips

TipWhy
Use defnJIT to XLA/MLX — 10–100x vs pure Elixir
Pick the right backendBinaryBackend to debug; EXLA/EMLX for speed (Ch 18)
Batch operationsGPU utilization; avoid scalar loops
Keep data on deviceDon’t Nx.to_flat_list in hot paths
Use bf16Half memory, faster on modern GPUs / Apple Silicon
Compile with fixed shapesa Nx.template/2 lets XLA specialize per shape
Read the fused graphprint_expr/1 from Nx.Defn.Kernel, inside a defn

Specializing on shape is what defn’s JIT cache keys on, and it is the layer below Bumblebee’s compile: / Nx.Serving options — those keys specialize on a batch key, not on a raw shape:

# raw defn: specialize on templates for EVERY argument, then compile once
x_t = Nx.template({32, 784}, :f32)
w1_t = Nx.template({784, 256}, :f32)
b1_t = Nx.template({256}, :f32)
w2_t = Nx.template({256, 10}, :f32)
b2_t = Nx.template({10}, :f32)

compiled =
  Nx.Defn.compile(&MathOps.mlp/2, [x_t, %{w1: w1_t, b1: b1_t, w2: w2_t, b2: b2_t}],
                  compiler: EXLA)

compiled.(real_x, real_params)   # a callable, cached by shape

Note the params argument is a map — mlp/2 reads params.w1 etc, and a map is an Nx.Container, so the whole structure is part of the specialization key. A compile/3 list must cover every argument, or the resulting closure raises when called with the missing one.

And to see the graph the compiler will build, print the expression from inside the defn. import Nx.Defn injects Nx.Defn.Kernel into the body, so print_expr/1 is available bare and takes an already-built expression — not a capture plus templates:

defmodule MathOps do
  import Nx.Defn

  defn traced(x) do
    y = Nx.multiply(x, 2)
    print_expr(y)      # prints #Nx.Tensor< Nx.Defn.Expr ... >
    Nx.add(y, 1)
  end
end

Verified output shape:

#Nx.Tensor<
  f32[2]

  Nx.Defn.Expr
  parameter a:0       f32[2]
  b = multiply 2, a   f32[2]
>

Two things that do not work: passing a capture plus templates to print_expr (print_expr/2’s second argument is IO.inspect options, not a template list), and Nx.Defn.Debug as a debugging entry point (@moduledoc false; it is a private compiler shim).

If a benchmark varies shapes, you are timing the compiler — see the harness in Ch 18 §18.8.

17.7 Serialization and Named Axes

Persistence reduces to binaries plus metadata. Nx.serialize/1 is the reference implementation — simple, not fast; fine for configs and tests:

serialized = Nx.serialize(tensor)
restored   = Nx.deserialize(serialized)   #=> identical tensor

Hot paths prefer the raw triple — Nx.to_binary/1, Nx.type/1, Nx.shape/1 — which round-trips through files and network with zero framing overhead. Ch 21’s ML.Persistence builds on exactly that.

Inside defn, named axes replace positional bookkeeping, so “is axis 1 the head or the sequence?” stops being a bug class:

defn mean_over_batch(t) do
  t
  |> Nx.rename([batch: 0, features: 1])   # rename/2 takes a LIST of names
  |> Nx.mean(axes: [:batch])             # keyword instead of position 0
end

Names must be set before you use them — Nx.rename/2 on an unnamed tensor assigns, it does not require.

Adopt them for models with three-plus dimensions; skip for throwaway scripts where positions are obvious.

Explore More

  • Nx guides — start with “Tensor basics,” then “Nx.Defn,” then “Compiling functions”
  • Nx.Defn docs — compiler options, custom transforms, hooks for mid-graph inspection
  • Autodiff explainer in the Axon book — reverse-mode differentiation with Nx examples (free PDF)
  • Practice Lab: Lab 1 — Nx Optimization — gradient ascent, container gradients, and a backend benchmark on an all-new solar-tracker example
  • Exercise idea: implement softmax twice — once with plain Elixir lists, once as defn — and benchmark on 1M elements to internalize why backends matter

Checkpoint

  1. Why does Nx.Random return {tensor, new_key}?
  2. What triggers recompilation in defn?
  3. What is a “container” in grad/2?
Answers
  1. Functional RNG: no global state, reproducible, parallelizable — same key always yields the same sequence.
  2. A call with input shapes/dtypes not seen before.
  3. Any structure (tuple/map/list) wrapping trainable parameters; gradients are returned in the identical structure.

Next: Chapter 18 — Backends: EXLA, EMLX & Hardware