/
basic_ops.py
4290 lines (3720 loc) · 150 KB
/
basic_ops.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
from __future__ import print_function
import copy
import logging
import sys
import numpy
from six import iteritems
from six.moves import StringIO, xrange
import theano
from theano import gof, Type, Apply
from theano import tensor, scalar, config
from theano.gradient import grad_undefined
from theano.scalar import Scalar
scal = scalar # somewhere scalar gets reassigned to be a function
try:
# We must be able to import this file to create the full doc when nvcc
# is not available
from theano.sandbox.cuda import filter as type_support_filter
from theano.sandbox.cuda import device_properties
import cuda_ndarray
except ImportError:
pass
from theano.sandbox.cuda import GpuOp
from theano.sandbox.cuda.type import CudaNdarrayType
from theano.sandbox.cuda.elemwise import NaiveAlgo
_logger_name = 'theano.sandbox.cuda.basic_ops'
_logger = logging.getLogger(_logger_name)
def as_cuda_ndarray_variable(x):
if getattr(x, 'owner', None):
if isinstance(x.owner.op, HostFromGpu):
return x.owner.inputs[0]
elif (isinstance(x.owner.op, GpuFromHost) and
x.owner.inputs[0].owner and
isinstance(x.owner.inputs[0].owner.op, HostFromGpu)):
return x.owner.inputs[0].owner.inputs[0]
if hasattr(x, '_as_CudaNdarrayVariable'):
return x._as_CudaNdarrayVariable()
tensor_x = tensor.as_tensor_variable(x)
return gpu_from_host(tensor_x)
def as_cuda_array(obj):
if isinstance(obj, numpy.ndarray):
return cuda_ndarray.cuda_ndarray.CudaNdarray(obj)
elif isinstance(obj, cuda_ndarray.cuda_ndarray.CudaNdarray):
return obj
else:
raise TypeError("Don't know how to cast to a CudaNdarray object")
class HostFromGpu(GpuOp):
"""
Implement the transfer from gpu to the cpu.
"""
check_input = False
def __eq__(self, other):
return type(self) == type(other)
def __hash__(self):
return hash(type(self))
def __str__(self):
return 'HostFromGpu'
def make_node(self, x):
if not isinstance(x.type, CudaNdarrayType):
raise TypeError("Expected a Theano variable with type "
"CudaNdarrayType. Got %s with type %s" % (x,
x.type))
return Apply(self, [x], [tensor.TensorType(dtype=x.dtype,
broadcastable=x.broadcastable)()])
def perform(self, node, inp, out):
x, = inp
z, = out
z[0] = numpy.asarray(x)
def grad(self, inputs, grads):
gz, = grads
return [gpu_from_host(gz)]
def R_op(self, inputs, eval_points):
ev, = eval_points
return [self(ev)]
def infer_shape(self, node, xshp):
return xshp
def c_code(self, node, name, inputs, outputs, sub):
inp = inputs[0]
out = outputs[0]
fail = sub['fail']
return """
Py_XDECREF(%(out)s);
%(out)s = (PyArrayObject *) CudaNdarray_CreateArrayObj(%(inp)s);
if(!%(out)s){
%(fail)s;
}
""" % locals()
def c_code_cache_version(self):
return (3,)
host_from_gpu = HostFromGpu()
class GpuFromHost(GpuOp):
"""
Implement the transfer from cpu to the gpu.
"""
check_input = False
def __eq__(self, other):
return type(self) == type(other)
def __hash__(self):
return hash(type(self))
def __str__(self):
return 'GpuFromHost'
def make_node(self, x):
if not isinstance(x.type, tensor.TensorType):
raise TypeError("Expected a Theano variable with type "
"TensorType. Got %s with type %s" % (x,
x.type))
return Apply(self, [x], [CudaNdarrayType(broadcastable=x.broadcastable,
dtype=x.dtype)()])
def perform(self, node, inp, out):
x, = inp
z, = out
z[0] = type_support_filter(theano._asarray(x, dtype='float32'),
tuple([0] * x.ndim), 0, z[0])
def grad(self, inputs, grads):
gz, = grads
gz = as_cuda_ndarray_variable(gz)
return [host_from_gpu(gz)]
def R_op(self, inputs, eval_points):
ev, = eval_points
return [self(ev)]
def infer_shape(self, node, xshp):
return xshp
def c_code(self, node, name, inputs, outputs, sub):
inp = inputs[0]
out = outputs[0]
fail = sub['fail']
return """
int err = 0;
Py_XDECREF(%(out)s);
%(out)s = (CudaNdarray*) CudaNdarray_New();
if(!%(out)s){
%(fail)s;
}
err = CudaNdarray_CopyFromArray(%(out)s, %(inp)s);
if(err){
%(fail)s;
}
""" % locals()
def c_code_cache_version(self):
return (2,)
gpu_from_host = GpuFromHost()
class GpuElemwise(GpuOp):
"""
Implement a generic elemwise on the gpu.
"""
nin = property(lambda self: self.scalar_op.nin)
nout = property(lambda self: self.scalar_op.nout)
def __init__(self, scalar_op, inplace_pattern=None, sync=None):
# TODO-- this looks like a bug-- either we should use the sync argument
# or get rid of it, we shouldn't let the client think they can control
# sync when they can't
if inplace_pattern is None:
inplace_pattern = {}
sync = config.gpuelemwise.sync
self.scalar_op = scalar_op
self.inplace_pattern = inplace_pattern
self.destroy_map = dict((o, [i]) for o, i in inplace_pattern.items())
self.sync = sync
self._rehash()
self.src_generator = NaiveAlgo(self.scalar_op, sync=sync,
inplace_pattern=self.inplace_pattern)
def __getstate__(self):
d = copy.copy(self.__dict__)
d.pop('__epydoc_asRoutine', None)
d.pop('_hashval')
return d
def __setstate__(self, d):
self.__dict__.update(d)
# old objects defaulted to sync behaviour
self.sync = d.get('sync', True)
self._rehash()
def __eq__(self, other):
return (type(self) == type(other) and
self.scalar_op == other.scalar_op and
self.inplace_pattern == other.inplace_pattern and
self.sync == other.sync)
def _rehash(self):
items = list(self.inplace_pattern.items())
items.sort()
tuple_items = [k for k, v in items]
for k, v in items:
if isinstance(v, (tuple, list)):
tuple_items += [tuple(v)]
else:
tuple_items += [v]
tuple_items = tuple(tuple_items)
h = (hash(type(self)) ^ hash(self.scalar_op) ^
hash(tuple_items) ^ hash(self.sync))
# don't change a code that has already been computed for this object
assert h == getattr(self, '_hashval', h)
self._hashval = h
def __hash__(self):
return self._hashval
def __str__(self):
if self.inplace_pattern:
items = list(self.inplace_pattern.items())
items.sort()
# We need to print the scalar_op, not only the its class name
# to have the full definition of composite op.
return "GpuElemwise{%s}%s" % (self.scalar_op, str(items))
return "GpuElemwise{%s,no_inplace}" % (self.scalar_op)
def __repr__(self):
return self.__str__()
def make_node(self, *inputs):
_inputs = [as_cuda_ndarray_variable(i) for i in inputs]
if self.nin > 0 and len(_inputs) != self.nin:
raise TypeError('Wrong argument count', (self.nin, len(_inputs)))
target_length = max([input.type.ndim for input in _inputs])
args = []
for input in _inputs:
length = input.type.ndim
difference = target_length - length
if not difference:
args.append(input)
else:
# TODO: use LComplete instead
args.append(GpuDimShuffle(
input.type.broadcastable,
['x'] * difference + list(range(length))
)(input))
_inputs = args
# output is broadcastable only along dimensions where all
# inputs are broadcastable
broadcastable = []
for d in xrange(_inputs[0].type.ndim):
bcast_d = True
for i in _inputs:
if not i.type.broadcastable[d]:
bcast_d = False
break
broadcastable.append(bcast_d)
assert len(broadcastable) == _inputs[0].type.ndim
otype = CudaNdarrayType(broadcastable=broadcastable)
assert self.nout > 0
return Apply(self, _inputs, [otype() for o in xrange(self.nout)])
def c_support_code(self, *args, **kwargs):
return self.src_generator.c_support_code(*args, **kwargs)
def c_support_code_apply(self, *args, **kwargs):
return self.src_generator.c_support_code_apply(*args, **kwargs)
def c_code(self, *args, **kwargs):
return self.src_generator.c_code(*args, **kwargs)
def c_compile_args(self):
# TODO: compile ptx file without constraint and then use the number of
# registers required to inform the maximum number of threads per block.
return ["--maxrregcount=32"]
def c_code_cache_version(self):
return self.src_generator.cache_version
class GpuDimShuffle(GpuOp):
"""
Implement DimShuffle on the gpu.
"""
check_broadcast = False
def __init__(self, input_broadcastable, new_order):
input_broadcastable = tuple(input_broadcastable)
self.input_broadcastable = input_broadcastable
self.new_order = tuple(new_order)
for i, b in enumerate(input_broadcastable):
if i not in new_order:
if not b:
# we cannot drop non-broadcastable dimensions
raise ValueError("You cannot drop a non-broadcastable"
" dimension.",
(input_broadcastable, new_order))
# this is the list of the original dimensions that we keep
self.shuffle = [x for x in new_order if x != 'x']
# list of dimensions of the output that are broadcastable and were not
# in the original input
self.augment = [i for i, x in enumerate(new_order) if x == 'x']
self.view_map = {0: [0]}
self._rehash()
def __getstate__(self):
d = dict(self.__dict__)
del d['_hashval']
return d
def __setstate__(self, d):
self.__dict__.update(d)
self._rehash()
def make_node(self, input):
ib = tuple(input.type.broadcastable)
if not ib == self.input_broadcastable:
if len(ib) != len(self.input_broadcastable):
raise TypeError((
"The number of dimensions of the "
"input is incorrect for this op. Expected %s, got %s."
% (self.input_broadcastable, ib)))
for expected, b in zip(self.input_broadcastable, ib):
if expected is True and b is False:
raise TypeError((
"The broadcastable pattern of the "
"input is incorrect for this op. Expected %s, got %s."
% (self.input_broadcastable, ib)))
# else, expected == b or expected is False and b is True
# Both case are good.
ob = []
if not isinstance(input.type, CudaNdarrayType):
input = as_cuda_ndarray_variable(input)
for value in self.new_order:
if value == 'x':
ob.append(True)
else:
ob.append(ib[value])
return Apply(self, [input], [CudaNdarrayType(broadcastable=ob)()])
def __eq__(self, other):
# it's probably not necessary to compare input_broadcastable
return type(self) == type(other) \
and self.new_order == other.new_order \
and self.input_broadcastable == other.input_broadcastable
def _rehash(self):
self._hashval = (hash(type(self).__name__) ^
hash(type(self).__module__) ^
hash(self.new_order) ^
hash(self.input_broadcastable))
def __hash__(self):
return self._hashval
def __str__(self):
return "GpuDimShuffle{%s}" % ",".join(str(x) for x in self.new_order)
def c_code(self, node, name, inp, out, sub):
input, = inp
res, = out
basename = input + '__view_or_copy'
nd_in = len(self.input_broadcastable)
nd_out = len(self.new_order)
sio = StringIO()
fail = sub['fail']
# check input
print("""
if (%(input)s->nd != %(nd_in)s)
{
PyErr_Format(PyExc_TypeError,
"required nd=%(nd_in)s, got nd=%%i", %(input)s->nd);
%(fail)s;
}
""" % locals(), file=sio)
# alloc an output
print("""
if (%(res)s && (%(res)s->nd == %(nd_out)s))
{
//re-use previously-allocated cnda
}
else
{
if (%(res)s)
{
if (CudaNdarray_set_nd(%(res)s, %(nd_out)s))
{
Py_DECREF(%(res)s);
%(res)s = NULL;
%(fail)s;
}
}
else
{
%(res)s = (CudaNdarray*) CudaNdarray_New(%(nd_out)s);
if (NULL == %(res)s)
{
%(fail)s;
}
}
}
""" % locals(), file=sio)
print("""
if (CudaNdarray_set_device_data(%(res)s,
CudaNdarray_DEV_DATA(%(input)s),
%(input)s))
{
// err message set
Py_DECREF(%(res)s);
%(res)s = NULL;
%(fail)s;
}
""" % locals(), file=sio)
# reassign the dimension and strides in the host pointers
for i, o in enumerate(self.new_order):
if o == 'x':
# TODO: remove this assertion
# the correct thing to do is to insert a run-time check
# that the size in this dimension is 1
assert node.outputs[0].type.broadcastable[i]
print("""
CudaNdarray_set_dim(%(res)s, %(i)s, 1);
CudaNdarray_set_stride(%(res)s, %(i)s, 0);
""" % locals(), file=sio)
else:
print("""
CudaNdarray_set_dim(%(res)s, %(i)s,
CudaNdarray_HOST_DIMS(%(input)s)[%(o)s]);
CudaNdarray_set_stride(%(res)s, %(i)s,
CudaNdarray_HOST_STRIDES(%(input)s)[%(o)s]);
""" % locals(), file=sio)
for i, o in enumerate(self.new_order):
print("""
//std::cerr << "GpuDimShuffle " << %(res)s << " str[%(i)s] = " << %(res)s->str[%(i)s] << "\\n";
""" % locals(), file=sio)
# copy the host dims and stride -> device
if 0:
print("""
if (CudaNdarray_copy_structure_to_device(%(res)s))
{
//err msg set
Py_DECREF(%(res)s);
%(res)s = NULL;
%(fail)s;
}
""" % locals(), file=sio)
if 0: # print full code to stdout
print('--------------------------------------')
print('C_CODE')
print('')
print(self)
print("IN BROAD", self.input_broadcastable)
print("NEW ORDER", self.new_order)
print('------------')
print('')
print(sio.getvalue())
print('--------------------------------------')
if 0:
sys.exit()
return sio.getvalue()
def c_code_cache_version(self):
return (1, 0)
def infer_shape(self, node, shapes):
ishp, = shapes
# transpose
rval = [ishp[i] for i in self.shuffle]
# augment
for augm in self.augment:
rval.insert(augm, 1)
return [rval]
class GpuCAReduce(GpuOp):
"""
GpuCAReduce is a Reduction along some dimensions by a scalar op.
The dimensions along which to reduce is specified by the
`reduce_mask` that you pass to the constructor. The `reduce_mask`
is a tuple of booleans (actually integers 0 or 1) that specify for
each input dimension, whether to reduce it (1) or not (0).
Parameters
----------
pre_scalar_op
If present, must be a scalar op with only 1 input.
We will execute it on the input value before reduction.
Notes
-----
This Op is a work in progress.
This op was recently upgraded from just GpuSum a general CAReduce. Not
many code cases are supported for scalar_op being anything other than
scal. Add instances yet.
Important note: if you implement new cases for this op, be sure to
benchmark them and make sure that they actually result in a speedup.
GPUs are not especially well-suited to reduction operations so it is
quite possible that the GPU might be slower for some cases.
Examples
--------
When scalar_op is a theano.scalar.basic.Add instance:
- reduce_mask == (1,) sums a vector to a scalar
- reduce_mask == (1,0) computes the sum of each column in a matrix
- reduce_mask == (0,1) computes the sum of each row in a matrix
- reduce_mask == (1,1,1) computes the sum of all elements in a 3-tensor.
..note:: Any reduce_mask of all zeros is a sort of 'copy', and may
be removed during graph optimization.
"""
def __init__(self, reduce_mask, scalar_op, pre_scalar_op=None):
self.reduce_mask = tuple(reduce_mask)
self.scalar_op = scalar_op
# used to make sure that calls to scalar op
# have unique name arguments
self._n_scalar_op_calls = 0
self.pre_scalar_op = pre_scalar_op
if pre_scalar_op:
assert pre_scalar_op.nin == 1
def __eq__(self, other):
return (type(self) == type(other) and
self.reduce_mask == other.reduce_mask and
self.scalar_op == other.scalar_op and
self.pre_scalar_op == other.pre_scalar_op)
def __hash__(self):
return (hash(type(self)) ^
hash(self.reduce_mask) ^
hash(type(self.scalar_op)) ^
hash(type(self.pre_scalar_op)))
def __str__(self):
pre = ""
if self.pre_scalar_op:
pre = "pre=%s,red=" % str(self.pre_scalar_op)
return "GpuCAReduce{%s%s}{%s}" % (
pre,
str(self.scalar_op),
','.join(str(i) for i in self.reduce_mask)
)
def __setstate__(self, d):
self.__dict__.update(d)
# For unpickling of old ops.
if not hasattr(self, "pre_scalar_op"):
self.pre_scalar_op = None
def make_node(self, x):
x = as_cuda_ndarray_variable(x)
if (x.type.ndim != len(self.reduce_mask)):
raise TypeError("x must have rank %i" % len(self.reduce_mask))
o_broadcast = [x.type.broadcastable[i] for i
in xrange(x.type.ndim) if not self.reduce_mask[i]]
return Apply(self, [x], [CudaNdarrayType(o_broadcast)()])
"""
This method must be commented, because there's no way
to communicate that it's OK to call for + but not for
max
def perform(self, node, inp, out):
x, = inp
z, = out
# reduce_max is declared but does nothing but
# raise NotImplementedError.
# We can't call it here anyway because it hasn't
# been added to the python bindings yet
z[0] = x.reduce_sum(self.reduce_mask)
"""
def supports_c_code(self, inputs):
"""
Returns True if the current op and reduce pattern has functioning C
code.
"""
# If we don't even have the right method, we certainly
# don't support the C code
# (This is the test that used to be implemented by
# local_gpu_sum)
pattern = (''.join(str(i) for i in self.reduce_mask))
if not hasattr(self, 'c_code_reduce_%s' % pattern):
return False
# Now that this is a general reduction op, we might
# have a method for a pattern, but that pattern
# might not be implemented for the current scalar op.
# To detect this more complicated situation, we
# make fake arguments to c_code, try to run them,
# and see if NotImplementedError gets raised.
node = self.make_node(*inputs)
name = 'fake_name'
inp = ['fake_input_name_%d' % i for i in xrange(len(inputs))]
out = ['fake_output_name_%d' % i for i in xrange(len(node.outputs))]
sub = {'fail': 'fake failure code'}
try:
self.c_code(node, name, inp, out, sub)
self.c_support_code_apply(node, name)
except NotImplementedError:
return False
return True
def c_code(self, node, name, inp, out, sub):
x, = inp
z, = out
nd_in = node.inputs[0].type.ndim
nd_out = node.outputs[0].type.ndim
assert nd_in - nd_out == sum(self.reduce_mask)
sio = StringIO()
fail = sub['fail']
# check input
print("""
if (%(x)s->nd != %(nd_in)s)
{
PyErr_Format(PyExc_TypeError,
"required nd=%(nd_in)s, got nd=%%i", %(x)s->nd);
%(fail)s;
}
""" % locals(), file=sio)
# It might be nice to use a property of the op class to do this,
# but tensor.elemwise.CAReduce has this exact same check so I guess
# this is OK to do
if self.scalar_op in [scal.minimum, scal.maximum]:
conds = ["(CudaNdarray_HOST_DIMS(%s)[%d] == 0)" % (x, i)
for i in xrange(nd_in)
if self.reduce_mask[i]]
assert len(conds) > 0
cond = "(" + " || ".join(conds) + ")"
print("""
if %(cond)s
{
PyErr_Format(PyExc_ValueError," tried to reduce a 0-length axis.");
%(fail)s;
}
""" % locals(), file=sio)
#
# alloc an output if we need one
#
# check the basics of out output
print("""
if ( !%(z)s
|| (%(z)s->nd != %(nd_out)s)
""" % locals(), file=sio)
# ensure that the output has the right non-reduced dimensions
j = 0
for i in xrange(nd_in):
if not self.reduce_mask[i]:
print(" || (CudaNdarray_HOST_DIMS(%(z)s)[%(j)s] != CudaNdarray_HOST_DIMS(%(x)s)[%(i)d]) " % locals(), file=sio)
j += 1
print("""
)
{
""" % locals(), file=sio)
if nd_out > 0:
print("int new_dims[%(nd_out)s]; " % locals(), file=sio)
else:
print("int *new_dims=NULL; ", file=sio)
j = 0
for i in xrange(nd_in):
if not self.reduce_mask[i]:
print('new_dims[%(j)s] = CudaNdarray_HOST_DIMS(%(x)s)[%(i)s];' % locals(), file=sio)
j += 1
print("""
Py_XDECREF(%(z)s);
%(z)s = (CudaNdarray*) CudaNdarray_NewDims(%(nd_out)s, new_dims);
if (NULL == %(z)s)
{
%(fail)s;
}
}
""" % locals(), file=sio)
# \begin bracket the reduction in a check that there is
# actually work to do
if getattr(self.scalar_op, 'identity', None) == 0:
zero_shp = "cudaMemset(%(z)s->devdata, 0, CudaNdarray_SIZE(%(z)s) * sizeof(float))" % locals()
# TODO: elif getattr(self.scalar_op, 'identity', None) == 1:
else:
zero_shp = """
PyErr_Format(PyExc_NotImplementedError,
"GpuCAReduce not implemented when input shape is 0 for this scalar_op");
%(fail)s;
""" % locals()
print("""
if (CudaNdarray_SIZE(%(z)s) && ! CudaNdarray_SIZE(%(x)s)){
%(zero_shp)s;
}
else if (CudaNdarray_SIZE(%(z)s))
{
""" % locals(), file=sio)
#
# Now perform the reduction
#
if all(i == 1 for i in self.reduce_mask):
# check if the tensor is ccontiguous, if true, use the c_code_reduce_ccontig code.
# TODO: check if we are ccontiguous when we un-dimshuffle
# TODO: if only some dims are ccontiguous, call version with less dims.
print('if(CudaNdarray_is_c_contiguous(%(x)s)){'%locals(), file=sio)
self.c_code_reduce_ccontig(sio, node, name, x, z, fail)
print("}else{", file=sio)
getattr(self, 'c_code_reduce_%s'%(''.join(
str(i) for i in self.reduce_mask)))(sio, node, name, x, z, fail)
print("}", file=sio)
else:
getattr(self, 'c_code_reduce_%s'%(''.join(
str(i) for i in self.reduce_mask)))(sio, node, name, x, z, fail)
# \end bracket the reduction ...
print("""
}
""" % locals(), file=sio)
return sio.getvalue()
def _makecall(self, node, name, x, z, fail, pattern=None):
"""
Return a string for making a kernel call.
The return value looks something like:
.. code-block:: c
if (verbose)
printf("running kernel_reduce_10_%(name)s\\n");
int n_shared = sizeof(float) * n_threads.x * n_threads.y * n_threads.z;
kernel_reduce_10_%(name)s<<<n_blocks, n_threads,
n_shared>>>(
CudaNdarray_HOST_DIMS(%(x)s)[0],
CudaNdarray_HOST_DIMS(%(x)s)[1],
CudaNdarray_DEV_DATA(%(x)s),
CudaNdarray_HOST_STRIDES(%(x)s)[0],
CudaNdarray_HOST_STRIDES(%(x)s)[1],
CudaNdarray_DEV_DATA(%(z)s),
CudaNdarray_HOST_STRIDES(%(z)s)[0]
);
CNDA_THREAD_SYNC;
if (cudaSuccess != cudaGetLastError())
{
PyErr_Format(PyExc_RuntimeError, "Cuda error: ... );
%(fail)s;
}
"""
sio = StringIO()
if pattern is None:
pattern = ''.join(str(c) for c in self.reduce_mask)
ndim = len(self.reduce_mask)
nd_out = ndim - sum(self.reduce_mask)
shapes_format = "shape=(%s)" % ",".join(["%d"] * node.inputs[0].ndim)
shapes_data = ",".join("CudaNdarray_HOST_DIMS(%s)[%d]" % (x, i)
for i in xrange(node.inputs[0].ndim))
print("""
if (verbose)
printf("running kernel_reduce_%(pattern)s_%(name)s\\n");
int n_shared = sizeof(float) * n_threads.x * n_threads.y * n_threads.z;
if (verbose>1)
printf("n_threads.x=%%d, n_threads.y=%%d, n_threads.z=%%d,"
" nb_threads=%%d, n_blocks.x=%%d, n_blocks.y=%%d,"
" nb_block=%%d, n_shared=%%d, %(shapes_format)s\\n",
n_threads.x,n_threads.y,n_threads.z,
n_threads.x*n_threads.y*n_threads.z,
n_blocks.x,n_blocks.y,
n_blocks.x*n_blocks.y, n_shared, %(shapes_data)s);
kernel_reduce_%(pattern)s_%(name)s<<<n_blocks, n_threads, n_shared>>>(
""" % locals(), file=sio)
for i in xrange(ndim):
print("""
CudaNdarray_HOST_DIMS(%(x)s)[%(i)s],
""" % locals(), file=sio)
print("""
CudaNdarray_DEV_DATA(%(x)s)
""" % locals(), file=sio)
for i in xrange(ndim):
print("""
,CudaNdarray_HOST_STRIDES(%(x)s)[%(i)s]
""" % locals(), file=sio)
print("""
,CudaNdarray_DEV_DATA(%(z)s)
""" % locals(), file=sio)
for i in xrange(nd_out):
print("""
,CudaNdarray_HOST_STRIDES(%(z)s)[%(i)s]
""" % locals(), file=sio)
print("""
);
CNDA_THREAD_SYNC;
cudaError_t sts = cudaGetLastError();
if (cudaSuccess != sts)
{
PyErr_Format(PyExc_RuntimeError,
"Cuda error: %%s: %%s."
" (grid: %%i x %%i; block: %%i x %%i x %%i)"
" %(shapes_format)s \\n",
"kernel_reduce_%(pattern)s_%(name)s",
cudaGetErrorString(sts),
n_blocks.x,
n_blocks.y,
n_threads.x,
n_threads.y,
n_threads.z,
%(shapes_data)s);
%(fail)s;
}
""" % locals(), file=sio)
return sio.getvalue()
def _k_decl(self, node, nodename, pattern=None,
ndim=None, reduce_mask=None):
"""
Return a string to declare a kernel function.
The result will look something like this:
.. code-block:: c
static __global__ void kernel_reduce_110_%(nodename)s(
const int d0,
const int d1,
const int d2,
const float *A,
const int sA0,
const int sA1,
const int sA2,
float * Z,
const int sZ0)
Since the nodename is unique, we don't need to put the name
of the scalar_op in here.
"""
if reduce_mask is None:
reduce_mask = self.reduce_mask
if ndim is None:
ndim = len(reduce_mask)
if pattern is None:
pattern = ''.join(str(i) for i in reduce_mask)
sio = StringIO()
print("""
static __global__ void kernel_reduce_%(pattern)s_%(nodename)s(
""" % locals(), file=sio)
for i in xrange(ndim):
print("""
const int d%(i)s,
""" % locals(), file=sio)
print("""
const float *A,
""" % locals(), file=sio)
for i in xrange(ndim):
print("""
const int sA%(i)s,
""" % locals(), file=sio)
print("""
float * Z
""" % locals(), file=sio)
for i in xrange(ndim - sum(reduce_mask)):
print("""
, const int sZ%(i)s
""" % locals(), file=sio)
print(")", file=sio)
return sio.getvalue()
def _k_init(self, *args):
return """
const int threadCount = blockDim.x * blockDim.y * blockDim.z;
const int threadNum = threadIdx.z * blockDim.x * blockDim.y
+ threadIdx.y * blockDim.x + threadIdx.x;
extern __shared__ float buf[];
float myresult = 0.0f;
//This is caught in cuda/init.py when we init the gpu. I keep
//it here to ease finding code that rely on this.
if (warpSize != 32)
{
Z[0] = -666;
return;
}
"""
def _assign_init(self, first_item):
"""
This return the initial value for myresult.
If the scalar op have an identity value, return it.
Otherwise, check that the scalar op is maximum or minimum
and return first_item. It should be the first element of the reduction.
As the maximum and minimum of the same value don't change, this work.
"""
if hasattr(self.scalar_op, 'identity'):
return str(self.scalar_op.identity)
else:
assert isinstance(self.scalar_op, (scal.Maximum,
scal.Minimum))
if self.pre_scalar_op:
#dtype = node.inputs[0].dtype
dtype = 'float32'
dummy_var = scal.Scalar(dtype=dtype)()
dummy_node = self.pre_scalar_op.make_node(dummy_var)
dummy_name = 'assign_init_pre_scalar_op' + str(self._n_scalar_op_calls)
self._n_scalar_op_calls += 1
t = self.pre_scalar_op.c_code(dummy_node, dummy_name,
(first_item,), ("",), {})
assert t.startswith(' = ')
first_item = t[3:]
if first_item[-1] == ';':
first_item = first_item[:-1]
return first_item
def _assign_reduce(self, node, name, left, right, sub, pre):
"""
Parameters
----------