forked from alibaba/TinyNeuralNetwork
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tracer.py
3344 lines (2833 loc) · 132 KB
/
tracer.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
import contextlib
import copy
import ctypes
import importlib
import inspect
import io
import os
import queue
import re
import sys
import traceback
import typing
import weakref
import types
import torch
import torch.nn as nn
import yaml
import numpy as np
from torch.nn.parallel.data_parallel import DataParallel
from torch.nn.parallel.distributed import DistributedDataParallel
from tinynn.util.train_util import get_module_device
from tinynn.util.util import get_logger, import_from_path, tensors2ndarray
from ._utils import patch_getitem, revert_getitem, patch_new, revert_new
from . import interop # noqa: F401
# Basic types
class GlobalData(object):
"""The data structure to store data that can be used in this script,
which is a wrapper of a object of a built-in type."""
def __init__(self, value):
super().__init__()
self.value = value
def get_value(self):
"""Returns the inner value of the wrapper"""
return self.value
def set_value(self, value):
"""Sets the inner value of the wrapper"""
self.value = value
def __str__(self):
"""Returns the string representation of the inner object"""
return self.value.__str__()
def __repr__(self):
"""Returns the string representation of the inner object"""
return self.value.__repr__()
def __call__(self, *args):
"""Simplifies the usage of the wrapper
e.g. a = GlobalData(3)
a() -> a.get_value()
a(1) -> a.set_value(1)"""
if len(args) == 0:
return self.get_value()
elif len(args) == 1:
return self.set_value(*args)
else:
raise ValueError(
f'length of input data must in [0,1], but got length: {len(args)} --> args: {args}'
)
def __bool__(self):
"""Returns the actual boolean value of the inner object"""
return self.value.__bool__()
# Constants
# Template for a traced module
MODULE_TEMPLATE = """
%(import_block)s
class %(name_block)s(torch.nn.Module):
def __init__(self):
super().__init__()
%(init_block)s
%(forward_block)s
if __name__ == "__main__":
model = %(name_block)s()
%(load_weight_block)s
model.eval()
model.cpu()
%(input_block)s
output = model(%(input_names)s)
print(output)
"""
# Special math operators
SPECIAL_OPERATORS = ['add', 'and', 'div', 'floordiv', 'lshift', 'mul', 'or', 'pow', 'rshift', 'sub', 'xor', 'truediv']
# Global objects
# Logger
log = get_logger(__name__, 'WARNING')
# Loaded overriable items from the config file
overridable_funcs = {}
overridable_modules = []
overridable_creation_funcs = {}
torch_overrides_funcs = []
torch_overrides_wrappers = []
torch_tracking_modules = []
# Reuse generated wrapper functions and modules
generated_wrapper_funcs = {}
generated_wrapper_modules = {}
# Load state for the override items
overridable_funcs_loaded = GlobalData(False)
overridable_modules_loaded = GlobalData(False)
overridable_creation_funcs_loaded = GlobalData(False)
torch_overrides_funcs_loaded = GlobalData(False)
tracking_modules_loaded = GlobalData(False)
funcs_overrided = GlobalData(False)
modules_overrided = GlobalData(False)
creation_funcs_overrided = GlobalData(False)
tracking_modules_overrided = GlobalData(False)
# Lock for tracing
lock = GlobalData(False)
handle_func_lock = GlobalData(False)
# Whether the constructors get traced
module_constructor_traced = set()
# Current traced graph
current_graph = GlobalData(None)
# Generated module constructor lines
module_constructor_lines = {}
module_constructor_weakrefs = {}
# Directory of the current script
current_dir = os.path.dirname(os.path.abspath(__file__))
# Original module constructor signatures
module_constructor_signatures = {}
# Original values of tracked objects
original_values_for_tracked_objects = {}
# Original module class names
importable_module_names = {}
# Ignore warning for update module parameters
mod_param_update_warning_ignore = GlobalData(False)
# Modules that are skipped while tracing
skip_modules = set()
class TraceNode(object):
"""A basic data structure to represent a node in the computation graph"""
module: typing.Union[torch.nn.Module, 'TraceFunction', 'ConstantNode']
prev_nodes: typing.List['TraceNode']
next_nodes: typing.List['TraceNode']
prev_tensors: typing.List[torch.Tensor]
next_tensors: typing.List[torch.Tensor]
prev_indices: typing.List[typing.Optional[int]]
rev_index: bool
unique_name: str
active: bool
def __init__(
self,
module: typing.Union[torch.nn.Module, 'ConstantNode', 'TraceFunction'],
cur_graph: typing.Optional['TraceGraph'] = None,
):
# Inner module, could either be a `nn.Module`, `ConstantNode` or `TraceFunction`
self.module = module
# Previous and next nodes in the computation graph
self.prev_nodes = []
self.next_nodes = []
# The input and output tensors for the node
self.prev_tensors = []
self.next_tensors = []
# The indices used to retrieve the corresponding tensor
# e.g. torch.chunk() returns [A, B], in which A and B are PyTorch tensors.
# so if we use A in this node, then the corresponding prev_index is 0.
# If the tensor is not a sub item, then `None` should be used.
self.prev_indices = []
# In some nodes, the indices are reversed. For example, for an output node,
# the indices are not used to fetch the items, but to construct a list that
# contains them.
self.rev_index = False
# The current TraceGraph to be processed
# In the trace phase, it can be obtained through `current_graph()`
# Otherwise, you need to pass it explicitly
if cur_graph is None:
cur_graph = current_graph()
# Unique name of the node (the key of the node in the node map in TraceGraph)
if type(module) in (ConstantNode, TraceFunction):
self.unique_name = module.unique_name
else:
self.unique_name = cur_graph.module_unique_name_dict[id(module)]
if isinstance(module, nn.Module) and id(module) in cur_graph.module_original_name_dict:
self.original_name = cur_graph.module_original_name_dict[id(module)]
elif type(module) == ConstantNode:
self.original_name = module.original_name
else:
self.original_name = self.unique_name
# Whether the node is active in the computation graph
self.active = True
# The index of the node in the graph
self.forward_order = 0
# Whether the node is in a quantized graph
self.quantized = False
# Numbering of the name of the node
if cur_graph.global_nodes.get(self.unique_name) is not None:
cur_graph.global_nodes[self.unique_name] += 1
self.unique_name = "_".join([self.unique_name, str(cur_graph.global_nodes[self.unique_name])])
else:
cur_graph.global_nodes[self.unique_name] = 0
def type(self):
"""Returns the original name of the function or the type of the module"""
if type(self.module) == TraceFunction:
return self.module.func_type
return type(self.module)
def kind(self):
"""Returns the kind of the function or the type of the module"""
if type(self.module) == TraceFunction:
return self.module.kind
return type(self.module)
def is_class(self) -> bool:
"""Judges whether it is a class function or not"""
if type(self.module) == TraceFunction:
return self.module.is_class
else:
return False
def full_name(self) -> str:
"""Returns the original full name of the function (including namespace)"""
if type(self.module) in (TraceFunction, ConstantNode):
return self.module.full_name
else:
return f'{type(self.module).__module__}.{type(self.module).__name__}'
def __hash__(self) -> str:
"""Uses the unique name as the hash for the node"""
return self.unique_name
def prev_node_unique_name(self, idx, inplace=False) -> str:
"""A utility function to generate the name of the previous node with index"""
if idx < len(self.prev_nodes) and idx < len(self.prev_indices):
getattr_on_module = False
if (
isinstance(self.prev_nodes[idx].module, torch.nn.Module)
and type(self.module) == TraceFunction
and self.module.is_property
and '.' not in self.module.full_name
):
getattr_on_module = True
actual_inplace = False
if inplace:
actual_inplace = getattr_on_module
if isinstance(self.prev_nodes[idx].module, ConstantNode):
actual_inplace = True
if actual_inplace:
node_name = self.prev_nodes[idx].original_name
else:
node_name = self.prev_nodes[idx].unique_name
node_idx = self.prev_indices[idx]
ns = ''
if type(self.prev_nodes[idx].module) in (ConstantNode, torch.nn.quantized.FloatFunctional):
ns = 'self.'
elif getattr_on_module:
prev_t_ids = set(id(t) for t in self.prev_tensors)
next_t_ids = set(id(t) for t in self.prev_nodes[idx].next_tensors)
if len(prev_t_ids & next_t_ids) == 0:
ns = 'self.'
if node_idx is None:
return f'{ns}{node_name}'
else:
if isinstance(node_idx, (list, tuple)):
indices_str = ''.join([f'[{i}]' for i in node_idx])
return f'{ns}{node_name}{indices_str}'
else:
return f'{ns}{node_name}[{node_idx}]'
else:
return ''
class ConstantNode(object):
"""A data structure for runtime-defined constants"""
def __init__(
self,
data: typing.List,
dtype: torch.dtype,
shape: torch.Size,
unique_name: typing.Optional[str] = None,
original_name: typing.Optional[str] = None,
):
# Raw data (list)
self.data = data
# Data shape
self.shape = tuple(shape)
# Data type
self.dtype = str(dtype)
# Please refer to the the description of those properties in `TraceFunction`
self.kind = 'tensor'
self.func_type = 'tensor'
self.full_name = 'torch.tensor'
self.is_class = False
self.is_parameter = False
self.is_persistent = False
self.requires_grad = False
self.data_str = None
# Numbering of the name of the node
if current_graph().global_functions.get(self.kind, None) is None:
current_graph().global_functions[self.kind] = 0
else:
current_graph().global_functions[self.kind] += 1
if unique_name is None:
self.unique_name = "_".join([self.kind, str(current_graph().global_functions[self.kind])])
else:
self.unique_name = unique_name
self.inplace = original_name is not None
if original_name is None:
self.original_name = self.unique_name
else:
self.original_name = original_name
def parse(self, convert_to_parameter: bool = False, persistent: bool = False, requires_grad: bool = False):
def _stringify_list(content) -> str:
"""Convert a list of objects to a string"""
if isinstance(content, (list, tuple)):
sub_contents = []
for item in content:
sub_contents.append(_stringify_list(item))
inner_content = ', '.join(sub_contents)
return f'[{inner_content}]'
elif type(content) in (int, float, bool):
return str(content)
elif type(content) == str:
return f'"{content}"'
# If `convert_to_parameter` is `True`, the content of the data will not be written inline.
self.is_parameter = convert_to_parameter
self.is_persistent = persistent
self.requires_grad = requires_grad
if not persistent:
self.data_str = f'{_stringify_list(self.data)}'
return self
class TraceFunction(object):
"""A data structure for traced functions"""
def __init__(
self, full_name: str, is_class: bool = False, is_property: bool = False, prefix: typing.Optional[str] = None
):
super().__init__()
# The base name of the function
self.func_type = full_name.split('.')[-1]
# The class name of the function
# It can be acquired by removing underlines in the base name of the function for special math
# operators and inline functions
self.kind = None
if self.func_type.endswith('__') and self.func_type.startswith('__'):
inner_name = self.func_type[2:-2]
if len(inner_name) > 1 and inner_name[0] in ('i', 'r'):
inner_op = inner_name[1:]
if inner_op in SPECIAL_OPERATORS:
self.kind = inner_op
if self.kind is None:
self.kind = inner_name
if self.kind is None:
if self.func_type.endswith('_'):
self.kind = self.func_type[:-1]
else:
self.kind = self.func_type
# Numbering of the nodes
if current_graph().global_functions.get(self.kind, None) is None:
current_graph().global_functions[self.kind] = 0
else:
current_graph().global_functions[self.kind] += 1
if prefix is None:
prefix = ""
# Unique name
self.unique_name = prefix + "_".join([self.kind, str(current_graph().global_functions[self.kind])]) + "_f"
# The input tensors of the function
self.prev_tensors = []
# The name of the function (including namespace)
self.full_name = full_name
# Whether it is a class function/property
self.is_class = is_class
# Whether it is a property
self.is_property = is_property
# Alias
self.aliases = None
# Arguments
self.args = None
self.kwargs = None
self.args_string = None
self.args_parsed = None
self.args_parsed_origin = None
self.tensor_names = None
self.original_tensor_names = None
self.args_template = None
self.args_template_no_self = None
self.args_offset = None
def __repr__(self) -> str:
"""Returns the string representation of the object"""
arg_len = len(self.tensor_names)
if arg_len > 0:
prefix = 'lambda args: '
else:
prefix = 'lambda: '
extra_expr = self.extra_expr('args')
expr = f'{prefix}{extra_expr}'
return expr
def extra_expr(self, prefix=None, first=None, original=False):
"""Returns the extra string representation of the object"""
arg_len = len(self.tensor_names)
if arg_len == 0:
expr = f'{self.full_name}({self.args_template})'
else:
if prefix is None:
if original:
tensor_names = [
(o_name if o_name.startswith('self.') else f'self.{o_name}')
if u_name.startswith('self.')
else u_name
for u_name, o_name in zip(self.tensor_names, self.original_tensor_names)
]
else:
tensor_names = self.tensor_names
else:
tensor_names = [f'{prefix}[{i}]' for i in range(arg_len)]
if first is not None:
tensor_names = [first] + tensor_names[1:]
if self.is_class:
if self.is_property:
expr = f'{tensor_names[0]}.{self.func_type}'
elif self.func_type == '__getitem__':
args = self.args_string_no_self
if not args.startswith('[') and not args.endswith(']'):
args = f'[{args}]'
expr = f'{tensor_names[0]}{args}'
else:
full_template = f'{{}}.{self.func_type}({self.args_template_no_self})'
expr = full_template.format(*tensor_names)
else:
full_template = f'{self.full_name}({self.args_template})'
expr = full_template.format(*tensor_names)
return expr
def __call__(self, *args, **kwargs):
"""Calls the function with a list of tensor inputs"""
if len(kwargs) > 0:
log.warning('Keyword arguments are ignored when calling TraceFunction')
if len(args) == 0:
arg_len = 0
else:
if len(args) > 1:
log.warning('Multiple arguments are passed in, but all but the first one will be ignored')
if not isinstance(args[0], (tuple, list)):
log.error('Only tuple or list is accepted here')
assert False
arg_len = len(args[0])
expected_len = len(self.tensor_names)
if arg_len != expected_len:
log.error(f'Wrong number of input tensors, expected: {expected_len}, but got {arg_len}')
assert False
expr = self.extra_expr('args[0]')
return eval(expr)
def parse_args(self, *args, **kwargs):
"""Sets the string representation of the arguments"""
def _tensor_name(a, convert_to_parameter=False, original=False):
"""Get the tensor name from the computation graph"""
ns = ''
if constant_handler(a, self.unique_name, self.full_name):
ns = 'self.'
pre_node_name = current_graph().tensor_pre_node_dict[id(a)]
if original:
node = current_graph().nodes_map[pre_node_name]
pre_node_name = node.original_name
else:
pre_node_name = current_graph().tensor_pre_node_dict[id(a)]
node = current_graph().nodes_map[pre_node_name]
if original:
pre_node_name = node.original_name
if type(node.module) in (ConstantNode, torch.nn.quantized.FloatFunctional):
ns = 'self.'
if id(a) in current_graph().tensor_pre_index_dict:
pre_node_index = current_graph().tensor_pre_index_dict[id(a)]
log.debug(f'pre_index gen func {self.kind}: {pre_node_index}')
if isinstance(pre_node_index, (list, tuple)):
indices_str = ''.join([f'[{i}]' for i in pre_node_index])
return f"{ns}{pre_node_name}{indices_str}"
else:
return f"{ns}{pre_node_name}[{pre_node_index}]"
else:
return f"{ns}{pre_node_name}"
def _escape_arg(arg: str):
"""Escapes the special characters in the argument string"""
for c in ('{', '}'):
if c in arg:
arg = arg.replace(c, f'{c}{c}')
return arg
def _parse_args(arg):
"""Converts the argument to a list of strings"""
new_arg = []
for a in arg:
if isinstance(a, (list, tuple, torch.Size)):
new_arg.append(_parse_args(a))
elif type(a) in (torch.Tensor, torch.nn.Parameter) or (
type(a) in (torch.dtype, torch.device, torch.Size) and id(a) in current_graph().tensor_pre_node_dict
):
self.prev_tensors.append(a)
self.tensor_names.append(_tensor_name(a))
self.original_tensor_names.append(_tensor_name(a, original=True))
new_arg.append('{}')
elif type(a) in (str, torch.device):
new_arg.append(_escape_arg(f"\'{a}\'"))
elif type(a) in (int, float, bool, torch.dtype):
new_arg.append(str(a))
elif a is None:
new_arg.append('None')
elif a is Ellipsis:
new_arg.append('...')
elif type(a) == slice:
t = (a.start, a.stop, a.step)
parts = []
for x in t:
if x is None:
parts.append('')
else:
parts.extend(_parse_args([x]))
r = ':'.join(parts)
if r.endswith(':'):
r = r[:-1]
new_arg.append(r)
elif isinstance(a, torch.nn.quantized.FloatFunctional):
float_functional_cls = type(a)
module_constructor_lines[id(a)] = f'{qualified_name(float_functional_cls, short=True)}()'
new_node = TraceNode(a)
current_graph().nodes_map[new_node.unique_name] = new_node
current_graph().other_init_nodes.append(new_node)
current_graph().tensor_pre_node_dict[id(a)] = new_node.unique_name
self.tensor_names.append(_tensor_name(a))
self.original_tensor_names.append(_tensor_name(a, original=True))
self.prev_tensors.append(a)
new_arg.append('{}')
elif isinstance(a, nn.Module):
unique_name = current_graph().module_unique_name_dict[id(a)]
current_graph().tensor_pre_node_dict[id(a)] = unique_name
self.tensor_names.append(f'self.{unique_name}')
self.original_tensor_names.append(_tensor_name(a, original=True))
self.prev_tensors.append(a)
new_arg.append('{}')
else:
log.error(f"unsupported type {type(a)} while generating arg for func {self.full_name}")
assert False
return new_arg
self.tensor_names = []
self.original_tensor_names = []
self.prev_tensors.clear()
arg_str = _parse_args(args)
kw_items = kwargs.items()
if kw_items:
kw_keys, kw_vals = zip(*kw_items)
kw_val_strs = _parse_args(kw_vals)
for (k, v) in zip(kw_keys, kw_val_strs):
if type(v) is list:
v_str = self._flatten_list(v)
arg_str.append(f"{k}={v_str}")
else:
arg_str.append(f"{k}={v}")
self.args_parsed = copy.deepcopy(arg_str)
self.kwargs = copy.deepcopy(kwargs)
self.args_parsed_origin = copy.deepcopy(self.args_parsed)
self.args_to_string(self.args_parsed)
return self
def _flatten_list(self, content):
"""Flatten a list of nested list or string into a string"""
if isinstance(content, list):
sub_contents = []
for item in content:
sub_contents.append(self._flatten_list(item))
inner_content = ', '.join(sub_contents)
return f'[{inner_content}]'
else:
return content
def args_to_string(self, arg_str):
for i in range(len(arg_str)):
if type(arg_str[i]) is list:
arg_str[i] = self._flatten_list(arg_str[i])
try:
self.args_template = ", ".join(arg_str)
self.args_template_no_self = ", ".join(arg_str[1:])
self.args_offset = 1 if arg_str[0] == '{}' else 0
self.update_args_string()
except Exception:
log.error(f"Error generating argument string for function {self.full_name}")
assert False
return self
def update_tensor_name(self, index, new_name):
"""Updates the tensor name at the given index"""
self.tensor_names[index] = new_name
def replace_tensor_name(self, old_name, new_name):
"""Replaces the specific tensor name with the given one"""
for i, name in enumerate(self.tensor_names):
if name == old_name:
self.tensor_names[i] = new_name
def update_args_string(self):
"""Updates the string representation according to the templates and the tensor names"""
if self.args_template:
self.args_string = self.args_template.format(*self.tensor_names)
if self.args_template_no_self:
self.args_string_no_self = self.args_template_no_self.format(*self.tensor_names[self.args_offset :])
def get_tensor_name(self, index, original):
"""Retrieves the tensor name at the given index"""
if original:
return self.original_tensor_names[index]
else:
return self.tensor_names[index]
def add_alias(self, name, head=False):
"""Adds an aliases of the tensor"""
if self.aliases is None:
self.aliases = []
if head:
self.aliases.insert(0, name)
else:
self.aliases.append(name)
def get_aliases(self):
"""Retrieves the aliases of the tensor"""
return self.aliases
@contextlib.contextmanager
def no_catch():
"""Context manager for tracing nodes. Use it to avoid tracing the nodes recursively."""
if lock():
yield False
else:
lock(True)
yield True
lock(False)
@contextlib.contextmanager
def no_catch_handle_func():
"""Context manager for tracing nodes. Use it to avoid hacking into handle_torch_function recursively."""
if handle_func_lock():
yield False
else:
handle_func_lock(True)
yield True
handle_func_lock(False)
def args_as_string(args, kwargs):
"""String representation of the args and the keyword args"""
cleaned_args = [f'"{arg}"' if type(arg) == str else str(arg) for arg in args]
args_content = ', '.join(cleaned_args)
kwargs_content = ', '.join((f'{k}="{v}"' if type(v) is str else f'{k}={v}' for k, v in kwargs.items()))
args_connector = '' if args_content == '' or kwargs_content == '' else ', '
full_args_content = f'{args_content}{args_connector}{kwargs_content}'
return full_args_content
def new_setattr_gen(orig_setattr, key: str):
"""Wrapper function for the __setattr__ functions of the modules in PyTorch"""
log.debug(f'registered module setattr wrapper: {key}')
def new_setattr(obj, name, value):
log.debug(f'{key} in setattr function wrapper')
related = True
log.debug(f'{key} before with block, lock: {lock}')
with no_catch() as res:
if res:
if id(obj) not in module_constructor_traced:
related = False
class_type = type(obj)
if related and not hasattr(class_type, '__constants__'):
related = False
if related and name not in class_type.__constants__:
related = False
if related:
class_name = '.'.join(key.split('.')[:-1])
log_func = log.warning
if mod_param_update_warning_ignore():
log_func = log.debug
log_func(
f'The constant property `{name}` of {class_name} is changed. We need to drop the original'
' constructor line.'
)
module_constructor_traced.remove(id(obj))
del module_constructor_lines[id(obj)]
return orig_setattr(obj, name, value)
log.debug(f'{key} after with block, lock: {lock}')
return new_setattr
def new_module_getattr_gen(orig_getattr, key: str, res: typing.Dict[str, bool]):
log.debug(f'registered module getattr wrapper: {key}')
def new_getattr(obj, name):
log.debug(f'{key} in module getattr function wrapper')
result = orig_getattr(obj, name)
result_is_str = isinstance(result, str)
is_dict = name == '__dict__'
related = result_is_str or is_dict
# If the following conditions are satisfied
# a. the type of the result is `str` or the key is `__dict__`
# b. the 2nd last frame is on the `extra_repr` function or `__repr__` function
# c. the line is not starting with `if `
# then we should patch the variable.
if related:
last_frame = inspect.currentframe().f_back
func_name = last_frame.f_code.co_name
related = False
if func_name in ('extra_repr', '__repr__'):
if is_dict:
related = True
else:
fn = last_frame.f_code.co_filename
ln = last_frame.f_lineno
res_key = f'{fn}_{ln}'
if res_key in res:
related = res[res_key]
else:
lines = inspect.getframeinfo(last_frame)[3]
related = not re.match(r' *if .*', lines[0]) and not re.match(r'.*repr\(self\..*\)', lines[0])
res[res_key] = related
if related:
if result_is_str:
return f'"{result}"'
elif is_dict:
orig = result
result = {}
for k, v in orig.items():
if type(v) == str and (not k.startswith('__') and not k.endswith('__')):
result[k] = f'"{orig[k]}"'
else:
result[k] = v
return result
return new_getattr
def constant_handler(
tensor: torch.Tensor, node_name: typing.Optional[str] = None, type_name: typing.Optional[str] = None
) -> bool:
"""Appends the constant tensor to the computation graph
Args:
tensor (torch.Tensor): The constant tensor
node_name (typing.Optional[str], optional): The name of the node that depends on that tensor. Defaults to None.
type_name (typing.Optional[str], optional): The type of the node that depends on that tensor. Defaults to None.
Returns:
bool: Whether it is a new constant tensor
"""
if id(tensor) not in current_graph().tensor_pre_node_dict:
if id(tensor) in current_graph().parameter_module_dict:
mod_id = current_graph().parameter_module_dict[id(tensor)]
unique_name = current_graph().module_unique_name_dict[mod_id]
if unique_name in current_graph().related_modules:
mod = ctypes.cast(mod_id, ctypes.py_object).value
node = TraceNode(mod)
add_forward_node(node, [], [])
current_graph().tensor_pre_node_dict[mod_id] = node.unique_name
key = current_graph().parameter_original_name_dict[id(tensor)].split('.')[-1]
trace_func = TraceFunction(key, True, True).parse_args(mod)
trace_node = TraceNode(trace_func)
add_forward_node(trace_node, [mod], tensor)
return False
if not tensor.is_leaf:
if node_name is None:
node_name = 'unknown node'
if type_name is None:
type_name = 'unknown'
log.error(f'Connection is lost when generating code for {node_name} of type {type_name}')
else:
# constant tensor generation
log.warning('Constant generation is experimental and may yield error')
convert_to_parameter = False
persistent = False
requires_grad = tensor.requires_grad
if isinstance(tensor, torch.nn.Parameter):
convert_to_parameter = True
if tensor.numel() > 50:
persistent = True
raw_data = tensor.tolist()
unique_name = current_graph().parameter_unique_name_dict.get(id(tensor), None)
original_name = current_graph().parameter_original_name_dict.get(id(tensor), None)
with no_catch():
constant_node = ConstantNode(raw_data, tensor.dtype, tensor.shape, unique_name, original_name).parse(
convert_to_parameter, persistent, requires_grad
)
trace_node = TraceNode(constant_node)
add_constant_node(trace_node, tensor)
return True
else:
return False
def new_getattr_gen(orig_getattr, key: str, is_class: bool):
"""Wrapper function for the __getattribute__ functions of the modules in PyTorch"""
log.debug(f'registered module getattr wrapper: {key}')
def new_getattr(obj, name):
log.debug(f'{key} in getattr function wrapper')
related = False
log.debug(f'{key} before with block, lock: {lock}')
with no_catch() as res:
result = orig_getattr(obj, name)
if current_graph() is None:
related = False
if name in ('device', 'shape', 'data', 'dtype'):
related = True
if res:
if related:
# Also the property should be constant if the result object is unchanged.
# Only create a new node when there isn't one.
if (
id(result) in current_graph().tensor_pre_node_dict
and id(result) in original_values_for_tracked_objects
and original_values_for_tracked_objects[id(result)] == result
):
node_name = current_graph().tensor_pre_node_dict[id(result)]
trace_node = current_graph().nodes_map[node_name]
if trace_node.module.is_property and trace_node.module.func_type == 'shape':
result = tuple(trace_node.next_tensors)
else:
# Handling dynamic shape
# If the torch.Size object is generated by a tensor,
# then we connect it to the graph.
# Otherwise, don't track it.
old_result = None
if type(result) == torch.Size and isinstance(obj, torch.Tensor):
# Create a list of new tensors for the sake of tracking
# The reason to use that instead of a tensor is stated below.
# e.g. Users may use the following clause to deal with sizes
# x, y = tensor.size()
# Currently, there is no way to trace it.
# However, by doing this, if user calls `numel` on the `torch.Size`
# object, it will now throw an exception.
# TODO: Fix the case if user calls `numel` on `torch.Size`
constant_handler(obj, type_name=key)
original_values_for_tracked_objects[id(result)] = copy.deepcopy(result)
new_result = []
for elem in result:
new_result.append(torch.tensor(elem))
current_graph().tensor_pre_node_dict[
id(new_result[-1])
] = current_graph().tensor_pre_node_dict[id(obj)]
old_result = result
result = tuple(new_result)
log.debug(f'{key} is called with {name}')
new_key = key.replace('__getattribute__', name)
trace_func = TraceFunction(new_key, True, True).parse_args(obj)
trace_node = TraceNode(trace_func)
if old_result is not None:
current_graph().tensor_pre_node_dict[id(old_result)] = trace_node.unique_name
add_forward_node(trace_node, trace_func.prev_tensors, result)
log.debug(f'{key} after with block, lock: {lock}')
return result
return new_getattr
def new_init_tracking_gen(orig_init, key: str):
"""Wrapper function for the init functions of the modules in PyTorch"""
log.debug(f'registered module init tracking wrapper: {key}')
def new_init_tracking(obj, args, kwargs):
log.debug(f'{key} in init tracking function wrapper')
with no_catch():
is_tensor = torch.is_tensor(args[0])
if is_tensor:
return args[0].unbind(0)
else:
with no_catch():
return tuple([torch.as_tensor(x) for x in args[0]])
return new_init_tracking
def new_init_gen(orig_init, key: str):
"""Wrapper function for the init functions of the modules in PyTorch"""
log.debug(f'registered module init wrapper: {key}')
def new_init(obj, *args, **kwargs):
log.debug(f'{key} in init function wrapper')
module_constructor_traced.add(id(obj))
init_fullname = key
class_fullname = '.'.join(init_fullname.split('.')[:-1])
log.debug(f'{key} before with block, lock: {lock}')
with no_catch() as res:
if id(obj) not in module_constructor_lines or (