"src/targets/cpu/migemm.cpp" did not exist on "02f359b2300329b2160f6bd2be6d003e61e0aff3"
simplify_algebra.cpp 12.3 KB
Newer Older
Paul's avatar
Paul committed
1
#include <migraphx/simplify_algebra.hpp>
Paul's avatar
Paul committed
2
#include <migraphx/dead_code_elimination.hpp>
Paul's avatar
Paul committed
3
#include <migraphx/program.hpp>
4
#include <migraphx/op/add.hpp>
Paul's avatar
Paul committed
5
#include <migraphx/op/mul.hpp>
6
7
8
#include <migraphx/op/concat.hpp>
#include <migraphx/op/convolution.hpp>
#include <migraphx/op/as_shape.hpp>
Paul's avatar
Paul committed
9
#include <migraphx/op/broadcast.hpp>
Paul's avatar
Paul committed
10
11
#include <migraphx/matcher.hpp>
#include <migraphx/literal.hpp>
Paul's avatar
Paul committed
12

Paul's avatar
Paul committed
13
namespace migraphx {
Paul's avatar
Paul committed
14
inline namespace MIGRAPHX_INLINE_NS {
Paul's avatar
Paul committed
15

Paul's avatar
Paul committed
16
auto lit_broadcast() { return match::any_of(match::is_constant(), match::name("broadcast")); }
Paul's avatar
Paul committed
17
auto not_lit_broadcast() { return match::none_of(match::is_constant(), match::name("broadcast")); }
Paul's avatar
Paul committed
18
19
auto op_lit_broadcast(std::string op, std::string x, std::string y)
{
Paul's avatar
Paul committed
20
21
    return match::name(std::move(op))(match::either_arg(0, 1)(
        lit_broadcast().bind(std::move(x)), not_lit_broadcast().bind(std::move(y))));
Paul's avatar
Paul committed
22
23
}

Paul's avatar
Paul committed
24
25
auto conv_const_weights()
{
Paul's avatar
Paul committed
26
    return match::name("convolution")(match::used_once(),
Paul's avatar
Paul committed
27
                                      match::args(match::any(), match::is_constant().bind("w")));
Paul's avatar
Paul committed
28
29
}

30
31
32
33
34
35
36
37
38
MIGRAPHX_PRED_MATCHER(args_has_same_ops, instruction_ref ins)
{
    if(ins->inputs().empty())
        return true;
    return std::all_of(ins->inputs().begin(), ins->inputs().end(), [&](auto j) {
        return j->get_operator() == ins->inputs().front()->get_operator();
    });
}

Paul's avatar
Paul committed
39
40
41
struct find_mul_conv
{
    auto matcher() const
Paul's avatar
Paul committed
42
    {
Paul's avatar
Paul committed
43
44
        return match::name("mul")(match::either_arg(0, 1)(conv_const_weights().bind("conv"),
                                                          match::name("broadcast").bind("a")));
Paul's avatar
Paul committed
45
    }
Paul's avatar
Paul committed
46
47

    void apply(program& p, match::matcher_result r) const
Paul's avatar
Paul committed
48
    {
Paul's avatar
Paul committed
49
        auto ins      = r.result;
Paul's avatar
Paul committed
50
        auto conv_ins = r.instructions["conv"];
Paul's avatar
Paul committed
51
52
53
        auto a_ins    = r.instructions["a"];
        auto w_ins    = r.instructions["w"];

Paul's avatar
Paul committed
54
        auto broadcast_op = any_cast<op::broadcast>(a_ins->get_operator());
Paul's avatar
Paul committed
55
        if(broadcast_op.axis != 1)
Paul's avatar
Paul committed
56
57
            return;

Paul's avatar
Paul committed
58
59
60
61
62
        auto new_a = p.insert_instruction(
            ins, op::broadcast{0, w_ins->get_shape().lens()}, a_ins->inputs().front());
        auto new_mul  = p.insert_instruction(ins, op::mul{}, new_a, w_ins);
        auto new_conv = p.insert_instruction(
            ins, conv_ins->get_operator(), conv_ins->inputs().front(), new_mul);
Paul's avatar
Paul committed
63
        p.replace_instruction(ins, new_conv);
Paul's avatar
Paul committed
64
    }
Paul's avatar
Paul committed
65
66
};

Paul's avatar
Paul committed
67
// a * (x + b) => a * x + a * b
Paul's avatar
Paul committed
68
69
70
71
72
struct find_mul_add
{
    auto matcher() const
    {
        return match::name("mul")(match::either_arg(0, 1)(
Paul's avatar
Paul committed
73
74
75
            match::name("add")(
                match::either_arg(0, 1)(
                    match::any().bind("x"),
Paul's avatar
Paul committed
76
                    match::any_of(conv_const_weights(), match::is_constant()).bind("b")),
Paul's avatar
Paul committed
77
                match::none_of(match::args(match::is_constant(), match::is_constant())),
Paul's avatar
Paul committed
78
                match::used_once()),
Paul's avatar
Paul committed
79
            match::is_constant().bind("a")));
Paul's avatar
Paul committed
80
81
82
83
    }

    void apply(program& p, match::matcher_result r) const
    {
Paul's avatar
Paul committed
84
        auto ins   = r.result;
Paul's avatar
Paul committed
85
        auto a_ins = r.instructions["a"];
Paul's avatar
Paul committed
86
        auto b_ins = r.instructions["b"];
Paul's avatar
Paul committed
87
        auto x_ins = r.instructions["x"];
Paul's avatar
Paul committed
88
        assert(x_ins != b_ins);
Paul's avatar
Paul committed
89

Paul's avatar
Paul committed
90
91
92
        auto ax_ins = p.insert_instruction(ins, op::mul{}, a_ins, x_ins);
        auto ab_ins = p.insert_instruction(ins, op::mul{}, a_ins, b_ins);
        p.replace_instruction(ins, op::add{}, ax_ins, ab_ins);
Paul's avatar
Paul committed
93
94
95
    }
};

Paul's avatar
Paul committed
96
struct find_add_lit_broadcast
Paul's avatar
Paul committed
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
{
    auto matcher() const
    {
        return match::name("add")(
            match::either_arg(0, 1)(op_lit_broadcast("add", "a", "x"), lit_broadcast().bind("b")));
    }

    void apply(program& p, match::matcher_result r) const
    {
        auto ins   = r.result;
        auto x_ins = r.instructions["x"];
        auto a_ins = r.instructions["a"];
        auto b_ins = r.instructions["b"];

        auto sumab = p.insert_instruction(ins, op::add{}, a_ins, b_ins);
        p.replace_instruction(ins, op::add{}, x_ins, sumab);
    }
};

struct find_double_add_lit_broadcast
Paul's avatar
Paul committed
117
{
Paul's avatar
Paul committed
118
119
    auto matcher() const
    {
Paul's avatar
Paul committed
120
        return match::name("add")(
Paul's avatar
Paul committed
121
            match::args(op_lit_broadcast("add", "a", "x"), op_lit_broadcast("add", "b", "y")));
Paul's avatar
Paul committed
122
123
124
125
    }

    void apply(program& p, match::matcher_result r) const
    {
Paul's avatar
Paul committed
126
127
128
129
130
        auto ins   = r.result;
        auto x_ins = r.instructions["x"];
        auto y_ins = r.instructions["y"];
        auto a_ins = r.instructions["a"];
        auto b_ins = r.instructions["b"];
Paul's avatar
Paul committed
131
132
133

        instruction_ref sumab;

Paul's avatar
Paul committed
134
        if(a_ins->name() == "broadcast" and b_ins->name() == "broadcast")
Paul's avatar
Paul committed
135
136
137
        {
            if(a_ins->inputs().at(0)->get_shape() != b_ins->inputs().at(0)->get_shape())
                return;
Paul's avatar
Paul committed
138
139
140
141
            auto op = a_ins->get_operator();
            auto presum =
                p.insert_instruction(ins, op::add{}, a_ins->inputs().at(0), b_ins->inputs().at(0));
            sumab = p.insert_instruction(ins, op, presum);
Paul's avatar
Paul committed
142
143
144
145
146
147
148
149
150
151
152
        }
        else
        {
            sumab = p.insert_instruction(ins, op::add{}, a_ins, b_ins);
        }

        auto sumxy = p.insert_instruction(ins, op::add{}, x_ins, y_ins);
        p.replace_instruction(ins, op::add{}, sumxy, sumab);
    }
};

Paul's avatar
Paul committed
153
154
155
156
struct find_inner_broadcast
{
    auto matcher() const
    {
Paul's avatar
Paul committed
157
158
        return match::name("mul", "add")(
            match::args(match::name("broadcast").bind("x"), match::name("broadcast").bind("y")));
Paul's avatar
Paul committed
159
160
161
162
163
164
165
166
167
168
169
    }

    void apply(program& p, match::matcher_result r) const
    {
        auto ins   = r.result;
        auto x_ins = r.instructions["x"];
        auto y_ins = r.instructions["y"];

        auto xbroadcast = any_cast<op::broadcast>(x_ins->get_operator());
        auto ybroadcast = any_cast<op::broadcast>(y_ins->get_operator());

Paul's avatar
Paul committed
170
        if(xbroadcast.axis != ybroadcast.axis)
Paul's avatar
Paul committed
171
172
            return;

Paul's avatar
Paul committed
173
174
        auto op = p.insert_instruction(
            ins, ins->get_operator(), x_ins->inputs().front(), y_ins->inputs().front());
Paul's avatar
Paul committed
175
176
177
178
        p.replace_instruction(ins, xbroadcast, op);
    }
};

179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
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
struct find_concat_unary
{
    auto matcher() const
    {
        return match::name("concat")(args_has_same_ops(),
                                     match::arg(0)(match::nargs(1),
                                                   match::name("relu", "broadcast").bind("x"),
                                                   match::used_once()));
    }

    void apply(program& p, match::matcher_result r) const
    {
        auto ins  = r.result;
        auto x    = r.instructions["x"];
        auto op   = x->get_operator();
        auto axis = any_cast<op::concat>(ins->get_operator()).axis;
        // Adjust broadcast lens
        if(op.name() == "broadcast")
        {
            auto b = any_cast<op::broadcast>(op);
            if(b.axis != axis)
                return;
            b.broadcast_lens = ins->get_shape().lens();
            op               = b;
            axis             = 0;
        }

        auto inputs = ins->inputs();
        std::transform(inputs.begin(), inputs.end(), inputs.begin(), [&](auto i) {
            return i->inputs().front();
        });
        auto concat = p.insert_instruction(ins, op::concat{axis}, inputs);
        p.replace_instruction(ins, op, concat);
    }
};

struct find_concat_binary
{
    auto matcher() const
    {
        return match::name("concat")(args_has_same_ops(),
                                     match::arg(0)(match::nargs(2),
                                                   match::name("add", "multiply").bind("x"),
                                                   match::used_once()));
    }

    void apply(program& p, match::matcher_result r) const
    {
        auto ins       = r.result;
        auto x         = r.instructions["x"];
        auto op        = x->get_operator();
        auto concat_op = ins->get_operator();

        auto xinputs = ins->inputs();
        std::transform(xinputs.begin(), xinputs.end(), xinputs.begin(), [&](auto i) {
            return i->inputs().front();
        });
        auto yinputs = ins->inputs();
        std::transform(yinputs.begin(), yinputs.end(), yinputs.begin(), [&](auto i) {
            return i->inputs().back();
        });
        auto xconcat = p.insert_instruction(ins, concat_op, xinputs);
        auto yconcat = p.insert_instruction(ins, concat_op, yinputs);
        p.replace_instruction(ins, op, xconcat, yconcat);
    }
};

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
311
312
313
314
315
316
317
318
319
320
321
322
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
bool axis_equal(const std::vector<std::size_t>& x,
                const std::vector<std::size_t>& y,
                std::size_t axis)
{
    return x.size() == y.size() and x.size() > axis and
           std::equal(x.begin(), x.begin() + axis, y.begin()) and
           std::equal(x.begin() + axis + 1, x.end(), y.begin() + axis + 1);
}

bool axis_shape_equal(const shape& x, const shape& y, std::size_t axis)
{
    // TODO: Check strides
    return axis_equal(x.lens(), y.lens(), axis);
}

struct find_add_convs
{
    auto matcher() const
    {
        return match::name("add")(
            match::args(conv_const_weights().bind("a"), conv_const_weights().bind("b")));
    }

    static bool symmetrical_strides(const op::convolution& op)
    {
        return op.stride[0] == op.stride[1];
    }

    static std::size_t compute_stride_factor(const op::convolution& x, const op::convolution& y)
    {
        if(not symmetrical_strides(x))
            return 0;
        if(not symmetrical_strides(y))
            return 0;
        if((x.stride[0] % y.stride[0]) != 0)
            return 0;
        return x.stride[0] / y.stride[0];
    }

    static shape compute_stride_shape(const shape& input, std::size_t n)
    {
        return {input.type(),
                {input.lens()[0], input.lens()[1], input.lens()[2] / n, input.lens()[3] / n},
                {input.strides()[0],
                 input.strides()[1],
                 input.strides()[2] * n,
                 input.strides()[3] * n}};
    }

    void apply(program& p, match::matcher_result r) const
    {
        auto ins       = r.result;
        auto a_conv    = r.instructions["a"];
        auto a_input   = a_conv->inputs().at(0);
        auto a_weights = a_conv->inputs().at(1);
        auto b_conv    = r.instructions["b"];
        auto b_input   = b_conv->inputs().at(0);
        auto b_weights = b_conv->inputs().at(1);

        if(not axis_shape_equal(a_weights->get_shape(), b_weights->get_shape(), 1))
            return;

        auto a_op   = any_cast<op::convolution>(a_conv->get_operator());
        auto b_op   = any_cast<op::convolution>(b_conv->get_operator());
        auto new_op = a_op;

        if(a_op != b_op)
        {
            if(std::tie(a_op.padding, a_op.dilation, a_op.group) ==
                   std::tie(b_op.padding, b_op.dilation, b_op.group) and
               a_weights->get_shape().lens()[2] == 1 and a_weights->get_shape().lens()[3] == 1)
            {
                if(a_op.stride < b_op.stride)
                {
                    auto n = compute_stride_factor(b_op, a_op);
                    if(n == 0)
                        return;
                    new_op  = a_op;
                    b_input = p.insert_instruction(
                        ins, op::as_shape{compute_stride_shape(b_input->get_shape(), n)}, b_input);
                }
                else if(b_op.stride < a_op.stride)
                {
                    auto n = compute_stride_factor(a_op, b_op);
                    if(n == 0)
                        return;
                    new_op  = b_op;
                    a_input = p.insert_instruction(
                        ins, op::as_shape{compute_stride_shape(a_input->get_shape(), n)}, a_input);
                }
                else
                    return;
            }
            else
                return;
        }

        auto concat_input   = p.insert_instruction(ins, op::concat{1}, a_input, b_input);
        auto concat_weights = p.insert_instruction(ins, op::concat{1}, a_weights, b_weights);
        p.replace_instruction(ins, new_op, concat_input, concat_weights);
    }
};

Paul's avatar
Paul committed
349
350
void simplify_algebra::apply(program& p) const
{
Paul's avatar
Paul committed
351
    // Run simplifications multiple times
Paul's avatar
Paul committed
352
    for(int i = 0; i < 4; i++)
Paul's avatar
Paul committed
353
    {
Paul's avatar
Paul committed
354
        match::find_matches(p,
Paul's avatar
Paul committed
355
                            find_inner_broadcast{},
Paul's avatar
Paul committed
356
357
                            find_double_add_lit_broadcast{},
                            find_add_lit_broadcast{},
358
                            find_add_convs{},
Paul's avatar
Paul committed
359
                            find_mul_conv{},
360
361
362
                            find_mul_add{},
                            find_concat_unary{},
                            find_concat_binary{});
Paul's avatar
Paul committed
363
364
        dead_code_elimination{}.apply(p);
    }
Paul's avatar
Paul committed
365
}
Paul's avatar
Paul committed
366

Paul's avatar
Paul committed
367
} // namespace MIGRAPHX_INLINE_NS
Paul's avatar
Paul committed
368
} // namespace migraphx