Compile, Execute, and Profile NEFF Executables

A NEFF (Neuron Executable File Format) binary is the compiled executable run on AWS Trainium and Inferentia. This guide summarizes the full workflow: compiling NEFFs from PyTorch or NKI/NKIPy, executing them standalone with spike, and profiling traces with neuron-explorer.

flowchart LR
    PT["PyTorch (torch.nn.Module)"] -->|"torch_neuronx.trace"| NEFF[".neff"]
    NKI["NKI / NKIPy kernel"] -->|"extract HLO"| HLO[".hlo_module.pb"]
    HLO -->|"neuronx-cc"| NEFF
    NEFF --> Spike["spike (run)"]
    NEFF --> Prof["neuron-explorer (profile)"]

1. Compile from PyTorch (torch_neuronx.trace)

torch_neuronx.trace compiles a PyTorch callable given concrete example inputs, with three key constraints:

  1. Inputs/outputs must be tensors or nested lists/dicts/tuples of tensors (bake scalars like int or bool into a torch.nn.Module).
  2. Input shapes and dtypes must be concrete at trace time.
  3. The .neff artifact is written into compiler_workdir.

Example compiling a RoPE forward pass:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import torch
import torch_neuronx


def _apply_rotary_emb(x, cos, sin, is_neox_style):
cos = cos.unsqueeze(-2).to(x.dtype)
sin = sin.unsqueeze(-2).to(x.dtype)
if is_neox_style:
x1, x2 = torch.chunk(x, 2, dim=-1)
else:
x1, x2 = x[..., ::2], x[..., 1::2]
o1 = x1 * cos - x2 * sin
o2 = x2 * cos + x1 * sin
if is_neox_style:
return torch.cat((o1, o2), dim=-1)
return torch.stack((o1, o2), dim=-1).flatten(-2)


def _rotate_tensor(t, cos, sin, num_tokens, head_size, rotary_dim, is_neox_style):
orig_shape = t.shape
t = t.view(num_tokens, -1, head_size)
t_rot = _apply_rotary_emb(t[..., :rotary_dim], cos, sin, is_neox_style)
return torch.cat((t_rot, t[..., rotary_dim:]), dim=-1).reshape(orig_shape)


def rope_forward(positions, query, key=None, cos_sin_cache=None, head_size=None, rotary_dim=None, is_neox_style=True):
positions = positions.flatten()
cos, sin = cos_sin_cache.index_select(0, positions).chunk(2, dim=-1)
query = _rotate_tensor(query, cos, sin, positions.shape[0], head_size, rotary_dim, is_neox_style)
if key is not None:
key = _rotate_tensor(key, cos, sin, positions.shape[0], head_size, rotary_dim, is_neox_style)
return query, key


def _build_cos_sin_cache(rotary_dim, max_pos, base):
inv_freq = 1.0 / (base ** (torch.arange(0, rotary_dim, 2, dtype=torch.float) / rotary_dim))
freqs = torch.einsum("i,j->ij", torch.arange(max_pos, dtype=torch.float), inv_freq)
return torch.cat((freqs.cos(), freqs.sin()), dim=-1)


class Wrapper(torch.nn.Module):
def __init__(self, head_size, rotary_dim, is_neox_style=True):
super().__init__()
self.head_size = head_size
self.rotary_dim = rotary_dim
self.is_neox_style = is_neox_style

def forward(self, positions, query, key=None, cos_sin_cache=None):
return rope_forward(positions, query, key, cos_sin_cache, self.head_size, self.rotary_dim, self.is_neox_style)


torch.manual_seed(0)
head_size, rotary_dim, num_heads_q, num_heads_k = 64, 64, 32, 8
max_pos, base = 128, 500000.0
positions = torch.randint(0, max_pos, (1,))
cache = _build_cos_sin_cache(rotary_dim, max_pos, base)
q = torch.randn(1, num_heads_q * head_size)
k = torch.randn(1, num_heads_k * head_size)

traced = torch_neuronx.trace(
Wrapper(head_size, rotary_dim, is_neox_style=True),
(positions, q, k, cache),
compiler_args="--lnc=2",
compiler_workdir="./compiler_workdir",
)

--lnc=2 targets two NeuronCores; the compiled NEFF is written under ./compiler_workdir/, and traced can also be called directly in-process.

2. Compile from NKI or NKIPy Kernels

Extract HLO from an NKI kernel (matmul.py)

Write a kernel wrapped with PyTorchXLAKernel and trigger compilation with xm.mark_step():

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import nki.language as nl
import nki.isa as nisa
import torch
from torch_xla.core import xla_model as xm
from nki._torch_xla import PyTorchXLAKernel


def matmul(lhsT, rhs):
lhs_K, lhs_M = lhsT.shape
rhs_K, rhs_N = rhs.shape
lhs_dtype, rhs_dtype = lhsT.dtype, rhs.dtype
TILE_K = nl.tile_size.pmax
TILE_M = nl.tile_size.gemm_stationary_fmax
TILE_N = nl.tile_size.gemm_moving_fmax

