run_program_op_node.h 32.1 KB
Newer Older
0
0x45f 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
// Copyright (c) 2022 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 "paddle/fluid/eager/api/utils/global_utils.h"
#include "paddle/fluid/eager/grad_node_info.h"
#include "paddle/fluid/eager/tensor_wrapper.h"
20
#include "paddle/fluid/framework/new_executor/interpretercore.h"
21
#include "paddle/fluid/framework/variable_helper.h"
22 23
#include "paddle/fluid/ir/transforms/pd_op_to_kernel_pass.h"
#include "paddle/fluid/ir_adaptor/translator/program_translator.h"
0
0x45f 已提交
24 25
#include "paddle/fluid/operators/run_program_op.h"
#include "paddle/fluid/platform/enforce.h"
26
#include "paddle/fluid/platform/profiler/event_tracing.h"
27 28
#include "paddle/ir/core/program.h"
#include "paddle/ir/core/value.h"
0
0x45f 已提交
29

30 31
PHI_DECLARE_bool(enable_new_ir_in_executor);

0
0x45f 已提交
32
namespace details {
33
using Tensor = paddle::Tensor;
0
0x45f 已提交
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 60 61

static std::vector<Tensor> DereferenceTensors(
    const std::vector<Tensor *> &tensor_ptr) {
  std::vector<Tensor> res;
  for (auto *t : tensor_ptr) {
    res.emplace_back(*t);
  }
  return res;
}

static std::vector<std::string> GetTensorsName(const std::vector<Tensor> &ins) {
  std::vector<std::string> in_names;
  for (auto &in_t : ins) {
    in_names.emplace_back(in_t.name());
  }
  return in_names;
}

static std::vector<std::string> GetTensorsName(
    const std::vector<Tensor *> &ins) {
  std::vector<std::string> in_names;
  for (auto *in_t : ins) {
    in_names.emplace_back(in_t->name());
  }
  return in_names;
}

static void CheckInputVarStatus(const Tensor &tensor) {
62 63
  PADDLE_ENFORCE_EQ(tensor.defined() && tensor.is_dense_tensor(),
                    true,
64 65 66 67 68
                    paddle::platform::errors::InvalidArgument(
                        "The input tensor %s of "
                        "RunProgram(Grad)Op holds "
                        "wrong type. Expect type is DenseTensor.",
                        tensor.name()));
0
0x45f 已提交
69

70 71 72 73 74 75 76 77
  PADDLE_ENFORCE_EQ(
      static_cast<phi::DenseTensor *>(tensor.impl().get())->IsInitialized(),
      true,
      paddle::platform::errors::InvalidArgument(
          "The tensor in input tensor %s of "
          "RunProgram(Grad)Op "
          "is not initialized.",
          tensor.name()));
0
0x45f 已提交
78 79 80 81 82
}

static void CheckOutputVarStatus(const paddle::framework::Variable &src_var,
                                 const Tensor &dst_tensor) {
  auto name = dst_tensor.name();
83 84
  PADDLE_ENFORCE_EQ(dst_tensor.defined(),
                    true,
0
0x45f 已提交
85
                    paddle::platform::errors::InvalidArgument(
86
                        "dst_tensor `%s` shall be defined.", name));
0
0x45f 已提交
87

88
  if (dst_tensor.is_dense_tensor()) {
0
0x45f 已提交
89
    auto &src_tensor = src_var.Get<phi::DenseTensor>();
90 91
    PADDLE_ENFORCE_EQ(phi::DenseTensor::classof(&src_tensor),
                      true,
0
0x45f 已提交
92 93 94 95 96
                      paddle::platform::errors::InvalidArgument(
                          "The output tensor %s get from "
                          "RunProgram(Grad)Op's internal scope holds "
                          "wrong type. Expect type is DenseTensor",
                          name));
97
    PADDLE_ENFORCE_EQ(src_tensor.IsInitialized(),
98
                      true,
0
0x45f 已提交
99 100 101 102 103
                      paddle::platform::errors::InvalidArgument(
                          "The tensor in output tensor %s get from "
                          "RunProgram(Grad)Op's internal "
                          "scope is not initialized.",
                          name));
104
  } else if (dst_tensor.is_selected_rows()) {
0
0x45f 已提交
105
    auto &src_tensor = src_var.Get<phi::SelectedRows>();
106 107
    PADDLE_ENFORCE_EQ(phi::SelectedRows::classof(&src_tensor),
                      true,
0
0x45f 已提交
108 109 110 111 112
                      paddle::platform::errors::InvalidArgument(
                          "The output tensodfr %s get from "
                          "RunProgram(Grad)Op's internal scope holds "
                          "wrong type. Expect type is SelectedRows",
                          name));
113 114
    PADDLE_ENFORCE_EQ(src_tensor.initialized(),
                      true,
0
0x45f 已提交
115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132
                      paddle::platform::errors::InvalidArgument(
                          "The tensor in output tensor %s get from "
                          "RunProgram(Grad)Op's "
                          "internal scope is not initialized.",
                          name));

  } else {
    PADDLE_THROW(paddle::platform::errors::InvalidArgument(
        "The RunProgram(Grad)Op only support output "
        "variable of type LoDTensor or SelectedRows",
        name));
  }
}

static void ShareTensorsIntoScope(const std::vector<Tensor> &tensors,
                                  paddle::framework::Scope *scope) {
  for (size_t i = 0; i < tensors.size(); ++i) {
    auto name = tensors[i].name();
133 134
    if (name == paddle::framework::kFakeVarName ||
        name == paddle::framework::kEmptyVarName) {
0
0x45f 已提交
135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152
      continue;
    }
    auto *var = scope->Var(name);
    CheckInputVarStatus(tensors[i]);
    // share tensor
    auto tensor_base = tensors[i].impl();
    if (phi::DenseTensor::classof(tensor_base.get())) {
      auto *dst_tensor = var->GetMutable<phi::DenseTensor>();
      auto t = std::dynamic_pointer_cast<phi::DenseTensor>(tensor_base);
      *dst_tensor = *t;
    } else if (phi::SelectedRows::classof(tensor_base.get())) {
      auto *dst_tensor = var->GetMutable<phi::SelectedRows>();
      auto t = std::dynamic_pointer_cast<phi::SelectedRows>(tensor_base);
      *dst_tensor = *t;
    }
  }
}

153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177
static void ShareTensorsIntoScopeWithName(
    const std::vector<Tensor> &tensors,
    const std::vector<std::string> &tensor_names,
    paddle::framework::Scope *scope) {
  for (size_t i = 0; i < tensors.size(); ++i) {
    auto name = tensor_names[i];
    if (name == paddle::framework::kFakeVarName) {
      continue;
    }
    auto *var = scope->Var(name);
    CheckInputVarStatus(tensors[i]);
    // share tensor
    auto tensor_base = tensors[i].impl();
    if (phi::DenseTensor::classof(tensor_base.get())) {
      auto *dst_tensor = var->GetMutable<phi::DenseTensor>();
      auto t = std::dynamic_pointer_cast<phi::DenseTensor>(tensor_base);
      *dst_tensor = *t;
    } else if (phi::SelectedRows::classof(tensor_base.get())) {
      auto *dst_tensor = var->GetMutable<phi::SelectedRows>();
      auto t = std::dynamic_pointer_cast<phi::SelectedRows>(tensor_base);
      *dst_tensor = *t;
    }
  }
}

0
0x45f 已提交
178 179 180 181 182 183 184 185 186 187
static void ShareTensorsFromScope(
    const std::vector<Tensor *> &tensors,
    const paddle::framework::BlockDesc &global_block,
    paddle::framework::Scope *scope) {
  for (size_t i = 0; i < tensors.size(); ++i) {
    // NOTE: In case of setting out_tmp.stop_gradient = True in model code, all
    // parameters before generating out_tmp have no @GRAD, it will raise error
    // because we can't find them in scope. So we skip sharing these vars or
    // var@GRAD if they don't appear in global block.
    auto &name = tensors[i]->name();
188 189
    if (name == paddle::framework::kEmptyVarName ||
        name == paddle::framework::kFakeVarName || !global_block.HasVar(name)) {
0
0x45f 已提交
190 191 192 193 194 195
      VLOG(2) << "find tensor name is " << name << ", skip it!";
      continue;
    }
    // NOTE: Here skip not found var is dangerous, if a bug is caused here,
    // the result is grad calculation error, which will be very hidden!
    auto *var = scope->FindVar(name);
196 197 198 199 200 201
    PADDLE_ENFORCE_NOT_NULL(
        var,
        paddle::platform::errors::NotFound("The output tensor %s is not in "
                                           "RunProgram(Grad)Op'"
                                           "s internal scope.",
                                           name));
0
0x45f 已提交
202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218
    CheckOutputVarStatus(*var, *tensors[i]);
    // share tensor
    if (var->IsType<phi::DenseTensor>()) {
      auto &src_tensor = var->Get<phi::DenseTensor>();
      auto *dst_tensor = const_cast<phi::DenseTensor *>(
          dynamic_cast<const phi::DenseTensor *>(tensors[i]->impl().get()));
      VLOG(2) << "share " << name << " from scope";
      *dst_tensor = src_tensor;
    } else if (var->IsType<phi::SelectedRows>()) {
      auto &src_tensor = var->Get<phi::SelectedRows>();
      auto *dst_tensor = const_cast<phi::SelectedRows *>(
          dynamic_cast<const phi::SelectedRows *>(tensors[i]->impl().get()));
      *dst_tensor = src_tensor;
    }
  }
}

219 220 221 222 223 224 225
static void ShareTensorsFromScopeWithPartialBlock(
    const std::vector<Tensor *> &tensors,
    const paddle::framework::BlockDesc &forward_global_block,
    const paddle::framework::BlockDesc &backward_global_block,
    paddle::framework::Scope *scope) {
  for (size_t i = 0; i < tensors.size(); ++i) {
    auto &name = tensors[i]->name();
226 227
    if (name == paddle::framework::kEmptyVarName ||
        name == paddle::framework::kFakeVarName ||
228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 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
        (!forward_global_block.HasVar(name) &&
         !backward_global_block.HasVar(name))) {
      VLOG(2) << "find tensor name is " << name << ", skip it!";
      continue;
    }
    auto *var = scope->FindVar(name);
    PADDLE_ENFORCE_NOT_NULL(
        var,
        paddle::platform::errors::NotFound("The output tensor %s is not in "
                                           "RunProgram(Grad)Op'"
                                           "s internal scope.",
                                           name));
    CheckOutputVarStatus(*var, *tensors[i]);
    // share tensor
    if (var->IsType<phi::DenseTensor>()) {
      auto &src_tensor = var->Get<phi::DenseTensor>();
      auto *dst_tensor = const_cast<phi::DenseTensor *>(
          dynamic_cast<const phi::DenseTensor *>(tensors[i]->impl().get()));
      VLOG(2) << "share " << name << " from scope";
      *dst_tensor = src_tensor;
    } else if (var->IsType<phi::SelectedRows>()) {
      auto &src_tensor = var->Get<phi::SelectedRows>();
      auto *dst_tensor = const_cast<phi::SelectedRows *>(
          dynamic_cast<const phi::SelectedRows *>(tensors[i]->impl().get()));
      *dst_tensor = src_tensor;
    }
  }
}

static void BuildScopeByBlock(
    const paddle::framework::InterpreterCore &interpreter_core,
    const paddle::framework::BlockDesc &block,
    paddle::framework::Scope *scope) {
  for (auto &var_desc : block.AllVars()) {
    auto var_name = var_desc->Name();
    if (var_name == paddle::framework::kEmptyVarName) {
      continue;
    }
    if (!scope->FindLocalVar(var_name)) {
      auto *ptr = scope->Var(var_name);
      InitializeVariable(ptr, var_desc->GetType());
      VLOG(2) << "Initialize Block Variable " << var_name;
    }
  }
  auto &data_transfer_added_vars =
      interpreter_core.GetVariableScope()->DataTransferAddedVars();
  for (size_t i = 0; i < data_transfer_added_vars.size(); i++) {
    auto *ptr = scope->Var(data_transfer_added_vars[i].first);
    InitializeVariable(ptr,
                       static_cast<paddle::framework::proto::VarType::Type>(
                           data_transfer_added_vars[i].second));
    VLOG(2) << "Initialize Transfer Added Variable "
            << data_transfer_added_vars[i].first;
  }
}

284 285 286 287 288 289
static void GcScope(paddle::framework::Scope *scope) {
  std::deque<std::shared_ptr<paddle::memory::Allocation>> *garbages =
      new std::deque<std::shared_ptr<paddle::memory::Allocation>>();

  for (auto &var : scope->LocalVars()) {
    if (var != nullptr) {
290 291 292
      if (var->IsType<phi::DenseTensor>()) {
        garbages->emplace_back(
            var->GetMutable<phi::DenseTensor>()->MoveMemoryHolder());
293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311
      }
      if (var->IsType<phi::SelectedRows>()) {
        garbages->emplace_back(var->GetMutable<phi::SelectedRows>()
                                   ->mutable_value()
                                   ->MoveMemoryHolder());
      }
      if (var->IsType<paddle::framework::LoDTensorArray>()) {
        auto *lod_tensor_arr =
            var->GetMutable<paddle::framework::LoDTensorArray>();
        for (auto &t : *lod_tensor_arr) {
          garbages->emplace_back(t.MoveMemoryHolder());
        }
        lod_tensor_arr->clear();
      }
    }
  }
  delete garbages;  // free mem
}

0
0x45f 已提交
312 313 314
}  // namespace details

