operators.hpp 13.5 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
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
struct batch_norm_inference
{
    double epsilon = 1.0e-6;

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

    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
39
struct convolution
Paul's avatar
Paul committed
40
{
Paul's avatar
Paul committed
41
42
43
    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
44
45
46
47
48
49
50
    enum padding_mode_t
    {
        default_, // NOLINT
        same,
        valid
    };
    padding_mode_t padding_mode = default_;
Paul's avatar
Paul committed
51
    std::string name() const { return "convolution"; }
Paul's avatar
Paul committed
52
53
    shape compute_shape(std::vector<shape> inputs) const
    {
Paul's avatar
Paul committed
54
        check_shapes{inputs, *this}.has(2).same_type().same_ndims().only_dims(4);
Paul's avatar
Paul committed
55

Paul's avatar
Paul committed
56
        const shape& input   = inputs.at(0);
Paul's avatar
Paul committed
57
        const shape& weights = inputs.at(1);
Paul's avatar
Paul committed
58
        auto t               = input.type();
Paul's avatar
Paul committed
59
60
        if(padding_mode == default_)
        {
Paul's avatar
Paul committed
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
            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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
        }
        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
102
            MIGRAPH_THROW("Invalid padding mode");
Paul's avatar
Paul committed
103
        }
Paul's avatar
Paul committed
104
    }
Paul's avatar
Paul committed
105

Paul's avatar
Paul committed
106
107
108
109
    argument compute(context&, shape, std::vector<argument>) const
    {
        MIGRAPH_THROW("not computable");
    }
Paul's avatar
Paul committed
110

Paul's avatar
Paul committed
111
    friend std::ostream& operator<<(std::ostream& os, const convolution& op)
Paul's avatar
Paul committed
112
    {
Paul's avatar
Paul committed
113
114
115
116
117
        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
118
119
        return os;
    }
Paul's avatar
Paul committed
120
121
};

Paul's avatar
Paul committed
122
struct pooling
Paul's avatar
Paul committed
123
124
{
    std::string mode;
Paul's avatar
Paul committed
125
126
127
    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
128
    std::string name() const { return "pooling"; }
Scott Thornton's avatar
Scott Thornton committed
129

Paul's avatar
Paul committed
130
131
    shape compute_shape(std::vector<shape> inputs) const
    {
Paul's avatar
Paul committed
132
        check_shapes{inputs, *this}.has(1).only_dims(4);
Paul's avatar
Paul committed
133

Paul's avatar
Paul committed
134
        const shape& input = inputs.at(0);
Paul's avatar
Paul committed
135
        auto t             = input.type();
Paul's avatar
Paul committed
136

Paul's avatar
Paul committed
137
138
        assert(lengths[0] < (input.lens()[2] + 2 * padding[0]));
        assert(lengths[1] < (input.lens()[3] + 2 * padding[1]));
Paul's avatar
Paul committed
139

Scott Thornton's avatar
Scott Thornton committed
140
141
142
143
144
145
        return {t,
                {
                    input.lens()[0],
                    input.lens()[1],
                    std::size_t(std::max<std::ptrdiff_t>(
                        1,
Paul's avatar
Paul committed
146
                        std::ptrdiff_t(std::ceil((input.lens()[2] + 2 * padding[0] - lengths[0]) /
Paul's avatar
Paul committed
147
                                                 static_cast<float>(stride[0]))) +
Scott Thornton's avatar
Scott Thornton committed
148
149
150
                            1)),
                    std::size_t(std::max<std::ptrdiff_t>(
                        1,
Paul's avatar
Paul committed
151
                        std::ptrdiff_t(std::ceil((input.lens()[3] + 2 * padding[1] - lengths[1]) /
Paul's avatar
Paul committed
152
                                                 static_cast<float>(stride[1]))) +
Scott Thornton's avatar
Scott Thornton committed
153
154
                            1)),
                }};
Paul's avatar
Paul committed
155
    }
Paul's avatar
Paul committed
156

Paul's avatar
Paul committed
157
158
159
160
    argument compute(context&, shape, std::vector<argument>) const
    {
        MIGRAPH_THROW("not computable");
    }
Paul's avatar
Paul committed
161

Paul's avatar
Paul committed
162
    friend std::ostream& operator<<(std::ostream& os, const pooling& op)
Paul's avatar
Paul committed
163
    {
Paul's avatar
Paul committed
164
165
166
167
168
        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
169
170
        return os;
    }
Paul's avatar
Paul committed
171
172
};

