BatchNormalizationLayer.cpp 8.7 KB
Newer Older
1
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.
Z
zhangjinchao01 已提交
2 3 4 5 6 7 8 9 10 11 12 13 14 15

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 "paddle/utils/Stat.h"
16
#ifdef PADDLE_WITH_CUDA
Z
zhangjinchao01 已提交
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
#include "hl_batch_transpose.h"
#endif
#include "BatchNormalizationLayer.h"

namespace paddle {

REGISTER_LAYER(batch_norm, BatchNormalizationLayer);

bool BatchNormalizationLayer::init(const LayerMap& layerMap,
                                   const ParameterMap& parameterMap) {
  /* Initialize the basic parent class */
  if (!BatchNormBaseLayer::init(layerMap, parameterMap)) return false;

  return true;
}

void BatchNormalizationLayer::calMeanAndStd(const MatrixPtr& mat) {
  int numSamples = mat->getHeight();
  Matrix::resizeOrCreate(tmpMat_, numSamples, channels_, false, useGpu_);
  savedMean_->zeroMem();
  savedMean_->accumulateColSum(*mat);
  savedMean_->mulScalar(1.0 / numSamples);  // E[x]

  tmpMat_->assign(*mat);
H
hedaoyuan 已提交
41
  tmpMat_->square2();
Z
zhangjinchao01 已提交
42 43
  savedInvVar_->zeroMem();
  savedInvVar_->accumulateColSum(*tmpMat_);
44 45
  savedInvVar_->mulScalar(1.0 / numSamples);   // E[x^2]
  savedInvVar_->addSquare(*savedMean_, -1.0);  // E[x^2] - E^2[x]
Z
zhangjinchao01 已提交
46 47 48 49 50 51 52 53

  // Variance may be small negative value
  // because of the subtraction operation.
  // Here using clipping.
  savedInvVar_->downClip(real(0.0));

  calMovingMeanAndVar();

54
  savedInvVar_->subScalar(-epsilon_);
H
hedaoyuan 已提交
55
  savedInvVar_->sqrt2(*savedInvVar_);
Z
zhangjinchao01 已提交
56 57 58 59
}

void BatchNormalizationLayer::calMovingMeanAndVar() {
  // calculating and saving moving mean and variance
Y
Yu Yang 已提交
60 61 62 63 64 65 66 67
  auto& movingMean = movingMean_->getW();
  auto& movingVar = movingVar_->getW();
  // movingMean =  movingMean * movingAvgFraction_
  //            + savedMean_ * (1 - movingAvgFraction_)
  movingMean->add(*savedMean_, movingAvgFraction_, 1.0 - movingAvgFraction_);
  // movingVar =  movingVar * movingAvgFraction_
  //           + savedInvVar_ * (1 - movingAvgFraction_)
  movingVar->add(*savedInvVar_, movingAvgFraction_, 1.0 - movingAvgFraction_);
Z
zhangjinchao01 已提交
68 69 70 71 72 73 74
}

void BatchNormalizationLayer::setMeanAndStd() {
  savedMean_->copyFrom(*(movingMean_->getW()));
  savedInvVar_->copyFrom(*(movingVar_->getW()));
  savedInvVar_->downClip(real(0.0));

75
  savedInvVar_->subScalar(-epsilon_);
H
hedaoyuan 已提交
76
  savedInvVar_->sqrt2(*savedInvVar_);
Z
zhangjinchao01 已提交
77 78 79 80 81 82 83 84 85 86 87 88 89 90
}

void BatchNormalizationLayer::expandMat(const MatrixPtr& in, MatrixPtr& out) {
  CHECK_EQ(in->getWidth(), static_cast<size_t>(channels_ * imgPixels_));
  CHECK_EQ(out->getWidth(), static_cast<size_t>(channels_));
  CHECK(!in->isTransposed());
  CHECK(!out->isTransposed());
  if (imgPixels_ == 1) {
    out->assign(*in);
    return;
  }
  size_t batchSize = in->getHeight();
  CHECK_EQ(out->getHeight(), batchSize * imgPixels_);
  if (useGpu_) {
91
#ifndef PADDLE_WITH_CUDA
Z
zhangjinchao01 已提交
92 93
    LOG(FATAL) << "paddle is compiled only for cpu";
#else
94 95
    batchTranspose(
        in->getData(), out->getData(), imgPixels_, channels_, batchSize);
Z
zhangjinchao01 已提交
96 97 98 99
#endif
  } else {
    for (size_t i = 0; i < batchSize; i++) {
      const MatrixPtr inTmp =
100 101 102 103 104
          Matrix::create(in->getData() + i * imgPixels_ * channels_,
                         channels_,
                         imgPixels_,
                         false,
                         useGpu_);
Z
zhangjinchao01 已提交
105 106
      MatrixPtr outTmp =
          Matrix::create(out->getData() + i * imgPixels_ * channels_,
107 108 109 110
                         imgPixels_,
                         channels_,
                         false,
                         useGpu_);
Z
zhangjinchao01 已提交
111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127
      inTmp->transpose(outTmp, false);
    }
  }
}

void BatchNormalizationLayer::shrinkMat(const MatrixPtr& in, MatrixPtr& out) {
  CHECK_EQ(in->getWidth(), static_cast<size_t>(channels_));
  CHECK_EQ(out->getWidth(), static_cast<size_t>(channels_ * imgPixels_));
  size_t batchSize = out->getHeight();
  CHECK(!in->isTransposed());
  CHECK(!out->isTransposed());
  if (imgPixels_ == 1) {
    out->assign(*in);
    return;
  }
  CHECK_EQ(in->getHeight(), static_cast<size_t>(batchSize * imgPixels_));
  if (useGpu_) {
128
#ifndef PADDLE_WITH_CUDA
Z
zhangjinchao01 已提交
129 130
    LOG(FATAL) << "paddle is compiled only for cpu";
#else
131 132
    batchTranspose(
        in->getData(), out->getData(), channels_, imgPixels_, batchSize);
Z
zhangjinchao01 已提交
133 134 135 136
#endif
  } else {
    for (size_t i = 0; i < batchSize; i++) {
      const MatrixPtr inTmp =
137 138 139 140 141
          Matrix::create(in->getData() + i * channels_ * imgPixels_,
                         imgPixels_,
                         channels_,
                         false,
                         useGpu_);
Z
zhangjinchao01 已提交
142
      MatrixPtr outTmp =
143 144 145 146
          Matrix::create(out->getData() + i * imgPixels_ * channels_,
                         channels_,
                         imgPixels_,
                         useGpu_);
Z
zhangjinchao01 已提交
147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164
      inTmp->transpose(outTmp, false);
    }
  }
}

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

