operators.hpp 27 KB
Newer Older
Paul's avatar
Paul committed
1
2
#ifndef MIGRAPH_GUARD_OPERATORS_HPP
#define MIGRAPH_GUARD_OPERATORS_HPP
Paul's avatar
Paul committed
3

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

13
14
namespace migraph {
inline namespace MIGRAPH_INLINE_NS {
15
namespace op {
Paul's avatar
Paul committed
16

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

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

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

32
33
34
35
36
37
38
39
    enum bn_infer_mode_t
    {
        per_activation,
        spatial,
    };

    bn_infer_mode_t bn_mode = spatial;

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

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

Khalique's avatar
Khalique committed
54
struct lrn
Khalique's avatar
Khalique committed
55
56
{
    float alpha = 0.0001;
Khalique's avatar
Khalique committed
57
58
    float beta  = 0.75;
    float bias  = 1.0;
Khalique's avatar
Khalique committed
59
    int size;
Khalique's avatar
Khalique committed
60
    std::string name() const { return "lrn"; }
Khalique's avatar
Khalique committed
61
62
63
64
65
66
67

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

Khalique's avatar
Khalique committed
68
    friend std::ostream& operator<<(std::ostream& os, const lrn& op)
Khalique's avatar
Khalique committed
69
70
71
72
73
74
    {
        os << op.name() << ":" << op.alpha << ":" << op.beta << ":" << op.bias << ":" << op.size;
        return os;
    }
};

Paul's avatar
Paul committed
75
struct convolution
Paul's avatar
Paul committed
76
{
Paul's avatar
Paul committed
77
78
79
    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
80
81
82
83
84
85
86
    enum padding_mode_t
    {
        default_, // NOLINT
        same,
        valid
    };
    padding_mode_t padding_mode = default_;
Paul's avatar
Paul committed
87
88
89
90

    template <class Self, class F>
    static auto reflect(Self& self, F f)
    {
Paul's avatar
Paul committed
91
92
93
94
        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
95
96
    }

Paul's avatar
Paul committed
97
    std::string name() const { return "convolution"; }
Paul's avatar
Paul committed
98
99
    shape compute_shape(std::vector<shape> inputs) const
    {
Paul's avatar
Paul committed
100
        check_shapes{inputs, *this}.has(2).same_type().same_ndims().only_dims(4);
Paul's avatar
Paul committed
101

Paul's avatar
Paul committed
102
        const shape& input   = inputs.at(0);
Paul's avatar
Paul committed
103
        const shape& weights = inputs.at(1);
Paul's avatar
Paul committed
104
        auto t               = input.type();
Paul's avatar
Paul committed
105
106
        if(padding_mode == default_)
        {
Paul's avatar
Paul committed
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
            return {t,
                    {
                        input.lens()[0],
                        weights.lens()[0],
                        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
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
        }
        else if(padding_mode == same)
        {
            return {t,
                    {input.lens()[0],
                     weights.lens()[0],
                     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],
                 weights.lens()[0],
                 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
148
            MIGRAPH_THROW("Invalid padding mode");
Paul's avatar
Paul committed
149
        }
Paul's avatar
Paul committed
150
151
152
    }
};

Scott Thornton's avatar
Scott Thornton committed
153
154
struct im2col
{
Scott Thornton's avatar
Scott Thornton committed
155
156
157
158
159
160
161
162
163
    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
164
165
166
167
168
    padding_mode_t padding_mode = default_;

    template <class Self, class F>
    static auto reflect(Self& self, F f)
    {
Paul's avatar
Paul committed
169
170
171
172
        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
173
    }
Scott Thornton's avatar
Scott Thornton committed
174
175
176
177
178

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

    shape compute_shape(std::vector<shape> inputs) const
    {
Scott Thornton's avatar
Scott Thornton committed
179
180
181
        auto input          = inputs[0];
        auto weights        = inputs[1];
        auto batch_size     = input.lens()[0];
Scott Thornton's avatar
Scott Thornton committed
182
        auto input_channels = weights.lens()[1];
Scott Thornton's avatar
Scott Thornton committed
183
184
        auto kernel_height  = weights.lens()[2];
        auto kernel_width   = weights.lens()[3];
Scott Thornton's avatar
Scott Thornton committed
185
        check_shapes{inputs, *this}.has(2);
Scott Thornton's avatar
Scott Thornton committed
186
187
        if(batch_size != 1)
            MIGRAPH_THROW("im2col only support batch_size 1");
Scott Thornton's avatar
Scott Thornton committed
188
        auto output_height = std::size_t(std::max<std::ptrdiff_t>(
Scott Thornton's avatar
Scott Thornton committed
189
190
191
            1,
            (input.lens()[2] - (1 + dilation[0] * (kernel_height - 1)) + 2 * padding[0]) /
                    stride[0] +
Scott Thornton's avatar
Scott Thornton committed
192
                1));
Scott Thornton's avatar
Scott Thornton committed
193
194
195
196
        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
197
                1));
Scott Thornton's avatar
Scott Thornton committed
198
199
        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
200
201
202
    }
};

Paul's avatar
Paul committed
203
struct pooling
Paul's avatar
Paul committed
204
{
Paul's avatar
Paul committed
205
    std::string mode                   = "average";
Paul's avatar
Paul committed
206
207
208
    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
209
210
211
212

    template <class Self, class F>
    static auto reflect(Self& self, F f)
    {
Paul's avatar
Paul committed
213
214
215
216
        return pack(f(self.mode, "mode"),
                    f(self.padding, "padding"),
                    f(self.stride, "stride"),
                    f(self.lengths, "lengths"));
Paul's avatar
Paul committed
217
218
    }

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

Paul's avatar
Paul committed
221
222
    shape compute_shape(std::vector<shape> inputs) const
    {
Paul's avatar
Paul committed
223
        check_shapes{inputs, *this}.has(1).only_dims(4);
Paul's avatar
Paul committed
224

Paul's avatar
Paul committed
225
        const shape& input = inputs.at(0);
Paul's avatar
Paul committed
226
        auto t             = input.type();
Paul's avatar
Paul committed
227

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

Scott Thornton's avatar
Scott Thornton committed
231
232
233
234
235
236
        return {t,
                {
                    input.lens()[0],
                    input.lens()[1],
                    std::size_t(std::max<std::ptrdiff_t>(
                        1,
Paul's avatar
Paul committed
237
                        std::ptrdiff_t(std::floor((input.lens()[2] + 2 * padding[0] - lengths[0]) /
Paul's avatar
Paul committed
238
                                                  static_cast<float>(stride[0]))) +
Scott Thornton's avatar
Scott Thornton committed
239
240
241
                            1)),
                    std::size_t(std::max<std::ptrdiff_t>(
                        1,
Paul's avatar
Paul committed
242
                        std::ptrdiff_t(std::floor((input.lens()[3] + 2 * padding[1] - lengths[1]) /
Paul's avatar
Paul committed
243
                                                  static_cast<float>(stride[1]))) +
Scott Thornton's avatar
Scott Thornton committed
244
245
                            1)),
                }};
Paul's avatar
Paul committed
246
247
248
    }
};

Khalique's avatar
Khalique committed
249
250
251
252
253
254
255
256
257
258
259
260
261
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();
    }
    friend std::ostream& operator<<(std::ostream& os, const leaky_relu& op)
    {
        os << op.name() << ":" << op.alpha;
        return os;
Khalique's avatar
Khalique committed
262
    }
Khalique's avatar
Khalique committed
263
264
};

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

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

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

Paul's avatar
Paul committed
309
struct contiguous
310
311
312
313
{
    std::string name() const { return "contiguous"; }
    shape compute_shape(std::vector<shape> inputs) const
    {
Paul's avatar
Paul committed
314
        check_shapes{inputs, *this}.has(1);
Paul's avatar
Paul committed
315
316
        auto lens = inputs.at(0).lens();
        auto t    = inputs.at(0).type();
317
318
319
320
        return {t, lens};
    }
};

321
322
323
324
struct concat
{
    std::size_t axis = 0;
    std::string name() const { return "concat"; }
325
326
327
328
329
330
331
332
333
334
335
336
337
    std::vector<std::size_t> compute_offsets(const shape& output_shape,
                                             const std::vector<argument> args) const
    {
        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;
    }
338
339
    shape compute_shape(std::vector<shape> inputs) const
    {
Scott Thornton's avatar
Scott Thornton committed
340
        if(inputs.empty())
341
342
343
344
345
        {
            MIGRAPH_THROW("Number of input tensors should exceed 0");
        }

        const auto& first_shape_lens = inputs.front().lens();
Scott Thornton's avatar
Scott Thornton committed
346
347
348
349
350
351
352
353
354
355
        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];
                   }))
                {
                    MIGRAPH_THROW("Non-axis dimensions should match");
356
357
358
359
                }
            }
        }
        std::size_t new_dim_axis = 0;
