operators.hpp 22.1 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>
Paul's avatar
Paul committed
9
#include <cmath>
Paul's avatar
Paul committed
10
#include <utility>
Paul's avatar
Paul committed
11

Paul's avatar
Paul committed
12
namespace migraph {
13
namespace op {
Paul's avatar
Paul committed
14

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

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

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

30
31
32
33
34
35
36
37
    enum bn_infer_mode_t
    {
        per_activation,
        spatial,
    };

    bn_infer_mode_t bn_mode = spatial;

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

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

Paul's avatar
Paul committed
55
struct convolution
Paul's avatar
Paul committed
56
{
Paul's avatar
Paul committed
57
58
59
    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
60
61
62
63
64
65
66
    enum padding_mode_t
    {
        default_, // NOLINT
        same,
        valid
    };
    padding_mode_t padding_mode = default_;
Paul's avatar
Paul committed
67
68
69
70
71
72
73
74
75
76
77
78

    template <class Self, class F>
    static auto reflect(Self& self, F f)
    {
        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
79
    std::string name() const { return "convolution"; }
Paul's avatar
Paul committed
80
81
    shape compute_shape(std::vector<shape> inputs) const
    {
Paul's avatar
Paul committed
82
        check_shapes{inputs, *this}.has(2).same_type().same_ndims().only_dims(4);
Paul's avatar
Paul committed
83

Paul's avatar
Paul committed
84
        const shape& input   = inputs.at(0);
Paul's avatar
Paul committed
85
        const shape& weights = inputs.at(1);
Paul's avatar
Paul committed
86
        auto t               = input.type();
Paul's avatar
Paul committed
87
88
        if(padding_mode == default_)
        {
Paul's avatar
Paul committed
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
            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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
        }
        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
130
            MIGRAPH_THROW("Invalid padding mode");
Paul's avatar
Paul committed
131
        }
Paul's avatar
Paul committed
132
133
134
    }
};

Scott Thornton's avatar
Scott Thornton committed
135
136
struct im2col
{
Scott Thornton's avatar
Scott Thornton committed
137
138
139
140
141
142
143
144
145
    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
146
147
148
149
150
151
152
153
154
155
156
157
    padding_mode_t padding_mode = default_;

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

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

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

Paul's avatar
Paul committed
187
struct pooling
Paul's avatar
Paul committed
188
{
Paul's avatar
Paul committed
189
    std::string mode                   = "average";
Paul's avatar
Paul committed
190
191
192
    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
193
194
195
196
197
198
199
200
201
202
203
204

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

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

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

Paul's avatar
Paul committed
211
        const shape& input = inputs.at(0);
Paul's avatar
Paul committed
212
        auto t             = input.type();
Paul's avatar
Paul committed
213

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

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

Paul's avatar
Paul committed
235
struct activation
Paul's avatar
Paul committed
236
237
{
    std::string mode;
Paul's avatar
Paul committed
238
    std::string name() const { return "activation"; }
Paul's avatar
Paul committed
239
240
    shape compute_shape(std::vector<shape> inputs) const
    {
Paul's avatar
Paul committed
241
        check_shapes{inputs, *this}.has(1);
Paul's avatar
Paul committed
242
243
        return inputs.front();
    }
Paul's avatar
Paul committed
244
    friend std::ostream& operator<<(std::ostream& os, const activation& op)
Paul's avatar
Paul committed
245
    {
Paul's avatar
Paul committed
246
        os << op.name() << ":" << op.mode;
Paul's avatar
Paul committed
247
248
        return os;
    }
Paul's avatar
Paul committed
249
250
};

251
252
253
struct transpose
{
    std::vector<int64_t> dims;
Paul's avatar
Paul committed
254
255
256
257
258
259
260
261
262

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

263
264
265
    std::string name() const { return "transpose"; }
    shape compute_shape(std::vector<shape> inputs) const
    {
Paul's avatar
Paul committed
266
        check_shapes{inputs, *this}.has(1);
267
        auto input         = inputs.at(0);
268
        auto input_lens    = input.lens();
269
270
        auto input_strides = input.strides();
        auto t             = input.type();
Paul's avatar
Paul committed
271
272
        if(dims.size() != input_lens.size())
        {
Paul's avatar
Paul committed
273
            MIGRAPH_THROW("Permutation has wrong number of axes");
274
275
276
        }
        std::vector<int64_t> axes(dims.size());
        std::iota(axes.begin(), axes.end(), 0);
Paul's avatar
Paul committed
277
278
        if(!std::is_permutation(axes.begin(), axes.end(), dims.begin()))
        {
Paul's avatar
Paul committed
279
            MIGRAPH_THROW("Invalid permutation");
280
        }
281
282
        std::vector<size_t> output_lens(input_lens.size());
        std::vector<size_t> output_strides(input_lens.size());
Paul's avatar
Paul committed
283
284
285
        for(int i = 0; i < output_lens.size(); i++)
        {
            output_lens[i]    = input_lens[dims[i]];
286
287
            output_strides[i] = input_strides[dims[i]];
        }
288
        return {t, output_lens, output_strides};
289
    }
Paul's avatar
Paul committed
290
    argument compute(context&, shape output_shape, std::vector<argument> args) const
Paul's avatar
Paul committed
291
    {
Paul's avatar
Paul committed
292
        return {std::move(output_shape), std::move(args.front().data)};
Paul's avatar
Paul committed
293
    }
294
295
};

Paul's avatar
Paul committed
296
struct contiguous
297
298
299
300
{
    std::string name() const { return "contiguous"; }
    shape compute_shape(std::vector<shape> inputs) const
    {
Paul's avatar
Paul committed
301
        check_shapes{inputs, *this}.has(1);
Paul's avatar
Paul committed
302
303
304
305
        auto lens = inputs.at(0).lens();
        auto t    = inputs.at(0).type();
        if(lens.size() < 2)
        {
Paul's avatar
Paul committed
306
            MIGRAPH_THROW("Number of dimensions should exceed 1");
307
308
309
310
311
        }
        return {t, lens};
    }
};

312
313
314
315
316
struct slice
{
    std::vector<int64_t> axes;
    std::vector<int64_t> starts;
    std::vector<int64_t> ends;
Paul's avatar
Paul committed
317
318
319
320
321
322
323
324
325
326
327

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

328
    std::string name() const { return "slice"; }
Scott Thornton's avatar
Scott Thornton committed
329
330

    auto fix_index(const std::vector<std::size_t>& lens, std::size_t axis, int64_t index) const
331
    {
Scott Thornton's avatar
Scott Thornton committed
332
        int64_t r = std::min(index, static_cast<int64_t>(lens[axis]));
Scott Thornton's avatar
Scott Thornton committed
333
334
        if(r < 0)
            r += lens[axis];
Scott Thornton's avatar
Scott Thornton committed
335
        return std::size_t(r);
Scott Thornton's avatar
Scott Thornton committed
336
337
338
339
340
341
342
    }

    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
343
        if(!axes.empty())
Scott Thornton's avatar
Scott Thornton committed
344
        {
Scott Thornton's avatar
Scott Thornton committed
345
346
347
348
349
            for(std::size_t i = 0; i < axes.size(); i++)
            {
                auto axis = axes[i];
                offset += fix_index(lens, axis, starts[i]) * strides[axis];
            }
350
        }
Scott Thornton's avatar
Scott Thornton committed
351
352
        else
        {
Scott Thornton's avatar
Scott Thornton committed
353
354
355
356
            for(std::size_t axis = 0; axis < lens.size(); axis++)
            {
                offset += fix_index(lens, axis, starts[axis]) * strides[axis];
            }
357
        }
Scott Thornton's avatar
Scott Thornton committed
358
359
360
361
362
        return offset;
    }

    shape compute_shape(std::vector<shape> inputs) const
    {
Scott Thornton's avatar
Scott Thornton committed
363
364
365
366
        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
367
368
369
370
371
372
373
374
375
376
        // 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
377
        {
378
379
            MIGRAPH_THROW("inconsistent sizes");
        }
Scott Thornton's avatar
Scott Thornton committed
380
381
        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
382
        {
Scott Thornton's avatar
Scott Thornton committed
383
384
385
            auto axis = axes[i];
            new_lens[axis] =
                fix_index(old_lens, axis, ends[i]) - fix_index(old_lens, axis, starts[i]);
386
387
388
389
390
        }
        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
391
392
393
        auto input  = args[0];
        auto offset = compute_offset(input.get_shape()) * output_shape.type_size();
        return {std::move(output_shape), [=] { return input.data() + offset; }};
394
395
396
397
398
399
    }
};

struct squeeze
{
    std::vector<int64_t> axes;
Paul's avatar
Paul committed
400
401
402
403
404
405
406
407
408

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

409
410
411
412
    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
413
414
        auto type        = input_shape.type();
        auto old_lens    = input_shape.lens();
wsttiger's avatar
wsttiger committed
415
416
        if(std::any_of(
               axes.begin(), axes.end(), [&](auto axis) { return input_shape.lens()[axis] != 1; }))
Scott Thornton's avatar
Scott Thornton committed
417
        {
wsttiger's avatar
wsttiger committed
418
            MIGRAPH_THROW("squeeze axis dimension should be equal to 1");
419
420
        }
        std::vector<std::size_t> new_lens;
Scott Thornton's avatar
Scott Thornton committed
421
        if(axes.empty())
Scott Thornton's avatar
Scott Thornton committed
422
        {
wsttiger's avatar
wsttiger committed
423
424
425
426
            std::copy_if(old_lens.begin(),
                         old_lens.end(),
                         std::back_inserter(new_lens),
                         [](auto len) { return len != 1; });
427
        }
Scott Thornton's avatar
Scott Thornton committed
428
429
430
431
432
433
        else
        {
            for(std::size_t i = 0; i < old_lens.size(); i++)
            {
                if(std::find(axes.begin(), axes.end(), i) == axes.end())
                {
434
435
436
437
438
439
440
441
442
                    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
443
    }
444
445
446
447
448
};

struct unsqueeze
{
    std::vector<int64_t> axes;
Paul's avatar
Paul committed
449
450
451
452
453
454
455
456
457

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

458
459
460
    std::string name() const { return "unsqueeze"; }
    shape compute_shape(std::vector<shape> inputs) const
    {
Scott Thornton's avatar
Scott Thornton committed
461
462
463
        auto input_shape     = inputs[0];
        auto type            = input_shape.type();
        auto old_lens        = input_shape.lens();
464
465
466
        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
467
468
469
470
        for(std::size_t i = 0; i < new_size; i++)
        {
            if(std::find(axes.begin(), axes.end(), i) != axes.end())
            {
471
                new_lens[i] = 1;
Scott Thornton's avatar
Scott Thornton committed
472
473
474
            }
            else
            {
475
476
477
478
479
480
481
482
483
484
485
                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
486
487
488
struct reshape
{
    std::vector<int64_t> dims;
Paul's avatar
Paul committed
489
490
491
492
493
494
495
496
497

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

Paul's avatar
Paul committed
498
    std::string name() const { return "reshape"; }
Paul's avatar
Paul committed
499
500
    shape compute_shape(std::vector<shape> inputs) const
    {
Paul's avatar
Paul committed
501
        check_shapes{inputs, *this}.has(1);
Paul's avatar
Paul committed
502
503
        auto&& idims = inputs.front().lens();
        std::vector<std::size_t> rdims(dims.begin(), dims.end());
504
505
506
        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
507
        for(std::size_t i = 0; i < dims.size(); i++)
Paul's avatar
Paul committed
508
509
510
511
        {
            if(dims[i] == 0)
                rdims[i] = idims[i];
        }
512
513
514
515
516
517
518
519
520
521
522
        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
523
524
525
        if(dims.back() == -1)
        {
            rdims.pop_back();
Paul's avatar
Paul committed
526
            std::copy(idims.begin() + rdims.size(), idims.end(), std::back_inserter(rdims));
Paul's avatar
Paul committed
527
        }
Scott Thornton's avatar
Scott Thornton committed
528
        shape s{inputs.front().type(), rdims};
Paul's avatar
Paul committed
529
        if(s.elements() != inputs.front().elements())
Paul's avatar
Paul committed
530
            MIGRAPH_THROW("Wrong number of elements for reshape");
Scott Thornton's avatar
Scott Thornton committed
531
        return s;
Paul's avatar
Paul committed
532
    }
Paul's avatar
Paul committed
533
    argument compute(context&, shape output_shape, std::vector<argument> args) const
Paul's avatar
Paul committed
534
    {
Paul's avatar
Paul committed
535
        return {std::move(output_shape), std::move(args.front().data)};
Paul's avatar
Paul committed
536
    }
Paul's avatar
Paul committed
537
538
};

539
540
struct gemm
{
Paul's avatar
Paul committed
541
    float alpha = 1.0;
Paul's avatar
Paul committed
542
    float beta  = 0.0;
Paul's avatar
Paul committed
543
544
545
546
547
548
549
550
551
552

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

553
    std::string name() const { return "gemm"; }
554
555
    shape compute_shape(std::vector<shape> inputs) const
    {
Paul's avatar
Paul committed
556
        check_shapes{inputs, *this}.has(2).same_type();
557
558
        const shape& a = inputs.at(0);
        const shape& b = inputs.at(1);
Scott Thornton's avatar
Scott Thornton committed
559
        auto t         = a.type();
560

561
        if(a.lens()[1] != b.lens()[0])
Paul's avatar
Paul committed
562
563
            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
564
        return {t, {a.lens()[0], b.lens()[1]}};
565
566
567
    }
};

568
struct unary
Scott Thornton's avatar
Scott Thornton committed
569
{
570
571
    shape compute_shape(std::vector<shape> inputs) const
    {
572
573
        check_shapes{inputs}.has(1);
        return inputs.at(0);
574
    }
Scott Thornton's avatar
Scott Thornton committed
575
576
};

577
578
struct identity : unary
{
579
    std::string name() const { return "identity"; }
580
581
582
};

struct abs : unary
Scott Thornton's avatar
Scott Thornton committed
583
{
584
    std::string name() const { return "abs"; }
Scott Thornton's avatar
Scott Thornton committed
585
586
};

587
struct exp : unary
Scott Thornton's avatar
Scott Thornton committed
588
{
589
    std::string name() const { return "exp"; }
Scott Thornton's avatar
Scott Thornton committed
590
591
};

592
struct sin : unary
Scott Thornton's avatar
Scott Thornton committed
593
{
594
    std::string name() const { return "sin"; }
Scott Thornton's avatar
Scott Thornton committed
595
596
};

597
struct cos : unary
Scott Thornton's avatar
Scott Thornton committed
598
{
599
    std::string name() const { return "cos"; }
Scott Thornton's avatar
Scott Thornton committed
600
601
};

602
struct tan : unary
Scott Thornton's avatar
Scott Thornton committed
603
{
604
    std::string name() const { return "tan"; }
Scott Thornton's avatar
Scott Thornton committed
605
606
};

607
struct asin : unary
Scott Thornton's avatar
Scott Thornton committed
608
{
609
    std::string name() const { return "asin"; }
Scott Thornton's avatar
Scott Thornton committed
610
611
};

612
struct acos : unary
Scott Thornton's avatar
Scott Thornton committed
613
{
614
    std::string name() const { return "acos"; }
Scott Thornton's avatar
Scott Thornton committed
615
616
};

617
struct atan : unary
Scott Thornton's avatar
Scott Thornton committed
618
{
619
    std::string name() const { return "atan"; }
Scott Thornton's avatar
Scott Thornton committed
620
621
};

622
struct tanh : unary
Scott Thornton's avatar
Scott Thornton committed
623
{
624
    std::string name() const { return "tanh"; }
Scott Thornton's avatar
Scott Thornton committed
625
626
};

627
struct sigmoid : unary
Scott Thornton's avatar
Scott Thornton committed
628
{
629
    std::string name() const { return "sigmoid"; }
Scott Thornton's avatar
Scott Thornton committed
630
631
};

632
struct neg : unary
Scott Thornton's avatar
Scott Thornton committed
633
{
634
    std::string name() const { return "neg"; }
Scott Thornton's avatar
Scott Thornton committed
635
636
};

Paul's avatar
Paul committed
637
638
639
640
641
642
643
644
645
646
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);
    }
};

647
struct flatten
Scott Thornton's avatar
Scott Thornton committed
648
{
Paul's avatar
Paul committed
649
    uint64_t axis = 0;
Paul's avatar
Paul committed
650
651
652
653
654
655
656
657
658

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

Scott Thornton's avatar
Scott Thornton committed
659
    std::string name() const { return "flatten"; }
Paul's avatar
Paul committed
660
661
662
    shape compute_shape(std::vector<shape> inputs) const
    {
        check_shapes{inputs}.has(1);
Paul's avatar
Paul committed
663
664
        auto&& lens = inputs.front().lens();

Paul's avatar
Paul committed
665
        if(axis > lens.size())
Paul's avatar
Paul committed
666
        {
Paul's avatar
Paul committed
667
            MIGRAPH_THROW("axis for flatten must be less than tensor rank");
Paul's avatar
Paul committed
668
        }
Paul's avatar
Paul committed
669
670
671
672
        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<>{});
673
        return {inputs.at(0).type(), {x, y}};
Paul's avatar
Paul committed
674
675
676
    }
    argument compute(context&, shape output_shape, std::vector<argument> args) const
    {
Paul's avatar
Paul committed
677
        return {std::move(output_shape), std::move(args.front().data)};
Paul's avatar
Paul committed
678
    }
Scott Thornton's avatar
Scott Thornton committed
679
};
680
681
682
struct broadcast
{
    uint64_t axis = 0;
Paul's avatar
Paul committed
683
684
685
686
687
688
689
690
691

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

Scott Thornton's avatar
Scott Thornton committed
692
    shape broadcast_shape;
693
694
695
    std::string name() const { return "broadcast"; }
    shape compute_shape(std::vector<shape> inputs) const
    {
Scott Thornton's avatar
Scott Thornton committed
696
697
        auto t     = inputs.at(0).type();
        auto input = inputs.at(0);
Paul's avatar
Paul committed
698

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

Scott Thornton's avatar
Scott Thornton committed
701
702
703
        if(std::all_of(broadcast_shape.lens().cbegin(), broadcast_shape.lens().cend(), [&](auto x) {
               return x == 1;
           }))
704
        {
Scott Thornton's avatar
Scott Thornton committed
705
            if(axis != 0)
Paul's avatar
Paul committed
706
                MIGRAPH_THROW("when broadcasting tensor of size 1, axis should be 0");
Scott Thornton's avatar
Scott Thornton committed
707
            return {t, broadcast_shape.lens(), std::move(bcast_strides)};
708
709
710
        }
        else
        {
Scott Thornton's avatar
Scott Thornton committed
711
            assert(broadcast_shape.lens().size() - axis >= input.lens().size());
Scott Thornton's avatar
Scott Thornton committed
712
713
            if(!std::equal(
                   input.lens().begin(), input.lens().end(), broadcast_shape.lens().begin() + axis))
Paul's avatar
Paul committed
714
                MIGRAPH_THROW("when broadcasting success sizes must match");
Paul's avatar
Paul committed
715
            std::copy(input.strides().begin(), input.strides().end(), bcast_strides.begin() + axis);
Scott Thornton's avatar
Scott Thornton committed
716
            return {t, broadcast_shape.lens(), std::move(bcast_strides)};
717
718
        }
    }
Paul's avatar
Paul committed
719
    argument compute(context&, shape output_shape, std::vector<argument> args) const
Scott Thornton's avatar
Scott Thornton committed
720
    {
Scott Thornton's avatar
Scott Thornton committed
721
        return {std::move(output_shape), std::move(args.at(0).data)};
Scott Thornton's avatar
Scott Thornton committed
722
    }
723
724
};

725
struct binary
Scott Thornton's avatar
Scott Thornton committed
726
{
727
728
    shape compute_shape(std::vector<shape> inputs) const
    {
729
730
        check_shapes{inputs}.has(2).same_type().same_dims();
        return inputs.at(0);
731
    }
Scott Thornton's avatar
Scott Thornton committed
732
733
};

734
735
736
737
738
739
struct add : binary
{
    std::string name() const { return "add"; }
};

struct sub : binary
Scott Thornton's avatar
Scott Thornton committed
740
741
742
743
{
    std::string name() const { return "sub"; }
};

744
struct mul : binary
Scott Thornton's avatar
Scott Thornton committed
745
746
747
748
{
    std::string name() const { return "mul"; }
};

749
struct div : binary
Scott Thornton's avatar
Scott Thornton committed
750
751
752
753
{
    std::string name() const { return "div"; }
};

Paul's avatar
Paul committed
754
755
756
757
struct load
{
    shape s;
    std::size_t offset = 0;
Paul's avatar
Paul committed
758
759
760
761
762
763
764
765
766
767

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

Paul's avatar
Paul committed
768
769
770
771
772
773
774
775
776
777
778
779
    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
780
struct outline
Scott Thornton's avatar
Scott Thornton committed
781
{
Paul's avatar
Paul committed
782
    shape s;
Paul's avatar
Paul committed
783
784
785
786
787
788
789
790
791

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

Paul's avatar
Paul committed
792
    std::string name() const { return "outline"; }
Paul's avatar
Paul committed
793
    shape compute_shape(const std::vector<shape>& inputs) const
Paul's avatar
Paul committed
794
    {
Paul's avatar
Paul committed
795
        check_shapes{inputs, *this}.has(0);
Paul's avatar
Paul committed
796
797
        return s;
    }
Paul's avatar
Paul committed
798
799
800
801
    argument compute(context&, const shape&, const std::vector<argument>&) const
    {
        return {s, nullptr};
    }
Scott Thornton's avatar
Scott Thornton committed
802
803
};

804
} // namespace op
Paul's avatar
Paul committed
805
} // namespace migraph
Paul's avatar
Paul committed
806
807

#endif