cpu_quantize_pass_tester.cc 24.4 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
// 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.

15
#include "paddle/fluid/framework/ir/mkldnn/cpu_quantize_pass.h"
16
#include <gtest/gtest.h>
17

18
#include "paddle/fluid/framework/naive_executor.h"
H
hong 已提交
19
#include "paddle/fluid/imperative/type_defs.h"
20 21 22 23 24 25 26 27 28
#include "paddle/fluid/platform/place.h"

namespace paddle {
namespace framework {
namespace ir {

void SetOp(ProgramDesc* prog, const std::string& type, const std::string& name,
           const std::vector<std::string>& inputs,
           const std::vector<std::string>& outputs, bool use_mkldnn,
29
           const std::string& mkldnn_data_type = "float32") {
30 31 32 33
  auto* op = prog->MutableBlock(0)->AppendOp();
  op->SetType(type);
  op->SetAttr("use_mkldnn", use_mkldnn);
  op->SetAttr("name", name);
H
hong 已提交
34

35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
  if (type == "conv2d") {
    op->SetInput("Input", {inputs[0]});
    op->SetInput("Filter", {inputs[1]});
    if (inputs.size() > 2)
      op->SetInput("Bias", {inputs[2]});
    else
      op->SetInput("Bias", {});
    if (inputs.size() > 3) {
      op->SetInput("ResidualData", {inputs[3]});
      op->SetAttr("fuse_residual_connection", true);
    } else {
      op->SetInput("ResidualData", {});
      op->SetAttr("fuse_residual_connection", false);
    }
    op->SetOutput("Output", {outputs[0]});
50
    op->SetAttr("mkldnn_data_type", mkldnn_data_type);
51 52 53
    op->SetAttr("Scale_in", 1.0f);
    op->SetAttr("Scale_out", 1.0f);
    op->SetAttr("Scale_weights", std::vector<float>{1.0f});
54
  } else if (type == "pool2d" || type == "transpose2" || type == "reshape2") {
55 56
    op->SetInput("X", {inputs[0]});
    op->SetOutput("Out", {outputs[0]});
57
    op->SetAttr("mkldnn_data_type", mkldnn_data_type);
58 59 60 61 62 63 64 65
  } else if (type == "dropout") {
    op->SetInput("X", {inputs[0]});
    op->SetOutput("Out", {outputs[0]});
  } else if (type == "fc") {
    op->SetInput("Input", {inputs[0]});
    if (inputs.size() > 1) op->SetInput("W", {inputs[1]});
    if (inputs.size() > 2) op->SetInput("Bias", {inputs[2]});
    op->SetOutput("Out", {outputs[0]});
66
    op->SetAttr("mkldnn_data_type", mkldnn_data_type);
M
Michał Gallus 已提交
67 68 69
    op->SetAttr("Scale_in", 1.0f);
    op->SetAttr("Scale_out", 1.0f);
    op->SetAttr("Scale_weights", std::vector<float>{1.0f});
70 71 72
  } else if (type == "concat") {
    op->SetInput("X", inputs);
    op->SetOutput("Out", outputs);
73
    op->SetAttr("mkldnn_data_type", mkldnn_data_type);
74 75 76 77
  } else if (type == "dequantize") {
    op->SetInput("Input", {inputs[0]});
    op->SetOutput("Output", {outputs[0]});
    op->SetAttr("Scale", 1.0f);
78 79 80 81
  } else if (type == "matmul") {
    op->SetInput("X", {inputs[0]});
    if (inputs.size() > 1) op->SetInput("Y", {inputs[1]});
    op->SetOutput("Out", {outputs[0]});
82
    op->SetAttr("mkldnn_data_type", mkldnn_data_type);
83 84 85
    op->SetAttr("Scale_x", 1.0f);
    op->SetAttr("Scale_y", 1.0f);
    op->SetAttr("Scale_out", 1.0f);
86 87 88 89
  } else if (type == "elementwise_add") {
    op->SetInput("X", {inputs[0]});
    if (inputs.size() > 1) op->SetInput("Y", {inputs[1]});
    op->SetOutput("Out", {outputs[0]});
90
    op->SetAttr("mkldnn_data_type", mkldnn_data_type);
91 92 93
    op->SetAttr("Scale_x", 1.0f);
    op->SetAttr("Scale_y", 1.0f);
    op->SetAttr("Scale_out", 1.0f);
94 95 96
  }
}

97 98 99 100 101 102 103 104 105
void InitTensorHolder(Scope* scope, const paddle::platform::Place& place,
                      const char* var_name) {
  auto x = scope->Var(var_name);
  auto tensor = x->GetMutable<LoDTensor>();
  tensor->mutable_data(place, proto::VarType::FP32, 1);
}

void PreparePass(std::unique_ptr<ir::Graph>* graph, const ProgramDesc& prog,
                 const std::initializer_list<std::string> variable_names,
106
                 int* original_nodes_num, int* current_nodes_num,
107 108
                 std::string var_without_scale = "",
                 std::string var_signed = "") {
109 110 111 112 113 114
  auto place = paddle::platform::CPUPlace();
  NaiveExecutor exe{place};
  Scope scope;
  exe.CreateVariables(prog, 0, true, &scope);
  auto* scales = new VarQuantScale();
  for (auto& v : variable_names) {
115
    if (v.compare(var_without_scale) == 0) continue;
116 117 118 119 120
    InitTensorHolder(&scope, place, v.c_str());
    LoDTensor tensor;
    tensor.Resize({1});
    auto* ptr = tensor.mutable_data<double>(place);
    ptr[0] = 2.0;
121
    (*scales)[v] = std::make_pair(v == var_signed, std::move(tensor));
122 123 124 125 126 127 128 129 130 131 132 133
  }

  (*graph)->SetNotOwned(kParamScopeAttr, &scope);
  std::unique_ptr<Pass> pass =
      PassRegistry::Instance().Get("cpu_quantize_pass");
  pass->Set("quant_var_scales", scales);

  *original_nodes_num = (*graph)->Nodes().size();
  (*graph).reset(pass->Apply((*graph).release()));
  *current_nodes_num = (*graph)->Nodes().size();
}

134
namespace {
135
static const std::initializer_list<std::string> variable_names{
M
Michał Gallus 已提交
136 137
    "a",  "w1", "c", "d", "w2", "e",  "f",  "g", "h",
    "w3", "b1", "i", "j", "w4", "b2", "w5", "b3"};
138 139 140 141
// (a,w1)->Conv1->c and c->Pool1->d
//
// (d,w2)->Conv2->e and e->Pool2->f
//
M
Michał Gallus 已提交
142
// d->Dropout1->g and (g, w5, b3)->Fc1->h and (h,w3,b1,i)->Conv3->j
143 144
//
// (d,w4, b2)->Conv4->i
145 146
ProgramDesc BuildProgramDesc(bool use_mkldnn,
                             const std::string& mkldnn_data_type) {
147 148 149 150 151 152 153 154 155
  ProgramDesc prog;
  for (auto& v : variable_names) {
    auto* var = prog.MutableBlock(0)->Var(v);
    if (v.find("w") == 0 || v.find("b") == 0) {
      var->SetPersistable(true);
    }
  }

  SetOp(&prog, "conv2d", "Conv1", {"a", "w1"}, {"c"}, use_mkldnn,
156 157
        mkldnn_data_type);
  SetOp(&prog, "pool2d", "Pool1", {"c"}, {"d"}, use_mkldnn, mkldnn_data_type);
158 159

  SetOp(&prog, "conv2d", "Conv2", {"d", "w2"}, {"e"}, use_mkldnn,
160 161
        mkldnn_data_type);
  SetOp(&prog, "pool2d", "Pool2", {"e"}, {"f"}, use_mkldnn, mkldnn_data_type);
162 163

  SetOp(&prog, "dropout", "Dropout1", {"d"}, {"g"}, use_mkldnn);
M
Michał Gallus 已提交
164
  SetOp(&prog, "fc", "Fc1", {"g", "w5", "b3"}, {"h"}, use_mkldnn,
165
        mkldnn_data_type);
166
  SetOp(&prog, "conv2d", "Conv3", {"h", "w3", "b1", "i"}, {"j"}, use_mkldnn,
167
        mkldnn_data_type);
168 169

  SetOp(&prog, "conv2d", "Conv4", {"c", "w4", "b2"}, {"i"}, use_mkldnn,
170
        mkldnn_data_type);
171 172 173 174

  return prog;
}

175 176 177 178 179 180 181
void MainTest(const ProgramDesc& prog, int conv_count, int pool_count,
              int quant_count, int dequant_count, int added_nodes_count,
              float scale) {
  std::unique_ptr<ir::Graph> graph(new ir::Graph(prog));
  int original_nodes_num, current_nodes_num;
  PreparePass(&graph, prog, variable_names, &original_nodes_num,
              &current_nodes_num);
182 183 184 185 186 187 188 189 190 191

  int quantize_nodes_count = 0;
  int dequantize_nodes_count = 0;
  int conv2d_nodes_count = 0;
  int pool2d_nodes_count = 0;
  for (auto* node : graph->Nodes()) {
    if (node->IsOp()) {
      auto* op = node->Op();
      if (op->Type() == "conv2d") {
        conv2d_nodes_count++;
192 193
        auto op_name = BOOST_GET_CONST(std::string, op->GetAttr("name"));
        EXPECT_EQ(BOOST_GET_CONST(float, op->GetAttr("Scale_in")), scale)
194
            << "Scale_in for node '" + op_name + "'.";
195
        EXPECT_EQ(BOOST_GET_CONST(float, op->GetAttr("Scale_out")), scale)
196
            << "Scale_out for node '" + op_name + "'.";
197 198 199
        EXPECT_EQ(BOOST_GET_CONST(std::vector<float>,
                                  op->GetAttr("Scale_weights"))[0],
                  scale)
200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218
            << "Scale_weights for node '" + op_name + "'.";
      } else if (op->Type() == "pool2d") {
        pool2d_nodes_count++;
      } else if (op->Type() == "quantize") {
        quantize_nodes_count++;
      } else if (op->Type() == "dequantize") {
        dequantize_nodes_count++;
      }
    }
  }
  EXPECT_EQ(conv2d_nodes_count, conv_count);
  EXPECT_EQ(pool2d_nodes_count, pool_count);
  EXPECT_EQ(quantize_nodes_count, quant_count);
  EXPECT_EQ(dequantize_nodes_count, dequant_count);
  EXPECT_EQ(original_nodes_num + added_nodes_count, current_nodes_num);
}

TEST(CpuQuantizePass, quantize) {
  bool use_mkldnn = true;
219
  std::string mkldnn_data_type = "int8";
220 221 222 223 224 225
  // (a->QUANT1->IN1,w1)->Conv1->OUT1->DEQUANT1->c and
  // c->QUANT2->IN2->Pool1->OUT2->DEQUANT2->d
  //
  // (d->QUANT3->IN3,w2)->Conv2->OUT3->DEQUANT3->e and
  // e->QUANT4->IN4->Pool2->OUT4->DEQUANT4->f
  //
M
Michał Gallus 已提交
226
  // d->Dropout1->g and (g->QUANT8->IN8,w5,b3)->Fc1->OUT7->DEQUANT7->h and
227 228 229
  // (h->QUANT5->IN5,w3,b1,i->QUANT6->IN6)->Conv3->OUT5->DEQUANT5->j
  //
  // (d->QUANT7->IN7,w4, b2)->Conv4->DEQUANT6->OUT6->i
M
Michał Gallus 已提交
230 231
  // Insert nodes: 8 Quant + 8 IN + 7 OUT + 7 DEQUANT
  int added_nodes = 8 + 8 + 7 + 7;
232 233
  MainTest(BuildProgramDesc(use_mkldnn, mkldnn_data_type), 4, 2, 8, 7,
           added_nodes, 2.0f * 127);
234 235 236 237
}

TEST(CpuQuantizePass, do_not_quantize) {
  bool use_mkldnn = true;
238
  std::string mkldnn_data_type = "float32";
239
  int added_nodes = 0;
240 241
  MainTest(BuildProgramDesc(use_mkldnn, mkldnn_data_type), 4, 2, 0, 0,
           added_nodes, 1.0f);
242 243
}

244 245 246 247 248 249 250 251 252 253
static const std::initializer_list<std::string> variable_names_concat = {
    "a1", "b1", "a2", "b2", "c", "d"};

// a1->Pool1->b1
// a2->Pool2->b2
// (b1,b2)->Concat->c
// c->Pool3->d
ProgramDesc BuildProgramDescConcat() {
  ProgramDesc prog;

254 255 256 257
  SetOp(&prog, "pool2d", "Pool1", {"a1"}, {"b1"}, true, "float32");
  SetOp(&prog, "pool2d", "Pool2", {"a2"}, {"b2"}, true, "float32");
  SetOp(&prog, "concat", "Concat", {"b1", "b2"}, {"c"}, true, "int8");
  SetOp(&prog, "pool2d", "Pool3", {"c"}, {"d"}, true, "float32");
258 259 260 261 262 263 264

  return prog;
}

void MainTestConcat(const ProgramDesc& prog, int pool_count, int concat_count,
                    int quant_count, int dequant_count, int added_nodes_count) {
  std::unique_ptr<ir::Graph> graph(new ir::Graph(prog));
265 266 267
  int original_nodes_num, current_nodes_num;
  PreparePass(&graph, prog, variable_names_concat, &original_nodes_num,
              &current_nodes_num);
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

  int quantize_nodes_count = 0;
  int dequantize_nodes_count = 0;
  int concat_nodes_count = 0;
  int pool2d_nodes_count = 0;
  for (auto* node : graph->Nodes()) {
    if (node->IsOp()) {
      auto* op = node->Op();
      if (op->Type() == "concat") {
        concat_nodes_count++;
      } else if (op->Type() == "pool2d") {
        pool2d_nodes_count++;
      } else if (op->Type() == "quantize") {
        quantize_nodes_count++;
      } else if (op->Type() == "dequantize") {
        dequantize_nodes_count++;
      }
    }
  }
  EXPECT_EQ(concat_nodes_count, concat_count);
  EXPECT_EQ(pool2d_nodes_count, pool_count);
  EXPECT_EQ(quantize_nodes_count, quant_count);
  EXPECT_EQ(dequantize_nodes_count, dequant_count);
  EXPECT_EQ(original_nodes_num + added_nodes_count, current_nodes_num);
}

TEST(CpuQuantizePass, concat) {
  // a1->Pool1->b1
  // a2->Pool2->b2
  // (b1->QUANT1->IN1, b2->QUANT2->IN2)->Concat->c
  // c->OUT1->DEQUANT1->Pool3->d
  int pool_count = 3;
  int concat_count = 1;
  int quant_count = 2;
  int dequant_count = 1;
  int added_nodes_count = 6;
  MainTestConcat(BuildProgramDescConcat(), pool_count, concat_count,
                 quant_count, dequant_count, added_nodes_count);
}

308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324
static const std::initializer_list<std::string> variable_names_transpose = {
    "a", "w1", "b", "c", "w2", "d", "e", "f"};

// a->Conv1->b
// b->Transpose1->c
// c->Conv2->d
// d->Transpose2->e
// e->Dropout->f
ProgramDesc BuildProgramDescTranspose() {
  ProgramDesc prog;
  for (auto& v : variable_names_transpose) {
    auto* var = prog.MutableBlock(0)->Var(v);
    if (v.find("w") == 0) {
      var->SetPersistable(true);
    }
  }

325 326 327 328 329
  SetOp(&prog, "conv2d", "Conv1", {"a", "w1"}, {"b"}, true, "int8");
  SetOp(&prog, "transpose2", "Transpose1", {"b"}, {"c"}, true, "int8");
  SetOp(&prog, "conv2d", "Conv1", {"c", "w2"}, {"d"}, true, "int8");
  SetOp(&prog, "transpose2", "Transpose2", {"d"}, {"e"}, true, "int8");
  SetOp(&prog, "dropout", "Dropout", {"e"}, {"f"}, true, "float32");
330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352

  return prog;
}

void MainTestTranspose(const ProgramDesc& prog, int conv_count,
                       int transpose_count, int quant_count, int dequant_count,
                       int added_nodes_count, float scale) {
  std::unique_ptr<ir::Graph> graph(new ir::Graph(prog));
  int original_nodes_num, current_nodes_num;
  PreparePass(&graph, prog, variable_names_transpose, &original_nodes_num,
              &current_nodes_num);

  int quantize_nodes_count = 0;
  int dequantize_nodes_count = 0;
  int transpose_nodes_count = 0;
  int conv_nodes_count = 0;
  for (auto* node : graph->Nodes()) {
    if (node->IsOp()) {
      auto* op = node->Op();
      if (op->Type() == "transpose2") {
        transpose_nodes_count++;
      } else if (op->Type() == "conv2d") {
        conv_nodes_count++;
353 354
        auto op_name = BOOST_GET_CONST(std::string, op->GetAttr("name"));
        EXPECT_EQ(BOOST_GET_CONST(float, op->GetAttr("Scale_in")), scale)
355
            << "Scale_in for node '" + op_name + "'.";
356
        EXPECT_EQ(BOOST_GET_CONST(float, op->GetAttr("Scale_out")), scale)
357
            << "Scale_out for node '" + op_name + "'.";
358 359 360
        EXPECT_EQ(BOOST_GET_CONST(std::vector<float>,
                                  op->GetAttr("Scale_weights"))[0],
                  scale)
361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386
            << "Scale_weights for node '" + op_name + "'.";
      } else if (op->Type() == "quantize") {
        quantize_nodes_count++;
      } else if (op->Type() == "dequantize") {
        dequantize_nodes_count++;
      }
    }
  }
  EXPECT_EQ(transpose_nodes_count, transpose_count);
  EXPECT_EQ(conv_nodes_count, conv_count);
  EXPECT_EQ(quantize_nodes_count, quant_count);
  EXPECT_EQ(dequantize_nodes_count, dequant_count);
  EXPECT_EQ(original_nodes_num + added_nodes_count, current_nodes_num);
}

TEST(CpuQuantizePass, transpose) {
  // a1->Quant->a2->Conv1->b1->Dequant->b2
  // b2->Quant->b3->Transpose->c1->Dequant->c2
  // c2->Quant->c3->Conv2->d1->Dequant->d2
  // d2->Quant->d3->Transpose->e1->Dequant->e2
  // e2->Dropout->f
  int conv_count = 2;
  int transpose_count = 2;
  int quant_count = 4;
  int dequant_count = 4;
  // 4 Quant + 4 IN + 4 DeQuant + 4 OUT
387
  int added_nodes_count = 4 + 4 + 4 + 4;
388 389 390
  MainTestTranspose(BuildProgramDescTranspose(), conv_count, transpose_count,
                    quant_count, dequant_count, added_nodes_count, 2.0f * 127);
}
391 392 393 394 395 396 397 398 399

static const std::initializer_list<std::string> variable_names_reshape = {
    "a", "w1", "b", "c", "d", "e", "f"};

// a->Dequantize->b
// b->Reshape->c
// c->Dropout->d
ProgramDesc BuildProgramDescReshape() {
  ProgramDesc prog;
400
  for (auto& v : variable_names_reshape) {
401 402 403
    prog.MutableBlock(0)->Var(v);
  }
  SetOp(&prog, "dequantize", "Dequantize1", {"a"}, {"b"}, true);
404 405
  SetOp(&prog, "reshape2", "Reshape2", {"b"}, {"c"}, true, "int8");
  SetOp(&prog, "dropout", "Dropout", {"c"}, {"d"}, true, "float32");
406 407 408 409 410 411 412 413 414

  return prog;
}

// a->Transpose->b
// b->Reshape->c
// c->Dropout->d
ProgramDesc BuildProgramDescReshapeBetweenNonQuantizedOp() {
  ProgramDesc prog;
415
  for (auto& v : variable_names_reshape) {
416 417 418
    prog.MutableBlock(0)->Var(v);
  }

419 420 421
  SetOp(&prog, "transpose2", "Transpose2", {"a"}, {"b"}, true, "float32");
  SetOp(&prog, "reshape2", "Reshape2", {"b"}, {"c"}, true, "int8");
  SetOp(&prog, "dropout", "Dropout", {"c"}, {"d"}, true, "float32");
422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448

  return prog;
}

void MainTestReshape(const ProgramDesc& prog, int transpose_count,
                     int reshape_count, int quant_count, int dequant_count,
                     int added_nodes_count, float scale) {
  std::unique_ptr<ir::Graph> graph(new ir::Graph(prog));
  int original_nodes_num, current_nodes_num;
  PreparePass(&graph, prog, variable_names_reshape, &original_nodes_num,
              &current_nodes_num);

  float quant_scale = 1.0f;
  float dequant_scale = 1.0f;
  int quantize_nodes_count = 0;
  int dequantize_nodes_count = 0;
  int transpose_nodes_count = 0;
  int reshape_nodes_count = 0;
  for (auto* node : graph->Nodes()) {
    if (node->IsOp()) {
      auto* op = node->Op();
      if (op->Type() == "transpose2") {
        transpose_nodes_count++;
      } else if (op->Type() == "reshape2") {
        reshape_nodes_count++;
      } else if (op->Type() == "quantize") {
        quantize_nodes_count++;
449
        quant_scale = BOOST_GET_CONST(float, op->GetAttr("Scale"));
450 451 452 453
        EXPECT_EQ(quant_scale, scale) << "Scale for node '" + op->Type() + "'.";
      } else if (op->Type() == "dequantize") {
        dequantize_nodes_count++;
        auto op_name = op->GetAttrIfExists<std::string>("name");
454
        VLOG(3) << op_name << "\n";
455
        if (op_name != "Dequantize1") {
456
          dequant_scale = BOOST_GET_CONST(float, op->GetAttr("Scale"));
457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497
          EXPECT_EQ(dequant_scale, scale)
              << "Scale for node '" + op->Type() + "'.";
        }
      }
    }
  }
  EXPECT_EQ(transpose_nodes_count, transpose_count);
  EXPECT_EQ(reshape_nodes_count, reshape_count);
  EXPECT_EQ(quantize_nodes_count, quant_count);
  EXPECT_EQ(dequantize_nodes_count, dequant_count);
  EXPECT_EQ(original_nodes_num + added_nodes_count, current_nodes_num);
}

TEST(CpuQuantizePass, reshape) {
  // a->Dequantize->b
  // b2->Quant->b3->Reshape2->c1->Dequant->c2
  // c2->Dropout->d
  int reshape_count = 1;
  int transpose_count = 0;
  int quant_count = 1;
  int dequant_count = 2;
  // 1 Quant + 1 IN + 1 DeQuant + 1 OUT
  int added_nodes_count = 4;
  MainTestReshape(BuildProgramDescReshape(), transpose_count, reshape_count,
                  quant_count, dequant_count, added_nodes_count, 2.0f * 127);
}

TEST(CpuQuantizePass, reshapeBetweenNonQuantizedOp) {
  // a->Transpos2->b
  // b->Reshape2->c
  // c->Dropout->d
  int reshape_count = 1;
  int transpose_count = 1;
  int quant_count = 0;
  int dequant_count = 0;
  // 0 Quant + 0 IN + 0 DeQuant + 0 OUT
  int added_nodes_count = 0;
  MainTestReshape(BuildProgramDescReshapeBetweenNonQuantizedOp(),
                  transpose_count, reshape_count, quant_count, dequant_count,
                  added_nodes_count, 2.0f * 127);
}
498

499 500 501 502 503
static const std::initializer_list<std::string> variable_names_matmul = {
    "a", "b", "c", "d", "e", "f"};

ProgramDesc BuildProgramDescMatmul() {
  ProgramDesc prog;
504
  for (auto& v : variable_names_matmul) {
505 506 507 508
    prog.MutableBlock(0)->Var(v);
  }
  SetOp(&prog, "dequantize", "Dequantize1", {"a"}, {"b"}, true);
  SetOp(&prog, "dequantize", "Dequantize2", {"c"}, {"d"}, true);
509 510
  SetOp(&prog, "matmul", "Matmul", {"b", "d"}, {"e"}, true, "int8");
  SetOp(&prog, "dropout", "Dropout", {"e"}, {"f"}, true, "float32");
511 512 513 514 515 516

  return prog;
}

ProgramDesc BuildProgramDescMatmulNotQuantized() {
  ProgramDesc prog;
517
  for (auto& v : variable_names_matmul) {
518 519 520 521
    prog.MutableBlock(0)->Var(v);
  }
  SetOp(&prog, "dropout", "Dropout", {"a"}, {"b"}, false);
  SetOp(&prog, "dequantize", "Dequantize", {"c"}, {"d"}, true);
522 523
  SetOp(&prog, "matmul", "Matmul", {"b", "d"}, {"e"}, true, "int8");
  SetOp(&prog, "dropout", "Dropout", {"e"}, {"f"}, true, "float32");
524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542

  return prog;
}

void MainTestMatmul(const ProgramDesc& prog, int matmul_count, int quant_count,
                    int dequant_count, int added_nodes_count, float scale) {
  std::unique_ptr<ir::Graph> graph(new ir::Graph(prog));
  int original_nodes_num, current_nodes_num;
  PreparePass(&graph, prog, variable_names_matmul, &original_nodes_num,
              &current_nodes_num);

  int quantize_nodes_count = 0;
  int dequantize_nodes_count = 0;
  int matmul_nodes_count = 0;
  for (auto* node : graph->Nodes()) {
    if (node->IsOp()) {
      auto* op = node->Op();
      if (op->Type() == "matmul") {
        matmul_nodes_count++;
543 544
        auto op_name = BOOST_GET_CONST(std::string, op->GetAttr("name"));
        EXPECT_EQ(BOOST_GET_CONST(float, op->GetAttr("Scale_x")), scale)
545
            << "Scale_x for node '" + op_name + "'.";
546
        EXPECT_EQ(BOOST_GET_CONST(float, op->GetAttr("Scale_y")), scale)
547
            << "Scale_y for node '" + op_name + "'.";
548
        EXPECT_EQ(BOOST_GET_CONST(float, op->GetAttr("Scale_out")), scale)
549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581
            << "Scale_out for node '" + op_name + "'.";
      } else if (op->Type() == "quantize") {
        quantize_nodes_count++;
      } else if (op->Type() == "dequantize") {
        dequantize_nodes_count++;
      }
    }
  }
  EXPECT_EQ(matmul_nodes_count, matmul_count);
  EXPECT_EQ(quantize_nodes_count, quant_count);
  EXPECT_EQ(dequantize_nodes_count, dequant_count);
  EXPECT_EQ(original_nodes_num + added_nodes_count, current_nodes_num);
}

TEST(CpuQuantizePass, matmul) {
  int matmul_count = 1;
  int quant_count = 2;
  int dequant_count = 3;
  // 2 Quant + 2 IN + 1 DeQuant + 1 OUT
  int added_nodes_count = 6;
  MainTestMatmul(BuildProgramDescMatmul(), matmul_count, quant_count,
                 dequant_count, added_nodes_count, 2.0f * 127);
}

TEST(CpuQuantizePass, matmul_not_quantized) {
  int matmul_count = 1;
  int quant_count = 0;
  int dequant_count = 1;
  // nothing change
  int added_nodes_count = 0;
  MainTestMatmul(BuildProgramDescMatmulNotQuantized(), matmul_count,
                 quant_count, dequant_count, added_nodes_count, 1.0f);
}
582 583 584 585 586 587 588 589 590 591 592 593

static const std::initializer_list<std::string> variable_names_elementwise_add =
    {"a", "b", "c", "d", "e", "f"};

ProgramDesc BuildProgramDescElementwiseAdd() {
  ProgramDesc prog;
  for (auto& v : variable_names_elementwise_add) {
    prog.MutableBlock(0)->Var(v);
  }
  SetOp(&prog, "dequantize", "Dequantize1", {"a"}, {"b"}, true);
  SetOp(&prog, "dequantize", "Dequantize2", {"c"}, {"d"}, true);
  SetOp(&prog, "elementwise_add", "ElementwiseAdd", {"b", "d"}, {"e"}, true,
594 595
        "int8");
  SetOp(&prog, "dropout", "Dropout", {"e"}, {"f"}, true, "float32");
596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672

  return prog;
}

void MainTestElementwiseAdd(const ProgramDesc& prog, int elementwise_add_count,
                            int quant_count, int dequant_count,
                            int added_nodes_count, float scale,
                            bool output_scale_missing = false,
                            bool unsigned_and_signed_input = false) {
  std::unique_ptr<ir::Graph> graph(new ir::Graph(prog));
  int original_nodes_num, current_nodes_num;
  PreparePass(&graph, prog, variable_names_elementwise_add, &original_nodes_num,
              &current_nodes_num, output_scale_missing ? "e" : "",
              unsigned_and_signed_input ? "b" : "");

  int quantize_nodes_count = 0;
  int dequantize_nodes_count = 0;
  int elementwise_add_nodes_count = 0;
  for (auto* node : graph->Nodes()) {
    if (node->IsOp()) {
      auto* op = node->Op();
      if (op->Type() == "elementwise_add") {
        elementwise_add_nodes_count++;
        if (unsigned_and_signed_input) scale = 1.0f;
        auto op_name = BOOST_GET_CONST(std::string, op->GetAttr("name"));
        EXPECT_EQ(BOOST_GET_CONST(float, op->GetAttr("Scale_x")), scale)
            << "Scale_x for node '" + op_name + "'.";
        EXPECT_EQ(BOOST_GET_CONST(float, op->GetAttr("Scale_y")), scale)
            << "Scale_y for node '" + op_name + "'.";
        if (output_scale_missing) scale = 1.0;
        EXPECT_EQ(BOOST_GET_CONST(float, op->GetAttr("Scale_out")), scale)
            << "Scale_out for node '" + op_name + "'.";
      } else if (op->Type() == "quantize") {
        quantize_nodes_count++;
      } else if (op->Type() == "dequantize") {
        dequantize_nodes_count++;
      }
    }
  }
  EXPECT_EQ(elementwise_add_nodes_count, elementwise_add_count);
  EXPECT_EQ(quantize_nodes_count, quant_count);
  EXPECT_EQ(dequantize_nodes_count, dequant_count);
  EXPECT_EQ(original_nodes_num + added_nodes_count, current_nodes_num);
}

TEST(CpuQuantizePass, elementwise_add) {
  int elementwise_add_count = 1;
  int quant_count = 2;
  int dequant_count = 3;
  // 2 Quant + 2 IN + 1 DeQuant + 1 OUT
  int added_nodes_count = 6;
  MainTestElementwiseAdd(BuildProgramDescElementwiseAdd(),
                         elementwise_add_count, quant_count, dequant_count,
                         added_nodes_count, 2.0f * 127);
}

TEST(CpuQuantizePass, elementwise_add_output_scale_missing) {
  int elementwise_add_count = 1;
  int quant_count = 2;
  int dequant_count = 2;
  // 2 Quant + 2 IN
  int added_nodes_count = 4;
  MainTestElementwiseAdd(BuildProgramDescElementwiseAdd(),
                         elementwise_add_count, quant_count, dequant_count,
                         added_nodes_count, 2.0f * 127, true);
}

TEST(CpuQuantizePass, elementwise_add_unsigned_and_signed_input) {
  int elementwise_add_count = 1;
  int quant_count = 0;
  int dequant_count = 2;
  int added_nodes_count = 0;
  MainTestElementwiseAdd(BuildProgramDescElementwiseAdd(),
                         elementwise_add_count, quant_count, dequant_count,
                         added_nodes_count, 2.0f * 127, false, true);
}

673
}  // namespace
674

675 676 677 678 679
}  // namespace ir
}  // namespace framework
}  // namespace paddle

USE_PASS(cpu_quantize_pass);