grad_node_info.cc 15.8 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
// 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.

#include "paddle/fluid/eager/grad_node_info.h"
16
#include "paddle/fluid/eager/accumulation/accumulation_node.h"
17
#include "paddle/fluid/eager/autograd_meta.h"
18 19
#include "paddle/fluid/eager/utils.h"

20 21
#include "paddle/phi/common/data_type.h"
#include "paddle/phi/core/dense_tensor.h"
22
#include "paddle/phi/core/sparse_coo_tensor.h"
23

24 25 26
#include "paddle/fluid/framework/convert_utils.h"
#include "paddle/fluid/framework/data_type.h"
#include "paddle/fluid/framework/data_type_transform.h"
27
#include "paddle/fluid/framework/var_type.h"
28

29 30 31 32 33 34
#include "paddle/fluid/platform/enforce.h"
#include "paddle/fluid/platform/errors.h"

#include "glog/logging.h"

/**
35
 * Implementation of GradNodeBase, Edge and GradTensorHolder.
36 37 38 39
**/
namespace egr {

GradNodeBase::GradNodeBase(size_t bwd_in_slot_num, size_t bwd_out_slot_num) {
J
Jiabin Yang 已提交
40
  VLOG(6) << "Construct GradNodeBase";
41 42 43 44 45
  bwd_in_meta_.resize(bwd_in_slot_num);
  bwd_out_meta_.resize(bwd_out_slot_num);
  adj_edges_.resize(bwd_out_slot_num);
}

46 47 48 49 50 51 52
void GradNodeBase::AddEdges(std::vector<AutogradMeta*>* metas, size_t slot_id) {
  PADDLE_ENFORCE_LT(
      slot_id, adj_edges_.size(),
      paddle::platform::errors::InvalidArgument(
          "Given slot id is out of range of adj_edges outter size, "
          "adj_edges is designed to has the same size of grad "
          "inputs's slot num."));
53 54 55

  for (size_t i = 0; i < metas->size(); i++) {
    const auto& meta = (*metas)[i];
56 57 58
    // adj_edges has as same rank as fwd inputs, and record it's output rank
    // from
    // its pre-ops
59
    if (meta && !meta->StopGradient()) {
60
      auto node = meta->GetMutableGradNode();
61
      if (!node || !node.get()) {
62
        meta->SetGradNode(std::make_shared<egr::GradNodeAccumulation>(meta));
63
      }
64 65 66

      adj_edges_[slot_id].emplace_back(meta->GetMutableGradNode(),
                                       meta->OutRankInfo());
J
Jiabin Yang 已提交
67 68
    } else {
      adj_edges_[slot_id].emplace_back();
69
    }
70 71 72
  }
}

73
void GradNodeBase::AddEdges(AutogradMeta* meta, size_t slot_id) {
74 75 76 77 78 79
  PADDLE_ENFORCE_LT(
      slot_id, adj_edges_.size(),
      paddle::platform::errors::InvalidArgument(
          "Given slot id is out of range of adj_edges outter size, "
          "adj_edges is designed to has the same size of grad "
          "inputs's slot num."));
80

81
  if (meta && !meta->StopGradient()) {
82
    auto node = meta->GetMutableGradNode();
83
    if (!node || !node.get()) {
84
      meta->SetGradNode(std::make_shared<egr::GradNodeAccumulation>(meta));
85
    }
86 87 88 89 90
    VLOG(6) << "Add Edges for slot: " << slot_id << ", the Edge is from "
            << this->name() << " to " << meta->GetMutableGradNode()->name();

    adj_edges_[slot_id].emplace_back(meta->GetMutableGradNode(),
                                     meta->OutRankInfo());
J
Jiabin Yang 已提交
91 92
  } else {
    adj_edges_[slot_id].emplace_back();
93
  }
94 95
}

96
const std::vector<std::vector<GradSlotMeta>>& GradNodeBase::InputMeta() const {
97 98 99
  return bwd_in_meta_;
}

100
const std::vector<std::vector<GradSlotMeta>>& GradNodeBase::OutputMeta() const {
101 102 103
  return bwd_out_meta_;
}

104
void GradNodeBase::SetGradInMeta(const paddle::experimental::Tensor& fwd_out,
105
                                 size_t slot_rank) {
106
  VLOG(6) << "Set GradSlotMeta for Grad Inputs";
107
  auto* fwd_out_meta = egr::EagerUtils::nullable_autograd_meta(fwd_out);
108 109 110 111 112 113
  PADDLE_ENFORCE_LE(
      slot_rank, (bwd_in_meta_.size() - 1),
      paddle::platform::errors::InvalidArgument(
          "Slot Rank should less equal than bwd_in_meta_ size, since "
          "bwd_in_meta_ is designed to hold as same num as backward "
          "inputs."));
114 115 116 117 118 119 120 121
  auto& metas = bwd_in_meta_.at(slot_rank);
  if (metas.size() == 0) {
    metas.resize(1);
  }

  auto& meta = metas[0];
  meta.SetStopGradient(fwd_out_meta->StopGradient());

122 123 124 125 126 127
  if (!fwd_out.is_initialized()) {
    VLOG(6)
        << "Skip Configuring GradSlotMeta for uninitialized GradInput Tensor";
    return;
  }

128
  phi::DenseTensor* dense_tensor = nullptr;
129 130 131
  // Record TensorMeta
  if (phi::DenseTensor::classof(fwd_out.impl().get())) {
    // Only Copy Meta
132 133 134 135 136
    dense_tensor = static_cast<phi::DenseTensor*>(fwd_out.impl().get());
  } else if (phi::SparseCooTensor::classof(fwd_out.impl().get())) {
    phi::SparseCooTensor* coo_tensor =
        static_cast<phi::SparseCooTensor*>(fwd_out.impl().get());
    dense_tensor = coo_tensor->mutable_non_zero_elements();
137 138 139
  } else {
    VLOG(6) << "Unable to initialize the DenseTensorMeta of GradSlotMeta with "
               "non-DenseTensor argument.";
140
  }
141 142 143 144 145 146 147 148 149 150 151 152 153
  PADDLE_ENFORCE_NE(
      dense_tensor->meta().dtype, phi::DataType::UNDEFINED,
      paddle::platform::errors::Fatal(
          "Attempting to copy DenseTensorMeta with phi::DataType::UNDEFINED,"
          "which is illegal."));

  meta.SetTensorMeta(dense_tensor->meta());
  meta.SetPlace(fwd_out.inner_place());

  if (paddle::framework::IsComplexType(
          paddle::framework::TransToProtoVarType(dense_tensor->type()))) {
    need_complex_to_real_ = true;
  }
154 155
}

156 157 158
void GradNodeBase::SetGradInMeta(
    const std::vector<paddle::experimental::Tensor>& fwd_out,
    size_t slot_rank) {
159
  VLOG(6) << "Set GradSlotMeta for Grad Inputs";
160
  size_t slot_size = fwd_out.size();
161 162 163 164 165 166
  PADDLE_ENFORCE_LE(
      slot_rank, (bwd_in_meta_.size() - 1),
      paddle::platform::errors::InvalidArgument(
          "Slot Rank should less equal than bwd_in_meta_ size, since "
          "bwd_in_meta_ is designed to hold as same num as backward "
          "inputs."));
167
  auto& metas = bwd_in_meta_.at(slot_rank);
168
  // Init stop gradient vector before use to avoid push back
169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188
  if (metas.size() < slot_size) {
    VLOG(7) << "Init bwd_in_meta_ with slot rank: " << slot_rank;
    metas.resize(slot_size);
  }
  for (size_t i = 0; i < slot_size; i++) {
    auto& meta = metas[i];
    const auto& fwd_out_tensor = fwd_out[i];
    auto* fwd_out_meta =
        egr::EagerUtils::nullable_autograd_meta(fwd_out_tensor);
    PADDLE_ENFORCE_NOT_NULL(fwd_out_meta,
                            paddle::platform::errors::PreconditionNotMet(
                                "Bwd_in_meta should only be called while "
                                "autograd_meta is not null. If you got this "
                                "error, it indicates bugs in framework."));
    if (fwd_out_meta->StopGradient()) {
      // Set Stop Gradient only when its true or non-initialized autograd_meta,
      // since all default value is false.
      meta.SetStopGradient(fwd_out_meta->StopGradient());
    }

189 190 191 192 193 194
    if (!fwd_out_tensor.is_initialized()) {
      VLOG(6)
          << "Skip Configuring GradSlotMeta for uninitialized GradInput Tensor";
      return;
    }

195 196 197 198 199 200 201 202 203 204 205 206
    // Record TensorMeta
    if (phi::DenseTensor::classof(fwd_out_tensor.impl().get())) {
      // Only Copy Meta
      phi::DenseTensor* dense_tensor =
          static_cast<phi::DenseTensor*>(fwd_out_tensor.impl().get());

      PADDLE_ENFORCE_NE(
          dense_tensor->meta().dtype, phi::DataType::UNDEFINED,
          paddle::platform::errors::Fatal("Attempting to copy DenseTensorMeta "
                                          "with phi::DataType::UNDEFINED,"
                                          "which is illegal."));
      meta.SetTensorMeta(dense_tensor->meta());
207 208
      meta.SetPlace(fwd_out_tensor.inner_place());

209 210 211 212 213 214 215 216 217
      if (paddle::framework::IsComplexType(
              paddle::framework::TransToProtoVarType(dense_tensor->type()))) {
        need_complex_to_real_ = true;
      }
    } else {
      VLOG(6) << "Unable to initialize the DenseTensorMeta of GradSlotMeta "
                 "with non-DenseTensor argument.";
    }
  }
218 219
}

220
void GradNodeBase::SetGradOutMeta(const paddle::experimental::Tensor& fwd_in,
221
                                  size_t slot_rank) {
222
  auto* fwd_in_meta = egr::EagerUtils::nullable_autograd_meta(fwd_in);
223
  PADDLE_ENFORCE_LE(
224
      (slot_rank + 1), bwd_out_meta_.size(),
225 226 227 228
      paddle::platform::errors::InvalidArgument(
          "Slot Rank should less equal than bwd_out_meta_ size, "
          "since bwd_out_meta_ is designed to hold as same num as "
          "backward outputs."));
229
  auto& metas = bwd_out_meta_.at(slot_rank);
230
  // Init stop gradient vector before use to avoid push back
231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252
  if (metas.size() == 0) {
    metas.resize(1);
  }
  auto& meta = metas[0];
  if (fwd_in_meta) {
    meta.SetStopGradient(fwd_in_meta->StopGradient());
  } else {
    meta.SetStopGradient(true);
  }

  // Record TensorMeta
  if (fwd_in.impl() && fwd_in.impl().get()) {
    if (phi::DenseTensor::classof(fwd_in.impl().get())) {
      // Only Copy Meta
      phi::DenseTensor* dense_tensor =
          static_cast<phi::DenseTensor*>(fwd_in.impl().get());
      PADDLE_ENFORCE_NE(
          dense_tensor->meta().dtype, phi::DataType::UNDEFINED,
          paddle::platform::errors::Fatal("Attempting to copy DenseTensorMeta "
                                          "with phi::DataType::UNDEFINED,"
                                          "which is illegal."));
      meta.SetTensorMeta(dense_tensor->meta());
253
      meta.SetPlace(fwd_in.inner_place());
254
    }
255 256 257
  } else {
    VLOG(6) << "Unable to initialize the DenseTensorMeta of GradSlotMeta with "
               "non-DenseTensor argument.";
258 259 260
  }
}

261 262 263
void GradNodeBase::SetGradOutMeta(
    const std::vector<paddle::experimental::Tensor>& fwd_in, size_t slot_rank) {
  size_t slot_size = fwd_in.size();
264
  PADDLE_ENFORCE_LE(
265
      slot_rank, (bwd_out_meta_.size() - 1),
266 267 268 269
      paddle::platform::errors::InvalidArgument(
          "Slot Rank should less equal than bwd_out_meta_ size, "
          "since bwd_out_meta_ is designed to hold as same num as "
          "backward outputs."));
270
  auto& metas = bwd_out_meta_.at(slot_rank);
271
  // Init stop gradient vector before use to avoid push back
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
  if (metas.size() < slot_size) {
    metas.resize(slot_size);
  }
  for (size_t i = 0; i < slot_size; i++) {
    const auto& fwd_in_tensor = fwd_in[i];
    auto& meta = metas[i];
    auto* fwd_in_meta = egr::EagerUtils::nullable_autograd_meta(fwd_in_tensor);
    if (fwd_in_meta) {
      // Set Stop Gradient only when its true or non-initialized autograd_meta,
      // since all default value is false.
      meta.SetStopGradient(fwd_in_meta->StopGradient());
    }

    // Record TensorMeta
    if (fwd_in_tensor.impl() && fwd_in_tensor.impl().get()) {
      if (phi::DenseTensor::classof(fwd_in_tensor.impl().get())) {
        // Only Copy Meta
        phi::DenseTensor* dense_tensor =
            static_cast<phi::DenseTensor*>(fwd_in_tensor.impl().get());

        PADDLE_ENFORCE_NE(dense_tensor->meta().dtype, phi::DataType::UNDEFINED,
                          paddle::platform::errors::Fatal(
                              "Attempting to copy DenseTensorMeta with "
                              "phi::DataType::UNDEFINED,"
                              "which is illegal."));
        meta.SetTensorMeta(dense_tensor->meta());
298
        meta.SetPlace(fwd_in_tensor.inner_place());
299 300 301 302 303
      }
    } else {
      VLOG(6) << "Unable to initialize the DenseTensorMeta of GradSlotMeta "
                 "with non-DenseTensor argument.";
    }
304
  }
305 306 307 308 309 310 311 312 313
}

void GradNodeBase::SetDefaultGradInOutMeta() {
  PADDLE_ENFORCE((bwd_out_meta_.size() == 1) && (bwd_in_meta_.size() == 1),
                 paddle::platform::errors::PreconditionNotMet(
                     "We can only support 1 input and 1 output in default grad "
                     "meta setter, other size of inputs and outputs should "
                     "create with Setter and Getters"));
  // Default stop_gradient is false and slot id is 0, slot size is 1;
314 315
  bwd_out_meta_[0].resize(1);
  bwd_in_meta_[0].resize(1);
316 317
}

318 319 320 321 322
int64_t GradNodeBase::RegisterGradientHook(
    size_t slot_id, size_t rank, std::shared_ptr<egr::TensorHook>&& hook) {
  gradient_hooks_.emplace(next_hook_id_,
                          std::make_tuple(slot_id, rank, std::move(hook)));
  return next_hook_id_++;
323 324
}

325 326 327 328
const std::vector<std::vector<Edge>>& GradNodeBase::GetEdges() const {
  return adj_edges_;
}

329 330 331 332
std::vector<std::vector<Edge>>& GradNodeBase::GetMutableEdges() {
  return adj_edges_;
}

333 334 335 336
std::vector<std::vector<paddle::experimental::Tensor>>
GradNodeBase::ApplyGradientHooks(
    const std::vector<std::vector<paddle::experimental::Tensor>>& tensors) {
  std::vector<std::vector<paddle::experimental::Tensor>> outs(tensors.size());
337 338 339 340 341
  for (auto& hook_pair : gradient_hooks_) {
    size_t slot_id = std::get<0>(hook_pair.second);
    size_t rank = std::get<1>(hook_pair.second);

    auto hook = std::get<2>(hook_pair.second);
342 343 344 345 346 347 348 349 350 351 352 353

    PADDLE_ENFORCE(slot_id < tensors.size(),
                   paddle::platform::errors::Fatal(
                       "Slot_id from registered hook should be smaller than "
                       "slot size of grad_tensors"));

    PADDLE_ENFORCE(rank < tensors[slot_id].size(),
                   paddle::platform::errors::Fatal(
                       "rank of slot %d from registered hook should be smaller "
                       "than rank size of grad_tensors",
                       slot_id));

354
    std::vector<paddle::experimental::Tensor>& slot_out = outs[slot_id];
355
    slot_out.resize(tensors[slot_id].size());
356
    paddle::experimental::Tensor& out = slot_out[rank];
357
    if (!out.defined() || !out.initialized()) {
358
      out = (*hook)(tensors[slot_id][rank]);
359
    } else {
360
      // If more than one hook is registered, the input to the next hook func
361
      // should be the output of the previous hook
362
      out = (*hook)(out);
363 364 365 366 367 368 369 370 371 372 373 374
    }
  }

  for (size_t i = 0; i < outs.size(); i++) {
    if (outs[i].empty() && (!tensors[i].empty())) {
      outs[i].resize(tensors[i].size());
    }
    // TODO(Jiabin): Optimize this if we only add hook slot by slot
    for (size_t j = 0; j < outs[i].size(); j++) {
      if (!outs[i][j].defined() || !outs[i][j].initialized()) {
        outs[i][j] = tensors[i][j];
      }
375
      CheckTensor(tensors[i][j], outs[i][j]);
376 377 378 379 380 381
    }
  }

  return outs;
}

382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422
void GradNodeBase::HandleComplexGradToRealGrad(
    std::vector<std::vector<paddle::experimental::Tensor>>* out_grads) {
  for (size_t slot_id = 0; slot_id < out_grads->size(); slot_id++) {
    const std::vector<paddle::experimental::Tensor>& slot_out_grads =
        (*out_grads)[slot_id];
    for (size_t rank_id = 0; rank_id < slot_out_grads.size(); rank_id++) {
      const GradSlotMeta& slot_meta = bwd_out_meta_[slot_id][rank_id];

      PADDLE_ENFORCE(
          slot_meta.HasTensorMeta() > 0,
          paddle::platform::errors::Fatal(
              "We require TensorMeta in GradInputMeta() to obtain forward data "
              "types."
              "However, no TensorMeta is detected in bwd_out_meta_."));

      auto fwd_data_type = paddle::framework::TransToProtoVarType(
          slot_meta.GetTensorMeta().dtype);
      const paddle::experimental::Tensor& grad = slot_out_grads[rank_id];

      if (paddle::framework::IsComplexType(fwd_data_type)) continue;

      // Only Handle Complex To Real for DenseTensor for now
      if (phi::DenseTensor::classof(grad.impl().get())) {
        phi::DenseTensor* grad_dense_tensor =
            static_cast<phi::DenseTensor*>(grad.impl().get());

        auto curr_data_type =
            paddle::framework::TransToProtoVarType(grad_dense_tensor->type());
        if (!paddle::framework::IsComplexType(curr_data_type)) continue;

        // Convert Complex GradOut to Real
        auto out = std::make_shared<phi::DenseTensor>();
        paddle::framework::TransComplexToReal(fwd_data_type, curr_data_type,
                                              *grad_dense_tensor, out.get());

        (*out_grads)[slot_id][rank_id].set_impl(out);
      }
    }
  }
}

423
}  // namespace egr