intrin.py 7.68 KB
Newer Older
1
"""Expression Intrinsics and math functions in TVM."""
2 3
from __future__ import absolute_import as _abs

4
from ._ffi.function import register_func as _register_func
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
from . import make as _make
from .api import convert, const
from .expr import Call as _Call
from .schedule import Buffer as _Buffer

def _pack_buffer(buf):
    """Build intrinsics that packs the buffer.
    """
    assert buf.shape
    shape = _make.Call("handle", "tvm_stack_make_shape", buf.shape,
                       _Call.Intrinsic, None, 0)
    strides = _make.Call("handle", "tvm_stack_make_shape", buf.strides,
                         _Call.Intrinsic, None, 0) if buf.strides else 0
    pack_args = [buf.data,
                 shape,
                 strides,
                 len(buf.shape),
                 const(0, dtype=buf.dtype),
23
                 buf.elem_offset]
24 25
    return _make.Call("handle", "tvm_stack_make_array",
                      pack_args, _Call.Intrinsic, None, 0)
26 27

def call_packed(*args):
28 29 30 31 32 33 34 35
    """Build expression by call an external packed function.

    The argument to packed function can be Expr or Buffer.
    The argument is the corresponding POD type when Expr is presented.

    When the argument is Buffer, the corresponding PackedFunc
    will recieve an TVMArrayHandle whose content is valid during the callback period.
    If the PackedFunc is a python callback, then the corresponding argument is NDArray.
36 37 38

    Parameters
    ----------
39
    args : list of Expr or Buffer.
40
        Positional arguments.
41 42 43 44 45 46 47 48 49

    Returns
    -------
    call : Expr
        The call expression.

    See Also
    --------
    tvm.extern : Create tensor with extern function call.
50
    """
51
    call_args = [_pack_buffer(x) if isinstance(x, _Buffer) else x for x in args]
52
    return _make.Call(
53
        "int32", "tvm_call_packed", call_args, _Call.Intrinsic, None, 0)
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71


def call_pure_intrin(dtype, func_name, *args):
    """Build expression by calling a pure intrinsic function.

    Intrinsics can be overloaded with multiple data types via
    the intrinsic translation rule.

    Parameters
    ----------
    dtype : str
        The data type of the result.

    func_name: str
        The intrinsic function name.

    args : list
        Positional arguments.
72 73 74 75 76

    Returns
    -------
    call : Expr
        The call expression.
77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
    """
    args = convert(args)
    return _make.Call(
        dtype, func_name, convert(args), _Call.PureIntrinsic, None, 0)


def call_pure_extern(dtype, func_name, *args):
    """Build expression by calling a pure extern function.

    Parameters
    ----------
    dtype : str
        The data type of the result.

    func_name: str
92
        The extern function name.
93 94 95

    args : list
        Positional arguments.
96 97 98 99 100

    Returns
    -------
    call : Expr
        The call expression.
101 102 103 104
    """
    return _make.Call(
        dtype, func_name, convert(args), _Call.PureExtern, None, 0)

105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128

def call_extern(dtype, func_name, *args):
    """Build expression by calling a extern function.

    Parameters
    ----------
    dtype : str
        The data type of the result.

    func_name: str
        The extern function name.

    args : list
        Positional arguments.

    Returns
    -------
    call : Expr
        The call expression.
    """
    return _make.Call(
        dtype, func_name, convert(args), _Call.Extern, None, 0)


129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144
def exp(x):
    """Take exponetial of input x.

    Parameters
    ----------
    x : Expr
        Input argument.

    Returns
    -------
    y : Expr
        The result.
    """
    return call_pure_intrin(x.dtype, "exp", x)


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
def tanh(x):
    """Take hyperbolic tanh of input x.

    Parameters
    ----------
    x : Expr
        Input argument.

    Returns
    -------
    y : Expr
        The result.
    """
    return call_pure_intrin(x.dtype, "tanh", x)


