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

#include "paddle/fluid/operators/fake_quantize_op.h"
16

17
#include <algorithm>
视言's avatar
视言 已提交
18
#include <string>
19

20
#include "paddle/fluid/framework/eigen.h"
21
#include "paddle/fluid/framework/op_version_registry.h"
22
#include "paddle/fluid/platform/transform.h"
W
wuyefeilin 已提交
23
#include "paddle/phi/kernels/impl/clip_kernel_impl.h"
视言's avatar
视言 已提交
24 25 26 27

namespace paddle {
namespace operators {

28 29 30 31 32
template <typename T>
struct Compare {
 public:
  bool operator()(const T a, const T b) { return (std::abs(a) < std::abs(b)); }
};
33 34

template <typename T>
L
Leo Chen 已提交
35 36
struct FindAbsMaxFunctor<phi::CPUContext, T> {
  void operator()(const phi::CPUContext &ctx,
37 38 39
                  const T *in,
                  const int num,
                  T *out) {
40
    *out = std::abs(*(std::max_element(in + 0, in + num, Compare<T>())));
41 42 43
  }
};

L
Leo Chen 已提交
44
template struct FindAbsMaxFunctor<phi::CPUContext, float>;
45

46
template <typename T>
L
Leo Chen 已提交
47 48
struct FindChannelAbsMaxFunctor<phi::CPUContext, T> {
  void operator()(const phi::CPUContext &ctx,
49 50 51
                  const framework::Tensor &in_tensor,
                  const int quant_axis,
                  T *out_abs_max) {
52 53 54
    // At present, channelwise quantization supports conv2d, depthwise_conv2d
    // conv2d_transpose and mul
    PADDLE_ENFORCE_EQ(
55 56
        quant_axis == 0 || quant_axis == 1,
        true,
57 58 59
        platform::errors::InvalidArgument("'quant_axis' should be 0 or 1, but "
                                          "the received is %d",
                                          quant_axis));
60
    auto *in_data = in_tensor.data<T>();
61 62 63 64 65
    auto in_dims = in_tensor.dims();
    const int64_t channel = in_dims[quant_axis];
    if (quant_axis == 0) {
      const int64_t channel_size = in_tensor.numel() / channel;
      for (int64_t i = 0; i < channel; i++) {
66 67
        auto *start = in_data + i * channel_size;
        auto *end = in_data + (i + 1) * channel_size;
68 69 70 71 72 73 74 75 76 77 78
        out_abs_max[i] =
            std::abs(*(std::max_element(start, end, Compare<T>())));
      }
    } else if (quant_axis == 1) {
      for (int64_t i = 0; i < channel; i++) {
        out_abs_max[i] = 0;
      }
      const int64_t step_i = in_tensor.numel() / in_dims[0];
      const int64_t step_j = in_tensor.numel() / (in_dims[0] * in_dims[1]);
      for (int64_t i = 0; i < in_dims[0]; i++) {
        for (int64_t j = 0; j < in_dims[1]; j++) {
79 80
          auto *start = in_data + i * step_i + j * step_j;
          auto *end = in_data + i * step_i + (j + 1) * step_j;
81 82 83 84
          T abs_max = std::abs(*(std::max_element(start, end, Compare<T>())));
          out_abs_max[j] = std::max(out_abs_max[j], abs_max);
        }
      }
85 86 87 88
    }
  }
};

L
Leo Chen 已提交
89
template struct FindChannelAbsMaxFunctor<phi::CPUContext, float>;
90

91
template <typename T>
L
Leo Chen 已提交
92 93
struct ClipAndFakeQuantFunctor<phi::CPUContext, T> {
  void operator()(const phi::CPUContext &ctx,
94 95 96 97 98
                  const framework::Tensor &in,
                  const framework::Tensor &scale,
                  const int bin_cnt,
                  const int round_type,
                  framework::Tensor *out) {
99
    T s = scale.data<T>()[0];
100
    T inv_s = inverse(s);
L
Leo Chen 已提交
101
    platform::Transform<phi::CPUContext> trans;
102 103 104 105 106 107 108 109 110 111 112 113 114 115 116
    if (round_type == 0) {
      trans(ctx,
            in.data<T>(),
            in.data<T>() + in.numel(),
            out->mutable_data<T>(ctx.GetPlace()),
            QuantTensorFunctor<T>(static_cast<T>(bin_cnt), inv_s));
    } else {
      trans(ctx,
            in.data<T>(),
            in.data<T>() + in.numel(),
            out->mutable_data<T>(ctx.GetPlace()),
            phi::ClipFunctor<T>(-s, s));
      auto out_e = framework::EigenVector<T>::Flatten(*out);
      out_e.device(*ctx.eigen_device()) = (bin_cnt * inv_s * out_e).round();
    }
117 118 119
  }
};

L
Leo Chen 已提交
120
template struct ClipAndFakeQuantFunctor<phi::CPUContext, float>;
121

122
template <typename T>
L
Leo Chen 已提交
123 124
struct ClipAndFakeQuantDequantFunctor<phi::CPUContext, T> {
  void operator()(const phi::CPUContext &ctx,
125 126 127 128 129
                  const framework::Tensor &in,
                  const framework::Tensor &scale,
                  const int bin_cnt,
                  const int round_type,
                  framework::Tensor *out) {
130
    T s = scale.data<T>()[0];
131 132
    T inv_s = inverse(s);

L
Leo Chen 已提交
133
    platform::Transform<phi::CPUContext> trans;
134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151
    if (round_type == 0) {
      trans(ctx,
            in.data<T>(),
            in.data<T>() + in.numel(),
            out->mutable_data<T>(ctx.GetPlace()),
            QuantTensorFunctor<T>(static_cast<T>(bin_cnt), inv_s));
      auto out_e = framework::EigenVector<T>::Flatten(*out);
      out_e.device(*ctx.eigen_device()) = out_e * s / static_cast<T>(bin_cnt);
    } else {
      trans(ctx,
            in.data<T>(),
            in.data<T>() + in.numel(),
            out->mutable_data<T>(ctx.GetPlace()),
            phi::ClipFunctor<T>(-s, s));
      auto out_e = framework::EigenVector<T>::Flatten(*out);
      out_e.device(*ctx.eigen_device()) =
          (bin_cnt * inv_s * out_e).round() * s / static_cast<T>(bin_cnt);
    }
152 153
  }
};
L
Leo Chen 已提交
154
template struct ClipAndFakeQuantDequantFunctor<phi::CPUContext, float>;
155

156
template <typename T>
L
Leo Chen 已提交
157 158
struct ChannelClipAndFakeQuantFunctor<phi::CPUContext, T> {
  void operator()(const phi::CPUContext &ctx,
159 160 161 162 163 164
                  const framework::Tensor &in,
                  const framework::Tensor &scale,
                  const int bin_cnt,
                  const int round_type,
                  const int quant_axis,
                  framework::Tensor *out) {
165 166 167
    // At present, channelwise quantization supports conv2d, depthwise_conv2d
    // conv2d_transpose and mul
    PADDLE_ENFORCE_EQ(
168 169
        quant_axis == 0 || quant_axis == 1,
        true,
170 171 172
        platform::errors::InvalidArgument("'quant_axis' should be 0 or 1, but "
                                          "the received is %d",
                                          quant_axis));
173 174 175
    auto *scale_data = scale.data<T>();
    auto *in_data = in.data<T>();
    auto *out_data = out->mutable_data<T>(ctx.GetPlace());
176 177
    auto in_dims = in.dims();
    const int64_t channel = in_dims[quant_axis];
L
Leo Chen 已提交
178
    platform::Transform<phi::CPUContext> trans;
179 180 181 182
    if (quant_axis == 0) {
      const int64_t channel_size = in.numel() / channel;
      for (int64_t i = 0; i < channel; i++) {
        T s = scale_data[i];
183 184
        auto *start = in_data + i * channel_size;
        auto *end = in_data + (i + 1) * channel_size;
185
        T inv_s = inverse(s);
186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207
        if (round_type == 0) {
          trans(ctx,
                start,
                end,
                out_data + i * channel_size,
                QuantTensorFunctor<T>(static_cast<T>(bin_cnt), inv_s));
        } else {
          trans(ctx,
                start,
                end,
                out_data + i * channel_size,
                phi::ClipFunctor<T>(-s, s));
        }
      }
      if (round_type == 1) {
        for (int64_t i = 0; i < channel; i++) {
          T s = scale_data[i];
          T inv_s = inverse(s);
          framework::Tensor one_channel_out = out->Slice(i, i + 1);
          auto out_e = framework::EigenVector<T>::Flatten(one_channel_out);
          out_e.device(*ctx.eigen_device()) = (bin_cnt * inv_s * out_e).round();
        }
208 209 210 211 212 213 214 215
      }
    } else if (quant_axis == 1) {
      const int64_t step_i = in.numel() / in_dims[0];
      const int64_t step_j = in.numel() / (in_dims[0] * in_dims[1]);
      for (int i = 0; i < in_dims[0]; i++) {
        for (int j = 0; j < in_dims[1]; j++) {
          T s = scale_data[j];
          T inv_s = inverse(s);
216 217 218 219 220 221 222 223 224 225 226 227 228 229 230
          auto *start = in_data + i * step_i + j * step_j;
          auto *end = in_data + i * step_i + (j + 1) * step_j;
          auto *cur_out_data = out_data + i * step_i + j * step_j;
          if (round_type == 0) {
            trans(ctx,
                  start,
                  end,
                  cur_out_data,
                  QuantTensorFunctor<T>(static_cast<T>(bin_cnt), inv_s));
          } else {
            trans(ctx, start, end, cur_out_data, phi::ClipFunctor<T>(-s, s));
            for (int k = 0; k < step_j; k++) {
              cur_out_data[k] = std::round(bin_cnt * inv_s * cur_out_data[k]);
            }
          }
231 232
        }
      }
233 234 235 236
    }
  }
};

L
Leo Chen 已提交
237
template struct ChannelClipAndFakeQuantFunctor<phi::CPUContext, float>;
H
huangxu96 已提交
238
template <typename T>
L
Leo Chen 已提交
239 240
struct ChannelClipFakeQuantDequantFunctor<phi::CPUContext, T> {
  void operator()(const phi::CPUContext &ctx,
241 242 243 244 245 246
                  const framework::Tensor &in,
                  const framework::Tensor &scale,
                  const int bin_cnt,
                  const int round_type,
                  const int quant_axis,
                  framework::Tensor *out) {
H
huangxu96 已提交
247
    PADDLE_ENFORCE_EQ(
248 249
        quant_axis == 0 || quant_axis == 1,
        true,
H
huangxu96 已提交
250 251 252
        platform::errors::InvalidArgument("'quant_axis' should be 0 or 1, but "
                                          "the received is %d",
                                          quant_axis));
253

254 255 256
    auto *scale_data = scale.data<T>();
    auto *in_data = in.data<T>();
    auto *out_data = out->mutable_data<T>(ctx.GetPlace());
H
huangxu96 已提交
257 258
    auto in_dims = in.dims();
    const int64_t channel = in_dims[quant_axis];
L
Leo Chen 已提交
259
    platform::Transform<phi::CPUContext> trans;
H
huangxu96 已提交
260 261 262 263
    if (quant_axis == 0) {
      const int64_t channel_size = in.numel() / channel;
      for (int i = 0; i < channel; i++) {
        T s = scale_data[i];
264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282
        auto *start = in_data + i * channel_size;
        auto *end = in_data + (i + 1) * channel_size;
        if (round_type == 0) {
          T inv_s = inverse(s);
          trans(ctx,
                start,
                end,
                out_data + i * channel_size,
                QuantTensorFunctor<T>(static_cast<T>(bin_cnt), inv_s));
        } else {
          trans(ctx,
                start,
                end,
                out_data + i * channel_size,
                phi::ClipFunctor<T>(-s, s));
        }
      }
      for (int i = 0; i < channel; i++) {
        T s = scale_data[i];
H
huangxu96 已提交
283 284
        framework::Tensor one_channel_out = out->Slice(i, i + 1);
        auto out_e = framework::EigenVector<T>::Flatten(one_channel_out);
285 286 287 288 289 290 291 292
        if (round_type == 0) {
          out_e.device(*ctx.eigen_device()) =
              out_e * s / static_cast<T>(bin_cnt);
        } else {
          T inv_s = inverse(s);
          out_e.device(*ctx.eigen_device()) =
              (bin_cnt * inv_s * out_e).round() * s / static_cast<T>(bin_cnt);
        }
H
huangxu96 已提交
293 294 295 296 297 298 299 300
      }
    } else if (quant_axis == 1) {
      const int64_t step_i = in.numel() / in_dims[0];
      const int64_t step_j = in.numel() / (in_dims[0] * in_dims[1]);
      for (int i = 0; i < in_dims[0]; i++) {
        for (int j = 0; j < in_dims[1]; j++) {
          T s = scale_data[j];
          T inv_s = inverse(s);
301 302 303 304 305 306 307 308 309 310 311 312
          auto *start = in_data + i * step_i + j * step_j;
          auto *end = in_data + i * step_i + (j + 1) * step_j;
          auto *cur_out_data = out_data + i * step_i + j * step_j;
          if (round_type == 0) {
            trans(ctx,
                  start,
                  end,
                  cur_out_data,
                  QuantTensorFunctor<T>(static_cast<T>(bin_cnt), inv_s));
          } else {
            trans(ctx, start, end, cur_out_data, phi::ClipFunctor<T>(-s, s));
          }
H
huangxu96 已提交
313
          for (int k = 0; k < step_j; k++) {
314 315 316 317 318 319
            if (round_type == 0) {
              cur_out_data[k] = cur_out_data[k] * s / static_cast<T>(bin_cnt);
            } else {
              cur_out_data[k] = std::round(bin_cnt * inv_s * cur_out_data[k]) *
                                s / static_cast<T>(bin_cnt);
            }
H
huangxu96 已提交
320 321 322 323 324 325 326
          }
        }
      }
    }
  }
};

L
Leo Chen 已提交
327
template struct ChannelClipFakeQuantDequantFunctor<phi::CPUContext, float>;
328
template <typename T>
L
Leo Chen 已提交
329 330
struct FindRangeAbsMaxFunctor<phi::CPUContext, T> {
  void operator()(const phi::CPUContext &ctx,
331 332 333 334 335 336 337
                  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) {
    T *scale_arr = scales_arr->mutable_data<T>(ctx.GetPlace());
338 339 340 341 342 343 344 345 346 347 348
    int64_t it = iter.data<int64_t>()[0];
    int idx = it % window_size;
    T removed = scale_arr[idx];
    T cur = cur_scale.data<T>()[0];
    scale_arr[idx] = cur;

    T max = last_scale.data<T>()[0];
    if (max < cur) {
      max = cur;
    } else if (fabs(removed - max) < 1e-6) {
      int size = (it > window_size) ? window_size : it;
L
Leo Chen 已提交
349
      FindAbsMaxFunctor<phi::CPUContext, T>()(ctx, scale_arr, size, &max);
350 351 352 353 354
    }
    out_scale->mutable_data<T>(ctx.GetPlace())[0] = max;
  }
};

L
Leo Chen 已提交
355
template struct FindRangeAbsMaxFunctor<phi::CPUContext, float>;
356

357
template <typename T>
L
Leo Chen 已提交
358 359
struct FindMovingAverageAbsMaxFunctor<phi::CPUContext, T> {
  void operator()(const phi::CPUContext &ctx,
360 361 362 363 364 365 366
                  const framework::Tensor &in_accum,
                  const framework::Tensor &in_state,
                  const T *cur_scale,
                  const float rate,
                  framework::Tensor *out_state,
                  framework::Tensor *out_accum,
                  framework::Tensor *out_scale) {
367 368 369 370 371 372 373 374 375 376 377 378 379 380
    T accum = in_accum.data<T>()[0];
    T state = in_state.data<T>()[0];
    T scale = cur_scale[0];

    state = rate * state + 1;
    accum = rate * accum + scale;
    scale = accum / state;

    out_state->mutable_data<T>(ctx.GetPlace())[0] = state;
    out_accum->mutable_data<T>(ctx.GetPlace())[0] = accum;
    out_scale->mutable_data<T>(ctx.GetPlace())[0] = scale;
  }
};

L
Leo Chen 已提交
381
template struct FindMovingAverageAbsMaxFunctor<phi::CPUContext, float>;
382

383
class FakeQuantOrWithDequantAbsMaxOp : public framework::OperatorWithKernel {
视言's avatar
视言 已提交
384
 public:
385 386 387 388
  FakeQuantOrWithDequantAbsMaxOp(const std::string &type,
                                 const framework::VariableNameMap &inputs,
                                 const framework::VariableNameMap &outputs,
                                 const framework::AttributeMap &attrs)
视言's avatar
视言 已提交
389 390
      : OperatorWithKernel(type, inputs, outputs, attrs) {}

391 392 393 394 395 396
  void InferShape(framework::InferShapeContext *ctx) const override {
    OP_INOUT_CHECK(
        ctx->HasInput("X"), "Input", "X", "FakeQuantOrWithDequantAbsMaxOp");
    OP_INOUT_CHECK(ctx->HasOutput("Out"),
                   "Output",
                   "Out",
397
                   "FakeQuantOrWithDequantAbsMaxOp");
398 399 400
    OP_INOUT_CHECK(ctx->HasOutput("OutScale"),
                   "Output",
                   "OutScale",
401
                   "FakeQuantOrWithDequantAbsMaxOp");
视言's avatar
视言 已提交
402
    ctx->SetOutputDim("Out", ctx->GetInputDim("X"));
403
    ctx->SetOutputDim("OutScale", {1});
视言's avatar
视言 已提交
404 405
    ctx->ShareLoD("X", /*->*/ "Out");
  }
406 407 408

