# Hello NPU

This is the smallest complete NPU program: a buffer copied from host memory through a memory tile and back, with no compute kernel. Compiling and running it exercises the whole chain, from IRON Python through the MLIR-AIE compiler to an NPU binary dispatched by HRX. CI compiles and runs this exact file on an NPU.

## Run it

Install the SDK ([Install](<https://rocm.github.io/FastFlow-SDK/install/index.md>)), then download and run the program:

```
curl -fsSLO https://rocm.github.io/FastFlow-SDK/examples/hello_npu.py
python hello_npu.py
# PASS: 4096 int32 elements copied through the NPU
```

`python hello_npu.py --build-only` compiles without an NPU and prints the paths of the generated `xclbin` and instruction stream.

Importing `aie` with the SDK installed selects the HRX runtime, so you do not need XRT. Values you set yourself for `NPU_RUNTIME` or `HRX_LIBHRX` take precedence.

## The program

```
#!/usr/bin/env python3
# Copyright Advanced Micro Devices, Inc.
# SPDX-License-Identifier: MIT
"""Hello NPU: compile the smallest complete IRON design and run it on the NPU.

The design is a pure-DMA memcpy, DDR -> MemTile -> DDR, with no compute
kernel, so it covers the whole chain: IRON -> MLIR -> aiecc -> bootgen ->
xclbin -> HRX -> NPU.

    python hello_npu.py               # compile and run (needs an NPU)
    python hello_npu.py --build-only  # compile only

CI runs it with `python dev.py test-npu-jit [--build-only]`.

For the programming abstractions (ObjectFifo, Worker, tiling, C++ kernels) and
many more designs, see the iron-tools/MLIR-AIE programming guide
<https://xilinx.github.io/mlir-aie/dev/> and programming examples
<https://github.com/Xilinx/mlir-aie/tree/main/programming_examples>.
"""

import argparse
import sys
from pathlib import Path

import aie.iron as iron
import numpy as np
from aie.iron import CompileTime, In, ObjectFifo, Out, Program, Runtime
from aie.iron.device import NPU2, AnyShimTile

LINE = 1024
SIZE = 4096


@iron.jit
def memcpy_passthrough(src: In, dst: Out, *, n: CompileTime[int]):
    line_ty = np.ndarray[(LINE,), np.dtype[np.int32]]
    vec_ty = np.ndarray[(n,), np.dtype[np.int32]]

    of_in = ObjectFifo(line_ty, name="in")
    of_out = of_in.cons().forward()

    def sequence(a_in, c_out, in_handle, out_handle):
        in_handle.fill(a_in)
        out_handle.drain(c_out, wait=True)

    rt = Runtime(
        sequence,
        [
            vec_ty,
            vec_ty,
            of_in.prod(tile=AnyShimTile),
            of_out.cons(tile=AnyShimTile),
        ],
    )

    return Program(NPU2(), rt).resolve_program()


def build_only(size: int) -> int:
    xclbin, insts = memcpy_passthrough.specialize(n=size).compile()
    for label, path in (("xclbin", xclbin), ("insts", insts)):
        if path is None or not Path(path).is_file() or Path(path).stat().st_size == 0:
            print(f"FAIL: compiler produced no usable {label} ({path})")
            return 1
    print(f"PASS: compiled a {size} int32 memcpy design")
    print(f"  xclbin: {xclbin} ({Path(xclbin).stat().st_size} bytes)")
    print(f"  insts:  {insts} ({Path(insts).stat().st_size} bytes)")
    return 0


def build_and_run(size: int) -> int:
    src = iron.arange(1, size + 1, dtype=np.int32, device="npu")
    dst = iron.zeros_like(src)

    memcpy_passthrough(src, dst, n=size)

    if np.array_equal(dst.numpy(), src.numpy()):
        print(f"PASS: {size} int32 elements copied through the NPU")
        return 0

    differing = int(np.count_nonzero(dst.numpy() != src.numpy()))
    print(f"FAIL: {differing}/{size} elements differ")
    return 1


def main() -> int:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument(
        "--build-only",
        action="store_true",
        help="compile the design but do not dispatch it (no NPU required)",
    )
    parser.add_argument(
        "-n", "--size", type=int, default=SIZE, help=f"elements (default: {SIZE})"
    )
    options = parser.parse_args()
    if options.size <= 0 or options.size % LINE:
        parser.error(f"--size must be a positive multiple of {LINE}")
    if options.build_only:
        return build_only(options.size)
    return build_and_run(options.size)


if __name__ == "__main__":
    sys.exit(main())
```

- `@iron.jit` compiles the function the first time it is called with a new compile-time value (`n`) and caches the result.
- An `ObjectFifo` moves data between tiles; `.forward()` routes it through a memory tile.
- The `Runtime` sequence fills the input from host memory and drains the output back.
- `Program(NPU2(), rt)` targets the XDNA2 NPU and lets the placer choose shim tiles (`AnyShimTile`).
- `iron.arange(..., device="npu")` and `iron.zeros_like` allocate buffers the NPU can read and write.

## Next steps

- Add compute: the [MLIR-AIE programming guide](<https://xilinx.github.io/mlir-aie/dev/>) introduces workers, kernels, and tiling. The [programming examples](<https://github.com/Xilinx/mlir-aie/tree/main/programming_examples>) go from `passthrough_kernel` to matrix multiplication. They assume an MLIR-AIE checkout with Makefiles and XRT; with the SDK you already have the toolchain and runtime, so read the IRON design code and skip their setup.
- Use tuned operators instead of writing kernels: the [IRON operators](<https://rocm.github.io/FastFlow-SDK/reference/operators/index.md#run-an-operator>) cover GEMM, attention, normalization, activations, and more, and one runs on the NPU in a dozen lines.
- Put your kernels in a real model: [Replace Gemma 4 GEMM and dequant with IRON](<https://rocm.github.io/FastFlow-SDK/examples/iron-gemma4-gemm-dequant/index.md>).

## Limitations

- The `@iron.jit` path this example uses runs an `xclbin` and an instruction stream, so its sequences cannot use `load_pdi` or `ScratchpadParameter`: that path carries no standalone PDIs, their relocations, or scratchpad metadata. An `iron.Graph` compiled to a [full ELF](<https://rocm.github.io/FastFlow-SDK/glossary/index.md>) carries them. Running one needs NPU firmware 1.0.20.31 or later on Linux. On Windows it needs NPU driver 32.0.20101.3760 or later, or 32.0.203.376 or later on the 32.0.203 line; 32.0.203.329 and older refuse it. `fastflow probe` reports both versions.
- NPU preemption is not supported on the HRX path.
