test_hooks.cc 9.4 KB
Newer Older
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
// 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.

#include <memory>
#include <set>
#include <string>
#include <vector>

#include "glog/logging.h"
#include "gtest/gtest.h"
#include "paddle/fluid/framework/op_registry.h"
#include "paddle/fluid/imperative/basic_engine.h"
#include "paddle/fluid/imperative/hooks.h"
#include "paddle/fluid/imperative/tracer.h"
#include "paddle/fluid/memory/memcpy.h"
27 28 29 30
#include "paddle/phi/core/kernel_registry.h"

PD_DECLARE_KERNEL(add, CPU, ALL_LAYOUT);
PD_DECLARE_KERNEL(add_grad, CPU, ALL_LAYOUT);
31 32 33 34 35 36 37 38 39 40 41 42 43

namespace platform = paddle::platform;
namespace framework = paddle::framework;
namespace memory = paddle::memory;

DECLARE_bool(sort_sum_gradient);

namespace paddle {
namespace imperative {

using vb_vector = std::vector<std::shared_ptr<imperative::VarBase>>;
using var_pair = std::pair<std::string, vb_vector>;

44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
std::shared_ptr<imperative::VariableWrapper> DoubleHook(
    const std::shared_ptr<imperative::VariableWrapper>& var) {
  // 1. create out var
  auto out_var = std::make_shared<imperative::VariableWrapper>(var->Name());
  out_var->SetType(var->Type());
  out_var->SetDataType(var->DataType());
  out_var->SetForwardDataType(var->ForwardDataType());
  out_var->InnerSetOverridedStopGradient(var->InnerOverridedStopGradient());

  // 2. get input and output var's tensor
  auto* out_tensor = out_var->MutableVar()->GetMutable<framework::LoDTensor>();
  auto& tensor = var->Var().Get<framework::LoDTensor>();
  out_tensor->Resize(tensor.dims());

  // 3. double calc
  auto* data = tensor.data<float>();
  auto* out_data = out_tensor->mutable_data<float>(platform::CPUPlace());
  for (int64_t i = 0; i < out_tensor->numel(); ++i) {
    out_data[i] = data[i] * 2.0;
  }

  return out_var;
}

68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
TEST(TestHooks, TestGradVarLeafBackwardHook) {
  // 1. prepare
  Tracer tracer;
  std::shared_ptr<VarBase> x(new VarBase(true, "x"));
  std::shared_ptr<VarBase> y(new VarBase(true, "y"));
  std::shared_ptr<VarBase> out(new VarBase(true, "out"));
  x->SetOverridedStopGradient(false);
  y->SetOverridedStopGradient(false);

  platform::CPUPlace place;
  std::vector<float> src_data(10, 2.0);
  std::vector<int64_t> x_dims = {2, 5};
  std::vector<int64_t> y_dims = {5, 2};

  auto* x_tensor = x->MutableVar()->GetMutable<framework::LoDTensor>();
  auto* y_tensor = y->MutableVar()->GetMutable<framework::LoDTensor>();

85
  x_tensor->Resize(phi::make_ddim(x_dims));
86 87 88 89
  auto* mutable_x = x_tensor->mutable_data<float>(place);
  memory::Copy(place, mutable_x, place, src_data.data(),
               sizeof(float) * src_data.size());

90
  y_tensor->Resize(phi::make_ddim(y_dims));
91 92 93 94 95 96 97 98 99 100 101 102 103
  auto* mutable_y = y_tensor->mutable_data<float>(place);
  memory::Copy(place, mutable_y, place, src_data.data(),
               sizeof(float) * src_data.size());

  var_pair x_pair = var_pair("X", vb_vector(1, x));
  var_pair y_pair = var_pair("Y", vb_vector(1, y));
  var_pair out_pair = var_pair("Out", vb_vector(1, out));

  NameVarBaseMap ins = {x_pair, y_pair};
  NameVarBaseMap outs = {out_pair};
  framework::AttributeMap mul_attr_map;
  mul_attr_map["use_mkldnn"] = false;

104 105 106 107 108 109 110 111
  // add VariableWrapper hook
  x->GradVarBase()->AddVariableWrapperHook(
      std::make_shared<imperative::CppVariableWrapperHook>(DoubleHook));

  // add Void hook
  int64_t hook_value = 0;
  x->GradVarBase()->AddVoidHook(
      std::make_shared<std::function<void()>>([&]() { hook_value = 10; }));
112 113

  // 2. forward
J
Jiabin Yang 已提交
114
  tracer.TraceOp<VarBase>("mul", ins, outs, mul_attr_map, place, true);
115 116 117 118 119 120

  ASSERT_EQ(x->GradVarBase()->GradOpNum(), 0UL);
  ASSERT_EQ(y->GradVarBase()->GradOpNum(), 0UL);
  ASSERT_EQ(out->GradVarBase()->GradOpNum(), 1UL);

  // 3. backward
121 122
  std::vector<std::shared_ptr<imperative::VarBase>> tensors{out};
  std::vector<std::shared_ptr<imperative::VarBase>> grad_tensors{nullptr};
123
  BasicEngine engine;
124
  engine.Init(tensors, grad_tensors);
125 126
  engine.Execute();

127
  // verify VariableWrapper hook result
128 129 130 131 132 133
  framework::LoDTensor x_grad;
  framework::TensorCopySync(x->GradVar().Get<framework::LoDTensor>(), place,
                            &x_grad);
  for (int i = 0; i < x_grad.numel(); ++i) {
    ASSERT_EQ(x_grad.data<float>()[i], 8.0);
  }
134 135
  // verify Void hook result
  ASSERT_EQ(hook_value, 10);
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

  framework::LoDTensor y_grad;
  framework::TensorCopySync(y->GradVar().Get<framework::LoDTensor>(), place,
                            &y_grad);

  for (int i = 0; i < y_grad.numel(); ++i) {
    ASSERT_EQ(y_grad.data<float>()[i], 4.0);
  }
}

void GradVarLeafBackwardHookWithGradAccmulatedTest() {
  // 1. prepare
  Tracer tracer;
  std::shared_ptr<VarBase> x(new VarBase(true, "x"));
  std::shared_ptr<VarBase> y(new VarBase(true, "y"));
  std::shared_ptr<VarBase> z(new VarBase(true, "z"));
  std::shared_ptr<VarBase> out_xy(new VarBase(true, "out_xy"));
  std::shared_ptr<VarBase> out_xz(new VarBase(true, "out_xz"));
  std::shared_ptr<VarBase> out(new VarBase(true, "out"));
  x->SetOverridedStopGradient(false);
  y->SetOverridedStopGradient(false);
  z->SetOverridedStopGradient(false);

  platform::CPUPlace place;
  std::vector<float> src_data(10, 2.0);
  std::vector<int64_t> x_dims = {2, 5};
  std::vector<int64_t> y_dims = {5, 2};
  std::vector<int64_t> z_dims = {5, 2};

  auto* x_tensor = x->MutableVar()->GetMutable<framework::LoDTensor>();
  auto* y_tensor = y->MutableVar()->GetMutable<framework::LoDTensor>();
  auto* z_tensor = z->MutableVar()->GetMutable<framework::LoDTensor>();

169
  x_tensor->Resize(phi::make_ddim(x_dims));
170 171 172 173
  auto* mutable_x = x_tensor->mutable_data<float>(place);
  memory::Copy(place, mutable_x, place, src_data.data(),
               sizeof(float) * src_data.size());

174
  y_tensor->Resize(phi::make_ddim(y_dims));
175 176 177 178
  auto* mutable_y = y_tensor->mutable_data<float>(place);
  memory::Copy(place, mutable_y, place, src_data.data(),
               sizeof(float) * src_data.size());

179
  z_tensor->Resize(phi::make_ddim(z_dims));
180 181 182 183
  auto* mutable_z = z_tensor->mutable_data<float>(place);
  memory::Copy(place, mutable_z, place, src_data.data(),
               sizeof(float) * src_data.size());

184 185 186 187 188 189 190 191
  // add VariableWrapper hook
  x->GradVarBase()->AddVariableWrapperHook(
      std::make_shared<imperative::CppVariableWrapperHook>(DoubleHook));

  // add Void hook
  int64_t hook_value = 0;
  x->GradVarBase()->AddVoidHook(
      std::make_shared<std::function<void()>>([&]() { hook_value = 100; }));
192 193 194 195 196 197 198 199 200

  // 2. forward
  var_pair x_pair = var_pair("X", vb_vector(1, x));
  var_pair y_pair = var_pair("Y", vb_vector(1, y));
  var_pair out_xy_pair = var_pair("Out", vb_vector(1, out_xy));
  NameVarBaseMap ins = {x_pair, y_pair};
  NameVarBaseMap outs = {out_xy_pair};
  framework::AttributeMap mul_attr_map;
  mul_attr_map["use_mkldnn"] = false;
J
Jiabin Yang 已提交
201
  tracer.TraceOp<VarBase>("mul", ins, outs, mul_attr_map, place, true);
202 203 204 205 206

  var_pair z_pair = var_pair("Y", vb_vector(1, z));
  var_pair out_xz_pair = var_pair("Out", vb_vector(1, out_xz));
  ins = {x_pair, z_pair};
  outs = {out_xz_pair};
J
Jiabin Yang 已提交
207
  tracer.TraceOp<VarBase>("mul", ins, outs, mul_attr_map, place, true);
208 209 210 211 212 213 214

  var_pair xy_pair = var_pair("X", vb_vector(1, out_xy));
  var_pair xz_pair = var_pair("Y", vb_vector(1, out_xz));
  var_pair out_pair = var_pair("Out", vb_vector(1, out));
  ins = {xy_pair, xz_pair};
  outs = {out_pair};
  framework::AttributeMap add_attr_map;
J
Jiabin Yang 已提交
215 216
  tracer.TraceOp<VarBase>("elementwise_add", ins, outs, add_attr_map, place,
                          true);
217 218 219 220 221 222 223

  ASSERT_EQ(x->GradVarBase()->GradOpNum(), 0UL);
  ASSERT_EQ(y->GradVarBase()->GradOpNum(), 0UL);
  ASSERT_EQ(z->GradVarBase()->GradOpNum(), 0UL);
  ASSERT_EQ(out->GradVarBase()->GradOpNum(), 1UL);

  // 3. backward
224 225
  std::vector<std::shared_ptr<imperative::VarBase>> tensors{out};
  std::vector<std::shared_ptr<imperative::VarBase>> grad_tensors{nullptr};
226
  BasicEngine engine;
227
  engine.Init(tensors, grad_tensors);
228 229
  engine.Execute();

230
  // verify VariableWrapper hook result
231 232 233 234 235 236
  framework::LoDTensor x_grad;
  framework::TensorCopySync(x->GradVar().Get<framework::LoDTensor>(), place,
                            &x_grad);
  for (int i = 0; i < x_grad.numel(); ++i) {
    ASSERT_EQ(x_grad.data<float>()[i], 16.0);
  }
237 238
  // verify Void hook result
  ASSERT_EQ(hook_value, 100);
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

  framework::LoDTensor y_grad;
  framework::TensorCopySync(y->GradVar().Get<framework::LoDTensor>(), place,
                            &y_grad);

  for (int i = 0; i < y_grad.numel(); ++i) {
    ASSERT_EQ(y_grad.data<float>()[i], 4.0);
  }

  framework::LoDTensor z_grad;
  framework::TensorCopySync(z->GradVar().Get<framework::LoDTensor>(), place,
                            &z_grad);

  for (int i = 0; i < z_grad.numel(); ++i) {
    ASSERT_EQ(z_grad.data<float>()[i], 4.0);
  }
}

TEST(TestHooks, TestGradVarLeafBackwardHookWithGradAccmulated) {
  GradVarLeafBackwardHookWithGradAccmulatedTest();
}

TEST(TestHooks, TestGradVarLeafBackwardHookWithSortedGradAccmulated) {
  FLAGS_sort_sum_gradient = true;
  GradVarLeafBackwardHookWithGradAccmulatedTest();
  FLAGS_sort_sum_gradient = false;
}

}  // namespace imperative
}  // namespace paddle

USE_OP(mul);
USE_OP(mul_grad);
272 273
USE_OP_ITSELF(elementwise_add);
USE_OP_ITSELF(elementwise_add_grad);