eager_tensor.h 10.6 KB
Newer Older
J
Jiabin Yang 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
// 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
// framework deps
#include "paddle/fluid/framework/pten_utils.h"
#include "paddle/fluid/framework/tensor.h"
#include "paddle/fluid/framework/variable.h"
// pten deps
#include "paddle/pten/api/all.h"
22
#include "paddle/pten/api/lib/api_declare.h"
J
Jiabin Yang 已提交
23
#include "paddle/pten/api/lib/utils/tensor_utils.h"
24
#include "paddle/pten/core/convert_utils.h"
J
Jiabin Yang 已提交
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
/**
 * This class is used by Eager mode for now. It's painful to do this in Eager
 * Mode, the better
 * choice is to use paddle::experimental::Tensor directly. However, we have a
 * punch of nested kernel code, and
 * they use paddle::framework::Variable in inner logic code. So, we have to
 * provide variable in
 * paddle::framework::ExecutionContext to support it. We should remove this as
 * soon as we finish our latest
 * Pten Lib, and use paddle::experimental::Tensor instead.
 *
 * Note: Keep this class as clean as possible.
 * This class should only support method declared in
 * paddle::experimental::Tensor with access method of
 * paddle::framework::Variable no more members are acceptable.
 * **/

namespace egr {
class EagerTensor final {
 public:
  /* Part 1: Constructors */
  EagerTensor()
      : tensor_(std::make_shared<paddle::experimental::Tensor>()),
        var_(paddle::framework::Variable()) {}
  explicit EagerTensor(const std::string& name)
      : tensor_(std::make_shared<paddle::experimental::Tensor>(name)),
        var_(paddle::framework::Variable()) {}
  /**
   * @description: Use a TensorImpl pointer to construct a Tensor
   * @param {shared_ptr<TensorBase>} tensor_impl
   * @return {Tensor}
   */
  explicit EagerTensor(const std::shared_ptr<pten::TensorBase>& tensor_impl)
      : tensor_(std::make_shared<paddle::experimental::Tensor>(tensor_impl)),
        var_(paddle::framework::Variable()) {}
60

J
Jiabin Yang 已提交
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 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 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155
  EagerTensor(const EagerTensor&) = default;
  EagerTensor(EagerTensor&&) = default;

  /* Part 2: Name access methods */
  /**
   * @description: Return the name of current Tensor.
   * @param None
   * @return {const std::string&}
   */
  const std::string& name() const { return tensor_->name(); }
  /**
   * @description: Set the name of current Tensor.
   * @param {const std::string& name}
   * @return None
   */
  void set_name(const std::string& name) { tensor_->set_name(name); }

  /* Part 3: Dimension, DataType and DataLayout methods */
  /**
   * @description: Return the number of elements of current Tensor.
   * @param None
   * @return {int64_t}
   */
  int64_t numel() const { return tensor_->numel(); }
  /**
   * @description: Return the shape (dimensions) of current Tensor.
   * @param None
   * @return {DDim}
   */
  paddle::framework::DDim shape() const { return tensor_->dims(); }

  /**
   * @description: Return the data type of current Tensor.
   * @param None
   * @return {DataType}
   */
  paddle::experimental::DataType type() const { return tensor_->type(); }

  /**
   * @description: Return the layout of current Tensor.
   * @param None
   * @return {DataLayout}
   */
  paddle::experimental::DataLayout layout() const { return tensor_->layout(); }

  /* Part 3: Device and Backend methods */
  /**
   * @description: Return the place (device) of current Tensor.
   * @param None
   * @return {Place}
   */
  paddle::platform::Place place() const { return tensor_->inner_place(); }

  /**
   * Backend judgment APIs, shield the concept of Backend.
   */
  bool is_cpu() const { return paddle::platform::is_cpu_place(place()); }
  bool is_cuda() const { return paddle::platform::is_gpu_place(place()); }