inline void RunProgramAPI(
315 316 317
    const std::vector<paddle::Tensor> &x,
    const std::vector<paddle::Tensor> &params,
    std::vector<paddle::Tensor *> &out,                   // NOLINT
0
0x45f 已提交
318
    std::vector<paddle::framework::Scope *> &step_scope,  // NOLINT
319
    std::vector<paddle::Tensor *> &dout,                  // NOLINT
320
    bool require_any_grad,
0
0x45f 已提交
321 322
    const paddle::framework::AttributeMap &attrs) {
  VLOG(2) << "RunProgramOpKernel Compute";
0
0x45f 已提交
323 324 325 326 327
  // In the original run_program OP, the default value of the is_test
  // attribute is false, we should check if there is is_test parameter
  // in attrs
  auto is_test = false;
  if (attrs.count("is_test")) {
R
Ruibiao Chen 已提交
328
    is_test = PADDLE_GET_CONST(bool, attrs.at("is_test"));
0
0x45f 已提交
329
  }
330
  int64_t program_id = PADDLE_GET_CONST(int64_t, attrs.at("program_id"));
331
  auto place = egr::Controller::Instance().GetExpectedPlace();
0
0x45f 已提交
332 333 334 335 336

  // NOTE(chenweihang): In order not to add new variable type, use vector
  // here. Originally, here can use scope directly.
  auto *out_scope_vec = &step_scope;
  PADDLE_ENFORCE_EQ(
337 338
      out_scope_vec->size(),
      1,
0
0x45f 已提交
339 340 341
      paddle::platform::errors::InvalidArgument(
          "The OutScope of RunProgramGradOp should only hold one scope."));

342
  VLOG(2) << "RunProgramOp use interpretercore to execute program.";
0
0x45f 已提交
343

344
  paddle::framework::Scope *global_inner_scope = out_scope_vec->front();
0
0x45f 已提交
345

L
Leo Chen 已提交
346 347
  VLOG(4) << "global_inner_scope:" << global_inner_scope;

348 349
  auto input_names =
      PADDLE_GET_CONST(std::vector<std::string>, attrs.at("x_names"));
350
  auto output_names = details::GetTensorsName(out);
351
  auto param_names = details::GetTensorsName(params);
352
  auto dout_names = details::GetTensorsName(dout);
353

354 355 356 357 358 359 360
  if (VLOG_IS_ON(6)) {
    std::stringstream s;
    s << "input_names: ";
    for (auto name : input_names) {
      s << name << " ";
    }
    s << std::endl;
361 362 363 364 365
    s << "param_names: ";
    for (auto name : param_names) {
      s << name << " ";
    }
    s << std::endl;
366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389
    s << "output_names: ";
    for (auto name : output_names) {
      s << name << " ";
    }
    s << std::endl;
    s << "dout_names: ";
    for (auto name : dout_names) {
      s << name << " ";
    }
    s << std::endl;
    VLOG(6) << s.str();
  }

  auto *forward_global_block = PADDLE_GET_CONST(
      paddle::framework::BlockDesc *, attrs.at("forward_global_block"));
  auto *backward_global_block = PADDLE_GET_CONST(
      paddle::framework::BlockDesc *, attrs.at("backward_global_block"));
  auto *forward_program = forward_global_block->Program();
  auto *backward_program = backward_global_block->Program();

  auto &interpretercore_info_cache =
      paddle::framework::InterpreterCoreInfoCache::Instance();
  std::shared_ptr<paddle::framework::InterpreterCore> interpreter_core =
      nullptr;
390 391
  if (!interpretercore_info_cache.Has(
          program_id, global_inner_scope, /*is_grad=*/false)) {
392 393 394 395 396 397 398 399
    paddle::platform::RecordEvent record_event(
        "create_new_interpretercore",
        paddle::platform::TracerEventType::UserDefined,
        1);
    VLOG(2) << "No interpretercore cahce, so create a new interpretercore "
               "for program: "
            << program_id;
    // Step 1. share input_vars & parameters into scope
400
    details::ShareTensorsIntoScopeWithName(x, input_names, global_inner_scope);
401 402
    details::ShareTensorsIntoScope(params, global_inner_scope);
    // Step 2. create new interpretercore
403 404 405 406

    if (FLAGS_enable_new_ir_in_executor) {
      // build new ir program
      auto ir_program = paddle::framework::ConstructFowardIrProgram(
407
          forward_global_block, backward_global_block, output_names, x, params);
408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423
      interpreter_core =
          paddle::framework::CreateNewIRInterpreterCoreInfoToCache(
              std::move(ir_program),
              place,
              /*is_grad=*/false,
              program_id,
              global_inner_scope);
    } else {
      interpreter_core =
          paddle::framework::CreateProgramInterpreterCoreInfoToCache(
              *forward_program,
              place,
              /*is_grad=*/false,
              program_id,
              global_inner_scope);
    }
424 425 426 427
    // Step 3. get all eager gc vars
    std::set<std::string> skip_eager_delete_vars =
        paddle::framework::details::ParseSafeEagerDeletionSkipVarsSet(
            *backward_program);
428

429 430 431 432 433 434 435 436 437
    // all out_vars are skip_eager_var
    skip_eager_delete_vars.insert(output_names.begin(), output_names.end());
    skip_eager_delete_vars.insert(dout_names.begin(), dout_names.end());
    // update interpretercore skip_gc_var
    interpreter_core->SetSkipGcVars(skip_eager_delete_vars);

    std::set<std::string> input_vars;
    input_vars.insert(input_names.begin(), input_names.end());
    interpreter_core->SetJitInputVars(input_vars);
438

439 440
    if (VLOG_IS_ON(6)) {
      std::stringstream s;
441 442
      s << "skip_eager_delete_vars: ";
      for (auto name : skip_eager_delete_vars) {
443 444 445 446 447
        s << name << " ";
      }
      VLOG(6) << s.str();
    }

448
    interpretercore_info_cache.UpdateSkipEagerDeleteVars(
449
        program_id, global_inner_scope, false, skip_eager_delete_vars);
450 451 452 453 454 455 456 457
    VLOG(2) << "Get skip GC vars size is: " << skip_eager_delete_vars.size();
  } else {
    paddle::platform::RecordEvent record_event(
        "get_interpretercore_cahce",
        paddle::platform::TracerEventType::UserDefined,
        1);
    VLOG(2) << "Get interpretercore cahce by program:" << program_id;
    // Step 1. get cache interpretercore
458 459
    auto &cached_value = interpretercore_info_cache.GetMutable(
        program_id, global_inner_scope, /*is_grad=*/false);
460 461
    interpreter_core = cached_value.core_;
    // Step 2. update scope for cache interpretercore
462
    details::ShareTensorsIntoScopeWithName(x, input_names, global_inner_scope);
463 464 465 466 467 468
    details::ShareTensorsIntoScope(params, global_inner_scope);
    if (interpreter_core->GetVariableScope()->GetMutableScope() !=
        global_inner_scope) {
      details::BuildScopeByBlock(
          *interpreter_core.get(), *forward_global_block, global_inner_scope);
      interpreter_core->reset_scope(global_inner_scope);
469
    }
470
  }
471

472 473 474 475 476 477 478 479
  // interpretercore run
  if (forward_global_block->OpSize() > 0) {
    paddle::platform::RecordEvent record_event(
        "interpreter_core_run",
        paddle::platform::TracerEventType::UserDefined,
        1);
    interpreter_core->Run({});
  }
480

481 482 483 484 485 486 487 488 489 490
  {
    paddle::platform::RecordEvent record_event(
        "fetch_and_gc", paddle::platform::TracerEventType::UserDefined, 1);
    // Get Output
    details::ShareTensorsFromScopeWithPartialBlock(
        out, *forward_global_block, *backward_global_block, global_inner_scope);
    details::ShareTensorsFromScopeWithPartialBlock(dout,
                                                   *forward_global_block,
                                                   *backward_global_block,
                                                   global_inner_scope);
491 492

    VLOG(3) << paddle::framework::GenScopeTreeDebugInfo(out_scope_vec->front());
493

494 495 496 497
    if (is_test || !require_any_grad) {
      VLOG(4) << "don't require any grad, set this scope can reused";
      VLOG(4) << "is_test: " << is_test
              << ", require_any_grad: " << require_any_grad;
C
co63oc 已提交
498
      global_inner_scope->SetCanReused(true);
499 500 501
      details::GcScope(global_inner_scope);
    } else {
      VLOG(4) << "not test, set this scope can not reused";
C
co63oc 已提交
502
      global_inner_scope->SetCanReused(false);
503
    }
504 505
  }

506
#ifdef PADDLE_WITH_DNNL
507
  if (FLAGS_use_mkldnn) paddle::platform::DontClearMKLDNNCache(place);
508
#endif
0
0x45f 已提交
509 510 511
}

