test_WarpCTCLayer.cpp 7.5 KB
Newer Older
1
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve.
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 <paddle/utils/Version.h>
Y
Yu Yang 已提交
17
#include "ModelConfig.pb.h"
18
#include "paddle/gserver/layers/CTCLayer.h"
Y
Yu Yang 已提交
19 20
#include "paddle/gserver/layers/DataLayer.h"
#include "paddle/gserver/layers/Layer.h"
21 22 23 24 25 26 27
#include "paddle/gserver/layers/WarpCTCLayer.h"

#include "TestUtil.h"

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

28
DECLARE_bool(use_gpu);
29 30 31 32

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
    cpuMatrix->copyFrom(matrix);
    return cpuMatrix->getData();
  } else {
    return matrix.getData();
  }
}

41
int checkError(const Matrix& matrix1, const Matrix& matrix2) {
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
  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.";
65
  return count;
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
}

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.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);

  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) {
198 199
  for (auto layerSize : {10, 64}) {
    for (auto batchSize : {1, 10, 32}) {
L
Liu Yiqun 已提交
200 201
      for (auto normByTimes : {false, true}) {
        for (auto useGpu : {false, true}) {
202
#ifdef PADDLE_ONLY_CPU
L
Liu Yiqun 已提交
203
          if (useGpu) continue;
204
#endif
205
          LOG(INFO) << "layerSize=" << layerSize << " batchSize=" << batchSize
L
Liu Yiqun 已提交
206
                    << " normByTimes = " << normByTimes << " useGpu=" << useGpu;
207

L
Liu Yiqun 已提交
208
          FLAGS_use_gpu = useGpu;
209

L
Liu Yiqun 已提交
210 211
          Argument data0;
          initArgument(batchSize, layerSize, useGpu, data0);
212

L
Liu Yiqun 已提交
213 214
          Argument data1;
          data1.resizeAndCopyFrom(data0);
215

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

L
Liu Yiqun 已提交
221 222
          LayerPtr labelLayer =
              createLabelLayer("label", batchSize, layerSize, useGpu);
223

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

229 230 231 232 233
          /// Check cost
          LOG(INFO) << "Check cost: "
                    << checkError(*(warpctcLayer->getOutput().value),
                                  *(ctcLayer->getOutput().value))
                    << " different elements.";
234

L
Liu Yiqun 已提交
235
          /// Check gradients
236 237 238 239
          LOG(INFO) << "Check gradients: "
                    << checkError(*(dataLayer0->getOutput().grad),
                                  *(dataLayer1->getOutput().grad))
                    << " different elements";
L
Liu Yiqun 已提交
240
        }
241 242 243 244
      }
    }
  }
}