-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathNDArray.chpl
More file actions
2687 lines (2175 loc) · 86 KB
/
NDArray.chpl
File metadata and controls
2687 lines (2175 loc) · 86 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
module NDArray {
import ChapelArray;
import Math;
import Random;
import IO;
import Path;
use Env;
use Remote;
use SimpleDomain;
import Utilities as util;
use Utilities.Standard;
use Utilities.Types;
import Bridge;
type domainType = _domain(?);
/* The most fundamental tensor type.
This type represents a multidimensional array, supporting a variety
of operations useful for machine learning.
All of the operations of this class are intended to be run on the GPU.
*/
record ndarray : serializable {
/* The rank of this :record:`ndarray`. The rank is synonymous with the number of dimensions. */
param rank: int;
/* The element type of this :record:`ndarray`. */
type eltType = defaultEltType;
var _domain: domain(rank,int);
var data: [_domain] eltType = noinit;
forwarding data except shape, _dom;
pragma "no copy return"
pragma "return not owned"
inline proc _dom do return _domain;
/* Create a new :record:`ndarray` with the requisite element type `eltType`
and domain `dom`.
:arg eltType: The element of type of the new :record:`ndarray`.
:type eltType: type
:arg dom: The domain of the new :record:`ndarray`.
*/
inline
proc init(type eltType, const dom: ?t)
where isDomainType(t) {
this.rank = dom.rank;
this.eltType = eltType;
this._domain = dom;
}
/* Create a new :record:`ndarray` with the requisite element type `eltType`
and domain `dom`, filled with the value `fill`.
:arg eltType: The element type of the new :record:`ndarray`.
:type eltType: type
:arg dom: The domain of the new :record:`ndarray`.
:arg fill: The fill value of the new :record:`ndarray`. All elements
of the :record:`ndarray` will be initialised to a copy of this element.
:type fill: const in eltType
*/
inline
proc init(type eltType, const dom: ?t, const in fill: eltType)
where isDomainType(t) {
this.rank = dom.rank;
this.eltType = eltType;
this._domain = dom;
this.data = fill;
}
/* Create a new :record:`ndarray` with rank `rank`, element type `eltType`,
and domain `dom`.
The domain must have the same rank as the requested rank.
:arg rank: The rank of the new :record:`ndarray`. It must be the same value
as `dom.rank`.
:type rank: param int
:arg eltType: The element type of the new :record:`ndarray`.
:arg dom: The domain of the new :record:`ndarray`. `dom.rank` must be the same
value as `rank`.
*/
proc init(param rank: int, type eltType, const dom: ?t)
where isDomainType(t)
&& dom.rank == rank {
this.rank = rank;
this.eltType = eltType;
this._domain = dom;
}
/* Create a new :record:`ndarray` with rank `rank`, element type `eltType`,
domain `dom`, initialized with values taken from the array `arr`.
:arg rank: The rank of the new :record:`ndarray`. It must be the same value
as `dom.rank`.
:type rank: param int
:arg eltType: The element type of the new :record:`ndarray`.
:type eltType: type
:arg dom: The domain of the new :record:`ndarray`.
:arg arr: The values from which the new :record:`ndarray` will be initialized.
:type arr: const []eltType
*/
proc init(param rank: int, type eltType, const dom: ?t, const arr: []eltType)
where isDomainType(t)
&& dom.rank == rank {
this.rank = rank;
this.eltType = eltType;
this._domain = dom;
this.data = arr;
}
/* Create an :record:`ndarray` with the given element type `eltType` and shape
`shape`.
:arg eltType: The element type of the new :record:`ndarray`.
:type eltType: type
:arg shape: The shape of the new :record:`ndarray`, given as a tuple. The new
:record:`ndarray` will have the same rank as the size of the tuple.
:type shape: ?rank * int
*/
proc init(type eltType, shape: ?rank * int) {
var ranges: rank*range;
for param i in 0..<rank do
ranges(i) = 0..<shape(i);
this.init(eltType,{(...ranges)});
}
/* Create a new :record:`ndarray` with the given rank `rank` and element type
`eltType`.
:arg rank: The rank of the new :record:`ndarray`.
:type rank: param int
:arg eltType: The element type of the new :record:`ndarray`.
:type eltType: type
*/
proc init(param rank: int, type eltType = defaultEltType) {
const shape: rank * int;
this.init(eltType,shape);
}
/* Create a new :record:`ndarray` with the given element type `eltType`
and shape given by the remaining arguments.
:arg eltType: The element type of the new :record:`ndarray`.
:type eltType: type
*/
proc init(type eltType = defaultEltType, const shape: int ...?rank) do
this.init(eltType,shape);
/* Create a new :record:`ndarray` from the given rectangular domain `dom` and
element type `eltType`.
:arg dom: The domain with which to create the new :record:`ndarray`.
:type dom: rect(?rank)
:arg eltType: The element type of the new :record:`ndarray`.
:type eltType: type
*/
proc init(const dom: rect(?rank), type eltType) do
this.init(eltType,dom); // This could be optimized by refactoring whole init system.
/* Create a new :record:`ndarray` from the given domain `dom` and element
type `eltType`.
:arg dom: The domain from which to create the new :record:`ndarray`.
:arg eltType: The element type of the new :record:`ndarray`.
:type eltType: type
*/
proc init(const dom: ?t,type eltType = defaultEltType)
where isDomainType(t) {
this.init(eltType,dom);
}
/* Create a new :record:`ndarray` out of an array.
:arg Arr: The array from which to initialize the new :record:`ndarray`.
:type Arr: []
The new :record:`ndarray` will have the same element type, domain, and data
as the array `Arr`.
*/
proc init(const Arr: []) {
this.rank = Arr.rank;
this.eltType = Arr.eltType;
this._domain = Arr.domain;
this.data = Arr;
}
/* Copy-construct a new :record:`ndarray`.
:arg A: The :record:`ndarray` to copy.
:type A: ndarray(?rank, ?eltType)
*/
proc init(const A: ndarray(?rank,?eltType)) {
this.rank = rank;
this.eltType = eltType;
this._domain = A._domain;
this.data = A.data;
}
/* Initialize an :record:`ndarray` with the given element type `eltType` and
domain `dom` from random data.
:arg eltType: The element type of the new :record:`ndarray`.
:type eltType: type
:arg rs: A random stream from which to pull random data.
:arg dom: The domain the new :record:`ndarray` should have.
*/
proc init(type eltType, ref rs: Random.randomStream(eltType), const dom: ?t)
where isDomainType(t) {
this.init(eltType,dom);
rs.fill(data);
}
// proc init(it: _iteratorRecord) {
// const arr = it;
// this.init(arr);
// }
/* Create a new :record:`ndarray` with the data from an array `other`.
:arg other: The array with which to initialize the data of the :record:`ndarray`.
:type other: const [] ?eltType
The :record:`ndarray` will have the same domain and data as the array `other`.
*/
proc init=(const other: [] ?eltType) do
this.init(other);
/* :record:`ndarray` copy-initializer.
:arg other: The :record:`ndarray` to copy.
:type other: ndarray(?rank, ?eltType)
*/
proc init=(const other: ndarray(?rank,?eltType)) {
this.rank = rank;
this.eltType = eltType;
this._domain = other._domain;
this.data = other.data;
}
}
// proc ref ndarray.this(args: int...rank) ref {
// return data.this((...args));
// }
proc ndarray.this(args: int...rank) {
return data.this((...args));
}
proc ref ndarray.setData(const arr: [] eltType)
where arr.rank == rank do
if arr.domain == this.domain then
data = arr;
else
this = arr;
proc ref ndarray.reshapeDomain(const dom: domain(rank,int))
where isRegularDomain(dom) {
_domain = dom;
}
/* Yield the shape of an :record:`ndarray`.
The shape is the size of each dimension.
We have that for any :record:`ndarray`, the size of the shape will be the same as its rank.
.. code-block::
// D is a value of type domain
const t = new ndarray(real, D);
t.shape.size == D.rank // Will always be true
:returns: The shape of the :record:`ndarray`.
:rtype: rank * int
*/
proc ndarray.shape: rank * int {
var s: rank * int;
const dms = _domain.dims();
for param i in 0..<rank {
const ref dm = dms(i);
s(i) = (dm.highBound - dm.lowBound) + 1;
}
return s;
}
/* Reshapes an :record:`ndarray`.
This function comes in two flavors:
#. Reshape the :record:`ndarray` to have the argument domain.
#. Reshape the :record:`ndarray` to have the argument shape, given as arguments to the function.
:arg dom: The domain to reshape the :record:`ndarray` to have.
:returns: A new :record:`ndarray` with the new shape.
:rtype: ndarray(rank, eltType)
*/
proc ndarray.reshape(const dom: ?t): ndarray(dom.rank,eltType)
where isDomainType(t) {
var arr = new ndarray(eltType,dom);
const arrDom = arr.domain;
const selfDom = this.domain;
ref arrData = arr.data;
const ref selfData = this.data;
const arrShape = arrDom.shape;
const selfShape = selfDom.shape;
const selfShapeDivs = util.shapeDivisors((...selfShape));
const zero: eltType = 0;
forall (i,idx) in arrDom.everyZip() {
const selfIdx = util.indexAtHelperMultiples(i,(...selfShapeDivs));
const a = if util.shapeContains(selfShape,selfIdx)
then selfData[selfIdx]
else zero;
arrData[idx] = a;
}
return arr;
}
/* Reshape an :record:`ndarray` to have the shape corresponding to the arguments.
:returns: A new :record:`ndarray` with the shape given by the arguments.
:rtype: ndarray(newRank, eltType)
*/
proc ndarray.reshape(newShape: int ...?newRank): ndarray(newRank,eltType) do
return this.reshape(util.domainFromShape((...newShape)));
/* Yield a slice of an :record:`ndarray` according to the arguments.
This function behaves exactly the same as Chapel's standard
`slicing syntax <https://chapel-lang.org/docs/language/spec/arrays.html#array-slicing>`_.
:returns: A new :record:`ndarray` representing the slice of the :record:`ndarray`.
*/
proc ndarray.slice(args...) {
const slc = data[(...args)];
return new ndarray(slc);
}
/* Switches the dimensions of an :record:`ndarray` around
so that they come in the corresponding order instead of
in their natural order.
For each value in ``axes``, the dimension with that index
will become the dimension given by its position in the ``axes`` tuple.
For instance, given a two-dimensional :record:`ndarray` ``A``,
``A.permute(1, 0)`` would perform a transpose. Dimension 1
would become dimension 0, and dimension 0 would become dimension 1.
:returns: A new :record:`ndarray` with the shuffled dimensions.
*/
proc ndarray.permute(axes: int...rank) {
const oldShape = data.shape;
var oldShapeR = data.dims();
var newShapeR: rank*range;
for param i in 0..<rank {
newShapeR(i) = data.dim(axes(i));
}
const newDom = {(...newShapeR)};
var prm = new ndarray(newDom,eltType);
const newShape = prm.shape;
ref prmData = prm.data;
const ref thisData = this.data;
forall i in 0..<data.size {
var oldIdx,newIdx: rank*int;
for param j in 0..<rank {
oldIdx(j) = i % oldShape(j);
newIdx(j) = i % newShape(j);
}
prmData[newIdx] = thisData[oldIdx];
}
return prm;
}
proc ndarray.expand(axes: int...rank) {
const shape = data.domain.shape;
const oldRanges = data.dims();
var newRanges: rank*range = oldRanges;
for param i in 0..<rank {
const axis = axes(i);
const ds = shape(i);
if axis != ds {
if ds == 1 {
newRanges(i) = 0..<axis;
} else {
halt("Cannot expand an axis that is not 1.");
}
} else {
newRanges(i) = oldRanges(i);
}
}
// const dom = util.domainFromShape((...axes));
const dom = {(...newRanges)};
var expanded = new ndarray(dom,eltType);
const oldShape = shape;
const newShape = dom.shape;
ref expandedData = expanded.data;
const expandedDataDomain = expandedData.domain;
const ref thisData = this.data;
// @assertOnGpu
forall idx in expandedDataDomain.every() {
var origIdx: rank * int;
if idx.type == int {
origIdx(0) = idx;
} else {
origIdx = idx;
}
for param i in 0..<rank {
if oldShape(i) == 1 then origIdx(i) = 0;
}
expandedData[idx] = thisData[origIdx];
}
return expanded;
}
proc ndarray.unsqueeze(dim: int): ndarray(rank + 1,eltType) {
const shape = this.domain.shape;
param newRank: int = rank + 1;
var offset: int = 0;
var newShape: newRank * int;
for param i in 0..<newRank {
if i == dim {
newShape(i) = 1;
offset = 1;
} else {
newShape(i) = shape(i - offset);
}
}
return this.reshape((...newShape));
}
proc ref ndarray.sumOneAxis(axis: int): ndarray(rank,eltType) {
const dims = this.domain.dims();
const sumAxis = dims(axis);
const sumAxisSize = sumAxis.size;
var newDims = dims;
newDims(axis) = 0..<1;
const newDomain = {(...newDims)};
var S = new ndarray(newDomain,eltType);
ref B = S.data;
ref A = data;
// @assertOnGpu
forall idx in newDomain.every() {
var origIdx: newDomain.rank * int;
if idx.type == int {
origIdx(0) = idx;
} else {
origIdx = idx;
}
var sum: eltType = 0;
for i in 0..<sumAxisSize {
origIdx(axis) = i;
sum += A[origIdx];
}
B[idx] = sum;
}
return S;
}
proc ndarray.sumAxesMask(withAxesMask: rank*int): ndarray(rank,eltType) {
var acc: ndarray(rank,eltType) = this;
for param i in 0..<rank {
if withAxesMask(i) == 1 {
acc = acc.sumOneAxis(i);
}
}
return acc;
}
proc ndarray.sum(): ndarray(rank,eltType) do
return this.sum((...this.nDimTuple()));
proc ndarray.sum(axes: int...?axesCount): ndarray(rank,eltType) {
var acc: ndarray(rank,eltType) = new ndarray(data);
for param i in 0..<axesCount {
acc = acc.sumOneAxis(axes(i));
}
return acc;
}
/* Yields the indices of all of the axes of the :record:`ndarray`, as a tuple.
:returns: A tuple representing the indices of the axes of the :record:`ndarray`
:rtype: rank * int
*/
proc ndarray.nDimTuple(): rank * int {
var tpl: rank * int;
for param i in 0..<rank do
tpl(i) = i;
return tpl;
}
proc ndarray.mean(): ndarray(rank,eltType) do
return this.mean((...this.nDimTuple()));
proc ndarray.mean(axes: int...?axesCount): ndarray(rank,eltType) {
const shape = this.shape;
var denom: eltType = 1.0;
for param i in 0..<axesCount {
const reducedN = shape(axes(i));
denom *= reducedN : eltType;
}
return this.sum((...axes)) / denom;
}
proc ndarray.shrink(narg: 2*int ... rank,param exactBounds = false): ndarray(rank,eltType) {
var newShape: rank * int;
var sliceRanges: rank * range;
for param i in 0..<rank {
var (start,end) = narg(i);
if start < 0 && end < 0 {
start = 0;
end = this.shape(i);
}
if !exactBounds {
sliceRanges(i) = start..#end;
} else {
sliceRanges(i) = start..<end;
}
newShape(i) = sliceRanges(i).size;
}
const sliceDom = {(...sliceRanges)};
const newDom = util.domainFromShape((...newShape));
var shrunk = new ndarray(newDom,eltType);
shrunk.data = data[sliceDom];
return shrunk;
}
proc ndarray.pad(narg: 2*int ... rank,value: eltType = 0): ndarray(rank,eltType) {
var newShape: rank * int;
var sliceRanges: rank * range;
for param i in 0..<rank {
const dimSize = data.domain.shape(i);
var (left,right) = narg(i);
sliceRanges(i) = left..#dimSize;
newShape(i) = dimSize + left + right;
}
const sliceDom = {(...sliceRanges)};
const newDom = util.domainFromShape((...newShape));
var padded = new ndarray(newDom,eltType);
padded.data = value;
padded.data[sliceDom] = data;
return padded;
}
proc ndarray.dilate(dil: int) where rank == 2 {
if dil < 0 then util.err("Cannot dilate ", this.type:string, ", of shape ", this.shape, ", by dilation=", dil);
if dil == 0 then return this;
const (height,width) = this.shape;
const insertH = (height - 1) * dil;
const insertW = (width - 1) * dil;
const newHeight = insertH + height;
const newWidth = insertW + width;
const dom = util.domainFromShape(newHeight,newWidth);
var dilated = new ndarray(dom,eltType);
ref dat = dilated.data;
const ref thisData = data;
const step = dil + 1;
const selfDom = this.domain;
forall (h,w) in data.domain.every() {
dat[h * step,w * step] = thisData[h,w];
}
return dilated;
}
proc ndarray.dilate(dil: int) where rank == 3 {
if dil < 0 then util.err("Cannot dilate ", this.type:string, ", of shape ", this.shape, ", by dilation=", dil);
if dil == 0 then return this;
const (channels,height,width) = this.shape;
const insertH = (height - 1) * dil;
const insertW = (width - 1) * dil;
const newHeight = insertH + height;
const newWidth = insertW + width;
const dom = util.domainFromShape(channels,newHeight,newWidth);
var dilated = new ndarray(dom,eltType);
ref dat = dilated.data;
const ref thisData = data;
const step = dil + 1;
forall (c,h,w) in this.domain.every() do
dat[c,h * step,w * step] = thisData[c,h,w];
return dilated;
}
proc ndarray.squeeze(param newRank: int): ndarray(newRank,eltType) where newRank < rank {
// I think this will work: (a member of the chapel team needs to review this)
// I suspect heavy performance hits will happen when running this on CUDA.
if newRank == 1 {
var me = new ndarray(1,eltType);
const s = data.size;
me.reshapeDomain({0..<s});
const dataDomain = data.domain;
ref meData = me.data;
const ref thisData = data;
// @assertOnGpu
forall i in me.domain.every() {
meData[i] = thisData[dataDomain.indexAt(i)];
}
// var j = 0;
// for i in data.domain {
// me[j] = data[i];
// j += 1;
// }
return me;
}
const oldShape = this.shape;
var newShape: newRank*int;
var offset: int = 0;
for param i in 0..<rank {
if oldShape(i) == 1 {
offset -= 1;
} else {
newShape(i + offset) = oldShape(i);
}
}
const dom = util.domainFromShape((...newShape));
var me = new ndarray(dom,eltType);
me.reshapeDomain(dom);
ref meData = me.data;
// I had to change this
// forall (i,a) in zip(dom,this.data) do meData[i] = a;
// to this
forall i in 0..<dom.size do
meData[util.indexAt(i,(...newShape))] = this.data[util.indexAt(i,(...oldShape))];
// because of a type error about the dimensionality of `dom` and `this.data`. The new version is likely less performant.
return me;
}
/* :returns: The minimum value from the :record:`ndarray`.
:rtype: ndarray(1, eltType)
*/
proc ndarray.min(): ndarray(1,eltType) {
var me = new ndarray({0..<1},eltType);
const myData = this.data;
me.data[0] = Math.min reduce myData;
return me;
}
/* :returns: The maximum value from the :record:`ndarray`.
:rtype: ndarray(1, eltType)
*/
proc ndarray.max(): ndarray(1,eltType) {
var me = new ndarray({0..<1},eltType);
const myData = this.data;
me.data[0] = max reduce myData;
return me;
}
proc ndarray.max(axes: int...?axesCount): ndarray(rank,eltType) {
compilerWarning("max is unimplemented.");
return this; // Implement me.
}
proc ndarray.populateRemote(re: borrowed Remote(ndarray(rank,eltType))): borrowed Remote(ndarray(rank,eltType)) {
on re.device {
ref reArr = re.ptr;
reArr = this;
}
return re;
}
proc ndarray.toRemote(): owned Remote(ndarray(rank,eltType)) {
var re = new Remote(ndarray(rank,eltType));
populateRemote(re.borrow());
return re;
}
iter ref ndarray.batchify(param dim: int = 0) ref where dim < rank {
const dimR = data.domain.shape(dim);
var dims = data.dims();
for i in dimR {
yield data[(...((...dims(0..<dim)),i,(...dims((dim+1)..<rank))))];
}
}
proc ndarray.kernelRot(): ndarray(4,eltType) where rank == 4 {
const (features,channels,height,width) = data.domain.shape;
var me = new ndarray(data.domain,eltType);
ref meData = me.data;
const ref thisData = data;
const selfDom = this.domain;
forall (f,c,h,w) in selfDom.every() {
meData[f,c,h,w] = thisData[f,c,height - h - 1,width - w - 1];
}
return me;
}
proc ndarray.kernelRot(): ndarray(3,eltType) where rank == 3 {
const (channels,height,width) = data.domain.shape;
var me = new ndarray(data.domain,eltType);
ref meData = me.data;
const ref thisData = data;
forall (c,h,w) in this.domain.every() {
meData[c,h,w] = thisData[c,height - h - 1,width - w - 1];
}
return me;
}
/* Retrieves the top `k` elements from a one-dimensional :record:`ndarray`.
.. code-block::
const a = new ndarray([10, 2, 4, 7, 9, 13]);
a.topk(3) // [10, 9, 13]
:arg k: The number of elements to retrieve.
:type k: int
:returns: The top `k` elements from a one-dimensional :record:`ndarray`.
The return value preserves the original order of the elements in the source
:record:`ndarray` with respect to each other.
:rtype: ndarray(1, int)
*/
proc ndarray.topk(k: int): ndarray(1, int) where rank == 1 {
const myData = this.data;
const myDom = this.domain;
const mySize = myDom.size;
if k > mySize then util.err("Cannot get top ", k, " from ", mySize, " elements.");
var topK: [0..<k] int = 0..<k;
var topKData: [0..<k] eltType = myData[0..<k];
// Repeatedly find the minimum from the elements of topKData,
// and then swap it out with some element from the remaining portion
// of the array, if that element is larger.
// The end result is that topKData will hold the k largest elements of the array.
for i in k..<mySize {
var minIdx = 0;
var minVal = topKData(minIdx);
for j in 1..<k {
if topKData(j) < minVal {
minIdx = j;
minVal = topKData(j);
}
}
if myData(i) > minVal {
topK(minIdx) = i;
topKData(minIdx) = myData(i);
}
}
// sort topK based on topKData
use Sort;
record cmp: keyComparator { proc key(x) do return x(1); }
var paired = [i in 0..<k] (topK(i), topKData(i));
sort(paired, comparator=new reverseComparator(new cmp()));
var res = [p in paired] p(0);
return new ndarray(res);
}
/* :returns: The index of the largest element in a one-dimensional :record:`ndarray`.
If there are multiple indices in the array that hold the maximal element, this
method will return the smallest such index.
:rtype: int
*/
proc ndarray.argmax() where rank == 1 {
// What on earth is up with this comment...
// const DATA = this.data;
// const (_,i) = maxloc reduce zip(
// DATA
// DATA.domain);
// return i;
// For some reason this is causing problems. Keeping this because I am worried the above wont run on gpu.
var mxi: int = 0;
const data = this.data;
var mx: eltType = data[mxi];
for i in data.domain {
const mei = data[i];
if mx < mei {
mxi = i;
mx = mei;
}
}
return mxi;
}
/* Applies the rectified linear unit function to each element in the :record:`ndarray`.
.. math::
\mathrm{ReLU}(x) = (x)^+ = \max(0, x)
Zeroes every element that is less than 0.
:returns: A new :record:`ndarray` with every element run through the recitifed linear unit function.
*/
inline proc ndarray.relu() {
return Bridge.relu(this : Bridge.tensorHandle(eltType)) : ndarray(rank, eltType);
}
/* Computes the Gaussian error linear units function for each element.
.. math::
\mathrm{GELU}(x) = 0.5 \cdot x \cdot \mathrm{erf}(x \cdot \frac{1}{\sqrt{2}})
:returns: A new :record:`ndarray` where every element has been passed through ``GELU`` as defined above.
*/
inline proc ndarray.gelu() {
return Bridge.gelu(this : Bridge.tensorHandle(eltType)) : ndarray(rank, eltType);
}
/* Computes the Sigmoid linear unit function for each element.
This function is also known as the swish function.
.. math::
\mathrm{silu}(x) = \frac{x}{\sigma(x)}\mathrm{,\ where}\ \sigma(x)\ \mathrm{is\ the\ logistic\ sigmoid.}
:returns: A new :record:`ndarray` where the ``silu`` has been computed for each element, as defined above.
*/
inline proc ndarray.silu() {
return Bridge.silu(this : Bridge.tensorHandle(eltType)) : ndarray(rank, eltType);
}
/* Computes the mish function for each element.
.. math::
\mathrm{mish}(x) = x\tanh(\ln(1 + e^x))
:returns: A new :record:`ndarray` where ``mish`` has been computed for each element, as defined above.
*/
inline proc ndarray.mish() {
return Bridge.mish(this : Bridge.tensorHandle(eltType)) : ndarray(rank, eltType);
}
/* Computes the sigmoid function :math:`\sigma(x)` for each element.
.. math::
\sigma(x) = \frac{1}{1 + e^{-x}}
:returns: A new :record:`ndarray` where the sigmoid function has been computed for each element.
*/
inline proc ndarray.sigmoid() {
const ref thisData = data;
const dom = this.domain;
var rl = new ndarray(dom, eltType);
ref rld = rl.data;
forall i in dom.every() {
const x = thisData[i];
rld[i] = 1 / (1 + Math.exp(-x));
}
return rl;
}
/* Computes the hyperbolic tangent function for each element.
.. math::
\tanh(x) = \frac{e^x - e^{-x}}{e^x + e^{-x}}
:returns: A new :record:`ndarray` where :math:`\tanh(x)` has been computed for each element ``x``.
*/
inline proc ndarray.tanh() {
const ref thisData = data;
const dom = this.domain;
var rl = new ndarray(dom, eltType);
ref rld = rl.data;
forall i in dom.every() {
const x = thisData[i];
rld[i] = Math.tanh(x);
}
return rl;
}
/* Computes the ReLU6 function for each element.
.. math::
\mathrm{ReLU6}(x) = \min(\max(0, x), 6)
Clamps every element in the range :math:`[0, 6]`.
:returns: A new :record:`ndarray` where every element has been clamped to the range :math:`[0, 6]`.
*/
inline proc ndarray.relu6() {
return Bridge.relu6(this : Bridge.tensorHandle(eltType)) : ndarray(rank, eltType);
}
/* Computes the SELU function for each element.
.. math::
\mathrm{SELU}(x) = s \cdot (\max(0, x) + \min(0, \alpha \cdot (e^x - 1)))
where :math:`\alpha = 1.6732632423543772848170429916717` and :math:`s = 1.0507009873554804934193349852946`.
:returns: A new :record:`ndarray` where every element has been run through SELU as defined above.
*/
inline proc ndarray.selu() {
return Bridge.selu(this : Bridge.tensorHandle(eltType)) : ndarray(rank, eltType);
}
/* Computes LogSigmoid for each element.
.. math::
\mathrm{LogSigmoid}(x_i) = \log(\frac{1}{1 + e^{-x_i}})
:returns: A new :record:`ndarray` where every element has had LogSigmoid computed for it.
*/
inline proc ndarray.logsigmoid() {
return Bridge.logsigmoid(this : Bridge.tensorHandle(eltType)) : ndarray(rank, eltType);
}
/* Computes Tanhshrink for each element.
.. math::
\mathrm{Tanhshrink}(x) = x - \mathrm{Tanh}(x)
:returns: A new :record:`ndarray` where every element has had Tanhshrink applied to it.
*/
inline proc ndarray.tanhshrink() {
return Bridge.tanhshrink(this : Bridge.tensorHandle(eltType)) : ndarray(rank, eltType);
}
/* Computes Softsign for each element.
.. math::
\mathrm{Softsign}(x) = \frac{x}{1 + \left|x\right|}
:returns: A new :record:`ndarray` where every element has had Softsign applied to it.
*/
inline proc ndarray.softsign() {
return Bridge.softsign(this : Bridge.tensorHandle(eltType)) : ndarray(rank, eltType);
}