Skip to content

[NKI 0.7.0] Tracing is not thread-safe: concurrent @nki.jit traces fail ("No active NKI context") because the tracer context is a module global #1453

Done

Description

@scttfrdmn

Environment: trn2.3xlarge, Neuron SDK 2.33.0, nki 0.7.0+37713544100.gfede04bb, neuronx-cc 2.28.7631.0, Python 3.12.3. The repro is CPU-only: no device and no torch.

Summary. Tracing two or more distinct @nki.jit kernels at the same time from different Python threads fails nondeterministically per thread, and deterministically per run. The errors are No active NKI context, No backend set, or an MLIR Location error. Running the same traces one after another always passes.

Cause: nki/_backends/mlir_tracer/context.py keeps the active tracer context in a module global, set and cleared by every trace:

21:_current_context: "MLIRTracerContext | None" = None
38:def set_current_context(ctx: "MLIRTracerContext | None") -> None:
40:    global _current_context
41:    _current_context = ctx

So concurrent traces overwrite or clear each other's context.

Why it matters: the same tracer runs on the first call of a torch_neuronx.nki_op kernel, so multi-threaded drivers must serialise every first call per kernel and shape. For example, a host thread per NeuronCore driving kernels on neuron:0..3 has to do this. We do exactly that in trnsci/trnsolver#54 and trnsci/trnfft#96.

Repro (save as nki_trace_threads.py, run python nki_trace_threads.py --threads 4, and again with --serial):

import argparse, sys, threading, traceback
import numpy as np
import nki, nki.isa as nisa, nki.language as nl
from nki.compiler.frontend import FrontendKind, source_to_mlir
P = 128

def make_kernel(i):
    c = float(i + 1)
    @nki.jit
    def kernel(x):
        n = x.shape[1]
        out = nl.ndarray((P, n), dtype=nl.float32, buffer=nl.shared_hbm)
        t = nl.ndarray((P, n), dtype=nl.float32, buffer=nl.sbuf)
        nisa.dma_copy(dst=t, src=x)
        for _ in range(64):
            nisa.tensor_scalar(t, t, op0=nl.multiply, operand0=c, op1=nl.add, operand1=c)
        nisa.dma_copy(dst=out, src=t)
        return out
    return kernel

ap = argparse.ArgumentParser(); ap.add_argument("--threads", type=int, default=4); ap.add_argument("--serial", action="store_true")
a = ap.parse_args(); N = a.threads
ks = [make_kernel(i) for i in range(N)]; x = np.zeros((P, 16), np.float32)
errors = [None] * N; barrier = threading.Barrier(N)

def work(i):
    try:
        if not a.serial: barrier.wait()
        source_to_mlir(ks[i], x, target="trn2", frontend=FrontendKind.TRACER).verify()
    except BaseException as e:
        errors[i] = "".join(traceback.format_exception_only(e)).strip()

if a.serial:
    for i in range(N): work(i)
else:
    th = [threading.Thread(target=work, args=(i,)) for i in range(N)]
    [t.start() for t in th]; [t.join() for t in th]
bad = [i for i in range(N) if errors[i]]
for i in bad: print(f"--- thread {i}: {errors[i].splitlines()[0][:300]}")
print(f"RESULT {'FAIL' if bad else 'PASS'} {len(bad)}/{N} threads failed ({'serial' if a.serial else 'concurrent'})")

Observed (verbatim, consecutive runs):

$ python nki_trace_threads.py --threads 4      # x3
RESULT FAIL 3/4 threads failed (concurrent)
RESULT FAIL 4/4 threads failed (concurrent)
RESULT FAIL 3/4 threads failed (concurrent)
$ python nki_trace_threads.py --threads 2
--- thread 1: RuntimeError: No active NKI context. Are you inside a traced kernel or interpret_kernel?
RESULT FAIL 1/2 threads failed (concurrent)
$ python nki_trace_threads.py --threads 4 --serial   # x3
RESULT PASS 0/4 threads failed (serial)

Other runs also failed with RuntimeError: No backend set. Call _activate_backend() before using nki.isa operations. and An MLIR function requires a Location but none was provided....

Expected: concurrent traces of independent kernels succeed. Make the tracer context (and the active backend and MLIR location) thread-local, as the simulator's context already appears to be, or document that NKI tracing must be serialised process-wide.

Activity

  1. github-actions commented on Nov 1, 2026

    @github-actions

    Hi @scttfrdmn, Thank you for filing the issue! We will take a look and get back to you.

  2. added
    bug
    on Nov 1, 2026
  3. aws-petrosdebesay commented on Nov 5, 2026

    @aws-petrosdebesay
    Contributor

    Thank you for raising this issue. We have identified the fix and will update this issue once the fix is available.

  4. romagros-aws commented on Nov 30, 2026

    @romagros-aws
    Contributor

    Hi @scttfrdmn - We released NKI 0.8.0 as part of the Neuron SDK 2.34 today, which should fix that particular issue.

    Closing the ticket, feel free to re-open if you still encounter the issue with the latest SDK.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Trn2buginference

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions