DeConv3DLayer.cpp 7.8 KB
Newer Older
C
chengduoZH 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14
/* 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. */

C
chengduoZH 已提交
15
#include "DeConv3DLayer.h"
C
chengduoZH 已提交
16 17 18 19 20 21 22 23
#include "paddle/utils/Logging.h"
#include "paddle/utils/Stat.h"

namespace paddle {

REGISTER_LAYER(deconv3d, DeConv3DLayer);

#define DECONV_OUTPUT_SIZE(IN_SIZE, STRID, PAD, KSIZE) \
C
chengduoZH 已提交
24
  (((IN_SIZE)-1) * (STRID)-2 * (PAD) + (KSIZE))
C
chengduoZH 已提交
25 26

bool DeConv3DLayer::init(const LayerMap &layerMap,
C
chengduoZH 已提交
27
                         const ParameterMap &parameterMap) {
C
chengduoZH 已提交
28 29 30 31 32 33
  if (!ConvBaseLayer::init(layerMap, parameterMap)) return false;
  // for Deconv, the dimension of Kernel is
  // channel * output * depth * height * weigth
  // Matrix storage format: (output * depth * height * weigth) x  channel
  for (int index = 0; index < config_.inputs().size(); ++index) {
    M_.push_back(filterChannels_[index]);
C
chengduoZH 已提交
34 35 36 37 38 39 40
    K_.push_back(filterPixels_[index] * (numFilters_ / groups_[index]));
    if (weights_[index]->getW())
      weights_[index]->getW()->reshape(filterPixels_[index] * numFilters_,
                                       filterChannels_[index]);
    if (weights_[index]->getWGrad())
      weights_[index]->getWGrad()->reshape(filterPixels_[index] * numFilters_,
                                           filterChannels_[index]);
C
chengduoZH 已提交
41
  }
C
chengduoZH 已提交
42 43 44 45 46
  if (biases_->getWGrad())
    biases_->getWGrad()->reshape(biases_->getWGrad()->width_,
                                 biases_->getWGrad()->height_);
  if (biases_->getW())
    biases_->getW()->reshape(biases_->getW()->width_, biases_->getW()->height_);
C
chengduoZH 已提交
47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
  CHECK(inputLayers_.size() == parameters_.size());
  return true;
}

size_t DeConv3DLayer::getSize() {
  CHECK_NE(inputLayers_.size(), 0UL);
  // imgSizeH_.clear();
  // imgSizeW_.clear();
  // imgSizeD_.clear();
  outputH_.clear();
  outputW_.clear();
  outputD_.clear();
  N_.clear();
  No_.clear();
  size_t layerSize = 0;
  for (size_t i = 0; i < inputLayers_.size(); ++i) {
    // imgSizeH_.push_back(inputLayers_[i]->getOutput().getFrameHeight());
    // imgSizeW_.push_back(inputLayers_[i]->getOutput().getFrameWidth());
    // imgSizeD_.push_back(inputLayers_[i]->getOutput().getFrameDepth());
C
chengduoZH 已提交
66 67 68 69 70 71
    outputW_.push_back(DECONV_OUTPUT_SIZE(
        imgSizeW_[i], stride_[i], padding_[i], filterSize_[i]));
    outputH_.push_back(DECONV_OUTPUT_SIZE(
        imgSizeH_[i], strideY_[i], paddingY_[i], filterSizeY_[i]));
    outputD_.push_back(DECONV_OUTPUT_SIZE(
        imgSizeD_[i], strideZ_[i], paddingZ_[i], filterSizeZ_[i]));
C
chengduoZH 已提交
72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
    No_.push_back(outputD_[i] * outputH_[i] * outputW_[i]);
    N_.push_back(imgSizeD_[i] * imgSizeH_[i] * imgSizeW_[i]);
    CHECK(layerSize == 0 || N_[i] * size_t(numFilters_) == layerSize);
    layerSize += No_[i] * numFilters_;
  }
  getOutput().setFrameHeight(outputH_[0]);
  getOutput().setFrameWidth(outputW_[0]);
  getOutput().setFrameDepth(outputD_[0]);
  return layerSize;
}

void DeConv3DLayer::forward(PassType passType) {
  Layer::forward(passType);
  int batchSize = inputLayers_[0]->getOutputValue()->getHeight();
  int outWidth = getSize();
  resetOutput(batchSize, outWidth);
  const MatrixPtr outMat = getOutputValue();

  for (size_t i = 0; i != inputLayers_.size(); ++i) {
    REGISTER_TIMER_INFO("FwdDeConv3D", getName().c_str());
C
chengduoZH 已提交
92
    const MatrixPtr &inMat = getInputValue(i);
C
chengduoZH 已提交
93 94 95 96
    int M = M_[i];
    int N = N_[i];
    int K = K_[i];
    MatrixPtr wMat = weights_[i]->getW();
C
chengduoZH 已提交
97
    Matrix::resizeOrCreate(colBuf_, K * groups_[i], N, false, useGpu_);
C
chengduoZH 已提交
98
    for (int n = 0; n < batchSize; ++n) {
C
chengduoZH 已提交
99 100 101 102 103 104 105
      real *inData = inMat->getData() + n * inMat->getStride();
      for (int g = 0; g < groups_[i]; ++g) {
        MatrixPtr inMatSub = Matrix::create(inData, M, N, false, useGpu_);
        MatrixPtr wMatSub = wMat->subMatrix(g * K, K);
        MatrixPtr colBufDataSub = colBuf_->subMatrix(g * K, K);
        colBufDataSub->mul(*wMatSub, *inMatSub, 1.0, 0.0);
        inData += M * N;
C
chengduoZH 已提交
106
      }
C
chengduoZH 已提交
107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122
      colBuf_->col2Vol(outMat->getData() + n * outMat->getStride(),
                       numFilters_,
                       outputD_[i],
                       outputH_[i],
                       outputW_[i],
                       filterSizeZ_[i],
                       filterSizeY_[i],
                       filterSize_[i],
                       strideZ_[i],
                       strideY_[i],
                       stride_[i],
                       paddingZ_[i],
                       paddingY_[i],
                       padding_[i],
                       1.0,
                       1.0);
C
chengduoZH 已提交
123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138
    }
  }
  if (nullptr != this->biasParameter_) {
    REGISTER_TIMER_INFO("FwBiasTimer", getName().c_str());
    this->addBias();
  }
  forwardActivation();
}

void DeConv3DLayer::backward(const UpdateCallback &callback) {
  backwardActivation();
  int batchSize = getOutputGrad()->getHeight();
  if (biases_ && biases_->getWGrad()) {
    bpropBiases();
    biases_->getParameterPtr()->incUpdate(callback);
  }
C
chengduoZH 已提交
139 140 141 142 143
  for (size_t i = 0; i < inputLayers_.size(); ++i) {
    if (weights_[i]->getWGrad() || this->needGradient_) {
      int M = M_[i];
      int N = N_[i];
      int K = K_[i];
C
chengduoZH 已提交
144
      REGISTER_TIMER_INFO("BwdDeConv3D", getName().c_str());
C
chengduoZH 已提交
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
      Matrix::resizeOrCreate(colBuf_, K * groups_[i], N, false, useGpu_);
      const MatrixPtr &inMat = getInputValue(i);
      for (int n = 0; n < batchSize; ++n) {
        colBuf_->vol2Col(
            getOutputGrad()->getData() + n * getOutputGrad()->getStride(),
            numFilters_,
            outputD_[i],
            outputH_[i],
            outputW_[i],
            filterSizeZ_[i],
            filterSizeY_[i],
            filterSize_[i],
            strideZ_[i],
            strideY_[i],
            stride_[i],
            paddingZ_[i],
            paddingY_[i],
            padding_[i]);
        if (weights_[i]->getWGrad()) {
          real *inData = inMat->getData() + n * inMat->getStride();
          for (int g = 0; g < groups_[i]; ++g) {
            MatrixPtr colBufDataSub = colBuf_->subMatrix(g * K, K);
            MatrixPtr wGradMatSub =
                weights_[i]->getWGrad()->subMatrix(g * K, K);
            MatrixPtr inMatSub = Matrix::create(inData, M, N, false, useGpu_);
            wGradMatSub->mul(
                *colBufDataSub, *(inMatSub->getTranspose()), 1.0, 1.0);
            inData += M * N;
          }
C
chengduoZH 已提交
174
        }
C
chengduoZH 已提交
175 176 177 178 179 180 181 182 183 184 185
        if (getInputGrad(i)) {
          real *preGrad =
              getInputGrad(i)->getData() + n * getInputGrad(i)->getStride();
          for (int g = 0; g < groups_[i]; ++g) {
            MatrixPtr w = weights_[i]->getW()->subMatrix(g * K, K);
            MatrixPtr outGradMat = colBuf_->subMatrix(g * K, K);
            MatrixPtr inGradMatSub =
                Matrix::create(preGrad, M, N, false, useGpu_);
            inGradMatSub->mul(*(w->getTranspose()), *outGradMat, 1.0, 1.0);
            preGrad += M * N;
          }
C
chengduoZH 已提交
186 187 188
        }
      }
      REGISTER_TIMER_INFO("WeightUpdate", getName().c_str());
C
chengduoZH 已提交
189
      weights_[i]->getParameterPtr()->incUpdate(callback);
C
chengduoZH 已提交
190 191 192
    }
  }
}
C
chengduoZH 已提交
193 194
void DeConv3DLayer::bpropWeights(int i) {}
void DeConv3DLayer::bpropData(int i) {}
C
chengduoZH 已提交
195 196

void DeConv3DLayer::bpropBiases() {
C
chengduoZH 已提交
197
  const MatrixPtr &outGradMat = getOutputGrad();
C
chengduoZH 已提交
198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215

  if (this->sharedBiases_) {
    biases_->getWGrad()->collectSharedBias(*outGradMat, 1.0f);
  } else {
    biases_->getWGrad()->collectBias(*outGradMat, 1.0f);
  }
}

void DeConv3DLayer::addBias() {
  MatrixPtr outMat = getOutputValue();
  if (this->sharedBiases_) {
    outMat->addSharedBias(*(biases_->getW()), 1.0f);
  } else {
    outMat->addBias(*(biases_->getW()), 1.0f);
  }
}

}  // namespace paddle