simplify_reshapes.cpp 41.9 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2015-2022 Advanced Micro Devices, Inc. All rights reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
24
#include <iterator>
Paul's avatar
Paul committed
25
26
27
#include <migraphx/simplify_reshapes.hpp>
#include <migraphx/program.hpp>
#include <migraphx/instruction.hpp>
28
#include <migraphx/op/as_shape.hpp>
29
#include <migraphx/op/transpose.hpp>
Paul's avatar
Paul committed
30
#include <migraphx/op/concat.hpp>
31
#include <migraphx/op/slice.hpp>
Paul's avatar
Paul committed
32
33
#include <migraphx/iterator_for.hpp>
#include <migraphx/ranges.hpp>
Paul's avatar
Paul committed
34
#include <migraphx/matcher.hpp>
35
#include <migraphx/permutation.hpp>
36
#include <migraphx/dead_code_elimination.hpp>
Paul's avatar
Paul committed
37
#include <unordered_set>
38
#include <migraphx/make_op.hpp>
39
#include <migraphx/tune_axis.hpp>
Paul's avatar
Paul committed
40
41
#include <migraphx/common_dims.hpp>
#include <migraphx/dom_info.hpp>
42

43
#include <map>
Paul's avatar
Paul committed
44

Paul's avatar
Paul committed
45
namespace migraphx {
Paul's avatar
Paul committed
46
inline namespace MIGRAPHX_INLINE_NS {
Paul's avatar
Paul committed
47

Paul's avatar
Paul committed
48
const auto& reshaper_names()
Paul's avatar
Paul committed
49
{
50
51
    // clang-format off
    static const std::unordered_set<std::string> names = {
52
        "flatten",
53
        "reshape",
54
55
        "squeeze",
        "unsqueeze"
56
57
    };
    // clang-format on
Paul's avatar
Paul committed
58
    return names;
Paul's avatar
Paul committed
59
60
}

Paul's avatar
Paul committed
61
bool is_reshaper(instruction_ref ins) { return contains(reshaper_names(), ins->name()); }
Paul's avatar
Paul committed
62
63
64

instruction_ref find_transpose_input(instruction_ref ins)
{
Paul's avatar
Paul committed
65
    if(ins->inputs().size() != 1)
Paul's avatar
Paul committed
66
        return ins;
Paul's avatar
Paul committed
67
    if(ins->inputs().front()->name() == "contiguous")
Paul's avatar
Paul committed
68
69
70
71
        return find_transpose_input(ins->inputs().front());
    if(ins->inputs().front()->name() == "transpose")
        return ins->inputs().front();
    return ins;
Paul's avatar
Paul committed
72
73
}

74
75
76
77
78
79
80
auto get_transpose_dims(instruction_ref ins)
{
    return any_cast<const op::transpose&>(ins->get_operator()).dims;
}

bool is_no_transpose(const std::vector<int64_t>& dims)
{
Paul's avatar
Paul committed
81
    if(dims.empty())
82
        return true;
Paul's avatar
Paul committed
83
    if(dims.front() != 0)
84
        return false;
Paul's avatar
Paul committed
85
86
    return std::adjacent_find(
               dims.begin(), dims.end(), [](auto x, auto y) { return (y - x) != 1; }) == dims.end();
87
88
}

Paul's avatar
Paul committed
89
struct find_reshaper
Paul's avatar
Paul committed
90
{
Paul's avatar
Paul committed
91
    auto matcher() const
Paul's avatar
Paul committed
92
    {
Paul's avatar
Paul committed
93
        auto no_output_reshape = match::none_of[match::outputs()](match::name(reshaper_names()));
Paul's avatar
Format  
Paul committed
94
95
96
97
        auto input_reshape =
            match::arg(0)(match::skip(match::name("contiguous"))(match::name(reshaper_names())));
        auto input = match::skip(match::name(reshaper_names()),
                                 match::name("contiguous"))(match::arg(0).bind("x"));
Paul's avatar
Paul committed
98
        return match::name(reshaper_names())(no_output_reshape, input_reshape, input);
Paul's avatar
Paul committed
99
100
    }

101
    void apply(module& m, const match::matcher_result& mr) const
Paul's avatar
Paul committed
102
    {
Paul's avatar
Format  
Paul committed
103
        auto ins   = mr.result;
Paul's avatar
Paul committed
104
        auto input = mr.instructions["x"];
Paul's avatar
Format  
Paul committed
105
        auto dims  = ins->get_shape().lens();
Paul's avatar
Paul committed
106

Paul's avatar
Format  
Paul committed
107
        if(not input->get_shape().standard())
Paul's avatar
Paul committed
108
            input = m.insert_instruction(ins, make_op("contiguous"), input);
Paul's avatar
Paul committed
109
        m.replace_instruction(ins, make_op("reshape", {{"dims", dims}}), input);
Paul's avatar
Paul committed
110
111
112
    }
};

Paul's avatar
Paul committed
113
114
115
116
117
struct find_nop_reshapes
{
    auto matcher() const
    {
        auto reshapes = reshaper_names();
118
119
120
        reshapes.insert("as_shape");
        reshapes.insert("broadcast");
        reshapes.insert("concat");
Paul Fultz II's avatar
Paul Fultz II committed
121
        reshapes.insert("convert");
122
123
        reshapes.insert("multibroadcast");
        reshapes.insert("pad");
Paul's avatar
Paul committed
124
        reshapes.insert("slice");
125
        reshapes.insert("transpose");
Paul's avatar
Paul committed
126
        return match::name(reshapes)(match::same_shape(match::arg(0)));
Paul's avatar
Paul committed
127
128
    }

129
    void apply(module& m, const match::matcher_result& mr) const
Paul's avatar
Paul committed
130
131
    {
        auto ins = mr.result;
132
        m.replace_instruction(ins, ins->inputs().front());
Paul's avatar
Paul committed
133
134
135
    }
};

Paul's avatar
Paul committed
136
137
138
139
struct find_transpose
{
    auto matcher() const
    {
140
141
142
143
144
        auto output_not_transpose =
            match::none_of(match::skip_output(match::name("contiguous"))(match::name("transpose")));
        auto input_has_transpose =
            match::args(match::skip(match::name("contiguous"))(match::name("transpose")));
        return match::name("transpose")(output_not_transpose, input_has_transpose);
Paul's avatar
Paul committed
145
146
    }

147
    void apply(module& m, const match::matcher_result& mr) const
Paul's avatar
Paul committed
148
149
    {
        auto ins = mr.result;
Paul's avatar
Paul committed
150
151
        auto x   = ins;
        auto t   = ins;
Paul's avatar
Paul committed
152
153
154
155
156
157
158
159
160
161
162
163
        std::vector<std::int64_t> dims(ins->get_shape().lens().size());
        std::iota(dims.begin(), dims.end(), 0);
        do
        {
            dims = reorder_dims(get_transpose_dims(t), dims);
            x    = t;
            t    = find_transpose_input(x);
        } while(x != t and t->name() == "transpose");
        if(t == ins or t->name() != "transpose")
            return;
        if(is_no_transpose(dims))
        {
164
            m.replace_instruction(ins, t->inputs().front());
Paul's avatar
Paul committed
165
166
        }
        else
Paul's avatar
Paul committed
167
        {
168
            m.replace_instruction(
169
                ins, make_op("transpose", {{"permutation", dims}}), t->inputs().front());
Paul's avatar
Paul committed
170
        }
Paul's avatar
Paul committed
171
    }
Paul's avatar
Paul committed
172
173
};

174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
struct find_nested_convert
{
    auto matcher() const { return match::name("convert")(match::arg(0)(match::name("convert"))); }

    void apply(module& m, const match::matcher_result& mr) const
    {
        auto ins   = mr.result;
        auto x     = ins->inputs().front();
        auto input = x->inputs().front();

        if(ins->get_shape() != input->get_shape())
            return;

        m.replace_instruction(ins, input);
    }
};

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
struct find_nested_slice
{
    auto matcher() const { return match::name("slice")(match::arg(0)(match::name("slice"))); }

    using axes_map = std::map<std::size_t, std::pair<std::size_t, std::size_t>>;

    static axes_map get_axes(instruction_ref ins)
    {
        axes_map result;
        auto op = any_cast<op::slice>(ins->get_operator());
        for(std::size_t i = 0; i < op.axes.size(); i++)
        {
            result[op.axes[i]] = std::make_pair(op.starts[i], op.ends[i]);
        }
        return result;
    }

    static axes_map merge(const axes_map& m1, const axes_map& m2)
    {
        axes_map result;
        // Non overlapping
        for(auto&& p : m1)
        {
            if(contains(m2, p.first))
                continue;
            result[p.first] = p.second;
        }
        for(auto&& p : m2)
        {
            if(contains(m1, p.first))
                continue;
            result[p.first] = p.second;
        }
        // Overlapping
        for(auto&& p1 : m1)
        {
            if(not contains(m2, p1.first))
                continue;
            auto&& v1        = p1.second;
            auto&& v2        = m2.at(p1.first);
            auto start       = v1.first + v2.first;
            auto end         = start + (v2.second - v2.first);
            result[p1.first] = std::make_pair(start, end);
        }
        return result;
    }

238
    void apply(module& m, const match::matcher_result& mr) const
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
    {
        auto ins   = mr.result;
        auto slice = ins->inputs().front();
        auto input = slice->inputs().front();

        auto a1 = get_axes(ins);
        auto a2 = get_axes(slice);

        auto axes = merge(a2, a1);

        auto op = op::slice{};
        for(auto&& pp : axes)
        {
            op.axes.push_back(pp.first);
            op.starts.push_back(pp.second.first);
            op.ends.push_back(pp.second.second);
        }
256
        m.replace_instruction(ins, op, input);
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
struct find_concat_multibroadcasts
{
    auto matcher() const
    {
        return match::name("concat")(match::all_of[match::inputs()](match::name("multibroadcast")));
    }

    void apply(module& m, const match::matcher_result& mr) const
    {
        auto ins        = mr.result;
        auto op         = any_cast<op::concat>(ins->get_operator());
        auto out_lens   = ins->get_shape().lens();
        auto inputs     = ins->inputs();
        auto in_strides = inputs.front()->get_shape().strides();

        // Only apply when concat axis is not a broadcasted dimension
        if(std::any_of(inputs.begin(), inputs.end(), [&](auto i) {
               return i->get_shape().strides()[op.axis] == 0;
           }))
        {
            return;
        }

        // Use inputs of multibroadcast ops as inputs to new concat op
        std::transform(inputs.begin(), inputs.end(), inputs.begin(), [](auto i) {
            return i->inputs().front();
        });

        // Reduce axis by number of leading broadcasted dimensions
        if(inputs.front()->get_shape().lens().size() < out_lens.size())
            op.axis -= std::count(in_strides.begin(), in_strides.begin() + op.axis, 0);

        auto concat = m.insert_instruction(ins, op, inputs);
        m.replace_instruction(
            ins, migraphx::make_op("multibroadcast", {{"out_lens", out_lens}}), concat);
    }
};

Paul's avatar
Paul committed
298
299
300
301
struct find_concat_transpose
{
    auto matcher() const
    {
302
        return match::name("concat")(match::all_of[match::inputs()](match::name("transpose")));
Paul's avatar
Paul committed
303
304
    }

305
    void apply(module& m, const match::matcher_result& mr) const
Paul's avatar
Paul committed
306
    {
Shucai Xiao's avatar
Shucai Xiao committed
307
308
309
        auto ins          = mr.result;
        auto trans_inputs = ins->inputs();
        auto s            = trans_inputs.front()->get_shape();
Paul's avatar
Paul committed
310
        assert(s.transposed());
Shucai Xiao's avatar
Shucai Xiao committed
311
312
313
314
        auto op          = any_cast<op::concat>(ins->get_operator());
        auto permutation = find_permutation(s);

        // permutation should be the same for all inputs
315
        if(not std::all_of(trans_inputs.begin(), trans_inputs.end(), [&](auto in) {
Shucai Xiao's avatar
Shucai Xiao committed
316
317
318
319
320
321
322
323
               return (find_permutation(in->get_shape()) == permutation);
           }))
        {
            return;
        }

        // axis could be a negative value
        int64_t n_dim = static_cast<int64_t>(s.lens().size());
324
        op.axis       = tune_axis(n_dim, op.axis, op.name());
Shucai Xiao's avatar
Shucai Xiao committed
325

Paul's avatar
Paul committed
326
        auto ipermutation = invert_permutation(permutation);
Paul's avatar
Paul committed
327
        op.axis           = ipermutation[op.axis];
Paul's avatar
Paul committed
328
329
330

        std::vector<instruction_ref> inputs;
        std::transform(
Paul's avatar
Paul committed
331
            ins->inputs().begin(), ins->inputs().end(), std::back_inserter(inputs), [&](auto i) {
332
                return m.insert_instruction(
333
                    ins, make_op("transpose", {{"permutation", permutation}}), i);
Paul's avatar
Paul committed
334
            });
335
336
        auto concat = m.insert_instruction(ins, op, inputs);
        auto t      = m.insert_instruction(
337
            ins, make_op("transpose", {{"permutation", ipermutation}}), concat);
Paul's avatar
Paul committed
338
        assert(ins->get_shape().lens() == t->get_shape().lens());
339
        m.replace_instruction(ins, t);
Paul's avatar
Paul committed
340
341
342
    }
};

Paul Fultz II's avatar
Paul Fultz II committed
343
344
345
346
347
348
349
350
351
352
353
354
355
struct find_nested_concat
{
    auto matcher() const
    {
        return match::name("concat")(match::any_of[match::inputs()](match::name("concat")));
    }

    static std::size_t get_axis(instruction_ref ins)
    {
        auto op = any_cast<op::concat>(ins->get_operator());
        return op.axis;
    }

356
    void apply(module& m, const match::matcher_result& mr) const
Paul Fultz II's avatar
Paul Fultz II committed
357
358
359
360
361
362
363
364
365
366
367
368
369
    {
        auto ins  = mr.result;
        auto axis = get_axis(ins);
        std::vector<instruction_ref> args;
        fix([&](auto self, auto&& inputs) {
            for(auto&& i : inputs)
            {
                if(i->name() == "concat" and get_axis(i) == axis and i->outputs().size() == 1)
                    self(i->inputs());
                else
                    args.push_back(i);
            }
        })(ins->inputs());
370
        m.replace_instruction(ins, ins->get_operator(), args);
Paul Fultz II's avatar
Paul Fultz II committed
371
372
373
    }
};

374
375
376
377
378
379
380
381
struct find_resize
{
    auto matcher() const
    {
        return match::name("gather")(
            match::args(match::name("reshape").bind("data"), match::is_constant().bind("ind")));
    }

382
    void apply(module& m, const match::matcher_result& r) const
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
    {
        auto ins     = r.result;
        auto ins_rsp = r.instructions["data"];
        auto ins_ind = r.instructions["ind"];

        // resize input shape
        if(ins_rsp->get_shape().lens().size() != 1)
        {
            return;
        }

        // resize output shape
        const auto& in_shape  = ins_rsp->inputs().front()->get_shape();
        const auto& out_shape = ins->get_shape();
        // check if output shape is multiple of input shape
        const auto& in_lens  = in_shape.lens();
        const auto& out_lens = out_shape.lens();
        if(in_lens.size() != out_lens.size())
        {
            return;
        }

        // output shape must be multiple of input shape
        std::vector<bool> is_multi(in_lens.size());
        std::transform(
            in_lens.begin(), in_lens.end(), out_lens.begin(), is_multi.begin(), [](auto x, auto y) {
                return (y % x == 0);
            });
        if(not std::all_of(is_multi.begin(), is_multi.end(), [](auto b) { return b; }))
        {
            return;
        }

        // output must be multiple of inputs
        std::vector<std::size_t> scales(in_lens.size());
        std::transform(
            in_lens.begin(), in_lens.end(), out_lens.begin(), scales.begin(), [](auto x, auto y) {
                return y / x;
            });

        // if ind is not constant, cannot optimize
        std::vector<int> vec_ind;
        auto arg_ind = ins_ind->eval();
        if(arg_ind.empty())
        {
            return;
        }
        arg_ind.visit([&](auto v) { vec_ind.assign(v.begin(), v.end()); });
431
        if(not all_of(range(out_shape.elements()), [&](auto i) {
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
               auto out_idx = out_shape.multi(i);
               auto in_idx  = out_idx;
               std::transform(out_idx.begin(),
                              out_idx.end(),
                              scales.begin(),
                              in_idx.begin(),
                              [&](auto io, auto scale) { return io - (io % scale); });
               return vec_ind[i] == vec_ind[out_shape.index(in_idx)];
           }))
        {
            return;
        }

        // wrap up shapes for multibroadcast
        std::vector<std::pair<std::size_t, std::size_t>> dim_scales;
        std::transform(in_lens.begin(),
                       in_lens.end(),
                       out_lens.begin(),
                       std::back_inserter(dim_scales),
                       [](auto x, auto y) { return std::make_pair(x, y / x); });

        std::vector<int64_t> in_dims;
        std::vector<int64_t> out_dims;
        for(auto& isp : dim_scales)
        {
            in_dims.push_back(isp.first);
            out_dims.push_back(isp.first * isp.second);
            if(isp.first == 1 or isp.second == 1)
            {
                continue;
            }

            out_dims.back() = isp.first;
            in_dims.push_back(1);
            out_dims.push_back(isp.second);
        }

        auto in_rsp   = ins_rsp->inputs().front();
470
        auto rsp_data = m.insert_instruction(
471
            ins_rsp, migraphx::make_op("reshape", {{"dims", in_dims}}), in_rsp);
472
        auto mb_rsp = m.insert_instruction(
473
            ins_rsp, migraphx::make_op("multibroadcast", {{"out_lens", out_dims}}), rsp_data);
474
        auto std_mb = m.insert_instruction(ins, migraphx::make_op("contiguous"), mb_rsp);
475
        std::vector<int64_t> rsp_dims(out_lens.begin(), out_lens.end());
476
        m.replace_instruction(ins, migraphx::make_op("reshape", {{"dims", rsp_dims}}), std_mb);
477
478
479
480
481
482
483
484
485
486
487
488
    }
};

struct find_where_op
{
    auto matcher() const
    {
        return match::name("gather")(
            match::args(match::name("reshape")(match::arg(0)(match::name("concat").bind("data"))),
                        match::is_constant().bind("ind")));
    }

489
    void apply(module& m, const match::matcher_result& r) const
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
    {
        auto ins     = r.result;
        auto concat  = r.instructions["data"];
        auto ins_ind = r.instructions["ind"];
        std::vector<bool> vec_ind;
        auto arg_ind = ins_ind->eval();
        arg_ind.visit([&](auto v) { vec_ind.assign(v.begin(), v.end()); });
        // ind has to be the same value
        auto val = vec_ind.front();
        if(not std::all_of(vec_ind.begin(), vec_ind.end(), [&](auto v) { return (v == val); }))
        {
            return;
        }

        // concat axis must be 0
        auto op = any_cast<op::concat>(concat->get_operator());
        if(op.axis != 0)
        {
            return;
        }

        // check concat inputs, it has to be 2 and have the same shape
        const auto& inputs = concat->inputs();
        if(inputs.size() != 2)
        {
            return;
        }
        if(inputs.at(0)->get_shape() != inputs.at(1)->get_shape())
        {
            return;
        }
        if(inputs.at(0)->get_shape().lens() != ins_ind->get_shape().lens())
        {
            return;
        }

        if(val)
        {
528
            m.replace_instruction(ins, inputs.at(0));
529
530
531
        }
        else
        {
532
            m.replace_instruction(ins, inputs.at(1));
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
        }
    }
};

struct find_reshape_cont
{
    auto matcher() const
    {
        return match::pointwise(
            match::nargs(2),
            match::either_arg(0, 1)(
                match::name("reshape")(match::args(match::name("contiguous").bind("cont")))
                    .bind("rsp"),
                match::any()));
    }

549
    void apply(module& m, const match::matcher_result& r) const
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
    {
        auto ins      = r.result;
        auto ins_cont = r.instructions["cont"];
        auto in_ins   = r.instructions["rsp"];

        auto cont_input = ins_cont->inputs().front();
        auto lens       = cont_input->get_shape().lens();
        std::vector<int64_t> dims(lens.begin(), lens.end());

        if(in_ins->get_shape() != ins->get_shape())
        {
            return;
        }

        if(not std::all_of(ins->inputs().begin(), ins->inputs().end(), [](auto i) {
               return i->get_shape().standard();
           }))
        {
            return;
        }

        auto out_lens = ins->get_shape().lens();
        std::vector<int64_t> out_dims(out_lens.begin(), out_lens.end());
        std::vector<instruction_ref> inputs;
        for(const auto& in : ins->inputs())
        {
            if(in == in_ins)
            {
                inputs.push_back(cont_input);
            }
            else
            {
                inputs.push_back(
583
                    m.insert_instruction(ins, make_op("reshape", {{"dims", dims}}), in));
584
585
            }
        }
586
587
        auto out = m.insert_instruction(ins, ins->get_operator(), inputs);
        m.replace_instruction(ins, make_op("reshape", {{"dims", out_dims}}), out);
588
589
590
    }
};

591
// match sequence of transpose --> contiguous --> reshaper_op
Paul's avatar
Format  
Paul committed
592
template <class... Ms>
Paul's avatar
Paul committed
593
auto match_transpose_contiguous_reshaper(Ms... ms)
594
595
596
{
    return match::name({"reshape", "squeeze", "unsqueeze"})(
               match::used_once(),
Paul's avatar
Format  
Paul committed
597
598
599
600
               match::args(match::name("contiguous")(
                               match::used_once(),
                               match::args(match::transpose_shape(ms...).bind("trans_ins")))
                               .bind("cont_ins")))
601
602
603
604
605
606
607
608
609
610
611
612
        .bind("reshaper_ins");
};

// finds the pattern of transpose --> contiguous --> reshaper_op --> unary
// application of this matcher moves the unary operation before the contiguous so it becomes
// transpose --> unary --> contiguous --> reshaper_op. later pointwise sub-module can be created out
// of unary --> contiguous --> reshaper_op. Such pattern appears in depthToSpace or spaceToDepth
// operator.
struct find_transpose_contiguous_reshaper_unary
{
    auto matcher() const
    {
613
614
615
        return pointwise(match::used_once(),
                         match::nargs(1),
                         match::args(match_transpose_contiguous_reshaper()));
616
617
    }

618
    void apply(module& m, const match::matcher_result& r) const
619
620
621
622
623
624
    {
        auto ins           = r.result;
        auto reshaper_ins  = r.instructions["reshaper_ins"];
        auto trans_ins     = r.instructions["trans_ins"];
        auto cont_ins      = r.instructions["cont_ins"];
        auto unary_op_name = ins->get_operator().name();
625
626
        auto unary_ins     = m.insert_instruction(cont_ins, make_op(unary_op_name), trans_ins);
        auto new_cont_ins  = m.insert_instruction(cont_ins, make_op("contiguous"), unary_ins);
627
        // older cont and reshape are removed by deadcode elimination
628
        m.replace_instruction(ins, reshaper_ins->get_operator(), new_cont_ins);
629
630
631
    }
};

Paul's avatar
Paul committed
632
633
634
635
struct find_mul_add_transpose_contiguous_reshaper_gemm
{
    auto matcher() const
    {
Paul's avatar
Format  
Paul committed
636
637
638
639
        auto pw = match::name("mul", "add")(
            match::used_once(),
            match::either_arg(0, 1)(match::is_constant().bind("c"), match::any().bind("x")));
        return match::name("dot")(match::either_arg(0, 1)(
Paul's avatar
Format  
Paul committed
640
641
            match_transpose_contiguous_reshaper(match::args(pw.bind("pointwise"))),
            match::is_constant()));
Paul's avatar
Paul committed
642
643
644
645
    }

    void apply(module& m, const match::matcher_result& r) const
    {
Paul's avatar
Format  
Paul committed
646
647
648
649
650
651
        auto ins             = r.result;
        auto reshaper_ins    = r.instructions["reshaper_ins"];
        auto trans_ins       = r.instructions["trans_ins"];
        auto x_ins           = r.instructions["x"];
        auto c_ins           = r.instructions["c"];
        auto pw_ins          = r.instructions["pointwise"];
Paul's avatar
Paul committed
652
653
654
655
656
        auto insert_reshapes = [&](auto x) {
            auto t = m.insert_instruction(ins, trans_ins->get_operator(), x);
            auto c = m.insert_instruction(ins, make_op("contiguous"), t);
            return m.insert_instruction(ins, reshaper_ins->get_operator(), c);
        };
Paul's avatar
Format  
Paul committed
657
        if(x_ins->name() == "mul")
Paul's avatar
Paul committed
658
        {
Paul's avatar
Format  
Paul committed
659
660
661
662
            x_ins = m.insert_instruction(
                ins,
                make_op("mul"),
                {insert_reshapes(x_ins->inputs()[0]), insert_reshapes(x_ins->inputs()[1])});
Paul's avatar
Paul committed
663
664
        }

Paul's avatar
Format  
Paul committed
665
666
        auto y_ins =
            m.insert_instruction(ins, pw_ins->get_operator(), {x_ins, insert_reshapes(c_ins)});
Paul's avatar
Paul committed
667
668
669
670
        m.replace_instruction(reshaper_ins, y_ins);
    }
};

671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
struct find_slice_transpose
{
    auto matcher() const
    {
        return match::any(match::any_of[match::outputs()](
            match::name("slice")(match::output(match::name("transpose")))));
    }

    static std::vector<int64_t> find_common_perm(const std::vector<instruction_ref>& transposes)
    {
        std::map<std::vector<int64_t>, int64_t> count;
        for(auto t : transposes)
        {
            auto perm = t->get_operator().to_value()["permutation"].to_vector<int64_t>();
            count[perm]++;
        }
        return std::max_element(
                   count.begin(), count.end(), by(std::less<>{}, [](auto&& p) { return p.second; }))
            ->first;
    }

    void apply(module& m, const match::matcher_result& r) const
    {
        auto ins = r.result;
        std::vector<instruction_ref> splits;
        std::copy_if(ins->outputs().begin(),
                     ins->outputs().end(),
                     std::back_inserter(splits),
                     [&](instruction_ref out) {
                         return out->name() == "slice" and out->outputs().size() == 1 and
                                out->outputs().front()->name() == "transpose";
                     });
        if(splits.size() < 2)
            return;
        std::vector<instruction_ref> transposes;
        std::transform(splits.begin(),
                       splits.end(),
                       std::back_inserter(transposes),
                       [](auto split) { return split->outputs().front(); });
        auto perm  = find_common_perm(transposes);
        auto iperm = invert_permutation(perm);
        auto pre   = m.insert_instruction(
            std::next(ins), make_op("transpose", {{"permutation", perm}}), ins);
        for(auto i : range(transposes.size()))
        {
            auto split = splits[i];
            auto t     = transposes[i];
            auto op    = any_cast<op::slice>(split->get_operator());
            std::transform(op.axes.begin(), op.axes.end(), op.axes.begin(), [&](auto axis) {
                return iperm[axis];
            });
            auto new_ins = m.insert_instruction(t, op, pre);
            if(t->get_operator() != pre->get_operator())
            {
                auto curr = t->get_operator().to_value()["permutation"].to_vector<int64_t>();
                new_ins   = m.insert_instruction(
                    t, make_op("transpose", {{"permutation", reorder_dims(iperm, curr)}}), new_ins);
            }
            m.replace_instruction(t, new_ins);
        }
    }
};

734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
struct find_transpose_slice
{
    auto matcher() const
    {
        return match::name("transpose")(match::all_of[match::outputs()](match::name("slice")));
    }

    static std::vector<int64_t> slice_distance(const op::slice& op)
    {
        assert(op.starts.size() == op.ends.size());
        std::vector<int64_t> result(op.starts.size());
        std::transform(
            op.ends.begin(), op.ends.end(), op.starts.begin(), result.begin(), std::minus<>{});
        return result;
    }

    void apply(module& m, const match::matcher_result& r) const
    {
        auto ins    = r.result;
        auto slices = ins->outputs();
        if(slices.empty())
            return;
        auto slice     = any_cast<op::slice>(slices.front()->get_operator());
        auto sdistance = slice_distance(slice);
        // Check all distances and axes are the same
        if(std::any_of(slices.begin(), slices.end(), [&](auto sins) {
               auto s = any_cast<op::slice>(sins->get_operator());
               return s.axes != slice.axes or slice_distance(s) != sdistance;
           }))
            return;
        // Check distances are divisible by lens of corresponding axes
        auto mod_by_distance = [&](const auto& v, auto f) {
            return std::inner_product(v.begin(),
                                      v.end(),
                                      sdistance.begin(),
                                      0,
                                      std::plus<>{},
                                      [&](auto x, auto d) -> uint64_t {
                                          if(d == 0)
                                              return 1;
                                          return f(x) % d;
                                      });
        };
        if(mod_by_distance(slice.axes, [&](auto x) { return ins->get_shape().lens()[x]; }) != 0 or
           mod_by_distance(slice.starts, id{}) != 0 or mod_by_distance(slice.ends, id{}) != 0)
            return;
        // TODO: Handle multiple axes
        if(sdistance.size() != 1)
            return;
        auto axis = slice.axes.front();
        // Skip if axis would be packed
        if(std::all_of(ins->get_shape().lens().begin(),
                       ins->get_shape().lens().begin() + axis,
                       [](auto x) { return x == 1; }))
            return;
        // Compute axis before transpose to use for unsqueeze
        auto perm    = ins->get_operator().to_value()["permutation"].to_vector<int64_t>();
791
        auto preaxis = perm[axis];
shivadbhavsar's avatar
shivadbhavsar committed
792
793
794
795
796
797
798
799
        // Make unsqueeze
        std::vector<int64_t> steps(sdistance.size());
        std::transform(
            slice.axes.begin(),
            slice.axes.end(),
            sdistance.begin(),
            steps.begin(),
            [&](const auto ax, const auto sdis) { return ins->get_shape().lens().at(ax) / sdis; });
800
        auto unsqueeze = m.insert_instruction(
shivadbhavsar's avatar
shivadbhavsar committed
801
            ins, make_op("unsqueeze", {{"axes", {preaxis}}, {"steps", steps}}), ins->inputs());
802
803
        // Make transpose
        std::transform(perm.begin(), perm.end(), perm.begin(), [&](auto i) {
shivadbhavsar's avatar
shivadbhavsar committed
804
            if(i >= preaxis)
805
806
807
                return i + 1;
            return i;
        });
shivadbhavsar's avatar
shivadbhavsar committed
808
        perm.insert(perm.begin(), preaxis);
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
        auto transpose =
            m.insert_instruction(ins, make_op("transpose", {{"permutation", perm}}), unsqueeze);
        // Slice and squeeze
        for(auto s : slices)
        {
            auto op        = any_cast<op::slice>(s->get_operator());
            op.axes        = {0};
            op.starts      = {op.starts.front() / sdistance.front()};
            op.ends        = {op.ends.front() / sdistance.front()};
            auto slice_ins = m.insert_instruction(ins, op, transpose);
            auto squeeze =
                m.insert_instruction(ins, make_op("squeeze", {{"axes", {0}}}), slice_ins);
            m.replace_instruction(s, squeeze);
        }
    }
};

Paul's avatar
Paul committed
826
827
struct find_reshape_gemm
{
Paul's avatar
Format  
Paul committed
828
    auto matcher() const { return match::name("reshape")(match::arg(0)(match::name("dot"))); }
Paul's avatar
Paul committed
829
830
831

    static bool is_batched_unsqueeze(instruction_ref ins)
    {
Paul's avatar
Format  
Paul committed
832
        auto input  = ins->inputs().front()->get_shape().lens();
Paul's avatar
Paul committed
833
        auto output = ins->get_shape().lens();
Paul's avatar
Format  
Paul committed
834
        if(output.size() <= input.size())
Paul's avatar
Paul committed
835
            return false;
Paul's avatar
Format  
Paul committed
836
        if(not std::equal(input.end() - 2, input.end(), output.end() - 2, output.end()))
Paul's avatar
Paul committed
837
838
839
840
841
842
            return false;
        return true;
    }

    static operation make_reshape(std::vector<std::size_t> batches, instruction_ref ins)
    {
Paul's avatar
Format  
Paul committed
843
844
        batches.insert(
            batches.end(), ins->get_shape().lens().end() - 2, ins->get_shape().lens().end());
Paul's avatar
Paul committed
845
846
847
848
849
850
        return make_op("reshape", {{"dims", batches}});
    }

    void apply(module& m, const match::matcher_result& r) const
    {
        auto reshape_ins = r.result;
Paul's avatar
Format  
Paul committed
851
        auto dot_ins     = reshape_ins->inputs().front();
Paul's avatar
Paul committed
852
853

        // TODO: Put this in the matcher
Paul's avatar
Format  
Paul committed
854
        if(not is_batched_unsqueeze(reshape_ins))
Paul's avatar
Paul committed
855
856
857
            return;

        std::vector<std::size_t> batches;
Paul's avatar
Format  
Paul committed
858
859
860
861
862
863
864
865
        std::copy(reshape_ins->get_shape().lens().begin(),
                  reshape_ins->get_shape().lens().end() - 2,
                  std::back_inserter(batches));

        auto input0 = m.insert_instruction(
            dot_ins, make_reshape(batches, dot_ins->inputs()[0]), dot_ins->inputs()[0]);
        auto input1 = m.insert_instruction(
            dot_ins, make_reshape(batches, dot_ins->inputs()[1]), dot_ins->inputs()[1]);
Paul's avatar
Paul committed
866
867
868
869
        m.replace_instruction(dot_ins, make_op("dot"), input0, input1);
    }
};

Paul's avatar
Paul committed
870
871
872
873
struct find_broadcast_reshaper
{
    auto matcher() const
    {
Paul's avatar
Format  
Paul committed
874
        auto broadcast =
Paul's avatar
Paul committed
875
            match::broadcast_shape(match::skip(match::broadcast_shape())(match::any().bind("x")));
Paul's avatar
Format  
Paul committed
876
877
        return match::name(reshaper_names())(
            match::args(match::skip(match::name("contiguous"))(broadcast.bind("broadcast"))));
Paul's avatar
Paul committed
878
879
880
881
882
    }

    void apply(module& m, const match::matcher_result& r) const
    {
        auto ins           = r.result;
Paul's avatar
Format  
Paul committed
883
884
        auto broadcast_ins = r.instructions["broadcast"];
        auto x_ins         = r.instructions["x"];
Paul's avatar
Paul committed
885
886

        auto broadcast_shape = broadcast_ins->get_shape();
Paul's avatar
Format  
Paul committed
887
        auto result_shape    = ins->get_shape();
Paul's avatar
Paul committed
888

Paul's avatar
Format  
Paul committed
889
890
        if(std::accumulate(broadcast_shape.strides().begin(), broadcast_shape.strides().end(), 0) !=
           1)
Paul's avatar
Paul committed
891
892
            return;

Paul's avatar
Format  
Paul committed
893
894
895
        auto baxis =
            std::find(broadcast_shape.strides().begin(), broadcast_shape.strides().end(), 1) -
            broadcast_shape.strides().begin();
Paul's avatar
Paul committed
896
        auto relements = result_shape.lens();
Paul's avatar
Format  
Paul committed
897
898
899
900
901
902
903
904
905
        std::partial_sum(
            relements.begin(), relements.end(), relements.begin(), std::multiplies<>{});
        auto prefix_elements = std::accumulate(broadcast_shape.lens().begin(),
                                               broadcast_shape.lens().begin() + baxis + 1,
                                               1,
                                               std::multiplies<>{});
        auto axis =
            std::find(relements.begin(), relements.end(), prefix_elements) - relements.begin();
        if(axis >= relements.size())
Paul's avatar
Paul committed
906
907
            return;

Paul's avatar
Format  
Paul committed
908
        if(x_ins->get_shape().lens().size() > 1)
Paul's avatar
Paul committed
909
910
            x_ins = m.insert_instruction(ins, make_op("squeeze"), x_ins);

Paul's avatar
Format  
Paul committed
911
912
913
914
        m.replace_instruction(
            ins,
            make_op("broadcast", {{"axis", axis}, {"out_lens", ins->get_shape().lens()}}),
            x_ins);
Paul's avatar
Paul committed
915
916
917
    }
};

Paul's avatar
Paul committed
918
919
struct find_poinwise_reduce_reshape
{
Paul's avatar
Paul committed
920
921
922
923
924
    template<class... Ms>
    static auto match_reshaper(Ms... ms)
    {
        return match::name({"reshape", "squeeze", "unsqueeze"})(match::arg(0)(match::skip(match::name("contiguous"))(ms...)));
    }
Paul's avatar
Paul committed
925
926
927
    auto matcher() const
    {
        auto pointwise_or_reduce = match::any_of(match::pointwise(), match::reduce());
Paul's avatar
Format  
Paul committed
928
        auto reshape_pointwise_or_reduce =
Paul's avatar
Paul committed
929
            match_reshaper(match::pointwise().bind("x")).bind("reshape");
Paul's avatar
Paul committed
930
931
932
        return pointwise_or_reduce(match::any_of[match::inputs()](reshape_pointwise_or_reduce));
    }

Paul's avatar
Paul committed
933
934
935
936
937
938
939
940
941
942
    static bool is_broadcast(const operation& op)
    {
        return contains({"broadcast", "multibroadcast"}, op.name());
    }

    static bool is_broadcast(instruction_ref ins)
    {
        return is_broadcast(ins->get_operator());
    }

Paul's avatar
Paul committed
943
944
945
946
947
948
949
950
    static bool is_pointwise(instruction_ref ins)
    {
        auto a = ins->get_operator().attributes();
        return a.get("pointwise", false);
    }

    static bool is_reduce(instruction_ref ins)
    {
Paul's avatar
Paul committed
951
952
953
954
955
956
        return is_reduce(ins->get_operator());
    }

    static bool is_reduce(const operation& op)
    {
        auto a = op.attributes();
Paul's avatar
Paul committed
957
958
959
960
961
962
963
964
965
        return a.get("reduce", false);
    }

    static bool is_pointwise_or_reduce(instruction_ref ins)
    {
        auto a = ins->get_operator().attributes();
        return a.get("pointwise", false) or a.get("reduce", false);
    }

Paul's avatar
Paul committed
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
    static std::vector<instruction_ref> topo_sort(instruction_ref entry, const std::unordered_set<instruction_ref>& inss, std::unordered_set<instruction_ref>& aux)
    {
        std::vector<instruction_ref> instructions;
        bool has_entry = contains(inss, entry);
        fix([&](auto self, instruction_ref ins) {
            if (ins != entry or has_entry)
                instructions.push_back(ins);
            for(auto input:ins->inputs())
            {
                if(not contains(inss, input))
                    aux.insert(input);
            }
            for(auto output : ins->outputs())
            {
                if (contains(instructions, output))
                    continue;
                if (not contains(inss, output))
                    continue;
                self(output);
            }
        })(entry);
        assert(instructions.size() == inss.size());
        return instructions;
    }

    static std::vector<instruction_ref> topo_sort(const std::unordered_set<instruction_ref>& inss, std::unordered_set<instruction_ref>& aux)
    {
        std::vector<instruction_ref> instructions;
        std::unordered_set<instruction_ref> visited;
        for(auto ins:inss)
        {
            fix([&](auto self, instruction_ref child) {
                if (contains(visited, child))
                    return;
                for(auto output:child->outputs())
                {
                    if (not contains(inss, output))
                        continue;
                    self(output);
                }
                visited.insert(child);
                for(auto input:child->inputs())
                {
                    if(not contains(inss, input))
                        aux.insert(input);
                }
                instructions.push_back(child);
            })(ins);
        }
        std::reverse(instructions.begin(), instructions.end());
        assert(instructions.size() == inss.size());
        return instructions;
    }

Paul's avatar
Paul committed
1020
1021
    void apply(module& m, const match::matcher_result& r) const
    {
Paul's avatar
Paul committed
1022
        // std::cout << "find_poinwise_reduce_reshape" << std::endl;
Paul's avatar
Format  
Paul committed
1023
1024
1025
        auto ins         = r.result;
        auto x_ins       = r.instructions["x"];
        auto reshape_ins = r.instructions["reshape"];
Paul's avatar
Paul committed
1026

Paul's avatar
Paul committed
1027
        auto nelements = x_ins->get_shape().elements();
Paul's avatar
Paul committed
1028
1029
1030
        auto dims1 = x_ins->get_shape().lens();
        auto dims2 = reshape_ins->get_shape().lens();

Paul's avatar
Paul committed
1031
1032
1033
1034
1035
1036
1037
        auto cd = common_dims::compute(dims1, dims2);
        if (cd.empty())
            return;

        // m.debug_print();
        // m.debug_print(reshape_ins);
        // m.debug_print(ins);
Paul's avatar
Paul committed
1038
        // Collect from inputs
Paul's avatar
Paul committed
1039
1040
        std::unordered_set<instruction_ref> input_inss;
        instruction_ref entry;
Paul's avatar
Paul committed
1041
        fix([&](auto self, instruction_ref i) {
Paul's avatar
Paul committed
1042
1043
1044
            if(contains(input_inss, i))
                return;
            input_inss.insert(i);
Paul's avatar
Format  
Paul committed
1045
            entry                    = i;
Paul's avatar
Paul committed
1046
            auto pointwise_or_reduce = [](instruction_ref input) {
Paul's avatar
Format  
Paul committed
1047
                if(input->can_eval())
Paul's avatar
Paul committed
1048
1049
1050
1051
                    return false;
                return is_pointwise(input);
            };
            auto it = std::find_if(i->inputs().begin(), i->inputs().end(), pointwise_or_reduce);
Paul's avatar
Format  
Paul committed
1052
            if(it == i->inputs().end())
Paul's avatar
Paul committed
1053
1054
1055
                return;
            auto it2 = std::find_if(it, i->inputs().end(), pointwise_or_reduce);
            // If there is more than one pointwise_reduce than stop
Paul's avatar
Format  
Paul committed
1056
            if(it2 != i->inputs().end())
Paul's avatar
Paul committed
1057
1058
1059
                return;
            self(*it);
        })(x_ins);
Paul's avatar
Paul committed
1060
1061
1062
1063

        std::vector<int64_t> axes;
        auto dom = compute_post_dominator(m);
        std::unordered_set<instruction_ref> output_inss;
Paul's avatar
Paul committed
1064
1065
        // Collect from output
        fix([&](auto self, instruction_ref out) {
Paul's avatar
Paul committed
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
            // if(contains(inss, out))
                // return;
            // std::cout << "Visit: ";
            // m.debug_print(out);
            // m.debug_print(out->inputs());
            auto outputs = out->outputs();
            std::sort(outputs.begin(), outputs.end(), by(std::less<>{}, [&](instruction_ref i) {
                return std::distance(reshape_ins, i);
            }));
            // m.debug_print(outputs);
            for(auto output : outputs)
Paul's avatar
Paul committed
1077
            {
Paul's avatar
Format  
Paul committed
1078
1079
                if(not std::all_of(
                       output->inputs().begin(), output->inputs().end(), [&](auto input) {
Paul's avatar
Paul committed
1080
                           return input->can_eval() or reshape_ins == input or contains(output_inss, input);// or dom.strictly_dominate(reshape_ins, input);
Paul's avatar
Format  
Paul committed
1081
                       }))
Paul's avatar
Paul committed
1082
                    continue;
Paul's avatar
Paul committed
1083
                if(not is_pointwise_or_reduce(output) and not is_broadcast(output))
Paul's avatar
Paul committed
1084
                    continue;
Paul's avatar
Paul committed
1085
                if (is_reduce(output))
Paul's avatar
Paul committed
1086
                {
Paul's avatar
Paul committed
1087
1088
1089
1090
1091
                    auto op_axes = output->get_operator().to_value()["axes"].to_vector<int64_t>();
                    if (axes.empty())
                        axes = op_axes;
                    if(axes != op_axes)
                        return;
Paul's avatar
Paul committed
1092
                }
Paul's avatar
Paul committed
1093
                output_inss.insert(output);
Paul's avatar
Paul committed
1094
1095
                self(output);
            }
Paul's avatar
Paul committed
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
        })(reshape_ins);

        std::vector<int64_t> common_axes;
        for(auto axis:axes)
        {
            common_axes.insert(common_axes.end(), cd.axes_map2[axis].begin(), cd.axes_map2[axis].end());
        }
        auto common_rdims = cd.dims;
        for(auto axis:common_axes)
        {
            common_rdims[axis] = 1;
        }
        // Topological sort
        std::unordered_set<instruction_ref> aux;
        auto input_instructions = topo_sort(input_inss, aux);
        auto output_instructions = topo_sort(output_inss, aux);
        // std::cout << "output_inss:\n";
        // m.debug_print({output_inss.begin(), output_inss.end()});
        // std::cout << "Output instructions:\n";
        // m.debug_print(output_instructions);
        // std::cout << "aux:\n";
        // m.debug_print({aux.begin(), aux.end()});

        auto last = output_instructions.back();
        auto insert_reshape = [&](instruction_ref input) {
            auto use_rdims = input->get_shape().elements() < nelements;
            auto c = m.insert_instruction(last, make_op("contiguous"), input);
            return m.insert_instruction(last, make_op("reshape", {{"dims", use_rdims ? common_rdims : cd.dims}}), c);
        };

        std::unordered_map<instruction_ref, instruction_ref> map_ins;
        // map_ins[entry] = insert_reshape(entry);
        for(auto i:aux)
        {
            map_ins[i] = insert_reshape(i);
        }
        auto inserter = [&](module& mm, instruction_ref i, operation op, const std::vector<instruction_ref>& args, const std::vector<module_ref>& module_args) {
            if (is_reduce(op))
                op.from_value({{"axes", common_axes}});
            if (is_broadcast(op))
                op.from_value({{"out_lens", cd.dims}});
            // std::cout << op << std::endl;
            // m.debug_print(args);
            return mm.insert_instruction(i, op, args, module_args);
        };
        auto new_x_ins = m.insert_instructions(inserter, last, input_instructions, map_ins).front();
        map_ins[reshape_ins] = new_x_ins;
        auto new_last = m.insert_instructions(inserter, last, output_instructions, map_ins).front();
        auto new_c = m.insert_instruction(last, make_op("contiguous"), new_last);
        auto new_reshape = m.insert_instruction(last, make_op("reshape", {{"dims", dims2}}), new_c);
        m.debug_print();
        m.debug_print(last);
        m.debug_print(new_reshape);
        m.replace_instruction(last, new_reshape);
        std::abort();
Paul's avatar
Paul committed
1151
1152
1153
    }
};

1154
void simplify_reshapes::apply(module& m) const
Paul's avatar
Paul committed
1155
{
1156
    for(int i = 0; i < 4; i++)
Paul's avatar
Paul committed
1157
    {
1158
        match::find_matches(m,
1159
1160
                            find_where_op{},
                            find_resize{},
1161
1162
                            find_nop_reshapes{},
                            find_reshaper{},
Paul's avatar
Paul committed
1163
                            // find_broadcast_reshaper{},
Paul's avatar
Paul committed
1164
                            // find_reshape_cont{},
1165
1166
                            find_transpose{},
                            find_concat_transpose{},
1167
                            find_concat_multibroadcasts{},
1168
                            find_nested_convert{},
1169
                            find_nested_slice{},
1170
                            find_nested_concat{},
1171
                            find_transpose_slice{},
1172
                            find_slice_transpose{},
Paul's avatar
Paul committed
1173
                            find_transpose_contiguous_reshaper_unary{},
Paul's avatar
Paul committed
1174
                            find_mul_add_transpose_contiguous_reshaper_gemm{},
Paul's avatar
Paul committed
1175
1176
                            find_reshape_gemm{},
                            find_poinwise_reduce_reshape{});
1177
        dead_code_elimination{}.apply(m);
Paul's avatar
Paul committed
1178
    }
Paul's avatar
Paul committed
1179
1180
}

Paul's avatar
Paul committed
1181
} // namespace MIGRAPHX_INLINE_NS
Paul's avatar
Paul committed
1182
} // namespace migraphx