topi_integration.py 19 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
# pylint: disable=unused-variable,invalid-name,unused-argument
18 19 20 21 22 23 24 25 26 27 28 29
"""
Decorators for registering tunable templates to TOPI.

These decorators can make your simple implementation be able to use different configurations
for different workloads.
Here we directly use all arguments to the TOPI call as "workload", so make sure all the arguments
(except tvm.Tensor) in you calls are hashable. For tvm.Tensor, we will serialize it to a hashable
tuple.

See tvm/topi/python/topi/arm_cpu/depthwise_conv2d.py for example usage.
"""

30
from ... import _api_internal, tensor, placeholder
31

32 33
from .task import args_to_workload, dispatcher, register
from ..util import get_const_tuple
34 35

# A table that records all registered dispatcher for all targets
eqy committed
36
_REGISTERED_DISPATCHER = {
37 38 39
}


40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
def serialize_args(args):
    """serialize arguments of a topi function to a hashable tuple.

    Parameters
    ----------
    args: list of hashable or Tensor
    """
    ret = []
    for t in args:
        if isinstance(t, tensor.Tensor):
            ret.append(('TENSOR', get_const_tuple(t.shape), t.dtype))
        else:
            ret.append(t)
    return tuple(ret)


def deserialize_args(args):
    """The inverse function of :code:`serialize_args`.

    Parameters
    ----------
    args: list of hashable or Tensor
    """
    ret = []
    for t in args:
        if isinstance(t, tuple) and t[0] == 'TENSOR':
            ret.append(placeholder(shape=t[1], dtype=t[2]))
        else:
            ret.append(t)
    return ret


# Task extractor for nnvm graph, relay program
class TaskExtractEnv:
    """Global environment for extracting tuning tasks from nnvm graph"""
    current = None
76
    registered = None
77

78
    def __init__(self, allow_duplicate=False):
79 80 81 82 83 84 85 86
        import topi

        # topi compute -> autotvm task name
        self.topi_to_task = {
            topi.nn.conv2d: "topi_nn_conv2d",
            topi.nn.depthwise_conv2d_nchw: "topi_nn_depthwise_conv2d_nchw",
            topi.nn.group_conv2d_nchw: "topi_nn_group_conv2d_nchw",
            topi.nn.conv2d_transpose_nchw: "topi_nn_conv2d_transpose_nchw",
87
            topi.nn.conv2d_NCHWc: "topi_x86_conv2d_NCHWc",
88
            topi.nn.dense: "topi_nn_dense",
89 90
            topi.nn.bitserial_conv2d_nchw: "topi_nn_bitserial_conv2d_nchw",
            topi.nn.bitserial_conv2d_nhwc: "topi_nn_bitserial_conv2d_nhwc",
91
            topi.nn.bitserial_dense: "topi_nn_bitserial_dense",
92
            topi.nn.deformable_conv2d_nchw: "topi_nn_deformable_conv2d_nchw",
93 94 95 96 97 98 99 100 101
        }

        self.topi_to_schedule = {
            topi.nn.conv2d: [topi.generic.schedule_conv2d_nchw,
                             topi.generic.schedule_conv2d_nhwc],
            topi.nn.depthwise_conv2d_nchw: [topi.generic.schedule_depthwise_conv2d_nchw,
                                            topi.generic.schedule_depthwise_conv2d_nhwc],
            topi.nn.group_conv2d_nchw: [topi.generic.schedule_group_conv2d_nchw],
            topi.nn.conv2d_transpose_nchw: [topi.generic.schedule_conv2d_transpose_nchw],
102
            topi.nn.conv2d_NCHWc: [topi.generic.schedule_conv2d_NCHWc],
103
            topi.nn.dense: [topi.generic.schedule_dense],
104 105
            topi.nn.bitserial_conv2d_nchw: [topi.generic.schedule_bitserial_conv2d_nchw],
            topi.nn.bitserial_conv2d_nhwc: [topi.generic.schedule_bitserial_conv2d_nhwc],
106
            topi.nn.bitserial_dense: [topi.generic.schedule_bitserial_dense],
107
            topi.nn.deformable_conv2d_nchw: [topi.generic.schedule_deformable_conv2d_nchw],
108 109
        }

