nanoglia 0.3.1

Run TensorFlow Lite models loaded at runtime on microcontrollers: one no_std API, CMSIS-NN / ESP-NN accelerated kernels, every byte from your allocator.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
use crate::planner::{self, Interval};
use crate::{Encoding, ExecutionContext, Registry, Target, TensorRef};
use core::alloc::Layout;
use core::marker::PhantomData;
use core::mem::MaybeUninit;
use nanoglia_core::backend::{BackendKind, Kernel, KernelPlan};
use nanoglia_core::le::LeSlice;
use nanoglia_core::{
    ALIGN, Allocator, Block, DataType, Detail, Dims, Error, ErrorCode, MAX_OP_INPUTS,
    MAX_OP_OUTPUTS, OpCode, OpDesc, Quantization, Result, TensorDesc, align_up,
};
use nanoglia_tflite::{Model, SubGraph};

/// Where a tensor lives at execution time.
#[derive(Clone, Copy, Debug)]
pub(crate) enum Location {
    /// Not used by any operator.
    Unused,
    /// Constant data, at this offset in the model bytes.
    Const { offset: u32, len: u32 },
    /// Activation, at this offset in the context arena.
    Arena { offset: u32, len: u32 },
}

/// A prepared operator.
#[derive(Clone, Copy, Debug)]
pub(crate) struct OpEntry<'k> {
    /// The selected kernel, borrowed from a backend of the registry.
    pub kernel: &'k dyn Kernel,
    pub persist_offset: u32,
    pub persist_len: u32,
    /// Index of the first input in the I/O table; outputs follow the inputs.
    pub io_start: u32,
    pub inputs: u16,
    pub outputs: u16,
}

/// A typed array inside the graph block.
#[derive(Clone, Copy, Debug)]
pub(crate) struct Section<T> {
    offset: usize,
    len: usize,
    _type: PhantomData<T>,
}

impl<T> Section<T> {
    fn new(layout: &mut Layout, len: usize) -> Result<Self> {
        let array = Layout::array::<T>(len).map_err(|_| Error::out_of_memory(usize::MAX))?;
        let (extended, offset) = layout
            .extend(array)
            .map_err(|_| Error::out_of_memory(usize::MAX))?;
        *layout = extended;
        Ok(Self {
            offset,
            len,
            _type: PhantomData,
        })
    }

    fn get<'b>(&self, block: &'b [u8]) -> &'b [T] {
        debug_assert!(self.offset + self.len * size_of::<T>() <= block.len());
        // SAFETY: the section lies within the block (laid out by `Layout::extend`), is aligned
        // for `T` (the block is `ALIGN`-aligned and `T`'s alignment is at most `ALIGN`), and was
        // fully initialised during `Graph::load` before any shared access.
        unsafe {
            core::slice::from_raw_parts(block.as_ptr().add(self.offset).cast::<T>(), self.len)
        }
    }

    fn uninit<'b>(&self, block: &'b mut [u8]) -> &'b mut [MaybeUninit<T>] {
        debug_assert!(self.offset + self.len * size_of::<T>() <= block.len());
        // SAFETY: in bounds and aligned as above; `MaybeUninit` needs no initialisation.
        unsafe {
            core::slice::from_raw_parts_mut(
                block.as_mut_ptr().add(self.offset).cast::<MaybeUninit<T>>(),
                self.len,
            )
        }
    }
}

/// A loaded model, ready to create execution contexts.
///
/// The graph borrows the model bytes and the backends of its [`Registry`] (`'m`): weights are
/// never copied, and each operator keeps a reference to the kernel its backend selected. It owns
/// one block of memory from `A` holding the operator table, the prepared parameters and the
/// memory plan. A graph is immutable: create one [`ExecutionContext`] per concurrent inference.
/// It is `Send` and `Sync` when `A` is (kernels and backends are `Sync`).
///
/// # Example
///
/// Load a model from bytes the firmware already holds (here a small int8 classifier: input
/// `[3, 12]`, output `[3, 6]`), with all memory taken from a buffer on the stack:
///
/// ```
/// # #[repr(C, align(16))]
/// # struct Aligned<T: ?Sized>(T);
/// # static MODEL: &Aligned<[u8]> = &Aligned(*include_bytes!(concat!(
/// #     env!("CARGO_MANIFEST_DIR"),
/// #     "/doc/classifier.tflite"
/// # )));
/// # fn main() -> Result<(), nanoglia::Error> {
/// use nanoglia::{Arena, Encoding, Graph, Target};
///
/// let mut memory = [0u8; 4 * 1024];
/// let arena = Arena::new(&mut memory);
///
/// let graph = Graph::load_in(&[&MODEL.0], Encoding::Autodetect, Target::Auto, &arena)?;
/// let mut ctx = graph.init_execution_context_in(&arena)?;
///
/// ctx.input_mut(0)?.as_mut_slice::<i8>()?.fill(10);
/// ctx.compute()?;
/// let scores = ctx.output(0)?;
/// assert_eq!(scores.dims().as_slice(), &[3, 6]);
/// assert_eq!(scores.as_slice::<i8>()?.len(), 18);
/// # Ok(())
/// # }
/// ```
pub struct Graph<'m, A: Allocator> {
    model: &'m [u8],
    subgraph: SubGraph<'m>,
    block: Block<A>,
    ops: Section<OpEntry<'m>>,
    locations: Section<Location>,
    io: Section<i32>,
    arena_size: usize,
    scratch_offset: usize,
    scratch_size: usize,
}

