-
Notifications
You must be signed in to change notification settings - Fork 15
/
ad_lms_vector.scala
2520 lines (2216 loc) · 102 KB
/
ad_lms_vector.scala
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
package lantern
import scala.util.continuations._
import scala.util.continuations
import org.scala_lang.virtualized.virtualize
import org.scala_lang.virtualized.SourceContext
import scala.virtualization.lms._
import scala.collection.mutable.ArrayBuffer
import scala.collection.{Seq => NSeq}
import scala.math._
trait TensorExp extends Dsl with Diff {
/**
Memory Management:
finally we used a temperate solution called "memory arena". The base code will claim a large piece of code for the whole program.
internally, every malloc will borrow memory from this arena.
By using getAllocMem and setAllocMem, we can selectively return a big trunk of memory after one iteration of training.
**/
class Timer (val index: Int){
unchecked[Unit](s"clock_t begin_$index, end_$index; double time_spent_$index")
def startTimer = { unchecked[Unit](s"begin_$index = clock()") }
def stopTimer = { unchecked[Unit](s"end_$index = clock()") }
def printElapsedTime = {
unchecked[Unit](
s"end_$index = clock(); printf(",
"\"Time elapsed: %f\\n\", ",
s"(double)(end_$index - begin_$index) / CLOCKS_PER_SEC)")
}
}
object Timer {
var index: Int = 0
def apply(): Timer = {
val timer = new Timer(index)
index += 1
timer
}
}
def get_time() = unchecked[Double]("((double)clock() / CLOCKS_PER_SEC)")
class Timer2 (index: Int) {
unchecked[Unit](s"struct timeval begin_$index, end_$index, diff_$index")
def startTimer = { unchecked[Unit](s"gettimeofday(&begin_$index, NULL)") }
def getElapsedTime: Rep[Long] = {
unchecked[Unit](s"gettimeofday(&end_$index, NULL)")
unchecked[Unit](s"timeval_subtract(&diff_$index, &end_$index, &begin_$index);")
unchecked[Long](s"((diff_$index.tv_sec * 1000000L) + (diff_$index.tv_usec))")
}
}
object Timer2 {
var index: Int = 0
def apply(): Timer2 = {
val timer = new Timer2(index)
index += 1
timer
}
}
object Dataset {
class DataLoader(name: String, train: Boolean, mean: Float, std: Float, dims: Int*) {
def remap[T:Typ] = if (typ[T] == typ[Float]) "float"
else if (typ[T] == typ[Int]) "int"
else ???
def open(path: Rep[String]) = uncheckedPure[Int]("open(",path,",0)")
def filelen(fd: Rep[Int]) = uncheckedPure[Long]("fsize(",fd,")") // FIXME: fresh name
def mmap[T:Typ](fd: Rep[Int], len: Rep[Long]) = uncheckedPure[Array[T]]("(",remap(typ[T]),"*)mmap(0, ",len,", PROT_READ | PROT_WRITE, MAP_FILE | MAP_PRIVATE, ",fd,", 0)")
val fd = open(s"../data/bin/${name}_${if (train) "train" else "test"}.bin")
val len = filelen(fd)
val data = mmap[Float](fd, len)
val dLength = (len/4L).toInt
val tfd = open(s"../data/bin/${name}_${if (train) "train" else "test"}_target.bin")
val tlen = filelen(tfd)
val target = mmap[Int](tfd, tlen)
val length = (tlen/4L).toInt
def dataset = new Tensor(data, NSeq(60000, dims(1), dims(2)))
@virtualize
def normalize() = {
this.foreach { (i, t, d) =>
t.normalize(mean, std, inPlace = true)
}
}
@virtualize
def foreach(f: (Rep[Int], Tensor, Rep[Int]) => Unit) = {
var off = var_new(0)
for (img <- 0 until length: Rep[Range]) {
val dataPtr = slice(data, off)
val t = Tensor(dataPtr, dims : _*)
f(img, t, target(img))
off += t.scalarCount
}
assertC(off == dLength, "Data length doesn't match\\n")
}
}
}
def convSize(size: Int, kernelSize: Int, strideSize: Int) = (size - kernelSize)/strideSize + 1
def mmax(a: Int, b: Int) = if (a >= b) a else b
@virtualize
def assertC(cond: Rep[Boolean], msg: String, args: Rep[Any]*): Unit = {
if(!cond) { printf(msg, args : _*); exit() }
}
def slice[T: Manifest](arr: Rep[Array[T]], off: Rep[Int]) = uncheckedPure[Array[T]](arr, "+", off)
object Encoding {
val ix_a = 96 // index starts from 1
def char_to_ix(ch: Rep[Char]): Rep[Int] = ch.AsInstanceOf[Int] - ix_a
def ix_to_char(ix: Rep[Int]): Rep[Char] = (ix + ix_a).AsInstanceOf[Char]
}
class Dimensions(val dims: NSeq[Int]) {
def apply(idx: Int) = {
if (idx >= dims.length) ???
else dims(idx)
}
def last = dims.last
def reverse = Dimensions(dims.reverse: _*)
val (nbElem +: strides) = (dims :\ NSeq[Int](1)) {
case (dim, seq@(t +: q)) => (dim * t) +: seq
}
override def toString = dims mkString " x "
override def equals(o: Any) = o match {
case t: Dimensions => this.dims == t.dims
case _ => false
}
}
implicit def Dimensions2Seq(x: Dimensions) = x.dims
object Dimensions {
def apply(x: Int*) = new Dimensions(x)
}
/*
case class TTT(seq: NSeq[Int]) {
def apply(x: Int) = {
if (x >= seq.length) ???
seq(x)
}
def last = seq.last
def reverse = TTT(seq.reverse)
def equal(that: TTT) = {
that.seq == seq
}
}
implicit def ttttoSeq(x: TTT) = x.seq
*/
object Random {
def rand() = unchecked[Float]("(float)rand()/RAND_MAX")
def srand(seed: Option[Int] = None) = unchecked[Unit]("srand(",seed.map(_.toString).getOrElse("time(NULL)"),")")
}
def exit() = unchecked[Unit]("exit(0)")
abstract class DataLoop {
def foreach(f: Rep[Int] => Unit): Unit
}
@virtualize
object DataLoop {
def apply(size: Int) = if (size <= 1) {
new DataLoop {
def foreach(f: Rep[Int] => Unit) = {
for (i <- 0 until size: Range) f(unit(i))
}
}
} else {
new DataLoop {
def foreach(f: Rep[Int] => Unit) = {
for (i <- 0 until size: Rep[Range]) f(i)
}
}
}
}
/* Not supported in LMS??
abstract class ForLoop {
def foreach(f: Rep[Int] => Unit): Unit
}
@virtualize
object ForLoop {
def apply(start: Int, step: Int, step_size: Int) = if (step <= 5) {
new ForLoop {
def foreach(f: Rep[Int] => Unit) = {
for (i <- (start until (start + step_size * step) by step_size): Range) f(unit(i))
}
}
} else {
new ForLoop {
def foreach(f: Rep[Int] => Unit) = {
for (i <- (start until (start + step * step_size) by step_size): Rep[Range]) f(i)
}
}
}
} */
/**
* Defines tensor-specific operations.
* Eventually, a tensor operation IR may be introduced to enable analyses/transformations.
*/
trait Backend {
def dot(x: Tensor, y: Tensor): Tensor
// TODO: Add more ops.
}
/**
* Native tensor op backend.
* Tensor ops are defined in terms of primitive operations.
*/
trait BackendNative extends Backend {
// Compute vector-vector dot product, i.e. inner product.
// [V] dot [V] => [1] (scalar)
private def vvdot(x: Tensor, y: Tensor): Tensor = {
assert(x.shape(0) == y.shape(0))
val value = var_new(0.0f)
for (i <- DataLoop(x.shape.last)) {
value += x.data(i) * y.data(i)
}
val res = NewArray[Float](1)
res(0) = readVar(value)
Tensor(res, 1)
}
// Compute matrix-vector dot product.
// [M1 x M2] dot [M2] => [M1]
private def mvdot(x: Tensor, y: Tensor): Tensor = {
assert(x.shape(1) == y.shape(0))
val dim1 = x.shape(0)
val dim2 = x.shape(1)
val res = NewArray[Float](dim1)
for (i <- DataLoop(dim1)) {
val value = var_new(0.0f)
for (j <- DataLoop(dim2)) {
value += x.data(i * dim2 + j) * y.data(j)
}
res(i) = readVar(value)
}
Tensor(res, dim1)
}
// Compute matrix-matrix dot product.
// [M1 x M2] dot [M2 x M3] => [M1 x M3]
private def mmdot(x: Tensor, y: Tensor): Tensor = {
assert(x.shape(1) == y.shape(0))
val dim1 = x.shape(0)
val dim2 = x.shape(1)
val dim3 = y.shape(1)
val res = NewArray[Float](dim1 * dim3)
for (i <- DataLoop(dim1)) {
for (j <- DataLoop(dim3)) {
val value = var_new(0.0f)
for (k <- DataLoop(dim2)) {
value += x.data(i * dim2 + k) * y.data(k * dim3 + j)
}
res(i * dim3 + j) = readVar(value)
}
}
Tensor(res, dim1, dim3)
}
override def dot(x: Tensor, y: Tensor): Tensor =
(x.rank, y.rank) match {
case (1, 1) => vvdot(x, y)
case (2, 1) => mvdot(x, y)
case (2, 2) => mmdot(x, y)
case _ => throw new IllegalArgumentException(s"Incompatible shapes: ${x.shape}, ${y.shape}")
}
}
/**
* cuBLAS tensor op backend. WIP.
*/
trait BackendCUBLAS extends Backend {
// GEMM reference:
// https://docs.nvidia.com/cuda/cublas/index.html#cublas-lt-t-gt-gemm
//
// cublasStatus_t cublasSgemm(cublasHandle_t handle,
// cublasOperation_t transa, cublasOperation_t transb,
// int m, int n, int k,
// const float *alpha,
// const float *A, int lda,
// const float *B, int ldb,
// const float *beta,
// float *C, int ldc)
def sgemm(a: Array[Float], b: Array[Float], c: Array[Float]) = unchecked[Array[Float]]("cublasSgemm(...)")
override def dot(x: Tensor, y: Tensor): Tensor = ???
}
/**
* Default tensor op backend, extending `BackendNative`.
*/
class BackendDefault extends BackendNative
val backend: Backend = new BackendDefault
class Tensor(val data: Rep[Array[Float]], val dimensions: NSeq[Int]) extends Serializable {
def shape = Dimensions(dimensions: _*)
val rank = dimensions.length
val scalarCount = shape.nbElem
val isScalar = scalarCount == 1
assert(shape.strides.length >= 1)
assert(scalarCount != 0, "Empty Tensor!!!")
def apply(i: Rep[Int]) = data(i)
def apply(i: Rep[Int], j: Rep[Int]) = data(i * shape(1) + j) // FIXME the index of matrix is not the normal way
@virtualize
def clipAt(bound: Float) = {
for (i <- DataLoop(scalarCount)) {
if (data(i) > bound) data(i) = bound
if (data(i) < -1.0f * bound) data(i) = -1.0f * bound
}
}
def mapInPlace(op: Rep[Float] => Rep[Float]) = {
for (i <- DataLoop(scalarCount)) this.data(i) = op(this.data(i))
}
def map(op: Rep[Float] => Rep[Float]) = {
val res = NewArray[Float](scalarCount)
for (i <- DataLoop(scalarCount)) res(i) = op(this.data(i))
new Tensor(res, shape)
}
def fold(init: Rep[Float])(op: (Rep[Float], Rep[Float]) => Rep[Float]) = {
val res = var_new[Float](init)
for (i <- DataLoop(scalarCount)) var_assign(res, op(res, this.data(i)))
res
}
def elementWiseOpWithBroadCast(that: Tensor, op: ((Rep[Float], Rep[Float]) => Rep[Float])) = {
Tensor.dimBroadcast(shape, that.shape) match {
case None => throw new IllegalArgumentException(s"dimensions of vector do not match! ${this.shape.seq} != ${that.shape.seq}")
case Some((thisShape, thatShape, resShape)) => {
val resData = NewArray[Float](resShape.nbElem)
val res = new Tensor(resData, resShape)
def inplace(offThis: Rep[Int], offThat: Rep[Int], offRes: Rep[Int], dim: Int): Unit = {
val offres = var_new[Int](offRes)
val offthis = var_new[Int](offThis)
val offthat = var_new[Int](offThat)
for (i <- DataLoop(resShape(dim))) {
if (dim == resShape.size - 1) {
resData(offres) = op(this.data(offthis), that.data(offthat))
} else {
inplace(offthis, offthat, offres, dim + 1)
}
offres += resShape.strides(dim)
if (thisShape(dim) > 1) offthis += thisShape.strides(dim)
if (thatShape(dim) > 1) offthat += thatShape.strides(dim)
}
}
inplace(0, 0, 0, 0)
res
}
}
}
def +(that: Rep[Float]): Tensor = this.map(x => x + that)
def +(that: Tensor): Tensor = this.elementWiseOpWithBroadCast(that, _ + _)
// this operator updates the values of this, unlike the + operator
def +=(that: Rep[Float]): Unit = this.mapInPlace(x => x + that)
def += (that: Tensor): Unit = {
if (that.scalarCount == 1) {
generate_comment("+= tensor of dim 0")
this += that.data(0) // broadcast
}
else if (this.scalarCount == 1) ??? // this.data(0) = that.fold(this.data(0))((agg, x) => agg + x)
else if (this.shape == that.shape)
for (i <- DataLoop(scalarCount)) this.data(i) += that.data(i)
else throw new IllegalArgumentException(s"dimensions of vector do not match +=! ${this.shape.seq} != ${that.shape.seq}")
}
def -(that: Rep[Float]): Tensor = this.map(x => x - that)
def -(that: Tensor): Tensor = this.elementWiseOpWithBroadCast(that, _ - _)
// this operator updates the values of this, unlike the - operator
def -=(that: Rep[Float]): Unit = this.mapInPlace(x => x - that)
def -= (that: Tensor): Unit = {
if (that.scalarCount == 1) this -= that.data(0) // broadcast
else if (this.scalarCount == 1) {
???
// this.data(0) = that.fold(this.data(0))((agg, x) => agg - x)
}
else if (this.shape == that.shape)
for (i <- DataLoop(scalarCount)) this.data(i) -= that.data(i)
else throw new IllegalArgumentException("dimensions of vector do not match +=!")
}
// Element wise multiplication
def *(that: Rep[Float]): Tensor = this.map(x => x * that)
def *(that: Tensor): Tensor = this.elementWiseOpWithBroadCast(that, _ * _)
// this operator updates the values of this, unlike the * operator
def *=(that: Rep[Float]): Unit = this.mapInPlace(x => x * that)
def *= (that: Tensor): Unit = {
if (that.scalarCount == 1) this *= that.data(0) // broadcast
else if (this.scalarCount == 1) {
???
// this.data(0) = that.fold(this.data(0))((agg, x) => agg * x)
}
else if (this.shape == that.shape)
for (i <- DataLoop(scalarCount)) this.data(i) *= that.data(i)
else throw new IllegalArgumentException("dimensions of vector do not match +=!")
}
// element wise division
def /(that: Rep[Float]): Tensor = this.map(x => x / that)
def /(that: Tensor): Tensor = this.elementWiseOpWithBroadCast(that, _ / _)
// this operator updates the values of this, unlike the / operator
def /=(that: Rep[Float]): Unit = this.mapInPlace(x => x / that)
def /= (that: Tensor): Unit = {
if (that.scalarCount == 1) this /= that.data(0) // broadcast
else if (this.scalarCount == 1) ??? // this.data(0) = that.fold(this.data(0))((agg, x) => agg / x)
else if (this.shape == that.shape)
for (i <- DataLoop(scalarCount)) this.data(i) /= that.data(i)
else throw new IllegalArgumentException("dimensions of vector do not match +=!")
}
def setAsOne() = { this.mapInPlace(x => 1.0f); () }
def clear() = { this.mapInPlace(x => 0.0f); () }
def copy_data(that: Tensor) = {
assert(this.scalarCount == that.scalarCount, "dimensions of vector do not match copy_data!")
for (i <- DataLoop(scalarCount)) this.data(i) = that.data(i)
}
// `dot` represents the following:
// - vector-vector dot product.
// [V] dot [V] => [1] (scalar)
// - matrix-vector multiplication.
// [M1 x M2] dot [M2] => [M1]
// - matrix-matrix multiplication.
// [M1 x M2] dot [M2 x M3] => [M1 x M3]
def dot(that: Tensor) = {
generate_comment(s"dot: ${this.shape.seq}, ${that.shape.seq}")
(this.rank, that.rank) match {
case (1, 1) => assert(this.shape(0) == that.shape(0), s"Incompatible shapes: ${this.shape}, ${that.shape}")
case (2, 1) => assert(this.shape(1) == that.shape(0), s"Incompatible shapes: ${this.shape}, ${that.shape}")
case (2, 2) => assert(this.shape(0) == that.shape(1), s"Incompatible shapes: ${this.shape}, ${that.shape}")
case _ => throw new IllegalArgumentException(
s"Only vector-vector, matrix-vector, and matrix-matrix multiplication are allowed (actual shapes: ${this.shape}, ${that.shape})")
}
backend.dot(this, that)
}
// NOTE: only handles (Vector cart Vector)
def cart(that: Tensor) = {
assert(this.rank == 1 && that.rank == 1, "cartesian product is only for 1d vectors")
val res = NewArray[Float](this.shape(0) * that.shape(0))
val off = var_new(0)
for (i <- DataLoop(this.shape(0))) {
//for (i <- (0 until this.dims(0)): Rep[Range]) {
for (j <- DataLoop(that.shape(0))) {
//for (j <- (0 until that.dims(0)): Rep[Range]) {
res(off) = data(i) * that.data(j)
off += 1
}
}
Tensor(res, this.shape(0), that.shape(0))
}
def trans() = {
assert(this.rank == 2, "transpose is only for matrix. Tensor transpose is not supported here")
val res = NewArray[Float](this.scalarCount)
val offT = var_new(0)
for (i <- DataLoop(this.shape(1))) {
//for (i <- (0 until this.dims(1)): Rep[Range]) {
val off = var_new(0)
for (j <- DataLoop(this.shape(0))) {
//for (j <- (0 until this.dims(0)): Rep[Range]) {
res(offT + j) = data(off + i)
off += this.shape(1)
}
offT += this.shape(0)
}
new Tensor(res, this.shape.reverse)
}
def tanh() = this.map(x => Math.tanh(x).toFloat)
def exp() = this.map(x => Math.exp(x).toFloat)
def log() = this.map(x => Math.log(x).toFloat)
def sqrt() = this.map(x => Math.sqrt(x).toFloat)
def sigmoid() = this.map(x => 1.0f / (Math.exp(-1.0f * x).toFloat + 1.0f))
// NOTE: sum all elements
def sum() = Tensor.scalar(this.fold(0.0f)(_ + _))
@virtualize
def sum2D(dim: Int) = {
assert (this.rank == 2, "Only deal with 2D tensor")
assert (dim == 0 || dim == 1, "dim must be in range of this.nbDims")
if (dim == 0) ???
else {
val res = NewArray[Float](this.shape(0))
val offset = var_new(0)
for (i <- DataLoop(this.shape(0))) {
val sum = var_new(0.0f)
for (j <- DataLoop(this.shape(1))) {
sum += this.data(offset)
offset += 1
}
res(i) = sum
}
Tensor(res, this.shape(0))
}
}
@virtualize
def check(limit: Float) = {
val idx = var_new(0)
while (idx < this.scalarCount && -limit < this.data(idx) && this.data(idx) < limit) {
idx += 1
}
idx != this.scalarCount
}
@virtualize
def max() = this.fold(scala.Float.MinValue)((agg, x) => if (x > agg) x else agg)
@virtualize
def max2D(dim: Int) = {
assert (this.rank == 2, "Only deal with 2D tensor")
assert (dim == 0 || dim == 1, "dim must be in range of this.nbDims")
if (dim == 0) ???
else {
val res = NewArray[Float](this.shape(0))
val offset = var_new(0)
for (i <- DataLoop(this.shape(0))) {
val max = var_new(scala.Float.MinValue)
for (j <- DataLoop(this.shape(1))) {
if (this.data(offset) > max) max = this.data(offset)
offset += 1
}
res(i) = max
}
Tensor(res, this.shape(0))
}
}
// FIXME: Proper tensor
@virtualize
def maxIndex() = {
assert(this.rank == 1)
val vMax = var_new(this.data(0))
val iMax = var_new(0)
for (idx <- 1 until this.scalarCount: Rep[Range]) {
if (this.data(idx) > vMax) {
iMax = idx
vMax = this.data(idx)
}
}
iMax
}
@virtualize // batched log softmax
def logSoftmaxB() = {
assert(this.rank == 2, "logSoftmaxB should handle 2D tensors: batch * 1D")
val max = this.max2D(dim = 1)
val res = Tensor.zeros_like(this)
// fill res with exp(x_i - max)
val offset = var_new(0)
for (batch <- DataLoop(this.shape(0))) {
for (i <- DataLoop(this.shape(1))) {
res.data(offset) = Math.exp(this.data(offset) - max.data(batch)).toFloat
offset += 1
}
}
val sum = res.sum2D(dim = 1)
offset = 0
for (batch <- DataLoop(res.shape(0))) {
val logsum = max.data(batch) + Math.log(sum.data(batch)).toFloat
for (i <- DataLoop(res.shape(1))) {
res.data(offset) = this.data(offset) - logsum
offset += 1
}
}
res
}
@virtualize
def logSoftmax() = {
assert(this.rank == 1, "TODO: logSoftmax only handles 1d vectors so far")
val m = this.max
val logsum = m + Math.log(this.fold(0.0f)((agg, x) => agg + Math.exp(x - m).toFloat)).toFloat
this.map(x => x - logsum)
}
@virtualize
def softmax_batch() = {
assert(this.rank == 2, "softmax input should be 2-D (batch * 1D logits)")
val max = this.max2D(dim = 1)
val res = Tensor.zeros_like(this)
val offset = var_new(0)
for (batch <- DataLoop(this.shape(0))) {
for (i <- DataLoop(this.shape(1))) {
res.data(offset) = Math.exp(this.data(offset) - max.data(batch)).toFloat
offset += 1
}
}
val sum = res.sum2D(dim = 1)
offset = 0
for (batch <- DataLoop(res.shape(0))) {
for (i <- DataLoop(res.shape(1))) {
res.data(offset) = res.data(offset) / sum.data(batch)
offset += 1
}
}
res
}
@virtualize
def softmax() = {
assert(this.rank == 1, "TODO: softmax only handles 1d vectors so far: " + this.rank)
val m = this.max
val normalized = this.map(x => x - m)
val nor_exp = normalized.exp()
nor_exp / nor_exp.sum()
}
@virtualize
def nllLossB(target: Rep[Array[Int]]) = {
assert(this.rank == 2, "For nllLossB, input should be 2D and target should be 1D")
val res = NewArray[Float](this.shape(0))
val offset = var_new(0)
for (batch <- DataLoop(this.shape(0))) {
res(batch) = -1.0f * this.data(offset + target(batch))
offset += this.shape.strides(0)
}
Tensor(res, this.shape(0))
}
@virtualize
def nllLoss(target: Rep[Int]) = {
assert(this.rank == 1, "input for nllLoss has to be 1d")
// assertC(0 <= target && target < this.nbElem, "Incorrect target")
Tensor.scalar(-1.0f * this.data(target))
}
def resize(dims: Int*) = {
assert(dims.product == this.scalarCount, s"dims: $dims != scalarCount: $scalarCount")
Tensor(this.data, dims : _*)
}
// NOTE: sum matrix to vector, condense on the dims(1) dimension
def sumOnDim1() = {
assert(this.rank <= 2)
if (this.rank == 1) this
else {
val res = NewArray[Float](this.shape(1))
val off = var_new(0)
for (j <- DataLoop(this.shape(1))) {
//for (j <- (0 until this.dims(1)): Rep[Range]) {
res(off) = this.data(off)
off += 1
}
for (i <- (1 until this.shape(0)): Rep[Range]) {
val offR = var_new(0)
for (j <- DataLoop(this.shape(1))) {
//for (j <- (0 until this.dims(1)): Rep[Range]) {
res(offR) += data(off)
off += 1
offR += 1
}
}
Tensor(res, this.shape(1))
}
}
def printHead(count: Int = 10, msg: String = ""): Unit = {
if (msg != "")
printf(s"$msg (size ${this.shape.seq mkString " x "})\\n")
for (i <- 0 until count: Rep[Range]) {
printf(format, this.data(i))
}
printf("\\n")
}
def print(msg: String = ""): Unit = {
if (msg != "")
printf(s"$msg (size ${this.shape.seq mkString " x "})\\n")
if (this.rank == 4) this.print4D
else if (this.rank == 3) this.print3D
else this.printRaw(this.shape.last)
}
val format = "%.10f "
def print4D = {
val idx = var_new(1)
for (i <- 0 until this.shape(0): Rep[Range]) {
val idx1 = var_new(1)
for (j <- 0 until this.shape(1): Rep[Range]) {
printf(s"Pane #(%d, %d) - ${this.shape(2)} x ${this.shape(3)}\\n", idx, idx1)
for (k <- 0 until this.shape(2): Rep[Range]) {
for (l <- 0 until this.shape(3): Rep[Range]) {
printf(format, this.data(i * this.shape.strides(0) + j * this.shape.strides(1) + k * this.shape.strides(2) + l))
}
printf("\\n")
}
printf("\\n\\n")
idx1 += 1
}
idx += 1
}
}
def print3D = {
val idx = var_new(1)
for (i <- 0 until this.shape(0): Rep[Range]) {
printf(s"Pane #%d - ${this.shape(1)} x ${this.shape(2)}\\n", idx)
for (k <- 0 until this.shape(1): Rep[Range]) {
for (l <- 0 until this.shape(2): Rep[Range]) {
printf(format, this.data(i * this.shape.strides(0) + k * this.shape.strides(1) + l))
}
printf("\\n")
}
printf("\\n\\n")
idx += 1
}
}
@virtualize
def printRaw(row: Int = 10) = {
for (i <- 0 until this.scalarCount: Rep[Range]) {
printf(format, data(i))
val imod = i % row
if (imod == row - 1)
printf("\\n")
}
printf("\\n")
}
// setting: this is matrix, that is dims(0)-sized vector, y is dims(1)-sized vector
// the result is to update this so that this += that * y, where * is cartesian product
def add_cartesian(that: Tensor, y: Tensor) = {
generate_comment("add_cartesian")
assert(this.rank == 2 && that.shape == Dimensions(this.shape(1)) && y.shape == Dimensions(this.shape(0)) ||
this.rank == 1 && that.shape == this.shape && y.isScalar, s"${shape} - ${that.shape} - ${y.shape}")
val off = var_new(0)
// TODO remove loop if not used
val up = if (this.rank > 1) this.shape(0) else 1
for (i <- DataLoop(up)) {
//for (i <- (0 until up): Rep[Range]) {
for (j <- DataLoop(shape(1))) {
//for (j <- (0 until dims(1)): Rep[Range]) {
this.data(off + j) = this.data(off + j) + that.data(j) * y.data(i)
}
off += this.shape(1)
}
}
// FIXME: Maybe try to support slicing??
// FIXME: Maybe add support for reshaping??
// FIXME: Maybe support transposing??
// setting: this is dims(0)-sized vector, that is matrix (dims(0) * dims(1)), y is dims(1)-sized vector
// the result is to update this so that this accumulate every matrix col * y
def add_composion(that: Tensor, y: Tensor) = {
assert(that.rank == 2 && this.shape.seq == NSeq(that.shape(1)) && y.shape.seq == NSeq(that.shape(0))
|| that.rank == 1 && this.shape == that.shape && y.isScalar, s"${shape} - ${that.shape} - ${y.shape}")
val off = var_new(0)
// FIXME!!
val up = if (that.rank > 1) that.shape(0) else 1
for (i <- DataLoop(up)) {
//for (i <- (0 until up): Rep[Range]) {
for (j <- DataLoop(that.shape(1))) {
//for (j <- (0 until that.dims(1)): Rep[Range]) {
data(j) += that.data(off + j) * y.data(i)
}
off += that.shape(1)
}
}
// def add_composion(that: Tensor, y: Tensor) = {
// if (this.nbDims == 1)
// this.resize(that.dims(0), )
// }
@virtualize
def addMul(that: Tensor, y: Tensor) = {
assert(this.rank == 2 && that.rank == 2 && y.rank == 2, s"Dimensions: ${this.shape.seq} - ${that.shape.seq} - ${y.shape.seq}")
assert(this.shape(0) == that.shape(0) && this.shape(1) == y.shape(1) && that.shape(1) == y.shape(0), s"Dimensions: ${this.shape.seq} + ${that.shape.seq} * ${y.shape.seq}")
var offThis = var_new(0)
var offThatR = var_new(0)
var offYC = var_new(0)
for (i <- DataLoop(this.shape(0))) {
val offYR = var_new(offYC)
for (j <- DataLoop(this.shape(1))) {
val offY = var_new(offYR)
val offThat = var_new(offThatR)
for (k <- DataLoop(that.shape(1))) {
this.data(offThis) = this.data(offThis) + that.data(offThat) * y.data(offY)
offThat += 1
offY += y.shape.strides(0)
}
offThis += 1
offYR += 1
}
offThatR += that.shape.strides(0)
offYC *= 0
}
}
// private function to get data with default to the only element
def getAt(i: Rep[Int]) = {
if (this.isScalar) data(0)
else data(i)
}
def square(t: Rep[Float]) = t * t
def add_mult(a: Tensor, b: Tensor) = {
assert(Tensor.dimCompatible(a, b) && Tensor.dimCompatible(a, this) && Tensor.dimCompatible(this, b), "dim not Compatible in add_mult")
// FIXME!!!
val dims0M = mmax(shape(0), mmax(a.shape(0), b.shape(0)))
val dims1M = mmax(if (this.rank > 1) shape(1) else 1, mmax(if (a.rank > 1) a.shape(1) else 1, if (b.rank > 1) b.shape(1) else 1))
//if (this.isScalar) {
// for (i <- 0 until (dims0M * dims1M): Rep[Range]) data(0) = data(0) + a.getAt(i) * b.getAt(i)
//} else {
// for (i <- (0 until dims0M * dims1M): Rep[Range]) data(i) = data(i) + a.getAt(i) * b.getAt(i)
//}
for (i <- DataLoop(dims0M * dims1M)) {
if (this.isScalar) { data(0) = data(0) + a.getAt(i) * b.getAt(i) }
else { data(i) = data(i) + a.getAt(i) * b.getAt(i) }
}
}
def addMul(a: Rep[Float], b: Tensor) = {
assert(this.shape == b.shape)
generate_comment("Generate code for addMul")
for (i <- DataLoop(this.scalarCount)) {
//for (i <- 0 until this.nbElem: Rep[Range]) {
this.data(i) = this.data(i) + a * b.data(i)
}
}
def cmulAdd(a: Float, b: Tensor) = {
assert(this.shape == b.shape)
for (i <- DataLoop(this.scalarCount))
//for (i <- 0 until this.nbElem: Rep[Range])
this.data(i) = a * this.data(i) + b.data(i)
this // FIXME ??
}
def add_div(a: Tensor, b: Tensor) = {
assert(Tensor.dimCompatible(a, b) && Tensor.dimCompatible(a, this) && Tensor.dimCompatible(this, b), "dim not Compatible in add_div")
val dims0M = mmax(shape(0), mmax(a.shape(0), b.shape(0)))
// FIXME
val dims1M = mmax(if (rank > 1) shape(1) else 1, mmax(if (a.rank > 1) a.shape(1) else 1, if (b.rank > 1) b.shape(1) else 1))
//if (this.isScalar) {
// for (i <- (0 until dims0M * dims1M): Rep[Range]) data(0) = data(0) + a.getAt(i) / b.getAt(i)
//} else {
// for (i <- (0 until dims0M * dims1M): Rep[Range]) data(i) = data(i) + a.getAt(i) / b.getAt(i)
//}
for (i <- DataLoop(dims0M * dims1M)) {
if (this.isScalar) { data(0) = data(0) + a.getAt(i) / b.getAt(i) }
else { data(i) = data(i) + a.getAt(i) / b.getAt(i) }
}
}
def minus_mult_div_square(a: Tensor, b: Tensor, c: Tensor) = {
assert(Tensor.dimCompatible(a, b) && Tensor.dimCompatible(a, c) && Tensor.dimCompatible(c, b) &&
Tensor.dimCompatible(this, b) && Tensor.dimCompatible(a, this) && Tensor.dimCompatible(this, c),
"dim not competible in minus_mult_div_square")
val dims0M = mmax(shape(0), mmax(a.shape(0), mmax(b.shape(0), c.shape(0))))
// FIXME
val dims1M = mmax(if (rank > 1) shape(1) else 1, mmax(if (a.rank > 1) a.shape(1) else 1, if (b.rank > 1) b.shape(1) else 1))
//if (this.isScalar) {
// for (i <- (0 until dims0M * dims1M): Rep[Range]) data(0) = data(0) - a.getAt(i) * b.getAt(i) / square(c.getAt(i))
//} else {
// for (i <- (0 until dims0M * dims1M): Rep[Range]) data(i) = data(i) - a.getAt(i) * b.getAt(i) / square(c.getAt(i))
//}
for (i <- DataLoop(dims0M * dims1M)) {
if (this.isScalar) { data(0) = data(0) - a.getAt(i) * b.getAt(i) / square(c.getAt(i)) }
else { data(i) = data(i) - a.getAt(i) * b.getAt(i) / square(c.getAt(i)) }
}
}
def add_oneMinusSquare_mult(a: Tensor, b: Tensor) = {
assert(Tensor.dimCompatible(a, b) && Tensor.dimCompatible(a, this) && Tensor.dimCompatible(this, b), "dim not Compatible in add_oneMinusSquare_mult")
val dims0M = mmax(shape(0), mmax(a.shape(0), b.shape(0)))
// FIXME
val dims1M = mmax(if (rank > 1) shape(1) else 1, mmax(if (a.rank > 1) a.shape(1) else 1, if (b.rank > 1) b.shape(1) else 1))
//if (this.isScalar) {
// for (i <- (0 until dims0M * dims1M): Rep[Range]) data(0) = data(0) + (1.0f - square(a.getAt(i))) * b.getAt(i)
//} else {
// for (i <- (0 until dims0M * dims1M): Rep[Range]) data(i) = data(i) + (1.0f - square(a.getAt(i))) * b.getAt(i)
//}
for (i <- DataLoop(dims0M * dims1M)) {
if (this.isScalar) { data(0) = data(0) + (1.0f - square(a.getAt(i))) * b.getAt(i) }
else { data(i) = data(i) + (1.0f - square(a.getAt(i))) * b.getAt(i) }
}
}
def oneMinusThenMult(t: Rep[Float]) = (1.0f - t) * t
def add_oneMinusThenMult_mult(a: Tensor, b: Tensor) = {
assert(Tensor.dimCompatible(a, b) && Tensor.dimCompatible(a, this) && Tensor.dimCompatible(this, b), "dim not Compatible in add_oneMinusThenMult_mult")
val dims0M = mmax(shape(0), mmax(a.shape(0), b.shape(0)))
// FIXME
val dims1M = mmax(if (rank > 1) shape(1) else 1, mmax(if (a.rank > 1) a.shape(1) else 1, if (b.rank > 1) b.shape(1) else 1))
//if (this.isScalar) {
// for (i <- (0 until dims0M * dims1M): Rep[Range]) data(0) = data(0) + oneMinusThenMult(a.getAt(i)) * b.getAt(i)
//} else {
// for (i <- (0 until dims0M * dims1M): Rep[Range]) data(i) = data(i) + oneMinusThenMult(a.getAt(i)) * b.getAt(i)
//}
for (i <- DataLoop(dims0M * dims1M)) {
if (this.isScalar) { data(0) = data(0) + oneMinusThenMult(a.getAt(i)) * b.getAt(i) }
else { data(i) = data(i) + oneMinusThenMult(a.getAt(i)) * b.getAt(i) }
}
}
@virtualize
def conv2D_batch(kernel: Tensor, bias: Tensor, strides: NSeq[Int], pads: NSeq[Int]): Tensor = {
assert (this.rank == 4, "For conv_batch , input should be 4-D, with the first dim to be batch")
assert(kernel.rank == 4, "For Conv, kernel should be 4-D")
assert(bias.rank == 1, "For Conv, bias should be 1-D")
assert(bias.shape(0) == kernel.shape(0), "For Conv, bias length should be the same as number of kernels")
assert(kernel.shape(1) == this.shape(1), "For Conv, input dim_0 should be the same as kernel dim_1")
assert(this.shape(2) >= kernel.shape(2) && this.shape(3) >= kernel.shape(3), "Image too small for Conv")
val totalPads = pads.sum
// TODO: (Fei Wang) not sure if the order is correct!!!
assert(pads.size == 4, "pads should have 4 values, up, down, left, right")
assert(strides.size == 2, "strides should have a strideRow and a strideCol")
val ((strideRow:Int) :: (strideCol:Int) :: Nil) = strides.take(2).toList
val ((padUp:Int) :: (padDown:Int) :: (padLeft:Int) :: (padRight:Int) :: Nil) = pads.take(4).toList
assert(strideRow >= 1, "stride of row should be at least 1")
assert(strideCol >= 1, "stride of col should be at least 1")
assert(padUp == padDown && padUp == padLeft && padUp == padRight, "For now, assume all values in pads are the same")
val resWidth = convSize(this.shape(2) + padLeft + padRight, kernel.shape(2), strideRow)
val resHeight = convSize(this.shape(3) + padUp + padDown, kernel.shape(3), strideCol)
val res = Tensor.fillWithBias(bias, 1, this.shape(0), kernel.shape(0), resWidth, resHeight)
for (i <- DataLoop(this.shape(0))) {
val ptrInput = slice(this.data, i * this.shape.strides(0))
val ptrOutput = slice(res.data, i * res.shape.strides(0))
Tensor(ptrInput, this.shape.drop(1): _*).conv2D_inplace(kernel, strides, pads, Tensor(ptrOutput, res.shape.drop(1): _*))
}
res
}
@virtualize
def conv2D_inplace(kernel: Tensor, strides: NSeq[Int], pads: NSeq[Int], res: Tensor): Unit = {
val totalPads = pads.sum
val ((strideRow:Int) :: (strideCol:Int) :: Nil) = strides.take(2).toList
val ((padUp:Int) :: (padDown:Int) :: (padLeft:Int) :: (padRight:Int) :: Nil) = pads.take(4).toList
val resWidth = res.shape(1)
val resHeight = res.shape(2)
val offOut = var_new(0) // offset for the res by channel
val offWeight1 = var_new(0) // offset for the kernel by channel (dim_0)
for (outPane <- DataLoop(kernel.shape(0))) {
val offWeight2 = var_new(offWeight1) // offset for the kernel for each z-dim of a given channel
val offInput = var_new(0) // offset for this for each channel of input
val ptrOutput = slice(res.data, offOut) // res, restarting from the start of this output channel (2D)
for (inPane <- DataLoop(this.shape(0))) {
val ptrInput = slice(this.data, offInput) // input, restarting from the start of this input channel (2D)
val ptrWeight = slice(kernel.data, offWeight2) // kernel, restarting from the start of this input channel (2D)
if (totalPads == 0) Tensor(ptrOutput, resHeight, resWidth).conv2D1(
Tensor(ptrInput, this.shape(1), this.shape(2)),
Tensor(ptrWeight, kernel.shape(2), kernel.shape(3)),