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 18 — Backends: EXLA, EMLX & Hardware

The single most important architectural idea in Numerical Elixir:

The Nx API describes the computation (what). The backend decides how it is executed (how).

18.1 The Layered Architecture

flowchart TD
    EL["Elixir"] --> NX["Nx"]
    NX --> T["Nx.Tensor<br/>data container"]
    T --> D["Nx.Defn<br/>compilation hook"]
    D --> CB["Compiler / Backend"]
    CB --> EXLA["EXLA → XLA<br/>CPU / GPU / TPU"]
    CB --> EM["EMLX → MLX<br/>Apple GPU"]
    CB --> OTH["Other backends"]

Application logic never knows which backend runs. Swap hardware by swapping configuration.

x = Nx.tensor([1, 2, 3, 4])
Nx.sum(x * x)   #=> 30

# Same high-level op, different possible engines:
# - Default backend: pure Elixir loop
# - EXLA: XLA JIT → CPU/GPU kernel
# - EMLX: MLX → Apple Silicon GPU

Two distinctions sharpen this for BEAM developers.

Backend vs compiler. A backend owns tensor storage and op dispatch; a compiler optimizes a whole traced expression as one unit. BinaryBackend interprets each op separately — correct and readable, but blind to cross-op structure. EXLA couples storage with compilation: tensors live in XLA buffers and your entire defn becomes one fused program. The unit of optimization, not the language, is where the 10–100x comes from.

Process model. Compiled kernels run as dirty NIFs on dirty schedulers — never blocking normal schedulers, never yielding mid-kernel. XLA brings its own intra-op thread pools beneath that. Your processes stay responsive while native threads burn underneath: the Port/NIF discipline, applied to accelerators.

18.2 Backend Comparison

BackendTargetStatusBest For
Nx.BinaryBackend (default)CPU, pure ElixirStablePrototyping, small tensors, CI
EXLAXLA → CPU/GPU/TPUStableProduction ML, large models
EMLXMLX → Apple Silicon GPUActiveMac development
TorchxLibTorch → CPU/CUDAStablePyTorch interop, CUDA where EXLA is awkward

TorchScript is not an Nx backend — it is PyTorch’s serialization format, so it appears nowhere in this table. The LibTorch backend is Torchx (hex torchx, configured via LIBTORCH_TARGET).

For ONNX models inherited from a Python team, the answer is neither of these: use Ortex to run the ONNX graph plus Nx.Serving to batch it (Ch 21). That combination is the practical path for an Erlang shop taking delivery of ONNX artifacts.

Speed: BinaryBackend is the ~1x baseline; EXLA/EMLX typically deliver 10–100x on real workloads.

Choose deliberately, not by hype:

SituationReach for
Debugging numerics, exact intermediate valuesBinaryBackend
CI without native deps or downloadsBinaryBackend
Steady-state training/inference loopsEXLA
Apple Silicon dev box, pure Nx/defn workEMLX
GPU production (CUDA/ROCm)EXLA with the matching client

The interpreter re-traces on every call — slow, but intermediates survive exactly where a compiler would fuse them away. Prototype there; compile once the numbers look right.

18.3 Configuration

Four setters, and picking the wrong one is the classic “works in iex, fails in Livebook / fails in the release” bug. They differ in scope:

CallScopeUse for
Nx.default_backend(EXLA.Backend)this process onlyquick per-process demos
Nx.global_default_backend(EXLA.Backend)global VM stateLivebooks and IEx
Nx.Defn.default_options(compiler: EXLA)this processsetting a compiler without a backend
config :nx, :default_backend, EXLA.Backendrelease configproduction

A GenServer calling Nx.default_backend/1 in its init/1 sets the backend for that process only — every other process, including Nx.Serving partitions and Tasks, is unaffected. This is the single most important row in the table; Ch 21 revisits it where it bites in production.

# Livebook / IEx — global, so other spawned processes inherit it
Nx.global_default_backend(EXLA.Backend)

# Per tensor
x = Nx.tensor([1, 2, 3], backend: EXLA.Backend)

# JIT-compile a defn for a specific compiler (cached)
fun = Nx.Defn.jit(&MyModule.my_fn/1, compiler: EXLA)