impl<A: Allocator> core::fmt::Debug for Graph<'_, A> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("Graph")
            .field("operators", &self.ops.len)
            .field("tensors", &self.locations.len)
            .field("graph_bytes", &self.block.len())
            .field("context_bytes", &self.arena_size)
            .finish()
    }
}

const NO_TENSOR: TensorDesc<'static> = TensorDesc {
    index: u32::MAX,
    dtype: DataType::I8,
    dims: Dims::scalar(),
    quant: Quantization::NONE,
    data: None,
    name: "",
};

/// The operator descriptions of one operator, built on the stack.
struct OpDescs<'m> {
    inputs: [Option<TensorDesc<'m>>; MAX_OP_INPUTS],
    outputs: [TensorDesc<'m>; MAX_OP_OUTPUTS],
}

fn malformed() -> Error {
    Error::new(
        ErrorCode::InvalidEncoding,
        Detail::MalformedModel { offset: 0 },
    )
}

pub(crate) fn tensor_index(raw: i32, count: usize) -> Result<Option<usize>> {
    match raw {
        -1 => Ok(None),
        i if i >= 0 && (i as usize) < count => Ok(Some(i as usize)),
        _ => Err(malformed()),
    }
}

impl<'m, A: Allocator> Graph<'m, A> {
    /// Loads a model with the default [`Registry`] (the backends enabled by the crate features),
    /// taking all its memory from `alloc`.
    ///
    /// `builders` holds the model bytes (a single buffer for TFLite), which the graph borrows.
    /// They must stay valid and unchanged as long as the graph lives; constant buffers must be
    /// aligned for their type, which holds when the model starts on a 16-byte boundary.
    ///
    /// The model is verified first: a malformed model returns an error, never panics.
    ///
    /// ```
    /// # #[repr(C, align(16))]
    /// # struct Aligned<T: ?Sized>(T);
    /// # static MODEL: &Aligned<[u8]> = &Aligned(*include_bytes!(concat!(
    /// #     env!("CARGO_MANIFEST_DIR"),
    /// #     "/doc/classifier.tflite"
    /// # )));
    /// # fn main() -> Result<(), nanoglia::Error> {
    /// use nanoglia::{Arena, Encoding, ErrorCode, Graph, Target};
    ///
    /// let mut memory = [0u8; 4 * 1024];
    /// let arena = Arena::new(&mut memory);
    /// let graph = Graph::load_in(&[&MODEL.0], Encoding::Autodetect, Target::Auto, &arena)?;
    /// assert_eq!(graph.operator_count(), 1);
    ///
    /// // Not a TFLite model: an error, not a panic.
    /// let error = Graph::load_in(&[b"not a model"], Encoding::Autodetect, Target::Auto, &arena)
    ///     .unwrap_err();
    /// assert_eq!(error.code, ErrorCode::InvalidEncoding);
    /// # Ok(())
    /// # }
    /// ```
    pub fn load_in(
        builders: &[&'m [u8]],
        encoding: Encoding,
        target: Target,
        alloc: A,
    ) -> Result<Self> {
        Self::load_with(&Registry::default(), builders, encoding, target, alloc)
    }

    /// Loads a model, picking kernels from `registry`: for each operator, the first backend of the
    /// registry that supports it. Use it to add your own backends or kernels, or to restrict
    /// the backends a firmware links.
    ///
    /// The graph borrows the backends for as long as it lives (the same lifetime `'m` as the
    /// model bytes; the default registry is `'static`), so a backend may own state its kernels
    /// use, such as a driver handle. See the guide *Write a backend* in the documentation.
    ///
    /// ```
    /// # #[repr(C, align(16))]
    /// # struct Aligned<T: ?Sized>(T);
    /// # static MODEL: &Aligned<[u8]> = &Aligned(*include_bytes!(concat!(
    /// #     env!("CARGO_MANIFEST_DIR"),
    /// #     "/doc/classifier.tflite"
    /// # )));
    /// # fn main() -> Result<(), nanoglia::Error> {
    /// use nanoglia::{Arena, Detail, Encoding, ErrorCode, Graph, Registry, Target};
    ///
    /// let mut memory = [0u8; 4 * 1024];
    /// let arena = Arena::new(&mut memory);
    ///
    /// // A registry without any backend: the model's FULLY_CONNECTED has no kernel.
    /// let empty = Registry::new(&[]);
    /// let error = Graph::load_with(&empty, &[&MODEL.0], Encoding::Autodetect, Target::Auto, &arena)
    ///     .unwrap_err();
    /// assert_eq!(error.code, ErrorCode::UnsupportedOperation);
    /// assert!(matches!(error.detail, Detail::UnsupportedOp { op_index: 0, .. }));
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// A graph cannot outlive the backends it borrows:
    ///
    /// ```compile_fail,E0597
    /// # #[repr(C, align(16))]
    /// # struct Aligned<T: ?Sized>(T);
    /// # static MODEL: &Aligned<[u8]> = &Aligned(*include_bytes!(concat!(
    /// #     env!("CARGO_MANIFEST_DIR"),
    /// #     "/doc/classifier.tflite"
    /// # )));
    /// use nanoglia::core::OpDesc;
    /// use nanoglia::core::allocator_api2::alloc::Global;
    /// use nanoglia::core::backend::{Backend, Kernel};
    /// use nanoglia::{Encoding, Graph, Registry, Target};
    ///
    /// struct Local;
    /// impl Backend for Local {
    ///     fn name(&self) -> &'static str {
    ///         "local"
    ///     }
    ///     fn select<'s>(&'s self, op: &OpDesc<'_, '_>) -> Option<&'s dyn Kernel> {
    ///         Registry::default().backends().iter().find_map(|b| b.select(op))
    ///     }
    /// }
    ///
    /// let graph = {
    ///     let local = Local;
    ///     let backends: [&dyn Backend; 1] = [&local];
    ///     let registry = Registry::new(&backends);
    ///     Graph::load_with(&registry, &[&MODEL.0], Encoding::Autodetect, Target::Auto, Global)
    /// }; // error: `local` dropped while the graph still borrows it
    /// # drop(graph);
    /// ```
    pub fn load_with(
        registry: &Registry<'m>,
        builders: &[&'m [u8]],
        encoding: Encoding,
        target: Target,
        alloc: A,
    ) -> Result<Self> {
        let (bytes, subgraph) = open(builders, encoding)?;
        let sizing = Sizing::compute(registry, target, &subgraph)?;
        let tensor_count = subgraph.tensor_count();
        let mut block = Block::new_zeroed(sizing.block_size, alloc)?;
        let memory = block.as_mut_slice();

        // Memory plan, in the working sections of the block.
        let (intervals, order) = sizing.sections.working_memory(memory);
        let activations = plan_activations(&subgraph, intervals, order)?;

        // Tensor locations.
        for t in 0..tensor_count {
            let desc = subgraph.tensor(t)?;
            let location = if let Some(data) = desc.data {
                let offset = data.as_ptr() as usize - bytes.as_ptr() as usize;
                let align = desc.dtype.size().unwrap_or(1);
                if data.as_ptr().align_offset(align) != 0 {
                    return Err(Error::invalid_argument(Detail::Misaligned {
                        tensor: t as u32,
                    }));
                }
                Location::Const {
                    offset: offset as u32,
                    len: data.len() as u32,
                }
            } else {
                let (intervals, _) = sizing.sections.working_memory(memory);
                let iv = intervals[t];
                if iv.first == u32::MAX {
                    Location::Unused
                } else {
                    Location::Arena {
                        offset: iv.offset,
                        len: iv.size,
                    }
                }
            };
            sizing.sections.locations.uninit(memory)[t].write(location);
        }

        // Kernels: prepare their parameters and fill the operator and I/O tables.
        let mut persist_offset = sizing.persist_start;
        let mut io_next = 0usize;
        for index in 0..subgraph.operator_count() {
            let mut descs = OpDescs {
                inputs: [None; MAX_OP_INPUTS],
                outputs: [NO_TENSOR; MAX_OP_OUTPUTS],
            };
            let (desc, input_ids, output_ids) = describe(&subgraph, index, &mut descs)?;
            let kernel = select(registry, target, &desc)?.kernel;
            let plan = kernel.plan(&desc)?;
            if plan.scratch > sizing.scratch_size {
                // The backend selected or planned differently in the first pass.
                return Err(Error::new(ErrorCode::Unknown, Detail::None));
            }
            let persist_len = plan.persistent;
            let region = persist_offset
                .checked_add(persist_len)
                .and_then(|end| memory.get_mut(persist_offset..end))
                .ok_or_else(|| Error::new(ErrorCode::Unknown, Detail::None))?;
            kernel.prepare(&desc, region)?;

            let io_slots = sizing.sections.io.uninit(memory);
            let io_start = io_next;
            for raw in input_ids.iter().chain(output_ids.iter()) {
                io_slots[io_next].write(raw);
                io_next += 1;
            }
            sizing.sections.ops.uninit(memory)[index].write(OpEntry {
                kernel,
                persist_offset: persist_offset as u32,
                persist_len: persist_len as u32,
                io_start: io_start as u32,
                inputs: input_ids.len() as u16,
                outputs: output_ids.len() as u16,
            });
            persist_offset = align_up(persist_len)
                .and_then(|len| persist_offset.checked_add(len))
                .ok_or_else(|| Error::out_of_memory(usize::MAX))?;
        }

        let scratch_offset =
            align_up(activations).ok_or_else(|| Error::out_of_memory(usize::MAX))?;
        let scratch_size =
            align_up(sizing.scratch_size).ok_or_else(|| Error::out_of_memory(usize::MAX))?;
        let arena_size = scratch_offset
            .checked_add(scratch_size)
            .ok_or_else(|| Error::out_of_memory(usize::MAX))?;

        Ok(Self {
            model: bytes,
            subgraph,
            block,
            ops: sizing.sections.ops,
            locations: sizing.sections.locations,
            io: sizing.sections.io,
            arena_size,
            scratch_offset,
            scratch_size,
        })
    }

    /// The memory this graph uses: its own block and the arena of each execution context.
    pub fn memory_requirements(&self) -> MemoryRequirements {
        MemoryRequirements {
            graph_bytes: self.block.len(),
            context_bytes: self.arena_size,
        }
    }

    /// Creates an execution context, taking its arena (activations and scratch memory) from
    /// `alloc`.
    pub fn init_execution_context_in<B: Allocator>(
        &self,
        alloc: B,
    ) -> Result<ExecutionContext<'_, 'm, A, B>> {
        ExecutionContext::new(self, alloc)
    }

    /// Number of inputs.
    pub fn input_count(&self) -> usize {
        self.subgraph.inputs().len()
    }

    /// Number of outputs.
    pub fn output_count(&self) -> usize {
        self.subgraph.outputs().len()
    }

    /// Description of input `index`.
    pub fn input(&self, index: usize) -> Result<TensorDesc<'m>> {
        self.io_desc(self.subgraph.inputs(), index)
    }

    /// Description of output `index`.
    pub fn output(&self, index: usize) -> Result<TensorDesc<'m>> {
        self.io_desc(self.subgraph.outputs(), index)
    }

    /// Descriptions of the inputs, in order.
    ///
    /// Every tensor of the model was decoded when the graph loaded, from the same bytes, so
    /// [`Self::input`] cannot fail for an index below [`Self::input_count`]: the iterator yields
    /// exactly `input_count()` descriptions.
    ///
    /// ```
    /// # #[repr(C, align(16))]
    /// # struct Aligned<T: ?Sized>(T);
    /// # static MODEL: &Aligned<[u8]> = &Aligned(*include_bytes!(concat!(
    /// #     env!("CARGO_MANIFEST_DIR"),
    /// #     "/doc/classifier.tflite"
    /// # )));
    /// # fn main() -> Result<(), nanoglia::Error> {
    /// use nanoglia::{Arena, DataType, Encoding, Graph, Target};
    ///
    /// let mut memory = [0u8; 4 * 1024];
    /// let arena = Arena::new(&mut memory);
    /// let graph = Graph::load_in(&[&MODEL.0], Encoding::Autodetect, Target::Auto, &arena)?;
    /// for input in graph.inputs() {
    ///     assert_eq!(input.dtype, DataType::I8);
    ///     assert_eq!(input.dims.as_slice(), &[3, 12]);
    /// }
    /// assert_eq!(graph.outputs().map(|output| output.name).collect::<Vec<_>>(), ["output"]);
    /// # Ok(())
    /// # }
    /// ```
    pub fn inputs(&self) -> impl Iterator<Item = TensorDesc<'m>> + '_ {
        (0..self.input_count()).filter_map(|i| self.input(i).ok())
    }

    /// Descriptions of the outputs, in order; as [`Self::inputs`], it yields exactly
    /// [`Self::output_count`] descriptions.
    pub fn outputs(&self) -> impl Iterator<Item = TensorDesc<'m>> + '_ {
        (0..self.output_count()).filter_map(|i| self.output(i).ok())
    }

    /// Index of the input named `name`.
    pub fn input_index(&self, name: &str) -> Result<usize> {
        self.find(self.subgraph.inputs(), name)
    }

    /// Index of the output named `name`.
    pub fn output_index(&self, name: &str) -> Result<usize> {
        self.find(self.subgraph.outputs(), name)
    }

    /// Bytes of the graph block (kernel table, prepared parameters, memory plan).
    pub fn graph_bytes(&self) -> usize {
        self.block.len()
    }

    /// Bytes each execution context allocates (activations and scratch memory).
    pub fn context_bytes(&self) -> usize {
        self.arena_size
    }

    /// Number of operators.
    pub fn operator_count(&self) -> usize {
        self.ops.len
    }

    /// Name of the kernel selected for operator `index`, for diagnostics.
    pub fn kernel_name(&self, index: usize) -> Option<&'static str> {
        self.ops().get(index).map(|op| op.kernel.name())
    }

    fn io_desc(&self, list: LeSlice<'m, i32>, index: usize) -> Result<TensorDesc<'m>> {
        let raw = list.get(index).ok_or_else(|| {
            Error::invalid_argument(Detail::IndexOutOfRange {
                index: index as u32,
            })
        })?;
        let t = tensor_index(raw, self.locations.len)?.ok_or_else(malformed)?;
        self.subgraph.tensor(t)
    }

    fn find(&self, list: LeSlice<'m, i32>, name: &str) -> Result<usize> {
        for (i, raw) in list.iter().enumerate() {
            if let Some(t) = tensor_index(raw, self.locations.len)?
                && self.subgraph.tensor(t)?.name == name
            {
                return Ok(i);
            }
        }
        Err(Error::new(ErrorCode::NotFound, Detail::TensorNotFound))
    }

    pub(crate) fn ops(&self) -> &[OpEntry<'m>] {
        self.ops.get(self.block.as_slice())
    }

    pub(crate) fn io_table(&self) -> &[i32] {
        self.io.get(self.block.as_slice())
    }

    pub(crate) fn location(&self, raw: i32) -> Location {
        match tensor_index(raw, self.locations.len) {
            Ok(Some(t)) => self.locations.get(self.block.as_slice())[t],
            _ => Location::Unused,
        }
    }

    pub(crate) fn persist(&self, op: &OpEntry<'_>) -> &[u8] {
        let start = op.persist_offset as usize;
        &self.block.as_slice()[start..start + op.persist_len as usize]
    }

    pub(crate) fn model(&self) -> &'m [u8] {
        self.model
    }

    pub(crate) fn tensors(&self) -> GraphTensors<'_> {
        GraphTensors {
            subgraph: &self.subgraph,
            locations: self.locations.get(self.block.as_slice()),
            model: self.model,
        }
    }

    pub(crate) fn scratch(&self) -> (usize, usize) {
        (self.scratch_offset, self.scratch_size)
    }

    pub(crate) fn input_tensor(&self, index: usize) -> Result<(TensorDesc<'m>, Location)> {
        let raw = self.subgraph.inputs().get(index).ok_or_else(|| {
            Error::invalid_argument(Detail::IndexOutOfRange {
                index: index as u32,
            })
        })?;
        Ok((
            self.io_desc(self.subgraph.inputs(), index)?,
            self.location(raw),
        ))
    }

    pub(crate) fn output_tensor(&self, index: usize) -> Result<(TensorDesc<'m>, Location)> {
        let raw = self.subgraph.outputs().get(index).ok_or_else(|| {
            Error::invalid_argument(Detail::IndexOutOfRange {
                index: index as u32,
            })
        })?;
        Ok((
            self.io_desc(self.subgraph.outputs(), index)?,
            self.location(raw),
        ))
    }
}

