test_LayerGrad.cpp 80.4 KB
Newer Older
1
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.
Z
zhangjinchao01 已提交
2 3 4 5 6 7 8 9 10 11 12 13 14

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
#ifdef PADDLE_WITH_CUDA
16
#include <cudnn.h>
W
wanghaoshuang 已提交
17
#endif
Z
zhangjinchao01 已提交
18 19
#include <gtest/gtest.h>
#include <string>
Q
qijun 已提交
20
#include <vector>
Z
zhangjinchao01 已提交
21
#include "ModelConfig.pb.h"
X
Xin Pan 已提交
22
#include "paddle/legacy/gserver/layers/DataLayer.h"
23
#include "paddle/math/MathUtils.h"
Z
zhangjinchao01 已提交
24 25

#include "LayerGradUtil.h"
26
#include "paddle/testing/TestUtil.h"
Z
zhangjinchao01 已提交
27 28 29 30

using namespace paddle;  // NOLINT
using namespace std;     // NOLINT

31 32 33 34 35
DECLARE_bool(use_gpu);
DECLARE_int32(gpu_id);
DECLARE_double(checkgrad_eps);
DECLARE_bool(thread_local_rand_use_global_seed);
DECLARE_bool(prev_batch_state);
Z
zhangjinchao01 已提交
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55

TEST(Operator, dot_mul) {
  TestConfig config;
  config.layerConfig.set_size(10);

  config.inputDefs.push_back({INPUT_DATA, "layer_0", 10, 0});
  config.inputDefs.push_back({INPUT_DATA, "layer_1", 10, 0});
  config.layerConfig.add_inputs();
  config.layerConfig.add_inputs();

  OperatorConfig& operatorConf = *config.layerConfig.add_operator_confs();
  operatorConf.set_type("dot_mul");
  operatorConf.set_dotmul_scale(-1);

  testOperatorGrad(config, operatorConf, 100, false, false);
}

TEST(Projection, context) {
  for (auto contextStart : {-5, -3, -1, 0, 3}) {
    for (auto contextLength : {1, 2, 5, 7}) {
56
      for (auto batchSize : {1, 2, 5, 20}) {
Z
zhangjinchao01 已提交
57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
        for (auto trainablePadding : {false, true}) {
          LOG(INFO) << " contextStart=" << contextStart
                    << " contextLength=" << contextLength
                    << " batchSize=" << batchSize
                    << " trainablePadding=" << trainablePadding;
          ProjectionConfig conf;
          conf.set_type("context");
          conf.set_input_size(10);
          conf.set_context_start(contextStart);
          conf.set_context_length(contextLength);
          conf.set_trainable_padding(trainablePadding);
          conf.set_output_size(conf.context_length() * conf.input_size());
          int pad =
              std::max(0, -conf.context_start()) +
              std::max(0, conf.context_start() + conf.context_length() - 1);
          for (auto useGpu : {false, true}) {
            testProjectionGrad(
74 75 76 77
                conf,
                INPUT_SEQUENCE_DATA,
                trainablePadding ? conf.input_size() * pad : 0,
                batchSize,
Z
zhangjinchao01 已提交
78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
                useGpu,
                contextStart + contextLength <= 1);  // = testState
          }
        }
      }
    }
  }
}

TEST(Projection, trans_fc) {
  ProjectionConfig conf;
  conf.set_type("trans_fc");
  conf.set_input_size(50);
  conf.set_output_size(20);
  for (auto useGpu : {false, true}) {
93 94 95 96 97
    testProjectionGrad(conf,
                       INPUT_DATA,
                       /* parameterSize */ 1000,
                       /* batchSize */ 100,
                       useGpu);
Z
zhangjinchao01 已提交
98 99 100 101 102 103 104 105 106
  }
}

TEST(Projection, fc) {
  ProjectionConfig conf;
  conf.set_type("fc");
  conf.set_input_size(10);
  conf.set_output_size(20);
  for (auto useGpu : {false, true}) {
107 108 109 110 111
    testProjectionGrad(conf,
                       INPUT_DATA,
                       /* parameterSize */ 200,
                       /* batchSize */ 100,
                       useGpu);
Z
zhangjinchao01 已提交
112 113 114 115 116 117 118 119 120
  }
}

TEST(Projection, dot_mul) {
  ProjectionConfig conf;
  conf.set_type("dot_mul");
  conf.set_input_size(20);
  conf.set_output_size(20);
  for (auto useGpu : {false, true}) {
121 122 123 124 125
    testProjectionGrad(conf,
                       INPUT_DATA,
                       /* parameterSize */ 20,
                       /* batchSize */ 100,
                       useGpu);
Z
zhangjinchao01 已提交
126 127 128 129 130 131 132 133 134
  }
}

TEST(Projection, table) {
  ProjectionConfig conf;
  conf.set_type("table");
  conf.set_input_size(10);
  conf.set_output_size(20);
  for (auto useGpu : {false, true}) {
135 136 137 138 139
    testProjectionGrad(conf,
                       INPUT_LABEL,
                       /* parameterSize */ 200,
                       /* batchSize */ 100,
                       useGpu);
Z
zhangjinchao01 已提交
140 141 142 143 144 145 146 147 148
  }
}

TEST(Projection, identity) {
  ProjectionConfig conf;
  conf.set_type("identity");
  conf.set_input_size(10);
  conf.set_output_size(10);
  for (auto useGpu : {false, true}) {
149 150 151 152 153
    testProjectionGrad(conf,
                       INPUT_DATA,
                       /* parameterSize */ 0,
                       /* batchSize */ 100,
                       useGpu);
Z
zhangjinchao01 已提交
154 155 156
  }
}

157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176
TEST(Projection, slice) {
  ProjectionConfig conf;
  conf.set_type("slice");
  conf.set_input_size(100);
  SliceConfig& slice1 = *conf.add_slices();
  slice1.set_start(10);
  slice1.set_end(20);
  SliceConfig& slice2 = *conf.add_slices();
  slice2.set_start(50);
  slice2.set_end(70);
  conf.set_output_size(30);
  for (auto useGpu : {false, true}) {
    testProjectionGrad(conf,
                       INPUT_DATA,
                       /* parameterSize */ 0,
                       /* batchSize */ 10,
                       useGpu);
  }
}

X
xuwei06 已提交
177 178 179 180 181 182
TEST(Projection, scaling) {
  ProjectionConfig conf;
  conf.set_type("scaling");
  conf.set_input_size(10);
  conf.set_output_size(10);
  for (auto useGpu : {false}) {
183 184 185 186 187
    testProjectionGrad(conf,
                       INPUT_DATA,
                       /* parameterSize */ 1,
                       /* batchSize */ 100,
                       useGpu);
X
xuwei06 已提交
188 189 190
  }
}

W
wangyang59 已提交
191
void testProjectionConv(size_t groups, bool isDeconv) {
192
  const int NUM_FILTERS = 18;
193
  const int FILTER_SIZE = 2;
194
  const int FILTER_SIZE_Y = 2;
195 196 197
  const int CHANNELS = 3;
  const int IMAGE_SIZE = 16;

198 199 200 201 202 203
#if CUDNN_VERSION >= 6000
  const int DILATION = 2;
#else
  const int DILATION = 1;
#endif

204
  ProjectionConfig conf;
W
wangyang59 已提交
205 206 207 208 209
  if (isDeconv) {
    conf.set_type("convt");
  } else {
    conf.set_type("conv");
  }
210 211 212 213 214 215 216 217 218 219
  conf.set_num_filters(NUM_FILTERS);

  ConvConfig* conv = conf.mutable_conv_conf();
  conv->set_filter_size(FILTER_SIZE);
  conv->set_filter_size_y(FILTER_SIZE_Y);
  conv->set_channels(CHANNELS);
  conv->set_padding(0);
  conv->set_padding_y(1);
  conv->set_stride(2);
  conv->set_stride_y(2);
220 221
  conv->set_dilation(DILATION);
  conv->set_dilation_y(DILATION);
222
  conv->set_groups(groups);
W
wangyang59 已提交
223 224 225 226 227
  if (isDeconv) {
    conv->set_filter_channels(NUM_FILTERS / conv->groups());
  } else {
    conv->set_filter_channels(conv->channels() / conv->groups());
  }
228
  conv->set_img_size(IMAGE_SIZE);
229
  int output_x = outputSize(conv->img_size(),
230
                            (conv->filter_size() - 1) * DILATION + 1,
231 232 233 234
                            conv->padding(),
                            conv->stride(),
                            /* caffeMode */ true);
  int output_y = outputSize(conv->img_size(),
235
                            (conv->filter_size_y() - 1) * DILATION + 1,
236 237 238
                            conv->padding_y(),
                            conv->stride_y(),
                            /* caffeMode */ true);
239
  conv->set_output_x(output_x);
W
wangyang59 已提交
240
  conv->set_output_y(output_y);
W
wanghaoshuang 已提交
241 242
  LOG(INFO) << "DILATION:" << DILATION << "; output_x: " << output_x
            << "; output_y: " << output_y;
W
wangyang59 已提交
243
  if (isDeconv) {
W
wanghaoshuang 已提交
244 245 246 247 248 249 250 251 252 253 254 255 256
    int deconv_image_x = imageSize(output_x,
                                   (conv->filter_size() - 1) * DILATION + 1,
                                   conv->padding(),
                                   conv->stride(),
                                   /* caffeMode */ true);
    int deconv_image_y = imageSize(output_y,
                                   (conv->filter_size_y() - 1) * DILATION + 1,
                                   conv->padding_y(),
                                   conv->stride_y(),
                                   /* caffeMode */ true);

    LOG(INFO) << " deconv_image_x: " << deconv_image_x
              << "; deconv_image_y: " << deconv_image_y;
W
wangyang59 已提交
257
    conf.set_input_size(output_x * output_y * CHANNELS);
W
wanghaoshuang 已提交
258
    conf.set_output_size(deconv_image_x * deconv_image_y * NUM_FILTERS);
W
wangyang59 已提交
259 260 261 262
  } else {
    conf.set_input_size(IMAGE_SIZE * IMAGE_SIZE * CHANNELS);
    conf.set_output_size(output_x * output_y * NUM_FILTERS);
  }
263

L
Luo Tao 已提交
264 265 266 267 268 269 270 271 272
  testProjectionGrad(conf,
                     INPUT_DATA,
                     /* parameterSize */ NUM_FILTERS * CHANNELS * FILTER_SIZE *
                         FILTER_SIZE_Y / groups,
                     /* batchSize */ 100,
                     true,
                     false,
                     NUM_FILTERS,
                     true);
273
}
274

275
#ifdef PADDLE_WITH_CUDA
276
TEST(Projection, conv) {
W
wangyang59 已提交
277 278 279 280 281 282
  /// test ConvProjection
  testProjectionConv(1, false);
  testProjectionConv(3, false);
  /// test ConvTransProjection
  testProjectionConv(1, true);
  testProjectionConv(3, true);
283
}
284 285
#endif

L
Update  
liaogang 已提交
286 287 288 289 290 291
TEST(Layer, BilinearInterpLayer) {
  TestConfig config;
  config.layerConfig.set_type("bilinear_interp");
  config.biasSize = 0;
  config.inputDefs.push_back({INPUT_DATA, "layer_0", 4096, 0});

L
liaogang 已提交
292 293
  LayerInputConfig* input = config.layerConfig.add_inputs();
  BilinearInterpConfig* bilinear = input->mutable_bilinear_interp_conf();
L
Luo Tao 已提交
294 295 296 297
  ImageConfig* image = bilinear->mutable_image_conf();
  image->set_img_size(32);
  image->set_img_size_y(32);
  image->set_channels(4);
L
liaogang 已提交
298

L
liaogang 已提交
299 300 301 302 303 304 305
  for (auto useGpu : {false, true}) {
    for (auto outSize : {32, 64}) {
      bilinear->set_out_size_x(outSize);
      bilinear->set_out_size_y(outSize);
      testLayerGrad(config, "bilinear_interp", 10, false, useGpu);
    }
  }
L
Update  
liaogang 已提交
306 307
}

Z
zhangjinchao01 已提交
308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354
TEST(Layer, concat) {
  TestConfig config;
  config.biasSize = 0;
  config.layerConfig.set_type("concat");
  config.layerConfig.set_size(15);
  config.layerConfig.set_active_type("sigmoid");

  config.inputDefs.push_back({INPUT_DATA, "layer_0", 5, 0});
  config.layerConfig.add_inputs();
  config.inputDefs.push_back({INPUT_DATA, "layer_1", 10, 0});
  config.layerConfig.add_inputs();

  for (auto useGpu : {false, true}) {
    testLayerGrad(config, "concat", 100, false, useGpu);
  }
}

TEST(Layer, AddtoLayer) {
  TestConfig config;
  config.biasSize = 0;
  config.layerConfig.set_type("addto");
  config.layerConfig.set_size(10);
  config.layerConfig.set_active_type("sigmoid");

  config.inputDefs.push_back({INPUT_DATA, "layer_0", 10, 0});
  config.layerConfig.add_inputs();
  config.inputDefs.push_back({INPUT_DATA, "layer_1", 10, 0});
  config.layerConfig.add_inputs();

  for (auto useGpu : {false, true}) {
    testLayerGrad(config, "addto", 100, false, useGpu);
  }
}

TEST(Layer, CTCLayer) {
  TestConfig config;
  config.layerConfig.set_type("ctc");
  config.layerConfig.set_norm_by_times(false);
  config.layerConfig.set_size(10);
  config.biasSize = 0;

  config.inputDefs.push_back({INPUT_SEQUENCE_DATA, "layer_0", 10, 0});
  config.inputDefs.push_back({INPUT_SEQUENCE_LABEL, "layer_1", 10, 0});
  config.layerConfig.add_inputs();
  config.layerConfig.add_inputs();

  for (auto useGpu : {false, true}) {
355 356 357 358 359
    testLayerGrad(config,
                  "ctc",
                  100,
                  /* trans */ false, /* useGpu */
                  useGpu);
Z
zhangjinchao01 已提交
360 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 387 388 389 390 391 392 393 394
  }
}