Paul's avatar
Paul committed
173
struct activation
Paul's avatar
Paul committed
174
175
{
    std::string mode;
Paul's avatar
Paul committed
176
    std::string name() const { return "activation"; }
Paul's avatar
Paul committed
177
178
    shape compute_shape(std::vector<shape> inputs) const
    {
Paul's avatar
Paul committed
179
        check_shapes{inputs, *this}.has(1);
Paul's avatar
Paul committed
180
181
        return inputs.front();
    }
Paul's avatar
Paul committed
182

Paul's avatar
Paul committed
183
184
185
186
    argument compute(context&, shape, std::vector<argument>) const
    {
        MIGRAPH_THROW("not computable");
    }
Paul's avatar
Paul committed
187
    friend std::ostream& operator<<(std::ostream& os, const activation& op)
Paul's avatar
Paul committed
188
    {
Paul's avatar
Paul committed
189
        os << op.name() << ":" << op.mode;
Paul's avatar
Paul committed
190
191
        return os;
    }
Paul's avatar
Paul committed
192
193
};

194
195
196
197
198
199
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
200
        check_shapes{inputs, *this}.has(1);
201
        auto input         = inputs.at(0);
202
        auto input_lens    = input.lens();
203
204
        auto input_strides = input.strides();
        auto t             = input.type();
Paul's avatar
Paul committed
205
206
        if(dims.size() != input_lens.size())
        {
Paul's avatar
Paul committed
207
            MIGRAPH_THROW("Permutation has wrong number of axes");
208
209
210
        }
        std::vector<int64_t> axes(dims.size());
        std::iota(axes.begin(), axes.end(), 0);
Paul's avatar
Paul committed
211
212
        if(!std::is_permutation(axes.begin(), axes.end(), dims.begin()))
        {
Paul's avatar
Paul committed
213
            MIGRAPH_THROW("Invalid permutation");
214
        }
215
216
        std::vector<size_t> output_lens(input_lens.size());
        std::vector<size_t> output_strides(input_lens.size());
Paul's avatar
Paul committed
217
218
219
        for(int i = 0; i < output_lens.size(); i++)
        {
            output_lens[i]    = input_lens[dims[i]];
220
221
            output_strides[i] = input_strides[dims[i]];
        }
222
        return {t, output_lens, output_strides};
223
    }
Paul's avatar
Paul committed
224
225
226
227
    argument compute(context&, shape, std::vector<argument>) const
    {
        MIGRAPH_THROW("not computable");
    }
228
229
};

Paul's avatar
Paul committed
230
struct contiguous
231
232
233
234
{
    std::string name() const { return "contiguous"; }
    shape compute_shape(std::vector<shape> inputs) const
    {
Paul's avatar
Paul committed
235
        check_shapes{inputs, *this}.has(1);
Paul's avatar
Paul committed
236
237
238
239
        auto lens = inputs.at(0).lens();
        auto t    = inputs.at(0).type();
        if(lens.size() < 2)
        {
Paul's avatar
Paul committed
240
            MIGRAPH_THROW("Number of dimensions should exceed 1");
241
242
243
        }
        return {t, lens};
    }
Paul's avatar
Paul committed
244
245
246
247
    argument compute(context&, shape, std::vector<argument>) const
    {
        MIGRAPH_THROW("not computable");
    }
248
249
};

