grad_node_info.cc 19.2 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 17

#include "glog/logging.h"
18
#include "paddle/fluid/eager/accumulation/accumulation_node.h"
19
#include "paddle/fluid/eager/autograd_meta.h"
20 21 22 23
#include "paddle/fluid/eager/utils.h"
#include "paddle/fluid/framework/convert_utils.h"
#include "paddle/fluid/framework/data_type.h"
#include "paddle/fluid/framework/data_type_transform.h"
24 25 26
#include "paddle/fluid/framework/var_type.h"
#include "paddle/fluid/platform/enforce.h"
#include "paddle/fluid/platform/errors.h"
27 28 29
#include "paddle/phi/common/data_type.h"
#include "paddle/phi/core/dense_tensor.h"
#include "paddle/phi/core/sparse_coo_tensor.h"
30
#include "paddle/phi/core/sparse_csr_tensor.h"
31 32

/**
33
 * Implementation of GradNodeBase, Edge and GradTensorHolder.
34
 **/
35 36
namespace egr {

37
static void CheckTensor(const paddle::Tensor& pre, const paddle::Tensor& post) {
38 39 40 41 42
  if (!pre.initialized() && post.initialized()) {
    PADDLE_THROW(paddle::platform::errors::PermissionDenied(
        "The tensor in before and after hook are not consistent"));
  }
  if (pre.initialized() && post.initialized()) {
43 44
    VLOG(7) << phi::DataTypeToString(pre.dtype()) << " "
            << phi::DataTypeToString(post.dtype());
45
    PADDLE_ENFORCE_EQ(
46 47
        pre.dtype(),
        post.dtype(),
48 49 50
        paddle::platform::errors::PermissionDenied(
            "The dtype of tensor before(%s) and after(%s) hook are not "
            "consistent",
51 52
            phi::DataTypeToString(pre.dtype()),
            phi::DataTypeToString(post.dtype())));
53 54 55 56 57 58 59
    PADDLE_ENFORCE_EQ(pre.place(),
                      post.place(),
                      paddle::platform::errors::PermissionDenied(
                          "The place of tensor before(%s) and after(%s) "
                          "hook are not consistent",
                          pre.place().DebugString(),
                          post.place().DebugString()));
60 61 62
  }
}

63
GradNodeBase::GradNodeBase(size_t bwd_in_slot_num, size_t bwd_out_slot_num) {
J
Jiabin Yang 已提交
64
  VLOG(7) << "Construct GradNodeBase";
65 66 67 68
  bwd_in_meta_.resize(bwd_in_slot_num);
  bwd_out_meta_.resize(bwd_out_slot_num);
}

69 70 71
const paddle::small_vector<std::vector<GradSlotMeta>, kSlotSmallVectorSize>&
GradNodeBase::InputMeta() const {
  return bwd_in_meta_;
72 73
}

74 75 76
const paddle::small_vector<std::vector<GradSlotMeta>, kSlotSmallVectorSize>&
GradNodeBase::OutputMeta() const {
  return bwd_out_meta_;
77 78
}

79 80
paddle::small_vector<std::vector<GradSlotMeta>, kSlotSmallVectorSize>&
GradNodeBase::MutableOutputMeta() {
81 82 83
  return bwd_out_meta_;
}

84
void GradNodeBase::SetGradInMeta(const paddle::Tensor& fwd_out,
85
                                 size_t slot_rank) {
J
Jiabin Yang 已提交
86
  VLOG(7) << "Set GradSlotMeta for Grad Inputs";
87
  auto* fwd_out_meta = egr::EagerUtils::nullable_autograd_meta(fwd_out);
88
  PADDLE_ENFORCE_LE(
89 90
      slot_rank,
      (bwd_in_meta_.size() - 1),
91 92 93 94
      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."));
95 96 97 98 99 100
  auto& metas = bwd_in_meta_.at(slot_rank);
  if (metas.size() == 0) {
    metas.resize(1);
  }

  auto& meta = metas[0];
101 102 103
  if (fwd_out_meta && fwd_out_meta->StopGradient()) {
    meta.SetStopGradient(fwd_out_meta->StopGradient());
  }
104

105
  if (!fwd_out.initialized()) {
J
Jiabin Yang 已提交
106
    VLOG(7)
107 108 109 110
        << "Skip Configuring GradSlotMeta for uninitialized GradInput Tensor";
    return;
  }

111
  phi::DenseTensor* dense_tensor = nullptr;
112 113 114
  // Record TensorMeta
  if (phi::DenseTensor::classof(fwd_out.impl().get())) {
    // Only Copy Meta
115 116 117 118 119
    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();
120 121 122 123
  } else if (phi::SparseCsrTensor::classof(fwd_out.impl().get())) {
    phi::SparseCsrTensor* csr_tensor =
        static_cast<phi::SparseCsrTensor*>(fwd_out.impl().get());
    dense_tensor = csr_tensor->mutable_non_zero_elements();
124
  } else {
J
Jiabin Yang 已提交
125
    VLOG(7) << "Unable to initialize the DenseTensorMeta of GradSlotMeta with "
126
               "non-DenseTensor argument.";
127
  }
128
  PADDLE_ENFORCE_NE(
129 130
      dense_tensor->meta().dtype,
      phi::DataType::UNDEFINED,
131 132 133 134 135
      paddle::platform::errors::Fatal(
          "Attempting to copy DenseTensorMeta with phi::DataType::UNDEFINED,"
          "which is illegal."));

  meta.SetTensorMeta(dense_tensor->meta());
C
Chen Weihang 已提交
136
  meta.SetPlace(fwd_out.place());
137

138 139
  if (dense_tensor->type() == paddle::experimental::DataType::COMPLEX64 ||
      dense_tensor->type() == paddle::experimental::DataType::COMPLEX128) {
140 141
    need_complex_to_real_ = true;
  }
142 143
}

144 145
void GradNodeBase::SetGradInMeta(const std::vector<paddle::Tensor>& fwd_out,
                                 size_t slot_rank) {
J
Jiabin Yang 已提交
146
  VLOG(7) << "Set GradSlotMeta for Grad Inputs";
147
  size_t slot_size = fwd_out.size();
148
  PADDLE_ENFORCE_LE(
149 150
      slot_rank,
      (bwd_in_meta_.size() - 1),
151 152 153 154
      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."));
155
  auto& metas = bwd_in_meta_.at(slot_rank);
156
  // Init stop gradient vector before use to avoid push back
157 158 159 160 161 162 163 164 165 166 167 168 169 170
  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."));
171
    if (fwd_out_meta && fwd_out_meta->StopGradient()) {
172 173 174 175 176
      // Set Stop Gradient only when its true or non-initialized autograd_meta,
      // since all default value is false.
      meta.SetStopGradient(fwd_out_meta->StopGradient());
    }

177
    if (!fwd_out_tensor.initialized()) {
J
Jiabin Yang 已提交
178
      VLOG(7)
179 180 181 182
          << "Skip Configuring GradSlotMeta for uninitialized GradInput Tensor";
      return;
    }

183 184 185 186 187 188 189
    // 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(
190 191
          dense_tensor->meta().dtype,
          phi::DataType::UNDEFINED,
192 193 194 195
          paddle::platform::errors::Fatal("Attempting to copy DenseTensorMeta "
                                          "with phi::DataType::UNDEFINED,"
                                          "which is illegal."));
      meta.SetTensorMeta(dense_tensor->meta());
C
Chen Weihang 已提交
196
      meta.SetPlace(fwd_out_tensor.place());
197

198 199
      if (dense_tensor->type() == paddle::experimental::DataType::COMPLEX64 ||
          dense_tensor->type() == paddle::experimental::DataType::COMPLEX128) {
200 201 202
        need_complex_to_real_ = true;
      }
    } else {
J
Jiabin Yang 已提交
203
      VLOG(7) << "Unable to initialize the DenseTensorMeta of GradSlotMeta "
204 205 206
                 "with non-DenseTensor argument.";
    }
  }
207 208
}