TEST(Layer, cosSimLayer) {
  TestConfig config;
  config.layerConfig.set_type("cos");
  config.layerConfig.set_size(1);
  config.biasSize = 0;

  config.inputDefs.push_back({INPUT_DATA, "layer_0", 50, 0});
  config.inputDefs.push_back({INPUT_DATA, "layer_1", 50, 0});
  config.layerConfig.add_inputs();
  config.layerConfig.add_inputs();

  for (auto useGpu : {false, true}) {
    testLayerGrad(config, "cos", 100, false, useGpu);
  }
}

TEST(Layer, CosSimVecMatLayer) {
  TestConfig config;
  config.layerConfig.set_type("cos_vm");
  config.layerConfig.set_size(5);  // output size
  config.layerConfig.set_cos_scale(2.0);

  config.inputDefs.push_back({INPUT_DATA, "layer_0", 20, 0});
  config.layerConfig.add_inputs();
  config.inputDefs.push_back({INPUT_DATA, "layer_1", 100, 0});
  config.layerConfig.add_inputs();

  for (auto useGpu : {false, true}) {
    testLayerGrad(config, "cos_vm", 100, false, useGpu);
  }
}

395 396 397 398 399 400 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 427 428 429 430 431 432 433 434 435 436 437 438
void testDepthwiseConvLayer(const string& type, bool useGpu) {
  TestConfig config;
  config.biasSize = 32;
  config.layerConfig.set_type(type);
  config.layerConfig.set_num_filters(32);
  config.layerConfig.set_partial_sum(1);
  config.layerConfig.set_shared_biases(true);

  config.inputDefs.push_back({INPUT_DATA, "layer_0", 2048, 192});
  LayerInputConfig* input = config.layerConfig.add_inputs();
  ConvConfig* conv = input->mutable_conv_conf();
  conv->set_filter_size(2);
  conv->set_filter_size_y(3);
  conv->set_channels(16);
  conv->set_padding(0);
  conv->set_padding_y(1);
  conv->set_stride(2);
  conv->set_stride_y(2);
  conv->set_groups(16);
  conv->set_filter_channels(conv->channels() / conv->groups());
  conv->set_img_size(16);
  conv->set_img_size_y(8);
  conv->set_output_x(outputSize(conv->img_size(),
                                conv->filter_size(),
                                conv->padding(),
                                conv->stride(),
                                /* caffeMode */ true));
  conv->set_output_y(outputSize(conv->img_size_y(),
                                conv->filter_size_y(),
                                conv->padding_y(),
                                conv->stride_y(),
                                /* caffeMode */ true));
  config.layerConfig.set_size(conv->output_x() * conv->output_y() *
                              config.layerConfig.num_filters());

  testLayerGrad(config, "depthwise_conv", 100, false, useGpu);
  // Use small batch_size and useWeight=true to test biasGrad
  testLayerGrad(config, "depthwise_conv", 2, false, useGpu, true, 0.02);
}

TEST(Layer, depthwiseConvLayer) {
  //  'depthwise_conv' is a sepecial case of 'exconv' whose
  //  groups size equals to the input channels size.
  testDepthwiseConvLayer("exconv", /* useGpu= */ false);
439
#ifdef PADDLE_WITH_CUDA
440 441 442 443
  testDepthwiseConvLayer("exconv", /* useGpu= */ true);
#endif
}

Z
zhangjinchao01 已提交
444 445 446 447 448 449 450 451
void testConvLayer(const string& type, bool trans, bool useGpu) {
  TestConfig config;
  config.biasSize = 16;
  config.layerConfig.set_type(type);
  config.layerConfig.set_num_filters(16);
  config.layerConfig.set_partial_sum(1);
  config.layerConfig.set_shared_biases(true);

X
xzl 已提交
452
  int dilation = 2;
453 454 455 456 457 458 459 460 461
  if (type == "cudnn_conv") {
#if CUDNN_VERSION >= 6000
    dilation = 2;
#else
    dilation = 1;
#endif
  }

  config.inputDefs.push_back({INPUT_DATA, "layer_0", 768, 192});
Z
zhangjinchao01 已提交
462 463 464
  LayerInputConfig* input = config.layerConfig.add_inputs();
  ConvConfig* conv = input->mutable_conv_conf();
  conv->set_filter_size(2);
465
  conv->set_filter_size_y(2);
Z
zhangjinchao01 已提交
466 467 468 469 470
  conv->set_channels(3);
  conv->set_padding(0);
  conv->set_padding_y(1);
  conv->set_stride(2);
  conv->set_stride_y(2);
471 472
  conv->set_dilation(dilation);
  conv->set_dilation_y(dilation);
Z
zhangjinchao01 已提交
473 474 475
  conv->set_groups(1);
  conv->set_filter_channels(conv->channels() / conv->groups());
  conv->set_img_size(16);
476
  conv->set_img_size_y(16);
477
  conv->set_output_x(outputSize(conv->img_size(),
478
                                (conv->filter_size() - 1) * dilation + 1,
479 480
                                conv->padding(),
                                conv->stride(),
481
                                /* caffeMode */ true));
L
Luo Tao 已提交
482
  conv->set_output_y(outputSize(conv->img_size_y(),
483
                                (conv->filter_size_y() - 1) * dilation + 1,
L
Luo Tao 已提交
484 485
                                conv->padding_y(),
                                conv->stride_y(),
L
Luo Tao 已提交
486 487
                                /* caffeMode */ true));
  config.layerConfig.set_size(conv->output_x() * conv->output_y() *
Z
zhangjinchao01 已提交
488 489 490
                              config.layerConfig.num_filters());

  testLayerGrad(config, "conv", 100, trans, useGpu);
491 492
  // Use small batch_size and useWeight=true to test biasGrad
  testLayerGrad(config, "conv", 2, trans, useGpu, true, 0.02);
Z
zhangjinchao01 已提交
493 494 495 496
}

TEST(Layer, convLayer) {
  testConvLayer("exconv", /* trans= */ false, /* useGpu= */ false);
497
#ifdef PADDLE_WITH_CUDA
Z
zhangjinchao01 已提交
498 499 500 501 502
  testConvLayer("exconv", /* trans= */ false, /* useGpu= */ true);
  testConvLayer("cudnn_conv", /* trans= */ false, /* useGpu= */ true);
#endif
}

W
wangyang59 已提交
503 504 505 506 507 508 509 510
void testConvTransLayer(const string& type, bool trans, bool useGpu) {
  TestConfig config;
  config.biasSize = 3;
  config.layerConfig.set_type(type);
  config.layerConfig.set_num_filters(3);
  config.layerConfig.set_partial_sum(1);
  config.layerConfig.set_shared_biases(true);

W
wangyang59 已提交
511
  config.inputDefs.push_back({INPUT_DATA, "layer_0", 1024, 384});
W
wangyang59 已提交
512 513 514
  LayerInputConfig* input = config.layerConfig.add_inputs();
  ConvConfig* conv = input->mutable_conv_conf();
  conv->set_filter_size(2);
W
wangyang59 已提交
515
  conv->set_filter_size_y(4);
W
wangyang59 已提交
516 517 518 519 520 521 522 523
  conv->set_channels(16);
  conv->set_padding(0);
  conv->set_padding_y(1);
  conv->set_stride(2);
  conv->set_stride_y(2);
  conv->set_groups(1);
  conv->set_filter_channels(3 / conv->groups());
  conv->set_img_size(16);
524 525 526 527
  conv->set_output_x(outputSize(conv->img_size(),
                                conv->filter_size(),
                                conv->padding(),
                                conv->stride(),
528
                                /* caffeMode */ true));
W
wangyang59 已提交
529 530 531 532 533

  config.layerConfig.set_size(conv->img_size() * conv->img_size() *
                              config.layerConfig.num_filters());

  testLayerGrad(config, "convTrans", 100, trans, useGpu);
534 535
  // Use small batch_size and useWeight=true to test biasGrad
  testLayerGrad(config, "convTrans", 2, trans, useGpu, true, 0.02);
W
wangyang59 已提交
536 537 538
}

TEST(Layer, convTransLayer) {
539 540 541
  for (auto useGpu : {false, true}) {
    testConvTransLayer("exconvt", /* trans= */ false, /* useGpu= */ useGpu);
  }
542
#ifdef PADDLE_WITH_CUDA
W
wangyang59 已提交
543 544
  testConvTransLayer("cudnn_convt", /* trans= */ false, /* useGpu= */ true);
#endif
W
wangyang59 已提交
545 546
}

Z
zhangjinchao01 已提交
547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563
TEST(Layer, blockExpandLayer) {
  TestConfig config;
  config.biasSize = 0;
  config.layerConfig.set_type("blockexpand");

  config.inputDefs.push_back({INPUT_DATA, "layer_0", 6144, 0});
  LayerInputConfig* input = config.layerConfig.add_inputs();
  BlockExpandConfig* blockExpand = input->mutable_block_expand_conf();
  blockExpand->set_img_size_x(64);
  blockExpand->set_img_size_y(32);
  blockExpand->set_channels(3);
  blockExpand->set_padding_x(0);
  blockExpand->set_padding_y(0);
  blockExpand->set_block_x(4);
  blockExpand->set_block_y(32);
  blockExpand->set_stride_x(2);
  blockExpand->set_stride_y(2);
564 565 566 567 568 569 570 571 572 573
  blockExpand->set_output_x(outputSize(blockExpand->img_size_x(),
                                       blockExpand->block_x(),
                                       blockExpand->padding_x(),
                                       blockExpand->stride_x(),
                                       /* caffeMode */ false));
  blockExpand->set_output_y(outputSize(blockExpand->img_size_y(),
                                       blockExpand->block_y(),
                                       blockExpand->padding_y(),
                                       blockExpand->stride_y(),
                                       /* caffeMode */ false));
Z
zhangjinchao01 已提交
574 575 576 577 578 579 580 581
  config.layerConfig.set_size(blockExpand->block_x() * blockExpand->block_y() *
                              blockExpand->channels());

  for (auto useGpu : {false, true}) {
    testLayerGrad(config, "blockexpand", 100, false, useGpu);
  }
}

582 583 584 585 586 587 588 589
TEST(Layer, maxoutLayer) {
  TestConfig config;
  config.biasSize = 0;
  config.layerConfig.set_type("maxout");

  config.inputDefs.push_back({INPUT_DATA, "layer_0", 4096, 0});
  LayerInputConfig* input = config.layerConfig.add_inputs();
  MaxOutConfig* maxout = input->mutable_maxout_conf();
L
Luo Tao 已提交
590
  ImageConfig* image = maxout->mutable_image_conf();
591

L
Luo Tao 已提交
592 593 594
  image->set_img_size(32);
  image->set_img_size_y(32);
  image->set_channels(4);
595 596 597 598 599 600
  maxout->set_groups(2);

  for (auto useGpu : {false, true}) {
    testLayerGrad(config, "maxout", 10, false, useGpu);
  }
}
C
caoying03 已提交
601

Z
zhangjinchao01 已提交
602 603
void testFcLayer(string format, size_t nnz) {
  TestConfig config;
604
  config.biasSize = 1024;
Z
zhangjinchao01 已提交
605
  config.layerConfig.set_type("fc");
606
  config.layerConfig.set_size(1024);
Z
zhangjinchao01 已提交
607 608 609 610
  config.layerConfig.set_active_type("sigmoid");
  config.layerConfig.set_drop_rate(0.1);

  config.inputDefs.push_back(
611
      {INPUT_DATA, "layer_0", 2048, nnz, ParaSparse(format)});
Z
zhangjinchao01 已提交
612 613 614 615 616 617
  config.layerConfig.add_inputs();

  LOG(INFO) << config.inputDefs[0].sparse.sparse << " "
            << config.inputDefs[0].sparse.format;

  for (auto useGpu : {false, true}) {
618 619 620 621 622
    testLayerGrad(config,
                  "fc",
                  100,
                  /* trans */ false,
                  useGpu,
Z
zhangjinchao01 已提交
623 624 625 626 627
                  /* weight */ true);
  }
}

TEST(Layer, fcLayer) {
628 629 630
  testFcLayer("", 1024 * 1024 * 2);
  testFcLayer("csc", 1024 * 10);
  testFcLayer("csr", 1024 * 10);
Z
zhangjinchao01 已提交
631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649
}

TEST(Layer, SelectiveFullyConnectedLayer) {
  TestConfig config;
  size_t nin = 16;
  size_t nout = 256;
  config.layerConfig.set_type("selective_fc");
  config.layerConfig.set_size(nout);
  config.layerConfig.set_active_type("sigmoid");
  config.layerConfig.set_has_selected_colums(true);
  config.layerConfig.set_selective_fc_pass_generation(false);
  config.biasSize = nout;

  config.inputDefs.push_back({INPUT_DATA, "input0", nin, nin * nout});
  config.layerConfig.add_inputs();
  config.inputDefs.push_back(
      {INPUT_SPARSE_NON_VALUE_DATA, "index", nout, 0, ParaSparse("csr", true)});
  config.layerConfig.add_inputs();

650 651 652 653 654 655
  testLayerGrad(config,
                "selective_fc",
                100,
                /* trans= */ false,
                /* useGup= */ false,
                false);
656
#ifdef PADDLE_WITH_CUDA
657 658 659 660 661 662
  testLayerGrad(config,
                "selective_fc",
                100,
                /* trans= */ false,
                /* useGup= */ true,
                false);
Z
zhangjinchao01 已提交
663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678
#endif
}

