"src/vscode:/vscode.git/clone" did not exist on "3d089f91c9e3d94e59aaa3e9947ab30a32e2ea78"
parse_pad.cpp 6.86 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.
 */
Paul Fultz II's avatar
Paul Fultz II committed
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
#include <migraphx/onnx/op_parser.hpp>
#include <migraphx/onnx/checks.hpp>
#include <migraphx/ranges.hpp>
#include <migraphx/instruction.hpp>
#include <migraphx/make_op.hpp>

namespace migraphx {
inline namespace MIGRAPHX_INLINE_NS {
namespace onnx {

void calc_reflect_indices(std::vector<int>& indices, const int64_t num_dims)
{
    int k         = 0;
    bool reversed = false;
    // in reflect padding, if the num_pads > num_dims,
    // compute the extra pad indices periodically, ex. ( 1, 2, 3, 2, 1, 0)
    for(int& idx : indices)
    {
        if(k == num_dims - 1)
            reversed = true;
        if(k == 0)
            reversed = false;
        if(reversed)
            k--;
        else
            k++;
        idx = k;
    }
}

instruction_ref reflect_pad(const onnx_parser::node_info& info,
                            const std::vector<int64_t>& pads,
                            instruction_ref input)
{
    size_t num_dims = pads.size() / 2;
    std::vector<int> ldims(pads.begin(), pads.begin() + num_dims);
    std::vector<int> rdims(pads.begin() + num_dims, pads.end());
    assert(ldims.size() == rdims.size());

    std::vector<int64_t> axes(num_dims);
    std::iota(axes.begin(), axes.end(), int64_t{0});

    // iterate over dimensions, starting from lowest dimension
    for(int64_t i = num_dims - 1; i >= 0; i--)
    {
        auto axis   = i;
        auto lcount = ldims.at(i);
        auto rcount = rdims.at(i);
        if(lcount == 0 and rcount == 0) // no padding for current dim
            continue;

        // calculate starts and ends for each iteration since shape may change
        std::vector<size_t> dims = input->get_shape().lens();
        std::vector<int64_t> starts(axes.size(), 0);
        std::vector<int64_t> ends(dims.begin(), dims.end());
        std::vector<instruction_ref> slices;

        auto starts_it = starts.begin() + i;
        auto ends_it   = ends.begin() + i;
        auto dims_it   = dims.begin() + i;

        std::vector<int> l_indices(lcount);
        std::vector<int> r_indices(rcount);

        // compute slice indices in a periodic fashion
        calc_reflect_indices(l_indices, *dims_it);
        calc_reflect_indices(r_indices, *dims_it);

        for(int idx : l_indices)
        {
            *starts_it = idx;
            *ends_it   = *starts_it + 1;
Shucai Xiao's avatar
Shucai Xiao committed
96
            slices.push_back(info.add_instruction(
Paul Fultz II's avatar
Paul Fultz II committed
97
98
99
100
101
102
103
104
105
106
107
108
                make_op("slice", {{"axes", axes}, {"starts", starts}, {"ends", ends}}), input));
        }
        // when padding on the left side, the outermost pad should be at the beginning
        std::reverse(slices.begin(), slices.end());
        slices.push_back(input);
        for(int idx : r_indices)
        {
            *starts_it = *dims_it - idx - 1;
            *ends_it   = *starts_it + 1;
            slices.push_back(info.add_instruction(
                make_op("slice", {{"axes", axes}, {"starts", starts}, {"ends", ends}}), input));
        }
Shucai Xiao's avatar
Shucai Xiao committed
109
        input = info.add_instruction(make_op("concat", {{"axis", axis}}), slices);
Paul Fultz II's avatar
Paul Fultz II committed
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
    }
    return input;
}

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

    instruction_ref parse(const op_desc& /*opd*/,
                          const onnx_parser& parser,
                          onnx_parser::node_info info,
                          std::vector<instruction_ref> args) const
    {
        std::vector<int64_t> pads{};
        if(args.size() >= 2)
        {
            auto pad_arg = args.at(1)->eval();
            check_arg_empty(pad_arg, "PARSE_PAD: pad input must be constant");
            pad_arg.visit([&](auto v) { pads.assign(v.begin(), v.end()); });
        }
        else if(contains(info.attributes, "pads"))
        {
            auto&& pad_vals = info.attributes["pads"].ints();
            pads            = std::vector<int64_t>(pad_vals.begin(), pad_vals.end());
        }
        else
        {
            MIGRAPHX_THROW("PARSE_PAD: pad must be available");
        }

        // check if padding is actually being done (at least one value is nonzero)
        if(std::all_of(pads.begin(), pads.end(), [](const int& i) { return i == 0; }))
        {
            return info.add_instruction(make_op("identity"), args.front());
        }

        if(contains(info.attributes, "mode"))
        {
            auto mode = info.attributes.at("mode").s();
            if(mode == "reflect")
charlie's avatar
Initial  
charlie committed
150
151
152
153
            {
                if(args.front()->get_shape().dynamic())
                {
                    MIGRAPHX_THROW("PARSE_PAD: reflect padding with dynamic shape not supported");
charlie's avatar
charlie committed
154
                }
Paul Fultz II's avatar
Paul Fultz II committed
155
                return reflect_pad(info, pads, args.front());
charlie's avatar
Initial  
charlie committed
156
            }
Paul Fultz II's avatar
Paul Fultz II committed
157
158
159
160
161
162
163
164
165
166
167
168
            if(mode != "constant")
            {
                MIGRAPHX_THROW(
                    "PARSE_PAD: migraphx currently only supports constant and reflect padding");
            }
        }

        float value = 0.0f;
        // third input is the value
        if(args.size() == 3)
        {
            auto val_ins = args.at(2);
169
            if(not val_ins->can_eval())
Paul Fultz II's avatar
Paul Fultz II committed
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
            {
                MIGRAPHX_THROW("PARSE_PAD: input value must be constant");
            }
            auto val_arg = val_ins->eval();
            if(val_arg.get_shape().elements() != 1)
            {
                MIGRAPHX_THROW("PARSE_PAD: value should contain only one element");
            }
            value = val_arg.at<float>();
        }
        else if(contains(info.attributes, "value"))
        {
            value = parser.parse_value(info.attributes.at("value")).at<float>();
        }

        return info.add_instruction(migraphx::make_op("pad", {{"pads", pads}, {"value", value}}),
                                    args.front());
    }
};

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