tensor.py 9.69 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
"""Tensor and Operation class for computation declaration."""
18
# pylint: disable=invalid-name
tqchen committed
19
from __future__ import absolute_import as _abs
20
from ._ffi.node import NodeBase, NodeGeneric, register_node, convert_to_node
21
from . import _api_internal
tqchen committed
22 23 24
from . import make as _make
from . import expr as _expr

25

26
class TensorSlice(NodeGeneric, _expr.ExprOp):
27
    """Auxiliary data structure for enable slicing syntax from tensor."""
28

29
    def __init__(self, tensor, indices):
tqchen committed
30 31
        if not isinstance(indices, tuple):
            indices = (indices,)
32 33 34 35
        self.tensor = tensor
        self.indices = indices

    def __getitem__(self, indices):
36 37
        if not isinstance(indices, tuple):
            indices = (indices,)
38 39
        return TensorSlice(self.tensor, self.indices + indices)

40 41 42 43
    def asnode(self):
        """Convert slice to node."""
        return self.tensor(*self.indices)

44 45 46 47 48
    @property
    def dtype(self):
        """Data content of the tensor."""
        return self.tensor.dtype

49 50 51 52
@register_node
class TensorIntrinCall(NodeBase):
    """Intermediate structure for calling a tensor intrinsic."""

53

54
itervar_cls = None
55

56

tqchen committed
57
@register_node
58
class Tensor(NodeBase, _expr.ExprOp):
tqchen committed
59
    """Tensor object, to construct, see function.Tensor"""
60

tqchen committed
61 62 63 64
    def __call__(self, *indices):
        ndim = self.ndim
        if len(indices) != ndim:
            raise ValueError("Need to provide %d index in tensor slice" % ndim)
65
        indices = convert_to_node(indices)
tqchen committed
66 67
        args = []
        for x in indices:
68
            if isinstance(x, _expr.Expr):
tqchen committed
69
                args.append(x)
70 71
            elif isinstance(x, iter_var_cls):
                args.append(x.var)
tqchen committed
72 73 74
            else:
                raise ValueError("The indices must be expression")

75 76 77
        return _make.Call(self.dtype, self.op.name,
                          args, _expr.Call.Halide,
                          self.op, self.value_index)
tqchen committed
78

79 80 81
    def __getitem__(self, indices):
        return TensorSlice(self, indices)

82
    def __hash__(self):
83
        return _api_internal._TensorHash(self)
84 85 86

    def __eq__(self, other):
        if not isinstance(other, Tensor):
87 88
            if isinstance(other, _expr.ExprOp):
                return _expr.EqualOp(self, other)
89
            return False
90 91 92 93
        if self.ndim == 0 and other.ndim == 0:
            raise ValueError("Equal == comparison among rank-0 tensor is ambiguous, "
                             "use Tensor.equal for content expression equvalence, "
                             "use Tensor.same_as for exact reference comparison")
94
        return _api_internal._TensorEqual(self, other)
95

tqchen committed
96 97
    @property
    def ndim(self):
98
        """Dimension of the tensor."""
tqchen committed
99
        return len(self.shape)
100

101 102 103 104 105 106 107 108 109 110 111 112
    @property
    def axis(self):
        """Axis of the tensor."""
        return self.__getattr__("axis")

    @property
    def op(self):
        """The corressponding :any:`Operation`."""
        return self.__getattr__("op")

    @property
    def value_index(self):
113
        """The output value index the tensor corresponds to."""
114 115 116 117 118 119 120
        return self.__getattr__("value_index")

    @property
    def shape(self):
        """The output shape of the tensor."""
        return self.__getattr__("shape")

121 122 123 124 125
    @property
    def name(self):
        op = self.op
        if op.num_outputs == 1:
            return op.name
126
        return "%s.v%d" % (op.name, self.value_index)
127

128

129

130
class Operation(NodeBase):
131
    """Represent an operation that generates a tensor"""
132

133 134 135 136 137 138 139 140 141 142 143 144 145
    def output(self, index):
        """Get the index-th output of the operation

        Parameters
        ----------
        index : int
            The index size.

        Returns
        -------
        out : Tensor
            The i-th output.
        """
146
        return _api_internal._OpGetOutput(self, index)
147

148 149
    @property
    def num_outputs(self):
150
        """Number of outputs from this op."""
151
        return _api_internal._OpNumOutputs(self)
152

153 154 155 156 157 158
    @property
    def input_tensors(self):
        """List of input tensors to this op."""
        return _api_internal._OpInputTensors(self)


159
@register_node
160 161 162
class PlaceholderOp(Operation):
    """Placeholder operation."""

163

