util.py 4.31 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=invalid-name
"""Utilities"""
import logging
import multiprocessing
import time

23 24
from random import randrange

25 26 27 28
import numpy as np

from .. import expr, ir_pass

29
logger = logging.getLogger('autotvm')
30 31 32 33 34 35 36 37 38 39

class EmptyContext(object):
    """An empty context"""
    def __enter__(self):
        pass

    def __exit__(self, exc_type, exc_val, exc_tb):
        pass


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 76 77 78 79
def get_rank(values):
    """get rank of items

    Parameters
    ----------
    values: Array

    Returns
    -------
    ranks: Array of int
        the rank of this item in the input (the largest value ranks first)
    """
    tmp = np.argsort(-values)
    ranks = np.empty_like(tmp)
    ranks[tmp] = np.arange(len(tmp))
    return ranks


def sample_ints(low, high, m):
    """
    Sample m different integer numbers from [low, high) without replacement
    This function is an alternative of `np.random.choice` when (high - low) > 2 ^ 32, in
    which case numpy does not work.

    Parameters
    ----------
    low: int
        low point of sample range
    high: int
        high point of sample range
    m: int
        The number of sampled int

    Returns
    -------
    ints: an array of size m
    """
    vis = set()
    assert m <= high - low
    while len(vis) < m:
80
        new = randrange(low, high)
81
        while new in vis:
82
            new = randrange(low, high)
83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
        vis.add(new)

    return list(vis)


def pool_map(func, args, batch_size, verbose=False, pool=None):
    """A wrapper of multiprocessing.pool.Pool.map to support small-batch mapping
    for large argument list. This can reduce memory usage

    Parameters
    ----------
    func: Func(arg) -> np.ndarray
        mapping function
    args: List
        list of arguments
    batch_size: int
        batch size in mapping
    verbose: bool, optional
        whether print progress
    pool: multiprocessing.Pool, optional
        pool objection

    Returns
    -------
    converted numpy array
    """

    ret = None
    tic = time.time()
    local_pool = pool or multiprocessing.Pool()
    if verbose:
114
        logger.info("mapping begin")
115 116
    for i in range(0, len(args), batch_size):
        if verbose:
117 118
            logger.info("mapping %d/%d elapsed %.2f", i, len(args),
                        time.time() - tic)
119 120 121
        tmp = np.array(local_pool.map(func, args[i:i+batch_size]))
        ret = tmp if ret is None else np.concatenate((ret, tmp))
    if verbose:
122
        logger.info("mapping done")
123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178
    if not pool:
        local_pool.close()
    return ret

def get_func_name(func):
    """Get name of a function

    Parameters
    ----------
    func: Function
        The function
    Returns
    -------
    name: str
        The name
    """

    return func.func_name if hasattr(func, 'func_name') else func.__name__


def get_const_int(exp):
    """Verifies expr is integer and get the constant value.

    Parameters
    ----------
    exp : tvm.Expr or int
        The input expression.

    Returns
    -------
    out_value : int
        The output.
    """
    if isinstance(exp, int):
        return exp
    if not isinstance(exp, (expr.IntImm, expr.UIntImm)):
        exp = ir_pass.Simplify(expr)
    if not isinstance(exp, (expr.IntImm, expr.UIntImm)):
        raise ValueError("Expect value to be constant int")
    return exp.value


def get_const_tuple(in_tuple):
    """Verifies input tuple is IntImm, returns tuple of int.

    Parameters
    ----------
    in_tuple : tuple of Expr
        The input.

    Returns
    -------
    out_tuple : tuple of int
        The output.
    """
    return tuple(get_const_int(x) for x in in_tuple)