quantization.cpp 15.8 KB
Newer Older
Shucai Xiao's avatar
Shucai Xiao committed
1
#include <migraphx/quantization.hpp>
2
3
4
#include <migraphx/program.hpp>
#include <migraphx/instruction.hpp>
#include <migraphx/iterator_for.hpp>
5
#include <migraphx/op/convert.hpp>
Shucai Xiao's avatar
Shucai Xiao committed
6
#include <migraphx/op/dot.hpp>
Shucai Xiao's avatar
Shucai Xiao committed
7
#include <migraphx/op/mul.hpp>
8
#include <migraphx/op/add.hpp>
Shucai Xiao's avatar
Shucai Xiao committed
9
10
11
12
#include <migraphx/op/quant_dot.hpp>
#include <migraphx/op/convolution.hpp>
#include <migraphx/op/quant_convolution.hpp>
#include <migraphx/op/multibroadcast.hpp>
13
#include <migraphx/stringutils.hpp>
14
#include <migraphx/ranges.hpp>
15
16
17
18
19
#include <utility>

namespace migraphx {
inline namespace MIGRAPHX_INLINE_NS {

Shucai Xiao's avatar
Shucai Xiao committed
20
instruction_ref insert_quant_ins(program& prog,
Shucai Xiao's avatar
Shucai Xiao committed
21
22
23
24
25
                                 instruction_ref& ins,
                                 shape::type_t type,
                                 std::unordered_map<instruction_ref, instruction_ref>& map_ins,
                                 float scale = 1.0f,
                                 float shift = 0.0f)
26
{
Shucai Xiao's avatar
Shucai Xiao committed
27
    if(map_ins.count(ins) > 0)
28
    {
Shucai Xiao's avatar
Shucai Xiao committed
29
        return map_ins[ins];
30
31
    }

Shucai Xiao's avatar
Shucai Xiao committed
32
    assert(ins->get_shape().type() == shape::float_type ||
Shucai Xiao's avatar
Shucai Xiao committed
33
34
35
           ins->get_shape().type() == shape::double_type ||
           ins->get_shape().type() == shape::int32_type);
    instruction_ref quant_ins{};
Shucai Xiao's avatar
Shucai Xiao committed
36
    quant_ins    = prog.insert_instruction(std::next(ins), op::convert{type, scale, shift}, ins);
Shucai Xiao's avatar
Shucai Xiao committed
37
    map_ins[ins] = quant_ins;
38

Shucai Xiao's avatar
Shucai Xiao committed
39
    return quant_ins;
40
41
}

Shucai Xiao's avatar
Shucai Xiao committed
42
43
44
// This function is to convert any instructions specified in the input
// from double or float to float16 by inserting a convert operator.
// For the conversion, there could be cases of overflowing, but it
Shucai Xiao's avatar
Shucai Xiao committed
45
// is very rare in the area of deeping learning, so we just do a
Shucai Xiao's avatar
Shucai Xiao committed
46
// truncate of the input to get the fp16.
47
void quantize(program& prog, const std::vector<std::string>& ins_names)
48
{
49
    std::unordered_map<instruction_ref, instruction_ref> map_fp16;
Shucai Xiao's avatar
Shucai Xiao committed
50
    for(auto ins : iterator_for(prog))
51
    {
52
        // all indicates every instruction is converted
Shucai Xiao's avatar
Shucai Xiao committed
53
        if((not contains(ins_names, "all")) and (not contains(ins_names, ins->name())))
54
55
56
        {
            continue;
        }
57

58
        shape::type_t orig_type = ins->get_shape().type();
Shucai Xiao's avatar
Shucai Xiao committed
59
        // process all inputs, if input is a fp32 or fp64, convert it
60
        // to a fp16 by adding a convert operator.
61
        auto inputs = ins->inputs();
62
        std::vector<instruction_ref> converted_inputs;
Shucai Xiao's avatar
Shucai Xiao committed
63
        for(auto input : inputs)
64
65
        {
            auto s = input->get_shape();
Shucai Xiao's avatar
Shucai Xiao committed
66
            if(s.type() == shape::float_type || s.type() == shape::double_type)
67
            {
68
                // if the input is a convert operator, uses its input
69
70
                // as its current input
                instruction_ref input_fp16{};
71
                if(input->name() == "convert")
72
73
74
75
76
                {
                    input_fp16 = input->inputs().front();
                }
                else
                {
Shucai Xiao's avatar
Shucai Xiao committed
77
                    input_fp16 = insert_quant_ins(prog, input, shape::half_type, map_fp16);
78
                }
79
                converted_inputs.push_back(input_fp16);
80
            }
81
82
83
84
85
86
            else
            {
                converted_inputs.push_back(input);
            }
        }

87
        // no change for the input, go to the next instruction
Shucai Xiao's avatar
Shucai Xiao committed
88
        if(inputs == converted_inputs)
89
        {
90
            continue;
Shucai Xiao's avatar
Shucai Xiao committed
91
92
93
94
95
96
        }

        auto op        = ins->get_operator();
        auto ins_shape = compute_shape(op, converted_inputs);
        if(ins_shape.type() != orig_type)
        {
Shucai Xiao's avatar
Shucai Xiao committed
97
98
99
100
101
            // check the dead code case to avoid assert
            bool output_empty = ins->outputs().empty();
            auto ins_orig_type =
                prog.insert_instruction(std::next(ins), op::convert{orig_type}, ins);
            if(!output_empty)
102
            {
Shucai Xiao's avatar
Shucai Xiao committed
103
                prog.replace_instruction(ins, ins_orig_type);
Shucai Xiao's avatar
Shucai Xiao committed
104
            }
Shucai Xiao's avatar
Shucai Xiao committed
105
106
107
108
109
110
111
112
113
        }

        prog.replace_instruction(ins, op, converted_inputs);
    }
}

void quantize(program& prog) { quantize(prog, {"all"}); }

// int8 quantization is different from fp16 since int8 can only handle value
Shucai Xiao's avatar
Shucai Xiao committed
114
// -128 ~ 127. To convert the float or double to int8, we need a scale and
Shucai Xiao's avatar
Shucai Xiao committed
115
// a shift, then the convert can be done as v_int8 = fp * scale + shift.
Shucai Xiao's avatar
Shucai Xiao committed
116
// To simplify the changes, we consider shift as 0.0f for now.
Shucai Xiao's avatar
Shucai Xiao committed
117
118
119
120
void quantize_int8(program& prog, const std::vector<std::string>& ins_names)
{
    // For now, we only support the int8 quantization of gemm and convolution
    std::vector<std::string> op_names = {"dot", "convolution"};
Shucai Xiao's avatar
Shucai Xiao committed
121
    if(!std::all_of(ins_names.begin(), ins_names.end(), [&](auto name) {
Shucai Xiao's avatar
Shucai Xiao committed
122
           return (std::find(op_names.begin(), op_names.end(), name) != op_names.end());
Shucai Xiao's avatar
Shucai Xiao committed
123
       }))
Shucai Xiao's avatar
Shucai Xiao committed
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
    {
        MIGRAPHX_THROW("QUANTIZE_INT8: only support DOT and CONVOLUTION operation");
    }

    // tmp value used just testing
    std::vector<std::pair<float, float>> int8_param{{1.0f, 0.0f}, {1.0f, 0.0f}, {1.0f, 0.0f}};

    std::unordered_map<instruction_ref, instruction_ref> map_quant_ins;
    for(auto ins : iterator_for(prog))
    {
        if(not contains(ins_names, ins->name()))
        {
            continue;
        }

        shape::type_t orig_type = ins->get_shape().type();

        // for the dot operator, there could be 2 or 3 input arguments
        // if the 3rd argument is available, convert it to an int32.
        std::vector<instruction_ref> converted_inputs;

        // process all inputs, if input is a fp32 or fp64, convert it
Shucai Xiao's avatar
Shucai Xiao committed
146
        // to a int8 type by adding a convert operator and replace
Shucai Xiao's avatar
Shucai Xiao committed
147
        // the operator with the corresponding int8 version
Shucai Xiao's avatar
Shucai Xiao committed
148
        auto inputs             = ins->inputs();
Shucai Xiao's avatar
Shucai Xiao committed
149
150
151
        std::size_t param_index = 0;
        for(auto input : inputs)
        {
Shucai Xiao's avatar
Shucai Xiao committed
152
153
            // In general, the target_type is int8, but for the dot
            // operation, if it has 3 inputs, then the last one should
Shucai Xiao's avatar
Shucai Xiao committed
154
155
            // be converted to int32_type
            shape::type_t quant_type = shape::int8_type;
156
            auto param = int8_param[param_index++];
Shucai Xiao's avatar
Shucai Xiao committed
157
            if(ins->name() == "dot" and inputs.size() == 3 and input == inputs.back())
Shucai Xiao's avatar
Shucai Xiao committed
158
            {
Shucai Xiao's avatar
Shucai Xiao committed
159
160
                quant_type = shape::int32_type;
            }
Shucai Xiao's avatar
Shucai Xiao committed
161
162

            auto s     = input->get_shape();
163
164
            if((s.type() == shape::float_type || s.type() == shape::double_type ||
               s.type() == shape::int32_type) && s.type() != quant_type)
Shucai Xiao's avatar
Shucai Xiao committed
165
166
167
168
169
170
171
            {
                // if the input is a convert operator, uses its input
                // as its current input
                instruction_ref quant_input{};
                if(input->name() == "convert")
                {
                    auto tmp_ins = input->inputs().front();
Shucai Xiao's avatar
Shucai Xiao committed
172
                    if(tmp_ins->get_shape().type() == quant_type)
Shucai Xiao's avatar
Shucai Xiao committed
173
174
175
176
177
                    {
                        quant_input = input->inputs().front();
                    }
                    else
                    {
Shucai Xiao's avatar
Shucai Xiao committed
178
179
                        quant_input = insert_quant_ins(
                            prog, input, quant_type, map_quant_ins, param.first, param.second);
Shucai Xiao's avatar
Shucai Xiao committed
180
181
182
                    }
                }
                else
183
                {
Shucai Xiao's avatar
Shucai Xiao committed
184
185
                    quant_input = insert_quant_ins(
                        prog, input, quant_type, map_quant_ins, param.first, param.second);
186
                }
Shucai Xiao's avatar
Shucai Xiao committed
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
                converted_inputs.push_back(quant_input);
            }
            else
            {
                converted_inputs.push_back(input);
            }
        }

        // no change for the input, go to the next instruction
        if(inputs == converted_inputs)
        {
            continue;
        }

        // When converting from other types to int8_type, there are parameters
        // used as scale and shift(.0f), which will generate results diffrent from
        // the original results. To adjust the output to be "correct(approximatly
Shucai Xiao's avatar
Shucai Xiao committed
204
        // equal)", we need additional calculation for the adjustment
Shucai Xiao's avatar
Shucai Xiao committed
205
        if(ins->name() == "dot")
Shucai Xiao's avatar
Shucai Xiao committed
206
        {
Shucai Xiao's avatar
Shucai Xiao committed
207
            auto dot_op         = any_cast<op::dot>(ins->get_operator());
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
            float new_alpha = dot_op.alpha / (int8_param[0].first * int8_param[1].first);
            float new_beta = dot_op.beta;
            // We need additional checking about the quant_alpha value. If 
            // abs(quant_alpha) > 50 (some tmp value set here), we can convert
            // it to an integer as the new_alpha in the quant_dot
            float threshold = 50.0f;
            if (fabs(new_alpha) >= threshold && fabs(new_beta) >= threshold)
            {
                int32_t quant_alpha = static_cast<int32_t>(new_alpha);
                int32_t quant_beta = static_cast<int32_t>(new_beta);
                shape quant_shape = compute_shape(op::quant_dot{1, 0}, converted_inputs);
                if (quant_shape.type() == orig_type)
                {
                    prog.replace_instruction(ins, op::quant_dot{quant_alpha, quant_beta}, converted_inputs);
                }
                else
                {
                    auto quant_dot = prog.insert_instruction(ins, op::quant_dot{quant_alpha, quant_beta}, converted_inputs);
                    prog.replace_instruction(ins, op::convert{orig_type}, quant_dot);
                }
            }
            // only alpha can be quantized, quantization of beta will cause 
            // big error, so we have to manually do the multiplication and 
            // addition
            else if (fabs(new_alpha) >= threshold)
            {
                int32_t quant_alpha = static_cast<int32_t>(new_alpha);
                int32_t quant_beta = 0;
                if (orig_type == shape::int32_type)
                {
                    if (inputs.size() == 2 or dot_op.beta == 0.0f)
                    {
                        prog.replace_instruction(ins, op::quant_dot{quant_alpha, quant_beta}, converted_inputs);
                    }
                    // if there are 3 inputs, we need to consider the third argument
                    else
                    {
                        auto q_dot = prog.insert_instruction(ins, op::quant_dot{quant_alpha, quant_beta}, converted_inputs);
                        std::vector<float> vec_beta(q_dot->get_shape().elements(), dot_op.beta);
                        auto l_beta = prog.add_literal(literal{orig_type, vec_beta});
                        auto beta_c = prog.insert_instruction(ins, op::mul{}, l_beta, inputs.back());
                        prog.replace_instruction(ins, op::add{}, q_dot, beta_c);
                    }
                }
                else
                {
                    if (inputs.size() == 2 or dot_op.beta == 0.0f)
                    {
                        auto q_dot = prog.insert_instruction(ins, op::quant_dot{quant_alpha, quant_beta}, converted_inputs);
                        prog.replace_instruction(ins, op::convert{orig_type}, q_dot);
                    }
                    // if there are 3 inputs, we need to consider the third argument
                    else
                    {
                        auto q_dot = prog.insert_instruction(ins, op::quant_dot{quant_alpha, quant_beta}, converted_inputs);
                        auto oq_dot = prog.insert_instruction(ins, op::convert{orig_type}, q_dot);
                        std::vector<float> vec_beta(q_dot->get_shape().elements(), dot_op.beta);
                        auto l_beta = prog.add_literal(literal{oq_dot->get_shape(), vec_beta});
                        auto beta_c = prog.insert_instruction(ins, op::mul{}, l_beta, inputs.back());
                        prog.replace_instruction(ins, op::add{}, q_dot, beta_c);
                    }
                }
            }
            else
            {
                auto q_dot = prog.insert_instruction(ins, op::quant_dot{1, 0}, converted_inputs);
                std::vector<float> vec_alpha(q_dot->get_shape().elements(), new_alpha);
                if (orig_type == shape::int32_type)
                {
                    auto l_alpha = prog.add_literal(literal(ins->get_shape(), vec_alpha));
                    if (converted_inputs.size() == 2 or dot_op.beta == 0.0f)
                    {
                        prog.replace_instruction(ins, op::mul{}, l_alpha, q_dot);
                    }
                    // case of 3 arguments
                    else
                    {
                        std::vector<float> vec_beta(ins->get_shape().elements(), new_beta);
                        auto l_beta = prog.add_literal(literal(ins->get_shape(), vec_beta));
                        auto alpha_ab = prog.insert_instruction(ins, op::mul{}, l_alpha, q_dot);
                        auto beta_c = prog.insert_instruction(ins, op::mul{}, l_beta, inputs.back());                  
                        prog.replace_instruction(ins, op::add{}, alpha_ab, beta_c);
                    }
                }
                else
                {
                    auto oq_dot = prog.insert_instruction(ins, op::convert{orig_type}, q_dot);
                    auto l_alpha = prog.add_literal(literal(ins->get_shape(), vec_alpha));
                    if (converted_inputs.size() == 2 or dot_op.beta == 0.0f)
                    {
                        prog.replace_instruction(ins, op::mul{}, l_alpha, oq_dot);
                    }
                    // case of 3 arguments
                    else
                    {
                        std::vector<float> vec_beta(ins->get_shape().elements(), new_beta);
                        auto l_beta = prog.add_literal(literal(ins->get_shape(), vec_beta));
                        auto alpha_ab = prog.insert_instruction(ins, op::mul{}, l_alpha, oq_dot);
                        auto beta_c = prog.insert_instruction(ins, op::mul{}, l_beta, inputs.back());                  
                        prog.replace_instruction(ins, op::add{}, alpha_ab, beta_c);
                    }
                }
            }
Shucai Xiao's avatar
Shucai Xiao committed
311
        }
Shucai Xiao's avatar
Shucai Xiao committed
312
        else if(ins->name() == "convolution")
Shucai Xiao's avatar
Shucai Xiao committed
313
        {
Shucai Xiao's avatar
Shucai Xiao committed
314
            // Current MIOpen convolution does not support alpha and beta,
Shucai Xiao's avatar
Shucai Xiao committed
315
            // so we need a separate multiply to adjust the output
Shucai Xiao's avatar
Shucai Xiao committed
316
317
318
319
320
321
            auto conv_op       = any_cast<op::convolution>(ins->get_operator());
            auto padding       = conv_op.padding;
            auto stride        = conv_op.stride;
            auto dilation      = conv_op.dilation;
            auto padding_mode  = conv_op.padding_mode;
            auto group         = conv_op.group;
Shucai Xiao's avatar
Shucai Xiao committed
322
            auto adjust_factor = 1.0 / (int8_param[0].first * int8_param[1].first);
Shucai Xiao's avatar
Shucai Xiao committed
323

324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
            shape quant_shape = compute_shape(op::quant_convolution{}, converted_inputs);
            std::vector<float> vec_factor(quant_shape.elements(), adjust_factor);
            auto fl     = prog.add_literal(literal{{orig_type, quant_shape.lens()}, vec_factor});
            if (quant_shape.type() == orig_type)
            {
                if (adjust_factor == 1.0f)
                {
                    prog.replace_instruction(ins, op::quant_convolution{padding, stride, dilation, padding_mode, group}, converted_inputs);
                }
                else
                {
                    auto quant_conv = prog.replace_instruction(ins, op::quant_convolution{padding, stride, dilation, padding_mode, group}, converted_inputs);
                    prog.replace_instruction(ins, op::mul{}, quant_conv, fl);
                }
            }
            else
            {
                auto quant_conv = prog.insert_instruction(ins, op::quant_convolution{padding, stride, dilation, padding_mode, group}, converted_inputs);
                if (adjust_factor == 1.0f)
                {
                    prog.replace_instruction(ins, op::convert{orig_type}, quant_conv);
                }
                else
                {
                    auto oq_conv = prog.insert_instruction(ins, op::convert{orig_type}, quant_conv);
                    prog.replace_instruction(ins, op::mul{}, oq_conv, fl);
                }
            }
Shucai Xiao's avatar
Shucai Xiao committed
352
353
354
355
356
        }
        else
        {
            MIGRAPHX_THROW("INT8_QUANTIZE: does not support operator" + ins->name());
        }
357
358
359
360
361
    }
}

} // namespace MIGRAPHX_INLINE_NS
} // namespace migraphx