# XLA on AWS Neuron

`Backend.Xla` loads a PJRT plugin: our CPU plugin by default, or the Neuron plugin that `AGENTICA_ML_NEURON_PLUGIN` names. AWS ships it for its NeuronCores, the chips of Inferentia2 (`inf2`) and Trainium (`trn1`), so the same traced functions, `Train.fit` included, run on a NeuronCore with no change to the code. Generation runs too (see Generation below); serving is not covered yet ([ml#477](https://github.com/agentica-lang/ml/issues/477)). This page sets it up on an `inf2.xlarge` (one chip, 2 NeuronCores of 16 GiB each).

## Set up

Start the machine from an AWS Deep Learning AMI Neuron (Ubuntu 24.04). It has the Neuron driver, the runtime and the Python environments under `/opt`; the plugin is in the JAX one. Install Agentica from its [release](https://github.com/agentica-lang/agentica/releases) and get the ml packages as usual. Then set four variables:

```sh
export PATH=/opt/aws_neuronx_venv_jax_0_10/bin:$PATH
export AGENTICA_ML_NEURON_PLUGIN=/opt/aws_neuronx_venv_jax_0_10/lib/python3.12/site-packages/libneuronxla/libneuronpjrt.so
export NEURON_RT_VISIBLE_CORES=0
export NEURON_CC_FLAGS=""
```

- `PATH` must hold the environment's `bin`: the plugin runs the Neuron compiler, `neuronx-cc`, from there.
- `AGENTICA_ML_NEURON_PLUGIN` is the Neuron plugin's file. Set and not empty, it replaces our CPU plugin for the whole process and the devices become `Neuron(0)` and up, and `tools/install_xla.agc` is not needed. Empty or unset, the backend loads the CPU plugin.
- `NEURON_RT_VISIBLE_CORES` picks the NeuronCores of the process, here the first; `0-1` gives it both.
- `NEURON_CC_FLAGS` passes options to the compiler (see bf16 below).

The folder of the environment changes with the AMI; `ls /opt` shows it.

## The device

Under `AGENTICA_ML_NEURON_PLUGIN` the backend is `Backend.Xla(Device.Neuron(i))`: core `i` of the ones `NEURON_RT_VISIBLE_CORES` shows, so `NEURON_RT_VISIBLE_CORES=1` puts `Neuron(0)` on the second core. `Tensor.xla_device()` gives the first device of this process, `Neuron(0)` or `Cpu`, so a program that does not hard-code it runs on both:

```agentica
backend = Tensor.Backend.Xla(Tensor.xla_device())
x = Tensor.ones([4], Tensor.Dtype.F32, backend).unwrap!
```

`Tensor.xla_devices()` lists them all: with `NEURON_RT_VISIBLE_CORES=0-1`, `Neuron(0)` and `Neuron(1)`. A tensor lives on one core, a compiled function runs on the core of its inputs and constants, and `Tensor.to_device` copies a tensor to another core. A program is compiled once for every core, with no core of its own (a portable PJRT program), and runs on the core of the call ([ml#508](https://github.com/agentica-lang/ml/issues/508)); a plugin that refuses that compiles each program once per core, as before, and so does every process under `AGENTICA_ML_XLA_PORTABLE=0`. A portable program whose run fails switches the process to per-core compiles for the programs it compiles after. Two cores in one process have run only with our CPU plugin standing in for Neuron's so far (two host devices, in CI), and whether Neuron's plugin takes a portable program is not checked on inf2 yet. A core past the last is refused with an error that names `NEURON_RT_VISIBLE_CORES`. While the plugin is Neuron's, `Xla(Device.Cpu)` is not available, and the other way round. A NeuronCore takes one process: two processes cannot share a core.

## Compiling

Each traced function is compiled by `neuronx-cc` when it first runs, which is slower than on the CPU: about 1.6 s for a small program and up to about 40 s for a big one (a training step over a hundred parameters takes 35 s). Opening the plugin takes about 5 s more. Neuron keeps the compiled programs in `/var/tmp/neuron-compile-cache`, so the same function compiles once per machine, and later runs take about 30 ms to load it. Shapes are part of a program: keep batch sizes fixed so that the cache hits.

`agentica test` gives each test 30 s, so on a fresh cache a test whose program compiles longer fails with `RUNTIME-TEST-TIMEOUT`; run it once more when the compile cache has the other programs.

## bf16

With `NEURON_CC_FLAGS` empty, the answers of the tests matched the CPU within 1e-6. For bf16 products, which are faster on a NeuronCore, set:

```sh
export NEURON_CC_FLAGS="--auto-cast matmult"
```

The compiler then runs every matrix product of every program it compiles in bf16. The answers move by about 1e-3, so compare with a tolerance to match.

## Flags per program

`NEURON_CC_FLAGS` is the base. A program traced for a phase gets more, as AWS's NxD Inference passes them: `Trace.compile(specs, f, Trace.Phase.Prompt)` adds `--model-type=transformer --internal-hlo2tensorizer-options=--modular-flow-mac-threshold=10 -O1`, `Trace.Phase.Decode` adds `--model-type=transformer --internal-hlo2tensorizer-options=--modular-flow-mac-threshold=10 -O2`, and `Trace.Phase.Any`, the default, adds nothing. A flag that `NEURON_CC_FLAGS` already sets (a `-O` level, a `--model-type`, an `--internal-hlo2tensorizer-options`) is not added again. `transformers` compiles a prompt as `Prompt` and every step over a cache as `Decode`. To set a phase's flags yourself, which replaces them whole:

```sh
export AGENTICA_ML_NEURON_PROMPT_FLAGS="--auto-cast matmult --model-type=transformer -O1"
export AGENTICA_ML_NEURON_DECODE_FLAGS="--auto-cast matmult --model-type=transformer -O2"
```

Every program, overrides included, also gets `--hbm-scratchpad-page-size=N` when `NEURON_SCRATCHPAD_PAGE_SIZE` is `N` MB, because the runtime runs every program with the page it opened with (512 MB by default). An aliased buffer larger than the page, such as a layer's KV cache that a step writes in place, is copied instead. `Qwen3.open` (and `Qwen3.load`) on a NeuronCore asks for a page that holds one sequence's keys of a layer at every position (`Tensor.xla_scratchpad(bytes)`): before the plugin opens it sets the variable when the default is too small, and after, it fails with the value to set. A value you set wins. A paged pool or a batch of rows holds more than one sequence and is not counted. The new flags change the key of every prompt and decode program in Neuron's compile cache, so the first run after them compiles cold.

The flags are built from `NEURON_CC_FLAGS` as it was when the XLA plugin opened; changing it later in the process is not supported. The same function with other flags is another program, compiled once more. Neuron's compile cache keys a program by a hash of its flags as well. That the plugin reads the flags at each compile, and the speed of each set, are not checked on inf2 yet ([ml#490](https://github.com/agentica-lang/ml/issues/490)).

## Check it

From the `tensor` and `train` folders of the ml repository, with the variables set:

```sh
cd tensor
TENSOR_REQUIRE_XLA=1 timeout 1800 agentica test --max-steps 10000000 \
  test/xla_test.agc test/xla_ops_test.agc test/xla_half_test.agc test/xla_bf16_test.agc \
  test/xla_missing_test.agc test/xla_plugin_test.agc test/from_file_test.agc
cd ../train
TENSOR_REQUIRE_XLA=1 timeout 1800 agentica test --max-steps 10000000 \
  test/fit_test.agc test/schedule_test.agc test/adamw_test.agc test/loop_test.agc \
  test/resume_test.agc test/checkpoint_test.agc
```

`TENSOR_REQUIRE_XLA=1` makes a missing plugin a failure, not a pass. Every test passes. One check is skipped on a NeuronCore and counted as passed, because `agentica test` has no skip status for tests yet ([agentica#2060](https://github.com/agentica-lang/agentica/issues/2060)): the training step of a hundred parameters in `fit_test` compiles in about 35 s, past the 30 s a test gets ([agentica#2057](https://github.com/agentica-lang/agentica/issues/2057)).

## How the program differs on Neuron

The lowering keeps the answers of the CPU on a NeuronCore, where its compiler would change them:

- A half weight (`F16` or `BF16`) that is an operand of a product (`matmul`, `linear`, `batch_matmul`, `expert_matmul`, `attention`), or the input of `to_dtype` to `F32`, is widened to `F32` by its bits. A `convert` there would be folded by the compiler into a product in half precision (about 1e-3 off). The rows of a lookup keep the `convert`. The widening costs time on each run, which is not measured yet ([ml#390](https://github.com/agentica-lang/ml/issues/390)). Under `--auto-cast` other than `none` the products are bf16 anyway, so the program keeps the plain `convert`.
- `top_ids` is XLA's `TopK` (`chlo.top_k`), not a sort, which this compiler does not build.
- `to_dtype` from a float to an integer truncates toward zero first, as on the CPU, where a NeuronCore's conversion rounds.
- The indices of `scatter_add` and `set_rows` are clamped into the rows, so an index outside them is the usual error and not a fault of the device.

## Generation

`transformers` generates on `Backend.Xla(Tensor.xla_device())`, batched rows included (`Generate.step_batch`). From the `transformers` folder, with the variables set:

```sh
TENSOR_REQUIRE_XLA=1 timeout 2400 agentica test --max-steps 200000000 \
  test/generate_batch_test.agc test/serving_test.agc test/paged_test.agc
TENSOR_REQUIRE_XLA=1 timeout 2400 agentica test --max-steps 200000000 --only xla test/generate_test.agc
```

`tools/bench_qwen.agc DIR xla` times Qwen3 decoding; `BATCH=n` decodes `n` rows at once. On an `inf2.8xlarge` core, with Qwen3-0.6B, `WEIGHTS=bf16`, `NEURON_CC_FLAGS="--auto-cast matmult"`, a 128-token prompt and 64 new tokens, decoding gave 110, 144 and 197 tokens per second for 1, 2 and 4 rows. The first run of each shape compiles for minutes, so on a fresh cache a test can fail with `RUNTIME-TEST-TIMEOUT`; run it again once the cache has the programs.

Speculative decoding (`Generate.generate_speculative`: drafts from the prompt and the answer so far, checked in one step of the model) gives the ids of greedy decoding. `tools/speculative_check.agc DIR xla` checks that on a Qwen3 checkpoint and prints how many drafts were accepted and the speed of both. On the CPU plugin with Qwen3-0.6B and 16 new tokens the ids match greedy. The NeuronCore run, with its acceptance and speed, is pending ([ml#478](https://github.com/agentica-lang/ml/issues/478)).

## Speed

On an `inf2.xlarge`, from the first measurements (milliseconds, the median of a run, batch 64 / 256 / 1024):

| | NeuronCore | XLA on the CPU |
|---|---|---|
| MLP 784-512-512-10, forward | 0.28 / 0.33 / 0.41 | 0.59 / 1.75 / 6.47 |
| a training step of that MLP with Adam, F32 | 0.99 / 1.10 / 1.42 | 2.99 / 6.26 / 18.73 |
| the same step, bf16 products | 0.86 / 0.88 / 0.93 | |

A run costs about 0.2 ms more on a NeuronCore than on the CPU, so small programs are faster on the CPU and the NeuronCore wins as batches grow.