#[cfg(feature = "alloc")]
impl<'m> Graph<'m, nanoglia_core::allocator_api2::alloc::Global> {
    /// Loads a model with the default [`Registry`], taking its memory from the global allocator.
    pub fn load(builders: &[&'m [u8]], encoding: Encoding, target: Target) -> Result<Self> {
        Self::load_in(
            builders,
            encoding,
            target,
            nanoglia_core::allocator_api2::alloc::Global,
        )
    }

    /// Creates an execution context whose arena comes from the global allocator.
    pub fn init_execution_context(
        &self,
    ) -> Result<
        ExecutionContext<
            '_,
            'm,
            nanoglia_core::allocator_api2::alloc::Global,
            nanoglia_core::allocator_api2::alloc::Global,
        >,
    > {
        self.init_execution_context_in(nanoglia_core::allocator_api2::alloc::Global)
    }
}

/// The operators and tensors of a graph, without its allocator type: what an
/// [`OpInfo`](crate::OpInfo) reads.
#[derive(Clone, Copy)]
pub(crate) struct GraphTensors<'a> {
    subgraph: &'a SubGraph<'a>,
    locations: &'a [Location],
    model: &'a [u8],
}

impl<'a> GraphTensors<'a> {
    /// The code of operator `index`.
    pub(crate) fn opcode(&self, index: usize) -> Result<OpCode<'a>> {
        Ok(self.subgraph.operator(index)?.code)
    }

    /// A view of tensor `raw` (an index of the model, `-1` for an omitted optional input), its
    /// activations read from `arena`.
    pub(crate) fn view(&self, raw: i32, arena: &'a [u8]) -> Result<TensorRef<'a>> {
        let t = tensor_index(raw, self.locations.len())?
            .ok_or_else(|| Error::new(ErrorCode::NotFound, Detail::TensorNotFound))?;
        let desc = self.subgraph.tensor(t)?;
        let range =
            |offset: u32, len: u32| offset as usize..(offset as usize).saturating_add(len as usize);
        let data = match self.locations.get(t).copied().unwrap_or(Location::Unused) {
            Location::Unused => Some(&[][..]),
            Location::Const { offset, len } => self.model.get(range(offset, len)),
            Location::Arena { offset, len } => arena.get(range(offset, len)),
        };
        Ok(TensorRef::new(desc, data.ok_or_else(malformed)?))
    }
}

