forked from dsharlet/array
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patharray.h
More file actions
3240 lines (2849 loc) · 133 KB
/
array.h
File metadata and controls
3240 lines (2849 loc) · 133 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
// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/** \file array.h
* \brief Main header for array library
*/
#ifndef NDARRAY_ARRAY_H
#define NDARRAY_ARRAY_H
#include <array>
// TODO(jiawen): CUDA *should* support assert on device. This might be due to the fact that we are
// not depending on the CUDA toolkit.
#if defined(__CUDA__)
#undef assert
#define assert(e)
#else
#include <cassert>
#endif
#include <cstdio>
#include <limits>
#include <memory>
#include <tuple>
#include <type_traits>
// Some things in this header are unbearably slow without optimization if they
// don't get inlined.
#if defined(__GNUC__)
#define NDARRAY_INLINE inline __attribute__((always_inline))
#elif defined(__clang__)
#if defined(__CUDA__)
#define NDARRAY_INLINE __forceinline__
#else
#define NDARRAY_INLINE inline __attribute__((always_inline))
#endif
#else
#define NDARRAY_INLINE inline
#endif
// Many of the functions in this header are templates that are usually unique
// specializations, which are beneficial to inline. The compiler will inline
// functions it knows are used only once, but it can't know this unless the
// functions have internal linkage.
#define NDARRAY_UNIQUE static
// Functions attributed with NDARRAY_HOST_DEVICE can run on both device and host mode on CUDA.
#if defined(__CUDA__)
#define NDARRAY_HOST_DEVICE __device__ __host__
#else
#define NDARRAY_HOST_DEVICE
#endif
#if defined(__GNUC__) || defined(__clang__)
#define NDARRAY_RESTRICT __restrict__
#else
#define NDARRAY_RESTRICT
#endif
#if defined(__CUDA__)
#define NDARRAY_PRINT_ERR(...) printf(__VA_ARGS__)
#else
#define NDARRAY_PRINT_ERR(...) fprintf(stderr, __VA_ARGS__)
#endif
namespace nda {
using size_t = std::size_t;
/** When `NDARRAY_INT_INDICES` is defined, array indices are `int` values, otherwise
* they are `std::ptrdiff_t`. std::ptrdiff_t is helpful for the compiler to
* optimize address arithmetic, because it has the same size as a pointer. */
#ifdef NDARRAY_INT_INDICES
using index_t = int;
#define NDARRAY_INDEX_T_FMT "%d"
#else
using index_t = std::ptrdiff_t;
#define NDARRAY_INDEX_T_FMT "%td"
#endif
/** This value indicates a compile-time constant parameter is an unknown value,
* and to use the corresponding runtime value instead. If a compile-time constant
* value is not `dynamic`, it is said to be `static`. A runtime value is said to be
* 'compatible with' a compile-time constant value if the values are equal, or the
* compile-time constant value is dynamic. */
// It would be better to use a more unreasonable value that would never be
// used in practice, or find a better way to express this pattern.
// (https://github.com/dsharlet/array/issues/9).
constexpr index_t dynamic = -9;
/** This value indicates a runtime parameter is an unknown value, and may be
* replaced by a default value computed by the library. */
constexpr index_t unresolved = std::numeric_limits<index_t>::min();
namespace internal {
// Workaround CUDA not supporting std::declval.
// https://stackoverflow.com/questions/31969644/compilation-error-with-nvcc-and-c11-need-minimal-failing-example
template <typename T>
NDARRAY_HOST_DEVICE typename std::add_rvalue_reference<T>::type declval() noexcept;
NDARRAY_INLINE constexpr index_t abs(index_t x) { return x >= 0 ? x : -x; }
NDARRAY_INLINE constexpr index_t is_static(index_t x) { return x != dynamic; }
NDARRAY_INLINE constexpr index_t is_dynamic(index_t x) { return x == dynamic; }
NDARRAY_INLINE constexpr index_t is_resolved(index_t x) { return x != unresolved; }
NDARRAY_INLINE constexpr index_t is_unresolved(index_t x) { return x == unresolved; }
constexpr bool is_dynamic(index_t a, index_t b) { return is_dynamic(a) || is_dynamic(b); }
// Returns true if a and b are statically not equal, but they may still be
// dynamically not equal even if this returns false.
constexpr bool not_equal(index_t a, index_t b) { return is_static(a) && is_static(b) && a != b; }
template <index_t A, index_t B>
using disable_if_not_equal = std::enable_if_t<!not_equal(A, B)>;
// Math for (possibly) static values.
constexpr index_t static_abs(index_t x) { return is_dynamic(x) ? dynamic : abs(x); }
constexpr index_t static_add(index_t a, index_t b) { return is_dynamic(a, b) ? dynamic : a + b; }
constexpr index_t static_sub(index_t a, index_t b) { return is_dynamic(a, b) ? dynamic : a - b; }
constexpr index_t static_mul(index_t a, index_t b) { return is_dynamic(a, b) ? dynamic : a * b; }
constexpr index_t static_min(index_t a, index_t b) {
return is_dynamic(a, b) ? dynamic : (a < b ? a : b);
}
constexpr index_t static_max(index_t a, index_t b) {
return is_dynamic(a, b) ? dynamic : (a > b ? a : b);
}
// A type that mimics a constexpr index_t with value Value, unless Value is
// dynamic, then mimics index_t.
template <index_t Value>
struct constexpr_index {
public:
// These asserts are really hard to debug
// https://github.com/dsharlet/array/issues/26
NDARRAY_HOST_DEVICE constexpr_index(index_t value = Value) { assert(value == Value); }
NDARRAY_HOST_DEVICE constexpr_index& operator=(index_t value) {
assert(value == Value);
return *this;
}
NDARRAY_HOST_DEVICE NDARRAY_INLINE operator index_t() const { return Value; }
};
template <>
struct constexpr_index<dynamic> {
index_t value_;
public:
NDARRAY_HOST_DEVICE constexpr_index(index_t value) : value_(value) {}
NDARRAY_HOST_DEVICE constexpr_index& operator=(index_t value) {
value_ = value;
return *this;
}
NDARRAY_INLINE NDARRAY_HOST_DEVICE operator index_t() const { return value_; }
};
// Defined here to avoid pulling in <algorithm>.
template <typename T>
constexpr const T& max(const T& a, const T& b) {
return (a < b) ? b : a;
}
template <typename T>
constexpr const T& min(const T& a, const T& b) {
return (b < a) ? b : a;
}
} // namespace internal
/** An iterator representing an index. */
class index_iterator {
index_t i_;
public:
/** Construct the iterator with an index `i`. */
index_iterator(index_t i) : i_(i) {}
/** Access the current index of this iterator. */
NDARRAY_INLINE NDARRAY_HOST_DEVICE index_t operator*() const { return i_; }
NDARRAY_INLINE NDARRAY_HOST_DEVICE bool operator==(const index_iterator& r) const {
return i_ == r.i_;
}
NDARRAY_INLINE NDARRAY_HOST_DEVICE bool operator!=(const index_iterator& r) const {
return i_ != r.i_;
}
NDARRAY_INLINE NDARRAY_HOST_DEVICE index_iterator operator++(int) { return index_iterator(i_++); }
NDARRAY_INLINE NDARRAY_HOST_DEVICE index_iterator operator--(int) { return index_iterator(i_--); }
NDARRAY_INLINE NDARRAY_HOST_DEVICE index_iterator& operator++() {
++i_;
return *this;
}
NDARRAY_INLINE NDARRAY_HOST_DEVICE index_iterator& operator--() {
--i_;
return *this;
}
NDARRAY_INLINE NDARRAY_HOST_DEVICE index_iterator& operator+=(index_t r) {
i_ += r;
return *this;
}
NDARRAY_INLINE NDARRAY_HOST_DEVICE index_iterator& operator-=(index_t r) {
i_ -= r;
return *this;
}
NDARRAY_INLINE NDARRAY_HOST_DEVICE index_iterator operator+(index_t r) {
return index_iterator(i_ + r);
}
NDARRAY_INLINE NDARRAY_HOST_DEVICE index_iterator operator-(index_t r) {
return index_iterator(i_ - r);
}
NDARRAY_INLINE NDARRAY_HOST_DEVICE index_t operator-(const index_iterator& r) {
return i_ - r.i_;
}
NDARRAY_INLINE NDARRAY_HOST_DEVICE index_t operator[](index_t n) const { return i_ + n; }
};
template <index_t Min, index_t Extent, index_t Stride>
class dim;
/** Describes a half-open interval of indices. The template parameters enable
* providing compile time constants for the `min` and `extent` of the interval.
* The values in the interval `[min, min + extent)` are considered in bounds.
*
* `interval<> a` is said to be 'compatible with' another `interval<Min, Extent> b` if
* `a.min()` is compatible with `Min` and `a.extent()` is compatible with `Extent`.
*
* Examples:
* - `interval<>` is an interval with runtime-valued `min` and `extent`.
* - `interval<0>` is an interval with compile-time constant `min` of 0, and
* runtime-valued `extent`.
* - `interval<dynamic, 8>` is an interval with compile-time constant `extent of 8
* and runtime-valued `min`.
* - `interval<2, 3>` is a fully compile-time constant interval of indices 2, 3, 4. */
template <index_t Min_ = dynamic, index_t Extent_ = dynamic>
class interval {
protected:
internal::constexpr_index<Min_> min_;
internal::constexpr_index<Extent_> extent_;
public:
static constexpr index_t Min = Min_;
static constexpr index_t Extent = Extent_;
static constexpr index_t Max = internal::static_sub(internal::static_add(Min, Extent), 1);
/** Construct a new interval object. If the `min` or `extent` is specified in
* the constructor, it must have a value compatible with `Min` or `Extent`,
* respectively.
*
* The default values if not specified in the constructor are:
* - The default `min` is `Min` if `Min` is static, or 0 if not.
* - The default `extent` is `Extent` if `Extent` is static, or 1 if not. */
NDARRAY_HOST_DEVICE interval(index_t min, index_t extent) : min_(min), extent_(extent) {}
NDARRAY_HOST_DEVICE interval(index_t min)
: interval(min, internal::is_static(Extent) ? Extent : 1) {}
NDARRAY_HOST_DEVICE interval() : interval(internal::is_static(Min) ? Min : 0) {}
NDARRAY_HOST_DEVICE interval(const interval&) = default;
NDARRAY_HOST_DEVICE interval(interval&&) = default;
NDARRAY_HOST_DEVICE interval& operator=(const interval&) = default;
NDARRAY_HOST_DEVICE interval& operator=(interval&&) = default;
/** Copy construction or assignment of another interval object, possibly
* with different compile-time template parameters. `other.min()` and
* `other.extent()` must be compatible with `Min` and `Extent`, respectively. */
template <index_t CopyMin, index_t CopyExtent,
class = internal::disable_if_not_equal<Min, CopyMin>,
class = internal::disable_if_not_equal<Extent, CopyExtent>>
NDARRAY_HOST_DEVICE interval(const interval<CopyMin, CopyExtent>& other)
: interval(other.min(), other.extent()) {}
template <index_t CopyMin, index_t CopyExtent,
class = internal::disable_if_not_equal<Min, CopyMin>,
class = internal::disable_if_not_equal<Extent, CopyExtent>>
NDARRAY_HOST_DEVICE interval& operator=(const interval<CopyMin, CopyExtent>& other) {
set_min(other.min());
set_extent(other.extent());
return *this;
}
/** Get or set the first index in this interval. */
NDARRAY_INLINE NDARRAY_HOST_DEVICE index_t min() const { return min_; }
NDARRAY_INLINE NDARRAY_HOST_DEVICE void set_min(index_t min) { min_ = min; }
/** Get or set the number of indices in this interval. */
NDARRAY_INLINE NDARRAY_HOST_DEVICE index_t extent() const { return extent_; }
NDARRAY_INLINE NDARRAY_HOST_DEVICE index_t size() const { return extent_; }
NDARRAY_INLINE NDARRAY_HOST_DEVICE void set_extent(index_t extent) { extent_ = extent; }
/** Get or set the last index in this interval. */
NDARRAY_INLINE NDARRAY_HOST_DEVICE index_t max() const { return min_ + extent_ - 1; }
NDARRAY_INLINE NDARRAY_HOST_DEVICE void set_max(index_t max) { set_extent(max - min_ + 1); }
/** Returns true if `at` is within the interval `[min(), max()]`. */
NDARRAY_INLINE NDARRAY_HOST_DEVICE bool is_in_range(index_t at) const {
return min_ <= at && at <= max();
}
/** Returns true if `at.min()` and `at.max()` are both within the interval
* `[min(), max()]`. */
template <index_t OtherMin, index_t OtherExtent>
NDARRAY_INLINE NDARRAY_HOST_DEVICE bool is_in_range(
const interval<OtherMin, OtherExtent>& at) const {
return min_ <= at.min() && at.max() <= max();
}
template <index_t OtherMin, index_t OtherExtent, index_t OtherStride>
NDARRAY_INLINE NDARRAY_HOST_DEVICE bool is_in_range(
const dim<OtherMin, OtherExtent, OtherStride>& at) const {
return min_ <= at.min() && at.max() <= max();
}
/** Make an iterator referring to the first index in this interval. */
NDARRAY_HOST_DEVICE index_iterator begin() const { return index_iterator(min_); }
/** Make an iterator referring to one past the last index in this interval. */
NDARRAY_HOST_DEVICE index_iterator end() const { return index_iterator(max() + 1); }
/** Two interval objects are considered equal if they contain the
* same indices. */
template <index_t OtherMin, index_t OtherExtent>
NDARRAY_HOST_DEVICE bool operator==(const interval<OtherMin, OtherExtent>& other) const {
return min_ == other.min() && extent_ == other.extent();
}
template <index_t OtherMin, index_t OtherExtent>
NDARRAY_HOST_DEVICE bool operator!=(const interval<OtherMin, OtherExtent>& other) const {
return !operator==(other);
}
};
/** An alias of `interval` with a fixed extent and dynamic min. This is useful
* as the inner part of a `split` with a fixed extent. */
template <index_t Extent>
using fixed_interval = interval<dynamic, Extent>;
/** Make an interval from a half-open range `[begin, end)`. */
NDARRAY_INLINE NDARRAY_HOST_DEVICE interval<> range(index_t begin, index_t end) {
return interval<>(begin, end - begin);
}
NDARRAY_INLINE NDARRAY_HOST_DEVICE interval<> r(index_t begin, index_t end) {
return interval<>(begin, end - begin);
}
/** Make an interval from a half-open range `[begin, begin + Extent)`. */
template <index_t Extent>
NDARRAY_HOST_DEVICE fixed_interval<Extent> range(index_t begin) {
return fixed_interval<Extent>(begin);
}
template <index_t Extent>
NDARRAY_HOST_DEVICE fixed_interval<Extent> r(index_t begin) {
return fixed_interval<Extent>(begin);
}
/** Placeholder object representing an interval that indicates keep
* the whole dimension when used in an indexing expression. */
const interval<0, -1> all, _;
/** Overloads of `std::begin` and `std::end` for an interval. */
template <index_t Min, index_t Extent>
NDARRAY_HOST_DEVICE index_iterator begin(const interval<Min, Extent>& d) {
return d.begin();
}
template <index_t Min, index_t Extent>
NDARRAY_HOST_DEVICE index_iterator end(const interval<Min, Extent>& d) {
return d.end();
}
/** Clamp `x` to the interval [min, max]. */
NDARRAY_INLINE NDARRAY_HOST_DEVICE index_t clamp(index_t x, index_t min, index_t max) {
return internal::min(internal::max(x, min), max);
}
/** Clamp `x` to the range described by an object `r` with a `min()` and
* `max()` method. */
template <class Range>
NDARRAY_HOST_DEVICE index_t clamp(index_t x, const Range& r) {
return clamp(x, r.min(), r.max());
}
/** Describes one dimension of an array. The template parameters enable
* providing compile time constants for the `min`, `extent`, and `stride` of the
* dim.
*
* These parameters define a mapping from the indices of the dimension to
* offsets: `offset(x) = (x - min)*stride`. The extent does not affect the
* mapping directly. Values not in the interval `[min, min + extent)` are considered
* to be out of bounds. */
template <index_t Min_ = dynamic, index_t Extent_ = dynamic, index_t Stride_ = dynamic>
class dim : protected interval<Min_, Extent_> {
public:
using base_range = interval<Min_, Extent_>;
protected:
internal::constexpr_index<Stride_> stride_;
using base_range::extent_;
using base_range::min_;
public:
using base_range::Extent;
using base_range::Max;
using base_range::Min;
static constexpr index_t Stride = Stride_;
static constexpr index_t DefaultStride = internal::is_static(Stride) ? Stride : unresolved;
/** Construct a new dim object. If the `min`, `extent` or `stride` are
* specified in the constructor, it must have a value compatible with `Min`,
* `Extent`, or `Stride`, respectively.
*
* The default values if not specified in the constructor are:
* - The default `min` is `Min` if `Min` is static, or 0 if not.
* - The default `extent` is `Extent` if `Extent` is static, or 0 if not.
* - The default `stride` is `Stride`. */
NDARRAY_HOST_DEVICE dim(index_t min, index_t extent, index_t stride = DefaultStride)
: base_range(min, extent), stride_(stride) {}
NDARRAY_HOST_DEVICE dim(index_t extent) : dim(internal::is_static(Min) ? Min : 0, extent) {}
NDARRAY_HOST_DEVICE dim() : dim(internal::is_static(Extent) ? Extent : 0) {}
NDARRAY_HOST_DEVICE dim(const base_range& interval, index_t stride = DefaultStride)
: dim(interval.min(), interval.extent(), stride) {}
NDARRAY_HOST_DEVICE dim(const dim&) = default;
NDARRAY_HOST_DEVICE dim(dim&&) = default;
NDARRAY_HOST_DEVICE dim& operator=(const dim&) = default;
NDARRAY_HOST_DEVICE dim& operator=(dim&&) = default;
/** Copy construction or assignment of another dim object, possibly
* with different compile-time template parameters. `other.min()`,
* `other.extent()`, and `other.stride()` must be compatible with `Min`,
* `Extent`, and `Stride`, respectively. */
template <index_t CopyMin, index_t CopyExtent, index_t CopyStride,
class = internal::disable_if_not_equal<Min, CopyMin>,
class = internal::disable_if_not_equal<Extent, CopyExtent>,
class = internal::disable_if_not_equal<Stride, CopyStride>>
NDARRAY_HOST_DEVICE dim(const dim<CopyMin, CopyExtent, CopyStride>& other)
: dim(other.min(), other.extent()) {
set_stride(other.stride());
}
template <index_t CopyMin, index_t CopyExtent, index_t CopyStride,
class = internal::disable_if_not_equal<Min, CopyMin>,
class = internal::disable_if_not_equal<Extent, CopyExtent>,
class = internal::disable_if_not_equal<Stride, CopyStride>>
NDARRAY_HOST_DEVICE dim& operator=(const dim<CopyMin, CopyExtent, CopyStride>& other) {
set_min(other.min());
set_extent(other.extent());
set_stride(other.stride());
return *this;
}
using base_range::begin;
using base_range::end;
using base_range::extent;
using base_range::size;
using base_range::is_in_range;
using base_range::max;
using base_range::min;
using base_range::set_extent;
using base_range::set_max;
using base_range::set_min;
/** Get or set the distance in flat indices between neighboring elements
* in this dim. */
NDARRAY_INLINE NDARRAY_HOST_DEVICE index_t stride() const { return stride_; }
NDARRAY_INLINE NDARRAY_HOST_DEVICE void set_stride(index_t stride) {
if (internal::is_static(Stride_)) {
assert(internal::is_unresolved(stride) || stride == Stride_);
} else {
stride_ = stride;
}
}
/** Offset of the index `at` in this dim in the flat array. */
NDARRAY_INLINE NDARRAY_HOST_DEVICE index_t flat_offset(index_t at) const {
return (at - min_) * stride_;
}
/** Two dim objects are considered equal if their mins, extents, and strides
* are equal. */
template <index_t OtherMin, index_t OtherExtent, index_t OtherStride>
NDARRAY_HOST_DEVICE bool operator==(const dim<OtherMin, OtherExtent, OtherStride>& other) const {
return min_ == other.min() && extent_ == other.extent() && stride_ == other.stride();
}
template <index_t OtherMin, index_t OtherExtent, index_t OtherStride>
NDARRAY_HOST_DEVICE bool operator!=(const dim<OtherMin, OtherExtent, OtherStride>& other) const {
return !operator==(other);
}
};
/** Alias of `dim` where the min is not specified at compile time. */
template <index_t Extent, index_t Stride = dynamic>
using fixed_dim = dim<dynamic, Extent, Stride>;
/** Alias of `dim` where the compile-time stride parameter is known
* to be one. */
template <index_t Min = dynamic, index_t Extent = dynamic>
using dense_dim = dim<Min, Extent, 1>;
/** Alias of `dim` where only the stride parameter is specified at
* compile time. */
template <index_t Stride>
using strided_dim = dim<dynamic, dynamic, Stride>;
/** Alias of `dim` where the compile-time stride parameter is known
* to be zero. */
template <index_t Min = dynamic, index_t Extent = dynamic>
using broadcast_dim = dim<Min, Extent, 0>;
namespace internal {
// An iterator for a range of intervals.
// This is like a random access iterator in that it can move forward in constant time, but
// but unlike a random access iterator, it cannot be moved in reverse.
template <index_t InnerExtent = dynamic>
class split_iterator {
fixed_interval<InnerExtent> i;
index_t outer_max;
public:
NDARRAY_HOST_DEVICE split_iterator(const fixed_interval<InnerExtent>& i, index_t outer_max)
: i(i), outer_max(outer_max) {}
NDARRAY_HOST_DEVICE bool operator==(const split_iterator& r) const {
return i.min() == r.i.min();
}
NDARRAY_HOST_DEVICE bool operator!=(const split_iterator& r) const {
return i.min() != r.i.min();
}
NDARRAY_HOST_DEVICE fixed_interval<InnerExtent> operator*() const { return i; }
NDARRAY_HOST_DEVICE const fixed_interval<InnerExtent>* operator->() const { return &i; }
NDARRAY_HOST_DEVICE split_iterator& operator+=(index_t n) {
assert(n >= 0);
if (is_static(InnerExtent)) {
// When the extent of the inner split is a compile-time constant,
// we can't shrink the out of bounds interval. Instead, shift the min,
// assuming the outer dimension is bigger than the inner extent.
i.set_min(i.min() + InnerExtent * n);
// Only shift the min when this straddles the end of the buffer,
// so the iterator can advance to the end (one past the max).
if (i.min() <= outer_max && i.max() > outer_max) { i.set_min(outer_max - InnerExtent + 1); }
} else {
// When the extent of the inner split is not a compile-time constant,
// we can just modify the extent.
i.set_min(i.min() + i.extent() * n);
index_t max = min(i.max(), outer_max);
i.set_extent(max - i.min() + 1);
}
return *this;
}
NDARRAY_HOST_DEVICE split_iterator operator+(index_t n) const {
split_iterator<InnerExtent> result(*this);
return result += n;
}
NDARRAY_HOST_DEVICE split_iterator& operator++() {
return *this += 1;
}
NDARRAY_HOST_DEVICE split_iterator operator++(int) {
split_iterator<InnerExtent> result(*this);
*this += 1;
return result;
}
NDARRAY_HOST_DEVICE index_t operator-(const split_iterator& r) const {
return r.i.extent() > 0 ? (i.max() - r.i.min() + r.i.extent() - i.extent()) / r.i.extent() : 0;
}
NDARRAY_HOST_DEVICE fixed_interval<InnerExtent> operator[](index_t n) const {
split_iterator result(*this);
result += n;
return *result;
}
};
template <index_t InnerExtent = dynamic>
class split_result {
public:
using iterator = split_iterator<InnerExtent>;
private:
iterator begin_;
iterator end_;
public:
NDARRAY_HOST_DEVICE split_result(iterator begin, iterator end) : begin_(begin), end_(end) {}
NDARRAY_HOST_DEVICE iterator begin() const { return begin_; }
NDARRAY_HOST_DEVICE iterator end() const { return end_; }
NDARRAY_HOST_DEVICE index_t size() const { return end_ - begin_; }
NDARRAY_HOST_DEVICE iterator operator[](index_t i) const { return begin_ + i; }
};
} // namespace internal
/** Split an interval `v` into an iteratable range of intervals by a compile-time
* constant `InnerExtent`. If `InnerExtent` does not divide `v.extent()`,
* the last interval will be shifted to overlap with the second-to-last iteration,
* to preserve the compile-time constant extent, which implies `v.extent()`
* must be larger `InnerExtent`.
*
* Examples:
* - `split<4>(interval<>(0, 8))` produces the intervals `[0, 4)`, `[4, 8)`.
* - `split<5>(interval<>(0, 12))` produces the intervals `[0, 5)`,
* `[5, 10)`, `[7, 12)`. Note the last two intervals overlap. */
template <index_t InnerExtent, index_t Min, index_t Extent>
NDARRAY_HOST_DEVICE internal::split_result<InnerExtent> split(
const interval<Min, Extent>& v) {
assert(v.extent() >= InnerExtent);
return {{fixed_interval<InnerExtent>(v.min()), v.max()},
{fixed_interval<InnerExtent>(v.max() + 1), v.max()}};
}
template <index_t InnerExtent, index_t Min, index_t Extent, index_t Stride>
NDARRAY_HOST_DEVICE internal::split_result<InnerExtent> split(
const dim<Min, Extent, Stride>& v) {
return split<InnerExtent>(interval<Min, Extent>(v.min(), v.extent()));
}
/** Split an interval `v` into an iterable range of intervals by `inner_extent`. If
* `inner_extent` does not divide `v.extent()`, the last iteration will be
* clamped to the outer interval.
*
* Examples:
* - `split(interval<>(0, 12), 5)` produces the intervals `[0, 5)`,
* ` [5, 10)`, `[10, 12)`. */
// TODO: This probably doesn't need to be templated, but it might help
// avoid some conversion messes. dim<Min, Extent> probably can't implicitly
// convert to interval<>.
template <index_t Min, index_t Extent>
NDARRAY_HOST_DEVICE internal::split_result<> split(
const interval<Min, Extent>& v, index_t inner_extent) {
return {{interval<>(v.min(), internal::min(inner_extent, v.extent())), v.max()},
{interval<>(v.max() + 1, 0), v.max()}};
}
template <index_t Min, index_t Extent, index_t Stride>
NDARRAY_HOST_DEVICE internal::split_result<> split(
const dim<Min, Extent, Stride>& v, index_t inner_extent) {
return split(interval<Min, Extent>(v.min(), v.extent()), inner_extent);
}
namespace internal {
using std::index_sequence;
using std::make_index_sequence;
// Call `fn` with the elements of tuple `args` unwrapped from the tuple.
// TODO: When we assume C++17, this can be replaced by std::apply.
template <class Fn, class Args, size_t... Is>
NDARRAY_INLINE NDARRAY_HOST_DEVICE auto apply(Fn&& fn, const Args& args, index_sequence<Is...>)
-> decltype(fn(std::get<Is>(args)...)) {
return fn(std::get<Is>(args)...);
}
template <class Fn, class Args>
NDARRAY_INLINE NDARRAY_HOST_DEVICE auto apply(Fn&& fn, const Args& args)
-> decltype(internal::apply(fn, args, make_index_sequence<std::tuple_size<Args>::value>())) {
return internal::apply(fn, args, make_index_sequence<std::tuple_size<Args>::value>());
}
template <class Fn, class... Args>
using enable_if_callable = decltype(internal::declval<Fn>()(internal::declval<Args>()...));
template <class Fn, class Args>
using enable_if_applicable =
decltype(internal::apply(internal::declval<Fn>(), internal::declval<Args>()));
// Some variadic reduction helpers.
NDARRAY_INLINE constexpr index_t sum() { return 0; }
NDARRAY_INLINE constexpr index_t sum(index_t x0) { return x0; }
NDARRAY_INLINE constexpr index_t sum(index_t x0, index_t x1) { return x0 + x1; }
NDARRAY_INLINE constexpr index_t sum(index_t x0, index_t x1, index_t x2) { return x0 + x1 + x2; }
template <class... Rest>
NDARRAY_INLINE constexpr index_t sum(index_t x0, index_t x1, index_t x2, index_t x3, Rest... rest) {
return x0 + x1 + x2 + x3 + sum(rest...);
}
NDARRAY_INLINE constexpr int product() { return 1; }
template <class T, class... Rest>
NDARRAY_INLINE constexpr T product(T first, Rest... rest) {
return first * product(rest...);
}
NDARRAY_INLINE constexpr index_t variadic_min() { return std::numeric_limits<index_t>::max(); }
template <class... Rest>
NDARRAY_INLINE constexpr index_t variadic_min(index_t first, Rest... rest) {
return min(first, variadic_min(rest...));
}
NDARRAY_INLINE constexpr index_t variadic_max() { return std::numeric_limits<index_t>::min(); }
template <class... Rest>
NDARRAY_INLINE constexpr index_t variadic_max(index_t first, Rest... rest) {
return max(first, variadic_max(rest...));
}
// Computes the product of the extents of the dims.
template <class Tuple, size_t... Is>
NDARRAY_HOST_DEVICE index_t product(const Tuple& t, index_sequence<Is...>) {
return product(std::get<Is>(t)...);
}
// Returns true if all of bools are true.
template <class... Bools>
constexpr bool all(Bools... bools) {
return sum((bools ? 0 : 1)...) == 0;
}
template <class... Bools>
constexpr bool any(Bools... bools) {
return sum((bools ? 1 : 0)...) != 0;
}
// Computes the sum of the offsets of a list of dims and indices.
template <class Dims, class Indices, size_t... Is>
NDARRAY_HOST_DEVICE index_t flat_offset(
const Dims& dims, const Indices& indices, index_sequence<Is...>) {
return sum(std::get<Is>(dims).flat_offset(std::get<Is>(indices))...);
}
// Computes one more than the sum of the offsets of the last index in every dim.
template <class Dims, size_t... Is>
NDARRAY_HOST_DEVICE index_t flat_min(const Dims& dims, index_sequence<Is...>) {
return sum((std::get<Is>(dims).extent() - 1) * min<index_t>(0, std::get<Is>(dims).stride())...);
}
template <class Dims, size_t... Is>
NDARRAY_HOST_DEVICE index_t flat_max(const Dims& dims, index_sequence<Is...>) {
return sum((std::get<Is>(dims).extent() - 1) *
internal::max<index_t>(0, std::get<Is>(dims).stride())...);
}
// Make dims with the interval of the first parameter and the stride
// of the second parameter.
template <index_t DimMin, index_t DimExtent, index_t DimStride>
NDARRAY_HOST_DEVICE auto range_with_stride(index_t x, const dim<DimMin, DimExtent, DimStride>& d) {
return dim<dynamic, 1, DimStride>(x, 1, d.stride());
}
template <index_t CropMin, index_t CropExtent, index_t DimMin, index_t DimExtent, index_t Stride>
NDARRAY_HOST_DEVICE auto range_with_stride(
const interval<CropMin, CropExtent>& x, const dim<DimMin, DimExtent, Stride>& d) {
return dim<CropMin, CropExtent, Stride>(x.min(), x.extent(), d.stride());
}
template <index_t CropMin, index_t CropExtent, index_t CropStride, index_t DimMin,
index_t DimExtent, index_t Stride>
NDARRAY_HOST_DEVICE auto range_with_stride(
const dim<CropMin, CropExtent, CropStride>& x, const dim<DimMin, DimExtent, Stride>& d) {
return dim<CropMin, CropExtent, Stride>(x.min(), x.extent(), d.stride());
}
template <index_t Min, index_t Extent, index_t Stride>
NDARRAY_HOST_DEVICE auto range_with_stride(const decltype(_)&, const dim<Min, Extent, Stride>& d) {
return d;
}
template <class Intervals, class Dims, size_t... Is>
NDARRAY_HOST_DEVICE auto intervals_with_strides(
const Intervals& intervals, const Dims& dims, index_sequence<Is...>) {
return std::make_tuple(range_with_stride(std::get<Is>(intervals), std::get<Is>(dims))...);
}
// Make a tuple of dims corresponding to elements in intervals that are not slices.
template <class Dim>
NDARRAY_HOST_DEVICE std::tuple<> skip_slices_impl(const Dim& d, index_t) {
return std::tuple<>();
}
template <class Dim, index_t Min, index_t Extent>
NDARRAY_HOST_DEVICE std::tuple<Dim> skip_slices_impl(const Dim& d, const interval<Min, Extent>&) {
return std::tuple<Dim>(d);
}
template <class Dim, index_t Min, index_t Extent, index_t Stride>
NDARRAY_HOST_DEVICE std::tuple<Dim> skip_slices_impl(
const Dim& d, const dim<Min, Extent, Stride>&) {
return std::tuple<Dim>(d);
}
template <class Dims, class Intervals, size_t... Is>
NDARRAY_HOST_DEVICE auto skip_slices(
const Dims& dims, const Intervals& intervals, index_sequence<Is...>) {
return std::tuple_cat(skip_slices_impl(std::get<Is>(dims), std::get<Is>(intervals))...);
}
// Checks if all indices are in interval of each corresponding dim.
template <class Dims, class Indices, size_t... Is>
NDARRAY_HOST_DEVICE bool is_in_range(
const Dims& dims, const Indices& indices, index_sequence<Is...>) {
return all(std::get<Is>(dims).is_in_range(std::get<Is>(indices))...);
}
// Get the mins of a series of intervals.
template <class Dim>
NDARRAY_HOST_DEVICE index_t min_of_range(index_t x, const Dim&) {
return x;
}
template <index_t Min, index_t Extent, class Dim>
NDARRAY_HOST_DEVICE index_t min_of_range(const interval<Min, Extent>& x, const Dim&) {
return x.min();
}
template <index_t Min, index_t Extent, index_t Stride, class Dim>
NDARRAY_HOST_DEVICE index_t min_of_range(const dim<Min, Extent, Stride>& x, const Dim&) {
return x.min();
}
template <class Dim>
NDARRAY_HOST_DEVICE index_t min_of_range(const decltype(_)&, const Dim& dim) {
return dim.min();
}
template <class Intervals, class Dims, size_t... Is>
NDARRAY_HOST_DEVICE auto mins_of_intervals(
const Intervals& intervals, const Dims& dims, index_sequence<Is...>) {
return std::make_tuple(min_of_range(std::get<Is>(intervals), std::get<Is>(dims))...);
}
template <class... Dims, size_t... Is>
NDARRAY_HOST_DEVICE auto mins(const std::tuple<Dims...>& dims, index_sequence<Is...>) {
return std::make_tuple(std::get<Is>(dims).min()...);
}
template <class... Dims, size_t... Is>
NDARRAY_HOST_DEVICE auto extents(const std::tuple<Dims...>& dims, index_sequence<Is...>) {
return std::make_tuple(std::get<Is>(dims).extent()...);
}
template <class... Dims, size_t... Is>
NDARRAY_HOST_DEVICE auto strides(const std::tuple<Dims...>& dims, index_sequence<Is...>) {
return std::make_tuple(std::get<Is>(dims).stride()...);
}
template <class... Dims, size_t... Is>
NDARRAY_HOST_DEVICE auto maxs(const std::tuple<Dims...>& dims, index_sequence<Is...>) {
return std::make_tuple(std::get<Is>(dims).max()...);
}
// The following series of functions implements the algorithm for
// automatically determining what unknown dynamic strides should be.
// A proposed stride is "OK" w.r.t. `dim` if the proposed
// stride does not intersect the dim.
template <class Dim>
NDARRAY_HOST_DEVICE bool is_stride_ok(index_t stride, index_t extent, const Dim& dim) {
if (is_unresolved(dim.stride())) {
// If the dimension has an unknown stride, it's OK, we're
// resolving the current dim first.
return true;
}
if (extent == 1 && abs(stride) == abs(dim.stride()) && dim.extent() > 1) {
// If a dimension is extent 1, avoid giving this dimension the same stride
// as another dimension with extent greater than 1. This doesn't affect the
// results of most programs (because the stride only ever multiplied with
// zero), but it makes the strides less objectionable to asserts in some
// other libraries that make extra assumptions about images, and may be
// easier to understand.
return false;
}
if (dim.extent() * abs(dim.stride()) <= stride) {
// The dim is completely inside the proposed stride.
return true;
}
index_t flat_extent = extent * stride;
if (abs(dim.stride()) >= flat_extent) {
// The dim is completely outside the proposed stride.
return true;
}
return false;
}
// Replace strides that are not OK with values that cannot be the
// smallest stride.
template <class... Dims>
NDARRAY_HOST_DEVICE index_t filter_stride(index_t stride, index_t extent, const Dims&... dims) {
if (all(is_stride_ok(stride, extent, dims)...)) {
return stride;
} else {
return std::numeric_limits<index_t>::max();
}
}
// The candidate stride for some other dimension is the minimum stride it
// could have without intersecting this dim.
template <class Dim>
NDARRAY_HOST_DEVICE index_t candidate_stride(const Dim& dim) {
if (is_unresolved(dim.stride())) {
return std::numeric_limits<index_t>::max();
} else {
return max<index_t>(1, abs(dim.stride()) * dim.extent());
}
}
// Find the best stride (the smallest) out of all possible candidate strides.
template <class Dims, size_t... Is>
NDARRAY_HOST_DEVICE index_t find_stride(index_t extent, const Dims& dims, index_sequence<Is...>) {
return variadic_min(filter_stride(1, extent, std::get<Is>(dims)...),
filter_stride(candidate_stride(std::get<Is>(dims)), extent, std::get<Is>(dims)...)...);
}
// Replace unknown dynamic strides for each dimension, starting with the first dimension.
template <class AllDims>
NDARRAY_HOST_DEVICE void resolve_unknown_strides(AllDims& all_dims) {}
template <class AllDims, class Dim0, class... Dims>
NDARRAY_HOST_DEVICE void resolve_unknown_strides(AllDims& all_dims, Dim0& dim0, Dims&... dims) {
if (is_unresolved(dim0.stride())) {
constexpr size_t rank = std::tuple_size<AllDims>::value;
dim0.set_stride(find_stride(dim0.extent(), all_dims, make_index_sequence<rank>()));
}
resolve_unknown_strides(all_dims, dims...);
}
template <class Dims, size_t... Is>
NDARRAY_HOST_DEVICE void resolve_unknown_strides(Dims& dims, index_sequence<Is...>) {
resolve_unknown_strides(dims, std::get<Is>(dims)...);
}
template <class Dims, size_t... Is>
NDARRAY_HOST_DEVICE bool is_resolved(const Dims& dims, index_sequence<Is...>) {
return all(is_resolved(std::get<Is>(dims).stride())...);
}
// A helper to transform an array to a tuple.
template <class T, class Tuple, size_t... Is>
NDARRAY_HOST_DEVICE std::array<T, sizeof...(Is)> tuple_to_array(
const Tuple& t, index_sequence<Is...>) {
return {{std::get<Is>(t)...}};
}
template <class T, class... Ts>
NDARRAY_HOST_DEVICE std::array<T, sizeof...(Ts)> tuple_to_array(const std::tuple<Ts...>& t) {
return tuple_to_array<T>(t, make_index_sequence<sizeof...(Ts)>());
}
template <class T, size_t N, size_t... Is>
NDARRAY_HOST_DEVICE auto array_to_tuple(const std::array<T, N>& a, index_sequence<Is...>) {
return std::make_tuple(a[Is]...);
}
template <class T, size_t N>
NDARRAY_HOST_DEVICE auto array_to_tuple(const std::array<T, N>& a) {
return array_to_tuple(a, make_index_sequence<N>());
}
template <class T, size_t N>
using tuple_of_n = decltype(array_to_tuple(internal::declval<std::array<T, N>>()));
// A helper to check if a parameter pack is entirely implicitly convertible to
// any type Ts, for use with std::enable_if
template <class T, class... Args>
struct all_of_any_type : std::false_type {};
template <class T>
struct all_of_any_type<T> : std::true_type {};
template <class... Ts, class Arg, class... Args>
struct all_of_any_type<std::tuple<Ts...>, Arg, Args...> {
static constexpr bool value = any(std::is_constructible<Ts, Arg>::value...) &&
all_of_any_type<std::tuple<Ts...>, Args...>::value;
};
// Wrapper for checking if a parameter pack is entirely implicitly convertible
// to one type T.
template <class T, class... Args>
using all_of_type = all_of_any_type<std::tuple<T>, Args...>;
template <size_t I, class T, class... Us, std::enable_if_t<(I < sizeof...(Us)), int> = 0>
NDARRAY_HOST_DEVICE auto convert_dim(const std::tuple<Us...>& u) {
return std::get<I>(u);
}
template <size_t I, class T, class... Us, std::enable_if_t<(I >= sizeof...(Us)), int> = 0>
NDARRAY_HOST_DEVICE auto convert_dim(const std::tuple<Us...>& u) {
// For dims beyond the rank of U, make a dimension of type T_I with extent 1.
return decltype(std::get<I>(internal::declval<T>()))(1);
}
template <class T, class U, size_t... Is>
NDARRAY_HOST_DEVICE T convert_dims(const U& u, internal::index_sequence<Is...>) {
return std::make_tuple(convert_dim<Is, T>(u)...);
}
// Check that the dimensions in src_dims are either copied to the dst shape (not sliced),
// or are trivial slices (they are extent 1).
template <size_t DstRank, class SrcDims, size_t... Is>
NDARRAY_HOST_DEVICE bool is_trivial_slice(
const SrcDims& src_dims, internal::index_sequence<Is...>) {
return all((Is < DstRank || std::get<Is>(src_dims).extent() == 1)...);
}
constexpr index_t factorial(index_t x) { return x == 1 ? 1 : x * factorial(x - 1); }
// The errors that result from not satisfying this check are probably hell,
// but it would be pretty tricky to check that all of [0, Rank) is in `Is...`
template <size_t Rank, size_t... Is>
using enable_if_permutation = std::enable_if_t<sizeof...(Is) == Rank && all(Is < Rank...) &&
product((Is + 2)...) == factorial(Rank + 1)>;
template <class DimDst, class DimSrc>
NDARRAY_HOST_DEVICE void assert_dim_compatible(size_t dim_index, const DimSrc& src) {
bool compatible = true;
if (is_static(DimDst::Min) && src.min() != DimDst::Min) {
NDARRAY_PRINT_ERR("Error converting dim %zu: expected static min " NDARRAY_INDEX_T_FMT
", got " NDARRAY_INDEX_T_FMT "\n",
dim_index, DimDst::Min, src.min());
compatible = false;
}
if (is_static(DimDst::Extent) && src.extent() != DimDst::Extent) {