simplify_algebra.cpp 9.61 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
}

Paul's avatar
Paul committed
30
31
32
struct find_mul_conv
{
    auto matcher() const
Paul's avatar
Paul committed
33
    {
Paul's avatar
Paul committed
34
35
        return match::name("mul")(match::either_arg(0, 1)(conv_const_weights().bind("conv"),
                                                          match::name("broadcast").bind("a")));
Paul's avatar
Paul committed
36
    }
Paul's avatar
Paul committed
37
38

    void apply(program& p, match::matcher_result r) const
Paul's avatar
Paul committed
39
    {
Paul's avatar
Paul committed
40
        auto ins      = r.result;
Paul's avatar
Paul committed
41
        auto conv_ins = r.instructions["conv"];
Paul's avatar
Paul committed
42
43
44
        auto a_ins    = r.instructions["a"];
        auto w_ins    = r.instructions["w"];

Paul's avatar
Paul committed
45
        auto broadcast_op = any_cast<op::broadcast>(a_ins->get_operator());
Paul's avatar
Paul committed
46
        if(broadcast_op.axis != 1)
Paul's avatar
Paul committed
47
48
            return;

Paul's avatar
Paul committed
49
50
51
52
53
        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
54
        p.replace_instruction(ins, new_conv);
Paul's avatar
Paul committed
55
    }
Paul's avatar
Paul committed
56
57
};

Paul's avatar
Paul committed
58
// a * (x + b) => a * x + a * b
Paul's avatar
Paul committed
59
60
61
62
63
struct find_mul_add
{
    auto matcher() const
    {
        return match::name("mul")(match::either_arg(0, 1)(
Paul's avatar
Paul committed
64
65
66
            match::name("add")(
                match::either_arg(0, 1)(
                    match::any().bind("x"),
Paul's avatar
Paul committed
67
                    match::any_of(conv_const_weights(), match::is_constant()).bind("b")),
Paul's avatar
Paul committed
68
                match::none_of(match::args(match::is_constant(), match::is_constant())),
Paul's avatar
Paul committed
69
                match::used_once()),
Paul's avatar
Paul committed
70
            match::is_constant().bind("a")));
Paul's avatar
Paul committed
71
72
73
74
    }

    void apply(program& p, match::matcher_result r) const
    {
Paul's avatar
Paul committed
75
        auto ins   = r.result;
Paul's avatar
Paul committed
76
        auto a_ins = r.instructions["a"];
Paul's avatar
Paul committed
77
        auto b_ins = r.instructions["b"];
Paul's avatar
Paul committed
78
        auto x_ins = r.instructions["x"];
Paul's avatar
Paul committed
79
        assert(x_ins != b_ins);
Paul's avatar
Paul committed
80

Paul's avatar
Paul committed
81
82
83
        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
84
85
86
    }
};

Paul's avatar
Paul committed
87
struct find_add_lit_broadcast
Paul's avatar
Paul committed
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
{
    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
108
{
Paul's avatar
Paul committed
109
110
    auto matcher() const
    {
Paul's avatar
Paul committed
111
        return match::name("add")(
Paul's avatar
Paul committed
112
            match::args(op_lit_broadcast("add", "a", "x"), op_lit_broadcast("add", "b", "y")));
Paul's avatar
Paul committed
113
114
115
116
    }

    void apply(program& p, match::matcher_result r) const
    {
Paul's avatar
Paul committed
117
118
119
120
121
        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
122
123
124

        instruction_ref sumab;

Paul's avatar
Paul committed
125
        if(a_ins->name() == "broadcast" and b_ins->name() == "broadcast")
Paul's avatar
Paul committed
126
127
128
        {
            if(a_ins->inputs().at(0)->get_shape() != b_ins->inputs().at(0)->get_shape())
                return;
Paul's avatar
Paul committed
129
130
131
132
            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
133
134
135
136
137
138
139
140
141
142
143
        }
        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
144
145
146
147
struct find_inner_broadcast
{
    auto matcher() const
    {
Paul's avatar
Paul committed
148
149
        return match::name("mul", "add")(
            match::args(match::name("broadcast").bind("x"), match::name("broadcast").bind("y")));
Paul's avatar
Paul committed
150
151
152
153
154
155
156
157
158
159
160
    }

    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
161
        if(xbroadcast.axis != ybroadcast.axis)
Paul's avatar
Paul committed
162
163
            return;

Paul's avatar
Paul committed
164
165
        auto op = p.insert_instruction(
            ins, ins->get_operator(), x_ins->inputs().front(), y_ins->inputs().front());
Paul's avatar
Paul committed
166
167
168
169
        p.replace_instruction(ins, xbroadcast, op);
    }
};

170
171
172
173
174
175
176
177
178
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
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
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
273
274
void simplify_algebra::apply(program& p) const
{
Paul's avatar
Paul committed
275
    // Run simplifications multiple times
Paul's avatar
Paul committed
276
    for(int i = 0; i < 4; i++)
Paul's avatar
Paul committed
277
    {
Paul's avatar
Paul committed
278
        match::find_matches(p,
Paul's avatar
Paul committed
279
                            find_inner_broadcast{},
Paul's avatar
Paul committed
280
281
                            find_double_add_lit_broadcast{},
                            find_add_lit_broadcast{},
282
                            find_add_convs{},
Paul's avatar
Paul committed
283
284
                            find_mul_conv{},
                            find_mul_add{});
Paul's avatar
Paul committed
285
286
        dead_code_elimination{}.apply(p);
    }
Paul's avatar
Paul committed
287
}
Paul's avatar
Paul committed
288

Paul's avatar
Paul committed
289
} // namespace MIGRAPHX_INLINE_NS
Paul's avatar
Paul committed
290
} // namespace migraphx