tensor_wrapper.h 8.5 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
// 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.

/**
 * We now still need TensorWrapper and it is designed to Copy
 * tensor in autograd mode.
 *
 * Since in autograd usage, we need to pass autograd_meta to
 * backward computation however in tensor interface add to much
 * autograd_related method is not a good choice.
 *
 * In TensorWrapper we will keep autograd info to backward, only
 * for input var, but for output var it will only copy autograd
 * with no grad **/

#pragma once
#include "paddle/fluid/eager/autograd_meta.h"
#include "paddle/fluid/eager/grad_node_info.h"
#include "paddle/fluid/eager/utils.h"
31
#include "paddle/phi/api/lib/utils/allocator.h"
32
#ifndef PADDLE_NO_PYTHON
33
#include "paddle/fluid/eager/hooks.h"
34
#endif
35 36 37 38 39

namespace egr {
class TensorWrapper {
 public:
  TensorWrapper() = default;
40
  explicit TensorWrapper(const paddle::Tensor& tensor,
41
                         bool no_need_buffer = false) {
42 43 44 45 46 47 48 49 50
    // set inplace_version_snapshot_ according to tensor's current inplace
    // version.
    if (tensor.impl() && phi::DenseTensor::classof(tensor.impl().get())) {
      phi::DenseTensor* dense_tensor =
          static_cast<phi::DenseTensor*>(tensor.impl().get());
      auto& inplace_version_counter = dense_tensor->InplaceVersionCounter();
      inplace_version_snapshot_ = inplace_version_counter.CurrentVersion();
    }

51
    /**
52 53 54
     * Normally, we should only save data and part of autograd_meta of fwd
     * tensor, and should not reserve its original grad_node,
     * to avoid recursive and additional depends on GradNodeBase
55
     * **/
56
    auto* tensor_autograd_meta = EagerUtils::nullable_autograd_meta(tensor);
57
    no_need_buffer_ = no_need_buffer;
58
    // shallow copy tensor_impl here
59 60 61 62 63
    if (no_need_buffer) {
      if (phi::DenseTensor::classof(tensor.impl().get())) {
        // Only Copy Meta
        phi::DenseTensor* dense_tensor =
            static_cast<phi::DenseTensor*>(tensor.impl().get());
64 65
        // TODO(jiabin): It's not a good idea to set memory size to zero, find
        // another way and change this.
C
Chen Weihang 已提交
66 67 68
        intermidiate_tensor_.set_impl(std::make_shared<phi::DenseTensor>(
            std::make_shared<phi::Allocation>(nullptr, 0, tensor.place()),
            dense_tensor->meta()));
69 70 71 72 73
      } else {
        PADDLE_THROW(paddle::platform::errors::Fatal(
            "Unrecognized tensor type for no_need_buffer feature"));
      }
    } else {
74
#ifndef PADDLE_NO_PYTHON
75
      if (egr::SavedTensorsHooks::GetInstance().IsEnable() &&
W
wanghuancoder 已提交
76
          tensor.is_dense_tensor() && tensor.initialized()) {
77 78
        phi::DenseTensor* dense_tensor =
            static_cast<phi::DenseTensor*>(tensor.impl().get());
C
Chen Weihang 已提交
79 80 81
        intermidiate_tensor_.set_impl(std::make_shared<phi::DenseTensor>(
            std::make_shared<phi::Allocation>(nullptr, 0, tensor.place()),
            dense_tensor->meta()));
82 83 84
        auto pack_hook = egr::SavedTensorsHooks::GetInstance().GetPackHook();
        unpack_hook_ = egr::SavedTensorsHooks::GetInstance().GetUnPackHook();
        packed_value_ = (*pack_hook)(tensor);
85
      } else {
86
#endif
87
        intermidiate_tensor_.set_impl(tensor.impl());
88
#ifndef PADDLE_NO_PYTHON
89
      }
90
#endif
91
    }
92

93 94 95 96
    if (VLOG_IS_ON(7)) {
      // TODO(jiabin): This may has server performance issue
      intermidiate_tensor_.set_name(tensor.name() + "@Saved");
    }
97

98
    if (tensor_autograd_meta) {
99 100 101
      auto autograd_meta =
          std::make_shared<AutogradMeta>(*tensor_autograd_meta);
      autograd_meta->ResetGradNode();
102 103
      intermidiate_tensor_.set_autograd_meta(autograd_meta);
      weak_grad_node_ = tensor_autograd_meta->GetMutableGradNode();
104
    }
105
  }
106

107
#ifndef PADDLE_NO_PYTHON
108 109 110 111 112 113 114
  TensorWrapper(const TensorWrapper& other) {
    no_need_buffer_ = other.no_need_buffer_;
    intermidiate_tensor_ = other.intermidiate_tensor_;
    weak_grad_node_ = other.weak_grad_node_;
    inplace_version_snapshot_ = other.inplace_version_snapshot_;
    packed_value_ = other.packed_value_;
    unpack_hook_ = other.unpack_hook_;
115 116 117
    if (packed_value_) {
      packed_value_->inc_ref();
    }
118 119 120 121 122 123 124 125 126
  }