TEST(Layer, DataNormLayer) {
  TestConfig config;
  config.layerConfig.set_type("data_norm");
  config.layerConfig.set_size(20);
  config.biasSize = 0;

  config.inputDefs.push_back({INPUT_DATA, "layer_0", 20, 100});
  config.inputDefs.back().isStatic = true;
  config.layerConfig.add_inputs();

  for (auto strategy : {"z-score", "min-max", "decimal-scaling"}) {
    config.layerConfig.set_data_norm_strategy(strategy);
    // The parameters are static, so not support GPU now
679 680 681 682
    testLayerGrad(config,
                  "data_norm",
                  200,
                  /* trans */ false,
Z
zhangjinchao01 已提交
683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698
                  /* useGpu */ false);
  }
}

TEST(Layer, hsigmoidLayer) {
  TestConfig config;
  config.layerConfig.set_type("hsigmoid");
  config.layerConfig.set_num_classes(5);
  config.layerConfig.set_size(1);
  config.biasSize = config.layerConfig.num_classes() - 1;

  config.inputDefs.push_back({INPUT_DATA, "layer_0", 50, 200});
  config.inputDefs.push_back({INPUT_LABEL, "layer_1", 5, 0});
  config.layerConfig.add_inputs();
  config.layerConfig.add_inputs();

P
peterzhang2029 已提交
699 700 701 702
  for (auto useGpu : {false, true}) {
    testLayerGrad(config,
                  "hsigmoid",
                  100,
P
--amend  
peterzhang2029 已提交
703 704
                  /* trans */ false,
                  /* useGpu */ useGpu);
P
peterzhang2029 已提交
705
  }
Z
zhangjinchao01 已提交
706 707 708 709 710 711 712 713 714 715 716 717 718
}

TEST(Layer, multi_cross) {
  TestConfig config;
  config.layerConfig.set_type("multi-class-cross-entropy");
  config.biasSize = 0;

  config.inputDefs.push_back({INPUT_DATA, "layer_0", 50, 0});
  config.inputDefs.push_back({INPUT_LABEL, "layer_1", 10, 0});
  config.layerConfig.add_inputs();
  config.layerConfig.add_inputs();

  for (auto useGpu : {false, true}) {
719 720
    testLayerGrad(
        config, "multi-class-cross-entropy", 100, /* trans */ false, useGpu);
Z
zhangjinchao01 已提交
721 722 723
  }
}

H
Haonan 已提交
724
TEST(Layer, multi_binary_label_sparse_mat) {
Z
zhangjinchao01 已提交
725 726 727 728 729 730 731 732 733
  TestConfig config;
  config.layerConfig.set_type("multi_binary_label_cross_entropy");
  config.biasSize = 0;

  config.inputDefs.push_back({INPUT_DATA, "layer_0", 50, 0});
  config.inputDefs.push_back({INPUT_SPARSE_NON_VALUE_DATA, "layer_1", 50, 0});
  config.layerConfig.add_inputs();
  config.layerConfig.add_inputs();

734
  for (auto useGpu : {false, true}) {
735 736 737 738 739
    testLayerGrad(config,
                  "multi_binary_label_cross_entropy",
                  100,
                  /* trans */ false,
                  useGpu);
740
  }
Z
zhangjinchao01 已提交
741 742
}

H
Haonan 已提交
743 744 745 746 747 748 749 750 751 752 753
TEST(layer, multi_binary_label_id) {
  TestConfig config;
  config.layerConfig.set_type("multi_binary_label_cross_entropy");
  config.biasSize = 0;

  config.inputDefs.push_back({INPUT_DATA, "layer_0", 50, 0});
  config.inputDefs.push_back({INPUT_LABEL, "layer_1", 10, 0});
  config.layerConfig.add_inputs();
  config.layerConfig.add_inputs();

  for (auto useGpu : {false, true}) {
754 755 756 757 758
    testLayerGrad(config,
                  "multi_binary_label_cross_entropy",
                  100,
                  /* trans */ false,
                  useGpu);
H
Haonan 已提交
759 760 761
  }
}

Z
zhangjinchao01 已提交
762 763 764 765 766 767 768 769 770 771 772 773
TEST(Layer, multi_cross_with_selfnorm) {
  TestConfig config;
  config.layerConfig.set_type("multi_class_cross_entropy_with_selfnorm");
  config.layerConfig.set_softmax_selfnorm_alpha(0.1);
  config.biasSize = 0;

  config.inputDefs.push_back({INPUT_DATA, "layer_0", 50, 0});
  config.inputDefs.push_back({INPUT_LABEL, "layer_1", 10, 0});
  config.layerConfig.add_inputs();
  config.layerConfig.add_inputs();

  // Not support GPU now
774 775 776
  testLayerGrad(config,
                "multi_class_cross_entropy_with_selfnorm",
                100,
Z
zhangjinchao01 已提交
777 778 779 780 781 782 783 784 785 786 787 788 789 790 791
                /* trans */ false,
                /* useGpu */ false);
}

TEST(Layer, multi_cross_soft) {
  TestConfig config;
  config.layerConfig.set_type("soft_binary_class_cross_entropy");
  config.biasSize = 0;

  config.inputDefs.push_back({INPUT_DATA, "layer_0", 10, 0});
  config.inputDefs.push_back({INPUT_DATA_TARGET, "layer_1", 10, 0});
  config.layerConfig.add_inputs();
  config.layerConfig.add_inputs();

  for (auto useGpu : {false, true}) {
792 793 794 795 796
    testLayerGrad(config,
                  "soft_binary_class_cross_entropy",
                  100,
                  /* trans */ false,
                  useGpu);
Z
zhangjinchao01 已提交
797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825
  }
}

TEST(Layer, square_error) {
  TestConfig config;
  config.layerConfig.set_type("square_error");
  config.biasSize = 0;

  config.inputDefs.push_back({INPUT_DATA, "layer_0", 10, 0});
  config.inputDefs.push_back({INPUT_DATA_TARGET, "layer_1", 10, 0});
  config.layerConfig.add_inputs();
  config.layerConfig.add_inputs();

  for (auto useGpu : {false, true}) {
    testLayerGrad(config, "square_error", 100, /* trans */ false, useGpu);
  }
}

TEST(Layer, sparse_square_error) {
  TestConfig config;
  config.layerConfig.set_type("square_error");
  config.biasSize = 0;

  config.inputDefs.push_back({INPUT_DATA, "layer_0", 50, 0});
  config.inputDefs.push_back({INPUT_SPARSE_NON_VALUE_DATA, "layer_1", 50, 0});
  config.layerConfig.add_inputs();
  config.layerConfig.add_inputs();

  // "GpuSparseMatrix" as label is not supported
826 827 828 829
  testLayerGrad(config,
                "square_error",
                100,
                /* trans */ false,
Z
zhangjinchao01 已提交
830 831 832 833 834 835 836 837 838 839 840 841 842 843
                /* useGpu */ false);
}

TEST(Layer, sparse_float_square_error) {
  TestConfig config;
  config.layerConfig.set_type("square_error");
  config.biasSize = 0;

  config.inputDefs.push_back({INPUT_DATA, "layer_0", 50, 0});
  config.inputDefs.push_back({INPUT_SPARSE_FLOAT_VALUE_DATA, "layer_1", 50, 0});
  config.layerConfig.add_inputs();
  config.layerConfig.add_inputs();

  // "GpuSparseMatrix" as label is not supported
844 845 846 847
  testLayerGrad(config,
                "square_error",
                100,
                /* trans */ false,
Z
zhangjinchao01 已提交
848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868
                /* useGpu */ false);
}

TEST(Layer, square_error_weighted) {
  TestConfig config;
  config.layerConfig.set_type("square_error");
  config.biasSize = 0;
  config.testAccumulate = false;

  config.inputDefs.push_back({INPUT_DATA, "layer_0", 10, 0});
  config.inputDefs.push_back({INPUT_DATA_TARGET, "layer_1", 10, 0});
  config.inputDefs.push_back({INPUT_DATA_TARGET, "layer_2", 1, 0});
  config.layerConfig.add_inputs();
  config.layerConfig.add_inputs();
  config.layerConfig.add_inputs();

  for (auto useGpu : {false, true}) {
    testLayerGrad(config, "square_error", 100, /* trans */ false, useGpu);
  }
}

L
Luo Tao 已提交
869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886
TEST(Layer, huber_regression_loss) {
  TestConfig config;
  config.layerConfig.set_type("huber_regression");
  config.biasSize = 0;

  config.inputDefs.push_back({INPUT_DATA, "layer_0", 10, 0});
  config.inputDefs.push_back({INPUT_DATA_TARGET, "layer_1", 10, 0});
  config.layerConfig.add_inputs();
  config.layerConfig.add_inputs();

  for (auto useGpu : {false, true}) {
    for (auto delta : {1, 3, 5}) {
      config.layerConfig.set_delta(delta);
      testLayerGrad(config, "huber_regression", 100, /* trans */ false, useGpu);
    }
  }
}

Z
zhangjinchao01 已提交
887 888
TEST(Layer, huber_two_class) {
  TestConfig config;
889
  config.layerConfig.set_type("huber_classification");
Z
zhangjinchao01 已提交
890 891 892 893 894 895 896 897
  config.biasSize = 0;

  config.inputDefs.push_back({INPUT_DATA, "layer_0", 1, 0});
  config.inputDefs.push_back({INPUT_LABEL, "layer_1", 2, 0});
  config.layerConfig.add_inputs();
  config.layerConfig.add_inputs();

  for (auto useGpu : {false, true}) {
L
Luo Tao 已提交
898
    testLayerGrad(config, "huber_two_class", 100, /* trans */ false, useGpu);
Z
zhangjinchao01 已提交
899 900 901 902 903 904 905 906 907
  }
}

void testExpandLayer(string trans_type, bool hasSubseq) {
  TestConfig config;
  config.layerConfig.set_type("expand");

  config.inputDefs.push_back(
      {trans_type == "non-seq" ? INPUT_DENSE_DIM_DATA : INPUT_SEQUENCE_DATA,
908 909 910
       "layer_0",
       10,
       0});
Z
zhangjinchao01 已提交
911
  config.inputDefs.push_back(
912 913 914 915
      {hasSubseq ? INPUT_HASSUB_SEQUENCE_DATA : INPUT_SEQUENCE_DATA,
       "layer_1",
       10,
       0});
Z
zhangjinchao01 已提交
916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931
  config.layerConfig.add_inputs();
  config.layerConfig.add_inputs();
  config.layerConfig.set_trans_type(trans_type);
  LOG(INFO) << " trans_type=" << trans_type << " hasSubseq=" << hasSubseq;

  for (auto useGpu : {false, true}) {
    testLayerGrad(config, "expand", 30, false, useGpu);
  }
}

TEST(Layer, ExpandLayer) {
  testExpandLayer("non-seq", false);  // non-seq expand to seq
  testExpandLayer("non-seq", true);   // non-seq expand to hasSubseq
  testExpandLayer("seq", true);       // seq expand to hasSubseq
}

932 933 934
void testDegradeLayer(bool hasSubseq,
                      string layer_type,
                      string trans_type,
L
Luo Tao 已提交
935
                      int stride) {
Z
zhangjinchao01 已提交
936 937 938
  TestConfig config;
  config.layerConfig.set_type(layer_type);
  config.layerConfig.set_size(10);
939
  config.layerConfig.set_seq_pool_stride(stride);
Z
zhangjinchao01 已提交
940 941 942
  config.biasSize = 0;

  config.inputDefs.push_back(
943 944 945 946
      {hasSubseq ? INPUT_HASSUB_SEQUENCE_DATA : INPUT_SEQUENCE_DATA,
       "layer_0",
       10,
       0});
Z
zhangjinchao01 已提交
947 948 949 950 951 952 953 954 955 956 957 958
  config.layerConfig.add_inputs();
  config.layerConfig.set_trans_type(trans_type);

  auto testDegradeLayerGrad = [](TestConfig& config, string layer_type) {
    for (auto useGpu : {false, true}) {
      testLayerGrad(config, layer_type, 100, false, useGpu);
    }
  };

  if (layer_type == "average") {
    for (auto strategy : {"average", "sum", "squarerootn"}) {
      LOG(INFO) << " hasSubseq=" << hasSubseq << " trans_type=" << trans_type
959 960
                << " average_strategy=" << strategy
                << " seq_pool_stride=" << stride;
Z
zhangjinchao01 已提交
961 962 963 964
      config.layerConfig.set_average_strategy(strategy);
      testDegradeLayerGrad(config, layer_type);
    }
  } else {
965 966
    LOG(INFO) << " hasSubseq=" << hasSubseq << " trans_type=" << trans_type
              << " seq_pool_stride=" << stride;
Z
zhangjinchao01 已提交
967 968 969 970 971
    testDegradeLayerGrad(config, layer_type);
  }
}

TEST(Layer, MaxLayer) {
L
Luo Tao 已提交
972
  testDegradeLayer(false, "max", "non-seq", -1);  // seq max to non-seq
973 974 975 976 977 978
  testDegradeLayer(false,
                   "max",
                   "non-seq",
                   5);  // seq max to a shorten seq, stride window = 5
  testDegradeLayer(true, "max", "non-seq", -1);  // hasSubseq max to non-seq
  testDegradeLayer(true, "max", "seq", -1);      // hasSubseq max to seq
Z
zhangjinchao01 已提交
979 980 981
}