  /* Part 4: Data Access methods */
  /**
   * @description: Return the implemention of current Tensor.
   * @param None
   * @return {std::shared_ptr<TensorBase>}
   */
  std::shared_ptr<pten::TensorBase> impl() const { return tensor_->impl(); }

  /**
   * @description: Set the implemention of current Tensor.
   * @param {std::shared_ptr<TensorBase>}
   * @return None
   */
  void set_impl(const std::shared_ptr<pten::TensorBase>& impl) {
    tensor_->set_impl(impl);
  }

  // TODO(chenweihang): Whether API Tensor need `data` and `mutable_data`?

  // TODO(chenweihang): slice and split methods use kernels?

  /* Part 5: Status utils methods */
  /**
   * @description: Determine whether it is a meaningful Tensor
   * @param None
   * @return {bool}
   */
  bool defined() const { return tensor_->defined(); }

  /**
   * @description: Determine whether Tensor is initialized
   * @param None
   * @return {bool}
   */
  bool initialized() const { return tensor_->initialized(); }

156 157 158 159
  bool safe_initialized() const {
    return initialized() || var_.IsInitialized();
  }

J
Jiabin Yang 已提交
160 161 162 163 164 165 166
  /**
   * @description: Reset the Tensor implementation
   * @param None
   * @return {void}
   */
  void reset() { tensor_->reset(); }

167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196
  /**
 * @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
 */
  // TODO(chenweihang): replace Backend by new Place
  EagerTensor copy_to(pten::Backend backend, bool blocking) const {
    if (Var().IsInitialized()) {
      const_cast<EagerTensor*>(this)->SyncToTensor();
    }
    return EagerTensor(tensor_->copy_to(backend, blocking));
  }

  /**
 * @brief Transfer the source Tensor to current Tensor.
 *
 * @param src, the source Tensor to be copied.
 * @param blocking, Should we copy this in sync way.
 * @return void
 */
  void copy_(const EagerTensor& src, const bool blocking) {
    if (src.Var().IsInitialized()) {
      const_cast<EagerTensor*>(&src)->SyncToTensor();
    }
    if (Var().IsInitialized()) {
      SyncToTensor();
    }
    tensor_->copy_(*(src.tensor_.get()), blocking);
  }
J
Jiabin Yang 已提交
197 198 199 200 201 202 203 204 205 206 207 208 209 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
  /* Part 6: Operator overloading */
  EagerTensor& operator=(const EagerTensor& x) & {
    tensor_ = x.tensor_;
    var_ = x.var_;
    return *this;
  }
  EagerTensor& operator=(EagerTensor&& x) & {
    tensor_ = std::move(x.tensor_);
    var_ = std::move(x.var_);
    return *this;
  }

  /* Part 7: Autograd methods */
  paddle::experimental::AbstractAutogradMeta* get_autograd_meta() const {
    return tensor_->get_autograd_meta();
  }
  void set_autograd_meta(
      std::shared_ptr<paddle::experimental::AbstractAutogradMeta>
          autograd_meta) {
    tensor_->set_autograd_meta(autograd_meta);
  }

  /** Part 9: Get framework::Variable from EagerTensor **/
  const paddle::framework::Variable& Var() const { return var_; }

  paddle::framework::Variable* MutableVar() { return &var_; }