209
void GradNodeBase::SetGradOutMeta(const paddle::Tensor& fwd_in,
210
                                  size_t slot_rank) {
211
  auto* fwd_in_meta = egr::EagerUtils::nullable_autograd_meta(fwd_in);
212
  PADDLE_ENFORCE_LE(
213 214
      (slot_rank + 1),
      bwd_out_meta_.size(),
215 216 217 218
      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."));
219
  auto& metas = bwd_out_meta_.at(slot_rank);
220
  // Init stop gradient vector before use to avoid push back
221 222 223 224
  if (metas.size() == 0) {
    metas.resize(1);
  }
  auto& meta = metas[0];
225
  // Set Stop_gradient
226 227
  if (fwd_in_meta) {
    meta.SetStopGradient(fwd_in_meta->StopGradient());
228 229
  } else {
    meta.SetStopGradient(true);
230
  }
231 232 233 234 235 236 237
  // Set Adj Edges
  if (fwd_in_meta && !fwd_in_meta->StopGradient()) {
    auto node = fwd_in_meta->GetMutableGradNode();
    if (!node || !node.get()) {
      fwd_in_meta->SetGradNode(
          std::make_shared<egr::GradNodeAccumulation>(fwd_in_meta));
    }
238
    VLOG(3) << "Add Edges for slot: " << slot_rank << ", the Edge is from "
239 240 241
            << this->name() << " (addr: " << this << ") "
            << " to " << fwd_in_meta->GetMutableGradNode()->name()
            << " (addr: " << fwd_in_meta->GetMutableGradNode().get() << ")";
242

243 244
    meta.SetEdge(fwd_in_meta->GetMutableGradNode(), fwd_in_meta->OutRankInfo());
  }
245 246 247 248 249 250 251
  // 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(
252 253
          dense_tensor->meta().dtype,
          phi::DataType::UNDEFINED,
254 255 256 257
          paddle::platform::errors::Fatal("Attempting to copy DenseTensorMeta "
                                          "with phi::DataType::UNDEFINED,"
                                          "which is illegal."));
      meta.SetTensorMeta(dense_tensor->meta());
C
Chen Weihang 已提交
258
      meta.SetPlace(fwd_in.place());
259
    }
