1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
//! Onnx node helpers.

pub mod ops;

use std::cell::RefCell;
use std::rc::Rc;

use onnx_pb::{Axes, NodeProto};

use crate::builder::Bag;

/// Node wrapper.
#[derive(Clone)]
pub struct Node {
    pub(crate) inner: Rc<RefCell<NodeProto>>,
    pub(crate) bag: Option<Bag>,
}

impl Node {
    /// Creates new node from proto.
    pub fn from_proto(inner: NodeProto) -> Self {
        Node {
            bag: None,
            inner: Rc::new(RefCell::new(inner)),
        }
    }

    /// Returns node name.
    pub fn name(&self) -> String {
        self.inner.borrow().name.clone()
    }

    /// Renames output names accordingly.
    pub fn with_name<N: Into<String>>(self, name: N) -> Self {
        let name = name.into();
        let mut bag = self.bag.clone();
        {
            let mut inner = self.inner.borrow_mut();
            inner
                .output
                .iter_mut()
                .enumerate()
                .for_each(|(index, output)| {
                    let name = format!("{}{}", name, index);
                    maybe_bag_rename(&mut bag, &output, &name);
                    *output = name;
                });
            maybe_bag_rename(&mut bag, &inner.name, &name);
            inner.name = name;
        }
        self
    }

    /// Creates new absolute operation.
    pub fn abs(&self) -> Node {
        let mut node: Node = ops::Abs::new(self.select_output()).into();
        maybe_bag_node(self.bag.clone(), &mut node);
        node
    }

    /// Creates new square root operation.
    pub fn sqrt(&self) -> Node {
        let mut node: Node = ops::Sqrt::new(self.select_output()).into();
        maybe_bag_node(self.bag.clone(), &mut node);
        node
    }

    /// Creates new power operation.
    pub fn pow<T: Into<String>>(&self, power: T) -> Node {
        let mut node: Node = ops::Pow::new(self.select_output(), power).into();
        maybe_bag_node(self.bag.clone(), &mut node);
        node
    }

    /// Creates new reduce sum operation.
    pub fn sum<A: Into<Axes>>(&self, axes: A, keepdims: bool) -> Node {
        let mut node: Node = ops::ReduceSum::new(self.select_output(), axes, keepdims).into();
        maybe_bag_node(self.bag.clone(), &mut node);
        node
    }

    /// Creates new reduce max operation.
    pub fn max<A: Into<Axes>>(&self, axes: A, keepdims: bool) -> Node {
        let mut node: Node = ops::ReduceMax::new(self.select_output(), axes, keepdims).into();
        maybe_bag_node(self.bag.clone(), &mut node);
        node
    }

    /// Creates new reduce mean operation.
    pub fn mean<A: Into<Axes>>(&self, axes: A, keepdims: bool) -> Node {
        let mut node: Node = ops::ReduceMean::new(self.select_output(), axes, keepdims).into();
        maybe_bag_node(self.bag.clone(), &mut node);
        node
    }

    /// Creates new reduce min operation.
    pub fn min<A: Into<Axes>>(&self, axes: A, keepdims: bool) -> Node {
        let mut node: Node = ops::ReduceMin::new(self.select_output(), axes, keepdims).into();
        maybe_bag_node(self.bag.clone(), &mut node);
        node
    }

    /// Creates new equal comparison operation.
    pub fn equal<Rhs: Into<String>>(&self, right: Rhs) -> Node {
        let mut node: Node = ops::Equal::new(self.select_output(), right).into();
        maybe_bag_node(self.bag.clone(), &mut node);
        node
    }

    /// Creates new greater comparison operation.
    pub fn greater<Rhs: Into<String>>(&self, right: Rhs) -> Node {
        let mut node: Node = ops::Greater::new(self.select_output(), right).into();
        maybe_bag_node(self.bag.clone(), &mut node);
        node
    }

    /// Creates new less comparison operation.
    pub fn less<Rhs: Into<String>>(&self, right: Rhs) -> Node {
        let mut node: Node = ops::Less::new(self.select_output(), right).into();
        maybe_bag_node(self.bag.clone(), &mut node);
        node
    }

    /// Creates new logical and operation.
    pub fn and<Rhs: Into<String>>(&self, right: Rhs) -> Node {
        let mut node: Node = ops::And::new(self.select_output(), right).into();
        maybe_bag_node(self.bag.clone(), &mut node);
        node
    }

