"vscode:/vscode.git/clone" did not exist on "1692db3c32dae5f7b10434e2e00405b39dafba74"
operators.hpp 13.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
15
struct check_shapes
{
    const std::vector<shape>* shapes;

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

    const check_shapes& has(std::size_t n) const
    {
        assert(shapes != nullptr);
        if(shapes->size() != n)
Paul's avatar
Paul committed
22
23
            RTG_THROW("Wrong number of arguments: expected " + std::to_string(n) + " but given " +
                      std::to_string(shapes->size()));
Paul's avatar
Paul committed
24
25
26
27
28
29
        return *this;
    }

    const check_shapes& only_dims(std::size_t n) const
    {
        assert(shapes != nullptr);
Paul's avatar
Paul committed
30
31
        if(!shapes->empty())
        {
Paul's avatar
Paul committed
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
            if(shapes->front().lens().size() != n)
                RTG_THROW("Only " + std::to_string(n) + "d supported");
        }
        return *this;
    }

    const check_shapes& same_shape() const
    {
        if(!this->same([](const shape& s) { return s; }))
            RTG_THROW("Shapes do not match");
        return *this;
    }

    const check_shapes& same_type() const
    {
        if(!this->same([](const shape& s) { return s.type(); }))
            RTG_THROW("Types do not match");
        return *this;
    }

    const check_shapes& same_dims() const
    {
        if(!this->same([](const shape& s) { return s.lens(); }))
            RTG_THROW("Dimensions do not match");
        return *this;
    }

59
60
61
62
63
64
65
    const check_shapes& same_ndims() const
    {
        if(!this->same([](const shape& s) { return s.lens().size(); }))
            RTG_THROW("Dimensions do not match");
        return *this;
    }

Paul's avatar
Paul committed
66
    template <class F>
Paul's avatar
Paul committed
67
68
69
70
71
72
    bool same(F f) const
    {
        assert(shapes != nullptr);
        if(shapes->empty())
            return true;
        auto&& key = f(shapes->front());
Paul's avatar
Paul committed
73
        return this->all_of([&](const shape& s) { return f(s) == key; });
Paul's avatar
Paul committed
74
75
    }

Paul's avatar
Paul committed
76
    template <class Predicate>
Paul's avatar
Paul committed
77
78
79
80
81
82
83
    bool all_of(Predicate p) const
    {
        assert(shapes != nullptr);
        return std::all_of(shapes->begin(), shapes->end(), p);
    }
};

Paul's avatar
Paul committed
84
85
struct not_computable
{
Paul's avatar
Paul committed
86
    argument compute(shape, std::vector<argument>) const { RTG_THROW("not computable"); }
Paul's avatar
Paul committed
87
88
};