  /** Part 10: Sync paddle::framework::Variable with pten::Tensor **/
  void SyncToVar(paddle::framework::proto::VarType_Type type =
                     paddle::framework::proto::VarType::LOD_TENSOR) {
    // Synchronize allocation only once.
    if (!var_.IsInitialized()) {
      // TODO(jiabin): Support selected rows later.
      if (this->initialized()) {
        if (type == paddle::framework::proto::VarType::LOD_TENSOR) {
          auto* framework_tensor =
              var_.GetMutable<paddle::framework::LoDTensor>();
          framework_tensor->Resize(tensor_->dims());
235
          framework_tensor->set_layout(tensor_->layout());
J
Jiabin Yang 已提交
236 237 238
          // Contruct framework::Tensor from egr::EagerTensor
          auto tensor_dense =
              std::dynamic_pointer_cast<pten::DenseTensor>(tensor_->impl());
239
          if (tensor_dense && tensor_dense.get()) {
240 241
            paddle::experimental::SharesStorage(tensor_dense.get(),
                                                framework_tensor);
J
Jiabin Yang 已提交
242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258
          } else {
            PADDLE_THROW(paddle::platform::errors::Fatal(
                "Unrecognized egr::EagerTensor type, only "
                "DenseTensor is supported for now."));
          }
        }
      } else {
        PADDLE_THROW(paddle::platform::errors::Fatal(
            "Can not Sync EagerTensor %s whose "
            "pten::DenseTensor is not initialized!",
            name()));
      }
    }
  }
  /** Part 11: Sync paddle::framework::Variable with pten::Tensor **/
  void SyncToTensor() {
    // Synchronize allocation only once.
259 260 261 262 263 264
    if (var_.IsInitialized()) {
      if (var_.IsType<paddle::framework::LoDTensor>()) {
        SetImplWithLegacyTensor<paddle::framework::LoDTensor,
                                pten::DenseTensor>();
      } else if (var_.IsType<paddle::framework::Tensor>()) {
        SetImplWithLegacyTensor<paddle::framework::Tensor, pten::DenseTensor>();
J
Jiabin Yang 已提交
265
      } else {
266 267 268 269
        PADDLE_THROW(
            paddle::platform::errors::Fatal("Unable to fetch underlying tensor "
                                            "from VarBase, only LoDTensor and "
                                            "Tensor are supported for now"));
J
Jiabin Yang 已提交
270
      }
271 272 273 274 275
    } else {
      PADDLE_THROW(paddle::platform::errors::Fatal(
          "Can not Sync EagerTensor %s whose paddle::framework::Variable is "
          "not initialized!",
          name()));
J
Jiabin Yang 已提交
276 277 278 279 280
    }
  }

  void ResetVar(const paddle::framework::Variable& src) { var_ = src; }

281 282 283 284 285 286 287 288
  const std::shared_ptr<paddle::experimental::Tensor>& Tensor() const {
    return tensor_;
  }

  void set_tensor(const std::shared_ptr<paddle::experimental::Tensor>& tensor) {
    tensor_ = tensor;
  }

J
Jiabin Yang 已提交
289 290 291 292
 private:
  template <typename LEGACY_TYPE, typename TYPE>
  void SetImplWithLegacyTensor() {
    const auto& framework_tensor = var_.Get<LEGACY_TYPE>();
293
    if (defined()) {
294 295
      VLOG(8) << "Sync Var to initialized tensor for: " << name();
      paddle::experimental::ReMakePtenDenseTensor(
296
          framework_tensor, static_cast<pten::DenseTensor*>(impl().get()));
297 298 299 300 301
    } else {
      VLOG(8) << "Sync Var to uninitialized tensor for: " << name();
      this->set_impl(std::move(
          paddle::experimental::MakePtenDenseTensor(framework_tensor)));
    }
J
Jiabin Yang 已提交
302 303 304 305
    var_.Clear();
  }

 private:
306 307 308 309 310 311 312 313 314 315
  /**
  * @description: Use a pten::Tensor pointer to construct a EagerTensor, never
  * public this!!!!.
  * @param {pten::Tensor} tensor
  * @return {EagerTensor}
  */
  explicit EagerTensor(const paddle::experimental::Tensor& tensor)
      : tensor_(std::make_shared<paddle::experimental::Tensor>(tensor)),
        var_(paddle::framework::Variable()) {}

J
Jiabin Yang 已提交
316 317 318 319
  std::shared_ptr<paddle::experimental::Tensor> tensor_ = nullptr;
  paddle::framework::Variable var_;
};
}  // namespace egr