expr.py 15.5 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
# pylint: disable=no-else-return, unidiomatic-typecheck, invalid-name
"""The expression nodes of Relay."""
from __future__ import absolute_import
20
from numbers import Number as _Number
21 22 23

import numpy as _np
from .base import RelayNode, register_relay_node
24
from . import _make
25
from . import _expr
26
from . import ty as _ty
27
from .._ffi import base as _base
28
from .. import nd as _nd
29 30
from .. import convert

31 32
# will be registered afterwards
_op_make = None
33

34
class Expr(RelayNode):
35
    """The base type for all Relay expressions."""
36
    @property
37
    def checked_type(self):
38
        """Get the checked type of tvm.relay.Expr.
39 40 41

        Returns
        -------
42
        checked_type : tvm.relay.Type
43 44
            The checked type.
        """
45 46 47 48 49
        ret = self._checked_type_
        if ret is None:
            raise ValueError("The type checker has not populated"
                             " the checked_type for this node")
        return ret
50

51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
    def astype(self, dtype):
        """Cast the content type of the current data to dtype.

        Parameters
        ----------
        dtype : str
            The target data type.

        Note
        ----
        This function only works for TensorType Exprs.

        Returns
        -------
        result : tvm.relay.Expr
            The result expression.
        """
68
        return _make.cast(self, dtype)
69

70 71 72
    def __neg__(self):
        return _op_make.negative(self)

73 74 75 76 77 78 79 80 81 82 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 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128
    def __add__(self, other):
        if isinstance(other, Expr):
            return _op_make.add(self, other)
        elif isinstance(other, _Number):
            raise TypeError('convert "%s" with `const` first' % str(other))
        else:
            raise TypeError("type %s not supported" % str(type(other)))

    def __radd__(self, other):
        return self.__add__(other)

    def __sub__(self, other):
        if isinstance(other, Expr):
            return _op_make.subtract(self, other)
        elif isinstance(other, _Number):
            raise TypeError('convert "%s" with `const` first' % str(other))
        else:
            raise TypeError("type %s not supported" % str(type(other)))

    def __rsub__(self, other):
        if isinstance(other, _Number):
            raise TypeError('convert "%s" with `const` first' % str(other))
        else:
            raise TypeError("type %s not supported" % str(type(other)))

    def __mul__(self, other):
        if isinstance(other, Expr):
            return _op_make.multiply(self, other)
        elif isinstance(other, _Number):
            raise TypeError('convert "%s" with `const` first' % str(other))
        else:
            raise TypeError("type %s not supported" % str(type(other)))

    def __rmul__(self, other):
        return self.__mul__(other)

    def __div__(self, other):
        if isinstance(other, Expr):
            return _op_make.divide(self, other)
        elif isinstance(other, _Number):
            raise TypeError('convert "%s" with `const` first' % str(other))
        else:
            raise TypeError("type %s not supported" % str(type(other)))

    def __rdiv__(self, other):
        if isinstance(other, _Number):
            raise TypeError('convert "%s" with `const` first' % str(other))
        else:
            raise TypeError("type %s not supported" % str(type(other)))

    def __truediv__(self, other):
        return self.__div__(other)

    def __rtruediv__(self, other):
        return self.__rdiv__(other)

129 130 131

@register_relay_node
class Constant(Expr):
132
    """A constant expression in Relay.
133

134 135 136 137 138
    Parameters
    ----------
    data : tvm.nd.NDArray
        The data content of the constant expression.
    """
139 140 141 142 143 144
    def __init__(self, data):
        self.__init_handle_by_constructor__(_make.Constant, data)


@register_relay_node
class Tuple(Expr):
145
    """Tuple expression that groups several fields together.
146

147 148 149 150 151
    Parameters
    ----------
    fields : List[tvm.relay.Expr]
        The fields in the tuple.
    """
152 153 154
    def __init__(self, fields):
        self.__init_handle_by_constructor__(_make.Tuple, fields)

155 156 157 158 159 160 161 162
    def __getitem__(self, index):
        if index >= len(self):
            raise IndexError("Tuple index out of range")
        return self.fields[index]

    def __len__(self):
        return len(self.fields)

163 164 165
    def astype(self, _):
        raise TypeError("astype cannot be used on tuple")

166 167 168

@register_relay_node
class Var(Expr):
169
    """A local variable in Relay.
170

171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186
    Local variable can be used to declare input
    arguments to a function, or intermediate variables.

    Parameters
    ----------
    name_hint: str
        The name of the variable.
        This name only acts as a hint, and is not used
        for equality.

    type_annotation: tvm.relay.Type, optional
        The type annotation on the variable.
    """
    def __init__(self, name_hint, type_annotation=None):
        self.__init_handle_by_constructor__(
            _make.Var, name_hint, type_annotation)
187

188 189 190 191 192 193
    @property
    def name_hint(self):
        """Get name hint of the current var."""
        name = self.vid.name_hint
        return name

194 195 196 197 198 199 200 201 202 203 204 205 206 207
    def __call__(self, *args):
        """Call the variable (if it represents a function).

        Parameters
        ----------
        args: List[relay.Expr]
            The arguments to the call.

        Returns
        -------
        call: Call
            A call taking the variable as a function.
        """
        return Call(self, args)
