-
Notifications
You must be signed in to change notification settings - Fork 2.5k
/
op.py
1568 lines (1266 loc) · 54 KB
/
op.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
"""
Defines base classes `Op`, `PureOp`, and `CLinkerOp`.
The `Op` class is the base interface for all operations
compatible with `gof`'s :doc:`graph` routines.
"""
from __future__ import absolute_import, print_function, division
import inspect
import logging
import numpy
import os
import re
import sys
import warnings
import theano
from theano import config
import theano.gof.cc
from six import itervalues
from theano.gof import graph
from theano.gof import utils
from theano.gof.cmodule import GCC_compiler
from theano.gof.fg import FunctionGraph
__authors__ = "theano-dev"
__copyright__ = "(c) 2010, Universite de Montreal"
__license__ = "3-clause BSD License"
__contact__ = "theano-dev <theano-dev@googlegroups.com>"
__docformat__ = "restructuredtext en"
_logger = logging.getLogger('theano.gof.op.Op')
class CLinkerObject(object):
"""
Standard elements of an Op or Type used with the CLinker.
"""
def c_headers(self):
"""
Optional: Return a list of header files required by code returned by
this class.
Examples
--------
return ['<iostream>', '<math.h>', '/full/path/to/header.h']
These strings will be prefixed with "#include " and inserted at the
beginning of the c source code.
Strings in this list that start neither with '<' nor '"' will be
enclosed in double-quotes.
Raises
------
MethodNotDefined
Subclass does not implement this method.
"""
raise utils.MethodNotDefined(
"c_headers", type(self), self.__class__.__name__)
def c_header_dirs(self):
"""
Optional: Return a list of header search paths required by code
returned by this class.
Examples
--------
return ['/usr/local/include', '/opt/weirdpath/src/include']
Provides search paths for headers, in addition to those in any relevant
environment variables.
Hint: for unix compilers, these are the things that get '-I' prefixed
in the compiler cmdline.
Raises
------
MethodNotDefined
Subclass does not implement this method.
"""
raise utils.MethodNotDefined(
"c_header_dirs",
type(self),
self.__class__.__name__)
def c_libraries(self):
"""
Optional: Return a list of libraries required by code returned by
this class.
Examples
--------
return ['gsl', 'gslcblas', 'm', 'fftw3', 'g2c'].
The compiler will search the directories specified by the environment
variable LD_LIBRARY_PATH in addition to any returned by `c_lib_dirs`.
Hint: for unix compilers, these are the things that get '-l' prefixed
in the compiler cmdline.
Raises
------
MethodNotDefined
Subclass does not implement this method.
"""
raise utils.MethodNotDefined(
"c_libraries", type(self), self.__class__.__name__)
def c_lib_dirs(self):
"""
Optional: Return a list of library search paths required by code
returned by this class.
Examples
--------
return ['/usr/local/lib', '/opt/weirdpath/build/libs'].
Provides search paths for libraries, in addition to those in any
relevant environment variables (e.g. LD_LIBRARY_PATH).
Hint: for unix compilers, these are the things that get '-L' prefixed
in the compiler cmdline.
Raises
------
MethodNotDefined
Subclass does not implement this method.
"""
raise utils.MethodNotDefined(
"c_lib_dirs", type(self), self.__class__.__name__)
def c_support_code(self):
"""
Optional: Return utility code for use by a `Variable` or `Op` to be
included at global scope prior to the rest of the code for this class.
QUESTION: How many times will this support code be emitted for a graph
with many instances of the same type?
Raises
------
MethodNotDefined
Subclass does not implement this method.
"""
raise utils.MethodNotDefined(
"c_support_code",
type(self),
self.__class__.__name__)
def c_code_cache_version(self):
"""
Return a tuple of integers indicating the version of this Op.
An empty tuple indicates an 'unversioned' Op that will not be cached
between processes.
The cache mechanism may erase cached modules that have been superceded
by newer versions. See `ModuleCache` for details.
See Also
--------
c_code_cache_version_apply()
"""
return ()
def c_compile_args(self):
"""
Optional: Return a list of compile args recommended to compile the
code returned by other methods in this class.
Example
-------
return ['-ffast-math']
Compiler arguments related to headers, libraries and search paths should
be provided via the functions `c_headers`, `c_libraries`,
`c_header_dirs`, and `c_lib_dirs`.
Raises
------
MethodNotDefined
Subclass does not implement this method.
"""
raise utils.MethodNotDefined(
"c_compile_args",
type(self),
self.__class__.__name__)
def c_no_compile_args(self):
"""
Optional: return a list of incompatible gcc compiler arguments.
We will remove those arguments from the command line of gcc. So if
another Op adds a compile arg in the graph that is incompatible
with this Op, the incompatible arg will not be used.
Useful for instance to remove -ffast-math.
EXAMPLE
WRITEME
Raises
------
MethodNotDefined
The subclass does not override this method.
"""
raise utils.MethodNotDefined(
"c_no_compile_args",
type(self),
self.__class__.__name__)
def c_init_code(self):
"""
Optional: return a list of code snippets to be inserted in module
initialization.
Raises
------
MethodNotDefined
The subclass does not override this method.
"""
raise utils.MethodNotDefined("c_init_code", type(self),
self.__class__.__name__)
class CLinkerOp(CLinkerObject):
"""
Interface definition for `Op` subclasses compiled by `CLinker`.
A subclass should implement WRITEME.
WRITEME: structure of automatically generated C code.
Put this in doc/code_structure.txt
"""
def c_code(self, node, name, inputs, outputs, sub):
"""
Required: return the C implementation of an Op.
Returns C code that does the computation associated to this `Op`,
given names for the inputs and outputs.
Parameters
----------
node : Apply instance
The node for which we are compiling the current c_code.
The same Op may be used in more than one node.
name : str
A name that is automatically assigned and guaranteed to be
unique.
inputs : list of strings
There is a string for each input of the function, and the
string is the name of a C variable pointing to that input.
The type of the variable depends on the declared type of
the input. There is a corresponding python variable that
can be accessed by prepending "py_" to the name in the
list.
outputs : list of strings
Each string is the name of a C variable where the Op should
store its output. The type depends on the declared type of
the output. There is a corresponding python variable that
can be accessed by prepending "py_" to the name in the
list. In some cases the outputs will be preallocated and
the value of the variable may be pre-filled. The value for
an unallocated output is type-dependent.
sub : dict of strings
Extra symbols defined in `CLinker` sub symbols (such as 'fail').
WRITEME
Raises
------
MethodNotDefined
The subclass does not override this method.
"""
raise utils.MethodNotDefined('%s.c_code' % self.__class__.__name__)
def c_code_cache_version_apply(self, node):
"""
Return a tuple of integers indicating the version of this Op.
An empty tuple indicates an 'unversioned' Op that will not be
cached between processes.
The cache mechanism may erase cached modules that have been
superceded by newer versions. See `ModuleCache` for details.
See Also
--------
c_code_cache_version()
Notes
-----
This function overrides `c_code_cache_version` unless it explicitly
calls `c_code_cache_version`. The default implementation simply
calls `c_code_cache_version` and ignores the `node` argument.
"""
return self.c_code_cache_version()
def c_code_cleanup(self, node, name, inputs, outputs, sub):
"""
Optional: return C code to run after c_code, whether it failed or not.
This is a convenient place to clean up things allocated by c_code().
Parameters
----------
node : Apply instance
WRITEME
name : str
A name that is automatically assigned and guaranteed to be
unique.
inputs : list of strings
There is a string for each input of the function, and the
string is the name of a C variable pointing to that input.
The type of the variable depends on the declared type of
the input. There is a corresponding python variable that
can be accessed by prepending "py_" to the name in the
list.
outputs : list of strings
Each string is the name of a C variable correspoinding to
one of the outputs of the Op. The type depends on the
declared type of the output. There is a corresponding
python variable that can be accessed by prepending "py_" to
the name in the list.
sub : dict of strings
extra symbols defined in `CLinker` sub symbols (such as 'fail').
WRITEME
Raises
------
MethodNotDefined
The subclass does not override this method.
"""
raise utils.MethodNotDefined('%s.c_code_cleanup' %
self.__class__.__name__)
def c_support_code_apply(self, node, name):
"""
Optional: return utility code for use by an `Op` that will be
inserted at global scope, that can be specialized for the
support of a particular `Apply` node.
Parameters
----------
node: an Apply instance in the graph being compiled
name: str
A string or number that serves to uniquely identify this node.
Symbol names defined by this support code should include the name,
so that they can be called from the c_code, and so that they do not
cause name collisions.
Notes
-----
This function is called in addition to c_support_code and will
supplement whatever is returned from there.
Raises
------
MethodNotDefined
Subclass does not implement this method.
"""
raise utils.MethodNotDefined("c_support_code_apply",
type(self), self.__class__.__name__)
def c_init_code_apply(self, node, name):
"""
Optional: return a code string specific to the apply
to be inserted in the module initialization code.
Parameters
----------
node : an Apply instance in the graph being compiled
name : str
A string or number that serves to uniquely identify this node.
Symbol names defined by this support code should include the name,
so that they can be called from the c_code, and so that they do not
cause name collisions.
Notes
-----
This function is called in addition to c_init_code and will supplement
whatever is returned from there.
Raises
------
MethodNotDefined
The subclass does not override this method.
"""
raise utils.MethodNotDefined("c_init_code_apply", type(self),
self.__class__.__name__)
def c_init_code_struct(self, node, name, sub):
"""
Optional: return a code string specific to the apply
to be inserted in the struct initialization code.
Parameters
----------
node : an Apply instance in the graph being compiled
name : str
A unique name to distinguish variables from those of other nodes.
sub
A dictionary of values to substitute in the code.
Most notably it contains a 'fail' entry that you should place in
your code after setting a python exception to indicate an error.
Raises
------
MethodNotDefined
The subclass does not override this method.
"""
raise utils.MethodNotDefined("c_init_code_apply", type(self),
self.__class__.__name__)
def c_support_code_struct(self, node, name):
"""
Optional: return utility code for use by an `Op` that will be
inserted at struct scope, that can be specialized for the
support of a particular `Apply` node.
Parameters
----------
node : an Apply instance in the graph being compiled
name : str
A unique name to distinguish you variables from those of other
nodes.
Raises
------
MethodNotDefined
Subclass does not implement this method.
"""
raise utils.MethodNotDefined("c_support_code_struct",
type(self), self.__class__.__name__)
def c_cleanup_code_struct(self, node, name):
"""
Optional: return a code string specific to the apply to be
inserted in the struct cleanup code.
Parameters
----------
node : an Apply instance in the graph being compiled
name : str
A unique name to distinguish variables from those of other nodes.
Raises
------
MethodNotDefined
The subclass does not override this method.
"""
raise utils.MethodNotDefined("c_cleanup_code_struct", type(self),
self.__class__.__name__)
class PureOp(object):
"""
An :term:`Op` is a type of operation.
`Op` is an abstract class that documents the interface for theano's data
transformations. It has many subclasses, such as
`sparse dot <http://pylearn.org/epydoc/theano.sparse.Dot-class.html>`__,
and `Shape <http://pylearn.org/epydoc/theano.tensor.Shape-class.html>`__.
These subclasses are meant to be instantiated.
An instance has several responsabilities:
- making `Apply` instances, which mean "apply this type of operation to some
particular inputs" (via `make_node`),
- performing the calculation of outputs from given inputs
(via the `perform`),
- [optionally] building gradient-calculating graphs (via `grad`).
To see how `Op`, `Type`, `Variable`, and `Apply` fit together see the page
on :doc:`graph`.
For more specifications on how these methods should behave: see the
`Op Contract` in the sphinx docs (advanced tutorial on Op-making).
"""
default_output = None
"""
Configuration variable for `__call__`.
A subclass should not change this class variable, but instead over-ride it with a subclass
variable or an instance variable.
"""
#############
# make_node #
#############
def make_node(self, *inputs):
"""
Required: return an Apply instance representing the
application of this Op to the provided inputs.
"""
raise utils.MethodNotDefined(
"make_node", type(self), self.__class__.__name__)
@classmethod
def _get_test_value(cls, v):
"""
Extract test value from variable v.
Raises AttributeError if there is none.
For a Constant, the test value is v.value.
For a Shared variable, it is the internal value.
For another Variable, it is the content of v.tag.test_value.
"""
# avoid circular import
from theano.compile.sharedvalue import SharedVariable
if isinstance(v, graph.Constant):
return v.value
elif isinstance(v, SharedVariable):
return v.get_value(borrow=True, return_internal_type=True)
elif isinstance(v, graph.Variable) and hasattr(v.tag, 'test_value'):
# ensure that the test value is correct
try:
ret = v.type.filter(v.tag.test_value)
except Exception as e:
# Better error message.
detailed_err_msg = (
"For compute_test_value, one input test value does not"
" have the requested type.\n")
detailed_err_msg += utils.get_variable_trace_string(v)
detailed_err_msg += (
"\nThe error when converting the test value to that"
" variable type:")
# We need to only have 1 args and it should be of type
# string. Otherwise, it print the tuple and so the
# new line do not get printed.
args = (detailed_err_msg,) + tuple(str(arg) for arg in e.args)
e.args = ("\n".join(args),)
raise
return ret
detailed_err_msg = utils.get_variable_trace_string(v)
raise AttributeError('%s has no test value %s' % (v, detailed_err_msg))
def __call__(self, *inputs, **kwargs):
"""
Optional: return some or all output[s] of `make_node`.
It is called by code such as:
.. python::
x = tensor.matrix()
# tensor.exp is an Op instance, calls
# Op.__call__(self=<instance of exp>, inputs=(x,))
y = tensor.exp(x)
This class implements a convenience function (for graph-building) which
uses `default_output`, but subclasses are free to override this function
and ignore `default_output`.
Parameters
----------
inputs
The Op's inputs, forwarded to the call to `make_node()`.
kwargs
Additional keyword arguments to be forwarded to
`make_node()` *except* for optional argument `return_list` (which
defaults to False). If `return_list` is True, then the returned
value is always a list. Otherwise it is either a single Variable
when the output of `make_node()` contains a single element, or this
output (unchanged) when it contains multiple elements.
"""
return_list = kwargs.pop('return_list', False)
node = self.make_node(*inputs, **kwargs)
if config.compute_test_value != 'off':
run_perform = True
# build test input-values
storage_map = {}
compute_map = {}
for i, ins in enumerate(node.inputs):
try:
storage_map[ins] = [self._get_test_value(ins)]
compute_map[ins] = [True]
except AttributeError:
# no test-value was specified, act accordingly
if config.compute_test_value == 'warn':
warnings.warn(
'Warning, Cannot compute test value: input %i (%s) of Op %s missing default value' %
(i, ins, node), stacklevel=2)
run_perform = False
elif config.compute_test_value == 'raise':
detailed_err_msg = utils.get_variable_trace_string(ins)
raise ValueError(
'Cannot compute test value: input %i (%s) of Op %s missing default value. %s' %
(i, ins, node, detailed_err_msg))
elif config.compute_test_value == 'ignore':
# silently skip test
run_perform = False
elif config.compute_test_value == 'pdb':
import pdb
pdb.post_mortem(sys.exc_info()[2])
else:
raise ValueError(
'%s is invalid for option config.compute_Test_value' %
config.compute_test_value)
# if all inputs have test-values, run the actual op
if run_perform:
# Original values should not be destroyed:
# copy the values of the inputs in destroy_map
destroyed_inputs_idx = set()
if getattr(node.op, 'destroy_map', None):
for i_pos_list in itervalues(node.op.destroy_map):
destroyed_inputs_idx.update(i_pos_list)
for inp_idx in destroyed_inputs_idx:
inp = node.inputs[inp_idx]
storage_map[inp] = [storage_map[inp][0].copy()]
# Prepare storage_map and compute_map for the outputs
for o in node.outputs:
storage_map[o] = [None]
compute_map[o] = [False]
# compute output value once with test inputs to validate graph
thunk = node.op.make_thunk(node, storage_map, compute_map,
no_recycling=[])
thunk.inputs = [storage_map[v] for v in node.inputs]
thunk.outputs = [storage_map[v] for v in node.outputs]
required = thunk()
assert not required # We provided all inputs
for output in node.outputs:
# Check that the output has been computed
assert compute_map[output][
0], (output, storage_map[output][0])
# add 'test_value' to output tag, so that downstream ops can use these
# numerical values as inputs to their perform method.
output.tag.test_value = storage_map[output][0]
if self.default_output is not None:
rval = node.outputs[self.default_output]
if return_list:
rval = [rval]
return rval
else:
if return_list:
return list(node.outputs)
elif len(node.outputs) == 1:
return node.outputs[0]
else:
return node.outputs
def __ne__(self, other):
return not (self == other)
# Convenience so that subclass implementers don't have to import utils
# just to self.add_tag_trace
add_tag_trace = staticmethod(utils.add_tag_trace)
#########################
# Python implementation #
#########################
def L_op(self, inputs, outputs, output_grads):
return self.grad(inputs, output_grads)
def R_op(self, inputs, eval_points):
"""
This method is primarily used by tensor.Rop
Suppose the op outputs
[ f_1(inputs), ..., f_n(inputs) ]
Parameters
----------
inputs : a Variable or list of Variables
eval_points
A Variable or list of Variables with the same length as inputs.
Each element of eval_points specifies the value of the corresponding
input at the point where the R op is to be evaluated.
Returns
-------
list of n elements
rval[i] should be Rop(f=f_i(inputs),
wrt=inputs,
eval_points=eval_points)
"""
raise NotImplementedError(
"%s of class %s does not "
"implement R_op. If this is a theano op, write to the "
"theano-dev mailing list for assistance. If it is your "
"own op, implement the R_op method." %
(self, self.__class__.__name__))
def perform(self, node, inputs, output_storage, params=None):
"""
Required: Calculate the function on the inputs and put the variables in
the output storage. Return None.
Parameters
----------
node : Apply instance
Contains the symbolic inputs and outputs.
inputs : list
Sequence of inputs (immutable).
output_storage : list
List of mutable 1-element lists (do not change the length of
these lists)
Notes
-----
The `output_storage` list might contain data. If an element of
output_storage is not None, it has to be of the right type,
for instance, for a TensorVariable, it has to be a Numpy ndarray,
with the right number of dimensions, and the correct dtype.
Its shape and stride pattern, can be arbitrary. It not is
guaranteed that it was produced by a previous call to impl. It
could be allocated by another Op impl is free to reuse it as it
sees fit, or to discard it and allocate new memory.
Raises
------
MethodNotDefined
The subclass does not override this method.
"""
raise utils.MethodNotDefined(
"perform", type(self), self.__class__.__name__,
"Did you used Theano flags mode=FAST_COMPILE?"
" You can use optimizer=fast_compile instead.")
def do_constant_folding(self, node):
"""
This allows each op to determine if it wants to be constant
folded when all its inputs are constant. This allows it to
choose where it puts its memory/speed trade-off. Also, it
could make things faster as constants can't be used for inplace
operations (see *IncSubtensor).
"""
return True
class Op(utils.object2, PureOp, CLinkerOp):
"""
Convenience class to bundle `PureOp` and `CLinkerOp`.
"""
def prepare_node(self, node, storage_map, compute_map, impl):
"""
Make any special modifications that the Op needs before doing
make_thunk().
This can modify the node inplace and should return nothing.
It can be called multiple time with different impl. It is the
op responsability to don't re-prepare the node when it isn't
good to do so.
"""
pass
def make_c_thunk(self, node, storage_map, compute_map, no_recycling):
"""Like make_thunk, but will only try to make a C thunk.
"""
node_input_storage = [storage_map[r] for r in node.inputs]
node_output_storage = [storage_map[r] for r in node.outputs]
# float16 gets special treatment since running
# unprepared C code will get bad results.
if not getattr(self, '_f16_ok', False):
def is_f16(t):
return getattr(t, 'dtype', '') == 'float16'
if (any(is_f16(i.type) for i in node.inputs) or
any(is_f16(o.type) for o in node.outputs)):
print("Disabling C code for %s due to unsupported "
"float16" % (self,))
raise NotImplementedError("float16")
e = FunctionGraph(node.inputs, node.outputs)
e_no_recycling = [new_o
for (new_o, old_o) in zip(e.outputs, node.outputs)
if old_o in no_recycling]
cl = theano.gof.cc.CLinker().accept(e,
no_recycling=e_no_recycling)
_logger.debug('Trying CLinker.make_thunk')
outputs = cl.make_thunk(input_storage=node_input_storage,
output_storage=node_output_storage)
fill_storage, node_input_filters, node_output_filters = outputs
def rval():
fill_storage()
for o in node.outputs:
compute_map[o][0] = True
rval.cthunk = fill_storage.cthunk
rval.inputs = node_input_storage
rval.outputs = node_output_storage
rval.lazy = False
return rval
def make_py_thunk(self, node, storage_map, compute_map, no_recycling,
debug=False):
"""
Like make_thunk() but only makes python thunks.
"""
node_input_storage = [storage_map[r] for r in node.inputs]
node_output_storage = [storage_map[r] for r in node.outputs]
if debug:
p = node.op.debug_perform
else:
p = node.op.perform
params = node.run_params()
if params is graph.NoParams:
# default arguments are stored in the closure of `rval`
def rval(p=p, i=node_input_storage, o=node_output_storage, n=node):
r = p(n, [x[0] for x in i], o)
for o in node.outputs:
compute_map[o][0] = True
return r
else:
params_val = node.params_type.filter(params)
def rval(p=p, i=node_input_storage, o=node_output_storage, n=node,
params=params_val):
r = p(n, [x[0] for x in i], o, params)
for o in node.outputs:
compute_map[o][0] = True
return r
rval.inputs = node_input_storage
rval.outputs = node_output_storage
rval.perform = p
rval.lazy = False
return rval
def make_thunk(self, node, storage_map, compute_map, no_recycling,
impl=None):
"""
This function must return a thunk, that is a zero-arguments
function that encapsulates the computation to be performed
by this op on the arguments of the node.
Parameters
----------
node
Something previously returned by self.make_node.
storage_map
dict variable -> one-element-list where a computed
value for this variable may be found.
compute_map
dict variable -> one-element-list where a boolean
value will be found. The boolean indicates whether the
variable's storage_map container contains a valid value (True)
or if it has not been computed yet (False).
no_recycling
List of variables for which it is forbidden to reuse memory
allocated by a previous call.
impl
Currently, None, 'c' or 'py'. If 'c' or 'py' we will only try
that version of the code.
Notes
-----
If the thunk consults the storage_map on every call, it is safe
for it to ignore the no_recycling argument, because elements of the
no_recycling list will have a value of None in the storage map. If
the thunk can potentially cache return values (like CLinker does),
then it must not do so for variables in the no_recycling list.
self.prepare_node(node, ...) is always called. If we try 'c' and it
fail and we try again 'py', prepare_node will be called twice.
"""
if (impl is None and theano.config.cxx) or impl == 'c':
self.prepare_node(node, storage_map=storage_map,
compute_map=compute_map, impl='c')
try:
return self.make_c_thunk(node, storage_map, compute_map,
no_recycling)
except (NotImplementedError, utils.MethodNotDefined):
# We requested the c code, so don't catch the error.
if impl == 'c':
raise
_logger.debug('Falling back on perform')
# condition: either there was no c_code, or it failed or
# python code was requested.
self.prepare_node(node, storage_map=storage_map,
compute_map=compute_map, impl='py')
return self.make_py_thunk(node, storage_map, compute_map, no_recycling)
def make_node(self, *inputs):
"""
Create a "apply" nodes for the inputs in that order.
"""
if not hasattr(self, 'itypes'):
raise NotImplementedError("You can either define itypes and otypes,\
or implement make_node")
if not hasattr(self, 'otypes'):
raise NotImplementedError("You can either define itypes and otypes,\
or implement make_node")
if len(inputs) != len(self.itypes):
raise ValueError("We expected %d inputs but got %d." %
(len(self.itypes), len(inputs)))
if not all(inp.type == it for inp, it in zip(inputs, self.itypes)):
raise TypeError(
"We expected inputs of types '%s' but got types '%s' " %
(str(self.itypes), str([inp.type for inp in inputs])))
return theano.Apply(self, inputs, [o() for o in self.otypes])
def get_test_value(v):
"""
Extract test value from `v`. Raises AttributeError if there is none.
If input `v` is not already a variable, it is turned into one by calling
`as_tensor_variable(v)`, so that this function can be applied e.g.
on numpy arrays or Python lists and scalars, considering them as constants.
For a Constant, the test value is v.value.
For a Shared variable, it is the internal value.
For another Variable, it is the content of v.tag.test_value.
"""
if not isinstance(v, graph.Variable):
v_var = theano.tensor.as_tensor_variable(v)
else:
v_var = v
return PureOp._get_test_value(v_var)
def missing_test_message(msg):
"""
Displays msg, a message saying that some test_value is missing,
in the appropriate form based on config.compute_test_value:
off: The interactive debugger is off, so we do nothing.
ignore: The interactive debugger is set to ignore missing inputs,
so do nothing.
warn: Display msg as a warning.
Raises
------
AttributeError
With msg as the exception text.
"""
action = config.compute_test_value
if action == 'raise':
raise AttributeError(msg)
elif action == 'warn':
warnings.warn(msg, stacklevel=2)
else: