shape.cpp 10.9 KB
Newer Older
Paul's avatar
Paul committed
1

Paul's avatar
Paul committed
2
3
#include <migraphx/shape.hpp>
#include <migraphx/stringutils.hpp>
4
#include <migraphx/serialize.hpp>
5
#include <migraphx/permutation.hpp>
Paul's avatar
Paul committed
6
7
8
#include <numeric>
#include <algorithm>
#include <functional>
9
#include <unordered_map>
Paul's avatar
Paul committed
10
#include <iostream>
Paul's avatar
Paul committed
11

Paul's avatar
Paul committed
12
namespace migraphx {
Paul's avatar
Paul committed
13
inline namespace MIGRAPHX_INLINE_NS {
Paul's avatar
Paul committed
14

Paul's avatar
Paul committed
15
16
struct shape_impl
{
Paul's avatar
Paul committed
17
18
    static std::shared_ptr<shape_impl> default_shape()
    {
19
        static const std::shared_ptr<shape_impl> result = std::make_shared<shape_impl>();
Paul's avatar
Paul committed
20
21
22
        return result;
    }

Paul Fultz II's avatar
Paul Fultz II committed
23
    shape_impl() : m_type(shape::float_type) {}
Paul's avatar
Paul committed
24

Paul Fultz II's avatar
Paul Fultz II committed
25
26
27
28
    shape_impl(shape::type_t t) : m_type(t), m_lens({1}), m_strides({0}), m_standard(true)
    {
        assert(t != shape::tuple_type);
    }
29
    shape_impl(shape::type_t t, std::vector<int> l)
Paul's avatar
Paul committed
30
31
        : m_type(t), m_lens(std::move(l)), m_standard(true)
    {
Paul Fultz II's avatar
Paul Fultz II committed
32
        assert(t != shape::tuple_type);
Paul's avatar
Paul committed
33
34
35
        this->calculate_strides();
        assert(m_lens.size() == m_strides.size());
    }
36
    shape_impl(shape::type_t t, std::vector<int> l, std::vector<int> s)
Paul's avatar
Paul committed
37
38
        : m_type(t), m_lens(std::move(l)), m_strides(std::move(s))
    {
Paul Fultz II's avatar
Paul Fultz II committed
39
        assert(t != shape::tuple_type);
Paul's avatar
Paul committed
40
        assert(m_lens.size() == m_strides.size());
Khalique's avatar
Khalique committed
41
42
        // assert(std::any_of(m_strides.begin(), m_strides.end(), [](auto x) { return x > 0; }) and
        //        "At least one stride must be non-zero");
43
44
        m_standard = this->elements() == this->element_space() and
                     std::is_sorted(m_strides.rbegin(), m_strides.rend());
Paul's avatar
Paul committed
45
    }
Paul Fultz II's avatar
Paul Fultz II committed
46
47

    shape_impl(const std::vector<shape>& subs) : m_type(shape::tuple_type), m_shapes(subs) {}
Paul's avatar
Paul committed
48
    shape::type_t m_type;
49
50
    std::vector<int> m_lens    = {};
    std::vector<int> m_strides = {};
Paul Fultz II's avatar
Paul Fultz II committed
51
52
    std::vector<shape> m_shapes        = {};
    bool m_standard                    = false;
Paul's avatar
Paul committed
53
54
55
56
57
58
59
60
61
62
63

    void calculate_strides()
    {
        m_strides.clear();
        m_strides.resize(m_lens.size(), 0);
        if(m_strides.empty())
            return;
        m_strides.back() = 1;
        std::partial_sum(m_lens.rbegin(),
                         m_lens.rend() - 1,
                         m_strides.rbegin() + 1,
64
                         std::multiplies<int>());
Paul's avatar
Paul committed
65
66
    }

67
    int element_space() const
Paul's avatar
Paul committed
68
69
70
71
72
73
74
    {
        assert(m_lens.size() == m_strides.size());
        if(m_lens.empty())
            return 0;
        return std::inner_product(m_lens.begin(),
                                  m_lens.end(),
                                  m_strides.begin(),
75
76
77
                                  int{0},
                                  std::plus<int>{},
                                  [](int l, int s) { return (l - 1) * s; }) +
Paul's avatar
Paul committed
78
79
80
               1;
    }

81
    int elements() const
Paul's avatar
Paul committed
82
83
84
85
86
    {
        assert(m_lens.size() == m_strides.size());
        if(m_lens.empty())
            return 0;
        return std::accumulate(
87
            m_lens.begin(), m_lens.end(), int{1}, std::multiplies<int>());
Paul's avatar
Paul committed
88
    }
Paul's avatar
Paul committed
89
};
Paul's avatar
Paul committed
90

91
92
93
94
const std::vector<shape::type_t>& shape::types()
{
    static const std::vector<shape::type_t> result = {
#define MIGRAPHX_GENERATE_TYPE_VECTOR(x, t) x,
Paul Fultz II's avatar
Paul Fultz II committed
95
        MIGRAPHX_SHAPE_VISIT_TYPES(MIGRAPHX_GENERATE_TYPE_VECTOR) tuple_type};
96
97
98
    return result;
}

99
100
101
102
std::string shape::name(shape::type_t t)
{
    switch(t)
    {
Paul Fultz II's avatar
Paul Fultz II committed
103
    case tuple_type: return "tuple_type";
104
105
106
107
108
109
110
111
112
113
114
#define MIGRAPHX_SHAPE_GENERATE_TYPE_NAME_CASE(x, t) \
    case x: return #x;
        MIGRAPHX_SHAPE_VISIT_TYPES(MIGRAPHX_SHAPE_GENERATE_TYPE_NAME_CASE)
#undef MIGRAPHX_SHAPE_GENERATE_TYPE_NAME_CASE
    }
    MIGRAPHX_THROW("Invalid type");
}
std::string shape::cpp_type(shape::type_t t)
{
    switch(t)
    {
Paul Fultz II's avatar
Paul Fultz II committed
115
    case tuple_type: MIGRAPHX_THROW("No C++ type for tuple");
116
117
118
119
120
121
122
123
#define MIGRAPHX_SHAPE_GENERATE_CPP_TYPE_CASE(x, t) \
    case x: return #t;
        MIGRAPHX_SHAPE_VISIT_TYPES(MIGRAPHX_SHAPE_GENERATE_CPP_TYPE_CASE)
#undef MIGRAPHX_SHAPE_GENERATE_CPP_TYPE_CASE
    }
    MIGRAPHX_THROW("Invalid type");
}

Paul's avatar
Paul committed
124
125
126
shape::shape() : impl(shape_impl::default_shape()) {}

shape::shape(type_t t) : impl(std::make_shared<shape_impl>(t)) {}
127
shape::shape(type_t t, std::vector<int> l)
Paul's avatar
Paul committed
128
    : impl(std::make_shared<shape_impl>(t, std::move(l)))
Paul's avatar
Paul committed
129
130
{
}
131
shape::shape(type_t t, std::vector<int> l, std::vector<int> s)
Paul's avatar
Paul committed
132
    : impl(std::make_shared<shape_impl>(t, std::move(l), std::move(s)))
Paul's avatar
Paul committed
133
134
135
{
}

Paul Fultz II's avatar
Paul Fultz II committed
136
137
shape::shape(const std::vector<shape>& subs) : impl(std::make_shared<shape_impl>(subs)) {}

138
shape shape::from_permutation(type_t t,
139
                              const std::vector<int>& l,
140
141
142
143
144
145
146
147
                              const std::vector<int64_t>& perm)
{
    auto new_lens = reorder_dims(l, perm);
    shape result  = reorder_shape({t, new_lens}, invert_permutation(perm));
    assert(result.lens() == l);
    return result;
}

Paul's avatar
Paul committed
148
shape::type_t shape::type() const { return impl->m_type; }
149
150
151
152
const std::vector<int>& shape::lens() const { return impl->m_lens; }
const std::vector<int>& shape::strides() const { return impl->m_strides; }
int shape::elements() const { return impl->elements(); }
int shape::bytes() const
Paul's avatar
Paul committed
153
{
Paul Fultz II's avatar
Paul Fultz II committed
154
155
    if(this->sub_shapes().empty())
    {
156
        int n = 0;
Paul Fultz II's avatar
Paul Fultz II committed
157
158
159
160
161
162
163
        this->visit_type([&](auto as) { n = as.size(); });
        return n * this->element_space();
    }
    else
    {
        return std::accumulate(this->sub_shapes().begin(),
                               this->sub_shapes().end(),
164
                               int{0},
Paul Fultz II's avatar
Paul Fultz II committed
165
166
                               [&](auto x, auto y) { return x + y.bytes(); });
    }
Paul's avatar
Paul committed
167
}
168
int shape::type_size() const
Scott Thornton's avatar
Scott Thornton committed
169
{
170
    int n = 0;
Paul Fultz II's avatar
Paul Fultz II committed
171
172
    if(this->sub_shapes().empty())
        this->visit_type([&](auto as) { n = as.size(); });
Scott Thornton's avatar
Scott Thornton committed
173
174
    return n;
}
175
int shape::index(std::initializer_list<int> l) const
Paul's avatar
Paul committed
176
177
178
{
    assert(l.size() <= this->lens().size());
    assert(this->lens().size() == this->strides().size());
179
    return std::inner_product(l.begin(), l.end(), this->strides().begin(), int{0});
Paul's avatar
Paul committed
180
}
181
int shape::index(const std::vector<int>& l) const
Paul's avatar
Paul committed
182
183
184
{
    assert(l.size() <= this->lens().size());
    assert(this->lens().size() == this->strides().size());
185
    return std::inner_product(l.begin(), l.end(), this->strides().begin(), int{0});
Paul's avatar
Paul committed
186
}
187
int shape::index(int i) const
Paul's avatar
Paul committed
188
189
{
    assert(this->lens().size() == this->strides().size());
Paul's avatar
Paul committed
190
    if(this->standard())
Paul's avatar
Paul committed
191
192
        return i;
    else
Paul's avatar
Paul committed
193
    {
194
195
196
        int s      = 1;
        int result = 0;
        for(int j = 0; j < this->lens().size(); j++)
Paul's avatar
Paul committed
197
        {
198
199
200
201
            const int k      = this->lens().size() - j - 1;
            const int stride = this->strides()[k];
            const int len    = this->lens()[k];
            const int idx    = (i % (s * len)) / s;
Paul's avatar
Paul committed
202
203
204
205
206
            result += stride * idx;
            s *= len;
        }
        return result;
    }
Paul's avatar
Paul committed
207
}
208

209
std::vector<int> shape::multi(int i) const
210
211
212
{
    assert(this->standard());

213
    std::vector<int> indices(lens().size());
214
215
216
217
218
    multi_copy(i, indices.data(), indices.data() + lens().size());

    return indices;
}

219
void shape::multi_copy(int i, int* start, const int* end) const
220
221
222
223
{
    assert(this->standard());
    (void)end;
    assert(lens().size() <= (end - start));
224
    std::transform(strides().begin(),
Shucai Xiao's avatar
Shucai Xiao committed
225
226
                   strides().end(),
                   lens().begin(),
227
                   start,
228
                   [&](int stride, int len) {
Shucai Xiao's avatar
Shucai Xiao committed
229
230
231
                       assert(len > 0 and stride > 0);
                       return (i / stride) % len;
                   });
232
233
}

Paul Fultz II's avatar
Paul Fultz II committed
234
235
236
237
bool shape::packed() const
{
    return this->sub_shapes().empty() and this->elements() == this->element_space();
}
Paul's avatar
Paul committed
238

Paul's avatar
Paul committed
239
240
bool shape::transposed() const
{
241
242
243
    if(this->broadcasted())
    {
        // TODO: Use a filter_iterator instead
244
        std::vector<int> s;
245
246
247
248
        s.reserve(this->strides().size());
        std::copy_if(this->strides().begin(),
                     this->strides().end(),
                     std::back_inserter(s),
249
                     [](int x) { return x != 0; });
250
251
252
253
254
255
        return not std::is_sorted(s.rbegin(), s.rend());
    }
    else
    {
        return not std::is_sorted(this->strides().rbegin(), this->strides().rend());
    }
Paul's avatar
Paul committed
256
}
Paul's avatar
Paul committed
257
258
259
260

bool shape::broadcasted() const
{
    assert(this->lens().size() == this->strides().size());
Paul's avatar
Paul committed
261
262
    return std::accumulate(this->strides().begin(),
                           this->strides().end(),
263
264
                           int{1},
                           std::multiplies<int>()) == 0;
Paul's avatar
Paul committed
265
266
}

Khalique's avatar
Khalique committed
267
268
269
270
bool shape::scalar() const
{
    assert(this->lens().size() == this->strides().size());
    // if any stride > 0, then accumulate will return false
Paul Fultz II's avatar
Paul Fultz II committed
271
    return this->sub_shapes().empty() and
272
           std::accumulate(this->strides().begin(), this->strides().end(), int(0)) == 0;
Khalique's avatar
Khalique committed
273
274
}

Paul's avatar
Paul committed
275
bool shape::standard() const { return impl->m_standard; }
Paul's avatar
Paul committed
276

277
278
279
280
281
282
283
284
shape shape::normalize_standard() const
{
    if(this->standard())
        return {this->type(), this->lens()};
    else
        return *this;
}

285
shape shape::with_lens(type_t t, const std::vector<int>& l) const
286
287
288
289
290
291
{
    assert(l.size() == this->lens().size());
    auto perm = find_permutation(*this);
    return shape::from_permutation(t, l, perm);
}

292
shape shape::with_lens(const std::vector<int>& l) const
293
294
295
296
{
    return this->with_lens(this->type(), l);
}

297
int shape::element_space() const { return impl->element_space(); }
Paul's avatar
Paul committed
298

299
std::string shape::type_string() const { return name(this->type()); }
Paul's avatar
Paul committed
300

Paul's avatar
Paul committed
301
302
bool operator==(const shape& x, const shape& y)
{
Paul Fultz II's avatar
Paul Fultz II committed
303
304
    return x.impl == y.impl or (x.type() == y.type() and x.lens() == y.lens() and
                                x.strides() == y.strides() and x.sub_shapes() == y.sub_shapes());
Paul's avatar
Paul committed
305
}
Paul's avatar
Paul committed
306
bool operator!=(const shape& x, const shape& y) { return !(x == y); }
Paul's avatar
Paul committed
307

Paul's avatar
Paul committed
308
309
std::ostream& operator<<(std::ostream& os, const shape& x)
{
Paul Fultz II's avatar
Paul Fultz II committed
310
311
312
313
314
315
316
317
318
319
    if(x.sub_shapes().empty())
    {
        os << x.type_string() << ", ";
        os << "{" << to_string_range(x.lens()) << "}, ";
        os << "{" << to_string_range(x.strides()) << "}";
    }
    else
    {
        os << "[" << to_string_range(x.sub_shapes()) << "]";
    }
Paul's avatar
Paul committed
320
321
322
    return os;
}

323
324
shape::type_t shape::parse_type(const std::string& s)
{
325
    static const std::unordered_map<std::string, shape::type_t> m = {
326
#define MIGRAPHX_SHAPE_GENERATE_TYPE_STRING_MAP(x, t) {#x, x}, {#t, x},
Paul Fultz II's avatar
Paul Fultz II committed
327
328
329
        MIGRAPHX_SHAPE_VISIT_TYPES(MIGRAPHX_SHAPE_GENERATE_TYPE_STRING_MAP){"tuple_type",
                                                                            tuple_type},
        {"tuple", tuple_type}};
330
331
332
    return m.at(s);
}

Paul Fultz II's avatar
Paul Fultz II committed
333
334
const std::vector<shape>& shape::sub_shapes() const { return impl->m_shapes; }

335
336
337
void migraphx_to_value(value& v, const shape& s)
{
    value result;
Paul Fultz II's avatar
Paul Fultz II committed
338
339
340
341
342
    result["type"]       = migraphx::to_value(s.type_string());
    result["lens"]       = migraphx::to_value(s.lens());
    result["strides"]    = migraphx::to_value(s.strides());
    result["sub_shapes"] = migraphx::to_value(s.sub_shapes());
    v                    = result;
343
344
345
}
void migraphx_from_value(const value& v, shape& s)
{
Paul Fultz II's avatar
Paul Fultz II committed
346
347
348
349
350
351
352
353
    auto t = v.at("type").get_string();
    if(t == "tuple_type")
    {
        s = shape{migraphx::from_value<std::vector<migraphx::shape>>(v.at("sub_shapes"))};
    }
    else
    {
        s = shape{shape::parse_type(t),
354
355
                  v.at("lens").to_vector<int>(),
                  v.at("strides").to_vector<int>()};
Paul Fultz II's avatar
Paul Fultz II committed
356
    }
357
358
}

Paul's avatar
Paul committed
359
} // namespace MIGRAPHX_INLINE_NS
Paul's avatar
Paul committed
360
} // namespace migraphx