-
Notifications
You must be signed in to change notification settings - Fork 4
/
npmat.py
2039 lines (1139 loc) · 43.1 KB
/
npmat.py
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
import os, pdb, time, warnings
import numpy as np
__DTYPE__ = np.float64
def dummy():
return CUDAMatrix(np.zeros((1, 1)))
def deprecated(func):
"""This is a decorator which can be used to mark functions
as deprecated. It will result in a warning being emmitted
when the function is used."""
def newFunc(*args, **kwargs):
warnings.warn("Call to deprecated function %s." % func.__name__,
category=DeprecationWarning)
return func(*args, **kwargs)
newFunc.__name__ = func.__name__
newFunc.__doc__ = func.__doc__
newFunc.__dict__.update(func.__dict__)
return newFunc
#from cudamat import CUDAMatException
class CUDAMatException(Exception):
pass
IncompatibleDimensionsException = CUDAMatException("Incompatible matrix dimensions.")
InvalidConfig = CUDAMatException("Invalid Configuration Error (i.e., a dim of the array must be smaller than 2**16.")
## TODO: Figure out which functions produce an invalid config error. These are those who allocate a thread per col/row/elem.
## Those who allocate a bunch of rows per thread, like mult, add, sub, etc, should be immune to the invalid
## configuration error. PS: this error occurs on the real cudamat, which is why it happens.
## Sum/Max/Cumsum
MAX_DIM = 2**16
class CUDAMatrix(object):
"""
A CUDAMatrix object represents a matrix of single precision floating point
numbers on a GPU.
"""
def __init__(self, array, ref=True):
if ref:
self.numpy_array = reformat(array)
else:
self.numpy_array = array
assert self.numpy_array.ndim == 2
self.trans = False
def __del__(self):
pass
@staticmethod
def init_random(seed):
import numpy.random as random
random.seed(seed)
@property
def num_elems(self):
return self.numpy_array.size
@property
def shape(self):
return self.numpy_array.shape
def cheap_transpose(self):
return CUDAMatrix(self.reshape((self.shape[1], self.shape[0])))
def reshape(self, shape):
assert shape[0]*shape[1] == self.shape[0]*self.shape[1]
#self.numpy_array.resize(shape)
#self.numpy_array = self.numpy_array.reshape(shape, order='F')
self.numpy_array.resize(*shape)
return self
def copy(self):
return empty().assign(self)
def set_np_array(self, X):
assert X.shape == self.shape
self.numpy_array[:] = X
self.copy_to_device()
return self
def zero_copy(self):
return self.copy().assign(0)
def resize(self, shape):
if self.shape != shape:
print 'CUDAMatrix: resize (%s -> %s)' % (self.shape, shape)
#self.numpy_array = np.resize(self.numpy_array, shape).astype(__DTYPE__)
self.numpy_array.resize(shape)
self.numpy_array[:] = 0
return self
@property
def T(self):
return CUDAMatrix(self.numpy_array.T)
@property
def mat(self):
return self.numpy_array
@deprecated
def set_shape(self, shape):
return self.resize(shape)
def asarray(self):
"""
Copies the matrix to an ndarray on the CPU and returns it.
"""
#return reformat(self.numpy_array.copy())
return self.numpy_array
def copy_to_device(self):
"""
Copy the matrix to the GPU.
"""
pass
def select_columns(self, indices, target):
"""
copies some columns of self into target.
<indices> must be a row vector. Its elements are float32's representing integers, e.g. "34.0" means the integer "34".
after this call, for all r,c, target[r,c]=self[r,indices[c]].
This returns target.
Negative indices are interpreted in the usual Python way: all elements of <indices> had better be in the range [-self.shape[1], self.shape[1]-1].
This does bounds checking, but out of bounds indices do not raise an exception (because the programmer was lazy). Instead, they result in NaN values in <target>.
"""
assert target.shape[0]==self.shape[0]
assert indices.shape[0]==1
assert indices.shape[1] == target.shape[1]
for c in range(target.shape[1]):
try:
target.numpy_array[:,c] = self.numpy_array[:, int(indices.numpy_array.ravel()[c])]
except IndexError:
target.numpy_array[:,c] = np.nan
return target
def set_selected_columns(self, indices, source):
"""
copies all columns of source into some columns of self.
<indices> must be a row vector. Its elements are float32's representing
integers, e.g. "34.0" means the integer "34". after this call, for all
r,c, self[r,indices[c]]=source[r,c]. This returns self.
Negative indices are interpreted in the usual Python way: all elements
of <indices> had better be in the range [-self.shape[1], self.shape[1]-1].
This does bounds checking, but out of bounds indices do not raise an
exception (because the programmer was lazy). Instead, they result in NaN
values in <self>.
"""
assert self.shape[0]==source.shape[0]
assert indices.shape[0]==1
assert indices.shape[1]==source.shape[1]
for c in range(source.shape[1]):
try:
self.numpy_array[:,int(indices.numpy_array.ravel()[c])] = source.numpy_array[:,c]
except IndexError:
self.numpy_array[:,int(indices.numpy_array.ravel()[c])] = np.nan
return self
def copy_to_host(self):
"""
Copy the matrix to the CPU.
"""
return self.asarray()
def np(self):
return self.copy_to_host()
def assign(self, val):
"""Assign val to self, where val can be a scalar or a CUDAMatrix
with the same dimensions as self. """
if isinstance(val, CUDAMatrix):
self.resize(val.shape)
self.numpy_array[:] = val.numpy_array
elif isinstance(val, (int, float, __DTYPE__)):
self.numpy_array[:] = val
return self
def free_device_memory(self):
"""
Free memory used up by the matrix on the GPU.
"""
pass
def set_trans(self, is_trans):
"""
Set the transposedness flag to is_trans.
"""
if is_trans is True:
self.numpy_array = self.numpy_array.T
def slice(self, first_col, last_col):
return CUDAMatrix(self.numpy_array[:, first_col:last_col], ref=False)
def get_row_slice(self, start, end, target = None):
"""
Get the rows with indices start through end. If target is not provided
memory for a new matrix will be allocated.
"""
ans = CUDAMatrix(self.numpy_array[start:end, :].copy())
if target is not None:
target.assign(ans)
else:
target = ans
return target
def set_row_slice(self, start, end, mat):
try:
self.numpy_array[start:end] = mat.numpy_array
except ValueError:
raise IncompatibleDimensionsException
return self
def get_col_slice(self, start, end, target = None):
## NOTE: no .copy()
ans = self.slice(start, end)
if target is not None:
target.assign(ans)
else:
target = ans
return target
def set_col_slice(self, start, end, mat):
return self.slice(start, end).assign(mat)
# def select_columns(self, indices, target):
# """
# Copies selected columns into a target matrix.
# <self>, <indices>, and <target> are all cudamat matrices.
# <self> is an M by K matrix.
# <indices> is of shape 1 by N. All elements x are expected to be
# 0<=x<K, and are expected to have nothing after the decimal point (i.e.
# to be floats representing integers).
# <target> is an M by N matrix that will be filled with the result.
# After the operation, for all i,j, target[i, j] = self[i, int(indices[j])]
# This returns <target>.
# ? idea: No bounds checking is done.
# """
# M, K = self.shape
# one, N = indices.shape
# assert one == 1
# M_, N_ = target.shape
# assert M_ == M and N == N_
# np_ints = indices.numpy_array.astype(int)
# if not (np_ints.max() < K and np_ints.min() >= 0):
# raise ValueError("Index out of bounds.")
# target.numpy_array[:] = self.numpy_array[:, np_ints.flatten()]
# return target
def transpose(self, target = None):
if target is None:
return CUDAMatrix(self.numpy_array.T.copy())
else:
target.numpy_array.resize((self.shape[1], self.shape[0]))
target.numpy_array[:] = self.numpy_array.T
return target
def assign_transpose(self, t):
return t.transpose(target = self)
def fill_with_rand(self):
"""
Fill matrix on the GPU with random numbers drawn from the uniform
distribution over the (0,1) interval.
"""
self.numpy_array[:] = np.random.rand(*self.shape)
return self
def fill_with_randn(self):
"""
Fill matrix on the GPU with random numbers drawn from the standard normal
distribution.
"""
self.numpy_array[:] = np.random.randn(*self.shape)
return self
def add_col_vec(self, vec, target = None):
"""
Add vector vec to every column of the matrix. If a target is provided,
it is used to store the result instead of self.
"""
a, b = self.shape
a_, b_ = vec.shape
if not (b_ == 1 and a_ == a):
raise IncompatibleDimensionsException
if target is None:
target = self
target.resize(self.shape)
target.numpy_array[:] = self.numpy_array + vec.numpy_array
return target
def assign_add_col_vec(self, a, b):
return a.add_col_vec(b, target = self)
def add_col_mult(self, vec, mult, target = None):
"""
Add a multiple of vector vec to every column of the matrix. If a target
is provided, it is used to store the result instead of self.
"""
a, b = self.shape
a_, b_ = vec.shape
if not (b_ == 1 and a_ == a):
raise IncompatibleDimensionsException
if target is None:
target = self
target.resize(self.shape)
target.numpy_array[:] = self.numpy_array + vec.numpy_array * mult
return target
def assign_add_col_mult(self, a, m, b):
return a.add_col_vec(b, m, target = self)
def add_row_vec(self, vec, target = None):
"""
Add vector vec to every row of the matrix. If a target is provided,
it is used to store the result instead of self.
"""
a, b = self.shape
a_, b_ = vec.shape
if not (a_ == 1 and b_ == b):
raise IncompatibleDimensionsException
if target is None:
target = self
target.resize(self.shape)
target.numpy_array[:] = vec.numpy_array + self.numpy_array
return target
def assign_add_row_vec(self, a, b):
return a.add_row_vec(b, target = self)
def mult_by_col(self, vec, target = None):
"""
Multiply vector vec into every column of the matrix. If a target is
provided, it is used to store the result instead of self.
"""
a, b = self.shape
a_, b_ = vec.shape
if not (b_ == 1 and a_ == a):
raise IncompatibleDimensionsException
if target is None:
target = self
target.resize(self.shape)
target.numpy_array[:] = vec.numpy_array * self.numpy_array
return target
def mult_by_row(self, vec, target = None):
"""
Multiply vector vec into every row of the matrix. If a target is
provided, it is used to store the result instead of self.
"""
a, b = self.shape
a_, b_ = vec.shape
if not (b_ == b and a_ == 1):
raise IncompatibleDimensionsException
if target is None:
target = self
target.resize(self.shape)
target.numpy_array[:] = vec.numpy_array * self.numpy_array
return target
def sum(self, axis, target = None):
"""
Sum the matrix along the given dimension, where 0 represents the leading
dimension and 1 represents the non-leading dimension. If a target is
not prvided, a new vector is created for storing the result.
"""
if axis == 0:
ans = self.numpy_array.sum(0)[np.newaxis, :]
elif axis == 1:
ans = self.numpy_array.sum(1)[:, np.newaxis]
else:
raise ValueError("axis must be only 0 or 1; instead, got %s\n", axis)
ans = CUDAMatrix(ans)
if target is not None:
target.assign(ans)
else:
target = ans
return target
def mean(self, axis, target = None):
if axis == 0:
ans = self.numpy_array.mean(0)[np.newaxis, :]
elif axis == 1:
ans = self.numpy_array.mean(1)[:, np.newaxis]
else:
raise ValueError("axis must be only 0 or 1; instead, got %s\n", axis)
ans = CUDAMatrix(ans)
if target is not None:
target.assign(ans)
else:
target = ans
return target
def assign_sum(self, mat, axis):
return mat.sum(axis, target = self)
def assign_mean(self, mat, axis):
return mat.mean(axis, target = self)
def add_sums(self, mat, axis, mult = 1.):
"""
Add a multiple of the sums of the matrix mat along the given dimension
to self.
"""
if self.numpy_array.shape != self.mat.shape:
raise IncompatibleDimensionsException
sum = mat.sum(axis)
sum.numpy_array *= mult
if axis == 0:
self.add_row_vec(sum)
elif axis == 1:
self.add_col_vec(sum)
return self
def less_than(self, val, target = None):
"""
Perform the operation target = 1. * (self < val), where val can be a matrix or a scalar.
"""
if target is None:
target = self
target.resize(self.shape)
if isinstance(val, (int, float, __DTYPE__)):
target.numpy_array[:] = self.numpy_array < val
else:
if val.shape != self.shape:
raise IncompatibleDimensionsException
target.numpy_array[:] = (self.numpy_array < val.numpy_array).astype(__DTYPE__)
return target
def assign_less_than(self, mat, val):
return mat.less_than(val, self)
def greater_than(self, val, target = None):
"""
Perform the operation target = 1. * (self > val), where val can be a matrix or a scalar.
"""
if target is None:
target = self
target.resize(self.shape)
if isinstance(val, (int, float, __DTYPE__)):
target.numpy_array[:] = (self.numpy_array > val).astype(__DTYPE__)
else:
if val.shape != self.shape:
raise IncompatibleDimensionsException
target.numpy_array[:] = (self.numpy_array > val.numpy_array).astype(__DTYPE__)
return target
def assign_greater_than(self, mat, val):
return mat.greater_than(val, self)
def max(self, axis, target = None, transpose_aux=None):
"""
Find the maximum value along the given dimension, where 0 represents the
leading dimension and 1 represents the non-leading dimension. If a target
is not prvided, a new vector is created for storing the result.
"""
m, n = self.shape
if axis == 0:
if target is None:
target = empty((1, n))
target.resize((1, n))
target.numpy_array[:] = self.numpy_array.max(0)
elif axis == 1:
# IN theory: we are supposed to do this:
# if not target:
# #target = CUDAMatrix(np.empty((m, 1), dtype=np.float32, order = 'F'))
# target = empty((m, 1))
# else:
# target.resize((m, 1))
# err_code = _cudamat.max_by_axis(self.p_mat, target.p_mat, ct.c_int(axis))
# if err_code:
# raise generate_exception(err_code)
assert transpose_aux != None
self.transpose(target = transpose_aux)
target.reshape(target.shape[::-1])
transpose_aux.max(axis = 0, target = target)
target.reshape(target.shape[::-1])
return target
def assign_max(self, mat, axis, transpose_aux=None):
return mat.max(axis, target = self, transpose_aux = transpose_aux)
def total_max(self):
row_maxes = empty((1, 1)).assign_max(self, axis = 0)
return row_maxes.reshape((row_maxes.shape[1], row_maxes.shape[0])).max(axis = 0).asarray()[0,0]
def total_sum(self):
return self.numpy_array.sum()
def sign(self, target = None):
if target is None:
target = empty(self.shape)
target.resize(self.shape)
target.numpy_array[:] = np.sign(self.numpy_array)
return target
def assign_sign(self, a):
return a.sign(target = self)
def apply_sigmoid(self, target = None):
"""
Apply the logistic sigmoid to each element of the matrix.
"""
return sigmoid(self, target)
def sigmoid(self, target = None):
"""
Apply the logistic sigmoid to each element of the matrix.
"""
return sigmoid(self, target)
def assign_sigmoid(self, t):
return sigmoid(t, self)
def log(self, target = None):
return log(self, target)
def assign_log(self, t):
return log(t, self)
def exp(self, target = None):
return exp(self, target)
def assign_exp(self, t):
return exp(t, self)
def pow(self, p, target = None):
return pow(self, p, target)
def assign_pow(self, mat, p):
return pow(mat, p, self)
def sqrt(self, target = None):
return sqrt(self, target)
def assign_sqrt(self, mat):
return sqrt(mat, self)
def reciprocal(self, target = None):
"""
Find the reciprocal of each element of the matrix.
"""
if not target:
target = self
target.resize(self.shape)
target.numpy_array[:] = 1./self.numpy_array[:]
return target
def assign_reciprocal(self, mat):
return mat.reciprocal(target = self)
def dot(self, mat2, target = None):
"""
Multiply the matrix by mat2 from the right.
"""
return dot(self, mat2, target)
def assign_dot(self, m1, m2):
m1.dot(m2, target = self)
return self
def add_dot(self, m1, m2):
"""
Add the dot product of m1 and m2 to the matrix.
"""
m3 = dot(m1, m2)
if m3.shape != self.shape:
raise IncompatibleDimensionsException
self.numpy_array += m3.numpy_array
return self
def subtract_dot(self, m1, m2):
"""
Subtract the dot product of m1 and m2 from the matrix.
"""
m3 = dot(m1, m2)
if m3.shape != self.shape:
raise IncompatibleDimensionsException
self.numpy_array -= m3.numpy_array
return self
def add_mult(self, mat2, alpha = 1.):
"""
Add multiple of mat2 to the matrix.
"""
if mat2.shape != self.shape:
raise IncompatibleDimensionsException
self.numpy_array += mat2.numpy_array * alpha
return self
def assign_mult(self, mat2, alpha):
self.resize(mat2.shape)
self.assign(0)
self.add_mult(mat2, alpha)
return self
def subtract_mult(self, mat2, alpha = 1.):
"""
Subtract a multiple of mat2 from the matrix.
"""
if mat2.shape != self.shape:
raise IncompatibleDimensionsException
self.numpy_array -= mat2.numpy_array * alpha
return self
def add(self, val, target = None):
"""Add val to self, where val can be a scalar or a CUDAMatrix with the
same dimensions as self. """
if not target:
target = self
target.resize(self.shape)
if isinstance(val, CUDAMatrix):
if target.shape != val.shape:
raise IncompatibleDimensionsException
target.numpy_array[:] = self.numpy_array + val.numpy_array
elif isinstance(val, (int, float, __DTYPE__)):
target.numpy_array[:] = self.numpy_array + val
else:
raise ValueError, "Value must be of type CUDAMatrix, int, or float."
return target
def assign_add(self, a, b):
a.add(b, target = self)
return self
def subtract(self, val, target = None):
"""Subtract val from self, where val can be a scalar or a CUDAMatrix with
the same dimensions as self. """
if not target:
target = self
target.resize(self.shape)
if isinstance(val, CUDAMatrix):
if target.shape != val.shape:
raise IncompatibleDimensionsException
target.numpy_array[:] = self.numpy_array - val.numpy_array
elif isinstance(val, (int, float, __DTYPE__)):
target.numpy_array[:] = self.numpy_array - val
else:
raise ValueError, "Value must be of type CUDAMatrix, int, or float."
return target
def assign_subtract(self, a, b):
a.subtract(b, target = self)
return self
def divide(self, val, target = None):
"""Divide self by val, where val can be a scalar or a CUDAMatrix with the
same dimensions as self. """
if not target:
target = self
target.resize(self.shape)
if isinstance(val, CUDAMatrix):
if target.shape != val.shape:
raise IncompatibleDimensionsException
target.numpy_array[:] = self.numpy_array / val.numpy_array
elif isinstance(val, (int, float, __DTYPE__)):
target.numpy_array[:] = self.numpy_array / val
else:
raise ValueError, "Value must be of type CUDAMatrix, int, or float."
return target
def assign_divide(self, a, b):
a.divide(b, target = self)
return self
def mult(self, val, target = None):
"""Multiply self by val, where val can be a scalar or a CUDAMatrix with
the same dimensions as self. """
if not target:
target = self
target.resize(self.shape)
if isinstance(val, CUDAMatrix):
if target.shape != val.shape:
raise IncompatibleDimensionsException
target.numpy_array[:] = self.numpy_array * val.numpy_array
elif isinstance(val, (int, float, __DTYPE__)):
target.numpy_array[:] = self.numpy_array * val
else:
raise ValueError, "Value must be of type CUDAMatrix, int, or float."
return target
def assign_mult(self, a, b):
a.mult(b, target = self)
return self
@deprecated
def assign_scalar(self, alpha):
"""
Assign scalar alpha to every element of the matrix.
"""
self.assign(alpha)
return self
@deprecated
def mult_by_scalar(self, alpha, target = None):