tensor.h 12.1 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
/* Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.

Licensed 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. */

#pragma once

#include <functional>
#include <memory>
#include <utility>
20
#include <vector>
21

22 23 24 25
#ifdef PADDLE_WITH_CUDA
#include <cuda_runtime.h>
using gpuStream_t = cudaStream_t;
#endif
26

27 28 29 30 31 32 33
#ifdef PADDLE_WITH_HIP
#include <hip/hip_runtime.h>
using gpuStream_t = hipStream_t;
#endif

#include "paddle/pten/api/ext/dll_decl.h"
#include "paddle/pten/api/ext/place.h"
34
#include "paddle/pten/common/backend.h"
35 36 37 38 39 40
#include "paddle/pten/common/data_type.h"
#include "paddle/pten/common/layout.h"

namespace pten {
class TensorBase;
}  // namespace pten
41 42

namespace paddle {
43 44 45 46 47 48
namespace framework {
class DDim;
}
namespace platform {
class Place;
}
49 50 51
namespace experimental {

class Tensor;
52
class CompatiblePTenTensorUtils;
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 80 81 82 83 84 85 86

class AbstractAutogradMeta {
 public:
  // No AbstractAutogradMeta should be created
  virtual ~AbstractAutogradMeta() {}
};

/**
 * Tensor is the API description of the basic data structure in the
 * [ "Paddle Tensor Operation (pten)" Library ].
 *
 * It is not limited to a simple n-dimensional array.
 * It contains a smart pointer to `TensorImpl`. The data description contained
 * in Tensor is defined by TensorImpl. Tensor only defines the interface for
 * computation.
 *
 * This is a new Tensor design, which is independent of the original
 * framework::Tensor in fluid. The original Tensor will be gradually discarded
 * in the future.
 *
 * Note: Tensor can be NULL state, Tensor is meaningful only when the
 * TensorImpl to which it is pointed is not empty.
 *
 * Note: For the consistency of C++ API self, and the consistency between C++
 * API and Python API, all member methods of Tensor are named with lowercase
 * letters and underscores.
 *
 * Note: Tensor cannot be inherited. The heterogeneous Tensor implementation
 * can be achieved by inheriting the underlying TensorBase.
 *
 * Note: This Tensor API is suitable for training and custom operators,
 * another simple Tensor design may be required for inference.
 */

87
class PD_DLL_DECL Tensor final {
88
 public:
89 90
  /* Part 1: Construction and destruction methods */

91 92 93 94 95 96 97 98
  /**
   * @brief Construct a new Tensor object
   */
  Tensor() = default;

  /**
   * @brief Construct a new Tensor object by copy
   */
99
  Tensor(const Tensor&) = default;
100 101 102 103

  /**
   * @brief Construct a new Tensor object by move
   */
104 105 106
  Tensor(Tensor&&) = default;

  /**
107 108 109 110 111 112 113 114 115 116 117
   * @brief Construct a new Tensor object by a TensorBase pointer
   *
   * @param tensor_impl
   */
  explicit Tensor(std::shared_ptr<pten::TensorBase> tensor_impl);

  /**
   * @brief Construct a new Tensor object on the target place.
   * This is a deprecated method and may be removed in the future!
   *
   * @param place
118
   */
119 120 121 122 123 124 125 126 127 128 129
  explicit Tensor(const PlaceType& place);

  /**
   * @brief Construct a new Tensor object on the target place
   * with specified shape.
   * This is a deprecated method and may be removed in the future!
   *
   * @param place
   * @param shape
   */
  Tensor(const PlaceType& place, const std::vector<int64_t>& shape);
130

131
  /* Part 2: Dimension, DataType and DataLayout methods */
132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148

  /**
   * @brief Return the number of elements of Tensor.
   *
   * @return int64_t
   */
  int64_t numel() const;

  /**
   * @brief Get the size of current tensor.
   * The compatible method of `Tensor::numel()`.
   * This is a deprecated method and may be removed in the future!
   *
   * @return int64_t
   */
  int64_t size() const;

149
  /**
150 151 152
   * @brief Return the dimensions of Tensor.
   *
   * @return paddle::framework::DDim
153
   */
154
  paddle::framework::DDim dims() const;
155 156

  /**
157 158 159 160 161 162 163 164 165 166
   * @brief Return the shape (dimensions) of Tensor.
   * The compatible method of `Tensor::dims()`.
   * This is a deprecated method and may be removed in the future!
   *
   * @return std::vector<int64_t>
   */
  std::vector<int64_t> shape() const;

