test_reference_count_pass_last_lived_ops.cc 6.9 KB
Newer Older
Z
Zeng Jinle 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
// Copyright (c) 2019 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 "gtest/gtest.h"
#include "paddle/fluid/framework/details/multi_devices_helper.h"
#include "paddle/fluid/framework/ir/graph.h"
#include "paddle/fluid/framework/ir/graph_helper.h"
#include "paddle/fluid/framework/ir/memory_optimize_pass/memory_optimization_var_info.h"
#include "paddle/fluid/framework/ir/memory_optimize_pass/reference_count_pass_helper.h"
#include "paddle/fluid/framework/parallel_executor.h"
#include "paddle/fluid/framework/program_desc.h"

USE_OP(scale);
USE_OP(elementwise_mul);
USE_OP(elementwise_add);
USE_OP(elementwise_add_grad);

DECLARE_double(eager_delete_tensor_gb);

namespace paddle {
namespace framework {
33
namespace p = paddle::platform;
Z
Zeng Jinle 已提交
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 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91

static std::vector<platform::Place> CreatePlaces(size_t num, bool use_cuda) {
  std::vector<platform::Place> result;
  result.reserve(num);
  for (size_t i = 0; i < num; ++i) {
    if (use_cuda) {
      result.emplace_back(platform::CUDAPlace(i));
    } else {
      result.emplace_back(platform::CPUPlace());
    }
  }
  return result;
}

static void NewVar(BlockDesc *block, const std::string &name,
                   const std::vector<int64_t> &shape) {
  auto *var_desc = block->Var(name);
  var_desc->SetShape(shape);
}

static void AppendOp(BlockDesc *block, const std::string &type,
                     VariableNameMap inputs, VariableNameMap outputs,
                     AttributeMap attrs) {
  auto &op_info = OpInfoMap::Instance().Get(type);
  if (op_info.Checker()) {
    op_info.Checker()->Check(&attrs);
  }

  auto *op = block->AppendOp();
  op->SetType(type);
  for (auto &pair : inputs) {
    op->SetInput(pair.first, pair.second);
  }

  for (auto &pair : outputs) {
    op->SetOutput(pair.first, pair.second);
    for (auto &var_name : pair.second) {
      if (!block->FindVarRecursive(var_name)) {
        NewVar(block, var_name, {});
      }
    }
  }

  op->SetAttrMap(attrs);
  op->InferVarType(block);
  op->InferShape(*block);
}

class ReferenceCountPassTestHelper {
 public:
  ReferenceCountPassTestHelper(const ProgramDesc &program, bool use_cuda)
      : graph_(program) {
    details::BuildStrategy build_strategy;
    build_strategy.enable_inplace_ = false;
    build_strategy.memory_optimize_ = false;
    FLAGS_eager_delete_tensor_gb = -1;

    details::ExecutionStrategy exec_strategy;
92
    exec_strategy.use_device_ = use_cuda ? p::kCUDA : p::kCPU;
Z
Zeng Jinle 已提交
93 94 95 96 97 98 99 100 101

    executor_.reset(new ParallelExecutor(CreatePlaces(1, use_cuda), {}, "",
                                         &scope_, {}, exec_strategy,
                                         build_strategy, &graph_));

    auto ref_cnt_pass =
        ir::PassRegistry::Instance().Get("reference_count_pass");
    ref_cnt_pass->SetNotOwned(ir::kMemOptVarInfoMapList, &mem_opt_var_infos_);
    ref_cnt_pass->SetNotOwned(ir::kLastLiveOpsOfVars, &last_live_ops_of_vars_);
102
    ref_cnt_pass->Apply(&const_cast<ir::Graph &>(executor_->Graph()));
Z
Zeng Jinle 已提交
103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 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 178 179 180 181 182
  }

  bool IsLastLivedOps(const std::string &name,
                      std::vector<std::string> ops) const {
    std::sort(ops.begin(), ops.end());
    return LastLivedOpTypes(name) == ops;
  }

  std::vector<OperatorBase *> LastLivedOps(const std::string &name) const {
    auto &ops = last_live_ops_of_vars_[0].at(name).ops();
    std::vector<OperatorBase *> ret;
    for (auto *op : ops) {
      ret.emplace_back(op->GetOp());
    }
    return ret;
  }