164
@register_node
165
class BaseComputeOp(Operation):
166
    """Compute operation."""
167 168
    @property
    def axis(self):
169
        """Represent the IterVar axis, defined when it is a ComputeOp"""
170 171 172 173 174 175 176
        return self.__getattr__("axis")

    @property
    def reduce_axis(self):
        """Represent axis of reductions, only defined when it is a ComputeOp"""
        return self.__getattr__("reduce_axis")

177 178

@register_node
179 180 181 182 183 184 185
class ComputeOp(BaseComputeOp):
    """Scalar operation."""
    pass


@register_node
class TensorComputeOp(BaseComputeOp):
186 187 188 189
    """Tensor operation."""


@register_node
190 191
class ScanOp(Operation):
    """Scan operation."""
192 193
    @property
    def scan_axis(self):
194
        """Represent the scan axis, only defined when it is a ScanOp"""
195 196
        return self.__getattr__("scan_axis")

197 198 199

@register_node
class ExternOp(Operation):
200
    """External operation."""
201

202 203 204 205

@register_node
class HybridOp(Operation):
    """Hybrid operation."""
206 207
    @property
    def axis(self):
208
        """Represent the IterVar axis, also defined when it is a HybridOp"""
209
        return self.__getattr__("axis")
210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 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 312 313 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


@register_node
class Layout(NodeBase):
    """Layout is composed of upper cases, lower cases and numbers,
    where upper case indicates a primal axis and
    the corresponding lower case with factor size indicates the subordinate axis.
    For example, NCHW16c can describe a 5-D tensor of
    [batch_size, channel, height, width, channel_block].
    Here subordinate axis channel_block=16 is the factor size of the primal axis C (channel).

    Do not construct directly, use :any:`layout` instead.
    See the documentation of :any:`layout` for more details.

    See Also
    --------
    layout : Declare a layout
    """
    def __len__(self):
        return _api_internal._LayoutNdim(self)

    def __contains__(self, axis):
        return len(axis) == 1 and axis[0].isalpha() and axis[0] in self.name

    def __getitem__(self, index):
        if index >= len(self):
            raise IndexError("Layout index out of range")
        return _api_internal._LayoutGetItem(self, index)

    def index_of(self, axis):
        """Get the index of an axis

        Parameters
        ----------
        axis : str
            The axis name, need to be [a-z,A-Z]

        Returns
        -------
        index : int
            The index of the axis, -1 if not found.
        """
        return _api_internal._LayoutIndexOf(self, axis)

    def factor_of(self, axis):
        """Get the factor size of the subordinate axis.

        Parameters
        ----------
        axis : str
            The axis name, need to be [a-z,A-Z]

        Returns
        -------
        factor : int
            the size of the subordinate-axis of axis (if axis is a primal-axis),
            or the size of axis itself (if axis is a subordinate-axis).
            Return -1 if axis is not in the layout.
        """
        return _api_internal._LayoutFactorOf(self, axis)


@register_node
class BijectiveLayout(NodeBase):
    """Bijective mapping for two layouts (src-layout and dst-layout).
    It provides shape and index conversion between each other.

    Do not construct directly, use :any:`bijective_layout` instead.
    See the documentation of :any:`bijective_layout` for more details.

    See Also
    --------
    bijective_layout : Declare a bijective layout converter
    """
    def forward_index(self, index):
        """Given the indices of the src-layout, infer the dst index.

        Parameters
        ----------
        index: Array of Expr
            The indices in src-layout.

        Returns
        -------
        dst_index: Array of Expr
            The inferred indices in dst-layout.
        """
        return _api_internal._BijectiveLayoutForwardIndex(self, index)

    def backward_index(self, index):
        """Given the indices of the dst-layout, infer the src index.

        Parameters
        ----------
        index: Array of Expr
            The indices in dst-layout.

        Returns
        -------
        src_index: Array of Expr
            The inferred indices in src-layout.
        """
        return _api_internal._BijectiveLayoutBackwardIndex(self, index)

    def forward_shape(self, shape):
        """Given the shape of the src-layout, infer the dst shape.

        Parameters
        ----------
        shape: Array of Expr
            The shape in src-layout.

        Returns
        -------
        dst_shape: Array of Expr
            The inferred shape in dst-layout.
        """
        return _api_internal._BijectiveLayoutForwardShape(self, shape)

    def backward_shape(self, shape):
        """Given the shape of the dst-layout, infer the src shape.

        Parameters
        ----------
        shape: Array of Expr
            The shape in dst-layout.

        Returns
        -------
        src_shape: Array of Expr
            The inferred shape in src-layout.
        """
        return _api_internal._BijectiveLayoutBackwardShape(self, shape)