operators.hpp 15.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

Paul's avatar
Paul committed
11
namespace migraph {
Paul's avatar
Paul committed
12

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

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

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

28
29
30
31
32
33
34
35
    enum bn_infer_mode_t
    {
        per_activation,
        spatial,
    };

    bn_infer_mode_t bn_mode = spatial;

36
37
    bool is_test = false;

38
39
40
41
42
43
44
45
46
47
48
49
    shape compute_shape(std::vector<shape> inputs) const
    {
        check_shapes{inputs, *this}.has(5);
        return inputs.front();
    }

    argument compute(context&, shape, std::vector<argument>) const
    {
        MIGRAPH_THROW("not computable");
    }
};

Paul's avatar
Paul committed
50
struct convolution
Paul's avatar
Paul committed
51
{
Paul's avatar
Paul committed
52
53
54
    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
55
56
57
58
59
60
61
    enum padding_mode_t
    {
        default_, // NOLINT
        same,
        valid
    };
    padding_mode_t padding_mode = default_;
Paul's avatar
Paul committed
62
    std::string name() const { return "convolution"; }
Paul's avatar
Paul committed
63
64
    shape compute_shape(std::vector<shape> inputs) const
    {
Paul's avatar
Paul committed
65
        check_shapes{inputs, *this}.has(2).same_type().same_ndims().only_dims(4);
Paul's avatar
Paul committed
66

Paul's avatar
Paul committed
67
        const shape& input   = inputs.at(0);
Paul's avatar
Paul committed
68
        const shape& weights = inputs.at(1);
Paul's avatar
Paul committed
69
        auto t               = input.type();
Paul's avatar
Paul committed
70
71
        if(padding_mode == default_)
        {
Paul's avatar
Paul committed
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
            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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
        }
        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
113
            MIGRAPH_THROW("Invalid padding mode");
Paul's avatar
Paul committed
114
        }
Paul's avatar
Paul committed
115
    }
Paul's avatar
Paul committed
116

Paul's avatar
Paul committed
117
118
119
120
    argument compute(context&, shape, std::vector<argument>) const
    {
        MIGRAPH_THROW("not computable");
    }
Paul's avatar
Paul committed
121

Paul's avatar
Paul committed
122
    friend std::ostream& operator<<(std::ostream& os, const convolution& op)
Paul's avatar
Paul committed
123
    {
Paul's avatar
Paul committed
124
125
126
127
128
        os << op.name() << "[";
        os << "padding={" << stream_range(op.padding) << "}, ";
        os << "stride={" << stream_range(op.stride) << "}, ";
        os << "dilation={" << stream_range(op.dilation) << "}";
        os << "]";
Paul's avatar
Paul committed
129
130
        return os;
    }
Paul's avatar
Paul committed
131
132
};

