use derive_new::new;
use onnx_ir_derive::NodeBuilder;
use crate::ir::{
ArgType, Argument, DType, Node, RawNode, RuntimeInputRef, TensorData, TensorDataExt, TensorType,
};
use crate::processor::{
InputSpec, NodeProcessor, NodeSpec, OutputPreferences, OutputSpec, ProcessError,
};
#[derive(Debug, Clone, NodeBuilder)]
pub struct ConstantOfShapeNode {
pub name: String,
pub inputs: Vec<Argument>,
pub outputs: Vec<Argument>,
pub config: ConstantOfShapeConfig,
}
#[derive(Debug, Clone, new)]
pub struct ConstantOfShapeConfig {
pub shape: ConstantOfShapeShape,
pub value: Option<TensorData>,
}
#[derive(Debug, Clone)]
pub enum ConstantOfShapeShape {
Static(Vec<i64>),
Runtime(RuntimeInputRef),
}
impl Default for ConstantOfShapeShape {
fn default() -> Self {
Self::Static(vec![])
}
}
pub(crate) struct ConstantOfShapeProcessor;
impl NodeProcessor for ConstantOfShapeProcessor {
type Config = ConstantOfShapeConfig;
fn spec(&self) -> NodeSpec {
NodeSpec {
min_opset: 9,
max_opset: None,
inputs: InputSpec::Exact(1),
outputs: OutputSpec::Exact(1),
}
}
fn lift_constants(&self, node: &mut RawNode, _opset: usize) -> Result<(), ProcessError> {
if !node.inputs.is_empty() && node.inputs[0].is_constant() {
node.inputs[0].to_static()?;
}
Ok(())
}
fn infer_types(
&self,
node: &mut RawNode,
_opset: usize,
_output_preferences: &OutputPreferences,
) -> Result<(), ProcessError> {
match &node.inputs[0].ty {
ArgType::Tensor(tensor) => {
if tensor.rank != 1 {
return Err(ProcessError::Custom(
"ConstantOfShape: shape tensor must be 1D".to_string(),
));
}
if !matches!(tensor.dtype, DType::I64) {
return Err(ProcessError::TypeMismatch {
expected: "Int64".to_string(),
actual: format!("{:?}", tensor.dtype),
});
}
}
ArgType::Shape(_) => {
}
_ => {
return Err(ProcessError::TypeMismatch {
expected: "Tensor or Shape".to_string(),
actual: format!("{:?}", node.inputs[0].ty),
});
}
}
let _config = self
.extract_config(node, _opset)
.expect("Config extraction failed");
let value_type = node
.attrs
.get("value")
.map(|v| v.clone().into_tensor().elem_type())
.unwrap_or(DType::F32);
let rank = match &node.inputs[0].ty {
ArgType::Shape(rank) => *rank,
ArgType::Tensor(tensor_type) => {
if let Some(tensor_data) = node.inputs[0].value() {
match tensor_data.to_i64_vec() {
Ok(shape_vec) => shape_vec.len(),
Err(_) => {
return Err(ProcessError::Custom(format!(
"ConstantOfShape node {} requires Int32 or Int64 shape input",
node.name
)));
}
}
} else if let Some(shape) = &tensor_type.static_shape {
shape.first().copied().ok_or_else(|| {
ProcessError::Custom(
"ConstantOfShape node must have a non-empty static shape value"
.to_string(),
)
})?
} else {
return Err(ProcessError::Custom(format!(
"ConstantOfShape node {} must have either a constant value or a static shape",
node.name
)));
}
}
_ => {
return Err(ProcessError::TypeMismatch {
expected: "Tensor or Shape".to_string(),
actual: format!("{:?}", node.inputs[0].ty),
});
}
};
node.inputs[0].ty = ArgType::Shape(rank);
if rank == 1 && value_type == DType::I64 {
if let Some(input_value) = node.inputs[0].value() {
if let Ok(shape_vec) = input_value.to_i64_vec() {
if !shape_vec.is_empty() {
let output_size = shape_vec[0] as usize;
node.outputs[0].ty = ArgType::Shape(output_size);
} else {
node.outputs[0].ty = ArgType::Scalar(value_type);
}
} else {
node.outputs[0].ty = ArgType::Tensor(TensorType {
dtype: value_type,
rank,
static_shape: None,
});
}
} else {
node.outputs[0].ty = ArgType::Tensor(TensorType {
dtype: value_type,
rank,
static_shape: None,
});
}
} else if rank == 0 {
node.outputs[0].ty = ArgType::Scalar(value_type);
} else {
node.outputs[0].ty = ArgType::Tensor(TensorType {
dtype: value_type,
rank,
static_shape: None,
});
}
Ok(())
}
fn extract_config(&self, node: &RawNode, _opset: usize) -> Result<Self::Config, ProcessError> {
let shape = match node.inputs[0].value() {
Some(tensor_data) => match tensor_data.to_i64_vec() {
Ok(shape) => ConstantOfShapeShape::Static(shape),
Err(_) => {
return Err(ProcessError::Custom(format!(
"ConstantOfShape node {} requires Int32 or Int64 shape data",
node.name
)));
}
},
None => {
ConstantOfShapeShape::Runtime(RuntimeInputRef::new(node.inputs[0].name.clone(), 0))
}
};
let value = node.attrs.get("value").map(|v| v.clone().into_tensor());
let config = ConstantOfShapeConfig { shape, value };
Ok(config)
}
fn build_node(&self, builder: RawNode, opset: usize) -> Node {
let config = self
.extract_config(&builder, opset)
.expect("Config extraction failed");
Node::ConstantOfShape(ConstantOfShapeNode {
name: builder.name,
inputs: builder.inputs,
outputs: builder.outputs,
config,
})
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::ir::{AttributeValue, NodeType, TensorData};
use crate::node::test_utils::TestNodeBuilder;
fn create_test_node(input_ty: ArgType) -> TestNodeBuilder {
TestNodeBuilder::new(NodeType::ConstantOfShape, "test_constantofshape")
.add_input("shape", input_ty)
.output_tensor_f32("output", 0, None) }
#[test]
fn test_shape_input() {
let mut node = create_test_node(ArgType::Shape(3)).build();
let processor = ConstantOfShapeProcessor;
let prefs = OutputPreferences::new();
processor.infer_types(&mut node, 16, &prefs).unwrap();
match &node.outputs[0].ty {
ArgType::Tensor(tensor) => {
assert_eq!(tensor.dtype, DType::F32);
assert_eq!(tensor.rank, 3);
}
_ => panic!("Expected tensor output"),
}
}
#[test]
fn test_tensor_input_with_static_shape() {
let mut node = create_test_node(ArgType::Tensor(TensorType {
dtype: DType::I64,
rank: 1,
static_shape: Some(vec![4]),
}))
.build();
let processor = ConstantOfShapeProcessor;
let prefs = OutputPreferences::new();
processor.infer_types(&mut node, 16, &prefs).unwrap();
match &node.outputs[0].ty {
ArgType::Tensor(tensor) => {
assert_eq!(tensor.dtype, DType::F32);
assert_eq!(tensor.rank, 4);
}
_ => panic!("Expected tensor output"),
}
}
#[test]
fn test_custom_value_type() {
let mut node = create_test_node(ArgType::Shape(2)).build();
node.attrs.insert(
"value".to_string(),
AttributeValue::Tensor(TensorData::new(vec![7i64], vec![])),
);
let processor = ConstantOfShapeProcessor;
let prefs = OutputPreferences::new();
processor.infer_types(&mut node, 16, &prefs).unwrap();
match &node.outputs[0].ty {
ArgType::Tensor(tensor) => {
assert_eq!(tensor.dtype, DType::I64);
assert_eq!(tensor.rank, 2);
}
_ => panic!("Expected tensor output"),
}
}
#[test]
fn test_invalid_input_type() {
let mut node = create_test_node(ArgType::Scalar(DType::F32)).build();
let processor = ConstantOfShapeProcessor;
let prefs = OutputPreferences::new();
let result = processor.infer_types(&mut node, 16, &prefs);
assert!(matches!(result, Err(ProcessError::TypeMismatch { .. })));
}
#[test]
fn test_no_static_shapes_with_value_attr() {
let mut node = TestNodeBuilder::new(NodeType::ConstantOfShape, "constantofshape1")
.input_tensor_i64_data("constant180_out1", vec![2, 3, 4], vec![3])
.output_default("/model/encoder/patch_encoder/ConstantOfShape_output_0")
.attr_tensor("value", TensorData::new(vec![1i64], vec![1]))
.build_with_graph_data(16);
let processor = ConstantOfShapeProcessor;
let prefs = OutputPreferences::new();
processor.infer_types(&mut node, 16, &prefs).unwrap();
match &node.outputs[0].ty {
ArgType::Tensor(tensor) => {
assert_eq!(tensor.dtype, DType::I64);
assert_eq!(tensor.rank, 3); }
_ => panic!("Expected tensor output"),
}
}
#[test]
fn test_scalar_output_with_shape_0() {
let mut node = create_test_node(ArgType::Shape(0)).build();
let processor = ConstantOfShapeProcessor;
let prefs = OutputPreferences::new();
processor.infer_types(&mut node, 16, &prefs).unwrap();
match &node.outputs[0].ty {
ArgType::Scalar(elem_type) => {
assert_eq!(*elem_type, DType::F32);
}
_ => panic!("Expected scalar output for rank 0 input"),
}
}
#[test]
fn test_scalar_output_with_tensor_shape_0() {
let mut node = create_test_node(ArgType::Tensor(TensorType {
dtype: DType::I64,
rank: 1,
static_shape: Some(vec![0]), }))
.build();
let processor = ConstantOfShapeProcessor;
let prefs = OutputPreferences::new();
processor.infer_types(&mut node, 16, &prefs).unwrap();
match &node.outputs[0].ty {
ArgType::Scalar(elem_type) => {
assert_eq!(*elem_type, DType::F32);
}
_ => panic!("Expected scalar output for rank 0 input"),
}
}
#[test]
fn test_scalar_output_with_custom_value() {
let mut node = create_test_node(ArgType::Shape(0)).build();
node.attrs.insert(
"value".to_string(),
AttributeValue::Tensor(TensorData::new(vec![42i64], vec![])),
);
let processor = ConstantOfShapeProcessor;
let prefs = OutputPreferences::new();
processor.infer_types(&mut node, 16, &prefs).unwrap();
match &node.outputs[0].ty {
ArgType::Scalar(elem_type) => {
assert_eq!(*elem_type, DType::I64);
}
_ => panic!("Expected scalar output for rank 0 input"),
}
}
#[test]
fn test_shape_optimization_with_int64() {
let mut node = TestNodeBuilder::new(NodeType::ConstantOfShape, "test_constantofshape")
.input_tensor_i64_data("shape", vec![5i64], vec![1]) .output_tensor_f32("output", 0, None)
.attr_tensor("value", TensorData::new(vec![1i64], vec![]))
.build_with_graph_data(16);
node.inputs[0].ty = ArgType::Shape(1);
let processor = ConstantOfShapeProcessor;
let prefs = OutputPreferences::new();
processor.infer_types(&mut node, 16, &prefs).unwrap();
match &node.outputs[0].ty {
ArgType::Shape(size) => {
assert_eq!(*size, 5);
}
_ => {
panic!("Expected Shape(5) output for Shape(1) input with value [5] and Int64 fill")
}
}
}
#[test]
fn test_shape_1_with_float_no_optimization() {
let mut node = create_test_node(ArgType::Shape(1)).build();
node.attrs.insert(
"value".to_string(),
AttributeValue::Tensor(TensorData::new(vec![1.5f32], vec![])),
);
let processor = ConstantOfShapeProcessor;
let prefs = OutputPreferences::new();
processor.infer_types(&mut node, 16, &prefs).unwrap();
match &node.outputs[0].ty {
ArgType::Tensor(tensor) => {
assert_eq!(tensor.dtype, DType::F32);
assert_eq!(tensor.rank, 1);
}
_ => panic!("Expected Tensor output for Shape(1) input with Float32 value"),
}
}
#[test]
fn test_shape_1_default_value_no_optimization() {
let mut node = create_test_node(ArgType::Shape(1)).build();
let processor = ConstantOfShapeProcessor;
let prefs = OutputPreferences::new();
processor.infer_types(&mut node, 16, &prefs).unwrap();
match &node.outputs[0].ty {
ArgType::Tensor(tensor) => {
assert_eq!(tensor.dtype, DType::F32);
assert_eq!(tensor.rank, 1);
}
_ => panic!("Expected Tensor output for Shape(1) input with default Float32 value"),
}
}
}