 protected:
  framework::OpKernelType GetExpectedKernelType(
409
      const framework::ExecutionContext &ctx) const override {
410 411 412
    return framework::OpKernelType(
        OperatorWithKernel::IndicateVarDataType(ctx, "X"),
        ctx.device_context());
413
  }
视言's avatar
视言 已提交
414 415
};

416 417
class FakeQuantOrWithDequantAbsMaxOpMaker
    : public framework::OpProtoAndCheckerMaker {
视言's avatar
视言 已提交
418 419
 public:
  void Make() override {
420 421 422 423 424
    AddInput("X", "(Tensor) Input is float data type.");
    AddOutput("Out",
              "(Tensor) Output of quantized low level tensor, "
              "but also saved as float data type.");
    AddOutput("OutScale", "(Tensor) Current scale");
视言's avatar
视言 已提交
425 426
    AddAttr<int>("bit_length", "(int, default 8)")
        .SetDefault(8)
427 428 429
        .AddCustomChecker([](const int &bit_length) {
          PADDLE_ENFORCE_EQ(bit_length >= 1 && bit_length <= 16,
                            true,
430 431 432 433
                            platform::errors::InvalidArgument(
                                "'bit_length' should be between 1 and 16, but "
                                "the received is %d",
                                bit_length));
视言's avatar
视言 已提交
434
        });
435 436
    AddAttr<int>(
        "round_type",
437
        "(int, default 1) The round type of fp32 to int."
438 439 440
        "0: rounding to nearest ties to even. Eg: round(1.5)=2, round(2.5)=2"
        "1: rounding to nearest ties away from zero. Eg: round(1.5)=2, "
        "round(2.5)=3")
441 442 443 444 445 446 447 448 449 450 451 452
        .SetDefault(1)
        .AddCustomChecker([](const int &round_type) {
          PADDLE_ENFORCE_EQ(
              round_type == 0 || round_type == 1,
              true,
              platform::errors::InvalidArgument(
                  "'round_type' should be 0 or 1, 0 rounding to "
                  "nearest ties to even and 1 is rounding to nearest "
                  "ties away from zero.but the received is %d",
                  round_type));
        })
        .AsExtra();
视言's avatar
视言 已提交
453
    AddComment(R"DOC(
454
This is a Base Op which supports FakeQuantAbsMaxOpMaker and FakeQuantDequantAbsMaxOpMaker.
455
FakeQuantAbsMaxOp operator is used in the dynamic quantization.
视言's avatar
视言 已提交
456

457
$$scale = max(abs(X))$$
458 459
$$range = 2^{bit_length - 1} - 1$$
$$Out = round(X/scale * range)$$
视言's avatar
视言 已提交
460

461
FakeQuantDequantAbsMaxOp operator does the abs_max quantization and then dequantization.
462 463 464 465 466

$$scale = max(abs(X))$$
$$range = 2^{bit\_length - 1} - 1$$
$$Out = round(X/scale * range) * scale / range$$

467 468 469
)DOC");
  }
};
视言's avatar
视言 已提交
470

Z
Zhen Wang 已提交
471 472 473 474
class FakeChannelWiseQuantizeAbsMaxOp : public framework::OperatorWithKernel {
 public:
  using framework::OperatorWithKernel::OperatorWithKernel;

475 476 477 478 479 480
  void InferShape(framework::InferShapeContext *ctx) const override {
    OP_INOUT_CHECK(
        ctx->HasInput("X"), "Input", "X", "FakeChannelWiseQuantizeAbsMax");
    OP_INOUT_CHECK(ctx->HasOutput("Out"),
                   "Output",
                   "Out",
481
                   "FakeChannelWiseQuantizeAbsMax");
482 483 484
    OP_INOUT_CHECK(ctx->HasOutput("OutScale"),
                   "Output",
                   "OutScale",
485
                   "FakeChannelWiseQuantizeAbsMax");
486
    int quant_axis = ctx->Attrs().Get<int>("quant_axis");
Z
Zhen Wang 已提交
487
    ctx->SetOutputDim("Out", ctx->GetInputDim("X"));
488
    ctx->SetOutputDim("OutScale", {ctx->GetInputDim("X")[quant_axis]});
Z
Zhen Wang 已提交
489 490 491 492 493
    ctx->ShareLoD("X", /*->*/ "Out");
  }

