run_program_op.h 23.5 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
/* Copyright (c) 2020 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 <algorithm>
#include <iterator>
19
#include <memory>
20
#include <string>
21
#include <unordered_map>
22
#include <unordered_set>
23 24 25
#include <utility>
#include <vector>

26
#include "paddle/fluid/framework/executor_cache.h"
27
#include "paddle/fluid/framework/op_desc.h"
28 29 30 31 32 33
#include "paddle/fluid/framework/op_registry.h"
#include "paddle/fluid/framework/operator.h"
#include "paddle/fluid/framework/program_desc.h"
#include "paddle/fluid/framework/scope.h"
#include "paddle/fluid/framework/var_type_traits.h"
#include "paddle/fluid/framework/variable.h"
34 35 36
#ifdef PADDLE_WITH_MKLDNN
#include "paddle/fluid/platform/mkldnn_helper.h"
#endif
37 38 39
#ifdef PADDLE_WITH_CUDA
#include "paddle/fluid/operators/cuda_graph_with_in_out.h"
#endif
40
#include "paddle/phi/core/flags.h"
41

42
PHI_DECLARE_bool(use_mkldnn);
43 44 45 46 47 48

namespace paddle {
namespace operators {

using StepScopeVar = std::vector<framework::Scope *>;
using BlockDesc = framework::BlockDesc;
49
using ProgramDesc = framework::ProgramDesc;
50 51

using Variable = framework::Variable;
52
using SelectedRows = phi::SelectedRows;
53 54 55

namespace details {

56
// all input vars should be phi::DenseTensor & is initialized
57 58
static void CheckInputVarStatus(const Variable &var,
                                const std::string &var_name) {
59 60 61 62 63 64 65 66 67
  PADDLE_ENFORCE_EQ(var.IsType<phi::DenseTensor>(),
                    true,
                    platform::errors::InvalidArgument(
                        "The input variable %s of "
                        "RunProgram(Grad)Op holds "
                        "wrong type. Expect type is phi::DenseTensor, but "
                        "receive type is %s.",
                        var_name,
                        platform::demangle(framework::ToTypeName(var.Type()))));
68
  PADDLE_ENFORCE_EQ(
69
      var.Get<phi::DenseTensor>().IsInitialized(),
70
      true,
71
      platform::errors::InvalidArgument("The tensor in input variable %s of "
72
                                        "RunProgram(Grad)Op "
73 74 75 76 77 78 79
                                        "is not initialized.",
                                        var_name));
}

static void CheckOutputVarStatus(const Variable &src_var,
                                 const Variable &dst_var,
                                 const std::string &var_name) {
80
  if (dst_var.IsType<phi::DenseTensor>()) {
81
    PADDLE_ENFORCE_EQ(
82
        src_var.IsType<phi::DenseTensor>(),
83
        true,
84 85
        platform::errors::InvalidArgument(
            "The output variable %s get from "
86
            "RunProgram(Grad)Op's internal scope holds "
87 88
            "wrong type. Expect type is phi::DenseTensor, but receive type is "
            "%s.",
89 90
            var_name,
            platform::demangle(framework::ToTypeName(src_var.Type()))));
91
    PADDLE_ENFORCE_EQ(src_var.Get<phi::DenseTensor>().IsInitialized(),
92
                      true,
93 94
                      platform::errors::InvalidArgument(
                          "The tensor in output variable %s get from "
95
                          "RunProgram(Grad)Op's internal "
96 97
                          "scope is not initialized.",
                          var_name));
98
  } else if (dst_var.IsType<phi::SelectedRows>()) {
99
    PADDLE_ENFORCE_EQ(
100 101
        src_var.IsType<phi::SelectedRows>(),
        true,
102 103
        platform::errors::InvalidArgument(
            "The output variable %s get from "
104
            "RunProgram(Grad)Op's internal scope holds "
105 106 107
            "wrong type. Expect type is SelectedRows, but receive type is %s.",
            var_name,
            platform::demangle(framework::ToTypeName(src_var.Type()))));
108
    PADDLE_ENFORCE_EQ(src_var.Get<phi::SelectedRows>().value().IsInitialized(),
109 110 111 112 113 114
                      true,
                      platform::errors::InvalidArgument(
                          "The tensor in output variable %s get from "
                          "RunProgram(Grad)Op's "
                          "internal scope is not initialized.",
                          var_name));
115 116 117

  } else {
    PADDLE_THROW(platform::errors::InvalidArgument(
118
        "The RunProgram(Grad)Op only support output "
119
        "variable of type phi::DenseTensor or SelectedRows, "
120
        "but received variable %s's type is %s",
121 122
        var_name,
        platform::demangle(framework::ToTypeName(dst_var.Type()))));
123 124 125 126
  }
}

static void VariableShare(const Variable &src_var, Variable *dst_var) {
127 128 129 130 131 132
  // The previous check ensures that the variable type can only be
  // phi::DenseTensor or SelectedRows.
  if (src_var.IsType<phi::DenseTensor>()) {
    auto *lod_tensor = dst_var->GetMutable<phi::DenseTensor>();
    lod_tensor->ShareDataWith(src_var.Get<phi::DenseTensor>());
    lod_tensor->set_lod(src_var.Get<phi::DenseTensor>().lod());
133 134
  } else if (src_var.IsType<phi::SelectedRows>()) {
    auto *selected_rows = dst_var->GetMutable<phi::SelectedRows>();
135
    selected_rows->mutable_value()->ShareDataWith(
136 137 138
        src_var.Get<phi::SelectedRows>().value());
    selected_rows->set_rows(src_var.Get<phi::SelectedRows>().rows());
    selected_rows->set_height(src_var.Get<phi::SelectedRows>().height());
139 140 141
  }
}

142
static void ShareVarsIntoScope(const std::vector<Variable *> &vars,
143 144 145
                               const std::vector<std::string> &var_names,
                               framework::Scope *scope) {
  for (size_t i = 0; i < vars.size(); ++i) {
0
0x45f 已提交
146
    if (var_names[i] == framework::kFakeVarName) {
147 148
      continue;
    }
149 150 151
    auto *var = scope->Var(var_names[i]);
    CheckInputVarStatus(*vars[i], var_names[i]);
    VariableShare(*vars[i], var);
152 153 154
  }
}

155 156
static void ShareVarsFromScope(const std::vector<Variable *> &vars,
                               const std::vector<std::string> &var_names,
157
                               const BlockDesc &global_block,
158
                               framework::Scope *scope) {
159
  for (size_t i = 0; i < vars.size(); ++i) {
160 161 162 163
    // 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 findthem in scope. So we skip sharing these vars or
    // var@GRAD if they don't appear in global block.
164
    if (var_names[i] == framework::kEmptyVarName ||
0
0x45f 已提交
165 166
        var_names[i] == framework::kFakeVarName ||
        !global_block.HasVar(var_names[i])) {
167
      VLOG(2) << "find variable name is " << var_names[i] << ", skip it!";
168 169 170 171
      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!
172
    auto *var = scope->FindVar(var_names[i]);
173
    PADDLE_ENFORCE_NOT_NULL(
174 175 176 177 178
        var,
        platform::errors::NotFound("The output variable %s is not in "
                                   "RunProgram(Grad)Op'"
                                   "s internal scope.",
                                   var_names[i]));
179
    CheckOutputVarStatus(*var, *vars[i], var_names[i]);
180
    VariableShare(*var, vars[i]);
181 182 183
  }
}

184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199
#ifdef PADDLE_WITH_CUDA
static cudaStreamCaptureMode StringToCUDAGraphCaptureMode(
    const std::string &mode) {
  if (mode == "global") {
    return cudaStreamCaptureModeGlobal;
  } else if (mode == "thread_local") {
    return cudaStreamCaptureModeThreadLocal;
  } else if (mode == "relaxed") {
    return cudaStreamCaptureModeRelaxed;
  } else {
    PADDLE_THROW(phi::errors::InvalidArgument(
        "Unsupported CUDA Graph capture mode %s", mode));
  }
}
#endif

200 201
}  // namespace details

202
template <typename T, typename DeviceContext>
203 204 205
class RunProgramOpKernel : public framework::OpKernel<T> {
 public:
  void Compute(const framework::ExecutionContext &ctx) const override {
206 207 208 209 210 211 212 213 214 215
    const auto &capture_mode = ctx.Attr<std::string>("cuda_graph_capture_mode");
    auto is_test = ctx.Attr<bool>("is_test");
    if (capture_mode.empty()) {
      ComputeImpl(ctx, is_test, false);
      return;
    }

#ifdef PADDLE_WITH_CUDA
    auto mode = details::StringToCUDAGraphCaptureMode(capture_mode);
    PADDLE_ENFORCE_EQ(
216 217
        platform::is_gpu_place(ctx.GetPlace()),
        true,
218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238
        phi::errors::InvalidArgument("The cuda_graph_capture_mode is only "
                                     "valid when using NVIDIA GPU."));
    auto *graph_var = ctx.OutputVar("CUDAGraph");
    PADDLE_ENFORCE_NOT_NULL(
        graph_var,
        phi::errors::InvalidArgument("Output(CUDAGraph) must exist when "
                                     "cuda_graph_capture_mode is valid."));
    using GraphVecType = std::vector<std::unique_ptr<CUDAGraphWithInOuts>>;
    auto &inner_graphs = *(graph_var->GetMutable<GraphVecType>());
    inner_graphs.resize(std::max<size_t>(3, inner_graphs.size()));
    size_t graph_idx = is_test ? 0 : 1;
    if (inner_graphs[graph_idx].get() == nullptr) {
      int64_t pool_id;
      if (inner_graphs[1 - graph_idx].get() != nullptr) {
        pool_id = inner_graphs[1 - graph_idx]->PoolID();
      } else {
        pool_id = ctx.Attr<int64_t>("cuda_graph_pool_id");
      }

      framework::PEAndGraphPair pe_and_graph;
      auto callable = [this, is_test, &pe_and_graph](
239
                          const framework::ExecutionContext &exe_ctx) {
240 241 242 243 244 245 246
        pe_and_graph = ComputeImpl(exe_ctx, is_test, true);
      };
      inner_graphs[graph_idx] = CaptureCUDAGraph(
          callable, ctx, {"X"}, {"Out", "DOut"}, mode, pool_id);
      VLOG(10) << "Capture Forward CUDA Graph";
    } else {
      VLOG(10) << "Run Forward CUDA Graph directly";
247 248
      ExecuteCUDAGraph(
          ctx, {"X"}, {"Out", "DOut"}, inner_graphs[graph_idx].get());
249 250 251 252 253 254 255 256 257 258 259 260
    }
#else
    PADDLE_THROW(
        phi::errors::InvalidArgument("The cuda_graph_capture_mode is only "
                                     "valid when using NVIDIA GPU."));
#endif
  }

 private:
  framework::PEAndGraphPair ComputeImpl(const framework::ExecutionContext &ctx,
                                        bool is_test,
                                        bool use_cuda_graph) const {
261
    VLOG(2) << "RunProgramOpKernel Compute";
262
    framework::PEAndGraphPair pe_and_graph;
263 264 265 266
    // Step 1. prepare inputs, outputs, attrs
    auto &input_vars = ctx.MultiInputVar("X");
    auto &param_vars = ctx.MultiInputVar("Params");
    auto output_vars = ctx.MultiOutputVar("Out");
267
    auto dout_vars = ctx.MultiOutputVar("DOut");
268 269 270

    auto input_var_names = ctx.InputNames("X");
    auto output_var_names = ctx.OutputNames("Out");
271 272 273 274 275 276
    std::vector<std::string> dout_var_names;
    if (!dout_vars.empty()) {
      // DOut is a dispensable out, only get the names when it exists.
      // Otherwise, it will throw a NotFound error.
      dout_var_names = ctx.OutputNames("DOut");
    }
277

278 279 280 281 282 283
    // current program may not hold parameters
    std::vector<std::string> param_names;
    if (!param_vars.empty()) {
      param_names = ctx.InputNames("Params");
    }

284 285
    auto start_op_index = ctx.Attr<int64_t>("start_op_index");
    auto end_op_index = ctx.Attr<int64_t>("end_op_index");
286
    auto program_id = ctx.Attr<int64_t>("program_id");
287 288 289 290

    // NOTE(chenweihang): In order not to add new variable type, use vector
    // here. Originally, here can use scope directly.
    auto *out_scope_vec = ctx.Output<StepScopeVar>("OutScope");
291 292
    std::unique_ptr<framework::Scope> inner_scope{nullptr};
    if (out_scope_vec->size() == 0) {
293 294
      // For cuda graph under static graph mode usage.
      // For static graph mode, we cannot set value of a tensor before any run,
295 296 297
      // the OutScope variable passed to the op actually contains nothing.
      // Just create a tmp scope to run the program.
      PADDLE_ENFORCE_EQ(
298 299
          use_cuda_graph,
          true,
300 301 302 303 304
          platform::errors::InvalidArgument(
              "If not provide OutScope then must run under cuda graph mode."));
      inner_scope = std::make_unique<framework::Scope>();
    } else {
      PADDLE_ENFORCE_EQ(
305 306
          out_scope_vec->size(),
          1,
307 308 309
          platform::errors::InvalidArgument(
              "The OutScope of RunProgramGradOp should only hold one scope."));
    }
310 311 312

    // Step 2. prepare executor and init persistable variables

313 314 315 316 317
    // NOTE(Aurelius84): While training some models, forward can be called many
    // times and then apply backpropagation all at once, such as Reinforcement
    // Learning. Tensor data in multi-step training should be saved into single
    // scope separately. Otherwise, the gradients can be miscalculated because
    // always using the Tensor data of the last step in forward.
318 319
    framework::Scope *global_inner_scope =
        out_scope_vec->size() == 0 ? inner_scope.get() : out_scope_vec->front();
320
    VLOG(2) << "The number of sub scopes before forward: "
321
            << global_inner_scope->kids().size();
322
    framework::Scope &scope = global_inner_scope->NewScope();
323

324 325 326 327
    // share input_vars & parameters into scope
    details::ShareVarsIntoScope(input_vars, input_var_names, &scope);
    details::ShareVarsIntoScope(param_vars, param_names, &scope);

328 329
    auto *global_block = ctx.Attr<BlockDesc *>("global_block");

330
    if (end_op_index > start_op_index) {
331
      auto *program = global_block->Program();
332 333 334 335 336 337
      bool is_new_created;
      if (use_cuda_graph) {
        pe_and_graph = framework::CreateFixOrderExecutorInfo(
            *program, ctx.GetPlace(), start_op_index, end_op_index, &scope);
        is_new_created = true;
      } else {
338 339 340 341 342 343 344
        auto cache_info = framework::GetExecutorInfoFromCache(*program,
                                                              ctx.GetPlace(),
                                                              start_op_index,
                                                              end_op_index,
                                                              /*is_grad=*/false,
                                                              program_id,
                                                              &scope);
