Repository navigation
Expand file tree
/
Copy pathstr-tf-patch.diff
More file actions
2476 lines (2465 loc) · 102 KB
/
Copy pathstr-tf-patch.diff
File metadata and controls
2476 lines (2465 loc) · 102 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
diff --git a/tensorflow/python/BUILD b/tensorflow/python/BUILD
index b322779e..a64a3827 100644
--- a/tensorflow/python/BUILD
+++ b/tensorflow/python/BUILD
@@ -186,6 +186,7 @@ py_library(
"//tensorflow/python/ops/parallel_for",
"//tensorflow/python/ops/ragged",
"//tensorflow/python/ops/signal",
+ "//tensorflow/python/ops/stropt",
"//tensorflow/python/profiler",
"//tensorflow/python/saved_model",
"//tensorflow/python/tools:module_util",
diff --git a/tensorflow/python/keras/engine/training.py b/tensorflow/python/keras/engine/training.py
index 907b118c..e175f926 100644
--- a/tensorflow/python/keras/engine/training.py
+++ b/tensorflow/python/keras/engine/training.py
@@ -20,6 +20,7 @@ from __future__ import print_function
import collections
import json
+from re import S
import numpy as np
from tensorflow.python import tf2
@@ -1006,19 +1007,23 @@ class Model(network.Network):
outputs = [
training_v2_utils._non_none_constant_value(v) for v in outputs] # pylint: disable=protected-access
else:
+ # logging.info("=======graph mode training batch start=======")
x = training_utils.ModelInputs(x).as_list()
ins = x + (y or []) + (sample_weights or [])
if not isinstance(K.symbolic_learning_phase(), int):
ins += [True] # Add learning phase value.
-
self._update_sample_weight_modes(sample_weights=sample_weights)
+ # logging.info("Prepare train function")
self._make_train_function()
+ # logging.info("Invoke training")
+ # logging.info(f"Computational graph size={len(self._graph.get_operations())}")
outputs = self.train_function(ins) # pylint: disable=not-callable
if reset_metrics:
self.reset_metrics()
+ # logging.info("=======graph mode training batch end=======")
if len(outputs) == 1:
return outputs[0]
return outputs
diff --git a/tensorflow/python/keras/optimizer_v2/optimizer_v2.py b/tensorflow/python/keras/optimizer_v2/optimizer_v2.py
index 6b916fc7..7ebc97ad 100644
--- a/tensorflow/python/keras/optimizer_v2/optimizer_v2.py
+++ b/tensorflow/python/keras/optimizer_v2/optimizer_v2.py
@@ -22,8 +22,11 @@ from __future__ import print_function
import abc
import functools
+from logging import info
import six
+import configparser
+import os
from tensorflow.python.distribute import distribution_strategy_context as distribute_ctx
from tensorflow.python.distribute import reduce_util as ds_reduce_util
@@ -386,7 +389,12 @@ class OptimizerV2(trackable.Trackable):
params = nest.flatten(params)
with backend.get_graph().as_default(), backend.name_scope(self._name +
"/gradients"):
- grads = gradients.gradients(loss, params)
+ from tensorflow.python.ops.stropt.str_strategy import str_gradients
+ config = configparser.ConfigParser()
+ config.read(os.environ['HOME'] + "/.str/strategy.conf")
+ grads = str_gradients(loss, params, config=config, optimizer_name=self._name)
+
+ # grads = gradients.gradients(loss, params) # vanilla
for grad, param in zip(grads, params):
if grad is None:
raise ValueError("Variable {} has `None` for gradient. "
diff --git a/tensorflow/python/keras/optimizers.py b/tensorflow/python/keras/optimizers.py
index 10ce8336..bb3d3fa4 100644
--- a/tensorflow/python/keras/optimizers.py
+++ b/tensorflow/python/keras/optimizers.py
@@ -17,6 +17,7 @@
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
+import logging
import six
from six.moves import zip # pylint: disable=redefined-builtin
diff --git a/tensorflow/python/lib/core/bfloat16.cc b/tensorflow/python/lib/core/bfloat16.cc
index 7d170113..fde3a837 100644
--- a/tensorflow/python/lib/core/bfloat16.cc
+++ b/tensorflow/python/lib/core/bfloat16.cc
@@ -490,7 +490,7 @@ bool RegisterBfloat16Cast(int numpy_type, bool cast_is_safe) {
}
template <typename InType, typename OutType, typename Functor>
-void BinaryUFunc(char** args, npy_intp const* dimensions, npy_intp const* steps,
+void BinaryUFunc(char** args, npy_intp* dimensions, npy_intp* steps,
void* data) {
const char* i0 = args[0];
const char* i1 = args[1];
@@ -506,7 +506,7 @@ void BinaryUFunc(char** args, npy_intp const* dimensions, npy_intp const* steps,
}
template <typename Functor>
-void CompareUFunc(char** args, npy_intp const* dimensions, npy_intp const* steps,
+void CompareUFunc(char** args, npy_intp* dimensions, npy_intp* steps,
void* data) {
BinaryUFunc<bfloat16, npy_bool, Functor>(args, dimensions, steps, data);
}
diff --git a/tensorflow/python/ops/stropt/BUILD b/tensorflow/python/ops/stropt/BUILD
new file mode 100644
index 00000000..774b2767
--- /dev/null
+++ b/tensorflow/python/ops/stropt/BUILD
@@ -0,0 +1,21 @@
+package(
+ default_visibility = ["//tensorflow:internal"],
+ licenses = ["notice"], # Apache 2.0
+)
+
+py_library(
+ name = "stropt",
+ srcs = [
+ "__init__.py",
+ "memory_saving_gradients.py",
+ "str_strategy.py",
+ "strategy_parser.py",
+ "lms.py",
+ "topos.py",
+ ],
+ srcs_version = "PY2AND3",
+ deps = [
+ "//tensorflow/contrib/graph_editor:graph_editor_py",
+ ]
+)
+
diff --git a/tensorflow/python/ops/stropt/__init__.py b/tensorflow/python/ops/stropt/__init__.py
new file mode 100644
index 00000000..e69de29b
diff --git a/tensorflow/python/ops/stropt/lms.py b/tensorflow/python/ops/stropt/lms.py
new file mode 100644
index 00000000..8b8da6c6
--- /dev/null
+++ b/tensorflow/python/ops/stropt/lms.py
@@ -0,0 +1,1040 @@
+# (C) Copyright IBM Corp. 2018. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+# ==============================================================================
+"""LMS
+"""
+import re
+import tensorflow as tf
+import tensorflow.contrib.graph_editor as ge
+from tensorflow.contrib.graph_editor import util
+
+import time
+from six.moves import queue as Queue
+from tensorflow.python.ops.stropt import topos
+from enum import Enum
+
+
+class CTRLD_Strategy(Enum):
+ CHAIN_RULE = 1
+ DIRECT_ORDER = 2
+
+# Operations with these types will be excluded from swapping
+ATOMIC_TYPES = {'Const', 'Mul', 'Add',
+ 'Identity', 'Assign', 'VariableV2',
+ 'Reshape', 'Shape', 'ShapeN',
+ 'Placeholder'}
+
+
+class LMS(object):
+ """LMS class for Large Model Support (LMS).
+
+ The `LMS` object statically modifies a model by swapping its tensors
+ to the host so that the model can be trained with the limited memory
+ of GPUs.
+
+ Tensors those are generated by forward operations and consumed by
+ backward operations are candidates for swapping. The `LMS` object will
+ automatically find these tensors.
+
+ Swapping is done by cutting the link between a forward operation and
+ its backward operation, then replacing the link by inserting `identity`
+ operations on the host. In theory, this procedure does not have any
+ effect on the training convergence as well as inference task.
+ """
+ def __init__(self, optimizer_scopes, graph=None,
+ starting_scope=None,
+ starting_op_names=None,
+ excl_scopes=set(),
+ incl_scopes=set(),
+ excl_types=set(),
+ incl_types=set(),
+ lb=1, ub=10000,
+ n_tensors=-1,
+ fuse_swapins=False,
+ ctrld_strategy="chain_rule",
+ swap_branches=False,
+ branch_threshold=0,
+ debug=False,
+ debug_level=1,
+ cpu_device="/cpu:0",
+ solved_strategy=None):
+ """Create an LMS object to edit the graph for supporting large model.
+
+ Args:
+ graph: the graph we will modify for LMS. This should be the graph of
+ user-defined neural network.
+ optimizer_scopes: a set of scopes for the optimizers/solvers.
+ starting_scope: tensors that are reachable from the operations in
+ this scope will be swapped for LMS. Set this to the scope of the
+ first layer if we would like to modify the whole graph.
+ starting_op_names: tensors that are reachable from the operations with
+ these names will be swapped for LMS.
+ excl_scopes: a set of scopes for operations whose tensors will not
+ be swapped out to the host. Default `empty`.
+ incl_scopes: a set of scopes for operations whose tensors will be
+ swapped out to the host. Default `empty`.
+ excl_types: a set of types for operations whose tensors will not be
+ swapped out to the host. Default `empty`.
+ incl_types: a set of types for operations whose tensors will be
+ swapped out to the host. Default `empty`.
+ n_tensors: the number of tensors for LMS, counting from the
+ `starting_scope`. To turn off LMS, set `n_tensors` to `0`.
+ Default `-1` (all reachable tensors will be swapped for LMS).
+ lb: lower-bound value for LMS. A tensor will be swapped in during the
+ backward phase at least `lb` nodes before it in the graph.
+ Default `1`.
+ ub: upper-bound value for LMS. Default `10000`.
+ fuse_swapins: Fuse "close" swap-in operations into one operation.
+ This may improve the performance. Default `False`.
+ ctrld_strategy: Two strategies to find control dependency ops for
+ swapin ops: `chain_rule` and `direct_order`. `chain_rule` strategy
+ starts from a forward operation, goes forward and finds a corresponding
+ backward operation to be a control dependency operation. `direct_order`
+ strategy directly gets a backward ops in the topological order to be
+ a control dependency operation. Both strategies depend on `lb` and `ub`
+ to choose a control dependency operation. While the `direct_order` is
+ more exact than `chain_rule` in relation to `lb` and `ub`, it experimentally
+ often results in smaller maximum batch size than `chain_rule`.
+ Default `chain_rule`.
+ swap_branches: If True, LMS will swap tensors in branches in the
+ forward phase. Default `False`.
+ branch_threshold: If `swap_branches` is enabled and the
+ topological-sort distance between the consuming operation and generating
+ operation of a tensor is greater than `branch_threshold`, then swap the
+ tensor. Default `0`.
+ debug: debug mode for LMS. Default `False`.
+ debug_level: Debug level for LMS (1 or 2). Default `1`.
+ cpu_device: the device we would like swap tensors to.
+ """
+ if not optimizer_scopes:
+ raise ValueError('A least one optimizer scope is required.')
+
+ self._graph = graph
+ self._optimizer_scopes = optimizer_scopes
+ self._excl_scopes = excl_scopes
+ self._incl_scopes = incl_scopes
+ self._excl_types = excl_types
+ self._incl_types = incl_types
+ self._starting_scope = starting_scope
+ self._starting_op_names = starting_op_names
+ self._lb = lb # lowerbound
+ self._ub = ub # upperbound
+ self._n_tensors = n_tensors
+ self._fuse_swapins = fuse_swapins
+ if ctrld_strategy == "chain_rule":
+ self._ctrld_strategy = CTRLD_Strategy.CHAIN_RULE
+ elif ctrld_strategy == "direct_order":
+ self._ctrld_strategy = CTRLD_Strategy.DIRECT_ORDER
+ else:
+ self._ctrld_strategy = CTRLD_Strategy.CHAIN_RULE
+
+ self._swap_branches = swap_branches
+ self._branch_threshold = branch_threshold
+
+ self._excl_types |= ATOMIC_TYPES
+
+ self._excl_ops = set()
+ self._incl_ops = set()
+ self._grad_ops = set()
+ self._topo_sort = None
+ self._cpu_device = cpu_device
+ self._debug = debug
+ self._debug_level = debug_level
+
+ # keep log of tensors on host
+ self._incpu_count = 0
+
+ # store a dictionary of visited ops to avoid multiple visits
+ self._ops_dict = {}
+
+ # Solved strategy of STR
+ self._ss = solved_strategy
+
+ def _build_gradient_ops(self):
+ """Return a set of operations in the backward phase.
+
+ Operations in the backward phase are determined by its scope.
+ """
+ for scope in self._optimizer_scopes:
+ ops_for_scope = set(ge.filter_ops_from_regex(
+ ge.make_list_of_op(self._graph), "^{}".format(scope)))
+ if not ops_for_scope:
+ self._log_info('No operations were found with optimizer '
+ 'scope {}.'.format(scope))
+ self._grad_ops.update(ops_for_scope)
+ if not self._grad_ops:
+ raise ValueError('No operations were found with optimizer '
+ 'scopes {}.'.format(self._optimizer_scopes))
+
+
+ def _get_seed_ops(self):
+ """Return a list of `tf.Operation` used as a starting point for LMS
+ to traverse the graph.
+
+ If a starting scope is given, the ops in this scope will be used.
+ Otherwise, this method automatically searches for starting ops.
+ """
+ # seep ops for search
+ seed_ops = set()
+ ops = ge.make_list_of_op(self._graph)
+ if self._starting_scope:
+ scope_ops = set(ge.filter_ops_from_regex(ops,
+ "^{}".format(self._starting_scope)))
+ if not scope_ops:
+ raise ValueError('No operations were found in starting '
+ 'scope {}.'.format(self._starting_scope))
+ seed_ops |= scope_ops
+
+ if self._starting_op_names:
+ for name in self._starting_op_names:
+ name_ops = set(ge.filter_ops_from_regex(ops,
+ "^{}$".format(name)))
+ if not name_ops:
+ raise ValueError('No starting operation was found with '
+ 'name {}.'.format(name))
+ seed_ops |= name_ops
+
+ seed_ops = list(seed_ops)
+ if not seed_ops:
+ candidates = set()
+ non_grad_ops = [op
+ for op in self._graph.get_operations()
+ if not (op in self._grad_ops)]
+ for op in non_grad_ops:
+ for t in op.outputs:
+ frontier_ops = set(util.get_consuming_ops(t))
+ if (frontier_ops & self._grad_ops):
+ candidates.add(op)
+ break
+
+ # ordering an operation by how much it covers the other ops
+ tmp_dict = {}
+ max_nelems = -1
+ for op in candidates:
+ nelems = len(set(ge.get_forward_walk_ops(op, within_ops=non_grad_ops,
+ inclusive=False)) &
+ candidates)
+ if nelems > 0:
+ tmp_dict[op] = nelems
+ max_nelems = nelems if (nelems > max_nelems) else max_nelems
+
+ # seed ops will cover most of the forward ops
+ seed_ops = [k for k, v in tmp_dict.items() if v == max_nelems]
+ return seed_ops
+
+ def _filter_scopes_and_types(self, within_ops, scopes, types):
+ """Return ops in within_ops that are in `scopes` or have a type
+ in `types`.
+
+ Args:
+ within_ops: an object convertible to a list of `tf.Operation`.
+ scopes: a list of scope path.
+ types: a list of tf.DataType.
+ Return:
+ A set of `tf.Operation`.
+ """
+ ret_ops = set()
+ for scope in scopes:
+ ops = set(ge.get_name_scope_ops(within_ops, scope))
+ if not ops:
+ raise ValueError('No operations were found with scope'
+ ' {}.'.format(scope))
+ ret_ops |= ops
+
+ found_types = set()
+ type_ops = set()
+ for op in within_ops:
+ if op.type in types:
+ found_types.add(op.type)
+ type_ops.add(op)
+
+ # We remove ATOMIC_TYPES from the input list of types because
+ # it is a constant and not user input. We only want to error if a
+ # user provided type is not found.
+ missing_types = types - found_types - ATOMIC_TYPES
+ if missing_types:
+ raise ValueError('No operations were found with types: '
+ ' {}.'.format(str(missing_types)))
+
+ ret_ops |= type_ops
+ return ret_ops
+
+ def _get_forward_walk_ops(self, op, inclusive=True):
+ """ A wrapper of `tensorflow.contrib.graph_editor.get_forward_walk_ops`
+ """
+ if op in self._ops_dict:
+ if inclusive:
+ return self._ops_dict[op]
+ else:
+ return list(set(self._ops_dict[op]) - {op})
+ else:
+ ret = ge.get_forward_walk_ops(op)
+ self._ops_dict[op] = ret
+ if inclusive:
+ return ret
+ else:
+ return list(set(ret) - {op})
+
+ def run(self, graph=None):
+ """Edit the graph by adding swapin and swapout ops.
+
+ Swapin and swapout ops are in the host.
+
+ The graph is modified in-place.
+
+ Return:
+ a set of added ops.
+ """
+ if graph:
+ self._graph = graph
+
+ if self._n_tensors == 0:
+ self._log_info("LMS is disabled and will not modify the model.")
+ return # turn off LMS
+ elif self._n_tensors < 0:
+ self._n_tensors = 0 # swap all tensors (default)
+
+ if not self._graph:
+ raise ValueError('The dataflow graph is required but has not been'
+ ' provided.')
+
+ self._log_info("Editing model for LMS")
+ self._print_configuration()
+ start_time = time.time()
+
+ self._build_gradient_ops()
+ seed_ops = self._get_seed_ops() # first op of this graph
+
+ self._log_info(
+ "Starting ops: {}".format(
+ [(op.name, op.type) for op in seed_ops]), 1)
+
+ reachable_ops = set()
+ for seed_op in seed_ops:
+ reachable_ops |= set(self._get_forward_walk_ops(seed_op))
+
+ for op in reachable_ops:
+ if 'lms/swap' in op.name:
+ self._log_info('This model has already been updated with LMS '
+ 'swap operations. LMS will not re-process it.')
+ return
+ # exclusive ops
+ self._excl_ops = self._filter_scopes_and_types(reachable_ops,
+ self._excl_scopes,
+ self._excl_types)
+ # inclusive ops
+ self._incl_ops = self._filter_scopes_and_types(reachable_ops,
+ self._incl_scopes,
+ self._incl_types)
+
+ reachable_ops -= self._grad_ops
+
+ # build a topological sort
+ self._topo_sort = topos.TOPOS(seed_ops, self._grad_ops)
+ self._topo_sort.build()
+ for i in range(0, self._topo_sort.size):
+ self._log_info("[{}]: {}".format(
+ i, [op.name for op in self._topo_sort.get_ops(i)]), 1)
+
+ if self._ss is None:
+ self._do_action(seed_ops)
+ else:
+ # STR instrumentation
+ fwd_ops = set(ge.make_list_of_op(self._graph)).difference(list(self._grad_ops))
+ records = self._ss.get_swap_record(list(fwd_ops), list(self._grad_ops))
+ self._log_info("Total {} records are found from STR strategy.".format(len(records)))
+ self._str_swap_action(records)
+
+ # check the validation of the new model
+ new_reachable_ops = set()
+ for seed_op in seed_ops:
+ new_reachable_ops |= set(ge.get_forward_walk_ops(seed_op))
+ new_reachable_ops -= self._grad_ops
+ if (new_reachable_ops >= reachable_ops):
+ self._log_info("Edited model is valid and logically equivalent to the original one")
+ self._log_info("Added {} ops into the model".format(len(new_reachable_ops - reachable_ops)))
+ else:
+ self._log_info("Edited model is invalid. Running this may produce unexpected result")
+
+ self._log_info("Editing model for LMS, took: {} ms".format(
+ (time.time()-start_time)*1000))
+ self._log_info(
+ "{} tensors will be swapped out(in) to(from) the host".format(
+ self._incpu_count))
+ return (new_reachable_ops - reachable_ops)
+
+ def _str_swap_action(self, records):
+ """ Edit the computing graph with swapping nodes. The editing is based on the solved strategy of STR
+
+ Args:
+ records (List[SwapRecord]): a list of swap records, which contains the swap out/in operations.
+ """
+ for i, record in enumerate(records):
+ self._log_info("Processing record: {}".format(record))
+ swapout_op = self._add_swapout(record.swap_out_source_ts.op, record.swap_out_source_ts)
+ self._incpu_count = self._incpu_count + 1
+ ge.add_control_inputs(swapout_op, [record.swap_out_control_op])
+ self._log_info("Add swap out node {}".format([swapout_op]))
+
+ # create swap_in nodes
+ for control_op, dest_ops in zip(record.swap_in_control_ops, record.swap_in_dest_ops):
+ self._log_info("Start add swap in node for dest. {}, control at {}".format(dest_ops, control_op))
+ # one swap in tensor may be used by multiple nodes
+ swapin_op = self._add_swapin_str(swapout_op, dest_ops, record.swap_out_source_ts)
+ if swapin_op is not None:
+ ge.add_control_inputs(swapin_op, [control_op])
+ self._log_info("Add swap in node: {}, linking to dest ops:{}".format([swapin_op], dest_ops))
+
+
+ def _do_action(self, src_ops):
+ """Add swapin and swapout ops for ops that are reachable from `src_ops`.
+
+ Args:
+ src_ops: a list of `tf.Operation`
+ """
+ open_set = Queue.Queue()
+ closed_set = set()
+
+ for op in src_ops:
+ open_set.put(op)
+
+ while not open_set.empty():
+ src_op = open_set.get()
+
+ # get next ops before the graph is changed
+ next_ops = set()
+ for t in src_op.outputs:
+ frontier_ops = set(util.get_consuming_ops(t))
+ next_ops |= frontier_ops - self._grad_ops
+
+ # do action for src_op
+ self._insert_swap_nodes(src_op)
+ if self._swapped_max_tensors():
+ return
+
+ for op in next_ops:
+ if op in closed_set:
+ continue
+ if op not in open_set.queue:
+ open_set.put(op)
+
+ closed_set.add(src_op)
+
+ def _fuse_swapin_ops(self, src_op, swapout_op, bw_frontier_ops, ts0):
+ """Fuse all swapin ops that swaps in the same tensor.
+
+ This method does an in-place modification to the graph.
+
+ Args:
+ src_op: a `tf.Operation`.
+ swapout_op: a `tf.Operation`.
+ bw_frontier_ops: a set of `tf.Operation`.
+ ts0: a `tf.Tensor`.
+
+ Return:
+ A set of `tf.Operation` that cannot be fused.
+ """
+ fuse_bw_frontier_ops = {
+ op for op in bw_frontier_ops
+ if self._topo_sort.get_order(op) > 0}
+ if len(fuse_bw_frontier_ops) >= 2:
+ with tf.device(self._cpu_device):
+ swap_in = tf.identity(ts0, name="lms/swapin")
+
+ # Connect: swap_out -> swap_in
+ self._connect_ops(swapout_op, swap_in.op)
+ self._excl_ops.add(swap_in.op)
+
+ # reuse swap_in tensors
+ for op in fuse_bw_frontier_ops:
+ # Connect: swap_in -> dest
+ input_idx = ge.sgv(
+ op, graph=self._graph).input_index(ts0)
+ self._connect_ops(swap_in.op, op, remap_inputs=True,
+ idx=input_idx)
+
+ self._log_info(
+ "{} (order {}) reuses tensor {}".format(
+ op.name,
+ self._topo_sort.get_order(op),
+ ts0.name),
+ 1)
+
+ # control dependency -> swap_in
+ min_order = self._topo_sort.size + 1
+ earliest_op = None
+ for op in fuse_bw_frontier_ops:
+ order = self._topo_sort.get_order(op)
+ if order < min_order:
+ min_order = order
+ earliest_op = op
+ if earliest_op:
+ self._add_control_dependency(src_op, earliest_op, swap_in.op)
+ bw_frontier_ops -= fuse_bw_frontier_ops
+ return bw_frontier_ops
+
+ def _get_branch_ops(self, within_ops, threshold=0):
+ """Get ops whose order compared to the minimum order
+ is greater than the threshold.
+
+ Args:
+ within_ops: a set of `tf.Operation`.
+ threshold: an integer.
+
+ Return:
+ A set of `tf.Operation`.
+ """
+ orders = {self._topo_sort.get_order(op)
+ for op in within_ops}
+ if not orders:
+ return set()
+ min_order = min(orders) + threshold
+ branch_ops = {
+ op
+ for op in within_ops
+ if (self._topo_sort.get_order(op) > min_order)}
+ return branch_ops
+
+ def _insert_swap_nodes(self, src_op):
+ """Insert swapin and swapout ops for the given operation into the graph.
+
+ This method does an in-place modification to the graph.
+
+ Args:
+ src_op: a `tf.Operation`
+ """
+ self._log_info("Operation: {}".format(src_op), 2)
+
+ # bypass excluded ops
+ if src_op in self._excl_ops:
+ return
+
+ # if inclusive mode is enabled, only proceed if this op is included
+ if self._incl_ops:
+ if src_op not in self._incl_ops:
+ return
+
+ for t in src_op.outputs:
+ if self._swapped_max_tensors():
+ return
+
+ frontier_ops = set(util.get_consuming_ops(t))
+ self._log_info("my frontier ops: {}".format(frontier_ops), 2)
+
+ bw_frontier_ops = frontier_ops & self._grad_ops
+ self._log_info("my bw frontier ops: {}".format(bw_frontier_ops), 2)
+
+ # swap branch ops if they are far enough (depending on threshold)
+ if self._swap_branches:
+ fw_branch_ops = self._get_branch_ops(
+ frontier_ops - self._grad_ops,
+ self._branch_threshold)
+ bw_frontier_ops = bw_frontier_ops | fw_branch_ops
+
+ # Do not swap tensors used by bw ops without outgoing ops.
+ # These bw ops can be removed by Tensorflow compiler
+ bw_frontier_ops = {op
+ for op in bw_frontier_ops
+ if set(self._get_forward_walk_ops(op, inclusive=False))}
+
+ if not bw_frontier_ops:
+ continue
+
+ self._log_info("Operation: {}, order {}, type {}".format(
+ src_op.name, self._topo_sort.get_order(src_op),
+ src_op.type), 1)
+
+ # create swap_out node only if there exists a real dest. operation
+ swapout_op = None
+ for op in bw_frontier_ops:
+ if self._topo_sort.get_order(op) >= 0:
+ swapout_op = self._add_swapout(src_op, t)
+ self._incpu_count = self._incpu_count + 1
+ break
+
+ # create swap_in nodes
+ if self._fuse_swapins and swapout_op:
+ bw_frontier_ops = self._fuse_swapin_ops(
+ src_op, swapout_op, bw_frontier_ops, t)
+ for dest_op in bw_frontier_ops:
+ if self._topo_sort.get_order(dest_op) < 0:
+ if src_op in self._grad_ops:
+ continue
+ else:
+ new_src_ops = self._find_new_src_op(dest_op)
+ for op in new_src_ops:
+ self._insert_swap_nodes(op)
+ else:
+ # swap_in op
+ swapin_op = self._add_swapin(swapout_op, dest_op, t)
+ # control dependency -> swap_in
+ self._add_control_dependency(src_op, dest_op, swapin_op)
+
+ def _add_swapout(self, src_op, ts0):
+ """Add a swapout operation to the graph to swap out the output tensor `ts0`
+ of the operation `src_op`.
+
+ This method does an in-place modification to the graph.
+
+ Example: the graph before and after this method invoked.
+ ```
+ Before
+ (src_op) -> |ts0| -> (dest_op)
+
+ After:
+ (src_op) -> |ts0| -> (swapout_op)
+ |ts0| -> (dest_op)
+ ```
+
+ Args:
+ src_op: a `tf.Operation` that produces the tensor `ts0`.
+ ts0: a output `tf.Tensor` of `src_op` being swapped out.
+
+ Return:
+ A `tf.Operation` newly added to the graph.
+ """
+ with tf.device(self._cpu_device):
+ swap_out = tf.identity(ts0, name="lms/swapout")
+
+ # Connect: src-node -> swap-out
+ src_svg = ge.sgv(src_op, graph=self._graph)
+ src_out_idx = src_svg.output_index(ts0)
+ self._connect_ops(src_op, swap_out.op, remap_outputs=True,
+ idx=src_out_idx)
+ self._excl_ops.add(swap_out.op)
+ self._log_info("Tensor {} will be placed on {}".format(
+ ts0.name, self._cpu_device), 1)
+
+ return swap_out.op
+
+ def _add_swapin(self, swapout_op, dest_op, ts0):
+ """Add a swapin operation to the graph. The swapin ops reads
+ the output tensor of `swapout_op` and passes it to `dest_op`,
+ replacing the input tensor `ts0` of `dest_op`.
+
+ This method does an in-place modification to the graph.
+
+ Example: the graph before and after this method invoked.
+ ```
+ Before
+ |ts0| -> (swapout_op)
+ |ts0| -> (dest_op)
+
+ After:
+ |ts0| -> (swapout_op) -> (swapin_op) -> (dest_op)
+ ```
+
+ Args:
+ swapout_op: a `tf.Operation` that swapped out the tensor `ts0`.
+ dest_op: a `tf.Operation` that will consume the output tensor of `swapout_op`.
+ ts0: a `tf.Tensor` being the original input tensor of `dest_op`.
+
+ Return:
+ A `tf.Operation` newly added to the graph.
+ """
+ with tf.device(self._cpu_device):
+ swap_in = tf.identity(ts0, name="lms/swapin")
+
+ # Connect: swap_out -> swap_in
+ self._connect_ops(swapout_op, swap_in.op)
+
+ # Connect: swap_in -> dest
+ dest_svg = ge.sgv(dest_op, graph=self._graph)
+ input_idx = dest_svg.input_index(ts0)
+ self._connect_ops(swap_in.op, dest_op, remap_inputs=True, idx=input_idx)
+ self._excl_ops.add(swap_in.op)
+
+ self._log_info("Consuming op {} (order {}) swaps in {}".format(
+ dest_op.name, self._topo_sort.get_order(dest_op),
+ ts0.name), 1)
+
+ return swap_in.op
+
+ def _add_swapin_str(self, swapout_op, dest_ops, ts0):
+ """Add a swapin operation to the graph. The swapin ops reads
+ the output tensor of `swapout_op` and passes it to `dest_op`,
+ replacing the input tensor `ts0` of `dest_op`.
+
+ Return:
+ A `tf.Operation` newly added to the graph.
+ """
+ with tf.device(self._cpu_device):
+ swap_in = tf.identity(ts0, name="lms-str/swapin")
+
+ # Connect: swap_out -> swap_in
+ self._connect_ops(swapout_op, swap_in.op)
+
+ for dest_op in dest_ops:
+ dest_svg = ge.sgv(dest_op, graph=self._graph)
+ if ts0 not in dest_svg._input_ts:
+ self._log_info("Tensor {} is not the input of svg {}, skip linking!".format(ts0, dest_svg))
+ return None
+ input_idx = dest_svg.input_index(ts0)
+ self._connect_ops(swap_in.op, dest_op, remap_inputs=True, idx=input_idx)
+
+ self._excl_ops.add(swap_in.op)
+ self._log_info("Consuming op {}, swaps in {}".format(
+ dest_ops, ts0.name), 1)
+
+ return swap_in.op
+
+ def _add_control_dependency(self, fw_op, bw_op, swapin_op):
+ """Find and add a control dependency to the graph.
+
+ This method does an in-place modification to the graph.
+
+ Args:
+ fw_op: a `tf.Operation`.
+ bw_op: a `tf.Operation`.
+ swapin_op: a `tf.Operation`.
+ """
+ # if lb is out of range, reset it to make sure
+ # that a control dependency op will be found
+ lb = self._lb
+ if (self._topo_sort.get_order(bw_op) - lb <=
+ self._topo_sort.get_order(fw_op)):
+ lb = 1
+ if fw_op in self._grad_ops:
+ re = self._do_direct_order(fw_op, bw_op, lb, self._ub)
+ elif self._ctrld_strategy is CTRLD_Strategy.CHAIN_RULE:
+ re = self._do_chain_rule(fw_op, bw_op, lb, self._ub)
+ elif self._ctrld_strategy is CTRLD_Strategy.DIRECT_ORDER:
+ re = self._do_direct_order(fw_op, bw_op, lb, self._ub)
+ else:
+ re = self._do_chain_rule(fw_op, bw_op, lb, self._ub)
+
+ ctrld_op = re[0]
+ ctrld_order = re[1]
+ if ctrld_op:
+ ge.add_control_inputs(swapin_op, ctrld_op)
+ self._log_info(
+ "Control dependency op {}, order: {}".format(
+ ctrld_op.name, ctrld_order), 1)
+ else:
+ self._log_info(
+ "No control dependency op needed for swap in of op {}.".format(
+ fw_op.name), 1)
+
+ def _find_new_src_op(self, original_op):
+ """Find a set of new operations to swap out their output tensors.
+
+ This method is used when `original_op` produces a tensor that is consumed by
+ a backward ops whose order is negative. In this case, the tensor might be consumed
+ immediately by the backward ops, depending on TensorFlow runtime. Hence, there is
+ no need to swap out the tensor.
+
+ This method starts from `original_op` and returns operations whose output tensors
+ are consumed by backward operations with positive order.
+
+ Args:
+ `original_op`: a `tf.Operation`.
+
+ Return:
+ A set of `tf.Operation`.
+ """
+ src_ops = set()
+ open_set = Queue.Queue()
+ closed_set = set()
+
+ open_set.put(original_op)
+
+ while not open_set.empty():
+ src_op = open_set.get()
+
+ # do action for src_op
+ next_ops = set()
+
+ frontier_ops = set()
+ for t in src_op.outputs:
+ frontier_ops |= set(util.get_consuming_ops(t))
+ has_order_ops = {
+ op
+ for op in frontier_ops
+ if (self._topo_sort.get_order(op) >
+ self._topo_sort.bw_starting_order)
+ }
+ if has_order_ops:
+ src_ops.add(src_op)
+
+ next_ops = frontier_ops - has_order_ops
+ for op in next_ops:
+ if op in closed_set:
+ continue
+ if op not in open_set.queue:
+ open_set.put(op)
+
+ closed_set.add(src_op)
+ return src_ops
+
+ def _do_chain_rule(self, fw_op, bw_op, lower_b, upper_b):
+ """Find a control dependency operation using chain rules.
+ Go down along the forward phase to find corresponding backward ops
+ as candidates for control dependency ops.
+
+ Args:
+ fw_op: a `tf.Operation` that has a tensor swapped out.
+ bw_op: a `tf.Operation` that consumes a tensor swapped in.
+ lower_b: an `integer`. The distance in the graph between
+ `fw_op` and a forward operation that has corresponding backward
+ ops as candidates for control dependency ops must be greater than
+ `lower_b`.
+ upper_b: an `integer`. The distance in the graph between
+ `fw_op` and a forward operation that has corresponding backward
+ ops as candidates for control dependency ops must be smaller than
+ `upper_b`
+
+ Return:
+ A tuple of (`tf.Operation`, an `integer`). The first item is
+ the control dependency operation that triggers swapping in the input
+ tensor of `bw_op`. The second item is the order of the control
+ dependency operation in the topological order.
+ """
+ fw_order = self._topo_sort.get_order(fw_op)
+ bw_order = self._topo_sort.get_order(bw_op)
+
+ # check if the bw op is near the boundary between fw and bw phases
+ if (bw_order - lower_b) < self._topo_sort.bw_starting_order:
+ return self._do_direct_order(fw_op, bw_op, lower_b, upper_b)
+
+ open_set1 = Queue.Queue()
+ open_set2 = Queue.Queue()
+ closed_set = set()
+
+ open_set1.put(fw_op)
+
+ result_ops = set()
+ while not open_set1.empty():
+ # stop if reaching the upperbound
+ if upper_b == 0 or (lower_b > upper_b):
+ break
+
+ src_op = open_set1.get()
+
+ # do action for src_op
+ total_consumming_ops = set()
+ for t in src_op.outputs:
+ consumming_ops = set(util.get_consuming_ops(t))
+ total_consumming_ops |= consumming_ops
+
+ if lower_b <= 0:
+ # inside the range
+ consumming_ops_bw = total_consumming_ops & self._grad_ops
+ # check validation
+ consumming_ops_bw = {
+ op
+ for op in consumming_ops_bw
+ if self._topo_sort.get_order(op) > fw_order}
+ consumming_ops_bw = {
+ op
+ for op in consumming_ops_bw
+ if self._topo_sort.get_order(op) < bw_order}
+ consumming_ops_bw = {
+ op
+ for op in consumming_ops_bw
+ if "/cond/" not in op.name}
+ result_ops |= consumming_ops_bw
+ # go to the next level
+ next_ops = total_consumming_ops - self._grad_ops
+ for op in next_ops:
+ if op in closed_set:
+ continue