parse_if.cpp 7.51 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.
 */
Shucai Xiao's avatar
Shucai Xiao committed
24
#include <migraphx/instruction_ref.hpp>
Shucai Xiao's avatar
Shucai Xiao committed
25
26
27
28
29
30
#include <migraphx/onnx/op_parser.hpp>
#include <migraphx/onnx/onnx_parser.hpp>
#include <migraphx/onnx/checks.hpp>
#include <migraphx/ranges.hpp>
#include <migraphx/instruction.hpp>
#include <migraphx/make_op.hpp>
31
32
#include <migraphx/reduce_dims.hpp>
#include <algorithm>
Shucai Xiao's avatar
Shucai Xiao committed
33
34
35
36
37
38
39
40
41
42
43
44
45
46

namespace migraphx {
inline namespace MIGRAPHX_INLINE_NS {
namespace onnx {

struct parse_if : op_parser<parse_if>
{
    std::vector<op_desc> operators() const { return {{"If"}}; }

    std::vector<instruction_ref> parse(const op_desc& /*opd*/,
                                       onnx_parser& parser,
                                       const onnx_parser::node_info& info,
                                       std::vector<instruction_ref> args) const
    {
Shucai Xiao's avatar
Shucai Xiao committed
47
48
        const auto& then_graph = info.attributes.at("then_branch").g();
        const auto& else_graph = info.attributes.at("else_branch").g();
Shucai Xiao's avatar
Shucai Xiao committed
49

Shucai Xiao's avatar
Shucai Xiao committed
50
        if(args.front()->get_shape().elements() != 1)
Shucai Xiao's avatar
Shucai Xiao committed
51
        {
52
53
            MIGRAPHX_THROW("PARSE_IF: " + info.name +
                           " condition input can have only one element!");
Shucai Xiao's avatar
Shucai Xiao committed
54
55
        }

Shucai Xiao's avatar
Shucai Xiao committed
56
57
        std::string then_name = info.name + "_if";
        module_ref then_mdl   = parser.prog.create_module(then_name);
Shucai Xiao's avatar
Shucai Xiao committed
58

Shucai Xiao's avatar
Shucai Xiao committed
59
60
        std::string else_name = info.name + "_else";
        module_ref else_mdl   = parser.prog.create_module(else_name);
Shucai Xiao's avatar
Shucai Xiao committed
61

Shucai Xiao's avatar
Shucai Xiao committed
62
63
        // parse the then sub_graph
        parser.parse_graph(then_mdl, then_graph);
Shucai Xiao's avatar
Shucai Xiao committed
64

Shucai Xiao's avatar
Shucai Xiao committed
65
66
        // parse_the else sub_graph
        parser.parse_graph(else_mdl, else_graph);
Shucai Xiao's avatar
Shucai Xiao committed
67

Shucai Xiao's avatar
Shucai Xiao committed
68
69
        auto then_out_shapes = then_mdl->get_output_shapes();
        auto else_out_shapes = else_mdl->get_output_shapes();
70

71
72
        auto throw_shapes = [&]() {
            MIGRAPHX_THROW("PARSE_IF: " + info.name +
73
                           " then and else sub_graphs must compatible shapes ");
74
75
76
77
78
79
        };

        if(then_out_shapes.size() != else_out_shapes.size())
        {
            throw_shapes();
        }
80
81

        // Must have the same type for both if/else blocks by onnx spec
82
        // Add exception for empty constant scalars
83
        if(then_out_shapes.at(0).type() != else_out_shapes.at(0).type())
Shucai Xiao's avatar
Shucai Xiao committed
84
        {
85
            MIGRAPHX_THROW("PARSE_IF: " + info.name +
86
                           " then and else sub_grahps must have same output type! " +
87
88
                           then_out_shapes.at(0).type_string() + " vs " +
                           else_out_shapes.at(0).type_string());
89
90
        }

91
        if(not then_out_shapes.at(0).dynamic() && not else_out_shapes.at(0).dynamic())
92
        {
93
94
            auto then_lens = then_out_shapes.at(0).lens();
            auto else_lens = else_out_shapes.at(0).lens();
95

96
            // Throw error if both branches have zero output shapes. Not possible for static inputs
97
            if(then_lens.empty() && else_lens.empty())
98
99
100
101
            {
                throw_shapes();
            }

102
103
104
            auto handle_empty_branch = [](module_ref& mdl, const shape& out_shape) {
                auto outline_ins = mdl->add_outline(out_shape);
                mdl->replace_return({outline_ins});
105
                return out_shape.lens();
106
107
            };

108
            // Handle one empty branch by setting output identical to the other
109
            // need to update the then_shape before we do further checks
110
            if(then_lens.empty())
111
            {
112
                then_lens = handle_empty_branch(then_mdl, else_out_shapes.at(0));
113
            }
114
            else if(else_lens.empty())
115
            {
116
                else_lens = handle_empty_branch(else_mdl, then_out_shapes.at(0));
117
            }
118
            else
119
            {
120
                // check equivilant length dims, and (x1,x2,.., xn, 1) == (x1,x2,..,xn)
121
                int dim_delta = abs((static_cast<int>(then_lens.size() - else_lens.size())));
122
123

                if(dim_delta <= 1)
124
                {
125
126
127
128
129
130
131
132
133
134
135
136
                    auto all_but_last_dims_equal = [](std::vector<size_t>& lens_A,
                                                      std::vector<size_t>& lens_B) {
                        if(lens_A.size() <= lens_B.size())
                        {
                            return equal(lens_A.begin(), lens_A.end(), lens_B.begin());
                        }
                        else
                        {
                            return equal(lens_B.begin(), lens_B.end(), lens_A.begin());
                        }
                    };

137
                    // make sure dims are equivalent in static shapes
138
                    if(not all_but_last_dims_equal(then_lens, else_lens))
139
140
141
                    {
                        throw_shapes();
                    }
142

143
144
145
146
                    auto unsqueeze_last_op = [](module_ref& mdl,
                                                const std::vector<size_t>& out_shape) {
                        auto convert_ins = mdl->add_instruction(
                            make_op("unsqueeze", {{"axes", {out_shape.size() - 1}}}),
147
                            std::prev(std::prev(mdl->end())));
148
                        mdl->replace_return({convert_ins});
149
                        mdl->remove_instruction({std::prev(convert_ins)});
150
151
                    };

152
153
                    auto last_then = *(std::prev(then_lens.end()));
                    auto last_else = *(std::prev(else_lens.end()));
154

155
                    // Find which dim to unsqueeze
156
                    if((then_lens.size() < else_lens.size()) && (last_else == 1))
157
                    {
158
                        unsqueeze_last_op(then_mdl, else_lens);
159
                    }
160
                    else if((then_lens.size() > else_lens.size()) && (last_then == 1))
161
                    {
162
                        unsqueeze_last_op(else_mdl, then_lens);
163
                    }
164
                }
165
166
167
168
                else
                {
                    throw_shapes();
                }
169
            }
Shucai Xiao's avatar
Shucai Xiao committed
170
        }
Shucai Xiao's avatar
Shucai Xiao committed
171

Shucai Xiao's avatar
Shucai Xiao committed
172
173
174
        auto if_ret = info.add_instruction(make_op("if"), args, {then_mdl, else_mdl});
        auto out_s  = if_ret->get_shape();
        assert(out_s.type() == shape::tuple_type);
Shucai Xiao's avatar
Shucai Xiao committed
175

Shucai Xiao's avatar
Shucai Xiao committed
176
177
178
179
180
181
        const auto& vec_shapes = out_s.sub_shapes();
        std::vector<instruction_ref> out_inss;
        for(std::size_t i = 0; i < vec_shapes.size(); ++i)
        {
            auto ret = info.add_instruction(make_op("get_tuple_elem", {{"index", i}}), if_ret);
            out_inss.push_back(ret);
Shucai Xiao's avatar
Shucai Xiao committed
182
        }
Shucai Xiao's avatar
Shucai Xiao committed
183
184

        return out_inss;
Shucai Xiao's avatar
Shucai Xiao committed
185
186
187
188
189
190
    }
};

} // namespace onnx
} // namespace MIGRAPHX_INLINE_NS
} // namespace migraphx