# Pre-compile against a fixed template — for a hot loop called repeatedly
compiled = Nx.Defn.compile(&MyModule.my_fn/1, [Nx.template({3}, :s64)], compiler: EXLA)

# Default compiler options, process-wide
Nx.Defn.default_options(compiler: EXLA, client: :host)   # :cuda on NVIDIA boxes

Confirm the machine actually has the device you expect, before debugging anything else. EXLA.Client.get_supported_platforms/0 lists the platforms XLA registered, and probing by allocating confirms a client initializes:

# does a CUDA client even initialize?
t = Nx.tensor([1.0, 2.0], backend: {EXLA.Backend, client: :cuda})

On a host-only build this raises, and the error names the problem exactly:

Could not find registered platform with name: "cuda".
Available platform names are: Host

That message is the diagnostic — it tells you the build lacks a GPU runtime, so nothing in your Elixir code will fix it. EXLA.Client.get_supported_platforms/0 returns the same platform list without allocating a tensor.

Clients map names to platforms/devices and are declared up front:

Nx.Defn.jit(&MyModule.my_fn/1, compiler: EXLA, client: :cuda)

Environment variables tune the native runtime rather than Elixir code: XLA_TARGET=cuda selects a GPU-enabled runtime at dependency-compile time — set it before mix deps.compile, not just before mix compile. In Docker that means an ARG/ENV in the build stage, and you must also bake the downloaded XLA archive into the final image. XLA_FLAGS passes raw XLA flags through. Both belong in Dockerfiles and CI scripts more than in Livebooks.

18.4 EXLA — XLA Under the BEAM

EXLA wraps XLA (Accelerated Linear Algebra — Google’s compiler behind TensorFlow/JAX):

flowchart LR
    A["Elixir"] --> B["Nx"] --> C["Nx.Defn"] --> D["EXLA"] --> E["XLA"] --> F["CPU / GPU / TPU"]

XLA performs kernel fusion, layout optimization, and memory planning — all invisible to your code. First call compiles; later calls hit the cached executable.

Conceptual run:

defmodule DemoMath do
  import Nx.Defn

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

  defn linear_layer(x, w, b), do: Nx.dot(x, w) + b
  defn relu(x), do: Nx.max(x, 0)
end

Nx.default_backend(EXLA.Backend)

key = Nx.Random.key(42)
x = Nx.Random.uniform(key, shape: {32, 784})

params = %{
  w1: Nx.Random.normal(key, shape: {784, 256}),
  b1: Nx.broadcast(Nx.tensor(0.0), {256}),
  w2: Nx.Random.normal(key, shape: {256, 10}),
  b2: Nx.broadcast(Nx.tensor(0.0), {10})
}

DemoMath.forward(x, params)   # JIT-compiled via XLA

Production notes:

  • Batching: accumulate requests → one batched kernel launch
  • Caching: compile once per shape signature
  • Memory: XLA manages device memory; BEAM manages host memory
  • Requires the exla dep; the XLA runtime downloads automatically from Hex

Two advanced terms you will meet in XLA documentation, defined briefly:

  • Buffer assignment / memory planning: allocation and free points are scheduled at compile time via liveness analysis — device memory usage is planned up front, not malloc-as-you-go.
  • SPMD sharding: one program compiled to run partitioned across many devices. Nx exposes early sharding support; park it until a single accelerator genuinely limits you.

18.5 EMLX — Apple Silicon via MLX

EMLX targets Apple’s MLX framework, built around unified memory (no copying between CPU and GPU):

flowchart LR
    A["Elixir"] --> B["Nx"] --> C["EMLX"] --> D["MLX"] --> E["Apple Silicon<br/>CPU / GPU / Neural Engine"]
Nx.default_backend(EMLX.Backend)

x = Nx.tensor([1.0, 2.0, 3.0, 4.0])
Nx.sum(x * x)   #=> 30.0 — running on Metal

Relevant if you develop on MacBook M1–M4, Mac Studio/Pro.

Unified memory is the headline: on discrete-GPU setups every batch crosses the bus twice per pass (upload inputs, download outputs), while MLX arrays share pages between CPU and GPU. Fewer copies, faster dev-loop iteration — at the cost of a runtime that only exists on Apple Silicon, so keep the deploy target independent of the dev box.