345 346 347 348 349 350
        pe_and_graph.first = cache_info.first;
        is_new_created = cache_info.second;
      }

      auto &parallel_executor = pe_and_graph.first;

351
      // all out_vars are skip_eager_var
352
      std::vector<std::string> tmp_vars;
353
      auto &skip_eager_delete_vars =
354 355 356 357 358
          use_cuda_graph
              ? tmp_vars
              : framework::ExecutorInfoCache::Instance().SkipEagerDeleteVars(
                    program_id, false);
      if (is_new_created) {
359
        parallel_executor->SkipMemoryReuse(/*scope_idx=*/0, input_var_names);
360 361 362 363 364 365 366 367
        skip_eager_delete_vars.insert(skip_eager_delete_vars.end(),
                                      output_var_names.begin(),
                                      output_var_names.end());
        skip_eager_delete_vars.insert(skip_eager_delete_vars.end(),
                                      dout_var_names.begin(),
                                      dout_var_names.end());
        framework::details::ParseSafeEagerDeletionSkipVars(
            *program, end_op_index, output_var_names, &skip_eager_delete_vars);
368 369 370 371 372
      }

      // Step 3. run ops
      parallel_executor->RunWithoutFetch(skip_eager_delete_vars);
    }
373
    // Step 4. Get Output
