use onnx_ir_derive::NodeBuilder;
use crate::ir::{ArgType, Argument, DType, Node, RawNode, TensorType};
use crate::processor::{
InputSpec, NodeProcessor, NodeSpec, OutputPreferences, OutputSpec, ProcessError,
compute_broadcast_rank, compute_broadcast_static_shape,
};
#[derive(Debug, Clone, NodeBuilder)]
pub struct WhereNode {
pub name: String,
pub inputs: Vec<Argument>,
pub outputs: Vec<Argument>,
}
fn get_elem_type(arg_type: &ArgType) -> DType {
match arg_type {
ArgType::Scalar(elem_type) => *elem_type,
ArgType::Tensor(tensor) => tensor.dtype,
ArgType::Shape(_) => DType::I64, }
}
fn should_output_shape(x: &ArgType, y: &ArgType, output_rank: usize, dtype: &DType) -> bool {
matches!(x, ArgType::Shape(_))
&& matches!(y, ArgType::Shape(_))
&& output_rank == 1
&& *dtype == DType::I64
}
fn get_shape_size(arg_type: &ArgType) -> usize {
match arg_type {
ArgType::Shape(size) => *size,
_ => 1,
}
}
pub(crate) struct WhereProcessor;
impl NodeProcessor for WhereProcessor {
type Config = ();
fn spec(&self) -> NodeSpec {
NodeSpec {
min_opset: 9,
max_opset: None,
inputs: InputSpec::Exact(3),
outputs: OutputSpec::Exact(1),
}
}
fn infer_types(
&self,
node: &mut RawNode,
_opset: usize,
_output_preferences: &OutputPreferences,
) -> Result<(), ProcessError> {
let condition = &node.inputs[0].ty;
let x = &node.inputs[1].ty;
let y = &node.inputs[2].ty;
let x_elem_type = get_elem_type(x);
let y_elem_type = get_elem_type(y);
let condition_elem_type = get_elem_type(condition);
if !matches!(condition, ArgType::Shape(_)) && !condition_elem_type.is_bool() {
return Err(ProcessError::TypeMismatch {
expected: "Bool".to_string(),
actual: format!("{:?}", condition_elem_type),
});
}
let elem_type = if x_elem_type == y_elem_type {
x_elem_type
} else if matches!(x, ArgType::Shape(_)) {
y_elem_type
} else if matches!(y, ArgType::Shape(_)) {
x_elem_type
} else {
return Err(ProcessError::TypeMismatch {
expected: format!("{:?}", x_elem_type),
actual: format!("{:?}", y_elem_type),
});
};
let output_rank = compute_broadcast_rank(&node.inputs);
if output_rank == 0 {
node.outputs[0].ty = ArgType::Scalar(elem_type);
} else if should_output_shape(x, y, output_rank, &elem_type) {
let shape_size = get_shape_size(x).max(get_shape_size(y));
node.outputs[0].ty = ArgType::Shape(shape_size);
} else {
let static_shape = compute_broadcast_static_shape(&node.inputs);
node.outputs[0].ty = ArgType::Tensor(TensorType {
dtype: elem_type,
rank: output_rank,
static_shape,
});
}
Ok(())
}
fn build_node(&self, builder: RawNode, _opset: usize) -> Node {
Node::Where(WhereNode {
name: builder.name,
inputs: builder.inputs,
outputs: builder.outputs,
})
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::ir::NodeType;
use crate::node::test_utils::TestNodeBuilder;
fn create_test_node(condition_rank: usize, x_rank: usize, y_rank: usize) -> RawNode {
TestNodeBuilder::new(NodeType::Where, "test_where")
.input_tensor_bool("condition", condition_rank, None)
.input_tensor_f32("X", x_rank, None)
.input_tensor_f32("Y", y_rank, None)
.output_tensor_f32("output", 0, None) .build()
}
#[test]
fn test_where_basic() {
let mut node = create_test_node(2, 3, 2);
let processor = WhereProcessor;
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_where_scalar_result() {
let mut node = create_test_node(0, 0, 0);
let processor = WhereProcessor;
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"),
}
}
#[test]
fn test_where_invalid_condition() {
let mut node = create_test_node(2, 2, 2);
let non_bool_input = TestNodeBuilder::new(NodeType::Identity, "temp")
.input_tensor_f32("x", 2, None)
.build()
.inputs
.pop()
.unwrap();
node.inputs[0] = non_bool_input;
let processor = WhereProcessor;
let prefs = OutputPreferences::new();
let result = processor.infer_types(&mut node, 16, &prefs);
assert!(matches!(result, Err(ProcessError::TypeMismatch { .. })));
}
#[test]
fn test_where_mismatched_types() {
let mut node = create_test_node(2, 2, 2);
let int64_input = TestNodeBuilder::new(NodeType::Identity, "temp")
.input_tensor_i64("y", 2, None)
.build()
.inputs
.pop()
.unwrap();
node.inputs[2] = int64_input;
let processor = WhereProcessor;
let prefs = OutputPreferences::new();
let result = processor.infer_types(&mut node, 16, &prefs);
assert!(matches!(result, Err(ProcessError::TypeMismatch { .. })));
}
#[test]
fn test_where_with_shape_inputs() {
let mut node = create_test_node(1, 0, 0);
node.inputs[1].ty = ArgType::Shape(3);
node.inputs[2].ty = ArgType::Shape(3);
let processor = WhereProcessor;
let prefs = OutputPreferences::new();
processor.infer_types(&mut node, 16, &prefs).unwrap();
match &node.outputs[0].ty {
ArgType::Shape(size) => {
assert_eq!(*size, 3); }
_ => panic!("Expected Shape output"),
}
}
#[test]
fn test_where_static_shape_propagation() {
let mut node = TestNodeBuilder::new(NodeType::Where, "test_where")
.input_tensor_bool("condition", 2, Some(vec![2, 2]))
.input_tensor_f32("X", 2, Some(vec![2, 2]))
.input_tensor_f32("Y", 2, Some(vec![2, 2]))
.output_tensor_f32("output", 0, None)
.build();
let processor = WhereProcessor;
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, 2);
assert_eq!(tensor.static_shape, Some(vec![2, 2]));
}
_ => panic!("Expected tensor output"),
}
}
#[test]
fn test_where_static_shape_propagation_partial() {
let mut node = TestNodeBuilder::new(NodeType::Where, "test_where")
.input_tensor_bool("condition", 2, None) .input_tensor_f32("X", 2, Some(vec![3, 4])) .input_tensor_f32("Y", 2, Some(vec![3, 4])) .output_tensor_f32("output", 0, None)
.build();
let processor = WhereProcessor;
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, 2);
assert_eq!(tensor.static_shape, Some(vec![3, 4]));
}
_ => panic!("Expected tensor output"),
}
}
}