benchmark_utils.cc 12.6 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 27 28 29 30
// Copyright (c) 2021 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 "paddle/fluid/eager/tests/performance_tests/benchmark_utils.h"

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

// Eager
#include "paddle/fluid/eager/api/all.h"
#include "paddle/fluid/eager/autograd_meta.h"
#include "paddle/fluid/eager/backward.h"
#include "paddle/fluid/eager/tests/test_utils.h"
#include "paddle/fluid/eager/utils.h"

// Eager Generated
31
#include "paddle/fluid/eager/api/generated/eager_generated/forwards/dygraph_functions.h"
32 33 34 35 36 37 38 39
#include "paddle/fluid/eager/api/generated/fluid_generated/dygraph_forward_api.h"

// Fluid
#include "paddle/fluid/framework/op_registry.h"
#include "paddle/fluid/imperative/basic_engine.h"
#include "paddle/fluid/imperative/tracer.h"
#include "paddle/fluid/memory/memcpy.h"

40
static size_t max_num_benchmark_runs = 4000;
41 42 43 44 45 46

namespace egr {

/* --------------------- */
/* ---- Eager Scale ---- */
/* --------------------- */
47 48 49
void benchmark_eager_scale(const paddle::experimental::Tensor& tensor,
                           bool accuracy_check) {
  paddle::experimental::Tensor input_tensor = tensor;
50 51 52 53 54
  float scale = 2.0;
  float bias = 3.0;

  size_t max_num_runs = accuracy_check ? 10 : max_num_benchmark_runs;
  for (size_t i = 0; i < max_num_runs; i++) {
55 56 57 58 59
    input_tensor = egr::scale(input_tensor,
                              scale,
                              bias,
                              true /*bias_after_scale*/,
                              true /*trace_backward*/);
60 61
  }

62
  std::vector<paddle::experimental::Tensor> target_tensors = {input_tensor};
63
  Backward(target_tensors, {});
64 65 66

  if (accuracy_check) {
    // Examine Forward Grad (w.r.t max_num_runs = 10)
67
    eager_test::CompareTensorWithValue<float>(input_tensor, 8189.0);
68
    // Examine Backward Grad (w.r.t max_num_runs = 10)
69
    eager_test::CompareGradTensorWithValue<float>(tensor, 1024.0);
70 71 72
  }
}

73 74 75 76 77 78 79 80 81 82 83 84
void benchmark_eager_matmul(const paddle::experimental::Tensor& X,
                            const paddle::experimental::Tensor& Y,
                            bool accuracy_check) {
  paddle::experimental::Tensor input_tensor0 = X;

  size_t max_num_runs = accuracy_check ? 2 : max_num_benchmark_runs;
  for (size_t i = 0; i < max_num_runs; i++) {
    input_tensor0 =
        matmul_final_state_dygraph_function(input_tensor0, Y, false, false);
  }

  std::vector<paddle::experimental::Tensor> target_tensors = {input_tensor0};
85
  Backward(target_tensors, {});
86 87 88 89 90 91 92 93 94 95

  if (accuracy_check) {
    // Examine Forward Grad (w.r.t max_num_runs = 2)
    eager_test::CompareTensorWithValue<float>(input_tensor0, 16);
    // Examine Backward Grad (w.r.t max_num_runs = 2)
    eager_test::CompareGradTensorWithValue<float>(X, 16);
    eager_test::CompareGradTensorWithValue<float>(Y, 16);
  }
}

96 97 98
/* ----------------------------------- */
/* ---- Eager Intermediate Matmul ---- */
/* ----------------------------------- */
99 100
void benchmark_eager_intermediate_matmul(const paddle::experimental::Tensor& X,
                                         const paddle::experimental::Tensor& Y,
101
                                         bool accuracy_check) {
102
  paddle::experimental::Tensor input_tensor0 = X;
103 104 105 106 107 108 109

  size_t max_num_runs = accuracy_check ? 2 : max_num_benchmark_runs;
  for (size_t i = 0; i < max_num_runs; i++) {
    input_tensor0 = matmul_v2_dygraph_function(
        input_tensor0, Y, {{"trans_x", false}, {"trans_y", false}});
  }

110
  std::vector<paddle::experimental::Tensor> target_tensors = {input_tensor0};
111
  Backward(target_tensors, {});
112 113 114

  if (accuracy_check) {
    // Examine Forward Grad (w.r.t max_num_runs = 2)
115
    eager_test::CompareTensorWithValue<float>(input_tensor0, 16);
116
    // Examine Backward Grad (w.r.t max_num_runs = 2)
117 118
    eager_test::CompareGradTensorWithValue<float>(X, 16);
    eager_test::CompareGradTensorWithValue<float>(Y, 16);
119 120 121 122 123 124
  }
}

/* -------------------------------- */
/* ---- Eager Intermediate MLP ---- */
/* -------------------------------- */
125 126 127
void benchmark_eager_intermediate_mlp(
    const paddle::experimental::Tensor& X,
    const std::vector<paddle::experimental::Tensor>& Ws,
128 129
    const std::vector<paddle::experimental::Tensor>& Bs,
    bool accuracy_check) {
130
  paddle::experimental::Tensor input0 = X;
131 132

  for (size_t i = 0; i < MLP_NUM_LINEAR; i++) {
133
    paddle::experimental::Tensor Out = matmul_v2_dygraph_function(
134 135 136 137 138
        input0, Ws[i], {{"trans_x", false}, {"trans_y", false}});

    input0 = elementwise_add_dygraph_function(Out, Bs[i], {});
  }

139 140
  paddle::experimental::Tensor Out =
      reduce_sum_dygraph_function(input0, {{"reduce_all", true}});
141

142
  std::vector<paddle::experimental::Tensor> target_tensors = {Out};
143
  Backward(target_tensors, {});
144 145 146 147 148 149

  if (accuracy_check) {
    std::unordered_map<std::string, float> result =
        compute_mlp_expected_results();

    // Examine Forward Grad (w.r.t max_num_runs = 2)
150
    eager_test::CompareTensorWithValue<float>(Out, result["Out"]);
151 152

    // Examine Backward Grad (w.r.t max_num_runs = 2)
153 154
    eager_test::CompareGradTensorWithValue<float>(X, result["GradX"]);
    eager_test::CompareGradTensorWithValue<float>(Ws[0], result["GradW"]);
155 156 157 158 159 160 161 162 163 164 165 166 167 168
  }
}

}  // namespace egr