374 375 376 377
    details::ShareVarsFromScope(
        output_vars, output_var_names, *global_block, &scope);
    details::ShareVarsFromScope(
        dout_vars, dout_var_names, *global_block, &scope);
378 379

    // Debug info: scope info when run end
380 381 382 383 384 385 386
    framework::Scope *target_scope{nullptr};
    if (out_scope_vec->size() == 0) {
      target_scope = inner_scope.get();
    } else {
      target_scope = out_scope_vec->front();
    }
    VLOG(3) << framework::GenScopeTreeDebugInfo(target_scope);
387 388
    // Step 5. Drop all children scopes while testing.
    if (is_test) {
389
      target_scope->DropKids();
390 391
    }
    VLOG(2) << "The number of sub scopes after forward: "
392
            << target_scope->kids().size();
393
#ifdef PADDLE_WITH_MKLDNN
394
    if (FLAGS_use_mkldnn) platform::DontClearMKLDNNCache(ctx.GetPlace());
395
#endif
396
    return pe_and_graph;
397 398 399
  }
};

400
template <typename T, typename DeviceContext>
401 402 403
class RunProgramGradOpKernel : public framework::OpKernel<T> {
 public:
  void Compute(const framework::ExecutionContext &ctx) const override {
404 405 406 407 408 409 410 411 412
    const auto &capture_mode = ctx.Attr<std::string>("cuda_graph_capture_mode");
    if (capture_mode.empty()) {
      ComputeImpl(ctx, false);
      return;
    }

#ifdef PADDLE_WITH_CUDA
    auto mode = details::StringToCUDAGraphCaptureMode(capture_mode);
    PADDLE_ENFORCE_EQ(
413 414
        platform::is_gpu_place(ctx.GetPlace()),
        true,
415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436
        phi::errors::InvalidArgument("The cuda_graph_capture_mode is only "
                                     "valid when using NVIDIA GPU."));
    auto *graph_var =
        const_cast<framework::Variable *>(ctx.InputVar("CUDAGraph"));
    PADDLE_ENFORCE_NOT_NULL(
        graph_var,
        phi::errors::InvalidArgument("Output(CUDAGraph) must exist when "
                                     "cuda_graph_capture_mode is valid."));
    auto &inner_graphs = *(
        graph_var
            ->GetMutable<std::vector<std::unique_ptr<CUDAGraphWithInOuts>>>());
    const size_t graph_idx = 2;
    if (inner_graphs[graph_idx].get() == nullptr) {
      framework::PEAndGraphPair pe_and_graph;
      auto callable =
          [this, &pe_and_graph](const framework::ExecutionContext &exe_ctx) {
            pe_and_graph = ComputeImpl(exe_ctx, true);
          };
      int64_t pool_id = inner_graphs[0].get() != nullptr
                            ? inner_graphs[0]->PoolID()
                            : inner_graphs[1]->PoolID();
      inner_graphs[graph_idx] =
437 438 439 440 441 442
          CaptureCUDAGraph(callable,
                           ctx,
                           {framework::GradVarName("Out")},
                           {framework::GradVarName("X")},
                           mode,
                           pool_id);
443 444
      VLOG(10) << "Capture Backward CUDA Graph";
    } else {
445 446
      ExecuteCUDAGraph(ctx,
                       {framework::GradVarName("Out")},
447 448 449 450 451 452 453 454 455 456 457 458 459 460
                       {framework::GradVarName("X")},
                       inner_graphs[graph_idx].get());
      VLOG(10) << "Run Backward CUDA Graph directly";
    }
#else
    PADDLE_THROW(
        phi::errors::InvalidArgument("The cuda_graph_capture_mode is only "
                                     "valid when using NVIDIA GPU."));
#endif
  }