  TensorWrapper& operator=(const TensorWrapper& other) {
    no_need_buffer_ = other.no_need_buffer_;
    intermidiate_tensor_ = other.intermidiate_tensor_;
    weak_grad_node_ = other.weak_grad_node_;
    inplace_version_snapshot_ = other.inplace_version_snapshot_;
    packed_value_ = other.packed_value_;
    unpack_hook_ = other.unpack_hook_;
127 128 129
    if (packed_value_) {
      packed_value_->inc_ref();
    }
130 131
    return *this;
  }
132
#endif
133

134
  paddle::Tensor recover() {
135 136 137
    VLOG(6) << "Recover tensor: " << intermidiate_tensor_.name()
            << " for wrapper";
    if (!intermidiate_tensor_.defined()) {
138
      VLOG(6) << "Return NULL tensor Here. ";
139
      return paddle::Tensor();
140
    }
141
#ifndef PADDLE_NO_PYTHON
142
    if (packed_value_ && unpack_hook_) {
143
      auto tensor_unpacked = (*unpack_hook_)(packed_value_);
144 145 146 147 148
      auto src_dense_tensor =
          static_cast<phi::DenseTensor*>(tensor_unpacked.impl().get());
      static_cast<phi::DenseTensor*>(intermidiate_tensor_.impl().get())
          ->ResetHolder(src_dense_tensor->MoveMemoryHolder());
    } else {
149
#endif
150
      check_inplace_version();
151
#ifndef PADDLE_NO_PYTHON
152
    }
153
#endif
154

155
    paddle::Tensor recovered_tensor = intermidiate_tensor_;
156 157 158

    std::shared_ptr<GradNodeBase> new_grad_node = weak_grad_node_.lock();
    if (new_grad_node) {
J
Jiabin Yang 已提交
159
      VLOG(7) << "Recovered TensorWrapper with GradNode "
160
              << new_grad_node->name() << " addr: " << new_grad_node.get();
161
    } else {
J
Jiabin Yang 已提交
162
      VLOG(7) << "Recovered TensorWrapper with Empty GradNode";
163 164 165
    }
    auto* intermediate_autograd_meta =
        EagerUtils::nullable_autograd_meta(intermidiate_tensor_);
166

167 168 169
    if (intermediate_autograd_meta) {
      auto p_ab_autograd_meta =
          std::make_shared<AutogradMeta>(*intermediate_autograd_meta);
170
      if (new_grad_node) {
171
        p_ab_autograd_meta->SetGradNode(new_grad_node);
172
      }
173
      recovered_tensor.set_autograd_meta(p_ab_autograd_meta);
174
    }
175 176

    return recovered_tensor;
177 178
  }

179
  paddle::Tensor get_intermidiate_tensor() { return intermidiate_tensor_; }
180

181 182 183
  void clear() { intermidiate_tensor_.reset(); }

 private:
184 185
  void check_inplace_version() {
    if (no_need_buffer_) {
J
Jiabin Yang 已提交
186
      VLOG(7) << "There's no need to check inplace_version because "
187 188 189 190 191 192 193 194 195
                 "no_need_buffer_ is true.";
      return;
    }
    if (intermidiate_tensor_.impl() &&
        phi::DenseTensor::classof(intermidiate_tensor_.impl().get())) {
      phi::DenseTensor* dense_tensor =
          static_cast<phi::DenseTensor*>(intermidiate_tensor_.impl().get());
      auto& inplace_version_counter = dense_tensor->InplaceVersionCounter();

196 197
      uint32_t wrapper_version_snapshot = inplace_version_snapshot_;
      uint32_t tensor_version = inplace_version_counter.CurrentVersion();
198
      PADDLE_ENFORCE_EQ(
199 200
          tensor_version,
          wrapper_version_snapshot,
201 202 203 204 205 206 207
          paddle::platform::errors::PermissionDenied(
              "Tensor '%s' used in gradient computation has been "
              "modified by an inplace operation. "
              "Its version is %d but the expected version is %d. "
              "Please fix your code to void calling an inplace operator "
              "after using the Tensor which will used in gradient "
              "computation.",
208 209
              intermidiate_tensor_.name(),
              tensor_version,
210
              wrapper_version_snapshot));
J
Jiabin Yang 已提交
211
      VLOG(7) << " The wrapper_version_snapshot of Tensor '"
212
              << intermidiate_tensor_.name() << "' is [ "
213
              << wrapper_version_snapshot << " ]";
J
Jiabin Yang 已提交
214
      VLOG(7) << " The tensor_version of Tensor '"
215 216
              << intermidiate_tensor_.name() << "' is [ " << tensor_version
              << " ]";
217 218 219
    }
  }

220
 private:
221
  bool no_need_buffer_ = false;
222
  paddle::Tensor intermidiate_tensor_;
223
  std::weak_ptr<egr::GradNodeBase> weak_grad_node_;
224
  uint32_t inplace_version_snapshot_ = 0;
225
#ifndef PADDLE_NO_PYTHON
226 227
  std::shared_ptr<egr::PyObjectHolderBase> packed_value_;
  std::shared_ptr<egr::UnPackHookBase> unpack_hook_;
228
#else
229
  std::shared_ptr<void> packed_value_;
230 231
  std::shared_ptr<void> unpack_hook_;
#endif
232 233
};
}  // namespace egr