 protected:
  framework::OpKernelType GetExpectedKernelType(
494
      const framework::ExecutionContext &ctx) const override {
495 496
    return framework::OpKernelType(
        OperatorWithKernel::IndicateVarDataType(ctx, "X"), ctx.GetPlace());
Z
Zhen Wang 已提交
497 498 499 500 501 502 503 504 505 506 507
  }
};

class FakeChannelWiseQuantizeAbsMaxOpMaker
    : public framework::OpProtoAndCheckerMaker {
 public:
  void Make() override {
    AddInput("X", "(Tensor) Input is float data type.");
    AddOutput("Out",
              "(Tensor) Output of quantized low level tensor, "
              "but also saved as float data type.");
508
    AddOutput("OutScale", "(Tensor) Current channel wise scale");
509 510 511 512 513
    AddAttr<int>("quant_axis",
                 "(int, default 0) The axis for quantization. "
                 "For conv2d, depthwise_conv2d, conv2d_transpose "
                 "and mul, the quant_axis is equal to the cout axis.")
        .SetDefault(0)
514 515 516
        .AddCustomChecker([](const int &quant_axis) {
          PADDLE_ENFORCE_EQ(quant_axis == 0 || quant_axis == 1,
                            true,
517 518 519 520 521
                            platform::errors::InvalidArgument(
                                "'quant_axis' should be 0 or 1, but "
                                "the received is %d",
                                quant_axis));
        });
Z
Zhen Wang 已提交
522 523
    AddAttr<int>("bit_length", "(int, default 8)")
        .SetDefault(8)
524 525 526
        .AddCustomChecker([](const int &bit_length) {
          PADDLE_ENFORCE_EQ(bit_length >= 1 && bit_length <= 16,
                            true,
527 528 529 530
                            platform::errors::InvalidArgument(
                                "'bit_length' should be between 1 and 16, but "
                                "the received is %d",
                                bit_length));
Z
Zhen Wang 已提交
531
        });
532 533
    AddAttr<int>(
        "round_type",
534
        "(int, default 1) The round type of fp32 to int."
535 536 537
        "0: rounding to nearest ties to even. Eg: round(1.5)=2, round(2.5)=2"
        "1: rounding to nearest ties away from zero. Eg: round(1.5)=2, "
        "round(2.5)=3")
538 539 540 541 542 543 544 545 546 547 548 549
        .SetDefault(1)
        .AddCustomChecker([](const int &round_type) {
          PADDLE_ENFORCE_EQ(
              round_type == 0 || round_type == 1,
              true,
              platform::errors::InvalidArgument(
                  "'round_type' should be 0 or 1, 0 rounding to "
                  "nearest ties to even and 1 is rounding to nearest "
                  "ties away from zero.but the received is %d",
                  round_type));
        })
        .AsExtra();
550 551 552 553
    AddAttr<bool>("is_test",
                  "(bool, default false) Set to true for inference only, false "
                  "for training. Some layers may run faster when this is true.")
        .SetDefault(false);
Z
Zhen Wang 已提交
554 555 556 557 558
    AddComment(R"DOC(
The scale of FakeChannelWiseQuantize operator is a vector.
In detail, each channel of the input X has a scale value.

$$scale_c = max(abs(X_c))$$
Z
Zhen Wang 已提交
559 560
$$range = 2^{bit\_length - 1} - 1$$
$$Out_c = round(\frac{X_c * range} {scale_c})$$
Z
Zhen Wang 已提交
561
In above three formulas, the range value of c is as follow:
Z
Zhen Wang 已提交
562
$$0 \leq c \lt \ the\ channel\ number\ of\ X$$
Z
Zhen Wang 已提交
563 564 565 566
)DOC");
  }
};

H
huangxu96 已提交
567 568 569 570 571
class FakeChannelWiseQuantizeDequantizeAbsMaxOp
    : public framework::OperatorWithKernel {
 public:
  using framework::OperatorWithKernel::OperatorWithKernel;

572 573 574 575
  void InferShape(framework::InferShapeContext *ctx) const override {
    OP_INOUT_CHECK(ctx->HasInput("X"),
                   "Input",
                   "X",
H
huangxu96 已提交
576
                   "FakeChannelWiseQuantizeDequantizeAbsMax");
577 578 579
    OP_INOUT_CHECK(ctx->HasOutput("Out"),
                   "Output",
                   "Out",
H
huangxu96 已提交
580
                   "FakeChannelWiseQuantizeDequantizeAbsMax");
581 582 583
    OP_INOUT_CHECK(ctx->HasOutput("OutScale"),
                   "Output",
                   "OutScale",
H
huangxu96 已提交
584 585 586 587 588 589 590 591 592
                   "FakeChannelWiseQuantizeDequantizeAbsMax");
    int quant_axis = ctx->Attrs().Get<int>("quant_axis");
    ctx->SetOutputDim("Out", ctx->GetInputDim("X"));
    ctx->SetOutputDim("OutScale", {ctx->GetInputDim("X")[quant_axis]});
    ctx->ShareLoD("X", /*->*/ "Out");
  }

 protected:
  framework::OpKernelType GetExpectedKernelType(
593
      const framework::ExecutionContext &ctx) const override {
H
huangxu96 已提交
594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612
    return framework::OpKernelType(
        OperatorWithKernel::IndicateVarDataType(ctx, "X"), ctx.GetPlace());
  }
};

class FakeChannelWiseQuantizeDequantizeAbsMaxOpMaker
    : public framework::OpProtoAndCheckerMaker {
 public:
  void Make() override {
    AddInput("X", "(Tensor) Input is float data type.");
    AddOutput("Out",
              "(Tensor) Output of quantized and dequantized low level tensor, "
              "saved as float data type.");
    AddOutput("OutScale", "(Tensor) Current channel wise scale");
    AddAttr<int>("quant_axis",
                 "(int, default 0) The axis for quantization. "
                 "For conv2d, depthwise_conv2d, conv2d_transpose "
                 "and mul, the quant_axis is equal to the cout axis.")
        .SetDefault(0)
613 614 615
        .AddCustomChecker([](const int &quant_axis) {
          PADDLE_ENFORCE_EQ(quant_axis == 0 || quant_axis == 1,
                            true,
H
huangxu96 已提交
616 617 618 619 620 621 622
                            platform::errors::InvalidArgument(
                                "'quant_axis' should be 0 or 1, but "
                                "the received is %d",
                                quant_axis));
        });
    AddAttr<int>("bit_length", "(int, default 8)")
        .SetDefault(8)
623 624 625
        .AddCustomChecker([](const int &bit_length) {
          PADDLE_ENFORCE_EQ(bit_length >= 1 && bit_length <= 16,
                            true,
H
huangxu96 已提交
626 627 628 629 630
                            platform::errors::InvalidArgument(
                                "'bit_length' should be between 1 and 16, but "
                                "the received is %d",
                                bit_length));
        });
631 632
    AddAttr<int>(
        "round_type",
633
        "(int, default 1) The round type of fp32 to int."
634 635 636
        "0: rounding to nearest ties to even. Eg: round(1.5)=2, round(2.5)=2"
        "1: rounding to nearest ties away from zero. Eg: round(1.5)=2, "
        "round(2.5)=3")
637 638 639 640 641 642 643 644 645 646 647 648
        .SetDefault(1)
        .AddCustomChecker([](const int &round_type) {
          PADDLE_ENFORCE_EQ(
              round_type == 0 || round_type == 1,
              true,
              platform::errors::InvalidArgument(
                  "'round_type' should be 0 or 1, 0 rounding to "
                  "nearest ties to even and 1 is rounding to nearest "
                  "ties away from zero.but the received is %d",
                  round_type));
        })
        .AsExtra();
H
huangxu96 已提交
649 650 651 652 653 654 655 656 657 658 659 660 661
    AddComment(R"DOC(
The scale of FakeChannelWiseQuantize operator is a vector.
In detail, each channel of the input X has a scale value.

$$scale_c = max(abs(X_c))$$
$$range = 2^{bit\_length - 1} - 1$$
$$Out_c = round(\frac{X_c * range} {scale_c}) * \frac{scale_c} {range}$$
In above three formulas, the range value of c is as follow:
$$0 \leq c \lt \ the\ channel\ number\ of\ X$$
)DOC");
  }
};

662 663
class FakeQuantizeRangeAbsMaxOp : public framework::OperatorWithKernel {
 public:
664 665 666 667
  FakeQuantizeRangeAbsMaxOp(const std::string &type,
                            const framework::VariableNameMap &inputs,
                            const framework::VariableNameMap &outputs,
                            const framework::AttributeMap &attrs)
668
      : OperatorWithKernel(type, inputs, outputs, attrs) {}
视言's avatar
视言 已提交
669

670
  void InferShape(framework::InferShapeContext *ctx) const override {
671
    OP_INOUT_CHECK(ctx->HasInput("X"), "Input", "X", "FakeQuantizeRangeAbsMax");
672 673 674 675 676
    OP_INOUT_CHECK(
        ctx->HasOutput("Out"), "Output", "Out", "FakeQuantizeRangeAbsMax");
    OP_INOUT_CHECK(ctx->HasOutput("OutScale"),
                   "Output",
                   "OutScale",
677
                   "FakeQuantizeRangeAbsMax");
678 679 680 681 682 683 684 685
    if (ctx->HasOutput("OutScales")) {
      int window_size = ctx->Attrs().Get<int>("window_size");
      ctx->SetOutputDim("OutScales", {window_size});
    }
    ctx->SetOutputDim("Out", ctx->GetInputDim("X"));
    ctx->SetOutputDim("OutScale", {1});
    ctx->ShareLoD("X", /*->*/ "Out");
  }
视言's avatar
视言 已提交
686

687 688
 protected:
  framework::OpKernelType GetExpectedKernelType(
689
      const framework::ExecutionContext &ctx) const override {
690 691 692
    return framework::OpKernelType(
        OperatorWithKernel::IndicateVarDataType(ctx, "X"),
        ctx.device_context());
693 694
  }
};
视言's avatar
视言 已提交
695

696 697 698 699 700 701 702 703 704 705 706 707 708 709
class FakeQuantizeRangeAbsMaxOpMaker
    : public framework::OpProtoAndCheckerMaker {
 public:
  void Make() override {
    AddInput("X", "(Tensor) Input is float data type.");
    AddInput("InScale", "Last scale.");
    AddInput("Iter", "Global step iteration.").AsDispensable();
    AddOutput("Out", "(Tensor) Output of quantized low level tensor.");
    AddOutput("OutScale", " Current scale");
    AddOutput("OutScales", "(Tensor) scale buffer.").AsDispensable();
    AddAttr<int>("window_size", "(int, default 10000) window range size.")
        .SetDefault(10000);
    AddAttr<int>("bit_length", "(int, default 8), quantization bit number.")
        .SetDefault(8)
710 711 712
        .AddCustomChecker([](const int &bit_length) {
          PADDLE_ENFORCE_EQ(bit_length >= 1 && bit_length <= 16,
                            true,
713 714 715 716
                            platform::errors::InvalidArgument(
                                "'bit_length' should be between 1 and 16, but "
                                "the received is %d",
                                bit_length));
717
        });
718 719
    AddAttr<int>(
        "round_type",
720
        "(int, default 1) The round type of fp32 to int."
721 722 723
        "0: rounding to nearest ties to even. Eg: round(1.5)=2, round(2.5)=2"
        "1: rounding to nearest ties away from zero. Eg: round(1.5)=2, "
        "round(2.5)=3")
724 725 726 727 728 729 730 731 732 733 734 735
        .SetDefault(1)
        .AddCustomChecker([](const int &round_type) {
          PADDLE_ENFORCE_EQ(
              round_type == 0 || round_type == 1,
              true,
              platform::errors::InvalidArgument(
                  "'round_type' should be 0 or 1, 0 rounding to "
                  "nearest ties to even and 1 is rounding to nearest "
                  "ties away from zero.but the received is %d",
                  round_type));
        })
        .AsExtra();
736 737 738 739
    AddAttr<bool>("is_test",
                  "(bool, default false) Set to true for inference only, false "
                  "for training. Some layers may run faster when this is true.")
        .SetDefault(false);
740 741
    AddComment(R"DOC(
FakeQuantize operator is used in static quantization.
视言's avatar
视言 已提交
742

743
$$scale = max(max(abs(x)), history_abs_max)$$
744 745
$$range = 2^{bit_length - 1} - 1$$
$$Out = round(X/scale * range)$$
视言's avatar
视言 已提交
746 747 748 749 750

)DOC");
  }
};

751 752
class FakeQuantOrWithDequantMovingAverageAbsMaxOp
    : public framework::OperatorWithKernel {
753
 public:
754
  FakeQuantOrWithDequantMovingAverageAbsMaxOp(
755 756 757 758
      const std::string &type,
      const framework::VariableNameMap &inputs,
      const framework::VariableNameMap &outputs,
      const framework::AttributeMap &attrs)
759 760
      : OperatorWithKernel(type, inputs, outputs, attrs) {}

761 762 763 764
  void InferShape(framework::InferShapeContext *ctx) const override {
    OP_INOUT_CHECK(ctx->HasInput("X"),
                   "Input",
                   "X",
765
                   "FakeQuantOrWithDequantMovingAverageAbsMax");
766 767 768
    OP_INOUT_CHECK(ctx->HasOutput("Out"),
                   "Output",
                   "Out",
769
                   "FakeQuantOrWithDequantMovingAverageAbsMax");
770 771 772
    OP_INOUT_CHECK(ctx->HasOutput("OutScale"),
                   "Output",
                   "OutScale",
773
                   "FakeQuantOrWithDequantMovingAverageAbsMax");
774 775 776 777 778 779 780 781 782 783 784 785 786
    if (ctx->HasOutput("OutState")) {
      ctx->SetOutputDim("OutState", {1});
    }
    if (ctx->HasOutput("OutAccum")) {
      ctx->SetOutputDim("OutAccum", {1});
    }
    ctx->SetOutputDim("Out", ctx->GetInputDim("X"));
    ctx->SetOutputDim("OutScale", {1});
    ctx->ShareLoD("X", /*->*/ "Out");
  }

 protected:
  framework::OpKernelType GetExpectedKernelType(
787
      const framework::ExecutionContext &ctx) const override {
788 789 790
    return framework::OpKernelType(
        OperatorWithKernel::IndicateVarDataType(ctx, "X"),
        ctx.device_context());
791 792 793
  }
};

794
class FakeQuantOrWithDequantMovingAverageAbsMaxOpMaker
795 796 797 798 799 800 801 802 803 804 805 806 807 808 809
    : public framework::OpProtoAndCheckerMaker {
 public:
  void Make() override {
    AddInput("X", "(Tensor) Input is float data type.");
    AddInput("InScale", "Last scale.");
    AddInput("InAccum", "Last accum.").AsDispensable();
    AddInput("InState", "Last state.").AsDispensable();
    AddOutput("Out", "(Tensor) Output of quantized low level tensor.");
    AddOutput("OutScale", " Current scale");
    AddOutput("OutState", "(Tensor) state buffer.").AsDispensable();
    AddOutput("OutAccum", "(Tensor) accum buffer.").AsDispensable();
    AddAttr<float>("moving_rate", "(float, default 0.9) moving rate.")
        .SetDefault(0.9);
    AddAttr<int>("bit_length", "(int, default 8), quantization bit number.")
        .SetDefault(8)
810 811 812
        .AddCustomChecker([](const int &bit_length) {
          PADDLE_ENFORCE_EQ(bit_length >= 1 && bit_length <= 16,
                            true,
813 814 815 816
                            platform::errors::InvalidArgument(
                                "'bit_length' should be between 1 and 16, but "
                                "the received is %d",
                                bit_length));
817
        });
818 819
    AddAttr<int>(
        "round_type",
820
        "(int, default 1) The round type of fp32 to int."
821 822 823
        "0: rounding to nearest ties to even. Eg: round(1.5)=2, round(2.5)=2"
        "1: rounding to nearest ties away from zero. Eg: round(1.5)=2, "
        "round(2.5)=3")
824 825 826 827 828 829 830 831 832 833 834 835
        .SetDefault(1)
        .AddCustomChecker([](const int &round_type) {
          PADDLE_ENFORCE_EQ(
              round_type == 0 || round_type == 1,
              true,
              platform::errors::InvalidArgument(
                  "'round_type' should be 0 or 1, 0 rounding to "
                  "nearest ties to even and 1 is rounding to nearest "
                  "ties away from zero.but the received is %d",
                  round_type));
        })
        .AsExtra();
836 837 838 839 840
    AddAttr<bool>("is_test",
                  "(bool, default false) Set to true for inference only, false "
                  "for training. Some layers may run faster when this is true.")
        .SetDefault(false);
    AddComment(R"DOC(
841
This is a Base Op which supports FakeQuantMovingAverageAbsMaxOp and FakeQuantDequantMovingAverageAbsMaxOp.
842
FakeQuantMovingAverageAbsMaxOp operator is used in the static quantization.
843

Z
Zhen Wang 已提交
844 845
$$scale = (moving\_rate*accum+max(abs(x)))/(moving\_rate*state+1)$$
$$range = 2^{bit\_length - 1} - 1$$
846 847
$$Out = round(X/scale * range)$$

848
FakeQuantDequantMovingAverageAbsMaxOp operator does the moving_average_abs_max quant and then dequant.
849 850 851 852 853

$$scale = (moving\_rate*accum+max(abs(x)))/(moving\_rate*state+1)$$
$$range = 2^{bit\_length - 1} - 1$$
$$Out = round(X/scale * range) * scale / range$$

854 855 856 857
)DOC");
  }
};

Z
Zhen Wang 已提交
858 859 860 861
class MovingAverageAbsMaxScaleOp : public framework::OperatorWithKernel {
 public:
  using framework::OperatorWithKernel::OperatorWithKernel;

862 863 864 865 866 867
  void InferShape(framework::InferShapeContext *ctx) const override {
    OP_INOUT_CHECK(
        ctx->HasInput("X"), "Input", "X", "MovingAverageAbsMaxScale");
    OP_INOUT_CHECK(ctx->HasOutput("OutScale"),
                   "Output",
                   "OutScale",
868
                   "MovingAverageAbsMaxScale");
869

Z
Zhen Wang 已提交
870 871 872 873 874 875
    if (ctx->HasOutput("OutState")) {
      ctx->SetOutputDim("OutState", {1});
    }
    if (ctx->HasOutput("OutAccum")) {
      ctx->SetOutputDim("OutAccum", {1});
    }
876 877 878 879 880
    if (ctx->HasOutput("Out")) {
      ctx->SetOutputDim("Out", ctx->GetInputDim("X"));
      ctx->SetOutputDim("OutScale", {1});
      ctx->ShareLoD("X", /*->*/ "Out");
    }
Z
Zhen Wang 已提交
881 882 883 884
  }