110 111 112 113 114 115 116 117 118 119 120 121 122 123
        # function reflection for tracing
        self.func_to_reflection = {
            topi.nn.conv2d:                 lambda x: setattr(topi.nn, 'conv2d', x),
            topi.nn.conv2d_NCHWc:           lambda x: setattr(topi.nn, 'conv2d_NCHWc', x),
            topi.nn.depthwise_conv2d_nchw:  lambda x: setattr(topi.nn, 'depthwise_conv2d_nchw', x),
            topi.nn.group_conv2d_nchw:      lambda x: setattr(topi.nn, 'group_conv2d_nchw', x),
            topi.nn.conv2d_transpose_nchw:  lambda x: setattr(topi.nn, 'conv2d_transpose_nchw', x),
            topi.nn.dense:                  lambda x: setattr(topi.nn, 'dense', x),
            topi.nn.bitserial_conv2d_nchw:  lambda x: setattr(topi.nn, 'bitserial_conv2d_nchw', x),
            topi.nn.bitserial_conv2d_nhwc:  lambda x: setattr(topi.nn, 'bitserial_conv2d_nhwc', x),
            topi.nn.bitserial_dense:        lambda x: setattr(topi.nn, 'bitserial_dense', x),
            topi.nn.deformable_conv2d_nchw: lambda x: setattr(topi.nn, 'deformable_conv2d_nchw', x),
        }

124
        self.allow_duplicate = allow_duplicate
125 126 127
        self._register_topi_task()
        self.task_collection = []
        self.wanted_topi_funcs = list(self.topi_to_task.keys())
128 129 130 131 132
        self.modified_funcs = []

    def __enter__(self):
        self.task_collection = []
        self.modified_funcs = []
133

134
        for topi_compute in self.wanted_topi_funcs:
135 136 137
            def _local_scope(compute_func):
                """start a scope to hold the local function in for loop"""

138 139 140
                def _tracing_wrapper(*args, **kwargs):
                    assert not kwargs, "Do not support extracting tuning tasks when " \
                                       "kwargs is used in TOPI function call. " \
141
                                       "Please modify it to use only positional args."
142 143 144 145 146 147 148 149 150
                    key = (self.topi_to_task[compute_func], serialize_args(args))
                    if self.allow_duplicate or key not in self.task_collection:
                        self.task_collection.append(key)

                    return compute_func(*args, **kwargs)

                self.func_to_reflection[compute_func](_tracing_wrapper)
                self.modified_funcs.append(compute_func)

151 152
            _local_scope(topi_compute)

153
        return self
154

155 156 157 158
    def __exit__(self, exc_type, exc_val, exc_tb):
        # revert modification
        for func in self.modified_funcs:
            self.func_to_reflection[func](func)
159 160 161 162 163

    def _register_topi_task(self):
        """register tuning wrapper for topi function"""
        import topi

164 165 166 167 168
        # Avoid double registration for certain targets
        if TaskExtractEnv.registered:
            return
        TaskExtractEnv.registered = True

169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211
        # Tuning wrapper for topi functions
        @register("topi_nn_conv2d")
        def _topi_nn_conv2d(*args, **kwargs):
            assert not kwargs, "Do not support kwargs in template function call"
            args = deserialize_args(args)
            A, W = args[:2]
            layout = args[-2]
            assert layout == 'NCHW', "only support NCHW currently"
            C = topi.nn.conv2d(*args, **kwargs)
            s = topi.generic.schedule_conv2d_nchw([C])
            return s, [A, W, C]

        @register("topi_nn_depthwise_conv2d_nchw")
        def _topi_nn_depthwise_conv2d_nchw(*args, **kwargs):
            assert not kwargs, "Do not support kwargs in template function call"
            args = deserialize_args(args)
            A, W = args[:2]
            C = topi.nn.depthwise_conv2d_nchw(*args, **kwargs)
            s = topi.generic.schedule_depthwise_conv2d_nchw([C])
            return s, [A, W, C]

        @register("topi_nn_group_conv2d_nchw")
        def _topi_nn_group_conv2d_nchw(*args, **kwargs):
            assert not kwargs, "Do not support kwargs in template function call"
            args = deserialize_args(args)
            A, W = args[:2]
            C = topi.nn.group_conv2d_nchw(*args, **kwargs)
            s = topi.generic.schedule_group_conv2d_nchw([C])
            return s, [A, W, C]

        @register("topi_nn_conv2d_transpose_nchw")
        def _topi_nn_conv2d_transpose_nchw(*args, **kwargs):
            assert not kwargs, "Do not support kwargs in template function call"
            args = deserialize_args(args)
            A, W = args[:2]
            C = topi.nn.conv2d_transpose_nchw(*args, **kwargs)
            s = topi.generic.schedule_conv2d_transpose_nchw([C])
            return s, [A, W, C]

        @register("topi_nn_dense")
        def _topi_nn_dense(*args, **kwargs):
            assert not kwargs, "Do not support kwargs in template function call"
            args = deserialize_args(args)
212 213 214 215 216
            if len(args) > 2:
                data, weight, bias = args[:3]
            else:
                data, weight = args
                bias = None
217 218 219 220 221 222
            C = topi.nn.dense(*args, **kwargs)
            s = topi.generic.schedule_dense([C])
            if bias is not None:
                return s, [data, weight, bias, C]
            return s, [data, weight, C]

