use core::fmt;
macro_rules! define_operation_kind {
($(($variant:ident, $name:literal, $family:ident, $profile:ident, $attrs:ident, $min:expr, $max:expr, $legacy:literal),)*) => {
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, serde::Serialize, serde::Deserialize)]
pub enum OperationKind {
Storage,
Fill,
Random,
Pointwise,
Reduction,
Normalization,
Broadcast,
Reshape,
Flatten,
Squeeze,
Unsqueeze,
Permute,
Transpose,
Slice,
Concat,
Stack,
MatMul,
Conv1d,
Conv2d,
Pool1d,
Pool2d,
AdaptiveAvgPool2d,
Embedding,
$(
#[doc = concat!("Canonical semantic operation `", $name, "`.")]
$variant,
)*
}
};
}
incin_operation_catalog!(define_operation_kind);
macro_rules! impl_catalog_operation_kind {
($(($variant:ident, $name:literal, $family:ident, $profile:ident, $attrs:ident, $min:expr, $max:expr, $legacy:literal),)*) => {
impl OperationKind {
#[must_use]
pub const fn is_exact(self) -> bool {
matches!(self, $(Self::$variant)|*)
}
const fn exact_family(self) -> Option<Self> {
match self {
$(Self::$variant => Some(Self::$family),)*
_ => None,
}
}
const fn exact_name(self) -> Option<&'static str> {
match self {
$(Self::$variant => Some($name),)*
_ => None,
}
}
}
};
}
incin_operation_catalog!(impl_catalog_operation_kind);
impl OperationKind {
#[must_use]
pub const fn family(self) -> Self {
if let Some(family) = self.exact_family() {
return family;
}
match self {
Self::Storage
| Self::Broadcast
| Self::Reshape
| Self::Flatten
| Self::Squeeze
| Self::Unsqueeze
| Self::Permute
| Self::Transpose
| Self::Slice
| Self::Concat
| Self::Stack
| Self::Embedding => Self::Storage,
Self::Fill => Self::Fill,
Self::Random => Self::Random,
Self::Pointwise => Self::Pointwise,
Self::Reduction
| Self::MatMul
| Self::Conv1d
| Self::Conv2d
| Self::Pool1d
| Self::Pool2d
| Self::AdaptiveAvgPool2d => Self::Reduction,
Self::Normalization => Self::Normalization,
_ => Self::Storage,
}
}
#[must_use]
pub const fn name(self) -> &'static str {
if let Some(name) = self.exact_name() {
return name;
}
match self {
Self::Storage => "storage",
Self::Fill => "fill",
Self::Random => "random",
Self::Pointwise => "pointwise",
Self::Reduction => "reduction",
Self::Normalization => "normalization",
Self::Broadcast => "broadcast",
Self::Reshape => "reshape",
Self::Flatten => "flatten",
Self::Squeeze => "squeeze",
Self::Unsqueeze => "unsqueeze",
Self::Permute => "permute",
Self::Transpose => "transpose",
Self::Slice => "slice",
Self::Concat => "concat",
Self::Stack => "stack",
Self::MatMul => "matmul",
Self::Conv1d => "conv1d",
Self::Conv2d => "conv2d",
Self::Pool1d => "pool1d",
Self::Pool2d => "pool2d",
Self::AdaptiveAvgPool2d => "adaptive_avg_pool2d",
Self::Embedding => "embedding",
_ => "unknown_operation",
}
}
}
impl fmt::Display for OperationKind {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.name())
}
}
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Axis {
Index(usize),
Named(&'static str),
Whole,
}
impl fmt::Display for Axis {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Index(i) => write!(f, "axis {i}"),
Self::Named(name) => write!(f, "axis '{name}'"),
Self::Whole => f.write_str("the shape as a whole"),
}
}
}
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum RankExpectation {
Exactly(usize),
AtLeast(usize),
AtMost(usize),
Between {
min: usize,
max: usize,
},
SameAs {
operand: &'static str,
rank: usize,
},
}
impl fmt::Display for RankExpectation {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Exactly(n) => write!(f, "exactly {n}"),
Self::AtLeast(n) => write!(f, "at least {n}"),
Self::AtMost(n) => write!(f, "at most {n}"),
Self::Between { min, max } => write!(f, "between {min} and {max}"),
Self::SameAs { operand, rank } => write!(f, "the same rank as {operand} ({rank})"),
}
}
}
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum DimensionConstraint {
Equal,
Broadcastable,
DivisibleBy,
AtLeast,
}
impl DimensionConstraint {
#[must_use]
pub const fn describe(self) -> &'static str {
match self {
Self::Equal => "equal",
Self::Broadcastable => "equal, or one of them 1",
Self::DivisibleBy => "an exact multiple",
Self::AtLeast => "greater than or equal",
}
}
}
impl fmt::Display for DimensionConstraint {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.describe())
}
}
#[non_exhaustive]
#[derive(thiserror::Error, Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ShapeError {
#[error("{operation}: expected rank {expected}, got {actual}")]
RankMismatch {
operation: OperationKind,
expected: RankExpectation,
actual: usize,
},
#[error("{operation}: {axis} mismatch: {lhs} vs {rhs}, which must be {constraint}")]
DimensionMismatch {
operation: OperationKind,
axis: Axis,
lhs: usize,
rhs: usize,
constraint: DimensionConstraint,
},
#[error("{operation}: axis range {start}..{end} is invalid for rank {rank}")]
InvalidAxisRange {
operation: OperationKind,
start: usize,
end: usize,
rank: usize,
},
#[error("{operation}: parameter '{parameter}' has invalid value {value}")]
InvalidParameter {
operation: OperationKind,
parameter: &'static str,
value: usize,
},
#[error("{operation}: arithmetic overflow evaluating '{expression}'")]
ArithmeticOverflow {
operation: OperationKind,
expression: &'static str,
},
#[error("{operation}: the computed rank-{rank} shape does not fit the target shape type")]
TargetShapeRejected {
operation: OperationKind,
rank: usize,
},
#[error("axis {axis} is invalid for rank {rank}")]
InvalidAxis {
axis: usize,
rank: usize,
},
#[error("axis {axis} specified multiple times in selector sequence")]
DuplicateAxis {
axis: usize,
},
#[error("named axis '{name}' is not present in the shape")]
MissingNamedAxis {
name: &'static str,
},
#[error("named axis '{name}' is ambiguous: it occurs more than once")]
AmbiguousNamedAxis {
name: &'static str,
},
#[error("broadcast axis {axis} has conflicting names '{lhs}' and '{rhs}'")]
ConflictingNamedAxes {
axis: usize,
lhs: &'static str,
rhs: &'static str,
},
#[error("{operation}: {axis} would have length 0")]
EmptyOutput {
operation: OperationKind,
axis: Axis,
},
}
impl ShapeError {
#[must_use]
pub const fn operation(&self) -> OperationKind {
match self {
Self::RankMismatch { operation, .. }
| Self::DimensionMismatch { operation, .. }
| Self::InvalidAxisRange { operation, .. }
| Self::InvalidParameter { operation, .. }
| Self::ArithmeticOverflow { operation, .. }
| Self::TargetShapeRejected { operation, .. }
| Self::EmptyOutput { operation, .. } => *operation,
_ => OperationKind::Storage,
}
}
pub const fn axis(&self) -> Option<Axis> {
match self {
Self::DimensionMismatch { axis, .. } | Self::EmptyOutput { axis, .. } => Some(*axis),
Self::InvalidAxis { axis, .. } | Self::DuplicateAxis { axis } => {
Some(Axis::Index(*axis))
}
_ => None,
}
}
}