test_quantize_op.cpp 5.9 KB
Newer Older
H
hjchen2 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14
/* Copyright (c) 2018 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. */

H
hjchen2 已提交
15
#include <iostream>
H
hjchen2 已提交
16 17 18 19 20
#include "../test_helper.h"
#include "../test_include.h"
#include "operators/quantize_op.h"

namespace paddle_mobile {
H
hjchen2 已提交
21 22 23 24 25 26 27
namespace round {
enum RoundType {
  RoundToEven = 0,
  RoundAwayZero = 1,
  RoundTowardsZero = 2,
};
}
H
hjchen2 已提交
28

H
hjchen2 已提交
29
template <round::RoundType T>
30 31 32
struct Round {
  int8_t operator()(float x);
};
H
hjchen2 已提交
33 34

template <>
35 36 37
struct Round<round::RoundAwayZero> {
  int8_t operator()(float x) { return std::round(x); }
};
H
hjchen2 已提交
38 39

template <>
40 41 42
struct Round<round::RoundTowardsZero> {
  int8_t operator()(float x) { return int8_t(x); }
};
H
hjchen2 已提交
43 44

template <>
45 46 47 48
struct Round<round::RoundToEven> {
  int8_t operator()(float x) {
    int8_t ret = 0;
    float v = std::round(x);
H
hjchen2 已提交
49
    int32_t q = (int32_t)v;
50
    if (abs(abs(q - x) - 0.5) > 0) {
H
hjchen2 已提交
51 52
      ret = q;
    } else {
H
hjchen2 已提交
53
      if (abs(q) % 2 == 0) {
54
        ret = q;
H
hjchen2 已提交
55
      } else {
56 57
        ret = q + ((q > 0) ? -1 : 1);
      }
H
hjchen2 已提交
58
    }
59
    return ret;
H
hjchen2 已提交
60
  }
61
};
H
hjchen2 已提交
62

H
hjchen2 已提交
63 64 65 66 67 68 69 70 71 72 73
template <round::RoundType T>
static void quantize(const Tensor *input, const float scale, const int pad,
                     const int8_t pad_val, Tensor *output) {
  int batch_size = input->dims()[0];
  int channels = input->dims()[1];
  int input_h = input->dims()[2];
  int input_w = input->dims()[3];
  int output_h = output->dims()[2];
  int output_w = output->dims()[3];
  size_t input_spatial = input_h * input_w;
  size_t output_spatial = output_h * output_w;
H
hjchen2 已提交
74 75
  const float *x = input->data<const float>();
  int8_t *y = output->mutable_data<int8_t>();
H
hjchen2 已提交
76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91

  for (int nc = 0; nc < batch_size * channels; ++nc) {
    const float *xh = x + nc * input_spatial;
    int8_t *yh = y + nc * output_spatial;
    // pad top
    for (int h = 0; h < pad; ++h, yh += output_w) {
      for (int w = 0; w < output_w; ++w) {
        yh[w] = pad_val;
      }
    }
    for (int h = 0; h < input_h; ++h, yh += output_w, xh += input_w) {
      // pad left
      for (int w = 0; w < pad; ++w) {
        yh[w] = pad_val;
      }
      for (int w = 0; w < input_w; ++w) {
92
        yh[w + pad] = Round<T>()(xh[w] * scale);
H
hjchen2 已提交
93 94 95 96 97 98 99 100 101 102
      }
      // pad right
      for (int w = 0; w < pad; ++w) {
        yh[pad + input_w + w] = pad_val;
      }
    }
    // pad bottom
    for (int h = 0; h < pad; ++h, yh += output_w) {
      for (int w = 0; w < output_w; ++w) {
        yh[w] = pad_val;
H
hjchen2 已提交
103 104 105 106 107
      }
    }
  }
}

H
hjchen2 已提交
108 109
static float find_abs_max(const Tensor *input) {
  float max_abs = 0.f;
110 111 112
  const float *x = input->data<const float>();
  size_t size = input->numel();
  for (size_t i = 0; i < size; ++i) {
H
hjchen2 已提交
113 114 115 116
    float value = std::abs(x[i]);
    if (value > max_abs) {
      max_abs = value;
    }
117
  }
H
hjchen2 已提交
118
  return max_abs;
119 120
}

H
hjchen2 已提交
121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139
int TestQuqntizeOp(int argc, char *argv[]) {
  if (argc < 5) {
    std::cout
        << "Usage: ./test-quantize-op batch_size channel height width [pad]"
        << std::endl;
    return 1;
  }
  int pad = 0;
  int batch_size = atoi(argv[1]);
  int channel = atoi(argv[2]);
  int height = atoi(argv[3]);
  int width = atoi(argv[4]);
  if (argc == 6) {
    pad = atoi(argv[5]);
  }
  std::cout << "batch_size: " << batch_size << ", channel: " << channel
            << ", height: " << height << ", width: " << width << std::endl;
  framework::DDim dim =
      framework::make_ddim({batch_size, channel, height, width});
H
hjchen2 已提交
140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155

  VariableNameMap inputs;
  VariableNameMap outputs;
  auto scope = std::make_shared<framework::Scope>();
  inputs["X"] = std::vector<std::string>({"input"});
  outputs["Out"] = std::vector<std::string>({"output"});
  outputs["OutScale"] = std::vector<std::string>({"output_scale"});

  auto input_var = scope.get()->Var("input");
  auto input = input_var->template GetMutable<framework::LoDTensor>();
  SetupTensor<float>(input, dim, -100.f, 100.f);

  auto output_var = scope.get()->Var("output");
  auto output_scale_var = scope.get()->Var("output_scale");

  framework::AttributeMap attrs;
H
hjchen2 已提交
156
  attrs["paddings"].Set<vector<int>>(std::vector<int>({pad, pad}));
H
hjchen2 已提交
157 158 159 160 161 162 163 164 165 166
  auto *op = new operators::QuantizeOp<CPU, float>("quantize", inputs, outputs,
                                                   attrs, scope);
  op->InferShape();
  op->Run();

  auto output = output_var->template Get<framework::LoDTensor>();
  const int8_t *output_data = output->data<int8_t>();
  auto output_scale = output_scale_var->template Get<framework::LoDTensor>();
  const float *output_scale_data = output_scale->data<float>();

167
  float output_scale_cmp = find_abs_max(input);
H
hjchen2 已提交
168 169 170 171 172
  PADDLE_MOBILE_ENFORCE(output_scale_cmp == output_scale_data[0],
                        "output_scale = %.6f, output_scale_cmp = %.6f",
                        output_scale_cmp, output_scale_data[0]);

  framework::Tensor output_cmp;
H
hjchen2 已提交
173
  output_cmp.Resize(output->dims());
174
  float scale = 127 / output_scale_cmp;
H
hjchen2 已提交
175 176 177
  // quantize<round::RoundToEven>(input, scale, pad, 0, &output_cmp);
  // quantize<round::RoundAwayZero>(input, scale, pad, 0, &output_cmp);
  quantize<round::RoundTowardsZero>(input, scale, pad, 0, &output_cmp);
H
hjchen2 已提交
178 179 180 181 182 183 184 185 186 187 188 189 190
  int8_t *output_cmp_data = output_cmp.data<int8_t>();
  for (int i = 0; i < output->numel(); ++i) {
    PADDLE_MOBILE_ENFORCE(output_data[i] == output_cmp_data[i],
                          "output[%d] = %d, output_cmp[%d] = %d", i,
                          static_cast<int>(output_data[i]), i,
                          static_cast<int>(output_cmp_data[i]));
  }
  delete op;
  return 0;
}

}  // namespace paddle_mobile

H
hjchen2 已提交
191 192 193
int main(int argc, char *argv[]) {
  return paddle_mobile::TestQuqntizeOp(argc, argv);
}