/// Memory a model needs, computed without loading it.
///
/// Use it to size a static [`Arena`](nanoglia_core::Arena): compute it once on the host (or in
/// a test) for your model, then reserve [`Self::arena_bytes`] bytes in the firmware.
///
/// ```
/// # #[repr(C, align(16))]
/// # struct Aligned<T: ?Sized>(T);
/// # static MODEL: &Aligned<[u8]> = &Aligned(*include_bytes!(concat!(
/// #     env!("CARGO_MANIFEST_DIR"),
/// #     "/doc/classifier.tflite"
/// # )));
/// # fn main() -> Result<(), nanoglia::Error> {
/// use nanoglia::{Arena, Encoding, Graph, MemoryRequirements, Target};
///
/// // Only the memory planner's working memory is needed, and given back.
/// let mut scratch = [0u8; 512];
/// let needs = MemoryRequirements::compute_in(
///     &[&MODEL.0],
///     Encoding::Autodetect,
///     Target::Auto,
///     &Arena::new(&mut scratch),
/// )?;
///
/// // A buffer of `arena_bytes(1)` holds the graph and one execution context, at any alignment.
/// let mut memory = vec![0u8; needs.arena_bytes(1)];
/// let arena = Arena::new(&mut memory);
/// let graph = Graph::load_in(&[&MODEL.0], Encoding::Autodetect, Target::Auto, &arena)?;
/// let _ctx = graph.init_execution_context_in(&arena)?;
/// assert_eq!(graph.memory_requirements(), needs);
/// # Ok(())
/// # }
/// ```
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct MemoryRequirements {
    /// Bytes of the graph block (kernel table, prepared parameters, memory plan).
    pub graph_bytes: usize,
    /// Bytes of each execution context (activations and scratch memory).
    pub context_bytes: usize,
}

