# Supporting new hardware

What it takes to add support for a new NPU or AI accelerator to the Open Inference Stack.


To add support for a new NPU, or another kind of AI accelerator, two driver
parts must be developed. If the hardware is not publicly documented, expect
reverse engineering to be part of the project.

Both parts are developed upstream, in Linux and Mesa, following those projects'
usual contribution process. See [Contribute](/contribute/) for where the code
lives, the developer guidelines, and where to find the developers.

## The kernel driver

The kernel side is intended to be small, and should not know anything about
neural networks. Its job is to safely make the hardware functions available to
userspace. It should:

- Probe the device, and handle clocks, power, resets and interrupts
- Allocate buffers for weights, activations and command streams, and map them
  for the NPU (perhaps through an IOMMU)
- Expose a small set of ioctls through a device node in `/dev/accel/`
- Schedule jobs (typically using `drm_sched`), and signal completion with fences
- Recover from hangs and timeouts

For more info, refer to the
[accel subsystem documentation](https://docs.kernel.org/accel/) and study the
`rocket` and `ethosu` drivers as examples.

## The Mesa driver

Most of the NPU driver work is in userspace, as a Gallium driver in Mesa.
Frontends such as Teflon and Torx turn a model into a list of operations and
Gallium then asks the driver to:

- Determine which operations (and which shapes and quantization schemes) it
  supports
- Compile a subgraph of supported operations for the NPU, which includes
  converting weights to the hardware's layout, splitting work into tiles that
  fit the on-chip memory, and generating the command stream
- Run the compiled subgraph and return the outputs

A Gallium ML driver must implement:

- A `struct pipe_ml_device` (defined in
  [`p_state.h`](https://gitlab.freedesktop.org/mesa/mesa/-/blob/main/src/gallium/include/pipe/p_state.h))
  that checks, compiles and saves subgraphs, so a model can be compiled ahead of
  time.
- ML context hooks (defined in
  [`p_context.h`](https://gitlab.freedesktop.org/mesa/mesa/-/blob/main/src/gallium/include/pipe/p_context.h))
  such as `ml_subgraph_invoke` that load a compiled subgraph and run it on the
  NPU.

The
[`ethosu`](https://gitlab.freedesktop.org/mesa/mesa/-/tree/main/src/gallium/drivers/ethosu)
and
[`rocket`](https://gitlab.freedesktop.org/mesa/mesa/-/tree/main/src/gallium/drivers/rocket)
drivers are good examples to study. Operations the driver does not support run
on the CPU instead, so a new driver can start with a few operations and grow
incrementally.


---
Source: http://model-citizen.ai/getting-started/new-hardware/