208 209 210

@register_relay_node
class GlobalVar(Expr):
211
    """A global variable in Tvm.Relay.
212

213
    GlobalVar is used to refer to the global functions
214
    stored in the module.
215 216 217 218 219 220

    Parameters
    ----------
    name_hint: str
        The name of the variable.
    """
221 222 223
    def __init__(self, name_hint):
        self.__init_handle_by_constructor__(_make.GlobalVar, name_hint)

224 225 226 227 228 229 230 231 232 233
    def __call__(self, *args):
        """Invoke the gobal function.

        Parameters
        ----------
        args: List[relay.Expr]
            Arguments.
        """
        return Call(self, args, None, None)

234 235

@register_relay_node
236 237
class Function(Expr):
    """A function declaration expression.
238

239 240 241 242
    Parameters
    ----------
    params: List[tvm.relay.Var]
        List of input parameters to the function.
243

244 245
    body: tvm.relay.Expr
        The body of the function.
246

247 248 249
    ret_type: Optional[tvm.relay.Type]
        The return type annotation of the function.

250 251 252 253
    type_params: Optional[List[tvm.relay.TypeParam]]
        The additional type parameters, this is only
        used in advanced usecase of template functions.
    """
254 255 256
    def __init__(self,
                 params,
                 body,
257
                 ret_type=None,
258 259
                 type_params=None,
                 attrs=None):
260 261 262 263
        if type_params is None:
            type_params = convert([])

        self.__init_handle_by_constructor__(
264
            _make.Function, params, body, ret_type, type_params, attrs)
265

266
    def __call__(self, *args):
267
        """Invoke the global function.
268 269 270 271 272 273 274 275

        Parameters
        ----------
        args: List[relay.Expr]
            Arguments.
        """
        return Call(self, args, None, None)

276 277 278

@register_relay_node
class Call(Expr):
279 280 281 282 283 284 285 286 287
    """Function call node in Relay.

    Call node corresponds the operator application node
    in computational graph terminology.

    Parameters
    ----------
    op: tvm.relay.Op or any tvm.relay.Expr with function type.
        The operation to be called.
288

289 290
    args: List[tvm.relay.Expr]
        The arguments to the call.
291

292 293 294 295 296 297 298 299 300 301
    attrs: Optional[tvm.Attrs]
        Attributes to the call, can be None

    type_args: Optional[List[tvm.relay.Type]]
        The additional type arguments, this is only
        used in advanced usecase of template functions.
    """
    def __init__(self, op, args, attrs=None, type_args=None):
        if not type_args:
            type_args = []
302
        self.__init_handle_by_constructor__(
303
            _make.Call, op, args, attrs, type_args)
304 305 306 307


@register_relay_node
class Let(Expr):
308 309 310 311
    """Let variable binding expression.

    Parameters
    ----------
312
    variable: tvm.relay.Var
313 314 315 316
        The local variable to be bound.

    value: tvm.relay.Expr
        The value to be bound.
317

318 319 320
    body: tvm.relay.Expr
        The body of the let binding.
    """
321
    def __init__(self, variable, value, body):
322
        self.__init_handle_by_constructor__(
323
            _make.Let, variable, value, body)
324 325 326 327


@register_relay_node
class If(Expr):
328 329 330 331 332 333
    """A conditional expression in Relay.

    Parameters
    ----------
    cond: tvm.relay.Expr
        The condition.
334

335 336 337 338 339 340 341
    true_branch: tvm.relay.Expr
        The expression evaluated when condition is true.

    false_branch: tvm.relay.Expr
        The expression evaluated when condition is false.
    """
    def __init__(self, cond, true_branch, false_branch):
342
        self.__init_handle_by_constructor__(
343 344
            _make.If, cond, true_branch, false_branch)

345

346 347
@register_relay_node
class TupleGetItem(Expr):
348 349 350 351 352 353
    """Get index-th item from a tuple.

    Parameters
    ----------
    tuple_value: tvm.relay.Expr
        The input tuple expression.
354

355 356 357 358
    index: int
        The index.
    """
    def __init__(self, tuple_value, index):
359
        self.__init_handle_by_constructor__(
360
            _make.TupleGetItem, tuple_value, index)
361

362

363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402
@register_relay_node
class RefCreate(Expr):
    """Create a new reference from initial value.
    Parameters
    ----------
    value: tvm.relay.Expr
       The initial value.
    """
    def __init__(self, value):
        self.__init_handle_by_constructor__(_make.RefCreate, value)


@register_relay_node
class RefRead(Expr):
    """Get the value inside the reference.
    Parameters
    ----------
    ref: tvm.relay.Expr
         The reference.
    """
    def __init__(self, ref):
        self.__init_handle_by_constructor__(_make.RefRead, ref)


@register_relay_node
class RefWrite(Expr):
    """
    Update the value inside the reference.
    The whole expression will evaluate to an empty tuple.
    Parameters
    ----------
    ref: tvm.relay.Expr
        The reference.
    value: tvm.relay.Expr
        The new value.
    """
    def __init__(self, ref, value):
        self.__init_handle_by_constructor__(_make.RefWrite, ref, value)