Scott Thornton's avatar
Scott Thornton committed
360
        for(const auto& input : inputs)
361
362
363
364
365
366
367
368
369
        {
            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
370
    int output_alias(const std::vector<shape>&) const { return 0; }
371
372
};

373
374
375
376
377
struct slice
{
    std::vector<int64_t> axes;
    std::vector<int64_t> starts;
    std::vector<int64_t> ends;
Paul's avatar
Paul committed
378
379
380
381

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

385
    std::string name() const { return "slice"; }
Scott Thornton's avatar
Scott Thornton committed
386
387

    auto fix_index(const std::vector<std::size_t>& lens, std::size_t axis, int64_t index) const
388
    {
Scott Thornton's avatar
Scott Thornton committed
389
        int64_t r = std::min(index, static_cast<int64_t>(lens[axis]));
Scott Thornton's avatar
Scott Thornton committed
390
391
        if(r < 0)
            r += lens[axis];
Scott Thornton's avatar
Scott Thornton committed
392
        return std::size_t(r);
Scott Thornton's avatar
Scott Thornton committed
393
394
395
396
397
398
399
    }

    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
400
        if(!axes.empty())
Scott Thornton's avatar
Scott Thornton committed
401
        {
Scott Thornton's avatar
Scott Thornton committed
402
403
404
405
406
            for(std::size_t i = 0; i < axes.size(); i++)
            {
                auto axis = axes[i];
                offset += fix_index(lens, axis, starts[i]) * strides[axis];
            }
407
        }
Scott Thornton's avatar
Scott Thornton committed
408
409
        else
        {
Scott Thornton's avatar
Scott Thornton committed
410
411
412
413
            for(std::size_t axis = 0; axis < lens.size(); axis++)
            {
                offset += fix_index(lens, axis, starts[axis]) * strides[axis];
            }
414
        }
Scott Thornton's avatar
Scott Thornton committed
415
416
417
418
419
        return offset;
    }

    shape compute_shape(std::vector<shape> inputs) const
    {
Scott Thornton's avatar
Scott Thornton committed
420
421
422
423
        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
424
425
426
427
428
429
430
431
432
433
        // std::vector<int64_t> t_axes(old_lens.size());
        // if(axes.size() == 0)
        // {
        //     std::iota(t_axes.begin(), t_axes.end(), 0);
        // }
        // else
        // {
        //     std::copy(axes.begin(), axes.end(), t_axes.begin());
        // }
        if(starts.size() != axes.size() || axes.size() != ends.size())
Scott Thornton's avatar
Scott Thornton committed
434
        {
435
436
            MIGRAPH_THROW("inconsistent sizes");
        }
Scott Thornton's avatar
Scott Thornton committed
437
438
        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
439
        {
Scott Thornton's avatar
Scott Thornton committed
440
441
442
            auto axis = axes[i];
            new_lens[axis] =
                fix_index(old_lens, axis, ends[i]) - fix_index(old_lens, axis, starts[i]);
443
444
445
446
447
        }
        return shape{t, new_lens, old_strides};
    }
    argument compute(context&, shape output_shape, std::vector<argument> args) const
    {
Scott Thornton's avatar
Scott Thornton committed
448
449
450
        auto input  = args[0];
        auto offset = compute_offset(input.get_shape()) * output_shape.type_size();
        return {std::move(output_shape), [=] { return input.data() + offset; }};
451
    }