 private:
  framework::PEAndGraphPair ComputeImpl(const framework::ExecutionContext &ctx,
                                        bool use_cuda_graph) const {
461
    VLOG(2) << "RunProgramGradOpKernel Compute";
462
    framework::PEAndGraphPair pe_and_graph;
463 464 465 466 467 468
    // Step 1. prepare inputs and outputs
    auto &output_grad_vars = ctx.MultiInputVar(framework::GradVarName("Out"));
    auto input_grad_vars = ctx.MultiOutputVar(framework::GradVarName("X"));
    auto param_grad_vars = ctx.MultiOutputVar(framework::GradVarName("Params"));

    // if all output vars are set to stop_gradient, grad op no need to executed
469 470 471
    if (input_grad_vars.empty() && param_grad_vars.empty()) {
      return pe_and_graph;
    }
472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487

    auto output_grad_var_names = ctx.InputNames(framework::GradVarName("Out"));
    // NOTE: after PR22939 [Add double grad] merged, the grad op maker's
    //   SetOutput will set to None if the input var stop_gradient=True,
    //   it will cause an NotFound error when ctx.OutputNames() is called
    std::vector<std::string> input_grad_var_names;
    std::vector<std::string> param_grad_names;
    if (!input_grad_vars.empty()) {
      input_grad_var_names = ctx.OutputNames(framework::GradVarName("X"));
    }
    if (!param_grad_vars.empty()) {
      param_grad_names = ctx.OutputNames(framework::GradVarName("Params"));
    }

    auto *block = ctx.Attr<BlockDesc *>("global_block");
    auto orig_end_op_index = ctx.Attr<int64_t>("end_op_index");
488
    auto program_id = ctx.Attr<int64_t>("program_id");
489
    // NOTE: skip `shape` and `fill_constant` op created by
490 491
    // fluid.backward.gradients, one forward output will generate one `shape`
    // and `fill_constant`
492 493 494 495 496
    int64_t start_op_index = orig_end_op_index + (output_grad_vars.size() * 2);
    int64_t end_op_index = block->OpSize();

    auto *out_scope_vec = ctx.Input<StepScopeVar>("OutScope");
    PADDLE_ENFORCE_EQ(
497 498
        out_scope_vec->size(),
        1,
499 500
        platform::errors::InvalidArgument(
            "The OutScope of RunProgramGradOp should only hold one scope."));
501 502 503 504

    framework::Scope *global_inner_scope = out_scope_vec->front();
    auto sub_scope_num = global_inner_scope->kids().size();
    VLOG(2) << "The number of sub scopes before backward: " << sub_scope_num;
505 506
    PADDLE_ENFORCE_GT(sub_scope_num,
                      0,
507 508 509 510 511
                      platform::errors::InvalidArgument(
                          "The OutScope of RunProgramGradOp should hold at "
                          "least one sub scope."));

    auto &scope = *(global_inner_scope->kids().front());
512
    auto *global_block = ctx.Attr<BlockDesc *>("global_block");
513

514 515
    if (end_op_index > start_op_index) {
      // Step 2. prepare executor and scope
516
      auto *program = global_block->Program();
517 518 519 520 521 522
      bool is_new_created;
      if (use_cuda_graph) {
        pe_and_graph = framework::CreateFixOrderExecutorInfo(
            *program, ctx.GetPlace(), start_op_index, end_op_index, &scope);
        is_new_created = true;
      } else {
523 524 525 526 527 528 529
        auto cache_info = framework::GetExecutorInfoFromCache(*program,
                                                              ctx.GetPlace(),
                                                              start_op_index,
                                                              end_op_index,
                                                              /*is_grad*/ true,
                                                              program_id,
                                                              &scope);
530 531 532
        pe_and_graph.first = cache_info.first;
        is_new_created = cache_info.second;
      }
533

534 535
      auto &parallel_executor = pe_and_graph.first;
      std::vector<std::string> tmp_vars;
536
      auto &skip_eager_delete_vars =
537 538 539 540 541
          use_cuda_graph
              ? tmp_vars
              : framework::ExecutorInfoCache::Instance().SkipEagerDeleteVars(
                    program_id, true);
      if (is_new_created) {
542 543 544 545 546 547 548 549 550
        parallel_executor->SkipMemoryReuse(/*scope_idx=*/0,
                                           output_grad_var_names);

        skip_eager_delete_vars.insert(skip_eager_delete_vars.end(),
                                      input_grad_var_names.begin(),
                                      input_grad_var_names.end());
        framework::details::AppendSkipDeletionVars(param_grad_names,
                                                   &skip_eager_delete_vars);
      }
551

552 553
      details::ShareVarsIntoScope(
          output_grad_vars, output_grad_var_names, &scope);
554 555 556 557 558 559 560
      // Debug info: scope info when run end
      VLOG(3) << framework::GenScopeTreeDebugInfo(out_scope_vec->front());

      // Step 3. run ops
      parallel_executor->RunWithoutFetch(
          /*skip_eager_delete_vars=*/skip_eager_delete_vars);
    }
561

562
    // Step 4. get outputs
563 564 565 566
    details::ShareVarsFromScope(
        input_grad_vars, input_grad_var_names, *global_block, &scope);
    details::ShareVarsFromScope(
        param_grad_vars, param_grad_names, *global_block, &scope);
567 568 569 570 571

    // Step5. drop current scope
    global_inner_scope->DeleteScope(&scope);
    VLOG(2) << "The number of sub scopes after backward: "
            << global_inner_scope->kids().size();
572
    return pe_and_graph;
573 574 575 576 577
  }
};

}  // namespace operators
}  // namespace paddle