result = nl.ndarray((lhs_M, rhs_N), dtype=lhs_dtype, buffer=nl.shared_hbm)
for m in nl.affine_range(lhs_M // TILE_M):
for n in nl.affine_range(rhs_N // TILE_N):
result_tile_psum = nl.ndarray((TILE_M, TILE_N), dtype=nl.float32, buffer=nl.psum)
for k in nl.affine_range(lhs_K // TILE_K):
lhsT_tile = nl.ndarray((TILE_K, TILE_M), dtype=lhs_dtype, buffer=nl.sbuf)
nisa.dma_copy(dst=lhsT_tile, src=lhsT[k * TILE_K : (k + 1) * TILE_K, m * TILE_M : (m + 1) * TILE_M])
rhs_tile = nl.ndarray((TILE_K, TILE_N), dtype=rhs_dtype, buffer=nl.sbuf)
nisa.dma_copy(dst=rhs_tile, src=rhs[k * TILE_K : (k + 1) * TILE_K, n * TILE_N : (n + 1) * TILE_N])
nisa.nc_matmul(dst=result_tile_psum, stationary=lhsT_tile, moving=rhs_tile)
result_tile = nl.ndarray((TILE_M, TILE_N), dtype=lhs_dtype, buffer=nl.sbuf)
nisa.tensor_copy(dst=result_tile, src=result_tile_psum, dtype=lhs_dtype)
nisa.dma_copy(dst=result[m * TILE_M : (m + 1) * TILE_M, n * TILE_N : (n + 1) * TILE_N], src=result_tile)
return result


if __name__ == '__main__':
kernel = PyTorchXLAKernel(func=matmul)
device = xm.xla_device()
c = kernel(torch.randn((2048, 2048), device=device), torch.randn((2048, 2048), device=device))
xm.mark_step()

Dump model.hlo_module.pb without executing on hardware (NEURON_EXTRACT_GRAPHS_ONLY=1):

1
2
3
4
5
6
7
8
9
extract_hlo_module() {
file="$1"; cache_dir="$2"; platform="$3" # platform: trn1, trn2, trn3
[ -f "$file" ] || { echo "ERROR: file not found: $file" >&2; return 1; }
script="$(cd "$(dirname "$file")" && pwd)/$(basename "$file")"
NEURON_PLATFORM_TARGET_OVERRIDE="$platform" \
NEURON_EXTRACT_GRAPHS_ONLY=1 \
NEURON_COMPILE_CACHE_URL="$cache_dir" \
python3 "$script"
}

The kernel module is typically the largest MODULE_*/model.hlo_module.pb in cache_dir.

Extract HLO with nkipy

For nkipy, trace and serialize directly:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import numpy as np
from nkipy.core.trace import NKIPyKernel


def matmul(A, B):
return A.T @ B


traced = NKIPyKernel.trace(matmul)
A = ((np.random.rand(2048, 2048) - 0.5) * 2).astype(np.float32)
B = ((np.random.rand(2048, 2048) - 0.5) * 2).astype(np.float32)
traced.specialize(A, B)
with open('nkipy_matmul.pb', 'wb') as f:
f.write(traced._code.to_proto().SerializeToString())

Compile HLO to NEFF (neuronx-cc)

1
neuronx-cc compile --framework XLA --target trn1 <input.hlo_module.pb> -o <output.neff>
Flag Description
--framework XLA Required. Input is an XLA HLO module
--target trn1|trn2|trn3 Target Neuron instance family
-o <file> Output NEFF path
--optlevel 1|2|3 Optimization level (default 2)
--enable-fast-loading-neuron-binaries Uncompressed NEFF for faster load time
--auto-cast matmult|all Auto-cast FP32 to lower precision
--auto-cast-type fp16|bf16|tf32 Auto-cast target dtype (default bf16)
--logical-nc-config 1|2 NeuronCores per logical core (trn2 only)

3. Execute a Pre-Compiled NEFF with spike

spike loads and executes .neff binaries on Neuron devices without invoking the compiler (regardless of whether the NEFF came from torch_neuronx.trace or neuronx-cc):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import torch
from spike import SpikeModel, SpikeTensor

model = SpikeModel.load_from_neff('model.hlo_module.neff', 'matmul')
print(model.input_tensors_info, model.output_tensors_info) # Inspect expected names, shapes, dtypes

A = torch.rand(2048, 2048)
B = torch.rand(2048, 2048)
outputs = model(inputs={
'input1': SpikeTensor.from_numpy(A.numpy(), name='input1'),
'input0': SpikeTensor.from_numpy(B.numpy(), name='input0'),
})
result = torch.from_numpy(outputs['output0'].numpy())
assert torch.allclose(A.T @ B, result, atol=1e-3)

SpikeTensor names must match the keys reported in model.input_tensors_info.

4. Profile with neuron-explorer

Capture an NTFF trace

1
2
3
4
5
neuron-explorer capture \
-n <neff file> \
-s <ntff file> \
--profile-nth-exec=2 \
--enable-dge-notifs
  • --profile-nth-exec=2: skips the first execution so cold warmup effects do not skew the trace.
  • --enable-dge-notifs: captures DGE DMA events, but can overflow the status notification queue and time out if a NEFF issues many DGE instructions.

View the trace in the web UI

1
neuron-explorer view --data-path <workspace directory>

This starts a web UI on port 3001 (http://localhost:3001/) and an API server on port 3002. On a headless remote host, either:

  1. Port forward ports 3001 and 3002 over SSH (with local copies of the NEFF and NTFF files), or
  2. Use a VNC remote desktop (Setting Up a VNC Server for Remote Desktop Access § Headless VNC Setup Guide) and open http://localhost:3001/ in a browser inside the session.

References


Compile, Execute, and Profile NEFF Executables
https://jifengwu2k.github.io/2026/07/19/Compile-Execute-and-Profile-NEFF-Executables/
Author
Jifeng Wu
Posted on
July 19, 2026
Licensed under