utils.py 4.17 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements.  See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership.  The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License.  You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied.  See the License for the
# specific language governing permissions and limitations
# under the License.
# pylint: disable=eval-used,invalid-name,too-many-arguments
"""Utility functions"""
from tvm import relay
Zhi committed
20
from tvm.relay import transform
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


def has_multiple_inputs(node_list, node_idx, input_names):
    """Check whether a node has multiple input nodes
    except variable nodes.

    Parameters
    ----------
    node_list : list of dict of str to object
        List of all nodes in a graph.

    node_idx : int
        Node index to be checked.

    input_names : list of str
        List of input names of graph.

    Returns
    -------
    out : bool
        Whether the specified node has multiple input nodes
    """
    num_inputs = 0
    node = node_list[node_idx]
    for in_idx in node["inputs"]:
        in_idx = in_idx[0]
        in_node = node_list[in_idx]
        # Exclude parameter nodes
49 50
        if in_node["op"] != "null" or \
                ("name" in in_node and in_node["name"] in input_names):
51 52 53 54
            num_inputs += 1
    return num_inputs > 1


55 56 57 58
def is_boundary_node(node_entry, input_names):
    """Whether a node is a boundary node.
    Currently input node and nodes in LAYOUT_FIXED_OP are
    counted as boundary.
59 60 61 62 63 64 65 66 67 68 69 70

    Parameters
    ----------
    node_entry : dict
        Node entry.

    input_names : list of str
        List of input names of graph.

    Returns
    -------
    out : bool
71
        whether node is a boundary node.
72
    """
73 74 75 76 77 78
    # Operators dependent on original layouts.
    _LAYOUT_FIXED_OP = ["batch_flatten", "transpose", "reshape",
                        "multibox_prior", "multibox_transform_loc", "where",
                        "non_max_suppression", "strided_slice"]

    out = node_entry["op"] in _LAYOUT_FIXED_OP or \
79 80
          ("name" in node_entry and node_entry["name"] in input_names)
    return out
81 82


83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
def is_skipped_node(node_entry):
    """Whether a node is not counted.

    Parameters
    ----------
    node_entry : dict
        Node entry.

    Returns
    -------
    out : bool
        whether node is skipped.
    """
    # Operators not counted in graph tuner.
    _SKIPPED_OP = ["Tuple"]

    return node_entry["op"] in _SKIPPED_OP


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
def bind_inputs(expr, input_shapes=None, input_dtypes="float32"):
    """Bind input variables of a relay function expression
    to new shapes and/or dtypes.

    Parameters
    ----------
    expr : tvm.relay.Expr.Function
        Input relay function expression.

    input_shapes : dict of str to tuple of int, optional
        Input shapes.

    input_dtypes : str or dict of str to str, optional
        Input dtypes.

    Returns
    -------
    out : tvm.relay.Expr.Function
        Bind relay function expression.
    """
    if input_shapes is None:
        return expr
    if isinstance(input_dtypes, str):
        input_dtypes = {key : input_dtypes for key in input_shapes.keys()}

    updated_input_dict = {}
    for input_name in input_shapes.keys():
        updated_input = relay.var(input_name, shape=input_shapes[input_name],
                                  dtype=input_dtypes[input_name])
        updated_input_dict[input_name] = updated_input

    rebind_dict = {}
    for var in expr.params:
        if var.name_hint in updated_input_dict:
            rebind_dict[var] = updated_input_dict[var.name_hint]
    updated_expr = relay.expr.bind(expr, rebind_dict)

Zhi committed
139 140
    mod = relay.Module.from_expr(updated_expr)
    mod = transform.InferType()(mod)
141
    entry = mod["main"]
Zhi committed
142
    return entry if isinstance(updated_expr, relay.Function) else entry.body