Skip to main content

virtio_accel_tosa_build/
lib.rs

1//! Safe authoring of static, single-block TOSA 1.0 artifacts.
2//!
3//! The raw FlatBuffers layout is private to this crate. Borrowed [`Graph`] definitions suit
4//! statically declared artifacts, while [`OwnedGraph`] supports frontends that discover names,
5//! shapes, constants, and operators incrementally. Both surfaces round-trip every artifact through
6//! `virtio-accel-tosa`'s bounded parser and complete target validator before returning owned bytes.
7
8#![no_std]
9#![forbid(unsafe_code)]
10
11extern crate alloc;
12
13pub mod quantized;
14
15use alloc::borrow::Cow;
16use alloc::collections::BTreeSet;
17use alloc::string::{String, ToString};
18use alloc::vec::Vec;
19use core::fmt;
20
21use flatbuffers::{FlatBufferBuilder, TableFinishedWIPOffset, WIPOffset};
22use virtio_accel_tosa::{DType, NanPropagationMode, Op, RoundingMode, SemanticError, Target};
23
24type Table = WIPOffset<TableFinishedWIPOffset>;
25
26// These are the six stable container-table vtable positions used by the
27// single-block surface. Keeping them here prevents consumers from duplicating
28// schema layout knowledge; the completed artifact is always verified by the
29// ingestion crate before it crosses this API boundary.
30mod slot {
31    pub const TENSOR_NAME: u16 = 4;
32    pub const TENSOR_SHAPE: u16 = 6;
33    pub const TENSOR_TYPE: u16 = 8;
34    pub const TENSOR_DATA: u16 = 10;
35
36    pub const SHAPE_NAME: u16 = 4;
37    pub const SHAPE_RANK: u16 = 6;
38    pub const SHAPE_DATA: u16 = 8;
39
40    pub const OPERATOR_OP: u16 = 4;
41    pub const OPERATOR_ATTRIBUTE_TYPE: u16 = 6;
42    pub const OPERATOR_ATTRIBUTE: u16 = 8;
43    pub const OPERATOR_INPUTS: u16 = 10;
44    pub const OPERATOR_OUTPUTS: u16 = 12;
45
46    pub const BLOCK_NAME: u16 = 4;
47    pub const BLOCK_OPERATORS: u16 = 6;
48    pub const BLOCK_TENSORS: u16 = 8;
49    pub const BLOCK_INPUTS: u16 = 10;
50    pub const BLOCK_OUTPUTS: u16 = 12;
51    pub const BLOCK_SHAPES: u16 = 14;
52
53    pub const REGION_NAME: u16 = 4;
54    pub const REGION_BLOCKS: u16 = 6;
55
56    pub const GRAPH_VERSION: u16 = 4;
57    pub const GRAPH_REGIONS: u16 = 6;
58
59    pub const VERSION_MAJOR: u16 = 4;
60    pub const VERSION_MINOR: u16 = 6;
61    pub const VERSION_PATCH: u16 = 8;
62    pub const VERSION_DRAFT: u16 = 10;
63
64    pub const AXIS: u16 = 4;
65    pub const AXIS_NAN_MODE: u16 = 6;
66
67    pub const CLAMP_MIN_VAL: u16 = 4;
68    pub const CLAMP_MAX_VAL: u16 = 6;
69    pub const CLAMP_NAN_MODE: u16 = 8;
70
71    pub const TRANSPOSE_PERMS: u16 = 4;
72
73    pub const NAN_MODE: u16 = 4;
74    pub const MAX_POOL_KERNEL: u16 = 4;
75    pub const MAX_POOL_STRIDE: u16 = 6;
76    pub const MAX_POOL_PAD: u16 = 8;
77    pub const MAX_POOL_NAN_MODE: u16 = 10;
78
79    pub const RESCALE_SCALE32: u16 = 4;
80    pub const RESCALE_ROUNDING_MODE: u16 = 6;
81    pub const RESCALE_PER_CHANNEL: u16 = 8;
82    pub const RESCALE_INPUT_UNSIGNED: u16 = 10;
83    pub const RESCALE_OUTPUT_UNSIGNED: u16 = 12;
84}
85
86/// A serialized compile-time shape value.
87///
88/// Shape values occupy the TOSA shape namespace rather than the tensor namespace. They must be
89/// produced by [`OperatorKind::ConstShape`] before an operator such as `RESHAPE` consumes them.
90#[derive(Clone, Copy, Debug, PartialEq, Eq)]
91pub struct Shape<'a> {
92    /// Unique block-local shape name.
93    pub name: &'a str,
94    /// Signed 64-bit TOSA shape components. A scalar target shape uses an empty slice.
95    pub values: &'a [i64],
96}
97
98impl<'a> Shape<'a> {
99    pub const fn new(name: &'a str, values: &'a [i64]) -> Self {
100        Self { name, values }
101    }
102}
103
104/// A statically shaped tensor definition.
105#[derive(Clone, Copy, Debug, PartialEq, Eq)]
106pub struct Tensor<'a> {
107    /// Unique block-local tensor name.
108    pub name: &'a str,
109    /// Concrete dimensions. Scalars use an empty slice.
110    pub shape: &'a [i32],
111    /// Stable TOSA 1.0 element type.
112    pub dtype: DType,
113    /// Inline constant bytes, when this tensor is produced by `CONST`.
114    pub data: Option<&'a [u8]>,
115}
116
117impl<'a> Tensor<'a> {
118    /// Define a non-constant tensor.
119    pub const fn new(name: &'a str, shape: &'a [i32], dtype: DType) -> Self {
120        Self {
121            name,
122            shape,
123            dtype,
124            data: None,
125        }
126    }
127
128    /// Define a tensor with inline constant storage.
129    pub const fn constant(name: &'a str, shape: &'a [i32], dtype: DType, data: &'a [u8]) -> Self {
130        Self {
131            name,
132            shape,
133            dtype,
134            data: Some(data),
135        }
136    }
137}
138
139/// Typed operator kinds supported by the initial authoring surface.
140///
141/// Variants with no fields still name their exact TOSA attribute table. This
142/// prevents a caller from pairing an opcode with the wrong union member.
143/// Bytes of inline storage for one `CLAMP` bound: enough for every TOSA scalar dtype. The
144/// bounds are one scalar each in the operand's own dtype, so they are carried as serialized
145/// bytes; a wider numeric type could not represent an integer or FP8 bound faithfully.
146pub const MAX_CLAMP_BOUND_BYTES: usize = 8;
147
148/// Permutation entries a `TRANSPOSE` carries inline, one per dimension.
149pub const MAX_TRANSPOSE_RANK: usize = 6;
150
151#[derive(Clone, Copy, Debug, PartialEq, Eq)]
152#[non_exhaustive]
153pub enum OperatorKind {
154    MatMul,
155    ArgMax {
156        axis: i32,
157        nan_mode: NanPropagationMode,
158    },
159    Ceil,
160    Floor,
161    /// The bounds are one scalar each in the operand's own dtype, so they are carried as their
162    /// serialized bytes (`bound_bytes` of each array is significant) rather than a wider type
163    /// that would not represent an integer or FP8 bound faithfully.
164    Clamp {
165        min_val: [u8; MAX_CLAMP_BOUND_BYTES],
166        max_val: [u8; MAX_CLAMP_BOUND_BYTES],
167        bound_bytes: u8,
168        nan_mode: NanPropagationMode,
169    },
170    Concat {
171        axis: i32,
172    },
173    Reverse {
174        axis: i32,
175    },
176    /// One permutation entry per dimension; `rank` of `perms` is significant.
177    Transpose {
178        perms: [i32; MAX_TRANSPOSE_RANK],
179        rank: u8,
180    },
181    ReduceMax {
182        axis: i32,
183        nan_mode: NanPropagationMode,
184    },
185    ReduceMin {
186        axis: i32,
187        nan_mode: NanPropagationMode,
188    },
189    ReduceProduct {
190        axis: i32,
191    },
192    ReduceSum {
193        axis: i32,
194    },
195    MaxPool2d {
196        kernel: [i32; 2],
197        stride: [i32; 2],
198        pad: [i32; 4],
199        nan_mode: NanPropagationMode,
200    },
201    Sigmoid,
202    Tanh,
203    Add,
204    LogicalAnd,
205    LogicalOr,
206    LogicalXor,
207    Maximum {
208        nan_mode: NanPropagationMode,
209    },
210    Minimum {
211        nan_mode: NanPropagationMode,
212    },
213    Mul,
214    Pow,
215    Sub,
216    Abs,
217    Cos,
218    Exp,
219    Log,
220    LogicalNot,
221    Negate,
222    Reciprocal,
223    Rsqrt,
224    Sin,
225    Select,
226    Equal,
227    Greater,
228    GreaterEqual,
229    Erf,
230    Reshape,
231    Cast,
232    Gather,
233    Slice,
234    Rescale {
235        scale32: bool,
236        rounding_mode: RoundingMode,
237        per_channel: bool,
238        input_unsigned: bool,
239        output_unsigned: bool,
240    },
241    Const,
242    Identity,
243    ConstShape,
244}
245
246impl OperatorKind {
247    /// Stable TOSA opcode selected by this typed variant.
248    pub const fn op(self) -> Op {
249        match self {
250            Self::MatMul => Op::MATMUL,
251            Self::ArgMax { .. } => Op::ARGMAX,
252            Self::Ceil => Op::CEIL,
253            Self::Floor => Op::FLOOR,
254            Self::Clamp { .. } => Op::CLAMP,
255            Self::Concat { .. } => Op::CONCAT,
256            Self::Reverse { .. } => Op::REVERSE,
257            Self::Transpose { .. } => Op::TRANSPOSE,
258            Self::ReduceMax { .. } => Op::REDUCE_MAX,
259            Self::ReduceMin { .. } => Op::REDUCE_MIN,
260            Self::ReduceProduct { .. } => Op::REDUCE_PRODUCT,
261            Self::ReduceSum { .. } => Op::REDUCE_SUM,
262            Self::MaxPool2d { .. } => Op::MAX_POOL2D,
263            Self::Sigmoid => Op::SIGMOID,
264            Self::Tanh => Op::TANH,
265            Self::Add => Op::ADD,
266            Self::LogicalAnd => Op::LOGICAL_AND,
267            Self::LogicalOr => Op::LOGICAL_OR,
268            Self::LogicalXor => Op::LOGICAL_XOR,
269            Self::Maximum { .. } => Op::MAXIMUM,
270            Self::Minimum { .. } => Op::MINIMUM,
271            Self::Mul => Op::MUL,
272            Self::Pow => Op::POW,
273            Self::Sub => Op::SUB,
274            Self::Abs => Op::ABS,
275            Self::Cos => Op::COS,
276            Self::Exp => Op::EXP,
277            Self::Log => Op::LOG,
278            Self::LogicalNot => Op::LOGICAL_NOT,
279            Self::Negate => Op::NEGATE,
280            Self::Reciprocal => Op::RECIPROCAL,
281            Self::Rsqrt => Op::RSQRT,
282            Self::Sin => Op::SIN,
283            Self::Select => Op::SELECT,
284            Self::Equal => Op::EQUAL,
285            Self::Greater => Op::GREATER,
286            Self::GreaterEqual => Op::GREATER_EQUAL,
287            Self::Erf => Op::ERF,
288            Self::Reshape => Op::RESHAPE,
289            Self::Cast => Op::CAST,
290            Self::Gather => Op::GATHER,
291            Self::Slice => Op::SLICE,
292            Self::Rescale { .. } => Op::RESCALE,
293            Self::Const => Op::CONST,
294            Self::Identity => Op::IDENTITY,
295            Self::ConstShape => Op::CONST_SHAPE,
296        }
297    }
298}
299
300/// One operator and its block-local tensor references.
301#[derive(Clone, Copy, Debug, PartialEq, Eq)]
302pub struct Operator<'a> {
303    pub kind: OperatorKind,
304    pub inputs: &'a [&'a str],
305    pub outputs: &'a [&'a str],
306}
307
308impl<'a> Operator<'a> {
309    pub const fn new(kind: OperatorKind, inputs: &'a [&'a str], outputs: &'a [&'a str]) -> Self {
310        Self {
311            kind,
312            inputs,
313            outputs,
314        }
315    }
316}
317
318/// An owned compile-time shape for incrementally assembled graphs.
319#[derive(Clone, Debug, PartialEq, Eq)]
320pub struct OwnedShape {
321    pub name: String,
322    pub values: Vec<i64>,
323}
324
325impl OwnedShape {
326    pub fn new(name: impl Into<String>, values: Vec<i64>) -> Self {
327        Self {
328            name: name.into(),
329            values,
330        }
331    }
332}
333
334impl From<Shape<'_>> for OwnedShape {
335    fn from(shape: Shape<'_>) -> Self {
336        Self::new(shape.name, shape.values.to_vec())
337    }
338}
339
340/// An owned tensor definition for incrementally assembled graphs.
341#[derive(Clone, Debug, PartialEq, Eq)]
342pub struct OwnedTensor<'a> {
343    pub name: String,
344    pub shape: Vec<i32>,
345    pub dtype: DType,
346    /// Inline constant bytes. Existing frontend storage may be borrowed to avoid a second copy;
347    /// newly transformed data can be moved into this field.
348    pub data: Option<Cow<'a, [u8]>>,
349}
350
351impl<'a> OwnedTensor<'a> {
352    /// Define a non-constant owned tensor.
353    pub fn new(name: impl Into<String>, shape: Vec<i32>, dtype: DType) -> Self {
354        Self {
355            name: name.into(),
356            shape,
357            dtype,
358            data: None,
359        }
360    }
361
362    /// Define an owned tensor with inline constant storage.
363    pub fn constant(
364        name: impl Into<String>,
365        shape: Vec<i32>,
366        dtype: DType,
367        data: impl Into<Cow<'a, [u8]>>,
368    ) -> Self {
369        Self {
370            name: name.into(),
371            shape,
372            dtype,
373            data: Some(data.into()),
374        }
375    }
376}
377
378impl<'a> From<Tensor<'a>> for OwnedTensor<'a> {
379    fn from(tensor: Tensor<'a>) -> Self {
380        match tensor.data {
381            Some(data) => Self::constant(tensor.name, tensor.shape.to_vec(), tensor.dtype, data),
382            None => Self::new(tensor.name, tensor.shape.to_vec(), tensor.dtype),
383        }
384    }
385}
386
387/// An owned typed operator for incrementally assembled graphs.
388#[derive(Clone, Debug, PartialEq, Eq)]
389pub struct OwnedOperator {
390    pub kind: OperatorKind,
391    pub inputs: Vec<String>,
392    pub outputs: Vec<String>,
393}
394
395impl OwnedOperator {
396    /// Define an operator from owned operand names.
397    pub const fn new(kind: OperatorKind, inputs: Vec<String>, outputs: Vec<String>) -> Self {
398        Self {
399            kind,
400            inputs,
401            outputs,
402        }
403    }
404}
405
406impl From<Operator<'_>> for OwnedOperator {
407    fn from(operator: Operator<'_>) -> Self {
408        Self::new(
409            operator.kind,
410            operator
411                .inputs
412                .iter()
413                .map(|name| (*name).to_string())
414                .collect(),
415            operator
416                .outputs
417                .iter()
418                .map(|name| (*name).to_string())
419                .collect(),
420        )
421    }
422}
423
424/// An owned, incrementally assembled static TOSA graph.
425///
426/// This surface is intended for compiler frontends whose names, shapes, constants, and operator
427/// lists are discovered at runtime. It owns names and metadata while permitting explicit borrowing
428/// of existing constant storage. It creates borrowed [`Graph`] views only during [`Self::build`],
429/// so callers do not need parallel adapter structures. The same structural and target validation
430/// as [`Graph::build`] remains authoritative.
431#[derive(Clone, Debug, PartialEq, Eq)]
432pub struct OwnedGraph<'a> {
433    pub name: String,
434    pub tensors: Vec<OwnedTensor<'a>>,
435    pub shapes: Vec<OwnedShape>,
436    pub operators: Vec<OwnedOperator>,
437    pub inputs: Vec<String>,
438    pub outputs: Vec<String>,
439}
440
441impl<'a> OwnedGraph<'a> {
442    pub fn new(name: impl Into<String>) -> Self {
443        Self {
444            name: name.into(),
445            tensors: Vec::new(),
446            shapes: Vec::new(),
447            operators: Vec::new(),
448            inputs: Vec::new(),
449            outputs: Vec::new(),
450        }
451    }
452
453    pub fn push_tensor(&mut self, tensor: OwnedTensor<'a>) -> &mut Self {
454        self.tensors.push(tensor);
455        self
456    }
457
458    pub fn push_shape(&mut self, shape: OwnedShape) -> &mut Self {
459        self.shapes.push(shape);
460        self
461    }
462
463    pub fn push_operator(&mut self, operator: OwnedOperator) -> &mut Self {
464        self.operators.push(operator);
465        self
466    }
467
468    pub fn push_input(&mut self, name: impl Into<String>) -> &mut Self {
469        self.inputs.push(name.into());
470        self
471    }
472
473    pub fn push_output(&mut self, name: impl Into<String>) -> &mut Self {
474        self.outputs.push(name.into());
475        self
476    }
477
478    /// Serialize and semantically validate this graph for `target`.
479    ///
480    /// The graph remains reusable after a build. All metadata views allocated here are transient;
481    /// the returned artifact bytes are the only allocation retained by the caller.
482    pub fn build(&self, target: Target) -> Result<Vec<u8>, BuildError> {
483        let tensors: Vec<_> = self
484            .tensors
485            .iter()
486            .map(|tensor| match &tensor.data {
487                Some(data) => {
488                    Tensor::constant(&tensor.name, &tensor.shape, tensor.dtype, data.as_ref())
489                }
490                None => Tensor::new(&tensor.name, &tensor.shape, tensor.dtype),
491            })
492            .collect();
493        let shapes: Vec<_> = self
494            .shapes
495            .iter()
496            .map(|shape| Shape::new(&shape.name, &shape.values))
497            .collect();
498        let operator_inputs: Vec<Vec<&str>> = self
499            .operators
500            .iter()
501            .map(|operator| operator.inputs.iter().map(String::as_str).collect())
502            .collect();
503        let operator_outputs: Vec<Vec<&str>> = self
504            .operators
505            .iter()
506            .map(|operator| operator.outputs.iter().map(String::as_str).collect())
507            .collect();
508        let operators: Vec<_> = self
509            .operators
510            .iter()
511            .enumerate()
512            .map(|(index, operator)| {
513                Operator::new(
514                    operator.kind,
515                    &operator_inputs[index],
516                    &operator_outputs[index],
517                )
518            })
519            .collect();
520        let inputs: Vec<_> = self.inputs.iter().map(String::as_str).collect();
521        let outputs: Vec<_> = self.outputs.iter().map(String::as_str).collect();
522
523        Graph::new(&self.name, &tensors, &operators, &inputs, &outputs)
524            .with_shapes(&shapes)
525            .build(target)
526    }
527}
528
529impl<'a> From<Graph<'a>> for OwnedGraph<'a> {
530    fn from(graph: Graph<'a>) -> Self {
531        Self {
532            name: graph.name.to_string(),
533            tensors: graph.tensors.iter().copied().map(Into::into).collect(),
534            shapes: graph.shapes.iter().copied().map(Into::into).collect(),
535            operators: graph.operators.iter().copied().map(Into::into).collect(),
536            inputs: graph
537                .inputs
538                .iter()
539                .map(|name| (*name).to_string())
540                .collect(),
541            outputs: graph
542                .outputs
543                .iter()
544                .map(|name| (*name).to_string())
545                .collect(),
546        }
547    }
548}
549
550/// A static TOSA graph containing one region and one basic block.
551#[derive(Clone, Copy, Debug, PartialEq, Eq)]
552pub struct Graph<'a> {
553    pub name: &'a str,
554    pub tensors: &'a [Tensor<'a>],
555    pub shapes: &'a [Shape<'a>],
556    pub operators: &'a [Operator<'a>],
557    pub inputs: &'a [&'a str],
558    pub outputs: &'a [&'a str],
559}
560
561impl<'a> Graph<'a> {
562    pub const fn new(
563        name: &'a str,
564        tensors: &'a [Tensor<'a>],
565        operators: &'a [Operator<'a>],
566        inputs: &'a [&'a str],
567        outputs: &'a [&'a str],
568    ) -> Self {
569        Self {
570            name,
571            tensors,
572            shapes: &[],
573            operators,
574            inputs,
575            outputs,
576        }
577    }
578
579    /// Add compile-time shape values to this graph.
580    pub const fn with_shapes(mut self, shapes: &'a [Shape<'a>]) -> Self {
581        self.shapes = shapes;
582        self
583    }
584
585    /// Serialize and semantically validate this graph for `target`.
586    ///
587    /// The returned vector is the only allocation retained by the caller.
588    /// Construction is linear in graph metadata and constant bytes. Validation
589    /// runs once on this cold authoring path; providers still perform their own
590    /// authoritative admission during `load_program`.
591    pub fn build(self, target: Target) -> Result<Vec<u8>, BuildError> {
592        self.check_static_surface()?;
593        let bytes = self.serialize();
594        let model = virtio_accel_tosa::parse(&bytes).map_err(BuildError::Parse)?;
595        model.validate_for(target).map_err(BuildError::Semantic)?;
596        Ok(bytes)
597    }
598
599    fn check_static_surface(self) -> Result<(), BuildError> {
600        if self.name.is_empty() {
601            return Err(BuildError::EmptyGraphName);
602        }
603        for tensor in self.tensors {
604            if tensor.shape.iter().any(|dimension| *dimension < 0) {
605                return Err(BuildError::DynamicShape);
606            }
607            if !tensor.dtype.is_tosa_1_0() {
608                return Err(BuildError::UnsupportedDType(tensor.dtype));
609            }
610        }
611
612        for shape in self.shapes {
613            if u32::try_from(shape.values.len()).is_err() {
614                return Err(BuildError::ShapeRankOverflow);
615            }
616        }
617
618        let mut constant_tensors = BTreeSet::new();
619        let mut constant_shapes = BTreeSet::new();
620        for operator in self.operators {
621            let outputs = match operator.kind {
622                OperatorKind::Const => &mut constant_tensors,
623                OperatorKind::ConstShape => &mut constant_shapes,
624                _ => continue,
625            };
626            outputs.extend(operator.outputs.iter().copied());
627        }
628
629        for tensor in self.tensors {
630            match tensor.data {
631                Some([]) => return Err(BuildError::EmptyConstantData),
632                Some(_) if !constant_tensors.contains(tensor.name) => {
633                    return Err(BuildError::TensorDataWithoutConst);
634                }
635                Some(_) => {}
636                None if constant_tensors.contains(tensor.name) => {
637                    return Err(BuildError::ConstWithoutTensorData);
638                }
639                None => {}
640            }
641        }
642        if self
643            .shapes
644            .iter()
645            .any(|shape| !constant_shapes.contains(shape.name))
646        {
647            return Err(BuildError::ShapeWithoutConstShape);
648        }
649        Ok(())
650    }
651
652    fn serialize(self) -> Vec<u8> {
653        let mut builder = FlatBufferBuilder::with_capacity(4096);
654
655        let tensors = {
656            let tables: Vec<_> = self
657                .tensors
658                .iter()
659                .map(|tensor| tensor_table(&mut builder, *tensor))
660                .collect();
661            builder.create_vector(&tables)
662        };
663        let shapes = {
664            let tables: Vec<_> = self
665                .shapes
666                .iter()
667                .map(|shape| shape_table(&mut builder, *shape))
668                .collect();
669            builder.create_vector(&tables)
670        };
671        let operators = {
672            let tables: Vec<_> = self
673                .operators
674                .iter()
675                .map(|operator| operator_table(&mut builder, *operator))
676                .collect();
677            builder.create_vector(&tables)
678        };
679        let block = {
680            let name = builder.create_string(self.name);
681            let inputs = string_vector(&mut builder, self.inputs);
682            let outputs = string_vector(&mut builder, self.outputs);
683            let table = builder.start_table();
684            builder.push_slot_always(slot::BLOCK_NAME, name);
685            builder.push_slot_always(slot::BLOCK_OPERATORS, operators);
686            builder.push_slot_always(slot::BLOCK_TENSORS, tensors);
687            builder.push_slot_always(slot::BLOCK_INPUTS, inputs);
688            builder.push_slot_always(slot::BLOCK_OUTPUTS, outputs);
689            builder.push_slot_always(slot::BLOCK_SHAPES, shapes);
690            builder.end_table(table)
691        };
692        let region = {
693            let name = builder.create_string(self.name);
694            let blocks = builder.create_vector(&[block]);
695            let table = builder.start_table();
696            builder.push_slot_always(slot::REGION_NAME, name);
697            builder.push_slot_always(slot::REGION_BLOCKS, blocks);
698            builder.end_table(table)
699        };
700        let graph = {
701            let version = {
702                let table = builder.start_table();
703                builder.push_slot::<i32>(slot::VERSION_MAJOR, 1, -1);
704                builder.push_slot::<i32>(slot::VERSION_MINOR, 0, -1);
705                builder.push_slot::<i32>(slot::VERSION_PATCH, 0, -1);
706                builder.push_slot::<bool>(slot::VERSION_DRAFT, false, true);
707                builder.end_table(table)
708            };
709            let regions = builder.create_vector(&[region]);
710            let table = builder.start_table();
711            builder.push_slot_always(slot::GRAPH_VERSION, version);
712            builder.push_slot_always(slot::GRAPH_REGIONS, regions);
713            builder.end_table(table)
714        };
715
716        builder.finish(graph, Some("TOSA"));
717        builder.finished_data().to_vec()
718    }
719}
720
721fn shape_table(builder: &mut FlatBufferBuilder<'_>, shape: Shape<'_>) -> Table {
722    let name = builder.create_string(shape.name);
723    let bytes: Vec<_> = shape
724        .values
725        .iter()
726        .flat_map(|value| value.to_le_bytes())
727        .collect();
728    let data = builder.create_vector(&bytes);
729    let table = builder.start_table();
730    builder.push_slot_always(slot::SHAPE_NAME, name);
731    builder.push_slot::<u32>(
732        slot::SHAPE_RANK,
733        u32::try_from(shape.values.len()).expect("shape rank checked before serialization"),
734        0,
735    );
736    builder.push_slot_always(slot::SHAPE_DATA, data);
737    builder.end_table(table)
738}
739
740fn tensor_table(builder: &mut FlatBufferBuilder<'_>, tensor: Tensor<'_>) -> Table {
741    let name = builder.create_string(tensor.name);
742    let shape = builder.create_vector(tensor.shape);
743    let data = tensor.data.map(|bytes| builder.create_vector(bytes));
744    let table = builder.start_table();
745    builder.push_slot_always(slot::TENSOR_NAME, name);
746    builder.push_slot_always(slot::TENSOR_SHAPE, shape);
747    builder.push_slot::<u32>(slot::TENSOR_TYPE, tensor.dtype.get(), 0);
748    if let Some(data) = data {
749        builder.push_slot_always(slot::TENSOR_DATA, data);
750    }
751    builder.end_table(table)
752}
753
754fn operator_table(builder: &mut FlatBufferBuilder<'_>, operator: Operator<'_>) -> Table {
755    let inputs = string_vector(builder, operator.inputs);
756    let outputs = string_vector(builder, operator.outputs);
757    let max_pool = match operator.kind {
758        OperatorKind::MaxPool2d {
759            kernel,
760            stride,
761            pad,
762            nan_mode,
763        } => Some((
764            builder.create_vector(&kernel),
765            builder.create_vector(&stride),
766            builder.create_vector(&pad),
767            nan_mode,
768        )),
769        _ => None,
770    };
771    let clamp = match operator.kind {
772        OperatorKind::Clamp {
773            min_val,
774            max_val,
775            bound_bytes,
776            nan_mode,
777        } => {
778            let bytes = bound_bytes as usize;
779            Some((
780                builder.create_vector(&min_val[..bytes]),
781                builder.create_vector(&max_val[..bytes]),
782                nan_mode,
783            ))
784        }
785        _ => None,
786    };
787    let transpose = match operator.kind {
788        OperatorKind::Transpose { perms, rank } => {
789            Some(builder.create_vector(&perms[..rank as usize]))
790        }
791        _ => None,
792    };
793    let attribute = {
794        let table = builder.start_table();
795        match operator.kind {
796            OperatorKind::Maximum { nan_mode } | OperatorKind::Minimum { nan_mode } => {
797                builder.push_slot::<u32>(slot::NAN_MODE, nan_mode.get(), 0);
798            }
799            OperatorKind::ArgMax { axis, nan_mode }
800            | OperatorKind::ReduceMax { axis, nan_mode }
801            | OperatorKind::ReduceMin { axis, nan_mode } => {
802                builder.push_slot::<i32>(slot::AXIS, axis, 0);
803                builder.push_slot::<u32>(slot::AXIS_NAN_MODE, nan_mode.get(), 0);
804            }
805            OperatorKind::Concat { axis }
806            | OperatorKind::Reverse { axis }
807            | OperatorKind::ReduceProduct { axis }
808            | OperatorKind::ReduceSum { axis } => {
809                builder.push_slot::<i32>(slot::AXIS, axis, 0);
810            }
811            OperatorKind::Clamp { .. } => {
812                let (min_val, max_val, nan_mode) = clamp.expect("CLAMP vectors were constructed");
813                builder.push_slot_always(slot::CLAMP_MIN_VAL, min_val);
814                builder.push_slot_always(slot::CLAMP_MAX_VAL, max_val);
815                builder.push_slot::<u32>(slot::CLAMP_NAN_MODE, nan_mode.get(), 0);
816            }
817            OperatorKind::Transpose { .. } => {
818                let perms = transpose.expect("TRANSPOSE perms were constructed");
819                builder.push_slot_always(slot::TRANSPOSE_PERMS, perms);
820            }
821            OperatorKind::MaxPool2d { .. } => {
822                let (kernel, stride, pad, nan_mode) =
823                    max_pool.expect("MAX_POOL2D vectors were constructed");
824                builder.push_slot_always(slot::MAX_POOL_KERNEL, kernel);
825                builder.push_slot_always(slot::MAX_POOL_STRIDE, stride);
826                builder.push_slot_always(slot::MAX_POOL_PAD, pad);
827                builder.push_slot::<u32>(slot::MAX_POOL_NAN_MODE, nan_mode.get(), 0);
828            }
829            OperatorKind::Rescale {
830                scale32,
831                rounding_mode,
832                per_channel,
833                input_unsigned,
834                output_unsigned,
835            } => {
836                builder.push_slot::<bool>(slot::RESCALE_SCALE32, scale32, false);
837                builder.push_slot::<u32>(slot::RESCALE_ROUNDING_MODE, rounding_mode.get(), 0);
838                builder.push_slot::<bool>(slot::RESCALE_PER_CHANNEL, per_channel, false);
839                builder.push_slot::<bool>(slot::RESCALE_INPUT_UNSIGNED, input_unsigned, false);
840                builder.push_slot::<bool>(slot::RESCALE_OUTPUT_UNSIGNED, output_unsigned, false);
841            }
842            _ => {}
843        }
844        builder.end_table(table)
845    };
846    let op = operator.kind.op();
847    let table = builder.start_table();
848    builder.push_slot::<u32>(slot::OPERATOR_OP, op.get(), 0);
849    // In the pinned TOSA 1.0 schema, stable Attribute union members are in
850    // the same order as their corresponding stable Op values.
851    builder.push_slot::<u8>(slot::OPERATOR_ATTRIBUTE_TYPE, op.get() as u8, 0);
852    builder.push_slot_always(slot::OPERATOR_ATTRIBUTE, attribute);
853    builder.push_slot_always(slot::OPERATOR_INPUTS, inputs);
854    builder.push_slot_always(slot::OPERATOR_OUTPUTS, outputs);
855    builder.end_table(table)
856}
857
858fn string_vector<'a>(
859    builder: &mut FlatBufferBuilder<'a>,
860    values: &[&str],
861) -> WIPOffset<flatbuffers::Vector<'a, flatbuffers::ForwardsUOffset<&'a str>>> {
862    let offsets: Vec<_> = values
863        .iter()
864        .map(|value| builder.create_string(value))
865        .collect();
866    builder.create_vector(&offsets)
867}
868
869/// Failure to construct a static graph accepted by the shared TOSA target.
870#[derive(Debug)]
871#[non_exhaustive]
872pub enum BuildError {
873    EmptyGraphName,
874    DynamicShape,
875    ShapeRankOverflow,
876    EmptyConstantData,
877    TensorDataWithoutConst,
878    ConstWithoutTensorData,
879    ShapeWithoutConstShape,
880    UnsupportedDType(DType),
881    Parse(virtio_accel_tosa::Error),
882    Semantic(SemanticError),
883}
884
885impl fmt::Display for BuildError {
886    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
887        match self {
888            Self::EmptyGraphName => formatter.write_str("graph name must not be empty"),
889            Self::DynamicShape => {
890                formatter.write_str("the single-block authoring surface requires static shapes")
891            }
892            Self::ShapeRankOverflow => formatter.write_str("shape rank does not fit TOSA u32"),
893            Self::EmptyConstantData => {
894                formatter.write_str("tensor constants require nonempty inline data")
895            }
896            Self::TensorDataWithoutConst => {
897                formatter.write_str("inline tensor data requires a CONST producer")
898            }
899            Self::ConstWithoutTensorData => {
900                formatter.write_str("CONST outputs require nonempty inline tensor data")
901            }
902            Self::ShapeWithoutConstShape => {
903                formatter.write_str("shape values require a CONST_SHAPE producer")
904            }
905            Self::UnsupportedDType(dtype) => {
906                write!(formatter, "unsupported TOSA 1.0 dtype {dtype:?}")
907            }
908            Self::Parse(error) => write!(
909                formatter,
910                "constructed artifact failed structural validation: {error}"
911            ),
912            Self::Semantic(error) => write!(
913                formatter,
914                "constructed artifact failed semantic validation: {error}"
915            ),
916        }
917    }
918}
919
920#[cfg(test)]
921mod tests {
922    use super::*;
923    use alloc::vec;
924    use virtio_accel_tosa::{ExtensionSet, Level, ProfileSet, Version};
925
926    const FLOAT_TARGET: Target = Target::new(
927        Version::TOSA_1_0,
928        ProfileSet::FLOATING_POINT,
929        Level::Level8K,
930        ExtensionSet::NONE,
931    );
932
933    #[test]
934    fn identity_round_trips_through_production_validation() {
935        let tensors = [
936            Tensor::new("input", &[1, 4], DType::FP32),
937            Tensor::new("output", &[1, 4], DType::FP32),
938        ];
939        let operators = [Operator::new(
940            OperatorKind::Identity,
941            &["input"],
942            &["output"],
943        )];
944        let graph = Graph::new("main", &tensors, &operators, &["input"], &["output"]);
945
946        let first = graph.build(FLOAT_TARGET).unwrap();
947        let second = graph.build(FLOAT_TARGET).unwrap();
948        assert_eq!(first, second);
949
950        let model = virtio_accel_tosa::parse(&first).unwrap();
951        model.validate_for(FLOAT_TARGET).unwrap();
952        let block = model.regions().next().unwrap().blocks().next().unwrap();
953        assert_eq!(block.operators().next().unwrap().op(), Op::IDENTITY);
954    }
955
956    #[test]
957    fn constants_and_typed_nan_attributes_round_trip() {
958        let one = 1.0_f32.to_le_bytes();
959        let tensors = [
960            Tensor::new("lhs", &[1], DType::FP32),
961            Tensor::constant("rhs", &[1], DType::FP32, &one),
962            Tensor::new("output", &[1], DType::FP32),
963        ];
964        let operators = [
965            Operator::new(OperatorKind::Const, &[], &["rhs"]),
966            Operator::new(
967                OperatorKind::Maximum {
968                    nan_mode: NanPropagationMode::PROPAGATE,
969                },
970                &["lhs", "rhs"],
971                &["output"],
972            ),
973        ];
974        let bytes = Graph::new("main", &tensors, &operators, &["lhs"], &["output"])
975            .build(FLOAT_TARGET)
976            .unwrap();
977
978        let model = virtio_accel_tosa::parse(&bytes).unwrap();
979        let block = model.regions().next().unwrap().blocks().next().unwrap();
980        assert_eq!(block.operators().len(), 2);
981    }
982
983    /// The slot offsets of every newly authorable attribute, checked by parsing the artifact
984    /// back. The opcode/union-tag test above cannot catch a wrong offset: a misplaced axis
985    /// serializes cleanly and reads back as a different number.
986    #[test]
987    fn newly_authorable_attributes_survive_a_parse() {
988        use virtio_accel_tosa::OpAttributes;
989
990        fn attributes_of(
991            tensors: &[Tensor<'_>],
992            operators: &[Operator<'_>],
993            inputs: &[&str],
994            outputs: &[&str],
995        ) -> Vec<u8> {
996            Graph::new("main", tensors, operators, inputs, outputs)
997                .build(FLOAT_TARGET)
998                .expect("graph builds")
999        }
1000
1001        let f32_shape = &[2, 3][..];
1002        let bytes = attributes_of(
1003            &[
1004                Tensor::new("x", f32_shape, DType::FP32),
1005                Tensor::new("y", &[2, 1], DType::FP32),
1006            ],
1007            &[Operator::new(
1008                OperatorKind::ReduceSum { axis: 1 },
1009                &["x"],
1010                &["y"],
1011            )],
1012            &["x"],
1013            &["y"],
1014        );
1015        let model = virtio_accel_tosa::parse(&bytes).unwrap();
1016        let analysis = model.analyze_for(FLOAT_TARGET).unwrap();
1017        let operator = analysis.operators().last().unwrap();
1018        assert!(matches!(
1019            operator.source().attributes(),
1020            OpAttributes::ReduceSum { axis: 1 }
1021        ));
1022
1023        let bytes = attributes_of(
1024            &[
1025                Tensor::new("x", f32_shape, DType::FP32),
1026                Tensor::new("y", &[3, 2], DType::FP32),
1027            ],
1028            &[Operator::new(
1029                OperatorKind::Transpose {
1030                    perms: [1, 0, 0, 0, 0, 0],
1031                    rank: 2,
1032                },
1033                &["x"],
1034                &["y"],
1035            )],
1036            &["x"],
1037            &["y"],
1038        );
1039        let model = virtio_accel_tosa::parse(&bytes).unwrap();
1040        let analysis = model.analyze_for(FLOAT_TARGET).unwrap();
1041        let OpAttributes::Transpose { perms } =
1042            analysis.operators().last().unwrap().source().attributes()
1043        else {
1044            panic!("TRANSPOSE attribute");
1045        };
1046        assert_eq!(perms.iter().collect::<Vec<_>>(), vec![1, 0]);
1047
1048        let lo = (-1.0_f32).to_le_bytes();
1049        let hi = 1.0_f32.to_le_bytes();
1050        let mut min_val = [0; MAX_CLAMP_BOUND_BYTES];
1051        let mut max_val = [0; MAX_CLAMP_BOUND_BYTES];
1052        min_val[..4].copy_from_slice(&lo);
1053        max_val[..4].copy_from_slice(&hi);
1054        let bytes = attributes_of(
1055            &[
1056                Tensor::new("x", f32_shape, DType::FP32),
1057                Tensor::new("y", f32_shape, DType::FP32),
1058            ],
1059            &[Operator::new(
1060                OperatorKind::Clamp {
1061                    min_val,
1062                    max_val,
1063                    bound_bytes: 4,
1064                    nan_mode: NanPropagationMode::PROPAGATE,
1065                },
1066                &["x"],
1067                &["y"],
1068            )],
1069            &["x"],
1070            &["y"],
1071        );
1072        let model = virtio_accel_tosa::parse(&bytes).unwrap();
1073        let analysis = model.analyze_for(FLOAT_TARGET).unwrap();
1074        let OpAttributes::Clamp {
1075            min_val, max_val, ..
1076        } = analysis.operators().last().unwrap().source().attributes()
1077        else {
1078            panic!("CLAMP attribute");
1079        };
1080        assert_eq!(min_val, &lo[..]);
1081        assert_eq!(max_val, &hi[..]);
1082
1083        let bytes = attributes_of(
1084            &[
1085                Tensor::new("x", f32_shape, DType::FP32),
1086                Tensor::new("y", &[2], DType::INT32),
1087            ],
1088            &[Operator::new(
1089                OperatorKind::ArgMax {
1090                    axis: 1,
1091                    nan_mode: NanPropagationMode::IGNORE,
1092                },
1093                &["x"],
1094                &["y"],
1095            )],
1096            &["x"],
1097            &["y"],
1098        );
1099        let model = virtio_accel_tosa::parse(&bytes).unwrap();
1100        let analysis = model.analyze_for(FLOAT_TARGET).unwrap();
1101        let OpAttributes::ArgMax { axis, nan_mode } =
1102            analysis.operators().last().unwrap().source().attributes()
1103        else {
1104            panic!("ARGMAX attribute");
1105        };
1106        assert_eq!(axis, 1);
1107        assert_eq!(nan_mode, NanPropagationMode::IGNORE);
1108    }
1109
1110    #[test]
1111    fn incrementally_owned_graph_matches_borrowed_artifact_bytes() {
1112        let one = 1.0_f32.to_le_bytes();
1113        let tensors = [
1114            Tensor::new("lhs", &[1], DType::FP32),
1115            Tensor::constant("rhs", &[1], DType::FP32, &one),
1116            Tensor::new("output", &[1], DType::FP32),
1117        ];
1118        let operators = [
1119            Operator::new(OperatorKind::Const, &[], &["rhs"]),
1120            Operator::new(OperatorKind::Add, &["lhs", "rhs"], &["output"]),
1121        ];
1122        let expected = Graph::new("main", &tensors, &operators, &["lhs"], &["output"])
1123            .build(FLOAT_TARGET)
1124            .unwrap();
1125
1126        let mut graph = OwnedGraph::new(String::from("main"));
1127        graph
1128            .push_tensor(OwnedTensor::new(String::from("lhs"), vec![1], DType::FP32))
1129            .push_tensor(OwnedTensor::constant(
1130                String::from("rhs"),
1131                vec![1],
1132                DType::FP32,
1133                one.to_vec(),
1134            ))
1135            .push_tensor(OwnedTensor::new("output", vec![1], DType::FP32))
1136            .push_operator(OwnedOperator::new(
1137                OperatorKind::Const,
1138                vec![],
1139                vec![String::from("rhs")],
1140            ))
1141            .push_operator(OwnedOperator::new(
1142                OperatorKind::Add,
1143                vec![String::from("lhs"), String::from("rhs")],
1144                vec![String::from("output")],
1145            ))
1146            .push_input(String::from("lhs"))
1147            .push_output(String::from("output"));
1148
1149        let first = graph.build(FLOAT_TARGET).unwrap();
1150        let second = graph.build(FLOAT_TARGET).unwrap();
1151        assert_eq!(first, expected);
1152        assert_eq!(second, expected);
1153    }
1154
1155    #[test]
1156    fn borrowed_graph_converts_to_an_incremental_graph() {
1157        let tensors = [
1158            Tensor::new("input", &[1, 4], DType::FP32),
1159            Tensor::new("output", &[2, 2], DType::FP32),
1160        ];
1161        let shapes = [Shape::new("target", &[2, 2])];
1162        let operators = [
1163            Operator::new(OperatorKind::ConstShape, &[], &["target"]),
1164            Operator::new(OperatorKind::Reshape, &["input", "target"], &["output"]),
1165        ];
1166        let borrowed =
1167            Graph::new("main", &tensors, &operators, &["input"], &["output"]).with_shapes(&shapes);
1168        let expected = borrowed.build(FLOAT_TARGET).unwrap();
1169
1170        let owned = OwnedGraph::from(borrowed);
1171        assert_eq!(owned.build(FLOAT_TARGET).unwrap(), expected);
1172        assert_eq!(owned.shapes, vec![OwnedShape::new("target", vec![2, 2])]);
1173    }
1174
1175    #[test]
1176    fn owned_tensor_can_reuse_existing_constant_storage() {
1177        let data = 1.0_f32.to_le_bytes();
1178        let tensor = OwnedTensor::constant("value", vec![1], DType::FP32, data.as_slice());
1179
1180        let Some(Cow::Borrowed(stored)) = tensor.data else {
1181            panic!("borrowed constant data was copied");
1182        };
1183        assert!(core::ptr::eq(stored, data.as_slice()));
1184    }
1185
1186    #[test]
1187    fn owned_graph_uses_the_borrowed_validation_contract() {
1188        let mut graph = OwnedGraph::new("main");
1189        graph
1190            .push_tensor(OwnedTensor::constant(
1191                "value",
1192                vec![1],
1193                DType::FP32,
1194                1.0_f32.to_le_bytes().to_vec(),
1195            ))
1196            .push_input("value")
1197            .push_output("value");
1198
1199        assert!(matches!(
1200            graph.build(FLOAT_TARGET),
1201            Err(BuildError::TensorDataWithoutConst)
1202        ));
1203    }
1204
1205    #[test]
1206    fn reshape_uses_a_typed_const_shape_operand() {
1207        let tensors = [
1208            Tensor::new("input", &[1, 4], DType::FP32),
1209            Tensor::new("output", &[2, 2], DType::FP32),
1210        ];
1211        let shapes = [Shape::new("target", &[2, 2])];
1212        let operators = [
1213            Operator::new(OperatorKind::ConstShape, &[], &["target"]),
1214            Operator::new(OperatorKind::Reshape, &["input", "target"], &["output"]),
1215        ];
1216        let bytes = Graph::new("main", &tensors, &operators, &["input"], &["output"])
1217            .with_shapes(&shapes)
1218            .build(FLOAT_TARGET)
1219            .unwrap();
1220
1221        let model = virtio_accel_tosa::parse(&bytes).unwrap();
1222        let block = model.regions().next().unwrap().blocks().next().unwrap();
1223        assert_eq!(block.shapes().len(), 1);
1224        assert_eq!(block.shapes().next().unwrap().values().unwrap().len(), 2);
1225        assert_eq!(block.operators().len(), 2);
1226    }
1227
1228    #[test]
1229    fn inline_tensor_data_requires_a_nonempty_const_producer() {
1230        let one = 1.0_f32.to_le_bytes();
1231        let data_without_const = [Tensor::constant("value", &[1], DType::FP32, &one)];
1232        assert!(matches!(
1233            Graph::new("main", &data_without_const, &[], &["value"], &["value"])
1234                .build(FLOAT_TARGET),
1235            Err(BuildError::TensorDataWithoutConst)
1236        ));
1237
1238        let missing_data = [Tensor::new("value", &[1], DType::FP32)];
1239        let constant = [Operator::new(OperatorKind::Const, &[], &["value"])];
1240        assert!(matches!(
1241            Graph::new("main", &missing_data, &constant, &[], &["value"]).build(FLOAT_TARGET),
1242            Err(BuildError::ConstWithoutTensorData)
1243        ));
1244
1245        let empty_data = [Tensor::constant("value", &[0], DType::FP32, &[])];
1246        assert!(matches!(
1247            Graph::new("main", &empty_data, &constant, &[], &["value"]).build(FLOAT_TARGET),
1248            Err(BuildError::EmptyConstantData)
1249        ));
1250    }
1251
1252    #[test]
1253    fn every_operator_kind_serializes_its_pinned_opcode_and_union_tag() {
1254        let cases = [
1255            (OperatorKind::MatMul, Op::MATMUL, 7),
1256            (
1257                OperatorKind::ArgMax {
1258                    axis: 1,
1259                    nan_mode: NanPropagationMode::PROPAGATE,
1260                },
1261                Op::ARGMAX,
1262                1,
1263            ),
1264            (OperatorKind::Ceil, Op::CEIL, 34),
1265            (OperatorKind::Floor, Op::FLOOR, 38),
1266            (
1267                OperatorKind::Clamp {
1268                    min_val: [0; MAX_CLAMP_BOUND_BYTES],
1269                    max_val: [0, 0, 0x80, 0x3f, 0, 0, 0, 0],
1270                    bound_bytes: 4,
1271                    nan_mode: NanPropagationMode::PROPAGATE,
1272                },
1273                Op::CLAMP,
1274                11,
1275            ),
1276            (OperatorKind::Concat { axis: 0 }, Op::CONCAT, 55),
1277            (OperatorKind::Reverse { axis: 1 }, Op::REVERSE, 58),
1278            (
1279                OperatorKind::Transpose {
1280                    perms: [1, 0, 2, 0, 0, 0],
1281                    rank: 3,
1282                },
1283                Op::TRANSPOSE,
1284                61,
1285            ),
1286            (
1287                OperatorKind::ReduceMax {
1288                    axis: 1,
1289                    nan_mode: NanPropagationMode::PROPAGATE,
1290                },
1291                Op::REDUCE_MAX,
1292                51,
1293            ),
1294            (
1295                OperatorKind::ReduceMin {
1296                    axis: 1,
1297                    nan_mode: NanPropagationMode::IGNORE,
1298                },
1299                Op::REDUCE_MIN,
1300                52,
1301            ),
1302            (
1303                OperatorKind::ReduceProduct { axis: 0 },
1304                Op::REDUCE_PRODUCT,
1305                53,
1306            ),
1307            (OperatorKind::ReduceSum { axis: 0 }, Op::REDUCE_SUM, 54),
1308            (OperatorKind::Erf, Op::ERF, 12),
1309            (
1310                OperatorKind::MaxPool2d {
1311                    kernel: [2, 2],
1312                    stride: [2, 2],
1313                    pad: [0; 4],
1314                    nan_mode: NanPropagationMode::PROPAGATE,
1315                },
1316                Op::MAX_POOL2D,
1317                8,
1318            ),
1319            (OperatorKind::Sigmoid, Op::SIGMOID, 13),
1320            (OperatorKind::Tanh, Op::TANH, 14),
1321            (OperatorKind::Add, Op::ADD, 15),
1322            (OperatorKind::LogicalAnd, Op::LOGICAL_AND, 21),
1323            (OperatorKind::LogicalOr, Op::LOGICAL_OR, 24),
1324            (OperatorKind::LogicalXor, Op::LOGICAL_XOR, 25),
1325            (
1326                OperatorKind::Maximum {
1327                    nan_mode: NanPropagationMode::PROPAGATE,
1328                },
1329                Op::MAXIMUM,
1330                26,
1331            ),
1332            (
1333                OperatorKind::Minimum {
1334                    nan_mode: NanPropagationMode::PROPAGATE,
1335                },
1336                Op::MINIMUM,
1337                27,
1338            ),
1339            (OperatorKind::Mul, Op::MUL, 28),
1340            (OperatorKind::Pow, Op::POW, 29),
1341            (OperatorKind::Sub, Op::SUB, 30),
1342            (OperatorKind::Abs, Op::ABS, 32),
1343            (OperatorKind::Cos, Op::COS, 36),
1344            (OperatorKind::Exp, Op::EXP, 37),
1345            (OperatorKind::Log, Op::LOG, 39),
1346            (OperatorKind::LogicalNot, Op::LOGICAL_NOT, 40),
1347            (OperatorKind::Negate, Op::NEGATE, 41),
1348            (OperatorKind::Reciprocal, Op::RECIPROCAL, 42),
1349            (OperatorKind::Rsqrt, Op::RSQRT, 43),
1350            (OperatorKind::Sin, Op::SIN, 44),
1351            (OperatorKind::Select, Op::SELECT, 45),
1352            (OperatorKind::Equal, Op::EQUAL, 46),
1353            (OperatorKind::Greater, Op::GREATER, 47),
1354            (OperatorKind::GreaterEqual, Op::GREATER_EQUAL, 48),
1355            (OperatorKind::Reshape, Op::RESHAPE, 57),
1356            (OperatorKind::Cast, Op::CAST, 65),
1357            (
1358                OperatorKind::Rescale {
1359                    scale32: true,
1360                    rounding_mode: RoundingMode::SINGLE_ROUND,
1361                    per_channel: false,
1362                    input_unsigned: false,
1363                    output_unsigned: false,
1364                },
1365                Op::RESCALE,
1366                66,
1367            ),
1368            (OperatorKind::Const, Op::CONST, 67),
1369            (OperatorKind::Identity, Op::IDENTITY, 68),
1370            (OperatorKind::ConstShape, Op::CONST_SHAPE, 75),
1371        ];
1372
1373        for (kind, expected_op, expected_attribute) in cases {
1374            let tensors = [
1375                Tensor::new("input", &[1], DType::FP32),
1376                Tensor::new("output", &[1], DType::FP32),
1377            ];
1378            let shapes = [Shape::new("target", &[1])];
1379            let regular_inputs = ["input"];
1380            let reshape_inputs = ["input", "target"];
1381            let tensor_output = ["output"];
1382            let shape_output = ["target"];
1383            let (inputs, outputs): (&[&str], &[&str]) = match kind {
1384                OperatorKind::Const => (&[], &tensor_output),
1385                OperatorKind::ConstShape => (&[], &shape_output),
1386                OperatorKind::Reshape => (&reshape_inputs, &tensor_output),
1387                _ => (&regular_inputs, &tensor_output),
1388            };
1389            let operator = [Operator::new(kind, inputs, outputs)];
1390            let graph = Graph::new("main", &tensors, &operator, &[], &[]).with_shapes(&shapes);
1391            let bytes = graph.serialize();
1392            let model = virtio_accel_tosa::parse(&bytes).unwrap();
1393            let parsed = model
1394                .regions()
1395                .next()
1396                .unwrap()
1397                .blocks()
1398                .next()
1399                .unwrap()
1400                .operators()
1401                .next()
1402                .unwrap();
1403            assert_eq!(parsed.op(), expected_op);
1404            assert_eq!(parsed.attribute_kind().get(), expected_attribute);
1405        }
1406    }
1407
1408    #[test]
1409    fn rejects_dynamic_shapes_before_serialization() {
1410        let tensors = [Tensor::new("value", &[-1], DType::FP32)];
1411        let graph = Graph::new("main", &tensors, &[], &["value"], &["value"]);
1412        assert!(matches!(
1413            graph.build(FLOAT_TARGET),
1414            Err(BuildError::DynamicShape)
1415        ));
1416    }
1417}