nnvm_integration.py 6.56 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
# 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.
17 18 19 20 21
# pylint: disable=unused-variable,invalid-name
"""
Decorator and utilities for the integration with TOPI and NNVM

"""
22
import threading
23
import warnings
24 25
import logging

26

27 28
from .task import create
from .topi_integration import TaskExtractEnv
29

30
logger = logging.getLogger('autotvm')
31 32


33
def extract_from_graph(graph, shape, dtype, target, symbols, params=None, target_host=None):
34 35
    """ Extract tuning tasks from a nnvm graph.

36
    This function collects tuning tasks by building the graph
37
    and trace all the calls to topi.
38 39 40 41 42

    Parameters
    ----------
    graph : Graph
        The graph to tune
43
    shape : dict of str to tuple
44 45 46 47 48 49
        The input shape to the graph
    dtype : str or dict of str to str
        The input types to the graph
    target: tvm.target.Target
        The compilation target
    symbols : Array of nnvm.symbol
50
        Array of nnvm symbols want to be tuned
51 52
    params : dict of str to NDArray
        The parameter dictionary.
53 54 55 56 57 58 59 60 61
    target_host: tvm.target.Target
        The host compilation target

    Returns
    -------
    task: Array of autotvm.task.Task
        collected tasks
    """
    import nnvm.compiler
62 63
    import nnvm
    import topi
64 65 66

    env = TaskExtractEnv.get()

67 68
    # NOTE: To add more symbols, you only need to change the following lists
    # nnvm symbol -> topi compute
69 70 71 72 73 74 75
    SYMBOL2TOPI = {
        nnvm.sym.conv2d: [topi.nn.conv2d, topi.nn.depthwise_conv2d_nchw,
                          topi.nn.group_conv2d_nchw],
        nnvm.sym.conv2d_transpose: [topi.nn.conv2d_transpose_nchw],
        nnvm.sym.dense: [topi.nn.dense],
    }

76 77
    topi_funcs = []
    for sym_name in symbols:
78 79
        if sym_name in SYMBOL2TOPI:
            topi_funcs.extend(SYMBOL2TOPI[sym_name])
80 81 82 83
        else:
            warnings.warn("Symbol %s is not tunable, ignored" % sym_name)

    # run compiler to collect all TOPI calls during compilation
84
    env.reset(topi_funcs)
85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
    with env:
        # disable logger temporarily
        old_state = logger.disabled
        logger.disabled = True

        nnvm.compiler.engine.clear_cache()
        # wrap build call in thread to avoid multiprocessing problems
        build_thread = threading.Thread(target=nnvm.compiler.build,
                                        args=(graph,
                                              target,
                                              shape,
                                              dtype,
                                              params,
                                              target_host))
        build_thread.start()
        build_thread.join()

        logger.disabled = old_state
103

104 105 106
    # create tasks for target
    tasks = []
    for task_name, args in env.get_tasks():
107 108 109 110 111 112 113
        try:
            tsk = create(task_name, args,
                         target=target, target_host=target_host,
                         template_key='direct')
            tasks.append(tsk)
        except topi.InvalidShapeError:
            print("[Warning] Invalid shape during AutoTVM task creation")
114 115 116 117

    return tasks


118
def extract_from_multiple_graph(graphs, shapes, dtypes, target, symbols, params, target_host=None):
119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134
    """ Extract tuning tasks from multiple nnvm graphs.

    This function is the multiple graph version of extract_from_graph

    Parameters
    ----------
    graphs : List of Graph
        The list of graphs to tune
    shapes : List of dict of str to tuple
        The input shape to the graph
    dtypes : List of str or dict of str to str
        The input types to the graph
    target: tvm.target.Target
        The compilation target
    symbols : Array of nnvm.symbol
        Array of nnvm symbols want to be tuned
135 136
    params : dict of str to NDArray
        The parameter dictionary.
137 138 139 140 141 142 143 144 145
    target_host: tvm.target.Target
        The host compilation target

    Returns
    -------
    task: Array of autotvm.task.Task
        collected tasks
    """
    import nnvm.compiler
146 147
    import nnvm
    import topi
148 149 150

    env = TaskExtractEnv.get()

151 152 153 154 155 156 157 158 159
    #NOTE: To add more symbols, you only need to change the following lists
    #nnvm symbol -> topi compute
    SYMBOL2TOPI = {
        nnvm.sym.conv2d: [topi.nn.conv2d, topi.nn.depthwise_conv2d_nchw,
                          topi.nn.group_conv2d_nchw],
        nnvm.sym.conv2d_transpose: [topi.nn.conv2d_transpose_nchw],
        nnvm.sym.dense: [topi.nn.dense],
    }

160 161
    topi_funcs = []
    for sym_name in symbols:
162 163
        if sym_name in SYMBOL2TOPI:
            topi_funcs.extend(SYMBOL2TOPI[sym_name])
164 165 166 167 168
        else:
            warnings.warn("Symbol %s is not tunable, ignored" % sym_name)

    # run compiler to collect all TOPI calls during compilation
    env.reset(topi_funcs)
169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187
    with env:
        # disable logger temporarily
        old_state = logger.disabled
        logger.disabled = True

        for graph, shape, dtype in zip(graphs, shapes, dtypes):
            nnvm.compiler.engine.clear_cache()
            # wrap build call in thread to avoid multiprocessing problems
            build_thread = threading.Thread(target=nnvm.compiler.build,
                                            args=(graph,
                                                  target,
                                                  shape,
                                                  dtype,
                                                  params,
                                                  target_host))
            build_thread.start()
            build_thread.join()

        logger.disabled = old_state
188 189

    # create tasks for target
190 191
    tasks = []
    for task_name, args in env.get_tasks():
192 193 194 195 196 197 198
        try:
            tsk = create(task_name, args,
                         target=target, target_host=target_host,
                         template_key='direct')
            tasks.append(tsk)
        except topi.InvalidShapeError:
            print("[Warning] Invalid shape during AutoTVM task creation")
199 200

    return tasks