Paul's avatar
Paul committed
250
251
252
struct reshape
{
    std::vector<int64_t> dims;
Paul's avatar
Paul committed
253
    std::string name() const { return "reshape"; }
Paul's avatar
Paul committed
254
255
    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
        auto&& idims = inputs.front().lens();
        std::vector<std::size_t> rdims(dims.begin(), dims.end());
259
260
261
        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
262
        for(std::size_t i = 0; i < dims.size(); i++)
Paul's avatar
Paul committed
263
264
265
266
        {
            if(dims[i] == 0)
                rdims[i] = idims[i];
        }
267
268
269
270
271
272
273
274
275
276
277
        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
278
279
280
        if(dims.back() == -1)
        {
            rdims.pop_back();
Paul's avatar
Paul committed
281
            std::copy(idims.begin() + rdims.size(), idims.end(), std::back_inserter(rdims));
Paul's avatar
Paul committed
282
        }
Scott Thornton's avatar
Scott Thornton committed
283
        shape s{inputs.front().type(), rdims};
Paul's avatar
Paul committed
284
        if(s.elements() != inputs.front().elements())
Paul's avatar
Paul committed
285
            MIGRAPH_THROW("Wrong number of elements for reshape");
Scott Thornton's avatar
Scott Thornton committed
286
        return s;
Paul's avatar
Paul committed
287
288
    }

Paul's avatar
Paul committed
289
290
291
292
    argument compute(context&, shape, std::vector<argument>) const
    {
        MIGRAPH_THROW("not computable");
    }
Paul's avatar
Paul committed
293

Paul's avatar
Paul committed
294
    friend std::ostream& operator<<(std::ostream& os, const reshape& op)
Paul's avatar
Paul committed
295
    {
Paul's avatar
Paul committed
296
297
298
        os << op.name() << "[";
        os << "dims={" << stream_range(op.dims) << "}, ";
        os << "]";
Paul's avatar
Paul committed
299
300
        return os;
    }
Paul's avatar
Paul committed
301
302
};

303
304
struct gemm
{
305
    std::string name() const { return "gemm"; }
306
307
    shape compute_shape(std::vector<shape> inputs) const
    {
Paul's avatar
Paul committed
308
        check_shapes{inputs, *this}.has(2).same_type();
309
310
        const shape& a = inputs.at(0);
        const shape& b = inputs.at(1);
Scott Thornton's avatar
Scott Thornton committed
311
        auto t         = a.type();
312

313
        if(a.lens()[1] != b.lens()[0])
Paul's avatar
Paul committed
314
            MIGRAPH_THROW("Inner dimensions do not match");
Scott Thornton's avatar
Scott Thornton committed
315
        return {t, {a.lens()[0], b.lens()[1]}};
316
    }
317

Paul's avatar
Paul committed
318
319
320
321
    argument compute(context&, shape, std::vector<argument>) const
    {
        MIGRAPH_THROW("not computable");
    }
322
323

    friend std::ostream& operator<<(std::ostream& os, const gemm& op)
324
325
    {
        os << op.name() << "[";
326
        os << "]";
Scott Thornton's avatar
Scott Thornton committed
327
        return os;
328
329
330
    }
};

331
struct unary
Scott Thornton's avatar
Scott Thornton committed
332
{
333
334
    shape compute_shape(std::vector<shape> inputs) const
    {
335
336
        check_shapes{inputs}.has(1);
        return inputs.at(0);
337
    }
Paul's avatar
Paul committed
338
339
340
341
    argument compute(context&, shape, std::vector<argument>) const
    {
        MIGRAPH_THROW("not computable");
    }
Scott Thornton's avatar
Scott Thornton committed
342
343
};

344
345
struct identity : unary
{
346
    std::string name() const { return "identity"; }
347
348
349
};

struct abs : unary
Scott Thornton's avatar
Scott Thornton committed
350
{
351
    std::string name() const { return "abs"; }
Scott Thornton's avatar
Scott Thornton committed
352
353
};

354
struct exp : unary
Scott Thornton's avatar
Scott Thornton committed
355
{
356
    std::string name() const { return "exp"; }
Scott Thornton's avatar
Scott Thornton committed
357
358
};