impl MemoryRequirements {
    /// Size of an [`Arena`](nanoglia_core::Arena) buffer that holds the graph and `contexts`
    /// execution contexts, whatever the alignment of the buffer.
    ///
    /// Saturates at `usize::MAX` (a size no buffer can have) instead of overflowing.
    pub const fn arena_bytes(&self, contexts: usize) -> usize {
        let graph = round_up_saturating(self.graph_bytes);
        let context = round_up_saturating(self.context_bytes);
        // Up to `ALIGN - 1` bytes are lost aligning the first block.
        (ALIGN - 1)
            .saturating_add(graph)
            .saturating_add(contexts.saturating_mul(context))
    }

    /// Computes the requirements of a model with the default [`Registry`]. Only the memory
    /// planner's working memory (about 20 bytes per tensor) is taken from `alloc`, and it is
    /// freed before returning.
    pub fn compute_in<A: Allocator>(
        builders: &[&[u8]],
        encoding: Encoding,
        target: Target,
        alloc: A,
    ) -> Result<Self> {
        Self::compute_with(&Registry::default(), builders, encoding, target, alloc)
    }

    /// Computes the requirements of a model, picking kernels from `registry`.
    pub fn compute_with<A: Allocator>(
        registry: &Registry<'_>,
        builders: &[&[u8]],
        encoding: Encoding,
        target: Target,
        alloc: A,
    ) -> Result<Self> {
        let (_, subgraph) = open(builders, encoding)?;
        // Only the planner's working memory: the intervals and the order, laid out as in the
        // graph block.
        let mut layout = Layout::from_size_align(0, ALIGN).map_err(|_| Error::out_of_memory(0))?;
        let working = WorkingSections::new(&mut layout, subgraph.tensor_count())?;
        let mut block = Block::new_zeroed(layout.size(), alloc)?;
        let breakdown = measure(registry, target, &subgraph, &working, block.as_mut_slice())?;
        Ok(breakdown.requirements())
    }

