BatchNormalizationLayer.cpp 8.7 KB
Newer Older
1
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve.
Z
zhangjinchao01 已提交
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

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"
#ifndef PADDLE_ONLY_CPU
#include "hl_batch_transpose.h"
#endif
#include "BatchNormalizationLayer.h"

namespace paddle {

REGISTER_LAYER(batch_norm, BatchNormalizationLayer);

const real BatchNormalizationLayer::EPS = 1E-5;

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 已提交
43
  tmpMat_->square2();
Z
zhangjinchao01 已提交
44 45
  savedInvVar_->zeroMem();
  savedInvVar_->accumulateColSum(*tmpMat_);
46 47
  savedInvVar_->mulScalar(1.0 / numSamples);   // E[x^2]
  savedInvVar_->addSquare(*savedMean_, -1.0);  // E[x^2] - E^2[x]
Z
zhangjinchao01 已提交
48 49 50 51 52 53 54 55 56

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

  calMovingMeanAndVar();

  savedInvVar_->subScalar(-EPS);
H
hedaoyuan 已提交
57
  savedInvVar_->sqrt2(*savedInvVar_);
Z
zhangjinchao01 已提交
58 59 60 61
}

void BatchNormalizationLayer::calMovingMeanAndVar() {
  // calculating and saving moving mean and variance
Y
Yu Yang 已提交
62 63 64 65 66 67 68 69
  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 已提交
70 71 72 73 74 75 76 77
}

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

  savedInvVar_->subScalar(-EPS);
H
hedaoyuan 已提交
78
  savedInvVar_->sqrt2(*savedInvVar_);
Z
zhangjinchao01 已提交
79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
}

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_) {
#ifdef PADDLE_ONLY_CPU
    LOG(FATAL) << "paddle is compiled only for cpu";
#else
96 97
    batchTranspose(
        in->getData(), out->getData(), imgPixels_, channels_, batchSize);
Z
zhangjinchao01 已提交
98 99 100 101
#endif
  } else {
    for (size_t i = 0; i < batchSize; i++) {
      const MatrixPtr inTmp =
102 103 104 105 106
          Matrix::create(in->getData() + i * imgPixels_ * channels_,
                         channels_,
                         imgPixels_,
                         false,
                         useGpu_);
Z
zhangjinchao01 已提交
107 108
      MatrixPtr outTmp =
          Matrix::create(out->getData() + i * imgPixels_ * channels_,
109 110 111 112
                         imgPixels_,
                         channels_,
                         false,
                         useGpu_);
Z
zhangjinchao01 已提交
113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132
      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_) {
#ifdef PADDLE_ONLY_CPU
    LOG(FATAL) << "paddle is compiled only for cpu";
#else
133 134
    batchTranspose(
        in->getData(), out->getData(), channels_, imgPixels_, batchSize);
Z
zhangjinchao01 已提交
135 136 137 138
#endif
  } else {
    for (size_t i = 0; i < batchSize; i++) {
      const MatrixPtr inTmp =
139 140 141 142 143
          Matrix::create(in->getData() + i * channels_ * imgPixels_,
                         imgPixels_,
                         channels_,
                         false,
                         useGpu_);
Z
zhangjinchao01 已提交
144
      MatrixPtr outTmp =
145 146 147 148
          Matrix::create(out->getData() + i * imgPixels_ * channels_,
                         channels_,
                         imgPixels_,
                         useGpu_);
Z
zhangjinchao01 已提交
149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166
      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();
  }

167 168 169 170 171 172
  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 已提交
173 174 175 176 177 178 179 180 181 182 183 184 185
  expandMat(getInputValue(0), expandedIn_);

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

  normIn_->assign(*expandedIn_);
186
  normIn_->addBias(*savedMean_, -1);     // subtract mean.
Z
zhangjinchao01 已提交
187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212
  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_);

213 214 215 216 217 218 219 220 221 222 223 224
  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 已提交
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 267 268

  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