Skip to main content

drivers_neural_network/
device.rs

1use alloc::{boxed::Box, vec, vec::Vec};
2use core::task::Poll;
3
4use file_system::{
5    BaseOperations, CharacterDevice, Context, ControlCommand, ControlCommandIdentifier,
6    IoErrorKind, MountOperations, Result, Size,
7};
8use shared::AnyByLayout;
9
10use crate::{
11    Backend, COMPUTE, GET_INPUT_COUNT, GET_INPUT_INFO, GET_INPUT_QUANTIZATION, GET_OUTPUT_COUNT,
12    GET_OUTPUT_INFO, GET_OUTPUT_QUANTIZATION, LOAD, LoadRequest, Loader, ModelBuffer,
13    ModelEncoding, SET_INPUT_INDEX, SET_OUTPUT_INDEX, command::validate_command,
14};
15
16/// A portable VFS character device backed by a statically selected inference backend.
17///
18/// Contains its backend by value: constructing this adapter adds no allocation or vtable.
19pub struct NeuralNetworkDevice<B> {
20    pub(crate) backend: B,
21}
22
23impl<B: Backend> NeuralNetworkDevice<B> {
24    pub const fn new(backend: B) -> Self {
25        Self { backend }
26    }
27
28    fn state<'context>(&self, context: &'context Context) -> Result<&'context DeviceContext<B>> {
29        context
30            .get_private_data_of_type::<DeviceContext<B>>()
31            .filter(|state| self.backend.owns_execution(&state.execution))
32            .ok_or(IoErrorKind::BadDescriptor)
33    }
34
35    fn state_mut<'context>(
36        &self,
37        context: &'context mut Context,
38    ) -> Result<&'context mut DeviceContext<B>> {
39        context
40            .get_private_data_mutable_of_type::<DeviceContext<B>>()
41            .filter(|state| self.backend.owns_execution(&state.execution))
42            .ok_or(IoErrorKind::BadDescriptor)
43    }
44}
45
46/// A portable VFS character device providing runtime model loading.
47///
48/// A platform mounts an instance of `LoaderDevice` (for example at `/devices/nn/cpu`).
49/// Handles start in a staging state where model bytes are written sequentially. After
50/// a [`LOAD`] control command is issued, the handle transitions to ready state and
51/// behaves identically to a [`NeuralNetworkDevice`] handle.
52pub struct LoaderDevice<L> {
53    pub(crate) loader: L,
54}
55
56impl<L: Loader> LoaderDevice<L> {
57    pub const fn new(loader: L) -> Self {
58        Self { loader }
59    }
60
61    fn state<'context>(
62        &self,
63        context: &'context Context,
64    ) -> Result<&'context LoaderContext<L::Backend>> {
65        let loader_id = core::ptr::from_ref(self) as usize;
66        context
67            .get_private_data_of_type::<LoaderContext<L::Backend>>()
68            .filter(|state| match state {
69                LoaderContext::Staging { loader_id: id, .. } => *id == loader_id,
70                LoaderContext::Ready {
71                    backend,
72                    device_context,
73                    loader_id: id,
74                } => *id == loader_id && backend.owns_execution(&device_context.execution),
75            })
76            .ok_or(IoErrorKind::BadDescriptor)
77    }
78
79    fn state_mut<'context>(
80        &self,
81        context: &'context mut Context,
82    ) -> Result<&'context mut LoaderContext<L::Backend>> {
83        let loader_id = core::ptr::from_ref(self) as usize;
84        context
85            .get_private_data_mutable_of_type::<LoaderContext<L::Backend>>()
86            .filter(|state| match state {
87                LoaderContext::Staging { loader_id: id, .. } => *id == loader_id,
88                LoaderContext::Ready {
89                    backend,
90                    device_context,
91                    loader_id: id,
92                } => *id == loader_id && backend.owns_execution(&device_context.execution),
93            })
94            .ok_or(IoErrorKind::BadDescriptor)
95    }
96}
97
98pub(crate) struct DeviceContext<B: Backend> {
99    pub(crate) execution: B::Execution,
100    pub(crate) input_filled: Vec<usize>,
101    pub(crate) input_index: usize,
102    pub(crate) output_index: usize,
103    pub(crate) computed: bool,
104}
105
106enum LoaderContext<B: Backend> {
107    Staging {
108        bytes: ModelBuffer,
109        loader_id: usize,
110    },
111    Ready {
112        backend: B,
113        device_context: DeviceContext<B>,
114        loader_id: usize,
115    },
116}
117
118pub(crate) fn compute<B: Backend>(backend: &B, state: &mut DeviceContext<B>) -> Result<()> {
119    state.computed = false;
120    for (index, filled) in state.input_filled.iter().enumerate() {
121        if backend.input_info(index)?.byte_len as usize != *filled {
122            return Err(IoErrorKind::InvalidArgument);
123        }
124    }
125    // Arena planning can overwrite inputs even when a kernel returns an error.
126    state.input_filled.fill(0);
127    backend.compute(&mut state.execution)?;
128    state.computed = true;
129    Ok(())
130}
131
132pub(crate) fn handle_inference_read<B: Backend>(
133    backend: &B,
134    state: &DeviceContext<B>,
135    buffer: &mut [u8],
136    absolute_position: Size,
137) -> Result<usize> {
138    if !state.computed {
139        return Err(IoErrorKind::DeviceUnavailable);
140    }
141    let tensor = backend.output(&state.execution, state.output_index)?;
142    let output = tensor.as_ref();
143    let offset = usize::try_from(absolute_position).unwrap_or(usize::MAX);
144    if offset >= output.len() {
145        return Ok(0);
146    }
147    let count = buffer.len().min(output.len() - offset);
148    buffer[..count].copy_from_slice(&output[offset..offset + count]);
149    Ok(count)
150}
151
152pub(crate) fn handle_inference_write<B: Backend>(
153    backend: &B,
154    state: &mut DeviceContext<B>,
155    buffer: &[u8],
156    absolute_position: Size,
157) -> Result<usize> {
158    let index = state.input_index;
159    let filled = *state
160        .input_filled
161        .get(index)
162        .ok_or(IoErrorKind::InvalidArgument)?;
163    let offset = usize::try_from(absolute_position).unwrap_or(usize::MAX);
164    if offset > filled {
165        return Err(IoErrorKind::InvalidArgument);
166    }
167    let mut tensor = backend.input(&mut state.execution, index)?;
168    let input = tensor.as_mut();
169    if offset >= input.len() {
170        return if buffer.is_empty() {
171            Ok(0)
172        } else {
173            Err(IoErrorKind::FileTooLarge)
174        };
175    }
176    let count = buffer.len().min(input.len() - offset);
177    input[offset..offset + count].copy_from_slice(&buffer[..count]);
178    state.input_filled[index] = filled.max(offset + count);
179    state.computed = false;
180    Ok(count)
181}
182
183pub(crate) fn handle_inference_control<B: Backend>(
184    backend: &B,
185    state: &mut DeviceContext<B>,
186    command: ControlCommandIdentifier,
187    input: &AnyByLayout,
188    output: &mut AnyByLayout,
189) -> Result<()> {
190    match command {
191        GET_INPUT_COUNT::IDENTIFIER => {
192            validate_command::<GET_INPUT_COUNT>(input, output)?;
193            *GET_INPUT_COUNT::cast_output(output)? = backend.input_count() as u32;
194        }
195        GET_INPUT_INFO::IDENTIFIER => {
196            validate_command::<GET_INPUT_INFO>(input, output)?;
197            let index = *GET_INPUT_INFO::cast_input(input)? as usize;
198            *GET_INPUT_INFO::cast_output(output)? = backend.input_info(index)?;
199        }
200        SET_INPUT_INDEX::IDENTIFIER => {
201            validate_command::<SET_INPUT_INDEX>(input, output)?;
202            let index = *SET_INPUT_INDEX::cast_input(input)? as usize;
203            if index >= backend.input_count() {
204                return Err(IoErrorKind::InvalidArgument);
205            }
206            state.input_index = index;
207        }
208        GET_OUTPUT_COUNT::IDENTIFIER => {
209            validate_command::<GET_OUTPUT_COUNT>(input, output)?;
210            *GET_OUTPUT_COUNT::cast_output(output)? = backend.output_count() as u32;
211        }
212        GET_OUTPUT_INFO::IDENTIFIER => {
213            validate_command::<GET_OUTPUT_INFO>(input, output)?;
214            let index = *GET_OUTPUT_INFO::cast_input(input)? as usize;
215            *GET_OUTPUT_INFO::cast_output(output)? = backend.output_info(index)?;
216        }
217        SET_OUTPUT_INDEX::IDENTIFIER => {
218            validate_command::<SET_OUTPUT_INDEX>(input, output)?;
219            let index = *SET_OUTPUT_INDEX::cast_input(input)? as usize;
220            if index >= backend.output_count() {
221                return Err(IoErrorKind::InvalidArgument);
222            }
223            state.output_index = index;
224        }
225        GET_INPUT_QUANTIZATION::IDENTIFIER => {
226            validate_command::<GET_INPUT_QUANTIZATION>(input, output)?;
227            let request = *GET_INPUT_QUANTIZATION::cast_input(input)?;
228            *GET_INPUT_QUANTIZATION::cast_output(output)? = backend.input_quantization(
229                request.tensor_index as usize,
230                request.quantization_index as usize,
231            )?;
232        }
233        GET_OUTPUT_QUANTIZATION::IDENTIFIER => {
234            validate_command::<GET_OUTPUT_QUANTIZATION>(input, output)?;
235            let request = *GET_OUTPUT_QUANTIZATION::cast_input(input)?;
236            *GET_OUTPUT_QUANTIZATION::cast_output(output)? = backend.output_quantization(
237                request.tensor_index as usize,
238                request.quantization_index as usize,
239            )?;
240        }
241        COMPUTE::IDENTIFIER => {
242            validate_command::<COMPUTE>(input, output)?;
243            compute(backend, state)?;
244        }
245        _ => return Err(IoErrorKind::Unsupported),
246    }
247    Ok(())
248}
249
250impl<B: Backend> BaseOperations for NeuralNetworkDevice<B> {
251    fn open(&self, context: &mut Context) -> Result<()> {
252        if context.get_private_data().is_some() {
253            return Err(IoErrorKind::InvalidState);
254        }
255        let execution = self.backend.create_execution()?;
256        context.set_private_data(Box::new(DeviceContext::<B> {
257            execution,
258            input_filled: vec![0; self.backend.input_count()],
259            input_index: 0,
260            output_index: 0,
261            computed: false,
262        }));
263        Ok(())
264    }
265
266    fn close(&self, context: &mut Context) -> Result<()> {
267        self.state(context)?;
268        context
269            .take_private_data_of_type::<DeviceContext<B>>()
270            .map(drop)
271            .ok_or(IoErrorKind::BadDescriptor)
272    }
273
274    fn read(
275        &self,
276        context: &mut Context,
277        _cx: &mut core::task::Context<'_>,
278        buffer: &mut [u8],
279        absolute_position: Size,
280    ) -> Poll<Result<usize>> {
281        file_system::ready(|| {
282            let state = self.state(context)?;
283            handle_inference_read(&self.backend, state, buffer, absolute_position)
284        })
285    }
286
287    fn write(
288        &self,
289        context: &mut Context,
290        _cx: &mut core::task::Context<'_>,
291        buffer: &[u8],
292        absolute_position: Size,
293    ) -> Poll<Result<usize>> {
294        file_system::ready(|| {
295            let state = self.state_mut(context)?;
296            handle_inference_write(&self.backend, state, buffer, absolute_position)
297        })
298    }
299
300    fn control(
301        &self,
302        context: &mut Context,
303        _cx: &mut core::task::Context<'_>,
304        command: ControlCommandIdentifier,
305        input: &AnyByLayout,
306        output: &mut AnyByLayout,
307    ) -> Poll<Result<()>> {
308        file_system::ready(|| {
309            let state = self.state_mut(context)?;
310            handle_inference_control(&self.backend, state, command, input, output)
311        })
312    }
313
314    fn clone_context(&self, _context: &Context) -> Result<Context> {
315        Err(IoErrorKind::Unsupported)
316    }
317}
318
319impl<B: Backend> MountOperations for NeuralNetworkDevice<B> {
320    fn unmount(&self) -> Result<()> {
321        Ok(())
322    }
323}
324
325impl<B: Backend> CharacterDevice for NeuralNetworkDevice<B> {}
326
327impl<L: Loader> BaseOperations for LoaderDevice<L> {
328    fn open(&self, context: &mut Context) -> Result<()> {
329        if context.get_private_data().is_some() {
330            return Err(IoErrorKind::InvalidState);
331        }
332        context.set_private_data(Box::new(LoaderContext::<L::Backend>::Staging {
333            bytes: ModelBuffer::new(),
334            loader_id: core::ptr::from_ref(self) as usize,
335        }));
336        Ok(())
337    }
338
339    fn close(&self, context: &mut Context) -> Result<()> {
340        self.state(context)?;
341        context
342            .take_private_data_of_type::<LoaderContext<L::Backend>>()
343            .map(drop)
344            .ok_or(IoErrorKind::BadDescriptor)
345    }
346
347    fn read(
348        &self,
349        context: &mut Context,
350        _cx: &mut core::task::Context<'_>,
351        buffer: &mut [u8],
352        absolute_position: Size,
353    ) -> Poll<Result<usize>> {
354        file_system::ready(|| {
355            let state = self.state(context)?;
356            match state {
357                LoaderContext::Staging { .. } => Err(IoErrorKind::InvalidState),
358                LoaderContext::Ready {
359                    backend,
360                    device_context,
361                    ..
362                } => handle_inference_read(backend, device_context, buffer, absolute_position),
363            }
364        })
365    }
366
367    fn write(
368        &self,
369        context: &mut Context,
370        _cx: &mut core::task::Context<'_>,
371        buffer: &[u8],
372        absolute_position: Size,
373    ) -> Poll<Result<usize>> {
374        file_system::ready(|| {
375            let state = self.state_mut(context)?;
376            match state {
377                LoaderContext::Staging { bytes, .. } => {
378                    let offset = usize::try_from(absolute_position).unwrap_or(usize::MAX);
379                    if offset > bytes.len() {
380                        return Err(IoErrorKind::InvalidArgument);
381                    }
382                    bytes.write_at_within(offset, buffer, self.loader.maximum_model_size())?;
383                    Ok(buffer.len())
384                }
385                LoaderContext::Ready {
386                    backend,
387                    device_context,
388                    ..
389                } => handle_inference_write(backend, device_context, buffer, absolute_position),
390            }
391        })
392    }
393
394    fn control(
395        &self,
396        context: &mut Context,
397        _cx: &mut core::task::Context<'_>,
398        command: ControlCommandIdentifier,
399        input: &AnyByLayout,
400        output: &mut AnyByLayout,
401    ) -> Poll<Result<()>> {
402        file_system::ready(|| {
403            let state = self.state_mut(context)?;
404            match state {
405                LoaderContext::Staging { bytes, loader_id } => {
406                    if command != LOAD::IDENTIFIER {
407                        return Err(IoErrorKind::InvalidState);
408                    }
409                    validate_command::<LOAD>(input, output)?;
410                    let request = *LOAD::cast_input(input)?;
411                    if request.version != LoadRequest::VERSION || request.reserved != [0, 0] {
412                        return Err(IoErrorKind::InvalidArgument);
413                    }
414                    let encoding = ModelEncoding::try_from(request.encoding)?;
415                    let model = core::mem::take(bytes);
416                    let backend = self.loader.load(encoding, model)?;
417                    let execution = backend.create_execution()?;
418                    let input_count = backend.input_count();
419                    *state = LoaderContext::Ready {
420                        backend,
421                        device_context: DeviceContext {
422                            execution,
423                            input_filled: vec![0; input_count],
424                            input_index: 0,
425                            output_index: 0,
426                            computed: false,
427                        },
428                        loader_id: *loader_id,
429                    };
430                    Ok(())
431                }
432                LoaderContext::Ready {
433                    backend,
434                    device_context,
435                    ..
436                } => {
437                    if command == LOAD::IDENTIFIER {
438                        return Err(IoErrorKind::InvalidState);
439                    }
440                    handle_inference_control(backend, device_context, command, input, output)
441                }
442            }
443        })
444    }
445
446    fn clone_context(&self, _context: &Context) -> Result<Context> {
447        Err(IoErrorKind::Unsupported)
448    }
449}
450
451impl<L: Loader> MountOperations for LoaderDevice<L> {
452    fn unmount(&self) -> Result<()> {
453        Ok(())
454    }
455}
456
457impl<L: Loader> CharacterDevice for LoaderDevice<L> {}