"vscode:/vscode.git/clone" did not exist on "d7e834d6baee771483377621a289ed5d87581da0"
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
23
24
25
26
    
    template<class Op>
    check_shapes(const std::vector<shape>& s, const Op& op) : shapes(&s), name(op.name()) {}

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

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

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

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

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

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

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

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

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

Paul's avatar
Paul committed
94
95
struct not_computable
{
Paul's avatar
Paul committed
96
    argument compute(context&, shape, std::vector<argument>) const { RTG_THROW("not computable"); }
Paul's avatar
Paul committed
97
98
};

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

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

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

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

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

Paul's avatar
Paul committed
190
        const shape& input = inputs.at(0);
Paul's avatar
Paul committed
191
        auto t             = input.type();
Paul's avatar
Paul committed
192

Paul's avatar
Paul committed
193
194
        assert(lengths[0] < (input.lens()[2] + 2 * padding[0]));
        assert(lengths[1] < (input.lens()[3] + 2 * padding[1]));
Paul's avatar
Paul committed
195

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

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

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

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

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

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

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

Paul's avatar
Paul committed
294
295
296
struct reshape
{
    std::vector<int64_t> dims;
Paul's avatar
Paul committed
297
    std::string name() const { return "reshape"; }
Paul's avatar
Paul committed
298
299
    shape compute_shape(std::vector<shape> inputs) const
    {
Paul's avatar
Paul committed
300
        check_shapes{inputs, *this}.has(1);
Paul's avatar
Paul committed
301
302
        auto&& idims = inputs.front().lens();
        std::vector<std::size_t> rdims(dims.begin(), dims.end());
Paul's avatar
Paul committed
303
        for(std::size_t i = 0; i < dims.size(); i++)
Paul's avatar
Paul committed
304
305
306
307
308
309
310
        {
            if(dims[i] == 0)
                rdims[i] = idims[i];
        }
        if(dims.back() == -1)
        {
            rdims.pop_back();
Paul's avatar
Paul committed
311
            std::copy(idims.begin() + rdims.size(), idims.end(), std::back_inserter(rdims));
Paul's avatar
Paul committed
312
        }
Paul's avatar
Paul committed
313
314
315
316
        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
317
318
    }

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

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

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

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

Paul's avatar
Paul committed
345
    argument compute(context&, shape, std::vector<argument>) const { RTG_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
    argument compute(context&, shape, std::vector<argument>) const { RTG_THROW("not computable"); }
Scott Thornton's avatar
Scott Thornton committed
363
364
};

365
366
struct identity : unary
{
367
    std::string name() const { return "identity"; }
368
369
370
};

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

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

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

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

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

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

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

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

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

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

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

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

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

435
436
437
438
439
440
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
441
442
443
444
        auto t      = inputs.at(0).type();
        auto result = inputs.at(0);
        auto input  = inputs.at(1);

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

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

479
480
481
482
483
484
struct add : binary
{
    std::string name() const { return "add"; }
};

struct sub : binary
Scott Thornton's avatar
Scott Thornton committed
485
486
487
488
{
    std::string name() const { return "sub"; }
};

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

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

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

Paul's avatar
Paul committed
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
template<class T>
struct check_context
{
    std::string name() const { return "check_context"; }
    shape compute_shape(std::vector<shape>) const
    {
        return {};
    }
    argument compute(context& ctx, shape, std::vector<argument>) const 
    {
        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
528
529
530
} // namespace rtg

#endif