    /// Computes the requirements of a model with the default [`Registry`], taking the planner's
    /// working memory from the global allocator.
    #[cfg(feature = "alloc")]
    pub fn compute(builders: &[&[u8]], encoding: Encoding, target: Target) -> Result<Self> {
        Self::compute_in(
            builders,
            encoding,
            target,
            nanoglia_core::allocator_api2::alloc::Global,
        )
    }
}

/// Where the memory of a model goes: the sizes of [`MemoryRequirements`] and what they are made
/// of. Reported by [`ModelReport`](crate::ModelReport) for a model that loads.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub struct MemoryBreakdown {
    /// Bytes of the graph block ([`Graph::graph_bytes`]): the operator table, the tensor
    /// locations, the memory plan and [`Self::persistent_bytes`].
    pub graph_bytes: usize,
    /// Bytes of each execution context ([`Graph::context_bytes`]): [`Self::activation_bytes`]
    /// plus [`Self::scratch_bytes`].
    pub context_bytes: usize,
    /// Part of the graph block: the prepared parameters of the kernels, each rounded up to
    /// [`ALIGN`] bytes.
    pub persistent_bytes: usize,
    /// Part of each context: the activation tensors, as the memory planner packs them.
    pub activation_bytes: usize,
    /// Part of each context: the scratch area shared by all operators, the largest scratch any
    /// kernel asks for.
    pub scratch_bytes: usize,
}

impl MemoryBreakdown {
    /// The two sizes an application reserves: the graph block and each execution context.
    pub const fn requirements(&self) -> MemoryRequirements {
        MemoryRequirements {
            graph_bytes: self.graph_bytes,
            context_bytes: self.context_bytes,
        }
    }
}

/// What loading `subgraph` allocates, computed as [`Graph::load_with`] does (kernel selection and
/// planning, constant alignment, dataflow and memory plan) without preparing the kernels.
/// `memory` is a zeroed block laid out with `working`.
pub(crate) fn measure(
    registry: &Registry<'_>,
    target: Target,
    subgraph: &SubGraph<'_>,
    working: &WorkingSections,
    memory: &mut [u8],
) -> Result<MemoryBreakdown> {
    // In the order of loading, so that a model refused for several reasons gets the same error.
    let sizing = Sizing::compute(registry, target, subgraph)?;
    let (intervals, order) = working.working_memory(memory);
    let activations = plan_activations(subgraph, intervals, order)?;
    // Reject the models loading would reject for their constants, too.
    for t in 0..subgraph.tensor_count() {
        let desc = subgraph.tensor(t)?;
        if let Some(data) = desc.data
            && data.as_ptr().align_offset(desc.dtype.size().unwrap_or(1)) != 0
        {
            return Err(Error::invalid_argument(Detail::Misaligned {
                tensor: t as u32,
            }));
        }
    }
    let overflow = || Error::out_of_memory(usize::MAX);
    let activation_bytes = align_up(activations).ok_or_else(overflow)?;
    let scratch_bytes = align_up(sizing.scratch_size).ok_or_else(overflow)?;
    Ok(MemoryBreakdown {
        graph_bytes: sizing.block_size,
        context_bytes: activation_bytes
            .checked_add(scratch_bytes)
            .ok_or_else(overflow)?,
        persistent_bytes: sizing.block_size - sizing.persist_start,
        activation_bytes,
        scratch_bytes,
    })
}

/// `n` rounded up to a multiple of [`ALIGN`], saturating at `usize::MAX`.
const fn round_up_saturating(n: usize) -> usize {
    match n.checked_next_multiple_of(ALIGN) {
        Some(rounded) => rounded,
        None => usize::MAX,
    }
}

/// Checks the encoding, verifies the model and returns its bytes and its only subgraph.
pub(crate) fn open<'m>(
    builders: &[&'m [u8]],
    encoding: Encoding,
) -> Result<(&'m [u8], SubGraph<'m>)> {
    let [bytes] = builders else {
        return Err(Error::invalid_argument(Detail::None));
    };
    let bytes: &'m [u8] = bytes;
    match encoding {
        Encoding::TensorFlowLite => {}
        Encoding::Autodetect if Model::is_tflite(bytes) => {}
        Encoding::Autodetect => {
            return Err(Error::new(
                ErrorCode::InvalidEncoding,
                Detail::UnknownEncoding,
            ));
        }
    }
    let model = Model::parse(bytes)?;
    if model.subgraph_count() != 1 {
        return Err(Error::unsupported(Detail::UnsupportedStructure));
    }
    let subgraph = model.subgraph(0)?;
    if subgraph.operator_count() > u32::MAX as usize || subgraph.tensor_count() > u32::MAX as usize
    {
        return Err(Error::unsupported(Detail::UnsupportedStructure));
    }
    Ok((bytes, subgraph))
}