    /// Creates new logical or operation.
    pub fn or<Rhs: Into<String>>(&self, right: Rhs) -> Node {
        let mut node: Node = ops::Or::new(self.select_output(), right).into();
        maybe_bag_node(self.bag.clone(), &mut node);
        node
    }

    /// Creates new relu activation operation.
    pub fn relu(&self) -> Node {
        let mut node: Node = ops::Relu::new(self.select_output()).into();
        maybe_bag_node(self.bag.clone(), &mut node);
        node
    }

    /// Creates new tanh activation operation.
    pub fn tanh(&self) -> Node {
        let mut node: Node = ops::Tanh::new(self.select_output()).into();
        maybe_bag_node(self.bag.clone(), &mut node);
        node
    }

    /// Creates new size operation.
    pub fn size(&self) -> Node {
        let mut node: Node = ops::Size::new(self.select_output()).into();
        maybe_bag_node(self.bag.clone(), &mut node);
        node
    }

    #[inline]
    fn select_output(&self) -> String {
        let node = self.inner.borrow();
        if node.op_type.is_empty() {
            node.name.clone()
        } else {
            node.output.first().unwrap().to_owned()
        }
    }
}

#[macro_export]
macro_rules! impl_nodes_op {
    ( $t:ident, $k:ident, $f:ident ) => {
        impl<Rhs: AsRef<Node>> std::ops::$k<Rhs> for $t {
            type Output = Node;

            #[inline(always)]
            fn $f(self, rhs: Rhs) -> Self::Output {
                let mut node: Node = ops::$k::new(self.select_output(), rhs.as_ref()).into();
                maybe_bag_node(self.bag.clone(), &mut node);
                node
            }
        }

        impl<Rhs: AsRef<Node>> std::ops::$k<Rhs> for &$t {
            type Output = Node;

            #[inline(always)]
            fn $f(self, rhs: Rhs) -> Self::Output {
                let mut node: Node = ops::$k::new(self.select_output(), rhs.as_ref()).into();
                maybe_bag_node(self.bag.clone(), &mut node);
                node
            }
        }
    };
}

#[macro_export]
macro_rules! impl_node_op {
    ( $t:ident, $k:ident, $f:ident ) => {
        impl std::ops::$k for &$t {
            type Output = Node;

            #[inline(always)]
            fn $f(self) -> Self::Output {
                let mut node: Node = ops::$k::new(self.select_output()).into();
                maybe_bag_node(self.bag.clone(), &mut node);
                node
            }
        }

        impl std::ops::$k for $t {
            type Output = Node;

            #[inline(always)]
            fn $f(self) -> Self::Output {
                let mut node: Node = ops::$k::new(self.select_output()).into();
                maybe_bag_node(self.bag.clone(), &mut node);
                node
            }
        }
    };
}

impl_nodes_op!(Node, Add, add);
impl_nodes_op!(Node, Sub, sub);
impl_nodes_op!(Node, Mul, mul);
impl_nodes_op!(Node, Div, div);
impl_node_op!(Node, Neg, neg);
impl_node_op!(Node, Not, not);

impl From<NodeProto> for Node {
    fn from(inner: NodeProto) -> Self {
        Node::from_proto(inner)
    }
}

impl Into<NodeProto> for Node {
    fn into(self) -> NodeProto {
        self.inner.borrow().clone()
    }
}

impl From<Node> for String {
    fn from(node: Node) -> String {
        node.select_output()
    }
}

impl From<&Node> for String {
    fn from(node: &Node) -> String {
        node.select_output()
    }
}

impl AsRef<Node> for Node {
    #[inline(always)]
    fn as_ref(&self) -> &Node {
        &self
    }
}

#[inline(always)]
pub(crate) fn maybe_bag_node(bag: Option<Bag>, node: &mut Node) {
    if let Some(mut bag) = bag {
        node.bag = Some(bag.clone());
        bag.node(node.inner.clone());
    }
}

#[inline(always)]
pub(crate) fn maybe_bag_rename(bag: &mut Option<Bag>, name: &str, new_name: &str) {
    if let Some(bag) = bag.as_mut() {
        bag.rename(name, new_name);
    }
}