359
struct sin : unary
Scott Thornton's avatar
Scott Thornton committed
360
{
361
    std::string name() const { return "sin"; }
Scott Thornton's avatar
Scott Thornton committed
362
363
};

364
struct cos : unary
Scott Thornton's avatar
Scott Thornton committed
365
{
366
    std::string name() const { return "cos"; }
Scott Thornton's avatar
Scott Thornton committed
367
368
};

369
struct tan : unary
Scott Thornton's avatar
Scott Thornton committed
370
{
371
    std::string name() const { return "tan"; }
Scott Thornton's avatar
Scott Thornton committed
372
373
};

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

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

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

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

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

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

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

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

414
415
416
417
418
419
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
420
421
422
423
        auto t      = inputs.at(0).type();
        auto result = inputs.at(0);
        auto input  = inputs.at(1);

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

Paul's avatar
Paul committed
426
427
        if(std::all_of(
               result.lens().cbegin(), result.lens().cend(), [&](auto x) { return x == 1; }))
428
        {
Scott Thornton's avatar
Scott Thornton committed
429
            if(axis != 0)
Paul's avatar
Paul committed
430
                MIGRAPH_THROW("when broadcasting tensor of size 1, axis should be 0");
Paul's avatar
Paul committed
431
            return {t, result.lens(), std::move(bcast_strides)};
432
433
434
        }
        else
        {
Paul's avatar
Paul committed
435
436
            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
437
                MIGRAPH_THROW("when broadcasting success sizes must match");
Paul's avatar
Paul committed
438
            std::copy(input.strides().begin(), input.strides().end(), bcast_strides.begin() + axis);
Paul's avatar
Paul committed
439
            return {t, result.lens(), std::move(bcast_strides)};
440
441
        }
    }
Paul's avatar
Paul committed
442
    argument compute(context&, shape output_shape, std::vector<argument> args) const
Scott Thornton's avatar
Scott Thornton committed
443
    {
444
        return {output_shape, std::move(args.at(1).data)};
Scott Thornton's avatar
Scott Thornton committed
445
    }
446
447
};

448
struct binary
Scott Thornton's avatar
Scott Thornton committed
449
{
450
    uint64_t broadcast = 0;
451
452
    shape compute_shape(std::vector<shape> inputs) const
    {
453
454
        check_shapes{inputs}.has(2).same_type().same_dims();
        return inputs.at(0);
455
    }
Paul's avatar
Paul committed
456
457
458
459
    argument compute(context&, shape, std::vector<argument>) const
    {
        MIGRAPH_THROW("not computable");
    }
Scott Thornton's avatar
Scott Thornton committed
460
461
};

462
463
464
465
466
467
struct add : binary
{
    std::string name() const { return "add"; }
};

struct sub : binary
Scott Thornton's avatar
Scott Thornton committed
468
469
470
471
{
    std::string name() const { return "sub"; }
};

472
struct mul : binary
Scott Thornton's avatar
Scott Thornton committed
473
474
475
476
{
    std::string name() const { return "mul"; }
};

477
struct div : binary
Scott Thornton's avatar
Scott Thornton committed
478
479
480
481
{
    std::string name() const { return "div"; }
};

Paul's avatar
Paul committed
482
struct outline
Scott Thornton's avatar
Scott Thornton committed
483
{
Paul's avatar
Paul committed
484
485
486
487
    shape s;
    std::string name() const { return "outline"; }
    shape compute_shape(std::vector<shape> inputs) const
    {
Paul's avatar
Paul committed
488
        check_shapes{inputs, *this}.has(0);
Paul's avatar
Paul committed
489
490
        return s;
    }
Paul's avatar
Paul committed
491
    argument compute(context&, shape, std::vector<argument>) const { return {s, nullptr}; }
Scott Thornton's avatar
Scott Thornton committed
492
493
};

Paul's avatar
Paul committed
494
} // namespace migraph
Paul's avatar
Paul committed
495
496

#endif