 protected:
  framework::OpKernelType GetExpectedKernelType(
885
      const framework::ExecutionContext &ctx) const override {
886 887
    return framework::OpKernelType(
        OperatorWithKernel::IndicateVarDataType(ctx, "X"), ctx.GetPlace());
Z
Zhen Wang 已提交
888 889 890 891 892 893 894 895 896 897
  }
};

class MovingAverageAbsMaxScaleOpMaker
    : public framework::OpProtoAndCheckerMaker {
 public:
  void Make() override {
    AddInput("X", "(Tensor) Input is float data type.");
    AddInput("InAccum", "Last accum.").AsDispensable();
    AddInput("InState", "Last state.").AsDispensable();
898 899 900
    AddOutput("Out",
              "(Tensor) Output tensor is just equivalent to the input tensor.")
        .AsDispensable();
Z
Zhen Wang 已提交
901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920
    AddOutput("OutScale", " Current scale");
    AddOutput("OutState", "(Tensor) state buffer.").AsDispensable();
    AddOutput("OutAccum", "(Tensor) accum buffer.").AsDispensable();
    AddAttr<float>("moving_rate", "(float, default 0.9) moving rate.")
        .SetDefault(0.9);
    AddAttr<bool>("is_test",
                  "(bool, default false) Set true for inference only and false "
                  "for training. Some layers may run faster when this is true.")
        .SetDefault(false);
    AddComment(R"DOC(
MovingAverageAbsMaxScale operator is only used for calculating the quantization scale.
And it will not quantize the input tensor.

$$scale = (moving\_rate*accum+max(abs(x)))/(moving\_rate*state+1)$$
$$Out = X$$

)DOC");
  }
};

921
class StrightThroughEstimatorGradOp : public framework::OperatorWithKernel {
922 923 924
 public:
  using framework::OperatorWithKernel::OperatorWithKernel;

925
  void InferShape(framework::InferShapeContext *ctx) const override {
926
    auto out_grad_name = framework::GradVarName("Out");
927
    auto x_grad_name = framework::GradVarName("X");
928 929 930
    OP_INOUT_CHECK(ctx->HasInput(out_grad_name),
                   "Input",
                   out_grad_name,
931
                   "StrightThroughEstimatorGradOp");
932 933 934
    OP_INOUT_CHECK(ctx->HasOutput(x_grad_name),
                   "Output",
                   x_grad_name,
935
                   "StrightThroughEstimatorGradOp");
936 937 938 939 940

    ctx->SetOutputDim(x_grad_name, ctx->GetInputDim(out_grad_name));
  }

