CrossMapNormalOp.cpp 12.1 KB
Newer Older
H
hedaoyuan 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14
/* Copyright (c) 2016 PaddlePaddle Authors. 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. */

H
hedaoyuan 已提交
15
#include "CrossMapNormalOp.h"
H
hedaoyuan 已提交
16
#include "paddle/math/Vector.h"
H
hedaoyuan 已提交
17 18 19

namespace paddle {

H
hedaoyuan 已提交
20
template <>
H
hedaoyuan 已提交
21 22
void CrossMapNormal<DEVICE_TYPE_CPU>(real* outputs,
                                     real* denoms,
H
hedaoyuan 已提交
23
                                     const real* inputs,
H
hedaoyuan 已提交
24 25 26 27 28 29 30 31 32 33 34
                                     size_t numSamples,
                                     size_t channels,
                                     size_t height,
                                     size_t width,
                                     size_t size,
                                     real scale,
                                     real pow) {
  size_t oneImage = height * width;
  size_t oneSample = channels * oneImage;

  CpuVector outputsV(numSamples * oneSample, outputs);
H
hedaoyuan 已提交
35
  CpuVector inputsV(numSamples * oneSample, const_cast<real*>(inputs));
H
hedaoyuan 已提交
36 37
  CpuVector denomsV(numSamples * oneSample, denoms);

H
hedaoyuan 已提交
38 39 40 41
  // f(x) = x * ( 1 + scale * SUM((x)^2) )^(-pow)
  // x represents inputs
  // f(x) represents outputs
  // denoms save the intermediate result for backward
H
hedaoyuan 已提交
42 43 44 45 46
  denomsV = denomsV.constant(1.0);
  const int start = -((int)size - 1) / 2;
  const int end = (int)size + start;
  for (size_t i = 0; i < numSamples; i++) {
    real* oneDenom = denoms + i * oneSample;
H
hedaoyuan 已提交
47
    real* oneInput = const_cast<real*>(inputs) + i * oneSample;
H
hedaoyuan 已提交
48
    for (int c = 0; c < (int)channels; c++) {
H
hedaoyuan 已提交
49
      CpuVector denom(oneImage, oneDenom + c * oneImage);
H
hedaoyuan 已提交
50 51
      for (int s = start; s < end; s++) {
        if (c + s >= 0 && c + s < (int)channels) {
H
hedaoyuan 已提交
52
          CpuVector input(oneImage, oneInput + (c + s) * oneImage);
H
hedaoyuan 已提交
53 54 55 56 57
          denom += input.square() * scale;
        }
      }
    }
  }
H
hedaoyuan 已提交
58 59

  outputsV = inputsV * denomsV.pow(-pow);
H
hedaoyuan 已提交
60 61
}

H
hedaoyuan 已提交
62
template <>
H
hedaoyuan 已提交
63
void CrossMapNormalGrad<DEVICE_TYPE_CPU>(real* inputsGrad,
H
hedaoyuan 已提交
64 65 66 67
                                         const real* inputsValue,
                                         const real* outputsValue,
                                         const real* outputsGrad,
                                         const real* denoms,
H
hedaoyuan 已提交
68 69 70 71 72 73 74 75
                                         size_t numSamples,
                                         size_t channels,
                                         size_t height,
                                         size_t width,
                                         size_t size,
                                         real scale,
                                         real pow) {
  size_t oneSample = channels * height * width;
H
hedaoyuan 已提交
76 77
  std::function<CpuVector(real*, size_t)> oneImage = [=](real* data,
                                                         size_t offset) {
H
hedaoyuan 已提交
78
    return CpuVector(height * width, data + offset);
H
hedaoyuan 已提交
79 80
  };

H
hedaoyuan 已提交
81 82
  const int start = -((int)size) / 2;
  const int end = (int)size + start;
H
hedaoyuan 已提交
83
  const real ratio = -(real)2 * scale * pow;
H
hedaoyuan 已提交
84 85 86
  for (size_t i = 0; i < numSamples; i++) {
    size_t sOffset = i * oneSample;
    real* oneInputGrad = inputsGrad + sOffset;
H
hedaoyuan 已提交
87 88 89 90
    real* oneInputValue = const_cast<real*>(inputsValue) + sOffset;
    real* oneDenom = const_cast<real*>(denoms) + sOffset;
    real* oneOutputGrad = const_cast<real*>(outputsGrad) + sOffset;
    real* oneOutputValue = const_cast<real*>(outputsValue) + sOffset;
H
hedaoyuan 已提交
91 92

    for (int c = 0; c < (int)channels; c++) {
H
hedaoyuan 已提交
93 94 95 96 97
      size_t cOffset = c * height * width;
      CpuVector inputGrad = oneImage(oneInputGrad, cOffset);
      CpuVector inputValue = oneImage(oneInputValue, cOffset);
      CpuVector denom = oneImage(oneDenom, cOffset);
      CpuVector outputGrad = oneImage(oneOutputGrad, cOffset);
H
hedaoyuan 已提交
98 99 100 101

      inputGrad = inputGrad + denom.pow(-pow) * outputGrad;
      for (int s = start; s < end; s++) {
        if (c + s >= 0 && c + s < (int)channels) {
H
hedaoyuan 已提交
102 103 104 105
          size_t offset = (c + s) * height * width;
          CpuVector output = oneImage(oneOutputValue, offset);
          CpuVector outputGrad = oneImage(oneOutputGrad, offset);
          CpuVector denom = oneImage(oneDenom, offset);
H
hedaoyuan 已提交
106 107 108 109 110 111 112 113

          inputGrad += ((outputGrad * output * ratio) / denom) * inputValue;
        }
      }
    }
  }
}

H
hedaoyuan 已提交
114
/**
115
 * \brief Normalization with across maps.
116
 *
117 118 119 120 121
 * This Function comes from the paper
 * "ImageNet Classification with Deep Convolutional Neural Networks".
 *
 * The original formula is:
 *
H
hedaoyuan 已提交
122 123 124 125 126
 *                                Input(i, x, y)
 * Output(i, x, y) = ----------------------------------------------
 *                                 -- upper
 *                    (k + alpha * >  (Input(j, x, y))^2) ^ (beta)
 *                                 -- j = lower
127
 *
H
hedaoyuan 已提交
128 129
 * upper is `min(C, c + N/2)`
 * lower if `max(0, c - N/2)`
H
hedaoyuan 已提交
130 131 132 133
 *
 * Function implementation:
 *
 * inputs and outpus is NCHW format, while input.shape.ndims() is equal 4.
134 135
 * And the meaning of each dimension(0-3) is respectively batch size,
 * feature maps, rows and columns.
H
hedaoyuan 已提交
136
 *
H
hedaoyuan 已提交
137 138 139 140 141 142
 * Input and Output in the above formula is for each map(i) of one image, and
 * Input(i, x, y), Output(i, x, y) represents an element in an image.
 *
 * C is the number of feature maps of one image, and N is a hyper-parameters
 * is configured when Function is initialized. The sum in the denominator
 * is the sum of the same position in the neighboring maps.
H
hedaoyuan 已提交
143 144 145 146 147
 *
 * In the implementation of Function, k is equal to 1,
 * so Function has no argument for k.
 *
 * Function Arguments:
148
 *
149
 * \param size_      represent N
H
hedaoyuan 已提交
150
 * \param scale_     represent alpha
151 152 153 154 155
 * \param pow_       represent beta
 * \param inputs[0]  represent Input
 * \param outputs[0] represent Output
 * \param outputs[1] represent The denominator in the formula(except beta)
 *
H
hedaoyuan 已提交
156
 * Note:
157
 * Save output[1] is to simplify the backward calculation.
158
 * TODO, if only consider the forward calculation, we can optimize to
159
 * remove the output[1].
H
hedaoyuan 已提交
160
 */
H
hedaoyuan 已提交
161 162 163 164
template <DeviceType Device>
class CrossMapNormalFunc : public FunctionBase {
public:
  void init(const FuncConfig& config) override {
H
hedaoyuan 已提交
165
    // function arguments
H
hedaoyuan 已提交
166 167 168
    size_ = config.get<size_t>("size");
    scale_ = config.get<real>("scale");
    pow_ = config.get<real>("pow");
H
hedaoyuan 已提交
169 170 171 172

    // number of inputs and outputs
    numInputs_ = 1;
    numOutputs_ = 2;
H
hedaoyuan 已提交
173 174
  }

175
  void calc(const BufferArgs& inputs, const BufferArgs& outputs) override {
H
hedaoyuan 已提交
176 177 178
    check(inputs, outputs);
    // ArgType check still on here,
    // not sure whether it is better to put inside the check.
179 180
    CHECK_EQ(outputs[0].getArgType(), ASSIGN_TO);
    CHECK_EQ(outputs[1].getArgType(), ASSIGN_TO);
H
hedaoyuan 已提交
181 182 183 184
    size_t batchSize = inputs[0].shape()[0];
    size_t maps = inputs[0].shape()[1];
    size_t rows = inputs[0].shape()[2];
    size_t columns = inputs[0].shape()[3];
185

H
hedaoyuan 已提交
186 187 188
    CrossMapNormal<Device>(outputs[0].data<real>(),
                           outputs[1].data<real>(),
                           inputs[0].data<real>(),
H
hedaoyuan 已提交
189 190 191 192
                           batchSize,
                           maps,
                           rows,
                           columns,
H
hedaoyuan 已提交
193 194 195
                           size_,
                           scale_,
                           pow_);
H
hedaoyuan 已提交
196 197
  }

H
hedaoyuan 已提交
198
  void check(const BufferArgs& inputs, const BufferArgs& outputs) override {
H
hedaoyuan 已提交
199 200
    CHECK_EQ(numInputs_, inputs.size());
    CHECK_EQ(numOutputs_, outputs.size());
H
hedaoyuan 已提交
201 202 203 204 205 206

    CHECK_EQ(inputs[0].shape().ndims(), (size_t)4);
    CHECK(inputs[0].shape() == outputs[0].shape());
    CHECK(inputs[0].shape() == outputs[1].shape());
  }

H
hedaoyuan 已提交
207 208 209 210 211 212 213 214 215 216 217
  // Only need the shape of the input, can calculate the
  // floating-point operation.
  size_t ops(const BufferArgs& inputs, const BufferArgs& outputs) override {
    CHECK_EQ((size_t)numInputs_, inputs.size());
    size_t batchSize = inputs[0].shape()[0];
    size_t maps = inputs[0].shape()[1];
    size_t rows = inputs[0].shape()[2];
    size_t columns = inputs[0].shape()[3];

    // number of floating-point operations
    // an approximate value
H
hedaoyuan 已提交
218
    size_t ops = batchSize * maps * rows * columns * (size_ * 2 + 3);
H
hedaoyuan 已提交
219 220

    return ops;
H
hedaoyuan 已提交
221 222
  }

H
hedaoyuan 已提交
223 224 225 226 227 228
private:
  size_t size_;
  real scale_;
  real pow_;
};

H
hedaoyuan 已提交
229
/**
230 231
 * \brief Backward calculation for normalization with across maps.
 *
H
hedaoyuan 已提交
232 233
 * Function implementation:
 *
234 235 236 237
 * The implementation of this Function is derived from the
 * CrossMapNormalFunc implementation.
 *
 * InputGrad = OutputGrad * denoms ^ (-beta)
H
hedaoyuan 已提交
238 239 240
 *    -- upper
 *  + > (OutputGrad * OutputValue * (-2 * alpha * beta) / denoms) * InputValue
 *    -- lower
241
 *
242 243 244
 * The data of inputs/outputs format is the same as the forward interface
 * and is NCHW.
 *
H
hedaoyuan 已提交
245 246 247 248 249
 * The upper and lower is the same as forward. The logic of the sum
 * is also the same as forward.
 *
 * Function Arguments:
 *
250
 * \param size_      represent N
H
hedaoyuan 已提交
251
 * \param scale_     represent alpha
252 253 254 255 256 257 258 259
 * \param pow_       represent beta
 * \param inputs[0]  represent InputValue, inputs[0] of CrossMapNormalFunc
 * \param inputs[1]  represent OutputValue, outputs[0] of CrossMapNormalFunc
 * \param inputs[2]  represent OutputGrad
 * \param inputs[3]  represent denoms, outputs[1] of CrossMapNormalFunc
 *                   This is the intermediate result that is
 *                   preserved in the forward calculation.
 * \param outputs[0] represent InputGrad
H
hedaoyuan 已提交
260 261 262 263 264
 */
template <DeviceType Device>
class CrossMapNormalGradFunc : public FunctionBase {
public:
  void init(const FuncConfig& config) override {
H
hedaoyuan 已提交
265
    // function arguments
H
hedaoyuan 已提交
266 267 268
    size_ = config.get<size_t>("size");
    scale_ = config.get<real>("scale");
    pow_ = config.get<real>("pow");
H
hedaoyuan 已提交
269 270 271 272

    // number of inputs and outputs
    numInputs_ = 4;
    numOutputs_ = 1;
H
hedaoyuan 已提交
273 274
  }

275
  void calc(const BufferArgs& inputs, const BufferArgs& outputs) override {
H
hedaoyuan 已提交
276
    check(inputs, outputs);
H
hedaoyuan 已提交
277 278 279 280 281 282 283
    if (outputs[0].getArgType() != ADD_TO) {
      // Currently, some algorithm implementations are ASSIGN_TO mode,
      // if need to support the ADD_TO calculation, need to clear the output.
      typename Tensor<real, Device>::Vector tmp(
          outputs[0].shape().getElements(), outputs[0].data<real>());
      tmp.zero();
    }
284

H
hedaoyuan 已提交
285 286 287 288
    size_t batchSize = inputs[0].shape()[0];
    size_t maps = inputs[0].shape()[1];
    size_t rows = inputs[0].shape()[2];
    size_t columns = inputs[0].shape()[3];
H
hedaoyuan 已提交
289 290 291 292 293 294

    CrossMapNormalGrad<Device>(outputs[0].data<real>(),
                               inputs[0].data<real>(),
                               inputs[1].data<real>(),
                               inputs[2].data<real>(),
                               inputs[3].data<real>(),
H
hedaoyuan 已提交
295 296 297 298
                               batchSize,
                               maps,
                               rows,
                               columns,
H
hedaoyuan 已提交
299 300 301 302 303
                               size_,
                               scale_,
                               pow_);
  }

H
hedaoyuan 已提交
304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330
  void check(const BufferArgs& inputs, const BufferArgs& outputs) override {
    CHECK_EQ(numInputs_, inputs.size());
    CHECK_EQ(numOutputs_, outputs.size());

    CHECK_EQ(inputs[0].shape().ndims(), (size_t)4);
    CHECK(inputs[0].shape() == inputs[1].shape());
    CHECK(inputs[0].shape() == inputs[2].shape());
    CHECK(inputs[0].shape() == inputs[3].shape());
    CHECK(inputs[0].shape() == outputs[0].shape());
  }

