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

4
#include <array>
Paul's avatar
Paul committed
5
#include <rtg/operation.hpp>
Paul's avatar
Paul committed
6
#include <rtg/stringutils.hpp>
Paul's avatar
Paul committed
7
#include <rtg/streamutils.hpp>
Paul's avatar
Paul committed
8
#include <cmath>
Paul's avatar
Paul committed
9

Paul's avatar
Paul committed
10
11
namespace rtg {

Paul's avatar
Paul committed
12
13
14
struct check_shapes
{
    const std::vector<shape>* shapes;
Paul's avatar
Paul committed
15
    const std::string name;
Paul's avatar
Paul committed
16

Paul's avatar
Paul committed
17
    check_shapes(const std::vector<shape>& s) : shapes(&s) {}
Paul's avatar
Paul committed
18
19
20
21
22

    template <class Op>
    check_shapes(const std::vector<shape>& s, const Op& op) : shapes(&s), name(op.name())
    {
    }
Paul's avatar
Paul committed
23
24
25

    std::string prefix() const
    {
Paul's avatar
Paul committed
26
27
28
29
        if(name.empty())
            return "";
        else
            return name + ": ";
Paul's avatar
Paul committed
30
    }
Paul's avatar
Paul committed
31
32
33
34
35

    const check_shapes& has(std::size_t n) const
    {
        assert(shapes != nullptr);
        if(shapes->size() != n)
Paul's avatar
Paul committed
36
37
            RTG_THROW(prefix() + "Wrong number of arguments: expected " + std::to_string(n) +
                      " but given " + std::to_string(shapes->size()));
Paul's avatar
Paul committed
38
39
40
41
42
43
        return *this;
    }

    const check_shapes& only_dims(std::size_t n) const
    {
        assert(shapes != nullptr);
Paul's avatar
Paul committed
44
45
        if(!shapes->empty())
        {
Paul's avatar
Paul committed
46
            if(shapes->front().lens().size() != n)
Paul's avatar
Paul committed
47
                RTG_THROW(prefix() + "Only " + std::to_string(n) + "d supported");
Paul's avatar
Paul committed
48
49
50
51
52
53
54
        }
        return *this;
    }

    const check_shapes& same_shape() const
    {
        if(!this->same([](const shape& s) { return s; }))
Paul's avatar
Paul committed
55
            RTG_THROW(prefix() + "Shapes do not match");
Paul's avatar
Paul committed
56
57
58
59
60
61
        return *this;
    }

    const check_shapes& same_type() const
    {
        if(!this->same([](const shape& s) { return s.type(); }))
Paul's avatar
Paul committed
62
            RTG_THROW(prefix() + "Types do not match");
Paul's avatar
Paul committed
63
64
65
66
67
68
        return *this;
    }

    const check_shapes& same_dims() const
    {
        if(!this->same([](const shape& s) { return s.lens(); }))
Paul's avatar
Paul committed
69
            RTG_THROW(prefix() + "Dimensions do not match");
Paul's avatar
Paul committed
70
71
72
        return *this;
    }

73
74
75
    const check_shapes& same_ndims() const
    {
        if(!this->same([](const shape& s) { return s.lens().size(); }))
Paul's avatar
Paul committed
76
            RTG_THROW(prefix() + "Dimensions do not match");
77
78
79
        return *this;
    }

Paul's avatar
Paul committed
80
    template <class F>
Paul's avatar
Paul committed
81
82
83
84
85
86
    bool same(F f) const
    {
        assert(shapes != nullptr);
        if(shapes->empty())
            return true;
        auto&& key = f(shapes->front());
Paul's avatar
Paul committed
87
        return this->all_of([&](const shape& s) { return f(s) == key; });
Paul's avatar
Paul committed
88
89
    }

Paul's avatar
Paul committed
90
    template <class Predicate>
Paul's avatar
Paul committed
91
92
93
94
95
96
97
    bool all_of(Predicate p) const
    {
        assert(shapes != nullptr);
        return std::all_of(shapes->begin(), shapes->end(), p);
    }
};

Paul's avatar
Paul committed
98
99
struct not_computable
{
Paul's avatar
Paul committed
100
    argument compute(context&, shape, std::vector<argument>) const { RTG_THROW("not computable"); }
Paul's avatar
Paul committed
101
102
};

Paul's avatar
Paul committed
103
struct convolution
Paul's avatar
Paul committed
104
{
Paul's avatar
Paul committed
105
106
107
    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
108
109
110
111
112
113
114
    enum padding_mode_t
    {
        default_, // NOLINT
        same,
        valid
    };
    padding_mode_t padding_mode = default_;
Paul's avatar
Paul committed
115
    std::string name() const { return "convolution"; }
Paul's avatar
Paul committed
116
117
    shape compute_shape(std::vector<shape> inputs) const
    {
Paul's avatar
Paul committed
118
        check_shapes{inputs, *this}.has(2).same_type().same_ndims().only_dims(4);
Paul's avatar
Paul committed
119

Paul's avatar
Paul committed
120
        const shape& input   = inputs.at(0);
Paul's avatar
Paul committed
121
        const shape& weights = inputs.at(1);
Paul's avatar
Paul committed
122
        auto t               = input.type();
Paul's avatar
Paul committed
123
124
        if(padding_mode == default_)
        {
Paul's avatar
Paul committed
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
            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
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
        }
        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
166
167
            RTG_THROW("Invalid padding mode");
        }
Paul's avatar
Paul committed
168
    }
Paul's avatar
Paul committed
169

Paul's avatar
Paul committed
170
    argument compute(context&, shape, std::vector<argument>) const { RTG_THROW("not computable"); }
Paul's avatar
Paul committed
171

Paul's avatar
Paul committed
172
    friend std::ostream& operator<<(std::ostream& os, const convolution& op)
Paul's avatar
Paul committed
173
    {
Paul's avatar
Paul committed
174
175
176
177
178
        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
179
180
        return os;
    }
Paul's avatar
Paul committed
181
182
};