/// The sections of the graph block.
struct BlockSections<'k> {
    ops: Section<OpEntry<'k>>,
    locations: Section<Location>,
    io: Section<i32>,
    working: WorkingSections,
}

impl BlockSections<'_> {
    fn working_memory<'b>(&self, memory: &'b mut [u8]) -> (&'b mut [Interval], &'b mut [u32]) {
        self.working.working_memory(memory)
    }
}

/// The memory planner's working memory.
pub(crate) struct WorkingSections {
    intervals: Section<Interval>,
    order: Section<u32>,
}

impl WorkingSections {
    /// Appends the two working arrays of a model of `tensor_count` tensors to `layout`.
    pub(crate) fn new(layout: &mut Layout, tensor_count: usize) -> Result<Self> {
        Ok(Self {
            intervals: Section::new(layout, tensor_count)?,
            order: Section::new(layout, tensor_count)?,
        })
    }

    /// The two working arrays, in a zeroed block laid out with these sections.
    fn working_memory<'b>(&self, memory: &'b mut [u8]) -> (&'b mut [Interval], &'b mut [u32]) {
        assert!(
            self.intervals.offset + self.intervals.len * size_of::<Interval>() <= self.order.offset
        );
        assert!(self.order.offset + self.order.len * size_of::<u32>() <= memory.len());
        // SAFETY: both sections lie in `memory` (checked above), do not overlap (`order` follows
        // `intervals`), and are aligned for their types (the block is `ALIGN`-aligned and the
        // offsets come from `Layout::extend`). `Interval` (four `u32`) and `u32` accept any bit
        // pattern, so the zeroed or previously written bytes are valid values.
        unsafe {
            let base = memory.as_mut_ptr();
            (
                core::slice::from_raw_parts_mut(
                    base.add(self.intervals.offset).cast::<Interval>(),
                    self.intervals.len,
                ),
                core::slice::from_raw_parts_mut(
                    base.add(self.order.offset).cast::<u32>(),
                    self.order.len,
                ),
            )
        }
    }
}

/// Pass 1 of loading: the kernel of every operator, and the size of the graph block.
struct Sizing<'k> {
    sections: BlockSections<'k>,
    persist_start: usize,
    block_size: usize,
    scratch_size: usize,
}

impl Sizing<'_> {
    fn compute(registry: &Registry<'_>, target: Target, subgraph: &SubGraph<'_>) -> Result<Self> {
        let op_count = subgraph.operator_count();
        let tensor_count = subgraph.tensor_count();
        let mut persist_total = 0usize;
        let mut scratch_size = 0usize;
        let mut io_total = 0usize;
        let mut npu_ops = 0usize;
        for index in 0..op_count {
            let choice = choose(registry, target, subgraph, index, None)?;
            npu_ops += usize::from(choice.kind == BackendKind::Npu);
            let plan = choice.plan;
            persist_total = persist_total
                .checked_add(
                    align_up(plan.persistent).ok_or_else(|| Error::out_of_memory(usize::MAX))?,
                )
                .ok_or_else(|| Error::out_of_memory(usize::MAX))?;
            scratch_size = scratch_size.max(plan.scratch);
            io_total += choice.io;
        }
        if target == Target::Npu && npu_ops == 0 {
            return Err(Error::unsupported(Detail::None));
        }

        let mut layout = Layout::from_size_align(0, ALIGN).map_err(|_| Error::out_of_memory(0))?;
        let ops = Section::new(&mut layout, op_count)?;
        let locations = Section::new(&mut layout, tensor_count)?;
        let io = Section::new(&mut layout, io_total)?;
        let working = WorkingSections::new(&mut layout, tensor_count)?;
        let persist_start =
            align_up(layout.size()).ok_or_else(|| Error::out_of_memory(usize::MAX))?;
        let block_size = persist_start
            .checked_add(persist_total)
            .ok_or_else(|| Error::out_of_memory(usize::MAX))?;
        Ok(Self {
            sections: BlockSections {
                ops,
                locations,
                io,
                working,
            },
            persist_start,
            block_size,
            scratch_size,
        })
    }
}

/// Computes when each activation tensor is alive and places it in the context arena.
///
/// Fills `intervals` (one per tensor: size, first and last operator, offset; `first ==
/// u32::MAX` for tensors no operator uses) and returns the size of the activation area.
/// Checks the dataflow: every activation is produced once, before it is consumed.
fn plan_activations(
    subgraph: &SubGraph<'_>,
    intervals: &mut [Interval],
    order: &mut [u32],
) -> Result<usize> {
    let tensor_count = subgraph.tensor_count();
    let op_count = subgraph.operator_count();
    intervals.fill(Interval {
        size: 0,
        first: u32::MAX,
        last: 0,
        offset: 0,
    });
    for raw in subgraph.inputs().iter() {
        let t = tensor_index(raw, tensor_count)?.ok_or_else(malformed)?;
        intervals[t].first = 0;
    }
    for index in 0..op_count {
        let op_index = index as u32;
        let op = subgraph.operator(index)?;
        for raw in op.inputs.iter() {
            if let Some(t) = tensor_index(raw, tensor_count)? {
                if desc_is_constant(subgraph, t)? {
                    continue;
                }
                let iv = &mut intervals[t];
                if iv.first == u32::MAX {
                    // Consumed before being produced (or never produced).
                    return Err(malformed());
                }
                iv.last = iv.last.max(op_index);
            }
        }
        for raw in op.outputs.iter() {
            let t = tensor_index(raw, tensor_count)?.ok_or_else(malformed)?;
            if desc_is_constant(subgraph, t)? {
                return Err(malformed());
            }
            let iv = &mut intervals[t];
            if iv.first != u32::MAX {
                // Produced twice, or an output overwriting a graph input.
                return Err(malformed());
            }
            iv.first = op_index;
            iv.last = iv.last.max(op_index);
        }
    }
    for raw in subgraph.outputs().iter() {
        let t = tensor_index(raw, tensor_count)?.ok_or_else(malformed)?;
        if desc_is_constant(subgraph, t)? {
            continue;
        }
        let iv = &mut intervals[t];
        if iv.first == u32::MAX {
            return Err(malformed());
        }
        iv.last = op_count as u32;
    }
    for (t, iv) in intervals.iter_mut().enumerate() {
        if iv.first == u32::MAX {
            continue;
        }
        let desc = subgraph.tensor(t)?;
        if desc.data.is_some() {
            continue;
        }
        let len = desc
            .byte_len()
            .ok_or_else(|| Error::unsupported(Detail::ShapeMismatch { tensor: t as u32 }))?;
        iv.size = u32::try_from(len).map_err(|_| Error::out_of_memory(len))?;
    }
    planner::plan(intervals, order).ok_or_else(|| Error::out_of_memory(usize::MAX))
}