223 224 225 226 227
        @register("topi_nn_bitserial_conv2d_nhwc")
        def _topi_bitserial_conv2d_nhwc(*args, **kwargs):
            args = deserialize_args(args)
            C = topi.nn.bitserial_conv2d_nhwc(*args, **kwargs)
            s = topi.generic.nn.schedule_bitserial_conv2d_nhwc([C])
228 229
            A, W = args[:2]
            return s, [A, W, C]
230 231 232 233 234 235

        @register("topi_nn_bitserial_conv2d_nchw")
        def _topi_bitserial_conv2d_nchw(*args, **kwargs):
            args = deserialize_args(args)
            C = topi.nn.bitserial_conv2d_nchw(*args, **kwargs)
            s = topi.generic.nn.schedule_bitserial_conv2d_nchw([C])
236 237 238 239 240 241 242 243 244 245 246
            A, W = args[:2]
            return s, [A, W, C]

        @register("topi_nn_bitserial_dense")
        def _topi_nn_bitserial_dense(*args, **kwargs):
            assert not kwargs, "Do not support kwargs in template function call"
            args = deserialize_args(args)
            A, W = args[:2]
            C = topi.nn.bitserial_dense(*args, **kwargs)
            s = topi.generic.schedule_bitserial_dense([C])
            return s, [A, W, C]
247

248 249 250 251 252 253 254 255 256
        @register("topi_nn_deformable_conv2d_nchw")
        def _topi_nn_deformable_conv2d_nchw(*args, **kwargs):
            assert not kwargs, "Do not support kwargs in template function call"
            args = deserialize_args(args)
            A, Offset, W = args[:3]
            C = topi.nn.deformable_conv2d_nchw(*args, **kwargs)
            s = topi.generic.schedule_deformable_conv2d_nchw([C])
            return s, [A, Offset, W, C]

257 258 259 260 261 262 263 264 265
        @register("topi_nn_conv2d_NCHWc")
        def _topi_nn_conv2d_NCHWc(*args, **kwargs):
            assert not kwargs, "Do not support kwargs in template function call"
            args = deserialize_args(args)
            A, W = args[:2]
            C = topi.nn.conv2d_NCHWc(*args, **kwargs)
            s = topi.generic.schedule_conv2d_NCHWc([C])
            return s, [A, W, C]

266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287
    def reset(self, wanted_topi_funcs):
        """Reset task collections

        Parameters
        ----------
        wanted_topi_funcs: List of function
            The topi function to be extracted
        """
        self.task_collection = []
        self.wanted_topi_funcs = wanted_topi_funcs

    def get_tasks(self):
        """Get collected tasks

        Returns
        -------
        tasks: List of tuple(name, args)
            A list of tasks extracted from the nnvm graph
        """
        return self.task_collection

    @staticmethod
288
    def get(allow_duplicate=False):
289 290
        """Get the single instance of TaskExtractEnv

291 292 293 294 295 296 297
        Parameters
        ----------
        allow_duplicate : boolean
            Whether to fetch all workloads in the network,
            even though some of them are the same. This is
            useful for graph tuning.

298 299 300 301 302 303
        Returns
        -------
        env: TaskExtractEnv
            The single instance of TaskExtractEnv
        """
        if not TaskExtractEnv.current:
304 305 306
            TaskExtractEnv.current = TaskExtractEnv(allow_duplicate)
        else:
            TaskExtractEnv.current.allow_duplicate = allow_duplicate
307 308 309
        return TaskExtractEnv.current


310
def register_topi_compute(topi_compute, target_keys, template_keys, func=None, override=False):
311 312
    """Register a tunable template for a topi compute function.

eqy committed
313
    After the registration, this topi compute will become a configuration dispatcher. It uses
314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345
    all its argument as workload and dispatches configurations according to the input workload.

    It also stores this "workload" to its final ComputeOp, which can be used to reconstruct
    "workload" in the following topi_schedule call.

    Parameters
    ----------
    topi_compute: GenericFunc
        The topi compute function that will be overloaded
    target_keys: str or list of str
        The compilation target. The same as the argument of GenericFunc.register.
    template_keys: str or list of str
        The template key.
        We might have several strategies for a single operator (e.g. direct, im2col, winograd).
        The template key is used to identity the algorithm strategy.
        Every operator must have a "direct" template, which is used by default.
    func: None or callable
        If it is None, return a decorator.
        If is callable, decorate this function.

    Returns
    -------
    decorator: callable
        A decorator

    Examples
    --------
    See tvm/topi/python/topi/arm_cpu/depthwise_conv2d.py for example usage.
    """
    def _decorator(f):
        targets = [target_keys] if isinstance(target_keys, str) else target_keys
        for target_key in targets:
