op_tester.cc 18.0 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
/* Copyright (c) 2016 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/operators/benchmark/op_tester.h"
16
#include <fstream>
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
#include "gflags/gflags.h"
#include "gtest/gtest.h"
#include "paddle/fluid/framework/op_info.h"
#include "paddle/fluid/framework/op_registry.h"
#include "paddle/fluid/framework/variable_helper.h"
#include "paddle/fluid/platform/init.h"
#include "paddle/fluid/platform/profiler.h"
#include "paddle/fluid/platform/timer.h"
#include "paddle/fluid/pybind/pybind.h"

namespace paddle {
namespace operators {
namespace benchmark {

DEFINE_string(op_config_list, "", "Path of op config file.");
32
DEFINE_int32(specified_config_id, -1, "Test the specified op config.");
33 34 35 36 37 38 39 40 41 42 43 44 45

void OpTester::Init(const std::string &filename) {
  Init(OpTesterConfig(filename));
}

void OpTester::Init(const OpTesterConfig &config) {
  config_ = config;

  auto &op_desc_info = framework::OpInfoMap::Instance();
  // Initialize the OpDesc
  if (op_desc_info.Has(config_.op_type)) {
    type_ = config_.op_type;

Y
Yiqun Liu 已提交
46
    CreateOpDesc();
47 48 49
    CreateInputVarDesc();
    CreateOutputVarDesc();
  } else {
G
GaoWei8 已提交
50 51
    PADDLE_THROW(platform::errors::NotFound(
        "Operator '%s' is not registered in OpTester.", config_.op_type));
52 53 54 55 56 57 58 59
  }

  if (config_.device_id >= 0) {
    place_ = paddle::platform::CUDAPlace(config_.device_id);
  } else {
    place_ = paddle::platform::CPUPlace();
  }

60
  framework::InitDevices();
61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
  scope_.reset(new paddle::framework::Scope());

  op_ = framework::OpRegistry::CreateOp(op_desc_);
  CreateVariables(scope_.get());
}

void OpTester::Run() {
  if (config_.print_debug_string) {
    LOG(INFO) << DebugString();
  }

  // Warm up
  RunImpl();

  platform::Timer timer;
  if (config_.profile) {
    if (platform::is_cpu_place(place_)) {
      platform::EnableProfiler(platform::ProfilerState::kCPU);
    } else {
#ifdef PADDLE_WITH_CUDA
      platform::EnableProfiler(platform::ProfilerState::kAll);
      platform::SetDeviceId(config_.device_id);
#else
G
GaoWei8 已提交
84 85
      PADDLE_THROW(platform::errors::PermissionDenied(
          "'CUDAPlace' is not supported in CPU only device."));
86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 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
#endif
    }

    timer.Start();
    for (int i = config_.repeat; i > 0; --i) {
      RunImpl();
    }
    timer.Pause();
    platform::DisableProfiler(platform::EventSortingKey::kDefault,
                              "op_tester_profiler");
  } else {
    timer.Start();
    for (int i = config_.repeat; i > 0; --i) {
      RunImpl();
    }
    timer.Pause();
  }
  config_.runtime = timer.ElapsedMS() / config_.repeat;
  LOG(INFO) << "=== Run " << config_.repeat
            << " times, latency: " << config_.runtime << " ms ===";
}

void OpTester::RunImpl() {
  op_->Run(*scope_, place_);
  platform::DeviceContextPool::Instance().Get(place_)->Wait();
  scope_->DropKids();
}

std::vector<std::string> OpTester::GetOpProtoInputNames() {
  std::vector<std::string> input_names;
  const framework::proto::OpProto &proto =
      framework::OpInfoMap::Instance().Get(type_).Proto();
  for (int i = 0; i != proto.inputs_size(); ++i) {
    const auto &input = proto.inputs(i);
    input_names.push_back(input.name());
  }
  return input_names;
}

std::vector<std::string> OpTester::GetOpProtoOutputNames() {
  std::vector<std::string> output_names;
  const framework::proto::OpProto &proto =
      framework::OpInfoMap::Instance().Get(type_).Proto();
  for (int i = 0; i != proto.outputs_size(); ++i) {
    const auto &output = proto.outputs(i);
    output_names.push_back(output.name());
  }
  return output_names;
}

Y
Yiqun Liu 已提交
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
std::unordered_map<std::string, framework::proto::AttrType>
OpTester::GetOpProtoAttrNames() {
  std::unordered_map<std::string, framework::proto::AttrType> attr_types;
  const framework::proto::OpProto &proto =
      framework::OpInfoMap::Instance().Get(type_).Proto();
  const std::vector<std::string> skipped_attrs = {
      framework::OpProtoAndCheckerMaker::OpRoleAttrName(),
      framework::OpProtoAndCheckerMaker::OpRoleVarAttrName(),
      framework::OpProtoAndCheckerMaker::OpNamescopeAttrName(),
      framework::OpProtoAndCheckerMaker::OpCreationCallstackAttrName()};
  for (int i = 0; i != proto.attrs_size(); ++i) {
    const auto &attr = proto.attrs(i);
    if (!Has(skipped_attrs, attr.name())) {
      VLOG(4) << "attr: " << attr.name() << ", type: " << attr.type();
      attr_types[attr.name()] = attr.type();
    }
  }
  return attr_types;
}

framework::proto::VarType::Type OpTester::TransToVarType(std::string str) {
  if (str == "int32") {
    return framework::proto::VarType::INT32;
  } else if (str == "int64") {
    return framework::proto::VarType::INT64;
  } else if (str == "fp32") {
    return framework::proto::VarType::FP32;
  } else if (str == "fp64") {
    return framework::proto::VarType::FP64;
  } else {
G
GaoWei8 已提交
166 167
    PADDLE_THROW(platform::errors::Unimplemented(
        "Unsupported dtype %s in OpTester.", str.c_str()));
Y
Yiqun Liu 已提交
168 169 170
  }
}

171 172 173 174
void OpTester::CreateInputVarDesc() {
  std::vector<std::string> input_names = GetOpProtoInputNames();
  for (auto &name : input_names) {
    const OpInputConfig *input = config_.GetInput(name);
175 176 177 178
    PADDLE_ENFORCE_NOT_NULL(
        input, platform::errors::NotFound(
                   "The input %s of operator %s is not correctlly provided.",
                   name, config_.op_type));
179 180 181 182 183 184

    std::string var_name = config_.op_type + "." + name;
    framework::VarDesc *var = Var(var_name);
    // Need to support more type
    var->SetType(framework::proto::VarType::LOD_TENSOR);
    var->SetPersistable(false);
Y
Yiqun Liu 已提交
185
    var->SetDataType(TransToVarType(input->dtype));
186 187 188
    var->SetShape(input->dims);

    op_desc_.SetInput(name, {var_name});
Y
Yiqun Liu 已提交
189
    inputs_[var_name] = *input;
190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206
  }
}

void OpTester::CreateOutputVarDesc() {
  std::vector<std::string> output_names = GetOpProtoOutputNames();
  for (auto &name : output_names) {
    std::string var_name = config_.op_type + "." + name;
    framework::VarDesc *var = Var(var_name);
    // Need to support more type
    var->SetType(framework::proto::VarType::LOD_TENSOR);
    var->SetPersistable(false);
    var->SetDataType(framework::proto::VarType::FP32);

    op_desc_.SetOutput(name, {var_name});
  }
}

Y
Yiqun Liu 已提交
207 208 209 210 211 212
void OpTester::CreateOpDesc() {
  op_desc_.SetType(config_.op_type);
  std::unordered_map<std::string, framework::proto::AttrType> attr_types =
      GetOpProtoAttrNames();
  for (auto item : config_.attrs) {
    const std::string &name = item.first;
213 214 215 216
    PADDLE_ENFORCE_NE(
        attr_types.find(name), attr_types.end(),
        platform::errors::NotFound("Operator %s does not have attribute %d.",
                                   type_, name));
Y
Yiqun Liu 已提交
217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237

    const std::string &value_str = item.second;
    const framework::proto::AttrType &type = attr_types[name];
    switch (type) {
      case framework::proto::AttrType::BOOLEAN:
        break;
      case framework::proto::AttrType::INT: {
        int value = StringTo<int>(value_str);
        op_desc_.SetAttr(name, {value});
      } break;
      case framework::proto::AttrType::FLOAT: {
        float value = StringTo<float>(value_str);
        op_desc_.SetAttr(name, {value});
      } break;
      case framework::proto::AttrType::STRING: {
        op_desc_.SetAttr(name, {value_str});
      } break;
      case framework::proto::AttrType::BOOLEANS:
      case framework::proto::AttrType::INTS:
      case framework::proto::AttrType::FLOATS:
      case framework::proto::AttrType::STRINGS:
G
GaoWei8 已提交
238 239
        PADDLE_THROW(platform::errors::Unimplemented(
            "Unsupported STRINGS type in OpTester yet."));
Y
Yiqun Liu 已提交
240 241 242 243 244 245 246
        break;
      case framework::proto::AttrType::LONG: {
        int64_t value = StringTo<int64_t>(value_str);
        op_desc_.SetAttr(name, value);
      } break;
      case framework::proto::AttrType::LONGS:
      default:
G
GaoWei8 已提交
247 248
        PADDLE_THROW(platform::errors::Unimplemented(
            "Unsupport attr type %d in OpTester.", type));
Y
Yiqun Liu 已提交
249 250 251 252
    }
  }
}

253 254 255 256 257 258 259 260 261 262 263 264
framework::VarDesc *OpTester::Var(const std::string &name) {
  auto it = vars_.find(name);
  if (it != vars_.end()) {
    return it->second.get();
  }
  auto *var = new framework::VarDesc(name);
  vars_[name].reset(var);
  return var;
}

template <typename T>
void OpTester::SetupTensor(framework::LoDTensor *tensor,
Y
Yiqun Liu 已提交
265
                           const std::vector<int64_t> &shape, T lower, T upper,
266 267
                           const std::string &initializer,
                           const std::string &filename) {
268 269 270 271 272
  static unsigned int seed = 100;
  std::mt19937 rng(seed++);
  std::uniform_real_distribution<double> uniform_dist(0, 1);

  T *ptr = tensor->mutable_data<T>(framework::make_ddim(shape), place_);
Y
Yiqun Liu 已提交
273 274 275 276 277 278 279

  framework::LoDTensor cpu_tensor;
  T *cpu_ptr = nullptr;

  if (!platform::is_cpu_place(place_)) {
    cpu_ptr = cpu_tensor.mutable_data<T>(framework::make_ddim(shape),
                                         platform::CPUPlace());
280
  } else {
Y
Yiqun Liu 已提交
281 282 283 284
    cpu_ptr = ptr;
  }

  if (initializer == "random") {
285 286 287
    for (int i = 0; i < cpu_tensor.numel(); ++i) {
      cpu_ptr[i] = static_cast<T>(uniform_dist(rng) * (upper - lower) + lower);
    }
Y
Yiqun Liu 已提交
288 289
  } else if (initializer == "natural") {
    for (int i = 0; i < cpu_tensor.numel(); ++i) {
290
      cpu_ptr[i] = static_cast<T>(lower + i);
Y
Yiqun Liu 已提交
291 292 293
    }
  } else if (initializer == "zeros") {
    for (int i = 0; i < cpu_tensor.numel(); ++i) {
294
      cpu_ptr[i] = static_cast<T>(0);
Y
Yiqun Liu 已提交
295
    }
296 297
  } else if (initializer == "file") {
    std::ifstream is(filename);
298
    for (int i = 0; i < cpu_tensor.numel(); ++i) {
299 300 301 302 303
      T value;
      is >> value;
      cpu_ptr[i] = static_cast<T>(value);
    }
    is.close();
Y
Yiqun Liu 已提交
304
  } else {
G
GaoWei8 已提交
305 306
    PADDLE_THROW(platform::errors::Unimplemented(
        "Unsupported initializer %s in OpTester.", initializer.c_str()));
Y
Yiqun Liu 已提交
307 308 309
  }

  if (!platform::is_cpu_place(place_)) {
310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331
    TensorCopySync(cpu_tensor, place_, tensor);
  }
}

void OpTester::CreateVariables(framework::Scope *scope) {
  for (auto &item : vars_) {
    auto &var = item.second;
    if (var->Name() == framework::kEmptyVarName) {
      continue;
    }

    auto *ptr = scope->Var(var->Name());
    framework::InitializeVariable(ptr, var->GetType());
    if (var->Persistable()) {
      VLOG(3) << "Create Variable " << var->Name()
              << " global, which pointer is " << ptr;
    } else {
      VLOG(3) << "Create Variable " << var->Name()
              << " locally, which pointer is " << ptr;
    }
  }

Y
Yiqun Liu 已提交
332
  for (auto &item : inputs_) {
333 334 335 336 337
    // Allocate memory for input tensor
    auto &var_name = item.first;
    VLOG(3) << "Allocate memory for tensor " << var_name;

    auto &var_desc = vars_[var_name];
338 339
    std::vector<int64_t> shape = var_desc->GetShape();

340
    auto *var = scope->Var(var_name);
341
    auto *tensor = var->GetMutable<framework::LoDTensor>();
Y
Yiqun Liu 已提交
342 343
    const auto &data_type = var_desc->GetDataType();
    if (data_type == framework::proto::VarType::INT32) {
344 345
      SetupTensor<int>(tensor, shape, 0, 1, item.second.initializer,
                       item.second.filename);
Y
Yiqun Liu 已提交
346
    } else if (data_type == framework::proto::VarType::INT64) {
347 348
      SetupTensor<int64_t>(tensor, shape, 0, 1, item.second.initializer,
                           item.second.filename);
Y
Yiqun Liu 已提交
349 350
    } else if (data_type == framework::proto::VarType::FP32) {
      SetupTensor<float>(tensor, shape, static_cast<float>(0.0),
351 352
                         static_cast<float>(1.0), item.second.initializer,
                         item.second.filename);
Y
Yiqun Liu 已提交
353 354
    } else if (data_type == framework::proto::VarType::FP64) {
      SetupTensor<double>(tensor, shape, static_cast<double>(0.0),
355 356
                          static_cast<double>(1.0), item.second.initializer,
                          item.second.filename);
Y
Yiqun Liu 已提交
357
    } else {
G
GaoWei8 已提交
358 359
      PADDLE_THROW(platform::errors::Unimplemented(
          "Unsupported dtype %d in OpTester.", data_type));
Y
Yiqun Liu 已提交
360
    }
361 362

    VLOG(3) << "Set lod for tensor " << var_name;
Y
Yiqun Liu 已提交
363
    std::vector<std::vector<size_t>> &lod_vec = item.second.lod;
364 365 366 367 368
    framework::LoD lod;
    for (size_t i = 0; i < lod_vec.size(); ++i) {
      lod.push_back(lod_vec[i]);
    }
    tensor->set_lod(lod);
369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390
  }
}

static std::string GenSpaces(int count) {
  std::stringstream ss;
  for (int i = 0; i < count; ++i) {
    ss << "  ";
  }
  return ss.str();
}

std::string OpTester::DebugString() {
  std::stringstream ss;
  int count = 0;
  for (auto &item : vars_) {
    auto &var = item.second;
    ss << GenSpaces(count++) << "vars {\n";
    ss << GenSpaces(count) << "name: \"" << var->Name() << "\"\n";
    ss << GenSpaces(count++) << "type: {\n";
    ss << GenSpaces(count) << "type: LOD_TENSOR\n";
    ss << GenSpaces(count++) << "lod_tensor {\n";
    ss << GenSpaces(count++) << "tensor {\n";
Y
Yiqun Liu 已提交
391 392 393 394 395 396 397 398 399 400
    const auto &data_type = var->GetDataType();
    if (data_type == framework::proto::VarType::INT32) {
      ss << GenSpaces(count) << "data_type: INT32\n";
    } else if (data_type == framework::proto::VarType::INT64) {
      ss << GenSpaces(count) << "data_type: INT64\n";
    } else if (data_type == framework::proto::VarType::FP32) {
      ss << GenSpaces(count) << "data_type: FP32\n";
    } else if (data_type == framework::proto::VarType::FP64) {
      ss << GenSpaces(count) << "data_type: FP64\n";
    }
401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426
    std::vector<int64_t> shape = var->GetShape();
    for (auto d : shape) {
      ss << GenSpaces(count) << "dims: " << d << "\n";
    }
    ss << GenSpaces(--count) << "}\n";
    ss << GenSpaces(--count) << "}\n";
    ss << GenSpaces(--count) << "}\n";
    ss << GenSpaces(count) << "persistable: " << var->Persistable() << "\n";
    ss << GenSpaces(--count) << "}\n";
  }
  ss << GenSpaces(count++) << "ops {\n";
  for (auto &name : op_desc_.InputNames()) {
    ss << GenSpaces(count++) << "inputs {\n";
    ss << GenSpaces(count) << "parameters: \"" << name << "\"\n";
    ss << GenSpaces(count) << "arguments: \"" << op_desc_.Input(name)[0]
       << "\"\n";
    ss << GenSpaces(--count) << "}\n";
  }
  for (auto &name : op_desc_.OutputNames()) {
    ss << GenSpaces(count++) << "outputs {\n";
    ss << GenSpaces(count) << "parameters: \"" << name << "\"\n";
    ss << GenSpaces(count) << "arguments: \"" << op_desc_.Output(name)[0]
       << "\"\n";
    ss << GenSpaces(--count) << "}\n";
  }
  ss << GenSpaces(count) << "type: " << op_desc_.Type() << "\n";
Y
Yiqun Liu 已提交
427 428 429 430 431 432 433 434
  for (auto &name : op_desc_.AttrNames()) {
    ss << GenSpaces(count++) << "attrs {\n";
    const auto &attr_type = op_desc_.GetAttrType(name);
    const auto &attr = op_desc_.GetAttr(name);
    ss << GenSpaces(count) << "name: \"" << name << "\"\n";
    switch (attr_type) {
      case framework::proto::AttrType::BOOLEAN: {
        ss << GenSpaces(count) << "type: BOOLEAN\n";
435
        ss << GenSpaces(count) << "b: " << BOOST_GET_CONST(bool, attr) << "\n";
Y
Yiqun Liu 已提交
436 437 438
      } break;
      case framework::proto::AttrType::INT: {
        ss << GenSpaces(count) << "type: INT\n";
439
        ss << GenSpaces(count) << "i: " << BOOST_GET_CONST(int, attr) << "\n";
Y
Yiqun Liu 已提交
440 441 442
      } break;
      case framework::proto::AttrType::FLOAT: {
        ss << GenSpaces(count) << "type: FLOAT\n";
443
        ss << GenSpaces(count) << "f: " << BOOST_GET_CONST(float, attr) << "\n";
Y
Yiqun Liu 已提交
444 445 446
      } break;
      case framework::proto::AttrType::STRING: {
        ss << GenSpaces(count) << "type: STRING\n";
447
        ss << GenSpaces(count) << "s: \"" << BOOST_GET_CONST(std::string, attr)
Y
Yiqun Liu 已提交
448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471
           << "\"\n";
      } break;
      case framework::proto::AttrType::BOOLEANS: {
        ss << GenSpaces(count) << "type: BOOLEANS\n";
        ss << GenSpaces(count) << "bools: "
           << "\n";
      } break;
      case framework::proto::AttrType::INTS: {
        ss << GenSpaces(count) << "type: INTS\n";
        ss << GenSpaces(count) << "ints: "
           << "\n";
      } break;
      case framework::proto::AttrType::FLOATS: {
        ss << GenSpaces(count) << "type: FLOATS\n";
        ss << GenSpaces(count) << "floats: "
           << "\n";
      } break;
      case framework::proto::AttrType::STRINGS: {
        ss << GenSpaces(count) << "type: STRINGS\n";
        ss << GenSpaces(count) << "strings: "
           << "\n";
      } break;
      case framework::proto::AttrType::LONG: {
        ss << GenSpaces(count) << "type: LONG\n";
472 473
        ss << GenSpaces(count) << "l: " << BOOST_GET_CONST(int64_t, attr)
           << "\n";
Y
Yiqun Liu 已提交
474 475 476 477 478 479 480
      } break;
      case framework::proto::AttrType::LONGS: {
        ss << GenSpaces(count) << "type: LONGS\n";
        ss << GenSpaces(count) << "longs: "
           << "\n";
      } break;
      default:
G
GaoWei8 已提交
481 482
        PADDLE_THROW(platform::errors::Unimplemented(
            "Unsupport attr type %d in OpTester.", attr_type));
Y
Yiqun Liu 已提交
483 484 485
    }
    ss << GenSpaces(--count) << "}\n";
  }
486 487 488 489 490 491
  ss << GenSpaces(--count) << "}\n";
  return ss.str();
}

TEST(op_tester, base) {
  if (!FLAGS_op_config_list.empty()) {
492
    std::ifstream fin(FLAGS_op_config_list, std::ios::in | std::ios::binary);
G
GaoWei8 已提交
493 494 495 496
    PADDLE_ENFORCE_EQ(
        static_cast<bool>(fin), true,
        platform::errors::InvalidArgument("OpTester cannot open file %s",
                                          FLAGS_op_config_list.c_str()));
497 498
    std::vector<OpTesterConfig> op_configs;
    while (!fin.eof()) {
Y
Yiqun Liu 已提交
499
      VLOG(4) << "Reading config " << op_configs.size() << "...";
500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517
      OpTesterConfig config;
      bool result = config.Init(fin);
      if (result) {
        op_configs.push_back(config);
      }
    }
    if (FLAGS_specified_config_id >= 0 &&
        FLAGS_specified_config_id < static_cast<int>(op_configs.size())) {
      OpTester tester;
      tester.Init(op_configs[FLAGS_specified_config_id]);
      tester.Run();
    } else {
      for (size_t i = 0; i < op_configs.size(); ++i) {
        OpTester tester;
        tester.Init(op_configs[i]);
        tester.Run();
      }
    }
518
  } else {
519
    OpTester tester;
520 521 522 523 524 525 526 527
    OpTesterConfig config;
    config.op_type = "elementwise_add";
    config.inputs.resize(2);
    config.inputs[0].name = "X";
    config.inputs[0].dims = {64, 64};
    config.inputs[1].name = "Y";
    config.inputs[1].dims = {64, 1};
    tester.Init(config);
528
    tester.Run();
529 530 531 532 533 534
  }
}

}  // namespace benchmark
}  // namespace operators
}  // namespace paddle