Paul's avatar
Paul committed
452
    int output_alias(const std::vector<shape>&) const { return 0; }
453
454
455
456
457
};

struct squeeze
{
    std::vector<int64_t> axes;
Paul's avatar
Paul committed
458
459
460
461

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

465
466
467
468
    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
469
470
        auto type        = input_shape.type();
        auto old_lens    = input_shape.lens();
wsttiger's avatar
wsttiger committed
471
472
        if(std::any_of(
               axes.begin(), axes.end(), [&](auto axis) { return input_shape.lens()[axis] != 1; }))
Scott Thornton's avatar
Scott Thornton committed
473
        {
wsttiger's avatar
wsttiger committed
474
            MIGRAPH_THROW("squeeze axis dimension should be equal to 1");
475
476
        }
        std::vector<std::size_t> new_lens;
Scott Thornton's avatar
Scott Thornton committed
477
        if(axes.empty())
Scott Thornton's avatar
Scott Thornton committed
478
        {
wsttiger's avatar
wsttiger committed
479
480
481
482
            std::copy_if(old_lens.begin(),
                         old_lens.end(),
                         std::back_inserter(new_lens),
                         [](auto len) { return len != 1; });
483
        }
Scott Thornton's avatar
Scott Thornton committed
484
485
486
487
488
489
        else
        {
            for(std::size_t i = 0; i < old_lens.size(); i++)
            {
                if(std::find(axes.begin(), axes.end(), i) == axes.end())
                {
490
491
492
493
494
495
496
497
498
                    new_lens.push_back(old_lens[i]);
                }
            }
        }
        return shape{type, new_lens};
    }
    argument compute(context&, shape output_shape, std::vector<argument> args) const
    {
        return {std::move(output_shape), std::move(args.front().data)};
Scott Thornton's avatar
Scott Thornton committed
499
    }
