#[derive(Debug, Clone, PartialEq, Default)]
pub struct Model<'a> {
pub ir_version: i64,
pub opset_import: Vec<OperatorSetId<'a>>,
pub producer_name: &'a str,
pub producer_version: &'a str,
pub domain: &'a str,
pub model_version: i64,
pub doc_string: &'a str,
pub graph: Option<Graph<'a>>,
pub metadata_props: Vec<StringStringEntry<'a>>,
pub training_info: Vec<TrainingInfo<'a>>,
pub functions: Vec<Function<'a>>,
}
#[derive(Debug, Clone, PartialEq, Default)]
pub struct OperatorSetId<'a> {
pub domain: &'a str,
pub version: i64,
}
#[derive(Debug, Clone, PartialEq, Default)]
pub struct StringStringEntry<'a> {
pub key: &'a str,
pub value: &'a str,
}
#[derive(Debug, Clone, PartialEq, Default)]
pub struct Graph<'a> {
pub node: Vec<Node<'a>>,
pub name: &'a str,
pub initializer: Vec<TensorProto<'a>>,
pub sparse_initializer: Vec<SparseTensor<'a>>,
pub doc_string: &'a str,
pub input: Vec<ValueInfo<'a>>,
pub output: Vec<ValueInfo<'a>>,
pub value_info: Vec<ValueInfo<'a>>,
pub quantization_annotation: Vec<TensorAnnotation<'a>>,
pub metadata_props: Vec<StringStringEntry<'a>>,
}
#[derive(Debug, Clone, PartialEq, Default)]
pub struct Node<'a> {
pub input: Vec<&'a str>,
pub output: Vec<&'a str>,
pub name: &'a str,
pub op_type: OpType<'a>,
pub domain: &'a str,
pub overload: &'a str,
pub attribute: Vec<Attribute<'a>>,
pub doc_string: &'a str,
pub metadata_props: Vec<StringStringEntry<'a>>,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum OpType<'a> {
Relu,
LeakyRelu,
Sigmoid,
Tanh,
Softmax,
LogSoftmax,
Elu,
Selu,
PRelu,
Gelu,
HardSigmoid,
HardSwish,
Softplus,
Softsign,
ThresholdedRelu,
Celu,
Mish,
Add,
Sub,
Mul,
Div,
Neg,
Abs,
Sqrt,
Exp,
Log,
Pow,
Ceil,
Floor,
Round,
Clip,
Sign,
Reciprocal,
Mod,
BitShift,
BitwiseAnd,
BitwiseOr,
BitwiseXor,
BitwiseNot,
Min,
Max,
Mean,
Sum,
Sin,
Cos,
Tan,
Asin,
Acos,
Atan,
Sinh,
Cosh,
Asinh,
Acosh,
Atanh,
Conv,
ConvTranspose,
ConvInteger,
AveragePool,
MaxPool,
GlobalAveragePool,
GlobalMaxPool,
GlobalLpPool,
LpPool,
MaxRoiPool,
MaxUnpool,
BatchNormalization,
InstanceNormalization,
LayerNormalization,
GroupNormalization,
LpNormalization,
MeanVarianceNormalization,
MatMul,
MatMulInteger,
Gemm,
Reshape,
Transpose,
Flatten,
Squeeze,
Unsqueeze,
Expand,
Tile,
Pad,
Slice,
Split,
SplitToSequence,
Concat,
ConcatFromSequence,
DepthToSpace,
SpaceToDepth,
ReverseSequence,
Gather,
GatherElements,
GatherND,
Scatter,
ScatterElements,
ScatterND,
ReduceMax,
ReduceMin,
ReduceMean,
ReduceSum,
ReduceProd,
ReduceL1,
ReduceL2,
ReduceLogSum,
ReduceLogSumExp,
ReduceSumSquare,
ArgMax,
ArgMin,
Equal,
Greater,
GreaterOrEqual,
Less,
LessOrEqual,
Not,
And,
Or,
Xor,
Where,
IsNaN,
IsInf,
Shape,
Size,
Cast,
CastLike,
ConstantOfShape,
Range,
OneHot,
NonZero,
TopK,
Unique,
EyeLike,
Compress,
LSTM,
GRU,
RNN,
Constant,
Identity,
If,
Loop,
Scan,
Resize,
Upsample,
Dropout,
QuantizeLinear,
DequantizeLinear,
DynamicQuantizeLinear,
QLinearConv,
QLinearMatMul,
Attention,
Einsum,
SequenceConstruct,
SequenceAt,
SequenceEmpty,
SequenceInsert,
SequenceErase,
SequenceLength,
SequenceMap,
Optional,
OptionalGetElement,
OptionalHasElement,
ImageDecoder,
GridSample,
RoiAlign,
AffineGrid,
CumSum,
Det,
Erf,
Hardmax,
Shrink,
StringNormalizer,
TfIdfVectorizer,
NegativeLogLikelihoodLoss,
SoftmaxCrossEntropyLoss,
Bernoulli,
RandomNormal,
RandomNormalLike,
RandomUniform,
RandomUniformLike,
Multinomial,
CenterCropPad,
Col2Im,
Trilu,
BlackmanWindow,
HannWindow,
HammingWindow,
DFT,
MelWeightMatrix,
STFT,
RegexFullMatch,
StringConcat,
StringSplit,
Custom(&'a str),
}
impl OpType<'_> {
pub fn all() -> &'static [OpType<'static>] {
&[
OpType::Relu,
OpType::LeakyRelu,
OpType::Sigmoid,
OpType::Tanh,
OpType::Softmax,
OpType::LogSoftmax,
OpType::Elu,
OpType::Selu,
OpType::PRelu,
OpType::Gelu,
OpType::HardSigmoid,
OpType::HardSwish,
OpType::Softplus,
OpType::Softsign,
OpType::ThresholdedRelu,
OpType::Celu,
OpType::Mish,
OpType::Add,
OpType::Sub,
OpType::Mul,
OpType::Div,
OpType::Neg,
OpType::Abs,
OpType::Sqrt,
OpType::Exp,
OpType::Log,
OpType::Pow,
OpType::Ceil,
OpType::Floor,
OpType::Round,
OpType::Clip,
OpType::Sign,
OpType::Reciprocal,
OpType::Mod,
OpType::BitShift,
OpType::BitwiseAnd,
OpType::BitwiseOr,
OpType::BitwiseXor,
OpType::BitwiseNot,
OpType::Min,
OpType::Max,
OpType::Mean,
OpType::Sum,
OpType::Sin,
OpType::Cos,
OpType::Tan,
OpType::Asin,
OpType::Acos,
OpType::Atan,
OpType::Sinh,
OpType::Cosh,
OpType::Asinh,
OpType::Acosh,
OpType::Atanh,
OpType::Conv,
OpType::ConvTranspose,
OpType::ConvInteger,
OpType::AveragePool,
OpType::MaxPool,
OpType::GlobalAveragePool,
OpType::GlobalMaxPool,
OpType::GlobalLpPool,
OpType::LpPool,
OpType::MaxRoiPool,
OpType::MaxUnpool,
OpType::BatchNormalization,
OpType::InstanceNormalization,
OpType::LayerNormalization,
OpType::GroupNormalization,
OpType::LpNormalization,
OpType::MeanVarianceNormalization,
OpType::MatMul,
OpType::MatMulInteger,
OpType::Gemm,
OpType::Reshape,
OpType::Transpose,
OpType::Flatten,
OpType::Squeeze,
OpType::Unsqueeze,
OpType::Expand,
OpType::Tile,
OpType::Pad,
OpType::Slice,
OpType::Split,
OpType::SplitToSequence,
OpType::Concat,
OpType::ConcatFromSequence,
OpType::DepthToSpace,
OpType::SpaceToDepth,
OpType::ReverseSequence,
OpType::Gather,
OpType::GatherElements,
OpType::GatherND,
OpType::Scatter,
OpType::ScatterElements,
OpType::ScatterND,
OpType::ReduceMax,
OpType::ReduceMin,
OpType::ReduceMean,
OpType::ReduceSum,
OpType::ReduceProd,
OpType::ReduceL1,
OpType::ReduceL2,
OpType::ReduceLogSum,
OpType::ReduceLogSumExp,
OpType::ReduceSumSquare,
OpType::ArgMax,
OpType::ArgMin,
OpType::Equal,
OpType::Greater,
OpType::GreaterOrEqual,
OpType::Less,
OpType::LessOrEqual,
OpType::Not,
OpType::And,
OpType::Or,
OpType::Xor,
OpType::Where,
OpType::IsNaN,
OpType::IsInf,
OpType::Shape,
OpType::Size,
OpType::Cast,
OpType::CastLike,
OpType::ConstantOfShape,
OpType::Range,
OpType::OneHot,
OpType::NonZero,
OpType::TopK,
OpType::Unique,
OpType::EyeLike,
OpType::Compress,
OpType::LSTM,
OpType::GRU,
OpType::RNN,
OpType::Constant,
OpType::Identity,
OpType::If,
OpType::Loop,
OpType::Scan,
OpType::Resize,
OpType::Upsample,
OpType::Dropout,
OpType::QuantizeLinear,
OpType::DequantizeLinear,
OpType::DynamicQuantizeLinear,
OpType::QLinearConv,
OpType::QLinearMatMul,
OpType::Attention,
OpType::Einsum,
OpType::SequenceConstruct,
OpType::SequenceAt,
OpType::SequenceEmpty,
OpType::SequenceInsert,
OpType::SequenceErase,
OpType::SequenceLength,
OpType::SequenceMap,
OpType::Optional,
OpType::OptionalGetElement,
OpType::OptionalHasElement,
OpType::ImageDecoder,
OpType::GridSample,
OpType::RoiAlign,
OpType::AffineGrid,
OpType::CumSum,
OpType::Det,
OpType::Erf,
OpType::Hardmax,
OpType::Shrink,
OpType::StringNormalizer,
OpType::TfIdfVectorizer,
OpType::NegativeLogLikelihoodLoss,
OpType::SoftmaxCrossEntropyLoss,
OpType::Bernoulli,
OpType::RandomNormal,
OpType::RandomNormalLike,
OpType::RandomUniform,
OpType::RandomUniformLike,
OpType::Multinomial,
OpType::CenterCropPad,
OpType::Col2Im,
OpType::Trilu,
OpType::BlackmanWindow,
OpType::HannWindow,
OpType::HammingWindow,
OpType::DFT,
OpType::MelWeightMatrix,
OpType::STFT,
OpType::RegexFullMatch,
OpType::StringConcat,
OpType::StringSplit,
]
}
pub fn as_str(&self) -> &str {
match self {
OpType::Custom(s) => s,
other => op_type_to_str(other),
}
}
}
impl Default for OpType<'_> {
fn default() -> Self {
OpType::Custom("")
}
}
impl std::fmt::Display for OpType<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
OpType::Custom(s) => write!(f, "{s}"),
other => write!(f, "{}", op_type_to_str(other)),
}
}
}
impl<'a> From<&'a str> for OpType<'a> {
fn from(s: &'a str) -> Self {
match s {
"Relu" => OpType::Relu,
"LeakyRelu" => OpType::LeakyRelu,
"Sigmoid" => OpType::Sigmoid,
"Tanh" => OpType::Tanh,
"Softmax" => OpType::Softmax,
"LogSoftmax" => OpType::LogSoftmax,
"Elu" => OpType::Elu,
"Selu" => OpType::Selu,
"PRelu" => OpType::PRelu,
"Gelu" => OpType::Gelu,
"HardSigmoid" => OpType::HardSigmoid,
"HardSwish" => OpType::HardSwish,
"Softplus" => OpType::Softplus,
"Softsign" => OpType::Softsign,
"ThresholdedRelu" => OpType::ThresholdedRelu,
"Celu" => OpType::Celu,
"Mish" => OpType::Mish,
"Add" => OpType::Add,
"Sub" => OpType::Sub,
"Mul" => OpType::Mul,
"Div" => OpType::Div,
"Neg" => OpType::Neg,
"Abs" => OpType::Abs,
"Sqrt" => OpType::Sqrt,
"Exp" => OpType::Exp,
"Log" => OpType::Log,
"Pow" => OpType::Pow,
"Ceil" => OpType::Ceil,
"Floor" => OpType::Floor,
"Round" => OpType::Round,
"Clip" => OpType::Clip,
"Sign" => OpType::Sign,
"Reciprocal" => OpType::Reciprocal,
"Mod" => OpType::Mod,
"BitShift" => OpType::BitShift,
"BitwiseAnd" => OpType::BitwiseAnd,
"BitwiseOr" => OpType::BitwiseOr,
"BitwiseXor" => OpType::BitwiseXor,
"BitwiseNot" => OpType::BitwiseNot,
"Min" => OpType::Min,
"Max" => OpType::Max,
"Mean" => OpType::Mean,
"Sum" => OpType::Sum,
"Sin" => OpType::Sin,
"Cos" => OpType::Cos,
"Tan" => OpType::Tan,
"Asin" => OpType::Asin,
"Acos" => OpType::Acos,
"Atan" => OpType::Atan,
"Sinh" => OpType::Sinh,
"Cosh" => OpType::Cosh,
"Asinh" => OpType::Asinh,
"Acosh" => OpType::Acosh,
"Atanh" => OpType::Atanh,
"Conv" => OpType::Conv,
"ConvTranspose" => OpType::ConvTranspose,
"ConvInteger" => OpType::ConvInteger,
"AveragePool" => OpType::AveragePool,
"MaxPool" => OpType::MaxPool,
"GlobalAveragePool" => OpType::GlobalAveragePool,
"GlobalMaxPool" => OpType::GlobalMaxPool,
"GlobalLpPool" => OpType::GlobalLpPool,
"LpPool" => OpType::LpPool,
"MaxRoiPool" => OpType::MaxRoiPool,
"MaxUnpool" => OpType::MaxUnpool,
"BatchNormalization" => OpType::BatchNormalization,
"InstanceNormalization" => OpType::InstanceNormalization,
"LayerNormalization" => OpType::LayerNormalization,
"GroupNormalization" => OpType::GroupNormalization,
"LpNormalization" => OpType::LpNormalization,
"MeanVarianceNormalization" => OpType::MeanVarianceNormalization,
"MatMul" => OpType::MatMul,
"MatMulInteger" => OpType::MatMulInteger,
"Gemm" => OpType::Gemm,
"Reshape" => OpType::Reshape,
"Transpose" => OpType::Transpose,
"Flatten" => OpType::Flatten,
"Squeeze" => OpType::Squeeze,
"Unsqueeze" => OpType::Unsqueeze,
"Expand" => OpType::Expand,
"Tile" => OpType::Tile,
"Pad" => OpType::Pad,
"Slice" => OpType::Slice,
"Split" => OpType::Split,
"SplitToSequence" => OpType::SplitToSequence,
"Concat" => OpType::Concat,
"ConcatFromSequence" => OpType::ConcatFromSequence,
"DepthToSpace" => OpType::DepthToSpace,
"SpaceToDepth" => OpType::SpaceToDepth,
"ReverseSequence" => OpType::ReverseSequence,
"Gather" => OpType::Gather,
"GatherElements" => OpType::GatherElements,
"GatherND" => OpType::GatherND,
"Scatter" => OpType::Scatter,
"ScatterElements" => OpType::ScatterElements,
"ScatterND" => OpType::ScatterND,
"ReduceMax" => OpType::ReduceMax,
"ReduceMin" => OpType::ReduceMin,
"ReduceMean" => OpType::ReduceMean,
"ReduceSum" => OpType::ReduceSum,
"ReduceProd" => OpType::ReduceProd,
"ReduceL1" => OpType::ReduceL1,
"ReduceL2" => OpType::ReduceL2,
"ReduceLogSum" => OpType::ReduceLogSum,
"ReduceLogSumExp" => OpType::ReduceLogSumExp,
"ReduceSumSquare" => OpType::ReduceSumSquare,
"ArgMax" => OpType::ArgMax,
"ArgMin" => OpType::ArgMin,
"Equal" => OpType::Equal,
"Greater" => OpType::Greater,
"GreaterOrEqual" => OpType::GreaterOrEqual,
"Less" => OpType::Less,
"LessOrEqual" => OpType::LessOrEqual,
"Not" => OpType::Not,
"And" => OpType::And,
"Or" => OpType::Or,
"Xor" => OpType::Xor,
"Where" => OpType::Where,
"IsNaN" => OpType::IsNaN,
"IsInf" => OpType::IsInf,
"Shape" => OpType::Shape,
"Size" => OpType::Size,
"Cast" => OpType::Cast,
"CastLike" => OpType::CastLike,
"ConstantOfShape" => OpType::ConstantOfShape,
"Range" => OpType::Range,
"OneHot" => OpType::OneHot,
"NonZero" => OpType::NonZero,
"TopK" => OpType::TopK,
"Unique" => OpType::Unique,
"EyeLike" => OpType::EyeLike,
"Compress" => OpType::Compress,
"LSTM" => OpType::LSTM,
"GRU" => OpType::GRU,
"RNN" => OpType::RNN,
"Constant" => OpType::Constant,
"Identity" => OpType::Identity,
"If" => OpType::If,
"Loop" => OpType::Loop,
"Scan" => OpType::Scan,
"Resize" => OpType::Resize,
"Upsample" => OpType::Upsample,
"Dropout" => OpType::Dropout,
"QuantizeLinear" => OpType::QuantizeLinear,
"DequantizeLinear" => OpType::DequantizeLinear,
"DynamicQuantizeLinear" => OpType::DynamicQuantizeLinear,
"QLinearConv" => OpType::QLinearConv,
"QLinearMatMul" => OpType::QLinearMatMul,
"Attention" => OpType::Attention,
"Einsum" => OpType::Einsum,
"SequenceConstruct" => OpType::SequenceConstruct,
"SequenceAt" => OpType::SequenceAt,
"SequenceEmpty" => OpType::SequenceEmpty,
"SequenceInsert" => OpType::SequenceInsert,
"SequenceErase" => OpType::SequenceErase,
"SequenceLength" => OpType::SequenceLength,
"SequenceMap" => OpType::SequenceMap,
"Optional" => OpType::Optional,
"OptionalGetElement" => OpType::OptionalGetElement,
"OptionalHasElement" => OpType::OptionalHasElement,
"ImageDecoder" => OpType::ImageDecoder,
"GridSample" => OpType::GridSample,
"RoiAlign" => OpType::RoiAlign,
"AffineGrid" => OpType::AffineGrid,
"Cumsum" | "CumSum" => OpType::CumSum,
"Det" => OpType::Det,
"Erf" => OpType::Erf,
"Hardmax" | "HardMax" => OpType::Hardmax,
"Shrink" => OpType::Shrink,
"StringNormalizer" => OpType::StringNormalizer,
"TfIdfVectorizer" => OpType::TfIdfVectorizer,
"NegativeLogLikelihoodLoss" => OpType::NegativeLogLikelihoodLoss,
"SoftmaxCrossEntropyLoss" => OpType::SoftmaxCrossEntropyLoss,
"Bernoulli" => OpType::Bernoulli,
"RandomNormal" => OpType::RandomNormal,
"RandomNormalLike" => OpType::RandomNormalLike,
"RandomUniform" => OpType::RandomUniform,
"RandomUniformLike" => OpType::RandomUniformLike,
"Multinomial" => OpType::Multinomial,
"CenterCropPad" => OpType::CenterCropPad,
"Col2Im" => OpType::Col2Im,
"Trilu" => OpType::Trilu,
"BlackmanWindow" => OpType::BlackmanWindow,
"HannWindow" => OpType::HannWindow,
"HammingWindow" => OpType::HammingWindow,
"DFT" => OpType::DFT,
"MelWeightMatrix" => OpType::MelWeightMatrix,
"STFT" => OpType::STFT,
"RegexFullMatch" => OpType::RegexFullMatch,
"StringConcat" => OpType::StringConcat,
"StringSplit" => OpType::StringSplit,
other => OpType::Custom(other),
}
}
}
fn op_type_to_str(op: &OpType<'_>) -> &'static str {
match op {
OpType::Relu => "Relu",
OpType::LeakyRelu => "LeakyRelu",
OpType::Sigmoid => "Sigmoid",
OpType::Tanh => "Tanh",
OpType::Softmax => "Softmax",
OpType::LogSoftmax => "LogSoftmax",
OpType::Elu => "Elu",
OpType::Selu => "Selu",
OpType::PRelu => "PRelu",
OpType::Gelu => "Gelu",
OpType::HardSigmoid => "HardSigmoid",
OpType::HardSwish => "HardSwish",
OpType::Softplus => "Softplus",
OpType::Softsign => "Softsign",
OpType::ThresholdedRelu => "ThresholdedRelu",
OpType::Celu => "Celu",
OpType::Mish => "Mish",
OpType::Add => "Add",
OpType::Sub => "Sub",
OpType::Mul => "Mul",
OpType::Div => "Div",
OpType::Neg => "Neg",
OpType::Abs => "Abs",
OpType::Sqrt => "Sqrt",
OpType::Exp => "Exp",
OpType::Log => "Log",
OpType::Pow => "Pow",
OpType::Ceil => "Ceil",
OpType::Floor => "Floor",
OpType::Round => "Round",
OpType::Clip => "Clip",
OpType::Sign => "Sign",
OpType::Reciprocal => "Reciprocal",
OpType::Mod => "Mod",
OpType::BitShift => "BitShift",
OpType::BitwiseAnd => "BitwiseAnd",
OpType::BitwiseOr => "BitwiseOr",
OpType::BitwiseXor => "BitwiseXor",
OpType::BitwiseNot => "BitwiseNot",
OpType::Min => "Min",
OpType::Max => "Max",
OpType::Mean => "Mean",
OpType::Sum => "Sum",
OpType::Sin => "Sin",
OpType::Cos => "Cos",
OpType::Tan => "Tan",
OpType::Asin => "Asin",
OpType::Acos => "Acos",
OpType::Atan => "Atan",
OpType::Sinh => "Sinh",
OpType::Cosh => "Cosh",
OpType::Asinh => "Asinh",
OpType::Acosh => "Acosh",
OpType::Atanh => "Atanh",
OpType::Conv => "Conv",
OpType::ConvTranspose => "ConvTranspose",
OpType::ConvInteger => "ConvInteger",
OpType::AveragePool => "AveragePool",
OpType::MaxPool => "MaxPool",
OpType::GlobalAveragePool => "GlobalAveragePool",
OpType::GlobalMaxPool => "GlobalMaxPool",
OpType::GlobalLpPool => "GlobalLpPool",
OpType::LpPool => "LpPool",
OpType::MaxRoiPool => "MaxRoiPool",
OpType::MaxUnpool => "MaxUnpool",
OpType::BatchNormalization => "BatchNormalization",
OpType::InstanceNormalization => "InstanceNormalization",
OpType::LayerNormalization => "LayerNormalization",
OpType::GroupNormalization => "GroupNormalization",
OpType::LpNormalization => "LpNormalization",
OpType::MeanVarianceNormalization => "MeanVarianceNormalization",
OpType::MatMul => "MatMul",
OpType::MatMulInteger => "MatMulInteger",
OpType::Gemm => "Gemm",
OpType::Reshape => "Reshape",
OpType::Transpose => "Transpose",
OpType::Flatten => "Flatten",
OpType::Squeeze => "Squeeze",
OpType::Unsqueeze => "Unsqueeze",
OpType::Expand => "Expand",
OpType::Tile => "Tile",
OpType::Pad => "Pad",
OpType::Slice => "Slice",
OpType::Split => "Split",
OpType::SplitToSequence => "SplitToSequence",
OpType::Concat => "Concat",
OpType::ConcatFromSequence => "ConcatFromSequence",
OpType::DepthToSpace => "DepthToSpace",
OpType::SpaceToDepth => "SpaceToDepth",
OpType::ReverseSequence => "ReverseSequence",
OpType::Gather => "Gather",
OpType::GatherElements => "GatherElements",
OpType::GatherND => "GatherND",
OpType::Scatter => "Scatter",
OpType::ScatterElements => "ScatterElements",
OpType::ScatterND => "ScatterND",
OpType::ReduceMax => "ReduceMax",
OpType::ReduceMin => "ReduceMin",
OpType::ReduceMean => "ReduceMean",
OpType::ReduceSum => "ReduceSum",
OpType::ReduceProd => "ReduceProd",
OpType::ReduceL1 => "ReduceL1",
OpType::ReduceL2 => "ReduceL2",
OpType::ReduceLogSum => "ReduceLogSum",
OpType::ReduceLogSumExp => "ReduceLogSumExp",
OpType::ReduceSumSquare => "ReduceSumSquare",
OpType::ArgMax => "ArgMax",
OpType::ArgMin => "ArgMin",
OpType::Equal => "Equal",
OpType::Greater => "Greater",
OpType::GreaterOrEqual => "GreaterOrEqual",
OpType::Less => "Less",
OpType::LessOrEqual => "LessOrEqual",
OpType::Not => "Not",
OpType::And => "And",
OpType::Or => "Or",
OpType::Xor => "Xor",
OpType::Where => "Where",
OpType::IsNaN => "IsNaN",
OpType::IsInf => "IsInf",
OpType::Shape => "Shape",
OpType::Size => "Size",
OpType::Cast => "Cast",
OpType::CastLike => "CastLike",
OpType::ConstantOfShape => "ConstantOfShape",
OpType::Range => "Range",
OpType::OneHot => "OneHot",
OpType::NonZero => "NonZero",
OpType::TopK => "TopK",
OpType::Unique => "Unique",
OpType::EyeLike => "EyeLike",
OpType::Compress => "Compress",
OpType::LSTM => "LSTM",
OpType::GRU => "GRU",
OpType::RNN => "RNN",
OpType::Constant => "Constant",
OpType::Identity => "Identity",
OpType::If => "If",
OpType::Loop => "Loop",
OpType::Scan => "Scan",
OpType::Resize => "Resize",
OpType::Upsample => "Upsample",
OpType::Dropout => "Dropout",
OpType::QuantizeLinear => "QuantizeLinear",
OpType::DequantizeLinear => "DequantizeLinear",
OpType::DynamicQuantizeLinear => "DynamicQuantizeLinear",
OpType::QLinearConv => "QLinearConv",
OpType::QLinearMatMul => "QLinearMatMul",
OpType::Attention => "Attention",
OpType::Einsum => "Einsum",
OpType::SequenceConstruct => "SequenceConstruct",
OpType::SequenceAt => "SequenceAt",
OpType::SequenceEmpty => "SequenceEmpty",
OpType::SequenceInsert => "SequenceInsert",
OpType::SequenceErase => "SequenceErase",
OpType::SequenceLength => "SequenceLength",
OpType::SequenceMap => "SequenceMap",
OpType::Optional => "Optional",
OpType::OptionalGetElement => "OptionalGetElement",
OpType::OptionalHasElement => "OptionalHasElement",
OpType::ImageDecoder => "ImageDecoder",
OpType::GridSample => "GridSample",
OpType::RoiAlign => "RoiAlign",
OpType::AffineGrid => "AffineGrid",
OpType::CumSum => "CumSum",
OpType::Det => "Det",
OpType::Erf => "Erf",
OpType::Hardmax => "Hardmax",
OpType::Shrink => "Shrink",
OpType::StringNormalizer => "StringNormalizer",
OpType::TfIdfVectorizer => "TfIdfVectorizer",
OpType::NegativeLogLikelihoodLoss => "NegativeLogLikelihoodLoss",
OpType::SoftmaxCrossEntropyLoss => "SoftmaxCrossEntropyLoss",
OpType::Bernoulli => "Bernoulli",
OpType::RandomNormal => "RandomNormal",
OpType::RandomNormalLike => "RandomNormalLike",
OpType::RandomUniform => "RandomUniform",
OpType::RandomUniformLike => "RandomUniformLike",
OpType::Multinomial => "Multinomial",
OpType::CenterCropPad => "CenterCropPad",
OpType::Col2Im => "Col2Im",
OpType::Trilu => "Trilu",
OpType::BlackmanWindow => "BlackmanWindow",
OpType::HannWindow => "HannWindow",
OpType::HammingWindow => "HammingWindow",
OpType::DFT => "DFT",
OpType::MelWeightMatrix => "MelWeightMatrix",
OpType::STFT => "STFT",
OpType::RegexFullMatch => "RegexFullMatch",
OpType::StringConcat => "StringConcat",
OpType::StringSplit => "StringSplit",
OpType::Custom(_) => unreachable!(),
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum DataType {
#[default]
Undefined,
Float,
Uint8,
Int8,
Uint16,
Int16,
Int32,
Int64,
String,
Bool,
Float16,
Double,
Uint32,
Uint64,
Complex64,
Complex128,
Bfloat16,
Float8e4m3fn,
Float8e4m3fnuz,
Float8e5m2,
Float8e5m2fnuz,
Uint4,
Int4,
Float4e2m1,
}
impl TryFrom<i32> for DataType {
type Error = crate::error::Error;
fn try_from(value: i32) -> Result<Self, Self::Error> {
match value {
0 => Ok(DataType::Undefined),
1 => Ok(DataType::Float),
2 => Ok(DataType::Uint8),
3 => Ok(DataType::Int8),
4 => Ok(DataType::Uint16),
5 => Ok(DataType::Int16),
6 => Ok(DataType::Int32),
7 => Ok(DataType::Int64),
8 => Ok(DataType::String),
9 => Ok(DataType::Bool),
10 => Ok(DataType::Float16),
11 => Ok(DataType::Double),
12 => Ok(DataType::Uint32),
13 => Ok(DataType::Uint64),
14 => Ok(DataType::Complex64),
15 => Ok(DataType::Complex128),
16 => Ok(DataType::Bfloat16),
17 => Ok(DataType::Float8e4m3fn),
18 => Ok(DataType::Float8e4m3fnuz),
19 => Ok(DataType::Float8e5m2),
20 => Ok(DataType::Float8e5m2fnuz),
21 => Ok(DataType::Uint4),
22 => Ok(DataType::Int4),
23 => Ok(DataType::Float4e2m1),
_ => Err(crate::error::Error::InvalidEnumValue {
enum_name: "DataType",
value,
}),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum AttributeType {
#[default]
Undefined,
Float,
Int,
String,
Tensor,
Graph,
Floats,
Ints,
Strings,
Tensors,
Graphs,
SparseTensor,
SparseTensors,
TypeProto,
TypeProtos,
}
impl TryFrom<i32> for AttributeType {
type Error = crate::error::Error;
fn try_from(value: i32) -> Result<Self, Self::Error> {
match value {
0 => Ok(AttributeType::Undefined),
1 => Ok(AttributeType::Float),
2 => Ok(AttributeType::Int),
3 => Ok(AttributeType::String),
4 => Ok(AttributeType::Tensor),
5 => Ok(AttributeType::Graph),
6 => Ok(AttributeType::Floats),
7 => Ok(AttributeType::Ints),
8 => Ok(AttributeType::Strings),
9 => Ok(AttributeType::Tensors),
10 => Ok(AttributeType::Graphs),
11 => Ok(AttributeType::SparseTensor),
12 => Ok(AttributeType::SparseTensors),
13 => Ok(AttributeType::TypeProto),
14 => Ok(AttributeType::TypeProtos),
_ => Err(crate::error::Error::InvalidEnumValue {
enum_name: "AttributeType",
value,
}),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum DataLocation {
#[default]
Default,
External,
}
impl TryFrom<i32> for DataLocation {
type Error = crate::error::Error;
fn try_from(value: i32) -> Result<Self, Self::Error> {
match value {
0 => Ok(DataLocation::Default),
1 => Ok(DataLocation::External),
_ => Err(crate::error::Error::InvalidEnumValue {
enum_name: "DataLocation",
value,
}),
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub enum Dimension<'a> {
Value(i64),
Param(&'a str),
}
impl Default for Dimension<'_> {
fn default() -> Self {
Dimension::Value(0)
}
}
#[derive(Debug, Clone, PartialEq, Default)]
pub struct TensorShapeDimension<'a> {
pub value: Dimension<'a>,
pub denotation: &'a str,
}
#[derive(Debug, Clone, PartialEq, Default)]
pub struct TensorShape<'a> {
pub dim: Vec<TensorShapeDimension<'a>>,
}
#[derive(Debug, Clone, PartialEq, Default)]
pub struct TensorTypeProto<'a> {
pub elem_type: DataType,
pub shape: Option<TensorShape<'a>>,
}
#[derive(Debug, Clone, PartialEq)]
pub struct SequenceTypeProto<'a> {
pub elem_type: Box<TypeProto<'a>>,
}
#[derive(Debug, Clone, PartialEq)]
pub struct MapTypeProto<'a> {
pub key_type: DataType,
pub value_type: Box<TypeProto<'a>>,
}
#[derive(Debug, Clone, PartialEq)]
pub struct OptionalTypeProto<'a> {
pub elem_type: Box<TypeProto<'a>>,
}
#[derive(Debug, Clone, PartialEq, Default)]
pub struct SparseTensorTypeProto<'a> {
pub elem_type: DataType,
pub shape: Option<TensorShape<'a>>,
}
#[derive(Debug, Clone, PartialEq)]
pub enum TypeValue<'a> {
Tensor(TensorTypeProto<'a>),
Sequence(SequenceTypeProto<'a>),
Map(MapTypeProto<'a>),
Optional(OptionalTypeProto<'a>),
SparseTensor(SparseTensorTypeProto<'a>),
}
#[derive(Debug, Clone, PartialEq, Default)]
pub struct TypeProto<'a> {
pub value: Option<TypeValue<'a>>,
pub denotation: &'a str,
}
#[derive(Debug, Clone, PartialEq, Default)]
pub struct ValueInfo<'a> {
pub name: &'a str,
pub r#type: Option<TypeProto<'a>>,
pub doc_string: &'a str,
pub metadata_props: Vec<StringStringEntry<'a>>,
}
#[derive(Debug, Clone, PartialEq, Default)]
pub struct TensorSegment {
pub begin: i64,
pub end: i64,
}
#[derive(Debug, Clone, PartialEq, Default)]
pub struct TensorProto<'a> {
pub(crate) dims: Vec<i64>,
pub(crate) data_type: DataType,
pub(crate) segment: Option<TensorSegment>,
pub(crate) float_data: Vec<f32>,
pub(crate) int32_data: Vec<i32>,
pub(crate) string_data: Vec<&'a [u8]>,
pub(crate) int64_data: Vec<i64>,
pub(crate) raw_data: &'a [u8],
pub(crate) double_data: Vec<f64>,
pub(crate) uint64_data: Vec<u64>,
pub(crate) name: &'a str,
pub(crate) doc_string: &'a str,
pub(crate) external_data: Vec<StringStringEntry<'a>>,
pub(crate) data_location: DataLocation,
pub(crate) metadata_props: Vec<StringStringEntry<'a>>,
}
#[derive(Debug, Clone, PartialEq, Default)]
pub struct SparseTensor<'a> {
pub values: Option<TensorProto<'a>>,
pub indices: Option<TensorProto<'a>>,
pub dims: Vec<i64>,
}
#[derive(Debug, Clone, PartialEq, Default)]
pub struct TensorAnnotation<'a> {
pub tensor_name: &'a str,
pub quant_parameter_tensor_names: Vec<StringStringEntry<'a>>,
}
#[derive(Debug, Clone, PartialEq, Default)]
pub struct Attribute<'a> {
pub name: &'a str,
pub ref_attr_name: &'a str,
pub doc_string: &'a str,
pub r#type: AttributeType,
pub f: f32,
pub i: i64,
pub s: &'a [u8],
pub t: Option<TensorProto<'a>>,
pub g: Option<Box<Graph<'a>>>,
pub sparse_tensor: Option<SparseTensor<'a>>,
pub tp: Option<TypeProto<'a>>,
pub floats: Vec<f32>,
pub ints: Vec<i64>,
pub strings: Vec<&'a [u8]>,
pub tensors: Vec<TensorProto<'a>>,
pub graphs: Vec<Graph<'a>>,
pub sparse_tensors: Vec<SparseTensor<'a>>,
pub type_protos: Vec<TypeProto<'a>>,
}
#[derive(Debug, Clone, PartialEq, Default)]
pub struct TrainingInfo<'a> {
pub initialization: Option<Graph<'a>>,
pub algorithm: Option<Graph<'a>>,
pub initialization_binding: Vec<StringStringEntry<'a>>,
pub update_binding: Vec<StringStringEntry<'a>>,
}
#[derive(Debug, Clone, PartialEq, Default)]
pub struct Function<'a> {
pub name: &'a str,
pub input: Vec<&'a str>,
pub output: Vec<&'a str>,
pub attribute: Vec<&'a str>,
pub attribute_proto: Vec<Attribute<'a>>,
pub node: Vec<Node<'a>>,
pub doc_string: &'a str,
pub opset_import: Vec<OperatorSetId<'a>>,
pub domain: &'a str,
pub overload: &'a str,
pub value_info: Vec<ValueInfo<'a>>,
pub metadata_props: Vec<StringStringEntry<'a>>,
}
impl<'a> TensorProto<'a> {
pub fn from_f32(name: &'a str, dims: Vec<i64>, data: Vec<f32>) -> Self {
Self { name, dims, data_type: DataType::Float, float_data: data, ..Default::default() }
}
pub fn from_f64(name: &'a str, dims: Vec<i64>, data: Vec<f64>) -> Self {
Self { name, dims, data_type: DataType::Double, double_data: data, ..Default::default() }
}
pub fn from_i32(name: &'a str, dims: Vec<i64>, data: Vec<i32>) -> Self {
Self { name, dims, data_type: DataType::Int32, int32_data: data, ..Default::default() }
}
pub fn from_i64(name: &'a str, dims: Vec<i64>, data: Vec<i64>) -> Self {
Self { name, dims, data_type: DataType::Int64, int64_data: data, ..Default::default() }
}
pub fn from_u64(name: &'a str, dims: Vec<i64>, data: Vec<u64>) -> Self {
Self { name, dims, data_type: DataType::Uint64, uint64_data: data, ..Default::default() }
}
pub fn from_strings(name: &'a str, dims: Vec<i64>, data: Vec<&'a [u8]>) -> Self {
Self { name, dims, data_type: DataType::String, string_data: data, ..Default::default() }
}
pub fn from_raw(name: &'a str, dims: Vec<i64>, data_type: DataType, data: &'a [u8]) -> Self {
Self { name, dims, data_type, raw_data: data, ..Default::default() }
}
pub fn name(&self) -> &'a str {
self.name
}
pub fn dims(&self) -> &[i64] {
&self.dims
}
pub fn data_type(&self) -> DataType {
self.data_type
}
pub fn segment(&self) -> Option<&TensorSegment> {
self.segment.as_ref()
}
pub fn doc_string(&self) -> &'a str {
self.doc_string
}
pub fn external_data(&self) -> &[StringStringEntry<'a>] {
&self.external_data
}
pub fn data_location(&self) -> DataLocation {
self.data_location
}
pub fn metadata_props(&self) -> &[StringStringEntry<'a>] {
&self.metadata_props
}
pub fn with_segment(mut self, segment: TensorSegment) -> Self {
self.segment = Some(segment);
self
}
pub fn with_doc_string(mut self, doc_string: &'a str) -> Self {
self.doc_string = doc_string;
self
}
pub fn with_external_data(mut self, external_data: Vec<StringStringEntry<'a>>) -> Self {
self.external_data = external_data;
self
}
pub fn with_data_location(mut self, data_location: DataLocation) -> Self {
self.data_location = data_location;
self
}
pub fn with_metadata_props(mut self, metadata_props: Vec<StringStringEntry<'a>>) -> Self {
self.metadata_props = metadata_props;
self
}
pub fn as_f32(&self) -> Option<std::borrow::Cow<'_, [f32]>> {
if !self.float_data.is_empty() {
return Some(std::borrow::Cow::Borrowed(&self.float_data));
}
if !self.raw_data.is_empty() && self.data_type == DataType::Float {
return Some(std::borrow::Cow::Owned(decode_raw_f32(self.raw_data)));
}
None
}
pub fn as_f64(&self) -> Option<std::borrow::Cow<'_, [f64]>> {
if !self.double_data.is_empty() {
return Some(std::borrow::Cow::Borrowed(&self.double_data));
}
if !self.raw_data.is_empty() && self.data_type == DataType::Double {
return Some(std::borrow::Cow::Owned(decode_raw_f64(self.raw_data)));
}
None
}
pub fn as_i32(&self) -> Option<std::borrow::Cow<'_, [i32]>> {
if !self.int32_data.is_empty() {
return Some(std::borrow::Cow::Borrowed(&self.int32_data));
}
if !self.raw_data.is_empty() && self.data_type == DataType::Int32 {
return Some(std::borrow::Cow::Owned(decode_raw_i32(self.raw_data)));
}
None
}
pub fn as_i64(&self) -> Option<std::borrow::Cow<'_, [i64]>> {
if !self.int64_data.is_empty() {
return Some(std::borrow::Cow::Borrowed(&self.int64_data));
}
if !self.raw_data.is_empty() && self.data_type == DataType::Int64 {
return Some(std::borrow::Cow::Owned(decode_raw_i64(self.raw_data)));
}
None
}
pub fn as_u64(&self) -> Option<std::borrow::Cow<'_, [u64]>> {
if !self.uint64_data.is_empty() {
return Some(std::borrow::Cow::Borrowed(&self.uint64_data));
}
if !self.raw_data.is_empty() && self.data_type == DataType::Uint64 {
return Some(std::borrow::Cow::Owned(decode_raw_u64(self.raw_data)));
}
None
}
pub fn as_strings(&self) -> Option<&[&'a [u8]]> {
if !self.string_data.is_empty() {
return Some(&self.string_data);
}
None
}
pub fn as_raw(&self) -> Option<&'a [u8]> {
if !self.raw_data.is_empty() {
return Some(self.raw_data);
}
None
}
}
fn decode_raw_f32(bytes: &[u8]) -> Vec<f32> {
bytes
.chunks_exact(4)
.map(|c| f32::from_le_bytes(c.try_into().unwrap()))
.collect()
}
fn decode_raw_f64(bytes: &[u8]) -> Vec<f64> {
bytes
.chunks_exact(8)
.map(|c| f64::from_le_bytes(c.try_into().unwrap()))
.collect()
}
fn decode_raw_i32(bytes: &[u8]) -> Vec<i32> {
bytes
.chunks_exact(4)
.map(|c| i32::from_le_bytes(c.try_into().unwrap()))
.collect()
}
fn decode_raw_i64(bytes: &[u8]) -> Vec<i64> {
bytes
.chunks_exact(8)
.map(|c| i64::from_le_bytes(c.try_into().unwrap()))
.collect()
}
fn decode_raw_u64(bytes: &[u8]) -> Vec<u64> {
bytes
.chunks_exact(8)
.map(|c| u64::from_le_bytes(c.try_into().unwrap()))
.collect()
}
impl<'a> Graph<'a> {
pub fn get_initializer(&self, name: &str) -> Option<&TensorProto<'a>> {
self.initializer.iter().find(|t| t.name == name)
}
pub fn non_init_inputs(&self) -> Vec<&ValueInfo<'a>> {
self.input
.iter()
.filter(|vi| !self.initializer.iter().any(|init| init.name == vi.name))
.collect()
}
}
impl<'a> ValueInfo<'a> {
pub fn tensor_elem_type(&self) -> Option<DataType> {
match &self.r#type {
Some(tp) => match &tp.value {
Some(TypeValue::Tensor(t)) => Some(t.elem_type),
_ => None,
},
None => None,
}
}
pub fn tensor_shape(&self) -> Option<&TensorShape<'a>> {
match &self.r#type {
Some(tp) => match &tp.value {
Some(TypeValue::Tensor(t)) => t.shape.as_ref(),
_ => None,
},
None => None,
}
}
}
impl TensorShape<'_> {
pub fn rank(&self) -> usize {
self.dim.len()
}
pub fn fixed_dims(&self) -> Option<Vec<i64>> {
self.dim
.iter()
.map(|d| match &d.value {
Dimension::Value(v) => Some(*v),
Dimension::Param(_) => None,
})
.collect()
}
}