forked from Theano/Theano
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprofiling.py
More file actions
1430 lines (1243 loc) · 56.1 KB
/
Copy pathprofiling.py
File metadata and controls
1430 lines (1243 loc) · 56.1 KB
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
"""
ProfileStats object for runtime and memory profiling.
"""
#
# TODO: measure memory usage like ProfileMode did
# TODO: put the optimization tips into a tips section??
# TODO: add tip to use specify_shape (is specify_shape even in library doc?)
# TODO: ensure field width for string fields makes columns line up
# TODO: what to do about 'diff summary'? (ask Fred?)
#
from __future__ import absolute_import, print_function, division
__authors__ = "James Bergstra"
__reviewer__ = "Razvan Pascanu"
__copyright__ = "(c) 2011, Universite de Montreal"
__license__ = "3-clause BSD License"
__contact__ = "theano-dev <theano-dev@googlegroups.com>"
__docformat__ = "restructuredtext en"
import atexit
import copy
import os
import sys
import time
from collections import defaultdict
import numpy
import theano
from six import iteritems
from theano.gof import graph
theano_imported_time = time.time()
config = theano.config
_atexit_print_list = []
_atexit_registered = False
def _atexit_print_fn():
"""
Print ProfileStat objects in _atexit_print_list to _atexit_print_file.
"""
to_sum = []
if config.profiling.destination == 'stderr':
destination_file = sys.stderr
elif config.profiling.destination == 'stdout':
destination_file = sys.stdout
else:
destination_file = open(config.profiling.destination, 'w')
for ps in _atexit_print_list:
if ps.fct_callcount or ps.compile_time > 0:
ps.summary(file=destination_file,
n_ops_to_print=config.profiling.n_ops,
n_apply_to_print=config.profiling.n_apply)
if not isinstance(ps, ScanProfileStats):
to_sum.append(ps)
else:
# TODO print the name if there is one!
print('Skipping empty Profile')
if len(to_sum) > 1:
# Make a global profile
cum = copy.copy(to_sum[0])
msg = ("Sum of all(%d) printed profiles at exit excluding Scan op"
" profile." % len(to_sum))
cum.message = msg
for ps in to_sum[1:]:
for attr in ["compile_time", "fct_call_time", "fct_callcount",
"vm_call_time", "optimizer_time", "linker_time",
"validate_time", "import_time"]:
setattr(cum, attr, getattr(cum, attr) + getattr(ps, attr))
# merge dictonary
for attr in ["apply_time", "apply_callcount",
"apply_cimpl", "variable_shape", "variable_strides"]:
cum_attr = getattr(cum, attr)
for key, val in iteritems(getattr(ps, attr)):
assert key not in cum_attr
cum_attr[key] = val
if cum.optimizer_profile and ps.optimizer_profile:
try:
merge = cum.optimizer_profile[0].merge_profile(
cum.optimizer_profile[1],
ps.optimizer_profile[1])
assert len(merge) == len(cum.optimizer_profile[1])
cum.optimizer_profile = (cum.optimizer_profile[0], merge)
except Exception as e:
print("Got an exception while merging profile")
print(e)
cum.optimizer_profile = None
else:
cum.optimizer_profile = None
cum.summary(file=destination_file,
n_ops_to_print=config.profiling.n_ops,
n_apply_to_print=config.profiling.n_apply)
class ProfileStats(object):
"""
Object to store runtime and memory profiling information for all of
Theano's operations: compilation, optimization, execution.
Parameters
----------
atexit_print : bool
True means that this object will be printed to stderr (using .summary())
at the end of the program.
**kwargs : misc initializers
These should (but need not) match the names of the class vars declared
in this class.
"""
def reset(self):
""" Ignore previous function call"""
#self.compile_time = 0.
self.fct_call_time = 0.
self.fct_callcount = 0
self.vm_call_time = 0.
self.apply_time = {}
self.apply_callcount = {}
# self.apply_cimpl = None
#self.messge = None
#
# Note on implementation:
# Class variables are used here so that each one can be
# documented and initialized together.
# dictionary variables are initialized with None.
#
compile_time = 0.0
# Total time spent in body of orig_function,
# dominated by graph optimization and compilation of C
#
fct_call_time = 0.0
# The total time spent in Function.__call__
#
fct_callcount = 0
# Number of calls to Function.__call__
#
vm_call_time = 0.0
# Total time spent in Function.fn.__call__
#
apply_time = None
# dict from node -> float runtime
#
apply_callcount = None
# dict from node -> number of executions
#
apply_cimpl = None
# dict from node -> bool (1 if c, 0 if py)
#
message = None
# pretty string to print in summary, to identify this output
#
variable_shape = {}
# Variable -> shapes
#
variable_strides = {}
# Variable -> strides
#
optimizer_time = 0.0
# time spent optimizing graph (FunctionMaker.__init__)
validate_time = 0.0
# time spent in fgraph.validate
# This is a subset of optimizer_time that is dominated by toposort()
# when the destorymap feature is included.
linker_time = 0.0
# time spent linking graph (FunctionMaker.create)
import_time = 0.0
# time spent in importing compiled python module.
line_width = config.profiling.output_line_width
nb_nodes = -1
# The number of nodes in the graph. We need the infomartion
# separatly in case we print the profile when the function wasn't
# executed or if there is lazy operation in the graph.
optimizer_profile = None
# None or tuple (the optimizer, the profile it returned)
# param is called flag_time_thunks because most other attributes with time
# in the name are times *of* something, rather than configuration flags.
def __init__(self, atexit_print=True, flag_time_thunks=None, **kwargs):
if (hasattr(theano, 'sandbox') and
hasattr(theano.sandbox, 'cuda') and
theano.sandbox.cuda.cuda_enabled):
if os.environ.get('CUDA_LAUNCH_BLOCKING', '0') != '1':
raise Exception(
"You are running the Theano profiler with CUDA enabled."
" Theano GPU ops execution is asynchronous by default."
" So by default, the profile is useless."
" You must set the environment variable"
" CUDA_LAUNCH_BLOCKING to 1 to tell the CUDA driver to"
" synchronize the execution to get a meaningful profile.")
self.apply_callcount = {}
self.output_size = {}
self.apply_time = {}
self.apply_cimpl = {}
self.variable_shape = {}
self.variable_strides = {}
if flag_time_thunks is None:
self.flag_time_thunks = config.profiling.time_thunks
else:
self.flag_time_thunks = flag_time_thunks
self.__dict__.update(kwargs)
if atexit_print:
global _atexit_print_list
_atexit_print_list.append(self)
global _atexit_registered
if not _atexit_registered:
atexit.register(_atexit_print_fn)
_atexit_registered = True
self.ignore_first_call = theano.config.profiling.ignore_first_call
def class_time(self):
"""
dict op -> total time on thunks
"""
# timing is stored by node, we compute timing by class on demand
rval = {}
for node, t in iteritems(self.apply_time):
typ = type(node.op)
rval.setdefault(typ, 0)
rval[typ] += t
return rval
def class_callcount(self):
"""
dict op -> total number of thunk calls
"""
# timing is stored by node, we compute timing by class on demand
rval = {}
for node, count in iteritems(self.apply_callcount):
typ = type(node.op)
rval.setdefault(typ, 0)
rval[typ] += count
return rval
def class_nodes(self):
"""
dict op -> total number of nodes
"""
# timing is stored by node, we compute timing by class on demand
rval = {}
for node, count in iteritems(self.apply_callcount):
typ = type(node.op)
rval.setdefault(typ, 0)
rval[typ] += 1
return rval
def class_impl(self):
"""
dict op -> total number of nodes
"""
# timing is stored by node, we compute timing by class on demand
rval = {}
for node in self.apply_callcount:
typ = type(node.op)
if self.apply_cimpl[node]:
impl = 'C '
else:
impl = 'Py'
rval.setdefault(typ, impl)
if rval[typ] != impl and len(rval[typ]) == 2:
rval[typ] += impl
return rval
def op_time(self):
"""
dict op -> total time on thunks
"""
# timing is stored by node, we compute timing by Op on demand
rval = {}
for node, t in iteritems(self.apply_time):
rval.setdefault(node.op, 0)
rval[node.op] += t
return rval
def fill_node_total_time(self, node, total_times):
"""
node -> fill total time icluding its parents (returns nothing)
"""
# timing is stored by node, we compute total time on demand
total = self.apply_time[node]
for parent in node.get_parents():
if parent.owner in self.apply_time:
if parent.owner not in total_times:
self.fill_node_total_time(parent.owner, total_times)
total += total_times[parent.owner]
total_times[node] = total
def compute_total_times(self):
"""
dict op -> total time icluding the time for parents
"""
rval = {}
for node in self.apply_time:
if node not in rval:
self.fill_node_total_time(node, rval)
return rval
def op_callcount(self):
"""
dict op -> total number of thunk calls
"""
# timing is stored by node, we compute timing by Op on demand
rval = {}
for node, count in iteritems(self.apply_callcount):
rval.setdefault(node.op, 0)
rval[node.op] += count
return rval
def op_nodes(self):
"""
dict op -> total number of nodes
"""
# timing is stored by node, we compute timing by Op on demand
rval = {}
for node, count in iteritems(self.apply_callcount):
rval.setdefault(node.op, 0)
rval[node.op] += 1
return rval
def op_impl(self):
"""
dict op -> 'C' or 'Py' depending how the op is implemented
"""
# timing is stored by node, we compute timing by Op on demand
rval = {}
for node in self.apply_callcount:
if self.apply_cimpl[node]:
rval[node.op] = 'C '
else:
rval[node.op] = 'Py'
return rval
def summary_class(self, file=sys.stderr, N=None):
if self.apply_time:
local_time = sum(self.apply_time.values())
else:
local_time = 0
if local_time == 0:
print(('ProfileMode.summary_class: total time 0'
' (did you forget to enable counters?)'), file=file)
return
class_time = self.class_time()
class_call = self.class_callcount()
class_apply = self.class_nodes()
class_impl = self.class_impl()
if N is None:
N = len(self.class_time)
otimes = [(t * 100 / local_time,
t,
clas,
class_impl.get(clas, ' '),
class_call.get(clas, 0),
class_apply.get(clas, 0))
for clas, t in iteritems(class_time)]
otimes.sort(key=lambda t: (t[1], t[4], t[5]), reverse=True)
tot = 0
print('Class', file=file)
print('---', file=file)
hs = []
# formatting string
es = []
hs += ['<% time>']
es += [' %4.1f%% ']
hs += ['<sum %>']
es += [' %5.1f%% ']
hs += ['<apply time>']
es += [' %7.3fs ']
hs += ['<time per call>']
es += [' %8.2es ']
hs += ['<type>']
es += [' %2s ']
hs += ['<#call>']
es += ['%6d ']
hs += ['<#apply>']
es += [' %4d ']
upto_length = numpy.sum([len(x) for x in hs]) + len(hs)
maxlen = max(self.line_width - upto_length, 0)
hs += ['<Class name>']
es += ['%s']
header_str = ' '.join(hs)
format_str = ' '.join(es)
print(header_str, file=file)
for f, t, a, impl, nb_call, nb_apply in otimes[:N]:
if nb_call == 0:
assert t == 0
continue
tot += t
ftot = tot * 100 / local_time
# Remove the useless start and end of the class name:
# "<class 'theano.sandbox.cuda.blas.GpuDot22'>" ->
# "theano.sandbox.cuda.blas.GpuDot22"
class_name = str(a)[8:-2][:maxlen]
print(format_str % (f, ftot, t, t / nb_call,
impl, nb_call,
nb_apply, class_name), file=file)
# While this carries over less information, it is arranged such
# that it way more readeable that the previous output of the
# profiler
print(' ... (remaining %i Classes account for %6.2f%%(%.2fs) of '
'the runtime)' %
(max(0, len(otimes) - N),
sum(f for f, t, a, ci, nb_call, nb_op in otimes[N:]),
sum(t for f, t, a, ci, nb_call, nb_op in otimes[N:])),
file=file)
print('', file=file)
def summary_ops(self, file=sys.stderr, N=None):
if self.apply_time:
local_time = sum(self.apply_time.values())
else:
local_time = 0
if local_time == 0:
print(('ProfileMode.summary_ops: total time 0'
' (did you forget to enable counters?)'), file=file)
return
op_time = self.op_time()
op_call = self.op_callcount()
op_apply = self.op_nodes()
op_impl = self.op_impl()
otimes = [(t * 100 / local_time,
t,
op,
op_impl.get(op, ' '),
op_call.get(op, 0),
op_apply.get(op, 0))
for op, t in iteritems(op_time)]
otimes.sort(key=lambda t: (t[1], t[4], t[5]), reverse=True)
tot = 0
print('Ops', file=file)
print('---', file=file)
hs = []
# formatting string
es = []
hs += ['<% time>']
es += [' %4.1f%% ']
hs += ['<sum %>']
es += [' %5.1f%% ']
hs += ['<apply time>']
es += [' %7.3fs ']
hs += ['<time per call>']
es += [' %8.2es ']
hs += ['<type>']
es += [' %2s ']
hs += ['<#call>']
es += [' %4d ']
hs += ['<#apply>']
es += [' %4d ']
upto_length = numpy.sum([len(x) for x in hs]) + len(hs)
maxlen = max(self.line_width - upto_length, 0)
hs += ['<Op name>']
es += ['%s']
header_str = ' '.join(hs)
format_str = ' '.join(es)
print(header_str, file=file)
for f, t, a, impl, nb_call, nb_apply in otimes[:N]:
if nb_call == 0:
assert t == 0
continue
tot += t
ftot = tot * 100 / local_time
print(format_str % (f, ftot, t, t / nb_call,
impl, nb_call,
nb_apply, str(a)[:maxlen]), file=file)
# While this carries over less information, it is arranged such
# that it way more readeable that the previous output of the
# profiler
print(' ... (remaining %i Ops account for %6.2f%%(%.2fs) of '
'the runtime)' %
(max(0, len(otimes) - N),
sum(f for f, t, a, ci, nb_call, nb_op in otimes[N:]),
sum(t for f, t, a, ci, nb_call, nb_op in otimes[N:])),
file=file)
print('', file=file)
def summary_nodes(self, file=sys.stderr, N=None):
if self.apply_time:
local_time = sum(self.apply_time.values())
else:
local_time = 0
if local_time == 0:
print(('ProfileMode.summary_nodes: total time 0'
' (did you forget to enable counters?)'), file=file)
return
print('Apply', file=file)
print('------', file=file)
# headers
hs = []
# formatting string
es = []
hs += ['<% time>']
es += [' %4.1f%% ']
hs += ['<sum %>']
es += [' %5.1f%% ']
hs += ['<apply time>']
es += [' %7.3fs ']
hs += ['<time per call>']
es += [' %8.2es ']
hs += ['<#call>']
es += [' %4d ']
hs += ['<id>']
es += ['%3d']
es += ['%s', '%s']
if self.variable_shape:
hs += ['<Mflops>', '<Gflops/s>']
upto_length = numpy.sum([len(x) for x in hs]) + len(hs)
maxlen = max(self.line_width - upto_length, 0)
hs += ['<Apply name>']
es += ['%s']
header_str = ' '.join(hs)
format_str = ' '.join(es)
print(header_str, file=file)
topos = {} # Only do the topo once per fct.
atimes = []
for a, t in iteritems(self.apply_time):
if a.fgraph not in topos:
topo = a.fgraph.toposort()
topos[a.fgraph] = topo
else:
topo = topos[a.fgraph]
atimes.append((
t * 100 / local_time,
t,
a,
topo.index(a),
self.apply_callcount[a]))
del topos
atimes.sort(reverse=True, key=lambda t: (t[1], t[3]))
tot = 0
for (f, t, a, nd_id, nb_call) in atimes[:N]:
tot += t
ftot = tot * 100 / local_time
if nb_call == 0:
continue
if not self.variable_shape:
flops = ""
flops_s = ""
elif hasattr(a.op, 'flops'):
fl = a.op.flops([self.variable_shape[var]
for var in a.inputs],
[self.variable_shape[var]
for var in a.outputs])
flops = '%8.1f' % (fl / 1024. / 1024)
flops_s = '%10.1f' % (fl / 1024. / 1024 / 1024 / t)
else:
flops = " "
flops_s = " "
print(format_str % (f, ftot, t, t / nb_call, nb_call,
nd_id,
flops, flops_s,
str(a)[:maxlen]), file=file)
if not config.profile_memory:
continue
for idx, var in enumerate(a.inputs):
sh = self.variable_shape.get(var, 'no shape')
st = self.variable_strides.get(var, 'no strides')
dtype = getattr(var, 'dtype', 'no dtype')
print(" input %d: dtype=%s, shape=%s, strides=%s " % (
idx, dtype, sh, st), file=file)
for idx, var in enumerate(a.outputs):
sh = self.variable_shape.get(var, 'no shape')
st = self.variable_strides.get(var, 'no strides')
dtype = getattr(var, 'dtype', 'no dtype')
print(" output %d: dtype=%s, shape=%s, strides=%s " % (
idx, dtype, sh, st), file=file)
# Same as before, this I've sacrificied some information making
# the output more readable
print(' ... (remaining %i Apply instances account for '
'%.2f%%(%.2fs) of the runtime)' %
(max(0, len(atimes) - N),
sum(f for f, t, a, nd_id, nb_call in atimes[N:]),
sum(t for f, t, a, nd_id, nb_call in atimes[N:])), file=file)
print('', file=file)
def summary_function(self, file):
print('Function profiling', file=file)
print('==================', file=file)
print(' Message: %s' % self.message, file=file)
print(' Time in %i calls to Function.__call__: %es' % (
self.fct_callcount, self.fct_call_time), file=file)
if self.fct_call_time > 0:
print(' Time in Function.fn.__call__: %es (%.3f%%)' % (
self.vm_call_time,
100 * self.vm_call_time / self.fct_call_time), file=file)
local_time = sum(self.apply_time.values())
if local_time > 0:
print(' Time in thunks: %es (%.3f%%)' %
(local_time, 100 * local_time / self.fct_call_time),
file=file)
print(' Total compile time: %es' % self.compile_time, file=file)
print(' Number of Apply nodes: %d' % self.nb_nodes, file=file)
print(' Theano Optimizer time: %es' % self.optimizer_time,
file=file)
print(' Theano validate time: %es' % self.validate_time,
file=file)
print(' Theano Linker time (includes C, CUDA code '
'generation/compiling): %es' % self.linker_time, file=file)
print(' Import time %es' % self.import_time, file=file)
print('', file=file)
# The validation time is a subset of optimizer_time
if self.optimizer_time > 0:
assert self.validate_time < self.optimizer_time
def summary_globals(self, file):
print('Time in all call to theano.grad() %es' %
theano.gradient.grad_time, file=file)
total_time = time.time() - theano_imported_time
print('Time since theano import %.3fs' % (total_time), file=file)
def summary_memory(self, file, N=None):
fct_memory = {} # fgraph->dict(node->[outputs size])
fct_shapes = {} # fgraph->dict(node->[outputs shapes]))
var_mem = {} # varible->size in bytes; don't include input variables
node_mem = {} # node->total outputs size (only dense outputs)
for node in self.apply_callcount:
fct_memory.setdefault(node.fgraph, {})
fct_memory[node.fgraph].setdefault(node, [])
fct_shapes.setdefault(node.fgraph, {})
fct_shapes[node.fgraph].setdefault(node, [])
sum_dense = 0
for out in node.outputs:
if out in self.variable_shape:
sh = self.variable_shape[out]
if hasattr(out.type, 'get_size'):
v = out.type.get_size(sh)
sum_dense += v
else:
v = 0 # 'Unknown'
else:
v = 0 # 'Variable isnt created'
var_mem[out] = v
fct_memory[node.fgraph][node].append(v)
fct_shapes[node.fgraph][node].append(sh)
node_mem[node] = sum_dense
del v
# Find the function that used the most of that statistic
max_sum_size = 0
# statistics with the old and new order
stats = [[[0, 0, 0], [0, 0, 0], 0, 0], # old, with dmap
[[0, 0, 0], [0, 0, 0], 0, 0], # old, without dmap
[[0, 0, 0], [0, 0, 0], 0, 0], # new, with dmap
[[0, 0, 0], [0, 0, 0], 0, 0]] # new, without dmap
# track min peak memory usage
min_max_peak = 0
min_peak_time = 0
def count_running_memory(order, fgraph, nodes_mem, ignore_dmap=False):
"""
Calculate memory with specific node order.
Return a list including the following values
1. node_memory_size
Sum of the size of all variables that actually allocate
memory (excluding views, and inplace).
2. running_memory_size
The memory allocated after the current apply node.
3. running_max_memory_size
The maximum of running_memory_size during the function.
4. node_memory_saved_by_view
The sum of memory saved by returning view instead of new
allocation.
5. node_memory_saved_by_inplace
The sum of memory saved by reusing the input instead of
new allocation.
"""
from theano.sandbox.cuda import CudaNdarrayType
# Initial Mem info values [CPU, GPU]
node_memory_size = [0, 0]
running_memory_size = [0, 0]
running_max_memory_size = [0, 0]
node_memory_saved_by_view = 0
node_memory_saved_by_inplace = 0
# This take only the inputs/outputs dependencies.
dependencies = fgraph.profile.dependencies
# Initial compute_map which is used to check if a node is valid
compute_map = defaultdict(lambda: [0])
for var in fgraph.inputs:
compute_map[var][0] = 1
# two data structure used to mimic Python gc
viewed_by = {} # {var1: [vars that view var1]}
# The len of the list is the value of python ref
# count. But we use a list, not just the ref count value.
# This is more safe to help detect potential bug in the algo
for var in fgraph.variables:
viewed_by[var] = []
view_of = {} # {var1: original var viewed by var1}
# The orignal mean that we don't keep trac of all the intermediate
# relationship in the view.
for node in order:
for var in node.outputs:
compute_map[var][0] = 1
idx = 0
if ignore_dmap:
dmap = None
else:
dmap = getattr(node.op, 'destroy_map', None)
vmap = getattr(node.op, 'view_map', None)
val = nodes_mem[node]
for v in val:
# TODO check the op returned a view
if dmap and idx in dmap:
node_memory_saved_by_inplace += v
# TODO check the op returned a view
elif vmap and idx in vmap:
node_memory_saved_by_view += v
idx += 1
# Update the Python emulating dicts and add the memory
# allocated by the node
idx2 = 0
for out in node.outputs:
if isinstance(out.type, CudaNdarrayType):
cg = 1
else:
cg = 0
ins = None
if dmap and idx2 in dmap:
vidx = dmap[idx2]
assert len(vidx) == 1, ("Here we only support the "
"possibility to destroy one "
"input")
ins = node.inputs[vidx[0]]
if vmap and idx2 in vmap:
assert ins is None
vidx = vmap[idx2]
assert len(vidx) == 1, ("Here we only support the "
"possibility to view one "
"input")
ins = node.inputs[vidx[0]]
if ins is not None:
# This is needed for destroy_map in case it
# return a partial view that is destroyed. So
# the output could be different then the
# input.
assert isinstance(ins, theano.Variable)
# we keep trac of view only again the origin
origin = view_of.get(ins, ins)
view_of[out] = origin
viewed_by[origin].append(out)
else:
running_memory_size[cg] += var_mem[out]
node_memory_size[cg] += var_mem[out]
idx2 += 1
running_max_memory_size[0] = max(running_max_memory_size[0],
running_memory_size[0])
running_max_memory_size[1] = max(running_max_memory_size[1],
running_memory_size[1])
# Mimic the combination of Theano and Python gc
for ins in set(node.inputs):
assert not (ins in view_of and viewed_by[ins])
# we trac the original var, so this shouldn't happen
if isinstance(ins.type, CudaNdarrayType):
cg = 1
else:
cg = 0
if (dependencies[ins] and
ins not in fgraph.outputs and
ins.owner and
all(
compute_map[v][0]
for v in dependencies[ins])):
if ins not in view_of and not viewed_by.get(ins, []):
running_memory_size[cg] -= var_mem[ins]
elif ins in view_of:
origin = view_of[ins]
viewed_by[origin].remove(ins)
if (not viewed_by[origin] and
origin not in fgraph.inputs and
not isinstance(origin, theano.Constant)):
running_memory_size[cg] -= var_mem[origin]
else:
# ins is viewed_by something else, so its
# memory isn't freed
pass
return [node_memory_size, running_memory_size,
running_max_memory_size, node_memory_saved_by_inplace,
node_memory_saved_by_view]
def count_minimum_peak(node_list, fgraph, nodes_mem):
global mem_count, mem_bound, max_mem_count
node_list = list(node_list)
mem_count = 0
max_mem_count = 0
mem_bound = numpy.inf
# This take only the inputs/outputs dependencies.
dependencies = fgraph.profile.dependencies
done_set = set([])
done_dict = {}
# Initial compute_map which is used to check if a node is valid
compute_map = defaultdict(lambda: [0])
for var in fgraph.inputs:
compute_map[var][0] = 1
for var in node_list:
for val in var.inputs:
if isinstance(val, graph.Constant):
compute_map[val][0] = 1
# Initial executable_nodes
executable_nodes = set()
for var in fgraph.inputs:
for c, _ in var.clients:
if c != "output":
deps = c.inputs + c.destroy_dependencies
if all(compute_map[v][0] for v in deps):
executable_nodes.add(c)
def min_memory_generator(executable_nodes, viewed_by, view_of):
"""
Generate all valid node order from node_list and compute its
memory peak.
Parameters
----------
executable_nodes
Set of executable nodes.
"""
global mem_count, mem_bound, max_mem_count
for node in executable_nodes:
new_exec_nodes = executable_nodes.copy()
new_exec_nodes.remove(node)
# Check if cut path now
if max_mem_count > mem_bound:
continue
viewof_change = []
# Use to track view_of changes
viewedby_add = defaultdict(lambda: [])
viewedby_remove = defaultdict(lambda: [])
# Use to track viewed_by changes
for var in node.outputs:
compute_map[var][0] = 1
mem_created = 0
mem_freed = 0
max_storage = max_mem_count
dmap = getattr(node.op, 'destroy_map', None)
vmap = getattr(node.op, 'view_map', None)
idx = 0
# Update the Python emulating dicts and add the
# memory allocated by the node
for out in node.outputs:
ins = None
if dmap and idx in dmap:
vidx = dmap[idx]
assert len(vidx) == 1, ("Here we only support "
"the possibility to "
"destroy one input")
ins = node.inputs[vidx[0]]
if vmap and idx in vmap:
assert ins is None
vidx = vmap[idx]
assert len(vidx) == 1, ("Here we only support "
"the possibility to "
"view one input")
ins = node.inputs[vidx[0]]
if ins is not None:
# This is needed for destroy_map in case it
# return a partial view that is destroyed. So
# the output could be different then the
# input.
assert isinstance(ins, theano.Variable)
# We keep track of view only again the original
origin = view_of.get(ins, ins)
view_of[out] = origin
viewof_change.append(out)
viewed_by[origin].append(out)
viewedby_add[origin].append(out)
else:
mem_created += var_mem[out]
idx += 1
mem_count += mem_created
max_mem_count = max(max_mem_count, mem_count)
# Mimic the combination of Theano and Python gc.
for ins in node.inputs:
assert not (ins in view_of and
viewed_by[ins])
# We track of the original var, so this shouldn't
# happen
if (dependencies[ins] and
ins not in fgraph.outputs and
ins.owner and
all(
compute_map[v][0]
for v in dependencies[ins])):
if (ins not in view_of and
not viewed_by.get(ins, [])):
mem_freed += var_mem[ins]
elif ins in view_of:
origin = view_of[ins]
viewed_by[origin].remove(ins)
viewedby_remove[origin].append(ins)
if (not viewed_by[origin] and
origin not in fgraph.inputs and
not isinstance(origin,
theano.Constant)):
mem_freed += var_mem[origin]
else:
# ins is viewed_by something else, so its
# memory isn't freed
pass
mem_count -= mem_freed
done_set.add(node)
frozen_set = frozenset(done_set)
if (done_dict.get(frozen_set, max_mem_count + 1) >
max_mem_count):