18.6 Compatibility Warnings (Read Before Mixing)

Verified 2026-08 against nx 0.13.1 / emlx 0.4.1 / bumblebee 0.7.1. This combination is a moving target — re-check before you hit it.

emlx 0.4.x was incompatible with nx 0.13 + bumblebee: Bumblebee passes a batch_keys option EMLX did not support, and running a serving raised ** (ArgumentError) ... batch_keys. Diagnosis: the error names batch_keys, and it appears only under EMLX — swap to EXLA.Backend (which works on macOS, CPU by default). Plain Nx/defn on Apple Silicon → EMLX is fine.

Rule of thumb:

  • Bumblebee / Nx.Serving workloads → EXLA
  • Plain Nx/defn exploration on Apple Silicon → EMLX fine
  • Deterministic debugging/CI → BinaryBackend

18.7 The Architectural Payoff

flowchart TD
    APP["Application logic (Elixir)"] --> NUM["Numerical expression<br/>Nx.Defn / Axon"]
    NUM --> BE["Execution backend<br/>EXLA / EMLX / …"]
    BE --> HW["Native hardware<br/>CPU / GPU / TPU"]

Elixir can orchestrate. Specialized native runtimes can optimize.

This is the same boundary discipline as calling into a Port/NIF from Erlang — now applied to accelerators.

18.8 A Benchmarking Harness

Opinions about backends deserve measurements. Benchee makes the comparison one command deep:

Mix.install([{:nx, "~> 0.13"}, {:exla, "~> 0.13"}, {:benchee, "~> 1.4"}])

defmodule Bench do
  import Nx.Defn

  defn softmax(x) do
    max = Nx.reduce_max(x, axes: [-1], keep_axes: true)
    exp = Nx.exp(x - max)
    exp / Nx.sum(exp, axes: [-1], keep_axes: true)
  end
end

input = Nx.Random.normal(Nx.Random.key(1), shape: {1024, 1024})
jit = Nx.Defn.jit(&Bench.softmax/1, compiler: EXLA)   # compile ONCE, outside the loop

# Move the input onto the device first. Otherwise the "exla" closure JITs
# over a Binary tensor and every call pays a host→device copy — you are
# measuring the transfer, not the kernel.
exla_input = Nx.backend_transfer(input, EXLA.Backend)

# warm up: the first call of a JITed closure includes compilation
Bench.softmax(input)
jit.(exla_input)

Benchee.run(
  %{
    "binary" => fn -> Bench.softmax(input) end,
    "exla" => fn -> jit.(exla_input) end
  },
  time: 5,
  memory_time: 2
)

Reading the report with Erlang eyes:

  • The binary backend’s memory column materializes every intermediate; EXLA allocates once.
  • memory_time measures BEAM heap, not device memory. It says nothing about GPU VRAM. For VRAM, use EXLA client statistics or your accelerator’s own profiler.
  • Warm up before measuring, and pin shapes — a benchmark that varies shapes benchmarks the compiler, not the kernel.

Explore More

  • EXLA docs — compiler options, client/device configuration, GPU setup notes
  • EMLX repo — Apple Silicon MLX bindings, unified-memory explanations
  • Nx backends guide — write your own toy backend; the best way to learn the behaviour contract
  • XLA docs — what fusion/layout optimization actually do under §18.4
  • Exercise idea: run the §18.4 demo with Nx.Defn.Evaluator, then EXLA, and compare timings on {32, 784}×{784, 256} — then change batch size and watch the recompile happen in the logs
  • Practice Lab: Lab 1 — Nx Optimization — BinaryBackend vs EXLA benchmarked with Benchee on new examples

Checkpoint

  1. What does the default backend execute on?
  2. When does XLA recompile an executable?
  3. Which backend must Bumblebee notebooks use today?
Answers
  1. Pure Elixir loops (Nx.BinaryBackend) over CPU binaries.
  2. On first call per shape/dtype signature; results are cached thereafter.
  3. EXLA.Backend (works everywhere incl. macOS CPU).

Next: Chapter 19 — Training Models with Axon