Paul's avatar
Paul committed
133
struct pooling
Paul's avatar
Paul committed
134
135
{
    std::string mode;
Paul's avatar
Paul committed
136
137
138
    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
139
    std::string name() const { return "pooling"; }
Scott Thornton's avatar
Scott Thornton committed
140

Paul's avatar
Paul committed
141
142
    shape compute_shape(std::vector<shape> inputs) const
    {
Paul's avatar
Paul committed
143
        check_shapes{inputs, *this}.has(1).only_dims(4);
Paul's avatar
Paul committed
144

Paul's avatar
Paul committed
145
        const shape& input = inputs.at(0);
Paul's avatar
Paul committed
146
        auto t             = input.type();
Paul's avatar
Paul committed
147

148
149
        // assert(lengths[0] < (input.lens()[2] + 2 * padding[0]));
        // assert(lengths[1] < (input.lens()[3] + 2 * padding[1]));
Paul's avatar
Paul committed
150

Scott Thornton's avatar
Scott Thornton committed
151
152
153
154
155
156
        return {t,
                {
                    input.lens()[0],
                    input.lens()[1],
                    std::size_t(std::max<std::ptrdiff_t>(
                        1,
157
                        std::ptrdiff_t(std::floor((input.lens()[2] + 2 * padding[0] - lengths[0]) /
Paul's avatar
Paul committed
158
                                                 static_cast<float>(stride[0]))) +
Scott Thornton's avatar
Scott Thornton committed
159
160
161
                            1)),
                    std::size_t(std::max<std::ptrdiff_t>(
                        1,
162
                        std::ptrdiff_t(std::floor((input.lens()[3] + 2 * padding[1] - lengths[1]) /
Paul's avatar
Paul committed
163
                                                 static_cast<float>(stride[1]))) +
Scott Thornton's avatar
Scott Thornton committed
164
                            1)),
165
166
167
168
169
170
171
172
173
174
                    // std::size_t(std::max<std::ptrdiff_t>(
                    //         1,
                    //         std::ptrdiff_t((input.lens()[2] + 2 * padding[0] - lengths[0]) /
                    //                                  static_cast<float>(stride[0])) +
                    //         1)),
                    // std::size_t(std::max<std::ptrdiff_t>(
                    //         1,
                    //         std::ptrdiff_t((input.lens()[3] + 2 * padding[1] - lengths[1]) /
                    //                                  static_cast<float>(stride[1])) +
                    //         1)),
Scott Thornton's avatar
Scott Thornton committed
175
                }};
Paul's avatar
Paul committed
176
    }
Paul's avatar
Paul committed
177

Paul's avatar
Paul committed
178
179
180
181
    argument compute(context&, shape, std::vector<argument>) const
    {
        MIGRAPH_THROW("not computable");
    }
Paul's avatar
Paul committed
182

Paul's avatar
Paul committed
183
    friend std::ostream& operator<<(std::ostream& os, const pooling& op)
Paul's avatar
Paul committed
184
    {
Paul's avatar
Paul committed
185
186
187
188
189
        os << op.name() << "[";
        os << "padding={" << stream_range(op.padding) << "}, ";
        os << "stride={" << stream_range(op.stride) << "}, ";
        os << "lengths={" << stream_range(op.lengths) << "}";
        os << "]";
Paul's avatar
Paul committed
190
191
        return os;
    }
Paul's avatar
Paul committed
192
193
};

Paul's avatar
Paul committed
194
struct activation
Paul's avatar
Paul committed
195
196
{
    std::string mode;
Paul's avatar
Paul committed
197
    std::string name() const { return "activation"; }
Paul's avatar
Paul committed
198
199
    shape compute_shape(std::vector<shape> inputs) const
    {
Paul's avatar
Paul committed
200
        check_shapes{inputs, *this}.has(1);
Paul's avatar
Paul committed
201
202
        return inputs.front();
    }
Paul's avatar
Paul committed
203

Paul's avatar
Paul committed
204
205
206
207
    argument compute(context&, shape, std::vector<argument>) const
    {
        MIGRAPH_THROW("not computable");
    }
Paul's avatar
Paul committed
208
    friend std::ostream& operator<<(std::ostream& os, const activation& op)
Paul's avatar
Paul committed
209
    {
Paul's avatar
Paul committed
210
        os << op.name() << ":" << op.mode;
Paul's avatar
Paul committed
211
212
        return os;
    }
Paul's avatar
Paul committed
213
214
};

215
216
217
218
219
220
struct transpose
{
    std::vector<int64_t> dims;
    std::string name() const { return "transpose"; }
    shape compute_shape(std::vector<shape> inputs) const
    {
Paul's avatar
Paul committed
221
        check_shapes{inputs, *this}.has(1);
222
        auto input         = inputs.at(0);
223
        auto input_lens    = input.lens();
224
225
        auto input_strides = input.strides();
        auto t             = input.type();
Paul's avatar
Paul committed
226
227
        if(dims.size() != input_lens.size())
        {
Paul's avatar
Paul committed
228
            MIGRAPH_THROW("Permutation has wrong number of axes");
229
230
231
        }
        std::vector<int64_t> axes(dims.size());
        std::iota(axes.begin(), axes.end(), 0);
Paul's avatar
Paul committed
232
233
        if(!std::is_permutation(axes.begin(), axes.end(), dims.begin()))
        {
Paul's avatar
Paul committed
234
            MIGRAPH_THROW("Invalid permutation");
235
        }
236
237
        std::vector<size_t> output_lens(input_lens.size());
        std::vector<size_t> output_strides(input_lens.size());
Paul's avatar
Paul committed
238
239
240
        for(int i = 0; i < output_lens.size(); i++)
        {
            output_lens[i]    = input_lens[dims[i]];
241
242
            output_strides[i] = input_strides[dims[i]];
        }
243
        return {t, output_lens, output_strides};
244
    }
Paul's avatar
Paul committed
245
    argument compute(context&, shape output_shape, std::vector<argument> args) const
Paul's avatar
Paul committed
246
    {
Paul's avatar
Paul committed
247
        return {output_shape, std::move(args.front().data)};
Paul's avatar
Paul committed
248
    }
249
250
};

