forked from leejet/stable-diffusion.cpp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtensor.hpp
More file actions
1645 lines (1451 loc) · 72.1 KB
/
tensor.hpp
File metadata and controls
1645 lines (1451 loc) · 72.1 KB
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
#ifndef __SD_TENSOR_HPP__
#define __SD_TENSOR_HPP__
#include <algorithm>
#include <cmath>
#include <cstdint>
#include <cstdio>
#include <initializer_list>
#include <memory>
#include <numeric>
#include <optional>
#include <sstream>
#include <stdexcept>
#include <string>
#include <type_traits>
#include <utility>
#include <vector>
#include "rng.hpp"
namespace sd {
template <typename T>
class Tensor;
inline std::vector<int64_t> tensor_unravel_index(int64_t flat, const std::vector<int64_t>& shape);
[[noreturn]] inline void tensor_throw_invalid_argument(const std::string& message) {
std::fprintf(stderr, "sd::Tensor error: %s\n", message.c_str());
std::fflush(stderr);
throw std::invalid_argument(message);
}
inline std::string tensor_shape_to_string(const std::vector<int64_t>& shape) {
std::ostringstream oss;
oss << "[";
for (size_t i = 0; i < shape.size(); ++i) {
if (i != 0) {
oss << ", ";
}
oss << shape[i];
}
oss << "]";
return oss.str();
}
inline int64_t tensor_numel(const std::vector<int64_t>& shape) {
if (shape.empty()) {
return 0;
}
int64_t numel = 1;
for (int64_t dim : shape) {
if (dim < 0) {
tensor_throw_invalid_argument("Tensor shape must be non-negative, got shape=" +
tensor_shape_to_string(shape));
}
numel *= dim;
}
return numel;
}
template <typename T>
class Tensor {
public:
Tensor() = default;
explicit Tensor(std::vector<int64_t> shape)
: data_(static_cast<size_t>(tensor_numel(shape))), shape_(std::move(shape)) {
}
Tensor(std::vector<int64_t> shape, std::vector<T> data)
: data_(std::move(data)), shape_(std::move(shape)) {
if (static_cast<int64_t>(data_.size()) != tensor_numel(shape_)) {
tensor_throw_invalid_argument("Tensor data size does not match shape: data.size()=" +
std::to_string(data_.size()) + ", shape=" +
tensor_shape_to_string(shape_) + ", numel=" +
std::to_string(tensor_numel(shape_)));
}
}
const std::vector<int64_t>& shape() const {
return shape_;
}
int64_t dim() const {
return static_cast<int64_t>(shape_.size());
}
int64_t numel() const {
return static_cast<int64_t>(data_.size());
}
bool empty() const {
return data_.empty();
}
T* data() {
return data_.data();
}
const T* data() const {
return data_.data();
}
std::vector<T>& values() {
return data_;
}
const std::vector<T>& values() const {
return data_;
}
void resize(std::vector<int64_t> shape) {
shape_ = std::move(shape);
data_.resize(static_cast<size_t>(tensor_numel(shape_)));
}
Tensor& reshape_(std::vector<int64_t> shape) {
if (tensor_numel(shape) != numel()) {
tensor_throw_invalid_argument("Tensor reshape changes element count: from shape=" +
tensor_shape_to_string(shape_) + " (numel=" +
std::to_string(numel()) + ") to shape=" +
tensor_shape_to_string(shape) + " (numel=" +
std::to_string(tensor_numel(shape)) + ")");
}
shape_ = std::move(shape);
return *this;
}
Tensor reshape(std::vector<int64_t> shape) const {
Tensor result = *this;
result.reshape_(std::move(shape));
return result;
}
Tensor& squeeze_() {
std::vector<int64_t> new_shape;
new_shape.reserve(shape_.size());
for (int64_t dim : shape_) {
if (dim != 1) {
new_shape.push_back(dim);
}
}
shape_ = std::move(new_shape);
return *this;
}
Tensor& squeeze_(size_t dim) {
if (dim >= shape_.size()) {
tensor_throw_invalid_argument("Tensor squeeze dimension out of range: dim=" +
std::to_string(dim) + ", shape=" +
tensor_shape_to_string(shape_));
}
if (shape_[dim] != 1) {
tensor_throw_invalid_argument("Tensor squeeze requires dimension size 1: dim=" +
std::to_string(dim) + ", shape=" +
tensor_shape_to_string(shape_));
}
shape_.erase(shape_.begin() + static_cast<std::ptrdiff_t>(dim));
return *this;
}
Tensor squeeze() const {
Tensor result = *this;
result.squeeze_();
return result;
}
Tensor squeeze(size_t dim) const {
Tensor result = *this;
result.squeeze_(dim);
return result;
}
Tensor& unsqueeze_(size_t dim) {
if (dim > shape_.size()) {
tensor_throw_invalid_argument("Tensor unsqueeze dimension out of range: dim=" +
std::to_string(dim) + ", shape=" +
tensor_shape_to_string(shape_));
}
shape_.insert(shape_.begin() + static_cast<std::ptrdiff_t>(dim), 1);
return *this;
}
Tensor unsqueeze(size_t dim) const {
Tensor result = *this;
result.unsqueeze_(dim);
return result;
}
Tensor permute(const std::vector<size_t>& dims) const {
if (dims.size() != static_cast<size_t>(dim())) {
tensor_throw_invalid_argument("Tensor permute requires one dimension index per axis: tensor_shape=" +
tensor_shape_to_string(shape_) + ", dims_size=" +
std::to_string(dims.size()));
}
std::vector<bool> seen(dims.size(), false);
std::vector<int64_t> out_shape(dims.size(), 1);
for (size_t i = 0; i < dims.size(); ++i) {
size_t dim_index = dims[i];
if (dim_index >= dims.size() || seen[dim_index]) {
tensor_throw_invalid_argument("Tensor permute dimensions must be a valid permutation: tensor_shape=" +
tensor_shape_to_string(shape_));
}
seen[dim_index] = true;
out_shape[i] = shape_[dim_index];
}
Tensor result(out_shape);
if (result.numel() == 0) {
return result;
}
for (int64_t flat = 0; flat < result.numel(); ++flat) {
std::vector<int64_t> out_coord = tensor_unravel_index(flat, out_shape);
std::vector<int64_t> src_coord(static_cast<size_t>(dim()), 0);
for (size_t i = 0; i < dims.size(); ++i) {
src_coord[dims[i]] = out_coord[i];
}
result[flat] = index(src_coord);
}
return result;
}
Tensor& permute_(const std::vector<size_t>& dims) {
*this = permute(dims);
return *this;
}
void fill_(const T& value) {
std::fill(data_.begin(), data_.end(), value);
}
Tensor& masked_fill_(const Tensor<uint8_t>& mask, const T& value);
T mean() const;
static Tensor zeros(std::vector<int64_t> shape) {
return Tensor(std::move(shape));
}
static Tensor zeros_like(const Tensor& other) {
return zeros(other.shape());
}
static Tensor ones(std::vector<int64_t> shape) {
return full(std::move(shape), static_cast<T>(1));
}
static Tensor ones_like(const Tensor& other) {
return ones(other.shape());
}
static Tensor full(std::vector<int64_t> shape, const T& value) {
Tensor tensor(std::move(shape));
tensor.fill_(value);
return tensor;
}
static Tensor randn(std::vector<int64_t> shape, const std::shared_ptr<RNG>& rng) {
static_assert(std::is_same_v<T, float>, "Tensor::randn currently requires Tensor<float>");
if (!rng) {
tensor_throw_invalid_argument("Tensor randn requires a valid RNG");
}
const uint32_t size = static_cast<uint32_t>(tensor_numel(shape));
return Tensor(std::move(shape), rng->randn(size));
}
static Tensor randn_like(const Tensor& other, const std::shared_ptr<RNG>& rng) {
return randn(other.shape(), rng);
}
static Tensor from_vector(std::vector<T> data) {
const int64_t size = static_cast<int64_t>(data.size());
return Tensor({size}, std::move(data));
}
T& index(const std::vector<int64_t>& coord) {
return data_.at(offset_of(coord));
}
const T& index(const std::vector<int64_t>& coord) const {
return data_.at(offset_of(coord));
}
template <typename... Indices, typename = std::enable_if_t<(std::is_convertible_v<Indices, int64_t> && ...)>>
T& index(Indices... indices) {
return index(std::vector<int64_t>{static_cast<int64_t>(indices)...});
}
template <typename... Indices, typename = std::enable_if_t<(std::is_convertible_v<Indices, int64_t> && ...)>>
const T& index(Indices... indices) const {
return index(std::vector<int64_t>{static_cast<int64_t>(indices)...});
}
T& operator[](int64_t index) {
return data_.at(static_cast<size_t>(index));
}
const T& operator[](int64_t index) const {
return data_.at(static_cast<size_t>(index));
}
private:
size_t offset_of(const std::vector<int64_t>& coord) const {
if (coord.size() != shape_.size()) {
tensor_throw_invalid_argument("Tensor index rank mismatch: coord_rank=" +
std::to_string(coord.size()) + ", shape=" +
tensor_shape_to_string(shape_));
}
size_t offset = 0;
size_t stride = 1;
for (size_t i = 0; i < shape_.size(); ++i) {
if (coord[i] < 0 || coord[i] >= shape_[i]) {
tensor_throw_invalid_argument("Tensor index out of range: shape=" +
tensor_shape_to_string(shape_));
}
offset += static_cast<size_t>(coord[i]) * stride;
stride *= static_cast<size_t>(shape_[i]);
}
return offset;
}
std::vector<T> data_;
std::vector<int64_t> shape_;
};
template <typename T>
inline T Tensor<T>::mean() const {
if (empty()) {
return T{};
}
T sum = T{};
for (const T& value : data_) {
sum += value;
}
return sum / static_cast<T>(numel());
}
template <>
inline float Tensor<float>::mean() const {
if (empty()) {
return 0.0f;
}
double sum = 0.0;
for (float value : data_) {
sum += static_cast<double>(value);
}
return static_cast<float>(sum / static_cast<double>(numel()));
}
template <typename T>
inline void tensor_check_same_shape(const Tensor<T>& lhs, const Tensor<T>& rhs) {
if (lhs.shape() != rhs.shape()) {
tensor_throw_invalid_argument("Tensor shapes must match: lhs_shape=" +
tensor_shape_to_string(lhs.shape()) + ", rhs_shape=" +
tensor_shape_to_string(rhs.shape()));
}
}
inline std::vector<int64_t> tensor_broadcast_shape(const std::vector<int64_t>& lhs, const std::vector<int64_t>& rhs) {
size_t ndim = std::max(lhs.size(), rhs.size());
std::vector<int64_t> shape(ndim, 1);
for (size_t i = 0; i < ndim; ++i) {
int64_t lhs_dim = lhs.size() > i ? lhs[i] : 1;
int64_t rhs_dim = rhs.size() > i ? rhs[i] : 1;
if (lhs_dim != rhs_dim && lhs_dim != 1 && rhs_dim != 1) {
tensor_throw_invalid_argument("Tensor shapes are not broadcastable: lhs_shape=" +
tensor_shape_to_string(lhs) + ", rhs_shape=" +
tensor_shape_to_string(rhs));
}
shape[i] = std::max(lhs_dim, rhs_dim);
}
return shape;
}
inline std::vector<int64_t> tensor_unravel_index(int64_t flat, const std::vector<int64_t>& shape) {
std::vector<int64_t> coord(shape.size(), 0);
for (size_t i = 0; i < shape.size(); ++i) {
if (shape[i] <= 0) {
tensor_throw_invalid_argument("Tensor unravel_index requires positive shape: shape=" +
tensor_shape_to_string(shape));
}
coord[i] = flat % shape[i];
flat /= shape[i];
}
return coord;
}
inline std::vector<int64_t> tensor_compute_strides(const std::vector<int64_t>& shape) {
std::vector<int64_t> strides(shape.size(), 1);
int64_t stride = 1;
for (size_t i = 0; i < shape.size(); ++i) {
strides[i] = stride;
stride *= shape[i];
}
return strides;
}
template <typename F>
inline void tensor_for_each_broadcast_offset(const std::vector<int64_t>& out_shape,
const std::vector<int64_t>& lhs_shape_raw,
const std::vector<int64_t>& lhs_strides_raw,
const std::vector<int64_t>& rhs_shape_raw,
const std::vector<int64_t>& rhs_strides_raw,
F&& fn) {
const size_t ndim = out_shape.size();
std::vector<int64_t> out_strides = tensor_compute_strides(out_shape);
std::vector<int64_t> lhs_shape(ndim, 1);
std::vector<int64_t> lhs_strides(ndim, 0);
std::vector<int64_t> rhs_shape(ndim, 1);
std::vector<int64_t> rhs_strides(ndim, 0);
for (size_t i = 0; i < lhs_shape_raw.size(); ++i) {
lhs_shape[i] = lhs_shape_raw[i];
lhs_strides[i] = lhs_strides_raw[i];
}
for (size_t i = 0; i < rhs_shape_raw.size(); ++i) {
rhs_shape[i] = rhs_shape_raw[i];
rhs_strides[i] = rhs_strides_raw[i];
}
const int64_t numel = tensor_numel(out_shape);
for (int64_t flat = 0; flat < numel; ++flat) {
int64_t remaining = flat;
int64_t lhs_offset = 0;
int64_t rhs_offset = 0;
for (size_t i = ndim; i-- > 0;) {
int64_t coord = remaining / out_strides[i];
remaining %= out_strides[i];
if (lhs_shape[i] != 1) {
lhs_offset += coord * lhs_strides[i];
}
if (rhs_shape[i] != 1) {
rhs_offset += coord * rhs_strides[i];
}
}
fn(flat, lhs_offset, rhs_offset);
}
}
template <typename T>
inline Tensor<T>& Tensor<T>::masked_fill_(const Tensor<uint8_t>& mask, const T& value) {
if (empty()) {
return *this;
}
tensor_broadcast_shape(shape_, mask.shape());
const std::vector<int64_t> data_strides = tensor_compute_strides(shape_);
const std::vector<int64_t> mask_strides = tensor_compute_strides(mask.shape());
const uint8_t* mask_data = mask.data();
tensor_for_each_broadcast_offset(shape_,
shape_,
data_strides,
mask.shape(),
mask_strides,
[&](int64_t, int64_t data_offset, int64_t mask_offset) {
if (mask_data[mask_offset] != 0) {
data_[static_cast<size_t>(data_offset)] = value;
}
});
return *this;
}
template <typename T, typename Scalar, typename = std::enable_if_t<std::is_arithmetic<Scalar>::value>>
inline Tensor<uint8_t> operator<(const Tensor<T>& lhs, Scalar rhs) {
Tensor<uint8_t> result(lhs.shape());
const T value = static_cast<T>(rhs);
for (int64_t i = 0; i < lhs.numel(); ++i) {
result[i] = lhs[i] < value ? 1 : 0;
}
return result;
}
template <typename T, typename Scalar, typename = std::enable_if_t<std::is_arithmetic<Scalar>::value>>
inline Tensor<uint8_t> operator<(Scalar lhs, const Tensor<T>& rhs) {
Tensor<uint8_t> result(rhs.shape());
const T value = static_cast<T>(lhs);
for (int64_t i = 0; i < rhs.numel(); ++i) {
result[i] = value < rhs[i] ? 1 : 0;
}
return result;
}
template <typename T>
inline Tensor<uint8_t> operator<(const Tensor<T>& lhs, const Tensor<T>& rhs) {
const std::vector<int64_t> out_shape = tensor_broadcast_shape(lhs.shape(), rhs.shape());
Tensor<uint8_t> result(out_shape);
const std::vector<int64_t> lhs_strides = tensor_compute_strides(lhs.shape());
const std::vector<int64_t> rhs_strides = tensor_compute_strides(rhs.shape());
const T* lhs_data = lhs.data();
const T* rhs_data = rhs.data();
tensor_for_each_broadcast_offset(out_shape,
lhs.shape(),
lhs_strides,
rhs.shape(),
rhs_strides,
[&](int64_t flat, int64_t lhs_offset, int64_t rhs_offset) {
result[flat] = lhs_data[lhs_offset] < rhs_data[rhs_offset] ? 1 : 0;
});
return result;
}
template <typename T>
inline Tensor<T>& operator+=(Tensor<T>& lhs, const Tensor<T>& rhs) {
if (lhs.shape() == rhs.shape()) {
for (int64_t i = 0; i < lhs.numel(); ++i) {
lhs[i] += rhs[i];
}
return lhs;
}
tensor_broadcast_shape(lhs.shape(), rhs.shape());
const std::vector<int64_t> lhs_strides = tensor_compute_strides(lhs.shape());
const std::vector<int64_t> rhs_strides = tensor_compute_strides(rhs.shape());
const T* rhs_data = rhs.data();
tensor_for_each_broadcast_offset(lhs.shape(),
lhs.shape(),
lhs_strides,
rhs.shape(),
rhs_strides,
[&](int64_t, int64_t lhs_offset, int64_t rhs_offset) {
lhs[static_cast<int64_t>(lhs_offset)] += rhs_data[rhs_offset];
});
return lhs;
}
template <typename T, typename Scalar, typename = std::enable_if_t<std::is_arithmetic<Scalar>::value>>
inline Tensor<T>& operator+=(Tensor<T>& lhs, Scalar rhs) {
const T value = static_cast<T>(rhs);
for (int64_t i = 0; i < lhs.numel(); ++i) {
lhs[i] += value;
}
return lhs;
}
template <typename T>
inline Tensor<T>& operator-=(Tensor<T>& lhs, const Tensor<T>& rhs) {
if (lhs.shape() == rhs.shape()) {
for (int64_t i = 0; i < lhs.numel(); ++i) {
lhs[i] -= rhs[i];
}
return lhs;
}
tensor_broadcast_shape(lhs.shape(), rhs.shape());
const std::vector<int64_t> lhs_strides = tensor_compute_strides(lhs.shape());
const std::vector<int64_t> rhs_strides = tensor_compute_strides(rhs.shape());
const T* rhs_data = rhs.data();
tensor_for_each_broadcast_offset(lhs.shape(),
lhs.shape(),
lhs_strides,
rhs.shape(),
rhs_strides,
[&](int64_t, int64_t lhs_offset, int64_t rhs_offset) {
lhs[static_cast<int64_t>(lhs_offset)] -= rhs_data[rhs_offset];
});
return lhs;
}
template <typename T, typename Scalar, typename = std::enable_if_t<std::is_arithmetic<Scalar>::value>>
inline Tensor<T>& operator-=(Tensor<T>& lhs, Scalar rhs) {
const T value = static_cast<T>(rhs);
for (int64_t i = 0; i < lhs.numel(); ++i) {
lhs[i] -= value;
}
return lhs;
}
template <typename T>
inline Tensor<T>& operator*=(Tensor<T>& lhs, const Tensor<T>& rhs) {
if (lhs.shape() == rhs.shape()) {
for (int64_t i = 0; i < lhs.numel(); ++i) {
lhs[i] *= rhs[i];
}
return lhs;
}
tensor_broadcast_shape(lhs.shape(), rhs.shape());
const std::vector<int64_t> lhs_strides = tensor_compute_strides(lhs.shape());
const std::vector<int64_t> rhs_strides = tensor_compute_strides(rhs.shape());
const T* rhs_data = rhs.data();
tensor_for_each_broadcast_offset(lhs.shape(),
lhs.shape(),
lhs_strides,
rhs.shape(),
rhs_strides,
[&](int64_t, int64_t lhs_offset, int64_t rhs_offset) {
lhs[static_cast<int64_t>(lhs_offset)] *= rhs_data[rhs_offset];
});
return lhs;
}
template <typename T, typename Scalar, typename = std::enable_if_t<std::is_arithmetic<Scalar>::value>>
inline Tensor<T>& operator*=(Tensor<T>& lhs, Scalar rhs) {
const T value = static_cast<T>(rhs);
for (int64_t i = 0; i < lhs.numel(); ++i) {
lhs[i] *= value;
}
return lhs;
}
template <typename T>
inline Tensor<T>& operator/=(Tensor<T>& lhs, const Tensor<T>& rhs) {
if (lhs.shape() == rhs.shape()) {
for (int64_t i = 0; i < lhs.numel(); ++i) {
lhs[i] /= rhs[i];
}
return lhs;
}
tensor_broadcast_shape(lhs.shape(), rhs.shape());
const std::vector<int64_t> lhs_strides = tensor_compute_strides(lhs.shape());
const std::vector<int64_t> rhs_strides = tensor_compute_strides(rhs.shape());
const T* rhs_data = rhs.data();
tensor_for_each_broadcast_offset(lhs.shape(),
lhs.shape(),
lhs_strides,
rhs.shape(),
rhs_strides,
[&](int64_t, int64_t lhs_offset, int64_t rhs_offset) {
lhs[static_cast<int64_t>(lhs_offset)] /= rhs_data[rhs_offset];
});
return lhs;
}
template <typename T, typename Scalar, typename = std::enable_if_t<std::is_arithmetic<Scalar>::value>>
inline Tensor<T>& operator/=(Tensor<T>& lhs, Scalar rhs) {
const T value = static_cast<T>(rhs);
for (int64_t i = 0; i < lhs.numel(); ++i) {
lhs[i] /= value;
}
return lhs;
}
template <typename T>
inline Tensor<T> operator+(Tensor<T> lhs, const Tensor<T>& rhs) {
if (lhs.shape() != rhs.shape()) {
const std::vector<int64_t> out_shape = tensor_broadcast_shape(lhs.shape(), rhs.shape());
Tensor<T> result(out_shape);
const std::vector<int64_t> lhs_strides = tensor_compute_strides(lhs.shape());
const std::vector<int64_t> rhs_strides = tensor_compute_strides(rhs.shape());
const T* lhs_data = lhs.data();
const T* rhs_data = rhs.data();
tensor_for_each_broadcast_offset(out_shape,
lhs.shape(),
lhs_strides,
rhs.shape(),
rhs_strides,
[&](int64_t flat, int64_t lhs_offset, int64_t rhs_offset) {
result[flat] = lhs_data[lhs_offset] + rhs_data[rhs_offset];
});
return result;
}
lhs += rhs;
return lhs;
}
template <typename T, typename Scalar, typename = std::enable_if_t<std::is_arithmetic<Scalar>::value>>
inline Tensor<T> operator+(Tensor<T> lhs, Scalar rhs) {
lhs += rhs;
return lhs;
}
template <typename T, typename Scalar, typename = std::enable_if_t<std::is_arithmetic<Scalar>::value>>
inline Tensor<T> operator+(Scalar lhs, Tensor<T> rhs) {
rhs += lhs;
return rhs;
}
template <typename T>
inline Tensor<T> operator-(Tensor<T> lhs, const Tensor<T>& rhs) {
if (lhs.shape() != rhs.shape()) {
const std::vector<int64_t> out_shape = tensor_broadcast_shape(lhs.shape(), rhs.shape());
Tensor<T> result(out_shape);
const std::vector<int64_t> lhs_strides = tensor_compute_strides(lhs.shape());
const std::vector<int64_t> rhs_strides = tensor_compute_strides(rhs.shape());
const T* lhs_data = lhs.data();
const T* rhs_data = rhs.data();
tensor_for_each_broadcast_offset(out_shape,
lhs.shape(),
lhs_strides,
rhs.shape(),
rhs_strides,
[&](int64_t flat, int64_t lhs_offset, int64_t rhs_offset) {
result[flat] = lhs_data[lhs_offset] - rhs_data[rhs_offset];
});
return result;
}
lhs -= rhs;
return lhs;
}
template <typename T, typename Scalar, typename = std::enable_if_t<std::is_arithmetic<Scalar>::value>>
inline Tensor<T> operator-(Tensor<T> lhs, Scalar rhs) {
lhs -= rhs;
return lhs;
}
template <typename T, typename Scalar, typename = std::enable_if_t<std::is_arithmetic<Scalar>::value>>
inline Tensor<T> operator-(Scalar lhs, const Tensor<T>& rhs) {
Tensor<T> result = rhs;
const T value = static_cast<T>(lhs);
for (int64_t i = 0; i < result.numel(); ++i) {
result[i] = value - result[i];
}
return result;
}
template <typename T>
inline Tensor<T> operator*(Tensor<T> lhs, const Tensor<T>& rhs) {
if (lhs.shape() != rhs.shape()) {
const std::vector<int64_t> out_shape = tensor_broadcast_shape(lhs.shape(), rhs.shape());
Tensor<T> result(out_shape);
const std::vector<int64_t> lhs_strides = tensor_compute_strides(lhs.shape());
const std::vector<int64_t> rhs_strides = tensor_compute_strides(rhs.shape());
const T* lhs_data = lhs.data();
const T* rhs_data = rhs.data();
tensor_for_each_broadcast_offset(out_shape,
lhs.shape(),
lhs_strides,
rhs.shape(),
rhs_strides,
[&](int64_t flat, int64_t lhs_offset, int64_t rhs_offset) {
result[flat] = lhs_data[lhs_offset] * rhs_data[rhs_offset];
});
return result;
}
lhs *= rhs;
return lhs;
}
template <typename T, typename Scalar, typename = std::enable_if_t<std::is_arithmetic<Scalar>::value>>
inline Tensor<T> operator*(Tensor<T> lhs, Scalar rhs) {
lhs *= rhs;
return lhs;
}
template <typename T, typename Scalar, typename = std::enable_if_t<std::is_arithmetic<Scalar>::value>>
inline Tensor<T> operator*(Scalar lhs, Tensor<T> rhs) {
rhs *= lhs;
return rhs;
}
template <typename T>
inline Tensor<T> operator/(Tensor<T> lhs, const Tensor<T>& rhs) {
if (lhs.shape() != rhs.shape()) {
const std::vector<int64_t> out_shape = tensor_broadcast_shape(lhs.shape(), rhs.shape());
Tensor<T> result(out_shape);
const std::vector<int64_t> lhs_strides = tensor_compute_strides(lhs.shape());
const std::vector<int64_t> rhs_strides = tensor_compute_strides(rhs.shape());
const T* lhs_data = lhs.data();
const T* rhs_data = rhs.data();
tensor_for_each_broadcast_offset(out_shape,
lhs.shape(),
lhs_strides,
rhs.shape(),
rhs_strides,
[&](int64_t flat, int64_t lhs_offset, int64_t rhs_offset) {
result[flat] = lhs_data[lhs_offset] / rhs_data[rhs_offset];
});
return result;
}
lhs /= rhs;
return lhs;
}
template <typename T, typename Scalar, typename = std::enable_if_t<std::is_arithmetic<Scalar>::value>>
inline Tensor<T> operator/(Tensor<T> lhs, Scalar rhs) {
lhs /= rhs;
return lhs;
}
template <typename T, typename Scalar, typename = std::enable_if_t<std::is_arithmetic<Scalar>::value>>
inline Tensor<T> operator/(Scalar lhs, const Tensor<T>& rhs) {
Tensor<T> result = rhs;
const T value = static_cast<T>(lhs);
for (int64_t i = 0; i < result.numel(); ++i) {
result[i] = value / result[i];
}
return result;
}
template <typename T>
inline Tensor<T> operator-(const Tensor<T>& tensor) {
Tensor<T> result = tensor;
for (int64_t i = 0; i < result.numel(); ++i) {
result[i] = -result[i];
}
return result;
}
template <typename T>
inline Tensor<T> zeros(std::vector<int64_t> shape) {
return Tensor<T>::zeros(std::move(shape));
}
template <typename T>
inline Tensor<T> full(std::vector<int64_t> shape, const T& value) {
return Tensor<T>::full(std::move(shape), value);
}
template <typename T>
inline Tensor<T> randn(std::vector<int64_t> shape, const std::shared_ptr<RNG>& rng) {
return Tensor<T>::randn(std::move(shape), rng);
}
template <typename T>
inline Tensor<T> randn_like(const Tensor<T>& tensor, const std::shared_ptr<RNG>& rng) {
return Tensor<T>::randn(tensor.shape(), rng);
}
template <typename T>
inline std::vector<T> tensor_to_vector(const Tensor<T>& tensor) {
return tensor.values();
}
namespace ops {
enum class InterpolateMode {
Nearest,
NearestExact,
NearestMax,
NearestMin,
NearestAvg,
Bilinear,
Bicubic,
Lanczos,
};
inline bool is_nearest_like_interpolate_mode(InterpolateMode mode) {
return mode == InterpolateMode::Nearest ||
mode == InterpolateMode::NearestExact ||
mode == InterpolateMode::NearestMax ||
mode == InterpolateMode::NearestMin ||
mode == InterpolateMode::NearestAvg;
}
inline bool is_2d_filter_interpolate_mode(InterpolateMode mode) {
return mode == InterpolateMode::Bilinear ||
mode == InterpolateMode::Bicubic ||
mode == InterpolateMode::Lanczos;
}
inline int64_t nearest_exact_interpolate_index(int64_t output_index,
int64_t input_size,
int64_t output_size) {
const double scale = static_cast<double>(input_size) / static_cast<double>(output_size);
const double center = (static_cast<double>(output_index) + 0.5) * scale - 0.5;
return std::min(std::max<int64_t>(static_cast<int64_t>(std::floor(center + 0.5)), 0), input_size - 1);
}
inline double linear_interpolate_weight(double x) {
x = std::abs(x);
return x < 1.0 ? 1.0 - x : 0.0;
}
inline double cubic_interpolate_weight(double x) {
constexpr double a = -0.75; // Match PyTorch bicubic interpolation.
x = std::abs(x);
if (x <= 1.0) {
return ((a + 2.0) * x - (a + 3.0)) * x * x + 1.0;
}
if (x < 2.0) {
return ((a * x - 5.0 * a) * x + 8.0 * a) * x - 4.0 * a;
}
return 0.0;
}
inline double sinc(double x) {
constexpr double pi = 3.14159265358979323846;
if (std::abs(x) < 1e-12) {
return 1.0;
}
const double pix = pi * x;
return std::sin(pix) / pix;
}
inline double lanczos_interpolate_weight(double x) {
constexpr double radius = 3.0;
x = std::abs(x);
if (x >= radius) {
return 0.0;
}
return sinc(x) * sinc(x / radius);
}
struct InterpolateContributor {
int64_t index;
double weight;
};
inline std::vector<std::vector<InterpolateContributor>> make_interpolate_contributors(
int64_t input_size,
int64_t output_size,
InterpolateMode mode,
bool antialias) {
std::vector<std::vector<InterpolateContributor>> contributors(static_cast<size_t>(output_size));
const double scale = static_cast<double>(input_size) / static_cast<double>(output_size);
const double filter_scale = antialias ? std::max(1.0, scale) : 1.0;
for (int64_t out = 0; out < output_size; ++out) {
const double center = (static_cast<double>(out) + 0.5) * scale - 0.5;
int64_t start = 0;
int64_t end = 0;
if (mode == InterpolateMode::Bilinear) {
const double support = filter_scale;
start = static_cast<int64_t>(std::ceil(center - support));
end = static_cast<int64_t>(std::floor(center + support));
} else if (mode == InterpolateMode::Bicubic) {
const double support = 2.0 * filter_scale;
start = static_cast<int64_t>(std::ceil(center - support));
end = static_cast<int64_t>(std::floor(center + support));
} else if (mode == InterpolateMode::Lanczos) {
const double support = 3.0 * filter_scale;
start = static_cast<int64_t>(std::ceil(center - support));
end = static_cast<int64_t>(std::floor(center + support));
} else {
tensor_throw_invalid_argument("Unsupported 2D filter interpolate mode: mode=" +
std::to_string(static_cast<int>(mode)));
}
double weight_sum = 0.0;
std::vector<InterpolateContributor>& axis_contributors = contributors[static_cast<size_t>(out)];
axis_contributors.reserve(static_cast<size_t>(end - start + 1));
for (int64_t in = start; in <= end; ++in) {
double weight = 0.0;
if (mode == InterpolateMode::Bilinear) {
weight = linear_interpolate_weight((center - static_cast<double>(in)) / filter_scale);
} else if (mode == InterpolateMode::Bicubic) {
weight = cubic_interpolate_weight((center - static_cast<double>(in)) / filter_scale);
} else {
weight = lanczos_interpolate_weight((center - static_cast<double>(in)) / filter_scale);
}
if (weight == 0.0) {
continue;
}
const int64_t clamped_index = std::min(std::max<int64_t>(in, 0), input_size - 1);
axis_contributors.push_back({clamped_index, weight});
weight_sum += weight;
}
if ((antialias || mode == InterpolateMode::Lanczos) &&
std::abs(weight_sum) > 1e-12) {
for (auto& contributor : axis_contributors) {
contributor.weight /= weight_sum;
}
}
if (axis_contributors.empty()) {
const int64_t nearest = std::min(
std::max<int64_t>(static_cast<int64_t>(std::floor(center + 0.5)), 0),
input_size - 1);
axis_contributors.push_back({nearest, 1.0});
}
}
return contributors;
}
template <typename T>
inline Tensor<T> interpolate_2d_filter(const Tensor<T>& input,
const std::vector<int64_t>& output_shape,
InterpolateMode mode,
bool antialias) {
if (input.dim() < 2) {
tensor_throw_invalid_argument("2D filter interpolate requires rank >= 2: input_shape=" +
tensor_shape_to_string(input.shape()) + ", output_shape=" +
tensor_shape_to_string(output_shape));
}
for (size_t i = 2; i < output_shape.size(); ++i) {
if (input.shape()[i] != output_shape[i]) {
tensor_throw_invalid_argument("2D filter interpolate only supports resizing dimensions 0 and 1: input_shape=" +
tensor_shape_to_string(input.shape()) + ", output_shape=" +
tensor_shape_to_string(output_shape));
}
}
Tensor<T> output(output_shape);
const int64_t input_width = input.shape()[0];
const int64_t input_height = input.shape()[1];
const int64_t output_width = output_shape[0];
const int64_t output_height = output_shape[1];
const int64_t input_plane = input_width * input_height;
const int64_t output_plane = output_width * output_height;
const int64_t plane_count = input.numel() / input_plane;
auto x_contributors = make_interpolate_contributors(input_width, output_width, mode, antialias);
auto y_contributors = make_interpolate_contributors(input_height, output_height, mode, antialias);
for (int64_t plane = 0; plane < plane_count; ++plane) {
const int64_t input_plane_offset = plane * input_plane;
const int64_t output_plane_offset = plane * output_plane;
for (int64_t y = 0; y < output_height; ++y) {
const auto& y_axis = y_contributors[static_cast<size_t>(y)];
for (int64_t x = 0; x < output_width; ++x) {
const auto& x_axis = x_contributors[static_cast<size_t>(x)];
double value = 0.0;
for (const auto& yc : y_axis) {
const int64_t input_row_offset = input_plane_offset + yc.index * input_width;