TEST(Layer, SequenceLastInstanceLayer) {
982 983
  testDegradeLayer(false,
                   "seqlastins",
L
Luo Tao 已提交
984 985
                   "non-seq",
                   -1);  // seq seqlastins to non-seq
986 987 988 989
  testDegradeLayer(false,
                   "seqlastins",
                   "non-seq",
                   5);  // seq seqlastins to a shorten seq, stride window = 5
990 991
  testDegradeLayer(true,
                   "seqlastins",
L
Luo Tao 已提交
992 993
                   "non-seq",
                   -1);  // hasSubseq seqlastins to non-seq
Y
Yang Yu 已提交
994 995 996 997
  testDegradeLayer(true,
                   "seqlastins",
                   "seq",
                   -1);  // hasSubseq seqlastins to seq
Z
zhangjinchao01 已提交
998 999 1000
}

TEST(Layer, AverageLayer) {
L
Luo Tao 已提交
1001
  testDegradeLayer(false, "average", "non-seq", -1);  // seq average to non-seq
1002
  testDegradeLayer(false,
L
Luo Tao 已提交
1003
                   "average",
1004 1005
                   "non-seq",
                   5);  // seq average to a shorten seq, stride window = 5
Y
Yang Yu 已提交
1006 1007 1008 1009
  testDegradeLayer(true,
                   "average",
                   "non-seq",
                   -1);                          // hasSubseq average to non-seq
L
Luo Tao 已提交
1010
  testDegradeLayer(true, "average", "seq", -1);  // hasSubseq average to seq
Z
zhangjinchao01 已提交
1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104
}

TEST(Layer, SequenceConcatLayer) {
  TestConfig config;
  config.layerConfig.set_type("seqconcat");
  config.layerConfig.set_size(10);
  config.biasSize = 0;

  config.inputDefs.push_back({INPUT_SEQUENCE_DATA, "layer_0", 10, 0});
  config.layerConfig.add_inputs();
  config.inputDefs.push_back({INPUT_SEQUENCE_DATA, "layer_1", 10, 0});
  config.layerConfig.add_inputs();

  for (auto useGpu : {false, true}) {
    testLayerGrad(config, "seqconcat", 100, false, useGpu);
  }
}

TEST(Layer, SequenceReshapeLayer) {
  TestConfig config;
  config.layerConfig.set_type("seqreshape");
  config.layerConfig.set_size(10);

  config.inputDefs.push_back({INPUT_SEQUENCE_DATA, "layer_0", 100, 0});
  config.layerConfig.add_inputs();

  for (auto useGpu : {false, true}) {
    testLayerGrad(config, "seqreshape", 100, false, useGpu);
  }
}

TEST(Layer, ConvShiftLayer) {
  TestConfig config;
  config.layerConfig.set_type("conv_shift");
  config.layerConfig.set_size(10);

  config.inputDefs.push_back({INPUT_DATA, "layer_0", 10, 0});
  config.inputDefs.push_back({INPUT_DATA, "layer_1", 3, 0});
  config.layerConfig.add_inputs();
  config.layerConfig.add_inputs();

  // Not support GPU now
  testLayerGrad(config, "conv_shift", 100, false, false);
}

TEST(Layer, PowerLayer) {
  TestConfig config;
  config.layerConfig.set_type("power");
  config.layerConfig.set_size(10);

  config.inputDefs.push_back({INPUT_DATA, "layer_0", 1, 0});
  config.inputDefs.push_back({INPUT_DATA, "layer_1", 10, 0});
  config.layerConfig.add_inputs();
  config.layerConfig.add_inputs();

  for (auto useGpu : {false, true}) {
    testLayerGrad(config, "power", 100, false, useGpu);
  }
}

TEST(Layer, ConvexCombinationLayer) {
  TestConfig config;
  config.layerConfig.set_type("convex_comb");
  config.layerConfig.set_size(20);
  config.biasSize = 0;

  config.inputDefs.push_back({INPUT_DATA, "layer_0", 5, 0});
  config.inputDefs.push_back({INPUT_DATA, "layer_1", 100, 0});
  config.layerConfig.add_inputs();
  config.layerConfig.add_inputs();

  for (auto useGpu : {false, true}) {
    testLayerGrad(config, "convex_comb", 100, false, useGpu);
  }
}

TEST(Layer, InterpolationLayer) {
  TestConfig config;
  config.layerConfig.set_type("interpolation");
  config.layerConfig.set_size(10);
  config.biasSize = 0;

  config.inputDefs.push_back({INPUT_DATA, "layer_0", 1, 0});
  config.inputDefs.push_back({INPUT_DATA, "layer_1", 10, 0});
  config.inputDefs.push_back({INPUT_DATA, "layer_2", 10, 0});
  config.layerConfig.add_inputs();
  config.layerConfig.add_inputs();
  config.layerConfig.add_inputs();

  for (auto useGpu : {false, true}) {
    testLayerGrad(config, "interpolation", 100, false, useGpu);
  }
}

R
ranqiu 已提交
1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115
TEST(Layer, DotProdLayer) {
  TestConfig config;
  config.layerConfig.set_type("dot_prod");
  config.layerConfig.set_size(1);

  config.inputDefs.push_back({INPUT_DATA, "layer_0", 10, 0});
  config.layerConfig.add_inputs();
  config.inputDefs.push_back({INPUT_DATA, "layer_1", 10, 0});
  config.layerConfig.add_inputs();

  for (auto useGpu : {false, true}) {
R
ranqiu 已提交
1116
    testLayerGrad(config, "dot_prod", 10, false, useGpu);
R
ranqiu 已提交
1117 1118 1119
  }
}

Z
zhangjinchao01 已提交
1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170
TEST(Layer, OuterProdLayer) {
  TestConfig config;
  config.layerConfig.set_type("out_prod");
  config.layerConfig.set_size(100);

  config.inputDefs.push_back({INPUT_DATA, "layer_0", 10, 0});
  config.layerConfig.add_inputs();
  config.inputDefs.push_back({INPUT_DATA, "layer_1", 10, 0});
  config.layerConfig.add_inputs();

  for (auto useGpu : {false, true}) {
    testLayerGrad(config, "out_prod", 100, false, useGpu);
  }
}

TEST(Layer, SlopeInterceptLayer) {
  TestConfig config;
  config.layerConfig.set_type("slope_intercept");
  config.layerConfig.set_size(10);
  config.layerConfig.set_slope(1.0);
  config.layerConfig.set_intercept(0.1);

  config.inputDefs.push_back({INPUT_DATA, "layer_0", 10, 0});
  config.layerConfig.add_inputs();

  for (auto useGpu : {false, true}) {
    testLayerGrad(config, "slope_intercept", 100, false, useGpu);
  }
}

TEST(Layer, ScalingLayer) {
  TestConfig config;
  config.layerConfig.set_type("scaling");
  config.layerConfig.set_size(10);
  config.biasSize = 0;

  config.inputDefs.push_back({INPUT_DATA, "layer_0", 1, 0});
  config.layerConfig.add_inputs();
  config.inputDefs.push_back({INPUT_DATA, "layer_1", 10, 0});
  config.layerConfig.add_inputs();

  for (auto useGpu : {false, true}) {
    testLayerGrad(config, "scaling", 100, false, useGpu);
  }
}

void testNormLayer(const string& normType, bool trans, bool useGpu) {
  TestConfig config;
  config.layerConfig.set_type("norm");
  config.layerConfig.set_active_type("relu");

L
Luo Tao 已提交
1171
  config.inputDefs.push_back({INPUT_DATA, "layer_0", 1568, 0});
Z
zhangjinchao01 已提交
1172 1173 1174 1175 1176 1177 1178 1179 1180
  LayerInputConfig* input = config.layerConfig.add_inputs();
  NormConfig* norm = input->mutable_norm_conf();
  norm->set_norm_type(normType);
  norm->set_channels(16);
  norm->set_size(5);
  norm->set_scale(0.001);
  norm->set_pow(0.75);
  norm->set_blocked(0);
  norm->set_img_size(14);
L
Luo Tao 已提交
1181
  norm->set_img_size_y(7);
Z
zhangjinchao01 已提交
1182
  norm->set_output_x(norm->img_size());
L
Luo Tao 已提交
1183
  norm->set_output_y(norm->img_size_y());
Z
zhangjinchao01 已提交
1184 1185 1186 1187 1188 1189 1190
  if (norm->norm_type() == "cmrnorm" ||
      norm->norm_type() == "cmrnorm-projection") {
    norm->set_scale(norm->scale() / norm->size());
  } else {
    norm->set_scale(norm->scale() / (norm->size() * norm->size()));
  }

L
Luo Tao 已提交
1191
  config.layerConfig.set_size(norm->output_x() * norm->output_y() *
Z
zhangjinchao01 已提交
1192 1193 1194 1195 1196 1197 1198
                              norm->channels());
  config.biasSize = 0;

  testLayerGrad(config, "norm", 100, trans, useGpu);
}

TEST(Layer, NormLayer) {
1199 1200 1201 1202 1203 1204
  testNormLayer("cmrnorm-projection",
                /* trans= */ false, /* useGpu= */
                true);
  testNormLayer("cmrnorm-projection",
                /* trans= */ false, /* useGpu= */
                false);
Z
zhangjinchao01 已提交
1205 1206
}

1207 1208
void setPoolConfig(TestConfig* config,
                   PoolConfig* pool,
Z
zhangjinchao01 已提交
1209 1210 1211 1212 1213
                   const string& poolType) {
  (*config).biasSize = 0;
  (*config).layerConfig.set_type("pool");
  (*config).layerConfig.set_num_filters(16);

1214 1215 1216
  int kw = 3, kh = 3;
  int pw = 0, ph = 0;
  int sw = 2, sh = 2;
Z
zhangjinchao01 已提交
1217 1218
  pool->set_pool_type(poolType);
  pool->set_channels(16);
1219 1220 1221 1222 1223 1224 1225 1226
  pool->set_size_x(kw);
  pool->set_size_y(kh);
  pool->set_start(0);
  pool->set_padding(pw);
  pool->set_padding_y(ph);
  pool->set_stride(sw);
  pool->set_stride_y(sh);

1227 1228
  int ow = outputSize(pool->img_size(), kw, pw, sw, /* caffeMode */ false);
  int oh = outputSize(pool->img_size_y(), kh, ph, sh, /* caffeMode */ false);
1229 1230
  pool->set_output_x(ow);
  pool->set_output_y(oh);
Z
zhangjinchao01 已提交
1231 1232
}

1233 1234 1235 1236
void testPoolLayer(const string& poolType,
                   bool trans,
                   bool useGpu,
                   bool excludeMode = true) {
Z
zhangjinchao01 已提交
1237 1238 1239 1240 1241 1242
  TestConfig config;
  config.inputDefs.push_back({INPUT_DATA, "layer_0", 3136, 0});
  LayerInputConfig* input = config.layerConfig.add_inputs();
  PoolConfig* pool = input->mutable_pool_conf();

  pool->set_img_size(14);
1243
  pool->set_img_size_y(14);
1244
  pool->set_exclude_mode(excludeMode);
1245 1246
  setPoolConfig(&config, pool, poolType);
  config.layerConfig.set_size(pool->output_x() * pool->output_y() *
Z
zhangjinchao01 已提交
1247 1248 1249 1250 1251
                              pool->channels());

  testLayerGrad(config, "pool", 100, trans, useGpu);
}

1252
#ifdef PADDLE_WITH_CUDA
Z
zhangjinchao01 已提交
1253 1254 1255 1256 1257 1258 1259 1260 1261 1262
void testPoolLayer2(const string& poolType, bool trans, bool useGpu) {
  TestConfig config;
  config.inputDefs.push_back({INPUT_DATA, "layer_0", 3200, 0});
  LayerInputConfig* input = config.layerConfig.add_inputs();
  PoolConfig* pool = input->mutable_pool_conf();

  pool->set_size_y(4);
  pool->set_stride_y(3);
  pool->set_img_size(10);
  pool->set_img_size_y(20);
1263
  setPoolConfig(&config, pool, poolType);
Z
zhangjinchao01 已提交
1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275
  pool->set_output_y((pool->img_size_y() - pool->start() - pool->size_y()) /
                         ((float)pool->stride_y()) +
                     1.5);
  config.layerConfig.set_size(pool->output_x() * pool->output_y() *
                              pool->channels());

  testLayerGrad(config, "pool", 100, trans, useGpu);
}
#endif

TEST(Layer, PoolLayer) {
  testPoolLayer("avg-projection", /* trans= */ false, /* useGpu= */ false);
1276 1277 1278 1279
  testPoolLayer("avg-projection",
                /* trans= */ false,
                /* useGpu= */ false,
                /* excludeMode= */ false);
Z
zhangjinchao01 已提交
1280
  testPoolLayer("max-projection", /* trans= */ false, /* useGpu= */ false);
X
xzl 已提交
1281
  testPoolLayer("max-pool-with-mask", /* trans= */ false, /* useGpu= */ false);
Z
zhangjinchao01 已提交
1282

1283
#ifdef PADDLE_WITH_CUDA
Z
zhangjinchao01 已提交
1284
  testPoolLayer("avg-projection", /* trans= */ false, /* useGpu= */ true);
1285 1286 1287 1288
  testPoolLayer("avg-projection",
                /* trans= */ false,
                /* useGpu= */ true,
                /* excludeMode= */ false);
Z
zhangjinchao01 已提交
1289 1290 1291 1292 1293
  testPoolLayer("max-projection", /* trans= */ false, /* useGpu= */ true);
  testPoolLayer("cudnn-max-pool", /* trans= */ false, /* useGpu= */ true);
  testPoolLayer("cudnn-avg-pool", /* trans= */ false, /* useGpu= */ true);
  testPoolLayer2("cudnn-max-pool", /* trans= */ false, /* useGpu= */ true);
  testPoolLayer2("cudnn-avg-pool", /* trans= */ false, /* useGpu= */ true);
Y
Yang Yu 已提交
1294 1295 1296
  testPoolLayer2("cudnn-avg-incl-pad-pool",
                 /* trans= */ false,
                 /* useGpu= */ true);
X
xzl 已提交
1297
  testPoolLayer("max-pool-with-mask", /* trans= */ false, /* useGpu= */ true);
Z
zhangjinchao01 已提交
1298 1299 1300
#endif
}