Paul's avatar
Paul committed
89
struct convolution
Paul's avatar
Paul committed
90
{
Paul's avatar
Paul committed
91
92
93
    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
94
95
96
97
98
99
100
    enum padding_mode_t
    {
        default_, // NOLINT
        same,
        valid
    };
    padding_mode_t padding_mode = default_;
Paul's avatar
Paul committed
101
    std::string name() const { return "convolution"; }
Paul's avatar
Paul committed
102
103
    shape compute_shape(std::vector<shape> inputs) const
    {
104
        check_shapes{inputs}.has(2).same_type().same_ndims().only_dims(4);
Paul's avatar
Paul committed
105

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

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

Paul's avatar
Paul committed
158
    friend std::ostream& operator<<(std::ostream& os, const convolution& op)
Paul's avatar
Paul committed
159
    {
Paul's avatar
Paul committed
160
161
162
163
164
        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
165
166
        return os;
    }
Paul's avatar
Paul committed
167
168
};

Paul's avatar
Paul committed
169
struct pooling
Paul's avatar
Paul committed
170
171
{
    std::string mode;
Paul's avatar
Paul committed
172
173
174
    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
175
    std::string name() const { return "pooling"; }
Paul's avatar
Paul committed
176
177
    shape compute_shape(std::vector<shape> inputs) const
    {
Paul's avatar
Paul committed
178
        check_shapes{inputs}.has(1).only_dims(4);
Paul's avatar
Paul committed
179

Paul's avatar
Paul committed
180
        const shape& input = inputs.at(0);
Paul's avatar
Paul committed
181
        auto t             = input.type();
Paul's avatar
Paul committed
182

Paul's avatar
Paul committed
183
184
        assert(lengths[0] < (input.lens()[2] + 2 * padding[0]));
        assert(lengths[1] < (input.lens()[3] + 2 * padding[1]));
Paul's avatar
Paul committed
185

Paul's avatar
Paul committed
186
187
188
189
190
191
        return {t,
                {
                    input.lens()[0],
                    input.lens()[1],
                    std::size_t(std::max<std::ptrdiff_t>(
                        1,
Paul's avatar
Paul committed
192
                        std::ceil((input.lens()[2] + 2 * padding[0] - lengths[0]) /
Paul's avatar
Paul committed
193
194
195
196
                                  static_cast<float>(stride[0])) +
                            1)),
                    std::size_t(std::max<std::ptrdiff_t>(
                        1,
Paul's avatar
Paul committed
197
                        std::ceil((input.lens()[3] + 2 * padding[1] - lengths[1]) /
Paul's avatar
Paul committed
198
199
200
                                  static_cast<float>(stride[1])) +
                            1)),
                }};
Paul's avatar
Paul committed
201
    }
Paul's avatar
Paul committed
202

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

Paul's avatar
Paul committed
205
    friend std::ostream& operator<<(std::ostream& os, const pooling& op)
Paul's avatar
Paul committed
206
    {
Paul's avatar
Paul committed
207
208
209
210
211
        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
212
213
        return os;
    }
Paul's avatar
Paul committed
214
215
};

Paul's avatar
Paul committed
216
struct activation
Paul's avatar
Paul committed
217
218
{
    std::string mode;
Paul's avatar
Paul committed
219
    std::string name() const { return "activation"; }
Paul's avatar
Paul committed
220
221
    shape compute_shape(std::vector<shape> inputs) const
    {
Paul's avatar
Paul committed
222
        check_shapes{inputs}.has(1);
Paul's avatar
Paul committed
223
224
        return inputs.front();
    }
Paul's avatar
Paul committed
225

Paul's avatar
Paul committed
226
    argument compute(shape, std::vector<argument>) const { RTG_THROW("not computable"); }
Paul's avatar
Paul committed
227
    friend std::ostream& operator<<(std::ostream& os, const activation& op)
Paul's avatar
Paul committed
228
    {
Paul's avatar
Paul committed
229
        os << op.name() << ":" << op.mode;
Paul's avatar
Paul committed
230
231
        return os;
    }
Paul's avatar
Paul committed
232
233
};

234
235
236
237
238
239
240
241
struct transpose
{
    std::vector<int64_t> dims;
    std::string name() const { return "transpose"; }
    shape compute_shape(std::vector<shape> inputs) const
    {
        check_shapes{inputs}.has(1);
        auto input         = inputs.at(0);
242
        auto input_lens    = input.lens();
243
244
        auto input_strides = input.strides();
        auto t             = input.type();
Paul's avatar
Paul committed
245
246
        if(dims.size() != input_lens.size())
        {
247
248
249
250
            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
251
252
        if(!std::is_permutation(axes.begin(), axes.end(), dims.begin()))
        {
253
254
            RTG_THROW("Invalid permutation");
        }
255
256
        std::vector<size_t> output_lens(input_lens.size());
        std::vector<size_t> output_strides(input_lens.size());
Paul's avatar
Paul committed
257
258
259
        for(int i = 0; i < output_lens.size(); i++)
        {
            output_lens[i]    = input_lens[dims[i]];
260
261
            output_strides[i] = input_strides[dims[i]];
        }
262
        return {t, output_lens, output_strides};
263
264
265
266
    }
    argument compute(shape, std::vector<argument>) const { RTG_THROW("not computable"); }
};

Paul's avatar
Paul committed
267
struct contiguous
268
269
270
271
272
{
    std::string name() const { return "contiguous"; }
    shape compute_shape(std::vector<shape> inputs) const
    {
        check_shapes{inputs}.has(1);
Paul's avatar
Paul committed
273
274
275
276
        auto lens = inputs.at(0).lens();
        auto t    = inputs.at(0).type();
        if(lens.size() < 2)
        {
277
278
279
280
            RTG_THROW("Number of dimensions should exceed 1");
        }
        return {t, lens};
    }
281
    argument compute(shape, std::vector<argument>) const { RTG_THROW("not computable"); }
282
283
};

Paul's avatar
Paul committed
284
285
286
struct reshape
{
    std::vector<int64_t> dims;
Paul's avatar
Paul committed
287
    std::string name() const { return "reshape"; }
Paul's avatar
Paul committed
288
289
    shape compute_shape(std::vector<shape> inputs) const
    {
Paul's avatar
Paul committed
290
        if(inputs.empty())
Paul's avatar
Paul committed
291
            RTG_THROW("Wrong number of arguments");
Paul's avatar
Paul committed
292
293
        auto&& idims = inputs.front().lens();
        std::vector<std::size_t> rdims(dims.begin(), dims.end());
Paul's avatar
Paul committed
294
        for(std::size_t i = 0; i < dims.size(); i++)
Paul's avatar
Paul committed
295
296
297
298
299
300
301
        {
            if(dims[i] == 0)
                rdims[i] = idims[i];
        }
        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
304
305
306
        }
        return {inputs.front().type(), rdims};
    }

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

Paul's avatar
Paul committed
309
    friend std::ostream& operator<<(std::ostream& os, const reshape& op)
Paul's avatar
Paul committed
310
    {
Paul's avatar
Paul committed
311
312
313
        os << op.name() << "[";
        os << "dims={" << stream_range(op.dims) << "}, ";
        os << "]";
Paul's avatar
Paul committed
314
315
        return os;
    }
Paul's avatar
Paul committed
316
317
};

318
319
struct gemm
{
320
    std::string name() const { return "gemm"; }
321
322
    shape compute_shape(std::vector<shape> inputs) const
    {
323
        check_shapes{inputs}.has(2).same_type();
324
325
        const shape& a = inputs.at(0);
        const shape& b = inputs.at(1);
Scott Thornton's avatar
Scott Thornton committed
326
        auto t         = a.type();
327

328
        if(a.lens()[1] != b.lens()[0])
329
            RTG_THROW("Inner dimensions do not match");
Scott Thornton's avatar
Scott Thornton committed
330
        return {t, {a.lens()[0], b.lens()[1]}};
331
    }
332

333
    argument compute(shape, std::vector<argument>) const { RTG_THROW("not computable"); }
334
335

    friend std::ostream& operator<<(std::ostream& os, const gemm& op)
336
337
    {
        os << op.name() << "[";
338
        os << "]";
Scott Thornton's avatar
Scott Thornton committed
339
        return os;
340
341
342
    }
};

343
struct unary
Scott Thornton's avatar
Scott Thornton committed
344
{
345
346
    shape compute_shape(std::vector<shape> inputs) const
    {
347
348
        check_shapes{inputs}.has(1);
        return inputs.at(0);
349
350
    }
    argument compute(shape, std::vector<argument>) const { RTG_THROW("not computable"); }
Scott Thornton's avatar
Scott Thornton committed
351
352
};

353
354
struct identity : unary
{
355
    std::string name() const { return "identity"; }
356
357
358
};

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

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

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

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

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

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

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

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

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

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

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

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

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

423
424
425
426
427
428
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
429
430
431
432
        auto t      = inputs.at(0).type();
        auto result = inputs.at(0);
        auto input  = inputs.at(1);

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

456
struct binary
Scott Thornton's avatar
Scott Thornton committed
457
{
458
    uint64_t broadcast = 0;
459
460
    shape compute_shape(std::vector<shape> inputs) const
    {
461
462
        check_shapes{inputs}.has(2).same_type().same_dims();
        return inputs.at(0);
463
    }
464
    argument compute(shape, std::vector<argument>) const { RTG_THROW("not computable"); }
Scott Thornton's avatar
Scott Thornton committed
465
466
};

467
468
469
470
471
472
struct add : binary
{
    std::string name() const { return "add"; }
};

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

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

482
struct div : binary
Scott Thornton's avatar
Scott Thornton committed
483
484
485
486
{
    std::string name() const { return "div"; }
};

Paul's avatar
Paul committed
487
struct outline
Scott Thornton's avatar
Scott Thornton committed
488
{
Paul's avatar
Paul committed
489
490
491
492
493
494
495
    shape s;
    std::string name() const { return "outline"; }
    shape compute_shape(std::vector<shape> inputs) const
    {
        check_shapes{inputs}.has(0);
        return s;
    }
Paul's avatar
Paul committed
496
    argument compute(shape, std::vector<argument>) const { return {s, nullptr}; }
Scott Thornton's avatar
Scott Thornton committed
497
498
};

Paul's avatar
Paul committed
499
500
501
} // namespace rtg

#endif