virtio_accel_xdna/lib.rs
1//! AMD XDNA (Ryzen AI NPU) host backend for `virtio-accel`.
2//!
3//! This crate executes device-neutral TOSA 1.0 programs on an AMD XDNA2 NPU through the HRX
4//! runtime (`libhrx`), compiling admitted graphs with the pinned aiecc toolchain as a bounded
5//! subprocess. The design is recorded across the AMD XDNA wayfinder map (issue #78) and its
6//! decision tickets (#82 numerical tier, #83 crate layout, #84 compiler helper, #85 execution
7//! model), whose resolution records live on their respective ticket branches.
8//!
9//! By default the native modules (`ffi`, `native`) compile when the build script finds a complete
10//! amdxdna-native HRX prefix (`VIRTIO_ACCEL_HRX_DIR`/`HRX_DIR`, or the `VIRTIO_ACCEL_HRX_LIB_DIR`
11//! escape hatch) and sets the `va_xdna` cfg; `VIRTIO_ACCEL_XDNA` forces the probe on (`1`, failing
12//! loudly) or off (`0`). Hosts without HRX build the portable admission surface (`lower`), the
13//! artifact codec, the offline compiler driver (`compile_artifact`, unix), and a placeholder —
14//! and compile no `unsafe` at all. The opt-in `runtime-loading` feature enables the native
15//! adapter on Linux without SDK probing/linking, resolving the pinned ABI at runtime.
16//! `VIRTIO_ACCEL_XDNA=0` still forces the placeholder.
17//!
18//! **Scope today:** the full `Accelerator` lifecycle — the HRX device/stream owner, `hrx_buffer`
19//! primitives (persistent mapping, range flush/invalidate, release), and the serialized dispatch
20//! worker bridging `hrx_stream_dispatch`/`synchronize` to a latched nonblocking `poll_event`
21//! (execution-model spec, issue #85). `load_program` accepts the crate-local precompiled format
22//! ([`artifact`]) directly, and a TOSA artifact by admitting it and compiling it with the bounded
23//! aiecc helper subprocess (issue #84). The compilable TOSA subsets today are BF16 IDENTITY,
24//! BF16 → FP32 MATMUL, BF16 MAX_POOL2D, explicit FP8 → BF16 storage conversion, the fused
25//! FP8 → FP32 MATMUL that keeps that promotion on the compute core, exact INT8 IDENTITY,
26//! zero-point-aware INT8 → INT32 MATMUL, and exact INT32 → INT8 RESCALE.
27//! Admission (`lower`) unit-tests on every host.
28
29#![cfg_attr(not(va_xdna), forbid(unsafe_code))]
30
31pub mod artifact;
32#[path = "../experiments/bfp_experiment.rs"]
33pub mod bfp_experiment;
34mod lower;
35
36pub use artifact::{PrecompiledArtifact, XDNA_PRECOMPILED_FORMAT};
37pub use lower::{
38 AdmitError, CompilerSpec, Fp8Format, XDNA_TOSA_CAPABILITY, XDNA_TOSA_FP8_CAPABILITY,
39 XDNA_TOSA_FP8_TARGET, XDNA_TOSA_INTEGER_CAPABILITY, XDNA_TOSA_INTEGER_TARGET, XDNA_TOSA_TARGET,
40 admit,
41};
42
43use virtio_accel_tosa::{CapabilityDescriptor, TosaCapabilityProvider};
44
45#[cfg(va_xdna)]
46const TOSA_CAPABILITIES: &[CapabilityDescriptor] = &[
47 XDNA_TOSA_CAPABILITY,
48 XDNA_TOSA_FP8_CAPABILITY,
49 XDNA_TOSA_INTEGER_CAPABILITY,
50];
51#[cfg(not(va_xdna))]
52const TOSA_CAPABILITIES: &[CapabilityDescriptor] = &[];
53
54/// The HRX runtime publishes no finite upper bound for a loaded program's device residency.
55///
56/// Requiring the maximal charge keeps the provider promise truthful: a process cannot retain
57/// `u64::MAX` bytes for one program. Device integrations set their aggregate program-residency
58/// policy accordingly when admitting an XDNA program. Mirrors the OpenVINO backend, whose runtime
59/// has the same property.
60pub const REQUIRED_RESIDENT_BYTES: u64 = u64::MAX;
61
62/// `BackendError::External` domain tag for this backend's failures ("XDNA" in ASCII), covering
63/// both HRX runtime errors and compiler-helper failures.
64pub const XDNA_ERROR_DOMAIN: u32 = 0x5844_4e41;
65
66/// Failure to initialize an XDNA backend instance.
67#[derive(Clone, Copy, Debug, PartialEq, Eq)]
68pub enum InitError {
69 /// The crate was built without a detected HRX runtime (`libhrx`).
70 RuntimeUnavailable,
71 /// HRX initialized but enumerated no NPU device on this host.
72 DeviceUnavailable,
73 /// The HRX device or stream could not be initialized.
74 Initialization,
75}
76
77impl core::fmt::Display for InitError {
78 fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
79 write!(formatter, "{self:?}")
80 }
81}
82
83impl std::error::Error for InitError {}
84
85// The compiler-helper driver is pure safe subprocess code: it needs the pinned toolchain at run
86// time, never HRX, so it compiles on every unix host — the offline catalog-population host is
87// exactly a build machine *without* libhrx. (Unix-only: it drives the helper in its own process
88// group, a unix notion.)
89#[cfg(unix)]
90mod compiler;
91#[cfg(va_xdna)]
92mod ffi;
93#[cfg(va_xdna)]
94mod native;
95#[cfg(va_xdna)]
96pub use native::{
97 XdnaAccelerator, XdnaBuffer, XdnaContext, XdnaEvent, XdnaProgram, XdnaQueue, XdnaResourceCounts,
98};
99#[cfg(all(va_xdna, feature = "test-control"))]
100#[doc(hidden)]
101pub use native::{XdnaTestConfig, XdnaTestFault};
102
103/// Admit a TOSA artifact and compile it to a precompiled-artifact container ([`artifact`]) with
104/// the pinned toolchain, without touching the device.
105///
106/// This is the offline / catalog-population path (compiler-helper contract, issue #84): a build
107/// host produces artifacts that a device-less serving host later loads through the precompiled
108/// format. Requires the toolchain (`VIRTIO_ACCEL_AMDXDNA_TOOLCHAIN`) at run time and no HRX at
109/// all — it is available on any unix build, with or without the `va_xdna` native modules.
110#[cfg(unix)]
111pub fn compile_artifact(
112 tosa: &[u8],
113 target: virtio_accel_tosa::Target,
114) -> Result<Vec<u8>, virtio_accel_core::BackendError> {
115 let spec = lower::admit(tosa, target)?;
116 compiler::Compiler::from_env()?.compile(spec)
117}
118
119/// Placeholder that keeps workspace consumers portable when no HRX runtime was detected.
120#[cfg(not(va_xdna))]
121#[derive(Clone, Copy, Debug, Default)]
122pub struct XdnaAccelerator;
123
124#[cfg(not(va_xdna))]
125impl XdnaAccelerator {
126 /// Report that no HRX runtime was detected when this crate was built.
127 pub fn new() -> Result<Self, InitError> {
128 Err(InitError::RuntimeUnavailable)
129 }
130}
131
132impl TosaCapabilityProvider for XdnaAccelerator {
133 fn tosa_capabilities(&self) -> &'static [CapabilityDescriptor] {
134 TOSA_CAPABILITIES
135 }
136}