/
basic_ops.py
1703 lines (1436 loc) · 57.2 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 absolute_import, print_function, division
import os
import copy
import re
import numpy as np
import theano
from theano import Op, Apply, Type, Variable
from theano import tensor, config
from theano.gradient import grad_undefined
from theano.scalar import (bool as bool_t,
int32 as int32_t)
from theano.tensor.basic import (
Alloc, AllocEmpty, alloc_validate_shape, Join, Split)
from theano.gof import HideC, COp, ParamsType
from theano.gof.utils import MethodNotDefined
from theano.gof.opt import copy_stack_trace
from collections import deque
from six import string_types
from six.moves import xrange
from six import iteritems
try:
import pygpu
from pygpu import gpuarray
except ImportError:
pass
from .type import (GpuArrayType, GpuArrayConstant, gpu_context_type,
get_context, ContextNotDefined)
from .fp16_help import write_w
def as_gpuarray_variable(x, context_name):
"""
This will attempt to convert `x` into a variable on the GPU.
It can take either a value of another variable. If `x` is already
suitable, it will be returned as-is.
Parameters
----------
x
Object to convert
context_name : str or None
target context name for the result
"""
# If this is already some form of variable, try to avoid an extra transfer
if isinstance(x, Variable):
while True:
# If we are already a GpuArrayVariable in the right context
# then there is nothing to do.
if (isinstance(x.type, GpuArrayType) and
x.type.context_name == context_name):
return x
# If x is the result of a transfer, try to dig through.
if getattr(x, 'owner', None):
if isinstance(x.owner.op, HostFromGpu):
x = x.owner.inputs[0]
continue
if isinstance(x.owner.op, GpuFromHost):
x = x.owner.inputs[0]
continue
if isinstance(x.owner.op, GpuToGpu):
x = x.owner.inputs[0]
continue
# If none of the conditions where met, then continue with
# the rest of the body
break
# If we couldn't deal with transfers, then maybe it's a tensor
if isinstance(x.type, tensor.TensorType):
return copy_stack_trace(x, GpuFromHost(context_name)(x))
# Try _as_GpuArrayVariable if possible
if hasattr(x, '_as_GpuArrayVariable'):
return copy_stack_trace(x, x._as_GpuArrayVariable(context_name))
# If it didn't work try for a constant
ctx = get_context(context_name)
if isinstance(x, gpuarray.GpuArray):
if x.context.ptr != ctx.ptr:
x = x.transfer(ctx)
x = gpuarray.asarray(x, context=ctx)
bcast = [(s == 1) for s in x.shape]
return GpuArrayConstant(GpuArrayType(dtype=x.dtype,
broadcastable=bcast,
context_name=context_name),
x)
def infer_context_name(*vars):
"""
Infer the context name to use from the inputs given
"""
# We try to infer the closest context first
# TODO: What to do in case of context conflicts?
# We currently use a first found wins approach.
todo = deque()
todo.extendleft(vars)
while todo:
v = todo.pop()
if isinstance(v.type, GpuArrayType):
return v.type.context_name
if hasattr(v.tag, 'context_name'):
return v.tag.context_name
if v.owner:
if isinstance(v.owner.op, HostFromGpu):
return v.owner.inputs[0].type.context_name
if len(v.owner.inputs) == 1:
todo.extendleft(v.owner.inputs)
# If we can't find a context try None if it exists
try:
get_context(None)
return None
except ContextNotDefined:
raise ValueError("Could not infer context from inputs")
def gpuarray_helper_inc_dir():
return os.path.join(os.path.dirname(__file__), 'c_code')
class Kernel(object):
"""
This class groups together all the attributes of a gpu kernel.
`params` should contain the data type for each argument. Buffer
arguments should use the GpuArray class as the data type and
scalar should use their equivalent numpy dtype. For ga_size and
ga_ssize, use gpuarray.SIZE and gpuarray.SSIZE.
If the `ctypes` flags is set to `True` then it should be a C
string which represent the typecode to use.
`flags` can contain the following keys whose values are booleans:
have_double
the kernel uses double-typed variables somewhere
have_small
the kernel uses variables whose type takes less than 4
bytes somewhere
have_complex
the kernel uses complex values somewhere
have_half
the kernel uses half-floats somewhere
ctypes
the `params` list consists of C typecodes
It can also have the key `cflags` which is a string of C flag
values like this `"GA_USE_DOUBLE|GA_USE_SMALL"`.
Parameters
----------
code: str
The source code of the kernel.
params: list
list of parameter types.
name: str
the name of the kernel function in the source.
flags: dict
dictionary of flags
codevar: str
the name of the variable for the code object.
(defaults to `kcode_` + name)
objvar: str
the name of the variable for the kernel object.
(defaults to `k_` + name)
fname: str
the name of the function wrapper.
(defaults to name + `_call`)
sname: str
the name of the scheduled call function
(defaults to name _ `_scall`)
"""
def __init__(self, code, params, name, flags,
codevar=None, objvar=None, fname=None, sname=None):
self.code = code
self.params = params
self.name = name
self.flags = flags
if codevar is None:
codevar = 'kcode_' + name
self.codevar = codevar
if objvar is None:
objvar = 'k_' + name
self.objvar = objvar
if fname is None:
fname = name + '_call'
self.fname = fname
if sname is None:
sname = name + '_scall'
self.sname = sname
@staticmethod
def get_flags(*types):
def get_dtype(t):
if isinstance(t, string_types):
return np.dtype(t)
elif isinstance(t, Type):
return t.dtype
elif isinstance(t, Variable):
return t.type.dtype
else:
raise TypeError("can't get a dtype from %s" % (type(t),))
dtypes = [get_dtype(t) for t in types]
flags = dict()
if any(d == np.float64 for d in dtypes):
flags['have_double'] = True
if any(d.itemsize < 4 for d in dtypes):
flags['have_small'] = True
if any(d.kind == 'c' for d in dtypes):
flags['have_complex'] = True
if any(d == np.float16 for d in dtypes):
flags['have_half'] = True
return flags
def _get_c_flags(self):
res = []
if self.flags.get('cflags', '') != '':
res.append(self.flags['cflags'])
if self.flags.get('have_double', False):
res.append('GA_USE_DOUBLE')
if self.flags.get('have_small', False):
res.append('GA_USE_SMALL')
if self.flags.get('have_complex', False):
res.append('GA_USE_COMPLEX')
if self.flags.get('have_half', False):
res.append('GA_USE_HALF')
res = '|'.join(res)
if not res:
return '0'
return res
def _get_py_flags(self):
res = dict(self.flags)
cflags = res.pop('cflags', '')
for fl in cflags.split('|'):
fl = fl.strip()
if fl == 'GA_USE_DOUBLE':
res['have_double'] = True
if fl == 'GA_USE_SMALL':
res['have_small'] = True
if fl == 'GA_USE_COMPLEX':
res['have_complex'] = True
if fl == 'GA_USE_HALF':
res['have_half'] = True
return res
def _get_c_types(self):
def m(t):
if t == gpuarray.GpuArray:
return "GA_BUFFER"
else:
return str(gpuarray.dtype_to_typecode(t))
return ', '.join(m(t) for t in self.params)
def get_ctype(dtype):
if dtype is gpuarray.GpuArray:
return "gpudata *"
elif isinstance(dtype, np.dtype):
return 'npy_' + dtype.name
elif dtype == gpuarray.SIZE:
return "size_t"
elif dtype == gpuarray.SSIZE:
return "ssize_t"
else:
dtype = np.dtype(dtype)
return 'npy_' + dtype.name
class GpuKernelBase(object):
"""
Base class for operations that need to compile kernels.
It is not mandatory to use this class, but it helps with a lot of
the small things that you have to pay attention to.
"""
params_type = gpu_context_type
def get_params(self, node):
# Default implementation, suitable for most sub-classes.
# To be necessarly overridden in a subclass that uses a ParamsType.
assert (self.params_type is gpu_context_type and
node.inputs and
isinstance(node.inputs[0].type, GpuArrayType))
return node.inputs[0].type.context
def get_gpu_context(self, node):
# Private method used to retrieve GPU context, instead of
# directly using self.get_params(node), as this latter may be overridden.
if isinstance(self.params_type, ParamsType) and self.params_type.has_type(gpu_context_type):
# Get field name of gpu_context_type into ParamsType object.
gpu_context_field = self.params_type.get_field(gpu_context_type)
# Get Params object (self.get_params() should have been overridden).
wrap = self.get_params(node)
# Get GPU context from Params object.
return getattr(wrap, gpu_context_field)
assert self.params_type is gpu_context_type
return self.get_params(node)
def get_gpu_context_c_name(self, params_c_name):
# Private method used to retrieve C name of GPU context variable,
# instead of directly using sub['params'], as params may not be a GPU context
# (e.g. for sub-classes that use ParamsType).
if isinstance(self.params_type, ParamsType) and self.params_type.has_type(gpu_context_type):
return "(%s->%s)" % (params_c_name, self.params_type.get_field(gpu_context_type))
assert self.params_type is gpu_context_type
return params_c_name
def gpu_kernels(self, node, name):
"""
This is the method to override. This should return an iterable
of Kernel objects that describe the kernels this op will need.
"""
raise MethodNotDefined('gpu_kernels')
def c_headers(self):
try:
o = super(GpuKernelBase, self).c_headers()
except MethodNotDefined:
o = []
return o + ['gpuarray/types.h', 'numpy/npy_common.h']
def c_header_dirs(self):
try:
o = super(GpuKernelBase, self).c_header_dirs()
except MethodNotDefined:
o = []
# We rely on the input types for the directory to gpuarray includes
return o + [np.get_include()]
def _generate_kernel_code(self, k):
code = '\\n'.join(l for l in k.code.split('\n'))
code = code.replace('"', '\\"')
return ("""static const char *%(cname)s_unsigned = "%(code)s";
static const char *%(cname)s = (char *)%(cname)s_unsigned;
""" %
dict(cname=k.codevar, code=code))
def _generate_kernel_vars(self, k):
return """GpuKernel %(kname)s;""" % dict(kname=k.objvar)
def _generate_kernel_wrap(self, k):
args = []
setargs = []
for i, p in enumerate(k.params):
args.append("{} arg{}".format(get_ctype(p), i))
if p is gpuarray.GpuArray:
setarg = "GpuKernel_setarg(&{0}, {1}, arg{1});"
else:
setarg = "GpuKernel_setarg(&{0}, {1}, &arg{1});"
setargs.append(setarg.format(k.objvar, i))
args = ', '.join(args)
setargs = '\n '.join(setargs)
return """
int {fname}(unsigned int _nd, size_t *_gdim, size_t *_ldim, size_t _shared,
{args}) {{
{setargs}
return GpuKernel_call(&{kname}, _nd, _gdim, _ldim, _shared, NULL);
}}
int {sname}(unsigned int _nd, size_t *_n, size_t _shared, {args}) {{
size_t _gs = 0;
size_t _ls = 0;
int _err;
if (_nd != 1) return GA_UNSUPPORTED_ERROR;
_err = GpuKernel_sched(&{kname}, _n[0], &_gs, &_ls);
if (_err != GA_NO_ERROR)
return _err;
{setargs}
return GpuKernel_call(&{kname}, 1, &_gs, &_ls, _shared, NULL);
}}
""".format(args=args, fname=k.fname, setargs=setargs, sname=k.sname,
kname=k.objvar)
def c_support_code_apply(self, node, name):
kernels = self.gpu_kernels(node, name)
codes = '\n'.join(self._generate_kernel_code(k) for k in kernels)
return codes
def c_support_code_struct(self, node, name):
kernels = self.gpu_kernels(node, name)
kvars = '\n'.join(self._generate_kernel_vars(k) for k in kernels)
wrappers = '\n'.join(self._generate_kernel_wrap(k) for k in kernels)
return kvars + '\n' + wrappers
def _generate_zeros(self, k):
return """memset(&%(v)s, 0, sizeof(%(v)s));""" % dict(v=k.objvar)
def _generate_kernel_init(self, k, fail, ctx):
return """{
int err;
int types[%(numargs)u] = {%(types)s};
if ((err = GpuKernel_init(&%(ovar)s, %(ctx)s->ctx, 1,
&%(cname)s, NULL, "%(kname)s", %(numargs)u,
types, %(flags)s, NULL)) != GA_NO_ERROR) {
PyErr_Format(PyExc_RuntimeError, "GpuKernel_init error %%d: %%s",
err, gpucontext_error(%(ctx)s->ctx, err));
%(fail)s
}
}""" % dict(numargs=len(k.params), types=k._get_c_types(),
ovar=k.objvar, kname=k.name, cname=k.codevar,
flags=k._get_c_flags(), fail=fail, ctx=ctx)
def c_init_code_struct(self, node, name, sub):
ctx = self.get_gpu_context_c_name(sub['params'])
kernels = self.gpu_kernels(node, name)
inits_0 = '\n'.join(self._generate_zeros(k) for k in kernels)
inits = '\n'.join(self._generate_kernel_init(k, sub['fail'], ctx)
for k in kernels)
return '\n'.join([inits_0, inits])
def _generate_kernel_cleanup(self, k):
return "GpuKernel_clear(&%(ovar)s);" % dict(ovar=k.objvar)
def c_cleanup_code_struct(self, node, name):
kernels = self.gpu_kernels(node, name)
cleanups = '\n'.join(self._generate_kernel_cleanup(k) for k in kernels)
return cleanups
# This is a shorthand for if your op only has a fixed version
# You can reimplement it, but make sure to call kernel_version()
def c_code_cache_version_apply(self, node):
v = self.c_code_cache_version()
if not v:
return ()
return (v, self.kernel_version(node))
def kernel_version(self, node):
"""
If you override :meth:`c_code_cache_version_apply`, call this
method to have the version of the kernel support code.
Parameters
----------
node : apply node
The node that we need the cache version for.
"""
return (9,)
def forward_string_meth(name):
def f(*args):
res = getattr(GpuKernelBase, name)(*args)
try:
res = res + '\n' + getattr(COp, name)(*args)
except MethodNotDefined:
pass
return res
f.__name__ = name
return f
def get_dtype(s):
if s == '*':
return gpuarray.GpuArray
if s == 'size':
return gpuarray.SIZE
if s == 'ssize':
return gpuarray.SSIZE
else:
return np.dtype(s)
class CGpuKernelBase(COp, GpuKernelBase):
"""
Class to combine GpuKernelBase and COp.
It adds a new section type 'kernels' where you can define kernels
with the '#kernel' tag
"""
SECTIONS = copy.copy(COp.SECTIONS)
SECTIONS.add('kernels')
kernel_re = re.compile(r'^#kernel ([a-zA-Z_].*?)$', re.MULTILINE)
get_params = GpuKernelBase.get_params
c_support_code_apply = forward_string_meth('c_support_code_apply')
c_support_code_struct = forward_string_meth('c_support_code_struct')
c_init_code_struct = forward_string_meth('c_init_code_struct')
c_cleanup_code_struct = forward_string_meth('c_cleanup_code_struct')
def c_code_cache_version_apply(self, node):
return GpuKernelBase.c_code_cache_version_apply(self, node)
def _type_macros(self, node):
define_template = "#define %s %s\n"
undef_template = "#undef %s\n"
define_macros = []
undef_macros = []
for i, v in enumerate(node.inputs):
if isinstance(v.type, GpuArrayType):
macro_name = "DTYPE_INPUT_%d" % (i,)
macro_value = pygpu.gpuarray.dtype_to_ctype(v.dtype)
define_macros.append(
define_template %
(macro_name, macro_value))
undef_macros.append(undef_template % macro_name)
for i, v in enumerate(node.outputs):
if isinstance(v.type, GpuArrayType):
macro_name = "DTYPE_OUTPUT_%d" % (i,)
macro_value = pygpu.gpuarray.dtype_to_ctype(v.dtype)
define_macros.append(
define_template %
(macro_name, macro_value))
undef_macros.append(undef_template % macro_name)
return ''.join(define_macros), ''.join(undef_macros)
def gpu_kernels(self, node, name):
if hasattr(self, '_cached_kernels'):
return self._cached_kernels
if 'kernels' in self.code_sections:
code = self.code_sections['kernels']
split = self.kernel_re.split(code)
if split[0].strip() != '':
raise ValueError("Stray code in kernels section before the "
"first #kernel statement.")
def_macros, undef_macros = self._type_macros(node)
n = 1
res = []
while n < len(split):
kspec = split[n]
kcode = split[n + 1]
splt2 = kspec.split(':')
if len(splt2) != 3:
raise ValueError("Bad kernel spec: %s" % (kspec,))
kname = splt2[0].strip()
ktypes = [get_dtype(s.strip()) for s in splt2[1].split(',')]
kflags = splt2[2].strip()
kcode = def_macros + '\n' + kcode + '\n' + undef_macros
res.append(Kernel(kcode, ktypes, kname,
flags=dict(cflags=kflags)))
n += 2
self._cached_kernels = res
return res
else:
return GpuKernelBase.gpu_kernels(self, node, name)
class HostFromGpu(Op):
"""
Transfer data to CPU.
"""
__props__ = ()
_f16_ok = True
def __str__(self):
return 'HostFromGpu(gpuarray)'
def make_node(self, x):
if not isinstance(x.type, GpuArrayType):
raise TypeError(x)
return Apply(self, [x],
[tensor.TensorType(dtype=x.dtype,
broadcastable=x.broadcastable)()])
def perform(self, node, inp, out):
x, = inp
z, = out
z[0] = np.asarray(x)
def c_code(self, node, name, inputs, outputs, sub):
return """
GpuArray %(name)s_ga_s;
GpuArray *%(name)s_ga = NULL;
int %(name)serr;
PyArray_Descr *%(name)s_dtype;
if (!GpuArray_ISONESEGMENT(&%(inp)s->ga)) {
if (GpuArray_copy(&%(name)s_ga_s, &%(inp)s->ga, GA_C_ORDER) != GA_NO_ERROR) {
PyErr_SetString(PyExc_RuntimeError, "Can't make contiguous copy");
%(fail)s;
}
%(name)s_ga = &%(name)s_ga_s;
} else {
%(name)s_ga = &%(inp)s->ga;
}
%(name)s_dtype = typecode_to_dtype(%(name)s_ga->typecode);
Py_XDECREF(%(out)s);
// PyArray_Empty below steals a reference to the dtype we pass it
// so we need an extra one to spare.
Py_INCREF(%(name)s_dtype);
%(out)s = (PyArrayObject *)PyArray_Empty(%(inp)s->ga.nd,
(npy_intp *)%(inp)s->ga.dimensions,
%(name)s_dtype,
(%(inp)s->ga.flags & GA_F_CONTIGUOUS) &&
!(%(inp)s->ga.flags & GA_C_CONTIGUOUS));
if (%(out)s == NULL) {
if (%(name)s_ga == &%(name)s_ga_s) GpuArray_clear(%(name)s_ga);
%(fail)s
}
Py_BEGIN_ALLOW_THREADS
%(name)serr = GpuArray_read(PyArray_DATA(%(out)s),
PyArray_NBYTES(%(out)s),
%(name)s_ga);
Py_END_ALLOW_THREADS
if (%(name)s_ga == &%(name)s_ga_s) GpuArray_clear(%(name)s_ga);
if (%(name)serr != GA_NO_ERROR) {
PyErr_SetString(PyExc_RuntimeError, "Could not read device data.");
%(fail)s
}
""" % {'name': name, 'fail': sub['fail'], 'inp': inputs[0],
'out': outputs[0]}
def c_code_cache_version(self):
return (2,)
def grad(self, inputs, grads):
gz, = grads
return [GpuFromHost(inputs[0].type.context_name)(gz)]
def R_op(self, inputs, eval_points):
ev, = eval_points
return [self(ev)]
def infer_shape(self, node, xshp):
return xshp
host_from_gpu = HostFromGpu()
class GpuFromHost(Op):
"""
Transfer data to GPU.
"""
__props__ = ('context_name',)
_f16_ok = True
params_type = gpu_context_type
def __init__(self, context_name):
self.context_name = context_name
def __str__(self):
return 'GpuFromHost<%s>' % (self.context_name,)
def make_node(self, x):
if not isinstance(x.type, tensor.TensorType):
raise TypeError(x)
if "complex" in x.dtype:
raise TypeError("complex not supported in the new gpuarray back-end.", x)
return Apply(self, [x], [GpuArrayType(broadcastable=x.broadcastable,
context_name=self.context_name,
dtype=x.dtype)()])
def get_params(self, node):
return get_context(self.context_name)
def perform(self, node, inp, out, ctx):
x, = inp
z, = out
z[0] = gpuarray.array(x, context=ctx)
def grad(self, inputs, grads):
gz, = grads
return [as_gpuarray_variable(
gz, context_name=self.context_name).transfer('cpu')]
def R_op(self, inputs, eval_points):
ev, = eval_points
return [self(ev)]
def infer_shape(self, node, xshp):
return xshp
def c_headers(self):
return ["gpuarray_helper.h"]
def c_header_dirs(self):
return [gpuarray_helper_inc_dir()]
def c_code(self, node, name, inputs, outputs, sub):
return """
PyArrayObject *%(name)s_tmp;
%(name)s_tmp = PyArray_GETCONTIGUOUS(%(inp)s);
int err;
if (%(name)s_tmp == NULL)
%(fail)s
if (%(out)s == NULL || !GpuArray_IS_C_CONTIGUOUS(&%(out)s->ga) ||
!theano_size_check(%(out)s, PyArray_NDIM(%(name)s_tmp),
(size_t *)PyArray_DIMS(%(name)s_tmp),
get_typecode((PyObject *)PyArray_DESCR(%(name)s_tmp)))) {
Py_XDECREF(%(out)s);
%(out)s = pygpu_empty(PyArray_NDIM(%(name)s_tmp),
(size_t *)PyArray_DIMS(%(name)s_tmp),
get_typecode((PyObject *)PyArray_DESCR(%(name)s_tmp)),
GA_C_ORDER, %(ctx)s, Py_None);
if (%(out)s == NULL) {
Py_DECREF(%(name)s_tmp);
%(fail)s;
}
}
Py_BEGIN_ALLOW_THREADS
err = GpuArray_write(&%(out)s->ga, PyArray_DATA(%(name)s_tmp),
PyArray_NBYTES(%(name)s_tmp));
Py_END_ALLOW_THREADS
Py_DECREF(%(name)s_tmp);
if (err != GA_NO_ERROR) {
PyErr_Format(PyExc_RuntimeError, "Could not write data to gpu");
%(fail)s;
}
""" % {'name': name, 'inp': inputs[0], 'ctx': sub['params'],
'out': outputs[0], 'fail': sub['fail']}
def c_code_cache_version(self):
return (10,)
class GpuToGpu(Op):
"""
Transfer data between GPUs.
"""
__props__ = ('context_name',)
_f16_ok = True
params_type = gpu_context_type
def __init__(self, context_name):
self.context_name = context_name
def __str__(self):
return 'GpuToGpu<%s>' % (self.context_name,)
def make_node(self, x):
if not isinstance(x.type, GpuArrayType):
raise TypeError(x)
return Apply(self, [x], [GpuArrayType(broadcastable=x.broadcastable,
context_name=self.context_name,
dtype=x.dtype)()])
def get_params(self, node):
return get_context(self.context_name)
def perform(self, node, inp, out, ctx):
x, = inp
z, = out
z[0] = x.transfer(ctx)
def grad(self, inputs, grads):
gz, = grads
return [GpuToGpu(inputs[0].type.context_name)(gz)]
def R_op(self, inputs, eval_points):
return self(eval_points[0])
def infer_shape(self, node, xshp):
return xshp
def c_code(self, node, name, inputs, outputs, sub):
return """
Py_XDECREF(%(out)s);
%(out)s = pygpu_empty(%(inp)s->ga.nd,
%(inp)s->ga.dimensions,
%(inp)s->ga.typecode,
GpuArray_IS_C_CONTIGUOUS(&(%(inp)s->ga)) ? GA_C_ORDER:GA_F_ORDER,
%(ctx)s, Py_None);
if (%(out)s == NULL) {
%(fail)s
}
if (pygpu_transfer(%(out)s, %(inp)s)) {
%(fail)s
}
""" % {'inp': inputs[0], 'ctx': sub['params'],
'out': outputs[0], 'fail': sub['fail']}
def c_code_cache_version(self):
return (1,)
class GpuAlloc(HideC, Alloc):
"""
Allocate initialized memory on the GPU.
Parameters
----------
context_name : str
The name of the context in which to allocate memory
memset_0 : bool
It's only an optimized version. True, it means the
value is always 0, so the c code call memset as it is faster.
"""
__props__ = ('memset_0', 'context_name')
_f16_ok = True
params_type = ParamsType(context=gpu_context_type, memset_0=bool_t)
def __init__(self, context_name, memset_0=False):
self.context_name = context_name
self.memset_0 = memset_0
def get_params(self, node):
return self.params_type.get_params(context=get_context(self.context_name),
memset_0=self.memset_0)
def __str__(self):
# Hide the memset parameter when not used to prevent confusion.
if self.memset_0:
m = "{memset_0=True}"
else:
m = ""
return "%s<%s>%s" % (self.__class__.__name__, self.context_name, m)
def make_node(self, value, *shape):
value = as_gpuarray_variable(value, context_name=self.context_name)
sh, bcast = alloc_validate_shape(shape)
if value.ndim > len(sh):
TypeError("The GpuAlloc value to use has more dimensions "
"than the specified shape", value.ndim, len(sh))
otype = value.type.clone(broadcastable=bcast)
return Apply(self, [value] + sh, [otype()])
def c_headers(self):
return ['<numpy_compat.h>']
def perform(self, node, inputs, outs, params):
out, = outs
v = inputs[0]
sh = tuple(map(int, inputs[1:]))
if out[0] is None or out[0].shape != sh:
if self.memset_0:
out[0] = gpuarray.zeros(sh, dtype=v.dtype, context=params.context)
else:
out[0] = gpuarray.empty(sh, dtype=v.dtype, context=params.context)
out[0][...] = v
else:
out[0][...] = v
def c_code(self, node, name, inp, out, sub):
vv = inp[0]
ndim = len(inp[1:])
zz, = out
code = """
int i;
size_t %(name)s_shape[%(ndim)s];
""" % dict(name=name, ndim=ndim)
for i, shp_i in enumerate(inp[1:]):
code += """
%(name)s_shape[%(i)s] = ((dtype_%(shp_i)s *)PyArray_DATA(%(shp_i)s))[0];
""" % dict(name=name, i=i, shp_i=shp_i)
code += """
int need_new_out = (NULL == %(zz)s || %(zz)s->ga.nd != %(ndim)s);
if (!need_new_out)
for (i = 0; i < %(ndim)s; i++)
need_new_out |= %(zz)s->ga.dimensions[i] != %(name)s_shape[i];
if (need_new_out && (%(params)s->memset_0)) {
//pygpu_zeros can be faster then empty followed by memset.
Py_XDECREF(%(zz)s);
%(zz)s = pygpu_zeros(%(ndim)s, %(name)s_shape,
%(vv)s->ga.typecode, GA_C_ORDER,
%(params)s->context, Py_None);
if (!%(zz)s) {
%(fail)s
}
} else {
if (need_new_out) {
Py_XDECREF(%(zz)s);
%(zz)s = pygpu_empty(%(ndim)s, %(name)s_shape,
%(vv)s->ga.typecode, GA_C_ORDER,
%(params)s->context, Py_None);
if (!%(zz)s) {
%(fail)s
}
}
if (%(params)s->memset_0 && GpuArray_ISONESEGMENT(&%(zz)s->ga))
{
int err = GpuArray_memset(&%(zz)s->ga, 0);
if (err != GA_NO_ERROR)
{
PyErr_Format(PyExc_MemoryError,
"GpuAlloc: Error memsetting %%llu"
" element of device memory to 0.",
(unsigned long long)PyGpuArray_SIZE(%(zz)s));
%(fail)s;
}
}
else if (GpuArray_setarray(&%(zz)s->ga, &%(vv)s->ga) !=
GA_NO_ERROR) {
PyErr_SetString(PyExc_ValueError, "setarray failed");
%(fail)s
}
}
""" % dict(name=name, ndim=ndim, zz=zz, vv=vv, params=sub['params'],
fail=sub['fail'])
return code
def c_code_cache_version(self):
return (4,)
def do_constant_folding(self, node):
from . import subtensor, blas
for client in node.outputs[0].clients:
if client[0] == 'output':
# If the output is a constant, it will have to be deepcopied
# each time the function is called. So we do not fold.
return False
# The following ops work inplace of their input id 0.
elif (client[1] == 0 and
# Ops that will work inplace on the Alloc. So if they
# get constant_folded, they would copy the
# constant and this is less efficients.
# Not doing the constant folding could also lower
# the peak memory usage, as we the "constant" won't
# always exists.
isinstance(client[0].op,
(subtensor.GpuIncSubtensor,
subtensor.GpuAdvancedIncSubtensor1,
subtensor.GpuAdvancedIncSubtensor1_dev20,
subtensor.GpuAdvancedIncSubtensor,
blas.GpuGemm, blas.GpuGemv,
blas.GpuGer)
)):
return False
# If the clients is a transfer, we don't want to fold. We
# let the moving opt finish before deciding what to do.
elif isinstance(client[0].op, HostFromGpu):
return False
return True
class GpuAllocEmpty(HideC, AllocEmpty):
"""
Allocate uninitialized memory on the GPU.
"""
__props__ = ('dtype', 'context_name')
_f16_ok = True
params_type = ParamsType(context=gpu_context_type,
typecode=int32_t)
def __init__(self, dtype, context_name):
self.dtype = dtype
self.context_name = context_name
@property
def typecode(self):
return gpuarray.dtype_to_typecode(self.dtype)
def get_params(self, node):
return self.params_type.get_params(context=get_context(self.context_name),
typecode=self.typecode)
def make_node(self, *shape):
sh, bcast = alloc_validate_shape(shape)
output = GpuArrayType(dtype=self.dtype, broadcastable=bcast,
context_name=self.context_name)()
output.tag.values_eq_approx = tensor.type.values_eq_approx_always_true
# The outut can contain nan/inf.
output.type.filter_checks_isfinite = False
output.tag.nan_guard_mode_check = False
return Apply(self, sh, [output])
def debug_perform(self, node, inputs, out_, params):
self.perform(node, inputs, out_, params)
out_[0][0][:] = -123456789
def perform(self, node, inputs, out_, params):
out = out_[0]
sh = [int(i) for i in inputs]
if out[0] is None or out[0].shape != sh:
out[0] = pygpu.empty(sh, dtype=self.dtype, context=params.context)
# if out[0] is the right shape, we just return it
def c_headers(self):
return ['<gpuarray_helper.h>']