nnvm_integration.py 5.45 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 22
# pylint: disable=unused-variable,invalid-name
"""
Decorator and utilities for the integration with TOPI and NNVM

"""
import warnings
23 24
import logging

25

26
from ... import target as _target
27

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

31
logger = logging.getLogger('autotvm')
32 33 34 35 36


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

37 38
    This function collects tuning tasks by building the graph
    with a "tracing" target and tracing all the calls to topi.
39 40 41 42 43

    Parameters
    ----------
    graph : Graph
        The graph to tune
44
    shape : dict of str to tuple
45 46 47 48 49 50
        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
51
        Array of nnvm symbols want to be tuned
52 53 54 55 56 57 58 59 60
    target_host: tvm.target.Target
        The host compilation target

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

    env = TaskExtractEnv.get()

66 67 68 69 70 71 72 73 74
    #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],
    }

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

    # run compiler to collect all TOPI calls during compilation
83
    env.reset(topi_funcs)
84 85 86 87 88

    # disable logger temporarily
    old_state = logger.disabled
    logger.disabled = True

89 90 91 92
    # use a "tracing" target to do a fake compile for collecting topi calls
    tracing_target = _target.create("llvm -device=tracing")
    nnvm.compiler.engine.clear_cache()
    nnvm.compiler.build(graph, target=tracing_target, shape=shape, dtype=dtype)
93 94

    logger.disabled = old_state
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
    # create tasks for target
    tasks = []
    for task_name, args in env.get_tasks():
        tasks.append(create(task_name, args,
                            target=target, target_host=target_host,
                            template_key='direct'))

    return tasks


def extract_from_multiple_graph(graphs, shapes, dtypes, target, symbols, target_host=None):
    """ 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
    target_host: tvm.target.Target
        The host compilation target

    Returns
    -------
    task: Array of autotvm.task.Task
        collected tasks
    """
    import nnvm.compiler
132 133
    import nnvm
    import topi
134 135 136

    env = TaskExtractEnv.get()

137 138 139 140 141 142 143 144 145
    #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],
    }

146 147
    topi_funcs = []
    for sym_name in symbols:
148 149
        if sym_name in SYMBOL2TOPI:
            topi_funcs.extend(SYMBOL2TOPI[sym_name])
150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169
        else:
            warnings.warn("Symbol %s is not tunable, ignored" % sym_name)

    # run compiler to collect all TOPI calls during compilation
    env.reset(topi_funcs)

    # disable logger temporarily
    old_state = logger.disabled
    logger.disabled = True

    # use a "tracing" target to do a fake compile for collecting topi calls
    tracing_target = _target.create("llvm -device=tracing")

    nnvm.compiler.engine.clear_cache()
    for graph, shape, dtype in zip(graphs, shapes, dtypes):
        nnvm.compiler.build(graph, target=tracing_target, shape=shape, dtype=dtype)

    logger.disabled = old_state

    # create tasks for target
170 171 172 173 174 175 176
    tasks = []
    for task_name, args in env.get_tasks():
        tasks.append(create(task_name, args,
                            target=target, target_host=target_host,
                            template_key='direct'))

    return tasks