tensor.h 8.27 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
/*
 * 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.
 */

tqchen committed
20
/*!
tqchen committed
21
 * \file tvm/tensor.h
tqchen committed
22 23 24 25 26
 * \brief Dataflow tensor object
 */
#ifndef TVM_TENSOR_H_
#define TVM_TENSOR_H_

27
#include <tvm/node/container.h>
tqchen committed
28
#include <string>
tqchen committed
29
#include <vector>
30
#include <utility>
tqchen committed
31
#include <type_traits>
tqchen committed
32

33 34
#include "base.h"
#include "expr.h"
35
#include "expr_operator.h"
36
#include "arithmetic.h"
tqchen committed
37 38 39

namespace tvm {

40 41
// Internal node container of Tensor
class TensorNode;
tqchen committed
42 43
// internal node container for Operation
class OperationNode;
44

tqchen committed
45 46 47 48
/*!
 * \brief Tensor structure representing a possible input,
 *  or intermediate computation result.
 */
49
class Tensor : public NodeRef {
50
 public:
tqchen committed
51 52
  /*! \brief default constructor, used internally */
  Tensor() {}
53
  explicit Tensor(ObjectPtr<Object> n) : NodeRef(n) {}
tqchen committed
54
  /*!
55 56 57 58
   * \brief access the internal node container
   * \return the pointer to the internal node container
   */
  inline const TensorNode* operator->() const;
59 60 61 62 63 64
  /*!
   * \brief check if two tensors equals each other.
   * \param other tensor to be checked.
   * \return whether the two tensors equals each other.
   */
  inline bool operator==(const Tensor& other) const;
65 66 67 68 69 70
  /*!
   * \brief check if two tensors are different.
   * \param other tensor to be checked.
   * \return whether the two tensors are different.
   */
  inline bool operator!=(const Tensor& other) const;
tqchen committed
71
  /*! \return The dimension of the tensor */
72
  inline size_t ndim() const;
tqchen committed
73 74 75 76 77
  /*!
   * \brief Take elements from the tensor
   * \param args The indices
   * \return the result expression representing tensor read.
   */
78 79 80
  template<typename... Args>
  inline Expr operator()(Args&& ...args) const {
    Array<Expr> indices{std::forward<Args>(args)...};
tqchen committed
81 82 83 84 85 86 87
    return operator()(indices);
  }
  /*!
   * \brief Take elements from the tensor
   * \param indices the indices.
   * \return the result expression representing tensor read.
   */
88
  TVM_DLL Expr operator()(Array<Expr> indices) const;
89
  /*!
90 91 92 93
   * \brief Take elements from the tensor
   * \param indices the indices.
   * \return the result expression representing tensor read.
   */
94
  TVM_DLL Expr operator()(Array<Var> indices) const;
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 129 130 131 132 133 134
   * \brief data structure to represent a slice that fixes first k coordinates.
   *  This is used to enable syntax sugar of Tensor[x][y][z] to get the element.
   */
  class Slice {
   public:
    // construct via tensor and indices
    Slice(const Tensor& tensor, std::vector<Expr> indices)
        : tensor_(tensor), indices_(indices) {}
    /*!
     * \brief get i-th slice from the current slice.
     * \param i the index of the coordinate
     * \return the subsequent slice.
     */
    inline Slice operator[](Expr i) {
      std::vector<Expr> other = indices_;
      other.emplace_back(i);
      return Slice(tensor_, other);
    }
    /*!
     * \brief Convert slice to expression.
     *  This is only valid when all the coordinates are fully specified.
     * \return the corresponding expression of this slice.
     */
    inline operator Expr() const {
      return tensor_(indices_);
    }

   private:
    const Tensor& tensor_;
    std::vector<Expr> indices_;
  };
  /*!
   * \brief get i-th slice from the current Tensor.
   * \param i the index of the coordinate
   * \return the subsequent slice.
   */
  inline Slice operator[](Expr i) const {
    return Slice(*this, {i});
  }
tqchen committed
135 136
  /*! \brief specify container node */
  using ContainerType = TensorNode;
137 138
};

tqchen committed
139
/*! \brief Operation that produces tensors */
140
class Operation : public ir::FunctionRef {
tqchen committed
141 142 143
 public:
  /*! \brief default constructor  */
  Operation() {}
144
  explicit Operation(ObjectPtr<Object> n) : FunctionRef(n) {}
tqchen committed
145 146 147 148 149 150 151 152 153 154
  /*!
   * \brief access the internal node container
   * \return the pointer to the internal node container
   */
  inline const OperationNode* operator->() const;
  /*!
   * \brief get the i-th output of the operation.
   * \param i the output index.
   * \return The i-th output.
   */
155
  TVM_DLL Tensor output(size_t i) const;
tqchen committed
156 157
  /*! \brief specify container node */
  using ContainerType = OperationNode;
tqchen committed
158
};
tqchen committed
159

160
/*! \brief Node to represent a tensor */
161
class TensorNode : public Node {
162
 public:
tqchen committed
163 164
  /*! \brief The shape of the tensor */
  Array<Expr> shape;
165
  /*! \brief data type in the content of the tensor */
166
  Type dtype;
tqchen committed
167
  /*! \brief the source operation, can be None */
tqchen committed
168
  Operation op;
tqchen committed
169
  /*! \brief the output index from source operation */
tqchen committed
170
  int value_index{0};
171 172
  /*! \brief constructor */
  TensorNode() {}
173

174
  void VisitAttrs(AttrVisitor* v) {
tqchen committed
175
    v->Visit("shape", &shape);
176
    v->Visit("dtype", &dtype);
tqchen committed
177 178
    v->Visit("op", &op);
    v->Visit("value_index", &value_index);
179
  }
180 181 182 183
  TVM_DLL static Tensor make(Array<Expr> shape,
                             Type dtype,
                             Operation op,
                             int value_index);
184 185