Paul's avatar
Paul committed
500
    int output_alias(const std::vector<shape>&) const { return 0; }
501
502
503
504
505
};

struct unsqueeze
{
    std::vector<int64_t> axes;
Paul's avatar
Paul committed
506
507
508
509

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

513
514
515
    std::string name() const { return "unsqueeze"; }
    shape compute_shape(std::vector<shape> inputs) const
    {
Scott Thornton's avatar
Scott Thornton committed
516
517
518
        auto input_shape     = inputs[0];
        auto type            = input_shape.type();
        auto old_lens        = input_shape.lens();
519
520
521
        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
522
523
524
525
        for(std::size_t i = 0; i < new_size; i++)
        {
            if(std::find(axes.begin(), axes.end(), i) != axes.end())
            {
526
                new_lens[i] = 1;
Scott Thornton's avatar
Scott Thornton committed
527
528
529
            }
            else
            {
530
531
532
533
534
535
536
537
538
                new_lens[i] = old_lens[p++];
            }
        }
        return shape{type, new_lens};
    }
    argument compute(context&, shape output_shape, std::vector<argument> args) const
    {
        return {std::move(output_shape), std::move(args.front().data)};
    }
Paul's avatar
Paul committed
539
    int output_alias(const std::vector<shape>&) const { return 0; }
540
541
};

Paul's avatar
Paul committed
542
543
544
struct reshape
{
    std::vector<int64_t> dims;
Paul's avatar
Paul committed
545
546
547
548

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

Paul's avatar
Paul committed
552
    std::string name() const { return "reshape"; }
Paul's avatar
Paul committed
553
554
    shape compute_shape(std::vector<shape> inputs) const
    {
Paul's avatar
Paul committed
555
        check_shapes{inputs, *this}.has(1);
Paul's avatar
Paul committed
556
557
        auto&& idims = inputs.front().lens();
        std::vector<std::size_t> rdims(dims.begin(), dims.end());
558
559
560
        auto n_neg_dims = std::count(dims.begin(), dims.end(), -1);
        if(n_neg_dims > 1)
            MIGRAPH_THROW("Dimensions for reshape can only have one -1 dim");
Paul's avatar
Paul committed
561
        for(std::size_t i = 0; i < dims.size(); i++)
Paul's avatar
Paul committed
562
563
564
565
        {
            if(dims[i] == 0)
                rdims[i] = idims[i];
        }
566
567
568
569
570
571
572
573
574
575
576
        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
577
578
579
        if(dims.back() == -1)
        {
            rdims.pop_back();
Paul's avatar
Paul committed
580
            std::copy(idims.begin() + rdims.size(), idims.end(), std::back_inserter(rdims));
Paul's avatar
Paul committed
581
        }
Scott Thornton's avatar
Scott Thornton committed
582
        shape s{inputs.front().type(), rdims};
Paul's avatar
Paul committed
583
        if(s.elements() != inputs.front().elements())
Paul's avatar
Paul committed
584
            MIGRAPH_THROW("Wrong number of elements for reshape");
Scott Thornton's avatar
Scott Thornton committed
585
        return s;
Paul's avatar
Paul committed
586
    }
Paul's avatar
Paul committed
587
    argument compute(context&, shape output_shape, std::vector<argument> args) const
Paul's avatar
Paul committed
588
    {
Paul's avatar
Paul committed
589
        return {std::move(output_shape), std::move(args.front().data)};
Paul's avatar
Paul committed
590
    }
Paul's avatar
Paul committed
591
    int output_alias(const std::vector<shape>&) const { return 0; }
Paul's avatar
Paul committed
592
593
};

