test_gradient_accmulator.cc 10.8 KB
Newer Older
J
Jiabin Yang 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
// 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 <memory>
16
#include <type_traits>
J
Jiabin Yang 已提交
17 18 19 20 21 22 23 24 25 26 27 28 29 30
#include <vector>
#include "gtest/gtest.h"
#include "paddle/fluid/framework/variable.h"
#include "paddle/fluid/imperative/gradient_accumulator.h"
#include "paddle/fluid/memory/memcpy.h"

namespace imperative = paddle::imperative;
namespace platform = paddle::platform;
namespace framework = paddle::framework;
namespace paddle {
namespace imperative {

void TensorAdd(const framework::Variable& src, framework::Variable* dst);

31 32
template <typename Place, typename T>
int TensorddTest(Place place, T t1, T t2) {
J
Jiabin Yang 已提交
33 34 35 36 37 38 39 40 41
  framework::Variable var1;
  framework::Variable var2;
  std::vector<T> src_data(10, t1);
  std::vector<T> dst_data(10, t2);
  std::vector<T> result;
  platform::CPUPlace src_place;
  for (unsigned int i = 0; i < 10; i++) {
    result.emplace_back(src_data[i] + dst_data[i]);
  }
42

J
Jiabin Yang 已提交
43 44 45 46 47 48 49
  std::vector<int64_t> dims = {2, 5};
  auto* src = var1.GetMutable<framework::LoDTensor>();
  auto* dst = var2.GetMutable<framework::LoDTensor>();
  src->Resize(framework::make_ddim(dims));
  dst->Resize(framework::make_ddim(dims));
  auto* src_mutable = src->mutable_data<T>(place);
  auto* dst_mutable = dst->mutable_data<T>(place);
50 51 52 53 54 55 56 57 58 59 60
  if (!std::is_same<Place, platform::CUDAPlace>::value) {
    paddle::memory::Copy(place, src_mutable, src_place, src_data.data(),
                         sizeof(T) * src_data.size());
    paddle::memory::Copy(place, dst_mutable, src_place, dst_data.data(),
                         sizeof(T) * dst_data.size());
#if defined(PADDLE_WITH_CUDA)
  } else {
    paddle::memory::Copy(place, src_mutable, src_place, src_data.data(),
                         sizeof(T) * src_data.size(), 0);
    paddle::memory::Copy(place, dst_mutable, src_place, dst_data.data(),
                         sizeof(T) * dst_data.size(), 0);
J
Jiabin Yang 已提交
61 62 63 64 65 66 67 68 69 70
#endif
  }
  imperative::TensorAdd(var1, &var2);
  framework::LoDTensor rlt;
  platform::CPUPlace rlt_place;
  framework::TensorCopySync(*dst, rlt_place, &rlt);

  for (unsigned int i = 0; i < rlt.numel(); i++) {
    if (rlt.data<T>()[i] != result[i]) return 1;
  }
71

J
Jiabin Yang 已提交
72 73 74 75 76 77 78 79 80 81
  return 0;
}

TEST(test_add_functor, add_functor) {
#if defined(PADDLE_WITH_CUDA)
  platform::CUDAPlace gpu_place(0);
#endif
  platform::CPUPlace cpu_place;

  int cpu_res = 1;
82 83 84 85
  cpu_res = TensorddTest(cpu_place, 1.0, 0.0);
  EXPECT_EQ(cpu_res, 0);
  cpu_res = TensorddTest(cpu_place, static_cast<double>(1.0),
                         static_cast<double>(2.0));
J
Jiabin Yang 已提交
86
  EXPECT_EQ(cpu_res, 0);
87 88
  cpu_res = TensorddTest(cpu_place, static_cast<platform::float16>(1.0),
                         static_cast<platform::float16>(2.0));
J
Jiabin Yang 已提交
89 90 91
  EXPECT_EQ(cpu_res, 0);
#if defined(PADDLE_WITH_CUDA)
  int gpu_res = 1;
92 93 94 95
  gpu_res = TensorddTest(gpu_place, 1.0, 0.0);
  EXPECT_EQ(gpu_res, 0);
  gpu_res = TensorddTest(gpu_place, static_cast<double>(1.0),
                         static_cast<double>(2.0));
J
Jiabin Yang 已提交
96
  EXPECT_EQ(gpu_res, 0);
97 98
  gpu_res = TensorddTest(gpu_place, static_cast<platform::float16>(1.0),
                         static_cast<platform::float16>(2.0));
J
Jiabin Yang 已提交
99 100 101 102
  EXPECT_EQ(gpu_res, 0);
#endif
}

103 104 105 106 107 108 109 110 111 112 113 114 115 116
TEST(test_add_functor, execption) {
  platform::CUDAPinnedPlace cuda_pinned_place;
  platform::CUDAPlace cuda_place(0);
  platform::CPUPlace cpu_place;

  ASSERT_ANY_THROW(TensorddTest(cpu_place, 1, 0));
#if defined(PADDLE_WITH_CUDA)
  ASSERT_ANY_THROW(TensorddTest(cuda_pinned_place, 1.0, 0.0));
  ASSERT_ANY_THROW(TensorddTest(cuda_pinned_place,
                                static_cast<platform::float16>(1.0),
                                static_cast<platform::float16>(2.0)));
#endif
}

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 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 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 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313
static void CopyVar(const framework::Variable& var,
                    framework::Variable* dst_ptr) {
  auto& dst = *dst_ptr;
  dst.Clear();
  if (var.IsType<framework::LoDTensor>()) {
    const auto& src_tensor = var.Get<framework::LoDTensor>();
    auto* dst_tensor = dst.GetMutable<framework::LoDTensor>();
    framework::TensorCopySync(src_tensor, src_tensor.place(), dst_tensor);
  } else {
    const auto& src_selected_rows = var.Get<framework::SelectedRows>();
    auto* dst_selected_rows = dst.GetMutable<framework::SelectedRows>();
    dst_selected_rows->set_rows(src_selected_rows.rows());
    dst_selected_rows->set_height(src_selected_rows.height());
    framework::TensorCopySync(src_selected_rows.value(),
                              src_selected_rows.value().place(),
                              dst_selected_rows->mutable_value());
  }
}

static bool IsEqualVar(const framework::Variable& var1,
                       const framework::Variable& var2) {
  if (var1.Type() != var2.Type()) {
    return false;
  }

  framework::Tensor t1, t2;

  if (var1.IsType<framework::LoDTensor>()) {
    framework::TensorCopySync(var1.Get<framework::LoDTensor>(),
                              platform::CPUPlace(), &t1);
    framework::TensorCopySync(var2.Get<framework::LoDTensor>(),
                              platform::CPUPlace(), &t2);
  } else {
    auto& s1 = var1.Get<framework::SelectedRows>();
    auto& s2 = var2.Get<framework::SelectedRows>();

    if (s1.height() != s2.height()) {
      return false;
    }

    if (s1.rows().size() != s2.rows().size()) {
      return false;
    }

    auto row1_data = s1.rows().data();
    auto row2_data = s2.rows().data();
    if (std::memcmp(row1_data, row2_data,
                    s1.rows().size() * sizeof(*row1_data)) != 0) {
      return false;
    }

    framework::TensorCopySync(var1.Get<framework::SelectedRows>().value(),
                              platform::CPUPlace(), &t1);
    framework::TensorCopySync(var2.Get<framework::SelectedRows>().value(),
                              platform::CPUPlace(), &t2);
  }

  if (t1.type() != t2.type() || t1.dims() != t2.dims()) {
    return false;
  }

  auto* t1_p = t1.data<void>();
  auto* t2_p = t2.data<void>();
  return std::memcmp(t1_p, t2_p,
                     t1.numel() * framework::SizeOfType(t1.type())) == 0;
}

template <typename T>
static framework::Variable RandomTensor(const framework::DDim& dims,
                                        const platform::Place& place,
                                        int low = -10, int high = 10) {
  framework::Tensor cpu_tensor;
  cpu_tensor.Resize(dims);
  auto* ptr = cpu_tensor.mutable_data<T>(platform::CPUPlace());
  std::uniform_int_distribution<int> dist(low, high);
  std::random_device rd;
  std::mt19937 engine(rd());
  for (int64_t i = 0; i < cpu_tensor.numel(); ++i) {
    ptr[i] = dist(engine);
  }

  framework::Variable ret;
  framework::TensorCopySync(cpu_tensor, place,
                            ret.GetMutable<framework::LoDTensor>());
  return ret;
}

template <typename T>
static framework::Variable RandomSelectedRows(framework::DDim dims,
                                              const platform::Place& place,
                                              int64_t row_number, int low = -10,
                                              int high = 10) {
  auto height = dims[0];
  dims[0] = row_number;

  framework::Variable ret;
  auto* sr = ret.GetMutable<framework::SelectedRows>();
  auto tensor_var = RandomTensor<T>(dims, place, low, high);
  sr->mutable_value()->ShareDataWith(
      tensor_var.template Get<framework::LoDTensor>());
  sr->set_height(height);
  sr->mutable_rows()->resize(row_number);
  auto* row_data = sr->mutable_rows()->data();
  std::uniform_int_distribution<int64_t> dist(0, height - 1);
  std::random_device rd;
  std::mt19937 engine(rd());
  for (int64_t i = 0; i < dims[0]; ++i) {
    row_data[i] = dist(engine);
  }
  return ret;
}

static std::unique_ptr<GradientAccumulator> CreateAccumulator(
    const std::shared_ptr<VariableWrapper>& var, bool sort_gradient) {
  if (sort_gradient) {
    return std::unique_ptr<GradientAccumulator>(
        new SortedGradientAccumulator(var.get()));
  } else {
    return std::unique_ptr<GradientAccumulator>(
        new EagerGradientAccumulator(var.get()));
  }
}

static void TestGradientAccumulatorTestUnchangeInput(
    const platform::Place& place, bool sort_gradient) {
  framework::DDim dim{10, 20};
  int64_t maximum_row_number = 100;

  std::uniform_int_distribution<int64_t> dist(1, maximum_row_number);
  int seed;
  {
    std::random_device rd;
    seed = rd();
  }

  std::mt19937 engine(seed);

  auto create_var = [&](bool use_tensor) {
    if (use_tensor) {
      return RandomTensor<float>(dim, place);
    } else {
      return RandomSelectedRows<float>(dim, place, dist(engine));
    }
  };

  std::vector<bool> use_tensors = {false, true};

  for (auto use_tensor1 : use_tensors) {
    for (auto use_tensor2 : use_tensors) {
      auto g_var1 = std::make_shared<VariableWrapper>("g_var1");
      g_var1->SetOverridedStopGradient(false);
      auto g_accum1 = CreateAccumulator(g_var1, sort_gradient);
      g_accum1->IncreaseRefCnt();
      g_accum1->IncreaseRefCnt();

      auto g_var2 = std::make_shared<VariableWrapper>("g_var2");
      g_var2->SetOverridedStopGradient(false);
      auto g_accum2 = CreateAccumulator(g_var2, sort_gradient);
      g_accum2->IncreaseRefCnt();
      g_accum2->IncreaseRefCnt();

      auto var1 = create_var(use_tensor1);
      auto var_wrapper1_1 = std::make_shared<VariableWrapper>("tmp1_1");
      auto var_wrapper2_1 = std::make_shared<VariableWrapper>("tmp2_1");
      CopyVar(var1, var_wrapper1_1->MutableVar());
      CopyVar(var1, var_wrapper2_1->MutableVar());

      auto var2 = create_var(use_tensor2);
      auto var_wrapper1_2 = std::make_shared<VariableWrapper>("tmp1_2");
      auto var_wrapper2_2 = std::make_shared<VariableWrapper>("tmp2_2");
      CopyVar(var2, var_wrapper1_2->MutableVar());
      CopyVar(var2, var_wrapper2_2->MutableVar());

      g_accum1->Add(var_wrapper1_1, 0, false);
      g_accum1->Add(var_wrapper1_2, 1, false);

      g_accum2->Add(var_wrapper2_1, 0, true);
      g_accum2->Add(var_wrapper2_2, 1, true);

      ASSERT_TRUE(IsEqualVar(var_wrapper2_1->Var(), var1));
      ASSERT_TRUE(IsEqualVar(var_wrapper2_2->Var(), var2));
      ASSERT_TRUE(IsEqualVar(g_var1->Var(), g_var2->Var()));
    }
  }
}

TEST(test_gradient_accumulator, test_unchange_input) {
  for (auto sort_gradient : {false, true}) {
    TestGradientAccumulatorTestUnchangeInput(platform::CPUPlace(),
                                             sort_gradient);
#ifdef PADDLE_WITH_CUDA
    TestGradientAccumulatorTestUnchangeInput(platform::CUDAPlace(0),
                                             sort_gradient);
#endif
  }
}

J
Jiabin Yang 已提交
314 315
}  // namespace imperative
}  // namespace paddle