fake_quantize_op.h 14.8 KB
Newer Older
视言's avatar
视言 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
/* 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 <string>
#include "paddle/fluid/framework/eigen.h"
#include "paddle/fluid/framework/op_registry.h"
Z
Zhen Wang 已提交
20
#include "paddle/fluid/framework/tensor_util.h"
21
#include "paddle/fluid/memory/malloc.h"
视言's avatar
视言 已提交
22
#include "paddle/fluid/operators/math/blas.h"
23
#include "paddle/fluid/platform/hostdevice.h"
24
#include "paddle/fluid/platform/transform.h"
视言's avatar
视言 已提交
25 26 27 28

namespace paddle {
namespace operators {

29 30 31 32 33 34
template <typename T>
inline HOSTDEVICE T inverse(T s) {
  T eps = 1e-6;
  return s <= 1e-30 ? 1.0 / (s + eps) : 1.0 / s;
}

35 36 37 38
template <typename DeviceContext, typename T>
struct FindAbsMaxFunctor {
  void operator()(const DeviceContext& ctx, const T* in, const int num, T* out);
};
视言's avatar
视言 已提交
39 40

template <typename DeviceContext, typename T>
41 42 43 44 45 46
struct ClipAndFakeQuantFunctor {
  void operator()(const DeviceContext& ctx, const framework::Tensor& in,
                  const framework::Tensor& scale, const int bin_cnt,
                  framework::Tensor* out);
};

47 48 49 50 51 52 53
template <typename DeviceContext, typename T>
struct ClipAndFakeQuantDequantFunctor {
  void operator()(const DeviceContext& ctx, const framework::Tensor& in,
                  const framework::Tensor& scale, const int bin_cnt,
                  framework::Tensor* out);
};

54 55 56 57 58 59 60 61
template <typename DeviceContext, typename T>
struct FindRangeAbsMaxFunctor {
  void operator()(const DeviceContext& ctx, const framework::Tensor& cur_scale,
                  const framework::Tensor& last_scale,
                  const framework::Tensor& iter, const int window_size,
                  framework::Tensor* scales_arr, framework::Tensor* out_scale);
};

62 63
template <typename DeviceContext, typename T>
struct FindChannelAbsMaxFunctor {
64 65
  void operator()(const DeviceContext& ctx, const framework::Tensor& in_tensor,
                  const int quant_axis, T* out_abs_max);
66 67 68 69 70 71
};

template <typename DeviceContext, typename T>
struct ChannelClipAndFakeQuantFunctor {
  void operator()(const DeviceContext& ctx, const framework::Tensor& in,
                  const framework::Tensor& scale, const int bin_cnt,
72
                  const int quant_axis, framework::Tensor* out);
73 74
};

H
huangxu96 已提交
75 76 77 78 79 80 81
template <typename DeviceContext, typename T>
struct ChannelClipFakeQuantDequantFunctor {
  void operator()(const DeviceContext& ctx, const framework::Tensor& in,
                  const framework::Tensor& scale, const int bin_cnt,
                  const int quant_axis, framework::Tensor* out);
};

82 83 84 85 86 87 88 89 90
template <typename DeviceContext, typename T>
struct FindMovingAverageAbsMaxFunctor {
  void operator()(const DeviceContext& ctx, const framework::Tensor& in_accum,
                  const framework::Tensor& in_state,
                  const framework::Tensor& cur_scale,
                  framework::Tensor* out_state, framework::Tensor* out_accum,
                  framework::Tensor* out_scale);
};

91
template <typename DeviceContext, typename T>
92
class FakeAbsMaxKernelBase : public framework::OpKernel<T> {
视言's avatar
视言 已提交
93
 public:
94 95 96 97 98 99 100 101 102 103 104 105
  void Compute(const framework::ExecutionContext& context) const override {
    auto* in = context.Input<framework::Tensor>("X");
    auto* out = context.Output<framework::Tensor>("Out");
    auto* out_scale = context.Output<framework::Tensor>("OutScale");
    T* out_s = out_scale->mutable_data<T>(context.GetPlace());

    int bit_length = context.Attr<int>("bit_length");
    int bin_cnt = std::pow(2, bit_length - 1) - 1;

    auto& dev_ctx = context.template device_context<DeviceContext>();
    const T* in_data = in->data<T>();
    FindAbsMaxFunctor<DeviceContext, T>()(dev_ctx, in_data, in->numel(), out_s);
106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137
    RunClipFunctor(dev_ctx, *in, *out_scale, bin_cnt, out);
  }

  virtual ~FakeAbsMaxKernelBase() = default;

 protected:
  virtual void RunClipFunctor(const DeviceContext& dev_ctx,
                              const framework::Tensor& in,
                              const framework::Tensor& scale, int bin_cnt,
                              framework::Tensor* out) const = 0;
};

template <typename DeviceContext, typename T>
class FakeQuantizeAbsMaxKernel : public FakeAbsMaxKernelBase<DeviceContext, T> {
 protected:
  void RunClipFunctor(const DeviceContext& dev_ctx, const framework::Tensor& in,
                      const framework::Tensor& scale, int bin_cnt,
                      framework::Tensor* out) const override {
    ClipAndFakeQuantFunctor<DeviceContext, T>()(dev_ctx, in, scale, bin_cnt,
                                                out);
  }
};

template <typename DeviceContext, typename T>
class FakeQuantizeDequantizeAbsMaxKernel
    : public FakeAbsMaxKernelBase<DeviceContext, T> {
 protected:
  void RunClipFunctor(const DeviceContext& dev_ctx, const framework::Tensor& in,
                      const framework::Tensor& scale, int bin_cnt,
                      framework::Tensor* out) const override {
    ClipAndFakeQuantDequantFunctor<DeviceContext, T>()(dev_ctx, in, scale,
                                                       bin_cnt, out);
视言's avatar
视言 已提交
138
  }
139
};
视言's avatar
视言 已提交
140

Z
Zhen Wang 已提交
141 142 143 144 145 146 147
template <typename DeviceContext, typename T>
class FakeChannelWiseQuantizeAbsMaxKernel : public framework::OpKernel<T> {
 public:
  void Compute(const framework::ExecutionContext& context) const override {
    auto* in = context.Input<framework::Tensor>("X");

    auto* out = context.Output<framework::Tensor>("Out");
148
    auto* out_scale = context.Output<framework::Tensor>("OutScale");
Z
Zhen Wang 已提交
149 150 151 152
    out->mutable_data<T>(context.GetPlace());

    int bit_length = context.Attr<int>("bit_length");
    int bin_cnt = std::pow(2, bit_length - 1) - 1;
153
    int quant_axis = context.Attr<int>("quant_axis");
154
    bool is_test = context.Attr<bool>("is_test");
Z
Zhen Wang 已提交
155 156

    auto& dev_ctx = context.template device_context<DeviceContext>();
157 158 159 160 161
    if (!is_test) {
      T* out_scale_data = out_scale->mutable_data<T>(context.GetPlace());
      FindChannelAbsMaxFunctor<DeviceContext, T>()(dev_ctx, *in, quant_axis,
                                                   out_scale_data);
    }
162
    ChannelClipAndFakeQuantFunctor<DeviceContext, T>()(
163
        dev_ctx, *in, *out_scale, bin_cnt, quant_axis, out);
Z
Zhen Wang 已提交
164 165 166
  }
};

H
huangxu96 已提交
167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190
template <typename DeviceContext, typename T>
class FakeChannelWiseQuantizeDequantizeAbsMaxKernel
    : public framework::OpKernel<T> {
 public:
  void Compute(const framework::ExecutionContext& context) const override {
    auto* in = context.Input<framework::Tensor>("X");
    auto* out = context.Output<framework::Tensor>("Out");
    auto* out_scale = context.Output<framework::Tensor>("OutScale");
    T* out_scale_data = out_scale->mutable_data<T>(context.GetPlace());
    auto& dev_ctx = context.template device_context<DeviceContext>();
    out->mutable_data<T>(dev_ctx.GetPlace());

    int bit_length = context.Attr<int>("bit_length");
    int bin_cnt = std::pow(2, bit_length - 1) - 1;
    int quant_axis = context.Attr<int>("quant_axis");

    FindChannelAbsMaxFunctor<DeviceContext, T>()(dev_ctx, *in, quant_axis,
                                                 out_scale_data);

    ChannelClipFakeQuantDequantFunctor<DeviceContext, T>()(
        dev_ctx, *in, *out_scale, bin_cnt, quant_axis, out);
  }
};

191 192 193 194
template <typename DeviceContext, typename T>
class FakeQuantizeRangeAbsMaxKernel : public framework::OpKernel<T> {
 public:
  void Compute(const framework::ExecutionContext& context) const override {
视言's avatar
视言 已提交
195
    auto* in = context.Input<framework::Tensor>("X");
196
    auto* in_scale = context.Input<framework::Tensor>("InScale");
视言's avatar
视言 已提交
197

198 199 200 201
    auto* out = context.Output<framework::Tensor>("Out");
    out->mutable_data<T>(context.GetPlace());

    bool is_test = context.Attr<bool>("is_test");
视言's avatar
视言 已提交
202 203
    int bit_length = context.Attr<int>("bit_length");
    int bin_cnt = std::pow(2, bit_length - 1) - 1;
204
    auto& dev_ctx = context.template device_context<DeviceContext>();
视言's avatar
视言 已提交
205

206 207 208 209 210
    // testing
    if (is_test) {
      ClipAndFakeQuantFunctor<DeviceContext, T>()(dev_ctx, *in, *in_scale,
                                                  bin_cnt, out);
      return;
视言's avatar
视言 已提交
211 212
    }

213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229
    // training
    auto* out_scale = context.Output<framework::Tensor>("OutScale");
    auto* out_scales = context.Output<framework::Tensor>("OutScales");
    auto* iter = context.Input<framework::Tensor>("Iter");

    int window_size = context.Attr<int>("window_size");
    out_scale->mutable_data<T>(context.GetPlace());

    framework::Tensor cur_scale;
    T* cur_scale_data = cur_scale.mutable_data<T>({1}, context.GetPlace());
    FindAbsMaxFunctor<DeviceContext, T>()(dev_ctx, in->data<T>(), in->numel(),
                                          cur_scale_data);
    FindRangeAbsMaxFunctor<DeviceContext, T>()(dev_ctx, cur_scale, *in_scale,
                                               *iter, window_size, out_scales,
                                               out_scale);
    ClipAndFakeQuantFunctor<DeviceContext, T>()(dev_ctx, *in, *out_scale,
                                                bin_cnt, out);
视言's avatar
视言 已提交
230 231 232
  }
};

233
template <typename DeviceContext, typename T>
234
class FakeMovingAverageAbsMaxKernelBase : public framework::OpKernel<T> {
235 236 237 238 239 240 241 242 243 244 245 246 247 248
 public:
  void Compute(const framework::ExecutionContext& context) const override {
    auto* in = context.Input<framework::Tensor>("X");
    auto* in_scale = context.Input<framework::Tensor>("InScale");
    auto* out = context.Output<framework::Tensor>("Out");
    out->mutable_data<T>(context.GetPlace());

    bool is_test = context.Attr<bool>("is_test");
    int bit_length = context.Attr<int>("bit_length");
    int bin_cnt = std::pow(2, bit_length - 1) - 1;
    auto& dev_ctx = context.template device_context<DeviceContext>();

    // testing
    if (is_test) {
249
      RunClipFunctor(dev_ctx, *in, *in_scale, bin_cnt, out);
250 251 252 253 254 255
      return;
    }

    // training
    auto* in_accum = context.Input<framework::Tensor>("InAccum");
    auto* in_state = context.Input<framework::Tensor>("InState");
256
    auto cur_scale = memory::Alloc(dev_ctx, sizeof(T));
257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273
    T* cur_scale_data = static_cast<T*>(cur_scale->ptr());

    FindAbsMaxFunctor<DeviceContext, T>()(dev_ctx, in->data<T>(), in->numel(),
                                          cur_scale_data);

    auto* out_state = context.Output<framework::Tensor>("OutState");
    auto* out_accum = context.Output<framework::Tensor>("OutAccum");
    auto* out_scale = context.Output<framework::Tensor>("OutScale");
    out_state->mutable_data<T>(context.GetPlace());
    out_accum->mutable_data<T>(context.GetPlace());
    out_scale->mutable_data<T>(context.GetPlace());
    float moving_rate = context.Attr<float>("moving_rate");

    FindMovingAverageAbsMaxFunctor<DeviceContext, T>()(
        dev_ctx, *in_accum, *in_state, cur_scale_data, moving_rate, out_state,
        out_accum, out_scale);

274 275
    RunClipFunctor(dev_ctx, *in, *out_scale, bin_cnt, out);
  }
276 277 278 279 280 281 282 283

  virtual ~FakeMovingAverageAbsMaxKernelBase() = default;

 protected:
  virtual void RunClipFunctor(const DeviceContext& dev_ctx,
                              const framework::Tensor& in,
                              const framework::Tensor& in_scale, int bin_cnt,
                              framework::Tensor* out) const = 0;
284 285 286 287 288
};

template <typename DeviceContext, typename T>
class FakeQuantizeMovingAverageAbsMaxKernel
    : public FakeMovingAverageAbsMaxKernelBase<DeviceContext, T> {
289
 protected:
290 291 292 293 294 295 296 297 298 299 300
  void RunClipFunctor(const DeviceContext& dev_ctx, const framework::Tensor& in,
                      const framework::Tensor& in_scale, int bin_cnt,
                      framework::Tensor* out) const override {
    ClipAndFakeQuantFunctor<DeviceContext, T>()(dev_ctx, in, in_scale, bin_cnt,
                                                out);
  }
};

template <typename DeviceContext, typename T>
class FakeQuantizeDequantizeMovingAverageAbsMaxKernel
    : public FakeMovingAverageAbsMaxKernelBase<DeviceContext, T> {
301
 protected:
302 303 304 305 306
  void RunClipFunctor(const DeviceContext& dev_ctx, const framework::Tensor& in,
                      const framework::Tensor& in_scale, int bin_cnt,
                      framework::Tensor* out) const override {
    ClipAndFakeQuantDequantFunctor<DeviceContext, T>()(dev_ctx, in, in_scale,
                                                       bin_cnt, out);
307 308 309
  }
};

Z
Zhen Wang 已提交
310 311 312 313 314 315 316
template <typename DeviceContext, typename T>
class MovingAverageAbsMaxScaleKernel : public framework::OpKernel<T> {
 public:
  void Compute(const framework::ExecutionContext& context) const override {
    auto* in = context.Input<framework::Tensor>("X");
    auto& dev_ctx = context.template device_context<DeviceContext>();

317 318 319 320 321 322
    if (context.HasOutput("Out")) {
      auto* out = context.Output<framework::Tensor>("Out");
      out->mutable_data<T>(context.GetPlace());
      framework::TensorCopy(*in, context.GetPlace(), dev_ctx, out);
    }

Z
Zhen Wang 已提交
323 324 325 326 327 328 329 330 331
    bool is_test = context.Attr<bool>("is_test");
    // testing
    if (is_test) {
      return;
    }

    // training
    auto* in_accum = context.Input<framework::Tensor>("InAccum");
    auto* in_state = context.Input<framework::Tensor>("InState");
332
    auto cur_scale = memory::Alloc(dev_ctx, sizeof(T));
Z
Zhen Wang 已提交
333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351
    T* cur_scale_data = static_cast<T*>(cur_scale->ptr());

    FindAbsMaxFunctor<DeviceContext, T>()(dev_ctx, in->data<T>(), in->numel(),
                                          cur_scale_data);

    auto* out_state = context.Output<framework::Tensor>("OutState");
    auto* out_accum = context.Output<framework::Tensor>("OutAccum");
    auto* out_scale = context.Output<framework::Tensor>("OutScale");
    out_state->mutable_data<T>(context.GetPlace());
    out_accum->mutable_data<T>(context.GetPlace());
    out_scale->mutable_data<T>(context.GetPlace());
    float moving_rate = context.Attr<float>("moving_rate");

    FindMovingAverageAbsMaxFunctor<DeviceContext, T>()(
        dev_ctx, *in_accum, *in_state, cur_scale_data, moving_rate, out_state,
        out_accum, out_scale);
  }
};

352
template <typename DeviceContext, typename T>
353
class StrightThroughEstimatorGradKernel : public framework::OpKernel<T> {
354 355 356 357 358 359
 public:
  void Compute(const framework::ExecutionContext& context) const override {
    auto* d_out =
        context.Input<framework::LoDTensor>(framework::GradVarName("Out"));
    auto x_grad_name = framework::GradVarName("X");
    auto* d_x = context.Output<framework::LoDTensor>(x_grad_name);
360 361 362 363
    PADDLE_ENFORCE_NOT_NULL(d_x, platform::errors::PreconditionNotMet(
                                     "StrightThroughEstimatorGradKernel "
                                     "doesn't have the output named %s.",
                                     x_grad_name));
364 365 366 367 368 369 370

    // Initialize dx as same as d_out
    d_x->mutable_data<T>(context.GetPlace());
    framework::TensorCopy(*d_out, context.GetPlace(), d_x);
  }
};

视言's avatar
视言 已提交
371 372
}  // namespace operators
}  // namespace paddle