Skip to main content

virtio_accel_tosa/
capability.rs

1use crate::{DType, Op, Target};
2
3macro_rules! flags {
4    ($name:ident, $bits:ty) => {
5        #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
6        #[repr(transparent)]
7        pub struct $name($bits);
8
9        impl $name {
10            pub const NONE: Self = Self(0);
11
12            pub const fn union(self, other: Self) -> Self {
13                Self(self.0 | other.0)
14            }
15
16            pub const fn contains(self, other: Self) -> bool {
17                self.0 & other.0 == other.0
18            }
19
20            pub const fn bits(self) -> $bits {
21                self.0
22            }
23        }
24    };
25}
26
27flags!(ValueRoles, u8);
28
29impl ValueRoles {
30    /// Graph-visible block input.
31    pub const INPUT: Self = Self(1 << 0);
32    /// Graph-visible block output.
33    pub const OUTPUT: Self = Self(1 << 1);
34    /// Serialized constant tensor.
35    pub const CONSTANT: Self = Self(1 << 2);
36    /// Non-boundary value produced and consumed inside a graph.
37    pub const INTERMEDIATE: Self = Self(1 << 3);
38    /// Every tensor role.
39    pub const ALL: Self =
40        Self(Self::INPUT.0 | Self::OUTPUT.0 | Self::CONSTANT.0 | Self::INTERMEDIATE.0);
41}
42
43flags!(DTypeConstraints, u8);
44
45impl DTypeConstraints {
46    /// This dtype is accepted only when a constant is consumed as a compile-time operator
47    /// parameter and does not become a graph-visible provider tensor.
48    pub const PARAMETER_ONLY: Self = Self(1 << 0);
49}
50
51flags!(OperatorConstraints, u16);
52
53impl OperatorConstraints {
54    /// Every NaN-mode attribute on this operator must select propagating NaNs.
55    pub const PROPAGATING_NAN: Self = Self(1 << 0);
56    /// Pool padding values must all be zero.
57    pub const ZERO_PADDING: Self = Self(1 << 1);
58    /// Shape or permutation operands must be serialized compile-time constants.
59    pub const CONSTANT_PARAMETERS: Self = Self(1 << 2);
60    /// TOSA zero-point operands must be serialized zeros.
61    pub const ZERO_ZERO_POINTS: Self = Self(1 << 3);
62    /// The TOSA `MUL` shift operand must be a serialized zero.
63    pub const ZERO_SHIFT: Self = Self(1 << 4);
64}
65
66/// One dtype admitted in explicitly listed graph roles.
67#[derive(Clone, Copy, Debug, PartialEq, Eq)]
68pub struct DTypeCapability {
69    pub dtype: DType,
70    pub roles: ValueRoles,
71    pub constraints: DTypeConstraints,
72}
73
74impl DTypeCapability {
75    pub const fn new(dtype: DType, roles: ValueRoles) -> Self {
76        Self {
77            dtype,
78            roles,
79            constraints: DTypeConstraints::NONE,
80        }
81    }
82
83    pub const fn constrained(
84        dtype: DType,
85        roles: ValueRoles,
86        constraints: DTypeConstraints,
87    ) -> Self {
88        Self {
89            dtype,
90            roles,
91            constraints,
92        }
93    }
94}
95
96/// One implemented operator and the conservative restrictions a scheduler must preserve.
97#[derive(Clone, Copy, Debug, PartialEq, Eq)]
98pub struct OperatorCapability {
99    pub op: Op,
100    pub constraints: OperatorConstraints,
101}
102
103impl OperatorCapability {
104    pub const fn new(op: Op) -> Self {
105        Self {
106            op,
107            constraints: OperatorConstraints::NONE,
108        }
109    }
110
111    pub const fn constrained(op: Op, constraints: OperatorConstraints) -> Self {
112        Self { op, constraints }
113    }
114}
115
116/// Provider treatment of semantic runtime conditions derived during TOSA analysis.
117#[derive(Clone, Copy, Debug, PartialEq, Eq)]
118#[non_exhaustive]
119pub enum RuntimeConditionSupport {
120    /// No analyzed runtime conditions are accepted at program admission.
121    None,
122    /// Advisory `REQUIRE` conditions may remain, but mandatory dynamic conditions are rejected.
123    AdvisoryOnly,
124    /// Index bounds must be discharged by `TosaAnalysis::proves_byte_lookup_bounds`.
125    /// Other dynamic conditions remain unsupported.
126    ProvenByteLookup,
127    /// Index bounds must be discharged by `TosaAnalysis::proves_byte_lookup_bounds`
128    /// or `TosaAnalysis::proves_constant_index_bounds`. Other conditions are rejected.
129    ProvenConstantOrByteLookup,
130}
131
132/// Whole-graph structural boundary that is not reducible to an operator bit.
133#[derive(Clone, Copy, Debug, PartialEq, Eq)]
134pub struct GraphCapabilities {
135    /// Maximum regions accepted in one artifact.
136    pub max_regions: usize,
137    /// Maximum basic blocks accepted across all regions.
138    pub max_blocks: usize,
139    /// Whether graph-visible tensor dimensions may remain dynamic at load time.
140    pub dynamic_shapes: bool,
141    /// Runtime conditions the provider may retain after semantic analysis.
142    pub runtime_conditions: RuntimeConditionSupport,
143}
144
145/// Conservative semantic admission descriptor for one exact TOSA target.
146///
147/// A positive query means that scheduling a `load_program` attempt is lawful. It does not promise
148/// that concrete shapes, cross-operand relationships, resource availability, native compilation,
149/// or runtime device state will succeed. Program admission remains authoritative.
150#[derive(Clone, Copy, Debug)]
151pub struct CapabilityDescriptor {
152    pub target: Target,
153    pub dtypes: &'static [DTypeCapability],
154    pub operators: &'static [OperatorCapability],
155    pub graph: GraphCapabilities,
156}
157
158impl CapabilityDescriptor {
159    pub const fn dtype(self, dtype: DType) -> Option<DTypeCapability> {
160        let mut index = 0;
161        while index < self.dtypes.len() {
162            let capability = self.dtypes[index];
163            if capability.dtype.get() == dtype.get() {
164                return Some(capability);
165            }
166            index += 1;
167        }
168        None
169    }
170
171    pub const fn supports_dtype(self, dtype: DType, role: ValueRoles) -> bool {
172        match self.dtype(dtype) {
173            Some(capability) => capability.roles.contains(role),
174            None => false,
175        }
176    }
177
178    pub const fn operator(self, op: Op) -> Option<OperatorCapability> {
179        let mut index = 0;
180        while index < self.operators.len() {
181            let capability = self.operators[index];
182            if capability.op.get() == op.get() {
183                return Some(capability);
184            }
185            index += 1;
186        }
187        None
188    }
189
190    pub const fn supports_operator(self, op: Op) -> bool {
191        self.operator(op).is_some()
192    }
193}
194
195/// Optional host-side interface implemented by concrete TOSA providers.
196///
197/// Providers return an empty slice when their native runtime/device is unavailable. Each entry is
198/// an exact target/profile tier; consumers must not combine fields from different descriptors.
199pub trait TosaCapabilityProvider {
200    fn tosa_capabilities(&self) -> &'static [CapabilityDescriptor];
201}
202
203#[cfg(test)]
204mod tests {
205    use super::*;
206    use crate::{ExtensionSet, Level, ProfileSet, Version};
207
208    const DTYPES: &[DTypeCapability] = &[
209        DTypeCapability::new(DType::FP32, ValueRoles::ALL),
210        DTypeCapability::constrained(
211            DType::INT8,
212            ValueRoles::CONSTANT,
213            DTypeConstraints::PARAMETER_ONLY,
214        ),
215    ];
216    const OPERATORS: &[OperatorCapability] = &[
217        OperatorCapability::new(Op::IDENTITY),
218        OperatorCapability::constrained(Op::MAXIMUM, OperatorConstraints::PROPAGATING_NAN),
219    ];
220    const DESCRIPTOR: CapabilityDescriptor = CapabilityDescriptor {
221        target: Target::new(
222            Version::TOSA_1_0,
223            ProfileSet::FLOATING_POINT,
224            Level::Level8K,
225            ExtensionSet::NONE,
226        ),
227        dtypes: DTYPES,
228        operators: OPERATORS,
229        graph: GraphCapabilities {
230            max_regions: 1,
231            max_blocks: 1,
232            dynamic_shapes: false,
233            runtime_conditions: RuntimeConditionSupport::None,
234        },
235    };
236
237    #[test]
238    fn role_queries_do_not_turn_parameter_constants_into_boundaries() {
239        assert!(DESCRIPTOR.supports_dtype(DType::FP32, ValueRoles::INPUT));
240        assert!(DESCRIPTOR.supports_dtype(DType::INT8, ValueRoles::CONSTANT));
241        assert!(!DESCRIPTOR.supports_dtype(DType::INT8, ValueRoles::INPUT));
242        assert!(
243            DESCRIPTOR
244                .dtype(DType::INT8)
245                .unwrap()
246                .constraints
247                .contains(DTypeConstraints::PARAMETER_ONLY)
248        );
249    }
250
251    #[test]
252    fn operator_queries_return_scheduler_visible_restrictions() {
253        assert!(DESCRIPTOR.supports_operator(Op::IDENTITY));
254        assert!(!DESCRIPTOR.supports_operator(Op::ERF));
255        assert!(
256            DESCRIPTOR
257                .operator(Op::MAXIMUM)
258                .unwrap()
259                .constraints
260                .contains(OperatorConstraints::PROPAGATING_NAN)
261        );
262    }
263}