C
chengduoZH 已提交
1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363
void setPool3DConfig(TestConfig* config,
                     PoolConfig* pool,
                     const string& poolType) {
  // filter size
  const int NUM_FILTERS = 16;
  const int FILTER_SIZE = 3;
  const int FILTER_SIZE_Y = 3;
  const int FILTER_SIZE_Z = 3;
  const int CHANNELS = 16;

  (*config).biasSize = 0;
  (*config).layerConfig.set_type("pool3d");
  (*config).layerConfig.set_num_filters(NUM_FILTERS);

  int kw = FILTER_SIZE, kh = FILTER_SIZE_Y, kd = FILTER_SIZE_Z;
  int pw = 0, ph = 0, pd = 0;
  int sw = 2, sh = 2, sd = 2;

  pool->set_pool_type(poolType);
  pool->set_pool_type("avg");
  pool->set_channels(CHANNELS);
  pool->set_size_x(kw);
  pool->set_size_y(kh);
  pool->set_size_z(kd);
  pool->set_padding(0);
  pool->set_padding_y(0);
  pool->set_padding_z(0);
  pool->set_stride(sw);
  pool->set_stride_y(sh);
  pool->set_stride_z(sd);
  pool->set_start(0);
  int ow = outputSize(pool->img_size(), kw, pw, sw, /* caffeMode */ false);
  int oh = outputSize(pool->img_size_y(), kh, ph, sh, /* caffeMode */ false);
  int od = outputSize(pool->img_size_z(), kd, pd, sd, /* caffeMode */ false);
  pool->set_output_x(ow);
  pool->set_output_y(oh);
  pool->set_output_z(od);
}

void testPool3DLayer(const string& poolType, bool trans, bool useGpu) {
  TestConfig config;
  config.inputDefs.push_back({INPUT_DATA, "layer_0", 11664, 0});
  LayerInputConfig* input = config.layerConfig.add_inputs();
  PoolConfig* pool = input->mutable_pool_conf();

  const int IMAGE_SIZE = 9;
  const int IMAGE_SIZE_Y = 9;
  const int IMAGE_SIZE_Z = 9;

  pool->set_img_size(IMAGE_SIZE);
  pool->set_img_size_y(IMAGE_SIZE_Y);
  pool->set_img_size_z(IMAGE_SIZE_Z);

  setPool3DConfig(&config, pool, poolType);
  config.layerConfig.set_size(pool->output_x() * pool->output_y() *
                              pool->channels());

  testLayerGrad(config, "pool3d", 100, trans, useGpu);
}

TEST(Layer, Pool3DLayer) {
  testPool3DLayer("avg", /* trans= */ false, /* useGpu= */ false);
  testPool3DLayer("max", /* trans= */ false, /* useGpu= */ false);
1364
#ifdef PADDLE_WITH_CUDA
C
chengduoZH 已提交
1365 1366 1367 1368 1369
  testPool3DLayer("avg", /* trans= */ false, /* useGpu= */ true);
  testPool3DLayer("max", /* trans= */ false, /* useGpu= */ true);
#endif
}

1370 1371 1372
void testSppLayer(const string& poolType,
                  const int pyramidHeight,
                  bool trans,
Q
qijun 已提交
1373 1374 1375 1376 1377 1378 1379 1380
                  bool useGpu) {
  TestConfig config;
  config.layerConfig.set_type("spp");
  config.inputDefs.push_back({INPUT_DATA, "layer_0", 3200, 0});
  LayerInputConfig* input = config.layerConfig.add_inputs();
  SppConfig* sppConfig = input->mutable_spp_conf();
  sppConfig->set_pool_type(poolType);
  sppConfig->set_pyramid_height(pyramidHeight);
L
Luo Tao 已提交
1381 1382 1383 1384
  ImageConfig* imageConfig = sppConfig->mutable_image_conf();
  imageConfig->set_channels(16);
  imageConfig->set_img_size(10);
  imageConfig->set_img_size_y(20);
Q
qijun 已提交
1385
  int outputSize = (std::pow(4, sppConfig->pyramid_height()) - 1) / (4 - 1);
L
Luo Tao 已提交
1386
  config.layerConfig.set_size(outputSize * imageConfig->channels());
Q
qijun 已提交
1387 1388 1389 1390 1391
  testLayerGrad(config, "spp", 100, trans, useGpu);
}

TEST(Layer, SpatialPyramidPoolLayer) {
  for (auto useGpu : {false, true}) {
1392 1393 1394 1395
    for (auto pyramidHeight : {1, 2, 3}) {
      testSppLayer("avg-projection", pyramidHeight, false, useGpu);
      testSppLayer("max-projection", pyramidHeight, false, useGpu);
    }
Q
qijun 已提交
1396 1397 1398
  }
}

Z
zhangjinchao01 已提交
1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415
TEST(Layer, rankCostLayer) {
  TestConfig config;
  config.layerConfig.set_type("rank-cost");
  config.biasSize = 0;

  config.inputDefs.push_back({INPUT_DATA, "layer_0", 1, 0});
  config.inputDefs.push_back({INPUT_DATA, "layer_1", 1, 0});
  config.inputDefs.push_back({INPUT_DATA_TARGET, "layer_2", 1, 0});
  config.layerConfig.add_inputs();
  config.layerConfig.add_inputs();
  config.layerConfig.add_inputs();

  for (auto useGpu : {false, true}) {
    testLayerGrad(config, "rank-cost", 100, false, useGpu);
  }
}

X
xuwei06 已提交
1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428
TEST(Layer, sumCostLayer) {
  TestConfig config;
  config.layerConfig.set_type("sum_cost");
  config.biasSize = 0;

  config.inputDefs.push_back({INPUT_DATA, "layer_0", 1, 0});
  config.layerConfig.add_inputs();

  for (auto useGpu : {false, true}) {
    testLayerGrad(config, "sum_cost", 100, false, useGpu);
  }
}

Z
zhangjinchao01 已提交
1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479
TEST(Layer, weightedRankCostLayer) {
  TestConfig config;
  config.layerConfig.set_type("rank-cost");
  config.biasSize = 0;

  config.inputDefs.push_back({INPUT_DATA, "layer_0", 1, 0});
  config.inputDefs.push_back({INPUT_DATA, "layer_1", 1, 0});
  config.inputDefs.push_back({INPUT_DATA_TARGET, "layer_2", 1, 0});
  config.inputDefs.push_back({INPUT_DATA_TARGET, "layer_3", 1, 0});
  config.layerConfig.add_inputs();
  config.layerConfig.add_inputs();
  config.layerConfig.add_inputs();
  config.layerConfig.add_inputs();

  for (auto useGpu : {false, true}) {
    testLayerGrad(config, "weighted-rank-cost", 100, false, useGpu);
  }
}

TEST(Layer, TensorLayer) {
  TestConfig config;
  config.layerConfig.set_type("tensor");
  config.layerConfig.set_size(10);
  config.layerConfig.set_active_type("sigmoid");
  config.biasSize = config.layerConfig.size();

  config.inputDefs.push_back({INPUT_DATA, "layer_0", 5, 250});
  config.inputDefs.push_back({INPUT_DATA, "layer_1", 5, 0});
  config.layerConfig.add_inputs();
  config.layerConfig.add_inputs();

  for (auto useGpu : {false, true}) {
    testLayerGrad(config, "tensor", 100, false, useGpu);
  }
}

TEST(Layer, RecurrentLayer) {
  TestConfig config;
  config.layerConfig.set_type("recurrent");
  config.layerConfig.set_size(4);
  config.layerConfig.set_active_type("tanh");
  config.biasSize = 4;

  config.inputDefs.push_back(
      {INPUT_SEQUENCE_DATA, "layer_0", /* dim= */ 4, /* paraSize= */ 16});
  config.layerConfig.add_inputs();

  for (auto useGpu : {false, true}) {
    for (auto reversed : {false, true}) {
      config.layerConfig.set_reversed(reversed);
      config.testState = !reversed;
1480 1481
      testLayerGrad(
          config, "recurrent", 50, /* trans= */ false, useGpu, false, 1.0);
Z
zhangjinchao01 已提交
1482 1483 1484 1485 1486 1487 1488 1489
    }
  }
}

TEST(Layer, LstmLayer) {
  TestConfig config;
  config.layerConfig.set_type("lstmemory");
  config.layerConfig.set_size(4);
1490
  config.layerConfig.set_active_type("tanh");
Z
zhangjinchao01 已提交
1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502
  config.layerConfig.set_active_state_type("sigmoid");
  config.layerConfig.set_active_gate_type("sigmoid");
  config.biasSize = 28;

  config.inputDefs.push_back(
      {INPUT_SEQUENCE_DATA, "layer_0", /* dim= */ 16, /* paraSize= */ 64});
  config.layerConfig.add_inputs();

  for (auto useGpu : {false, true}) {
    for (auto reversed : {false, true}) {
      config.layerConfig.set_reversed(reversed);
      config.testState = !reversed;
1503 1504
      testLayerGrad(
          config, "lstmemory", 100, /* trans= */ false, useGpu, false, 0.02);
Z
zhangjinchao01 已提交
1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572
    }
  }
  for (auto useGpu : {true}) {
    config.testBatchState = true;
    config.layerConfig.set_reversed(false);
    testLayerGrad(config, "lstmemory", 10, /* trans= */ false, useGpu);
  }
}

TEST(Layer, MDLstmLayer) {
  TestConfig config;
  config.layerConfig.set_type("mdlstmemory");
  config.layerConfig.set_size(4);
  config.layerConfig.set_active_type("sigmoid");
  config.layerConfig.set_active_state_type("sigmoid");
  config.layerConfig.set_active_gate_type("sigmoid");
  config.biasSize = 4 * 9;

  config.inputDefs.push_back(
      {INPUT_SEQUENCE_MDIM_DATA, "layer_0", 4 * 5, 4 * 4 * 5});
  config.layerConfig.add_inputs();
  config.layerConfig.add_directions(true);
  config.layerConfig.add_directions(true);

  for (auto useGpu : {false, true}) {
    for (int i = 0; i < 2; i++) {
      for (int j = 0; j < 2; j++) {
        config.layerConfig.set_directions(0, bool(i));
        config.layerConfig.set_directions(1, bool(j));
        testLayerGrad(config, "mdlstmemory", 100, false, useGpu);
      }
    }
  }
}

TEST(Layer, ParameterReluLayer) {
  auto testParameterReluLayer = [&](size_t inputSize, size_t channels) {
    TestConfig config;
    config.layerConfig.set_type("prelu");
    config.inputDefs.push_back({INPUT_DATA, "layer_0", inputSize, channels});
    config.layerConfig.add_inputs();
    config.layerConfig.set_size(inputSize);
    config.layerConfig.set_partial_sum(inputSize /
                                       channels);  // size of feature map
    for (auto useGpu : {false, true}) {
      testLayerGrad(config, "prelu", 100, false, useGpu);
    }
  };

  testParameterReluLayer(192, 1);
  testParameterReluLayer(192, 3);
  testParameterReluLayer(192, 192);
}

TEST(Layer, ResizeLayer) {
  TestConfig config;
  config.biasSize = 0;
  config.layerConfig.set_type("resize");
  config.layerConfig.set_size(64);

  config.inputDefs.push_back({INPUT_DATA, "layer_0", 16, 0});
  config.layerConfig.add_inputs();

  for (auto useGpu : {false, true}) {
    testLayerGrad(config, "resize", 100, false, useGpu);
  }
}

1573 1574 1575 1576
TEST(Layer, RotateLayer) {
  TestConfig config;
  config.biasSize = 0;
  config.layerConfig.set_type("rotate");
H
Haonan 已提交
1577
  const int CHANNEL = 2;
H
Haonan 已提交
1578 1579
  const int HEIGHT = 8;
  const int WIDTH = 4;
H
Haonan 已提交
1580
  const int INPUT_SIZE = HEIGHT * WIDTH * CHANNEL;
1581
  config.layerConfig.set_size(INPUT_SIZE);
H
Haonan 已提交
1582 1583
  config.layerConfig.set_height(HEIGHT);
  config.layerConfig.set_width(WIDTH);
1584 1585 1586 1587 1588 1589 1590 1591
  config.inputDefs.push_back({INPUT_DATA, "layer_0", INPUT_SIZE, 0});
  config.layerConfig.add_inputs();

  for (auto useGpu : {false, true}) {
    testLayerGrad(config, "rotate", 100, false, useGpu);
  }
}

