fake_quantize_op.h 16.5 KB
Newer Older
视言's avatar
视言 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
/* 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>
18

视言's avatar
视言 已提交
19 20
#include "paddle/fluid/framework/eigen.h"
#include "paddle/fluid/framework/op_registry.h"
Z
Zhen Wang 已提交
21
#include "paddle/fluid/framework/tensor_util.h"
22
#include "paddle/fluid/memory/malloc.h"
23
#include "paddle/fluid/platform/transform.h"
24 25
#include "paddle/phi/core/hostdevice.h"
#include "paddle/phi/kernels/funcs/blas/blas.h"
视言's avatar
视言 已提交
26 27 28 29

namespace paddle {
namespace operators {

30 31
template <typename T>
inline HOSTDEVICE T inverse(T s) {
W
whs 已提交
32 33 34
  T eps = static_cast<T>(1e-6);
  T one = static_cast<T>(1.0);
  return s <= static_cast<T>(1e-30) ? one / (s + eps) : one / s;
35 36
}

37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
template <typename T>
inline HOSTDEVICE T roundWithTiesToEven(T x) {
  T xLower = floor(x);
  T xUpper = ceil(x);
  // x is in interval [xl,xu]. Choose closest of two bounds, breaking ties to
  // even.
  T dLower = x - xLower;
  T dUpper = xUpper - x;
  return static_cast<T>(
      (dLower == dUpper ? fmod(xLower, 2.0F) == 0.0F : dLower < dUpper)
          ? xLower
          : xUpper);
}

template <typename T>
class QuantTensorFunctor {
 public:
  explicit QuantTensorFunctor(const T bin_cnt, const int round_type,
                              const T inv_s)
      : bin_cnt_(bin_cnt), round_type_(round_type), inv_s_(inv_s) {}
  HOSTDEVICE T operator()(const T x) const {
    T out = bin_cnt_ * inv_s_ * x;
    if (round_type_ == 0) {
      out = roundWithTiesToEven(out);
    } else if (round_type_ == 1) {
      out = std::round(out);
    }
    T max_bound = bin_cnt_;
    T min_bound = -bin_cnt_ - static_cast<T>(1);
    out = out > max_bound ? max_bound : out;
    out = out < min_bound ? min_bound : out;
    return out;
  }

 private:
  T bin_cnt_;
  int round_type_;
  T inv_s_;
};

77 78 79 80
template <typename DeviceContext, typename T>
struct FindAbsMaxFunctor {
  void operator()(const DeviceContext& ctx, const T* in, const int num, T* out);
};
视言's avatar
视言 已提交
81 82

template <typename DeviceContext, typename T>
83 84 85
struct ClipAndFakeQuantFunctor {
  void operator()(const DeviceContext& ctx, const framework::Tensor& in,
                  const framework::Tensor& scale, const int bin_cnt,
86
                  const int round_type, framework::Tensor* out);
87 88
};

89 90 91 92
template <typename DeviceContext, typename T>
struct ClipAndFakeQuantDequantFunctor {
  void operator()(const DeviceContext& ctx, const framework::Tensor& in,
                  const framework::Tensor& scale, const int bin_cnt,
93
                  int round_type, framework::Tensor* out);
94 95
};

96 97 98 99 100 101 102 103
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);
};

104 105
template <typename DeviceContext, typename T>
struct FindChannelAbsMaxFunctor {
106 107
  void operator()(const DeviceContext& ctx, const framework::Tensor& in_tensor,
                  const int quant_axis, T* out_abs_max);
108 109 110 111 112 113
};

template <typename DeviceContext, typename T>
struct ChannelClipAndFakeQuantFunctor {
  void operator()(const DeviceContext& ctx, const framework::Tensor& in,
                  const framework::Tensor& scale, const int bin_cnt,
114 115
                  const int round_type, const int quant_axis,
                  framework::Tensor* out);
116 117
};

H
huangxu96 已提交
118 119 120 121
template <typename DeviceContext, typename T>
struct ChannelClipFakeQuantDequantFunctor {
  void operator()(const DeviceContext& ctx, const framework::Tensor& in,
                  const framework::Tensor& scale, const int bin_cnt,
122
                  int round_type, const int quant_axis, framework::Tensor* out);
H
huangxu96 已提交
123 124
};

125 126 127 128 129 130 131 132 133
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);
};

134
template <typename DeviceContext, typename T>
135
class FakeAbsMaxKernelBase : public framework::OpKernel<T> {
视言's avatar
视言 已提交
136
 public:
137 138 139 140 141 142 143
  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");
144
    int round_type = context.Attr<int>("round_type");
145 146 147 148 149
    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);
150
    RunClipFunctor(dev_ctx, *in, *out_scale, bin_cnt, round_type, out);
151 152 153 154 155 156 157 158
  }

  virtual ~FakeAbsMaxKernelBase() = default;

 protected:
  virtual void RunClipFunctor(const DeviceContext& dev_ctx,
                              const framework::Tensor& in,
                              const framework::Tensor& scale, int bin_cnt,
159
                              int round_type, framework::Tensor* out) const = 0;
160 161 162 163 164 165 166
};

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,
167
                      int round_type, framework::Tensor* out) const override {
168
    ClipAndFakeQuantFunctor<DeviceContext, T>()(dev_ctx, in, scale, bin_cnt,
169
                                                round_type, out);
170 171 172 173 174 175 176 177 178
  }
};

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,
179 180 181
                      int round_type, framework::Tensor* out) const override {
    ClipAndFakeQuantDequantFunctor<DeviceContext, T>()(
        dev_ctx, in, scale, bin_cnt, round_type, out);
视言's avatar
视言 已提交
182
  }
183
};
视言's avatar
视言 已提交
184

Z
Zhen Wang 已提交
185 186 187 188 189 190 191
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");
192
    auto* out_scale = context.Output<framework::Tensor>("OutScale");
Z
Zhen Wang 已提交
193 194 195
    out->mutable_data<T>(context.GetPlace());

    int bit_length = context.Attr<int>("bit_length");
196
    int round_type = context.Attr<int>("round_type");
Z
Zhen Wang 已提交
197
    int bin_cnt = std::pow(2, bit_length - 1) - 1;
198
    int quant_axis = context.Attr<int>("quant_axis");
199
    bool is_test = context.Attr<bool>("is_test");
Z
Zhen Wang 已提交
200 201

    auto& dev_ctx = context.template device_context<DeviceContext>();
202 203 204 205 206
    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);
    }
207
    ChannelClipAndFakeQuantFunctor<DeviceContext, T>()(
208
        dev_ctx, *in, *out_scale, bin_cnt, round_type, quant_axis, out);
Z
Zhen Wang 已提交
209 210 211
  }
};

H
huangxu96 已提交
212 213 214 215 216 217 218 219 220 221 222 223 224
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");
225
    int round_type = context.Attr<int>("round_type");
H
huangxu96 已提交
226 227 228 229 230 231 232
    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>()(
233
        dev_ctx, *in, *out_scale, bin_cnt, round_type, quant_axis, out);
H
huangxu96 已提交
234 235 236
  }
};

237 238 239 240
template <typename DeviceContext, typename T>
class FakeQuantizeRangeAbsMaxKernel : public framework::OpKernel<T> {
 public:
  void Compute(const framework::ExecutionContext& context) const override {
视言's avatar
视言 已提交
241
    auto* in = context.Input<framework::Tensor>("X");
242
    auto* in_scale = context.Input<framework::Tensor>("InScale");
视言's avatar
视言 已提交
243

244 245 246 247
    auto* out = context.Output<framework::Tensor>("Out");
    out->mutable_data<T>(context.GetPlace());

    bool is_test = context.Attr<bool>("is_test");
视言's avatar
视言 已提交
248
    int bit_length = context.Attr<int>("bit_length");
249
    int round_type = context.Attr<int>("round_type");
视言's avatar
视言 已提交
250
    int bin_cnt = std::pow(2, bit_length - 1) - 1;
251
    auto& dev_ctx = context.template device_context<DeviceContext>();
视言's avatar
视言 已提交
252

253 254 255
    // testing
    if (is_test) {
      ClipAndFakeQuantFunctor<DeviceContext, T>()(dev_ctx, *in, *in_scale,
256
                                                  bin_cnt, round_type, out);
257
      return;
视言's avatar
视言 已提交
258 259
    }

260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275
    // 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,
276
                                                bin_cnt, round_type, out);
视言's avatar
视言 已提交
277 278 279
  }
};

280
template <typename DeviceContext, typename T>
281
class FakeMovingAverageAbsMaxKernelBase : public framework::OpKernel<T> {
282 283 284 285 286 287 288 289 290
 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");
291
    int round_type = context.Attr<int>("round_type");
292 293 294 295 296
    int bin_cnt = std::pow(2, bit_length - 1) - 1;
    auto& dev_ctx = context.template device_context<DeviceContext>();

    // testing
    if (is_test) {
297
      RunClipFunctor(dev_ctx, *in, *in_scale, bin_cnt, round_type, out);
298 299 300 301 302 303
      return;
    }

    // training
    auto* in_accum = context.Input<framework::Tensor>("InAccum");
    auto* in_state = context.Input<framework::Tensor>("InState");
304
    auto cur_scale = memory::Alloc(dev_ctx, sizeof(T));
305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321
    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);

322
    RunClipFunctor(dev_ctx, *in, *out_scale, bin_cnt, round_type, out);
323
  }
324 325 326 327 328 329 330

  virtual ~FakeMovingAverageAbsMaxKernelBase() = default;

 protected:
  virtual void RunClipFunctor(const DeviceContext& dev_ctx,
                              const framework::Tensor& in,
                              const framework::Tensor& in_scale, int bin_cnt,
331
                              int round_type, framework::Tensor* out) const = 0;
332 333 334 335 336
};

template <typename DeviceContext, typename T>
class FakeQuantizeMovingAverageAbsMaxKernel
    : public FakeMovingAverageAbsMaxKernelBase<DeviceContext, T> {
337
 protected:
338 339
  void RunClipFunctor(const DeviceContext& dev_ctx, const framework::Tensor& in,
                      const framework::Tensor& in_scale, int bin_cnt,
340
                      int round_type, framework::Tensor* out) const override {
341
    ClipAndFakeQuantFunctor<DeviceContext, T>()(dev_ctx, in, in_scale, bin_cnt,
342
                                                round_type, out);
343 344 345 346 347 348
  }
};

template <typename DeviceContext, typename T>
class FakeQuantizeDequantizeMovingAverageAbsMaxKernel
    : public FakeMovingAverageAbsMaxKernelBase<DeviceContext, T> {
349
 protected:
350 351
  void RunClipFunctor(const DeviceContext& dev_ctx, const framework::Tensor& in,
                      const framework::Tensor& in_scale, int bin_cnt,
352 353 354
                      int round_type, framework::Tensor* out) const override {
    ClipAndFakeQuantDequantFunctor<DeviceContext, T>()(
        dev_ctx, in, in_scale, bin_cnt, round_type, out);
355 356 357
  }
};

Z
Zhen Wang 已提交
358 359 360 361 362 363 364
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>();

365 366 367 368 369 370
    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 已提交
371 372 373 374 375 376 377 378 379
    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");
380
    auto cur_scale = memory::Alloc(dev_ctx, sizeof(T));
Z
Zhen Wang 已提交
381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399
    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);
  }
};

400
template <typename DeviceContext, typename T>
401
class StrightThroughEstimatorGradKernel : public framework::OpKernel<T> {
402 403 404 405 406 407
 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);
408 409 410 411
    PADDLE_ENFORCE_NOT_NULL(d_x, platform::errors::PreconditionNotMet(
                                     "StrightThroughEstimatorGradKernel "
                                     "doesn't have the output named %s.",
                                     x_grad_name));
412 413 414 415 416 417 418

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

视言's avatar
视言 已提交
419 420
}  // namespace operators
}  // namespace paddle