403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419
class TempExpr(Expr):
    """Baseclass of all TempExpr.

    TempExprs are pass specific expression that can be
    useful to define intermediate result in the
    rewriting pass such as layout or type transformation.
    """
    def realize(self):
        """Convert the expression to a normal(non-temp) Expr.

        Returns
        -------
        The corresponding normal expression.
        """
        return _expr.TempExprRealize(self)


420
class TupleWrapper(object):
421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438
    """TupleWrapper.

    This class is a Python wrapper for a Relay tuple of known size.
    It allows for accessing the fields of the Relay tuple as though
    it were a Python tuple.

    Parameters
    ----------
    tuple_value: tvm.relay.Expr
        The input tuple

    size: int
        The size of the tuple.
    """
    def __init__(self, tuple_value, size):
        self.tuple_value = tuple_value
        self.size = size

439
    def astuple(self):
440 441 442 443
        """Returns the underlying Relay tuple if this wrapper is passed
        as an argument to an FFI function."""
        return self.tuple_value

Siva committed
444 445 446 447 448 449 450 451
    def astext(self):
        """Get the text format of the tuple expression.

        Returns
        -------
        text : str
            The text format of the tuple expression.
        """
452
        return self.tuple_value.astext()
Siva committed
453

454 455 456 457
    def __getitem__(self, index):
        if index >= len(self):
            raise IndexError("Tuple index out of range")
        return TupleGetItem(self.tuple_value, index)
458 459

    def __len__(self):
460 461 462 463
        return self.size

    def __repr__(self):
        return ("TupleWrapper(" + self.tuple_value.__repr__() +
464
                ", " + str(self.size) + ")")
465

466 467 468
    def astype(self, _):
        raise TypeError("astype cannot be used on tuple")

469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528

def var(name_hint,
        type_annotation=None,
        shape=None,
        dtype="float32"):
    """Create a new tvm.relay.Var.

    This is a simple wrapper function that allows specify
    shape and dtype directly.

    Parameters
    ----------
    name_hint: str
        The name of the variable.
        This name only acts as a hint, and is not used
        for equality.

    type_annotation: Optional[tvm.relay.Type, str]
        The type annotation on the variable.
        When type_annotation is a str, we will create a scalar variable.

    shape: Optional[List[tvm.Expr]]
        The shape of the tensor type.

    dtype: str, optional
        The data type of the tensor.

    Examples
    --------
    .. code-block:: python

      # The following 4 lines are equivalent to each other
      x = tvm.relay.Var("x", tvm.relay.TensorType([1, 2]))
      x = tvm.relay.var("x", tvm.relay.TensorType([1, 2]))
      x = tvm.relay.var("x", shape=[1, 2])
      x = tvm.relay.var("x", shape=[1, 2], dtype="float32")

      # The following 2 lines are equivalent to each other.
      y = tvm.relay.var("x", "float32")
      y = tvm.relay.var("x", shape=(), dtype="float32")
    """
    if type_annotation is not None and shape is not None:
        raise ValueError("Can only specify either type_annotation or shape.")
    if shape is not None:
        type_annotation = _ty.TensorType(shape, dtype)
    elif isinstance(type_annotation, str):
        type_annotation = _ty.TensorType((), type_annotation)
    return Var(name_hint, type_annotation)


def const(value, dtype=None):
    """Create a constant value.

    Parameters
    ----------
    value: Union[bool, int, float, numpy.ndarray, tvm.nd.NDArray]
        The constant value.

    dtype: str, optional
        The data type of the value.
529 530 531 532 533 534 535 536 537

    Note
    ----
    When dtype is None, we use the following rule:

    - int maps to "int32"
    - float maps to "float32"
    - bool maps to "bool"
    - other using the same default rule as numpy.
538
    """
539
    if isinstance(value, (_base.numeric_types, (bool, list))):
540
        value = _np.array(value, dtype=dtype)
541 542 543 544 545 546 547 548
    if not dtype:
        # when dtype is None: int maps to "int32", float maps to "float32"
        map_dtype = {
            _np.dtype('int64'): _np.int32,
            _np.dtype('float64'): _np.float32
            }.get(value.dtype, None)
        if map_dtype:
            value = value.astype(map_dtype)
549 550
    if isinstance(value, (_np.ndarray, _np.generic)):
        value = _nd.array(value)
551

552 553 554
    if not isinstance(value, _nd.NDArray):
        raise ValueError("value has to be scalar or NDArray")
    return Constant(value)
555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575


def bind(expr, binds):
    """Bind an free variables in expr or function arguments.

    We can bind parameters expr if it is a function.

    Parameters
    ----------
    expr : tvm.relay.Expr
        The input expression.

    binds : Union[Map[tvm.relay.Var, tvm.relay.Expr], Map[str, tvm.relay.Expr]]
        The specific bindings.

    Returns
    -------
    result : tvm.relay.Expr
        The expression or function after binding.
    """
    return _expr.Bind(expr, binds)