device/neural_network.rs
1//! Neural network device class control commands and protocol definitions.
2//!
3//! Neural network devices are registered under class prefix [`crate::kind::NEURAL_NETWORK`] (`b'N'`).
4//!
5//! # Protocol Overview
6//!
7//! Applications interact with neural network character devices using standard VFS
8//! operations ([`file_system::BaseOperations`]):
9//!
10//! - **Fixed-model devices** (`NeuralNetworkDevice`):
11//! A platform mounts a fixed model at a designated path (e.g. `/devices/nn/digit_classifier`).
12//! 1. Query tensor counts and shapes using [`GET_INPUT_COUNT`], [`GET_INPUT_INFO`],
13//! [`GET_OUTPUT_COUNT`], and [`GET_OUTPUT_INFO`].
14//! 2. Select the input tensor index using [`SET_INPUT_INDEX`]. Seek the file descriptor to 0
15//! and write the tensor bytes sequentially with `write()`.
16//! 3. Execute inference by issuing the [`COMPUTE`] command.
17//! 4. Select the output tensor index using [`SET_OUTPUT_INDEX`]. Seek the file descriptor to 0
18//! and read the result bytes with `read()`.
19//! 5. Closing the file descriptor releases the per-open execution arena.
20//!
21//! - **Runtime model loader devices** (`LoaderDevice`):
22//! A platform mounts a loader node (e.g. `/devices/nn/cpu`).
23//! 1. Open the loader node. The descriptor starts in the *Staging* state.
24//! 2. Write the model binary bytes sequentially from offset 0 using `write()`.
25//! Writes beyond the loader's maximum model size are rejected with [`file_system::IoErrorKind::FileTooLarge`].
26//! Non-contiguous writes are rejected with [`file_system::IoErrorKind::InvalidArgument`].
27//! 3. Send the [`LOAD`] command with a [`LoadRequest`] payload (e.g. TensorFlow Lite format).
28//! Upon successful preparation, the descriptor transitions to the *Ready* state.
29//! 4. From this point forward, the descriptor behaves identically to a fixed-model device:
30//! input/output inspection, tensor staging via `write()`, [`COMPUTE`], and output retrieval
31//! via `read()`.
32//! 5. Attempting inference commands before [`LOAD`] returns [`file_system::IoErrorKind::InvalidState`].
33//! A second [`LOAD`] on a ready descriptor returns [`file_system::IoErrorKind::InvalidState`].
34//! 6. Closing the descriptor frees both the dynamically allocated model and its execution state.
35
36use file_system::{ControlCommand, define_command};
37
38define_command!(
39 GET_INPUT_COUNT,
40 Read,
41 crate::kind::NEURAL_NETWORK,
42 0x01,
43 (),
44 u32
45);
46define_command!(
47 GET_INPUT_INFO,
48 Read,
49 crate::kind::NEURAL_NETWORK,
50 0x02,
51 u32,
52 TensorInfo
53);
54define_command!(
55 SET_INPUT_INDEX,
56 Write,
57 crate::kind::NEURAL_NETWORK,
58 0x03,
59 u32,
60 ()
61);
62define_command!(
63 GET_OUTPUT_COUNT,
64 Read,
65 crate::kind::NEURAL_NETWORK,
66 0x04,
67 (),
68 u32
69);
70define_command!(
71 GET_OUTPUT_INFO,
72 Read,
73 crate::kind::NEURAL_NETWORK,
74 0x05,
75 u32,
76 TensorInfo
77);
78define_command!(
79 SET_OUTPUT_INDEX,
80 Write,
81 crate::kind::NEURAL_NETWORK,
82 0x06,
83 u32,
84 ()
85);
86define_command!(COMPUTE, Write, crate::kind::NEURAL_NETWORK, 0x07, (), ());
87define_command!(
88 GET_INPUT_QUANTIZATION,
89 Read,
90 crate::kind::NEURAL_NETWORK,
91 0x08,
92 QuantizationRequest,
93 QuantizationEntry
94);
95define_command!(
96 GET_OUTPUT_QUANTIZATION,
97 Read,
98 crate::kind::NEURAL_NETWORK,
99 0x09,
100 QuantizationRequest,
101 QuantizationEntry
102);
103define_command!(
104 LOAD,
105 Write,
106 crate::kind::NEURAL_NETWORK,
107 0x0A,
108 LoadRequest,
109 ()
110);
111
112/// Maximum rank in the version-one VFS tensor metadata layout.
113pub const MAX_TENSOR_RANK: usize = 6;
114
115file_system::plain_data! {
116 #[repr(C)]
117 /// Metadata returned by `GET_INPUT_INFO` and `GET_OUTPUT_INFO`.
118 ///
119 /// `data_type` uses the TensorFlow Lite tensor type value. `dimensions` contains
120 /// the first `rank` dimensions; `rank` cannot exceed `MAX_TENSOR_RANK`.
121 #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
122 pub struct TensorInfo {
123 pub data_type: u32,
124 pub rank: u32,
125 pub dimensions: [i32; MAX_TENSOR_RANK],
126 pub byte_len: u32,
127 /// `-1` when the tensor is not quantized.
128 pub quantization_axis: i32,
129 /// Number of quantization entries, zero when not quantized.
130 pub quantization_count: u32,
131 }
132}
133
134file_system::plain_data! {
135 #[repr(C)]
136 /// Selects a quantization entry for an input or output tensor.
137 #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
138 pub struct QuantizationRequest {
139 pub tensor_index: u32,
140 pub quantization_index: u32,
141 }
142}
143
144file_system::plain_data! {
145 #[repr(C)]
146 /// One scale/zero-point pair for a tensor quantization axis. Layout:
147 /// `scale` at offset 0, `reserved` at offset 4 (must be zero when read
148 /// back), `zero_point` at offset 8; 16 bytes, no padding.
149 #[derive(Clone, Copy, Debug, Default, PartialEq)]
150 pub struct QuantizationEntry {
151 pub scale: f32,
152 pub reserved: u32,
153 pub zero_point: i64,
154 }
155}
156
157file_system::plain_data! {
158 #[repr(C)]
159 /// Request payload for the [`LOAD`] control command.
160 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
161 pub struct LoadRequest {
162 /// Protocol version, must be [`LoadRequest::VERSION`] (`1`).
163 pub version: u32,
164 /// Model format encoding (`0` for TensorFlow Lite).
165 pub encoding: u32,
166 /// Reserved for future expansion; must be set to `[0, 0]`.
167 pub reserved: [u32; 2],
168 }
169}
170
171impl LoadRequest {
172 /// Current protocol version.
173 pub const VERSION: u32 = 1;
174 /// TensorFlow Lite flatbuffer encoding identifier.
175 pub const ENCODING_TENSORFLOW_LITE: u32 = 0;
176
177 /// Create a new version-1 load request with the specified model encoding.
178 pub const fn new(encoding: u32) -> Self {
179 Self {
180 version: Self::VERSION,
181 encoding,
182 reserved: [0; 2],
183 }
184 }
185
186 /// Create a new version-1 TensorFlow Lite load request.
187 pub const fn tensorflow_lite() -> Self {
188 Self::new(Self::ENCODING_TENSORFLOW_LITE)
189 }
190}
191
192impl Default for LoadRequest {
193 fn default() -> Self {
194 Self::tensorflow_lite()
195 }
196}
197
198#[cfg(test)]
199mod tests {
200 use super::*;
201
202 #[test]
203 fn quantization_entry_is_padding_free() {
204 assert_eq!(
205 core::mem::size_of::<QuantizationEntry>(),
206 core::mem::size_of::<f32>() + core::mem::size_of::<u32>() + core::mem::size_of::<i64>()
207 );
208 assert_eq!(core::mem::size_of::<QuantizationEntry>(), 16);
209 assert_eq!(core::mem::align_of::<QuantizationEntry>(), 8);
210 }
211}