eqy committed
346 347 348
            if target_key not in _REGISTERED_DISPATCHER:
                _REGISTERED_DISPATCHER[target_key] = {}
            if topi_compute not in _REGISTERED_DISPATCHER[target_key]:
349 350 351 352 353
                @topi_compute.register(target_key)
                @dispatcher
                def config_dispatcher(*args, **kwargs):
                    """override topi call as a config dispatcher"""
                    assert not kwargs, "Do not support kwargs in template function call"
354
                    return args_to_workload(args, topi_compute)
eqy committed
355
                _REGISTERED_DISPATCHER[target_key][topi_compute] = config_dispatcher
356

eqy committed
357
            config_dispatcher = _REGISTERED_DISPATCHER[target_key][topi_compute]
358

359
            @config_dispatcher.register(template_keys, override=override)
360 361 362 363 364 365 366 367 368 369 370 371 372 373
            def template_call(cfg, *args, **kwargs):
                """call the topi func and attach workload to compute node"""
                assert not kwargs, "Do not support kwargs in template function call"

                if f == topi_compute.fdefault:
                    node = f(*args, **kwargs)
                else:
                    node = f(cfg, *args, **kwargs)

                # attach workload to return op
                op = node.op
                attrs = {}
                for k, v in node.op.attrs.items():
                    attrs[k] = v
374
                attrs['workload'] = args_to_workload(args, topi_compute)
375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397
                if isinstance(op, tensor.ComputeOp):
                    op = _api_internal._ComputeOp(
                        op.name, op.tag, attrs, op.axis, op.body)
                elif isinstance(op, tensor.ExternOp):
                    op = _api_internal._ExternOp(
                        op.name, op.tag, attrs,
                        op.inputs, op.input_placeholders,
                        op.output_placeholders, op.body)
                else:
                    raise RuntimeError("Unsupported op type: " + str(type(op)))

                if isinstance(node, tensor.Tensor):
                    return op.output(0)
                return [op.output(i) for i in range(len(node))]

        return f

    if func:
        _decorator(func)

    return _decorator


398
def register_topi_schedule(topi_schedule, target_keys, template_keys, func=None, override=False):
399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433
    """Register a tunable template for a topi schedule function.

    After the registration. This topi schedule will become a configuration dispatcher. It dispatches
    configurations according to the input workload.

    Note that this function will try to find "workload" from all the ComputeOp in the input.
    You can attach "workload" to your compute op by using :any:`register_topi_compute`.

    Parameters
    ----------
    topi_schedule: GenericFunc
        The topi schedule function that will be overloaded
    target_keys: str or list of str
        The compilation target
    template_keys: str or list of str
        The template key.
        We might have several strategies for a single operator (e.g. direct, im2col, winograd).
        The template key is used to identity the algorithm strategy.
        Every operator must have a "direct" template, which is used by default.
    func: None or callable
        If it is None, return a decorator.
        If is callable, decorate this function.

    Returns
    -------
    decorator: callable
        A decorator

    Examples
    --------
    See tvm/topi/python/topi/arm_cpu/depthwise_conv2d.py for example usage.
    """
    def _decorator(f):
        targets = [target_keys] if isinstance(target_keys, str) else target_keys
        for target_key in targets:
eqy committed
434 435 436
            if target_key not in _REGISTERED_DISPATCHER:
                _REGISTERED_DISPATCHER[target_key] = {}
            if topi_schedule not in _REGISTERED_DISPATCHER[target_key]:
437 438
                @topi_schedule.register(target_key)
                @dispatcher
439
                def config_dispatcher(outs, *args, **kwargs):
440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459
                    """override topi call as a workload dispatcher"""
                    def traverse(tensors):
                        """traverse all ops to find attached workload"""
                        for t in tensors:
                            op = t.op
                            if 'workload' in op.attrs:
                                return op.attrs['workload']
                            wkl = traverse(op.input_tensors)
                            if wkl:
                                return wkl
                        return None

                    outs = [outs] if isinstance(outs, tensor.Tensor) else outs
                    workload = traverse(outs)

                    if workload is None:
                        raise RuntimeError("Cannot find workload in attribute of this schedule")

                    return args_to_workload(workload)

eqy committed
460
                _REGISTERED_DISPATCHER[target_key][topi_schedule] = config_dispatcher
461

eqy committed
462
            config_dispatcher = _REGISTERED_DISPATCHER[target_key][topi_schedule]
463

464
            @config_dispatcher.register(template_keys, override=override)
465
            def template_call(cfg, outs, *args, **kwargs):
466 467
                """call the schedule func"""
                if f == topi_schedule.fdefault:
468 469
                    return f(outs, *args, **kwargs)
                return f(cfg, outs, *args, **kwargs)
470 471 472 473 474 475 476

        return f

    if func:
        _decorator(func)

    return _decorator