"test/ref_ops_nonstd_shape_test.cpp" did not exist on "7477aeb88590a4be745c0208bc62be4ecd21d2db"
parse_instancenorm.cpp 6.67 KB
Newer Older
1
2
3
/*
 * The MIT License (MIT)
 *
4
 * Copyright (c) 2015-2023 Advanced Micro Devices, Inc. All rights reserved.
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
 *
 * 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 Fultz II's avatar
Paul Fultz II committed
25
26
27
28
#include <migraphx/onnx/op_parser.hpp>
#include <migraphx/ranges.hpp>
#include <migraphx/instruction.hpp>
#include <migraphx/make_op.hpp>
29
30
31
#include <migraphx/env.hpp>

MIGRAPHX_DECLARE_ENV_VAR(MIGRAPHX_DISABLE_FP16_INSTANCENORM_CONVERT);
Paul Fultz II's avatar
Paul Fultz II committed
32
33
34
35
36
37
38

namespace migraphx {
inline namespace MIGRAPHX_INLINE_NS {
namespace onnx {

struct parse_instancenorm : op_parser<parse_instancenorm>
{
39
    std::set<shape::type_t> valid_types = {shape::float_type, shape::half_type, shape::double_type};
40

Paul Fultz II's avatar
Paul Fultz II committed
41
42
    std::vector<op_desc> operators() const { return {{"InstanceNormalization"}}; }

43
    instruction_ref parse(const op_desc& opd,
Paul Fultz II's avatar
Paul Fultz II committed
44
45
                          const onnx_parser& parser,
                          onnx_parser::node_info info,
46
                          std::vector<instruction_ref> oargs) const
Paul Fultz II's avatar
Paul Fultz II committed
47
48
49
50
    {
        // y = scale * ( x - mean ) / sqrt ( variance + epsilon ) + bias
        // mean = reduce_mean({D1, D2, ... Dk}, x)
        // variance = reduce_mean({D1, D2, ... Dk}, (x - mean)^2)
51
52
53
54
55
56
        // Convert fp16 to fp32 to workaround for FP16 accuracy issues with reduce_mean/variance.
        bool convert_fp16 = true;
        if(enabled(MIGRAPHX_DISABLE_FP16_INSTANCENORM_CONVERT{}))
        {
            convert_fp16 = false;
        }
Paul Fultz II's avatar
Paul Fultz II committed
57
58
59
60
61
        float epsilon = 1e-5f;
        if(contains(info.attributes, "epsilon"))
        {
            epsilon = parser.parse_value(info.attributes.at("epsilon")).at<float>();
        }
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
        auto dtype         = oargs[0]->get_shape().type();
        auto literal_dtype = dtype;
        std::vector<instruction_ref> args;
        // cppcheck-suppress knownConditionTrueFalse
        if(dtype == shape::half_type and convert_fp16)
        {
            std::transform(oargs.begin(), oargs.end(), std::back_inserter(args), [&](const auto i) {
                return info.add_instruction(
                    make_op("convert", {{"target_type", shape::float_type}}), i);
            });
            literal_dtype = shape::float_type;
        }
        else
        {
            args = oargs;
        }

Paul Fultz II's avatar
Paul Fultz II committed
79
80
81
        auto x     = args[0];
        auto scale = args[1];
        auto bias  = args[2];
82
83
84
85
        if(not contains(valid_types, dtype))
            MIGRAPHX_THROW(opd.op_name + ": invalid output type: " + std::to_string(dtype) +
                           ". Valid types are 1 (float), 10 (half), and 11 (double).");

86
        auto ndims = x->get_shape().ndim();
Paul Fultz II's avatar
Paul Fultz II committed
87
88
89
90
91
        assert(ndims >= 2);
        auto kdims = ndims - 2;
        std::vector<int64_t> axes(kdims);
        std::iota(axes.begin(), axes.end(), 2);
        auto mean = info.add_instruction(make_op("reduce_mean", {{"axes", axes}}), x);
92
93
94
95

        // Use add_common_op() to insert multibroadcast/convert instructions where needed when
        // inputs may be either static or dynamic.
        auto l1 = info.add_common_op("sub", x, mean);
96
97
98
99
100
101
102
        // for the fp16, if not converting to fp32 then divide `x` and `mean` by `sqrt(n)` and take
        // reduce_sum to calculate variance i.e.
        // var =  reduce_sum((x/s_n - mean/s_n)^2) where s_n = sqrt(n)
        std::string reduce_op_name =
            (dtype == shape::half_type and not convert_fp16) ? "reduce_sum" : "reduce_mean";
        if(dtype == shape::half_type and not convert_fp16)
        {
103
104
105
106
107
108
            if(x->get_shape().dynamic())
            {
                MIGRAPHX_THROW("PARSE_INSTANCENORM: half type not supported with dynamic shape "
                               "unless convert_fp16 is TRUE");
            }
            auto dims = x->get_shape().lens();
109
110
111
112
113
114
115
116
            double n =
                std::accumulate(dims.begin() + 2, dims.end(), 1, [&](const auto& i, const auto& j) {
                    return i * j;
                });
            n              = 1.0 / std::sqrt(n);
            auto n_literal = info.add_literal(literal{dtype, {n}});
            x              = info.add_common_op("mul", {x, n_literal});
        }
117
        auto l0              = info.add_common_op("sqdiff", x, mean);
118
119
        auto variance        = info.add_instruction(make_op(reduce_op_name, {{"axes", axes}}), l0);
        auto epsilon_literal = info.add_literal(literal{shape{literal_dtype}, {epsilon}});
120
121
        auto l2              = info.add_common_op("add", variance, epsilon_literal);

Paul Fultz II's avatar
Paul Fultz II committed
122
        auto l3 = info.add_instruction(make_op("rsqrt"), l2);
123
124
125
126
127
128
        auto l4 = info.add_common_op("mul", l1, l3);

        // add_common_op() doesn't apply the plain broadcast op, so we add that op explicitly for
        // both scale and bias.
        instruction_ref scale_bcast;
        instruction_ref bias_bcast;
129
        if(x->get_shape().dynamic())
130
131
132
133
134
135
        {
            scale_bcast = info.add_instruction(make_op("broadcast", {{"axis", 1}}), scale, x);
            bias_bcast  = info.add_instruction(make_op("broadcast", {{"axis", 1}}), bias, x);
        }
        else
        {
136
            auto dims   = x->get_shape().lens();
137
138
139
140
141
            scale_bcast = info.add_instruction(
                make_op("broadcast", {{"axis", 1}, {"out_lens", dims}}), scale);
            bias_bcast =
                info.add_instruction(make_op("broadcast", {{"axis", 1}, {"out_lens", dims}}), bias);
        }
142
143
144
145
146
147
148
149
        auto l5  = info.add_instruction(make_op("mul"), l4, scale_bcast);
        auto ret = info.add_instruction(make_op("add"), l5, bias_bcast);
        if(dtype == shape::half_type and convert_fp16)
        {
            return info.add_instruction(make_op("convert", {{"target_type", shape::half_type}}),
                                        ret);
        }
        return ret;
Paul Fultz II's avatar
Paul Fultz II committed
150
151
152
153
154
155
    }
};

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