def sigmoid(x):
    """Quick function to get sigmoid

    Parameters
    ----------
    x : Expr
        Input argument.

    Returns
    -------
    y : Expr
        The result.
    """
174
    return call_pure_intrin(x.dtype, "sigmoid", x)
175 176


177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192
def log(x):
    """Take log of input x.

    Parameters
    ----------
    x : Expr
        Input argument.

    Returns
    -------
    y : Expr
        The result.
    """
    return call_pure_intrin(x.dtype, "log", x)


ziheng committed
193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208
def sqrt(x):
    """Take log of input x.

    Parameters
    ----------
    x : Expr
        Input argument.

    Returns
    -------
    y : Expr
        The result.
    """
    return call_pure_intrin(x.dtype, "sqrt", x)


209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227
def power(x, y):
    """x power y

    Parameters
    ----------
    x : Expr
        Input argument.

    y : Expr
        The exponent

    Returns
    -------
    z : Expr
        The result.
    """
    return call_pure_intrin(x.dtype, "pow", x, y)


228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243
def popcount(x):
    """Count the number of set bits in input x.

    Parameters
    ----------
    x : Expr
        Input argument.

    Returns
    -------
    y : Expr
        The result.
    """
    return call_pure_intrin(x.dtype, "popcount", x)


244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311
# Intrinsic rule related code
def register_intrin_rule(target, intrin, f=None, override=False):
    """Register an intrinsic function generation rule.

    Intrinsic generation rules are callback functions for
    code generator to get device specific calls.
    This function simply translates to.

    :code:`register_func("tvm.intrin.rule.%s.%s" % (target, intrin), f, override)`

    TVM may already pre-register intrinsic rules in the backend.
    However, user can use this function to change the intrinsic translation
    behavior or add new intrinsic rules during runtime.

    Parameters
    ----------
    target : str
        The name of codegen target.

    intrin : str
        The name of the instrinsic.

    f : function, optional
        The function to be registered.

    override: boolean optional
        Whether override existing entry.

    Returns
    -------
    fregister : function
        Register function if f is not specified.

    Examples
    --------
    The following code registers exp expansion rule for opencl.

    .. code-block:: python

        register_intrin_rule("opencl", "exp", my_exp_rule, override=True)
    """
    return _register_func("tvm.intrin.rule.%s.%s" % (target, intrin), f, override)


def _rule_float_suffix(op):
    """Intrinsic rule: Add float suffix if it is float32.

    This is an example intrinsic generation rule.

    Parameters
    ----------
    op : Expr
        The call expression of original intrinsic.

    Returns
    -------
    ret : Expr
        The translated intrinsic rule.
        Return same op if no translation is possible.

    See Also
    --------
    register_intrin_rule : The registeration function for intrin rule.
    """
    if op.dtype == "float32":
        return call_pure_extern(op.dtype, "%sf" % op.name, *op.args)
    elif op.dtype == "float64":
        return call_pure_extern(op.dtype, op.name, *op.args)
312
    return op
313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336


def _rule_float_direct(op):
    """Intrinsic rule: Directly call pure extern function for floats.

    This is an example intrinsic generation rule.

    Parameters
    ----------
    op : Expr
        The call expression of original intrinsic.

    Returns
    -------
    ret : Expr
        The translated intrinsic rule.
        Return same op if no translation is possible.

    See Also
    --------
    register_intrin_rule : The registeration function for intrin rule.
    """
    if str(op.dtype).startswith("float"):
        return call_pure_extern(op.dtype, op.name, *op.args)
337
    return None
338 339 340 341 342

# opencl pattern for exp
register_intrin_rule("opencl", "exp", _rule_float_direct, override=True)
# default pattern for exp
register_intrin_rule("default", "exp", _rule_float_suffix, override=True)
343 344 345

# default pattern for sigmoid
register_intrin_rule("default", "sigmoid", lambda op: 1.0 / (1.0 + exp(-op.args[0])))