group_norm_op.h 15.2 KB
Newer Older
D
Dun 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.

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. */

#pragma once
#include <algorithm>
17 18
#include <array>
#include <numeric>
19 20
#include <string>
#include "paddle/fluid/framework/data_layout.h"
D
Dun 已提交
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
#include "paddle/fluid/framework/eigen.h"
#include "paddle/fluid/framework/op_registry.h"
#include "paddle/fluid/operators/elementwise/elementwise_op_function.h"
#include "paddle/fluid/operators/math/blas.h"
#include "paddle/fluid/operators/math/math_function.h"

namespace paddle {
namespace operators {

using Tensor = framework::Tensor;
using LoDTensor = framework::LoDTensor;
using DataLayout = framework::DataLayout;

template <typename DeviceContext, typename T>
class GroupNormKernel : public framework::OpKernel<T> {
 public:
  void Compute(const framework::ExecutionContext& ctx) const override {
38 39 40
    const std::string data_layout_str = ctx.Attr<std::string>("data_layout");
    const DataLayout data_layout =
        framework::StringToDataLayout(data_layout_str);
D
Dun 已提交
41 42 43 44 45 46 47 48 49 50 51
    const float epsilon = ctx.Attr<float>("epsilon");
    auto* scale = ctx.Input<Tensor>("Scale");
    auto* bias = ctx.Input<Tensor>("Bias");
    auto* x = ctx.Input<Tensor>("X");

    auto* y = ctx.Output<Tensor>("Y");
    auto* mean = ctx.Output<Tensor>("Mean");
    auto* var = ctx.Output<Tensor>("Variance");
    const auto groups = ctx.Attr<int>("groups");

    const auto x_dims = x->dims();
52 53 54 55
    const int C =
        (data_layout == DataLayout::kNCHW ? x_dims[1]
                                          : x_dims[x_dims.size() - 1]);
    const int group_size = (C - 1) / groups + 1;
D
Dun 已提交
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70

    y->mutable_data<T>(ctx.GetPlace());
    mean->mutable_data<T>(ctx.GetPlace());
    var->mutable_data<T>(ctx.GetPlace());

    auto* x_data = x->data<T>();
    auto* y_data = y->data<T>();
    auto* mean_data = mean->data<T>();
    auto* var_data = var->data<T>();

    const T* scale_data = nullptr;
    if (scale) scale_data = scale->data<T>();
    const T* bias_data = nullptr;
    if (bias) bias_data = bias->data<T>();

71 72 73
    int imsize = (data_layout == DataLayout::kNCHW ? x_dims[2] * x_dims[3]
                                                   : x_dims[1] * x_dims[2]);

D
Dun 已提交
74 75
    auto* iter_x_data = x_data;
    auto* iter_y_data = y_data;
76
    for (int bid = 0; bid < x_dims[0]; bid++) {
D
Dun 已提交
77
      for (int gid = 0; gid < groups; gid++) {
78 79 80 81 82
        const int64_t M = 8;
        std::array<T, M> x_mean_arr;
        std::array<T, M> x_var_arr;
        std::fill(x_mean_arr.begin(), x_mean_arr.end(), T(0));
        std::fill(x_var_arr.begin(), x_var_arr.end(), T(0));
D
Dun 已提交
83
        T x_mean = 0, x_var = 0;
84 85 86 87 88 89 90 91 92
        int number =
            std::min(group_size, static_cast<int>(C - gid * group_size));
        auto* tmp_x = iter_x_data;
        auto* x_src_data = iter_x_data;
        auto* tmp_y = iter_y_data;
        auto* y_src_data = iter_y_data;

        if (data_layout == DataLayout::kNCHW) {
          for (int cid = 0; cid < number; cid++) {
93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123
            int imid;
            for (imid = 0; imid < imsize - (imsize % M);
                 imid += M, iter_x_data += M) {
              // TODO(gaoxiang) :Because AVX/AVX2/AVX512 can not directly used
              // in template class/function, before we complete high
              // performance cpu vector extension, temporarily unrolling
              // loop to get high precision and performance
              x_mean_arr[0] += iter_x_data[0];
              x_var_arr[0] += iter_x_data[0] * iter_x_data[0];
              x_mean_arr[1] += iter_x_data[1];
              x_var_arr[1] += iter_x_data[1] * iter_x_data[1];
              x_mean_arr[2] += iter_x_data[2];
              x_var_arr[2] += iter_x_data[2] * iter_x_data[2];
              x_mean_arr[3] += iter_x_data[3];
              x_var_arr[3] += iter_x_data[3] * iter_x_data[3];
              x_mean_arr[4] += iter_x_data[4];
              x_var_arr[4] += iter_x_data[4] * iter_x_data[4];
              x_mean_arr[5] += iter_x_data[5];
              x_var_arr[5] += iter_x_data[5] * iter_x_data[5];
              x_mean_arr[6] += iter_x_data[6];
              x_var_arr[6] += iter_x_data[6] * iter_x_data[6];
              x_mean_arr[7] += iter_x_data[7];
              x_var_arr[7] += iter_x_data[7] * iter_x_data[7];
            }
            x_mean =
                std::accumulate(x_mean_arr.cbegin(), x_mean_arr.cend(), x_mean);
            x_var =
                std::accumulate(x_var_arr.cbegin(), x_var_arr.cend(), x_var);
            std::fill(x_mean_arr.begin(), x_mean_arr.end(), T(0));
            std::fill(x_var_arr.begin(), x_var_arr.end(), T(0));
            for (; imid < imsize; imid++, iter_x_data++) {
124 125 126 127 128 129 130
              x_mean += iter_x_data[0];
              x_var += iter_x_data[0] * iter_x_data[0];
            }
          }
        } else {
          for (int cid = 0; cid < number; cid++) {
            iter_x_data = tmp_x + cid;
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
            int imid;
            for (imid = 0; imid < imsize - (imsize % M);
                 imid += M, iter_x_data += M * C) {
              // TODO(gaoxiang) :Because AVX/AVX2/AVX512 can not directly used
              // in template class/function, before we complete high
              // performance cpu vector extension, temporarily unrolling
              // loop to get high precision and performance
              x_mean_arr[0] += iter_x_data[0 * C];
              x_var_arr[0] += iter_x_data[0 * C] * iter_x_data[0 * C];
              x_mean_arr[1] += iter_x_data[1 * C];
              x_var_arr[1] += iter_x_data[1 * C] * iter_x_data[1 * C];
              x_mean_arr[2] += iter_x_data[2 * C];
              x_var_arr[2] += iter_x_data[2 * C] * iter_x_data[2 * C];
              x_mean_arr[3] += iter_x_data[3 * C];
              x_var_arr[3] += iter_x_data[3 * C] * iter_x_data[3 * C];
              x_mean_arr[4] += iter_x_data[4 * C];
              x_var_arr[4] += iter_x_data[4 * C] * iter_x_data[4 * C];
              x_mean_arr[5] += iter_x_data[5 * C];
              x_var_arr[5] += iter_x_data[5 * C] * iter_x_data[5 * C];
              x_mean_arr[6] += iter_x_data[6 * C];
              x_var_arr[6] += iter_x_data[6 * C] * iter_x_data[6 * C];
              x_mean_arr[7] += iter_x_data[7 * C];
              x_var_arr[7] += iter_x_data[7 * C] * iter_x_data[7 * C];
            }
            x_mean =
                std::accumulate(x_mean_arr.cbegin(), x_mean_arr.cend(), x_mean);
            x_var =
                std::accumulate(x_var_arr.cbegin(), x_var_arr.cend(), x_var);
            std::fill(x_mean_arr.begin(), x_mean_arr.end(), T(0));
            std::fill(x_var_arr.begin(), x_var_arr.end(), T(0));
            for (; imid < imsize; imid++, iter_x_data += C) {
162 163 164
              x_mean += iter_x_data[0];
              x_var += iter_x_data[0] * iter_x_data[0];
            }
D
Dun 已提交
165
          }
166
          iter_x_data = tmp_x + group_size;
D
Dun 已提交
167
        }
168

D
Dun 已提交
169 170
        x_mean /= number * imsize;
        x_var /= number * imsize;
171 172
        x_var = std::max(x_var - x_mean * x_mean, T(0));
        T var_inv = T(1) / std::sqrt(x_var + epsilon);
D
Dun 已提交
173 174
        mean_data[bid * groups + gid] = x_mean;
        var_data[bid * groups + gid] = x_var;
175 176 177 178 179 180 181 182 183

        if (data_layout == DataLayout::kNCHW) {
          for (int cid = 0; cid < number; cid++) {
            for (int imid = 0; imid < imsize; imid++, tmp_x++, iter_y_data++) {
              T val = (tmp_x[0] - x_mean) * var_inv;
              if (scale_data) val *= scale_data[gid * group_size + cid];
              if (bias_data) val += bias_data[gid * group_size + cid];
              iter_y_data[0] = val;
            }
D
Dun 已提交
184
          }
185 186 187 188 189 190 191 192 193 194 195 196 197
        } else {
          for (int cid = 0; cid < number; cid++) {
            tmp_x = x_src_data + cid;
            iter_y_data = y_src_data + cid;
            for (int imid = 0; imid < imsize;
                 imid++, tmp_x += C, iter_y_data += C) {
              T val = (tmp_x[0] - x_mean) * var_inv;
              if (scale_data) val *= scale_data[gid * group_size + cid];
              if (bias_data) val += bias_data[gid * group_size + cid];
              iter_y_data[0] = val;
            }
          }
          iter_y_data = tmp_y + group_size;
D
Dun 已提交
198 199
        }
      }
200 201 202 203 204
      if (data_layout == DataLayout::kNHWC) {
        iter_x_data = x_data + (bid + 1) * C * imsize;
        iter_y_data = y_data + (bid + 1) * C * imsize;
      }
    }
D
Dun 已提交
205 206 207 208 209 210 211
  }
};

template <typename DeviceContext, typename T>
class GroupNormGradKernel : public framework::OpKernel<T> {
 public:
  void Compute(const framework::ExecutionContext& ctx) const override {
212 213 214
    const std::string data_layout_str = ctx.Attr<std::string>("data_layout");
    const DataLayout data_layout =
        framework::StringToDataLayout(data_layout_str);
D
Dun 已提交
215
    const float epsilon = ctx.Attr<float>("epsilon");
216
    auto* x = ctx.Input<Tensor>("Y");
D
Dun 已提交
217 218
    auto* var = ctx.Input<Tensor>("Variance");
    auto* scale = ctx.Input<Tensor>("Scale");
219
    auto* bias = ctx.Input<Tensor>("Bias");
D
Dun 已提交
220 221 222 223 224 225 226 227 228
    auto* d_y = ctx.Input<Tensor>(framework::GradVarName("Y"));
    const auto groups = ctx.Attr<int>("groups");

    // init output
    auto* d_x = ctx.Output<Tensor>(framework::GradVarName("X"));
    auto* d_scale = ctx.Output<Tensor>(framework::GradVarName("Scale"));
    auto* d_bias = ctx.Output<Tensor>(framework::GradVarName("Bias"));

    const auto& x_dims = x->dims();
229 230 231 232
    const int C =
        (data_layout == DataLayout::kNCHW ? x_dims[1]
                                          : x_dims[x_dims.size() - 1]);
    const int group_size = (C - 1) / groups + 1;
D
Dun 已提交
233

234
    d_x->mutable_data<T>(ctx.GetPlace());
D
Dun 已提交
235 236 237 238
    math::SetConstant<DeviceContext, T> set_zero;
    auto& dev_ctx = ctx.template device_context<DeviceContext>();

    auto* x_data = x->data<T>();
239
    auto* d_x_data = d_x->data<T>();
D
Dun 已提交
240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256
    auto* y_data = d_y->data<T>();
    auto* var_data = var->data<T>();
    T* d_scale_data = nullptr;
    if (d_scale) {
      d_scale->mutable_data<T>(ctx.GetPlace());
      set_zero(dev_ctx, d_scale, static_cast<T>(0));
      d_scale_data = d_scale->data<T>();
    }
    T* d_bias_data = nullptr;
    if (d_bias) {
      d_bias->mutable_data<T>(ctx.GetPlace());
      set_zero(dev_ctx, d_bias, static_cast<T>(0));
      d_bias_data = d_bias->data<T>();
    }

    const T* scale_data = nullptr;
    if (scale) scale_data = scale->data<T>();
257 258
    const T* bias_data = nullptr;
    if (bias) bias_data = bias->data<T>();
D
Dun 已提交
259

260 261
    int imsize = (data_layout == DataLayout::kNCHW ? x_dims[2] * x_dims[3]
                                                   : x_dims[1] * x_dims[2]);
D
Dun 已提交
262 263 264
    auto* iter_x_data = x_data;
    auto* iter_d_x_data = d_x_data;
    auto* iter_y_data = y_data;
265
    for (int bid = 0; bid < x_dims[0]; bid++) {
D
Dun 已提交
266 267 268
      for (int gid = 0; gid < groups; gid++) {
        T x_var = var_data[bid * groups + gid];
        T var_inv = 1.0 / sqrt(x_var + epsilon);
269 270
        int number =
            std::min(group_size, static_cast<int>(C - gid * group_size));
271
        T number_inv = 1.0 / (number * imsize);
272 273 274 275 276 277 278 279
        auto* tmp_x = iter_x_data;
        auto* tmp_y = iter_y_data;
        auto* tmp_d_x = iter_d_x_data;
        auto* x_src_data = iter_x_data;
        auto* y_src_data = iter_y_data;
        auto* iter_x_data_backup = iter_x_data;
        auto* iter_y_data_backup = iter_y_data;
        auto* iter_d_x_data_backup = iter_d_x_data;
280
        T dp_scale = 0, dp_bias = 0;
281 282 283 284 285 286 287 288 289

        if (data_layout == DataLayout::kNCHW) {
          for (int cid = 0; cid < number; cid++) {
            for (int imid = 0; imid < imsize;
                 imid++, iter_x_data++, iter_y_data++) {
              T val = iter_x_data[0];
              if (bias_data) val -= bias_data[gid * group_size + cid];
              T dval = iter_y_data[0];
              dp_scale += val * dval;
290 291
              if (scale_data)
                dp_bias += dval * scale_data[gid * group_size + cid];
292 293 294 295 296 297 298

              if (scale_data && scale_data[gid * group_size + cid] != 0)
                val /= scale_data[gid * group_size + cid];
              if (d_bias_data) d_bias_data[gid * group_size + cid] += dval;
              if (d_scale_data)
                d_scale_data[gid * group_size + cid] += val * dval;
            }
D
Dun 已提交
299 300
          }

301 302 303 304 305 306 307
          for (int cid = 0; cid < number; cid++) {
            for (int imid = 0; imid < imsize;
                 imid++, iter_d_x_data++, tmp_x++, tmp_y++) {
              T v_y = tmp_x[0];
              T dly = tmp_y[0];
              T dss = dp_scale;
              T dbs = dp_bias;
308 309 310
              T v_scale = 1., v_bias = 0.;
              if (scale_data) v_scale = scale_data[gid * group_size + cid];
              if (bias_data) v_bias = bias_data[gid * group_size + cid];
311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327
              v_y -= v_bias;
              if (v_scale != 0) v_y /= v_scale;
              iter_d_x_data[0] =
                  (dly * v_scale - number_inv * dss * v_y - number_inv * dbs) *
                  var_inv;
            }
          }
        } else {
          for (int cid = 0; cid < number; cid++) {
            iter_x_data = x_src_data + cid;
            iter_y_data = y_src_data + cid;
            for (int imid = 0; imid < imsize;
                 imid++, iter_x_data += C, iter_y_data += C) {
              T val = iter_x_data[0];
              if (bias_data) val -= bias_data[gid * group_size + cid];
              T dval = iter_y_data[0];
              dp_scale += val * dval;
328 329
              if (scale_data)
                dp_bias += dval * scale_data[gid * group_size + cid];
330 331 332 333 334 335 336

              if (scale_data && scale_data[gid * group_size + cid] != 0)
                val /= scale_data[gid * group_size + cid];
              if (d_bias_data) d_bias_data[gid * group_size + cid] += dval;
              if (d_scale_data)
                d_scale_data[gid * group_size + cid] += val * dval;
            }
D
Dun 已提交
337
          }
338 339 340 341 342 343 344 345 346 347 348

          for (int cid = 0; cid < number; cid++) {
            tmp_x = x_src_data + cid;
            tmp_y = y_src_data + cid;
            iter_d_x_data = tmp_d_x + cid;
            for (int imid = 0; imid < imsize;
                 imid++, iter_d_x_data += C, tmp_x += C, tmp_y += C) {
              T v_y = tmp_x[0];
              T dly = tmp_y[0];
              T dss = dp_scale;
              T dbs = dp_bias;
349 350 351
              T v_scale = 1.0, v_bias = 0.;
              if (scale_data) v_scale = scale_data[gid * group_size + cid];
              if (bias_data) v_bias = bias_data[gid * group_size + cid];
352 353 354 355 356 357 358 359 360 361
              v_y -= v_bias;
              if (v_scale != 0) v_y /= v_scale;
              iter_d_x_data[0] =
                  (dly * v_scale - number_inv * dss * v_y - number_inv * dbs) *
                  var_inv;
            }
          }
          iter_x_data = iter_x_data_backup + group_size;
          iter_y_data = iter_y_data_backup + group_size;
          iter_d_x_data = iter_d_x_data_backup + group_size;
D
Dun 已提交
362 363
        }
      }
364 365 366 367 368 369
      if (data_layout == DataLayout::kNHWC) {
        iter_x_data = x_data + (bid + 1) * C * imsize;
        iter_d_x_data = d_x_data + (bid + 1) * C * imsize;
        iter_y_data = y_data + (bid + 1) * C * imsize;
      }
    }
D
Dun 已提交
370 371 372 373 374
  }
};

}  // namespace operators
}  // namespace paddle