WarpCTCLayer.cpp 7.8 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 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 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

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 "WarpCTCLayer.h"

namespace paddle {

REGISTER_LAYER(warp_ctc, WarpCTCLayer);

bool WarpCTCLayer::init(const LayerMap& layerMap,
                        const ParameterMap& parameterMap) {
  /* Initialize the basic parament class */
  Layer::init(layerMap, parameterMap);

  CHECK_EQ(inputLayers_.size(), 2UL);

  /* The inputLayers_[0] must be sequence output without softmax */
  numClasses_ = config_.size();
  CHECK_GE(numClasses_, 2UL);
  CHECK_EQ(numClasses_, inputLayers_[0]->getSize());

  blank_ = config_.blank();
  CHECK_LT(blank_, numClasses_);

  normByTimes_ = config_.norm_by_times();

  // We don't need sequenceStartPositions because each sample of output_ is
  // for the cost of one sequence.
  setNeedSequenceInfo(false);

  return true;
}

void WarpCTCLayer::forward(PassType passType) {
  Layer::forward(passType);

  const Argument& output = getInput(0);
  const Argument& labels = getInput(1);

  CHECK(output.sequenceStartPositions);
  CHECK(labels.sequenceStartPositions);
  CHECK(labels.ids);

  size_t numSequences = labels.sequenceStartPositions->getSize() - 1;
  CHECK_EQ(numSequences, output.sequenceStartPositions->getSize() - 1);

  resizeOutput(numSequences, 1);

  const int* cpuLabelStartPositions =
      labels.sequenceStartPositions->getData(false);
  const int* cpuOutputStartPositions =
      output.sequenceStartPositions->getData(false);

  std::vector<int> cpuLabelLengths(numSequences);
  std::vector<int> cpuOutputLengths(numSequences);
  for (size_t i = 0; i < numSequences; i++) {
    cpuLabelLengths[i] =
        cpuLabelStartPositions[i + 1] - cpuLabelStartPositions[i];
    cpuOutputLengths[i] =
        cpuOutputStartPositions[i + 1] - cpuOutputStartPositions[i];
  }

  /* Get the maximum sequence length */
  maxSequenceLength_ = 0;
  maxSequenceLength_ = *std::max_element(
      cpuOutputLengths.data(), cpuOutputLengths.data() + numSequences);

  Matrix::resizeOrCreate(batchValue_,
                         /* height */ numSequences * maxSequenceLength_,
                         /* width */ numClasses_,
                         /* trans */ false,
                         /* useGpu */ useGpu_);

  Matrix::resizeOrCreate(batchGrad_,
                         /* height */ numSequences * maxSequenceLength_,
                         /* width */ numClasses_,
                         /* trans */ false,
                         /* useGpu */ useGpu_);
  batchGrad_->zeroMem();

  seq2batchPadding(output.value, batchValue_, output.sequenceStartPositions);

  /* labels always in CPU memory */
  IVector::resizeOrCreate(cpuLabels_,
                          /* size */ (labels.ids)->getSize(),
                          /* useGpu */ false);
  cpuLabels_->copyFrom(*(labels.ids));

  /* labels always in CPU memory */
  Matrix::resizeOrCreate(cpuCosts_,
L
Liu Yiqun 已提交
102 103
                         /* height */ numSequences,
                         /* width */ 1,
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 203 204 205 206 207 208 209 210
                         /* trans */ false,
                         /* useGpu */ false);

  /* Init warp-ctc options */
  hl_warpctc_options_t options;
  hl_warpctc_init(blank_, useGpu_, &options);

  /* Get the needed workspace size */
  size_t workspaceBytes = 0;
  hl_warpctc_get_workspace_size(cpuLabelLengths.data(),
                                cpuOutputLengths.data(),
                                numClasses_,
                                numSequences,
                                &options,
                                &workspaceBytes);
  CHECK_GT(workspaceBytes, 0UL);

  size_t workspaceLength = workspaceBytes / sizeof(real) + 1;
  Vector::resizeOrCreate(workspace_,
                         /* size */ workspaceLength,
                         /* useGpu */ useGpu_);

  hl_warpctc_compute_loss(batchValue_->getData(),
                          batchGrad_->getData(),
                          cpuLabels_->getData(),
                          cpuLabelLengths.data(),
                          cpuOutputLengths.data(),
                          numClasses_,
                          numSequences,
                          cpuCosts_->getData(),
                          workspace_->getData(),
                          &options);

  /* Copy the costs */
  output_.value->copyFrom(*cpuCosts_);
}

void WarpCTCLayer::backward(const UpdateCallback& callback) {
  (void)callback;

  const Argument& output = getInput(0);
  CHECK(batchGrad_);

  batch2seqPadding(
      output.grad, batchGrad_, output.sequenceStartPositions, normByTimes_);
}

void WarpCTCLayer::seq2batchPadding(const MatrixPtr& seqValue,
                                    MatrixPtr& batchValue,
                                    const ICpuGpuVectorPtr& seqStartPositions) {
  size_t numSequences = seqStartPositions->getSize() - 1;
  const int* seqStartPositionsData = seqStartPositions->getData(useGpu_);

  real* seqData = seqValue->getData();
  real* batchData = batchValue->getData();
  if (useGpu_) {
    hl_sequence2batch_copy_padding(batchData,
                                   seqData,
                                   seqStartPositionsData,
                                   numClasses_,
                                   maxSequenceLength_,
                                   numSequences,
                                   false,
                                   true);
  } else {
    for (size_t i = 0; i < maxSequenceLength_; i++) {
      for (size_t j = 0; j < numSequences; j++) {
        size_t sequenceStart = seqStartPositionsData[j];
        size_t sequenceLength =
            seqStartPositionsData[j + 1] - seqStartPositionsData[j];
        if (i < sequenceLength) {
          memcpy(batchData + (i * numSequences + j) * numClasses_,
                 seqData + (sequenceStart + i) * numClasses_,
                 numClasses_ * sizeof(real));
        } else {
          memset(batchData + (i * numSequences + j) * numClasses_,
                 0,
                 numClasses_ * sizeof(real));
        }
      }
    }
  }
}

void WarpCTCLayer::batch2seqPadding(const MatrixPtr& seqValue,
                                    MatrixPtr& batchValue,
                                    const ICpuGpuVectorPtr& seqStartPositions,
                                    bool normByTimes) {
  size_t numSequences = seqStartPositions->getSize() - 1;
  const int* seqStartPositionsData = seqStartPositions->getData(useGpu_);

  real* seqData = seqValue->getData();
  real* batchData = batchValue->getData();
  if (useGpu_) {
    hl_sequence2batch_copy_padding(batchData,
                                   seqData,
                                   seqStartPositionsData,
                                   numClasses_,
                                   maxSequenceLength_,
                                   numSequences,
                                   normByTimes,
                                   false);
  } else {
    for (size_t i = 0; i < numSequences; i++) {
      int sequenceStart = seqStartPositionsData[i];
      int sequenceLength =
          seqStartPositionsData[i + 1] - seqStartPositionsData[i];
L
Liu Yiqun 已提交
211
      real scale = normByTimes ? (1.0f / (real)sequenceLength) : 1.0f;
212
      for (int j = 0; j < sequenceLength; j++) {
L
Liu Yiqun 已提交
213 214 215
        for (size_t k = 0; k < numClasses_; k++) {
          seqData[(sequenceStart + j) * numClasses_ + k] =
              batchData[(j * numSequences + i) * numClasses_ + k] * scale;
216 217 218 219 220 221 222
        }
      }
    }
  }
}

}  // namespace paddle