Paul's avatar
Paul committed
251
struct contiguous
252
253
254
255
{
    std::string name() const { return "contiguous"; }
    shape compute_shape(std::vector<shape> inputs) const
    {
Paul's avatar
Paul committed
256
        check_shapes{inputs, *this}.has(1);
Paul's avatar
Paul committed
257
258
259
260
        auto lens = inputs.at(0).lens();
        auto t    = inputs.at(0).type();
        if(lens.size() < 2)
        {
Paul's avatar
Paul committed
261
            MIGRAPH_THROW("Number of dimensions should exceed 1");
262
263
264
        }
        return {t, lens};
    }
Paul's avatar
Paul committed
265
266
267
268
    argument compute(context&, shape, std::vector<argument>) const
    {
        MIGRAPH_THROW("not computable");
    }
269
270
};

Paul's avatar
Paul committed
271
272
273
struct reshape
{
    std::vector<int64_t> dims;
Paul's avatar
Paul committed
274
    std::string name() const { return "reshape"; }
Paul's avatar
Paul committed
275
276
    shape compute_shape(std::vector<shape> inputs) const
    {
Paul's avatar
Paul committed
277
        check_shapes{inputs, *this}.has(1);
Paul's avatar
Paul committed
278
279
        auto&& idims = inputs.front().lens();
        std::vector<std::size_t> rdims(dims.begin(), dims.end());
280
281
282
        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
283
        for(std::size_t i = 0; i < dims.size(); i++)
Paul's avatar
Paul committed
284
285
286
287
        {
            if(dims[i] == 0)
                rdims[i] = idims[i];
        }
288
289
290
291
292
293
294
295
296
297
298
        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
299
300
301
        if(dims.back() == -1)
        {
            rdims.pop_back();
Paul's avatar
Paul committed
302
            std::copy(idims.begin() + rdims.size(), idims.end(), std::back_inserter(rdims));
Paul's avatar
Paul committed
303
        }
Scott Thornton's avatar
Scott Thornton committed
304
        shape s{inputs.front().type(), rdims};
Paul's avatar
Paul committed
305
        if(s.elements() != inputs.front().elements())
Paul's avatar
Paul committed
306
            MIGRAPH_THROW("Wrong number of elements for reshape");
Scott Thornton's avatar
Scott Thornton committed
307
        return s;
Paul's avatar
Paul committed
308
309
    }

Paul's avatar
Paul committed
310
    argument compute(context&, shape output_shape, std::vector<argument> args) const
Paul's avatar
Paul committed
311
    {
Paul's avatar
Paul committed
312
        return {output_shape, std::move(args.front().data)};
Paul's avatar
Paul committed
313
    }
Paul's avatar
Paul committed
314

Paul's avatar
Paul committed
315
    friend std::ostream& operator<<(std::ostream& os, const reshape& op)
Paul's avatar
Paul committed
316
    {
Paul's avatar
Paul committed
317
318
319
        os << op.name() << "[";
        os << "dims={" << stream_range(op.dims) << "}, ";
        os << "]";
Paul's avatar
Paul committed
320
321
        return os;
    }
Paul's avatar
Paul committed
322
323
};

324
325
struct gemm
{
Paul's avatar
Paul committed
326
    float alpha = 1.0;
Paul's avatar
Paul committed
327
    float beta  = 0.0;
328
    std::string name() const { return "gemm"; }
329
330
    shape compute_shape(std::vector<shape> inputs) const
    {
Paul's avatar
Paul committed
331
        check_shapes{inputs, *this}.has(2).same_type();
332
333
        const shape& a = inputs.at(0);
        const shape& b = inputs.at(1);
Scott Thornton's avatar
Scott Thornton committed
334
        auto t         = a.type();
335

336
        if(a.lens()[1] != b.lens()[0])
Paul's avatar
Paul committed
337
338
            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
339
        return {t, {a.lens()[0], b.lens()[1]}};
340
    }
341

Paul's avatar
Paul committed
342
343
344
345
    argument compute(context&, shape, std::vector<argument>) const
    {
        MIGRAPH_THROW("not computable");
    }
346
347