260
  } else {
J
Jiabin Yang 已提交
261
    VLOG(7) << "Unable to initialize the DenseTensorMeta of GradSlotMeta with "
262
               "non-DenseTensor argument.";
263 264 265
  }
}

266 267
void GradNodeBase::SetGradOutMeta(const std::vector<paddle::Tensor>& fwd_in,
                                  size_t slot_rank) {
268
  size_t slot_size = fwd_in.size();
269
  PADDLE_ENFORCE_LE(
270 271
      slot_rank,
      (bwd_out_meta_.size() - 1),
272 273 274 275
      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."));
276
  auto& metas = bwd_out_meta_.at(slot_rank);
277
  // Init stop gradient vector before use to avoid push back
278 279 280 281 282 283 284
  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);
285
    // Set Stop_gradient
286 287 288
    if (fwd_in_meta) {
      meta.SetStopGradient(fwd_in_meta->StopGradient());
    }
289
    // Set Adj Edges
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 321 322 323 324 325 326 327
    if (fwd_in_meta && !fwd_in_meta->StopGradient()) {
      auto node = fwd_in_meta->GetMutableGradNode();
      if (!node || !node.get()) {
        fwd_in_meta->SetGradNode(
            std::make_shared<egr::GradNodeAccumulation>(fwd_in_meta));
      }
      VLOG(3) << "Add Edges for slot: " << slot_rank << ", the Edge is from "
              << this->name() << " (addr: " << this << ") "
              << " to " << fwd_in_meta->GetMutableGradNode()->name()
              << " (addr: " << fwd_in_meta->GetMutableGradNode().get() << ")";

      meta.SetEdge(fwd_in_meta->GetMutableGradNode(),
                   fwd_in_meta->OutRankInfo());
    }
    // 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->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_in_tensor.place());
      }
    } else {
      VLOG(7)
          << "Unable to initialize the DenseTensorMeta of GradSlotMeta with "
             "non-DenseTensor argument.";
    }
  }
}