  /**
   * @brief Reset the shape of the tensor.
167 168 169 170
   * Note: This method means Reset the shape of the tensor,
   * and must be called before calling mutable_data() or
   * copy_to(const PlaceType& place), this is not a standard definition of
   * reshape behavior, so we will deprecated this feature in the future.
171 172 173 174 175 176 177 178 179
   *
   * @param shape
   */
  void reshape(const std::vector<int64_t>& shape);

  /**
   * @brief Return the data type of Tensor.
   *
   * @return DataType
180
   */
181
  DataType dtype() const;
182 183

  /**
184 185 186 187 188
   * @brief Return the data type of Tensor.
   * The compatible method of `Tensor::dtype()`.
   * This is a deprecated method and may be removed in the future!
   *
   * @return DataType
189
   */
190
  DataType type() const;
191 192

  /**
193 194 195
   * @brief Return the layout of Tensor.
   *
   * @return DataLayout
196
   */
197
  DataLayout layout() const;
198 199

  /* Part 3: Device and Backend methods */
200

201
  /**
202 203 204 205
   * @brief Return the place (device) of Tensor.
   * This is a deprecated method and may be removed in the future!
   *
   * @return PlaceType
206
   */
207
  PlaceType place() const;
208 209

  /**
210 211 212 213 214
   * @brief Return the place (device) of Tensor.
   * Because the `place` method already exists, so we need to use a new name,
   * here we temporarily use `inner_place`.
   *
   * @return paddle::platform::Place
215
   */
216
  paddle::platform::Place inner_place() const;
217 218

  /**
219 220 221 222
   * @brief Determine whether the tensor device is CPU
   *
   * @return true
   * @return false
223
   */
224 225 226 227 228 229 230 231 232
  bool is_cpu() const;

  /**
   * @brief Determine whether the tensor device is CUDA
   *
   * @return true
   * @return false
   */
  bool is_cuda() const;
233 234

  /* Part 4: Data Access methods */
235 236 237 238 239 240 241 242 243 244 245

  /**
   * @brief Get the memory pointer in CPU or GPU with specific data type.
   * It's usually used to get the output data pointer.
   *
   * @tparam T
   * @return T*
   */
  template <typename T>
  T* mutable_data();

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
   * @brief Get the memory pointer in CPU or GPU with specific data type.
   * It's usually used to get the output data pointer.
   * This is a deprecated method and may be removed in the future!
   *
   * @tparam T
   * @param place
   * @return T*
   */
  template <typename T>
  T* mutable_data(const PlaceType& place);

  /**
   * @brief Get the const memory pointer directly.
   * It's usually used to get the output data pointer.
   *
   * @tparam T
   * @return T*
   */
  template <typename T>
  const T* data() const;

  /**
   * @brief Get the memory pointer directly.
   * It's usually used to get the output data pointer.
   * This is a deprecated method and may be removed in the future!
   *
   * @tparam T
   * @return T*
   */
  template <typename T>
  T* data();

  /**
   * @brief Return a sub-tensor of the given tensor.
   * It is usually used to extract a sub-tensor (which supports
   * modifying the data of the original tensor) to perform further
   * operations.
   *
   * @param begin_idx The index of the start row (inclusive) to slice.
   *                  The index number begins from 0.
   * @param end_idx The index of the end row (exclusive) to slice.
   *                 The index number begins from begin_idx + 1.
   * @return Tensor
   */
  Tensor slice(const int64_t begin_idx, const int64_t end_idx) const;

  /**
   * @brief Return the implemention of current Tensor.
   *
   * @return std::shared_ptr<pten::TensorBase>
   */
  std::shared_ptr<pten::TensorBase> impl() const;

  /**
   * @brief Set the implemention of current Tensor.
   *
   * @param impl
   */
  void set_impl(const std::shared_ptr<pten::TensorBase>& impl);

#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
  /**
   * @brief Get the stream where the tensor is currently located
   * This is a deprecated method and may be removed in the future!
   *
   * @return gpuStream_t
   */
  gpuStream_t stream() const;
#endif

  /* Part 5: Data Transform methods */