    friend std::ostream& operator<<(std::ostream& os, const gemm& op)
348
349
    {
        os << op.name() << "[";
350
        os << "]";
Scott Thornton's avatar
Scott Thornton committed
351
        return os;
352
353
354
    }
};

355
struct unary
Scott Thornton's avatar
Scott Thornton committed
356
{
357
358
    shape compute_shape(std::vector<shape> inputs) const
    {
359
360
        check_shapes{inputs}.has(1);
        return inputs.at(0);
361
    }
Paul's avatar
Paul committed
362
363
364
365
    argument compute(context&, shape, std::vector<argument>) const
    {
        MIGRAPH_THROW("not computable");
    }
Scott Thornton's avatar
Scott Thornton committed
366
367
};

368
369
struct identity : unary
{
370
    std::string name() const { return "identity"; }
371
372
373
};

struct abs : unary
Scott Thornton's avatar
Scott Thornton committed
374
{
375
    std::string name() const { return "abs"; }
Scott Thornton's avatar
Scott Thornton committed
376
377
};

378
struct exp : unary
Scott Thornton's avatar
Scott Thornton committed
379
{
380
    std::string name() const { return "exp"; }
Scott Thornton's avatar
Scott Thornton committed
381
382
};

383
struct sin : unary
Scott Thornton's avatar
Scott Thornton committed
384
{
385
    std::string name() const { return "sin"; }
Scott Thornton's avatar
Scott Thornton committed
386
387
};

388
struct cos : unary
Scott Thornton's avatar
Scott Thornton committed
389
{
390
    std::string name() const { return "cos"; }
Scott Thornton's avatar
Scott Thornton committed
391
392
};

393
struct tan : unary
Scott Thornton's avatar
Scott Thornton committed
394
{
395
    std::string name() const { return "tan"; }
Scott Thornton's avatar
Scott Thornton committed
396
397
};

398
struct asin : unary
Scott Thornton's avatar
Scott Thornton committed
399
{
400
    std::string name() const { return "asin"; }
Scott Thornton's avatar
Scott Thornton committed
401
402
};

403
struct acos : unary
Scott Thornton's avatar
Scott Thornton committed
404
{
405
    std::string name() const { return "acos"; }
Scott Thornton's avatar
Scott Thornton committed
406
407
};

408
struct atan : unary
Scott Thornton's avatar
Scott Thornton committed
409
{
410
    std::string name() const { return "atan"; }
Scott Thornton's avatar
Scott Thornton committed
411
412
};

413
struct softmax : unary
Scott Thornton's avatar
Scott Thornton committed
414
{
415
    std::string name() const { return "softmax"; }
Scott Thornton's avatar
Scott Thornton committed
416
417
};

418
struct tanh : unary
Scott Thornton's avatar
Scott Thornton committed
419
{
420
    std::string name() const { return "tanh"; }
Scott Thornton's avatar
Scott Thornton committed
421
422
};

423
struct sigmoid : unary
Scott Thornton's avatar
Scott Thornton committed
424
{
425
    std::string name() const { return "sigmoid"; }
Scott Thornton's avatar
Scott Thornton committed
426
427
};

428
struct neg : unary
Scott Thornton's avatar
Scott Thornton committed
429
{
430
    std::string name() const { return "neg"; }
Scott Thornton's avatar
Scott Thornton committed
431
432
};

433
struct flatten
Scott Thornton's avatar
Scott Thornton committed
434
{
Scott Thornton's avatar
Scott Thornton committed
435
    uint64_t axis = 0;
Scott Thornton's avatar
Scott Thornton committed
436
    std::string name() const { return "flatten"; }
Scott Thornton's avatar
Scott Thornton committed
437
438
439
    shape compute_shape(std::vector<shape> inputs) const
    {
        check_shapes{inputs}.has(1);
Scott Thornton's avatar
Scott Thornton committed
440
        if(axis == 0)
Scott Thornton's avatar
Scott Thornton committed
441
442
443
        {
            return {inputs.at(0).type(), {1, inputs.at(0).elements()}};
        }
Scott Thornton's avatar
Scott Thornton committed
444
        if(axis == 1)
Scott Thornton's avatar
Scott Thornton committed
445
446
447
448
449
450
451
452
453
454
455
456
        {
            return {inputs.at(0).type(), {inputs.at(0).elements(), 1}};
        }
        else
        {
            MIGRAPH_THROW("axis can only be either 0 or 1");
        }
    }
    argument compute(context&, shape output_shape, std::vector<argument> args) const
    {
        return {output_shape, std::move(args.front().data)};
    }
Scott Thornton's avatar
Scott Thornton committed
457
458
};