inline void RunProgramGradAPI(
512
    const std::vector<paddle::Tensor> &out_grad,
0
0x45f 已提交
513 514
    const std::vector<paddle::framework::Scope *> &step_scope,  // NOLINT
    const paddle::framework::AttributeMap &attrs,
515 516
    std::vector<paddle::Tensor *> &x_grad,      // NOLINT
    std::vector<paddle::Tensor *> &params_grad  // NOLINT
517
) {
0
0x45f 已提交
518 519 520 521
  // if all output vars are set to stop_gradient, grad op no need to executed
  if (x_grad.empty() && params_grad.empty()) return;
  auto *out_scope_vec = &step_scope;
  PADDLE_ENFORCE_EQ(
522 523
      out_scope_vec->size(),
      1,
0
0x45f 已提交
524 525
      paddle::platform::errors::InvalidArgument(
          "The OutScope of RunProgramGradOp should only hold one scope."));
526 527 528
  paddle::framework::Scope *global_inner_scope = out_scope_vec->front();

  int64_t program_id = PADDLE_GET_CONST(int64_t, attrs.at("program_id"));
0
0x45f 已提交
529

530
  auto place = egr::Controller::Instance().GetExpectedPlace();
531 532
  VLOG(2) << "RunProgramGradOp use interpretercore to execute program.";

L
Leo Chen 已提交
533
  VLOG(4) << "global_inner_scope:" << global_inner_scope;
534 535 536 537 538 539 540 541 542 543 544 545

  auto *forward_global_block = PADDLE_GET_CONST(
      paddle::framework::BlockDesc *, attrs.at("forward_global_block"));
  auto *backward_global_block = PADDLE_GET_CONST(
      paddle::framework::BlockDesc *, attrs.at("backward_global_block"));
  auto *backward_program = backward_global_block->Program();

  auto out_grad_names = details::GetTensorsName(out_grad);
  auto &interpretercore_info_cache =
      paddle::framework::InterpreterCoreInfoCache::Instance();
  std::shared_ptr<paddle::framework::InterpreterCore> interpreter_core =
      nullptr;
546 547
  if (!interpretercore_info_cache.Has(
          program_id, global_inner_scope, /*is_grad=*/true)) {
548 549 550 551 552 553
    paddle::platform::RecordEvent record_event(
        "create_new_interpretercore",
        paddle::platform::TracerEventType::UserDefined,
        1);
    VLOG(2) << "No interpretercore cahce, so create a new interpretercore";
    details::ShareTensorsIntoScope(out_grad, global_inner_scope);
554 555

    if (FLAGS_enable_new_ir_in_executor) {
556 557 558 559 560 561
      auto res =
          paddle::framework::ConstructBackwardIrProgram(backward_global_block,
                                                        out_grad,
                                                        x_grad,
                                                        params_grad,
                                                        global_inner_scope);
562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578

      interpreter_core =
          paddle::framework::CreateNewIRInterpreterCoreInfoToCache(
              std::move(res),
              place,
              /*is_grad=*/true,
              program_id,
              global_inner_scope);
    } else {
      interpreter_core =
          paddle::framework::CreateProgramInterpreterCoreInfoToCache(
              *backward_program,
              place,
              /*is_grad=*/true,
              program_id,
              global_inner_scope);
    }
579 580 581 582

    // share threadpool
    // NOTE(zhiqiu): this only works interpreter_core is executed strictly
    // after the related fwd_interpreter_core.
583
    if (interpretercore_info_cache.Has(program_id, global_inner_scope, false)) {
584
      auto fwd_interpreter_core =
585 586
          interpretercore_info_cache
              .GetMutable(program_id, global_inner_scope, /*is_grad=*/false)
587 588 589 590
              .core_;
      interpreter_core->ShareWorkQueueFrom(fwd_interpreter_core);
      VLOG(4) << "Share workqueue from " << fwd_interpreter_core.get() << " to "
              << interpreter_core.get();
591
    }
592

593 594 595 596
    std::vector<std::string> x_grad_names;
    std::vector<std::string> param_grad_names;
    if (!x_grad.empty()) {
      x_grad_names = details::GetTensorsName(x_grad);
597
    }
598 599
    if (!params_grad.empty()) {
      param_grad_names = details::GetTensorsName(params_grad);
600
    }
601 602 603 604 605 606 607 608 609
    // get all eager gc vars
    std::set<std::string> skip_eager_delete_vars;
    // all out_vars are skip_eager_var
    skip_eager_delete_vars.insert(x_grad_names.begin(), x_grad_names.end());
    // initialize skip gc vars by forward_program and backward_program
    paddle::framework::details::AppendSkipDeletionVars(param_grad_names,
                                                       &skip_eager_delete_vars);
    interpreter_core->SetSkipGcVars(skip_eager_delete_vars);
    interpretercore_info_cache.UpdateSkipEagerDeleteVars(
610 611 612 613
        program_id,
        global_inner_scope,
        /*is_grad=*/true,
        skip_eager_delete_vars);
614
    VLOG(2) << "Get skip GC vars size is: " << skip_eager_delete_vars.size();
615
  } else {
616 617 618 619 620
    paddle::platform::RecordEvent record_event(
        "get_interpretercore_cahce",
        paddle::platform::TracerEventType::UserDefined,
        1);
    VLOG(2) << "Get interpretercore cahce by program:" << program_id;
621 622
    auto &cached_value = interpretercore_info_cache.GetMutable(
        program_id, global_inner_scope, /*is_grad=*/true);
623 624 625 626 627 628 629 630 631
    interpreter_core = cached_value.core_;

    // update scope
    details::ShareTensorsIntoScope(out_grad, global_inner_scope);
    if (interpreter_core->GetVariableScope()->GetMutableScope() !=
        global_inner_scope) {
      details::BuildScopeByBlock(
          *interpreter_core.get(), *backward_global_block, global_inner_scope);
      interpreter_core->reset_scope(global_inner_scope);
0
0x45f 已提交
632
    }
633
  }
0
0x45f 已提交
634

635 636 637 638 639 640 641 642 643
  if (backward_global_block->OpSize() > 0) {
    paddle::platform::RecordEvent record_event(
        "interpreter_core_run",
        paddle::platform::TracerEventType::UserDefined,
        1);
    // Debug info: scope info when run end
    VLOG(3) << paddle::framework::GenScopeTreeDebugInfo(out_scope_vec->front());
    interpreter_core->Run({});
  }
0
0x45f 已提交
644

645 646 647 648 649 650 651 652 653 654 655 656 657
  {
    paddle::platform::RecordEvent record_event(
        "fetch_and_gc", paddle::platform::TracerEventType::UserDefined, 1);
    // Step 4. get outputs
    details::ShareTensorsFromScopeWithPartialBlock(x_grad,
                                                   *forward_global_block,
                                                   *backward_global_block,
                                                   global_inner_scope);
    details::ShareTensorsFromScopeWithPartialBlock(params_grad,
                                                   *forward_global_block,
                                                   *backward_global_block,
                                                   global_inner_scope);
    VLOG(4) << "after backward gc all vars";
C
co63oc 已提交
658
    global_inner_scope->SetCanReused(true);
659
    details::GcScope(global_inner_scope);
0
0x45f 已提交
660 661 662 663 664 665 666 667
  }
}