  // Only need the shape of one input, can calculate the
  // floating-point operation.
  size_t ops(const BufferArgs& inputs, const BufferArgs& outputs) override {
    CHECK_LT((size_t)1, inputs.size());
    size_t batchSize = inputs[0].shape()[0];
    size_t maps = inputs[0].shape()[1];
    size_t rows = inputs[0].shape()[2];
    size_t columns = inputs[0].shape()[3];

    // number of floating-point operations
    // an approximate value
    size_t ops = batchSize * maps * rows * columns * (size_ * 4 + 2);

    return ops;
  }

H
hedaoyuan 已提交
331 332 333 334 335 336
private:
  size_t size_;
  real scale_;
  real pow_;
};

H
hedaoyuan 已提交
337
REGISTER_TYPED_FUNC(CrossMapNormal, CPU, CrossMapNormalFunc);
H
hedaoyuan 已提交
338
REGISTER_TYPED_FUNC(CrossMapNormalGrad, CPU, CrossMapNormalGradFunc);
H
hedaoyuan 已提交
339 340
#ifndef PADDLE_ONLY_CPU
REGISTER_TYPED_FUNC(CrossMapNormal, GPU, CrossMapNormalFunc);
H
hedaoyuan 已提交
341
REGISTER_TYPED_FUNC(CrossMapNormalGrad, GPU, CrossMapNormalGradFunc);
H
hedaoyuan 已提交
342
#endif
H
hedaoyuan 已提交
343

H
hedaoyuan 已提交
344
}  // namespace paddle