test_SeqSliceLayerGrad.cpp 7.0 KB
Newer Older
1
/* Copyright (c) 2016 Baidu, Inc. All Rights Reserved.
C
caoying03 已提交
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */

#include <gtest/gtest.h>
#include "ModelConfig.pb.h"
X
Xin Pan 已提交
17
#include "paddle/legacy/gserver/layers/DataLayer.h"
C
caoying03 已提交
18 19 20 21 22 23 24 25 26 27

#include "LayerGradUtil.h"
#include "paddle/testing/TestUtil.h"

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

DECLARE_int32(gpu_id);
DECLARE_bool(thread_local_rand_use_global_seed);

C
caoying03 已提交
28 29 30
const int MAX_SEQ_NUM = 17;
const int MAX_SEQ_LEN = 23;
const int MAX_BEAM_SIZE = 13;
C
caoying03 已提交
31

32 33
const size_t SEED = (size_t)(time(NULL));

C
caoying03 已提交
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
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;
}

void genSeqInfo(vector<int>& seqStartPos, vector<int>& subSeqStartPos) {
  seqStartPos.resize(1, 0);
  subSeqStartPos.resize(1, 0);

50
  srand(SEED);
C
caoying03 已提交
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107
  int seqNum = 1 + (rand() % MAX_SEQ_NUM);
  for (int i = 0; i < seqNum; ++i) {
    int subSeqNum = 1 + (rand() % MAX_SEQ_NUM);
    for (int j = 0; j < subSeqNum; ++j)
      subSeqStartPos.push_back(subSeqStartPos.back() +
                               (1 + (rand() % MAX_SEQ_LEN)));
    seqStartPos.push_back(subSeqStartPos.back());
  }
}

/*
  generate start indices according to sequence start positions.
 */
void genStarts(vector<int>& seqStartPos,
               vector<vector<real>>& starts,
               size_t beamSize) {
  starts.clear();
  starts.resize(seqStartPos.size() - 1, vector<real>(beamSize, -1.));

  for (size_t i = 0; i < seqStartPos.size() - 1; ++i) {
    int seqLen = seqStartPos[i + 1] - seqStartPos[i];
    vector<real> randStarts =
        randSampling(seqLen, min(seqLen, static_cast<int>(beamSize)));
    copy(begin(randStarts), end(randStarts), begin(starts[i]));
  }
}

/*
  generate end indices according to sequence start positions and start indices.
 */
void genEnds(vector<int>& seqStartPos,
             vector<vector<real>>& starts,
             vector<vector<real>>& ends,
             size_t beamSize) {
  CHECK_EQ(seqStartPos.size() - 1, starts.size());
  ends.clear();
  ends.resize(seqStartPos.size() - 1, vector<real>(beamSize, -1.));

  for (size_t i = 0; i < starts.size(); ++i) {
    for (size_t j = 0; j < starts[i].size(); ++j) {
      int seqLen = seqStartPos[i + 1] - seqStartPos[i];
      CHECK_GE(seqLen - 1, starts[i][j]);
      if (starts[i][j] == -1.) break;
      if (starts[i][j] == (seqLen - 1)) {
        ends[i][j] = starts[i][j];
      } else {
        ends[i][j] = starts[i][j] + randSampling(seqLen - starts[i][j], 1)[0];
      }
    }
  }
}

void genTestData(vector<int>& seqStartPos,
                 vector<int>& subSeqStartPos,
                 vector<vector<real>>& starts,
                 vector<vector<real>>& ends,
                 bool hasSubseq) {
C
caoying03 已提交
108
  size_t beamSize = 1 + (rand() % MAX_BEAM_SIZE);
C
caoying03 已提交
109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169
  genSeqInfo(seqStartPos, subSeqStartPos);

  genStarts(hasSubseq ? subSeqStartPos : seqStartPos, starts, beamSize);
  genEnds(hasSubseq ? subSeqStartPos : seqStartPos, starts, ends, beamSize);
}

template <typename T>
void flatten2dVector(vector<vector<T>>& inVec, vector<T>& outVec) {
  size_t totalSize{0};
  for (auto const& items : inVec) totalSize += items.size();
  outVec.reserve(totalSize);

  for (auto& items : inVec)
    move(items.begin(), items.end(), back_inserter(outVec));
}