  /**
   * @brief Copy the current Tensor data to the specified device
321 322 323 324 325
   * and return the new Tensor. It's usually used to set the input tensor data.
   * Note: The Tensor's `copy_to` method is deprecated since version 2.3, and
   * will be removed in version 2.4, please use `to` method instead. reason:
   * copying a Tensor to another device does not need to specify the
   * data type template argument
326 327 328 329
   *
   * @tparam T
   * @param target_place, the target place of which the tensor will copy to.
   * @return Tensor
330
   */
331 332
  template <typename T>
  Tensor copy_to(const PlaceType& target_place) const;
333 334

  /**
335 336 337 338 339
   * @brief Transfer the current Tensor to the specified device and return.
   *
   * @param place, the target place of which the tensor will copy to.
   * @return Tensor
   */
340 341 342
  // TODO(chenweihang): replace Backend by new Place, may be append dtype and
  // layout arguments in the future
  Tensor to(Backend backend, bool blocking) const;
343 344 345 346 347 348

  /**
   * @brief Cast datatype from one to another
   *
   * @param target_type
   * @return Tensor
349
   */
350
  Tensor cast(const DataType& target_type) const;
351

352
  /* Part 6: Status utils methods */
353

354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377
  /**
   * @brief Determine whether it is a meaningful Tensor
   *
   * @return true
   * @return false
   */
  bool defined() const;

  /**
   * @brief Determine whether Tensor is initialized.
   *
   * @return true
   * @return false
   */
  bool initialized() const;

  /**
   * @brief Determine whether Tensor is initialized.
   * This is a deprecated method and may be removed in the future!
   *
   * @return true
   * @return false
   */
  bool is_initialized() const;
378 379

  /**
380
   * @brief Reset the Tensor implementation
381
   */
382 383 384
  void reset();

  /* Part 7: Operator overloading */
385 386

  /**
387 388 389 390
   * @brief Assignment operator
   *
   * @param x
   * @return Tensor&
391
   */
392
  Tensor& operator=(const Tensor& x) &;
393 394

  /**
395 396 397 398
   * @brief Move assignment operator
   *
   * @param x
   * @return Tensor&
399
   */
400
  Tensor& operator=(Tensor&& x) &;
401

402
  /* Part 8: Autograd methods */
403

404 405 406 407 408 409
  /**
   * @brief Get the autograd meta object
   *
   * @return AbstractAutogradMeta*
   */
  AbstractAutogradMeta* get_autograd_meta() const;
410

411 412 413 414 415 416
  /**
   * @brief Set the autograd meta object
   *
   * @param autograd_meta
   */
  void set_autograd_meta(std::shared_ptr<AbstractAutogradMeta> autograd_meta);
417

418 419 420 421
  /* Part 9: Auto generated Tensor methods */

 private:
  friend class CompatiblePTenTensorUtils;
422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458

 private:
  /**
   * [ Why use abstract TensorImpl interface here? ]
   *
   * We hope that the data structure at the API level of the framework can be
   * unified to Tensor, but Tensor itself is heterogeneous.
   *
   * Tensor can generally be represented by void* and size_t, place.
   * This is suitable for most scenarios including CPU, CUDA, HIP, CPU, etc.,
   * but there are a few cases where this definition cannot be described,
   * such as the Tensor representation in third-party lib such as Metal,
   * OpenCL, etc., as well as some special Tensor implementations, including
   * Tensor containing only one Scalar value, or Tensor representing String,
   * etc.
   *
   * Therefore, we hope to use a unified interface to shield the underlying
   * heterogeneous Tensor implementation, so that the API level can be unified
   * to one `Tensor`.
   */
  std::shared_ptr<pten::TensorBase> impl_;

  /**
   * [ Why need abstract AbstractAutogradMeta here? ]
   *
   * Dynamic graphs need to hold backward information
   *
   * [ Why AutogradMeta not in TensorImpl? ]
   *
   * 1. AutogradMeta is only used in dynamic graph, It is execution-related
   *    information, not Tensor data description-related information.
   * 2. Kernel calculation does not require AutogradMeta.
   */
  std::shared_ptr<AbstractAutogradMeta> autograd_meta_{nullptr};

  /**
   * Tensor name: used for adapt original execution mechanism and debug analysis
459
   * in the development of new dygraph. It may be removed in the future.
460 461 462 463 464 465
   */
  std::string name_;
};

}  // namespace experimental
}  // namespace paddle
466 467 468 469 470

namespace paddle {
// In order to be compatible with the original custom operator Tensor interface
using Tensor = paddle::experimental::Tensor;
}  // namespace paddle