Shucai Xiao's avatar
Shucai Xiao committed
594
struct dot
595
{
Paul's avatar
Paul committed
596
    float alpha = 1.0;
Paul's avatar
Paul committed
597
    float beta  = 0.0;
Paul's avatar
Paul committed
598
599
600
601

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

Shucai Xiao's avatar
Shucai Xiao committed
605
    std::string name() const { return "dot"; }
606
607
    shape compute_shape(std::vector<shape> inputs) const
    {
Paul's avatar
Paul committed
608
        check_shapes{inputs, *this}.has(2).same_type();
609
610
        const shape& a = inputs.at(0);
        const shape& b = inputs.at(1);
Scott Thornton's avatar
Scott Thornton committed
611
        auto t         = a.type();
612

613
        if(a.lens()[1] != b.lens()[0])
Paul's avatar
Paul committed
614
615
            MIGRAPH_THROW("Inner dimensions do not match: {" + to_string_range(a.lens()) + "} x {" +
                          to_string_range(b.lens()) + "}");
Scott Thornton's avatar
Scott Thornton committed
616
        return {t, {a.lens()[0], b.lens()[1]}};
617
618
619
    }
};

620
struct unary
Scott Thornton's avatar
Scott Thornton committed
621
{
622
623
    shape compute_shape(std::vector<shape> inputs) const
    {
624
625
        check_shapes{inputs}.has(1);
        return inputs.at(0);
626
    }
Scott Thornton's avatar
Scott Thornton committed
627
628
};

629
struct identity
630
{
631
    std::string name() const { return "identity"; }
Scott Thornton's avatar
Scott Thornton committed
632
    shape compute_shape(std::vector<shape> inputs) const { return inputs.at(0); }
633
634
635
636
    argument compute(context&, shape output_shape, std::vector<argument> args) const
    {
        return {std::move(output_shape), std::move(args.at(0).data)};
    }
Paul's avatar
Paul committed
637
    int output_alias(const std::vector<shape>&) const { return 0; }
638
639
640
};

struct abs : unary
Scott Thornton's avatar
Scott Thornton committed
641
{
642
    std::string name() const { return "abs"; }
Scott Thornton's avatar
Scott Thornton committed
643
644
};

645
struct exp : unary
Scott Thornton's avatar
Scott Thornton committed
646
{
647
    std::string name() const { return "exp"; }
Scott Thornton's avatar
Scott Thornton committed
648
649
};

650
struct sin : unary
Scott Thornton's avatar
Scott Thornton committed
651
{
652
    std::string name() const { return "sin"; }
Scott Thornton's avatar
Scott Thornton committed
653
654
};

655
struct cos : unary
Scott Thornton's avatar
Scott Thornton committed
656
{
657
    std::string name() const { return "cos"; }
Scott Thornton's avatar
Scott Thornton committed
658
659
};

660
struct tan : unary
Scott Thornton's avatar
Scott Thornton committed
661
{
662
    std::string name() const { return "tan"; }
Scott Thornton's avatar
Scott Thornton committed
663
664
};

665
struct asin : unary
Scott Thornton's avatar
Scott Thornton committed
666
{
667
    std::string name() const { return "asin"; }
Scott Thornton's avatar
Scott Thornton committed
668
669
};

670
struct acos : unary
Scott Thornton's avatar
Scott Thornton committed
671
{
672
    std::string name() const { return "acos"; }
Scott Thornton's avatar
Scott Thornton committed
673
674
};

675
struct atan : unary
Scott Thornton's avatar
Scott Thornton committed
676
{
677
    std::string name() const { return "atan"; }
Scott Thornton's avatar
Scott Thornton committed
678
679
};

680
struct tanh : unary
Scott Thornton's avatar
Scott Thornton committed
681
{
682
    std::string name() const { return "tanh"; }
Scott Thornton's avatar
Scott Thornton committed
683
684
};

685
struct sigmoid : unary
Scott Thornton's avatar
Scott Thornton committed
686
{
687
    std::string name() const { return "sigmoid"; }
Scott Thornton's avatar
Scott Thornton committed
688
689
};