  framework::OpKernelType GetExpectedKernelType(
941
      const framework::ExecutionContext &ctx) const override {
942 943 944 945 946 947 948
    auto input_data_type = OperatorWithKernel::IndicateVarDataType(
        ctx, framework::GradVarName("Out"));
    return framework::OpKernelType(input_data_type, ctx.GetPlace());
  }
};

template <typename T>
949
class StrightThroughEstimatorMaker : public framework::SingleGradOpMaker<T> {
950 951 952 953 954
 public:
  using framework::SingleGradOpMaker<T>::SingleGradOpMaker;

 protected:
  void Apply(GradOpPtr<T> grad_op) const override {
955
    grad_op->SetType("stright_throuth_estimator_grad");
956 957 958 959 960 961
    grad_op->SetInput(framework::GradVarName("Out"), this->OutputGrad("Out"));
    grad_op->SetOutput(framework::GradVarName("X"), this->InputGrad("X"));
    grad_op->SetAttrMap(this->Attrs());
  }
};

视言's avatar
视言 已提交
962 963 964 965
}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;
L
Leo Chen 已提交
966
using CPU = phi::CPUContext;
967

H
hong 已提交
968
REGISTER_OPERATOR(
969 970
    fake_quantize_abs_max,
    ops::FakeQuantOrWithDequantAbsMaxOp,
971
    ops::FakeQuantOrWithDequantAbsMaxOpMaker,
H
hong 已提交
972 973
    paddle::framework::EmptyGradOpMaker<paddle::framework::OpDesc>,
    paddle::framework::EmptyGradOpMaker<paddle::imperative::OpBase>);
974 975
REGISTER_OP_CPU_KERNEL(fake_quantize_abs_max,
                       ops::FakeQuantizeAbsMaxKernel<CPU, float>);
视言's avatar
视言 已提交
976

977
REGISTER_OPERATOR(
978 979
    fake_quantize_dequantize_abs_max,
    ops::FakeQuantOrWithDequantAbsMaxOp,
980 981 982
    ops::FakeQuantOrWithDequantAbsMaxOpMaker,
    ops::StrightThroughEstimatorMaker<paddle::framework::OpDesc>,
    ops::StrightThroughEstimatorMaker<paddle::imperative::OpBase>);
983 984 985
REGISTER_OP_CPU_KERNEL(fake_quantize_dequantize_abs_max,
                       ops::FakeQuantizeDequantizeAbsMaxKernel<CPU, float>);

H
hong 已提交
986
REGISTER_OPERATOR(
987 988
    fake_quantize_range_abs_max,
    ops::FakeQuantizeRangeAbsMaxOp,
H
hong 已提交
989 990 991
    ops::FakeQuantizeRangeAbsMaxOpMaker,
    paddle::framework::EmptyGradOpMaker<paddle::framework::OpDesc>,
    paddle::framework::EmptyGradOpMaker<paddle::imperative::OpBase>);
992 993
REGISTER_OP_CPU_KERNEL(fake_quantize_range_abs_max,
                       ops::FakeQuantizeRangeAbsMaxKernel<CPU, float>);
Z
Zhen Wang 已提交
994

H
hong 已提交
995 996 997 998 999 1000
REGISTER_OPERATOR(
    fake_quantize_moving_average_abs_max,
    ops::FakeQuantOrWithDequantMovingAverageAbsMaxOp,
    ops::FakeQuantOrWithDequantMovingAverageAbsMaxOpMaker,
    paddle::framework::EmptyGradOpMaker<paddle::framework::OpDesc>,
    paddle::framework::EmptyGradOpMaker<paddle::imperative::OpBase>);
1001 1002
REGISTER_OP_CPU_KERNEL(fake_quantize_moving_average_abs_max,
                       ops::FakeQuantizeMovingAverageAbsMaxKernel<CPU, float>);
1003

1004 1005 1006 1007 1008 1009
REGISTER_OPERATOR(
    fake_quantize_dequantize_moving_average_abs_max,
    ops::FakeQuantOrWithDequantMovingAverageAbsMaxOp,
    ops::FakeQuantOrWithDequantMovingAverageAbsMaxOpMaker,
    ops::StrightThroughEstimatorMaker<paddle::framework::OpDesc>,
    ops::StrightThroughEstimatorMaker<paddle::imperative::OpBase>);
1010 1011 1012 1013
REGISTER_OP_CPU_KERNEL(
    fake_quantize_dequantize_moving_average_abs_max,
    ops::FakeQuantizeDequantizeMovingAverageAbsMaxKernel<CPU, float>);

H
hong 已提交
1014
REGISTER_OPERATOR(
1015 1016
    fake_channel_wise_quantize_abs_max,
    ops::FakeChannelWiseQuantizeAbsMaxOp,
H
hong 已提交
1017 1018 1019
    ops::FakeChannelWiseQuantizeAbsMaxOpMaker,
    paddle::framework::EmptyGradOpMaker<paddle::framework::OpDesc>,
    paddle::framework::EmptyGradOpMaker<paddle::imperative::OpBase>);
Z
Zhen Wang 已提交
1020 1021
REGISTER_OP_CPU_KERNEL(fake_channel_wise_quantize_abs_max,
                       ops::FakeChannelWiseQuantizeAbsMaxKernel<CPU, float>);
Z
Zhen Wang 已提交
1022

H
hong 已提交
1023
REGISTER_OPERATOR(
1024 1025
    moving_average_abs_max_scale,
    ops::MovingAverageAbsMaxScaleOp,
H
hong 已提交
1026
    ops::MovingAverageAbsMaxScaleOpMaker,
1027 1028
    ops::StrightThroughEstimatorMaker<paddle::framework::OpDesc>,
    ops::StrightThroughEstimatorMaker<paddle::imperative::OpBase>);
Z
Zhen Wang 已提交
1029 1030
REGISTER_OP_CPU_KERNEL(moving_average_abs_max_scale,
                       ops::MovingAverageAbsMaxScaleKernel<CPU, float>);
1031

1032 1033 1034 1035
REGISTER_OPERATOR(stright_throuth_estimator_grad,
                  ops::StrightThroughEstimatorGradOp);
REGISTER_OP_CPU_KERNEL(stright_throuth_estimator_grad,
                       ops::StrightThroughEstimatorGradKernel<CPU, float>);
H
huangxu96 已提交
1036

1037 1038 1039 1040 1041 1042
REGISTER_OPERATOR(
    fake_channel_wise_quantize_dequantize_abs_max,
    ops::FakeChannelWiseQuantizeDequantizeAbsMaxOp,
    ops::FakeChannelWiseQuantizeDequantizeAbsMaxOpMaker,
    ops::StrightThroughEstimatorMaker<paddle::framework::OpDesc>,
    ops::StrightThroughEstimatorMaker<paddle::imperative::OpBase>);
H
huangxu96 已提交
1043 1044 1045
REGISTER_OP_CPU_KERNEL(
    fake_channel_wise_quantize_dequantize_abs_max,
    ops::FakeChannelWiseQuantizeDequantizeAbsMaxKernel<CPU, float>);
1046 1047 1048 1049 1050 1051 1052

REGISTER_OP_VERSION(fake_channel_wise_quantize_abs_max)
    .AddCheckpoint(
        R"ROC(add new attributes [quant_axis] for applying per-channel "
        "quantization to conv2d_tranpose and mul ops.)ROC",
        paddle::framework::compatible::OpVersionDesc().NewAttr(
            "quant_axis", "The axis for quantization.", 0));
1053 1054 1055 1056 1057 1058 1059
REGISTER_OP_VERSION(moving_average_abs_max_scale)
    .AddCheckpoint(
        R"ROC(Incompatible upgrade of output [Out])ROC",
        paddle::framework::compatible::OpVersionDesc().DeleteOutput(
            "Out",
            "Delete output in order to make the inference model not "
            "save moving_average_abs_max_scale operator. This will "
1060
            "make the quantitative model be correctly applied in inference."))
1061 1062 1063 1064
    .AddCheckpoint(R"ROC(Incompatible upgrade of output [Out])ROC",
                   paddle::framework::compatible::OpVersionDesc().NewOutput(
                       "Out",
                       "In order to support dygraph qat, add output again."));