Paul's avatar
Paul committed
183
struct pooling
Paul's avatar
Paul committed
184
185
{
    std::string mode;
Paul's avatar
Paul committed
186
187
188
    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
189
    std::string name() const { return "pooling"; }
Paul's avatar
Paul committed
190
191
    shape compute_shape(std::vector<shape> inputs) const
    {
Paul's avatar
Paul committed
192
        check_shapes{inputs, *this}.has(1).only_dims(4);
Paul's avatar
Paul committed
193

Paul's avatar
Paul committed
194
        const shape& input = inputs.at(0);
Paul's avatar
Paul committed
195
        auto t             = input.type();
Paul's avatar
Paul committed
196

Paul's avatar
Paul committed
197
198
        assert(lengths[0] < (input.lens()[2] + 2 * padding[0]));
        assert(lengths[1] < (input.lens()[3] + 2 * padding[1]));
Paul's avatar
Paul committed
199

Paul's avatar
Paul committed
200
201
202
203
204
205
        return {t,
                {
                    input.lens()[0],
                    input.lens()[1],
                    std::size_t(std::max<std::ptrdiff_t>(
                        1,
Paul's avatar
Paul committed
206
                        std::ceil((input.lens()[2] + 2 * padding[0] - lengths[0]) /
Paul's avatar
Paul committed
207
208
209
210
                                  static_cast<float>(stride[0])) +
                            1)),
                    std::size_t(std::max<std::ptrdiff_t>(
                        1,
Paul's avatar
Paul committed
211
                        std::ceil((input.lens()[3] + 2 * padding[1] - lengths[1]) /
Paul's avatar
Paul committed
212
213
214
                                  static_cast<float>(stride[1])) +
                            1)),
                }};
Paul's avatar
Paul committed
215
    }
Paul's avatar
Paul committed
216

Paul's avatar
Paul committed
217
    argument compute(context&, shape, std::vector<argument>) const { RTG_THROW("not computable"); }
Paul's avatar
Paul committed
218

Paul's avatar
Paul committed
219
    friend std::ostream& operator<<(std::ostream& os, const pooling& op)
Paul's avatar
Paul committed
220
    {
Paul's avatar
Paul committed
221
222
223
224
225
        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
226
227
        return os;
    }
Paul's avatar
Paul committed
228
229
};

Paul's avatar
Paul committed
230
struct activation
Paul's avatar
Paul committed
231
232
{
    std::string mode;
Paul's avatar
Paul committed
233
    std::string name() const { return "activation"; }
Paul's avatar
Paul committed
234
235
    shape compute_shape(std::vector<shape> inputs) const
    {
Paul's avatar
Paul committed
236
        check_shapes{inputs, *this}.has(1);
Paul's avatar
Paul committed
237
238
        return inputs.front();
    }
Paul's avatar
Paul committed
239

Paul's avatar
Paul committed
240
    argument compute(context&, shape, std::vector<argument>) const { RTG_THROW("not computable"); }
Paul's avatar
Paul committed
241
    friend std::ostream& operator<<(std::ostream& os, const activation& op)
Paul's avatar
Paul committed
242
    {
Paul's avatar
Paul committed
243
        os << op.name() << ":" << op.mode;
Paul's avatar
Paul committed
244
245
        return os;
    }
Paul's avatar
Paul committed
246
247
};