690
struct neg : unary
Scott Thornton's avatar
Scott Thornton committed
691
{
692
    std::string name() const { return "neg"; }
Scott Thornton's avatar
Scott Thornton committed
693
694
};

Khalique's avatar
Khalique committed
695
696
697
698
699
struct relu : unary
{
    std::string name() const { return "relu"; }
};

Paul's avatar
Paul committed
700
701
702
703
704
705
706
707
708
709
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);
    }
};

710
struct flatten
Scott Thornton's avatar
Scott Thornton committed
711
{
Paul's avatar
Paul committed
712
    uint64_t axis = 0;
Paul's avatar
Paul committed
713
714
715
716

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

Scott Thornton's avatar
Scott Thornton committed
720
    std::string name() const { return "flatten"; }
Paul's avatar
Paul committed
721
722
723
    shape compute_shape(std::vector<shape> inputs) const
    {
        check_shapes{inputs}.has(1);
Paul's avatar
Paul committed
724
725
        auto&& lens = inputs.front().lens();

Paul's avatar
Paul committed
726
        if(axis > lens.size())
Paul's avatar
Paul committed
727
        {
Paul's avatar
Paul committed
728
            MIGRAPH_THROW("axis for flatten must be less than tensor rank");
Paul's avatar
Paul committed
729
        }
Paul's avatar
Paul committed
730
731
732
733
        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<>{});
734
        return {inputs.at(0).type(), {x, y}};
Paul's avatar
Paul committed
735
736
737
    }
    argument compute(context&, shape output_shape, std::vector<argument> args) const
    {
Paul's avatar
Paul committed
738
        return {std::move(output_shape), std::move(args.front().data)};
Paul's avatar
Paul committed
739
    }
Paul's avatar
Paul committed
740
    int output_alias(const std::vector<shape>&) const { return 0; }
Scott Thornton's avatar
Scott Thornton committed
741
};
742
743
744
struct broadcast
{
    uint64_t axis = 0;
Paul's avatar
Paul committed
745
746
747
748

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

Scott Thornton's avatar
Scott Thornton committed
752
    shape broadcast_shape;
753
754
755
    std::string name() const { return "broadcast"; }
    shape compute_shape(std::vector<shape> inputs) const
    {
Scott Thornton's avatar
Scott Thornton committed
756
757
        auto t     = inputs.at(0).type();
        auto input = inputs.at(0);
Paul's avatar
Paul committed
758

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

Scott Thornton's avatar
Scott Thornton committed
761
762
763
        if(std::all_of(broadcast_shape.lens().cbegin(), broadcast_shape.lens().cend(), [&](auto x) {
               return x == 1;
           }))
764
        {
Scott Thornton's avatar
Scott Thornton committed
765
            if(axis != 0)
Paul's avatar
Paul committed
766
                MIGRAPH_THROW("when broadcasting tensor of size 1, axis should be 0");
Scott Thornton's avatar
Scott Thornton committed
767
            return {t, broadcast_shape.lens(), std::move(bcast_strides)};
768
769
770
        }
        else
        {
Scott Thornton's avatar
Scott Thornton committed
771
            assert(broadcast_shape.lens().size() - axis >= input.lens().size());
Scott Thornton's avatar
Scott Thornton committed
772
773
            if(!std::equal(
                   input.lens().begin(), input.lens().end(), broadcast_shape.lens().begin() + axis))
Paul's avatar
Paul committed
774
                MIGRAPH_THROW("when broadcasting success sizes must match");
Paul's avatar
Paul committed
775
            std::copy(input.strides().begin(), input.strides().end(), bcast_strides.begin() + axis);
Scott Thornton's avatar
Scott Thornton committed
776
            return {t, broadcast_shape.lens(), std::move(bcast_strides)};
777
778
        }
    }
Paul's avatar
Paul committed
779
    argument compute(context&, shape output_shape, std::vector<argument> args) const
Scott Thornton's avatar
Scott Thornton committed
780
    {
Scott Thornton's avatar
Scott Thornton committed
781
        return {std::move(output_shape), std::move(args.at(0).data)};
Scott Thornton's avatar
Scott Thornton committed
782
    }
Paul's avatar
Paul committed
783
    int output_alias(const std::vector<shape>&) const { return 0; }
784
785
};