class GradNodeRunProgram : public egr::GradNodeBase {
 public:
  GradNodeRunProgram(size_t bwd_in_slot_num, size_t bwd_out_slot_num)
      : egr::GradNodeBase(bwd_in_slot_num, bwd_out_slot_num) {}

668
  ~GradNodeRunProgram() {
L
Leo Chen 已提交
669 670 671 672 673 674
    if (!executed_) {
      auto *out_scope_vec = &step_scope_;
      VLOG(4) << "~GradNodeRunProgram";
      // Normally out_scope_vec.size() == 1. for safty, we add for-loop here.
      for (size_t i = 0; i < out_scope_vec->size(); ++i) {
        paddle::framework::Scope *global_inner_scope = out_scope_vec->at(i);
C
co63oc 已提交
675
        global_inner_scope->SetCanReused(true);
L
Leo Chen 已提交
676
        details::GcScope(global_inner_scope);
C
co63oc 已提交
677
        VLOG(4) << "global_inner_scope SetCanReused";
L
Leo Chen 已提交
678
      }
679 680
    }
  }
0
0x45f 已提交
681
  // Functor: perform backward computations
682
  virtual paddle::small_vector<std::vector<paddle::Tensor>,
683
                               egr::kSlotSmallVectorSize>
684
  operator()(paddle::small_vector<std::vector<paddle::Tensor>,
685
                                  egr::kSlotSmallVectorSize> &grads,  // NOLINT
686 687
             bool create_graph UNUSED,
             bool is_new_grad UNUSED) override {
0
0x45f 已提交
688
    VLOG(3) << "Running Eager Backward Node: GradNodeRunProgram";
689
    paddle::small_vector<std::vector<paddle::Tensor>, egr::kSlotSmallVectorSize>
690
        hooked_grads = GradNodeRunProgram::ApplyGradientHooks(grads);
691 692
    PADDLE_ENFORCE_EQ(hooked_grads.size(),
                      1,
693 694 695
                      paddle::platform::errors::InvalidArgument(
                          "The hooked_grads.size() of RunProgramGradOp should "
                          "be equal to 1."));
0
0x45f 已提交
696

697 698 699 700
    std::vector<paddle::Tensor> x_grad;
    std::vector<paddle::Tensor> params_grad;
    std::vector<paddle::Tensor *> x_grad_ptr;
    std::vector<paddle::Tensor *> params_grad_ptr;
701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718
    {
      paddle::platform::RecordEvent record_event(
          "construct_grad_tensor",
          paddle::platform::TracerEventType::UserDefined,
          1);

      egr::EagerUtils::FillZeroForEmptyOptionalGradInput(&hooked_grads[0],
                                                         this->InputMeta()[0]);
      VLOG(3) << "hooked_grads[0].size() : " << hooked_grads[0].size();
      ConstructXGradTensors(x_, &x_grad);
      ConstructParamGradTensors(params_, &params_grad);
      for (auto &i : x_grad) {
        x_grad_ptr.emplace_back(&i);
      }
      for (auto &i : params_grad) {
        if (i.defined()) {
          params_grad_ptr.emplace_back(&i);
        }
0
0x45f 已提交
719
      }
0
0x45f 已提交
720 721
    }

722 723
    auto out_grad_names =
        PADDLE_GET_CONST(std::vector<std::string>, attrs_.at("out_grad_names"));
724
    PADDLE_ENFORCE_EQ(hooked_grads[0].size(),
725
                      out_grad_names.size(),
726 727
                      paddle::platform::errors::InvalidArgument(
                          "The hooked_grads[0].size() and "
728 729 730
                          "out_grad_names.size() should be equal."));
    for (size_t i = 0; i < out_grad_names.size(); ++i) {
      hooked_grads[0][i].set_name(out_grad_names[i]);
0
0x45f 已提交
731
    }
732 733
    RunProgramGradAPI(
        hooked_grads[0], step_scope_, attrs_, x_grad_ptr, params_grad_ptr);
0
0x45f 已提交
734
    VLOG(3) << "End Eager Backward Node: GradNodeRunProgram";
L
Leo Chen 已提交
735 736

    executed_ = true;
0
0x45f 已提交
737 738 739
    return {x_grad, params_grad};
  }

740 741 742 743 744
  void ClearTensorWrappers() override {
    x_.clear();
    params_.clear();
    SetIsTensorWrappersCleared(true);
  }
745

0
0x45f 已提交
746 747 748 749 750
  // SetAttrMap
  void SetAttrMap(const paddle::framework::AttributeMap &attrs) {
    attrs_ = attrs;
  }

751
  void SetFwdX(const std::vector<paddle::Tensor> &tensors) { x_ = tensors; }
0
0x45f 已提交
752

753
  void SetFwdParams(const std::vector<paddle::Tensor> &tensors) {
0
0x45f 已提交
754 755 756 757 758 759 760 761
    params_ = tensors;
  }