  int batchSize = getInputValue(0)->getHeight();
  calFeatureMapSize();
  resetOutput(batchSize, getInputValue(0)->getWidth());

  // for testing in training peroid.
  useGlobalStats_ = (passType == PASS_TEST);
  if (passType == PASS_TEST && config_.has_use_global_stats()) {
    useGlobalStats_ = config_.use_global_stats();
  }

165 166 167 168 169 170
  Matrix::resizeOrCreate(
      expandedIn_, batchSize * imgPixels_, channels_, false, useGpu_);
  Matrix::resizeOrCreate(
      normIn_, batchSize * imgPixels_, channels_, false, useGpu_);
  Matrix::resizeOrCreate(
      expandedOut_, batchSize * imgPixels_, channels_, false, useGpu_);
Z
zhangjinchao01 已提交
171 172 173 174 175 176 177 178 179 180 181 182 183
  expandMat(getInputValue(0), expandedIn_);

  if (useGlobalStats_) {
    if (firstTest_) {
      setMeanAndStd();
      firstTest_ = false;
    }
  } else {
    calMeanAndStd(expandedIn_);
    firstTest_ = true;
  }

  normIn_->assign(*expandedIn_);
184
  normIn_->addBias(*savedMean_, -1);     // subtract mean.
Z
zhangjinchao01 已提交
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
  normIn_->divRowVector(*savedInvVar_);  // divide std.