 private:
  std::vector<std::string> LastLivedOpTypes(const std::string &name) const {
    auto iter = last_live_ops_of_vars_[0].find(name);
    std::vector<std::string> ret;
    if (iter != last_live_ops_of_vars_[0].end()) {
      for (auto *op : iter->second.ops()) {
        ret.emplace_back(op->GetOp()->Type());
      }
    }
    std::sort(ret.begin(), ret.end());
    return ret;
  }

 private:
  ir::Graph graph_;
  Scope scope_;
  std::unique_ptr<ParallelExecutor> executor_;

  ir::MemOptVarInfoMapList mem_opt_var_infos_;
  std::vector<ir::LastLiveOpsOfVars> last_live_ops_of_vars_;
};

TEST(test_reference_count_pass, test_no_need_buffer_var_shrink) {
  ProgramDesc program;
  auto *block = program.MutableBlock(0);
  std::vector<int64_t> shape{{3, 4, 5}};

  /**
   * The network is:
   *
   * x0 = fluid.layer.data(...)
   * x1 = scale(x0, scale=1)
   * x2 = scale(x1, scale=2)
   * x3 = elementwise_mul(x1, x2)
   * scale(x3, out=x1, scale=3) # produce a new version of x1
   * x4, x5 = elementwise_add_grad(dout=x3, x=x2, y=x1)
   * x6 = elementwise_mul(x4, x5)
   * x7 = elementwise_add(x5, x5)
   */
  std::string x0 = "x0";
  std::string x1 = "x1";
  std::string x2 = "x2";
  std::string x3 = "x3";
  std::string x4 = "x4";
  std::string x5 = "x5";
  std::string x6 = "x6";
  std::string x7 = "x7";

  NewVar(block, x0, shape);
  AppendOp(block, "scale", {{"X", {x0}}}, {{"Out", {x1}}}, {{"scale", 1.0f}});
  AppendOp(block, "scale", {{"X", {x1}}}, {{"Out", {x2}}}, {{"scale", 2.0f}});
  AppendOp(block, "elementwise_mul", {{"X", {x1}}, {"Y", {x2}}},
           {{"Out", {x3}}}, {});
  AppendOp(block, "scale", {{"X", {x3}}}, {{"Out", {x1}}}, {{"scale", 3.0f}});
  AppendOp(block, "elementwise_add_grad",
           {{GradVarName("Out"), {x3}}, {"X", {x2}}, {"Y", {x1}}},
           {{GradVarName("X"), {x4}}, {GradVarName("Y"), {x5}}}, {});
  AppendOp(block, "elementwise_mul", {{"X", {x4}}, {"Y", {x5}}},
           {{"Out", {x6}}}, {});
  AppendOp(block, "elementwise_add", {{"X", {x5}}, {"Y", {x5}}},
           {{"Out", {x7}}}, {});

  std::vector<bool> use_cuda_list{false};
183
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
Z
Zeng Jinle 已提交
184 185 186 187 188 189
  use_cuda_list.push_back(true);
#endif
  for (auto use_cuda : use_cuda_list) {
    ReferenceCountPassTestHelper helper(program, use_cuda);
    ASSERT_TRUE(helper.IsLastLivedOps(x0, {"scale"}));
    ASSERT_EQ(
190
        BOOST_GET_CONST(float, helper.LastLivedOps(x0)[0]->Attrs().at("scale")),
Z
Zeng Jinle 已提交
191 192 193 194
        1.0f);

    ASSERT_TRUE(helper.IsLastLivedOps(x1, {"scale"}));
    ASSERT_EQ(
195
        BOOST_GET_CONST(float, helper.LastLivedOps(x1)[0]->Attrs().at("scale")),
Z
Zeng Jinle 已提交
196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211
        3.0f);

    ASSERT_TRUE(helper.IsLastLivedOps(x2, {"elementwise_mul"}));
    ASSERT_TRUE(helper.IsLastLivedOps(x3, {"elementwise_add_grad"}));

    ASSERT_TRUE(helper.IsLastLivedOps(x4, {"elementwise_mul"}));
    ASSERT_TRUE(
        helper.IsLastLivedOps(x5, {"elementwise_mul", "elementwise_add"}));

    ASSERT_TRUE(helper.IsLastLivedOps(x6, {"elementwise_mul"}));
    ASSERT_TRUE(helper.IsLastLivedOps(x7, {"elementwise_add"}));
  }
}

}  // namespace framework
}  // namespace paddle