"src/include/vscode:/vscode.git/clone" did not exist on "c425d1a7232ac843dd6d9cb65e3cd56ecc47a85d"
operators.hpp 31.4 KB
Newer Older
Paul's avatar
Paul committed
1
2
#ifndef MIGRAPHX_GUARD_OPERATORS_HPP
#define MIGRAPHX_GUARD_OPERATORS_HPP
Paul's avatar
Paul committed
3

4
#include <array>
Paul's avatar
Paul committed
5
6
7
8
#include <migraphx/operation.hpp>
#include <migraphx/check_shapes.hpp>
#include <migraphx/stringutils.hpp>
#include <migraphx/streamutils.hpp>
9
10
#include <migraphx/literal.hpp>
#include <migraphx/shape_for_each.hpp>
Paul's avatar
Paul committed
11
#include <migraphx/config.hpp>
Paul's avatar
Paul committed
12
#include <cmath>
Paul's avatar
Paul committed
13
#include <utility>
Paul's avatar
Paul committed
14

Paul's avatar
Paul committed
15
namespace migraphx {
Paul's avatar
Paul committed
16
inline namespace MIGRAPHX_INLINE_NS {
17
namespace op {
Paul's avatar
Paul committed
18

Paul's avatar
Paul committed
19
20
struct not_computable
{
Paul's avatar
Paul committed
21
    argument compute(const shape&, const std::vector<argument>&) const
Paul's avatar
Paul committed
22
    {
Paul's avatar
Paul committed
23
        MIGRAPHX_THROW("not computable");
Paul's avatar
Paul committed
24
    }
Paul's avatar
Paul committed
25
26
};

27
28
struct batch_norm_inference
{
29
30
    float epsilon  = 1.0e-6f;
    float momentum = 0.9f;
31
32
33

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

34
35
36
37
38
39
40
41
    enum bn_infer_mode_t
    {
        per_activation,
        spatial,
    };

    bn_infer_mode_t bn_mode = spatial;

Paul's avatar
Paul committed
42
43
44
45
    template <class Self, class F>
    static auto reflect(Self& self, F f)
    {
        return pack(
Paul's avatar
Paul committed
46
            f(self.epsilon, "epsilon"), f(self.momentum, "momentum"), f(self.bn_mode, "bn_mode"));
Paul's avatar
Paul committed
47
    }
48

49
50
51
52
53
54
55
    shape compute_shape(std::vector<shape> inputs) const
    {
        check_shapes{inputs, *this}.has(5);
        return inputs.front();
    }
};

Paul's avatar
Paul committed
56
struct convolution
Paul's avatar
Paul committed
57
{
Paul's avatar
Paul committed
58
59
60
    std::array<std::size_t, 2> padding  = {{0, 0}};
    std::array<std::size_t, 2> stride   = {{1, 1}};
    std::array<std::size_t, 2> dilation = {{1, 1}};
Paul's avatar
Paul committed
61
62
63
64
65
66
67
    enum padding_mode_t
    {
        default_, // NOLINT
        same,
        valid
    };
    padding_mode_t padding_mode = default_;
Khalique's avatar
Khalique committed
68
    int group                   = 1;
Paul's avatar
Paul committed
69
70
71
72

    template <class Self, class F>
    static auto reflect(Self& self, F f)
    {
Paul's avatar
Paul committed
73
74
75
        return pack(f(self.padding, "padding"),
                    f(self.stride, "stride"),
                    f(self.dilation, "dilation"),
Khalique's avatar
Khalique committed
76
77
                    f(self.padding_mode, "padding_mode"),
                    f(self.group, "group"));
Paul's avatar
Paul committed
78
79
    }

Paul's avatar
Paul committed
80
    std::string name() const { return "convolution"; }
Paul's avatar
Paul committed
81
82
    shape compute_shape(std::vector<shape> inputs) const
    {
Paul's avatar
Paul committed
83
        check_shapes{inputs, *this}.has(2).same_type().same_ndims().only_dims(4);
Paul's avatar
Paul committed
84

Paul's avatar
Paul committed
85
        const shape& input   = inputs.at(0);
Paul's avatar
Paul committed
86
        const shape& weights = inputs.at(1);
Paul's avatar
Paul committed
87
        auto t               = input.type();
Paul's avatar
Paul committed
88
89
        if(padding_mode == default_)
        {
Paul's avatar
Paul committed
90
91
92
            return {t,
                    {
                        input.lens()[0],
Khalique's avatar
Khalique committed
93
                        weights.lens()[0],
Paul's avatar
Paul committed
94
95
96
97
98
99
100
101
102
103
104
105
106
                        std::size_t(std::max<std::ptrdiff_t>(
                            1,
                            (input.lens()[2] - (1 + dilation[0] * (weights.lens()[2] - 1)) +
                             2 * padding[0]) /
                                    stride[0] +
                                1)),
                        std::size_t(std::max<std::ptrdiff_t>(
                            1,
                            (input.lens()[3] - (1 + dilation[1] * (weights.lens()[3] - 1)) +
                             2 * padding[1]) /
                                    stride[1] +
                                1)),
                    }};
Paul's avatar
Paul committed
107
108
109
110
111
        }
        else if(padding_mode == same)
        {
            return {t,
                    {input.lens()[0],
Khalique's avatar
Khalique committed
112
                     weights.lens()[0],
Paul's avatar
Paul committed
113
114
115
116
117
118
119
120
121
122
                     static_cast<std::size_t>(
                         std::ceil(static_cast<double>(input.lens()[2]) / stride[0])),
                     static_cast<std::size_t>(
                         std::ceil(static_cast<double>(input.lens()[3]) / stride[1]))}};
        }
        else if(padding_mode == valid)
        {
            return {
                t,
                {input.lens()[0],
Khalique's avatar
Khalique committed
123
                 weights.lens()[0],
Paul's avatar
Paul committed
124
125
126
127
128
129
130
                 static_cast<std::size_t>(std::ceil(
                     static_cast<double>(input.lens()[2] - weights.lens()[2] + 1) / stride[0])),
                 static_cast<std::size_t>(std::ceil(
                     static_cast<double>(input.lens()[3] - weights.lens()[3] + 1) / stride[1]))}};
        }
        else
        {
Paul's avatar
Paul committed
131
            MIGRAPHX_THROW("Invalid padding mode");
Paul's avatar
Paul committed
132
        }
Paul's avatar
Paul committed
133
134
135
    }
};

Scott Thornton's avatar
Scott Thornton committed
136
137
struct im2col
{
Scott Thornton's avatar
Scott Thornton committed
138
139
140
141
142
143
144
145
146
    std::array<std::size_t, 2> padding  = {{0, 0}};
    std::array<std::size_t, 2> stride   = {{1, 1}};
    std::array<std::size_t, 2> dilation = {{1, 1}};
    enum padding_mode_t
    {
        default_, // NOLINT
        same,
        valid
    };
Paul's avatar
Paul committed
147
148
149
150
151
    padding_mode_t padding_mode = default_;

    template <class Self, class F>
    static auto reflect(Self& self, F f)
    {
Paul's avatar
Paul committed
152
153
154
155
        return pack(f(self.padding, "padding"),
                    f(self.stride, "stride"),
                    f(self.dilation, "dilation"),
                    f(self.padding_mode, "padding_mode"));
Paul's avatar
Paul committed
156
    }
Scott Thornton's avatar
Scott Thornton committed
157
158
159
160
161

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

    shape compute_shape(std::vector<shape> inputs) const
    {
Scott Thornton's avatar
Scott Thornton committed
162
163
164
        auto input          = inputs[0];
        auto weights        = inputs[1];
        auto batch_size     = input.lens()[0];
Scott Thornton's avatar
Scott Thornton committed
165
        auto input_channels = weights.lens()[1];
Scott Thornton's avatar
Scott Thornton committed
166
167
        auto kernel_height  = weights.lens()[2];
        auto kernel_width   = weights.lens()[3];
Scott Thornton's avatar
Scott Thornton committed
168
        check_shapes{inputs, *this}.has(2);
Scott Thornton's avatar
Scott Thornton committed
169
        if(batch_size != 1)
Paul's avatar
Paul committed
170
            MIGRAPHX_THROW("im2col only support batch_size 1");
Scott Thornton's avatar
Scott Thornton committed
171
        auto output_height = std::size_t(std::max<std::ptrdiff_t>(
Scott Thornton's avatar
Scott Thornton committed
172
173
174
            1,
            (input.lens()[2] - (1 + dilation[0] * (kernel_height - 1)) + 2 * padding[0]) /
                    stride[0] +
Scott Thornton's avatar
Scott Thornton committed
175
                1));
Scott Thornton's avatar
Scott Thornton committed
176
177
178
179
        auto output_width  = std::size_t(std::max<std::ptrdiff_t>(
            1,
            (input.lens()[3] - (1 + dilation[1] * (kernel_width - 1)) + 2 * padding[1]) /
                    stride[1] +
Scott Thornton's avatar
Scott Thornton committed
180
                1));
Scott Thornton's avatar
Scott Thornton committed
181
182
        auto channels_col  = kernel_height * kernel_width * input_channels;
        return {input.type(), {output_height * output_width, channels_col}};
Scott Thornton's avatar
Scott Thornton committed
183
184
185
    }
};

Paul's avatar
Paul committed
186
struct pooling
Paul's avatar
Paul committed
187
{
Paul's avatar
Paul committed
188
    std::string mode                   = "average";
Paul's avatar
Paul committed
189
190
191
    std::array<std::size_t, 2> padding = {{0, 0}};
    std::array<std::size_t, 2> stride  = {{1, 1}};
    std::array<std::size_t, 2> lengths = {{1, 1}};
Paul's avatar
Paul committed
192
193
194
195

    template <class Self, class F>
    static auto reflect(Self& self, F f)
    {
Paul's avatar
Paul committed
196
197
198
199
        return pack(f(self.mode, "mode"),
                    f(self.padding, "padding"),
                    f(self.stride, "stride"),
                    f(self.lengths, "lengths"));
Paul's avatar
Paul committed
200
201
    }

Paul's avatar
Paul committed
202
    std::string name() const { return "pooling"; }
Scott Thornton's avatar
Scott Thornton committed
203

Paul's avatar
Paul committed
204
205
    shape compute_shape(std::vector<shape> inputs) const
    {
Paul's avatar
Paul committed
206
        check_shapes{inputs, *this}.has(1).only_dims(4);
Paul's avatar
Paul committed
207

Paul's avatar
Paul committed
208
        const shape& input = inputs.at(0);
Paul's avatar
Paul committed
209
        auto t             = input.type();
Paul's avatar
Paul committed
210

Paul's avatar
Paul committed
211
212
        assert(lengths[0] <= (input.lens()[2] + 2 * padding[0]));
        assert(lengths[1] <= (input.lens()[3] + 2 * padding[1]));
Paul's avatar
Paul committed
213

Scott Thornton's avatar
Scott Thornton committed
214
215
216
217
218
219
        return {t,
                {
                    input.lens()[0],
                    input.lens()[1],
                    std::size_t(std::max<std::ptrdiff_t>(
                        1,
Paul's avatar
Paul committed
220
                        std::ptrdiff_t(std::floor((input.lens()[2] + 2 * padding[0] - lengths[0]) /
Paul's avatar
Paul committed
221
                                                  static_cast<float>(stride[0]))) +
Scott Thornton's avatar
Scott Thornton committed
222
223
224
                            1)),
                    std::size_t(std::max<std::ptrdiff_t>(
                        1,
Paul's avatar
Paul committed
225
                        std::ptrdiff_t(std::floor((input.lens()[3] + 2 * padding[1] - lengths[1]) /
Paul's avatar
Paul committed
226
                                                  static_cast<float>(stride[1]))) +
Scott Thornton's avatar
Scott Thornton committed
227
228
                            1)),
                }};
Paul's avatar
Paul committed
229
230
231
    }
};

Khalique's avatar
Khalique committed
232
233
234
235
236
237
238
239
240
struct leaky_relu
{
    std::string name() const { return "leaky_relu"; }
    float alpha;
    shape compute_shape(std::vector<shape> inputs) const
    {
        check_shapes{inputs, *this}.has(1);
        return inputs.front();
    }
Khalique's avatar
Khalique committed
241
242
243

    template <class Self, class F>
    static auto reflect(Self& self, F f)
Khalique's avatar
Khalique committed
244
    {
Khalique's avatar
Khalique committed
245
        return pack(f(self.alpha, "alpha"));
Khalique's avatar
Khalique committed
246
247
248
249
250
251
252
253
254
255
256
257
    }
};

struct elu
{
    std::string name() const { return "elu"; }
    float alpha;
    shape compute_shape(std::vector<shape> inputs) const
    {
        check_shapes{inputs, *this}.has(1);
        return inputs.front();
    }
Khalique's avatar
Khalique committed
258
259
260

    template <class Self, class F>
    static auto reflect(Self& self, F f)
Khalique's avatar
Khalique committed
261
    {
Khalique's avatar
Khalique committed
262
        return pack(f(self.alpha, "alpha"));
Khalique's avatar
Khalique committed
263
    }
Khalique's avatar
Khalique committed
264
265
};

266
267
268
struct transpose
{
    std::vector<int64_t> dims;
Paul's avatar
Paul committed
269
270
271
272

    template <class Self, class F>
    static auto reflect(Self& self, F f)
    {
Paul's avatar
Paul committed
273
        return pack(f(self.dims, "dims"));
Paul's avatar
Paul committed
274
275
    }

276
277
278
    std::string name() const { return "transpose"; }
    shape compute_shape(std::vector<shape> inputs) const
    {
Paul's avatar
Paul committed
279
        check_shapes{inputs, *this}.has(1);
280
        auto input         = inputs.at(0);
281
        auto input_lens    = input.lens();
282
283
        auto input_strides = input.strides();
        auto t             = input.type();
Paul's avatar
Paul committed
284
285
        if(dims.size() != input_lens.size())
        {
Paul's avatar
Paul committed
286
            MIGRAPHX_THROW("Permutation has wrong number of axes");
287
288
289
        }
        std::vector<int64_t> axes(dims.size());
        std::iota(axes.begin(), axes.end(), 0);
Paul's avatar
Paul committed
290
291
        if(!std::is_permutation(axes.begin(), axes.end(), dims.begin()))
        {
Paul's avatar
Paul committed
292
            MIGRAPHX_THROW("Invalid permutation");
293
        }
294
295
        std::vector<size_t> output_lens(input_lens.size());
        std::vector<size_t> output_strides(input_lens.size());
Paul's avatar
Paul committed
296
        for(std::size_t i = 0; i < output_lens.size(); i++)
Paul's avatar
Paul committed
297
298
        {
            output_lens[i]    = input_lens[dims[i]];
299
300
            output_strides[i] = input_strides[dims[i]];
        }
301
        return {t, output_lens, output_strides};
302
    }
Paul's avatar
Paul committed
303
    argument compute(shape output_shape, std::vector<argument> args) const
Paul's avatar
Paul committed
304
    {
Paul's avatar
Paul committed
305
        return {std::move(output_shape), std::move(args.front().data)};
Paul's avatar
Paul committed
306
    }
Paul's avatar
Paul committed
307
    int output_alias(const std::vector<shape>&) const { return 0; }
308
309
};

wsttiger's avatar
fixes  
wsttiger committed
310
311
312
313
314
315
/// The contiguous operator takes a non-standard input tensor and returns
/// the same tensor but in standard form. For example, if input tensor A which has lens = (4,5)
/// is first transposed, i.e. lens = (5,4), this tensor's data layout remained the same
/// during the transpose operation; only it's shape lengths and strides were changed.
/// This leaves the tensor in a non-standard form. The contiguous operator copies the
/// underlying data such that resulting tensor is returned to a standard form.
Paul's avatar
Paul committed
316
struct contiguous
317
318
319
320
{
    std::string name() const { return "contiguous"; }
    shape compute_shape(std::vector<shape> inputs) const
    {
Paul's avatar
Paul committed
321
        check_shapes{inputs, *this}.has(1);
Paul's avatar
Paul committed
322
323
        auto lens = inputs.at(0).lens();
        auto t    = inputs.at(0).type();
324
325
326
327
        return {t, lens};
    }
};

328
329
330
331
struct concat
{
    std::size_t axis = 0;
    std::string name() const { return "concat"; }
332
    std::vector<std::size_t> compute_offsets(const shape& output_shape,
Paul's avatar
Paul committed
333
                                             const std::vector<argument>& args) const
334
335
336
337
338
339
340
341
342
343
344
    {
        std::vector<std::size_t> offsets;
        std::vector<std::size_t> offset(args[0].get_shape().lens().size(), 0);
        offset[axis] = 0;
        for(const auto& arg : args)
        {
            offsets.push_back(output_shape.index(offset));
            offset[axis] += arg.get_shape().lens()[axis];
        }
        return offsets;
    }
345
346
    shape compute_shape(std::vector<shape> inputs) const
    {
Scott Thornton's avatar
Scott Thornton committed
347
        if(inputs.empty())
348
        {
Paul's avatar
Paul committed
349
            MIGRAPHX_THROW("Number of input tensors should exceed 0");
350
351
352
        }

        const auto& first_shape_lens = inputs.front().lens();
Scott Thornton's avatar
Scott Thornton committed
353
354
355
356
357
358
359
360
361
        const auto& type             = inputs.front().type();
        for(std::size_t l = 0; l < first_shape_lens.size(); l++)
        {
            if(l != axis)
            {
                if(!std::all_of(inputs.begin(), inputs.end(), [&](auto s) {
                       return s.lens()[l] == first_shape_lens[l];
                   }))
                {
Paul's avatar
Paul committed
362
                    MIGRAPHX_THROW("Non-axis dimensions should match");
363
364
365
366
                }
            }
        }
        std::size_t new_dim_axis = 0;
Scott Thornton's avatar
Scott Thornton committed
367
        for(const auto& input : inputs)
368
369
370
371
372
373
374
375
376
        {
            const auto& lens = input.lens();
            new_dim_axis += lens[axis];
        }
        std::vector<std::size_t> new_lens;
        std::copy(first_shape_lens.begin(), first_shape_lens.end(), std::back_inserter(new_lens));
        new_lens[axis] = new_dim_axis;
        return {type, new_lens};
    }
Paul's avatar
Paul committed
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
    argument compute(const shape& output_shape, std::vector<argument> args) const
    {
        argument result{output_shape};
        std::vector<std::size_t> coffsets = compute_offsets(output_shape, args);
        for(std::size_t l = 0; l < args.size(); l++)
        {
            auto argl             = args[l];
            std::size_t nelements = argl.get_shape().elements();
            visit_all(result, argl)([&](auto output, auto input) {
                auto slice_shape =
                    shape{output_shape.type(), input.get_shape().lens(), output_shape.strides()};
                auto slice = make_view(slice_shape, output.data() + coffsets[l]);
                // cppcheck-suppress useStlAlgorithm
                for(std::size_t i = 0; i < nelements; i++)
                {
                    slice[i] = input[i];
                }
            });
        }
        return result;
    }
Paul's avatar
Paul committed
398
    int output_alias(const std::vector<shape>&) const { return 0; }
399
400
};

401
402
403
404
405
struct slice
{
    std::vector<int64_t> axes;
    std::vector<int64_t> starts;
    std::vector<int64_t> ends;
Paul's avatar
Paul committed
406
407
408
409

    template <class Self, class F>
    static auto reflect(Self& self, F f)
    {
Paul's avatar
Paul committed
410
        return pack(f(self.axes, "axes"), f(self.starts, "starts"), f(self.ends, "ends"));
Paul's avatar
Paul committed
411
412
    }

413
    std::string name() const { return "slice"; }
Scott Thornton's avatar
Scott Thornton committed
414
415

    auto fix_index(const std::vector<std::size_t>& lens, std::size_t axis, int64_t index) const
416
    {
Scott Thornton's avatar
Scott Thornton committed
417
        int64_t r = std::min(index, static_cast<int64_t>(lens[axis]));
Scott Thornton's avatar
Scott Thornton committed
418
419
        if(r < 0)
            r += lens[axis];
Scott Thornton's avatar
Scott Thornton committed
420
        return std::size_t(r);
Scott Thornton's avatar
Scott Thornton committed
421
422
423
424
425
426
427
    }

    auto compute_offset(const shape& s) const
    {
        const std::vector<std::size_t>& lens    = s.lens();
        const std::vector<std::size_t>& strides = s.strides();
        auto offset                             = 0;
Scott Thornton's avatar
Scott Thornton committed
428
        if(!axes.empty())
Scott Thornton's avatar
Scott Thornton committed
429
        {
Scott Thornton's avatar
Scott Thornton committed
430
431
432
433
434
            for(std::size_t i = 0; i < axes.size(); i++)
            {
                auto axis = axes[i];
                offset += fix_index(lens, axis, starts[i]) * strides[axis];
            }
435
        }
Scott Thornton's avatar
Scott Thornton committed
436
437
        else
        {
Scott Thornton's avatar
Scott Thornton committed
438
439
440
441
            for(std::size_t axis = 0; axis < lens.size(); axis++)
            {
                offset += fix_index(lens, axis, starts[axis]) * strides[axis];
            }
442
        }
Scott Thornton's avatar
Scott Thornton committed
443
444
445
446
447
        return offset;
    }

    shape compute_shape(std::vector<shape> inputs) const
    {
Scott Thornton's avatar
Scott Thornton committed
448
449
450
451
        auto input_shape        = inputs[0];
        auto t                  = input_shape.type();
        const auto& old_lens    = input_shape.lens();
        const auto& old_strides = input_shape.strides();
Scott Thornton's avatar
Scott Thornton committed
452
        if(starts.size() != axes.size() || axes.size() != ends.size())
Scott Thornton's avatar
Scott Thornton committed
453
        {
Paul's avatar
Paul committed
454
            MIGRAPHX_THROW("inconsistent sizes");
455
        }
Scott Thornton's avatar
Scott Thornton committed
456
457
        std::vector<std::size_t> new_lens = old_lens;
        for(std::size_t i = 0; i < axes.size(); i++)
Scott Thornton's avatar
Scott Thornton committed
458
        {
Scott Thornton's avatar
Scott Thornton committed
459
460
461
            auto axis = axes[i];
            new_lens[axis] =
                fix_index(old_lens, axis, ends[i]) - fix_index(old_lens, axis, starts[i]);
462
463
464
        }
        return shape{t, new_lens, old_strides};
    }
Paul's avatar
Paul committed
465
    argument compute(shape output_shape, std::vector<argument> args) const
466
    {
Scott Thornton's avatar
Scott Thornton committed
467
468
469
        auto input  = args[0];
        auto offset = compute_offset(input.get_shape()) * output_shape.type_size();
        return {std::move(output_shape), [=] { return input.data() + offset; }};
470
    }
Paul's avatar
Paul committed
471
    int output_alias(const std::vector<shape>&) const { return 0; }
472
473
474
475
476
};

struct squeeze
{
    std::vector<int64_t> axes;
Paul's avatar
Paul committed
477
478
479
480

    template <class Self, class F>
    static auto reflect(Self& self, F f)
    {
Paul's avatar
Paul committed
481
        return pack(f(self.axes, "axes"));
Paul's avatar
Paul committed
482
483
    }

484
485
486
487
    std::string name() const { return "squeeze"; }
    shape compute_shape(std::vector<shape> inputs) const
    {
        auto input_shape = inputs[0];
Scott Thornton's avatar
Scott Thornton committed
488
489
        auto type        = input_shape.type();
        auto old_lens    = input_shape.lens();
wsttiger's avatar
wsttiger committed
490
491
        if(std::any_of(
               axes.begin(), axes.end(), [&](auto axis) { return input_shape.lens()[axis] != 1; }))
Scott Thornton's avatar
Scott Thornton committed
492
        {
Paul's avatar
Paul committed
493
            MIGRAPHX_THROW("squeeze axis dimension should be equal to 1");
494
495
        }
        std::vector<std::size_t> new_lens;
Scott Thornton's avatar
Scott Thornton committed
496
        if(axes.empty())
Scott Thornton's avatar
Scott Thornton committed
497
        {
wsttiger's avatar
wsttiger committed
498
499
500
501
            std::copy_if(old_lens.begin(),
                         old_lens.end(),
                         std::back_inserter(new_lens),
                         [](auto len) { return len != 1; });
502
        }
Scott Thornton's avatar
Scott Thornton committed
503
504
505
506
507
508
        else
        {
            for(std::size_t i = 0; i < old_lens.size(); i++)
            {
                if(std::find(axes.begin(), axes.end(), i) == axes.end())
                {
509
510
511
512
513
514
                    new_lens.push_back(old_lens[i]);
                }
            }
        }
        return shape{type, new_lens};
    }
Paul's avatar
Paul committed
515
    argument compute(shape output_shape, std::vector<argument> args) const
516
517
    {
        return {std::move(output_shape), std::move(args.front().data)};
Scott Thornton's avatar
Scott Thornton committed
518
    }
Paul's avatar
Paul committed
519
    int output_alias(const std::vector<shape>&) const { return 0; }
520
521
522
523
524
};

struct unsqueeze
{
    std::vector<int64_t> axes;
Paul's avatar
Paul committed
525
526
527
528

    template <class Self, class F>
    static auto reflect(Self& self, F f)
    {
Paul's avatar
Paul committed
529
        return pack(f(self.axes, "axes"));
Paul's avatar
Paul committed
530
531
    }

532
533
534
    std::string name() const { return "unsqueeze"; }
    shape compute_shape(std::vector<shape> inputs) const
    {
Scott Thornton's avatar
Scott Thornton committed
535
536
537
        auto input_shape     = inputs[0];
        auto type            = input_shape.type();
        auto old_lens        = input_shape.lens();
538
539
540
        std::size_t new_size = old_lens.size() + axes.size();
        std::vector<std::size_t> new_lens(new_size);
        std::size_t p = 0;
Scott Thornton's avatar
Scott Thornton committed
541
542
543
544
        for(std::size_t i = 0; i < new_size; i++)
        {
            if(std::find(axes.begin(), axes.end(), i) != axes.end())
            {
545
                new_lens[i] = 1;
Scott Thornton's avatar
Scott Thornton committed
546
547
548
            }
            else
            {
549
550
551
552
553
                new_lens[i] = old_lens[p++];
            }
        }
        return shape{type, new_lens};
    }
Paul's avatar
Paul committed
554
    argument compute(shape output_shape, std::vector<argument> args) const
555
556
557
    {
        return {std::move(output_shape), std::move(args.front().data)};
    }
Paul's avatar
Paul committed
558
    int output_alias(const std::vector<shape>&) const { return 0; }
559
560
};

Paul's avatar
Paul committed
561
562
563
struct reshape
{
    std::vector<int64_t> dims;
Paul's avatar
Paul committed
564
565
566
567

    template <class Self, class F>
    static auto reflect(Self& self, F f)
    {
Paul's avatar
Paul committed
568
        return pack(f(self.dims, "dims"));
Paul's avatar
Paul committed
569
570
    }

Paul's avatar
Paul committed
571
    std::string name() const { return "reshape"; }
Paul's avatar
Paul committed
572
573
    shape compute_shape(std::vector<shape> inputs) const
    {
Paul's avatar
Paul committed
574
        check_shapes{inputs, *this}.has(1);
Paul's avatar
Paul committed
575
576
        auto&& idims = inputs.front().lens();
        std::vector<std::size_t> rdims(dims.begin(), dims.end());
577
578
        auto n_neg_dims = std::count(dims.begin(), dims.end(), -1);
        if(n_neg_dims > 1)
Paul's avatar
Paul committed
579
            MIGRAPHX_THROW("Dimensions for reshape can only have one -1 dim");
Paul's avatar
Paul committed
580
        for(std::size_t i = 0; i < dims.size(); i++)
Paul's avatar
Paul committed
581
582
583
584
        {
            if(dims[i] == 0)
                rdims[i] = idims[i];
        }
585
586
587
588
589
590
591
592
593
594
595
        if(n_neg_dims > 0)
        {
            size_t missing_dim =
                -inputs.front().elements() /
                std::accumulate(rdims.begin(), rdims.end(), 1, std::multiplies<int64_t>());
            for(std::size_t i = 0; i < rdims.size(); i++)
            {
                if(dims[i] == -1)
                    rdims[i] = missing_dim;
            }
        }
Paul's avatar
Paul committed
596
597
598
        if(dims.back() == -1)
        {
            rdims.pop_back();
Paul's avatar
Paul committed
599
            std::copy(idims.begin() + rdims.size(), idims.end(), std::back_inserter(rdims));
Paul's avatar
Paul committed
600
        }
Scott Thornton's avatar
Scott Thornton committed
601
        shape s{inputs.front().type(), rdims};
Paul's avatar
Paul committed
602
        if(s.elements() != inputs.front().elements())
Paul's avatar
Paul committed
603
            MIGRAPHX_THROW("Wrong number of elements for reshape");
Scott Thornton's avatar
Scott Thornton committed
604
        return s;
Paul's avatar
Paul committed
605
    }
Paul's avatar
Paul committed
606
    argument compute(shape output_shape, std::vector<argument> args) const
Paul's avatar
Paul committed
607
    {
Paul's avatar
Paul committed
608
        return {std::move(output_shape), std::move(args.front().data)};
Paul's avatar
Paul committed
609
    }
Paul's avatar
Paul committed
610
    int output_alias(const std::vector<shape>&) const { return 0; }
Paul's avatar
Paul committed
611
612
};

Paul's avatar
Paul committed
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
struct as_shape
{
    shape s;
    template <class Self, class F>
    static auto reflect(Self& self, F f)
    {
        return pack(f(self.s, "shape"));
    }

    std::string name() const { return "as_shape"; }
    shape compute_shape(const std::vector<shape>& inputs) const
    {
        check_shapes{inputs, *this}.has(1).standard();
        assert(inputs.front().elements() == s.elements());
        return s;
    }
    argument compute(shape output_shape, std::vector<argument> args) const
    {
        return {std::move(output_shape), std::move(args.front().data)};
    }
    int output_alias(const std::vector<shape>&) const { return 0; }
};

636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
struct gather
{
    std::size_t axis = 0;
    std::string name() const { return "gather"; }

    shape compute_shape(std::vector<shape> inputs) const
    {
        check_shapes{inputs, *this}.has(2);
        auto lens = inputs[0].lens();
        if(axis >= lens.size())
        {
            MIGRAPHX_THROW("Gather, axis is out of range.");
        }
        auto type  = inputs[0].type();
        lens[axis] = inputs[1].elements();

        return {type, lens};
    }

    template <class T>
Shucai Xiao's avatar
Shucai Xiao committed
656
657
658
659
    void compute_index(const T& out_idx,
                       const std::vector<std::size_t>& vec_indices,
                       const std::size_t max_dim,
                       T& in_idx) const
660
    {
Shucai Xiao's avatar
Shucai Xiao committed
661
        in_idx          = out_idx;
Shucai Xiao's avatar
Shucai Xiao committed
662
        std::size_t idx = vec_indices.at(out_idx[axis]);
663
664
        if(idx >= max_dim)
        {
665
            MIGRAPHX_THROW("Gather: indices are out of range in input tensor");
666
667
668
669
670
671
672
        }
        in_idx[axis] = idx;
    }

    argument compute(const shape& output_shape, std::vector<argument> args) const
    {
        argument result{output_shape};
673
674
675
676
        // max dimension in axis
        std::size_t max_dim = args[0].get_shape().lens()[axis];
        std::vector<std::size_t> vec_indices;
        args[1].visit([&](auto indices) { vec_indices.assign(indices.begin(), indices.end()); });
677
        visit_all(result, args[0])([&](auto output, auto input) {
678
            std::vector<std::size_t> in_idx;
679
            shape_for_each(output.get_shape(), [&](const auto& idx) {
680
                this->compute_index(idx, vec_indices, max_dim, in_idx);
681
682
683
684
685
686
687
688
689
690
                output(idx.begin(), idx.end()) = input(in_idx.begin(), in_idx.end());
            });
        });

        return result;
    }

    int output_alias(const std::vector<shape>&) const { return 0; }
};

Shucai Xiao's avatar
Shucai Xiao committed
691
struct dot
692
{
Paul's avatar
Paul committed
693
    float alpha = 1.0;
Paul's avatar
Paul committed
694
    float beta  = 0.0;
Paul's avatar
Paul committed
695
696
697
698

    template <class Self, class F>
    static auto reflect(Self& self, F f)
    {
Paul's avatar
Paul committed
699
        return pack(f(self.alpha, "alpha"), f(self.beta, "beta"));
Paul's avatar
Paul committed
700
701
    }

Shucai Xiao's avatar
Shucai Xiao committed
702
    std::string name() const { return "dot"; }
703
704
    shape compute_shape(std::vector<shape> inputs) const
    {
Paul's avatar
Paul committed
705
        check_shapes{inputs, *this}.has(2).same_type();
706
707
        const shape& a = inputs.at(0);
        const shape& b = inputs.at(1);
Scott Thornton's avatar
Scott Thornton committed
708
        auto t         = a.type();
709

710
        if(a.lens()[1] != b.lens()[0])
Paul's avatar
Paul committed
711
712
            MIGRAPHX_THROW("Inner dimensions do not match: {" + to_string_range(a.lens()) +
                           "} x {" + to_string_range(b.lens()) + "}");
Scott Thornton's avatar
Scott Thornton committed
713
        return {t, {a.lens()[0], b.lens()[1]}};
714
715
716
    }
};

717
struct unary
Scott Thornton's avatar
Scott Thornton committed
718
{
719
720
    shape compute_shape(std::vector<shape> inputs) const
    {
721
722
        check_shapes{inputs}.has(1);
        return inputs.at(0);
723
    }
Scott Thornton's avatar
Scott Thornton committed
724
725
};

726
struct identity
727
{
728
    std::string name() const { return "identity"; }
Scott Thornton's avatar
Scott Thornton committed
729
    shape compute_shape(std::vector<shape> inputs) const { return inputs.at(0); }
Paul's avatar
Paul committed
730
    argument compute(shape output_shape, std::vector<argument> args) const
731
732
733
    {
        return {std::move(output_shape), std::move(args.at(0).data)};
    }
Paul's avatar
Paul committed
734
    int output_alias(const std::vector<shape>&) const { return 0; }
735
736
737
};

struct abs : unary
Scott Thornton's avatar
Scott Thornton committed
738
{
739
    std::string name() const { return "abs"; }
Scott Thornton's avatar
Scott Thornton committed
740
741
};

742
struct exp : unary
Scott Thornton's avatar
Scott Thornton committed
743
{
744
    std::string name() const { return "exp"; }
Scott Thornton's avatar
Scott Thornton committed
745
746
};

Shucai Xiao's avatar
Shucai Xiao committed
747
748
749
750
751
struct log : unary
{
    std::string name() const { return "log"; }
};

752
struct sin : unary
Scott Thornton's avatar
Scott Thornton committed
753
{
754
    std::string name() const { return "sin"; }
Scott Thornton's avatar
Scott Thornton committed
755
756
};

757
struct cos : unary
Scott Thornton's avatar
Scott Thornton committed
758
{
759
    std::string name() const { return "cos"; }
Scott Thornton's avatar
Scott Thornton committed
760
761
};

762
struct tan : unary
Scott Thornton's avatar
Scott Thornton committed
763
{
764
    std::string name() const { return "tan"; }
Scott Thornton's avatar
Scott Thornton committed
765
766
};

767
struct asin : unary
Scott Thornton's avatar
Scott Thornton committed
768
{
769
    std::string name() const { return "asin"; }
Scott Thornton's avatar
Scott Thornton committed
770
771
};

772
struct acos : unary
Scott Thornton's avatar
Scott Thornton committed
773
{
774
    std::string name() const { return "acos"; }
Scott Thornton's avatar
Scott Thornton committed
775
776
};

777
struct atan : unary
Scott Thornton's avatar
Scott Thornton committed
778
{
779
    std::string name() const { return "atan"; }
Scott Thornton's avatar
Scott Thornton committed
780
781
};

782
783
784
785
786
787
788
789
790
791
struct sinh : unary
{
    std::string name() const { return "sinh"; }
};

struct cosh : unary
{
    std::string name() const { return "cosh"; }
};

792
struct tanh : unary
Scott Thornton's avatar
Scott Thornton committed
793
{
794
    std::string name() const { return "tanh"; }
Scott Thornton's avatar
Scott Thornton committed
795
796
};

797
struct sigmoid : unary
Scott Thornton's avatar
Scott Thornton committed
798
{
799
    std::string name() const { return "sigmoid"; }
Scott Thornton's avatar
Scott Thornton committed
800
801
};

802
struct neg : unary
Scott Thornton's avatar
Scott Thornton committed
803
{
804
    std::string name() const { return "neg"; }
Scott Thornton's avatar
Scott Thornton committed
805
806
};

Khalique's avatar
Khalique committed
807
808
809
810
811
struct relu : unary
{
    std::string name() const { return "relu"; }
};

Paul's avatar
Paul committed
812
813
814
815
816
817
818
819
820
821
struct softmax
{
    std::string name() const { return "softmax"; }
    shape compute_shape(std::vector<shape> inputs) const
    {
        check_shapes{inputs}.has(1).only_dims(4);
        return inputs.at(0);
    }
};

822
struct flatten
Scott Thornton's avatar
Scott Thornton committed
823
{
Paul's avatar
Paul committed
824
    uint64_t axis = 0;
Paul's avatar
Paul committed
825
826
827
828

    template <class Self, class F>
    static auto reflect(Self& self, F f)
    {
Paul's avatar
Paul committed
829
        return pack(f(self.axis, "axis"));
Paul's avatar
Paul committed
830
831
    }

Scott Thornton's avatar
Scott Thornton committed
832
    std::string name() const { return "flatten"; }
Paul's avatar
Paul committed
833
834
835
    shape compute_shape(std::vector<shape> inputs) const
    {
        check_shapes{inputs}.has(1);
Paul's avatar
Paul committed
836
837
        auto&& lens = inputs.front().lens();

Paul's avatar
Paul committed
838
        if(axis > lens.size())
Paul's avatar
Paul committed
839
        {
Paul's avatar
Paul committed
840
            MIGRAPHX_THROW("axis for flatten must be less than tensor rank");
Paul's avatar
Paul committed
841
        }
Paul's avatar
Paul committed
842
843
844
845
        auto x =
            std::accumulate(lens.begin(), lens.begin() + axis, std::size_t{1}, std::multiplies<>{});
        auto y =
            std::accumulate(lens.begin() + axis, lens.end(), std::size_t{1}, std::multiplies<>{});
846
        return {inputs.at(0).type(), {x, y}};
Paul's avatar
Paul committed
847
    }
Paul's avatar
Paul committed
848
    argument compute(shape output_shape, std::vector<argument> args) const
Paul's avatar
Paul committed
849
    {
Paul's avatar
Paul committed
850
        return {std::move(output_shape), std::move(args.front().data)};
Paul's avatar
Paul committed
851
    }
Paul's avatar
Paul committed
852
    int output_alias(const std::vector<shape>&) const { return 0; }
Scott Thornton's avatar
Scott Thornton committed
853
};
854

wsttiger's avatar
fixes  
wsttiger committed
855
856
857
858
859
860
861
862
/// The broadcast operator performs the numpy-style broadcasting of an axis of a given tensor. This
/// is achieved primarily by setting the stride of the broadcasted axis to zero. Linear indicies are
/// computed from multi-indicies by computing the inner product on the multi-index with the strides.
/// For example, if we have a tensor A(2,3) it has lengths of (2,3) and strides of (3,1). If we want
/// to compute the linear offset that corresponds to the element on the 2nd row (i = 1) and 3rd
/// column (j = 2), we compute the following inner product (1,2) dot (3, 1) = 1*3 + 2*1 = 5. It is
/// obvious from there that we can negate the effects of a given axis by setting the stride of that
/// axis to zero.
863
864
865
struct broadcast
{
    uint64_t axis = 0;
Paul's avatar
Paul committed
866
867
868
869

    template <class Self, class F>
    static auto reflect(Self& self, F f)
    {
Paul's avatar
Paul committed
870
        return pack(f(self.axis, "axis"));
Paul's avatar
Paul committed
871
872
    }

Scott Thornton's avatar
Scott Thornton committed
873
    shape broadcast_shape;
874
875
876
    std::string name() const { return "broadcast"; }
    shape compute_shape(std::vector<shape> inputs) const
    {
Scott Thornton's avatar
Scott Thornton committed
877
878
        auto t     = inputs.at(0).type();
        auto input = inputs.at(0);
Paul's avatar
Paul committed
879

Scott Thornton's avatar
Scott Thornton committed
880
        std::vector<size_t> bcast_strides(broadcast_shape.lens().size(), 0);
881

Scott Thornton's avatar
Scott Thornton committed
882
883
884
        if(std::all_of(broadcast_shape.lens().cbegin(), broadcast_shape.lens().cend(), [&](auto x) {
               return x == 1;
           }))
885
        {
Scott Thornton's avatar
Scott Thornton committed
886
            if(axis != 0)
Paul's avatar
Paul committed
887
                MIGRAPHX_THROW("when broadcasting tensor of size 1, axis should be 0");
Scott Thornton's avatar
Scott Thornton committed
888
            return {t, broadcast_shape.lens(), std::move(bcast_strides)};
889
890
891
        }
        else
        {
Scott Thornton's avatar
Scott Thornton committed
892
            assert(broadcast_shape.lens().size() - axis >= input.lens().size());
Scott Thornton's avatar
Scott Thornton committed
893
894
            if(!std::equal(
                   input.lens().begin(), input.lens().end(), broadcast_shape.lens().begin() + axis))
Paul's avatar
Paul committed
895
                MIGRAPHX_THROW("when broadcasting success sizes must match");
Paul's avatar
Paul committed
896
            std::copy(input.strides().begin(), input.strides().end(), bcast_strides.begin() + axis);
Scott Thornton's avatar
Scott Thornton committed
897
            return {t, broadcast_shape.lens(), std::move(bcast_strides)};
898
899
        }
    }
Paul's avatar
Paul committed
900
    argument compute(shape output_shape, std::vector<argument> args) const
Scott Thornton's avatar
Scott Thornton committed
901
    {
Scott Thornton's avatar
Scott Thornton committed
902
        return {std::move(output_shape), std::move(args.at(0).data)};
Scott Thornton's avatar
Scott Thornton committed
903
    }
Paul's avatar
Paul committed
904
    int output_alias(const std::vector<shape>&) const { return 0; }
905
906
};

Scott Thornton's avatar
Scott Thornton committed
907
908
909
struct multibroadcast
{
    std::vector<std::size_t> output_lens;
910
911
912
913
914
915
916

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

Scott Thornton's avatar
Scott Thornton committed
917
    std::string name() const { return "multibroadcast"; }
918

Scott Thornton's avatar
Scott Thornton committed
919
920
921
922
923
924
    shape compute_shape(std::vector<shape> inputs) const
    {
        check_shapes{inputs, *this}.has(1);
        auto t     = inputs.at(0).type();
        auto input = inputs.at(0);

wsttiger's avatar
wsttiger committed
925
        if(input.lens().empty())
Paul's avatar
Paul committed
926
            MIGRAPHX_THROW("inputs dimensions should be > 0");
Scott Thornton's avatar
Scott Thornton committed
927

Scott Thornton's avatar
Scott Thornton committed
928
        if(input.lens().size() > output_lens.size())
Paul's avatar
Paul committed
929
            MIGRAPHX_THROW("inputs dimensions should <= output size");
Scott Thornton's avatar
Scott Thornton committed
930
931

        std::vector<size_t> bcast_strides(output_lens.size(), 0);
Scott Thornton's avatar
Scott Thornton committed
932
933
        auto offset = output_lens.size() - input.lens().size();
        for(int i = input.lens().size() - 1; i >= 0; i--)
Scott Thornton's avatar
Scott Thornton committed
934
        {
Scott Thornton's avatar
Scott Thornton committed
935
            if(output_lens[i + offset] == input.lens()[i])
Scott Thornton's avatar
Scott Thornton committed
936
            {
Scott Thornton's avatar
Scott Thornton committed
937
                bcast_strides[i + offset] = input.strides()[i];
Scott Thornton's avatar
Scott Thornton committed
938
939
940
941
            }
        }
        return {t, output_lens, bcast_strides};
    }
Paul's avatar
Paul committed
942
    argument compute(shape output_shape, std::vector<argument> args) const
Scott Thornton's avatar
Scott Thornton committed
943
944
945
946
947
948
    {
        return {std::move(output_shape), std::move(args.at(0).data)};
    }
    int output_alias(const std::vector<shape>&) const { return 0; }
};

Khalique's avatar
Khalique committed
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
struct scalar
{
    shape scalar_bcast;

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

    shape compute_shape(std::vector<shape> inputs) const
    {
        assert(check_shapes{inputs}.has(1).only_dims(1).size() == 1);
        auto t     = inputs.at(0).type();
        auto input = inputs.at(0);
        std::vector<std::size_t> strides(scalar_bcast.lens().size(), 0);
        return {t, scalar_bcast.lens(), strides};
    }

Paul's avatar
Paul committed
964
    argument compute(shape output_shape, std::vector<argument> args) const
Khalique's avatar
Khalique committed
965
966
967
    {
        return {std::move(output_shape), std::move(args.at(0).data)};
    }
Paul's avatar
Paul committed
968
    int output_alias(const std::vector<shape>&) const { return 0; }
Khalique's avatar
Khalique committed
969
970
};

971
struct binary
Scott Thornton's avatar
Scott Thornton committed
972
{
973
974
    shape compute_shape(std::vector<shape> inputs) const
    {
975
        check_shapes{inputs}.has(2).same_type().same_dims();
Scott Thornton's avatar
Scott Thornton committed
976
        auto t    = inputs.at(0).type();
977
978
        auto lens = inputs.at(0).lens();
        return {t, lens};
979
    }
Scott Thornton's avatar
Scott Thornton committed
980
981
};

982
983
984
985
986
987
struct add : binary
{
    std::string name() const { return "add"; }
};

struct sub : binary
Scott Thornton's avatar
Scott Thornton committed
988
989
990
991
{
    std::string name() const { return "sub"; }
};

992
struct mul : binary
Scott Thornton's avatar
Scott Thornton committed
993
994
995
996
{
    std::string name() const { return "mul"; }
};

997
struct div : binary
Scott Thornton's avatar
Scott Thornton committed
998
999
1000
1001
{
    std::string name() const { return "div"; }
};

Khalique's avatar
Khalique committed
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
struct max : binary
{
    std::string name() const { return "max"; }
};

struct min : binary
{
    std::string name() const { return "min"; }
};

Paul's avatar
Paul committed
1012
1013
1014
1015
struct load
{
    shape s;
    std::size_t offset = 0;
Paul's avatar
Paul committed
1016
1017
1018
1019

    template <class Self, class F>
    static auto reflect(Self& self, F f)
    {
Paul's avatar
Paul committed
1020
        return pack(f(self.s, "shape"), f(self.offset, "offset"));
Paul's avatar
Paul committed
1021
1022
    }

Paul's avatar
Paul committed
1023
1024
1025
1026
1027
1028
    std::string name() const { return "load"; }
    shape compute_shape(const std::vector<shape>& inputs) const
    {
        check_shapes{inputs}.has(1);
        return s;
    }
Paul's avatar
Paul committed
1029
    argument compute(const shape&, const std::vector<argument>& args) const
Paul's avatar
Paul committed
1030
1031
1032
    {
        return {s, args[0].data() + offset};
    }
Paul's avatar
Paul committed
1033
    int output_alias(const std::vector<shape>&) const { return 0; }
Paul's avatar
Paul committed
1034
1035
};

Paul's avatar
Paul committed
1036
struct outline
Scott Thornton's avatar
Scott Thornton committed
1037
{
Paul's avatar
Paul committed
1038
    shape s;
Paul's avatar
Paul committed
1039
1040
1041
1042

    template <class Self, class F>
    static auto reflect(Self& self, F f)
    {
Paul's avatar
Paul committed
1043
        return pack(f(self.s, "shape"));
Paul's avatar
Paul committed
1044
1045
    }

Paul's avatar
Paul committed
1046
    std::string name() const { return "outline"; }
Paul's avatar
Paul committed
1047
    shape compute_shape(const std::vector<shape>& inputs) const
Paul's avatar
Paul committed
1048
    {
Paul's avatar
Paul committed
1049
        check_shapes{inputs, *this}.has(0);
Paul's avatar
Paul committed
1050
1051
        return s;
    }
Paul's avatar
Paul committed
1052
    argument compute(const shape&, const std::vector<argument>&) const { return {s, nullptr}; }
Scott Thornton's avatar
Scott Thornton committed
1053
1054
};

1055
} // namespace op
Paul's avatar
Paul committed
1056
} // namespace MIGRAPHX_INLINE_NS
Paul's avatar
Paul committed
1057
} // namespace migraphx
Paul's avatar
Paul committed
1058
1059

#endif