Z
zhangjinchao01 已提交
1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616
TEST(Layer, NCELayer) {
  TestConfig config;
  size_t numClasses = 4;
  config.layerConfig.set_type("nce");
  config.layerConfig.set_size(1);
  config.layerConfig.set_active_type("sigmoid");
  config.layerConfig.set_num_classes(numClasses);
  config.biasSize = numClasses;

  config.inputDefs.push_back(
      {INPUT_DATA, "layer_0", /* dim= */ 16, /* paraSize= */ 16 * numClasses});
  config.inputDefs.push_back(
      {INPUT_LABEL, "label", /* dim= */ numClasses, /* paraSize= */ 0});
  config.layerConfig.add_inputs();
  config.layerConfig.add_inputs();

  for (auto withWeight : {false, true}) {
    if (withWeight) {
      config.inputDefs.push_back(
          {INPUT_DATA_TARGET, "weight", /* dim= */ 1, /* paraSize= */ 0});
      config.layerConfig.add_inputs();
    }

    for (auto isIdLabel : {false, true}) {
      config.inputDefs[1] = {
1617 1618
          isIdLabel ? INPUT_LABEL : INPUT_SPARSE_NON_VALUE_DATA,
          "label",
Z
zhangjinchao01 已提交
1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639
          /* dim= */ numClasses,
          /* paraSize= */ 0};

      for (auto withDist : {false, true}) {
        config.layerConfig.clear_neg_sampling_dist();
        if (withDist) {
          double sum = 0;
          for (size_t i = 0; i < numClasses; ++i) {
            real p = rand();  // NOLINT use rand_r
            config.layerConfig.add_neg_sampling_dist(p);
            sum += p;
          }
          for (size_t i = 0; i < numClasses; ++i) {
            real p = config.layerConfig.neg_sampling_dist(i) / sum;
            config.layerConfig.set_neg_sampling_dist(i, p);
          }
        }
        LOG(INFO) << "NCELayer "
                  << " isIdLabel=" << isIdLabel << " withWeight=" << withWeight
                  << " withDist=" << withDist;
        // Not support GPU now
1640 1641 1642 1643
        testLayerGrad(config,
                      "nce",
                      100,
                      /* trans= */ false,
Z
zhangjinchao01 已提交
1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716
                      /* useGpu */ false);
      }
    }
  }
}

TEST(Layer, GatedRecurrentLayer) {
  TestConfig config;
  config.layerConfig.set_type("gated_recurrent");
  config.layerConfig.set_size(4);
  config.layerConfig.set_active_type("sigmoid");
  config.layerConfig.set_active_gate_type("sigmoid");
  config.biasSize = 12;

  config.inputDefs.push_back(
      {INPUT_SEQUENCE_DATA, "layer_0", /* dim= */ 12, /* paraSize= */ 48});
  config.layerConfig.add_inputs();

  for (auto useGpu : {false, true}) {
    for (auto reversed : {false, true}) {
      config.layerConfig.set_reversed(reversed);
      config.testState = !reversed;
      testLayerGrad(config, "gated_recurrent", 100, /* trans= */ false, useGpu);
    }
  }
}

TEST(Layer, GruStepLayer) {
  TestConfig config;
  config.layerConfig.set_type("gru_step");
  config.layerConfig.set_size(4);
  config.layerConfig.set_active_type("sigmoid");
  config.layerConfig.set_active_gate_type("sigmoid");
  config.biasSize = 12;

  config.inputDefs.push_back(
      {INPUT_DATA, "layer_0", /* dim= */ 12, /* paraSize= */ 48});
  config.inputDefs.push_back(
      {INPUT_DATA, "layer_1", /* dim= */ 4, /* paraSize= */ 0});
  config.layerConfig.add_inputs();
  config.layerConfig.add_inputs();

  for (auto useGpu : {false, true}) {
    testLayerGrad(config, "gruStep", 100, /* trans= */ false, useGpu);
  }
}

TEST(Layer, LstmStepLayer) {
  TestConfig config;
  config.layerConfig.set_type("lstm_step");
  config.layerConfig.set_size(4);
  config.layerConfig.set_active_type("sigmoid");
  config.layerConfig.set_active_state_type("sigmoid");
  config.layerConfig.set_active_gate_type("sigmoid");
  config.biasSize = 12;
  config.testAccumulate = false;

  config.inputDefs.push_back(
      {INPUT_DATA, "layer_0", /* dim= */ 16, /* paraSize= */ 0});
  config.inputDefs.push_back(
      {INPUT_DATA, "layer_1", /* dim= */ 4, /* paraSize= */ 0});
  config.layerConfig.add_inputs();
  config.layerConfig.add_inputs();

  for (auto useGpu : {false, true}) {
    testLayerGrad(config, "lstmStep", 100, /* trans= */ false, useGpu);
  }
}

void testBatchNormLayer(const string& type, bool trans, bool useGpu) {
  TestConfig config;
  const int CHANNELS = 10;
  const int IMG_SIZE = 16;
L
Luo Tao 已提交
1717 1718
  const int IMG_SIZE_Y = 8;
  size_t size = CHANNELS * IMG_SIZE * IMG_SIZE_Y;
Z
zhangjinchao01 已提交
1719
  config.layerConfig.set_type(type);
L
Luo Tao 已提交
1720
  config.layerConfig.set_size(size);
Z
zhangjinchao01 已提交
1721 1722
  config.layerConfig.set_active_type("sigmoid");
  config.biasSize = CHANNELS;
1723 1724
  config.inputDefs.push_back({INPUT_DATA,
                              "layer_0",
L
Luo Tao 已提交
1725
                              /* dim= */ size,
Z
zhangjinchao01 已提交
1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739
                              /* paraSize= */ CHANNELS});

  config.inputDefs.push_back({INPUT_DATA, "layer_1_running_mean", 1, CHANNELS});
  config.inputDefs.back().isStatic = true;
  config.inputDefs.push_back({INPUT_DATA, "layer_2_running_var", 1, CHANNELS});
  config.inputDefs.back().isStatic = true;

  LayerInputConfig* input = config.layerConfig.add_inputs();
  config.layerConfig.add_inputs();
  config.layerConfig.add_inputs();

  ImageConfig* img_conf = input->mutable_image_conf();
  img_conf->set_channels(CHANNELS);
  img_conf->set_img_size(IMG_SIZE);
L
Luo Tao 已提交
1740
  img_conf->set_img_size_y(IMG_SIZE_Y);
Z
zhangjinchao01 已提交
1741

1742 1743 1744 1745 1746
  testLayerGrad(config,
                "batch_norm",
                64,
                /* trans= */ trans,
                useGpu,
Z
zhangjinchao01 已提交
1747 1748 1749 1750 1751
                /* useWeight */ true);
}

TEST(Layer, BatchNormalizationLayer) {
  testBatchNormLayer("batch_norm", false, false);
1752
#ifdef PADDLE_WITH_CUDA
Z
zhangjinchao01 已提交
1753 1754 1755 1756 1757 1758 1759
  testBatchNormLayer("batch_norm", false, true);
  if (hl_get_cudnn_lib_version() >= int(4000)) {
    testBatchNormLayer("cudnn_batch_norm", false, true);
  }
#endif
}

1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800
void testBatchNorm3DLayer(const string& type, bool trans, bool useGpu) {
  TestConfig config;
  const int CHANNELS = 10;
  const int IMG_SIZE = 16;
  const int IMG_SIZE_Y = 8;
  const int IMG_SIZE_Z = 8;
  size_t size = CHANNELS * IMG_SIZE * IMG_SIZE_Y * IMG_SIZE_Z;
  config.layerConfig.set_type(type);
  config.layerConfig.set_size(size);
  config.layerConfig.set_active_type("sigmoid");
  config.biasSize = CHANNELS;
  config.inputDefs.push_back({INPUT_DATA,
                              "layer_0",
                              /* dim= */ size,
                              /* paraSize= */ CHANNELS});

  config.inputDefs.push_back({INPUT_DATA, "layer_1_running_mean", 1, CHANNELS});
  config.inputDefs.back().isStatic = true;
  config.inputDefs.push_back({INPUT_DATA, "layer_2_running_var", 1, CHANNELS});
  config.inputDefs.back().isStatic = true;

  LayerInputConfig* input = config.layerConfig.add_inputs();
  config.layerConfig.add_inputs();
  config.layerConfig.add_inputs();

  ImageConfig* img_conf = input->mutable_image_conf();
  img_conf->set_channels(CHANNELS);
  img_conf->set_img_size(IMG_SIZE);
  img_conf->set_img_size_y(IMG_SIZE_Y);
  img_conf->set_img_size_z(IMG_SIZE_Z);

  testLayerGrad(config,
                "batch_norm",
                64,
                /* trans= */ trans,
                useGpu,
                /* useWeight */ true);
}

TEST(Layer, testBatchNorm3DLayer) {
  testBatchNorm3DLayer("batch_norm", false, false);
1801
#ifdef PADDLE_WITH_CUDA
1802 1803 1804 1805 1806 1807 1808
  testBatchNorm3DLayer("batch_norm", false, true);
  if (hl_get_cudnn_lib_version() >= int(4000)) {
    testBatchNorm3DLayer("cudnn_batch_norm", false, true);
  }
#endif
}

1809
void testConvOperator(bool isDeconv) {
Z
zhangjinchao01 已提交
1810 1811 1812 1813 1814 1815
  TestConfig config;
  const int NUM_FILTERS = 16;
  const int FILTER_SIZE = 2;
  const int FILTER_SIZE_Y = 3;
  const int CHANNELS = 3;
  const int IMAGE_SIZE = 16;
1816
  const int IMAGE_SIZE_Y = 9;
Z
zhangjinchao01 已提交
1817
  OperatorConfig& operatorConf = *config.layerConfig.add_operator_confs();
1818 1819 1820 1821 1822
  if (isDeconv) {
    operatorConf.set_type("convt");
  } else {
    operatorConf.set_type("conv");
  }
Z
zhangjinchao01 已提交
1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833
  ConvConfig* conv = operatorConf.mutable_conv_conf();
  operatorConf.set_num_filters(NUM_FILTERS);
  conv->set_filter_size(FILTER_SIZE);
  conv->set_filter_size_y(FILTER_SIZE_Y);
  conv->set_channels(CHANNELS);
  conv->set_padding(0);
  conv->set_padding_y(1);
  conv->set_stride(2);
  conv->set_stride_y(2);
  conv->set_groups(1);
  conv->set_img_size(IMAGE_SIZE);
L
Luo Tao 已提交
1834
  conv->set_img_size_y(IMAGE_SIZE_Y);
L
Luo Tao 已提交
1835 1836 1837 1838
  conv->set_output_x(outputSize(conv->img_size(),
                                conv->filter_size(),
                                conv->padding(),
                                conv->stride(),
L
Luo Tao 已提交
1839
                                /*  caffeMode */ true));
L
Luo Tao 已提交
1840 1841 1842 1843
  conv->set_output_y(outputSize(conv->img_size_y(),
                                conv->filter_size_y(),
                                conv->padding_y(),
                                conv->stride_y(),
L
Luo Tao 已提交
1844
                                /*  caffeMode */ true));
Z
zhangjinchao01 已提交
1845

1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860
  if (isDeconv) {
    conv->set_filter_channels(NUM_FILTERS / conv->groups());
    config.inputDefs.push_back({INPUT_DATA,
                                "layer_0",
                                conv->output_x() * conv->output_y() * CHANNELS,
                                0});
    config.layerConfig.set_size(IMAGE_SIZE * IMAGE_SIZE_Y * NUM_FILTERS);
  } else {
    conv->set_filter_channels(conv->channels() / conv->groups());
    config.inputDefs.push_back(
        {INPUT_DATA, "layer_0", IMAGE_SIZE * IMAGE_SIZE_Y * CHANNELS, 0});
    config.layerConfig.set_size(conv->output_x() * conv->output_y() *
                                NUM_FILTERS);
  }

Z
zhangjinchao01 已提交
1861
  config.inputDefs.push_back(
1862 1863 1864 1865
      {INPUT_DATA,
       "layer_1",
       FILTER_SIZE * FILTER_SIZE_Y * CHANNELS * NUM_FILTERS,
       0});
Z
zhangjinchao01 已提交
1866 1867 1868 1869 1870 1871
  config.layerConfig.add_inputs();
  config.layerConfig.add_inputs();

  testOperatorGrad(config, operatorConf, 100, /*useGpu*/ true, false);
}

1872 1873 1874 1875 1876
TEST(Operator, conv) {
  testConvOperator(/*isDeconv*/ true);
  testConvOperator(/*isDeconv*/ false);
}

Z
zhangjinchao01 已提交
1877 1878 1879 1880 1881 1882 1883
TEST(Layer, FeatureMapExpandLayer) {
  TestConfig config;
  config.layerConfig.set_type("featmap_expand");
  const int CHANNELS = 10;
  const int INPUT_SIZE = 100;
  config.layerConfig.set_size(INPUT_SIZE * CHANNELS);
  config.layerConfig.set_num_filters(CHANNELS);
1884 1885 1886 1887
  config.inputDefs.push_back({INPUT_SEQUENCE_DATA,
                              "layer_0",
                              /* dim= */ INPUT_SIZE,
                              /* paraSize= */ 0});
Z
zhangjinchao01 已提交
1888 1889
  config.layerConfig.add_inputs();
  for (auto useGpu : {false, true}) {
X
xuwei06 已提交
1890 1891 1892 1893 1894 1895 1896 1897 1898
    for (auto asRowVec : {false, true}) {
      config.layerConfig.set_user_arg(asRowVec ? "as_row_vec" : "as_col_vec");
      testLayerGrad(config,
                    "featmap_expand",
                    /*batch_size*/ 100,
                    /* trans= */ false,
                    useGpu,
                    /* useWeight */ true);
    }
Z
zhangjinchao01 已提交
1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921
  }
}

TEST(Layer, MultiplexLayer) {
  TestConfig config;
  const int LAYER_SIZE = 100;
  config.layerConfig.set_type("multiplex");
  config.layerConfig.set_size(LAYER_SIZE);

  config.inputDefs.push_back({INPUT_LABEL, "layer_0", 2, 0});
  config.inputDefs.push_back(
      {INPUT_DATA, "layer_1", /* dim= */ LAYER_SIZE, /* paraSize= */ 0});
  config.inputDefs.push_back(
      {INPUT_DATA, "layer_2", /* dim= */ LAYER_SIZE, /* paraSize= */ 0});
  config.layerConfig.add_inputs();
  config.layerConfig.add_inputs();
  config.layerConfig.add_inputs();

  for (auto useGpu : {false, true}) {
    testLayerGrad(config, "multiplex", 512, /* trans= */ false, useGpu);
  }
}

