scatter.hpp 2.02 KB
Newer Older
Shucai Xiao's avatar
Shucai Xiao committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#ifndef MIGRAPHX_GUARD_OPERATORS_SCATTER_HPP
#define MIGRAPHX_GUARD_OPERATORS_SCATTER_HPP

#include <array>
#include <migraphx/check_shapes.hpp>
#include <migraphx/stringutils.hpp>
#include <migraphx/streamutils.hpp>
#include <migraphx/shape_for_each.hpp>
#include <migraphx/config.hpp>
#include <migraphx/value.hpp>
#include <migraphx/op/normalize_attribute.hpp>
#include <cmath>
#include <utility>

namespace migraphx {
inline namespace MIGRAPHX_INLINE_NS {
namespace op {

struct scatter
{
    int64_t axis = 0;

    template <class Self, class F>
    static auto reflect(Self& self, F f)
    {
        return pack(f(self.axis, "axis"));
    }

    value attributes() const
    {
        value normalize;
        normalize["axis"] = value::array{normalize_attribute::include_min};
        return {{"normalize_axes", normalize}};
    }

    std::string name() const { return "scatter"; }

    shape normalize_compute_shape(std::vector<shape> inputs) const
    {
        check_shapes{inputs, *this}.has(3).standard();
        return inputs.front();
    }

    argument compute(const shape& output_shape, std::vector<argument> args) const
    {
        argument result{output_shape};
        // max dimension in axis
Shucai Xiao's avatar
Shucai Xiao committed
48
        auto axis_dim_size = output_shape.lens()[axis];
Shucai Xiao's avatar
Shucai Xiao committed
49
50
51
52
53
        visit_all(result, args[0], args[2])([&](auto output, auto data, auto update) {
            std::copy(data.begin(), data.end(), output.begin());
            args[1].visit([&](auto indices) {
                auto ind_s = indices.get_shape();
                shape_for_each(ind_s, [&](const auto& idx) {
Shucai Xiao's avatar
Shucai Xiao committed
54
                    auto out_idx                        = idx;
Shucai Xiao's avatar
Shucai Xiao committed
55
56
57
                    auto index = indices[ind_s.index(idx)];
                    index = (index < 0) ? index + axis_dim_size : index;
                    out_idx[axis] = index;
Shucai Xiao's avatar
Shucai Xiao committed
58
59
60
61
62
63
64
65
66
67
68
69
70
71
                    output[output_shape.index(out_idx)] = update[ind_s.index(idx)];
                });
            });
        });

        return result;
    }
};

} // namespace op
} // namespace MIGRAPHX_INLINE_NS
} // namespace migraphx

#endif