fn desc_is_constant(subgraph: &SubGraph<'_>, t: usize) -> Result<bool> {
    Ok(subgraph.tensor(t)?.data.is_some())
}

/// Builds the description of operator `index` in `descs`.
fn describe<'m, 'd>(
    subgraph: &SubGraph<'m>,
    index: usize,
    descs: &'d mut OpDescs<'m>,
) -> Result<(OpDesc<'m, 'd>, LeSlice<'m, i32>, LeSlice<'m, i32>)> {
    let op = subgraph.operator(index)?;
    let tensor_count = subgraph.tensor_count();
    if op.inputs.len() > MAX_OP_INPUTS || op.outputs.len() > MAX_OP_OUTPUTS {
        return Err(Error::unsupported(Detail::UnsupportedStructure));
    }
    for (slot, raw) in descs.inputs.iter_mut().zip(op.inputs.iter()) {
        *slot = match tensor_index(raw, tensor_count)? {
            Some(t) => {
                if subgraph.tensor_is_variable(t)? {
                    return Err(Error::unsupported(Detail::UnsupportedStructure));
                }
                Some(subgraph.tensor(t)?)
            }
            None => None,
        };
    }
    for (slot, raw) in descs.outputs.iter_mut().zip(op.outputs.iter()) {
        let t = tensor_index(raw, tensor_count)?.ok_or_else(malformed)?;
        *slot = subgraph.tensor(t)?;
    }
    let desc = OpDesc {
        index: index as u32,
        code: op.code,
        options: op.options,
        inputs: &descs.inputs[..op.inputs.len()],
        outputs: &descs.outputs[..op.outputs.len()],
    };
    Ok((desc, op.inputs, op.outputs))
}

/// The kernel a backend selected for an operator.
#[derive(Clone, Copy)]
struct Selected<'r> {
    kernel: &'r dyn Kernel,
    backend: &'static str,
    kind: BackendKind,
}

fn select<'r>(
    registry: &Registry<'r>,
    target: Target,
    desc: &OpDesc<'_, '_>,
) -> Result<Selected<'r>> {
    for &backend in registry.backends() {
        let kind = backend.kind();
        if target == Target::Cpu && kind == BackendKind::Npu {
            continue;
        }
        if let Some(kernel) = backend.select(desc) {
            return Ok(Selected {
                kernel,
                backend: backend.name(),
                kind,
            });
        }
    }
    Err(Error::unsupported(Detail::UnsupportedOp {
        op_index: desc.index,
        opcode: desc.opcode_number(),
    }))
}

/// The kernel of an operator and its memory needs: what loading checks for each operator.
#[derive(Clone, Copy)]
pub(crate) struct Choice<'r> {
    pub kernel: &'r dyn Kernel,
    /// Name of the backend the kernel comes from.
    pub backend: &'static str,
    pub kind: BackendKind,
    pub plan: KernelPlan,
    /// Number of inputs and outputs.
    pub io: usize,
}

/// Describes operator `index`, selects its kernel and plans it, as loading does: an error is the
/// one loading returns for this operator. With `persist`, a buffer aligned to [`ALIGN`] and at
/// least as large as the persistent parameters, the kernel is prepared in it too.
pub(crate) fn choose<'r>(
    registry: &Registry<'r>,
    target: Target,
    subgraph: &SubGraph<'_>,
    index: usize,
    persist: Option<&mut [u8]>,
) -> Result<Choice<'r>> {
    let mut descs = OpDescs {
        inputs: [None; MAX_OP_INPUTS],
        outputs: [NO_TENSOR; MAX_OP_OUTPUTS],
    };
    let (desc, _, _) = describe(subgraph, index, &mut descs)?;
    let selected = select(registry, target, &desc)?;
    let plan = selected.kernel.plan(&desc)?;
    if let Some(persist) = persist {
        // As loading: the planned size exactly, zeroed.
        let region = persist
            .get_mut(..plan.persistent)
            .ok_or_else(|| Error::new(ErrorCode::Unknown, Detail::None))?;
        region.fill(0);
        selected.kernel.prepare(&desc, region)?;
    }
    Ok(Choice {
        kernel: selected.kernel,
        backend: selected.backend,
        kind: selected.kind,
        plan,
        io: desc.inputs.len() + desc.outputs.len(),
    })
}