D
dangqingqing 已提交
1922
TEST(Layer, PadLayer) {
Z
zhangjinchao01 已提交
1923 1924
  TestConfig config;
  config.biasSize = 0;
D
dangqingqing 已提交
1925
  config.layerConfig.set_type("pad");
Z
zhangjinchao01 已提交
1926

D
dangqingqing 已提交
1927 1928 1929 1930 1931
  int c = 4;
  int h = 31;
  int w = 36;
  size_t size = c * h * w;
  config.inputDefs.push_back({INPUT_DATA, "layer_0", size, 0});
Z
zhangjinchao01 已提交
1932
  LayerInputConfig* input = config.layerConfig.add_inputs();
D
dangqingqing 已提交
1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944
  PadConfig* pad = input->mutable_pad_conf();
  ImageConfig* image = pad->mutable_image_conf();

  image->set_channels(c);
  image->set_img_size(h);
  image->set_img_size_y(w);
  pad->add_pad_c(1);
  pad->add_pad_c(2);
  pad->add_pad_h(2);
  pad->add_pad_h(3);
  pad->add_pad_w(3);
  pad->add_pad_w(5);
Z
zhangjinchao01 已提交
1945 1946

  for (auto useGpu : {false, true}) {
D
dangqingqing 已提交
1947
    testLayerGrad(config, "pad", 10, false, useGpu);
Z
zhangjinchao01 已提交
1948 1949 1950
  }
}

1951
TEST(Layer, CrossChannelNormLayer) {
G
gaoyuan 已提交
1952
  TestConfig config;
Y
yangyaming 已提交
1953 1954
  config.paramInitialMean = 1.;
  config.paramInitialStd = 0.;
1955
  config.layerConfig.set_type("norm");
G
gaoyuan 已提交
1956
  config.layerConfig.set_size(100);
1957 1958 1959 1960 1961 1962 1963 1964
  LayerInputConfig* input = config.layerConfig.add_inputs();
  NormConfig* norm = input->mutable_norm_conf();
  norm->set_norm_type("cross-channel-norm");
  norm->set_channels(10);
  norm->set_size(100);
  norm->set_scale(0);
  norm->set_pow(0);
  norm->set_blocked(0);
G
gaoyuan 已提交
1965 1966 1967
  config.inputDefs.push_back({INPUT_DATA, "layer_0", 100, 10});

  for (auto useGpu : {false, true}) {
Y
yangyaming 已提交
1968
    testLayerGrad(config, "cross-channel-norm", 10, false, useGpu, false);
G
gaoyuan 已提交
1969 1970 1971
  }
}

G
gaoyuan 已提交
1972 1973 1974 1975
TEST(Layer, smooth_l1) {
  TestConfig config;
  config.layerConfig.set_type("smooth_l1");

1976 1977
  config.inputDefs.push_back({INPUT_DATA, "layer_0", 200, 0});
  config.inputDefs.push_back({INPUT_DATA_TARGET, "layer_1", 200, 0});
G
gaoyuan 已提交
1978 1979 1980 1981
  config.layerConfig.add_inputs();
  config.layerConfig.add_inputs();

  for (auto useGpu : {false, true}) {
D
dangqingqing 已提交
1982
    testLayerGrad(config, "smooth_l1", 100, false, useGpu, false);
G
gaoyuan 已提交
1983 1984 1985
  }
}

1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049
TEST(Layer, multibox_loss) {
  TestConfig config;
  config.layerConfig.set_type("multibox_loss");
  config.biasSize = 0;
  LayerInputConfig* input = config.layerConfig.add_inputs();
  MultiBoxLossConfig* multiboxLoss = input->mutable_multibox_loss_conf();
  multiboxLoss->set_num_classes(21);
  multiboxLoss->set_input_num(1);
  multiboxLoss->set_overlap_threshold(0.5);
  multiboxLoss->set_neg_pos_ratio(3);
  multiboxLoss->set_neg_overlap(0.5);
  multiboxLoss->set_background_id(0);
  multiboxLoss->set_height(3);
  multiboxLoss->set_width(3);

  size_t gtNum = 1;
  MatrixPtr labelValue = Matrix::create(gtNum, 6, false, false);
  labelValue->randomizeUniform();
  labelValue->add(-0.5);
  labelValue->sigmoid(*labelValue);
  real* labelData = labelValue->getData();
  size_t labelWidth = labelValue->getWidth();
  for (size_t i = 0; i < gtNum; ++i) {
    *(labelData + i * labelWidth) = std::rand() % 20 + 1;
    *(labelData + i * labelWidth + 1) = 0.400259;
    *(labelData + i * labelWidth + 2) = 0.377857;
    *(labelData + i * labelWidth + 3) = 0.525712;
    *(labelData + i * labelWidth + 4) = 0.519368;
  }
  vector<int> seqStartPositions(gtNum + 1, 0);
  for (size_t i = 1; i <= gtNum; ++i) {
    seqStartPositions[i] = i;
  }

  // Ensure at lease one matched bbox
  MatrixPtr priorValue = Matrix::create(1, 72, false, false);
  priorValue->randomizeUniform();
  priorValue->add(-0.5);
  priorValue->sigmoid(*priorValue);
  real* priorData = priorValue->getData();
  *(priorData) = 0.424811;
  *(priorData + 1) = 0.397059;
  *(priorData + 2) = 0.538905;
  *(priorData + 3) = 0.447091;
  *(priorData + 4) = 0.425720;
  *(priorData + 5) = 0.515228;
  *(priorData + 6) = 0.519452;
  *(priorData + 7) = 0.591065;

  config.inputDefs.push_back(
      {INPUT_SELF_DEFINE_DATA, "priorbox", priorValue, {}});
  config.inputDefs.push_back(
      {INPUT_SELF_DEFINE_DATA, "label", labelValue, seqStartPositions});
  config.inputDefs.push_back({INPUT_DATA, "locPred", 36, 0});
  config.inputDefs.push_back({INPUT_DATA, "confPred", 189, 0});
  config.layerConfig.add_inputs();
  config.layerConfig.add_inputs();
  config.layerConfig.add_inputs();

  for (auto useGpu : {false, true}) {
    testLayerGrad(config, "multibox_loss", 1, false, useGpu, false);
  }
}

2050 2051 2052
TEST(Layer, TransLayer) {
  TestConfig config;
  const int height = 128;
2053
  const int width = 256;
2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065
  config.layerConfig.set_type("trans");
  config.layerConfig.set_size(width);

  config.inputDefs.push_back(
      {INPUT_DATA, "layer_0", /* dim= */ height * width, /* paraSize= */ 0});
  config.layerConfig.add_inputs();

  for (auto useGpu : {false, true}) {
    testLayerGrad(config, "trans", height, /* trans= */ false, useGpu);
  }
}

2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085
TEST(Layer, RowConvLayer) {
  const int context = 3;
  const int size = 512;

  TestConfig config;
  config.layerConfig.set_type("row_conv");
  config.layerConfig.set_size(size);
  config.layerConfig.set_active_type("sigmoid");

  config.inputDefs.push_back(
      {INPUT_SEQUENCE_DATA, "layer_0", size, context * size});
  LayerInputConfig* input = config.layerConfig.add_inputs();
  RowConvConfig* conv = input->mutable_row_conv_conf();
  conv->set_context_length(context);

  for (auto useGpu : {false, true}) {
    testLayerGrad(config, "row_conv", 100, false, useGpu, false);
  }
}

2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113
TEST(Layer, CropLayer) {
  TestConfig config;
  // config input_0
  config.inputDefs.push_back({INPUT_DATA, "layer_0", 1024, 0});
  LayerInputConfig* input = config.layerConfig.add_inputs();
  ImageConfig* img = input->mutable_image_conf();
  img->set_channels(4);
  img->set_img_size(16);
  config.layerConfig.set_axis(2);
  config.layerConfig.add_offset(0);
  config.layerConfig.add_offset(0);

  // config input_1
  config.inputDefs.push_back({INPUT_DATA, "layer_1", 128, 0});
  input = config.layerConfig.add_inputs();
  img = input->mutable_image_conf();
  img->set_channels(2);
  img->set_img_size(8);

  // config crop layer
  config.layerConfig.set_type("crop");
  config.layerConfig.set_name("cropLayer");

  for (auto useGpu : {false, true}) {
    testLayerGrad(config, "crop", 100, false, useGpu, false);
  }
}

G
guosheng 已提交
2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125
TEST(Layer, roi_pool) {
  TestConfig config;
  config.layerConfig.set_type("roi_pool");
  config.biasSize = 0;
  LayerInputConfig* input = config.layerConfig.add_inputs();
  ROIPoolConfig* roiPoolConf = input->mutable_roi_pool_conf();
  roiPoolConf->set_pooled_width(7);
  roiPoolConf->set_pooled_height(7);
  roiPoolConf->set_spatial_scale(1. / 16);
  roiPoolConf->set_width(14);
  roiPoolConf->set_height(14);

2126 2127 2128 2129
  const size_t roiNum = 10;
  const size_t roiDim = 10;
  const size_t batchSize = 5;
  MatrixPtr roiValue = Matrix::create(roiNum, roiDim, false, false);
G
guosheng 已提交
2130 2131
  roiValue->zeroMem();
  real* roiData = roiValue->getData();
2132 2133 2134 2135 2136 2137 2138 2139
  for (size_t i = 0; i < roiNum; ++i) {
    roiData[i * roiDim + 0] = std::rand() % batchSize;
    roiData[i * roiDim + 1] = std::rand() % 224;  // xMin
    roiData[i * roiDim + 2] = std::rand() % 224;  // yMin
    size_t xMin = static_cast<size_t>(roiData[i * roiDim + 1]);
    size_t yMin = static_cast<size_t>(roiData[i * roiDim + 2]);
    roiData[i * roiDim + 3] = xMin + std::rand() % (224 - xMin);  // xMax
    roiData[i * roiDim + 4] = yMin + std::rand() % (224 - yMin);  // yMax
G
guosheng 已提交
2140 2141 2142 2143 2144 2145 2146
  }

  config.inputDefs.push_back({INPUT_DATA, "input", 3 * 14 * 14, {}});
  config.inputDefs.push_back({INPUT_SELF_DEFINE_DATA, "rois", roiValue, {}});
  config.layerConfig.add_inputs();

  for (auto useGpu : {false, true}) {
2147
    testLayerGrad(config, "roi_pool", batchSize, false, useGpu, false);
G
guosheng 已提交
2148 2149 2150
  }
}

2151
TEST(Layer, SwitchOrderLayer) {
2152 2153 2154 2155 2156 2157 2158 2159 2160
  TestConfig config;
  // config input_0
  config.inputDefs.push_back({INPUT_DATA, "layer_0", 1024, 0});
  LayerInputConfig* input = config.layerConfig.add_inputs();
  ImageConfig* img = input->mutable_image_conf();
  img->set_channels(4);
  img->set_img_size(16);
  img->set_img_size_y(16);

2161
  ReshapeConfig* reshape = config.layerConfig.mutable_reshape_conf();
W
wanghaoshuang 已提交
2162 2163 2164 2165
  reshape->add_height_axis(0);
  reshape->add_height_axis(1);
  reshape->add_height_axis(2);
  reshape->add_width_axis(3);
2166

2167
  // config softmax layer
2168 2169
  config.layerConfig.set_type("switch_order");
  config.layerConfig.set_name("switchOrderLayer");
2170 2171

  for (auto useGpu : {false, true}) {
2172
    testLayerGrad(config, "switch_order", 100, false, useGpu, true);
2173 2174 2175
  }
}

C
caoying03 已提交
2176 2177 2178 2179 2180 2181 2182 2183 2184 2185
vector<real> randSampling(real range, int n) {
  CHECK_GE(range, n);
  vector<real> num(range);
  iota(begin(num), end(num), 0.);
  if (range == n) return num;

  random_shuffle(begin(num), end(num));
  num.resize(n);
  sort(begin(num), end(num));
  return num;
2186 2187
}

2188
TEST(Layer, SubNestedSequenceLayer) {
C
caoying03 已提交
2189 2190
  // layer size is not crutial for this layer,
  // so use a small layer size in unittest
2191 2192 2193 2194 2195 2196 2197 2198
  const int layerSize = 4;

  const int maxSeqNum = 50;
  const int maxSeqLen = 50;
  const int maxBeamSize = 32;

  srand((size_t)(time(NULL)));
  int beamSize = 1 + (rand() % maxBeamSize);
2199 2200 2201 2202 2203 2204

  TestConfig config;
  config.layerConfig.set_type("sub_nested_seq");
  config.layerConfig.set_name("sub_nested_seq_layer");
  config.layerConfig.set_size(layerSize);

C
caoying03 已提交
2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221
  int seqNum = 1 + (rand() % maxSeqNum);

  // sequence information for the first input, it is a nested sequence
  vector<int> seqStartPos(seqNum + 1, 0);
  vector<int> subSeqStartPos(1, 0);

  // selected indices
  MatrixPtr selectedIndices = Matrix::create(seqNum, beamSize, false, false);
  selectedIndices->one();
  selectedIndices->mulScalar(-1.);
  real* indicesData = selectedIndices->getData();

  for (int i = 0; i < seqNum; ++i) {
    int subSeqNum = 1 + (rand() % maxSeqNum);
    for (int j = 0; j < subSeqNum; ++j) {
      subSeqStartPos.push_back(subSeqStartPos.back() +
                               (1 + (rand() % maxSeqLen)));
2222
    }
C
caoying03 已提交
2223 2224 2225 2226 2227 2228
    vector<real> selSeqs =
        randSampling(static_cast<real>(subSeqNum), min(beamSize, subSeqNum));
    memcpy(indicesData + (i * beamSize),
           selSeqs.data(),
           selSeqs.size() * sizeof(real));
    seqStartPos[i + 1] = subSeqStartPos.back();
2229 2230
  }

C
caoying03 已提交
2231 2232
  MatrixPtr seqInputPtr =
      Matrix::create(seqStartPos.back(), layerSize, false, false);
2233
  seqInputPtr->randomizeUniform();
2234
  config.inputDefs.push_back({INPUT_SELF_DEFINE_DATA,
C
caoying03 已提交
2235 2236 2237
                              "nested_seq_input",
                              seqInputPtr,
                              seqStartPos,
2238 2239 2240
                              subSeqStartPos});
  config.layerConfig.add_inputs();
  config.inputDefs.push_back(
C
caoying03 已提交
2241
      {INPUT_SELF_DEFINE_DATA, "selected_indices", selectedIndices});
2242 2243 2244 2245 2246
  config.layerConfig.add_inputs();

  for (auto useGpu : {false, true}) {
    testLayerGrad(config,
                  "sub_nested_seq",
C
caoying03 已提交
2247
                  /* batchSize */ seqNum,
2248 2249 2250 2251 2252 2253
                  /* trans */ false,
                  /* useGpu*/ useGpu,
                  /* useWeight */ false);
  }
}