void testSeqSliceLayer(bool hasSubseq,
                       bool useGpu,
                       vector<int>& seqStartPos,
                       vector<int>& subSeqStartPos,
                       vector<vector<real>>& starts,
                       vector<vector<real>>& ends) {
  // layer size is not crutial for this layer,
  // so here use a small layer size in the unittest.
  const size_t layerSize{4};
  TestConfig config;
  config.layerConfig.set_type("seq_slice");
  config.layerConfig.set_size(layerSize);

  // add the first input
  MatrixPtr seqInputPtr =
      Matrix::create(hasSubseq ? subSeqStartPos.back() : seqStartPos.back(),
                     layerSize,
                     false,
                     false);
  seqInputPtr->randomizeUniform();

  if (hasSubseq) {
    config.inputDefs.push_back({INPUT_SELF_DEFINE_DATA,
                                "seq_input",
                                seqInputPtr,
                                seqStartPos,
                                subSeqStartPos});
  } else {
    config.inputDefs.push_back(
        {INPUT_SELF_DEFINE_DATA, "seq_input", seqInputPtr, seqStartPos});
  }
  config.layerConfig.add_inputs();

  // add start indices
  if (starts.size()) {
    vector<real> startsToVec;
    flatten2dVector(starts, startsToVec);

    MatrixPtr startMatrixPtr =
        Matrix::create(starts.size(), starts[0].size(), false, false);
    startMatrixPtr->copyFrom(startsToVec.data(), startsToVec.size());

    config.inputDefs.push_back(
        {INPUT_SELF_DEFINE_DATA, "starts", startMatrixPtr});
    config.layerConfig.add_inputs();
C
caoying03 已提交
170
    config.layerConfig.set_select_first(true);
C
caoying03 已提交
171 172 173 174 175 176
  }

  // add end indices
  if (ends.size()) {
    vector<real> endsToVec;
    flatten2dVector(ends, endsToVec);
C
caoying03 已提交
177

C
caoying03 已提交
178 179
    MatrixPtr endMatrixPtr =
        Matrix::create(ends.size(), ends[0].size(), false, false);
C
caoying03 已提交
180 181
    endMatrixPtr->copyFrom(endsToVec.data(), endsToVec.size());

C
caoying03 已提交
182 183
    config.inputDefs.push_back({INPUT_SELF_DEFINE_DATA, "ends", endMatrixPtr});
    config.layerConfig.add_inputs();
C
caoying03 已提交
184
    config.layerConfig.set_select_first(false);
C
caoying03 已提交
185 186 187 188 189 190 191 192 193 194 195
  }

  testLayerGrad(config, "seq_slice", /*batchSize*/ 100, false, useGpu, false);
}

TEST(Layer, SeqSliceLayer) {
  vector<int> seqStartPos;
  vector<int> subSeqStartPos;
  vector<vector<real>> starts;
  vector<vector<real>> ends;

C
caoying03 已提交
196
  std::vector<bool> mode = {false};
197
#ifdef PADDLE_WITH_CUDA
C
caoying03 已提交
198 199
  mode.push_back(true);
#endif
C
caoying03 已提交
200
  genSeqInfo(seqStartPos, subSeqStartPos);
C
caoying03 已提交
201 202
  for (bool hasSubseq : {true, false}) {
    LOG(INFO) << "hasSubSeq : " << hasSubseq;
C
caoying03 已提交
203
    genTestData(seqStartPos, subSeqStartPos, starts, ends, hasSubseq);
C
caoying03 已提交
204
    for (bool useGpu : mode) {
C
caoying03 已提交
205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224
      vector<vector<real>> tmp;
      testSeqSliceLayer(
          hasSubseq, useGpu, seqStartPos, subSeqStartPos, tmp, ends);
      testSeqSliceLayer(
          hasSubseq, useGpu, seqStartPos, subSeqStartPos, starts, tmp);
      testSeqSliceLayer(
          hasSubseq, useGpu, seqStartPos, subSeqStartPos, starts, ends);
    }
  }
}

int main(int argc, char** argv) {
  initMain(argc, argv);
  hl_start();
  hl_init(FLAGS_gpu_id);
  FLAGS_thread_local_rand_use_global_seed = true;
  srand(1);
  testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}