Exemplo n.º 1
0
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.
    returns 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, {})
Exemplo n.º 2
0
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.
    returns 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, {})
Exemplo n.º 3
0
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
        },
    )
Exemplo n.º 4
0
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
        },
    )
Exemplo n.º 5
0
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})
Exemplo n.º 6
0
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)], {})
Exemplo n.º 7
0
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})
Exemplo n.º 8
0
def shuffle_channels(data: Node,
                     axis: int,
                     group: int,
                     name: Optional[str] = None) -> Node:
    """Perform permutation on data in the channel dimension of the input tensor.

    @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.

    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:

    @code{.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.]]]]
    @endcode
    """
    return _get_node_factory_opset3().create("ShuffleChannels",
                                             [as_node(data)], {
                                                 "axis": axis,
                                                 "group": group
                                             })
Exemplo n.º 9
0
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})
Exemplo n.º 10
0
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})
Exemplo n.º 11
0
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,
        },
    )
Exemplo n.º 12
0
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.
    returns 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, {})
Exemplo n.º 13
0
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.
    returns ReadValue node
    """
    return _get_node_factory_opset3().create(
        "ReadValue",
        [as_node(init_value)],
        {"variable_id": variable_id}
    )
Exemplo n.º 14
0
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.

    returns The new node which performs NonZero
    """
    return _get_node_factory_opset3().create(
        "NonZero",
        [as_node(data)],
        {"output_type": output_type}
    )
Exemplo n.º 15
0
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()})
Exemplo n.º 16
0
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.

    @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.
    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{.py}
        # just required ones
        attrs = {
            'offset': 85,
        }
        attrs = {
            'offset': 85,
            'flip': True,
            'clip': True,
            'fixed_size': [32, 64, 128]
        }
    @endcode
    Optional attributes which are absent from dictionary will be set with corresponding default.
    """
    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)
Exemplo n.º 17
0
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{.py}
        # 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],
        }
    @endcode
    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)
Exemplo n.º 18
0
 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