  expandedOut_->assign(*normIn_);
  expandedOut_->mulRowVector(*weight_->getW());  // multiple gamma.
  if (biases_) {
    expandedOut_->addBias(*(biases_->getW()), 1);  // add beta.
  }
  MatrixPtr out = getOutputValue();
  shrinkMat(expandedOut_, out);

  /* activation */ {
    REGISTER_TIMER_INFO("FwAtvTimer", getName().c_str());
    forwardActivation();
  }
}

void BatchNormalizationLayer::backward(const UpdateCallback& callback) {
  /* Do derivation */ {
    REGISTER_TIMER_INFO("BpAvtTimer", getName().c_str());
    backwardActivation();
  }
  int batchSize = getInputValue(0)->getHeight();

  Matrix::resizeOrCreate(meanGrad_, 1, channels_, false, useGpu_);
  Matrix::resizeOrCreate(stdGrad_, 1, channels_, false, useGpu_);

211 212 213 214 215 216 217 218 219 220 221 222
  Matrix::resizeOrCreate(
      expandedInGrad_, batchSize * imgPixels_, channels_, false, useGpu_);
  Matrix::resizeOrCreate(
      inGrad_, batchSize, imgPixels_ * channels_, false, useGpu_);
  Matrix::resizeOrCreate(
      normInGrad_, batchSize * imgPixels_, channels_, false, useGpu_);
  Matrix::resizeOrCreate(
      expandedOutGrad_, batchSize * imgPixels_, channels_, false, useGpu_);
  Matrix::resizeOrCreate(
      tmpMat_, batchSize * imgPixels_, channels_, false, useGpu_);
  Matrix::resizeOrCreate(
      tmpGrad_, batchSize * imgPixels_, channels_, false, useGpu_);
Z
zhangjinchao01 已提交
223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266

  expandMat(getOutputGrad(), expandedOutGrad_);

  // compute derivatives.
  if (biases_ && biases_->getWGrad()) {
    REGISTER_TIMER_INFO("BpBiasTimer", getName().c_str());
    biases_->getWGrad()->collectBias(*expandedOutGrad_, 1);
    /* Increasing the number of gradient */
    biases_->getParameterPtr()->incUpdate(callback);
  }
  if (weight_->getWGrad()) {
    tmpMat_->dotMul(*expandedOutGrad_, *normIn_);
    weight_->getWGrad()->collectBias(*tmpMat_, 1);
  }

  // compute input gradients.
  normInGrad_->assign(*expandedOutGrad_);
  normInGrad_->mulRowVector(*(weight_->getW()));  // multiple gamma.
  // normInGrad * (x - \mu)/ \sqrt(\delta^2)
  tmpMat_->dotMul(*normInGrad_, *normIn_);
  stdGrad_->zeroMem();
  stdGrad_->collectBias(*tmpMat_, -1.0 / (batchSize * imgPixels_));
  tmpGrad_->assign(*normIn_);
  tmpGrad_->mulRowVector(*stdGrad_);

  meanGrad_->zeroMem();
  meanGrad_->collectBias(*normInGrad_, -1.0 / (batchSize * imgPixels_));

  expandedInGrad_->zeroMem();
  expandedInGrad_->add(*normInGrad_, *tmpGrad_);
  expandedInGrad_->addRowVector(*meanGrad_);
  expandedInGrad_->divRowVector(*savedInvVar_);

  shrinkMat(expandedInGrad_, inGrad_);
  if (getInputGrad(0)) {
    getInputGrad(0)->add(*getInputGrad(0), *inGrad_);
  }
  {
    REGISTER_TIMER_INFO("WeightUpdate", getName().c_str());
    weight_->getParameterPtr()->incUpdate(callback);
  }
}

}  // namespace paddle