use core::fmt;
use core::ops::{BitAnd, BitAndAssign, BitOr, BitOrAssign};
use crate::shapes::ShapeBuf;
use crate::shapes::error::{OperationKind, ShapeError};
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct DescriptorSchemaVersion(u32);
impl DescriptorSchemaVersion {
pub const CURRENT: Self = Self(3);
#[must_use]
pub const fn new(version: u32) -> Self {
Self(version)
}
#[must_use]
pub const fn get(self) -> u32 {
self.0
}
#[must_use]
pub const fn is_compatible_with(self, other: Self) -> bool {
self.0 == other.0
}
}
impl fmt::Display for DescriptorSchemaVersion {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "v{}", self.0)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum ReduceOp {
Sum,
Mean,
Max,
Min,
Prod,
}
impl fmt::Display for ReduceOp {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(match self {
Self::Sum => "sum",
Self::Mean => "mean",
Self::Max => "max",
Self::Min => "min",
Self::Prod => "prod",
})
}
}
#[derive(Clone, Copy, PartialEq, Eq, Hash, Default, serde::Serialize, serde::Deserialize)]
pub(crate) struct AxisMask(u64);
impl AxisMask {
pub const MAX_AXES: usize = u64::BITS as usize;
pub const EMPTY: Self = Self(0);
#[must_use]
pub const fn contains(self, axis: usize) -> bool {
axis < Self::MAX_AXES && (self.0 >> axis) & 1 == 1
}
#[must_use]
pub const fn count(self) -> usize {
self.0.count_ones() as usize
}
#[must_use]
pub const fn is_empty(self) -> bool {
self.0 == 0
}
pub const fn insert(self, axis: usize) -> Option<Self> {
if axis < Self::MAX_AXES {
Some(Self(self.0 | (1u64 << axis)))
} else {
None
}
}
pub fn axes(self) -> impl Iterator<Item = usize> {
let mut bits = self.0;
core::iter::from_fn(move || {
if bits == 0 {
return None;
}
let axis = bits.trailing_zeros() as usize;
bits &= bits - 1;
Some(axis)
})
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct AxisSet(AxisSetRepr);
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
enum AxisSetRepr {
Empty,
Inline(AxisMask),
Spilled(alloc::vec::Vec<usize>),
}
impl Default for AxisSet {
fn default() -> Self {
Self::EMPTY
}
}
impl serde::Serialize for AxisSet {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
let axes: alloc::vec::Vec<_> = self.axes().collect();
serializer.collect_seq(axes)
}
}
impl<'de> serde::Deserialize<'de> for AxisSet {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
let axes = alloc::vec::Vec::<usize>::deserialize(deserializer)?;
Ok(axes
.into_iter()
.fold(Self::EMPTY, |set, axis| set.insert(axis)))
}
}
pub trait IntoAxisSet {
fn into_axis_set(self) -> AxisSet;
}
impl IntoAxisSet for AxisSet {
fn into_axis_set(self) -> AxisSet {
self
}
}
impl IntoAxisSet for AxisMask {
fn into_axis_set(self) -> AxisSet {
self.axes()
.fold(AxisSet::EMPTY, |set, axis| set.insert(axis))
}
}
impl AxisSet {
pub const EMPTY: Self = Self(AxisSetRepr::Empty);
pub fn contains(&self, axis: usize) -> bool {
match &self.0 {
AxisSetRepr::Empty => false,
AxisSetRepr::Inline(mask) => mask.contains(axis),
AxisSetRepr::Spilled(axes) => axes.contains(&axis),
}
}
pub fn count(&self) -> usize {
match &self.0 {
AxisSetRepr::Empty => 0,
AxisSetRepr::Inline(mask) => mask.count(),
AxisSetRepr::Spilled(axes) => axes.len(),
}
}
pub fn is_empty(&self) -> bool {
match &self.0 {
AxisSetRepr::Empty => true,
AxisSetRepr::Inline(mask) => mask.is_empty(),
AxisSetRepr::Spilled(axes) => axes.is_empty(),
}
}
pub fn axes(&self) -> alloc::vec::IntoIter<usize> {
match &self.0 {
AxisSetRepr::Empty => alloc::vec::Vec::new().into_iter(),
AxisSetRepr::Inline(mask) => mask.axes().collect::<alloc::vec::Vec<_>>().into_iter(),
AxisSetRepr::Spilled(axes) => axes.clone().into_iter(),
}
}
pub fn all_below(rank: usize) -> Self {
(0..rank).fold(Self::EMPTY, |set, axis| set.insert(axis))
}
pub fn is_contiguous_run(&self) -> bool {
let axes: alloc::vec::Vec<_> = self.axes().collect();
axes.windows(2)
.all(|pair| pair[0].checked_add(1) == Some(pair[1]))
}
pub fn try_from_axes(
operation: OperationKind,
rank: usize,
axes: impl IntoIterator<Item = usize>,
) -> Result<Self, ShapeError> {
let mut set = Self::EMPTY;
for axis in axes {
if axis >= rank || set.contains(axis) {
return Err(ShapeError::InvalidParameter {
operation,
parameter: "axis",
value: axis,
});
}
set = set.insert(axis);
}
Ok(set)
}
pub fn insert(self, axis: usize) -> Self {
match self.0 {
AxisSetRepr::Empty => {
if axis < AxisMask::MAX_AXES {
Self(AxisSetRepr::Inline(AxisMask::EMPTY.insert(axis).unwrap()))
} else {
Self(AxisSetRepr::Spilled(alloc::vec![axis]))
}
}
AxisSetRepr::Inline(mask) => {
if axis < AxisMask::MAX_AXES {
Self(AxisSetRepr::Inline(mask.insert(axis).unwrap()))
} else {
let mut axes: alloc::vec::Vec<usize> = (0..AxisMask::MAX_AXES)
.filter(|&a| mask.contains(a))
.collect();
axes.push(axis);
axes.sort_unstable();
Self(AxisSetRepr::Spilled(axes))
}
}
AxisSetRepr::Spilled(mut axes) => {
if !axes.contains(&axis) {
axes.push(axis);
axes.sort_unstable();
}
Self(AxisSetRepr::Spilled(axes))
}
}
}
}
impl BitOr for AxisMask {
type Output = Self;
fn bitor(self, rhs: Self) -> Self {
Self(self.0 | rhs.0)
}
}
impl BitAnd for AxisMask {
type Output = Self;
fn bitand(self, rhs: Self) -> Self {
Self(self.0 & rhs.0)
}
}
impl BitOrAssign for AxisMask {
fn bitor_assign(&mut self, rhs: Self) {
self.0 |= rhs.0;
}
}
impl BitAndAssign for AxisMask {
fn bitand_assign(&mut self, rhs: Self) {
self.0 &= rhs.0;
}
}
impl fmt::Debug for AxisMask {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("AxisMask")?;
f.debug_set().entries(self.axes()).finish()
}
}
pub trait ExecutionDescriptor: Clone + fmt::Debug {
fn output_shape(&self) -> Option<&ShapeBuf> {
None
}
}