459
460
461
462
463
464
struct broadcast
{
    uint64_t axis = 0;
    std::string name() const { return "broadcast"; }
    shape compute_shape(std::vector<shape> inputs) const
    {
Paul's avatar
Paul committed
465
466
467
468
        auto t      = inputs.at(0).type();
        auto result = inputs.at(0);
        auto input  = inputs.at(1);

Paul's avatar
Paul committed
469
        std::vector<size_t> bcast_strides(result.lens().size(), 0);
470

Paul's avatar
Paul committed
471
472
        if(std::all_of(
               result.lens().cbegin(), result.lens().cend(), [&](auto x) { return x == 1; }))
473
        {
Scott Thornton's avatar
Scott Thornton committed
474
            if(axis != 0)
Paul's avatar
Paul committed
475
                MIGRAPH_THROW("when broadcasting tensor of size 1, axis should be 0");
Paul's avatar
Paul committed
476
            return {t, result.lens(), std::move(bcast_strides)};
477
478
479
        }
        else
        {
Paul's avatar
Paul committed
480
481
            assert(result.lens().size() - axis >= input.lens().size());
            if(!std::equal(input.lens().begin(), input.lens().end(), result.lens().begin() + axis))
Paul's avatar
Paul committed
482
                MIGRAPH_THROW("when broadcasting success sizes must match");
Paul's avatar
Paul committed
483
            std::copy(input.strides().begin(), input.strides().end(), bcast_strides.begin() + axis);
Paul's avatar
Paul committed
484
            return {t, result.lens(), std::move(bcast_strides)};
485
486
        }
    }
Paul's avatar
Paul committed
487
    argument compute(context&, shape output_shape, std::vector<argument> args) const
Scott Thornton's avatar
Scott Thornton committed
488
    {
489
        return {output_shape, std::move(args.at(1).data)};
Scott Thornton's avatar
Scott Thornton committed
490
    }
491
492
};

493
struct binary
Scott Thornton's avatar
Scott Thornton committed
494
{
495
    uint64_t broadcast = 0;
496
497
    shape compute_shape(std::vector<shape> inputs) const
    {
498
499
        check_shapes{inputs}.has(2).same_type().same_dims();
        return inputs.at(0);
500
    }
Paul's avatar
Paul committed
501
502
503
504
    argument compute(context&, shape, std::vector<argument>) const
    {
        MIGRAPH_THROW("not computable");
    }
Scott Thornton's avatar
Scott Thornton committed
505
506
};

507
508
509
510
511
512
struct add : binary
{
    std::string name() const { return "add"; }
};

struct sub : binary
Scott Thornton's avatar
Scott Thornton committed
513
514
515
516
{
    std::string name() const { return "sub"; }
};

517
struct mul : binary
Scott Thornton's avatar
Scott Thornton committed
518
519
520
521
{
    std::string name() const { return "mul"; }
};

522
struct div : binary
Scott Thornton's avatar
Scott Thornton committed
523
524
525
526
{
    std::string name() const { return "div"; }
};

Paul's avatar
Paul committed
527
struct outline
Scott Thornton's avatar
Scott Thornton committed
528
{
Paul's avatar
Paul committed
529
530
531
532
    shape s;
    std::string name() const { return "outline"; }
    shape compute_shape(std::vector<shape> inputs) const
    {
Paul's avatar
Paul committed
533
        check_shapes{inputs, *this}.has(0);
Paul's avatar
Paul committed
534
535
        return s;
    }
Paul's avatar
Paul committed
536
    argument compute(context&, shape, std::vector<argument>) const { return {s, nullptr}; }
Scott Thornton's avatar
Scott Thornton committed
537
538
};

Paul's avatar
Paul committed
539
} // namespace migraph
Paul's avatar
Paul committed
540
541

#endif