def embedding_bag_offsets_sum( emb_table: Node, indices: NodeInput, offsets: NodeInput, default_index: Optional[NodeInput] = None, per_sample_weights: Optional[NodeInput] = None, name: Optional[str] = None, ) -> Node: """Return a node which performs sums of bags of embeddings without the intermediate embeddings. :param emb_table: Tensor containing the embedding lookup table. :param indices: Tensor with indices. :param offsets: Tensor containing the starting index positions of each bag in indices. :param per_sample_weights: Tensor with weights for each sample. :param default_index: Scalar containing default index in embedding table to fill empty bags. :param name: Optional name for output node. :return: The new node which performs EmbeddingBagOffsetsSum """ inputs = [emb_table, as_node(indices), as_node(offsets)] if per_sample_weights is not None: inputs.append(default_index) inputs.append(per_sample_weights) elif default_index is not None: inputs.append(default_index) return _get_node_factory_opset3().create("EmbeddingBagOffsetsSum", inputs, {})
def embedding_segments_sum( emb_table: Node, indices: NodeInput, segment_ids: NodeInput, num_segments: Optional[NodeInput] = None, default_index: Optional[NodeInput] = None, per_sample_weights: Optional[NodeInput] = None, name: Optional[str] = None, ) -> Node: """Return an EmbeddingSegmentsSum node. EmbeddingSegmentsSum constructs an output tensor by replacing every index in a given input tensor with a row (from the weights matrix) at that index :param emb_table: Tensor containing the embedding lookup table. :param indices: Tensor with indices. :param segment_ids: Tensor with indices into the output Tensor :param num_segments: Tensor with number of segments. :param default_index: Scalar containing default index in embedding table to fill empty bags. :param per_sample_weights: Weights to be multiplied with embedding table. :param name: Optional name for output node. :return: EmbeddingSegmentsSum node """ inputs = [as_node(emb_table), as_node(indices), as_node(segment_ids)] if per_sample_weights is not None: inputs.append(as_node(num_segments)) inputs.append(as_node(default_index)) inputs.append(as_node(per_sample_weights)) elif default_index is not None: inputs.append(as_node(num_segments)) inputs.append(as_node(default_index)) elif num_segments is not None: inputs.append(as_node(num_segments)) return _get_node_factory_opset3().create("EmbeddingSegmentsSum", inputs, {})
def elu(data, alpha, name=None): # type: (NodeInput, NodeInput, str) -> Node """Perform Exponential Linear Unit operation element-wise on data from input node. Computes exponential linear: alpha * (exp(data) - 1) if < 0, data otherwise. For more information refer to: `Fast and Accurate Deep Network Learning by Exponential Linear Units (ELUs) <http://arxiv.org/abs/1511.07289>`_ :param data: Input tensor. One of: input node, array or scalar. :param alpha: Multiplier for negative values. One of: input node or scalar value. :param name: Optional output node name. :return: The new node performing an ELU operation on its input data element-wise. """ return Elu(as_node(data), as_node(alpha))
def extract_image_patches( image: NodeInput, sizes: TensorShape, strides: List[int], rates: TensorShape, auto_pad: str, name: Optional[str] = None, ) -> Node: """! Return a node which produces the ExtractImagePatches operation. @param image: 4-D Input data to extract image patches. @param sizes: Patch size in the format of [size_rows, size_cols]. @param strides: Patch movement stride in the format of [stride_rows, stride_cols] @param rates: Element seleciton rate for creating a patch. @param auto_pad: Padding type. @param name: Optional name for output node. @return ExtractImagePatches node """ return _get_node_factory_opset3().create( "ExtractImagePatches", [as_node(image)], { "sizes": sizes, "strides": strides, "rates": rates, "auto_pad": auto_pad }, )
def clamp(data, min_value, max_value, name=None): # type: (NodeInput, ScalarData, ScalarData, str) -> Node """Perform clamp element-wise on data from input node. Performs a clipping operation on an input value between a pair of boundary values. For each element in :code:`data`, if the element's value is lower than :code:`min_value`, it will be replaced with :code:`min_value`. If the value is higher than :code:`max_value`, it will be replaced by :code:`max_value`. Intermediate values of :code:`data` are returned without change. Clamp uses the following logic: .. code-block:: python if data < min_value: data=min_value elif data > max_value: data=max_value :param data: Input tensor. One of: input node, array or scalar. :param min_value: The lower bound of the <min_value;max_value> range. Scalar value. :param max_value: The upper bound of the <min_value;max_value> range. Scalar value. :param name: Optional output node name. :return: The new node performing a clamp operation on its input data element-wise. """ return Clamp(as_node(data), min_value, max_value)
def bucketize( data: Node, buckets: NodeInput, output_type: str = "i64", with_right_bound: bool = True, name: Optional[str] = None, ) -> Node: """! Return a node which produces the Bucketize operation. @param data: Input data to bucketize @param buckets: 1-D of sorted unique boundaries for buckets @param output_type: Output tensor type, "i64" or "i32", defaults to i64 @param with_right_bound: indicates whether bucket includes the right or left edge of interval. default true = includes right edge @param name: Optional name for output node. @return Bucketize node """ return _get_node_factory_opset3().create( "Bucketize", [data, as_node(buckets)], { "output_type": output_type, "with_right_bound": with_right_bound }, )
def softsign(node: NodeInput, name: Optional[str] = None) -> Node: """Apply SoftSign operation on the input node element-wise. :param node: One of: input node, array or scalar. :param name: The optional name for the output node. :return: New node with SoftSign operation applied on each element of it. """ return _get_node_factory_opset9().create("SoftSign", [as_node(node)], {})
def log_softmax(data: NodeInput, axis: int, name: Optional[str] = None) -> Node: """Apply LogSoftmax operation on each element of input tensor. :param data: The tensor providing input data. :param axis: An axis along which LogSoftmax should be calculated :return: The new node with LogSoftmax operation applied on each element. """ return _get_node_factory_opset5().create("LogSoftmax", [as_node(data)], {"axis": axis})
def softmax(data: NodeInput, axis: int, name: Optional[str] = None) -> Node: """Apply softmax operation on each element of input tensor. :param data: The tensor providing input data. :param axis: An axis along which Softmax should be calculated. Can be positive or negative. :param name: Optional name for the node :return: The new node with softmax operation applied on each element. """ return _get_node_factory_opset8().create("Softmax", [as_node(data)], {"axis": axis})
def shuffle_channels(data: Node, axis: int, groups: int, name: Optional[str] = None) -> Node: """! Perform permutation on data in the channel dimension of the input tensor. The operation is the equivalent with the following transformation of the input tensor `data` of shape [N, C, H, W]: `data_reshaped` = reshape(`data`, [N, group, C / group, H * W]) `data_trnasposed` = transpose(`data_reshaped`, [0, 2, 1, 3]) `output` = reshape(`data_trnasposed`, [N, C, H, W]) For example: ~~~~~~~~~~~~~{.py} Inputs: tensor of shape [1, 6, 2, 2] data = [[[[ 0., 1.], [ 2., 3.]], [[ 4., 5.], [ 6., 7.]], [[ 8., 9.], [10., 11.]], [[12., 13.], [14., 15.]], [[16., 17.], [18., 19.]], [[20., 21.], [22., 23.]]]] axis = 1 groups = 3 Output: tensor of shape [1, 6, 2, 2] output = [[[[ 0., 1.], [ 2., 3.]], [[ 8., 9.], [10., 11.]], [[16., 17.], [18., 19.]], [[ 4., 5.], [ 6., 7.]], [[12., 13.], [14., 15.]], [[20., 21.], [22., 23.]]]] ~~~~~~~~~~~~~ @param data: The node with input tensor. @param axis: Channel dimension index in the data tensor. A negative value means that the index should be calculated from the back of the input data shape. @param group: The channel dimension specified by the axis parameter should be split into this number of groups. @param name: Optional output node name. @return The new node performing a permutation on data in the channel dimension of the input tensor. """ return _get_node_factory_opset3().create("ShuffleChannels", [as_node(data)], { "axis": axis, "groups": groups })
def shape_of(data: NodeInput, output_type: str = "i64", name: Optional[str] = None) -> Node: """! Return a node which produces a tensor containing the shape of its input data. @param data: The tensor containing the input data. @param output_type: Output element type. @return ShapeOf node """ return _get_node_factory_opset3().create("ShapeOf", [as_node(data)], {"output_type": output_type})
def assign(new_value: NodeInput, variable_id: str, name: Optional[str] = None) -> Node: """Return a node which produces the Assign operation. @param new_value: Node producing a value to be assigned to a variable. @param variable_id: Id of a variable to be updated. @param name: Optional name for output node. @return Assign node """ return _get_node_factory_opset6().create("Assign", [as_node(new_value)], {"variable_id": variable_id})
def max_pool( data: NodeInput, strides: List[int], dilations: List[int], pads_begin: List[int], pads_end: List[int], kernel_shape: TensorShape, rounding_type: str = "floor", auto_pad: Optional[str] = None, index_element_type: Optional[str] = "i64", axis: Optional[int] = 0, name: Optional[str] = None, ) -> Node: """Perform max pooling operation and return both values and indices of the selected elements. :param data: The node providing input data. :param strides: The distance (in pixels) to slide the filter on the feature map over the axes. :param dilations: The dilation of filter elements(distance between elements). :param pads_begin: The number of pixels to add at the beginning along each axis. :param pads_end: The number of pixels to add at the end along each axis. :param kernel_shape: The pooling operation kernel shape. :param rounding_type: Determines used rounding schema when computing output shape. Acceptable values are: ['floor', 'ceil']. Defaults to 'floor'. :param auto_pad: Determines how the padding is calculated. Acceptable values: [None, 'same_upper', 'same_lower', 'valid']. Defaults to None. :param index_element_type: The data type used for the indices output of this operator. Defaults to i64. :param axis: The first dimension in the data shape used to determine the maximum returned index value. The value is the product of all dimensions starting at the provided axis. Defaults to 0. :param name: The optional name for the created output node. :return: The new node performing max pooling operation. """ if auto_pad is None: auto_pad = "explicit" return _get_node_factory_opset8().create( "MaxPool", [as_node(data)], { "strides": strides, "dilations": dilations, "pads_begin": pads_begin, "pads_end": pads_end, "kernel": kernel_shape, "rounding_type": rounding_type.upper(), "auto_pad": auto_pad.upper(), "index_element_type": index_element_type, "axis": axis, }, )
def read_value(init_value: NodeInput, variable_id: str, name: Optional[str] = None) -> Node: """Return a node which produces the Assign operation. @param init_value: Node producing a value to be returned instead of an unassigned variable. @param variable_id: Id of a variable to be read. @param name: Optional name for output node. @return ReadValue node """ return _get_node_factory_opset6().create("ReadValue", [as_node(init_value)], {"variable_id": variable_id})
def non_zero(data: NodeInput, output_type: str = "i64", name: Optional[str] = None,) -> Node: """Return the indices of the elements that are non-zero. :param data: Input data. :param output_type: Output tensor type. :return: The new node which performs NonZero """ return _get_node_factory_opset3().create( "NonZero", [as_node(data)], {"output_type": output_type} )
def embedding_bag_packed_sum( emb_table: NodeInput, indices: NodeInput, per_sample_weights: Optional[NodeInput] = None, name: Optional[str] = None, ) -> Node: """Return an EmbeddingBagPackedSum node. EmbeddingSegmentsSum constructs an output tensor by replacing every index in a given input tensor with a row (from the weights matrix) at that index :param emb_table: Tensor containing the embedding lookup table. :param indices: Tensor with indices. :param per_sample_weights: Weights to be multiplied with embedding table. :param name: Optional name for output node. :return: EmbeddingBagPackedSum node """ inputs = [as_node(emb_table), as_node(indices)] if per_sample_weights is not None: inputs.append(as_node(per_sample_weights)) return _get_node_factory_opset3().create("EmbeddingBagPackedSum", inputs, {})
def gelu(node, name=None): # type: (NodeInput, str) -> Node r"""Perform Gaussian Error Linear Unit operation element-wise on data from input node. Computes GELU function: .. math:: f(x) = 0.5\cdot x\cdot(1 + erf( \dfrac{x}{\sqrt{2}}) For more information refer to: `Gaussian Error Linear Unit (GELU) <https://arxiv.org/pdf/1606.08415.pdf>`_ :param node: Input tensor. One of: input node, array or scalar. :param name: Optional output node name. :return: The new node performing a GELU operation on its input data element-wise. """ return Gelu(as_node(node))
def unsqueeze(data, axes, name=None): # type: (Node, NodeInput, str) -> Node """Perform unsqueeze operation on input tensor. Insert single-dimensional entries to the shape of a tensor. Takes one required argument axes, a list of dimensions that will be inserted. Dimension indices in axes are as seen in the output tensor. For example: Inputs: tensor with shape [3, 4, 5], axes=[0, 4] Result: tensor with shape [1, 3, 4, 5, 1] :param data: The node with data tensor. :param axes: List of non-negative integers, indicate the dimensions to be inserted. One of: input node or array. :return: The new node performing an unsqueeze operation on input tensor. """ return Unsqueeze(data, as_node(axes))
def broadcast( data: NodeInput, target_shape: NodeInput, axes_mapping: Optional[NodeInput] = None, broadcast_spec: str = "NUMPY", name: Optional[str] = None, ) -> Node: """! Create a node which broadcasts the input node's values along specified axes to a desired shape. @param data: The node with input tensor data. @param target_shape: The node with a new shape we want to broadcast tensor to. @param axes_mapping: The node with a axis positions (0-based) in the result that are being broadcast. @param broadcast_spec: The type of broadcasting that specifies mapping of input tensor axes to output shape axes. Range of values: NUMPY, EXPLICIT, BIDIRECTIONAL. @param name: Optional new name for output node. @return New node with broadcast shape. """ inputs = as_nodes(data, target_shape) if broadcast_spec.upper() == "EXPLICIT": inputs.append(as_node(axes_mapping)) return _get_node_factory_opset3().create("Broadcast", inputs, {"mode": broadcast_spec.upper()})
def proposal( class_probs: Node, bbox_deltas: Node, image_shape: NodeInput, attrs: dict, name: Optional[str] = None, ) -> Node: """Filter bounding boxes and outputs only those with the highest prediction confidence. :param class_probs: 4D input floating point tensor with class prediction scores. :param bbox_deltas: 4D input floating point tensor with corrected predictions of bounding boxes :param image_shape: The 1D input tensor with 3 or 4 elements describing image shape. :param attrs: The dictionary containing key, value pairs for attributes. :param name: Optional name for the output node. * base_size The size of the anchor to which scale and ratio attributes are applied. Range of values: a positive unsigned integer number Default value: None Required: yes * pre_nms_topn The number of bounding boxes before the NMS operation. Range of values: a positive unsigned integer number Default value: None Required: yes * post_nms_topn The number of bounding boxes after the NMS operation. Range of values: a positive unsigned integer number Default value: None Required: yes * nms_thresh The minimum value of the proposal to be taken into consideration. Range of values: a positive floating-point number Default value: None Required: yes * feat_stride The step size to slide over boxes (in pixels). Range of values: a positive unsigned integer Default value: None Required: yes * min_size The minimum size of box to be taken into consideration. Range of values: a positive unsigned integer number Default value: None Required: yes * ratio The ratios for anchor generation. Range of values: a list of floating-point numbers Default value: None Required: yes * scale The scales for anchor generation. Range of values: a list of floating-point numbers Default value: None Required: yes * clip_before_nms The flag that specifies whether to perform clip bounding boxes before non-maximum suppression or not. Range of values: True or False Default value: True Required: no * clip_after_nms The flag that specifies whether to perform clip bounding boxes after non-maximum suppression or not. Range of values: True or False Default value: False Required: no * normalize The flag that specifies whether to perform normalization of output boxes to [0,1] interval or not. Range of values: True or False Default value: False Required: no * box_size_scale Specifies the scale factor applied to logits of box sizes before decoding. Range of values: a positive floating-point number Default value: 1.0 Required: no * box_coordinate_scale Specifies the scale factor applied to logits of box coordinates before decoding. Range of values: a positive floating-point number Default value: 1.0 Required: no * framework Specifies how the box coordinates are calculated. Range of values: "" (empty string) - calculate box coordinates like in Caffe* tensorflow - calculate box coordinates like in the TensorFlow* Object Detection API models Default value: "" (empty string) Required: no Example of attribute dictionary: .. code-block:: python # just required ones attrs = { 'base_size': 85, 'pre_nms_topn': 10, 'post_nms_topn': 20, 'nms_thresh': 0.34, 'feat_stride': 16, 'min_size': 32, 'ratio': [0.1, 1.5, 2.0, 2.5], 'scale': [2, 3, 3, 4], } Optional attributes which are absent from dictionary will be set with corresponding default. :return: Node representing Proposal operation. """ requirements = [ ("base_size", True, np.unsignedinteger, is_positive_value), ("pre_nms_topn", True, np.unsignedinteger, is_positive_value), ("post_nms_topn", True, np.unsignedinteger, is_positive_value), ("nms_thresh", True, np.floating, is_positive_value), ("feat_stride", True, np.unsignedinteger, is_positive_value), ("min_size", True, np.unsignedinteger, is_positive_value), ("ratio", True, np.floating, None), ("scale", True, np.floating, None), ("clip_before_nms", False, np.bool_, None), ("clip_after_nms", False, np.bool_, None), ("normalize", False, np.bool_, None), ("box_size_scale", False, np.floating, is_positive_value), ("box_coordinate_scale", False, np.floating, is_positive_value), ("framework", False, np.str_, None), ] check_valid_attributes("Proposal", attrs, requirements) return _get_node_factory_opset4().create( "Proposal", [class_probs, bbox_deltas, as_node(image_shape)], attrs)
def prior_box(layer_shape: Node, image_shape: NodeInput, attrs: dict, name: Optional[str] = None) -> Node: """Generate prior boxes of specified sizes and aspect ratios across all dimensions. Available attributes are: * min_size The minimum box size (in pixels). Range of values: positive floating point numbers Default value: [] Required: no * max_size The maximum box size (in pixels). Range of values: positive floating point numbers Default value: [] Required: no * aspect_ratio Aspect ratios of prior boxes. Range of values: set of positive floating point numbers Default value: [] Required: no * flip The flag that denotes that each aspect_ratio is duplicated and flipped. Range of values: {True, False} Default value: False Required: no * clip The flag that denotes if each value in the output tensor should be clipped to [0,1] interval. Range of values: {True, False} Default value: False Required: no * step The distance between box centers. Range of values: floating point non-negative number Default value: 0 Required: no * offset This is a shift of box respectively to top left corner. Range of values: floating point non-negative number Default value: None Required: yes * variance The variance denotes a variance of adjusting bounding boxes. The attribute could contain 0, 1 or 4 elements. Range of values: floating point positive numbers Default value: [] Required: no * scale_all_sizes The flag that denotes type of inference. Range of values: False - max_size is ignored True - max_size is used Default value: True Required: no * fixed_ratio This is an aspect ratio of a box. Range of values: a list of positive floating-point numbers Default value: None Required: no * fixed_size This is an initial box size (in pixels). Range of values: a list of positive floating-point numbers Default value: None Required: no * density This is the square root of the number of boxes of each type. Range of values: a list of positive floating-point numbers Default value: None Required: no * min_max_aspect_ratios_order The flag that denotes the order of output prior box. Range of values: False - the output prior box is in order of [min, aspect_ratios, max] True - the output prior box is in order of [min, max, aspect_ratios] Default value: True Required: no Example of attribute dictionary: .. code-block:: python # just required ones attrs = { 'offset': 85, } attrs = { 'offset': 85, 'flip': True, 'clip': True, 'fixed_size': [32, 64, 128] } Optional attributes which are absent from dictionary will be set with corresponding default. :param layer_shape: Shape of layer for which prior boxes are computed. :param image_shape: Shape of image to which prior boxes are scaled. :param attrs: The dictionary containing key, value pairs for attributes. :param name: Optional name for the output node. :return: Node representing prior box operation. """ requirements = [ ("offset", True, np.floating, is_non_negative_value), ("min_size", False, np.floating, is_positive_value), ("max_size", False, np.floating, is_positive_value), ("aspect_ratio", False, np.floating, is_positive_value), ("flip", False, np.bool_, None), ("clip", False, np.bool_, None), ("step", False, np.floating, is_non_negative_value), ("variance", False, np.floating, is_positive_value), ("scale_all_sizes", False, np.bool_, None), ("fixed_ratio", False, np.floating, is_positive_value), ("fixed_size", False, np.floating, is_positive_value), ("density", False, np.floating, is_positive_value), ("min_max_aspect_ratios_order", False, np.bool_, None), ] check_valid_attributes("PriorBox", attrs, requirements) return _get_node_factory_opset8().create( "PriorBox", [layer_shape, as_node(image_shape)], attrs)
def wrapper(input_value: NodeInput, *args: Any, **kwargs: Any) -> Node: input_node = as_node(input_value) node = node_factory_function(input_node, *args, **kwargs) node = _set_node_friendly_name(node, **kwargs) return node
def absolute(node, name=None): # type: (NodeInput, str) -> Node """Return node which applies f(x) = abs(x) to the input node elementwise.""" node = as_node(node) return Abs(node)
def wrapper(input_value, *args, **kwargs): # type: (NodeInput, *Any, **Any) -> Node input_node = as_node(input_value) node = node_factory_function(input_node, *args, **kwargs) node = _set_node_name(node, **kwargs) return node