test_WarpCTCLayer.cpp 7.5 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
/* Copyright (c) 2016 Baidu, Inc. All Rights Reserve.

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 <paddle/utils/Version.h>
#include "paddle/gserver/layers/Layer.h"
#include "paddle/gserver/layers/DataLayer.h"
#include "paddle/gserver/layers/CTCLayer.h"
#include "paddle/gserver/layers/WarpCTCLayer.h"
#include "ModelConfig.pb.h"

#include "TestUtil.h"

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

P_DECLARE_bool(use_gpu);

const real* getData(const Matrix& matrix) {
  if (matrix.useGpu()) {
    MatrixPtr cpuMatrix = Matrix::create(
L
Liu Yiqun 已提交
33
        matrix.getHeight(), matrix.getWidth(), matrix.isTransposed(), false);
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 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 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 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 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202
    cpuMatrix->copyFrom(matrix);
    return cpuMatrix->getData();
  } else {
    return matrix.getData();
  }
}

void checkError(const Matrix& matrix1, const Matrix& matrix2) {
  CHECK_EQ(matrix1.getHeight(), matrix2.getHeight());
  CHECK_EQ(matrix1.getWidth(), matrix2.getWidth());
  CHECK_EQ(matrix1.isTransposed(), matrix2.isTransposed());
#ifndef PADDLE_TYPE_DOUBLE
  real err = 1e-3;
#else
  real err = 1e-10;
#endif

  int height = matrix1.getHeight();
  int width = matrix1.getWidth();

  const real* data1 = getData(matrix1);
  const real* data2 = getData(matrix2);
  int count = 0;
  for (int i = 0; i < height; i++) {
    for (int j = 0; j < width; j++) {
      if (fabs(data1[i * width + j] - data2[i * width + j]) > err) {
        count++;
      }
    }
  }
  EXPECT_EQ(count, 0) << "There are " << count << " different element.";
}

void initArgument(size_t batchSize,
                  int layerSize,
                  bool useGpu,
                  Argument& data) {
  data.value = Matrix::create(batchSize, layerSize, false, useGpu);
  data.grad = Matrix::create(batchSize, layerSize, false, useGpu);
  data.value->randomizeUniform();
  data.value->add(-0.5);
  /// data.value->sigmoid(*data.value);
  data.grad->zeroMem();

  generateSequenceStartPositions(batchSize, data.sequenceStartPositions);
}

LayerPtr createDataLayer(
    string name, size_t batchSize, int layerSize, bool useGpu, Argument& data) {
  LayerConfig layerConfig;
  layerConfig.set_name(name);
  layerConfig.set_type("data");
  layerConfig.set_size(layerSize);
  LayerPtr layer = LayerPtr(new DataLayer(layerConfig));

  DataLayerPtr dataLayer = std::dynamic_pointer_cast<DataLayer>(layer);
  dataLayer->setData(data);
  dataLayer->forward(PASS_GC);

  /// std::cout << "dataLayer: " << std::endl;
  /// (dataLayer->getOutput().value)->print(std::cout);

  return layer;
}

LayerPtr createLabelLayer(string name,
                          size_t batchSize,
                          size_t numClasses,
                          bool useGpu) {
  LayerConfig layerConfig;
  layerConfig.set_name(name);
  layerConfig.set_type("data");
  layerConfig.set_size(1);
  LayerPtr layer = LayerPtr(new DataLayer(layerConfig));

  Argument data;
  data.ids = IVector::create(batchSize, useGpu);
  data.ids->rand(numClasses - 1);

  generateSequenceStartPositions(batchSize, data.sequenceStartPositions);

  DataLayerPtr labelLayer = std::dynamic_pointer_cast<DataLayer>(layer);
  labelLayer->setData(data);
  labelLayer->forward(PASS_GC);

  return layer;
}

LayerPtr createCTCLayer(string name,
                        size_t numClasses,
                        bool useGpu,
                        bool normByTimes,
                        LayerPtr dataLayer,
                        LayerPtr labelLayer) {
  LayerMap layerMap;
  layerMap[dataLayer->getName()] = dataLayer;
  layerMap[labelLayer->getName()] = labelLayer;

  ParameterMap parameterMap;

  LayerConfig layerConfig;
  layerConfig.set_name(name);
  layerConfig.set_type("ctc");
  layerConfig.set_size(numClasses);
  layerConfig.set_norm_by_times(normByTimes);

  layerConfig.add_inputs();
  LayerInputConfig& input0 = *(layerConfig.mutable_inputs(0));
  input0.set_input_layer_name(dataLayer->getName());

  layerConfig.add_inputs();
  LayerInputConfig& input1 = *(layerConfig.mutable_inputs(1));
  input1.set_input_layer_name(labelLayer->getName());

  LayerPtr layer = LayerPtr(new CTCLayer(layerConfig));
  layerMap[layer->getName()] = layer;
  layer->init(layerMap, parameterMap);

  ActivationFunction* softmaxActivation = ActivationFunction::create("softmax");

  softmaxActivation->forward(dataLayer->getOutput());
  layer->forward(PASS_GC);

  layer->backward();
  softmaxActivation->backward(dataLayer->getOutput());

  return layer;
}

LayerPtr createWarpCTCLayer(string name,
                            size_t numClasses,
                            bool useGpu,
                            bool normByTimes,
                            LayerPtr dataLayer,
                            LayerPtr labelLayer) {
  LayerMap layerMap;
  layerMap[dataLayer->getName()] = dataLayer;
  layerMap[labelLayer->getName()] = labelLayer;

  ParameterMap parameterMap;

  LayerConfig layerConfig;
  layerConfig.set_name(name);
  layerConfig.set_type("warp_ctc");
  layerConfig.set_size(numClasses);
  layerConfig.set_blank(numClasses - 1);
  layerConfig.set_norm_by_times(normByTimes);

  layerConfig.add_inputs();
  LayerInputConfig& input0 = *(layerConfig.mutable_inputs(0));
  input0.set_input_layer_name(dataLayer->getName());

  layerConfig.add_inputs();
  LayerInputConfig& input1 = *(layerConfig.mutable_inputs(1));
  input1.set_input_layer_name(labelLayer->getName());

  LayerPtr layer = LayerPtr(new WarpCTCLayer(layerConfig));
  layerMap[layer->getName()] = layer;
  layer->init(layerMap, parameterMap);

  layer->forward(PASS_GC);
  layer->backward();

  return layer;
}

TEST(Layer, WarpCTCLayer) {
  for (auto layerSize : {10, 64, 128}) {
    for (auto batchSize : {1, 10, 20, 64}) {
L
Liu Yiqun 已提交
203 204
      for (auto normByTimes : {false, true}) {
        for (auto useGpu : {false, true}) {
205
#ifdef PADDLE_ONLY_CPU
L
Liu Yiqun 已提交
206
          if (useGpu) continue;
207
#endif
L
Liu Yiqun 已提交
208 209
          LOG(INFO) << " layerSize=" << layerSize << " batchSize=" << batchSize
                    << " normByTimes = " << normByTimes << " useGpu=" << useGpu;
210

L
Liu Yiqun 已提交
211
          FLAGS_use_gpu = useGpu;
212

L
Liu Yiqun 已提交
213 214
          Argument data0;
          initArgument(batchSize, layerSize, useGpu, data0);
215

L
Liu Yiqun 已提交
216 217
          Argument data1;
          data1.resizeAndCopyFrom(data0);
218

L
Liu Yiqun 已提交
219 220 221 222
          LayerPtr dataLayer0 =
              createDataLayer("data", batchSize, layerSize, useGpu, data0);
          LayerPtr dataLayer1 =
              createDataLayer("data", batchSize, layerSize, useGpu, data1);
223

L
Liu Yiqun 已提交
224 225
          LayerPtr labelLayer =
              createLabelLayer("label", batchSize, layerSize, useGpu);
226

L
Liu Yiqun 已提交
227 228 229 230
          LayerPtr warpctcLayer = createWarpCTCLayer(
              "cost", layerSize, useGpu, normByTimes, dataLayer0, labelLayer);
          LayerPtr ctcLayer = createCTCLayer(
              "cost", layerSize, useGpu, normByTimes, dataLayer1, labelLayer);
231

L
Liu Yiqun 已提交
232 233 234
          /// Check loss
          checkError(*(warpctcLayer->getOutput().value),
                     *(ctcLayer->getOutput().value));
235

L
Liu Yiqun 已提交
236 237 238 239
          /// Check gradients
          checkError(*(dataLayer0->getOutput().grad),
                     *(dataLayer1->getOutput().grad));
        }
240 241 242 243 244 245 246 247 248 249
      }
    }
  }
}

int main(int argc, char** argv) {
  testing::InitGoogleTest(&argc, argv);
  initMain(argc, argv);
  return RUN_ALL_TESTS();
}