  static constexpr const char* _type_key = "Tensor";
186
  TVM_DECLARE_NODE_TYPE_INFO(TensorNode, Node);
tqchen committed
187 188
};

tqchen committed
189 190

// Implementations of inline functions
191
inline const TensorNode* Tensor::operator->() const {
192
  return static_cast<const TensorNode*>(get());
193 194 195 196 197 198
}

inline size_t Tensor::ndim() const {
  return (*this)->shape.size();
}

199 200 201 202 203 204 205 206 207 208 209
inline bool Tensor::operator==(const Tensor& other) const {
  if (get() == other.get()) return true;
  if (get() == nullptr || other.get() == nullptr) return false;
  if ((*this)->op.defined() || other->op.defined()) {
    return (*this)->op == other->op &&
        (*this)->value_index == other->value_index;
  } else {
    return false;
  }
}

210 211 212 213
inline bool Tensor::operator!=(const Tensor& other) const {
  return !(*this == other);
}

214 215 216 217
// macro to turn every operation of slice to expression
#define DEFINE_OVERLOAD_SLICE_UNARY_OP(Op)                              \
  inline Expr operator Op (const Tensor::Slice& a) {                    \
    return Op a.operator Expr() ;                                       \
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

#define DEFINE_OVERLOAD_SLICE_BINARY_OP(Op)                             \
  template<typename T>                                                  \
  inline Expr operator Op (const Tensor::Slice& a, const T& b) {        \
    return a.operator Expr() Op b;                                      \
  }                                                                     \
  template<typename T>                                                  \
  inline Expr operator Op (const T& a, const Tensor::Slice& b) {        \
    return a Op b.operator Expr();                                      \
  }                                                                     \
  inline Expr operator Op (const Tensor::Slice& a, const Tensor::Slice& b) { \
    return a.operator Expr() Op b.operator Expr();                      \
  }

DEFINE_OVERLOAD_SLICE_UNARY_OP(!);
DEFINE_OVERLOAD_SLICE_UNARY_OP(-);
DEFINE_OVERLOAD_SLICE_BINARY_OP(+);
DEFINE_OVERLOAD_SLICE_BINARY_OP(-);
DEFINE_OVERLOAD_SLICE_BINARY_OP(*);
DEFINE_OVERLOAD_SLICE_BINARY_OP(==);
DEFINE_OVERLOAD_SLICE_BINARY_OP(<=);
DEFINE_OVERLOAD_SLICE_BINARY_OP(>=);
DEFINE_OVERLOAD_SLICE_BINARY_OP(!=);
DEFINE_OVERLOAD_SLICE_BINARY_OP(&&);
DEFINE_OVERLOAD_SLICE_BINARY_OP(||);
DEFINE_OVERLOAD_SLICE_BINARY_OP(>>);
DEFINE_OVERLOAD_SLICE_BINARY_OP(<<);
DEFINE_OVERLOAD_SLICE_BINARY_OP(>);  // NOLINT(*)
DEFINE_OVERLOAD_SLICE_BINARY_OP(<);  // NOLINT(*)

tqchen committed
249
}  // namespace tvm
250 251 252

namespace std {
template <>
253
struct hash<::tvm::Operation> : public ::tvm::NodeHash {
254
};
255 256 257 258

template <>
struct hash<::tvm::Tensor> {
  std::size_t operator()(const ::tvm::Tensor& k) const {
259
    ::tvm::NodeHash hasher;
260
    if (k.defined() && k->op.defined()) {
261
      return hasher(k->op);
262
    } else{
263
      return hasher(k);
264 265 266 267
    }
  }
};
}  // namespace std
tqchen committed
268
#endif  // TVM_TENSOR_H_