Scott Thornton's avatar
Scott Thornton committed
786
787
788
struct multibroadcast
{
    std::vector<std::size_t> output_lens;
789
790
791
792
793
794
795

    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
796
    std::string name() const { return "multibroadcast"; }
797

Scott Thornton's avatar
Scott Thornton committed
798
799
800
801
802
803
    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
804
        if(input.lens().empty())
Scott Thornton's avatar
Scott Thornton committed
805
806
            MIGRAPH_THROW("inputs dimensions should be > 0");

Scott Thornton's avatar
Scott Thornton committed
807
        if(input.lens().size() > output_lens.size())
Scott Thornton's avatar
Scott Thornton committed
808
809
810
            MIGRAPH_THROW("inputs dimensions should <= output size");

        std::vector<size_t> bcast_strides(output_lens.size(), 0);
Scott Thornton's avatar
Scott Thornton committed
811
812
        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
813
        {
Scott Thornton's avatar
Scott Thornton committed
814
            if(output_lens[i + offset] == input.lens()[i])
Scott Thornton's avatar
Scott Thornton committed
815
            {
Scott Thornton's avatar
Scott Thornton committed
816
                bcast_strides[i + offset] = input.strides()[i];
Scott Thornton's avatar
Scott Thornton committed
817
818
819
820
821
822
823
824
825
826
827
            }
        }
        return {t, output_lens, bcast_strides};
    }
    argument compute(context&, shape output_shape, std::vector<argument> args) const
    {
        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
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
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};
    }

    argument compute(context&, shape output_shape, std::vector<argument> args) const
    {
        return {std::move(output_shape), std::move(args.at(0).data)};
    }
Paul's avatar
Paul committed
847
    int output_alias(const std::vector<shape>&) const { return 0; }
Khalique's avatar
Khalique committed
848
849
};

850
struct binary
Scott Thornton's avatar
Scott Thornton committed
851
{
852
853
    shape compute_shape(std::vector<shape> inputs) const
    {
854
        check_shapes{inputs}.has(2).same_type().same_dims();
Scott Thornton's avatar
Scott Thornton committed
855
        auto t    = inputs.at(0).type();
856
857
        auto lens = inputs.at(0).lens();
        return {t, lens};
858
    }
Scott Thornton's avatar
Scott Thornton committed
859
860
};

861
862
863
864
865
866
struct add : binary
{
    std::string name() const { return "add"; }
};

struct sub : binary
Scott Thornton's avatar
Scott Thornton committed
867
868
869
870
{
    std::string name() const { return "sub"; }
};

871
struct mul : binary
Scott Thornton's avatar
Scott Thornton committed
872
873
874
875
{
    std::string name() const { return "mul"; }
};

876
struct div : binary
Scott Thornton's avatar
Scott Thornton committed
877
878
879
880
{
    std::string name() const { return "div"; }
};

Paul's avatar
Paul committed
881
882
883
884
struct load
{
    shape s;
    std::size_t offset = 0;
Paul's avatar
Paul committed
885
886
887
888

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

Paul's avatar
Paul committed
892
893
894
895
896
897
898
899
900
901
    std::string name() const { return "load"; }
    shape compute_shape(const std::vector<shape>& inputs) const
    {
        check_shapes{inputs}.has(1);
        return s;
    }
    argument compute(context&, const shape&, const std::vector<argument>& args) const
    {
        return {s, args[0].data() + offset};
    }
Paul's avatar
Paul committed
902
    int output_alias(const std::vector<shape>&) const { return 0; }
Paul's avatar
Paul committed
903
904
};

Paul's avatar
Paul committed
905
struct outline
Scott Thornton's avatar
Scott Thornton committed
906
{
Paul's avatar
Paul committed
907
    shape s;
Paul's avatar
Paul committed
908
909
910
911

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

Paul's avatar
Paul committed
915
    std::string name() const { return "outline"; }
Paul's avatar
Paul committed
916
    shape compute_shape(const std::vector<shape>& inputs) const
Paul's avatar
Paul committed
917
    {
Paul's avatar
Paul committed
918
        check_shapes{inputs, *this}.has(0);
Paul's avatar
Paul committed
919
920
        return s;
    }
Paul's avatar
Paul committed
921
922
923
924
    argument compute(context&, const shape&, const std::vector<argument>&) const
    {
        return {s, nullptr};
    }
Scott Thornton's avatar
Scott Thornton committed
925
926
};

927
} // namespace op
928
} // namespace MIGRAPH_INLINE_NS
Paul's avatar
Paul committed
929
} // namespace migraph
Paul's avatar
Paul committed
930
931

#endif