248
249
250
251
252
253
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
254
        check_shapes{inputs, *this}.has(1);
255
        auto input         = inputs.at(0);
256
        auto input_lens    = input.lens();
257
258
        auto input_strides = input.strides();
        auto t             = input.type();
Paul's avatar
Paul committed
259
260
        if(dims.size() != input_lens.size())
        {
261
262
263
264
            RTG_THROW("Permutation has wrong number of axes");
        }
        std::vector<int64_t> axes(dims.size());
        std::iota(axes.begin(), axes.end(), 0);
Paul's avatar
Paul committed
265
266
        if(!std::is_permutation(axes.begin(), axes.end(), dims.begin()))
        {
267
268
            RTG_THROW("Invalid permutation");
        }
269
270
        std::vector<size_t> output_lens(input_lens.size());
        std::vector<size_t> output_strides(input_lens.size());
Paul's avatar
Paul committed
271
272
273
        for(int i = 0; i < output_lens.size(); i++)
        {
            output_lens[i]    = input_lens[dims[i]];
274
275
            output_strides[i] = input_strides[dims[i]];
        }
276
        return {t, output_lens, output_strides};
277
    }
Paul's avatar
Paul committed
278
    argument compute(context&, shape, std::vector<argument>) const { RTG_THROW("not computable"); }
279
280
};

Paul's avatar
Paul committed
281
struct contiguous
282
283
284
285
{
    std::string name() const { return "contiguous"; }
    shape compute_shape(std::vector<shape> inputs) const
    {
Paul's avatar
Paul committed
286
        check_shapes{inputs, *this}.has(1);
Paul's avatar
Paul committed
287
288
289
290
        auto lens = inputs.at(0).lens();
        auto t    = inputs.at(0).type();
        if(lens.size() < 2)
        {
291
292
293
294
            RTG_THROW("Number of dimensions should exceed 1");
        }
        return {t, lens};
    }
Paul's avatar
Paul committed
295
    argument compute(context&, shape, std::vector<argument>) const { RTG_THROW("not computable"); }
296
297
};

Paul's avatar
Paul committed
298
299
300
struct reshape
{
    std::vector<int64_t> dims;
Paul's avatar
Paul committed
301
    std::string name() const { return "reshape"; }
Paul's avatar
Paul committed
302
303
    shape compute_shape(std::vector<shape> inputs) const
    {
Paul's avatar
Paul committed
304
        check_shapes{inputs, *this}.has(1);
Paul's avatar
Paul committed
305
306
        auto&& idims = inputs.front().lens();
        std::vector<std::size_t> rdims(dims.begin(), dims.end());
Paul's avatar
Paul committed
307
        for(std::size_t i = 0; i < dims.size(); i++)
Paul's avatar
Paul committed
308
309
310
311
312
313
314
        {
            if(dims[i] == 0)
                rdims[i] = idims[i];
        }
        if(dims.back() == -1)
        {
            rdims.pop_back();
Paul's avatar
Paul committed
315
            std::copy(idims.begin() + rdims.size(), idims.end(), std::back_inserter(rdims));
Paul's avatar
Paul committed
316
        }
Paul's avatar
Paul committed
317
318
319
320
        shape s{inputs.front().type(), rdims};
        if(s.elements() != inputs.front().elements())
            RTG_THROW("Wrong number of elements for reshape");
        return s;
Paul's avatar
Paul committed
321
322
    }

Paul's avatar
Paul committed
323
    argument compute(context&, shape, std::vector<argument>) const { RTG_THROW("not computable"); }
Paul's avatar
Paul committed
324

Paul's avatar
Paul committed
325
    friend std::ostream& operator<<(std::ostream& os, const reshape& op)
Paul's avatar
Paul committed
326
    {
Paul's avatar
Paul committed
327
328
329
        os << op.name() << "[";
        os << "dims={" << stream_range(op.dims) << "}, ";
        os << "]";
Paul's avatar
Paul committed
330
331
        return os;
    }
Paul's avatar
Paul committed
332
333
};