2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282
TEST(Layer, ClipLayer) {
  const size_t batchSize = 128;
  const size_t size = 512;
  TestConfig config;
  config.layerConfig.set_type("clip");
  config.inputDefs.push_back({INPUT_DATA, "input", size, 0});
  LayerInputConfig* input = config.layerConfig.add_inputs();
  ClipConfig* layerConf = input->mutable_clip_conf();
  double p1 = std::rand() / (double)RAND_MAX;
  double p2 = std::rand() / (double)RAND_MAX;
  layerConf->set_min(std::min(p1, p2));
  layerConf->set_max(std::max(p1, p2));
  for (auto useGpu : {false, true}) {
    testLayerGrad(config, "clip", batchSize, false, useGpu, false);
  }
}

TEST(Layer, RowL2NormLayer) {
  const size_t batchSize = 128;
  const size_t size = 512;
  TestConfig config;
  config.layerConfig.set_type("row_l2_norm");
  config.layerConfig.set_size(size);
  config.inputDefs.push_back({INPUT_DATA, "input", size, 0});
  config.layerConfig.add_inputs();
  for (auto useGpu : {false, true}) {
    testLayerGrad(config, "row_l2_norm", batchSize, false, useGpu, false);
  }
}
G
guosheng 已提交
2283

2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295
void test3DConvLayer(const string& type, bool trans, bool useGpu) {
  // filter size
  const int NUM_FILTERS = 6;
  // const int CHANNELS = 3;
  const int FILTER_SIZE = 3;
  const int FILTER_SIZE_Y = 3;
  const int FILTER_SIZE_Z = 3;

  // input image
  const int CHANNELS = 3;
  const int IMAGE_SIZE = 9;
  const int IMAGE_SIZE_Y = 9;
C
chengduoZH 已提交
2296
  const int IMAGE_SIZE_Z = 9;
2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355

  TestConfig config;
  config.biasSize = NUM_FILTERS;
  config.layerConfig.set_type(type);
  config.layerConfig.set_num_filters(NUM_FILTERS);
  config.layerConfig.set_partial_sum(1);
  config.layerConfig.set_shared_biases(true);

  // Setting up conv3D-trans layer
  LayerInputConfig* input = config.layerConfig.add_inputs();
  ConvConfig* conv = input->mutable_conv_conf();

  conv->set_channels(CHANNELS);
  conv->set_filter_size(FILTER_SIZE);
  conv->set_filter_size_y(FILTER_SIZE_Y);
  conv->set_filter_size_z(FILTER_SIZE_Z);
  conv->set_padding(0);
  conv->set_padding_y(0);
  conv->set_padding_z(0);
  conv->set_stride(2);
  conv->set_stride_y(2);
  conv->set_stride_z(2);
  conv->set_img_size(IMAGE_SIZE);
  conv->set_img_size_y(IMAGE_SIZE_Y);
  conv->set_img_size_z(IMAGE_SIZE_Z);
  conv->set_output_x(outputSize(conv->img_size(),
                                conv->filter_size(),
                                conv->padding(),
                                conv->stride(),
                                /*  caffeMode */ true));
  conv->set_output_y(outputSize(conv->img_size_y(),
                                conv->filter_size_y(),
                                conv->padding_y(),
                                conv->stride_y(),
                                /*  caffeMode */ true));
  conv->set_output_z(outputSize(conv->img_size_z(),
                                conv->filter_size_z(),
                                conv->padding_z(),
                                conv->stride_z(),
                                /*  caffeMode */ true));

  config.layerConfig.set_size(conv->output_x() * conv->output_y() *
                              conv->output_z() * NUM_FILTERS);
  conv->set_groups(1);
  conv->set_filter_channels(conv->channels() / conv->groups());
  config.inputDefs.push_back(
      {INPUT_DATA,
       "layer_0",
       CHANNELS * IMAGE_SIZE * IMAGE_SIZE_Y * IMAGE_SIZE_Z,
       conv->filter_channels() * FILTER_SIZE * FILTER_SIZE_Y * FILTER_SIZE_Z *
           NUM_FILTERS});

  testLayerGrad(config, "conv3D", 10, trans, useGpu);
  // Use small batch_size and useWeight=true to test biasGrad
  testLayerGrad(config, "conv3D", 2, trans, useGpu, true, 0.02);
}

TEST(Layer, test3DConvLayer) {
  test3DConvLayer("conv3d", /* trans= */ false, /* useGpu= */ false);
2356
#ifdef PADDLE_WITH_CUDA
2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395
  test3DConvLayer("conv3d", /* trans= */ false, /* useGpu= */ true);
#endif
}

void test3DDeConvLayer(const string& type, bool trans, bool useGpu) {
  // filter size
  const int NUM_FILTERS = 6;
  // const int CHANNELS = 3;
  const int FILTER_SIZE = 3;
  const int FILTER_SIZE_Y = 3;
  const int FILTER_SIZE_Z = 3;

  // input image
  const int CHANNELS = 3;
  const int IMAGE_SIZE = 4;
  const int IMAGE_SIZE_Y = 6;
  const int IMAGE_SIZE_Z = 6;

  // Setting up conv-trans layer
  TestConfig config;
  config.biasSize = NUM_FILTERS;
  config.layerConfig.set_type("deconv3d");
  config.layerConfig.set_num_filters(NUM_FILTERS);
  config.layerConfig.set_partial_sum(1);
  config.layerConfig.set_shared_biases(true);

  LayerInputConfig* input = config.layerConfig.add_inputs();
  ConvConfig* conv = input->mutable_conv_conf();

  conv->set_channels(CHANNELS);
  conv->set_filter_size(FILTER_SIZE);
  conv->set_filter_size_y(FILTER_SIZE_Y);
  conv->set_filter_size_z(FILTER_SIZE_Z);
  conv->set_padding(0);
  conv->set_padding_y(0);
  conv->set_padding_z(0);
  conv->set_stride(2);
  conv->set_stride_y(2);
  conv->set_stride_z(2);
2396 2397 2398 2399 2400
  conv->set_output_x(IMAGE_SIZE);
  conv->set_output_y(IMAGE_SIZE_Y);
  conv->set_output_z(IMAGE_SIZE_Z);

  conv->set_img_size(imageSize(conv->output_x(),
C
chengduoZH 已提交
2401 2402 2403 2404
                               conv->filter_size(),
                               conv->padding(),
                               conv->stride(),
                               true));
2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416
  conv->set_img_size_y(imageSize(conv->output_y(),
                                 conv->filter_size_y(),
                                 conv->padding_y(),
                                 conv->stride_y(),
                                 true));
  conv->set_img_size_z(imageSize(conv->output_z(),
                                 conv->filter_size_z(),
                                 conv->padding_z(),
                                 conv->stride_z(),
                                 true));
  config.layerConfig.set_size(conv->img_size() * conv->img_size_y() *
                              conv->img_size_z() * NUM_FILTERS);
2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432
  conv->set_groups(1);
  conv->set_filter_channels(conv->channels() / conv->groups());
  config.inputDefs.push_back(
      {INPUT_DATA,
       "layer_0",
       CHANNELS * IMAGE_SIZE * IMAGE_SIZE_Y * IMAGE_SIZE_Z,
       conv->filter_channels() * FILTER_SIZE * FILTER_SIZE_Y * FILTER_SIZE_Z *
           NUM_FILTERS});

  testLayerGrad(config, "deconv3D", 10, trans, useGpu);
  // Use small batch_size and useWeight=true to test biasGrad
  testLayerGrad(config, "deconv3D", 2, trans, useGpu, true, 0.02);
}

TEST(Layer, test3DDeConvLayer) {
  test3DDeConvLayer("deconv3d", /* trans= */ false, /* useGpu= */ false);
2433
#ifdef PADDLE_WITH_CUDA
2434 2435 2436 2437
  test3DDeConvLayer("deconv3d", /* trans= */ false, /* useGpu= */ true);
#endif
}

G
guosheng 已提交
2438
TEST(Layer, ScaleShiftLayer) {
Y
Yang Yu 已提交
2439
  // FIXME: Disable ScaleShiftLayer because it is not stable.
Y
Yang Yu 已提交
2440
  // https://github.com/PaddlePaddle/Paddle/issues/7781
Y
Yang Yu 已提交
2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453
  return;
  //  const size_t batchSize = 16;
  //  const size_t size = 32;
  //  TestConfig config;
  //  config.layerConfig.set_type("scale_shift");
  //  config.layerConfig.set_size(size);
  //  config.biasSize = 1;
  //  config.inputDefs.push_back(
  //      {INPUT_DATA, "input", /* dim= */ size, /* paraSize= */ 1});
  //  config.layerConfig.add_inputs();
  //  for (auto useGpu : {false, true}) {
  //    testLayerGrad(config, "scale_shift", batchSize, false, useGpu, false);
  //  }
G
guosheng 已提交
2454 2455
}

Y
yangyaming 已提交
2456
TEST(Layer, ScaleSubRegionLayer) {
Y
yangyaming 已提交
2457 2458 2459
  const size_t batchSize = 64;
  const size_t size = 4096;
  TestConfig config;
Y
yangyaming 已提交
2460
  config.layerConfig.set_type("scale_sub_region");
Y
yangyaming 已提交
2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473
  config.inputDefs.push_back({INPUT_DATA, "input", size, 0});
  MatrixPtr indicesV = Matrix::create(batchSize, 6, false, false);
  auto* data = indicesV->getData();
  for (size_t i = 0; i < batchSize; ++i) {
    data[i * 2] = 2;
    data[i * 2 + 1] = 4;
    data[i * 2 + 2] = 16;
    data[i * 2 + 3] = 32;
    data[i * 2 + 4] = 16;
    data[i * 2 + 5] = 32;
  }
  config.inputDefs.push_back({INPUT_SELF_DEFINE_DATA, "indices", indicesV, {}});
  LayerInputConfig* input = config.layerConfig.add_inputs();
Y
yangyaming 已提交
2474 2475 2476
  ScaleSubRegionConfig* scaleSubRegionConf =
      input->mutable_scale_sub_region_conf();
  ImageConfig* imgConf = scaleSubRegionConf->mutable_image_conf();
Y
yangyaming 已提交
2477 2478 2479
  imgConf->set_img_size(32);
  imgConf->set_img_size_y(32);
  imgConf->set_channels(4);
Y
yangyaming 已提交
2480
  scaleSubRegionConf->set_value(2.0);
Y
yangyaming 已提交
2481 2482 2483
  config.layerConfig.add_inputs();

  for (auto useGpu : {false, true}) {
Y
yangyaming 已提交
2484
    testLayerGrad(config, "scale_sub_region", batchSize, false, useGpu, false);
Y
yangyaming 已提交
2485 2486 2487
  }
}

C
caoying03 已提交
2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506
TEST(Layer, L2DistanceLayer) {
  TestConfig config;
  config.layerConfig.set_type("l2_distance");
  config.layerConfig.set_size(1);
  config.biasSize = 0;

  const size_t input_dim = 27;
  const size_t batch_size = 11;

  config.inputDefs.push_back({INPUT_DATA, "layer_0", input_dim, 0});
  config.inputDefs.push_back({INPUT_DATA, "layer_1", input_dim, 0});
  config.layerConfig.add_inputs();
  config.layerConfig.add_inputs();

  for (auto useGpu : {false, true}) {
    testLayerGrad(config, "l2_distance", batch_size, false, useGpu);
  }
}

2507 2508 2509 2510 2511
void testFactorizationMachineLayer(InputType type, bool useGpu) {
  const int FACTOR_SIZE = 10;
  TestConfig config;
  config.layerConfig.set_type("factorization_machine");
  config.layerConfig.set_factor_size(FACTOR_SIZE);
W
wangmeng28 已提交
2512 2513
  config.layerConfig.set_size(1);
  config.biasSize = 0;
2514
  config.inputDefs.push_back({type, "layer_0", 128, 1280});
2515 2516 2517 2518 2519
  config.layerConfig.add_inputs();
  testLayerGrad(config, "factorization_machine", 16, false, useGpu, false);
}

TEST(Layer, FactorizationMachineLayer) {
2520 2521 2522
  for (auto useGpu : {false, true}) {
    testFactorizationMachineLayer(INPUT_DATA, useGpu);
  }
2523
  testFactorizationMachineLayer(INPUT_SPARSE_FLOAT_VALUE_DATA, false);
2524 2525
}

Z
zhangjinchao01 已提交
2526 2527 2528 2529 2530 2531 2532
int main(int argc, char** argv) {
  testing::InitGoogleTest(&argc, argv);
  initMain(argc, argv);
  FLAGS_thread_local_rand_use_global_seed = true;
  srand(1);
  return RUN_ALL_TESTS();
}