namespace paddle {
namespace imperative {

static void FluidCheckTensorValue(const std::shared_ptr<imperative::VarBase>& X,
                                  const paddle::platform::Place& place,
                                  float value) {
  auto* tensor = X->MutableVar()->GetMutable<framework::LoDTensor>();
  float* t_ptr = tensor->mutable_data<float>(place);
  std::vector<float> host_data(tensor->numel());
169 170

#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
171 172 173
  if (place == paddle::platform::CUDAPlace()) {
    paddle::platform::DeviceContextPool& pool =
        paddle::platform::DeviceContextPool::Instance();
L
Leo Chen 已提交
174
    auto* dev_ctx = dynamic_cast<phi::GPUContext*>(pool.Get(place));
175 176
    auto stream = dev_ctx->stream();

177 178 179 180 181 182
    paddle::memory::Copy(paddle::platform::CPUPlace(),
                         host_data.data(),
                         paddle::platform::CUDAPlace(),
                         t_ptr,
                         sizeof(float) * tensor->numel(),
                         stream);
183 184
    t_ptr = host_data.data();
  }
185 186
#endif

187 188 189 190 191 192 193 194 195
  VLOG(6) << "Tensor Value: " << t_ptr[0] << ", Expected Value: " << value;
  PADDLE_ENFORCE(
      t_ptr[0] == value,
      paddle::platform::errors::Fatal(
          "Detected numerical Error, Expected %f but got %f", value, t_ptr[0]));
}

static void FluidCheckGradTensorValue(
    const std::shared_ptr<imperative::VarBase>& X,
196 197
    const paddle::platform::Place& place,
    float value) {
198 199 200
  auto* grad_tensor = X->MutableGradVar()->GetMutable<framework::LoDTensor>();
  float* g_ptr = grad_tensor->mutable_data<float>(place);
  std::vector<float> g_host_data(grad_tensor->numel());
201 202

#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
203 204 205
  if (place == paddle::platform::CUDAPlace()) {
    paddle::platform::DeviceContextPool& pool =
        paddle::platform::DeviceContextPool::Instance();
L
Leo Chen 已提交
206
    auto* dev_ctx = dynamic_cast<phi::GPUContext*>(pool.Get(place));
207 208
    auto stream = dev_ctx->stream();

209 210 211 212 213 214
    paddle::memory::Copy(paddle::platform::CPUPlace(),
                         g_host_data.data(),
                         paddle::platform::CUDAPlace(),
                         g_ptr,
                         sizeof(float) * grad_tensor->numel(),
                         stream);
215 216
    g_ptr = g_host_data.data();
  }
217 218
#endif

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
  VLOG(6) << "Tensor Value: " << g_ptr[0] << ", Expected Value: " << value;
  PADDLE_ENFORCE(
      g_ptr[0] == value,
      paddle::platform::errors::Fatal(
          "Detected numerical Error, Expected %f but got %f", value, g_ptr[0]));
}

/* --------------------- */
/* ---- Fluid Scale ---- */
/* --------------------- */
// TODO(jiabin): Change this and remove nolint
void benchmark_fluid_scale(const std::shared_ptr<imperative::VarBase>& X,
                           const paddle::platform::Place& place,
                           bool accuracy_check) {
  imperative::Tracer tracer;
  framework::AttributeMap attrs;

  attrs["use_mkldnn"] = false;
  attrs["scale"] = 2;
  attrs["bias"] = 3;
  attrs["bias_after_scale"] = true;

  std::shared_ptr<imperative::VarBase> tmp_out = X;

  size_t max_num_runs = accuracy_check ? 10 : max_num_benchmark_runs;
  for (size_t i = 0; i < max_num_runs; i++) {
    imperative::NameVarBaseMap ins = {{"X", {tmp_out}}};
    imperative::NameVarBaseMap outs = {
        {"Out",
         {std::shared_ptr<imperative::VarBase>(
             new imperative::VarBase(true, "Out"))}}};

J
Jiabin Yang 已提交
251
    tracer.TraceOp<VarBase>("scale", ins, outs, attrs, place, true);
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

    tmp_out = outs["Out"][0];
  }

  auto* engine = tracer.GetEngine();
  std::vector<std::shared_ptr<imperative::VarBase>> grad_tensors{nullptr};
  engine->Init({tmp_out}, grad_tensors, false /*retain_graph*/);
  engine->Execute();

  if (accuracy_check) {
    FluidCheckTensorValue(tmp_out, place, 8189.0);
    FluidCheckGradTensorValue(X, place, 1024.0);
  }
}

/* ---------------------- */
/* ---- Fluid Matmul ---- */
/* ---------------------- */
void benchmark_fluid_matmul(const std::shared_ptr<imperative::VarBase>& X,
                            const std::shared_ptr<imperative::VarBase>& Y,
                            const paddle::platform::Place& place,
                            bool accuracy_check) {
  imperative::Tracer tracer;

  std::shared_ptr<imperative::VarBase> tmp_out = X;

  size_t max_num_runs = accuracy_check ? 2 : max_num_benchmark_runs;
  for (size_t i = 0; i < max_num_runs; i++) {
    framework::AttributeMap attrs;
    imperative::NameVarBaseMap ins = {{"X", {tmp_out}}, {"Y", {Y}}};
    imperative::NameVarBaseMap outs = {
        {"Out",
         {std::shared_ptr<imperative::VarBase>(
             new imperative::VarBase(true, "Out"))}}};

J
Jiabin Yang 已提交
287
    tracer.TraceOp<VarBase>("matmul_v2", ins, outs, attrs, place, true);
288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310

    tmp_out = outs["Out"][0];
  }

  auto* engine = tracer.GetEngine();
  std::vector<std::shared_ptr<imperative::VarBase>> grad_tensors{nullptr};
  engine->Init({tmp_out}, grad_tensors, false /*retain_graph*/);
  engine->Execute();

  if (accuracy_check) {
    FluidCheckTensorValue(tmp_out, place, 16);
    FluidCheckGradTensorValue(X, place, 16);
    FluidCheckGradTensorValue(Y, place, 16);
  }
}

/* ------------------- */
/* ---- Fluid MLP ---- */
/* ------------------- */
void benchmark_fluid_mlp(
    const std::shared_ptr<imperative::VarBase>& X,
    const std::vector<std::shared_ptr<imperative::VarBase>>& Ws,
    const std::vector<std::shared_ptr<imperative::VarBase>>& Bs,
311 312
    const paddle::platform::Place& place,
    bool accuracy_check) {
313 314 315 316 317 318 319 320 321 322 323 324 325
  imperative::Tracer tracer;

  imperative::NameVarBaseMap ins;
  imperative::NameVarBaseMap outs;
  framework::AttributeMap attrs;
  std::shared_ptr<imperative::VarBase> input0 = X;
  for (size_t i = 0; i < MLP_NUM_LINEAR; i++) {
    // Matmul0
    ins = {{"X", {input0}}, {"Y", {Ws[0]}}};
    outs = {{"Out",
             {std::shared_ptr<imperative::VarBase>(
                 new imperative::VarBase(true, "Out"))}}};

J
Jiabin Yang 已提交
326
    tracer.TraceOp<VarBase>("matmul_v2", ins, outs, attrs, place, true);
327 328 329 330 331 332 333

    // EW-Add0
    ins = {{"X", outs["Out"]}, {"Y", {Bs[i]}}};
    outs = {{"Out",
             {std::shared_ptr<imperative::VarBase>(
                 new imperative::VarBase(true, "Out"))}}};

J
Jiabin Yang 已提交
334
    tracer.TraceOp<VarBase>("elementwise_add", ins, outs, attrs, place, true);
335 336 337 338 339 340 341 342 343 344
    input0 = outs["Out"][0];
  }

  // ReduceSum
  ins = {{"X", {input0}}};
  outs = {{"Out",
           {std::shared_ptr<imperative::VarBase>(
               new imperative::VarBase(true, "Out"))}}};
  attrs = {{"reduce_all", true}};

J
Jiabin Yang 已提交
345
  tracer.TraceOp<VarBase>("reduce_sum", ins, outs, attrs, place, true);
346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363

  auto* engine = tracer.GetEngine();
  std::vector<std::shared_ptr<imperative::VarBase>> grad_tensors{nullptr};
  engine->Init(outs["Out"], grad_tensors, false /*retain_graph*/);
  engine->Execute();

  if (accuracy_check) {
    std::unordered_map<std::string, float> result =
        egr::compute_mlp_expected_results();

    FluidCheckTensorValue(outs["Out"][0], place, result["Out"]);
    FluidCheckGradTensorValue(X, place, result["GradX"]);
    FluidCheckGradTensorValue(Ws[0], place, result["GradW"]);
  }
}

}  // namespace imperative
}  // namespace paddle