void GradNodeBase::SetGradOutMeta(
328
    const std::vector<const paddle::Tensor*>& fwd_in, size_t slot_rank) {
329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350
  size_t slot_size = fwd_in.size();
  PADDLE_ENFORCE_LE(
      slot_rank,
      (bwd_out_meta_.size() - 1),
      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."));
  auto& metas = bwd_out_meta_.at(slot_rank);
  // Init stop gradient vector before use to avoid push back
  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);
    // Set Stop_gradient
    if (fwd_in_meta) {
      meta.SetStopGradient(fwd_in_meta->StopGradient());
    }
    // Set Adj Edges
351 352 353 354 355 356
    if (fwd_in_meta && !fwd_in_meta->StopGradient()) {
      auto node = fwd_in_meta->GetMutableGradNode();
      if (!node || !node.get()) {
        fwd_in_meta->SetGradNode(
            std::make_shared<egr::GradNodeAccumulation>(fwd_in_meta));
      }
357
      VLOG(3) << "Add Edges for slot: " << slot_rank << ", the Edge is from "
358 359 360
              << this->name() << " (addr: " << this << ") "
              << " to " << fwd_in_meta->GetMutableGradNode()->name()
              << " (addr: " << fwd_in_meta->GetMutableGradNode().get() << ")";
361

362 363 364
      meta.SetEdge(fwd_in_meta->GetMutableGradNode(),
                   fwd_in_meta->OutRankInfo());
    }
365 366 367 368 369 370
    // 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());
371 372
        PADDLE_ENFORCE_NE(dense_tensor->dtype(),
                          phi::DataType::UNDEFINED,
373
                          paddle::platform::errors::Fatal(
374 375
                              "Attempting to copy DenseTensorMeta "
                              "with phi::DataType::UNDEFINED,"
376 377
                              "which is illegal."));
        meta.SetTensorMeta(dense_tensor->meta());
C
Chen Weihang 已提交
378
        meta.SetPlace(fwd_in_tensor.place());
379 380
      }
    } else {
J
Jiabin Yang 已提交
381
      VLOG(7)
382 383
          << "Unable to initialize the DenseTensorMeta of GradSlotMeta with "
             "non-DenseTensor argument.";
384
    }
385
  }
386 387 388 389 390 391 392 393 394
}

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;
395 396
  bwd_out_meta_[0].resize(1);
  bwd_in_meta_[0].resize(1);
397 398
}

399 400 401 402 403
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_++;
404 405
}

406
paddle::small_vector<std::vector<paddle::Tensor>, kSlotSmallVectorSize>
407
GradNodeBase::ApplyGradientHooks(
408
    const paddle::small_vector<std::vector<paddle::Tensor>,
409
                               kSlotSmallVectorSize>& tensors) {
410 411
  paddle::small_vector<std::vector<paddle::Tensor>, kSlotSmallVectorSize> outs(
      tensors.size());
412 413 414 415 416
  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);
417 418 419 420 421 422 423 424 425 426 427 428

    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));

429
    std::vector<paddle::Tensor>& slot_out = outs[slot_id];
430
    slot_out.resize(tensors[slot_id].size());
431
    paddle::Tensor& out = slot_out[rank];
432
    if (!out.defined() || !out.initialized()) {
433
      out = (*hook)(tensors[slot_id][rank]);
434
    } else {
435
      // If more than one hook is registered, the input to the next hook func
436
      // should be the output of the previous hook
437
      out = (*hook)(out);
438 439 440 441 442 443 444 445 446 447 448 449
    }
  }

  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];
      }
450
      CheckTensor(tensors[i][j], outs[i][j]);
451 452 453 454 455 456
    }
  }

  return outs;
}

457
void GradNodeBase::HandleComplexGradToRealGrad(
458 459
    paddle::small_vector<std::vector<paddle::Tensor>, kSlotSmallVectorSize>*
        out_grads) {
460
  for (size_t slot_id = 0; slot_id < out_grads->size(); slot_id++) {
461
    const std::vector<paddle::Tensor>& slot_out_grads = (*out_grads)[slot_id];
462 463 464 465 466 467 468 469 470 471 472 473
    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);
474
      const paddle::Tensor& grad = slot_out_grads[rank_id];
475 476 477 478 479 480 481 482 483 484 485 486 487 488

      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>();
489 490
        paddle::framework::TransComplexToReal(
            fwd_data_type, curr_data_type, *grad_dense_tensor, out.get());
491 492 493 494 495 496 497

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

498
}  // namespace egr