-
Notifications
You must be signed in to change notification settings - Fork 3
/
tinytorch.hpp
1424 lines (1226 loc) · 48.5 KB
/
tinytorch.hpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#pragma once
#include <omp.h>
#include <algorithm>
#include <cassert>
#include <cmath>
#include <cstddef>
#include <cstdint>
#include <cstdlib>
#include <ctime>
#include <iostream>
#include <limits>
#include <random>
#include <ranges>
#include <stdexcept>
#include <type_traits>
#include <unordered_map>
#include <vector>
#ifdef __ARM_NEON
#include <arm_neon.h>
#endif
namespace tinytorch {
const size_t kTensorMemAlign = 16;
template <typename T>
inline void AssertAligned(T ptr) {
assert(((uintptr_t)(ptr)) % kTensorMemAlign == 0);
}
enum TensorType {
kF32,
kI32,
kLEN // number of tensor types
};
const size_t kTypeSize[kLEN] = {
sizeof(float),
sizeof(int32_t),
};
template <typename T>
inline bool IsTypeCompatible(TensorType type) {
switch (type) {
case kF32:
return std::is_same<T, float>::value;
case kI32:
return std::is_same<T, int32_t>::value;
default:
throw std::runtime_error("Malformed tensor type");
}
}
struct Object {
size_t offset;
size_t size;
Object *next;
std::byte padding[8];
};
const size_t kObjectSize = sizeof(struct Object);
template <typename T>
class TensorContextT {
public:
const size_t TENSOR_SIZE = sizeof(T);
explicit TensorContextT(size_t mem_size) : mem_size_(mem_size) {
mem_buffer_ = new std::byte[mem_size];
n_objects_ = 0;
objects_begin_ = nullptr;
objects_end_ = nullptr;
}
~TensorContextT() { delete[] mem_buffer_; }
T *NewTensor(const std::vector<int> &dims, float *data) {
return NewTensor(dims, kF32, reinterpret_cast<std::byte *>(data));
}
T *NewTensor(const std::vector<int> &dims, TensorType type = kF32, std::byte *data = nullptr) {
const int n_dims = dims.size();
size_t size_needed = 0;
if (data == nullptr) {
size_t data_size = kTypeSize[type];
for (int i = 0; i < n_dims; i++) {
data_size *= dims[i];
}
size_needed += ((data_size + kTensorMemAlign - 1) / kTensorMemAlign) * kTensorMemAlign;
}
size_needed += TENSOR_SIZE;
// layout
// [Struct Object][Struct Tensor][data]
std::byte *cur = mem_buffer_;
if (objects_end_ != nullptr) {
cur += objects_end_->offset + objects_end_->size;
}
if (cur + size_needed + kObjectSize > mem_buffer_ + mem_size_) {
throw std::runtime_error("Out of tensor memory");
}
Object *object = reinterpret_cast<Object *>(cur);
*object = {.offset = (size_t)(cur - mem_buffer_) + kObjectSize,
.size = size_needed,
.next = nullptr};
AssertAligned(object);
if (objects_end_ != nullptr) {
objects_end_->next = object;
} else {
objects_begin_ = object;
}
objects_end_ = object;
T *tensor = reinterpret_cast<T *>(cur + kObjectSize);
AssertAligned(tensor);
*tensor = T(this, dims, type, data == nullptr ? cur + kObjectSize + TENSOR_SIZE : data);
AssertAligned(tensor->data_);
n_objects_++;
return tensor;
}
void PrintLayout(bool verbose = false) {
std::cout << "TensorContext Layout" << std::endl;
std::cout << "---------------------" << std::endl;
std::cout << "Total memory size: " << mem_size_ << std::endl;
std::cout << "Used memory size: "
<< (objects_end_ == nullptr ? 0 : (objects_end_->offset + objects_end_->size))
<< std::endl;
std::cout << "Number of objects: " << n_objects_ << std::endl;
if (verbose) {
std::cout << "Objects:" << std::endl;
Object *cur = objects_begin_;
while (cur != nullptr) {
std::cout << " offset: " << cur->offset << ", size: " << cur->size << std::endl;
cur = cur->next;
}
}
}
private:
size_t mem_size_;
std::byte *mem_buffer_;
int n_objects_;
Object *objects_begin_;
Object *objects_end_;
};
class Tensor;
using TensorContext = TensorContextT<Tensor>;
class NormalDist {
public:
NormalDist() { generator_.seed(std::random_device{}()); }
float operator()() { return normal_dist_(generator_); }
private:
std::normal_distribution<float> normal_dist_;
std::default_random_engine generator_;
};
enum TensorOp {
kOpNone,
kOpAdd,
kOpMul,
kOpMatmul,
kOpLookup,
kOpNorm,
kOpBroadcast,
kOpView,
kOpTranspose,
kOpGelu,
kOpSoftmax,
kOpCrossEntropy,
kOpLEN // number of tensor operations
};
const std::string TENSOR_OP_NAMES[kOpLEN] = { // NOLINT
"NONE", "ADD", "MUL", "MATMUL", "LOOKUP", "NORM",
"BROADCAST", "VIEW", "TRANSPOSE", "GELU", "SOFTMAX", "CROSS_ENTROPY",
};
const int kMaxTensorDims = 4;
const int kMaxTensorOpParams = 2;
// Tensor operations time profile
class Profile {
public:
void Reset() {
times_.clear();
counts_.clear();
}
void AddTime(TensorOp op, double time) {
times_[op] += time;
counts_[op]++;
}
void Print() {
std::cout << "Profile" << std::endl;
std::cout << "-------" << std::endl;
for (int i = 0; i < kOpLEN; i++) {
if (counts_[i] > 0) {
std::cout << TENSOR_OP_NAMES[i] << ": " << times_[i] * 1000 << "ms ("
<< (times_[i] / counts_[i] * 1000) << "ms per op, " << counts_[i]
<< " times)" << std::endl;
}
}
}
private:
std::unordered_map<int, double> times_;
std::unordered_map<int, size_t> counts_;
};
class Tensor {
public:
// Add
Tensor &operator+(Tensor &other) { return operator2(other, kOpAdd); }
// Mul
Tensor &operator*(Tensor &other) { return operator2(other, kOpMul); }
// Mul by scalar
Tensor &operator*(float val) {
assert(type_ == kF32);
return *this * *(ctx_->NewTensor({1}, type_)->Fill(val));
}
private:
Tensor &operator2(Tensor &other_ref, TensorOp op) {
auto other = &other_ref;
assert(other != this);
if (!SameShape(*other)) {
assert(can_broadcast_to(*other, *this));
other = &broadcast_to(ctx_, *other, *this);
}
Tensor *dst = ctx_->NewTensor(Dims());
dst->op_ = op;
dst->src0_ = this;
dst->src1_ = other;
return *dst;
}
public:
// Lookup
Tensor &operator[](Tensor &index) {
assert(index.type_ == kI32);
assert(n_dims_ + index.n_dims_ - 1 <= kMaxTensorDims);
std::vector<int> ds;
for (int i = kMaxTensorDims - 1; i > kMaxTensorDims - n_dims_; i--) {
ds.push_back(dims_[i]);
}
for (int i = kMaxTensorDims - 1; i >= kMaxTensorDims - index.n_dims_; i--) {
ds.push_back(index.dims_[i]);
}
reverse(ds.begin(), ds.end());
Tensor *dst = ctx_->NewTensor(ds, type_);
dst->op_ = kOpLookup;
dst->src0_ = this;
dst->src1_ = &index;
return *dst;
}
// Norm
Tensor &Norm() {
assert(type_ == kF32);
Tensor *dst = ctx_->NewTensor(Dims(), type_);
dst->op_ = kOpNorm;
dst->src0_ = this;
return *dst;
}
// Gelu
Tensor &Gelu() {
assert(type_ == kF32);
Tensor *dst = ctx_->NewTensor(Dims(), type_);
dst->op_ = kOpGelu;
dst->src0_ = this;
return *dst;
}
// Softmax
Tensor &Softmax(bool is_casual = false, int vocab_size = 0) {
assert(type_ == kF32);
if (vocab_size > 0) {
assert(vocab_size <= dims_[kMaxTensorDims - 1]);
}
Tensor *dst = ctx_->NewTensor(Dims(), type_);
dst->op_ = kOpSoftmax;
dst->src0_ = this;
dst->op_params_[0] = is_casual;
dst->op_params_[1] = vocab_size;
return *dst;
}
// CrossEntropy
Tensor &CrossEntropy(Tensor &target) {
assert(type_ == kF32 && target.type_ == kI32);
auto shape = Dims();
shape.pop_back();
assert(shape == target.Dims());
Tensor *dst = ctx_->NewTensor(shape, type_);
dst->op_ = kOpCrossEntropy;
dst->src0_ = this;
dst->src1_ = ⌖
return *dst;
}
// Split
std::vector<Tensor *> Split(int size, int axis) {
assert(axis < n_dims_);
auto dimi = kMaxTensorDims - n_dims_ + axis;
assert(dims_[dimi] % size == 0);
std::vector<Tensor *> tensors;
if (dims_[dimi] == size) {
tensors.push_back(this);
return tensors;
}
std::vector<int> shape = Dims();
shape[axis] = size;
for (int i = 0; i < dims_[dimi] / size; i++) {
tensors.push_back(&View(shape, i, axis));
}
return tensors;
}
// View
// TODO(ysg): the view is actually a copy, we need to implement a real view
Tensor &View(const std::vector<int> &shape, int split_no = 0, int split_axis = 0) {
assert(NumElements() % num_of_elements(shape) == 0);
int dimi = kMaxTensorDims - n_dims_ + split_axis;
assert(dims_[dimi] % (NumElements() / num_of_elements(shape)) == 0);
Tensor *dst = ctx_->NewTensor(shape, type_);
dst->op_ = kOpView;
dst->src0_ = this;
dst->op_params_[0] = split_no;
dst->op_params_[1] = split_axis;
return *dst;
}
// Tranpose
Tensor &Transpose(int axis0, int axis1) {
assert(axis0 < n_dims_ && axis1 < n_dims_);
auto dimi0 = kMaxTensorDims - n_dims_ + axis0;
auto dimi1 = kMaxTensorDims - n_dims_ + axis1;
std::vector<int> shape = Dims();
std::swap(shape[axis0], shape[axis1]);
Tensor *dst = ctx_->NewTensor(shape, type_);
dst->op_ = kOpTranspose;
dst->src0_ = this;
dst->op_params_[0] = dimi0;
dst->op_params_[1] = dimi1;
return *dst;
}
// Matmul
// (B, M, N) x (B, P, N) -> (B, M, P)
// we assume that the input tensors are in the format (B, M, N) and (B, P, N)
Tensor &MatMul(Tensor &other_ref) {
auto other = &other_ref;
assert(other != this);
if (!can_matmul(*this, *other)) {
assert(can_broadcast_to(*other, *this, 2));
other = &broadcast_to(ctx_, *other, *this, 2);
assert(can_matmul(*this, *other));
}
std::vector<int> dst_dims = {dims_[0], dims_[1], dims_[2], other->dims_[2]};
dst_dims.erase(dst_dims.begin(), dst_dims.begin() + dst_dims.size() - n_dims_);
Tensor *dst = ctx_->NewTensor(dst_dims);
dst->op_ = kOpMatmul;
dst->src0_ = this;
dst->src1_ = other;
return *dst;
}
void Forward() {
std::vector<Tensor *> sorted = topo_sort(this);
struct timespec start, end;
ForwardProfile.Reset();
for (auto *t : sorted) {
clock_gettime(CLOCK_MONOTONIC, &start);
switch (t->op_) {
case kOpAdd:
add_forward(t, t->src0_, t->src1_);
break;
case kOpMul:
mul_forward(t, t->src0_, t->src1_);
break;
case kOpMatmul:
matmul_forward(t, t->src0_, t->src1_);
break;
case kOpLookup:
lookup_forward(t, t->src0_, t->src1_);
break;
case kOpNorm:
norm_forward(t, t->src0_);
break;
case kOpTranspose:
transpose_forward(t, t->src0_, t->op_params_[0], t->op_params_[1]);
break;
case kOpView:
view_forward(t, t->src0_, t->op_params_[0], t->op_params_[1]);
break;
case kOpBroadcast:
broadcast_forward(t, t->src0_);
break;
case kOpGelu:
gelu_forward(t, t->src0_);
break;
case kOpSoftmax:
softmax_forward(t, t->src0_, t->op_params_[0], t->op_params_[1]);
break;
case kOpCrossEntropy:
cross_entropy_forward(t, t->src0_, t->src1_);
break;
case kOpNone:
// no-op
break;
default:
throw std::runtime_error("Forward(): Not implemented, " +
TENSOR_OP_NAMES[t->op_]);
}
clock_gettime(CLOCK_MONOTONIC, &end);
ForwardProfile.AddTime(t->op_,
end.tv_sec - start.tv_sec + (end.tv_nsec - start.tv_nsec) / 1e9);
}
}
void Backward(bool init_grad = true, float init_val = 1.0f) {
std::vector<Tensor *> sorted = topo_sort(this);
if (init_grad) {
AllocGrad(false)->grad()->Fill(init_val);
}
struct timespec start, end;
BackwardProfile.Reset();
for (auto *t : sorted | std::ranges::views::reverse) {
clock_gettime(CLOCK_MONOTONIC, &start);
switch (t->op_) {
case kOpAdd:
add_backward(t, t->src0_, t->src1_);
break;
case kOpMul:
mul_backward(t, t->src0_, t->src1_);
break;
case kOpMatmul:
matmul_backward(t, t->src0_, t->src1_);
break;
case kOpLookup:
lookup_backward(t, t->src0_, t->src1_);
break;
case kOpNorm:
norm_backward(t, t->src0_);
break;
case kOpTranspose:
transpose_backward(t, t->src0_, t->op_params_[0], t->op_params_[1]);
break;
case kOpView:
view_backward(t, t->src0_, t->op_params_[0], t->op_params_[1]);
break;
case kOpBroadcast:
broadcast_backward(t, t->src0_);
break;
case kOpGelu:
gelu_backward(t, t->src0_);
break;
case kOpSoftmax:
softmax_backward(t, t->src0_, t->op_params_[0], t->op_params_[1]);
break;
case kOpCrossEntropy:
cross_entropy_backward(t, t->src0_, t->src1_);
break;
case kOpNone:
// no-op
break;
default:
throw std::runtime_error("Backward(): Not implemented, " +
TENSOR_OP_NAMES[t->op_]);
}
clock_gettime(CLOCK_MONOTONIC, &end);
BackwardProfile.AddTime(
t->op_, end.tv_sec - start.tv_sec + (end.tv_nsec - start.tv_nsec) / 1e9);
}
}
void ZeroGrad() {
std::vector<Tensor *> sorted = topo_sort(this);
for (auto t : sorted) {
if (t->grad_ != nullptr) {
t->grad_->Fill(0.0f);
}
}
}
void PrintTensor(bool include_data = true, size_t sample_size = 10) {
std::cout << "Tensor" << std::endl;
std::cout << "------" << std::endl;
std::cout << "n_dims: " << n_dims_ << std::endl;
std::cout << "dims: ";
for (int i = kMaxTensorDims - n_dims_; i < kMaxTensorDims; i++) {
std::cout << dims_[i] << " ";
}
std::cout << std::endl;
std::cout << "stride: ";
for (int i = kMaxTensorDims - n_dims_; i < kMaxTensorDims; i++) {
std::cout << strides_[i] << " ";
}
std::cout << std::endl;
std::cout << "op: " << TENSOR_OP_NAMES[op_] << "(" << this << ")" << std::endl;
if (src0_ != nullptr) {
std::cout << "src0: " << TENSOR_OP_NAMES[src0_->op_] << "(" << src0_ << ")"
<< std::endl;
}
if (src1_ != nullptr) {
std::cout << "src1: " << TENSOR_OP_NAMES[src1_->op_] << "(" << src1_ << ")"
<< std::endl;
}
if (include_data) {
std::cout << "data: \n";
size_t upto = std::min(n_vec(), sample_size);
for (size_t i = 0; i < upto; i++) {
vec_print(vsize(), type_, data_ + i * vstride() * kTypeSize[type_]);
std::cout << std::endl;
}
if (grad_ != nullptr) {
std::cout << "grad: \n";
for (size_t i = 0; i < upto; i++) {
vec_print(grad_->vsize(), type_,
grad_->data_ + i * grad_->vstride() * kTypeSize[type_]);
std::cout << std::endl;
}
}
}
}
public:
TensorType type() { return type_; }
std::byte *data() { return data_; }
inline Tensor *grad() { return grad_; }
// just for testing
inline Tensor *RandomGrad() {
grad_ = ctx_->NewTensor(Dims())->RandomNorm();
return this;
}
// just for testing
inline Tensor *FillGrad(float *data) {
assert(grad_ == nullptr);
grad_ = ctx_->NewTensor(Dims())->Fill(data);
return this;
}
inline Tensor *AllocGrad(bool init = true) {
if (grad_ == nullptr) {
grad_ = ctx_->NewTensor(Dims());
if (init) {
grad_->Fill(0.0f);
}
}
return this;
}
inline Tensor *CopyDataFrom(const Tensor &other) {
assert(SameShape(other));
memcpy(data_, other.data_, NumElements() * kTypeSize[type_]);
return this;
}
std::vector<Tensor *> Tensors() { return topo_sort(this); }
inline std::vector<float> Flatten() const { return Flatten<float>(); }
template <typename T>
inline std::vector<T> Flatten() const {
assert(IsTypeCompatible<T>(type_));
assert(IsContiguous());
if (data_ == nullptr) {
return {};
}
T *ptr = (T *)data_;
std::vector<T> vec(ptr, ptr + NumElements());
return vec;
}
inline size_t NumElements() const {
static_assert(kMaxTensorDims == 4, "MAX_TENSOR_DIMS is not 4 - update this function");
return (size_t)dims_[0] * dims_[1] * dims_[2] * dims_[3];
}
template <typename T>
Tensor *Fill(const std::vector<T> &in_data) {
assert(in_data.size() == NumElements());
return Fill(in_data.data());
}
template <typename T>
typename std::enable_if<!std::is_pointer<T>::value, Tensor *>::type Fill(T val) {
assert(IsTypeCompatible<T>(type_));
for (size_t i = 0; i < n_vec(); i++) {
vec_fill(vsize(), (T *)data_ + i * vstride(), val);
}
return this;
}
template <typename T>
typename std::enable_if<std::is_scalar<T>::value, Tensor *>::type Fill(const T *in_data) {
assert(IsTypeCompatible<T>(type_));
assert(IsContiguous());
for (size_t i = 0; i < n_vec(); i++) {
vec_fill(vsize(), (T *)data_ + i * vstride(), in_data + i * vstride());
}
return this;
}
Tensor *RandomNorm() {
assert(type_ == kF32);
assert(IsContiguous());
for (size_t i = 0; i < n_vec(); i++) {
vec_random_norm(vsize(), (float *)data_ + i * vstride());
}
return this;
}
inline std::vector<int> Dims() const {
return std::vector<int>(dims_ + kMaxTensorDims - n_dims_, dims_ + kMaxTensorDims);
}
inline std::vector<size_t> Strides() const {
return std::vector<size_t>(strides_ + kMaxTensorDims - n_dims_, strides_ + kMaxTensorDims);
}
inline bool IsContiguous() const {
static_assert(kMaxTensorDims == 4, "MAX_TENSOR_DIMS is not 4 - update this function");
return strides_[3] == 1 && strides_[2] == strides_[3] * dims_[3] &&
strides_[1] == strides_[2] * dims_[2] && strides_[0] == strides_[1] * dims_[1];
}
bool SameShape(const Tensor &other, bool check_type = true, bool check_stride = false) const {
return Dims() == other.Dims() && (!check_stride || Strides() == other.Strides()) &&
(!check_type || type_ == other.type_);
}
private:
Tensor() = delete;
Tensor(TensorContextT<Tensor> *ctx, const std::vector<int> &shape, TensorType type,
std::byte *data)
: ctx_(ctx),
n_dims_(shape.size()),
data_(data),
type_(type),
op_(kOpNone),
grad_(nullptr),
src0_(nullptr),
src1_(nullptr) {
assert(n_dims_ <= kMaxTensorDims);
for (int i = 0; i < n_dims_; i++) {
dims_[i + kMaxTensorDims - n_dims_] = shape[i];
}
for (int i = 0; i < kMaxTensorDims - n_dims_; i++) {
dims_[i] = 1;
}
strides_[kMaxTensorDims - 1] = 1;
for (int i = kMaxTensorDims - 2; i >= 0; i--) {
strides_[i] = strides_[i + 1] * dims_[i + 1];
}
}
static bool can_matmul(const Tensor &src0, const Tensor &src1) {
static_assert(kMaxTensorDims == 4, "MAX_TENSOR_DIMS is not 4 - update this function");
return src0.n_dims_ >= 2 && src0.n_dims_ == src1.n_dims_ &&
src0.dims_[3] == src1.dims_[3] && src0.dims_[0] == src1.dims_[0] &&
src0.dims_[1] == src1.dims_[1];
}
// start_dim_r is the starting dimension from the right
static bool can_broadcast_to(const Tensor &from, const Tensor &to, int start_dim_r = 0) {
const auto &shape = to.Dims();
bool ok = shape.size() >= from.n_dims_ && shape.size() <= kMaxTensorDims;
assert(from.n_dims_ >= start_dim_r);
for (int i = start_dim_r; i < from.n_dims_; i++) {
ok = ok && (from.dims_[kMaxTensorDims - i - 1] == shape[shape.size() - i - 1] ||
from.dims_[kMaxTensorDims - i - 1] == 1);
}
return ok;
}
// start_dim_r is the starting dimension from the right
static Tensor &broadcast_to(TensorContext *ctx, Tensor &from, const Tensor &to,
int start_dim_r = 0) {
// check that the shape is compatible with the current tensor
assert(can_broadcast_to(from, to, start_dim_r));
auto dshape = to.Dims();
for (int i = 0; i < start_dim_r; i++) {
dshape[dshape.size() - i - 1] = from.dims_[kMaxTensorDims - i - 1];
}
Tensor *dst = ctx->NewTensor(dshape, from.type_);
dst->op_ = kOpBroadcast;
dst->src0_ = &from;
return *dst;
}
size_t n_vec() const {
static_assert(kMaxTensorDims == 4, "MAX_TENSOR_DIMS is not 4 - update this function");
return (size_t)dims_[0] * dims_[1] * dims_[2];
}
size_t vstride() const {
static_assert(kMaxTensorDims == 4, "MAX_TENSOR_DIMS is not 4 - update this function");
return strides_[2];
}
size_t vsize() const {
static_assert(kMaxTensorDims == 4, "MAX_TENSOR_DIMS is not 4 - update this function");
return (size_t)dims_[3];
}
size_t n_mat() const {
static_assert(kMaxTensorDims == 4, "MAX_TENSOR_DIMS is not 4 - update this function");
return (size_t)dims_[0] * dims_[1];
}
std::tuple<int, int> mat() const {
static_assert(kMaxTensorDims == 4, "MAX_TENSOR_DIMS is not 4 - update this function");
return {dims_[2], dims_[3]};
}
size_t mstride() const {
static_assert(kMaxTensorDims == 4, "MAX_TENSOR_DIMS is not 4 - update this function");
return strides_[1];
}
static size_t num_of_elements(const std::vector<int> &shape) {
size_t e = 1;
for (auto s : shape) {
e *= s;
}
return e;
}
// Add
// TODO(ysg): support strided add
static void add_forward(Tensor *dst, Tensor *src0, Tensor *src1) {
assert(dst->type_ == kF32);
assert(src0->SameShape(*src1) && src1->SameShape(*dst));
assert(src0->IsContiguous() && src1->IsContiguous() && dst->IsContiguous());
size_t n = dst->n_vec();
for (size_t i = 0; i < n; i++) {
vec_add(dst->vsize(), (float *)dst->data_ + i * dst->vstride(),
(float *)src0->data_ + i * src0->vstride(),
(float *)src1->data_ + i * src1->vstride());
}
}
static void add_backward(Tensor *dst, Tensor *src0, Tensor *src1) {
if (src0->grad_ == nullptr) {
src0->AllocGrad(false)->grad()->CopyDataFrom(*dst->grad_);
} else {
add_forward(src0->grad_, src0->grad_, dst->grad_);
}
if (src1->grad_ == nullptr) {
src1->AllocGrad(false)->grad()->CopyDataFrom(*dst->grad_);
} else {
add_forward(src1->grad_, src1->grad_, dst->grad_);
}
}
// Mul
// TODO(ysg): support strided mul
static void mul_forward(Tensor *dst, Tensor *src0, Tensor *src1, bool is_acc = false) {
assert(dst->type_ == kF32);
assert(src0->SameShape(*src1) && src1->SameShape(*dst));
assert(src0->IsContiguous() && src1->IsContiguous() && dst->IsContiguous());
size_t n = dst->n_vec(), m = dst->vsize();
if (!is_acc) {
for (size_t i = 0; i < n; i++) {
float *out = (float *)dst->data_ + i * dst->vstride();
float *in0 = (float *)src0->data_ + i * src0->vstride();
float *in1 = (float *)src1->data_ + i * src1->vstride();
for (size_t j = 0; j < m; j++) {
out[j] = in0[j] * in1[j];
}
}
} else {
for (size_t i = 0; i < n; i++) {
float *out = (float *)dst->data_ + i * dst->vstride();
float *in0 = (float *)src0->data_ + i * src0->vstride();
float *in1 = (float *)src1->data_ + i * src1->vstride();
for (size_t j = 0; j < m; j++) {
out[j] += in0[j] * in1[j];
}
}
}
}
static void mul_backward(Tensor *dst, Tensor *src0, Tensor *src1) {
src0->AllocGrad();
mul_forward(src0->grad_, dst->grad_, src1, true);
src1->AllocGrad();
mul_forward(src1->grad_, dst->grad_, src0, true);
}
// Matmul
// TODO(ysg): support strided matmul
static void matmul_forward(Tensor *dst, Tensor *src0, Tensor *src1) {
assert(src0->n_mat() == dst->n_mat() && src1->n_mat() == dst->n_mat());
assert(dst->type_ == kF32 && src0->type_ == dst->type_ && src1->type_ == dst->type_);
assert(src0->IsContiguous() && src1->IsContiguous() && dst->IsContiguous());
size_t n = dst->dims_[2], m = dst->dims_[3], p = src0->dims_[3];
#pragma omp parallel for collapse(2)
for (size_t mati = 0; mati < dst->n_mat(); mati++) {
for (size_t i = 0; i < n; i++) {
float *out = (float *)dst->data_ + mati * dst->mstride() + i * dst->strides_[2];
float *in0 = (float *)src0->data_ + mati * src0->mstride() + i * src0->strides_[2];
for (size_t j = 0; j < m; j++) {
float *in1 =
(float *)src1->data_ + mati * src1->mstride() + j * src1->strides_[2];
out[j] = vec_dot_f32(p, in0, in1);
}
}
}
}
static void matmul_backward(Tensor *dst, Tensor *src0, Tensor *src1) {
src0->AllocGrad();
src1->AllocGrad();
size_t matn = dst->n_mat();
float *dout = (float *)dst->grad_->data_;
float *din0 = (float *)src0->grad_->data_, *in0 = (float *)src0->data_;
float *din1 = (float *)src1->grad_->data_, *in1 = (float *)src1->data_;
// src0->grad += dst->grad matmul src1^T
size_t n = src0->dims_[2], m = src0->dims_[3], p = dst->dims_[3];
#pragma omp parallel for collapse(2)
for (size_t mati = 0; mati < matn; mati++) {
float *in1_ma = in1 + mati * src1->mstride();
for (size_t i = 0; i < n; i++) {
float *din0_mai = din0 + mati * src0->mstride() + i * src0->strides_[2];
float *dout_mai = dout + mati * dst->mstride() + i * dst->strides_[2];
for (size_t k = 0; k < p; k++) {
for (size_t j = 0; j < m; j++) {
din0_mai[j] += dout_mai[k] * in1_ma[k * src1->strides_[2] + j];
}
}
}
}
// src1->grad += dst->grad^T matmul src0^T
n = src1->dims_[2], m = src1->dims_[3], p = dst->dims_[2];
#pragma omp parallel for
for (size_t mati = 0; mati < matn; mati++) {
float *dout_ma = dout + mati * dst->mstride();
float *in0_ma = in0 + mati * src0->mstride();
for (size_t k = 0; k < p; k++) {
for (size_t i = 0; i < n; i++) {
float *din1_mai = din1 + mati * src1->mstride() + i * src1->strides_[2];
for (size_t j = 0; j < m; j++) {
din1_mai[j] +=
dout_ma[k * dst->strides_[2] + i] * in0_ma[k * src0->strides_[2] + j];
}
}
}
}
}
inline static float vec_dot_f32(const size_t n, const float *va, const float *vb) {
float sum = 0.0f;
// TODO(ysg): resolve this
#ifdef F32_NEON_IS_SLOWER // __ARM_NEON
const size_t n4 = n / 4 * 4;
float32x4_t sum4 = vdupq_n_f32(0.0f);
for (size_t i = 0; i < n4; i += 4) {
float32x4_t va4 = vld1q_f32(va + i);
float32x4_t vb4 = vld1q_f32(vb + i);
sum4 = vmlaq_f32(sum4, va4, vb4);
}
sum = sum4[0] + sum4[1] + sum4[2] + sum4[3];
#else
const size_t n4 = 0;
#endif
for (size_t i = n4; i < n; i++) {
sum += va[i] * vb[i];
}
return sum;
}
// Lookup
static void lookup_forward(Tensor *dst, Tensor *src0, Tensor *src1) {
assert(dst->type_ == src0->type_ && src1->type_ == kI32);
assert(src0->IsContiguous() && src1->IsContiguous() && dst->IsContiguous());
size_t i0_size = src0->dims_[kMaxTensorDims - src0->n_dims_];
size_t i0_stride = src0->strides_[kMaxTensorDims - src0->n_dims_];
size_t type_size = kTypeSize[src0->type_];
for (size_t i = 0; i < src1->NumElements(); i++) {
int32_t idx = ((int32_t *)src1->data_)[i];
assert(idx >= 0 && idx < i0_size);
memcpy(dst->data_ + i * i0_stride * type_size,
src0->data_ + idx * i0_stride * type_size, i0_stride * type_size);
}
}
static void lookup_backward(Tensor *dst, Tensor *src0, Tensor *src1) {
src0->AllocGrad();
size_t i0_stride = src0->strides_[kMaxTensorDims - src0->n_dims_];
size_t type_size = kTypeSize[src0->type_];
for (size_t i = 0; i < src1->NumElements(); i++) {
int32_t idx = ((int32_t *)src1->data_)[i];
vec_add(i0_stride, (float *)src0->grad_->data_ + idx * i0_stride,
(float *)src0->grad_->data_ + idx * i0_stride,
(float *)dst->grad_->data_ + i * i0_stride);
}
}
// Norm
static void norm_forward(Tensor *dst, Tensor *src) {
assert(src->type_ == kF32 && dst->type_ == src->type_);
assert(src->IsContiguous() && dst->IsContiguous());
for (size_t idx = 0; idx < src->n_vec(); idx++) {
const float *vec = (float *)src->data_ + idx * src->vstride();
size_t vec_size = src->vsize();
// calculate the mean and the rstd (without bias correction)
float mean = vec_mean(vec_size, vec);
float rstd = vec_rstd(vec_size, vec, mean);
float *out = (float *)dst->data_ + idx * dst->vstride();
for (size_t i = 0; i < vec_size; i++) {
out[i] = (vec[i] - mean) * rstd;
}
}
}
static void norm_backward(Tensor *dst, Tensor *src) {
src->AllocGrad();
for (size_t idx = 0; idx < src->n_vec(); idx++) {
const float *a = (float *)src->data_ + idx * src->vstride();
const float *b = (float *)dst->data_ + idx * dst->vstride();
size_t vec_size = src->vsize();
assert(vec_size > 0);
float mean = vec_mean(vec_size, a);
float rstd = vec_rstd(vec_size, a, mean);
float *sgrad = (float *)src->grad_->data_ + idx * src->vstride();
float *dgrad = (float *)dst->grad_->data_ + idx * dst->vstride();
float dgrad_mean = 0.0f, dgrad2_mean = 0.0f;
for (size_t i = 0; i < vec_size; i++) {
dgrad_mean += dgrad[i];
dgrad2_mean += dgrad[i] * b[i];
}
dgrad_mean /= vec_size;
dgrad2_mean /= vec_size;
for (size_t i = 0; i < vec_size; i++) {