334
335
struct gemm
{
336
    std::string name() const { return "gemm"; }
337
338
    shape compute_shape(std::vector<shape> inputs) const
    {
Paul's avatar
Paul committed
339
        check_shapes{inputs, *this}.has(2).same_type();
340
341
        const shape& a = inputs.at(0);
        const shape& b = inputs.at(1);
Scott Thornton's avatar
Scott Thornton committed
342
        auto t         = a.type();
343

344
        if(a.lens()[1] != b.lens()[0])
345
            RTG_THROW("Inner dimensions do not match");
Scott Thornton's avatar
Scott Thornton committed
346
        return {t, {a.lens()[0], b.lens()[1]}};
347
    }
348

Paul's avatar
Paul committed
349
    argument compute(context&, shape, std::vector<argument>) const { RTG_THROW("not computable"); }
350
351

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

434
struct flatten
Scott Thornton's avatar
Scott Thornton committed
435
436
437
438
{
    std::string name() const { return "flatten"; }
};

439
440
441
442
443
444
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
445
446
447
448
        auto t      = inputs.at(0).type();
        auto result = inputs.at(0);
        auto input  = inputs.at(1);

Paul's avatar
Paul committed
449
        std::vector<size_t> bcast_strides(result.lens().size(), 0);
Paul's avatar
Paul committed
450
451
        if(std::all_of(
               result.lens().cbegin(), result.lens().cend(), [&](auto x) { return x == 1; }))
452
        {
Scott Thornton's avatar
Scott Thornton committed
453
454
            if(axis != 0)
                RTG_THROW("when broadcasting tensor of size 1, axis should be 0");
Paul's avatar
Paul committed
455
            return {t, result.lens(), std::move(bcast_strides)};
456
457
458
        }
        else
        {
Paul's avatar
Paul committed
459
460
            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
461
                RTG_THROW("when broadcasting success sizes must match");
Paul's avatar
Paul committed
462
            std::copy(input.strides().begin(), input.strides().end(), bcast_strides.begin() + axis);
Paul's avatar
Paul committed
463
            return {t, result.lens(), std::move(bcast_strides)};
464
465
        }
    }
Paul's avatar
Paul committed
466
    argument compute(context&, shape output_shape, std::vector<argument> args) const
Scott Thornton's avatar
Scott Thornton committed
467
    {
468
        return {output_shape, std::move(args.at(1).data)};
Scott Thornton's avatar
Scott Thornton committed
469
    }
470
471
};

472
struct binary
Scott Thornton's avatar
Scott Thornton committed
473
{
474
    uint64_t broadcast = 0;
475
476
    shape compute_shape(std::vector<shape> inputs) const
    {
477
478
        check_shapes{inputs}.has(2).same_type().same_dims();
        return inputs.at(0);
479
    }
Paul's avatar
Paul committed
480
    argument compute(context&, shape, std::vector<argument>) const { RTG_THROW("not computable"); }
Scott Thornton's avatar
Scott Thornton committed
481
482
};

483
484
485
486
487
488
struct add : binary
{
    std::string name() const { return "add"; }
};

struct sub : binary
Scott Thornton's avatar
Scott Thornton committed
489
490
491
492
{
    std::string name() const { return "sub"; }
};

493
struct mul : binary
Scott Thornton's avatar
Scott Thornton committed
494
495
496
497
{
    std::string name() const { return "mul"; }
};

498
struct div : binary
Scott Thornton's avatar
Scott Thornton committed
499
500
501
502
{
    std::string name() const { return "div"; }
};

Paul's avatar
Paul committed
503
struct outline
Scott Thornton's avatar
Scott Thornton committed
504
{
Paul's avatar
Paul committed
505
506
507
508
    shape s;
    std::string name() const { return "outline"; }
    shape compute_shape(std::vector<shape> inputs) const
    {
Paul's avatar
Paul committed
509
        check_shapes{inputs, *this}.has(0);
Paul's avatar
Paul committed
510
511
        return s;
    }
Paul's avatar
Paul committed
512
    argument compute(context&, shape, std::vector<argument>) const { return {s, nullptr}; }
Scott Thornton's avatar
Scott Thornton committed
513
514
};

Paul's avatar
Paul committed
515
template <class T>
Paul's avatar
Paul committed
516
517
518
struct check_context
{
    std::string name() const { return "check_context"; }
Paul's avatar
Paul committed
519
520
    shape compute_shape(std::vector<shape>) const { return {}; }
    argument compute(context& ctx, shape, std::vector<argument>) const
Paul's avatar
Paul committed
521
522
523
524
525
526
527
528
    {
        T* x = any_cast<T>(&ctx);
        if(x == nullptr)
            RTG_THROW(std::string("Unexpected context type: ") + ctx.type_id().name());
        return {};
    }
};

Paul's avatar
Paul committed
529
530
531
} // namespace rtg

#endif