  void SetStepScope(const std::vector<paddle::framework::Scope *> &scopes) {
    step_scope_ = scopes;
  }

 protected:
762 763
  void ConstructXGradTensors(const std::vector<paddle::Tensor> &x,
                             std::vector<paddle::Tensor> *x_grad) {
764 765 766 767 768 769 770 771 772 773 774
    auto x_grad_names =
        PADDLE_GET_CONST(std::vector<std::string>, attrs_.at("x_grad_names"));
    PADDLE_ENFORCE_EQ(
        x.size(),
        x_grad_names.size(),
        paddle::platform::errors::InvalidArgument(
            "The x.size() and x_grad_names.size() should be equal. "
            "But received x.size() = %d, x_grad_names.size() = %d",
            x.size(),
            x_grad_names.size()));

0
0x45f 已提交
775 776
    // TODO(dev): Need an elegant way to determine inforamtion of grad_tensor,
    // such as: name, tensor type(DenseTensor or SelectedRows).
777 778
    for (size_t i = 0; i < x.size(); i++) {
      if (x[i].is_dense_tensor()) {
779
        x_grad->emplace_back(std::make_shared<phi::DenseTensor>());
780
      } else if (x[i].is_selected_rows()) {
781
        x_grad->emplace_back(std::make_shared<phi::SelectedRows>());
782
      }
783
      x_grad->back().set_name(x_grad_names[i]);
0
0x45f 已提交
784 785 786
    }
  }

787 788
  void ConstructParamGradTensors(const std::vector<paddle::Tensor> &params,
                                 std::vector<paddle::Tensor> *param_grads) {
789 790 791 792 793 794 795 796 797 798 799
    auto param_grad_names = PADDLE_GET_CONST(std::vector<std::string>,
                                             attrs_.at("param_grad_names"));
    PADDLE_ENFORCE_EQ(params.size(),
                      param_grad_names.size(),
                      paddle::platform::errors::InvalidArgument(
                          "The param.size() and "
                          "param_grad_names.size() should be equal."));

    for (size_t i = 0; i < params.size(); ++i) {
      auto &p = params[i];
      auto &p_grad = egr::EagerUtils::unsafe_autograd_meta(p)->Grad();
800 801 802
      // In eager mode, the number of param_grad should be the same as
      // param, so here an empty Tensor is added for the param with
      // stop_gradient=True
803 804 805 806 807 808
      if (!p_grad.defined()) {
        param_grads->emplace_back();
      } else if (p_grad.is_dense_tensor()) {
        param_grads->emplace_back(std::make_shared<phi::DenseTensor>());
      } else if (p_grad.is_selected_rows()) {
        param_grads->emplace_back(std::make_shared<phi::SelectedRows>());
809
      }
810
      param_grads->back().set_name(param_grad_names[i]);
0
0x45f 已提交
811 812 813
    }
  }

814 815 816 817 818 819
  std::shared_ptr<GradNodeBase> Copy() const override {
    auto copied_node =
        std::shared_ptr<GradNodeRunProgram>(new GradNodeRunProgram(*this));
    return copied_node;
  }

0
0x45f 已提交
820 821
 private:
  // TensorWrappers
822 823
  std::vector<paddle::Tensor> x_;
  std::vector<paddle::Tensor> params_;
0
0x45f 已提交
824 825 826 827
  std::vector<paddle::framework::Scope *> step_scope_;

  // Attribute Map
  paddle::framework::AttributeMap attrs_;
L
Leo Chen 已提交
828 829

  bool executed_{false};
0
0x45f 已提交
830
};