Skip to content

NKI Backend

The NKI dispatch layer controls whether BLAS operations run on the native Trainium Tensor Engine or fall back to PyTorch.

Backend selection

import trnblas

trnblas.set_backend("auto")  # measured routing on Trainium, PyTorch elsewhere (default)
trnblas.set_backend("pytorch")  # force PyTorch fallback
trnblas.set_backend("nki")  # force NKI (requires nki>=0.3.0)

What auto does depends on the dispatch path (v0.9.0, #62, #63):

  • Native (TorchNeuron, Trn2/Trn3): gemm, batched_gemm, syrk, symm and left trsm are routed by measured time. Device-resident operands run as aten on the neuron device, except one region where the LNC-split GEMM kernel (#79) is faster: fp32 gemm with A a transposed view, 16 ≤ M ≤ 64, 128 ≤ K ≤ 512, N ≥ 256·K and K·N ≥ 2^24 (the DF-MP2 half-transform C_occ.T @ eri). Host operands run on the host CPU below a per-op size threshold and as one upload + aten + one download above it; host trsm solves with LAPACK on the host. For device-resident inputs, the DF-MP2 pair energy (nki_batched_pair_energy) runs the fused pair_energy_sym NKI kernel above 3 GFLOP per row launch (1.8× faster than aten on the energy step at 96/672/2304) and aten below it. TRNBLAS_NATIVE_GEMM overrides the GEMM route.
  • XLA (Trn1): the NKI kernels, as before.
  • No device: PyTorch.

set_backend("nki") always runs the NKI kernels, for device-resident operands too. float64 is cast to float32 for the kernels (see Precision and dtypes); other dtypes the kernels do not compute (integer, bool, complex) run in torch, or raise NotImplementedError under TRNBLAS_REQUIRE_NKI=1 (v0.9.1, #68).

Precision and dtypes

Trainium computes float64 at fp32 precision, so no NKI kernel gives float64 accuracy. trnblas follows the trnsci suite-wide policy (#89):

Mode float64 operands
set_backend("auto") Run in host torch at float64 accuracy. No kernel is called. float64 / complex128 operands already on the neuron device are copied to the host, computed there, and the result is returned on the device in float64 (one UserWarning per op; see below).
set_backend("nki") Cast to float32, run on the NKI kernel, result cast back. One UserWarning per op says precision is reduced to float32. Ops with no kernel (Level 1/2, symm, trmm) run in torch on the operands' device: host float64 keeps float64 accuracy with no warning, and float64 / complex128 on the neuron device runs on device aten at fp32 precision with the same once-per-op warning. Ops with a kernel give the same warning when device float64 / complex128 does not take the float32 cast (see below).
TRNBLAS_REQUIRE_NKI=1 NotImplementedError. Takes precedence over the nki cast. float64 / complex128 on the neuron device raise at every public op, including the routes with no kernel (see below).
set_backend("pytorch") torch, as always.
  • Device-resident float64. On Trainium, aten on the neuron device computes float64 at fp32 precision (measured on Trn2), so under auto a float64 or complex128 operand on the device does not run as device aten. Every public op (trnblas.* and trnblas.nki.*) copies the device-resident operands to the host, computes in host torch at float64, and returns the result on the original device in float64. One UserWarning per op says "float64 on the neuron device is computed on the host for float64 accuracy (device arithmetic is fp32); pass float32 to stay on device". The cost is the host-link round trip. To keep device aten (fp32 precision, no copies), set TRNBLAS_FP64_ON_DEVICE=1; to stay on the device at full speed, pass float32. Host-resident float64 is unchanged (host torch), and with this release a forced TRNBLAS_NATIVE_GEMM=aten|lnc no longer uploads host float64 to device aten unless TRNBLAS_FP64_ON_DEVICE=1 is set. set_backend("nki") and "pytorch" are not affected. Under TRNBLAS_REQUIRE_NKI=1 (backends auto and nki), a float64 / complex128 operand on the device raises NotImplementedError at every public op, with no host copy, ahead of TRNBLAS_FP64_ON_DEVICE; before, the routes with no kernel (auto GEMM-family device aten, symm, Level 1/2) computed it at fp32 precision with no error. The trnblas.parallel (multi-process) helpers are float32 pipelines and are not covered, except parallel.pair_energy (below).
  • Explicit nki, device float64 off the cast (#103). On an op with a kernel, float64 / complex128 on the neuron device takes the float32 kernel cast only when every operand is float64 and the call has a kernel route. The other calls run on device aten at fp32 precision, and the op emits one UserWarning ("... run on device aten; precision is reduced to float32"), sharing the dedup set of the cast warning (nki_gemm and gemm count as one op). That covers complex128 operands (gemm, batched_gemm, syrk, the energy APIs), float64 mixed with another dtype (a float64 C on a float32 gemm / syrk, mixed trsm operands, float64 amplitudes with integer or complex eps), shapes or sides with no kernel route (batched or 1-D gemm operands, a 1-D operand to nki_batched_gemm, side="right" trsm), the metric_inv_half device route (its Cholesky runs on device aten), and the nki_batched_pair_energy / parallel.pair_energy aten route. TRNBLAS_REQUIRE_NKI=1 raises for all of them, parallel.pair_energy included. No warning where the work stays on the host at full precision: left trsm on complex128 and the metric_inv_half host route. A mixed call that torch refuses (float64 @ float32) still raises, with no warning.
  • The GEMM / SYRK kernels take float32, bfloat16 and float16 (FP32 PSUM accumulation, output in the input dtype). The DF-MP2 energy kernels take float32; bfloat16 / float16 operands are upcast exactly.
  • The result dtype always matches the pytorch backend for the same inputs, including bfloat16/float16 and mixed-dtype promotion. For the energy APIs that is torch.promote_types of the operands: nki_mp2_energy over all four, nki_batched_pair_energy / nki_fused_gemm_energy over the amplitudes and eps_vir (the occupied energies enter as Python floats). The kernels still accumulate in FP32; only the returned scalar is cast.
  • float64 orbital energies count as float64 operands: under auto a call with float32 amplitudes and float64 eps runs in torch. Pass float32 eps to keep the energy step on the kernel.
  • A float64 operand mixed with another dtype (e.g. float64 @ float32) is not cast; it behaves as the pytorch backend does.
  • symm has no NKI kernel and always computes in torch, so float64 keeps float64 accuracy under every backend.
  • Integer, bool and complex operands never reach a kernel: they run in torch (or raise under TRNBLAS_REQUIRE_NKI=1). trnblas has no complex kernels, so complex128 is not cast to complex64.

trnblas.HAS_NKI is True when the nki package (NKI 0.3.0+, Neuron SDK 2.29+) is importable. trnblas uses the canonical nki.* namespace directly; the legacy neuronxcc.nki.* shim is not used.

Dispatch path

On Neuron hardware, kernels run on one of two torch-neuronx lineages, detected on the first kernel launch:

  • Native (TorchNeuron, Trn2/Trn3): each kernel is a PyTorch custom op on device="neuron", also callable directly and inside torch.compile(backend="neuron"): torch.ops.trnblas.gemm_ragged, gemm_<tm>_<tk>_<tn> (one per autotune tile config, default gemm_128_128_512), syrk, mp2_energy, fused_gemm_energy, batched_pair, j_batched. TRSM rides the GEMM ops. The ops are registered only once this path is selected.
  • XLA (Trn1): kernels run on the torch_xla device, as before.

On the native path, for host-resident inputs or with TRNBLAS_PAIR_ENERGY=legacy, nki_batched_pair_energy takes the single full-batch kernel (batched_pair) up to est_iters = nocc² × N_A² × N_K = 3072 and the chunked per-i kernel (j_batched) above it (XLA: 4096). On trn2 the full-batch kernel is 2–11× faster warm, but above 3072 its first-call compile reached 43–178 s, against 2–4 s for the chunked kernel. See Installation.

Environment variables

Variable Effect
TRNBLAS_REQUIRE_NKI=1 Re-raise kernel exceptions instead of falling back to torch.matmul — surfaces silent breakage in validation runs. Dtypes the kernels do not take (float64 included) raise NotImplementedError.
TRNBLAS_FP64_ON_DEVICE=1 Under auto, keep float64 / complex128 operands that are on the neuron device on device aten (fp32 precision) instead of computing them on the host at float64 accuracy. See Precision and dtypes.
TRNBLAS_USE_SIMULATOR=1 Route kernel dispatch through nki.simulate(kernel)(numpy_args) on CPU. Bypasses torch_xla + NEFF compile; used for fast correctness iteration. See docs/developing_kernels.md.
TRNSCI_NKI_DISPATCH=auto\|native\|xla Suite-wide. Forces the native or XLA dispatch path.
TRNBLAS_BATCHED_PAIR_CHUNK_THRESHOLD=<n> Overrides batched-pair routing (default 4096 on XLA, 3072 on native).
TRNBLAS_NATIVE_GEMM=auto\|nki\|aten\|host\|lnc Native path. Overrides the measured GEMM-family route; see Installation.

GEMM kernel

trnblas.nki.nki_gemm — NKI-dispatched GEMM with stationary tile reuse:

  • A tile (128×128) loaded once to SBUF, held stationary in the systolic array.
  • B tiles streamed through as the moving operand.
  • Partial products accumulated in PSUM.
  • HBM padding: M/K rounded to 128, N rounded to 512 (when N > 512); kernel uses TILE_N = min(N, 512) for single-tile small-N. Result is sliced back to the original (M, N).

Status: validated on trn1.2xlarge with neuronxcc 2.24. 17/17 hardware tests pass. Cached-NEFF speedup ~2.8× on warm runs; per-call kernel timings land at 1.6 ms (512³) and 4.5 ms (1024³) on warm cache.

Batched GEMM

trnblas.nki.nki_batched_gemm — per-slice dispatch through the cached 2D _gemm_kernel. Every slice after the first hits the NEFF cache (identical signature), so per-slice cost is HBM transfer + Tensor Engine dispatch only.

Fused MP2 energy-reduction kernel

trnblas.nki.nki_mp2_energy(T_flat, eps_occ_chunk, eps_occ_full, eps_vir) — computes

E_chunk = Σ_{i, j, a, b} T[i,j,a,b] * (2·T[i,j,a,b] - T[i,j,b,a]) / Δ[i,j,a,b]

where T[i,j,a,b] = T_flat[i*nvir + a, j*nvir + b] and Δ[i,j,a,b] = eps_occ[i] + eps_occ[j] - eps_vir[a] - eps_vir[b].

Partition-dim sub-tiling: P_TILE picked at trace time as the largest divisor of nvir that is ≤ 128 (the NKI partition limit). All three DF-MP2 bench shapes (nvir = 112 / 448 / 672) share P_TILE = 112, so one compiled kernel serves all.

Returns: (P_TILE, ic, nocc) fp32 tensor of per-partition partials; caller reduces host-side via .sum().

Status: on-hardware correctness validated across nvir ∈ {8, 16, 64, 256, 448} — all 5 tests pass on trn1 (under the NKI 0.3.0 MLIR verifier after the #15 M2 broadcast-fix commit c1769c6).

Measured perf (trn1.2xlarge, warm NEFF cache, SDK 2.29):

DF-MP2 shape Energy step — torch Energy step — fused Speedup
medium (nbasis=512, nocc=64, nvir=448) 8.03 s 5.43 s 1.48×
large (nbasis=768, nocc=96, nvir=672) 44.57 s 30.27 s 1.47×

Bit-parity with the torch reference at both shapes (atol=1e-4, rtol=1e-4). The fused kernel beats torch consistently but the speedup ratio is roughly shape-invariant — per-(i,j) dispatch cost scales with nocc² same as the torch path, so the RFC's 3–5× target isn't hit. The remaining perf work (larger free-dim tiles, atomic-add variant, multi-engine pipeline evidence) is tracked under #15. Production examples/df_mp2.py exposes the kernel via --fused-energy; default remains the torch path until a future milestone hits the 3× bar.