Skip to main content

onnx_ir/node/
bitshift.rs

1//! # BitShift
2//!
3//! Performs element-wise bitwise shift operation.
4//!
5//! **ONNX Spec**: <https://onnx.ai/onnx/operators/onnx__BitShift.html>
6//!
7//! ## Type Constraints
8//! - T in (tensor(uint8), tensor(uint16), tensor(uint32), tensor(uint64))
9//!
10//! ## Broadcasting
11//! This operator supports multidirectional (i.e., Numpy-style) broadcasting.
12//!
13//! ## Opset Versions
14//! - **Opset 11**: Initial version with left/right bitwise shift operations on unsigned integers
15//!
16//! ## Examples
17//! - If direction is "RIGHT", X = [1, 4], and Y = [1, 1], output Z = [0, 2]
18//! - If direction is "LEFT", X = [1, 2], and Y = [1, 2], output Z = [2, 8]
19use derive_new::new;
20use onnx_ir_derive::NodeBuilder;
21
22use crate::ir::Argument;
23
24use crate::ir::{Node, RawNode};
25use crate::processor::{
26    InputSpec, NodeProcessor, NodeSpec, OutputPreferences, OutputSpec, ProcessError,
27};
28
29/// Direction for BitShift operation
30#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
31pub enum Direction {
32    #[default]
33    Left,
34    Right,
35}
36
37impl Direction {
38    fn from_str(s: &str) -> Result<Self, String> {
39        match s.to_lowercase().as_str() {
40            "left" => Ok(Direction::Left),
41            "right" => Ok(Direction::Right),
42            _ => Err(format!("Invalid bit shift direction: {s}")),
43        }
44    }
45}
46
47/// Configuration for BitShift operation
48#[derive(Debug, Clone, new)]
49pub struct BitShiftConfig {
50    pub direction: Direction,
51}
52
53/// Node representation for BitShift operation
54#[derive(Debug, Clone, NodeBuilder)]
55pub struct BitShiftNode {
56    pub name: String,
57    pub inputs: Vec<Argument>,
58    pub outputs: Vec<Argument>,
59    pub config: BitShiftConfig,
60}
61
62pub(crate) struct BitShiftProcessor;
63
64impl NodeProcessor for BitShiftProcessor {
65    type Config = BitShiftConfig;
66
67    fn spec(&self) -> NodeSpec {
68        NodeSpec {
69            min_opset: 11,
70            max_opset: None,
71            inputs: InputSpec::Exact(2),
72            outputs: OutputSpec::Exact(1),
73        }
74    }
75
76    fn infer_types(
77        &self,
78        node: &mut RawNode,
79        opset: usize,
80        _output_preferences: &OutputPreferences,
81    ) -> Result<(), ProcessError> {
82        // Validate node attributes
83        let _ = self.extract_config(node, opset)?;
84
85        // Output type is same as input with broadcasting
86        crate::processor::same_as_input_broadcast(node);
87
88        Ok(())
89    }
90
91    fn extract_config(&self, node: &RawNode, _opset: usize) -> Result<Self::Config, ProcessError> {
92        // Extract direction attribute
93        let direction_str = node
94            .attrs
95            .get("direction")
96            .map(|val| val.clone().into_string())
97            .transpose()?
98            .ok_or_else(|| ProcessError::MissingAttribute("direction".to_string()))?;
99
100        let direction =
101            Direction::from_str(&direction_str).map_err(|e| ProcessError::InvalidAttribute {
102                name: "direction".to_string(),
103                reason: e,
104            })?;
105
106        let config = BitShiftConfig { direction };
107        Ok(config)
108    }
109
110    fn build_node(&self, builder: RawNode, opset: usize) -> Result<Node, ProcessError> {
111        let config = self.extract_config(&builder, opset)?;
112
113        Ok(Node::BitShift(BitShiftNode {
114            name: builder.name,
115            inputs: builder.inputs,
116            outputs: builder.outputs,
117            config,
118        }))
119    }
120}
121
122#[cfg(test)]
123mod tests {
124    use super::*;
125    use crate::ir::NodeType;
126    use crate::node::test_utils::TestNodeBuilder;
127
128    #[test]
129    fn test_bitshift_config_with_direction_left() {
130        let node = TestNodeBuilder::new(NodeType::BitShift, "test_bitshift")
131            .input_tensor_i32("X", 2, None)
132            .input_tensor_i32("Y", 2, None)
133            .output_tensor_i32("Z", 2, None)
134            .attr_string("direction", "left")
135            .build();
136
137        let mut node = node;
138        let processor = BitShiftProcessor;
139        let prefs = OutputPreferences::new();
140        let config = processor.extract_config(&node, 16).unwrap();
141        processor.infer_types(&mut node, 16, &prefs).unwrap();
142        assert_eq!(config.direction, Direction::Left);
143    }
144
145    #[test]
146    fn test_bitshift_config_with_direction_right() {
147        let node = TestNodeBuilder::new(NodeType::BitShift, "test_bitshift")
148            .input_tensor_i32("X", 2, None)
149            .input_tensor_i32("Y", 2, None)
150            .output_tensor_i32("Z", 2, None)
151            .attr_string("direction", "right")
152            .build();
153
154        let mut node = node;
155        let processor = BitShiftProcessor;
156        let prefs = OutputPreferences::new();
157        let config = processor.extract_config(&node, 16).unwrap();
158        processor.infer_types(&mut node, 16, &prefs).unwrap();
159        assert_eq!(config.direction, Direction::Right);
160    }
161
162    #[test]
163    fn test_bitshift_config_default_direction() {
164        let node = TestNodeBuilder::new(NodeType::BitShift, "test_bitshift")
165            .input_tensor_i32("X", 2, None)
166            .input_tensor_i32("Y", 2, None)
167            .output_tensor_i32("Z", 2, None)
168            .build();
169
170        let processor = BitShiftProcessor;
171        let extract_result = processor.extract_config(&node, 16);
172        assert!(matches!(
173            extract_result,
174            Err(ProcessError::MissingAttribute(ref s)) if s == "direction"
175        ));
176    }
177}